예제 #1
0
파일: EditStak.cpp 프로젝트: cjang/chai
void EditStak::visit(const uint32_t variable, const uint32_t version)
{
    if (0 == _replaceVar.count(variable))
    {
        if (0 == _replaceVarBC.count(variable))
        {
            // no change
            _newBytecode.push( BC(variable, version) );
        }
        else
        {
            // change the variable, replace with bytecode
            _newBytecode.push( _replaceVarBC[variable] );
            _isEdited = true;
        }
    }
    else
    {
        // note: variable replacement overrides bytecode in case of both

        // change the variable, replace with another variable
        _newBytecode.push( BC(_replaceVar[variable], version) );
        _isEdited = true;
    }
}
예제 #2
0
파일: complex.cpp 프로젝트: caosuomo/rads
bool complex::InsertCube(block* b)
{
   bitcode* bc=new bitcode(BC(b).Bits());
   bc->SetAs(BC(b));
   
   cubes.Insert(*bc,b);
   if (previous_cube==NULL)
     {
	previous_cube=new bitcode(cube_bits);
	previous_cube->SetAs(bc);
	delete bc;
        return true;	
     }

//   assert(previous_cube->Bits()==cube_bits);
   
   node* simplifiable_node;
   block* simplifiable_block;
   int levels=Ancestor(bc,previous_cube);  
   while (levels>=DIM)
     {
	for (int j=0; j<DIM; ++j)
	   (*previous_cube)++;
	levels-=DIM;
        simplifiable_node=cubes.Find(*previous_cube);
	simplifiable_block=Merge(simplifiable_node);
	Simplify(simplifiable_block);
      }
   
   delete previous_cube;
   previous_cube=new bitcode(cube_bits);
   previous_cube->SetAs(*bc);
   delete bc;
   return true;
}
예제 #3
0
파일: ogl_color.cpp 프로젝트: paud/d2x-xl
void OglColor4sf (float r, float g, float b, float s)
{
if (gameStates.ogl.bStandardContrast)
	glColor4f (r * s, g * s, b * s, gameStates.ogl.fAlpha);
else {
	float c = (float) gameStates.ogl.nContrast - 8.0f;

	if (c > 0.0f)
		c = 1.0f / (1.0f + c * (3.0f / 8.0f));
	else
		c = 1.0f - c * (3.0f / 8.0f);
	glColor4f (BC (r, c) * s, BC (g, c) * s, BC (b, c) * s, gameStates.ogl.fAlpha);
	}
}
예제 #4
0
  // Checks whether 3D points p lies inside or outside of the triangle ABC
  bool includePointTriangle(Vec3r& P,
			    Vec3r& A,
			    Vec3r& B,
			    Vec3r& C) {
    Vec3r AB(B - A);
    Vec3r BC(C - B);
    Vec3r CA(A - C);
    Vec3r AP(P - A);
    Vec3r BP(P - B);
    Vec3r CP(P - C);

    Vec3r N(AB ^ BC); // triangle's normal

    N.normalize();

    Vec3r J(AB ^ AP), K(BC ^ BP), L(CA ^ CP);
    J.normalize();
    K.normalize();
    L.normalize();

    if(J * N < 0)
      return false; // on the right of AB

    if(K * N < 0)
      return false; // on the right of BC

    if(L * N < 0)
      return false; // on the right of CA

    return true;
  }
예제 #5
0
bool change_coor(std::pair<int, int> postcard, std::pair<int, int> envelope)
{
    int hypotenuse_envelope = sqrt(pow(envelope.first, 2) + pow(envelope.second, 2));
    if (hypotenuse_envelope - postcard.second)
    {
        float h_postcard, w_postcard;
        std::pair<int, int> A(0, 0);
        std::pair<int, int> B(0, postcard.second);
        std::pair<int, int> C(postcard.first, 0);
        std::pair<int, int> D(postcard.first, postcard.second);
        for (float angle = 0; angle <= 2*PI;)
        {
            std::pair<float, float> AD(rotate(D, angle));
            std::pair<float, float> new_A(rotate(A, angle));
            AD.first -= new_A.first;
            AD.second -= new_A.second;
            std::pair<float, float> BC(rotate(C, angle));
            std::pair<float, float> new_B(rotate(B, angle));
            BC.first -= new_B.first;
            BC.second -= new_B.second;
            h_postcard = std::max(abs(BC.second), abs(AD.second));
            w_postcard = std::max(abs(BC.first), abs(AD.first));

            if ((h_postcard <= envelope.second)&&(w_postcard <= envelope.first))
                return true;
            angle += 0.001;

        }
    }
    else
        return false;
}
예제 #6
0
 Uint32 Long() const
 {
     return (AC()<<24)
            | (RC()<<16)
            | (GC()<<8)
            | BC();
 }
예제 #7
0
int VertexOrientation2DF0D::operator()(Interface0DIterator& iter)
{
	Vec2f A, C;
	Vec2f B(iter->getProjectedX(), iter->getProjectedY());
	if (iter.isBegin()) {
		A = Vec2f(iter->getProjectedX(), iter->getProjectedY());
	}
	else {
		Interface0DIterator previous = iter;
		--previous ;
		A = Vec2f(previous->getProjectedX(), previous->getProjectedY());
	}
	Interface0DIterator next = iter;
	++next;
	if (next.isEnd())
		C = Vec2f(iter->getProjectedX(), iter->getProjectedY());
	else
		C = Vec2f(next->getProjectedX(), next->getProjectedY());

	Vec2f AB(B - A);
	if (AB.norm() != 0)
		AB.normalize();
	Vec2f BC(C - B);
	if (BC.norm() != 0)
		BC.normalize();
	result = AB + BC;
	if (result.norm() != 0)
		result.normalize();
	return 0;
}
예제 #8
0
파일: MeshQuad.cpp 프로젝트: cpraveen/taxis
double QuadQuality(const Vertex & a,const Vertex &b,const Vertex &c,const Vertex &d)
{
  // calcul de 4 angles --
  R2 A((R2)a),B((R2)b),C((R2)c),D((R2)d);
  R2 AB(B-A),BC(C-B),CD(D-C),DA(A-D);
  //  Move(A),Line(B),Line(C),Line(D),Line(A);
  const Metric & Ma  = a;
  const Metric & Mb  = b;
  const Metric & Mc  = c;
  const Metric & Md  = d;
    
  double lAB=Norme2(AB);
  double lBC=Norme2(BC);
  double lCD=Norme2(CD);
  double lDA=Norme2(DA);
  AB /= lAB;  BC /= lBC;  CD /= lCD;  DA /= lDA;
  // version aniso 
  double cosDAB= Ma(DA,AB)/(Ma(DA)*Ma(AB)),sinDAB= Det(DA,AB);
  double cosABC= Mb(AB,BC)/(Mb(AB)*Mb(BC)),sinABC= Det(AB,BC);
  double cosBCD= Mc(BC,CD)/(Mc(BC)*Mc(CD)),sinBCD= Det(BC,CD);
  double cosCDA= Md(CD,DA)/(Md(CD)*Md(DA)),sinCDA= Det(CD,DA);
  double sinmin=Min(Min(sinDAB,sinABC),Min(sinBCD,sinCDA));
  // cout << A << B << C << D ;
  // cout << " sinmin " << sinmin << " " << cosDAB << " " << cosABC << " " << cosBCD << " " << cosCDA << endl;
  // rattente(1);
  if (sinmin<=0) return sinmin;
  return 1.0-Max(Max(Abs(cosDAB),Abs(cosABC)),Max(Abs(cosBCD),Abs(cosCDA)));
}
예제 #9
0
  Vec3f VertexOrientation3DF0D::operator()(Interface0DIterator& iter) {
    Vec3r A,C;
    Vec3r B(iter->getX(), iter->getY(), iter->getZ());
    if(iter.isBegin())
      A = Vec3r(iter->getX(), iter->getY(), iter->getZ());
    else
      {
	Interface0DIterator previous = iter;
	--previous ;
	A = Vec3r(previous->getX(), previous->getY(), previous->getZ());
      }
    Interface0DIterator next = iter;
    ++next ;
    if(next.isEnd())
      C = Vec3r(iter->getX(), iter->getY(), iter->getZ());
    else
      C = Vec3r(next->getX(), next->getY(), next->getZ());

    Vec3r AB(B-A);
    if(AB.norm() != 0)
      AB.normalize();
    Vec3r BC(C-B);
    if(BC.norm() != 0)
      BC.normalize();
    Vec3f res (AB + BC);
    if(res.norm() != 0)
      res.normalize();
    return res;
  }
