Exemplo n.º 1
0
void
vh_scanner_path_add (scanner_t *scanner, const char *location, int recursive)
{
  struct path_s *path;

  vh_log (VALHALLA_MSG_VERBOSE, __FUNCTION__);

  if (!scanner)
    return;

  /* check if the path is already in the list */
  for (path = scanner->paths; path; path = path->next)
    if (!strcmp (path->location, location))
      return;

  if (!scanner->paths)
  {
    scanner->paths = path_new (location, recursive);
    return;
  }

  for (path = scanner->paths; path->next; path = path->next)
    ;

  path->next = path_new (location, recursive);
}
Exemplo n.º 2
0
/**
 * Return a newly allocated individual path to reach a peer from the local peer,
 * according to the path tree of some tunnel.
 *
 * @param t Tunnel from which to read the path tree.
 * @param peer Short ID of the destination peer to whom we want a path.
 *
 * @return A newly allocated individual path to reach the destination peer.
 *         Path must be destroyed afterwards.
 */
struct MeshPeerPath *
tree_get_path_to_peer (struct MeshTunnelTree *t, GNUNET_PEER_Id peer)
{
  struct MeshTunnelTreeNode *n;
  struct MeshPeerPath *p;

  n = tree_find_peer (t, peer);
  if (NULL == n)
  {
    GNUNET_break (0);
    return NULL;
  }
  p = path_new (0);

  /* Building the path (inverted!) */
  while (n->peer != 1)
  {
    GNUNET_array_append (p->peers, p->length, n->peer);
    GNUNET_PEER_change_rc (n->peer, 1);
    n = n->parent;
    if (NULL == n)
    {
      GNUNET_break (0);
      path_destroy (p);
      return NULL;
    }
  }
  GNUNET_array_append (p->peers, p->length, 1);
  GNUNET_PEER_change_rc (1, 1);

  path_invert (p);

  return p;
}
Exemplo n.º 3
0
PyObject*
PyPath_Create(PyObject* self, PyObject* args)
{
    PyObject* data;
    int count;
    double *xy;

    if (PyArg_ParseTuple(args, "i:Path", &count)) {

        /* number of vertices */
        xy = alloc_array(count);
        if (!xy)
            return NULL;

    } else {

        /* sequence or other path */
        PyErr_Clear();
        if (!PyArg_ParseTuple(args, "O", &data))
            return NULL;

        count = PyPath_Flatten(data, &xy);
        if (count < 0)
            return NULL;
    }

    return (PyObject*) path_new(count, xy, 0);
}
Exemplo n.º 4
0
void perfect_path_print_paths(char *filename, int max_length, int singleton_length,
							  boolean with_coverages, dBGraph * db_graph)
{
	FILE * fout = NULL;
	FILE * fout_cov = NULL;
	int i;
	fout = fopen(filename, "w");
	
	if (with_coverages) {
		char filename_cov[strlen(filename) + 10];
		sprintf(filename_cov, "%s_cov", filename);
		fout_cov = fopen(filename_cov, "w");
	}
	limit = max_length;
	
	//Path *path = path_new(max_length, db_graph->kmer_size);
	//path->id=-1;
    
    perfect_path_print_supernodes_args ** args = calloc(db_graph->number_of_threads, sizeof(perfect_path_print_supernodes_args * ));
    
    for (i = 0; i < db_graph->number_of_threads; i++) {
        args[i] = calloc(1, sizeof(perfect_path_print_supernodes_args)) ;
        args[i]->db_graph = db_graph;
        args[i]->path = path_new(max_length, db_graph->kmer_size);
        args[i]->fout = fout;
        args[i]->fout_cov = fout_cov;//TODO: Make the printing function "thread safe"
    }
  
	//buffers = path_array_new(2);
	
	
	double graph_cov = db_graph_get_average_coverage(db_graph);
    log_and_screen_printf("Average coverage: %5.2f \n", graph_cov);
    
    
	
	hash_table_traverse_with_args(&print_supernode, (void ** ) args ,db_graph);
	
	
	log_and_screen_printf("%'d nodes visited [%'qd singletons, %'qd repetitive]\n", args[0]->count_nodes, args[0]->count_sing, args[0]->count_rep);//TODO: At some point we can make this multithreading
	path_counts_print_and_log(&args[0]->counts);
    
    
	for (i = 0; i < db_graph->number_of_threads; i++) {
        free(args[i]);
        path_destroy(args[i]->path);
    }
    free(args);
	
	
	fclose(fout);
	if (with_coverages) {
		fclose(fout_cov);
	}
}
Exemplo n.º 5
0
static void
mu_container_path_foreach (MuContainer *c, MuContainerPathForeachFunc func,
			gpointer user_data)
{
	Path *path;

	path = path_new (100);

	mu_container_path_foreach_real (c, 0, path, func, user_data);

	path_destroy (path);
}
Exemplo n.º 6
0
/**
 * Duplicate a path, incrementing short peer's rc.
 *
 * @param path The path to duplicate.
 */
