Ejemplo n.º 1
0
 def test_simple_weight(self, weight):
     """Weight is one constant function"""
     if weight < 0:
         with raises(ValueError):
             find_path(self.edges_low, 1, 4, lambda u, v, data: weight)
     elif weight > 0:
         result = find_path(self.edges_low, 1, 4, lambda u, v, data: weight)
         assert result == (2 * weight, [1, 2, 4])
Ejemplo n.º 2
0
 def test_individual_weight(self, weight):
     """Weight is attribute in edges"""
     edges = {
         k: {target: {
             'weight': weight
         }
             for target in d}
         for k, d in self.edges_low.items()
     }
     if weight < 0:
         with raises(ValueError):
             find_path(edges, 1, 4)
     elif weight > 0:
         result = find_path(edges, 1, 4)
         assert result == (2 * weight, [1, 2, 4])
Ejemplo n.º 3
0
    def read_timeline(self, edgearray) -> list:
        """
        Read from td_node_status and the edearray to
        - create the timeline of the solving process
        - construct the path and solution-tables used during solving.

        Parameters
        ----------
        edgearray : array of pairs of bagids
            Representing the tree-like structure between all bag-ids.
            It is assumed that all ids are included in this array.
            Example: [(2, 1), (3, 2), (4, 2), (5, 4)]

        Returns
        -------
        result : array
            array of bagids and eventually solution-tables.

        """
        with self.connection.cursor() as cur:  # create a cursor
            timeline = list()
            adj = convert_to_adj(edgearray) if self.intermed_nodes else {}
            cur.execute(
                f"SELECT node FROM public.p{self.problem}_td_node_status ORDER BY start_time"
            )
            order_solved = list(flatten(cur.fetchall()))
            # tour sol -> through result nodes along the edges

            if self.intermed_nodes:
                last = order_solved[-1]
                startpath = find_path(adj, last, order_solved[0])
                timeline = [[bag] for bag in startpath[1]]
            else:
                timeline.append([order_solved[0]])
            # add the other bags in order_solved to the timeline
            last = order_solved[0]
            for bag in order_solved:
                if self.intermed_nodes:
                    path = find_path(adj, last, bag)
                    for intermed in path[1][1:]:
                        timeline.append([intermed])
                # query column names
                #  deepcode ignore Sqli: general query, inserting integers
                cur.execute(
                    "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS "
                    f"WHERE TABLE_NAME = 'p{self.problem}_td_node_{bag}'")
                column_names = list(flatten(cur.fetchall()))
                LOGGER.debug("column_names %s", column_names)
                # get solutions
                #  deepcode ignore Sqli: general query, inserting integers
                cur.execute(
                    f"SELECT * FROM public.p{self.problem}_td_node_{bag}")
                solution_raw = cur.fetchall()
                LOGGER.debug("solution_raw %s", solution_raw)
                # check for nulled variables - assuming whole columns are
                # nulled:
                columns_notnull = [
                    column_names[i] for i, x in enumerate(solution_raw[0])
                    if x is not None
                ]
                solution = [
                    bag,
                    [[
                        columns_notnull,
                        *[[int(v) for v in row if v is not None]
                          for row in solution_raw]
                    ], "sol bag " + str(bag),
                     self.footer(solution_raw), True]
                ]
                timeline.append(solution)
                last = bag
            return timeline
Ejemplo n.º 4
0
    def read_timeline(self, edgearray) -> list:
        """
        Read from td_node_status and the edearray to
        - create the timeline of the solving process
        - construct the path and solution-tables used during solving.

        Parameters
        ----------
        edgearray : array of pairs of bagids
            Representing the tree-like structure between all bag-ids.
            It is assumed that all ids are included in this array.
            Example: [(2, 1), (3, 2), (4, 2), (5, 4)]

        Returns
        -------
        result : array
            array of bagids and eventually solution-tables.

        """
        with self.connection.cursor() as cur:  # create a cursor
            timeline = list()
            adj = convert_to_adj(edgearray) if self.intermed_nodes else {}
            order_solved = list(
                flatten(query_td_node_status_ordered(cur, self.problem)))
            # tour sol -> through result nodes along the edges

            if self.intermed_nodes:
                last = order_solved[-1]
                startpath = find_path(adj, last, order_solved[0])
                timeline = [[bag] for bag in startpath[1]]
            else:
                timeline.append([order_solved[0]])
            # add the other bags in order_solved to the timeline
            last = order_solved[0]
            for bag in order_solved:
                if self.intermed_nodes:
                    path = find_path(adj, last, bag)
                    for intermed in path[1][1:]:
                        timeline.append([intermed])
                # query column names
                column_names = list(
                    flatten(query_column_name(cur, self.problem, bag)))
                LOGGER.debug("column_names %s", column_names)
                # get solutions
                solution_raw = query_bag(cur, self.problem, bag)
                LOGGER.debug("solution_raw %s", solution_raw)
                # check for nulled variables - assuming whole columns are
                # nulled:
                columns_notnull = [
                    column_names[i] for i, x in enumerate(solution_raw[0])
                    if x is not None
                ]
                solution = [
                    bag,
                    [[
                        columns_notnull,
                        *[[int(v) for v in row if v is not None]
                          for row in solution_raw]
                    ], "sol bag " + str(bag),
                     self.footer(solution_raw), True]
                ]
                timeline.append(solution)
                last = bag
            return timeline
Ejemplo n.º 5
0
 def test_source_not_in_graph(self):
     """Should raise ValueError"""
     with raises(ValueError):
         find_path(self.edges_low, -1, 4)
Ejemplo n.º 6
0
 def test_empty_graph(self, source, target):
     """Empty graph should raise Value Error."""
     with raises(ValueError):
         find_path({}, source, target)
Ejemplo n.º 7
0
 def test_length0(self, arg):
     """Staying on one node."""
     result = find_path(arg, 1, 1)
     assert result == (0, [1])
Ejemplo n.º 8
0
 def test_normal_path(self):
     """Can find a short path."""
     result = find_path(self.edges_low, 1, 4)
     assert result == (2, [1, 2, 4])
Ejemplo n.º 9
0
 def test_no_path(self):
     """Should raise ValueError"""
     with raises(DijkstraNoPath):
         find_path({**self.edges_low, **self.edges_high}, 1, 10)
Ejemplo n.º 10
0
 def test_target_not_in_graph(self):
     """Should raise ValueError"""
     with raises(ValueError):
         find_path(self.edges_low, 1, -4)