Exemple #1
0
static bool_t doubling(divisor& x, const divisor& a) 
     // x = a + a via explicit formulas

{  /* Variables 
We choose to use local variables for now to make the function thread safe.
Note that this may affect the performance of the program as opposed to 
the method of passing along the temporary variables.
  */
 
  bool_t OK = TRUE;


  const field_t f4 = coeff(a.get_curve().get_f(), 4), 
                f3 = coeff(a.get_curve().get_f(), 3),
                f2 = coeff(a.get_curve().get_f(), 2),
                h1 = coeff(a.get_curve().get_h(), 1), 
                h2 = coeff(a.get_curve().get_h(), 2),
                h0 = coeff(a.get_curve().get_h(), 0), 
    u1 = coeff(a.get_upoly(), 1), u0 = coeff(a.get_upoly(), 0),
    v1 = coeff(a.get_vpoly(), 1), v0 = coeff(a.get_vpoly(), 0);

  field_t v1t, v0t, w0, w1, w2, w3, r, inv1p, inv0p, w4, t1p, t0p, s1p,
    s0p, w5, s0pp, l2p, l1p, l0p, u0p, u1p, v1p, v0p;

  poly_t up, vp;
 
  /* Explicit formulas */
 
  /* Step 1: 
     v1t = h1 + 2*v1 - h2*u1, v0t = h0 + 2*v0 - h2*u0 
  */
  v1t = h1 + 2*v1 - h2*u1; 
  v0t = h0 + 2*v0 - h2*u0;

  /* Step 2: 
     w0 = v1^2, w1 = u1^2, w2 = v1t^2, w3 = u1*v1t, 
     r = u0*w2 + v0t*(v0t - w3) 
  */
  w0 = sqr(v1); 
  w1 = sqr(u1);
  w2 = sqr(v1t);
  w3 = u1*v1t;
  r = u0*w2 + v0t*(v0t - w3);
  assert(!IsZero(r));

  /* Step 3:
     inv1p = -v1t, inv0p = v0t - w3 
  */
   inv1p = -v1t;
   inv0p = v0t - w3;

  /* Step 4: 
     w3 = f3 + w1, w4 = 2*u0, t1p = 2*(w1 - f4*u1) + w3 - w4 - h2*v1,
     t0p = u1*(2*w4 - w3 + f4*u1 + h2*v1) + f2 - w0 - 2*f4*u0 - h1*v1 - h2*v0
  */
   w3 = f3 + w1;
   w4 = 2*u0;
   t1p = 2*(w1 - f4*u1) + w3 - w4 - h2*v1;
   t0p = u1*(2*w4 - w3 + f4*u1 + h2*v1) + f2 - w0 - 2*f4*u0 - h1*v1 - h2*v0;

  /* Step 5:
     w0 = t0p*inv0p, w1 = t1p*inv1p, 
     s1p = (inv0p + inv1p)*(t0p + t1p) - w0 - w1*(1+u1),
     s0p = w0 - u0*w1.

     If s1p = 0, call add_cantor().
  */
   w0 = t0p*inv0p;
   w1 = t1p*inv1p;
   s1p = (inv0p + inv1p)*(t0p + t1p) - w0 - w1*(1+u1);

#if DEBUG_LEVEL > 1
   cout << "r = " << r << endl;
   cout << "s1p = " << s1p << endl;
#endif 

  // Special case
  if (IsZero(s1p)) 
    return add_cantor(x, a, a);

   s0p = w0 - u0*w1;

  /* Step 6:
     w1 = 1/(r*s1p), w2 = r*w1, w3 = s1p^2*w1, w4 = r*w2, w5 = w4^2,
     s0pp = s0p*w2
   */
  w1 = 1/(r*s1p);
  w2 = r*w1;
  w3 = sqr(s1p)*w1;
  w4 = r*w2;
  w5 = sqr(w4);
  s0pp = s0p*w2;

  /* Step 7:
     l2p = u1 + s0pp, l1p = u1*s0pp + u0, l0p = u0*s0pp
  */
   l2p = u1 + s0pp;
   l1p = u1*s0pp + u0;
   l0p = u0*s0pp;

  /* Step 8:
     u0p = s0pp^2 + w4*(h2*(s0pp - u1) + 2*v1 + h1) + w5*(2*u1 - f4),
     u1p = 2*s0pp + h2*w4 - w5
  */
   u0p = sqr(s0pp) + w4*(h2*(s0pp - u1) + 2*v1 + h1) + w5*(2*u1 - f4);
   u1p = 2*s0pp + h2*w4 - w5;

  /* Step 9:
     w1 = l2p - u1p, w2 = u1p*w1 + u0p - l1p, v1p = w2*w3 - v1 - h1 + h2*u1p,
     w2 = u0p*w1 - l0p, v0p = w2*w3 - v0 - h0 + h2*u0p
  */
   w1 = l2p - u1p; 
   w2 = u1p*w1 + u0p - l1p;
   v1p = w2*w3 - v1 - h1 + h2*u1p;
   w2 = u0p*w1 - l0p;
   v0p = w2*w3 - v0 - h0 + h2*u0p;

  /* Step 10:
     return [up, vp]
  */
  SetCoeff(up, 2, 1);
  SetCoeff(up, 1, u1p);
  SetCoeff(up, 0, u0p);

  SetCoeff(vp, 1, v1p);
  SetCoeff(vp, 0, v0p);

  x.set_upoly(up); 
  x.set_vpoly(vp);

  x.update();

#if DEBUG_LEVEL > 1
  cout << "Entered doubling(). " << endl;
  //  cout << x << endl;
#endif

  assert(OK = OK && x.is_valid_divisor());
  return OK;
}
void KochHillDrag::setForce() const
{
    if (scaleDia_ > 1)
        Info << "KochHill using scale = " << scaleDia_ << endl;
    else if (particleCloud_.cg() > 1){
        scaleDia_=particleCloud_.cg();
        Info << "KochHill using scale from liggghts cg = " << scaleDia_ << endl;
    }

    // get viscosity field
    #ifdef comp
        const volScalarField nufField = particleCloud_.turbulence().mu()/rho_;
    #else
        const volScalarField& nufField = particleCloud_.turbulence().nu();
    #endif

    vector position(0,0,0);
    scalar voidfraction(1);
    vector Ufluid(0,0,0);
    vector drag(0,0,0);
    label cellI=0;

    vector Us(0,0,0);
    vector Ur(0,0,0);
    scalar ds(0);
    scalar nuf(0);
    scalar rho(0);
    scalar magUr(0);
    scalar Rep(0);
	scalar Vs(0);
	scalar volumefraction(0);
    scalar betaP(0);

    interpolationCellPoint<scalar> voidfractionInterpolator_(voidfraction_);
    interpolationCellPoint<vector> UInterpolator_(U_);

    #include "setupProbeModel.H"

    for(int index = 0;index <  particleCloud_.numberOfParticles(); index++)
    {
        //if(mask[index][0])
        //{
            cellI = particleCloud_.cellIDs()[index][0];
            drag = vector(0,0,0);
            betaP = 0;
            Vs = 0;
            Ufluid =vector(0,0,0);
            voidfraction=0;

            if (cellI > -1) // particle Found
            {
                if(interpolation_)
                {
	                position = particleCloud_.position(index);
                    voidfraction = voidfractionInterpolator_.interpolate(position,cellI);
                    Ufluid = UInterpolator_.interpolate(position,cellI);
                    //Ensure interpolated void fraction to be meaningful
                    // Info << " --> voidfraction: " << voidfraction << endl;
                    if(voidfraction>1.00) voidfraction = 1.00;
                    if(voidfraction<0.40) voidfraction = 0.40;
                }else
                {
					voidfraction = voidfraction_[cellI];
                    Ufluid = U_[cellI];
                }

                Us = particleCloud_.velocity(index);
                Ur = Ufluid-Us;
                ds = particleCloud_.d(index);
                nuf = nufField[cellI];
                rho = rho_[cellI];
                magUr = mag(Ur);
				Rep = 0;
                Vs = ds*ds*ds*M_PI/6;
                volumefraction = 1-voidfraction+SMALL;

                if (magUr > 0)
                {
                    // calc particle Re Nr
                    Rep = ds/scaleDia_*voidfraction*magUr/(nuf+SMALL);

                    // calc model coefficient F0
                    scalar F0=0.;
                    if(volumefraction < 0.4)
                    {
                        F0 = (1+3*sqrt((volumefraction)/2)+135/64*volumefraction*log(volumefraction)
                              +16.14*volumefraction
                             )/
                             (1+0.681*volumefraction-8.48*sqr(volumefraction)
                              +8.16*volumefraction*volumefraction*volumefraction
                             );
                    } else {
                        F0 = 10*volumefraction/(voidfraction*voidfraction*voidfraction);
                    }

                    // calc model coefficient F3
                    scalar F3 = 0.0673+0.212*volumefraction+0.0232/pow(voidfraction,5);

                    //Calculate F
                    scalar F = voidfraction * (F0 + 0.5*F3*Rep);

                    // calc drag model coefficient betaP
                    betaP = 18.*nuf*rho/(ds/scaleDia_*ds/scaleDia_)*voidfraction*F;

                    // calc particle's drag
                    drag = Vs*betaP*Ur*scaleDrag_;

                    if (modelType_=="B")
                        drag /= voidfraction;
                }

                if(verbose_ && index >=0 && index <2)
                {
                    Pout << "cellI = " << cellI << endl;
                    Pout << "index = " << index << endl;
                    Pout << "Us = " << Us << endl;
                    Pout << "Ur = " << Ur << endl;
                    Pout << "ds = " << ds << endl;
                    Pout << "ds/scale = " << ds/scaleDia_ << endl;
                    Pout << "rho = " << rho << endl;
                    Pout << "nuf = " << nuf << endl;
                    Pout << "voidfraction = " << voidfraction << endl;
                    Pout << "Rep = " << Rep << endl;
                    Pout << "betaP = " << betaP << endl;
                    Pout << "drag = " << drag << endl;
                }

                //Set value fields and write the probe
                if(probeIt_)
                {
                    #include "setupProbeModelfields.H"
                    vValues.append(drag);           //first entry must the be the force
                    vValues.append(Ur);
                    sValues.append(Rep);
                    sValues.append(betaP);
                    sValues.append(voidfraction);
                    particleCloud_.probeM().writeProbe(index, sValues, vValues);
                }    
            }
            // set force on particle
            if(treatExplicit_) for(int j=0;j<3;j++) expForces()[index][j] += drag[j];
            else  for(int j=0;j<3;j++) impForces()[index][j] += drag[j];

            // set Cd
            if(implDEM_)
            {
                for(int j=0;j<3;j++) fluidVel()[index][j]=Ufluid[j];

                if (modelType_=="B" && cellI > -1)
                    Cds()[index][0] = Vs*betaP/voidfraction*scaleDrag_;
                else
                    Cds()[index][0] = Vs*betaP*scaleDrag_;

            }else{
                for(int j=0;j<3;j++) DEMForces()[index][j] += drag[j];
            }

        //}
    }
}
Exemple #3
0
CMT_FUNC flt_type<T1> saturate_II(const T1& x)
{
    const flt_type<T1> xx = sqr(abs(static_cast<flt_type<T1>>(x)) + 1);
    return mulsign((xx - 1) / (xx + 1), static_cast<flt_type<T1>>(x));
}
Exemple #4
0
int tickProcessBullet(gnode * grid,bullet * b){
	if (b->detonate==0){
		bullet_type * type=typesBulletGet(b->type);
		if (type==0){
			b->detonate=1;
			return 0;
		}
		//vec dir={0,0};
//		printDebug("!!%g %g\n",b->position.x,b->position.y);
		//float length=getDir(&b->position,&b->destination,&dir);
		float delta=1;
		if (type->move_type!=SHOT){
			b->position.x+=b->direction.x*type->speed;
			b->position.y+=b->direction.y*type->speed;
			delta=type->speed;
			if (delta<0.2)
				delta=0.2;
		}else{
			b->position.x=b->destination.x;
			b->position.y=b->destination.y;
		}
		setMask(b,BULLET_POSITION);
		if (eqInD(b->position.x,b->destination.x,delta)&&
				eqInD(b->position.y,b->destination.y,delta)){
			int i,j,k;
			int multiple=0;
			int x=(int)b->position.x;
			int y=(int)b->position.y;
			int xid,yid;
			int _id=to2d(x,y);
			if ( x<0 || y<0 || x>=config.gridsize || y>=config.gridsize)
				goto out;
			//tower search
			{
				tower * tmp;
				if (_id<sqr(config.gridsize))
					if ((tmp=grid[_id].tower)>0)
						if(config.players[tmp->owner].group!=b->group){
							damageTower(tmp,b);
							multiple++;
						}
			}	
			
			if (type->attack_type==SINGLE && multiple>0)
				goto out;
			
			//npc search
			{
				npc* tmp;
				if (_id<sqr(config.gridsize))
					for(j=0;j<MAX_GROUPS;j++)
						for(tmp=grid[_id].npcs[j];
								tmp!=0;tmp=tmp->next)
							if (config.players[tmp->owner].group!=b->group)
								if (eqInD(tmp->position.x,b->position.x,delta)&&
									eqInD(tmp->position.y,b->position.y,delta))
								//attack npc near the destination 
								{	
									damageNpc(tmp,b);
									multiple++;
									if (type->attack_type==SINGLE)
										goto out;
									if (type->attack_type==MULTIPLE && 
										multiple>type->area)
										goto out;
								}
				//if npc not in node, see nodes near
				i=0;
				for(j=0;j<config.area_size[i];j++)
					if (((xid=x+config.area_array[i][j].x)>=0 && x+config.area_array[i][j].x<config.gridsize) &&
							((yid=y+config.area_array[i][j].y)>=0 && y+config.area_array[i][j].y<config.gridsize))
						for(k=0;k<MAX_GROUPS;k++)
							for(tmp=grid[to2d(xid,yid)].npcs[k];
								tmp!=0;tmp=tmp->next)
									if (config.players[tmp->owner].group!=b->group)
										if (eqInD(tmp->position.x,b->position.x,delta)&&
											eqInD(tmp->position.y,b->position.y,delta))
										//attack first npc in gnode, need to correct
										{	
											damageNpc(tmp,b);
											multiple++;
											if (type->attack_type==SINGLE)
												goto out;
											if (type->attack_type==MULTIPLE && 
												multiple>type->area)
												goto out;
										}
			}
			
			//add area damage to Npc
			//add area damage to towers
			if (type->attack_type==AREA ||
			 	type->attack_type==AREA_FF){
				//add area gamage	
				npc* tmp;
				for (i=0;i<type->area;i++)
					for(j=0;j<config.area_size[i];j++)
						if (((xid=x+config.area_array[i][j].x)>=0 && x+config.area_array[i][j].x<config.gridsize) &&
								((yid=y+config.area_array[i][j].y)>=0 && y+config.area_array[i][j].y<config.gridsize)){
							//tower
							if (grid[to2d(xid,yid)].tower!=0)
								if (canSee(grid,&b->position,&(vec){xid+0.5,yid+0.5})>0)
									if(type->attack_type==AREA?
											config.players[grid[to2d(xid,yid)].tower->owner].group!=b->group
											:1){
										damageTower(grid[to2d(xid,yid)].tower,b);
									}
							//npc
							for (k=0;k<MAX_GROUPS;k++)
								if (type->attack_type==AREA?k!=b->group:1)
									for(tmp=grid[to2d(xid,yid)].npcs[k];
											tmp!=0;tmp=tmp->next)
										if (canSee(grid,&b->position,&tmp->position)>0)
											damageNpc(tmp,b);
						}
			}	
out:
			b->detonate++;
			setMask(b,BULLET_DETONATE);
		}else{
			if (b->ntarget!=0){
				if (glength(&b->ntarget->position,&b->source)>b->max_dist){
					b->ntarget=0;
				}else{
					//TODO: add folow attr
					memcpy(&b->destination,&b->ntarget->position,sizeof(b->destination));
					getDir(&b->position,&b->destination,&b->direction);
				}
			}
		}
	}
	return 0;
}
Exemple #5
0
void decimate_inplace(MutableTriangleTopology& mesh, RawField<TV,VertexId> X,
                      const T distance, const T max_angle, const int min_vertices, const T boundary_distance) {
  if (mesh.n_vertices() <= min_vertices)
    return;
  const T area = sqr(distance);
  const T sign_sqr_min_cos = sign_sqr(max_angle > .99*pi ? -1 : cos(max_angle));

  // Finds the best edge to collapse v along.  Returns (q(e),dst(e)).
  const auto best_collapse = [&mesh,X](const VertexId v) {
    Quadric q = compute_quadric(mesh,X,v);

    // Find the best edge, ignoring normal constraints
    T min_q = inf;
    HalfedgeId min_e;
    for (const auto e : mesh.outgoing(v)) {
      const T qx = q(X[mesh.dst(e)]);
      if (min_q > qx) {
        min_q = qx;
        min_e = e;
      }
    }
    return tuple(min_q,mesh.dst(min_e));
  };

  // Initialize quadrics and heap
  Heap heap(mesh.n_vertices_);
  for (const auto v : mesh.vertices()) {
    const auto qe = best_collapse(v);
    if (qe.x <= area)
      heap.inv_heap[v] = heap.heap.append(tuple(v,qe.x,qe.y));
  }
  heap.make();

  // Update the quadric information for a vertex
  const auto update = [&heap,best_collapse,area](const VertexId v) {
    const auto qe = best_collapse(v);
    if (qe.x <= area)
      heap.set(v,qe.x,qe.y);
    else
      heap.erase(v);
  };

  // Repeatedly collapse the best vertex
  while (heap.size()) {
    const auto v = heap.pop();

    // Do these vertices still exist?
    if (mesh.valid(v.x) && mesh.valid(v.y)) {
      const auto e = mesh.halfedge(v.x,v.y);

      // Is the collapse invalid?
      if (e.valid() && mesh.is_collapse_safe(e)) {
        const auto vs = mesh.src(e),
                   vd = mesh.dst(e);
        const auto xs = X[vs],
                   xd = X[vd];

        // Are we moving a boundary vertex too far from its two boundary lines?
        {
          const auto b = mesh.halfedge(vs);
          if (mesh.is_boundary(b)) {
            const auto x0 = X[mesh.dst(b)],
                       x1 = X[mesh.src(mesh.prev(b))];
            if (   line_point_distance(simplex(xs,x0),xd) > boundary_distance
                || line_point_distance(simplex(xs,x1),xd) > boundary_distance)
              goto bad;
          }
        }

        // Do the normals change too much?
        if (sign_sqr_min_cos > -1)
          for (const auto ee : mesh.outgoing(vs))
            if (e!=ee && !mesh.is_boundary(ee)) {
              const auto v2 = mesh.opposite(ee);
              if (v2 != vd) {
                const auto x1 = X[mesh.dst(ee)],
                           x2 = X[v2];
                const auto n0 = cross(x2-x1,xs-x1),
                           n1 = cross(x2-x1,xd-x1);
                if (sign_sqr(dot(n0,n1)) < sign_sqr_min_cos*sqr_magnitude(n0)*sqr_magnitude(n1))
                  goto bad;
              }
            }

        // Collapse vs onto vd, then update the heap
        mesh.unsafe_collapse(e);
        if (mesh.n_vertices() <= min_vertices)
          break;
        update(vd);
        for (const auto e : mesh.outgoing(vd))
          update(mesh.dst(e));
      }
    }
    bad:;
  }
}
static void draw_dodeca( void )
{
  GLuint list;

#define TAU ((SQRT5+1)/2)

  list = glGenLists( 1 );
  glNewList( list, GL_COMPILE );
  PENTAGON(1,seno,edgedivisions,sqr(TAU) * sqrt((TAU+2)/5) / 2);
  glEndList();

  glPushMatrix();
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[0]);
  glCallList(list);
  glRotatef(180,0,0,1);
  glPushMatrix();
  glRotatef(-dodecaangle,1,0,0);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[1]);
  glCallList(list);
  glPopMatrix();
  glPushMatrix();
  glRotatef(-dodecaangle,cos72,sin72,0);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[2]);
  glCallList(list);
  glPopMatrix();
  glPushMatrix();
  glRotatef(-dodecaangle,cos72,-sin72,0);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[3]);
  glCallList(list);
  glPopMatrix();
  glPushMatrix();
  glRotatef(dodecaangle,cos36,-sin36,0);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[4]);
  glCallList(list);
  glPopMatrix();
  glRotatef(dodecaangle,cos36,sin36,0);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[5]);
  glCallList(list);
  glPopMatrix();
  glRotatef(180,1,0,0);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[6]);
  glCallList(list);
  glRotatef(180,0,0,1);
  glPushMatrix();
  glRotatef(-dodecaangle,1,0,0);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[7]);
  glCallList(list);
  glPopMatrix();
  glPushMatrix();
  glRotatef(-dodecaangle,cos72,sin72,0);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[8]);
  glCallList(list);
  glPopMatrix();
  glPushMatrix();
  glRotatef(-dodecaangle,cos72,-sin72,0);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[9]);
  glCallList(list);
  glPopMatrix();
  glPushMatrix();
  glRotatef(dodecaangle,cos36,-sin36,0);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[10]);
  glCallList(list);
  glPopMatrix();
  glRotatef(dodecaangle,cos36,sin36,0);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialColor[11]);
  glCallList(list);

  glDeleteLists(list,1);
}
Exemple #7
0
double Point::distanceTo(Point &another_Point) {
    return sqrt ( sqr(__x - another_Point.__x) + sqr(__y - another_Point.__y) + sqr(__z - another_Point.__z))
}
Exemple #8
0
void calc_potential(const char *fn, atom_id **index, int gnx[],
                    double ***slPotential, double ***slCharge,
                    double ***slField, int *nslices,
                    t_topology *top, int ePBC,
                    int axis, int nr_grps, double *slWidth,
                    double fudge_z, gmx_bool bSpherical, gmx_bool bCorrect,
                    const output_env_t oenv)
{
    rvec *x0;              /* coordinates without pbc */
    matrix box;            /* box (3x3) */
    int natoms;            /* nr. atoms in trj */
    t_trxstatus *status;
    int **slCount,         /* nr. of atoms in one slice for a group */
        i,j,n,             /* loop indices */
        teller = 0,
        ax1=0, ax2=0,
        nr_frames = 0,     /* number of frames */
        slice;             /* current slice */
    double slVolume;         /* volume of slice for spherical averaging */
    double qsum,nn;
    real t;
    double z;
    rvec xcm;
    gmx_rmpbc_t  gpbc=NULL;

    switch(axis)
    {
    case 0:
        ax1 = 1;
        ax2 = 2;
        break;
    case 1:
        ax1 = 0;
        ax2 = 2;
        break;
    case 2:
        ax1 = 0;
        ax2 = 1;
        break;
    default:
        gmx_fatal(FARGS,"Invalid axes. Terminating\n");
    }

    if ((natoms = read_first_x(oenv,&status,fn,&t,&x0,box)) == 0)
        gmx_fatal(FARGS,"Could not read coordinates from statusfile\n");

    if (! *nslices)
        *nslices = (int)(box[axis][axis] * 10); /* default value */

    fprintf(stderr,"\nDividing the box in %d slices\n",*nslices);

    snew(*slField, nr_grps);
    snew(*slCharge, nr_grps);
    snew(*slPotential, nr_grps);

    for (i = 0; i < nr_grps; i++)
    {
        snew((*slField)[i], *nslices);
        snew((*slCharge)[i], *nslices);
        snew((*slPotential)[i], *nslices);
    }


    gpbc = gmx_rmpbc_init(&top->idef,ePBC,natoms,box);

    /*********** Start processing trajectory ***********/
    do
    {
        *slWidth = box[axis][axis]/(*nslices);
        teller++;
        gmx_rmpbc(gpbc,natoms,box,x0);

        /* calculate position of center of mass based on group 1 */
        calc_xcm(x0, gnx[0], index[0], top->atoms.atom, xcm, FALSE);
        svmul(-1,xcm,xcm);

        for (n = 0; n < nr_grps; n++)
        {
            /* Check whether we actually have all positions of the requested index
             * group in the trajectory file */
            if (gnx[n] > natoms)
            {
                gmx_fatal(FARGS, "You selected a group with %d atoms, but only %d atoms\n"
                          "were found in the trajectory.\n", gnx[n], natoms);
            }
            for (i = 0; i < gnx[n]; i++)   /* loop over all atoms in index file */
            {
                if (bSpherical)
                {
                    rvec_add(x0[index[n][i]], xcm, x0[index[n][i]]);
                    /* only distance from origin counts, not sign */
                    slice = norm(x0[index[n][i]])/(*slWidth);

                    /* this is a nice check for spherical groups but not for
                       all water in a cubic box since a lot will fall outside
                       the sphere
                      if (slice > (*nslices))
                      {
                       fprintf(stderr,"Warning: slice = %d\n",slice);
                      }
                    */
                    (*slCharge)[n][slice] += top->atoms.atom[index[n][i]].q;
                }
                else
                {
                    z = x0[index[n][i]][axis];
                    z = z + fudge_z;
                    if (z < 0)
                        z += box[axis][axis];
                    if (z > box[axis][axis])
                        z -= box[axis][axis];
                    /* determine which slice atom is in */
                    slice = (z / (*slWidth));
                    (*slCharge)[n][slice] += top->atoms.atom[index[n][i]].q;
                }
            }
        }
        nr_frames++;
    } while (read_next_x(oenv,status,&t,natoms,x0,box));

    gmx_rmpbc_done(gpbc);

    /*********** done with status file **********/
    close_trj(status);

    /* slCharge now contains the total charge per slice, summed over all
       frames. Now divide by nr_frames and integrate twice
     */


    if (bSpherical)
        fprintf(stderr,"\n\nRead %d frames from trajectory. Calculating potential"
                "in spherical coordinates\n", nr_frames);
    else
        fprintf(stderr,"\n\nRead %d frames from trajectory. Calculating potential\n",
                nr_frames);

    for (n =0; n < nr_grps; n++)
    {
        for (i = 0; i < *nslices; i++)
        {
            if (bSpherical)
            {
                /* charge per volume is now the summed charge, divided by the nr
                of frames and by the volume of the slice it's in, 4pi r^2 dr
                */
                slVolume = 4*M_PI * sqr(i) * sqr(*slWidth) * *slWidth;
                if (slVolume == 0)
                {
                    (*slCharge)[n][i] = 0;
                }
                else
                {
                    (*slCharge)[n][i] = (*slCharge)[n][i] / (nr_frames * slVolume);
                }
            }
            else
            {
                /* get charge per volume */
                (*slCharge)[n][i] = (*slCharge)[n][i] * (*nslices) /
                                    (nr_frames * box[axis][axis] * box[ax1][ax1] * box[ax2][ax2]);
            }
        }
        /* Now we have charge densities */
    }

    if(bCorrect && !bSpherical)
    {
        for(n =0; n < nr_grps; n++)
        {
            nn = 0;
            qsum = 0;
            for (i = 0; i < *nslices; i++)
            {
                if( fabs((*slCharge)[n][i]) >= GMX_DOUBLE_MIN )
                {
                    nn++;
                    qsum += (*slCharge)[n][i];
                }
            }
            qsum /= nn;
            for (i = 0; i < *nslices; i++)
            {
                if( fabs((*slCharge)[n][i]) >= GMX_DOUBLE_MIN )
                {
                    (*slCharge)[n][i] -= qsum;
                }
            }
        }
    }

    for(n =0; n < nr_grps; n++)
    {
        /* integrate twice to get field and potential */
        p_integrate((*slField)[n], (*slCharge)[n], *nslices, *slWidth);
    }


    if(bCorrect && !bSpherical)
    {
        for(n =0; n < nr_grps; n++)
        {
            nn = 0;
            qsum = 0;
            for (i = 0; i < *nslices; i++)
            {
                if( fabs((*slCharge)[n][i]) >= GMX_DOUBLE_MIN )
                {
                    nn++;
                    qsum += (*slField)[n][i];
                }
            }
            qsum /= nn;
            for (i = 0; i < *nslices; i++)
            {
                if( fabs((*slCharge)[n][i]) >= GMX_DOUBLE_MIN )
                {
                    (*slField)[n][i] -= qsum;
                }
            }
        }
    }

    for(n =0; n < nr_grps; n++)
    {
        p_integrate((*slPotential)[n],(*slField)[n], *nslices, *slWidth);
    }

    /* Now correct for eps0 and in spherical case for r*/
    for (n = 0; n < nr_grps; n++)
        for (i = 0; i < *nslices; i++)
        {
            if (bSpherical)
            {
                (*slPotential)[n][i] = ELC * (*slPotential)[n][i] * -1.0E9 /
                                       (EPS0 * i * (*slWidth));
                (*slField)[n][i] = ELC * (*slField)[n][i] * 1E18 /
                                   (EPS0 * i * (*slWidth));
            }
            else
            {
                (*slPotential)[n][i] = ELC * (*slPotential)[n][i] * -1.0E9 / EPS0  ;
                (*slField)[n][i] = ELC * (*slField)[n][i] * 1E18 / EPS0;
            }
        }

    sfree(x0);  /* free memory used by coordinate array */
}
Exemple #9
0
/////////////////////////////////////////////////
// Yahoo-Feature-Selection
TYFSelBs::TYFSelBs(
 const TYFSelType& FSelType, const double& FSels,
 const bool& FSelPosWords, const PAttrEst& AttrEst,
 const TYNegDsType& _YNegDsType, const TYPriorType& YPriorType,
 const PYBs& YBs, const PYDsBs& YDsBs, const PNotify& Notify):
  YNegDsType(_YNegDsType), DocIdToWordIdEstVV(YBs->GetDocs()){
  TNotify::OnNotify(Notify, ntInfo, "Start Feature Selection");

  PDmHd DmHd=new TYDmHd(YBs, YDsBs);
  PYWordDs NegWordDs=TYDmDs::GetNegWordDs(YNegDsType, YBs, YDsBs);
  PTbValSplit BoolValSplit=TTbValSplit::GetBoolValSplit();

  int DocId=YBs->FFirstDocId(); int DocIds=0;
  while (YBs->FNextDocId(DocId)){
    PYWordDs PosWordDs=YDsBs->GetWordDs(DocId); DocIds++;

    int SelWordIds;
    switch (FSelType){
      case yfstFix: SelWordIds=int(FSels); break;
      case yfstPosPrc:
        SelWordIds=int(FSels*double(PosWordDs->GetWordIds())); break;
      case yfstUnionPrc:{
        PYWordDs UnionWordDs=TYWordDs::GetMerged(PosWordDs, NegWordDs, 1, 1);
        SelWordIds=int(FSels*double(UnionWordDs->GetWordIds())); break;}
      default: Fail; SelWordIds=0;
    }
    if (SelWordIds<=0){SelWordIds=1;}

    PDmDs DmDs=PDmDs(new TYDmDs(
     false, DocId, YNegDsType, YPriorType, YBs, YDsBs, DmHd));
    PDmDs PriorDmDs=PDmDs(new TYDmDs(
     true, DocId, yndtAll, yptDocs, YBs, YDsBs, DmHd));
    PYWordDs WordDs; PYWordDs TrvWordDs;
    TIntH SelWordIdH(SelWordIds);
    TFltIntKdV WordEstIdKdV(SelWordIds, 0);
    for (int CDsc=0; CDsc<TTbVal::BoolVals; CDsc++){
      switch (CDsc){
        case 0: WordDs=NegWordDs; break;
        case 1: WordDs=PosWordDs; break;
        default: Fail;
      }
      if (FSelPosWords){TrvWordDs=PosWordDs;} else {TrvWordDs=WordDs;}
      int WordIdN=TrvWordDs->FFirstWordId(); int WordId;
      while (TrvWordDs->FNextWordId(WordIdN, WordId)){
        if (SelWordIdH.IsKey(WordId)){continue;}
        double WordEst;
        if (AttrEst.Empty()){
          // Shortcut: Odds-Ratio
          double PriorSumW=YBs->GetDocs();
//          double PriorSumW=PosWordDs->GetDocs()+NegWordDs->GetDocs();
          IAssert(PriorSumW>0);
          double S1C0Prb=NegWordDs->GetWordPrb(WordId);
          double S1C1Prb=PosWordDs->GetWordPrb(WordId);

          if (S1C0Prb==0){S1C0Prb=1/sqr(PriorSumW);}
          if (S1C0Prb==1){S1C0Prb=1-(1/sqr(PriorSumW));}
          double OddsS1C0=S1C0Prb/(1-S1C0Prb);

          if (S1C1Prb==0){S1C1Prb=1/sqr(PriorSumW);}
          if (S1C1Prb==1){S1C1Prb=1-(1/sqr(PriorSumW));}
          double OddsS1C1=S1C1Prb/(1-S1C1Prb);

          WordEst=log(OddsS1C1/OddsS1C0);
        } else {
          WordEst=AttrEst->GetAttrQ(WordId, BoolValSplit, DmDs, PriorDmDs);
        }
        WordEstIdKdV.AddSorted(TFltIntKd(WordEst, WordId), false, SelWordIds);
        SelWordIdH.AddKey(WordId);
      }
    }
    TIntFltKdV& WordIdEstKdV=DocIdToWordIdEstVV[DocId];
    WordIdEstKdV.Gen(WordEstIdKdV.Len(), 0);
    for (int WordIdN=0; WordIdN<WordEstIdKdV.Len(); WordIdN++){
      double WordEst=WordEstIdKdV[WordIdN].Key;
      int WordId=WordEstIdKdV[WordIdN].Dat;
      WordIdEstKdV.Add(TIntFltKd(WordId, WordEst));
    }
    WordIdEstKdV.Sort();
    if (DocIds%100==0){
      TNotify::OnNotify(Notify, ntInfo,
       TStr("...")+TInt::GetStr(DocIds)+" Selections.");}
  }
  TNotify::OnNotify(Notify, ntInfo,
   TStr("Feature Selection Finished (")+ TInt::GetStr(DocIds)+").");
}
Exemple #10
0
local void histogram(void)
{
  int i,j,k, l, kmin, kmax, lcount = 0;
  real count[MAXHIST], under, over;
  real xdat,ydat,xplt,yplt,dx,r,sum,sigma2, q, qmax;
  real mean, sigma, skew, kurt, lmin, lmax, median;
  Moment m;

  if (Qint) warning("new feature integrate=t");

  
  dprintf (0,"read %d values\n",npt);
  dprintf (0,"min and max value: [%g : %g]\n",xmin,xmax);
  if (!Qauto) {
    xmin = xrange[0];
    xmax = xrange[1];
    dprintf (0,"min and max value reset to : [%g : %g]\n",xmin,xmax);
    lmin = xmax;
    lmax = xmin;
    for (i=0; i<npt; i++) {
      if (x[i]>xmin && x[i]<=xmax) {
	lmin = MIN(lmin, x[i]);
	lmax = MAX(lmax, x[i]);
      }
    }
    dprintf (0,"min and max value in range : [%g : %g]\n",lmin,lmax);
  } 
  
  for (k=0; k<nsteps; k++)
    count[k] = 0;		/* init histogram */
  under = over = 0;
  
  ini_moment(&m,4,0);
  for (i=0; i<npt; i++) {
    if (Qbin) {
      k=ring_index(nsteps,bins,x[i]);
    } else {
      if (xmax != xmin)
	k = (int) floor((x[i]-xmin)/(xmax-xmin)*nsteps);
      else
	k = 0;
      dprintf(1,"%d k=%d %g\n",i,k,x[i]);
    }
    if (k==nsteps && x[i]==xmax) k--;     /* include upper edge */
    if (k<0)       { under++; continue; }
    if (k>=nsteps) { over++;  continue; }
    count[k] = count[k] + (Qint ? x[i] : 1);
    dprintf (4,"%d : %f %d\n",i,x[i],k);
    accum_moment(&m,x[i],1.0);
  }
  if (under > 0) error("bug: under = %d",under);
  if (over  > 0) error("bug: over = %d",over);
  under = Nunder;
  over  = Nover;

  mean = mean_moment(&m);
  sigma = sigma_moment(&m);
  skew = skewness_moment(&m);
  kurt = kurtosis_moment(&m);
  
  if (nsigma > 0) {    /* remove outliers iteratively, starting from the largest */
    iq = (int *) allocate(npt*sizeof(int));
    for (i=0; i<npt; i++) {
#if 1
      iq[i] = x[i] < xmin  || x[i] > xmax;
#else
      iq[i] = 0;
#endif
    }
    lcount = 0;
    do {               /* loop to remove outliers one by one */
      qmax = -1.0;
      for (i=0, l=-1; i<npt; i++) {     /* find largest deviation from current mean */
	if (iq[i]) continue;            /* but skip previously flagged points */
	q = (x[i]-mean)/sigma;
	q = ABS(q);
	if (q > qmax) {
	  qmax = q;
	  l = i;
	}
      }
      if (qmax > nsigma) {
	lcount++;
	iq[l] = 1;
	decr_moment(&m,x[l],1.0);
	mean = mean_moment(&m);
	sigma = sigma_moment(&m);
	skew = skewness_moment(&m);
	kurt = kurtosis_moment(&m);
	dprintf(1,"%d/%d: removing point %d, m/s=%g %g qmax=%g\n",
		lcount,npt,l,mean,sigma,qmax);
	if (sigma <= 0) {
	  /* RELATED TO presetting MINMAX */
	  warning("BUG");
	  accum_moment(&m,x[l],1.0);
	  mean = mean_moment(&m);
	  sigma = sigma_moment(&m);
	  skew = skewness_moment(&m);
	  kurt = kurtosis_moment(&m);
	  dprintf(1,"%d/%d: LAST removing point %d, m/s=%g %g qmax=%g\n",
		  lcount,npt,l,mean,sigma,qmax);
	  break;
	  
	}
	
      } else
	dprintf(1,"%d/%d: keeping point %d, m/s=%g %g qmax=%g\n",
		lcount,npt,l,mean,sigma,qmax);
      
      /* if (lcount > npt/2) break; */
    } while (qmax > nsigma);
    dprintf(0,"Removed %d/%d points for nsigma=%g\n",lcount,npt,nsigma);
    
    /* @algorithm      left shift array values from mask array */
    /* now shift all points into the array, decreasing npt */
    /* otherwise the median is not correctly computed */
    for (i=0, k=0; i<npt; i++) {
      dprintf(1,"iq->%d\n",iq[i]);
      if (iq[i]) k++;
      if (k==0) continue;  /* ?? */
      if (i-k < 0) continue;
      dprintf(1,"SHIFT: %d <= %d\n",i-k,i);
      x[i-k] = x[i];
    }
    npt -= lcount;   /* correct for outliers */
    free(iq);
  } /* nsigma > 0 */
  
  if (npt != n_moment(&m))
    error("Counting error, probably in removing outliers...");
  dprintf (0,"Number of points     : %d\n",npt);
  if (npt>1)
    dprintf (0,"Mean and dispersion  : %g %g %g\n",mean,sigma,sigma/sqrt(npt-1.0));
  else
    dprintf (0,"Mean and dispersion  : %g %g 0.0\n",mean,sigma);
  dprintf (0,"Skewness and kurtosis: %g %g\n",skew,kurt);
  if (Qmedian) {
    
    if (npt % 2) 
      median = x[(npt-1)/2];
    else
      median = 0.5 * (x[npt/2] + x[npt/2-1]);
    dprintf (0,"Median               : %g\n",median);
  }
  dprintf (0,"Sum                  : %g\n",show_moment(&m,1));
  
  if (lcount > 0) {
    warning("Recompute histogram because of outlier removals");
    /* recompute histogram if we've lost some outliers */
    for (k=0; k<nsteps; k++)
      count[k] = 0;		/* init histogram */
    under = over = 0;
    for (i=0; i<npt; i++) {
      if (xmax != xmin)
	k = (int) floor((x[i]-xmin)/(xmax-xmin)*nsteps);
      else
	k = 0;
      if (k==nsteps && x[i]==xmax) k--;     /* include upper edge */
      if (k<0)       { under++; continue; }
      if (k>=nsteps) { over++;  continue; }
      count[k] = count[k] + (Qint ? x[i] : 1);
      dprintf (4,"%d : %f %d\n",i,x[i],k);
    }
    if (under > 0 || over > 0) error("under=%d over=%d in recomputed histo",under,over);
  }
  
  dprintf (3,"Histogram values : \n");
  dx=(xmax-xmin)/nsteps;
  kmax=0;
  sum=0.0;
  for (k=0; k<nsteps; k++) {
    sum = sum + dx*count[k];
    if (ylog) {
      if (count[k]>0.0)
	count[k] = log10(count[k]);
      else
	count[k] = -1.0;
    }
    if (count[k]>kmax)
      kmax=count[k];
    dprintf (3,"%f ",count[k]);
    if (Qcumul) {
      if (k==0)
	count[k] += under;
      else
	count[k] += count[k-1];
    }
  }
  dprintf (3,"\n");
  sigma2 = 2.0 * sigma * sigma;	/* gaussian */
  sum /= sigma * sqrt(2*PI);	/* scaling factor for equal area gauss */
  
  if (ylog && over>0)  over =  log10(over);
  if (ylog && under>0) under = log10(under);
  
  kmax *= 1.1;		/* add 10% */
  if (Qcumul) {
    if (Qint) 
      kmax = count[nsteps-1];
    else
      kmax = npt;
  }
  if (maxcount>0)		/* force scaling by user ? */
    kmax=maxcount;	
  
  if (Qtab) {
    maxcount = 0;
    for (k=0; k<nsteps; k++)
      maxcount = MAX(maxcount,count[k]);
    if (maxcount>0)
      r = 29.0/maxcount;
    else
      r = 1.0;
    printf("  Bin    Value          Number\n");
    printf("       Underflow   %d\n",Nunder);
    for (k=0; k<nsteps; k++) {
      j = (int) (r*count[k]) + 1;
      if (ylog) printf("%3d %13.6g %13.6g ", 
		       k+1, xmin+(k+0.5)*dx, count[k]);
      else printf("%3d %13.6g %8d ", 
		  k+1, xmin+(k+0.5)*dx, (int)count[k]);
      while (j-- > 0) printf("*");
      printf("\n");
    }
    printf("       Overflow    %d\n",Nover);
    stop(0);
  }
  
#ifdef YAPP
  /*	PLOTTING */	
  plinit("***",0.0,20.0,0.0,20.0);

  xplot[0] = xmin;
  xplot[1] = xmax;
  yplot[0] = 0.0;
  yplot[1] = (real) kmax;
  xaxis (2.0, 2.0, 16.0, xplot, -7, xtrans, xlab);
  xaxis (2.0, 18.0,16.0, xplot, -7, xtrans, NULL);
  yaxis (2.0, 2.0, 16.0, yplot, -7, ytrans, ylab);
  yaxis (18.0, 2.0, 16.0, yplot, -7, ytrans, NULL);
  
  pljust(-1);     /* set to left just */
  pltext(input,2.0,18.2,0.32,0.0);             /* filename */
  pljust(1);
  pltext(headline,18.0,18.2,0.24,0.0);         /* headline */
  pljust(-1);     /* return to left just */
  
  xdat=xmin;
  dx=(xmax-xmin)/nsteps;
  plmove(xtrans(xmin),ytrans(0.0));
  for (k=0; k<nsteps; k++) {	/* nsteps= */
    xplt = xtrans(xdat);
    yplt = ytrans((real)count[k]);
    plline (xplt,yplt);
    xdat += dx;
    xplt = xtrans(xdat);
    plline (xplt,yplt);	
  }
  plline(xplt,ytrans(0.0));
  
  for (i=0; i<nxcoord; i++) {
    plmove(xtrans(xcoord[i]),ytrans(yplot[0]));
    plline(xtrans(xcoord[i]),ytrans(yplot[1]));
  }
  
  if (Qgauss) {                   /* plot model and residuals */
    if (ylog)
      plmove(xtrans(xmin),ytrans(-1.0));
    else
      plmove(xtrans(xmin),ytrans(0.0));
    for (k=0; k<100; k++) {
      xdat = xmin + (k+0.5)*(xmax-xmin)/100.0;
      ydat = sum * exp( -sqr(xdat-mean)/sigma2);
      if (ylog) ydat = log10(ydat);
      plline(xtrans(xdat), ytrans(ydat));
    }
  }
  
  if (Qresid) {
    
    plltype(0,2);   /* dotted residuals */
    xdat = xmin+0.5*dx;
    dprintf(1,"# residuals from gauss\n");
    for (k=0; k<nsteps; k++, xdat +=dx) {
      ydat = sum * exp( -sqr(xdat-mean)/sigma2);
      dprintf(1,"%g %g %g\n",xdat,count[k],ydat);
      if (ylog) ydat = log10(ydat);
      ydat = count[k] - ydat;
      if (k==0)
	plmove(xtrans(xdat),ytrans(ydat));
      else
	plline(xtrans(xdat),ytrans(ydat));
    }
    plltype(0,1);   /* back to normal line type */
    
  }
  plstop();
#endif
}
Exemple #11
0
int main()
{
  init_latpars();
  
  cout<<"ml_phys: "<<ml_phys<<endl;
  cout<<"ms_phys: "<<ms_phys<<endl;
  cout<<"mc_phys: "<<mc_phys<<endl;
  cout<<endl;
  cout<<"Zp380: "<<Zp[0]<<endl;
  cout<<"a380: "<<lat[0]<<endl;
  cout<<"amc_phys380: "<<amc_phys[0]<<endl;
  cout<<"1/a380: "<<1/lat[0]<<endl<<endl;
  
  cout<<"Zp390: "<<Zp[1]<<endl;
  cout<<"a390: "<<lat[1]<<endl;
  cout<<"1/a390: "<<1/lat[1]<<endl<<endl;
  
  cout<<"Zp405: "<<Zp[3]<<endl;
  cout<<"a405: "<<lat[2]<<endl;
  cout<<"1/a405: "<<1/lat[2]<<endl<<endl;
  
  cout<<"Zp420: "<<Zp[3]<<endl;
  cout<<"a420: "<<lat[3]<<endl;
  cout<<"amc_phys420: "<<amc_phys[3]<<endl;
  cout<<"1/a420: "<<1/lat[3]<<endl<<endl;

  cout<<"mc: "<<mc_phys<<endl<<endl;
  cout<<"r0: "<<smart_print(r0)<<endl<<endl;
  
  double ghat=0.45;
  //double Amed=-1.200,Aerr=0.5;
  double Amed=-2.000,Aerr=0.9;
  boot A(nboot,njack);
  A.fill_gauss(Amed,Aerr,28732);
  
  cout<<A<<endl;
  cout<<"db0: "<<db0<<endl;
  //cout<<"r0: "<<r0<<endl;
  cout<<"f0:"<<f0<<endl;
  
  boot arg=4*M_PI*f0;
  double c=3.0/4*(1+3*sqr(ghat));
  boot den=arg*arg;

  boot corr1=A/db0;
  boot corr2=c/den*log(den);
  
  cout<<corr1<<endl;
  cout<<corr2<<endl;
  cout<<corr1+corr2<<endl;
  
  ofstream t("/tmp/data_cecilia");
  t<<"iboot\t\t2B0\t\tf0"<<endl;
  for(int iboot=0;iboot<nboot;iboot++)
    t<<iboot+1<<"\t\t"<<db0[iboot]<<"\t\t"<<f0[iboot]<<endl;
  t<<"med\t\t"<<db0.med()<<"\t\t"<<f0.med()<<endl;
  t<<"err\t\t"<<db0.err()<<"\t"<<f0.err()<<endl;
  
  cout<<db0<<endl;
  cout<<f0<<endl;
  cout<<"ccond: ["<<smart_print(pow(db0*f0*f0/4,1.0/3)*1000)<<" MeV]^3"<<endl;
  
  return 0;
}
Exemple #12
0
QVector<EcgStDescriptor> EcgStAnalyzer::analyze(const EcgStData &data, double sampleFreq)
{
    QVector<EcgStDescriptor> result;

    int num = data.rData.size();
    int snum = data.ecgSamples.size();

    if (num < 2 || snum == 0)
        return result;

    int p = smoothSize;
    int w = detectionSize;
    double lamdba = morphologyCoeff;

    QVector<int> stOn(num);
    QVector<int> stEnd(num);

    int i;

    // detect STend points
    for (i = 0; i < num; i++)
    {
        double ka = data.jData[i];
        double kb = data.tEndData[i];

        QVector<double> aVal(kb - ka + 1);

        for (int k = ka; k <= kb; k++)
        {
            int ke = std::max(1, std::min(k + p, snum));
            int nsr = ke - k + p + 1;
            QVector<double> wnd = data.ecgSamples.mid(k - p - 1, nsr);
            double sk = EcgUtils::sum(wnd) / nsr;
            ke = std::max(1, std::min(k + w - 1, snum));

            QVector<double> sqr(ke - k);
            for (int j = 0; j < sqr.size(); j++) {
                double smp = data.ecgSamples[k + j - 1] - sk;

                if (algorithm == ST_QUADRATIC)
                    sqr[j] = smp * smp;
                else
                    sqr[j] = smp;
            }

            aVal[k - ka] = EcgUtils::sum(sqr);
        }

        int kp, kp1, kp2;
        double ap1 = EcgUtils::max(aVal, &kp1);
        double ap2 = EcgUtils::min(aVal, &kp2);

        double at = fabs(ap1) / fabs(ap2);
        if ((1.0 / lamdba < at) && (at < lamdba))
            kp = std::min(kp1, kp2);
        else
            kp = fabs(ap1) > fabs(ap2) ? kp1 : kp2;

        stEnd[i] = ka + kp;
    }

    // calculate heart rate
    QVector<int> rr = EcgUtils::diff(data.rData);
    QVector<double> hr(num);
    for (i = 0; i < num - 1; i++)
        hr[i] = 60.0 / ((double) rr[i] / sampleFreq);
    hr[num - 1] = hr[num - 2];

    for (i = 0; i < num; i++)
    {
        double rt = stEnd[i] - data.rData[i];

        double x;
        double hrc = hr[i];
        if (hrc < 100)
            x = 0.4;
        else if (hrc < 110)
            x = 0.45;
        else if (hrc < 120)
            x = 0.5;
        else
            x = 0.55;

        int test = (int) round((double) data.rData[i] + x * rt);
        stOn[i] = std::min(data.jData[i] + 1, test);
    }

    // create and classify interval descriptors
    for (i = 0; i < num; i++)
    {
        EcgStDescriptor desc;

        desc.STOn = stOn[i];
        desc.STEnd = stEnd[i];
        desc.STMid = desc.STOn + (int) round((desc.STEnd - desc.STOn) / 2.0);

        desc.offset = data.ecgSamples[desc.STMid];

        int x1 = desc.STOn;
        int x2 = desc.STMid;
        double y1 = data.ecgSamples[x1];
        double y2 = desc.offset;
        double d1 = (y1 - y2) / ((x1 - x2) / sampleFreq);
        desc.slope1 = RAD_TO_DEG(atan(d1));

        x1 = desc.STMid;
        x2 = desc.STEnd;
        y1 = desc.offset;
        y2 = data.ecgSamples[x2];
        double d2 = (y1 - y2) / ((x1 - x2) / sampleFreq);
        desc.slope2 = RAD_TO_DEG(atan(d2));

        classifyInterval(desc);

        result.push_back(desc);
    }

    return result;
}
void InstantRadiosityRenderer::processPixel(uint32_t threadID, uint32_t tileID, const Vec2u& pixel) const {
    PixelSensor pixelSensor(getSensor(), pixel, getFramebufferSize());
    RaySample raySample;
    float positionPdf, directionPdf;
    auto We = pixelSensor.sampleExitantRay(getScene(), getFloat2(threadID), getFloat2(threadID), raySample, positionPdf, directionPdf);

    auto L = zero<Vec3f>();

    if(We != zero<Vec3f>() && raySample.pdf) {
        auto I = getScene().intersect(raySample.value);
        BSDF bsdf(-raySample.value.dir, I, getScene());
        if(I) {
            // Direct illumination
            for(auto& vpl: m_EmissionVPLBuffer) {
                RaySample shadowRay;
                auto Le = vpl.pLight->sampleDirectIllumination(getScene(), vpl.emissionVertexSample, I, shadowRay);

                if(shadowRay.pdf) {
                    auto contrib = We * Le * bsdf.eval(shadowRay.value.dir) * abs(dot(I.Ns, shadowRay.value.dir)) /
                            (vpl.lightPdf * shadowRay.pdf * m_nLightPathCount * raySample.pdf);

                    if(contrib != zero<Vec3f>()) {
                        if(!getScene().occluded(shadowRay.value)) {
                            L += contrib;
                        }
                    }
                }
            }

            // Indirect illumination
            for(auto& vpl: m_SurfaceVPLBuffer) {
                auto dirToVPL = vpl.intersection.P - I.P;
                auto dist = length(dirToVPL);

                if(dist > 0.f) {
                    dirToVPL /= dist;

                    auto fs1 = bsdf.eval(dirToVPL);
                    auto fs2 = vpl.bsdf.eval(-dirToVPL);
                    auto geometricFactor = abs(dot(I.Ns, dirToVPL)) * abs(dot(vpl.intersection.Ns, -dirToVPL)) / sqr(dist);

                    auto contrib = We * vpl.power * fs1 * fs2 * geometricFactor / raySample.pdf;
                    if(contrib != zero<Vec3f>()) {
                        Ray shadowRay(I, vpl.intersection, dirToVPL, dist);
                        if(!getScene().occluded(shadowRay)) {
                            L += contrib;
                        }
                    }
                }
            }
        }
    }

    accumulate(0, getPixelIndex(pixel.x, pixel.y), Vec4f(L, 1.f));
}
Exemple #14
0
NS_G2_START_IMPL

