void
GUITriggeredRerouter::GUITriggeredRerouterEdge::drawGL(const GUIVisualizationSettings& s) const {
    const SUMOReal exaggeration = s.addSize.getExaggeration(s);
    if (s.scale * exaggeration >= 3) {
        glPushName(getGlID());
        const SUMOReal prob = myParent->getProbability();
        if (myAmClosedEdge) {
            // draw closing symbol onto all lanes
            const RerouteInterval* const ri =
                myParent->getCurrentReroute(MSNet::getInstance()->getCurrentTimeStep());
            if (ri != 0 && prob > 0) {
                // draw only if the edge is closed at this time
                if (std::find(ri->closed.begin(), ri->closed.end(), myEdge) != ri->closed.end()) {
                    const size_t noLanes = myFGPositions.size();
                    for (size_t j = 0; j < noLanes; ++j) {
                        Position pos = myFGPositions[j];
                        SUMOReal rot = myFGRotations[j];
                        glPushMatrix();
                        glTranslated(pos.x(), pos.y(), 0);
                        glRotated(rot, 0, 0, 1);
                        glTranslated(0, -1.5, 0);
                        int noPoints = 9;
                        if (s.scale > 25) {
                            noPoints = (int)(9.0 + s.scale / 10.0);
                            if (noPoints > 36) {
                                noPoints = 36;
                            }
                        }
                        glTranslated(0, 0, getType());
                        //glScaled(exaggeration, exaggeration, 1);
                        glColor3d(0.7, 0, 0);
                        GLHelper::drawFilledCircle((SUMOReal) 1.3, noPoints);
                        glTranslated(0, 0, .1);
                        glColor3d(1, 0, 0);
                        GLHelper::drawFilledCircle((SUMOReal) 1.3, noPoints, 0, prob * 360);
                        glTranslated(0, 0, .1);
                        glColor3d(1, 1, 1);
                        glRotated(-90, 0, 0, 1);
                        glBegin(GL_TRIANGLES);
                        glVertex2d(0 - .3, -1.);
                        glVertex2d(0 - .3, 1.);
                        glVertex2d(0 + .3, 1.);
                        glVertex2d(0 + .3, -1.);
                        glVertex2d(0 - .3, -1.);
                        glVertex2d(0 + .3, 1.);
                        glEnd();
                        glPopMatrix();
                    }
                }
            }

        } else {
            // draw rerouter symbol onto all lanes
            for (size_t i = 0; i < myFGPositions.size(); ++i) {
                const Position& pos = myFGPositions[i];
                SUMOReal rot = myFGRotations[i];
                glPushMatrix();
                glTranslated(pos.x(), pos.y(), 0);
                glRotated(rot, 0, 0, 1);
                glTranslated(0, 0, getType());
                glScaled(exaggeration, exaggeration, 1);
                glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

                glBegin(GL_TRIANGLES);
                glColor3d(1, .8f, 0);
                // base
                glVertex2d(0 - 1.4, 0);
                glVertex2d(0 - 1.4, 6);
                glVertex2d(0 + 1.4, 6);
                glVertex2d(0 + 1.4, 0);
                glVertex2d(0 - 1.4, 0);
                glVertex2d(0 + 1.4, 6);
                glEnd();

                glTranslated(0, 0, .1);
                glColor3d(0, 0, 0);
                pfSetPosition(0, 0);
                pfSetScale(3.f);
                SUMOReal w = pfdkGetStringWidth("U");
                glRotated(180, 0, 1, 0);
                glTranslated(-w / 2., 2, 0);
                pfDrawString("U");

                glTranslated(w / 2., -2, 0);
                std::string str = toString((int)(prob * 100)) + "%";
                pfSetPosition(0, 0);
                pfSetScale(.7f);
                w = pfdkGetStringWidth(str.c_str());
                glTranslated(-w / 2., 4, 0);
                pfDrawString(str.c_str());
                glPopMatrix();
            }
        }
        glPopName();
    }
}
Beispiel #2
0
string CTodo::toString()
{
    CAlarm *pAlarm;
    CRecurrence *cRec;
    string szRet;
    string szTemp;
    time_t temp = 0;
    std::stringstream ss;
    ss << "ID=";
    if (getId().c_str()){
	szTemp= getId().substr(0,100);
	ss << szTemp;
	szTemp.clear();
    }
    else
	ss << NULL_STRING;

    ss << ",CalendarId=";
    ss << getCalendarId();

    ss << ",summary=";
    if (getSummary().c_str()){
	szTemp= getSummary().substr(0,100);
	ss << szTemp;
	szTemp.clear();
    }

    else
	ss << NULL_STRING;
    ss << ",description=";
    if (getDescription().c_str()){
	szTemp= getDescription().substr(0,100);
	ss << szTemp;
	szTemp.clear();
    }

    else
	ss << NULL_STRING;
    ss << ",location=";
    if (getLocation().c_str()){
	szTemp= getLocation().substr(0,100);
	ss << szTemp;
	szTemp.clear();
    }

    else
	ss << NULL_STRING;
    ss << ",UId=";
    if (getGUid().c_str()){
	szTemp= getGUid().substr(0,100);
	ss << szTemp;
	szTemp.clear();
    }
    else
	ss << NULL_STRING;

    ss << ",TimeZone=";
    if (getTzid().c_str()){
	szTemp= getTzid().substr(0,100);
	ss << szTemp;
	szTemp.clear();
    }
    else
	ss << NULL_STRING;
    ss << ",Type=";
    ss << getType() ;
    ss << ",Flags=";
    switch (getFlags()){
	case HAS_ATTENDEE:
	    ss << "Has Attendee";
	    break;
	case HAS_ORGANIZER:
	    ss << "Has Organizer";
	    break;
	case HAS_RECURRENCE:
	    ss << "Has Recurrence";
	    break;
	case HAS_ALARM:
	    ss << "Has Alarm";
	    break;
	case HAS_RECURRENCE_ALARM :
	    ss << "Has Recurrent Alarm";
	    break;
	case HAS_PARTICIPANT :
	    ss << "Has Participant";
	    break;
	case HAS_CATEGORIES :
	    ss << "Has Categories";
	    break;
	case HAS_COMMENT:
	    ss << "Has Comment ";
	    break;
	case HAS_EXTRA:
	    ss << "Has Extra ";
	    break;
	default:
	    break;
    }

    ss << ",Status=";
    ss << getStatus();
    ss << ",Start date=";
    temp = getDateStart();
    ss << ctime(&temp);
    ss << ",End date=";
    temp = getDateEnd();
    ss << ctime(&temp);
    ss << ",Last modified=";
    temp = getLastModified();
    ss << ctime(&temp);
    ss << ",created=";
    temp = getCreatedTime();
    ss << ctime(&temp);
    ss << ",until=";
    temp = getUntil();
    ss << ctime(&temp);

    ss << ",All day=";
    ss << getAllDay();
    ss << ",Geo=";
    if (szGeo.c_str()){
	szTemp= szGeo.substr(0,100);
	ss << szTemp;
	szTemp.clear();
    }
    else
	ss << NULL_STRING;

    ss << ",TodoDue=";
    ss << iDue;
    ss << ",Completed=";
    ss << iCompleted;
    ss << ",Percent";
    ss << iPercentComplete;
    ss << ",Priority";
    ss << iPriority;
    pAlarm=getAlarm();
    if(pAlarm)
	ss << pAlarm->toString();
    else
	ss << ",Alarm=NULL";
    cRec=getRecurrence();
    if(cRec)
	ss << cRec->toString();
    else
	ss << ",Rec=NULL";

    szRet.append(ss.str());
    return szRet;
}
Beispiel #3
0
TouchSensorNode *TouchSensorNode::next() 
{
	return (TouchSensorNode *)Node::next(getType());
}
Beispiel #4
0
TouchSensorNode *TouchSensorNode::nextTraversal() 
{
	return (TouchSensorNode *)Node::nextTraversalByType(getType());
}
Beispiel #5
0
int main(int argc, char **argv)
{
    char *iFuncName;
    int m, info;
    int maxEvals;
    int iFuncNumb, n, numIter;
    int contSucess = 0;
    int type;
    real *x;
    real epsg, epsf, epsx;
    real maxiters = 0;
    long fnEvals, mediaFnEvals = 0;
    long gradEvals, mediaGradEvals = 0;
    bool sucess;
    int64_t initialTime, finalTime;
    int64_t deltaTime, mediaTime = 0;
    ap::real_1d_array xBFGS;
    MGrasp *mgrasp;
    LBFGS *lbfgs;
    Funcao *func;

    real *gaps;
    real mediaGaps[7];

    if (argc < 7) {
        usage();
        return 1;
    }

    epsg = 0.000001;
    epsf = 0.000001;
    epsx = 0.000001;
    maxiters = 0;

    iFuncName   = argv[1];
    iFuncNumb   = getFuncNumb(iFuncName);
    n           = atoi(argv[2]);
    maxEvals    = atoi(argv[3]);
    numIter     = atoi(argv[4]);
    type        = getType(argv[5]);
    m           = atoi(argv[6]);

    if (iFuncNumb == -1) {
        printf("Função %s não existe... \n\n", iFuncName);
        return 1;
    }

    if (type == -1) {
        printf("Tipo %s não existe... \n\n", argv[4]);
        return 1;
    }

    if (m > n) {
        printf("'m' deve ser menor ou igual a 'n' \n\n");
        return 1;
    }

    for (int i = 0; i < 7; i++) {
        mediaGaps[i] = 0.0;
    }

    if (iFuncNumb == Funcao::PAR_SPHERE) {
        if (!init_gpu(n)) {
            fprintf(stderr, "Erro inicializando GPU\n");
            return 2;
        }
    }

    srand(time(NULL));
    for (int i = 1; i <= numIter; i++) {
        sucess = false;

        printf("[%d]Iteracao \n", i);
        initialTime = getMilisegundos();

        mgrasp = initMGrasp(iFuncNumb, n, &func);

        if (type == PURO) {
            printf("Puro... \n");
            sucess = mgrasp->start(false, m, maxEvals);
        }
        else if (type == HIBRIDO) {
            printf("Hibrido... \n");
            sucess = mgrasp->start(true, m, maxEvals);
        }
        else {
            printf("BFGS... \n");
            x = new real[n];
            mgrasp->unifRandom(x);
            xBFGS.setbounds(1, n);
            for (int j = 0; j < n; j++) {
                xBFGS(j+1) = x[j];
            }
            lbfgs = new LBFGS(func, false);
            lbfgs->minimize(n, m, xBFGS, epsg, epsf, epsx, maxiters, info);

            sucess = true;
            printf("Info = %d \n", info);
        }

        finalTime = getMilisegundos();
        printf("\tTime = %lld \n", finalTime - initialTime);

        if (maxEvals) {
            gaps = mgrasp->getGaps();
            for (int j = 0; j < 7; j++){
                mediaGaps[j] += gaps[j];
                printf("[%d]Gap[%d] = %lf (%lf)... \n", i, j, mediaGaps[j], gaps[j]);
            }
        }
        else if (sucess) {
            contSucess++;
            fnEvals = func->getFnEvals();
            gradEvals = func->getGradEvals();
            deltaTime = finalTime - initialTime;

            mediaFnEvals   += fnEvals;
            mediaGradEvals += gradEvals;
            mediaTime      += deltaTime;
            printf("[%d]Sucesso(%d) = %ld (%d)... \n", i, contSucess, mediaFnEvals, fnEvals);
            printf("[%d]Grad(%d) = %ld (%d)... \n", i, contSucess, mediaGradEvals, gradEvals);
        }
        printf("\n");
        delete mgrasp;
        delete func;
    }

    if (maxEvals) {
        saveGaps(mediaGaps, numIter);
    }
    else {
        printf("Num execucoes com sucesso... = %d \n", contSucess);
        printf("Media de avaliacao da funcao... = %d \n", (long)((real)mediaFnEvals/contSucess));
        printf("Media de avaliacao do gradiente... = %d \n", (long)((real)mediaGradEvals/contSucess));
        printf("Media de tempo... = %d \n", (long)((real)mediaTime/contSucess));
    }

    if (iFuncNumb == Funcao::PAR_SPHERE)
        finalize_gpu();

    return 0;
}
QVariant ParameterFileModel::data(const QModelIndex& ind, int role) const {
	// mapper to convert parameter.type into QVariant::Type
	const VarTypeMap& mapper = VarTypeMap::instance();
	int row = ind.row();
	int col = ind.column();
	QString key = _keys[row];
	QString val;
	QVariant res;

	switch (role) {

	case Qt::EditRole:
	case Qt::DisplayRole:
		if ((row >= 0) && (row < _keys.size())) {
			switch (col) {
			case 0:
				// parameter name (without prefix)
				if (!_prefix.isEmpty())
					key.remove(0, _prefix.length());

				// remove dot after valid prefix
				if (key[0] == '.')
					key.remove(0, 1);
				return key;

			case 1:
				if (_parameterFile->isSet(_keys[row])) {
					val = _parameterFile->get(_keys[row]);
				}
				else if (_onlyParams) {
					val = getDefault(_keys[row]);
				}

				// handle parameter links
				if (val.startsWith('@')) {
					QString ref = val.mid(1);
					if(_parameterFile->isSet(ref)) {
						val = _parameterFile->get(ref);
					}
					else if(role == Qt::DisplayRole) {
						val = tr("[invalid reference to %1]").arg(ref);
					}
				}

				// handle QVariant type
				res = val;
				if (_useMetaInfo && isParameter(key)) {
					QString typestring = getType(key);
					QVariant::Type type = mapper[typestring];
					Q_ASSERT(res.canConvert(type));
					res.convert(type);
				}
				return res;

			case 2:
				if (role == Qt::DisplayRole) {
					return QVariant();
				}
				return getValue(key + ".editorpriority").toUInt();
			}
		}
		break;

	case Qt::ToolTipRole:
		if (_useMetaInfo) {
			QString ret = _metaInfos->getDocString(key, getClass(key));
			return ret.isEmpty() ? QVariant() : ret;
		}
		break;

	case Qt::ForegroundRole:
		if (_onlyParams && !isSet(key)) {
			return QColor(Qt::lightGray);
		}
		break;

	case Qt::BackgroundRole:
		switch (getValue(key+".editorpriority").toInt()) {
		case 1:
			return QColor("#8f8");
		case 2:
			return QColor("#ff8");
		case 3:
			return QColor("#f80");
		default:
			break;
		}
		break;

	case Qt::CheckStateRole:
		if (_useMetaInfo && col == 1 &&
				isParameter(key) && getType(key) == "bool") {
			const bool& checked = isSet(key) ?
					QVariant(getValue(key)).toBool() :
					QVariant(getDefault(key)).toBool();
			return checked ? Qt::Checked : Qt::Unchecked;
		}
		break;

	case Qt::StatusTipRole:
		if(col == 1) {
			if (isSet(key)) {
				QString ret = getValue(key);
				if(ret.startsWith('@')) {
					return tr("link to: %1").arg(ret.mid(1));
				}
			}
		}
		break;

	case Qt::DecorationRole:
		if(col == 1) {
			if (isSet(key)) {
				QString ret = getValue(key);
				if(ret.startsWith('@')) {
					return QIcon(":/icons/symlink.png");
				}
			}
		}
		break;

	} // role switch

	return QVariant();
}
bool ParameterFileModel::setData(
		const QModelIndex& ind, const QVariant& value, int role) {

	if (!prefixValid())
		return false;

	switch (role) {
	case Qt::EditRole:
	case Qt::DisplayRole:
		if ((ind.row() >= 0) && (ind.row() < _keys.size())) {
			switch (ind.column()) {
			case 0:
				if (_onlyParams)
					return false;

				if (value.canConvert(QVariant::String)) {
					QString oldName = _keys[ind.row()];
					QString newName;
					// do not forget the prefix at the beginning of the name
					if (!_prefix.isEmpty())
						newName = _prefix + ".";
					newName += value.toString();
					if (oldName == newName)
						return true; // nothing to do
					if (_parameterFile->isSet(newName))
						return false; // don't overwrite existing value

					// save value
					QString val = getValue(oldName);
					erase(oldName);
					setValue(newName, val);
					emit dataChanged(ind, ind);
					return true;
				}
				break;
			case 1:
				if (value.canConvert(QVariant::String)) {
					QString valueStr = value.toString();
					QString keyStr = _keys[ind.row()];
					if (valueStr == getValue(keyStr))
						return true; // nothing to do

					setValue(keyStr, valueStr);
					if (_onlyParams && _metaInfos->isDynamic(getClass(keyStr))) {
						save();
						_updateDynamics();
						QTimer::singleShot(0, this, SLOT(_update()));
						emit dynamicUpdate();
					}
					emit dataChanged(index(ind.row(), 0), ind);
					return true;
				}
				break;
			case 2:
				if (value.canConvert(QVariant::Int)) {
					// check if value is allowed
					int valueInt = value.toInt();
					QString valueStr = QVariant(valueInt).toString();
					if (valueInt < 0 || valueInt > 3) {
						return false;
					}

					if (valueInt == 0) {
						// 0 is default value -> no entry needed
						if (isSet(_keys[ind.row()] + ".editorpriority")) {
							// check if value exists to prevent exceptions
							erase(_keys[ind.row()] + ".editorpriority");
							emit dataChanged(index(ind.row(), 0), ind);
						}
						return true;
					}

					if (valueStr ==
							getValue(_keys[ind.row()] + ".editorpriority")) {
						return true; // nothing to do
					}

					setValue(_keys[ind.row()] + ".editorpriority", valueStr);
					emit dataChanged(index(ind.row(), 0), ind);
					return true;
				}
				break;
			}
		}
		break;

	case Qt::CheckStateRole:
		if (_useMetaInfo && ind.column()==1 && isParameter(_keys[ind.row()])) {
			Q_ASSERT(getType(_keys[ind.row()]) == "bool");
			bool checked (value.toBool());
			setValue (_keys[ind.row()], checked ? "true" : "false");
            emit dataChanged(index(ind.row(),0),ind);
            if (_keys[ind.row()].contains("active") && checked == true){
                reactivatePreviousPlugins();
            }
            // additional check whether the changed Parameter is the ActiveInactive
            if (_keys[ind.row()].contains("active") && checked == false){
                deactivate();
            }
        }
		break;
	}
	return false;
}
Beispiel #8
0
std::shared_ptr<te::mem::DataSet> terrama2::services::analysis::core::createAggregationBuffer(
        std::vector<uint32_t>& indexes, std::shared_ptr<ContextDataSeries> contextDataSeries, Buffer buffer,
        StatisticOperation aggregationStatisticOperation,
        const std::string& attribute)
{
  std::shared_ptr<te::mem::DataSet> dsOut;
  if(indexes.empty())
    return dsOut;



  // Creates memory dataset for buffer
  te::da::DataSetType* dt = new te::da::DataSetType("buffer");

  auto syncDs = contextDataSeries->series.syncDataSet;
  auto sampleGeom = syncDs->getGeometry(0, contextDataSeries->geometryPos);
  int geomSampleSrid = sampleGeom->getSRID();

  te::gm::GeometryProperty* prop = new te::gm::GeometryProperty("geom", 0, te::gm::MultiPolygonType, true);
  prop->setSRID(geomSampleSrid);
  dt->add(prop);


  te::dt::SimpleProperty* prop02 = new te::dt::SimpleProperty("attribute", te::dt::DOUBLE_TYPE, true);
  dt->add(prop02);

  dsOut.reset(new te::mem::DataSet(dt));


  std::shared_ptr<te::gm::Envelope> box(syncDs->getExtent(contextDataSeries->geometryPos));


  if(buffer.unit.empty())
    buffer.unit = "m";

  // Inserts each geometry in the rtree, if there is a conflict, it makes the union of the two geometries
  te::sam::rtree::Index<OccurrenceAggregation*, 4> rtree;

  for(size_t i = 0; i < indexes.size(); ++i)
  {
    auto geom = syncDs->getGeometry(indexes[i], contextDataSeries->geometryPos);


    double distance = terrama2::core::convertDistanceUnit(buffer.distance, buffer.unit, "METER");

    std::unique_ptr<te::gm::Geometry> tempGeom(dynamic_cast<te::gm::Geometry*>(geom.get()->clone()));
    if(!tempGeom)
    {
      QString errMsg(QObject::tr("Invalid geometry in dataset: ").arg(contextDataSeries->series.dataSet->id));
      throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
    }
    int utmSrid = terrama2::core::getUTMSrid(tempGeom.get());

    // Converts to UTM in order to create buffer in meters
    if(tempGeom->getSRID() != utmSrid)
    {
      tempGeom->transform(utmSrid);
    }
    std::unique_ptr<te::gm::Geometry> aggBuffer(tempGeom->buffer(distance, 16, te::gm::CapButtType));
    aggBuffer->setSRID(utmSrid);

    // Converts buffer to DataSet SRID in order to compare with the occurrences in the rtree
    aggBuffer->transform(geomSampleSrid);


    std::vector<OccurrenceAggregation*> vec;
    bool aggregated = false;

    // Search for occurrences in the same area
    rtree.search(*(aggBuffer->getMBR()), vec);
    for(std::size_t t = 0; t < vec.size(); ++t)
    {
      OccurrenceAggregation* occurrenceAggregation = vec[t];

      // If the an intersection is found, makes the union of the two geometries and mark the index.
      if(aggBuffer->intersects(occurrenceAggregation->buffer.get()))
      {
        rtree.remove(*(occurrenceAggregation->buffer->getMBR()), occurrenceAggregation);
        occurrenceAggregation->buffer.reset(aggBuffer->Union(occurrenceAggregation->buffer.get()));
        occurrenceAggregation->indexes.push_back(i);
        rtree.insert(*(occurrenceAggregation->buffer->getMBR()), occurrenceAggregation);
        aggregated = true;
      }
    }

    if(!aggregated)
    {
      OccurrenceAggregation* occurrenceAggregation = new OccurrenceAggregation();
      occurrenceAggregation->buffer.reset(aggBuffer.release());
      occurrenceAggregation->indexes.push_back(i);
      rtree.insert(*(occurrenceAggregation->buffer->getMBR()), occurrenceAggregation);
    }
  }

  // Fills the memory dataset with the geometries
  std::vector<OccurrenceAggregation*> occurrenceAggVec;

  rtree.search(*(box.get()), occurrenceAggVec);

  int attributeType = -1;

  if(aggregationStatisticOperation != StatisticOperation::COUNT)
  {
    auto property = contextDataSeries->series.teDataSetType->getProperty(attribute);

    if(!property)
    {
      QString errMsg(QObject::tr("Invalid attribute: %1").arg(QString::fromStdString(attribute)));
      throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
    }
    attributeType = property->getType();
  }


  for(size_t i = 0; i < occurrenceAggVec.size(); i++)
  {
    OccurrenceAggregation* occurrenceAggregation = occurrenceAggVec[i];

    OperatorCache cache;
    std::vector<double> values;
    values.reserve(occurrenceAggregation->indexes.size());
    for(unsigned int j = 0; j < occurrenceAggregation->indexes.size(); ++j)
    {
      cache.count++;

      if(aggregationStatisticOperation != StatisticOperation::COUNT)
      {
        if(attribute.empty())
        {
          QString errMsg(QObject::tr("Invalid attribute"));
          throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
        }

        double value = getValue(syncDs, attribute, occurrenceAggregation->indexes[j], attributeType);
        values.push_back(value);
        cache.sum += value;
        if(value > cache.max)
          cache.max = value;
        if(value < cache.min)
          cache.min = value;
      }
    }

    calculateStatistics(values, cache);

    auto item = new te::mem::DataSetItem(dsOut.get());
    item->setGeometry(0, dynamic_cast<te::gm::Geometry*>(occurrenceAggregation->buffer->clone()));
    item->setDouble(1, getOperationResult(cache, aggregationStatisticOperation));
    dsOut->add(item);
  }


  return dsOut;

}
Beispiel #9
0
 string SockAddr::toString(bool includePort) const {
     string out = getAddr();
     if (includePort && getType() != AF_UNIX && getType() != AF_UNSPEC)
         out += mongoutils::str::stream() << ':' << getPort();
     return out;
 }