Exemple #1
0
TEST(AgradFwdCeil,FvarFvarDouble) {
  using stan::math::fvar;
  using std::ceil;

  fvar<fvar<double> > x;
  x.val_.val_ = 1.5;
  x.val_.d_ = 2.0;

  fvar<fvar<double> > a = ceil(x);

  EXPECT_FLOAT_EQ(ceil(1.5), a.val_.val_);
  EXPECT_FLOAT_EQ(0, a.val_.d_);
  EXPECT_FLOAT_EQ(0, a.d_.val_);
  EXPECT_FLOAT_EQ(0, a.d_.d_);

  fvar<fvar<double> > y;
  y.val_.val_ = 1.5;
  y.d_.val_ = 2.0;

  a = ceil(y);
  EXPECT_FLOAT_EQ(ceil(1.5), a.val_.val_);
  EXPECT_FLOAT_EQ(0, a.val_.d_);
  EXPECT_FLOAT_EQ(0, a.d_.val_);
  EXPECT_FLOAT_EQ(0, a.d_.d_);
}
size_t DfpnSolver::ComputeMaxChildIndex(const std::vector<DfpnData>&
                                        childrenData) const
{
    HexAssert(!childrenData.empty());

    int numNonLosingChildren = 0;
    for (size_t i = 0; i < childrenData.size(); ++i)
        if (!childrenData[i].m_bounds.IsWinning())
            ++numNonLosingChildren;
    if (numNonLosingChildren < 2)
        return childrenData.size();

    // this needs experimenting!
    int childrenToLookAt = WideningBase() + (int) ceil(numNonLosingChildren
                                                       * WideningFactor());
    // Must examine at least two children when have two or more live,
    // since otherwise delta2 will be set to infinity in SelectChild.
    HexAssert(childrenToLookAt >= 2);

    int numNonLosingSeen = 0;
    for (size_t i = 0; i < childrenData.size(); ++i)
    {
        if (!childrenData[i].m_bounds.IsWinning())
            if (++numNonLosingSeen == childrenToLookAt)
                return i + 1;
    }
    return childrenData.size();
}
Exemple #3
0
 static inline int run()
 {
   using std::ceil;
   using std::log;
   return cast<double,int>(ceil(-log(std::numeric_limits<double>::epsilon())
                                / log(10.0)));
 }
Exemple #4
0
std::vector<int64_t>* PrimeFactors(const int64_t NUMBER) {
    using std::ceil;
    using std::sqrt;
    using std::vector;
    // We only need to test up to the square root of the number, if this fails
    // we know it's prime
    const int64_t LIMIT = static_cast<int64_t>(ceil(sqrt(NUMBER)));
    vector<bool> const * const PRIMES = PrimeSieve(LIMIT);

    int64_t current_number = NUMBER;
    vector<int64_t>* prime_factors = new vector<int64_t>();
    // We try dividing through by primes until our number reaches 1, then
    // return the list of primes
    for (int64_t i = 0; i < LIMIT; ++i) {
        if (PRIMES->at(i) && current_number % i == 0) {  // Is Prime
            do {
                current_number = current_number / i;
                prime_factors->push_back(i);
                if (current_number <= 1) {
                    return prime_factors;
                }
            } while(current_number % i == 0);
        }
    }
    // Should return from the loop
    return NULL;
}
      static source_type nearbyint ( argument_type s )
      {
#if !defined(BOOST_NO_STDC_NAMESPACE)
          using std::ceil ;
#endif
          return Double( ceil(s.v) );
      }
Exemple #6
0
// Calculate parking charge for a customer
// First three hours are charged $2.00, each hour for next three hours are charged $0.50, and
// 24-hour period charge $10.00
double calculateCharge( double parkingHours )
{
	double charge = 0.0; // parking charge in $
	
	if (parkingHours < 3.0) { // charge for first three parking hours
		charge = 2.00;
	}
	else if (parkingHours >= 3.0 && parkingHours < 6.0) // from 3 to 6 hours period
	{
		const double 	chargePerHour = 0.50; 	// each hour is charged $0.50
		const double 	baseCharge = 2.00;		// base charge for first three hours
		const int 		baseHour = 3;			// base hour when different charge is used

		double differ;	// time difference between parking hours and base hour
		differ = parkingHours - baseHour; // widening! (int baseHours -> double baseHours)
		
		// Difference must be round up for appropriate hour charge.
		int chargeFactor; 
		chargeFactor = ceil( differ );
		
		// For each hour, additional charge is added to base charge (for first three hours i.e. $2.00)
		// 				
		// 				charge = baseCharge + chargeFactor * chargePerHour
		//
		charge = baseCharge + chargeFactor * chargePerHour;
	} 
	else { // 24-hour period
		double chargePerDay = 10.00; // 24-hour period charge
		charge = chargePerDay;
	}

	return charge;
}
Exemple #7
0
  static source_type nearbyint ( argument_type s )
  {
    // Algorithm contributed by Guillaume Melquiond

#if !defined(BOOST_NO_STDC_NAMESPACE)
    using std::floor ;
    using std::ceil  ;
#endif

    // only works inside the range not at the boundaries
    S prev = floor(s);
    S next = ceil(s);

    S rt = (s - prev) - (next - s); // remainder type

    S const zero(0.0);
    S const two(2.0);

    if ( rt < zero )
      return prev;
    else if ( rt > zero )
      return next;
    else
    {
      bool is_prev_even = two * floor(prev / two) == prev ;
      return ( is_prev_even ? prev : next ) ;
    }
  }
