Esempio n. 1
0
int Interval::complementary(Interval& c1, Interval& c2) const {
	if (is_empty() || is_degenerated()) { // x.is_empty() should not happen if called from compl()
		c1=Interval::ALL_REALS;
		c2=Interval::EMPTY_SET;
		return 1;
	}
	else {
		if (lb()>NEG_INFINITY) {
			c1=Interval(NEG_INFINITY,lb());
			if (ub()<POS_INFINITY) {
				c2=Interval(ub(),POS_INFINITY);
				return 2;
			} else {
				c2=Interval::EMPTY_SET;
				return 1;
			}
		} else if (ub()<POS_INFINITY) {
			c1=Interval(ub(),POS_INFINITY);
			c2=Interval::EMPTY_SET;
			return 1;
		} else {
			c1=c2=Interval::EMPTY_SET;
			return 0;
		}
	}
}
Esempio n. 2
0
 double TRAC_IK::manipPenalty(const KDL::JntArray& arr) {
   double penalty = 1.0;
   for (uint i=0; i< arr.data.size(); i++) {
     if (types[i] == KDL::BasicJointType::Continuous)
       continue;
     double range = ub(i)-lb(i);
     penalty *= ((arr(i)-lb(i))*(ub(i)-arr(i))/(range*range));
   }
   return std::max(0.0,1.0 - exp(-1*penalty));
 }
Esempio n. 3
0
void lb(no *raiz) {										//faz impressão organizada em colchetes
    if(raiz != NULL) {									//mesmo código base da imrpessão pré ordem, já q os primeiros termos representados são os de cima e os da esquerda
        printf("[");									//adiciona um colhete antes de imprimir o numero
        printf("%d", raiz->chave);
        lb(raiz->esq);
        lb(raiz->dir);
        printf("] ");									//fecha o que foi imprimido na execução
    }
    else printf("[] ");									//se verificado que há um espaço vazio, imprime um colchete vazio
}
Esempio n. 4
0
  void TRAC_IK::normalize_limits(const KDL::JntArray& seed, KDL::JntArray& solution) {
    // Make sure rotational joint values are within 1 revolution of middle of
    // limits; then ensure joint limits are met.

    bool improved = false;

    for (uint i=0; i<lb.data.size(); i++) {

      if (types[i] == KDL::BasicJointType::TransJoint)
        continue;

      double target = seed(i);

      if (types[i] == KDL::BasicJointType::RotJoint && types[i]!=KDL::BasicJointType::Continuous)
        target = (ub(i)+lb(i))/2.0;

      double val = solution(i);

      if (val > target+M_PI) {
        //Find actual angle offset
        double diffangle = fmod(val-target,2*M_PI);
        // Add that to upper bound and go back a full rotation
        val = target + diffangle - 2*M_PI;
      }

      if (val < target-M_PI) {
        //Find actual angle offset
        double diffangle = fmod(target-val,2*M_PI);
        // Add that to upper bound and go back a full rotation
        val = target - diffangle + 2*M_PI;
      }

      if (types[i]==KDL::BasicJointType::Continuous) {
        solution(i) = val;
        continue;
      }

      if (val > ub(i)) {
        //Find actual angle offset
        double diffangle = fmod(val-ub(i),2*M_PI);
        // Add that to upper bound and go back a full rotation
        val = ub(i) + diffangle - 2*M_PI;
      }

      if (val < lb(i)) {
        //Find actual angle offset
        double diffangle = fmod(lb(i)-val,2*M_PI);
        // Add that to upper bound and go back a full rotation
        val = lb(i) - diffangle + 2*M_PI;
      }

      solution(i) = val;
    }

  }
