Beispiel #1
0
int	main(int ac, char **av)
{
  if (ac < 2)
    {
      std::cout << "Usage : ./test_dynamic_fsa [Chaine a rechercher]" << std::endl;
      return 0;
    }

  Edge	e0('m');
  Edge	e1('e');
  Edge	e2('c');
  Edge	e3('h');
  Edge	e4('a');
  Edge	e5('n');
  Edge	e6('t');

  Fsa	fsa;

  State*	s0 = State::createUniqueState();
  State*	s1 = State::createUniqueState();
  State*	s2 = State::createUniqueState();
  State*	s3 = State::createUniqueState();
  State*	s4 = State::createUniqueState();
  State*	s5 = State::createUniqueState();
  State*	s6 = State::createUniqueState();
  State*	s7 = State::createUniqueState();
  State*	sf = State::createUniqueState();

  sf->endState(true);
  s7->endState(true);


  s0->addLink(&e0, "S1");
  s1->addLink(&e1, "S2");
  s2->addLink(&e2, "S3");
  s2->addLink(&e1, "S2");
  s3->addLink(&e3, "S4");
  s4->addLink(&e4, "S5");
  s5->addLink(&e5, "S6");
  s6->addLink(&e6, "S7");
  s6->addLink(&e5, "S6");
  
  std::cout << s0->name() << std::endl;
  std::cout << s1->name() << std::endl;
  std::cout << s2->name() << std::endl;
  std::cout << s3->name() << std::endl;
  std::cout << s4->name() << std::endl;
  std::cout << s5->name() << std::endl;
  std::cout << s6->name() << std::endl;
  std::cout << s7->name() << std::endl;
  std::cout << sf->name() << std::endl;
  

  fsa.addState(s0);
  fsa.addState(s1);
  fsa.addState(s2);
  fsa.addState(s3);
  fsa.addState(s4);
  fsa.addState(s5);
  fsa.addState(s6);
  fsa.addState(s7);
  fsa.addState(sf);

  fsa.initState("S0");


  Matcher	match(fsa);

  match.find(av[1]);

  std::string	st(av[1]);
  st += av[1];

  int	l;
  match.find(st, l);

  std::cout << "La seconde instance de find a matcher " << l << " fois" << std::endl;

  return 0;
}
void CBasicMapDamage::RecalcArea(int x1, int x2, int y1, int y2)
{
	for(int y=y1;y<y2;y++){
    for(int x=x1;x<x2;x++){
			float height=readmap->heightmap[(y)*(gs->mapx+1)+x];
			height+=readmap->heightmap[(y)*(gs->mapx+1)+x+1];
			height+=readmap->heightmap[(y+1)*(gs->mapx+1)+x];
			height+=readmap->heightmap[(y+1)*(gs->mapx+1)+x+1];
      readmap->centerheightmap[y*gs->mapx+x]=height*0.25;
    }
  }
	int hy2=min(gs->hmapy-1,y2/2);
	int hx2=min(gs->hmapx-1,x2/2);
	for(int y=y1/2;y<=hy2;y++){
    for(int x=x1/2;x<=hx2;x++){
			readmap->halfHeightmap[y*gs->hmapx+x]=readmap->heightmap[(y*2+1)*(gs->mapx+1)+(x*2+1)];
		}
	}

	float3 n1,n2,n3,n4;
	int decy=max(0,y1-1);
	int incy=min(gs->mapy-1,y2+1);
	int decx=max(0,x1-1);
	int incx=min(gs->mapx-1,x2+1);

	for(int y=decy;y<=incy;y++){
		for(int x=decx;x<=incx;x++){

			float3 e1(-SQUARE_SIZE,readmap->heightmap[y*(gs->mapx+1)+x]-readmap->heightmap[y*(gs->mapx+1)+x+1],0);
			float3 e2( 0,readmap->heightmap[y*(gs->mapx+1)+x]-readmap->heightmap[(y+1)*(gs->mapx+1)+x],-SQUARE_SIZE);
			
			float3 n=e2.cross(e1);
			n.Normalize();

      readmap->facenormals[(y*gs->mapx+x)*2]=n;

			e1=float3( SQUARE_SIZE,readmap->heightmap[(y+1)*(gs->mapx+1)+x+1]-readmap->heightmap[(y+1)*(gs->mapx+1)+x],0);
			e2=float3( 0,readmap->heightmap[(y+1)*(gs->mapx+1)+x+1]-readmap->heightmap[(y)*(gs->mapx+1)+x+1],SQUARE_SIZE);
			
			n=e2.cross(e1);
			n.Normalize();

      readmap->facenormals[(y*gs->mapx+x)*2+1]=n;
    }
  }

	for(int y=max(2,(y1&0xfffffe));y<=min(gs->mapy-3,y2);y+=2){
		for(int x=max(2,(x1&0xfffffe));x<=min(gs->mapx-3,x2);x+=2){
			float3 e1(-SQUARE_SIZE*4,readmap->heightmap[(y-1)*(gs->mapx+1)+x-1]-readmap->heightmap[(y-1)*(gs->mapx+1)+x+3],0);
			float3 e2( 0,readmap->heightmap[(y-1)*(gs->mapx+1)+x-1]-readmap->heightmap[(y+3)*(gs->mapx+1)+x-1],-SQUARE_SIZE*4);

			float3 n=e2.cross(e1);
			n.Normalize();

			e1=float3( SQUARE_SIZE*4,readmap->heightmap[(y+3)*(gs->mapx+1)+x+3]-readmap->heightmap[(y+3)*(gs->mapx+1)+x-1],0);
			e2=float3( 0,readmap->heightmap[(y+3)*(gs->mapx+1)+x+3]-readmap->heightmap[(y-1)*(gs->mapx+1)+x+3],SQUARE_SIZE*4);
			
			float3 n2=e2.cross(e1);
			n2.Normalize();

			readmap->slopemap[(y/2)*gs->hmapx+(x/2)]=1-(n.y+n2.y)*0.5;

    }
  }
	pathManager->TerrainChange(x1,y1,x2,y2);
	featureHandler->TerrainChanged(x1,y1,x2,y2);
	readmap->HeightmapUpdated(x1,x2,y1,y2);

	decy=max(0,(y1*SQUARE_SIZE-QUAD_SIZE/2)/QUAD_SIZE);
	incy=min(qf->numQuadsZ-1,(y2*SQUARE_SIZE+QUAD_SIZE/2)/QUAD_SIZE);
	decx=max(0,(x1*SQUARE_SIZE-QUAD_SIZE/2)/QUAD_SIZE);
	incx=min(qf->numQuadsX-1,(x2*SQUARE_SIZE+QUAD_SIZE/2)/QUAD_SIZE);

	for(int y=decy;y<=incy;y++){
		for(int x=decx;x<=incx;x++){
			if(inRelosQue[y*qf->numQuadsX+x])
				continue;
			RelosSquare rs;
			rs.x=x;
			rs.y=y;
			rs.neededUpdate=gs->frameNum;
			rs.numUnits=qf->baseQuads[y*qf->numQuadsX+x].units.size();
			relosSize+=rs.numUnits;
			inRelosQue[y*qf->numQuadsX+x]=true;
			relosQue.push_back(rs);
		}
	}
}
Beispiel #3
0
int main()
{
    {
        Eris::Entity * e = new TestErisEntity("1", 0);
        e->shutdown();
        delete e;
    }

    {
        //Test that positioning works correctly
        TestErisEntity e1("1", 0);
        TestErisEntity e2("2", 0);
        TestErisEntity e3("3", 0);
        TestErisEntity e4("4", 0);
        e2.testSetLocation(&e1);
        e2.testSetPosition(WFMath::Point<3>(1, 2, 3));
        e4.testSetPosition(WFMath::Point<3>(1, 0, 0));
        e4.testSetVelocity(WFMath::Vector<3>(1, 0, 0));
        //Rotate the e2 entity halfways around the z-axis, so that the e3 view position gets affected.
        e2.testSetOrientation(WFMath::Quaternion(WFMath::Vector<3>(0, 0, 1), WFMath::numeric_constants<WFMath::CoordType>::pi()));
        e3.testSetPosition(WFMath::Point<3>(3, 2, 1));
        e3.testSetLocation(&e2);


        //The root entity won't have any valid position. We still expect the getViewPosition to report correct results, treating the position of the root entity as (0,0,0).
        assert(!e1.getPosition().isValid());
        assert(e2.getPosition().isValid());

        assert(e2.getPredictedPos() == WFMath::Point<3>(1, 2, 3));
        //Note that e1 don't have any valid position set, so it's position when calling getViewPosition() should be interpreted as (0,0,0).
        assert(e2.getViewPosition() == WFMath::Point<3>(1, 2, 3));

        e1.testSetPosition(WFMath::Point<3>(10, 20, 30));

        //Test position inheritence
        assert(e2.getPredictedPos() == WFMath::Point<3>(1, 2, 3));
        assert(e2.getViewPosition() == WFMath::Point<3>(11, 22, 33));
        assert(e3.getViewPosition() == WFMath::Point<3>(8, 20, 34));

        assert(e4.getViewPosition() == WFMath::Point<3>(1, 0, 0));
        e4.testUpdatePositionWithDelta(WFMath::TimeDiff(1000));
        assert(e4.getViewPosition() == WFMath::Point<3>(2, 0, 0));

        //Check that the position is updated instantly when onMoved is called.
        WFMath::Point<3> newPos(10, 20, 30);
        e4.Moved.connect([&](){
            assert(e4.getPosition() == newPos);
            assert(e4.getViewPosition() == newPos);
            assert(e4.getPredictedPos() == newPos);
        });
        e4.testSetPosition(newPos);

        e4.shutdown();
        e3.shutdown();
        e2.shutdown();
        e1.shutdown();
    }


    return 0;
}
Beispiel #4
0
bool CMap32::Set(UInt32 key, UInt32 value)
{
  if (Nodes.Size() == 0)
  {
    CNode n;
    n.Key = n.Keys[0] = n.Keys[1] = key;
    n.Values[0] = n.Values[1] = value;
    n.IsLeaf[0] = n.IsLeaf[1] = 1;
    n.Len = kNumBitsMax;
    Nodes.Add(n);
    return false;
  }
  if (Nodes.Size() == 1)
  {
    CNode &n = Nodes[0];
    if (n.Len == kNumBitsMax)
    {
      if (key == n.Key)
      {
        n.Values[0] = n.Values[1] = value;
        return true;
      }
      unsigned i = kNumBitsMax - 1;
      for (;GetSubBit(key, i) == GetSubBit(n.Key, i); i--);
      n.Len = (UInt16)(kNumBitsMax - (1 + i));
      unsigned newBit = GetSubBit(key, i);
      n.Values[newBit] = value;
      n.Keys[newBit] = key;
      return false;
    }
  }

  int cur = 0;
  unsigned bitPos = kNumBitsMax;
  for (;;)
  {
    CNode &n = Nodes[cur];
    bitPos -= n.Len;
    if (GetSubBits(key, bitPos, n.Len) != GetSubBits(n.Key, bitPos, n.Len))
    {
      unsigned i = n.Len - 1;
      for (; GetSubBit(key, bitPos + i) == GetSubBit(n.Key, bitPos + i); i--);
      
      CNode e2(n);
      e2.Len = (UInt16)i;

      n.Len = (UInt16)(n.Len - (1 + i));
      unsigned newBit = GetSubBit(key, bitPos + i);
      n.Values[newBit] = value;
      n.IsLeaf[newBit] = 1;
      n.IsLeaf[1 - newBit] = 0;
      n.Keys[newBit] = key;
      n.Keys[1 - newBit] = Nodes.Size();
      Nodes.Add(e2);
      return false;
    }
    unsigned bit = GetSubBit(key, --bitPos);

    if (n.IsLeaf[bit])
    {
      if (key == n.Keys[bit])
      {
        n.Values[bit] = value;
        return true;
      }
      unsigned i = bitPos - 1;
      for (;GetSubBit(key, i) == GetSubBit(n.Keys[bit], i); i--);
     
      CNode e2;
      
      unsigned newBit = GetSubBit(key, i);
      e2.Values[newBit] = value;
      e2.Values[1 - newBit] = n.Values[bit];
      e2.IsLeaf[newBit] = e2.IsLeaf[1 - newBit] = 1;
      e2.Keys[newBit] = key;
      e2.Keys[1 - newBit] = e2.Key = n.Keys[bit];
      e2.Len = (UInt16)(bitPos - (1 + i));

      n.IsLeaf[bit] = 0;
      n.Keys[bit] = Nodes.Size();

      Nodes.Add(e2);
      return false;
    }
    cur = (int)n.Keys[bit];
  }
}
Beispiel #5
0
/**
* Creates a tangent between two circles or arcs.
* Out of the 4 possible tangents, the one closest to
* the given coordinate is returned.
*
* @param coord Coordinate to define which tangent we want (typically a
*              mouse coordinate).
* @param circle1 1st circle or arc entity.
* @param circle2 2nd circle or arc entity.
*/
RS_Line* RS_Creation::createTangent2(const RS_Vector& coord,
                                     RS_Entity* circle1,
                                     RS_Entity* circle2) {
	RS_Line* ret = nullptr;
    RS_Vector circleCenter1;
    RS_Vector circleCenter2;
    double circleRadius1 = 0.0;
    double circleRadius2 = 0.0;

    // check given entities:
	if(! (circle1 && circle2))
		return nullptr;
	if( !(circle1->isArc() && circle2->isArc()))
		return nullptr;

	std::vector<RS_Line*> poss;
    //        for (int i=0; i<4; ++i) {
	//            poss[i] = nullptr;
    //        }
    RS_LineData d;
    if( circle1->rtti() == RS2::EntityEllipse) {
        std::swap(circle1,circle2);//move Ellipse to the second place
    }
    circleCenter1=circle1->getCenter();
    circleRadius1=circle1->getRadius();
    circleCenter2=circle2->getCenter();
    circleRadius2=circle2->getRadius();
    if(circle2->rtti() != RS2::EntityEllipse) {
        //no ellipse

        // create all possible tangents:

        double angle1 = circleCenter1.angleTo(circleCenter2);
        double dist1 = circleCenter1.distanceTo(circleCenter2);

        if (dist1>1.0e-6) {
            // outer tangents:
            double dist2 = circleRadius2 - circleRadius1;
            if (dist1>dist2) {
                double angle2 = asin(dist2/dist1);
				double angt1 = angle1 + angle2 + M_PI_2;
				double angt2 = angle1 - angle2 - M_PI_2;
                RS_Vector offs1;
                RS_Vector offs2;

                offs1.setPolar(circleRadius1, angt1);
                offs2.setPolar(circleRadius2, angt1);

                d = RS_LineData(circleCenter1 + offs1,
                                circleCenter2 + offs2);
				poss.push_back( new RS_Line(nullptr, d));


                offs1.setPolar(circleRadius1, angt2);
                offs2.setPolar(circleRadius2, angt2);

                d = RS_LineData(circleCenter1 + offs1,
                                circleCenter2 + offs2);
				poss.push_back( new RS_Line(nullptr, d));
            }

            // inner tangents:
            double dist3 = circleRadius2 + circleRadius1;
            if (dist1>dist3) {
                double angle3 = asin(dist3/dist1);
				double angt3 = angle1 + angle3 + M_PI_2;
				double angt4 = angle1 - angle3 - M_PI_2;
                RS_Vector offs1;
                RS_Vector offs2;

                offs1.setPolar(circleRadius1, angt3);
                offs2.setPolar(circleRadius2, angt3);

                d = RS_LineData(circleCenter1 - offs1,
                                circleCenter2 + offs2);
				poss.push_back( new RS_Line(nullptr, d));


                offs1.setPolar(circleRadius1, angt4);
                offs2.setPolar(circleRadius2, angt4);

                d = RS_LineData(circleCenter1 - offs1,
                                circleCenter2 + offs2);
				poss.push_back( new RS_Line(nullptr, d));
            }

        }
    }else{
        //circle2 is Ellipse
		std::unique_ptr<RS_Ellipse> e2((RS_Ellipse*)circle2->clone());
//        RS_Ellipse* e2=new RS_Ellipse(nullptr,RS_EllipseData(RS_Vector(4.,1.),RS_Vector(2.,0.),0.5,0.,0.,false));
//        RS_Ellipse  e3(nullptr,RS_EllipseData(RS_Vector(4.,1.),RS_Vector(2.,0.),0.5,0.,0.,false));
//        RS_Ellipse* circle1=new RS_Ellipse(nullptr,RS_EllipseData(RS_Vector(0.,0.),RS_Vector(1.,0.),1.,0.,0.,false));
        RS_Vector m0(circle1->getCenter());
//        std::cout<<"translation: "<<-m0<<std::endl;
        e2->move(-m0); //circle1 centered at origin

        double a,b;
        double a0(0.);
        if(circle1->rtti() != RS2::EntityEllipse){//circle1 is either arc or circle
            a=fabs(circle1->getRadius());
            b=a;
			if(fabs(a)<RS_TOLERANCE) return nullptr;
        }else{//circle1 is ellipse
            RS_Ellipse* e1=static_cast<RS_Ellipse*>(circle1);
            a0=e1->getAngle();
//            std::cout<<"rotation: "<<-a0<<std::endl;
            e2->rotate(-a0);//e1 major axis along x-axis
            a=e1->getMajorRadius();
            b=e1->getRatio()*a;
			if(fabs(a)<RS_TOLERANCE || fabs(b)<RS_TOLERANCE) return nullptr;
        }
        RS_Vector factor1(1./a,1./b);
//        std::cout<<"scaling: factor1="<<factor1<<std::endl;
        e2->scale(RS_Vector(0.,0.),factor1);//circle1 is a unit circle
        factor1.set(a,b);
        double a2(e2->getAngle());
//        std::cout<<"rotation: a2="<<-a2<<std::endl;
        e2->rotate(-a2); //ellipse2 with major axis in x-axis direction
        a=e2->getMajorP().x;
        b=a*e2->getRatio();
        RS_Vector v(e2->getCenter());
//        std::cout<<"Center: (x,y)="<<v<<std::endl;


        std::vector<double> m(0,0.);
        m.push_back(1./(a*a)); //ma000
        m.push_back(1./(b*b)); //ma000
        m.push_back(v.y*v.y-1.); //ma100
        m.push_back(v.x*v.y); //ma101
        m.push_back(v.x*v.x-1.); //ma111
        m.push_back(2.*a*b*v.y); //mb10
        m.push_back(2.*a*b*v.x); //mb11
        m.push_back(a*a*b*b); //mc1

		auto vs0=RS_Math::simultaneousQuadraticSolver(m); //to hold solutions
		if (vs0.getNumber()<1) return nullptr;
//        for(size_t i=0;i<vs0.getNumber();i++){
		for(RS_Vector vpec: vs0){
            RS_Vector vpe2(e2->getCenter()+ RS_Vector(vpec.y/e2->getRatio(),vpec.x*e2->getRatio()));
            vpec.x *= -1.;//direction vector of tangent
            RS_Vector vpe1(vpe2 - vpec*(RS_Vector::dotP(vpec,vpe2)/vpec.squared()));
//            std::cout<<"vpe1.squared()="<<vpe1.squared()<<std::endl;
			RS_Line *l=new RS_Line(nullptr,RS_LineData(vpe1,vpe2));
            l->rotate(a2);
            l->scale(factor1);
            l->rotate(a0);
            l->move(m0);
            poss.push_back(l);

        }
        //debugging

    }
    // find closest tangent:
	if(poss.size()<1) return nullptr;
    double minDist = RS_MAXDOUBLE;
    double dist;
    int idx = -1;
	for (size_t i=0; i<poss.size(); ++i) {
		if (poss[i]) {
            poss[i]->getNearestPointOnEntity(coord,false,&dist);
//        std::cout<<poss.size()<<": i="<<i<<" dist="<<dist<<"\n";
            if (dist<minDist) {
                minDist = dist;
                idx = i;
            }
        }
    }
//idx=static_cast<int>(poss.size()*(random()/(double(1.0)+RAND_MAX)));
    if (idx!=-1) {
        RS_LineData d = poss[idx]->getData();
		for(auto p: poss){
			if(p)
				delete p;
		}

		if (document && handleUndo) {
            document->startUndoCycle();
        }

        ret = new RS_Line(container, d);
		setEntity(ret);
    } else {
		ret = nullptr;
    }

    return ret;
}
Beispiel #6
0
//-----------------------------------------------------------------------------
//! SLRectangle::buildMesh fills in the underlying arrays from the SLMesh object
void SLRectangle::buildMesh(SLMaterial* material)
{  
    deleteData();
   
    // Check max. allowed no. of verts
    SLuint uIntNumV64 = (_resX+1) * (_resY+1);
    if (uIntNumV64 > UINT_MAX)
        SL_EXIT_MSG("SLMesh supports max. 2^32 vertices.");

    // allocate new arrays of SLMesh
    numV = (_resX+1) * (_resY+1);
    numI = _resX * _resY * 2 * 3;
    P = new SLVec3f[numV];
    N = new SLVec3f[numV];
    Tc = new SLVec2f[numV];

    if (uIntNumV64 < 65535)
         I16 = new SLushort[numI];
    else I32 = new SLuint[numI];
   
    // Calculate normal from the first 3 corners
    SLVec3f maxmin(_max.x, _min.y, 0);
    SLVec3f minmax(_min.x, _max.y, 0);
    SLVec3f e1(maxmin - _min);
    SLVec3f e2(minmax - _min);
    SLVec3f curN(e1^e2);
    curN.normalize();
   
    //Set one default material index
    mat = material;
   
    // define delta vectors dX & dY and deltas for texCoord dS,dT
    SLVec3f dX = e1 / (SLfloat)_resX;
    SLVec3f dY = e2 / (SLfloat)_resY;
    SLfloat dS = (_tmax.x - _tmin.x) / (SLfloat)_resX;
    SLfloat dT = (_tmax.y - _tmin.y) / (SLfloat)_resY;

    // Build vertex data
    SLuint i = 0;
    for (SLuint y=0; y<=_resY; ++y)
    {  
        SLVec3f curV = _min;
        SLVec2f curT = _tmin;
        curV   += (SLfloat)y*dY;
        curT.y += (SLfloat)y*dT;

        for (SLuint x=0; x<=_resX; ++x, ++i)
        {  
            P[i]  = curV;
            Tc[i] = curT;
            N[i]  = curN;
            curV   += dX;
            curT.x += dS;
        }      
    }
   
    // Build face vertex indexes
    if (I16)
    {
        SLuint v = 0, i = 0; //index for vertices and indexes
        for (SLuint y=0; y<_resY; ++y)
        {  
            for (SLuint x=0; x<_resX; ++x, ++v)
            {  // triangle 1
                I16[i++] = v;
                I16[i++] = v+_resX+2;
                I16[i++] = v+_resX+1;

                // triangle 2
                I16[i++] = v;
                I16[i++] = v+1;
                I16[i++] = v+_resX+2;
            }      
            v++;
        }
    } else
    {
        SLuint v = 0, i = 0; //index for vertices and indexes
        for (SLuint y=0; y<_resY; ++y)
        {  
            for (SLuint x=0; x<_resX; ++x, ++v)
            {  // triangle 1
                I32[i++] = v;
                I32[i++] = v+_resX+2;
                I32[i++] = v+_resX+1;

                // triangle 2
                I32[i++] = v;
                I32[i++] = v+1;
                I32[i++] = v+_resX+2;
            }      
            v++;
        }
    }
}
int main()
{
   
  cout  << setiosflags(ios::uppercase);
  /*
  ofstream out("GAUSS.out");
  out   << setiosflags(ios::uppercase);
  ofstream dout("GAUSSMOD.out");
  dout  << setiosflags(ios::uppercase);
  */

  mp_init();
  cout << "+++ Precision = " << mpipl << " +++" << endl;
 

  double s_in, h_in , b1_in, b2_in, db, g_in, dpi, x1_in, x2_in;
  int N, Nb, m, Control;

  dpi = 4.0 * atan(1.0);
  
  mp_real pi = mppic; // pi aus der Bibliothek !!!
  mp_real pi2 = pi * pi;
  static mp_real factor;
  
  mp_real b, b1, b2, bstep, g, x0, s, h, x1, x2;

  /* Parameter als doubles einlesen */
  cin >> b1_in >> b2_in >> Nb;
  cin >> g_in >> Control;
  cin >> s_in >> h_in >> N;
  cin >> x1_in >> x2_in >> m;

  /* Konversion: double -> mp_real */
  b1  = mp_real(b1_in);
  b2  = mp_real(b2_in);
  g  = mp_real(g_in);
  s  = mp_real(s_in);
  h  = mp_real(h_in);
  x1 = mp_real(x1_in);
  x2 = mp_real(x2_in);
//  a  = 1/(mp_real(2.0)*b1);

  bstep = (b2 - b1)/mp_real(Nb);


  /* Vorfaktor */
//  factor = mp_real(2.0)*b/power(pi,mp_real(1.5));
//  factor *= exp(mp_real(0.25) * pi2 * b * b);
  
  //dfactor = 2.0 * (b_in/pow(dpi,1.5)) * exp(b_in*b_in*dpi*dpi*.25);

  cout << "*** Parameter ***" << endl; 
  cout << "b1     = " << b1 ;
  cout << "b2     = " << b2 ;
  cout << "bstep  = " << bstep ;
  //cout << "a      = " << a;
  cout << "g      = " << g;
  cout << "h      = " << h;
  cout << "N      = " << N << endl;
  cout << '\v' ;
  cout << "x1     = " << x1;
  cout << "x2     = " << x2;
  cout << "m      = " << m << endl;
  
  cout << "xmax   = " << h * N << endl;
  
//  cout << "dfaktor = " <<dfactor << endl;
//  cout << "Faktor = " <<factor << endl;


  /* Datendatei */

  String data = "GAUSSMOD-N" ;
  data = data + N + "-xb" + x2_in + "-beta" + strdup(fix3(g_in)) + ".out"; 
  ofstream dout(data());
  
  
  
  mp_real mp_E2_Gauss, mp_E2_Gausstheo, mp_Reg, mp_Regtheo, mp_ModGauss, step;
  mp_real mp_diffrel, mp_diffrelreg;
  double E2, E2_Gauss, E2_Gausstheo, Reg, Reg_theod, ModGauss, diffrel, x0d;
  double diffrelreg;
  
  step = (x2 -x1)/mp_real(m);


  if(Control == 1)
    {
	cout << "*** Begin: Read Data ***" << endl; 
      for(int j = 0; j <= m; j++)
	{
	  x0 = x1 + j * step; 
	  mp_E2_Gauss = mpe2gauss(x0,g);
	  mp_E2_Gausstheo = mpe2gausstheo(x0,g);
	  mp_real mpdeltarel = abs(mp_E2_Gauss - mp_E2_Gausstheo)/abs(mp_E2_Gausstheo);
	  mpdeltarel *= mp_real(100.0);
	  
	  x0d = dble(x0);
	  E2 = e2(x0d);
	  E2_Gauss        = dble(mp_E2_Gauss);
	  E2_Gausstheo    = dble(mp_E2_Gausstheo);
	  double deltarel = dble(mpdeltarel);
	  cout << x0 << mp_E2_Gausstheo << mp_E2_Gauss << mpdeltarel << endl;;

	  (ostream&) dout << x0d << '\t' << E2 << '\t' << E2_Gausstheo <<'\t' << E2_Gauss << '\t' << deltarel << endl;
      	}
      cout << "*** End: Read Data ***" << endl; 
    }



  cout << "*** Begin: Regularisation Scan ***" << endl;
  for(int i = 0; i <= Nb; i++)
  {
      b = b1 + i * bstep;
      db = dble(b);
      factor = mp_real(2.0)*b/power(pi,mp_real(1.5));
      factor *= exp(mp_real(0.25) * pi2 * b * b);

      /* RegDatei */
      String reg = "GAUSSREG-N" ;
      reg = reg + N + "-xb" + x2_in + "-beta" + strdup(fix3(g_in)) + "-b" + strdup(fix3(db)) + ".out"; 
      ofstream out(reg());
      
      cout << " +++ i = " << i << ",  " << " b = " << db << " +++ " << endl;
      cout << '\v' ;
      
  for(int jj = 0; jj <= m; jj++)
    {
      x0 = x1 + jj * step;
      s = x0;
      mp_Reg = mptrapez(mpkern,x0,b,g,s,h,N);
      mp_Reg *= factor;
  
      mp_Regtheo  = Regtheo(x0,b,g); //reine Regularisierte
      mp_ModGauss = GaussDichte(x0,g); //Gaussdichte als Modell
      
      
      mp_diffrel = abs(mp_Reg - mp_Regtheo)/abs(mp_Regtheo);
      mp_diffrel *= mp_real(100.0);
      
      mp_diffrelreg  = abs(mp_Reg - mp_ModGauss)/abs(mp_ModGauss);
      mp_diffrelreg *= mp_real(100.0);

      Reg_theod  = dble(mp_Regtheo);
      Reg        = dble(mp_Reg);
      ModGauss   = dble(mp_ModGauss);
      diffrel    = dble(mp_diffrel);
      diffrelreg = dble(mp_diffrelreg);
      x0d        = dble(x0);

      cout << x0 << mp_Reg << mp_Regtheo << mp_ModGauss << mp_diffrel << mp_diffrelreg<< endl;


      (ostream&) out << x0d << '\t' << ModGauss << '\t' << Reg << '\t' << Reg_theod<< '\t' << diffrel <<'\t' << diffrelreg << endl;
      
    }
  }
  cout << "*** End: Regularisation Scan ***" << endl;
  return 0;
}
Beispiel #8
0
int json_cpp_tests() {
	json::Value e1(json::load_file("test.json"));
	json::Value e2(e1);
	json::Value e3;
	json::Value e4(json::load_string("{\"foo\": true, \"bar\": \"test\"}"));

	ASSERT_TRUE(e1.is_object(), "e1 is not an object");
	ASSERT_TRUE(e2.is_object(), "e2 is not an object");
	ASSERT_TRUE(e3.is_undefined(), "e3 has a defined value");
	ASSERT_TRUE(e4.is_object(), "e4 is not an object");

	ASSERT_EQ(e1.size(), 1, "e1 has too many properties");
	ASSERT_EQ(e2.size(), 1, "e2 has too many properties");
	ASSERT_EQ(e4.size(), 2, "e4 does not have 2 elements");

	ASSERT_TRUE(e1.get("web-app").is_object(), "e1[0].web-app is not an object");
	ASSERT_EQ(e1.get("web-app").get("servlet").at(0).get("servlet-class").as_string(), "org.cofax.cds.CDSServlet", "property has incorrect value");
	ASSERT_EQ(e1["web-app"]["servlet"][0]["servlet-class"].as_string(), "org.cofax.cds.CDSServlet", "property has incorrect value");

	ASSERT_EQ(e4["foo"].as_boolean(), true, "property has incorrect value");

	// verify iterator results (note that they can be returned in any order)
	json::Iterator i(e1.get("web-app"));
	std::set<std::string> iteratorResults;
	for ( int ii = 0; ii < 3; ++ii ) {
		ASSERT_FALSE(i.key().empty(), "iterator returned a null value");
		iteratorResults.insert(i.key());
		i.next();
	}
	ASSERT_FALSE(i.valid(), "iterator has more values than expected");
	ASSERT_EQ(iteratorResults.size(), 3, "iterator did not return enough values");

	json::Value e5(json::Value(12.34));
	ASSERT_TRUE(e5.is_number(), "e5 is not a number after assignment");
	ASSERT_EQ(e5.as_real(), 12.34, "e5 has incorrect value after assignment");

	json::Value e6(json::Value(true));
	ASSERT_TRUE(e6.is_boolean(), "e6 is not a boolean after assignment");
	ASSERT_EQ(e6.as_boolean(), true, "e6 has incorrect value after assignment");

	json::Value e7(json::Value("foobar"));
	ASSERT_TRUE(e7.is_string(), "e7 is not a string after assignment");
	ASSERT_EQ(e7.as_string(), "foobar", "e7 has incorrect value after assignment");

	json::Value e8(json::object());
	ASSERT_TRUE(e8.is_object(), "e8 is not an object after assignment");

	json::Value e9(json::null());
	ASSERT_TRUE(e9.is_null(), "e9 is not null after assignment");

	json::Value e10(json::array());
	ASSERT_TRUE(e10.is_array(), "e10 is not an array after index assignment");

	e10.set_at(0, json::Value("foobar"));
	ASSERT_EQ(e10.size(), 1, "e10 has incorrect number of elements after assignment");
	ASSERT_EQ(e10[0].as_string(), "foobar", "e10[0] has incorrect value after assignment");

	e10.set_at(1, json::Value("foobar"));
	ASSERT_TRUE(e10.is_array(), "e10 is not an array after index assignment");
	ASSERT_EQ(e10.size(), 2, "e10 has incorrect number of elements after assignment");
	ASSERT_EQ(e10[1].as_string(), "foobar", "e10[0] has incorrect value after assignment");

	e10.set_at(0, json::Value("barfoo"));
	ASSERT_TRUE(e10.is_array(), "e10 is not an array after index assignment");
	ASSERT_EQ(e10.size(), 2, "e10 has incorrect number of elements after assignment");
	ASSERT_EQ(e10[0].as_string(), "barfoo", "e10[0] has incorrect value after assignment");

	e10.set_at(100, json::null());
	ASSERT_TRUE(e10.is_array(), "e10 is not an array after index assignment");
	ASSERT_EQ(e10.size(), 2, "e10 has incorrect number of elements after assignment");

	e10.insert_at(1, json::Value("new"));
	ASSERT_EQ(e10.size(), 3, "e10 has incorrect size after insert");
	ASSERT_EQ(e10[1].as_string(), "new", "e10[1] has incorrect value after insert");
	ASSERT_EQ(e10[2].as_string(), "foobar", "e10[2] has incorrect value after insert");

	e10.del_at(0);
	ASSERT_EQ(e10.size(), 2, "e10 has incorrect size after delete");
	ASSERT_EQ(e10[1].as_string(), "foobar", "e10[1] has incorrect value after delete");

	e10.clear();
	ASSERT_EQ(e10.size(), 0, "e10 has incorrect number of elements after clear");

	json::Value e11(json::object());
	ASSERT_TRUE(e11.is_object(), "e11 is not an object after property assignment");

	e11.set_key("foo", json::Value("test"));
	ASSERT_EQ(e11.size(), 1, "e11 has incorrect number of properties after assignment");
	ASSERT_EQ(e11["foo"].as_string(), "test", "e11.foo has incorrect value after assignment");

	e11.set_key("foo", json::Value("again"));
	ASSERT_TRUE(e11.is_object(), "e11 is not an object after property assignment");
	ASSERT_EQ(e11.size(), 1, "e11 has incorrect number of properties after assignment");
	ASSERT_EQ(e11["foo"].as_string(), "again", "e11.foo has incorrect value after assignment");

	e11.set_key("bar", json::Value("test"));
	ASSERT_TRUE(e11.is_object(), "e11 is not an object after property assignment");
	ASSERT_EQ(e11.size(), 2, "e11 has incorrect number of properties after assignment");
	ASSERT_EQ(e11["bar"].as_string(), "test", "e11.foo has incorrect value after assignment");

	e11.clear();
	ASSERT_EQ(e11.size(), 0, "e11 has incorrect number of properties after clear");

	json::Value e12(json::object());
	e12.set_key("foo", json::Value("test"));
	e12.set_key("bar", json::Value(3));
	char* out_cstr = e12.save_string(JSON_COMPACT);
	std::string out(out_cstr);
	free(out_cstr);
	ASSERT_EQ(out, "{\"bar\":3,\"foo\":\"test\"}", "object did not serialize as expected");

	std::istringstream instr(out);
	instr >> e12;
	ASSERT_TRUE(e12.is_object(), "e12 is not an object after stream read");
	ASSERT_EQ(e12.size(), 2, "e12 has wrong size after stream read");
	ASSERT_EQ(e12.get("bar").as_integer(), 3, "e12.bar has incorrect value after stream read");
	ASSERT_EQ(e12.get("foo").as_string(), "test", "ee12.test has incorrect value after stream read");

	std::ostringstream outstr;
	outstr << e12;
	ASSERT_EQ(instr.str(), "{\"bar\":3,\"foo\":\"test\"}", "object did not serialize as expected");

	const json::Value e13(e12);
	ASSERT_EQ(e13["bar"].as_integer(), 3, "e13.bar has incorrect value after copy");

	json::Value e14(json::object());
	ASSERT_TRUE(e14.is_object(), "e14 is not an object after construction");
	e14.set_key("foo", json::object());
	ASSERT_TRUE(e14["foo"].is_object(), "e14.foo is not an object after assignment");
	e14["foo"]["bar"] = json::Value(42);
	ASSERT_EQ(e14["foo"]["bar"].as_integer(), 42, "e14.foo.bar has incorrect value after assignment");

	json::Value e15(json::array());
	ASSERT_TRUE(e15.is_array(), "e15 is not an array after construction");
	e15.set_at(0, json::Value(42));
	ASSERT_EQ(e15[0].as_integer(), 42, "e15[0] has incorrect value after assignment");
	e15[0] = json::Value("foo");
	ASSERT_EQ(e15[0].as_string(), "foo", "e15[0] has incorrecy value after assignment");
	return 0;
}
int
main(int argc, const char ** argv)
{
  try {
    bool opt_display = true;
    bool opt_click_allowed = true;

    // Read the command line options
    if (getOptions(argc, argv, opt_click_allowed, opt_display) == false) {
      exit (-1);
    }

    vpImage<unsigned char> Iint(512,512,0) ;
    vpImage<unsigned char> Iext(512,512,0) ;

    // We open a window using either X11, GTK or GDI.
#if defined VISP_HAVE_X11
    vpDisplayX displayInt;
    vpDisplayX displayExt;
#elif defined VISP_HAVE_GTK
    vpDisplayGTK displayInt;
    vpDisplayGTK displayExt;
#elif defined VISP_HAVE_GDI
    vpDisplayGDI displayInt;
    vpDisplayGDI displayExt;
#elif defined VISP_HAVE_OPENCV
    vpDisplayOpenCV displayInt;
    vpDisplayOpenCV displayExt;
#endif

    if (opt_display) {
      try{
        // Display size is automatically defined by the image (Iint) and (Iext) size
        displayInt.init(Iint, 100, 100,"Internal view") ;
        displayExt.init(Iext, (int)(130+Iint.getWidth()), 100, "External view") ;
        // Display the image
        // The image class has a member that specify a pointer toward
        // the display that has been initialized in the display declaration
        // therefore is is no longuer necessary to make a reference to the
        // display variable.
        vpDisplay::display(Iint) ;
        vpDisplay::display(Iext) ;
        vpDisplay::flush(Iint) ;
        vpDisplay::flush(Iext) ;
      }
      catch(...)
      {
        vpERROR_TRACE("Error while displaying the image") ;
        exit(-1);
      }
    }

    vpProjectionDisplay externalview ;

    //Set the camera parameters
    double px, py ; px = py = 600 ;
    double u0, v0 ; u0 = v0 = 256 ;

    vpCameraParameters cam(px,py,u0,v0);

    vpServo task ;
    vpSimulatorCamera robot ;

    // sets the initial camera location
    vpHomogeneousMatrix cMo(-0.2,0.1,2,
                            vpMath::rad(5),  vpMath::rad(5),  vpMath::rad(20));

    vpHomogeneousMatrix wMc, wMo;
    robot.getPosition(wMc) ;
    wMo = wMc * cMo; // Compute the position of the object in the world frame

    // sets the final camera location (for simulation purpose)
    vpHomogeneousMatrix cMod(0,0,1,
                             vpMath::rad(0),  vpMath::rad(0),  vpMath::rad(0));

    // sets the cylinder coordinates in the world frame
    vpCylinder cylinder(0,1,0,  // direction
                        0,0,0,  // point of the axis
                        0.1) ;  // radius

    externalview.insert(cylinder) ;

    // sets the desired position of the visual feature
    cylinder.track(cMod) ;
    cylinder.print() ;

    //Build the desired line features thanks to the cylinder and especially its paramaters in the image frame
    vpFeatureLine ld[2] ;
    int i ;
    for(i=0 ; i < 2 ; i++)
      vpFeatureBuilder::create(ld[i],cylinder,i)  ;

    // computes  the cylinder coordinates in the camera frame and its 2D coordinates
    // sets the current position of the visual feature
    cylinder.track(cMo) ;
    cylinder.print() ;

    //Build the current line features thanks to the cylinder and especially its paramaters in the image frame
    vpFeatureLine l[2] ;
    for(i=0 ; i < 2 ; i++)
    {
      vpFeatureBuilder::create(l[i],cylinder,i)  ;
      l[i].print() ;
    }

    // define the task
    // - we want an eye-in-hand control law
    // - robot is controlled in the camera frame
    task.setServo(vpServo::EYEINHAND_CAMERA) ;
    task.setInteractionMatrixType(vpServo::DESIRED,vpServo::PSEUDO_INVERSE) ;
    //  it can also be interesting to test these possibilities
    // task.setInteractionMatrixType(vpServo::CURRENT,vpServo::PSEUDO_INVERSE) ;
    // task.setInteractionMatrixType(vpServo::MEAN, vpServo::PSEUDO_INVERSE) ;
    // task.setInteractionMatrixType(vpServo::CURRENT, vpServo::PSEUDO_INVERSE) ;
    // task.setInteractionMatrixType(vpServo::DESIRED,  vpServo::TRANSPOSE) ;
    // task.setInteractionMatrixType(vpServo::CURRENT,  vpServo::TRANSPOSE) ;

    // we want to see  2 lines on 2 lines
    task.addFeature(l[0],ld[0]) ;
    task.addFeature(l[1],ld[1]) ;

    // Set the point of view of the external view
    vpHomogeneousMatrix cextMo(0,0,6,
                               vpMath::rad(40),  vpMath::rad(10),  vpMath::rad(60))   ;

    // Display the initial scene
    vpServoDisplay::display(task,cam,Iint) ;
    externalview.display(Iext,cextMo, cMo, cam, vpColor::red);
    vpDisplay::flush(Iint) ;
    vpDisplay::flush(Iext) ;

    // Display task information
    task.print() ;

    if (opt_display && opt_click_allowed) {
      std::cout << "\n\nClick in the internal camera view window to start..." << std::endl;
      vpDisplay::getClick(Iint) ;
    }

    // set the gain
    task.setLambda(1) ;

    // Display task information
    task.print() ;

    unsigned int iter=0 ;
    // The first loop is needed to reach the desired position
    do
    {
      std::cout << "---------------------------------------------" << iter++ <<std::endl ;
      vpColVector v ;

      // get the robot position
      robot.getPosition(wMc) ;
      // Compute the position of the camera wrt the object frame
      cMo = wMc.inverse() * wMo;

      // new line position
      // retrieve x,y and Z of the vpLine structure
      // Compute the parameters of the cylinder in the camera frame and in the image frame
      cylinder.track(cMo) ;

      //Build the current line features thanks to the cylinder and especially its paramaters in the image frame
      for(i=0 ; i < 2 ; i++)
      {
        vpFeatureBuilder::create(l[i],cylinder,i)  ;
      }

      // Display the current scene
      if (opt_display) {
        vpDisplay::display(Iint) ;
        vpDisplay::display(Iext) ;
        vpServoDisplay::display(task,cam,Iint) ;
        externalview.display(Iext,cextMo, cMo, cam, vpColor::red);
        vpDisplay::flush(Iint);
        vpDisplay::flush(Iext);
      }

      // compute the control law
      v = task.computeControlLaw() ;

      // send the camera velocity to the controller
      robot.setVelocity(vpRobot::CAMERA_FRAME, v) ;

      std::cout << "|| s - s* || = " << ( task.getError() ).sumSquare() <<std::endl ;
    }
    while(( task.getError() ).sumSquare() >  1e-9) ;


    // Second loop is to compute the control law while taking into account the secondary task.
    // In this example the secondary task is cut in four steps.
    // The first one consists in impose a movement of the robot along the x axis of the object frame with a velocity of 0.5.
    // The second one consists in impose a movement of the robot along the y axis of the object frame with a velocity of 0.5.
    // The third one consists in impose a movement of the robot along the x axis of the object frame with a velocity of -0.5.
    // The last one consists in impose a movement of the robot along the y axis of the object frame with a velocity of -0.5.
    // Each steps is made during 200 iterations.
    vpColVector e1(6) ; e1 = 0 ;
    vpColVector e2(6) ; e2 = 0 ;
    vpColVector proj_e1 ;
    vpColVector proj_e2 ;
    iter = 0;
    double rapport = 0;
    double vitesse = 0.5;
    unsigned int tempo = 800;

    while(iter < tempo)
    {
      vpColVector v ;

      robot.getPosition(wMc) ;
      // Compute the position of the camera wrt the object frame
      cMo = wMc.inverse() * wMo;

      cylinder.track(cMo) ;

      for(i=0 ; i < 2 ; i++)
      {
        vpFeatureBuilder::create(l[i],cylinder,i)  ;
      }

      if (opt_display)
      {
        vpDisplay::display(Iint) ;
        vpDisplay::display(Iext) ;
        vpServoDisplay::display(task,cam,Iint) ;
        externalview.display(Iext,cextMo, cMo, cam, vpColor::red);
        vpDisplay::flush(Iint);
        vpDisplay::flush(Iext);
      }

      v = task.computeControlLaw() ;

      if ( iter%tempo < 200  /*&&  iter%tempo >= 0*/)
      {
        e2 = 0;
        e1[0] = fabs(vitesse)  ;
        proj_e1 = task.secondaryTask(e1);
        rapport = vitesse/proj_e1[0];
        proj_e1 *= rapport ;
        v += proj_e1 ;
      }

      if ( iter%tempo < 400 &&  iter%tempo >= 200)
      {
        e1 = 0;
        e2[1] = fabs(vitesse)  ;
        proj_e2 = task.secondaryTask(e2);
        rapport = vitesse/proj_e2[1];
        proj_e2 *= rapport ;
        v += proj_e2 ;
      }

      if ( iter%tempo < 600 &&  iter%tempo >= 400)
      {
        e2 = 0;
        e1[0] = -fabs(vitesse)  ;
        proj_e1 = task.secondaryTask(e1);
        rapport = -vitesse/proj_e1[0];
        proj_e1 *= rapport ;
        v += proj_e1 ;
      }

      if ( iter%tempo < 800 &&  iter%tempo >= 600)
      {
        e1 = 0;
        e2[1] = -fabs(vitesse)  ;
        proj_e2 = task.secondaryTask(e2);
        rapport = -vitesse/proj_e2[1];
        proj_e2 *= rapport ;
        v += proj_e2 ;
      }

      robot.setVelocity(vpRobot::CAMERA_FRAME, v);

      std::cout << "|| s - s* || = " << ( task.getError() ).sumSquare() <<std::endl ;

      iter++;
    }

    if (opt_display && opt_click_allowed) {
      std::cout << "\nClick in the internal camera view window to end..." << std::endl;
      vpDisplay::getClick(Iint) ;
    }

    // Display task information
    task.print() ;
    task.kill();
    return 0;
  }
  catch(vpException e) {
    std::cout << "Catch a ViSP exception: " << e << std::endl;
    return 1;
  }
}
Beispiel #10
0
double kerngauss(double x_ , double x0_, double g)
{
  double y_ = e2(x_) * exp(- g * g * (x_ - x0_) * (x_ - x0_));
  return y_ ;
}
Beispiel #11
0
void	unitTestState(void)
{
  State	s;
  State sNamed(std::string("name"));
  State sNamedFinal("name", true);
  State sFinal("", true);

  /*
  ** Constructor and getter tests
  */
  assert(s.getName() == "");
  assert(s.isFinal() == false);

  assert(sNamed.getName() == "name");
  assert(sNamed.isFinal() == false);

  assert(sNamedFinal.getName() == "name");
  assert(sNamedFinal.isFinal());

  assert(sFinal.getName() == "");
  assert(sFinal.isFinal() == true);

  /*
  ** Comparison tests
  */
  assert(s == sFinal);
  assert(sNamed == sNamedFinal);
  assert(s < sNamed);
  assert(sNamedFinal > sFinal);
  assert(s >= sFinal);
  assert(s <= sFinal);

  /*
  ** Create tests
  */
  State s0 = State::create();
  State s1 = State::create();
  State s2 = State::create(true);

  assert(s0.getName() == "S0");
  assert(s1.getName() == "S1");
  assert(s2.getName() == "S2");

  /*
  ** link/unlink and access tests
  */
  Edge	e1('c');
  Edge	e2('4');

  s0.link(e1, s1.getName());
  s1.link(e2, s2);
  assert(s0[e1] == s1.getName());
  try {
    // this is supposed to throw but if it doesn't the assert will fail
    assert(s0[e2] == "");
  } catch (const std::out_of_range &oor) {
    (void)oor;
  }
  assert(s1[e2] == s2.getName());
  std::cout << "State passed unit tests" << std::endl;
}
dgInt32 dgConvexHull4d::InitVertexArray(dgHullVector* const points, const dgBigVector* const vertexCloud, dgInt32 count, void* const memoryPool, dgInt32 maxMemSize)
{
	for (dgInt32 i = 0; i < count; i ++) {
		points[i] = vertexCloud[i];
		points[i].m_index = i;
		points[i].m_mark = 0;
	}

	dgSort(points, count, ConvexCompareVertex);
	dgInt32 indexCount = 0;
	for (int i = 1; i < count; i ++) {
		for (; i < count; i ++) {
			if (ConvexCompareVertex (&points[indexCount], &points[i], NULL)) {
				indexCount ++;
				points[indexCount] = points[i];
				break;
			}
		}
	}
	count = indexCount + 1;
	if (count < 4) {
		m_count = 0;
		return count;
	}

	dgAABBPointTree4d* tree = BuildTree (NULL, points, count, 0, (dgInt8**) &memoryPool, maxMemSize);

	dgBigVector boxSize (tree->m_box[1] - tree->m_box[0]);	
	boxSize.m_w = dgFloat64 (0.0f);
	m_diag = dgFloat32 (sqrt (boxSize.DotProduct4(boxSize).m_x));

	m_points[4].m_x = dgFloat64 (0.0f);
	dgHullVector* const convexPoints = &m_points[0]; 
	dgStack<dgBigVector> normalArrayPool (256);
	dgBigVector* const normalArray = &normalArrayPool[0];
	dgInt32 normalCount = BuildNormalList (&normalArray[0]);

	dgInt32 index = SupportVertex (&tree, points, normalArray[0]);
	convexPoints[0] = points[index];
	points[index].m_mark = 1;

	bool validTetrahedrum = false;
	dgBigVector e1 (dgFloat64 (0.0f), dgFloat64 (0.0f), dgFloat64 (0.0f), dgFloat64 (0.0f)) ;
	for (dgInt32 i = 1; i < normalCount; i ++) {
		dgInt32 index = SupportVertex (&tree, points, normalArray[i]);
		dgAssert (index >= 0);
		e1 = points[index] - convexPoints[0];
		e1.m_w = dgFloat64 (0.0f);
		dgFloat64 error2 = e1.DotProduct4(e1).m_x;
		if (error2 > (dgFloat32 (1.0e-4f) * m_diag * m_diag)) {
			convexPoints[1] = points[index];
			points[index].m_mark = 1;
			validTetrahedrum = true;
			break;
		}
	}
	if (!validTetrahedrum) {
		m_count = 0;
		return count;
	}


	dgInt32 bestIndex = -1;
	dgFloat64 bestValue = dgFloat64 (1.0f);
	validTetrahedrum = false;
	dgFloat64 lenght2 = e1.DotProduct4(e1).m_x;
	dgBigVector e2(dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f));;
	for (dgInt32 i = 2; i < normalCount; i ++) {
		dgInt32 index = SupportVertex (&tree, points, normalArray[i]);
		dgAssert (index >= 0);
		dgAssert (index < count);
		e2 = points[index] - convexPoints[0];
		e2.m_w = dgFloat64 (0.0f);
		dgFloat64 den = e2.DotProduct4(e2).m_x;
		if (fabs (den) > (dgFloat64 (1.0e-6f) * m_diag)) {
			den = sqrt (lenght2 * den);
			dgFloat64 num = e2.DotProduct4(e1).m_x;
			dgFloat64 cosAngle = fabs (num / den);
			if (cosAngle < bestValue) {
				bestValue = cosAngle;
				bestIndex = index;
			}

			if (cosAngle < 0.9f) {
				break;
			}
		}
	}

	if (bestValue < dgFloat64 (0.999f)) {
		convexPoints[2] = points[bestIndex];
		points[bestIndex].m_mark = 1;
		validTetrahedrum = true;
	}

	if (!validTetrahedrum) {
		m_count = 0;
		return count;
	}

	validTetrahedrum = false;
	dgBigVector e3(dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f));;
	for (dgInt32 i = 3; i < normalCount; i ++) {
		dgInt32 index = SupportVertex (&tree, points, normalArray[i]);
		dgAssert (index >= 0);
		dgAssert (index < count);

		e3 = points[index] - convexPoints[0];
		e3.m_w = dgFloat64 (0.0f);
		//dgFloat64 volume = (e1 * e2) % e3;		
		dgFloat64 volume = e3.DotProduct3(e1.CrossProduct3(e2));
		if (fabs (volume) > (dgFloat64 (1.0e-4f) * m_diag * m_diag * m_diag)) {
			convexPoints[3] = points[index];
			points[index].m_mark = 1;
			validTetrahedrum = true;
			break;
		}
	}

	m_count = 4;
	if (!validTetrahedrum) {
		m_count = 0;
	}
	
	return count;
}
int main(int argc, char *argv[])
{
#ifdef HAVE_MPI
  Teuchos::GlobalMPISession mpiSession(&argc, &argv,0);
  int rank=mpiSession.getRank();
  int numProcs=mpiSession.getNProc();
#else
  int rank = 0;
  int numProcs = 1;
#endif
  int polyOrder = 3;
  int pToAdd = 2; // for tests

  // define our manufactured solution or problem bilinear form:
  bool useTriangles = false;

  FieldContainer<double> meshPoints(4,2);

  meshPoints(0,0) = 0.0; // x1
  meshPoints(0,1) = 0.0; // y1
  meshPoints(1,0) = 1.0;
  meshPoints(1,1) = 0.0;
  meshPoints(2,0) = 1.0;
  meshPoints(2,1) = 1.0;
  meshPoints(3,0) = 0.0;
  meshPoints(3,1) = 1.0;

  int H1Order = polyOrder + 1;
  int horizontalCells = 4, verticalCells = 4;

  double energyThreshold = 0.2; // for mesh refinements
  double nonlinearStepSize = 0.5;
  double nonlinearRelativeEnergyTolerance = 1e-8; // used to determine convergence of the nonlinear solution

  ////////////////////////////////////////////////////////////////////
  // DEFINE VARIABLES
  ////////////////////////////////////////////////////////////////////

  // new-style bilinear form definition
  VarFactory varFactory;
  VarPtr fhat = varFactory.fluxVar("\\widehat{f}");
  VarPtr u = varFactory.fieldVar("u");

  VarPtr v = varFactory.testVar("v",HGRAD);
  BFPtr bf = Teuchos::rcp( new BF(varFactory) ); // initialize bilinear form

  ////////////////////////////////////////////////////////////////////
  // CREATE MESH
  ////////////////////////////////////////////////////////////////////

  // create a pointer to a new mesh:
  Teuchos::RCP<Mesh> mesh = Mesh::buildQuadMesh(meshPoints, horizontalCells,
                            verticalCells, bf, H1Order,
                            H1Order+pToAdd, useTriangles);
  mesh->setPartitionPolicy(Teuchos::rcp(new ZoltanMeshPartitionPolicy("HSFC")));

  ////////////////////////////////////////////////////////////////////
  // INITIALIZE BACKGROUND FLOW FUNCTIONS
  ////////////////////////////////////////////////////////////////////
  BCPtr nullBC = Teuchos::rcp((BC*)NULL);
  RHSPtr nullRHS = Teuchos::rcp((RHS*)NULL);
  IPPtr nullIP = Teuchos::rcp((IP*)NULL);
  SolutionPtr backgroundFlow = Teuchos::rcp(new Solution(mesh, nullBC,
                               nullRHS, nullIP) );

  vector<double> e1(2); // (1,0)
  e1[0] = 1;
  vector<double> e2(2); // (0,1)
  e2[1] = 1;

  FunctionPtr u_prev = Teuchos::rcp( new PreviousSolutionFunction(backgroundFlow, u) );
  FunctionPtr beta = e1 * u_prev + Teuchos::rcp( new ConstantVectorFunction( e2 ) );

  ////////////////////////////////////////////////////////////////////
  // DEFINE BILINEAR FORM
  ////////////////////////////////////////////////////////////////////

  // v:
  // (sigma, grad v)_K - (sigma_hat_n, v)_dK - (u, beta dot grad v) + (u_hat * n dot beta, v)_dK
  bf->addTerm( -u, beta * v->grad());
  bf->addTerm( fhat, v);

  // ==================== SET INITIAL GUESS ==========================
  mesh->registerSolution(backgroundFlow);
  FunctionPtr zero = Teuchos::rcp( new ConstantScalarFunction(0.0) );
  FunctionPtr u0 = Teuchos::rcp( new U0 );

  map<int, Teuchos::RCP<Function> > functionMap;
  functionMap[u->ID()] = u0;

  backgroundFlow->projectOntoMesh(functionMap);
  // ==================== END SET INITIAL GUESS ==========================

  ////////////////////////////////////////////////////////////////////
  // DEFINE INNER PRODUCT
  ////////////////////////////////////////////////////////////////////
  IPPtr ip = Teuchos::rcp( new IP );
  ip->addTerm( v );
  ip->addTerm( beta * v->grad() );

  ////////////////////////////////////////////////////////////////////
  // DEFINE RHS
  ////////////////////////////////////////////////////////////////////
  Teuchos::RCP<RHSEasy> rhs = Teuchos::rcp( new RHSEasy );
  FunctionPtr u_prev_squared_div2 = 0.5 * u_prev * u_prev;
  rhs->addTerm( (e1 * u_prev_squared_div2 + e2 * u_prev) * v->grad());

  ////////////////////////////////////////////////////////////////////
  // DEFINE DIRICHLET BC
  ////////////////////////////////////////////////////////////////////
  Teuchos::RCP<BCEasy> inflowBC = Teuchos::rcp( new BCEasy );

  // Create spatial filters
  SpatialFilterPtr bottomBoundary = Teuchos::rcp( new BottomBoundary );
  SpatialFilterPtr leftBoundary = Teuchos::rcp( new LeftBoundary );
  SpatialFilterPtr rightBoundary = Teuchos::rcp( new LeftBoundary );

  // Create BCs
  FunctionPtr n = Teuchos::rcp( new UnitNormalFunction );
  FunctionPtr u0_squared_div_2 = 0.5 * u0 * u0;
  SimpleFunction* u0Ptr = static_cast<SimpleFunction *>(u0.get());
  double u0Left = u0Ptr->value(0,0);
  double u0Right = u0Ptr->value(1.0,0);
  FunctionPtr leftVal = Teuchos::rcp( new ConstantScalarFunction( -0.5*u0Left*u0Left ) );
  FunctionPtr rightVal = Teuchos::rcp( new ConstantScalarFunction( 0.5*u0Right*u0Right ) );
  inflowBC->addDirichlet(fhat, bottomBoundary, -u0 );
  inflowBC->addDirichlet(fhat, leftBoundary, leftVal );
  inflowBC->addDirichlet(fhat, rightBoundary, rightVal );

  ////////////////////////////////////////////////////////////////////
  // CREATE SOLUTION OBJECT
  ////////////////////////////////////////////////////////////////////
  Teuchos::RCP<Solution> solution = Teuchos::rcp(new Solution(mesh, inflowBC, rhs, ip));
  mesh->registerSolution(solution);

  if (enforceLocalConservation)
  {
    FunctionPtr zero = Teuchos::rcp( new ConstantScalarFunction(0.0) );
    solution->lagrangeConstraints()->addConstraint(fhat == zero);
  }

  ////////////////////////////////////////////////////////////////////
  // DEFINE REFINEMENT STRATEGY
  ////////////////////////////////////////////////////////////////////
  Teuchos::RCP<RefinementStrategy> refinementStrategy;
  refinementStrategy = Teuchos::rcp(new RefinementStrategy(solution,energyThreshold));

  ////////////////////////////////////////////////////////////////////
  // SOLVE
  ////////////////////////////////////////////////////////////////////

  for (int refIndex=0; refIndex<=numRefs; refIndex++)
  {
    double L2Update = 1e7;
    int iterCount = 0;
    while (L2Update > nonlinearRelativeEnergyTolerance && iterCount < maxNewtonIterations)
    {
      solution->solve();
      L2Update = solution->L2NormOfSolutionGlobal(u->ID());
      cout << "L2 Norm of Update = " << L2Update << endl;
      // backgroundFlow->clear();
      backgroundFlow->addSolution(solution, newtonStepSize);
      iterCount++;
    }
    cout << endl;

    // check conservation
    VarPtr testOne = varFactory.testVar("1", CONSTANT_SCALAR);
    // Create a fake bilinear form for the testing
    BFPtr fakeBF = Teuchos::rcp( new BF(varFactory) );
    // Define our mass flux
    FunctionPtr massFlux = Teuchos::rcp( new PreviousSolutionFunction(solution, fhat) );
    LinearTermPtr massFluxTerm = massFlux * testOne;

    Teuchos::RCP<shards::CellTopology> quadTopoPtr = Teuchos::rcp(new shards::CellTopology(shards::getCellTopologyData<shards::Quadrilateral<4> >() ));
    DofOrderingFactory dofOrderingFactory(fakeBF);
    int fakeTestOrder = H1Order;
    DofOrderingPtr testOrdering = dofOrderingFactory.testOrdering(fakeTestOrder, *quadTopoPtr);

    int testOneIndex = testOrdering->getDofIndex(testOne->ID(),0);
    vector< ElementTypePtr > elemTypes = mesh->elementTypes(); // global element types
    map<int, double> massFluxIntegral; // cellID -> integral
    double maxMassFluxIntegral = 0.0;
    double totalMassFlux = 0.0;
    double totalAbsMassFlux = 0.0;
    for (vector< ElementTypePtr >::iterator elemTypeIt = elemTypes.begin(); elemTypeIt != elemTypes.end(); elemTypeIt++)
    {
      ElementTypePtr elemType = *elemTypeIt;
      vector< ElementPtr > elems = mesh->elementsOfTypeGlobal(elemType);
      vector<int> cellIDs;
      for (int i=0; i<elems.size(); i++)
      {
        cellIDs.push_back(elems[i]->cellID());
      }
      FieldContainer<double> physicalCellNodes = mesh->physicalCellNodesGlobal(elemType);
      BasisCachePtr basisCache = Teuchos::rcp( new BasisCache(elemType,mesh) );
      basisCache->setPhysicalCellNodes(physicalCellNodes,cellIDs,true); // true: create side caches
      FieldContainer<double> cellMeasures = basisCache->getCellMeasures();
      FieldContainer<double> fakeRHSIntegrals(elems.size(),testOrdering->totalDofs());
      massFluxTerm->integrate(fakeRHSIntegrals,testOrdering,basisCache,true); // true: force side evaluation
      for (int i=0; i<elems.size(); i++)
      {
        int cellID = cellIDs[i];
        // pick out the ones for testOne:
        massFluxIntegral[cellID] = fakeRHSIntegrals(i,testOneIndex);
      }
      // find the largest:
      for (int i=0; i<elems.size(); i++)
      {
        int cellID = cellIDs[i];
        maxMassFluxIntegral = max(abs(massFluxIntegral[cellID]), maxMassFluxIntegral);
      }
      for (int i=0; i<elems.size(); i++)
      {
        int cellID = cellIDs[i];
        maxMassFluxIntegral = max(abs(massFluxIntegral[cellID]), maxMassFluxIntegral);
        totalMassFlux += massFluxIntegral[cellID];
        totalAbsMassFlux += abs( massFluxIntegral[cellID] );
      }
    }
    if (rank==0)
    {
      cout << endl;
      cout << "largest mass flux: " << maxMassFluxIntegral << endl;
      cout << "total mass flux: " << totalMassFlux << endl;
      cout << "sum of mass flux absolute value: " << totalAbsMassFlux << endl;
      cout << endl;

      stringstream outfile;
      outfile << "burgers_" << refIndex;
      backgroundFlow->writeToVTK(outfile.str(), 5);
    }

    if (refIndex < numRefs)
      refinementStrategy->refine(rank==0); // print to console on rank 0
  }

  return 0;
}
 Real AnalyticTwoAssetBarrierEngine::e4() const {
     return e2()-(2*std::log(barrier()/underlying2()))/(volatility2()*std::sqrt(residualTime()));
 }
