int main(int argc, char *argv[]){
  // 物理定数を定義(Fe)
  material_t material = setup_material(0.4174, 1.3885, 2.845);
  // 座標長さ1における実際の長さ(格子定数)
  float length = 2.9098453;
  // float length = 2 * material.r0 / sqrt(3);
  // 座標ファイルの読み込み
  FILE *rfp = read_file();

  // ファイル一行目から総原子数を求め、atoms配列を定義
  long atoms_number;
  fscanf(rfp, "%ld", &atoms_number);
  atom_t atoms[atoms_number];

  // atomsに座標を代入(bcc_structure.h参照)
  input_structure(rfp, atoms, atoms_number);

  fclose(rfp);

  // 総原子数から構造の大きさを求める(原子間距離を原子半径の2倍と仮定)
  int structure_length = cbrt(atoms_number / 2.0);
  // float structure_size = structure_length * material.r0 * 2.0;

  // // 結合エネルギが有効数字内で変化しなくなる距離を計算し、一辺を何回ループするか決定(すべての原子が同じ物理定数を持つと仮定)
  // int loop_number = eval_loop_number(material, structure_size);

  // // 拡張したatomsを作成
  // long extended_atoms_number = atoms_number * pow(loop_number, 3);
  // atom_t extended_atoms[extended_atoms_number];

  // // 拡張したatomsに座標を定義
  // initialize_extended_structure(extended_atoms, atoms, atoms_number, structure_length, loop_number);

  // // エネルギーを計算
  // eval_energy(atoms, atoms_number, extended_atoms, extended_atoms_number, material);
  eval_energy_ex(atoms, atoms_number, material, structure_length, length);

  // 出力
  FILE *wfp = write_file();
  output_structure(wfp, atoms, atoms_number);
  fclose(wfp);

  return 0;
}
Exemple #2
0
/**
 *  \brief
 *      Returns the three roots of the cubic equation with real coefficients.
 *
 *  \details
 *      Returns the three roots of the cubic equation;
 *
 *              \f[z^3 + b z^2 + c z + d = 0,\f]
 *
 *      where \f$b, c, d\f$ are real coefficients, and the coefficient on the
 *      \f$x^3\f$ term is assumed to be 1.
 *
 *      \param[in]      b   Real coefficient of the \f$z^2\f$ term.
 *      \param[in]      c   Real coefficient of the \f$z\f$ term.
 *      \param[in]      d   Real constant term.
 *      \param[out]     z1  First real root.
 *      \param[out]     z2  Second (possibly complex) root.
 *      \param[out]     z3  Third (possibly complex) root.
 *
 *      \return         The number of real roots
 *
 *      \author         Mike Henderson
 *      \date           2011
 *
 */
int  Lgm_CubicRoots( double b, double c, double d, double *z1, double complex *z2, double complex *z3 ){

    int     nReal;
    double  b2, Q, R, D2, D, RpD, RmD, S, T, Theta, SqrtNQ, f, g, h;

    b2 = b*b;

    Q  = (3.0*c - b2)/9.0;
    R  = (9.0*b*c - 27.0*d - 2.0*b2*b)/54.0;
    D2 = Q*Q*Q + R*R;

    if (D2 == 0){
        // All 3 roots are real and at least two are equal.
        if ( R > 0.0) {
            f = cbrt( R );
            *z1 = 2.0*f - b/3.0;
            *z2 = *z3 = -f - b/3.0;
        } else {
            f = -cbrt( -R );
            *z1 = 2.0*f - b/3.0;
            *z2 = *z3 = -f - b/3.0;
        }
        nReal = 3;
    } else if ( D2 > 0 ) {
        // only one real root exists. The other two are complex conjugates.
        D = sqrt(D2); RpD = R+D; RmD = R-D;
        S = (RpD > 0.0) ? cbrt( RpD ) : -cbrt( -RpD );
        T = (RmD > 0.0) ? cbrt( RmD ) : -cbrt( -RmD);
        f = S+T;
        g = sqrt(3.0)/2.0*(S-T);
        h = b/3.0;
        *z1 = f - h;
        *z2 = -0.5*f - h + g*I;
        *z3 = -0.5*f - h - g*I;
        nReal = 1;

    } else if ( D2 < 0 ) {
        // All three roots are real and unequal.
        // This uses the simplest of the alternative trig forms.
        SqrtNQ = sqrt(-Q);
        Theta = acos( R/(SqrtNQ*fabs(Q)) );
        *z1 = 2.0*SqrtNQ*cos(Theta/3.0) - b/3.0; // real (returned as real double z1)
        *z2 = 2.0*SqrtNQ*cos( (Theta + 2.0*M_PI)/3.0 ) - b/3.0; // real (but returned as double complex z2)
        *z3 = 2.0*SqrtNQ*cos( (Theta + 4.0*M_PI)/3.0 ) - b/3.0; // real (but returned as double complex z3)
        nReal = 3;

    }

    return( nReal );

}
Exemple #3
0
std::pair<int, long long> recursion(long long n)
{
	if (n == 0 || cf[n].first != 0)
	{
		return cf[n];
	}
	long long a = (long long)cbrt(n);
	long long b = a-1;
	std::pair<int, long long> ap = recursion(n - a*a*a), bp = recursion(a*a*a - b*b*b - 1);
	if (ap.first >= bp.first)
	{
		cf[n] = std::make_pair(ap.first+1, ap.second + a*a*a);
	}
	else
	{
		cf[n] = std::make_pair(bp.first+1, bp.second + b*b*b);
	}
	return cf[n];
}
Exemple #4
0
double dnormv (double *in, int size, int norm)
{
	double sum = 0;
	double res = 0;
	int counter = 0;

	switch (norm)
	{
		case 0:
			res = INFINITY;
			break;
		case 1:  /*Addition of all elements*/
			for (counter=0; counter < size; counter++)
			{
				sum += in[counter];
			}
			res = sum;
			break;
		case 2: /*Square root of addition of squares of all elements*/
			for (counter=0; counter < size; counter++)
			{
				sum += in[counter]*in[counter];
			}
			res = sqrt(sum);
			break;
		case 3: /*Cube root of addition of cubes of all elements*/
			for (counter=0; counter < size; counter++)
			{
				sum += pow(in[counter],3);
			}
			res = cbrt(sum);
			break;
		default : /*Nth root of addition of all elements raised to n*/
			for (counter=0; counter < size; counter++)
			{
				sum += pow(in[counter],norm);
			}
			res = pow(sum, 1./norm);
			break;
	}

	return res;
}
Foam::tmp<Foam::volScalarField> Foam::diameterModels::ADD::tauC() const
{
    //- Phase fraction
    const volScalarField& alpha = phase_;
    //- Turbulent kinetic energy
    const volScalarField& k = phase_.turbulence().k();

    return
    Cc_*
    (
        cbrt
        (
            constant::mathematical::pi/6.0
           *(alphaMax_ - alpha)/
            max(alpha,SMALL)
        )
       *d_/sqrt(2.0/3.0*k)
    );
}
Exemple #6
0
void test_fp_cbrt( void )
{
#if __STDC_VERSION__ >= 199901L
    printf( "Testing C99 cube root function...\n" );

    VERIFY( CompDbl( cbrt( 0.0 ), 0.0 ) );
    VERIFY( CompDbl( cbrt( 27.0 ), 3.0 ) );
    VERIFY( CompDbl( cbrt( -27.0 ), -3.0 ) );
    
    VERIFY( isnan(cbrt( NAN )) );
    VERIFY( cbrt( INFINITY ) == INFINITY );
    VERIFY( cbrt( -INFINITY ) == -INFINITY );
#endif
}
Exemple #7
0
void PelletAgglomerator::run(){
	//DemField& dem(field->cast<DemField>());
	// loop over all source particles, and loop over all contacts of each of them
	if(isnan(massIncPerRad)) throw std::runtime_error("PalletAgglomerator.massIncPerRad==NaN (must be specified)");
	if(dampHalfLife<0) dampHalfLife*=-scene->dt;
	Real sumDMass=0.;
	Real lambda=(dampHalfLife==0 || isnan(dampHalfLife))?0:(log(2)/dampHalfLife);
	for(const shared_ptr<Particle>& src: agglomSrcs){
		for(const auto& idCon: src->contacts){
			const shared_ptr<Contact>& c(idCon.second);
			if(!c->isReal()) continue;
			Particle* other(c->leakOther(src.get()));
			Real* radius=nullptr;
			// if(!other->shape->isA<Sphere>()) continue; // other particles is not a sphere
			if(other->shape->isA<Sphere>()) radius=&(other->shape->cast<Sphere>().radius);
			else if(other->shape->isA<Capsule>()) radius=&(other->shape->cast<Capsule>().radius);
			else continue;
			assert(dynamic_pointer_cast<L6Geom>(c->geom));
			// radius change
			// angVel is local already
			Real dMass=c->geom->cast<L6Geom>().angVel.tail<2>().norm()*scene->dt*massIncPerRad;
			sumDMass+=dMass;
			Real newVol=(4/3.)*M_PI*pow(*radius,3)+dMass/other->material->density;
			*radius=cbrt(3*newVol/(4*M_PI));
			other->shape->updateMassInertia(other->material->density);
			if(!other->matState) other->matState=make_shared<PelletMatState>();
			assert(dynamic_pointer_cast<PelletMatState>(other->matState));
			auto& pms=other->matState->cast<PelletMatState>();
			if(pms.stepAgglomUpdated!=scene->step){ pms.agglomRate=0.; pms.stepAgglomUpdated=scene->step; } // reset value
			pms.agglomRate+=dMass/scene->dt;
			// rotation damping
			if(lambda>0){
				other->shape->nodes[0]->getData<DemData>().angVel*=(1-lambda*scene->dt);
			}
			boost::mutex::scoped_lock l(pms.lock);
			pms.cumAgglomMass+=dMass;
			pms.cumAgglomAngle+=c->geom->cast<L6Geom>().angVel.tail<2>().norm()*scene->dt;
		}
	}
	currRate=(1-currRateSmooth)*currRate+currRateSmooth*(sumDMass/scene->dt);
	mass+=sumDMass;
};
Exemple #8
0
void kdSmbhSoft(KD kd, int nSplitting)
{
  
  int i;
  double max_mass;
  
  // smbh particles are ones with the largest mass
  max_mass = kd->pInit[0].fMass;
  for (i=0;i<kd->nParticles;i++) {
    if (max_mass < kd->pInit[i].fMass) {
      max_mass = kd->pInit[i].fMass;
    }
  }
  
  fprintf(stderr, "MAX MASS = %f\n", max_mass);
  for (i=0;i<kd->nParticles;i++) 
    if(kd->pInit[i].fMass == max_mass) 
      kd->pInit[i].fSoft = kd->pInit[i].fSoft/cbrt((double)nSplitting);
    
}
Exemple #9
0
/*! \brief
 * Determines a suitable grid size.
 *
 * \param[in,out] d    Grid information.
 * \param[in]     pbc  Information about the box.
 * \returns  FALSE if grid search is not suitable.
 */