Esempio n. 5
0
  void TRAC_IK::initialize() {

    assert(chain.getNrOfJoints()==lb.data.size());
    assert(chain.getNrOfJoints()==ub.data.size());

    jacsolver.reset(new KDL::ChainJntToJacSolver(chain));
    nl_solver.reset(new NLOPT_IK::NLOPT_IK(chain,lb,ub,maxtime,eps,NLOPT_IK::SumSq));
    iksolver.reset(new KDL::ChainIkSolverPos_TL(chain,lb,ub,maxtime,eps,true,true));


    for (uint i=0; i<chain.segments.size(); i++) {
      std::string type = chain.segments[i].getJoint().getTypeName();
      if (type.find("Rot")!=std::string::npos) {
        if (ub(types.size())>=std::numeric_limits<float>::max() && 
            lb(types.size())<=std::numeric_limits<float>::lowest())
          types.push_back(KDL::BasicJointType::Continuous);
        else
          types.push_back(KDL::BasicJointType::RotJoint);
      }
      else if (type.find("Trans")!=std::string::npos)
        types.push_back(KDL::BasicJointType::TransJoint);
    }
    
    assert(types.size()==lb.data.size());


    threads.create_thread(boost::bind(&boost::asio::io_service::run,
                                      &io_service));
    threads.create_thread(boost::bind(&boost::asio::io_service::run,
                                      &io_service));

    initialized = true;
  }
Esempio n. 6
0
void ADMMCut::CalculateX()
{
	// Construct Hessian Matrix for D-Qp problem
	SpMat Q;
	CalculateQ(D_, Q);

	SpMat H2 = Q.transpose() * Q;
	SpMat H = 2 * H1_ + penalty_ * H2;

	// Construct Linear coefficient for x-Qp problem
	a_ = Q.transpose() * lambda_;

	// Inequality constraints A*x <= b
	SpMat A(6 * Fd_, 6 * Fd_);
	A.setZero();
	VX b(6 * Fd_);
	b.setZero();

	// Variable constraints x >= lb, x <= ub
	VX lb(Nd_), ub(Nd_);
	lb.setZero();
	ub.setOnes();

	qp_->solve(H, a_, A, b, W_, d_, lb, ub, x_, NULL, NULL, debug_);
}
Esempio n. 7
0
void TestIndPos::testConjugate3() {
    size_t n = 100;
    Matrix lb(n, 1);
    for (size_t i = 0; i < n; i++) {
        lb[i] = 3.0 + i;
    }
    Function * ind_pos = new IndPos(lb);

    Matrix y(n, 1);

    double f_star;
    int status = ind_pos->callConj(y, f_star);
    _ASSERT(ForBESUtils::is_status_ok(status));
    _ASSERT_NUM_EQ(0.0, f_star, 1e-14);

    y[0] = 1.0;
    status = ind_pos->callConj(y, f_star);
    _ASSERT(ForBESUtils::is_status_ok(status));
    _ASSERT(std::isinf(f_star));

    y[0] = -1.0;
    y[1] = -2.0;
    y[2] = -3.0;
    status = ind_pos->callConj(y, f_star);
    _ASSERT(ForBESUtils::is_status_ok(status));
    _ASSERT_NUM_EQ(-26.0, f_star, 1e-14);


    delete ind_pos;
}
Esempio n. 8
0
 ModEvent
 SetVarImp::excludeI_full(Space& home, int mi, int ma, I& iterator) {
   Iter::Ranges::SingletonAppend<I> si(mi,ma,iterator);
   if (lub.excludeI(home, si)) {
     BndSetRanges ub(lub);
     BndSetRanges lb(glb);
     if (!Iter::Ranges::subset(lb,ub)) {
       glb.become(home, lub);
       glb.card(glb.size());
       lub.card(glb.size());
       return ME_SET_FAILED;
     }
     ModEvent me = ME_SET_LUB;
     if (cardMax() > lub.size()) {
       lub.card(lub.size());
       if (cardMin() > cardMax()) {
         glb.become(home, lub);
         glb.card(glb.size());
         lub.card(glb.size());
         return ME_SET_FAILED;
       }
       me = ME_SET_CLUB;
     }
     if (cardMax() == lub.size() && cardMin() == cardMax()) {
       glb.become(home, lub);
       me = ME_SET_VAL;
     }
     SetDelta d;
     return notify(home, me, d);
   }
   return ME_SET_NONE;
 }
