Esempio n. 1
0
int rk4(double x, double *y, double *dydx, double h, double *yout, double den){
	double hh, h6, xh;
	double yt[2], dyt[2], dym[2];
	int i;
	
	hh=h*0.5;
	h6=h/6.0;
	xh=x+hh;
	for (i=0;i<2;i++) {
		yt[i] = y[i] + hh*dydx[i];
	}
	
	derivs(xh,yt,dyt,den); //find derivative
	for (i=0;i<2;i++) {
		yt[i] = y[i] + hh*dyt[i];
	}
	
	derivs(xh,yt,dym,den); //find derivative
	for (i=0;i<2;i++) {
		yt[i] = y[i] + h*dym[i];
		dym[i] += dyt[i];
	}
	
	derivs(x+h,yt,dyt,den); //find derivative
	for (i=0;i<2;i++) {
		yout[i] = y[i] + h6*(dydx[i]+dyt[i]+2.0*dym[i]);
	}
	
	return 0;
}
Esempio n. 2
0
void rk4(double *y, double *dydt, int n, double h, double *yout)
{
    /* Fourth-order Runge-Kutta integrator.  *y is an array with the n variables;
    *dydt is the array of their derivatives; *yout is the array of values at
    t+dt. */

    int i;
    double hh,h6,*dym,*dyt,*yt;

    dym=malloc(n*sizeof(double));
    dyt=malloc(n*sizeof(double));
    yt=malloc(n*sizeof(double));

    hh=0.5*h;
    h6=h/6.0;

    for (i=0; i<n; i++)
        yt[i]=y[i]+hh*dydt[i];
    derivs(yt,dyt);
    for (i=0; i<n; i++)
        yt[i]=y[i]+hh*dyt[i];
    derivs(yt,dym);
    for (i=0; i<n; i++)
    {
        yt[i]=y[i]+h*dym[i];
        dym[i]+=dyt[i];
    }
    derivs(yt,dyt);
    for (i=0; i<n; i++)
        yout[i]=y[i]+h6*(dydt[i]+dyt[i]+2.0*dym[i]);
    free(dym);
    free(dyt);
    free(yt);
}
Esempio n. 3
0
void rk2 (double t, double x[], void derivs(double, double[], double[]),
double h, int M) 
{
	double k1[M], k2[M], xp[M];
	int i;
 	derivs(t, x, k1); 
	for (i=0; i < M; i++) xp[i] = x[i] + h * k1[i]; 
 	derivs(t+h, xp, k2); 
	for (i=0; i < M; i++) x[i] += 0.5 * h * (k1[i] + k2[i]); 
}
Esempio n. 4
0
void NR::simpr(Vec_I_DP &y, Vec_I_DP &dydx, Vec_I_DP &dfdx, Mat_I_DP &dfdy,
	const DP xs, const DP htot, const int nstep, Vec_O_DP &yout,
	void derivs(const DP, Vec_IO_DP &, Vec_O_DP &))
{
        const int NMAX=61000;
        Vec_INT ija(NMAX);
        Vec_DP sa(NMAX);
	double sa_a[NMAX];
	int ija_a[NMAX];
	int i,nn,RAZMER;
	DP d,h,x;
        const int ITOL=2,ITMAX=75;
        const DP TOL=1.0e-9;
        int ii,iter;
        DP err;

	int n=y.size();
	Vec_INT indx(n);
	Vec_DP del(n),ytemp(n),xinit(n);
	h=htot/nstep;
        NR::sprsin(dfdy,1.e-9,sa,ija);
		RAZMER = (ija[n]-1);
		for(i=0;i<RAZMER;i++) {ija_a[i]=ija[i]; sa_a[i] = -h*sa[i];}
		for (i=0;i<n;i++) ++sa_a[i];// a[i][j] = -h*dfdy[i][j];

//	ludcmp(a,indx,d);
	for (i=0;i<n;i++){ xinit[i] = 0.;
		yout[i]=h*(dydx[i]+h*dfdx[i]);}
	ija_p=new Vec_INT(ija_a,NMAX);
        sa_p=new Vec_DP(sa_a,NMAX);
	NR::linbcg(yout,xinit,ITOL,TOL,ITMAX,iter,err);
//	lubksb(a,indx,yout);
	for (i=0;i<n;i++)
		ytemp[i]=y[i]+(del[i]=yout[i]=xinit[i]);
	x=xs+h;
	derivs(x,ytemp,yout);
	for (nn=2;nn<=nstep;nn++) {
		for (i=0;i<n;i++)
			yout[i]=h*yout[i]-del[i];
	NR::linbcg(yout,xinit,ITOL,TOL,ITMAX,iter,err);
//		lubksb(a,indx,yout);
		for (i=0;i<n;i++) ytemp[i] += (del[i] += 2.0*(yout[i]=xinit[i]));
		x += h;
		derivs(x,ytemp,yout);
	}
	for (i=0;i<n;i++)
		yout[i]=h*yout[i]-del[i];
	NR::linbcg(yout,xinit,ITOL,TOL,ITMAX,iter,err);
//	lubksb(a,indx,yout);
	for (i=0;i<n;i++)
		yout[i] = xinit[i] + ytemp[i];
        delete sa_p;
        delete ija_p;
}
Esempio n. 5
0
Eigen::VectorXd LayerAdapter::gradient()
{
  Eigen::MatrixXd* output;
  layer.forwardPropagate(&input, output, false);
  Eigen::MatrixXd diff = *output - desired;
  Eigen::MatrixXd* e = &diff;
  layer.backpropagate(e, e);
  Eigen::VectorXd derivs(dimension());
  std::vector<double*>::const_iterator it = derivatives.begin();
  for(int i = 0; i < dimension(); i++, it++)
    derivs(i) = **it;
  return derivs;
}
Esempio n. 6
0
float rk2(float xin, float yin, float h){
  int i;
  float k1, k2, yt, yout, dydx;
 
  dydx = derivs(xin, yin); /* evaluate first dy/dx */
  k1 = h*dydx;
  yt = yin + 0.5*k1; 

  dydx = derivs(xin + 0.5*h, yt);
  k2 = h*dydx;
  yout = yin + k2;

  return yout;
}
// This is a pointwise calculation: compute the rhs for point result given input values in array phi
void calcrhs(struct nodedata * rhs,
               std::vector< nodedata* > const& vecval,
               std::vector< had_double_type* > const& vecx,
                int flag, had_double_type const& dx, int size,
                int compute_index, Par const& par)
{
  static had_double_type const c_0_25 = 0.25;
  static had_double_type const c_3 = 3.0;
  static had_double_type const c_m3 = -3.0;
  static had_double_type const c_2 = 2.0;
  //static had_double_type const c_0 = 0.0;

  if ( compute_index-2 >= 0 && compute_index+2 < size ) {
//    had_double_type const x = *vecx[compute_index];
    had_double_type const phi = vecval[compute_index]->phi[flag][0];
    had_double_type const Pi  = vecval[compute_index]->phi[flag][1];
    had_double_type const chi = vecval[compute_index]->phi[flag][2];
    had_double_type const a   = vecval[compute_index]->phi[flag][3];
    had_double_type const f   = vecval[compute_index]->phi[flag][4];
    had_double_type const g   = vecval[compute_index]->phi[flag][5];
    had_double_type const b   = vecval[compute_index]->phi[flag][6];
    had_double_type const q   = vecval[compute_index]->phi[flag][7];
    had_double_type const r   = vecval[compute_index]->phi[flag][8];
    had_double_type const VV  = c_0_25*par.lambda*pow(phi*phi-par.v*par.v,2);
    had_double_type const dphiVV  = par.lambda*phi*(phi*phi-par.v*par.v);

    had_double_type const dzPi  = derivs(vecval,compute_index,flag,1,dx);
    had_double_type const dzchi = derivs(vecval,compute_index,flag,2,dx);
    had_double_type const dzf   = derivs(vecval,compute_index,flag,4,dx);
    had_double_type const dzg   = derivs(vecval,compute_index,flag,5,dx);
    had_double_type const dzq   = derivs(vecval,compute_index,flag,7,dx);

    rhs->phi[0][0] = Pi;
    rhs->phi[0][1] = -Pi*(f/a +q/b) 
                     +( (c_3*a*g/(b*b) -a*a*r/(b*b*b) )*chi
                     +  (a/b)*(a/b)*dzchi - a*a*dphiVV );
    rhs->phi[0][2] = dzPi;
    rhs->phi[0][3] = f;
    rhs->phi[0][4] = a*( -(f*q)/(a*b)
                    + (c_2*g*g/(b*b) - a*g*r/(b*b*b)
                    +  a*dzg/(b*b) + a*a*VV));
    rhs->phi[0][5] = dzf;
    rhs->phi[0][6] = q;
    rhs->phi[0][7] = b*( -(f*q)/(a*b)
                    +(c_m3*a*g*r/(b*b*b)
                     +c_3*a*dzg/(b*b)
                     +(a*chi/b)*(a*chi/b) + a*a*VV));
    rhs->phi[0][8] = dzq;
  }
}
Esempio n. 8
0
void rk4 (double t, double x[], void derivs(double, double[], double[]),
double h, int M)
{
	double k1[M], k2[M], k3[M], k4[M], xp[M], h6;
	int i;
	h6 = h / 6;
	derivs(t, x, k1); //compute k1[i] (= derivs at (t, x))
	for (i=0; i < M; i++) xp[i] = x[i] + 0.5 * h * k1[i];
	derivs(t+0.5*h, xp, k2); //compute k2[i] (= derivs at (t+0.5*h, x+0.5*h*k1))
	for (i=0; i < M; i++) xp[i] = x[i] + 0.5 * h * k2[i];
	derivs(t+0.5*h, xp, k3); //compute k3[i] (= derivs at (t+0.5*h, x+0.5*h*k2))
	for (i=0; i < M; i++) xp[i] = x[i] + h * k3[i];
	derivs(t+h, xp, k4); //compute k4[i] (= derivs at (t+h, x+h*k3))
	for (i=0; i < M; i++) x[i] += h6*(k1[i] + 2*k2[i] + 2*k3[i] + k4[i]);
}
Esempio n. 9
0
int main(void)
{
	int i,j;
	float eps,hdid,hnext,htry,x=1.0,*y,*dydx,*dysav,*ysav,*yscal;

	y=vector(1,N);
	dydx=vector(1,N);
	dysav=vector(1,N);
	ysav=vector(1,N);
	yscal=vector(1,N);
	ysav[1]=bessj0(x);
	ysav[2]=bessj1(x);
	ysav[3]=bessj(2,x);
	ysav[4]=bessj(3,x);
	derivs(x,ysav,dysav);
	for (i=1;i<=N;i++) yscal[i]=1.0;
	htry=0.6;
	printf("%10s %11s %12s %13s\n","eps","htry","hdid","hnext");
	for (i=1;i<=15;i++) {
		eps=exp((double) -i);
		x=1.0;
		for (j=1;j<=N;j++) {
			y[j]=ysav[j];
			dydx[j]=dysav[j];
		}
		rkqs(y,dydx,N,&x,htry,eps,yscal,&hdid,&hnext,derivs);
		printf("%13f %8.2f %14.6f %12.6f \n",eps,htry,hdid,hnext);
	}
	free_vector(yscal,1,N);
	free_vector(ysav,1,N);
	free_vector(dysav,1,N);
	free_vector(dydx,1,N);
	free_vector(y,1,N);
	return 0;
}
Esempio n. 10
0
//===========================================================================
double Param2FunctionInt::isolateDegPar(int dir, int deg_edge, 
					double threshold)
