Ejemplo n.º 1
0
def calculate_move_human(human, cat, net):
    try:
        matches = shortest_path(net, source=human.current_station, target=cat.current_station)
    except nx.NetworkXNoPath:
        # no path (ei. all destination station are closed)
        human.can_move = False
        return
    if len(matches) > 1:
        if net.node[matches[1]]['closed']:
            matches = list(all_shortest_paths(net, source=human.current_station, target=cat.current_station)
                           )
            paths = []
            for path_id, sub_list in enumerate(matches):
                for c in sub_list:
                    if net.node[c]['closed']:
                        paths.append(False)
                        break
                if len(paths) < path_id:
                    paths.append(True)
            if True in paths:
                human.count_move += 1
                human.current_station = matches[path_id][1]
            else:
                human.can_move = False
        else:
            human.count_move += 1
            human.current_station = matches[1]
Ejemplo n.º 2
0
    def get_shortest_paths(self, from_, to_):
        """get_shortest_paths

        :param from_
        :param to
        """

        from networkx.exception import NetworkXNoPath
        from networkx.algorithms import all_shortest_paths

        try:
            return self.to_json(
                list(all_shortest_paths(self.__graph, from_, to_, 'weight')))
        except NetworkXNoPath:
            click.echo('No shortest paths between {} and {}'.format(
                from_, to_))
Ejemplo n.º 3
0
def generate_noisy_shortest_path_data(options):

    while True:
        num_nodes = options["num_entities"]
        min_path_len = options["min_path_len"]
        g = nx.random_graphs.connected_watts_strogatz_graph(num_nodes, 3, .5)
        source, target = np.random.randint(num_nodes, size=2)

        if source == target: continue  # reject trivial paths

        paths = list(nxalg.all_shortest_paths(g, source=source, target=target))

        if len(paths) > 1: continue  # reject when more than one shortest path

        path = paths[0]

        if len(path) < min_path_len: continue  # reject paths that's too short

        break

    edges = g.edges()

    num_confusing = options['num_confusing']
    if num_confusing > 0:
        g_confusing = nx.random_graphs.connected_watts_strogatz_graph(
            num_confusing, 3, .5)

        for e in g_confusing.edges():
            edges.append((e[0] + num_nodes, e[1] + num_nodes))

        random.shuffle(edges)

    # randomize index
    idx = _generate_random_node_index(num_nodes + num_confusing)
    new_edges = _relabel_nodes_in_edges(edges, idx)
    new_path = _relabel_nodes_in_path(path, idx)

    for edge in new_edges:
        print "%s connected-to %s" % (edge[0], edge[1])
        print "%s connected-to %s" % (edge[1], edge[0])

    print "eval shortest-path %s %s\t%s" % (idx[source], idx[target], ",".join(
        [str(v) for v in new_path]))
Ejemplo n.º 4
0
def generate_noisy_shortest_path_data(options):

    while True:
        num_nodes = options["num_entities"]
        min_path_len = options["min_path_len"]
        g = nx.random_graphs.connected_watts_strogatz_graph(num_nodes, 3, .5)
        source, target = np.random.randint(num_nodes, size=2)

        if source == target:  continue  # reject trivial paths

        paths = list(nxalg.all_shortest_paths(g, source=source, target=target))

        if len(paths) > 1:  continue  # reject when more than one shortest path

        path = paths[0]

        if len(path) < min_path_len: continue   # reject paths that's too short

        break

    edges = g.edges()

    num_confusing = options['num_confusing']
    if num_confusing > 0:
        g_confusing = nx.random_graphs.connected_watts_strogatz_graph(num_confusing, 3, .5)

        for e in g_confusing.edges():
            edges.append((e[0] + num_nodes, e[1] + num_nodes))

        random.shuffle(edges)

    # randomize index
    idx = _generate_random_node_index(num_nodes + num_confusing)
    new_edges = _relabel_nodes_in_edges(edges, idx)
    new_path = _relabel_nodes_in_path(path, idx)

    for edge in new_edges:
        print "%s connected-to %s" % (edge[0], edge[1])
        print "%s connected-to %s" % (edge[1], edge[0])

    print "eval shortest-path %s %s\t%s" % (idx[source], idx[target], ",".join([str(v) for v in new_path]))
Ejemplo n.º 5
0
def generate_shortest_path_data(options):

    while True:
        num_nodes = options["num_entities"]
        g = nx.random_graphs.connected_watts_strogatz_graph(num_nodes, 3, .5)
        source, target = np.random.randint(num_nodes, size=2)

        if source == target:  continue  # reject trivial paths

        paths = list(nxalg.all_shortest_paths(g, source=source, target=target))

        if len(paths) > 1:  continue  # reject when more than one shortest path

        path = paths[0]

        break

    for edge in g.edges():
        print "%s connected-to %s" % (edge[0], edge[1])
        print "%s connected-to %s" % (edge[1], edge[0])

    print "eval shortest-path %s %s\t%s" % (source, target, ",".join([str(v) for v in path]))
