Esempio n. 1
0
void maximizeArea(const MarkerPoint* nPoints, int nNumPoints, int nIdx0, int nIdx1, int nIdx2, int& nIdxMax) {
    int maxArea = 0;

    for (int i = 0; i < nIdx0; i++) {
        int area = calcArea(nPoints[i], nPoints[nIdx0], nPoints[nIdx1], nPoints[nIdx2]);
        if (area > maxArea) {
            maxArea = area;
            nIdxMax = i;
        }
    }

    for (int i = nIdx0 + 1; i < nIdx1; i++) {
        int area = calcArea(nPoints[nIdx0], nPoints[i], nPoints[nIdx1], nPoints[nIdx2]);
        if (area > maxArea) {
            maxArea = area;
            nIdxMax = i;
        }
    }

    for (int i = nIdx1 + 1; i < nIdx2; i++) {
        int area = calcArea(nPoints[nIdx0], nPoints[nIdx1], nPoints[i], nPoints[nIdx2]);
        if (area > maxArea) {
            maxArea = area;
            nIdxMax = i;
        }
    }

    for (int i = nIdx2 + 1; i < nNumPoints; i++) {
        int area = calcArea(nPoints[nIdx0], nPoints[nIdx1], nPoints[nIdx2], nPoints[i]);
        if (area > maxArea) {
            maxArea = area;
            nIdxMax = i;
        }
    }
}
Esempio n. 2
0
Vector		Triangle::getNormalVector(const Point& intersectPoint,
					const Vector& viewVector) const
{
  if (_normalSet == false)
    {
      double	cosA = viewVector * _normal;

      cosA = cosA / (viewVector.getNorm());
      if (cosA <= 0)
	return (_normal * -1);
      return (_normal);
      (void)intersectPoint;
    }
  else
    {
      double
	aT = calcArea(_absolutePosition, _vertex1, _vertex2),
	aB = calcArea(intersectPoint, _absolutePosition, _vertex1),
	aC = calcArea(intersectPoint, _vertex2, _vertex1),
	aA = aT - aB - aC;
      double
	c1 = aA / aT,
	c2 = aB / aT,
	c3 = aC / aT;
      Vector	normal = _normal0 * c3 + _normal1 * c1 + _normal2 * c2;
      normal.normalize();
      return (normal);
    }
}
Esempio n. 3
0
bool OverlapTester::isPointInTriangle(Vector2D &p, Triangle &tr)
{
    float pX = p.getX();
    float pY = p.getY();
    float p0X = tr.getPointA().getX();
    float p0Y = tr.getPointA().getY();
    float p1X = tr.getPointB().getX();
    float p1Y = tr.getPointB().getY();
    float p2X = tr.getPointC().getX();
    float p2Y = tr.getPointC().getY();
    
    /* Calculate area of triangle ABC */
    float a = calcArea(p0X, p0Y, p1X, p1Y, p2X, p2Y);
    
    /* Calculate area of triangle PBC */
    float a1 = calcArea (pX, pY, p1X, p1Y, p2X, p2Y);
    
    /* Calculate area of triangle PAC */
    float a2 = calcArea (p0X, p0Y, pX, pY, p2X, p2Y);
    
    /* Calculate area of triangle PAB */
    float a3 = calcArea (p0X, p0Y, p1X, p1Y, pX, pY);
    
    float aSum = a1 + a2 + a3;
    
    /* Check if sum of A1, A2 and A3 is same as A */
    return a < (aSum + 0.1f) && a > (aSum - 0.1f);
}
Esempio n. 4
0
int main(int argc, char** argv) {
    printf("|%10s|%10s|%10s|%10s|\n", "a", "b", "h", "Area");
    printf("%10.2f|\n", calcArea(5, 7, 12));
    printf("%10.2f|\n", calcArea(2, 1, 33));
    printf("%10.2f|\n", calcArea(8.5, 4.3, 2.7));
    printf("%10.2f|\n", calcArea(100, 200, 300));
    printf("%10.2f|\n", calcArea(0.222, 0.333, 0.555));
    return (EXIT_SUCCESS);
}
bool calcWeights(const SbVec3f& v1, const SbVec3f& v2, const SbVec3f& v3,
                 const SbVec3f& p, float& w0, float& w1, float& w2)
{
    float fAreaABC = calcArea(v1,v2,v3);
    float fAreaPBC = calcArea(p,v2,v3);
    float fAreaPCA = calcArea(p,v3,v1);
    float fAreaPAB = calcArea(p,v1,v2);

    w0=fAreaPBC/fAreaABC;
    w1=fAreaPCA/fAreaABC;
    w2=fAreaPAB/fAreaABC;

    return fabs(w0+w1+w2-1.0f)<0.001f;
}
Esempio n. 6
0
void RDirNode::calcRadius() {
    calcArea();

    // was gGourceMinDirSize
    this->dir_radius = std::max(1.0f, (float)sqrt(dir_area)) * gGourceDirPadding;
    this->dir_radius_sqrt = sqrt(dir_radius);
}
Esempio n. 7
0
void		Triangle::getMappedCoords(const Point& intersectPoint,
					  double& x, double &y) const
{
  double	areaA = calcArea(_absolutePosition, _vertex1, intersectPoint);
  double	areaB = calcArea(_vertex1, _vertex2, intersectPoint);
  double	areaC = calcArea(_vertex2, _absolutePosition, intersectPoint);
  double	sum = areaA + areaB + areaC;
  double	b = areaC / sum;
  double	c = areaA / sum;
  double	a = areaB / sum;
  Point		texturePoint = _textureVertex1 +
    (b * _textureV1 + c * _textureV2) / (a + b + c);

  x = texturePoint._x;
  y = -texturePoint._y;
}
Esempio n. 8
0
//Fill out the m_i array with the inverse of the node masses
void calcMasses(myGlobals &g) {
  int i;
  double *m_i=g.m_i;
  //Zero out node masses
  for (i=0;i<g.nnodes;i++) m_i[i]=0.0;
  //Add mass from surrounding triangles:
  for (i=0;i<g.nelems;i++) {
    if(g.validElem[i]){
      int n1=g.conn[3*i+0];
      int n2=g.conn[3*i+1];
      int n3=g.conn[3*i+2];
      double area=calcArea(g,i);
      //		if (1 || i%100==0) CkPrintf("Triangle %d (%d %d %d) has area %.3g\n",i,n1,n2,n3,area);
      double mass=0.333*density*(thickness*area);
      m_i[n1]+=mass;
      m_i[n2]+=mass;
      m_i[n3]+=mass;
    }
  }
  //Include mass from other processors
  FEM_Update_field(g.m_i_fid,m_i);
  //Invert masses to get m_i
  for (i=0;i<g.nnodes;i++) {
    double mass=m_i[i];
    if (mass<1.0e-10) m_i[i]=1.0; //Disconnected node (!)
    else m_i[i]=1.0/mass;
  }
}
Esempio n. 9
0
	// Hit test triangle
	bool Triangle::contains( const Vec2f & position ) const
	{

		// Get area values using input position and two points from triangle
		float area0 = calcArea( mDestination, mApex, position );
		float area1 = calcArea( mApex, mOrigin, position );
		float area2 = calcArea( mOrigin, mDestination, position );

		// Sum the absolute values of each area
		float areaSum = math<float>::abs( area0 ) + math<float>::abs( area1 ) + math<float>::abs( area2 );

		// If sum of the three areas is the same as the triangle's 
		// area, the point is inside
		return areaSum == mArea;

	}
