void
 channel(Home home, const IntVarArgs& x, const SetVarArgs& y) {
   if (home.failed()) return;
   ViewArray<Int::CachedView<Int::IntView> > xa(home,x.size());
   for (int i=x.size(); i--;)
     new (&xa[i]) Int::CachedView<Int::IntView>(x[i]);
   ViewArray<Set::CachedView<Set::SetView> > ya(home,y.size());
   for (int i=y.size(); i--;)
     new (&ya[i]) Set::CachedView<Set::SetView>(y[i]);
   GECODE_ES_FAIL((Set::Int::ChannelInt<Set::SetView>::post(home,xa,ya)));
 }
  void apply( stk_classic::mesh::Bucket::iterator bucket_i ,
              stk_classic::mesh::Bucket::iterator bucket_j ) const
  {
    typedef typename stk_classic::mesh::FieldTraits<field_type>::data_type scalar ;

    stk_classic::mesh::BucketArray<field_type> xa( x_ , bucket_i , bucket_j );

    scalar * xi = xa.contiguous_data();
    scalar * xe = xi + xa.size();

    std::fill(xi, xe, scalar_);
  }
// [[Rcpp::export]]
RcppExport SEXP convolve4cpp(SEXP a, SEXP b) {
  Rcpp::NumericVector xa(a), xb(b);
  int n_xa = xa.size(), n_xb = xb.size();
  Rcpp::NumericVector xab(n_xa + n_xb - 1);
  typedef Rcpp::NumericVector::iterator vec_iterator;
  vec_iterator ia = xa.begin(), ib = xb.begin();
  vec_iterator iab = xab.begin();
  for (int i = 0; i < n_xa; i++)
  for (int j = 0; j < n_xb; j++)
  iab[i + j] += ia[i] * ib[j];
  return xab;
}
Exemple #4
0
RcppExport SEXP convolve3cpp(SEXP a, SEXP b){
    Rcpp::NumericVector xa(a);
    Rcpp::NumericVector xb(b);
    int n_xa = xa.size() ;
    int n_xb = xb.size() ;
    int nab = n_xa + n_xb - 1;
    Rcpp::NumericVector xab(nab);

    for (int i = 0; i < n_xa; i++)
        for (int j = 0; j < n_xb; j++) 
            xab[i + j] += xa[i] * xb[j];

    return xab ;
}
  void apply( stk_classic::mesh::Bucket::iterator bucket_i ,
              stk_classic::mesh::Bucket::iterator bucket_j ,
              reduce_type * inout ) const
  {
    stk_classic::mesh::BucketArray<field_type> xa( field_x , bucket_i , bucket_j );

    scalar * xi = xa.contiguous_data();
    scalar * xe = xi + xa.size();

    scalar tmp = 0 ;
    while ( xi != xe ) { tmp += *xi * *xi ; ++xi; }

    *inout += tmp ;
  }
matrix2d<T> matrix2d<T>::extractMatrix2d(size_t x, size_t y, size_t w,
size_t h) {

  /* TEST ME TEST ME TEST ME TEST ME TEST ME TEST ME TEST ME TEST ME TEST ME */

  matrix2d<T> result(h, w);

  size_t x2[] = {h, w}, s[] = {rows_, 1};
  std::valarray<size_t> xa(x2, 2), sa(s, 2);

  result.data_ = data_[(const std::gslice)std::gslice(y * rows_ + x, xa, sa)];

  return result;
}
  void apply( stk_classic::mesh::Bucket::iterator bucket_i ,
              stk_classic::mesh::Bucket::iterator bucket_j ,
              reduce_type * inout ) const
  {
    stk_classic::mesh::BucketArray<field_type> xa( field_x , bucket_i , bucket_j );
    stk_classic::mesh::BucketArray<field_type> ya( field_y , bucket_i , bucket_j );

    scalar * xi = xa.contiguous_data();
    scalar * yi = ya.contiguous_data();
    scalar * ye = yi + ya.size();

    scalar tmp = 0 ;
    while ( yi != ye ) { tmp += *xi++ * *yi++ ; }
    *inout += tmp ;
  }
RcppExport SEXP test_cpp(SEXP a, SEXP b) {
  Rcpp::NumericVector xa(a);
  Rcpp::NumericVector xb(b);
  // Rcpp::StringVector aaa = "deine mudder";
  Rcpp::StringVector aaa = a;
  aaa.push_back("1") ;
  int n_xa = xa.size(), n_xb = xb.size();
  int nab = n_xa + n_xb - 1;
  Rcpp::NumericVector xab(nab);
  for (int i = 0; i < n_xa; i++)
    for (int j = 0; j < n_xb; j++)
      xab[i + j] += xa[i] * xb[j];
  return aaa ;
  return xab;
}
Exemple #9
0
/*!
 * \brief LAArmadillo::svd
 * Compute singular value decomposition of x
 * \param u
 * \param d
 * \param v
 * \param x
 * \return
 */