Exemple #8
0
void Stippler::createInitialDistribution() {
	using std::ceil;

	// find initial distribution
	boost::mt19937 rng;
	boost::uniform_01<boost::mt19937, float> generator( rng );

	float w = (float)(image.getWidth() - 1), h = (float)(image.getHeight() - 1);
	float xC, yC;

	for ( unsigned int i = 0; i < parameters.points; ) {
		xC = generator() * w;
		yC = generator() * h;

		//printf("%f //", generator());
		//printf("%f ::  ", ceil(generator()*255.0));
		//printf("%f \n", image.getIntensity(xC, yC));
		// do a nearest neighbour search on the vertices
		if ( ceil(generator() * 255.0f) <= image.getIntensity( xC, yC ) ) { //white is zero.
			//printf("aaaaaaa\n");
			vertsX[i] = xC;
			vertsY[i] = yC;
			radii[i] = 0.0f;

			i++;
		}
	}
}
Exemple #9
0
std::vector<bool>* PrimeSieve(const int64_t& LENGTH) {
    using std::ceil;
    using std::fill;
    using std::sqrt;
    using std::vector;
    // Fill with true
    vector<bool>* primes = new vector<bool>(LENGTH);
    fill(primes->begin(), primes->end(), true);

    // 0, 1 are not prime
    if (LENGTH >= 2) {
        primes->at(0) = primes->at(1) = false;
    } else if (LENGTH < 1) {
        return NULL;
    } else {
        primes->at(0) = false;
    }

    // Sieve
    for (int64_t i = 2; i < ceil(sqrt(LENGTH)); ++i) {
        if (primes->at(i)) {
            for (int64_t j = i * i; j < LENGTH; j += i) {
                primes->at(j) = false;
            }
        }
    }
    return primes;
}
Exemple #10
0
void Ave::start(Context &context) {
    using std::ceil;

    geoSegment = &context.getSegment(Constants::SEGMENT_GEO);
    sourceSegment = &context.getSegment(Constants::SEGMENT_SYN_COLLOCATED);

    getAuxdataProvider(context, Constants::AUX_ID_SYCP).getUByte("ave_square", averagingFactor);

    const Grid &sourceGrid = sourceSegment->getGrid();
    //const size_t sizeL = sourceGrid.getSizeL() / averagingFactor;
    const size_t sizeM = ceil(sourceGrid.getSizeM() / double(averagingFactor));
    const size_t sizeK = sourceGrid.getSizeK();
    const size_t maxL = ceil((sourceGrid.getMaxL() - sourceGrid.getMinL() + 1) / double(averagingFactor)) - 1;
    targetSegment = &context.addSwathSegment(Constants::SEGMENT_SYN_AVERAGED, maxL + 1, sizeM, sizeK, 0, maxL);

    addVariables(context);
}
Exemple #11
0
  static source_type nearbyint ( argument_type s )
  {
#if !defined(BOOST_NO_STDC_NAMESPACE)
    using std::floor ;
    using std::ceil  ;
#endif

    return s < static_cast<S>(0) ? ceil(s) : floor(s) ;
  }