예제 #10
0
float calcAngle(vector<float> & A, vector<float> & B, vector<float> & C) {
    vector<float> BA(3), BC(3);
    linear_combination(BA, 1, A, -1, B);
    linear_combination(BC, 1, C, -1, B);
    normalize_point(BA, BA); normalize_point(BC, BC);
    float dp = dot_product(BA,BC);
    if(dp > 1) dp = 1;
    else if(dp < -1) dp = -1;
    return RADIANS_TO_DEGREES( acos(dp) );
}
예제 #11
0
void	CBlender_Compile::PassSET_ZB		(BOOL bZTest, BOOL bZWrite, BOOL bInvertZTest)
{
	if (Pass())	bZWrite = FALSE;
	RS.SetRS	(D3DRS_ZFUNC,			bZTest?(bInvertZTest?D3DCMP_GREATER:D3DCMP_LESSEQUAL):D3DCMP_ALWAYS);
	RS.SetRS	(D3DRS_ZWRITEENABLE,	BC(bZWrite));
	/*
	if (bZWrite || bZTest)				RS.SetRS	(D3DRS_ZENABLE,	D3DZB_TRUE);
	else								RS.SetRS	(D3DRS_ZENABLE,	D3DZB_FALSE);
	*/
}
예제 #12
0
int Curvature2DAngleF0D::operator()(Interface0DIterator& iter)
{
	Interface0DIterator tmp1 = iter, tmp2 = iter;
	++tmp2;
	unsigned count = 1;
	while ((!tmp1.isBegin()) && (count < 3)) {
		--tmp1;
		++count;
	}
	while ((!tmp2.isEnd()) && (count < 3)) {
		++tmp2;
		++count;
	}
	if (count < 3) {
		// if we only have 2 vertices
		result = 0;
		return 0;
	}

	Interface0DIterator v = iter;
	if (iter.isBegin())
		++v;
	Interface0DIterator next = v;
	++next;
	if (next.isEnd()) {
		next = v;
		--v;
	}
	Interface0DIterator prev = v;
	--prev;

	Vec2r A(prev->getProjectedX(), prev->getProjectedY());
	Vec2r B(v->getProjectedX(), v->getProjectedY());
	Vec2r C(next->getProjectedX(), next->getProjectedY());
	Vec2r AB(B - A);
	Vec2r BC(C - B);
	Vec2r N1(-AB[1], AB[0]);
	if (N1.norm() != 0)
		N1.normalize();
	Vec2r N2(-BC[1], BC[0]);
	if (N2.norm() != 0)
		N2.normalize();
	if ((N1.norm() == 0) && (N2.norm() == 0)) {
		Exception::raiseException();
		result = 0;
		return -1; 
	}
	double cosin = N1 * N2;
	if (cosin > 1)
		cosin = 1;
	if (cosin < -1)
		cosin = -1;
	result = acos(cosin);
	return 0;
}
예제 #13
0
void	CBlender_Compile::PassSET_ablend_mode	(BOOL bABlend,	u32 abSRC, u32 abDST)
{
	if (bABlend && D3DBLEND_ONE==abSRC && D3DBLEND_ZERO==abDST)		bABlend = FALSE;
	RS.SetRS(D3DRS_ALPHABLENDENABLE,	BC(bABlend));
	RS.SetRS(D3DRS_SRCBLEND,			bABlend?abSRC:D3DBLEND_ONE	);
	RS.SetRS(D3DRS_DESTBLEND,			bABlend?abDST:D3DBLEND_ZERO	);

#if defined(USE_DX10) || defined(USE_DX11)
	//	Since in our engine D3DRS_SEPARATEALPHABLENDENABLE state is
	//	always set to false and in DirectX 10 blend functions for 
	//	color and alpha are always independent, assign blend options for
	//	alpha in DX10 identical to color.
	RS.SetRS(D3DRS_SRCBLENDALPHA,		bABlend?abSRC:D3DBLEND_ONE	);
	RS.SetRS(D3DRS_DESTBLENDALPHA,		bABlend?abDST:D3DBLEND_ZERO	);
#endif	//	USE_DX10
}
 // Constructor, initialize values
 Jacobi() {
     int i,j;
     usesAtSync = true;
       // allocate two dimensional array
     temperature = new double*[block_height+2];
     for (i=0; i<block_height+2; i++)
       temperature[i] = new double[block_width+2];
     messages_due = 4;
     for(i=0;i<block_height+2;++i){
       for(j=0;j<block_width+2;++j){
         temperature[i][j] = 0.0;
       }
     }
     itercnt=0;
     hasSent=false;
     BC();
 }
예제 #15
0
void CBlender_Compile::r_Stencil(BOOL Enable, u32 Func, u32 Mask, u32 WriteMask, u32 Fail, u32 Pass, u32 ZFail)
{
	RS.SetRS(	D3DRS_STENCILENABLE,	BC(Enable) );
	if (!Enable) return;
	RS.SetRS(	D3DRS_STENCILFUNC,		Func);
	RS.SetRS(	D3DRS_STENCILMASK,		Mask);
	RS.SetRS(	D3DRS_STENCILWRITEMASK,	WriteMask);
	RS.SetRS(	D3DRS_STENCILFAIL,		Fail);
	RS.SetRS(	D3DRS_STENCILPASS,		Pass);
	RS.SetRS(	D3DRS_STENCILZFAIL,		ZFail);
	//	Since we never really support different options for
	//	CW/CCW stencil use it to mimic DX9 behaviour for 
	//	single-sided stencil
	RS.SetRS(	D3DRS_CCW_STENCILFUNC,		Func);
	RS.SetRS(	D3DRS_CCW_STENCILFAIL,		Fail);
	RS.SetRS(	D3DRS_CCW_STENCILPASS,		Pass);
	RS.SetRS(	D3DRS_CCW_STENCILZFAIL,		ZFail);
}
    // Check to see if we have received all neighbor values yet
    // If all neighbor values have been received, we update our values and proceed
    void compute() {
      // We must create a new array for these values because we don't want to update any of the
      // the values in temperature[][] array until using them first. Other schemes could be used
      // to accomplish this same problem. We just put the new values in a temporary array
      // and write them to temperature[][] after all of the new values are computed.
      double new_temperature[block_height+2][block_width+2];

      for(int i=1;i<block_height+1;++i){
        for(int j=1;j<block_width+1;++j){
          // update my value based on the surrounding values
          new_temperature[i][j] = (temperature[i-1][j]+temperature[i+1][j]+temperature[i][j-1]+temperature[i][j+1]+temperature[i][j]) / 5.0;
        }
      }

      for(int i=0;i<block_height+2;++i)
        for(int j=0;j<block_width+2;++j)
          temperature[i][j] = new_temperature[i][j];

      // Enforce the boundary conditions again
      BC();
    }
