Пример #1
0
StrokesData *FullColorImageData::toStrokesData(ToonzScene *scene) const
{
	assert(scene);
	TRectD rect;
	if (!m_rects.empty())
		rect = m_rects[0];
	else if (!m_strokes.empty())
		rect = m_strokes[0].getBBox();
	unsigned int i;
	for (i = 0; i < m_rects.size(); i++)
		rect += m_rects[i];
	for (i = 0; i < m_strokes.size(); i++)
		rect += m_strokes[i].getBBox();
	TRasterImageP image(m_copiedRaster);
	image->setPalette(FullColorPalette::instance()->getPalette(scene));
	image->setDpi(m_dpiX, m_dpiY);

	const VectorizerParameters *vParams = scene->getProperties()->getVectorizerParameters();
	assert(vParams);

	std::auto_ptr<VectorizerConfiguration> config(vParams->getCurrentConfiguration(0.0));
	TVectorImageP vi = vectorize(image, rect, *config, m_transformation);

	StrokesData *sd = new StrokesData();

	std::set<int> indexes;
	for (i = 0; i < vi->getStrokeCount(); i++)
		indexes.insert(i);

	sd->setImage(vi, indexes);
	return sd;
}
Пример #2
0
 Reference dereference() const {
     return vectorize(
         _functor, 
         this->base_reference()->template get<0>(),
         this->base_reference()->template get<1>()
     );
 }