bool LAArmadillo::svd(OiMat &u, OiVec &d, OiMat &v, const OiMat &x){
    int matSize = x.getRowCount();
    arma::mat ua(matSize, matSize), va(matSize, matSize), xa(matSize, matSize);
    arma::vec da(matSize);

    this->oiMat2Arma(xa, x);

    arma::svd(ua, da, va, xa);

    this->arma2OiMat(u, ua);
    this->arma2OiMat(v, va);
    this->arma2OiVec(d, da);

    return true;
}
Exemple #10
0
int main() {
    //std::vector<fixed16> xa(1024 * 1024)
    //typedef float fp_t;
    auto & os = std::cout;
    {
        float m_x = 0.0;
        float m_y =-1343.13423412312312;
        float m_z = 1.0;
        
        auto m_ele = "FUK";
        
        boost::io::ios_all_saver ias( os );
        os << std::fixed << std::setprecision(4) <<  std::setw(10) <<  m_x <<  std::setw(10) << m_y << std::setw(10) << m_z <<  m_ele[0] << m_ele[1] << m_ele[2] << "  0  0  0  0  0  0  0  0  0  0  0  0\n";
    }
//     std::cout << "'" << std::fixed << std::setw(10) << std::setprecision(4) << 123.1234567890 << "'\n";
//     std::cout << "'" << std::fixed << std::setw(10) << std::setprecision(4) << float(0.0) << "'\n";
//     std::cout << 0.0 << "\n";
    typedef fixed22 fp_t;
#if 0
    
    std::valarray<fp_t> xa(1024 * 1024);
    std::valarray<fp_t> xb(1024 * 1024);
    
    std::valarray<fp_t> xc(1024 * 1024);
    for( size_t i = 0; i < 100; ++i ) {
        xa = 1.11;
        xb = 2.21;
        
        xc = xa + xb;
        
        long sum = xc.sum();
        std::cout << "sum: " << sum << "\n";
    }
#endif
    
    for( float i = -2.0;  i < 2.0; i+= (1/(1024.0*2)) ) {
        fp_t a = i;
        std::cout << i << " " << float(a) << " " << a << "\n";
    }
    
    {
        fp_t a = 1.001;
        fp_t b = 2.0;
        
        std::cout << a << " " << b << "\n";
    }    
    
}
Exemple #11
0
void DeviceSkin::calcRegions()
{
    const int numAreas = m_parameters.buttonAreas.size();
    for (int i=0; i<numAreas; i++) {
	QPolygon xa(m_parameters.buttonAreas[i].area.count());
	int n = m_parameters.buttonAreas[i].area.count();
	for (int p=0; p<n; p++) {
	    xa.setPoint(p,transform.map(m_parameters.buttonAreas[i].area[p]));
	}
	if ( n == 2 ) {
	    buttonRegions[i] = QRegion(xa.boundingRect());
	} else {
	    buttonRegions[i] = QRegion(xa);
	}
    }
}
Exemple #12
0
int main() {
    try {
        throw xa();
    } catch (...) {
        test();
    }
    try {
        throw xb();
    } catch (...) {
        test();
    }
    try {
        throw xc();
    } catch (...) {
        test();
    }
    _PASS;
}
  void apply( stk_classic::mesh::Bucket::iterator bucket_i ,
              stk_classic::mesh::Bucket::iterator bucket_j ) const
  {
    typedef typename stk_classic::mesh::FieldTraits<field_type>::data_type scalar ;

    stk_classic::mesh::BucketArray<field_type> xa( x_ , bucket_i , bucket_j );
    stk_classic::mesh::BucketArray<field_type> ya( y_ , bucket_i , bucket_j );

    scalar * xi = xa.contiguous_data();
    scalar * yi = ya.contiguous_data();
    scalar * ye = yi + ya.size();

    //is it worthwhile to optimize by adding special loops for
    //cases where alpha or beta equal 1.0 or 0.0, or where x==y?

    while(yi < ye) {
      *yi = alpha_* *xi++ + beta_* *yi;
      ++yi;
    }
  }
