Esempio n. 1
0
    virtual void handleEvents( bool __is_finished, bool verbose )
    {
        if ( __iterations == 0 )
        {
            //SEvent  startEv( IterationStarted, new IterationStarted<value_type>( __residual, __iterations) );
            //SSubject::notifyObservers( &startEv );
            if ( verbose )
                std::cout << "iteration " << __iterations << " : " << residual() << "\n";
        }

        if ( __is_finished == true )
        {
            //SEvent  finishEv( IterationFinished, new IterationFinished<value_type>( __residual, __iterations) );
            //SSubject::notifyObservers( &finishEv );
            if ( verbose )
                std::cout << "iteration " << __iterations << " : " << residual() << "\n";
        }

        else
        {
            if ( verbose )
                std::cout << "iteration " << __iterations << " : " << residual() << "\n";

            //SEvent  aEvent( IterationUpdated, new IterationUpdated<value_type>( __residual, __iterations) );
            //SSubject::notifyObservers( &aEvent );
        }
    }
Esempio n. 2
0
int main(int argv, char *argc[]) {
	info I, J;
	int N;
	double *u;

	if (argv > 1) {sscanf(argc[1],"%d", &N);}
	else {N = 100;}
//	if (scanf("%d", &N)) {} else {N = 40;}
	
	iinit(&I, N);
	u = advection(I.N, I.M);
	compare(u, I.N);
	residual(u, &I);
	iprint(I);
	free(u);

	N *= 2;
	iinit(&J, N);
	u = advection(J.N, J.M);
	compare(u, J.N);
	residual(u, &J);
	iprint(J);
	free(u);

	printf("Degree of convergence = %lg\n\n",
			log(I.S/J.S)/log(I.h/J.h));
	return 0;
}
Esempio n. 3
0
int main(){
	double a;//created variables
	double b;
	double c;
	double x1;
	double x2;

	cout<<"please input values a b c to solve the function of the form ax^2+bx+c=0\na=";//prompt for user input of variables a b and c
	cin>>a;
	cout<<"b=";
	cin>>b;
	cout<<"c=";
	cin>>c;


	if (a==0&b==0&c==0){//if statement that outputs that every possible number is a root
		cout<<"every real and complex number is a root\n";
		keep_window_open();//stops the program
	return 0;}
	
	
	if (a==0&b==0&c!=0){//if statement that outputs the equation is inconsistent in other words it is not of the form ax^2+bx+c and has no roots
		cout<<"the equation is inconsistent\n";
	keep_window_open();//stops the program
	return 0;}
	
	if (discriminant(a,b,c)<0){//if statement that outputs the possible roots are complex
		cout<<"the roots are complex\n";
	keep_window_open();//stops the program
	return 0;}
	
	if (a==0&b!=0){//if statement that says there is only one root
		cout<<"there is one root\n";
	}

	if(discriminant(a,b,c)==0){//if statement that outputs there are two of the same roots
		cout<<"there is one double root\n";
	}

	x1=(-b+sqrt((b*b)-(4*a*c)))/(2*a);//calcution of the roots
	x2=(-b-sqrt((b*b)-(4*a*c)))/(2*a);
	double r1=residual(a,b,c,x1);//use of the function to calculate the residual of roots x1 and x2
	double r2=residual(a,b,c,x2);

cout<<"root1:"<<x1<<"\nroot2:"<<x2<<"\nresidual1:"<<r1<<"\nresidual2:"<<r2<<"\n"; //output of the roots and residuals

keep_window_open();
return 0;
}
Esempio n. 4
0
  /**
   * R is initialized to be Y. When a new entry is selected in our model,
   * we have to compute the residual ONLY for the corresponding response
   * of R. Since we refit, we only have to touch those responses that 
   * have a non-zero value, which can be done by traversing X. An entry
   * in X has the form (source, target, value). Here, 'source' refers to 
   * the column of A that has been selected, 'target' to the column of 
   * Y that it affects. So, for each column, we can compute the residual
   * update. This can be done in parallel (unlike refitting).
   *
   * THIS HAS NOT YET BEEN MPI PARALLELIZED.
   */
  void residual () {
#if USE_PFUNC
    task root_task;
    attribute root_attribute (false /*nested*/, false /*grouped*/);
#endif

    space_type sel_space (0, shadow_X.size());
    Residual residual(&Y, &R, &l2_norm, &set_map, &snp_map, &materializer, M);
#if USE_PFUNC
      ParallelResidual root_residual (sel_space, residual, *global_taskmgr);
      pfunc::spawn (*global_taskmgr, root_task, root_attribute, root_residual);
      pfunc::wait (*global_taskmgr, root_task);
#else
      residual (sel_space);
#endif
  }