Esempio n. 10
0
// Name:		Hexagon()
// Author:		Erick Narvaez
// Summary:		Contructor for the Hexagon class. Sets the value of the following properties for the
//				object: sideLength, area, slice area, and size enums.
// Arguments:	
//				1) double length (input). The side length of the hexagon object. 
Hexagon::Hexagon(double length) {
	sideLength = length;
	whole = MEDIUM;
	slice = MEDIUM;
	calcArea();
	calcSliceArea();
}
Esempio n. 11
0
int Solution::maximalRectangle(vector<vector<int> > &A) {
    // Do not write main() function.
    // Do not read input, instead use the arguments to the function.
    // Do not print the output, instead return values as specified
    // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
    int row = A.size();
    int col = A[0].size();
    //vector<vector<int> > dp(row, vector<int>(col, 0));
    int dp[row][col];
    
    for(int i=0; i<row; i++){
        for(int j=0; j<col; ++j){
            if(A[i][j]==1){
                if(i==0)
                    dp[i][j] = 1;
                else
                    dp[i][j] = 1 + dp[i-1][j];
            }
            else{
                dp[i][j] = 0;
            }
        }
    }
    
    int ans = 0;
    for(int i = 0; i<row; ++i){
        ans = max(ans, calcArea(dp[i], col));
        //cout<<i<<" "<<ans<<endl;
    }
    return ans;
}
void CompressionChamber::calcInicProp(Mechanism mech, double sucChambPress, double sucChambRho, double sucChambExpTemp)
{
	calcArea();

	if(mech.getMech() == "crank_rod")
	{
		calcDispVol(2*mech.getEccent());
	}
	else
	if(mech.getMech() == "sinusoidal")
	{
		calcDispVol(mech.getStroke());
	}

	calcVol(mech.getSupDeadPt(), mech.getPos()); 
	refrig.setTemp(sucChambExpTemp);
	refrig.setPress(sucChambPress);
	
	refrig.calcRho();
	
	refrig.setRho(sucChambRho);
	refrig.calcMass(vol);

	calcPistDiam();

	calcContactLength();
}
Esempio n. 13
0
//O(n*log(n))
void solveProblem(int n) {
	if (n < 3)
		return;//we can't construct a convex hull with less than 3 vertices
	
	std::sort(vertices+1, vertices+n, comparerCCW);//sort vertices in CCW in relation to vertices[0](lowest vertex)
	std::stack<Vertex> S;
	
	S.push(vertices[0]);
	S.push(vertices[1]);
	Vertex stackTop;
	for (int i = 2; i < n; i++) {
		stackTop = S.top();
		S.pop();
		while (crossProduct(S.top(), stackTop, vertices[i]) < 0) {
			stackTop = S.top();
			S.pop();
		}
		S.push(stackTop); //insert again the element that didn't passed the test
		S.push(vertices[i]);
	}
	//From this moment on the convex hull is in the stack...

	//Now we mark the id's that are present in convex hull
	char marked[N];
	memset(marked, 0, n * sizeof(char));
	while (!S.empty()) {
		marked[S.top().id] = 1;
		S.pop();
	}

	//Now it's time to calculate areas of poligons inside convex hull
	int firstVertex; //index of first vertex of polygon INSIDE conevex hull
	bool startPol = false; //make true starting a new polygon
	double area;
	int polysDetected = 0;
	for (int i = 0; i < n; i++) {
		if (marked[i] == 0) {
			if (!startPol) {
				startPol = true;
				firstVertex = i-1; //id of first vertex INSIDE convex hull
			}
		}
		else {
			if (startPol) {
				startPol = false; //close the polygon
				//calc area of polygon
				area = calcArea(firstVertex, i);
				printf("%d %.1f\n", polysDetected++, area);
			}
		}
	}

	if (startPol) {
		//in this case the polygon isn't closed
		//calc area of polygon
		area = calcArea2(firstVertex, n); //this is a variation of calcArea
		printf("%d %.1f\n", polysDetected, area);
	}
}
Esempio n. 14
0
int
main(int argc, char * argv[])
{
    printf("\nCalculo de la Integral");
    printf("\nMetodo de los Trapecios");
    printf("\nIntervalo [a, b]");
    printf("\nNumero de Trapecios 'n' ");

    //int n;
    int a, b;	
    double deltX;

    printf("\n\nIngresar el valor de a: ");
    scanf("%d", &a);
    printf("\nIngresar el valor de b: ");
    scanf("%d", &b);	    
    //printf("\nIngresar el valor de n: ");
    //scanf("%f", &n);

    //deltX = (b - a) / n;

    //Areas
    double A1 = f(a) + f(b);
    double AT;
    double A2;

    printf("\n    n      Valorp       Valorm       Error Relativo");
    deltX = (double)(b - a) / 50.0000;
    A2 = calcArea(50, a, deltX);
    AT = (deltX / 2) * (A1 + A2);
    printf("\n   50   %f      184.2016       %f ", AT, error(AT));
    deltX = (double)(b - a) / 100.0000;
    A2 = calcArea(100, a, deltX);
    AT = (deltX / 2) * (A1 + A2);
    printf("\n   1000   %f      184.2016       %f ", AT, error(AT));
    deltX = (double)(b - a) / 5000.0000;
    A2 = calcArea(5000, a, deltX);
    AT = (deltX / 2) * (A1 + A2);
    printf("\n   5000   %f      184.2016       %f ", AT, error(AT));
    
    printf("\n");
    return 0;
}//main
float FostroDescriptor::calcPerimeter(FostroImage* image){
	FostroErosionFilter erosionFilter(3,3);
	FostroImage* tmpImage = erosionFilter.applyFilter(image, GRAY);
	tmpImage->setFilePath("erosionPerim.png");
	tmpImage->saveImage();

	float erodedArea = calcArea(tmpImage);

	return (area - erodedArea);
}
Esempio n. 16
0
// Check the quality of triangle i
void checkTriangle(myGlobals &g, int i)
{
  double area=calcArea(g,i);
  if (area<0) {
    CkError("Triangle %d of chunk %d is inverted! (area=%g)\n",
	    i,FEM_My_partition(),area);
    CkAbort("Inverted triangle");
  }
  if (area<1.0e-15) {
    CkError("Triangle %d of chunk %d is a sliver!\n",i,FEM_My_partition());
    CkAbort("Sliver triangle");
  }
}
static double calcMaxArea( GENERAL_COLLECTOR& aCollector, KICAD_T aType )
{
    double best = 0.0;

    for( int i = 0; i < aCollector.GetCount(); i++ )
    {
        BOARD_ITEM* item = aCollector[i];
        if( item->Type() == aType )
            best = std::max(best, calcArea( item ) );

    }

    return best;
}
Esempio n. 18
0
void Polygon::calcCentre()
{
	if ( !area && n_coords )
		calcArea();
	double float_x = 0.0L, float_y = 0.0L;
	for ( int i = 0, j = n_coords-1; i < n_coords; j = i++ )
	{
		float_x += ((coords[i].Y()-coords[j].Y())*((coords[i].X()*2)+(coords[i].X()*coords[j].X())+(coords[j].X()*2)));
		float_y += ((coords[j].X()-coords[i].X())*((coords[i].Y()*2)+(coords[i].Y()*coords[j].Y())+(coords[j].Y()*2)));
	}
	float_x /= (6*area);
	float_y /= (6*area);
	//printf( "%.2f,%.2f\n", float_x, float_y );
	centre = Coord( (int)round(float_x), (int)round(float_y) );
}
static double calcMinArea( GENERAL_COLLECTOR& aCollector, KICAD_T aType )
{
    double best = std::numeric_limits<double>::max();

    if( !aCollector.GetCount() )
        return 0.0;

    for( int i = 0; i < aCollector.GetCount(); i++ )
    {
        BOARD_ITEM* item = aCollector[i];
        if( item->Type() == aType )
            best = std::min( best, calcArea( item ) );

    }

    return best;
}
Esempio n. 20
0
int main(void)
{
  int seed, n;
  Triangle tri[100];
  printf("乱数 seed : ");
  scanf("%d", &seed);
  srand(seed);

  printf("3角形の個数 : ");
  scanf("%d", &n);

  getTriangle(n, tri);
  calcArea(n, tri);
  sortTriangle(n, tri);
  prtTriangle(n, tri);

  return 0;
}
Esempio n. 21
0
int main()
{
    double ans = 0;
    int n;
    printf("Enter number of vertices \n");
    scanf("%d", &n);
    point points[n];

    for (int i = 0; i < n; i++)
    {
        scanf("%lf %lf", &points[i].x, &points[i].y);
    }

    for (int i = 2; i < n; i++)
    {
        ans += calcArea(points[0], points[i - 1], points[i]);
    }

    printf("\n Answer is: %lf\n", ans);
}
Esempio n. 22
0
Polygon::Polygon( int p_n_coords, const Coord *p_coords ) : n_coords( p_n_coords )
{
	coords = new Coord[n_coords];

	int min_x = -1;
	int max_x = -1;
	int min_y = -1;
	int max_y = -1;
	for( int i = 0; i < n_coords; i++ )
	{
		coords[i] = p_coords[i];
		if ( min_x == -1 || coords[i].X() < min_x )
			min_x = coords[i].X();
		if ( max_x == -1 || coords[i].X() > max_x )
			max_x = coords[i].X();
		if ( min_y == -1 || coords[i].Y() < min_y )
			min_y = coords[i].Y();
		if ( max_y == -1 || coords[i].Y() > max_y )
			max_y = coords[i].Y();
	}
	extent = Box( min_x, min_y, max_x, max_y );
	calcArea();
	calcCentre();
}
void FostroDescriptor::calcDescriptors(FostroImage* image, int c){
	area = calcArea(image);
	perimeter = calcPerimeter(image);
	calcPerimeter2OverArea(image);
	calcMomentInvariants(image);
}
Esempio n. 24
0
std::string BaseLoop::decodeMessage(const std::string& data)
{
	std::ostringstream result;
	std::string cycdata;
	int index;

	// prepare data
	std::string token;
	std::istringstream stream(data);
	std::vector<std::string> cmd;

	while (std::getline(stream, token, ' ') != 0)
		cmd.push_back(token);

	if (cmd.size() == 0)
		return "command missing";

	switch (getCase(cmd[0])) {
	case notfound:
		result << "command not found";
		break;

	case get:
		if (cmd.size() < 3 || cmd.size() > 4) {
			result << "usage: 'get class cmd (sub)'";
			break;
		}

		index = m_commands->findCommand(data);

		if (index >= 0) {

			std::string type = m_commands->getType(index);
			std::string ebusCommand(A.getParam<const char*>("p_address"));
			ebusCommand += m_commands->getEbusCommand(index);
			std::transform(ebusCommand.begin(), ebusCommand.end(), ebusCommand.begin(), tolower);

			L.log(bas, trace, " type: %s msg: %s", type.c_str(), ebusCommand.c_str());
			// send busCommand
			m_ebusloop->addBusCommand(new BusCommand(type, ebusCommand));
			BusCommand* busCommand = m_ebusloop->getBusCommand();

			if (busCommand->getResult().c_str()[0] != '-') {
				// decode data
				Command* command = new Command(index, (*m_commands)[index], busCommand->getResult());

				// return result
				result << command->calcResult(cmd);

				delete command;
			} else {
				L.log(bas, error, " %s", busCommand->getResult().c_str());
				result << busCommand->getResult();
			}


			delete busCommand;

		} else {
			result << "ebus command not found";
		}

		break;

	case set:
		if (cmd.size() != 4) {
			result << "usage: 'set class cmd value'";
			break;
		}

		index = m_commands->findCommand(data.substr(0, data.find(cmd[3])-1));

		if (index >= 0) {

			std::string type = m_commands->getType(index);
			std::string ebusCommand(A.getParam<const char*>("p_address"));
			ebusCommand += m_commands->getEbusCommand(index);

			// encode data
			Command* command = new Command(index, (*m_commands)[index], cmd[3]);
			std::string value = command->calcData();
			if (value[0] != '-') {
				ebusCommand += value;
			} else {
				L.log(bas, error, " %s", value.c_str());
				delete command;
				break;
			}

			std::transform(ebusCommand.begin(), ebusCommand.end(), ebusCommand.begin(), tolower);

			L.log(bas, event, " type: %s msg: %s", type.c_str(), ebusCommand.c_str());
			// send busCommand
			m_ebusloop->addBusCommand(new BusCommand(type, ebusCommand));
			BusCommand* busCommand = m_ebusloop->getBusCommand();

			if (busCommand->getResult().c_str()[0] != '-') {
				// decode result
				if (busCommand->getResult().substr(busCommand->getResult().length()-8) == "00000000")
					result << "done";
				else
					result << "error";

			} else {
				L.log(bas, error, " %s", busCommand->getResult().c_str());
				result << busCommand->getResult();
			}

			delete busCommand;
			delete command;

		} else {
			result << "ebus command not found";
		}

		break;

	case cyc:
		if (cmd.size() < 3 || cmd.size() > 4) {
			result << "usage: 'cyc class cmd (sub)'";
			break;
		}

		index = m_commands->findCommand(data);

		if (index >= 0) {
			// get cycdata
			cycdata = m_cycdata->getData(index);
			if (cycdata != "") {
				// decode data
				Command* command = new Command(index, (*m_commands)[index], cycdata);

				// return result
				result << command->calcResult(cmd);

				delete command;
			} else {
				result << "no data stored";
			}
		} else {
			result << "ebus command not found";
		}

		break;

	case hex:
		if (cmd.size() != 3) {
			result << "usage: 'hex type value' (value: ZZPBSBNNDx)";
			break;
		}

		if ((strcasecmp(cmd[1].c_str(), "MS") == 0)
		||  (strcasecmp(cmd[1].c_str(), "MM") == 0)
		||  (strcasecmp(cmd[1].c_str(), "BC") == 0)) {

			std::string type = cmd[1];
			std::string ebusCommand(A.getParam<const char*>("p_address"));
			cmd[2].erase(std::remove_if(cmd[2].begin(), cmd[2].end(), isspace), cmd[2].end());
			ebusCommand += cmd[2];
			std::transform(ebusCommand.begin(), ebusCommand.end(), ebusCommand.begin(), tolower);

			L.log(bas, trace, " type: %s msg: %s", type.c_str(), ebusCommand.c_str());
			// send busCommand
			m_ebusloop->addBusCommand(new BusCommand(type, ebusCommand));
			BusCommand* busCommand = m_ebusloop->getBusCommand();

			if (busCommand->getResult().c_str()[0] == '-')
				L.log(bas, error, " %s", busCommand->getResult().c_str());

			result << busCommand->getResult();

			delete busCommand;
		} else {
			result << "specified message type is incorrect";
		}

		break;

	case dump:
		if (cmd.size() != 2) {
			result << "usage: 'dump state' (state: on|off)";
			break;
		}

		if (cmd[1] == "on")  m_ebusloop->dump(true);
		if (cmd[1] == "off") m_ebusloop->dump(false);
		result << "done";
		break;

	case logarea:
		if (cmd.size() != 2) {
			result << "usage: 'logarea area,area,..' (area: bas|net|bus|cyc|all)";
			break;
		}

		L.getSink(0)->setAreas(calcArea(cmd[1]));
		result << "done";
		break;

	case loglevel:
		if (cmd.size() != 2) {
			result << "usage: 'loglevel level' (level: error|event|trace|debug)";
			break;
		}

		L.getSink(0)->setLevel(calcLevel(cmd[1]));
		result << "done";
		break;

	case help:
		result << "commands:" << std::endl
		       << " get       - fetch ebus data       'get class cmd (sub)'" << std::endl
		       << " set       - set ebus values       'set class cmd value'" << std::endl
		       << " cyc       - fetch cycle data      'cyc class cmd (sub)'" << std::endl
		       << " hex       - send given hex value  'hex type value' (value: ZZPBSBNNDx)" << std::endl
		       << " dump      - change dump state     'dump state' (state: on|off)" << std::endl
		       << " logarea   - change log area       'logarea area,area,..' (area: bas|net|bus|cyc|all)" << std::endl
		       << " loglevel  - change log level      'loglevel level' (level: error|event|trace|debug)" << std::endl
		       << " quit      - close connection" << std::endl
		       << " help      - print this page";
		break;

	default:
		break;
	}

	return result.str();
}
Esempio n. 25
0
extern "C" void
driver(void)
{
  int ignored;
  int i, count;  
  int myChunk=FEM_My_partition();
  
  /*Add a refinement object to FEM array*/
  CkPrintf("[%d] begin init\n",myChunk);
  FEM_REFINE2D_Init();
  CkPrintf("[%d] end init\n",myChunk);
  
  myGlobals g;
  FEM_Register(&g,(FEM_PupFn)pup_myGlobals);
  init_myGlobal(&g);
  
  g.nnodes = FEM_Mesh_get_length(FEM_Mesh_default_read(),FEM_NODE);
  int maxNodes = g.nnodes;
  g.maxnodes=2*maxNodes;
  g.m_i_fid=FEM_Create_field(FEM_DOUBLE,1,0,sizeof(double));
  resize_nodes((void *)&g,&g.nnodes,&maxNodes);
  int nghost=0;
  g.nelems=FEM_Mesh_get_length(FEM_Mesh_default_read(),FEM_ELEM);
  g.maxelems=g.nelems;
  resize_elems((void *)&g,&g.nelems,&g.maxelems);

  FEM_REFINE2D_Newmesh(FEM_Mesh_default_read(),FEM_NODE,FEM_ELEM);
  
  //Initialize associated data
  for (i=0;i<g.maxnodes;i++) {
    g.R_net[i]=g.d[i]=g.v[i]=g.a[i]=vector2d(0.0);
  }
  
  //Apply a small initial perturbation to positions
  for (i=0;i<g.nnodes;i++) {
    const double max=1.0e-15/15.0; //Tiny perturbation
    g.d[i].x+=max*(i&15);
    g.d[i].y+=max*((i+5)&15);
  }
  
  int fid=FEM_Create_field(FEM_DOUBLE,2,0,sizeof(vector2d));
  
  for (i=0;i<g.nelems;i++){
    checkTriangle(g,i);
  }	
  sleep(5);
  //Timeloop
  if (CkMyPe()==0){
    CkPrintf("Entering timeloop\n");
  }	
  //  int tSteps=0x70FF00FF;
  int tSteps=4;
  int z=13;
  calcMasses(g);
  double startTime=CkWallTimer();
  double curArea=2.5e-5/1024;
  int t = 0;

  // THIS IS THE INITIAL MESH SENT TO NetFEM
  if (1) { //Publish data to the net
    publishMeshToNetFEM(g,myChunk,t);
  }
  double desiredArea;
  /* 
  //should not be necessary as it would have been set in the init
  for (i=0; i<g.nnodes; i++) {
    g.validNode[i] = 1;
  }
  for (i=0; i<g.nelems; i++) {
    g.validElem[i] = 1;
  }*/
  double avgArea = 0.0;
  for (i=0;i<g.nelems;i++) {
    avgArea += calcArea(g, i);
  }
  avgArea /= g.nelems;
  for (t=1;t<=tSteps;t++) {
    /*    if (1) { //Structural mechanics
    //Compute forces on nodes exerted by elements
    CST_NL(g.coord,g.conn,g.R_net,g.d,matConst,g.nnodes,g.nelems,g.S11,g.S22,g.S12);
    //Communicate net force on shared nodes
    FEM_Update_field(fid,g.R_net);
    //Advance node positions
    advanceNodes(dt,g.nnodes,g.coord,g.R_net,g.a,g.v,g.d,g.m_i,(t%4)==0);
    }*/
    
    //Debugging/perf. output
    double curTime=CkWallTimer();
    double total=curTime-startTime;
    startTime=curTime;
    vector2d *loc;
    double *areas;
	
    // prepare to coarsen
    loc=new vector2d[2*g.nnodes];
    for (i=0;i<g.nnodes;i++) {
      loc[i]=g.coord[i];//+g.d[i];
    }
    areas=new double[g.nelems];
    for (i=0;i<g.nelems;i++) {
      areas[i] = avgArea;
    }
    //coarsen one element at a time
    //int coarseIdx = (23  + 4*t)%g.nnodes;
    //areas[coarseIdx] = calcArea(g,coarseIdx)*2.5;
    
    CkPrintf("[%d] Starting coarsening step: %d nodes, %d elements\n", myChunk,countValidEntities(g.validNode,g.nnodes),countValidEntities(g.validElem,g.nelems));
    FEM_REFINE2D_Coarsen(FEM_Mesh_default_read(),FEM_NODE,(double *)g.coord,FEM_ELEM,areas,FEM_SPARSE);
    repeat_after_split((void *)&g);
    g.nelems = FEM_Mesh_get_length(FEM_Mesh_default_read(),FEM_ELEM);
    g.nnodes = FEM_Mesh_get_length(FEM_Mesh_default_read(),FEM_NODE);
    CkPrintf("[%d] Done with coarsening step: %d nodes, %d elements\n",
	     myChunk,countValidEntities(g.validNode,g.nnodes),countValidEntities(g.validElem,g.nelems));
    delete [] loc;
    delete[] areas;
    // THIS IS THE COARSENED MESH SENT TO NetFEM
    if (1) { //Publish data to the net
      publishMeshToNetFEM(g,myChunk,2*t-1);
    }

    //prepare to refine
    loc=new vector2d[2*g.nnodes];
    for (i=0;i<g.nnodes;i++) {
      loc[i]=g.coord[i];//+g.d[i];
    }
    
    areas=new double[g.nelems];
    for (i=0;i<g.nelems;i++) {
      areas[i] = avgArea;
    }
    //refine one element at a time
    //int refIdx = (13  + 3*t)%g.nnodes;
    //areas[refIdx] = calcArea(g,refIdx)/1.5;
    
    CkPrintf("[%d] Starting refinement step: %d nodes, %d elements\n", myChunk,countValidEntities(g.validNode,g.nnodes),countValidEntities(g.validElem,g.nelems));
    FEM_REFINE2D_Split(FEM_Mesh_default_read(),FEM_NODE,(double *)loc,FEM_ELEM,areas,FEM_SPARSE);
    repeat_after_split((void *)&g);
    
    g.nelems = FEM_Mesh_get_length(FEM_Mesh_default_read(),FEM_ELEM);
    g.nnodes = FEM_Mesh_get_length(FEM_Mesh_default_read(),FEM_NODE);
    CkPrintf("[%d] Done with refinement step: %d nodes, %d elements\n",
	     myChunk,countValidEntities(g.validNode,g.nnodes),countValidEntities(g.validElem,g.nelems));
    delete [] loc;
    delete[] areas;
    // THIS IS THE REFINED MESH SENT TO NetFEM
    if (1) { //Publish data to the net
      publishMeshToNetFEM(g,myChunk,2*t);
    }
  }
  if (CkMyPe()==0)
    CkPrintf("Driver finished\n");
}
Esempio n. 26
0
	// Update area
	void Triangle::calcArea()
	{
		mArea = calcArea( mOrigin, mDestination, mApex );
	}
