Exemplo n.º 1
0
bool
solvetest(const LinAlg::Matrix<real_type,n,n>& m,
          const LinAlg::Vector<real_type,n>& v)
{
  // compute a decomposition
  LinAlg::MatrixFactors<real_type,n,n,LinAlg::LUTag> decomp(m);

  // crude condition estimation
  real_type nrm = 0;
  real_type rnrm = 0;
  for (unsigned i = 0; i < rows(v); ++i) {
    nrm = max(nrm, norm1(m*Vector::unit(i, rows(v))));
    rnrm = max(rnrm, norm1(decomp.solve(Vector::unit(i, rows(v)))));
  }
  real_type cond = nrm*rnrm;

  // determine allowed tolerance from the condition number
  real_type rtol = sqrt(rows(v))*cond*10*Limits<real_type>::epsilon();
  real_type atol = sqrt(rows(v))*1e-5*Limits<real_type>::epsilon();

  // Check ...
  if (!equal(v, decomp.solve(m*v), rtol, atol)) {
    std::cerr << "Matrix solve test failed\n";
    std::cerr << "   condition number:       " << cond << "\n";
    std::cerr << "   norm of the difference: "
              << norm(v - decomp.solve(m*v)) << std::endl;
    return false;
  }

  return true;
}
Exemplo n.º 2
0
BOOST_FIXTURE_TEST_CASE( math2d__norms, Some2dPoints )
{
    BOOMST_CHECK_APPROX_EQUAL( 4_r, norm1(p2) );
    BOOMST_CHECK_APPROX_EQUAL( 10_r, norm2sq(p2) );
    BOOMST_CHECK_APPROX_EQUAL( 2_r, norm_max(p3) );
    BOOMST_CHECK_APPROX_EQUAL( 0_r, norm_max(zero2) );
}
 template <typename T> inline 
 typename realType<T>::Type norm1(const hoNDArray<T>& x)
 {
     typename realType<T>::Type r;
     norm1(x, r);
     return r;
 }
Exemplo n.º 4
0
static void task_norm1_work( void * arg , TPI_ThreadPool pool )
{
    int p_size , p_rank ;

    if ( ! TPI_Rank( pool , & p_rank , & p_size ) ) {

        struct TaskX * const t  = (struct TaskX *) arg ;

        const unsigned p_next = p_rank + 1 ;
        const unsigned n = t->number ;
        const double * const xb = t->x_beg + ( n * p_rank ) / p_size ;
        const double * const xe = t->x_beg + ( n * p_next ) / p_size ;
        double * const v  = t->x_sum ;

        double partial[2] = { 0 , 0 };

        norm1( partial , xb , xe );

        TPI_Lock( pool , 0 );

        SUM_ADD( v , partial[0] );
        SUM_ADD( v , partial[1] );

        TPI_Unlock( pool , 0 );
    }
}
Exemplo n.º 5
0
double dynamics_mul::get_curvature(dsc_obj *obj, HMesh::Walker hew0){
    // Find next edge on the boundary
    auto hew1 = hew0.next().opp();
    while (1) {
        if (s_dsc->is_interface(hew1.halfedge())) {
            hew1 = hew1.opp();
            break;
        }
        
        hew1 = hew1.next().opp();
    }
    
    Vec2 p0 = obj->get_pos(hew0.vertex()) - obj->get_pos(hew0.opp().vertex());
    Vec2 p1 = obj->get_pos(hew1.vertex()) - obj->get_pos(hew1.opp().vertex());
    
    Vec2 norm0(p0[1], -p0[0]); norm0.normalize();
    Vec2 norm1(p1[1], -p1[0]); norm1.normalize();
    Vec2 norm = norm0 + norm1; norm.normalize();
    
    
    double l0 = p0.length();
    double l1 = p1.length();
    double angle = std::atan2(CGLA::cross(p0, p1), DSC2D::Util::dot(p0, p1));
    double curvature = angle / (l0/2.0 + l1/2.0);
    
    return curvature;
}
Exemplo n.º 6
0
static void hsv_transform(hsv_t* hsv,hsvtrans_t t)
{
  switch (t.channel)
    {
    case hue:
      double_transform(&(hsv->hue),t);
      hsv->hue = norm360(hsv->hue);
      break;
    case saturation:
      double_transform(&(hsv->sat),t);
      hsv->sat = norm1(hsv->sat);
      break;
    case value:
      double_transform(&(hsv->val),t);
      hsv->val = norm1(hsv->val);
      break;
    }
}
Exemplo n.º 7
0
void
Math_norm1(void *fp)
{
	F_Math_norm1 *f;

	f = fp;

	*f->ret = norm1(f->x->len, (double*)(f->x->data));
}
Exemplo n.º 8
0
void Sphere::draw() {
    glBegin(GL_TRIANGLES);

    for (float y = 0; y < m_segmentsY; ++y) {
        float lowerY = 0.5 - y / m_segmentsY;
        float upperY = 0.5 - (y+1.0) / m_segmentsY;
        float lowerR = transverseSliceRadiusSphere(0.5,lowerY);
        float upperR = transverseSliceRadiusSphere(0.5,upperY);
        for (int i = 0; i < m_segmentsX; ++i) {

            float lowerXL = ithSliceXComponent(lowerR,i,m_segmentsX);
            float upperXL = ithSliceXComponent(lowerR,i+1,m_segmentsX);
            float lowerZL = ithSliceZComponent(lowerR,i,m_segmentsX);
            float upperZL = ithSliceZComponent(lowerR,i+1,m_segmentsX);

            float lowerXU = ithSliceXComponent(upperR,i,m_segmentsX);
            float upperXU = ithSliceXComponent(upperR,i+1,m_segmentsX);
            float lowerZU = ithSliceZComponent(upperR,i,m_segmentsX);
            float upperZU = ithSliceZComponent(upperR,i+1,m_segmentsX);

            Vector norm1(lowerXL,lowerY,lowerZL);
            norm1.normalize();
            glNormal3f(norm1[0],norm1[1],norm1[2]);
            glVertex3f(lowerXL,lowerY,lowerZL);

            Vector norm2(upperXL,lowerY,upperZL);
            norm2.normalize();
            glNormal3f(norm2[0],norm2[1],norm2[2]);
            glVertex3f(upperXL,lowerY,upperZL);

            Vector norm3(lowerXU,upperY,lowerZU);
            norm3.normalize();
            glNormal3f(norm3[0],norm3[1],norm3[2]);
            glVertex3f(lowerXU,upperY,lowerZU);

            Vector norm4(lowerXU,upperY,lowerZU);
            norm4.normalize();
            glNormal3f(norm4[0],norm4[1],norm4[2]);
            glVertex3f(lowerXU,upperY,lowerZU);


            Vector norm5(upperXL,lowerY,upperZL);
            norm5.normalize();
            glNormal3f(norm5[0],norm5[1],norm5[2]);
            glVertex3f(upperXL,lowerY,upperZL);

            Vector norm6(upperXU,upperY,upperZU);
            norm6.normalize();
            glNormal3f(norm6[0],norm6[1],norm6[2]);
            glVertex3f(upperXU,upperY,upperZU);
        }
    }   
    glEnd();
}
    template<class T> typename realType<T>::Type nrm1( hoNDArray<T> *x )
    {
        if( x == 0x0 )
            throw std::runtime_error("Gadgetron::nrm2(): Invalid input array");

        /*typedef typename realType<T>::Type realT;
        arma::Col<typename stdType<T>::Type> xM = as_arma_col(x);
        return realT(arma::norm(xM,1));*/

        return norm1(*x);
    }
