///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- void SmokeUpdateStrategy::Update( double deltaSeconds, Particle* first, Particle* firstInactive ) { Particle* current = first; while (current != firstInactive) { current->state = RK4( current->state, deltaSeconds ); current = current->next; } }
/******************Public functions**********************/ void System::simulate(double tMax, double ssize, bool stat){ time = 0; h = ssize; statSun = stat; for (int i = 0 ; i<nObj ; i++){ // Saveing the inital values calc_potential(); sys[i].update(sys[i].relR, sys[i].relV, time); } while (time <= tMax){ RK4(); time += h; } }
void Solsystem::movement(double intime, double inh){ double time = intime; double h = inh; double step = time/h; remove("positions.txt"); remove("energy.txt"); for(int i = 0; i<= step; i++){ RK4(h); if(i%10==0){ printtofile(); } /*if(i%1000000==0){ cout << i << endl; }*/ } }
int main () { /* Se crean las variables del hamiltoniano para resolver con Runge Kutta*/ double q1_RK, q3_RK, p1_RK, p3_RK; /* Se crean las variables del hamiltoniano para resolver con el Integrador Simplectico*/ double q1_LF, q3_LF, p1_LF, p3_LF; /* Distancia vertical entre los cuerpos masivos*/ double eps=1.0; /* Tiempo total*/ double T=2800; /* Paso de tiempo */ double h=0.006; /* Numero de pasos*/ int n=(int)(T/h); // Elementos aleatorios long seed; seed=n; srand48( seed ); /* Condiciones iniciales*/ q1_RK=q1_LF=0.35355; q3_RK=q3_LF=2*drand48()-1; p1_RK=p1_LF=0.0; p3_RK=p3_LF=2*drand48()-1; double t=0.0; int i; //Hamiltonianos double H1,H2; for (i=0;i<n;i++) { H1=0.5*pow(p1_RK,2) - 0.5*pow( (4*pow(q1_RK,2)+pow(eps,2)) ,-0.5); H2=0.5*pow(p1_LF,2) - 0.5*pow( (4*pow(q1_LF,2)+pow(eps,2)) ,-0.5); printf("%.6f %.6f %.4f\n",H1,H2,t); RK4(h,&q1_RK,&p1_RK,&q3_RK,&p3_RK,eps); leap_frog(h,&q1_LF,&p1_LF,&q3_LF,&p3_LF,eps); t+=h; } return 0; }
int main(int argc, char** argv){ double t=0, tmax=100, step=.1; double x_0=1,zx_0=0,v_0=0,zv_0=0.1; int i; char mode='l'; /* Parse the argument list. */ for (i = 0; i < argc; i++) if (argv[i][0] == '-') { switch (argv[i][1]) { case 's': step = atof(argv[++i]); break; case 't': tmax = atof(argv[++i]); break; case 'v': v_0 = atof(argv[++i]); break; case 'x': x_0 = atof(argv[++i]); break; } } mode=atoi(argv[1]); if (mode==2){RK4(argv[2],t,tmax,step,x_0,zx_0,v_0,zv_0);} if (mode==3){lpf_int(argv[2],t,tmax,step,x_0,zx_0,v_0,zv_0);} }
void Physics::step( real_t dt ) { // step the world forward by dt. Need to detect collisions, apply // forces, and integrate positions and orientations. // // Note: put RK4 here, not in any of the physics bodies // // Must use the functions that you implemented // // Note, when you change the position/orientation of a physics object, // change the position/orientation of the graphical object that represents // it detect_collisions(); save_initial_states(); //save initial state after changing it in collisions RK4(dt); update_graphics(); }
//////////////////////RK4 INTEGRATOR////////////////////// int RK4_integration(int *par_proc) { int i,j; double C,D,min,max; ////MAKE A COPY OF THE ORIGINAL POSITIONS for(j=0;j<Num_par;j++){ for(i=0;i<MAXDIM;i++){ Auxiliar[i][j]=par[j].pos[i]; } } ////CALCULATE OF F's AND G's FOR ALL PARTICLE IN ALL DIRECTION RK4(par_proc); min=par_proc[rank]; max=par_proc[rank+1]; //////////// PARTICLE j; VELOCITY AND POSITION IN DIRECTION i //////// for(j=min;j<max;j++) { for(i=0;i<MAXDIM;i++) { C = F1[i][j]+2.0*F2[i][j]+2.0*F3[i][j]+F4[i][j]; par[j].vel[i] = par[j].vel[i]+C/6.0; D = G1[i][j]+2.0*G2[i][j]+2.0*G3[i][j]+G4[i][j]; par[j].pos[i] = Auxiliar[i][j]+D/6.0; } } //POSITION'S BROADCAST for(i=0;i<size;i++) Bcast_part_pos(i,par_proc[i],par_proc[i+1]); //VELOCITIES BROADCAST for(i=0;i<size;i++) Bcast_part_vel(i,par_proc[i],par_proc[i+1]); return 0; }
void driftdelay(const struct drifter *ptdrifter, double ***delaytensor, size_t ndr, double *fields_dot, const double *fields, const double *parameters, const double *forcing, int xdim, int ydim, double dx, double dy, const unsigned int *lat, const unsigned *lon, const int **neighbors, double dt){ int i, j, k; double *fields_temp; fields_temp = calloc(3 * xdim * ydim, sizeof(double)); memcpy(fields_temp, fields, 3 * xdim * ydim * sizeof(double)); struct drifter *ptdrifter_temp; ptdrifter_temp = calloc(ndr, sizeof(struct drifter)); memcpy(ptdrifter_temp, ptdrifter, ndr * sizeof(struct drifter)); for(i = 0; i < ndr; i++){ delaytensor[i][0][0] = ptdrifter_temp[i].x; delaytensor[i][0][1] = ptdrifter_temp[i].y; } for(i = 1; i < Dm; i++){ for (j = 0; j < tau; j++){ RK4(fields_dot, fields_temp, parameters, forcing, xdim, ydim, dx, dy, dt, neighbors, lat, lon); RK4drift(ptdrifter_temp, ndr, fields_temp, parameters, forcing, xdim, ydim, dx, dy, neighbors, lat, lon, dt); } for(k = 0; k < ndr; k++) { delaytensor[k][i][0] = ptdrifter_temp[k].x; delaytensor[k][i][1] = ptdrifter_temp[k].y; } } free(fields_temp); free(ptdrifter_temp); }
// call this to solve the equations and save results to files // the system will determine the number of steps; all we need is to provide a step length // returns the system in the state the Leapfrog algoritm leaves it in (or nullptr if that algorithm is not used) vector<SolarSystem*>* Solvers::Solve(double step) { clock_t start, finish; // timers int n = this->_system->nSteps(); if (this->_useRK4) { start = clock(); // start timer for (int i = 0; i < n; i++) // for each time step { this->_rk4->plotCurrentStep(i, step); // if we want to plot this step, do it RK4(step); // perform step } // Timing part: End ... finish = clock(); this->rk4Time = (double)(finish - start) / CLOCKS_PER_SEC; // To convert this into seconds ! } if (this->_useLeapfrog) { start = clock(); // start timer for (int i = 0; i < n; i++) // for each time step { this->_leapfrog->plotCurrentStep(i, step); // if we want to plot this step, do its Leapfrog(step); // perform step } // Timing part: End ... finish = clock(); this->leapfrogTime = (double)(finish - start) / CLOCKS_PER_SEC; // To convert this into seconds ! } if (this->_useEuler) { start = clock(); // start timer for (int i = 0; i < n; i++) // for each time step { this->_euler->plotCurrentStep(i, step); // if we want to plot this step, do it Euler(step); // perform step } // Timing part: End ... finish = clock(); this->eulerTime = (double)(finish - start) / CLOCKS_PER_SEC; // To convert this into seconds ! } // put systems we want to return in here vector<SolarSystem*>* returnSystems = new vector<SolarSystem*>(); if (this->_useLeapfrog) { // plot to file (independent of dimension) for (int i = 0; i < this->_leapfrog->dim(); i++) { ostringstream fname = ostringstream(); fname << "sim_" << this->_leapfrog->name << "_pos" << i << ".dat"; this->_leapfrog->plotDim(i, fname.str()); } // make sure the system is up to date this->_leapfrog->calculate(); // add to list of systems to return returnSystems->push_back(this->_leapfrog); } if (this->_useRK4) { // plot to file (independent of dimension) for (int i = 0; i < this->_rk4->dim(); i++) { ostringstream fname = ostringstream(); fname << "sim_" << this->_rk4->name << "_pos" << i << ".dat"; this->_rk4->plotDim(i, fname.str()); } // make sure the system is up to date this->_rk4->calculate(); // add to list of systems to return returnSystems->push_back(this->_rk4); } if (this->_useEuler) { // plot to file (independent of dimension) for (int i = 0; i < this->_euler->dim(); i++) { ostringstream fname = ostringstream(); fname << "sim_" << this->_euler->name << "_pos" << i << ".dat"; this->_euler->plotDim(i, fname.str()); } // make sure the system is up to date this->_euler->calculate(); // add to list of systems to return returnSystems->push_back(this->_euler); } cout << "DONE!" << endl << endl; this->totalTime = this->leapfrogTime + this->rk4Time + this->eulerTime; return returnSystems; }
bool Bridge:: FinalRadius(const double height, const double theta, const double alpha, const bool save) { //__________________________________________________________________________ // // do we save ? //__________________________________________________________________________ if(save) { static vfs & fs = local_fs::instance(); fs.try_remove_file("profile.dat"); } //__________________________________________________________________________ // // check possibility //__________________________________________________________________________ const double omega = lens->omega(alpha); const double angle = omega+theta; if(angle>=180) { return false; } //__________________________________________________________________________ // // prepare initial conditions //__________________________________________________________________________ const double Rc = lens->rho(0.0)+height; const double R0 = lens->rho(alpha); const double r0 = R0*SinDeg(alpha); const double z0 = Rc - R0*CosDeg(alpha); const double drdz = CosDeg(angle)/SinDeg(angle); Y[1] = r0; Y[2] = drdz; //__________________________________________________________________________ // // do we save ? //__________________________________________________________________________ auto_ptr<ios::ostream> fp; if(save) { fp.reset(new ios::ocstream("profile.dat",false) ); (*fp)("%g %g\n", r0, z0 ); } //__________________________________________________________________________ // // Try to integrate //__________________________________________________________________________ double reg[3] = { Y[1],0,0 }; // curvature detector size_t num = 1; bool success = true; for(size_t i=NUM_STEPS;i>0;--i) { const double z_ini = (i*z0)/NUM_STEPS; const double z = ((i-1)*z0)/NUM_STEPS; RK4(z_ini, z); //______________________________________________________________________ // // analyze //______________________________________________________________________ const double r = Y[1]; //______________________________________________________________________ // // absolute position //______________________________________________________________________ if( isnan(r) || isinf(r) || r <= 0.0 ) { success = false; break; } //______________________________________________________________________ // // Relative position: inside lens ? //______________________________________________________________________ const double dr = r; const double dz = Rc-z; const double dist = Hypotenuse(dr, dz); const double aa = Rad2Deg(2.0 * Atan( dr / (dz+dist))); const double ra = lens->rho(aa); if(dist<ra) { success = false; break; } //__________________________________________________________________ // // test valid curvature //__________________________________________________________________ if(num<3) { reg[num++] = r; } else { reg[0] = reg[1]; reg[1] = reg[2]; reg[2] = r; if((reg[1]+reg[1])>= (reg[0]+reg[2]) ) { success = false; break; } } if(save && (r<=4*Rc)) { (*fp)("%g %g\n", r, z ); } } return success; }
void doIdle() { char s[20]="picxxxx.ppm"; int i; // save screen to file s[3] = 48 + (sprite / 1000); s[4] = 48 + (sprite % 1000) / 100; s[5] = 48 + (sprite % 100 ) / 10; s[6] = 48 + sprite % 10; if (saveScreenToFile==1) { saveScreenshot(windowWidth, windowHeight, s); //saveScreenToFile=0; // save only once, change this if you want continuos image generation (i.e. animation) sprite++; } if (sprite >= 300) // allow only 300 snapshots { exit(0); } if (pause == 0) { // insert code which appropriately performs one step of the cube simulation: if (Integration[0] == 'E') { Euler(&jello); }else if (Integration[0] == 'R') { RK4(&jello); }else { exit(0); } } if (Fx == 1) { jello.Force.x += 1; Fx = 0; } if (Fx == -1) { jello.Force.x -= 1; Fx = 0; } if (Fy == 1) { jello.Force.y += 1; Fy = 0; } if (Fy == -1) { jello.Force.y -= 1; Fy = 0; } if (Fa == 1) { alpha += 1; Fa = 0; } if (Fa == -1) { if (alpha != 0) { alpha -= 1; Fa = 0; } } if (Fb == 1) { beta += 0.1; Fb = 0; } if (Fb == -1) { beta -= 0.1; Fb = 0; } if (PNoise == -1) { jello.Force.x = 0; jello.Force.y = -1; PNoise = 0; for (int i=0; i<particleNum; i++) { jello.v[i].x = 0; jello.v[i].y = 0; jello.v[i].z = 0; jello.a[i].x = 0; jello.a[i].y = 0; jello.a[i].z = 0; } } if (PNoise == 1) { srand(time(NULL)); PerlinNoise P; if (alpha == 0) { jello.Force.x = P.PerlinNoise1D(rand()%100, particleNum , 0.3); jello.Force.y = P.PerlinNoise1D(rand()%100, particleNum , 0.3); }else { jello.Force.x = P.PerlinNoise1D(rand()%100, particleNum , 0.3) * 20; jello.Force.y = P.PerlinNoise1D(rand()%100, particleNum , 0.3) * 20; } } //reset everything if (Fx == -5) { for (int i=0; i<particleNum; i++) { jello.v[i].x = 0; jello.v[i].y = 0; jello.v[i].z = 0; jello.a[i].x = 0; jello.a[i].y = 0; jello.a[i].z = 0; } jello.Force.x = 0; jello.Force.y = -1; alpha = 0; beta = 0; PNoise = 0; Fx = 0; } glutPostRedisplay(); }
int main(int argc, char **argv){ int i; double min_t=0.0; double max_t=100; double k; double alpha_deg; k=atof(argv[1]); alpha_deg=atof(argv[2]); //Parametros de energia cinteica y angulo entran como parametros double alpha=alpha_deg*pi/180.0; double gamma; gamma=k*J_MeV/(m*c*c)+1; //Definicion de factor de Lorentz double V; V=c*(pow((1.0-1.0/(gamma*gamma)),0.5)); //Definicion de manginut de velocidad de la particula double T; T=2*pi*gamma*m/(q*B0); //Definicion del momento de cicloton de la particula double dt; dt=T/25; //Definicion del delta de tiempo como 1/25 del periodo de ciclotron int n_points=((max_t-min_t)/dt); double *t; double *x; double *y; double *z; double *u; double *v; double *w; double *r; double *vel; double *tnew; double *xnew; double *ynew; double *znew; double *unew; double *vnew; double *wnew; FILE *fileout; t=malloc(sizeof(double)*n_points); x=malloc(sizeof(double)*n_points); y=malloc(sizeof(double)*n_points); z=malloc(sizeof(double)*n_points); u=malloc(sizeof(double)*n_points); v=malloc(sizeof(double)*n_points); w=malloc(sizeof(double)*n_points); r=malloc(sizeof(double)*n_points); vel=malloc(sizeof(double)*n_points); //Definicion con punteros de double con cada una de las coordenadas (x,y,z) y sus respectivas velocidades (u,v,w) con las magnitudes de los vectores posicion (r) y velocidad (vel) tnew=malloc(sizeof(double)); xnew=malloc(sizeof(double)); ynew=malloc(sizeof(double)); znew=malloc(sizeof(double)); unew=malloc(sizeof(double)); vnew=malloc(sizeof(double)); wnew=malloc(sizeof(double)); //Definicion de punteros para ser utilizados como paramtros de RK4 t[0]=min_t; x[0]=2*Rt; y[0]=0; z[0]=0; u[0]=0; v[0]=V*sin(alpha); w[0]=V*cos(alpha); r[0]=pow(x[0]*x[0]+y[0]*y[0]+z[0]*z[0],0.5); vel[0]=pow(u[0]*u[0]+v[0]*v[0]+w[0]*w[0],0.5); //Inicializacion de velocidades y posiciones *tnew=t[0]; *xnew=x[0]; *ynew=y[0]; *znew=z[0]; *unew=u[0]; *vnew=v[0]; *wnew=w[0]; for(i=1;i<n_points;i++){ RK4(tnew,xnew,ynew,znew,unew,vnew,wnew,dt,gamma); t[i]=*tnew; x[i]=*xnew; y[i]=*ynew; z[i]=*znew; u[i]=*unew; v[i]=*vnew; w[i]=*wnew; r[i]=pow(x[i]*x[i]+y[i]*y[i]+z[i]*z[i],0.5); vel[i]=pow(u[i]*u[i]+v[i]*v[i]+w[i]*w[i],0.5); if(r[i]<=Rt){ break; } //Ciclo iterativo para el algoritmo de RK4 y el calculo de las nuevas posiciones y velocidades a partir de estos. Se tiene una prueba logica donde en caso de chocar una particula contra la tierra pare la iteracion. } char name[10]; int K, alpha_grad; K=(int) k; alpha_grad=(int) alpha_deg; sprintf(name, "%d_%d", K, alpha_grad); char new_name[20], end_name[10]; strcpy(new_name, "trayectoria_"); strcpy(end_name, ".dat"); strcat(new_name, name); strcat(new_name, end_name); //Definicion de nombre de archivo fileout = fopen(new_name, "w"); for(i=0;i<n_points;i++){ fprintf(fileout,"%f %f %f %f\n",t[i],x[i]/Rt,y[i]/Rt,z[i]/Rt); if(r[i]<=Rt){ break; } } //Impresion de datos de tiempo y posiciones en cada uno de los ejes, normalizada al radio terrestre fclose(fileout); double error; error=(vel[n_points-1]-vel[0])/vel[0]; return 0; }
int TestMHD(int argc, char *argv[]) { real cfl = 0.1; real tmax = 0.1; bool writemsh = false; real vmax = 6.0; bool usegpu = true; real dt = 0.0; real periodsize = 6.2831853; for (;;) { int cc = getopt(argc, argv, "c:t:w:D:P:g:s:"); if (cc == -1) break; switch (cc) { case 0: break; case 'c': cfl = atof(optarg); break; case 'g': usegpu = atoi(optarg); break; case 't': tmax = atof(optarg); break; case 'w': writemsh = true; break; case 'D': ndevice_cl= atoi(optarg); break; case 'P': nplatform_cl = atoi(optarg); break; default: printf("Error: invalid option.\n"); printf("Usage:\n"); printf("./testmanyv -c <cfl> -d <deg> -n <nraf> -t <tmax> -C\n -P <cl platform number> -D <cl device number> FIXME"); exit(1); } } bool test = true; field f; init_empty_field(&f); f.varindex = GenericVarindex; f.model.m = 9; f.model.cfl = cfl; strcpy(f.model.name,"MHD"); f.model.NumFlux=MHDNumFluxP2; f.model.BoundaryFlux=MHDBoundaryFlux; f.model.InitData=MHDInitData; f.model.ImposedData=MHDImposedData; char buf[1000]; sprintf(buf, "-D _M=%d -D _PERIODX=%f -D _PERIODY=%f", f.model.m, periodsize, periodsize); strcat(cl_buildoptions, buf); sprintf(numflux_cl_name, "%s", "MHDNumFluxP2"); sprintf(buf," -D NUMFLUX="); strcat(buf, numflux_cl_name); strcat(cl_buildoptions, buf); sprintf(buf, " -D BOUNDARYFLUX=%s", "MHDBoundaryFlux"); strcat(cl_buildoptions, buf); // Set the global parameters for the Vlasov equation f.interp.interp_param[0] = f.model.m; // _M f.interp.interp_param[1] = 1; // x direction degree f.interp.interp_param[2] = 1; // y direction degree f.interp.interp_param[3] = 0; // z direction degree f.interp.interp_param[4] = 4; // x direction refinement f.interp.interp_param[5] = 4; // y direction refinement f.interp.interp_param[6] = 1; // z direction refinement //set_vlasov_params(&(f.model)); // Read the gmsh file //ReadMacroMesh(&(f.macromesh), "test/testcartesiangrid2d2.msh"); ReadMacroMesh(&(f.macromesh), "../test/testOTgrid.msh"); //ReadMacroMesh(&(f.macromesh), "test/testcube.msh"); // Try to detect a 2d mesh Detect2DMacroMesh(&(f.macromesh)); bool is2d=f.macromesh.is2d; assert(is2d); f.macromesh.period[0]=periodsize; f.macromesh.period[1]=periodsize; // Mesh preparation BuildConnectivity(&(f.macromesh)); // Prepare the initial fields Initfield(&f); // Prudence... CheckMacroMesh(&(f.macromesh), f.interp.interp_param + 1); //Plotfield(0, (1==0), &f, "Rho", "dginit.msh"); f.vmax=vmax; real executiontime; if(usegpu) { printf("Using OpenCL:\n"); //executiontime = seconds(); //assert(1==2); RK4_CL(&f, tmax, dt, 0, NULL, NULL); CopyfieldtoCPU(&f); show_cl_timing(&f); //executiontime = seconds() - executiontime; show_cl_timing(&f); } else { printf("Using C:\n"); //executiontime = seconds(); RK4(&f, tmax, dt); //executiontime = seconds() - executiontime; } //Plotfield(0,false,&f, "Rho", "rho.msh"); //Plotfield(2,false,&f, "P", "p.msh"); //Gnuplot(&f,0,0.0,"data1D.dat"); printf("tmax: %f, cfl: %f\n", tmax, f.model.cfl); printf("deltax:\n"); printf("%f\n", f.hmin); printf("deltat:\n"); printf("%f\n", dt); printf("DOF:\n"); printf("%d\n", f.wsize); printf("executiontime (s):\n"); printf("%f\n", executiontime); printf("time per RK2 (s):\n"); printf("%f\n", executiontime / (real)f.itermax); return test; }