//**********************************************************************
PHX_EVALUATE_FIELDS(NeumannResidual,workset)
{ 
  residual.deep_copy(ScalarT(0.0));

  for (std::size_t cell = 0; cell < workset.num_cells; ++cell) {
    for (std::size_t ip = 0; ip < num_ip; ++ip) {
      normal_dot_flux(cell,ip) = ScalarT(0.0);
      for (std::size_t dim = 0; dim < num_dim; ++dim) {
	normal_dot_flux(cell,ip) += normal(cell,ip,dim) * flux(cell,ip,dim); 
      }
    }
  }

  // const Intrepid::FieldContainer<double> & weighted_basis = workset.bases[basis_index]->weighted_basis;
  const Teuchos::RCP<const BasisValues2<double> > bv = workset.bases[basis_index];
  for (std::size_t cell = 0; cell < workset.num_cells; ++cell) {
    for (std::size_t basis = 0; basis < residual.dimension(1); ++basis) {
      for (std::size_t qp = 0; qp < num_ip; ++qp) {
        residual(cell,basis) += normal_dot_flux(cell,qp)*bv->weighted_basis_scalar(cell,basis,qp);
      }
    }
  }

  if(workset.num_cells>0)
    Intrepid::FunctionSpaceTools::
      integrate<ScalarT>(residual, normal_dot_flux, 
			 (workset.bases[basis_index])->weighted_basis_scalar, 
			 Intrepid::COMP_BLAS);
}
//**********************************************************************
PHX_EVALUATE_FIELDS(InterfaceResidual,workset)
{ 
  residual.deep_copy(ScalarT(0.0));

  for (std::size_t cell = 0; cell < workset.num_cells; ++cell) {
    for (std::size_t ip = 0; ip < num_ip; ++ip) {
      normal_dot_flux(cell,ip) = ScalarT(0.0);
      for (std::size_t dim = 0; dim < num_dim; ++dim) {
	normal_dot_flux(cell,ip) += normal(cell,ip,dim) * flux(cell,ip,dim); 
      }
    }
  }

  // const Kokkos::DynRankView<double,PHX::Device> & weighted_basis = this->wda(workset).bases[basis_index]->weighted_basis;
  const Teuchos::RCP<const BasisValues2<double> > bv = this->wda(workset).bases[basis_index];
  for (std::size_t cell = 0; cell < workset.num_cells; ++cell) {
    for (std::size_t basis = 0; basis < residual.dimension(1); ++basis) {
      for (std::size_t qp = 0; qp < num_ip; ++qp) {
        residual(cell,basis) += normal_dot_flux(cell,qp)*bv->weighted_basis_scalar(cell,basis,qp);
      }
    }
  }

  if(workset.num_cells>0)
    Intrepid2::FunctionSpaceTools::
      integrate<ScalarT>(residual, normal_dot_flux, 
			 (this->wda(workset).bases[basis_index])->weighted_basis_scalar, 
			 Intrepid2::COMP_CPP);
}
Esempio n. 7
0
void EBPoissonOp::
levelJacobi(LevelData<EBCellFAB>&       a_phi,
            const LevelData<EBCellFAB>& a_rhs)
{
  CH_TIME("EBPoissonOp::levelJacobi");

  // Overhauled from previous in-place Gauss-Seidel-like method
  // This implementation is very inefficient in terms of memory usage,
  // and could be greatly improved.  It has the advantage, though,
  // of being very simple and easy to verify as correct.

  EBCellFactory factory(m_eblg.getEBISL());
  // Note: this is hardcoded to a single variable (component),
  // like some other code in this class
  LevelData<EBCellFAB> resid(m_eblg.getDBL(), 1, m_ghostCellsRHS, factory);

  residual(resid, a_phi, a_rhs, true);

  LevelData<EBCellFAB> relaxationCoeff(m_eblg.getDBL(), 1, m_ghostCellsRHS, factory);
  getJacobiRelaxCoeff(relaxationCoeff);

  EBLevelDataOps::scale(resid, relaxationCoeff);

  EBLevelDataOps::incr(a_phi, resid, 1.0);
}
Esempio n. 8
0
/*!
 * \brief Solve.
 */