void ComputeStiffnessMatrixNullspace::ComputeNullspace(int n, const double * vertexPos, double * basis, int includeRotationalNullspace, int generateOrthogonalBasis)
{
  int basisSize = (includeRotationalNullspace ? 6 : 3);

  memset(basis, 0, sizeof(double) * 3 * n * basisSize);

  // translational part
  for(int i=0; i<n; i++)
    for(int j=0; j<3; j++)
      basis[ELT(3*n, 3*i+j, j)] = 1.0;

  // rotational part
  if (includeRotationalNullspace)
  {
    for(int i=0; i<n; i++)
    {
      Vec3d p(vertexPos[3*i+0], vertexPos[3*i+1], vertexPos[3*i+2]);
      Vec3d e0(1,0,0);
      Vec3d e1(0,1,0);
      Vec3d e2(0,0,1);
      Vec3d r0 = cross(e0, p);
      Vec3d r1 = cross(e1, p);
      Vec3d r2 = cross(e2, p);
      for(int j=0; j<3; j++)
      {
        basis[ELT(3*n, 3*i+j, 3)] = r0[j];
        basis[ELT(3*n, 3*i+j, 4)] = r1[j];
        basis[ELT(3*n, 3*i+j, 5)] = r2[j];
      }
    }
  }

  if (generateOrthogonalBasis)
  {
    // normalize translational vectors
    for(int v=0; v<3; v++)
    {
      double norm2 = 0.0;
      for(int i=0; i<3*n; i++)
        norm2 += basis[ELT(3*n, i, v)] * basis[ELT(3*n, i, v)];
      double invNorm = 1.0 / sqrt(norm2);
      for(int i=0; i<3*n; i++)
        basis[ELT(3*n, i, v)] *= invNorm; 
    }
    
    // ortho-normalize rotational vectors
    if (includeRotationalNullspace)
    {
      for(int v=0; v<3; v++)
      {
        for(int j=0; j<3+v; j++)
        {
          double dotp = 0.0;
          for(int i=0; i<3*n; i++)
            dotp += basis[ELT(3*n, i, j)] * basis[ELT(3*n, i, 3+v)];
          for(int i=0; i<3*n; i++)
            basis[ELT(3*n, i, 3+v)] -= dotp * basis[ELT(3*n, i, j)];
  
          double norm2 = 0.0;
          for(int i=0; i<3*n; i++)
            norm2 += basis[ELT(3*n, i, 3+v)] * basis[ELT(3*n, i, 3+v)];
          double invNorm = 1.0 / sqrt(norm2);
          for(int i=0; i<3*n; i++)
            basis[ELT(3*n, i, 3+v)] *= invNorm; 
        }
      }
    }
  }
}
Beispiel #16
0
int main(int argc, char *argv[]) {
#ifdef HAVE_MPI
  Teuchos::GlobalMPISession mpiSession(&argc, &argv,0);
  choice::MpiArgs args( argc, argv );
#else
  choice::Args args( argc, argv );
#endif
  int commRank = Teuchos::GlobalMPISession::getRank();
  int numProcs = Teuchos::GlobalMPISession::getNProc();

  // Required arguments
  int numRefs = args.Input<int>("--numRefs", "number of refinement steps");
  int norm = args.Input<int>("--norm", "0 = graph\n    1 = robust\n    2 = coupled robust");

  // Optional arguments (have defaults)
  bool enforceLocalConservation = args.Input<bool>("--conserve", "enforce local conservation", false);
  double Re = args.Input("--Re", "Reynolds number", 40);
  double nu = 1./Re;
  double lambda = Re/2.-sqrt(Re*Re/4+4*pi*pi);
  int maxNewtonIterations = args.Input("--maxIterations", "maximum number of Newton iterations", 20);
  int polyOrder = args.Input("--polyOrder", "polynomial order for field variables", 2);
  int deltaP = args.Input("--deltaP", "how much to enrich test space", 2);
  // string saveFile = args.Input<string>("--meshSaveFile", "file to which to save refinement history", "");
  // string replayFile = args.Input<string>("--meshLoadFile", "file with refinement history to replay", "");
  args.Process();

  // if (commRank==0)
  // {
  //   cout << "saveFile is " << saveFile << endl;
  //   cout << "loadFile is " << replayFile << endl;
  // }

  ////////////////////   PROBLEM DEFINITIONS   ///////////////////////
  int H1Order = polyOrder+1;

  ////////////////////   DECLARE VARIABLES   ///////////////////////
  // define test variables
  VarFactory varFactory;
  // VarPtr tau11 = varFactory.testVar("tau11", HGRAD);
  // VarPtr tau12 = varFactory.testVar("tau12", HGRAD);
  // VarPtr tau22 = varFactory.testVar("tau22", HGRAD);
  VarPtr tau1 = varFactory.testVar("tau1", HDIV);
  VarPtr tau2 = varFactory.testVar("tau2", HDIV);
  VarPtr v1 = varFactory.testVar("v1", HGRAD);
  VarPtr v2 = varFactory.testVar("v2", HGRAD);
  VarPtr q = varFactory.testVar("q", HGRAD);

  // define trial variables
  VarPtr u1 = varFactory.fieldVar("u1");
  VarPtr u2 = varFactory.fieldVar("u2");
  // VarPtr sigma11 = varFactory.fieldVar("sigma11");
  // VarPtr sigma12 = varFactory.fieldVar("sigma12");
  // VarPtr sigma22 = varFactory.fieldVar("sigma22");
  VarPtr sigma1 = varFactory.fieldVar("sigma1", VECTOR_L2);
  VarPtr sigma2 = varFactory.fieldVar("sigma2", VECTOR_L2);
  VarPtr u1hat = varFactory.traceVar("u1hat");
  VarPtr u2hat = varFactory.traceVar("u2hat");
  VarPtr t1hat = varFactory.fluxVar("t1hat");
  VarPtr t2hat = varFactory.fluxVar("t2hat");
  VarPtr p = varFactory.fieldVar("p");

  ////////////////////   BUILD MESH   ///////////////////////
  BFPtr bf = Teuchos::rcp( new BF(varFactory) );

  // define nodes for mesh
  FieldContainer<double> meshBoundary(4,2);
  double xmin = -0.5;
  double xmax =  1.0;
  double ymin = -0.5;
  double ymax =  1.5;

  meshBoundary(0,0) =  xmin; // x1
  meshBoundary(0,1) =  ymin; // y1
  meshBoundary(1,0) =  xmax;
  meshBoundary(1,1) =  ymin;
  meshBoundary(2,0) =  xmax;
  meshBoundary(2,1) =  ymax;
  meshBoundary(3,0) =  xmin;
  meshBoundary(3,1) =  ymax;

  int horizontalCells = 6, verticalCells = 8;

  // create a pointer to a new mesh:
  Teuchos::RCP<Mesh> mesh = Mesh::buildQuadMesh(meshBoundary, horizontalCells, verticalCells,
                                                bf, H1Order, H1Order+deltaP);

  ////////////////////////////////////////////////////////////////////
  // INITIALIZE BACKGROUND FLOW FUNCTIONS
  ////////////////////////////////////////////////////////////////////

  BCPtr nullBC = Teuchos::rcp((BC*)NULL);
  RHSPtr nullRHS = Teuchos::rcp((RHS*)NULL);
  IPPtr nullIP = Teuchos::rcp((IP*)NULL);
  SolutionPtr backgroundFlow = Teuchos::rcp(new Solution(mesh, nullBC, nullRHS, nullIP) );

  vector<double> e1(2); // (1,0)
  e1[0] = 1;
  vector<double> e2(2); // (0,1)
  e2[1] = 1;

  FunctionPtr u1_prev = Function::solution(u1, backgroundFlow);
  FunctionPtr u2_prev = Function::solution(u2, backgroundFlow);
  FunctionPtr sigma1_prev = Function::solution(sigma1, backgroundFlow);
  FunctionPtr sigma2_prev = Function::solution(sigma2, backgroundFlow);
  FunctionPtr p_prev = Function::solution(p, backgroundFlow);
  // FunctionPtr sigma11_prev = Function::solution(sigma11, backgroundFlow);
  // FunctionPtr sigma12_prev = Function::solution(sigma12, backgroundFlow);
  // FunctionPtr sigma22_prev = Function::solution(sigma22, backgroundFlow);

  FunctionPtr zero = Teuchos::rcp( new ConstantScalarFunction(0.0) );
  FunctionPtr one = Teuchos::rcp( new ConstantScalarFunction(1.0) );
  FunctionPtr u1Exact     = Teuchos::rcp( new ExactU1(lambda) );
  FunctionPtr u2Exact     = Teuchos::rcp( new ExactU2(lambda) );
  // FunctionPtr beta = e1 * u1_prev + e2 * u2_prev;

  // ==================== SET INITIAL GUESS ==========================
  map<int, Teuchos::RCP<Function> > functionMap;
  functionMap[u1->ID()] = u1Exact;
  functionMap[u2->ID()] = u2Exact;
  // functionMap[sigma1->ID()] = Function::vectorize(zero,zero);
  // functionMap[sigma2->ID()] = Function::vectorize(zero,zero);
  // functionMap[p->ID()] = zero;

  backgroundFlow->projectOntoMesh(functionMap);

  ////////////////////   DEFINE BILINEAR FORM   ///////////////////////

  // // stress equation
  bf->addTerm( 1./nu*sigma1, tau1 );
  bf->addTerm( 1./nu*sigma2, tau2 );
  bf->addTerm( u1, tau1->div() );
  bf->addTerm( u2, tau2->div() );
  bf->addTerm( -u1hat, tau1->dot_normal() );
  bf->addTerm( -u2hat, tau2->dot_normal() );
  // bf->addTerm( 1./(2*nu)*sigma11, tau11 );
  // bf->addTerm( 1./(2*nu)*sigma12, tau12 );
  // bf->addTerm( 1./(2*nu)*sigma12, tau12 );
  // bf->addTerm( 1./(2*nu)*sigma22, tau22 );
  // bf->addTerm( u1, tau11->dx() );
  // bf->addTerm( u1, tau12->dy() );
  // bf->addTerm( u2, tau12->dx() );
  // bf->addTerm( u2, tau22->dy() );
  // bf->addTerm( -u1hat, tau11->times_normal_x() );
  // bf->addTerm( -u1hat, tau12->times_normal_y() );
  // bf->addTerm( -u2hat, tau12->times_normal_x() );
  // bf->addTerm( -u2hat, tau22->times_normal_y() );

  // momentum equation
  bf->addTerm( -2.*u1_prev*u1, v1->dx() );
  bf->addTerm( -u2_prev*u1, v1->dy() );
  bf->addTerm( -u1_prev*u2, v1->dy() );
  bf->addTerm( -u2_prev*u1, v2->dx() );
  bf->addTerm( -u1_prev*u2, v1->dy() );
  bf->addTerm( -2.*u2_prev*u2, v2->dy() );
  bf->addTerm( -p, v1->dx() );
  bf->addTerm( -p, v2->dy() );
  // bf->addTerm( sigma11, v1->dx() );
  // bf->addTerm( sigma12, v1->dy() );
  // bf->addTerm( sigma12, v2->dx() );
  // bf->addTerm( sigma22, v2->dy() );
  bf->addTerm( sigma1, v1->grad() );
  bf->addTerm( sigma2, v2->grad() );
  bf->addTerm( t1hat, v1);
  bf->addTerm( t2hat, v2);

  // continuity equation
  bf->addTerm( -u1, q->dx() );
  bf->addTerm( -u2, q->dy() );
  bf->addTerm( u1hat, q->times_normal_x() );
  bf->addTerm( u2hat, q->times_normal_y() );

  ////////////////////   SPECIFY RHS   ///////////////////////
  Teuchos::RCP<RHSEasy> rhs = Teuchos::rcp( new RHSEasy );

  // stress equation
  rhs->addTerm( -u1_prev * tau1->div() );
  rhs->addTerm( -u2_prev * tau2->div() );

  // momentum equation
  rhs->addTerm( 2.*u1_prev*u1_prev * v1->dx() );
  rhs->addTerm( u2_prev*u1_prev    * v1->dy() );
  rhs->addTerm( u1_prev*u2_prev    * v1->dy() );
  rhs->addTerm( u2_prev*u1_prev    * v2->dx() );
  rhs->addTerm( u1_prev*u2_prev    * v1->dy() );
  rhs->addTerm( 2.*u2_prev*u2_prev * v2->dy() );
  // rhs->addTerm( p_prev             * v1->dx() );
  // rhs->addTerm( p_prev             * v2->dy() );
  // rhs->addTerm( -sigma1_prev       * v1->grad() );
  // rhs->addTerm( -sigma2_prev       * v2->grad() );

  // rhs->addTerm( -sigma11_prev * v1->dx() );
  // rhs->addTerm( -sigma12_prev * v1->dy() );
  // rhs->addTerm( -sigma12_prev * v2->dx() );
  // rhs->addTerm( -sigma22_prev * v2->dy() );

  // continuity equation
  rhs->addTerm( u1_prev * q->dx() );
  rhs->addTerm( u2_prev * q->dy() );

  ////////////////////   DEFINE INNER PRODUCT(S)   ///////////////////////
  IPPtr ip = Teuchos::rcp(new IP);
  if (norm == 0)
  {
    ip = bf->graphNorm();
  }
  else if (norm == 1)
  {
    // ip = bf->l2Norm();
  }

  ////////////////////   CREATE BCs   ///////////////////////
  Teuchos::RCP<BCEasy> bc = Teuchos::rcp( new BCEasy );
  // Teuchos::RCP<PenaltyConstraints> pc = Teuchos::rcp( new PenaltyConstraints );
  SpatialFilterPtr left = Teuchos::rcp( new ConstantXBoundary(-0.5) );
  SpatialFilterPtr right = Teuchos::rcp( new ConstantXBoundary(1) );
  SpatialFilterPtr top = Teuchos::rcp( new ConstantYBoundary(-0.5) );
  SpatialFilterPtr bottom = Teuchos::rcp( new ConstantYBoundary(1.5) );
  bc->addDirichlet(u1hat, left, u1Exact);
  bc->addDirichlet(u2hat, left, u2Exact);
  bc->addDirichlet(u1hat, right, u1Exact);
  bc->addDirichlet(u2hat, right, u2Exact);
  bc->addDirichlet(u1hat, top, u1Exact);
  bc->addDirichlet(u2hat, top, u2Exact);
  bc->addDirichlet(u1hat, bottom, u1Exact);
  bc->addDirichlet(u2hat, bottom, u2Exact);
  
  // zero mean constraint on pressure
  bc->addZeroMeanConstraint(p);

  // pc->addConstraint(u1hat*u2hat-t1hat == zero, top);
  // pc->addConstraint(u2hat*u2hat-t2hat == zero, top);

  Teuchos::RCP<Solution> solution = Teuchos::rcp( new Solution(mesh, bc, rhs, ip) );
  // solution->setFilter(pc);

  // if (enforceLocalConservation) {
  //   solution->lagrangeConstraints()->addConstraint(u1hat->times_normal_x() + u2hat->times_normal_y() == zero);
  // }

  // ==================== Register Solutions ==========================
  mesh->registerSolution(solution);
  mesh->registerSolution(backgroundFlow);

  // Teuchos::RCP< RefinementHistory > refHistory = Teuchos::rcp( new RefinementHistory );
  // mesh->registerObserver(refHistory);

  ////////////////////   SOLVE & REFINE   ///////////////////////
  double energyThreshold = 0.2; // for mesh refinements
  RefinementStrategy refinementStrategy( solution, energyThreshold );
  VTKExporter exporter(backgroundFlow, mesh, varFactory);
  stringstream outfile;
  outfile << "kovasznay" << "_" << 0;
  exporter.exportSolution(outfile.str());

  double nonlinearRelativeEnergyTolerance = 1e-5; // used to determine convergence of the nonlinear solution
  for (int refIndex=0; refIndex<=numRefs; refIndex++)
  {
    double L2Update = 1e10;
    int iterCount = 0;
    while (L2Update > nonlinearRelativeEnergyTolerance && iterCount < maxNewtonIterations)
    {
      solution->solve(false);
      double u1L2Update = solution->L2NormOfSolutionGlobal(u1->ID());
      double u2L2Update = solution->L2NormOfSolutionGlobal(u2->ID());
      L2Update = sqrt(u1L2Update*u1L2Update + u2L2Update*u2L2Update);

      // Check local conservation
      if (commRank == 0)
      {
        cout << "L2 Norm of Update = " << L2Update << endl;

        // if (saveFile.length() > 0) {
        //   std::ostringstream oss;
        //   oss << string(saveFile) << refIndex ;
        //   cout << "on refinement " << refIndex << " saving mesh file to " << oss.str() << endl;
        //   refHistory->saveToFile(oss.str());
        // }
      }

      // line search algorithm
      double alpha = 1.0;
      backgroundFlow->addSolution(solution, alpha);
      iterCount++;
    }

    if (commRank == 0)
    {
      stringstream outfile;
      outfile << "kovasznay" << "_" << refIndex+1;
      exporter.exportSolution(outfile.str());
    }

    if (refIndex < numRefs)
      refinementStrategy.refine(commRank==0); // print to console on commRank 0
  }

  return 0;
}
Beispiel #17
0
int main()
{
    {
        // Check the default constructor
        EntityRef ref;
    }

    {
        // Check the default constructor initialises to NULL via get
        EntityRef ref;

        assert(ref.get() == 0);
    }

    {
        // Check the default constructor initialises to NULL via dereference
        EntityRef ref;

        assert(&(*ref) == 0);
    }

    {
        // Check the default constructor initialises to NULL via ->
        EntityRef ref;

        assert(ref.operator->() == 0);
    }

    {
        // Check the default constructor initialises to NULL via ==
        EntityRef ref;

        assert(ref == 0);
    }

    {
        // Check the initialising constructor via get
        Entity * e = new Entity("1", 1);
        EntityRef ref(e);

        assert(ref.get() == e);
    }

    {
        // Check the initialising constructor via dereference
        Entity * e = new Entity("1", 1);
        EntityRef ref(e);

        assert(&(*ref) == e);
    }

    {
        // Check the initialising constructor via ->
        Entity * e = new Entity("1", 1);
        EntityRef ref(e);

        assert(ref.operator->() == e);
    }

    {
        // Check the initialising constructor via ==
        Entity * e = new Entity("1", 1);
        EntityRef ref(e);

        assert(ref == e);
    }

    {
        // Check the copy constructor
        Entity * e = new Entity("1", 1);
        EntityRef ref(e);
        EntityRef ref2(ref);

        assert(ref2.get() == e);
    }

    {
        // Check the comparison operator
        Entity * e = new Entity("1", 1);
        EntityRef ref(e);
        EntityRef ref2(e);

        assert(ref == ref2);
    }

    {
        // Check the comparison operator
        Entity * e = new Entity("1", 1);
        Entity * e2 = new Entity("2", 2);
        EntityRef ref(e);
        EntityRef ref2(e2);

        assert(!(ref == ref2));
    }

#if 0
    // These tests should be included should we add operator!=
    {
        // Check the comparison operator
        Entity e("1", 1);
        EntityRef ref(&e);
        EntityRef ref2(&e);

        assert(!(ref != ref2));
    }

    {
        // Check the comparison operator
        Entity e("1", 1);
        Entity e2("2", 2);
        EntityRef ref(&e);
        EntityRef ref2(&e2);

        assert(ref != ref2);
    }
#endif

    {
        // Check the less than operator
        Entity * e = new Entity("1", 1);
        EntityRef ref(e);
        EntityRef ref2(e);

        assert(!(ref < ref2) && !(ref2 < ref));
    }

    {
        // Check the less than operator
        Entity * e = new Entity("1", 1);
        Entity * e2 = new Entity("2", 2);
        EntityRef ref(e);
        EntityRef ref2(e2);

        assert(ref < ref2 || ref2 < ref);
    }

    {
        // Check the assignment operator
        Entity * e = new Entity("1", 1);
        EntityRef ref;

        ref = EntityRef(e);

        assert(ref.get() == e);
    }

    {
        // Check that destroying the Entity makes the reference null.
        Entity e("1", 1);
        Entity * container = new Entity("2", 2);

        // Set the location of the entity being tested, as destroy requires it.
        e.m_location.m_loc = container;
        // Make sure the container has a contains structure, as destroy
        // requires it.
        container->m_contains = new LocatedEntitySet;
        // Increment the refcount on the container, else the tested Entity's
        // destructor will delete it.
        container->incRef();

        EntityRef ref(&e);

        assert(ref.get() == &e);
        e.destroy();
        assert(ref.get() == 0);
    }

    checkSignal();
}