struct MeshPeerPath *
path_duplicate (struct MeshPeerPath *path)
{
  struct MeshPeerPath *aux;
  unsigned int i;

  aux = path_new (path->length);
  memcpy (aux->peers, path->peers, path->length * sizeof (GNUNET_PEER_Id));
  for (i = 0; i < path->length; i++)
    GNUNET_PEER_change_rc (path->peers[i], 1);
  return aux;
}
Exemplo n.º 7
0
/**
 * Builds a path from a PeerIdentity array.
 *
 * @param peers PeerIdentity array.
 * @param size Size of the @c peers array.
 * @param myid ID of local peer, to find @c own_pos.
 * @param own_pos Output parameter: own position in the path.
 *
 * @return Fixed and shortened path.
 */
struct CadetPeerPath *
path_build_from_peer_ids (struct GNUNET_PeerIdentity *peers,
                          unsigned int size,
                          GNUNET_PEER_Id myid,
                          unsigned int *own_pos)
{
  struct CadetPeerPath *path;
  GNUNET_PEER_Id shortid;
  unsigned int i;
  unsigned int j;
  unsigned int offset;

  /* Create path */
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
  path = path_new (size);
  *own_pos = 0;
  offset = 0;
  for (i = 0; i < size; i++)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  - %u: taking %s\n",
         i, GNUNET_i2s (&peers[i]));
    shortid = GNUNET_PEER_intern (&peers[i]);

    /* Check for loops / duplicates */
    for (j = 0; j < i - offset; j++)
    {
      if (path->peers[j] == shortid)
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG, "    already exists at pos %u\n", j);
        offset = i - j;
        LOG (GNUNET_ERROR_TYPE_DEBUG, "    offset now %u\n", offset);
        GNUNET_PEER_change_rc (shortid, -1);
      }
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG, "    storing at %u\n", i - offset);
    path->peers[i - offset] = shortid;
    if (path->peers[i - offset] == myid)
      *own_pos = i - offset;
  }
  path->length -= offset;

  if (path->peers[*own_pos] != myid)
  {
    /* create path: self not found in path through self */
    GNUNET_break_op (0);
    path_destroy (path);
    return NULL;
  }

  return path;
}
Exemplo n.º 8
0
int main(void)
{
  switch_t s;
  chan_t c;
  packet_t p;
  path_t in;
  int sock;

  crypt_init();
  s = switch_new(0);

  if(util_loadjson(s) != 0 || (sock = util_server(0,1000)) <= 0)
  {
    printf("failed to startup %s or %s\n", strerror(errno), crypt_err());
    return -1;
  }

  printf("loaded hashname %s\n",s->id->hexname);

  // create/send a ping packet  
  c = chan_new(s, bucket_get(s->seeds, 0), "link", 0);
  p = chan_packet(c);
  chan_send(c, p);
  util_sendall(s,sock);

  in = path_new("ipv4");
  while(util_readone(s, sock, in) == 0)
  {
    switch_loop(s);

    while((c = switch_pop(s)))
    {
      printf("channel active %d %s %s\n",c->state,c->hexid,c->to->hexname);
      if(util_cmp(c->type,"connect") == 0) ext_connect(c);
      if(util_cmp(c->type,"link") == 0) ext_link(c);
      if(util_cmp(c->type,"path") == 0) ext_path(c);
      while((p = chan_pop(c)))
      {
        printf("unhandled channel packet %.*s\n", p->json_len, p->json);      
        packet_free(p);
      }
      if(c->state == ENDED) chan_free(c);
    }

    util_sendall(s,sock);
  }

  perror("exiting");
  return 0;
}
Exemplo n.º 9
0
int main (int argc, char **argv)
{
  point **ptoarr = malloc(4 * sizeof(point *));
  *ptoarr = point_new(0.0, 0.0);
  *(ptoarr + 1) = point_new(1.0, 0.0);
  *(ptoarr + 2) = point_new(0.0, 0.0);
  ptoarr[3] = point_new(1.0, 0.0);
  path *p = path_new(ptoarr, 4);
  path_show(p);
  printf("The distance is %lf\n", path_length(p));
  path_append(p, point_new(2.0, 2.0));
  path_show(p);
  return 0;
}
Exemplo n.º 10
0
static PyObject*
path_getslice(PyPathObject* self, int ilow, int ihigh)
{
    /* adjust arguments */
    if (ilow < 0)
        ilow = 0;
    else if (ilow >= self->count)
        ilow = self->count;
    if (ihigh < 0)
        ihigh = 0;
    if (ihigh < ilow)
        ihigh = ilow;
    else if (ihigh > self->count)
        ihigh = self->count;
    
    return (PyObject*) path_new(ihigh - ilow, self->xy + ilow * 2, 1);
}
Exemplo n.º 11
0
static Path *
screen_saver_floater_create_path_to_bubble_up (ScreenSaver        *screen_saver,
        ScreenSaverFloater *floater,
        gdouble             duration)
{
    Point start_position, end_position, start_control_point, end_control_point;

    start_position = floater->position;
    end_position.x = start_position.x;
    end_position.y = screen_saver->canvas_rectangle.top_left_point.y - FLOATER_MAX_SIZE;
    start_control_point.x = .5 * start_position.x;
    start_control_point.y = .5 * start_position.y;
    end_control_point.x = 1.5 * end_position.x;
    end_control_point.y = .5 * end_position.y;

    return path_new (&start_position, &start_control_point, &end_control_point,
                     &end_position, duration);
}
Exemplo n.º 12
0
void dinic(Net net, output * out_p, int flags){
	uint an_flow = 0, x = 0, r = 0, t = 1, i = 0;
	bool end = false;
	output out = *out_p;
	path p = NULL;
	nodes_list nodes = NULL;

	nodes = net_get_nodes(net);
	out_set_net(out, net);

	for(i = 0; !end ; i++) {

		an_flow = 0;

		nodes_aux_reset(nodes);
		net_aux_new(net);

		end = is_t_in_an(nodes);
		
		if (!end) {
			
			while(true) {

				x = advance(net); /* ADVANCE */

				if (x == t) { /* AUGMENT */
					r = residual_capacity(net); 
					an_flow += r;
					p = path_new();
					augment(net, p, r);
					out_add_path(out, p);
				} 
				else break;
			}

			if((flags & VERBOSE)){
				out_print_paths(out, i+1);
			}
		}

		out_path_destroy(out);
	}
	*out_p = out;
}
Exemplo n.º 13
0
path_t path_parse(char *json, int len)
{
  unsigned short js[64];
  path_t p;
  
  if(!json) return NULL;
  if(!len) len = strlen(json);
  js0n((unsigned char*)json, len, js, 64);
  if(!j0g_val("type",json,js)) return NULL;
  p = path_new(j0g_str("type",json,js));

  // just try to set all possible attributes
  path_ip(p, j0g_str("ip",json,js));
  if(j0g_str("port",json,js)) path_port(p, (uint16_t)strtol(j0g_str("port",json,js),NULL,10));
  path_id(p, j0g_str("id",json,js));
  path_http(p, j0g_str("http",json,js));
  
  return p;
}
Exemplo n.º 14
0
static PyObject* 
path_subscript(PyPathObject* self, PyObject* item) {
    if (PyIndex_Check(item)) {
        Py_ssize_t i;
        i = PyNumber_AsSsize_t(item, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred())
            return NULL;
        return path_getitem(self, i);
    }
    if (PySlice_Check(item)) {
        int len = 4;
        Py_ssize_t start, stop, step, slicelength;

        if (PySlice_GetIndicesEx((PyObject*)item, len, &start, &stop, &step, &slicelength) < 0)
            return NULL;

        if (slicelength <= 0) {
            double *xy = alloc_array(0);
            return (PyObject*) path_new(0, xy, 0);
        }
        else if (step == 1) {
            return path_getslice(self, start, stop);
        }
        else {
            PyErr_SetString(PyExc_TypeError, "slice steps not supported");
            return NULL;
        }
    }
    else {
        PyErr_Format(PyExc_TypeError,
                     "Path indices must be integers, not %.200s",
#ifdef PY3
                     Py_TYPE(&item)->tp_name);
#else
                     item->ob_type->tp_name);
#endif
        return NULL;
    }
}
Exemplo n.º 15
0
static Path *
screen_saver_floater_create_path_to_random_point (ScreenSaver        *screen_saver,
        ScreenSaverFloater *floater,
        gdouble             duration)
{
    Point start_position, end_position, start_control_point, end_control_point;

    start_position = floater->position;

    end_position.x = start_position.x +
                     (g_random_double_range (-.5, .5) * 4 * FLOATER_MAX_SIZE);
    end_position.y = start_position.y +
                     (g_random_double_range (-.5, .5) * 4 * FLOATER_MAX_SIZE);

    start_control_point.x = start_position.x + .95 * (end_position.x - start_position.x);
    start_control_point.y = start_position.y + .95 * (end_position.y - start_position.y);

    end_control_point.x = start_position.x + 1.0 * (end_position.x - start_position.x);
    end_control_point.y = start_position.y + 1.0 * (end_position.y - start_position.y);

    return path_new (&start_position, &start_control_point, &end_control_point,
                     &end_position, duration);
}
Exemplo n.º 16
0
static Path *
screen_saver_floater_create_path_to_on_screen (ScreenSaver        *screen_saver,
        ScreenSaverFloater *floater,
        gdouble             duration)
{
    Point start_position, end_position, start_control_point, end_control_point;
    start_position = floater->position;

    end_position.x = g_random_double_range (.25, .75) *
                     (screen_saver->canvas_rectangle.top_left_point.x +
                      screen_saver->canvas_rectangle.bottom_right_point.x);
    end_position.y = g_random_double_range (.25, .75) *
                     (screen_saver->canvas_rectangle.top_left_point.y +
                      screen_saver->canvas_rectangle.bottom_right_point.y);

    start_control_point.x = start_position.x + .9 * (end_position.x - start_position.x);
    start_control_point.y = start_position.y + .9 * (end_position.y - start_position.y);

    end_control_point.x = start_position.x + 1.0 * (end_position.x - start_position.x);
    end_control_point.y = start_position.y + 1.0 * (end_position.y - start_position.y);

    return path_new (&start_position, &start_control_point, &end_control_point,
                     &end_position, duration);
}
Exemplo n.º 17
0
Arquivo: path.c Projeto: jwise/kgtd
/* @brief loads the path onto the board and generates the relevant display list
 *
 * see level_data.c for path format description
 */
