示例#1
0
文件: my_main.c 项目: stuydw/mdl
void my_main( int polygons ) {

    int i, ax;
    double step;
    double xval, yval, zval, x2, y2, z2;
    double w, h, d, r1, r2, m;
    struct matrix *transform;
    struct matrix *tmp;
    struct stack *s;
    screen t;
    color g;

    g.red = 250;
    g.blue = 0;
    g.green = 0;

    s = new_stack();
    tmp = new_matrix(4, 1000);
    clear_screen( t );

    for (i=0; i<lastop; i++) {
        switch (op[i].opcode) {

        case COMMENT:
            break;

        case PUSH:
            push(s);
            break;

        case POP:
            pop(s);
            break;

        case MOVE:
            xval = op[i].op.move.d[0];
            yval = op[i].op.move.d[1];
            zval = op[i].op.move.d[2];

            transform = make_translate(xval, yval, zval);
            matrix_mult(transform, s->data[s->top]);
            break;

        case SCALE:
            xval = op[i].op.scale.d[0];
            yval = op[i].op.scale.d[1];
            zval = op[i].op.scale.d[2];

            transform = make_scale(xval, yval, zval);
            matrix_mult(transform, s->data[s->top]);
            break;

        case ROTATE:
            ax = op[i].op.rotate.axis;
            m = op[i].op.rotate.degrees;

            if(ax == 0)
                transform = make_rotX(m);

            if(ax == 1)
                transform = make_rotY(m);

            if(ax ==2)
                transform = make_rotZ(m);

            matrix_mult(transform, s->data[s->top]);
            break;

        case BOX:
            xval = op[i].op.box.d0[0];
            yval = op[i].op.box.d0[1];
            zval = op[i].op.box.d0[2];
            w = op[i].op.box.d1[0];
            h = op[i].op.box.d1[1];
            d = op[i].op.box.d1[2];


            add_box(tmp, xval, yval, zval, w, h, d);
            matrix_mult(s->data[s->top], tmp);
            draw_polygons(tmp, t, g);
            break;

        case SPHERE:
            xval = op[i].op.sphere.d[0];
            yval = op[i].op.sphere.d[1];
            zval = op[i].op.sphere.d[2];
            r1 = op[i].op.sphere.r;

            add_sphere(tmp, xval, yval, zval, r1, .01);
            matrix_mult(s->data[s->top], tmp);
            draw_polygons(tmp, t, g);
            break;

        case TORUS:
            xval = op[i].op.torus.d[0];
            yval = op[i].op.torus.d[1];
            zval = op[i].op.torus.d[2];
            r1 = op[i].op.torus.r0;
            r2 = op[i].op.torus.r1;

            add_torus(tmp, xval, yval, zval, r1, r2, .01);
            matrix_mult(s->data[s->top], tmp);
            draw_polygons(tmp, t, g);
            break;

        case LINE:
            xval = op[i].op.line.p0[0];
            yval = op[i].op.line.p0[1];
            zval = op[i].op.line.p0[2];
            x2 = op[i].op.line.p1[0];
            y2 = op[i].op.line.p1[1];
            z2 = op[i].op.line.p1[2];

            add_edge(tmp, xval, yval, zval, x2, y2, z2);
            matrix_mult(s->data[s->top], tmp);
            draw_lines(tmp, t, g);
            break;

        case SAVE:
            save_extension(t, op[i].op.save.p->name);
            break;

        case DISPLAY:
            display(t);
            break;

        }
    }
}
示例#2
0
文件: parser.c 项目: stuydw/3d
/*======== void parse_file () ==========
Inputs:   char * filename 
          struct matrix * transform, 
          struct matrix * pm,
          screen s
Returns: 

Goes through the file named filename and performs all of the actions listed in that file.
The file follows the following format:
     Every command is a single character that takes up a line
     Any command that requires arguments must have those arguments in the second line.
     The commands are as follows:
         l: add a line to the edge matrix - 
	    takes 6 arguemnts (x0, y0, z0, x1, y1, z1)
         b: add a hermite cutve to the edge matrix - 
	    takes 8 arguemnts (x0, y0, x1, y1, x2, y2, x3, y3)
         h: add a bezier to the edge matrix - 
	    takes 8 arguemnts (x0, y0, x1, y1, x2, y2, x3, y3)
         c: add a circle to the edge matrix - 
	    takes 3 arguemnts (cx, cy, r)
         m: add a sphere to the edge matrix - 
	    takes 3 arguemnts (cx, cy, r)
         d: add a torus to the edge matrix - 
	    takes 4 arguemnts (cx, cy, r1, r2)
         p: add a rectangular prism to the edge matrix - 
	    takes 6 arguemnts (x, y, z, width, height, depth)
	 w: clear the currnt edge matrix -
	    takes 0 arguments
	 i: set the transform matrix to the identity matrix - 
	 s: create a scale matrix, 
	    then multiply the transform matrix by the scale matrix - 
	    takes 3 arguments (sx, sy, sz)
	 t: create a translation matrix, 
	    then multiply the transform matrix by the translation matrix - 
	    takes 3 arguments (tx, ty, tz)
	 x: create an x-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 y: create an y-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 z: create an z-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 a: apply the current transformation matrix to the 
	    edge matrix
	 v: draw the lines of the edge matrix to the screen
	    display the screen
	 g: draw the lines of the edge matrix to the screen
	    save the screen to a file -
	    takes 1 argument (file name)
	 q: end parsing

See the file script for an example of the file format


IMPORTANT MATH NOTE:
the trig functions int math.h use radian mesure, but us normal
humans use degrees, so the file will contain degrees for rotations,
be sure to conver those degrees to radians (M_PI is the constant
for PI)

jdyrlandweaver
====================*/
void parse_file ( char * filename, 
                  struct matrix * transform, 
                  struct matrix * pm,
                  screen s) {

  FILE *f;
  char line[256];
  struct matrix * tmp;
  double angle;
  color g;

  g.red = 0;
  g.green = 255;
  g.blue = 255;
  
  clear_screen(s);

  if ( strcmp(filename, "stdin") == 0 ) 
    f = stdin;
  else
    f = fopen(filename, "r");
  
  while ( fgets(line, 255, f) != NULL ) {
    line[strlen(line)-1]='\0';
    //printf(":%s:\n",line);
    char c;
    double x, y, z, x1, y1, z1, x2, y2, x3, y3, x4, y4;
   
    c = line[0];

    switch (c) {
    case 'l':
      //      printf("LINE!\n");
      fgets(line, 255, f);
      //      printf("\t%s", line);
      //line[strlen(line)-1]='\0';
      sscanf(line, "%lf %lf %lf %lf %lf %lf", &x, &y, &z, &x1, &y1, &z1);
      add_edge(pm, x, y, z, x1, y1, z1);
      // printf( "%lf %lf %lf %lf %lf %lf\n", x, y, z, x1, y1, z1);
      break;
     case 'm':
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      add_sphere(pm, x, y, z, .01);
      break;
    case 'd':
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf", &x, &y, &x1, &y1);
      add_torus(pm, x, y, x1, y1, .01);
      break;
    case 'p':
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf", &x, &y, &z, &x1, &y1, &z1);
      add_box(pm, x, y, z, x1, y1, z1);
      break;
    case 'c':
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      add_circle(pm, x, y, z, 0.01);
      //printf( "%lf %lf %lf\n", x, y, z);
      break;
    case 'b':
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf %lf %lf",
	     &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4);
      add_curve(pm, x1, y1, x2, y2, x3, y3, x4, y4, 0.01, BEZIER_MODE );
      //printf( "%lf %lf %lf\n", x, y, z);
      break;
    case 'h':
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf %lf %lf",
	     &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4);
      add_curve(pm, x1, y1, x2, y2, x3, y3, x4, y4, 0.01, HERMITE_MODE );
      //printf( "%lf %lf %lf\n", x, y, z);
      break;
    case 's':
      //printf("SCALE\n");
      fgets(line, 255, f);
      //line[strlen(line)-1]='\0';      
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      tmp = make_scale(x, y, z);
      matrix_mult(tmp, transform);
      //print_matrix(transform);
      break;
    case 't':
      //printf("TRANSLATE\n");
      fgets(line, 255, f);
      //      line[strlen(line)-1]='\0';      
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      tmp = make_translate(x, y, z);
      matrix_mult(tmp, transform);
      //print_matrix(transform);
      break;
    case 'x':
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotX( angle);
      matrix_mult(tmp, transform);
      break;
    case 'y':
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotY( angle);
      matrix_mult(tmp, transform);
      break;
    case 'z':
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotZ( angle);
      matrix_mult(tmp, transform);
      break;
    case 'i':
      ident(transform);
      break;
    case 'a':
      //printf("APPLY!\n");
      //print_matrix( transform );
      //      print_matrix(pm);
      matrix_mult(transform, pm);
      break;
    case 'v':
      clear_screen(s);
      draw_lines(pm, s, g);
      display(s);
      break;
    case 'w':
      pm->lastcol = 0;
      break;
    case 'g':
      fgets(line, 255, f);
      // line[strlen(line)-1] = '\0';
      clear_screen(s);
      draw_lines(pm, s, g);
      save_extension(s, line);
      break;
    case 'q':
      return;
    case '#':
      break;
    default:
      printf("Invalid command\n");
      break;
    }
  }

  free_matrix(tmp);
  fclose(f);
  //printf("END PARSE\n");
}
示例#3
0
/*======== void parse_file () ==========
Inputs:   char * filename 
          struct matrix * transform, 
          struct matrix * pm,
          screen s
Returns: 

Goes through the file named filename and performs all of the actions listed in that file.
The file follows the following format:
     Every command is a single character that takes up a line
     Any command that requires arguments must have those arguments in the second line.
     The commands are as follows:
         line: add a line to the edge matrix - 
	    takes 6 arguemnts (x0, y0, z0, x1, y1, z1)
	 circle: add a circle to the edge matrix - 
	    takes 3 arguments (cx, cy, r)
	 hermite: add a hermite curve to the edge matrix -
	    takes 8 arguments (x0, y0, x1, y1, x2, y2, x3, y3)
	 bezier: add a bezier curve to the edge matrix -
	    takes 8 arguments (x0, y0, x1, y1, x2, y2, x3, y3)
	 ident: set the transform matrix to the identity matrix - 
	 scale: create a scale matrix, 
	    then multiply the transform matrix by the scale matrix - 
	    takes 3 arguments (sx, sy, sz)
	 translate: create a translation matrix, 
	    then multiply the transform matrix by the translation matrix - 
	    takes 3 arguments (tx, ty, tz)
	 xrotate: create an x-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 yrotate: create an y-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 zrotate: create an z-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 apply: apply the current transformation matrix to the 
	    edge matrix
	 display: draw the lines of the edge matrix to the screen
	    display the screen
	 save: draw the lines of the edge matrix to the screen
	    save the screen to a file -
	    takes 1 argument (file name)
	 quit: end parsing

See the file script for an example of the file format


IMPORTANT MATH NOTE:
the trig functions int math.h use radian mesure, but us normal
humans use degrees, so the file will contain degrees for rotations,
be sure to conver those degrees to radians (M_PI is the constant
for PI)
====================*/
void parse_file ( char * filename, 
                  struct matrix * transform, 
                  struct matrix * pm,
                  screen s) {

  color c;
  c.red=MAX_COLOR;
  c.blue=0;
  c.green=0;

  double step=10000;

  FILE *f;
  char line[256];

  double x0,y0,z0,x1,y1,z1;
  double cx,cy,radius;
  double x2,y2,x3,y3;
  double sx,sy,sz;
  double tx,ty,tz;
  double theta;

  if ( strcmp(filename, "stdin") == 0 ) 
    f = stdin;
  else
    f = fopen(filename, "r");
  
  while ( fgets(line, 255, f) != NULL ) {
    line[strlen(line)-1]='\0';
    printf(":%s:\n",line);  
    if (strcmp(line,"line") == 0){
      fgets(line,255, f);
      line[strlen(line)-1]='\0';
      printf(":%s:\n",line); 
      sscanf(line,"%lf %lf %lf %lf %lf %lf",&x0,&y0,&z0,&x1,&y1,&z1);
      printf("%f %f %f %f %f %f\n",x0,y0,z0,x1,y1,z1);
      add_edge(pm,x0,y0,z0,x1,y1,z1);
    }
    if (strcmp(line,"circle") == 0){
      fgets(line,255, f);
      line[strlen(line)-1]='\0';
      printf(":%s:\n",line); 
      sscanf(line,"%lf %lf %lf",&cx,&cy,&radius);
      add_circle(pm,cx,cy,radius,step);
    }
    if (strcmp(line,"hermite") == 0){
      fgets(line,255, f);
      line[strlen(line)-1]='\0';
      printf(":%s:\n",line); 
      sscanf(line,"%lf %lf %lf %lf %lf %lf %lf %lf",&x0,&y0,&x1,&y1,&x2,&y2,&x3,&y3);
      add_curve(pm,x0,y0,x1,y1,x2,y2,x3,y3,step,2);
    }
    if (strcmp(line,"bezier") == 0){
      fgets(line,255, f);
      line[strlen(line)-1]='\0';
      printf(":%s:\n",line); 
      sscanf(line,"%lf %lf %lf %lf %lf %lf %lf %lf",&x0,&y0,&x1,&y1,&x2,&y2,&x3,&y3);
      add_curve(pm,x0,y0,x1,y1,x2,y2,x3,y3,step,1);
    }
    if (strcmp(line,"ident") == 0)
      ident(transform);
    if (strcmp(line,"scale") == 0){
      fgets(line,255, f);
      line[strlen(line)-1]='\0';
      printf(":%s:\n",line); 
      sscanf(line,"%lf %lf %lf",&sx,&sy,&sz);
      struct matrix *scale = make_scale(sx,sy,sz);
      matrix_mult(scale,transform);
      free_matrix(scale);
    }
    if (strcmp(line,"translate") == 0){
      fgets(line,255, f);
      line[strlen(line)-1]='\0';
      printf(":%s:\n",line); 
      sscanf(line,"%lf %lf %lf",&tx,&ty,&tz);
      struct matrix *translate = make_translate(tx,ty,tz);
      matrix_mult(translate,transform);
      free_matrix(translate);
    }
    if (strcmp(line,"xrotate") == 0){
      fgets(line,255, f);
      line[strlen(line)-1]='\0';
      printf(":%s:\n",line); 
      sscanf(line,"%lf",&theta);
      struct matrix *rotX = make_rotX((theta/180.)*M_PI);
      matrix_mult(rotX,transform);
      free_matrix(rotX);
    }
    if (strcmp(line,"yrotate") == 0){
      fgets(line,255, f);
      line[strlen(line)-1]='\0';
      printf(":%s:\n",line); 
      sscanf(line,"%lf",&theta);
      struct matrix *rotY = make_rotY((theta/180.)*M_PI);
      matrix_mult(rotY,transform);
      free_matrix(rotY);
    }
    if (strcmp(line,"zrotate") == 0){
      fgets(line,255, f);
      line[strlen(line)-1]='\0';
      printf(":%s:\n",line); 
      sscanf(line,"%lf",&theta);
      struct matrix *rotZ = make_rotZ((theta/180.)*M_PI);
      matrix_mult(rotZ,transform);
      free_matrix(rotZ);
    }
    if (strcmp(line,"apply") == 0)
      matrix_mult(transform,pm);
    if (strcmp(line,"display") == 0){
      clear_screen(s);
      draw_lines(pm,s,c);
      display(s);
    }
    if (strcmp(line,"save") == 0){
      clear_screen(s);
      fgets(line,255, f);
      line[strlen(line)-1]='\0';
      printf(":%s:\n",line); 
      draw_lines(pm,s,c);
      save_extension(s,line);
    }
    if (strcmp(line,"quit") == 0)
      exit(42); 
  }
}
示例#4
0
文件: E.cpp 项目: 3013216027/acm-icpc
int main() {
    scanf("%s", string);
    memset(count, 0, sizeof(count));
    for (int i = 0; string[i]; ++ i) {
        count[string[i] - 'a'] ++;
    }
    scanf("%d", &n);
    int source = 26 + n;
    int target = source + 1;
    edge_count = 0;
    memset(first_edge, -1, sizeof(first_edge));
    for (int i = 0; i < 26; ++ i) {
        add_edge(source, i, count[i], 0);
    }
    for (int j = 0; j < n; ++ j) {
        scanf("%s", string);
        memset(count, 0, sizeof(count));
        for (int k = 0; string[k]; ++ k) {
            count[string[k] - 'a'] ++;
        }
        for (int i = 0; i < 26; ++ i) {
            add_edge(i, 26 + j, count[i], 0);
        }
        int limit;
        scanf("%d", &limit);
        add_edge(26 + j, target, limit, j + 1);
    }
    int answer = 0;
    while (true) {
        for (int i = 0; i <= target; ++ i) {
            visit[i] = false;
            distance[i] = INT_MAX;
        }
        visit[source] = true;
        distance[source] = 0;
        std::queue <int> queue;
        queue.push(source);
        while (!queue.empty()) {
            int u = queue.front();
            queue.pop();
            visit[u] = false;
            for (int iter = first_edge[u]; iter != -1; iter = next_edge[iter]) {
                if (capacity[iter] > 0 && distance[u] + cost[iter] < distance[to[iter]]) {
                    from[to[iter]] = iter;
                    distance[to[iter]] = distance[u] + cost[iter];
                    if (!visit[to[iter]]) {
                        visit[to[iter]] = true;
                        queue.push(to[iter]);
                    }
                }
            }
        }
        if (distance[target] == INT_MAX) {
            break;
        }
        int delta = INT_MAX;
        for (int i = target; i != source; i = to[from[i] ^ 1]) {
            delta = std::min(delta, capacity[from[i]]);
        }
        for (int i = target; i != source; i = to[from[i] ^ 1]) {
            capacity[from[i]] -= delta;
            capacity[from[i] ^ 1] += delta;
            answer += cost[from[i]] * delta;
        }
    }
    for (int iter = first_edge[source]; iter != -1; iter = next_edge[iter]) {
        if (capacity[iter] > 0) {
            puts("-1");
            return 0;
        }
    }
    printf("%d\n", answer);
    return 0;
}
示例#5
0
文件: my_main.c 项目: stuydw/mdl
void my_main( int polygons ) {

  int i;
  double step = .05;
  double xval, yval, zval;
  struct matrix *transform;
  struct matrix *tmp;
  struct stack *s;
  screen t;
  color g;

  g = change_color(4);

  s = new_stack();
  tmp = new_matrix(4, 1000);
  clear_screen( t );

  for (i=0;i<lastop;i++) {  
    switch (op[i].opcode) {
      
    case COMMENT:
      break;

    case PUSH:
      push(s);
      break;

    case POP:
      pop(s);
      break;

    case MOVE:
      xval = op[i].op.move.d[0];
      yval = op[i].op.move.d[1];
      zval = op[i].op.move.d[2];

      transform = make_translate(xval, yval, zval);
      matrix_mult(s->data[s->top], transform);
      s->data[s->top] = transform;
      break;
      
    case SCALE:
      xval = op[i].op.scale.d[0];
      yval = op[i].op.scale.d[1];
      zval = op[i].op.scale.d[2];
      
      transform - make_scale(xval, yval, zval);
      matrix_mult(s->data[s->top], transform);
      s->data[s->top] = transform;
      break;
 
    case ROTATE:
      switch ((int)op[i].op.rotate.axis) 
	{

	  double theta = op[i].op.rotate.degrees;

	case 0:
	  transform = make_rotX(theta);
	  break;
	case 1:
	  transform = make_rotY(theta);
	  break;
	case 2:
	  transform = make_rotZ(theta);
	  break;
      }
      
      matrix_mult(s->data[s->top], transform);
      s->data[s->top] = transform;
      break;

    case BOX:
      empty_matrix(tmp);

      xval = op[i].op.box.d0[0];
      yval = op[i].op.box.d0[1];
      zval = op[i].op.box.d0[2];

      double width = op[i].op.box.d1[0];
      double height = op[i].op.box.d1[1];
      double depth = op[i].op.box.d1[2];
      
      add_box(tmp, xval, yval, zval, width, height, depth);
      matrix_mult(s->data[s->top], tmp);
      draw_polygons(tmp, t, g);
      break;

    case SPHERE:
      empty_matrix(tmp);
      
      xval = op[i].op.sphere.d[0];
      yval = op[i].op.sphere.d[1];
      zval = op[i].op.sphere.d[2];
      
      double radius = op[i].op.sphere.r;

      add_sphere(tmp, xval, yval, zval, radius, step);
      matrix_mult(s->data[s->top], tmp);
      draw_polygons(tmp, t, g);
      break;

    case TORUS:
      empty_matrix(tmp);

      xval = op[i].op.torus.d[0];
      yval = op[i].op.torus.d[1];
      zval = op[i].op.torus.d[2];

      double r1 = op[i].op.torus.r0;
      double r2 = op[i].op.torus.r1;

      add_torus(tmp, xval, yval, zval, r1, r2, step);
      matrix_mult(s->data[s->top], tmp);
      draw_polygons(tmp, t, g);
      break;

    case LINE:
      empty_matrix(tmp);

      add_edge(tmp,
	       op[i].op.line.p0[0],
	       op[i].op.line.p0[1],
	       op[i].op.line.p0[2],
	       op[i].op.line.p1[0],
	       op[i].op.line.p1[1],
	       op[i].op.line.p1[2]);
      
      draw_lines(tmp, t, g);
      break;

    case SAVE:
      save_extension(t, op[i].op.save.p->name);
      break;

    case DISPLAY:
      display(t);
      break;
    
    }
  }
}
示例#6
0
template <class T> directed_graph<T> dijkstra(directed_graph<T> &graph, 
                                              size_t start,
                                              T infinity = 0xfffff,
                                              T zero = 0)
{
    typedef std::pair<size_t, T> vertex_t;

    auto distance = directed_graph<T>(graph);
    distance.clear_edges();

    const auto comp = [](const vertex_t &a, const vertex_t &b)
    {
        return a.second > b.second;
    };
    std::priority_queue<vertex_t, std::vector<vertex_t>, 
                        decltype(comp)> queue(comp);
    
    const auto len = graph.vertices().size();
    for (size_t i = 0; i < len; i++)
    {
        if (i == start) {
            distance.vertex(i) = zero;
            queue.emplace(i, zero);
        } else {
            distance.vertex(i) = infinity;
            queue.emplace(i, infinity);
        }
    }

    vertex_t current;
    std::vector<size_t> edges;
    std::set<size_t> complete;
    T tmp_cost;
    size_t tmp_pos;
    while (!queue.empty())
    {
        current = queue.top();
        queue.pop();

        if (complete.find(current.first) != complete.end())
            continue;

        complete.insert(current.first);

        edges = graph.edges(current.first);
        for (size_t i = 0; i < edges.size(); i++)
        {
            tmp_pos = edges.at(i);
           
            tmp_cost = distance.vertex(current.first) + 
                       graph.vertex(tmp_pos); 
           
            if (tmp_cost < distance.vertex(tmp_pos)) {
                distance.clear_edge(tmp_pos);
                distance.add_edge(tmp_pos, current.first);
                distance.vertex(tmp_pos) = tmp_cost;
                queue.emplace(tmp_pos, tmp_cost);
            }
        }
    }

    return distance;
}
bool
johnson_all_pairs_shortest_paths(VertexAndEdgeListGraph& g1,
                                 DistanceMatrix& D,
                                 VertexID id1, Weight w1, const BinaryPredicate& compare,
                                 const BinaryFunction& combine, const Infinity& inf,
                                 DistanceZero zero)
{
    typedef graph_traits<VertexAndEdgeListGraph> Traits1;
    typedef typename property_traits<Weight>::value_type DT;
    function_requires< BasicMatrixConcept<DistanceMatrix,
                       typename Traits1::vertices_size_type, DT> >();

    typedef typename Traits1::directed_category DirCat;
    bool is_undirected = is_same<DirCat, undirected_tag>::value;

    typedef adjacency_list<vecS, vecS, directedS,
            property< vertex_distance_t, DT>,
            property< edge_weight_t, DT,
            property< edge_weight2_t, DT > > > Graph2;
    typedef graph_traits<Graph2> Traits2;

    Graph2 g2(num_vertices(g1) + 1);
    typename property_map<Graph2, edge_weight_t>::type
    w = get(edge_weight, g2);
    typename property_map<Graph2, edge_weight2_t>::type
    w_hat = get(edge_weight2, g2);
    typename property_map<Graph2, vertex_distance_t>::type
    d = get(vertex_distance, g2);
    typedef typename property_map<Graph2, vertex_index_t>::type VertexID2;
    VertexID2 id2 = get(vertex_index, g2);

    // Construct g2 where V[g2] = V[g1] U {s}
    //   and  E[g2] = E[g1] U {(s,v)| v in V[g1]}
    std::vector<typename Traits1::vertex_descriptor>
    verts1(num_vertices(g1) + 1);
    typename Traits2::vertex_descriptor s = *vertices(g2).first;
    {
        typename Traits1::vertex_iterator v, v_end;
        int i = 1;
        for (tie(v, v_end) = vertices(g1); v != v_end; ++v, ++i) {
            typename Traits2::edge_descriptor e;
            bool z;
            tie(e, z) = add_edge(s, get(id1, *v) + 1, g2);
            put(w, e, zero);
            verts1[i] = *v;
        }
        typename Traits1::edge_iterator e, e_end;
        for (tie(e, e_end) = edges(g1); e != e_end; ++e) {
            typename Traits2::edge_descriptor e2;
            bool z;
            tie(e2, z) = add_edge(get(id1, source(*e, g1)) + 1,
                                  get(id1, target(*e, g1)) + 1, g2);
            put(w, e2, get(w1, *e));
            if (is_undirected) {
                tie(e2, z) = add_edge(get(id1, target(*e, g1)) + 1,
                                      get(id1, source(*e, g1)) + 1, g2);
                put(w, e2, get(w1, *e));
            }
        }
    }
    typename Traits2::vertex_iterator v, v_end, u, u_end;
    typename Traits2::edge_iterator e, e_end;
    shared_array_property_map<DT,VertexID2> h(num_vertices(g2), id2);

    for (tie(v, v_end) = vertices(g2); v != v_end; ++v)
        put(d, *v, inf);

    put(d, s, zero);
    // Using the non-named parameter versions of bellman_ford and
    // dijkstra for portability reasons.
    dummy_property_map pred;
    bellman_visitor<> bvis;
    if (bellman_ford_shortest_paths
            (g2, num_vertices(g2), w, pred, d, combine, compare, bvis)) {
        for (tie(v, v_end) = vertices(g2); v != v_end; ++v)
            put(h, *v, get(d, *v));
        // Reweight the edges to remove negatives
        for (tie(e, e_end) = edges(g2); e != e_end; ++e) {
            typename Traits2::vertex_descriptor a = source(*e, g2),
                                                b = target(*e, g2);
            put(w_hat, *e, combine(get(w, *e), (get(h, a) - get(h, b))));
        }
        for (tie(u, u_end) = vertices(g2); u != u_end; ++u) {
            dijkstra_visitor<> dvis;
            dijkstra_shortest_paths
            (g2, *u, pred, d, w_hat, id2, compare, combine, inf, zero,dvis);
            for (tie(v, v_end) = vertices(g2); v != v_end; ++v) {
                if (*u != s && *v != s) {
                    typename Traits1::vertex_descriptor u1, v1;
                    u1 = verts1[get(id2, *u)];
                    v1 = verts1[get(id2, *v)];
                    D[get(id2, *u)-1][get(id2, *v)-1] = combine(get(d, *v), (get(h, *v) - get(h, *u)));
                }
            }
        }
        return true;
    } else
        return false;
}
示例#8
0
int main()
{
    char buffer[128], z[128];
    int num_nodes;
    struct node *nodes;
    int i, edge;
    char name[128];
    struct item **adj, *ptr;
    struct node *u;
    int source;
    struct entry *queue = NULL;
    
    printf("Enter nuber of nodes: ");
    fgets(buffer, 127, stdin);
    sscanf(buffer, "%d", &num_nodes);
    nodes = (struct node *) malloc(num_nodes * sizeof(struct node));
    
    /*Initialize the vertices*/
    for(i=0; i<num_nodes; ++i)
    {
        nodes[i].id = i+1;
        printf("Enter name of node %d: ", i+1);
        fgets(buffer, 127, stdin);
        sscanf(buffer, "%[^\n]s", name);
        nodes[i].name = (char *) (malloc((strlen(name)+1) * sizeof(char)));
        strcpy(nodes[i].name, name);
        nodes[i].d = LONG_MAX;
        nodes[i].c = 'w';
        nodes[i].p = NULL;
    }
    
    adj = (struct item **)malloc(num_nodes * sizeof(struct item *));
    /*Initialize adjacency list to NULL*/
    for(i=0; i<num_nodes; ++i)
        adj[i] = NULL;
        
    /*Add all the edges to adjacency list. No mechanism implemented to prevent multi-edges or self-loop*/
    for(i=0; i<num_nodes; ++i)
    {
        printf("Enter all edges from %s: (-1 to end)\n", nodes[i].name);
        while(1)
        {
            fgets(buffer, 127, stdin);
            sscanf(buffer, "%s", z);
            if(strcmp(z, "exit") == 0)
                break;
            edge = find_vertex(nodes, num_nodes, z);
            if(edge == -1)
            {
                printf("Vertex %s does not exist\n", z);
                break;
            }
            add_edge(&adj[i], edge);
        }
    }
    
    #ifdef DEBUG
    /*Display all the edges*/
    for(i=0; i<num_nodes; ++i)
        display_edges(adj[i], nodes, i);
    #endif
    
    /*Choose a source vertex*/
    printf("Enter the source vertex: ");
    fgets(buffer, 127, stdin);
    sscanf(buffer, "%s", z);
    source = find_vertex(nodes, num_nodes, z);
    if(source == -1)
    {
        printf("Invalid vertex\n");
        exit(-1);
    }
    #ifdef DEBUG
    printf("***DEBUG MODE ON***\n");
    #endif
    /*Perform a BFS*/
    nodes[source-1].d = 0;
    nodes[source-1].p = NULL;
    nodes[source-1].c = 'g';
    push(&queue, &nodes[source-1]);
    #ifdef DEBUG
    printf("Pushed %s\n", nodes[source-1].name);
    display_queue(queue);
    #endif
    while(!empty(queue))
    {
        u = pop(&queue);
        #ifdef DEBUG
        printf("Popped %s\n", u->name);
        display_queue(queue);
        #endif
        i = u->id;
        ptr = adj[i-1];
        while(ptr != NULL)
        {
            if(nodes[ptr->vertex-1].c == 'w')
            {
                nodes[ptr->vertex-1].c = 'g';
                nodes[ptr->vertex-1].d = u->d + 1;
                nodes[ptr->vertex-1].p = u;
                push(&queue, &nodes[ptr->vertex-1]);
                #ifdef DEBUG
                printf("Pushed %s\n", nodes[ptr->vertex-1].name);
                display_queue(queue);
                #endif
            }
            ptr = ptr->next;
        }
        u->c = 'b';
    }
    
    #ifdef DEBUG
    printf("***Printing paths***\n");
    #endif
    for(i=0; i<num_nodes; ++i)
    {
        if(i != source-1)
        {
            print_path(&nodes[source-1], &nodes[i]);
            printf("\n");
        }
    }
    
    return 1;
}
示例#9
0
文件: my_main.c 项目: stuydw/mdl
void my_main( int polygons ) {

  int i, j;
  double step = 0.05; // Decided to make step this value
  double xval, yval, zval;
  struct matrix *transform;
  struct matrix *tmp;
  struct stack *s;
  screen t;
  color g;

  g = change_color(2);

  int axis; // 0,1,2 correspond to x,y,z axes of rotation, respectively
  double measure; // corresponds to angle of rotation

  double width, height, depth; // For box

  double radius; // For sphere

  double r1, r2; // For torus

  double x2,y2,z2; // For line
  
  s = new_stack();
  tmp = new_matrix(4, 1000);
  clear_screen( t );

  for (i=0;i<lastop;i++) {  
    switch (op[i].opcode) {

    case COMMENT:
      break;

    case PUSH:
      push(s);
      break;

    case POP:
      pop(s);
      break;

    case MOVE:
      xval = op[i].op.move.d[0];
      yval = op[i].op.move.d[1];
      zval = op[i].op.move.d[2];

      transform = make_translate(xval, yval, zval);      
      matrix_mult(s->data[s->top], transform);
      s->data[s->top] = transform;
      break;

    case SCALE:
      xval = op[i].op.scale.d[0];
      yval = op[i].op.scale.d[1];
      zval = op[i].op.scale.d[2];

      transform = make_scale(xval, yval, zval);
      matrix_mult(s->data[s->top], transform);
      s->data[s->top] = transform;
      break;

    case ROTATE:
      axis = op[i].op.rotate.axis;
      measure = op[i].op.rotate.degrees;

      if(axis == 0){
	transform = make_rotX(measure);}
      if(axis == 1){
	transform = make_rotY(measure);}
      if(axis == 2){
	transform = make_rotZ(measure);}

      matrix_mult(s->data[s->top], transform);
      s->data[s->top] = transform;
      break;

    case BOX:
      for(j = 0; j < tmp->lastcol; j++){
	tmp->m[0][j] = 0;
	tmp->m[1][j] = 0;
	tmp->m[2][j] = 0;
      }
      tmp->lastcol = 0;

      xval = op[i].op.box.d0[0];
      yval = op[i].op.box.d0[1];
      zval = op[i].op.box.d0[2];

      width = op[i].op.box.d1[0];
      height = op[i].op.box.d1[1];
      depth = op[i].op.box.d1[2];

      add_box(tmp, xval, yval, zval, width, height, depth);
      matrix_mult(s->data[s->top], tmp);
      //matrix_mult(transform, tmp);
      draw_polygons(tmp, t, g);
      //free_matrix(tmp);
      break;

    case SPHERE:
      for(j = 0; j < tmp->lastcol; j++){
	tmp->m[0][j] = 0;
	tmp->m[1][j] = 0;
	tmp->m[2][j] = 0;
      }
      tmp->lastcol = 0;

      xval = op[i].op.sphere.d[0];
      yval = op[i].op.sphere.d[1];
      zval = op[i].op.sphere.d[2];

      radius = op[i].op.sphere.r;

      add_sphere(tmp, xval, yval, zval, radius, step);
      matrix_mult(s->data[s->top], tmp);
      draw_polygons(tmp, t, g);
      break;

    case TORUS:
      for(j = 0; j < tmp->lastcol; j++){
	tmp->m[0][j] = 0;
	tmp->m[1][j] = 0;
	tmp->m[2][j] = 0;
      }
      tmp->lastcol = 0;

      xval = op[i].op.torus.d[0];
      yval = op[i].op.torus.d[1];
      zval = op[i].op.torus.d[2];

      r1 = op[i].op.torus.r0;
      r2 = op[i].op.torus.r1;

      add_torus(tmp, xval, yval, zval, r1, r2, step);
      matrix_mult(s->data[s->top], tmp);
      draw_polygons(tmp, t, g);
      break;

    case LINE:
      for(j = 0; j < tmp->lastcol; j++){
	tmp->m[0][j] = 0;
	tmp->m[1][j] = 0;
	tmp->m[2][j] = 0;
      }
      tmp->lastcol = 0;

      xval = op[i].op.line.p0[0];
      yval = op[i].op.line.p0[1];
      zval = op[i].op.line.p0[2];

      x2 = op[i].op.line.p1[0];
      y2 = op[i].op.line.p1[1];
      z2 = op[i].op.line.p1[2];

      add_edge(tmp, xval, yval, zval, x2, y2, z2);
      matrix_mult(s->data[s->top], tmp);
      draw_lines(tmp, t, g);
      break;

    case SAVE:
      save_extension(t, op[i].op.save.p->name);
      break;
      
    case DISPLAY:
      display(t);
      break;
      
    }
  }

  //free_stack(s);
  //free_matrix(transform);
}
示例#10
0
void Orderizer::process_solution(Space* space)
{
  // sanity check
  if (space == NULL) error("Space is NULL in Orderizer:process_solution().");

  if (!space->is_up_to_date())
    error("The space is not up to date.");

  int type = 1;

  nv = nt = ne = nl = 0;
  del_slot = -1;

  // estimate the required number of vertices and triangles
  Mesh* mesh = space->get_mesh();
  if (mesh == NULL) {
    error("Mesh is NULL in Orderizer:process_solution().");
  }
  int nn = mesh->get_num_active_elements();
  int ev = 77 * nn, et = 64 * nn, ee = 16 * nn, el = nn + 10;

  // reuse or allocate vertex, triangle and edge arrays
  lin_init_array(verts, double3, cv, ev);
  lin_init_array(tris, int3, ct, et);
  lin_init_array(edges, int3, ce, ee);
  lin_init_array(lvert, int, cl1, el);
  lin_init_array(ltext, char*, cl2, el);
  lin_init_array(lbox, double2, cl3, el);
  info = NULL;

  int oo, o[6];

  RefMap refmap;
  refmap.set_quad_2d(&quad_ord);

  // make a mesh illustrating the distribution of polynomial orders over the space
  Element* e;
  for_all_active_elements(e, mesh)
  {
    oo = o[4] = o[5] = space->get_element_order(e->id);
    for (unsigned int k = 0; k < e->nvert; k++)
      o[k] = space->get_edge_order(e, k);

    refmap.set_active_element(e);
    double* x = refmap.get_phys_x(type);
    double* y = refmap.get_phys_y(type);

    double3* pt = quad_ord.get_points(type);
    int np = quad_ord.get_num_points(type);
    int id[80];
    assert(np <= 80);

    #define make_vert(index, x, y, val) \
      { (index) = add_vertex(); \
      verts[index][0] = (x); \
      verts[index][1] = (y); \
      verts[index][2] = (val); }

    int mode = e->get_mode();
    if (e->is_quad())
    {
      o[4] = H2D_GET_H_ORDER(oo);
      o[5] = H2D_GET_V_ORDER(oo);
    }
    make_vert(lvert[nl], x[0], y[0], o[4]);

    for (int i = 1; i < np; i++)
      make_vert(id[i-1], x[i], y[i], o[(int) pt[i][2]]);

    for (int i = 0; i < num_elem[mode][type]; i++)
      add_triangle(id[ord_elem[mode][type][i][0]], id[ord_elem[mode][type][i][1]], id[ord_elem[mode][type][i][2]]);

    for (int i = 0; i < num_edge[mode][type]; i++)
    {
      if (e->en[ord_edge[mode][type][i][2]]->bnd || (y[ord_edge[mode][type][i][0] + 1] < y[ord_edge[mode][type][i][1] + 1]) ||
          ((y[ord_edge[mode][type][i][0] + 1] == y[ord_edge[mode][type][i][1] + 1]) &&
           (x[ord_edge[mode][type][i][0] + 1] <  x[ord_edge[mode][type][i][1] + 1])))
      {
        add_edge(id[ord_edge[mode][type][i][0]], id[ord_edge[mode][type][i][1]], 0);
      }
    }

    double xmin = 1e100, ymin = 1e100, xmax = -1e100, ymax = -1e100;
    for (unsigned int k = 0; k < e->nvert; k++)
    {
      if (e->vn[k]->x < xmin) xmin = e->vn[k]->x;
      if (e->vn[k]->x > xmax) xmax = e->vn[k]->x;
      if (e->vn[k]->y < ymin) ymin = e->vn[k]->y;
      if (e->vn[k]->y > ymax) ymax = e->vn[k]->y;
    }
    lbox[nl][0] = xmax - xmin;
    lbox[nl][1] = ymax - ymin;
    ltext[nl++] = labels[o[4]][o[5]];
  }
void BMMap::make_edges_delauney(  )
{
	for (int i=0; i < nloc; i++) {
		for (int j=0; j < nloc; j++) {
			adj[i][j].pass = 0;
		}
	}

	// DBG: fill in edges at random
#if 0
	for (i=0; i <10; i++) {
		int l1,l2;
		l1 = random( nloc );
		l2 = random( nloc );
		adj[l1][l2].pass = 1;
		adj[l2][l1].pass = 1;
	}
#endif

	std::vector<Triangle> tris, tris2;
	tris.push_back( Triangle() );
	tris.push_back( Triangle() );
	tris[0].ax = 0; tris[0].ay = 0;
	tris[0].bx = 800; tris[0].by = 0;
	tris[0].cx = 800; tris[0].cy = 600;

	tris[1].ax = 0;   tris[1].ay = 0;
	tris[1].bx = 0;   tris[1].by = 600;
	tris[1].cx = 800; tris[1].cy = 600;

	// edgelist
	std::vector<Edge> edge;

	for (int ndx=0; ndx < nloc; ndx++) {
		
		// init lists
		tris2.erase( tris2.begin(), tris2.end() );
		edge.erase( edge.begin(), edge.end() );
		

		// find all triangle whose circumcenter contains loc ndx
		for (i=0; i < tris.size(); i++) {
			float cx, cy, rad;

			circumcenter( tris[i], cx, cy, rad );
			float d = sqrt( (loc[ndx].xpos - cx) * (loc[ndx].xpos - cx) +
						    (loc[ndx].ypos - cy) * (loc[ndx].ypos - cy) );
			if (d <= rad) {
				// in triangle circumcenter, add to edgelist
				add_edge( edge, tris[i].ax, tris[i].ay, tris[i].bx, tris[i].by );
				add_edge( edge, tris[i].bx, tris[i].by, tris[i].cx, tris[i].cy );
				add_edge( edge, tris[i].cx, tris[i].cy, tris[i].ax, tris[i].ay );
				
			} else {
				// just keep the tri
				tris2.push_back( tris[i] );
				//printf("Keeping tri %i\n", i );
			}
		}

		// add a triangle for every edge appearing once in the list
		for (i=0; i < edge.size(); i++) {
			if ( edge[i].count == 1 ) {
				Triangle t;
				t.ax = loc[ndx].xpos;
				t.ay = loc[ndx].ypos;
				t.bx = edge[i].x1; t.by = edge[i].y1;
				t.cx = edge[i].x2; t.cy = edge[i].y2;
				tris2.push_back( t );

				//printf("constructing tri\n" );
			}
		}

		// update the list
		tris = tris2;				
	}


	// convert the tris to adjacency
	for (i=0; i < tris.size(); i++) {
		int andx, bndx, cndx;

		andx = -1; bndx = -1; cndx = -1;
		for (int j=0; j < nloc; j++) {
			if ( ((int)tris[i].ax == loc[j].xpos) &&
				 ((int)tris[i].ay == loc[j].ypos) ) andx = j;
			
			if ( ((int)tris[i].bx == loc[j].xpos) &&
				 ((int)tris[i].by == loc[j].ypos) ) bndx = j;
			
			if ( ((int)tris[i].cx == loc[j].xpos) &&
				 ((int)tris[i].cy == loc[j].ypos) ) cndx = j;
		}

		if ( (andx > 0) && (bndx >=0 )) {
			adj[andx][bndx].pass = 1;
			adj[bndx][andx].pass = 1;

			if (!adj[andx][bndx].de) {
				DualEdge *de = find_dual_edge( tris, andx, bndx );
				adj[andx][bndx].de = de;
				adj[bndx][andx].de = de;
			}

		}

		if ( (bndx > 0) && (cndx >=0 )) {
			adj[bndx][cndx].pass = 1;
			adj[cndx][bndx].pass = 1;

			if (!adj[bndx][cndx].de) {
				DualEdge *de = find_dual_edge( tris, bndx, cndx );
				adj[bndx][cndx].de = de;
				adj[cndx][bndx].de = de;
			}
		}

		if ( (cndx > 0) && (andx >=0 )) {
			adj[cndx][andx].pass = 1;
			adj[andx][cndx].pass = 1;

			if (!adj[cndx][andx].de) {
				DualEdge *de = find_dual_edge( tris, cndx, andx );
				adj[cndx][andx].de = de;
				adj[andx][cndx].de = de;
			}
		}
	}
	
}
示例#12
0
  bool is_kuratowski_subgraph(const Graph& g,
                              ForwardIterator begin, 
                              ForwardIterator end, 
                              VertexIndexMap vm
                              )
  {

    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;
    typedef typename graph_traits<Graph>::edge_descriptor edge_t;
    typedef typename graph_traits<Graph>::edges_size_type e_size_t;
    typedef typename graph_traits<Graph>::vertices_size_type v_size_t;
    typedef typename std::vector<vertex_t> v_list_t;
    typedef typename v_list_t::iterator v_list_iterator_t;
    typedef iterator_property_map
      <typename std::vector<v_list_t>::iterator, VertexIndexMap> 
      vertex_to_v_list_map_t;

    typedef adjacency_list<vecS, vecS, undirectedS> small_graph_t;

    detail::target_graph_t target_graph = detail::tg_k_3_3; //unless we decide otherwise later

    static small_graph_t K_5(detail::make_K_5<small_graph_t>());

    static small_graph_t K_3_3(detail::make_K_3_3<small_graph_t>());

    v_size_t n_vertices(num_vertices(g));
    v_size_t max_num_edges(3*n_vertices - 5);

    std::vector<v_list_t> neighbors_vector(n_vertices);
    vertex_to_v_list_map_t neighbors(neighbors_vector.begin(), vm);

    e_size_t count = 0;
    for(ForwardIterator itr = begin; itr != end; ++itr)
      {

        if (count++ > max_num_edges)
          return false;

        edge_t e(*itr);
        vertex_t u(source(e,g));
        vertex_t v(target(e,g));

        neighbors[u].push_back(v);
        neighbors[v].push_back(u);

      }


    for(v_size_t max_size = 2; max_size < 5; ++max_size)
      {

        vertex_iterator_t vi, vi_end;
        for(boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)
          {
            vertex_t v(*vi);

            //a hack to make sure we don't contract the middle edge of a path
            //of four degree-3 vertices
            if (max_size == 4 && neighbors[v].size() == 3)
              {
                if (neighbors[neighbors[v][0]].size() +
                    neighbors[neighbors[v][1]].size() +
                    neighbors[neighbors[v][2]].size()
                    < 11 // so, it has two degree-3 neighbors
                    )
                  continue;
              }

            while (neighbors[v].size() > 0 && neighbors[v].size() < max_size)
              {
                // Find one of v's neighbors u such that that v and u
                // have no neighbors in common. We'll look for such a 
                // neighbor with a naive cubic-time algorithm since the 
                // max size of any of the neighbor sets we'll consider 
                // merging is 3
                
                bool neighbor_sets_intersect = false;
                
                vertex_t min_u = graph_traits<Graph>::null_vertex();
                vertex_t u;
                v_list_iterator_t v_neighbor_end = neighbors[v].end();
                for(v_list_iterator_t v_neighbor_itr = neighbors[v].begin();
                    v_neighbor_itr != v_neighbor_end; 
                    ++v_neighbor_itr
                    )
                  {
                    neighbor_sets_intersect = false;
                    u = *v_neighbor_itr;
                    v_list_iterator_t u_neighbor_end = neighbors[u].end();
                    for(v_list_iterator_t u_neighbor_itr = 
                          neighbors[u].begin();
                        u_neighbor_itr != u_neighbor_end && 
                          !neighbor_sets_intersect; 
                        ++u_neighbor_itr
                        )
                      {
                        for(v_list_iterator_t inner_v_neighbor_itr = 
                              neighbors[v].begin();
                            inner_v_neighbor_itr != v_neighbor_end; 
                            ++inner_v_neighbor_itr
                            )
                          {
                            if (*u_neighbor_itr == *inner_v_neighbor_itr)
                              {
                                neighbor_sets_intersect = true;
                                break;
                              }
                          }
                        
                      }
                    if (!neighbor_sets_intersect &&
                        (min_u == graph_traits<Graph>::null_vertex() || 
                         neighbors[u].size() < neighbors[min_u].size())
                        )
                      {
                        min_u = u;
                      }
                        
                  }

                if (min_u == graph_traits<Graph>::null_vertex())
                  // Exited the loop without finding an appropriate neighbor of
                  // v, so v must be a lost cause. Move on to other vertices.
                  break;
                else
                  u = min_u;

                detail::contract_edge(neighbors, u, v);

              }//end iteration over v's neighbors

          }//end iteration through vertices v

        if (max_size == 3)
          {
            // check to see whether we should go on to find a K_5
            for(boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)
              if (neighbors[*vi].size() == 4)
                {
                  target_graph = detail::tg_k_5;
                  break;
                }

            if (target_graph == detail::tg_k_3_3)
              break;
          }
        
      }//end iteration through max degree 2,3, and 4

    
    //Now, there should only be 5 or 6 vertices with any neighbors. Find them.
    
    v_list_t main_vertices;
    vertex_iterator_t vi, vi_end;
    
    for(boost::tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)
      {
        if (!neighbors[*vi].empty())
          main_vertices.push_back(*vi);
      }
    
    // create a graph isomorphic to the contracted graph to test 
    // against K_5 and K_3_3
    small_graph_t contracted_graph(main_vertices.size());
    std::map<vertex_t,typename graph_traits<small_graph_t>::vertex_descriptor> 
      contracted_vertex_map;
    
    typename v_list_t::iterator itr, itr_end;
    itr_end = main_vertices.end();
    typename graph_traits<small_graph_t>::vertex_iterator 
      si = vertices(contracted_graph).first;
    
    for(itr = main_vertices.begin(); itr != itr_end; ++itr, ++si)
      {
        contracted_vertex_map[*itr] = *si;
      }

    typename v_list_t::iterator jtr, jtr_end;
    for(itr = main_vertices.begin(); itr != itr_end; ++itr)
      {
        jtr_end = neighbors[*itr].end();
        for(jtr = neighbors[*itr].begin(); jtr != jtr_end; ++jtr)
          {
            if (get(vm,*itr) < get(vm,*jtr))
              {
                add_edge(contracted_vertex_map[*itr],
                         contracted_vertex_map[*jtr],
                         contracted_graph
                         );
              }
          }
      }
    
    if (target_graph == detail::tg_k_5)
      {
        return boost::isomorphism(K_5,contracted_graph);
      }
    else //target_graph == tg_k_3_3
      {
        return boost::isomorphism(K_3_3,contracted_graph);
      }
    
    
  }
int main()
{
  int tn,n;
  int i,j;
  string str;
  int a,b,t;
  int tid, id;
  int costNode, costEdge;
  int inCirV;
  name[0] = string("Source");

  cin >> tn;
  while(tn--){
    cin >> n;
    Init();
    for(i=0;i<n;i++){
      cin >> str;
      scanf("%d%d",&a,&b);
      id = getID(str);
      add_edge(0, id, a);
      while(b--){
        cin >> str;
        scanf("%d",&a);
        tid = getID(str);
        add_edge(tid, id, a);
      }
    }
    cin >> t;
    while(t--){
      cin >> str;
      id = getID(str);
      add_edge(0, id, 0);
    }
    n++;
    memset(del, 0, sizeof(del));
    costNode = 0;
    while(1){
      for(i=0;i<n;i++) minIn[i] = INF, frm[i] = -1;
      for(i=0;i<m;i++){
        int u = edge[i][0];
        int v = edge[i][1];
        int cst = edge[i][2];
        if(u==v)continue;
        if(cst < minIn[v])
          minIn[v] = cst, frm[v] = u;
      }
      bool circleFlag = false;
      costEdge = 0;
      memset(use,-1,sizeof(use));
      memset(leader,-1,sizeof(leader));
      for(i=0;i<n;i++){
        if(del[i])continue;
        if(frm[i]==-1 && i!=0)return INF;
        if(i)costEdge += minIn[i];
        for(j=i; j!=-1 && use[j]==-1 ;j = frm[j])use[j] = i;
        if(j!=-1 && use[j]==i){
          circleFlag = true; inCirV = j;
          do{
            del[j] = 1;
            leader[j] = inCirV;
            costNode += minIn[j];
            j = frm[j];
          }while(j != inCirV);
          del[inCirV] = 0;
        }
      }
      if(!circleFlag)break;
      for(i=0;i<m;i++){
        int &u = edge[i][0];
        int &v = edge[i][1];
        int &cst = edge[i][2];
        if(u==v)continue;
        if(leader[v]!=-1)cst -= minIn[v];
        if(leader[u]!=-1)u = leader[u];
        if(leader[v]!=-1)v = leader[v];
        if(u == v) u = v = -1;
      }
    }
    if(debug)cout << "test:" << (costEdge+costNode) << "\n";
    cout << int((costNode+costEdge+4)/5) << "\n";
  }
  return 0;
}
示例#14
0
文件: main.c 项目: stuydw/matrix
int main() {

  struct matrix* testMatrix = new_matrix(10,10);
  struct matrix* testMatrix2 =new_matrix(10,10);
  struct matrix* m = new_matrix(3,1);
 
  int x,y;
  
  for (x = 0; x < testMatrix->rows; x++){
    for(y = 0; y < testMatrix->cols; y++){
      testMatrix -> m[x][y] = x + y + 3;
      testMatrix2 ->m[x][y] = 2;
    }
  }


  print_matrix(testMatrix);
  print_matrix(testMatrix2);

  matrix_mult(testMatrix,testMatrix2);
  print_matrix(testMatrix2);

  //scalar_mult(2,testMatrix);
  //printf("AFTER SCALAR \n");
  //print_matrix(testMatrix);

  //ident(testMatrix);
  //printf("AFTER IDENT \n");
  // print_matrix(testMatrix);

  screen s;
  color c;

  add_edge(m, 190, 100, 20, 100, 430, 0);
  add_edge(m, 160, 400, 20, 400, 160, 0);
  add_edge(m, 450, 100, 20, 400, 100, 0);
  add_edge(m, 250, 130, 20, 250, 350, 0);
  add_edge(m, 250, 250, 20, 325, 340, 0);


  c.red = 0;
  c.green = 255;
  c.blue = 255;
  
  int i, j;

  for( i=0; i<XRES; i++) 
    for ( j=0; j<YRES; j++) {

      c.red = random() % (MAX_COLOR + 1);
      c.green = random() % (MAX_COLOR + 1);
      c.blue = random() % (MAX_COLOR + 1);

      plot( s, c, i, j);
    }

  display( s );    
  save_ppm(s,  "image" );
  save_extension(s, "image.jpg");
  
}  
示例#15
0
文件: network.cpp 项目: gandalfvn/EOH
void NETWORK::load_network2(std::map<std::pair<std::string , std::string>,float> network, bool _weighted, int edges )
{
  // message file
  //std::string msg_file = _output + ".msg";
  //FILE *pMsg = NULL;

  // reset network
  for(int i=0; i<Order; i++)
    delete Nodes[i];
  Nodes.clear();
  Order = 0;
  Size = 0;

  // read edges
 // FILE_HANDLER f( _input_file.c_str(), "r" );
  //int edges = f.rows();
  //char line[1024] = {""};
  std::map<std::string, int> hash_table;
  int source, target;
  double weight;
  //char source_label[128] = {""};
  //char target_label[128] = {""};
  int source_id = 0;
  int target_id = 0;
  int columns;
  if (network.size() !=0)
  {
  std::map<std::pair<std::string , std::string>,float>::iterator it;
  for (std::map<std::pair<std::string , std::string>,float>::iterator it=network.begin(); it!=network.end(); ++it)
   {
    //f.get_text_line( line, sizeof(line) );
    //// check if line is valid (two or threee columns)
    //weight = 1.0;
    //columns = sscanf( line, "%s %s %lf", source_label, target_label, &weight );
    //if( (!_weighted && columns < 2) || (_weighted && columns != 3) )
    //{
    //  pMsg = fopen( msg_file.c_str(), "w" );
    //  fprintf( pMsg, "Error\nMissing column in line %i.", n+1 );
    //  fclose( pMsg );
    //  exit( 0 );
    //}
    std::pair< std::map<std::string, int>::iterator, bool> added;

    // source node
    added = hash_table.insert( std::pair<std::string, int>(std::string(it->first.first), (int)Nodes.size()) );
    if( added.second )
    {
      source_id = (int)Nodes.size();
	  add_node( it->first.first.c_str() );
    }
    else
      source_id = added.first->second;

    // target node
    added = hash_table.insert( std::pair<std::string, float>(std::string(it->first.second), (int)Nodes.size()) );
    if( added.second )
    {
      target_id = (int)Nodes.size();
      add_node( it->first.second.c_str());
    }
    else
      target_id = added.first->second;

    // add edge
    if( is_there_edge(source_id, target_id) )
    {
      weight += get_edge_weight( source_id, target_id );
      remove_edge(source_id, target_id);
      add_edge( source_id, target_id, abs(it->second)  );
    }
    else
      add_edge( source_id, target_id, abs(it->second) );
  }
}

  // if size limitazion is on, check network size
  //if( _size_limit != 0 && Order > _size_limit )
  //{
  //  pMsg = fopen( msg_file.c_str(), "w" );
  //  fprintf( pMsg, "Error\nNetwork is too large." );
  //  fclose( pMsg );
  //  exit(0);
  //}

  // normalize weights
  // uncomment this part for normal hierarchy computation
  // this commented out for no weight hierarchy computation
  /*int deg;
  double max_weight = Nodes[0]->outweight(0);
  for(int i=0; i<Order; i++)
  {
    deg = Nodes[i]->outdegree();
    for(int j=0; j<deg; j++)
    {
      if( Nodes[i]->outweight(j) > max_weight )
        max_weight = Nodes[i]->outweight(j);
    }
  }
  for(int i=0; i<Order; i++)
  {
    deg = Nodes[i]->outdegree();
    for(int j=0; j<deg; j++)
      Nodes[i]->setOutWeight( j, Nodes[i]->outweight(j)/max_weight );
  }*/

  // print network properties
  //pMsg = fopen( msg_file.c_str(), "w" );
  //fprintf( pMsg, "Success\n%i\n%i", Order, Size );
  //fclose( pMsg );
}
示例#16
0
/*======== void parse_file () ==========
Inputs:   char * filename 
          struct matrix * transform, 
          struct matrix * pm,
          screen s
Returns: 

Goes through the file named filename and performs all of the actions listed in that file.
The file follows the following format:
     Every command is a single character that takes up a line
     Any command that requires arguments must have those arguments in the second line.
     The commands are as follows:
         line: add a line to the edge matrix - 
	    takes 6 arguemnts (x0, y0, z0, x1, y1, z1)
	 circle: add a circle to the edge matrix - 
	    takes 3 arguments (cx, cy, r)
	 hermite: add a hermite curve to the edge matrix -
	    takes 8 arguments (x0, y0, x1, y1, x2, y2, x3, y3)
	 bezier: add a bezier curve to the edge matrix -
	    takes 8 arguments (x0, y0, x1, y1, x2, y2, x3, y3)
         sphere: add a sphere to the edge matrix - 
	    takes 3 arguemnts (cx, cy, r)
         torus: add a torus to the edge matrix - 
	    takes 4 arguemnts (cx, cy, r1, r2)
         box: add a rectangular prism to the edge matrix - 
	    takes 6 arguemnts (x, y, z, width, height, depth)
	 clear: clear the currnt edge matrix -
	    takes 0 arguments
	 ident: set the transform matrix to the identity matrix - 
	 scale: create a scale matrix, 
	    then multiply the transform matrix by the scale matrix - 
	    takes 3 arguments (sx, sy, sz)
	 translate: create a translation matrix, 
	    then multiply the transform matrix by the translation matrix - 
	    takes 3 arguments (tx, ty, tz)
	 xrotate: create an x-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 yrotate: create an y-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 zrotate: create an z-axis rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 1 argument (theta)
	 apply: apply the current transformation matrix to the 
	    edge matrix
	 display: draw the lines of the edge matrix to the screen
	    display the screen
	 save: draw the lines of the edge matrix to the screen
	    save the screen to a file -
	    takes 1 argument (file name)
	 quit: end parsing

See the file script for an example of the file format


IMPORTANT MATH NOTE:
the trig functions int math.h use radian mesure, but us normal
humans use degrees, so the file will contain degrees for rotations,
be sure to conver those degrees to radians (M_PI is the constant
for PI)
====================*/
void parse_file ( char * filename, 
                  struct matrix * transform, 
                  struct matrix * pm,
                  screen s) {

  FILE *f;
  char line[256];
  struct matrix * tmp;
  double angle;
  color g;


  g.red = 0;
  g.green = 255;
  g.blue = 0;

  struct stack * original = new_stack();

  
  clear_screen(s);

  if ( strcmp(filename, "stdin") == 0 ) 
    f = stdin;
  else
    f = fopen(filename, "r");
  
  while ( fgets(line, 255, f) != NULL ) {
    line[strlen(line)-1]='\0';
    //printf(":%s:\n",line);
    double x, y, z, x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4;
    
    if ( strncmp(line, "line", strlen(line)) == 0 ) {
      //      printf("LINE!\n");
      fgets(line, 255, f);
      //      printf("\t%s", line);
      //line[strlen(line)-1]='\0';
      sscanf(line, "%lf %lf %lf %lf %lf %lf", &x, &y, &z, &x1, &y1, &z1);
      add_edge(pm, x, y, z, x1, y1, z1);
      matrix_mult(original->data[original->top], tmp);
      draw_lines(tmp, s, g);
      //free_matrix(tmp);

      // printf( "%lf %lf %lf %lf %lf %lf\n", x, y, z, x1, y1, z1);
    }
    else if ( strncmp(line, "push", strlen(line)) == 0 ) {
      push(original);
    }
    else if ( strncmp(line, "pop", strlen(line)) == 0 ) {
      pop(original);
    }
    else if ( strncmp(line, "circle", strlen(line)) == 0 ) {
      //printf("CIRCLE\n");
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      add_circle(pm, x, y, z, 0.01);
      matrix_mult(original->data[original->top], tmp);
      draw_lines(tmp, s, g);
      //free_matrix(tmp);

      //printf( "%lf %lf %lf\n", x, y, z);
    }    
    else if ( strncmp(line, "bezier", strlen(line)) == 0 ) {
      //printf("BEZIER\n");
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf %lf %lf",
	     &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4);
      add_curve(pm, x1, y1, x2, y2, x3, y3, x4, y4, 0.01, BEZIER_MODE );
      matrix_mult(original->data[original->top], tmp);
      draw_lines(tmp, s, g);

      //printf( "%lf %lf %lf\n", x, y, z);
    }    
    else if ( strncmp(line, "hermite", strlen(line)) == 0 ) {
      //printf("HERMITE\n");
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf %lf %lf",
	     &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4);
      add_curve(pm, x1, y1, x2, y2, x3, y3, x4, y4, 0.01, HERMITE_MODE );
      matrix_mult(original->data[original->top], tmp);
      draw_lines(tmp, s, g);
      //printf( "%lf %lf %lf\n", x, y, z);
    }
    else if ( strncmp(line, "box", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf", &x, &y, &z, &x1, &y1, &z1);
      add_box(pm, x, y, z, x1, y1, z1);
      matrix_mult(original->data[original->top], tmp);
      draw_polygons(tmp, s, g);

      // printf( "%lf %lf %lf %lf %lf %lf\n", x, y, z, x1, y1, z1);
    }
    else if (strncmp(line, "sphere", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      add_sphere(pm, x, y, z, 10);
      matrix_mult(original->data[original->top], tmp);
      draw_polygons(tmp, s, g);
      //printf( "%lf %lf %lf\n", x, y, z);
    }
    else if (strncmp(line, "torus", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf", &x, &y, &z, &z1);
      add_torus(pm, x, y, z, z1, 10);
      matrix_mult(original->data[original->top], tmp);
      draw_polygons(tmp, s, g);
      //printf( "%lf %lf %lf\n", x, y, z);
    }
    else if ( strncmp(line, "scale", strlen(line)) == 0 ) {
      //printf("SCALE\n");
      fgets(line, 255, f);
      //line[strlen(line)-1]='\0';      
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      tmp = make_scale(x, y, z);
      matrix_mult(tmp, transform);
      matrix_mult(original->data[original->top], tmp);
      copy_matrix(tmp, original->data[original->top]);
      //print_matrix(transform);
    }
    else if ( strncmp(line, "translate", strlen(line)) == 0 ) {
      //printf("TRANSLATE\n");
      fgets(line, 255, f);
      //      line[strlen(line)-1]='\0';      
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      tmp = make_translate(x, y, z);
      matrix_mult(tmp, transform);
      copy_matrix(tmp, original->data[original->top]);
      //print_matrix(transform);
    }
    else if ( strncmp(line, "xrotate", strlen(line)) == 0 ) {
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotX( angle);
      matrix_mult(original->data[original->top], tmp);
      copy_matrix(tmp, original->data[original->top]);
    }
    else if ( strncmp(line, "yrotate", strlen(line)) == 0 ) {
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotY( angle);
      matrix_mult(original->data[original->top], tmp);
      copy_matrix(tmp, original->data[original->top]);
    }
    else if ( strncmp(line, "zrotate", strlen(line)) == 0 ) {
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotZ( angle);
      matrix_mult(original->data[original->top], tmp);
      copy_matrix(tmp, original->data[original->top]);
    }
    else if ( strncmp(line, "ident", strlen(line)) == 0 ) {
      ident(transform);
    }
    else if ( strncmp(line, "apply", strlen(line)) == 0 ) {
      //printf("APPLY!\n");
      //print_matrix( transform );
      //      print_matrix(pm);
      matrix_mult(transform, pm);
    }
    else if ( strncmp(line, "display", strlen(line)) == 0 ) {
      //clear_screen(s);
      //draw_polygons(pm, s, g);
      display(s);
    }
    else if ( strncmp(line, "save", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      line[strlen(line)-1] = '\0';
      //clear_screen(s);
      //draw_polygons(pm, s, g);
      save_extension(s, line);
    }
    else if ( strncmp(line, "clear", strlen(line)) == 0 ) {
      pm->lastcol = 0;
    }
    else if ( strncmp(line, "quit", strlen(line)) == 0 ) {
      return;
    }
    else if ( line[0] != '#' ) {
      printf("Invalid command\n");
    }
  }
  
  free_matrix(tmp);
  fclose(f);
  //printf("END PARSE\n");
}
示例#17
0
ftkgnt::MTreeType ftkgnt::BuildMergeTreeDcon(ftkgnt::RAGraph R1, unsigned short id,std::vector< std::set<int> > hypothesis)
{
	//Create the Merge Tree
	ftkgnt::MTreeType mTree; 
	std::set<int> currRPS;
	std::set<int> nextRPS;	
	
	//To store the RPSs @ the current depth
	std::vector<std::set<int> > curr_depth_RPS;
	
	//To store the RPSs @ all depths
	std::vector< std::vector< std::set<int> > > depth_map;  
	
	//This vector stores the current vector of labels (in int ) 
	std::set< int > curr_members;
	
	unsigned int depth;
	
	//Add the root node to the Merge Tree
	std::string s = convert2string(id);
	ftkgnt::node_mt V;
	V = add_vertex(mTree);
	
	//Current Root Path Set 	
	currRPS.insert(id);
	
	mTree[V].label =  s;
	mTree[V].RPS = currRPS;
	curr_depth_RPS.push_back(currRPS);
	depth_map.push_back(curr_depth_RPS);
	depth = 0;
	curr_depth_RPS = depth_map[depth];
	
	//Add the root as a member and get the current volume
	curr_members.insert(static_cast<int>(id));
	
	// Adjacency Iterators will iterate through the adjacent vertex of the 
	// Region Adjacency graph1 a.k.a the Adjacency_list
	ftkgnt::AdjVertIt avi, avinext, av_end;
	std::set<int>::iterator it;
	std::set<int>::iterator RPSIterator;
	std::set<int>::iterator volIterator;
	std::set<int>::iterator nRPSIterator;
	std::set<int>::iterator RPSIterator2;
	boost::property_map<ftkgnt::RAGraph, boost::vertex_name_t>::type nodes = get(boost::vertex_name, R1);
	
	//Start the loop here
	
	// Logic: For each node in the tree go through the Root Path Set 
	// For every element in the root path set get the neighbors  
	// Add the neighbor to the tree if valid.
	// Stop when All nodes traversed and if no change in number of vertices and 
	// number of edges,return the graph1
	
	unsigned int counter = 0; 
	while (counter != num_vertices(mTree))
	{
		currRPS =  mTree[counter].RPS;
		
		ftkgnt::node_mt V2 = vertex(counter,mTree);
		for(RPSIterator = currRPS.begin(); RPSIterator != currRPS.end(); RPSIterator++)
		{	
			int vertex_index = GetNodeIndex(static_cast<unsigned short>(*RPSIterator),R1);
			ftkgnt::node v = vertex(vertex_index,R1);
			boost::tie(avi, av_end)=adjacent_vertices(v,R1); 
			
			for (avi=avi; avi < av_end ; ++avi)
			{
				nextRPS = currRPS;	   
				ftkgnt::node X = *avi;
				int neighbor = atoi(nodes[X].c_str());
				
				//if "it" points to currRPS.end(), then this node is not present in 
				// the current RPS. RPS condition in Gang's paper   
				nextRPS.insert(neighbor);	
				
				it=currRPS.find(neighbor);
				depth = nextRPS.size() - 1 ;		   	    
				bool depth_cond = true;
				
				// Check if nextRPS is present in the depthmap for the current depth
				//This is the depth condition in Gang's paper.
				if(depth <= depth_map.size()-1)    
				{
					curr_depth_RPS= depth_map[depth]; 
					depth_cond = (curr_depth_RPS.end() == find(curr_depth_RPS.begin(), curr_depth_RPS.end(), nextRPS));	
				}  
				
				if(it==currRPS.end() && depth_cond)
				{
					//This condition checks if the current node is not @  
					// a new level/depth in the tree in the tree
					if(depth <= depth_map.size()-1) 
					{
							curr_depth_RPS= depth_map[depth];
							curr_depth_RPS.push_back(nextRPS);   
							depth_map[depth] =  curr_depth_RPS;     
					}	
					
					// If it is at the new depth.. first check the minimum volume @ the max depth
					// If this value is > than the limit of the cells... return the tree	   
					// If not update the 	   
					else
					{
						bool dcon = (depth<MAX_DEPTH);
						if(dcon)
						{
								curr_depth_RPS.clear();
								curr_depth_RPS.push_back(nextRPS);   
								depth_map.push_back(curr_depth_RPS);
							}
													
						else
						{
							return mTree;
						}
						
					}
					
					//Check if this hypothesis has been checked previously i.e. if this combination of nodes occured 
					// in a previous merge tree 
					bool hypo_cond;
					hypo_cond = (hypothesis.end() == find(hypothesis.begin(), hypothesis.end(), nextRPS));
						
					double vol = 0;	
					for(volIterator = nextRPS.begin(); volIterator != nextRPS.end(); volIterator++)
					{	
						std::vector<unsigned short>::iterator posn1 = find(labelIndex.begin(), labelIndex.end(), *volIterator);
						ftk::IntrinsicFeatures  features  =	allFeat[posn1 - labelIndex.begin()];
						vol+= features.ScalarFeatures[ftk::IntrinsicFeatures::VOLUME];
					}

					
					//Check for the volume condition 
					//Prevents unnecessary extension of tree branches in clusters   
					bool vol_cond = (vol<MAX_VOL);

					if(hypo_cond && vol_cond)
					{
						ftkgnt::node_mt V;
						V = add_vertex(mTree);
						mTree[V].label = nodes[X];
						mTree[V].RPS = nextRPS;
						int tail = num_vertices(mTree)-1;
						add_edge(counter,tail,mTree);
					}
					
				}
				
				//Delete nextRPS
				nextRPS.clear();
				
			}
			
		}		
		counter = counter +1;
		
	}
	
	return mTree;
	
}
示例#18
0
void check_in_circle(struct point_s * point, scll points, scll triangles, scll edges, cl_command_queue command_queue, cl_kernel kernel, bool is_cpu, int num_points)
{
  int error_code;
  int mult_for_cell_hack;
  if(is_cpu)
    mult_for_cell_hack = 1;
  else
    mult_for_cell_hack = HACK_FOR_PS3_NUM;

  if(is_cpu)
    SetKernelArgsCpu(point, triangles, points);
  else
    SetKernelArgsCell(point, triangles, points);

  cl_event write_event1;
  error_code = clEnqueueWriteBuffer(command_queue, triangles_mem, CL_TRUE, 0, triangles->alloc_size, triangles, 0, NULL, &write_event1);
  if(error_code != 0)
    {
      printf("Error occured writing triangles buffer = %d\n", error_code);
      return;
    }
  
  const size_t work_dim = 1;
  size_t global_work_size[work_dim];
  global_work_size[0] = triangles->count;
  size_t local_work_size[work_dim];
  local_work_size[0] = 1;

  cl_event ndrange_kernel_event;
  error_code = clEnqueueNDRangeKernel(command_queue, kernel, work_dim, NULL, global_work_size,
     local_work_size, 1, &write_event1, &ndrange_kernel_event);
  if(error_code != 0)
    {    
      printf("Error occured launching kernel = %d\n", error_code);  
      return;
    }

  clWaitForEvents(1, &ndrange_kernel_event);

  cl_event read_event;
  error_code = clEnqueueReadBuffer(command_queue, results_mem, CL_TRUE, 0, sizeof(bool) * triangles->count * mult_for_cell_hack, results,
    0, NULL, &read_event);
  clWaitForEvents(1, &read_event);
  if(error_code != 0)
    {
      printf("Error occured reading buffer = %d\n", error_code);
      return;
    }

  scll_node internal_curr_triangle = triangles->head;
  scll_node curr_triangle = scll_real_ptr(triangles, internal_curr_triangle);

  int i = 0;

  while(curr_triangle != NULL)
    {      
      bool * result = (bool *) &results[i * mult_for_cell_hack];
      if(*result == true)
        {
          struct triangle_s * triangle_data = (struct triangle_s *) &(curr_triangle->data);
          add_edge(edges, triangle_data->p1, triangle_data->p2);
          add_edge(edges, triangle_data->p2, triangle_data->p3);
          add_edge(edges, triangle_data->p3, triangle_data->p1);
          scll_node internal_next = curr_triangle->next;
          scll_remove(triangles, internal_curr_triangle);
          internal_curr_triangle = internal_next;
          curr_triangle = scll_real_ptr(triangles, internal_curr_triangle);  
        }
      else
        {
          internal_curr_triangle = curr_triangle->next;
          curr_triangle = scll_real_ptr(triangles, curr_triangle->next);
        }
      ++i;
    }
}
示例#19
0
文件: my_main.c 项目: stuydw/mdl
void my_main( int polygons ) {

  int i;
  double step;
  double xval, yval, zval;
  struct matrix *transform;
  struct matrix *tmp;
  struct stack *s;
  screen t;
  color g;
  
  s = new_stack();
  tmp = new_matrix(4, 1000);
  clear_screen( t );

  void clear_tmp(){
      for(j = 0; j < tmp->lastcol; j++){
	tmp->m[0][j] = 0;
	tmp->m[1][j] = 0;
	tmp->m[2][j] = 0;
      }
      tmp->lastcol = 0;
  }

  for (i=0;i<lastop;i++) {  
   clear_tmp();
   switch (op[i].opcode) {
  	case COMMENT:
	     break;
	case PUSH:
	     push(s);
	     break;
	case POP:
	     pop(s);
	     break;
	case SAVE:
	     save_extension(t, op[i].op.save.p->name);
             break;
        case  MOVE:
             xval = op[i].op.move.d[0];	
             yval = op[i].op.move.d[1];
             zval = op[i].op.move.d[2];
             transform = make_translate(xval, yval, zval);
             matrix_mult(s->data[s->top], transform);
             s->data[s->top]=transform;
	     break;
	case SCALE:
	     xval = op[i].op.move.d[0];
	     yval = op[i].op.move.d[1];
	     zval = op[i].op.move.d[2];
	     transform = make_scale(xval, yval, zval);
	     matrix_mult(s->data[s->top], transform);
	     s->data[s->top]=transform;
	     break;
	case LINE:
	     xval = op[i].op.line.p0[0];
             yval = op[i].op.line.p0[1];
             zval = op[i].op.line.p0[2];
             x2 = op[i].op.line.p1[0];
             y2 = op[i].op.line.p1[1];
             z2 = op[i].op.line.p1[2];
             add_edge(tmp, xval, yval, zval, x2, y2, z2);
             matrix_mult(s->data[s->top], tmp);
             draw_lines(tmp, t, g);
	     break;
	case BOX:
	     xval = op[i].op.box.d0[0];
             yval = op[i].op.box.d0[1];
             zval = op[i].op.box.d0[2];
             width = op[i].op.box.d1[0];
             height = op[i].op.box.d1[1];
             depth = op[i].op.box.d1[2];
             add_box(tmp, xval, yval, zval, width, height, depth);
             matrix_mult(s->data[s->top], tmp);
             draw_polygons(tmp, t, g);
             break;
	case SPHERE:
 	     xval = op[i].op.sphere.d[0];
             yval = op[i].op.sphere.d[1];
             zval = op[i].op.sphere.d[2];
             radius = op[i].op.sphere.r;
	     add_sphere(tmp, xval, yval, zval, radius, step);
      	     matrix_mult(s->data[s->top], tmp);
             draw_polygons(tmp, t, g);
             break;
	case TORUS:
	     xval = op[i].op.torus.d[0];
             yval = op[i].op.torus.d[1];
             zval = op[i].op.torus.d[2];
             r1 = op[i].op.torus.r0;
             r2 = op[i].op.torus.r1;
             add_torus(tmp, xval, yval, zval, r1, r2, step);
             matrix_mult(s->data[s->top], tmp);
             draw_polygons(tmp, t, g);
             break;
	case DISPLAY:
             display(t);
             break;
    }
  }
}
示例#20
0
int main ()
{
  ways = _tmp[0];
  nways = _tmp[1];

  freopen ("restore.in", "rt", stdin);
  freopen ("restore.out", "wt", stdout);

  scanf ("%d %d %d", &n, &m, &p);
  memset (ve, 0, sizeof ve);
  for (int i = 0; i < m; i++)
  {
    int a, b;
    scanf ("%d %d", &a, &b);
    add_edge (a - 1, b - 1);
  }
  scanf ("%d %d", &S, &t);
  S--;
  for (int i = 0; i < t; i++)
    scanf ("%d %d", &A[i], &B[i]);

  _bfs::bfs (S);

  for (int i = 0; i < n; i++)
    if (bi[i] == A[0])
      nways[i] = 1;
    else
      nways[i] = 0;
  _swap ();
  B[0]--;
  int cur = (B[0] ? 0 : 1);
  matrix m;
  while (cur < t)
  {
    m_build (m, A[cur]);
    m_pow (m, B[cur]);
    m_apply (m);
    cur++;
/*    if (B[cur] <= 32)
    {
      for (int i = 0; i < B[cur]; i++)
      {
        for (int j = 0; j < n; j++)
          if (ways[j])
            for (edge* e = ve[j]; e; e = e->next)
              if (bi[e->b] == A[cur])
                nways[e->b] = (nways [e->b] + ways[j]) % p;
        _swap ();
      }
    }
    else
    {
      for (int i = 0; i < 32; i++)
      {
        for (int j = 0; j < n; j++)
          if (ways[j])
            for (edge* e = ve[j]; e; e = e->next)
              if (bi[e->b] == A[cur])
                nways[e->b] = (nways [e->b] + ways[j]) % p;
        _swap ();
      }
      B[cur] -= 32;
      _cmp::compute (B[cur]);
      for (int i = 0; i < n; i++)
        nways[i] = 0;
      for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
          nways[j] = (nways[j] + ways[i] * xways[i][j]) % p;
    }
    cur++;*/
  }

  __int64 sum = 0;
  for (int i = 0; i < n; i++)
    sum = (sum + ways[i]) % p;
  printf ("%I64d", sum);

  return 0;
}
示例#21
0
int main( int argc, char** argv ) {

  screen s;
  struct matrix *edges;
  struct matrix *transform;
  color c;
  c.red = 0;
  c.green = 255;
  c.blue = 255;

  edges = new_matrix(4, 4);
  transform = new_matrix(4, 4);

  if ( argc == 2 )
    parse_file( argv[1], transform, edges, s );
  else
    parse_file( "stdin", transform, edges, s );

  add_edge( edges, 250,0,0, 250,25,0 );//M                       
  add_edge( edges, 250,25,0, 263,0,0 );
  add_edge( edges, 263,0,0, 275,25,0 );
  add_edge( edges, 275,25,0, 275,0,0 );
  add_edge( edges, 280,0,0, 293,25,0 );//A                      
  add_edge( edges, 293,25,0, 305,0,0 );
  add_edge( edges, 287,13,0, 299,13,0 );
  add_edge( edges, 310,0,0, 325,25,0 );//Y                               
  add_edge( edges, 318,13,0, 305,25,0 );
  add_edge( edges, 330,0,0, 343,25,0 );//A                              
  add_edge( edges, 343,25,0, 355,0,0 );
  add_edge( edges, 337,13,0, 349,13,0 );
  add_edge( edges, 360,0,0, 360,25,0 );//N                         
  add_edge( edges, 360,25,0, 385,0,0 );
  add_edge( edges, 385,0,0, 385,25,0 );
  add_edge( edges, 390,0,0, 390,25,0 );//K                           
  add_edge( edges, 390,13,0, 408,25,0 );
  add_edge( edges, 395,14,0, 408,0,0 );
  draw_lines(edges, s, c);

  save_extension(s, "dimensional.png");
  display(s);

  free_matrix( transform );
  free_matrix( edges );
}  
示例#22
0
文件: rim.cpp 项目: DinCahill/pagmo
void rim::connect(const vertices_size_type &)
{
	// Store frequently-used variables.
	const vertices_size_type t_size = get_number_of_vertices();
	pagmo_assert(t_size != 0);
	switch (t_size) {
	case 1: {
			// If the topology was empty, do not do anything.
			break;
		}
	case 2: {
			add_edge(0,1);
			add_edge(1,0);
			break;
		}
	case 3: {
			// Add edge to the center.
			add_edge(0,2);
			add_edge(2,0);
			// Add 1-2 connection.
			add_edge(1,2);
			add_edge(2,1);
			break;
		}
	case 4: {
			// Add edge to the center.
			add_edge(0,3);
			add_edge(3,0);
			// Add 1-3 and 3-2 connections.
			add_edge(1,3);
			add_edge(3,1);
			add_edge(2,3);
			add_edge(3,2);
			break;
		}
	default: {
			// Add edge to the center.
			add_edge(0,t_size - 1);
			add_edge(t_size - 1,0);
			// Remove connection (previous last)-first.
			remove_edge(t_size - 2,1);
			remove_edge(1,t_size - 2);
			// Add connection (previous last)-(new last).
			add_edge(t_size - 2,t_size - 1);
			add_edge(t_size - 1,t_size - 2);
			// Add connection (new last)-(first).
			add_edge(t_size - 1,1);
			add_edge(1,t_size - 1);
		}
	}
}
示例#23
0
double
Bchart::
parse()
{
  initDenom();
    alreadyPoppedNum = 0;
    
    bool   haveS = false;
    int locTimeout = ruleiCountTimeout_;
    for (;;)
    {
      //check();
      if( ruleiCounts_ > locTimeout || poppedEdgeCount_ > poppedTimeout_)
	{
	  if(printDebug(5)) cerr << "Ran out of time" << endl;
	  break;
	}

      if(get_S() && !haveS)
	{
	  // once we have found a parse, the total edes is set to edges * 3.5;
	  haveS = true;
	  if(printDebug(10)) cerr << "Found S " << poppedEdgeCount_ << endl;
	  poppedEdgeCountAtS_ = poppedEdgeCount_;
	  totEdgeCountAtS_ = ruleiCounts_;
	  int newTime = (int)(ruleiCounts_ * timeFactor);  
	  if(newTime < ruleiCountTimeout_)
	    locTimeout = newTime;
	}
      // We keep track of number of ruleis to decide when time out on parsing.;
      /* get best thing off of keylist */
      Edge* edge = heap->pop(); 
      if (!edge)
	{
	  if(printDebug(5)) cerr << "Nonthing on agenda" << endl;
	  break;
	}
      int stus = edge->status();
      int cD = curDemerits_[edge->start()][edge->loc()];
      if(edge->demerits() < cD - 5 && !haveS)
	{
	  edge->demerits() = cD;
	  edge->setmerit();
	  heap->insert(edge);
	  continue;
	}
      if(isinf(edge->prob()) || isnan(edge->prob()) || isinf(edge->merit())
	 || isnan(edge->merit()))
	{
	  if(printDebug(5)) cerr << "Over or underflow" << endl;
	  break;
	}
      if(alreadyPoppedNum >= 400000)
	{
	  if(printDebug(5)) cerr << "alreadyPopped got too large" << endl;
	  break;
	}
      if(printDebug() > 10)
	{
	  cerr << poppedEdgeCount_ << "\tPop";
	  if(stus == 0) cerr << "< ";
	  else if(stus == 2) cerr << ". ";
	  else cerr << "> ";
	  cerr << *edge << "\t" << edge->prob() << "\t" << edge->merit();
	  cerr << "\t" << ruleiCounts_;
	  cerr << endl;
	}
      poppedEdgeCount_++;
      alreadyPopped[alreadyPoppedNum++] = edge;
      if(!haveS) addToDemerits(edge);
      /* and add it to chart */
      //heap->check();
      switch (stus)
	{
	  case 0 : add_edge(edge, 0); break; //0 => continuing left;
	  case 1 : add_edge(edge, 1); break; //1 => continung right;
	  case 2 : addFinishedEdge(edge);
	}
    }

    /* at this point we are done looking for edges etc. */
    Item           *snode = get_S();
    /* No "S" node means the sentence was unparsable. */
    if (!snode)
      {
	return badParse;
      }
    double          ans = snode->prob();

    if (ans <= 0.0L)
	error("zero probability parse?");
    /*
    ans = -log2(ans);
    if (ans == quiet_nan(0L))
	error("log returned quiet_nan()");
    */
    static double	nat_log_2 = log( 2.0 );
    ans = -log( ans )/ nat_log_2;
    crossEntropy_ = ans;
    return ans;
}
示例#24
0
文件: TMap.cpp 项目: daagar/Mudlet
void TMap::initGraph()
{
    locations.clear();
    g.clear();
    g = mygraph_t(rooms.size()*10);//FIXME
    weightmap = get(edge_weight, g);
    QMapIterator<int, TRoom *> it( rooms );
    int roomCount=0;
    int edgeCount=0;
    while( it.hasNext() )
    {

        it.next();
        int i = it.key();
        if( ! rooms.contains( i ) || rooms[i]->isLocked )
        {
            continue;
        }
        roomCount++;
        location l;
        l.x = rooms[i]->x;
        l.y = rooms[i]->y;
        l.z = rooms[i]->z;
        locations.push_back( l );

        if( rooms[i]->north != -1 && rooms.contains( rooms[i]->north ) && !rooms[rooms[i]->north]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_NORTH ) )
            {
                edgeCount++;
                edge_descriptor e;
                bool inserted;
                tie(e, inserted) = add_edge( i,
                                             rooms[i]->north,
                                             g );
                weightmap[e] = rooms[rooms[i]->north]->weight;

            }
        }
        if( rooms[i]->south != -1 && rooms.contains( rooms[i]->south ) && !rooms[rooms[i]->south]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_SOUTH ) )
            {
                edgeCount++;
                edge_descriptor e;
                bool inserted;
                tie(e, inserted) = add_edge( i,
                                             rooms[i]->south,
                                             g );
                weightmap[e] = rooms[rooms[i]->south]->weight;
            }
        }
        if( rooms[i]->northeast != -1 && rooms.contains( rooms[i]->northeast ) && !rooms[rooms[i]->northeast]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_NORTHEAST ) )
            {
                edgeCount++;
                edge_descriptor e;
                bool inserted;
                tie(e, inserted) = add_edge( i,
                                            rooms[i]->northeast,
                                            g );
                weightmap[e] = rooms[rooms[i]->northeast]->weight;

            }
        }
        if( rooms[i]->east != -1 && rooms.contains( rooms[i]->east ) && !rooms[rooms[i]->east]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_EAST ) )
            {
               edgeCount++;
               edge_descriptor e;
               bool inserted;
               tie(e, inserted) = add_edge( i,
                                            rooms[i]->east,
                                            g );
               weightmap[e] = rooms[rooms[i]->east]->weight;
            }
        }
        if( rooms[i]->west != -1 && rooms.contains( rooms[i]->west ) && !rooms[rooms[i]->west]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_WEST ) )
            {
                edgeCount++;
                edge_descriptor e;
                bool inserted;
                tie(e, inserted) = add_edge( i,
                                             rooms[i]->west,
                                             g );
                weightmap[e] = rooms[rooms[i]->west]->weight;
            }
        }
        if( rooms[i]->southwest != -1 && rooms.contains( rooms[i]->southwest ) && !rooms[rooms[i]->southwest]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_SOUTHWEST ) )
            {
                edgeCount++;
                edge_descriptor e;
                bool inserted;
                tie(e, inserted) = add_edge( i,
                                             rooms[i]->southwest,
                                             g );
                weightmap[e] = rooms[rooms[i]->southwest]->weight;
            }
        }
        if( rooms[i]->southeast != -1 && rooms.contains( rooms[i]->southeast ) && !rooms[rooms[i]->southeast]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_SOUTHEAST ) )
            {
                edgeCount++;
                edge_descriptor e;
                bool inserted;
                tie(e, inserted) = add_edge( i,
                                             rooms[i]->southeast,
                                             g );
                weightmap[e] = rooms[rooms[i]->southeast]->weight;
            }
        }
        if( rooms[i]->northwest != -1 && rooms.contains( rooms[i]->northwest ) && !rooms[rooms[i]->northwest]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_NORTHWEST ) )
            {
                edgeCount++;
                edge_descriptor e;
                bool inserted;
                tie(e, inserted) = add_edge( i,
                                             rooms[i]->northwest,
                                             g );
                weightmap[e] = rooms[rooms[i]->northwest]->weight;
            }
        }
        if( rooms[i]->up != -1 && rooms.contains( rooms[i]->up ) && !rooms[rooms[i]->up]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_UP ) )
            {
                edgeCount++;
                edge_descriptor e;
                bool inserted;
                tie(e, inserted) = add_edge( i,
                                             rooms[i]->up,
                                             g );
                weightmap[e] = rooms[rooms[i]->up]->weight;
            }
        }
        if( rooms[i]->down != -1 && rooms.contains( rooms[i]->down ) && !rooms[rooms[i]->down]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_DOWN ) )
            {
                edgeCount++;
                edge_descriptor e;
                bool inserted;
                tie(e, inserted) = add_edge( i,
                                             rooms[i]->down,
                                             g );
                weightmap[e] = rooms[rooms[i]->down]->weight;
            }
        }
        if( rooms[i]->in != -1 && rooms.contains( rooms[i]->in ) && !rooms[rooms[i]->in]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_IN ) )
            {
                edgeCount++;
                edge_descriptor e;
                bool inserted;
                tie(e, inserted) = add_edge( i,
                                             rooms[i]->in,
                                             g );
                weightmap[e] = rooms[rooms[i]->in]->weight;
            }
        }
        if( rooms[i]->out != -1 && rooms.contains( rooms[i]->out ) && !rooms[rooms[i]->out]->isLocked )
        {
            if( ! rooms[i]->hasExitLock( DIR_OUT ) )
            {
                 edgeCount++;
                 edge_descriptor e;
                 bool inserted;
                 tie(e, inserted) = add_edge( i,
                                              rooms[i]->out,
                                              g );
                 weightmap[e] = rooms[rooms[i]->out]->weight;
            }
        }
        if( rooms[i]->other.size() > 0 )
        {
            QMapIterator<int, QString> it( rooms[i]->other );
            while( it.hasNext() )
            {
                it.next();
                int _id = it.key();
                if( ! rooms[i]->hasSpecialExitLock( _id, it.value() ) )
                {
                    edgeCount++;
                    edge_descriptor e;
                    bool inserted;
                    tie(e, inserted) = add_edge( i,
                                                 _id,
                                                 g );
                    weightmap[e] = rooms[_id]->weight;
                }
            }
        }
    }
    mMapGraphNeedsUpdate = false;
}
示例#25
0
Item*
Bchart::
edgesFromTree(InputTree* tree)
{
  int b, b0;
  b0 = tree->num();
  const Term* trm = Term::get(tree->term());
  assert(trm);
  //cerr << "ARI " << *trm << " " << b0 << endl;
  if(printDebug() > 1005)
    cerr << "EFIE " << trm->name() << " " << b0 << endl;
  /* If this is a terminal node, the rhs will be a word; otherwise it
     will be a rule expansion consisting of several Item s.
   */
  if(trm->terminal_p())
    {
      ECString tmpW1 = tree->word();
      char chars[128];
      ECString tmpW = toLower(tmpW1.c_str(), chars);
      
      int wInt = wtoInt(tmpW);
      Item* lhs = add_item(b0, trm, tree->start());
      lhs->start() = tree->start();
      lhs->finish() = tree->finish();
      Item* rhs = add_item2(b0, trm, wInt,tmpW);
      rhs->finish() = tree->finish();
      rhs->start() = tree->start();
      if(!lhs && !rhs)
	{
	  return NULL;
	}

      Items subItems;
      subItems.push_back(stops[tree->start()]);
      subItems.push_back(rhs);
      subItems.push_back(stops[tree->finish()]);
      Edge* edg = add_edge(lhs, subItems);
      if(!edg)
	{
	  return NULL;
	}
      edg->prob() = pHst(wInt,trm->toInt());
      edg->num() = b0;
      if(printDebug() > 5)
	cerr << "LHS " << *lhs << " " << tmpW  << edg->prob() << endl;
	  
      return lhs;
    }
  else
    {
      Item* lhs = add_item(b0, trm, -1);
      lhs->start() = tree->start();
      lhs->finish() = tree->finish();
      assert(lhs);
      Items subItems;
      subItems.push_back(stops[tree->start()]);
      InputTreesIter iti = tree->subTrees().begin();
      for( ; iti != tree->subTrees().end() ; iti++)
	{
	  InputTree* stree = (*iti);
	  cerr << "WBA "<< stree->term() << *stree   << endl;
	  Item* itm = edgesFromTree(stree);
	  if(!itm)
	    {
	      return NULL;
	    }
	  subItems.push_back(itm);
	}
      subItems.push_back(stops[tree->finish()]);
      Edge* edg = add_edge(lhs, subItems);
      if(!edg)
	{
	  return false;
	}
      edg->num() = b0;
      assignRProb(edg);
      if (printDebug() > 5)
	{
	  cerr << "Saw edge " << *edg << ": p=" << edg->prob() << endl;
	}
      //cerr << "endeFE " << *edg << endl;
      return lhs;
      rPendFactor();
    }
}
示例#26
0
void clustered_ba::connect(const vertices_size_type &idx)
{
	pagmo_assert(get_number_of_vertices() > 0);
	const vertices_size_type prev_size = get_number_of_vertices() - 1;
	if (prev_size < m_m0) {
		// If we had not built the initial m0 nodes, do it.
		// We want to connect the newcomer island with high probability, and make sure that
		// at least one connection exists (otherwise the island stays isolated).
		// NOTE: is it worth to make it a user-tunable parameter?
                const double prob = 0.0;
		// Flag indicating if at least 1 connection was added.
		bool connection_added = false;
		// Main loop.
		for (std::pair<v_iterator,v_iterator> vertices = get_vertices(); vertices.first != vertices.second; ++vertices.first) {
			// Do not consider the new vertex itself.
			if (*vertices.first != idx) {
				if (m_drng() < prob) {
					connection_added = true;
					// Add the connections
					add_edge(*vertices.first,idx);
					add_edge(idx,*vertices.first);
				}
			}
		}
		// If no connections were established and this is not the first island being inserted,
		// establish at least one connection with a random island other than n.
		if ((!connection_added) && (prev_size != 0)) {
			// Get a random vertex index between 0 and n_vertices - 1. Keep on repeating the procedure if by
			// chance we end up on idx again.
			boost::uniform_int<vertices_size_type> uni_int(0,get_number_of_vertices() - 1);
			vertices_size_type rnd;
                        do {
				rnd = uni_int(m_urng);
			} while (rnd == idx);
			// Add connections to the random vertex.
			add_edge(rnd,idx);
			add_edge(idx,rnd);
		}
	} else {
                // Now we need to add j edges, choosing the nodes with a probability
		// proportional to their number of connections. We keep track of the
		// connection established in order to avoid connecting twice to the same
		// node.
                // j is a random integer in the range 1 to m.
                boost::uniform_int<edges_size_type> uni_int2(1,m_m);
		std::size_t i = 0;
                std::size_t j = uni_int2(m_urng);
		std::pair<v_iterator,v_iterator> vertices;
		std::pair<a_iterator,a_iterator> adj_vertices;
                while (i < j) {
                        // Let's find the current total number of edges.
                        const edges_size_type n_edges = get_number_of_edges();
                        pagmo_assert(n_edges > 0);
                        boost::uniform_int<edges_size_type> uni_int(0,n_edges - 1 - i);
                        // Here we choose a random number between 0 and n_edges - 1 - i.
                        const edges_size_type rn = uni_int(m_urng);
                        edges_size_type n = 0;
			// Iterate over all vertices and accumulate the number of edges for each of them. Stop when the accumulated number of edges is greater
			// than rn. This is equivalent to giving a chance of connection to vertex v directly proportional to the number of edges departing from v.
			// You can think of this process as selecting a random edge among all the existing edges and connecting to the vertex from which the
			// selected edge departs.
			vertices = get_vertices();
			for (; vertices.first != vertices.second; ++vertices.first) {
				// Do not consider it_n.
				if (*vertices.first != idx) {
					adj_vertices = get_adjacent_vertices(*vertices.first);
					n += boost::numeric_cast<edges_size_type>(std::distance(adj_vertices.first,adj_vertices.second));
					if (n > rn) {
						break;
					}
				}
			}
			pagmo_assert(vertices.first != vertices.second);
			// If the candidate was not already connected, then add it.
			if (!are_adjacent(idx,*vertices.first)) {
                                // Connect to nodes that are already adjacent to idx with probability p.
                                // This step increases clustering in the network.
                                adj_vertices = get_adjacent_vertices(idx);
                                for(;adj_vertices.first != adj_vertices.second; ++adj_vertices.first) {
                                    if(m_drng() < m_p && *adj_vertices.first != *vertices.first && !are_adjacent(*adj_vertices.first,*vertices.first)) {
                                        add_edge(*adj_vertices.first, *vertices.first);
                                        add_edge(*vertices.first, *adj_vertices.first);
                                    }
                                }
                                // Connect to idx
				add_edge(*vertices.first,idx);
				add_edge(idx,*vertices.first);
				++i;
			}
		}
	}
}
示例#27
0
/*
	Converts arcs added by 'add_edge()' calls
	to a forward star graph representation.

	Linear time algorithm.
	No or little additional memory is allocated
	during this process
	(it may be necessary to allocate additional
	arc blocks, since arcs corresponding to the
	same node must be contiguous, i.e. be in one
	arc block.)
*/
void Graph::prepare_graph()
{
	node *i;
	arc_for_block *ab_for, *ab_for_first;
	arc_rev_block *ab_rev, *ab_rev_first, *ab_rev_scan;
	arc_forward *a_for;
	arc_reverse *a_rev, *a_rev_scan, a_rev_tmp;
	node_block *nb;
	bool for_flag = false, rev_flag = false;
	intptr_t k;

	if (!arc_rev_block_first)
	{
		node_id from = add_node(), to = add_node();
		add_edge(from, to, 1, 0);
	}

	/* FIRST STAGE */
	a_rev_tmp.sister = NULL;
	for (a_rev=arc_rev_block_first->current; a_rev<&arc_rev_block_first->arcs_rev[ARC_BLOCK_SIZE]; a_rev++)
	{
		a_rev -> sister = NULL;
	}

	ab_for = ab_for_first = arc_for_block_first;
	ab_rev = ab_rev_first = ab_rev_scan = arc_rev_block_first;
	a_for = &ab_for->arcs_for[0];
	a_rev = a_rev_scan = &ab_rev->arcs_rev[0];

	for (nb=node_block_first; nb; nb=nb->next)
	{
		for (i=&nb->nodes[0]; i<nb->current; i++)
		{
			/* outgoing arcs */
			k = (intptr_t) i -> first_out;
			if (a_for + k > &ab_for->arcs_for[ARC_BLOCK_SIZE])
			{
				if (k > ARC_BLOCK_SIZE) { if (error_function) (*error_function)("# of arcs per node exceeds block size!"); exit(1); }
				if (for_flag) ab_for = NULL;
				else          { ab_for = ab_for -> next; ab_rev_scan = ab_rev_scan -> next; }
				if (ab_for == NULL)
				{
					arc_for_block *next = arc_for_block_first;
					char *ptr = new char[sizeof(arc_for_block)+1];
					if (!ptr) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
					if ((intptr_t)ptr & 1) arc_for_block_first = (arc_for_block *) (ptr + 1);
					else              arc_for_block_first = (arc_for_block *) ptr;
					arc_for_block_first -> start = ptr;
					arc_for_block_first -> current = & ( arc_for_block_first -> arcs_for[0] );
					arc_for_block_first -> next = next;
					ab_for = arc_for_block_first;
					for_flag = true;
				}
				else a_rev_scan = &ab_rev_scan->arcs_rev[0];
				a_for = &ab_for->arcs_for[0];
			}
			if (ab_rev_scan)
			{
				a_rev_scan += k;
				i -> parent = (arc_forward *) a_rev_scan;
			}
			else i -> parent = (arc_forward *) &a_rev_tmp;
			a_for += k;
			i -> first_out = a_for;
			ab_for -> last_node = i;

			/* incoming arcs */
			k = (intptr_t) i -> first_in;
			if (a_rev + k > &ab_rev->arcs_rev[ARC_BLOCK_SIZE])
			{
				if (k > ARC_BLOCK_SIZE) { if (error_function) (*error_function)("# of arcs per node exceeds block size!"); exit(1); }
				if (rev_flag) ab_rev = NULL;
				else          ab_rev = ab_rev -> next;
				if (ab_rev == NULL)
				{
					arc_rev_block *next = arc_rev_block_first;
					char *ptr = new char[sizeof(arc_rev_block)+1];
					if (!ptr) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
					if ((intptr_t)ptr & 1) arc_rev_block_first = (arc_rev_block *) (ptr + 1);
					else              arc_rev_block_first = (arc_rev_block *) ptr;
					arc_rev_block_first -> start = ptr;
					arc_rev_block_first -> current = & ( arc_rev_block_first -> arcs_rev[0] );
					arc_rev_block_first -> next = next;
					ab_rev = arc_rev_block_first;
					rev_flag = true;
				}
				a_rev = &ab_rev->arcs_rev[0];
			}
			a_rev += k;
			i -> first_in = a_rev;
			ab_rev -> last_node = i;
		}
		/* i is the last node in block */
		i -> first_out = a_for;
		i -> first_in  = a_rev;
	}

	/* SECOND STAGE */
	for (ab_for=arc_for_block_first; ab_for; ab_for=ab_for->next)
	{
		ab_for -> current = ab_for -> last_node -> first_out;
	}

	for ( ab_for=ab_for_first, ab_rev=ab_rev_first;
		  ab_for;
		  ab_for=ab_for->next, ab_rev=ab_rev->next )
	for ( a_for=&ab_for->arcs_for[0], a_rev=&ab_rev->arcs_rev[0];
		  a_for<&ab_for->arcs_for[ARC_BLOCK_SIZE];
		  a_for++, a_rev++ )
	{
		arc_forward *af;
		arc_reverse *ar;
		node *from;
		int shift = 0, shift_new;
		captype r_cap, r_rev_cap, r_cap_new, r_rev_cap_new;

		if (!(from=(node *)(a_rev->sister))) continue;
		af = a_for;
		ar = a_rev;

		do
		{
			ar -> sister = NULL;

			shift_new = ((char *)(af->shift)) - (char *)from;
			r_cap_new = af -> r_cap;
			r_rev_cap_new = af -> r_rev_cap;
			if (shift)
			{
				af -> shift = shift;
				af -> r_cap = r_cap;
				af -> r_rev_cap = r_rev_cap;
			}
			shift = shift_new;
			r_cap = r_cap_new;
			r_rev_cap = r_rev_cap_new;

			af = -- from -> first_out;
			if ((arc_reverse *)(from->parent) != &a_rev_tmp)
			{
				from -> parent = (arc_forward *)(((arc_reverse *)(from -> parent)) - 1);
				ar = (arc_reverse *)(from -> parent);
			}
		} while (from=(node *)(ar->sister));

		af -> shift = shift;
		af -> r_cap = r_cap;
		af -> r_rev_cap = r_rev_cap;
	}

	for (ab_for=arc_for_block_first; ab_for; ab_for=ab_for->next)
	{
		i = ab_for -> last_node;
		a_for = i -> first_out;
		ab_for -> current -> shift     = a_for -> shift;
		ab_for -> current -> r_cap     = a_for -> r_cap;
		ab_for -> current -> r_rev_cap = a_for -> r_rev_cap;
		a_for -> shift = (intptr_t) (ab_for -> current + 1);
		i -> first_out = (arc_forward *) (((char *)a_for) - 1);
	}

	/* THIRD STAGE */
	for (ab_rev=arc_rev_block_first; ab_rev; ab_rev=ab_rev->next)
	{
		ab_rev -> current = ab_rev -> last_node -> first_in;
	}

	for (nb=node_block_first; nb; nb=nb->next)
	for (i=&nb->nodes[0]; i<nb->current; i++)
	{
		arc_forward *a_for_first, *a_for_last;

		a_for_first = i -> first_out;
		if (IS_ODD(a_for_first))
		{
			a_for_first = (arc_forward *) (((char *)a_for_first) + 1);
			a_for_last = (arc_forward *) ((a_for_first ++) -> shift);
		}
		else a_for_last = (i + 1) -> first_out;

		for (a_for=a_for_first; a_for<a_for_last; a_for++)
		{
			node *to = NEIGHBOR_NODE(i, a_for -> shift);
			a_rev = -- to -> first_in;
			a_rev -> sister = a_for;
		}
	}

	for (ab_rev=arc_rev_block_first; ab_rev; ab_rev=ab_rev->next)
	{
		i = ab_rev -> last_node;
		a_rev = i -> first_in;
		ab_rev -> current -> sister = a_rev -> sister;
		a_rev -> sister = (arc_forward *) (ab_rev -> current + 1);
		i -> first_in = (arc_reverse *) (((char *)a_rev) - 1);
	}
}
示例#28
0
文件: network.cpp 项目: gandalfvn/EOH
void NETWORK::load_network( std::string &_input_file, bool _weighted, std::string &_output, int _size_limit )
{
  // message file
  std::string msg_file = _output + ".msg";
  FILE *pMsg = NULL;

  // reset network
  for(int i=0; i<Order; i++)
    delete Nodes[i];
  Nodes.clear();
  Order = 0;
  Size = 0;

  // read edges
  FILE_HANDLER f( _input_file.c_str(), "r" );
  int edges = f.rows();
  char line[1024] = {""};
  std::map<std::string, int> hash_table;
  int source, target;
  double weight;
  char source_label[128] = {""};
  char target_label[128] = {""};
  int source_id = 0;
  int target_id = 0;
  int columns;
  for(int n=0; n<edges; n++)
  {
    f.get_text_line( line, sizeof(line) );
    // check if line is valid (two or threee columns)
    weight = 1.0;
    columns = sscanf( line, "%s %s %lf", source_label, target_label, &weight );
    if( (!_weighted && columns < 2) || (_weighted && columns != 3) )
    {
      pMsg = fopen( msg_file.c_str(), "w" );
      fprintf( pMsg, "Error\nMissing column in line %i.", n+1 );
      fclose( pMsg );
      exit( 0 );
    }
    std::pair< std::map<std::string, int>::iterator, bool> added;

    // source node
    added = hash_table.insert( std::pair<std::string, int>(std::string(source_label), (int)Nodes.size()) );
    if( added.second )
    {
      source_id = (int)Nodes.size();
      add_node( source_label );
    }
    else
      source_id = added.first->second;

    // target node
    added = hash_table.insert( std::pair<std::string, int>(std::string(target_label), (int)Nodes.size()) );
    if( added.second )
    {
      target_id = (int)Nodes.size();
      add_node( target_label );
    }
    else
      target_id = added.first->second;

    // add edge
    if( is_there_edge(source_id, target_id) )
    {
      weight += get_edge_weight( source_id, target_id );
      remove_edge(source_id, target_id);
      add_edge( source_id, target_id, weight );
    }
    else
      add_edge( source_id, target_id, weight );
  }

  // if size limitazion is on, check network size
  if( _size_limit != 0 && Order > _size_limit )
  {
    pMsg = fopen( msg_file.c_str(), "w" );
    fprintf( pMsg, "Error\nNetwork is too large." );
    fclose( pMsg );
    exit(0);
  }

  // normalize weights
  /*int deg;
  double max_weight = Nodes[0]->outweight(0);
  for(int i=0; i<Order; i++)
  {
    deg = Nodes[i]->outdegree();
    for(int j=0; j<deg; j++)
    {
      if( Nodes[i]->outweight(j) > max_weight )
        max_weight = Nodes[i]->outweight(j);
    }
  }
  for(int i=0; i<Order; i++)
  {
    deg = Nodes[i]->outdegree();
    for(int j=0; j<deg; j++)
      Nodes[i]->setOutWeight( j, Nodes[i]->outweight(j)/max_weight );
  }*/

  // print network properties
  //pMsg = fopen( msg_file.c_str(), "w" );
  //fprintf( pMsg, "Success\n%i\n%i", Order, Size );
  //fclose( pMsg );
}
示例#29
0
int
ImagingOutlineTransform(ImagingOutline outline, double a[6])
{
    Edge *eIn;
    Edge *eOut;
    int i, n;
    int x0, y0, x1, y1;
    int X0, Y0, X1, Y1;

    double a0 = a[0]; double a1 = a[1]; double a2 = a[2];
    double a3 = a[3]; double a4 = a[4]; double a5 = a[5];

    eIn = outline->edges;
    n = outline->count;

    /* FIXME: ugly! */
    outline->edges = NULL;
    outline->count = outline->size = 0;

    eOut = allocate(outline, n);
    if (!eOut) {
        outline->edges = eIn;
        outline->count = outline->size = n;
        ImagingError_MemoryError();
        return -1;
    }

    for (i = 0; i < n; i++) {

        x0 = eIn->x0;
        y0 = eIn->y0;

        /* FIXME: ouch! */
        if (eIn->x0 == eIn->xmin)
            x1 = eIn->xmax;
        else
            x1 = eIn->xmin;
        if (eIn->y0 == eIn->ymin)
            y1 = eIn->ymax;
        else
            y1 = eIn->ymin;

        /* full moon tonight!  if this doesn't work, you may need to
           upgrade your compiler (make sure you have the right service
           pack) */

        X0 = (int) (a0*x0 + a1*y0 + a2);
        Y0 = (int) (a3*x0 + a4*y0 + a5);
        X1 = (int) (a0*x1 + a1*y1 + a2);
        Y1 = (int) (a3*x1 + a4*y1 + a5);

        add_edge(eOut, X0, Y0, X1, Y1);

        eIn++;
        eOut++;

    }

    free(eIn);

    return 0;
}
示例#30
0
/*======== void my_main() ==========
  Inputs:
  Returns: 

  This is the main engine of the interpreter, it should
  handle most of the commadns in mdl.

  If frames is not present in the source (and therefore 
  num_frames is 1, then process_knobs should be called.

  If frames is present, the enitre op array must be
  applied frames time. At the end of each frame iteration
  save the current screen to a file named the
  provided basename plus a numeric string such that the
  files will be listed in order, then clear the screen and
  reset any other data structures that need it.

  Important note: you cannot just name your files in 
  regular sequence, like pic0, pic1, pic2, pic3... if that
  is done, then pic1, pic10, pic11... will come before pic2
  and so on. In order to keep things clear, add leading 0s
  to the numeric portion of the name. If you use sprintf, 
  you can use "%0xd" for this purpose. It will add at most
  x 0s in front of a number, if needed, so if used correctly,
  and x = 4, you would get numbers like 0001, 0002, 0011,
  0487

  05/17/12 09:41:35
  jdyrlandweaver
  ====================*/