Exemple #14
0
Vector OdeErrControl(
	Method          &method,
	const Scalar    &ti    ,
	const Scalar    &tf    ,
	const Vector    &xi    ,
	const Scalar    &smin  ,
	const Scalar    &smax  ,
	Scalar          &scur  ,
	const Vector    &eabs  ,
	const Scalar    &erel  ,
	Vector          &ef    ,
	Vector          &maxabs,
	size_t          &nstep )
{
	// check simple vector class specifications
	CheckSimpleVector<Scalar, Vector>();

	size_t n = size_t(xi.size());

	CPPAD_ASSERT_KNOWN(
		smin <= smax,
		"Error in OdeErrControl: smin > smax"
	);
	CPPAD_ASSERT_KNOWN(
		size_t(eabs.size()) == n,
		"Error in OdeErrControl: size of eabs is not equal to n"
	);
	CPPAD_ASSERT_KNOWN(
		size_t(maxabs.size()) == n,
		"Error in OdeErrControl: size of maxabs is not equal to n"
	);
	size_t m = method.order();
	CPPAD_ASSERT_KNOWN(
		m > 1,
		"Error in OdeErrControl: m is less than or equal one"
	);

	bool    ok;
	bool    minimum_step;
	size_t  i;
	Vector xa(n), xb(n), eb(n), nan_vec(n);

	// initialization
	Scalar zero(0);
	Scalar one(1);
	Scalar two(2);
	Scalar three(3);
	Scalar m1(m-1);
	Scalar ta = ti;
	for(i = 0; i < n; i++)
	{	nan_vec[i] = nan(zero);
		ef[i]      = zero;
		xa[i]      = xi[i];
		if( zero <= xi[i] )
			maxabs[i] = xi[i];
		else	maxabs[i] = - xi[i];

	}
	nstep = 0;

	Scalar tb, step, lambda, axbi, a, r, root;
	while( ! (ta == tf) )
	{	// start with value suggested by error criteria
		step = scur;

		// check maximum
		if( smax <= step )
			step = smax;

		// check minimum
		minimum_step = step <= smin;
		if( minimum_step )
			step = smin;

		// check if near the end
		if( tf <= ta + step * three / two )
			tb = tf;
		else	tb = ta + step;

		// try using this step size
		nstep++;
		method.step(ta, tb, xa, xb, eb);
		step = tb - ta;

		// check if this steps error estimate is ok
		ok = ! (hasnan(xb) || hasnan(eb));
		if( (! ok) && minimum_step )
		{	ef = nan_vec;
			return nan_vec;
		}

		// compute value of lambda for this step
		lambda = Scalar(10) * scur / step;
		for(i = 0; i < n; i++)
		{	if( zero <= xb[i] )
				axbi = xb[i];
			else	axbi = - xb[i];
			a    = eabs[i] + erel * axbi;
			if( ! (eb[i] == zero) )
			{	r = ( a / eb[i] ) * step / (tf - ti);
				root = exp( log(r) / m1 );
				if( root <= lambda )
					lambda = root;
			}
		}
		if( ok && ( one <= lambda || step <= smin * three / two) )
		{	// this step is within error limits or
			// close to the minimum size
			ta = tb;
			for(i = 0; i < n; i++)
			{	xa[i] = xb[i];
				ef[i] = ef[i] + eb[i];
				if( zero <= xb[i] )
					axbi = xb[i];
				else	axbi = - xb[i];
				if( axbi > maxabs[i] )
					maxabs[i] = axbi;
			}
		}
		if( ! ok )
		{	// decrease step an see if method will work this time
			scur = step / two;
		}
		else if( ! (ta == tf) )
		{	// step suggested by the error criteria is not used
			// on the last step because it may be very small.
			scur = lambda * step / two;
		}
	}
	return xa;
}
    void createAtomicLib() {
        typedef CG<double> CGD;
        typedef AD<CGD> ADCGD;

        /**
         * Tape model
         */
        std::vector<ADCGD> xa(na_);
        for (size_t j = 0; j < na_; j++)
            xa[j] = xa_[j];
        CppAD::Independent(xa);

        std::vector<ADCGD> ya(ns_);

        atomicFunction(xa, ya);

        ADFun<CGD> fun;
        fun.Dependent(ya);

        /**
         * Compile
         */
        std::string lName = getAtomicLibName()+(ignoreParameters_ ? "" : "All");
        ModelCSourceGen<double> compHelpL(fun, lName);
        compHelpL.setCreateForwardZero(true);
        compHelpL.setCreateForwardOne(true);
        compHelpL.setCreateReverseOne(true);
        compHelpL.setCreateReverseTwo(true);
        compHelpL.setTypicalIndependentValues(xa_);

        if (ignoreParameters_) {
            std::vector<std::set<size_t> > jacSparAll = extra::jacobianSparsitySet<std::vector<std::set<size_t> > >(fun);
            std::vector<std::set<size_t> > jacSpar(jacSparAll.size());
            for (size_t i = 0; i < jacSparAll.size(); i++) {
                // only differential information for states and controls
                std::set<size_t>::const_iterator itEnd = jacSparAll[i].upper_bound(ns_ + nm_ - 1);
                if (itEnd != jacSparAll[i].begin())
                    jacSpar[i].insert(jacSparAll[i].begin(), itEnd);
            }
            compHelpL.setCustomSparseJacobianElements(jacSpar);

            std::vector<std::set<size_t> > hessSparAll = extra::hessianSparsitySet<std::vector<std::set<size_t> > >(fun);
            std::vector<std::set<size_t> > hessSpar(hessSparAll.size());
            for (size_t i = 0; i < ns_ + nm_; i++) {
                std::set<size_t>::const_iterator it = hessSparAll[i].upper_bound(i); // only the lower left side
                if (it != hessSparAll[i].begin())
                    hessSpar[i].insert(hessSparAll[i].begin(), it);
            }
            compHelpL.setCustomSparseHessianElements(hessSpar);
        }

        ModelLibraryCSourceGen<double> compDynHelpL(compHelpL);
        compDynHelpL.setVerbose(verbose_);

        SaveFilesModelLibraryProcessor<double>::saveLibrarySourcesTo(compDynHelpL, "sources_" + lName);

        DynamicModelLibraryProcessor<double> p(compDynHelpL, lName);
        GccCompiler<double> compiler;
        if (!compilerFlags_.empty())
            compiler.setCompileFlags(compilerFlags_);
        atomicDynamicLib_.reset(p.createDynamicLibrary(compiler));

        /**
         * load the model
         */
        atomicModel_.reset(atomicDynamicLib_->model(lName));
    }
int
main2()
{
	xa();
	xb();
}
int xb() { xa1(); xb2(); xa(); }
Exemple #18
0
ILOSTLBEGIN
#include <unistd.h>
#include <math.h>

