def run(path): global G_gen global G_hall_of_fame config = neat.config.Config(*C_NEAT_CONFIG_DEFAULTS, path) pop = neat.Population(config) pop.add_reporter(neat.StdOutReporter(True)) stats = neat.StatisticsReporter() pop.add_reporter(stats) best_fitness = -1000 winner = neat.DefaultGenome(0) graph = Graph(C_FITNESS_THRESHOLD, C_HANDS_PER_GENERATION, C_POP_PER_GEN) while best_fitness < C_FITNESS_THRESHOLD: winner = pop.run(eval_genomes, 1) G_hall_of_fame.append(winner.fitness) G_ao10.append(average(G_hall_of_fame)) graph.update(G_hall_of_fame, G_ao10, G_gen) best_fitness = winner.fitness print("Winner (after %s hand of blackjack):" % (C_HANDS_PER_GENERATION * C_POP_PER_GEN * G_gen)) print(winner) with open("winner-feedforward", 'wb') as f: pickle.dump(winner, f) print("Winner saved")
def __regenerateTopologyGraph(self): graph = {} graphArguments = [] self.reachableNodes = [] rNodes = {} for originNodeAddress, neighbours in self.nodesState.items(): if not 'n' in neighbours: continue graph[originNodeAddress] = {} for neighbourNodeAddress, weight in neighbours['n'].items(): rNodes[neighbourNodeAddress] = True if neighbourNodeAddress in graph and originNodeAddress in graph[ neighbourNodeAddress]: continue graph[originNodeAddress][neighbourNodeAddress] = weight graphArguments.append( (originNodeAddress, neighbourNodeAddress, weight)) graphArguments.append( (neighbourNodeAddress, originNodeAddress, weight)) rNodes.pop(self.main.config.getMyName(), None) for nodeName, n in rNodes.items(): self.reachableNodes.append(nodeName) for neighbour in self.main.config.getMyNeighbours(): if self.neighbours[neighbour][ 'isOnline'] and not neighbour in self.reachableNodes: self.reachableNodes.append(neighbour) self.graph = Graph(graphArguments)
def __init__(self): AbstractWorld.__init__(self) self.graph = Graph(self.Edges,self.Verticies) self.animation = Animation(self.graph) self.screen = pygame.display.set_mode((600, 800)) self.clock = pygame.time.Clock() self.trucks = [] self.prodLines = [] self.warehouses = [] self.openOrders = [] self.finances = Finance()
class World(AbstractWorld): #Initializes the World object def __init__(self): AbstractWorld.__init__(self) self.graph = Graph(self.Edges,self.Verticies) self.animation = Animation(self.graph) self.screen = pygame.display.set_mode((600, 800)) self.clock = pygame.time.Clock() self.trucks = [] self.prodLines = [] self.warehouses = [] self.openOrders = [] self.finances = Finance() #Main method that will run the simulation def runSimulation(self, fps=1, initialTime=5*60, finalTime=23*60): #Get the lists of warehouses, production lines, and trucks that the company owns Warehouses = self.getLocationOfWarehouses() ProductionLines = self.getProductionLines() Trucks = self.getInitialTruckLocations() # Create objects for each production line, warehouse, and truck for w in Warehouses: self.warehouses.append(Warehouse(w['location'],w['type'])) for p in ProductionLines: self.prodLines.append(ProductionLine(p['location'],p['type'],['capacityOfMaterial[tons]'])) for i,t in enumerate(Trucks): self.trucks.append(Truck(t.currentPossition[1],self.graph,t.capacity,i)) # Print the production lines, warehouses, and trucks print "\nProduction Lines: ", ProductionLines, "\n" , "Warehouses: ", Warehouses, "\n" print "Vehicles: " for i,t in enumerate(Trucks): print "vehicle %d: %s"%(i, str(t)) #Initialize the graph and print the edges, verticies, and the graph (as a list of neighbors) self.graph.create_graph(Warehouses,ProductionLines) print "\nEdges: ", self.graph.Edges print "\nVertices: ", self.graph.Verticies print "\nGraph: ", self.graph.neighbors, "\n\n" # Initialize the floyd warshall algorithm to get all the shortest paths. And initialize the animation screen for the simulation self.graph.initialize_floyd_warshall() self.animation.initialize_animation(self.graph) #This for loop keeps track of the time and one iteration is equivalent to a minute of the work day for t in xrange(initialTime,finalTime): print "\n\n\nTime: %02d:%02d"%(t/60, t%60) #prints the time self.animation.time = t #updates the counter that tracks the time that is printed in the animation window newOrders = self.getNewOrdersForGivenTime(t) #Gets new orders if len(newOrders) != 0: #only enters this if statement if there are new orders print "\nNew orders:\n" #For each new order, print the production process, final location, path, and add a new truck for c in newOrders: print "\n", c print "Production Process: ", c.productionProcess print "Final Location: ", c.finalLocation #makes sure that the production line needed for each process has the necessary inventory, otherwise, sends a truck to stock up jobLocations = [] vehicles = [] for process in c.productionProcess: jobs,index = 100,0 for i,p in enumerate(self.prodLines): if p.type == process['processinLine']: #since there are multiple of the same production line, selects the one with the fewest current jobs if p.currentJobs < jobs: jobs = p.currentJobs index = i if self.prodLines[index].inventory[process['resourceNeeded']] < process['materialNeeded[tons]'] and not self.prodLines[index].shipmentOnWay[0]: #checks to see if the selected production line needs to be re-stocked vehicles.append(self.prodLines[index].get_resources(process['resourceNeeded'],process['materialNeeded[tons]'],self.trucks,self.graph,self.warehouses)) jobLocations.append(self.prodLines[index]) #Create an order object for this new order self.openOrders.append(ProductionOrder(c.id,c.productionProcess,c.finalLocation,jobLocations,self.trucks,vehicles,self.graph)) #For each open order, updates the order and removes it from the list of open orders if it is finished. Then updates the sales and discounts based on the order time for order in self.openOrders: #print order.__str__() order.update_order() if order.finished: self.openOrders.remove(order) print "Order ", order.ID, " Finished. Total Time: ", order.totalTime self.finances.update_revenue(order.totalTime) #Update each truck's location for truck in self.trucks: truck.update_truck_location() #Update the holding cost of each for each production line for line in self.prodLines: line.update_holding_cost() #Prints the current finances print self.finances.__str__() #Updates the finances and passes them to the animation to be displayed in the animation self.finances.update_costs(self.trucks, self.prodLines) self.animation.revenue = self.finances.sales - self.finances.discount self.animation.costs = self.finances.transportationCosts + self.finances.holdingCosts #Update the animation self.animation.update_animation(self.trucks) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() pygame.display.update() self.clock.tick(fps)
from Classes.World import World from Classes.Graph import Graph from networkx.classes import graph graphObj = Graph() myWorld = World(graphObj) for j in range(len(myWorld.Edges)): graphObj.add_edge( myWorld.Edges[j][0], myWorld.Edges[j][1], myWorld.Edges[j][2], myWorld.Edges[j][3], myWorld.Edges[j][4] ) #graphObj.add_edge(myWorld.Edges[i][0], myWorld.Edges[i][1],myWorld.Edges[i][2]) for when we want to add actual time #set the floyd welch matrix up graphObj.setFloyd() ''' trying to see if there is a realtionship between time and length of an ''' print(graphObj.getNeighbor(101)) vtx = myWorld.Verticies myWorld.changeToViz(vtx) #draws the vertex's ''' print('locatin of trucks')
class Router(): ROUTING = 'ROUTING' SECONDS_TILL_CONSIDERED_OFFLINE = 12 def setMain(self, main): self.main = main def __init__(self): self.nodesState = {} self.localState = { 'v': 0, # version 'n': {} # neighbours { 'Node name' : (int)weight } } self.server = None self.graph = None self.neighbours = {} self.reachableNodes = [] def initialize(self): for neighbour in self.main.config.getMyNeighbours(): self.neighbours[neighbour] = { 'isOnline': False, 'lastUpdateReceived': 0 } def __saveNodeState(self, nodeState, nodeName): self.nodesState[nodeName] = nodeState def __regenerateTopologyGraph(self): graph = {} graphArguments = [] self.reachableNodes = [] rNodes = {} for originNodeAddress, neighbours in self.nodesState.items(): if not 'n' in neighbours: continue graph[originNodeAddress] = {} for neighbourNodeAddress, weight in neighbours['n'].items(): rNodes[neighbourNodeAddress] = True if neighbourNodeAddress in graph and originNodeAddress in graph[ neighbourNodeAddress]: continue graph[originNodeAddress][neighbourNodeAddress] = weight graphArguments.append( (originNodeAddress, neighbourNodeAddress, weight)) graphArguments.append( (neighbourNodeAddress, originNodeAddress, weight)) rNodes.pop(self.main.config.getMyName(), None) for nodeName, n in rNodes.items(): self.reachableNodes.append(nodeName) for neighbour in self.main.config.getMyNeighbours(): if self.neighbours[neighbour][ 'isOnline'] and not neighbour in self.reachableNodes: self.reachableNodes.append(neighbour) self.graph = Graph(graphArguments) def handleIncomingPacket(self, packet): packet = self.__parsePacket(packet) if not packet: return nodeState = self.__extractNodeStateFromPacket(packet) if nodeState: self.__handleIfIsUpdatePacketFromNeighbour( packet.parts['updateInfoNodeName']) if nodeState and self.__nodeStateShouldBeUpdated( nodeState, packet.parts['updateInfoNodeName']): self.__saveNodeState(nodeState, packet.parts['updateInfoNodeName']) self.__regenerateTopologyGraph() self.__sendStateToAllNeighbours(nodeState, packet.parts['updateInfoNodeName'], packet.parts['srcNode']) def __parsePacket(self, packet): packet.splitPayload() try: packet.parts['updateInfoNodeName'] = packet.splitted.pop() packet.parts['version'] = int(packet.splitted.pop()) packet.parts['neighbourCount'] = int(packet.splitted.pop()) packet.parts['neighbours'] = {} for neighbour in packet.splitted: try: nInfo = neighbour.split('&') packet.parts['neighbours'][nInfo[0]] = int(nInfo[1]) except: pass except: return None return packet def __extractNodeStateFromPacket(self, packet): nodeState = { 'v': packet.parts['version'], 'n': packet.parts['neighbours'] } return nodeState def __nodeStateShouldBeUpdated(self, nodeState, fromNode): if fromNode == self.main.config.getMyName(): return False if not fromNode in self.nodesState: return True if self.nodesState[fromNode]['v'] < nodeState['v']: return True return False def __handleIfIsUpdatePacketFromNeighbour(self, fromNode): if fromNode in self.neighbours: self.neighbours[fromNode]['lastUpdateReceived'] = time.time() if not self.neighbours[fromNode]['isOnline']: self.neighbours[fromNode]['isOnline'] = True self.localState['n'][ fromNode] = 1 # weight can be some random number self.localState['v'] += 1 self.__regenerateTopologyGraph() self.__sendNodeFullTopology(fromNode) self.__sendStateToAllNeighbours(self.localState, self.main.config.getMyName()) def __sendNodeFullTopology(self, nodeName): for stateNodeName, state in self.nodesState.items(): self.main.sendPayload( self.__compilePayloadFromState(state, stateNodeName), nodeName, self.ROUTING) self.main.sendPayload( self.__compilePayloadFromState(self.localState, self.main.config.getMyName()), nodeName, self.ROUTING) def __compilePayloadFromState(self, state, nodeName): nodes = [] for node, weight in state['n'].items(): nodes.append(node + '&' + str(weight)) return nodeName + '|' + str(state['v']) + '|' + str(len( state['n'])) + '|' + '|'.join(nodes) def __sendStateToAllNeighbours(self, nodeState, stateOwnerName, exceptNode=''): for nodeName, weight in self.localState['n'].items(): if nodeName != exceptNode: self.main.sendPayload( self.__compilePayloadFromState(nodeState, stateOwnerName), nodeName, self.ROUTING) def getNextHop(self, destination): if destination in self.main.config.getMyNeighbours(): return destination try: return self.graph.dijkstra(self.main.config.getMyName(), destination)[1] except: return False def watchNeighbours(self): secsAfterLastNeighbourBroadcast = 10 while True: secsAfterLastNeighbourBroadcast += 1 sleep(1) if secsAfterLastNeighbourBroadcast >= 10: secsAfterLastNeighbourBroadcast = 0 for neighbour in self.main.config.getMyNeighbours(): if neighbour != self.main.config.getMyName(): self.main.sendPayloadAndForget( self.__compilePayloadFromState( self.localState, self.main.config.getMyName()), neighbour, self.ROUTING) for neighbour in self.main.config.getMyNeighbours(): if (self.neighbours[neighbour]['isOnline'] and time.time() - self.neighbours[neighbour]['lastUpdateReceived'] > self.SECONDS_TILL_CONSIDERED_OFFLINE): self.neighbours[neighbour]['isOnline'] = False self.localState['n'].pop(neighbour, None) self.localState['v'] += 1 self.__regenerateTopologyGraph() self.__sendStateToAllNeighbours( self.localState, self.main.config.getMyName()) # method for testing def setDummyData(self): self.nodesState['A'] = {'v': 0, 'n': {'B': 1, 'C': 5, 'D': 6}} self.nodesState['B'] = {'v': 0, 'n': {'A': 1, 'C': 2}} self.nodesState['C'] = { 'v': 0, 'n': { 'B': 2, 'A': 5, 'D': 10, 'E': 12 } } self.nodesState['D'] = {'v': 0, 'n': {'A': 6, 'C': 10}} self.nodesState['E'] = {'v': 0, 'n': {'C': 12}} self.nodesState['F'] = {'v': 0, 'n': {'G': 3}} self.nodesState['G'] = {'v': 0, 'n': {'F': 3}} # method for testing def getPath(self, _from, _to): try: return self.graph.dijkstra(_from, _to) except: return 'Destination does not exist'
from Classes.Graph import Graph nodes = ["A", "B", "C", "D", "E", "F"] graph = Graph(nodes) graph.add_edges("A", "B") graph.add_edges("A", "C") graph.add_edges("B", "C") graph.add_edges("B", "D") graph.add_edges("C", "E") graph.add_edges("D", "F") graph.add_edges("E", "D") print("Adajency List:") graph.print_graph() #graph.degree() source_node = input("Enter source node: ") goal_node = input("Enter goal node: ") print("The path from", source_node.upper(), "to", goal_node.upper(), "is: ") graph.dfs(nodes.index(source_node.upper()), nodes.index(goal_node.upper()))