Exemplo n.º 1
0
/*
 *      Apple trace selection on a given graph.
 */
void
TraceSelection (FGraph graph, int method, double min_prob)
{
  if (graph == 0)
    Punt ("TraceSelection: nil graph");
  if ((min_prob < 0.0) || (min_prob > 1.0))
    Punt ("TraceSelection: min_prob must be within [0..1]");
#ifdef DEBUG
  printf ("### BEFORE\n");
  WriteGraph ("stdout", graph);
#endif
  /*
   *  The old selection program.
   */
  switch (method)
    {
    case SELECT_BY_NODE_WEIGHT:
      best_successor_of = best_successor_1;
      best_predecessor_of = best_predecessor_1;
      min_prob_requirement = 0;
      SelectTraces (graph);
      PlaceTraces (graph);
      break;
    case SELECT_BY_ARC_WEIGHT:
      best_successor_of = best_successor_2;
      best_predecessor_of = best_predecessor_2;
      min_prob_requirement = 0;
      SelectTraces (graph);
      PlaceTraces (graph);
      break;
    case SELECT_BY_MIN_PROB:
      best_successor_of = best_successor_3;
      best_predecessor_of = best_predecessor_3;
      min_prob_requirement = min_prob;
      SelectTraces (graph);
      PlaceTraces (graph);
      break;
    case SELECT_BY_MAX_ARC:
      SelectBySortArc (graph);
      PlaceTraces (graph);
      break;
    default:
      Punt ("TraceSelection: illegal selection method");
    }
#ifdef DEBUG
  printf ("### AFTER\n");
  WriteGraph ("stdout", graph);
#endif
}
Exemplo n.º 2
0
Graph makePairsGraph(const RNAProfileAliMapType &inputMapProfile, const Algebra<double,RNA_Alphabet_Profile> *alg, const Matrix<double> *score_mtrx, double threshold) {
    Graph graph;
    RNAProfileAliMapType::const_iterator it,it2;
    RNAProfileAlignment *f1=NULL,*f2=NULL;

    graph = NewGraph(score_mtrx->xDim());

    for (int i=0; i<score_mtrx->xDim(); i++) {
        Xcoord(graph,i+1) = 0;
        Ycoord(graph,i+1) = 0;
    }

    for (it=inputMapProfile.begin(); it!=inputMapProfile.end(); it++) {
        f1=it->second;
        for (it2=inputMapProfile.begin(); it2->first<it->first; it2++) {
            double score;
            f2=it2->second;

            score=score_mtrx->getAt(it->first-1,it2->first-1);
            if (alg->choice(score,threshold) != threshold) { // is it better than the threshold ?
                AddEdge (graph,it->first,it2->first,(int)(score*100.0));
            }
        }
    }


    WriteGraph (graph,(char*)"test.out");
    return graph;
}
Exemplo n.º 3
0
void Permutator::WriteGraph(Node* n, BYTE* sectionData)
{
	std::memcpy((BYTE*)sectionData + n->GetOffset(), n->GetInstructions(), n->GetSize());
	for (DWORD i = 0; i < n->GetChildren().size(); ++i)
		WriteGraph(n->GetChildren().at(i), sectionData);

	return;
}
Exemplo n.º 4
0
/*************************************************************************
* Let the game begin
**************************************************************************/
main(int argc, char *argv[])
{
  int i, j, ne, nn, etype, numflag=0;
  idxtype *elmnts, *xadj, *adjncy;
  timer IOTmr, DUALTmr;
  char fileout[256], etypestr[4][5] = {"TRI", "TET", "HEX", "QUAD"};

  if (argc != 2) {
    printf("Usage: %s <meshfile>\n",argv[0]);
    exit(0);
  }

  cleartimer(IOTmr);
  cleartimer(DUALTmr);

  starttimer(IOTmr);
  elmnts = ReadMesh(argv[1], &ne, &nn, &etype);
  stoptimer(IOTmr);

  printf("**********************************************************************\n");
  printf("%s", METISTITLE);
  printf("Mesh Information ----------------------------------------------------\n");
  printf("  Name: %s, #Elements: %d, #Nodes: %d, Etype: %s\n\n", argv[1], ne, nn, etypestr[etype-1]);
  printf("Forming Dual Graph... -----------------------------------------------\n");

  xadj = idxmalloc(ne+1, "main: xadj");
  adjncy = idxmalloc(10*ne, "main: adjncy");

  starttimer(DUALTmr);
  METIS_MeshToDual(&ne, &nn, elmnts, &etype, &numflag, xadj, adjncy);
  stoptimer(DUALTmr);

  printf("  Dual Information: #Vertices: %d, #Edges: %d\n", ne, xadj[ne]/2);

  sprintf(fileout, "%s.dgraph", argv[1]);
  starttimer(IOTmr);
  WriteGraph(fileout, ne, xadj, adjncy);
  stoptimer(IOTmr);


  printf("\nTiming Information --------------------------------------------------\n");
  printf("  I/O:          \t\t %7.3f\n", gettimer(IOTmr));
  printf("  Dual Creation:\t\t %7.3f\n", gettimer(DUALTmr));
  printf("**********************************************************************\n");

  GKfree(&elmnts, &xadj, &adjncy, LTERM);

}
Exemplo n.º 5
0
int main(int argc, char *argv[]) {
    graph_t *graph, *fgraph;
    char filename[256];
    idx_t wgtflag;
    params_t params;

    if (argc != 2 && argc != 3) {
        printf("Usage: %s <GraphFile> [FixedGraphFile (for storing the fixed graph)]\n", argv[0]);
        exit(0);
    }

    memset((void *) &params, 0, sizeof(params_t));
    params.filename = gk_strdup(argv[1]);

    graph = ReadGraph(&params);
    if (graph->nvtxs == 0) {
        printf("Empty graph!\n");
        exit(0);
    }

    printf("**********************************************************************\n");
    printf("%s", METISTITLE);
    printf(" (HEAD: %s, Built on: %s, %s)\n", SVNINFO, __DATE__, __TIME__);
    printf(" size of idx_t: %zubits, real_t: %zubits, idx_t *: %zubits\n",
           8 * sizeof(idx_t), 8 * sizeof(real_t), 8 * sizeof(idx_t * ));
    printf("\n");
    printf("Graph Information ---------------------------------------------------\n");
    printf("  Name: %s, #Vertices: %"PRIDX", #Edges: %"PRIDX"\n\n",
           params.filename, graph->nvtxs, graph->nedges / 2);
    printf("Checking Graph... ---------------------------------------------------\n");

    if (CheckGraph(graph, 1, 1)) {
        printf("   The format of the graph is correct!\n");
    } else {
        printf("   The format of the graph is incorrect!\n");
        if (argc == 3) {
            fgraph = FixGraph(graph);
            WriteGraph(fgraph, argv[2]);
            FreeGraph(&fgraph);
            printf("   A corrected version was stored at %s\n", argv[2]);
        }
    }

    printf("\n**********************************************************************\n");

    FreeGraph(&graph);
    gk_free((void **) &params.filename, &params.tpwgtsfile, &params.tpwgts, LTERM);
}  
Exemplo n.º 6
0
int
main(int argc,char *argv[])
{

	srand (time(NULL));

	/*
	 * start with graph of size 8
	 */

	//ReadDump(g);
	
	
	/*
	int og=gsize;
        gsize=100;
        new_g=(int*)malloc(gsize*gsize*sizeof(int));
        CopyGraph(g,og,new_g,gsize);
        free(g);
        g=new_g;
	draw(g,gsize);
	*/

	gsize=125 ;

	printf(" -- \n");

	g=build(gsize);

	PrintGraph(g,gsize);
	WriteGraph(g,gsize);

	count = CliqueCount(g,gsize);

	printf("%d : %d \n",gsize,count);


	return(0);

}
Exemplo n.º 7
0
SaveGraph()
{
   short tx=rasInfo->RxOffset,ty=rasInfo->RyOffset;
   
   Scrollit(-tx,-ty);
   DisplaySprites(FALSE);

   fileRequester->fr_Hail="Save Graph as file";
   strcpy(fileRequester->fr_Dir,"pw:graph");
   strcpy(fileRequester->fr_File,lastgraph); /* Last maze loaded */
   LoadColors(&PlayScreen->ViewPort,FR_COLORS);

#if 1 || REGISTERED_USER
   if(FileRequest(fileRequester))
   {
      strcpy(fr_path,fileRequester->fr_Dir);
      strcpy(fr_name,fileRequester->fr_File);
      strcpy(filename,fr_path);
      if ( !strchr("/:\0",fr_path[strlen(fr_path)-1]) && strlen(fr_path))
         strcat(filename,"/");
      if (strlen(filename) > 1 && strlen(fr_name))
      {
         strcat(filename,fr_name);
         WriteGraph(filename);
      }
   }
#else
   AutoRequest(PlayWindow,&registertext[0],&regpostext,&regnegtext,0L,0L,320,61);
#endif
   SetMazeColors();
   Scrollit(tx,ty);
   ScreenToFront(PlayScreen);
   DisplaySprites(sprites_on);
   ToggleScreenToFront(1);

   return 0;
}
Exemplo n.º 8
0
int
main(int argc,char *argv[])
{
	int *g;
	int *new_g;
	int gsize;
	int count;
	int i;
	int j;
	int best_count;
	int best_i;
	int best_j;
	int best_x;
	int best_y;
	void *taboo_list;

	srand (time(NULL));

	/*
	 * start with graph of size 8
	 */
	gsize = 54;
	g = (int *)malloc(gsize*gsize*sizeof(int));
	if(g == NULL) {
		exit(1);
	}

	/*
	 * make a fifo to use as the taboo list
	 */
	taboo_list = FIFOInitEdge(TABOOSIZE);
	if(taboo_list == NULL) {
		exit(1);
	}

	/*
	 * start out with all zeros
	 */
	memset(g,0,gsize*gsize*sizeof(int));
	ReadGraph(g,gsize);

	/*
	int ns=gsize+10;

	new_g = (int *)malloc((ns)*(ns)*sizeof(int));
	//CopyGraph(g,gsize,new_g,ns);
	GoodCopy(g,gsize,new_g,ns);
	PrintGraph(new_g,ns);
	count = CliqueCount(new_g,ns);
	printf("%d\n",count);
	return ;
	*/
	/*
	 * while we do not have a publishable result
	 */

	int flag=1;
	int lastcount=IMAX;

	while(gsize < 102)
	{
		/*
		 * find out how we are doing
		 */
		count = CliqueCount(g,gsize);

		/*
		 * if we have a counter example
		 */
		if(count == 0)
		{
			printf("Eureka!  Counter-example found!\n");
			PrintGraph(g,gsize);
			WriteGraph(g,gsize);
			/*
			 * make a new graph one size bigger
			 */
			new_g = (int *)malloc((gsize+1)*(gsize+1)*sizeof(int));
			if(new_g == NULL)
				exit(1);
			/*
			 * copy the old graph into the new graph leaving the
			 * last row and last column alone
			 */
			//CopyGraph(g,gsize,new_g,gsize+1);
			GoodCopy(g,gsize,new_g,gsize+1);

			/*
			 * zero out the last column and last row
			for(i=0; i < (gsize+1); i++)
			{
				new_g[i*(gsize+1) + gsize] = 0; // last column
				new_g[gsize*(gsize+1) + i] = 0; // last row
			}

			*/
			/*
			 * throw away the old graph and make new one the
			 * graph
			 */
			free(g);
			g = new_g;
			gsize = gsize+1;

			/*
			 * reset the taboo list for the new graph
			 */
			taboo_list = FIFOResetEdge(taboo_list);

			/*
			 * keep going
			 */
			continue;
		}

		/*
		 * otherwise, we need to consider flipping an edge
		 *
		 * let's speculative flip each edge, record the new count,
		 * and unflip the edge.  We'll then remember the best flip and
		 * keep it next time around
		 *
		 * only need to work with upper triangle of matrix =>
		 * notice the indices
		 */

		int x,y;
		best_count = BIGCOUNT;
		for(x=0; x < gsize*gsize; x++)
		{
			for(y=x; y < gsize*gsize; y++)
			{
				if(y%gsize < x%gsize)
					continue;
				// swap
				if(g[x]==g[y] && x!=y)
					continue;
					
				swap(g,x,y);

				count = CliqueCount(g,gsize);

				// * is it better and the i,j,count not taboo?
				if((count < best_count) && 
					!FIFOFindEdge(taboo_list,x,y))
//					!FIFOFindEdgeCount(taboo_list,i,j,count))
				{
					best_count = count;
					best_x = x;
					best_y = y;
				}

				// * flip it back
				swap(g,x,y);
			}
		}

		/*
		best_count = BIGCOUNT;
		for(i=0; i < gsize; i++)
		{
			for(j=i+1; j < gsize; j++)
			{
				// flip it
				g[i*gsize+j] = 1 - g[i*gsize+j];
				count = CliqueCount(g,gsize);

				// * is it better and the i,j,count not taboo?
				if((count < best_count) && 
					!FIFOFindEdge(taboo_list,i,j))
//					!FIFOFindEdgeCount(taboo_list,i,j,count))
				{
					best_count = count;
					best_i = i;
					best_j = j;
				}

				// * flip it back
				g[i*gsize+j] = 1 - g[i*gsize+j];
			}
		}
		*/
		if(best_count == BIGCOUNT) {
			printf("no best edge found, terminating\n");
			exit(1);
		}
	
		/*
		 * keep the best flip we saw
		 */
		//g[best_i*gsize+best_j] = 1 - g[best_i*gsize+best_j];

		swap(g,best_x,best_y);

		/*
		 * taboo this graph configuration so that we don't visit
		 * it again
		 */
		count = CliqueCount(g,gsize);
//		FIFOInsertEdge(taboo_list,best_i,best_j);
		FIFOInsertEdgeCount(taboo_list,best_i,best_j,count);
//		FIFOInsertEdge(taboo_list,best_x,best_y);

		/*		
		printf("ce size: %d, best_count: %d, swap: (%d,%d)\n",
			gsize,
			best_count,
			best_x,
			best_y
			);
		*/
		/*
		printf("ce size: %d, best_count: %d, best edge: (%d,%d), new color: %d\n",
			gsize,
			best_count,
			best_i,
			best_j,
			g[best_i*gsize+best_j]);
		*/
		/*
		 * rinse and repeat
		 */
	}

	FIFODeleteGraph(taboo_list);


	return(0);

}
Exemplo n.º 9
0
/*
 *      Measure the trace selection result.
 *      Trace selection must have been applied.
 */