Exemplo n.º 10
0
void				tracer_bresenham(t_clist *param, t_clist *a, t_clist *b)
{
	int				dx;
	int				dy;

	stock_param(param, a, b);
	CONTENT(9) = set_color(a, b);
	norm1(param, &dx, &dy);
	if (dx > dy)
		norm2(param, dx, dy);
	else
		norm3(param, dx, dy);
}
Exemplo n.º 11
0
	void parabola(double a, const point2d &begin, const point2d &end){
		glVertex2d(begin[0], begin[1]);

		point2d delta = end-begin;
		if(norm1(delta) <= 1.0/pointsize) return;

		point2d midpoint(2);
		midpoint[0] = begin[0]+delta[0]/2;
		midpoint[1] = a*square(midpoint[0]);

		parabola(a, begin, midpoint);
		parabola(a, midpoint, end);
	}
Exemplo n.º 12
0
void OVariousObjects::DrawTriangle(OVector3 v0, OVector3 v1, OVector3 v2)
{
	OVector3 norm = (v2 - v0) * (v1 - v0);

	OVector3 norm1(norm.X(), 0.7f * norm.Y(), 0.5f * norm.Z());
	norm1 = norm1 * (norm1.FastInvertNorm());

	OVector3 norm2(norm.X(), 0.5f * norm.Y(), 0.7f * norm.Z());
	norm2 = norm2 * (norm2.FastInvertNorm());

	GLfloat points[9] = {
		v0.X(), v0.Y(), v0.Z(),
		v1.X(), v1.Y(), v1.Z(),
		v2.X(), v2.Y(), v2.Z()
	};

	GLfloat normals[9] = {
		norm.X(), norm.Y(), norm.Z(),
		norm1.X(), norm1.Y(), norm1.Z(),
		norm2.X(), norm2.Y(), norm2.Z()
	};

	GLfloat colours[12] = {
		0.1f, 0.3f, 0.5f, 0.8f,
		0.1f, 0.5f, 0.7f, 0.8f,
		0.3f, 0.5f, 0.9f, 0.8f
	};

	//glPolygonMode(GL_FRONT_AND_BACK, GL_LINES);
	//glColor4f(0.1f, 0.1f, 0.7f, 0.7f);
	
	glEnable(GL_COLOR_MATERIAL);

	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_NORMAL_ARRAY);
	glEnableClientState(GL_COLOR_ARRAY);
	
	glVertexPointer(3, GL_FLOAT, 0, points);
	glNormalPointer(GL_FLOAT, 0, normals);
	glColorPointer(4, GL_FLOAT, 0, colours);
	glDrawArrays(GL_TRIANGLES, 0, 3);

	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_NORMAL_ARRAY);
	glDisableClientState(GL_COLOR_ARRAY);
}
Exemplo n.º 13
0
void Triangle::build() 
{

  //Dessin 2D
  //glm::vec3 pos0(-1.0f, -1.0f, 0.0f);
  glm::vec3 pos0(-1.f, -1.f, 0.0f);
  glm::vec3 norm0(0.f, 0.f, 1.0f);
  glm::vec2 uv0(0.f, 0.f);

  //glm::vec3 pos1(1.0f, -1.0f, 0.0f);
  glm::vec3 pos1(3.f, -1.f, 0.0f);
  glm::vec3 norm1(0.f, 0.f, 1.0f);
  glm::vec2 uv1(2.f, 0.f);

	//glm::vec3 pos2(0.f, 0.5f, 0.0f);
	glm::vec3 pos2(-1.f, 3.0f, 0.0f);
  glm::vec3 norm2(0.f, 0.f, 1.0f);
  glm::vec2 uv2(0.f, 2.f);

  /*
    Pour un triangle faisant tout l'écran

    -1.0  -1.0  0.000000
    1.0  -1.0  0.000000
    0.0  0.5  0.000000
  */

  _vertices[0].position = pos0;
  _vertices[0].normal = norm0;
  _vertices[0].uv = uv0;


  _vertices[1].position = pos1;
  _vertices[1].normal = norm1;
  _vertices[1].uv = uv1;

  _vertices[2].position = pos2;
  _vertices[2].normal = norm2;
  _vertices[2].uv = uv2;

  _indices[0] = 0;
  _indices[1] = 1;
  _indices[2] = 2;

}
void LandscapeRenderer::BuildNormArray()
{
	if (m_verts.Size() <= 0)
		return;

	int nextNormId = 0;

	// Go through all the strips...
	for (int i = 0; i < m_strips.Size(); ++i)
	{
		LandTriangleStrip *strip = m_strips[i];

		m_verts[nextNormId++].m_norm = g_upVector;
		m_verts[nextNormId++].m_norm = g_upVector;
		int const maxJ = strip->m_numVerts - 2;
		
		// For each vertex in strip
		for (int j = 0; j < maxJ; j += 2)
		{
			Vector3 const &v1 = m_verts[strip->m_firstVertIndex + j].m_pos;
			Vector3 const &v2 = m_verts[strip->m_firstVertIndex + j + 1].m_pos;
			Vector3 const &v3 = m_verts[strip->m_firstVertIndex + j + 2].m_pos;
			Vector3 const &v4 = m_verts[strip->m_firstVertIndex + j + 3].m_pos;

			Vector3 north(v1 - v2);
			Vector3 northEast(v3 - v2);
			Vector3 east(v4 - v2);

			Vector3 norm1(northEast ^ north);
			norm1.Normalise();
			Vector3 norm2(east ^ northEast);
			norm2.Normalise();

			m_verts[nextNormId++].m_norm = norm1;
			m_verts[nextNormId++].m_norm = norm2;

			int vertIndex = strip->m_firstVertIndex + j + 2;
			AppDebugAssert(nextNormId - 2 == vertIndex);
		}
	}

	int vertIndex = m_verts.NumUsed();
	AppDebugAssert(nextNormId == vertIndex);
}
Exemplo n.º 15
0
void dynamics_mul::compute_curvature_force(){
    for (auto eid = s_dsc->halfedges_begin(); eid != s_dsc->halfedges_end(); eid++) {

        if (s_dsc->is_interface(*eid)) {
            auto hew0 = s_dsc->walker(*eid);
            
            // Find next edge on the boundary
            auto hew1 = hew0.next().opp();
            while (1) {
                if (s_dsc->is_interface(hew1.halfedge())) {
                    hew1 = hew1.opp();
                    break;
                }
                
                hew1 = hew1.next().opp();
            }
            
            assert(hew0.halfedge() != hew1.halfedge());
            
            Vec2 p0 = s_dsc->get_pos(hew0.vertex()) - s_dsc->get_pos(hew0.opp().vertex());
            Vec2 p1 = s_dsc->get_pos(hew1.vertex()) - s_dsc->get_pos(hew1.opp().vertex());
            
            Vec2 norm0(p0[1], -p0[0]); norm0.normalize();
            Vec2 norm1(p1[1], -p1[0]); norm1.normalize();
            Vec2 norm = norm0 + norm1; norm.normalize();

#ifdef DEBUG
            assert(norm.length() < 1.1 and norm.length() > 0.9);
#endif
            
            
            double l0 = p0.length();
            double l1 = p1.length();
            double angle = std::atan2(CGLA::cross(p0, p1), DSC2D::Util::dot(p0, p1));
            double curvature = angle / (l0/2.0 + l1/2.0);
            
            s_dsc->add_node_internal_force(
                    hew0.vertex(), -norm*curvature*s_dsc->get_avg_edge_length()*g_param.alpha);
        }
    }
}
Exemplo n.º 16
0
Arquivo: Map.cpp Projeto: anliec/Mosp
bool Map::smallMove(Living *livingToMove, Coordinate from, Coordinate to)
{
    if(norm1(from,to)==1){
        /*Tile & beginning = getTile(from);
        Tile & ending = getTile(to);*/
        if(getTile(to).getType() != TILE_WALKABLE){
            std::cout << "tile not walkable" << std::endl;
            return false;
        }
        if(getTile(from).removeLiving(livingToMove)){
            getTile(to).addLiving(livingToMove);
            return true;
        }
        else{
            std::cout << "living does not existe on " << from << std::endl;
            return false;
        }
    }
    else{
        return false;
    }
}
Exemplo n.º 17
0
Vector
LineSearch(Function& f, real_type t, const Vector& xk, const Vector& dk,
           real_type maxWide, real_type thresh)
{
  static const real_type vfac = (3-sqrt(5.0))/2;
  static const real_type wfac = (sqrt(5.0)-1)/2;

  thresh = fabs(maxWide)*thresh;

  Vector fx;

  Vector v = xk;
  f.eval(t, v, fx);
  real_type fv = norm(fx);

  Vector w = xk + maxWide*dk;
  f.eval(t, w, fx);
  real_type fw = norm(fx);

  while (norm1(v - w) > thresh) {
    Log(NewtonMethod, Debug2) << " Line Search: errv = " << fv
                              << ", errw = " << fw << endl;
    // check for isfinite ...
    if (fv > fw) {
      v = v + vfac*(w-v);
      f.eval(t, v, fx);
      fv = norm(fx);
    } else {
      w = v + wfac*(w-v);
      f.eval(t, w, fx);
      fw = norm(fx);
    }
  }

  return 0.5*(v+w);
}
 inline void norm1(size_t N, const  complext<float> * x, float& r)
 {
     norm1(N, (std::complex<float> *)x, r);
 }