Exemple #12
0
Matrix::pVector SymMatrix::GetEigenvalueRange(int indexOfLow, int indexOfHigh)
{
   assert(indexOfLow >= 0);
   assert(indexOfLow <= indexOfHigh);
   assert(indexOfHigh < GetSize());
     //lapack parameter list
   char jobz = 'N';//compute eigenvalues only
   char range = 'I';//all eigenvalues will be found
   char uplo = 'U';//upper triangle of A is stored
   int n = GetSize();
   int lda = GetSize();
   double vl, vu;//no referenced when range = 'A' or 'I'
   int il = indexOfLow + 1, iu = indexOfHigh + 1;//1<= il <= iu <= N
   double abstol = 0;//absolute error tolerance for the eigenvalues
   int m;//the total number of eigenvalues found
   vector<double> w(n);//the first m elements contain the selected
                       //eigenvalues in ascending order
   vector<double> z(n*n);//not referenced when jobz = 'N', but this
			 //reserved space
   int ldz = n;//the leading dimension of the array z
   vector<int> isuppz(2 * n);//the support of the eigenvectors in Z
   int info;
   //got the optimal size of workspace
   int lwork = -1;//the dimension of the array work
   int liwork = -1;//the dimension of the array iwork
   vector<double> work(26 * n);//workspace
   vector<int> iwork(10 * n);//workspace
   //query the optimal size
   dsyevr_(&jobz, &range, &uplo, &n, GetData(), &lda, &vl, &vu, &il, &iu, &abstol,
	   &m, w.data(), z.data(), &ldz, isuppz.data(), work.data(), &lwork,
	   iwork.data(), &liwork, &info);
   if(info == 0)
   {//succeed
      lwork = ceil(work[0]);
      liwork = iwork[0];
      //reallocate
      work.resize(lwork);
      iwork.resize(liwork);
   }
   else
   {
      return pVector();
   }
   //compute
   dsyevr_(&jobz, &range, &uplo, &n, GetData(), &lda, &vl, &vu, &il, &iu, &abstol,
	   &m, w.data(), z.data(), &ldz, isuppz.data(), work.data(), &lwork,
	   iwork.data(), &liwork, &info);
   if(info == 0)
   {
      pVector result(new Vector());
      result->assign(w.begin(), w.begin() + (indexOfHigh - indexOfLow) + 1);
      return result;
   }
   else
      return pVector();
}
inline double rng_dweibull(double q, double beta,
                           bool& throw_warning) {
  if (ISNAN(q) || ISNAN(beta) || q <= 0.0 || q >= 1.0 ||
      beta <= 0.0) {
    throw_warning = true;
    return NA_REAL;
  }
  double u = rng_unif();
  return ceil(pow(log(u)/log(q), 1.0/beta) - 1.0);
}
inline double invcdf_dweibull(double p, double q, double beta,
                              bool& throw_warning) {
#ifdef IEEE_754
  if (ISNAN(p) || ISNAN(q) || ISNAN(beta))
    return p+q+beta;
#endif
  if (q <= 0.0 || q >= 1.0 || beta <= 0.0 || !VALID_PROB(p)) {
    throw_warning = true;
    return NAN;
  }
  if (p == 0.0)
    return 0.0;
  return ceil(pow(log(1.0 - p)/log(q), 1.0/beta) - 1.0);
}
Exemple #15
0
Bitmap::Bitmap( std::string filename ) {
	using std::ceil;

	file = PNG::load( filename );

	intensityMap = new unsigned char[file->w * file->h];
	unsigned char *imPtr = intensityMap, *cPtr = file->data;

	for (unsigned int y = 0; y < file->h; y++) {
		for (unsigned int x = 0; x < file->w; x++, imPtr++, cPtr+=4) {
			*imPtr = 255 - (unsigned char)ceil(((float)(*(cPtr)) * 0.2126 + (float)(*(cPtr+1)) * 0.7152 + (float)(*(cPtr+2)) * 0.0722));
		}
	}
}
Exemple #16
0
int calculate_size(const Eigen::VectorXd& x, 
                   const std::string& name,
                   const int digits,
                   std::ios_base::fmtflags& format) {
  using std::max;
  using std::ceil;
  using std::log10;
  
  double padding = 0;
  if (digits > 0)
    padding = digits + 1;

  double fixed_size = 0.0;
  if (x.maxCoeff() > 0)
    fixed_size = ceil(log10(x.maxCoeff()+0.001)) + padding;
  if (x.minCoeff() < 0)
    fixed_size = max(fixed_size, ceil(log10(-x.minCoeff()+0.01))+(padding+1));
  format = std::ios_base::fixed;
  if (fixed_size < 7) {
    return max(fixed_size,
               max(name.length(), std::string("-0.0").length())+0.0);
  }

  double scientific_size = 0;
  scientific_size += 4.0;   // "-0.0" has four digits
  scientific_size += 1.0;   // e
  double exponent_size = 0;
  if (x.maxCoeff() > 0)
    exponent_size = ceil(log10(log10(x.maxCoeff())));
  if (x.minCoeff() < 0)
    exponent_size = max(exponent_size,
                        ceil(log10(log10(-x.minCoeff()))));
  scientific_size += fmin(exponent_size, 3);
  format = std::ios_base::scientific;
  return scientific_size;
}
Exemple #17
0
void test_round_even()
{
  cout << "Testing 'RoundEven' tie-breaking\n";

  double min = boost::numeric::bounds<double>::lowest();
  double max = boost::numeric::bounds<double>::highest();

#if !defined(BOOST_NO_STDC_NAMESPACE)
  using std::floor ;
  using std::ceil ;
#endif
  test_round_even(min, floor(min));
  test_round_even(max, ceil (max));
  test_round_even(2.0, 2.0);
  test_round_even(2.3, 2.0);
  test_round_even(2.5, 2.0);
  test_round_even(2.7, 3.0);
  test_round_even(3.0, 3.0);
  test_round_even(3.3, 3.0);
  test_round_even(3.5, 4.0);
  test_round_even(3.7, 4.0);
}
  static source_type nearbyint ( argument_type s )
  {
    // Algorithm contributed by Guillaume Melquiond
    
#if !defined(BOOST_NO_STDC_NAMESPACE)
    using std::floor ;
    using std::ceil  ;
#endif    

    // only works inside the range not at the boundaries
    S a = floor(s); 
    S b = ceil(s);  
    
    S c = (s - a) - (b - s); // the "good" subtraction
    
    if ( c < static_cast<S>(0.0) ) 
      return a;
    else if ( c >  static_cast<S>(0.0) )
      return b;
    else 
      return 2 * floor(b / static_cast<S>(2.0)); // needs to behave sanely
  }