//===========================================================================
{
    // Specify boundary parameters
    int  deg = (deg_edge == 3) ? 1 : deg_edge;
    int bd_idx = 2*dir + deg - 1;
    double bd_par = (deg == 1) ? startParam(dir) : endParam(dir);
    
    if (deg == 0 || deg_tol_ < 0 || !bd_deg_[bd_idx])
	return bd_par;  // No degeneracy

    // Compute the end parameter of the domain corresponding to a 
    // piece of the surface of size fac*epsge from the degenerate edge
    double fac = 10.0;
    int nsample = 5;
    double param[2], delta;
    int ki;

    param[dir] = bd_par;
    param[1-dir] = startParam(1-dir);
    delta = (endParam(1-dir) - param[1-dir])/(double)(nsample-1);

    Point der[2];
    double length;
    double delta_par = 0.0;
    for (ki=0; ki<nsample; ki++, param[1-dir] += delta)
    {
	derivs(param[0], param[1], der[0], der[1]);
	length = der[dir].length();
	delta_par = std::max(delta_par, fac*deg_tol_/length);
    }

    return (deg == 1) ? bd_par + delta_par : bd_par - delta_par;
}
Esempio n. 11
0
int main(void)
{
	int i;
	float a1=0.5976,a2=1.4023,a3=0.0,*y,*yout,*dfdx,**dfdy,*dydx;

	y=vector(1,NVAR);
	yout=vector(1,NVAR);
	dfdx=vector(1,NVAR);
	dfdy=matrix(1,NVAR,1,NVAR);
	dydx=vector(1,NVAR);
	y[1]=y[2]=1.0;
	y[3]=0.0;
	derivs(X1,y,dydx);
	jacobn(X1,y,dfdx,dfdy,NVAR);
	printf("Test Problem:\n");
	for (i=5;i<=50;i+=5) {
		simpr(y,dydx,dfdx,dfdy,NVAR,X1,HTOT,i,yout,derivs);
		printf("\n%s %5.2f %s %5.2f %s %2d %s \n",
			"x=",X1," to ",X1+HTOT," in ",i," steps");
		printf("%14s %9s\n","integration","bessj");
		printf("%12.6f %12.6f\n",yout[1],a1);
		printf("%12.6f %12.6f\n",yout[2],a2);
		printf("%12.6f %12.6f\n",yout[3],a3);
	}
	free_vector(dydx,1,NVAR);
	free_matrix(dfdy,1,NVAR,1,NVAR);
	free_vector(dfdx,1,NVAR);
	free_vector(yout,1,NVAR);
	free_vector(y,1,NVAR);
	return 0;
}
Esempio n. 12
0
int main(void)
{
	int i;
	float b1,b2,b3,b4,xf=X1+HTOT,*y,*yout,*dydx;

	y=vector(1,NVAR);
	yout=vector(1,NVAR);
	dydx=vector(1,NVAR);
	y[1]=bessj0(X1);
	y[2]=bessj1(X1);
	y[3]=bessj(2,X1);
	y[4]=bessj(3,X1);
	derivs(X1,y,dydx);
	b1=bessj0(xf);
	b2=bessj1(xf);
	b3=bessj(2,xf);
	b4=bessj(3,xf);
	printf("First four Bessel functions:\n");
	for (i=5;i<=50;i+=5) {
		mmid(y,dydx,NVAR,X1,HTOT,i,yout,derivs);
		printf("\n%s %5.2f %s %5.2f %s %2d %s \n",
			"x=",X1," to ",X1+HTOT," in ",i," steps");
		printf("%14s %9s\n","integration","bessj");
		printf("%12.6f %12.6f\n",yout[1],b1);
		printf("%12.6f %12.6f\n",yout[2],b2);
		printf("%12.6f %12.6f\n",yout[3],b3);
		printf("%12.6f %12.6f\n",yout[4],b4);
		printf("\nPress RETURN to continue...\n");
		(void) getchar();
	}
	free_vector(dydx,1,NVAR);
	free_vector(yout,1,NVAR);
	free_vector(y,1,NVAR);
	return 0;
}
Esempio n. 13
0
/*
* Simple Euler solver.
*/
void Neuron::solve(double dt, double *y) {
	double dydt[4];

	derivs(y, dydt);

	for (size_t i = 0; i < 4; ++i) y[i] += dt * dydt[i];
}
Esempio n. 14
0
int rkqc(double *y,double *dydx, double *x, double *h, double den, double *yscal, double *hdid, double *hnext, double TOL){
	
	double safety = 0.9;
	double fcor = 0.0666666667;
	double errcon = 6.0E-4;
    double pgrow = -0.20;
	double pshrnk = -0.25;
	double xsav;
	int i;
	double ysav[2],  dysav[2], ytemp[2];
	double errmax;
	double hh;
	
	xsav = *x;
	
	for (i=0;i<2;i++) {
		ysav[i] = y[i];
		dysav[i] = dydx[i];
	}
	
	do {
		hh = 0.5**h;
		rk4(xsav, ysav, dysav, hh, ytemp, den);
		
		*x = xsav + hh;
		derivs(*x,ytemp,dydx,den); //find derivative
		rk4(*x, ytemp, dydx, hh, y, den);
		
		*x = xsav + *h;
		if (*x  == xsav) {
			printf("ERROR: Stepsize not significant in RKQC.\n");
			return 0;
		}
		rk4(xsav, ysav, dysav, *h, ytemp, den);
		
		errmax = 0.0;
		for (i=0;i<2;i++) {
			ytemp[i] = y[i] - ytemp[i];
			errmax = max(errmax, sqrt(pow(ytemp[i]/yscal[i],2)));
		}
		errmax /= TOL;
		if (errmax > 1.0) *h = safety**h*(pow(errmax,pshrnk)); //if integration error is too large, decrease h
		
	} while (errmax > 1.0);
	
	
	*hdid = *h;
	if (errmax > errcon) {
		*hnext = safety**h*(pow(errmax,pgrow));//increase step size for next step
	} else {
		*hnext = 4.0**h;//if integration error is very small increase step size significantly for next step
	}
	
	for (i=0;i<2;i++) {
		y[i] += ytemp[i]*fcor;
	}
	
	return 0;
	
}
Esempio n. 15
0
int main(void)
{
	int i,j;
	float h,x=1.0,*y,*dydx,*yout;

	y=vector(1,N);
	dydx=vector(1,N);
	yout=vector(1,N);
	y[1]=bessj0(x);
	y[2]=bessj1(x);
	y[3]=bessj(2,x);
	y[4]=bessj(3,x);
	derivs(x,y,dydx);
	printf("\n%16s %5s %12s %12s %12s\n",
		"Bessel function:","j0","j1","j3","j4");
	for (i=1;i<=5;i++) {
		h=0.2*i;
		rk4(y,dydx,N,x,h,yout,derivs);
		printf("\nfor a step size of: %6.2f\n",h);
		printf("%12s","rk4:");
		for (j=1;j<=4;j++) printf(" %12.6f",yout[j]);
		printf("\n%12s %12.6f %12.6f %12.6f %12.6f\n","actual:",
			bessj0(x+h),bessj1(x+h),bessj(2,x+h),bessj(3,x+h));
	}
	free_vector(yout,1,N);
	free_vector(dydx,1,N);
	free_vector(y,1,N);
	return 0;
}
Esempio n. 16
0
void StepperDopr853<D>::step(const Doub htry,D &derivs) {
  VecDoub dydxnew(n);
  Doub h=htry;
  for (;;) {
    dy(h,derivs);
    Doub err=error(h);
    if (con.success(err,h)) break;
    if (std::abs(h) <= std::abs(x)*EPS) {
      // <added>
      std::cerr << "\nh=" << h << "\tx=" << x
                << "\tstd::abs(h)=" << std::abs(h) << "\tstd::abs(x)=" << std::abs(x)
                << "\tEPS=" << EPS << std::endl;
      // </added>
      Throw1WithMessage("stepsize underflow in StepperDopr853");
    }
  }
  derivs(x+h,yout,dydxnew);
  if (dense)
    prepare_dense(h,dydxnew,derivs);
  dydx=dydxnew;
  y=yout;
  xold=x;
  x += (hdid=h);
  hnext=con.hnext;
}
Esempio n. 17
0
Eigen::VectorXd LayerAdapter::gradient(std::vector<int>::const_iterator startN,
                                       std::vector<int>::const_iterator endN)
{
  // Assumes that we want to comput the gradient of the whole training set
  OPENANN_CHECK_EQUALS(*startN, 0);
  OPENANN_CHECK_EQUALS(endN-startN, input.rows());
  Eigen::MatrixXd* output;
  layer.forwardPropagate(&input, output, false);
  Eigen::MatrixXd diff = *output - desired;
  Eigen::MatrixXd* e = &diff;
  layer.backpropagate(e, e);
  Eigen::VectorXd derivs(dimension());
  std::vector<double*>::const_iterator it = derivatives.begin();
  for(int i = 0; i < dimension(); i++, it++)
    derivs(i) = **it;
  return derivs;
}
Esempio n. 18
0
 void update_derivs(const vector<int>& toCoords)
 {
     const vector<int>* fromCoords = add_delay(toCoords);
     if (fromCoords) 
     {
         outer(this->from->out_acts(*fromCoords), derivs().begin(), this->to->inputErrors[toCoords]);
     }
 }