void
ReportSelectionResult (FGraph graph, double *matrix)
{
  int i;
  Node node;
  Arc arc;
  if (graph == 0)
    Punt ("ReportSelectionResult: nil graph");
  if (matrix == 0)
    return;
  for (i = 0; i <= N_LEAF; i++)
    matrix[i] = 0.0;
  /*
   *  Compute the sequential locality.
   */
  for (node = graph->nodes; node != 0; node = nextNode (node))
    {
      Arc ptr;
      Node next_node;
      next_node = nextNode (node);
      if (next_node == 0)       /* ignore the last node */
        break;
      for (ptr = destinationArcs (node); ptr != 0; ptr = nextArc (ptr))
        {
          if (destinationNode (ptr) == next_node)
            {
              matrix[W_SEQUENTIAL] += arcWeight (ptr);
            }
        }
    }
  /*
   *  Measure various transition counts.
   */
  for (node = graph->nodes; node != 0; node = nextNode (node))
    {
      for (arc = destinationArcs (node); arc != 0; arc = nextArc (arc))
        {
          Node src, dest;
          int Sh, St, Dh, Dt;
          src = sourceNode (arc);
          dest = destinationNode (arc);
          Sh = nodeStatus (src) & TRACE_HEAD;
          St = nodeStatus (src) & TRACE_TAIL;
          Dh = nodeStatus (dest) & TRACE_HEAD;
          Dt = nodeStatus (dest) & TRACE_TAIL;
          if ((arcType (arc) != 0) && (arcType (arc) == nodeType (node)))
            {
              /*
               *      In-trace.
               */
              matrix[W_E] += arcWeight (arc);
            }
          else if (arcType (arc) != 0)
            {
              Punt ("ReportSelectionResult: illegal arc type");
            }
          else
            {
              if (St && Dh)
                {               /* terminal to head */
                  matrix[W_A] += arcWeight (arc);
                  /* detect loop back-edge */
                  if (nodeType (src) == nodeType (dest))
                    {
                      matrix[W_BACK_EDGE] += arcWeight (arc);
                    }
                }
              else if (St && !Dh)
                {               /* terminal to middle */
                  matrix[W_B] += arcWeight (arc);
                }
              else if (!St && Dh)
                {               /* middle to head */
                  matrix[W_C] += arcWeight (arc);
                }
              else
                {               /* middle to middle */
                  matrix[W_D] += arcWeight (arc);
                }
            }
        }
    }
#ifdef DEBUG_TRACE2
  if (matrix[W_E] > matrix[W_SEQUENTIAL])
    {
      WriteGraph ("zzz.debug", graph);
      fprintf (stderr, "in-trace = %f\n", matrix[W_E]);
      fprintf (stderr, "sequential = %f\n", matrix[W_SEQUENTIAL]);
      Punt ("ReportSelection: incorrect in-trace");
    }
#endif
  /*
   *  Measure several graph parameters.
   */
  for (node = graph->nodes; node != 0; node = nextNode (node))
    {
      nodeStatus (node) &= ~VISITED;    /* borrow the valid bit */
      matrix[N_NODES] += 1.0;
      matrix[W_NODES] += nodeWeight (node);
      if (destinationArcs (node) == 0)
        {
          matrix[N_LEAF] += 1.0;
        }
      if (sourceArcs (node) == 0)
        {
          matrix[N_ROOT] += 1.0;
        }
      for (arc = destinationArcs (node); arc != 0; arc = nextArc (arc))
        {
          matrix[N_ARCS] += 1.0;
          matrix[W_ARCS] += arcWeight (arc);
        }
    }
  for (node = graph->nodes; node != 0; node = nextNode (node))
    {
      Node ptr;
      int trace_id, loop, size;
      if (nodeStatus (node) & VISITED)
        continue;
      trace_id = nodeType (node);
      loop = 0;
      size = 0;
      for (ptr = graph->nodes; ptr != 0; ptr = nextNode (ptr))
        {
          if (nodeType (ptr) == trace_id)
            {
              nodeStatus (ptr) |= VISITED;
              size++;
              loop |= (nodeStatus (node) & LOOP_HEAD);
            }
        }
      matrix[N_TRACE] += 1.0;
      matrix[L_TRACE] += size;
      if (loop)
        {
          matrix[N_LOOP] += 1.0;
          matrix[L_LOOP] += size;
        }
    }
  if (matrix[L_TRACE] != matrix[N_NODES])
    Punt ("ReportSelectionResult: incorrect accounting");
  if (matrix[N_TRACE] != 0.0)
    matrix[L_TRACE] /= matrix[N_TRACE];
  if (matrix[N_LOOP] != 0.0)
    matrix[L_LOOP] /= matrix[N_LOOP];
}
Exemplo n.º 10
0
/*
 *      Places traces in a particular linear order
 *      to maximize sequential transition.
 *      A good way to achieve this is to construct a
 *      higher level graph, using traces as nodes.
 *      An arc is added between traces whose head
 *      and tail are connected by a transition.
 */