void path_load(state_t *state, map_t *map)
{
	int cur_x = map->x_start, cur_y = map->y_start, i;
	int new_x, new_y;
	int length = map->length;
	int *path = map->path;
	float x, y;
	path_t *cur, *prev = NULL;

	cur = state->path = path_new(map->x_start, map->y_start);

	for(i = 0; i < length; i+=2) {
		/* do x */
		new_x = cur_x + path[i];
		if(path[i] > 0) {
			for(; cur_x < new_x; cur_x++) {
				cur->next = path_new(cur_x, cur_y);
				cur = cur->next;
			}
		}
		else if(path[i] < 0) {
			for(; cur_x > new_x; cur_x--) {
				cur->next = path_new(cur_x, cur_y);
				cur = cur->next;
			}
		}
		if(i == length - 1)
			break;
		/* do y */
		new_y = cur_y + path[i+1];
		if(path[i + 1] > 0) {
			for(; cur_y < new_y; cur_y++) {
				cur->next = path_new(cur_x, cur_y);
				cur = cur->next;
			}
		}
		else if(path[i + 1] < 0) {
			for(; cur_y > new_y; cur_y--) {
				cur->next = path_new(cur_x, cur_y);
				cur = cur->next;
			}
		}
	}
	cur->next = NULL;

	glNewList(DISPLAY_LIST_PATH, GL_COMPILE);
	glBegin(GL_QUADS);
	for(cur = state->path; cur != NULL; cur = cur->next) {
		x = cur->pos.x;
		y = cur->pos.y;
		if(cur->next == NULL)
			glColor3f(0.9, 0.2, 0.2);
		else if(cur == state->path)
			glColor3f(0.1, 0.5, 0.1);
		else
			glColor3f(0.2, 0.2, 0.2);

		glVertex2f(x - GRID_SIZE/2, y - GRID_SIZE/2);
		glVertex2f(x + GRID_SIZE/2, y - GRID_SIZE/2);
		glVertex2f(x + GRID_SIZE/2, y + GRID_SIZE/2);
		glVertex2f(x - GRID_SIZE/2, y + GRID_SIZE/2);
	}
	glEnd();

	cur = state->path;
	cur_x = map->x_start;
	cur_y = map->y_start;
	glBegin(GL_LINES);
	for(i = 0; i < length; i+=2) {
		new_x = cur_x + path[i];
		if(path[i] > 0) {
			for(; cur_x < new_x; cur_x++) {
				draw_one(cur_x, cur_y, cur, prev);
				prev = cur;
				cur = cur->next;
			}
		}
		else if(path[i] < 0) {
			for(; cur_x > new_x; cur_x--) {
				draw_one(cur_x, cur_y, cur, prev);
				prev = cur;
				cur = cur->next;
			}
		}
		if(i == length - 1)
			break;
		new_y = cur_y + path[i+1];
		if(path[i + 1] > 0) {
			for(; cur_y < new_y; cur_y++) {
				draw_one(cur_x, cur_y, cur, prev);
				prev = cur;
				cur = cur->next;
			}
		}
		else if(path[i + 1] < 0) {
			for(; cur_y > new_y; cur_y--) {
				draw_one(cur_x, cur_y, cur, prev);
				prev = cur;
				cur = cur->next;
			}
		}
	}
	glEnd();
	glEndList();
}
Exemplo n.º 18
0
nglInputDevice* nglInputDeviceLinux::Enum (uint Index)
{
  if (!mInitCalled)
  {
    App->AddExit(Exit);
    mInitCalled = true;
  }

  if (!mpBasePath)
  {
    nglPath path_old(_T("/dev/js1"));
    nglPath path_new(_T("/dev/input/js1"));

    if (path_new.Exists())
      mpBasePath = (nglChar*) _T("/dev/input/js");
    else
    if (path_old.Exists())
      mpBasePath = (nglChar*) _T("/dev/js");
  }

  // No valid path to joystick devices
  if (!mpBasePath)
    return NULL;

  uint i;
  uint valid = 0;
  bool found = false;

  for (i = 0; !found; i++)
  {
    // Check existence of device node '{basepath}/js{i}'
    nglString path_str;
    path_str.Format("%s%d", mpBasePath, i);

    nglPath path(path_str);
    if (!path.Exists())
      break; // No more devices to check, end there

    // Grow vector if necessary
    if (i >= mDeviceList.size())
    {
      mDeviceList.resize(i + 1);
      mDeviceList[i] = NULL;
    }

    // If device has no associated instance, create one now
    if (mDeviceList[i] == NULL)
      mDeviceList[i] = new nglInputDeviceLinux(path);

    if (mDeviceList[i]->IsValid())
      valid++;
    found = (valid == Index + 1);
  }

  if (!found)
    return NULL;

  nglInputDeviceLinux* dev = mDeviceList[i-1];

  return dev ? CreateDevice(dev) : NULL;
}
Exemplo n.º 19
0
/* compute a path in the given pixmap, separating black from white.
   Start path at the point (x0,x1), which must be an upper left corner
   of the path. Also compute the area enclosed by the path. Return a
   new path_t object, or NULL on error (note that a legitimate path
   cannot have length 0). Sign is required for correct interpretation
   of turnpolicies. */