Exemplo n.º 19
0
void MyGLWidget::createBuffers ()
{
  // Carreguem el model de l'OBJ - Atenció! Abans de crear els buffers!
  //patr.load("/assig/idi/models/Patricio.obj");
  patr.load("/assig/idi/models/Patricio.obj");

  // Calculem la capsa contenidora del model
  calculaCapsaModel ();
  
  // Creació del Vertex Array Object del Patricio
  glGenVertexArrays(1, &VAO_Patr);
  glBindVertexArray(VAO_Patr);

  // Creació dels buffers del model patr
  // Buffer de posicions
  glGenBuffers(1, &VBO_PatrPos);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrPos);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_vertices(), GL_STATIC_DRAW);

  // Activem l'atribut vertexLoc
  glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(vertexLoc);

  // Buffer de normals
  glGenBuffers(1, &VBO_PatrNorm);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrNorm);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_normals(), GL_STATIC_DRAW);

  glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(normalLoc);

  // En lloc del color, ara passem tots els paràmetres dels materials
  // Buffer de component ambient
  glGenBuffers(1, &VBO_PatrMatamb);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatamb);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matamb(), GL_STATIC_DRAW);

  glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matambLoc);

  // Buffer de component difusa
  glGenBuffers(1, &VBO_PatrMatdiff);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatdiff);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matdiff(), GL_STATIC_DRAW);

  glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matdiffLoc);

  // Buffer de component especular
  glGenBuffers(1, &VBO_PatrMatspec);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatspec);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matspec(), GL_STATIC_DRAW);

  glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matspecLoc);

  // Buffer de component shininness
  glGenBuffers(1, &VBO_PatrMatshin);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatshin);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3, patr.VBO_matshin(), GL_STATIC_DRAW);

  glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matshinLoc);

  // Dades del terra
  // VBO amb la posició dels vèrtexs
  glm::vec3 posterra[12] = {
	glm::vec3(-1.0, -1.0, 1.0),
	glm::vec3(1.0, -1.0, 1.0),
	glm::vec3(-1.0, -1.0, -1.0),
	glm::vec3(-1.0, -1.0, -1.0),
	glm::vec3(1.0, -1.0, 1.0),
	glm::vec3(1.0, -1.0, -1.0),
	glm::vec3(-1.0, -1.0, -1.0),
	glm::vec3(1.0, -1.0, -1.0),
	glm::vec3(-1.0, 1.0, -1.0),
	glm::vec3(-1.0, 1.0, -1.0),
	glm::vec3(1.0, -1.0, -1.0),
	glm::vec3(1.0, 1.0, -1.0)
  }; 

  // VBO amb la normal de cada vèrtex
  glm::vec3 norm1 (0,1,0);
  glm::vec3 norm2 (0,0,1);
  glm::vec3 normterra[12] = {
	norm1, norm1, norm1, norm1, norm1, norm1, // la normal (0,1,0) per als primers dos triangles
	norm2, norm2, norm2, norm2, norm2, norm2  // la normal (0,0,1) per als dos últims triangles
  };

  // Definim el material del terra
  glm::vec3 amb(0,0,1);
  glm::vec3 diff(0,0,1);
  glm::vec3 spec(1,1,1);
  float shin = 100;

  // Fem que aquest material afecti a tots els vèrtexs per igual
  glm::vec3 matambterra[12] = {
	amb, amb, amb, amb, amb, amb, amb, amb, amb, amb, amb, amb
  };
  glm::vec3 matdiffterra[12] = {
	diff, diff, diff, diff, diff, diff, diff, diff, diff, diff, diff, diff
  };
  glm::vec3 matspecterra[12] = {
	spec, spec, spec, spec, spec, spec, spec, spec, spec, spec, spec, spec
  };
  float matshinterra[12] = {
	shin, shin, shin, shin, shin, shin, shin, shin, shin, shin, shin, shin
  };