int
main (int argc, char **argv)
{
	int N = 5000;
	if (argc > 1){
		N = atoi(argv[1]);
	}
	double M = 100000;
  double** w = new double*[N];
	for (int i = 0; i < N; i++){
		w[i] = new double[N];
		for (int j = 0; j < N; j++){
			if (i == j){
				w[i][j] = i;
			} 
			else {
				w[i][j] = i-abs(i-j);
			}
		}
	} 
	
	IloEnv   env;
   try {
			IloModel model(env);
      
      IloNumVarArray xa(env);
			IloNumVarArray xi(env);
			
			for (int i = 0; i < N; i++){
				xa.add(IloNumVar(env));
				xi.add(IloNumVar(env));
			}
		
			IloNumExpr obj = xa[0] + xi[0];	
			
			for (int i = 1; i < N; i++){
				
				obj = obj + xa[i];
				obj = obj + xi[i];
			}	
			
      IloRangeArray con(env);
			for (int i = 0; i < N; i++){
				for (int j = 0; j < N; j++){
					con.add(xa[i] + xi[j] >= w[i][j]);
				}
			}
			
			model.add(con);
   		model.add(IloMinimize(env, obj));
			// populate model 
 
      IloCplex cplex(model);

      if ( !cplex.solve() ) {
         env.error() << "Failed to optimize LP" << endl;
         throw(-1);
      }
      env.out() << "Solution value  = " << cplex.getObjValue() << endl;
   }
   catch (IloException& e) {
      cerr << "Concert exception caught: " << e << endl;
   }
   catch (...) {
      cerr << "Unknown exception caught" << endl;
   }

   env.end();

   return 0;
}
Exemple #19
0
  //--------------------------------------------------------
  //  apply_charged_surfaces
  //--------------------------------------------------------
  void ChargeRegulatorMethodEffectiveCharge::apply_local_forces()
  {
    double * q = lammpsInterface_->atom_charge();
    _atomElectricalForce_.resize(nlocal(),nsd_);

    double penalty = poissonSolver_->penalty_coefficient();
    if (penalty <= 0.0) throw ATC_Error("ExtrinsicModelElectrostatic::apply_charged_surfaces expecting non zero penalty");

    double dx[3];
    const DENS_MAT & xa((interscaleManager_->per_atom_quantity("AtomicCoarseGrainingPositions"))->quantity());

// WORKSPACE - most are static
    SparseVector<double> dv(nNodes_); 
    vector<SparseVector<double> > derivativeVectors;
    derivativeVectors.reserve(nsd_);
    const SPAR_MAT_VEC & shapeFunctionDerivatives((interscaleManager_->vector_sparse_matrix("InterpolateGradient"))->quantity());

    DenseVector<INDEX> nodeIndices;
    DENS_VEC nodeValues;

    NODE_TO_XF_MAP::const_iterator inode;
    for (inode = nodeXFMap_.begin(); inode != nodeXFMap_.end(); inode++) {
      
      int node = inode->first;
      DENS_VEC xI = (inode->second).first;
      double qI = (inode->second).second;
      double phiI = nodalChargePotential_[node];
      for (int i = 0; i < nlocal(); i++) {
        int atom = (atc_->internal_to_atom_map())(i);
        double qa = q[atom];
        if (qa != 0) { 
          double dxSq = 0.;
          for (int j = 0; j < nsd_; j++) {
            dx[j] = xa(i,j) - xI(j);
            dxSq += dx[j]*dx[j];
          }
          if (dxSq < rCsq_) { 
            // first apply pairwise coulombic interaction
            if (!useSlab_) { 
              double coulForce = qqrd2e_*qI*qa/(dxSq*sqrtf(dxSq));
              for (int j = 0; j < nsd_; j++) {
                _atomElectricalForce_(i,j) += dx[j]*coulForce; }
            }
            
            // second correct for FE potential induced by BCs
            // determine shape function derivatives at atomic location
            // and construct sparse vectors to store derivative data
            
            
            for (int j = 0; j < nsd_; j++) {
              shapeFunctionDerivatives[j]->row(i,nodeValues,nodeIndices);
              derivativeVectors.push_back(dv);
              for (int k = 0; k < nodeIndices.size(); k++) {
                derivativeVectors[j](nodeIndices(k)) = nodeValues(k); }
            }
              
            // compute greens function from charge quadrature
            
            SparseVector<double> shortFePotential(nNodes_); 
            shortFePotential.add_scaled(greensFunctions_[node],penalty*phiI);
              
            // compute electric field induced by charge
            DENS_VEC efield(nsd_);
            for (int j = 0; j < nsd_; j++) {
              efield(j) = -.1*dot(derivativeVectors[j],shortFePotential); }
              
            // apply correction in atomic forces
            double c = qV2e_*qa;
            for (int j = 0; j < nsd_; j++) {
              if ((!useSlab_) || (j==nsd_)) { 
                _atomElectricalForce_(i,j) -= c*efield(j);
              }
            }
          }
        }
      }
    }
    
  }