static void
PlaceTraces (FGraph graph)
{
  FGraph new_graph;
  Node node, current;
  Node node_order[MAX_GRAPH_SIZE];
  int i, size;
#ifndef SECOND_LEVEL_SELECT
  int min_trace_id, max_trace_id;
#endif
  if (graph->nodes == 0)
    return;
#ifdef SECOND_LEVEL_SELECT
  new_graph = NewGraph ();      /* create a high level graph */
  for (node = graph->nodes; node != 0; node = nextNode (node))
    {
      int trace_id;
      Node temp;
      trace_id = nodeType (node);
      temp = FindNode (new_graph, trace_id);
      if (temp == 0)
        {
          temp = NewNode ();
          nodeId (temp) = trace_id;
          AddNode (new_graph, temp);
        }
      if (node == graph->root)
        new_graph->root = temp;
    }
  for (node = graph->nodes; node != 0; node = nextNode (node))
    {
      Arc arc;
      if (!(nodeStatus (node) & TRACE_TAIL))
        continue;
      /*
       *      Find transitions to the head of other traces.
       *      Inner loop back-edge is not considered.
       */
      for (arc = destinationArcs (node); arc != 0; arc = nextArc (arc))
        {
          Node dest;
          dest = destinationNode (arc);
          if ((nodeType (dest) != nodeType (node)) &&
              (nodeStatus (dest) & TRACE_HEAD))
            {
              /*
               *      Add a link (trace[node]->trace[dest])
               */
              int src_trace_id, dest_trace_id;
              Node src_node, dest_node;
              Arc ar;
              src_trace_id = nodeType (node);
              dest_trace_id = nodeType (dest);
              src_node = FindNode (new_graph, src_trace_id);
              dest_node = FindNode (new_graph, dest_trace_id);
              ConnectNodes (src_node, dest_node, 0);
              ar = FindSrcArc (src_node, dest_node, 0);
              arcWeight (ar) = arcWeight (arc);
              ar = FindDestArc (src_node, dest_node, 0);
              arcWeight (ar) = arcWeight (arc);
            }
        }
    }
  /*
   *  Simply assign the node weights to max(connecting arc)
   */
  for (node = new_graph->nodes; node != 0; node = nextNode (node))
    {
      Arc arc;
      double max = 1.0;
      for (arc = sourceArcs (node); arc != 0; arc = nextArc (arc))
        if (arcWeight (arc) > max)
          max = arcWeight (arc);
      for (arc = destinationArcs (node); arc != 0; arc = nextArc (arc))
        if (arcWeight (arc) > max)
          max = arcWeight (arc);
      nodeWeight (node) = max;
    }
  /*
   *  Apply SelectTraces() on the new graph.
   *  Use SELECT_BY_ARC_WEIGHT
   */
  best_successor_of = best_successor_2;
  best_predecessor_of = best_predecessor_2;
  SelectTraces (new_graph);
  /*
   *  Determine the best sequential order of the traces.
   *  Essentially, we have the original problem again.
   *  However, after the second level trace selection,
   *  we expect most of the sequential transitions are
   *  captured. A naive heuristic is sufficient here.
   *  The sequential order must start with the ENTRY trace.
   */
#ifdef DEBUG_TRACE1
  printf ("... second level graph = \n");
  WriteGraph ("stdout", new_graph);
#endif
  /*
   *  Clear the valid bit of all nodes.
   */
  for (node = new_graph->nodes; node != 0; node = nextNode (node))
    {
      nodeStatus (node) &= ~VISITED;
    }
  /*
   *  Start from the root node.
   */
  size = 0;
  current = new_graph->root;
  while (current != 0)
    {
      Node ptr;
      Arc ar;
      int trace_id;
      if (nodeStatus (current) & VISITED)
        Punt ("PlaceTraces: reached a VISITed node");
      nodeStatus (current) |= VISITED;
      trace_id = nodeId (current);
      /*
       *      Layout the trace.
       */
      for (ptr = graph->nodes; ptr != 0; ptr = nextNode (ptr))
        {
          if ((nodeType (ptr) == trace_id) && (nodeStatus (ptr) & TRACE_HEAD))
            break;              /* find the starting node of the trace */
        }
      if (ptr == 0)
        Punt ("PlaceTraces: internal error (1)");
      while (ptr != 0)
        {
          Arc next;
          node_order[size++] = ptr;
          /*
           *  Follow the in-trace transition.
           */
          if (nodeStatus (ptr) & TRACE_TAIL)
            break;              /* reached the end of trace */
          for (next = destinationArcs (ptr); next != 0; next = nextArc (next))
            {
              if (arcType (next) == nodeType (ptr))
                break;          /* find a in-trace transition */
            }
          if (next == 0)
            break;
          ptr = destinationNode (next);
        }
      /*
       *      Select the next trace to be visited next.
       *      Follow an in-trace transition (of the higher level
       *      graph) if possible. 
       */
      for (ar = destinationArcs (current); ar != 0; ar = nextArc (ar))
        {
          if (arcType (ar) == nodeType (current))
            break;              /* find an in-trace transition */
        }
      if (ar != 0)
        {                       /* transition is still in-trace */
          current = destinationNode (ar);
        }
      else
        {                       /* must find another trace */
          /*
           *  Find the most important trace left.
           */
          Node nn, best;
          best = 0;
          for (nn = new_graph->nodes; nn != 0; nn = nextNode (nn))
            {
              if (nodeStatus (nn) & VISITED)
                continue;       /* skip over VISITED nodes */
              if (!(nodeStatus (nn) & TRACE_HEAD))
                continue;       /* skip over non-trace headers */
              if (best == 0)
                {
                  best = nn;
                }
              else
                {
                  if (nodeWeight (nn) > nodeWeight (best))
                    best = nn;
                }
            }
          current = best;       /* go out of trace if best=0 */
        }
    }
  /*
   *  Make sure that all traces have been layout.
   */
  for (node = new_graph->nodes; node != 0; node = nextNode (node))
    {
      if (!(nodeStatus (node) & VISITED))
        {
          Punt ("PlaceTraces: missing some traces");
        }
    }
  /*
   *  No longer need the higher level graph.
   */
  FreeGraph (&new_graph);       /* destroy the high level graph */
#else
  min_trace_id = 0x1FFFFFFF;
  max_trace_id = -0x1FFFFFFF;
  for (node = graph->nodes; node != 0; node = nextNode (node))
    {
      int trace_id;
      trace_id = nodeType (node);
      if (trace_id > max_trace_id)
        max_trace_id = trace_id;
      if (trace_id < min_trace_id)
        min_trace_id = trace_id;
    }
  for (node = graph->nodes; node != 0; node = nextNode (node))
    {
      nodeStatus (node) &= ~VISITED;
    }
  size = 0;
  for (i = min_trace_id; i <= max_trace_id; i++)
    {
      Node ptr;
      /*
       * 1. find the trace header.
       */
      for (ptr = graph->nodes; ptr != 0; ptr = nextNode (ptr))
        {
          if ((nodeType (ptr) == i) & ((nodeStatus (ptr) & TRACE_HEAD) != 0))
            break;
        }
      if (ptr == 0)
        continue;
      while (ptr != 0)
        {
          Arc next;
          if (nodeStatus (ptr) & VISITED)
            Punt ("PlaceTraces: visited a node twice");
          nodeStatus (ptr) |= VISITED;
          node_order[size++] = ptr;
          if (nodeStatus (ptr) & TRACE_TAIL)
            break;
          for (next = destinationArcs (ptr); next != 0; next = nextArc (next))
            {
              if (arcType (next) == nodeType (ptr))
                break;
            }
          if (next == 0)
            break;
          ptr = destinationNode (next);
        }
    }
  /*
   *  Make sure that all traces have been layout.
   */
  for (node = graph->nodes; node != 0; node = nextNode (node))
    {
      if (!(nodeStatus (node) & VISITED))
        {
          fprintf (stderr, "min trace id = %d\n", min_trace_id);
          fprintf (stderr, "max trace id = %d\n", max_trace_id);
          fprintf (stderr, "size = %d\n", size);
          WriteGraph ("stderr", graph);
          Punt ("PlaceTraces: missing some traces");
        }
    }
#endif
  /*
   *  Rearrange the order of nodes, according to the
   *  node_order[] order.
   */
  node_order[size] = 0;
  for (i = 0; i < size; i++)
    {
      nextNode (node_order[i]) = node_order[i + 1];
    }
  graph->nodes = node_order[0];
}
void mlmcl(int* nvtxs, idxtype* xadj, idxtype* adjncy, idxtype
*vwgt, idxtype* adjwgt, int* wgtflag, idxtype* indices, Options opt)
{
 /*	GraphType graph;
	my_SetUpGraph(&graph, *nvtxs, xadj, adjncy, vwgt, adjwgt,
	*wgtflag, 1); */
	int hubRemoval=opt.hubRemoval, recursiveCluster=0;
	float hub_pct = opt.hubPct;

	GraphType *graph = (GraphType*)malloc(sizeof(GraphType));
	my_SetUpGraph(graph, *nvtxs, xadj, adjncy, vwgt, adjwgt,
	*wgtflag, 1);
	// The last argument indicates we are setting up the original
	// graph 

	idxtype* newIds;
	if ( hubRemoval > 0 )
	{
		int hubThreshold = (int) floor(hub_pct * graph->nvtxs);
		GraphType *new_graph;
		newIds = removeHubs(graph, hubThreshold, *wgtflag,
						&new_graph, 0);
		free(graph->gdata);
		free(graph);
		graph = new_graph;
		
		// now need to remove any nodes that became singletons
		// because of hub removal.

		// we'll do another iteration of newIds, so back up 
		// the old newIds. newIds_bkp is of size *nvtxs.
		idxtype *newIds_bkp = newIds;

		int noOfSingletons = 0, newIdCounter;
		newIds = lookForSingletons(graph, &noOfSingletons);
		newIdCounter = graph->nvtxs - noOfSingletons;

		if ( noOfSingletons > 0 )
		{
			printf("%d nodes became singletons due to hub removal", 
						noOfSingletons );
			printf("; they will be removed.\n");
			fflush(stdout);

			getSubgraph(graph, newIds, newIdCounter, *wgtflag, 
							&new_graph);
			free(graph->gdata);
			free(graph);
			graph = new_graph;
			
			int i;
			for ( i=0; i<*nvtxs; i++ )
			{
				if ( newIds_bkp[i] > -1 )
				{
					newIds_bkp[i] = newIds[newIds_bkp[i]];
				}
				else
					newIds_bkp[i] = -1;
			}
			free(newIds);
		}

		newIds=newIds_bkp;
	}

//	printf("nnz:%d\n",graph.xadj[*nvtxs]);
	if ( opt.mis_coarsenType > 0 )
	{
//		mis_mlrmcl(graph, indices, opt); 
	}
	else
	{
		mlmclWithGraph(graph, indices, opt);
	}

	if ( hubRemoval > 0 )
	{
		int npart=mapPartition(indices, graph->nvtxs);
		float ncut=ComputeNCut(graph, indices, npart);
		printf("In graph that does not include hubs,"); 
		printf("No. of Clusters:%d, N-Cut value: %.2f\n", npart, ncut);

		mapIndices(indices, newIds, *nvtxs, npart);
		free(newIds);
		if ( *nvtxs - graph->nvtxs > 0 )
		{
			char filename[256];
			sprintf(filename, "input.nohubs.%.3f", hub_pct);
			WriteGraph(filename, graph->nvtxs, graph->xadj,
			graph->adjncy);
			printf("Wrote nohubs graph to %s\n", filename);
		}
	}

	if ( recursiveCluster > 0 )
	{
		int npart = mapPartition(indices, graph->nvtxs);
		float ncut = ComputeNCut(graph, indices, npart);
		printf("No. of clusters:%d, N-Cut:%.2f\n", npart, ncut);
		idxtype* hist = histogram(indices, graph->nvtxs, npart);

		int max=0, i=0, maxCluster=-1;
		for( i=0; i<npart; i++ )
		{
			if ( hist[i] > max )
			{
				max = hist[i];
				maxCluster = i;
			}
		}

		free(hist);

		if ( max > graph->nvtxs * 0.3 )
		{
			printf("Will recursively partition cluster of size");
			printf(" %d\n", max);
			
			idxtype* newIds = idxmalloc(graph->nvtxs,"mlmcl:newIds");
			int newIdCounter=0;
			for ( i=0; i<graph->nvtxs; i++ )
			{
				if ( indices[i] == maxCluster )
					newIds[i]=newIdCounter++;
				else
					newIds[i]=-1;
			}
			
			GraphType *new_graph;
			getSubgraph(graph, newIds, max, *wgtflag, &new_graph);

			idxtype *new_indices = idxmalloc(max,"mlmcl:new_indices");
			opt.coarsenTo = (int) round(((float) max 
							/ (float)graph->nvtxs) * opt.coarsenTo);
			mlmcl(&max,new_graph->xadj, new_graph->adjncy,
			new_graph->vwgt, new_graph->adjwgt, wgtflag,
			new_indices, opt );

			int new_npart = mapPartition( new_indices, max);
			for ( i=0; i<graph->nvtxs; i++ )
			{
				if ( newIds[i] > -1 )
				{
					int ni = new_indices[newIds[i]];
					if ( ni > 0 )
						indices[newIds[i]] = npart + ni - 1;
					else
						indices[newIds[i]] = maxCluster;
				}
			}
			
			printf("Recursive clustering yielded %d new",new_npart);
			printf(" clusters.");

			free(new_indices);
			free(newIds);
			free(new_graph->gdata);
			free(new_graph);

		}

	}
}
Exemplo n.º 12
0
bool Permutator::WriteModifiedFile()
{
	try
	{
		if (elfMode)
			outputFile.open("permutatedFile", std::ios::out | std::ios::binary);
		else
			outputFile.open("permutatedFile.exe", std::ios::out | std::ios::binary);
	}
	catch (std::fstream::failure e)
	{
		std::cerr << "WriteModifiedFile: Error while opening stream "
					<< "to modified file: " << e.what() << std::endl;
		return false;
	}
	
	try
	{
		if (elfMode) {
			// Write ELF header
			outputFile.write((char *)pElfHeader, sizeof(Elf32_Ehdr));

			// Write program headers
			for (int i=0; i<pElfHeader->e_phnum; i++) {

				Elf32_Phdr *pElfProgramHeader = (Elf32_Phdr *)
				ReadHeader(hInputFile, sizeof(Elf32_Phdr),
							i*sizeof(Elf32_Phdr)+pElfHeader->e_phoff);
				if (!pElfProgramHeader) {
					std::cerr << "WriteModifiedFile: Invalid program header read"
								<< std::endl;
					return false;
				}
				outputFile.write((char *)pElfProgramHeader, sizeof(Elf32_Phdr));
			}

			// Note: this assumes the offsets stay the same. 
			//  the assumption will not hold when permutation is implemented
		}
		else {
			// Write DOS header
			outputFile.write((char*)pDosHeader, sizeof(IMAGE_DOS_HEADER));

			// Write NT header
			outputFile.seekp(pDosHeader->e_lfanew, std::ios::beg);
			outputFile.write((char*)pNtHeader, sizeof(IMAGE_NT_HEADERS));
		}
	}
	catch (std::fstream::failure e)
	{
		std::cerr << "WriteModifiedFile: Error while writing "
					<< (elfMode ? "ELF/program" : "DOS/NT headers")
					<< " to modified file: " << e.what() << std::endl;
		return false;
	}
	

	// Write section headers and section data
	BYTE* sectionData = nullptr;
	PIMAGE_SECTION_HEADER pSectionHeader = nullptr;
	Elf32_Shdr *pElfSectionHeader = nullptr;

	if (elfMode) {
		for (int i=0; i < pElfHeader->e_shnum; i++) {
			pElfSectionHeader = (Elf32_Shdr *)
				ReadHeader(hInputFile, sizeof(Elf32_Shdr), 
							i*sizeof(Elf32_Shdr)+pElfHeader->e_shoff);
			if (!pElfSectionHeader)
			{
				std::cerr << "WriteModifiedFile: Invalid section header read"
					<< std::endl;
				return false;
			}

			if (!ElfWriteSectionHeader(pElfSectionHeader, i, 
										outputFile, pElfHeader->e_shoff))
			{
				std::cerr << "WriteModifiedFile: Error writing " << i+1 
							<< ". section header" << std::endl;
				continue;
			}

			// .text section
			if ((pElfHeader->e_entry >= pElfSectionHeader->sh_addr) &&
				(pElfHeader->e_entry < pElfSectionHeader->sh_addr
				 						+ pElfSectionHeader->sh_size))
			{
				sectionData = (BYTE*)malloc(pElfSectionHeader->sh_size);
				WriteGraph(graph.GetRoot(), sectionData);
				WriteData(sectionData);
				if (!ElfWriteSection(outputFile, pElfSectionHeader, sectionData))
				{
					std::cerr << "WriteModifiedFile: Error while writing data of "
							<< i+1 << ". (executable) section" << std::endl;
					continue;
				}
			}

			// other sections
			else
			{
				sectionData = ElfLoadSection(hInputFile, pElfSectionHeader);
				if (!sectionData)
				{
					std::cerr << "WriteModifiedFile: Unable to load " << i+1
								<< ". section" << std::endl;
					continue;
				}
				if (!ElfWriteSection(outputFile, pElfSectionHeader, sectionData))
				{
					std::cerr << "WriteModifiedFile: Error while writing data of "
								<< i+1 << ". section: " << std::endl;
					continue;
				}
			}
			

			free(pElfSectionHeader);
			free(sectionData);
			pElfSectionHeader = nullptr;
			sectionData = nullptr;
		}
	}
	else {
		for (WORD i = 0; i < pNtHeader->FileHeader.NumberOfSections; ++i)
		{
			pSectionHeader = (PIMAGE_SECTION_HEADER)
				ReadHeader(hInputFile, IMAGE_SIZEOF_SECTION_HEADER, 
							dwFstSctHdrOffset + i*IMAGE_SIZEOF_SECTION_HEADER);
			if (pSectionHeader == nullptr)
			{
				std::cerr << "WriteModifiedFile: Invalid section header read"
					<< std::endl;
				return false;
			}
			
			if (!WriteSectionHeader(pSectionHeader, i, outputFile, dwFstSctHdrOffset))
			{
				std::cerr << "WriteModifiedFile: Error writing "
							<< "the section header: " << pSectionHeader->Name
							<< std::endl;
				continue;
			}

			if ((pNtHeader->OptionalHeader.AddressOfEntryPoint 
					>= pSectionHeader->VirtualAddress)
				&&
				(pNtHeader->OptionalHeader.AddressOfEntryPoint 
				 	< (pSectionHeader->VirtualAddress 
							+ pSectionHeader->Misc.VirtualSize)))
			{
				sectionData = (BYTE*)malloc(pSectionHeader->SizeOfRawData);
				WriteGraph(graph.GetRoot(), sectionData);
				WriteData(sectionData);
				if (!WriteSection(outputFile, pSectionHeader, sectionData))
				{
					std::cerr << "WriteModifiedFile: Error while writing data of "
							<< "executable section: " << pSectionHeader->Name
							<< std::endl;
					continue;
				}
			}
			else
			{
				sectionData = LoadSection(hInputFile, pSectionHeader);
				if (sectionData == nullptr)
				{
					std::cerr << "WriteModifiedFile: Unable to load section: "
								<< pSectionHeader->Name << std::endl;
					continue;
				}
				if (!WriteSection(outputFile, pSectionHeader, sectionData))
				{
					std::cerr << "WriteModifiedFile: Error while writing data of "
								<< "section: " << pSectionHeader->Name 
								<< std::endl;
					continue;
				}
			}
			

			free(pSectionHeader);
			free(sectionData);
			sectionData = nullptr;
			pSectionHeader = nullptr;
		}

	// Write overlays if any
	// Overlay == data appended to PE file
		PIMAGE_SECTION_HEADER pLastSectionHeader = (PIMAGE_SECTION_HEADER)
			ReadHeader(hInputFile, 
						IMAGE_SIZEOF_SECTION_HEADER, 
						dwFstSctHdrOffset 
							+ IMAGE_SIZEOF_SECTION_HEADER 
							* (pNtHeader->FileHeader.NumberOfSections - 1));
		DWORD overlaySize;
		BYTE* overlay 
				= ExtractOverlays(hInputFile, pLastSectionHeader, &overlaySize);
		if (overlay != nullptr && overlaySize != 0)
		{
			if (!WriteDataToFile(outputFile, 
								pLastSectionHeader->PointerToRawData 
									+ pLastSectionHeader->SizeOfRawData,
								overlaySize, 
								overlay))
			{
				std::cerr << "WriteModifiedFile: Error while writing overlay "
							<< "data to modified file" << std::endl;
				return false;
			}
		}
	}

	try
	{
		outputFile.flush();
		outputFile.close();
	}
	catch (std::fstream::failure e)
	{
		std::cerr << "WriteModifiedFile: Error while closing modified file "
				<< "stream: " << e.what() << std::endl;
		return false;
	}

	return true;
}