Пример #3
0
StrokesData *ToonzImageData::toStrokesData(ToonzScene *scene) const
{
	assert(scene);
	TRectD rect;
	if (!m_rects.empty())
		rect = m_rects[0];
	else if (!m_strokes.empty())
		rect = m_strokes[0].getBBox();
	unsigned int i;
	for (i = 0; i < m_rects.size(); i++)
		rect += m_rects[i];
	for (i = 0; i < m_strokes.size(); i++)
		rect += m_strokes[i].getBBox();
	TToonzImageP image(m_copiedRaster, m_copiedRaster->getBounds());
	image->setPalette(m_palette.getPointer());
	image->setDpi(m_dpiX, m_dpiY);

	const VectorizerParameters &vParams = *scene->getProperties()->getVectorizerParameters();

	CenterlineConfiguration cConf = vParams.getCenterlineConfiguration(0.0);
	NewOutlineConfiguration oConf = vParams.getOutlineConfiguration(0.0);

	const VectorizerConfiguration &config = vParams.m_isOutline ? static_cast<const VectorizerConfiguration &>(oConf) : static_cast<const VectorizerConfiguration &>(cConf);

	TVectorImageP vi = vectorize(image, rect, config, m_transformation);

	StrokesData *sd = new StrokesData();

	std::set<int> indexes;
	for (i = 0; i < vi->getStrokeCount(); i++)
		indexes.insert(i);

	sd->setImage(vi, indexes);
	return sd;
}
Пример #4
0
/*
  Calculate volume of a tet_mesh by summing the volumes of all tets.
  Volume of each tet is given by:

    (1/6) * abs(dot_prod(a,cross_prod(b,c)))

  where a, b, and c are three edges of the tet that share a common
  vertex of the tet.
*/
double meshvol(struct tet_mesh *tet_mesh)
{


  struct node **nodes;
  struct tet_list *tlp;
  struct tet *tp;
  struct vector3 p1,p2,a,b,c,bxc;
  double volume;

  nodes=tet_mesh->nodes;

  volume = 0.0;

  for (tlp=tet_mesh->tet_head; tlp!=NULL; tlp=tlp->next)
  {
    tp=tlp->tet;
    p1.x=nodes[tp->node_index[0]]->x;
    p1.y=nodes[tp->node_index[0]]->y;
    p1.z=nodes[tp->node_index[0]]->z;

    p2.x=nodes[tp->node_index[1]]->x;
    p2.y=nodes[tp->node_index[1]]->y;
    p2.z=nodes[tp->node_index[1]]->z;
    vectorize(&p1,&p2,&a);

    p2.x=nodes[tp->node_index[2]]->x;
    p2.y=nodes[tp->node_index[2]]->y;
    p2.z=nodes[tp->node_index[2]]->z;
    vectorize(&p1,&p2,&b);

    p2.x=nodes[tp->node_index[3]]->x;
    p2.y=nodes[tp->node_index[3]]->y;
    p2.z=nodes[tp->node_index[3]]->z;
    vectorize(&p1,&p2,&c);

    cross_prod(&b,&c,&bxc);

    volume += fabs(dot_prod(&a,&bxc));
  }

  volume = volume/6.0;

  return(volume); 
}
Пример #5
0
/* sortlist */
extern List *sortlist(List *list) {
    if (length(list) > 1) {
        Vector *v = vectorize(list);
        sortvector(v);
        gcdisable(0);
        Ref(List *, lp, listify(v->count, v->vector));
        gcenable();
        list = lp;
        RefEnd(lp);
    }
Пример #6
0
	Barcode& Barcode2dBase::build( const std::string& rawData,
				       double             w,
				       double             h )
	{
		std::string  cookedData;   /* Preprocessed data */
		Matrix<bool> encodedData;  /* Encoded data matrix */

		clear();

		if ( rawData.empty() )
		{
			setIsEmpty( true );
			setIsDataValid( false );

			setWidth( 0 );
			setHeight( 0 );
		}
		else
		{
			setIsEmpty( false );

			if ( !validate( rawData ) )
			{
				setIsDataValid( false );

				setWidth( 0 );
				setHeight( 0 );
			}
			else
			{
				setIsDataValid( true );

				cookedData  = preprocess( rawData );
				encode( cookedData, encodedData );

				vectorize( encodedData, w, h );

				setWidth( w );
				setHeight( h );
			}
		}

		return *this;
	}
Пример #7
0
/* forkexec -- fork (if necessary) and exec */
extern List *forkexec(char *file, List *list, Boolean inchild) {
	int pid, status;
	Vector *env;
	gcdisable();
	env = mkenv();
	pid = efork(!inchild, FALSE);
	if (pid == 0) {
		execve(file, vectorize(list)->vector, env->vector);
		failexec(file, list);
	}
	gcenable();
	status = ewaitfor(pid);
	if ((status & 0xff) == 0) {
		sigint_newline = FALSE;
		SIGCHK();
		sigint_newline = TRUE;
	} else
		SIGCHK();
	printstatus(0, status);
	return mklist(mkterm(mkstatus(status), NULL), NULL);
}
Пример #8
0
/**
	compress Image
*/
void compressImg(image img, image output, s_args args){

    int *quantizeData = malloc(sizeof(int)*BLOCK_SIZE*BLOCK_SIZE);
    int *vectorizeData = malloc(sizeof(int)*BLOCK_SIZE*BLOCK_SIZE);
    float *dctData = malloc(sizeof(float)*BLOCK_SIZE*BLOCK_SIZE);
    int offset = 0;

    for (int i = 0; i < img.h; i += BLOCK_SIZE){
        for (int j = 0; j < img.w; j+= BLOCK_SIZE) 
        {
            dct(&img, dctData, j, i);
            quantize(dctData, quantizeData);
            vectorize(quantizeData, vectorizeData);
            putCompressedValues(&output, vectorizeData, &offset);
        }
        
    }

    writeCompressed(args.outFilename, &output);
    free(quantizeData);
    free(vectorizeData);
    free(dctData);
}
Пример #9
0
/*
  Calculate the material-specific volume of a Voronoi polyhedron
  This is done by creating a tetrahedralization of the Voronoi cell
  and then summing the volumes of all tets.
  The volume of each tet is given by:

    (1/6) * abs(dot_prod(a,cross_prod(b,c)))

  where a, b, and c are three edges of the tet that share a common
  vertex of the tet.
*/
double polyvol_by_material_1(struct tet_mesh *tet_mesh,
                             struct node *node,
                             u_int node_matindex)
{
  struct node **nodes;
  struct edge_list *elp;
  struct edge *ep;
  struct voronoi_facet *facet_head,*vfp;
  struct vector3 p1,p2,a,b,c,bxc;
  struct vector3 **vnp;
  double volume,facet_volume;
  u_int edge_matindex;
  u_int i;

  nodes = tet_mesh->nodes;
  vnp=tet_mesh->voronoi_nodes;

  volume = 0.0;
  for (elp=node->node_material[node_matindex].edge_head; elp!=NULL; elp=elp->next)
  {
    ep=elp->edge;

    if (ep->material_count>1)
    {
      edge_matindex=0;
      for (i=0;i<ep->material_count;i++)
      {
        if (node->node_material[node_matindex].matnum==ep->edge_material[i].matnum)
        {
          edge_matindex=i;
        }
      }
      facet_head=ep->edge_material[edge_matindex].facet;
    }
    else
    {
      facet_head=ep->facet;
    }

    /* use the central node of the Voronoi cell as the apex of each tet */
    p1.x=node->x;
    p1.y=node->y;
    p1.z=node->z;

    /* Triangulate each Voronoi facet and use each triangle as */
    /* the base of each tet */
    for (vfp=facet_head; vfp!=NULL; vfp=vfp->next)
    {
      facet_volume=0;

      for (i=2; i<vfp->nnodes; i++)
      {
        p2.x=vnp[vfp->node_index[0]]->x;
        p2.y=vnp[vfp->node_index[0]]->y;
        p2.z=vnp[vfp->node_index[0]]->z;
        vectorize(&p1,&p2,&a);

        p2.x=vnp[vfp->node_index[i-1]]->x;
        p2.y=vnp[vfp->node_index[i-1]]->y;
        p2.z=vnp[vfp->node_index[i-1]]->z;
        vectorize(&p1,&p2,&b);

        p2.x=vnp[vfp->node_index[i]]->x;
        p2.y=vnp[vfp->node_index[i]]->y;
        p2.z=vnp[vfp->node_index[i]]->z;
        vectorize(&p1,&p2,&c);

        cross_prod(&b,&c,&bxc);

        facet_volume += dot_prod(&a,&bxc);
      }
    }
    volume += fabs(facet_volume);
  }

  volume = volume/6.0;
  
  return(volume);

}
Пример #10
0
/* return 0 on no intersection and 1 on intersection */
int ray_trace(struct tet_mesh *tet_mesh,
              struct voronoi_facet *vfp,
              struct vector3 *pnt1,
              struct vector3 *pnt2)
{
  struct vector3 **vnp;

  vnp=tet_mesh->voronoi_nodes;

  /* calculate facet edge length ratio of consecutive edges */
  /* find two consecutive edges with a reasonable ratio */
  /* this procedure avoids nearly coincident facet vertices */
  found=0;
  for (v=0; v<vfp->nnodes && !found; v++)
  {
    if (v==0)
    {
      n2 = vfp->node_index[v+1];
      n3 = vfp->node_index[vfp->nnodes-1];
    }
    else if (v==vfp->nnodes-1)
    {
      n2 = vfp->node_index[0];
      n3 = vfp->node_index[v-1];
    }
    else
    {
      n2 = vfp->node_index[v+1];
      n3 = vfp->node_index[v-1];
    }
    n1 = vfp->node_index[v];
    p1.x = vnp[n1]->x;
    p1.y = vnp[n1]->y;
    p1.z = vnp[n1]->z;
    p2.x = vnp[n2]->x;
    p2.y = vnp[n2]->y;
    p2.z = vnp[n2]->z;
    vectorize(&p1,&p2,&v1);
    p2.x = vnp[n3]->x;
    p2.y = vnp[n3]->y;
    p2.z = vnp[n3]->z;
    vectorize(&p1,&p2,&v2);
    l1=vect_length(&v1);
    l2=vect_length(&v2);
    if (l1<l2)
    {
      edge_ratio=l1/l2;
    }
    else
    {
      edge_ratio=l2/l1;
    }
    if (edge_ratio>1e-9)
    {
      found=1;
    }
  }

  /* construct normal vector of facet */
  p1.x = vnp[n1]->x;
  p1.y = vnp[n1]->y;
  p1.z = vnp[n1]->z;
  p2.x = vnp[n2]->x;
  p2.y = vnp[n2]->y;
  p2.z = vnp[n2]->z;
  vectorize(&p1,&p2,&v1);
  p2.x = vnp[n3]->x;
  p2.y = vnp[n3]->y;
  p2.z = vnp[n3]->z;
  vectorize(&p1,&p2,&v2);
  cross_prod(&v1,&v2,&v_norm);
  normalize(&v_norm);

  a=v_norm.x;
  b=v_norm.y;
  c=v_norm.z;
  d=(v_norm.x*p1.x)+(v_norm.y*p1.y)+(v_norm.z*p1.z);
  projection=0;
  tmp=v_norm.x;
  if (tmp*tmp < v_norm.y*v_norm.y)
  {
    projection=1;
    tmp=v_norm.y;
  }
  if (tmp*tmp < v_norm.z*v_norm.z)
  {
    projection=2;
  }


  n_dot_delta=a*dx+b*dy+c*dz;
  if (n_dot_delta==0)
  {
    t=-1000;
  }
  else
  {
    t=(d-a*x-b*y-c*z)/n_dot_delta;
  }

  if (t>=0.0)
  {
    /* take 2D projection of polygon and hit point
    * and determine if hit point is within the projected polygon boundaries */
    x=pnt1->x;
    y=pnt1->y;
    z=pnt1->z;
    dx=pnt2->x-pnt1->x;
    dy=pnt2->y-pnt1->y;
    dz=pnt2->z-pnt1->z;
    vert=vnp[vfp->node_index[0]];
    if (projection == 0)
    {
      h1=y+t*dy;
      h2=z+t*dz;
      a1=vert->y-h1;
      a2=vert->z-h2;
    }
    else if (projection == 1)
    {
      h1=x+t*dx;
      h2=z+t*dz;
      a1=vert->x-h1;
      a2=vert->z-h2;
    }
    else
    {
      h1=x+t*dx;
      h2=y+t*dy;
      a1=vert->x-h1;
      a2=vert->y-h2;
    }
    j=1;
    prev_det=0;
    inside=1;
    n_vert = wp->n_vert;
    while (inside && j<vfp->nnodes;)
    {
      vert=vnp[vfp->node_index[j]];
      if (projection == 0)
      {
        b1=vert->y-h1;
        b2=vert->z-h2;
      }
      else if (projection == 1)
      {
        b1=vert->x-h1;
        b2=vert->z-h2;
      }
      else
      {
        b1=vert->x-h1;
        b2=vert->y-h2;
      }
      det=a1*b2-a2*b1;
      a1=b1;
      a2=b2;
      if (j>1)
      {
        inside=(!((det<0 && prev_det>=0) || (det>=0 && prev_det<0)));
      }
      prev_det=det;
      j++;
    }
    if (inside)
    {
      vert=vnp[vfp->node_index[0]];
      if (projection == 0)
      {
        b1=vert->y-h1;
        b2=vert->z-h2;
      }
      else if (projection == 1)
      {
        b1=vert->x-h1;
        b2=vert->z-h2;
      }
      else
      {
        b1=vert->x-h1;
        b2=vert->y-h2;
      }
      det=a1*b2-a2*b1;
      inside=(!((det<0 && prev_det>=0) || (det>=0 && prev_det<0)));
      prev_det=det;
    }

    if (inside)
    {
      return(1);
    }

  }
Пример #11
0
/*
  Calculate volume of a material-specific Voronoi polyhedron
  by summing over all surface triangles of the polyhedron, the quantity:

              |  x1   x2   x3  |
    (1/6) det |  y1   y2   y3  |
              |  z1   z2   z3  |

  where (xn,yn,zn) is vertex n of a surface triangle.  The surface normals of
  all triangles of the polyhedron must point toward the outside of the
  polyhedron.
*/
double polyvol_by_material_2(struct tet_mesh *tet_mesh,
                           struct node *node,
                           u_int node_matindex)
{
  struct node **nodes;
  struct edge_list *elp;
  struct edge *ep;
  struct voronoi_facet *facet_head,*vfp;
  struct vector3 p1,p2,pint,v1,v2,v_node,v_norm;
  struct vector3 **vnp;
  double x1,x2,x3,y1,y2,y3,z1,z2,z3;
  double dot,det,volume;
  double l1,l2,edge_ratio;
  u_int n1;
  u_int n2;
  u_int n3;
  u_int v,nnodes,node_count;
  u_int edge_matindex;
  u_int i;
  byte found;

  nodes=tet_mesh->nodes;
  vnp=tet_mesh->voronoi_nodes;

  /* first find a point on the interior of the material-specific Voronoi cell */
  /* this is done by finding a material specific interior Delaunay edge  */
  /* and placing a point 1/4 of the way along this edge away from node */
  found=0;
  for (elp=node->node_material[node_matindex].edge_head; elp!=NULL && !found; elp=elp->next)
  {
    ep=elp->edge;

    if (ep->edge_type == INTERIOR)
    {
      if (node->node_index == ep->node_index[0])
      {
        p1.x=nodes[ep->node_index[0]]->x;
        p1.y=nodes[ep->node_index[0]]->y;
        p1.z=nodes[ep->node_index[0]]->z;
        p2.x=nodes[ep->node_index[1]]->x;
        p2.y=nodes[ep->node_index[1]]->y;
        p2.z=nodes[ep->node_index[1]]->z;
      } 
      else
      {
        p1.x=nodes[ep->node_index[1]]->x;
        p1.y=nodes[ep->node_index[1]]->y;
        p1.z=nodes[ep->node_index[1]]->z;
        p2.x=nodes[ep->node_index[0]]->x;
        p2.y=nodes[ep->node_index[0]]->y;
        p2.z=nodes[ep->node_index[0]]->z;
      }
      vectorize(&p1,&p2,&v1);
      pint.x=p1.x+0.25*v1.x;
      pint.y=p1.y+0.25*v1.y;
      pint.z=p1.z+0.25*v1.z;
      found=1;
    }
  }
/*
  if (!found)
  {
    fprintf(stderr,"polyvol_by_material: warning: no interior point found for node %u\n",node->node_index);
  }
*/

  /* NOTE: the following is disabled in favor of the above method */
  /* Use the following only if no suitable interior edge is found */
  /* first find a point on the interior of the material-specific Voronoi cell */
  /* this is done by calculating the average value of the Voronoi vertices */
  if (!found)
  {
    pint.x=0;
    pint.y=0;
    pint.z=0;
    node_count=0;
    for (elp=node->node_material[node_matindex].edge_head; elp!=NULL; elp=elp->next)
    {
      ep=elp->edge;
  
      if (ep->material_count>1)
      {
        edge_matindex=0;
        for (i=0;i<ep->material_count;i++)
        {
          if (node->node_material[node_matindex].matnum==ep->edge_material[i].matnum)
          {
            edge_matindex=i;
          }
        }
        facet_head=ep->edge_material[edge_matindex].facet;
      }
      else
      {
        facet_head=ep->facet;
      }
  
      for (vfp=facet_head; vfp!=NULL; vfp=vfp->next)
      {
        nnodes=vfp->nnodes;
        for (v=0; v<nnodes; v++)
        {
          n1 = vfp->node_index[v];
          pint.x+=vnp[n1]->x;
          pint.y+=vnp[n1]->y;
          pint.z+=vnp[n1]->z;
          node_count++;
        }
  
      }
    }
    pint.x=pint.x/node_count;
    pint.y=pint.y/node_count;
    pint.z=pint.z/node_count;
  }



  /* now calculate volume of Voronoi cell */
  volume = 0.0;
  for (elp=node->node_material[node_matindex].edge_head; elp!=NULL; elp=elp->next)
  {
    ep=elp->edge;

    if (ep->material_count>1)
    {
      edge_matindex=0;
      for (i=0;i<ep->material_count;i++)
      {
        if (node->node_material[node_matindex].matnum==ep->edge_material[i].matnum)
        {
          edge_matindex=i;
        }
      }
      facet_head=ep->edge_material[edge_matindex].facet;
    }
    else
    {
      facet_head=ep->facet;
    }

    for (vfp=facet_head; vfp!=NULL; vfp=vfp->next)
    {

    /* orient and triangulate each face.*/
        /* calculate facet edge length ratio of consecutive edges */
        /* find two consecutive edges with a reasonable ratio */
        /* this procedure avoids nearly coincident tet circumcenters */
        found=0;
        for (v=0; v<vfp->nnodes && !found; v++)
        {
          if (v==0)
          {
            n2 = vfp->node_index[v+1];
            n3 = vfp->node_index[vfp->nnodes-1];
          }
          else if (v==vfp->nnodes-1)
          {
            n2 = vfp->node_index[0];
            n3 = vfp->node_index[v-1];
          }
          else
          {
            n2 = vfp->node_index[v+1];
            n3 = vfp->node_index[v-1];
          }
          n1 = vfp->node_index[v]; 
          p1.x = vnp[n1]->x; 
          p1.y = vnp[n1]->y; 
          p1.z = vnp[n1]->z; 
          p2.x = vnp[n2]->x; 
          p2.y = vnp[n2]->y; 
          p2.z = vnp[n2]->z; 
          vectorize(&p1,&p2,&v1);
          p2.x = vnp[n3]->x; 
          p2.y = vnp[n3]->y; 
          p2.z = vnp[n3]->z; 
          vectorize(&p1,&p2,&v2);
          l1=vect_length(&v1);
          l2=vect_length(&v2);
          if (l1<l2)
          {
            edge_ratio=l1/l2;
          }
          else
          {
            edge_ratio=l2/l1;
          }
          if (edge_ratio>1e-9)
          {
            found=1;
          }
        }

    /* determine orientation of Voronoi facet */
      /* construct vector from interior node to first vertex of facet */
      p1.x = vnp[n1]->x; 
      p1.y = vnp[n1]->y; 
      p1.z = vnp[n1]->z; 
      vectorize(&pint,&p1,&v_node);
      normalize(&v_node);

      /* construct normal vector of facet */
      p2.x = vnp[n2]->x; 
      p2.y = vnp[n2]->y; 
      p2.z = vnp[n2]->z; 
      vectorize(&p1,&p2,&v1);
      p2.x = vnp[n3]->x; 
      p2.y = vnp[n3]->y; 
      p2.z = vnp[n3]->z; 
      vectorize(&p1,&p2,&v2);
      cross_prod(&v1,&v2,&v_norm);
      normalize(&v_norm);

      dot=dot_prod(&v_node,&v_norm);

      nnodes=vfp->nnodes;
      if (dot>=0)
      {
        /* facet normal already points outward */
        n3 = vfp->node_index[nnodes-1]; 
        for (v=0; v<nnodes-2; v++)
        {

          n1 = vfp->node_index[v];
          n2 = vfp->node_index[v+1];
      
          x1=vnp[n1]->x;
          y1=vnp[n1]->y;
          z1=vnp[n1]->z;
          x2=vnp[n2]->x;
          y2=vnp[n2]->y;
          z2=vnp[n2]->z;
          x3=vnp[n3]->x;
          y3=vnp[n3]->y;
          z3=vnp[n3]->z;

          /* compute determinant of oriented triangle */
          det=x1*(y2*z3-y3*z2)+x2*(y3*z1-y1*z3)+x3*(y1*z2-y2*z1);

          volume+=det;
        }
      }
      else
      {
        /* facet normal points inward -- need to reverse it */
        n3 = vfp->node_index[1]; 
        for (v=0; v<nnodes-2; v++)
        {

          if (v==0)
          {
            n1 = vfp->node_index[0];
          }
          else
          {
            n1 = vfp->node_index[nnodes-v];
          }
          n2 = vfp->node_index[nnodes-v-1];
      
          x1=vnp[n1]->x;
          y1=vnp[n1]->y;
          z1=vnp[n1]->z;
          x2=vnp[n2]->x;
          y2=vnp[n2]->y;
          z2=vnp[n2]->z;
          x3=vnp[n3]->x;
          y3=vnp[n3]->y;
          z3=vnp[n3]->z;

          /* compute determinant of oriented triangle */
          det=x1*(y2*z3-y3*z2)+x2*(y3*z1-y1*z3)+x3*(y1*z2-y2*z1);

          volume+=det;
        }
      }
    }
  }
  volume = volume/6.0;

  return(volume); 
}
Пример #12
0
/*
  Calculate volume of a Voronoi polyhedron
  by summing over all surface triangles of the polyhedron, the quantity:

              |  x1   x2   x3  |
    (1/6) det |  y1   y2   y3  |
              |  z1   z2   z3  |

  where (xn,yn,zn) is vertex n of a surface triangle.  The surface normals of
  all triangles of the polyhedron must point toward the outside of the
  polyhedron.
*/
double polyvol_2(struct tet_mesh *tet_mesh, struct node *node)
{
  struct node **nodes;
  struct edge_list *elp;
  struct edge *ep;
  struct voronoi_facet *vfp;
  struct vector3 p1,p2,pint,v1,v2,v_node,v_norm;
  struct vector3 **vnp;
  double x1,x2,x3,y1,y2,y3,z1,z2,z3;
  double dot,det,volume;
  double edge_ratio,l1,l2;
  u_int n1;
  u_int n2;
  u_int n3;
  u_int v,nnodes;
  u_int edge_node_index;
  u_int i;
  byte found;

  nodes = tet_mesh->nodes;
  vnp=tet_mesh->voronoi_nodes;

  /* first find a point on the interior of the Voronoi cell */
  /* this is done by finding an interior Delaunay edge  */
  /* and placing a point 1/4 of the way along this edge away from node */
  i=0;
  found=0;
  for (elp=node->edge_head; elp!=NULL && !found; elp=elp->next)
  {
    ep=elp->edge;

    if (ep->edge_type == INTERIOR)
    {
      if (node->node_index == ep->node_index[0])
      {
        edge_node_index=ep->node_index[1];
        p1.x=nodes[ep->node_index[0]]->x;
        p1.y=nodes[ep->node_index[0]]->y;
        p1.z=nodes[ep->node_index[0]]->z;
        p2.x=nodes[ep->node_index[1]]->x;
        p2.y=nodes[ep->node_index[1]]->y;
        p2.z=nodes[ep->node_index[1]]->z;
      } 
      else
      {
        edge_node_index=ep->node_index[0];
        p1.x=nodes[ep->node_index[1]]->x;
        p1.y=nodes[ep->node_index[1]]->y;
        p1.z=nodes[ep->node_index[1]]->z;
        p2.x=nodes[ep->node_index[0]]->x;
        p2.y=nodes[ep->node_index[0]]->y;
        p2.z=nodes[ep->node_index[0]]->z;
      }
      vectorize(&p1,&p2,&v1);
      pint.x=p1.x+0.25*v1.x;
      pint.y=p1.y+0.25*v1.y;
      pint.z=p1.z+0.25*v1.z;
      found=1;
      if (node->node_index==1791)
      {
        printf("polyvol: node %u  using interior edge %u to %u\n",node->node_index,i,edge_node_index);
      }
    }
    i++;
  }

/*
  if (!found)
  {
    fprintf(stderr,"polyvol: warning: no interior point found for node %u\n",node->node_index);
  }
*/

  /* Set interior point to node if no suitable interior edge is found */
  if (!found)
  {
    pint.x=node->x;
    pint.y=node->y;
    pint.z=node->z;
  }


  i=0;
  volume = 0.0;

  for (elp=node->edge_head; elp!=NULL; elp=elp->next)
  {
    ep=elp->edge;

    if ((node->node_type!=INTERFACE)
        || (node->node_type==INTERFACE && ep->edge_type!=VIRTUAL))
    {
      for (vfp=ep->facet; vfp!=NULL; vfp=vfp->next)
      {

        /* orient and triangulate each facet.*/

        /* calculate facet edge length ratio of consecutive edges */
        /* find two consecutive edges with a reasonable ratio */
        /* this procedure avoids nearly coincident tet circumcenters */
        found=0;
        for (v=0; v<vfp->nnodes && !found; v++)
        {
          if (v==0)
          {
            n2 = vfp->node_index[v+1];
            n3 = vfp->node_index[vfp->nnodes-1];
          }
          else if (v==vfp->nnodes-1)
          {
            n2 = vfp->node_index[0];
            n3 = vfp->node_index[v-1];
          }
          else
          {
            n2 = vfp->node_index[v+1];
            n3 = vfp->node_index[v-1];
          }
          n1 = vfp->node_index[v]; 
          p1.x = vnp[n1]->x; 
          p1.y = vnp[n1]->y; 
          p1.z = vnp[n1]->z; 
          p2.x = vnp[n2]->x; 
          p2.y = vnp[n2]->y; 
          p2.z = vnp[n2]->z; 
          vectorize(&p1,&p2,&v1);
          p2.x = vnp[n3]->x; 
          p2.y = vnp[n3]->y; 
          p2.z = vnp[n3]->z; 
          vectorize(&p1,&p2,&v2);
          l1=vect_length(&v1);
          l2=vect_length(&v2);
          if (l1<l2)
          {
            edge_ratio=l1/l2;
          }
          else
          {
            edge_ratio=l2/l1;
          }
          if (edge_ratio>1e-9)
          {
            found=1;
          }
        }

/*
        if (!found)
        {
          fprintf(stderr,"polyvol: warning: no suitable edge length ratio found %u\n",node->node_index);
        }
*/

      /* determine orientation of Voronoi facet */
        /* construct vector from interior node to first vertex of facet */
        p1.x = vnp[n1]->x; 
        p1.y = vnp[n1]->y; 
        p1.z = vnp[n1]->z; 
/*
        p2.x=node->x;
        p2.y=node->y;
        p2.z=node->z;
*/
        p2.x=pint.x;
        p2.y=pint.y;
        p2.z=pint.z;
        vectorize(&p2,&p1,&v_node);
        normalize(&v_node);

        /* construct normal vector of facet */
        p2.x = vnp[n2]->x; 
        p2.y = vnp[n2]->y; 
        p2.z = vnp[n2]->z; 
        vectorize(&p1,&p2,&v1);
        p2.x = vnp[n3]->x; 
        p2.y = vnp[n3]->y; 
        p2.z = vnp[n3]->z; 
        vectorize(&p1,&p2,&v2);
        cross_prod(&v1,&v2,&v_norm);
        normalize(&v_norm);

        dot=dot_prod(&v_node,&v_norm);

        l1=vect_length(&v1);
        l2=vect_length(&v2);
        if (node->node_index==1791)
        {
          printf("polyvol: node %u facet %u n_voronoi_nodes %u dot %.9g l1 %.9g l2 %.9g\n",node->node_index,i,vfp->nnodes,dot,l1,l2);
        }

        nnodes=vfp->nnodes;
        if (dot>=0)
        {
          /* facet normal already points outward */
          n3 = vfp->node_index[nnodes-1]; 
          for (v=0; v<nnodes-2; v++)
          {

            n1 = vfp->node_index[v];
            n2 = vfp->node_index[v+1];
      
            x1=vnp[n1]->x;
            y1=vnp[n1]->y;
            z1=vnp[n1]->z;
            x2=vnp[n2]->x;
            y2=vnp[n2]->y;
            z2=vnp[n2]->z;
            x3=vnp[n3]->x;
            y3=vnp[n3]->y;
            z3=vnp[n3]->z;

            /* compute determinant of oriented triangle */
            det=x1*(y2*z3-y3*z2)+x2*(y3*z1-y1*z3)+x3*(y1*z2-y2*z1);

            volume+=det;
          }
        }
        else
        {
          /* facet normal points inward -- need to reverse it */
          n3 = vfp->node_index[1]; 
          for (v=0; v<nnodes-2; v++)
          {

            if (v==0)
            {
              n1 = vfp->node_index[0];
            }
            else
            {
              n1 = vfp->node_index[nnodes-v];
            }
            n2 = vfp->node_index[nnodes-v-1];
      
            x1=vnp[n1]->x;
            y1=vnp[n1]->y;
            z1=vnp[n1]->z;
            x2=vnp[n2]->x;
            y2=vnp[n2]->y;
            z2=vnp[n2]->z;
            x3=vnp[n3]->x;
            y3=vnp[n3]->y;
            z3=vnp[n3]->z;

            /* compute determinant of oriented triangle */
            det=x1*(y2*z3-y3*z2)+x2*(y3*z1-y1*z3)+x3*(y1*z2-y2*z1);

            volume+=det;
          }
        }
      }
    }
    i++;
  }
  volume = volume/6.0;

  return(volume); 
}
Пример #13
0
/*
  Calculate volume of a Voronoi polyhedron
  This is done by creating a tetrahedralization of the Voronoi cell
  and then summing the volumes of all tets.
  The volume of each tet is given by:

    (1/6) * abs(dot_prod(a,cross_prod(b,c)))

  where a, b, and c are three edges of the tet that share a common
  vertex of the tet.
*/
double polyvol_1(struct tet_mesh *tet_mesh, struct node *node)
{
  struct node **nodes;
  struct edge_list *elp;
  struct edge *ep;
  struct voronoi_facet *vfp;
  struct vector3 p1,p2,a,b,c,bxc;
  struct vector3 **vnp;
  double volume,facet_volume;
  u_int i;

  nodes = tet_mesh->nodes;
  vnp=tet_mesh->voronoi_nodes;

  volume = 0.0;
  for (elp=node->edge_head; elp!=NULL; elp=elp->next)
  {
    ep=elp->edge;

    if ((node->node_type!=INTERFACE)
        || (node->node_type==INTERFACE && ep->edge_type!=VIRTUAL))
    {
      /* use the central node of the Voronoi cell as the apex of each tet */
      p1.x=node->x;
      p1.y=node->y;
      p1.z=node->z;

      /* Triangulate each Voronoi facet and use each triangle as */
      /* the base of each tet */
      for (vfp=ep->facet; vfp!=NULL; vfp=vfp->next)
      {
        facet_volume=0;

        for (i=2; i<vfp->nnodes; i++)
        {
          p2.x=vnp[vfp->node_index[0]]->x;
          p2.y=vnp[vfp->node_index[0]]->y;
          p2.z=vnp[vfp->node_index[0]]->z;
          vectorize(&p1,&p2,&a);

          p2.x=vnp[vfp->node_index[i-1]]->x;
          p2.y=vnp[vfp->node_index[i-1]]->y;
          p2.z=vnp[vfp->node_index[i-1]]->z;
          vectorize(&p1,&p2,&b);

          p2.x=vnp[vfp->node_index[i]]->x;
          p2.y=vnp[vfp->node_index[i]]->y;
          p2.z=vnp[vfp->node_index[i]]->z;
          vectorize(&p1,&p2,&c);

          cross_prod(&b,&c,&bxc);

          facet_volume += dot_prod(&a,&bxc);
        }
      }
      volume += fabs(facet_volume);
    }
  }

  volume = volume/6.0;
  
  return(volume);

}
Пример #14
0
void main()
{
    FILE* fp;
    fp=fopen("ls_mb.txt","a");
    fprintf(fp,"-----------------------------------------------\n");
    fprintf(fp,"             start of program                  \n");
    fprintf(fp,"-------------------------------------------------");
    printf("Enter no of nodes:");
    scanf("%d",&no_of_node);
    printf("\nTotal nodes in the network: %d",no_of_node);
    fprintf(fp,"\nTotal nodes in the network: %d",no_of_node);
    for(a=2; a<200; a++)
    {
        count=0;
        for(a1=1; a1<=(a/2); a1++)
        {
            if(a1!=1)
            {
                if((a%a1)==0)
                    count+=1;
            }
        }
        if(count==0)
        {
            prime[zp]=a;
            prime[++zp]=a*a;
            zp++;
        }
    }
    temp=0;
    for (i=0; i<zp-1; i++)
    {
        for (j=0; j<zp-1-i; j++)
        {
            if (prime[j]>prime[j+1])
            {
                temp=prime[j];
                prime[j]=prime[j+1];
                prime[j+1]=temp;
            }
        }
    }
    temp=0;

//finding q for given n where k=(q*q)
    for(z1=0; z1<zp; z1++)
    {
        z2=prime[z1];
        temp=z2*z2;
        if(no_of_node<=temp)
        {
            p=prime[z1];
            break;
        }
    }
    for(z1=0; z1<zp; z1++)
    {
        z2=prime[z1];
        temp=z2*z2;
        if(no_of_node<=temp)
        {
            r=prime[z1];
            break;
        }
    }
    int pt;
    if(isprime(p)==1)
        pt=p;
    if(isprime(p)==0)
        pt=sqrt(p);
    int r1=r*r;
    float r1c2=r1*(r1-1)*0.5;
   // fprintf(fp,"\nqt : %d\n",pt);
    printf("\n p=%d",p);
    printf("\n r=%d",r);
    printf("\nenter value of k(2-%d) (keys per node)",p);
    scanf("%d",&k);
    fprintf(fp,"\nkeys per node : %d",k);
    fprintf(fp,"\nr : %d",r);
    int x=r+1;
    float px=(float) k/x;
    //printf("\npx: %f",px);
    //fprintf(fp,"\npx: %f",px);
    //printf("\nnodes: \n");
    //fprintf(fp,"\n p=%d",p);
    //fprintf(fp,"\nnodes: \n");

    for(i=0; i<p; i++)
    {
        for(j=0; j<p; j++)
        {
            node[count1][0]=i;
            node[count1][1]=j;
            count1++;
            //printf("N(%d,%d) ",i,j);
 //           fprintf(fp,"N(%d,%d) ",i,j);
        }
       // printf(";;\n");
   //     fprintf(fp,"\n");
    }
//printf("%d",count1);
//set of keys
    //fprintf(fp,"\n keys : \n");
  /*  for(a1=0; a1<k; a1++)
    {
        for(a2=0; a2<p; a2++)
        {
            fprintf(fp,"(%d,%d)",a1,a2);
        }
        fprintf(fp,"\n");
    }*/
    a1=0;
    a2=0;
    a3=0;
// calculating keys
    int l_t;
    if(isprime(p)==1)
    {
        for(a1=0; a1<p; a1++)  //a:a1 b:a2 x:a3 key(x,ax+b mod p)
        {
            for(a2=0; a2<p; a2++)
            {
                for(a3=0; a3<k; a3++)
                {
                    key_set[a1*p+a2][a3][0]=a3;
                    key_set[a1*p+a2][a3][1]=((a1*a3)+a2)%p;
                }
            }
        }
    }

    else
    {
        vectorize(p);
        printf("\nEnter the irreducable polynomial in z(%d)(From higher to lower degree)",pt);
        for(l_t=2;l_t>=0;l_t--)
        {
            printf("\nX^%d:",l_t);
            scanf("%d",&irr_poly[l_t]);
        }
        for(a1=0; a1<p; a1++)  //a:a1 b:a2 x:a3 key(x,ax+b mod p)
        {
            for(a2=0; a2<p; a2++)
            {
                for(a3=0; a3<k; a3++)
                {
                    key_set[a1*p+a2][a3][0]=a3;

                    poly_a[0]=vector[a1][0];
                    poly_a[1]=vector[a1][1];

                    poly_b[0]=vector[a2][0];
                    poly_b[1]=vector[a2][1];

                    poly_x[0]=vector[a3][0];
                    poly_x[1]=vector[a3][1];

                    mulpoly(poly_a,poly_x);
                    addpoly(mul_poly,poly_b);
                    //printf("\n %dX^2+%dX+%d + %dX+%d=%dX^2+%dX+%d",mul_poly[2],mul_poly[1],mul_poly[0],poly_b[1],poly_b[0],add_poly[2],add_poly[1],add_poly[0]);

                    add_poly[0]=add_poly[0]%pt;
                    add_poly[1]=add_poly[1]%pt;
                    add_poly[2]=add_poly[2]%pt;

                    //printf("\n %dX^2+%dX+%d",add_poly[2],add_poly[1],add_poly[0]);

                    while(1)
                    {
                        if((add_poly[2]-irr_poly[2]<0)||(add_poly[1]-irr_poly[1]<0)||(add_poly[0]-irr_poly[0]<0))
                            break;
                        else
                            add_poly[2]=add_poly[2]-irr_poly[2];
                            add_poly[1]=add_poly[1]-irr_poly[1];
                            add_poly[0]=add_poly[0]-irr_poly[0];
                    }

                    //printf("\n %dX^2+%dX+%d",add_poly[2],add_poly[1],add_poly[0]);

                    if((add_poly[2]!=0)&&(add_poly[1]!=0)&&(add_poly[0]==0))   //const 0
                    {
                        add_poly[1]=add_poly[1]+add_poly[2]*irr_poly[1];
                        add_poly[0]=add_poly[2]*get_x_bar(irr_poly[0],pt);
                        add_poly[2]=0;
                    }

                    if((add_poly[2]!=0)&&(add_poly[1]==0)&&(add_poly[0]!=0))     //X 0
                    {
                        add_poly[1]=add_poly[2]*irr_poly[1];
                        add_poly[0]=add_poly[0]+add_poly[2]*get_x_bar(irr_poly[0],pt);
                        add_poly[2]=0;
                    }

                    if((add_poly[2]!=0)&&(add_poly[1]==0)&&(add_poly[0]==0))        //const,X 0
                    {
                        add_poly[1]=add_poly[2]*irr_poly[1];
                        add_poly[0]=add_poly[2]*get_x_bar(irr_poly[0],pt);
                        add_poly[2]=0;
                    }

                    add_poly[0]=add_poly[0]%pt;
                    add_poly[1]=add_poly[1]%pt;
                    add_poly[2]=add_poly[2]%pt;

                    //printf("\n %dX^2+%dX+%d",add_poly[2],add_poly[1],add_poly[0]);

                    if((add_poly[2]==0)&&(add_poly[1]==0)&&(add_poly[0]==0))          //all 0
                    {
                        key_set[a1*p+a2][a3][1]=0;
                    }


                    if((add_poly[2]==0)&&(add_poly[1]!=0)&&(add_poly[0]!=0))       //X^2 0
                    {
                        key_set[a1*p+a2][a3][1]=add_poly[1]*pt+add_poly[0];
                    }

                    if((add_poly[2]==0)&&(add_poly[1]!=0)&&(add_poly[0]==0))        //X^2, const 0
                    {
                        key_set[a1*p+a2][a3][1]=add_poly[1]*pt;
                    }

                    if((add_poly[2]==0)&&(add_poly[1]==0)&&(add_poly[0]!=0))         //X^2,X 0
                    {
                        key_set[a1*p+a2][a3][1]=add_poly[0];
                    }



                    for(l_t=2;l_t>=0;l_t--)
                    {
                        add_poly[l_t]=0;
                        mul_poly[l_t]=0;
                    }
                }
            }
        }
    }
//print keys
    //fprintf(fp,"\n");
    printf("\n");
    //convert keys to single number
    for(a1=0; a1<p; a1++)
    {
        for(a2=0; a2<p; a2++)
        {
            for(a3=0; a3<k; a3++)
            {
                key_set_stat[a1*p+a2][a3]=key_set[a1*p+a2][a3][0]+key_set[a1*p+a2][a3][1]*p;
            }
        }
    }

    /*for(a1=0; a1<p; a1++)
    {
        for(a2=0; a2<p; a2++)
        {
            for(a3=0; a3<k; a3++)
            {
                printf("%d, ",key_set_stat[a1*p+a2][a3]);
            }
            printf("\n");
        }
    }*/

    // calculate E(s) and V(s)
    int compromised_node,a4,compromised[500];
    printf("Enter number of compromised nodes");
    scanf("%d",&compromised_node);
    for(a4=0; a4<compromised_node; a4++)
    {
        compromised[a4]=rand()%no_of_node;
    }
    //printf("\n compromised node ids : ");
    /*for(a4=0; a4<compromised_node; a4++)
    {
        printf("\n%d",compromised[a4]);
    }*/
    //printf("\ncompromised keys::");
    int compromised_keys[10000];
    count1=0;
    for(a1=0; a1<compromised_node; a1++)
    {
        //printf("C%d",compromised[a1]);
        for(a2=0; a2<k; a2++)
        {
            compromised_keys[count1]=key_set_stat[compromised[a1]][a2];
            //printf("%d,",compromised_keys[count1]);
            count1+=1;
        }
        //printf("\n");
    }
    //printf("\ncount1=%d",count1);
    //E(s) calculation
    int unique_key=0;
   for(a1=0;a1<15000;a1++)
    {
        key_ES[a1]=0;
    }
    for(a1=0;a1<count1;a1++)
    {
        key_ES[compromised_keys[a1]]++;
    }
    for(a1=0;a1<15000;a1++)
    {
        if(key_ES[a1]!=0)
        unique_key++;
    }
    printf("\n U:%d",unique_key);

    float broken_links,total_links,es;
    broken_links=(float)unique_key*nc2(p);
    total_links=(float)p*k*nc2(p);
    es=broken_links/total_links;
    printf("\nes::%f",es);

    fprintf(fp,"-----------------------------------------------\n");
    fprintf(fp,"             end of program                  \n");
    fprintf(fp,"-------------------------------------------------");
}
Пример #15
0
void main()
{
    FILE* fp;
    fp=fopen("rs.txt","a");
    fprintf(fp,"-----------------------------------------------\n");
    fprintf(fp,"             start of program                  \n");
    fprintf(fp,"-------------------------------------------------");
    printf("Enter no of nodes:");
    scanf("%d",&no_of_node);
    printf("\nTotal nodes in the network: %d",no_of_node);
    fprintf(fp,"\nTotal nodes in the network: %d",no_of_node);
    for(a=2; a<120; a++)
    {
        count=0;
        for(a1=1; a1<=(a/2); a1++)
        {
            if(a1!=1)
            {
                if((a%a1)==0)
                    count+=1;
            }
        }
        if(count==0)
        {
            prime[zp]=a;
            prime[++zp]=a*a;
            zp++;
        }
    }
    temp=0;
    for (i=0; i<zp-1; i++)
    {
        for (j=0; j<zp-1-i; j++)
        {
            if (prime[j]>prime[j+1])
            {
                temp=prime[j];
                prime[j]=prime[j+1];
                prime[j+1]=temp;
            }
        }
    }
    temp=0;

//finding q for given n where k=(q*q)
    for(z1=0; z1<zp; z1++)
    {
        z2=prime[z1];
        temp=z2*z2;
        if(no_of_node<=temp)
        {
            p=prime[z1];
            break;
        }
    }
    for(z1=0; z1<zp; z1++)
    {
        z2=prime[z1];
        temp=z2*z2;
        if(no_of_node<=temp)
        {
            r=prime[z1];
            break;
        }
    }
    int pt;
    if(isprime(p)==1)
        pt=p;
    if(isprime(p)==0)
        pt=sqrt(p);
    int r1=r*r;
    float r1c2=r1*(r1-1)*0.5;
    fprintf(fp,"\nqt : %d\n",pt);
    printf("\n p=%d",p);
    k=p;
    printf("\n k(keys per node) %d",p-1);
    fprintf(fp,"\nk : %d",k);
    int x=r+1;
    float px=(float) k/x;
    fprintf(fp,"\n p=%d",p);

    for(i=0; i<p; i++)
    {
        for(j=0; j<p; j++)
        {
            node[count1][0]=i;
            node[count1][1]=j;
            count1++;
            //printf("N(%d,%d) ",i,j);
            //fprintf(fp,"N(%d,%d) ",i,j);
        }
        //printf(";;\n");
        //fprintf(fp,"\n");
    }
//printf("%d",count1);
//set of keys
   /* fprintf(fp,"\n keys : \n");
    for(a1=0; a1<k; a1++)
    {
        for(a2=0; a2<p; a2++)
        {
            fprintf(fp,"(%d,%d)",a1,a2);
        }
        fprintf(fp,"\n");
    }*/
    a1=0;
    a2=0;
    a3=0;
// calculating keys
    int l_t;
    if(isprime(p)==1)
    {
        for(a1=0; a1<p; a1++)  //a:a1 b:a2 x:a3 key(ax+b mod p,x)
        {
            for(a2=0; a2<p; a2++)
            {
                for(a3=1; a3<k; a3++)
                {
                    key_set[a1*p+a2][a3][0]=((a1*a3)+a2)%p;
                    key_set[a1*p+a2][a3][1]=a3;
                }
            }
        }
    }

    else
    {
        vectorize(p);
        printf("\nEnter the irreducable polynomial in z(%d)(From higher to lower degree)",pt);
        for(l_t=2;l_t>=0;l_t--)
        {
            printf("\nX^%d:",l_t);
            scanf("%d",&irr_poly[l_t]);
        }
        for(a1=0; a1<p; a1++)  //a:a1 b:a2 x:a3 key(ax+b mod p,x)
        {
            for(a2=0; a2<p; a2++)
            {
                for(a3=1; a3<k; a3++)
                {
                    key_set[a1*p+a2][a3][1]=a3;

                    poly_a[0]=vector[a1][0];
                    poly_a[1]=vector[a1][1];

                    poly_b[0]=vector[a2][0];
                    poly_b[1]=vector[a2][1];

                    poly_x[0]=vector[a3][0];
                    poly_x[1]=vector[a3][1];

                    mulpoly(poly_a,poly_x);
                    addpoly(mul_poly,poly_b);
                    //printf("\n %dX^2+%dX+%d + %dX+%d=%dX^2+%dX+%d",mul_poly[2],mul_poly[1],mul_poly[0],poly_b[1],poly_b[0],add_poly[2],add_poly[1],add_poly[0]);

                    add_poly[0]=add_poly[0]%pt;
                    add_poly[1]=add_poly[1]%pt;
                    add_poly[2]=add_poly[2]%pt;

                    //printf("\n %dX^2+%dX+%d",add_poly[2],add_poly[1],add_poly[0]);

                    while(1)
                    {
                        if((add_poly[2]-irr_poly[2]<0)||(add_poly[1]-irr_poly[1]<0)||(add_poly[0]-irr_poly[0]<0))
                            break;
                        else
                            add_poly[2]=add_poly[2]-irr_poly[2];
                            add_poly[1]=add_poly[1]-irr_poly[1];
                            add_poly[0]=add_poly[0]-irr_poly[0];
                    }

                    //printf("\n %dX^2+%dX+%d",add_poly[2],add_poly[1],add_poly[0]);

                    if((add_poly[2]!=0)&&(add_poly[1]!=0)&&(add_poly[0]==0))   //const 0
                    {
                        add_poly[1]=add_poly[1]+add_poly[2]*irr_poly[1];
                        add_poly[0]=add_poly[2]*get_x_bar(irr_poly[0],pt);
                        add_poly[2]=0;
                    }

                    if((add_poly[2]!=0)&&(add_poly[1]==0)&&(add_poly[0]!=0))     //X 0
                    {
                        add_poly[1]=add_poly[2]*irr_poly[1];
                        add_poly[0]=add_poly[0]+add_poly[2]*get_x_bar(irr_poly[0],pt);
                        add_poly[2]=0;
                    }

                    if((add_poly[2]!=0)&&(add_poly[1]==0)&&(add_poly[0]==0))        //const,X 0
                    {
                        add_poly[1]=add_poly[2]*irr_poly[1];
                        add_poly[0]=add_poly[2]*get_x_bar(irr_poly[0],pt);
                        add_poly[2]=0;
                    }

                    add_poly[0]=add_poly[0]%pt;
                    add_poly[1]=add_poly[1]%pt;
                    add_poly[2]=add_poly[2]%pt;

                    //printf("\n %dX^2+%dX+%d",add_poly[2],add_poly[1],add_poly[0]);

                    if((add_poly[2]==0)&&(add_poly[1]==0)&&(add_poly[0]==0))          //all 0
                    {
                        key_set[a1*p+a2][a3][0]=0;
                    }


                    if((add_poly[2]==0)&&(add_poly[1]!=0)&&(add_poly[0]!=0))       //X^2 0
                    {
                        key_set[a1*p+a2][a3][0]=add_poly[1]*pt+add_poly[0];
                    }

                    if((add_poly[2]==0)&&(add_poly[1]!=0)&&(add_poly[0]==0))        //X^2, const 0
                    {
                        key_set[a1*p+a2][a3][0]=add_poly[1]*pt;
                    }

                    if((add_poly[2]==0)&&(add_poly[1]==0)&&(add_poly[0]!=0))         //X^2,X 0
                    {
                        key_set[a1*p+a2][a3][0]=add_poly[0];
                    }



                    for(l_t=2;l_t>=0;l_t--)
                    {
                        add_poly[l_t]=0;
                        mul_poly[l_t]=0;
                    }
                }
            }
        }
    }
//print keys
    //fprintf(fp,"\n");
    //printf("\n");
    //printf("Node                                            keys");
    //printf("\n----------------------------------------------------------\n");
    //for(a1=0; a1<p; a1++)
    //{
      //  for(a2=0; a2<p; a2++)
        //{
          //  printf("Node(%d,%d) => %d => ",a1,a2,(a1*p+a2));
            //for(a3=1; a3<k; a3++)
            //{
              //  printf("(%d,%d);",key_set[a1*p+a2][a3][0],key_set[a1*p+a2][a3][1]);
                //fprintf(fp,"(%d,%d);",key_set[a1*p+a2][a3][0],key_set[a1*p+a2][a3][1]);
            //}
            //countt++;
            //printf("\n");
            //fprintf(fp,"\n");
        //}
        //printf("\n\n\n");
    //}
    //fprintf(fp,"\n countt= %d\n",countt);
    // calculate E(s) and V(s)
    int compromised_node,a4,compromised[500];
    printf("\n\nEnter number of compromised nodes");
    scanf("%d",&compromised_node);
    for(a4=0; a4<compromised_node; a4++)
    {
        compromised[a4]=rand()%no_of_node;
    }
    printf("\n compromised node ids : ");
    fprintf(fp,"\n compromised node ids : ");
    for(a4=0; a4<compromised_node; a4++)
    {
        printf("\n%d",compromised[a4]);
        fprintf(fp,"\n%d",compromised[a4]);
    }
    //printf("\ncompromised keys::");
    //fprintf(fp,"\ncompromised keys::");
    int compromised_keys[100000][2];
    count1=0;
    for(a1=0; a1<compromised_node; a1++)
    {
        for(a2=1; a2<k; a2++)
        {
            compromised_keys[count1][0]=key_set[compromised[a1]][a2][0];
            compromised_keys[count1][1]=key_set[compromised[a1]][a2][1];
          //  printf("(%d,%d)",compromised_keys[count1][0],compromised_keys[count1][1]);
            count1++;
        }
    }

    int count2=0,node_list[100000];
    int flag2=0;
    int flag_broken=0;
    int common_key[50000][2];
    //checking links
    for(a1=0; a1<no_of_node; a1++)
    {

        for(a2=0; a2<compromised_node; a2++)
        {
            if(a1==compromised[a2])
            {
                node_list[a1]=-1;
                break;
            }
            else
                node_list[a1]=a1;
        }            //disable compromised nodes
    }
    for(a1=0; a1<no_of_node; a1++)
        fprintf(fp,"\n%d",node_list[a1]);

    for(a1=0; a1<no_of_node; a1++)
    {
        count2=0;
        if(node_list[a1]==-1)
        {
            continue;
        }
        for(a2=0; a2<no_of_node; a2++)
        {
            if(node_list[a2]==-1)
                continue;
            if(a1==a2)
            {
                continue;
            }

            count2=0;
            for(a3=1; a3<k; a3++)
            {
                for(a4=1; a4<k; a4++)
                {
                    if(key_set[a1][a3][0]==key_set[a2][a4][0] && key_set[a1][a3][1]==key_set[a2][a4][1])
                    {
                        common_key[count2][0]=key_set[a1][a3][0];
                        common_key[count2][1]=key_set[a1][a3][1];
                        //fprintf(fp,"(%d,%d);",common_key[count2][0],common_key[count2][1]);
                        count2++;
                        //printf("\nno of common keys between node %d and %d is %d",a1,a2,count2);
                        //fprintf(fp,"\nno of common keys between node %d and %d is %d",a1,a2,count2);
                    }
                }
            }
            if(a1!=a2)
            {
                printf("\nno of common keys between node %d and %d is %d",a1,a2,count2);
                //fprintf(fp,"\nno of common keys between node %d and %d is %d",a1,a2,count2);
            }

            for(a5=0; a5<count2; a5++)
            {
                for(a6=0; a6<count1; a6++)
                {
                    if((common_key[a5][0]==compromised_keys[a6][0])&&(common_key[a5][1]==compromised_keys[a6][1]))
                        flag2+=1;
                }
            }

            if(flag2!=0)
            {
                flag_broken+=1;
            }
            flag2=0;
            count2=0;
        }
        for(a5=0; a5<count2; a5++)
        {
            common_key[a5][0]=9999;
            common_key[a5][1]=9999;
        }
    }
    flag_broken=flag_broken/2;                                                              //eliminate 2 way communication
    printf("\nbroken links: %d\n",flag_broken);
    fprintf(fp,"\nbroken links: %d\n",flag_broken);
    float total_links;
    total_links=p*p*(p-1)*(p-1)*0.5;
    printf("\nTotal links : %.0f",total_links);
    fprintf(fp,"\nTotal links : %0.f,",total_links);
    float es;
    es=(float) flag_broken/total_links;
    printf("\nE(s)=%f",es);
    fprintf(fp,"\nE(s)=%f",es);
    fprintf(fp,"-----------------------------------------------\n");
    fprintf(fp,"             end of program                  \n");
    fprintf(fp,"-------------------------------------------------");
}
Пример #16
0
void polycent(struct tet_mesh *tet_mesh)

{
  struct polygon_list *plp;
  struct polygon *pop;
  struct vector3 p1,p2,mid1,mid2;
  struct vector3 n1,n2,n3;
  struct vector3 xp1,xp2,xp3;
  double d1,d2,d3;
  double dot1;

  for (plp=tet_mesh->boundary_head; plp!=NULL; plp=plp->next)
  {
    pop=plp->polygon;

    p1.x=tet_mesh->nodes[pop->node_index[0]]->x;
    p1.y=tet_mesh->nodes[pop->node_index[0]]->y;
    p1.z=tet_mesh->nodes[pop->node_index[0]]->z;
    p2.x=tet_mesh->nodes[pop->node_index[1]]->x;
    p2.y=tet_mesh->nodes[pop->node_index[1]]->y;
    p2.z=tet_mesh->nodes[pop->node_index[1]]->z;
    mid1.x=0.5*(p1.x+p2.x);
    mid1.y=0.5*(p1.y+p2.y);
    mid1.z=0.5*(p1.z+p2.z);
    vectorize(&p1,&p2,&n1);
    normalize(&n1);
    d1=dot_prod(&mid1,&n1);

    p2.x=tet_mesh->nodes[pop->node_index[2]]->x;
    p2.y=tet_mesh->nodes[pop->node_index[2]]->y;
    p2.z=tet_mesh->nodes[pop->node_index[2]]->z;
    mid2.x=0.5*(p1.x+p2.x);
    mid2.y=0.5*(p1.y+p2.y);
    mid2.z=0.5*(p1.z+p2.z);
    vectorize(&p1,&p2,&n2);
    normalize(&n2);
    d2=dot_prod(&mid2,&n2);

    cross_prod(&n1,&n2,&n3);
    normalize(&n3);
    d3=dot_prod(&p1,&n3);

    cross_prod(&n2,&n3,&xp1);
    cross_prod(&n3,&n1,&xp2);
    cross_prod(&n1,&n2,&xp3);
    dot1=dot_prod(&n1,&xp1);

    xp1.x=d1*xp1.x;
    xp1.y=d1*xp1.y;
    xp1.z=d1*xp1.z;
    
    xp2.x=d2*xp2.x;
    xp2.y=d2*xp2.y;
    xp2.z=d2*xp2.z;

    xp3.x=d3*xp3.x;
    xp3.y=d3*xp3.y;
    xp3.z=d3*xp3.z;

    pop->cent.x=(xp1.x+xp2.x+xp3.x)/dot1;
    pop->cent.y=(xp1.y+xp2.y+xp3.y)/dot1;
    pop->cent.z=(xp1.z+xp2.z+xp3.z)/dot1;

  }

  return;
}
Пример #17
0
void HMM::_fwdback(mat init_state_distrib, mat _transmat, mat obslik,
		mat &alpha, mat &beta, mat& gamma, double &loglik, mat &xi_summed,
		cube &gamma2, cube &obslik2,
		bool fwd_only, bool compute_gamma2) {

	/*
	 * Compute the posterior probs. in an HMM using the forwards backwards algo.
	 *
	 * Notation:
	 *  Y(t) = observation, Q(t) = hidden state, M(t) = mixture variable (for MOG outputs)
	 *  A(t) = discrete input (action) (for POMDP models)
	 *
	 * INPUT:
	 *  init_state_distrib(i) = Pr(Q(1) = i)
	 *  transmat(i,j) = Pr(Q(t) = j | Q(t-1)=i)
	 *   or transmat{a}(i,j) = Pr(Q(t) = j | Q(t-1)=i, A(t-1)=a) if there are discrete inputs
	 *  obslik(i,t) = Pr(Y(t)| Q(t)=i)
	 *
	 */

	bool scaled = true;
	bool maximize = false;
	bool compute_xi = true;

	int Q = obslik.n_rows;
	int T = obslik.n_cols;

	mat mixmat;
	mat act;	// qui act è tutti zero, altrimenti potrebbe essere un input, TODO aggiungere &act negli input
	mat scale;

	if (obslik2.is_empty())
		compute_gamma2 = false;

	act = zeros(1,T);			// TODO this could be a colvec
	scale = ones(1,T);
	field<mat> transmat(1,1);
	transmat(0,0) = _transmat;

	// scale(t) = Pr(O(t) | O(1:t-1)) = gamma21/c(t) as defined by Rabiner (1989).
	// Hence prod_t scale(t) = Pr(O(1)) Pr(O(2)|O(1)) Pr(O(3) | O(1:2)) ... = Pr(O(1), ... ,O(T))
	// or log P = sum_t log scale(t).
	// Rabiner suggests multiplying beta(t) by scale(t), but we can instead
	// normalise beta(t) - the constants will cancel when we compute gamma.

	if (compute_xi)
		xi_summed = zeros(Q,Q);
	//else
	// xi_summed = [];

	//%%%%%%%%% Forwards %%%%%%%%%%
	//cout << "fwdback > Forwards" << endl;

	int t = 0;
	alpha.col(0) = vectorize(init_state_distrib) % obslik.col(t);
	if (scaled){
		std::pair<mat,double> _tmp = normaliseC(alpha.col(t));
		alpha.col(t) = _tmp.first;
		scale(t) = _tmp.second;
	}

	for(int t=1; t<T; t++) {
		mat trans;
		mat m;

		trans = transmat(act(t-1));

		if (maximize){
			//m = max_mult(trans.t(), alpha.col(t-1)); // TODO max_mult
		} else {
			m = trans.t() * alpha.col(t-1);
		}

		alpha.col(t) = vectorize(m) % obslik.col(t);

		if (scaled) {
			std::pair<mat,double> _tmp = normaliseC(alpha.col(t));
			alpha.col(t) = _tmp.first;
			scale(t) = _tmp.second;
		}

		if (compute_xi && fwd_only) {// useful for online EM
			xi_summed = xi_summed + normalise((alpha.col(t-1) * obslik.col(t).t()) % trans);
		}
	}

	if (scaled) {
		uvec _s = find(scale);  	// se c'è almeno uno zero
									// portando a logaritmo c'è almeno un infinito
									// quindi somma tutto a infinito
		if ( _s.is_empty() ) {
			loglik = -std::numeric_limits<double>::max();
		} else {
			loglik = sum(sum(log(scale))); // nested arma::sum because sum(mat X) return a rowvec
		}
	} else {
		loglik = log(sum(alpha.col(T)));
	}

	if (fwd_only) {
		gamma = alpha;
		return;
	}

	//%%%%%%%%% Backwards %%%%%%%%%%
	//cout << "fwdback > Backwards" << endl;

	int M;
	mat trans;
	mat denom;

	beta = zeros(Q,T);
	if (compute_gamma2) {
		M = mixmat.n_cols;
		gamma2 = zeros(Q,M,T);
	} else {
		//gamma2 = []
	}

	beta.col(T-1) = ones(Q,1);

	gamma.col(T-1) = normalise(alpha.col(T-1) % beta.col(T-1));
	t=T-1;

	if (compute_gamma2) {
		denom = obslik.col(t) + (obslik.col(t)==0); // replace 0s with 1s before dividing
		gamma2.slice(t) = obslik2.slice(t) % mixmat % repmat(gamma.col(t), 1, M) % repmat(denom, 1, M);
	}

	for (int t=T-2; t>=0; t--) { // T-2 because there are some calls to t+1
								 // and col(T) will generate the error Mat::col(): out of bounds
					             // so we must assure the limit of col(T-1)
		mat b = beta.col(t+1) % obslik.col(t+1);
		trans = transmat(act(t));
		if (maximize){
			mat B = repmat(vectorize(b).t(), Q, 1);
			beta.col(t) = max(trans % B, 1);
		} else
			beta.col(t) = trans * b;

		if (scaled)
			beta.col(t) = normalise( beta.col(t) );

		gamma.col(t) = normalise(alpha.col(t) % beta.col(t));

		if (compute_xi){
			xi_summed = xi_summed + normalise((trans % (alpha.col(t) * b.t())));
		}

		if (compute_gamma2){
			denom = obslik.col(t) + (obslik(t)==0); // replace 0s with 1s before dividing
			gamma2.slice(t) = obslik2.slice(t) % mixmat % repmat(gamma.col(t), 1, M) % repmat(denom, 1, M);
		}
	}
}
        RecognitionResult GeometricRecognizer::recognize(Path2D points, string method)
	{
		//--- Make sure we have some templates to compare this to
		//---  or else recognition will be impossible
		if (templates.empty())
		{
			std::cout << "No templates loaded so no symbols to match." << std::endl;
                        return RecognitionResult("Unknown", 0);
		}

		points = normalizePath(points);
	
		//--- Initialize best distance to the largest possible number
		//--- That way everything will be better than that
                double bestDistance = MAX_DOUBLE;
		//--- We haven't found a good match yet
		int indexOfBestMatch = -1;
                double score = 0.0;

                    //--- Check the shape passed in against every shape in our database
                    for (int i = 0; i < (int)templates.size(); i++)
                    {
                        double distance;
                            //--- Calculate the total distance of each point in the passed in
                            //---  shape against the corresponding point in the template
                            //--- We'll rotate the shape a few degrees in each direction to
                            //---  see if that produces a better match
                        if (method=="protractor")
                            distance = optimalCosineDistance(vectorize(points), vectorize(templates[i].points));
                        else
                            distance = distanceAtBestAngle(points, templates[i]);

                            //cout << distance<< " " << bestDistance << " ";
                            //cout << " = " ;
                            if (distance < bestDistance)
                            {
                                    bestDistance     = distance;
                                    indexOfBestMatch = i;
                            }
                    }
                    //--- Turn the distance into a percentage by dividing it by
                    //---  half the maximum possible distance (across the diagonal
                    //---  of the square we scaled everything too)
                    //--- Distance = hwo different they are
                    //--- Subtract that from 1 (100%) to get the similarity
                    if (method=="protractor")
                        { score = bestDistance ? (1.0 / bestDistance) : MAX_DOUBLE ; }
                    else
                        score = 1.0 - (bestDistance / halfDiagonal);
                    //cout << score << "   " << bestDistance<< "   " ;

		//--- Make sure we actually found a good match
		//--- Sometimes we don't, like when the user doesn't draw enough points
		if (-1 == indexOfBestMatch)
		{
			cout << "Couldn't find a good match." << endl;
			return RecognitionResult("Unknown", 1);
		}
		RecognitionResult bestMatch(templates[indexOfBestMatch].name, score);
		return bestMatch;
	};