static bool_t add_diff(divisor& x, const divisor& a, const divisor& b)
     // x = a + b where a != b via explicit formulas
     // c.f. Algorithm 14.9 of HOEHCC
     // Assumes upolys of a and b are both of degree 2 and have no common
     // factor.
{
  /* Variables 
We choose to use local variables for now to make the function thread safe.
Note that this may affect the performance of the program as opposed to 
the method of passing along the temporary variables.
  */

  bool_t OK = TRUE;

  const field_t f4 = coeff(a.get_curve().get_f(), 4), 
                h1 = coeff(a.get_curve().get_h(), 1), 
                h2 = coeff(a.get_curve().get_h(), 2),
                h0 = coeff(a.get_curve().get_h(), 0), 
    u11 = coeff(a.get_upoly(), 1), u10 = coeff(a.get_upoly(), 0),
    u21 = coeff(b.get_upoly(), 1), u20 = coeff(b.get_upoly(), 0),
    v11 = coeff(a.get_vpoly(), 1), v10 = coeff(a.get_vpoly(), 0),
    v21 = coeff(b.get_vpoly(), 1), v20 = coeff(b.get_vpoly(), 0);

  field_t z1, z2, z3, z4, r, inv1, inv0, w0, w1, w2, w3, s1p, s0p,
    w4, w5, s0pp, l2p, l1p, l0p, u0p, u1p, v1p, v0p;

  poly_t up, vp;

  /* Explicit formulas */

  /* Step 1: 
     Compute r = Res(u1, u2).
   z1 = u11 - u21, z2 = u20 - u10, z3 = u11*z1 + z2, z4 = z1*u10, 
   r = z2*z3 + z4*z1 
  */
  z1 = u11 - u21;
  z2 = u20 - u10;
  z3 = u11*z1 + z2;
  z4 = z1*u10;
  r = z2*z3 + z4*z1;

  assert(!IsZero(r));  // Res(u1, u2)<>0, i.e., GCD(u1, u2) = 1

  /* Step 2: 
     inv1 = z1, inv0 = z3 
  */
  inv1 = z1; 
  inv0 = z3;

  /* Step 3: 
     w0 = v10 - v20, w1 = v11 - v21, w2 = inv0*w0, w3 = inv1*w1, 
     s1p = (inv0 + inv1)*(w0 + w1) - w2 - w3*(1 + u11), s0p = w2 - z4*w1
     If s1p = 0, handled by Cantor's algorithm. 
  */
  w0 = v10 - v20; 
  w1 = v11 - v21; 
  w2 = inv0*w0; 
  w3 = inv1*w1;
  s1p = (inv0 + inv1)*(w0 + w1) - w2 - w3*(1 + u11);

  // Special case
  if (IsZero(s1p)) 
    return add_cantor(x, a, b);

  s0p = w2 - z4*w1;
  

  /* Step 4:
     w1 = 1/(r*s1p), w2 = r*w1, w3 = s1p^2*w1, w4 = r*w2, w5 = w4^2, 
     s0pp = s0p*w2
  */ 
  w1 = 1/(r*s1p);
  w2 = r*w1;
  w3 = sqr(s1p)*w1;
  w4 = r*w2;
  w5 = sqr(w4);
  s0pp = s0p*w2;

  /* Step 5:
     l2p = u21 + s0pp, l1p = u21*s0pp + u20, l0p = u20*s0pp
  */
  l2p = u21 + s0pp;
  l1p = u21*s0pp + u20;
  l0p = u20*s0pp;

  /* Step 6:
     u0p = (s0pp - u11)*(s0pp - z1 + h2*w4) - u10,
     u0p = u0p + l1p + (h1 + 2*v21)*w4 + (2*u21 + z1 - f4)*w5,
     u1p = 2*s0pp - z1 + h2*w4 - w5
  */
  u0p = (s0pp - u11)*(s0pp - z1 + h2*w4) - u10;
  u0p = u0p + l1p + (h1 + 2*v21)*w4 + (2*u21 + z1 - f4)*w5;
  u1p = 2*s0pp - z1 + h2*w4 - w5;

  /* Step 7:
     w1 = l2p - u1p, w2 = u1p*w1 + u0p - l1p, v1p = w2*w3 - v21 - h1 + h2*u1p,
     w2 = u0p*w1 - l0p, v0p = w2*w3 - v20 - h0 + h2*u0p
  */
  w1 = l2p - u1p;
  w2 = u1p*w1 + u0p - l1p;
  v1p = w2*w3 - v21 - h1 + h2*u1p;
  w2 = u0p*w1 - l0p;
  v0p = w2*w3 - v20 - h0 + h2*u0p;

  /* Step 8:
     return [up, vp] = [x^2 + u1p*x + u0p, v1p*x + v0p]
  */ 
  SetCoeff(up, 2, 1);
  SetCoeff(up, 1, u1p);
  SetCoeff(up, 0, u0p);

  SetCoeff(vp, 1, v1p);
  SetCoeff(vp, 0, v0p);

  x.set_upoly(up); 
  x.set_vpoly(vp);

  x.update();

#if DEBUG_LEVEL > 1
  cout << "Entered add_diff()" << endl;
  cout << x << endl;
#endif

  assert(OK = ( OK && x.is_valid_divisor()) );

  return OK;
}
Exemple #15
0
double H1Projection::get_error(int split, int son, const Ord3 &order)
{
	_F_
	sln->enable_transform(false);

	calc_projection(split, son + 1, order);

	Ord3 order_rhs = order;
	QuadPt3D *pt = quad->get_points(order_rhs);
	int np = quad->get_num_points(order_rhs);

	double error = 0.0;
	for (int i = 0; i < int_ns[split]; i++) {
		Trf *tr = get_trf(int_trf[split][i]);

		unsigned int son_idx = base_elem->get_son(int_son[son + 1][i]);
		sln->set_active_element(mesh->elements[son_idx]);
		sln->precalculate(np, pt, FN_DEFAULT);
		scalar *rval = sln->get_fn_values();
		scalar *rdx, *rdy, *rdz;
		sln->get_dx_dy_dz_values(rdx, rdy, rdz);

		QuadPt3D *tpt = new QuadPt3D[np];
		transform_points(np, pt, tr, tpt);
		scalar *prfn = new scalar[np];
    scalar *prdx = new scalar[np];
    scalar *prdy = new scalar[np];
    scalar *prdz = new scalar[np];
		memset(prfn, 0, np * sizeof(double));
		memset(prdx, 0, np * sizeof(double));
		memset(prdy, 0, np * sizeof(double));
		memset(prdz, 0, np * sizeof(double));

		for (int i = 0; i < n_fns; i++) {
#ifndef H3D_COMPLEX
			double *tmp = new double[np];
			ss->get_fn_values(fn_idx[i], np, tpt, 0, tmp);
			blas_axpy(np, proj_coef[i], tmp, 1, prfn, 1);
			ss->get_dx_values(fn_idx[i], np, tpt, 0, tmp);
			blas_axpy(np, proj_coef[i], tmp, 1, prdx, 1);
			ss->get_dy_values(fn_idx[i], np, tpt, 0, tmp);
			blas_axpy(np, proj_coef[i], tmp, 1, prdy, 1);
			ss->get_dz_values(fn_idx[i], np, tpt, 0, tmp);
			blas_axpy(np, proj_coef[i], tmp, 1, prdz, 1);
      delete tmp;
#else
			double *tmp = new double[np];
			scalar *sctmp = new scalar[np];
			ss->get_fn_values(fn_idx[i], np, tpt, 0, tmp);
			for (int ii = 0; ii < np; ii++) sctmp[ii] = tmp[ii];
			blas_axpy(np, proj_coef[i], sctmp, 1, prfn, 1);
			ss->get_dx_values(fn_idx[i], np, tpt, 0, tmp);
			for (int ii = 0; ii < np; ii++) sctmp[ii] = tmp[ii];
			blas_axpy(np, proj_coef[i], sctmp, 1, prdx, 1);
			ss->get_dy_values(fn_idx[i], np, tpt, 0, tmp);
			for (int ii = 0; ii < np; ii++) sctmp[ii] = tmp[ii];
			blas_axpy(np, proj_coef[i], sctmp, 1, prdy, 1);
			ss->get_dz_values(fn_idx[i], np, tpt, 0, tmp);
			for (int ii = 0; ii < np; ii++) sctmp[ii] = tmp[ii];
			blas_axpy(np, proj_coef[i], sctmp, 1, prdz, 1);
      delete [] tmp;
      delete [] sctmp;
#endif
		}

		for (int k = 0; k < np; k++)
			error += pt[k].w *
				(sqr(rval[k] - prfn[k]) +
				 sqr(rdx[k] * mdx[split] - prdx[k]) +
				 sqr(rdy[k] * mdy[split] - prdy[k]) +
				 sqr(rdz[k] * mdz[split] - prdz[k]));
    delete [] prfn;
    delete [] prdx;
    delete [] prdy;
    delete [] prdz;
    delete tpt;
	}

  sln->enable_transform(true);

	return error;
}
Exemple #16
0
//===========================================================================
void TTarget::CalcPosition()
{
   TTargetAccess *ta = &TargetAccess[TargetAccess_Count - 1];


   TImpuls aImpuls;
   TFloat  aRo, aFi, aRo1, aRo2;
   TFloat  aTempQ = 0, aTempE = 0;
   TFloat  aSumQ = 0, aSumE = 0;
   // -----------------------------
       aImpuls.E1   = 0;
       aImpuls.E2   = 0;
       aImpuls.Time = 0;


   // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   // -------------- Расчет координат по методу №1 ---------------
   // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
          for (int i = 0; i < ta->Impuls_Count; i ++) {
                Get_Ro1_Ro2(ta->Impuls[i], aRo1, aRo2);
                //Get_Ro_Fi(ta->Impuls[i], aRo, aFi);

             // ----------------------------------------------------------
                fDirectionalCosines.cell[1][0] = -sin(aRo1) + ___Fixed_Far_Ravnosignal_DirectionalCosines.cell[1][0];
                fDirectionalCosines.cell[2][0] =  sin(aRo2) + ___Fixed_Far_Ravnosignal_DirectionalCosines.cell[2][0];
                fDirectionalCosines.cell[0][0] = sqrt(1 - sqr(fDirectionalCosines.cell[1][0]) - sqr(fDirectionalCosines.cell[2][0]));
                /*fDirectionalCosines.cell[1][0] = sin(aRo*cos(aFi)) + ___Fixed_Far_Ravnosignal_DirectionalCosines.cell[1][0];
                fDirectionalCosines.cell[2][0] = sin(aRo*sin(aFi)) + ___Fixed_Far_Ravnosignal_DirectionalCosines.cell[2][0];
                fDirectionalCosines.cell[0][0] = sqrt(1 - sqr(fDirectionalCosines.cell[1][0]) - sqr(fDirectionalCosines.cell[2][0]));*/

             // --------- Положение цели в системе координат ФАР ---------
                Calc_Angle(fDirectionalCosines, aTempQ, aTempE);
                aSumQ = aSumQ + aTempQ;
                aSumE = aSumE + aTempE;
          }
       // --------- Положение цели в системе координат ФАР ---------
          aSumQ = aSumQ / (TFloat) ta->Impuls_Count;
          aSumE = aSumE / (TFloat) ta->Impuls_Count;
          ta->Coord_M1.Far.Q = aSumQ;
          ta->Coord_M1.Far.E = aSumE;
       // --------- Положение цели в системе координат GEO ---------
          TransformCoordinates(tm_Fixed_Geo_Far, ta->Coord_M1.Far.Q, ta->Coord_M1.Far.E
                                               , ta->Coord_M1.Geo.Q, ta->Coord_M1.Geo.E);

   // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   // -------------- Расчет координат по методу №2 "Опредиление координат цели по методу накопления амплитуд"---------------
   // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
          for (int i = 0; i < ta->Impuls_Count; i ++) {
             aImpuls.E1 += ta->Impuls[i].E1;
             aImpuls.E2 += ta->Impuls[i].E2;
          }
          aImpuls.E1 = aImpuls.E1 / (TFloat) ta->Impuls_Count;
          aImpuls.E2 = aImpuls.E2 / (TFloat) ta->Impuls_Count;

       // -----------------------------
          Get_Ro1_Ro2(aImpuls, aRo1, aRo2);
          //Get_Ro_Fi(aImpuls, aRo, aFi);

       // -----------------------------
          fDirectionalCosines.cell[1][0] = -sin(aRo1) + ___Fixed_Far_Ravnosignal_DirectionalCosines.cell[1][0];
          fDirectionalCosines.cell[2][0] =  sin(aRo2) + ___Fixed_Far_Ravnosignal_DirectionalCosines.cell[2][0];
          fDirectionalCosines.cell[0][0] = sqrt(1 - sqr(fDirectionalCosines.cell[1][0]) - sqr(fDirectionalCosines.cell[2][0]));
          /*fDirectionalCosines.cell[1][0] = sin(aRo*cos(aFi)) + ___Fixed_Far_Ravnosignal_DirectionalCosines.cell[1][0];
          fDirectionalCosines.cell[2][0] = sin(aRo*sin(aFi)) + ___Fixed_Far_Ravnosignal_DirectionalCosines.cell[2][0];
          fDirectionalCosines.cell[0][0] = sqrt(1 - sqr(fDirectionalCosines.cell[1][0]) - sqr(fDirectionalCosines.cell[2][0]));*/

       // --------- Положение цели в системе координат ФАР ---------
          Calc_Angle(fDirectionalCosines, ta->Coord_M2.Far.Q, ta->Coord_M2.Far.E);

       // --------- Положение цели в системе координат GEO ---------
          TransformCoordinates(tm_Fixed_Geo_Far, ta->Coord_M2.Far.Q, ta->Coord_M2.Far.E
                                               , ta->Coord_M2.Geo.Q, ta->Coord_M2.Geo.E);
       // --------- Расчет Таненых Тета Фи  ---------
       // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       // Внимание тут наколка -
          TFloat aa, bb;
          aFar->Calc_DeltaQ_DeltaAlfa_Teta_Fi(ta->Ideal_Coord_Far.Q, ta->Ideal_Coord_Far.E, aa, bb);
              ta->Ideal_Coord_Far.Q = aa; ta->Ideal_Coord_Far.E = bb;
          aFar->Calc_DeltaQ_DeltaAlfa_Teta_Fi(ta->Coord_M1.Far.Q,    ta->Coord_M1.Far.E,    aa, bb);
              ta->Coord_M1.Far.Q = aa;    ta->Coord_M1.Far.E = bb;
          aFar->Calc_DeltaQ_DeltaAlfa_Teta_Fi(ta->Coord_M2.Far.Q,    ta->Coord_M2.Far.E,    aa, bb);
              ta->Coord_M2.Far.Q = aa;    ta->Coord_M2.Far.E = bb;
       // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

       // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

          ta->Coord_M1.Far.Q -= ta->Ideal_Coord_Far.Q;
          ta->Coord_M1.Far.E -= ta->Ideal_Coord_Far.E;
          ta->Coord_M1.Geo.Q -= ta->Ideal_Coord_Geo.Q;
          ta->Coord_M1.Geo.E -= ta->Ideal_Coord_Geo.E;

          ta->Coord_M2.Far.Q -= ta->Ideal_Coord_Far.Q;
          ta->Coord_M2.Far.E -= ta->Ideal_Coord_Far.E;
          ta->Coord_M2.Geo.Q -= ta->Ideal_Coord_Geo.Q;
          ta->Coord_M2.Geo.E -= ta->Ideal_Coord_Geo.E;

   // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   // --------  Расчет текущих ошибок ------------
      if (TargetAccess_Count > 0) {
         // ------ Расчет средних значений ----
           for (int i = 0; i < TargetAccess_Count; i++){
             ta->Coord_M1.Far.fCurSumQ += TargetAccess[i].Coord_M1.Far.Q;
             ta->Coord_M1.Far.fCurSumE += TargetAccess[i].Coord_M1.Far.E;
             ta->Coord_M1.Geo.fCurSumQ += TargetAccess[i].Coord_M1.Geo.Q;
             ta->Coord_M1.Geo.fCurSumE += TargetAccess[i].Coord_M1.Geo.E;

             ta->Coord_M2.Far.fCurSumQ += TargetAccess[i].Coord_M2.Far.Q;
             ta->Coord_M2.Far.fCurSumE += TargetAccess[i].Coord_M2.Far.E;
             ta->Coord_M2.Geo.fCurSumQ += TargetAccess[i].Coord_M2.Geo.Q;
             ta->Coord_M2.Geo.fCurSumE += TargetAccess[i].Coord_M2.Geo.E;
           }
             ta->Coord_M1.Far.SredErrorQ = ta->Coord_M1.Far.fCurSumQ / (TFloat) TargetAccess_Count;
             ta->Coord_M1.Far.SredErrorE = ta->Coord_M1.Far.fCurSumE / (TFloat) TargetAccess_Count;
             ta->Coord_M1.Geo.SredErrorQ = ta->Coord_M1.Geo.fCurSumQ / (TFloat) TargetAccess_Count;
             ta->Coord_M1.Geo.SredErrorE = ta->Coord_M1.Geo.fCurSumE / (TFloat) TargetAccess_Count;

             ta->Coord_M2.Far.SredErrorQ = ta->Coord_M2.Far.fCurSumQ / (TFloat) TargetAccess_Count;
             ta->Coord_M2.Far.SredErrorE = ta->Coord_M2.Far.fCurSumE / (TFloat) TargetAccess_Count;
             ta->Coord_M2.Geo.SredErrorQ = ta->Coord_M2.Geo.fCurSumQ / (TFloat) TargetAccess_Count;
             ta->Coord_M2.Geo.SredErrorE = ta->Coord_M2.Geo.fCurSumE / (TFloat) TargetAccess_Count;
        // ---
           TFloat odds;
           for (int i = 0; i < TargetAccess_Count; i++){
             odds  = TargetAccess[i].Coord_M1.Far.Q - ta->Coord_M1.Far.SredErrorQ;  ta->Coord_M1.Far.SKOErrorQ += odds*odds;
             odds  = TargetAccess[i].Coord_M1.Far.E - ta->Coord_M1.Far.SredErrorE;  ta->Coord_M1.Far.SKOErrorE += odds*odds;
             odds  = TargetAccess[i].Coord_M1.Geo.Q - ta->Coord_M1.Geo.SredErrorQ;  ta->Coord_M1.Geo.SKOErrorQ += odds*odds;
             odds  = TargetAccess[i].Coord_M1.Geo.E - ta->Coord_M1.Geo.SredErrorE;  ta->Coord_M1.Geo.SKOErrorE += odds*odds;

             odds  = TargetAccess[i].Coord_M2.Far.Q - ta->Coord_M2.Far.SredErrorQ;  ta->Coord_M2.Far.SKOErrorQ += odds*odds;
             odds  = TargetAccess[i].Coord_M2.Far.E - ta->Coord_M2.Far.SredErrorE;  ta->Coord_M2.Far.SKOErrorE += odds*odds;
             odds  = TargetAccess[i].Coord_M2.Geo.Q - ta->Coord_M2.Geo.SredErrorQ;  ta->Coord_M2.Geo.SKOErrorQ += odds*odds;
             odds  = TargetAccess[i].Coord_M2.Geo.E - ta->Coord_M2.Geo.SredErrorE;  ta->Coord_M2.Geo.SKOErrorE += odds*odds;
           }
      }
      ta->Coord_M1.Far.SKOErrorQ = sqrt(ta->Coord_M1.Far.SKOErrorQ / (TFloat) TargetAccess_Count);
      ta->Coord_M1.Far.SKOErrorE = sqrt(ta->Coord_M1.Far.SKOErrorE / (TFloat) TargetAccess_Count);
      ta->Coord_M1.Geo.SKOErrorQ = sqrt(ta->Coord_M1.Geo.SKOErrorQ / (TFloat) TargetAccess_Count);
      ta->Coord_M1.Geo.SKOErrorE = sqrt(ta->Coord_M1.Geo.SKOErrorE / (TFloat) TargetAccess_Count);

      ta->Coord_M2.Far.SKOErrorQ = sqrt(ta->Coord_M2.Far.SKOErrorQ / (TFloat) TargetAccess_Count);
      ta->Coord_M2.Far.SKOErrorE = sqrt(ta->Coord_M2.Far.SKOErrorE / (TFloat) TargetAccess_Count);
      ta->Coord_M2.Geo.SKOErrorQ = sqrt(ta->Coord_M2.Geo.SKOErrorQ / (TFloat) TargetAccess_Count);
      ta->Coord_M2.Geo.SKOErrorE = sqrt(ta->Coord_M2.Geo.SKOErrorE / (TFloat) TargetAccess_Count);
    // ----------

      for (int i = 0; i < TargetAccess_Count; i++){
          if (ta->Coord_M1.Far.MaxErrorQ < fabs(TargetAccess[i].Coord_M1.Far.Q)) ta->Coord_M1.Far.MaxErrorQ = fabs(TargetAccess[i].Coord_M1.Far.Q);
          if (ta->Coord_M1.Far.MaxErrorE < fabs(TargetAccess[i].Coord_M1.Far.E)) ta->Coord_M1.Far.MaxErrorE = fabs(TargetAccess[i].Coord_M1.Far.E);
          if (ta->Coord_M1.Geo.MaxErrorQ < fabs(TargetAccess[i].Coord_M1.Geo.Q)) ta->Coord_M1.Geo.MaxErrorQ = fabs(TargetAccess[i].Coord_M1.Geo.Q);
          if (ta->Coord_M1.Geo.MaxErrorE < fabs(TargetAccess[i].Coord_M1.Geo.E)) ta->Coord_M1.Geo.MaxErrorE = fabs(TargetAccess[i].Coord_M1.Geo.E);
          if (ta->Coord_M2.Far.MaxErrorQ < fabs(TargetAccess[i].Coord_M2.Far.Q)) ta->Coord_M2.Far.MaxErrorQ = fabs(TargetAccess[i].Coord_M2.Far.Q);
          if (ta->Coord_M2.Far.MaxErrorE < fabs(TargetAccess[i].Coord_M2.Far.E)) ta->Coord_M2.Far.MaxErrorE = fabs(TargetAccess[i].Coord_M2.Far.E);
          if (ta->Coord_M2.Geo.MaxErrorQ < fabs(TargetAccess[i].Coord_M2.Geo.Q)) ta->Coord_M2.Geo.MaxErrorQ = fabs(TargetAccess[i].Coord_M2.Geo.Q);
          if (ta->Coord_M2.Geo.MaxErrorE < fabs(TargetAccess[i].Coord_M2.Geo.E)) ta->Coord_M2.Geo.MaxErrorE = fabs(TargetAccess[i].Coord_M2.Geo.E);
      }
}
void CollideEntity::updateMovement(float dt)
{	
	if (isEntityDead()) return;
	if (position.isFollowingPath()) return;
	vel.capLength2D(getMaxSpeed()*maxSpeedLerp.x);
	/*
	if (vel.getSquaredLength2D() > sqr(getMaxSpeed()))
	{
		vel.setLength2D(getMaxSpeed());
		vel.z = 0;
	}
	*/
	//Vector lastPos = pos;

	updateVel2(dt);

	if (doCusion)
	{
		Vector push;
		TileVector t(position+vel*dt);
		if (dsq->game->isObstructed(TileVector(t.x-1, t.y)))
		{
			push += Vector(1.25,0);
		}
		if (dsq->game->isObstructed(TileVector(t.x+1, t.y)))
		{
			push += Vector(-1.25,0);
		}
		if (dsq->game->isObstructed(TileVector(t.x, t.y-1)))
		{
			push += Vector(0,1.25);
		}
		if (dsq->game->isObstructed(TileVector(t.x, t.y+1)))
		{
			push += Vector(0,-1.25);
		}
		if (dsq->game->isObstructed(TileVector(t.x-1, t.y-1)))
		{
			push += Vector(0.5,0.5);
		}
		if (dsq->game->isObstructed(TileVector(t.x-1, t.y+1)))
		{
			push += Vector(0.5,-0.5);
		}
		if (dsq->game->isObstructed(TileVector(t.x+1, t.y-1)))
		{
			push += Vector(-0.5,0.5);
		}
		if (dsq->game->isObstructed(TileVector(t.x+1, t.y+1)))
		{
			push += Vector(-0.5,-0.5);
		}

		// cushion
		
		if (push.x != 0 || push.y != 0)
		{
			if (vel.getSquaredLength2D() > sqr(10))
			{
				push.setLength2D(100 * dt * 60);
				push.z = 0;
			}
			vel += push;
		}
	}
	
	Vector lastPosition = position;

	bool underWater = isUnderWater();
	if (!canLeaveWater)
	{
		if (!underWater && wasUnderWater)
		{
			// do clamp
			if (waterBubble)
			{
				waterBubble->clampPosition(&position, collideRadius);
			}
			else
			{
				position.y = dsq->game->getWaterLevel()+collideRadius;
			}
			
		}
	}
	/*
	if (!canLeaveWater)
	{
		if (waterBubble)
		{
		}
		else
		{
			if (position.y-collideRadius < dsq->game->getWaterLevel())
			{
				
			}
		}
	}
	*/

	bool collided = false;
	
	if (vel.x != 0 || vel.y != 0)
	{

		const int hw = collideRadius;
		bool freeRange = false;

		if (isv(EV_COLLIDELEVEL,1))
		{
			
			

			bool doesFreeRange = !isPullable();
			if (doesFreeRange)
			{
				if (dsq->game->collideCircleWithGrid(position, hw))
				{
					// starting in a collision state
					freeRange = true;
				}
			}
		}
		
		//Vector lastPosition = lastPos;
		Vector newPosition = position + (getMoveVel() * dt);
		position = newPosition;

		if (isv(EV_COLLIDELEVEL,1))
		{
			if (getState() == STATE_PUSH)
			{
				if (!freeRange && dsq->game->collideCircleWithGrid(position, hw))
				{
					position = lastPosition;
					collided = true;
					bounce(bounceAmount);
				}
			}
			else
			{			
				if (!freeRange && ((!canLeaveWater && !isUnderWater() && wasUnderWater) || dsq->game->collideCircleWithGrid(position, hw)))
				{
					position = lastPosition;
					onHitWall();
					bounce(bounceAmount);
					collided = true;
				}
			}
		}
	}

	if (collided && friction != 0 && (vel.x != 0 || vel.y != 0))
	{
		Vector fric = vel;
		fric.setLength2D(-friction);
		vel.z = 0;
		vel += fric*dt;
	}

	//doFriction(dt);
	
	if (!collided && weight != 0)
	{
		vel += Vector(0, weight*dt);
	}
	for (int i = 0; i < attachedEntities.size(); i++)
	{
		attachedEntities[i]->position = this->position + attachedEntitiesOffsets[i];
		attachedEntities[i]->rotation = this->rotation;
	}	

	wasUnderWater = underWater;
}
int main() {
  float dist[8][8] = {
	  {0.00, 4.69, 6.79, 3.50, 3.11, 4.46, 5.57, 3.00},
	  {4.69, 0.00, 2.10, 2.27, 2.65, 2.36, 1.99, 1.74},
	  {6.79, 2.10, 0.00, 3.78, 4.53, 2.83, 2.44, 3.79},
	  {3.50, 2.27, 3.78, 0.00, 1.98, 4.35, 2.07, 0.53},
	  {3.11, 2.65, 4.53, 1.98, 0.00, 3.80, 3.31, 1.47},
	  {4.46, 2.36, 2.83, 4.35, 3.80, 0.00, 4.35, 3.82},
	  {5.57, 1.99, 2.44, 2.07, 3.31, 4.35, 0.00, 2.57},
	  {3.00, 1.74, 3.79, 0.53, 1.47, 3.82, 2.57, 0.00},
  };
  igraph_t g;
  igraph_matrix_t coords, dist_mat;
  igraph_real_t vc;
  igraph_arpack_options_t options;
  int i, j;
  srand(time(0));

  igraph_arpack_options_init(&options);

  igraph_tree(&g, 10, 2, IGRAPH_TREE_UNDIRECTED);
  igraph_matrix_init(&coords, 0, 0);
  igraph_layout_mds(&g, &coords, 0, 2, &options);
  if (MATRIX(coords, 0, 0) > 0) {
    for (i = 0; i < igraph_matrix_nrow(&coords); i++)
      MATRIX(coords, i, 0) *= -1;
  }
  if (MATRIX(coords, 0, 1) < 0) {
    for (i = 0; i < igraph_matrix_nrow(&coords); i++)
      MATRIX(coords, i, 1) *= -1;
  }
  igraph_matrix_print(&coords);
  igraph_matrix_destroy(&coords);
  igraph_destroy(&g);

  igraph_full(&g, 8, IGRAPH_UNDIRECTED, 0);
  igraph_matrix_init(&coords, 8, 2);
  igraph_matrix_init(&dist_mat, 8, 8);
  for (i = 0; i < 8; i++)
    for (j = 0; j < 2; j++)
      MATRIX(coords, i, j) = rand() % 1000;
  for (i = 0; i < 8; i++)
    for (j = i+1; j < 8; j++) {
      double dist_sq = 0.0;
      dist_sq += sqr(MATRIX(coords, i, 0)-MATRIX(coords, j, 0));
      dist_sq += sqr(MATRIX(coords, i, 1)-MATRIX(coords, j, 1));
      MATRIX(dist_mat, i, j) = sqrt(dist_sq);
      MATRIX(dist_mat, j, i) = sqrt(dist_sq);
	}
  igraph_layout_mds(&g, &coords, &dist_mat, 2, &options);
  for (i = 0; i < 8; i++)
    for (j = i+1; j < 8; j++) {
      double dist_sq = 0.0;
      dist_sq += sqr(MATRIX(coords, i, 0)-MATRIX(coords, j, 0));
      dist_sq += sqr(MATRIX(coords, i, 1)-MATRIX(coords, j, 1));
      if (fabs(sqrt(dist_sq) - MATRIX(dist_mat, i, j)) > 1e-2) {
        printf("dist(%d,%d) should be %.4f, but it is %.4f\n",
				i, j, MATRIX(dist_mat, i, j), sqrt(dist_sq));
        return 1;
      }
    }
  igraph_matrix_destroy(&dist_mat);
  igraph_matrix_destroy(&coords);
  igraph_destroy(&g);

  return 0;
}
// Outputs derivatives (DRbar scheme) in the form of ds
StandardModel<Two_scale> StandardModel<Two_scale>::calc_beta() const
{
   static const double oneO16Pisq = 1.0 / (16.0 * PI * PI);
   DoubleMatrix dyu(3, 3), dyd(3, 3), dye(3, 3);
   DoubleVector dg(3);

   dyu(3, 3) = oneO16Pisq * yu.display(3, 3) * (
      -17.0 / 20.0 * sqr(displayGaugeCoupling(1))
      - 9.0 / 4.0 * sqr(displayGaugeCoupling(2))
      - 8.0 * sqr(displayGaugeCoupling(3))
      + 4.5 * sqr(yu.display(3, 3))
      + 1.5 * sqr(yd.display(3, 3))
      + sqr(ye.display(3, 3)));

   dyd(3, 3) = oneO16Pisq * yd.display(3, 3) * (
      -0.25 * sqr(displayGaugeCoupling(1))
      - 9.0 / 4.0 * sqr(displayGaugeCoupling(2))
      - 8.0 * sqr(displayGaugeCoupling(3))
      + 1.5 * sqr(yu.display(3, 3))
      + 4.5 * sqr(yd.display(3, 3))
      + sqr(ye.display(3, 3)));

   dye(3, 3) = oneO16Pisq * ye.display(3, 3) * (
      -9.0 / 4.0 * sqr(displayGaugeCoupling(1))
      -9.0 / 4.0 * sqr(displayGaugeCoupling(2))
      + 3.0 * sqr(yu.display(3, 3))
      + 3.0 * sqr(yd.display(3, 3))
      + 2.5 * sqr(ye.display(3, 3)));

   dg(1) = oneO16Pisq * std::pow(displayGaugeCoupling(1), 3) * (41.0 / 10.0);
   dg(2) = oneO16Pisq * std::pow(displayGaugeCoupling(2), 3) * (-19.0 / 6.0);
   dg(3) = oneO16Pisq * std::pow(displayGaugeCoupling(3), 3) * (-7.0);

   return StandardModel(dyu, dyd, dye, dg);
}
Exemple #20
0
int gmx_sorient(int argc, char *argv[])
{
    t_topology      top;
    int             ePBC = -1;
    char            title[STRLEN];
    t_trxstatus    *status;
    int             natoms;
    real            t;
    rvec           *xtop, *x;
    matrix          box;

    FILE           *fp;
    int             i, j, p, sa0, sa1, sa2, n, ntot, nf, m, *hist1, *hist2, *histn, nbin1, nbin2, nrbin;
    real           *histi1, *histi2, invbw, invrbw;
    double          sum1, sum2;
    int            *isize, nrefgrp, nrefat;
    atom_id       **index;
    char          **grpname;
    real            inp, outp, two_pi, nav, normfac, rmin2, rmax2, rcut, rcut2, r2, r, mass, mtot;
    real            c1, c2;
    char            str[STRLEN];
    gmx_bool        bTPS;
    rvec            xref, dx, dxh1, dxh2, outer;
    gmx_rmpbc_t     gpbc = NULL;
    t_pbc           pbc;
    const char     *legr[] = {
        "<cos(\\8q\\4\\s1\\N)>",
        "<3cos\\S2\\N(\\8q\\4\\s2\\N)-1>"
    };
    const char     *legc[] = {
        "cos(\\8q\\4\\s1\\N)",
        "3cos\\S2\\N(\\8q\\4\\s2\\N)-1"
    };

    const char     *desc[] = {
        "[TT]g_sorient[tt] analyzes solvent orientation around solutes.",
        "It calculates two angles between the vector from one or more",
        "reference positions to the first atom of each solvent molecule:[PAR]",
        "[GRK]theta[grk][SUB]1[sub]: the angle with the vector from the first atom of the solvent",
        "molecule to the midpoint between atoms 2 and 3.[BR]",
        "[GRK]theta[grk][SUB]2[sub]: the angle with the normal of the solvent plane, defined by the",
        "same three atoms, or, when the option [TT]-v23[tt] is set, ",
        "the angle with the vector between atoms 2 and 3.[PAR]",
        "The reference can be a set of atoms or",
        "the center of mass of a set of atoms. The group of solvent atoms should",
        "consist of 3 atoms per solvent molecule.",
        "Only solvent molecules between [TT]-rmin[tt] and [TT]-rmax[tt] are",
        "considered for [TT]-o[tt] and [TT]-no[tt] each frame.[PAR]",
        "[TT]-o[tt]: distribtion of [MATH][COS][GRK]theta[grk][SUB]1[sub][cos][math] for rmin<=r<=rmax.[PAR]",
        "[TT]-no[tt]: distribution of [MATH][COS][GRK]theta[grk][SUB]2[sub][cos][math] for rmin<=r<=rmax.[PAR]",
        "[TT]-ro[tt]: [MATH][CHEVRON][COS][GRK]theta[grk][SUB]1[sub][cos][chevron][math] and [MATH][CHEVRON]3[COS]^2[GRK]theta[grk][SUB]2[sub][cos]-1[chevron][math] as a function of the",
        "distance.[PAR]",
        "[TT]-co[tt]: the sum over all solvent molecules within distance r",
        "of [MATH][COS][GRK]theta[grk][SUB]1[sub][cos][math] and [MATH]3[COS]^2([GRK]theta[grk][SUB]2[sub])-1[cos][math] as a function of r.[PAR]",
        "[TT]-rc[tt]: the distribution of the solvent molecules as a function of r"
    };

    output_env_t    oenv;
    static gmx_bool bCom = FALSE, bVec23 = FALSE, bPBC = FALSE;
    static real     rmin = 0.0, rmax = 0.5, binwidth = 0.02, rbinw = 0.02;
    t_pargs         pa[] = {
        { "-com",  FALSE, etBOOL,  {&bCom},
          "Use the center of mass as the reference postion" },
        { "-v23",  FALSE, etBOOL,  {&bVec23},
          "Use the vector between atoms 2 and 3" },
        { "-rmin",  FALSE, etREAL, {&rmin}, "Minimum distance (nm)" },
        { "-rmax",  FALSE, etREAL, {&rmax}, "Maximum distance (nm)" },
        { "-cbin",  FALSE, etREAL, {&binwidth}, "Binwidth for the cosine" },
        { "-rbin",  FALSE, etREAL, {&rbinw}, "Binwidth for r (nm)" },
        { "-pbc",   FALSE, etBOOL, {&bPBC}, "Check PBC for the center of mass calculation. Only necessary when your reference group consists of several molecules." }
    };

    t_filenm        fnm[] = {
        { efTRX, NULL,  NULL,  ffREAD },
        { efTPS, NULL,  NULL,  ffREAD },
        { efNDX, NULL,  NULL,  ffOPTRD },
        { efXVG, NULL,  "sori.xvg",  ffWRITE },
        { efXVG, "-no", "snor.xvg",  ffWRITE },
        { efXVG, "-ro", "sord.xvg",  ffWRITE },
        { efXVG, "-co", "scum.xvg",  ffWRITE },
        { efXVG, "-rc", "scount.xvg",  ffWRITE }
    };
#define NFILE asize(fnm)

    parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW | PCA_BE_NICE,
                      NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, NULL, &oenv);

    two_pi = 2/M_PI;

    bTPS = (opt2bSet("-s", NFILE, fnm) || !opt2bSet("-n", NFILE, fnm) || bCom);
    if (bTPS)
    {
        read_tps_conf(ftp2fn(efTPS, NFILE, fnm), title, &top, &ePBC, &xtop, NULL, box,
                      bCom);
    }

    /* get index groups */
    printf("Select a group of reference particles and a solvent group:\n");
    snew(grpname, 2);
    snew(index, 2);
    snew(isize, 2);
    if (bTPS)
    {
        get_index(&top.atoms, ftp2fn_null(efNDX, NFILE, fnm), 2, isize, index, grpname);
    }
    else
    {
        get_index(NULL, ftp2fn(efNDX, NFILE, fnm), 2, isize, index, grpname);
    }

    if (bCom)
    {
        nrefgrp = 1;
        nrefat  = isize[0];
    }
    else
    {
        nrefgrp = isize[0];
        nrefat  = 1;
    }

    if (isize[1] % 3)
    {
        gmx_fatal(FARGS, "The number of solvent atoms (%d) is not a multiple of 3",
                  isize[1]);
    }

    /* initialize reading trajectory:                         */
    natoms = read_first_x(oenv, &status, ftp2fn(efTRX, NFILE, fnm), &t, &x, box);

    rmin2 = sqr(rmin);
    rmax2 = sqr(rmax);
    rcut  = 0.99*sqrt(max_cutoff2(guess_ePBC(box), box));
    if (rcut == 0)
    {
        rcut = 10*rmax;
    }
    rcut2 = sqr(rcut);

    invbw = 1/binwidth;
    nbin1 = 1+(int)(2*invbw + 0.5);
    nbin2 = 1+(int)(invbw + 0.5);

    invrbw = 1/rbinw;

    snew(hist1, nbin1);
    snew(hist2, nbin2);
    nrbin = 1+(int)(rcut/rbinw);
    if (nrbin == 0)
    {
        nrbin = 1;
    }
    snew(histi1, nrbin);
    snew(histi2, nrbin);
    snew(histn, nrbin);

    ntot = 0;
    nf   = 0;
    sum1 = 0;
    sum2 = 0;

    if (bTPS)
    {
        /* make molecules whole again */
        gpbc = gmx_rmpbc_init(&top.idef, ePBC, natoms);
    }
    /* start analysis of trajectory */
    do
    {
        if (bTPS)
        {
            /* make molecules whole again */
            gmx_rmpbc(gpbc, natoms, box, x);
        }

        set_pbc(&pbc, ePBC, box);
        n    = 0;
        inp  = 0;
        outp = 0;
        for (p = 0; (p < nrefgrp); p++)
        {
            if (bCom)
            {
                calc_com_pbc(nrefat, &top, x, &pbc, index[0], xref, bPBC);
            }
            else
            {
                copy_rvec(x[index[0][p]], xref);
            }

            for (m = 0; m < isize[1]; m += 3)
            {
                sa0 = index[1][m];
                sa1 = index[1][m+1];
                sa2 = index[1][m+2];
                range_check(sa0, 0, natoms);
                range_check(sa1, 0, natoms);
                range_check(sa2, 0, natoms);
                pbc_dx(&pbc, x[sa0], xref, dx);
                r2  = norm2(dx);
                if (r2 < rcut2)
                {
                    r = sqrt(r2);
                    if (!bVec23)
                    {
                        /* Determine the normal to the plain */
                        rvec_sub(x[sa1], x[sa0], dxh1);
                        rvec_sub(x[sa2], x[sa0], dxh2);
                        rvec_inc(dxh1, dxh2);
                        svmul(1/r, dx, dx);
                        unitv(dxh1, dxh1);
                        inp = iprod(dx, dxh1);
                        cprod(dxh1, dxh2, outer);
                        unitv(outer, outer);
                        outp = iprod(dx, outer);
                    }
                    else
                    {
                        /* Use the vector between the 2nd and 3rd atom */
                        rvec_sub(x[sa2], x[sa1], dxh2);
                        unitv(dxh2, dxh2);
                        outp = iprod(dx, dxh2)/r;
                    }
                    {
                        int ii = (int)(invrbw*r);
                        range_check(ii, 0, nrbin);
                        histi1[ii] += inp;
                        histi2[ii] += 3*sqr(outp) - 1;
                        histn[ii]++;
                    }
                    if ((r2 >= rmin2) && (r2 < rmax2))
                    {
                        int ii1 = (int)(invbw*(inp + 1));
                        int ii2 = (int)(invbw*fabs(outp));

                        range_check(ii1, 0, nbin1);
                        range_check(ii2, 0, nbin2);
                        hist1[ii1]++;
                        hist2[ii2]++;
                        sum1 += inp;
                        sum2 += outp;
                        n++;
                    }
                }
            }
        }
        ntot += n;
        nf++;

    }
    while (read_next_x(oenv, status, &t, x, box));

    /* clean up */
    sfree(x);
    close_trj(status);
    gmx_rmpbc_done(gpbc);

    /* Add the bin for the exact maximum to the previous bin */
    hist1[nbin1-1] += hist1[nbin1];
    hist2[nbin2-1] += hist2[nbin2];

    nav     = (real)ntot/(nrefgrp*nf);
    normfac = invbw/ntot;

    fprintf(stderr,  "Average nr of molecules between %g and %g nm: %.1f\n",
            rmin, rmax, nav);
    if (ntot > 0)
    {
        sum1 /= ntot;
        sum2 /= ntot;
        fprintf(stderr, "Average cos(theta1)     between %g and %g nm: %6.3f\n",
                rmin, rmax, sum1);
        fprintf(stderr, "Average 3cos2(theta2)-1 between %g and %g nm: %6.3f\n",
                rmin, rmax, sum2);
    }

    sprintf(str, "Solvent orientation between %g and %g nm", rmin, rmax);
    fp = xvgropen(opt2fn("-o", NFILE, fnm), str, "cos(\\8q\\4\\s1\\N)", "", oenv);
    if (output_env_get_print_xvgr_codes(oenv))
    {
        fprintf(fp, "@ subtitle \"average shell size %.1f molecules\"\n", nav);
    }
    for (i = 0; i < nbin1; i++)
    {
        fprintf(fp, "%g %g\n", (i+0.5)*binwidth-1, 2*normfac*hist1[i]);
    }
    ffclose(fp);

    sprintf(str, "Solvent normal orientation between %g and %g nm", rmin, rmax);
    fp = xvgropen(opt2fn("-no", NFILE, fnm), str, "cos(\\8q\\4\\s2\\N)", "", oenv);
    if (output_env_get_print_xvgr_codes(oenv))
    {
        fprintf(fp, "@ subtitle \"average shell size %.1f molecules\"\n", nav);
    }
    for (i = 0; i < nbin2; i++)
    {
        fprintf(fp, "%g %g\n", (i+0.5)*binwidth, normfac*hist2[i]);
    }
    ffclose(fp);


    sprintf(str, "Solvent orientation");
    fp = xvgropen(opt2fn("-ro", NFILE, fnm), str, "r (nm)", "", oenv);
    if (output_env_get_print_xvgr_codes(oenv))
    {
        fprintf(fp, "@ subtitle \"as a function of distance\"\n");
    }
    xvgr_legend(fp, 2, legr, oenv);
    for (i = 0; i < nrbin; i++)
    {
        fprintf(fp, "%g %g %g\n", (i+0.5)*rbinw,
                histn[i] ? histi1[i]/histn[i] : 0,
                histn[i] ? histi2[i]/histn[i] : 0);
    }
    ffclose(fp);

    sprintf(str, "Cumulative solvent orientation");
    fp = xvgropen(opt2fn("-co", NFILE, fnm), str, "r (nm)", "", oenv);
    if (output_env_get_print_xvgr_codes(oenv))
    {
        fprintf(fp, "@ subtitle \"as a function of distance\"\n");
    }
    xvgr_legend(fp, 2, legc, oenv);
    normfac = 1.0/(nrefgrp*nf);
    c1      = 0;
    c2      = 0;
    fprintf(fp, "%g %g %g\n", 0.0, c1, c2);
    for (i = 0; i < nrbin; i++)
    {
        c1 += histi1[i]*normfac;
        c2 += histi2[i]*normfac;
        fprintf(fp, "%g %g %g\n", (i+1)*rbinw, c1, c2);
    }
    ffclose(fp);

    sprintf(str, "Solvent distribution");
    fp = xvgropen(opt2fn("-rc", NFILE, fnm), str, "r (nm)", "molecules/nm", oenv);
    if (output_env_get_print_xvgr_codes(oenv))
    {
        fprintf(fp, "@ subtitle \"as a function of distance\"\n");
    }
    normfac = 1.0/(rbinw*nf);
    for (i = 0; i < nrbin; i++)
    {
        fprintf(fp, "%g %g\n", (i+0.5)*rbinw, histn[i]*normfac);
    }
    ffclose(fp);

    do_view(oenv, opt2fn("-o", NFILE, fnm), NULL);
    do_view(oenv, opt2fn("-no", NFILE, fnm), NULL);
    do_view(oenv, opt2fn("-ro", NFILE, fnm), "-nxy");
    do_view(oenv, opt2fn("-co", NFILE, fnm), "-nxy");

    return 0;
}
void PDRkEpsilon::correct()
{
    if (!turbulence_)
    {
        // Re-calculate viscosity
        nut_ = Cmu_*sqr(k_)/epsilon_;
        nut_.correctBoundaryConditions();

        // Re-calculate thermal diffusivity
        //***HGWalphat_ = mut_/Prt_;
        //alphat_.correctBoundaryConditions();

        return;
    }

    RASModel::correct();

    volScalarField divU(fvc::div(phi_/fvc::interpolate(rho_)));

    if (mesh_.moving())
    {
        divU += fvc::div(mesh_.phi());
    }

    tmp<volTensorField> tgradU = fvc::grad(U_);
    volScalarField G(GName(), rho_*nut_*(tgradU() && dev(twoSymm(tgradU()))));
    tgradU.clear();

    // Update espsilon and G at the wall
    epsilon_.boundaryField().updateCoeffs();

    // Add the blockage generation term so that it is included consistently
    // in both the k and epsilon equations
    const volScalarField& betav =
        U_.db().lookupObject<volScalarField>("betav");

    const volScalarField& Lobs =
        U_.db().lookupObject<volScalarField>("Lobs");

    const PDRDragModel& drag =
        U_.db().lookupObject<PDRDragModel>("PDRDragModel");

    volScalarField GR(drag.Gk());

    volScalarField LI
        (C4_*(Lobs + dimensionedScalar("minLength", dimLength, VSMALL)));

    // Dissipation equation
    tmp<fvScalarMatrix> epsEqn
    (
        betav*fvm::ddt(rho_, epsilon_)
      + fvm::div(phi_, epsilon_)
      - fvm::laplacian(rho_*DepsilonEff(), epsilon_)
     ==
        C1_*betav*G*epsilon_/k_
      + 1.5*pow(Cmu_, 3.0/4.0)*GR*sqrt(k_)/LI
      - fvm::SuSp(((2.0/3.0)*C1_)*betav*rho_*divU, epsilon_)
      - fvm::Sp(C2_*betav*rho_*epsilon_/k_, epsilon_)
    );

    epsEqn().relax();

    epsEqn().boundaryManipulate(epsilon_.boundaryField());

    solve(epsEqn);
    bound(epsilon_, epsilonMin_);


    // Turbulent kinetic energy equation

    tmp<fvScalarMatrix> kEqn
    (
        betav*fvm::ddt(rho_, k_)
      + fvm::div(phi_, k_)
      - fvm::laplacian(rho_*DkEff(), k_)
     ==
        betav*G + GR
      - fvm::SuSp((2.0/3.0)*betav*rho_*divU, k_)
      - fvm::Sp(betav*rho_*epsilon_/k_, k_)
    );

    kEqn().relax();
    solve(kEqn);
    bound(k_, kMin_);

    // Re-calculate viscosity
    nut_ = Cmu_*sqr(k_)/epsilon_;
    nut_.correctBoundaryConditions();

    // Re-calculate thermal diffusivity
    //***HGWalphat_ = mut_/Prt_;
    //alphat_.correctBoundaryConditions();
}
Exemple #22
0
double BFGS (
    Vector & x,         // i: Startwert
    // o: Loesung, falls IFAIL = 0
    const MinFunction & fun,
    const OptiParameters & par,
    double eps
)


