def astar(graph: Graph, start_node, end_node): # Initialize the start node to have zero cost. start_node.g = 0 open_list = [start_node] while len(open_list) > 0: current_node = open_list[0] # Find the node with the lowest cost in the open list. for node in open_list: if node.f < current_node.f: current_node = node # Call build_path if the current node is the destination. if current_node == end_node: return build_path(current_node) # Close the already checked node. open_list.remove(current_node) current_node.closed = True # Loop through each node to find the neightbor with the lowest cost. for neighbor in graph.get_neighbors(current_node): # Do not check the cost if the neighbor node is already closed. if neighbor.closed: continue # Get the total cost from start to the next node. tentative_g = current_node.g + graph.get_cost( current_node, neighbor, 'astar') # Check if the neighbor has a cost assigned, and if so, check if it's the better than any other path to # the neighbor. if neighbor.g is None or tentative_g < neighbor.g: neighbor.parent = current_node neighbor.g = tentative_g neighbor.h = calculate_heuristics(current_node, end_node) neighbor.f = neighbor.g + neighbor.h # Add the neighbor node in the open_list to be checked. if not (neighbor in open_list): open_list.append(neighbor)
def parse_content(content): #get rid of whitespace characters content = [re.sub('\s', '', l) for l in content] #get rid of comments content = [l.split('#')[0] for l in content if l and l[0] != '#'] rules = [] tmp = -1 for i, line in enumerate(content): #loop until initialization of facts or questions if line[0] == '=' or line[0] == '?': tmp = i break #check unvalid characters match = re.search('[^A-Z()!+|^=<>]', line) if match != None: ut.exit_m("invalid character '{:s}' on line {:d}".format( match.group(), i + 1)) if re.search('!!', line) != None: ut.exit_m("do not put successive '!' on line {:d}".format(i + 1)) #select which 'then' sign if line.count('<=>') > 0: sign = '<=>' else: sign = '=>' #check if no 'then' sign if line.count(sign) == 0: ut.exit_m("No '=>' sign on line {:d}".format(i + 1)) split = line.split(sign) #check if too many 'then' sign if len(split) > 2: ut.exit_m("too many '{:s}' on line {:d}".format(i + 1)) #check before and after 'then' sign if split[0] == '' or split[1] == '': ut.exit_m("arguments missing on line {:d}".format(i + 1)) #check for characters of the 'then' sign in arguments for s in split: if re.search('[<=>]', s) != None: ut.exit_m("unwanted character on line {:d}".format(i + 1)) #append the rules rules.append([split[0], split[1], sign]) #case of no initialization and questions ini = '' ask = '' if tmp > -1: #if there is an initialization line if content[tmp][0] == '=': ini = content[tmp][1:] if re.search('[^A-Z]', ini) != None: ut.exit_m("unwanted character on the initialization line") if len(content) > tmp + 2: ut.exit_m("too many lines after initialization") if len(content) == tmp + 2: tmp += 1 if content[tmp][0] != '?': ut.exit_m("you must ask a question after initialization") #if there is a question line if content[tmp][0] == '?': ask = content[tmp][1:] if re.search('[^A-Z]', ask) != None: ut.exit_m("unwanted character on the question line") if len(content) != tmp + 1: ut.exit_m("the question line should be the last line of input") if len(ask) == 0: ut.exit_m('you should ask a question about facts') input = Graph(rules, ini, ask) return (input)
def __init__(self, file_name): self.parser = Parser(file_name) self.graph = Graph(self.parser) self.solver = Solver(self.parser, self.graph)
def run(self): while True: try: id = "" if self.model.currentNode: id = self.model.currentNode.id command, args = self.view.get(PROMPT_SYMBOL + " " + id + ": ") arg = command.parse(args) if command == Command.INIT: if len(arg) == 1: self.model.init(arg[0]) elif len(arg) == 2: self.model.init(arg[0], label=arg[1]) elif command == Command.TOUCH: if not self.model.currentNode: raise MalformedCommandException( "Error: No parent found. Use init command to initialise a tree." ) if len(arg) == 1: self.model.newNode(arg[0]) elif len(arg) == 2: self.model.newNode(arg[0], label=arg[1]) elif len(arg) == 3: self.model.newNode(arg[0], label=arg[1], eLabel=arg[2]) elif command == Command.CD: self.model.cd(arg[0]) elif command == Command.LABEL: if len(arg) == 0: self.view.put(self.model.currentNode.label) else: self.model.label(" ".join(arg)) elif command == Command.CR: self.model.switch(arg[0]) elif command == Command.TREE: Tree(self.model.currentNode).render() elif command == Command.ELABEL: if len(arg) == 0: self.view.put(self.model.currentNode.eLabel) else: self.model.elabel(" ".join(arg)) elif command == Command.EXPORT: Graph.OUTDIR = os.getcwd() Graph.OUTNAME = "out" if len(arg) == 0: Graph.Graph(self.model.currentRoot).render() elif len(arg) == 1: Graph.Graph(self.model.currentRoot, title=arg[0]).render() elif len(arg) == 2: Graph.Graph(self.model.currentRoot, title=arg[0]).render(filename=arg[1]) elif len(arg) == 3: Graph.Graph(self.model.currentRoot, title=arg[0]).render(filename=arg[1], directory=arg[2]) elif len(arg) == 4: Graph.OUTNAME = arg[1] Graph.OUTDIR = arg[2] Graph.Graph(self.model.currentRoot, title=arg[0], format=arg[3]).render() else: raise MalformedCommandException("Cannot render") except Exception as e: self.view.put(str(e))
from node import Graph, ParseException, parse_node nodes = {} graphs = {} # Read in the node data i=0 for line in sys.stdin: i += 1 if line.startswith("#") or line.isspace() or len(line) == 0: continue try: if line.startswith("["): g = Graph(line.strip()) graphs[g.id] = g sys.stderr.write("Read graph " + str(g) + "\n") else: n = parse_node(line.strip()) nodes[n.id] = n sys.stderr.write("Read node " + str(n) + "\n") except ParseException, ex: sys.stderr.write("%s at line %s\n" % (ex, i)) # Set links from nodes to graphs for i, g in graphs.iteritems(): g.set_links(nodes, graphs) # Set node links for i, n in nodes.iteritems():
# Import Necessary Classes and Functions from PIL import Image, ImageDraw from matplotlib.figure import Figure from astar import astar from bna import bna from imagegen import composite_and_save, generate_image from node import Node, Graph from roads import Road from runner import random_nodes, node_reset, segment_load, total_time, graph_reset import math, random import matplotlib.pyplot as plt import matplotlib.image as imgr # Create a Graph Object graph = Graph() # List Nodes in Graph graph.add_node(0, (0, 1)) graph.add_node(1, (1, 0)) graph.add_node(2, (4, 3)) graph.add_node(3, (5, 2)) # List Edges Between Nodes in Graph graph.add_edge(0, 1, Road(120, 1, math.sqrt(2))) graph.add_edge(2, 3, Road(120, 1, math.sqrt(2))) graph.add_edge(1, 0, Road(120, 1, math.sqrt(2))) graph.add_edge(3, 2, Road(120, 1, math.sqrt(2))) graph.add_edge(1, 3, Road(60, 4, math.sqrt(13))) graph.add_edge(0, 2, Road(60, 4, math.sqrt(13)))
def trainbyBatch(MyNeuralNetwork, Datas, Error=0.01, MaxTimes=-1, Speed=0.1, MyLearningAlgorithm=LearningAlgorithm.BackPropagation, Verbose=0, VerbosePerLoop=10000, Backup=True): # Parameter explianation: # MyNeuralNetwork: Simply your NeuralNetwork # InputData/OutputData: Simply your data in numpy's matrix type # Error/MaxTimes: The training will stop until its error smaller then Error or reach it MaxTimes(max training times) # Speed: Same as the LearningAlgorithm.BackPropagation one. # MyLearningAlgorithm: You can specify your training type here. # Verbose/VerbosePerLoop: 'Verbose' for your verbose level, and 'VerbosePerLoop' for Verbose frequency and information capture frequency, higher it is, less Verbose frequency. # Backup: Save .node file per 10*verbose. InputData = Datas[0] OutputData = Datas[1] InputValidationData = Datas[2] OutputValidationData = Datas[3] # Initlalize Datas timescount = 0 error = 99999 errorlogs = [] Validationerrorlogs = [] # errorlogs for pending errors for later Graphing use if Verbose >= 1: print(str(len(InputData)) + ' samples. Target error: ' + str(Error)) print('training...') while (error > Error and (timescount < MaxTimes or MaxTimes == -1)): error = MyLearningAlgorithm(MyNeuralNetwork, InputData, OutputData, Speed) timescount += 1 if Verbose > 1 and timescount % VerbosePerLoop == 0: print('Training log >>>epochs: ' + str(timescount) + ', error: ' + str(error)) # Verbose training status if Verbose > 2: errorlogs.append(error) if InputValidationData.all() != None: Validationerrorlogs.append( f.MeanSquareError( OutputValidationData, MyNeuralNetwork.feed(InputValidationData))) # Append error to list if timescount % (VerbosePerLoop) == 0: MyNeuralNetwork.savetoFile(MyNeuralNetwork.Name + '_latest') # Backup Neural Network to file # Train until it reach its goals if Verbose >= 1: print('Train log >>>Result: ') print('Tried times: ' + str(timescount) + ', error: ' + str(error)) print('InputData: ') print(InputData) print('OutputData: ') print(OutputData) print('Result output: ') print(MyNeuralNetwork.feed(InputData)) print('') if Verbose > 2: Graph.plotByList(errorlogs) if InputValidationData.all() != None: Graph.plotByList(Validationerrorlogs, 'Epochs', 'error rate', 'NN=' + MyNeuralNetwork.Name + ', Speed=' + str(Speed) + ', finalerror=' + str(error), LineTags=['Error', 'Validation Error'])
def start_button(): ''' Create NUMBER_OF_NODES nodes ''' #for i in range(NUMBER_OF_NODES): timer = 0 nodes = [] result = [] for i in range(NUMBER_OF_NODES): x = random.uniform(-10, 10) y = random.uniform(-10, 10) orientation = random.uniform( 0, np.pi) #should perhaps all start within range of pi radians? position = [x, y] new_node = Node(position=position, orientation=orientation) nodes.append(new_node) g = Graph(nodes=nodes) g_state = copy.deepcopy(g) head = graph_state(graph=g_state, time=timer) tail = head ''' should I do a few updates every time step ''' ''' while(timer < RUN_TIME): for node in g.nodes: g.update_graph(node = node) g_state = copy.deepcopy(g) temp = graph_state(graph = g_state, time = timer) tail.next = temp tail = temp timer+=1 ''' while (timer < RUN_TIME): count = 1 nodec = 1 print "" for node in g.nodes: print nodec nodec += 1 g.update_graph(node=node) if count % 4: g_state = copy.deepcopy(g) temp = graph_state(graph=g_state, time=timer) tail.next = temp tail = temp timer += 1 count += 1 #canvas.delete("all") #canvas.pack() while (head.next != None): graph = head.graph for node in graph.nodes: canvas_coord = cartesian_to_canvas(node.position_vector) print node.position_vector, canvas_coord #canvas.create_image(canvas_coord[0],canvas_coord[1], image = label.image) canvas.create_oval(canvas_coord[0] - RADIUS, canvas_coord[1] - RADIUS, canvas_coord[0] + RADIUS, canvas_coord[1] + RADIUS) canvas.pack() print "" head = head.next GUI.update() time.sleep(SLEEP_TIME) canvas.delete(ALL) #canvas.move("all", 100,100) return
return correctWord[2] else: return correctWord[3] fileText = open(options.input) fileOut = open(options.output, 'a+w') miss = 0 affix = '' add = False count = 0 for line in read_lines(fileText): graphNum = Graph() graphGen = Graph() line = line.replace('\n', '') for w in line.split(): if '[' not in w: graphNum.setLayer(['N'], [1]) graphGen.setLayer(['N'], [1]) else: if len(words) != 0 and words[0] == w: graphNum.setLayer(['P', 'S', 'N'], list(predsNum[0])) graphGen.setLayer(['F', 'M', 'N'], list(predsGen[0])) words.pop(0) predsNum = np.delete(predsNum, (0), axis=0) predsGen = np.delete(predsGen, (0), axis=0)