// Creació del Vertex Array Object del terra
  glGenVertexArrays(1, &VAO_Terra);
  glBindVertexArray(VAO_Terra);

  glGenBuffers(1, &VBO_TerraPos);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraPos);
  glBufferData(GL_ARRAY_BUFFER, sizeof(posterra), posterra, GL_STATIC_DRAW);

  // Activem l'atribut vertexLoc
  glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(vertexLoc);

  glGenBuffers(1, &VBO_TerraNorm);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraNorm);
  glBufferData(GL_ARRAY_BUFFER, sizeof(normterra), normterra, GL_STATIC_DRAW);

  // Activem l'atribut normalLoc
  glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(normalLoc);

  // En lloc del color, ara passem tots els paràmetres dels materials
  // Buffer de component ambient
  glGenBuffers(1, &VBO_TerraMatamb);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatamb);
  glBufferData(GL_ARRAY_BUFFER, sizeof(matambterra), matambterra, GL_STATIC_DRAW);

  glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matambLoc);

  // Buffer de component difusa
  glGenBuffers(1, &VBO_TerraMatdiff);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatdiff);
  glBufferData(GL_ARRAY_BUFFER, sizeof(matdiffterra), matdiffterra, GL_STATIC_DRAW);

  glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matdiffLoc);

  // Buffer de component especular
  glGenBuffers(1, &VBO_TerraMatspec);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatspec);
  glBufferData(GL_ARRAY_BUFFER, sizeof(matspecterra), matspecterra, GL_STATIC_DRAW);

  glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matspecLoc);

  // Buffer de component shininness
  glGenBuffers(1, &VBO_TerraMatshin);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatshin);
  glBufferData(GL_ARRAY_BUFFER, sizeof(matshinterra), matshinterra, GL_STATIC_DRAW);

  glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matshinLoc);

  glBindVertexArray(0);
}
 void norm1(const hoNDArray<T>& x, typename realType<T>::Type& r)
 {
     norm1(x.get_number_of_elements(), x.begin(), r);
 }
 inline void norm1(size_t N, const  complext<double> * x, double& r)
 {
     norm1(N, (std::complex<double> *)x, r);
 }