Esempio n. 19
0
void Conductance::solve(double dt, double *y) {
    double dydt[MODEL_DIM];

    derivs(y,dydt);

    for(size_t i = 0;i < MODEL_DIM;++i)
        y[i] += dt*dydt[i];
}
Esempio n. 20
0
void rkqc(double *y,double *dydt,int n,double t,double htry,double eps,
          double *yscal,double *hdid,double *hnext)
{
    /* Quality-controlled fifth-order Runge-Kutta. */

    int i;
    double tsav,hh,h,temp,errmax;
    double *dysav,*ysav,*ytemp;
    double PGROW,PSHRNK,FCOR,SAFETY,ERRCON;

    PGROW=-0.20;
    PSHRNK=-0.25;
    FCOR=1.0/15.0;
    SAFETY=0.9;
    ERRCON=6.0e-4;

    dysav=malloc(n*sizeof(double));
    ysav=malloc(n*sizeof(double));
    ytemp=malloc(n*sizeof(double));
    tsav=t;
    for (i=0; i<n; i++)
    {
        ysav[i]=y[i];
        dysav[i]=dydt[i];
    }
    h=htry;
    for (;;)
    {
        hh=0.5*h;
        rk4(ysav,dysav,n,hh,ytemp);
        t=tsav+hh;
        derivs(ytemp,dydt);
        rk4(ytemp,dydt,n,hh,y);
        t=tsav+h;
        if (t==tsav) printf("Step size too small in RKQC");
        rk4(ysav,dysav,n,h,ytemp);
        errmax=0.0;
        for (i=0; i<n; i++)
        {
            ytemp[i]=y[i]-ytemp[i];
            temp=fabs(ytemp[i]/yscal[i]);
            if (errmax<temp) errmax=temp;
        }
        errmax/=eps;
        if (errmax<1.0)
        {
            *hdid=h;
            *hnext=(errmax>ERRCON ? SAFETY*h*exp(PGROW*log(errmax)) : 4.0*h);
            break;
        }
        h=SAFETY*h*exp(PSHRNK*log(errmax));
    }
    for (i=0; i<n; i++)
        y[i]+=ytemp[i]*FCOR;
    free(ytemp);
    free(dysav);
    free(ysav);
}
Esempio n. 21
0
float euler(float xin, float yin, float h){
  /* do one Euler step of size h */
  int i;
  float yout, dydx;
 
  dydx = derivs(xin, yin); /* evaluate dy/dx */
  yout = yin + dydx * h; /* Euler step */

  return yout;
}
Esempio n. 22
0
void StepperDopr853<D>::prepare_dense(const Doub h,VecDoub_I &dydxnew,
                                      D &derivs) {
  Int i;
  Doub ydiff,bspl;
  VecDoub ytemp(n);
  for (i=0;i<n;i++) {
    rcont1[i]=y[i];
    ydiff=yout[i]-y[i];
    rcont2[i]=ydiff;
    bspl=h*dydx[i]-ydiff;
    rcont3[i]=bspl;
    rcont4[i]=ydiff-h*dydxnew[i]-bspl;
    rcont5[i]=d41*dydx[i]+d46*k6[i]+d47*k7[i]+d48*k8[i]+
      d49*k9[i]+d410*k10[i]+d411*k2[i]+d412*k3[i];
    rcont6[i]=d51*dydx[i]+d56*k6[i]+d57*k7[i]+d58*k8[i]+
      d59*k9[i]+d510*k10[i]+d511*k2[i]+d512*k3[i];
    rcont7[i]=d61*dydx[i]+d66*k6[i]+d67*k7[i]+d68*k8[i]+
      d69*k9[i]+d610*k10[i]+d611*k2[i]+d612*k3[i];
    rcont8[i]=d71*dydx[i]+d76*k6[i]+d77*k7[i]+d78*k8[i]+
      d79*k9[i]+d710*k10[i]+d711*k2[i]+d712*k3[i];
  }
  for (i=0;i<n;i++)
    ytemp[i]=y[i]+h*(a141*dydx[i]+a147*k7[i]+a148*k8[i]+a149*k9[i]+
                     a1410*k10[i]+a1411*k2[i]+a1412*k3[i]+a1413*dydxnew[i]);
  derivs(x+c14*h,ytemp,k10);
  for (i=0;i<n;i++)
    ytemp[i]=y[i]+h*(a151*dydx[i]+a156*k6[i]+a157*k7[i]+a158*k8[i]+
                     a1511*k2[i]+a1512*k3[i]+a1513*dydxnew[i]+a1514*k10[i]);
  derivs(x+c15*h,ytemp,k2);
  for (i=0;i<n;i++)
    ytemp[i]=y[i]+h*(a161*dydx[i]+a166*k6[i]+a167*k7[i]+a168*k8[i]+
                     a169*k9[i]+a1613*dydxnew[i]+a1614*k10[i]+a1615*k2[i]);
  derivs(x+c16*h,ytemp,k3);
  for (i=0;i<n;i++)
    {
      rcont5[i]=h*(rcont5[i]+d413*dydxnew[i]+d414*k10[i]+d415*k2[i]+d416*k3[i]);
      rcont6[i]=h*(rcont6[i]+d513*dydxnew[i]+d514*k10[i]+d515*k2[i]+d516*k3[i]);
      rcont7[i]=h*(rcont7[i]+d613*dydxnew[i]+d614*k10[i]+d615*k2[i]+d616*k3[i]);
      rcont8[i]=h*(rcont8[i]+d713*dydxnew[i]+d714*k10[i]+d715*k2[i]+d716*k3[i]);
    }
}
Esempio n. 23
0
//establishes function for Runge-Kutta Method  2
void rk2 (double t, double x[], void derivs(double, double[], double[]), double h, int M) 
{
 
	double k1[M], k2[M], xp[M];
	int i;

	derivs(t, x, k1); 
// compute k1[i] (= derivs at (t, x) )
 
	for (i=0; i < M; i++) 
		xp[i] = x[i] + h * k1[i]; 
// xp = x + h*k1

 	derivs(t+h, xp, k2); 

// compute k2[i] (= derivs at (t+h, x+h*k1) )
 
	for(i=0; i < M; i++) 
		x[i] += 0.5 * h * (k1[i] + k2[i]); 
// compute x[i]
}
Esempio n. 24
0
void NR::simpr(Vec_I_DP &y, Vec_I_DP &dydx, Vec_I_DP &dfdx, Mat_I_DP &dfdy,
	const DP xs, const DP htot, const int nstep, Vec_O_DP &yout,
	void derivs(const DP, Vec_I_DP &, Vec_O_DP &))
{
	int i,j,nn;
	DP d,h,x;

	int n=y.size();
	Mat_DP a(n,n);
	Vec_INT indx(n);
	Vec_DP del(n),ytemp(n);
	h=htot/nstep;
	for (i=0;i<n;i++) {
		for (j=0;j<n;j++) a[i][j] = -h*dfdy[i][j];
		++a[i][i];
	}
	ludcmp(a,indx,d);
	for (i=0;i<n;i++)
		yout[i]=h*(dydx[i]+h*dfdx[i]);
	lubksb(a,indx,yout);
	for (i=0;i<n;i++)
		ytemp[i]=y[i]+(del[i]=yout[i]);
	x=xs+h;
	derivs(x,ytemp,yout);
	for (nn=2;nn<=nstep;nn++) {
		for (i=0;i<n;i++)
			yout[i]=h*yout[i]-del[i];
		lubksb(a,indx,yout);
		for (i=0;i<n;i++) ytemp[i] += (del[i] += 2.0*yout[i]);
		x += h;
		derivs(x,ytemp,yout);
	}
	for (i=0;i<n;i++)
		yout[i]=h*yout[i]-del[i];
	lubksb(a,indx,yout);
	for (i=0;i<n;i++)
		yout[i] += ytemp[i];
}
bool MultiSmoothInterpolate(SmoothConstrainedInterpolator& interp,const vector<Vector>& pts,GeneralizedCubicBezierSpline& path)
{
  path.segments.resize(0);
  path.durations.resize(0);
  Vector temp;
  GeneralizedCubicBezierSpline cpath;
  vector<GeneralizedCubicBezierCurve> pathSegs;
  MonotonicInterpolate(pts,pathSegs,interp.space);
  //SplineInterpolate(pts,pathSegs,interp.space);
  Assert(pathSegs.size()+1==pts.size());
  vector<Vector> derivs(pts.size());
  pathSegs[0].Deriv(0,derivs[0]);
  for(size_t i=0;i+1<pts.size();i++) 
    pathSegs[i].Deriv(1,derivs[i+1]);
  //project tangent points
  for(size_t i=0;i<pts.size();i++) 
    interp.ProjectVelocity(pts[i],derivs[i]);

  /*
  //condition tangent points?
  for(size_t i=0;i+1<pts.size();i++) 
    pathSegs[i].SetNaturalTangents(derivs[i],derivs[i+1]);
  //TODO: global solve?
  for(int iters=0;iters<10;iters++) {
    for(size_t i=0;i+1<pts.size();i++) {
      ConditionMiddleTangent(pathSegs[i],pathSegs[i+1]);
      pathSegs[i].Deriv(1,derivs[i+1]);
    }
  }
  */

  for(size_t i=0;i+1<pts.size();i++) {
    cpath.segments.resize(0);
    cpath.durations.resize(0);

    Assert(i < pathSegs.size());
    Assert(pathSegs.size()+1==pts.size());
    //bool res=interp.Make(pts[i],di,pts[i+1],dn,cpath);
    bool res=interp.Make(pathSegs[i].x0,derivs[i],pathSegs[i].x3,derivs[i+1],cpath);
    if(!res) {
      printf("Could not make path between point %d and %d\n",i,i+1);
      return false;
    }
    //cout<<"Actual initial velocity: "<<3.0*(cpath.front().x1-cpath.front().x0)/cdurations.front()<<", terminal velocity: "<<3.0*(cpath.back().x3-cpath.back().x2)/cdurations.back()<<endl;
    path.Concat(cpath);
  }
  return true;
}
Esempio n. 26
0
void modeldata::spin_galaxy(double factor) {
	extern void derivs(int,double,double *, double *);
	double r,a,v,cosine,sine;
	derivs(neq,time_step,x,der);

	for(int i=0;i<npoints;i++) {
		r=sqrt(pos.x[i]*pos.x[i]+pos.y[i]*pos.y[i]);
		if(r>0.0) {
			a=sqrt(vder.x[i]*vder.x[i]+vder.y[i]*vder.y[i]);
			v=sqrt(a*r);
			cosine=pos.x[i]/r;
			sine=pos.y[i]/r;
			vel.x[i]=v*factor*(-sine);
			vel.y[i]=v*factor*cosine;
		}
	}

}
Esempio n. 27
0
 void compute_derivs(const state_type &y, state_type &dydt,
                     const double t) {
   derivs(y, dydt, t, pars);
 }
