Exemplo n.º 1
0
// Prime-power factorization
void pp_factorize(vector<long>& factors, long N)
{
  Vec< Pair<long, long> > pf;
  factorize(pf,N); // prime factors, N = \prod_i pf[i].first^{pf[i].second}
  factors.resize(pf.length());
  for (long i=0; i<pf.length(); i++)
    factors[i] = power_long(pf[i].a, pf[i].b); // p_i^e_i
}
Exemplo n.º 2
0
void assert_vec_p(const Vec<T> &ref, const Vec<T> &act, int line)
{
  static const double tol = 1e-3;
  ASSERT_EQ(ref.length(), ref.length()) << line;
  for (int n = 0; n < ref.length(); ++n) {
    ASSERT_NEAR(ref(n), act(n), tol) << line;
  }
}
double computeAverageDouble(Vec<double> &result){

    RR average = 0;

    for (int i = 1; i <= result.length() ; i++){
        average += result(i);
    }

    return to_double(average/result.length());
}
Exemplo n.º 4
0
void setHyperColumn(const Vec<T>& v, const CubeSlice<T>& s, long pos)
{
   long m = s.getProd(1);
   long n = s.getDim(0);

   assert(pos >= 0 && pos < m);
   if (v.length() < n) n = v.length();

   for (long i = 0; i < n; i++)
      s[pos + i*m] = v[i];
}
Exemplo n.º 5
0
void
DEMParticleCreator::addExtraTranslations(const Vec& shift, 
                                         REAL boundaryMargin,
                                         Vec inPlaneDiag,
                                         REAL widthX, REAL widthY, REAL widthZ,
                                         const Face& face,
                                         const IntersectionStatus status, 
                                         std::vector<Vec>& translations) 
{
  if (status.second.first == Face::Location::VERTEX) {
    int vertIndex = status.second.second;
    //std::cout << "is vertex " << vertIndex << "\n";
    if (vertIndex == 0) {
      for (int ii = 1; ii < 4; ++ii) {
        Vec inPlane = face.vertex[ii] - face.vertex[vertIndex];
        auto length = inPlane.length();
        inPlane.normalizeInPlace();
        if (ii == 2) {
          inPlane *= length;
          inPlane += (inPlaneDiag*boundaryMargin);
        } else {
          inPlane *= (length + boundaryMargin);
        }
        Vec outOfPlane = inPlane + shift;
        translations.push_back(inPlane);
        translations.push_back(outOfPlane);
      }
    } else if (vertIndex == 1 || vertIndex == 3) {
      Vec normal = Vec(1,1,1) - inPlaneDiag;
      Vec vec1 = normal * Vec(widthX + boundaryMargin, 
        widthY + boundaryMargin, widthZ + boundaryMargin);
      Vec vec2 = face.vertex[2] - face.vertex[vertIndex];
      auto length = vec2.length();
      vec2.normalizeInPlace();
      vec2 *= (length + boundaryMargin);
      //std::cout << "vec1 = " << vec1 << " vec2 = " << vec2 << "\n";
      translations.push_back(vec1 + vec2);
    }
  } 
  else if (status.second.first == Face::Location::EDGE) {
    int edgeIndex = status.second.second;
    //std::cout << "is edge " << edgeIndex << "\n";
    if (edgeIndex == 0 || edgeIndex == 3) {
      int oppIndex = (edgeIndex+3) % 4;
      Vec inPlane = face.vertex[oppIndex] - face.vertex[edgeIndex];
      auto length = inPlane.length() + boundaryMargin;
      inPlane.normalizeInPlace();
      inPlane *= length;
      Vec outOfPlane = inPlane + shift;
      translations.push_back(inPlane);
      translations.push_back(outOfPlane);
    }
  }
}
Exemplo n.º 6
0
QString TetraGPSEncoder::generate(TGPSReal lat, TGPSReal lon, TGPSReal precMeters){
	const Vec coord(cos(lat)*cos(lon), cos(lat)*sin(lon), sin(lat));
	qDebug()<<"COORD:"<<coord<<coord.length()<<coord.latlon();
	QVector<Tri> faces;
	const TGPSReal ma=(M_PI*2.0)/3.0;
	const Vec north(    +0.0,                                    +1.0,      +0.0);
	const Vec prime(    +0.0,                                    +sin(-ma), +cos(-ma));
	const Vec meridian2(prime.x()*cos(+ma) - prime.z()*sin(+ma), prime.y(), prime.z()*cos(+ma) + prime.x()*sin(+ma));
	const Vec meridian3(prime.x()*cos(-ma) - prime.z()*sin(-ma), prime.y(), prime.z()*cos(-ma) + prime.x()*sin(-ma));
	qDebug()<<"north=    "<<north<<north.length();
	qDebug()<<"prime=    "<<prime<<prime.length();
	qDebug()<<"meridian2="<<meridian2<<meridian2.length();
	qDebug()<<"meridian3="<<meridian3<<meridian3.length();
	faces.push_back(Tri(north,prime,meridian2, 1));
	faces.push_back(Tri(north,prime,meridian3, 2));
	faces.push_back(Tri(north,meridian2,meridian3, 3));
	faces.push_back(Tri(prime,meridian2,meridian3, 4));
	TGPSReal score=1000.0;
	QStringList ret;
	int sub=0;
	Tri best,second;
	while((score*planetRadiusMeters)>precMeters && sub++<9){
		//qDebug()<<"----ROUND "<<sub<< score;
		TGPSReal eps=1000.0;
		for(auto tri:faces) {
			TGPSReal delta=(tri.center-coord).length();
			//qDebug()<<"DELTA: "<<delta<<tri.center<<tri.center.length();
			if(delta<eps){
				if(delta<score){
					score=delta;
				}
				eps=delta;
				best=tri;
				qDebug()<<"NEW BEST: "<<best<<"!";
			}
		}
		QString name=best.name();
		//if("0"==name){			break;		}
		ret<<name;
		faces=best.subdivide();

		if(best!=second){
			second=best;
		}
		else{
			break;
		}
	}
	TGPSReal d=(coord-best.center).length()/best.reach();
	qDebug()<<"BEST: "<<best<<" with "<< d<<" normalized distance from center and " << (score*planetRadiusMeters)<<" meters after "<<sub<<" iterations";
	return ret.join(".");
}
Exemplo n.º 7
0
// Get multiple layers of a Benes permutation network. Returns in out[i][j]
// the shift amount to move item j in the i'th layer. Also isID[i]=true if
// the i'th layer is the identity (i.e., contains only 0 shift amounts).
void ColPerm::getBenesShiftAmounts(Vec<Permut>& out, Vec<bool>& isID,
				   const Vec<long>& benesLvls) const
{
  // Go over the columns one by one. For each column extract the columns
  // permutation, prepare a Benes network for it, and then for every layer
  // compute the shift amounts for this columns.

  long n = getDim(dim);     // the permutations are over [0,n-1]

  // Allocate space
  out.SetLength(benesLvls.length());
  isID.SetLength(benesLvls.length());
  for (long k=0; k<benesLvls.length(); k++) {
    out[k].SetLength(getSize());
    isID[k] = true;
  }

  Vec<long> col;
  col.SetLength(n);

  for (long slice_index = 0; slice_index < numSlices(dim); slice_index++) {
    ConstCubeSlice<long> slice(*this, slice_index, dim);
    for (long col_index = 0; col_index < slice.numCols(); col_index++) {
      getHyperColumn(col, slice, col_index);

      GeneralBenesNetwork net(col); // build a Benes network for this column

      // Sanity checks: width of network == n,
      //                and sum of benesLvls entries == # of levels
      assert(net.getSize()==n);
      {long sum=0;
       for (long k=0; k<benesLvls.length(); k++) sum+=benesLvls[k];
       assert(net.getNumLevels()==sum);
      }

      // Compute the layers of the collapased network for this column
      for (long lvl=0,k=0; k<benesLvls.length(); lvl += benesLvls[k], k++) {

	// Returns in col the shift amounts for this layer in the network,
	// restricted to this column. Also returns true if the returned
	// permutation is the idendity, false otherwise.
	bool id = collapseBenesLevels(col, net, lvl, benesLvls[k]);
	isID[k] = isID[k] && id;

        CubeSlice<long> oslice(out[k], getSig());
        CubeSlice<long> osubslice(oslice, slice_index, dim);
        setHyperColumn(col, osubslice, col_index);
      }  // next collapsed layer
    }  // next column
  } // next slice
}
Exemplo n.º 8
0
void vecRed(Vec<ZZ>& out, const Vec<ZZ>& in, long q, bool abs)
{
  out.SetLength(in.length());  // allocate space if needed

  for (long i=0; i<in.length(); i++) {
    long c = in[i]%q;
    if (abs)       { if (c<0) c+=q; }
    else if (q==2) { if (in[i]<0) c = -c; }
    else { 
      if (c >= q/2)        c -= q;
      else if (c < -(q/2)) c += q;
    }
    out[i] = c;
  }
}
Exemplo n.º 9
0
// powVec[d] = m_d = p_d^{e_d}
// computes multiEvalPoints[d] as a vector of length phi(m_d)
//   containing base^{(m/m_d) j} for j in Z_{m_d}^*
void computeMultiEvalPoints(Vec< Vec<zz_p> >& multiEvalPoints,
                            const zz_p& base,
                            long m,
                            const Vec<long>& powVec,
                            const Vec<long>& phiVec)
{
   long k = powVec.length();

   multiEvalPoints.SetLength(k);

   for (long d = 0; d < k; d++) {
      long m_d = powVec[d];
      long phi_d = phiVec[d];
      long count = 0;

      zz_p pow = conv<zz_p>(1);
      zz_p mult = power(base, m/m_d);

      multiEvalPoints[d].SetLength(phi_d);

      for (long j = 0; j < m_d; j++) {
         if (GCD(j, m_d) == 1) {
            multiEvalPoints[d][count] = pow;
            count++;
         }
         pow = pow * mult;
      }
   }
}
Exemplo n.º 10
0
// factors[d] = (p_d, e_d)
// computes powVec[d] = p_d^{e_d}
void computePowVec(Vec<long>& powVec, 
                   const Vec< Pair<long, long> >& factors)
{
  long k = factors.length();
  powVec.SetLength(k);
  for (long d = 0; d < k; d++)
    powVec[d] = computePow(factors[d]);
}
Exemplo n.º 11
0
// returns \prod_d vec[d]
long computeProd(const Vec<long>& vec)
{
  long prod = 1;
  long k = vec.length();
  for (long d = 0; d < k; d++)
    prod = prod * vec[d];
  return prod;
}
Exemplo n.º 12
0
void computePowVec(Vec<long>& powVec, 
                   const Vec< Pair<long, long> >& factors)
{
  long k = factors.length();
  powVec.SetLength(k);
  for (long i = 0; i < k; i++)
    powVec[i] = computePow(factors[i]);
}
Exemplo n.º 13
0
// computeProd(vec) returns the product of the entries of vec
long computeProd(const Vec<long>& vec)
{
  long prod = 1;
  long k = vec.length();
  for (long i = 0; i < k; i++)
    prod = prod * vec[i];
  return prod;
}
Exemplo n.º 14
0
// powVec[d] = p_d^{e_d}, m = \prod_d p_d^{e_d}
// computes divVec[d] = m/p_d^{e_d}
void computeDivVec(Vec<long>& divVec, long m,
                   const Vec<long>& powVec)
{
  long k = powVec.length();
  divVec.SetLength(k);

  for (long d = 0; d < k; d++)
    divVec[d] = m/powVec[d];
}
Exemplo n.º 15
0
// vec[d] = (a_d , b_d)
// returns \prod_d a_d^{b_d}
long computeProd(const Vec< Pair<long, long> >& vec)
{
  long prod = 1;
  long k = vec.length();
  for (long d = 0; d < k; d++) {
    prod = prod * computePow(vec[d]);
  }
  return prod;
}
Exemplo n.º 16
0
void computeDivVec(Vec<long>& divVec, long m,
                   const Vec<long>& powVec)
{
  long k = powVec.length();
  divVec.SetLength(k);

  for (long i = 0; i < k; i++)
    divVec[i] = m/powVec[i];
}
Exemplo n.º 17
0
void readContextBinary(istream& str, FHEcontext& context)
{
  assert(readEyeCatcher(str, BINIO_EYE_CONTEXT_BEGIN)==0);

  // Get the standard deviation
  context.stdev = read_raw_xdouble(str);

  long sizeOfS = read_raw_int(str);

  IndexSet s;
  for(long tmp, i=0; i<sizeOfS; i++){
    tmp = read_raw_int(str);
    s.insert(tmp);
  }

  context.moduli.clear();
  context.specialPrimes.clear();
  context.ctxtPrimes.clear();

  long nPrimes = read_raw_int(str);

  for (long p,i=0; i<nPrimes; i++) {
    p = read_raw_int(str);

    context.moduli.push_back(Cmodulus(context.zMStar,p,0));

    if (s.contains(i))
      context.specialPrimes.insert(i); // special prime
    else
      context.ctxtPrimes.insert(i);    // ciphertext prime
  }
  
  long nDigits = read_raw_int(str);

  context.digits.resize(nDigits);
  for(long i=0; i<(long)context.digits.size(); i++){
    sizeOfS = read_raw_int(str);

    for(long tmp, n=0; n<sizeOfS; n++){
      tmp = read_raw_int(str);
      context.digits[i].insert(tmp);
    }
  }

  // Read in the partition of m into co-prime factors (if bootstrappable)
  Vec<long> mv;
  read_ntl_vec_long(str, mv);

  long t = read_raw_int(str);
  bool consFlag = read_raw_int(str);  

  if (mv.length()>0) {
    context.makeBootstrappable(mv, t, consFlag);
  }

  assert(readEyeCatcher(str, BINIO_EYE_CONTEXT_END)==0);
}
Exemplo n.º 18
0
void setHyperColumn(const Vec<T>& v, const CubeSlice<T>& s, long pos, const T& val)
{
   long m = s.getProd(1);
   long n = s.getDim(0);
   long n1 = n;

   assert(pos >= 0 && pos < m);
   if (v.length() < n) n1 = v.length();

   const T* vp = &v[0];
   T* sp = &s[0];

   for (long i = 0; i < n1; i++)
      sp[pos + i*m] = vp[i];

   for (long i = n1; i < n; i++)
      sp[pos + i*m] = val;
}
Exemplo n.º 19
0
// NOTE: the signature for this is in lzz_p.h
void conv(vec_zz_p& x, const Vec<long>& a)
{
   long i, n;

   n = a.length();
   x.SetLength(n);

   VectorConv(n, x.elts(), a.elts());
}
Exemplo n.º 20
0
bool SubdivScene::repositionSelectedVertex(int x, int y) {
    if (!selectedVertex)
        return false;

    printf("Repositioning vertex, (%i, %i)...\n", x,y);
    //In the plane perpendicular to camera->look, and through which the vertex passes, 
    //move vertex from where it is to where the mouse is

    //Use current vertex position to calculate the center of the screen
    Vec camPos = camera->getPos();
    Vec vPos = selectedVertex->getData().p;
    Vec diff = vPos - camPos;
    Vec look = camera->getLook().normalize();
    float cosAngle = sqrt(diff.normalize().dot(look));
    float lookLength = diff.length()*cosAngle;
    Vec centreDiff = look*lookLength;
    Vec diffInPlane = vPos - (camPos + centreDiff);
printf(" diffInPlane is"); diffInPlane.print();
printf(" Cam pos is"); camPos.print();


    float anglex = (x - Globals::getWidth()/2)*Globals::getFovx() * Globals::PI/180/Globals::getWidth();
    float angley = (y - Globals::getHeight()/2)*Globals::getFovy() * Globals::PI/180/Globals::getHeight();
    float hLength = tan(anglex)*centreDiff.length();
    float vLength = tan(angley)*centreDiff.length();
printf(" anglex is %f and angley is %f, fovx is %f\n", anglex, angley, Globals::getFovx());
printf(" hLength is %f and vLength is %f, hrat is %i\n", hLength, vLength, x - Globals::getWidth()/2);


    //calculate the shifts in the horiz and vertical directions
    Vec right = camera->getLook().cross(camera->getUp()).normalize()*hLength;
    Vec up = camera->getUp().normalize()*vLength;

printf(" Right is"); right.print();
printf(" up is"); up.print();

    Vec newPos = vPos + right + up - diffInPlane;
    selectedVertex->getData().p = newPos;

    printf("  Old position was (%f, %f, %f)\n", vPos.x, vPos.y, vPos.z);
    printf("  New position is (%f, %f, %f)\n", newPos.x, newPos.y, newPos.z);

    redrawRequired = true;
}
Exemplo n.º 21
0
void mapPowerfulToPoly(ZZX& poly, 
                       const Vec<long>& pow, 
                       const Vec<long>& divVec,
                       long m,
                       const ZZX& phimX)
{
  long k = pow.length();
  assert(divVec.length() == k);

  long j = 0;
  for (long i = 0; i < k; i++)
    j += pow[i] * divVec[i];

  j %= m;

  ZZX f = ZZX(j, 1);

  poly = f % phimX;
}
Exemplo n.º 22
0
// powVec[d] = p_d^{e_d}
// cycVec[d] = Phi_{p_d^{e_d}}(X) mod p
void computeCycVec(Vec<zz_pX>& cycVec, const Vec<long>& powVec)
{
  long k = powVec.length();
  cycVec.SetLength(k);

  for (long d = 0; d < k; d++) {
    ZZX PhimX = Cyclotomic(powVec[d]);
    cycVec[d] = conv<zz_pX>(PhimX);
  }
}
Exemplo n.º 23
0
void Spring::apply() const
{
  Vec delta = mB->pos - mA->pos;
  float distance = delta.length();
  float offset = mRestLength - distance;
  if( distance > ci::EPSILON_VALUE )
  { offset /= distance; }
  Vec correction = delta * offset / 2.0f * mStiffness;
  mA->pos -= correction;
  mB->pos += correction;
}
Exemplo n.º 24
0
ZZ sum(const Vec<ZZ>& v)
{
   ZZ acc;

   acc = 0;

   for (long i = 0; i < v.length(); i++)
      acc += v[i];

   return acc;
}
Exemplo n.º 25
0
// Adds one to the little-endian representation of an integer in base digits,
// returns true if there was an overflow
static bool addOne(Vec<long>& rep, const Vec<long> digits)
{
  for (long i=rep.length()-1; i>=0; --i) {
    rep[i]++;
    if (rep[i] >= digits[i])
      rep[i] -= digits[i];
    else
      return false;
  }
  return true;
}
Exemplo n.º 26
0
void mapPowerfulToPoly(ZZX& poly, 
                       const Vec<long>& pow, 
                       const Vec<long>& divVec,
                       long m,
                       const ZZX& phimX)
{
  long k = pow.length();
  //OLD: assert(divVec.length() == k);
  helib::assertEq(divVec.length(), k, "pow and divVec have different sizes");

  long j = 0;
  for (long i = 0; i < k; i++)
    j += pow[i] * divVec[i];

  j %= m;

  ZZX f = ZZX(j, 1);

  poly = f % phimX;
}
Exemplo n.º 27
0
// Compute one or more layers corresponding to one network of one leaf
void PermNetwork::setLayers4Leaf(long lyrIdx, const ColPerm& p,
				 const Vec<long>& benesLvls, long gIdx,
				 const SubDimension& leafData, 
				 const Permut& map2cube)
{
#ifdef DEBUG_PRINTOUT
  std::cerr << "Layer "<<lyrIdx<<", column-permutation="<< p << endl;
#endif
  // Compute the shift amounts for all the layers in this network
  Vec<bool> isID;
  Vec<Permut> shifts;
  if (benesLvls.length()==1) {// Special case for a "trivial" 1-layer network
    shifts.SetLength(1);
    isID.SetLength(1);
    isID[0] = !p.getShiftAmounts(shifts[0]);
  }
  else  // The general case of a multi-layer Benes network
    p.getBenesShiftAmounts(shifts,isID,benesLvls);

  // Copy the shift amounts to the right place in the bigger network,
  // renaming the slots from a linear array to the hyper cube
  for (long i=0; i<benesLvls.length(); i++) {
    PermNetLayer& lyr = layers[lyrIdx+i];
    lyr.genIdx = gIdx;
    lyr.isID = isID[i];
    lyr.e = leafData.e;
    if (!lyr.isID) {
#ifdef DEBUG_PRINTOUT
      std::cerr << "layer "<<lyrIdx+i<<": "<<shifts[i]<<endl;
#endif
      if (leafData.good) // For good leaves, shift by -x is the same as size-x
	for (long k=0; k<shifts[i].length(); k++)
	  if (shifts[i][k]<0) shifts[i][k] += leafData.size;
      applyPermToVec(lyr.shifts, shifts[i], map2cube); // do the renaming
#ifdef DEBUG_PRINTOUT
      std::cerr << "       : "<<lyr.shifts<<endl;
#endif
    }
    //    else std::cerr << "layer "<<lyrIdx+i<<"= identity\n";
  }
}
Exemplo n.º 28
0
// divVec[d] = m/p_d^{e_d}, powVec[d] = p^{e_d}
// computes invVec[d] = divVec[d]^{-1} mod powVec[d]
void computeInvVec(Vec<long>& invVec,
                   const Vec<long>& divVec, const Vec<long>& powVec)
{
  long k = divVec.length();
  invVec.SetLength(k);

  for (long d = 0; d < k; d++) {
    long t1 = divVec[d] % powVec[d];
    long t2 = InvMod(t1, powVec[d]);
    invVec[d] = t2;
  }
}
Exemplo n.º 29
0
void computeInvVec(Vec<long>& invVec,
                   const Vec<long>& divVec, const Vec<long>& powVec)
{
  long k = divVec.length();
  invVec.SetLength(k);

  for (long i = 0; i < k; i++) {
    long t1 = divVec[i] % powVec[i];
    long t2 = InvMod(t1, powVec[i]);
    invVec[i] = t2;
  }
}
Exemplo n.º 30
0
void Spring::apply()
{
	Vec x = *p1->x - *p2->x,
		v = *p1->v - *p2->v;
	if (!x)
		return;
	
	unit l = x.length();
	Vec f = ((ks * (l - rest)) + (kd * (v * x) / l)) * (x / l);
	
	*p1->f += f;
	*p2->f -= f;
}