예제 #17
0
//  checks whether M is inside the triangle
//  Gives incorrect result if M is not in plane ABC ( check this before! )
bool R3DTriangle::isInside(R3DPoint D)
{      

// if point M is in plane of triangle ABC
// and AM,BM,CM do not cross the sides

R3DPoint X;

R3DPoint M = (A+B+C)/3;

R3DLineSegment DM(D,M);

R3DLineSegment AB(A,B);
R3DLineSegment BC(B,C);
R3DLineSegment AC(A,C);

return !( intersect(DM,AB,&X)  ||
           intersect(DM,AC,&X)  ||
           intersect(DM,BC,&X) 
         );

}
예제 #18
0
bool UnitTests::Multifurcating()
{
	std::vector< std::vector<double> > dissMatrix;

	// unweighted Soergel
	DiversityCalculator Soergel("../unit-tests/Multifurcating.env", "../unit-tests/Multifurcating.tre", "Soergel", 1000, false, false, false, false, false);
	Soergel.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.855070))
		return false;

	// weighted Bray-Curtis
	DiversityCalculator BC("../unit-tests/Multifurcating.env", "../unit-tests/Multifurcating.tre", "Bray-Curtis", 1000, true, false, false, false, false);
	BC.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.75457500))
		return false;

	// weighted normalized UniFrac
	DiversityCalculator NWU("../unit-tests/Multifurcating.env", "../unit-tests/Multifurcating.tre", "NormalizedWeightedUniFrac", 1000, true, false, false, false, false);
	NWU.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.75457500))
		return false;

	// MRCA restricted weighted normalized UniFrac
	DiversityCalculator MRCA_NWU("../unit-tests/Multifurcating.env", "../unit-tests/Multifurcating.tre", "NormalizedWeightedUniFrac", 1000, true, false, true, false, false);
	MRCA_NWU.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.75457500))
		return false;

	return true;
}
예제 #19
0
bool Collision::CircleSegmentCollision(sf::Vector2f circleCenter, int radius, sf::Vector2f pointA, sf::Vector2f pointB)///Collision type Cercle - Segement
{
    std::cout<<"\nTest 1 Point A <"<<pointA.x<<","<<pointA.y<<"> Point B <"<<pointB.x<<","<<pointB.y<<">";
    if(!CircleDroiteCollision(pointA, pointB, circleCenter, radius))
        return false;
    std::cout<<" - Completed\nTest 2";
    sf::Vector2f AB(pointB.x - pointA.x, pointB.y - pointA.y);
    sf::Vector2f AC(circleCenter.x - pointA.x, circleCenter.y - pointA.y);
    sf::Vector2f BC(circleCenter.x - pointB.x, circleCenter.y - pointB.y);
    float pascal1 = AB.x * AC.x + AB.y * AC.y;
    float pascal2 = (-AB.x)*BC.x + (-AB.y)*BC.y;
    std::cout<<" - Completed\nTest 3";
    if(pascal1 >= 0 && pascal2 >=0)
        return true;
    std::cout<<" - Completed\nTest 4";
    if(PointCircleCollision(pointA, circleCenter, radius))
        return true;
    std::cout<<" - Completed\nTest 5";
    if(PointCircleCollision(pointB, circleCenter, radius))
        return true;
    std::cout<<" - Completed";
    return false;
}
예제 #20
0
bool Triangle::Intersects(const a2de::Vector2D& position) const {

    Vector3D A(GetPointA().GetX(), GetPointA().GetY());
    Vector3D B(GetPointB().GetX(), GetPointB().GetY());
    Vector3D C(GetPointC().GetX(), GetPointC().GetY());

    Vector3D AB(A - B);
    Vector3D BC(B - C);
    Vector3D CA(C - A);

    Vector3D AP(A - position);
    Vector3D BP(B - position);
    Vector3D CP(C - position);

    Vector3D resultABAP(Vector3D::CrossProduct(AB, AP));
    Vector3D resultBCBP(Vector3D::CrossProduct(BC, BP));
    Vector3D resultCACP(Vector3D::CrossProduct(CA, CP));

    bool resultPos = (resultABAP.GetZ() > 0.0) && (resultBCBP.GetZ() > 0.0) && (resultCACP.GetZ() > 0.0);
    bool resultZero = (Math::IsEqual(resultABAP.GetZ(), 0.0) && Math::IsEqual(resultBCBP.GetZ(), 0.0) && Math::IsEqual(resultCACP.GetZ(), 0.0));
    bool resultNeg = (resultABAP.GetZ() < 0.0) && (resultBCBP.GetZ() < 0.0) && (resultCACP.GetZ() < 0.0);
    //bool isOn = point.IsOnLine(GetLineAB()) || point.IsOnLine(GetLineBC()) || point.IsOnLine(GetLineCA());
    return (/*isOn ||*/ resultPos || resultZero || resultNeg);
}
예제 #21
0
파일: complex.cpp 프로젝트: caosuomo/rads
block* complex::Merge(node* n)
{
   list<block*> sub_blocks;
   Recurse(n,&sub_blocks,0);

   list<block*>::iterator sbit=sub_blocks.begin();
//   if (sbit==sub_blocks.end())
//     exit(1);

   block* b=new block(BC(*sbit),this);
//    block* b=new block(*((*sbit)->bc),this);
//   assert(b->bdry_verts.Empty());
//   (b->bc)->SetAs(BC(*sbit));
   BC(b).SetAs(BC(*sbit));
   for(int i=0;i<DIM;++i)
     BC(b)++;
   int level=(cube_bits-BC(b).Bits())/DIM;
   for(int i=0;i<level*DIM;++i)
     BC(b)--;
   BC(b).Coordinates(min);
   for(int i=0;i<level*DIM;++i)
     BC(b)++;

   vertex* v;
   int vc[DIM];
   int flag=1;
   cell_iter bvit;
   cell_iter cit;
   cobdry_iter cbit;

   while(sbit!=sub_blocks.end())
     {
	bvit=(*sbit)->bdry_verts.Begin();
	while(bvit!=(*sbit)->bdry_verts.End())
	  {
             v=(vertex*)(*bvit);
	     v->bc->Coordinates(vc);
	     flag=1;
	     for (int i=0; i<DIM; ++i)
	       flag*=(((min[i]<vc[i])&&(vc[i]<min[i]+Power2(level)))||((vc[i]==0)||(vc[i]==Power2(cube_bits/DIM))));
             if (flag)
	       {
		  if (!(v->Interior()))
		    {
		       v->MarkInterior();
		       DeleteVertex(v);
		       b->cells[0].InsertUniqueSort(v);
		    }
	       }
	     else
	       b->bdry_verts.InsertUniqueSort(v);
	     ++bvit;
	  }
	for(int i=0;i<DIM;++i)
	   {
 	      cit=(*sbit)->cells[i].Begin();
	      while(cit!=(*sbit)->cells[i].End())
	         {
	            b->cells[i].InsertUniqueSort(Ptr(cit));
	            ++cit;
	         }
	   }
	++sbit;
     }

   cit=b->cells[0].Begin();
   while(cit!=b->cells[0].End())
     {
	cbit=((vertex*)(*cit))->Cobdry()->Begin();
//      cout << "size " << (*cit)->Cobdry()->Size() << endl;
	while(cbit!=((vertex*)(*cit))->Cobdry()->End())
	   {
	      ((edge*)Ptr(cbit))->MarkInterior();
//	      b->cells[1].InsertUniqueSort(Ptr(cbit));
	      if (b->cells[1].Find(Ptr(cbit))==b->cells[1].End())
		{
		   b->cells[1].InsertUniqueSort(Ptr(cbit));
		}
	      ++cbit;
	   }
	++cit;
     }
   
   cit=b->cells[1].Begin();
   while(cit!=b->cells[1].End())
     {
	cbit=((edge*)(*cit))->Cobdry()->Begin();
//      cout << "size " << (*cit)->Cobdry()->Size() << endl;
	while(cbit!=((edge*)(*cit))->Cobdry()->End())
	   {
	      ((ncell*)Ptr(cbit))->MarkInterior();
//	      b->cells[2].InsertUniqueSort(Ptr(cbit));
	      if (b->cells[2].Find(Ptr(cbit))==b->cells[2].End())
		{
		   b->cells[2].InsertUniqueSort(Ptr(cbit));
		}
	      ++cbit;
	   }
	++cit;
     }	
	
   for(int i=3;i<DIM;++i)
     {
	cit=b->cells[i-1].Begin();
	while(cit!=b->cells[i-1].End())
	  {
	     cbit=((ncell*)(*cit))->Cobdry()->Begin();
//             cout << "size " << (*cit)->Cobdry()->Size() << endl;
	     while(cbit!=((ncell*)(*cit))->Cobdry()->End())
	       {
		  ((ncell*)Ptr(cbit))->MarkInterior();
//		  b->cells[i].InsertUniqueSort(Ptr(cbit));
		  if (b->cells[i].Find(Ptr(cbit))==b->cells[i].End())
		    {
		       b->cells[i].InsertUniqueSort(Ptr(cbit));
		    }
		  ++cbit;
	       }
	     ++cit;
	  }
     }
   
   if (n==cubes.Root)
     cubes.Root=b;
   else
     {
       node* parent=n->Parent;
       if (parent->Left==n)
         parent->Left=b;
       else
         parent->Right=b;
       b->Parent=parent;	
     }	
   
   Delete(n,0);
   
   return(b);	
}
예제 #22
0
파일: bootstrap.c 프로젝트: kwatch/rubinius
void cpu_bootstrap_exceptions(STATE) {
  int sz;
  sz = 3;
  
  OBJECT exc, scp, std, arg, nam, loe, rex, stk, sxp, sce, type, lje, vm;
  OBJECT fce;
  
  #define dexc(name, sup) rbs_class_new(state, #name, sz, sup)
  
  exc = dexc(Exception, BC(object));
  state->global->exception = exc;
  dexc(fatal, exc);
  vm = dexc(VMError, exc);
  dexc(VMAssertion, vm);
  scp = dexc(ScriptError, exc);
  std = dexc(StandardError, exc);
  type = dexc(TypeError, std);
  arg = dexc(ArgumentError, std);
  nam = dexc(NameError, std);
  rex = dexc(RegexpError, std);
  dexc(NoMethodError, nam);
  dexc(SyntaxError, scp);
  loe = dexc(LoadError, scp);
  dexc(RuntimeError, std);
  sce = dexc(SystemCallError, std);
  stk = dexc(StackError, exc);
  sxp = dexc(StackExploded, stk);
  
  lje = dexc(LocalJumpError, std);
  dexc(IllegalLongReturn, lje);
  
  fce = dexc(FlowControlException, exc);
  dexc(ReturnException, fce);
  dexc(LongReturnException, fce);
  
  state->global->exc_type = type;
  state->global->exc_arg = arg;
  state->global->exc_loe = loe;
  state->global->exc_rex = rex;
  
  state->global->exc_stack_explosion = sxp;
  state->global->exc_primitive_failure = dexc(PrimitiveFailure, exc);
  
  state->global->exc_segfault = dexc(MemorySegmentionError, exc);

  OBJECT ern = rbs_module_new(state, "Errno", state->global->object);

  state->global->errno_mapping = lookuptable_new(state);

  rbs_const_set(state, ern, "Mapping", state->global->errno_mapping);
  
  sz = 4;
  
#define set_syserr(num, name) ({ \
  OBJECT _cls = rbs_class_new_with_namespace(state, name, sz, sce, ern); \
  rbs_const_set(state, _cls, "Errno", I2N(num)); \
  lookuptable_store(state, state->global->errno_mapping, I2N(num), _cls); \
  })

/*
 * Stolen from MRI
 */

#ifdef EPERM
    set_syserr(EPERM, "EPERM");
#endif
#ifdef ENOENT
    set_syserr(ENOENT, "ENOENT");
#endif
#ifdef ESRCH
    set_syserr(ESRCH, "ESRCH");
#endif
#ifdef EINTR
    set_syserr(EINTR, "EINTR");
#endif
#ifdef EIO
    set_syserr(EIO, "EIO");
#endif
#ifdef ENXIO
    set_syserr(ENXIO, "ENXIO");
#endif
#ifdef E2BIG
    set_syserr(E2BIG, "E2BIG");
#endif
#ifdef ENOEXEC
    set_syserr(ENOEXEC, "ENOEXEC");
#endif
#ifdef EBADF
    set_syserr(EBADF, "EBADF");
#endif
#ifdef ECHILD
    set_syserr(ECHILD, "ECHILD");
#endif
#ifdef EAGAIN
    set_syserr(EAGAIN, "EAGAIN");
#endif
#ifdef ENOMEM
    set_syserr(ENOMEM, "ENOMEM");
#endif
#ifdef EACCES
    set_syserr(EACCES, "EACCES");
#endif
#ifdef EFAULT
    set_syserr(EFAULT, "EFAULT");
#endif
#ifdef ENOTBLK
    set_syserr(ENOTBLK, "ENOTBLK");
#endif
#ifdef EBUSY
    set_syserr(EBUSY, "EBUSY");
#endif
#ifdef EEXIST
    set_syserr(EEXIST, "EEXIST");
#endif
#ifdef EXDEV
    set_syserr(EXDEV, "EXDEV");
#endif
#ifdef ENODEV
    set_syserr(ENODEV, "ENODEV");
#endif
#ifdef ENOTDIR
    set_syserr(ENOTDIR, "ENOTDIR");
#endif
#ifdef EISDIR
    set_syserr(EISDIR, "EISDIR");
#endif
#ifdef EINVAL
    set_syserr(EINVAL, "EINVAL");
#endif
#ifdef ENFILE
    set_syserr(ENFILE, "ENFILE");
#endif
#ifdef EMFILE
    set_syserr(EMFILE, "EMFILE");
#endif
#ifdef ENOTTY
    set_syserr(ENOTTY, "ENOTTY");
#endif
#ifdef ETXTBSY
    set_syserr(ETXTBSY, "ETXTBSY");
#endif
#ifdef EFBIG
    set_syserr(EFBIG, "EFBIG");
#endif
#ifdef ENOSPC
    set_syserr(ENOSPC, "ENOSPC");
#endif
#ifdef ESPIPE
    set_syserr(ESPIPE, "ESPIPE");
#endif
#ifdef EROFS
    set_syserr(EROFS, "EROFS");