void my_main( int polygons ) {

  int i, f, j;
  double step;
  double xval, yval, zval, knob_value;
  struct matrix *transform;
  struct matrix *tmp;
  struct stack *s;
  screen t;
  color g;

  struct vary_node **knobs;
  struct vary_node *vn;
  char frame_name[128];
  
  num_frames = 1;
  step = 5;
 
  g.red = 0;
  g.green = 255;
  g.blue = 255;

  first_pass();
  if (num_frames>1){
    knobs = second_pass();
  }

  int cur_frame;
  char frame_num_string[4];
  
  for (cur_frame=0;cur_frame<num_frames-1;cur_frame++){
    strcpy(frame_name,"animation_frames/");
    strcat(frame_name,name);
    sprintf(frame_num_string,"%03d",cur_frame+1);
    strcat(frame_name,frame_num_string);

    s = new_stack();
    tmp = new_matrix(4,0);
    for (i=0;i<lastop;i++) {
      
      switch (op[i].opcode) {

      case SPHERE:
	add_sphere( tmp,op[i].op.sphere.d[0], //cx
		    op[i].op.sphere.d[1],  //cy
		    op[i].op.sphere.d[2],  //cz
		    op[i].op.sphere.r,
		    step);
	//apply the current top origin
	matrix_mult( s->data[ s->top ], tmp );
	draw_polygons( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case TORUS:
	add_torus( tmp, op[i].op.torus.d[0], //cx
		   op[i].op.torus.d[1],      //cy
		   op[i].op.torus.d[2],      //cz
		   op[i].op.torus.r0,
		   op[i].op.torus.r1,
		   step);
	matrix_mult( s->data[ s->top ], tmp );
	draw_polygons( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case BOX:
	add_box( tmp, op[i].op.box.d0[0],
		 op[i].op.box.d0[1],
		 op[i].op.box.d0[2],
		 op[i].op.box.d1[0],
		 op[i].op.box.d1[1],
		 op[i].op.box.d1[2]);
	matrix_mult( s->data[ s->top ], tmp );
	draw_polygons( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case LINE:
	add_edge( tmp, op[i].op.line.p0[0],
		  op[i].op.line.p0[1],
		  op[i].op.line.p0[1],
		  op[i].op.line.p1[0],
		  op[i].op.line.p1[1],
		  op[i].op.line.p1[1]);
	draw_lines( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case SET:
	vn = knobs[cur_frame];
	while (vn != NULL){
	  if (strcmp(vn->name,op[i].op.set.p->name)==0){
	    vn->value = op[i].op.set.val;
	  }
	  vn = vn->next;
	}
	break;

      case SETKNOBS:
	vn = knobs[cur_frame];
	while (vn != NULL){
	  vn->value = op[i].op.setknobs.value;
	  vn = vn->next;
	}
	break;

      case MOVE:
	//get the factors
	xval = op[i].op.move.d[0];
	yval = op[i].op.move.d[1];
	zval = op[i].op.move.d[2];
	if (op[i].op.move.p != NULL){
	  vn = knobs[cur_frame];
	  while (vn != NULL){
	    if (strcmp(vn->name,op[i].op.scale.p->name)==0){
	      xval*=vn->value;
	      yval*=vn->value;
	      zval*=vn->value;
	    }
	    vn = vn->next;
	  }
	}
	transform = make_translate( xval, yval, zval );
	//multiply by the existing origin
	matrix_mult( s->data[ s->top ], transform );
	//put the new matrix on the top
	copy_matrix( transform, s->data[ s->top ] );
	free_matrix( transform );

	break;

      case SCALE:

	xval = op[i].op.scale.d[0];
	yval = op[i].op.scale.d[1];
	zval = op[i].op.scale.d[2];

	if (op[i].op.scale.p != NULL){
	  vn = knobs[cur_frame];
	  while (vn != NULL){
	    if (strcmp(vn->name,op[i].op.scale.p->name)==0){
	      xval*=vn->value;
	      yval*=vn->value;
	      zval*=vn->value;
	    }
	    vn = vn->next;
	  }
	}
	transform = make_scale( xval, yval, zval );
	matrix_mult( s->data[ s->top ], transform );
	//put the new matrix on the top
	copy_matrix( transform, s->data[ s->top ] );
	free_matrix( transform );
	break;
      case ROTATE:
	xval = op[i].op.rotate.degrees * ( M_PI / 180 );
	if (op[i].op.scale.p == NULL){
	  vn = knobs[cur_frame];
	  while (vn != NULL){
	    if (strcmp(vn->name,op[i].op.rotate.p->name)==0){
	      xval*=vn->value;
	    }
	    vn = vn->next;
	  }
	}
	//get the axis
	if ( op[i].op.rotate.axis == 0 ) 
	  transform = make_rotX( xval );
	else if ( op[i].op.rotate.axis == 1 ) 
	  transform = make_rotY( xval );
	else if ( op[i].op.rotate.axis == 2 ) 
	  transform = make_rotZ( xval );
	matrix_mult( s->data[ s->top ], transform );
	//put the new matrix on the top
	copy_matrix( transform, s->data[ s->top ] );
	free_matrix( transform );
	break;
      case PUSH:
	push( s );
	break;
      case POP:
	pop( s );
	break;
      case SAVE:
	save_extension( t, op[i].op.save.p->name );
	break;
      case DISPLAY:
	display( t );
	break;
      }
    }
    if (num_frames > 1){
      save_extension( t, frame_name );
      clear_screen(t);
      free_stack( s );
      free_matrix( tmp );
    }
  }
}