Exemplo n.º 1
0
int judge(db d, int r0, int r1)
{
    if (eps(d - r0 - r1) >= 0) return -1;
    if (eps(d + r1 - r0) <= 0) return 0;
    if (eps(d + r0 - r1) <= 0) return 1;
    return 2;
}
Exemplo n.º 2
0
int
TimoshenkoSection3d::setTrialSectionDeformation (const Vector &deforms)
{
  int res = 0;
  e = deforms;

  kData[0] = 0.0; kData[1] = 0.0; kData[2] = 0.0; kData[3] = 0.0;
  kData[4] = 0.0; kData[5] = 0.0; kData[6] = 0.0; kData[7] = 0.0;
  kData[8] = 0.0; 
  sData[0] = 0.0; sData[1] = 0.0;  sData[2] = 0.0; 

  int loc = 0;

  double d0 = deforms(0);
  double d1 = deforms(1);
  double d2 = deforms(2);

  for (int i = 0; i < numFibers; i++) {
    NDMaterial *theMat = theMaterials[i];
    double y = matData[loc++] - yBar;
    double z = matData[loc++] - zBar;
    double A = matData[loc++];

    // determine material strain and set it
    double strain = d0 + y*d1 + z*d2;

    Vector eps(3);
    eps(0) = strain;
    res = theMat->setTrialStrain(eps);

    const Vector &stress = theMat->getStress();
    const Matrix &tangent = theMat->getTangent();

    double value = tangent(0,0) * A;
    double vas1 = y*value;
    double vas2 = z*value;
    double vas1as2 = vas1*z;

    kData[0] += value;
    kData[1] += vas1;
    kData[2] += vas2;
    
    kData[4] += vas1 * y;
    kData[5] += vas1as2;
    
    kData[8] += vas2 * z; 

    double fs0 = stress(0) * A;

    sData[0] += fs0;
    sData[1] += fs0 * y;
    sData[2] += fs0 * z;
  }

  kData[3] = kData[1];
  kData[6] = kData[2];
  kData[7] = kData[5];

  return res;
}
Exemplo n.º 3
0
wkt_multi_generator<OutputIterator, GeometryContainer>::wkt_multi_generator()
    : wkt_multi_generator::base_type(wkt)
{
    boost::spirit::karma::lit_type lit;
    boost::spirit::karma::eps_type eps;
    boost::spirit::karma::_val_type _val;
    boost::spirit::karma::_1_type _1;
    boost::spirit::karma::_a_type _a;

    geometry_types.add
        (mapnik::geometry_type::types::Point,"Point")
        (mapnik::geometry_type::types::LineString,"LineString")
        (mapnik::geometry_type::types::Polygon,"Polygon")
        ;

    wkt =  eps(phoenix::at_c<1>(_a))[_a = _multi_type(_val)]
        << lit("GeometryCollection(") << geometry << lit(")")
        | eps(is_multi(_val)) << lit("Multi") << geometry_types[_1 = phoenix::at_c<0>(_a)]
        << "(" << multi_geometry << ")"
        |  geometry
        ;

    geometry =  -(single_geometry % lit(','))
        ;

    single_geometry = geometry_types[_1 = _type(_val)] << path
        ;

    multi_geometry = -(path % lit(','))
        ;

}
Exemplo n.º 4
0
bool FractureElasticNorm::evalInt (LocalIntegral& elmInt,
                                   const FiniteElement& fe,
                                   const Vec3& X) const
{
  FractureElasticityVoigt& p = static_cast<FractureElasticityVoigt&>(myProblem);
  ElmNorm&             pnorm = static_cast<ElmNorm&>(elmInt);

  // Evaluate the symmetric strain tensor, eps
  Matrix Bmat;
  SymmTensor eps(p.getNoSpaceDim());
  if (!p.kinematics(elmInt.vec.front(),fe.N,fe.dNdX,0.0,Bmat,eps,eps))
    return false;
  else if (!eps.isZero(1.0e-16))
    // Scale the shear strain components by 0.5 to convert from engineering
    // strains gamma_ij = eps_ij + eps_ji to the tensor components eps_ij
    // which are needed for consistent calculation of principal directions
    for (unsigned short int i = 1; i <= eps.dim(); i++)
      for (unsigned short int j = i+1; j <= eps.dim(); j++)
        eps(i,j) *= 0.5;

  // Evaluate the material parameters at this point
  double lambda, mu;
  if (!p.material->evaluate(lambda,mu,fe,X))
    return false;

  bool printElm = fe.iel == dbgElm;
  if (printElm)
    std::cout <<"\nFractureElasticNorm::evalInt: iel,ip,X = "
              << fe.iel <<" "<< fe.iGP <<" "<< X << std::endl;

  // Evaluate the strain energy at this point
  double Phi[4];
  double Gc = p.getStressDegradation(fe.N,elmInt.vec);
  if (!p.evalStress(lambda,mu,Gc,eps,Phi,nullptr,nullptr,true,printElm))
    return false;

  // Integrate the total elastic energy
  pnorm[0] += Phi[2]*fe.detJxW;

  if (p.haveLoads())
  {
    // Evaluate the body load
    Vec3 f = p.getBodyforce(X);
    // Evaluate the displacement field
    Vec3 u = p.evalSol(pnorm.vec.front(),fe.N);
    // Integrate the external energy (f,u^h)
    pnorm[1] += f*u*fe.detJxW;
  }

  // Integrate the tensile and compressive energies
  pnorm[2] += Phi[0]*fe.detJxW;
  pnorm[3] += Phi[1]*fe.detJxW;
  // Integrate the bulk energy
  pnorm[4] += Phi[3]*fe.detJxW;

  return true;
}
Exemplo n.º 5
0
int
PermutationTensor::eps(unsigned int i, unsigned int j, unsigned int k)
{
  if (i==0 && j>0 && k>0)
    return eps(j-1, k-1);
  else if (j==0 && i>0 && k>0)
    return -eps(i-1, k-1);
  else if (k==0 && i>0 && j>0)
    return eps(i-1, j-1);
  return 0;
}
Exemplo n.º 6
0
void FourierTransformer::generate_transformer_U(const alps::params &parms,
                                                boost::shared_ptr<FourierTransformer> &fourier_ptr,
                                                const std::vector<double> &densities)
{
  int n_flavors = parms["FLAVORS"]|2;
  int n_site = parms["SITES"]|1;
  double U = parms["U"];
  if (parms.defined("GENERAL_FOURIER_TRANSFORMER")) {
    std::cout << "using general fourier transformer" << "\n";
    std::vector<std::vector<double> > eps(n_flavors);
    std::vector<std::vector<double> >epssq(n_flavors);
    for (int f=0; f<n_flavors; ++f) {
      eps[f].resize(1);
      epssq[f].resize(1);
      eps[f][0] = parms["EPS_"+boost::lexical_cast<std::string>(f)];
      epssq[f][0] = parms["EPSSQ_"+boost::lexical_cast<std::string>(f)];
    }
    fourier_ptr.reset(new GFourierTransformer((double)parms["BETA"], (double)parms["MU"]+U/2., U,
                                              n_flavors, 1, densities, eps, epssq));
  }
  else if (parms.defined("CLUSTER_LOOP")){
    std::string clusterloop=parms["CLUSTER_LOOP"];
    if(clusterloop==std::string("DCA")){
      ClusterTransformer* clusterhandler=ClusterTransformer::generate_transformer(parms);
      std::vector<std::vector<double> > eps_f(n_flavors, clusterhandler->epsav());
      std::vector<std::vector<double> > epssq_f(n_flavors, clusterhandler->epssqav());
      fourier_ptr.reset(new GFourierTransformer((double)parms["BETA"], (double)parms["MU"]+U/2., U,
                                                n_flavors, n_site, densities, eps_f, epssq_f));
      delete clusterhandler;
    }else if(clusterloop==std::string("CDMFT")){
      std::cout<<"using CDMFT cluster Fourier transformer"<<std::endl;
      std::cout<<"warning: G0 moments are not implemented for CDMFT"<<std::endl;
      std::vector<std::vector<double> > eps_f(n_flavors, std::vector<double>(n_site*n_site,0));
      std::vector<std::vector<double> > epssq_f(n_flavors, std::vector<double>(n_site*n_site,0));
      fourier_ptr.reset(new ClusterG0FourierTransformer((double)parms["BETA"], (double)parms["MU"]+U/2, U,
                                                        n_flavors, n_site, eps_f, epssq_f));
    }
    else throw std::logic_error("please figure out how to do fourier transforms in your cluster framwork if it is not DCA: "+clusterloop);
  }
  else {
    std::cout << "using Bethe lattice fourier transform" << "\n";
    std::vector<std::vector<double> > eps(n_flavors);
    std::vector<std::vector<double> >epssq(n_flavors);
    double t = parms["t"];
    for (int f=0; f<n_flavors; ++f) {
      eps[f].resize(1);
      epssq[f].resize(1);
      eps[f][0] = 0.;
      epssq[f][0] = t*t;
    }
    fourier_ptr.reset(new GFourierTransformer((double)parms["BETA"], (double)parms["MU"]+U/2., U,
                                              n_flavors, 1, densities, eps, epssq));
  }
}
Exemplo n.º 7
0
Arquivo: master.cpp Projeto: ogdf/ogdf
bool Master::check() const
{
	double optVal;

	if (!knownOptimum(optVal)) return false;

	if (optVal - eps() < primalBound() && primalBound() < optVal + eps())
		return true;
	else
		return false;
}
        /// get boundary lines of polytope
        LinesList& getPolytopeLines()
        {
            if (!_lines.empty()) return _lines;

            PlaneMask selector_mask = 0x1;
            for (PlaneList::const_iterator it=_planes.begin(); it!=_planes.end();
             ++it, selector_mask <<= 1 ) {
            const osg::Plane& plane1=*it;
            const Vec3_type normal1=plane1.getNormal();
            const Vec3_type point1=normal1*(-plane1[3]);   /// canonical point on plane1
            PlaneMask sub_selector_mask = (selector_mask<<1);
            for (PlaneList::const_iterator jt=it+1; jt!=_planes.end(); ++jt, sub_selector_mask <<= 1 ) {
                const osg::Plane& plane2=*jt;
                const Vec3_type normal2=plane2.getNormal();
                if (osg::absolute(normal1*normal2) > (1.0-eps())) continue;
                const Vec3_type lineDirection = normal1^normal2;

                const Vec3_type searchDirection = lineDirection^normal1; /// search dir in plane1
                const value_type seachDist = -plane2.distance(point1)/(searchDirection*normal2);
                if (osg::isNaN(seachDist)) continue;
                const Vec3_type linePoint=point1+searchDirection*seachDist;
                _lines.push_back(PlanesLine(selector_mask|sub_selector_mask, linePoint, lineDirection));
            }
            }
            return _lines;
        }