#endif
#ifdef EMLINK
    set_syserr(EMLINK, "EMLINK");
#endif
#ifdef EPIPE
    set_syserr(EPIPE, "EPIPE");
#endif
#ifdef EDOM
    set_syserr(EDOM, "EDOM");
#endif
#ifdef ERANGE
    set_syserr(ERANGE, "ERANGE");
#endif
#ifdef EDEADLK
    set_syserr(EDEADLK, "EDEADLK");
#endif
#ifdef ENAMETOOLONG
    set_syserr(ENAMETOOLONG, "ENAMETOOLONG");
#endif
#ifdef ENOLCK
    set_syserr(ENOLCK, "ENOLCK");
#endif
#ifdef ENOSYS
    set_syserr(ENOSYS, "ENOSYS");
#endif
#ifdef ENOTEMPTY
    set_syserr(ENOTEMPTY, "ENOTEMPTY");
#endif
#ifdef ELOOP
    set_syserr(ELOOP, "ELOOP");
#endif
#ifdef EWOULDBLOCK
    set_syserr(EWOULDBLOCK, "EWOULDBLOCK");
#endif
#ifdef ENOMSG
    set_syserr(ENOMSG, "ENOMSG");
#endif
#ifdef EIDRM
    set_syserr(EIDRM, "EIDRM");
#endif
#ifdef ECHRNG
    set_syserr(ECHRNG, "ECHRNG");
#endif
#ifdef EL2NSYNC
    set_syserr(EL2NSYNC, "EL2NSYNC");
#endif
#ifdef EL3HLT
    set_syserr(EL3HLT, "EL3HLT");
#endif
#ifdef EL3RST
    set_syserr(EL3RST, "EL3RST");
#endif
#ifdef ELNRNG
    set_syserr(ELNRNG, "ELNRNG");
#endif
#ifdef EUNATCH
    set_syserr(EUNATCH, "EUNATCH");
#endif
#ifdef ENOCSI
    set_syserr(ENOCSI, "ENOCSI");
#endif
#ifdef EL2HLT
    set_syserr(EL2HLT, "EL2HLT");
#endif
#ifdef EBADE
    set_syserr(EBADE, "EBADE");
#endif
#ifdef EBADR
    set_syserr(EBADR, "EBADR");
#endif
#ifdef EXFULL
    set_syserr(EXFULL, "EXFULL");
#endif
#ifdef ENOANO
    set_syserr(ENOANO, "ENOANO");
#endif
#ifdef EBADRQC
    set_syserr(EBADRQC, "EBADRQC");
#endif
#ifdef EBADSLT
    set_syserr(EBADSLT, "EBADSLT");
#endif
#ifdef EDEADLOCK
    set_syserr(EDEADLOCK, "EDEADLOCK");
#endif
#ifdef EBFONT
    set_syserr(EBFONT, "EBFONT");
#endif
#ifdef ENOSTR
    set_syserr(ENOSTR, "ENOSTR");
#endif
#ifdef ENODATA
    set_syserr(ENODATA, "ENODATA");
#endif
#ifdef ETIME
    set_syserr(ETIME, "ETIME");
#endif
#ifdef ENOSR
    set_syserr(ENOSR, "ENOSR");
#endif
#ifdef ENONET
    set_syserr(ENONET, "ENONET");
#endif
#ifdef ENOPKG
    set_syserr(ENOPKG, "ENOPKG");
#endif
#ifdef EREMOTE
    set_syserr(EREMOTE, "EREMOTE");
#endif
#ifdef ENOLINK
    set_syserr(ENOLINK, "ENOLINK");
#endif
#ifdef EADV
    set_syserr(EADV, "EADV");
#endif
#ifdef ESRMNT
    set_syserr(ESRMNT, "ESRMNT");
#endif
#ifdef ECOMM
    set_syserr(ECOMM, "ECOMM");
#endif
#ifdef EPROTO
    set_syserr(EPROTO, "EPROTO");
#endif
#ifdef EMULTIHOP
    set_syserr(EMULTIHOP, "EMULTIHOP");
#endif
#ifdef EDOTDOT
    set_syserr(EDOTDOT, "EDOTDOT");
#endif
#ifdef EBADMSG
    set_syserr(EBADMSG, "EBADMSG");
#endif
#ifdef EOVERFLOW
    set_syserr(EOVERFLOW, "EOVERFLOW");
#endif
#ifdef ENOTUNIQ
    set_syserr(ENOTUNIQ, "ENOTUNIQ");
#endif
#ifdef EBADFD
    set_syserr(EBADFD, "EBADFD");
#endif
#ifdef EREMCHG
    set_syserr(EREMCHG, "EREMCHG");
#endif
#ifdef ELIBACC
    set_syserr(ELIBACC, "ELIBACC");
#endif
#ifdef ELIBBAD
    set_syserr(ELIBBAD, "ELIBBAD");
#endif
#ifdef ELIBSCN
    set_syserr(ELIBSCN, "ELIBSCN");
#endif
#ifdef ELIBMAX
    set_syserr(ELIBMAX, "ELIBMAX");
#endif
#ifdef ELIBEXEC
    set_syserr(ELIBEXEC, "ELIBEXEC");
#endif
#ifdef EILSEQ
    set_syserr(EILSEQ, "EILSEQ");
#endif
#ifdef ERESTART
    set_syserr(ERESTART, "ERESTART");
#endif
#ifdef ESTRPIPE
    set_syserr(ESTRPIPE, "ESTRPIPE");
#endif
#ifdef EUSERS
    set_syserr(EUSERS, "EUSERS");
#endif
#ifdef ENOTSOCK
    set_syserr(ENOTSOCK, "ENOTSOCK");
#endif
#ifdef EDESTADDRREQ
    set_syserr(EDESTADDRREQ, "EDESTADDRREQ");
#endif
#ifdef EMSGSIZE
    set_syserr(EMSGSIZE, "EMSGSIZE");
#endif
#ifdef EPROTOTYPE
    set_syserr(EPROTOTYPE, "EPROTOTYPE");
#endif
#ifdef ENOPROTOOPT
    set_syserr(ENOPROTOOPT, "ENOPROTOOPT");
#endif
#ifdef EPROTONOSUPPORT
    set_syserr(EPROTONOSUPPORT, "EPROTONOSUPPORT");
#endif
#ifdef ESOCKTNOSUPPORT
    set_syserr(ESOCKTNOSUPPORT, "ESOCKTNOSUPPORT");
#endif
#ifdef EOPNOTSUPP
    set_syserr(EOPNOTSUPP, "EOPNOTSUPP");
#endif
#ifdef EPFNOSUPPORT
    set_syserr(EPFNOSUPPORT, "EPFNOSUPPORT");
#endif
#ifdef EAFNOSUPPORT
    set_syserr(EAFNOSUPPORT, "EAFNOSUPPORT");
#endif
#ifdef EADDRINUSE
    set_syserr(EADDRINUSE, "EADDRINUSE");
#endif
#ifdef EADDRNOTAVAIL
    set_syserr(EADDRNOTAVAIL, "EADDRNOTAVAIL");
#endif
#ifdef ENETDOWN
    set_syserr(ENETDOWN, "ENETDOWN");
#endif
#ifdef ENETUNREACH
    set_syserr(ENETUNREACH, "ENETUNREACH");
#endif
#ifdef ENETRESET
    set_syserr(ENETRESET, "ENETRESET");
#endif
#ifdef ECONNABORTED
    set_syserr(ECONNABORTED, "ECONNABORTED");
#endif
#ifdef ECONNRESET
    set_syserr(ECONNRESET, "ECONNRESET");
#endif
#ifdef ENOBUFS
    set_syserr(ENOBUFS, "ENOBUFS");
#endif
#ifdef EISCONN
    set_syserr(EISCONN, "EISCONN");
#endif
#ifdef ENOTCONN
    set_syserr(ENOTCONN, "ENOTCONN");
#endif
#ifdef ESHUTDOWN
    set_syserr(ESHUTDOWN, "ESHUTDOWN");
#endif
#ifdef ETOOMANYREFS
    set_syserr(ETOOMANYREFS, "ETOOMANYREFS");
#endif
#ifdef ETIMEDOUT
    set_syserr(ETIMEDOUT, "ETIMEDOUT");
#endif
#ifdef ECONNREFUSED
    set_syserr(ECONNREFUSED, "ECONNREFUSED");
#endif
#ifdef EHOSTDOWN
    set_syserr(EHOSTDOWN, "EHOSTDOWN");
#endif
#ifdef EHOSTUNREACH
    set_syserr(EHOSTUNREACH, "EHOSTUNREACH");
#endif
#ifdef EALREADY
    set_syserr(EALREADY, "EALREADY");
#endif
#ifdef EINPROGRESS
    set_syserr(EINPROGRESS, "EINPROGRESS");
#endif
#ifdef ESTALE
    set_syserr(ESTALE, "ESTALE");
#endif
#ifdef EUCLEAN
    set_syserr(EUCLEAN, "EUCLEAN");
#endif
#ifdef ENOTNAM
    set_syserr(ENOTNAM, "ENOTNAM");
#endif
#ifdef ENAVAIL
    set_syserr(ENAVAIL, "ENAVAIL");
#endif
#ifdef EISNAM
    set_syserr(EISNAM, "EISNAM");
#endif
#ifdef EREMOTEIO
    set_syserr(EREMOTEIO, "EREMOTEIO");
#endif
#ifdef EDQUOT
    set_syserr(EDQUOT, "EDQUOT");