void JacobiSolver::iterate( const int max_iters, const double tolerance )
{
    // Extract the linear problem.
    Epetra_CrsMatrix *A = 
	dynamic_cast<Epetra_CrsMatrix*>( d_linear_problem->GetMatrix() );
    Epetra_Vector *x = 
	dynamic_cast<Epetra_Vector*>( d_linear_problem->GetLHS() );
    const Epetra_Vector *b = 
	dynamic_cast<Epetra_Vector*>( d_linear_problem->GetRHS() );

    // Setup the residual.
    Epetra_Map row_map = A->RowMap();
    Epetra_Vector residual( row_map );

    // Iterate.
    Epetra_CrsMatrix H = buildH( A );
    Epetra_Vector temp_vec( row_map );
    d_num_iters = 0;
    double residual_norm = 1.0;
    double b_norm;
    b->NormInf( &b_norm );
    double conv_crit = b_norm*tolerance;
    while ( residual_norm > conv_crit && d_num_iters < max_iters )
    {
	H.Apply( *x, temp_vec );
	x->Update( 1.0, temp_vec, 1.0, *b, 0.0 );

	A->Apply( *x, temp_vec );
	residual.Update( 1.0, *b, -1.0, temp_vec, 0.0 );

	residual.NormInf( &residual_norm );
	++d_num_iters;
    }
}
bool LOCA::Epetra::Interface::MultiPoint::
computeF(const Epetra_Vector& x, Epetra_Vector& F, const FillType fillFlag)
{
  bool stat = true;

  // Copy owned parts of vector from vector with global map 
  // to one with split map
  solution->Epetra_Vector::operator=(x);
  solutionOverlap->Import(*solution, *overlapImporter, Insert);

  EpetraExt::BlockVector residual(*solution);

  for (int i=0; i < timeStepsOnTimeDomain; i++) {

    solution->ExtractBlockValues(splitVec, (*rowIndex)[i]);

    splitRes.PutScalar(0.0);

    // Pass step index so application can adjust parameters
    iReq->setMultiPointParameter((*rowIndex)[i]); 
    stat = iReq->computeF(splitVec, splitRes, fillFlag);

    residual.LoadBlockValues(splitRes, (*rowIndex)[i]);
  }

  // F does not know it is a clone of a block vector, 
  // so must copy values from residual
  // -- can be fixed? Maybe make residual a view of F instad of copying.
  F = residual;

  return stat;
}
Residual	Analyzer::translation(const ConstImageAdapter<double>&image,
	const ImagePoint& where, int _patchsize) const {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "get translation at %s",
		std::string(where).c_str());
	// create the subwindow we want to lock at
	int	xoffset = where.x() - _patchsize / 2;
	int	yoffset = where.y() - _patchsize / 2;
	ImagePoint	patchcorner(xoffset, yoffset);
	ImageRectangle	window(patchcorner,
			ImageSize(patchsize, _patchsize));
	debug(LOG_DEBUG, DEBUG_LOG, 0, "window: %s",
		window.toString().c_str());

	// we need a phase correlator to measure the transform
	transform::PhaseCorrelator	pc(false);

	// compute the translation between the windows
	WindowAdapter<double>	frompatch(image, window);
	WindowAdapter<double>	topatch(baseimage, window);
	std::pair<Point, double>	delta
		= pc(frompatch, topatch);
	Point	translation = delta.first;
	double	weight = delta.second;
	debug(LOG_DEBUG, DEBUG_LOG, 0, "%s -> %s",
		where.toString().c_str(),
		translation.toString().c_str());

	// add the residual to the result set
	Residual	residual(where, translation, weight);
	return residual;
}
Esempio n. 11
0
std::vector< Eigen::VectorXd > NormalVarianceMixtureBaseError::simulate(std::vector< Eigen::VectorXd > Y)
{

	std::vector< Eigen::VectorXd > residual( Y.size());
	for(int i = 0; i < Y.size(); i++){
		residual[i] =   sigma * (Rcpp::as< Eigen::VectorXd >(Rcpp::rnorm( Y[i].size()) ));
	  if(common_V == 0){
	    for(int ii = 0; ii < residual[i].size(); ii++)
	    {
	      double V = simulate_V();
	      Vs[i][ii] = V;
	      residual[i][ii] *=  sqrt(V);
	    }
	  } else {
	    double V = simulate_V();
	    for(int ii = 0; ii < residual[i].size(); ii++)
	    {
	      Vs[i][ii] = V;
	      residual[i][ii] *=  sqrt(V);
	    }
	  }


	}
	return(residual);
}
Esempio n. 12
0
bool VxlSelfCalib::calibIdenticalK(const vcl_vector< vnl_matrix_fixed<double, 3, 4> > & projections,
                                   const vnl_matrix_fixed<double, 3, 3> & initK,
                                   const vnl_vector_fixed<double, 3> & init_p,
                                   vnl_matrix_fixed<double, 3, 3> & finalK,
                                   vnl_vector_fixed<double, 3> & final_p)
{
    assert(projections.size() >= 3);
    
    vgl_point_2d<double> pp(initK[0][2], initK[1][2]);  
    calibIdenticalKEqu195_Residual residual(projections, pp);
    
    vnl_vector<double> x(4, 0.0);
    x[0] = initK[0][0];
    x[1] = init_p[0];
    x[2] = init_p[1];
    x[3] = init_p[2];
    
    vnl_levenberg_marquardt lmq(residual);
    
    bool isMinized = lmq.minimize(x);
    if (!isMinized) {
        vcl_cerr<<"Error: minimization failed.\n";
        vcl_cerr<<"x = "<<x<<vcl_endl;
        lmq.diagnose_outcome();
        return false;
    }
    lmq.diagnose_outcome();
    
    vcl_cerr<<"x = "<<x<<vcl_endl;
    
    
    
    return true;
}
Esempio n. 13
0
/**
In order to do so, first a reasonable dt for stability is calculated and F,G,RHS are evaluated.
Afterwards, the Poisson pressure equation is solved and the velocitys are updated.
\param[in] printInfo boolean if additional informations on the fields and rediduum of p are printed
\param[in] verbose boolean if debbuging information should be printed (standard: false)
*/
void Compute::TimeStep(bool printInfo, bool verbose=false)
{
	// TODO: test
	
	// compute dt
	if (verbose) std::cout << "Computing the timestep width..." << std::flush; // only for debugging issues
	real_t dt = compute_dt();
	if (verbose) std::cout << "Done.\n" << std::flush; // only for debugging issues
	
	// compute F, G
	MomentumEqu(dt);
	update_boundary_values(); //update boundary values
	
	// compute rhs
	RHS(dt);
	
	// solve Poisson equation
	real_t residual(_epslimit + 1.0);
	index_t iteration(0);
	//while (iteration <= _param->IterMax() && residual > _epslimit){
	while (true){
		// one solver cycle is done here
		residual = _solver->Cycle(_p, _rhs);

		iteration++;
		if (iteration > _param->IterMax()){
			//if (printInfo) {
				std::cout << "Warning: Solver did not converge! Residual: " << residual << "\n";
			//}
			break;
		} else if (residual < _epslimit){
			//if (printInfo) {
				std::cout << "Solver converged after " << iteration << " timesteps. Residual: " << residual << "\n";
			//}
			break;
		}
	}
	
	// compute new velocitys u, v
	NewVelocities(dt);
	update_boundary_values();

	//update total time
	_t += dt;

	// print information
	if (printInfo){
		std::cout << "============================================================\n";
		// total simulated time
		std::cout << "Total simulated time: t = " << _t << "\n";
		// timestep
		std::cout << "Last timestep: dt = " << dt << "\n";
		// magnitudes of the fields
		std::cout << "max(F) = " << _F->AbsMax() << ", max(G) = " << _G->AbsMax() << ", max(rhs) = " << _rhs->AbsMax() << "\n";
		std::cout << "max(u) = " << _u->AbsMax() << ", max(v) = " << _v->AbsMax() << ", max(p) = " << _p->AbsMax() << "\n";
		//std::cout << "Average value of rhs: " << _rhs->average_value() << "\n";
		std::cout << "============================================================\n";
	}
}
Esempio n. 14
0
void Domain1D::
eval(size_t jg, doublereal* xg, doublereal* rg,
     integer* mask, doublereal rdt)
{

    if (jg != npos && (jg + 1 < firstPoint() || jg > lastPoint() + 1)) {
        return;
    }

    // if evaluating a Jacobian, compute the steady-state residual
    if (jg != npos) {
        rdt = 0.0;
    }

    // start of local part of global arrays
    doublereal* x = xg + loc();
    doublereal* rsd = rg + loc();
    integer* diag = mask + loc();

    size_t jmin, jmax, jpt,  j, i;
    jpt = jg - firstPoint();

    if (jg == npos) {      // evaluate all points
        jmin = 0;
        jmax = m_points - 1;
    } else {          // evaluate points for Jacobian
        jmin = std::max<size_t>(jpt, 1) - 1;
        jmax = std::min(jpt+1,m_points-1);
    }

    for (j = jmin; j <= jmax; j++) {
        if (j == 0 || j == m_points - 1) {
            for (i = 0; i < m_nv; i++) {
                rsd[index(i,j)] = residual(x,i,j);
                diag[index(i,j)] = 0;
            }
        } else {
            for (i = 0; i < m_nv; i++) {
                rsd[index(i,j)] = residual(x,i,j)
                                  - timeDerivativeFlag(i)*rdt*(value(x,i,j) - prevSoln(i,j));
                diag[index(i,j)] = timeDerivativeFlag(i);
            }
        }
    }
}
Esempio n. 15
0
static void
KBDWindow ( float* window, unsigned int size, float alpha )
{
    double  sumvalue = 0.;
    double  scale;
    int     i;

    scale = 0.25 / sqrt (size);
    for ( i = 0; i < (int)size/2; i++ )
        window [i] = sumvalue += Bessel_I_0 ( M_PI * alpha * residual (4.*i/size - 1.) );

    // need to add one more value to the nomalization factor at size/2:
    sumvalue += Bessel_I_0 ( M_PI * alpha * residual (4.*(size/2)/size-1.) );

    // normalize the window and fill in the righthand side of the window:
    for ( i = 0; i < (int)size/2; i++ )
        window [size-1-i] = window [i] = /*sqrt*/ ( window [i] / sumvalue ) * scale;
}
Esempio n. 16
0
 //----------------------------------------------------------------------
 Bart::LogitResidualData *
 LogitBartPosteriorSampler::create_and_store_residual(int i) {
   Ptr<BinomialRegressionData> data_point(model_->dat()[i]);
   double original_prediction = model_->predict(data_point->x());
   boost::shared_ptr<Bart::LogitResidualData> residual(
       new Bart::LogitResidualData(data_point, original_prediction));
   residuals_.push_back(residual);
   return residual.get();
 }