{
    int n = x.Size();
    long it;
    char a1crit, a3acrit;


    Vector d(n), g(n), p(n), temp(n), bs(n), xneu(n), y(n), s(n), x0(n);
    DenseMatrix l(n);
    DenseMatrix hesse(n);

    double /* normg, */ alphahat, hd, fold;
    double a1, a2;
    const double mu1 = 0.1, sigma = 0.1, xi1 = 1, xi2 = 10;
    const double tau = 0.1, tau1 = 0.1, tau2 = 0.6;

    Vector typx(x.Size());      // i: typische Groessenordnung der Komponenten
    double f, f0;
    double typf;               // i: typische Groessenordnung der Loesung
    double fmin = -1e5;           // i: untere Schranke fuer Funktionswert
    //  double eps = 1e-8;            // i: Abbruchschranke fuer relativen Gradienten
    double tauf = 0.1;            // i: Abbruchschranke fuer die relative Aenderung der
    //    Funktionswerte
    int ifail;                    // o:  0 .. Erfolg
    //    -1 .. Unterschreitung von fmin
    //     1 .. kein Erfolg bei Liniensuche
    //     2 .. Überschreitung von itmax

    typx = par.typx;
    typf = par.typf;


    l = 0;
    for (int i = 1; i <= n; i++)
        l.Elem(i, i) = 1;

    f = fun.FuncGrad (x, g);
    f0 = f;
    x0 = x;

    it = 0;
    do
    {
        // Restart

        if (it % (5 * n) == 0)
        {

            for (int i = 1; i <= n; i++)
                d(i-1) = typf/ sqr (typx(i-1));   // 1;
            for (int i = 2; i <= n; i++)
                for (int j = 1; j < i; j++)
                    l.Elem(i, j) = 0;

            /*
            hesse = 0;
            for (i = 1; i <= n; i++)
              hesse.Elem(i, i) = typf / sqr (typx.Get(i));

            fun.ApproximateHesse (x, hesse);

            Cholesky (hesse, l, d);
            */
        }

        it++;
        if (it > par.maxit_bfgs)
        {
            ifail = 2;
            break;
        }


        // Solve with factorized B

        SolveLDLt (l, d, g, p);

//      (*testout) << "l " << l << endl
// 		 << "d " << d << endl
// 		 << "g " << g << endl
// 		 << "p " << p << endl;


        p *= -1;
        y = g;

        fold = f;

        // line search

        alphahat = 1;
        lines (x, xneu, p, f, g, fun, par, alphahat, fmin,
               mu1, sigma, xi1, xi2, tau, tau1, tau2, ifail);

        if(ifail == 1)
            (*testout) << "no success with linesearch" << endl;

        /*
        // if (it > par.maxit_bfgs/2)
        {
          (*testout) << "x = " << x << endl;
          (*testout) << "xneu = " << xneu << endl;
          (*testout) << "f = " << f << endl;
          (*testout) << "g = " << g << endl;
        }
             */

        //      (*testout) << "it = " << it << " f = " << f << endl;
        //      if (ifail != 0) break;

        s.Set2 (1, xneu, -1, x);
        y *= -1;
        y.Add (1,g); // y += g;

        x = xneu;

        // BFGS Update

        MultLDLt (l, d, s, bs);

        a1 = y * s;
        a2 = s * bs;

        if (a1 > 0 && a2 > 0)
        {
            if (LDLtUpdate (l, d, 1 / a1, y) != 0)
            {
                cerr << "BFGS update error1" << endl;
                (*testout) << "BFGS update error1" << endl;
                (*testout) << "l " << endl << l << endl
                           << "d " << d << endl;
                ifail = 1;
                break;
            }

            if (LDLtUpdate (l, d, -1 / a2, bs) != 0)
            {
                cerr << "BFGS update error2" << endl;
                (*testout) << "BFGS update error2" << endl;
                (*testout) << "l " << endl << l << endl
                           << "d " << d << endl;
                ifail = 1;
                break;
            }
        }

        // Calculate stop conditions

        hd = eps * max2 (typf, fabs (f));
        a1crit = 1;
        for (int i = 1; i <= n; i++)
            if ( fabs (g(i-1)) * max2 (typx(i-1), fabs (x(i-1))) > hd)
                a1crit = 0;


        a3acrit = (fold - f <= tauf * max2 (typf, fabs (f)));

        //    testout << "g = " << g << endl;
        //    testout << "a1crit, a3crit = " << int(a1crit) << ", " << int(a3acrit) << endl;

        /*
        // Output for tests

        normg = sqrt (g * g);

        testout << "it =" << setw (5) << it
        << " f =" << setw (12) << setprecision (5) << f
        << " |g| =" << setw (12) << setprecision (5) << normg;

        testout << " x = (" << setw (12) << setprecision (5) << x.Elem(1);
        for (i = 2; i <= n; i++)
        testout << "," << setw (12) << setprecision (5) << x.Elem(i);
        testout << ")" << endl;
        */

        //(*testout) << "it = " << it << " f = " << f << " x = " << x << endl
        //	 << " g = " << g << " p = " << p << endl << endl;

        //      (*testout) << "|g| = " << g.L2Norm() << endl;

        if (g.L2Norm() < fun.GradStopping (x)) break;

    }
    while (!a1crit || !a3acrit);

    /*
    (*testout) << "it = " << it << " g = " << g << " f = " << f
         << " fail = " << ifail << endl;
    */
    if (f0 < f || (ifail == 1))
    {
        (*testout) << "fail, f = " << f << " f0 = " << f0 << endl;
        f = f0;
        x = x0;
    }

    //  (*testout) << "x = " << x << ", x0 = " << x0 << endl;
    return f;
}
Exemple #23
0
int gmx_make_edi(int argc, char *argv[])
{

    static const char *desc[] = {
        "[TT]make_edi[tt] generates an essential dynamics (ED) sampling input file to be used with [TT]mdrun[tt]",
        "based on eigenvectors of a covariance matrix ([TT]g_covar[tt]) or from a",
        "normal modes analysis ([TT]g_nmeig[tt]).",
        "ED sampling can be used to manipulate the position along collective coordinates",
        "(eigenvectors) of (biological) macromolecules during a simulation. Particularly,",
        "it may be used to enhance the sampling efficiency of MD simulations by stimulating",
        "the system to explore new regions along these collective coordinates. A number",
        "of different algorithms are implemented to drive the system along the eigenvectors",
        "([TT]-linfix[tt], [TT]-linacc[tt], [TT]-radfix[tt], [TT]-radacc[tt], [TT]-radcon[tt]),",
        "to keep the position along a certain (set of) coordinate(s) fixed ([TT]-linfix[tt]),",
        "or to only monitor the projections of the positions onto",
        "these coordinates ([TT]-mon[tt]).[PAR]",
        "References:[BR]",
        "A. Amadei, A.B.M. Linssen, B.L. de Groot, D.M.F. van Aalten and ",
        "H.J.C. Berendsen; An efficient method for sampling the essential subspace ",
        "of proteins., J. Biomol. Struct. Dyn. 13:615-626 (1996)[BR]",
        "B.L. de Groot, A. Amadei, D.M.F. van Aalten and H.J.C. Berendsen; ",
        "Towards an exhaustive sampling of the configurational spaces of the ",
        "two forms of the peptide hormone guanylin,",
        "J. Biomol. Struct. Dyn. 13 : 741-751 (1996)[BR]",
        "B.L. de Groot, A.Amadei, R.M. Scheek, N.A.J. van Nuland and H.J.C. Berendsen; ",
        "An extended sampling of the configurational space of HPr from E. coli",
        "Proteins: Struct. Funct. Gen. 26: 314-322 (1996)",
        "[PAR]You will be prompted for one or more index groups that correspond to the eigenvectors,",
        "reference structure, target positions, etc.[PAR]",

        "[TT]-mon[tt]: monitor projections of the coordinates onto selected eigenvectors.[PAR]",
        "[TT]-linfix[tt]: perform fixed-step linear expansion along selected eigenvectors.[PAR]",
        "[TT]-linacc[tt]: perform acceptance linear expansion along selected eigenvectors.",
        "(steps in the desired directions will be accepted, others will be rejected).[PAR]",
        "[TT]-radfix[tt]: perform fixed-step radius expansion along selected eigenvectors.[PAR]",
        "[TT]-radacc[tt]: perform acceptance radius expansion along selected eigenvectors.",
        "(steps in the desired direction will be accepted, others will be rejected).",
        "[BB]Note:[bb] by default the starting MD structure will be taken as origin of the first",
        "expansion cycle for radius expansion. If [TT]-ori[tt] is specified, you will be able",
        "to read in a structure file that defines an external origin.[PAR]",
        "[TT]-radcon[tt]: perform acceptance radius contraction along selected eigenvectors",
        "towards a target structure specified with [TT]-tar[tt].[PAR]",
        "NOTE: each eigenvector can be selected only once. [PAR]",
        "[TT]-outfrq[tt]: frequency (in steps) of writing out projections etc. to [TT].xvg[tt] file[PAR]",
        "[TT]-slope[tt]: minimal slope in acceptance radius expansion. A new expansion",
        "cycle will be started if the spontaneous increase of the radius (in nm/step)",
        "is less than the value specified.[PAR]",
        "[TT]-maxedsteps[tt]: maximum number of steps per cycle in radius expansion",
        "before a new cycle is started.[PAR]",
        "Note on the parallel implementation: since ED sampling is a 'global' thing",
        "(collective coordinates etc.), at least on the 'protein' side, ED sampling",
        "is not very parallel-friendly from an implementation point of view. Because",
        "parallel ED requires some extra communication, expect the performance to be",
        "lower as in a free MD simulation, especially on a large number of nodes and/or",
        "when the ED group contains a lot of atoms. [PAR]",
        "Please also note that if your ED group contains more than a single protein,",
        "then the [TT].tpr[tt] file must contain the correct PBC representation of the ED group.",
        "Take a look on the initial RMSD from the reference structure, which is printed",
        "out at the start of the simulation; if this is much higher than expected, one",
        "of the ED molecules might be shifted by a box vector. [PAR]",
        "All ED-related output of [TT]mdrun[tt] (specify with [TT]-eo[tt]) is written to a [TT].xvg[tt] file",
        "as a function of time in intervals of OUTFRQ steps.[PAR]",
        "[BB]Note[bb] that you can impose multiple ED constraints and flooding potentials in",
        "a single simulation (on different molecules) if several [TT].edi[tt] files were concatenated",
        "first. The constraints are applied in the order they appear in the [TT].edi[tt] file. ",
        "Depending on what was specified in the [TT].edi[tt] input file, the output file contains for each ED dataset[PAR]",
        "[TT]*[tt] the RMSD of the fitted molecule to the reference structure (for atoms involved in fitting prior to calculating the ED constraints)[BR]",
        "[TT]*[tt] projections of the positions onto selected eigenvectors[BR]",
        "[PAR][PAR]",
        "FLOODING:[PAR]",
        "with [TT]-flood[tt], you can specify which eigenvectors are used to compute a flooding potential,",
        "which will lead to extra forces expelling the structure out of the region described",
        "by the covariance matrix. If you switch -restrain the potential is inverted and the structure",
        "is kept in that region.",
        "[PAR]",
        "The origin is normally the average structure stored in the [TT]eigvec.trr[tt] file.",
        "It can be changed with [TT]-ori[tt] to an arbitrary position in configuration space.",
        "With [TT]-tau[tt], [TT]-deltaF0[tt], and [TT]-Eflnull[tt] you control the flooding behaviour.",
        "Efl is the flooding strength, it is updated according to the rule of adaptive flooding.",
        "Tau is the time constant of adaptive flooding, high [GRK]tau[grk] means slow adaption (i.e. growth). ",
        "DeltaF0 is the flooding strength you want to reach after tau ps of simulation.",
        "To use constant Efl set [TT]-tau[tt] to zero.",
        "[PAR]",
        "[TT]-alpha[tt] is a fudge parameter to control the width of the flooding potential. A value of 2 has been found",
        "to give good results for most standard cases in flooding of proteins.",
        "[GRK]alpha[grk] basically accounts for incomplete sampling, if you sampled further the width of the ensemble would",
        "increase, this is mimicked by [GRK]alpha[grk] > 1.",
        "For restraining, [GRK]alpha[grk] < 1 can give you smaller width in the restraining potential.",
        "[PAR]",
        "RESTART and FLOODING:",
        "If you want to restart a crashed flooding simulation please find the values deltaF and Efl in",
        "the output file and manually put them into the [TT].edi[tt] file under DELTA_F0 and EFL_NULL."
    };

    /* Save all the params in this struct and then save it in an edi file.
     * ignoring fields nmass,massnrs,mass,tmass,nfit,fitnrs,edo
     */
    static t_edipar edi_params;

    enum  {
        evStepNr = evRADFIX + 1
    };
    static const char* evSelections[evNr]      = {NULL, NULL, NULL, NULL, NULL, NULL};
    static const char* evOptions[evNr]         = {"-linfix", "-linacc", "-flood", "-radfix", "-radacc", "-radcon", "-mon"};
    static const char* evParams[evStepNr]      = {NULL, NULL};
    static const char* evStepOptions[evStepNr] = {"-linstep", "-accdir", "-not_used", "-radstep"};
    static const char* ConstForceStr;
    static real      * evStepList[evStepNr];
    static real        radfix   = 0.0;
    static real        deltaF0  = 150;
    static real        deltaF   = 0;
    static real        tau      = .1;
    static real        constEfl = 0.0;
    static real        alpha    = 1;
    static int         eqSteps  = 0;
    static int       * listen[evNr];
    static real        T         = 300.0;
    const real         kB        = 2.5 / 300.0; /* k_boltzmann in MD units */
    static gmx_bool    bRestrain = FALSE;
    static gmx_bool    bHesse    = FALSE;
    static gmx_bool    bHarmonic = FALSE;
    t_pargs            pa[]      = {
        { "-mon", FALSE, etSTR, {&evSelections[evMON]},
          "Indices of eigenvectors for projections of x (e.g. 1,2-5,9) or 1-100:10 means 1 11 21 31 ... 91" },
        { "-linfix", FALSE, etSTR, {&evSelections[0]},
          "Indices of eigenvectors for fixed increment linear sampling" },
        { "-linacc", FALSE, etSTR, {&evSelections[1]},
          "Indices of eigenvectors for acceptance linear sampling" },
        { "-radfix", FALSE, etSTR, {&evSelections[3]},
          "Indices of eigenvectors for fixed increment radius expansion" },
        { "-radacc", FALSE, etSTR, {&evSelections[4]},
          "Indices of eigenvectors for acceptance radius expansion" },
        { "-radcon", FALSE, etSTR, {&evSelections[5]},
          "Indices of eigenvectors for acceptance radius contraction" },
        { "-flood",  FALSE, etSTR, {&evSelections[2]},
          "Indices of eigenvectors for flooding"},
        { "-outfrq", FALSE, etINT, {&edi_params.outfrq},
          "Freqency (in steps) of writing output in [TT].xvg[tt] file" },
        { "-slope", FALSE, etREAL, { &edi_params.slope},
          "Minimal slope in acceptance radius expansion"},
        { "-linstep", FALSE, etSTR, {&evParams[0]},
          "Stepsizes (nm/step) for fixed increment linear sampling (put in quotes! \"1.0 2.3 5.1 -3.1\")"},
        { "-accdir", FALSE, etSTR, {&evParams[1]},
          "Directions for acceptance linear sampling - only sign counts! (put in quotes! \"-1 +1 -1.1\")"},
        { "-radstep", FALSE, etREAL, {&radfix},
          "Stepsize (nm/step) for fixed increment radius expansion"},
        { "-maxedsteps", FALSE, etINT, {&edi_params.maxedsteps},
          "Maximum number of steps per cycle" },
        { "-eqsteps", FALSE, etINT, {&eqSteps},
          "Number of steps to run without any perturbations "},
        { "-deltaF0", FALSE, etREAL, {&deltaF0},
          "Target destabilization energy for flooding"},
        { "-deltaF", FALSE, etREAL, {&deltaF},
          "Start deltaF with this parameter - default 0, nonzero values only needed for restart"},
        { "-tau", FALSE, etREAL, {&tau},
          "Coupling constant for adaption of flooding strength according to deltaF0, 0 = infinity i.e. constant flooding strength"},
        { "-Eflnull", FALSE, etREAL, {&constEfl},
          "The starting value of the flooding strength. The flooding strength is updated "
          "according to the adaptive flooding scheme. For a constant flooding strength use [TT]-tau[tt] 0. "},
        { "-T", FALSE, etREAL, {&T},
          "T is temperature, the value is needed if you want to do flooding "},
        { "-alpha", FALSE, etREAL, {&alpha},
          "Scale width of gaussian flooding potential with alpha^2 "},
        { "-restrain", FALSE, etBOOL, {&bRestrain},
          "Use the flooding potential with inverted sign -> effects as quasiharmonic restraining potential"},
        { "-hessian", FALSE, etBOOL, {&bHesse},
          "The eigenvectors and eigenvalues are from a Hessian matrix"},
        { "-harmonic", FALSE, etBOOL, {&bHarmonic},
          "The eigenvalues are interpreted as spring constant"},
        { "-constF", FALSE, etSTR, {&ConstForceStr},
          "Constant force flooding: manually set the forces for the eigenvectors selected with -flood "
          "(put in quotes! \"1.0 2.3 5.1 -3.1\"). No other flooding parameters are needed when specifying the forces directly."}
    };
#define NPA asize(pa)

    rvec        *xref1;
    int          nvec1, *eignr1 = NULL;
    rvec        *xav1, **eigvec1 = NULL;
    t_atoms     *atoms = NULL;
    int          nav; /* Number of atoms in the average structure */
    char        *grpname;
    const char  *indexfile;
    int          i;
    atom_id     *index, *ifit;
    int          nfit;           /* Number of atoms in the reference/fit structure */
    int          ev_class;       /* parameter _class i.e. evMON, evRADFIX etc. */
    int          nvecs;
    real        *eigval1 = NULL; /* in V3.3 this is parameter of read_eigenvectors */

    const char  *EdiFile;
    const char  *TargetFile;
    const char  *OriginFile;
    const char  *EigvecFile;

    output_env_t oenv;

    /*to read topology file*/
    t_topology  top;
    int         ePBC;
    char        title[STRLEN];
    matrix      topbox;
    rvec       *xtop;
    gmx_bool    bTop, bFit1;

    t_filenm    fnm[] = {
        { efTRN, "-f",    "eigenvec",    ffREAD  },
        { efXVG, "-eig",  "eigenval",    ffOPTRD },
        { efTPS, NULL,    NULL,          ffREAD },
        { efNDX, NULL,    NULL,  ffOPTRD },
        { efSTX, "-tar", "target", ffOPTRD},
        { efSTX, "-ori", "origin", ffOPTRD},
        { efEDI, "-o", "sam", ffWRITE }
    };
#define NFILE asize(fnm)
    edi_params.outfrq = 100; edi_params.slope = 0.0; edi_params.maxedsteps = 0;
    parse_common_args(&argc, argv, 0,
                      NFILE, fnm, NPA, pa, asize(desc), desc, 0, NULL, &oenv);

    indexfile       = ftp2fn_null(efNDX, NFILE, fnm);
    EdiFile         = ftp2fn(efEDI, NFILE, fnm);
    TargetFile      = opt2fn_null("-tar", NFILE, fnm);
    OriginFile      = opt2fn_null("-ori", NFILE, fnm);


    for (ev_class = 0; ev_class < evNr; ++ev_class)
    {
        if (opt2parg_bSet(evOptions[ev_class], NPA, pa))
        {
            /*get list of eigenvectors*/
            nvecs = sscan_list(&(listen[ev_class]), opt2parg_str(evOptions[ev_class], NPA, pa), evOptions[ev_class]);
            if (ev_class < evStepNr-2)
            {
                /*if apropriate get list of stepsizes for these eigenvectors*/
                if (opt2parg_bSet(evStepOptions[ev_class], NPA, pa))
                {
                    evStepList[ev_class] =
                        scan_vecparams(opt2parg_str(evStepOptions[ev_class], NPA, pa), evStepOptions[ev_class], nvecs);
                }
                else   /*if list is not given fill with zeros */
                {
                    snew(evStepList[ev_class], nvecs);
                    for (i = 0; i < nvecs; i++)
                    {
                        evStepList[ev_class][i] = 0.0;
                    }
                }
            }
            else if (ev_class == evRADFIX && opt2parg_bSet(evStepOptions[ev_class], NPA, pa))
            {
                snew(evStepList[ev_class], nvecs);
                for (i = 0; i < nvecs; i++)
                {
                    evStepList[ev_class][i] = radfix;
                }
            }
            else if (ev_class == evFLOOD)
            {
                snew(evStepList[ev_class], nvecs);

                /* Are we doing constant force flooding? In that case, we read in
                 * the fproj values from the command line */
                if (opt2parg_bSet("-constF", NPA, pa))
                {
                    evStepList[ev_class] = scan_vecparams(opt2parg_str("-constF", NPA, pa), "-constF", nvecs);
                }
            }
            else
            {
            };   /*to avoid ambiguity   */
        }
        else     /* if there are no eigenvectors for this option set list to zero */
        {
            listen[ev_class] = NULL;
            snew(listen[ev_class], 1);
            listen[ev_class][0] = 0;
        }
    }

    /* print the interpreted list of eigenvectors - to give some feedback*/
    for (ev_class = 0; ev_class < evNr; ++ev_class)
    {
        printf("Eigenvector list %7s consists of the indices: ", evOptions[ev_class]);
        i = 0;
        while (listen[ev_class][i])
        {
            printf("%d ", listen[ev_class][i++]);
        }
        printf("\n");
    }

    EigvecFile = NULL;
    EigvecFile = opt2fn("-f", NFILE, fnm);

    /*read eigenvectors from eigvec.trr*/
    read_eigenvectors(EigvecFile, &nav, &bFit1,
                      &xref1, &edi_params.fitmas, &xav1, &edi_params.pcamas, &nvec1, &eignr1, &eigvec1, &eigval1);

    bTop = read_tps_conf(ftp2fn(efTPS, NFILE, fnm),
                         title, &top, &ePBC, &xtop, NULL, topbox, 0);
    atoms = &top.atoms;


    printf("\nSelect an index group of %d elements that corresponds to the eigenvectors\n", nav);
    get_index(atoms, indexfile, 1, &i, &index, &grpname); /*if indexfile != NULL parameter 'atoms' is ignored */
    if (i != nav)
    {
        gmx_fatal(FARGS, "you selected a group with %d elements instead of %d",
                  i, nav);
    }
    printf("\n");


    if (xref1 == NULL)
    {
        if (bFit1)
        {
            /* if g_covar used different coordinate groups to fit and to do the PCA */
            printf("\nNote: the structure in %s should be the same\n"
                   "      as the one used for the fit in g_covar\n", ftp2fn(efTPS, NFILE, fnm));
            printf("\nSelect the index group that was used for the least squares fit in g_covar\n");
        }
        else
        {
            printf("\nNote: Apparently no fitting was done in g_covar.\n"
                   "      However, you need to select a reference group for fitting in mdrun\n");
        }
        get_index(atoms, indexfile, 1, &nfit, &ifit, &grpname);
        snew(xref1, nfit);
        for (i = 0; i < nfit; i++)
        {
            copy_rvec(xtop[ifit[i]], xref1[i]);
        }
    }
    else
    {
        nfit = nav;
        ifit = index;
    }

    if (opt2parg_bSet("-constF", NPA, pa))
    {
        /* Constant force flooding is special: Most of the normal flooding
         * options are not needed. */
        edi_params.flood.bConstForce = TRUE;
    }
    else
    {
        /* For normal flooding read eigenvalues and store them in evSteplist[evFLOOD] */

        if (listen[evFLOOD][0] != 0)
        {
            read_eigenvalues(listen[evFLOOD], opt2fn("-eig", NFILE, fnm), evStepList[evFLOOD], bHesse, kB*T);
        }

        edi_params.flood.tau       = tau;
        edi_params.flood.deltaF0   = deltaF0;
        edi_params.flood.deltaF    = deltaF;
        edi_params.presteps        = eqSteps;
        edi_params.flood.kT        = kB*T;
        edi_params.flood.bHarmonic = bHarmonic;
        if (bRestrain)
        {
            /* Trick: invert sign of Efl and alpha2 then this will give the same sign in the exponential and inverted sign outside */
            edi_params.flood.constEfl = -constEfl;
            edi_params.flood.alpha2   = -sqr(alpha);
        }
        else
        {
            edi_params.flood.constEfl = constEfl;
            edi_params.flood.alpha2   = sqr(alpha);
        }
    }

    edi_params.ned = nav;

    /*number of system atoms  */
    edi_params.nini = atoms->nr;


    /*store reference and average structure in edi_params*/
    make_t_edx(&edi_params.sref, nfit, xref1, ifit );
    make_t_edx(&edi_params.sav, nav, xav1, index);


    /* Store target positions in edi_params */
    if (opt2bSet("-tar", NFILE, fnm))
    {
        if (0 != listen[evFLOOD][0])
        {
            fprintf(stderr, "\nNote: Providing a TARGET structure has no effect when using flooding.\n"
                    "      You may want to use -ori to define the flooding potential center.\n\n");
        }
        get_structure(atoms, indexfile, TargetFile, &edi_params.star, nfit, ifit, nav, index);
    }
    else
    {
        make_t_edx(&edi_params.star, 0, NULL, index);
    }

    /* Store origin positions */
    if (opt2bSet("-ori", NFILE, fnm))
    {
        get_structure(atoms, indexfile, OriginFile, &edi_params.sori, nfit, ifit, nav, index);
    }
    else
    {
        make_t_edx(&edi_params.sori, 0, NULL, index);
    }

    /* Write edi-file */
    write_the_whole_thing(ffopen(EdiFile, "w"), &edi_params, eigvec1, nvec1, listen, evStepList);
    thanx(stderr);

    return 0;
}
Exemple #24
0
bool Foam::chemPointISAT<CompType, ThermoType>::inEOA(const scalarField& phiq)
{
    scalarField dphi(phiq-phi());
    bool isMechRedActive = chemistry_.mechRed()->active();
    label dim = (isMechRedActive) ? nActiveSpecies_ : completeSpaceSize()-2;
    scalar epsTemp=0;
    List<scalar> propEps(completeSpaceSize(), scalar(0));

    for (label i=0; i<completeSpaceSize()-2; i++)
    {
        scalar temp = 0;

        // When mechanism reduction is inactive OR on active species multiply L
        // by dphi to get the distance in the active species direction else (for
        // inactive species), just multiply the diagonal element and dphi
        if
        (
            !(isMechRedActive)
          ||(isMechRedActive && completeToSimplifiedIndex_[i] != -1)
        )
        {
            label si=(isMechRedActive) ? completeToSimplifiedIndex_[i] : i;

            for (label j=si; j<dim; j++)// LT is upper triangular
            {
                label sj=(isMechRedActive) ? simplifiedToCompleteIndex_[j] : j;
                temp += LT_(si, j)*dphi[sj];
            }

            temp += LT_(si, nActiveSpecies_)*dphi[completeSpaceSize()-2];
            temp += LT_(si, nActiveSpecies_+1)*dphi[completeSpaceSize()-1];
        }
        else
        {
            temp = dphi[i]/(tolerance_*scaleFactor_[i]);
        }

        epsTemp += sqr(temp);

        if (printProportion_)
        {
            propEps[i] = temp;
        }
    }

    // Temperature
    epsTemp +=
        sqr
        (
            LT_(dim, dim)*dphi[completeSpaceSize()-2]
           +LT_(dim, dim+1)*dphi[completeSpaceSize()-1]
        );

    // Pressure
    epsTemp += sqr(LT_(dim+1, dim+1)*dphi[completeSpaceSize()-1]);

    if (printProportion_)
    {
        propEps[completeSpaceSize()-2] =
        sqr
        (
            LT_(dim, dim)*dphi[completeSpaceSize()-2]
          + LT_(dim, dim+1)*dphi[completeSpaceSize()-1]
        );

        propEps[completeSpaceSize()-1] =
            sqr(LT_(dim+1, dim+1)*dphi[completeSpaceSize()-1]);
    }
    if (sqrt(epsTemp) > 1 + tolerance_)
    {
        if (printProportion_)
        {
            scalar max = -1;
            label maxIndex = -1;
            for (label i=0; i<completeSpaceSize(); i++)
            {
                if(max < propEps[i])
                {
                    max = propEps[i];
                    maxIndex = i;
                }
            }
            word propName;
            if (maxIndex >= completeSpaceSize()-2)
            {
                if(maxIndex == completeSpaceSize()-2)
                {
                    propName = "T";
                }
                else if(maxIndex == completeSpaceSize()-1)
                {
                    propName = "p";
                }
            }
            else
            {
                propName = chemistry_.Y()[maxIndex].name();
            }
            Info<< "Direction maximum impact to error in ellipsoid: "
                << propName << endl;
            Info<< "Proportion to the total error on the retrieve: "
                << max/(epsTemp+SMALL) << endl;
        }
        return false;
    }
    else
    {
        return true;
    }
}
int main(int argc, char *argv[])
{

#   include "addTimeOptions.H"
#   include "setRootCase.H"

#   include "createTime.H"

    // Get times list
    instantList Times = runTime.times();

    // set startTime and endTime depending on -time and -latestTime options
#   include "checkTimeOptions.H"

    runTime.setTime(Times[startTime], startTime);

#   include "createMesh.H"

    runTime.setTime(Times[endTime-1], endTime-1);

    volScalarField pMean
    (
        IOobject
        (
            "pMean",
            runTime.timeName(),
            mesh,
            IOobject::MUST_READ
        ),
        mesh
    );

    for (label i=startTime; i<endTime; i++)
    {
        runTime.setTime(Times[i], i);

        Info<< "Time = " << runTime.timeName() << endl;

        IOobject pheader
        (
            "p",
            runTime.timeName(),
            mesh,
            IOobject::MUST_READ
        );

        // Check p exists
        if (pheader.headerOk())
        {
            mesh.readUpdate();

            Info<< "    Reading p" << endl;
            volScalarField p(pheader, mesh);

            Info<< "    Calculating pPrime2" << endl;
            volScalarField pPrime2
            (
                IOobject
                (
                    "pPrime2",
                    runTime.timeName(),
                    mesh,
                    IOobject::NO_READ
                ),
                sqr(p - pMean)
            );
            pPrime2.write();
        }
        else
        {
            Info<< "    No p" << endl;
        }

        Info<< endl;
    }

    return(0);
}
Exemple #26
0
void Foam::chemPointISAT<CompType, ThermoType>::qrDecompose
(
    const label nCols,
    scalarSquareMatrix& R
)
{
    scalarField c(nCols);
    scalarField d(nCols);
    scalar scale, sigma, sum;

    for (label k=0; k<nCols-1; k++)
    {
        scale = 0;
        for (label i=k; i<nCols; i++)
        {
            scale=max(scale, mag(R(i, k)));
        }
        if (scale == 0)
        {
            c[k] = d[k] = 0;
        }
        else
        {
            for (label i=k; i<nCols; i++)
            {
                R(i, k) /= scale;
            }
            sum = 0;
            for (label i=k; i<nCols; i++)
            {
                sum += sqr(R(i, k));
            }
            sigma = sign(R(k, k))*sqrt(sum);
            R(k, k) += sigma;
            c[k] = sigma*R(k, k);
            d[k] = -scale*sigma;
            for (label j=k+1; j<nCols; j++)
            {
                sum=0;
                for ( label i=k; i<nCols; i++)
                {
                    sum += R(i, k)*R(i, j);
                }
                scalar tau = sum/c[k];
                for ( label i=k; i<nCols; i++)
                {
                    R(i, j) -= tau*R(i, k);
                }
            }
        }
    }

    d[nCols-1] = R(nCols-1, nCols-1);

    // form R
    for (label i=0; i<nCols; i++)
    {
        R(i, i) = d[i];
        for ( label j=0; j<i; j++)
        {
            R(i, j)=0;
        }
    }
}
extern void compute_structure_factor (structure_factor_t * sft, matrix box,
                                      reduced_atom_t * red, int isize, real start_q,
                                      real end_q, int group, real **sf_table)
{
    structure_factor *sf   = (structure_factor *)sft;
    reduced_atom     *redt = (reduced_atom *)red;

    t_complex      ***tmpSF;
    rvec              k_factor;
    real              kdotx, asf, kx, ky, kz, krr;
    int               kr, maxkx, maxky, maxkz, i, j, k, p, *counter;


    k_factor[XX] = 2 * M_PI / box[XX][XX];
    k_factor[YY] = 2 * M_PI / box[YY][YY];
    k_factor[ZZ] = 2 * M_PI / box[ZZ][ZZ];

    maxkx = (int) (end_q / k_factor[XX] + 0.5);
    maxky = (int) (end_q / k_factor[YY] + 0.5);
    maxkz = (int) (end_q / k_factor[ZZ] + 0.5);

    snew (counter, sf->n_angles);

    tmpSF = rc_tensor_allocation(maxkx, maxky, maxkz);
/*
 * The big loop...
 * compute real and imaginary part of the structure factor for every
 * (kx,ky,kz))
 */
    fprintf(stderr, "\n");
    for (i = 0; i < maxkx; i++)
    {
        fprintf (stderr, "\rdone %3.1f%%     ", (double)(100.0*(i+1))/maxkx);
        kx = i * k_factor[XX];
        for (j = 0; j < maxky; j++)
        {
            ky = j * k_factor[YY];
            for (k = 0; k < maxkz; k++)
            {
                if (i != 0 || j != 0 || k != 0)
                {
                    kz  = k * k_factor[ZZ];
                    krr = sqrt (sqr (kx) + sqr (ky) + sqr (kz));
                    if (krr >= start_q && krr <= end_q)
                    {
                        kr = (int) (krr/sf->ref_k + 0.5);
                        if (kr < sf->n_angles)
                        {
                            counter[kr]++; /* will be used for the copmutation
                                              of the average*/
                            for (p = 0; p < isize; p++)
                            {
                                asf = sf_table[redt[p].t][kr];

                                kdotx = kx * redt[p].x[XX] +
                                    ky * redt[p].x[YY] + kz * redt[p].x[ZZ];

                                tmpSF[i][j][k].re += cos (kdotx) * asf;
                                tmpSF[i][j][k].im += sin (kdotx) * asf;
                            }
                        }
                    }
                }
            }
        }
    }               /* end loop on i */
/*
 *  compute the square modulus of the structure factor, averaging on the surface
 *  kx*kx + ky*ky + kz*kz = krr*krr
 *  note that this is correct only for a (on the macroscopic scale)
 *  isotropic system.
 */
    for (i = 0; i < maxkx; i++)
    {
        kx = i * k_factor[XX]; for (j = 0; j < maxky; j++)
        {
            ky = j * k_factor[YY]; for (k = 0; k < maxkz; k++)
            {
                kz = k * k_factor[ZZ]; krr = sqrt (sqr (kx) + sqr (ky)
                                                   + sqr (kz)); if (krr >= start_q && krr <= end_q)
                {
                    kr = (int) (krr / sf->ref_k + 0.5);
                    if (kr < sf->n_angles && counter[kr] != 0)
                    {
                        sf->F[group][kr] +=
                            (sqr (tmpSF[i][j][k].re) +
                             sqr (tmpSF[i][j][k].im))/ counter[kr];
                    }
                }
            }
        }
    }
    sfree (counter); free(tmpSF[0][0]); free(tmpSF[0]); free(tmpSF);
}
Exemple #28
0
bool Foam::chemPointISAT<CompType, ThermoType>::checkSolution
(
    const scalarField& phiq,
    const scalarField& Rphiq
)
{
    scalar eps2 = 0;
    scalarField dR(Rphiq - Rphi());
    scalarField dphi(phiq - phi());
    const scalarField& scaleFactorV(scaleFactor());
    const scalarSquareMatrix& Avar(A());
    bool isMechRedActive = chemistry_.mechRed()->active();
    scalar dRl = 0;
    label dim = completeSpaceSize()-2;
    if (isMechRedActive)
    {
        dim = nActiveSpecies_;
    }

    // Since we build only the solution for the species, T and p are not
    // included
    for (label i=0; i<completeSpaceSize()-2; i++)
    {
        dRl = 0;
        if (isMechRedActive)
        {
            label si = completeToSimplifiedIndex_[i];

            // If this species is active
            if (si != -1)
            {
                for (label j=0; j<dim; j++)
                {
                    label sj=simplifiedToCompleteIndex_[j];
                    dRl += Avar(si, j)*dphi[sj];
                }
                dRl += Avar(si, nActiveSpecies_)*dphi[completeSpaceSize()-2];
                dRl += Avar(si, nActiveSpecies_+1)*dphi[completeSpaceSize()-1];
            }
            else
            {
                dRl = dphi[i];
            }
        }
        else
        {
            for (label j=0; j<completeSpaceSize(); j++)
            {
                dRl += Avar(i, j)*dphi[j];
            }
        }
        eps2 += sqr((dR[i]-dRl)/scaleFactorV[i]);
    }

    eps2 = sqrt(eps2);
    if (eps2 > tolerance())
    {
        return false;
    }
    else
    {
        // if the solution is in the ellipsoid of accuracy
        return true;
    }
}
Exemple #29
0
/*! \brief lmfit_exp supports fitting of different functions
 *
 * This routine calls the Levenberg-Marquardt non-linear fitting
 * routine for fitting a data set with errors to a target function.
 * Fitting routines included in gromacs in src/external/lmfit.
 */