// todo: explain the selection heuristics
void SELECTION_TOOL::guessSelectionCandidates( GENERAL_COLLECTOR& aCollector ) const
{
    std::set<BOARD_ITEM*> rejected;

    const double footprintAreaRatio = 0.2;
    const double modulePadMinCoverRatio = 0.45;
    const double padViaAreaRatio = 0.5;
    const double trackViaLengthRatio = 2.0;
    const double trackTrackLengthRatio = 0.3;
    const double textToFeatureMinRatio = 0.2;
    const double textToFootprintMinRatio = 0.4;

    LAYER_ID actLayer = m_frame->GetActiveLayer();

    LSET silkLayers( 2, B_SilkS, F_SilkS );

    if( silkLayers[actLayer] )
    {
        std::set<BOARD_ITEM*> preferred;

        for( int i = 0; i < aCollector.GetCount(); ++i )
        {
            BOARD_ITEM* item = aCollector[i];

            if ( item->Type() == PCB_MODULE_TEXT_T || item->Type() == PCB_TEXT_T || item->Type() == PCB_LINE_T )
                if ( silkLayers[item->GetLayer()] )
                    preferred.insert ( item );
        }

        if( preferred.size() != 0 )
        {
            aCollector.Empty();

            BOOST_FOREACH( BOARD_ITEM* item, preferred )
                aCollector.Append( item );
            return;
        }
    }

    if( aCollector.CountType( PCB_MODULE_TEXT_T ) > 0 )
    {
        for( int i = 0; i < aCollector.GetCount(); ++i )
            if( TEXTE_MODULE* txt = dyn_cast<TEXTE_MODULE*>( aCollector[i] ) )
            {
                double textArea = calcArea( txt );

                for( int j = 0; j < aCollector.GetCount(); ++j )
                {
                    BOARD_ITEM* item = aCollector[j];
                    double areaRatio = calcRatio( textArea, calcArea( item ) );

                    if( item->Type() == PCB_MODULE_T && areaRatio < textToFootprintMinRatio )
                    {
                        //printf("rejectModuleN\n");

                        rejected.insert( item );
                    }

                    switch( item->Type() )
                    {
                        case PCB_TRACE_T:
                        case PCB_PAD_T:
                        case PCB_LINE_T:
                        case PCB_VIA_T:
                        case PCB_MODULE_T:
                            if( areaRatio > textToFeatureMinRatio )
                            {
                                //printf("t after moduleRejected\n");
                                rejected.insert( txt );
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
    }

    if( aCollector.CountType( PCB_MODULE_T ) > 0 )
    {
        double minArea = calcMinArea( aCollector, PCB_MODULE_T );
        double maxArea = calcMaxArea( aCollector, PCB_MODULE_T );

        if( calcRatio( minArea, maxArea ) <= footprintAreaRatio )
        {
            for( int i = 0; i < aCollector.GetCount(); ++i )
                if( MODULE* mod = dyn_cast<MODULE*>( aCollector[i] ) )
                {
                    double normalizedArea = calcRatio( calcArea(mod), maxArea );

                    if( normalizedArea > footprintAreaRatio )
                    {
                        //printf("rejectModule1\n");

                        rejected.insert( mod );
                    }
                }
        }
    }

    if( aCollector.CountType ( PCB_PAD_T ) > 0 )
    {
        for( int i = 0; i < aCollector.GetCount(); ++i )
        {
            if ( D_PAD* pad = dyn_cast<D_PAD*>( aCollector[i] ) )
            {
                double ratio = pad->GetParent()->PadCoverageRatio();

                if( ratio < modulePadMinCoverRatio )
                    rejected.insert( pad->GetParent() );
            }
        }
    }

    if( aCollector.CountType( PCB_VIA_T ) > 0 )
    {
        for( int i = 0; i < aCollector.GetCount(); ++i )
        {
            if( VIA* via = dyn_cast<VIA*>( aCollector[i] ) )
            {
                double viaArea = calcArea( via );

                for( int j = 0; j < aCollector.GetCount(); ++j )
                {
                    BOARD_ITEM* item = aCollector[j];
                    double areaRatio = calcRatio ( viaArea, calcArea( item ) );

                    if( item->Type() == PCB_MODULE_T && areaRatio < modulePadMinCoverRatio )
                        rejected.insert( item );

                    if( item->Type() == PCB_PAD_T && areaRatio < padViaAreaRatio )
                        rejected.insert( item );

                    if( TRACK* track = dyn_cast<TRACK*>( item ) )
                    {
                        if( track->GetNetCode() != via->GetNetCode() )
                            continue;

                        double lenRatio = (double) ( track->GetLength() + track->GetWidth() ) / (double) via->GetWidth();

                        if( lenRatio > trackViaLengthRatio )
                            rejected.insert( track );
                    }
                }
            }
        }
    }

    int nTracks = aCollector.CountType ( PCB_TRACE_T );

    if( nTracks > 0 )
    {
        double maxLength = 0.0;
        double minLength = std::numeric_limits<double>::max();
        double maxArea = 0.0;

        for( int i = 0; i < aCollector.GetCount(); ++i )
            if ( TRACK *track = dyn_cast<TRACK*> ( aCollector[i] ) )
            {
                maxLength = std::max( track->GetLength(), maxLength );
                maxLength = std::max( (double)track->GetWidth(), maxLength );

                minLength = std::min( std::max ( track->GetLength(), (double)track->GetWidth() ), minLength );

                double area =  ( track->GetLength() + track->GetWidth() * track->GetWidth() );
                maxArea = std::max(area, maxArea);
            }

        if( maxLength > 0.0 && minLength/maxLength < trackTrackLengthRatio && nTracks > 1 )
        {
            for( int i = 0; i < aCollector.GetCount(); ++i )
             {
                if( TRACK* track = dyn_cast<TRACK*>( aCollector[i] ) )
                {
                    double ratio = std::max( (double) track->GetWidth(), track->GetLength()) / maxLength;

                    if( ratio > trackTrackLengthRatio )
                        rejected.insert( track) ;
                }
            }
        }

        for( int j = 0; j < aCollector.GetCount(); ++j )
        {
            if( MODULE* mod = dyn_cast<MODULE*>( aCollector[j] ) )
            {
                double ratio = maxArea / mod->GetFootprintRect().GetArea();

                if( ratio < modulePadMinCoverRatio )
                {
                    //printf("rejectModule\n");
                    rejected.insert( mod );
                }
            }
        }
    }

    BOOST_FOREACH( BOARD_ITEM* item, rejected )
    {
        aCollector.Remove( item );
    }
Esempio n. 28
0
void ImgWarp_MLS_Rigid::calcDelta(){
    int i, j, k;

    Point_< double > swq, qstar, newP, tmpP;
    double sw;
    
    double ratio;

    if (preScale){
        ratio = sqrt(calcArea(newDotL) / calcArea(oldDotL));
        for (i=0; i<nPoint; i++)
            newDotL[i] *= 1/ratio;
    }

    double *w=new double[nPoint];

    rDx.create(tarH, tarW);
    rDy.create(tarH, tarW);

	if (nPoint < 2){
		rDx.setTo(0);
		rDy.setTo(0);
		return;
	}
    Point_< double > swp, pstar, curV, curVJ, Pi, PiJ, Qi;
    double miu_r;

    for (i = 0; ; i+=gridSize){
        if (i>=tarW && i<tarW+gridSize - 1)
            i=tarW-1;
        else if (i>=tarW)
            break;
        for (j = 0; ; j+=gridSize){
            if (j>=tarH && j<tarH+gridSize - 1)
                j = tarH - 1;
            else if (j>=tarH)
                break;
            sw = 0;
            swp.x = swp.y = 0;
            swq.x = swq.y = 0;
            newP.x = newP.y = 0;
            curV.x = i;
            curV.y = j;
            for (k = 0; k < nPoint; k++){
                if ((i==oldDotL[k].x) && j==oldDotL[k].y)
                    break;
                if (alpha==1)
                    w[k] = 1/((i-oldDotL[k].x)*(i-oldDotL[k].x)+
                        (j-oldDotL[k].y)*(j-oldDotL[k].y));
                else
                    w[k] = pow((i-oldDotL[k].x)*(i-oldDotL[k].x)+
                        (j-oldDotL[k].y)*(j-oldDotL[k].y), -alpha);
                sw = sw + w[k];
                swp = swp + w[k] * oldDotL[k];
                swq = swq + w[k] * newDotL[k];
            }
            if ( k == nPoint ) {
                pstar = (1 / sw) * swp ;
                qstar = 1/sw * swq;
    //            qDebug("pstar: (%f, %f)", pstar[0], pstar[1]);

                // Calc miu_r
                //miu_s = 0;
                double s1=0, s2=0;
                for (k = 0; k < nPoint; k++){
                    if (i==oldDotL[k].x && j==oldDotL[k].y)
                        continue;

                    Pi = oldDotL[k] - pstar;
                    PiJ.x = -Pi.y, PiJ.y = Pi.x;
                    Qi = newDotL[k] - qstar;
                    s1 += w[k] * Qi.dot(Pi);
                    s2 += w[k] * Qi.dot(PiJ);
                }
                miu_r = sqrt(s1*s1 + s2*s2);

                curV -= pstar;
                curVJ.x = -curV.y, curVJ.y = curV.x;

                for (k = 0; k < nPoint; k++){
                    if (i==oldDotL[k].x && j==oldDotL[k].y)
                        continue;

                    Pi = oldDotL[k] - pstar;
                    PiJ.x = -Pi.y, PiJ.y = Pi.x;

                    tmpP.x = Pi.dot(curV) * newDotL[k].x
                             - PiJ.dot(curV) * newDotL[k].y;
                    tmpP.y = -Pi.dot(curVJ) * newDotL[k].x
                             + PiJ.dot(curVJ) * newDotL[k].y;
                    tmpP *= w[k]/miu_r;
                    newP += tmpP;
                }
                newP += qstar;
            }
            else {
                newP = newDotL[k];
            }

            if (preScale){
                rDx(j, i) = newP.x * ratio - i;
                rDy(j, i) = newP.y * ratio - j;
            }
            else {
                rDx(j, i) = newP.x - i;
                rDy(j, i) = newP.y - j;
            }
        }
    }

    delete [] w;
    
    if (preScale){
        for (i=0; i<nPoint; i++)
            newDotL[i] *= ratio;
    }
    
    // cout<<rDx<<endl;
}