Esempio n. 28
0
//==========================================================================
bool SplineSurface::normal_not_failsafe(Point& pt, double upar, double vpar) const
//==========================================================================
{
    double tol = DEFAULT_SPACE_EPSILON;

#ifdef _OPENMP
    vector<Point> derivs(3, Point(1.0, 1.0, 1.0));
#else
    static vector<Point> derivs(3, Point(1.0, 1.0, 1.0));
#endif
    point(derivs, upar, vpar, 1);
    //    vector<Point> derivs = ParamSurface::point(upar, vpar, 1);

    //    Point &der1=derivs[1];
    //    Point &der2=derivs[2];
    pt.resize(3);
    pt.setToCrossProd(derivs[1], derivs[2]);
    double l = pt.length();
    int iterations = 0;
    // @@sbr But this depends on the parametrization!!! Why not use
    // angle between cross tangents as a guiding line?
    double cross_tan_ang = derivs[1].angle_smallest(derivs[2]);
    cross_tan_ang = min(cross_tan_ang, fabs(M_PI - cross_tan_ang));
    double cross_tan_ang_tol = 1e-03;
    while (l < tol) {
	// Surface is degenerate at that point. One of the derivatives
	// must be small.
	int okderindex = 1;
	if (derivs[1].length2() < derivs[2].length2())
	    okderindex = 2;
	Point okder = derivs[okderindex];
// #ifdef _MSC_VER
// 	const RectDomain& rd 
// 	  = dynamic_cast<const RectDomain&>(parameterDomain());
// #else
	const RectDomain& rd = parameterDomain();
// #endif
	double lowx = okderindex==2 ? rd.vmin() : rd.umin();
	double x = okderindex==2 ? vpar : upar;
	bool xislow = false;
	if (abs(x-lowx) < tol) {
	    xislow = true;
	}
	double lowt = okderindex==2 ? rd.umin() : rd.vmin();
	double hight = okderindex==2 ? rd.umax() : rd.vmax();
	double t = okderindex==2 ? upar : vpar;
	double newt = lowt;
	bool lowchoice = true;
	if (hight - t > t - lowt) {
	    newt = hight;
	    lowchoice = false;
	}
	if (okderindex==2) {
	    upar = newt;
	} else {
	    vpar = newt;
	}
	point (derivs, upar, vpar, 1);
	bool okderfirst = true;
	if (okderindex==2) {
	    okderfirst = (lowchoice == xislow);
	} else {
	    okderfirst = (lowchoice != xislow);
	}
	pt = okderfirst ?
	    okder % derivs[okderindex] : derivs[okderindex] % okder;
	l = pt.length();
	++iterations;
	if (iterations == 2) break;
    }
    if (l < tol || cross_tan_ang < cross_tan_ang_tol) {
//         if (cross_tan_ang < cross_tan_ang_tol)
// 	    MESSAGE("Too small angle between cross tangents, "
// 		    "degenerate point!");
	pt.setValue(0.0);
	return false;
    }
    pt /= l;
    return true;
}
Esempio n. 29
0
int odeint(double ystart0, double ystart1, double x1, double x2, double den, int *kount, double *xp, double **yp, int M, int KMAX) {
	
	double HMIN = 0.0;			//Minimum step size
	double H1 = 0.0001;			//Size of first step
	int MAXSTP = 100000;		//Maximum number of steps for integration
	double TINY = 1.0E-30;		//To avoid certain numbers get zero
	double DXSAV = 0.0001;		//Output step size for integration
	double TOL = 1.0E-12;		//Tolerance of integration
	
	
	double x;
	double h;
	int i,j;
	double y[2];
	double hdid, hnext;
	double xsav;
	double dydx[2], yscal[2];
	
	x = x1;   //King's W parameter
	if (x2-x1 >= 0.0) {
		h = sqrt(pow(H1,2));
	} else {
		h = - sqrt(pow(H1,2));
	}  //step size
	
	y[0] = ystart0;  //z^2
	y[1] = ystart1;  //2*z*dz/dW  where z is scaled radius	
	
	xsav = x-DXSAV*2.0;
	
	for (i=0;i<MAXSTP;i++) {        //limit integration to MAXSTP steps
		
		derivs(x,y,dydx,den); //find derivative
		
		for (j=0;j<2;j++) {
			yscal[j] = sqrt(pow(y[j],2))+sqrt(h*dydx[j])+TINY;  //advance y1 and y2
		}
		
		if (sqrt(pow(x-xsav,2)) > sqrt(pow(DXSAV,2))) {
			if (*kount < KMAX-1) {
				xp[*kount] = x;
				for (j=0;j<2;j++) {
					yp[*kount][j] = y[j];
				}
				*kount = *kount + 1;
				xsav = x;
			}
		}  //store x, y1 and y2 if the difference in x is smaller as the desired output step size DXSAV
		
		if (((x+h-x2)*(x+h-x1)) > 0.0) h = x2-x;
		
		rkqc(y,dydx,&x,&h,den,yscal, &hdid, &hnext, TOL);	//do a Runge-Kutta step
		
		if ((x-x2)*(x2-x1) >= 0.0) {
			ystart0 = y[0];
			ystart1 = y[1];
			
			xp[*kount] = x;
			for (j=0;j<2;j++) {
				yp[*kount][j] = y[j];
			}
			return 0;	
			*kount = *kount +1;
		}
		
		if (sqrt(pow(hnext,2)) < HMIN) {
			printf("Stepsize smaller than minimum.\n");
			return 0;
		}
		
		h = hnext;
	} 
	
	return 0;
}
Esempio n. 30
0
int
main()
{
    DenseVector     sings;
    GeMat           deltas(3,2);

    std::vector<GeMat> _deltas;
    Function        x2f(x2, sings);
    Function        onef(one, sings);
    Function        x3f(x3, sings);
    Function        cosf(mycos, sings);
    Function        sinf(mysin, sings);
    Function        expf(myexp, sings);
    Basis           basis(4);
    basis.template enforceBoundaryCondition<lawa::DirichletBC>();
    IndexSet        indexset;
    Coeff1D         coeff;

    std::vector<Function> fvec;

    int rank = 2;
    int dim  = 64;

    for (int i=1; i<=32; ++i) {
        fvec.push_back(cosf);
        fvec.push_back(onef);
        fvec.push_back(x2f);
        fvec.push_back(onef);
    }

    SepCoeff        coeffs(rank, dim);
    IndexSetVec     indexsetvec(dim);
    lawa::SeparableFunctionD<T> F(fvec, rank, dim);
    MatInt                      derivs(rank, dim);
    for (int i=1; i<=rank; ++i) {
        for (int j=1; j<=dim; ++j) {
            derivs(i,j) = 0;
            _deltas.push_back(deltas);
        }
    }

    lawa::SeparableRHSD<T, Basis>   Fint(basis, F, _deltas, derivs);

    getFullIndexSet(basis, indexset, 2);

    std::cout << "The index set size is\n" << indexset.size()
              << std::endl;

    for (int l=0; (unsigned)l<indexsetvec.size(); ++l) {
        indexsetvec[l] = indexset;
    }

    /* Map */
    lawa::Mapwavind<Index1D> map(dim);
    map.rehash(50);

    genCoefficients(coeffs, Fint, indexsetvec);
    lawa::HTCoefficients<T, Basis>    f(dim, basis, map);
    lawa::HTCoefficients<T, Basis>    u(dim, basis, map);
    lawa::HTCoefficients<T, Basis>    r(dim, basis, map);

    Laplace1D       LaplaceBil(basis);
    RefLaplace1D    RefLaplaceBil(basis.refinementbasis);
    Identity1D      IdentityBil(basis);
    RefIdentity1D   RefIdentityBil(basis.refinementbasis);
    LOp_Lapl1D      lapl(basis, basis, RefLaplaceBil, LaplaceBil);

    Sepop A(lapl, dim, dim);

    lawa::Sepdiagscal<Basis>    S(dim, basis);
    setScaling(S, 0.5);

    lawa::HTAWGM_Params  params;
    params.maxit_pcg  = 100;
    params.maxit_awgm = 100;
    params.tol_awgm   = 1e-08;
    params.delta1_pcg = 1e-01;
    params.delta2_pcg = 1e-01;
    params.delta3_pcg = 1e-01;
    params.alpha      = 0.95;
    params.recompr    = 1e-02;
    params.gamma      = 0.1;
    params.theta      = 1e-08;


    std::cout << "HTAWGM params =\n";
    std::cout << params << std::endl;

    unsigned its;
    double   res;

    its = htawgm(A, S, u, Fint, indexsetvec, res, params);

    std::cout << "htawgm took " << its << " iterations to reach "
              << res << " accuracy" << std::endl;
    std::cout << "Final scaling set to\n" << S << std::endl;

    return 0;
}