Exemplo n.º 9
0
inline
VectorPtr<2, T> & VectorPtr<2, T>::minimize(const const_VectorPtr<2, T> & other)
{
	int epsExp;
	int ptrExp[2];
	int dExp;
	T ptrSig[2];
	T epsilon = std::max(eps(other[0]), eps(other[1]));
	std::frexp(epsilon, & epsExp);
	ptrSig[0] = std::frexp(Parent::m_ptr[0], & ptrExp[0]);
	ptrSig[1] = std::frexp(Parent::m_ptr[1], & ptrExp[1]);
	dExp = -epsExp + std::min(ptrExp[0], ptrExp[1]);
	Parent::m_ptr[0] = std::ldexp(ptrSig[0], ptrExp[0] - dExp);
	Parent::m_ptr[1] = std::ldexp(ptrSig[1], ptrExp[1] - dExp);
	return *this;
}
Exemplo n.º 10
0
DPoint SpringEmbedderGridVariant::ForceModelBase::
computeMixedForcesDisplacement(int j, int boxLength,
                               std::function<DPoint(double, const DPoint &)> attractiveChange,
                               std::function<double()> attractiveFinal) const
{
	DPoint disp(computeRepulsiveForce(j, boxLength, 2));

	const NodeInfo &vj = m_vInfo[j];

	DPoint forceAttr(0, 0);
	DPoint forceRep(0, 0); // subtract rep. force on adjacent vertices
	for (int i = vj.m_adjBegin; i != vj.m_adjStop; ++i) {
		int u = m_adjLists[i];

		DPoint dist = vj.m_pos - m_vInfo[u].m_pos;
		double d = dist.norm();

		forceAttr -= attractiveChange(d, dist);
		if (d < boxLength) {
			double f = 1.0 / (d * d + eps());
			forceRep += f * dist;
		}
	}

	forceAttr *= attractiveFinal();
	forceRep *= m_idealEdgeLength * m_idealEdgeLength;

	disp += forceAttr - forceRep;
	return disp;
}
Exemplo n.º 11
0
DPoint SpringEmbedderGridVariant::ForceModelBase::
computeRepulsiveForce(int j, double boxLength, int idealExponent, int normExponent) const
{
	const NodeInfo &vj = m_vInfo[j];
	int grid_x = vj.m_gridX;
	int grid_y = vj.m_gridY;

	// repulsive forces on node j: F_rep(d) = iel^2 / d^normExponent
	DPoint force(0, 0);
	for (int gi = -1; gi <= 1; ++gi) {
		for (int gj = -1; gj <= 1; ++gj) {
			for (int u : m_gridCell(grid_x + gi, grid_y + gj)) {
				if (u == j) {
					continue;
				}
				DPoint dist = vj.m_pos - m_vInfo[u].m_pos;
				double d = dist.norm();

				if(d < boxLength) {
					dist /= std::pow(d, normExponent+1) + eps();
					force += dist;
				}
			}
		}
	}

	force *= std::pow(m_idealEdgeLength, idealExponent);

	return force;
}
Exemplo n.º 12
0
bool PoroElasticity::evalElasticityMatrices (ElmMats& elMat, const Matrix& B,
                                             const FiniteElement& fe,
                                             const Vec3& X) const
{
  SymmTensor eps(nsd), sigma(nsd);
  if (!B.multiply(elMat.vec[Vu],eps))
    return false;

  Matrix C; double U = 0.0;
  if (!material->evaluate(C,sigma,U,fe,X,eps,eps,iS))
    return false;

  // Integrate the (material) stiffness
  Matrix CB;
  if (CB.multiply(C,B).multiply(fe.detJxW).empty()) // CB = dSdE*B*|J|*w
    return false;

  if (elMat.A[uu_K].multiply(B,CB,true,false,true).empty()) // K_uu += B^T * CB
    return false;

  // Integrate the internal forces, if deformed configuration
  if (iS == 0 || eps.isZero(1.0e-16))
    return true;

  sigma *= fe.detJxW;
  return B.multiply(sigma,elMat.b[Fu],true,-1); // F_u -= B^T*sigma
}
Exemplo n.º 13
0
void
LIBeam3dNL :: computeStrainVector(FloatArray &answer, GaussPoint *gp, TimeStep *tStep)
{
    FloatArray xd(3), eps(3), curv(3);

    // update temp triad
    this->updateTempTriad(tStep);

    this->computeXdVector(xd, tStep);

    // compute eps_xl, gamma_l2, gamma_l3
    eps.beTProductOf(tempTc, xd);
    eps.times(1. / this->l0);
    eps.at(1) -= 1.0;

    // update curvature at midpoint
    this->computeTempCurv(curv, tStep);

    answer.resize(6);
    answer.at(1) = eps.at(1); // eps_xl
    answer.at(2) = eps.at(2); // gamma_l2
    answer.at(3) = eps.at(3); // gamma_l3
    answer.at(4) = curv.at(1); // kappa_1
    answer.at(5) = curv.at(2); // kappa_2
    answer.at(6) = curv.at(3); // kappa_3
}
Exemplo n.º 14
0
/***********************************************************************//**
 * @brief Print integral information
 *
 * @param[in] chatter Chattiness (defaults to NORMAL).
 * @return String containing integral information.
 ***************************************************************************/
