示例#1
0
 def get_turtle_state_from(self, head):
     turtle = Turtle()
     root = self.get_root_from(head)
     path = shortest_path(self.parentage, root, head)
     for node in path:
         turtle.move(node)
     return turtle
    def test_join_network(self):
        """
        Tests various joins by path analysis
        """
        md = MetaData()
        table_one = Table("one", md, Column("pk", Integer, primary_key=True))
        table_two = Table(
            "two",
            md,
            Column("pk", Integer, primary_key=True),
            Column("one_fk", Integer, ForeignKey("one.pk")),
        )

        network = join_network(md.tables)

        self.assertListEqual(
            [tbl.name for tbl in shortest_path(network, table_two, table_one)],
            ["two", "one"])

        def fails():
            shortest_path(network, table_one, table_two)

        self.assertRaises(NetworkXNoPath, fails)

        table_three = Table("three", md, Column("pk",
                                                Integer,
                                                primary_key=True),
                            Column("two_fk", Integer, ForeignKey("two.pk")))

        table_four = Table("four", md, Column("pk", Integer, primary_key=True),
                           Column("three_fk", Integer, ForeignKey("three.pk")))

        self.assertListEqual([
            tbl.name for tbl in shortest_path(join_network(md.tables),
                                              table_four, table_one)
        ], ["four", "three", "two", "one"])

        table_five = Table("five", md, Column("pk", Integer, primary_key=True),
                           Column("one_fk", Integer, ForeignKey("one.pk")))
        table_six = Table("six", md, Column("pk", Integer, primary_key=True),
                          Column("five_fk", Integer, ForeignKey("five.pk")))

        self.assertListEqual([
            tbl.name for tbl in shortest_path(join_network(md.tables),
                                              table_six, table_one)
        ], ["six", "five", "one"])
    def solve_instance(self, instance):
        """
        Where the magic happens.
        This method should return the solution (as a string) of the given instance.
        """
        self.graph = nx.Graph()

        self.add_nodes_to_graph(instance)
        self.add_edges_to_graph(instance)

        path = shortest_path(self.graph, instance.start, instance.end)
        return "->".join(path)
示例#4
0
 def shortestPath(self, source: V, target: V) -> Optional[list]:
     """
     """
     try:
         path_nodes = shortest_path(self.graph,
                                    source=source,
                                    target=target)
         path: list = [{} for x in range(0, len(path_nodes) - 1)]
         for pos, _ in enumerate(path):
             path[pos] = {path_nodes[pos], path_nodes[pos + 1]}
         return path
     except NetworkXNoPath:
         return None
def find_cycle_with_edge_of_matching(graph: nx.Graph, matching: Dict[Any, Any]) -> List[Any]:
    tmp_graph = copy.deepcopy(graph)
    # Remove the edge so and find a path from a node of the edge to the other one.
    # If a path is found, the circle is completed with the removed edge
    for k, v in matching.items():
        if not tmp_graph.has_edge(k, v):
            # The graph could have been reduced
            continue
        tmp_graph.remove_edge(k, v)
        try:
            path = shortest_path(G=tmp_graph, source=v, target=k)
        except nx.NetworkXNoPath:
            tmp_graph.add_edge(k, v)
            continue
        else:
            tmp_graph.add_edge(k, v)
            return cast(List[Any], path)
    # No cycle was found
    raise nx.NetworkXNoCycle
示例#6
0
def make_candidate_path_graph(drop_poles, candidate_segment_cost_graph):
    g = nx.Graph()
    for pole1, pole2 in combinations(drop_poles, 2):
        pole1_id = pole1.id
        pole2_id = pole2.id
        pole1_xyz = pole1.geometry.coords[0]
        pole2_xyz = pole2.geometry.coords[0]
        line_coords = shortest_path(candidate_segment_cost_graph,
                                    pole1_xyz,
                                    pole2_xyz,
                                    weight='cost')
        line_cost = shortest_path_length(candidate_segment_cost_graph,
                                         pole1_xyz,
                                         pole2_xyz,
                                         weight='cost')
        g.add_edge(pole1_id,
                   pole2_id,
                   id='%s-%s' % (pole1_id, pole2_id),
                   path_type=None,
                   geometry=LineString(line_coords),
                   cost=line_cost)
    return g
示例#7
0
 def shortest_path(self, from_node, to_node):
     path = shortest_path(self.reachability, from_node, to_node)
     return path