Esempio n. 9
0
/*--------------------------------------------------------*/
int NOMAD::TGP_Model::filter_and_sort_X
(const std::vector<const NOMAD::Eval_Point *> &X          ,
 const NOMAD::Point                            *center     ,
 std::list<const NOMAD::Eval_Point *>          &filtered_X) const
{
    NOMAD::Point              alt_center;
    const NOMAD::Eval_Point *cur = NULL;
    int                       p0  = X.size() , i;

    // alternate center if center==NULL:
    if (!center)
    {
        int          j;
        NOMAD::Point lb(_n0) , ub(_n0);
        for (i = 0 ; i < p0 ; ++i)
        {
            cur = X[i];
            if (test_interpolation_point(cur))
            {
                for (j = 0 ; j < _n0 ; ++j)
                {
                    if (!lb[j].is_defined() || (*cur)[j] < lb[j])
                        lb[j] = (*cur)[j];
                    if (!ub[j].is_defined() || (*cur)[j] > ub[j])
                        ub[j] = (*cur)[j];
                }
            }
        }
        alt_center = NOMAD::Point(_n0);
        for (j = 0 ; j < _n0 ; ++j)
            alt_center[j] = (lb[j] + ub[j]) / 2.0;
    }

    // X_tmp is used to sort the points:
    std::multiset<NOMAD::Model_Sorted_Point> tmp_X;

    for (i = 0 ; i < p0 ; ++i)
    {

        cur = X[i];

        // test if the interpolation point is valid for interpolation:
        if (test_interpolation_point(cur))
        {

            NOMAD::Model_Sorted_Point sorted_pt
            (&NOMAD::Cache::get_modifiable_point(*cur) ,
             (center) ? *center : alt_center);

            tmp_X.insert(sorted_pt);
        }
    }

    // copy the set X_tmp to filtered_X:
    std::multiset<NOMAD::Model_Sorted_Point>::const_iterator it , end = tmp_X.end();
    for (it = tmp_X.begin() ; it != end ; ++it)
        filtered_X.push_back(static_cast<NOMAD::Eval_Point *>(it->get_point()));

    return filtered_X.size();
}
Esempio n. 10
0
TEST(BoundingBox, Intersection){
	Point lb(1,2,0);
	Point ub(2,4,0);
	BoundingBox bb1(lb, ub);
	BoundingBox bb2(lb, ub);

	// Intersection should return an bounding box equal to bb2 and bb1,
	// they are the same bb
	BoundingBox bbIntersection = bb2.intersection(bb1);
	EXPECT_TRUE( bbIntersection.getLb().getX() == bb2.getLb().getX() &&
				bbIntersection.getLb().getY() == bb2.getLb().getY() &&
				bbIntersection.getLb().getZ() == bb2.getLb().getZ());

	EXPECT_TRUE( bbIntersection.getUb().getX() == bb2.getUb().getX() &&
				bbIntersection.getUb().getY() == bb2.getUb().getY() &&
				bbIntersection.getUb().getZ() == bb2.getUb().getZ());

	Point lb3(2,3,0);
	Point ub3(2,4,0);
	BoundingBox bb3(lb3, ub3);
	bbIntersection = bb2.intersection(bb3);
	// lower bound is the value of of bb3
	EXPECT_TRUE( bbIntersection.getLb().getX() == lb3.getX() &&
				bbIntersection.getLb().getY() == lb3.getY() &&
				bbIntersection.getLb().getZ() == lb3.getZ());

	// upper bound should not change
	EXPECT_TRUE( bbIntersection.getUb().getX() == bb2.getUb().getX() &&
				bbIntersection.getUb().getY() == bb2.getUb().getY() &&
				bbIntersection.getUb().getZ() == bb2.getUb().getZ());

}
Esempio n. 11
0
 int getmax(int r)
 {
  int ret = 0;
  for(;r;r-=lb(r))
   ret = max(ret,p[r]);
  return ret;
 }