Esempio n. 17
0
    void lasso2(const std::vector<float>& y,const std::vector<float>& x,std::vector<float>& w,unsigned int max_fiber)
    {
        unsigned int y_dim = y.size();
        std::vector<float> residual(y);
        std::vector<float> tmp(y_dim);
        std::vector<char> fib_map(y_dim);
        w.resize(y_dim);

        float step_size = decomposition_fraction;
        unsigned int max_iter = ((float)max_fiber/step_size);
        unsigned char total_fiber = 0;
        for(int fib_index = 0;fib_index < max_iter;++fib_index)
        {
            // calculate the correlation with each SFO

            image::matrix::vector_product(&*x.begin(),&*residual.begin(),&*tmp.begin(),
                                            image::dyndim(y_dim,y_dim));
            // get the most correlated orientation
            int dir = std::max_element(tmp.begin(),tmp.end())-tmp.begin();
            float corr = tmp[dir];
            if(corr < 0.0)
                break;
            if(!fib_map[dir])
            {
                total_fiber++;
                if(total_fiber > max_fiber)
                    break;
                fib_map[dir] = 1;
            }
            std::vector<float>::const_iterator xi = x.begin()+dir*y_dim;
            if(fib_index == 0)
            {
                std::vector<float>::const_iterator xj = x.begin();
                float min_step_value = std::numeric_limits<float>::max();
                int min_step_dir = 0;
                for(int index = 0;index < y_dim;++index,xj += y_dim)
                {
                    if(index == dir)
                        continue;
                    float value = lar_get_step(xi,xi,xj,residual.begin(),y_dim);
                    if(value < min_step_value)
                    {
                        min_step_dir = index;
                        min_step_value = value;
                    }
                }
                w[dir] += min_step_value;
                image::vec::axpy(residual.begin(),residual.end(),-min_step_value,xi);
            }
            else
            {
                w[dir] += corr*step_size;
                image::vec::axpy(residual.begin(),residual.end(),-corr*step_size,xi);
            }
        }
    }
