Пример #1
0
SPPMParameters::SPPMParameters(const ParamArray& params)
  : m_dl_mode(get_mode(params, "dl_mode", SPPM))
  , m_enable_ibl(params.get_optional<bool>("enable_ibl", true))
  , m_enable_caustics(params.get_optional<bool>("enable_caustics", true))
  , m_light_photon_count(params.get_optional<size_t>("light_photons_per_pass", 100000))
  , m_env_photon_count(params.get_optional<size_t>("env_photons_per_pass", 100000))
  , m_photon_packet_size(params.get_optional<size_t>("photon_packet_size", 100000))
  , m_photon_tracing_max_path_length(nz(params.get_optional<size_t>("photon_tracing_max_path_length", 0)))
  , m_photon_tracing_rr_min_path_length(nz(params.get_optional<size_t>("photon_tracing_rr_min_path_length", 3)))
  , m_path_tracing_max_path_length(nz(params.get_optional<size_t>("path_tracing_max_path_length", 0)))
  , m_path_tracing_rr_min_path_length(nz(params.get_optional<size_t>("path_tracing_rr_min_path_length", 3)))
  , m_max_iterations(params.get_optional<size_t>("max_iterations", 1000))
  , m_initial_radius_percents(params.get_required<float>("initial_radius", 0.1f))
  , m_alpha(params.get_optional<float>("alpha", 0.7f))
  , m_max_photons_per_estimate(params.get_optional<size_t>("max_photons_per_estimate", 100))
  , m_dl_light_sample_count(params.get_optional<double>("dl_light_samples", 1.0))
  , m_view_photons(params.get_optional<bool>("view_photons", false))
  , m_view_photons_radius(params.get_optional<float>("view_photons_radius", 1.0e-3f))
{
    // Precompute the reciprocal of the number of light samples.
    m_rcp_dl_light_sample_count =
        m_dl_light_sample_count > 0.0 && m_dl_light_sample_count < 1.0
            ? static_cast<float>(1.0 / m_dl_light_sample_count)
            : 0.0f;
}
void SparseVector<T_Element,T_Alloc>::insert_element(element_type ele)
{
  assert_space(1);
  assert_is_sorted();
  // Find the insertion point
  if( nz() ) {
    typedef SparseVectorUtilityPack::SpVecIndexLookup<T_Element> SpVecIndexLookup;
    typedef typename SpVecIndexLookup::poss_type poss_type;
    index_lookup_.validate_state();
    poss_type poss
      = ( nz()
          ? index_lookup_.find_poss(ele.index(), SpVecIndexLookup::LOWER_ELE)
          : poss_type(0,SpVecIndexLookup::BEFORE_ELE)
        );
    // Make sure this element does not already exist!
#ifdef TEUCHOS_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION(
      nz() && poss.rel == SpVecIndexLookup::EQUAL_TO_ELE, std::length_error
      ,"SparseVector<...>::insert_element(...) : Error, this index"
      " all ready exists!" );
#endif
    const size_type
      insert_poss = (poss.rel == SpVecIndexLookup::BEFORE_ELE ? poss.poss : poss.poss+1);
    // Copy elements out of the way to make room for inserted element
    std::copy_backward( // This assumes element_type supports assignment!
      index_lookup_.ele() + insert_poss, index_lookup_.ele() + index_lookup_.nz()
      , index_lookup_.ele() + index_lookup_.nz() + 1 );
    index_lookup_.ele()[insert_poss] = ele;
    index_lookup_.incr_nz();
  }
  else { // The first element we are adding!
    index_lookup_.ele()[0] = ele;
    index_lookup_.incr_nz();
  }
}
Пример #3
0
static Rcpp::IntegerVector nz_vec(Rcpp::NumericMatrix alpha_new,
				  Rcpp::NumericMatrix eta_new,
				  Rcpp::NumericVector d_new,
				  double eps)
{
  int K = alpha_new.ncol();
  int p = alpha_new.nrow();
  int L = eta_new.nrow();
  
  Rcpp::IntegerVector result(p*K + L*K + L);
 	
  for (int i = 0; i < p*K; i++) {
    result[i] = nz(alpha_new[i],eps);
  }

  for (int i = 0; i < L*K; i++) {
    result[p*K + i] = nz(eta_new[i],eps);
  }

  for (int i = 0; i < L; i++) {
    result[p*K + L*K + i] = nz(d_new[i],eps);
  }

  return result;
}
Пример #4
0
static void
ptransfer(const char *direction, long bytes, 
	  const struct timeval *t0, 
	  const struct timeval *t1)
{
	struct timeval td;
#ifdef EMBED
	/* Use all ints for embedded targets */
	unsigned long s, bs;

	if (ftpverbose) {
		tvsub(&td, t1, t0);
		s = (td.tv_sec * 1000) + (td.tv_usec / 1000);
#define	nz(x)	((x) == 0 ? 1 : (x))
		bs = bytes / nz(s);
		printf("%ld bytes %s in %d secs (%d Kbytes/sec)\n",
		    bytes, direction, (s/1000), bs);
	}
#else
	float s, bs;

	if (ftpverbose) {
		tvsub(&td, t1, t0);
		s = td.tv_sec + (td.tv_usec / 1000000.);
#define	nz(x)	((x) == 0 ? 1 : (x))
		bs = bytes / nz(s);
		printf("%ld bytes %s in %.3g secs (%.2g Kbytes/sec)\n",
		    bytes, direction, s, bs / 1024.0);
	}
#endif
}
Пример #5
0
void Bayes::sample_zpi() {
  //! sample classification
  // ublas::matrix<double> probx(k, n);

  for (int i=0; i<k; ++i) {
    row(probx, i).assign(pi(i) * mvnormpdf(x, mu(i), Omega(i)));
  }

  // print out likelihood
  for (int i=0; i<n; ++i) {
    double tmpsum = sum(column(probx, i));
    if (tmpsum > 0) {
      current += log(tmpsum);
    }
  }
  if (loglik < current && current < 0) {
    loglik = current;
    ml_pi.assign(pi);
    ml_mu.assign(mu);
    ml_Omega.assign(Omega);
  }
  current = 0.0;
  
  ublas::vector<int> nz(k);
  for (int i=0; i<k; ++i)
    nz(i) = 0;

  for (int i=0; i<n; ++i) {
    column(probx, i) /= sum(column(probx, i));
    z(i) = rdisc(column(probx, i));
  }

  // calculate counts and complete data log likelihood
  for (int i=0; i<k; ++i)
    for (int j=0; j<n; ++j)
      if (z[j] == i) {
	nz(i) += 1;
      }

  pi = dirichlet_rnd(nz);

  // get indices sorted in reverse order
  std::vector<int> idx(argsort(pi));
  std::reverse(idx.begin(), idx.end());
  ublas::indirect_array<> u_idx(idx.size());
  for (size_t i=0; i<idx.size(); ++i)
    u_idx(i) = idx[i];

  pi = project(pi, u_idx);
  mu = project(mu, u_idx);
  Omega = project(Omega, u_idx);

  ublas::vector<int> oldz(z);
  for (int i=0; i<k; ++i)
    for (size_t j=0; j<oldz.size(); ++j)
      if (i == oldz[j])
	z[j] = idx[i];

}
Пример #6
0
int main(){
  V3f x(0,0,1); V3f xr(rot_x(x, 0.87)); same("x rotation", x.dot(xr), cos(0.87));
  V3f y(0,0,1); V3f yr(rot_y(y, 0.23)); same("y rotation", y.dot(yr), cos(0.23));
  V3f z(1,0,0); V3f zr(rot_z(z, 0.19)); same("z rotation", z.dot(zr), cos(0.19));

  V3f nx(3,2,5);
  V3f ny(-2,3,4);
  V3f nz(-4,4,3.8);

  V3f nnx(3,2,5);
  V3f nny(-2,3,4);
  V3f nnz(-4,4,3.8);

  ortoNormalize(nnx, nny, nnz);
  
  same("x unit", nnx.length(), 1.0);
  same("y unit", nny.length(), 1.0);
  same("z unit", nnz.length(), 1.0);

  V3f tmp; tmp.cross(nnx, nx);

  same("x colinear", tmp.length(), 0.0);
  
  tmp.cross(nnx, nny); tmp-=nnz; same("x orto", tmp.length(), 0);
  tmp.cross(nny, nnz); tmp-=nnx; same("y orto", tmp.length(), 0);
  tmp.cross(nnz, nnx); tmp-=nny; same("z orto", tmp.length(), 0);


};
Пример #7
0
GLuint FileAssociatedTexture::getOrCreateCube(
	const QString & fileNames
,   OpenGLFunctions & gl
,	const GLenum mag_filter
,	const GLenum min_filter)
{
    if (s_texturesByFilePath.contains(fileNames))
        return s_texturesByFilePath[fileNames];

    QString px(fileNames); px.replace("?", "px");
    QString nx(fileNames); nx.replace("?", "nx");
    QString py(fileNames); py.replace("?", "py");
    QString ny(fileNames); ny.replace("?", "ny");
    QString pz(fileNames); pz.replace("?", "pz");
    QString nz(fileNames); nz.replace("?", "nz");

    QStringList files = QStringList() << px << nx << py << ny << pz << nz;
    QStringList absolutes;
    foreach(const QString & file, files)
    {
        QFileInfo fi(file);
        if (!fi.exists())
        {
            qWarning() << file << " does not exist: texture has no associated file.";
            return -1;
        }
        absolutes << fi.absoluteFilePath();
    }
Пример #8
0
int collide(int *a, int *b)
{
	 // sanity checking
	 if (a == 000 || b == 000)
		  return -1; // bad args
	 if (b[0] < 1)
		  return -2; // x at 0
	 if (b[1] < 1)
		  return -3; // y at 0
	 if (b[2] < 1)
		  return -4; // z at 0
	 if (b[0] > xres)
		  return -5; // x at max
	 if (b[0] > yres)
		  return -6; // y at max
	 if (b[0] > zres)
		  return -7; // z at max

	 int vec[3] = {(b[0]-a[0]), (b[1]-a[1]), (b[2]-a[2])}; // vector
	 int result = 0;

	 /* below is a fairly basic algo to keep checking until there is no conflict
	  * may be optimizable
	  */
	 do
	 {
		  result = 0;
		  if (vec[0] > 0)
		  {
				result += px(&b[0]);
		  }
		  if (vec[1] > 0)
		  {
				result += py(&b[1]);
		  }
		  if (vec[2] > 0)
		  {
				result += pz(&b[2]);
		  }
		  if (vec[0] < 0)
		  {
				result += nx(&b[0]);
		  }
		  if (vec[1] < 0)
		  {
				result += ny(&b[1]);
		  }
		  if (vec[2] < 0)
		  {
				result += nz(&b[2]);
		  }
		  vec[0] = (b[0]-a[0]);
		  vec[1] = (b[1]-a[1]);
		  vec[2] = (b[2]-a[2]); // recalc. should eliminate unnecessary checks
	 }
	 while (result != 0);

	 return 0;
}
Пример #9
0
static int df(Rcpp::NumericMatrix beta_new, double eps)
{
  int result = 0;
  int n = beta_new.nrow() * beta_new.ncol();
  for(int i=0; i < n; i++){
    result += nz(beta_new[i],eps);
  }
  return result;
}
Пример #10
0
//---------------------------------------------------------
void NDG3D::Normals3D()
//---------------------------------------------------------
{
  // function [nx, ny, nz, sJ] = Normals3D()
  // Purpose : Compute outward pointing normals at
  //	    elements faces as well as surface Jacobians

  GeometricFactors3D();

  // interpolate geometric factors to face nodes
  DMat frx=rx(Fmask,All),  fsx=sx(Fmask,All),  ftx=tx(Fmask,All);
  DMat fry=ry(Fmask,All),  fsy=sy(Fmask,All),  fty=ty(Fmask,All);
  DMat frz=rz(Fmask,All),  fsz=sz(Fmask,All),  ftz=tz(Fmask,All);

  // build normals
  nx.resize(4*Nfp, K); ny.resize(4*Nfp, K); nz.resize(4*Nfp, K);
  Index1D fid1(1,Nfp), fid2(Nfp+1,2*Nfp), fid3(2*Nfp+1,3*Nfp), fid4(3*Nfp+1,4*Nfp);

  // face 1
  nx(fid1, All) = -ftx(fid1,All);
  ny(fid1, All) = -fty(fid1,All);
  nz(fid1, All) = -ftz(fid1,All);

  // face 2
  nx(fid2, All) = -fsx(fid2,All);
  ny(fid2, All) = -fsy(fid2,All);
  nz(fid2, All) = -fsz(fid2,All);

  // face 3
  nx(fid3, All) = frx(fid3,All) + fsx(fid3,All) + ftx(fid3,All);
  ny(fid3, All) = fry(fid3,All) + fsy(fid3,All) + fty(fid3,All);
  nz(fid3, All) = frz(fid3,All) + fsz(fid3,All) + ftz(fid3,All);

  // face 4
  nx(fid4, All) = -frx(fid4,All);
  ny(fid4, All) = -fry(fid4,All);
  nz(fid4, All) = -frz(fid4,All);

  // normalise
  sJ = sqrt(sqr(nx) + sqr(ny) + sqr(nz));
  
  nx.div_element(sJ); ny.div_element(sJ); nz.div_element(sJ);
  sJ.mult_element(J(Fmask, All));  //sJ=sJ.*J(Fmask(:),:);
}
Пример #11
0
static Rcpp::IntegerVector nz(Rcpp::NumericVector v, double eps)
{
  int n = v.size();
  Rcpp::IntegerVector result(n);
  
  for(int i=0; i < n; i++){
    result[i] = nz(v[i],eps);
  }
  return result;
}
Пример #12
0
static Rcpp::IntegerMatrix nz(Rcpp::NumericMatrix m, double eps)
{
  int nr = m.nrow();
  int nc = m.ncol();
  Rcpp::IntegerMatrix result(nr, nc);
  for(int i=0; i < nr*nc; i++){
    result[i] = nz(m[i],eps);
  }
  return result;
}
AbstractLinAlgPack::size_type
AbstractLinAlgPack::SparseVectorUtilityPack::SpVecIndexLookup<T_Element>::find_element(
  index_type index, bool is_sorted ) const
{
  typedef T_Element* itr_t;
  if(is_sorted) {
    const std::pair<itr_t,itr_t> p = std::equal_range( ele(), ele() + nz()
      , index - offset(), compare_element_indexes_less<element_type>() );
    // If p.second - p.first == 1 then the element exits
    if( p.second - p.first == 1 )
      return p.first - ele();	// zero based
    else
      return nz(); // zero based
  }
  else {
    const itr_t itr = std::find_if( ele(), ele() + nz()
      , compare_element_indexes_equal_to<element_type>(index - offset()) );
    return itr - ele();	// zero based
  }
}
Пример #14
0
Matrixf3& Matrixf3::operator *= (const Matrixf3& m)
{
	Pointf3 nx(x ^ m.CX(), x ^ m.CY(), x ^ m.CZ());
	Pointf3 ny(y ^ m.CX(), y ^ m.CY(), y ^ m.CZ());
	Pointf3 nz(z ^ m.CX(), z ^ m.CY(), z ^ m.CZ());
	x = nx;
	y = ny;
	z = nz;
	a *= m;
	return *this;
}
Пример #15
0
void
mb(uint64 bytes)
{
    struct timeval td;
    double  s, bs;

    tvsub(&td, &stop_tv, &start_tv);
    s = td.tv_sec + td.tv_usec / 1000000.0;
    bs = bytes / nz(s);
    if (!ftiming) ftiming = stderr;
    (void) fprintf(ftiming, "%.2f MB/sec\n", bs / MB);
}
void Mesh::makeSurfaceMesh()
{  // Hill, F.S. Jr., "Computer Graphics using OpenGL", 2nd edition, 2002, p.355,
   //   Case Study 6.13, Drawing smooth parametric surfaces.
        int i, j;
        double pi = 3.141592653589793 ;
        int numValsU = 40; 
        int numValsV = 40;       // set these
	/*double u, v, uMin = -pi;
        double vMin = -pi;
	double uMax = pi;
        double vMax = pi;*/
        double u, v, uMin = -pi/4;
        double vMin = -pi/4;
	double uMax = pi/4;
        double vMax = pi/4;
	double delU = (uMax - uMin)/(numValsU - 1);
	double delV = (vMax - vMin)/(numValsV - 1);

	numVerts = numValsU * numValsV + 1; // total # of vertices
	numFaces = (numValsU -1) * (numValsV - 1) ; // # of faces
	numNormals = numVerts; // for smooth shading - one normal per vertex
	pt   = new Point3[numVerts];   // make space 
	face = new Face[numFaces];    
	norm = new Vector3[numNormals]; 

	for(i = 0, u = uMin; i < numValsU; i++, u += delU)
		for(j = 0, v = vMin; j < numValsV; j++, v += delV)
		{
			int whichVert = i * numValsV + j; //index of the vertex and normal
			// set this vertex: use functions X, Y, and Z
			pt[whichVert].set(X(u, v),Y(u, v),Z(u, v));
			// set the normal at this vertex: use functions nx, ny, nz
			norm[whichVert].set(nx(u, v), ny(u, v), nz(u, v));
			norm[whichVert].normalize();
			// make quadrilateral
			if(i > 0 && j > 0) // when to compute next face
			{
				int whichFace =(i - 1) * (numValsV - 1) + (j - 1); 
				face[whichFace].vert = new VertexID[4];
				//assert(face[whichFace].vert != NULL);
				face[whichFace].nVerts = 4;
				face[whichFace].vert[0].vertIndex = // same as norm index
				face[whichFace].vert[0].normIndex = whichVert;
				face[whichFace].vert[1].vertIndex = 
				face[whichFace].vert[1].normIndex = whichVert - 1;
				face[whichFace].vert[2].vertIndex = 
				face[whichFace].vert[2].normIndex = whichVert - numValsV - 1;
				face[whichFace].vert[3].vertIndex = 
				face[whichFace].vert[3].normIndex = whichVert - numValsV;
			}
		}
}
Пример #17
0
void
mb(uint64 bytes)
{
	struct timeval td;
	double  s, bs;

	tvsub(&td, &stop_tv, &start_tv);
	s = td.tv_sec + td.tv_usec / 1000000.0;
	bs = bytes / nz(s);
	if (s == 0.0) return;
	if (!ftiming) ftiming = stderr;
	(void) fprintf(ftiming, "<measurement units=\"MB/sec\">%.2f</measurement>\n", bs / MB);
}
Пример #18
0
static void
ptransfer(const char *direction, long bytes, 
	  const struct timeval *t0, 
	  const struct timeval *t1)
{
	struct timeval td;
	float s, bs;

	if (verbose) {
		tvsub(&td, t1, t0);
		s = td.tv_sec + (td.tv_usec / 1000000.);
#define	nz(x)	((x) == 0 ? 1 : (x))
		bs = bytes / nz(s);
		printf("%ld bytes %s in %.3g secs (%.2g Kbytes/sec)\n",
		    bytes, direction, s, bs / 1024.0);
	}
}
SparseVector<T_Element,T_Alloc>&
SparseVector<T_Element,T_Alloc>::operator=(
  const SparseVector<T_Element,T_Alloc>& sp_vec)
{
  if(this == &sp_vec) return *this;	// assignment to self

  know_is_sorted_ = sp_vec.know_is_sorted_;
  assume_sorted_ = sp_vec.assume_sorted_;

  if( max_nz() < sp_vec.nz() ) {
    // need to allocate more storage
    resize(0,0);	// free current storage
    resize(sp_vec.dim(),sp_vec.nz(),sp_vec.offset());
  }
  else if( nz() ) {
    // Don't allocate new memory, just call distructors on current elements
    // and reset to uninitialized.
    for(iterator ele_itr = begin(); ele_itr != end();) {
#ifdef _PG_CXX
      (ele_itr++)->~element_type();
#else
      alloc_.destroy(ele_itr++);
#endif
    }
    // Set the other data
    size_ = sp_vec.size_;
  }
  
  // set nz and offset
  index_lookup_.set_sp_vec(index_lookup_.ele(),sp_vec.nz(),sp_vec.offset()); 

  if( sp_vec.nz() ) {
    // Perform an uninitialized copy of the elements
    iterator		ele_to_itr		= index_lookup_.ele();
    const_iterator	ele_from_itr	= sp_vec.begin();
    while(ele_from_itr != sp_vec.end()) {
#ifdef _PG_CXX
      new (ele_to_itr++) element_type(*ele_from_itr++);
#else
      alloc_.construct(ele_to_itr++,*ele_from_itr++);
#endif
    }
  }

  return *this;
}
Пример #20
0
static Rcpp::NumericMatrix refit_model(Rcpp::NumericMatrix X,
				       Rcpp::NumericVector y,
				       Rcpp::NumericMatrix beta_new,
				       Rcpp::IntegerVector nk,
				       int model,
				       double eps,
				       int maxiter)
{
  int K = nk.size();
  int p = X.ncol();
  int n;
  Rcpp::NumericMatrix Xtmp(X.nrow(),p);
  Rcpp::NumericMatrix beta_refit(p,K);
  Rcpp::NumericVector lasso_result;
 
  int idx = 0;
  for (int k = 0; k < K; k++) {
    n = nk[k];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < p; j++) {
	Xtmp(idx+i,j) = X(idx+i,j) * nz(beta_new(j,k),eps);
      }
    }
    idx += n;
  }
   
 
  idx = 0;
  for (int k = 0; k < K; k++) {
    n = nk[k];
    lasso_result = lasso(Xtmp(Rcpp::Range(idx,idx+n-1),Rcpp::_), y[Rcpp::Range(idx,idx+n-1)], 0.0, model, false, eps, maxiter);
    for(int j = 0; j < p; j++){
      beta_refit(j,k) = lasso_result[j];
    }
    idx += n;
  }
  
  return beta_refit;
}
Пример #21
0
bool 
Sol_MultigridPressure3DBase::initialize_base_storage(int nx_val, int ny_val, int nz_val, double hx_val, double hy_val, double hz_val)
{
  // pre-validate
  if (!check_float(hx_val) || !check_float(hy_val) || !check_float(hz_val)) {
    printf("[ERROR] Sol_MultigridPressure3DBase::initialize_storage - garbage hx,hy,hz value %f %f %f\n", hx_val, hy_val, hz_val);
    return false;
  }

  // do allocation and initialization
  _num_levels = num_levels(nx_val, ny_val, nz_val);

  _h = new double[_num_levels];
  _dim = new int3[_num_levels];
  _h[0] = min3(hx_val, hy_val, hz_val);
  _fx = (_h[0] * _h[0]) / (hx_val * hx_val);
  _fy = (_h[0] * _h[0]) / (hy_val * hy_val);
  _fz = (_h[0] * _h[0]) / (hz_val * hz_val);
  _omega = optimal_omega(_fx, _fy, _fz);
  _dim[0].x = nx_val;
  _dim[0].y = ny_val;
  _dim[0].z = nz_val;

  int level;
  for (level=1; level < _num_levels; level++) {
    int this_nx = nx(level-1)/2;
    int this_ny = ny(level-1)/2;
    int this_nz = nz(level-1)/2;

    _h[level] = get_h(level-1)*2;
    _dim[level].x = this_nx;
    _dim[level].y = this_ny;
    _dim[level].z = this_nz;
  }

  return true;
}
Пример #22
0
ngl::Mat4 Bvh::getRotationFromZ(ngl::Vec3 _vec) const
{
    ngl::Mat4 rotM;
    float x, y, z;
    // rotate negative z axis to _vec direction
    _vec.normalize();
    ngl::Vec3 nz(0,0,-1);
    float angle = acos(_vec.dot(nz));
    ngl::Vec3 norm = _vec.cross(nz);
    if(norm.length()<= 0.0001)
    {
        x= z = 0.0;
        y = 1.0;
    }
    else
    {
        norm.normalize();
        x = norm.m_x;
        y = norm.m_y;
        z = norm.m_z;
    }

    // Axis and Angle matrix rotation see
    // http://en.wikipedia.org/wiki/Rotation_matrix for more details
    float c = cos(angle);
    float s = sin(angle);
    float C=1-c;
    float xs  = x*s;  float  ys = y*s;  float  zs = z*s;
    float xC  = x*C;  float  yC = y*C;  float  zC = z*C;
    float xyC = x*yC; float yzC = y*zC; float zxC = z*xC;

    rotM.m_m[0][0]=x*xC+c;  rotM.m_m[0][1]= xyC-zs;  rotM.m_m[0][2]= zxC+ys;
    rotM.m_m[1][0]=xyC+zs;   rotM.m_m[1][1]=y*yC+c;  rotM.m_m[1][2]= yzC-xs;
    rotM.m_m[2][0]=zxC-ys;   rotM.m_m[2][1]=yzC+xs;  rotM.m_m[2][2]=z*zC+c;
    return rotM;
}
Пример #23
0
		sparse<T> sparse<T>::transpose() const
		{
			sparse<T> b(symbolic::sparse::transpose());

			dense_vector<size_t> nz(nrow, 0u);
			for (size_t j = 0; j < b.ncol; ++j)
			{
				nz[j] = b.pc[j];
			}

			for (size_t j = 0; j < ncol; ++j)
			{
				for (size_t i = pc[j]; i < pc[j + 1]; ++i)
				{
					size_t k = ir[i];

					b.x[nz[k]] = x[i];

					++nz[k];
				}
			}

			return b;
		}