Exemple #19
0
TEST(AgradFwdCeil,Fvar) {
  using stan::math::fvar;
  using std::ceil;

  fvar<double> x(0.5,1.0);
  fvar<double> y(2.0,2.0);

  fvar<double> a = ceil(x);
  EXPECT_FLOAT_EQ(ceil(0.5), a.val_);
  EXPECT_FLOAT_EQ(0, a.d_);

  fvar<double> b = ceil(y);
  EXPECT_FLOAT_EQ(ceil(2.0), b.val_);
   EXPECT_FLOAT_EQ(0.0, b.d_);

  fvar<double> c = ceil(2 * x);
  EXPECT_FLOAT_EQ(ceil(2 * 0.5), c.val_);
   EXPECT_FLOAT_EQ(0.0, c.d_);
}
Exemple #20
0
 static auto UnaryOp(T t)
 {
     using std::ceil;
     return ceil(t);
 }
Exemple #21
0
std::vector<T> legendre_p_zeros_imp(int n, const Policy& pol)
{
    using std::cos;
    using std::sin;
    using std::ceil;
    using std::sqrt;
    using boost::math::constants::pi;
    using boost::math::constants::half;
    using boost::math::tools::newton_raphson_iterate;

    BOOST_ASSERT(n >= 0);
    std::vector<T> zeros;
    if (n == 0)
    {
        // There are no zeros of P_0(x) = 1.
        return zeros;
    }
    int k;
    if (n & 1)
    {
        zeros.resize((n-1)/2 + 1, std::numeric_limits<T>::quiet_NaN());
        zeros[0] = 0;
        k = 1;
    }
    else
    {
        zeros.resize(n/2, std::numeric_limits<T>::quiet_NaN());
        k = 0;
    }
    T half_n = ceil(n*half<T>());

    while (k < (int)zeros.size())
    {
        // Bracket the root: Szego:
        // Gabriel Szego, Inequalities for the Zeros of Legendre Polynomials and Related Functions, Transactions of the American Mathematical Society, Vol. 39, No. 1 (1936)
        T theta_nk =  ((half_n - half<T>()*half<T>() - static_cast<T>(k))*pi<T>())/(static_cast<T>(n)+half<T>());
        T lower_bound = cos( (half_n - static_cast<T>(k))*pi<T>()/static_cast<T>(n + 1));
        T cos_nk = cos(theta_nk);
        T upper_bound = cos_nk;
        // First guess follows from:
        //  F. G. Tricomi, Sugli zeri dei polinomi sferici ed ultrasferici, Ann. Mat. Pura Appl., 31 (1950), pp. 93-97;
        T inv_n_sq = 1/static_cast<T>(n*n);
        T sin_nk = sin(theta_nk);
        T x_nk_guess = (1 - inv_n_sq/static_cast<T>(8) + inv_n_sq /static_cast<T>(8*n) - (inv_n_sq*inv_n_sq/384)*(39  - 28 / (sin_nk*sin_nk) ) )*cos_nk;

        boost::uintmax_t number_of_iterations = policies::get_max_root_iterations<Policy>();

        legendre_p_zero_func<T, Policy> f(n, pol);

        const T x_nk = newton_raphson_iterate(f, x_nk_guess,
                                              lower_bound, upper_bound,
                                              policies::digits<T, Policy>(),
                                              number_of_iterations);

        BOOST_ASSERT(lower_bound < x_nk);
        BOOST_ASSERT(upper_bound > x_nk);
        zeros[k] = x_nk;
        ++k;
    }
    return zeros;
}
Exemple #22
0
void colorize(const Image<uint32_t> &input, const Image<uint32_t> &strokes, Image<uint32_t> &output) {
    int w     = input.width();
    int h     = input.height();
    int x,y;

    int max_d          = floor(log(min(h,w))/log(2)-2);
    float scale_factor = 1.0f/( pow(2,max_d-1) );
    int padded_w       = ceil(w*scale_factor)*pow(2,max_d-1);
    int padded_h       = ceil(h*scale_factor)*pow(2,max_d-1);

    // RGB 2 YUV and padarray
    Image<float> yuv_fused(padded_w,padded_h,3);
    hl_fuse_yuv(input, strokes, yuv_fused);


    // Extract Strokes mask
    Image<float> stroke_mask(padded_w, padded_h);
    hl_nonzero(strokes,stroke_mask);

    Image<float> result(padded_w,padded_h,3);

    int n = padded_h;
    int m = padded_w;
    int k = 1;

    Tensor3d D,G,I;
    Tensor3d Dx,Dy,iDx,iDy;
    MG smk;
    G.set(n,m,k);
    D.set(n,m,k);
    I.set(n,m,k);

    int in_itr_num  = 5;
    int out_itr_num = 1;

    Dx.set(n,m,k-1);
    Dy.set(n,m,k-1);
    iDx.set(n,m,k-1);
    iDy.set(n,m,k-1);

    // Fill in label mask and luminance channels
    for ( y = 0; y<n; y++){
        for ( x = 0; x<m; x++){
            I(y,x,0) = stroke_mask(x,y);
            G(y,x,0) = yuv_fused(x,y,0);
            I(y,x,0) = !I(y,x,0);
        }
    }

    // Write output luminance
    for ( y=0; y<n; y++){
        for ( x=0; x<m; x++){
            result(x,y,0)=G(y,x,0);
        }
    }

    smk.set(n,m,k,max_d);
    smk.setI(I) ;
    smk.setG(G);
    smk.setFlow(Dx,Dy,iDx,iDy);

    // Solve chrominance
    for (int t=1; t<3; t++){
        for ( y=0; y<n; y++){
            for ( x=0; x<m; x++){
                D(y,x,0)       = yuv_fused(x,y,t);
                smk.P()(y,x,0) = yuv_fused(x,y,t);
                D(y,x,0)      *= (!I(y,x,0));
            }
        }

        smk.Div() = D ;

        Tensor3d tP2;

        for (int itr=0; itr<out_itr_num; itr++){
            smk.setDepth(max_d);
            Field_MGN(&smk, in_itr_num, 2) ;
            smk.setDepth(ceil(max_d/2));
            Field_MGN(&smk, in_itr_num, 2) ;
            smk.setDepth(2);
            Field_MGN(&smk, in_itr_num, 2) ;
            smk.setDepth(1);
            Field_MGN(&smk, in_itr_num, 4) ;
        }

        tP2 = smk.P();

        for ( y=0; y<n; y++){
            for ( x=0; x<m; x++){
                result(x,y,t) = tP2(y,x,0);
            }
        }
    }
    
    hl_yuv2rgb(result,output);
    

}
Exemple #23
0
std::pair< Point<float>, float > Stippler::calculateCellCentroid( Point<float> &inside, EdgeList &edgeList ) {
	using std::make_pair;
	using std::numeric_limits;
	using std::vector;
	using std::floor;
	using std::ceil;
	using std::abs;
	using std::sqrt;
	using std::pow;

	vector< Line<float> > clipLines;
	Extents<float> extent = getCellExtents(edgeList);

	unsigned int x, y;

	float xDiff = ( extent.maxX - extent.minX );
	float yDiff = ( extent.maxY - extent.minY );

	unsigned int tileWidth = (unsigned int)ceil(xDiff) * parameters.subpixels;
	unsigned int tileHeight = (unsigned int)ceil(yDiff) * parameters.subpixels;

	float xStep = xDiff / (float)tileWidth;
	float yStep = yDiff / (float)tileHeight;

	float spotDensity, areaDensity = 0.0f, maxAreaDensity = 0.0f;
	float xSum = 0.0f;
	float ySum = 0.0f;

	float xCurrent;
	float yCurrent;

	// compute the clip lines
	for ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {
		Line<float> l = createClipLine( inside.x, inside.y, 
			value_iter->begin.x, value_iter->begin.y,
			value_iter->end.x, value_iter->end.y );
	
		if (l.a < numeric_limits<float>::epsilon() && abs(l.b) < numeric_limits<float>::epsilon()) {
			continue;
		}

		clipLines.push_back(l);
	}

	for ( y = 0, yCurrent = extent.minY; y < tileHeight; ++y, yCurrent += yStep ) {
		for ( x = 0, xCurrent = extent.minX; x < tileWidth; ++x, xCurrent += xStep ) {
			// a point is outside of the polygon if it is outside of all clipping planes
			bool outside = false;
			for ( vector< Line<float> >::iterator iter = clipLines.begin(); iter != clipLines.end(); iter++ ) {
				if ( xCurrent * iter->a + yCurrent * iter->b + iter->c >= 0.0f ) {
					outside = true;
					break;
				}
			}

			if (!outside) {
				spotDensity = image.getIntensity(xCurrent, yCurrent);

				areaDensity += spotDensity;
				maxAreaDensity += 255.0f;
				xSum += spotDensity * xCurrent;
				ySum += spotDensity * yCurrent;
			}
		}
	}

	float area = areaDensity * xStep * yStep / 255.0f;
	float maxArea = maxAreaDensity * xStep * yStep / 255.0f;

	Point<float> pt;
	if (areaDensity > numeric_limits<float>::epsilon()) {
		pt.x = xSum / areaDensity;
		pt.y = ySum / areaDensity;
	} else {
		// if for some reason, the cell is completely white, then the centroid does not move
		pt.x = inside.x;
		pt.y = inside.y;
	}

	float closest = numeric_limits<float>::max(),
		  farthest = numeric_limits<float>::min(),
		  distance;
	float x0 = pt.x, y0 = pt.y,
	      x1, x2, y1, y2;

	for ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {
		x1 = value_iter->begin.x; x2 = value_iter->end.x;
		y1 = value_iter->begin.y; y2 = value_iter->end.y;

		distance = abs( ( x2 - x1 ) * ( y1 - y0 ) - ( x1 - x0 ) * ( y2 - y1 ) ) / sqrt( pow( x2 - x1, 2.0f ) + pow( y2 - y1, 2.0f ) );
		if ( closest > distance ) {
			closest = distance;
		}
		if ( farthest < distance ) {
			farthest = distance;
		}
	}

	float radius;
	if ( parameters.noOverlap ) {
		radius = closest;
	} else {
		radius = farthest;
	}
	radius *= area / maxArea;

	return make_pair( pt, radius );
}
Exemple #24
0
  bool SpinDensity::put(xmlNodePtr cur)
  {
    using std::ceil;
    using std::sqrt;
    reset();
    string write_report = "no";
    OhmmsAttributeSet attrib;
    attrib.add(myName,"name");
    attrib.add(write_report,"report");
    attrib.put(cur);

    bool have_dr = false;
    bool have_grid = false;
    bool have_center = false;
    bool have_corner = false;
    bool have_cell = false;

    PosType dr;
    PosType center;
    Tensor<RealType,DIM> axes;

    int test_moves = 0;

    xmlNodePtr element = cur->xmlChildrenNode;
    while(element!=NULL)
    {
      string ename((const char*)element->name);
      if(ename=="parameter")
      {
        string name((const char*)(xmlGetProp(element,(const xmlChar*)"name")));
        if(name=="dr")      
        {
          have_dr = true;
          putContent(dr,element);   
        }
        else if(name=="grid") 
        {
          have_grid = true;
          putContent(grid,element);        
        }
        else if(name=="corner") 
        {
          have_corner = true;
          putContent(corner,element);        
        }
        else if(name=="center") 
        {
          have_center = true;
          putContent(center,element);        
        }
        else if(name=="cell") 
        {
          have_cell = true;
          putContent(axes,element);        
        }
        else if(name=="test_moves") 
          putContent(test_moves,element);        
      }
      element = element->next;
    }

    if(have_dr && have_grid)
    {
      APP_ABORT("SpinDensity::put  dr and grid are provided, this is ambiguous");
    }
    else if(!have_dr && !have_grid)
      APP_ABORT("SpinDensity::put  must provide dr or grid");

    if(have_corner && have_center)
      APP_ABORT("SpinDensity::put  corner and center are provided, this is ambiguous");
    if(have_cell)
    {
      cell.set(axes);
      if(!have_corner && !have_center)
        APP_ABORT("SpinDensity::put  must provide corner or center");
    }
    else
      cell = Ptmp->Lattice;

    if(have_center)
      corner = center-cell.Center;

    if(have_dr)
      for(int d=0;d<DIM;++d)
        grid[d] = (int)ceil(sqrt(dot(cell.Rv[d],cell.Rv[d]))/dr[d]);

    npoints = 1;
    for(int d=0;d<DIM;++d)
      npoints *= grid[d];
    gdims[0] = npoints/grid[0];
    for(int d=1;d<DIM;++d)
      gdims[d] = gdims[d-1]/grid[d];

    if(write_report=="yes")
      report("  ");
    if(test_moves>0)
      test(test_moves,*Ptmp);

    return true;
  }