#endif

}
예제 #23
0
파일: bootstrap.c 프로젝트: kwatch/rubinius
/* Creates the rubinius object universe from scratch. */
void cpu_bootstrap(STATE) {
  OBJECT cls, obj, tmp, tmp2;
  int i;

  /* Class is created first by hand, and twittle to setup the internal
     recursion. */
  cls = NEW_OBJECT(Qnil, CLASS_FIELDS);
  cls->klass = cls;
  class_set_instance_fields(cls, I2N(CLASS_FIELDS));
  class_set_has_ivars(cls, Qtrue);
  class_set_object_type(cls, I2N(ClassType));
  cls->obj_type = ClassType;
  
  BC(class) = cls;
  obj = _object_basic_class(state, Qnil);
  BC(object) = obj;
  BC(module) = _module_basic_class(state, obj);
  class_set_superclass(cls, BC(module));
  BC(metaclass) = _metaclass_basic_class(state, cls);
  class_set_object_type(BC(metaclass), I2N(MetaclassType));
  
  BC(tuple) = _tuple_basic_class(state, obj);
  BC(hash) =  _hash_basic_class(state, obj);
  BC(lookuptable) = _lookuptable_basic_class(state, obj);
  BC(methtbl) = _methtbl_basic_class(state, BC(lookuptable));
  
  object_create_metaclass(state, obj, cls);
  object_create_metaclass(state, BC(module), object_metaclass(state, obj));
  object_create_metaclass(state, BC(class), object_metaclass(state, BC(module)));
  
  object_create_metaclass(state, BC(tuple), (OBJECT)0);
  object_create_metaclass(state, BC(hash), (OBJECT)0);
  object_create_metaclass(state, BC(lookuptable), (OBJECT)0);
  object_create_metaclass(state, BC(methtbl), (OBJECT)0);
  
  module_setup_fields(state, object_metaclass(state, obj));
  module_setup_fields(state, object_metaclass(state, BC(module)));
  module_setup_fields(state, object_metaclass(state, BC(class)));
  module_setup_fields(state, object_metaclass(state, BC(tuple)));
  module_setup_fields(state, object_metaclass(state, BC(hash)));
  module_setup_fields(state, object_metaclass(state, BC(lookuptable)));
  module_setup_fields(state, object_metaclass(state, BC(methtbl)));
  BC(symbol) = _symbol_class(state, obj);
  BC(array) = _array_class(state, obj);
  BC(bytearray) = _bytearray_class(state, obj);
  BC(string) = _string_class(state, obj);
  BC(symtbl) = _symtbl_class(state, obj);
  BC(cmethod) = _cmethod_class(state, obj);
  BC(io) = _io_class(state, obj);
  BC(blokenv) = _blokenv_class(state, obj);
  BC(icache) = _icache_class(state, obj);
  BC(staticscope) = _staticscope_class(state, obj);
 
  class_set_object_type(BC(bytearray), I2N(ByteArrayType));
  class_set_object_type(BC(string), I2N(StringType));
  class_set_object_type(BC(methtbl), I2N(MTType));
  class_set_object_type(BC(tuple), I2N(TupleType));
  class_set_object_type(BC(hash), I2N(HashType));
  class_set_object_type(BC(lookuptable), I2N(LookupTableType));
  
  /* The symbol table */
  state->global->symbols = symtbl_new(state);
  
  module_setup(state, obj, "Object");
  module_setup(state, cls, "Class");
  module_setup(state, BC(module), "Module");
  module_setup(state, BC(metaclass), "MetaClass");
  module_setup(state, BC(symbol), "Symbol");
  module_setup(state, BC(tuple), "Tuple");
  module_setup(state, BC(array), "Array");
  module_setup(state, BC(bytearray), "ByteArray");
  module_setup(state, BC(hash), "Hash");
  module_setup(state, BC(lookuptable), "LookupTable");
  module_setup(state, BC(string), "String");
  module_setup(state, BC(symtbl), "SymbolTable");
  module_setup(state, BC(methtbl), "MethodTable");
  module_setup(state, BC(cmethod), "CompiledMethod");
  module_setup(state, BC(io), "IO");
  module_setup(state, BC(blokenv), "BlockEnvironment");
  module_setup(state, BC(icache), "InlineCache");
  module_setup(state, BC(staticscope), "StaticScope");
 
  class_set_object_type(BC(array), I2N(ArrayType));
  class_set_object_type(BC(cmethod), I2N(CMethodType));
  class_set_object_type(BC(blokenv), I2N(BlockEnvType));
    
  rbs_const_set(state, obj, "Symbols", state->global->symbols);
  BC(nil_class) = rbs_class_new(state, "NilClass", 0, obj);
  BC(true_class) = rbs_class_new(state, "TrueClass", 0, obj);
  BC(false_class) = rbs_class_new(state, "FalseClass", 0, obj);
  tmp = rbs_class_new(state, "Numeric", 0, obj);
  tmp2 = rbs_class_new(state, "Integer", 0, tmp);
  BC(fixnum_class) = rbs_class_new(state, "Fixnum", 0, tmp2);
  class_set_object_type(BC(fixnum_class), I2N(FixnumType));
  
  BC(bignum) = rbs_class_new(state, "Bignum", 0, tmp2);
  class_set_object_type(BC(bignum), I2N(BignumType));
  bignum_init(state);
  
  BC(floatpoint) = rbs_class_new(state, "Float", 0, tmp);
  class_set_object_type(BC(floatpoint), I2N(FloatType));
  
  BC(undef_class) = rbs_class_new(state, "UndefClass", 0, obj);
  BC(fastctx) = rbs_class_new(state, "MethodContext", 0, obj);
  BC(methctx) = BC(fastctx);
  BC(blokctx) = rbs_class_new(state, "BlockContext", 0, BC(fastctx));
  
  BC(task) = rbs_class_new(state, "Task", 0, obj);
  class_set_object_type(BC(task), I2N(TaskType));
  
  BC(iseq) = rbs_class_new(state, "InstructionSequence", 0, BC(bytearray));
  class_set_object_type(BC(iseq), I2N(ISeqType));

  #define bcs(name, sup, string) BC(name) = _ ## name ## _class(state, sup); \
    module_setup(state, BC(name), string);
  
  /* the special_classes C array is use do quickly calculate the class
     of an immediate by just indexing into the array using (obj & 0x1f) */
  
  /* fixnum, symbol, and custom can have a number of patterns below
     0x1f, so we fill them all. */
     
  for(i = 0; i < SPECIAL_CLASS_SIZE; i += 4) {
    state->global->special_classes[i + 0] = Qnil;
    state->global->special_classes[i + 1] = BC(fixnum_class);
    state->global->special_classes[i + 2] = Qnil;
    if(((i + 3) & 0x7) == 0x3) {
      state->global->special_classes[i + 3] = BC(symbol);
    } else {
      state->global->special_classes[i + 3] = CUSTOM_CLASS;
    }
  }
  
  /* These only have one value, so they only need one spot in
     the array */
  state->global->special_classes[(intptr_t)Qundef] = BC(undef_class);
  state->global->special_classes[(intptr_t)Qfalse] = BC(false_class);
  state->global->special_classes[(intptr_t)Qnil  ] = BC(nil_class);
  state->global->special_classes[(intptr_t)Qtrue ] = BC(true_class);
    
  bcs(regexp, obj, "Regexp");
  class_set_object_type(BC(regexp), I2N(RegexpType));
  bcs(regexpdata, obj, "RegexpData");
  class_set_object_type(BC(regexpdata), I2N(RegexpDataType));
  bcs(matchdata, obj, "MatchData");
      
  cpu_bootstrap_exceptions(state);
  
  rbs_module_new(state, "Rubinius", BC(object));
  
  Init_list(state);
  Init_cpu_task(state);
  Init_ffi(state);
  regexp_init(state);
  selector_init(state);
  send_site_init(state);
    
  rbs_const_set(state, 
        rbs_const_get(state, BASIC_CLASS(object), "Rubinius"),
        "Primitives",
        cpu_populate_prim_names(state));
  
  state->global->external_ivars = lookuptable_new(state);

}
예제 #24
0
double Math::Triangle::distance(const Point2D& p, Point2D* closestPoint)
{
    //Source is: http://wonderfl.net/c/b27F

    Vector2D AB(_b.x - _a.x, _b.y - _a.y);
    Vector2D AP(p.x - _a.x, p.y - _a.y);
    double ABXAP = (AB.x * AP.y) - (AB.y * AP.x);

    Vector2D BC(_c.x - _b.x, _c.y - _b.y);
    Vector2D BP(p.x - _b.x, p.y - _b.y);
    double BCXBP = (BC.x * BP.y) - (BC.y * BP.x);

    Vector2D CA(_a.x - _c.x, _a.y - _c.y);
    Vector2D CP(p.x - _c.x, p.y - _c.y);
    double CAXCP = (CA.x * CP.y) - (CA.y * CP.x);

    double distance = 0;

    //+++ //inside
    if (ABXAP >= 0 && BCXBP >= 0 && CAXCP >=0)
    {
        if(closestPoint) {
            closestPoint->x = p.x;
            closestPoint->y = p.y;
        }
    }
    //-+- //vertex
    else if (ABXAP < 0 && BCXBP >= 0 && CAXCP < 0)
    {
        distance = AP.x * AP.x + AP.y * AP.y;
        if(closestPoint) {
            closestPoint->x = _a.x;
            closestPoint->y = _a.y;
        }
    }
    //--+ //vertex
    else if (ABXAP < 0 && BCXBP < 0 && CAXCP >= 0)
    {
        distance = BP.x * BP.x + BP.y * BP.y;
        if(closestPoint) {
            closestPoint->x = _b.x;
            closestPoint->y = _b.y;
        }
    }
    //+-- //vertex
    else if (ABXAP >= 0 && BCXBP < 0 && CAXCP < 0)
    {
        distance = CP.x * CP.x + CP.y * CP.y;
        if(closestPoint) {
            closestPoint->x = _c.x;
            closestPoint->y = _c.y;
        }
    }
    //-++ //edge
    else if (ABXAP < 0 && BCXBP >= 0 && CAXCP >= 0)
    {
        double wd = ((AB.x * AP.x) + (AB.y * AP.y) ) / ((AB.x * AB.x) + (AB.y * AB.y));
        if (wd < 0) {
            wd = 0;
        }
        if (wd > 1) {
            wd = 1;
        }
        Point2D r;
        r.x = _a.x + (_b.x - _a.x) * wd;
        r.y = _a.y + (_b.y - _a.y) * wd;

        if (closestPoint) {
            closestPoint->x = r.x;
            closestPoint->y = r.y;
        }
        r.x = p.x - r.x;
        r.y = p.y - r.y;
        distance = r.x * r.x + r.y * r.y;
    }
    //+-+ //edge
    else if (ABXAP >= 0 && BCXBP < 0 && CAXCP >= 0)
    {
        double wd = ((BC.x * BP.x) + (BC.y * BP.y) ) / ((BC.x * BC.x) + (BC.y * BC.y));
        if (wd < 0) {
            wd = 0;
        }
        if (wd > 1) {
            wd = 1;
        }
        Point2D r;
        r.x = _b.x + (_c.x - _b.x) * wd;
        r.y = _b.y + (_c.y - _b.y) * wd;

        if (closestPoint) {
            closestPoint->x = r.x;
            closestPoint->y = r.y;
        }
        r.x = p.x - r.x;
        r.y = p.y - r.y;
        distance = r.x * r.x + r.y * r.y;
    }
    //++- //edge
    else if (ABXAP >= 0 && BCXBP >= 0 && CAXCP < 0)
    {
        double wd = ((CA.x * CP.x) + (CA.y * CP.y) ) / ((CA.x * CA.x) + (CA.y * CA.y));
        if (wd < 0) {
            wd = 0;
        }
        if (wd > 1) {
            wd = 1;
        }
        Point2D r;
        r.x = _c.x + (_a.x - _c.x) * wd;
        r.y = _c.y + (_a.y - _c.y) * wd;

        if (closestPoint) {
            closestPoint->x = r.x;
            closestPoint->y = r.y;
        }
        r.x = p.x - r.x;
        r.y = p.y - r.y;
        distance = r.x * r.x + r.y * r.y;
    }

    return distance;
}
예제 #25
0
void CollisionOutline_Impl::optimize(unsigned char check_distance, float corner_angle)
{
	unsigned char orig_check_distance = check_distance;

	std::vector<Contour>::iterator it;
	for( it = contours.begin(); it != contours.end(); ++it )
	{
		check_distance = orig_check_distance;

		std::vector<Pointf> &points = (*it).get_points();

		if( points.empty() ) continue;

		std::vector<Pointf> optimized;

		optimized.push_back(points.front());

		if( static_cast<int>(points.size()) < check_distance )
			check_distance = 1;

		for( unsigned int i=0; i < points.size()-check_distance; ++i )
		{
			int A_index = i-check_distance;
			int B_index = i+check_distance;

			if( A_index < 0 )
			{
				if( points.front() == points.back() )
					A_index += points.size();
				else
					A_index = 0;
			}
			if( B_index > (int)points.size() )
			{
				if( points.front() == points.back() )
					B_index -= points.size();
				else
					B_index = (int)points.size();
			}

			Pointf &A = optimized.back();
			Pointf &B = points[i];
			Pointf &C = points[B_index];

			Vec4f AB(B.x-A.x, B.y-A.y, 0, 0);	// TODO: Does this need to be Vec4f ?
			Vec4f BC(C.x-B.x, C.y-B.y, 0, 0);

			if( check_distance != 1 && AB.length3() < 2 )
				continue;

			float angle = AB.angle3(BC).to_radians(); // If things stopped working, it's because this should be degrees, not radians. Added when introducing Angle. -- HS 12.12.2008
			
			if( angle > corner_angle )
			{
				optimized.push_back(points[i]);
			}
		}

		points = optimized;
	}
}
예제 #26
0
Module::ReturnType SubgraphUpwardPlanarizer::doCall(UpwardPlanRep &UPR,
		const EdgeArray<int>  &cost,
		const EdgeArray<bool> &forbid)
{
	const Graph &G = UPR.original();
	GraphCopy GC(G);

	//reverse some edges in order to obtain a DAG
	List<edge> feedBackArcSet;
	m_acyclicMod.get().call(GC, feedBackArcSet);
	for(edge e : feedBackArcSet) {
		GC.reverseEdge(e);
	}

	OGDF_ASSERT(isSimple(G));

	//mapping cost
	EdgeArray<int> cost_GC(GC);
	for(edge e : GC.edges) {
		if (forbid[GC.original(e)])
			cost_GC[e] = numeric_limits<int>::max();
		else
			cost_GC[e] = cost[GC.original(e)];
	}

	// tranform to single source graph by adding a super source s_hat and connect it with the other sources
	EdgeArray<bool> sourceArcs(GC, false);
	node s_hat = GC.newNode();
	for(node v : GC.nodes) {
		if (v->indeg() == 0 && v != s_hat) {
			edge e_tmp = GC.newEdge(s_hat, v);
			cost_GC[e_tmp] = 0; // crossings source arcs cause not cost
			sourceArcs[e_tmp] = true;
		}
	}


	/*
	//------------------------------------------------debug
	GraphAttributes AG_GC(GC, GraphAttributes::nodeGraphics|
						GraphAttributes::edgeGraphics|
						GraphAttributes::nodeColor|
						GraphAttributes::edgeColor|
						GraphAttributes::nodeLabel|
						GraphAttributes::edgeLabel
						);
	AG_GC.setAllHeight(30.0);
	AG_GC.setAllWidth(30.0);
	for(node z : AG_GC.constGraph().nodes) {
		AG_GC.label(z) = to_string(z->index());
	}
	AG_GC.writeGML("c:/temp/GC.gml");
	// --------------------------------------------end debug
	*/

	BCTree BC(GC);
	const Graph &bcTree = BC.bcTree();

	GraphCopy G_dummy;
	G_dummy.createEmpty(G);
	NodeArray<GraphCopy> biComps(bcTree, G_dummy); // bicomps of G; init with an empty graph
	UpwardPlanRep UPR_dummy;
	UPR_dummy.createEmpty(G);
	NodeArray<UpwardPlanRep> uprs(bcTree, UPR_dummy); // the upward planarized representation of the bicomps; init with an empty UpwarPlanRep

	constructComponentGraphs(BC, biComps);

	for(node v : bcTree.nodes) {

		if (BC.typeOfBNode(v) == BCTree::CComp)
			continue;

		GraphCopy &block = biComps[v];

		OGDF_ASSERT(m_subgraph.valid());

		// construct a super source for this block
		node s, s_block;
		hasSingleSource(block, s);
		s_block = block.newNode();
		block.newEdge(s_block, s); //connect s

		UpwardPlanRep bestUPR;

		//upward planarize if not upward planar
		if (!UpwardPlanarity::upwardPlanarEmbed_singleSource(block)) {

			for (int i = 0; i < m_runs; i++) {// i multistarts
				UpwardPlanRep UPR_tmp;
				UPR_tmp.createEmpty(block);
				List<edge> delEdges;

				m_subgraph.get().call(UPR_tmp, delEdges);

				OGDF_ASSERT( isSimple(UPR_tmp) );
				UPR_tmp.augment();

				//mark the source arcs of block
				UPR_tmp.m_isSourceArc[UPR_tmp.copy(s_block->firstAdj()->theEdge())] = true;
				for (adjEntry adj_tmp : UPR_tmp.copy(s_block->firstAdj()->theEdge()->target())->adjEntries) {
					edge e_tmp = UPR_tmp.original(adj_tmp->theEdge());
					if (e_tmp != nullptr && block.original(e_tmp) != nullptr && sourceArcs[block.original(e_tmp)])
						UPR_tmp.m_isSourceArc[adj_tmp->theEdge()] = true;
				}

				//assign "crossing cost"
				EdgeArray<int> cost_Block(block);
				for (edge e : block.edges) {
					if (block.original(e) == nullptr || GC.original(block.original(e)) == nullptr)
						cost_Block[e] = 0;
					else
						cost_Block[e] = cost_GC[block.original(e)];
				}

				/*
				if (false) {
					//---------------------------------------------------debug
					LayerBasedUPRLayout uprLayout;
					UpwardPlanRep upr_bug(UPR_tmp.getEmbedding());
					adjEntry adj_bug = upr_bug.getAdjEntry(upr_bug.getEmbedding(), upr_bug.getSuperSource(), upr_bug.getEmbedding().externalFace());
					node s_upr_bug = upr_bug.newNode();
					upr_bug.getEmbedding().splitFace(s_upr_bug, adj_bug);
					upr_bug.m_isSourceArc.init(upr_bug, false);
					upr_bug.m_isSourceArc[s_upr_bug->firstAdj()->theEdge()] = true;
					upr_bug.s_hat = s_upr_bug;
					upr_bug.augment();

					GraphAttributes GA_UPR_tmp(UPR_tmp, GraphAttributes::nodeGraphics|
							GraphAttributes::edgeGraphics|
							GraphAttributes::nodeColor|
							GraphAttributes::edgeColor|
							GraphAttributes::nodeLabel|
							GraphAttributes::edgeLabel
							);
					GA_UPR_tmp.setAllHeight(30.0);
					GA_UPR_tmp.setAllWidth(30.0);

					uprLayout.call(upr_bug, GA_UPR_tmp);

					// label the nodes with their index
					for(node z : GA_UPR_tmp.constGraph().nodes) {
						GA_UPR_tmp.label(z) = to_string(z->index());
						GA_UPR_tmp.y(z)=-GA_UPR_tmp.y(z);
						GA_UPR_tmp.x(z)=-GA_UPR_tmp.x(z);
					}
					for(edge eee : GA_UPR_tmp.constGraph().edges) {
						DPolyline &line = GA_UPR_tmp.bends(eee);
						ListIterator<DPoint> it;
						for(it = line.begin(); it.valid(); it++) {
							(*it).m_y = -(*it).m_y;
							(*it).m_x = -(*it).m_x;
						}
					}
					GA_UPR_tmp.writeGML("c:/temp/UPR_tmp_fups.gml");
					cout << "UPR_tmp/fups faces:";
					UPR_tmp.outputFaces(UPR_tmp.getEmbedding());
					//end -----------------------------------------------debug
				}
				*/

				delEdges.permute();
				m_inserter.get().call(UPR_tmp, cost_Block, delEdges);

				if (i != 0) {
					if (UPR_tmp.numberOfCrossings() < bestUPR.numberOfCrossings()) {
						//cout << endl << "new cr_nr:" << UPR_tmp.numberOfCrossings() << " old  cr_nr : " << bestUPR.numberOfCrossings() << endl;
						bestUPR = UPR_tmp;
					}
				}
				else
					bestUPR = UPR_tmp;
			}//for
		}
		else { //block is upward planar
			CombinatorialEmbedding Gamma(block);
			FaceSinkGraph fsg((const CombinatorialEmbedding &) Gamma, s_block);
			SList<face> faceList;
			fsg.possibleExternalFaces(faceList);
			Gamma.setExternalFace(faceList.front());

			UpwardPlanRep UPR_tmp(Gamma);
			UPR_tmp.augment();

			//mark the source arcs of  block
			UPR_tmp.m_isSourceArc[UPR_tmp.copy(s->firstAdj()->theEdge())] = true;
			for (adjEntry adj_tmp : UPR_tmp.copy(s->firstAdj()->theEdge()->target())->adjEntries) {
				edge e_tmp = UPR_tmp.original(adj_tmp->theEdge());
				if (e_tmp != nullptr && block.original(e_tmp) != nullptr && sourceArcs[block.original(e_tmp)])
					UPR_tmp.m_isSourceArc[adj_tmp->theEdge()] = true;
			}

			bestUPR = UPR_tmp;

			/*
			//debug
			//---------------------------------------------------debug
			GraphAttributes GA_UPR_tmp(UPR_tmp, GraphAttributes::nodeGraphics|
					GraphAttributes::edgeGraphics|
					GraphAttributes::nodeColor|
					GraphAttributes::edgeColor|
					GraphAttributes::nodeLabel|
					GraphAttributes::edgeLabel
					);
			GA_UPR_tmp.setAllHeight(30.0);
			GA_UPR_tmp.setAllWidth(30.0);

			// label the nodes with their index
			for(node z : GA_UPR_tmp.constGraph().nodes) {
				GA_UPR_tmp.label(z) = to_string(z->index());
				GA_UPR_tmp.y(z)=-GA_UPR_tmp.y(z);
				GA_UPR_tmp.x(z)=-GA_UPR_tmp.x(z);
			}
			for(edge eee : GA_UPR_tmp.constGraph().edges) {
				DPolyline &line = GA_UPR_tmp.bends(eee);
				ListIterator<DPoint> it;
				for(it = line.begin(); it.valid(); it++) {
					(*it).m_y = -(*it).m_y;
					(*it).m_x = -(*it).m_x;
				}
			}
			GA_UPR_tmp.writeGML("c:/temp/UPR_tmp_fups.gml");
			cout << "UPR_tmp/fups faces:";
			UPR_tmp.outputFaces(UPR_tmp.getEmbedding());
			//end -----------------------------------------------debug
			*/

		}
		uprs[v] = bestUPR;
	}

	// compute the number of crossings
	int nr_cr = 0;
	for(node v : bcTree.nodes) {
		if (BC.typeOfBNode(v) != BCTree::CComp)
			nr_cr = nr_cr + uprs[v].numberOfCrossings();
	}

	//merge all component to a graph
	node parent_BC = BC.bcproper(s_hat);
	NodeArray<bool> nodesDone(bcTree, false);
	dfsMerge(GC, BC, biComps, uprs, UPR, nullptr, parent_BC, nodesDone); // start with the component which contains the super source s_hat

	//augment to single sink graph
	UPR.augment();

	//set crossings
	UPR.crossings = nr_cr;


	//------------------------------------------------debug
	/*
	LayerBasedUPRLayout uprLayout;
	UpwardPlanRep upr_bug(UPR.getEmbedding());
	adjEntry adj_bug = upr_bug.getAdjEntry(upr_bug.getEmbedding(), upr_bug.getSuperSource(), upr_bug.getEmbedding().externalFace());
	node s_upr_bug = upr_bug.newNode();
	upr_bug.getEmbedding().splitFace(s_upr_bug, adj_bug);
	upr_bug.m_isSourceArc.init(upr_bug, false);
	upr_bug.m_isSourceArc[s_upr_bug->firstAdj()->theEdge()] = true;
	upr_bug.s_hat = s_upr_bug;
	upr_bug.augment();
	GraphAttributes AG(UPR, GraphAttributes::nodeGraphics|
						GraphAttributes::edgeGraphics|
						GraphAttributes::nodeColor|
						GraphAttributes::edgeColor|
						GraphAttributes::nodeLabel|
						GraphAttributes::edgeLabel
						);
	AG.setAllHeight(30.0);
	AG.setAllWidth(30.0);

	uprLayout.call(upr_bug, AG);

	for(node v : AG.constGraph().nodes) {
		int idx;
		idx = v->index();


		if (UPR.original(v) != 0)
			idx = UPR.original(v)->index();


		AG.label(v) = to_string(idx);
		if (UPR.isDummy(v))
			AG.fillColor(v) = "#ff0000";
		AG.y(v)=-AG.y(v);
	}
	// label the edges with their index
	for(edge e : AG.constGraph().edges) {
		AG.label(e) = to_string(e->index());
		if (UPR.isSourceArc(e))
			AG.strokeColor(e) = "#00ff00";
		if (UPR.isSinkArc(e))
			AG.strokeColor(e) = "#ff0000";

		DPolyline &line = AG.bends(e);
		ListIterator<DPoint> it;
		for(it = line.begin(); it.valid(); it++) {
			(*it).m_y = -(*it).m_y;
		}
	}
	AG.writeGML("c:/temp/upr_res.gml");
	//cout << "UPR_RES";
	//UPR.outputFaces(UPR.getEmbedding());
	//cout << "Mapping :" << endl;
	//for(node v : UPR.nodes) {
	//	if (UPR.original(v) != 0) {
	//		cout << "node UPR  " << v << "   node G  " << UPR.original(v) << endl;
	//	}
	//}
	// --------------------------------------------end debug
	*/

	OGDF_ASSERT(hasSingleSource(UPR));
	OGDF_ASSERT(isSimple(UPR));
	OGDF_ASSERT(isAcyclic(UPR));
	OGDF_ASSERT(UpwardPlanarity::isUpwardPlanar_singleSource(UPR));

/*
	for(edge eee : UPR.original().edges) {
		if (UPR.isReversed(eee))
			cout << endl << eee << endl;
	}
*/
	return Module::retFeasible;
}
예제 #27
0
/**
  * Node betweenness centrality is the fraction of all shortest paths in
  * the network that contain a given node. Nodes with high values of
  * betweenness centrality participate in a large number of shortest paths.
  *
  *     Input:      G,      weighted (directed/undirected) connection matrix.
  *     Output:     BC,     node betweenness centrality vector.
  *                 EBC,    edge betweenness centrality matrix.
  *
  * Notes:
  *    The input matrix must be a mapping from weight to distance. For
  * instance, in a weighted correlation network, higher correlations are
  * more naturally interpreted as shorter distances, and the input matrix
  * should consequently be some inverse of the connectivity matrix.
  *    Betweenness centrality may be normalised to [0,1] via BC/[(N-1)(N-2)]
  *
  * Reference: Brandes (2001) J Math Sociol 25:163-177.
  */