Пример #24
0
    osg::Node* createCube(unsigned int mask)
    {
        osg::Geode* geode = new osg::Geode;

        osg::Geometry* geometry = new osg::Geometry;
        geode->addDrawable(geometry);

        osg::Vec3Array* vertices = new osg::Vec3Array;
        geometry->setVertexArray(vertices);

        osg::Vec3Array* normals = new osg::Vec3Array;
        geometry->setNormalArray(normals, osg::Array::BIND_PER_VERTEX);

        osg::Vec4Array* colours = new osg::Vec4Array;
        geometry->setColorArray(colours, osg::Array::BIND_OVERALL);
        colours->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));


        osg::Vec3 origin(0.0f,0.0f,0.0f);
        osg::Vec3 dx(2.0f,0.0f,0.0f);
        osg::Vec3 dy(0.0f,1.0f,0.0f);
        osg::Vec3 dz(0.0f,0.0f,1.0f);

        osg::Vec3 px(1.0f,0.0,0.0f);
        osg::Vec3 nx(-1.0f,0.0,0.0f);
        osg::Vec3 py(0.0f,1.0f,0.0f);
        osg::Vec3 ny(0.0f,-1.0f,0.0f);
        osg::Vec3 pz(0.0f,0.0f,1.0f);
        osg::Vec3 nz(0.0f,0.0f,-1.0f);

        if (mask & FRONT_FACE)
        {
            // front face
            vertices->push_back(origin);
            vertices->push_back(origin+dx);
            vertices->push_back(origin+dx+dz);
            vertices->push_back(origin+dz);
            normals->push_back(ny);
            normals->push_back(ny);
            normals->push_back(ny);
            normals->push_back(ny);
        }

        if (mask & BACK_FACE)
        {
            // back face
            vertices->push_back(origin+dy);
            vertices->push_back(origin+dy+dz);
            vertices->push_back(origin+dy+dx+dz);
            vertices->push_back(origin+dy+dx);
            normals->push_back(py);
            normals->push_back(py);
            normals->push_back(py);
            normals->push_back(py);
        }

        if (mask & LEFT_FACE)
        {
            // left face
            vertices->push_back(origin+dy);
            vertices->push_back(origin);
            vertices->push_back(origin+dz);
            vertices->push_back(origin+dy+dz);
            normals->push_back(nx);
            normals->push_back(nx);
            normals->push_back(nx);
            normals->push_back(nx);
        }

        if (mask & RIGHT_FACE)
        {
            // right face
            vertices->push_back(origin+dx+dy);
            vertices->push_back(origin+dx+dy+dz);
            vertices->push_back(origin+dx+dz);
            vertices->push_back(origin+dx);
            normals->push_back(px);
            normals->push_back(px);
            normals->push_back(px);
            normals->push_back(px);
        }

        if (mask & TOP_FACE)
        {
            // top face
            vertices->push_back(origin+dz);
            vertices->push_back(origin+dz+dx);
            vertices->push_back(origin+dz+dx+dy);
            vertices->push_back(origin+dz+dy);
            normals->push_back(pz);
            normals->push_back(pz);
            normals->push_back(pz);
            normals->push_back(pz);
        }

        if (mask & BOTTOM_FACE)
        {
            // bottom face
            vertices->push_back(origin);
            vertices->push_back(origin+dy);
            vertices->push_back(origin+dx+dy);
            vertices->push_back(origin+dx);
            normals->push_back(nz);
            normals->push_back(nz);
            normals->push_back(nz);
            normals->push_back(nz);
        }

        geometry->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, vertices->size()));

        return geode;
    }