std::string GIntegral::print(const GChatter& chatter) const
{
    // Initialise result string
    std::string result;

    // Continue only if chatter is not silent
    if (chatter != SILENT) {

        // Append header
        result.append("=== GIntegral ===");

        // Append information
        result.append("\n"+gammalib::parformat("Relative precision"));
        result.append(gammalib::str(eps()));
        result.append("\n"+gammalib::parformat("Max. number of iterations"));
        result.append(gammalib::str(max_iter()));
        if (silent()) {
            result.append("\n"+gammalib::parformat("Warnings")+"suppressed");
        }
        else {
            result.append("\n"+gammalib::parformat("Warnings"));
            result.append("in standard output");
        }

    } // endif: chatter was not silent

    // Return result
    return result;
}
/** Sets the vertices in a irrlicht vertex array to the 4 points of this quad.
 *  \param v The vertex array in which to set the vertices. 
 *  \param color The color to use for this quad.
 */
void Quad::getVertices(video::S3DVertex *v, const video::SColor &color) const
{
    // Eps is used to raise the track debug quads a little bit higher than
    // the ground, so that they are actually visible.
    core::vector3df eps(0, 0.1f, 0);
    v[0].Pos = m_p[0].toIrrVector()+eps;
    v[1].Pos = m_p[1].toIrrVector()+eps;
    v[2].Pos = m_p[2].toIrrVector()+eps;
    v[3].Pos = m_p[3].toIrrVector()+eps;

    core::triangle3df tri(m_p[0].toIrrVector(), m_p[1].toIrrVector(), 
                          m_p[2].toIrrVector());
    core::vector3df normal = tri.getNormal();
    normal.normalize();
    v[0].Normal = normal;
    v[1].Normal = normal;
    v[2].Normal = normal;

    core::triangle3df tri1(m_p[0].toIrrVector(), m_p[2].toIrrVector(), 
                           m_p[3].toIrrVector());
    core::vector3df normal1 = tri1.getNormal();
    normal1.normalize();
    v[3].Normal = normal1;

    v[0].Color  = color;
    v[1].Color  = color;
    v[2].Color  = color;
    v[3].Color  = color;
}   // setVertices
Exemplo n.º 16
0
bool PoroElasticity::evalSol (Vector& s, const FiniteElement& fe,
                              const Vec3& X, const Vector& disp) const
{
  if (!material)
  {
    std::cerr <<" *** PoroElasticity::evalSol: No material data."<< std::endl;
    return false;
  }

  Matrix Bmat;
  if (!this->formBmatrix(Bmat,fe.dNdX))
    return false;

  SymmTensor eps(nsd), sigma(nsd);
  if (!Bmat.multiply(disp,eps))
    return false;

  Matrix Cmat; double U = 0.0;
  if (!material->evaluate(Cmat,sigma,U,fe,X,eps,eps))
    return false;

  s = eps;
  const RealArray& sig = sigma;
  s.insert(s.end(),sig.begin(),sig.end());

  return true;
}
Exemplo n.º 17
0
db calcarea(int a, db a0, db a1)
{
    db da = a1 - a0;
    if (!eps(da)) return 0;
    db x0 = x[a] + r[a] * cos(a0), y0 = y[a] + r[a] * sin(a0);
    db x1 = x[a] + r[a] * cos(a1), y1 = y[a] + r[a] * sin(a1);
    return r[a] * r[a] * (da - sin(da)) + (x0 * y1 - x1 * y0);
}
Exemplo n.º 18
0
/* interface calling into the fortran routine */
static int lbfgs(index_t *x0, at *f, at *g, double gtol, htable_t *p, at *vargs)
{
   /* argument checking and setup */

   extern void lbfgs_(int *n, int *m, double *x, double *fval, double *gval, \
                      int *diagco, double *diag, int iprint[2], double *gtol, \
                      double *xtol, double *w, int *iflag);

   ifn (IND_STTYPE(x0) == ST_DOUBLE)
      error(NIL, "not an array of doubles", x0->backptr);
   ifn (Class(f)->listeval)
      error(NIL, "not a function", f);
   ifn (Class(f)->listeval)
      error(NIL, "not a function", g);
   ifn (gtol > 0)
      error(NIL, "threshold value not positive", NEW_NUMBER(gtol));
   
   at *gx = copy_array(x0)->backptr;
   at *(*listeval_f)(at *, at *) = Class(f)->listeval;
   at *(*listeval_g)(at *, at *) = Class(g)->listeval;
   at *callf = new_cons(f, new_cons(x0->backptr, vargs));
   at *callg = new_cons(g, new_cons(gx, new_cons(x0->backptr, vargs)));

   htable_t *params = lbfgs_params();
   if (p) htable_update(params, p);
   int iprint[2];
   iprint[0] = (int)Number(htable_get(params, NEW_SYMBOL("iprint-1")));
   iprint[1] = (int)Number(htable_get(params, NEW_SYMBOL("iprint-2")));
   lb3_.gtol = Number(htable_get(params, NEW_SYMBOL("ls-gtol")));
   lb3_.stpmin = Number(htable_get(params, NEW_SYMBOL("ls-stpmin")));
   lb3_.stpmax = Number(htable_get(params, NEW_SYMBOL("ls-stpmax")));
   int m = (int)Number(htable_get(params, NEW_SYMBOL("lbfgs-m")));
   int n = index_nelems(x0);
   double *x = IND_ST(x0)->data;
   double  fval;
   double *gval = IND_ST(Mptr(gx))->data;
   int diagco = false;
   double *diag = mm_blob(n*sizeof(double));
   double *w = mm_blob((n*(m+m+1)+m+m)*sizeof(double));
   double xtol = eps(1); /* machine precision */
   int iflag = 0;

   ifn (n>0)
      error(NIL, "empty array", x0->backptr);
   ifn (m>0)
      error(NIL, "m-parameter must be positive", NEW_NUMBER(m));

   /* reverse communication loop */
   do {
      fval = Number(listeval_f(Car(callf), callf));
      listeval_g(Car(callg), callg);
      lbfgs_(&n, &m, x, &fval, gval, &diagco, diag, iprint, &gtol, &xtol, w, &iflag);
      assert(iflag<2);
   } while (iflag > 0);
   
   return iflag;
}
Exemplo n.º 19
0
void MaintainerMain::on_episode_converter_clicked()
{
    EpisodeConverter eps(NULL);
    eps.setWindowFlags( Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint );
    eps.setWindowModality(Qt::NonModal);
    this->hide();
    eps.exec();
    this->show();
}
Exemplo n.º 20
0
Arquivo: master.cpp Projeto: ogdf/ogdf
bool Master::primalViolated(double x) const
{
	if (optSense_.max()) {
		if (objInteger_) {
			return x <= primalBound_;
		}
		else {
			return x + eps() <= primalBound_;
		}
	}
	else {
		if (objInteger_) {
			return x >= primalBound_;
		}
		else {
			return x - eps() >= primalBound_;
		}
	}
}
Exemplo n.º 21
0
	DPoint SpringEmbedderGridVariant::ForceModelGronemann::computeDisplacement(int j, double boxLength) const
	{
		const double cEps = eps();
		const double cIELEps = m_idealEdgeLength + cEps;

		const NodeInfo &vj = m_vInfo[j];
		int grid_x = vj.m_gridX;
		int grid_y = vj.m_gridY;

		// repulsive forces on node j: F_rep(d) = iel^2 / d
		DPoint force(0,0);
		for(int gi = -1; gi <= 1; gi++) {
			for(int gj = -1; gj <= 1; gj++) {
				for(int u : m_gridCell(grid_x+gi,grid_y+gj)) {

					if(u == j) continue;
					DPoint dist = vj.m_pos - m_vInfo[u].m_pos;
					double d = dist.norm();

					if(d < boxLength) {
						dist /= d * d + cEps;
						force += dist;
					}
				}
			}
		}

		force *= m_idealEdgeLength * m_idealEdgeLength;
		DPoint disp(force);

		// attractive forces on j: F_attr(d) = c / deg(v) * ln(d/iel)
		const double c = 0.5;

		DPoint forceRepSub(0,0); // subtract rep. force on adjacent vertices
		force = DPoint(0,0);
		for(int l = vj.m_adjBegin; l != vj.m_adjStop; ++l) {
			int u = m_adjLists[l];

			DPoint dist = vj.m_pos - m_vInfo[u].m_pos;
			double d = dist.norm();

			force -= log((d+cEps) / cIELEps) * dist;
			if(d < boxLength) {
				double f = 1.0 / (d * d + cEps);
				forceRepSub += f * dist;
			}
		}

		force       *= c * (vj.m_adjStop-vj.m_adjBegin);
		forceRepSub *= m_idealEdgeLength * m_idealEdgeLength;
		disp += force - forceRepSub;

		return disp;
	}
