Example #1
0
    def return_alg_sol(algorithm: str):
        # MyClass = MaxFlowGraphs
        # method_list = [attribute for attribute in dir(MyClass) if callable(getattr(MyClass, attribute)) and attribute.startswith('__') is False]
        method_list = inspect.getmembers(MaxFlowGraphs,
                                         predicate=inspect.isfunction)

        mfg = MaxFlowGraphs()

        sol = []
        for func in method_list:
            try:
                edgeDict, data = func[1](mfg)
                myGraph = GraphFactory.create_graph("Generic",
                                                    edge_dict=edgeDict,
                                                    vertex_dict=None,
                                                    graph_type="directed",
                                                    deep_copy=False)
                mf = MaxFlow(myGraph, source=data['source'], sink=data['sink'])
                mf.run(algorithm)
                sol.append([mf.maxFlowVal, mf.minCutVal])
            except Exception as e:
                e.message = "Failed at: " + func[0]
                raise

        return sol
    def test_max_flow_with_fordfulkerson_edkarp_infinity_1(self):
        # Define some edges       
        edgeDict = {('r', 'a'): {"cap": 2},
                    ('r', 'b'): {"cap": 4},
                    ('r', 'c'): {"cap": 3},
                    ('r', 'd'): {"cap": 2},
                    ('e', 's'): {"cap": 7},
                    ('f', 's'): {"cap": 1},
                    ('g', 's'): {"cap": 3},
                    ('h', 's'): {"cap": 1},
                    ('a', 'e'): {"cap": INF},
                    ('b', 'a'): {"cap": INF},
                    ('b', 'c'): {"cap": INF},
                    ('c', 'd'): {"cap": INF},
                    ('c', 'f'): {"cap": INF},
                    ('f', 'g'): {"cap": INF},
                    ('d', 'g'): {"cap": INF},
                    ('h', 'd'): {"cap": INF},
                    }

        myGraph = GraphFactory.create_graph("Generic", edge_dict=edgeDict, vertex_dict=None, graph_type="directed", deep_copy=False)

        mf = MaxFlow(myGraph)
        self.assertRaises(ValueError, mf.run)

        # Create mf object and set source + sink
        mf = MaxFlow(myGraph)
        mf.set_source('r')
        mf.set_sink('s')

        # execute
        mf.run()

        # Test min-cut and max-flow values
        self.assertEqual(mf.maxFlowVal, mf.minCutVal)
    def test_max_flow_with_fordfulkerson_edkarp_complex(self):
        # Define some edges
        edgeDict = {('r','p'): {"cap": 6},
                    ('r','a'): {"cap": 9},
                    ('r','q'): {"cap": 4},
                    ('p','b'): {"cap": 3},
                    ('p','q'): {"cap": 2},
                    ('q','p'): {"cap": 1},
                    ('q','b'): {"cap": 2},
                    ('q','d'): {"cap": 6},
                    ('b','a'): {"cap": 1},
                    ('b','s'): {"cap": 8},
                    ('a','c'): {"cap": 8},
                    ('a','d'): {"cap": 1},
                    ('c','q'): {"cap": 1},
                    ('c','b'): {"cap": 2},
                    ('c','s'): {"cap": 4},
                    ('d','c'): {"cap": 1},
                    ('d','s'): {"cap": 6},
                    }

        myGraph = GraphFactory.create_graph("Generic", edge_dict=edgeDict, vertex_dict=None, graph_type="directed", deep_copy=False)

        # either is valid
        mf = MaxFlow(myGraph, source = 's', sink='t')

        mf = MaxFlow(myGraph)
        mf.set_source('r')
        mf.set_sink('s')

        mf.run()
        
        # Test min-cut and max-flow values
        self.assertEqual(mf.maxFlowVal, mf.minCutVal)
    def test_max_flow_with_fordfulkerson_edkarp_simple_3(self):
        # Define some edges       
        edgeDict = {('S', 'A'): {"cap": 4},
                    ('S', 'B'): {"cap": 2},
                    ('A', 'C'): {"cap": 3},
                    ('B', 'C'): {"cap": 2},
                    ('B', 'D'): {"cap": 3},
                    ('C', 'B'): {"cap": 1},
                    ('C', 'T'): {"cap": 2},
                    ('D', 'T'): {"cap": 4},
                    }

        myGraph = GraphFactory.create_graph("Generic", edge_dict=edgeDict, vertex_dict=None, graph_type="directed", deep_copy=False)

        # Test undefined sink, source error
        mf = MaxFlow(myGraph)
        self.assertRaises(ValueError, mf.run)

        # either is valid
        # mf = MaxFlow(myGraph, source='S', sink='T')

        # or this
        mf = MaxFlow(myGraph)
        mf.set_source('S')
        mf.set_sink('T')

        # execute
        mf.run()

        # Test max flow value
        self.assertEqual(myGraph.edge_dict[('S','A')]['flow']+myGraph.edge_dict[('S','B')]['flow'], 5)

        # Test min-cut and max-flow values
        self.assertEqual(mf.maxFlowVal, mf.minCutVal)
    def test_create_square_grid_obs_list(self):
        # Spec out our squareGrid
        minX = -15  # [m]
        maxX = 15
        minY = -15
        maxY = 15
        grid = None  # pre-existing 2d numpy array?
        grid_size = 1  # grid fineness[m]
        grid_dim = [minX, maxX, minY, maxY]
        neighbor_type = 8  # neighbor type

        # Create a squareGrid using GraphFactory
        sq = GraphFactory.create_graph("OccupancySquareGrid",
                                       grid=grid,
                                       grid_dim=grid_dim,
                                       grid_size=grid_size,
                                       neighbor_type=neighbor_type)

        # test to see if sq is an instance of SquareGrid
        self.assertTrue("OccupancySquareGrid" in str(type(sq)))

        # test if instance values are correct
        self.assertEqual(sq.grid_size, grid_size)
        self.assertEqual(sq.grid_dim, grid_dim)
        self.assertEqual(sq.neighbor_type, neighbor_type)

        # Define obstacles (physical coordinates, origin is lower-left)
        obstacles = [(x, 0) for x in range(-10, 10, 1)]
        obstacles.extend([(0, y) for y in range(-10, 10, 1)])

        # We can either add obstacles using 'set_obstacle' method, or do it with GraphFactory
        sq.set_obstacles(obstacles)

        # Show image (comment this out if it blocks)
        sq.show_grid()
    def test_max_flow_with_fordfulkerson_edkarp_simple_1(self):

        #             +---------+             
        #      +------>         |-------+     
        #    3 |      |    1    |       |2    
        #      |      +---------+       |     
        # +---------+      |       +----v----+
        # |         |      |       |         |
        # |   s     |    5 |       |    t    |
        # +---------+      |       +----^----+
        #      |      +----v----+       |     
        #    2 |      |         |       |3    
        #      +------>    2    |-------+     
        #             +---------+   
        # 
        #   Define some edges         
        edgeDict = {('s','1'): {"cap": 3},
                    ('s','2'): {"cap": 2},
                    ('1','2'): {"cap": 5},
                    ('1','t'): {"cap": 2},
                    ('2','t'): {"cap": 3},
                    }

        myGraph = GraphFactory.create_graph("Generic", edge_dict=edgeDict, vertex_dict=None, graph_type="directed", deep_copy=False)

        # Test undefined sink, source error
        mf = MaxFlow(myGraph)
        self.assertRaises(ValueError, mf.run)

        # either is valid
        mf = MaxFlow(myGraph, source = 's', sink='t')

        mf = MaxFlow(myGraph)
        mf.set_source('s')
        mf.set_sink('t')

        mf.run()

        # test solution
        self.assertEqual(myGraph.edge_dict[('s','1')]['flow'], 3)
        self.assertEqual(myGraph.edge_dict[('s','2')]['flow'], 2)
        self.assertEqual(myGraph.edge_dict[('1','2')]['flow'], 1)
        self.assertEqual(myGraph.edge_dict[('1','t')]['flow'], 2)
        self.assertEqual(myGraph.edge_dict[('2','t')]['flow'], 3)

        # Test min-cut and max-flow values
        self.assertEqual(mf.maxFlowVal, mf.minCutVal)
