Exemplo n.º 1
0
void modCalcAzel::slotComputeCoords()
{
	SkyPoint sp;
	double epoch0 = getEpoch( epochName->text() );
	KStarsDateTime dt;
	dt.setFromEpoch( epoch0 );
	long double jd = getDateTime().djd();
	long double jd0 = dt.djd();

	dms LST( getDateTime().gst().Degrees() + getLongitude().Degrees() );

	if(radioApCoords->isChecked()) {
		sp = getEquCoords();
		sp.apparentCoord(jd0, jd);
		dms lat(getLatitude());
		sp.EquatorialToHorizontal( &LST, &lat );
		showHorCoords( sp );

	} else {
		sp = getHorCoords();
		dms lat(getLatitude());
		sp.HorizontalToEquatorial( &LST, &lat );
		showEquCoords( sp );
	}

}
Exemplo n.º 2
0
 v8::Handle<v8::Array> js_to_array() const {
     v8::HandleScope scope;
     v8::Local<v8::Array> array = v8::Array::New(2);
     array->Set(0, v8::Number::New(lon()));
     array->Set(1, v8::Number::New(lat()));
     return scope.Close(array);
 }
Exemplo n.º 3
0
void MarblePhysics::updateProgress(qreal progress)
{
    Q_ASSERT(d->m_mode != Instant);
    Q_ASSERT(d->m_mode != Automatic);

    if (progress >= 1.0)
    {
        d->m_presenter->flyTo( d->m_target, Instant );
        d->m_presenter->setViewContext( Marble::Still );
        return;
    }

    Q_ASSERT(progress >= 0.0 && progress < 1.0);
    qreal lon(0.0), lat(0.0);
    d->suggestedPos(progress, lon, lat);
    qreal range = d->suggestedRange(progress);

    GeoDataLookAt intermediate;
    intermediate.setLongitude(lon, GeoDataCoordinates::Radian);
    intermediate.setLatitude(lat, GeoDataCoordinates::Radian);
    intermediate.setAltitude(0.0);
    intermediate.setRange(range);

    d->m_presenter->setViewContext( Marble::Animation );
    d->m_presenter->flyTo( intermediate, Instant );
}
Exemplo n.º 4
0
NOXREF void CCSBot::MoveAwayFromPosition(const Vector *pos)
{
	// compute our current forward and lateral vectors
	float angle = pev->v_angle[ YAW ];

	Vector2D dir(BotCOS(angle), BotSIN(angle));
	Vector2D lat(-dir.y, dir.x);

	// compute unit vector to goal position
	Vector2D to(pos->x - pev->origin.x, pos->y - pev->origin.y);
	to.NormalizeInPlace();

	// move away from the position independant of our view direction
	float toProj = to.x * dir.x + to.y * dir.y;
	float latProj = to.x * lat.x + to.y * lat.y;

	const float c = 0.5f;
	if (toProj > c)
		MoveBackward();
	else if (toProj < -c)
		MoveForward();

	if (latProj >= c)
		StrafeRight();
	else if (latProj <= -c)
		StrafeLeft();
}
Exemplo n.º 5
0
double run_soft_sphere(double reduced_density, double temp) {
  Functional f = SoftFluid(sigma, 1, 0);
  const double mu = find_chemical_potential(OfEffectivePotential(f), temp, reduced_density*pow(2,-5.0/2.0));
  printf("mu is %g for reduced_density = %g at temperature %g\n", mu, reduced_density, temp);

  //printf("Filling fraction is %g with functional %s at temperature %g\n", reduced_density, teff);
  //fflush(stdout);
  temperature = temp;
  //if (kT == 0) kT = ;1

  Lattice lat(Cartesian(xmax,0,0), Cartesian(0,ymax,0), Cartesian(0,0,zmax));
  GridDescription gd(lat, dx);

  Grid softspherepotential(gd);
  softspherepotential.Set(soft_sphere_potential);

  f = SoftFluid(sigma, 1, mu); // compute approximate energy with chemical potential mu
  const double approx_energy = f(temperature, reduced_density*pow(2,-5.0/2.0))*xmax*ymax*zmax;
  const double precision = fabs(approx_energy*1e-9);

  f = OfEffectivePotential(SoftFluid(sigma, 1, mu) + ExternalPotential(softspherepotential));

  static Grid *potential = 0;
  potential = new Grid(gd);
  *potential = softspherepotential - temperature*log(reduced_density*pow(2,-5.0/2.0)/(1.0*radius*radius*radius))*VectorXd::Ones(gd.NxNyNz); // Bad starting guess
  printf("\tMinimizing to %g absolute precision from %g from %g...\n", precision, approx_energy, temperature);
  fflush(stdout);

  Minimizer min = Precision(precision,
                            PreconditionedConjugateGradient(f, gd, temperature,
                                potential,
                                QuadraticLineMinimizer));
  took("Setting up the variables");
  for (int i=0; min.improve_energy(true) && i<100; i++) {
  }

  took("Doing the minimization");
  min.print_info();

  Grid density(gd, EffectivePotentialToDensity()(temperature, gd, *potential));
  //printf("# per area is %g at filling fraction %g\n", density.sum()*gd.dvolume/dw/dw, reduced_density);

  char *plotname = (char *)malloc(1024);

  sprintf(plotname, "papers/fuzzy-fmt/figs/radial-wca-%06.4f-%04.2f.dat", temp, reduced_density);
  z_plot(plotname, Grid(gd, pow(2,5.0/2.0)*density));
  free(plotname);

  {
    //double peak = peak_memory()/1024.0/1024;
    //double current = current_memory()/1024.0/1024;
    //printf("Peak memory use is %g M (current is %g M)\n", peak, current);

  }

  took("Plotting stuff");
  printf("density %g gives ff %g for reduced_density = %g and T = %g\n", density(0,0,gd.Nz/2),
         density(0,0,gd.Nz/2)*4*M_PI/3, reduced_density, temp);
  return density(0, 0, gd.Nz/2)*4*M_PI/3; // return bulk filling fraction
}
Exemplo n.º 6
0
bool CHostageImprov::FaceTowards(const Vector &target, float deltaT)
{
	bool bError = false;
	Vector2D to = (target - GetFeet()).Make2D();

#ifndef PLAY_GAMEDLL
	to.NormalizeInPlace();
#else
	// TODO: fix test demo
	float_precision float_x = target.x - GetFeet().x;
	float_precision float_y = target.y - GetFeet().y;
	float_precision flLen = to.Length();

	if (flLen <= 0)
	{
		to.x = 1;
		to.y = 0;
	}
	else
	{
		to.x = float_x / flLen;
		to.y = float_y / flLen;
	}
#endif

	float moveAngle = GetMoveAngle();

	Vector2D lat(BotCOS(moveAngle), BotSIN(moveAngle));
	Vector2D dir(-lat.y, lat.x);

	float_precision dot = DotProduct(to, dir);

	if (DotProduct(to, lat) < 0.0f)
	{
		if (dot >= 0.0f)
			dot = 1.0f;
		else
			dot = -1.0f;

		bError = true;
	}

	const float maxTurnRate = 0.05f;

	if (bError || Q_fabs(dot) >= maxTurnRate)
	{
		const float tolerance = 300.0f;
		float moveRatio = dot * deltaT * tolerance + moveAngle;

		BotCOS(moveRatio);
		BotSIN(moveRatio);

		m_moveAngle = moveRatio;
		m_hostage->pev->angles.y = moveRatio;

		return false;
	}

	return true;
}
Exemplo n.º 7
0
bool RoutingLayerPrivate::handleMouseButtonRelease( QMouseEvent *e )
{
    if ( e->button() != Qt::LeftButton ) {
        return false;
    }

    if ( m_movingIndex >= 0 ) {
        m_movingIndex = -1;
        clearStopOver();
        m_marbleWidget->model()->routingManager()->retrieveRoute();
        return true;
    }

    if ( !m_dropStopOver.isNull() && !m_dragStopOver.isNull() ) {
        QPoint moved = e->pos() - m_dragStopOver;
        if ( moved.manhattanLength() < 10 ) {
            return false;
        }

        qreal lon( 0.0 ), lat( 0.0 );
        if ( m_dragStopOverRightIndex >= 0 && m_dragStopOverRightIndex <= m_routeRequest->size()
                && m_marbleWidget->geoCoordinates( m_dropStopOver.x(), m_dropStopOver.y(), lon, lat, GeoDataCoordinates::Radian ) ) {
            GeoDataCoordinates position( lon, lat );
            m_dragStopOverRightIndex = viaInsertPosition( e->modifiers() );
            m_routeRequest->insert( m_dragStopOverRightIndex, position );
            clearStopOver();
            m_marbleWidget->model()->routingManager()->retrieveRoute();
            return true;
        }
    }

    return false;
}
Exemplo n.º 8
0
void test_energy(const char *name, Functional f, double kT,
                 double true_energy, double fraccuracy = 1e-15) {
  printf("\n************");
  for (unsigned i=0;i<strlen(name);i++) printf("*");
  printf("\n* Testing %s *\n", name);
  for (unsigned i=0;i<strlen(name);i++) printf("*");
  printf("************\n\n");

  Lattice lat(Cartesian(0,.5,.5), Cartesian(.5,0,.5), Cartesian(.5,.5,0));
  int resolution = 20;
  GridDescription gd(lat, resolution, resolution, resolution);
  Grid density(gd);
  density = 1e-3*(-500*r2(gd)).cwise().exp()
    + 1e-7*VectorXd::Ones(gd.NxNyNz);

  retval += f.run_finite_difference_test(name, kT, density);

  double e = f.integral(kT, density);
  printf("Energy = %.16g\n", e);
  printf("Fractional error = %g\n", (e - true_energy)/fabs(true_energy));
  if (e < true_energy) {
    printf("FAIL: the energy is too low! (it is %.16g)\n", e);
    retval++;
  }
  if (!(fabs((e - true_energy)/true_energy) < fraccuracy)) {
    printf("FAIL: Error in the energy is too big!\n");
    retval++;
  }
}
Exemplo n.º 9
0
void SandPile::caluclateClusterdata(int point,int &time, int &size, int &distance) {
	std::vector<int> critical(nrOfElements);
	std::vector<int> lat(getLattice());
	lat[point] ++;
	testCritical(point,lat,critical,0,time, size);
	distance = 0;
	double curDistance = 0;

	int koord1[dimension];
	int koord2[dimension];
	coord(dimension,sidelength,point,koord1);
	for(int i=0;i<nrOfElements;i++){
		if(critical[i]==1){
			coord(dimension,sidelength,i,koord2);
			curDistance = radius(dimension,koord1,koord2);
			if(curDistance >distance) distance = curDistance;
		}
	}
//	std::cout   << "\t" << "SandPile:: calculate Clusterdata" << "\t"
//				<< time << "\t"
//				<< size << "\t"
//				<< distance << "\t"
//				<< "\n";

}
Exemplo n.º 10
0
void SandPile::caluclateDissipationdata(int point,std::vector<int> &dissipationRate) {
//int point,std::vector<int> &lat,std::vector<int> &critical, int timesteps, int &timestepsMax, int &size, std::vector<int> dissipationRate
	std::vector<int> critical(nrOfElements);
	std::vector<int> lat(getLattice());
	lat[point] += 1;
	int size = 0;
	int timeMax = 0;
	testDissipation(point,lat,critical,0,timeMax, size,dissipationRate);

//	coutLattice2d(critical);

//	int koord1[dimension];
//	int koord2[dimension];
//	coord(dimension,sidelength,point,koord1);
//	for(int i=0;i<nrOfElements;i++){
//		if(critical[i]==1){
//			coord(dimension,sidelength,i,koord2);
//			curDistance = radius(dimension,koord1,koord2);
//			if(curDistance >distance) distance = curDistance;
//		}
//	}

//	std::cout   << "\t" << "SandPile:: calculate Clusterdata" << "\t"
//				<< time << "\t"
//				<< size << "\t"
//				<< distance << "\t"
//				<< "\n";

}
void
NIImporter_OpenStreetMap::NodesHandler::myStartElement(int element, const SUMOSAXAttributes& attrs) {
    ++myHierarchyLevel;
    if (element == SUMO_TAG_NODE) {
        bool ok = true;
        if (myHierarchyLevel != 2) {
            WRITE_ERROR("Node element on wrong XML hierarchy level (id='" + toString(attrs.getIntReporting(SUMO_ATTR_ID, 0, ok)) + "', level='" + toString(myHierarchyLevel) + "').");
            return;
        }
        int id = attrs.getIntReporting(SUMO_ATTR_ID, 0, ok);
        std::string action = attrs.hasAttribute("action") ? attrs.getStringSecure("action", "") : "";
        if (action == "delete") {
            return;
        }
        if (!ok) {
            return;
        }
        myLastNodeID = -1;
        if (myToFill.find(id) == myToFill.end()) {
            myLastNodeID = id;
            // assume we are loading multiple files...
            //  ... so we won't report duplicate nodes
            bool ok = true;
            double tlat, tlon;
            std::istringstream lon(attrs.getStringReporting(SUMO_ATTR_LON, toString(id).c_str(), ok));
            if (!ok) {
                return;
            }
            lon >> tlon;
            if (lon.fail()) {
                WRITE_ERROR("Node's '" + toString(id) + "' lon information is not numeric.");
                return;
            }
            std::istringstream lat(attrs.getStringReporting(SUMO_ATTR_LAT, toString(id).c_str(), ok));
            if (!ok) {
                return;
            }
            lat >> tlat;
            if (lat.fail()) {
                WRITE_ERROR("Node's '" + toString(id) + "' lat information is not numeric.");
                return;
            }
            NIOSMNode* toAdd = new NIOSMNode();
            toAdd->id = id;
            toAdd->tlsControlled = false;
            toAdd->lat = tlat;
            toAdd->lon = tlon;
            myIsInValidNodeTag = true;

            std::set<NIOSMNode*, CompareNodes>::iterator similarNode = myUniqueNodes.find(toAdd);
            if (similarNode == myUniqueNodes.end()) {
                myUniqueNodes.insert(toAdd);
            } else {
                delete toAdd;
                toAdd = *similarNode; 
                WRITE_MESSAGE("Found duplicate nodes. Substituting " + toString(id) + " with " + toString(toAdd->id));
            }
            myToFill[id] = toAdd;
        }
Exemplo n.º 12
0
int main(int, char **) {
  FILE *o = fopen("paper/figs/constrained-water.dat", "w");

  Functional f = OfEffectivePotential(SaftFluidSlow(water_prop.lengthscale,
                                                    water_prop.epsilonAB, water_prop.kappaAB,
                                                    water_prop.epsilon_dispersion,
                                                    water_prop.lambda_dispersion, water_prop.length_scaling, 0));
  double mu_satp = find_chemical_potential(f, water_prop.kT,
                                           water_prop.liquid_density);
  Lattice lat(Cartesian(width,0,0), Cartesian(0,width,0), Cartesian(0,0,zmax));
  GridDescription gd(lat, 0.1);

  Grid potential(gd);
  Grid constraint(gd);
  constraint.Set(notinwall);

  f = constrain(constraint,
                OfEffectivePotential(SaftFluidSlow(water_prop.lengthscale,
                                                   water_prop.epsilonAB, water_prop.kappaAB,
                                                   water_prop.epsilon_dispersion,
                                                   water_prop.lambda_dispersion, water_prop.length_scaling, mu_satp)));


  Minimizer min = Precision(0, PreconditionedConjugateGradient(f, gd, water_prop.kT, &potential,
                                                               QuadraticLineMinimizer));

  potential = water_prop.liquid_density*constraint
    + water_prop.vapor_density*VectorXd::Ones(gd.NxNyNz);
  //potential = water_prop.liquid_density*VectorXd::Ones(gd.NxNyNz);
  potential = -water_prop.kT*potential.cwise().log();

  const int numiters = 50;
  for (int i=0;i<numiters && min.improve_energy(true);i++) {
    fflush(stdout);
    Grid density(gd, EffectivePotentialToDensity()(water_prop.kT, gd, potential));
    density.epsNative1d("paper/figs/1d-constrained-plot.eps",
			Cartesian(0,0,0), Cartesian(0,0,zmax),
			water_prop.liquid_density, 1, "Y axis: , x axis: ");
  }
  min.print_info();

  double energy = min.energy()/width/width;
  printf("Energy is %.15g\n", energy);

  double N = 0;
  {
    Grid density(gd, EffectivePotentialToDensity()(water_prop.kT, gd, potential));
    for (int i=0;i<gd.NxNyNz;i++) N += density[i]*gd.dvolume;
  }
  N = N/width/width;
  printf("N is %.15g\n", N);

    Grid density(gd, EffectivePotentialToDensity()(water_prop.kT, gd, potential));
    density.epsNative1d("paper/figs/1d-constrained-plot.eps", Cartesian(0,0,0), Cartesian(0,0,zmax), water_prop.liquid_density, 1, "Y axis: , x axis: ");
    //potential.epsNative1d("hard-wall-potential.eps", Cartesian(0,0,0), Cartesian(0,0,zmax), 1, 1);

    fclose(o);
}
Exemplo n.º 13
0
void Evnav::write(QVector<Edge> &path, QJsonObject &json)
{
    // by convention with osrm
    QJsonObject summary;
    QJsonArray charging_steps;

    double total_energy = 0;
    double total_charge_time = 0;
    double total_travel_time = 0;
    double total_distance = 0;

    for (int i = 0; i < path.size(); i++) {
        Edge &e = path[i];
        // FIXME: overload operator+=
        total_energy += e.m_energy;
        total_charge_time += e.m_charge_time;
        total_travel_time += e.m_travel_time;
        total_distance += e.m_dist;
    }

    for (int i = 0; i < path.size() - 1; i++) {
        Edge &e = path[i];
        Charger charger = m_provider->charger(e.to());
        QJsonArray loc;
        // I would rather do: charger.loc().lon().toFloat();
        QJsonValue lon((double)util::toFloating(charger.loc().lon));
        QJsonValue lat((double)util::toFloating(charger.loc().lat));
        loc.append(lon);
        loc.append(lat);

        QJsonObject step;
        step["name"] = charger.name();
        step["location"] = loc;

        // we charge for the next leg
        step["energy"] = path[i + 1].m_energy;
        step["charging_duration"] = path[i + 1].m_charge_time;
        step["charging_cost"] = (path[i + 1].m_charge_time / 3600.0) * 10.0; // 10 $/h

        charging_steps.append(step);
    }

    double total_cost = ((total_charge_time / 3600.0) * 10.0);

    json["code"] = "Ok";
    json["message"] = "reachable";
    summary["distance"] = total_distance;
    summary["duration"] = total_charge_time + total_travel_time;
    summary["energy"] = total_energy;
    summary["driving_duration"] = total_travel_time;
    summary["charging_duration"] = total_charge_time;
    summary["charging_cost"] = total_cost;
    json["route_summary"] = summary;
    json["charging_steps"] = charging_steps;

    return;
}
void IqHelpViewerMainWindow::rusificateFindString()
{
    if (m_rusLocaleButton->isChecked()) {
        m_findStringLineEdit->setText(rus(m_findStringLineEdit->text()));
    }
    else {
        m_findStringLineEdit->setText(lat(m_findStringLineEdit->text()));
    }
}
Exemplo n.º 15
0
void RoutingInputWidget::setHomePosition()
{
    qreal lon( 0.0 ), lat( 0.0 );
    int zoom( 0 );
    d->m_marbleModel->home( lon, lat, zoom );
    GeoDataCoordinates home( lon, lat, 0.0, GeoDataCoordinates::Degree );
    setTargetPosition( home );
    requestActivity();
}
Exemplo n.º 16
0
bool RoutingLayerPrivate::handleMouseMove( QMouseEvent *e )
{
    if ( m_pointSelection ) {
        m_marbleWidget->setCursor( Qt::CrossCursor );
        return true;
    }

    if ( !m_routingModel ) {
        return false;
    }

    qreal lon( 0.0 ), lat( 0.0 );
    if ( m_marbleWidget->geoCoordinates( e->pos().x(), e->pos().y(),
                                         lon, lat, GeoDataCoordinates::Radian ) ) {

        if ( m_movingIndex >= 0 ) {
            GeoDataCoordinates moved( lon, lat );
            m_routeRequest->setPosition( m_movingIndex, moved );
            m_marbleWidget->setCursor( Qt::ArrowCursor );
        } else if ( !m_dragStopOver.isNull() ) {
            // Repaint only that region of the map that is affected by the change
            m_dragStopOverRightIndex = viaInsertPosition( e->modifiers() );
            QRect dirty = m_routeRegion.boundingRect();
            dirty |= QRect( m_dropStopOver, m_pixmapSize );
            dirty |= QRect( e->pos(), m_pixmapSize );
            if ( e->buttons() & Qt::LeftButton ) {
                m_dropStopOver = e->pos();
            } else {
                m_dragStopOver = QPoint();
                m_dropStopOver = QPoint();
            }
            m_marbleWidget->update( dirty );
            m_marbleWidget->setCursor( Qt::ArrowCursor );
        } else if ( isInfoPoint( e->pos() ) ) {
            clearStopOver();
            m_marbleWidget->setCursor( Qt::ArrowCursor );
        } else if ( m_routeRegion.contains( e->pos() ) ) {
            m_dropStopOver = e->pos();
            m_marbleWidget->setCursor( Qt::ArrowCursor );
        } else if ( !m_dropStopOver.isNull() ) {
            clearStopOver();
        } else if ( isAlternativeRoutePoint( e->pos() ) ) {
            m_marbleWidget->setCursor( Qt::ArrowCursor );
        }
        else {
            return false;
        }

        // Update pixmap in the map (old and new position needs repaint)
        paintStopOver( QRect( e->pos(), m_pixmapSize ) );
        return true;
    }

    return false;
}
Exemplo n.º 17
0
void RoutingLayerPrivate::storeDragPosition( const QPoint &pos )
{
    m_dragStopOver = pos;
    m_dragStopOverRightIndex = -1;

    qreal lon( 0.0 ), lat( 0.0 );
    if ( m_routeRequest && !pos.isNull()
        && m_marbleWidget->geoCoordinates( pos.x(), pos.y(), lon, lat, GeoDataCoordinates::Radian ) ) {
        GeoDataCoordinates waypoint( lon, lat );
        m_dragStopOverRightIndex = m_routingModel->rightNeighbor( waypoint, m_routeRequest );
    }
}
Exemplo n.º 18
0
void AlgFourierProp::run()
{
  char *fname = "run()";
  VRB.Func(cname,fname);

  //----------------------------------------------------------------
  // Set the Lattice pointer
  //----------------------------------------------------------------

  Lattice& lat( AlgLattice() );

  //----------------------------------------------------------------
  // set the variables
  //----------------------------------------------------------------

  QPropWArg qarg;
  qarg.cg = alg_FourierProp_arg->cg;
  qarg.x  = alg_FourierProp_arg->x_src;
  qarg.y  = alg_FourierProp_arg->y_src;
  qarg.z  = alg_FourierProp_arg->z_src;
  qarg.t  = alg_FourierProp_arg->t_src;
  qarg.gauge_fix_snk  = 1;
  
  //----------------------------------------------------------------
  // Fetch propagator
  //----------------------------------------------------------------
  
  QPropWGFPointSrc prop0( lat, &qarg, common_arg );
  
  prop0.Run();

  //----------------------------------------------------------------
  // set current propagator
  //----------------------------------------------------------------

  prop=&prop0;
  
  //----------------------------------------------------------------
  // output header. 
  //----------------------------------------------------------------
  
  FILE* fp(NULL);
  
  if( (fp = Fopen((char *)alg_FourierProp_arg->results, "a")) == NULL ) {
    ERR.FileA(cname,fname, (char *)alg_FourierProp_arg->results);
  }
  print_header(fp,"AlgFourierProp");
  
  ft(fp,alg_FourierProp_arg->plist);
  
  Fclose(fp);
}
Exemplo n.º 19
0
double run_walls(double reduced_density, const char *name, Functional fhs, double teff) {
  double kT = teff;
  if (kT == 0) kT = 1;

  Functional f = OfEffectivePotential(fhs);

  const double zmax = width + 2*spacing;
  Lattice lat(Cartesian(dw,0,0), Cartesian(0,dw,0), Cartesian(0,0,zmax));
  GridDescription gd(lat, dx);

  Grid constraint(gd);
  constraint.Set(notinwall);
  f = constrain(constraint, f);

  Grid potential(gd);
  potential = pow(2,-5.0/2.0)*(reduced_density*constraint + 1e-4*reduced_density*VectorXd::Ones(gd.NxNyNz));
  potential = -kT*potential.cwise().log();

  const double approx_energy = fhs(kT, reduced_density*pow(2,-5.0/2.0))*dw*dw*width;
  const double precision = fabs(approx_energy*1e-11);
  printf("\tMinimizing to %g absolute precision from %g from %g...\n", precision, approx_energy, kT);
  fflush(stdout);

  Minimizer min = Precision(precision,
                            PreconditionedConjugateGradient(f, gd, kT,
                                                            &potential,
                                                            QuadraticLineMinimizer));
  took("Setting up the variables");
  if (strcmp(name, "hard") != 0 && false) {
    printf("For now, SoftFluid doesn't work properly, so we're skipping the\n");
    printf("minimization at temperature %g.\n", teff);
  } else {
    for (int i=0;min.improve_energy(false) && i<100;i++) {
    }
  }
  took("Doing the minimization");
  min.print_info();

  Grid density(gd, EffectivePotentialToDensity()(kT, gd, potential));
  //printf("# per area is %g at filling fraction %g\n", density.sum()*gd.dvolume/dw/dw, eta);

  char *plotname = (char *)malloc(1024);

  sprintf(plotname, "papers/fuzzy-fmt/figs/walls%s-%06.4f-%04.2f.dat", name, teff, reduced_density);
  z_plot(plotname, Grid(gd, density*pow(2,5.0/2.0)));
  free(plotname);

  took("Plotting stuff");
  printf("density %g gives ff %g for reduced density = %g and T = %g\n", density(0,0,gd.Nz/2),
         density(0,0,gd.Nz/2)*4*M_PI/3, reduced_density, teff);
  return density(0, 0, gd.Nz/2)*4*M_PI/3; // return bulk filling fraction
}
Exemplo n.º 20
0
void ParameterFile::recomputeTree() const {
   vec2 lats, lons;
   LocationParameters::const_iterator it = mParameters.begin();
   for(it = mParameters.begin(); it != mParameters.end(); it++) {
      const Location loc = it->first;
      std::vector<float> lat(1, loc.lat());
      std::vector<float> lon(1, loc.lon());
      lats.push_back(lat);
      lons.push_back(lon);
      mLocations.push_back(loc);
   }
   mNearestNeighbourTree.build(lats, lons);
}
Exemplo n.º 21
0
void
ItemSerializer::toJson(std::ostream& out, const sserialize::Static::spatial::GeoShape& gs) const
{
	sserialize::spatial::GeoShapeType gst = gs.type();
	out << "{\"t\":" << gst << ",\"v\":";
	switch(gst) {
	case sserialize::spatial::GS_POINT:
		{
			auto gp = gs.get<sserialize::spatial::GS_POINT>();
			out << "[" << gp->lat() << "," << gp->lon() << "]";
		}
		break;
	case sserialize::spatial::GS_WAY:
	case sserialize::spatial::GS_POLYGON:
		{
			auto gw = gs.get<sserialize::spatial::GS_WAY>();
			out << "[";
			if (gw->size()) {
				auto it(gw->cbegin()), end(gw->cend());
				sserialize::Static::spatial::GeoPoint gp(*it);
				out << "[" << gp.lat() << "," << gp.lon() << "]";
				for(++it; it != end; ++it) {
					gp = *it;
					out << ",[" << gp.lat() << "," << gp.lon() << "]";
				}
			}
			out << "]";
		}
		break;
	case sserialize::spatial::GS_MULTI_POLYGON:
		{
			out << "{";
			auto gmw = gs.get<sserialize::spatial::GS_MULTI_POLYGON>();
			if (gmw->innerPolygons().size()) {
				out << "\"inner\":";
				toJson(out, gmw->innerPolygons());
				out << ",";
			}
			out << "\"outer\":";
			toJson(out, gmw->outerPolygons());
			out << "}";
		}
		break;
	default:
		break;
	}
	out << "}";
}
Exemplo n.º 22
0
int main() {
  YQLSettings settings;
  InputSmhiPmp input;
  std::cout << (int) offsetof(InputSmhiPmp,inputSmhiPmpLat) << std::endl;
  std::cout << (int) offsetof(InputSmhiPmp,inputSmhiPmpLon) << std::endl;
  std::string lat("58.59");
  std::string lon("16.18"); 
  input.inputSmhiPmpLat = &lat[0];
  input.inputSmhiPmpLon = &lon[0];
  Maybe<OutputSmhiPmp>* output = smhiPmp(&settings, &input);
  if (output->just) {
    OutputSmhiPmp* data = output->data;
    char* referenceTime = data->outputSmhiPmpReferenceTime;
    std::cout << referenceTime << std::endl;
  }
}
Exemplo n.º 23
0
QVariant TargetModel::homeData ( int role ) const
{
    switch( role ) {
    case Qt::DisplayRole: return tr( "Home" );
    case Qt::DecorationRole: return QIcon( ":/icons/go-home.png" );
    case MarblePlacemarkModel::CoordinateRole: {
        qreal lon( 0.0 ), lat( 0.0 );
        int zoom( 0 );
        m_marbleModel->home( lon, lat, zoom );
        const GeoDataCoordinates coordinates = GeoDataCoordinates( lon, lat, 0, GeoDataCoordinates::Degree );
        return qVariantFromValue( coordinates );
    }
    }

    return QVariant();
}
Exemplo n.º 24
0
void ossimNitfBlockaTag::converLocStringToPt(const ossimString& locationString,
                                             ossimDpt& pt) const
{
   if (locationString.size() != 21) return;

   std::string s = locationString;
   
   std::string lat(s, 0, 10);
   std::string lon(s, 10, 11);

   if ( (lat[0] == 'N') || (lat[0] == 'S') )
   {
      // Need to enter spaces for ossimDms to parse correctly
      std::ostringstream latStream;
      latStream << lat.substr(0, 3) << " " << lat.substr(3, 2)
                << " " << lat.substr(5);
      lat = latStream.str();
      
      // Use the dms class to parse.
      ossimDms dms(0.0, true);
      dms.setDegrees(lat.c_str());
      pt.y = dms.getDegrees();
   }
   else
   {
      ossimString os = lat;
      pt.y = os.toDouble();
   }
   if ( (lon[0] == 'E') || (lon[0] == 'W') )
   {
      // Need to enter spaces for ossimDms to parse correctly
      std::ostringstream lonStream;
      lonStream << lon.substr(0, 4) << " " << lon.substr(4, 2)
                << " " << lon.substr(6);
      lon = lonStream.str();
      
      // Use the dms class to parse.
      ossimDms dms(0.0, false);
      dms.setDegrees(lon.c_str());
      pt.x = dms.getDegrees();
   }
   else
   {
      ossimString os = lon;
      pt.x = os.toDouble();
   }
}
Exemplo n.º 25
0
void CCSBot::StrafeAwayFromPosition(const Vector *pos)
{
	// compute our current forward and lateral vectors
	float angle = pev->v_angle[ YAW ];

	Vector2D dir(BotCOS(angle), BotSIN(angle));
	Vector2D lat(-dir.y, dir.x);

	// compute unit vector to goal position
	Vector2D to(pos->x - pev->origin.x, pos->y - pev->origin.y);
	to.NormalizeInPlace();

	float latProj = to.x * lat.x + to.y * lat.y;

	if (latProj >= 0.0f)
		StrafeRight();
	else
		StrafeLeft();
}
Exemplo n.º 26
0
int main() {
  Lattice lat(Cartesian(0,.5,.5), Cartesian(.5,0,.5), Cartesian(.5,.5,0));
  Cartesian middle(0.5,0.5,0.5);
  Relative middlerel = lat.toRelative(middle);
  Reciprocal recip(0.2,0,0);
  int resolution = 20;
  Grid foo(lat, resolution, resolution, resolution),
    bar(lat, resolution, resolution, resolution);
  foo.Set(gaussian);
  foo.epsSlice("demo.eps", Cartesian(1,0,0), Cartesian(0,1,0),
               Cartesian(-.5,-.5,.5), 150);
  foo.epsNativeSlice("native.eps", Cartesian(1,0,0), Cartesian(0,1,0),
                     Cartesian(-.5,-.5,.5));
  
  //std::cout << "and here is the foo" << (foo + 2*bar + foo.cwise()*bar);
  std::cout << "middle and middlerel are:\n"
            << middle << std::endl << middlerel << std::endl
            << lat.toCartesian(middlerel) << std::endl;
  std::cout << "middle dot recip: " << recip * middle << std::endl;
  return 0;
}
Exemplo n.º 27
0
void CHostageImprov::Wiggle()
{
	// for wiggling
	if (m_wiggleTimer.IsElapsed())
	{
		m_wiggleDirection = static_cast<NavRelativeDirType>(RANDOM_LONG(FORWARD, LEFT));
		m_wiggleTimer.Start(RANDOM_FLOAT(0.3f, 0.5f));
	}

	const float force = 15.0f;
	Vector dir(BotCOS(m_moveAngle), BotSIN(m_moveAngle), 0.0f);
	Vector lat(-dir.y, dir.x, 0.0f);

	switch (m_wiggleDirection)
	{
	case FORWARD:
		ApplyForce(dir * force);
		break;
	case BACKWARD:
		ApplyForce(dir * -force);
		break;
	case LEFT:
		ApplyForce(lat * force);
		break;
	case RIGHT:
		ApplyForce(lat * -force);
		break;
	default:
		break;
	}

	const float minStuckJumpTime = 0.5f;
	if (m_follower.GetStuckDuration() > minStuckJumpTime && m_wiggleJumpTimer.IsElapsed())
	{
		if (Jump())
		{
			m_wiggleJumpTimer.Start(RANDOM_FLOAT(0.75f, 1.2f));
		}
	}
}
Exemplo n.º 28
0
void DISPLAY::drawData(int page) {
    char s[80];
    switch(page) {
        case 0:
            if (EventCatch(EVT_PRN)) {
                sprintf(s, "%2d %3.0f", StatPRN, StatSNR);
                writeAt(4, 0, s);
            }
            if (EventCatch(EVT_BARS)) {
                setCursor(0, 1);
                for (int i=0; i<NUM_CHANS; i++) write(StatBars[i]);
            }
            break;
        case 1:
            if (EventCatch(EVT_POS)) {
                sprintf(s, "%-5d %8.5f %c", StatChans, StatLat, StatNS);
                writeAt(0, 0, s);
                sprintf(s, "%-5.0f %8.5f %c", StatAlt, StatLon, StatEW);
                writeAt(0, 1, s);
            }
            break;
        case 2:
            if (EventCatch(EVT_POS)) {
                UMS lat(StatLat), lon(StatLon);
                sprintf(s, "%2d\xDF%3d\xDF%7.3f %c", lat.u, lat.m, lat.s, StatNS);
                writeAt(0, 0, s);
                sprintf(s, "%2d\xDF%3d\xDF%7.3f %c", lon.u, lon.m, lon.s, StatEW);
                writeAt(0, 1, s);
            }
            break;
        case 3:
            if (EventCatch(EVT_TIME)) {
                UMS hms(StatSec/60/60);
                sprintf(s, "%s %02d:%02d:%02.0f", Week[StatDay], hms.u, hms.m, hms.s);
                writeAt(0, 0, s);
            }
    }
}
Exemplo n.º 29
0
bool ESHDFIonsParser::put(xmlNodePtr cur)
{
  //add basic attributes of the speciesset
  SpeciesSet& tspecies(ref_.getSpeciesSet());
  int icharge= tspecies.addAttribute("charge");//charge_tag);
  int iatnumber= tspecies.addAttribute(atomic_number_tag);
  int membersize= tspecies.addAttribute("membersize");
  int massind= tspecies.addAttribute(mass_tag);
  if(myComm->rank()==0 && hfile_id>=-1)
    readESHDF();
  if(myComm->size()==1)
    return true;
  int nspecies=tspecies.getTotalNum();
  int natoms=ref_.getTotalNum();
  ostringstream o;
  if(myComm->rank()==0)
  {
    int i=0;
    for(; i<nspecies-1; ++i)
      o<<tspecies.speciesName[i]<<",";
    o<<tspecies.speciesName[i];
  }
  TinyVector<int,3> bsizes(nspecies,natoms,o.str().size()+1);
  myComm->bcast(bsizes);
  //send the names: UGLY!!!!
  nspecies=bsizes[0];
  char *species_names=new char[bsizes[2]];
  if(myComm->rank()==0)
    snprintf(species_names, bsizes[2], "%s",o.str().c_str());
  myComm->bcast(species_names,bsizes[2]);
  if(myComm->rank())
  {
    vector<string> vlist;
    parsewords(species_names,vlist);
    for(int i=0; i<vlist.size(); ++i)
      tspecies.addSpecies(vlist[i]);
    //create natoms particles
    ref_.create(bsizes[1]);
  }
  delete [] species_names;
  ParticleSet::Tensor_t lat(ref_.Lattice.R);
  ParticleSet::Buffer_t pbuffer;
  for(int i=0; i<tspecies.numAttributes(); ++i)
    pbuffer.add(tspecies.d_attrib[i]->begin(),tspecies.d_attrib[i]->end());
  pbuffer.add(lat.begin(),lat.end());
  pbuffer.add(get_first_address(ref_.R),get_last_address(ref_.R));
  pbuffer.add(ref_.GroupID.begin(),ref_.GroupID.end());
  myComm->bcast(pbuffer);
  ref_.R.InUnit=PosUnit::CartesianUnit;
  if(myComm->rank())
  {
    pbuffer.rewind();
    for(int i=0; i<tspecies.numAttributes(); ++i)
      pbuffer.get(tspecies.d_attrib[i]->begin(),tspecies.d_attrib[i]->end());
    pbuffer.get(lat.begin(),lat.end());
    pbuffer.get(get_first_address(ref_.R),get_last_address(ref_.R));
    pbuffer.get(ref_.GroupID.begin(),ref_.GroupID.end());
    ref_.Lattice.set(lat);
  }
  return true;
}
Exemplo n.º 30
0
void CCSBot::MoveTowardsPosition(const Vector *pos)
{
	// Jump up on ledges
	// Because we may not be able to get to our goal position and enter the next
	// area because our extent collides with a nearby vertical ledge, make sure
	// we look far enough ahead to avoid this situation.
	// Can't look too far ahead, or bots will try to jump up slopes.

	// NOTE: We need to do this frequently to catch edges at the right time
	// TODO: Look ahead *along path* instead of straight line
	if ((m_lastKnownArea == NULL || !(m_lastKnownArea->GetAttributes() & NAV_NO_JUMP)) &&
		!IsOnLadder() && !m_isJumpCrouching)
	{
		float ground;
		Vector aheadRay(pos->x - pev->origin.x, pos->y - pev->origin.y, 0);
		aheadRay.NormalizeInPlace();

		// look far ahead to allow us to smoothly jump over gaps, ledges, etc
		// only jump if ground is flat at lookahead spot to avoid jumping up slopes
		bool jumped = false;

		if (IsRunning())
		{
			const float farLookAheadRange = 80.0f;
			Vector normal;
			Vector stepAhead = pev->origin + farLookAheadRange * aheadRay;
			stepAhead.z += HalfHumanHeight;

			if (GetSimpleGroundHeightWithFloor(&stepAhead, &ground, &normal))
			{
				if (normal.z > 0.9f)
					jumped = DiscontinuityJump(ground, ONLY_JUMP_DOWN);
			}
		}

		if (!jumped)
		{
			// close up jumping
			// cant be less or will miss jumps over low walls
			const float lookAheadRange = 30.0f;
			Vector stepAhead = pev->origin + lookAheadRange * aheadRay;
			stepAhead.z += HalfHumanHeight;

			if (GetSimpleGroundHeightWithFloor(&stepAhead, &ground))
			{
				jumped = DiscontinuityJump(ground);
			}
		}

		if (!jumped)
		{
			// about to fall gap-jumping
			const float lookAheadRange = 10.0f;
			Vector stepAhead = pev->origin + lookAheadRange * aheadRay;
			stepAhead.z += HalfHumanHeight;

			if (GetSimpleGroundHeightWithFloor(&stepAhead, &ground))
			{
				jumped = DiscontinuityJump(ground, ONLY_JUMP_DOWN, MUST_JUMP);
			}
		}
	}

	// compute our current forward and lateral vectors
	float angle = pev->v_angle.y;

	Vector2D dir(BotCOS(angle), BotSIN(angle));
	Vector2D lat(-dir.y, dir.x);

	// compute unit vector to goal position
	Vector2D to(pos->x - pev->origin.x, pos->y - pev->origin.y);
	to.NormalizeInPlace();

	// move towards the position independant of our view direction
	float toProj = to.x * dir.x + to.y * dir.y;
	float latProj = to.x * lat.x + to.y * lat.y;

	const float c = 0.25f;
	if (toProj > c)
		MoveForward();
	else if (toProj < -c)
		MoveBackward();

	// if we are avoiding someone via strafing, don't override
	if (m_avoid != NULL)
		return;

	if (latProj >= c)
		StrafeLeft();
	else if (latProj <= -c)
		StrafeRight();
}