Exemplo n.º 22
0
complex<SX> canonical(int i, int n, SX& fin, SX& J, SX& U0, SX& dU, SX mu) {

    vector<vector<complex < SX>>> f(L, vector<complex < SX >> (dim, complex<SX>(0, 0)));
    vector<SX> norm2(L, 0);
    for (int j = 0; j < L; j++) {
        for (int k = 0; k < dim; k++) {
            int l = 2 * (j * dim + k);
            f[j][k] = complex<SX>(fin[l], fin[l + 1]);
        }
        for (int m = 0; m <= nmax; m++) {
            norm2[j] += f[j][m].real() * f[j][m].real() + f[j][m].imag() * f[j][m].imag();
        }
    }

    complex<SX> S = complex<SX>(0, 0);

    complex<SX> Sj1, Sj2;

    int j1 = mod(i - 1);
    int j2 = mod(i + 1);

    Sj1 = complex<SX>(0, 0);
    Sj2 = complex<SX>(0, 0);

    if (n < nmax) {
        for (int m = 1; m <= nmax; m++) {
            if (n != m - 1) {
                Sj1 += -J[j1] * g(n, m) * (1 / eps(U0, n, m))
                        * ~f[i][n + 1] * ~f[j1][m - 1] * f[i][n] * f[j1][m];
                Sj2 += -J[i] * g(n, m) * (1 / eps(U0, n, m))
                        * ~f[i][n + 1] * ~f[j2][m - 1] * f[i][n] * f[j2][m];

            }
        }
    }

    S += Sj1;
    S += Sj2;

    return S; //S.imag();
}
Exemplo n.º 23
0
Arquivo: master.cpp Projeto: ogdf/ogdf
void Master::primalBound(double x)
{
	if (optSense()->max()) {
		if (x < primalBound_) {
			Logger::ifout() << "Error: Master::primalBound(): got worse\nold bound: " << primalBound_ << "\nnew bound: " << x << "\n";
			OGDF_THROW_PARAM(AlgorithmFailureException, ogdf::AlgorithmFailureCode::PrimalBound);
		}
	}
	else {
		if (x > primalBound_) {
			Logger::ifout() << "Error: Master::primalBound(): got worse\nold bound: " << primalBound_ << "\nnew bound: " << x << "\n";
			OGDF_THROW_PARAM(AlgorithmFailureException, ogdf::AlgorithmFailureCode::PrimalBound);
		}
	}

	// make sure that this is an integer value for \a objInteger_
	/* After the test for integrality, we round the value to the next
	*   integer. The reason is that a new primal bound coming obtained
	*   by the solution of the relaxation in a subproblem might have some
	*   garbage in it (e.g., \a 10.000000000034 or \a 9.999999999987).
	*   With this garbage the
	*   fathoming of node might fail in the subproblem optimization, although
	*   it is already correct.
	*/
	if (objInteger_) {
		if (!isInteger(x, eps())) {
			Logger::ifout() << "Master::primalBound(): value " << x << " is not integer, but feasible solutions with integer objective function values are expected.\n";
			OGDF_THROW_PARAM(AlgorithmFailureException, ogdf::AlgorithmFailureCode::NotInteger);
		}

		x = floor(x + eps());
	}

	primalBound_ = x;

	// update the primal bound in the Tree Interface
	if (optSense()->max()) treeInterfaceLowerBound(x);
	else                   treeInterfaceUpperBound(x);

	history_->update();
}
    multi_geometry_generator_grammar()
        : multi_geometry_generator_grammar::base_type(start)
    {
        boost::spirit::karma::uint_type uint_;
        boost::spirit::bool_type bool_;
        boost::spirit::karma::_val_type _val;
        boost::spirit::karma::_1_type _1;
        boost::spirit::karma::lit_type lit;
        boost::spirit::karma::_a_type _a;
        boost::spirit::karma::eps_type eps;
        boost::spirit::karma::string_type kstring;

        geometry_types.add
            (mapnik::geometry_type::types::Point,"\"Point\"")
            (mapnik::geometry_type::types::LineString,"\"LineString\"")
            (mapnik::geometry_type::types::Polygon,"\"Polygon\"")
            (mapnik::geometry_type::types::Point + 3,"\"MultiPoint\"")
            (mapnik::geometry_type::types::LineString + 3,"\"MultiLineString\"")
            (mapnik::geometry_type::types::Polygon + 3,"\"MultiPolygon\"")
            ;

        start %= ( eps(phoenix::at_c<1>(_a))[_a = multi_type_(_val)]
                   << lit("{\"type\":\"GeometryCollection\",\"geometries\":[")
                   << geometry_collection << lit("]}")
                   |
                   geometry)
            ;

        geometry_collection = -(geometry2 % lit(','))
            ;

        geometry = ( &bool_(true)[_1 = not_empty_(_val)] << lit("{\"type\":")
                     << geometry_types[_1 = phoenix::at_c<0>(_a)][_a = multi_type_(_val)]
                     << lit(",\"coordinates\":")
                     << kstring[ phoenix::if_ (phoenix::at_c<0>(_a) > 3) [_1 = '['].else_[_1 = ""]]
                     << coordinates
                     << kstring[ phoenix::if_ (phoenix::at_c<0>(_a) > 3) [_1 = ']'].else_[_1 = ""]]
                     << lit('}')) | lit("null")
            ;

        geometry2 = lit("{\"type\":")
            << geometry_types[_1 = _a][_a = type_(_val)]
            << lit(",\"coordinates\":")
            << path
            << lit('}')
            ;

        coordinates %= path % lit(',')
            ;

    }
    void evaluation_test()
    {
      typedef eli::geom::curve::bezier<data__, 2> bezier_curve_type;
      data_type eps(std::numeric_limits<data__>::epsilon());

      control_point_type cntrl_in[5];
      typename bezier_curve_type::control_point_type bez_cntrl[5];
      curve_type ebc;
      bezier_curve_type bc;
      typename curve_type::point_type eval_out, eval_ref;
      typename curve_type::data_type t;

      // set control points and create curves
      cntrl_in[0] << 2.0;
      cntrl_in[1] << 1.5;
      cntrl_in[2] << 0.0;
      cntrl_in[3] << 1.0;
      cntrl_in[4] << 0.5;
      bez_cntrl[0] << 0,    2;
      bez_cntrl[1] << 0.25, 1.5;
      bez_cntrl[2] << 0.5,  0;
      bez_cntrl[3] << 0.75, 1;
      bez_cntrl[4] << 1,    0.5;

      ebc.resize(4);
      bc.resize(4);
      for (index_type i=0; i<5; ++i)
      {
        ebc.set_control_point(cntrl_in[i], i);
        bc.set_control_point(bez_cntrl[i], i);
      }

      // test evaluation at end points
      t=0;
      eval_out=ebc.f(t);
      eval_ref=bc.f(t);
      TEST_ASSERT(eval_out==eval_ref);
      t=1;
      eval_out=ebc.f(t);
      eval_ref=bc.f(t);
      TEST_ASSERT(eval_out==eval_ref);

      // test evaluation at interior point
      t=static_cast<data__>(0.45);
      eval_out=ebc.f(t);
      eval_ref=bc.f(t);
      TEST_ASSERT((eval_out-eval_ref).norm()<1.1*eps);
    }