Esempio n. 12
0
void glpk_wrapper::set_domain(box const & b) {
    assert(!b.is_empty());
    changed = true;
    domain = b;
    for (unsigned int i = 0; i < b.size(); i++) {
        auto interval = b[i];
        double lb = interval.lb();
        double ub = interval.ub();
        if (lb == NEG_INFINITY) {
            if (ub == POS_INFINITY) {
                glp_set_col_bnds(lp, i+1, GLP_FR, lb, ub);
            } else {
                glp_set_col_bnds(lp, i+1, GLP_UP, lb, ub);
            }
        } else {
            if (ub == POS_INFINITY) {
                glp_set_col_bnds(lp, i+1, GLP_LO, lb, ub);
            } else {
                if (lb == ub) {
                    glp_set_col_bnds(lp, i+1, GLP_FX, lb, ub);
                } else {
                    glp_set_col_bnds(lp, i+1, GLP_DB, lb, ub);
                }
            }
        }
    }
}
Esempio n. 13
0
int getmax(int x,int y)
{
 int ret = 0;
 for(;x;x-=lb(x))
  ret = max(ret,s[x].getmax(y));
 return ret;
}
Esempio n. 14
0
bool raycast(game* g, vec2 from, vec2 to) {
	ivec2 cur(fast_floor(from.x), fast_floor(from.y));
	ivec2 end(fast_floor(to.x), fast_floor(to.y));
	ivec2 sign(sign(to.x - from.x), sign(to.y - from.y));
	vec2 abs_delta(abs(to.x - from.x), abs(to.y - from.y));
	vec2 delta_t(vec2(1.0f) / abs_delta);
	vec2 lb(to_vec2(cur));
	vec2 ub(lb + vec2(1.0f));
	vec2 t(vec2((from.x > to.x) ? (from.x - lb.x) : (ub.x - from.x), (from.y > to.y) ? (from.y - lb.y) : (ub.y - from.y)) / abs_delta);

	for(;;) {
		if (g->is_raycast_solid(cur.x, cur.y))
			return true;

		if (t.x <= t.y) {
			if (cur.x == end.x) break;
			t.x += delta_t.x;
			cur.x += sign.x;
		}
		else {
			if (cur.y == end.y) break;
			t.y += delta_t.y;
			cur.y += sign.y;
		}
	}

	return false;
}
Esempio n. 15
0
mga_target_event::mga_target_event(
				 const kep_toolbox::plantes::planet_ptr start,
				 const kep_toolbox::planet::planet_ptr end,
				 const kep_toolbox::epoch t_end,
				 double T_max,
				 bool discount_launcher
		):base(6), m_start(start), m_end(end), m_t_end(t_end), m_T_max(T_max), m_discount_launcher(discount_launcher)
{
	// We check that all planets have equal central body
	if (start->get_mu_central_body() != end->get_mu_central_body()) {
		pagmo_throw(value_error,"The planets do not all have the same mu_central_body");  
	}

	// We check that T_max is positive
	if (T_max <= 0) {
		pagmo_throw(value_error,"T_max must be larger than zero");
	}

	// Now setting the problem bounds
	decision_vector lb(6,0.0), ub(6,1.0);
	lb[0] = 1.; lb[5] = 1e-5;
	ub[0] = T_max; ub[2] = 12000.0; ub[5] = 1-1e-5;

	set_bounds(lb,ub);
}
Esempio n. 16
0
bool core::archive::image_cache::save_all() const
{
    archive::storage_mode mode;
    mode.flags_.write_ = true;
    mode.flags_.truncate_ = true;

    if (!storage_->open(mode))
        return false;

    core::tools::auto_scope lb([this]{ storage_->close(); });

    image_vector_t block;
    for (const auto& image : image_by_msgid_)
    {
        block.emplace_back(image.second);
        if (block.size() >= max_block_size)
        {
            if (!serialize_block(*storage_, block))
                return false;
            block.clear();
        }
    }

    if (!block.empty())
    {
        return serialize_block(*storage_, block);
    }

    return true;
}
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray *prhs[])
{
  if(nrhs!=3 || nlhs != 8)
  {
    mexErrMsgIdAndTxt("Drake:testMultipleTimeLinearPostureConstrainttmex:BadInputs","Usage [num_cnst,cnst_val,iAfun,jAvar,A,cnst_name,lb,ub] = testMultipleTimeLinearPostureConstraintmex(kinCnst,q,t)");
  }
  MultipleTimeLinearPostureConstraint* cnst = (MultipleTimeLinearPostureConstraint*) getDrakeMexPointer(prhs[0]);
  int n_breaks = mxGetNumberOfElements(prhs[2]);
  double* t_ptr = new double[n_breaks];
  memcpy(t_ptr,mxGetPrSafe(prhs[2]),sizeof(double)*n_breaks);
  int nq = cnst->getRobotPointer()->num_positions;
  MatrixXd q(nq,n_breaks);
  if(mxGetM(prhs[1]) != nq || mxGetN(prhs[1]) != n_breaks)
  {
    mexErrMsgIdAndTxt("Drake:testMultipleTimeLinearPostureConstraintmex:BadInputs","Argument 2 must be of size nq*n_breaks");
  }
  memcpy(q.data(),mxGetPrSafe(prhs[1]),sizeof(double)*nq*n_breaks); 
  int num_cnst = cnst->getNumConstraint(t_ptr,n_breaks); 
  VectorXd c(num_cnst);
  cnst->feval(t_ptr,n_breaks,q,c);
  VectorXi iAfun;
  VectorXi jAvar;
  VectorXd A;
  cnst->geval(t_ptr,n_breaks,iAfun,jAvar,A);
  std::vector<std::string> cnst_names;
  cnst->name(t_ptr,n_breaks,cnst_names);
  VectorXd lb(num_cnst);
  VectorXd ub(num_cnst);
  cnst->bounds(t_ptr,n_breaks,lb,ub);
  VectorXd iAfun_tmp(iAfun.size());
  VectorXd jAvar_tmp(jAvar.size());
  for(int i = 0;i<iAfun.size();i++)
  {
    iAfun_tmp(i) = (double) iAfun(i)+1;
    jAvar_tmp(i) = (double) jAvar(i)+1;
  }
  plhs[0] = mxCreateDoubleScalar((double) num_cnst);
  plhs[1] = mxCreateDoubleMatrix(num_cnst,1,mxREAL);
  memcpy(mxGetPrSafe(plhs[1]),c.data(),sizeof(double)*num_cnst);
  plhs[2] = mxCreateDoubleMatrix(iAfun_tmp.size(),1,mxREAL);
  memcpy(mxGetPrSafe(plhs[2]),iAfun_tmp.data(),sizeof(double)*iAfun_tmp.size());
  plhs[3] = mxCreateDoubleMatrix(jAvar_tmp.size(),1,mxREAL);
  memcpy(mxGetPrSafe(plhs[3]),jAvar_tmp.data(),sizeof(double)*jAvar_tmp.size());
  plhs[4] = mxCreateDoubleMatrix(A.size(),1,mxREAL);
  memcpy(mxGetPrSafe(plhs[4]),A.data(),sizeof(double)*A.size());
  int name_ndim = 1;
  mwSize name_dims[] = {(mwSize) num_cnst};
  plhs[5] = mxCreateCellArray(name_ndim,name_dims);
  mxArray *name_ptr;
  for(int i = 0;i<num_cnst;i++)
  {
    name_ptr = mxCreateString(cnst_names[i].c_str());
    mxSetCell(plhs[5],i,name_ptr);
  }
  plhs[6] = mxCreateDoubleMatrix(num_cnst,1,mxREAL);
  plhs[7] = mxCreateDoubleMatrix(num_cnst,1,mxREAL);
  memcpy(mxGetPrSafe(plhs[6]),lb.data(),sizeof(double)*num_cnst);
  memcpy(mxGetPrSafe(plhs[7]),ub.data(),sizeof(double)*num_cnst);
  delete[] t_ptr;
}
Esempio n. 18
0
double Interval::delta(const Interval& x) const {
	if (is_empty()) return 0;
	if (x.is_empty()) return diam();

	// ** warning **
	// checking if *this or x is infinite by
	// testing if the lower/upper bounds are -oo/+oo
	// is not enough because diam() may return +oo even
	// with finite bounds (e.g, very large intervals like [-DBL_MAX,DBL_MAX]).
    // ("almost-unboundedness")

	volatile double d=diam();
	volatile double dx=x.diam();
	// furthermore, if these variables are not declared volatile
	// conditions like d==POS_INFINITY are evaluated
	// to FALSE for intervals like [-DBL_MAX,DBL_MAX] (with -O3 option)
	// while the returned expression (d-dx) evaluates to +oo (instead of 0).

	if (d==POS_INFINITY) {
		//cout << "d=" << d << " dx=" << dx << endl;
		if (dx==POS_INFINITY) {
			double left=(x.lb()==NEG_INFINITY? 0 : x.lb()-lb());
			double right=(x.ub()==POS_INFINITY? 0 : ub()-x.ub());
			//cout << "left=" << left << " right=" << right << endl;
			return left+right;
		} else
			return POS_INFINITY;
	}
	else return d-dx;
}
Esempio n. 19
0
File: 3.cpp Progetto: fyh/training
int getsum(int r) {
	int ret = 0;
	for (int i = r; i >= 0; i -= lb(i)) {
		ret += sum[i];
	}
	return ret;
}
Esempio n. 20
0
int FiberMeshFairing::solveLaplacianCurvatureEnerge()
{
    std::vector< Scalar > lb(mesh_->n_vertices_());
    std::vector< Scalar > x(mesh_->n_vertices_());
    if(!ls_laplacian_solver_->solve(lb,c_,x))
    {
        return 0;
    }
    Scalar re = 0;
    Scalar total = 0;
    for(size_t i=0; i < c_.size(); i++)
    {
        re += sqrt( (c_[i] - x[i]) * (c_[i] - x[i]));
        total += sqrt(c_[i] * c_[i]);
    }

    DebugLog<<re / total <<std::endl;
    if(re < total * tolerance_)
    {
        return -1;
    }
    c_.clear();

    for(size_t i=0; i < mesh_->n_vertices_(); i++)
    {
        c_.push_back(x[i]);
    }
    return 1;
}
Esempio n. 21
0
void demography  :: EndContact(b2Contact* contact)
{
    bool A = contact->GetFixtureA()->IsSensor();
    bool B = contact->GetFixtureB()->IsSensor();
    if(A ^ B)
    {
        lb("sens",432);
        //auto 
        //    bodyA = contact->GetFixtureA()->GetBody(),
        //    bodyB = contact->GetFixtureB()->GetBody();
        //auto
        //    ga = contact->GetFixtureA()->GetFilterData().groupIndex,
        //    gb = contact->GetFixtureB()->GetFilterData().groupIndex;

        //if(ga && gb)
        //{
        //    nears[bodyA] .erase(bodyB);
        //    nears[bodyB] .erase(bodyA);
        //}
        //else
        //{
        //    if(A) targets.erase(bodyA);
        //    else  targets.erase(bodyB);
        //}
    }
}
Esempio n. 22
0
void ofxMesh::addFace(ofRectangle r) {
    ofVec2f lt(r.x,r.y);
    ofVec2f rt(r.x+r.width,r.y);
    ofVec2f rb(r.x+r.width,r.y+r.height);
    ofVec2f lb(r.x,r.y+r.height);
    addFace(lt,lb,rb,rt);
}
Esempio n. 23
0
File: One.cpp Progetto: alviano/wasp
bool
One::foundUnsat()
{
    ++numberOfCalls;
    
    const Clause* core = solver.getUnsatCore();
    assert( core != NULL );
    const Clause& unsatCore = *( core );
    
    //The incoherence does not depend on weak constraints
    if( unsatCore.size() == 0 )
        return false;    
        
    solver.clearConflictStatus();
    solver.unrollToZero();

    for( unsigned int i = 0; i < unsatCore.size(); i++ )
        visit( unsatCore[ i ].getVariable() );
    
    vector< Literal > literals;
    vector< uint64_t > weights;

    unsigned int n = 0;
    uint64_t minWeight = computeMinWeight();
    if( !processCoreOne( literals, weights, minWeight, n ) || !addAggregateOne( literals, weights, n + 1 ) )
        return false;
    incrementLb( minWeight );
    solver.foundLowerBound( lb() ); 
    
    return true;
}
Esempio n. 24
0
void dfs(int now){
	
	if( now==n-1 ){
		int c = (1<<n) - 1 - x;
		if( !illegal(c) ) ++ans;
	}
	
	else {
		int less = (1<<n)-1-x;
		while( less ){
			int c = lb(less);
			less-=c;
			if( illegal(c) ) continue;
			else {	
				x+=c;
				z+=c<<now;
				s+=c<<(n-now-1);
				dfs(now+1);
				x-=c;
				z-=c<<now;
				s-=c<<(n-now-1);	
			}
		}	
	}
}
Esempio n. 25
0
bool OsiRowCut::infeasible(const OsiSolverInterface &) const
{
  if (lb() > ub())
    return true;

  return false;
}
Esempio n. 26
0
int getsum(int dep,int tx,int ty)
{
    int x = dep;
    sum = 0;
    for(; x; x -= lb(x))
        query(c[x],1,n,tx,ty);
    return sum;
}
Esempio n. 27
0
void Type_Contiguous::unserialize(const void* contiguous_buf, void* noncontiguous_buf, int count, MPI_Op op)
{
  const char* contiguous_buf_char = static_cast<const char*>(contiguous_buf);
  char* noncontiguous_buf_char = static_cast<char*>(noncontiguous_buf)+lb();
  int n= count*block_count_;
  if(op!=MPI_OP_NULL)
    op->apply( contiguous_buf_char, noncontiguous_buf_char, &n, old_type_);
}
void mexFunction(int nlhs,mxArray* plhs[], int nrhs, const mxArray * prhs[])
{
  if(nrhs!=3 || nlhs != 7)
  {
    mexErrMsgIdAndTxt("Drake:testMultipleTimeKinCnstmex:BadInputs","Usage [type,num_cnst,cnst_val,dcnst_val,cnst_name,lb,ub] = testMultipleTimeKinCnstmex(kinCnst,q,t)");
  }
  MultipleTimeKinematicConstraint* cnst = (MultipleTimeKinematicConstraint*) getDrakeMexPointer(prhs[0]);
  int n_breaks = mxGetNumberOfElements(prhs[2]);
  double* t_ptr = new double[n_breaks];
  memcpy(t_ptr,mxGetPrSafe(prhs[2]),sizeof(double)*n_breaks);
  int nq = cnst->getRobotPointer()->num_positions;
  MatrixXd q(nq,n_breaks);
  if(mxGetM(prhs[1]) != nq || mxGetN(prhs[1]) != n_breaks)
  {
    mexErrMsgIdAndTxt("Drake:testMultipleTimeKinCnstmex:BadInputs","Argument 2 must be of size nq*n_breaks");
  }
  memcpy(q.data(),mxGetPrSafe(prhs[1]),sizeof(double)*nq*n_breaks); 
  int type = cnst->getType();
  int num_cnst = cnst->getNumConstraint(t_ptr,n_breaks); 
  VectorXd c(num_cnst);
  MatrixXd dc(num_cnst,nq*n_breaks);
  cnst->eval(t_ptr,n_breaks,q,c,dc);
  VectorXd lb(num_cnst);
  VectorXd ub(num_cnst);
  cnst->bounds(t_ptr,n_breaks,lb,ub);
  std::vector<std::string> cnst_names;
  cnst->name(t_ptr,n_breaks,cnst_names);
  int retvec_size;
  if(num_cnst == 0)
  {
    retvec_size = 0;
  }
  else
  {
    retvec_size = 1;
  }
  plhs[0] = mxCreateDoubleScalar((double) type);
  plhs[1] = mxCreateDoubleScalar((double) num_cnst);
  plhs[2] = mxCreateDoubleMatrix(num_cnst,retvec_size,mxREAL);
  memcpy(mxGetPrSafe(plhs[2]),c.data(),sizeof(double)*num_cnst);
  plhs[3] = mxCreateDoubleMatrix(num_cnst,nq*n_breaks,mxREAL);
  memcpy(mxGetPrSafe(plhs[3]),dc.data(),sizeof(double)*num_cnst*nq*n_breaks);
  int name_ndim = 1;
  mwSize name_dims[] = {(mwSize) num_cnst};
  plhs[4] = mxCreateCellArray(name_ndim,name_dims);
  mxArray *name_ptr;
  for(int i = 0;i<num_cnst;i++)
  {
    name_ptr = mxCreateString(cnst_names[i].c_str());
    mxSetCell(plhs[4],i,name_ptr);
  }
  plhs[5] = mxCreateDoubleMatrix(num_cnst,retvec_size,mxREAL);
  plhs[6] = mxCreateDoubleMatrix(num_cnst,retvec_size,mxREAL);
  memcpy(mxGetPrSafe(plhs[5]),lb.data(),sizeof(double)*num_cnst);
  memcpy(mxGetPrSafe(plhs[6]),ub.data(),sizeof(double)*num_cnst);
  delete[] t_ptr;
}
Esempio n. 29
0
  //-----------------------------------------------------------------------------------------------------
  bool miner::find_nonce_for_given_block(crypto::cn_context &context, Block& bl, const difficulty_type& diffic) {

    unsigned nthreads = std::thread::hardware_concurrency();

    if (nthreads > 0 && diffic > 5) {
      std::vector<std::future<void>> threads(nthreads);
      std::atomic<uint32_t> foundNonce;
      std::atomic<bool> found(false);
      uint32_t startNonce = crypto::rand<uint32_t>();

      for (unsigned i = 0; i < nthreads; ++i) {
        threads[i] = std::async(std::launch::async, [&, i]() {
          crypto::cn_context localctx;
          crypto::hash h;

          Block lb(bl); // copy to local block

          for (uint32_t nonce = startNonce + i; !found; nonce += nthreads) {
            lb.nonce = nonce;

            if (!get_block_longhash(localctx, lb, h)) {
              return;
            }

            if (check_hash(h, diffic)) {
              foundNonce = nonce;
              found = true;
              return;
            }
          }
        });
      }

      for (auto& t : threads) {
        t.wait();
      }

      if (found) {
        bl.nonce = foundNonce.load();
      }

      return found;
    } else {
      for (; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++) {
        crypto::hash h;
        if (!get_block_longhash(context, bl, h)) {
          return false;
        }

        if (check_hash(h, diffic)) {
          return true;
        }
      }
    }

    return false;
  }
Esempio n. 30
0
void cScSetup::Store(bool AsIs)
{
  if(ScOpts) ScOpts->Store(AsIs);
  cSystems::ConfigStore(AsIs);
  if(LogOpts) LogOpts->Store(AsIs);
  cLineBuff lb(128);
  if(cLogging::GetConfig(&lb))
    ScPlugin->SetupStore("LogConfig",lb.Line());
}