Exemplo n.º 22
0
Int_t main(Int_t argc, Char_t *argv[])
{
   ROOT::Mpi::TEnvironment env(argc, argv);
   ROOT::Mpi::TIntraCommunicator world;
   TVectorT<Double_t> mResult;
   Double_t fScalarResult;
   TVectorT<Double_t> v1(elements);
   TVectorT<Double_t> v2(elements);

   for (Int_t i = 0; i < elements; i++) {
      v1[i] = i + (i + world.Size());
      v2[i] = i * (i + world.Size());

   }

///////////////////////////////////////////////
//Testing methdos with results in single Rank//
///////////////////////////////////////////////
   ROOT::Mpi::Math::TVectorTWrapper<Double_t> add(v1);
   add.Addition(v2, root);

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> sub(v1);
   sub.Subtraction(v2, root);

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> dot(v1);
   dot.Dot(v2, root);

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> norm2Sqr(v1);
   norm2Sqr.Norm2Sqr(root);

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> norm1(v1);
   norm1.Norm1(root);

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> min(v1);
   min.Min(root);

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> max(v1);
   max.Max(root);

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> normalize(v1);
   normalize.Normalize(root);

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> sum(v1);
   sum.Sum(root);

   if (world.Rank() == root) {
      add.GetResult(mResult);
      MpiCompareTVectorTest(mResult, v1 + v2, world.Rank(), "Vector Addition Single");

      sub.GetResult(mResult);
      MpiCompareTVectorTest(mResult, v1 - v2, world.Rank(), "Vector Subtraction Single");

      dot.GetResult(fScalarResult);
      MpiCompareTest(fScalarResult, Dot(v1, v2) , world.Rank(), "Vector Dot Product Single");

      norm2Sqr.GetResult(fScalarResult);
      MpiCompareTest(fScalarResult, v1.Norm2Sqr() , world.Rank(), "Vector Norm2Sqr Single");

      norm1.GetResult(fScalarResult);
      MpiCompareTest(fScalarResult, v1.Norm1() , world.Rank(), "Vector Norm1 Single");

      min.GetResult(fScalarResult);
      MpiCompareTest(fScalarResult, v1.Min() , world.Rank(), "Vector Min Single");

      max.GetResult(fScalarResult);
      MpiCompareTest(fScalarResult, v1.Max() , world.Rank(), "Vector Max Single");

      normalize.GetResult(mResult);
      MpiCompareTest(mResult.Norm2Sqr(), ((1 / TMath::Sqrt(v1.Norm2Sqr()))*v1).Norm2Sqr() , world.Rank(), "Vector Normalize Single");

      sum.GetResult(fScalarResult);
      MpiCompareTest(fScalarResult, v1.Sum(), world.Rank(), "Vector Sum Single");
   }

///////////////////////////////////////////////
//Testing methdos with results in all ranks  //
///////////////////////////////////////////////

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> addAll(v1);
   add.Addition(v2);

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> subAll(v1);
   sub.Subtraction(v2);

   add.GetResult(mResult);
   MpiCompareTVectorTest(mResult, v1 + v2, world.Rank(), "Vector Addition All");

   sub.GetResult(mResult);
   MpiCompareTVectorTest(mResult, v1 - v2, world.Rank(), "Vector Subtraction All");

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> dotAll(v1);
   dotAll.Dot(v2);
   dotAll.GetResult(fScalarResult);
   MpiCompareTest(fScalarResult, Dot(v1, v2) , world.Rank(), "Vector Dot Product All");

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> norm2SqrAll(v2);
   norm2SqrAll.Norm2Sqr();
   norm2SqrAll.GetResult(fScalarResult);
   MpiCompareTest(fScalarResult, v2.Norm2Sqr() , world.Rank(), "Vector Norm2Sqr All");

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> norm1All(v2);
   norm1All.Norm1();
   norm1All.GetResult(fScalarResult);
   MpiCompareTest(fScalarResult, v2.Norm1() , world.Rank(), "Vector Norm1 All");

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> minAll(v2);
   minAll.Min();
   minAll.GetResult(fScalarResult);
   MpiCompareTest(fScalarResult, v2.Min() , world.Rank(), "Vector Min All");


   ROOT::Mpi::Math::TVectorTWrapper<Double_t> maxAll(v2);
   maxAll.Max();
   maxAll.GetResult(fScalarResult);
   MpiCompareTest(fScalarResult, v2.Max() , world.Rank(), "Vector Max All");

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> normalizeAll(v2);
   normalizeAll.Normalize();
   normalizeAll.GetResult(mResult);
   //show if the vector is normalize, then Norm2Sqr of result is near to 1
   MpiCompareTest(mResult.Norm2Sqr(), ((1 / TMath::Sqrt(v2.Norm2Sqr()))*v2).Norm2Sqr() , world.Rank(), "Vector Normalize All");

   ROOT::Mpi::Math::TVectorTWrapper<Double_t> sumAll(v2);
   sumAll.Sum();
   sumAll.GetResult(fScalarResult);
   MpiCompareTest(fScalarResult, v2.Sum() , world.Rank(), "Vector Sum All");


   return 0;
}
Exemplo n.º 23
0
void xdnorm1( double * s2 , unsigned n , const double * x )
{
    norm1( s2 , x , x + n );
}
Exemplo n.º 24
0
vector_t& vector_t::normalize_1()
{
	stack::fe_asserter dummy{};
	*this /= norm1();
	return *this;
}
Exemplo n.º 25
0
CubitBoolean SimplifyTool::maximum_angle_deviation(
    RefFace* seed_ref_face,
    RefFace* ref_face_ptr,
    double angle_in,
    double &angle_out)
{
  double max_angle = -360;
  RefEdge* ref_edge = NULL;

  double tol = angle_in / 2.0;
    
    
  DLIList<RefEdge*> common_edges;
  int num_edges = seed_ref_face->common_ref_edges(ref_face_ptr, common_edges);
  if(num_edges != common_edges.size()){
    PRINT_ERROR("Unexpected results.  List size incorrect.\n");
    return CUBIT_FALSE;
  }

  int i, j;
  for(i=0; i<num_edges; i++){
      
    GMem g_mem;
    ref_edge = common_edges.get_and_step();
      
    ref_edge->get_geometry_query_engine()->
        get_graphics(ref_edge->get_curve_ptr(), &g_mem, tol);

    if(g_mem.pointListCount < 2)
    {
        // Decrease tolerance and try again (we can get this for small features)
      tol /= 2.;
        
      ref_edge->get_geometry_query_engine()->
          get_graphics(ref_edge->get_curve_ptr(), &g_mem, tol); 
    }

    if(g_mem.pointListCount < 2)
    {
        // Lets give up 
      PRINT_ERROR( "Unable to find average normal of a curve\n" );
      return CUBIT_FAILURE;
    }

    GPoint* plist = g_mem.point_list();
      
    for( j=0; j<g_mem.pointListCount; j++ )
    {
      CubitVector p1(plist[j].x, plist[j].y, plist[j].z);
        

      CubitVector norm1(ref_face_ptr->normal_at(p1));
      CubitVector norm2(seed_ref_face->normal_at(p1));
        
      double angle = norm1.interior_angle( norm2 );
      if(angle > max_angle)
        max_angle=angle;
    }
  }
  if(max_angle < -.000001){
    return CUBIT_FAILURE;
  }
  angle_out = max_angle;
    
  return CUBIT_SUCCESS;
}
Exemplo n.º 26
0
bool
LevenbergMarquart(Function& f,
                  real_type t,
                  Vector& x,
                  real_type atol, real_type rtol,
                  unsigned *itCount,
                  unsigned maxit)
{
  Log(NewtonMethod, Debug3) << "Start guess\nx = " << trans(x) << endl;

  Matrix J;
  LinAlg::MatrixFactors<real_type,0,0,LinAlg::LUTag> jacFactors;

  bool converged = false;
  real_type tau = 1e-1;
  real_type nu = 2;

  // Compute in each step a new jacobian
  f.jac(t, x, J);
  Log(NewtonMethod, Debug3) << "Jacobian is:\n" << J << endl;
  real_type mu = tau*norm1(J);

  Vector fx;
  // Compute the actual error
  f.eval(t, x, fx);
  Vector g = trans(J)*fx;

  do {
    jacFactors = trans(J)*J + mu*LinAlg::Eye<real_type,0,0>(rows(x), rows(x));
    Log(NewtonMethod, Debug) << "Jacobian is "
                             << (jacFactors.singular() ? "singular" : "ok")
                             << endl;
   
    // Compute the search direction
    Vector h = jacFactors.solve(-g);
    Log(NewtonMethod, Debug) << "Solve Residual "
                             << norm(trans(J)*J*h + mu*h + g)/norm(g) << endl;

    // Get a better search guess
    Vector xnew = x + h;

    // check convergence
    converged = equal(x, xnew, atol, rtol);
    Log(NewtonMethod, Debug) << "Convergence test: ||h||_1 = " << norm1(h)
                             << ", converged = " << converged << endl;
    if (converged)
      break;

    f.eval(t, x, fx);
    real_type Fx = norm(fx);
    f.eval(t, xnew, fx);
    real_type Fxnew = norm(fx);
    real_type rho = (Fx - Fxnew)/(0.5*dot(h, mu*h - g));
    Log(NewtonMethod, Debug) << "Rho = " << rho
                             << ", Fxnew = " << Fxnew 
                             << ", Fx = " << Fx
                             << endl;
    if (0 < rho) {
      Log(NewtonMethod, Debug) << "Accepted step!" << endl;
      Log(NewtonMethod, Debug3) << "xnew = " << trans(xnew) << endl;
      Log(NewtonMethod, Debug3) << "h    = " << trans(h) << endl;

      // New guess is the better one
      x = xnew;

      f.jac(t, x, J);
      Log(NewtonMethod, Debug3) << "Jacobian is:\n" << J << endl;
      // Compute the actual error
      f.eval(t, x, fx);
      g = trans(J)*fx;
      converged = norm1(g) < atol;
      Log(NewtonMethod, Debug) << "||g||_1 = " << norm1(g) << endl;

      mu = mu * max(real_type(1)/3, 1-pow(2*rho-1, real_type(3)));
      nu = 2;

    } else {
      mu = mu * nu;
      nu = 2 * nu;
    }
  } while (!converged);

  return converged;
}
Exemplo n.º 27
0
R dist1(V2<R> const& p, V2<R> const& q)
	{ return norm1(q-p); }