Exemplo n.º 26
0
//----------------------------------------------------------------------
// fp -> double -> fp rountrip test
//----------------------------------------------------------------------
TEST_F(lfpTest, FDF_RoundTrip) {
	// since a l_fp has 64 bits in it's mantissa and a double has
	// only 54 bits available (including the hidden '1') we have to
	// make a few concessions on the roundtrip precision. The 'eps()'
	// function makes an educated guess about the avilable precision
	// and checks the difference in the two 'l_fp' values against
	// that limit.
	for (size_t idx=0; idx < addsub_cnt; ++idx) {
		LFP    op1(addsub_tab[idx][0].h, addsub_tab[idx][0].l);
		double op2(op1);
		LFP    op3(op2);
		// for manual checks only:
		// std::cout << std::setprecision(16) << op2 << std::endl;
		ASSERT_LE(fabs(op1-op3), eps(op2));
	}	
}
Exemplo n.º 27
0
	DPoint SpringEmbedderGridVariant::ForceModelFRModAttr::computeDisplacement(int j, double boxLength) const
	{
		const double cEps = eps();

		const NodeInfo &vj = m_vInfo[j];
		int grid_x = vj.m_gridX;
		int grid_y = vj.m_gridY;

		// repulsive forces on node j: F_rep(d) = iel^3 / d
		DPoint force(0,0);
		for(int gi = -1; gi <= 1; gi++) {
			for(int gj = -1; gj <= 1; gj++) {
				for(int u : m_gridCell(grid_x+gi,grid_y+gj)) {

					if(u == j) continue;
					DPoint dist = vj.m_pos - m_vInfo[u].m_pos;
					double d = dist.norm();

					if(d < boxLength) {
						dist /= d * d + cEps;
						force += dist;
					}
				}
			}
		}

		force *= m_idealEdgeLength * m_idealEdgeLength * m_idealEdgeLength;
		DPoint disp(force);

		// attractive forces on j: F_attr(d) = -d^3 / iel
		force = DPoint(0,0);
		for(int l = vj.m_adjBegin; l != vj.m_adjStop; ++l) {
			int u = m_adjLists[l];

			DPoint dist = vj.m_pos - m_vInfo[u].m_pos;
			double d = dist.norm();

			dist *= d*d;
			force -= dist;
		}

		force /= m_idealEdgeLength;
		disp += force;

		return disp;
	}
    void length_test()
    {
      data_type eps(std::numeric_limits<data__>::epsilon());
      typedef eli::geom::curve::bezier<data__, 2> bezier_curve_type;
      control_point_type cntrl_in[5];
      typename bezier_curve_type::control_point_type bez_cntrl[5];
      curve_type ebc;
      bezier_curve_type bc;
      typename curve_type::point_type eval_out, eval_ref;
      typename curve_type::data_type length_cal, length_ref;

      // set control points and create curves
      cntrl_in[0] << 2.0;
      cntrl_in[1] << 1.5;
      cntrl_in[2] << 0.0;
      cntrl_in[3] << 1.0;
      cntrl_in[4] << 0.5;
      bez_cntrl[0] << 0,    2;
      bez_cntrl[1] << 0.25, 1.5;
      bez_cntrl[2] << 0.5,  0;
      bez_cntrl[3] << 0.75, 1;
      bez_cntrl[4] << 1,    0.5;

      ebc.resize(4);
      bc.resize(4);
      for (index_type i=0; i<5; ++i)
      {
        ebc.set_control_point(cntrl_in[i], i);
        bc.set_control_point(bez_cntrl[i], i);
      }

      // calculate the length of curve
      data_type tol(std::sqrt(eps));
      eli::geom::curve::length(length_cal, ebc, tol);
      eli::geom::curve::length(length_ref, bc, tol);
      TEST_ASSERT(length_cal==length_ref);

      // test computing some segment length
      typename curve_type::data_type t0, t1;
      t0 = static_cast<data__>(0.2);
      t1 = static_cast<data__>(0.7);

      eli::geom::curve::length(length_cal, ebc, t0, t1, tol);
      eli::geom::curve::length(length_ref, bc, t0, t1, tol);
      TEST_ASSERT(length_cal==length_ref);
    }