static path_t *findpath(potrace_bitmap_t *bm, int x0, int y0, int sign, int turnpolicy) {
  int x, y, dirx, diry, len, size, area;
  int c, d, tmp;
  point_t *pt, *pt1;
  path_t *p = NULL;

  x = x0;
  y = y0;
  dirx = 0;
  diry = -1;

  len = size = 0;
  pt = NULL;
  area = 0;
  
  while (1) {
    /* add point to path */
    if (len>=size) {
      size += 100;
      size = (int)(1.3 * size);
      pt1 = (point_t *)realloc(pt, size * sizeof(point_t));
      if (!pt1) {
	goto error;
      }
      pt = pt1;
    }
    pt[len].x = x;
    pt[len].y = y;
    len++;
    
    /* move to next point */
    x += dirx;
    y += diry;
    area += x*diry;
    
    /* path complete? */
    if (x==x0 && y==y0) {
      break;
    }
    
    /* determine next direction */
    c = BM_GET(bm, x + (dirx+diry-1)/2, y + (diry-dirx-1)/2);
    d = BM_GET(bm, x + (dirx-diry-1)/2, y + (diry+dirx-1)/2);
    
    if (c && !d) {               /* ambiguous turn */
      if (turnpolicy == POTRACE_TURNPOLICY_RIGHT
	  || (turnpolicy == POTRACE_TURNPOLICY_BLACK && sign == '+')
	  || (turnpolicy == POTRACE_TURNPOLICY_WHITE && sign == '-')
	  || (turnpolicy == POTRACE_TURNPOLICY_RANDOM && detrand(x,y))
	  || (turnpolicy == POTRACE_TURNPOLICY_MAJORITY && majority(bm, x, y))
	  || (turnpolicy == POTRACE_TURNPOLICY_MINORITY && !majority(bm, x, y))) {
	tmp = dirx;              /* right turn */
	dirx = diry;
	diry = -tmp;
      } else {
	tmp = dirx;              /* left turn */
	dirx = -diry;
	diry = tmp;
      }
    } else if (c) {              /* right turn */
      tmp = dirx;
      dirx = diry;
      diry = -tmp;
    } else if (!d) {             /* left turn */
      tmp = dirx;
      dirx = -diry;
      diry = tmp;
    }
  } /* while this path */

  /* allocate new path object */
  p = path_new();
  if (!p) {
    goto error;
  }

  p->priv->pt = pt;
  p->priv->len = len;
  p->area = area;
  p->sign = sign;

  return p;
 
 error:
   free(pt);
   return NULL; 
}
Exemplo n.º 20
0
Arquivo: req.c Projeto: RAttab/optics
static const struct path *crest_req_get_path(struct crest_req *req)
{
    if (!req->path) req->path = path_new(req->url);
    return req->path;
}
Exemplo n.º 21
0
static path_t*extract_path(graphcut_workspace_t*work, unsigned char*mytree, unsigned char*othertree, node_t*pos, node_t*newpos, halfedge_t*dir)
{
    int t;
    node_t*p = pos;
    node_t*nodes = work->graph->nodes;
    int len1 = 0;
    /* walk up tree1 */
    DBG printf("walk back up (1) to %d\n", NR(work->pos1));
    while(p != work->pos1) {
	halfedge_t*back = work->back[NR(p)];
	DBG printf("walk backward (1): %d %d\n", NR(p), back?NR(back->fwd->node):-1);
	node_t*old = p;
	p = work->back[NR(p)]->fwd->node;
	assert(p!=old);
	len1++;
    }
    p = newpos;
    int len2 = 0;
    DBG printf("walk back up (2) to %d\n", NR(work->pos2));
    /* walk up tree2 */
    while(p != work->pos2) {
	DBG printf("walk backward (2): %d\n", NR(p));
	p = work->back[NR(p)]->fwd->node;
	len2++;
    }
    path_t*path = path_new(len1+len2+2);

    t = len1;
    path->pos[t] = p = pos;
    path->dir[t] = dir;
    path->firsthalf[t] = 1;
    while(p != work->pos1) {
	assert(mytree[NR(p)]&IN_TREE);
	halfedge_t*dir = work->back[NR(p)];
	assert(dir->node == p);
	p = dir->fwd->node;
	t--;
	path->pos[t] = p;
	path->dir[t] = dir->fwd;
	path->firsthalf[t] = 1;
    }
    assert(!t);

    t = len1+1;

    p = newpos;
    while(p != work->pos2) {
	assert(othertree[NR(p)]&IN_TREE);
	halfedge_t*dir = work->back[NR(p)];
	path->pos[t] = p;
	path->dir[t] = dir;
	path->firsthalf[t] = 0;
	p = dir->fwd->node;
	t++;
    }

    /* terminator */
    path->pos[t] = p;
    path->dir[t] = 0; // last node
    path->firsthalf[t] = 0;

    assert(t == len1+len2+1);
    return path;
}
Exemplo n.º 22
0
/*----------------------------------------------------------------------*
 * Function:                                                            *
 * Purpose:                                                             *
 * Params:                                                              *
 * Returns:                                                             *
 *----------------------------------------------------------------------*/