Exemplo n.º 28
0
void NodeGeom::ComputeIntersectionVertices()
{
	FPoint3 v, v_next, v_prev;
	FPoint3 pn0, pn1;
	float w;			// link width

	SortLinksByAngle();

	// how many links meet here?
	if (NumLinks() == 0)
	{
		; // bogus case (put a breakpoint here)
	}
	else if (NumLinks() == 1)
	{
		// dead end: only need 2 vertices for this node
		m_iVerts = 2;
		m_v.SetSize(2);

		// get info about the link
		LinkGeom *r = GetLink(0);
		w = (r->m_fLeftWidth + r->m_fRightWidth) / 2;

		pn1 = GetAdjacentRoadpoint(0);
		v = CreateRoadVector(m_p3, pn1, w);

		m_v[0].Set(m_p3.x + v.z, m_p3.y, m_p3.z - v.x);
		m_v[1].Set(m_p3.x - v.z, m_p3.y, m_p3.z + v.x);

		one++;
	}
	else if (NumLinks() == 2)
	{
		// only need 2 vertices for this node; no intersection
		m_iVerts = 2;
		m_v.SetSize(2);

		// get info about the links
		w = (GetLink(0)->m_fLeftWidth + GetLink(1)->m_fRightWidth) / 2.0f;

		pn0 = GetAdjacentRoadpoint(0);
		pn1 = GetAdjacentRoadpoint(1);

		v = CreateRoadVector(pn0, pn1, w);

		m_v[0].Set(m_p3.x + v.z, m_p3.y, m_p3.z - v.x);
		m_v[1].Set(m_p3.x - v.z, m_p3.y, m_p3.z + v.x);

		two++;
	}
	else
	{
		// intersection: need 2 vertices for each link meeting here
		m_iVerts = 2 * NumLinks();
		m_v.SetSize(m_iVerts);

		// For each pairs of links, find the places where the link edges
		//  intersect as they approach this node.

		// The following is an array of float triples, used as follows:
		//  x = minimum distance which avoids intersection with next link
		//  y = minimum distance which avoids intersection with previous link
		//  z = greater of x or y.
		FLine3 distance_to_intersection(NumLinks());

		// Go through the links once, collecting the minimum distances
		for (int i = 0; i < NumLinks(); i++)
		{
			// indices of the next and previous links
			const int i_next = (i == NumLinks()-1) ? 0 : i+1;

			const TLink *pL = GetLink(i);
			const TLink *pL_next = GetLink(i_next);

			const float width1 = pL->m_fLeftWidth;
			const float width2 = pL_next->m_fRightWidth;

			const FPoint3 linkv1 = GetUnitLinkVector(i);
			const FPoint3 linkv2 = GetUnitLinkVector(i_next);

			// Use 2D vectors for the following math
			// Compute two vectors: left road edge of this link, right road
			//  edge of the following link, compute where they intersect, in
			//  terms of the ua and ub factors, which are the distance along
			//  each input vector to the intersection point.
			const FPoint2 v1(linkv1.x, linkv1.z);
			const FPoint2 v2(linkv2.x, linkv2.z);

			const float denom = v2.y*v1.x - v2.x*v1.y;
			if (fabs(denom) < 0.01)
			{
				// too parallel, pick a safety value
				distance_to_intersection[i].x = 1.0f;
				distance_to_intersection[i_next].y = 1.0f;
			}
			else
			{
				FPoint2 norm1(linkv1.z, -linkv1.x);
				FPoint2 norm2(linkv2.z, -linkv2.x);
				norm1.Normalize();
				norm2.Normalize();

				const FPoint2 center(m_p3.x, m_p3.z);
				const FPoint2 p1 = center + norm1 * width1;
				const FPoint2 p2 = center - norm2 * width2;

				const float ua = (v2.x*(p1.y - p2.y) - v2.y*(p1.x - p2.x)) / denom;
				const float ub = (v1.x*(p1.y - p2.y) - v1.y*(p1.x - p2.x)) / denom;

				distance_to_intersection[i].x = ua;
				distance_to_intersection[i_next].y = ub;
			}
		}
		// Go through the links again, picking the largest minimum
		for (int i = 0; i < NumLinks(); i++)
		{
			distance_to_intersection[i].z = std::max(distance_to_intersection[i].x,
				distance_to_intersection[i].y);
		}
		// Now we can finally set the two points where this link meets the
		//  intersection without overlapping with the other links
		for (int i = 0; i < NumLinks(); i++)
		{
			const TLink *pL = GetLink(i);
			v = GetUnitLinkVector(i);

			FPoint3 norm(v.z, 0, -v.x);
			norm.Normalize();
			norm *= pL->m_fLeftWidth;

			const float dist = distance_to_intersection[i].z;
			m_v[i * 2 + 0] = m_p3 + norm + (v * dist);
			m_v[i * 2 + 1] = m_p3 - norm + (v * dist);
		}
		many++;
	}
}
Exemplo n.º 29
0
    void PointcloudProc::match(const Frame& frame0, const Frame& frame1, 
          const Eigen::Vector3d& trans, const Eigen::Quaterniond& rot, 
          std::vector<cv::DMatch>& matches) const
    {
      PointCloud<PointXYZRGBNormal> transformed_cloud;
      
      // First, transform the current frame. (Is this inverse?) (Or just transform the other cloud?)
      //transformPointCloudWithNormals<PointXYZRGBNormal>(frame1.cloud, transformed_cloud, -trans.cast<float>(), rot.cast<float>().conjugate());
      
      //transformPointCloudWithNormals<PointXYZRGBNormal>(frame0.pointcloud, transformed_cloud, -trans.cast<float>(), rot.cast<float>().conjugate());
      transformPointCloudWithNormals<PointXYZRGBNormal>(frame0.pointcloud, transformed_cloud, Vector3f(0,0,0), rot.cast<float>().conjugate());
      transformPointCloudWithNormals<PointXYZRGBNormal>(transformed_cloud, transformed_cloud, -trans.cast<float>(), Quaternionf(1, 0, 0, 0));
      //pcl::io::savePCDFileASCII ("cloud0.pcd", transformed_cloud);
      //pcl::io::savePCDFileASCII ("cloud1.pcd", frame1.pointcloud);
      
      // Optional/TODO: Perform ICP to further refine estimate.
      /*PointCloud<PointXYZRGBNormal> cloud_reg;

      IterativeClosestPointNonLinear<PointXYZRGBNormal, PointXYZRGBNormal> reg;
      reg.setInputCloud (boost::make_shared<const PointCloud<PointXYZRGBNormal> > (transformed_cloud));
      reg.setInputTarget (boost::make_shared<const PointCloud<PointXYZRGBNormal> > (frame1.pointcloud));
      reg.setMaximumIterations(50);
      reg.setTransformationEpsilon (1e-8);

      reg.align(cloud_reg); */
            
      // Find matches between pointclouds in frames. (TODO: also compare normals)
      std::vector<int> f0_indices, f1_indices;
      getMatchingIndices(transformed_cloud, frame1.pointcloud, f0_indices, f1_indices);
      
      // Fill in keypoints and projections of relevant features.
      // Currently just done when setting the pointcloud.
      
      // Convert matches into the correct format.
      matches.clear();
      // Starting at i=1 as a hack to not let through (0,0,0) matches (why is this in the ptcloud?))
      
      #pragma omp parallel for shared( transformed_cloud, f0_indices, f1_indices )
      for (unsigned int i=1; i < f0_indices.size(); i++)
      {
        const PointXYZRGBNormal &pt0 = transformed_cloud.points[f0_indices[i]];
        const PointXYZRGBNormal &pt1 = frame1.pointcloud.points[f1_indices[i]];
        
        // Figure out distance and angle between normals
        Quaterniond normalquat;
        Vector3d norm0(pt0.normal[0], pt0.normal[1], pt0.normal[2]), norm1(pt1.normal[0], pt1.normal[1], pt1.normal[2]);
        normalquat.setFromTwoVectors(norm0, norm1);
        //double angledist = normalquat.angularDistance(normalquat.Identity());
        double dist = (Vector3d(pt0.x, pt0.y, pt0.z)-Vector3d(pt1.x, pt1.y, pt1.z)).norm();
        
        /* Vector4d p0_pt = Vector4d(pt0.x, pt0.y, pt0.z, 1.0);
        Vector3d expected_proj = projectPoint(p0_pt, frame0.cam);
        
        Vector3d diff = expected_proj - frame1.pl_kpts[f1_indices[i]].head<3>();
        diff(2) = diff(2) - diff(0);
        
        printf("[Proj difference] %f %f %f\n", diff(0), diff(1), diff(2)); */
        
        if ((norm0 - norm1).norm() < 0.5 && dist < 0.2)
          #pragma omp critical
          matches.push_back(cv::DMatch(f0_indices[i], f1_indices[i], dist));
      }
      
      printf("[Frame] Found %d matches, then converted %d matches.\n", (int)f0_indices.size(), (int)matches.size());
    }