Exemple #25
0
void NGC_Exporter::export_layer(shared_ptr<Layer> layer, string of_name)
{
    string layername = layer->get_name();
    shared_ptr<RoutingMill> mill = layer->get_manufacturer();
    bool bAutolevelNow;
    vector<shared_ptr<icoords> > toolpaths = layer->get_toolpaths();
    vector<unsigned int> bridges;
    vector<unsigned int>::const_iterator currentBridge;

    double xoffsetTot;
    double yoffsetTot;
    Tiling tiling( tileInfo, cfactor );
    tiling.setGCodeEnd(string("\nG04 P0 ( dwell for no time -- G64 should not smooth over this point )\n")
        + (bZchangeG53 ? "G53 " : "") + "G00 Z" + str( format("%.3f") % ( mill->zchange * cfactor ) ) + 
        " ( retract )\n\n" + postamble + "M5 ( Spindle off. )\nG04 P" +
        to_string(mill->spindown_time) +
        "\nM9 ( Coolant off. )\n"
        "M2 ( Program end. )\n\n" );

    tiling.initialXOffsetVar = globalVars.getUniqueCode();
    tiling.initialYOffsetVar = globalVars.getUniqueCode();

    // open output file
    std::ofstream of;
    of.open(of_name.c_str());

    // write header to .ngc file
    for ( string s : header )
    {
        of << "( " << s << " )\n";
    }

    if( ( bFrontAutoleveller && layername == "front" ) ||
        ( bBackAutoleveller && layername == "back" ) )
        bAutolevelNow = true;
    else
        bAutolevelNow = false;

    if( bAutolevelNow || ( tileInfo.enabled && tileInfo.software != CUSTOM ) )
        of << "( Gcode for " << getSoftwareString(tileInfo.software) << " )\n";
    else
        of << "( Software-independent Gcode )\n";

    of.setf(ios_base::fixed);      //write floating-point values in fixed-point notation
    of.precision(5);              //Set floating-point decimal precision

    of << "\n" << preamble;       //insert external preamble

    if (bMetricoutput)
    {
        of << "G94 ( Millimeters per minute feed rate. )\n"
           << "G21 ( Units == Millimeters. )\n\n";
    }
    else
    {
        of << "G94 ( Inches per minute feed rate. )\n"
           << "G20 ( Units == INCHES. )\n\n";
    }

    of << "G90 ( Absolute coordinates. )\n"
       << "S" << left << mill->speed << " ( RPM spindle speed. )\n";

    if (mill->explicit_tolerance)
        of << "G64 P" << mill->tolerance * cfactor << " ( set maximum deviation from commanded toolpath )\n";

    of << "F" << mill->feed * cfactor << " ( Feedrate. )\n\n";

    if( bAutolevelNow )
    {
        if( !leveller->prepareWorkarea( toolpaths ) )
        {
            std::cerr << "Required number of probe points (" << leveller->requiredProbePoints() <<
                      ") exceeds the maximum number (" << leveller->maxProbePoints() << "). "
                      "Reduce either al-x or al-y." << std::endl;
            exit(EXIT_FAILURE);
        }

        leveller->header( of );
    }

    of << "F" << mill->feed * cfactor << " ( Feedrate. )\n"
       << "M3 ( Spindle on clockwise. )\n"
       << "G04 P" << mill->spinup_time << "\n";
    
    tiling.header( of );

    for( unsigned int i = 0; i < tileInfo.forYNum; i++ )
    {
        yoffsetTot = yoffset - i * tileInfo.boardHeight;
        
        for( unsigned int j = 0; j < tileInfo.forXNum; j++ )
        {
            xoffsetTot = xoffset - ( i % 2 ? tileInfo.forXNum - j - 1 : j ) * tileInfo.boardWidth;

            if( tileInfo.enabled && tileInfo.software == CUSTOM )
                of << "( Piece #" << j + 1 + i * tileInfo.forXNum << ", position [" << j << ";" << i << "] )\n\n";

            // contours
            for ( shared_ptr<icoords> path : toolpaths )
            {
                // retract, move to the starting point of the next contour
                of << "G04 P0 ( dwell for no time -- G64 should not smooth over this point )\n";
                of << "G00 Z" << mill->zsafe * cfactor << " ( retract )\n\n";
                of << "G00 X" << ( path->begin()->first - xoffsetTot ) * cfactor << " Y"
                   << ( path->begin()->second - yoffsetTot ) * cfactor << " ( rapid move to begin. )\n";

                /* if we're cutting, perhaps do it in multiple steps, but do isolations just once.
                 * i know this is partially repetitive, but this way it's easier to read
                 */
                shared_ptr<Cutter> cutter = dynamic_pointer_cast<Cutter>(mill);

                if (cutter && cutter->do_steps)
                {

                    //--------------------------------------------------------------------
                    //cutting (outline)

                    const unsigned int steps_num = ceil(-mill->zwork / cutter->stepsize);

                    if( bBridges )
                        if( i == 0 && j == 0 )  //Compute the bridges only the 1st time
                            bridges = layer->get_bridges( path );

                    for (unsigned int i = 0; i < steps_num; i++)
                    {
                        const double z = mill->zwork / steps_num * (i + 1);

                        of << "G01 Z" << z * cfactor << " F" << mill->vertfeed * cfactor << " ( plunge. )\n";
                        of << "G04 P0 ( dwell for no time -- G64 should not smooth over this point )\n";
                        of << "F" << mill->feed * cfactor << "\n";
                        of << "G01 ";

                        icoords::iterator iter = path->begin();
                        icoords::iterator last = path->end();      // initializing to quick & dirty sentinel value

                        if (bBridges)
                            currentBridge = bridges.begin();

                        while (iter != path->end())
                        {

                            of << "X" << ( iter->first - xoffsetTot ) * cfactor << " Y"
                               << ( iter->second - yoffsetTot ) * cfactor << '\n';

                            if (bBridges && currentBridge != bridges.end())
                            {
                                if (z < cutter->bridges_height)
                                {
                                    if (*currentBridge == iter - path->begin())
                                        of << "Z" << cutter->bridges_height * cfactor << '\n';
                                    else if (*currentBridge == last - path->begin())
                                    {
                                        of << "Z" << z * cfactor << " F" << cutter->vertfeed * cfactor << '\n';
                                        of << "F" << cutter->feed * cfactor << '\n';
                                        of << "G01 ";
                                    }
                                }

                                if (*currentBridge == last - path->begin())
                                    ++currentBridge;
                            }

                            last = iter;
                            ++iter;
                        }
                    }
                }
                else
                {
                    //--------------------------------------------------------------------
                    // isolating (front/backside)
                    of << "F" << mill->vertfeed * cfactor << '\n';

                    if( bAutolevelNow )
                    {
                        leveller->setLastChainPoint( icoordpair( ( path->begin()->first - xoffsetTot ) * cfactor,
                                                     ( path->begin()->second - yoffsetTot ) * cfactor ) );
                        of << leveller->g01Corrected( icoordpair( ( path->begin()->first - xoffsetTot ) * cfactor,
                                                      ( path->begin()->second - yoffsetTot ) * cfactor ) );
                    }
                    else
                        of << "G01 Z" << mill->zwork * cfactor << "\n";

                    of << "G04 P0 ( dwell for no time -- G64 should not smooth over this point )\n";
                    of << "F" << mill->feed * cfactor << '\n';

                    if (!bAutolevelNow)
                        of << "G01 ";

                    icoords::iterator iter = path->begin();

                    while (iter != path->end())
                    {
                        if( bAutolevelNow )
                            of << leveller->addChainPoint( icoordpair( ( iter->first - xoffsetTot ) * cfactor,
                                                                           ( iter->second - yoffsetTot ) * cfactor ) );
                        else
                            of << "X" << ( iter->first - xoffsetTot ) * cfactor << " Y"
                               << ( iter->second - yoffsetTot ) * cfactor << '\n';
                        ++iter;
                    }
                }
            }
        }
    }
    
    tiling.footer( of );

    if( bAutolevelNow )
    {
        leveller->footer( of );
    }

    of.close();
}
Exemple #26
0
inline double round(double x) {
	return (x > 0.0) ? floor(x + 0.5) : ceil(x - 0.5);
}
Exemple #27
0
 inline T0
 operator()(const T0& arg1) const {
   return ceil(arg1);
 }