Ejemplo n.º 6
0
def generate_shortest_path_data(options):

    while True:
        num_nodes = options["num_entities"]
        g = nx.random_graphs.connected_watts_strogatz_graph(num_nodes, 3, .5)
        source, target = np.random.randint(num_nodes, size=2)

        if source == target: continue  # reject trivial paths

        paths = list(nxalg.all_shortest_paths(g, source=source, target=target))

        if len(paths) > 1: continue  # reject when more than one shortest path

        path = paths[0]

        break

    for edge in g.edges():
        print "%s connected-to %s" % (edge[0], edge[1])
        print "%s connected-to %s" % (edge[1], edge[0])

    print "eval shortest-path %s %s\t%s" % (source, target, ",".join(
        [str(v) for v in path]))
Ejemplo n.º 7
0
 def find_complexSV(self):
     
     pool = []
     nodes = self.graph.nodes()
     for n1 in nodes:
         for n2 in nodes:
             if n1 == n2:
                 continue
             pre = has_path(self.graph, n1, n2)
             if pre:
                 # do not consider edge weight
                 paths = list(all_shortest_paths(self.graph, n1, n2, weight=None))
                 for p in paths:
                     if not self._containloop(p):
                         pool.append((len(p), p))
     pool.sort(reverse=True)
     
     # so far, the candidate paths contain no self-loops, but are still redundant
     # check distance-decay for each pair of regions
     queue = [(self.clr, self._change_format(p[1]), self.span, self.balance_type, p[1], self.protocol) for p in pool]
     log.info('Filtering {0} redundant candidates ...'.format(len(queue)))
     jobs = Parallel(n_jobs=self.n_jobs, verbose=10)(delayed(filterAssembly)(*i) for i in queue)
     pre_alleles = []
     for ck, p in jobs:
         if ck:
             pre_alleles.append(p)
     
     # these assembly should exist within the same allele
     alleles = []
     for p in pre_alleles:
         for v in alleles:
             if self._issubset(p, v) or self._issubset(p, self._getreverse(v)):
                 break
         else:
             alleles.append(p)
     
     self.alleles = alleles
Ejemplo n.º 8
0
def create_random_graph(type, filePath, numberOfCase, graph_scale):
    """

    :param type: the graph type
    :param filePath: the output file path
    :param numberOfCase: the number of examples
    :return:
    """
    with open(filePath, "w+") as f:
        degree = 0.0
        for _ in range(numberOfCase):
            info = {}
            graph_node_size = graph_scale
            edge_prob = 0.3

            while True:
                edge_count = 0.0
                if type == "random":
                    graph = nx.gnp_random_graph(graph_node_size,
                                                edge_prob,
                                                directed=True)
                    for id in graph.edge:
                        edge_count += len(graph.edge[id])
                    start = random.randint(0, graph_node_size - 1)
                    adj = nx.shortest_path(graph, start)

                    max_len = 0
                    path = []
                    paths = []
                    for neighbor in adj:
                        if len(adj[neighbor]) > max_len and neighbor != start:
                            paths = []
                            max_len = len(adj[neighbor])
                            path = adj[neighbor]
                            end = neighbor
                            for p in nx.all_shortest_paths(graph, start, end):
                                paths.append(p)

                    if len(path) > 0 and path[0] == start and len(
                            path) == 3 and len(paths) == 1:
                        degree += edge_count / graph_node_size
                        break

                elif type == "no-cycle":
                    graph = nx.DiGraph()
                    for i in range(graph_node_size):
                        nodes = graph.nodes()
                        if len(nodes) == 0:
                            graph.add_node(i)
                        else:
                            size = random.randint(1, min(i, 2))
                            fathers = random.sample(range(0, i), size)
                            for father in fathers:
                                graph.add_edge(father, i)
                    for id in graph.edge:
                        edge_count += len(graph.edge[id])
                    start = 0
                    end = graph_node_size - 1
                    path = nx.shortest_path(graph, 0, graph_node_size - 1)
                    paths = [
                        p for p in nx.all_shortest_paths(
                            graph, 0, graph_node_size - 1)
                    ]
                    if len(path) >= 4 and len(paths) == 1:
                        degree += edge_count / graph_node_size
                        break

                elif type == "baseline":
                    num_nodes = graph_node_size
                    graph = nx.random_graphs.connected_watts_strogatz_graph(
                        num_nodes, 3, edge_prob)
                    for id in graph.edge:
                        edge_count += len(graph.edge[id])
                    start, end = np.random.randint(num_nodes, size=2)

                    if start == end:
                        continue  # reject trivial paths

                    paths = list(
                        nxalg.all_shortest_paths(graph,
                                                 source=start,
                                                 target=end))

                    if len(paths) > 1:
                        continue  # reject when more than one shortest path

                    path = paths[0]

                    if len(path) != 4:
                        continue
                    degree += edge_count / graph_node_size
                    break

            adj_list = graph.adjacency_list()

            g_ids = {}
            g_ids_features = {}
            g_adj = {}
            for i in range(graph_node_size):
                g_ids[i] = i
                if i == start:
                    g_ids_features[i] = "START"
                elif i == end:
                    g_ids_features[i] = "END"
                else:
                    # g_ids_features[i] = str(i+10)
                    g_ids_features[i] = str(random.randint(1, 15))
                g_adj[i] = adj_list[i]

            # print start, end, path
            text = ""
            for id in path:
                text += g_ids_features[id] + " "

            info["seq"] = text.strip()
            info["g_ids"] = g_ids
            info['g_ids_features'] = g_ids_features
            info['g_adj'] = g_adj
            f.write(json.dumps(info) + "\n")

        print("average degree in the graph is :{}".format(degree /
                                                          numberOfCase))