static gmx_bool
grid_setup_cells(gmx_ana_nbsearch_t *d, t_pbc *pbc)
{
    real targetsize;
    int  dd;

#ifdef HAVE_CBRT
    targetsize = cbrt(pbc->box[XX][XX] * pbc->box[YY][YY] * pbc->box[ZZ][ZZ]
                      * 10 / d->nref);
#else
    targetsize = pow(pbc->box[XX][XX] * pbc->box[YY][YY] * pbc->box[ZZ][ZZ]
                     * 10 / d->nref, 1./3.);
#endif

    d->ncells = 1;
    for (dd = 0; dd < DIM; ++dd)
    {
        d->ncelldim[dd] = (int)(pbc->box[dd][dd] / targetsize);
        d->ncells      *= d->ncelldim[dd];
        if (d->ncelldim[dd] < 3)
        {
            return FALSE;
        }
    }
    /* Reallocate if necessary */
    if (d->cells_nalloc < d->ncells)
    {
        int  i;

        srenew(d->ncatoms, d->ncells);
        srenew(d->catom, d->ncells);
        srenew(d->catom_nalloc, d->ncells);
        for (i = d->cells_nalloc; i < d->ncells; ++i)
        {
            d->catom[i]        = NULL;
            d->catom_nalloc[i] = 0;
        }
        d->cells_nalloc = d->ncells;
    }
    return TRUE;
}
Foam::tmp<Foam::volScalarField>
Foam::kineticTheoryModels::radialModels::SinclairJackson::g0prime
(
    const phaseModel& phase1,
 const phaseModel& phase2
) const
{
    volScalarField aByaMax
    (
        cbrt
        (
            min
            (
                max(phase1, scalar(1e-3)),
                alphaMinFriction_
            )/phase1.alphaMax()
        )
    );

    return (1.0/(3*phase1.alphaMax()))/sqr(aByaMax - sqr(aByaMax));
}
Exemple #11
0
// ratio = v0/v1.
inline double secant_rule(double x0,double x1,double ratio,
  int num_roots_in_cluster)
{
    switch(num_roots_in_cluster)
    {
     case 1:
      break;
     case 2:
      eprintf("disallowed");
      break;
     case 3:
      ratio = cbrt(ratio);
      break;
     default:
      assert_eq(1,num_roots_in_cluster%2);
      ratio = copysign(pow(fabs(ratio),1./num_roots_in_cluster),ratio);
    }
    double denominator = (1.-ratio);
    assert_gt(denominator,0.);
    return (x0-ratio*x1)/denominator;
}
Exemple #12
0
static void Test_alpha_epsilon(void) {
  printf("\n** Test_alpha_epsilon: **\n");
  const REAL8 f = 0.01;
  const REAL8 q = 4;
  const REAL8 chil = 0.5625;
  const REAL8 chip = 0.18;

  NNLOanglecoeffs angcoeffs;
  ComputeNNLOanglecoeffs(&angcoeffs,q,chil,chip);

  const REAL8 omega = LAL_PI * f;
  const REAL8 logomega = log(omega);
  const REAL8 omega_cbrt = cbrt(omega);
  const REAL8 omega_cbrt2 = omega_cbrt*omega_cbrt;
  const REAL8 alpha = (angcoeffs.alphacoeff1/omega
                    + angcoeffs.alphacoeff2/omega_cbrt2
                    + angcoeffs.alphacoeff3/omega_cbrt
                    + angcoeffs.alphacoeff4*logomega
                    + angcoeffs.alphacoeff5*omega_cbrt);

  const REAL8 epsilon = (angcoeffs.epsiloncoeff1/omega
                      + angcoeffs.epsiloncoeff2/omega_cbrt2
                      + angcoeffs.epsiloncoeff3/omega_cbrt
                      + angcoeffs.epsiloncoeff4*logomega
                      + angcoeffs.epsiloncoeff5*omega_cbrt);

  const REAL8 alpha_expected = -11.8196;
  const REAL8 epsilon_expected = -11.936;

  print_difference("alpha", alpha, alpha_expected);
  print_difference("epsilon", epsilon, epsilon_expected);

  const REAL8 eps = 1e-5;

  assert(
       approximatelyEqual(alpha,    alpha_expected,   eps)
    && approximatelyEqual(epsilon,  epsilon_expected, eps)
    && "Test_alpha_epsilon()"
  );
}
void Foam::WallLocalSpringSliderDashpot<CloudType>::findMinMaxProperties
(
    scalar& rMin,
    scalar& rhoMax,
    scalar& UMagMax
) const
{
    rMin = VGREAT;
    rhoMax = -VGREAT;
    UMagMax = -VGREAT;

    forAllConstIter(typename CloudType, this->owner(), iter)
    {
        const typename CloudType::parcelType& p = iter();

        // Finding minimum diameter to avoid excessive arithmetic

        scalar dEff = p.d();

        if (useEquivalentSize_)
        {
            dEff *= cbrt(p.nParticle()*volumeFactor_);
        }

        rMin = min(dEff, rMin);

        rhoMax = max(p.rho(), rhoMax);

        UMagMax = max
        (
            mag(p.U()) + mag(p.omega())*dEff/2,
            UMagMax
        );
    }

    // Transform the minimum diameter into minimum radius
    //     rMin = dMin/2

    rMin /= 2.0;
}
Exemple #14
0
void dump_histo_img(unsigned char* histo, unsigned int height, unsigned int width, const char *filename)
{
    RGB* pixel_map = (RGB*) malloc (height*width*sizeof(RGB));

    size_t y, x;
    for (y = 0; y < height; ++y)
    {
        for (x = 0; x < width; ++x)
        {
            unsigned char value = histo[y * width + x];

            if (value == 0){
                pixel_map[y*width+x].R = 0;
                pixel_map[y*width+x].G = 0;
                pixel_map[y*width+x].B = 0;
            } else {
                pixel_map[y*width+x] = HSVtoRGB(0.0,1.0,cbrt(1+ 63.0*((float)value)/((float)UINT8_MAX))/4);
            }
        }
    }
    create_bmp(pixel_map, height, width, filename);
    free(pixel_map);
}
Exemple #15
0
static TACommandVerdict cbrt_cmd(TAThread thread,TAInputStream stream)
{
    double x, res;

    // Prepare

    x = readDouble(&stream);
    
    START_TARGET_OPERATION(thread);
    
    // Execute

    res = cbrt(x);
    
    END_TARGET_OPERATION(thread);
    
    // Response
    
    writeDouble(thread, res);

    sendResponse(thread);
    return taDefaultVerdict;
}
Exemple #16
0
int engrid_scene(object ** list) {
  grid * g;
  int numobj, numcbrt;
  vector gmin, gmax;
  gridindex index;
 
  if (*list == NULL)
    return 0;

  numobj = countobj(*list);

  if ( !silent_mode )
    fprintf(stderr, "Scene contains %d bounded objects.\n", numobj);

  if (numobj > 16) {
    numcbrt = (int) cbrt(4*numobj);
    globalbound(list, &gmin, &gmax);

    g = (grid *) newgrid(numcbrt, numcbrt, numcbrt, gmin, gmax);
    engrid_objlist(g, list);

    numobj = countobj(*list);
    g->nextobj = *list;
    *list = (object *) g;

    /* now create subgrids.. */
    for (index.z=0; index.z<g->zsize; index.z++) {
      for (index.y=0; index.y<g->ysize; index.y++) {
        for (index.x=0; index.x<g->xsize; index.x++) {
          engrid_cell(g, &index);
        }
      }
    } 
  }

  return 1;
}
Exemple #17
0
long double
cbrtl(long double x) {
	long double s, t, r, w, y;
	double dx, dy;
	int *py = (int *) &dy;
	int n, m, m3, n0, sx;

	if (!finitel(x))
		return (x + x);
	if (iszerol(x))
		return (x);
	n0 = 0;
	if (*((int *) &d_one) == 0)
		n0 = 1;
	sx = signbitl(x);
	x = fabsl(x);
	n = ilogbl(x);
	m = n / 3;
	m3 = m + m + m;
	y = scalbnl(x, -m3);
	dx = (double) y;
	dy = cbrt(dx);
	py[1 - n0] += 2;
	if (py[1 - n0] == 0)
		py[n0] += 1;

	/* one step newton iteration to 113 bits with error < 0.667ulps */
	t = (long double) dy;
	t = scalbnl(t, m);
	s = t * t;
	r = x / s;
	w = t + t;
	r = (r - t) / (w + r);
	t += t * r;

	return (sx == 0 ? t : -t);
}
Exemple #18
0
void
imb_XYZ2Lab_tables( void )
{
	static int built_tables = 0;

	int was_built;
	int i;

	g_mutex_lock( im__global_lock );
	was_built = built_tables;
	built_tables = 1;
	g_mutex_unlock( im__global_lock );
	if( was_built )
		return;

	for( i = 0; i < QUANT_ELEMENTS; i++ ) {
		float Y = (double) i / QUANT_ELEMENTS;

		if( Y < 0.008856 ) 
			cbrt_table[i] = 7.787 * Y + (16.0 / 116.0);
		else 
			cbrt_table[i] = cbrt( Y );
	}
}
Exemple #19
0
 Matrix NumericalDerivatives::Hessian(const Vector &x,
                                      bool quick_and_dirty) const {
   int dim = x.size();
   SpdMatrix ans(x.size());
   const double tol = cbrt(std::numeric_limits<double>::epsilon());
   for (int i = 0; i < dim; ++i) {
     double hi = tol * std::max<double>(0.1, fabs(x[i]));
     int lo = quick_and_dirty ? i : 0;
     for (int j = lo; j < dim; ++j) {
       double hj = tol * std::max<double>(0.1, fabs(x[j]));
       if (i == j) {
         ans(i, j) = homogeneous_scalar_second_derivative(x, i, hi);
       } else {
         ans(i, j) = scalar_second_derivative(x, i, hi, j, hj);
       }
     }
   }
   if (quick_and_dirty) {
     ans.reflect();
   } else {
     ans = .5 * (ans + ans.transpose());
   }
   return std::move(ans);
 }
