static bool _ViewerCallback(object fncallback, PyEnvironmentBasePtr pyenv, KinBody::LinkPtr plink,RaveVector<float> position,RaveVector<float> direction)
 {
     object res;
     PyGILState_STATE gstate = PyGILState_Ensure();
     try {
         res = fncallback(openravepy::toPyKinBodyLink(plink,pyenv),toPyVector3(position),toPyVector3(direction));
     }
     catch(...) {
         RAVELOG_ERROR("exception occured in python viewer callback:\n");
         PyErr_Print();
     }
     PyGILState_Release(gstate);
     extract<bool> xb(res);
     if( xb.check() ) {
         return (bool)xb;
     }
     extract<int> xi(res);
     if( xi.check() ) {
         return (int)xi;
     }
     extract<double> xd(res);
     if( xd.check() ) {
         return (double)xd>0;
     }
     return true;
 }
예제 #2
0
// Fit model to this random selection of data points.
void
vpHomography::computeTransformation(vpColVector &x, unsigned int *ind, vpColVector &M)
{
  unsigned int i ;
  unsigned int n = x.getRows()/4 ;
  std::vector<double> xa(4), xb(4);
  std::vector<double> ya(4), yb(4);
  unsigned int n2 = n * 2;
  unsigned int ind2;
  for(i=0 ; i < 4 ; i++)
    {
      ind2 = 2 * ind[i];
      xb[i] = x[ind2] ;
      yb[i] = x[ind2+1] ;

      xa[i] = x[n2+ind2] ;
      ya[i] = x[n2+ind2+1] ;
    }

  vpHomography aHb ;
  try {
    vpHomography::HLM(xb, yb, xa, ya, true, aHb);
  }
  catch(...)
    {
      aHb.setIdentity();
    }

  M.resize(9);
  for (i=0 ; i <9 ; i++)
    {
      M[i] = aHb.data[i] ;
    }
  aHb /= aHb[2][2] ;
}
예제 #3
0
 bytes MCByteBuffer::xchrbuf(int reading_, size_t size) {
   reading = reading_;
   buf_pt = 0;
   bytes xb(size);
   buf.swap(xb);
   return xb;
 }
예제 #4
0
파일: rthsort.cpp 프로젝트: fxcebx/Rth
RcppExport SEXP rthsort_int(SEXP a, SEXP decreasing, SEXP inplace,
   SEXP nthreads)
{
  Rcpp::IntegerVector xa(a);
  
  #if RTH_OMP
  omp_set_num_threads(INT(nthreads));
  #elif RTH_TBB
  tbb::task_scheduler_init init(INT(nthreads));
  #endif
  
  thrust::device_vector<int> dx(xa.begin(), xa.end());
  
  if (INTEGER(decreasing)[0])
    thrust::sort(dx.begin(), dx.end(), thrust::greater<int>());
  else
    thrust::sort(dx.begin(), dx.end());
  
  if (INTEGER(inplace)[0]) {
     thrust::copy(dx.begin(), dx.end(), xa.begin());
     // return xa;
  } else {
     Rcpp::IntegerVector xb(xa.size());
     thrust::copy(dx.begin(), dx.end(), xb.begin());
     return xb;
  }
}
예제 #5
0
LPXLFOPER EXCEL_EXPORT
xlEchoDoubleOrNothing(
LPXLFOPER xa,
double defaultValue)
{
EXCEL_BEGIN;

	if (XlfExcel::Instance().IsCalledByFuncWiz())
		return XlfOper(true);

XlfOper xb(
	(xa));
CellMatrix xc(
	xb.AsCellMatrix("xc"));
DoubleOrNothing x(
	DoubleOrNothing(xc,"x"));


 double t = (clock()+0.0)/CLOCKS_PER_SEC;
double result(
	EchoDoubleOrNothing(
		x,
		defaultValue)
	);
  t = (clock()+0.0)/CLOCKS_PER_SEC-t;
CellMatrix resultCells(result);
CellMatrix time(1,2);
time(0,0) = "time taken";
time(0,1) = t;
resultCells.PushBottom(time);
return XlfOper(resultCells);
EXCEL_END
}
예제 #6
0
파일: rthsort.cpp 프로젝트: fxcebx/Rth
RcppExport SEXP rthsort_double(SEXP a, SEXP decreasing, SEXP inplace,
   SEXP nthreads)
{
  Rcpp::NumericVector xa(a);
  
  #if RTH_OMP
  omp_set_num_threads(INT(nthreads));
  #elif RTH_TBB
  tbb::task_scheduler_init init(INT(nthreads));
  #endif
  
  // set up device vector and copy xa to it
  thrust::device_vector<double> dx(xa.begin(), xa.end());
  
  // sort, then copy back to R vector
  if (INTEGER(decreasing)[0])
    thrust::sort(dx.begin(), dx.end(), thrust::greater<double>());
  else
    thrust::sort(dx.begin(), dx.end());
  if (INTEGER(inplace)[0]) {
     thrust::copy(dx.begin(), dx.end(), xa.begin());
     // return xa;
  } else {
     Rcpp::NumericVector xb(xa.size());
     thrust::copy(dx.begin(), dx.end(), xb.begin());
     return xb;
  }
}
예제 #7
0
// [[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;
}
예제 #8
0
void CReport::ReportError(long ErrNo, char * fmt, ...)
  {
  char Buff[1024];
  va_list argptr;
  va_start(argptr, fmt);
  vsprintf(Buff, fmt, argptr);
  va_end(argptr);
  CXM_DDEErrorCode xb(ErrNo, Buff);
  CXMsgLst XMr;
  XMr.PackMsg(xb);
  pDdeExec->XSendMessage(XMr, xRoute);
  if (ErrNo)
    LogError("Report", 0, Buff);
  }