rowvec Connectome::betweenessCentrality(const mat &G, mat &EBC)
{
    uint n = G.n_rows,q = n-1,v=0,w=0;
    double Duw,DPvw;
    vec t;
    rowvec BC = zeros(1,n),D,NP,DP;
    uvec S,Q,V,tt,W;
    mat G1;
    umat P;
    EBC = zeros<mat>(n,n);

    for (uint u = 0; u<n;++u) {
        D = rowvec(1,n).fill(datum::inf); D(u) = 0;
        NP = zeros(1,n); NP(u) = 1;
        S = linspace<uvec>(0,n-1,n);
        P = zeros<umat>(n,n);
        Q = zeros<uvec>(n);
        q = n-1;
        G1 = G;
        V = uvec(1).fill(u);
        while (true) {
            // instead of replacing indices by 0 like S(V)=0;
            // we declare all indices then remove the V indeces
            // from S. Notice that it is assured that tt should
            // be one element since indices don't repeat
            for (int i=0;i<V.n_elem;++i) {
                tt = find(S == V(i),1);
                if (!tt.is_empty())
                    S.shed_row(tt(0));
            }
            G1.cols(V).fill(0);
            for (uint i=0; i<V.n_elem;++i) {
                v = V(i);
                Q(q) = v; --q;
                W = find( G1.row(v) != 0);
                for (uint j = 0;j<W.n_elem;++j) {
                    w = W(j);
                    Duw = D(v)+G1(v,w);
                    if (Duw<D(w)) {
                        D(w) = Duw;
                        NP(w) = NP(v);
                        P.row(w).fill(0);
                        P(w,v) = 1;
                    }
                    else if (Duw == D(w)) {
                        NP(w) += NP(v);
                        P(w,v) = 1;
                    }
                }
            }

            if (S.is_empty())
                break;
            t = D(S);
            if ( !is_finite(t.min()) ){
                // the number of inf elements is assumed to be always = q
                Q.subvec(0,q) = find(D == datum::inf);
                break;
            }
            V = find(D == t.min());
        }
        DP = zeros(1,n);
        for (uint i=0; i<Q.n_elem-1;++i) {
            w = Q(i);
            BC(w) += DP(w);
            tt = find(P.row(w) != 0);
            for (uint j=0; j<tt.n_elem;++j) {
                v = tt(j);
                DPvw = (1+DP(w))*NP(v)/NP(w);
                DP(v) += DPvw;
                EBC(v,w) += DPvw;
            }
        }
    }
    return BC;
}
예제 #28
0
bool UnitTests::SharedSeqs()
{
	std::vector< std::vector<double> > dissMatrix;

	// unweighted MRCA (= MRCA restricted Soergel)
	DiversityCalculator uMRCA("../unit-tests/SharedSeqs.env", "../unit-tests/SharedSeqs.tre", "Soergel", 1000, false, false, true, false, false);
	uMRCA.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 8.0/13.0))
		return false;
	if(!Compare(dissMatrix[2][0], 8.0/13.0))
		return false;
	if(!Compare(dissMatrix[2][1], 2.0/6.0))
		return false;

	// unweighted Tamas coefficient
	DiversityCalculator uTC("../unit-tests/SharedSeqs.env", "../unit-tests/SharedSeqs.tre", "Tamas coefficient", 1000, false, false, false, false, false);
	uTC.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 8.0/13.0))
		return false;
	if(!Compare(dissMatrix[2][0], 8.0/13.0))
		return false;
	if(!Compare(dissMatrix[2][1], 2.0/13.0))
		return false;

	// unweighted Soergel
	DiversityCalculator uSoergel("../unit-tests/SharedSeqs.env", "../unit-tests/SharedSeqs.tre", "Soergel", 1000, false, false, false, false, false);
	uSoergel.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 8.0/13.0))
		return false;
	if(!Compare(dissMatrix[2][0], 8.0/13.0))
		return false;
	if(!Compare(dissMatrix[2][1], 2.0/9.0))
		return false;

	// unweighted Canberra
	DiversityCalculator uCanberra("../unit-tests/SharedSeqs.env", "../unit-tests/SharedSeqs.tre", "Canberra", 1000, false, false, false, false, false);
	uCanberra.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 8.0))
		return false;
	if(!Compare(dissMatrix[2][0], 8.0))
		return false;
	if(!Compare(dissMatrix[2][1], 2.0))
		return false;

	// weighted Soergel
	DiversityCalculator Soergel("../unit-tests/SharedSeqs.env", "../unit-tests/SharedSeqs.tre", "Soergel", 1000, true, false, false, false, false);
	Soergel.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.55))
		return false;
	if(!Compare(dissMatrix[2][0], 0.615385))
		return false;
	if(!Compare(dissMatrix[2][1], 0.16981))
		return false;

	// weighted Bray-Curtis
	DiversityCalculator BC("../unit-tests/SharedSeqs.env", "../unit-tests/SharedSeqs.tre", "Bray-Curtis", 1000, true, false, false, false, false);
	BC.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.37931000))
		return false;
	if(!Compare(dissMatrix[2][0], 0.444440))
		return false;
	if(!Compare(dissMatrix[2][1], 0.092783500))
		return false;

	// weighted Fst
	DiversityCalculator Fst("../unit-tests/SharedSeqs.env", "../unit-tests/SharedSeqs.tre", "Fst", 1000, true, false, false, false, false);
	Fst.Dissimilarity("../unit-tests/temp", "UPGMA");
	
	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.139560))
		return false;
	if(!Compare(dissMatrix[2][0], 0.18378390))
		return false;
	if(!Compare(dissMatrix[2][1], 0.043478190))
		return false;

	return true;
}
예제 #29
0
파일: gsubr.c 프로젝트: teyc/guile
     (while (<= i n)
       (generate-bytecode i)
       (setq i (1+ i)))))