Пример #25
0
int main(int argc, char** argv) {
    const double PI(3.141592653589793);

    if (argc != 4) {
        std::cout << "usage:" << std::endl;
        std::cout << "package_scene path_scene output" << std::endl;
        return 0;
    }
    ros::init(argc, argv, "dart_test");

    ros::NodeHandle nh_;

    std::string package_name( argv[1] );
    std::string scene_urdf( argv[2] );

    ros::Rate loop_rate(400);

    ros::Publisher joint_state_pub_;
    joint_state_pub_ = nh_.advertise<sensor_msgs::JointState>("/joint_states", 10);
    tf::TransformBroadcaster br;
    MarkerPublisher markers_pub(nh_);

    std::string package_path_barrett = ros::package::getPath("barrett_hand_defs");
    std::string package_path = ros::package::getPath(package_name);

    // Load the Skeleton from a file
    dart::utils::DartLoader loader;
    loader.addPackageDirectory("barrett_hand_defs", package_path_barrett);
    loader.addPackageDirectory("barrett_hand_sim_dart", package_path);

    boost::shared_ptr<GraspSpecification > gspec = GraspSpecification::readFromUrdf(package_path + scene_urdf);

    dart::dynamics::SkeletonPtr scene( loader.parseSkeleton(package_path + scene_urdf) );
    scene->enableSelfCollision(true);

    dart::dynamics::SkeletonPtr bh( loader.parseSkeleton(package_path_barrett + "/robots/barrett_hand.urdf") );
    Eigen::Isometry3d tf;
    tf = scene->getBodyNode("gripper_mount_link")->getRelativeTransform();
    bh->getJoint(0)->setTransformFromParentBodyNode(tf);

    dart::simulation::World* world = new dart::simulation::World();

    world->addSkeleton(scene);
    world->addSkeleton(bh);

    Eigen::Vector3d grav(0,0,-1);
    world->setGravity(grav);

    GripperController gc;

    double Kc = 400.0;
    double KcDivTi = Kc / 1.0;
    gc.addJoint("right_HandFingerOneKnuckleOneJoint", Kc, KcDivTi, 0.0, 0.001, 50.0, true, false);
    gc.addJoint("right_HandFingerOneKnuckleTwoJoint", Kc, KcDivTi, 0.0, 0.001, 50.0, false, true);
    gc.addJoint("right_HandFingerTwoKnuckleTwoJoint", Kc, KcDivTi, 0.0, 0.001, 50.0, false, true);
    gc.addJoint("right_HandFingerThreeKnuckleTwoJoint", Kc, KcDivTi, 0.0, 0.001, 50.0, false, true);

    gc.addJointMimic("right_HandFingerTwoKnuckleOneJoint", 2.0*Kc, KcDivTi, 0.0, 0.001, 50.0, true, "right_HandFingerOneKnuckleOneJoint", 1.0, 0.0);
    gc.addJointMimic("right_HandFingerOneKnuckleThreeJoint", 2.0*Kc, KcDivTi, 0.0, 0.001, 50.0, false, "right_HandFingerOneKnuckleTwoJoint", 0.333333, 0.0);
    gc.addJointMimic("right_HandFingerTwoKnuckleThreeJoint", 2.0*Kc, KcDivTi, 0.0, 0.001, 50.0, false, "right_HandFingerTwoKnuckleTwoJoint", 0.333333, 0.0);
    gc.addJointMimic("right_HandFingerThreeKnuckleThreeJoint", 2.0*Kc, KcDivTi, 0.0, 0.001, 50.0, false, "right_HandFingerThreeKnuckleTwoJoint", 0.333333, 0.0);

    gc.setGoalPosition("right_HandFingerOneKnuckleOneJoint", gspec->getGoalPosition("right_HandFingerOneKnuckleOneJoint"));
    gc.setGoalPosition("right_HandFingerOneKnuckleTwoJoint", gspec->getGoalPosition("right_HandFingerOneKnuckleTwoJoint"));
    gc.setGoalPosition("right_HandFingerTwoKnuckleTwoJoint", gspec->getGoalPosition("right_HandFingerTwoKnuckleTwoJoint"));
    gc.setGoalPosition("right_HandFingerThreeKnuckleTwoJoint", gspec->getGoalPosition("right_HandFingerThreeKnuckleTwoJoint"));

    std::map<std::string, double> joint_q_map;
    joint_q_map["right_HandFingerOneKnuckleOneJoint"] = gspec->getInitPosition("right_HandFingerOneKnuckleOneJoint");
    joint_q_map["right_HandFingerTwoKnuckleOneJoint"] = gspec->getInitPosition("right_HandFingerOneKnuckleOneJoint");
    joint_q_map["right_HandFingerOneKnuckleTwoJoint"] = gspec->getInitPosition("right_HandFingerOneKnuckleTwoJoint");
    joint_q_map["right_HandFingerOneKnuckleThreeJoint"] = 0.333333 * gspec->getInitPosition("right_HandFingerOneKnuckleTwoJoint");
    joint_q_map["right_HandFingerTwoKnuckleTwoJoint"] = gspec->getInitPosition("right_HandFingerTwoKnuckleTwoJoint");
    joint_q_map["right_HandFingerTwoKnuckleThreeJoint"] = 0.333333 * gspec->getInitPosition("right_HandFingerTwoKnuckleTwoJoint");
    joint_q_map["right_HandFingerThreeKnuckleTwoJoint"] = gspec->getInitPosition("right_HandFingerThreeKnuckleTwoJoint");
    joint_q_map["right_HandFingerThreeKnuckleThreeJoint"] = 0.333333 * gspec->getInitPosition("right_HandFingerThreeKnuckleTwoJoint");

    for (std::vector<std::string >::const_iterator it = gc.getJointNames().begin(); it != gc.getJointNames().end(); it++) {
        dart::dynamics::Joint *j = bh->getJoint((*it));
        j->setActuatorType(dart::dynamics::Joint::FORCE);
     	j->setPositionLimited(true);
        j->setPosition(0, joint_q_map[(*it)]);
    }

    int counter = 0;

    while (ros::ok()) {
        world->step(false);

        for (std::map<std::string, double>::iterator it = joint_q_map.begin(); it != joint_q_map.end(); it++) {
            dart::dynamics::Joint *j = bh->getJoint(it->first);
            it->second = j->getPosition(0);
        }

        gc.controlStep(joint_q_map);

        // Compute the joint forces needed to compensate for Coriolis forces and
        // gravity
        const Eigen::VectorXd& Cg = bh->getCoriolisAndGravityForces();

        for (std::map<std::string, double>::iterator it = joint_q_map.begin(); it != joint_q_map.end(); it++) {
            dart::dynamics::Joint *j = bh->getJoint(it->first);
            int qidx = j->getIndexInSkeleton(0);
            double u = gc.getControl(it->first);
            double dq = j->getVelocity(0);
            if (!gc.isBackdrivable(it->first)) {
                j->setPositionLowerLimit(0, std::max(j->getPositionLowerLimit(0), it->second-0.01));
            }

            if (gc.isStopped(it->first)) {
                j->setPositionLowerLimit(0, std::max(j->getPositionLowerLimit(0), it->second-0.01));
                j->setPositionUpperLimit(0, std::min(j->getPositionUpperLimit(0), it->second+0.01));
//                std::cout << it->first << " " << "stopped" << std::endl;
            }
            j->setForce(0, 0.02*(u-dq) + Cg(qidx));
        }

        for (int bidx = 0; bidx < bh->getNumBodyNodes(); bidx++) {
            dart::dynamics::BodyNode *b = bh->getBodyNode(bidx);
            const Eigen::Isometry3d &tf = b->getTransform();
            KDL::Frame T_W_L;
            EigenTfToKDL(tf, T_W_L);
//            std::cout << b->getName() << std::endl;
            publishTransform(br, T_W_L, b->getName(), "world");
        }

        int m_id = 0;
        for (int bidx = 0; bidx < scene->getNumBodyNodes(); bidx++) {
                dart::dynamics::BodyNode *b = scene->getBodyNode(bidx);

                const Eigen::Isometry3d &tf = b->getTransform();
                KDL::Frame T_W_L;
                EigenTfToKDL(tf, T_W_L);
                publishTransform(br, T_W_L, b->getName(), "world");
                for (int cidx = 0; cidx < b->getNumCollisionShapes(); cidx++) {
                    dart::dynamics::ConstShapePtr sh = b->getCollisionShape(cidx);
                    if (sh->getShapeType() == dart::dynamics::Shape::MESH) {
                        std::shared_ptr<const dart::dynamics::MeshShape > msh = std::static_pointer_cast<const dart::dynamics::MeshShape >(sh);
                        m_id = markers_pub.addMeshMarker(m_id, KDL::Vector(), 0, 1, 0, 1, 1, 1, 1, msh->getMeshUri(), b->getName());
                    }
                }
        }

        markers_pub.publish();

        ros::spinOnce();
        loop_rate.sleep();

        counter++;
        if (counter < 3000) {
        }
        else if (counter == 3000) {
            dart::dynamics::Joint::Properties prop = bh->getJoint(0)->getJointProperties();
            dart::dynamics::FreeJoint::Properties prop_free;
            prop_free.mName = prop_free.mName;
            prop_free.mT_ParentBodyToJoint = prop.mT_ParentBodyToJoint;
            prop_free.mT_ChildBodyToJoint = prop.mT_ChildBodyToJoint;
            prop_free.mIsPositionLimited = false;
            prop_free.mActuatorType = dart::dynamics::Joint::VELOCITY;
            bh->getRootBodyNode()->changeParentJointType<dart::dynamics::FreeJoint >(prop_free);
        }
        else if (counter < 4000) {
            bh->getDof("Joint_pos_z")->setVelocity(-0.1);
        }
        else {
            break;
        }
    }

    //
    // generate models
    //

    const std::string ob_name( "graspable" );

    scene->getBodyNode(ob_name)->setFrictionCoeff(0.001);

    // calculate point clouds for all links and for the grasped object
    std::map<std::string, pcl::PointCloud<pcl::PointNormal>::Ptr > point_clouds_map;
    std::map<std::string, pcl::PointCloud<pcl::PrincipalCurvatures>::Ptr > point_pc_clouds_map;
    std::map<std::string, KDL::Frame > frames_map;
    std::map<std::string, boost::shared_ptr<std::vector<KDL::Frame > > > features_map;
    std::map<std::string, boost::shared_ptr<pcl::VoxelGrid<pcl::PointNormal> > > grids_map;
    for (int skidx = 0; skidx < world->getNumSkeletons(); skidx++) {
        dart::dynamics::SkeletonPtr sk = world->getSkeleton(skidx);

        for (int bidx = 0; bidx < sk->getNumBodyNodes(); bidx++) {
            dart::dynamics::BodyNode *b = sk->getBodyNode(bidx);
            const Eigen::Isometry3d &tf = b->getTransform();
            const std::string &body_name = b->getName();
            if (body_name.find("right_Hand") != 0 && body_name != ob_name) {
                continue;
            }
            KDL::Frame T_W_L;
            EigenTfToKDL(tf, T_W_L);
            std::cout << body_name << "   " << b->getNumCollisionShapes() << std::endl;
            for (int cidx = 0; cidx < b->getNumCollisionShapes(); cidx++) {
                dart::dynamics::ConstShapePtr sh = b->getCollisionShape(cidx);
                if (sh->getShapeType() == dart::dynamics::Shape::MESH) {
                    std::shared_ptr<const dart::dynamics::MeshShape > msh = std::static_pointer_cast<const dart::dynamics::MeshShape >(sh);
                    std::cout << "mesh path: " << msh->getMeshPath() << std::endl;
                    std::cout << "mesh uri: " << msh->getMeshUri() << std::endl;
                    const Eigen::Isometry3d &tf = sh->getLocalTransform();
                    KDL::Frame T_L_S;
                    EigenTfToKDL(tf, T_L_S);
                    KDL::Frame T_S_L = T_L_S.Inverse();

                    const aiScene *sc = msh->getMesh();
                    if (sc->mNumMeshes != 1) {
                        std::cout << "ERROR: sc->mNumMeshes = " << sc->mNumMeshes << std::endl;
                    }
                    int midx = 0;
//                    std::cout << "v: " << sc->mMeshes[midx]->mNumVertices << "   f: " << sc->mMeshes[midx]->mNumFaces << std::endl;
                    pcl::PointCloud<pcl::PointNormal>::Ptr cloud_1 (new pcl::PointCloud<pcl::PointNormal>);
                    uniform_sampling(sc->mMeshes[midx], 1000000, *cloud_1);
                    for (int pidx = 0; pidx < cloud_1->points.size(); pidx++) {
                        KDL::Vector pt_L = T_L_S * KDL::Vector(cloud_1->points[pidx].x, cloud_1->points[pidx].y, cloud_1->points[pidx].z);
                        cloud_1->points[pidx].x = pt_L.x();
                        cloud_1->points[pidx].y = pt_L.y();
                        cloud_1->points[pidx].z = pt_L.z();
                    }
                    // Voxelgrid
                    boost::shared_ptr<pcl::VoxelGrid<pcl::PointNormal> > grid_(new pcl::VoxelGrid<pcl::PointNormal>);
                    pcl::PointCloud<pcl::PointNormal>::Ptr res(new pcl::PointCloud<pcl::PointNormal>);
                    grid_->setDownsampleAllData(true);
                    grid_->setSaveLeafLayout(true);
                    grid_->setInputCloud(cloud_1);
                    grid_->setLeafSize(0.004, 0.004, 0.004);
                    grid_->filter (*res);
                    point_clouds_map[body_name] = res;
                    frames_map[body_name] = T_W_L;
                    grids_map[body_name] = grid_;

                    std::cout << "res->points.size(): " << res->points.size() << std::endl;

                    pcl::search::KdTree<pcl::PointNormal>::Ptr tree (new pcl::search::KdTree<pcl::PointNormal>);

                    // Setup the principal curvatures computation
                    pcl::PrincipalCurvaturesEstimation<pcl::PointNormal, pcl::PointNormal, pcl::PrincipalCurvatures> principalCurvaturesEstimation;

                    // Provide the original point cloud (without normals)
                    principalCurvaturesEstimation.setInputCloud (res);

                    // Provide the point cloud with normals
                    principalCurvaturesEstimation.setInputNormals(res);

                    // Use the same KdTree from the normal estimation
                    principalCurvaturesEstimation.setSearchMethod (tree);
                    principalCurvaturesEstimation.setRadiusSearch(0.02);

                    // Actually compute the principal curvatures
                    pcl::PointCloud<pcl::PrincipalCurvatures>::Ptr principalCurvatures (new pcl::PointCloud<pcl::PrincipalCurvatures> ());
                    principalCurvaturesEstimation.compute (*principalCurvatures);
                    point_pc_clouds_map[body_name] = principalCurvatures;

                    features_map[body_name].reset( new std::vector<KDL::Frame >(res->points.size()) );
                    for (int pidx = 0; pidx < res->points.size(); pidx++) {
                        KDL::Vector nx, ny, nz(res->points[pidx].normal[0], res->points[pidx].normal[1], res->points[pidx].normal[2]);
                        if ( std::fabs( principalCurvatures->points[pidx].pc1 - principalCurvatures->points[pidx].pc2 ) > 0.001) {
                            nx = KDL::Vector(principalCurvatures->points[pidx].principal_curvature[0], principalCurvatures->points[pidx].principal_curvature[1], principalCurvatures->points[pidx].principal_curvature[2]);
                        }
                        else {
                            if (std::fabs(nz.z()) < 0.7) {
                                nx = KDL::Vector(0, 0, 1);
                            }
                            else {
                                nx = KDL::Vector(1, 0, 0);
                            }
                        }
                        ny = nz * nx;
                        nx = ny * nz;
                        nx.Normalize();
                        ny.Normalize();
                        nz.Normalize();
                        (*features_map[body_name])[pidx] = KDL::Frame( KDL::Rotation(nx, ny, nz), KDL::Vector(res->points[pidx].x, res->points[pidx].y, res->points[pidx].z) );
                    }
                }
            }
        }
    }

    const double sigma_p = 0.01;//05;
    const double sigma_q = 10.0/180.0*PI;//100.0;
    const double sigma_r = 0.2;//05;
    double sigma_c = 5.0/180.0*PI;

    int m_id = 101;

    // generate object model
    boost::shared_ptr<ObjectModel > om(new ObjectModel);
    for (int pidx = 0; pidx < point_clouds_map[ob_name]->points.size(); pidx++) {
        if (point_pc_clouds_map[ob_name]->points[pidx].pc1 > 1.1 * point_pc_clouds_map[ob_name]->points[pidx].pc2) {
            // e.g. pc1=1, pc2=0
            // edge
            om->addPointFeature((*features_map[ob_name])[pidx] * KDL::Frame(KDL::Rotation::RotZ(PI)), point_pc_clouds_map[ob_name]->points[pidx].pc1, point_pc_clouds_map[ob_name]->points[pidx].pc2);
            om->addPointFeature((*features_map[ob_name])[pidx], point_pc_clouds_map[ob_name]->points[pidx].pc1, point_pc_clouds_map[ob_name]->points[pidx].pc2);
        }
        else {
            for (double angle = 0.0; angle < 359.0/180.0*PI; angle += 20.0/180.0*PI) {
                om->addPointFeature((*features_map[ob_name])[pidx] * KDL::Frame(KDL::Rotation::RotZ(angle)), point_pc_clouds_map[ob_name]->points[pidx].pc1, point_pc_clouds_map[ob_name]->points[pidx].pc2);
            }
        }
    }


    std::cout << "om.getPointFeatures().size(): " << om->getPointFeatures().size() << std::endl;
    KDL::Frame T_W_O = frames_map[ob_name];

    // generate collision model
    std::map<std::string, std::list<std::pair<int, double> > > link_pt_map;
    boost::shared_ptr<CollisionModel > cm(new CollisionModel);
    cm->setSamplerParameters(sigma_p, sigma_q, sigma_r);

    std::list<std::string > gripper_link_names;
    for (int bidx = 0; bidx < bh->getNumBodyNodes(); bidx++) {
        const std::string &link_name = bh->getBodyNode(bidx)->getName();
        gripper_link_names.push_back(link_name);
    }

    double dist_range = 0.01;
    for (std::list<std::string >::const_iterator nit = gripper_link_names.begin(); nit != gripper_link_names.end(); nit++) {
        const std::string &link_name = (*nit);
        if (point_clouds_map.find( link_name ) == point_clouds_map.end()) {
            continue;
        }
        cm->addLinkContacts(dist_range, link_name, point_clouds_map[link_name], frames_map[link_name],
                            om->getPointFeatures(), T_W_O);
    }

    // generate hand configuration model
    boost::shared_ptr<HandConfigurationModel > hm(new HandConfigurationModel);
    std::map<std::string, double> joint_q_map_before( joint_q_map );

    double angleDiffKnuckleTwo = 15.0/180.0*PI;
    joint_q_map_before["right_HandFingerOneKnuckleTwoJoint"] -= angleDiffKnuckleTwo;
    joint_q_map_before["right_HandFingerTwoKnuckleTwoJoint"] -= angleDiffKnuckleTwo;
    joint_q_map_before["right_HandFingerThreeKnuckleTwoJoint"] -= angleDiffKnuckleTwo;
    joint_q_map_before["right_HandFingerOneKnuckleThreeJoint"] -= angleDiffKnuckleTwo*0.333333;
    joint_q_map_before["right_HandFingerTwoKnuckleThreeJoint"] -= angleDiffKnuckleTwo*0.333333;
    joint_q_map_before["right_HandFingerThreeKnuckleThreeJoint"] -= angleDiffKnuckleTwo*0.333333;

    hm->generateModel(joint_q_map_before, joint_q_map, 1.0, 10, sigma_c);

    writeToXml(argv[3], cm, hm);

    return 0;
}
Пример #26
0
void
showkre(void)
{
	float f1, f2;
	int psiz;
	int i, lc;
	long inttotal;
	long l;
	static int failcnt = 0;
	double total_time;

	etime = 0;
	CP_UPDATE(cp_time.cp_user);
	CP_UPDATE(cp_time.cp_nice);
	CP_UPDATE(cp_time.cp_sys);
	CP_UPDATE(cp_time.cp_intr);
	CP_UPDATE(cp_time.cp_idle);

	total_time = etime;
	if (total_time == 0.0)
		total_time = 1.0;

	if (etime < 100000.0) {	/* < 100ms ignore this trash */
		if (failcnt++ >= MAXFAIL) {
			clear();
			mvprintw(2, 10, "The alternate system clock has died!");
			mvprintw(3, 10, "Reverting to ``pigs'' display.");
			move(CMDLINE, 0);
			refresh();
			failcnt = 0;
			sleep(5);
			command("pigs");
		}
		return;
	}
	failcnt = 0;
	etime /= 1000000.0;
	etime /= ncpu;
	if (etime == 0)
		etime = 1;
	inttotal = 0;
	for (i = 0; i < nintr; i++) {
		if (s.intrcnt[i] == 0)
			continue;
		if (intrloc[i] == 0) {
			if (nextintsrow == LINES)
				continue;
			intrloc[i] = nextintsrow++;
			mvprintw(intrloc[i], INTSCOL + 9, "%-10.10s",
				intrname[i]);
		}
		X(intrcnt);
		l = (long)((float)s.intrcnt[i]/etime + 0.5);
		inttotal += l;
		put64(l, intrloc[i], INTSCOL + 2, 6, 'D');
	}
	put64(inttotal, INTSROW + 1, INTSCOL + 2, 6, 'D');
	Z(ncs_goodhits); Z(ncs_badhits); Z(ncs_miss);
	Z(ncs_longhits); Z(ncs_longmiss); Z(ncs_neghits);
	s.nchcount = nchtotal.ncs_goodhits + nchtotal.ncs_badhits +
	    nchtotal.ncs_miss + nchtotal.ncs_neghits;
	s.nchpathcount = nchtotal.ncs_longhits + nchtotal.ncs_longmiss;
	if (state == TIME) {
		s1.nchcount = s.nchcount;
		s1.nchpathcount = s.nchpathcount;
	}

	psiz = 0;
	f2 = 0.0;
	for (lc = 0; lc < CPUSTATES; lc++) {
		uint64_t val = *(uint64_t *)(((uint8_t *)&s.cp_time) +
		    cpuoffsets[lc]);
		f1 = 100.0 * val / total_time;
		f2 += f1;
		l = (int) ((f2 + 1.0) / 2.0) - psiz;
		if (f1 > 99.9)
			f1 = 99.9;	/* no room to display 100.0 */
		putfloat(f1, GRAPHROW, GRAPHCOL + 10 * lc, 4, 1, 0);
		move(GRAPHROW + 2, psiz);
		psiz += l;
		while (l-- > 0)
			addch(cpuchar[lc]);
	}

	put64(ucount(), STATROW, STATCOL, 3, 'D');
	putfloat(avenrun[0], STATROW, STATCOL + 18, 6, 2, 0);
	putfloat(avenrun[1], STATROW, STATCOL + 25, 6, 2, 0);
	putfloat(avenrun[2], STATROW, STATCOL + 32, 6, 2, 0);
	mvaddstr(STATROW, STATCOL + 53, buf);
#define pgtokb(pg) (int64_t)((intmax_t)(pg) * vms.v_page_size / 1024)
#define pgtomb(pg) (int64_t)((intmax_t)(pg) * vms.v_page_size / (1024 * 1024))
#define pgtob(pg)  (int64_t)((intmax_t)(pg) * vms.v_page_size)
	put64(pgtob(total.t_arm), MEMROW + 2, MEMCOL + 4, 6, 0);
	put64(pgtob(total.t_armshr), MEMROW + 2, MEMCOL + 11, 6, 0);
	put64(pgtob(total.t_avm), MEMROW + 2, MEMCOL + 19, 6, 0);
	put64(pgtob(total.t_avmshr), MEMROW + 2, MEMCOL + 26, 6, 0);
	put64(pgtob(total.t_rm), MEMROW + 3, MEMCOL + 4, 6, 0);
	put64(pgtob(total.t_rmshr), MEMROW + 3, MEMCOL + 11, 6, 0);
	put64(pgtob(total.t_vm), MEMROW + 3, MEMCOL + 19, 6, 0);
	put64(pgtob(total.t_vmshr), MEMROW + 3, MEMCOL + 26, 6, 0);
	put64(pgtob(total.t_free), MEMROW + 2, MEMCOL + 34, 6, 0);
	put64(total.t_rq - 1, PROCSROW + 1, PROCSCOL + 0, 3, 'D');
	put64(total.t_pw, PROCSROW + 1, PROCSCOL + 3, 3, 'D');
	put64(total.t_dw, PROCSROW + 1, PROCSCOL + 6, 3, 'D');
	put64(total.t_sl, PROCSROW + 1, PROCSCOL + 9, 3, 'D');
	put64(total.t_sw, PROCSROW + 1, PROCSCOL + 12, 3, 'D');
	if (extended_vm_stats == 0) {
		PUTRATE(Vmm.v_zfod, VMSTATROW + 0, VMSTATCOL, 7);
	}
	PUTRATE(Vmm.v_cow_faults, VMSTATROW + 1, VMSTATCOL, 7);
	put64(pgtob(vms.v_wire_count), VMSTATROW + 2, VMSTATCOL, 7, 0);
	put64(pgtob(vms.v_active_count), VMSTATROW + 3, VMSTATCOL, 7, 0);
	put64(pgtob(vms.v_inactive_count), VMSTATROW + 4, VMSTATCOL, 7, 0);
	put64(pgtob(vms.v_cache_count), VMSTATROW + 5, VMSTATCOL, 7, 0);
	put64(pgtob(vms.v_free_count), VMSTATROW + 6, VMSTATCOL, 7, 0);
	PUTRATE(Vmm.v_dfree, VMSTATROW + 7, VMSTATCOL, 7);
	PUTRATE(Vmm.v_pfree, VMSTATROW + 8, VMSTATCOL, 7);
	PUTRATE(Vmm.v_reactivated, VMSTATROW + 9, VMSTATCOL, 7);
	PUTRATE(Vmm.v_pdwakeups, VMSTATROW + 10, VMSTATCOL, 7);
	PUTRATE(Vmm.v_pdpages, VMSTATROW + 11, VMSTATCOL, 7);
	PUTRATE(Vmm.v_intrans, VMSTATROW + 12, VMSTATCOL, 7);

	if (extended_vm_stats) {
		PUTRATE(Vmm.v_zfod, VMSTATROW + 11, VMSTATCOL - 16, 9);
		PUTRATE(Vmm.v_ozfod, VMSTATROW + 12, VMSTATCOL - 16, 9);
#define nz(x)	((x) ? (x) : 1)
		put64((s.Vmm.v_zfod - s.Vmm.v_ozfod) * 100 / nz(s.Vmm.v_zfod),
		    VMSTATROW + 13, VMSTATCOL - 16, 9, 'D');
#undef nz
		PUTRATE(Vmm.v_tfree, VMSTATROW + 14, VMSTATCOL - 16, 9);
	}

	put64(s.bufspace, VMSTATROW + 13, VMSTATCOL, 7, 0);
	put64(s.dirtybufspace/1024, VMSTATROW + 14, VMSTATCOL, 7, 'k');
	put64(s.desiredvnodes, VMSTATROW + 15, VMSTATCOL, 7, 'D');
	put64(s.numvnodes, VMSTATROW + 16, VMSTATCOL, 7, 'D');
	put64(s.freevnodes, VMSTATROW + 17, VMSTATCOL, 7, 'D');
	PUTRATE(Vmm.v_vnodein, PAGEROW + 2, PAGECOL + 6, 4);
	PUTRATE(Vmm.v_vnodeout, PAGEROW + 2, PAGECOL + 11, 4);
	PUTRATE(Vmm.v_swapin, PAGEROW + 2, PAGECOL + 18, 4);
	PUTRATE(Vmm.v_swapout, PAGEROW + 2, PAGECOL + 23, 4);
	PUTRATE(Vmm.v_vnodepgsin, PAGEROW + 3, PAGECOL + 6, 4);
	PUTRATE(Vmm.v_vnodepgsout, PAGEROW + 3, PAGECOL + 11, 4);
	PUTRATE(Vmm.v_swappgsin, PAGEROW + 3, PAGECOL + 18, 4);
	PUTRATE(Vmm.v_swappgsout, PAGEROW + 3, PAGECOL + 23, 4);
	PUTRATE(Vmm.v_swtch, GENSTATROW + 1, GENSTATCOL + 1, 4);
	PUTRATE(Vmm.v_trap, GENSTATROW + 1, GENSTATCOL + 6, 4);
	PUTRATE(Vmm.v_syscall, GENSTATROW + 1, GENSTATCOL + 11, 4);
	PUTRATE(Vmm.v_intr, GENSTATROW + 1, GENSTATCOL + 16, 4);
	PUTRATE(Vmm.v_soft, GENSTATROW + 1, GENSTATCOL + 21, 4);
	PUTRATE(Vmm.v_vm_faults, GENSTATROW + 1, GENSTATCOL + 26, 4);
	mvprintw(DISKROW, DISKCOL + 5, "                              ");
	for (i = 0, lc = 0; i < num_devices && lc < MAXDRIVES; i++)
		if (dev_select[i].selected) {
			char tmpstr[80];
			sprintf(tmpstr, "%s%d", dev_select[i].device_name,
				dev_select[i].unit_number);
			mvprintw(DISKROW, DISKCOL + 5 + 6 * lc,
				" %5.5s", tmpstr);
			switch(state) {
			case TIME:
				dinfo(i, ++lc, &cur, &last);
				break;
			case RUN:
				dinfo(i, ++lc, &cur, &run);
				break;
			case BOOT:
				dinfo(i, ++lc, &cur, NULL);
				break;
			}
		}
#define nz(x)	((x) ? (x) : 1)
	put64(s.nchpathcount, NAMEIROW + 1, NAMEICOL + 3, 9, 'D');

	put64(nchtotal.ncs_longhits, NAMEIROW + 1, NAMEICOL + 12, 7, 'D');
	putfloat(nchtotal.ncs_longhits * 100.0 / nz(s.nchpathcount),
	    NAMEIROW + 1, NAMEICOL + 19, 4, 0, 0);

	putfloat((double)s.nchcount / nz(s.nchpathcount),
	    NAMEIROW + 1, NAMEICOL + 27, 5, 2, 1);
#undef nz
}
Пример #27
0
static void
sync_chans( main_vars_t *mvars, int ent )
{
	group_conf_t *group;
	channel_conf_t *chan;
	store_t *store;
	string_list_t *mbox, *sbox, **mboxp, **sboxp;
	char *channame;
	int t;

	if (!mvars->cben)
		return;
	switch (ent) {
	case E_OPEN: goto opened;
	case E_SYNC: goto syncone;
	}
	for (;;) {
		mvars->boxlist = 0;
		if (!mvars->all) {
			if (mvars->chanptr)
				channame = mvars->chanptr->string;
			else {
				for (group = groups; group; group = group->next)
					if (!strcmp( group->name, mvars->argv[mvars->oind] )) {
						mvars->chanptr = group->channels;
						channame = mvars->chanptr->string;
						goto gotgrp;
					}
				channame = mvars->argv[mvars->oind];
			  gotgrp: ;
			}
			if ((mvars->boxlist = strchr( channame, ':' )))
				*mvars->boxlist++ = 0;
			for (chan = channels; chan; chan = chan->next)
				if (!strcmp( chan->name, channame ))
					goto gotchan;
			error( "No channel or group named '%s' defined.\n", channame );
			mvars->ret = 1;
			goto gotnone;
		  gotchan:
			mvars->chan = chan;
		}
		merge_actions( mvars->chan, mvars->ops, XOP_HAVE_TYPE, OP_MASK_TYPE, OP_MASK_TYPE );
		merge_actions( mvars->chan, mvars->ops, XOP_HAVE_CREATE, OP_CREATE, 0 );
		merge_actions( mvars->chan, mvars->ops, XOP_HAVE_EXPUNGE, OP_EXPUNGE, 0 );

		mvars->state[M] = mvars->state[S] = ST_FRESH;
		info( "Channel %s\n", mvars->chan->name );
		mvars->boxes[M] = mvars->boxes[S] = mvars->cboxes = 0;
		mvars->skip = mvars->cben = 0;
		for (t = 0; t < 2; t++) {
			mvars->drv[t] = mvars->chan->stores[t]->driver;
			if ((store = mvars->drv[t]->own_store( mvars->chan->stores[t] )))
				store_opened( store, AUX );
		}
		for (t = 0; t < 2 && !mvars->skip; t++)
			if (mvars->state[t] == ST_FRESH) {
				info( "Opening %s %s...\n", str_ms[t], mvars->chan->stores[t]->name );
				mvars->drv[t]->open_store( mvars->chan->stores[t], store_opened, AUX );
			}
		mvars->cben = 1;
	  opened:
		if (mvars->skip)
			goto next;
		if (mvars->state[M] != ST_OPEN || mvars->state[S] != ST_OPEN)
			return;

		if (mvars->boxlist)
			mvars->boxp = mvars->boxlist;
		else if (mvars->chan->patterns) {
			mvars->boxes[M] = filter_boxes( mvars->ctx[M]->boxes, mvars->chan->patterns );
			mvars->boxes[S] = filter_boxes( mvars->ctx[S]->boxes, mvars->chan->patterns );
			for (mboxp = &mvars->boxes[M]; (mbox = *mboxp); ) {
				for (sboxp = &mvars->boxes[S]; (sbox = *sboxp); sboxp = &sbox->next)
					if (!strcmp( sbox->string, mbox->string )) {
						*sboxp = sbox->next;
						free( sbox );
						*mboxp = mbox->next;
						mbox->next = mvars->cboxes;
						mvars->cboxes = mbox;
						goto gotdupe;
					}
				mboxp = &mbox->next;
			  gotdupe: ;
			}
		}

		if (mvars->list && mvars->multiple)
			printf( "%s:\n", mvars->chan->name );
	  syncml:
		mvars->done = mvars->cben = 0;
	  syncmlx:
		if (mvars->boxlist) {
			if ((mvars->names[S] = strsep( &mvars->boxp, ",\n" ))) {
				if (!*mvars->names[S])
					mvars->names[S] = 0;
				if (!mvars->list) {
					mvars->names[M] = mvars->names[S];
					sync_boxes( mvars->ctx, mvars->names, mvars->chan, done_sync, mvars );
					goto syncw;
				}
				puts( nz( mvars->names[S], "INBOX" ) );
				goto syncmlx;
			}
		} else if (mvars->chan->patterns) {
			if ((mbox = mvars->cboxes)) {
				mvars->cboxes = mbox->next;
				if (!mvars->list) {
					mvars->names[M] = mvars->names[S] = mbox->string;
					sync_boxes( mvars->ctx, mvars->names, mvars->chan, done_sync_dyn, mvars );
					goto syncw;
				}
				puts( mbox->string );
				free( mbox );
				goto syncmlx;
			}
			for (t = 0; t < 2; t++)
				if ((mbox = mvars->boxes[t])) {
					mvars->boxes[t] = mbox->next;
					if ((mvars->chan->ops[1-t] & OP_MASK_TYPE) && (mvars->chan->ops[1-t] & OP_CREATE)) {
						if (!mvars->list) {
							mvars->names[M] = mvars->names[S] = mbox->string;
							sync_boxes( mvars->ctx, mvars->names, mvars->chan, done_sync_dyn, mvars );
							goto syncw;
						}
						puts( mbox->string );
					}
					free( mbox );
					goto syncmlx;
				}
		} else {
			if (!mvars->list) {
				sync_boxes( mvars->ctx, mvars->chan->boxes, mvars->chan, done_sync, mvars );
				mvars->skip = 1;
			  syncw:
				mvars->cben = 1;
				if (!mvars->done)
					return;
			  syncone:
				if (!mvars->skip)
					goto syncml;
			} else
				printf( "%s <=> %s\n", nz( mvars->chan->boxes[M], "INBOX" ), nz( mvars->chan->boxes[S], "INBOX" ) );
		}

	  next:
		for (t = 0; t < 2; t++)
			if (mvars->state[t] == ST_OPEN) {
				mvars->drv[t]->disown_store( mvars->ctx[t] );
				mvars->state[t] = ST_CLOSED;
			}
		if (mvars->state[M] != ST_CLOSED || mvars->state[S] != ST_CLOSED) {
			mvars->skip = mvars->cben = 1;
			return;
		}
		free_string_list( mvars->cboxes );
		free_string_list( mvars->boxes[M] );
		free_string_list( mvars->boxes[S] );
		if (mvars->all) {
			if (!(mvars->chan = mvars->chan->next))
				break;
		} else {
			if (mvars->chanptr && (mvars->chanptr = mvars->chanptr->next))
				continue;
		  gotnone:
			if (!mvars->argv[++mvars->oind])
				break;
		}
	}
	for (t = 0; t < N_DRIVERS; t++)
		drivers[t]->cleanup();
}
Пример #28
0
void
showvmstat(void)
{
	int inttotal;
	int i, l, r, c;
	static int failcnt = 0;
	static int relabel = 0;
	static int last_disks = 0;
	static char pigs[] = "pigs";

	if (relabel) {
		labelvmstat();
		relabel = 0;
	}

	cpuswap();
	if (display_mode == TIME) {
		drvswap();
		etime = cur.cp_etime;
		/* < 5 ticks - ignore this trash */
		if ((etime * hertz) < 1.0) {
			if (failcnt++ <= MAXFAIL)
				return;
			clear();
			mvprintw(2, 10, "The alternate system clock has died!");
			mvprintw(3, 10, "Reverting to ``pigs'' display.");
			move(CMDLINE, 0);
			refresh();
			failcnt = 0;
			sleep(5);
			command(pigs);
			return;
		}
	} else
		etime = 1.0;

	show_vmstat_top(&s.Total, &s.uvmexp, &s1.uvmexp);

	/* Memory totals */
#define pgtokb(pg)	((pg) * (s.uvmexp.pagesize / 1024))
	putint(pgtokb(s.uvmexp.active), MEMROW + 2, MEMCOL + 6, 9);
	putint(pgtokb(s.uvmexp.active + s.uvmexp.swpginuse),	/* XXX */
	    MEMROW + 2, MEMCOL + 16, 9);
	putint(pgtokb(s.uvmexp.npages - s.uvmexp.free),
	    MEMROW + 3, MEMCOL + 6, 9);
	putint(pgtokb(s.uvmexp.npages - s.uvmexp.free + s.uvmexp.swpginuse),
	    MEMROW + 3, MEMCOL + 16, 9);
	putint(pgtokb(s.uvmexp.free), MEMROW + 2, MEMCOL + 26, 9);
	putint(pgtokb(s.uvmexp.free + s.uvmexp.swpages - s.uvmexp.swpginuse),
	    MEMROW + 3, MEMCOL + 26, 9);
#undef pgtokb

	/* Namei cache */
	Z(s, s1, ncs_goodhits); Z(s, s1, ncs_badhits); Z(s, s1, ncs_miss);
	Z(s, s1, ncs_long); Z(s, s1, ncs_pass2); Z(s, s1, ncs_2passes);
	s.nchcount = s.nchstats.ncs_goodhits + s.nchstats.ncs_badhits +
	    s.nchstats.ncs_miss + s.nchstats.ncs_long +
	    s.nchstats.ncs_pass2 + s.nchstats.ncs_2passes;
	if (display_mode == TIME)
		s1.nchcount = s.nchcount;

	putint(s.nchcount, NAMEIROW + 2, NAMEICOL, 9);
	putint(s.nchstats.ncs_goodhits, NAMEIROW + 2, NAMEICOL + 9, 9);
#define nz(x)	((x) ? (x) : 1)
	putfloat(s.nchstats.ncs_goodhits * 100.0 / nz(s.nchcount),
	   NAMEIROW + 2, NAMEICOL + 19, 4, 0, 1);
	putint(s.nchstats.ncs_pass2, NAMEIROW + 2, NAMEICOL + 23, 9);
	putfloat(s.nchstats.ncs_pass2 * 100.0 / nz(s.nchcount),
	   NAMEIROW + 2, NAMEICOL + 34, 4, 0, 1);
#undef nz

	/* Disks */
	for (l = 0, i = 0, r = DISKROW, c = DISKCOL;
	     i < (int)ndrive; i++) {
		if (!drv_select[i])
			continue;

		if (disk_horiz)
			c += DISKCOLWIDTH;
		else
			r++;
		if (c + DISKCOLWIDTH > DISKCOLEND) {
			if (disk_horiz && LINES - 1 - DISKROW >
			    (DISKCOLEND - DISKCOL) / DISKCOLWIDTH) {
				disk_horiz = 0;
				relabel = 1;
			}
			break;
		}
		if (r >= LINES - 1) {
			if (!disk_horiz && LINES - 1 - DISKROW <
			    (DISKCOLEND - DISKCOL) / DISKCOLWIDTH) {
				disk_horiz = 1;
				relabel = 1;
			}
			break;
		}
		l++;

		dinfo(i, r, c);
	}
	/* blank out if we lost any disks */
	for (i = l; i < last_disks; i++) {
		int j;
		if (disk_horiz)
			c += DISKCOLWIDTH;
		else
			r++;
		for (j = 0; j < 5; j++) {
			if (disk_horiz)
				mvprintw(r+j, c, "%*s", DISKCOLWIDTH, "");
			else
				mvprintw(r, c+j*DISKCOLWIDTH, "%*s", DISKCOLWIDTH, "");
		}
	}
	last_disks = l;

	/* Interrupts */
	failcnt = 0;
	inttotal = 0;
	for (i = 0; i < nintr; i++) {
		if (s.intrcnt[i] == 0)
			continue;
		if (intrloc[i] == 0) {
			if (nextintsrow == LINES)
				continue;
			intrloc[i] = nextintsrow++;
			mvprintw(intrloc[i], INTSCOL + 9, "%-.*s",
				INTSCOLEND - (INTSCOL + 9), intrname[i]);
		}
		X(s, s1, intrcnt);
		l = (int)((float)s.intrcnt[i]/etime + 0.5);
		inttotal += l;
		putint(l, intrloc[i], INTSCOL, 8);
	}

	for (i = 0; i < nevcnt; i++) {
		if (s.evcnt[i] == 0)
			continue;
		if (ie_head[i].ie_loc == 0) {
			if (nextintsrow == LINES)
				continue;
			ie_head[i].ie_loc = nextintsrow++;
			print_ie_title(i);
		}
		X(s, s1, evcnt);
		l = (int)((float)s.evcnt[i]/etime + 0.5);
		inttotal += l;
		putint(l, ie_head[i].ie_loc, INTSCOL, 8);
	}
	putint(inttotal, INTSROW, INTSCOL, 8);

	PUTRATE(s, s1, uvmexp.forks, VMSTATROW + 0, VMSTATCOL + 3, 6);
	PUTRATE(s, s1, uvmexp.forks_ppwait, VMSTATROW + 1, VMSTATCOL + 3, 6);
	PUTRATE(s, s1, uvmexp.forks_sharevm, VMSTATROW + 2, VMSTATCOL + 3, 6);
	PUTRATE(s, s1, uvmexp.fltpgwait, VMSTATROW + 3, VMSTATCOL + 4, 5);
	PUTRATE(s, s1, uvmexp.fltrelck, VMSTATROW + 4, VMSTATCOL + 3, 6);
	PUTRATE(s, s1, uvmexp.fltrelckok, VMSTATROW + 5, VMSTATCOL + 3, 6);
	PUTRATE(s, s1, uvmexp.fltnoram, VMSTATROW + 6, VMSTATCOL + 3, 6);
	PUTRATE(s, s1, uvmexp.fltamcopy, VMSTATROW + 7, VMSTATCOL + 3, 6);
	PUTRATE(s, s1, uvmexp.flt_prcopy, VMSTATROW + 8, VMSTATCOL + 3, 6);
	PUTRATE(s, s1, uvmexp.flt_przero, VMSTATROW + 9, VMSTATCOL + 3, 6);
	PUTRATE(s, s1, uvmexp.flt_acow, VMSTATROW + 10, VMSTATCOL, 9);
	putint(s.uvmexp.freemin, VMSTATROW + 11, VMSTATCOL, 9);
	putint(s.uvmexp.freetarg, VMSTATROW + 12, VMSTATCOL, 9);
	putint(s.uvmexp.inactarg, VMSTATROW + 13, VMSTATCOL, 9);
	putint(s.uvmexp.wired, VMSTATROW + 14, VMSTATCOL, 9);
	PUTRATE(s, s1, uvmexp.pdfreed, VMSTATROW + 15, VMSTATCOL, 9);
	if (LINES - 1 > VMSTATROW + 16)
		PUTRATE(s, s1, uvmexp.pdscans, VMSTATROW + 16, VMSTATCOL, 9);

}
Пример #29
0
void graph(FILE * fp)
{
   static char buf[BUFLNG], arg[BUFLNG / 2], xtype[16], ytype[16];
   static double xa, ya, xap, yap, xmin, xmax, ymin, ymax;
   static double xs = -NSCALE, ys = -NSCALE;
   int n, c;
   char *s, *p;
   double x, y, lpt, th, dt, lscale, rad;
   int is_grid, old_lbl = 0;
   char xory;

   h *= fct;
   w *= fct;

   for (n = 0; (s = fgets(buf, BUFLNG, fp));) {
      s = getarg(s, arg);
      if (s == NULL || *arg == '#');    /* comment line */
      else if ((!is_t && strcmp(arg, "x") == 0)
               || (is_t && strcmp(arg, "y") == 0)) {
         s = gettyp(s, xtype);
         if (sscanf(s, "%lf %lf %lf", &xmin, &xmax, &xa) != 3)
            xa = xmin;
         if (strncmp(xtype, "log", 3) == 0) {
            xmin = log10(xmin);
            xmax = log10(xmax);
            xa = log10(xa);
            is_xlog = (xtype[3] == '*') ? -1 : 1;
         }
         xfct = xl / (xmax - xmin);
         xap = (xa - xmin) * xfct;
         x00 = -xmin * xfct;
      } else if ((!is_t && strcmp(arg, "y") == 0)
                 || (is_t && strcmp(arg, "x") == 0)) {
         s = gettyp(s, ytype);
         if (sscanf(s, "%lf %lf %lf", &ymin, &ymax, &ya) != 3)
            ya = ymin;
         if (strncmp(ytype, "log", 3) == 0) {
            ymin = log10(ymin);
            ymax = log10(ymax);
            ya = log10(ya);
            is_ylog = (ytype[3] == '*') ? -1 : 1;
         }
         yfct = (yl) ? yl / (ymax - ymin) : 0;
         yap = (ya - ymin) * yfct;
         y00 = -ymin * yfct;
      } else if ((!is_t && strncmp(arg, "xscale", 6) == 0)
                 || (is_t && strncmp(arg, "yscale", 6) == 0)) {
         is_grid = *(arg + 6);
         if (type < 0 || (ya != ymin && ya != ymax)) {
            plot(0.0, yap, 3);
            plot(xl, yap, 2);
         }
         ys = yap - h - MSCALE;
         while ((s = getarg(s, p = arg)) != NULL) {
            if (*p != '"') {
               x = atof((is_number(*p)) ? p : p + 1);
               if (strncmp(xtype, "mel", 3) == 0)
                  x = argapf(x / nz(xmax, xmin),
                             atof(xtype + 3)) * nz(xmax, xmin);
               else if (is_xlog)
                  x = log10(x);
               x = (x - xmin) * xfct;
               lscale = (*p == 's') ? LSCALE / 2 : LSCALE;
               if (*p != '\\' && *p != '@') {
                  plot(x, yap, 3);
                  plot(x, yap + lscale, 2);
                  if (type > 0 && !is_grid && yap == 0) {
                     plot(x, yl, 3);
                     plot(x, yl - lscale, 2);
                  }
               } else if (*p == '\\')
                  ++p;
            }
            if (is_number(*p) || *p++ == '"')
               _symbol(x - sleng(p, h, w) / 2, ys - ysadj(), p, h, w, 0.0);
         }
      } else if ((!is_t && strncmp(arg, "yscale", 6) == 0)
                 || (is_t && strncmp(arg, "xscale", 6) == 0)) {
         is_grid = *(arg + 6);
         if (type < 0 || (xa != xmin && xa != xmax)) {
            plot(xap, 0.0, 3);
            plot(xap, yl, 2);
         }
         while ((s = getarg(s, p = arg)) != NULL) {
            if (*p != '"') {
               y = atof((is_number(*p)) ? p : p + 1);
               if (strncmp(ytype, "mel", 3) == 0)
                  y = argapf(y / nz(ymax, ymin),
                             atof(ytype + 3)) * nz(ymax, ymin);
               else if (is_ylog)
                  y = log10(y);
               y = (y - ymin) * yfct;
               lscale = (*p == 's') ? LSCALE / 2 : LSCALE;
               if (*p != '\\' && *p != '@') {
                  plot(xap, y, 3);
                  plot(xap + lscale, y, 2);
                  if (type > 0 && !is_grid && xap == 0) {
                     plot(xl, y, 3);
                     plot(xl - lscale, y, 2);
                  }
               } else if (*p == '\\')
                  ++p;
            }
            if (is_number(*p) || *p++ == '"') {
               x = xap - sleng(p, h, w) - MSCALE;
               if (x < xs)
                  xs = x;
               _symbol(x, y - h * 0.5, p, h, w, 0.0);
            }
         }
      } else if (strcmp(arg + 1, "grid") == 0) {
         draw_fig0(xbuf, ybuf, n, wf, hf, fct);
         if ((!is_t && (*arg == 'x')) || (is_t && (*arg == 'y'))) {
            ybuf[0] = 0;
            ybuf[1] = yl;
            while ((s = getarg(s, arg)) != NULL) {
               x = atof(arg);
               if (is_xlog)
                  x = log10(x);
               xbuf[0] = xbuf[1]
                   = (x - xmin) * xfct;
               draw_fig0(xbuf, ybuf, 2, wf, hf, fct);
            }
         } else {
            xbuf[0] = 0;
            xbuf[1] = xl;
            while ((s = getarg(s, arg)) != NULL) {
               y = atof(arg);
               if (is_ylog)
                  y = log10(y);
               ybuf[0] = ybuf[1]
                   = (y - ymin) * yfct;
               draw_fig0(xbuf, ybuf, 2, wf, hf, fct);
            }
         }
         n = 0;
      } else if (strcmp(arg + 1, "circle") == 0) {
         xory = *arg;
         s = getarg(s, arg);
         x = xt(atof(arg));
         s = getarg(s, arg);
         y = yt(atof(arg));
         swap(&x, &y);
         x = xfct * x + x00;
         y = yfct * y + y00;
         while ((s = getarg(s, arg)) != NULL) {
            if ((!is_t && xory == 'x') || (is_t && xory == 'y'))
               rad = xt(atof(arg)) * xfct;
            else
               rad = yt(atof(arg)) * yfct;
            pntstyl(ptyp);
            circle(x, y, rad, rad, 0., 360.);
         }
      } else if (strcmp(arg, "circle") == 0) {
         s = getarg(s, arg);
         x = xt(atof(arg));
         s = getarg(s, arg);
         y = yt(atof(arg));
         swap(&x, &y);
         x = xfct * x + x00;
         y = yfct * y + y00;
         while ((s = getarg(s, arg)) != NULL) {
            rad = atof(arg);
            pntstyl(ptyp);
            circle(x, y, rad, rad, 0., 360.);
         }
      } else if (strcmp(arg + 1, "name") == 0) {
         s = getname(s, p = arg + 1);
         if ((!is_t && *arg == 'x') || (is_t && *arg == 'y'))
            _symbol((xl - sleng(s, h, w)) / 2,
                    (*p) ? -atof(p) - h : ys - h - NSCALE, s, h, w, 0.0);
         else
            _symbol((*p) ? -atof(p) : xs - MSCALE,
                    (yl - sleng(s, h, w)) / 2, s, h, w, 90.0);
      } else if (strncmp(arg, "title", 5) == 0 || strncmp(arg, "print", 5) == 0) {
         sscanf(s, "%lf %lf", &x, &y);
         swap(&x, &y);
         if (*arg == 'p') {
            x = xfct * xt(x) + x00;
            y = yfct * yt(y) + y00;
         }
         s = gettxt_fig(s);
         th = getarg(s + strlen(s) + 1, arg) ? atof(arg) : 0;
         if (*(arg + 5)) {
            x -= rx(LADJ * h / 2, h / 2, th);
            y -= ry(LADJ * h / 2, h / 2, th);
         }
         _symbol(x, y, s, h, w, th);
      } else if (strcmp(arg, "eod") == 0 || strcmp(arg, "EOD") == 0) {
         draw_fig0(xbuf, ybuf, n, wf, hf, fct);
         n = 0;
      } else if (strcmp(arg, "pen") == 0) {
         n = flush(xbuf, ybuf, n, wf, hf, fct);
         pen(atoi(s));
      } else if (strcmp(arg, "join") == 0) {
         n = flush(xbuf, ybuf, n, wf, hf, fct);
         join(atoi(s));
      } else if (strcmp(arg, "csize") == 0) {
         if (sscanf(s, "%lf %lf", &h, &w) != 2)
            w = h;
      } else if (strcmp(arg, "hight") == 0) {
         if (sscanf(s, "%lf %lf", &mh, &mw) != 2)
            mw = mh;
      } else if (strcmp(arg, "line") == 0) {
         n = flush(xbuf, ybuf, n, wf, hf, fct);
         if (sscanf(s, "%d %lf", &ltype, &lpt) != 2) {
            if (ltype > 0)
               lpt = lpit[ltype - 1];
         }
         if (--ltype >= 0)
            mode(lmod[ltype], lpt);
      } else if (strcmp(arg, "italic") == 0)
         italic(atof(s));
      else if (strcmp(arg, "mark") == 0) {
         while (*s == ' ' || *s == '\t')
            ++s;
         if (*s == '\\' && *(s + 1) == '0')
            *label = '\0';
         else
            strcpy(label, s);
      } else if (strcmp(arg, "paint") == 0) {
         sscanf(s, "%d %lf %lf", &ptyp, &dhat, &that);
      } else if (strcmp(arg, "clip") == 0) {
         draw_fig0(xbuf, ybuf, n, wf, hf, fct);
         for (n = 0; (s = getarg(s, arg)) != NULL; ++n) {
            x = xt(atof(arg));
            if ((s = getarg(s, arg)) == NULL)
               break;
            y = yt(atof(arg));
            swap(&x, &y);
            xbuf[n] = xfct * x + x00;
            ybuf[n] = yfct * y + y00;
         }
         if (n == 0) {
            xclip0 = yclip0 = 0;
            xclip1 = xl;
            yclip1 = yl;
            swap(&xclip1, &yclip1);
         } else if (n == 2) {
            xclip0 = xbuf[0];
            yclip0 = ybuf[0];
            xclip1 = xbuf[1];
            yclip1 = ybuf[1];
         }
         n = 0;
      } else if (strcmp(arg, "box") == 0) {
         draw_fig0(xbuf, ybuf, n, wf, hf, fct);
         for (n = 0; (s = getarg(s, arg)) != NULL; ++n) {
            x = xt(atof(arg));
            if ((s = getarg(s, arg)) == NULL)
               break;
            y = yt(atof(arg));
            swap(&x, &y);
            xbuf[n] = xfct * x + x00;
            ybuf[n] = yfct * y + y00;
         }
         if (n == 2) {
            xbuf[2] = xbuf[1];
            ybuf[3] = ybuf[2] = ybuf[1];
            ybuf[1] = ybuf[0];
            xbuf[3] = xbuf[0];
            n = 4;
         }
         polyg(xbuf, ybuf, n, wf, hf, fct);
         n = 0;
      } else {
         x = xt(atof(arg));
         s = getarg(s, arg);
         y = yt(atof(arg));
         swap(&x, &y);
         xbuf[n] = x = xfct * x + x00;
         ybuf[n] = y = yfct * y + y00;
         if (is_in(x, y) && ((s = getarg(s, arg))
                             || *label || old_lbl > 0)) {
            c = 0;
            if (s || *label) {
               if (s == NULL)
                  s = getarg(label, arg);
               if (*arg == '\\' && (abs(c = atoi(arg + 1))) < 16)
                  mark(abs(c), &x, &y, 1, mh, 1);
               else if (abs(c) == 16) {
                  pntstyl(ptyp);
                  circle(x, y, mh / 2, mh / 2, 0., 360.);
               } else {
                  if (c) {
                     *arg = c;
                     *(arg + 1) = '\0';
                  }
                  _symbol(x - LADJ * h / 2, y - w / 2, arg, h, w, atof(s));
               }
            }
            if (c > 0)
               n = flush(xbuf, ybuf, n, wf, hf, fct);
            if ((c > 0 || old_lbl > 0) && n) {
               dt = atan2(y - ybuf[0], x - xbuf[0]);
               if (old_lbl > 0) {
                  xbuf[0] += MADJ * mh * cos(dt);
                  ybuf[0] += MADJ * mh * sin(dt);
               }
               if (c > 0) {
                  xbuf[1] -= MADJ * mh * cos(dt);
                  ybuf[1] -= MADJ * mh * sin(dt);
               }
               draw_fig0(xbuf, ybuf, 2, wf, hf, fct);
               xbuf[0] = x;
               ybuf[0] = y;
               n = 0;
            }
            old_lbl = c;
         }
         if (++n >= BUFLNG)
            n = flush(xbuf, ybuf, n, wf, hf, fct);
      }
   }
   draw_fig0(xbuf, ybuf, n, wf, hf, fct);
}
typename AbstractLinAlgPack::SparseVectorUtilityPack::SpVecIndexLookup<T_Element>::poss_type
AbstractLinAlgPack::SparseVectorUtilityPack::SpVecIndexLookup<T_Element>::find_poss(
  index_type index, UpperLower uplow) const
{
  // First look at the cache.  If it matches then use that information, otherwise
  // perform a binary search to find the possition then cache it for latter.

  if(index_cached_) {
    if(index == index_cached_)	// Same as cache so use cache
      return poss_type(adjust_cached_poss(uplow),ele_rel_cached_);
    if(index == index_cached_ + 1 && ele_rel_cached_ == AFTER_ELE
      && uplow == LOWER_ELE)
    {
      // Since poss_cached_ = ( max p s.t. ele_[p].index() < index_cached_ )
      // there are three possibilities here:
      // Either:

      // a) poss_cashed_ == nz_ - 1
      if( poss_cached_ == nz_ - 1 )
        return poss_type( poss_cached_ , AFTER_ELE );	

      // b) ele_[poss_cashed_+1].index() == index
      if( ele_[poss_cached_+1].index() == index )
        return poss_type( poss_cached_+1 , EQUAL_TO_ELE );

      // c) ele_[poss_cashed_+1].index() > index.
      if( ele_[poss_cached_+1].index() > index )
        return poss_type( poss_cached_+1 , BEFORE_ELE );
    }
    if(index == index_cached_ - 1 && ele_rel_cached_ == BEFORE_ELE
      && uplow == UPPER_ELE)
    {
      // Since poss_cached_ = ( max p s.t. ele_[p].index() < index_cached_ )
      // there are three possibilities here:
      // Either:

      // a) poss_cashed_ == 0
      if( poss_cached_ == 0 )
        return poss_type( poss_cached_ , BEFORE_ELE );	
      
      // b) ele_[poss_cashed_-1].index() == index
      if( ele_[poss_cached_+1].index() == index )
        return poss_type( poss_cached_-1 , EQUAL_TO_ELE );

      // c) ele_[poss_cashed_-1].index() < index.
      return poss_type( poss_cached_ - 1, AFTER_ELE);	
    }
  }

  // Perform binary search for the element
  poss_type poss = binary_ele_search(index,uplow);

  // Cache the result if needed.  Don't cache an endpoint
  if(poss.poss != 0 && poss.poss != nz() - 1) {
    index_cached_ = index;
    poss_cached_ = poss.poss;
    ele_rel_cached_ = poss.rel;
  }

  return poss;
}