예제 #9
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 ;
}
예제 #10
0
void TPZHelmholtzComplex1D::Contribute(TPZMaterialData &data, REAL weight, TPZFMatrix<STATE> &ek, TPZFMatrix<STATE> &ef) {

    TPZManVector<STATE,2> alphaval(1), betaval(1), phiaval(1);
    fAlpha->Execute(data.x, alphaval);
    fBeta->Execute(data.x, betaval);
    fPhi->Execute(data.x, phiaval);
    
    #ifdef LOG4CXX 
    {
        std::stringstream sout;        
        sout << "Coordenate x: " << data.x << " alpha = " << alphaval << " beta = " << betaval << " phi = " << phiaval;
        LOGPZ_DEBUG(logger, sout.str());
    }
    #endif
    
    TPZFNMatrix<4, STATE> xk(1, 1), xb(1, 1), xc(1, 1, 0.), xf(1, 1);
    xk(0,0) = alphaval[0];    
    xb(0,0) = betaval[0];    
    xf(0,0) = -phiaval[0];   
       
    SetMaterial(xk, xc, xb, xf);
    TPZMat1dLin::Contribute(data, weight, ek, ef);
}
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;
}
예제 #12
0
파일: fixed.cpp 프로젝트: sim82/playground
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";
    }    
    
}
예제 #13
0
int main() {
    try {
        throw xa();
    } catch (...) {
        test();
    }
    try {
        throw xb();
    } catch (...) {
        test();
    }
    try {
        throw xc();
    } catch (...) {
        test();
    }
    _PASS;
}
예제 #14
0
LPXLFOPER EXCEL_EXPORT
xlEchoShort(
LPXLFOPER xa)
{
EXCEL_BEGIN;

	if (XlfExcel::Instance().IsCalledByFuncWiz())
		return XlfOper(true);

XlfOper xb(
	(xa));
short x(
	xb.AsShort("x"));

short result(
	EchoShort(
		x)
	);
return XlfOper(result);
EXCEL_END
}
예제 #15
0
double Prior::sample_alpha(Model* model, const VectorView& y, Rand& rng)
{
  // then use full conditional of alpha to update it
  size_t nterms = (model->beta).length() - m_e;

  double a = alpha_;

  do { // disallow exact zero value
    if (nterms > 0){
      // propose switching sign of alpha and eta (sign of eta has no effect as long
      // as we actually sample beta; note that eta has symmetric zero mean
      // distribution); this is metropolis move with deterministic
      // proposal; no effect is mu_alpha is zero (might as well skip...)
      if ((a <= 0.0) || log(rng.rand_01()) <= -2.0 * mu_alpha * a){
        a = -a;
      }

      Vector xb(n);
      Vector eb(n);

      xb.set_to_product((model->x).columnblock(m_e, nterms),
          (model->beta).block(m_e, nterms), false);
      eb.set_to_product((model->x).columnblock(0, m_e),
          (model->beta).block(0, m_e), false);
      eb -= y; // note: this is E * b - y, hence there is minus below in mu formul.

      double alpha_sigma2 = a * model->sigma2;
      double var = 1.0 / (1.0 + VectorView::dotproduct(xb, xb) / (a * alpha_sigma2));
      double mu = var * (mu_alpha - VectorView::dotproduct(eb, xb) / alpha_sigma2);

      a = sqrt(var) * rng.rand_normal() + mu;
    } else {
      // sample from prior
      a = rng.rand_normal() + mu_alpha;
    }
  } while (a == 0 || a * a == 0);
  model->mu_beta_computed = false;

  return a;
}
예제 #16
0
 void OBExternalBondData::SetData(OBAtom *atom,OBBond *bond,int idx)
 {
   OBExternalBond xb(atom,bond,idx);
   _vexbnd.push_back(xb);
 }