Exemple #20
0
DLLEXPORT int solveCubic(double c3, double c2, double c1, double c0, 
                         double & s0, double & s1, double & s2)
{
    int i, num;
    double  sub,
        A, B, C,
        sq_A, p, q,
        cb_p, D;

    if (isZero(c3))
        return solveQuadric(c2, c1, c0, s0, s1);

    // normalize the equation:x ^ 3 + Ax ^ 2 + Bx  + C = 0
    A = c2 / c3;
    B = c1 / c3;
    C = c0 / c3;

    // substitute x = y - A / 3 to eliminate the quadric term: x^3 + px + q = 0

    sq_A = A * A;
    p = 1.0/3.0 * (-1.0/3.0 * sq_A + B);
    q = 1.0/2.0 * (2.0/27.0 * A *sq_A - 1.0/3.0 * A * B + C);

    // use Cardano's formula

    cb_p = p * p * p;
    D = q * q + cb_p;

    if (isZero(D))
    {
        if (isZero(q))
        {
            // one triple solution
            s0 = 0.0;
            num = 1;
        }
        else
        {
            // one single and one double solution
            double u = cbrt(-q);
            s0 = 2.0 * u;
            s1 = - u;
            num = 2;
        }
    }
    else
        if (D < 0.0)
        {
            // casus irreductibilis: three real solutions
            double phi = 1.0/3.0 * acos(-q / sqrt(-cb_p));
            double t = 2.0 * sqrt(-p);
            s0 = t * cos(phi);
            s1 = -t * cos(phi + M_PI / 3.0);
            s2 = -t * cos(phi - M_PI / 3.0);
            num = 3;
        }
        else
        {
            // one real solution
            double sqrt_D = sqrt(D);
            double u = cbrt(sqrt_D + fabs(q));
            if (q > 0.0)
                s0 = - u + p / u ;
            else
                s0 = u - p / u;
            num = 1;
        }

        // resubstitute
        sub = 1.0 / 3.0 * A;
        s0 -= sub;
        s1 -= sub;
        s2 -= sub;
        return num;
}
Exemple #21
0
static double jnx(double n, double x)
{
    double zeta, sqz, zz, zp, np;
    double cbn, n23, t, z, sz;
    double pp, qq, z32i, zzi;
    double ak, bk, akl, bkl;
    int sign, doa, dob, nflg, k, s, tk, tkp1, m;
    static double u[8];
    static double ai, aip, bi, bip;

    /* Test for x very close to n. Use expansion for transition region if so. */
    cbn = cbrt(n);
    z = (x - n) / cbn;
    if (fabs(z) <= 0.7)
        return (jnt(n, x));

    z = x / n;
    zz = 1.0 - z * z;
    if (zz == 0.0)
        return (0.0);

    if (zz > 0.0) {
        sz = sqrt(zz);
        t = 1.5 * (log((1.0 + sz) / z) - sz);	/* zeta ** 3/2          */
        zeta = cbrt(t * t);
        nflg = 1;
    }
    else {
        sz = sqrt(-zz);
        t = 1.5 * (sz - acos(1.0 / z));
        zeta = -cbrt(t * t);
        nflg = -1;
    }
    z32i = fabs(1.0 / t);
    sqz = cbrt(t);

    /* Airy function */
    n23 = cbrt(n * n);
    t = n23 * zeta;

#if CEPHES_DEBUG
    printf("zeta %.5E, Airy(%.5E)\n", zeta, t);
#endif
    airy(t, &ai, &aip, &bi, &bip);

    /* polynomials in expansion */
    u[0] = 1.0;
    zzi = 1.0 / zz;
    u[1] = polevl(zzi, P1, 1) / sz;
    u[2] = polevl(zzi, P2, 2) / zz;
    u[3] = polevl(zzi, P3, 3) / (sz * zz);
    pp = zz * zz;
    u[4] = polevl(zzi, P4, 4) / pp;
    u[5] = polevl(zzi, P5, 5) / (pp * sz);
    pp *= zz;
    u[6] = polevl(zzi, P6, 6) / pp;
    u[7] = polevl(zzi, P7, 7) / (pp * sz);

#if CEPHES_DEBUG
    for (k = 0; k <= 7; k++)
        printf("u[%d] = %.5E\n", k, u[k]);
#endif

    pp = 0.0;
    qq = 0.0;
    np = 1.0;
    /* flags to stop when terms get larger */
    doa = 1;
    dob = 1;
    akl = NPY_INFINITY;
    bkl = NPY_INFINITY;

    for (k = 0; k <= 3; k++) {
        tk = 2 * k;
        tkp1 = tk + 1;
        zp = 1.0;
        ak = 0.0;
        bk = 0.0;
        for (s = 0; s <= tk; s++) {
            if (doa) {
                if ((s & 3) > 1)
                    sign = nflg;
                else
                    sign = 1;
                ak += sign * mu[s] * zp * u[tk - s];
            }

            if (dob) {
                m = tkp1 - s;
                if (((m + 1) & 3) > 1)
                    sign = nflg;
                else
                    sign = 1;
                bk += sign * lambda[s] * zp * u[m];
            }
            zp *= z32i;
        }

        if (doa) {
            ak *= np;
            t = fabs(ak);
            if (t < akl) {
                akl = t;
                pp += ak;
            }
            else
                doa = 0;
        }

        if (dob) {
            bk += lambda[tkp1] * zp * u[0];
            bk *= -np / sqz;
            t = fabs(bk);
            if (t < bkl) {
                bkl = t;
                qq += bk;
            }
            else
                dob = 0;
        }
#if CEPHES_DEBUG
        printf("a[%d] %.5E, b[%d] %.5E\n", k, ak, k, bk);
#endif
        if (np < MACHEP)
            break;
        np /= n * n;
    }

    /* normalizing factor ( 4*zeta/(1 - z**2) )**1/4    */
    t = 4.0 * zeta / zz;
    t = sqrt(sqrt(t));

    t *= ai * pp / cbrt(n) + aip * qq / (n23 * n);
    return (t);
}
Exemple #22
0
int             main(int argc, char **argv)
{
  int		tI,
		idN,
  		option,
		con = WLZ_0_CONNECTED,
		nLo = 0,
		nHi = 0,
		maxSep = 1024,
		nObj = 0,
  		ok = 1,
		usage = 0;
  char		tC;
  double  	tD,
		mrkMass = 1.0,
  		rad = 0.0;
  int		tR[4];
  WlzPixelV	gV,
  		bV;
  WlzBlobMark	mrk = WLZ_BLOBMARK_CIRCLE;
  WlzObject     *inObj = NULL,
  		*outObj = NULL,
		*mrkObj = NULL;
  WlzObject	**lObj = NULL;
  FILE		*fP = NULL;
  char 		*inObjFileStr,
  		*outObjFileStr;
  WlzErrorNum	errNum = WLZ_ERR_NONE;
  const char	*errMsg;
  static char	optList[] = "c:g:G:hm:n:N:o:r:x:",
  		fileStrDef[] = "-";

  opterr = 0;
  memset(&gV, 0, sizeof(WlzPixelV));
  bV.type = WLZ_GREY_UBYTE;
  bV.v.ubv = 0;
  gV.type = WLZ_GREY_ERROR;
  inObjFileStr = fileStrDef;
  outObjFileStr = fileStrDef;
  while((usage == 0) && ((option = getopt(argc, argv, optList)) != -1))
  {
    switch(option)
    {
      case 'c':
        if(sscanf(optarg, "%d", &tI) != 1)
	{
	  usage = 1;
	}
	else
	{
	  switch(tI)
	  {
	    case  4:
	      con = WLZ_4_CONNECTED;
	      break;
	    case  6:
	      con = WLZ_6_CONNECTED;
	      break;
	    case  8:
	      con = WLZ_8_CONNECTED;
	      break;
	    case 18:
	      con = WLZ_18_CONNECTED;
	      break;
	    case 26:
	      con = WLZ_26_CONNECTED;
	      break;
	    default:
	      usage = 1;
	      break;
	  }
	}
	break;
      case 'g':
        switch(gV.type)
	{
	  case WLZ_GREY_UBYTE:
	    if((sscanf(optarg, "%d", &tI) != 1) ||
	       (tI < 0) || (tI > 255))
	    {
	      usage = 1;
	    }
	    else
	    {
	      gV.v.ubv = tI;
	    }
	    break;
	  case WLZ_GREY_SHORT:
	    if((sscanf(optarg, "%d", &tI) != 1) ||
	       (tI < SHRT_MIN) || (tI > SHRT_MAX))
	    {
	      usage = 1;
	    }
	    else
	    {
	      gV.v.shv = tI;
	    }
	    break;
	  case WLZ_GREY_INT:
	    if(sscanf(optarg, "%d", &tI) != 1)
	    {
	      usage = 1;
	    }
	    else
	    {
	      gV.v.inv = tI;
	    }
	    break;
	  case WLZ_GREY_FLOAT:
	    if((sscanf(optarg, "%lg", &tD) != 1) ||
	       (tD < -(FLT_MAX)) || (tD > FLT_MAX))
	    {
	      usage = 1;
	    }
	    else
	    {
	      gV.v.flv = tD;
	    }
	    break;
	  case WLZ_GREY_DOUBLE:
	    if(sscanf(optarg, "%lg", &tD) != 1)
	    {
	      usage = 1;
	    }
	    else
	    {
	      gV.v.dbv = tD;
	    }
	    break;
	  case WLZ_GREY_RGBA:
	    tR[3] = 255;
	    tR[0] = tR[1] = tR[2] = 0;
	    if((sscanf(optarg, "%d,%d,%d,%d",
	               &(tR[0]), &(tR[1]), &(tR[2]), &(tR[3])) == 0) ||
	       (tR[0] < 0) || (tR[0] > 255) ||
	       (tR[1] < 0) || (tR[1] > 255) ||
	       (tR[2] < 0) || (tR[2] > 255) ||
	       (tR[3] < 0) || (tR[3] > 255))
	    {
	      usage = 1;
	    }
	    else
	    {
	      WLZ_RGBA_RGBA_SET(gV.v.rgbv, tR[0], tR[1], tR[2], tR[3]);
	    }
	    break;
	  default:
	    usage = 1;
	    break;
	}
	break;
      case 'G':
        if(sscanf(optarg, "%c", &tC) != 1)
	{
	  usage = 1;
	}
	switch(tC)
	{
	  case 'v':
	    gV.type = WLZ_GREY_ERROR;
	    break;
	  case 'u':
	    gV.type = WLZ_GREY_UBYTE;
	    break;
	  case 's':
	    gV.type = WLZ_GREY_SHORT;
	    break;
	  case 'i':
	    gV.type = WLZ_GREY_INT;
	    break;
	  case 'f':
	    gV.type = WLZ_GREY_FLOAT;
	    break;
	  case 'd':
	    gV.type = WLZ_GREY_DOUBLE;
	    break;
	  case 'r':
	    gV.type = WLZ_GREY_RGBA;
	    break;
	  default:
	    usage = 1;
	    break;
	}
	break;
      case 'm':
        if((sscanf(optarg, "%d", &tI) != 1) ||
	   ((tI != WLZ_BLOBMARK_CIRCLE) && (tI != WLZ_BLOBMARK_SQUARE)))
	{
	  usage = 1;
	}
	else
	{
	  mrk = (WlzBlobMark )tI;
	}
	break;
      case 'n':
        if((sscanf(optarg, "%d", &nLo) != 1) || (nLo < 0))
	{
	  usage = 1;
	}
	break;
      case 'N':
        if((sscanf(optarg, "%d", &nHi) != 1) || (nHi < 0))
	{
	  usage = 1;
	}
	break;
      case 'o':
        outObjFileStr = optarg;
	break;
      case 'r':
        if((sscanf(optarg, "%lg", &rad) != 1) || (rad < 0.0))
	{
	  usage = 1;
	}
	break;
      case 'x':
        if((sscanf(optarg, "%d", &maxSep) != 1) || (maxSep < 1))
	{
	  usage = 1;
	}
      case 'h': /* FALLTHROUGH */
      default:
        usage = 1;
	break;
    }
  }
  if((usage == 0) && (nLo > nHi) && (nHi != 0))
  {
    usage = 1;
  }
  if((usage == 0) && (optind < argc))
  {
    if((optind + 1) != argc)
    {
      usage = 1;
    }
    else
    {
      inObjFileStr = *(argv + optind);
    }
  }
  ok = (usage == 0);
  /* Read input domain object. */
  if(ok)
  {
    if((inObjFileStr == NULL) ||
	(*inObjFileStr == '\0') ||
	((fP = (strcmp(inObjFileStr, "-")?
	       fopen(inObjFileStr, "r"): stdin)) == NULL) ||
	((inObj = WlzAssignObject(WlzReadObj(fP, &errNum), NULL)) == NULL) ||
	(errNum != WLZ_ERR_NONE))
    {
      ok = 0;
    }
    if(fP)
    {
      if(strcmp(inObjFileStr, "-"))
      {
	(void )fclose(fP);
      }
      fP = NULL;
    }
  }
  /* Check object type and connectivity. */
  if(ok)
  {
    switch(inObj->type)
    {
      case WLZ_2D_DOMAINOBJ:
	switch(con)
	{
	  case WLZ_0_CONNECTED:
	    con = WLZ_8_CONNECTED;
	    break;
	  case WLZ_4_CONNECTED: /* FALLTHROUGH */
	  case WLZ_8_CONNECTED:
	    break;
	  default:
	    ok = 0;
	    errNum = WLZ_ERR_PARAM_DATA;
	    (void )WlzStringFromErrorNum(errNum, &errMsg);
	    (void )fprintf(stderr,
	           "%s: Connectivity for 2D must be 4 or 8 (%s).\n",
		   *argv, errMsg);
	    break;
	}
	break;
      case WLZ_3D_DOMAINOBJ:
	switch(con)
	{
	  case WLZ_0_CONNECTED:
	    con = WLZ_26_CONNECTED;
	    break;
	  case  WLZ_6_CONNECTED: /* FALLTHROUGH */
	  case WLZ_18_CONNECTED: /* FALLTHROUGH */
	  case WLZ_26_CONNECTED:
	    break;
	  default:
	    ok = 0;
	    errNum = WLZ_ERR_PARAM_DATA;
	    (void )WlzStringFromErrorNum(errNum, &errMsg);
	    (void )fprintf(stderr,
	           "%s: Connectivity for 3D must be 6, 18 or 26 (%s).\n",
		   *argv, errMsg);
	    break;
	}
	break;
      default:
	ok = 0;
	errNum = WLZ_ERR_OBJECT_TYPE;
	(void )WlzStringFromErrorNum(errNum, &errMsg);
	(void )fprintf(stderr,
	       "%s: Input object must either a 2 or 3D domain object (%s).\n",
	       *argv, errMsg);
	break;
    }
  }
  /* Make basic marker with centre at the origin. */
  if(ok)
  {
    double	mrkRad;

    if(rad > 0.5)
    {
      mrkRad = rad;
    }
    else
    {
      mrkRad = 127;
    }
    if(mrk == WLZ_BLOBMARK_SQUARE)
    {
      mrkObj = WlzMakeCuboidObject(inObj->type, mrkRad, mrkRad, mrkRad,
                                   0, 0, 0, &errNum);
    }
    else /* mrk = WLZ_BLOBMARK_CIRCLE */
    {
      mrkObj = WlzMakeSphereObject(inObj->type, mrkRad, 0, 0, 0, &errNum);
    }
    if(mrkObj == NULL)
    {
      ok = 0;
      (void )WlzStringFromErrorNum(errNum, &errMsg);
      (void )fprintf(stderr,
             "%s: Failed to create basic marker object (%s).\n",
	     *argv, errMsg);
    }
    else
    {
      mrkMass = WlzVolume(mrkObj, NULL);
    }
  }
  /* Label the given domain. */
  if(ok)
  {
    errNum = WlzLabel(inObj, &nObj, &lObj, maxSep, 1, con);
    if((errNum != WLZ_ERR_NONE) || (nObj == 0))
    {
      ok = 0;
      if(errNum == WLZ_ERR_NONE)
      {
        errNum = WLZ_ERR_DOMAIN_DATA;
      }
      (void )WlzStringFromErrorNum(errNum, &errMsg);
      (void )fprintf(stderr,
      "%s: Failed to split the given object into separate regions (%s)\n",
      *argv, errMsg);
    }
  }
  /* Work through the separate object list removing small/large objects
   * according to the low and high thresholds. */
  if(ok)
  {
    int		idM;

    for(idN = 0, idM = 0; idN < nObj; ++idN)
    {
      int	vol;

      vol = WlzVolume(lObj[idN], &errNum);
      if(errNum == WLZ_ERR_NONE)
      {
        if(((nLo > 0) && (vol < nLo)) || ((nHi > 0) && (vol > nHi)))
	{
	  (void )WlzFreeObj(lObj[idN]);
	}
	else
	{
	  lObj[idM] = lObj[idN];
	  ++idM;
	}
      }
    }
    nObj = idM;
    if(nObj == 0)
    {
      ok = 0;
      errNum = WLZ_ERR_DOMAIN_DATA;
      (void )WlzStringFromErrorNum(errNum, &errMsg);
      (void )fprintf(stderr,
                     "%s: Failed to find and separate regions (%s)\n",
		     *argv, errMsg);

    }
  }
  /* Build a marker object by adding a mark at the centre of mass of each
   * separate fragment. */
  if(ok)
  {
    WlzObject	*obj0 = NULL;

    idN = 0;
    obj0 = WlzMakeEmpty(&errNum);
    while((errNum == WLZ_ERR_NONE) && (idN < nObj))
    {
      double	  mass;
      WlzDVertex3 com;
      WlzObject	  *obj1 = NULL,
      		  *obj2 = NULL;
      WlzAffineTransform *tr = NULL;

      com = WlzCentreOfMass3D(lObj[idN], 1, &mass, &errNum);
      if(errNum == WLZ_ERR_NONE)
      {
        double	s;

	if(rad < 0.5)
	{
	  double t;

	  t = mass / mrkMass;
	  if(inObj->type == WLZ_2D_DOMAINOBJ)
	  {
	    s = sqrt(t);
	  }
	  else /* inObj->type == WLZ_3D_DOMAINOBJ */
	  {
	    s = cbrt(t);
	  }
	}
	else
	{
	  s = 1.0;
	}
        tr = (inObj->type == WLZ_2D_DOMAINOBJ)?
             WlzAffineTransformFromPrimVal(
	       WLZ_TRANSFORM_2D_AFFINE, com.vtX, com.vtY, 0.0,
	       s, 0.0, 0.0, 0.0, 0.0, 0.0, 0, &errNum):
             WlzAffineTransformFromPrimVal(
	       WLZ_TRANSFORM_3D_AFFINE, com.vtX, com.vtY, com.vtZ,
	       s, 0.0, 0.0, 0.0, 0.0, 0.0, 0, &errNum);
      }
      if(errNum == WLZ_ERR_NONE)
      {
	obj1 = WlzAffineTransformObj(mrkObj, tr, WLZ_INTERPOLATION_NEAREST,
				     &errNum);
      }
      if(errNum == WLZ_ERR_NONE)
      {
	obj2 = WlzUnion2(obj0, obj1, &errNum);
      }
      if(errNum == WLZ_ERR_NONE)
      {
        (void )WlzFreeObj(obj0);
	obj0 = obj2;
	obj2 = NULL;
      }
      (void )WlzFreeObj(obj1);
      (void )WlzFreeObj(obj2);
      (void )WlzFreeAffineTransform(tr);
      ++idN;
    }
    if(errNum == WLZ_ERR_NONE)
    {
      WlzValues	val;
      WlzObjectType vTT;

      val.core = NULL;
      if(gV.type != WLZ_GREY_ERROR)
      {
	vTT = WlzGreyTableType(WLZ_GREY_TAB_RAGR, gV.type, NULL);
	if(inObj->type == WLZ_2D_DOMAINOBJ)
	{
	  val.v = WlzNewValueTb(obj0, vTT, bV, &errNum);
	}
	else /* inObj->type == WLZ_3D_DOMAINOBJ */
	{
	  val.vox = WlzNewValuesVox(obj0, vTT, bV, &errNum);
	}
      }
      if(errNum == WLZ_ERR_NONE)
      {
        outObj = WlzMakeMain(inObj->type, obj0->domain, val, NULL, NULL,
	                     &errNum);
      }
      if((errNum == WLZ_ERR_NONE) && (gV.type != WLZ_GREY_ERROR))
      {
        errNum = WlzGreySetValue(outObj, gV);
      }
    }
  }
  if(ok)
  {
    errNum = WLZ_ERR_WRITE_EOF;
    if(((fP = (strcmp(outObjFileStr, "-")?
              fopen(outObjFileStr, "w"): stdout)) == NULL) ||
       ((errNum = WlzWriteObj(fP, outObj)) != WLZ_ERR_NONE))
    {
      ok = 0;
      (void )WlzStringFromErrorNum(errNum, &errMsg);
      (void )fprintf(stderr,
                     "%s: Failed to write output object (%s).\n",
		     *argv, errMsg);
    }
    if(fP && strcmp(outObjFileStr, "-"))
    {
      (void )fclose(fP);
    }
  }
  (void )WlzFreeObj(inObj);
  if(lObj != NULL)
  {
    for(idN = 0; idN < nObj; ++idN)
    {
      (void )WlzFreeObj(lObj[idN]);
    }
    AlcFree(lObj);
  }
  (void )WlzFreeObj(outObj);
  if(usage)
  {
    (void )fprintf(stderr,
    "Usage: %s%sExample: %s%s",
    *argv,
    " [-c#] [-g#] [-G#] [-h] [-m#] [-n#] [-N#]\n"
    "       [-o<output object>] [-r#]] [-x#] [<input object>]\n"
    "Options:\n"
    "  -c  Connectivity: 4, 6, 8, 18 or 26 connected (default 8 for 2D\n"
    "      domains and 26 for 3D domains).\n"
    "  -g  Grey value for marker. This is a single number for all except\n"
    "      RGBA (colour) grey values. RGBA components must be separated by\n"
    "      by a comma.\n"
    "  -G  Grey value type for marker specified by letter:\n"
    "        v  no grey values (default).\n"
    "        u  unsigned byte grey values.\n"
    "        s  short grey values.\n"
    "        i  int grey values.\n"
    "        f  int grey values.\n"
    "        d  int grey values.\n"
    "        r  red, green, blue, alpha grey values.\n"
    "  -h  Help, prints usage message.\n"
    "  -m  Marker type specified by a number:\n"
    "        1  circle/sphere (default)\n"
    "        2  square/cube\n"
    "  -n  Threshold minimum area/volume of blob for a marker (default\n"
    "      >= 1).\n"
    "  -N  Threshold maximum area/volume of blob for a marker. If zero\n"
    "      there is no upper limit. (default  0).\n"
    "  -o  Output object file.\n"
    "  -r  Marker radius. Attempts to keep the same area/volume if zero.\n"
    "      (default 0).\n"
    "  -x  Maximum number of separate regions in the object (default 1024).\n"
    "Reads a spatial domain object and replaces each spatialy separate\n"
    "region with a marker placed at the centre of mass of the region.\n"
    "All files are read from the standard input and written to the standard\n"
    "output unless filenames are given.\n"
    "If grey values are required then the grey value type must be set before\n"
    "the actual grey value.\n",
    *argv,
    " -o out.wlz -n 4 -r 10 -G r -g 200,100,0,255 in.wlz\n"
    "A spatial domain object is read from the file in.wlz and each\n"
    "spatialy separate region of the domain is replaced by a circle or\n"
    "sphere of radius 10 (pixels). All small regions with less than four\n"
    "(pixels voxels) is ignored. The output object (with grey values set\n"
    "to orange) is written to the file out.wlz.\n");
  }
  return(!ok);
}
void LALInferenceTemplateROQ(LALInferenceModel *model)
{
double m1,m2,mc,eta,q,iota=0;
/* Prefer m1 and m2 if available (i.e. for injection template) */
  if(LALInferenceCheckVariable(model->params,"mass1")&&LALInferenceCheckVariable(model->params,"mass2"))
  {
    m1=*(REAL8 *)LALInferenceGetVariable(model->params,"mass1");
    m2=*(REAL8 *)LALInferenceGetVariable(model->params,"mass2");
    eta=m1*m2/((m1+m2)*(m1+m2));
    mc=pow(eta , 0.6)*(m1+m2);
  }
  else
  {
    if (LALInferenceCheckVariable(model->params,"q")) {
      q = *(REAL8 *)LALInferenceGetVariable(model->params,"q");
      q2eta(q, &eta);
    }
    else
      eta = *(REAL8*) LALInferenceGetVariable(model->params, "eta");
    mc       = *(REAL8*) LALInferenceGetVariable(model->params, "chirpmass");
    mc2masses(mc, eta, &m1, &m2);
  }

  iota = acos(LALInferenceGetREAL8Variable(model->params, "costheta_jn"));     /* zenith angle between J and N in radians */

  double cosiota = cos(iota);
  double plusCoef  = 0.5 * (1.0 + cosiota*cosiota);
  double crossCoef = cosiota;
  /* external: SI; internal: solar masses */
  const REAL8 m = m1 + m2;
  const REAL8 m_sec = m * LAL_MTSUN_SI;  /* total mass in seconds */
  const REAL8 etap2 = eta * eta;
  const REAL8 etap3 = etap2 * eta;
  const REAL8 piM = LAL_PI * m_sec;
  const REAL8 mSevenBySix = -7./6.;
  const REAL8 phic = *(REAL8 *)LALInferenceGetVariable(model->params,"phase");
  const REAL8 r = 1e6*LAL_PC_SI;
  REAL8 logv0 = log(1.); //the standard tf2 definition is log(v0), but I've changed it to reflect Scott's convention
  REAL8 shft, amp0;//, f_max;
  REAL8 psiNewt, psi2, psi3, psi4, psi5, psi6, psi6L, psi7, psi3S, psi4S, psi5S;
  REAL8 eta_fac = -113. + 76. * eta;
  REAL8 chi=0; //NOTE: chi isn't used here yet, so we just set it to zero
  gsl_complex h_i;

  /* extrinsic parameters */
  amp0 = -pow(m_sec, 5./6.) * sqrt(5.*eta / 24.) / (Pi_p2by3 * r / LAL_C_SI);
  shft = 0;//LAL_TWOPI * (tStart.gpsSeconds + 1e-9 * tStart.gpsNanoSeconds);

  /* spin terms in the amplitude and phase (in terms of the reduced
   * spin parameter */
  psi3S = 113.*chi/3.;
  psi4S = 63845.*(-81. + 4.*eta)*chi*chi/(8. * eta_fac * eta_fac);
  psi5S = -565.*(-146597. + 135856.*eta + 17136.*etap2)*chi/(2268.*eta_fac);

  /* coefficients of the phase at PN orders from 0 to 3.5PN */
  psiNewt = 3./(128.*eta);
  psi2 = 3715./756. + 55.*eta/9.;
  psi3 = psi3S - 16.*LAL_PI;
  psi4 = 15293365./508032. + 27145.*eta/504. + 3085.*eta*eta/72. + psi4S;
  psi5 = (38645.*LAL_PI/756. - 65.*LAL_PI*eta/9. + psi5S);
  psi6 = 11583231236531./4694215680. - (640.*Pi_p2)/3. - (6848.*LAL_GAMMA)/21.
           + (-5162.983708047263 + 2255.*Pi_p2/12.)*eta
           + (76055.*etap2)/1728. - (127825.*etap3)/1296.;
  psi6L = -6848./21.;
  psi7 = (77096675.*LAL_PI)/254016. + (378515.*LAL_PI*eta)/1512.
           - (74045.*LAL_PI*eta*eta)/756.;

  for (unsigned int i = 0; i < model->roq->frequencyNodes->size; i++) {
    /* fourier frequency corresponding to this bin */
    const REAL8 f = gsl_vector_get(model->roq->frequencyNodes, i);
    const REAL8 v3 = piM*f;

    /* PN expansion parameter */
    REAL8 v, v2, v4, v5, v6, v7, logv, Psi, amp;
    v = cbrt(v3);
    v2 = v*v; v4 = v3*v; v5 = v4*v; v6 = v3*v3; v7 = v6*v;
    logv = log(v);

    /* compute the phase and amplitude */
    Psi = psiNewt / v5 * (1.
         + psi2 * v2 + psi3 * v3 + psi4 * v4
         + psi5 * v5 * (1. + 3. * (logv - logv0))
         + (psi6 + psi6L * (log4 + logv)) * v6 + psi7 * v7);

    amp = amp0 * pow(f, mSevenBySix);

    GSL_SET_COMPLEX(&h_i, amp * cos(Psi + shft * f - 2.*phic - LAL_PI_4), - amp * sin(Psi + shft * f - 2.*phic - LAL_PI_4));

    gsl_vector_complex_set(model->roq->hplus, i, gsl_complex_mul_real(h_i,plusCoef));
    gsl_vector_complex_set(model->roq->hcross, i, gsl_complex_mul_real(gsl_complex_mul_imag(h_i,-1.0),crossCoef));

  }
	return;
}
Exemple #24
0
void run( MPI_Comm comm , const int cmd[] )
{
  int comm_rank = 0 ;

#if defined( KOKKOS_ENABLE_MPI )
  MPI_Comm_rank( comm , & comm_rank );
#else
  comm = 0 ;
#endif


  if ( 0 == comm_rank ) {
    if ( cmd[ CMD_USE_THREADS ] ) { std::cout << "THREADS , " << cmd[ CMD_USE_THREADS ] ; }
    else if ( cmd[ CMD_USE_OPENMP ] ) { std::cout << "OPENMP , " << cmd[ CMD_USE_OPENMP ] ; }
    else if ( cmd[ CMD_USE_CUDA ] ) { std::cout << "CUDA" ; }

    if ( cmd[ CMD_USE_FIXTURE_QUADRATIC ] ) { std::cout << " , QUADRATIC-ELEMENT" ; }
    else { std::cout << " , LINEAR-ELEMENT" ; }

    if ( cmd[ CMD_USE_ATOMIC ] ) { std::cout << " , USING ATOMICS" ; }
  }

  std::vector< std::pair<std::string,std::string> > headers;


  headers.push_back(std::make_pair("ELEMS","count"));
  headers.push_back(std::make_pair("NODES","count"));
  headers.push_back(std::make_pair("NEWTON","iter"));
  headers.push_back(std::make_pair("CG","iter"));
  headers.push_back(std::make_pair("MAP_RATIO","ratio"));
  headers.push_back(std::make_pair("SET_FILL/NODE","millisec"));
  headers.push_back(std::make_pair("SCAN/NODE","millisec"));
  headers.push_back(std::make_pair("GRAPH_FILL/NODE","millisec"));
  headers.push_back(std::make_pair("SORT/NODE","millisec"));
  headers.push_back(std::make_pair("ELEM_GRAPH_FILL/NODE","millisec"));
  headers.push_back(std::make_pair("MATRIX_CREATE/NODE","millisec"));
  headers.push_back(std::make_pair("MATRIX_FILL/NODE","millisec"));
  headers.push_back(std::make_pair("BOUNDARY/NODE","millisec"));
  headers.push_back(std::make_pair("MAT_VEC/ITER/ROW","millisec"));
  headers.push_back(std::make_pair("CG/ITER/ROW","millisec"));
  headers.push_back(std::make_pair("ERROR","ratio"));

  // find print widths
  size_t min_width = 10;
  std::vector< size_t > widths(headers.size());
  for (size_t i=0, ie=headers.size(); i<ie; ++i)
    widths[i] = std::max(min_width, headers[i].first.size()+1);

  // print column headers
  if ( 0 == comm_rank ) {
    std::cout << std::endl ;
    for (size_t i=0; i<headers.size(); ++i)
      std::cout << std::setw(widths[i]) << headers[i].first << " ,";
    std::cout << "\b\b  " << std::endl;
    for (size_t i=0; i<headers.size(); ++i)
      std::cout << std::setw(widths[i]) << headers[i].second << " ,";
    std::cout << "\b\b  " << std::endl;

    std::cout << std::scientific;
    std::cout.precision(3);
  }

  if ( cmd[ CMD_USE_FIXTURE_BEGIN ] ) {
    for ( int i = cmd[CMD_USE_FIXTURE_BEGIN] ; i < cmd[CMD_USE_FIXTURE_END] * 2 ; i *= 2 ) {
      int nelem[3] ;
      nelem[0] = std::max( 1 , (int) cbrt( ((double) i) / 2.0 ) );
      nelem[1] = 1 + nelem[0] ;
      nelem[2] = 2 * nelem[0] ;

      const Kokkos::Example::FENL::Perf perf =
        cmd[ CMD_USE_FIXTURE_QUADRATIC ]
        ? Kokkos::Example::FENL::fenl< Device , Kokkos::Example::BoxElemPart::ElemQuadratic >
            ( comm , cmd[CMD_PRINT], cmd[CMD_USE_TRIALS], cmd[CMD_USE_ATOMIC], nelem )
        : Kokkos::Example::FENL::fenl< Device , Kokkos::Example::BoxElemPart::ElemLinear >
            ( comm , cmd[CMD_PRINT], cmd[CMD_USE_TRIALS], cmd[CMD_USE_ATOMIC], nelem )
        ;

      if ( 0 == comm_rank ) print_perf_value( std::cout , widths, perf );
    }
  }
  else {
    int nelem[3] = { cmd[ CMD_USE_FIXTURE_X ] ,
                     cmd[ CMD_USE_FIXTURE_Y ] ,
                     cmd[ CMD_USE_FIXTURE_Z ] };

    const Kokkos::Example::FENL::Perf perf =
      cmd[ CMD_USE_FIXTURE_QUADRATIC ]
      ? Kokkos::Example::FENL::fenl< Device , Kokkos::Example::BoxElemPart::ElemQuadratic >
          ( comm , cmd[CMD_PRINT], cmd[CMD_USE_TRIALS], cmd[CMD_USE_ATOMIC], nelem )
      : Kokkos::Example::FENL::fenl< Device , Kokkos::Example::BoxElemPart::ElemLinear >
          ( comm , cmd[CMD_PRINT], cmd[CMD_USE_TRIALS], cmd[CMD_USE_ATOMIC], nelem )
      ;

    if ( 0 == comm_rank ) print_perf_value( std::cout , widths, perf );
  }
}
Exemple #25
0
int SolveCubic( double c[4], double s[3] )
{
    int     i, num;
    double  sub;
    double  A, B, C;
    double  sq_A, p, q;
    double  cb_p, D;

    /* normal form: x^3 + Ax^2 + Bx + C = 0 */

    A = c[ 2 ] / c[ 3 ];
    B = c[ 1 ] / c[ 3 ];
    C = c[ 0 ] / c[ 3 ];

    /*  substitute x = y - A/3 to eliminate quadric term:
	x^3 +px + q = 0 */

    sq_A = A * A;
    p = 1.0/3 * (- 1.0/3 * sq_A + B);
    q = 1.0/2 * (2.0/27 * A * sq_A - 1.0/3 * A * B + C);

    /* use Cardano's formula */

    cb_p = p * p * p;
    D = q * q + cb_p;

    if (IsZero(D))
    {
	if (IsZero(q)) /* one triple solution */
	{
	    s[ 0 ] = 0;
	    num = 1;
	}
	else /* one single and one double solution */
	{
	    double u = cbrt(-q);
	    s[ 0 ] = 2 * u;
	    s[ 1 ] = - u;
	    num = 2;
	}
    }
    else if (D < 0) /* Casus irreducibilis: three real solutions */
    {
	double phi = 1.0/3 * acos(-q / sqrt(-cb_p));
	double t = 2 * sqrt(-p);

	s[ 0 ] =   t * cos(phi);
	s[ 1 ] = - t * cos(phi + M_PI / 3);
	s[ 2 ] = - t * cos(phi - M_PI / 3);
	num = 3;
    }
    else /* one real solution */
    {
	double sqrt_D = sqrt(D);
	double u = cbrt(sqrt_D - q);
	double v = - cbrt(sqrt_D + q);

	s[ 0 ] = u + v;
	num = 1;
    }

    /* resubstitute */

    sub = 1.0/3 * A;

    for (i = 0; i < num; ++i)
	s[ i ] -= sub;

    return num;
}
Exemple #26
0
_inline double _cubeBrightnessReduction( double base )
{
	return lossCalculator( cbrt( base ), cbrt( base * _effectiveFPS( ) / _currentFPS( ) ) );
}
Exemple #27
0
int main(int argc, char *argv[])
{
  double x;
  x = cbrt((double) argc);
  return 0;
}
Exemple #28
0
int SFCbrt(lua_State* l)
{
    double x = lua_tonumber(Scripts.vm, 1);
    lua_pushnumber(Scripts.vm, cbrt(x));
    return 1;
}
void Foam::PairSpringSliderDashpot<CloudType>::evaluatePair
(
    typename CloudType::parcelType& pA,
    typename CloudType::parcelType& pB
) const
{
    vector r_AB = (pA.position() - pB.position());

    scalar dAEff = pA.d();

    if (useEquivalentSize_)
    {
        dAEff *= cbrt(pA.nParticle()*volumeFactor_);
    }

    scalar dBEff = pB.d();

    if (useEquivalentSize_)
    {
        dBEff *= cbrt(pB.nParticle()*volumeFactor_);
    }

    scalar r_AB_mag = mag(r_AB);

    scalar normalOverlapMag = 0.5*(dAEff + dBEff) - r_AB_mag;

    if (normalOverlapMag > 0)
    {
        //Particles in collision

        vector rHat_AB = r_AB/(r_AB_mag + VSMALL);

        vector U_AB = pA.U() - pB.U();

        // Effective radius
        scalar R = 0.5*dAEff*dBEff/(dAEff + dBEff);

        // Effective mass
        scalar M = pA.mass()*pB.mass()/(pA.mass() + pB.mass());

        scalar kN = (4.0/3.0)*sqrt(R)*Estar_;

        scalar etaN = alpha_*sqrt(M*kN)*pow025(normalOverlapMag);

        // Normal force
        vector fN_AB =
            rHat_AB
           *(kN*pow(normalOverlapMag, b_) - etaN*(U_AB & rHat_AB));

        // Cohesion force
        if (cohesion_)
        {
            fN_AB +=
                -cohesionEnergyDensity_
                *overlapArea(dAEff/2.0, dBEff/2.0, r_AB_mag)
                *rHat_AB;
        }

        pA.f() += fN_AB;
        pB.f() += -fN_AB;

        vector USlip_AB =
            U_AB - (U_AB & rHat_AB)*rHat_AB
          + (pA.omega() ^ (dAEff/2*-rHat_AB))
          - (pB.omega() ^ (dBEff/2*rHat_AB));

        scalar deltaT = this->owner().mesh().time().deltaTValue();

        vector& tangentialOverlap_AB =
            pA.collisionRecords().matchPairRecord
            (
                pB.origProc(),
                pB.origId()
            ).collisionData();

        vector& tangentialOverlap_BA =
            pB.collisionRecords().matchPairRecord
            (
                pA.origProc(),
                pA.origId()
            ).collisionData();

        vector deltaTangentialOverlap_AB = USlip_AB*deltaT;

        tangentialOverlap_AB += deltaTangentialOverlap_AB;
        tangentialOverlap_BA += -deltaTangentialOverlap_AB;

        scalar tangentialOverlapMag = mag(tangentialOverlap_AB);

        if (tangentialOverlapMag > VSMALL)
        {
            scalar kT = 8.0*sqrt(R*normalOverlapMag)*Gstar_;

            scalar etaT = etaN;

            // Tangential force
            vector fT_AB;

            if (kT*tangentialOverlapMag > mu_*mag(fN_AB))
            {
                // Tangential force greater than sliding friction,
                // particle slips

                fT_AB = -mu_*mag(fN_AB)*USlip_AB/mag(USlip_AB);

                tangentialOverlap_AB = vector::zero;
                tangentialOverlap_BA = vector::zero;
            }
            else
            {
                fT_AB =
                    -kT*tangentialOverlapMag
                   *tangentialOverlap_AB/tangentialOverlapMag
                  - etaT*USlip_AB;
            }

            pA.f() += fT_AB;
            pB.f() += -fT_AB;

            pA.torque() += (dAEff/2*-rHat_AB) ^ fT_AB;
            pB.torque() += (dBEff/2*rHat_AB) ^ -fT_AB;
        }
    }
}
Exemple #30
0
__device__ inline double occaCuda_fastCbrt(const double x){ return cbrt(x);  }