Exemple #20
0
extern "C" void glm_gibbs(double * rZ, double * rxo,  double * rlam, int * rmodelprior, double * rpriorprob, double * rbeta1, double * rbeta2, int * rburnin, int * rniter, int * rscalemixture, double * ralpha,  int * rno, int * rna, int * rp, double * B_mcmc, double * prob_mcmc, int * gamma_mcmc, double * phi_mcmc, double * lam_mcmc, double * B_rb, double * prob_rb, double * intercept_mcmc, double * xo_scale)
{
	GetRNGstate();
	//MCMC Variables//
	int burnin=*rburnin;
	int niter=*rniter;

	//Dimensions//
	int p=*rp;
	int no=*rno;
	int na=*rna;

	//Phi Variables//
	double phi=1.0;

	//Yo Variables//
	std::vector<double> Z(rZ, rZ+no); 
	std::vector<double> xo(rxo, rxo+no*p);
	standardize_xo(xo,xo_scale,no,p);
	std::vector<double> xoyo(p);
	double yobar=0;

	std::vector<double> xoxo(p*p);
	dgemm_( &transT, &transN, &p, &p, &no, &unity, &*xo.begin(), &no, &*xo.begin(), &no, &inputscale0, &*xoxo.begin(), &p );

	//Construct Xa//
	std::vector<double> xa(p*(p+1)/2); //Triangular Packed Storage
	std::vector<double> d(p);
	chol_xa(xa,xoxo,d,p);


	//Reserve Memory for Submatrices//
	std::vector<double> xog; xog.reserve(no*p);
	std::vector<double> xogyo; xogyo.reserve(p);
	std::vector<double> xogxog_Lamg; xogxog_Lamg.reserve(p*p);
	std::vector<double> xag; xag.reserve(na*p);

	//Ya Variables//
	std::vector<double> xaya(p);

	//Beta Variables//
	double intercept=0;
	std::vector<double> Bols(p);
	std::vector<double> B(p,0.0);
	std::vector<double> Bg; Bg.reserve(p);

	//Lambda Variables//
	int scalemixture=*rscalemixture;
	double alpha=*ralpha;
	std::vector<double> lam(rlam,rlam+p);
	std::vector<double> lamg; lamg.reserve(p); //vector instead of diagonal pxp matrix

	//Gamma Variables//
	std::vector<int> gamma(p,1);
	int p_gamma=std::accumulate(gamma.begin(),gamma.end(),0);
	bool gamma_diff=true;
	int modelprior=*rmodelprior;

	//Probability Variables//
	std::vector<double> prob(p);
	std::vector<double> odds(p);
	std::vector<double> priorprob(rpriorprob,rpriorprob+p);

	//Theta Variables//
	double theta=0.5;
	double beta1=*rbeta1;
	double beta2=*rbeta2;

	//Store Initial Values//
	std::copy(B.begin(),B.end(),B_mcmc);
	std::copy(prob.begin(),prob.end(),prob_mcmc);
	std::copy(gamma.begin(),gamma.end(),gamma_mcmc);
	std::copy(lam.begin(),lam.end(),lam_mcmc);

	//Run Gibbs Sampler//
	for (int t = 1; t < niter; ++t)
	{

		//Form Submatrices//
		if(p_gamma) submatrices_uncollapsed(gamma_diff,B,xog,xag,lamg,Bg,gamma,lam,xo,xa,p_gamma,p,no,na);

		//Draw xoyo//
		draw_xoyo(Z,xoyo,yobar,xo,xog,Bg,phi,no,p,p_gamma,intercept);

		//Draw xaya//
		draw_uncollapsed_xaya(xaya,xa,xag,Bg,phi,na,p,p_gamma);

		//Compute Probabilities//
		if(modelprior==1)
		{
			bernoulli_probabilities(prob,odds,Bols,d,xoyo,xaya,priorprob,lam,phi);
		}else if(modelprior==2)
		{
			betabinomial_probabilities(prob,odds,Bols,d,xoyo,xaya,theta,lam,phi);
		}else
		{
			uniform_probabilities(prob,odds,Bols,d,xoyo,xaya,lam,phi);
		}

		//Draw Gamma//
		draw_gamma(gamma,p_gamma,prob);


		//Draw Theta//
		if(modelprior==2) theta=Rf_rbeta(beta1+p_gamma,p-p_gamma+beta2);


		//Draw Beta//
		draw_beta(gamma,B,Bols,d,lam,phi);

		//Draw Intercept//
		intercept=yobar+sqrt(1/(no*phi))*Rf_rnorm(0,1);

		//Draw Lambda//
		if(scalemixture) draw_lambda_t(lam,gamma,alpha,B,phi);


		//Store Draws//
		intercept_mcmc[t]=intercept;
		std::copy(gamma.begin(),gamma.end(),(gamma_mcmc+p*t));
		std::copy(prob.begin(),prob.end(),(prob_mcmc+p*t));
		std::copy(B.begin(),B.end(),(B_mcmc+p*t));
		std::copy(lam.begin(),lam.end(),(lam_mcmc+p*t));

		//Rao Blackwell//
		if(t>=burnin) rao_blackwell(B_rb,prob_rb,B,prob,burnin,niter);

		//Has Gamma Changed?//
		gamma_diff=gamma_change(gamma_mcmc,t,p);

	}
	PutRNGstate();
}
QQuickStateOperation::ActionList QQuickParentChange::actions()
{
    Q_D(QQuickParentChange);
    if (!d->target || !d->parent)
        return ActionList();

    ActionList actions;

    QQuickAction a;
    a.event = this;
    actions << a;

    if (d->xString.isValid()) {
        bool ok = false;
        qreal x = d->xString.value.numberLiteral(&ok);
        if (ok) {
            QQuickAction xa(d->target, QLatin1String("x"), x);
            actions << xa;
        } else {
            QQmlBinding *newBinding = new QQmlBinding(d->xString.value, d->target, qmlContext(this));
            QQmlProperty property(d->target, QLatin1String("x"));
            newBinding->setTarget(property);
            QQuickAction xa;
            xa.property = property;
            xa.toBinding = QQmlAbstractBinding::getPointer(newBinding);
            xa.fromValue = xa.property.read();
            xa.deletableToBinding = true;
            actions << xa;
        }
    }

    if (d->yString.isValid()) {
        bool ok = false;
        qreal y = d->yString.value.numberLiteral(&ok);
        if (ok) {
            QQuickAction ya(d->target, QLatin1String("y"), y);
            actions << ya;
        } else {
            QQmlBinding *newBinding = new QQmlBinding(d->yString.value, d->target, qmlContext(this));
            QQmlProperty property(d->target, QLatin1String("y"));
            newBinding->setTarget(property);
            QQuickAction ya;
            ya.property = property;
            ya.toBinding = QQmlAbstractBinding::getPointer(newBinding);
            ya.fromValue = ya.property.read();
            ya.deletableToBinding = true;
            actions << ya;
        }
    }

    if (d->scaleString.isValid()) {
        bool ok = false;
        qreal scale = d->scaleString.value.numberLiteral(&ok);
        if (ok) {
            QQuickAction sa(d->target, QLatin1String("scale"), scale);
            actions << sa;
        } else {
            QQmlBinding *newBinding = new QQmlBinding(d->scaleString.value, d->target, qmlContext(this));
            QQmlProperty property(d->target, QLatin1String("scale"));
            newBinding->setTarget(property);
            QQuickAction sa;
            sa.property = property;
            sa.toBinding = QQmlAbstractBinding::getPointer(newBinding);
            sa.fromValue = sa.property.read();
            sa.deletableToBinding = true;
            actions << sa;
        }
    }

    if (d->rotationString.isValid()) {
        bool ok = false;
        qreal rotation = d->rotationString.value.numberLiteral(&ok);
        if (ok) {
            QQuickAction ra(d->target, QLatin1String("rotation"), rotation);
            actions << ra;
        } else {
            QQmlBinding *newBinding = new QQmlBinding(d->rotationString.value, d->target, qmlContext(this));
            QQmlProperty property(d->target, QLatin1String("rotation"));
            newBinding->setTarget(property);
            QQuickAction ra;
            ra.property = property;
            ra.toBinding = QQmlAbstractBinding::getPointer(newBinding);
            ra.fromValue = ra.property.read();
            ra.deletableToBinding = true;
            actions << ra;
        }
    }

    if (d->widthString.isValid()) {
        bool ok = false;
        qreal width = d->widthString.value.numberLiteral(&ok);
        if (ok) {
            QQuickAction wa(d->target, QLatin1String("width"), width);
            actions << wa;
        } else {
            QQmlBinding *newBinding = new QQmlBinding(d->widthString.value, d->target, qmlContext(this));
            QQmlProperty property(d->target, QLatin1String("width"));
            newBinding->setTarget(property);
            QQuickAction wa;
            wa.property = property;
            wa.toBinding = QQmlAbstractBinding::getPointer(newBinding);
            wa.fromValue = wa.property.read();
            wa.deletableToBinding = true;
            actions << wa;
        }
    }

    if (d->heightString.isValid()) {
        bool ok = false;
        qreal height = d->heightString.value.numberLiteral(&ok);
        if (ok) {
            QQuickAction ha(d->target, QLatin1String("height"), height);
            actions << ha;
        } else {
            QQmlBinding *newBinding = new QQmlBinding(d->heightString.value, d->target, qmlContext(this));
            QQmlProperty property(d->target, QLatin1String("height"));
            newBinding->setTarget(property);
            QQuickAction ha;
            ha.property = property;
            ha.toBinding = QQmlAbstractBinding::getPointer(newBinding);
            ha.fromValue = ha.property.read();
            ha.deletableToBinding = true;
            actions << ha;
        }
    }

    return actions;
}
Exemple #22
0
Vector OdeErrControl(
	Method          &method, 
	const Scalar    &ti    , 
	const Scalar    &tf    , 
	const Vector    &xi    , 
	const Scalar    &smin  , 
	const Scalar    &smax  , 
	Scalar          &scur  ,
	const Vector    &eabs  , 
	const Scalar    &erel  , 
	Vector          &ef    ,
	Vector          &maxabs,
	size_t          &nstep ) 
{
	// check simple vector class specifications
	CheckSimpleVector<Scalar, Vector>();

	size_t n = xi.size();

	CppADUsageError(
		smin <= smax,
		"Error in OdeErrControl: smin > smax"
	);
	CppADUsageError(
		eabs.size() == n,
		"Error in OdeErrControl: size of eabs is not equal to n"
	);
	CppADUsageError(
		maxabs.size() == n,
		"Error in OdeErrControl: size of maxabs is not equal to n"
	);
	size_t m = method.order();
	CppADUsageError(
		m > 1,
		"Error in OdeErrControl: m is less than or equal one"
	);

	size_t i;
	Vector xa(n), xb(n), eb(n);

	// initialization
	Scalar zero(0);
	Scalar one(1);
	Scalar two(2);
	Scalar three(3);
	Scalar m1(m-1);
	Scalar ta = ti;
	for(i = 0; i < n; i++)
	{	ef[i] = zero;
		xa[i] = xi[i];
		if( zero <= xi[i] )
			maxabs[i] = xi[i];
		else	maxabs[i] = - xi[i];

	}  
	nstep = 0;

	Scalar tb, step, lambda, axbi, a, r, root;
	while( ! (ta == tf) )
	{	// start with value suggested by error criteria
		step = scur;

		// check maximum
		if( smax <= step )
			step = smax;

		// check minimum
		if( step <= smin )
			step = smin;

		// check if near the end
		if( tf <= ta + step * three / two )
			tb = tf;
		else	tb = ta + step;

		// try using this step size
		nstep++;
		method.step(ta, tb, xa, xb, eb);
		step = tb - ta;

		// compute value of lambda for this step
		lambda = Scalar(10) * scur / step;
		for(i = 0; i < n; i++)
		{	if( zero <= xb[i] )
				axbi = xb[i];
			else	axbi = - xb[i];
			a    = eabs[i] + erel * axbi;
			if( ! (eb[i] == zero) )
			{	r = ( a / eb[i] ) * step / (tf - ti);
				root = exp( log(r) / m1 ); 
				if( root <= lambda )
					lambda = root;
			}
		}
		if( one <= lambda || step <= smin * three / two )
		{	// this step is within error limits or 
			// close to the minimum size
			ta = tb;
			for(i = 0; i < n; i++)
			{	xa[i] = xb[i];
				ef[i] = ef[i] + eb[i];
				if( zero <= xb[i] )
					axbi = xb[i];
				else	axbi = - xb[i];
				if( axbi > maxabs[i] )
					maxabs[i] = axbi;
			}
		}

		// step suggested by error criteria 
		// do not use last step becasue it may be very small
		if( ! (ta == tf) )
			scur = lambda * step / two;
	}
	return xa;
}
 void
 channelSorted(Home home, const IntVarArgs& x, SetVar y) {
   if (home.failed()) return;
   ViewArray<IntView> xa(home,x);
   GECODE_ES_FAIL(Set::Int::Match<Set::SetView>::post(home,y,xa));
 }
