bool MaskedImage::advect(const VectorField2D & velocity, double deltaT, UArray<double> & inOutX, UArray<double> & inOutY, double errorTolerance, SInt32 maximumTimeStepCount) { if(deltaT == 0.0) return true; ParticleIntegrator integrator(velocity); double nextTimeStep = 0.1*deltaT; double minimumTimeStep = fabs(0.1*deltaT/maximumTimeStepCount); SInt32 imageSize = getXSize()*getYSize(); if(inOutX.getSize() != imageSize || inOutY.getSize() != imageSize) return false; SInt32 maxCount = 1000000; // keeps us from allocating too much memory at a time UArray<double> newData(imageSize); UArray<bool> newMask(imageSize); for(SInt32 imageIndex = 0; imageIndex < imageSize; imageIndex += maxCount) { SInt32 localCount = std::min(maxCount, imageSize-imageIndex); // set up the points, one for each output pixel UArray<double> points(2*localCount); for(SInt32 index = 0; index < localCount; index++) { points[2*index] = inOutX[index + imageIndex]; points[2*index+1] = inOutY[index + imageIndex]; } // integrate the pixels backward in time to their locations in the original image if(!integrator.integrate(points, deltaT, 0, errorTolerance, nextTimeStep, minimumTimeStep, maximumTimeStepCount)) return false; // interpolate the advected image at the points in the original image UArray<double> pixelX(localCount), pixelY(localCount), advectedPixels(localCount); UArray<bool> advectedMask(localCount); for(SInt32 index = 0; index < localCount; index++) { pixelX[index] = points[2*index]; pixelY[index] = points[2*index+1]; inOutX[index + imageIndex] = points[2*index]; inOutY[index + imageIndex] = points[2*index+1]; } maskedInterpolate(pixelX, pixelY, advectedPixels, advectedMask); // copy the advected pixels and mask back into this image for(SInt32 index = 0; index < localCount; index++) { newData[index + imageIndex] = advectedPixels[index]; newMask[index + imageIndex] = advectedMask[index]; } } getData().copy(newData); mask.copy(newMask); return true; }
void AdaptiveStepSizeIntegrator<DifferentialEquation>::Instance::WriteToMessage( not_null<serialization::IntegratorInstance*> message) const { Integrator<ODE>::Instance::WriteToMessage(message); auto* const extension = message->MutableExtension( serialization::AdaptiveStepSizeIntegratorInstance::extension); adaptive_step_size_.WriteToMessage(extension->mutable_adaptive_step_size()); integrator().WriteToMessage(extension->mutable_integrator()); }
/* >>> start tutorial code >>> */ int main( ){ USING_NAMESPACE_ACADO // DEFINE A RIGHT-HAND-SIDE: // ------------------------- DifferentialState x; AlgebraicState z; Parameter p,q; DifferentialEquation f; f << dot(x) == -p*x*x*z ; f << 0 == q*q - z*z; // DEFINE AN INTEGRATOR: // --------------------- IntegratorBDF integrator(f); integrator.set( INTEGRATOR_PRINTLEVEL, HIGH ); // DEFINE INITIAL VALUES: // ---------------------- double x0 = 1.0; double z0 = 1.000000; double pp[2] = { 1.0, 1.0 }; double t0 = 0.0 ; double tend = 0.2 ; // START THE INTEGRATION: // ---------------------- //integrator.freezeAll(); integrator.integrate( t0, tend, &x0, &z0, pp ); // GET THE RESULTS // --------------- VariablesGrid differentialStates; VariablesGrid algebraicStates ; integrator.getX ( differentialStates ); integrator.getXA( algebraicStates ); differentialStates.print( "x" ); algebraicStates.print( "z" ); return 0; }
void BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator3D( benchmark::State& state) { // NOLINT(runtime/references) Length q_error; Speed v_error; while (state.KeepRunning()) { SolveHarmonicOscillatorAndComputeError3D(state, q_error, v_error, integrator()); } std::stringstream ss; ss << q_error << ", " << v_error; state.SetLabel(ss.str()); }
void Cluster::update(const double timestep) { std::vector<State> newStates; for (const auto& p : particles) { auto accelFunc = std::bind(&Particle::findAcceleration, &p, std::placeholders::_1); newStates.push_back(integrator(accelFunc, p.pos, p.vel, timestep)); } for (size_t i = 0; i < particles.size(); i++) { particles.at(i).setState(newStates.at(i)); } }
/*[x dxdt]=integration_loop(tau, t, s_noise, Integr_Param,x0'); *prhs: tau, t, s_noise, Integr_Param,x0' (these are const (constant) and you cannot modify) *plhs: x, dxdt * The gateway function (this connects mex file to MATLAB) */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Retrieve the input data */ /* General form: type variablename = mxGetPr(prhs(index))*/ double tau = *(mxGetPr(prhs[0])); mexPrintf("tau = %f\n", tau); /* Print in command line to make sure that everything works OK */ double *t = mxGetPr(prhs[1]); mexPrintf("got t"); int iters=mxGetM(prhs[1]); mexPrintf("iters = %d\n", iters); double s_noise = *(mxGetPr(prhs[2])); mexPrintf("s_noise = %f\n", s_noise); /*Retrieve the integrator parameters: //Integr_Param={atol rtol};*/ mwIndex CellEllement; CellEllement=0; double abstol = *((double*)mxGetData(mxGetCell(prhs[3],CellEllement))); /* mxGetData(): This is to input a cell */ mexPrintf("abstol = %f\n", abstol); CellEllement=1; double reltol = *((double*)mxGetData(mxGetCell(prhs[3],CellEllement))); mexPrintf("reltol = %f\n", reltol); double *x0 = mxGetPr(prhs[4]); int D = mxGetM(prhs[4]); mexPrintf("D = %d\n", D); /* Prepare/define the output data */ /* Create a pointer to the output data */ plhs[0] = mxCreateDoubleMatrix(D, iters, mxREAL);/* This creates MATLAB variable/matrix variables in order to return/output them back to MATLAB */ double *x = mxGetPr(plhs[0]); printf("made x\n"); plhs[1] = mxCreateDoubleMatrix(D, iters, mxREAL); double *dxdt = mxGetPr(plhs[1]); printf("made dxdt\n"); /* Other internal C variables */ /*Generate and initialize the system's parameters structure*/ par params={D, tau}; /* Now the show begins in C. Call the function integrator() */ /* void integrator(function F, int D, void *params, double x[], double dxdt[], double x0[], double t[], int iters, double s_noise, double abstol, double reltol) */ integrator(System, D, ¶ms, x, dxdt, x0, t, iters, s_noise, abstol, reltol); printf("main loop done \n:"); }
void AgentCore::control() { Eigen::VectorXd stats_error = statsMsgToVector(target_statistics_) - statsMsgToVector(estimated_statistics_); // update non constant values of the jacobian of phi(p) = [px, py, pxx, pxy, pyy] jacob_phi_(2,0) = 2*pose_virtual_.position.x; jacob_phi_(3,0) = pose_virtual_.position.y; jacob_phi_(3,1) = pose_virtual_.position.x; jacob_phi_(4,1) = 2*pose_virtual_.position.y; // twist_virtual = inv(B + Jphi'*lambda*Jphi) * Jphi' * gamma * stats_error Eigen::VectorXd control_law = (b_ + jacob_phi_.transpose()*lambda_*jacob_phi_).inverse() *jacob_phi_.transpose()*gamma_*stats_error; // control command saturation double current_velocity_virtual = std::sqrt(std::pow(control_law(0),2) + std::pow(control_law(1),2)); if (current_velocity_virtual > velocity_virtual_threshold_) { control_law *= velocity_virtual_threshold_ / current_velocity_virtual; } geometry_msgs::Pose pose_old = pose_virtual_; pose_virtual_.position.x = integrator(pose_virtual_.position.x, twist_virtual_.linear.x, control_law(0), 1); pose_virtual_.position.y = integrator(pose_virtual_.position.y, twist_virtual_.linear.y, control_law(1), 1); setTheta(pose_virtual_.orientation, std::atan2(control_law(1), control_law(0))); twist_virtual_.linear.x = control_law(0); twist_virtual_.linear.y = control_law(1); std::stringstream s; s << "Statistics error (" << (Eigen::RowVectorXd)stats_error << ")."; console(__func__, s, DEBUG_V); s << "Control commands (" << (Eigen::RowVectorXd)control_law << ")."; console(__func__, s, DEBUG_VV); s << "Virtual pose (" << pose_virtual_.position.x << ", " << pose_virtual_.position.y << ")."; console(__func__, s, DEBUG_VVV); s << "Virtual twist (" << twist_virtual_.linear.x << ", " << twist_virtual_.linear.y << ")."; console(__func__, s, DEBUG_VVV); broadcastPose(pose_virtual_, agent_virtual_frame_); broadcastPath(pose_virtual_, pose_old, agent_virtual_frame_); }
void iterate(){ /* particles_add(); */ /* console(); */ integrator(); boundary(); collisions_search_direct(); t+=dt; if(t>100) exit(0); display(); }
Function simpleIntegrator(Function f, const std::string& plugin, const Dict& plugin_options) { // Consistency check casadi_assert_message(f.n_in()==2, "Function must have two inputs: x and p"); casadi_assert_message(f.n_out()==1, "Function must have one outputs: dot(x)"); // Sparsities Sparsity x_sp = f.sparsity_in(0); Sparsity p_sp = f.sparsity_in(1); // Wrapper function inputs MX x = MX::sym("x", x_sp); MX u = MX::sym("u", vertcat(Sparsity::scalar(), vec(p_sp))); // augment p with t // Normalized xdot int u_offset[] = {0, 1, 1+p_sp.size1()}; vector<MX> pp = vertsplit(u, vector<int>(u_offset, u_offset+3)); MX h = pp[0]; MX p = reshape(pp[1], p_sp.size()); MX f_in[] = {x, p}; MX xdot = f(vector<MX>(f_in, f_in+2)).at(0); xdot *= h; // Form DAE function MXDict dae = {{"x", x}, {"p", u}, {"ode", xdot}}; // Create integrator function Dict plugin_options2 = plugin_options; plugin_options2["t0"] = 0; // Normalized time plugin_options2["tf"] = 1; // Normalized time Function ifcn = integrator("integrator", plugin, dae, plugin_options2); // Inputs of constructed function MX x0 = MX::sym("x0", x_sp); p = MX::sym("p", p_sp); h = MX::sym("h"); // State at end MX xf = ifcn(MXDict{{"x0", x0}, {"p", vertcat(h, vec(p))}}).at("xf"); // Form discrete-time dynamics return Function("F", {x0, p, h}, {xf}, {"x0", "p", "h"}, {"xf"}); }
int MainApplication::run(int argc, char *argv[]) { Generator generator; uint structure = 0; uvec3 nUnitCells; vec3 unitCellSize; double interactionLength; nUnitCells << 12 << endr << 12 << endr << 12; double a = 5.72; // Angstrom unitCellSize << a << endr << a << endr << a; unitCellSize /= L0; // converting to MD units interactionLength = 3.0; // MD units State state = generator.createCrystal(structure, nUnitCells, unitCellSize, interactionLength); state.printInfo(); generator.saveStateBox(&state, "state-0000.xyz"); long idum = -1; double temperature = 5.0; // MD units generator.setTemperature(&state, temperature, &idum, 1); double dt = 0.005; // MD units Integrator integrator(&state); ostringstream filename; uint nCycles = 200; for (uint i = 1; i < 1+nCycles; i++) { cout << "Cycle " << i << " of " << nCycles << endl; integrator.stepForward(dt); filename.str(string()); filename << "./state-" << setfill('0') << setw(4) << i << ".xyz"; generator.saveStateBox(&state, filename.str()); } return 0; }
void iterate(){ /* printf("trees[0x10000].index_particle_first:%d\n",trees[0x10000].index_particle_first); */ /* particles_add(); */ /* console(); */ integrator(); boundary(); collisions_search_direct(); t+=dt; if(t>100) exit(0); display(); }
void createMagnet(){ TString angle[2]={"180","9.5"}; for(int i=1;i<2;i++){ VectorField *field=new VectorField(new BoreMap(angle[i].Atof())); FieldReader *reader=new FieldReader(field); for(float r=0;r<=7;r+=0.25){ TString file=Form("C:/Opera/tables/Magnet Rr=%1.2f th=%s.table",r,angle[i].Data()); cout<<"Reading from file "<<file<<endl; reader->read(file); } cout<<"Saving magnetic field"<<endl; field->save("C:/Opera/tables/magnet.root",Form("bfield-%s",angle[i].Data())); cout<<"Calculating potential"<<endl; BoreInt integrator(field,angle[i].Atof()); integrator.integrate(); ScalarField *pot=integrator.getPotential(); cout<<"Saving scalar potential"<<endl; pot->save("C:/Opera/tables/magnet.root",Form("potential-%s",angle[i].Data())); delete reader; delete field; delete pot; } }
/* >>> start tutorial code >>> */ int main( ){ // DEFINE VARIABLES: // ---------------------- DifferentialState x; DifferentialEquation f; f << dot(x) == -x*x; TaylorModel<Interval> Mod( 1, 1 ); Tmatrix<T> x0(1); x0(0) = T( &Mod, 0, Interval(0.99,1.0)); EllipsoidalIntegrator integrator( f, 4 ); integrator.set(INTEGRATOR_PRINTLEVEL, HIGH ); integrator.set(INTEGRATOR_TOLERANCE, 1e-4 ); integrator.set(ABSOLUTE_TOLERANCE, 1e-4 ); integrator.integrate( 0.0, 5.0, &x0 ); return 0; }
void anteriorTibialLoadsFD(Model& model, double knee_angle) { addTibialLoads(model, knee_angle); // init system std::time_t result = std::time(nullptr); std::cout << "\nBefore initSystem() " << std::asctime(std::localtime(&result)) << endl; SimTK::State& si = model.initSystem(); result = std::time(nullptr); std::cout << "\nAfter initSystem() " << std::asctime(std::localtime(&result)) << endl; // set gravity model.updGravityForce().setGravityVector(si, Vec3(0,0,0)); setKneeAngle(model, si, knee_angle, true, true); //setATT(model,si, knee_angle); // disable muscles //string muscle_name; //for (int i=0; i<model.getActuators().getSize(); i++) //{ // muscle_name = model.getActuators().get(i).getName(); // model.getActuators().get(i).setDisabled(si, true); //if (muscle_name == "bifemlh_r" || muscle_name == "bifemsh_r" || muscle_name == "grac_r" \ // || muscle_name == "lat_gas_r" || muscle_name == "med_gas_r" || muscle_name == "sar_r" \ // || muscle_name == "semimem_r" || muscle_name == "semiten_r" \ // || muscle_name == "rect_fem_r" || muscle_name == "vas_med_r" || muscle_name == "vas_int_r" || muscle_name == "vas_lat_r" ) // model.getActuators().get(i).setDisabled(si, false); //} model.equilibrateMuscles( si); // Add reporters ForceReporter* forceReporter = new ForceReporter(&model); model.addAnalysis(forceReporter); CustomAnalysis* customReporter = new CustomAnalysis(&model, "r"); model.addAnalysis(customReporter); // Create the integrator and manager for the simulation. SimTK::RungeKuttaMersonIntegrator integrator(model.getMultibodySystem()); //SimTK::CPodesIntegrator integrator(model.getMultibodySystem()); //integrator.setAccuracy(1.0e-3); //integrator.setFixedStepSize(0.001); Manager manager(model, integrator); // Define the initial and final simulation times double initialTime = 0.0; double finalTime = 1.0; // Integrate from initial time to final time manager.setInitialTime(initialTime); manager.setFinalTime(finalTime); std::cout<<"\n\nIntegrating from "<<initialTime<<" to " <<finalTime<<std::endl; result = std::time(nullptr); std::cout << "\nBefore integrate(si) " << std::asctime(std::localtime(&result)) << endl; manager.integrate(si); result = std::time(nullptr); std::cout << "\nAfter integrate(si) " << std::asctime(std::localtime(&result)) << endl; // Save the simulation results //osimModel.updAnalysisSet().adoptAndAppend(forces); Storage statesDegrees(manager.getStateStorage()); statesDegrees.print("../outputs/states_ant_load_" + changeToString(abs(knee_angle)) +".sto"); model.updSimbodyEngine().convertRadiansToDegrees(statesDegrees); statesDegrees.setWriteSIMMHeader(true); statesDegrees.print("../outputs/states_degrees_ant_load_" + changeToString(abs(knee_angle)) +".mot"); // force reporter results model.updAnalysisSet().adoptAndAppend(forceReporter); forceReporter->getForceStorage().print("../outputs/force_reporter_ant_load_" + changeToString(abs(knee_angle)) +".mot"); customReporter->print( "../outputs/custom_reporter_ant_load_" + changeToString(abs(knee_angle)) +".mot"); model.removeAnalysis(forceReporter); model.removeAnalysis(customReporter); }
int main( ){ // Define a Right-Hand-Side: // ------------------------- DifferentialState x("", 4, 1), P("", 4, 4); Control u("", 2, 1); IntermediateState rhs = cstrModel( x, u ); DMatrix Q = zeros<double>(4,4); Q(0,0) = 0.2; Q(1,1) = 1.0; Q(2,2) = 0.5; Q(3,3) = 0.2; DMatrix R = zeros<double>(2,2); R(0,0) = 0.5; R(1,1) = 5e-7; DifferentialEquation f; f << dot(x) == rhs; f << dot(P) == getRiccatiODE( rhs, x, u, P, Q, R ); // Define an integrator: // --------------------- IntegratorRK45 integrator( f ); integrator.set( INTEGRATOR_PRINTLEVEL, MEDIUM ); integrator.set( PRINT_INTEGRATOR_PROFILE, YES ); // Define an initial value: // ------------------------ //double x_ss[4] = { 2.14, 1.09, 114.2, 112.9 }; double x_start[20] = { 1.0, 0.5, 100.0, 100.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; double u_start[2] = { 14.19, -1113.5 }; // double u_start[2] = { 10.00, -7000.0 }; Grid timeInterval( 0.0, 5000.0, 100 ); integrator.freezeAll(); integrator.integrate( timeInterval, x_start, 0 ,0, u_start ); // GET THE RESULTS // --------------- VariablesGrid differentialStates; integrator.getX( differentialStates ); DVector PP = differentialStates.getLastVector(); DMatrix PPP(4,4); for( int i=0; i<4; ++i ) for( int j=0; j<4; ++j ) PPP(i,j) = PP(4+i*4+j); PPP.print( "P1.txt","",PS_PLAIN ); // PPP.printToFile( "P2.txt","",PS_PLAIN ); GnuplotWindow window; window.addSubplot( differentialStates(0), "cA [mol/l]" ); window.addSubplot( differentialStates(1), "cB [mol/l]" ); window.addSubplot( differentialStates(2), "theta [C]" ); window.addSubplot( differentialStates(3), "thetaK [C]" ); window.addSubplot( differentialStates(4 ), "P11" ); window.addSubplot( differentialStates(9 ), "P22" ); window.addSubplot( differentialStates(14), "P33" ); window.addSubplot( differentialStates(19), "P44" ); window.plot(); return 0; }
int main( ){ USING_NAMESPACE_ACADO // Define a Right-Hand-Side: // ------------------------- DifferentialState phi; // the angle phi DifferentialState dphi; // the first derivative of phi w.r.t time Control F; // a force acting on the pendulum Parameter l; // the length of the pendulum const double m = 1.0 ; // the mass of the pendulum const double g = 9.81 ; // the gravitational constant const double alpha = 2.0 ; // frictional constant IntermediateState z; DifferentialEquation f; z = sin(phi); f << dot(phi ) == dphi; f << dot(dphi) == -(m*g/l)*z - alpha*dphi + F/(m*l); // DEFINE AN INTEGRATOR: // --------------------- IntegratorRK45 integrator( f ); integrator.set( INTEGRATOR_PRINTLEVEL, HIGH ); integrator.set( INTEGRATOR_TOLERANCE, 1.0e-6 ); // DEFINE INITIAL VALUES: // ---------------------- double x_start[2] = { 1.0, 0.0 }; double u [1] = { 0.0 }; double p [1] = { 1.0 }; double t_start = 0.0 ; double t_end = 2.0 ; // START THE INTEGRATION: // ---------------------- //integrator.freezeAll(); integrator.integrate( t_start, t_end, x_start, 0, p, u ); // GET THE RESULTS // --------------- VariablesGrid differentialStates; integrator.getX( differentialStates ); differentialStates.print( "x" ); return 0; }
TEST(TestGenAlpha, SingleDOFa) { SIM1DOF simulator(new Problem()); GenAlpha integrator(simulator,false); runSingleDof(simulator,integrator,0.02); }
int main( ){ USING_NAMESPACE_ACADO // Define a Right-Hand-Side: // ------------------------- DifferentialState x, y; DifferentialEquation f; f << dot(x) == y; f << dot(y) == -x; // Define an integrator: // --------------------- IntegratorRK45 integrator( f ); integrator.set( INTEGRATOR_PRINTLEVEL, MEDIUM ); integrator.set( PRINT_INTEGRATOR_PROFILE, YES ); // Define an initial value: // ------------------------ double x_start[2] = { 0.0, 1.0 }; Grid timeInterval( 0.0, 2.0*M_PI, 100 ); integrator.freezeAll(); integrator.integrate( timeInterval, x_start ); // GET THE RESULTS // --------------- VariablesGrid differentialStates; integrator.getX( differentialStates ); GnuplotWindow window; window.addSubplot( differentialStates(0) ); window.addSubplot( differentialStates(1) ); window.plot(); // Vector seed(2); // // seed( 0 ) = 1.0; // seed( 1 ) = 0.0; // // integrator.setForwardSeed( 1, seed ); // integrator.integrateSensitivities(); // // VariablesGrid sens; // integrator.getForwardSensitivities( sens, 1 ); // // GnuplotWindow window2; // window2.addSubplot( sens(0) ); // window2.addSubplot( sens(1) ); // window2.plot(); return 0; }
int main(int argc, char **argv) { // nspluginviewer is a helper app, it shouldn't do session management at all setenv("SESSION_MANAGER", "", 1); // trap X errors kdDebug(1430) << "1 - XSetErrorHandler" << endl; XSetErrorHandler(x_errhandler); setvbuf(stderr, NULL, _IONBF, 0); kdDebug(1430) << "2 - parseCommandLine" << endl; parseCommandLine(argc, argv); #if QT_VERSION < 0x030100 // Create application kdDebug(1430) << "3 - XtToolkitInitialize" << endl; XtToolkitInitialize(); g_appcon = XtCreateApplicationContext(); Display *dpy = XtOpenDisplay(g_appcon, NULL, "nspluginviewer", "nspluginviewer", 0, 0, &argc, argv); _notifiers[0].setAutoDelete(TRUE); _notifiers[1].setAutoDelete(TRUE); _notifiers[2].setAutoDelete(TRUE); kdDebug(1430) << "4 - KXtApplication app" << endl; KLocale::setMainCatalogue("nsplugin"); KXtApplication app(dpy, argc, argv, "nspluginviewer"); #else kdDebug(1430) << "3 - create QXtEventLoop" << endl; QXtEventLoop integrator("nspluginviewer"); parseCommandLine(argc, argv); KLocale::setMainCatalogue("nsplugin"); kdDebug(1430) << "4 - create KApplication" << endl; KApplication app(argc, argv, "nspluginviewer"); GlibEvents glibevents; #endif { KConfig cfg("kcmnspluginrc", true); cfg.setGroup("Misc"); int v = KCLAMP(cfg.readNumEntry("Nice Level", 0), 0, 19); if(v > 0) { nice(v); } v = cfg.readNumEntry("Max Memory", 0); if(v > 0) { rlimit rl; memset(&rl, 0, sizeof(rl)); if(0 == getrlimit(RLIMIT_AS, &rl)) { rl.rlim_cur = kMin(v, int(rl.rlim_max)); setrlimit(RLIMIT_AS, &rl); } } } // initialize the dcop client kdDebug(1430) << "5 - app.dcopClient" << endl; DCOPClient *dcop = app.dcopClient(); if(!dcop->attach()) { KMessageBox::error(NULL, i18n("There was an error connecting to the Desktop " "communications server. Please make sure that " "the 'dcopserver' process has been started, and " "then try again."), i18n("Error Connecting to DCOP Server")); exit(1); } kdDebug(1430) << "6 - dcop->registerAs" << endl; if(g_dcopId) g_dcopId = dcop->registerAs(g_dcopId, false); else g_dcopId = dcop->registerAs("nspluginviewer"); dcop->setNotifications(true); // create dcop interface kdDebug(1430) << "7 - new NSPluginViewer" << endl; NSPluginViewer *viewer = new NSPluginViewer("viewer", 0); // start main loop #if QT_VERSION < 0x030100 kdDebug(1430) << "8 - XtAppProcessEvent" << endl; while(!g_quit) XtAppProcessEvent(g_appcon, XtIMAll); #else kdDebug(1430) << "8 - app.exec()" << endl; app.exec(); #endif // delete viewer delete viewer; }
int main( ){ DifferentialState phi, dphi; Control u; Parameter p; TIME t; IntermediateState x(5); x(0) = t ; x(1) = phi ; x(2) = dphi; x(3) = u ; x(4) = p ; CFunction pendulumModel( 2, ffcn_model ); // Define a Right-Hand-Side: // ------------------------- DifferentialEquation f; f << pendulumModel(x); // DEFINE AN INTEGRATOR: // --------------------- IntegratorRK45 integrator( f ); integrator.set(INTEGRATOR_PRINTLEVEL, HIGH ); // DEFINE INITIAL VALUES: // ---------------------- double x_start[2] = { 0.0, 0.0 }; double u_ [1] = { 1.0 }; double p_ [1] = { 1.0 }; double t_start = 0.0; double t_end = 1.0; // START THE INTEGRATION: // ---------------------- integrator.freezeAll(); integrator.integrate( t_start, t_end, x_start, 0, p_, u_ ); // DEFINE A SEED MATRIX: // --------------------- Vector seed1(2); Vector seed2(2); seed1(0) = 1.0; seed1(1) = 0.0; seed2(0) = 1.0; seed2(1) = 0.0; // COMPUTE FIRST ORDER DERIVATIVES: // -------------------------------- integrator.setForwardSeed(1,seed1); integrator.integrateSensitivities(); // COMPUTE SECOND ORDER DERIVATIVES: // --------------------------------- integrator.setForwardSeed(2,seed2); integrator.integrateSensitivities(); // GET THE RESULTS // --------------- VariablesGrid differentialStates; integrator.getX( differentialStates ); Vector Dx( 2 ), DDx( 2 ); integrator.getForwardSensitivities( Dx,1 ); integrator.getForwardSensitivities( DDx,2 ); differentialStates.print( "x" ); Dx.print( "Dx" ); DDx.print( "DDx" ); return 0; }
int main(int argc, char **argv) { // The name of the configuration file std::string strConfigurationFilename; std::vector<MolDyn::Component<real> > components; real simBoxLength; /* Command line initialization */ if (argc < 3) { std::cout << "Usage is moldyn -i <config filename>" << std::endl; return 0; } for (int i = 1; i < argc; ++i) { if (i + 1 != argc) { if (std::string(argv[i]).compare("-i") == 0) { strConfigurationFilename = argv[i + 1]; } } } if (strConfigurationFilename.length() < 3) { std::cout << "No input files found." << std::endl; std::cout << "Usage is moldyn -i <config filename>" << std::endl; return 0; } MolDyn::Configuration<real> config(strConfigurationFilename); MolDyn::Output<real> output(config); std::cout << "----------- VARIABLES IN FILE ------------- " << std::endl; std::cout << "Number of particles: " << config.totalParticles << std::endl; std::cout << "LJCUT: " << config.LJCutoff << std::endl; std::cout << "Temperature (K): " << config.temperature << std::endl; std::cout << "dt (ps): " << config.dt << std::endl; std::cout << "Equilibration steps: " << config.equilibrationSteps << std::endl; std::cout << "Production steps: " << config.productionSteps << std::endl; std::cout << "Energy interval (steps): " << config.energyInterval << std::endl; std::cout << "Tape interval (steps): " << config.tapeInterval << std::endl; std::cout << "Animation interval (steps): " << config.animationInterval << std::endl; std::cout << "Number of species: " << config.maxComponents << std::endl; for (unsigned int i = 0; i < config.maxComponents; ++i) { std::cout << "Component " << i + 1 << " out of " << config.maxComponents; std::cout << std::endl; std::cout << "Sigma (A): " << config.components[i].sigma << std::endl; std::cout << "Epsilon/KB: " << config.components[i].epsilonKB << std::endl; std::cout << "Epsilon: " << config.components[i].epsilon << std::endl; std::cout << "Mass (amu): " << config.components[i].mass << std::endl; std::cout << "Density (gm/cm3): " << config.components[i].densityGCM << std::endl; std::cout << "Density (particles/A3): " << config.components[i].density << std::endl; } simBoxLength = MolDyn::getSimBoxLength(config.components); MolDyn::MixedLJPotential<real> potential(config.maxComponents, config.LJCutoff); for (unsigned int i = 0; i < config.maxComponents; ++i) { potential.addComponent(config.components[i]); } MolDyn::VelocityVerlet<real> integrator(potential, config.maxComponents, config.dt); for (unsigned int i = 0; i < config.maxComponents; ++i) { integrator.addSpecies(config.components[i]); } MolDyn::SimulationBox<real> simulationBox(config.totalParticles, integrator, config.temperature, simBoxLength, config.sigmaCut, config.maxComponents); for (unsigned int i = 0; i < config.maxComponents; ++i) { simulationBox.addComponent(config.components[i]); } simulationBox.initialize(); std::cout << "STARTING EQUILIBRATION RUN" << std::endl; for (unsigned int i = 0; i < config.equilibrationSteps; ++i) { simulationBox.step(true); if ((i + 1) % 1000 == 0) { std::cout << "Equilibration step " << i + 1 << std::endl; } output.write(simulationBox, i, true); } std::cout << "EQUILIBRATION OVER" << std::endl; std::cout << "STARTING PRODUCTION RUN" << std::endl; for (unsigned int i = 0; i < config.productionSteps; ++i) { simulationBox.step(false); if ((i + 1) % 1000 == 0) { std::cout << "Production step " << i + 1 << std::endl; } output.write(simulationBox, i + config.equilibrationSteps, false); } // end for std::cout << "PRODUCTION OVER" << std::endl; }
TEST(TestNewmark, Prescribed) { SIM2DOF simulator(new Problem()); Newmark integrator(simulator,true); runPrescribed(simulator,integrator); }
TEST(TestNewmark, SingleDOFu) { SIM1DOF simulator(new Problem()); Newmark integrator(simulator,true); runSingleDof(simulator,integrator); }
void flexionFDSimulation(Model& model) { addFlexionController(model); //addExtensionController(model); // init system std::time_t result = std::time(nullptr); std::cout << "\nBefore initSystem() " << std::asctime(std::localtime(&result)) << endl; SimTK::State& si = model.initSystem(); result = std::time(nullptr); std::cout << "\nAfter initSystem() " << std::asctime(std::localtime(&result)) << endl; // set gravity model.updGravityForce().setGravityVector(si, Vec3(-9.80665,0,0)); //model.updGravityForce().setGravityVector(si, Vec3(0,0,0)); setHipAngle(model, si, 90); setKneeAngle(model, si, 0, false, false); model.equilibrateMuscles( si); // Add reporters ForceReporter* forceReporter = new ForceReporter(&model); model.addAnalysis(forceReporter); CustomAnalysis* customReporter = new CustomAnalysis(&model, "r"); model.addAnalysis(customReporter); // Create the integrator and manager for the simulation. SimTK::RungeKuttaMersonIntegrator integrator(model.getMultibodySystem()); //SimTK::CPodesIntegrator integrator(model.getMultibodySystem()); //integrator.setAccuracy(.01); //integrator.setAccuracy(1e-3); //integrator.setFixedStepSize(0.001); Manager manager(model, integrator); // Define the initial and final simulation times double initialTime = 0.0; double finalTime = 0.2; // Integrate from initial time to final time manager.setInitialTime(initialTime); manager.setFinalTime(finalTime); std::cout<<"\n\nIntegrating from "<<initialTime<<" to " <<finalTime<<std::endl; result = std::time(nullptr); std::cout << "\nBefore integrate(si) " << std::asctime(std::localtime(&result)) << endl; manager.integrate(si); result = std::time(nullptr); std::cout << "\nAfter integrate(si) " << std::asctime(std::localtime(&result)) << endl; // Save the simulation results Storage statesDegrees(manager.getStateStorage()); statesDegrees.print("../outputs/states_flex.sto"); model.updSimbodyEngine().convertRadiansToDegrees(statesDegrees); statesDegrees.setWriteSIMMHeader(true); statesDegrees.print("../outputs/states_degrees_flex.mot"); // force reporter results forceReporter->getForceStorage().print("../outputs/force_reporter_flex.mot"); customReporter->print( "../outputs/custom_reporter_flex.mot"); }
void flexionFDSimulationWithHitMap(Model& model) { addFlexionController(model); //addExtensionController(model); //addTibialLoads(model, 0); model.setUseVisualizer(true); // init system std::time_t result = std::time(nullptr); std::cout << "\nBefore initSystem() " << std::asctime(std::localtime(&result)) << endl; SimTK::State& si = model.initSystem(); result = std::time(nullptr); std::cout << "\nAfter initSystem() " << std::asctime(std::localtime(&result)) << endl; // set gravity //model.updGravityForce().setGravityVector(si, Vec3(-9.80665,0,0)); //model.updGravityForce().setGravityVector(si, Vec3(0,0,0)); //setHipAngle(model, si, 90); //setKneeAngle(model, si, 0, false, false); //model.equilibrateMuscles( si); MultibodySystem& system = model.updMultibodySystem(); SimbodyMatterSubsystem& matter = system.updMatterSubsystem(); GeneralForceSubsystem forces(system); ContactTrackerSubsystem tracker(system); CompliantContactSubsystem contactForces(system, tracker); contactForces.setTrackDissipatedEnergy(true); //contactForces.setTransitionVelocity(1e-3); for (int i=0; i < matter.getNumBodies(); ++i) { MobilizedBodyIndex mbx(i); if (i==19 || i==20 || i==22)// || i==15 || i==16) { MobilizedBody& mobod = matter.updMobilizedBody(mbx); std::filebuf fb; //cout << mobod.updBody(). if (i==19) fb.open ( "../resources/femur_lat_r.obj",std::ios::in); else if (i==20) fb.open ( "../resources/femur_med_r.obj",std::ios::in); else if (i==22) fb.open ( "../resources/tibia_upper_r.obj",std::ios::in); //else if (i==15) //fb.open ( "../resources/meniscus_lat_r.obj",std::ios::in); //else if (i==16) //fb.open ( "../resources/meniscus_med_r.obj",std::ios::in); std::istream is(&fb); PolygonalMesh polMesh; polMesh.loadObjFile(is); fb.close(); SimTK::ContactGeometry::TriangleMesh mesh(polMesh); ContactSurface contSurf;//(mesh, ContactMaterial(1.0e6, 1, 1, 0.03, 0.03), 0.001); if (i==19 || i==20 || i==22) contSurf = ContactSurface(mesh, ContactMaterial(10, 1, 1, 0.03, 0.03), 0.001); //else if (i==15 || i==16) //contSurf = ContactSurface(mesh, ContactMaterial(10, 3, 1, 0.03, 0.03), 0.001); DecorativeMesh showMesh(mesh.createPolygonalMesh()); showMesh.setOpacity(0.5); mobod.updBody().addDecoration( showMesh); mobod.updBody().addContactSurface(contSurf); } } ModelVisualizer& viz(model.updVisualizer()); //Visualizer viz(system); viz.updSimbodyVisualizer().addDecorationGenerator(new HitMapGenerator(system,contactForces)); viz.updSimbodyVisualizer().setMode(Visualizer::RealTime); viz.updSimbodyVisualizer().setDesiredBufferLengthInSec(1); viz.updSimbodyVisualizer().setDesiredFrameRate(30); viz.updSimbodyVisualizer().setGroundHeight(-3); viz.updSimbodyVisualizer().setShowShadows(true); Visualizer::InputSilo* silo = new Visualizer::InputSilo(); viz.updSimbodyVisualizer().addInputListener(silo); Array_<std::pair<String,int> > runMenuItems; runMenuItems.push_back(std::make_pair("Go", GoItem)); runMenuItems.push_back(std::make_pair("Replay", ReplayItem)); runMenuItems.push_back(std::make_pair("Quit", QuitItem)); viz.updSimbodyVisualizer().addMenu("Run", RunMenuId, runMenuItems); Array_<std::pair<String,int> > helpMenuItems; helpMenuItems.push_back(std::make_pair("TBD - Sorry!", 1)); viz.updSimbodyVisualizer().addMenu("Help", HelpMenuId, helpMenuItems); system.addEventReporter(new MyReporter(system,contactForces,ReportInterval)); //system.addEventReporter(new Visualizer::Reporter(viz.updSimbodyVisualizer(), ReportInterval)); // Check for a Run->Quit menu pick every <x> second. system.addEventHandler(new UserInputHandler(*silo, 0.001)); system.realizeTopology(); //Show ContactSurfaceIndex for each contact surface // for (int i=0; i < matter.getNumBodies(); ++i) { //MobilizedBodyIndex mbx(i); // const MobilizedBody& mobod = matter.getMobilizedBody(mbx); // const int nsurfs = mobod.getBody().getNumContactSurfaces(); //printf("mobod %d has %d contact surfaces\n", (int)mbx, nsurfs); ////cout << "mobod with mass: " << (float)mobod.getBodyMass(si) << " has " << nsurfs << " contact surfaces" << endl; // //for (int i=0; i<nsurfs; ++i) { // //printf("%2d: index %d\n", i, // //(int)tracker.getContactSurfaceIndex(mbx,i)); // //} // } //cout << "tracker num of surfaces: " << tracker.getNumSurfaces() << endl; //State state = system.getDefaultState(); //viz.report(state); State& state = model.initializeState(); viz.updSimbodyVisualizer().report(state); // Add reporters ForceReporter* forceReporter = new ForceReporter(&model); model.addAnalysis(forceReporter); CustomAnalysis* customReporter = new CustomAnalysis(&model, "r"); model.addAnalysis(customReporter); // Create the integrator and manager for the simulation. SimTK::RungeKuttaMersonIntegrator integrator(model.getMultibodySystem()); //SimTK::CPodesIntegrator integrator(model.getMultibodySystem()); //integrator.setAccuracy(.01); //integrator.setAccuracy(1e-3); //integrator.setFixedStepSize(0.001); Manager manager(model, integrator); // Define the initial and final simulation times double initialTime = 0.0; double finalTime = 0.2; // Integrate from initial time to final time manager.setInitialTime(initialTime); manager.setFinalTime(finalTime); std::cout<<"\n\nIntegrating from "<<initialTime<<" to " <<finalTime<<std::endl; result = std::time(nullptr); std::cout << "\nBefore integrate(si) " << std::asctime(std::localtime(&result)) << endl; manager.integrate(state); result = std::time(nullptr); std::cout << "\nAfter integrate(si) " << std::asctime(std::localtime(&result)) << endl; // Save the simulation results Storage statesDegrees(manager.getStateStorage()); statesDegrees.print("../outputs/states_flex.sto"); model.updSimbodyEngine().convertRadiansToDegrees(statesDegrees); statesDegrees.setWriteSIMMHeader(true); statesDegrees.print("../outputs/states_degrees_flex.mot"); // force reporter results forceReporter->getForceStorage().print("../outputs/force_reporter_flex.mot"); //customReporter->print( "../outputs/custom_reporter_flex.mot"); //cout << "You can choose 'Replay'" << endl; int menuId, item; unsigned int frameRate = 5; do { cout << "Please choose 'Replay' or 'Quit'" << endl; viz.updInputSilo().waitForMenuPick(menuId, item); if (item != ReplayItem && item != QuitItem) cout << "\aDude... follow instructions!\n"; if (item == ReplayItem) { cout << "Type desired frame rate (integer) for playback and press Enter (default = 1) : "; //frameRate = cin.get(); cin >> frameRate; if (cin.fail()) { cout << "Not an int. Setting default frame rate." << endl; cin.clear(); cin.ignore(std::numeric_limits<int>::max(),'\n'); frameRate = 1; } //cout << "saveEm size: " << saveEm.size() << endl; for (unsigned int i=0; i<saveEm.size(); i++) { viz.updSimbodyVisualizer().drawFrameNow(saveEm.getElt(i)); if (frameRate == 0) frameRate = 1; usleep(1000000/frameRate); } } } while (menuId != RunMenuId || item != QuitItem); }
/** * Make sure random numbers are computed correctly when steps get merged. */ void testMergedRandoms() { const int numParticles = 10; const int numSteps = 10; System system; for (int i = 0; i < numParticles; i++) system.addParticle(1.0); CustomIntegrator integrator(0.1); integrator.addPerDofVariable("dofUniform1", 0); integrator.addPerDofVariable("dofUniform2", 0); integrator.addPerDofVariable("dofGaussian1", 0); integrator.addPerDofVariable("dofGaussian2", 0); integrator.addGlobalVariable("globalUniform1", 0); integrator.addGlobalVariable("globalUniform2", 0); integrator.addGlobalVariable("globalGaussian1", 0); integrator.addGlobalVariable("globalGaussian2", 0); integrator.addComputePerDof("dofUniform1", "uniform"); integrator.addComputePerDof("dofUniform2", "uniform"); integrator.addComputePerDof("dofGaussian1", "gaussian"); integrator.addComputePerDof("dofGaussian2", "gaussian"); integrator.addComputeGlobal("globalUniform1", "uniform"); integrator.addComputeGlobal("globalUniform2", "uniform"); integrator.addComputeGlobal("globalGaussian1", "gaussian"); integrator.addComputeGlobal("globalGaussian2", "gaussian"); Context context(system, integrator, platform); // See if the random numbers are computed correctly. vector<Vec3> values1, values2; for (int i = 0; i < numSteps; i++) { integrator.step(1); integrator.getPerDofVariable(0, values1); integrator.getPerDofVariable(1, values2); for (int i = 0; i < numParticles; i++) for (int j = 0; j < 3; j++) { double v1 = values1[i][j]; double v2 = values2[i][j]; ASSERT(v1 >= 0 && v1 < 1); ASSERT(v2 >= 0 && v2 < 1); ASSERT(v1 != v2); } integrator.getPerDofVariable(2, values1); integrator.getPerDofVariable(3, values2); for (int i = 0; i < numParticles; i++) for (int j = 0; j < 3; j++) { double v1 = values1[i][j]; double v2 = values2[i][j]; ASSERT(v1 >= -10 && v1 < 10); ASSERT(v2 >= -10 && v2 < 10); ASSERT(v1 != v2); } double v1 = integrator.getGlobalVariable(0); double v2 = integrator.getGlobalVariable(1); ASSERT(v1 >= 0 && v1 < 1); ASSERT(v2 >= 0 && v2 < 1); ASSERT(v1 != v2); v1 = integrator.getGlobalVariable(2); v2 = integrator.getGlobalVariable(3); ASSERT(v1 >= -10 && v1 < 10); ASSERT(v2 >= -10 && v2 < 10); ASSERT(v1 != v2); } }
int main( ){ USING_NAMESPACE_ACADO // DEFINE THE RIGHT-HAND-SIDE // OF A DOUBLE PENDULUM: // --------------------------- DifferentialState y1; DifferentialState y2; DifferentialState y3; DifferentialStateDerivative dy1; DifferentialStateDerivative dy2; DifferentialStateDerivative dy3; Parameter p1; Parameter p2; Parameter p3; DifferentialEquation f; f << dy1 + p1*y1 - p2*y2*y3 ; f << dy2 - p1*y1 + p2*y2*y3 + p3*y2*y2 ; f << dy3 - p3*y2*y2 ; // DEFINE AN INTEGRATOR: // --------------------- IntegratorBDF integrator(f); integrator.set(INTEGRATOR_PRINTLEVEL, MEDIUM ); integrator.set(INTEGRATOR_TOLERANCE, 1e-5 ); integrator.set(ABSOLUTE_TOLERANCE, 1e-6 ); integrator.set(MAX_NUM_INTEGRATOR_STEPS, 2000 ); // integrator.set(MAX_INTEGRATOR_STEPSIZE, 1e-3 ); integrator.set( LINEAR_ALGEBRA_SOLVER , SPARSE_LU ); // DEFINE INITIAL VALUES: // ---------------------- double x0[3] = { 1.0, 0.0, 0.0 }; double pp[3] = { 0.04, 1e+4, 3e+7 }; double t0 = 0.0 ; double tend = 4e9; // START THE INTEGRATION: // ---------------------- // double a = acadoGetTime(); //integrator.freezeAll(); integrator.integrate( t0, tend, x0, 0, pp ); // printf("%.16e \n", acadoGetTime() - a ); // GET THE RESULTS // --------------- VariablesGrid differentialStates; integrator.getX( differentialStates ); differentialStates.print( "x" ); return 0; }
TEST(TestControlBerendsenBins,SingleBin){ std::ifstream file("../foam-1728.json"); if(!file.is_open()){ std::cout<<"File not found"<<std::endl; exit(0); } std::string jsonstr; std::string line; while (!file.eof()) { getline(file, line); jsonstr += line; } file.close(); rapidjson::Document document; if(document.Parse<0>(jsonstr.c_str()).HasParseError()){ std::cout<<"Parsing error "<<std::endl; exit(0); } const double stepSizeInFs = document["StepSizeInFs"].GetDouble(); const int numParticles = document["NumberAtoms"].GetInt(); std::string equationStr = document["Equation"].GetString(); const double rCut = document["rCut"].GetDouble(); const rapidjson::Value& b = document["Boxsize"]; double bx = b[(rapidjson::SizeType)0].GetDouble(); double by = b[(rapidjson::SizeType)1].GetDouble(); double bz = b[(rapidjson::SizeType)2].GetDouble(); int numSpecies = document["NumberSpecies"].GetInt(); std::vector<OpenMM::Vec3> posInNm; std::vector<OpenMM::Vec3> velInNm; OpenMM::Platform::loadPluginsFromDirectory( OpenMM::Platform::getDefaultPluginsDirectory()); OpenMM::System system; //add particles to the system by reading from json file system.setDefaultPeriodicBoxVectors(OpenMM::Vec3(bx,0,0),OpenMM::Vec3(0,by,0),OpenMM::Vec3(0,0,bz)); const rapidjson::Value& mass = document["masses"]; const rapidjson::Value& pos = document["Positions"]; const rapidjson::Value& vel = document["Velocities"]; posInNm.clear(); velInNm.clear(); for(rapidjson::SizeType m=0;m<mass.Size();m++){ double tm = mass[(rapidjson::SizeType) m].GetDouble(); system.addParticle(tm); posInNm.push_back(OpenMM::Vec3(pos[(rapidjson::SizeType) m]["0"].GetDouble(), pos[(rapidjson::SizeType) m]["1"].GetDouble(), pos[(rapidjson::SizeType) m]["2"].GetDouble() )); velInNm.push_back(OpenMM::Vec3(vel[(rapidjson::SizeType) m]["0"].GetDouble(), vel[(rapidjson::SizeType) m]["1"].GetDouble(), vel[(rapidjson::SizeType) m]["2"].GetDouble() )); } std::cout<<"Initialized System with "<<system.getNumParticles()<<" Particles."<<std::endl; OpenMM::CustomNonbondedForce* nonbonded = new OpenMM::CustomNonbondedForce(equationStr); nonbonded->setNonbondedMethod(OpenMM::CustomNonbondedForce::CutoffPeriodic); nonbonded->setCutoffDistance(rCut);// * OpenMM::NmPerAngstrom nonbonded->addPerParticleParameter("Ar");//later on collect it from json string based on OF for(int p=0;p<numParticles;p++){ std::vector<double> params(numSpecies); params[0] = (double) 1; nonbonded->addParticle(params); } system.addForce(nonbonded); std::vector<std::string> ctools(1); ctools[0] = "ControlBerendsenInBins"; OpenMM::Vec3 startPoint = OpenMM::Vec3((10*0.34),(0*0.34),(10*0.34)); OpenMM::Vec3 endPoint = OpenMM::Vec3((10*0.34),(20*0.34),(10*0.34)); OpenMM::ControlTools controls(ctools,(double)292,0.001, startPoint,endPoint); int num_plat = OpenMM::Platform::getNumPlatforms(); std::cout<<"Number of registered platforms: "<< num_plat <<std::endl; for(int i=0;i<num_plat;i++) { OpenMM::Platform& tempPlatform = OpenMM::Platform::getPlatform(i); std::string tempPlatformName = tempPlatform.getName(); std::cout<<"Platform "<<(i+1)<<" is "<<tempPlatformName.c_str()<<std::endl; } OpenMM::Platform& platform = OpenMM::Platform::getPlatformByName("OpenCL"); OpenMM::VelocityVerletIntegrator integrator(stepSizeInFs * OpenMM::PsPerFs); OpenMM::Context context(system,integrator,platform,controls); string Platformname = context.getPlatform().getName(); std::cout<<"Using OpenMM "<<Platformname.c_str()<<" Platform"<<std::endl; context.setPositions(posInNm); context.setVelocities(velInNm); int nbs = context.getControls().getNBins(); printf("Using %d bins for the system\n",nbs); //start the simulation loop integrator.step(1); printf("Finished initial integration\n"); int counter=0; std::cout<<"starting the loop\n"; for(int frame=1;frame<400;++frame){ // OpenMM::State state = context.getState(OpenMM::State::Velocities); // const double time = state.getTime(); double* mola = context.getControls().getBinTemperature(); // OpenMM::Vec3* tv = context.getControls().getTestVariable(); double gpuMol = 0.0; for(int k=0;k<nbs;k++){ gpuMol += mola[k]; } EXPECT_EQ((double) numParticles,gpuMol); integrator.step(1); } std::cout<<"Simulation completed with counter value "<<counter<<std::endl; }
/* >>> start tutorial code >>> */ int main( ){ USING_NAMESPACE_ACADO // DEFINE VALRIABLES: // --------------------------- DifferentialStateVector x(3); // the position of the pendulum (x,y,alpha) DifferentialStateVector v(3); // the associated velocities AlgebraicStateVector a(3); // the associated accelerations AlgebraicStateVector lambda(2); // the constraint forces const double L = 1.00; // the length of the pendulum const double m = 1.00; // the mass of the pendulum const double g = 9.81; // the gravitational constant const double J = m*L*L; // the inertial of the pendulum IntermediateStateVector R(3); IntermediateStateVector G(2); R.setComponent( 0, m*a(0) ); // ---------------------------------------- R.setComponent( 1, m*a(1) + m*g ); // the definition of the force residuum: R.setComponent( 2, J*a(2) ); // R := m*a - F G.setComponent( 0, x(0)-L*sin(x(2)) ); // definition of the constraint manifold G G.setComponent( 1, x(1)+L*cos(x(2)) ); // --------------------------------------- // AUTOMATIC GENERATION OF AN INDEX 1 DAE SYSTEM BASES ON THE // NEWTON EULER FORMALISM: // ----------------------------------------------------------- DifferentialEquation f; NewtonEulerFormalism( f, R, G, x, v, a, lambda ); // Define an integrator: // --------------------- IntegratorBDF integrator( f ); // Define an initial value: // ------------------------ double x_start[6]; double z_start[5]; x_start[0] = 1.9866932270683099e-01; x_start[1] = -9.8006654611577315e-01; x_start[2] = 2.0000003107582773e-01; x_start[3] = -1.4519963562050693e-04; x_start[4] = 4.7104175041346282e-04; x_start[5] = 4.4177521668741377e-04; z_start[0] = -9.5504866367984165e-01; z_start[1] = -1.9359778029074531e-01; z_start[2] = -9.7447321693831934e-01; z_start[3] = -9.5504866367984165e-01; z_start[4] = 9.6164022197092560e+00; double t_start = 0.0; double t_end = 10.0; // START THE INTEGRATION // ---------------------- integrator.set( INTEGRATOR_PRINTLEVEL, MEDIUM ); // integrator.set( INTEGRATOR_TOLERANCE, 1e-12 ); integrator.freezeAll(); integrator.integrate( x_start, z_start, t_start, t_end ); VariablesGrid xres,zres; integrator.getTrajectory(&xres,&zres,NULL,NULL,NULL,NULL); GnuplotWindow window; window.addSubplot( xres(0), "The x-position of the mass m" ); window.addSubplot( xres(1), "The y-position of the mass m" ); window.addSubplot( xres(2), "The excitation angle of the pendulum" ); window.addSubplot( xres(3), "The velocity in x-direction" ); window.addSubplot( xres(4), "The velocity in y-direction" ); window.addSubplot( xres(5), "The angular velocity" ); // window.addSubplot( zres(0), "The acceleration in x-direction" ); // window.addSubplot( zres(1), "The acceleration in y-direction" ); // window.addSubplot( zres(2), "The angular acceleration" ); window.addSubplot( zres(3), "The constraint force in x-direction" ); window.addSubplot( zres(4), "The constraint force in y-direction" ); window.plot(); return 0; }
int main( ){ USING_NAMESPACE_ACADO // DEFINE A RIGHT-HAND-SIDE: // ------------------------- DifferentialState x; AlgebraicState z; Parameter p,q; IntermediateState is(4); is(0) = x; is(1) = z; is(2) = p; is(3) = q; CFunction simpledaeModel( 2, ffcn_model ); // Define a Right-Hand-Side: // ------------------------- DifferentialEquation f; f << simpledaeModel(is); // DEFINE AN INTEGRATOR: // --------------------- IntegratorBDF integrator(f); // DEFINE INITIAL VALUES: // ---------------------- double x0 = 1.0; double z0 = 1.000000; double pp[2] = { 1.0, 1.0 }; Grid interval( 0.0, 1.0, 100 ); // START THE INTEGRATION: // ---------------------- integrator.integrate( interval, &x0, &z0, pp ); VariablesGrid differentialStates; VariablesGrid algebraicStates ; VariablesGrid intermediateStates; integrator.getX ( differentialStates ); integrator.getXA( algebraicStates ); integrator.getI ( intermediateStates ); GnuplotWindow window; window.addSubplot( differentialStates(0) ); window.addSubplot( algebraicStates (0) ); window.plot(); return 0; }