static void sse_test (void) { assert (ys (1) == xs ()); assert (ys (2) == xs () * 2); assert (yd (1) == xd ()); assert (yd (2) == xd () * 2); }
void real_main (int argc, char *const argv[]) { int i = 1; print_n (); if (i == argc) xd (stdin, NULL); else for (; i < argc; ++i) { FILE *in = must_fopen (argv[i], "r"); xd (in, argv[i]); must_fclose (in, argv[i]); } finish (); }
int main() { unsigned long cpu_facilities; cpu_facilities = i386_cpuid (); if (cpu_facilities & bit_SSE) { assert (ys (1) == xs ()); assert (ys (2) == xs () * 2); assert (yd (1) == xd ()); assert (yd (2) == xd () * 2); } return 0; }
void Michalewicz::runProblem() { double pi = atan(1)*4; std::vector<VariablePtr> vars = { std::make_shared<Variable>(0, 0, pi), std::make_shared<Variable>(0, 0, pi), std::make_shared<Variable>(1) }; // Set starting points vars.at(0)->setValue(1.0); vars.at(1)->setValue(1.0); DataTable data; double dx = 0.05; for (double x1 = 0; x1 <= pi; x1+=dx) { for (double x2 = 0; x2 <= pi; x2+=dx) { std::vector<double> x = {x1, x2}; DenseVector xd(2); xd << x1, x2; DenseVector yd = michalewiczFunction(xd); data.addSample(x,yd(0)); } } // Test accuracy of B-spline // DenseVector (*foo)(DenseVector); // foo = &michalewiczFunction; // BSpline* bs = new BSpline(*data, 3); // bool testpassed = bs->testBspline(foo); // if (testpassed) // { // cout << "B-spline is very accurate:)" << endl; // } // else // { // cout << "B-spline is NOT very accurate:(" << endl; // } BSpline bs(data, BSplineType::CUBIC); auto constraint = std::make_shared<ConstraintBSpline>(vars, bs, false); //SolverIpopt solver(constraint); BB::BranchAndBound solver(constraint); // Optimize SolverResult result = solver.optimize(); cout << result << endl; fopt_found = result.objectiveValue; zopt_found = result.primalVariables; cout << zopt_found << endl; }
static bool _ViewerCallback(object fncallback, PyEnvironmentBasePtr pyenv, KinBody::LinkPtr plink,RaveVector<float> position,RaveVector<float> direction) { object res; PyGILState_STATE gstate = PyGILState_Ensure(); try { res = fncallback(openravepy::toPyKinBodyLink(plink,pyenv),toPyVector3(position),toPyVector3(direction)); } catch(...) { RAVELOG_ERROR("exception occured in python viewer callback:\n"); PyErr_Print(); } PyGILState_Release(gstate); extract<bool> xb(res); if( xb.check() ) { return (bool)xb; } extract<int> xi(res); if( xi.check() ) { return (int)xi; } extract<double> xd(res); if( xd.check() ) { return (double)xd>0; } return true; }
void QgsCoordinateTransform::transformInPlace( QVector<float> &x, QVector<float> &y, QVector<float> &z, TransformDirection direction ) const { if ( !d->mIsValid || d->mShortCircuit ) return; Q_ASSERT( x.size() == y.size() ); // Apparently, if one has a std::vector, it is valid to use the // address of the first element in the vector as a pointer to an // array of the vectors data, and hence easily interface with code // that wants C-style arrays. try { //copy everything to double vectors since proj needs double int vectorSize = x.size(); QVector<double> xd( x.size() ); QVector<double> yd( y.size() ); QVector<double> zd( z.size() ); double *destX = xd.data(); double *destY = yd.data(); double *destZ = zd.data(); const float *srcX = x.constData(); const float *srcY = y.constData(); const float *srcZ = z.constData(); for ( int i = 0; i < vectorSize; ++i ) { *destX++ = static_cast< double >( *srcX++ ); *destY++ = static_cast< double >( *srcY++ ); *destZ++ = static_cast< double >( *srcZ++ ); } transformCoords( x.size(), &xd[0], &yd[0], &zd[0], direction ); //copy back float *destFX = x.data(); float *destFY = y.data(); float *destFZ = z.data(); const double *srcXD = xd.constData(); const double *srcYD = yd.constData(); const double *srcZD = zd.constData(); for ( int i = 0; i < vectorSize; ++i ) { *destFX++ = static_cast< float >( *srcXD++ ); *destFY++ = static_cast< float >( *srcYD++ ); *destFZ++ = static_cast< float >( *srcZD++ ); } } catch ( QgsCsException & ) { // rethrow the exception QgsDebugMsg( QStringLiteral( "rethrowing exception" ) ); throw; } }
xml_obj_t xml_obj_t::from_pub3 (ptr<const pub3::expr_t> in) { ptr<xml_struct_t> st = New refcounted<xml_struct_t> (); xml_obj_t xd (st); if (!in) return xd; ptr<const pub3::expr_dict_t> d; ptr<const pub3::expr_list_t> l; int64_t t; str s; if ((d = in->to_dict ())) { pub3::bindtab_t::const_iterator_t it (*d); const str *key; ptr<pub3::expr_t> x; while ((key = it.next (&x))) { xml_obj_t tmp = from_pub3 (x); st->put (*key, tmp.el ()); } } else if ((l = in->to_list ())) { ptr<xml_array_t> a = New refcounted<xml_array_t> (); for (size_t i = 0; i < l->size (); i++) { xml_obj_t tmp = from_pub3 ((*l)[i]); a->put (i, tmp.el ()); } return xml_obj_t (a); } else if ((in->to_int (&t))) { return xml_obj_t (New refcounted<xml_int_t> (t)); } else if ((s = in->to_str (false))) { return xml_obj_t (New refcounted<xml_str_t> (s)); } return xd; }
void LIBeam3dNL :: computeStrainVector(FloatArray &answer, GaussPoint *gp, TimeStep *tStep) { FloatArray xd(3), eps(3), curv(3); // update temp triad this->updateTempTriad(tStep); this->computeXdVector(xd, tStep); // compute eps_xl, gamma_l2, gamma_l3 eps.beTProductOf(tempTc, xd); eps.times(1. / this->l0); eps.at(1) -= 1.0; // update curvature at midpoint this->computeTempCurv(curv, tStep); answer.resize(6); answer.at(1) = eps.at(1); // eps_xl answer.at(2) = eps.at(2); // gamma_l2 answer.at(3) = eps.at(3); // gamma_l3 answer.at(4) = curv.at(1); // kappa_1 answer.at(5) = curv.at(2); // kappa_2 answer.at(6) = curv.at(3); // kappa_3 }
void Michalewicz::runProblem() { double pi = atan(1)*4; std::vector<VariablePtr> vars = { std::make_shared<Variable>(0, 0, pi), std::make_shared<Variable>(0, 0, pi), std::make_shared<Variable>(1) }; // Set starting points vars.at(0)->setValue(1.0); vars.at(1)->setValue(1.0); DataTable data; unsigned int nums = 10; // 60x60 yields is sufficient to model function around optimum auto x1 = linspace(0, 4, nums); auto x2 = linspace(0, 4, nums); for (auto x1i : x1) { for (auto x2i : x2) { DenseVector xd(2); xd << x1i, x2i; double yd = michalewiczFunction(xd); data.addSample(xd, yd); } } // Test accuracy of B-spline // DenseVector (*foo)(DenseVector); // foo = &michalewiczFunction; // BSpline* bs = new BSpline(*data, 3); // bool testpassed = bs->testBspline(foo); // if (testpassed) // { // cout << "B-spline is very accurate:)" << endl; // } // else // { // cout << "B-spline is NOT very accurate:(" << endl; // } BSpline bs = BSpline::Builder(data).degree(3).build(); auto constraint = std::make_shared<ConstraintBSpline>(vars, bs, false); //SolverIpopt solver(constraint); BB::BranchAndBound solver(constraint); // Optimize SolverResult result = solver.optimize(); cout << result << endl; fopt_found = result.objectiveValue; zopt_found = result.primalVariables; cout << zopt_found << endl; }
void QgsCoordinateTransform::transformInPlace( QVector<float>& x, QVector<float>& y, QVector<float>& z, TransformDirection direction ) const { if ( mShortCircuit || !mInitialisedFlag ) return; Q_ASSERT( x.size() == y.size() ); // Apparently, if one has a std::vector, it is valid to use the // address of the first element in the vector as a pointer to an // array of the vectors data, and hence easily interface with code // that wants C-style arrays. try { //copy everything to double vectors since proj needs double int vectorSize = x.size(); QVector<double> xd( x.size() ); QVector<double> yd( y.size() ); QVector<double> zd( z.size() ); for ( int i = 0; i < vectorSize; ++i ) { xd[i] = x[i]; yd[i] = y[i]; zd[i] = z[i]; } transformCoords( x.size(), &xd[0], &yd[0], &zd[0], direction ); //copy back for ( int i = 0; i < vectorSize; ++i ) { x[i] = xd[i]; y[i] = yd[i]; z[i] = zd[i]; } } catch ( QgsCsException & ) { // rethrow the exception QgsDebugMsg( "rethrowing exception" ); throw; } }
void LIBeam3dNL :: computeTempCurv(FloatArray &answer, TimeStep *tStep) { Material *mat = this->giveMaterial(); IntegrationRule *iRule = integrationRulesArray [ giveDefaultIntegrationRule() ]; GaussPoint *gp = iRule->getIntegrationPoint(0); ; FloatArray ui(3), xd(3), curv(3), ac(3), PrevEpsilon; FloatMatrix sc(3, 3), tmid(3, 3); answer.resize(3); // update curvature at midpoint // first, compute Tmid // ask increments this->computeVectorOf(EID_MomentumBalance, VM_Incremental, tStep, ui); ac.at(1) = 0.5 * ( ui.at(10) - ui.at(4) ); ac.at(2) = 0.5 * ( ui.at(11) - ui.at(5) ); ac.at(3) = 0.5 * ( ui.at(12) - ui.at(6) ); this->computeSMtrx(sc, ac); sc.times(1. / 2.); // compute I+sc sc.at(1, 1) += 1.0; sc.at(2, 2) += 1.0; sc.at(3, 3) += 1.0; tmid.beProductOf(sc, this->tc); // update curvature at centre ac.at(1) = ( ui.at(10) - ui.at(4) ); ac.at(2) = ( ui.at(11) - ui.at(5) ); ac.at(3) = ( ui.at(12) - ui.at(6) ); answer.beTProductOf(tmid, ac); answer.times(1 / this->l0); // ask for previous kappa PrevEpsilon = ( ( StructuralMaterialStatus * ) mat->giveStatus(gp) )->giveStrainVector(); if ( PrevEpsilon.giveSize() ) { answer.at(1) += PrevEpsilon.at(4); answer.at(2) += PrevEpsilon.at(5); answer.at(3) += PrevEpsilon.at(6); } }
//Initialize Points void CalibrationUtils::initScreenPoints() { int p = 0; vector2df xd(screenBB.lowerRightCorner.X-screenBB.upperLeftCorner.X,0.0f); vector2df yd(0.0f, screenBB.lowerRightCorner.Y-screenBB.upperLeftCorner.Y); xd /= (float) GRID_X; yd /= (float) GRID_Y; for(int j = 0; j <= GRID_Y; j++) { for(int i = 0; i <= GRID_X; i++) { screenPoints[p] = screenBB.upperLeftCorner + xd*i + yd*j; //printf("(%d, %d) = (%f, %f)\n", i, j, screenPoints[p].X, screenPoints[p].Y); p++; } } }
void LIBeam3dNL :: computeXMtrx(FloatMatrix &answer, TimeStep *tStep) { int i, j; FloatArray xd(3); FloatMatrix s(3, 3); this->computeXdVector(xd, tStep); this->computeSMtrx(s, xd); answer.resize(12, 6); answer.zero(); for ( i = 1; i < 4; i++ ) { answer.at(i, i) = -1.0; answer.at(i + 6, i) = 1.0; answer.at(i + 3, i + 3) = -1.0; answer.at(i + 9, i + 3) = 1.0; for ( j = 1; j < 4; j++ ) { answer.at(i + 3, j) = answer.at(i + 9, j) = 0.5 * s.at(j, i); } } }
virtual void xct_state_changed(smlevel_1::xct_state_t, smlevel_1::xct_state_t new_state) { if(new_state == smlevel_1::xct_ended) _owner->report_finished(xd()); }
void cartesianMover::position_slider_changed(GtkRange *range, cartesianMover *cm) { ICartesianControl *icrt = cm->crt; GtkWidget **sliderPosArray = (GtkWidget **) cm->sliderArray; GtkWidget *sliderVel = (GtkWidget *) cm->sliderVelocity; int sliderIndex; for(int i=0; i < NUMBER_OF_CARTESIAN_COORDINATES; i++) if(sliderPosArray[i]==(GtkWidget*) range) sliderIndex=i; gboolean focus; g_object_get((gpointer) range, "has-focus", &focus, NULL); if (focus) { if (sliderIndex<3) { Vector xd(3); Vector x; Vector o; xd(0) = gtk_range_get_value((GtkRange *) sliderPosArray[0]); xd(1) = gtk_range_get_value((GtkRange *) sliderPosArray[1]); xd(2) = gtk_range_get_value((GtkRange *) sliderPosArray[2]); if(!icrt->getPose(x,o)) fprintf(stderr, "Troubles in gettin the cartesian pose for %s\n", cm->partLabel); double time = gtk_range_get_value((GtkRange *) sliderVel); if(!icrt->goToPoseSync(xd,o,time)) fprintf(stderr, "Troubles in executing the cartesian pose for %s\n", cm->partLabel); //else // fprintf(stderr, "Sent %s new cartesian for %s with time %.1f\n", xd.toString().c_str(),cm->partLabel, time); int count= 0; bool checkDone=false; while(checkDone==false && count*10<2*time*1000) { icrt->checkMotionDone(&checkDone); //fprintf(stderr, "Check %d\n", checkDone); Time::delay(0.01); count++; } if(!checkDone) { //fprintf(stderr, "Aborting since trajectory was not completed in 2*Time\n"); dialog_message(GTK_MESSAGE_ERROR,(char *)"Aborting cartesian trajectory", (char *)"Final point reaching was taking too much time", true); icrt->stopControl(); } } else { Vector eud(3); Vector x; Vector o; eud(0) = gtk_range_get_value((GtkRange *) sliderPosArray[3]) * M_PI/180; eud(1) = gtk_range_get_value((GtkRange *) sliderPosArray[4]) * M_PI/180; eud(2) = gtk_range_get_value((GtkRange *) sliderPosArray[5]) * M_PI/180; //fprintf(stderr, "Will move to x=%s, o=%s\n", x.toString().c_str(), o.toString().c_str()); Matrix Rd = euler2dcm(eud); Vector od = dcm2axis(Rd); if(!icrt->getPose(x,o)) fprintf(stderr, "Troubles in gettin the cartesian pose for %s\n", cm->partLabel); double time = gtk_range_get_value((GtkRange *) sliderVel); if(!icrt->goToPoseSync(x,od,time)) fprintf(stderr, "Troubles in executing the cartesian pose for %s\n", cm->partLabel); //else // fprintf(stderr, "Sent %s new orientation for %s\n", od.toString().c_str(), cm->partLabel); int count= 0; bool checkDone=false; while(checkDone==false && count*10<2*time*1000) { icrt->checkMotionDone(&checkDone); //fprintf(stderr, "Check %d\n", checkDone); Time::delay(0.01); count++; } if(!checkDone) { //fprintf(stderr, "Aborting since trajectory was not completed in 2*Time\n"); dialog_message(GTK_MESSAGE_ERROR,(char *)"Aborting cartesian trajectory", (char *)"Final point reaching was taking too much time", true); icrt->stopControl(); } } } }
void AcadoOCPInternal::evaluate(int nfdir, int nadir){ // Initial constraint function if(!rfcn_.f_.isNull()){ const Matrix<double>& lbr = input(ACADO_LBR); ACADO::Vector lb(lbr.size(),&lbr.front()); const Matrix<double>& ubr = input(ACADO_UBR); ACADO::Vector ub(ubr.size(),&ubr.front()); ocp_->subjectTo( ACADO::AT_START, lb <= (*rfcn_.fcn_)(*arg_) <= ub); } // Path constraint function if(!cfcn_.f_.isNull()){ const Matrix<double>& lbc = input(ACADO_LBC); ACADO::Vector lb(lbc.size(),&lbc.front()); const Matrix<double>& ubc = input(ACADO_UBC); ACADO::Vector ub(ubc.size(),&ubc.front()); ocp_->subjectTo( lb <= (*cfcn_.fcn_)(*arg_) <= ub ); } // State bounds Matrix<double> &lbx = input(ACADO_LBX); Matrix<double> &ubx = input(ACADO_UBX); for(int i=0; i<nxd_; ++i) ocp_->subjectTo( lbx.at(i) <= xd_[i] <= ubx.at(i) ); for(int i=nxd_; i<nx_; ++i) ocp_->subjectTo( lbx.at(i) <= xa_[i-nxd_] <= ubx.at(i) ); // Pass bounds on state at initial time Matrix<double> &lbx0 = input(ACADO_LBX0); Matrix<double> &ubx0 = input(ACADO_UBX0); for(int i=0; i<nxd_; ++i) ocp_->subjectTo( ACADO::AT_START, lbx0.at(i) <= xd_[i] <= ubx0.at(i) ); for(int i=nxd_; i<nx_; ++i) ocp_->subjectTo( ACADO::AT_START, lbx0.at(i) <= xa_[i-nxd_] <= ubx0.at(i) ); // ocp_->subjectTo( AT_END , xd_[1] == 0.0 ); // ocp_->subjectTo( AT_END , xd_[2] == 0.0 ); // Control bounds Matrix<double> &lbu = input(ACADO_LBU); Matrix<double> &ubu = input(ACADO_UBU); for(int i=0; i<nu_; ++i) ocp_->subjectTo( lbu.at(i) <= u_[i] <= ubu.at(i) ); // Parameter bounds Matrix<double> &lbp = input(ACADO_LBP); Matrix<double> &ubp = input(ACADO_UBP); for(int i=0; i<np_; ++i) ocp_->subjectTo( lbp.at(i) <= p_[i] <= ubp.at(i) ); // Periodic boundary condition if(hasSetOption("periodic_bounds")){ const vector<int>& periodic = getOption("periodic_bounds"); if(periodic.size()!=nx_) throw CasadiException("wrong dimension for periodic_bounds"); for(int i=0; i<nxd_; ++i) if(periodic[i]) ocp_->subjectTo( 0.0, xd_[i], -xd_[i], 0.0); for(int i=nxd_; i<nx_; ++i) if(periodic[i]) ocp_->subjectTo( 0.0, xa_[i-nxd_], -xa_[i-nxd_], 0.0); } algorithm_ = new ACADO::OptimizationAlgorithm(*ocp_); // set print level ACADO::PrintLevel printlevel; if(getOption("print_level")=="none") printlevel = ACADO::NONE; else if(getOption("print_level")=="low") printlevel = ACADO::LOW; else if(getOption("print_level")=="medium") printlevel = ACADO::MEDIUM; else if(getOption("print_level")=="high") printlevel = ACADO::HIGH; else if(getOption("print_level")=="debug") printlevel = ACADO::DEBUG; else throw CasadiException("Illegal print level. Allowed are \"none\", \"low\", \"medium\", \"high\", \"debug\""); algorithm_->set(ACADO::INTEGRATOR_PRINTLEVEL, printlevel ); // Set integrator if(hasSetOption("integrator")){ GenericType integ = getOption("integrator"); ACADO::IntegratorType itype; if(integ=="rk4") itype=ACADO::INT_RK4; else if(integ=="rk12") itype=ACADO::INT_RK12; else if(integ=="rk23") itype=ACADO::INT_RK23; else if(integ=="rk45") itype=ACADO::INT_RK45; else if(integ=="rk78") itype=ACADO::INT_RK78; else if(integ=="bdf") itype=ACADO::INT_BDF; else if(integ=="discrete") itype=ACADO::INT_DISCRETE; else if(integ=="unknown") itype=ACADO::INT_UNKNOWN; #ifdef ACADO_HAS_USERDEF_INTEGRATOR else if(integ=="casadi"){ if(ACADO::Integrator::integrator_creator_ || ACADO::Integrator::integrator_user_data_) throw CasadiException("AcadoOCPInternal::AcadoOCPInternal: An instance already exists"); if(integrators_.size() <= n_nodes_) throw CasadiException("AcadoOCPInternal::AcadoOCPInternal: Number of integrators does not match number of shooting nodes"); ACADO::Integrator::integrator_creator_ = &AcadoIntegratorBackend::create; ACADO::Integrator::integrator_user_data_ = this; itype=ACADO::INT_UNKNOWN; } #endif else throw CasadiException("AcadoOCPInternal::evaluate: no such integrator: " + integ.toString()); algorithm_->set(ACADO::INTEGRATOR_TYPE, itype); }; // Set integrator tolerance if(hasSetOption("integrator_tolerance")) algorithm_->set( ACADO::INTEGRATOR_TOLERANCE, getOption("integrator_tolerance").toDouble()); if(hasSetOption("absolute_tolerance")) algorithm_->set( ACADO::ABSOLUTE_TOLERANCE, getOption("absolute_tolerance").toDouble()); if(hasSetOption("kkt_tolerance")) algorithm_->set( ACADO::KKT_TOLERANCE, getOption("kkt_tolerance").toDouble()); if(hasSetOption("max_num_iterations")) algorithm_->set( ACADO::MAX_NUM_ITERATIONS, getOption("max_num_iterations").toInt() ); if(hasSetOption("max_num_integrator_steps")) algorithm_->set( ACADO::MAX_NUM_INTEGRATOR_STEPS, getOption("max_num_integrator_steps").toInt() ); if(hasSetOption("relaxation_parameter")) algorithm_->set( ACADO::RELAXATION_PARAMETER, getOption("relaxation_parameter").toDouble()); if(hasSetOption("dynamic_sensitivity")){ if(getOption("dynamic_sensitivity") == "forward_sensitivities") algorithm_->set( ACADO::DYNAMIC_SENSITIVITY, ACADO::FORWARD_SENSITIVITY ); else if(getOption("dynamic_sensitivity") == "backward_sensitivities") algorithm_->set( ACADO::DYNAMIC_SENSITIVITY, ACADO::BACKWARD_SENSITIVITY ); else throw CasadiException("illegal dynamic_sensitivity"); } if(hasSetOption("hessian_approximation")){ int hess; GenericType op = getOption("hessian_approximation"); if(op=="exact_hessian") hess = ACADO::EXACT_HESSIAN; else if(op == "constant_hessian") hess = ACADO::CONSTANT_HESSIAN; else if(op == "full_bfgs_update") hess = ACADO::FULL_BFGS_UPDATE; else if(op == "block_bfgs_update") hess = ACADO::BLOCK_BFGS_UPDATE; else if(op == "gauss_newton") hess = ACADO::GAUSS_NEWTON; else if(op == "gauss_newton_with_block_bfgs") hess = ACADO::GAUSS_NEWTON_WITH_BLOCK_BFGS; else throw CasadiException("illegal hessian approximation"); algorithm_->set( ACADO::HESSIAN_APPROXIMATION, hess); } // should the states be initialized by a forward integration? bool auto_init = getOption("auto_init").toInt(); // Initialize differential states if(nxd_>0){ // Initial guess Matrix<double> &x0 = input(ACADO_X_GUESS); // Assemble the variables grid ACADO::VariablesGrid xd(nxd_, n_nodes_+1); for(int i=0; i<n_nodes_+1; ++i){ ACADO::Vector v(nxd_,&x0.at(i*nx_)); xd.setVector(i,v); } // Pass to acado algorithm_->initializeDifferentialStates(xd,auto_init ? ACADO::BT_TRUE : ACADO::BT_FALSE); } // Initialize algebraic states if(nxa_>0){ // Initial guess Matrix<double> &x0 = input(ACADO_X_GUESS); // Assemble the variables grid ACADO::VariablesGrid xa(nxa_, n_nodes_+1); for(int i=0; i<n_nodes_+1; ++i){ ACADO::Vector v(nxa_,&x0.at(i*nx_+nxd_)); xa.setVector(i,v); } // Pass to acado algorithm_->initializeAlgebraicStates(xa,auto_init ? ACADO::BT_TRUE : ACADO::BT_FALSE); } // Initialize controls if(nu_>0){ // Initial guess Matrix<double> &u0 = input(ACADO_U_GUESS); // Assemble the variables grid ACADO::VariablesGrid u(nu_, n_nodes_+1); for(int i=0; i<n_nodes_+1; ++i){ ACADO::Vector v(nu_,&u0.at(i*nu_)); u.setVector(i,v); } // Pass to acado algorithm_->initializeControls(u); } // Initialize parameters if(np_>0){ // Initial guess Matrix<double> &p0 = input(ACADO_P_GUESS); // Assemble the variables grid ACADO::VariablesGrid p(np_, n_nodes_+1); for(int i=0; i<n_nodes_+1; ++i){ ACADO::Vector v(np_,&p0.front()); // NB! p.setVector(i,v); } // Pass to acado algorithm_->initializeParameters(p); } // Solve algorithm_->solve(); // Get the optimal state trajectory if(nxd_>0){ Matrix<double> &xopt = output(ACADO_X_OPT); ACADO::VariablesGrid xd; algorithm_->getDifferentialStates(xd); assert(xd.getNumPoints()==n_nodes_+1); for(int i=0; i<n_nodes_+1; ++i){ // Copy to result ACADO::Vector v = xd.getVector(i); &xopt.at(i*nx_) << v; } } if(nxa_>0){ Matrix<double> &xopt = output(ACADO_X_OPT); ACADO::VariablesGrid xa; algorithm_->getAlgebraicStates(xa); assert(xa.getNumPoints()==n_nodes_+1); for(int i=0; i<n_nodes_+1; ++i){ // Copy to result ACADO::Vector v = xa.getVector(i); &xopt.at(i*nx_ + nxd_) << v; } } // Get the optimal control trajectory if(nu_>0){ Matrix<double> &uopt = output(ACADO_U_OPT); ACADO::VariablesGrid u; algorithm_->getControls(u); assert(u.getNumPoints()==n_nodes_+1); for(int i=0; i<n_nodes_+1; ++i){ // Copy to result ACADO::Vector v = u.getVector(i); &uopt.at(i*nu_) << v; } } // Get the optimal parameters if(np_>0){ Matrix<double> &popt = output(ACADO_P_OPT); ACADO::Vector p; algorithm_->getParameters(p); &popt.front() << p; } // Get the optimal cost double cost = algorithm_->getObjectiveValue(); output(ACADO_COST).set(cost); }
bool plotNoiseStandardDeviation(const hoNDArray< std::complex<T> >& m, const std::vector<std::string>& coilStrings, const std::string& xlabel, const std::string& ylabel, const std::string& title, size_t xsize, size_t ysize, bool trueColor, hoNDArray<float>& plotIm) { try { size_t CHA = m.get_size(0); GADGET_CHECK_RETURN_FALSE(coilStrings.size() == CHA); hoNDArray<double> xd, yd, yd2; xd.create(CHA); yd.create(CHA); size_t c; for (c = 0; c < CHA; c++) { xd(c) = c+1; yd(c) = std::sqrt( std::abs(m(c, c)) ); } double maxY = Gadgetron::max(&yd); yd2 = yd; std::sort(yd2.begin(), yd2.end()); double medY = yd2(CHA / 2); // increase dot line to be 1 sigma ~= 33% double medRange = 0.33; if (maxY < medY*(1 + medRange)) { maxY = medY*(1 + medRange); } hoNDArray<unsigned char> im; im.create(3, xsize, ysize); Gadgetron::clear(im); plsdev("mem"); plsmem(im.get_size(1), im.get_size(2), im.begin()); plinit(); plfont(2); pladv(0); plvpor(0.15, 0.75, 0.1, 0.8); plwind(0, CHA+1, 0, maxY*1.05); plcol0(15); plbox("bcnst", 0.0, 0, "bcnstv", 0.0, 0); std::string gly; getPlotGlyph(0, gly); // circle plstring(CHA, xd.begin(), yd.begin(), gly.c_str()); // draw the median line pllsty(1); double px[2], py[2]; px[0] = 0; px[1] = CHA+1; py[0] = medY; py[1] = medY; plline(2, px, py); pllsty(2); py[0] = medY*(1 - medRange); py[1] = medY*(1 - medRange); plline(2, px, py); py[0] = medY*(1 + medRange); py[1] = medY*(1 + medRange); plline(2, px, py); plmtex("b", 3.2, 0.5, 0.5, xlabel.c_str()); plmtex("t", 2.0, 0.5, 0.5, title.c_str()); plmtex("l", 5.0, 0.5, 0.5, ylabel.c_str()); // draw the legend std::vector<PLINT> opt_array(CHA), text_colors(CHA), line_colors(CHA), line_styles(CHA), symbol_numbers(CHA), symbol_colors(CHA); std::vector<PLFLT> symbol_scales(CHA), line_widths(CHA), box_scales(CHA, 1); std::vector<const char*> symbols(CHA); PLFLT legend_width, legend_height; std::vector<const char*> legend_text(CHA); std::vector<std::string> legends(CHA); size_t n; for (n = 0; n < CHA; n++) { opt_array[n] = PL_LEGEND_SYMBOL; text_colors[n] = 15; line_colors[n] = 15; line_styles[n] = (n % 8 + 1); line_widths[n] = 0.2; symbol_colors[n] = 15; symbol_scales[n] = 0.75; symbol_numbers[n] = 1; symbols[n] = gly.c_str(); std::ostringstream ostr; ostr << n+1 << ":" << coilStrings[n]; legends[n] = ostr.str(); legend_text[n] = legends[n].c_str(); } pllegend(&legend_width, &legend_height, PL_LEGEND_BACKGROUND, PL_POSITION_OUTSIDE | PL_POSITION_RIGHT, 0.02, // x 0.0, // y 0.05, // plot_width 0, // bg_color 15, // bb_color 1, // bb_style 0, // nrow 0, // ncolumn CHA, // nlegend &opt_array[0], 0.05, // text_offset 0.5, // text_scale 1.0, // text_spacing 0.5, // text_justification &text_colors[0], (const char **)(&legend_text[0]), NULL, // box_colors NULL, // box_patterns &box_scales[0], // box_scales NULL, // box_line_widths &line_colors[0], &line_styles[0], &line_widths[0], &symbol_colors[0], &symbol_scales[0], &symbol_numbers[0], (const char **)(&symbols[0]) ); plend(); outputPlotIm(im, trueColor, plotIm); } catch (...) { GERROR_STREAM("Errors happened in plotNoiseStandardDeviation(...) ... "); return false; } return true; }
static DF1(xn1){RZ( w); R vn(xd(0L,w,self));}
void LIBeam3dNL :: computeStiffnessMatrix(FloatMatrix &answer, MatResponseMode rMode, TimeStep *tStep) { int i, j, k; double s1, s2; FloatMatrix d, x, xt(12, 6), dxt, sn, sm, sxd, y; FloatArray n(3), m(3), xd(3), TotalStressVector; IntegrationRule *iRule = integrationRulesArray [ giveDefaultIntegrationRule() ]; GaussPoint *gp = iRule->getIntegrationPoint(0); answer.resize( this->computeNumberOfDofs(EID_MomentumBalance), this->computeNumberOfDofs(EID_MomentumBalance) ); answer.zero(); // linear part this->updateTempTriad(tStep); // update temp triad this->computeXMtrx(x, tStep); xt.zero(); for ( i = 1; i <= 12; i++ ) { for ( j = 1; j <= 3; j++ ) { for ( k = 1; k <= 3; k++ ) { // compute x*Tbar, taking into account sparsity of Tbar xt.at(i, j) += x.at(i, k) * tempTc.at(k, j); xt.at(i, j + 3) += x.at(i, k + 3) * tempTc.at(k, j); } } } this->computeConstitutiveMatrixAt(d, rMode, gp, tStep); dxt.beProductTOf(d, xt); answer.beProductOf(xt, dxt); answer.times(1. / this->l0); // geometric stiffness ks = ks1+ks2 // ks1 this->computeStressVector(TotalStressVector, gp, tStep); for ( i = 1; i <= 3; i++ ) { s1 = s2 = 0.0; for ( j = 1; j <= 3; j++ ) { s1 += tempTc.at(i, j) * TotalStressVector.at(j); s2 += tempTc.at(i, j) * TotalStressVector.at(j + 3); } n.at(i) = s1; m.at(i) = s2; } this->computeSMtrx(sn, n); this->computeSMtrx(sm, m); for ( i = 1; i <= 3; i++ ) { for ( j = 1; j <= 3; j++ ) { answer.at(i, j + 3) += sn.at(i, j); answer.at(i, j + 9) += sn.at(i, j); answer.at(i + 3, j + 3) += sm.at(i, j); answer.at(i + 3, j + 9) += sm.at(i, j); answer.at(i + 6, j + 3) -= sn.at(i, j); answer.at(i + 6, j + 9) -= sn.at(i, j); answer.at(i + 9, j + 3) -= sm.at(i, j); answer.at(i + 9, j + 9) -= sm.at(i, j); } } // ks2 this->computeXdVector(xd, tStep); this->computeSMtrx(sxd, xd); y.beProductOf(sxd, sn); y.times(0.5); for ( i = 1; i <= 3; i++ ) { for ( j = 1; j <= 3; j++ ) { answer.at(i + 3, j) -= sn.at(i, j); answer.at(i + 3, j + 3) += y.at(i, j); answer.at(i + 3, j + 6) += sn.at(i, j); answer.at(i + 3, j + 9) += y.at(i, j); answer.at(i + 9, j) -= sn.at(i, j); answer.at(i + 9, j + 3) += y.at(i, j); answer.at(i + 9, j + 6) += sn.at(i, j); answer.at(i + 9, j + 9) += y.at(i, j); } } }
static DF2(xn2){RZ(a&&w); R vn(xd(a ,w,self));}
int main() { #if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ > 4) std::cout << "gcc " << __GNUC__ << "." << __GNUC_MINOR__ << std::endl; #endif #ifdef USE_SSEVECT std::cout << "sse vector enabled in cmssw" << std::endl; #endif std::cout << sizeof(Basic2DVectorF) << std::endl; std::cout << sizeof(Basic2DVectorD) << std::endl; std::cout << sizeof(Basic3DVectorF) << std::endl; std::cout << sizeof(Basic3DVectorD) << std::endl; std::cout << sizeof(Basic3DVectorLD) << std::endl; Basic3DVectorF x(2.0f,4.0f,5.0f); Basic3DVectorF y(-3.0f,2.0f,-5.0f); Basic3DVectorD xd(2.0,4.0,5.0); Basic3DVectorD yd = y; Basic3DVectorLD xld(2.0,4.0,5.0); Basic3DVectorLD yld = y; Basic2DVectorF x2(2.0f,4.0f); Basic2DVectorF y2 = y.xy(); Basic2DVectorD xd2(2.0,4.0); Basic2DVectorD yd2 = yd.xy(); { std::cout << dotV(x,y) << std::endl; std::cout << normV(x) << std::endl; std::cout << norm(x) << std::endl; std::cout << min(x.mathVector(),y.mathVector()) << std::endl; std::cout << max(x.mathVector(),y.mathVector()) << std::endl; std::cout << dotV(x,yd) << std::endl; std::cout << dotV(xd,y) << std::endl; std::cout << dotV(xd,yd) << std::endl; std::cout << normV(xd) << std::endl; std::cout << norm(xd) << std::endl; std::cout << dotV(xld,yld) << std::endl; std::cout << normV(xld) << std::endl; std::cout << norm(xld) << std::endl; Basic3DVectorF z = x.cross(y); std::cout << z << std::endl; std::cout << -z << std::endl; Basic3DVectorD zd = x.cross(yd); std::cout << zd << std::endl; std::cout << -zd << std::endl; std::cout << xd.cross(y)<< std::endl; std::cout << xd.cross(yd)<< std::endl; Basic3DVectorLD zld = x.cross(yld); std::cout << zld << std::endl; std::cout << -zld << std::endl; std::cout << xld.cross(y)<< std::endl; std::cout << xld.cross(yld)<< std::endl; std::cout << z.eta() << " " << (-z).eta() << std::endl; std::cout << zd.eta() << " " << (-zd).eta() << std::endl; std::cout << zld.eta() << " " << (-zld).eta() << std::endl; #if defined( __GXX_EXPERIMENTAL_CXX0X__) auto s = x+xd - 3.1*z; std::cout << s << std::endl; auto s2 = x+xld - 3.1*zd; std::cout << s2 << std::endl; #endif } { std::cout << dotV(x2,y2) << std::endl; std::cout << normV(x2) << std::endl; std::cout << norm(x2) << std::endl; std::cout << min(x2.mathVector(),y2.mathVector()) << std::endl; std::cout << max(x2.mathVector(),y2.mathVector()) << std::endl; std::cout << dotV(x2,yd2) << std::endl; std::cout << dotV(xd2,y2) << std::endl; std::cout << dotV(xd2,yd2) << std::endl; std::cout << normV(xd2) << std::endl; std::cout << norm(xd2) << std::endl; Basic2DVectorF z2(x2); z2-=y2; std::cout << z2 << std::endl; std::cout << -z2 << std::endl; Basic2DVectorD zd2 = x2-yd2; std::cout << zd2 << std::endl; std::cout << -zd2 << std::endl; std::cout << x2.cross(y2) << std::endl; std::cout << x2.cross(yd2) << std::endl; std::cout << xd2.cross(y2)<< std::endl; std::cout << xd2.cross(yd2)<< std::endl; #if defined( __GXX_EXPERIMENTAL_CXX0X__) auto s2 = x2+xd2 - 3.1*z2; std::cout << s2 << std::endl; #endif } { std::cout << "f" << std::endl; Basic3DVectorF vx(2.0f,4.0f,5.0f); Basic3DVectorF vy(-3.0f,2.0f,-5.0f); vx+=vy; std::cout << vx << std::endl; Basic3DVectorF vz(1.f,1.f,1.f); addScaleddiff(vz,0.1f,vx,vy); std::cout << vz << std::endl; } { std::cout << "d" << std::endl; Basic3DVectorD vx(2.0,4.0,5.0); Basic3DVectorD vy(-3.0,2.0,-5.0); vx+=vy; std::cout << vx << std::endl; Basic3DVectorD vz(1.,1.,1); addScaleddiff(vz,0.1,vx,vy); std::cout << vz << std::endl; } std::cout << "std::vector" << std::endl; std::vector<Basic3DVectorF> vec1; vec1.reserve(50); std::vector<float> vecf(21); std::vector<Basic3DVectorF> vec2(51); std::vector<Basic3DVectorF> vec3; vec3.reserve(23456); }
double yd (double a) { return xd () * a; }
// add using dual numbers // combine diffeq and incorporation for direct RedTrace computation void DerivativeRedTrace(float *red_out, float *ival_offset, float *da_offset, float *dk_offset, int npts, float *deltaFrameSeconds, float *deltaFrame, float *nuc_rise_ptr, int SUB_STEPS, int my_start, Dual A, float SP, Dual kr, float kmax, float d, float sens, float gain, float tauB, PoissonCDFApproxMemo *math_poiss) { int i; Dual totocc, totgen; // mixed_poisson_struct mix_ctrl; MixtureMemo mix_memo; Dual pact,pact_new; Dual c_dntp_top, c_dntp_bot; Dual hplus_events_sum, hplus_events_current; // mean events per molecule, cumulative and current Dual ldt; Dual Ival; Dual One(1.0); Dual Zero(0.0); Dual Half(0.5); Dual xSP(SP); Dual xkmax(kmax); Dual xd(d); Dual xA = mix_memo.Generate(A,math_poiss); //xA.Dump("xA"); //A = InitializeMixture(&mix_ctrl,A,MAX_HPLEN); // initialize Poisson with correct amplitude which maxes out at MAX_HPLEN mix_memo.ScaleMixture(SP); //ScaleMixture(&mix_ctrl,SP); // scale mixture fractions to proper number of molecules pact = Dual(mix_memo.total_live); // active polymerases // wrong??? //pact.Dump("pact"); //Dual pact_zero = pact; totocc = xSP*xA; // how many hydrogens we'll eventually generate //totocc.Dump("totocc"); totgen = totocc; // number remaining to generate //totgen.Dump("totgen"); c_dntp_bot = Zero; // concentration of dNTP in the well c_dntp_top = Zero; // concentration at top hplus_events_sum = hplus_events_current = Zero; // Events per molecule memset(ival_offset,0,sizeof(float[my_start])); // zero the points we don't compute memset(da_offset,0,sizeof(float[my_start])); // zero the points we don't compute memset(dk_offset,0,sizeof(float[my_start])); // zero the points we don't compute Dual scaled_kr = kr*Dual(n_to_uM_conv)/xd; // convert molecules of polymerase to active concentraction Dual half_kr = kr *Half; // for averaging // kr.Dump("kr"); //scaled_kr.Dump("scaled_kr"); //half_kr.Dump("half_kr"); // first non-zero index of the computed [dNTP] array for this nucleotide int c_dntp_top_ndx = my_start*SUB_STEPS; Dual c_dntp_bot_plus_kmax = Dual(1.0/kmax); Dual c_dntp_old_effect = Zero; Dual c_dntp_new_effect = Zero; Dual cur_gen(0.0); Dual equilibrium(0.0); int st; // trace variables Dual old_val = Zero; Dual cur_val = Zero; Dual run_sum = Zero; Dual half_dt = Zero; Dual TauB(tauB); Dual SENS(sens); memset(red_out,0,sizeof(float[my_start])); for (i=my_start;i < npts;i++) { // Do one prediction time step if (totgen.a > 0.0) { // need to calculate incorporation ldt = (deltaFrameSeconds[i]/SUB_STEPS); // multiply by half_kr out here, because I'm going to use it twice? ldt *= half_kr; // scale time by rate out here //ldt.Dump("ldt"); for (st=1; (st <= SUB_STEPS) && (totgen.a > 0.0);st++) { c_dntp_bot.a = nuc_rise_ptr[c_dntp_top_ndx]; c_dntp_top_ndx++; // calculate denominator equilibrium = c_dntp_bot_plus_kmax; equilibrium *= pact; equilibrium *= scaled_kr; equilibrium += One; c_dntp_bot /= equilibrium; //c_dntp_bot.Dump("c_dntp_bot"); // the level at which new nucs are used up as fast as they diffuse in c_dntp_bot_plus_kmax.Reciprocal(c_dntp_bot + xkmax); // scale for michaelis-menten kinetics, assuming nucs are limiting factor //c_dntp_bot_plus_kmax.Dump("plus_kmax"); // Now compute effect of concentration on enzyme rate c_dntp_old_effect = c_dntp_new_effect; c_dntp_new_effect = c_dntp_bot; c_dntp_new_effect *= c_dntp_bot_plus_kmax; // current effect of concentration on enzyme rate //c_dntp_new_effect.Dump("c_dntp_new"); // update events per molecule hplus_events_current = c_dntp_old_effect; hplus_events_current += c_dntp_new_effect; hplus_events_current *= ldt; //hplus_events_current.Dump("current"); // events per molecule is average rate * time of rate hplus_events_sum += hplus_events_current; //hplus_events_sum.Dump("sum"); // how many active molecules left at end of time period given poisson process with total intensity of events // exp(-t) * (1+t+t^2/+t^3/6+...) where we interpolate between polynomial lengths by A // exp(-t) ( 1+... + frac*(t^k/k!)) where k = ceil(A-1) and frac = A-floor(A), for A>=1 pact_new = mix_memo.GetStep(hplus_events_sum); //pact_new = pact_zero; //pact_new.Dump("pact_new"); // how many hplus were generated // reuse pact for average // reuse hplus-events_current for total events pact += pact_new; pact *= Half; // average number of molecules //hplus_events_current *= pact; // events/molecule *= molecule is total events totgen -= pact*hplus_events_current; // active molecules * events per molecule //totgen.Dump("totgen"); pact = pact_new; // update to current number of molecules //pact.Dump("pact"); } if (totgen.a < 0.0) totgen = Zero; } Ival = totocc; Ival -= totgen; ival_offset[i] = Ival.a; Ival *= SENS; // convert from hydrogen to counts // Now compute trace // trace half_dt = deltaFrame[i]*0.5; // calculate new value Ival *= TauB; cur_val = Ival; cur_val -= run_sum; old_val *= half_dt; // update cur_val -= old_val; cur_val /= (TauB+half_dt); // update run sum run_sum += old_val; // reuse update run_sum += cur_val*half_dt; old_val = cur_val; // set for next value //cur_val *= gain; // gain=1.0 always currently red_out[i] = cur_val.a; da_offset[i] = cur_val.da; dk_offset[i] = cur_val.dk; // now we have done one prediction time step } }
static DF2(xconj){RZ(a&&w); R xd(a,w, self);}
static DF1(xadv ){RZ(w); R xd(w,0L,self);}
void main(int argc, char *argv[]) { int i, err; Arg *ap; Binit(&bout, 1, OWRITE); err = 0; ap = 0; while(argc>1 && argv[1][0]=='-' && argv[1][1]){ --argc; argv++; argv[0]++; if(argv[0][0] == 'r'){ repeats = 1; if(argv[0][1]) goto Usage; continue; } if(argv[0][0] == 's'){ swizzle = 1; if(argv[0][1]) goto Usage; continue; } if(argv[0][0] == 'u'){ flush = 1; if(argv[0][1]) goto Usage; continue; } if(argv[0][0] == 'a'){ argv[0]++; switch(argv[0][0]){ case 'o': abase = 0; break; case 'd': abase = 1; break; case 'x': abase = 2; break; default: goto Usage; } if(argv[0][1]) goto Usage; continue; } ap = &arg[narg]; initarg(); while(argv[0][0]){ switch(argv[0][0]){ case 'c': ap->chartype = TAscii; ap->loglen = 0; if(argv[0][1] || argv[0][-1]!='-') goto Usage; break; case 'R': ap->chartype = TRune; ap->loglen = 0; if(argv[0][1] || argv[0][-1]!='-') goto Usage; break; case 'o': ap->base = 0; break; case 'd': ap->base = 1; break; case 'x': ap->base = 2; break; case 'b': case '1': ap->loglen = 0; break; case 'w': case '2': ap->loglen = 1; break; case 'l': case '4': ap->loglen = 2; break; case 'v': case '8': ap->loglen = 3; break; default: Usage: fprint(2, "usage: xd [-u] [-r] [-s] [-a{odx}] [-c|{b1w2l4v8}{odx}] ... file ...\n"); exits("usage"); } argv[0]++; } if(ap->chartype == TRune) ap->fn = fmtr; else if(ap->chartype == TAscii) ap->fn = fmtc; else ap->fn = fmt[ap->loglen]; ap->fmt = dfmt[ap->loglen][ap->base]; ap->afmt = afmt[ap>arg][abase]; } if(narg == 0) initarg(); if(argc == 1) err = xd(0, 0); else if(argc == 2) err = xd(argv[1], 0); else for(i=1; i<argc; i++) err |= xd(argv[i], 1); exits(err? "error" : 0); }
void TestSorter(Char_t *xdffilename="/afs/rhic.bnl.gov/star/data/samples/test.xdf",const Char_t *col="phep[3]") { // Read XDF file Load(); St_XDFFile xdf(xdffilename); TDataSet *event = xdf.NextEventGet(); if (!event) { printf(" NO events \n"); return;} table=0; TDataSetIter root(event); table = (St_particle *)root["/evgen/particle"]; // [] means we are looking for the "real" table/ not just a St_DataSet if (table) { TString colName = col; sorter = new TTableSorter(table,colName,1,5); // sorter = new TTableSorter(*table,colName,1,5); table->Print(0,6); int cols = sorter->GetFirstRow() + sorter->GetNRows() -1; cout << " Result of the ordering the table: " << endl << "<" << sorter->GetTableName() <<" : " << sorter->GetTableType() << "[" << sorter->GetFirstRow() << "]> - " << "<" << sorter->GetTableName() <<" : " << sorter->GetTableType() << "[" << cols << "]> " << " along: \"" << sorter->GetName() << "\" column" << endl; cout << "This table contains " << sorter->CountKeys() << " different keys" << endl; int i; cout << "Index:"; for (i=0; i < sorter->GetNRows(); i++) cout << " [" << sorter->GetIndex(i) << "] "; cout << endl; cout << "Value: " ; particle_st *particle = table->GetTable(); for (i=0; i < sorter->GetNRows(); i++) cout << particle[sorter->GetIndex(i)]->phep[3] << " "; cout << endl; cout << " Binary Search test:"<< endl; for (i=sorter->GetNRows()-1; i >= 0 ; i--) { Float_t ph = particle[sorter->GetIndex(i)]->phep[3]; Int_t lastFound = sorter->BinarySearch(ph); cout << i << ". " << ph << " == " << lastFound << " : " << sorter->GetLastFound() << endl; } // Int_t key2Count = 1; // cout << " Key: " << key2Count << " found " << sorter->CountKey(&key2Count) << " times" << endl; // key2Count = 10; // cout << " Key: " << key2Count << " found " << sorter->CountKey(&key2Count) << " times" << endl; } // second sample: // /afs/rhic.bnl.gov/star/data/samples/set0027_03_49evts_dst.xdf cout << " Second pass " << endl; St_XDFFile xd("/afs/rhic.bnl.gov/star/data/samples/gstar.dst.xdf"); event = xd.NextEventGet(); if (event) { St_dst_vertex *table=0; table = (St_dst_vertex *)event->FindByName("vertex"); if (table) { TString colName = "vtx_id"; sorter = new TTableSorter(table,colName,1,5); // sorter = new TTableSorter(*table,colName,1,5); // sorter = new TTableSorter(table->GetHeader(),colName,1,5); TTableSorter &sort = *sorter; table->Print(0,6); int cols = sorter->GetFirstRow() + sorter->GetNRows() - 1; cout << " Result of the ordering the table: " << endl << "<" << sorter->GetTableName() <<" : " << sorter->GetTableType() << "[" << sorter->GetFirstRow() << "]> - " << "<" << sorter->GetTableName() <<" : " << sorter->GetTableType() << "[" << cols << "]> " << " along: \"" << sorter->GetName() << "\" column" << endl; cout << "This table contains " << sorter->CountKeys() << " different keys" << endl; cout << "Index:"; for (i=0; i < sorter->GetNRows(); i++) cout << " [" << sorter->GetIndex(i) << "] "; cout << endl; cout << "Value: " ; dst_vertex_st *vertex = table->GetTable(); for (i=0; i < sorter->GetNRows(); i++) cout << vertex[sorter->GetIndex(i)]->vtx_id << " "; cout << endl; for (i=0; i < sorter->GetNRows(); i++) cout << vertex[sorter->GetIndex(i)]->z << " "; cout << endl; cout << " Binary Search test:"<< endl; Int_t nrows = sorter->GetNRows() - 1; for (i=nrows; i >= 0 ; i--) { Short_t vtx = vertex[sorter->GetIndex(i)]->vtx_id; Int_t lastFound = sorter->BinarySearch(vtx); cout << i << ". " << vtx << " == " << lastFound << " : " << sorter->GetLastFound() << endl; if (sort[vtx] != lastFound) cout << " *** Error **** " << lastFound << " != " << sorter[vtx] << endl; // printf(" *** Error **** %d != %d \n" lastFound,sorter[vtx]); } // Int_t key2Count = 1; // cout << " Key: " << key2Count << " found " << sorter->CountKey(&key2Count) << " times" << endl; // key2Count = 10; // cout << " Key: " << key2Count << " found " << sorter->CountKey(&key2Count) << " times" << endl; } } else cout << " NO events" << endl; }
int main(int argc, char *argv[]) { struct option longopts[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, // { "long", no_argument, NULL, 'l' }, // { "delete", required_argument, NULL, 'd' }, // { "print", required_argument, NULL, 'p' }, // { "dump", required_argument, NULL, 'o' }, // { "write", required_argument, NULL, 'w' }, // { "follow-symlinks", no_argument, NULL, 'L' }, // { "create", no_argument, NULL, 'C' }, // { "replace", no_argument, NULL, 'R' }, // { "nosecurity", no_argument, NULL, 'S' }, // 10.6 only? // { "nodefault", no_argument, NULL, 'D' }, // 10.6 only? // { "show-compression", no_argument, NULL, 'Z' }, // 10.6 only? // { "cols", required_argument, NULL, 'c' }, { NULL, 0, NULL, 0 } }; int c; char *attr = NULL; char *value = NULL; // todo: -s <> and -S options to get XA sizes? // todo: -w <> -f <> ? // todo: -e attr exists? while ((c = getopt_long(argc, argv, "hV" "ld:o:p:w:" "c:x" "LCRSDZ", longopts, NULL)) != EOF) { switch (c) { case 'l': case 'o': case 'p': case 'd': case 'w': if (action != '\0') { warnx("You may not specify more than one `-dopw' option"); fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]); return 2; } else { action = c; if (action != 'l') { size_t l = strlen(optarg) + 1; attr = xmalloc(l); memcpy(attr, optarg, l); if ((action == 'w') && (optind < argc)) { char *val = argv[optind]; optind += 1; l = strlen(val) + 1; value = xmalloc(l); memcpy(value, val, l); } } } break; case 'L': options ^= XATTR_NOFOLLOW; break; case 'C': options ^= XATTR_CREATE; break; case 'R': options ^= XATTR_REPLACE; break; case 'S': options ^= XATTR_NOSECURITY; break; case 'D': options ^= XATTR_NODEFAULT; break; case 'Z': options ^= XATTR_SHOWCOMPRESSION; break; case 'x': hex ^= 1; break; case 'c': { unsigned long acols = strtoul(optarg, NULL, 0); if (acols > 0 && errno == 0) gCols = acols; else err(1, NULL); } break; case 'h': printf("usage: %s [<action>] [<options>] <file>...\n" "ACTIONS\n" " (default)\t" "List names of xattrs\n" " -p <name>\t" "Print data for given xattr\n" " -d <name>\t" "Delete given xattr\n" " -w <name> <value>\t" "Write xattr\n" "OPTIONS\n" " -L\t" "Follow symlinks.\n" " -C\t" "Fail if xattr exists (create)\n" " -R\t" "Fail if xattr doesn't exist (replace)\n" " -D\t" "Bypass the default extended attribute file (dot-underscore file)\n" " -Z\t" "Show HFS compression attributes\n" , argv[0]); return 0; case 'V': PRINT_VERSION; return 0; // case '?': default: // fprintf(stderr, "Usage: %s [-LRC] ACTION [ARG] <file>...\n", argv[0]); goto bad_cmd; } } if ((argc -= optind) == 0) { warnx("No files to act on"); bad_cmd: fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]); return 2; } argv += optind; switch (action) { case '\0': if (argc == 1) x(argv[0]); else { printf("%s:\n", argv[0]); x(argv[0]); argv += 1; do { printf("\n%s:\n", argv[0]); x(argv[0]); } while (++argv, --argc); } break; case 'o': if (strcmp("-", attr) != 0) { if (argc == 1) xo(argv[0], attr); else { printf("%s:\n", argv[0]); xo(argv[0], attr); argv += 1; argc -= 1; do { printf("\n%s:\n", argv[0]); xo(argv[0], attr); } while (++argv, --argc); } } else { size_t n; char **list = readList(&n); // check goto oloopInit; oloop: putchar('\n'); oloopInit: printf("%s:\n", argv[0]); for (size_t i = 0; i < n; i++) { printf("%s:\n", list[i]); xo(argv[0], list[i]); } argv += 1; argc -= 1; if (argc) goto oloop; // fixme: ? leaking each list item free(list); } break; case 'p': if (strcmp("-", attr) != 0) { if (argc == 1) xp(argv[0], attr); else { printf("%s:\n", argv[0]); xp(argv[0], attr); argv += 1; argc -= 1; do { printf("\n%s:\n", argv[0]); xp(argv[0], attr); } while (++argv, --argc); } } else { size_t n; char **list = readList(&n); // check goto ploopInit; ploop: putchar('\n'); ploopInit: printf("%s:\n", argv[0]); for (size_t i = 0; i < n; i++) { printf("%s:\n", list[i]); xp(argv[0], list[i]); } argv += 1; argc -= 1; if (argc) goto ploop; // fixme: ? leaking each list item free(list); } break; case 'l': if (argc == 1) xP(argv[0]); else { printf("%s:\n", argv[0]); xP(argv[0]); argv += 1; argc -= 1; do { printf("\n%s:\n", argv[0]); xP(argv[0]); } while (++argv, --argc); } break; case 'w': { // write xattr // Read data from stdin // 4096 bytes is max size for all xattrs except resource fork size_t totalSize; if (value == NULL) { value = malloc(4096); size_t lastReadSize = 0; unsigned int n = 0; // Accumulate data into buffer, expanding as needed while (value && (lastReadSize = fread(value + (n*4096), 1, 4096, stdin)) == 4096) value = realloc(value, (++n + 1)*4096); if (value == NULL) err(1, NULL); totalSize = (n*4096)+lastReadSize; } else { totalSize = strlen(value); } do { if (setxattr(argv[0], attr, value, totalSize, 0, options) != 0) warn("%s", argv[0]); } while (++argv, --argc); free(value); } break; case 'd': // delete xattrs if (strcmp("-", attr) != 0) { do { xd(argv[0], attr); } while (++argv, --argc); } else { size_t n; char **list = readList(&n); // check do { for (size_t i = 0; i < n; i++) xd(argv[0], list[i]); } while (++argv, --argc); // fixme: ? leaking each list item free(list); } break; } free(attr); return (errno != 0); }
Transformation Boonas:: parseParams(int start, int argc, char** argv, Transformation matrix) { QString currIn; for(int i = start; i < (argc - 1); i += 2) // iterate through parameters skiping every other { if(strcmp(argv[i], "XT") == 0) { currIn = argv[i + 1]; matrix = xt(currIn.toFloat(), matrix); } else if(strcmp(argv[i], "YT") == 0) { currIn = argv[i + 1]; matrix = yt(currIn.toFloat(), matrix); } else if(strcmp(argv[i], "ZT") == 0) { currIn = argv[i + 1]; matrix = zt(currIn.toFloat(), matrix); } else if(strcmp(argv[i], "XS") == 0) { currIn = argv[i + 1]; matrix = xs(currIn.toFloat(), matrix); } else if(strcmp(argv[i], "YS") == 0) { currIn = argv[i + 1]; matrix = ys(currIn.toFloat(), matrix); } else if(strcmp(argv[i], "ZS") == 0) { currIn = argv[i + 1]; matrix = zs(currIn.toFloat(), matrix); } else if(strcmp(argv[i], "US") == 0) { currIn = argv[i + 1]; matrix = us(currIn.toFloat(), matrix); } else if(strcmp(argv[i], "XD") == 0) { currIn = argv[i + 1]; matrix = xd(currIn.toFloat(), matrix); } else if(strcmp(argv[i], "YD") == 0) { currIn = argv[i + 1]; matrix = yd(currIn.toFloat(), matrix); } else if(strcmp(argv[i], "ZD") == 0) { currIn = argv[i + 1]; matrix = zd(currIn.toFloat(), matrix); } else if(strcmp(argv[i], "XR") == 0) { currIn = argv[i + 1]; matrix = xr(currIn.toFloat(), matrix); } else if(strcmp(argv[i], "YR") == 0) { currIn = argv[i + 1]; matrix = yr(currIn.toFloat(), matrix); } else // MUST BE ZR { currIn = argv[i + 1]; matrix = zr(currIn.toFloat(), matrix); } } return matrix; }