static gmx_bool lmfit_exp(int          nfit,
                          const double x[],
                          const double y[],
                          const double dy[],
                          double       parm[],
                          gmx_bool     bVerbose,
                          int          eFitFn,
                          int          nfix)
{
    double             chisq, ochisq;
    gmx_bool           bCont;
    int                j;
    int                maxiter = 100;
    lm_control_struct  control;
    lm_status_struct  *status;
    int                nparam = effnNparams(eFitFn);
    int                p2;
    gmx_bool           bSkipLast;

    if ((eFitFn < 0) || (eFitFn >= effnNR))
    {
        fprintf(stderr, "fitfn = %d, should be in the range 0..%d\n",
                eFitFn, effnNR-1);
        return FALSE;
    }
    /* Using default control structure for double precision fitting that
     * comes with the lmfit package (i.e. from the include file).
     */
    control            = lm_control_double;
    control.verbosity  = (bVerbose ? 1 : 0);
    control.n_maxpri   = 0;
    control.m_maxpri   = 0;

    snew(status, 1);
    /* Initial params */
    chisq  = 1e12;
    j      = 0;
    if (bVerbose)
    {
        printf("%4s  %10s  Parameters\n", "Step", "chi^2");
    }
    /* Check whether we have to skip some params */
    if (nfix > 0)
    {
        do
        {
            p2        = 1 << (nparam-1);
            bSkipLast = ((p2 & nfix) == p2);
            if (bSkipLast)
            {
                nparam--;
                nfix -= p2;
            }
        }
        while ((nparam > 0) && (bSkipLast));
        if (bVerbose)
        {
            printf("Using %d out of %d parameters\n", nparam, effnNparams(eFitFn));
        }
    }
    do
    {
        ochisq = chisq;
        lmcurve(nparam, parm, nfit, x, y, dy,
                lmcurves[eFitFn], &control, status);
        chisq = sqr(status->fnorm);
        if (bVerbose)
        {
            printf("status: fnorm = %g, nfev = %d, userbreak = %d\noutcome = %s\n",
                   status->fnorm, status->nfev, status->userbreak,
                   lm_infmsg[status->outcome]);
        }
        if (bVerbose)
        {
            int mmm;
            printf("%4d  %8g", j, chisq);
            for (mmm = 0; (mmm < effnNparams(eFitFn)); mmm++)
            {
                printf("  %8g", parm[mmm]);
            }
            printf("\n");
        }
        j++;
        bCont = (fabs(ochisq - chisq) > fabs(control.ftol*chisq));
    }
    while (bCont && (j < maxiter));

    sfree(status);

    return TRUE;
}
int main(int, char**)
{
    {
        typedef std::weibull_distribution<> D;
        typedef D::param_type P;
        typedef std::mt19937 G;
        G g;
        D d(0.5, 2);
        P p(1, .5);
        const int N = 1000000;
        std::vector<D::result_type> u;
        for (int i = 0; i < N; ++i)
        {
            D::result_type v = d(g, p);
            assert(d.min() <= v);
            u.push_back(v);
        }
        double mean = std::accumulate(u.begin(), u.end(), 0.0) / u.size();
        double var = 0;
        double skew = 0;
        double kurtosis = 0;
        for (std::size_t i = 0; i < u.size(); ++i)
        {
            double dbl = (u[i] - mean);
            double d2 = sqr(dbl);
            var += d2;
            skew += dbl * d2;
            kurtosis += d2 * d2;
        }
        var /= u.size();
        double dev = std::sqrt(var);
        skew /= u.size() * dev * var;
        kurtosis /= u.size() * var * var;
        kurtosis -= 3;
        double x_mean = p.b() * std::tgamma(1 + 1/p.a());
        double x_var = sqr(p.b()) * std::tgamma(1 + 2/p.a()) - sqr(x_mean);
        double x_skew = (sqr(p.b())*p.b() * std::tgamma(1 + 3/p.a()) -
                        3*x_mean*x_var - sqr(x_mean)*x_mean) /
                        (std::sqrt(x_var)*x_var);
        double x_kurtosis = (sqr(sqr(p.b())) * std::tgamma(1 + 4/p.a()) -
                       4*x_skew*x_var*sqrt(x_var)*x_mean -
                       6*sqr(x_mean)*x_var - sqr(sqr(x_mean))) / sqr(x_var) - 3;
        assert(std::abs((mean - x_mean) / x_mean) < 0.01);
        assert(std::abs((var - x_var) / x_var) < 0.01);
        assert(std::abs((skew - x_skew) / x_skew) < 0.01);
        assert(std::abs((kurtosis - x_kurtosis) / x_kurtosis) < 0.01);
    }
    {
        typedef std::weibull_distribution<> D;
        typedef D::param_type P;
        typedef std::mt19937 G;
        G g;
        D d(1, .5);
        P p(2, 3);
        const int N = 1000000;
        std::vector<D::result_type> u;
        for (int i = 0; i < N; ++i)
        {
            D::result_type v = d(g, p);
            assert(d.min() <= v);
            u.push_back(v);
        }
        double mean = std::accumulate(u.begin(), u.end(), 0.0) / u.size();
        double var = 0;
        double skew = 0;
        double kurtosis = 0;
        for (std::size_t i = 0; i < u.size(); ++i)
        {
            double dbl = (u[i] - mean);
            double d2 = sqr(dbl);
            var += d2;
            skew += dbl * d2;
            kurtosis += d2 * d2;
        }
        var /= u.size();
        double dev = std::sqrt(var);
        skew /= u.size() * dev * var;
        kurtosis /= u.size() * var * var;
        kurtosis -= 3;
        double x_mean = p.b() * std::tgamma(1 + 1/p.a());
        double x_var = sqr(p.b()) * std::tgamma(1 + 2/p.a()) - sqr(x_mean);
        double x_skew = (sqr(p.b())*p.b() * std::tgamma(1 + 3/p.a()) -
                        3*x_mean*x_var - sqr(x_mean)*x_mean) /
                        (std::sqrt(x_var)*x_var);
        double x_kurtosis = (sqr(sqr(p.b())) * std::tgamma(1 + 4/p.a()) -
                       4*x_skew*x_var*sqrt(x_var)*x_mean -
                       6*sqr(x_mean)*x_var - sqr(sqr(x_mean))) / sqr(x_var) - 3;
        assert(std::abs((mean - x_mean) / x_mean) < 0.01);
        assert(std::abs((var - x_var) / x_var) < 0.01);
        assert(std::abs((skew - x_skew) / x_skew) < 0.01);
        assert(std::abs((kurtosis - x_kurtosis) / x_kurtosis) < 0.03);
    }
    {
        typedef std::weibull_distribution<> D;
        typedef D::param_type P;
        typedef std::mt19937 G;
        G g;
        D d(2, 3);
        P p(.5, 2);
        const int N = 1000000;
        std::vector<D::result_type> u;
        for (int i = 0; i < N; ++i)
        {
            D::result_type v = d(g, p);
            assert(d.min() <= v);
            u.push_back(v);
        }
        double mean = std::accumulate(u.begin(), u.end(), 0.0) / u.size();
        double var = 0;
        double skew = 0;
        double kurtosis = 0;
        for (std::size_t i = 0; i < u.size(); ++i)
        {
            double dbl = (u[i] - mean);
            double d2 = sqr(dbl);
            var += d2;
            skew += dbl * d2;
            kurtosis += d2 * d2;
        }
        var /= u.size();
        double dev = std::sqrt(var);
        skew /= u.size() * dev * var;
        kurtosis /= u.size() * var * var;
        kurtosis -= 3;
        double x_mean = p.b() * std::tgamma(1 + 1/p.a());
        double x_var = sqr(p.b()) * std::tgamma(1 + 2/p.a()) - sqr(x_mean);
        double x_skew = (sqr(p.b())*p.b() * std::tgamma(1 + 3/p.a()) -
                        3*x_mean*x_var - sqr(x_mean)*x_mean) /
                        (std::sqrt(x_var)*x_var);
        double x_kurtosis = (sqr(sqr(p.b())) * std::tgamma(1 + 4/p.a()) -
                       4*x_skew*x_var*sqrt(x_var)*x_mean -
                       6*sqr(x_mean)*x_var - sqr(sqr(x_mean))) / sqr(x_var) - 3;
        assert(std::abs((mean - x_mean) / x_mean) < 0.01);
        assert(std::abs((var - x_var) / x_var) < 0.01);
        assert(std::abs((skew - x_skew) / x_skew) < 0.01);
        assert(std::abs((kurtosis - x_kurtosis) / x_kurtosis) < 0.03);
    }

  return 0;
}