int grow_graph_from_node(dBNode* start_node, dBNode** best_node, dBGraph* graph)
{                         
    Queue* nodes_to_walk;
    dBNode* node;
    int orientation;
    int depth;
    int current_graph_size = 0;
    int best_coverage = 0;
    int best_edges = 0;
    
    *best_node = 0;
    
    // Nucleotide iterator, used to walk all possible paths from a node
    void walk_if_exists(Nucleotide n) {
        //if (debug) printf("Trying nucleotide %i\n", n);
        
        // If there is an edge in any colour for this nucleotide...
        if (db_node_edge_exist_any_colour(node, n, orientation)) {
            
            //if (debug) printf("  Edge exists\n");
            
            // Get first node along this edge and check we've not already visited it...
            Orientation next_orientation;
            Nucleotide reverse_nucleotide;
            dBNode * next_node;
            next_node = db_graph_get_next_node(node, orientation, &next_orientation, n, &reverse_nucleotide, graph);
            if (!next_node) {
                log_and_screen_printf("Error: Something went wrong with db_graph_get_next_node\n");
                exit(-1);
            }
            
            // If not already visited the first node, walk it...
            if (!db_node_check_flag_visited(next_node)) {
                pathStep first_step;
                Path * new_path;
                dBNode* end_node; 
                int i = 0;
                                
                // Get path				
                first_step.node = node;
                first_step.orientation = orientation;
                first_step.label = n;
                new_path = path_new(MAX_EXPLORE_NODES, graph->kmer_size);
                if (!new_path) {
                    log_and_screen_printf("ERROR: Not enough memory to allocate new path.\n");
                    exit(-1);
                }
                
                db_graph_get_perfect_path_with_first_edge_all_colours(&first_step, &db_node_action_do_nothing, new_path, graph);
                
                // Add end node to list of nodes to visit
                end_node = new_path->nodes[new_path->length-1];
                if (!db_node_check_flag_visited(end_node)) {
                    if (!db_node_is_blunt_end_all_colours(end_node, new_path->orientations[new_path->length-1])) {
                        if (queue_push_node(nodes_to_walk, end_node, depth+1) == NULL) {
                            log_and_screen_printf("Queue too large. Ending.\n");
                            exit(1);
                        }                        
                    }
                }
                
                // Now go through all nodes, look for best and mark all as visited
                for (i=0; i<new_path->length; i++) {
                    if (!db_node_check_flag_visited(new_path->nodes[i])) {
                        int this_coverage = element_get_coverage_all_colours(new_path->nodes[i]);
                        int this_edges = db_node_edges_count_all_colours(new_path->nodes[i], forward) + db_node_edges_count_all_colours(new_path->nodes[i], reverse);
                        
                        if ((best_node == 0) ||
                            (this_coverage > best_coverage) ||
                            ((this_coverage == best_coverage) && (this_edges < best_edges)))
                        {
                            best_coverage = this_coverage;
                            best_edges = this_edges;
                            *best_node = new_path->nodes[i];                            
                        }
                        
                        db_node_action_set_flag_visited(new_path->nodes[i]);
                        current_graph_size++;                        
                    }
                }
                
                // Clean up
                path_destroy(new_path);
            }
        }
    }
    
    // Start a queue of nodes to walk
    //log_and_screen_printf("Allocating %d Mb to store queue information (max %d nodes, when full each node could be %d)...\n", ((METACORTEX_QUEUE_SIZE * sizeof(QueueItem*)) / 1024) / 1024, METACORTEX_QUEUE_SIZE, sizeof(QueueItem));
    nodes_to_walk = queue_new(METACORTEX_QUEUE_SIZE);
    if (!nodes_to_walk) {
        log_and_screen_printf("Couldn't get memory for node queue.\n");
        exit(-1);
    }
    
    // Add start node to list of nodes to visit
    if (queue_push_node(nodes_to_walk, start_node, 0) == NULL) {
        log_and_screen_printf("Queue too large. Ending.\n");
        exit(-1);        
    }
    
    if (!db_node_check_flag_visited(start_node)) {
        db_node_action_set_flag_visited(start_node);
        current_graph_size++;
    }
    
    // Now keep visiting nodes and walking paths
    while (nodes_to_walk->number_of_items > 0) {
        // Take top node from list
        node = queue_pop_node(nodes_to_walk, &depth);
        
        // Look at all paths out from here
        orientation = forward;
        nucleotide_iterator(&walk_if_exists);
        orientation = reverse;
        nucleotide_iterator(&walk_if_exists);				
    }
    
    queue_free(nodes_to_walk);
    
    // If we didn't find a start node, presumably this is a singleton?
    if (*best_node == 0) {
        printf("Note: didn't find a best node, setting to start node\n");
        *best_node = start_node;
    }
    
    return current_graph_size;
}
Exemplo n.º 23
0
void metacortex_find_subgraphs(dBGraph* graph, char* consensus_contigs_filename, int min_subgraph_kmers)
{
    SubGraphInfo* sub_graphs;
    FILE* fp;
    Path *path_fwd = path_new(MAX_EXPLORE_PATH_LENGTH, graph->kmer_size);
    Path *path_rev = path_new(MAX_EXPLORE_PATH_LENGTH, graph->kmer_size);
    Path *final_path = path_new(MAX_EXPLORE_PATH_LENGTH, graph->kmer_size);
    char seq[256];
    char analysis_filename[strlen(consensus_contigs_filename) + 10];
    long int total_nodes = 0;
    int n_seeds = 0;
    int i;
    
    sprintf(analysis_filename, "%s.analysis", consensus_contigs_filename);
    log_and_screen_printf("Running metacortex subgraph analysis...\n");
    log_and_screen_printf("          Contig file: %s\n", consensus_contigs_filename);
    log_and_screen_printf("        Analysis file: %s\n", analysis_filename);
    log_and_screen_printf("Minimum subgraph size: %i\n", min_subgraph_kmers);
    
    /* Initialise temporaray path array buffers */
    path_array_initialise_buffers(graph->kmer_size);
    
    /* Create a list of subgraphs */
    log_and_screen_printf("Allocating %d Mb to store subgraph information (max %d seeds)...\n", ((MAX_SEEDS * sizeof(SubGraphInfo)) / 1024) / 1024, MAX_SEEDS);
    sub_graphs = calloc(MAX_SEEDS, sizeof(SubGraphInfo));
    if (!sub_graphs) {
        log_and_screen_printf("ERROR: Can't get memory for subgraphs\n");
        exit(-1);
    }

    /* Open the analysis file */
    fp = fopen(analysis_filename, "w");
    if (!fp) {
        log_and_screen_printf("ERROR: Can't open analysis file.\n");
        exit(-1);
    }
        
    /* For each node, if it's not pruned or visited, try and grow a graph */
    void explore_node(dBNode * node) {
        if (node == NULL) {
            log_and_screen_printf("Error: NULL node passed to explore_node.\n");
            exit(-1);
        }
        
        if (db_node_check_for_any_flag(node, PRUNED | VISITED) == false) {
            int nodes_in_graph;
            
            /* Grow graph from this node, returning the 'best' (highest coverage) node to store as seed point */
            nodes_in_graph = grow_graph_from_node(node, &(sub_graphs[n_seeds].seed_node), graph);
            total_nodes += nodes_in_graph;
            
            if (sub_graphs[n_seeds].seed_node == NULL) {
                printf("ERROR: Seed node is NULL, nodes in graph is %d\n", nodes_in_graph);
            } else {
                /* Write data to analysis file */
                binary_kmer_to_seq(&(node->kmer), graph->kmer_size, seq);            
                fprintf(fp, "%i\t%i\t%ld\t%s\t", n_seeds, nodes_in_graph, total_nodes, seq);
                binary_kmer_to_seq(&(sub_graphs[n_seeds].seed_node->kmer), graph->kmer_size, seq);
                fprintf(fp, "%s\n", seq);

                /* Store nodes in this subgraph */
                sub_graphs[n_seeds].graph_size = nodes_in_graph;
                n_seeds++;
                
                /* Check we've not run out of seed storage - in future, this should dynamically allocate */
                if (n_seeds == MAX_SEEDS) {
                    log_and_screen_printf("Error: MAX_SEEDS exceeded. Quitting.\n");
                    exit(-1);
                }
            }
        }
    }
    
    /* Traverse each node... */
    log_and_screen_printf("Finding subgraphs...\n");
    hash_table_traverse(&explore_node, graph);
    log_and_screen_printf("Finished. Total: %ld\n", total_nodes);
    fclose(fp);    
    
    /* Open consensus contigs file */
    fp = fopen(consensus_contigs_filename, "w");
    if (!fp) {
        log_and_screen_printf("ERROR: Can't open contig file.\n");
        exit(-1);
    }
    
    /* Now go through all the seed points and generate the consensus contigs by walking forward and backward from the seed */
    db_graph_reset_flags(graph);    
    log_and_screen_printf("Outputting contigs...\n");
	log_progress_bar(0);
	long long one_percent = n_seeds/100;
    int percent;
    
    if (one_percent < 1) {
        one_percent = 1;
    }
    
    for (i=0; i<n_seeds; i++) {
        if (i % one_percent == 0) {
            percent = (100 * i) / n_seeds;
            log_progress_bar(percent);
        } 
        
        //log_printf("Graph %i\n", i);           
        if (sub_graphs[i].graph_size >= min_subgraph_kmers) {            
            binary_kmer_to_seq(&(sub_graphs[i].seed_node->kmer), graph->kmer_size, seq);
            coverage_walk_get_path(sub_graphs[i].seed_node, forward, NULL, graph, path_fwd);
            coverage_walk_get_path(sub_graphs[i].seed_node, reverse, NULL, graph, path_rev);
            path_reverse(path_fwd, final_path);
            path_append(final_path, path_rev);
            final_path->id = i;
            path_to_fasta(final_path, fp);
            //log_printf("  Seed %s\tFwd path length %i\tRev path length %i\tFinal path length %i\n", seq, path_fwd->length, path_rev->length, final_path->length);
            path_reset(path_fwd);
            perfect_path_get_path(sub_graphs[i].seed_node, forward, &db_node_action_do_nothing, graph, path_fwd);
            //log_printf("\t\tPerfect path fwd length %i\n", path_fwd->length);
            path_reset(path_rev);
            path_reset(final_path);
        } else {
            log_printf("  Number of nodes (%i} too small. Not outputting contig.\n", sub_graphs[i].graph_size);
        }
        
    }
	log_progress_bar(100);
	printf("\n");
    log_and_screen_printf("Finished contig output.\n");    
    fclose(fp);
    
    free(sub_graphs);
}
Exemplo n.º 24
0
static void*
pthread_main (void *arg)
{

     int* arr = (int*)arg;
     int thrn = *(arr); arr++;
     int num_elem = *(arr);arr++;
#ifdef DEBUG     
     printf ("starting thread %d num elem %d\n", thrn, num_elem);
#endif
     int i;
     _depth = num_nodes + 1;
     for (i = 0; i < num_elem; i++){
#ifdef DEBUG
	  printf ("iterating thread %d elem #%d\n", thrn, arr[i]);
#endif
	  _update_path = num_nodes;
	  bmap_init_static (num_nodes);
	  _node_to_start = arr[i];
	  _stop_cnt = 0;

	  _found_min = (_global_found_min == ULONG_MAX ? ULONG_MAX: _global_found_min + 1);

#ifdef DEBUG
	  _stat_cut_by_weight = _stat_cut_by_presence = _stat_evaluated = _stat_found_hash = 0;
#endif

	  GraphPath *path = path_new ();
	  Bitmap *bitmap = bmap_new ();
	  int res = find_shortest_path (bitmap, &path);

#ifdef DEBUG
	  printf ("MAX: %lu -> %lu (weight:%lu, presence:%lu, eval:%lu, hash:%lu)\n", 
		  _found_min, path->total_weight, _stat_cut_by_weight, 
		  _stat_cut_by_presence, _stat_evaluated, _stat_found_hash);
	  bmap_print_hash ();
#endif	  

	  if (res){
	       /* begin critical section */
	       pthread_mutex_lock (&_mutex);
	       
	       if (path->total_weight < _global_found_min){
		    match_cnt = 0;
		    if (best_found_path)
			 path_free (best_found_path);
		    best_found_path = path_clone (path);
		    _global_found_min = path->total_weight;
	       }

	       if (path->total_weight == _global_found_min){
		    match_cnt++;
	       }

	       if (match_cnt >= MINIMUM_NUMBER_MATCHES_RESULTS){
		    print_solution (best_found_path);
		    exit(0);
	       }	       
	       pthread_mutex_unlock (&_mutex);

	       /* end critical section */	  

	  }	
	  path_free (path);
	  bmap_free (bitmap);
	  _depth += 2;
     }
     bmap_free_static ();
     return 0;
}