示例#8
0
def compose_join(network,
                 loa_name,
                 table_name,
                 column_name,
                 loa_index_columns,
                 agg_fn="avg"):
    """
    compose_join

    Creates a list of operations that can be applied to a Query object, making
    it retrieve data at a certain LOA

    :param network: A networkx graph representing a database
    :param loa_name: The name of the LOA to retrieve data at
    :param table_name: The name of the table from which to retrieve the data 
    :param column_name: The name of the column to retrieve 
    :param agg_fn: If the retrieval op. needs to aggregate data, if will do so with this function
    :returns: An iterator containing functions to be applied to a Query object 
    :raises QueryError: If table_name.column_name does not exist in the DB 
    :raises ConfigError: If the requested loa is not configured  
    """

    lookup = {tbl.name: tbl for tbl in network}
    get_col_ref = lambda tbl, name: lookup[tbl].c[name]  #.label(tbl+"_"+name)

    loa_table = lookup[loa_name]

    try:
        column_ref = get_col_ref(table_name, column_name)
    except KeyError as ke:
        raise exceptions.QueryError(
            f"{table_name}.{column_name} not found") from ke

    index_columns_ref = []
    for idx_table_name, idx_column_name in loa_index_columns:
        try:
            index_columns_ref.append(
                get_col_ref(idx_table_name, idx_column_name))
        except KeyError as ke:
            raise exceptions.ConfigError(
                f"Index column for {loa_table}"
                f" {idx_table_name}.{idx_column_name} not found")

    all_columns = list(set(index_columns_ref + [column_ref]))
    names = [c.table.name + "_" + c.name for c in all_columns]
    aggregates = False

    # Compute joins (+ agg)
    join = []
    joined = set()
    for idx, c in enumerate(all_columns):
        try:
            path = shortest_path(network, loa_table, c.table)
        except NetworkXNoPath:
            aggregates = True
            path = shortest_path(network, c.table, loa_table)
            path.reverse()
            all_columns[idx] = getattr(sa.func, agg_fn)(c)
            names[idx] = names[idx] + "_" + agg_fn

        prev = loa_table
        for table in path[1:]:
            if table not in joined:
                try:
                    con = network[prev][table]
                    join.append(
                        class_partial("join", table,
                                      con["reference"] == con["referent"]))
                except KeyError:
                    con = network[table][prev]
                    join.append(
                        class_partial("join", table,
                                      con["referent"] == con["reference"]))
                joined = joined.union({table})
            else:
                pass
            prev = table

    # Selects
    all_columns = [col.label(name) for col, name in zip(all_columns, names)]
    select = [class_partial("add_columns", col) for col in all_columns]

    # Aggregation
    if aggregates:
        group_by = [class_partial("group_by", c) for c in index_columns_ref]
    else:
        group_by = []

    logger.debug("%s selects", len(select))
    logger.debug("%s joins", len(join))
    logger.debug("%s groupbys", len(group_by))

    return chain(select, [class_partial("select_from", loa_table)], join,
                 group_by)
示例#9
0
 def shortest_path_to_destination(self, origin: Location,
                                  destination: Location) -> List[Location]:
     path: List[Tuple[int]] = shortest_paths.shortest_path(
         self._graph, origin.coordinates, destination.coordinates)
     return [Location(node[0], node[1]) for node in path]
示例#10
0
import networkx as nx
from networkx.algorithms.shortest_paths import shortest_path

with open("input.txt") as input_file:
    lines = input_file.readlines()

g = nx.DiGraph()

for line in lines:
    if ")" not in line:
        continue
    t, f = line.strip().split(")")
    g.add_edge(f, t)

orbits = 0

for node in g.nodes:
    if node == "COM":
        continue
    path = shortest_path(g, node, "COM")
    orbits += len(path) - 1

print(orbits)
 def fails():
     shortest_path(network, table_one, table_two)
示例#12
0
import networkx as nx
from networkx.algorithms.shortest_paths import shortest_path

with open("input.txt") as input_file:
    lines = input_file.readlines()

g = nx.Graph()

for line in lines:
    if ")" not in line:
        continue
    t, f = line.strip().split(")")
    g.add_edge(f, t)

orbits = 0

path = shortest_path(g, "YOU", "SAN")
steps = len(path)-3

print(path)
print(steps)