示例#1
0
 def __init__(self, master, **kwargs):
     super().__init__(master, **kwargs)
     self.master = master
     self._image = None
     self._image_data = None
     self._fourier = None
     self._gray_scale = None
     self.rowconfigure(0, weight=1)
     self.columnconfigure(0, weight=1)
     self.canvas = Graph(self)
示例#2
0
 def __init__(self, first_node):
     '''
     '''
     Graph.__init__(self)
     
     self.travel_partition(first_node)
     self.shape_violation=None
     self.rule_shapes=None
     self.solution_shapes=[]
     self.total_rule_shape_points=0
     self.color_violation=None
     self.sun_violation=None
示例#3
0
    def __init__(self, first_node):
        '''
        '''
        Graph.__init__(self)

        self.travel_partition(first_node)
        self.shape_violation = None
        self.rule_shapes = None
        self.solution_shapes = []
        self.total_rule_shape_points = 0
        self.color_violation = None
        self.sun_violation = None
    def __init__(self, gx, gy, is_outer=True, auto_assign_edges=True):
        # TODO: Ugh, everything is turning into RectGridGraph :(
        self.gx = gx
        self.gy = gy
        Graph.__init__(self)
        
        self.is_outer = is_outer

        # Create the list of Nodes
        node_list = []
        for y in range(gy):
            for x in range(gx):
                #print (x,y)
                # "Outer" vs "Inner" Nodes have different behaviour, though currently Inner is a sub-class
                if self.is_outer:
                    n = GridNode(x, y, gx, gy)
                else:
                    n = GridSquare(x, y, gx, gy)
                node_list.append(n)

        self.set_nodes(node_list)

        ''' Setup a list of sorted keys for when we want to iterate in order
        The sort key is just the GridNode vector reversed (y,x) so that we can return
        the lowest row left-right then continue up.
        '''
        self.sorted_keys = sorted(self.keys(), key=lambda k: (k[1], k[0]))
        
        # Assign 90 degree Edges to all nodes
        # TODO: Move this out of __init__
        if auto_assign_edges:
            self.assign_edges()

        '''BEGIN: Outer-Grid specific setup '''
        if is_outer == True:
            
            
            # initialize the "inner squares" grid
            self.inner_grid = RectGridGraph(gx - 1, gy - 1, is_outer=False, auto_assign_edges=auto_assign_edges)
            # TODO: Move this out of __init__
            if auto_assign_edges:
                self.associate_outer_to_inner()
                # some paths are best avoided...
                self.remove_path_dead_ends()
            
            # Assign each GridNode a unique symbol (if possible) within this
            # Graph
            self.assign_symbols()

        '''END: Outer-Grid specific setup '''
示例#5
0
    def bootUp(self, m):
        """ Bootstrap Graph With Millenium Falcon Data. """

        self.m_falcon = self.fetch(m)

        self.graph = Graph(self.m_falcon['autonomy'])

        for item in self.m_falcon['routes']:
            # this creates both the vertices and edges
            # skip routes with travelTime > autonomy ??? => skip un-walkable paths
            if item['travelTime'] > self.m_falcon['autonomy']:
                break

            self.graph.add_edge(item['origin'], item['destination'],
                                item['travelTime'])

        self.resource_limit = self.m_falcon['autonomy']
示例#6
0
    def test_output_9(self):
        # The length of the shortest route (in terms of distance to travel) from B to B.
        graph_routesBB = Graph()
        graph_routesBB.build_graph(self.list_routes)
        graph_routesBB.path_list = graph_routesBB.build_path_list('B', 'B')
        value = graph_routesBB.shortest_path()

        self.assertEqual(9, value)
示例#7
0
    def test_output_1(self):
        # The distance of the route A-D.
        graph_routesAC = Graph()
        graph_routesAC.build_graph(self.list_routes)
        graph_routesAC.path_list = graph_routesAC.build_path_list('A', 'C')
        value = graph_routesAC.find_path_size(["A", "B", "C"])

        self.assertEqual(9, value)