*/
static const scm_t_uint32 subr_stub_code[] = {
  /* C-u 1 0 M-x generate-bytecodes RET */
  /* 0 arguments */
  A(0),

  /* 1 arguments */
  A(1), B(1),
  C(),

  /* 2 arguments */
  A(2), AB(1,1), B(2),
  AC(1), BC(1),

  /* 3 arguments */
  A(3), AB(2,1), AB(1,2), B(3),
  AC(2), ABC(1,1), BC(2),

  /* 4 arguments */
  A(4), AB(3,1), AB(2,2), AB(1,3), B(4),
  AC(3), ABC(2,1), ABC(1,2), BC(3),

  /* 5 arguments */
  A(5), AB(4,1), AB(3,2), AB(2,3), AB(1,4), B(5),
  AC(4), ABC(3,1), ABC(2,2), ABC(1,3), BC(4),

  /* 6 arguments */
  A(6), AB(5,1), AB(4,2), AB(3,3), AB(2,4), AB(1,5), B(6),
예제 #30
0
bool UnitTests::WeightedDataMatrixMothur()
{
	std::vector< std::vector<double> > dissMatrix;

	// weighted Bray-Curtis
	DiversityCalculator BC("../unit-tests/DataMatrixMothur.env", "", "Bray-Curtis", 1000, true, false, false, false, false);
	BC.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.8))
		return false;
	if(!Compare(dissMatrix[2][0], 0.6))
		return false;
	if(!Compare(dissMatrix[2][1], 0.8))
		return false;

	// weighted Canberra
	DiversityCalculator Canberra("../unit-tests/DataMatrixMothur.env", "", "Canberra", 1000, true, false, false, false, false);
	Canberra.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 6.35152))
		return false;
	if(!Compare(dissMatrix[2][0], 8.11111))
		return false;
	if(!Compare(dissMatrix[2][1], 5.92063))
		return false;

	// weighted Gower
	DiversityCalculator Gower("../unit-tests/DataMatrixMothur.env", "", "Gower", 1000, true, false, false, false, false);
	Gower.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 6.58333))
		return false;
	if(!Compare(dissMatrix[2][0], 7.88889))
		return false;
	if(!Compare(dissMatrix[2][1], 5.52778))
		return false;

	// weighted Hellinger
	DiversityCalculator Hellinger("../unit-tests/DataMatrixMothur.env", "", "Hellinger", 1000, true, false, false, false, false);
	Hellinger.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 1.13904))
		return false;
	if(!Compare(dissMatrix[2][0], 1.05146))
		return false;
	if(!Compare(dissMatrix[2][1], 1.17079))
		return false;

	// weighted Manhattan
	DiversityCalculator Manhattan("../unit-tests/DataMatrixMothur.env", "", "Manhattan", 1000, true, false, false, false, false);
	Manhattan.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 1.6))
		return false;
	if(!Compare(dissMatrix[2][0], 1.2))
		return false;
	if(!Compare(dissMatrix[2][1], 1.6))
		return false;

	// weighted Morisita-Horn
	DiversityCalculator MH("../unit-tests/DataMatrixMothur.env", "", "Morisita-Horn", 1000, true, false, false, false, false);
	MH.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.873239))
		return false;
	if(!Compare(dissMatrix[2][0], 0.333333))
		return false;
	if(!Compare(dissMatrix[2][1], 0.859155))
		return false;

	// weighted Soergel
	DiversityCalculator Soergel("../unit-tests/DataMatrixMothur.env", "", "Soergel", 1000, true, false, false, false, false);
	Soergel.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.88888901))
		return false;
	if(!Compare(dissMatrix[2][0], 0.75))
		return false;
	if(!Compare(dissMatrix[2][1], 0.88888901))
		return false;

	// weighted species profile
	/*
	DiversityCalculator SP("../unit-tests/DataMatrixMothur.env", "", "Species profile", 1000, true, false, false, false, false);
	SP.Dissimilarity("../unit-tests/temp.diss");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.78740102))
		return false;
	if(!Compare(dissMatrix[2][0], 0.44721401))
		return false;
	if(!Compare(dissMatrix[2][1], 0.78102499))
		return false;
	*/

	// weighted Chi-squared
	// Note: EBD uses a slightly different form of the Chi-squared measure as suggested in Numerical Ecology by Legendre adn Legendre
	// Nonetheless, it is easy to verify this using mothur. Simply divide by sqrt(N), N is the total number of sequences.
	DiversityCalculator ChiSquared("../unit-tests/DataMatrixMothur.env", "", "Chi-squared", 1000, true, false, false, false, false);
	ChiSquared.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 1.0973200))
		return false;
	if(!Compare(dissMatrix[2][0], 0.96513098))
		return false;
	if(!Compare(dissMatrix[2][1], 1.1147900))
		return false;

	// weighted Euclidean
	DiversityCalculator Euclidean("../unit-tests/DataMatrixMothur.env", "", "Euclidean", 1000, true, false, false, false, false);
	Euclidean.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.78740102))
		return false;
	if(!Compare(dissMatrix[2][0], 0.44721401))
		return false;
	if(!Compare(dissMatrix[2][1], 0.78102499))
		return false;

	// weighted Kulczynski
	DiversityCalculator Kulczynski("../unit-tests/DataMatrixMothur.env", "", "Kulczynski", 1000, true, false, false, false, false);
	Kulczynski.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.8))
		return false;
	if(!Compare(dissMatrix[2][0], 0.6))
		return false;
	if(!Compare(dissMatrix[2][1], 0.8))
		return false;

	// weighted Pearson
	DiversityCalculator uPearson("../unit-tests/DataMatrixMothur.env", "", "Pearson", 1000, true, false, false, false, false);
	uPearson.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 1.22089))
		return false;
	if(!Compare(dissMatrix[2][0], 0.5))
		return false;
	if(!Compare(dissMatrix[2][1], 1.2008))
		return false;

	// weighted Yue-Clayton
	DiversityCalculator YC("../unit-tests/DataMatrixMothur.env", "", "YueClayton", 1000, true, false, false, false, false);
	YC.Dissimilarity("../unit-tests/temp", "UPGMA");

	ReadDissMatrix("../unit-tests/temp.diss", dissMatrix);
	if(!Compare(dissMatrix[1][0], 0.93233103))
		return false;
	if(!Compare(dissMatrix[2][0], 0.5))
		return false;
	if(!Compare(dissMatrix[2][1], 0.92424202))
		return false;

	return true;
}