예제 #17
0
grid_manager mpi_manager_2D::make_LocalGrid(grid_manager &GlobalGrid) {
	//! Take the global grid and generate a local one
	
	// First get all properties from global grid manager:
	NumArray<int> mx(DIM);
	NumArray<double> xb(DIM), Len(DIM);
	for(int dir=0; dir<DIM; ++dir) {
		mx[dir] = GlobalGrid.get_mx(dir);
		xb[dir] = GlobalGrid.get_xb(dir);
		Len[dir] = GlobalGrid.get_Len(dir);
	}

	// Now compute local extent of grid (cell-wise and space-wise)
	if (rank == 0) {
		for (int dir=0; dir<DIM; ++dir) {
			mx[dir] /= nproc[dir];
			Len[dir] /= nproc[dir];
		}
	}

	
	MPI_Barrier(comm2d);
	MPI_Bcast(mx, DIM, MPI_INT, 0, comm2d);
	MPI_Bcast(Len, DIM, MPI_DOUBLE, 0, comm2d);
	MPI_Bcast(xb, DIM, MPI_DOUBLE, 0, comm2d);
	MPI_Barrier(comm2d);

	// Now the local computations that need to be done by each rank:
	NumArray<double> xe(DIM);
	for (int dir=0; dir<DIM; ++dir) {
		xb[dir] += Len[dir]*coords[dir];
		xe[dir] = xb[dir] + Len[dir];
	}

	// if(rank == 2) {
	// 	std::cout << " mx: " << mx[0] << " " << mx[1] << " " << mx[2];
	// 	std::cout << std::endl;
	// 	std::cout << " Len: " << Len[0] << " " << Len[1] << " " << Len[2];
	// 	std::cout << std::endl;
	// 	std::cout << " xb: " << xb[0] << " " << xb[1] << " " << xb[2];
	// 	std::cout << std::endl;
	// 	std::cout << " xe: " << xe[0] << " " << xe[1] << " " << xe[2];
	// 	std::cout << std::endl;
	// }


	int rim = GlobalGrid.get_rim();


	// Now make the local grid manager:
	grid_manager LocalGrid(xb[0], xb[1], xe[0], xe[1],
	                       mx[0]+1, mx[1]+1, rim);

	// Now set corresponding boundary types (old type at
	// outer-boundaries / -1 at MPI boundaries)
	for(int bound=0; bound<2*DIM; ++bound) {
		if(is_OuterBoundary(bound)) {
			LocalGrid.set_bcType(bound, GlobalGrid.get_bcType(bound));
		} else {
			LocalGrid.set_bcType(bound, -1);
		}
	}

	return LocalGrid;

}
예제 #18
0
  // Run one valid triangle. Solve for x in
  //     P' T Q' x = R \ b,
  // where P = diag(p) and similarly for Q and R, and T is a triangle.
  static int test (const TestOptions& to, const bool print_options=false,
                   const bool exception_expected=false) {
    int nerr = 0;

    const Int max_nrhs = 3;
    const Real tol = std::numeric_limits<Real>::epsilon()*1e6;

    // Generate matrix data.
    Data d;
    Size nnz;
    {
      ut::gen_tri_matrix(to, d);     // triangle
      nnz = d.ir.back();
      ut::gen_rand_perm(d.m, d.p);   // row permutation vector
      ut::gen_rand_perm(d.m, d.q);   // col permutation vector
      ut::gen_rand_vector(d.m, d.r); // row scaling
    }

    const Int ldb = d.m + 3, ldx = d.m + 4;
    std::vector<Sclr> b(ldb*max_nrhs), xt(d.m*max_nrhs), x(ldx*max_nrhs);
    {
      // True x.
      ut::gen_rand_vector(xt.size(), xt);
      // Generate the rhs b.
      for (Int irhs = 0; irhs < max_nrhs; ++irhs) {
        const Sclr* const xtp = xt.data() + irhs*d.m;
        Sclr* const bp = b.data() + irhs*ldb;
        std::vector<Sclr> y(d.m);
        for (Int i = 0; i < d.m; ++i)
          x[i] = xtp[d.q[i]];
        ut::mvp(d, to.transpose, to.conjugate, x.data(), y.data());
        for (Int i = 0; i < d.m; ++i)
          bp[d.p[i]] = y[i];
        for (Int i = 0; i < d.m; ++i)
          bp[i] *= d.r[i];
      }
    }
    std::vector<Sclr> bo(b);

    typename ihts::CrsMatrix* T;
    typename ihts::Options opts;
    {
      T = ihts::make_CrsMatrix(d.m, d.ir.data(), d.jc.data(), d.v.data(),
                               to.transpose, to.conjugate);
      if ( ! to.reprocess && to.nthreads > 1)
        ihts::register_Deallocator(T, &d);
      if (to.solve_type == TestOptions::ls_only)
        ihts::set_level_schedule_only(opts);
      else if (to.solve_type == TestOptions::rb_only)
        opts.min_lset_size = d.m + 1;
      // To really test things well, choose very small block sizes. (This is bad
      // for performance.) These parameters are not meant to be set by the user
      // ordinarily, but they are exposed in case an expert is tuning performance
      // or, as here, for testing.
      opts.min_block_size = 6;
      opts.min_parallel_rows = 2;
      opts.pp_min_block_size = 12;
      if (to.matrix_type == TestOptions::block_sparse)
        opts.levelset_block_size = to.block_size;
    }

    {
      typename ihts::Impl* impl;
      try {
        impl = ihts::preprocess(T, max_nrhs - 1 /* For testing; see below. */,
                                to.nthreads, to.reprocess, d.p.data(), d.q.data(),
                                d.r.data(), &opts);
      } catch (...) {
        if ( ! exception_expected) {
          std::cerr << "Unexpected exception on ";
          to.print(std::cerr);
          std::cerr << "\n";
          ut::write_matrixmarket(d, "unexpected_exception.mm");
        }
        ihts::delete_CrsMatrix(T);
        throw;
      }
      if (print_options)
        ihts::print_options(impl, std::cout);
      if (to.reprocess) {
        // This isn't necessary since we aren't changing the numbers, but
        // pretend we are to test the numerical phase. Do it 3 times to test
        // idempotency.
        for (int rep = 0; rep < 3; ++rep)
          ihts::reprocess_numeric(impl, T, d.r.data());
      }
      // Exercise reset_max_nrhs.
      ihts::reset_max_nrhs(impl, max_nrhs);
      if (ihts::is_lower_tri(impl) &&
          ((to.upper && ! to.transpose) || ( ! to.upper && to.transpose)) &&
          d.m > 1 && nnz > static_cast<Size>(d.m) /* not diag */)
        ++nerr;
      for (int slv = 0; slv < 2; ++slv) {
        // Check each solve interface.
        switch (slv) {
        case 0:
          ihts::solve_omp(impl, b.data(), to.nrhs, x.data(), ldb, ldx);
          break;
        case 1:
          ihts::solve_omp(impl, b.data(), to.nrhs, x.data(), 0.0,  1.0,
                          ldb, ldx);
          ihts::solve_omp(impl, b.data(), to.nrhs, x.data(), 2.0, -1.0,
                          ldb, ldx);
          break;
        case 2:
          ihts::solve_omp(impl, b.data(), to.nrhs, ldb);
          break;
        }
        double rd = 0;
        for (Int i = 0; i < to.nrhs; ++i)
          rd = std::max(
            rd, ut::reldif(xt.data() + i*d.m,
                           (slv == 2 ? b.data() + i*ldb : x.data() + i*ldx),
                           d.m));
        if (slv == 2) b = bo;
        if (rd >= tol) {
          ++nerr;
          if (to.verbose) std::cout << "rd " << slv << ": " << rd << "\n";
        }
      }
      ihts::delete_Impl(impl);
    }

    if (to.nthreads == 1) {
      std::vector<Sclr> xb(d.m*to.nrhs), w(d.m);
      for (Int irhs = 0; irhs < to.nrhs; ++irhs) {
        const Sclr* const bp = b.data() + irhs*ldb;
        Sclr* const xbp = xb.data() + irhs*d.m;
        for (Int i = 0; i < d.m; ++i)
          xbp[i] = bp[i];
      }
      ihts::solve_serial(T, ! to.upper, xb.data(), to.nrhs, d.p.data(),
                         d.q.data(), d.r.data(), w.data());
      const double rd = ut::reldif(xt.data(), xb.data(), d.m*to.nrhs);
      if (rd >= tol) {
        ++nerr;
        if (to.verbose) std::cout << "serial rd: " << rd << "\n";
      }
    }

    ihts::delete_CrsMatrix(T);

    if (to.verbose) {
      const bool print = to.verbose == 2 || (to.verbose == 1 && nerr);
      if (print) {
        std::cout << (nerr ? "fail" : "pass") << "ed: ";
        to.print(std::cout);
        std::cout << "\n";
      }
    }

    return nerr;
  }
    /**
     * With the critical edge selection, initial kernel erstimation can be accomplished quickly.
     * Objective function: E(k) = ||∇I^s ⊗ k - ∇B||² + γ||k||²
     * 
     * @param selectionGrads  array of x and y gradients of final selected edges (∇I^s) [-1, 1]
     * @param blurredGrads    array of x and y gradients of blurred image (∇B) [-1, 1]
     * @param kernel          energy preserving kernel (k)
     */
    void fastKernelEstimation(const array<Mat,2>& selectionGrads,
                              const array<Mat,2>& blurredGrads, Mat& kernel,
                              const float weight = 1e-2) {

        assert(selectionGrads[0].rows == blurredGrads[0].rows && "matrixes have to be of same size!");
        assert(selectionGrads[0].cols == blurredGrads[0].cols && "matrixes have to be of same size!");

        // based on Perseval's theorem, perform FFT
        //                __________              __________
        //             (  F(∂_x I^s) * F(∂_x B) + F(∂_y I^s) * F(∂_y B) )
        // k = F^-1 * ( ----------------------------------------------   )
        //             (         F(∂_x I^s)² + F(∂_y I^s)² + γ          )
        // where * is pointwise multiplication
        //                   __________
        // and F(∂_x I^s)² = F(∂_x I^s) * F(∂_x I^s) ! because they mean the norm
        // 
        // here: F(∂_x I^s) = xS
        //       F(∂_x B)   = xB
        //       F(∂_y I^s) = yS
        //       F(∂_y B)   = yB
        
        // compute FFTs
        // the result are stored as 2 channel matrices: Re(FFT(I)), Im(FFT(I))
        Mat xS, xB, yS, yB;
        deblur::dft(selectionGrads[0], xS);
        deblur::dft(blurredGrads[0], xB);
        deblur::dft(selectionGrads[1], yS);
        deblur::dft(blurredGrads[1], yB);

        complex<float> we(weight, 0.0);

        // kernel in Fourier domain
        Mat K = Mat::zeros(xS.size(), xS.type());

        // pixelwise computation of kernel
        for (int y = 0; y < K.rows; y++) {
            for (int x = 0; x < K.cols; x++) { 
                // complex entries at the current position
                complex<float> xs(xS.at<Vec2f>(y, x)[0], xS.at<Vec2f>(y, x)[1]);
                complex<float> ys(yS.at<Vec2f>(y, x)[0], yS.at<Vec2f>(y, x)[1]);

                complex<float> xb(xB.at<Vec2f>(y, x)[0], xB.at<Vec2f>(y, x)[1]);
                complex<float> yb(yB.at<Vec2f>(y, x)[0], yB.at<Vec2f>(y, x)[1]);


                // kernel entry in the Fourier space
                complex<float> k = (conj(xs) * xb + conj(ys) * yb) /
                                   (conj(xs) * xs + conj(ys) * ys + we);
                                   // (abs(xs) * abs(xs) + abs(ys) * abs(ys) + we); // equivalent
                
                K.at<Vec2f>(y, x) = { real(k), imag(k) };
            }
        }

        // only use the real part of the complex output
        Mat kernelBig;
        dft(K, kernelBig, DFT_INVERSE | DFT_REAL_OUTPUT);

        // FIXME: find kernel inside image (kind of bounding box) instead of force user to
        // approximate a correct kernel-width (otherwise some information are lost)

        // cut of kernel in middle of the temporary kernel
        int x = kernelBig.cols / 2 - kernel.cols / 2;
        int y = kernelBig.rows / 2 - kernel.rows / 2;
        swapQuadrants(kernelBig);
        Mat kernelROI = kernelBig(Rect(x, y, kernel.cols, kernel.rows));

        // copy the ROI to the kernel to avoid that some OpenCV functions accidently
        // uses the information outside of the ROI (like copyMakeBorder())
        kernelROI.copyTo(kernel);

        // threshold kernel to erease negative values
        threshold(kernel, kernel, 0.0, -1, THRESH_TOZERO);

        // // kernel has to be energy preserving
        // // this means: sum(kernel) = 1
        kernel /= sum(kernel)[0];
    }