Example #7
0
    def __init__(self, G, source=None, sink=None):
        # construct Gf, the residual graph.
        self.G = G
        self.Gf = GraphFactory.create_graph("Generic",
                                            edge_dict=G.edge_dict,
                                            vertex_dict=None,
                                            graph_type="undirected",
                                            deep_copy=True)
        self.source = source
        self.sink = sink
        # Add flow to edges
        for val in self.G.edge_dict.values():
            val["flow"] = 0

        # Variables defined at termination
        self.maxFlowVal = None
        self.minCutVal = 0
        self.minCutSet = {}
        self.reachSet = None
    def test_occupancy_square_grid_best_first_search(self):
        # Spec out our squareGrid
        minX = -15  # [m]
        maxX = 15
        minY = -15
        maxY = 15
        grid = None  # pre-existing 2d numpy array?
        grid_size = 1  # grid fineness[m]
        grid_dim = [minX, maxX, minY, maxY]
        neighbor_type = 8  # neighbor type

        # Create a squareGrid using GraphFactory
        sq = GraphFactory.create_graph("OccupancySquareGrid",
                                       grid=grid,
                                       grid_dim=grid_dim,
                                       grid_size=grid_size,
                                       neighbor_type=neighbor_type)

        # Create BFS object, with A*star
        bfs = BestFirstSearch(graph=sq,
                              start=(-15, -15),
                              goal=(15, 15),
                              heuristic_type='diagonal_nonuniform',
                              visualize=False)
        parent_astar, cost_so_far_astar = bfs.run()

        # Create BFS object with Dijkstra
        bfs = BestFirstSearch(graph=sq,
                              start=(-15, -15),
                              goal=(15, 15),
                              heuristic_type=None,
                              visualize=False)
        parent_dijkstra, cost_so_far_dijkstra = bfs.run()

        # assert size of cost_so_far
        self.assertGreaterEqual(len(cost_so_far_dijkstra),
                                len(cost_so_far_astar))

        # shortest path val should be the same
        self.assertEqual(cost_so_far_astar[(15, 15)],
                         cost_so_far_dijkstra[(15, 15)])
    def test_max_flow_with_fordfulkerson_edkarp_simple_2(self):
        # Define some edges       
        edgeDict = {(0, 1): {"cap": 16},
                    (0, 2): {"cap": 13},
                    (1, 2): {"cap": 10},
                    (1, 3): {"cap": 12},
                    (2, 1): {"cap": 4},
                    (2, 4): {"cap": 14},
                    (3, 2): {"cap": 9},
                    (3, 5): {"cap": 20},
                    (4, 3): {"cap": 7},
                    (4, 5): {"cap": 4},
                    }

        myGraph = GraphFactory.create_graph("Generic", edge_dict=edgeDict, vertex_dict=None, graph_type="directed", deep_copy=False)

        # Test undefined sink, source error
        mf = MaxFlow(myGraph)
        self.assertRaises(ValueError, mf.run)

        # either is valid
        mf = MaxFlow(myGraph, source=0, sink=5)

        # or this
        mf = MaxFlow(myGraph)
        mf.set_source(0)
        mf.set_sink(5)

        # execute
        mf.run()
        
        # Test max flow value
        self.assertEqual(myGraph.edge_dict[(0,1)]['flow']+myGraph.edge_dict[(0,2)]['flow'], 23)

        # Test min-cut and max-flow values
        self.assertEqual(mf.maxFlowVal, mf.minCutVal)
    def test_create_generic_undirected(self):

        # Define some edges
        edgeDict = {
            ('v1', 'v2'): 1,
            ('v2', 'v3'): 1,
            ('v3', 'v4'): 1,
            ('v4', 'v5'): 1,
            ('v5', 'v6'): 1,
            ('v6', 'v7'): 1,
            ('v7', 'v8'): 1,
            ('v8', 'v5'): 1
        }

        vertexDict = {
            'v9': 1,
            'v10': 2,
            'v11': 3,
            'v12': 4,
            'v13': 5,
            'v14': 6
        }

        # Create a generic graph using factory method
        genG = GraphFactory.create_graph("Generic",
                                         edge_dict=edgeDict,
                                         vertex_dict=vertexDict,
                                         graph_type="undirected",
                                         deep_copy=True)

        # test to see if genG is an instance of "GenericGraph"
        self.assertTrue("GenericGraph" in str(type(genG)))

        # test accessing edges
        ew = genG.cost('v1', 'v2')
        self.assertEqual(ew, 1)

        # test accesing vertices
        vw = genG.cost('v14')
        self.assertEqual(vw, 6)

        # Test removal of edges. Should return a KeyError
        genG.remove_edges([('v1', 'v2')])
        genG.remove_edges([('v8', 'v5')])
        self.assertRaises(KeyError, genG.cost, 'v1', 'v2')
        self.assertRaises(KeyError, genG.cost, 'v8', 'v5')

        # Test removal of vertix 14. Should return a KeyError
        genG.remove_vertices(['v14'])
        self.assertRaises(KeyError, genG.cost, 'v14')

        # Test getting list of vertices. v14 just got removed
        self.assertEquals(
            set(genG.get_vertices()),
            set([
                'v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v9', 'v10',
                'v11', 'v12', 'v13'
            ]))

        # try assigning a value to v1
        genG.add_vertex({'v1': 100})

        # try adding new edges from v1 and add back node v14
        genG.add_edge({('v1', 'v9'): 19, ('v10', 'v14'): 1010})
    def test_create_generic_mat2dict(self):
        # create a 6x6 matrix
        mat = [[0 for i in range(6)] for j in range(6)]
        # define edges
        mat[0][1] = {"cap": 16}
        mat[0][2] = {"cap": 13}
        mat[1][3] = {"cap": 12}
        mat[1][2] = {"cap": 10}
        mat[2][1] = {"cap": 4}
        mat[2][4] = {"cap": 14}
        mat[3][2] = {"cap": 9}
        mat[3][5] = {"cap": 20}
        mat[4][3] = {"cap": 7}
        mat[4][5] = {"cap": 4}

        # Create generic graph
        genG = GraphFactory.create_graph("Generic",
                                         edge_dict=None,
                                         vertex_dict=None,
                                         deep_copy=False)

        # use helper method to turn mat into a dict
        edgeDict1 = genG.mat_to_dict(mat)

        # Define some edges (see test_network_flow simple2)
        edgeDict2 = {
            (0, 1): {
                "cap": 16
            },
            (0, 2): {
                "cap": 13
            },
            (1, 2): {
                "cap": 10
            },
            (1, 3): {
                "cap": 12
            },
            (2, 1): {
                "cap": 4
            },
            (2, 4): {
                "cap": 14
            },
            (3, 2): {
                "cap": 9
            },
            (3, 5): {
                "cap": 20
            },
            (4, 3): {
                "cap": 7
            },
            (4, 5): {
                "cap": 4
            },
        }
        self.assertEqual(edgeDict1, edgeDict2)

        # Try adding vertices to empty genG
        genG.add_edge(edgeDict1)

        self.assertEqual(genG.edge_dict, edgeDict2)

        # Try adding vertices to empty genG
        vertex_dict = {0: 100, 5: 99}
        genG.add_vertex(vertex_dict)

        pass
    def test_generic_graph_attribute_vertices_only(self):
        # Define edges, but give them a name
        vertexDict = {
            ('r', 'p'): {
                "cap": 6,
                "flow": 0
            },
            ('r', 'a'): {
                "cap": 1,
                "flow": 0
            },
            ('r', 'q'): {
                "cap": 4,
                "flow": 0
            },
            ('p', 'b'): {
                "cap": 3,
                "flow": 0
            },
            ('p', 'q'): {
                "cap": 2,
                "flow": 0
            },
            ('q', 'p'): {
                "cap": 1,
                "flow": 0
            },
            ('q', 'b'): {
                "cap": 2,
                "flow": 0
            },
            ('q', 'd'): {
                "cap": 6,
                "flow": 0
            },
        }

        # Try deleting specific edges
        genG = GraphFactory.create_graph("Generic",
                                         edge_dict=None,
                                         vertex_dict=vertexDict,
                                         deep_copy=False)

        # Try adding additional keys. WARNING: existing keys will get overwritten!
        new_vertices = {
            ('b', 'a'): {
                "cap": 1,
                "flow": 0
            },
            ('b', 's'): {
                "cap": 8,
                "flow": 0
            },
            ('a', 'c'): {
                "cap": 8,
                "flow": 0
            },
            ('a', 'd'): {
                "cap": 1,
                "flow": 0
            },
            ('c', 'q'): {
                "cap": 1,
                "flow": 0
            },
            ('c', 'b'): {
                "cap": 2,
                "flow": 0
            },
            ('c', 's'): {
                "cap": 4,
                "flow": 0
            },
            ('d', 'c'): {
                "cap": 1,
                "flow": 0
            },
            ('d', 's'): {
                "cap": 6,
                "flow": 0
            },
        }
        genG.add_vertex(new_vertices)

        # test to see if genG is an instance of "GenericGraph"
        self.assertTrue("GenericGraph" in str(type(genG)))

        # There should be 17 nodes
        self.assertEqual(genG.node_count(), 17)

        # Try getting nested weight names
        for v in vertexDict:
            val = genG.cost(v, name="cap")
            self.assertEqual(val, vertexDict[v]["cap"])

        # Try deleting edges
        remove_list = [('b', 'a'), ('b', 's'), ('a', 'c')]
        genG.remove_vertices(remove_list)

        # removed edges should not be in the graph. Test for error raise
        for v in remove_list:
            self.assertRaises(KeyError, genG.cost, v, name="cap")

        # add deep nested edge names. WARNING: existing keys will get overwritten!
        nested_vertex = {('r', 'p'): {"level1": {"level2": {"level3": 300}}}}
        genG.add_vertex(nested_vertex)

        # Try getting nested_edge value
        self.assertEqual(
            genG.cost(('r', 'p'), name=["level1", "level2", "level3"]), 300)

        # Try getting only level 1
        self.assertEqual(genG.cost(('r', 'p'), name="level1"),
                         {'level2': {
                             'level3': 300
                         }})

        # Try getting only level 1 as a list
        self.assertEqual(genG.cost(('r', 'p'), name=["level1"]),
                         {'level2': {
                             'level3': 300
                         }})

        # Checking for any neighbors should raise KeyError
        self.assertRaises(KeyError, genG.neighbors, ('r', 'p'))