Exemple #24
0
void
FMultiGrid::ABecCoeff::set_coeffs (MGT_Solver & mgt_solver, FMultiGrid& fmg)
{
    BL_ASSERT( fmg.m_baselevel >= 0 );
    BL_ASSERT( fmg.m_baselevel == 0 || fmg.m_crse_ratio != IntVect::TheZeroVector() );

    Array< Array<Real> > xa(fmg.m_nlevels);
    Array< Array<Real> > xb(fmg.m_nlevels);

    for (int lev=0; lev < fmg.m_nlevels; ++lev) {
	xa[lev].resize(BL_SPACEDIM);
	xb[lev].resize(BL_SPACEDIM);
	if (lev + fmg.m_baselevel == 0) {
	    // For level 0, the boundary lives exactly on the faces
	    for (int n=0; n<BL_SPACEDIM; n++) {
		xa[lev][n] = 0.0;
		xb[lev][n] = 0.0;
	    }
	} else if (lev == 0) {
	    const Real* dx = fmg.m_geom[0].CellSize();
	    for (int n=0; n<BL_SPACEDIM; n++) {
		xa[lev][n] = 0.5 * fmg.m_crse_ratio[n] * dx[n];
		xb[lev][n] = 0.5 * fmg.m_crse_ratio[n] * dx[n];
	    }	    
	} else {
	    const Real* dx_crse = fmg.m_geom[lev-1].CellSize();
	    for (int n=0; n<BL_SPACEDIM; n++) {
		xa[lev][n] = 0.5 * dx_crse[n];
		xb[lev][n] = 0.5 * dx_crse[n];
	    }
	}
    }

    switch (eq_type) {
        case const_gravity_eq:
	{
	    mgt_solver.set_const_gravity_coeffs(xa, xb);
	    break;
	}
        case (gravity_eq):
	{
	    BL_ASSERT(coeffs_set);
	    mgt_solver.set_gravity_coefficients(b, xa, xb);
	    break;
	}
        case (macproj_eq):
	{
	    BL_ASSERT(coeffs_set);
	    mgt_solver.set_mac_coefficients(b, xa, xb);
	    break;
	}
        case (general_eq):
	{
	    BL_ASSERT(scalars_set && coeffs_set);
	    mgt_solver.set_abeclap_coeffs(alpha, a, beta, b, xa, xb);
	    break;
	}
        default:
	{
	    BoxLib::Abort("FMultiGrid::ABecCoeff::set_coeffs: How did we get here?");
	}
    }
}
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);
}
/*************************************************************************
Dense solver.

This  subroutine  solves  a  system  A*X=B,  where A is NxN non-denegerate
real matrix, X and B are NxM real matrices.

Additional features include:
* automatic detection of degenerate cases
* iterative improvement

INPUT PARAMETERS
    A       -   array[0..N-1,0..N-1], system matrix
    N       -   size of A
    B       -   array[0..N-1,0..M-1], right part
    M       -   size of right part
    
OUTPUT PARAMETERS
    Info    -   return code:
                * -3    if A is singular, or VERY close to singular.
                        X is filled by zeros in such cases.
                * -1    if N<=0 or M<=0 was passed
                *  1    if task is solved (matrix A may be near  singular,
                        check R1/RInf parameters for condition numbers).
    Rep     -   solver report, see below for more info
    X       -   array[0..N-1,0..M-1], it contains:
                * solution of A*X=B if A is non-singular (well-conditioned
                  or ill-conditioned, but not very close to singular)
                * zeros,  if  A  is  singular  or  VERY  close to singular
                  (in this case Info=-3).

SOLVER REPORT

Subroutine sets following fields of the Rep structure:
* R1        reciprocal of condition number: 1/cond(A), 1-norm.
* RInf      reciprocal of condition number: 1/cond(A), inf-norm.

SEE ALSO:
    DenseSolverR() - solves A*x = b, where x and b are Nx1 matrices.

  -- ALGLIB --
     Copyright 24.08.2009 by Bochkanov Sergey
*************************************************************************/
void rmatrixsolvem(const ap::real_2d_array& a,
     int n,
     const ap::real_2d_array& b,
     int m,
     int& info,
     densesolverreport& rep,
     ap::real_2d_array& x)
{
    int i;
    int j;
    int k;
    int rfs;
    int nrfs;
    ap::integer_1d_array p;
    ap::real_1d_array xc;
    ap::real_1d_array y;
    ap::real_1d_array bc;
    ap::real_1d_array xa;
    ap::real_1d_array xb;
    ap::real_1d_array tx;
    ap::real_2d_array da;
    double v;
    double verr;
    bool smallerr;
    bool terminatenexttime;

    
    //
    // prepare: check inputs, allocate space...
    //
    if( n<=0||m<=0 )
    {
        info = -1;
        return;
    }
    da.setlength(n, n);
    x.setlength(n, m);
    y.setlength(n);
    xc.setlength(n);
    bc.setlength(n);
    tx.setlength(n+1);
    xa.setlength(n+1);
    xb.setlength(n+1);
    
    //
    // factorize matrix, test for exact/near singularity
    //
    for(i = 0; i <= n-1; i++)
    {
        ap::vmove(&da(i, 0), &a(i, 0), ap::vlen(0,n-1));
    }
    rmatrixlu(da, n, n, p);
    rep.r1 = rmatrixlurcond1(da, n);
    rep.rinf = rmatrixlurcondinf(da, n);
    if( ap::fp_less(rep.r1,10*ap::machineepsilon)||ap::fp_less(rep.rinf,10*ap::machineepsilon) )
    {
        for(i = 0; i <= n-1; i++)
        {
            for(j = 0; j <= m-1; j++)
            {
                x(i,j) = 0;
            }
        }
        rep.r1 = 0;
        rep.rinf = 0;
        info = -3;
        return;
    }
    info = 1;
    
    //
    // solve
    //
    for(k = 0; k <= m-1; k++)
    {
        
        //
        // First, non-iterative part of solution process:
        // * pivots
        // * L*y = b
        // * U*x = y
        //
        ap::vmove(bc.getvector(0, n-1), b.getcolumn(k, 0, n-1));
        for(i = 0; i <= n-1; i++)
        {
            if( p(i)!=i )
            {
                v = bc(i);
                bc(i) = bc(p(i));
                bc(p(i)) = v;
            }
        }
        y(0) = bc(0);
        for(i = 1; i <= n-1; i++)
        {
            v = ap::vdotproduct(&da(i, 0), &y(0), ap::vlen(0,i-1));
            y(i) = bc(i)-v;
        }
        xc(n-1) = y(n-1)/da(n-1,n-1);
        for(i = n-2; i >= 0; i--)
        {
            v = ap::vdotproduct(&da(i, i+1), &xc(i+1), ap::vlen(i+1,n-1));
            xc(i) = (y(i)-v)/da(i,i);
        }
        
        //
        // Iterative improvement of xc:
        // * calculate r = bc-A*xc using extra-precise dot product
        // * solve A*y = r
        // * update x:=x+r
        //
        // This cycle is executed until one of two things happens:
        // 1. maximum number of iterations reached
        // 2. last iteration decreased error to the lower limit
        //
        nrfs = densesolverrfsmax(n, rep.r1, rep.rinf);
        terminatenexttime = false;
        for(rfs = 0; rfs <= nrfs-1; rfs++)
        {
            if( terminatenexttime )
            {
                break;
            }
            
            //
            // generate right part
            //
            smallerr = true;
            for(i = 0; i <= n-1; i++)
            {
                ap::vmove(&xa(0), &a(i, 0), ap::vlen(0,n-1));
                xa(n) = -1;
                ap::vmove(&xb(0), &xc(0), ap::vlen(0,n-1));
                xb(n) = b(i,k);
                xdot(xa, xb, n+1, tx, v, verr);
                bc(i) = -v;
                smallerr = smallerr&&ap::fp_less(fabs(v),4*verr);
            }
            if( smallerr )
            {
                terminatenexttime = true;
            }
            
            //
            // solve
            //
            for(i = 0; i <= n-1; i++)
            {
                if( p(i)!=i )
                {
                    v = bc(i);
                    bc(i) = bc(p(i));
                    bc(p(i)) = v;
                }
            }
            y(0) = bc(0);
            for(i = 1; i <= n-1; i++)
            {
                v = ap::vdotproduct(&da(i, 0), &y(0), ap::vlen(0,i-1));
                y(i) = bc(i)-v;
            }
            tx(n-1) = y(n-1)/da(n-1,n-1);
            for(i = n-2; i >= 0; i--)
            {
                v = ap::vdotproduct(&da(i, i+1), &tx(i+1), ap::vlen(i+1,n-1));
                tx(i) = (y(i)-v)/da(i,i);
            }
            
            //
            // update
            //
            ap::vadd(&xc(0), &tx(0), ap::vlen(0,n-1));
        }
        
        //
        // Store xc
        //
        ap::vmove(x.getcolumn(k, 0, n-1), xc.getvector(0, n-1));
    }
}