예제 #20
0
int
main2()
{
	xa();
	xb();
}
예제 #21
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?");
	}
    }
}
예제 #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;
}
예제 #23
0
파일: main.cpp 프로젝트: amosleeday/RTKM
void ProcessDouble(CString commandFile,int* sysidUse)
{
	ProcessRinex    readdata;
	Position spp;
	CString CommadFile	=_T("CommandFile.txt");
	
	/*                            data                                  */
	DdCtrl ddCtrlPtr[MAXSYS]; DdData dddataPre,dddataCurr;  SdData lastSdData;
	ObsEpochData roverData1,baseData1;DdObsInfo ddobsinfo1,preddobsinfo[2];
	DdAmbInfo ambinfo[2],preambinfo[2];
	int numCod=0,numPhs=0;
	double dt;// the time diff of obs time from two files

	SppCtrl sppctrl[2];

	SppInfo sppinfo[2],baseInfo[2];
	SppInfoGlo sppinfoGlo,baseInfoGlo;

	double baseCrd[3],roverCrd[3];
	InPutFileSet  inputfile;
	ReadCommFile(ddCtrlPtr,inputfile,_T("CommandFile.txt"),baseCrd,roverCrd);
	inputfile.CheckPath();
	for(int i=0;i<2;i++) sppctrl[i].sysid=ddCtrlPtr[ sysidUse[i]-1 ].sysid;

	//read broadcast eph
	
	BroadEphHeader brdephheader;
	BroadEphData*		broadephdata=new BroadEphData[MAXEPHNUM];
	BroadEphDataGlo* gloeph=new BroadEphDataGlo[MAXEPHNUM_GLO];
	int nSate	=0,nSateGlo	=0;
	CString NFileName=inputfile.fileEph[0];
	readdata.ReadBroadEph(NFileName, brdephheader,broadephdata,gloeph, nSate,nSateGlo);
	

	//Rover station
	ObsHeader			obsHeader1,obsHeader2;
	ObsEpochData		epochData1,epochData2;
	CString OFileName1	=inputfile.fileRover[0];//E:\\Ъ§Он\\SHCORS\\066(0307)\\SHCH\\0001066J00.14O""0002066C00.14O"E:\\CUTB2014120124.obs
	CString OFileName2	=inputfile.fileBase[0];
	CStdioFile	Ofile1;CStdioFile	Ofile2;CString	line1;CString	line2;

	Ofile1.Open(OFileName1,CFile::modeRead);
	readdata.ReadObsHeader(Ofile1,line1,obsHeader1);
	Ofile2.Open(OFileName2,CFile::modeRead);
	readdata.ReadObsHeader(Ofile2,line2,obsHeader2);
	//Base station
	for (int i=0;i<3;i++) baseInfo[0].recPos[i]=baseInfo[1].recPos[i]=baseCrd[i];
	for (int i=0;i<3;i++) baseInfo[0].recPos[i]=baseInfo[1].recPos[i]=baseCrd[i];
	int	nEpoch1=0,nEpoch2=0;
	int	eventFlag1=0,eventFlag2=0;
	int nEpoch=0;
	//output to file
	CString outs;
	GetOutPath(CommadFile,outs);
	char* outchar=new char[outs.GetLength()+1];
	fstream fout;
	fout.open(outchar,ios::out);
	while (eventFlag1!=10 && eventFlag2!=10)
	{
		epochData1.ZeroElem();	epochData2.ZeroElem();
		epochData1=readdata.GetEpochData(Ofile1,line1,obsHeader1,nEpoch1,eventFlag1);
		epochData1.Sort();
		epochData2=readdata.GetEpochData(Ofile2,line2,obsHeader2,nEpoch2,eventFlag2);
		epochData2.Sort();

		dt=(epochData1.week-epochData2.week)*7*86400.0+(epochData1.sec-epochData2.sec);
		if (fabs(dt)<0.5)
		{
			nEpoch++;
			math::matrix<double> NormEqu[5];
			math::matrix<double> N11,N12,N22,U1,U2;
			for (int i=0;i<2;i++)
			{
				SingleSys(spp,dddataPre,dddataCurr,lastSdData,roverData1,baseData1,sppctrl[i],ddCtrlPtr[sysidUse[i]-1],
					ambinfo[i],preambinfo[i],sppinfo[i],baseInfo[i],ddobsinfo1,brdephheader,broadephdata,gloeph,nSate,nSateGlo,
					obsHeader1,epochData1,obsHeader2,epochData2,baseCrd,roverCrd,nEpoch,sysidUse[i],NormEqu);
				
				if (i==0)
				{
					N11=NormEqu[0];N12=NormEqu[1];N22=NormEqu[2];
					U1=NormEqu[3];	U2=NormEqu[4];
				}
				if (i==1)
				{
					N11 +=NormEqu[0];N12=ConvergeMat(N12.RowNo(),N12,NormEqu[1]);
					N22=DiagMatSym(N22,NormEqu[2]);
					U1 +=NormEqu[3];	U2=VecMat(1,U2, NormEqu[4]);
				}
			}
			NormEqu[0]=N11;NormEqu[1]=N12;NormEqu[2]=N22;
			NormEqu[3]=U1;	NormEqu[4]=U2;
			/*---------------------	end	processing method-------------------	*/
			int resultflag=0; double ratio=0.0;
			if(nEpoch%1000==0) cout<<nEpoch<<endl;

				double xxb[3];
				math::matrix<double>xb=SoluShortEpoch(ddCtrlPtr[0],NormEqu,ambinfo[0],resultflag,ratio);
				preambinfo[0]=ambinfo[0];
				for(int i=0;i<3;i++) sppinfo[0].recPos[i]=roverCrd[i];  
				for(int i=0;i<3;i++) xxb[i]=xb(i,0)+sppinfo[0].recPos[i];  

				fout<<~XYZ2NEU(sppinfo[0].recPos,xxb);
				//cout<<~XYZ2NEU(sppinfo[0].recPos,xxb);

			int t0,t1,t2,t3;
			t0=((int)dddataCurr.sec%86400);
			t1=t0/3600; //hour
			t2=(t0-t1*3600)/60;  //hour
			t3=(t0-t1*3600-t2*60)%60;
			 if(fabs(xb(0,0))>1.0 || fabs(xb(1,0))>1.0) cout<<t1<<" "<<t2<<" "<<t3<<" "<<dddataCurr.pairNum<<"  "<<nEpoch<<endl;
			//cout<<endl;
			dddataPre		=dddataCurr;
			/*	end equation part	*/
		}
		else
		{
			if (dt>0.0) epochData2=readdata.GetEpochData(Ofile2,line2,obsHeader2,nEpoch2,eventFlag2);
			else epochData1=readdata.GetEpochData(Ofile1,line1,obsHeader1,nEpoch1,eventFlag1);
		}
		if (eventFlag1==10 || eventFlag2==10) nEpoch1++;
	}//end while

	fout.close();
	Ofile1.Close();
	Ofile2.Close();
	delete[] broadephdata,gloeph,outchar;
}
예제 #24
0
파일: main.cpp 프로젝트: amosleeday/RTKM
void ProcessSingle(CString commandFile,int sysidUse,const char* outFile)
{
	ProcessRinex    readdata;
	CString CommadFile	=_T("CommandFile.txt");
	//control block
	DdData dddataPre;
	DdData dddataCurr;
	SdData lastSdData;
	ObsEpochData roverData,baseData;	//single system
	DdObsInfo ddobsinfo,preddobsinfo;
	DdAmbInfo ambinfo,preambinfo;
	int numCod=0,numPhs=0;
	math::matrix<double> prenorm[5];
	double dt;

	SppCtrl sppctrl;
	Position spp;
	SppInfo sppinfo,baseInfo;
	SppInfoGlo sppinfoGlo,baseInfoGlo;

	DdCtrl ddctrl;
	InPutFileSet  inputfile;
	double baseCrd[3],roverCrd[3];
	DdCtrl ddCtrlPtr[MAXSYS];
	ReadCommFile(ddCtrlPtr,inputfile,_T("CommandFile.txt"),baseCrd,roverCrd);
	inputfile.CheckPath();
	ddctrl=ddCtrlPtr[sysidUse-1];
	sppctrl.sysid=ddctrl.sysid;
	sppctrl.maskEle=ddctrl.maskele;
	//read broadcast eph
	CString NFileName=inputfile.fileEph[0];
	BroadEphHeader brdephheader;
	BroadEphData*		broadephdata=new BroadEphData[MAXEPHNUM];
	BroadEphDataGlo* gloeph=new BroadEphDataGlo[MAXEPHNUM_GLO];
	int nSate	=0;
	int nSateGlo	=0;
	readdata.ReadBroadEph(NFileName, brdephheader,broadephdata,gloeph, nSate,nSateGlo);
	

	//Rover station
	ObsHeader			obsHeader1;
	ObsEpochData		epochData1;
	CString OFileName1	=inputfile.fileRover[0];//E:\\Ъ§Он\\SHCORS\\066(0307)\\SHCH\\0001066J00.14O""0002066C00.14O"E:\\CUTB2014120124.obs
	CStdioFile	Ofile1;
	Ofile1.Open(OFileName1,CFile::modeRead);
	CString	line1;
	readdata.ReadObsHeader(Ofile1,line1,obsHeader1);

	//Base station
	for (int i=0;i<3;i++) baseInfo.recPos[i]=baseCrd[i];

	ObsHeader			obsHeader2;
	ObsEpochData		epochData2;

	CString OFileName2	=inputfile.fileBase[0];
	CStdioFile	Ofile2;
	Ofile2.Open(OFileName2,CFile::modeRead);
	CString	line2;
	readdata.ReadObsHeader(Ofile2,line2,obsHeader2);
	int	nEpoch1=0,nEpoch2=0;

	int	eventFlag1=0,eventFlag2=0;
	int nEpoch=0;
	//output to file
	fstream fout;
	fout.open(outFile,ios::out);
	while (eventFlag1!=10 && eventFlag2!=10)
	{
		epochData1.ZeroElem();	epochData2.ZeroElem();
		epochData1=readdata.GetEpochData(Ofile1,line1,obsHeader1,nEpoch1,eventFlag1);
		epochData1.Sort();
		epochData2=readdata.GetEpochData(Ofile2,line2,obsHeader2,nEpoch2,eventFlag2);
		epochData2.Sort();
		if(epochData1.sateNum>=5&&ddctrl.CodTypeNo()>1)	epochData1=epochData1.AutoShrink(2);
		if(epochData2.sateNum>=5&&ddctrl.CodTypeNo()>1)	epochData2=epochData2.AutoShrink(2);
		dt=(epochData1.week-epochData2.week)*7*86400.0+(epochData1.sec-epochData2.sec);
		if (1)//mark  fabs(dt)<0.5
		{
			nEpoch++;
			lastSdData.ZeroElem();
			roverData.ZeroElem();	baseData.ZeroElem();  sppinfo.ZeroElem(); baseInfo.ZeroElem();
			if (sysidUse==1 || sysidUse==3 ||sysidUse==5)
			{
				spp.StandPosition(brdephheader,broadephdata,epochData1,nSate,sppctrl,sppinfo,roverData);
				spp.baseStn(baseInfo,broadephdata,epochData2,baseData,nSate,sppctrl);
			}
			else if(sysidUse==2)
			{
				spp.StandPosition(brdephheader,gloeph,epochData1,nSateGlo,sppctrl,sppinfoGlo,roverData);//Glo
				spp.baseStn(baseInfoGlo,gloeph,epochData2,baseData,nSateGlo,sppctrl);//glo

			}
			int t0,t1,t2,t3;
			t0=((int)roverData.sec%86400);
			t1=t0/3600; //hour
			t2=(t0-t1*3600)/60;  //hour
			t3=(t0-t1*3600-t2*60)%60;
#if FileOutSpp
			//fout<<"epoch:   "<<t1<<"  "<<t2<<"  "<<t3<<endl;
			//SppFileOut(fout,sppinfo);
			
#endif
			if (nEpoch>288)
			{
				nEpoch=nEpoch;
			}
			//continue;
			if(Norm(roverCrd,3)>0.0) PtrEqual(roverCrd,sppinfo.recPos,3);
			int refPrn=0;
			ddobsinfo.ZeroEle();
			int tprn=0;
			refPrn=spp.SelectRefSate(baseInfo,sppinfo,5.0,baseData,roverData,lastSdData,ddobsinfo,0,tprn);
			int refpos;
			refpos=GetPos(lastSdData.prn,refPrn,lastSdData.satnum);

			dddataCurr.ZeroElem(); ambinfo.ZeroElem();
			spp.DoubleDiff(refPrn,refpos,lastSdData,dddataCurr);
			if(dddataCurr.pairNum<4) exit(1);
			DdData ts=dddataCurr;
			/*	-----------------------------------------end data preparation part	---------------------------------------*/
			dddataCurr=spp.ComObsPhsCod(ddctrl,ddobsinfo,ambinfo,dddataCurr);
			if(nEpoch>1) spp.PassPreAmb(preambinfo,ambinfo,ddctrl.PhsTypeNo());
			/* -----------------------------------------end cycle slip---------------------------------------- */

			int obsNum	=ddobsinfo.SumCod()+ddobsinfo.SumPhs();//the number of all obs in one system at current epoch
			int phsNum	=ddobsinfo.SumPhs();
			int ionoNum=dddataCurr.pairNum;
			int ambNum=ambinfo.SumUnfix();
			//if(nEpoch>1)ambNum=preambinfo.SumUnfix();
			if(ambNum==0) ambNum=1;
			/*	equation part	*/
			math::matrix<double> DesMatPos(obsNum,3);
			math::matrix<double> DesMatAmb(obsNum,ambNum);
			math::matrix<double> Weight(obsNum,obsNum);
			math::matrix<double> L(obsNum,1);
			math::matrix<double> DesMatTrop(obsNum,1);
			math::matrix<double> DesMatIono(obsNum,obsNum);

			spp.FormDdErrEq(DesMatPos,DesMatTrop,DesMatIono,DesMatAmb,L,dddataCurr,ddctrl,ambinfo,ddobsinfo);
			Weight=spp.FormWeightVc(ddctrl,dddataCurr,ddobsinfo);

			/*---------------------	end	processing method-------------------	*/
			int resultflag=0; double ratio=0.0;
			if(nEpoch%1000==0) cout<<nEpoch<<endl;
			if (nEpoch>0)
			{
				double xxb[3];
				math::matrix<double>xb=SoluShortEpoch(ddctrl,DesMatPos,DesMatAmb,Weight,L,ddobsinfo,ambinfo,resultflag,ratio);
				preambinfo=ambinfo;
				for(int i=0;i<3;i++) xxb[i]=xb(i,0)+sppinfo.recPos[i];  
				fout<<resultflag<<"   "<<dddataCurr.pairNum<<"   "<<~XYZ2NEU(sppinfo.recPos,xxb);
				//cout<<~XYZ2NEU(sppinfo.recPos,xxb);
				preddobsinfo=ddobsinfo;
			}
		//	int t0,t1,t2,t3;
			//t0=((int)dddataCurr.sec%86400);
			//t1=t0/3600; //hour
			//t2=(t0-t1*3600)/60;  //hour
			//t3=(t0-t1*3600-t2*60)%60;
			//cout<<"ratio    "<<ratio<<"   "<<t1<<" "<<t2<<" "<<t3<<" "<<dddataCurr.pairNum<<"  "<<nEpoch<<endl;
			//cout<<endl;
			dddataPre		=dddataCurr;
			/*	end equation part	*/
		}
		else
		{
			if (dt>0.0) epochData2=readdata.GetEpochData(Ofile2,line2,obsHeader2,nEpoch2,eventFlag2);
			else epochData1=readdata.GetEpochData(Ofile1,line1,obsHeader1,nEpoch1,eventFlag1);
		}
		if (eventFlag1==10 || eventFlag2==10) nEpoch1++;
	}//end while

	fout.close();
	Ofile1.Close();
	Ofile2.Close();
	delete[] broadephdata,gloeph;
}
예제 #25
0
void OrganizedData::process(RawData* raw, int nBlock, double pTest, int nSupport)
{
    int nData = raw->nData, nDim = raw->nDim - 1;

    this->nSupport = nSupport;
    this->nBlock   = nBlock;
    this->nDim     = nDim;

    train   = field<mat>(nBlock,2);
    test    = field<mat>(nBlock,2);
    support = field<mat>(1,2);

    mat xm(nSupport,nDim),
        ym(nSupport,1);

    vec mark(nData); mark.fill(0);

    printf("Randomly selecting %d supporting point ...\n", nSupport);

    for (int i = 0; i < nSupport; i++)
	{
		int pos = IRAND(0, nData - 1);
		while (mark[pos] > 0)
			pos = IRAND(0, nData - 1);
		mark[pos] = 1;
		for (int j = 0; j < nDim; j++)
			xm(i, j) = raw->X(pos,j);
		ym(i,0) = raw->X(pos,nDim);
	}

	support(0,0) = xm; xm.clear();
	support(0,1) = ym; ym.clear();

    cout << "Partitioning the remaining data into " << nBlock << " cluster using K-Mean ..." << endl;

    vvd _remain;

    for (int i = 0; i < nData; i++) if (!mark(i))
    {
        rowvec R = raw->X.row(i);
        _remain.push_back(r2v(R));
    }

    mat remaining = v2m(_remain);

    mark.clear();

    RawData* remain = new RawData(remaining);

    KMean* partitioner = new KMean(remain);

    Partition* clusters = partitioner->cluster(nBlock);

    cout << "Packaging training/testing data points into their respective cluster" << endl;

    for (int i = 0; i < nBlock; i++)
    {
        cout << "Processing block " << i + 1 << endl;

        int bSize   = (int) clusters->member[i].size(),
            tSize   = (int) floor(bSize * pTest),
            pos     = 0,
            counter = 0;

        mark = vec(bSize); mark.fill(0);

        if (bSize > tSize)  // if we can afford to draw tSize test points from this block without depleting it ...
        {
            mat xt(tSize,nDim),
                yt(tSize,1);

            for (int j = 0; j < tSize; j++)
            {
                pos = IRAND(0, bSize - 1);
				while (mark[pos] > 0)
					pos = IRAND(0, bSize - 1);
				mark[pos] = 1; pos = clusters->member[i][pos];

				for (int t = 0; t < nDim; t++)
					xt(j, t) = remain->X(pos,t);
				yt(j,0) = remain->X(pos,nDim);
            }

            bSize  -= tSize;
            nTest  += tSize;

            test(i,0) = xt; xt.clear();
            test(i,1) = yt; yt.clear();
        }

        nTrain += bSize;

        mat xb(bSize,nDim),
            yb(bSize,1);

        //cout << remain->X.n_rows << endl;

        for (int j = 0; j < (int)mark.n_elem; j++) if (mark[j] < 1)
        {
            for (int t = 0; t < nDim; t++) {
                xb(counter,t) = remain->X(clusters->member[i][j],t);
            }
            yb(counter++,0) = remain->X(clusters->member[i][j],nDim);
        }

        train(i,0) = xb; xb.clear();
        train(i,1) = yb; yb.clear();

        mark.clear();

        printf("Done ! nData[%d] = %d, nTrain[%d] = %d, nTest[%d] = %d .\n", i, (int) clusters->member[i].size(), i, train(i,0).n_rows, i, (int) test(i,0).n_rows);
    }
}
예제 #26
0
/// Generates the background mesh and computes displacements of its nodes using linear elasticity
void DGhybrid::generate_backmesh_and_compute_displacements()
{
	// make a list of interior points of the quadratic mesh
	
	int ip, ipoin, ib, ilp, idim, ninpoin_q = 0, k = 0, j;

	for(ipoin = 0; ipoin < mq->gnpoin(); ipoin++)
		ninpoin_q += bounflag_q[ipoin];

	ninpoin_q = mq->gnpoin() - ninpoin_q;

	inpoints_q.setup(ninpoin_q, mq->gndim());

	k = 0;
	for(ipoin = 0; ipoin < mq->gnpoin(); ipoin++)
		if(!bounflag_q[ipoin])
		{
			for(idim = 0; idim < mq->gndim(); idim++)
				inpoints_q(k,idim) = mq->gcoords(ipoin,idim);
			k++;
		}
	std::cout << "DGhybrid: generate_backmesh_and_compute_displacements(): No. of interior points to move = " << inpoints_q.rows() << std::endl;

	// setup DGM and get backmesh
	
	dgm.setup(mq->gndim(), &inpoints_q, &backpoints, &motion_b);
	dgm.generateDG();
	bm = dgm.getDelaunayGraph();
	std::cout << "DGhybrid: Back mesh has " << bm.gnpoin() << " points, " << bm.gnelem() << " elements." << std::endl;
	bm.writeGmsh2("testdg.msh");

	// prepare input for linear elasticity problem
	
	motion_b.setup(nbackp,m->gndim());
	motion_b.zeros();

	// cflags contains 1 if the corresponding backmesh point has a Dirichlet BC
	std::vector<int> cflags(nbackp,0);
	
	// get displacements of the boundary points of the quadratic mesh
	k = 0;
	for(ip = 0; ip < mq->gnpoin(); ip++)
	{
		if(bounflag_q[ip] == 1)
		{
			for(idim = 0; idim < mq->gndim(); idim++)
			{
				motion_b(k, idim) = b_motion_q->get(ip,idim);
				cflags[k] = 1;
			}
			k++;
		}
	}

	// setup and solve the elasticity equations to get displacement of the background mesh
	std::cout << "Starting linelast" << std::endl;	
	linm.setup(&bm, lambda, mu);
	linm.assembleStiffnessMatrix();
	linm.assembleLoadVector();
	linm.dirichletBC_points(cflags, motion_b);

	amat::SpMatrix A = linm.stiffnessMatrix();
	amat::Matrix<double> b = linm.loadVector();
	amat::Matrix<double> xb(2*nbackp,1);
	amat::Matrix<double> x(2*nbackp,1);
	xb.zeros();

	// TODO: add a switch to change solver
	x = sparseCG_d(&A, b, xb, tol, maxiter);

	for(int i = 0; i < nbackp; i++)
		for(idim = 0; idim < mq->gndim(); idim++)
			motion_b(i, idim) = x.get(i+idim*nbackp);
}
예제 #27
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;
}
예제 #28
0
BOOL CHistoryTopic::Request(UINT wFmt, const char* pszItem,
                            void** ppData, DWORD* pdwSize)
  {
  if (wFmt != CF_TEXT)
    return FALSE;
  CXM_Route HRoute;
  flag GotHistorian = pDdeExec->XFindObject(pExecName_Historian, HRoute);
  char sz[MaxDDEMsgLen];
  char szItem[1024];
  szItem[0] = 0;
  szItem[sizeof(szItem)-1] = 0;
  sz[0] = 0;
  flag OK = 0;
  pCHistQueryList pQry = NULL;
  if (GotHistorian)
    {
    byte Opt;
    double StartTime;
    double LastTime;
    byte TimeOpt;
    flag Headings;
    long NoPts;
    CStringArray TagList;
    strncpy(szItem, pszItem, sizeof(szItem)-1);
    int ValidFormat = pDdeExec->InterpretRequest(szItem, Opt, StartTime, LastTime, TimeOpt, Headings, NoPts, TagList);
    int TagCnt = TagList.GetSize();
    if (TagCnt>0 && ValidFormat==0)
      OK = 1;
    if (OK)
      {
      CString Txt;
      pQry = new CHistQueryList(sz);
      //HRoute.dbgDump("Historian Route ");
      CXMsgLst XM;
      CXM_QueryHistoryOther xb(StartTime, LastTime, (long)pQry, Opt, TimeOpt, Headings, NoPts, dNAN, DDE);
      for (int i=0; i<TagCnt; i++)
        {
        Txt = TagList.GetAt(i);
        xb.AddTag((pchar)(const char*)Txt);
        }
      XM.PackMsg(xb);
      XM.PackMsg(HRoute);
      pDdeExec->XSendMessage(XM, HRoute);
      pQry->Wait();
      }
    else
      {
      if (ValidFormat!=0)
        wsprintf(sz, "Cannot retrieve query, invalid format\r\n\r\n");
      else if (TagCnt==0)
        wsprintf(sz, "Cannot retrieve query, no tags were specified\r\n\r\n");
      else
        wsprintf(sz, "InValid\r\n\r\n");
      }
    }
  else
    wsprintf(sz, "No historian configured, cannot retrieve query\r\n\r\n");

  //if (OK)
    {
    if (sz[0]==0)
      wsprintf(sz, "No Valid Tags\r\n\r\n");
    CDDEStringItem* pItem = new CDDEStringItem();
    pItem->Create(pszItem);
    pItem->m_pTopic = this; //do this instead of calling AddItem
    pItem->SetDataOnly(sz);
    BOOL b = pItem->Request(wFmt, ppData, pdwSize);
    delete pQry;
    PostThreadMessage(pDdeExec->dwThreadId, wm_SyscadDdeCommand, MAKEWPARAM(DDE_DELETEITEM, (WORD)0), (LPARAM)pItem);
    return b;
    /*UINT wCBformat = RegisterClipboardFormat((LPSTR)"XlTable");
    return DdeCreateDataHandle(dwDDEInstance(),
      (LPBYTE) sz,
      28,
      0,
      hszItem,
      wCBformat,//XlTable,//CF_TEXT,
      NULL);*/
    }
  return FALSE;
  }
예제 #29
0
/*************************************************************************
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));
    }
}