void lib_test_client::draw(visualizer &d, draw_scope &scope)
{
    auto draw_vertex = [&] (my_graph::vertex_id id, int frame) 
    {
        coord<int> vert_coord = scope.world2screen(pgraph_->get_vertex(id).get_data().c);
        coord<int> eps (frame, frame);
        d.draw_rect(vert_coord - eps, vert_coord + eps);
    };

    d.set_bg_color(0, 0, 0);

    d.set_color(64, 64, 64);
    d.draw_buffers(g_desc.vb, 0, pgraph_->v_count(), g_desc.ib, 0, pgraph_->e_count());

    if (start_.is_initialized())
    {
        d.set_color(255, 0, 0);
        draw_vertex(*start_, 2);
    }
    if (end_.is_initialized())
    {
        d.set_color(255, 255, 0);
        draw_vertex(*end_, 2);
    }
    if (selected_.is_initialized())
    {
        d.set_color(0, 255, 0);
        draw_vertex(*selected_, 3);
    }
    d.set_color(255, 255, 255);
    draw_vertex(87909, 3);

    if (!path_.empty())
    {
        d.set_color(255, 255, 255);
        vis_coord last = path_[0];
        for (size_t i = 1; i < path_.size(); ++i)
        {
            d.draw_line(get_scope().world2screen(last), 
                        get_scope().world2screen(path_[i]));
            last = path_[i];
        }
    }

}
Exemplo n.º 30
0
 CArray<Eigen::Dynamic,N> evaluate(CMatrix<D,N> const& grid) const
 {
     ScalarHaWp<D,MultiIndex> unionwp;
     
     unionwp.eps() = eps();
     unionwp.parameters() = parameters();
     unionwp.shape() = union_shape();
     
     std::vector< ShapeEnum<D,MultiIndex>* > shape_list(n_components());
     std::vector< complex_t const* > coeffs_list(n_components());
     
     for (std::size_t n = 0; n < n_components(); n++) {
         shape_list[n] = component(n).shape().get();
         coeffs_list[n] = component(n).coefficients().data();
     }
     
     return unionwp.template create_evaluator<N>(grid).vector_reduce(shape_list.data(), coeffs_list.data(), n_components());
 }