Esempio n. 18
0
void Foam::amgPrecon::precondition
(
    scalarField& x,
    const scalarField& b,
    const direction cmpt
) const
{
    // Execute preconditioning
    residual(x, b, cmpt);
    cycle(x, b, cmpt);
}
Esempio n. 19
0
void slae::gaussSeidel( myVector & oX, int iMaxIter, int & oIterCount, double iEps )
{
    int k;
    double res = 1;
    for( k = 0; k < iMaxIter && res > iEps; ++k )
    {
        iteration();
        res = residual();
    }
    oX = m_AprX;
    oIterCount = k;
}
Esempio n. 20
0
void run_solver(MatrixType const & matrix, VectorType const & rhs, VectorType const & ref_result, SolverTag const & solver, PrecondTag const & precond)
{
  VectorType result(rhs);
  VectorType residual(rhs);
  
  result = viennacl::linalg::solve(matrix, rhs, solver, precond);
  residual -= viennacl::linalg::prod(matrix, result);
  std::cout << "  > Relative residual: " << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(rhs) << std::endl;
  std::cout << "  > Iterations: " << solver.iters() << std::endl;
  result -= ref_result;
  std::cout << "  > Relative deviation from result: " << viennacl::linalg::norm_2(result) / viennacl::linalg::norm_2(ref_result) << std::endl;
}
Esempio n. 21
0
bool SSiPPSolver::checkSolved(State* s)
{
    std::list<State*> open, closed;

    State* tmp = s;
    if (!tmp->checkBits(mdplib::SOLVED_SSiPP)) {
        open.push_front(s);
        s->setBits(mdplib::CLOSED_SSiPP);
    }
    bool rv = true;
    while (!open.empty()) {
        tmp = open.front();
        open.pop_front();
        closed.push_front(tmp);
        Action* a = greedyAction(problem_, tmp);
        tmp->setBestAction(a);
        if (problem_->goal(tmp))
            continue;
        if (tmp->deadEnd()) {
            rv = false;
            continue;
        }
        if (residual(problem_, tmp) > epsilon_) {
            rv = false;
        }
        // Return if it ran out of time
        if (ranOutOfTime()) {
            return false;
        }
        for (Successor su : problem_->transition(tmp, a)) {
            State* next = su.su_state;
            if (!next->checkBits(mdplib::SOLVED_SSiPP) &&
                !next->checkBits(mdplib::CLOSED_SSiPP)) {
                open.push_front(next);
                next->setBits(mdplib::CLOSED_SSiPP);
            }
        }
    }
    if (rv) {
        for (State* sc : closed) {
            sc->setBits(mdplib::SOLVED_SSiPP);
        }
    } else {
        while (!closed.empty()) {
            tmp = closed.front();
            closed.pop_front();
            tmp->clearBits(mdplib::CLOSED_SSiPP);
            bellmanUpdate(problem_, tmp);
        }
    }
    return rv;
}
Esempio n. 22
0
Foam::tmp<Foam::scalarField> Foam::lduMatrix::residual
(
    const scalarField& psi,
    const scalarField& source,
    const FieldField<Field, scalar>& interfaceBouCoeffs,
    const lduInterfaceFieldPtrsList& interfaces,
    const direction cmpt
) const
{
    tmp<scalarField> trA(new scalarField(psi.size()));
    residual(trA.ref(), psi, source, interfaceBouCoeffs, interfaces, cmpt);
    return trA;
}
Esempio n. 23
0
Real
IsotropicPlasticity::computeResidual(unsigned qp, Real effectiveTrialStress, Real scalar)
{
  Real residual(0);
  _hardening_slope = 0;
  if (_yield_condition > 0)
  {
    _hardening_slope = computeHardening( qp, scalar );
    // The order here is important.  The final term can be small, and we don't want it lost to roundoff.
    residual = (effectiveTrialStress - _hardening_variable[qp] - _yield_stress) - (3 * _shear_modulus * scalar);
    _hardening_variable[qp] = _hardening_variable_old[qp] + (_hardening_slope * scalar);
  }
  return residual;
}
Esempio n. 24
0
DoubleVector RowDoubleMatrix::conjugateGradient(const DoubleVector &B, double epsilon, unsigned int niter, bool printMessages, unsigned int messageStep) const
{
    DoubleVector X(size_, 0.0); // начальное приближение - вектор нулей
    DoubleVector resid(size_); // невязка
    DoubleVector direction; // направление поиска
    DoubleVector temp(size_); // ременное хранилище для обмена данными
    double resid_norm; // норма невязки
    double alpha;
    double beta;

    double resid_resid, resid_resid_new;

    residual(X, B, resid);

    direction = resid;

    resid_norm = resid.norm_2();

    if (printMessages) std::cout << "Начальная невязка: " << resid_norm << std::endl;
    if (resid_norm > epsilon)
    {
        resid_resid = resid * resid;
        for (unsigned int i = 0; i < niter; i++)
        {
            product(direction, temp);
//            std::cout << direction.norm_2() << "    " << temp.norm_2() << std::endl;
            alpha = (resid_resid) / (direction * temp);
            X += alpha * direction;
            resid -= alpha * temp;
            resid_resid_new = resid * resid;
            resid_norm = sqrt(resid_resid_new);
            if (resid_norm <= epsilon)
            {
                if (printMessages)
                    std::cout << "Решение найдено. Итераций: " << i << ", невязка: " << resid_norm << std::endl;
                break;
            }
            if (printMessages && (i % messageStep == 0))
                std::cout << i << ", невязка: " << resid_norm << std::endl;

            beta = (resid_resid_new) / (resid_resid);
            // d = r + d*beta
            direction.scale(beta);
            direction += resid;
            //
            resid_resid = resid_resid_new;
        }
    }
    return X;
}
Esempio n. 25
0
// Generate expected return of next n periods
vec ARMA11::predict(int n, vec y)
{
	int m = y.n_elem-1;
	vec x = residual(y);
	vec er(n);

	er[0] = mu-phi*(y[m]-mu)+psi*x[m];
	if (n>1) {
		for (int i=1; i<n; i++) {
			er[i] = mu-phi*er[i-1];
		}
	}	
	return er;
}
Esempio n. 26
0
bool LRTDPSolver::checkSolved(mlcore::State* s)
{
    std::list<mlcore::State*> open, closed;

    mlcore::State* tmp = s;
    if (!tmp->checkBits(mdplib::SOLVED)) {
        open.push_front(s);
    }

    bool rv = true;
    while (!open.empty()) {
        tmp = open.front();
        open.pop_front();

        mlcore::Action* a = greedyAction(problem_, tmp);
        if (problem_->goal(tmp) || tmp->deadEnd())
            continue;

        closed.push_front(tmp);
        tmp->setBits(mdplib::CLOSED);

        if (residual(problem_, tmp) > epsilon_)
            rv = false;

        for (mlcore::Successor su : problem_->transition(tmp, a)) {
            mlcore::State* next = su.su_state;
            if (!next->checkBits(mdplib::SOLVED) &&
                !next->checkBits(mdplib::CLOSED)) {
                open.push_front(next);
            }
        }
    }

    if (rv) {
        for (mlcore::State* sc : closed) {
            sc->setBits(mdplib::SOLVED);
            sc->clearBits(mdplib::CLOSED);
        }
    } else {
        while (!closed.empty()) {
            tmp = closed.front();
            closed.pop_front();
            tmp->clearBits(mdplib::CLOSED);
            bellmanUpdate(problem_, tmp);
        }
    }

    return rv;
}
Esempio n. 27
0
void
GlobalStrainUserObject::finalize()
{
  std::vector<Real> residual(9);
  std::vector<Real> jacobian(81);

  std::copy(&_residual(0, 0), &_residual(0, 0) + 9, residual.begin());
  std::copy(&_jacobian(0, 0, 0, 0), &_jacobian(0, 0, 0, 0) + 81, jacobian.begin());

  gatherSum(residual);
  gatherSum(jacobian);

  std::copy(residual.begin(), residual.end(), &_residual(0, 0));
  std::copy(jacobian.begin(), jacobian.end(), &_jacobian(0, 0, 0, 0));
}
Esempio n. 28
0
  void operator()() {
    /* Set up MPI */
    setup ();

    /* Set up norm */
    compute_l2_norm ();
    
#if USE_PFUNC
    task root_task;
    attribute root_attribute (false /*nested*/, false /*grouped*/);
#endif

    /* Iterate until one of the stopping conditions is triggered */
    int num_selected = 0;
    while (true) {

      /* Create a projector and execute the loop for local result */
      space_type my_space = 
        partitioner_t::create (0, N, mpi_rank, mpi_size);
      Projector projector 
        (&R,&snp_map,&materializer,&filter,block_size,M,N,K);
#if USE_PFUNC
      ProjectReduceType root_project (my_space, projector, *global_taskmgr);
      pfunc::spawn (*global_taskmgr, root_task, root_attribute, root_project);
      pfunc::wait (*global_taskmgr, root_task);
#else
      projector (my_space);
#endif

      /* Reduce globally to get the result */
      edge_type selected = find_global_max (projector.get_result ());
      X.insert (selected);
      add_to_shadow (selected);
      ++num_selected;

      /* Re-estimate the coefficients given the new information */
      refit ();

      /* Compute the residual again */
      residual ();

      /* See if we have reached termination conditions */
      if (MAX_SELECT<num_selected || EPSILON>=fro_norm()) break;
    }

    /* Clean up MPI */
    cleanup ();
  }
	DG_INLINE void FactorizeLCP(const dgJointInfo* const jointInfoArray, const dgJacobian* const internalForces, dgJacobianMatrixElement* const matrixRow, dgForcePair& accel)
	{
		dgAssert((dgUnsigned64(&m_bodyMass) & 0x0f) == 0);

		m_bodyMass.SetZero();
		if (m_body->GetInvMass().m_w != dgFloat32(0.0f)) {
			GetInertia();
		}

		if (m_joint) {
			dgAssert(m_parent);
			const dgJointInfo* const jointInfo = &jointInfoArray[m_joint->m_index];
			dgAssert(jointInfo->m_joint == m_joint);
			dgAssert(jointInfo->m_joint->GetBody0() == m_body);
			dgAssert(jointInfo->m_joint->GetBody1() == m_parent->m_body);

			const dgInt32 m0 = jointInfo->m_m0;
			const dgInt32 m1 = jointInfo->m_m1;
			const dgJacobian& y0 = internalForces[m0];
			const dgJacobian& y1 = internalForces[m1];
			const dgInt32 first = jointInfo->m_pairStart;
			dgInt32 clampedValue = m_dof - 1;

			//dgSpatialVector& accel = force.m_joint;
			for (dgInt32 i = 0; i < m_dof; i++) {
				dgInt32 k = m_sourceJacobianIndex[i];
				const dgJacobianMatrixElement* const row = &matrixRow[first + k];
				
				//dgFloat32 force = row->m_force + row->m_invJMinvJt * residual.GetScalar();
				dgFloat32 force = row->m_force;
				if ((force >= row->m_lowerBoundFrictionCoefficent) && (force <= row->m_upperBoundFrictionCoefficent)) {
					dgVector residual(row->m_JMinv.m_jacobianM0.m_linear.CompProduct4(y0.m_linear) + row->m_JMinv.m_jacobianM0.m_angular.CompProduct4(y0.m_angular) +
									  row->m_JMinv.m_jacobianM1.m_linear.CompProduct4(y1.m_linear) + row->m_JMinv.m_jacobianM1.m_angular.CompProduct4(y1.m_angular));
					residual = dgVector(row->m_coordenateAccel) - residual.AddHorizontal();
					accel.m_joint[i] = -residual.GetScalar();
				} else {
					dgAssert (0);
					dgSwap (m_sourceJacobianIndex[i], m_sourceJacobianIndex[clampedValue]);
					i --;
					m_dof --;
					clampedValue --;
				}
			}
			GetJacobians(jointInfo, matrixRow);
		}

		Factorize();
	}
Esempio n. 30
0
File: nterm.c Progetto: rforge/muste
static int linreg(double *X,double *Y,double *S,double *U,double *T,double *B,double *R,int m,int n) {
// RS REM  int i;
  mat_store(X,T,m,n);
  if (mat_gram_schmidt(S,U,T,m,n,TOLERANCE)<0) {
    sur_print("\nUnable to solve!");
//    showmatrix(X,m,n);    
    WAIT; return(-1);
  }
  mat_transp(T,S,m,n);
  mat_mlt(S,T,Y,n,m,1);
  solve_upper(B,U,S,n,1,TOLERANCE);

  fixmat(B,n);

  return(residual(R,B,Y,X,m,n));
}