示例#8
0
    def test_output_8(self):
        # The length of the shortest route (in terms of distance to travel) from A to C.
        graph_routesAC = Graph()
        graph_routesAC.build_graph(self.list_routes)
        graph_routesAC.path_list = graph_routesAC.build_path_list('A', 'C')
        value = graph_routesAC.shortest_path()

        self.assertEqual(9, value)
示例#9
0
    def test_output_5(self):
        # The distance of the route A-E-D.
        graph_routesAD = Graph()
        graph_routesAD.build_graph(self.list_routes)
        graph_routesAD.path_list = graph_routesAD.build_path_list('A', 'D')
        value = graph_routesAD.find_path_size(["A", "E", "D"])

        self.assertEqual('NO SUCH ROUTE', value)
示例#10
0
    def test_output_4(self):
        # The distance of the route A-E-B-C-D.
        graph_routesAD = Graph()
        graph_routesAD.build_graph(self.list_routes)
        graph_routesAD.path_list = graph_routesAD.build_path_list('A', 'D')
        value = graph_routesAD.find_path_size(["A", "E", "B", "C", "D"])

        self.assertEqual(22, value)
示例#11
0
    def test_output_10(self):
        # The number of different routes from C to C with a distance of less than 30.  In the sample data, the trips
        # are: CDC, CEBC, CEBCDC, CDCEBC, CDEBC, CEBCEBC, CEBCEBCEBC.
        graph_routesCC = Graph()
        graph_routesCC.build_graph(self.list_routes)
        graph_routesCC.path_list = graph_routesCC.build_path_list(
            'C', 'C', max_distance=30)
        value = graph_routesCC.number_routes()

        self.assertEqual(7, value)
示例#12
0
class Image(tk.Frame):
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)
        self.master = master
        self._image = None
        self._image_data = None
        self._fourier = None
        self._gray_scale = None
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)
        self.canvas = Graph(self)

    def show(self):
        self.canvas.image(self.get_data(), 'gray')
        self.canvas.grid(row=0, column=0, sticky="wens")

    def open_image(self, image):
        self._image = PILImage.open(image)
        self.size = self._image.size
        self._image_data = np.array(self._image)

    def set_image(self, data):
        self._image = PILImage.fromarray(data)
        self._image_data = data
        self._fourier = None

    def get_data(self):
        return self._image_data

    def get_fourier(self):
        if self._fourier is None:
            self._fourier = Fourier.fast2d(self.get_data())
        return self._fourier

    def get_gray(self):
        if self._gray_scale is None:
            self._gray_scale = ImageOps.grayscale(self._image)
        return self._gray_scale
示例#13
0
    def test_output_7(self):
        # The number of trips starting at A and ending at C with exactly 4 stops.  In the sample data below,
        # there are three such trips: A to C (via B,C,D); A to C (via D,C,D); and A to C (via D,E,B).
        graph_routesAC4 = Graph()
        graph_routesAC4.build_graph(self.list_routes)
        graph_routesAC4.path_list = graph_routesAC4.build_path_list(
            'A', 'C', path_stop=4)
        value = len(graph_routesAC4.path_list)

        self.assertEqual(3, value)
示例#14
0
    def test_output_6(self):
        # The number of trips starting at C and ending at C with a maximum of 3 stops.  In the sample data below,
        # there are two such trips: C-D-C (2 stops). and C-E-B-C (3 stops).
        graph_routesCC3 = Graph()
        graph_routesCC3.build_graph(self.list_routes)
        graph_routesCC3.path_list = graph_routesCC3.build_path_list(
            'C', 'C', max_path_stop=3)
        value = len(graph_routesCC3.path_list)

        self.assertEqual(2, value)
示例#15
0
from lib.Graph import Graph

list_routes = input("Input the routes.(Example: 'AB5, BC4, CD8'):")
#list_routes = "AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7"

graph_routesAC = Graph()
graph_routesAC.build_graph(list_routes)
graph_routesAC.path_list = graph_routesAC.build_path_list('A', 'C')

graph_routesAD = Graph()
graph_routesAD.build_graph(list_routes)
graph_routesAD.path_list = graph_routesAC.build_path_list('A', 'D')

##############################################################################################################