Exemplo n.º 30
0
int main(int argc, char *argv[])
{
  Teuchos::oblackholestream blackhole;
  Teuchos::GlobalMPISession mpiSession(&argc,&argv,&blackhole);

  // 
  // Get the default communicator and node
  //
  auto &platform = Tpetra::DefaultPlatform::getDefaultPlatform();
  auto comm = platform.getComm();
  auto node = platform.getNode();
  const int myImageID = comm->getRank();
  const int numImages = comm->getSize();
  const bool verbose = (myImageID==0);

  // 
  // Say hello, print some communicator info
  //
  if (verbose) {
    std::cout << "\n" << Tpetra::version() << std::endl;
    std::cout << "Comm info: " << *comm;
    std::cout << "Node type: " << Teuchos::typeName(*node) << std::endl;
    std::cout << std::endl;
  }

  // 
  // Create a simple map for domain and range
  // 
  Tpetra::global_size_t numGlobalRows = 1000*numImages;
  auto map = Tpetra::createUniformContigMapWithNode<int,int>(numGlobalRows, comm, node);
  auto x = Tpetra::createVector<double>(map),
       y = Tpetra::createVector<double>(map);

  // Create a simple diagonal operator using lambda function
  auto fTwoOp = Tpetra::RTI::binaryOp<double>( [](double /*y*/, double x) { return 2.0 * x; } , map );
  // y = 3*fTwoOp*x + 2*y = 3*2*1 + 2*1 = 8
  x->putScalar(1.0);
  y->putScalar(1.0);
  fTwoOp->apply( *x, *y, Teuchos::NO_TRANS, 3.0, 2.0 );
  // check that y == eights
  double norm = y->norm1();
  if (verbose) {
    std::cout << "Tpetra::RTI::binaryOp" << std::endl
              << "norm(y) result == " << std::setprecision(2) << std::scientific << norm 
              << ", expected value is " << numGlobalRows * 8.0 << std::endl;
  }

  //
  // Create a finite-difference stencil using a Kokkos kernel and non-trivial maps
  //
  decltype(map) colmap;
  if (numImages > 1) {
    Teuchos::Array<int>           colElements;
    Teuchos::ArrayView<const int> rowElements = map->getNodeElementList();
    // This isn't the most efficient Map/Import layout, but it makes for a very straight-forward kernel
    if (myImageID != 0) colElements.push_back( map->getMinGlobalIndex() - 1 );
    colElements.insert(colElements.end(), rowElements.begin(), rowElements.end());
    if (myImageID != numImages-1) colElements.push_back( map->getMaxGlobalIndex() + 1 );
    colmap = Tpetra::createNonContigMapWithNode<int,int>(colElements(), comm, node);
  }
  else {
    colmap = map;
  }
  auto importer = createImport(map,colmap);
  // Finite-difference kernel = tridiag(-1, 2, -1)
  FDStencil<double> kern(myImageID, numImages, map->getNodeNumElements(), -1.0, 2.0, -1.0);
  auto FDStencilOp = Tpetra::RTI::kernelOp<double>( kern, map, map, importer );
  // x = ones(), FD(x) = [1 zeros() 1]
  FDStencilOp->apply( *x, *y );
  norm = y->norm1();
  if (verbose) {
    std::cout << std::endl
              << "TpetraExamples::FDStencil" << std::endl
              << "norm(y) result == " << std::setprecision(2) << std::scientific << norm 
              << ", expected value is " << 2.0 << std::endl;
  }

  std::cout << "\nEnd Result: TEST PASSED" << std::endl;
  return 0;
}