void NBNodeCont::guessTLs(OptionsCont& oc, NBTrafficLightLogicCont& tlc) { // build list of definitely not tls-controlled junctions std::vector<NBNode*> ncontrolled; if (oc.isSet("tls.unset")) { std::vector<std::string> notTLControlledNodes = oc.getStringVector("tls.unset"); for (std::vector<std::string>::const_iterator i = notTLControlledNodes.begin(); i != notTLControlledNodes.end(); ++i) { NBNode* n = NBNodeCont::retrieve(*i); if (n == 0) { throw ProcessError(" The node '" + *i + "' to set as not-controlled is not known."); } std::set<NBTrafficLightDefinition*> tls = n->getControllingTLS(); for (std::set<NBTrafficLightDefinition*>::const_iterator j = tls.begin(); j != tls.end(); ++j) { (*j)->removeNode(n); } n->removeTrafficLights(); ncontrolled.push_back(n); } } TrafficLightType type = SUMOXMLDefinitions::TrafficLightTypes.get(OptionsCont::getOptions().getString("tls.default-type")); // loop#1 checking whether the node shall be tls controlled, // because it is assigned to a district if (oc.exists("tls.taz-nodes") && oc.getBool("tls.taz-nodes")) { for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { NBNode* cur = (*i).second; if (cur->isNearDistrict() && find(ncontrolled.begin(), ncontrolled.end(), cur) == ncontrolled.end()) { setAsTLControlled(cur, tlc, type); } } } // maybe no tls shall be guessed if (!oc.getBool("tls.guess")) { return; } // guess joined tls first, if wished if (oc.getBool("tls.join")) { // get node clusters std::vector<std::set<NBNode*> > cands; generateNodeClusters(oc.getFloat("tls.join-dist"), cands); // check these candidates (clusters) whether they should be controlled by a tls for (std::vector<std::set<NBNode*> >::iterator i = cands.begin(); i != cands.end();) { std::set<NBNode*>& c = (*i); // regard only junctions which are not yet controlled and are not // forbidden to be controlled for (std::set<NBNode*>::iterator j = c.begin(); j != c.end();) { if ((*j)->isTLControlled() || find(ncontrolled.begin(), ncontrolled.end(), *j) != ncontrolled.end()) { c.erase(j++); } else { ++j; } } // check whether the cluster should be controlled if (!shouldBeTLSControlled(c)) { i = cands.erase(i); } else { ++i; } } // cands now only contain sets of junctions that shall be joined into being tls-controlled unsigned int index = 0; for (std::vector<std::set<NBNode*> >::iterator i = cands.begin(); i != cands.end(); ++i) { std::vector<NBNode*> nodes; for (std::set<NBNode*>::iterator j = (*i).begin(); j != (*i).end(); j++) { nodes.push_back(*j); } std::string id = "joinedG_" + toString(index++); NBTrafficLightDefinition* tlDef = new NBOwnTLDef(id, nodes, 0, type); if (!tlc.insert(tlDef)) { // actually, nothing should fail here WRITE_WARNING("Could not build guessed, joined tls"); delete tlDef; return; } } } // guess tls for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { NBNode* cur = (*i).second; // do nothing if already is tl-controlled if (cur->isTLControlled()) { continue; } // do nothing if in the list of explicit non-controlled junctions if (find(ncontrolled.begin(), ncontrolled.end(), cur) != ncontrolled.end()) { continue; } std::set<NBNode*> c; c.insert(cur); if (!shouldBeTLSControlled(c) || cur->getIncomingEdges().size() < 3) { continue; } setAsTLControlled((*i).second, tlc, type); } }
/* * Unregister the service with the Windows SCM * Input - ServiceName */ int UnregisterService (LPCSTR lpszServiceName, int quiet) { TCHAR MsgErrorString[MAX_STR_SIZE]; /* Message or Error string */ SC_HANDLE hSCManager = NULL; /* SCM handle */ SC_HANDLE hService = NULL; /* Service Handle */ SERVICE_STATUS sStatus; TCHAR szRegAppLogKey[] = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\"; TCHAR szRegKey[512]; int exitStatus = 0; /* HKEY hKey = NULL; ?* Key to registry entry */ TRY { /* * Open Service Control Manager */ hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_CREATE_SERVICE); if (hSCManager == NULL) { ProcessError (EVENTLOG_ERROR_TYPE, _T ("Can't open SCM (Service Control Manager)"), 1, quiet); exitStatus = SERVICE_ERROR_SCM_OPEN; LEAVE; } /* * Open registered service */ hService = OpenService (hSCManager, lpszServiceName, SERVICE_ALL_ACCESS); if (hService == NULL) { _snprintf (MsgErrorString, sizeof(MsgErrorString), "%s %s", _T ("Can't open service"), lpszServiceName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_OPEN_SERVICE; LEAVE; } /* * Query service status * If running stop before deleting */ if (QueryServiceStatus (hService, &sStatus)) { if (sStatus.dwCurrentState == SERVICE_RUNNING || sStatus.dwCurrentState == SERVICE_PAUSED) { ControlService (hService, SERVICE_CONTROL_STOP, &sStatus); } }; /* * Delete the service */ if (DeleteService (hService) == FALSE) { _snprintf (MsgErrorString, sizeof(MsgErrorString), "%s %s", _T ("Can't delete service"), lpszServiceName); /* * Log message to eventlog */ ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 0, quiet); LEAVE; } /* * Log "Service deleted successfully " message to eventlog */ _snprintf (MsgErrorString, sizeof(MsgErrorString), "%s %s", lpszServiceName, _T ("service deleted")); ProcessError (EVENTLOG_INFORMATION_TYPE, MsgErrorString, 0, quiet); /* * Delete registry entries for EventLog */ _tcscpy (szRegKey, szRegAppLogKey); _tcscat (szRegKey, lpszServiceName); RegDeleteKey (HKEY_LOCAL_MACHINE, szRegKey); } /* * Delete the handles */ FINALLY { if (hService) CloseServiceHandle (hService); if (hSCManager) CloseServiceHandle (hSCManager); } return (exitStatus); }
bool MSEdge::insertVehicle(SUMOVehicle& v, SUMOTime time, const bool checkOnly) const { // when vaporizing, no vehicles are inserted, but checking needs to be successful to trigger removal if (isVaporizing()) { return checkOnly; } const SUMOVehicleParameter& pars = v.getParameter(); const MSVehicleType& type = v.getVehicleType(); if (pars.departSpeedProcedure == DEPART_SPEED_GIVEN && pars.departSpeed > getVehicleMaxSpeed(&v)) { if (type.getSpeedDeviation() > 0 && pars.departSpeed <= type.getSpeedFactor() * getSpeedLimit() * (2 * type.getSpeedDeviation() + 1.)) { WRITE_WARNING("Choosing new speed factor for vehicle '" + pars.id + "' to match departure speed."); v.setChosenSpeedFactor(type.computeChosenSpeedDeviation(0, pars.departSpeed / (type.getSpeedFactor() * getSpeedLimit()))); } else { throw ProcessError("Departure speed for vehicle '" + pars.id + "' is too high for the departure edge '" + getID() + "'."); } } if (checkOnly && v.getEdge()->getPurpose() == MSEdge::EDGEFUNCTION_DISTRICT) { return true; } if (!checkOnly) { std::string msg; if (!v.hasValidRoute(msg)) { if (MSGlobals::gCheckRoutes) { throw ProcessError("Vehicle '" + v.getID() + "' has no valid route. " + msg); } else if (v.getEdge()->getPurpose() == MSEdge::EDGEFUNCTION_DISTRICT) { WRITE_WARNING("Removing vehicle '" + pars.id + "' which has no valid route."); MSNet::getInstance()->getInsertionControl().descheduleDeparture(&v); return false; } } } if (MSGlobals::gUseMesoSim) { SUMOReal pos = 0.0; switch (pars.departPosProcedure) { case DEPART_POS_GIVEN: if (pars.departPos >= 0.) { pos = pars.departPos; } else { pos = pars.departPos + getLength(); } if (pos < 0 || pos > getLength()) { WRITE_WARNING("Invalid departPos " + toString(pos) + " given for vehicle '" + v.getID() + "'. Inserting at lane end instead."); pos = getLength(); } break; case DEPART_POS_RANDOM: case DEPART_POS_RANDOM_FREE: pos = RandHelper::rand(getLength()); break; default: break; } bool result = false; MESegment* segment = MSGlobals::gMesoNet->getSegmentForEdge(*this, pos); MEVehicle* veh = static_cast<MEVehicle*>(&v); if (pars.departPosProcedure == DEPART_POS_FREE) { while (segment != 0 && !result) { if (checkOnly) { result = segment->hasSpaceFor(veh, time, true); } else { result = segment->initialise(veh, time); } segment = segment->getNextSegment(); } } else { if (checkOnly) { result = segment->hasSpaceFor(veh, time, true); } else { result = segment->initialise(veh, time); } } return result; } if (checkOnly) { switch (v.getParameter().departLaneProcedure) { case DEPART_LANE_GIVEN: case DEPART_LANE_DEFAULT: case DEPART_LANE_FIRST_ALLOWED: { const SUMOReal occupancy = getDepartLane(static_cast<MSVehicle&>(v))->getBruttoOccupancy(); return occupancy == (SUMOReal)0 || occupancy * myLength + v.getVehicleType().getLengthWithGap() <= myLength; } default: for (std::vector<MSLane*>::const_iterator i = myLanes->begin(); i != myLanes->end(); ++i) { const SUMOReal occupancy = (*i)->getBruttoOccupancy(); if (occupancy == (SUMOReal)0 || occupancy * myLength + v.getVehicleType().getLengthWithGap() <= myLength) { return true; } } } return false; } MSLane* insertionLane = getDepartLane(static_cast<MSVehicle&>(v)); return insertionLane != 0 && insertionLane->insertVehicle(static_cast<MSVehicle&>(v)); }
// =========================================================================== // class definitions // =========================================================================== SUMOSAXAttributesImpl_Binary::SUMOSAXAttributesImpl_Binary( const std::map<int, std::string>& predefinedTagsMML, const std::string& objectType, BinaryInputDevice* in) : SUMOSAXAttributes(objectType), myAttrIds(predefinedTagsMML) { while (in->peek() == BinaryFormatter::BF_XML_ATTRIBUTE) { unsigned char attr; *in >> attr; int type = in->peek(); switch (type) { case BinaryFormatter::BF_BYTE: *in >> myCharValues[attr]; break; case BinaryFormatter::BF_INTEGER: *in >> myIntValues[attr]; break; case BinaryFormatter::BF_FLOAT: case BinaryFormatter::BF_SCALED2INT: *in >> myFloatValues[attr]; break; case BinaryFormatter::BF_STRING: *in >> myStringValues[attr]; break; case BinaryFormatter::BF_LIST: { int size; *in >> size; while (size > 0) { const int type = in->peek(); if (type != BinaryFormatter::BF_POSITION_2D && type != BinaryFormatter::BF_POSITION_3D && type != BinaryFormatter::BF_SCALED2INT_POSITION_2D && type != BinaryFormatter::BF_SCALED2INT_POSITION_3D) { throw ProcessError("Invalid binary file, only supporting position vectors."); } size--; Position p; *in >> p; myPositionVectors[attr].push_back(p); } break; } case BinaryFormatter::BF_EDGE: *in >> myIntValues[attr]; break; case BinaryFormatter::BF_LANE: *in >> myIntValues[attr]; in->putback(BinaryFormatter::BF_BYTE); *in >> myCharValues[attr]; break; case BinaryFormatter::BF_POSITION_2D: case BinaryFormatter::BF_POSITION_3D: case BinaryFormatter::BF_SCALED2INT_POSITION_2D: case BinaryFormatter::BF_SCALED2INT_POSITION_3D: { Position p; *in >> p; myPositionVectors[attr].push_back(p); break; } case BinaryFormatter::BF_BOUNDARY: { Position p; *in >> p; myPositionVectors[attr].push_back(p); in->putback(BinaryFormatter::BF_POSITION_2D); *in >> p; myPositionVectors[attr].push_back(p); break; } case BinaryFormatter::BF_COLOR: *in >> myIntValues[attr]; break; case BinaryFormatter::BF_NODE_TYPE: *in >> myCharValues[attr]; break; case BinaryFormatter::BF_EDGE_FUNCTION: *in >> myCharValues[attr]; break; case BinaryFormatter::BF_ROUTE: { std::ostringstream into(std::ios::binary); int size; *in >> size; FileHelpers::writeByte(into, BinaryFormatter::BF_ROUTE); FileHelpers::writeInt(into, size); if (size > 0) { int intsToRead = size - 1; int bitsOrEntry; in->putback(BinaryFormatter::BF_INTEGER); *in >> bitsOrEntry; FileHelpers::writeInt(into, bitsOrEntry); if (bitsOrEntry < 0) { intsToRead = (-bitsOrEntry * (size - 1) - 1) / sizeof(int) / 8 + 2; } while (intsToRead > 0) { in->putback(BinaryFormatter::BF_INTEGER); *in >> bitsOrEntry; FileHelpers::writeInt(into, bitsOrEntry); intsToRead--; } } myStringValues[attr] = into.str(); break; } default: throw ProcessError("Invalid binary file"); } myAttrs.insert(attr); }
void MSInsertionControl::determineCandidates(SUMOTime time) { MSVehicleControl& vehControl = MSNet::getInstance()->getVehicleControl(); for (std::vector<Flow>::iterator i = myFlows.begin(); i != myFlows.end();) { SUMOVehicleParameter* pars = i->pars; bool tryEmitByProb = pars->repetitionProbability > 0; while ((pars->repetitionProbability < 0 && pars->repetitionsDone < pars->repetitionNumber && pars->depart + pars->repetitionsDone * pars->repetitionOffset < time + DELTA_T) || (tryEmitByProb && pars->depart < time + DELTA_T && pars->repetitionEnd > time // only call rand if all other conditions are met && RandHelper::rand(&myFlowRNG) < (pars->repetitionProbability * TS)) ) { tryEmitByProb = false; // only emit one per step SUMOVehicleParameter* newPars = new SUMOVehicleParameter(*pars); newPars->id = pars->id + "." + toString(i->index); newPars->depart = pars->repetitionProbability > 0 ? time : (SUMOTime)(pars->depart + pars->repetitionsDone * pars->repetitionOffset) + computeRandomDepartOffset(); pars->repetitionsDone++; // try to build the vehicle if (vehControl.getVehicle(newPars->id) == nullptr) { const MSRoute* route = MSRoute::dictionary(pars->routeid); MSVehicleType* vtype = vehControl.getVType(pars->vtypeid, MSRouteHandler::getParsingRNG()); SUMOVehicle* vehicle = vehControl.buildVehicle(newPars, route, vtype, !MSGlobals::gCheckRoutes); int quota = vehControl.getQuota(); if (quota > 0) { vehControl.addVehicle(newPars->id, vehicle); add(vehicle); i->index++; while (--quota > 0) { SUMOVehicleParameter* quotaPars = new SUMOVehicleParameter(*pars); quotaPars->id = pars->id + "." + toString(i->index); quotaPars->depart = pars->repetitionProbability > 0 ? time : (SUMOTime)(pars->depart + pars->repetitionsDone * pars->repetitionOffset) + computeRandomDepartOffset(); SUMOVehicle* vehicle = vehControl.buildVehicle(quotaPars, route, vtype, !MSGlobals::gCheckRoutes); vehControl.addVehicle(quotaPars->id, vehicle); add(vehicle); i->index++; } } else { vehControl.deleteVehicle(vehicle, true); } } else { // strange: another vehicle with the same id already exists if (MSGlobals::gStateLoaded) { vehControl.discountStateLoaded(); break; } throw ProcessError("Another vehicle with the id '" + newPars->id + "' exists."); } } if (pars->repetitionsDone == pars->repetitionNumber || (pars->repetitionProbability > 0 && pars->repetitionEnd <= time)) { i = myFlows.erase(i); MSRoute::checkDist(pars->routeid); delete pars; } else { ++i; } } checkCandidates(time, MSRoutingEngine::isEnabled()); }
// =========================================================================== // method definitions // =========================================================================== SUMOVehicleParameter* SUMOVehicleParserHelper::parseFlowAttributes(const SUMOSAXAttributes& attrs, const SUMOTime beginDefault, const SUMOTime endDefault) { bool ok = true; std::string id = attrs.get<std::string>(SUMO_ATTR_ID, 0, ok); if (attrs.hasAttribute(SUMO_ATTR_PERIOD) && attrs.hasAttribute(SUMO_ATTR_VEHSPERHOUR)) { throw ProcessError("At most one of '" + attrs.getName(SUMO_ATTR_PERIOD) + "' and '" + attrs.getName(SUMO_ATTR_VEHSPERHOUR) + "' has to be given in the definition of flow '" + id + "'."); } if (attrs.hasAttribute(SUMO_ATTR_PERIOD) && attrs.hasAttribute(SUMO_ATTR_PROB)) { throw ProcessError("At most one of '" + attrs.getName(SUMO_ATTR_PERIOD) + "' and '" + attrs.getName(SUMO_ATTR_PROB) + "' has to be given in the definition of flow '" + id + "'."); } if (attrs.hasAttribute(SUMO_ATTR_PROB) && attrs.hasAttribute(SUMO_ATTR_VEHSPERHOUR)) { throw ProcessError("At most one of '" + attrs.getName(SUMO_ATTR_PROB) + "' and '" + attrs.getName(SUMO_ATTR_VEHSPERHOUR) + "' has to be given in the definition of flow '" + id + "'."); } if (attrs.hasAttribute(SUMO_ATTR_PERIOD) || attrs.hasAttribute(SUMO_ATTR_VEHSPERHOUR) || attrs.hasAttribute(SUMO_ATTR_PROB)) { if (attrs.hasAttribute(SUMO_ATTR_END) && attrs.hasAttribute(SUMO_ATTR_NUMBER)) { throw ProcessError("If '" + attrs.getName(SUMO_ATTR_PERIOD) + "', '" + attrs.getName(SUMO_ATTR_VEHSPERHOUR) + "' or '" + attrs.getName(SUMO_ATTR_PROB) + "' are given at most one of '" + attrs.getName(SUMO_ATTR_END) + "' and '" + attrs.getName(SUMO_ATTR_NUMBER) + "' are allowed in flow '" + id + "'."); } } else { if (!attrs.hasAttribute(SUMO_ATTR_NUMBER)) { throw ProcessError("At least one of '" + attrs.getName(SUMO_ATTR_PERIOD) + "', '" + attrs.getName(SUMO_ATTR_VEHSPERHOUR) + "', '" + attrs.getName(SUMO_ATTR_PROB) + "', and '" + attrs.getName(SUMO_ATTR_NUMBER) + "' is needed in flow '" + id + "'."); } } SUMOVehicleParameter* ret = new SUMOVehicleParameter(); ret->id = id; try { parseCommonAttributes(attrs, ret, "flow"); } catch (ProcessError&) { delete ret; throw; } // parse repetition information if (attrs.hasAttribute(SUMO_ATTR_PERIOD)) { ret->setParameter |= VEHPARS_PERIODFREQ_SET; ret->repetitionOffset = attrs.getSUMOTimeReporting(SUMO_ATTR_PERIOD, id.c_str(), ok); } if (attrs.hasAttribute(SUMO_ATTR_VEHSPERHOUR)) { ret->setParameter |= VEHPARS_PERIODFREQ_SET; const double vph = attrs.get<double>(SUMO_ATTR_VEHSPERHOUR, id.c_str(), ok); if (ok && vph <= 0) { delete ret; throw ProcessError("Invalid repetition rate in the definition of flow '" + id + "'."); } if (ok && vph != 0) { ret->repetitionOffset = TIME2STEPS(3600. / vph); } } if (attrs.hasAttribute(SUMO_ATTR_PROB)) { ret->repetitionProbability = attrs.get<double>(SUMO_ATTR_PROB, id.c_str(), ok); if (ok && (ret->repetitionProbability <= 0 || ret->repetitionProbability > 1)) { delete ret; throw ProcessError("Invalid repetition probability in the definition of flow '" + id + "'."); } } ret->depart = beginDefault; if (attrs.hasAttribute(SUMO_ATTR_BEGIN)) { ret->depart = attrs.getSUMOTimeReporting(SUMO_ATTR_BEGIN, id.c_str(), ok); } if (ok && ret->depart < 0) { delete ret; throw ProcessError("Negative begin time in the definition of flow '" + id + "'."); } ret->repetitionEnd = endDefault; if (ret->repetitionEnd < 0) { ret->repetitionEnd = SUMOTime_MAX; } if (attrs.hasAttribute(SUMO_ATTR_END)) { ret->repetitionEnd = attrs.getSUMOTimeReporting(SUMO_ATTR_END, id.c_str(), ok); } if (ok && ret->repetitionEnd < ret->depart) { delete ret; throw ProcessError("Flow '" + id + "' ends before its begin time."); } if (attrs.hasAttribute(SUMO_ATTR_NUMBER)) { ret->repetitionNumber = attrs.get<int>(SUMO_ATTR_NUMBER, id.c_str(), ok); ret->setParameter |= VEHPARS_PERIODFREQ_SET; if (ret->repetitionNumber == 0) { WRITE_WARNING("Flow '" + id + "' has 0 vehicles; will skip it."); } else { if (ok && ret->repetitionNumber < 0) { delete ret; throw ProcessError("Negative repetition number in the definition of flow '" + id + "'."); } if (ok && ret->repetitionOffset < 0) { ret->repetitionOffset = (ret->repetitionEnd - ret->depart) / ret->repetitionNumber; } } ret->repetitionEnd = ret->depart + ret->repetitionNumber * ret->repetitionOffset; } else { // interpret repetitionNumber if (ok && ret->repetitionProbability > 0) { ret->repetitionNumber = std::numeric_limits<int>::max(); } else { if (ok && ret->repetitionOffset <= 0) { delete ret; throw ProcessError("Invalid repetition rate in the definition of flow '" + id + "'."); } if (ret->repetitionEnd == SUMOTime_MAX) { ret->repetitionNumber = std::numeric_limits<int>::max(); } else { const double repLength = (double)(ret->repetitionEnd - ret->depart); ret->repetitionNumber = (int)ceil(repLength / ret->repetitionOffset); } } } if (!ok) { delete ret; throw ProcessError(); } return ret; }
bool NLBuilder::build() { // try to build the net if (!load("net-file", true)) { return false; } // check whether the loaded net agrees with the simulation options if (myOptions.getBool("no-internal-links") && myXMLHandler.haveSeenInternalEdge()) { WRITE_WARNING("Network contains internal links but option --no-internal-links is set. Vehicles will 'jump' across junctions and thus underestimate route lengths and travel times."); } if (myOptions.getString("lanechange.duration") != "0" && myXMLHandler.haveSeenNeighs()) { throw ProcessError("Network contains explicit neigh lanes which do not work together with option --lanechange.duration."); } buildNet(); // @note on loading order constraints: // - additional-files before route-files and state-files due to referencing // - additional-files before weight-files since the latter might contain intermodal edge data and the intermodal net depends on the stops and public transport from the additionals // load additional net elements (sources, detectors, ...) if (myOptions.isSet("additional-files")) { if (!load("additional-files")) { return false; } // load shapes with separate handler NLShapeHandler sh("", myNet.getShapeContainer()); if (!ShapeHandler::loadFiles(myOptions.getStringVector("additional-files"), sh)) { return false; } if (myXMLHandler.haveSeenAdditionalSpeedRestrictions()) { myNet.getEdgeControl().setAdditionalRestrictions(); } } // load weights if wished if (myOptions.isSet("weight-files")) { if (!myOptions.isUsableFileList("weight-files")) { return false; } // build and prepare the weights handler std::vector<SAXWeightsHandler::ToRetrieveDefinition*> retrieverDefs; // travel time, first (always used) EdgeFloatTimeLineRetriever_EdgeTravelTime ttRetriever(myNet); retrieverDefs.push_back(new SAXWeightsHandler::ToRetrieveDefinition("traveltime", true, ttRetriever)); // the measure to use, then EdgeFloatTimeLineRetriever_EdgeEffort eRetriever(myNet); std::string measure = myOptions.getString("weight-attribute"); if (!myOptions.isDefault("weight-attribute")) { if (measure == "CO" || measure == "CO2" || measure == "HC" || measure == "PMx" || measure == "NOx" || measure == "fuel" || measure == "electricity") { measure += "_perVeh"; } retrieverDefs.push_back(new SAXWeightsHandler::ToRetrieveDefinition(measure, true, eRetriever)); } // set up handler SAXWeightsHandler handler(retrieverDefs, ""); // start parsing; for each file in the list std::vector<std::string> files = myOptions.getStringVector("weight-files"); for (std::vector<std::string>::iterator i = files.begin(); i != files.end(); ++i) { // report about loading when wished WRITE_MESSAGE("Loading weights from '" + *i + "'..."); // parse the file if (!XMLSubSys::runParser(handler, *i)) { return false; } } } // load the previous state if wished if (myOptions.isSet("load-state")) { long before = SysUtils::getCurrentMillis(); const std::string& f = myOptions.getString("load-state"); PROGRESS_BEGIN_MESSAGE("Loading state from '" + f + "'"); MSStateHandler h(f, string2time(myOptions.getString("load-state.offset"))); XMLSubSys::runParser(h, f); if (myOptions.isDefault("begin")) { myOptions.set("begin", time2string(h.getTime())); if (TraCIServer::getInstance() != 0) { TraCIServer::getInstance()->setTargetTime(h.getTime()); } } if (MsgHandler::getErrorInstance()->wasInformed()) { return false; } if (h.getTime() != string2time(myOptions.getString("begin"))) { WRITE_WARNING("State was written at a different time " + time2string(h.getTime()) + " than the begin time " + myOptions.getString("begin") + "!"); } PROGRESS_TIME_MESSAGE(before); } // load routes if (myOptions.isSet("route-files") && string2time(myOptions.getString("route-steps")) <= 0) { if (!load("route-files")) { return false; } } // optionally switch off traffic lights if (myOptions.getBool("tls.all-off")) { myNet.getTLSControl().switchOffAll(); } WRITE_MESSAGE("Loading done."); return true; }
void MSRouteHandler::myStartElement(int element, const SUMOSAXAttributes& attrs) { SUMORouteHandler::myStartElement(element, attrs); switch (element) { case SUMO_TAG_PERSON: myActivePlan = new MSPerson::MSPersonPlan(); break; case SUMO_TAG_RIDE: { const std::string pid = myVehicleParameter->id; bool ok = true; MSEdge* from = 0; const std::string desc = attrs.get<std::string>(SUMO_ATTR_LINES, pid.c_str(), ok); StringTokenizer st(desc); std::string bsID = attrs.getOpt<std::string>(SUMO_ATTR_BUS_STOP, 0, ok, ""); MSBusStop* bs = 0; if (bsID != "") { bs = MSNet::getInstance()->getBusStop(bsID); if (bs == 0) { throw ProcessError("Unknown bus stop '" + bsID + "' for person '" + myVehicleParameter->id + "'."); } } if (attrs.hasAttribute(SUMO_ATTR_FROM)) { const std::string fromID = attrs.get<std::string>(SUMO_ATTR_FROM, pid.c_str(), ok); from = MSEdge::dictionary(fromID); if (from == 0) { throw ProcessError("The from edge '" + fromID + "' within a ride of person '" + pid + "' is not known."); } if (!myActivePlan->empty() && &myActivePlan->back()->getDestination() != from) { throw ProcessError("Disconnected plan for person '" + myVehicleParameter->id + "' (" + fromID + "!=" + myActivePlan->back()->getDestination().getID() + ")."); } if (myActivePlan->empty()) { myActivePlan->push_back(new MSPerson::MSPersonStage_Waiting( *from, -1, myVehicleParameter->depart, myVehicleParameter->departPos, "start")); } } else if (myActivePlan->empty()) { throw ProcessError("The start edge within for person '" + pid + "' is not known."); } const std::string toID = attrs.get<std::string>(SUMO_ATTR_TO, pid.c_str(), ok); MSEdge* to = MSEdge::dictionary(toID); if (to == 0) { throw ProcessError("The to edge '" + toID + "' within a ride of person '" + pid + "' is not known."); } myActivePlan->push_back(new MSPerson::MSPersonStage_Driving(*to, bs, st.getVector())); break; } case SUMO_TAG_WALK: { myActiveRoute.clear(); bool ok = true; if (attrs.hasAttribute(SUMO_ATTR_EDGES)) { MSEdge::parseEdgesList(attrs.get<std::string>(SUMO_ATTR_EDGES, myVehicleParameter->id.c_str(), ok), myActiveRoute, myActiveRouteID); } else { if (attrs.hasAttribute(SUMO_ATTR_FROM) && attrs.hasAttribute(SUMO_ATTR_TO)) { const std::string fromID = attrs.get<std::string>(SUMO_ATTR_FROM, myVehicleParameter->id.c_str(), ok); MSEdge* from = MSEdge::dictionary(fromID); if (from == 0) { throw ProcessError("The from edge '" + fromID + "' within a walk of person '" + myVehicleParameter->id + "' is not known."); } const std::string toID = attrs.get<std::string>(SUMO_ATTR_TO, myVehicleParameter->id.c_str(), ok); MSEdge* to = MSEdge::dictionary(toID); if (to == 0) { throw ProcessError("The to edge '" + toID + "' within a walk of person '" + myVehicleParameter->id + "' is not known."); } MSNet::getInstance()->getRouterTT().compute(from, to, 0, 0, myActiveRoute); // @todo: only footways, current time? } } if (myActiveRoute.empty()) { throw ProcessError("No edges to walk for person '" + myVehicleParameter->id + "'."); } if (!myActivePlan->empty() && &myActivePlan->back()->getDestination() != myActiveRoute.front()) { throw ProcessError("Disconnected plan for person '" + myVehicleParameter->id + "' (" + myActiveRoute.front()->getID() + "!=" + myActivePlan->back()->getDestination().getID() + ")."); } SUMOReal departPos = attrs.getOpt<SUMOReal>(SUMO_ATTR_DEPARTPOS, myVehicleParameter->id.c_str(), ok, 0); SUMOReal arrivalPos = attrs.getOpt<SUMOReal>(SUMO_ATTR_ARRIVALPOS, myVehicleParameter->id.c_str(), ok, -1); const SUMOTime duration = attrs.getOptSUMOTimeReporting(SUMO_ATTR_DURATION, 0, ok, -1); SUMOReal speed = DEFAULT_PERSON_SPEED; if (attrs.hasAttribute(SUMO_ATTR_SPEED)) { speed = attrs.getOpt<SUMOReal>(SUMO_ATTR_SPEED, 0, ok, speed); if (speed < 0) { throw ProcessError("Negative walking speed for '" + myVehicleParameter->id + "'."); } } std::string bsID = attrs.getOpt<std::string>(SUMO_ATTR_BUS_STOP, 0, ok, ""); MSBusStop* bs = 0; if (bsID != "") { bs = MSNet::getInstance()->getBusStop(bsID); if (bs == 0) { throw ProcessError("Unknown bus stop '" + bsID + "' for person '" + myVehicleParameter->id + "'."); } } if (myActivePlan->empty()) { myActivePlan->push_back(new MSPerson::MSPersonStage_Waiting( *myActiveRoute.front(), -1, myVehicleParameter->depart, departPos, "start")); } myActivePlan->push_back(new MSPerson::MSPersonStage_Walking(myActiveRoute, bs, duration, speed, departPos, arrivalPos)); myActiveRoute.clear(); break; } case SUMO_TAG_FLOW: if (attrs.hasAttribute(SUMO_ATTR_FROM) && attrs.hasAttribute(SUMO_ATTR_TO)) { myActiveRouteID = "!" + myVehicleParameter->id; bool ok = true; MSEdge::parseEdgesList(attrs.get<std::string>(SUMO_ATTR_FROM, myVehicleParameter->id.c_str(), ok), myActiveRoute, "for vehicle '" + myVehicleParameter->id + "'"); MSEdge::parseEdgesList(attrs.get<std::string>(SUMO_ATTR_TO, myVehicleParameter->id.c_str(), ok), myActiveRoute, "for vehicle '" + myVehicleParameter->id + "'"); closeRoute(true); } break; case SUMO_TAG_TRIP: { bool ok = true; if (attrs.hasAttribute(SUMO_ATTR_FROM) || !myVehicleParameter->wasSet(VEHPARS_TAZ_SET)) { MSEdge::parseEdgesList(attrs.get<std::string>(SUMO_ATTR_FROM, myVehicleParameter->id.c_str(), ok), myActiveRoute, "for vehicle '" + myVehicleParameter->id + "'"); MSEdge::parseEdgesList(attrs.get<std::string>(SUMO_ATTR_TO, myVehicleParameter->id.c_str(), ok), myActiveRoute, "for vehicle '" + myVehicleParameter->id + "'"); } else { const MSEdge* fromTaz = MSEdge::dictionary(myVehicleParameter->fromTaz + "-source"); if (fromTaz == 0) { WRITE_ERROR("Source district '" + myVehicleParameter->fromTaz + "' not known for '" + myVehicleParameter->id + "'!"); } else if (fromTaz->getNoFollowing() == 0) { WRITE_ERROR("Source district '" + myVehicleParameter->fromTaz + "' has no outgoing edges for '" + myVehicleParameter->id + "'!"); } else { myActiveRoute.push_back(fromTaz->getFollower(0)); } } closeRoute(true); closeVehicle(); } break; default: break; } // parse embedded vtype information if (myCurrentVType != 0 && element != SUMO_TAG_VTYPE && element != SUMO_TAG_PARAM) { SUMOVehicleParserHelper::parseVTypeEmbedded(*myCurrentVType, element, attrs); return; } }
GUIGlID GUITextureSubSys::getTexture(GUITexture which) { // If texture isn't loaded, load it if (myInstance->myTextures.at(which) == 0) { switch (which) { case GNETEXTURE_E3 : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_E3, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_E3SELECTED : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_E3Selected, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_EMPTY : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_Empty, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_EMPTYSELECTED : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_EmptySelected, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_LOCK : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_Lock, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_LOCKSELECTED : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_LockSelected, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_NOTMOVING : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_NotMoving, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_NOTMOVINGSELECTED : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_NotMovingSelected, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_REROUTER : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_Rerouter, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_REROUTERSELECTED : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_RerouterSelected, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_ROUTEPROBE : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_RouteProbe, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_ROUTEPROBESELECTED : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_RouteProbeSelected, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_TLS : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_TLS, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_VAPORIZER : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_Vaporizer, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_VAPORIZERSELECTED : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_VaporizerSelected, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_VARIABLESPEEDSIGN : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_VariableSpeedSign, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_VARIABLESPEEDSIGNSELECTED : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_VariableSpeedSignSelected, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_LANEBIKE : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_LaneBike, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_LANEBUS : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_LaneBus, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; case GNETEXTURE_LANEPEDESTRIAN : myInstance->myTextures[which] = GUITexturesHelper::add(new FXGIFImage(myInstance->myApp, GNETexture_LanePedestrian, IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP)); break; default: throw ProcessError("Undefined texture"); } } // Return GLID associated to the texture return myInstance->myTextures.at(which); }
void MSRouteHandler::closeVehicle() { // get nested route const MSRoute* route = MSRoute::dictionary("!" + myVehicleParameter->id); MSVehicleControl& vehControl = MSNet::getInstance()->getVehicleControl(); if (myVehicleParameter->departProcedure == DEPART_GIVEN) { // let's check whether this vehicle had to depart before the simulation starts if (!(myAddVehiclesDirectly || checkLastDepart()) || myVehicleParameter->depart < string2time(OptionsCont::getOptions().getString("begin"))) { if (route != 0) { route->addReference(); route->release(); } return; } } // get the vehicle's type MSVehicleType* vtype = 0; if (myVehicleParameter->vtypeid != "") { vtype = vehControl.getVType(myVehicleParameter->vtypeid); if (vtype == 0) { throw ProcessError("The vehicle type '" + myVehicleParameter->vtypeid + "' for vehicle '" + myVehicleParameter->id + "' is not known."); } } else { // there should be one (at least the default one) vtype = vehControl.getVType(); } if (route == 0) { // if there is no nested route, try via the (hopefully) given route-id route = MSRoute::dictionary(myVehicleParameter->routeid); } if (route == 0) { // nothing found? -> error if (myVehicleParameter->routeid != "") { throw ProcessError("The route '" + myVehicleParameter->routeid + "' for vehicle '" + myVehicleParameter->id + "' is not known."); } else { throw ProcessError("Vehicle '" + myVehicleParameter->id + "' has no route."); } } myActiveRouteID = ""; // try to build the vehicle SUMOVehicle* vehicle = 0; if (vehControl.getVehicle(myVehicleParameter->id) == 0) { vehicle = vehControl.buildVehicle(myVehicleParameter, route, vtype); // maybe we do not want this vehicle to be inserted due to scaling if (vehControl.isInQuota()) { // add the vehicle to the vehicle control vehControl.addVehicle(myVehicleParameter->id, vehicle); if (myVehicleParameter->departProcedure == DEPART_TRIGGERED) { vehControl.addWaiting(*route->begin(), vehicle); vehControl.registerOneWaitingForPerson(); } registerLastDepart(); myVehicleParameter = 0; } else { vehControl.deleteVehicle(vehicle, true); myVehicleParameter = 0; vehicle = 0; } } else { // strange: another vehicle with the same id already exists if (!MSGlobals::gStateLoaded) { // and was not loaded while loading a simulation state // -> error throw ProcessError("Another vehicle with the id '" + myVehicleParameter->id + "' exists."); } else { // ok, it seems to be loaded previously while loading a simulation state vehicle = 0; } } // check whether the vehicle shall be added directly to the network or // shall stay in the internal buffer if (vehicle != 0) { if (vehicle->getParameter().departProcedure == DEPART_GIVEN) { MSNet::getInstance()->getInsertionControl().add(vehicle); } } }
void MSRouteHandler::addStop(const SUMOSAXAttributes& attrs) { bool ok = true; std::string errorSuffix; if (myActiveRouteID != "") { errorSuffix = " in route '" + myActiveRouteID + "'."; } else if (myActivePlan) { errorSuffix = " in person '" + myVehicleParameter->id + "'."; } else { errorSuffix = " in vehicle '" + myVehicleParameter->id + "'."; } SUMOVehicleParameter::Stop stop; SUMOVehicleParserHelper::parseStop(stop, attrs); // try to parse the assigned bus stop stop.busstop = attrs.getOpt<std::string>(SUMO_ATTR_BUS_STOP, 0, ok, ""); if (stop.busstop != "") { // ok, we have obviously a bus stop MSBusStop* bs = MSNet::getInstance()->getBusStop(stop.busstop); if (bs != 0) { const MSLane& l = bs->getLane(); stop.lane = l.getID(); stop.endPos = bs->getEndLanePosition(); stop.startPos = bs->getBeginLanePosition(); } else { WRITE_ERROR("The bus stop '" + stop.busstop + "' is not known" + errorSuffix); return; } } else { // no, the lane and the position should be given // get the lane stop.lane = attrs.getOpt<std::string>(SUMO_ATTR_LANE, 0, ok, ""); if (ok && stop.lane != "") { if (MSLane::dictionary(stop.lane) == 0) { WRITE_ERROR("The lane '" + stop.lane + "' for a stop is not known" + errorSuffix); return; } } else { WRITE_ERROR("A stop must be placed on a bus stop or a lane" + errorSuffix); return; } if (myActivePlan && !myActivePlan->empty() && &myActivePlan->back()->getDestination() != &MSLane::dictionary(stop.lane)->getEdge()) { throw ProcessError("Disconnected plan for person '" + myVehicleParameter->id + "' (" + MSLane::dictionary(stop.lane)->getEdge().getID() + "!=" + myActivePlan->back()->getDestination().getID() + ")."); } if (myActivePlan && myActivePlan->empty()) { myActivePlan->push_back(new MSPerson::MSPersonStage_Waiting( MSLane::dictionary(stop.lane)->getEdge(), -1, myVehicleParameter->depart, myVehicleParameter->departPos, "start")); } stop.endPos = attrs.getOpt<SUMOReal>(SUMO_ATTR_ENDPOS, 0, ok, MSLane::dictionary(stop.lane)->getLength()); if (attrs.hasAttribute(SUMO_ATTR_POSITION)) { WRITE_WARNING("Deprecated attribute 'pos' in description of stop" + errorSuffix); stop.endPos = attrs.getOpt<SUMOReal>(SUMO_ATTR_POSITION, 0, ok, stop.endPos); } stop.startPos = attrs.getOpt<SUMOReal>(SUMO_ATTR_STARTPOS, 0, ok, MAX2(0., stop.endPos - 2 * POSITION_EPS)); const bool friendlyPos = attrs.getOpt<bool>(SUMO_ATTR_FRIENDLY_POS, 0, ok, false); if (!ok || !checkStopPos(stop.startPos, stop.endPos, MSLane::dictionary(stop.lane)->getLength(), POSITION_EPS, friendlyPos)) { WRITE_ERROR("Invalid start or end position for stop on lane '" + stop.lane + "'" + errorSuffix); return; } } // get the standing duration if (!attrs.hasAttribute(SUMO_ATTR_DURATION) && !attrs.hasAttribute(SUMO_ATTR_UNTIL)) { stop.triggered = attrs.getOpt<bool>(SUMO_ATTR_TRIGGERED, 0, ok, true); stop.duration = -1; stop.until = -1; } else { stop.duration = attrs.getOptSUMOTimeReporting(SUMO_ATTR_DURATION, 0, ok, -1); stop.until = attrs.getOptSUMOTimeReporting(SUMO_ATTR_UNTIL, 0, ok, -1); if (!ok || (stop.duration < 0 && stop.until < 0)) { WRITE_ERROR("Invalid duration or end time is given for a stop on lane '" + stop.lane + "'" + errorSuffix); return; } stop.triggered = attrs.getOpt<bool>(SUMO_ATTR_TRIGGERED, 0, ok, false); } stop.parking = attrs.getOpt<bool>(SUMO_ATTR_PARKING, 0, ok, stop.triggered); if (!ok) { WRITE_ERROR("Invalid bool for 'triggered' or 'parking' for stop on lane '" + stop.lane + "'" + errorSuffix); return; } // expected persons std::string expectedStr = attrs.getOpt<std::string>(SUMO_ATTR_EXPECTED, 0, ok, ""); std::set<std::string> personIDs; SUMOSAXAttributes::parseStringSet(expectedStr, personIDs); stop.awaitedPersons = personIDs; const std::string idx = attrs.getOpt<std::string>(SUMO_ATTR_INDEX, 0, ok, "end"); if (idx == "end") { stop.index = STOP_INDEX_END; } else if (idx == "fit") { stop.index = STOP_INDEX_FIT; } else { stop.index = attrs.get<int>(SUMO_ATTR_INDEX, 0, ok); if (!ok || stop.index < 0) { WRITE_ERROR("Invalid 'index' for stop on lane '" + stop.lane + "'" + errorSuffix); return; } } if (myActiveRouteID != "") { myActiveRouteStops.push_back(stop); } else if (myActivePlan) { std::string actType = attrs.getOpt<std::string>(SUMO_ATTR_ACTTYPE, 0, ok, "waiting"); myActivePlan->push_back(new MSPerson::MSPersonStage_Waiting( MSLane::dictionary(stop.lane)->getEdge(), stop.duration, stop.until, stop.startPos, actType)); } else { myVehicleParameter->stops.push_back(stop); } }
Boundary GNECalibrator::getCenteringBoundary() const { throw ProcessError("This additional doesn't have a boundary"); }
SUMOTime MSCalibrator::execute(SUMOTime currentTime) { // get current simulation values (valid for the last simulation second) // XXX could we miss vehicle movements if this is called less often than every DELTA_T (default) ? updateMeanData(); const bool hadRemovals = removePending(); // check whether an adaptation value exists if (isCurrentStateActive(currentTime)) { myAmActive = true; // all happens in isCurrentStateActive() } else { myAmActive = false; reset(); if (!mySpeedIsDefault) { // reset speed to default if (myLane == nullptr) { myEdge->setMaxSpeed(myDefaultSpeed); } else { myLane->setMaxSpeed(myDefaultSpeed); } mySpeedIsDefault = true; } if (myCurrentStateInterval == myIntervals.end()) { // keep calibrator alive for gui but do not call again return TIME2STEPS(86400); } return myFrequency; } // we are active if (!myDidSpeedAdaption && myCurrentStateInterval->v >= 0) { if (myLane == nullptr) { myEdge->setMaxSpeed(myCurrentStateInterval->v); } else { myLane->setMaxSpeed(myCurrentStateInterval->v); } mySpeedIsDefault = false; myDidSpeedAdaption = true; } const bool calibrateFlow = myCurrentStateInterval->q >= 0; const int totalWishedNum = totalWished(); int adaptedNum = passed() + myClearedInJam; #ifdef MSCalibrator_DEBUG std::cout << time2string(currentTime) << " " << myID << " q=" << myCurrentStateInterval->q << " totalWished=" << totalWishedNum << " adapted=" << adaptedNum << " jam=" << invalidJam(myLane == 0 ? -1 : myLane->getIndex()) << " entered=" << myEdgeMeanData.nVehEntered << " departed=" << myEdgeMeanData.nVehDeparted << " arrived=" << myEdgeMeanData.nVehArrived << " left=" << myEdgeMeanData.nVehLeft << " waitSecs=" << myEdgeMeanData.waitSeconds << " vaporized=" << myEdgeMeanData.nVehVaporized << "\n"; #endif if (calibrateFlow && adaptedNum < totalWishedNum && !hadRemovals) { // we need to insert some vehicles const double hourFraction = STEPS2TIME(currentTime - myCurrentStateInterval->begin + DELTA_T) / (double) 3600.; const int wishedNum = (int)std::floor(myCurrentStateInterval->q * hourFraction + 0.5); // round to closest int // only the difference between inflow and aspiredFlow should be added, thus // we should not count vehicles vaporized from a jam here // if we have enough time left we can add missing vehicles later const int relaxedInsertion = (int)std::floor(STEPS2TIME(myCurrentStateInterval->end - currentTime) / 3); const int insertionSlack = MAX2(0, adaptedNum + relaxedInsertion - totalWishedNum); // increase number of vehicles #ifdef MSCalibrator_DEBUG std::cout << " wished:" << wishedNum << " slack:" << insertionSlack << " before:" << adaptedNum << "\n"; #endif while (wishedNum > adaptedNum + insertionSlack) { SUMOVehicleParameter* pars = myCurrentStateInterval->vehicleParameter; const MSRoute* route = myProbe != nullptr ? myProbe->getRoute() : nullptr; if (route == nullptr) { route = MSRoute::dictionary(pars->routeid); } if (route == nullptr) { WRITE_WARNING("No valid routes in calibrator '" + myID + "'."); break; } if (!route->contains(myEdge)) { WRITE_WARNING("Route '" + route->getID() + "' in calibrator '" + myID + "' does not contain edge '" + myEdge->getID() + "'."); break; } const int routeIndex = (int)std::distance(route->begin(), std::find(route->begin(), route->end(), myEdge)); MSVehicleType* vtype = MSNet::getInstance()->getVehicleControl().getVType(pars->vtypeid); assert(route != 0 && vtype != 0); // build the vehicle SUMOVehicleParameter* newPars = new SUMOVehicleParameter(*pars); newPars->id = myID + "." + toString((int)STEPS2TIME(myCurrentStateInterval->begin)) + "." + toString(myInserted); newPars->depart = currentTime; newPars->routeid = route->getID(); MSVehicle* vehicle; try { vehicle = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().buildVehicle( newPars, route, vtype, true, false)); } catch (const ProcessError& e) { if (!MSGlobals::gCheckRoutes) { WRITE_WARNING(e.what()); vehicle = nullptr; break; } else { throw e; } } #ifdef MSCalibrator_DEBUG std::cout << " resetting route pos: " << routeIndex << "\n"; #endif vehicle->resetRoutePosition(routeIndex); if (myEdge->insertVehicle(*vehicle, currentTime)) { if (!MSNet::getInstance()->getVehicleControl().addVehicle(vehicle->getID(), vehicle)) { throw ProcessError("Emission of vehicle '" + vehicle->getID() + "' in calibrator '" + getID() + "'failed!"); } myInserted++; adaptedNum++; #ifdef MSCalibrator_DEBUG std::cout << "I "; #endif } else { // could not insert vehicle #ifdef MSCalibrator_DEBUG std::cout << "F "; #endif MSNet::getInstance()->getVehicleControl().deleteVehicle(vehicle, true); break; } } } if (myCurrentStateInterval->end <= currentTime + myFrequency) { writeXMLOutput(); } return myFrequency; }
void NIImporter_OpenStreetMap::insertEdge(Edge* e, int index, NBNode* from, NBNode* to, const std::vector<int> &passed, NBEdgeCont& ec, NBTypeCont& tc) { // patch the id std::string id = e->id; if (index >= 0) { id = id + "#" + toString(index); } // convert the shape PositionVector shape; for (std::vector<int>::const_iterator i = passed.begin(); i != passed.end(); ++i) { NIOSMNode* n = myOSMNodes.find(*i)->second; Position pos(n->lon, n->lat); if (!NILoader::transformCoordinates(pos, true)) { throw ProcessError("Unable to project coordinates for edge " + id + "."); } shape.push_back_noDoublePos(pos); } std::string type = e->myHighWayType; if (!tc.knows(type)) { if (type.find(compoundTypeSeparator) != std::string::npos) { // this edge has a combination type which does not yet exist in the TypeContainer StringTokenizer tok = StringTokenizer(type, compoundTypeSeparator); std::set<std::string> types; while (tok.hasNext()) { std::string t = tok.next(); if (tc.knows(t)) { types.insert(t); } else { WRITE_WARNING("Discarding edge " + id + " with type \"" + type + "\" (unknown compound \"" + t + "\")."); return; } } if (types.size() == 2 && types.count("railway.tram") == 1) { // compound types concern mostly the special case of tram tracks on a normal road. // in this case we simply discard the tram information since the default for road is to allow all vclasses types.erase("railway.tram"); std::string otherCompound = *(types.begin()); // XXX if otherCompound does not allow all vehicles (e.g. SVC_DELIVERY), tram will still not be allowed type = otherCompound; } else { // other cases not implemented yet WRITE_WARNING("Discarding edge " + id + " with unknown type \"" + type + "\"."); return; } } else { // we do not know the type -> something else, ignore //WRITE_WARNING("Discarding edge " + id + " with unknown type \"" + type + "\"."); return; } } // otherwise it is not an edge and will be ignored int noLanes = tc.getNumLanes(type); SUMOReal speed = tc.getSpeed(type); bool defaultsToOneWay = tc.getIsOneWay(type); SUMOVehicleClasses allowedClasses = tc.getAllowedClasses(type); SUMOVehicleClasses disallowedClasses = tc.getDisallowedClasses(type); // check directions bool addSecond = true; if (e->myIsOneWay == "true" || e->myIsOneWay == "yes" || e->myIsOneWay == "1" || (defaultsToOneWay && e->myIsOneWay != "no" && e->myIsOneWay != "false" && e->myIsOneWay != "0")) { addSecond = false; } // if we had been able to extract the number of lanes, override the highway type default if (e->myNoLanes >= 0) { if (!addSecond) { noLanes = e->myNoLanes; } else { noLanes = e->myNoLanes / 2; } } // if we had been able to extract the maximum speed, override the type's default if (e->myMaxSpeed != MAXSPEED_UNGIVEN) { speed = (SUMOReal)(e->myMaxSpeed / 3.6); } if (noLanes != 0 && speed != 0) { if (e->myIsOneWay != "" && e->myIsOneWay != "false" && e->myIsOneWay != "no" && e->myIsOneWay != "true" && e->myIsOneWay != "yes" && e->myIsOneWay != "-1" && e->myIsOneWay != "1") { WRITE_WARNING("New value for oneway found: " + e->myIsOneWay); } LaneSpreadFunction lsf = addSecond ? LANESPREAD_RIGHT : LANESPREAD_CENTER; if (e->myIsOneWay != "-1") { NBEdge* nbe = new NBEdge(id, from, to, type, speed, noLanes, tc.getPriority(type), tc.getWidth(type), NBEdge::UNSPECIFIED_OFFSET, shape, e->streetName, lsf); nbe->setVehicleClasses(allowedClasses, disallowedClasses); if (!ec.insert(nbe)) { delete nbe; throw ProcessError("Could not add edge '" + id + "'."); } } if (addSecond) { if (e->myIsOneWay != "-1") { id = "-" + id; } NBEdge* nbe = new NBEdge(id, to, from, type, speed, noLanes, tc.getPriority(type), tc.getWidth(type), NBEdge::UNSPECIFIED_OFFSET, shape.reverse(), e->streetName, lsf); nbe->setVehicleClasses(allowedClasses, disallowedClasses); if (!ec.insert(nbe)) { delete nbe; throw ProcessError("Could not add edge '-" + id + "'."); } } } }
void SUMOVehicleParserHelper::parseCommonAttributes(const SUMOSAXAttributes& attrs, SUMOVehicleParameter* ret, std::string element) { //ret->refid = attrs.getStringSecure(SUMO_ATTR_REFID, ""); bool ok = true; // parse route information if (attrs.hasAttribute(SUMO_ATTR_ROUTE)) { ret->setParameter |= VEHPARS_ROUTE_SET; // !!! needed? ret->routeid = attrs.get<std::string>(SUMO_ATTR_ROUTE, ret->id.c_str(), ok); } // parse type information if (attrs.hasAttribute(SUMO_ATTR_TYPE)) { ret->setParameter |= VEHPARS_VTYPE_SET; // !!! needed? ret->vtypeid = attrs.get<std::string>(SUMO_ATTR_TYPE, ret->id.c_str(), ok); } // parse line information if (attrs.hasAttribute(SUMO_ATTR_LINE)) { ret->setParameter |= VEHPARS_LINE_SET; // !!! needed? ret->line = attrs.get<std::string>(SUMO_ATTR_LINE, ret->id.c_str(), ok); } // parse zone information if (attrs.hasAttribute(SUMO_ATTR_FROM_TAZ)) { ret->setParameter |= VEHPARS_FROM_TAZ_SET; ret->fromTaz = attrs.get<std::string>(SUMO_ATTR_FROM_TAZ, ret->id.c_str(), ok); } if (attrs.hasAttribute(SUMO_ATTR_TO_TAZ)) { ret->setParameter |= VEHPARS_TO_TAZ_SET; ret->toTaz = attrs.get<std::string>(SUMO_ATTR_TO_TAZ, ret->id.c_str(), ok); } // parse reroute information if (attrs.getOpt<bool>(SUMO_ATTR_REROUTE, 0, ok, false)) { ret->setParameter |= VEHPARS_FORCE_REROUTE; } std::string error; // parse depart lane information if (attrs.hasAttribute(SUMO_ATTR_DEPARTLANE)) { ret->setParameter |= VEHPARS_DEPARTLANE_SET; const std::string helper = attrs.get<std::string>(SUMO_ATTR_DEPARTLANE, ret->id.c_str(), ok); if (!SUMOVehicleParameter::parseDepartLane(helper, element, ret->id, ret->departLane, ret->departLaneProcedure, error)) { throw ProcessError(error); } } // parse depart position information if (attrs.hasAttribute(SUMO_ATTR_DEPARTPOS)) { ret->setParameter |= VEHPARS_DEPARTPOS_SET; const std::string helper = attrs.get<std::string>(SUMO_ATTR_DEPARTPOS, ret->id.c_str(), ok); if (!SUMOVehicleParameter::parseDepartPos(helper, element, ret->id, ret->departPos, ret->departPosProcedure, error)) { throw ProcessError(error); } } // parse lateral depart position information if (attrs.hasAttribute(SUMO_ATTR_DEPARTPOS_LAT)) { ret->setParameter |= VEHPARS_DEPARTPOSLAT_SET; const std::string helper = attrs.get<std::string>(SUMO_ATTR_DEPARTPOS_LAT, ret->id.c_str(), ok); if (!SUMOVehicleParameter::parseDepartPosLat(helper, element, ret->id, ret->departPosLat, ret->departPosLatProcedure, error)) { throw ProcessError(error); } } // parse depart speed information if (attrs.hasAttribute(SUMO_ATTR_DEPARTSPEED)) { ret->setParameter |= VEHPARS_DEPARTSPEED_SET; std::string helper = attrs.get<std::string>(SUMO_ATTR_DEPARTSPEED, ret->id.c_str(), ok); if (!SUMOVehicleParameter::parseDepartSpeed(helper, element, ret->id, ret->departSpeed, ret->departSpeedProcedure, error)) { throw ProcessError(error); } } // parse arrival lane information if (attrs.hasAttribute(SUMO_ATTR_ARRIVALLANE)) { ret->setParameter |= VEHPARS_ARRIVALLANE_SET; std::string helper = attrs.get<std::string>(SUMO_ATTR_ARRIVALLANE, ret->id.c_str(), ok); if (!SUMOVehicleParameter::parseArrivalLane(helper, element, ret->id, ret->arrivalLane, ret->arrivalLaneProcedure, error)) { throw ProcessError(error); } } // parse arrival position information if (attrs.hasAttribute(SUMO_ATTR_ARRIVALPOS)) { ret->setParameter |= VEHPARS_ARRIVALPOS_SET; std::string helper = attrs.get<std::string>(SUMO_ATTR_ARRIVALPOS, ret->id.c_str(), ok); if (!SUMOVehicleParameter::parseArrivalPos(helper, element, ret->id, ret->arrivalPos, ret->arrivalPosProcedure, error)) { throw ProcessError(error); } } // parse lateral arrival position information if (attrs.hasAttribute(SUMO_ATTR_ARRIVALPOS_LAT)) { ret->setParameter |= VEHPARS_ARRIVALPOSLAT_SET; std::string helper = attrs.get<std::string>(SUMO_ATTR_ARRIVALPOS_LAT, ret->id.c_str(), ok); if (!SUMOVehicleParameter::parseArrivalPosLat(helper, element, ret->id, ret->arrivalPosLat, ret->arrivalPosLatProcedure, error)) { throw ProcessError(error); } } // parse arrival speed information if (attrs.hasAttribute(SUMO_ATTR_ARRIVALSPEED)) { ret->setParameter |= VEHPARS_ARRIVALSPEED_SET; std::string helper = attrs.get<std::string>(SUMO_ATTR_ARRIVALSPEED, ret->id.c_str(), ok); if (!SUMOVehicleParameter::parseArrivalSpeed(helper, element, ret->id, ret->arrivalSpeed, ret->arrivalSpeedProcedure, error)) { throw ProcessError(error); } } // parse color if (attrs.hasAttribute(SUMO_ATTR_COLOR)) { ret->setParameter |= VEHPARS_COLOR_SET; ret->color = attrs.get<RGBColor>(SUMO_ATTR_COLOR, ret->id.c_str(), ok); } else { ret->color = RGBColor::DEFAULT_COLOR; } // parse person number if (attrs.hasAttribute(SUMO_ATTR_PERSON_NUMBER)) { ret->setParameter |= VEHPARS_PERSON_NUMBER_SET; ret->personNumber = attrs.get<int>(SUMO_ATTR_PERSON_NUMBER, ret->id.c_str(), ok); } // parse container number if (attrs.hasAttribute(SUMO_ATTR_CONTAINER_NUMBER)) { ret->setParameter |= VEHPARS_CONTAINER_NUMBER_SET; ret->containerNumber = attrs.get<int>(SUMO_ATTR_CONTAINER_NUMBER, ret->id.c_str(), ok); } }
/* ------------------------------------------------------------------------- * main * ----------------------------------------------------------------------- */ int main(int argc, char** argv) { OptionsCont& oc = OptionsCont::getOptions(); // give some application descriptions oc.setApplicationDescription("Router for the microscopic, multi-modal traffic simulation SUMO based on junction turning ratios."); oc.setApplicationName("jtrrouter", "Eclipse SUMO jtrrouter Version " VERSION_STRING); int ret = 0; RONet* net = 0; try { // initialise the application system (messaging, xml, options) XMLSubSys::init(); ROJTRFrame::fillOptions(); OptionsIO::setArgs(argc, argv); OptionsIO::getOptions(); if (oc.processMetaOptions(argc < 2)) { SystemFrame::close(); return 0; } XMLSubSys::setValidation(oc.getString("xml-validation"), oc.getString("xml-validation.net")); MsgHandler::initOutputOptions(); if (!(ROJTRFrame::checkOptions() && SystemFrame::checkOptions())) { throw ProcessError(); } RandHelper::initRandGlobal(); std::vector<double> defs = getTurningDefaults(oc); // load data ROLoader loader(oc, true, !oc.getBool("no-step-log")); net = new RONet(); initNet(*net, loader, defs); try { // parse and set the turn defaults first loadJTRDefinitions(*net, oc); // build routes computeRoutes(*net, loader, oc); } catch (XERCES_CPP_NAMESPACE::SAXParseException& e) { WRITE_ERROR(toString(e.getLineNumber())); ret = 1; } catch (XERCES_CPP_NAMESPACE::SAXException& e) { WRITE_ERROR(TplConvert::_2str(e.getMessage())); ret = 1; } if (MsgHandler::getErrorInstance()->wasInformed()) { throw ProcessError(); } } catch (const ProcessError& e) { if (std::string(e.what()) != std::string("Process Error") && std::string(e.what()) != std::string("")) { WRITE_ERROR(e.what()); } MsgHandler::getErrorInstance()->inform("Quitting (on error).", false); ret = 1; #ifndef _DEBUG } catch (const std::exception& e) { if (std::string(e.what()) != std::string("")) { WRITE_ERROR(e.what()); } MsgHandler::getErrorInstance()->inform("Quitting (on error).", false); ret = 1; } catch (...) { MsgHandler::getErrorInstance()->inform("Quitting (on unknown error).", false); ret = 1; #endif } delete net; SystemFrame::close(); if (ret == 0) { std::cout << "Success." << std::endl; } return ret; }
SUMOVTypeParameter* SUMOVehicleParserHelper::beginVTypeParsing(const SUMOSAXAttributes& attrs, const std::string& file) { bool ok = true; std::string id = attrs.get<std::string>(SUMO_ATTR_ID, 0, ok); SUMOVehicleClass vClass = SVC_PASSENGER; if (attrs.hasAttribute(SUMO_ATTR_VCLASS)) { vClass = parseVehicleClass(attrs, id); } SUMOVTypeParameter* vtype = new SUMOVTypeParameter(id, vClass); if (attrs.hasAttribute(SUMO_ATTR_VCLASS)) { vtype->setParameter |= VTYPEPARS_VEHICLECLASS_SET; } if (attrs.hasAttribute(SUMO_ATTR_LENGTH)) { vtype->length = attrs.get<double>(SUMO_ATTR_LENGTH, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_LENGTH_SET; } if (attrs.hasAttribute(SUMO_ATTR_MINGAP)) { vtype->minGap = attrs.get<double>(SUMO_ATTR_MINGAP, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_MINGAP_SET; } if (attrs.hasAttribute(SUMO_ATTR_MAXSPEED)) { vtype->maxSpeed = attrs.get<double>(SUMO_ATTR_MAXSPEED, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_MAXSPEED_SET; } if (attrs.hasAttribute(SUMO_ATTR_SPEEDFACTOR)) { vtype->speedFactor = Distribution_Parameterized(attrs.get<std::string>(SUMO_ATTR_SPEEDFACTOR, vtype->id.c_str(), ok)); vtype->setParameter |= VTYPEPARS_SPEEDFACTOR_SET; } if (attrs.hasAttribute(SUMO_ATTR_SPEEDDEV)) { vtype->speedFactor.getParameter()[1] = attrs.get<double>(SUMO_ATTR_SPEEDDEV, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_SPEEDFACTOR_SET; } if (attrs.hasAttribute(SUMO_ATTR_EMISSIONCLASS)) { vtype->emissionClass = parseEmissionClass(attrs, vtype->id); vtype->setParameter |= VTYPEPARS_EMISSIONCLASS_SET; } if (attrs.hasAttribute(SUMO_ATTR_IMPATIENCE)) { if (attrs.get<std::string>(SUMO_ATTR_IMPATIENCE, vtype->id.c_str(), ok) == "off") { vtype->impatience = -std::numeric_limits<double>::max(); } else { vtype->impatience = attrs.get<double>(SUMO_ATTR_IMPATIENCE, vtype->id.c_str(), ok); } vtype->setParameter |= VTYPEPARS_IMPATIENCE_SET; } if (attrs.hasAttribute(SUMO_ATTR_WIDTH)) { vtype->width = attrs.get<double>(SUMO_ATTR_WIDTH, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_WIDTH_SET; } if (attrs.hasAttribute(SUMO_ATTR_HEIGHT)) { vtype->height = attrs.get<double>(SUMO_ATTR_HEIGHT, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_HEIGHT_SET; } if (attrs.hasAttribute(SUMO_ATTR_GUISHAPE)) { vtype->shape = parseGuiShape(attrs, vtype->id); vtype->setParameter |= VTYPEPARS_SHAPE_SET; } if (attrs.hasAttribute(SUMO_ATTR_OSGFILE)) { vtype->osgFile = attrs.get<std::string>(SUMO_ATTR_OSGFILE, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_OSGFILE_SET; } if (attrs.hasAttribute(SUMO_ATTR_IMGFILE)) { vtype->imgFile = attrs.get<std::string>(SUMO_ATTR_IMGFILE, vtype->id.c_str(), ok); if (vtype->imgFile != "" && !FileHelpers::isAbsolute(vtype->imgFile)) { vtype->imgFile = FileHelpers::getConfigurationRelative(file, vtype->imgFile); } vtype->setParameter |= VTYPEPARS_IMGFILE_SET; } if (attrs.hasAttribute(SUMO_ATTR_COLOR)) { vtype->color = attrs.get<RGBColor>(SUMO_ATTR_COLOR, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_COLOR_SET; } else { vtype->color = RGBColor::YELLOW; } if (attrs.hasAttribute(SUMO_ATTR_PROB)) { vtype->defaultProbability = attrs.get<double>(SUMO_ATTR_PROB, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_PROBABILITY_SET; } if (attrs.hasAttribute(SUMO_ATTR_LANE_CHANGE_MODEL)) { vtype->setParameter |= VTYPEPARS_LANE_CHANGE_MODEL_SET; std::string lcmS = attrs.get<std::string>(SUMO_ATTR_LANE_CHANGE_MODEL, vtype->id.c_str(), ok); if (lcmS == "JE2013") { WRITE_WARNING("Lane change model 'JE2013' is deprecated. Using default model instead."); lcmS = "default"; } if (SUMOXMLDefinitions::LaneChangeModels.hasString(lcmS)) { vtype->lcModel = SUMOXMLDefinitions::LaneChangeModels.get(lcmS); } else { WRITE_ERROR("Unknown lane change model '" + lcmS + "' when parsing vtype '" + vtype->id + "'"); throw ProcessError(); } } if (attrs.hasAttribute(SUMO_ATTR_CAR_FOLLOW_MODEL)) { const std::string cfmS = attrs.get<std::string>(SUMO_ATTR_CAR_FOLLOW_MODEL, vtype->id.c_str(), ok); if (SUMOXMLDefinitions::CarFollowModels.hasString(cfmS)) { vtype->cfModel = SUMOXMLDefinitions::CarFollowModels.get(cfmS); vtype->setParameter |= VTYPEPARS_CAR_FOLLOW_MODEL; } else { WRITE_ERROR("Unknown car following model '" + cfmS + "' when parsing vtype '" + vtype->id + "'"); throw ProcessError(); } } if (attrs.hasAttribute(SUMO_ATTR_PERSON_CAPACITY)) { vtype->personCapacity = attrs.get<int>(SUMO_ATTR_PERSON_CAPACITY, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_PERSON_CAPACITY; } if (attrs.hasAttribute(SUMO_ATTR_CONTAINER_CAPACITY)) { vtype->containerCapacity = attrs.get<int>(SUMO_ATTR_CONTAINER_CAPACITY, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_CONTAINER_CAPACITY; } if (attrs.hasAttribute(SUMO_ATTR_BOARDING_DURATION)) { vtype->boardingDuration = attrs.getSUMOTimeReporting(SUMO_ATTR_BOARDING_DURATION, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_BOARDING_DURATION; } if (attrs.hasAttribute(SUMO_ATTR_LOADING_DURATION)) { vtype->loadingDuration = attrs.getSUMOTimeReporting(SUMO_ATTR_LOADING_DURATION, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_LOADING_DURATION; } if (attrs.hasAttribute(SUMO_ATTR_MAXSPEED_LAT)) { vtype->maxSpeedLat = attrs.get<double>(SUMO_ATTR_MAXSPEED_LAT, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_MAXSPEED_LAT_SET; } if (attrs.hasAttribute(SUMO_ATTR_MINGAP_LAT)) { vtype->minGapLat = attrs.get<double>(SUMO_ATTR_MINGAP_LAT, vtype->id.c_str(), ok); vtype->setParameter |= VTYPEPARS_MINGAP_LAT_SET; } if (attrs.hasAttribute(SUMO_ATTR_LATALIGNMENT)) { const std::string alignS = attrs.get<std::string>(SUMO_ATTR_LATALIGNMENT, vtype->id.c_str(), ok); if (SUMOXMLDefinitions::LateralAlignments.hasString(alignS)) { vtype->latAlignment = SUMOXMLDefinitions::LateralAlignments.get(alignS); vtype->setParameter |= VTYPEPARS_LATALIGNMENT_SET; } else { WRITE_ERROR("Unknown lateral alignment '" + alignS + "' when parsing vtype '" + vtype->id + "'"); throw ProcessError(); } } parseVTypeEmbedded(*vtype, vtype->cfModel, attrs, true); parseLCParams(*vtype, vtype->lcModel, attrs); if (!ok) { delete vtype; throw ProcessError(); } return vtype; }
void startComputation(RODFNet* optNet, RODFDetectorFlows& flows, RODFDetectorCon& detectors, OptionsCont& oc) { if (oc.getBool("print-absolute-flows")) { flows.printAbsolute(); } // if a network was loaded... (mode1) if (optNet != 0) { if (oc.getBool("remove-empty-detectors")) { PROGRESS_BEGIN_MESSAGE("Removing empty detectors"); optNet->removeEmptyDetectors(detectors, flows); PROGRESS_DONE_MESSAGE(); } else if (oc.getBool("report-empty-detectors")) { PROGRESS_BEGIN_MESSAGE("Scanning for empty detectors"); optNet->reportEmptyDetectors(detectors, flows); PROGRESS_DONE_MESSAGE(); } // compute the detector types (optionally) if (!detectors.detectorsHaveCompleteTypes() || oc.getBool("revalidate-detectors")) { optNet->computeTypes(detectors, oc.getBool("strict-sources")); } std::vector<RODFDetector*>::const_iterator i = detectors.getDetectors().begin(); for (; i != detectors.getDetectors().end(); ++i) { if ((*i)->getType() == SOURCE_DETECTOR) { break; } } if (i == detectors.getDetectors().end() && !oc.getBool("routes-for-all")) { throw ProcessError("No source detectors found."); } // compute routes between the detectors (optionally) if (!detectors.detectorsHaveRoutes() || oc.getBool("revalidate-routes") || oc.getBool("guess-empty-flows")) { PROGRESS_BEGIN_MESSAGE("Computing routes"); optNet->buildRoutes(detectors, oc.getBool("all-end-follower"), oc.getBool("keep-unfinished-routes"), oc.getBool("routes-for-all"), !oc.getBool("keep-longer-routes"), oc.getInt("max-search-depth")); PROGRESS_DONE_MESSAGE(); } } // check // whether the detectors are valid if (!detectors.detectorsHaveCompleteTypes()) { throw ProcessError("The detector types are not defined; use in combination with a network"); } // whether the detectors have routes if (!detectors.detectorsHaveRoutes()) { throw ProcessError("The emitters have no routes; use in combination with a network"); } // save the detectors if wished if (oc.isSet("detector-output")) { detectors.save(oc.getString("detector-output")); } // save their positions as POIs if wished if (oc.isSet("detectors-poi-output")) { detectors.saveAsPOIs(oc.getString("detectors-poi-output")); } // save the routes file if it was changed or it's wished if (detectors.detectorsHaveRoutes() && oc.isSet("routes-output")) { detectors.saveRoutes(oc.getString("routes-output")); } // guess flows if wished if (oc.getBool("guess-empty-flows")) { optNet->buildDetectorDependencies(detectors); detectors.guessEmptyFlows(flows); } const SUMOTime begin = string2time(oc.getString("begin")); const SUMOTime end = string2time(oc.getString("end")); const SUMOTime step = string2time(oc.getString("time-step")); // save emitters if wished if (oc.isSet("emitters-output") || oc.isSet("emitters-poi-output")) { optNet->buildEdgeFlowMap(flows, detectors, begin, end, step); // !!! if (oc.getBool("revalidate-flows")) { PROGRESS_BEGIN_MESSAGE("Rechecking loaded flows"); optNet->revalidateFlows(detectors, flows, begin, end, step); PROGRESS_DONE_MESSAGE(); } if (oc.isSet("emitters-output")) { PROGRESS_BEGIN_MESSAGE("Writing emitters"); detectors.writeEmitters(oc.getString("emitters-output"), flows, begin, end, step, *optNet, oc.getBool("calibrator-output"), oc.getBool("include-unused-routes"), oc.getFloat("scale"), // oc.getInt("max-search-depth"), oc.getBool("emissions-only")); PROGRESS_DONE_MESSAGE(); } if (oc.isSet("emitters-poi-output")) { PROGRESS_BEGIN_MESSAGE("Writing emitter pois"); detectors.writeEmitterPOIs(oc.getString("emitters-poi-output"), flows); PROGRESS_DONE_MESSAGE(); } } // save end speed trigger if wished if (oc.isSet("variable-speed-sign-output")) { PROGRESS_BEGIN_MESSAGE("Writing speed triggers"); detectors.writeSpeedTrigger(optNet, oc.getString("variable-speed-sign-output"), flows, begin, end, step); PROGRESS_DONE_MESSAGE(); } // save checking detectors if wished if (oc.isSet("validation-output")) { PROGRESS_BEGIN_MESSAGE("Writing validation detectors"); detectors.writeValidationDetectors(oc.getString("validation-output"), oc.getBool("validation-output.add-sources"), true, true); // !!! PROGRESS_DONE_MESSAGE(); } // build global rerouter on end if wished if (oc.isSet("end-reroute-output")) { PROGRESS_BEGIN_MESSAGE("Writing highway end rerouter"); detectors.writeEndRerouterDetectors(oc.getString("end-reroute-output")); // !!! PROGRESS_DONE_MESSAGE(); } /* // save the insertion definitions if(oc.isSet("flow-definitions")) { buildVehicleEmissions(oc.getString("flow-definitions")); } */ // }
int main(int argc, char** argv) { // build options OptionsCont& oc = OptionsCont::getOptions(); // give some application descriptions oc.setApplicationDescription("Builds and writes an emissions map."); oc.setApplicationName("emissionsMap", "SUMO emissionsMap Version " VERSION_STRING); // add options SystemFrame::addConfigurationOptions(oc); oc.addOptionSubTopic("Processing"); oc.doRegister("iterate", 'i', new Option_Bool(false)); oc.addDescription("iterate", "Processing", "If set, maps for all available emissions are written."); oc.doRegister("emission-class", 'e', new Option_String()); oc.addDescription("emission-class", "Processing", "Defines the name of the emission class to generate the map for."); oc.doRegister("v-min", new Option_Float(0.)); oc.addDescription("v-min", "Processing", "Defines the minimum velocity boundary of the map to generate (in m/s)."); oc.doRegister("v-max", new Option_Float(50.)); oc.addDescription("v-max", "Processing", "Defines the maximum velocity boundary of the map to generate (in m/s)."); oc.doRegister("v-step", new Option_Float(2.)); oc.addDescription("v-step", "Processing", "Defines the velocity step size (in m/s)."); oc.doRegister("a-min", new Option_Float(-4.)); oc.addDescription("a-min", "Processing", "Defines the minimum acceleration boundary of the map to generate (in m/s^2)."); oc.doRegister("a-max", new Option_Float(4.)); oc.addDescription("a-max", "Processing", "Defines the maximum acceleration boundary of the map to generate (in m/s^2)."); oc.doRegister("a-step", new Option_Float(.5)); oc.addDescription("a-step", "Processing", "Defines the acceleration step size (in m/s^2)."); oc.doRegister("s-min", new Option_Float(-10.)); oc.addDescription("s-min", "Processing", "Defines the minimum slope boundary of the map to generate (in deg)."); oc.doRegister("s-max", new Option_Float(10.)); oc.addDescription("s-max", "Processing", "Defines the maximum slope boundary of the map to generate (in deg)."); oc.doRegister("s-step", new Option_Float(1.)); oc.addDescription("s-step", "Processing", "Defines the slope step size (in deg)."); oc.addOptionSubTopic("Output"); oc.doRegister("output-file", 'o', new Option_String()); oc.addSynonyme("output", "output-file"); oc.addDescription("output", "Output", "Defines the file (or the path if --iterate was set) to write the map(s) into."); oc.addOptionSubTopic("Emissions"); oc.doRegister("phemlight-path", new Option_FileName("./PHEMlight/")); oc.addDescription("phemlight-path", "Emissions", "Determines where to load PHEMlight definitions from."); SystemFrame::addReportOptions(oc); // run int ret = 0; try { // initialise the application system (messaging, xml, options) XMLSubSys::init(); OptionsIO::setArgs(argc, argv); OptionsIO::getOptions(); OptionsCont& oc = OptionsCont::getOptions(); if (oc.processMetaOptions(argc < 2)) { SystemFrame::close(); return 0; } SUMOReal vMin = oc.getFloat("v-min"); SUMOReal vMax = oc.getFloat("v-max"); SUMOReal vStep = oc.getFloat("v-step"); SUMOReal aMin = oc.getFloat("a-min"); SUMOReal aMax = oc.getFloat("a-max"); SUMOReal aStep = oc.getFloat("a-step"); SUMOReal sMin = oc.getFloat("s-min"); SUMOReal sMax = oc.getFloat("s-max"); SUMOReal sStep = oc.getFloat("s-step"); if (!oc.getBool("iterate")) { if (!oc.isSet("emission-class")) { throw ProcessError("The emission class (-e) must be given."); } if (!oc.isSet("output-file")) { throw ProcessError("The output file (-o) must be given."); } const SUMOEmissionClass c = PollutantsInterface::getClassByName(oc.getString("emission-class")); single(oc.getString("output-file"), oc.getString("emission-class"), c, vMin, vMax, vStep, aMin, aMax, aStep, sMin, sMax, sStep, oc.getBool("verbose")); } else { if (!oc.isSet("output-file")) { oc.set("output-file", "./"); } const std::vector<SUMOEmissionClass> classes = PollutantsInterface::getAllClasses(); for (std::vector<SUMOEmissionClass>::const_iterator ci = classes.begin(); ci != classes.end(); ++ci) { SUMOEmissionClass c = *ci; single(oc.getString("output-file") + PollutantsInterface::getName(c) + ".csv", PollutantsInterface::getName(c), c, vMin, vMax, vStep, aMin, aMax, aStep, sMin, sMax, sStep, oc.getBool("verbose")); } } } catch (InvalidArgument& e) { MsgHandler::getErrorInstance()->inform(e.what()); MsgHandler::getErrorInstance()->inform("Quitting (on error).", false); ret = 1; } catch (ProcessError& e) { if (std::string(e.what()) != std::string("Process Error") && std::string(e.what()) != std::string("")) { MsgHandler::getErrorInstance()->inform(e.what()); } MsgHandler::getErrorInstance()->inform("Quitting (on error).", false); ret = 1; #ifndef _DEBUG } catch (...) { MsgHandler::getErrorInstance()->inform("Quitting (on unknown error).", false); ret = 1; #endif } SystemFrame::close(); if (ret == 0) { std::cout << "Success." << std::endl; } return ret; }
/* ------------------------------------------------------------------------- * main * ----------------------------------------------------------------------- */ int main(int argc, char** argv) { OptionsCont& oc = OptionsCont::getOptions(); // give some application descriptions oc.setApplicationDescription("Builds vehicle routes for SUMO using detector values."); oc.setApplicationName("dfrouter", "SUMO dfrouter Version " + (std::string)VERSION_STRING); int ret = 0; RODFNet* net = 0; RODFDetectorCon* detectors = 0; RODFDetectorFlows* flows = 0; try { // initialise the application system (messaging, xml, options) XMLSubSys::init(); RODFFrame::fillOptions(); OptionsIO::getOptions(true, argc, argv); if (oc.processMetaOptions(argc < 2)) { SystemFrame::close(); return 0; } XMLSubSys::setValidation(oc.getBool("xml-validation")); MsgHandler::initOutputOptions(); if (!RODFFrame::checkOptions()) { throw ProcessError(); } RandHelper::initRandGlobal(); // load data ROLoader loader(oc, false, !oc.getBool("no-step-log")); net = new RODFNet(oc.getBool("highway-mode")); RODFEdgeBuilder builder; loader.loadNet(*net, builder); net->buildApproachList(); // load detectors detectors = new RODFDetectorCon(); readDetectors(*detectors, oc, net); // load detector values flows = new RODFDetectorFlows(string2time(oc.getString("begin")), string2time(oc.getString("end")), string2time(oc.getString("time-step"))); readDetectorFlows(*flows, oc, *detectors); // build routes startComputation(net, *flows, *detectors, oc); } catch (const ProcessError& e) { if (std::string(e.what()) != std::string("Process Error") && std::string(e.what()) != std::string("")) { WRITE_ERROR(e.what()); } MsgHandler::getErrorInstance()->inform("Quitting (on error).", false); ret = 1; #ifndef _DEBUG } catch (const std::exception& e) { if (std::string(e.what()) != std::string("")) { WRITE_ERROR(e.what()); } MsgHandler::getErrorInstance()->inform("Quitting (on error).", false); ret = 1; } catch (...) { MsgHandler::getErrorInstance()->inform("Quitting (on unknown error).", false); ret = 1; #endif } delete net; delete flows; delete detectors; SystemFrame::close(); if (ret == 0) { std::cout << "Success." << std::endl; } return ret; }
void NBRampsComputer::buildOffRamp(NBNode* cur, NBNodeCont& nc, NBEdgeCont& ec, NBDistrictCont& dc, SUMOReal rampLength, bool dontSplit, std::set<NBEdge*>& incremented) { NBEdge* potHighway, *potRamp, *prev; getOffRampEdges(cur, &potHighway, &potRamp, &prev); // compute the number of lanes to append const unsigned int firstLaneNumber = potHighway->getNumLanes(); int toAdd = (potRamp->getNumLanes() + firstLaneNumber) - prev->getNumLanes(); NBEdge* first = prev; NBEdge* last = prev; NBEdge* curr = prev; if (toAdd > 0 && find(incremented.begin(), incremented.end(), prev) == incremented.end()) { SUMOReal currLength = 0; while (curr != 0 && currLength + curr->getGeometry().length() - POSITION_EPS < rampLength) { if (find(incremented.begin(), incremented.end(), curr) == incremented.end()) { curr->incLaneNo(toAdd); curr->invalidateConnections(true); incremented.insert(curr); moveRampRight(curr, toAdd); currLength += curr->getLength(); // !!! loaded length? last = curr; } NBNode* prevN = curr->getFromNode(); if (prevN->getIncomingEdges().size() == 1) { curr = prevN->getIncomingEdges()[0]; if (curr->getNumLanes() != firstLaneNumber) { // the number of lanes changes along the computation; we'll stop... curr = 0; } } else { // ambigous; and, in fact, what should it be? ...stop curr = 0; } } // check whether a further split is necessary if (curr != 0 && !dontSplit && currLength - POSITION_EPS < rampLength && curr->getNumLanes() == firstLaneNumber && find(incremented.begin(), incremented.end(), curr) == incremented.end()) { // there is enough place to build a ramp; do it bool wasFirst = first == curr; Position pos = curr->getGeometry().positionAtLengthPosition(curr->getGeometry().length() - (rampLength - currLength)); NBNode* rn = new NBNode(curr->getID() + "-AddedOffRampNode", pos); if (!nc.insert(rn)) { throw ProcessError("Ups - could not build on-ramp for edge '" + curr->getID() + "' (node could not be build)!"); } std::string name = curr->getID(); bool ok = ec.splitAt(dc, curr, rn, curr->getID(), curr->getID() + "-AddedOffRampEdge", curr->getNumLanes(), curr->getNumLanes() + toAdd); if (!ok) { WRITE_ERROR("Ups - could not build on-ramp for edge '" + curr->getID() + "'!"); return; } curr = ec.retrieve(name + "-AddedOffRampEdge"); curr->invalidateConnections(true); incremented.insert(curr); last = curr; moveRampRight(curr, toAdd); if (wasFirst) { first = curr; } } } // set connections from added ramp to ramp/highway if (!first->addLane2LaneConnections(potRamp->getNumLanes(), potHighway, 0, MIN2(first->getNumLanes() - 1, potHighway->getNumLanes()), NBEdge::L2L_VALIDATED, true)) { throw ProcessError("Could not set connection!"); } if (!first->addLane2LaneConnections(0, potRamp, 0, potRamp->getNumLanes(), NBEdge::L2L_VALIDATED, false)) { throw ProcessError("Could not set connection!"); } // patch ramp geometry PositionVector p = potRamp->getGeometry(); p.pop_front(); p.push_front(first->getLaneShape(0)[-1]); potRamp->setGeometry(p); // set connections from previous highway to added ramp NBNode* prevN = last->getFromNode(); if (prevN->getIncomingEdges().size() == 1) { NBEdge* prev = prevN->getIncomingEdges()[0];//const EdgeVector& o1 = cont->getToNode()->getOutgoingEdges(); if (prev->getNumLanes() < last->getNumLanes()) { last->addLane2LaneConnections(last->getNumLanes() - prev->getNumLanes(), last, 0, prev->getNumLanes(), NBEdge::L2L_VALIDATED); } } }
void RONetHandler::parseEdge(const SUMOSAXAttributes& attrs) { // get the id, report an error if not given or empty... bool ok = true; myCurrentName = attrs.get<std::string>(SUMO_ATTR_ID, 0, ok); if (!ok) { throw ProcessError(); } const SumoXMLEdgeFunc type = attrs.getEdgeFunc(ok); if (!ok) { WRITE_ERROR("Edge '" + myCurrentName + "' has an unknown type."); return; } // get the edge std::string from; std::string to; RONode* fromNode; RONode* toNode; int priority; myCurrentEdge = 0; if (type == EDGEFUNC_INTERNAL || type == EDGEFUNC_CROSSING || type == EDGEFUNC_WALKINGAREA) { assert(myCurrentName[0] == ':'); std::string junctionID = myCurrentName.substr(1, myCurrentName.rfind('_') - 1); myJunctionGraph[myCurrentName] = std::make_pair(junctionID, junctionID); from = junctionID; to = junctionID; priority = 0; } else { from = attrs.get<std::string>(SUMO_ATTR_FROM, myCurrentName.c_str(), ok); to = attrs.get<std::string>(SUMO_ATTR_TO, myCurrentName.c_str(), ok); priority = attrs.get<int>(SUMO_ATTR_PRIORITY, myCurrentName.c_str(), ok); if (!ok) { return; } } myJunctionGraph[myCurrentName] = std::make_pair(from, to); fromNode = myNet.getNode(from); if (fromNode == 0) { fromNode = new RONode(from); myNet.addNode(fromNode); } toNode = myNet.getNode(to); if (toNode == 0) { toNode = new RONode(to); myNet.addNode(toNode); } // build the edge myCurrentEdge = myEdgeBuilder.buildEdge(myCurrentName, fromNode, toNode, priority); // set the type myProcess = true; switch (type) { case EDGEFUNC_CONNECTOR: case EDGEFUNC_NORMAL: myCurrentEdge->setType(ROEdge::ET_NORMAL); break; case EDGEFUNC_SOURCE: myCurrentEdge->setType(ROEdge::ET_SOURCE); break; case EDGEFUNC_SINK: myCurrentEdge->setType(ROEdge::ET_SINK); break; case EDGEFUNC_WALKINGAREA: myCurrentEdge->setType(ROEdge::ET_WALKINGAREA); break; case EDGEFUNC_CROSSING: myCurrentEdge->setType(ROEdge::ET_CROSSING); break; case EDGEFUNC_INTERNAL: myCurrentEdge->setType(ROEdge::ET_INTERNAL); myProcess = false; break; default: throw ProcessError("Unhandled EdgeFunk " + toString(type)); } if (!myNet.addEdge(myCurrentEdge)) { myCurrentEdge = 0; } }
FXint GUILoadThread::run() { GUINet* net = 0; int simStartTime = 0; int simEndTime = 0; std::vector<std::string> guiSettingsFiles; bool osgView = false; OptionsCont& oc = OptionsCont::getOptions(); // register message callbacks MsgHandler::getMessageInstance()->addRetriever(myMessageRetriever); MsgHandler::getErrorInstance()->addRetriever(myErrorRetriever); MsgHandler::getWarningInstance()->addRetriever(myWarningRetriever); // try to load the given configuration if (!initOptions()) { // the options are not valid but maybe we want to quit GUIGlobals::gQuitOnEnd = oc.getBool("quit-on-end"); submitEndAndCleanup(net, simStartTime, simEndTime); return 0; } // within gui-based applications, nothing is reported to the console MsgHandler::getMessageInstance()->removeRetriever(&OutputDevice::getDevice("stdout")); MsgHandler::getWarningInstance()->removeRetriever(&OutputDevice::getDevice("stderr")); MsgHandler::getErrorInstance()->removeRetriever(&OutputDevice::getDevice("stderr")); // do this once again to get parsed options MsgHandler::initOutputOptions(); XMLSubSys::setValidation(oc.getString("xml-validation"), oc.getString("xml-validation.net")); GUIGlobals::gRunAfterLoad = oc.getBool("start"); GUIGlobals::gQuitOnEnd = oc.getBool("quit-on-end"); if (!MSFrame::checkOptions()) { MsgHandler::getErrorInstance()->inform("Quitting (on error).", false); submitEndAndCleanup(net, simStartTime, simEndTime); return 0; } // initialise global settings RandHelper::initRandGlobal(); RandHelper::initRandGlobal(&MSVehicleControl::myVehicleParamsRNG); MSFrame::setMSGlobals(oc); GUITexturesHelper::allowTextures(!oc.getBool("disable-textures")); MSVehicleControl* vehControl = 0; #ifdef HAVE_INTERNAL GUIVisualizationSettings::UseMesoSim = MSGlobals::gUseMesoSim; if (MSGlobals::gUseMesoSim) { vehControl = new GUIMEVehicleControl(); } else #endif vehControl = new GUIVehicleControl(); GUIEdgeControlBuilder* eb = 0; try { net = new GUINet( vehControl, new GUIEventControl(), new GUIEventControl(), new GUIEventControl()); eb = new GUIEdgeControlBuilder(); GUIDetectorBuilder db(*net); NLJunctionControlBuilder jb(*net, db); GUITriggerBuilder tb; NLHandler handler("", *net, db, tb, *eb, jb); tb.setHandler(&handler); NLBuilder builder(oc, *net, *eb, jb, db, handler); MsgHandler::getErrorInstance()->clear(); MsgHandler::getWarningInstance()->clear(); MsgHandler::getMessageInstance()->clear(); if (!builder.build()) { throw ProcessError(); } else { net->initGUIStructures(); simStartTime = string2time(oc.getString("begin")); simEndTime = string2time(oc.getString("end")); guiSettingsFiles = oc.getStringVector("gui-settings-file"); #ifdef HAVE_INTERNAL osgView = oc.getBool("osg-view"); #endif } } catch (ProcessError& e) { if (std::string(e.what()) != std::string("Process Error") && std::string(e.what()) != std::string("")) { WRITE_ERROR(e.what()); } MsgHandler::getErrorInstance()->inform("Quitting (on error).", false); delete net; net = 0; #ifndef _DEBUG } catch (std::exception& e) { WRITE_ERROR(e.what()); delete net; net = 0; #endif } if (net == 0) { MSNet::clearAll(); } delete eb; submitEndAndCleanup(net, simStartTime, simEndTime, guiSettingsFiles, osgView); return 0; }
int main(int argc, char *argv[]) { int i, num, port, result, numberOfLiveSockets, newSocket, pid; struct sockaddr_in serverAddress, remoteAddress; struct sigaction killAction; socklen_t serverAddressSize; port = SERVER_PORT; serverAddressSize = sizeof(struct sockaddr_in); requestsHandled = 0; connections = 0; num = 1; //This sets it so that when the precess is killed with ctrl-c it will close the proper sockets and print analytics killAction.sa_handler = KillProgramHandler; killAction.sa_flags = 0; if ((sigemptyset(&killAction.sa_mask) == -1 || sigaction(SIGINT, &killAction, NULL) == -1)) { std::cerr << "Failed to set SIGINT handler" << std::endl; exit(1); } // Creating the server socket serverSocket = socket(AF_INET, SOCK_STREAM, 0); if (serverSocket == -1) { ProcessError("Server socket creation"); } // Sets the socket so it can be re-used without it having to expire result = setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &num, sizeof(num)); if (result == -1) { ProcessError("Set server socket res-usable"); } // Bind server socket to port memset(&serverAddress, 0, sizeof(struct sockaddr_in)); serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); serverAddress.sin_port = htons(port); result = bind(serverSocket, (struct sockaddr *) &serverAddress, sizeof(serverAddress)); if (result == -1) { ProcessError("bind"); } // Server socket will listen for incoming concoctions with max of SERVER_LISTEN_MAX result = listen(serverSocket, SERVER_LISTEN_MAX); if (result == -1) { ProcessError("listen"); } //Basic server listen thread loop while (true) { newSocket = accept(serverSocket, (struct sockaddr *) &remoteAddress, &serverAddressSize); //Get new socket if (newSocket == -1) //If socket is error { ProcessError("Error on getting new socket"); } pid = fork(); //Fork so child can do work if (pid == 0) {//The child WatchSocket(newSocket); } connections++; //Increment connections //Parent will loop back } close(serverSocket); return 0; }
int NBHeightMapper::loadShapeFile(const std::string& file) { #ifdef HAVE_GDAL #if GDAL_VERSION_MAJOR < 2 OGRRegisterAll(); OGRDataSource* ds = OGRSFDriverRegistrar::Open(file.c_str(), FALSE); #else GDALAllRegister(); GDALDataset* ds = (GDALDataset*)GDALOpenEx(file.c_str(), GDAL_OF_VECTOR | GA_ReadOnly, NULL, NULL, NULL); #endif if (ds == NULL) { throw ProcessError("Could not open shape file '" + file + "'."); } // begin file parsing OGRLayer* layer = ds->GetLayer(0); layer->ResetReading(); // triangle coordinates are stored in WGS84 and later matched with network coordinates in WGS84 // build coordinate transformation OGRSpatialReference* sr_src = layer->GetSpatialRef(); OGRSpatialReference sr_dest; sr_dest.SetWellKnownGeogCS("WGS84"); OGRCoordinateTransformation* toWGS84 = OGRCreateCoordinateTransformation(sr_src, &sr_dest); if (toWGS84 == 0) { WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed."); } int numFeatures = 0; OGRFeature* feature; layer->ResetReading(); while ((feature = layer->GetNextFeature()) != NULL) { OGRGeometry* geom = feature->GetGeometryRef(); assert(geom != 0); // @todo gracefull handling of shapefiles with unexpected contents or any error handling for that matter assert(std::string(geom->getGeometryName()) == std::string("POLYGON")); // try transform to wgs84 geom->transform(toWGS84); OGRLinearRing* cgeom = ((OGRPolygon*) geom)->getExteriorRing(); // assume TIN with with 4 points and point0 == point3 assert(cgeom->getNumPoints() == 4); PositionVector corners; for (int j = 0; j < 3; j++) { Position pos((SUMOReal) cgeom->getX(j), (SUMOReal) cgeom->getY(j), (SUMOReal) cgeom->getZ(j)); corners.push_back(pos); myBoundary.add(pos); } addTriangle(corners); numFeatures++; /* OGRwkbGeometryType gtype = geom->getGeometryType(); switch (gtype) { case wkbPolygon: { break; } case wkbPoint: { WRITE_WARNING("got wkbPoint"); break; } case wkbLineString: { WRITE_WARNING("got wkbLineString"); break; } case wkbMultiPoint: { WRITE_WARNING("got wkbMultiPoint"); break; } case wkbMultiLineString: { WRITE_WARNING("got wkbMultiLineString"); break; } case wkbMultiPolygon: { WRITE_WARNING("got wkbMultiPolygon"); break; } default: WRITE_WARNING("Unsupported shape type occured"); break; } */ OGRFeature::DestroyFeature(feature); } #if GDAL_VERSION_MAJOR < 2 OGRDataSource::DestroyDataSource(ds); #else GDALClose(ds); #endif OCTDestroyCoordinateTransformation(toWGS84); OGRCleanupAll(); return numFeatures; #else WRITE_ERROR("Cannot load shape file since SUMO was compiled without GDAL support."); return 0; #endif }
void NIImporter_SUMO::_loadNetwork(OptionsCont& oc) { // check whether the option is set (properly) if (!oc.isUsableFileList("sumo-net-file")) { return; } // parse file(s) std::vector<std::string> files = oc.getStringVector("sumo-net-file"); for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) { if (!FileHelpers::isReadable(*file)) { WRITE_ERROR("Could not open sumo-net-file '" + *file + "'."); return; } setFileName(*file); PROGRESS_BEGIN_MESSAGE("Parsing sumo-net from '" + *file + "'"); XMLSubSys::runParser(*this, *file, true); PROGRESS_DONE_MESSAGE(); } // build edges for (std::map<std::string, EdgeAttrs*>::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) { EdgeAttrs* ed = (*i).second; // skip internal edges if (ed->func == EDGEFUNC_INTERNAL || ed->func == EDGEFUNC_CROSSING || ed->func == EDGEFUNC_WALKINGAREA) { continue; } // get and check the nodes NBNode* from = myNodeCont.retrieve(ed->fromNode); NBNode* to = myNodeCont.retrieve(ed->toNode); if (from == 0) { WRITE_ERROR("Edge's '" + ed->id + "' from-node '" + ed->fromNode + "' is not known."); continue; } if (to == 0) { WRITE_ERROR("Edge's '" + ed->id + "' to-node '" + ed->toNode + "' is not known."); continue; } // edge shape PositionVector geom; if (ed->shape.size() > 0) { geom = ed->shape; } else { // either the edge has default shape consisting only of the two node // positions or we have a legacy network geom = reconstructEdgeShape(ed, from->getPosition(), to->getPosition()); } // build and insert the edge NBEdge* e = new NBEdge(ed->id, from, to, ed->type, ed->maxSpeed, (unsigned int) ed->lanes.size(), ed->priority, NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, geom, ed->streetName, "", ed->lsf, true); // always use tryIgnoreNodePositions to keep original shape e->setLoadedLength(ed->length); if (!myNetBuilder.getEdgeCont().insert(e)) { WRITE_ERROR("Could not insert edge '" + ed->id + "'."); delete e; continue; } ed->builtEdge = myNetBuilder.getEdgeCont().retrieve(ed->id); } // assign further lane attributes (edges are built) for (std::map<std::string, EdgeAttrs*>::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) { EdgeAttrs* ed = (*i).second; NBEdge* nbe = ed->builtEdge; if (nbe == 0) { // inner edge or removed by explicit list, vclass, ... continue; } for (unsigned int fromLaneIndex = 0; fromLaneIndex < (unsigned int) ed->lanes.size(); ++fromLaneIndex) { LaneAttrs* lane = ed->lanes[fromLaneIndex]; // connections const std::vector<Connection>& connections = lane->connections; for (std::vector<Connection>::const_iterator c_it = connections.begin(); c_it != connections.end(); c_it++) { const Connection& c = *c_it; if (myEdges.count(c.toEdgeID) == 0) { WRITE_ERROR("Unknown edge '" + c.toEdgeID + "' given in connection."); continue; } NBEdge* toEdge = myEdges[c.toEdgeID]->builtEdge; if (toEdge == 0) { // removed by explicit list, vclass, ... continue; } if (nbe->hasConnectionTo(toEdge, c.toLaneIdx)) { WRITE_WARNING("Target lane '" + toEdge->getLaneID(c.toLaneIdx) + "' has multiple connections from '" + nbe->getID() + "'."); } nbe->addLane2LaneConnection( fromLaneIndex, toEdge, c.toLaneIdx, NBEdge::L2L_VALIDATED, true, c.mayDefinitelyPass, c.keepClear, c.contPos); // maybe we have a tls-controlled connection if (c.tlID != "" && myRailSignals.count(c.tlID) == 0) { const std::map<std::string, NBTrafficLightDefinition*>& programs = myTLLCont.getPrograms(c.tlID); if (programs.size() > 0) { std::map<std::string, NBTrafficLightDefinition*>::const_iterator it; for (it = programs.begin(); it != programs.end(); it++) { NBLoadedSUMOTLDef* tlDef = dynamic_cast<NBLoadedSUMOTLDef*>(it->second); if (tlDef) { tlDef->addConnection(nbe, toEdge, fromLaneIndex, c.toLaneIdx, c.tlLinkNo); } else { throw ProcessError("Corrupt traffic light definition '" + c.tlID + "' (program '" + it->first + "')"); } } } else { WRITE_ERROR("The traffic light '" + c.tlID + "' is not known."); } } } // allow/disallow XXX preferred nbe->setPermissions(parseVehicleClasses(lane->allow, lane->disallow), fromLaneIndex); // width, offset nbe->setLaneWidth(fromLaneIndex, lane->width); nbe->setEndOffset(fromLaneIndex, lane->endOffset); nbe->setSpeed(fromLaneIndex, lane->maxSpeed); } nbe->declareConnectionsAsLoaded(); if (!nbe->hasLaneSpecificWidth() && nbe->getLanes()[0].width != NBEdge::UNSPECIFIED_WIDTH) { nbe->setLaneWidth(-1, nbe->getLaneWidth(0)); } if (!nbe->hasLaneSpecificEndOffset() && nbe->getEndOffset(0) != NBEdge::UNSPECIFIED_OFFSET) { nbe->setEndOffset(-1, nbe->getEndOffset(0)); } } // insert loaded prohibitions for (std::vector<Prohibition>::const_iterator it = myProhibitions.begin(); it != myProhibitions.end(); it++) { NBEdge* prohibitedFrom = myEdges[it->prohibitedFrom]->builtEdge; NBEdge* prohibitedTo = myEdges[it->prohibitedTo]->builtEdge; NBEdge* prohibitorFrom = myEdges[it->prohibitorFrom]->builtEdge; NBEdge* prohibitorTo = myEdges[it->prohibitorTo]->builtEdge; if (prohibitedFrom == 0) { WRITE_WARNING("Edge '" + it->prohibitedFrom + "' in prohibition was not built"); } else if (prohibitedTo == 0) { WRITE_WARNING("Edge '" + it->prohibitedTo + "' in prohibition was not built"); } else if (prohibitorFrom == 0) { WRITE_WARNING("Edge '" + it->prohibitorFrom + "' in prohibition was not built"); } else if (prohibitorTo == 0) { WRITE_WARNING("Edge '" + it->prohibitorTo + "' in prohibition was not built"); } else { NBNode* n = prohibitedFrom->getToNode(); n->addSortedLinkFoes( NBConnection(prohibitorFrom, prohibitorTo), NBConnection(prohibitedFrom, prohibitedTo)); } } if (!myHaveSeenInternalEdge) { myNetBuilder.haveLoadedNetworkWithoutInternalEdges(); } if (oc.isDefault("lefthand")) { oc.set("lefthand", toString(myAmLefthand)); } if (oc.isDefault("junctions.corner-detail")) { oc.set("junctions.corner-detail", toString(myCornerDetail)); } if (oc.isDefault("junctions.internal-link-detail") && myLinkDetail > 0) { oc.set("junctions.internal-link-detail", toString(myLinkDetail)); } if (!deprecatedVehicleClassesSeen.empty()) { WRITE_WARNING("Deprecated vehicle class(es) '" + toString(deprecatedVehicleClassesSeen) + "' in input network."); deprecatedVehicleClassesSeen.clear(); } // add loaded crossings if (!oc.getBool("no-internal-links")) { for (std::map<std::string, std::vector<Crossing> >::const_iterator it = myPedestrianCrossings.begin(); it != myPedestrianCrossings.end(); ++it) { NBNode* node = myNodeCont.retrieve((*it).first); for (std::vector<Crossing>::const_iterator it_c = (*it).second.begin(); it_c != (*it).second.end(); ++it_c) { const Crossing& crossing = (*it_c); EdgeVector edges; for (std::vector<std::string>::const_iterator it_e = crossing.crossingEdges.begin(); it_e != crossing.crossingEdges.end(); ++it_e) { NBEdge* edge = myNetBuilder.getEdgeCont().retrieve(*it_e); // edge might have been removed due to options if (edge != 0) { edges.push_back(edge); } } if (edges.size() > 0) { node->addCrossing(edges, crossing.width, crossing.priority, true); } } } } // add roundabouts for (std::vector<std::vector<std::string> >::const_iterator it = myRoundabouts.begin(); it != myRoundabouts.end(); ++it) { EdgeSet roundabout; for (std::vector<std::string>::const_iterator it_r = it->begin(); it_r != it->end(); ++it_r) { NBEdge* edge = myNetBuilder.getEdgeCont().retrieve(*it_r); if (edge == 0) { if (!myNetBuilder.getEdgeCont().wasIgnored(*it_r)) { WRITE_ERROR("Unknown edge '" + (*it_r) + "' in roundabout"); } } else { roundabout.insert(edge); } } myNetBuilder.getEdgeCont().addRoundabout(roundabout); } }
/* * To register as Windows Service with SCM(Service Control Manager) * Input - Service Name, Service Display Name,Service Description and * Service startup arguments */ int RegisterService (LPCTSTR lpszServiceName, LPCTSTR lpszServiceDisplayName, LPCTSTR lpszServiceDescription, InputParams * StartUpArg, int quiet) /* Startup argument to the service */ { TCHAR szServicePath[MAX_PATH]; /* To hold module File name */ TCHAR MsgErrorString[MAX_STR_SIZE]; /* Message or Error string */ TCHAR szServiceCommand[MAX_PATH + 9]; /* Command to execute */ SC_HANDLE hSCManager = NULL; SC_HANDLE hService = NULL; TCHAR szRegAppLogKey[] = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\"; TCHAR szRegKey[512]; HKEY hKey = NULL; /* Key to registry entry */ HKEY hParamKey = NULL; /* To store startup parameters */ DWORD dwData; /* Type of logging supported */ DWORD i, j; /* Loop variables */ int exitStatus = 0; GetModuleFileName (NULL, szServicePath, MAX_PATH); TRY { /* * Open Service Control Manager handle */ hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_CREATE_SERVICE); if (hSCManager == NULL) { ProcessError (EVENTLOG_ERROR_TYPE, _T ("Can't open SCM (Service Control Manager)"), 1, quiet); exitStatus = SERVICE_ERROR_SCM_OPEN; LEAVE; } /* * Generate the Command to be executed by SCM */ _snprintf (szServiceCommand, sizeof(szServiceCommand), "%s %s", szServicePath, _T ("-service")); /* * Create the Desired service */ hService = CreateService (hSCManager, lpszServiceName, lpszServiceDisplayName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szServiceCommand, NULL, /* load-order group */ NULL, /* group member tag */ NULL, /* dependencies */ NULL, /* account */ NULL); /* password */ if (hService == NULL) { _snprintf (MsgErrorString, sizeof(MsgErrorString), "%s %s", _T ("Can't create service"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_SERVICE; LEAVE; } /* * Create registry entries for EventLog */ /* * Create registry Application event log key */ _tcscpy (szRegKey, szRegAppLogKey); _tcscat (szRegKey, lpszServiceName); /* * Create registry key */ if (RegCreateKey (HKEY_LOCAL_MACHINE, szRegKey, &hKey) != ERROR_SUCCESS) { _snprintf (MsgErrorString, sizeof(MsgErrorString), "%s %s", _T ("is unable to create registry entries"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES; LEAVE; } /* * Add Event ID message file name to the 'EventMessageFile' subkey */ RegSetValueEx (hKey, "EventMessageFile", 0, REG_EXPAND_SZ, (CONST BYTE *) szServicePath, _tcslen (szServicePath) + sizeof (TCHAR)); /* * Set the supported types flags. */ dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; RegSetValueEx (hKey, "TypesSupported", 0, REG_DWORD, (CONST BYTE *) & dwData, sizeof (DWORD)); /* * Close Registry key */ RegCloseKey (hKey); /* * Set Service Description String and save startup parameters if present */ if (lpszServiceDescription != NULL || StartUpArg->Argc > 2) { /* * Create Registry Key path */ _tcscpy (szRegKey, _T ("SYSTEM\\CurrentControlSet\\Services\\")); _tcscat (szRegKey, app_name); hKey = NULL; /* * Open Registry key using Create and Set access. */ if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, szRegKey, 0, KEY_WRITE, &hKey) != ERROR_SUCCESS) { _snprintf (MsgErrorString, sizeof(MsgErrorString), "%s %s", _T ("is unable to create registry entries"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES; LEAVE; } /* * Create description subkey and the set value */ if (lpszServiceDescription != NULL) { if (RegSetValueEx (hKey, "Description", 0, REG_SZ, (CONST BYTE *) lpszServiceDescription, _tcslen (lpszServiceDescription) + sizeof (TCHAR)) != ERROR_SUCCESS) { _snprintf (MsgErrorString, sizeof(MsgErrorString), "%s %s", _T ("is unable to create registry entries"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES; LEAVE; }; } /* * Save startup arguments if they are present */ if (StartUpArg->Argc > 2) { /* * Create Subkey parameters */ if (RegCreateKeyEx (hKey, "Parameters", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hParamKey, NULL) != ERROR_SUCCESS) { _snprintf (MsgErrorString, sizeof(MsgErrorString), "%s %s", _T ("is unable to create registry entries"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES; LEAVE; } /* * Save parameters */ /* * Loop through arguments */ if (quiet) /* Make sure we don't store -quiet arg */ i = 3; else i = 2; for (j = 1; i < StartUpArg->Argc; i++, j++) { _snprintf (szRegKey, sizeof(szRegKey), "%s%d", _T ("Param"), j); /* * Create registry key */ if (RegSetValueEx (hParamKey, szRegKey, 0, REG_SZ, (CONST BYTE *) StartUpArg->Argv[i], _tcslen (StartUpArg->Argv[i]) + sizeof (TCHAR)) != ERROR_SUCCESS) { _snprintf (MsgErrorString, sizeof(MsgErrorString), "%s %s", _T ("is unable to create registry entries"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES; LEAVE; }; } } /* * Everything is set, delete hKey */ RegCloseKey (hParamKey); RegCloseKey (hKey); } /* * Ready to Log messages */ /* * Successfully registered as service */ _snprintf (MsgErrorString, sizeof(MsgErrorString), "%s %s", lpszServiceName, _T ("successfully registered as a service")); /* * Log message to eventlog */ ProcessError (EVENTLOG_INFORMATION_TYPE, MsgErrorString, 0, quiet); } FINALLY { if (hSCManager) CloseServiceHandle (hSCManager); if (hService) CloseServiceHandle (hService); if (hKey) RegCloseKey (hKey); if (hParamKey) RegCloseKey (hParamKey); } return (exitStatus); }
void RONetHandler::parseEdge(const SUMOSAXAttributes& attrs) { // get the id, report an error if not given or empty... bool ok = true; myCurrentName = attrs.get<std::string>(SUMO_ATTR_ID, 0, ok); if (!ok) { throw ProcessError(); } const SumoXMLEdgeFunc type = attrs.getEdgeFunc(ok); if (!ok) { WRITE_ERROR("Edge '" + myCurrentName + "' has an unknown type."); return; } // get the edge RONode* fromNode; RONode* toNode; int priority; myCurrentEdge = 0; if (type == EDGEFUNC_INTERNAL) { // this is an internal edge - for now we only us it the ensure a match // between numerical edge ids in router and simulation // !!! recheck this; internal edges may be of importance during the dua fromNode = 0; toNode = 0; priority = 0; } else { const std::string from = attrs.get<std::string>(SUMO_ATTR_FROM, myCurrentName.c_str(), ok); const std::string to = attrs.get<std::string>(SUMO_ATTR_TO, myCurrentName.c_str(), ok); priority = attrs.get<int>(SUMO_ATTR_PRIORITY, myCurrentName.c_str(), ok); if (!ok) { return; } fromNode = myNet.getNode(from); if (fromNode == 0) { fromNode = new RONode(from); myNet.addNode(fromNode); } toNode = myNet.getNode(to); if (toNode == 0) { toNode = new RONode(to); myNet.addNode(toNode); } } // build the edge myCurrentEdge = myEdgeBuilder.buildEdge(myCurrentName, fromNode, toNode, priority); // set the type myProcess = true; switch (type) { case EDGEFUNC_CONNECTOR: case EDGEFUNC_NORMAL: myCurrentEdge->setType(ROEdge::ET_NORMAL); break; case EDGEFUNC_SOURCE: myCurrentEdge->setType(ROEdge::ET_SOURCE); break; case EDGEFUNC_SINK: myCurrentEdge->setType(ROEdge::ET_SINK); break; case EDGEFUNC_INTERNAL: myCurrentEdge->setType(ROEdge::ET_INTERNAL); myProcess = false; break; default: throw ProcessError("Unhandled EdgeFunk " + toString(type)); } if (!myNet.addEdge(myCurrentEdge)) { myCurrentEdge = 0; } }
// ------------ loading begin void MSTriggeredRerouter::myStartElement(SumoXMLTag element, const SUMOSAXAttributes &attrs) throw(ProcessError) { if (element==SUMO_TAG_INTERVAL) { bool ok = true; myCurrentIntervalBegin = attrs.getOptSUMOTimeReporting(SUMO_ATTR_BEGIN, "interval", 0, ok, -1); myCurrentIntervalEnd = attrs.getOptSUMOTimeReporting(SUMO_ATTR_END, "interval", 0, ok, -1); } if (element==SUMO_TAG_DEST_PROB_REROUTE) { // by giving probabilities of new destinations // get the destination edge std::string dest = attrs.getStringSecure(SUMO_ATTR_ID, ""); if (dest=="") { throw ProcessError("MSTriggeredRerouter " + getID() + ": No destination edge id given."); } MSEdge *to = MSEdge::dictionary(dest); if (to==0) { throw ProcessError("MSTriggeredRerouter " + getID() + ": Destination edge '" + dest + "' is not known."); } // get the probability to reroute bool ok = true; SUMOReal prob = attrs.getOptSUMORealReporting(SUMO_ATTR_PROB, "rerouter/dest_prob_reroute", getID().c_str(), ok, 1.); if (!ok) { throw ProcessError(); } if (prob<0) { throw ProcessError("MSTriggeredRerouter " + getID() + ": Attribute 'probability' for destination '" + dest + "' is negative (must not)."); } // add myCurrentEdgeProb.add(prob, to); } if (element==SUMO_TAG_CLOSING_REROUTE) { // by closing std::string closed_id = attrs.getStringSecure(SUMO_ATTR_ID, ""); if (closed_id=="") { throw ProcessError("MSTriggeredRerouter " + getID() + ": closed edge id given."); } MSEdge *closed = MSEdge::dictionary(closed_id); if (closed==0) { throw ProcessError("MSTriggeredRerouter " + getID() + ": Edge '" + closed_id + "' to close is not known."); } myCurrentClosed.push_back(closed); } if (element==SUMO_TAG_ROUTE_PROB_REROUTE) { // by explicite rerouting using routes // check if route exists std::string routeStr = attrs.getStringSecure(SUMO_ATTR_ID, ""); if (routeStr=="") { throw ProcessError("MSTriggeredRerouter " + getID() + ": No route id given."); } const MSRoute* route = MSRoute::dictionary(routeStr); if (route == 0) { throw ProcessError("MSTriggeredRerouter " + getID() + ": Route '" + routeStr + "' does not exist."); } // get the probability to reroute bool ok = true; SUMOReal prob = attrs.getOptSUMORealReporting(SUMO_ATTR_PROB, "rerouter/dest_prob_reroute", getID().c_str(), ok, 1.); if (!ok) { throw ProcessError(); } if (prob<0) { throw ProcessError("MSTriggeredRerouter " + getID() + ": Attribute 'probability' for route '" + routeStr + "' is negative (must not)."); } // add myCurrentRouteProb.add(prob, route); } }
void NBNodeCont::joinNodeClusters(NodeClusters clusters, NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc) { for (NodeClusters::iterator i = clusters.begin(); i != clusters.end(); ++i) { std::set<NBNode*> cluster = *i; assert(cluster.size() > 1); Position pos; bool setTL; std::string id; TrafficLightType type; analyzeCluster(cluster, id, pos, setTL, type); if (!insert(id, pos)) { // should not fail WRITE_WARNING("Could not join junctions " + id); continue; } NBNode* newNode = retrieve(id); if (setTL) { NBTrafficLightDefinition* tlDef = new NBOwnTLDef(id, newNode, 0, type); if (!tlc.insert(tlDef)) { // actually, nothing should fail here delete tlDef; throw ProcessError("Could not allocate tls '" + id + "'."); } } // collect edges std::set<NBEdge*> allEdges; for (std::set<NBNode*>::const_iterator j = cluster.begin(); j != cluster.end(); ++j) { const EdgeVector& edges = (*j)->getEdges(); allEdges.insert(edges.begin(), edges.end()); } // remap and remove edges which are completely within the new intersection for (std::set<NBEdge*>::iterator j = allEdges.begin(); j != allEdges.end();) { NBEdge* e = (*j); NBNode* from = e->getFromNode(); NBNode* to = e->getToNode(); if (cluster.count(from) > 0 && cluster.count(to) > 0) { for (std::set<NBEdge*>::iterator l = allEdges.begin(); l != allEdges.end(); ++l) { if (e != *l) { (*l)->replaceInConnections(e, e->getConnections()); } } ec.erase(dc, e); allEdges.erase(j++); // erase does not invalidate the other iterators } else { ++j; } } // remap edges which are incoming / outgoing for (std::set<NBEdge*>::iterator j = allEdges.begin(); j != allEdges.end(); ++j) { NBEdge* e = (*j); std::vector<NBEdge::Connection> conns = e->getConnections(); const bool outgoing = cluster.count(e->getFromNode()) > 0; NBNode* from = outgoing ? newNode : e->getFromNode(); NBNode* to = outgoing ? e->getToNode() : newNode; e->reinitNodes(from, to); // re-add connections which previously existed and may still valid. // connections to removed edges will be ignored for (std::vector<NBEdge::Connection>::iterator k = conns.begin(); k != conns.end(); ++k) { e->addLane2LaneConnection((*k).fromLane, (*k).toEdge, (*k).toLane, NBEdge::L2L_USER, false, (*k).mayDefinitelyPass); } } // remove original nodes registerJoinedCluster(cluster); for (std::set<NBNode*>::const_iterator j = cluster.begin(); j != cluster.end(); ++j) { erase(*j); } } }