size = graph_routesAC.find_path_size(["A", "B", "C"])
print('Output #1:', size)

##############################################################################################################

size = graph_routesAD.find_path_size(["A", "D"])
print('Output #2:', size)

##############################################################################################################

size = graph_routesAC.find_path_size(["A", "D", "C"])
print('Output #3:', size)

##############################################################################################################

size = graph_routesAD.find_path_size(["A", "E", "B", "C", "D"])
示例#16
0
class C3PO:

    countdown = 0
    resource_limit = 0
    """ Class C3PO. """
    def __init__(self, milleniumFalconJsonFile):
        """
						Class Constructor: Sets Millenium Falcon Travel Parameters
						@Parameters milleniumFalconJsonFile JSON File
		"""
        self.bootUp(milleniumFalconJsonFile)

    def bootUp(self, m):
        """ Bootstrap Graph With Millenium Falcon Data. """

        self.m_falcon = self.fetch(m)

        self.graph = Graph(self.m_falcon['autonomy'])

        for item in self.m_falcon['routes']:
            # this creates both the vertices and edges
            # skip routes with travelTime > autonomy ??? => skip un-walkable paths
            if item['travelTime'] > self.m_falcon['autonomy']:
                break

            self.graph.add_edge(item['origin'], item['destination'],
                                item['travelTime'])

        self.resource_limit = self.m_falcon['autonomy']

    def mapEmpirePath(self, empire):
        """
						Convert Empire Path To Dict With
						Planets As Keys of Days of Presence in List i.e. {'Hoth': [6, 7, 8]}
		"""
        self.countdown = empire['countdown']
        self.empirePath = {}
        for item in empire['bounty_hunters']:
            planet = item['planet']
            day = item['day']
            if planet in self.empirePath:
                self.empirePath[planet].append(day)
            else:
                self.empirePath[planet] = [day]

    def fetch(self, path):
        """ Fetch Json File Contents. """
        res = None

        try:
            with open(path) as fh:
                res = json.load(fh)
        except FileNotFoundError:  # EnvironmentError
            print('File Not Found: ' + path)

        return res

    def giveMeTheOdds(self, empireJsonFile):
        """
						Class To Compute The Odds Of The Millenium Falcon Reaching Endor In Time.
										:param empireJsonFile:
										:type empireJsonFile: Json File Path
										:return: Odds
														- 0: Millenium Falcon cannot reach Endor before Death Start Annihilates Endor
														- 0.0 < x < 1: Millenium Falcon can reach Endor before delay but might be captured
														- 1: Millenium Falcon can reach Endor before Death Start Annihilates Endor
										:rtype: double
		"""
        empire = self.fetch(empireJsonFile)

        if empire is None:
            sys.exit(1)

        self.mapEmpirePath(empire)

        # find_all_paths
        paths = self.graph.find_all_paths('Tatooine', 'Endor')

        odds = self.get_odds(paths)

        return max(odds)

    def has_risk(self, planet, day):
        """ Bool. Are Bounty Hunters on Path !? """
        return planet in self.empirePath and day in self.empirePath[planet]

    def cost(self, path):
        """ Get Cost and Risk Index For Path """
        cost = 0
        k = 0

        for i in range(0, len(path) - 1):
            travel_cost = self.graph.costs_dict[(path[i], path[i + 1])]

            if self.has_risk(path[i + 1], travel_cost + cost):
                k += 1

            if self.resource_limit - travel_cost == 0:
                cost += 1  # +1 refueling cost
                if self.has_risk(path[i + 1], travel_cost + cost):
                    k += 1

            cost += travel_cost

        return cost, k

    def get_odds(self, paths):
        """ Get Odds For List of Paths """
        odds = [0]
        for path in paths:
            cost, k = self.cost(path)

            # number of possible wait time
            waits = self.countdown - cost

            if waits < 0:
                continue

            odds.append(self.compute_odd(k - waits))

        return odds

    def compute_odd(self, k):
        """ Compute Odds Of Success in Mission """
        risk = 0
        while k > 0:
            risk += (9**(k - 1)) / (10**k)
            k -= 1

        return 1 - risk