コード例 #1
0
LinAlg::Matrix<float> SistemasLineares::GaussJacobi(LinAlg::Matrix<float> MatrizUni, unsigned MaxIterations)
{
    //Matriz Resposta
    LinAlg::Matrix<float> MatrizRes(MaxIterations, MatrizUni.getNumberOfColumns());
    LinAlg::Matrix<float> C (MatrizUni.getNumberOfRows(), MatrizUni.getNumberOfColumns() - 1);
    LinAlg::Matrix<float> g (MatrizUni.getNumberOfRows(), 1);
    LinAlg::Matrix<float> x0(C.getNumberOfColumns(), 1);

    //    //Deixa o vetor de chute inicial padronizado como vetor linha
    if(this->X0.getNumberOfColumns() < this->X0.getNumberOfRows())
        ~this->X0;

    //    //Insere o chute inicial na Matriz resposta
    for(unsigned i = 1; i < MatrizRes.getNumberOfColumns() - 1; ++i)
        x0(1,i) = this->X0(1,i);

        //Laço para contar as linhas da MatrizUni e Matriz C.
        for(unsigned i = 1; i <= MatrizUni.getNumberOfRows(); ++i)
        {   //Laço para contar as colunas da MAtrizUni e Matriz C.
            for(unsigned j = 1; j < MatrizUni.getNumberOfColumns(); ++j)
            {
                if(i != j)
                    C(i,j) = - MatrizUni(i,j)/MatrizUni(i,i);//Matriz com a diagonal zerada.
            }
            g(i,1) = MatrizUni(i,MatrizUni.getNumberOfColumns()) / MatrizUni(i,i);//Matriz dos termos independentes.
        }

        MatrizRes = ~x0;
        for(unsigned k = 1; k < MaxIterations; ++k)
        {
            x0 =  (C * x0) + g;
            MatrizRes = MatrizRes || ~x0;
        }
    return MatrizRes;
}
コード例 #2
0
ファイル: CVMath.cpp プロジェクト: rprata/computer-vision
void CVMath::setupMatrixM1()
{
	Line r1 = Points::getInstance().getR1();
	Line r2 = Points::getInstance().getR2();
	Line r3 = Points::getInstance().getR3();
	Line r4 = Points::getInstance().getR4();
	
	l0 << r1.x, r1.y, r1.z;
	l1 << r2.x, r2.y, r2.z;
	l2 << r3.x, r3.y, r3.z;
	l3 << r4.x, r4.y, r4.z;

	x0 = l0.cross(l1);
	x0 << x0(0)/x0(2), x0(1)/x0(2), 1;
	x1 = l2.cross(l3);
	x1 << x1(0)/x1(2), x1(1)/x1(2), 1;

	l =  x0.cross(x1);

	Hp = MatrixXd(3, 3);
	Hp << 1, 0, 0,
	     0, 1, 0,
	     l(0), l(1), l(2);
	std::cout << Hp << std::endl;
	Vector3d l0;
	Vector3d l1;
	Hp_INV = MatrixXd(3, 3);
	Hp_INV = Hp.inverse().eval();
	std::cout << Hp_INV << std::endl;
}
コード例 #3
0
Vector Initialize()
{
 	Vector x0(3, 0.0);

	x0(0) = 10000;
	return x0;
} 
コード例 #4
0
ファイル: mywidget.cpp プロジェクト: gehirn/lab3
void MyWidget::process()
{
    ui->plainTextEdit->clear();
    variant = ui->comboBox->currentIndex();
    print(QString("Variant %1").arg(variant));
    print(QString("[%1; %2]").arg(x0(), 0, 'g', 5).arg(xFinish(), 0, 'g', 3));

    //calc

    qreal x = x0(), y = y0(), z = z0();
    for (int i = 1; x < xFinish() || qFuzzyCompare(x, xFinish()); ++i)
    {
        qreal k1 = h() * f(x, y, z);
        qreal q1 = h() * g(x, y, z);

        qreal k2 = h() * f(x + h() / 2.0, y + k1 / 2.0, z + q1 / 2.0);
        qreal q2 = h() * g(x + h() / 2.0, y + k1 / 2.0, z + q1 / 2.0);

        qreal k3 = h() * f(x + h() / 2.0, y + k2 / 2.0, z + q2 / 2.0);
        qreal q3 = h() * g(x + h() / 2.0, y + k2 / 2.0, z + q2 / 2.0);

        qreal k4 = h() * f(x + h(), y + k3, z + q3);
        qreal q4 = h() * g(x + h(), y + k3, z + q3);

        print(QString("#%1").arg(i));
        print(QString("y(%1) = %2").arg(x, 0, 'g', 5).arg(y, 0, 'g', 5));
        print(QString("y_ex(%1) = %2").arg(x, 0, 'g',5).arg(yt(x), 0, 'g', 5));
        print(QString("error(%1) = %2").arg(x, 0, 'g',5).arg(ypo(y, x), 0, 'g', 5));

        x += h();
        y += (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0;
        z += (q1 + 2.0 * q2 + 2.0 * q3 + q4) / 6.0;

    }
}
コード例 #5
0
ファイル: opb_fonc_a_trou.cpp プロジェクト: rpankka/micmac
         void FoncATrou_OPB_Comp<Type>::calc_buf
         (
               INT **     output,
               INT ***    input
         )
{
    for (INT d= 0; d<dim_out() ; d++)
    {
        convert
        (
             output[d]+x0(),
             input[std::min(d,dim_in()-1)][0]+x0(),
             tx()
        );
    }

     INT a0 = _cpt[ycur()];
     INT a1 = _cpt[ycur()+1];
     for (INT a=a0 ; a<a1 ; a++)
     {
         INT x = _tx[a];
         for (INT d= 0; d<dim_out() ; d++)
             output[d][x] = _v[d][a];
     }
}
コード例 #6
0
ファイル: xRungeKutta4.cpp プロジェクト: loongfee/ossim-svn
void xRungeKutta4 :: halfTest (void)
{
	gpstk::Matrix<double> x0(2,1), truncError(2,1);
	x0(0,0) = 0.001; // Initial angle in radians
	x0(1,0) = 0.0; // Initial angular velocity in radians/second
	
	PendulumIntegrator pModel(x0,0.);
	
	double g = 9.81, L = 1.0;
	pModel.setPhysics(g,L);
	
	double deltaT = .00001;  // Step size in seconds for integrator
	
	double time = 0;
	double Nper = 2.5; // number of periods
	
	double addError = 0; //Total Error for angle
	double addDotError = 0; //Total Error for rate of change in angle
	
	long count = 0;
	
	while (pModel.getTime() < Nper * (2*3.14159265/sqrt(g/L)))
	{
		pModel.integrateTo((count++)*deltaT,truncError);
		addError += fabs(truncError(0,0));
		addDotError += fabs(truncError(1,0));
	}
	
	CPPUNIT_ASSERT_DOUBLES_EQUAL(-x0(0,0),pModel.getState()(0,0),addError*2);
	CPPUNIT_ASSERT_DOUBLES_EQUAL(x0(1,0),pModel.getState()(1,0),addDotError*2);
	
}
コード例 #7
0
ファイル: nnls_solver.cpp プロジェクト: n7wilson/NNLM
mat nnls_solver(const mat & H, mat mu, const umat & mask, int max_iter, double rel_tol, int n_threads)
{
	/****************************************************************************************************
	 * Description: sequential Coordinate-wise algorithm for non-negative least square regression problem
	 * 		A x = b, s.t. x[!m] >= 0, x[m] == 0
	 * Arguments:
	 * 	H         : A^T * A
	 * 	mu        : -A^T * b
	 * 	mask      : a mask matrix (m) of same dim of x
	 * 	max_iter  : maximum number of iterations
	 * 	rel_tol   : stop criterion, minimum change on x between two successive iteration
	 * 	n_threads : number of threads
	 * Return:
	 * 	x : solution to argmin_{x, x>=0} ||Ax - b||_F^2
	 * Reference:
	 * 	http://cmp.felk.cvut.cz/ftp/articles/franc/Franc-TR-2005-06.pdf
	 * Author:
	 * 	Eric Xihui Lin <*****@*****.**>
	 * Version:
	 * 	2015-11-16
	 ****************************************************************************************************/

	mat x(H.n_cols, mu.n_cols, fill::zeros);
	if (n_threads < 0) n_threads = 0;
	bool is_masked = !mask.empty();


	#pragma omp parallel for num_threads(n_threads) schedule(dynamic)
	for (int j = 0; j < mu.n_cols; j++)
	{
		if (is_masked && arma::all(mask.col(j))) 
			continue;
		vec x0(H.n_cols);
		// x0.fill(-9999);
		double tmp;
		int i = 0;
		double err1, err2 = 9999;
		do {
			// break if all entries of col_j are masked
			x0 = x.col(j);
			err1 = err2;
			err2 = 0;
			for (int k = 0; k < H.n_cols; k++)
			{
				if (is_masked && mask(k,j) > 0) continue;
				tmp = x(k,j) - mu(k,j) / H(k,k);
				if (tmp < 0) tmp = 0;
				if (tmp != x(k,j))
				{
					mu.col(j) += (tmp - x(k,j)) * H.col(k);
				}
				x(k,j) = tmp;
				tmp = std::abs(x(k,j) - x0(k));
				if (tmp > err2) err2 = tmp;
			}
		} while(++i < max_iter && std::abs(err1 - err2) / (err1 + 1e-9) > rel_tol);
	}
	return x;
}
コード例 #8
0
Vector Initialize()
{
 	Vector x0(3, 0.0);

	x0(0) = 400;
	x0(1) = 798; 
	return x0;
} 
コード例 #9
0
ファイル: minimizerthread.cpp プロジェクト: chivalry123/otkpp
void MinimizerThread::run()
{
  boost::numeric::ublas::vector< double > x0(2);
  x0(0) = x0_;
  x0(1) = y0_;
  
  if(!solver_->isExternalSolver())
  {
    NativeSolver *nativeSolver = dynamic_cast< NativeSolver * >(solver_);
    
    if(C_ != NULL)
      solver_->setup(*objFunc_, x0, Solver::DefaultSetup(), *C_);
    else
      solver_->setup(*objFunc_, x0, Solver::DefaultSetup(), NoConstraints());
    results_.iterates.clear();
    results_.iterates.push_back(x0);
    if(nativeSolver->getM() > 1)
    {
      results_.iteratePointSets.clear();
      results_.iteratePointSets.push_back(nativeSolver->getXArray());
    }
    
    unsigned int nIter = 0;
    NativeSolver::IterationStatus status = NativeSolver::ITERATION_CONTINUE;
    while(status == NativeSolver::ITERATION_CONTINUE && 
          (nativeSolver->hasBuiltInStoppingCriterion() || 
           !stopCrit_->test(*nativeSolver)) && 
          nIter < 10000 && !terminationFlag_)
    {
      status = nativeSolver->iterate();
      results_.iterates.push_back(nativeSolver->getX());
      if(nativeSolver->getM() > 1)
        results_.iteratePointSets.push_back(nativeSolver->getXArray());
      nIter++;
    }
    results_.xMin = nativeSolver->getX()[0];
    results_.yMin = nativeSolver->getX()[1];
    results_.fMin = nativeSolver->getFVal();
    results_.numIter = nativeSolver->getNumIter();
    results_.numFuncEval = nativeSolver->getNumFuncEval();
    results_.numGradEval = nativeSolver->getNumGradEval();
  }
  else
  {
    // TODO: stopping criterion for LMBM?
    boost::shared_ptr< Solver::Results > results = 
      solver_->solve(*objFunc_, x0, GradNormTest(1e-8));
    
    results_.xMin        = results->xMin[0];
    results_.yMin        = results->xMin[1];
    results_.fMin        = results->fMin;
    results_.numIter     = results->numIter;
    results_.numFuncEval = results->numFuncEval;
    results_.numGradEval = results->numGradEval;
    //results_.iterates    = results->iterates; // TODO: iterates?
  }
}
コード例 #10
0
ファイル: bslalg_typetraits.t.cpp プロジェクト: StefPac/bde
//..
// Our verification program simply instantiate several 'MyGenericContainer'
// templates with the two test types above, and checks that the allocator
// slot is as expected:
//..
    int usageExample()
    {
        bslma::TestAllocator ta0;
        bslma::TestAllocator ta1;
//..
// With 'MyTestTypeWithNoBslmaAllocatorTraits', the slot should never be set.
//..
        MyTestTypeWithNoBslmaAllocatorTraits x;

        allocSlot = &ta0;
        MyGenericContainer<MyTestTypeWithNoBslmaAllocatorTraits> x0(x);
        ASSERT(&ta0 == allocSlot);

        allocSlot = &ta0;
        MyGenericContainer<MyTestTypeWithNoBslmaAllocatorTraits> x1(x, &ta1);
        ASSERT(&ta0 == allocSlot);
//..
// With 'MyTestTypeWithBslmaAllocatorTraits', the slot should be set to the
// allocator argument, or to 0 if not specified:
//..
        MyTestTypeWithBslmaAllocatorTraits y;

        allocSlot = &ta0;
        MyGenericContainer<MyTestTypeWithBslmaAllocatorTraits> y0(y);
        ASSERT(0 == allocSlot);

        allocSlot = &ta0;
        MyGenericContainer<MyTestTypeWithBslmaAllocatorTraits> y1(y, &ta1);
        ASSERT(&ta1 == allocSlot);

        return 0;
    }
コード例 #11
0
ファイル: Bidomain.cpp プロジェクト: certik/nektar
    void Bidomain::DoOdeRhs(
            const Array<OneD, const  Array<OneD, NekDouble> >&inarray,
            Array<OneD,        Array<OneD, NekDouble> >&outarray,
            const NekDouble time)
    {
        int nq = m_fields[0]->GetNpoints();
        m_cell->TimeIntegrate(inarray, outarray, time);
        if (m_stimDuration > 0 && time < m_stimDuration)
        {
            Array<OneD,NekDouble> x0(nq);
            Array<OneD,NekDouble> x1(nq);
            Array<OneD,NekDouble> x2(nq);
            Array<OneD,NekDouble> result(nq);

            // get the coordinates
            m_fields[0]->GetCoords(x0,x1,x2);

            LibUtilities::EquationSharedPtr ifunc
                    = m_session->GetFunction("Stimulus", "u");
            ifunc->Evaluate(x0,x1,x2,time, result);

            Vmath::Vadd(nq, outarray[0], 1, result, 1, outarray[0], 1);
        }        
        Vmath::Smul(nq, 1.0/m_capMembrane, outarray[0], 1, outarray[0], 1);
    }
コード例 #12
0
void MainWindow::plot3(QCustomPlot *customPlot)
{
  QVector<double> x0(pts), y0(pts);

  update_w(w,1.0);
  double y_inc = 1.0; 
  for (int i=0; i<pts; ++i)   {
    x0[i] = (double)0.5*i/pts;
    y0[i] = y_inc*(w[i]);
  }

  customPlot->graph()->setData(x0, y0);
  customPlot->graph()->setLineStyle(QCPGraph::lsLine); 
  customPlot->graph()->setScatterStyle(QCPScatterStyle::ssNone); // (QCP::ScatterStyle)(rand()%9+1));
  QPen graphPen;
  graphPen.setColor(QColor(Qt::GlobalColor(5+graph_counter)));
  graphPen.setWidthF(2);
  customPlot->graph()->setPen(graphPen);
  customPlot->xAxis->setRange(0,0.5);
  customPlot->yAxis->setRange(-90,10);
  customPlot->legend->setVisible(true);
  //  customPlot->setInteraction(QCustomPlot::iSelectPlottables);
  customPlot->graph()->setName(QString(shape.c_str()));
  customPlot->replot();
}
コード例 #13
0
QgsLineString *QgsMapToolAddRectangle::rectangleToLinestring( const bool isOriented ) const
{
  std::unique_ptr<QgsLineString> ext( new QgsLineString() );
  if ( mRectangle.isEmpty() )
  {
    return ext.release();
  }

  QgsPoint x0( mRectangle.xMinimum(), mRectangle.yMinimum() );

  QgsPoint x1, x2, x3;
  if ( isOriented )
  {
    const double perpendicular = 90.0 * mSide;
    x1 = x0.project( mDistance1, mAzimuth );
    x3 = x0.project( mDistance2, mAzimuth + perpendicular );
    x2 = x1.project( mDistance2, mAzimuth + perpendicular );
  }
  else
  {
    x1 = QgsPoint( mRectangle.xMinimum(), mRectangle.yMaximum() );
    x2 = QgsPoint( mRectangle.xMaximum(), mRectangle.yMaximum() );
    x3 = QgsPoint( mRectangle.xMaximum(), mRectangle.yMinimum() );
  }
  ext->addVertex( x0 );
  ext->addVertex( x1 );
  ext->addVertex( x2 );
  ext->addVertex( x3 );
  ext->addVertex( x0 );

  return ext.release();
}
コード例 #14
0
RANDOM_HILL_CLIMBING::Parameter RANDOM_HILL_CLIMBING::move(RANDOM_HILL_CLIMBING::Parameter par)
{
	boost::variate_generator<RNG&, boost::uniform_real<Float_t> > r(_rng, boost::uniform_real<Float_t>(-1,1));
	Parameter result;
	
	Float_t factor=4;
	
	Float_t maxpos=0.1*factor;
	Float_t maxang=osg::PI/45*factor;
	do
	{
		result._pos=Vec3_t(r(), r(), r())*maxpos;
	} while (result._pos.length()>maxpos);
	result._pos=par._pos+result._pos;
	
	boost::variate_generator<RNG&, boost::uniform_real<Float_t> > rsimple(_rng, boost::uniform_real<Float_t>(0,1));
	Float_t x0(rsimple());
	Float_t t1(2*osg::PI*rsimple()), t2(2*osg::PI*rsimple());
	Float_t s1(sin(t1)), s2(sin(t2)), c1(cos(t1)), c2(cos(t2));
	Float_t r1(sqrt(1-x0)), r2(sqrt(x0));
	Quat_t randomori=Quat_t(s1*r1, c1*r1, s2*r2, c2*r2);
	result._ori.slerp(maxang, Quat_t(), randomori);
	Quat_t temp=par._ori*result._ori;
	result._ori=temp;
	
	// bond rotatio
	result._bond=vector<Float_t>(_fit->RotCount());
	for (unsigned int i=0; i!=_fit->RotCount(); ++i)
	{
		result._bond[i]=par._bond[i]+r()*maxang;
	}
	return result;
}
コード例 #15
0
ファイル: gauss.hpp プロジェクト: gregvw/legendre-gauss
int gauss(dvec& x, dvec& w) {

    int n = x.size();
    double dist = 1;
    double tol = 1e-15;
    int iter = 0;

    // Use Chebyshev-Gauss nodes and initial guess
    initguess(x);
//    chebnodes(x);

    dvec x0(x);
    dvec L(n,0.0);
    dvec Lp(n,0.0);
    dvec a(n,0.0);
    dvec b(n,0.0);

    rec_legendre(a,b);

    // Iteratively correct nodes with Newton's method
    while(dist>tol) {     
        newton_step(a,b,x,L,Lp);
        dist = dist_max(x,x0); 
        ++iter;
        x0 = x;
    } 

    // Compute Weights
    for(int i=0;i<n;++i){
        w[i] = 2.0/((1-x[i]*x[i])*(Lp[i]*Lp[i]));
    }

    return iter;
}
コード例 #16
0
ファイル: mainwindow.cpp プロジェクト: GeneKong/spuce
void MainWindow::plot2(QCustomPlot *customPlot)
{
  QVector<double> x0(pts), y0(pts);

  update_w(w,1.0);
  double y_inc = 1.0; 
  for (int i=0; i<pts; ++i)   {
    x0[i] = (double)0.5*i/pts;
    y0[i] = y_inc*(w[i]);
  }
  order = get_order();
  ui->order->setText(QApplication::translate("MainWindow", std::to_string(order).c_str(), 0));
  ui->ripple->setText(QApplication::translate("MainWindow", std::to_string(ripple()).c_str(), 0));
  ui->fc->setText(QApplication::translate("MainWindow", std::to_string(fc()).c_str(), 0));
  
  customPlot->graph()->setData(x0, y0);
  customPlot->graph()->setLineStyle(QCPGraph::lsLine); //(QCPGraph::LineStyle)(rand()%5+1));
  customPlot->graph()->setScatterStyle(QCPScatterStyle::ssNone); // (QCP::ScatterStyle)(rand()%9+1));
  QPen graphPen;
  //  graphPen.setColor(QColor(rand()%245+10, rand()%245+10, rand()%245+10));
  //graphPen.setWidthF(rand()/(double)RAND_MAX*2+1);

  graph_counter++;
  graph_counter = graph_counter%9;
  graphPen.setColor(QColor(Qt::GlobalColor(5+graph_counter)));
  graphPen.setWidthF(2);
  customPlot->graph()->setPen(graphPen);
  customPlot->xAxis->setRange(0,0.5);
  customPlot->yAxis->setRange(-90,10);
  customPlot->legend->setVisible(true);
  //  customPlot->setInteraction(QCustomPlot::iSelectPlottables);
  customPlot->graph()->setName(QString(shape.c_str()));
  customPlot->replot();
}
コード例 #17
0
int main(int argc, char **argv) {
    
    vctr x0(2);
    vctr u(1);
    x0.at(0)=0.1;
    x0.at(1)=0.0;
    u.at(0)=0.0;
    
    double dt_max=0.1;
    double state_dim=2;
    double control_dim=1;
    double tspan=2.0*M_PI;
    RK4 sys(&flow,dt_max,state_dim,control_dim);
    traj sol = sys.sim(tspan,x0,u);
    
    sys.print_traj(sol);
    printf("cost: %f\n",cost(sol));
    
    //Plot result
    vctr path(sol.time.size());
    for(int i=0;i<sol.path.size();i++)
    {
        path.at(i)=sol.path[i][0];
    }
    
    plt::plot(sol.time,path);
    plt::xlim(0, (int) ceil(sol.time.back()));
    plt::show();
    //plt::save("./basic.png");
    
    
    return 0;
}
コード例 #18
0
ファイル: luksan_vlcek_3.cpp プロジェクト: YS-L/pagmo
/// Implementation of the sparsity structure
void luksan_vlcek_3::set_sparsity(int &lenG, std::vector<int> &iGfun, std::vector<int> &jGvar) const
{
	//Initial point
	decision_vector x0(get_dimension(),1);
	//Numerical procedure
	estimate_sparsity(x0, lenG, iGfun, jGvar);
}
コード例 #19
0
    ApproximateES(size_t _N, double _lambda_min, double _lambda_max, EnergyMinimizer* _m , float* _x0 = NULL, size_t _max_iter = 10000, int _verbosity = 0, float* _x1 = NULL):
        kmc(_lambda_min, _lambda_max), 
        lambda_min(_lambda_min), 
        lambda_max(_lambda_max), 
        N(_N), 
        minimizer(_m), 
        max_iter(_max_iter), 
        verbosity(_verbosity) 
    {
        e1 = e2 = e3 = 0;
        short_array x0( new float[N] );
        short_array x1( new float[N] );
        for(size_t i = 0; i < N; i++) // copy
        {
            if(_x0 != NULL )
                x0[i] = _x0[i];
            else x0[i] = 0;

            if(_x1 != NULL )
                x1[i] = _x1[i];
            else x1[i] = x0[i];
        }
        Undefined u1(lambda_min, x0, x0);
        Undefined u2(lambda_max, x1, x1);
        Lambda.push(u1);
        Lambda.push(u2);

        labelings.push_back( x0 );
        labelings.push_back( x1 );
    }
コード例 #20
0
ファイル: dixon.cpp プロジェクト: Aleksandar7kr/ETU
Matrix dixon(Parser parser, const Matrix& x)
{
    Matrix x0(x);
    Matrix x1(x);
    Matrix p(x);
    unsigned k = 0;
    do
    {
        k++;
        x0 = x1;
        if (k == 1)
        {
            p = -1*grad(parser, x0);
        }
        else
        {
            double beta = -pow(grad(parser,x0).norm(),2)/getScalarPr(p,-p);
            p = -1*grad(parser, x0) + beta*p;
        }
        double alpha = powell(parser,x0,p,swenn_1(parser, x0,p,1));
        x1 = x0 + p*alpha;
    }    while(k < 100 && grad(parser,x0).norm() > myEPS && myEPS && fabs(parser.f(x0)-parser.f(x1))>myEPS);

    qDebug() << "iteration = " << k;
    return x1;
}
コード例 #21
0
RANDOM_HILL_CLIMBING::Parameter RANDOM_HILL_CLIMBING::init_new_Parameter()
{
	boost::variate_generator<RNG&, boost::uniform_real<Float_t> > r(_rng, boost::uniform_real<Float_t>(-1,1));
	Parameter result;
	// position
	do
	{
		result._pos=_center+Vec3_t(r() ,r(), r())*_radius;
	} while ((_center-result._pos).length()>_radius);
	
	// orientation
	// random quaternion
	// Ken Shoemake
	// UNIFORM RANDOM ROTATIONS
	// In D. Kirk, editor, Graphics Gems III, pages 124-132. Academic, New York, 1992.
	boost::variate_generator<RNG&, boost::uniform_real<Float_t> > 
	rsimple(_rng, boost::uniform_real<Float_t>(0,1));
	Float_t x0(rsimple());
	Float_t t1(2*osg::PI*rsimple()), t2(2*osg::PI*rsimple());
	Float_t s1(sin(t1)), s2(sin(t2)), c1(cos(t1)), c2(cos(t2));
	Float_t r1(sqrt(1-x0)), r2(sqrt(x0));
	result._ori=Quat_t(s1*r1, c1*r1, s2*r2, c2*r2);
	
	// bond rotation
	result._bond=vector<Float_t>(_fit->RotCount());
	for (unsigned int i=0; i!=_fit->RotCount(); ++i)
	{
		result._bond[i]=r()*osg::PI;
	}
	return result;
}
コード例 #22
0
ファイル: pso.cpp プロジェクト: cbaldauf/paradocks
PSO::Particle PSO::init_new_Particle()
{
	Float_t max_v=_radius/4;
	Float_t max_a=osg::PI/4;
	
	boost::variate_generator<RNG&, boost::uniform_real<Float_t> > r(_rng, boost::uniform_real<Float_t>(-1,1));
	Particle result;
	// position
	do
	{
		result._pos=_center+Vec3_t(r() ,r(), r())*_radius;
	} while ((_center-result._pos).length()>_radius);
	result._pb=result._pos;
	// position velocity
	do
	{
		result._pv=Vec3_t(r(), r(), r())*max_v;
	} while (result._pv.length()>max_v);
	
	// orientation
	// random quaternion
	// Ken Shoemake
	// UNIFORM RANDOM ROTATIONS
	// In D. Kirk, editor, Graphics Gems III, pages 124-132. Academic, New York, 1992.
	boost::variate_generator<RNG&, boost::uniform_real<Float_t> > 
	rsimple(_rng, boost::uniform_real<Float_t>(0,1));
	Float_t x0(rsimple());
	Float_t t1(2*osg::PI*rsimple()), t2(2*osg::PI*rsimple());
	Float_t s1(sin(t1)), s2(sin(t2)), c1(cos(t1)), c2(cos(t2));
	Float_t r1(sqrt(1-x0)), r2(sqrt(x0));
	result._ori=Quat_t(s1*r1, c1*r1, s2*r2, c2*r2);
	result._ob=result._ori;
	// orientation velocity
	x0=rsimple();
	t1=2*osg::PI*rsimple();
	t2=2*osg::PI*rsimple();
	s1=sin(t1);
	s2=sin(t2);
	c1=cos(t1);
	c2=cos(t2);
	r1=sqrt(1-x0);
	r2=sqrt(x0);
	Quat_t randomori=Quat_t(s1*r1, c1*r1, s2*r2, c2*r2);
	// max possible orientation velocity is pi(180)
	// but we allow only initanglevel orientation velocity
	result._ov.slerp(max_a/osg::PI, Quat_t(), randomori);
	
	// bond rotation
	result._bond=vector<Float_t>(_fit->RotCount());
	result._bv=vector<Float_t>(_fit->RotCount());
	for (unsigned int i=0; i!=_fit->RotCount(); ++i)
	{
		result._bond[i]=r()*osg::PI;
		// scale by maximum angle step width
		result._bv[i]=r()*max_a;
	}
	result._bb=result._bond;
	return result;
}
コード例 #23
0
void CrankNicolsonSorUpdater::update( const std::vector<double> & uOld,
                                      std::vector<double>* uNew,
                                      const std::vector<double> & prem ) const
{
    int N = uOld.size()-1;
    double c = getAlpha();

    // uOld restricted in the interior region
    Eigen::VectorXd u = Eigen::VectorXd::Zero(N-1);
    for (int i=0; i<N-1; i++) { u(i) = uOld[i+1]; }

    // Construct b-vector
    Eigen::VectorXd b = d_B*u;

    b(0) += 0.5*c*((*uNew)[0]+uOld[0]);
    b(N-2) += 0.5*c*((*uNew)[N]+uOld[N]);

    // Use the state vector at the previous time step as initial estimate
    Eigen::VectorXd x0 = Eigen::VectorXd::Zero(N-1);
    for (int i=0; i<N-1; i++) { x0(i) = uOld[i+1]; }
    
    // Construct early exercise premium vector
    Eigen::VectorXd p = Eigen::VectorXd::Zero(0);
    if ( prem.size()>0 ) {
        p = Eigen::VectorXd::Zero(N-1);
        for (int i=0; i<N-1; i++) { 
            p(i) = prem[i+1]; 
            // If early exercise premium is given, the initial 
            // estimate x0 is set to early exercise premium.
            // This is a reasonable choice because:
            // (1) At the 1st time step, i.e., m=0,
            //     early_exercise_premium = K*exp(ax)*max(1-exp(x),0),
            //     which is exactly the same as the terminal condition;
            // (2) At the successive time steps, i.e., m>0,
            //     early_exercise_premium serves as a good approximation
            //     of the value of state vectors. 
            x0(i) = prem[i+1];
        }
    }
    
    // update 
    std::tuple<Eigen::VectorXd, int> res = sor(d_omega, d_A, b, d_tol, x0, p);
    Eigen::VectorXd x = std::get<0>(res);
    
    for (int i=0; i<N-1; i++) { (*uNew)[i+1] = x(i); }
}
コード例 #24
0
ファイル: snopt_toyprob.cpp プロジェクト: YS-L/pagmo
/// Implementation of the sparsity structure
void snopt_toyprob::set_sparsity(int& lenG, std::vector<int>& iGfun, std::vector<int>& jGvar) const
{
	//Initial point
	decision_vector x0(2);
	x0[0] = 1; x0[1] = 1;
	//Numerical procedure
	this->estimate_sparsity(x0, lenG, iGfun, jGvar);
}
コード例 #25
0
ファイル: decorations.cpp プロジェクト: NaSchkafu/yalaa
int main(int argc, char *argv[])
{
    // A decorated affine form
    yalaa::aff_e_d_dec x0(iv_t(-1.0, 2.0));

    // A new affine form has the best decoration, as long as its original interval
    // is not empty or invalid.
    std::cout << "Decoration of x0: " << get_special(x0) << std::endl;

    // Square x0 is D5 (= 6), the best decoration
    std::cout << x0 << "^2 = " << sqr(x0) << " Deco: " << get_special(sqr(x0))
              << " Valid: " << is_valid(sqr(x0)) << std::endl;

    // The natural domain of sqrt is R+. Thus the resulting decoration of sqrt(x0)
    // is D2 (=3) (possibly defined)
    std::cout <<  "sqrt(" << x0 << ") = " << sqrt(x0) << " Deco: " << get_special(sqrt(x0))
              << " Valid: " << is_valid(sqrt(x0)) << std::endl;

    // The natural domain of log is R+, Thus the decoration is D2, as for lim x->0 log(x) is unbounded
    // the computation overflows for the natural domain resulting in Infinity as central value
    // Note the changed value of valid. Even if the decoration quality is the some as for sqrt(x0),
    // is_valid returns now false, as the form has no numerical meaningful value anymore.
    std::cout << "log(" << x0 << ") = " << log(x0) << " Deco: " << get_special(log(x0))
              << " Valid: " << is_valid(log(x0)) << std::endl;

    // A form for an empty interval is created. The decoration is D0 (=1).
    yalaa::aff_e_d_dec empty(iv_t(1, -1));
    std::cout << "Decoration of an empty affine form: " << get_special(empty)
              << " Valid: " << is_valid(empty) << std::endl;
    // If the empty is used as input argument of an operation, the result is again D0
    std::cout <<  "cos(" << empty << ") = " << cos(empty) << " Deco: " << get_special(cos(empty))
              << " Valid: " << is_valid(cos(empty)) << std::endl;

    // Combination of an affine form with a scalar
    // Normally scalars are treated like affine forms with a D5 decoration. However, if they have a
    // special value like NaN or infinity, the combination results in D-1 (=0) with indicates some
    // error.
    std::cout <<  "3.0*" << x0 << ") = " << 3*x0 << " Deco: " << get_special(3*x0)
              << " Valid: " << is_valid(3*x0) << std::endl;
    std::cout <<  "infinity*" << x0 << ") = " << std::numeric_limits<double>::infinity()*x0
              << " Deco: " << get_special(std::numeric_limits<double>::infinity()*x0)
              << " Valid: " << is_valid(std::numeric_limits<double>::infinity()*x0) << std::endl;

    // Decoations are propagated through inductively defined functions
    // Thus f = sqrt(x0) + x0
    // has the decoration D2, as sqrt(x0) is D2.
    yalaa::aff_e_d_dec sqrtx0(sqrt(x0));
    std::cout <<  "sqrt(" << x0 << ") + " << x0 << " = " << sqrt(x0) + x0
              << " Deco: " << get_special(sqrt(x0) + x0)
              << " Valid: " << is_valid(sqrt(x0) + x0) << std::endl;

    // The natural domain of exp is not violated, but the computation overflows resulting in D4
    // (defined and continuous). No statement is made about the boundness!
    // Commented out, as some libraries like C-XSC abort the program in case of an overflow.
    // yalaa::aff_e_d_dec x1(1000.0);
    // std::cout << "exp(" << x1 << ") = " << exp(x1) << " Deco: " << get_special(exp(x1)) << std::endl;
    return 0;
}
コード例 #26
0
ファイル: opb_skel.cpp プロジェクト: rpankka/micmac
void Skel_OPB_Comp::calc_buf(INT ** output,U_INT1 *** input)
{
     if (first_line_in_pack())
     {
         for (INT d =0; d < dim_in() ; d++)
         {
            U_INT1  **  l = input[d];

            for (int y = y0Buf() ; y < y1Buf() ; y++)
                 convert
                 (
                      _im_init[y-y0Buf()],
                      l[y]+x0Buf(),
                      x1Buf()-x0Buf()
                 );

            Skeleton
            (
                  _skel[d],
                  _im_init,
                  _sz.x,
                  _sz.y,
                  _larg
            );
         }
     }

     for (INT d =0; d < dim_in() ; d++)
         convert
         (
              output[d]+x0(),
              _skel[d][y_in_pack()-dy0()]-dx0(),
              tx()
         );

     if (_AvecDist)
         convert
         (
              output[1]+x0(),
              _im_init[y_in_pack()-dy0()]-dx0(),
              tx()
         );

}
コード例 #27
0
Vector Initialize()
{
 	Vector x0(8, 0.0);

	x0(0) = 11;
	x0(1) = 11; 
	x0(2) = 0; 
	x0(3) = 4.5165e12; 
	x0(4) = 0; 
	x0(5) = 4.5165e12;
	x0(6) = 0; 
	x0(7) = 0; 
	 
	return x0;
} 
コード例 #28
0
int main() {
    char user[3];
    read(0, user, 3);
    if (x0(user) || x1(user) || x2(user) || x3(user) || x4(user)) {
        failure();
    }
    else {
        success();
    }
}
コード例 #29
0
// calculate distance line-point
double distance2(double x,double y,double z, const double *p) {
   // distance line point is D= | (xp-x0) cross  ux |
   // where ux is direction of line and x0 is a point in the line (like t = 0)
   ROOT::Math::XYZVector xp(x,y,z);
   ROOT::Math::XYZVector x0(p[0], p[2], 0. );
   ROOT::Math::XYZVector x1(p[0] + p[1], p[2] + p[3], 1. );
   ROOT::Math::XYZVector u = (x1-x0).Unit();
   double d2 = ((xp-x0).Cross(u)) .Mag2();
   return d2;
}
コード例 #30
0
ファイル: earth_planet.cpp プロジェクト: YS-L/pagmo
/// Implementation of the sparsity structure: automated detection
void earth_planet::set_sparsity(int &lenG, std::vector<int> &iGfun, std::vector<int> &jGvar) const
{
	//Initial point
	decision_vector x0(get_dimension());
	for (pagmo::decision_vector::size_type i = 0; i<x0.size(); ++i)
	{
		x0[i] = get_lb()[i] + (get_ub()[i] - get_lb()[i]) / 3.12345;
	}
	//Numerical procedure
	estimate_sparsity(x0, lenG, iGfun, jGvar);
}