def fact_arith(self, cur_token, G): if cur_token.t_class in {'UNARY_OP', 'UNARY_ADD_OP'}: next_token, child_term_unary = self.term_unary(next(G), G) return next_token, tree('FACT_ARITH', [tree(cur_token.name), child_term_unary]) else: cur_token, child_term_unary = self.term_unary(cur_token, G) return cur_token, tree('FACT_ARITH', [child_term_unary])
def block(self, cur_token, G): if cur_token.name != "BEGIN": raise ParserError.raise_parse_error("block", "begin", cur_token) cur_token, tree_stmt_list = self.statement_list(next(G), G) if cur_token.name != "END": raise ParserError.raise_parse_error("block", "end", cur_token) return next(G), tree("BLOCK", [tree("BEGIN"), tree_stmt_list, tree("END")])
def program(curToken, G): if curToken.name != "BEGIN": raise raiseParserError("program", "begin", curToken) curToken, tree_stmt_list = statement_list(next(G), G) if curToken.name != "END": raiseParserError("program", "end", curToken) return next(G), tree("PROGRAM", [tree("BEGIN"), tree_stmt_list, tree("END")])
def lookup(self, player, btree, depth): if self.genWinningMove(player)!=-1: newboard=board() newboard.store=list(self.store) newboard.store[newboard.genWinningMove(player)]=player newboard.analyzeBoard() btree.AddSuccessor(tree(newboard)) return True elif self.genNonLoser(player)!=-1: newboard=board() newboard.store=list(self.store) newboard.store[newboard.genNonLoser(player)]=player newboard.analyzeBoard() btree.AddSuccessor(tree(newboard)) return True elif depth!=0: for i in range (0, self.length, 1): if self.store[i]==0: newboard=board() newboard.store=list(self.store) newboard.store[i]=player newboard.analyzeBoard() newtree=tree(newboard) self.lookup(self.oppo(player), newtree, depth-1) btree.AddSuccessor(newtree) return True
def main(): global stack while get_expression(): value = get_next_token() while value: if str.isdigit(value[0]) is True: # create a tree with current value having no descendants subtree = tree(value) # append value to the stack stack.append(subtree) else: # here were are an operator so must specify current descendants as the two curent values in the stack right = stack.pop() left = stack.pop() subtree = tree(value, left, right) # append value to the stack stack.append(subtree) # get the next available token value = get_next_token() for i in range(0, len(stack)): # pre order print("pre-order search: " + preOrderSearch(stack[i])) # in order print("in-order search: " + inOrderSearch(stack[i])) # post order print("post-order search: " + postOrderSearch(stack[i])) # perform operation on the tree print("eval: " + str(calculate(stack[i]))) print("\n\n")
def ident(self, curToken, G): if curToken.name != "ID": raise ParserError.raise_parse_error("ident", "ID", curToken) self.symbol_table[curToken.pattern] = {'type': 'int', 'scope': None, 'mem_name': None, 'init_val': None, 'curr_val': None, 'addr_reg': None, 'val_reg': None} t = tree('ID') t.token = curToken return next(G), tree("IDENT", [t])
def expr_bool(self, cur_token, G): children_expr_bool = [] while True: cur_token, child_term_bool = self.term_bool(cur_token, G) children_expr_bool.append(child_term_bool) if cur_token.t_class != "LOG_OR": return cur_token, tree("EXPR_BOOL", children_expr_bool) children_expr_bool.append(tree(cur_token.name, [], cur_token)) cur_token = next(G)
def term_bool(self, cur_token, G): children_term_bool = [] while True: cur_token, child_expr_eq = self.expr_eq(cur_token, G) children_term_bool.append(child_expr_eq) if cur_token.t_class != "LOG_AND": return cur_token, tree("TERM_BOOL", children_term_bool) children_term_bool.append(tree(cur_token.name, [], cur_token)) cur_token = next(G)
def expr_eq(self, cur_token, G): children_expr_eq = [] cur_token, child_expr_relation = self.expr_relation(cur_token, G) children_expr_eq.append(child_expr_relation) if cur_token.t_class == 'EQUAL_OP': children_expr_eq.append(tree(cur_token.name, [], cur_token)) cur_token, child_expr_relation = self.expr_relation(next(G), G) children_expr_eq.append(child_expr_relation) return cur_token, tree('EXPR_EQ', children_expr_eq)
def expr_relation(self, cur_token, G): children_expr_relation = [] cur_token, child_expr_arith = self.expr_arith(cur_token, G) children_expr_relation.append(child_expr_arith) if cur_token.t_class == 'REL_OP': children_expr_relation.append(tree(cur_token.name, [], cur_token)) cur_token, child_expr_arith = self.expr_arith(next(G), G) children_expr_relation.append(child_expr_arith) return cur_token, tree('EXPR_RELATION', children_expr_relation)
def expr_arith(self, cur_token, G): children_expr_arith = [] while True: cur_token, child_term_arith = self.term_arith(cur_token, G) children_expr_arith.append(child_term_arith) if cur_token.t_class != "UNARY_ADD_OP": return cur_token, tree("EXPR_ARITH", children_expr_arith) children_expr_arith.append(tree(cur_token.name, [], cur_token)) cur_token = next(G)
def term_arith(self, cur_token, G): children_term_arith = [] while True: cur_token, child_fact_arith = self.fact_arith(cur_token, G) children_term_arith.append(child_fact_arith) if cur_token.t_class != "MUL_OP": return cur_token, tree("TERM_ARITH", children_term_arith) children_term_arith.append(tree(cur_token.name, [], cur_token)) cur_token = next(G)
def func_gen(self, cur_token, G): if cur_token.t_class in {"IDENTIFIER", "LITERAL", "UNARY_OP", "UNARY_ADD_OP"} or cur_token.name == 'LPAREN': cur_token, child_tree = self.func_call(cur_token, G) return cur_token, tree("FUNC_GEN", [child_tree]) elif cur_token.t_class == "TYPE": cur_token, child_tree = self.func_dec(cur_token, G) return cur_token, tree("FUNC_GEN", [child_tree]) else: return cur_token, tree("FUNC_GEN")
def Generate_VHDL(name, XMLFile, HDLPath, map_template_file, pkg_template_file, useUhal): print("Generate VHDL for", name, "from", XMLFile) # get working directory wd = os.getcwd() # move into the output HDL directory os.chdir(wd + "/" + HDLPath) # make a symlink to the XML file fullXMLFile = wd + "/" + XMLFile # generate a fake top address table slaveAddress = "0x" + hex(0x00000000)[2:] topXMLFile = "top.xml" outXMLFile = open(topXMLFile, 'w') outXMLFile.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n") outXMLFile.write("<node id=\"TOP\">\n") outXMLFile.write(" <node id=\"" + name + "\" module=\"file://" + fullXMLFile + "\" address=\"" + slaveAddress + "\"/>\n") outXMLFile.write("</node>\n") outXMLFile.close() # generate the VHDL if useUhal: try: import uhal device = uhal.getDevice("dummy", "ipbusudp-1.3://localhost:12345", "file://" + topXMLFile) for i in device.getNodes(): if i.count('.') == 0: mytree = tree(device.getNode(i), log) mytree.generatePkg() mytree.generateRegMap(regMapTemplate=wd + "/" + map_template_file) except ImportError: print("uhal is not installed") else: root = ParserNode(name='TOP') buildTree(root, topXMLFile, init=True) for child in root.getChildren(): child.setParent(None) mytree = tree(child) mytree.generatePkg() mytree.generateRegMap() child.setParent(root) # cleanup os.remove(topXMLFile) os.chdir(wd) # go back to original path
def ConvertToTree_helper(self): siblings = [] if self.store[1] == (not True): return tree(self.store[0]) left_node = self.store[1] while True: if left_node == (not True): break next_node = tree(left_node.store[0]) if left_node.store[1] != (not True): next_node.store[1] = left_node.ConvertToTree_helper() siblings = siblings + [next_node] left_node = left_node.store[2] return siblings
def primary(curToken, G): if curToken.name == "LPAREN": curToken, child_expr = expression(next(G), G) if curToken.name != "RPAREN": raiseParserError("primary", ")", curToken) return next(G), tree("PRIMARY", [child_expr]) elif curToken.name == "ID": curToken, child_ident = ident(curToken, G) return curToken, tree("PRIMARY", [child_ident]) # I flipped this to a positive check just to make # it slightly clearer elif curToken.name == "INTLIT": return next(G), tree("PRIMARY", [tree("INTLIT")]) else: raiseParserError('primary', "INTLITERAL", curToken)
def statement(curToken, G): if curToken.name in ("READ", "WRITE"): tokenName = curToken.name curToken = next(G) if curToken.name != "LPAREN": raiseParserError("statement", '(', curToken) curToken, child_id_list_or_expr_list = id_list(next(G), G) if tokenName == "READ" else expr_list(next(G), G) if curToken.name != "RPAREN": raiseParserError("statement", ')', curToken) return next(G), tree("STATEMENT", [tree(tokenName), child_id_list_or_expr_list]) # Also done to make this more explicit # if not in read, write, then it is assign (or assign should throw error) else: curToken, child_assign = assign(curToken, G) return curToken, tree("STATEMENT", [child_assign])
def term_unary(self, cur_token, G): if cur_token.name == "LPAREN": cur_token, child_expr_bool = self.expr_bool(next(G), G) if cur_token.name != "RPAREN": raise ParserError.raise_parse_error("TERM_UNARY", ")", cur_token) return next(G), tree("TERM_UNARY", [child_expr_bool]) elif cur_token.name == "ID": cur_token, child_ident = self.var_ident(cur_token, G) return cur_token, tree("TERM_UNARY", [child_ident]) # I flipped this to a positive check just to make # it slightly clearer elif cur_token.t_class == "LITERAL": return next(G), tree("TERM_UNARY", [tree(cur_token.name, [], cur_token)]) else: raise ParserError.raise_parse_error('TERM_UNARY', "ID or LITERAL", cur_token)
def readtrees(self, filename): for lines in open(filename): if lines != '': self.trees.append(lines) t = tree() t.settree(lines) self.ptrees.append(t)
def alphabetaMakeTree(newroot, depth, player, opp): if depth == 0: # print("depth=0 and done!") return True options = playerMoveOptions(newroot.GetVal(), player) if options == []: print("no options...") return False # print("alphabetaMakeTree with depth = ",depth) CurrentBoardStrength = GetBoardStrength(newroot.GetVal(), player, opp) for possibility in options: tstBoard = GenTestBoard(list(newroot.GetVal()), possibility[0], possibility[1]) tstBoardStrength = GetBoardStrength(tstBoard, player, opp) ##### evaluate whether we ought to bother with making the enxt node... ##### (THIS IS THE PART TO MAKE BETTER.) # ->check1: if we are at the first node, consider ALL options for sure. # - TODO: i dont think check1 is necessary # ->check2: True if the strength of the tstBoard is better (not=) to current board. # ...but for check2, let's introduce a factor. with this factor, i'll allow moves # which look bad for the immediate next board state, but which may end up being # ok moves in the future. factor = 10 #currently ok with the death of a PAWN only appearing in the tree. # print("DEBUG: player=",player," CURRENT BOARD STRENGTH = ",CurrentBoardStrength,"TSTBOARDSTRENGTH=",tstBoardStrength) check2 = tstBoardStrength > CurrentBoardStrength - factor #is next better than this. check1 = newroot.GetParent( ) # will =False only when this is the parent. # print("check1=",check1,"check2=",check2) check3 = (newroot.GetSuccessors == []) # if tstBoardStrength == CurrentBoardStrength, allow a max number of tree nodes # to be added. if tstBoardStrength == CurrentBoardStrength and len( newroot.GetSuccessors()) > 50: # print("ok now its getting too big... hopefully limiting here is ok?") #lim=-1 lim = 2 #very much subject to change else: lim = -1 if check2 or (check1 == False) or check3: # print("adding the node with CurrentBS-factor=",CurrentBoardStrength - factor) newbranch = tree(tstBoard) newroot.AddSuccessor(newbranch) ##### if lim == -1: # print("lim=-1, adding all") for successor in newroot.GetSuccessors(): alphabetaMakeTree(successor, depth - 1, opp, player) #flipping who player is else: # print("lim=",lim,"adding len successors / lim") for i in range(0, len(newroot.GetSuccessors()), lim): successor = (newroot.GetSuccessors())[i] alphabetaMakeTree(successor, depth - 1, opp, player) return True
def ConvertToTree(self): if self.store[2] != (not True): return [(not True)] cTree = tree(self.store[0]) if self.store[1] != (not True): cTree.store[1] = self.ConvertToTree_helper() return [True, cTree]
def Brute_Force(board,player): #get easy instances out of the way if genWinningMove(board,player) != -1: return genWinningMove(board,player) if genNonLoser(board,player) != -1: return genNonLoser(board,player) #creating a tree of all possible board and assigning heuristics board_tree = tree(board) genTree(board_tree, player) addHeuristic(board_tree, player) #If it comes up with no moves if board_tree.children == []: return Competent(board,player) #getting child with highest heuristic heuristic_list = [] for child in board_tree.children: heuristic_list += [child.heuristic] move = -1 if player == 1: move = get_move(board, board_tree.children[heuristic_list.index(max(heuristic_list))].val) else: move = get_move(board, board_tree.children[heuristic_list.index(min(heuristic_list))].val) if move != -1: return move else: return Competent(board,player)
def readtrees(self, filename): for lines in open(filename): if lines != '': self.trees.append(lines) t = tree() t.settree(lines) self.ptrees.append(t)
def statement_list(self, cur_token, G): children_stmt_list = [] while True: cur_token, child_stmt = self.statement(cur_token, G) children_stmt_list.append(child_stmt) if cur_token.name not in ("READ", "WRITE", "ID", "WHILE", "IF", "RETURN") and cur_token.t_class != 'TYPE': return cur_token, tree("STATEMENT_LIST", children_stmt_list)
def mini_board(board, player, depth): tmp_board = list(board) if depth == ai_consts.minimax_max_depth: rval = eval_func(board, player) return [rval, tree(rval)] if player == chess_constants.player_white: enemy = chess_constants.player_black else: enemy = chess_constants.player_white root = eval_func(board, player) t = tree.tree(root) L = chess.getPlayerPositions(board, enemy) value = ai_consts.minimax_max_val for curr_pos in L: tmp = chess.getPieceLegalMoves(board, curr_pos) if tmp == []: continue for i in tmp: if i == []: continue tmp_board[i] = tmp_board[curr_pos] tmp_board[curr_pos] = chess_constants.empty_space temp_value = maxi_board(tmp_board, player, depth + 1) tmp_board = list(board) t.addSuccessor(temp_value[1]) if temp_value[0] < value: value = temp_value[0] return [value, t]
def alphabetaminimax(board, depth, player, opp): print("-----------alphabetaminmax-----------") if depth == 0: print("lol why.") return GenBestMove(board, player, opp) #dont even bother... TestBoard = list(board) alphabetaminimaxtree = tree(TestBoard) # print("OKOKOKOKMKKOKOKOKKKKOKKOKOKOOKOK PARENT ",alphabetaminimaxtree.GetParent()) out = [] test = alphabetaMakeTree(alphabetaminimaxtree, depth, player, opp) if test == False: #if the function failed print("no options then? uhhhh") return [] #decide what to do later XD print("depth level to check going into options: ", depth) #options_treels: list of final board options- list of trees options_treels = alphabetaminimaxtree.GetAtBottomLevel() if alphabetaminimaxtree.GetAtLevel(depth) == options_treels: print("checking option_treels: we ok") else: print( "checking option_treels: we have a depth difference. RIP, plz fix me." ) #may also use GetAtBottomLevel(), but then we gotta consider the change in depth- so #that's a cheap way to get evaluation not really up till depth. print("number of options = ", len(options_treels)) print("3 of options_treels ", options_treels[:3]) #should be a list of tree objects. #options: list of the actual boards stored in the trees of options_treels options = [] for i in range(len(options_treels)): options += [(options_treels[i]).GetVal()] # print("3 of options ",options[:3])#should be list of boards #optionValues: the board value associated with each option, another parallel list.. optionValues = [] #note: original move selection method was to pick the highest value of the board. #new idea: build a fcn which considers more than just the endvalue. #call this fcn Move2PickFromTree(options_treels, options, optionValues). #WillPick=0 #the index of the highest value in the optionValues list #print("WILLPICK=0 NOW") for opt in range(len(options) - 1): # each opt is a board optionValues += [GetBoardStrength(options[opt], player, opp)] #if optionValues[opt] > optionValues[WillPick]: # WillPick=opt # print("WillPick ",WillPick) #print("that was ",options[WillPick]," with value ",optionValues[WillPick]) move = Move2PickFromTree(options_treels, options, optionValues, depth, board, player, opp) return move
def expr_list(curToken, G): children_expr_list = [] while True: curToken, child_expr = expression(curToken, G) children_expr_list.append(child_expr) if curToken.name != "COMMA": return curToken, tree("EXPR_LIST", children_expr_list) curToken = next(G)
def id_list(curToken, G): children_id_list = [] while True: curToken, child_ident = ident(curToken, G) children_id_list.append(child_ident) if curToken.name != "COMMA": return curToken, tree("ID_LIST", children_id_list) curToken = next(G)
def expr_list(self, cur_token, G): children_expr_list = [] while True: cur_token, child_expr_bool = self.expr_bool(cur_token, G) children_expr_list.append(child_expr_bool) if cur_token.name != "COMMA": return cur_token, tree("EXPR_LIST", children_expr_list) cur_token = next(G)
def makeTree(self, k): #you recieve a list # print "k:", k a = tree(k[0]) for i in range(len(k[1])): # print "iii:", k[1][i] a.AddSuccessor(self.makeTree(k[1][i])) return a
def dec_list(self, cur_token, G): children_dec_term = [] while True: cur_token, child_dec_term = self.dec_term(cur_token, G) children_dec_term.append(child_dec_term) if cur_token.name != "COMMA": return cur_token, tree("DEC_LIST", children_dec_term) cur_token = next(G)
def expression(curToken, G): children_expr = [] while True: curToken, child_primary = primary(curToken, G) children_expr.append(child_primary) if curToken.t_class != "ARITHOP": return curToken, tree("EXPRESSION", children_expr) curToken, child_arith_op = arith_op(curToken, G) children_expr.append(child_arith_op)
def id_state_body(self, cur_token, G): if cur_token.name == "LPAREN": cur_token, child_tree = self.func(cur_token, G) else: cur_token, child_tree = self.assign(cur_token, G) if cur_token.name != "SEMICOLON": raise ParserError.raise_parse_error("ID_STATE_BODY", ";", cur_token) cur_token = next(G) return cur_token, tree("ID_STATE_BODY", [child_tree])
def __init__(self, root): self.explored=set() # explored set self.frontier=deque() # use deque for fast poping and checking there is same value self.frontier.append(root) self.searchtree=tree(root) self.numofnodegenbefore=0 # record the the num of nodes seen before self.numofnodeonfringe=1 # currently not used
def func_dec(self, cur_token, G): children = [] while True: if cur_token.t_class != "TYPE": raise ParserError.raise_parse_error("FUNC_DEC", "TYPE", cur_token) type_tree = tree("TYPE", [], cur_token) children.append(type_tree) cur_token = next(G) if cur_token.name == "REF": ref_tree = tree("REF", [], cur_token) children.append(ref_tree) cur_token = next(G) cur_token, child_ident = self.ident(cur_token, G) children.append(child_ident) if cur_token.name != "COMMA": return cur_token, tree("FUNC_DEC", children) cur_token = next(G) # comma
def statement_list(self, cur_token, G): children_stmt_list = [] while True: cur_token, child_stmt = self.statement(cur_token, G) if cur_token.name != "SEMICOLON": raise ParserError.raise_parse_error("STATEMENT_LIST", ";", cur_token) children_stmt_list.append(child_stmt) cur_token = next(G) if cur_token.name not in ("READ", "WRITE", "ID", "WHILE", "IF") and cur_token.t_class != 'TYPE': return cur_token, tree("STATEMENT_LIST", children_stmt_list)
def statement_list(curToken, G): children_stmt_list = [] while True: curToken, child_stmt = statement(curToken, G) if curToken.name != "SEMICOLON": raiseParserError("statement_list", ";", curToken) children_stmt_list.append(child_stmt) curToken = next(G) if curToken.name not in ("READ", "WRITE", "ID"): return curToken, tree("STATEMENT_LIST", children_stmt_list)
def toProperNewickTreeSet(self): ''' Convert this landscape into an unorganized set of trees where taxa names are transformed to their original form (i.e. not transformed to a state friendly for the Phylip format). :return: a :class:`.tree.treeSet` object ''' return self._toTreeSet( lambda t: tree(self.getVertex(t).getProperNewick()))
def alphabetaeverything(board, depth, player, opp): out = [False, False] # print("-----------alphabetaEVERYTHING-----------") if depth == 0: print("lol why.") return out #return GenBestMove(board,player,opp) #dont even bother... TestBoard = list(board) alphabetaminimaxtree = tree(TestBoard) # print("OKOKOKOKMKKOKOKOKKKKOKKOKOKOOKOK PARENT ",alphabetaminimaxtree.GetParent()) test = alphabetaMakeTree(alphabetaminimaxtree, depth, player, opp) if test == False: #if the function failed print("no options then? uhhhh") return out #decide what to do later XD # so my tree is good, and out[0] will return this tree! # # print("----adding to out[0]----") out[0] = alphabetaminimaxtree # print("depth level to check going into options: ",depth) #options_treels: list of final board options- list of trees options_treels = alphabetaminimaxtree.GetAtBottomLevel() # if alphabetaminimaxtree.GetAtLevel(depth) == options_treels: # print("checking option_treels: we ok") # else: # print("checking option_treels: we have a depth difference. RIP, plz fix me.") # print("number of options = ",len(options_treels)) # print("3 of options_treels ",options_treels[:3])#should be a list of tree objects. #options: list of the actual boards stored in the trees of options_treels options = [] for i in range(len(options_treels)): options += [(options_treels[i]).GetVal()] # print("3 of options ",options[:3])#should be list of boards #optionValues: the board value associated with each option, another parallel list.. optionValues = [] #WillPick=0 #the index of the highest value in the optionValues list #print("WILLPICK=0 NOW") for opt in range(len(options) - 1): # each opt is a board optionValues += [GetBoardStrength(options[opt], player, opp)] move = Move2PickFromTree(options_treels, options, optionValues, depth, board, player, opp) ## out[3] = 2-list detailing the move ## # print("----adding to out[3]----") out[1] = list(move) return out
def label_counts(t): if is_leaf(t): return {label(t): 1} else: counts = {} for b in branches(t) + [tree(label(t))]: for l, c in label_counts(b).items(): if l not in counts: counts[l] = 0 counts[l] += 1 return counts
def func(self, cur_token, G): if cur_token.name != "LPAREN": raise ParserError.raise_parse_error("FUNC", '(', cur_token) cur_token, child_func_gen = self.func_gen(next(G), G) if cur_token.name != "RPAREN": raise ParserError.raise_parse_error("FUNC", ')', cur_token) cur_token = next(G) # ) children = [] if cur_token.name == "ARROW": type_tree = tree("TYPE", [], next(G)) children.append(type_tree) cur_token = next(G) if cur_token.name == "BEGIN": cur_token, child_block = self.block(cur_token, G) children.append(child_block) # If the children list is empty, do not put it as a tree child if not children: return cur_token, tree("FUNC", [child_func_gen]) else: return cur_token, tree("FUNC", [child_func_gen, tree("FUNC_DEC_TAIL", children)])
def if_statement(self, cur_token, G): cur_token, child_expr_bool = self.expr_bool(next(G), G) if cur_token.name != "THEN": raise ParserError.raise_parse_error("IF_STATEMENT", 'THEN', cur_token) cur_token, child_block = self.block(next(G), G) if cur_token.name != "ELSE": return cur_token, tree("IF_STATEMENT", [tree("IF"), child_expr_bool, tree("THEN"), child_block]) cur_token, child_else_block = self.block(next(G), G) return cur_token, tree("IF_STATEMENT", [tree("IF"), child_expr_bool, tree("THEN"), child_block, tree("ELSE"), child_else_block])
def __init__(self, root, heuris=1): self.explored=set() self.frontier=[] if heuris==1: root.expectcost=heuristic1(root.content) else: root.expectcost=heuristic2(root.content) heapq.heappush(self.frontier, (root.expectcost, root) ) self.searchtree=tree(root) self.numofnodegenbefore=0
def toProperNewickTreeSet(self): ''' Convert this landscape into an unorganized set of trees where taxa names are transformed to their original form (i.e. not transformed to a state friendly for the Phylip format). :return: a :class:`.tree.treeSet` object ''' return self._toTreeSet( lambda t: tree(self.getVertex(t).getProperNewick()))
def getSimEntDataset(f, words, task): data = open(f, 'r') lines = data.readlines() examples = [] for i in lines: i = i.strip() if (len(i) > 0): i = i.split('\t') if len(i) == 3: if task == "sim": e = (tree(i[0], words), tree(i[1], words), float(i[2])) examples.append(e) elif task == "ent": e = (tree(i[0], words), tree(i[1], words), i[2]) examples.append(e) else: raise ValueError('Params.traintype not set correctly.') else: print(i) return examples
def computer(self, player): if self.genWinningMove(player)!=-1: return self.genWinningMove(player) elif self.genNonLoser(player)!=-1: return self.genNonLoser(player) else: sim=tree(self) self.lookup(player, sim, 4) self.eval(sim,4) #depth of 4 r=self.select_move(sim) return r
def ConvertToTree(self): root = self.store[0] rtree = tree(root) if self.store[1] != []: successor = self.store[1] while True: succ = successor.ConvertToTree() rtree.AddSuccessor(succ) if successor.store[2] != []: successor = successor.store[2] else: break return rtree
def getSentimentDataset(f, words): data = open(f, 'r') lines = data.readlines() examples = [] for i in lines: i = i.strip() if (len(i) > 0): i = i.split('\t') if len(i) == 2: e = (tree(i[0], words), i[1]) examples.append(e) else: print(i) return examples
def prune_binary(t, nums): if is_leaf(t): if label(t) in nums: return t return None else: next_valid_nums = [x[1:] for x in nums if x[0] == label(t)] new_branches = [] for b in branches(t): pruned_branch = prune_binary(b, next_valid_nums) if pruned_branch is not None: new_branches = new_branches + [pruned_branch] if not new_branches: return None return tree(label(t), new_branches)
def CThelper(self): root = self.store[0] x = tree(root) children = self.store[1] + self.store[2] if len(children) != 0: eldest = children[0] while True: fetus = eldest.CThelper() x.AddSuccessor(fetus) cc = eldest.store[1] + eldest.store[2] if (len(cc) == 2): eldest = cc[1] else: break return x
def square_tree(t): """Return a tree with the square of evey element in t >>> numbers = tree(1, [tree(2, [tree(3), tree(4)]), tree(5, [tree(6, [tree(7)]), tree(8)])]) >>> print_tree(square_tree(numbers)) 1 4 9 16 25 36 49 64 """ sq_branches = [square_tree(branch) for branch in branches(t)] return tree(label(t)**2, sq_branches)
def pureminimaxMakeTree(newroot, depth, player, opp): if depth == 0: # print("depth=0 and done!") return True options = playerMoveOptions(newroot.GetVal(), player) if options == []: print("no options...") return False # print("pureminimaxMakeTree with depth = ",depth) for possibility in options: tstBoard = GenTestBoard(list(newroot.GetVal()), possibility[0], possibility[1]) newbranch = tree(tstBoard) newroot.AddSuccessor(newbranch) #pureminimaxMakeTree(newbranch,depth-1,player) for successor in newroot.GetSuccessors(): pureminimaxMakeTree(successor, depth - 1, opp, player) return True
def Defensive(board, player): board_tree = tree(board) genTree(board_tree, player, 3, 12) Heuristic(board_tree, player) #displayTree(board_tree) if board_tree.children == []: return Random(board, player) heuristic_list = [] for child in board_tree.children: heuristic_list += [child.material + child.position] if player == 10: return board_tree.children[heuristic_list.index( max(heuristic_list))].move elif player == 20: return board_tree.children[heuristic_list.index( min(heuristic_list))].move else: return Random(board, player)
def GenerateHDL(name, XMLFile, HDLPath): print "Generate HDL for", name, "from", XMLFile #get working directory wd = os.getcwd() #move into the output HDL directory os.chdir(wd + "/" + HDLPath) #make a symlink to the XML file fullXMLFile = wd + "/" + XMLFile #generate a fake top address table slaveAddress = "0x" + hex(0x00000000)[2:] topXMLFile = "top.xml" outXMLFile = open(topXMLFile, 'w') outXMLFile.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n") outXMLFile.write("<node id=\"TOP\">\n") outXMLFile.write(" <node id=\"" + name + "\" module=\"file://" + fullXMLFile + "\" address=\"" + slaveAddress + "\"/>\n") outXMLFile.write("</node>\n") outXMLFile.close() #generate the HDL try: device = uhal.getDevice("dummy", "ipbusudp-1.3://localhost:12345", "file://" + topXMLFile) except Exception: raise Exception("File '%s' does not exist or has incorrect format" % topXMLFile) for i in device.getNodes(): if i.count('.') == 0: mytree = tree(device.getNode(i), log) mytree.generatePkg() mytree.generateRegMap(regMapTemplate=wd + "/regmap_helper/template_map.vhd") #cleanup os.remove(topXMLFile) os.chdir(wd) #go back to original path
def genTree(root, player, steps, n): #print "genTree, steps =",steps if steps == 0: return True other_player = 0 if player == 10: other_player = 20 elif player == 20: other_player = 10 candidate = [] if isInCheck(root.val, player): candidate = findOutCheck(root.val, player) else: candidate = candidateMoves(root.val, player, n) if candidate == []: return False #print "candidate",candidate #iterating through legal moves #preforming the move on a temperary board #adding it as a child to the successor list for C in candidate: if C != []: pos = C[0] new_pos = C[1] temp_board = copyBoard(root.val) temp_board[new_pos[0]][new_pos[1]] = temp_board[pos[0]][pos[1]] temp_board[pos[0]][pos[1]] = 0 child_tree = tree(temp_board) child_tree.move = C root.children += [child_tree] #iterating through the children of the tree #calling the function recursively on the child node and substracting 1 from step for T in root.children: genTree(T, other_player, steps - 1, n) return True
def getBestImprovement(self, i): ''' For a tree in the landscape, investigate neighbors to find a tree that leads to the best improvement of fitness function score on the basis of likelihood. :param i: a tree name (usually an integer) :return: a tree name (usually an integer) or None if no better tree ''' nodes = self.getNode tree = self.getTree ml = lambda d: tree(d).getScore()[0] if (not i in self.getNodeNames()): raise LookupError('No tree by that name in landscape.' % (i)) node = nodes(i) near = self.graph.neighbors(i) if (len(near) == 0): return None best = max(near, key=ml) if (best != None and ml(best) > ml(i)): return best else: return None
def genTree(root, player): if root == None: return False #enumerate child list with all possible moves empty = get_empty(root.val) #The base case to stop the recursion if empty == []: return False #adding a child for each element in empty for m in empty: root.AddSuccessor(tree(make_move(root.val,m,player))) #calling function recursively on each child other_player = 0 if player == 1: other_player = 2 elif player == 2: other_player = 1 for b in root.children: genTree(b,other_player) return True
from tree import * root=tree(1000) x=tree(2000) y=tree(3000) z=tree(4000) x1=tree(201) x2=tree(202) x3=tree(203) y1=tree(301) y2=tree(302) y3=tree(303) root.AddSuccessor(x) root.AddSuccessor(y) root.AddSuccessor(z) x.AddSuccessor(x1) x.AddSuccessor(x2) x.AddSuccessor(x3) y.AddSuccessor(y1) y.AddSuccessor(y2) y.AddSuccessor(y3) c=tree(3) d=tree(1) e=tree(4) f=tree(1) g=tree(5) f.AddSuccessor(g) e.AddSuccessor(f) d.AddSuccessor(e) c.AddSuccessor(d) z.AddSuccessor(c)
.format(N, len(train_set), len(test_set))) # STEP 3, LEARNING THE GRAMMAR print("\n######## LEARNING PCFG ########") def remove_functional(s): ''' e.g. NP-MOD -> NP ''' return s.split('-')[0] bin_forest = [] for tree_repr in train_set: t = tree(repr_to_root(tree_repr, label_filter=remove_functional)) t_b = t.get_binarized() bin_forest.append(t_b) pcfg = PCFG() pcfg.learn_from_bin_forest(bin_forest) print("PCFG statistics:\n") print( "\t{} terminals\n\t{} variables\n\t{} binary rules\n\t{} preterminal rules" .format(len(pcfg.terminals), len(pcfg.variables), len(pcfg.binary_rules), len(pcfg.preterminal_rules))) # STEP 4, parsing the test set with CKY print("\n######## PARSING TEST SET (CKY) ########") mean_perc = []
from tree import * from binary_tree import * a = tree('A') b = tree('B') c = tree('C') d = tree('D') e = tree('E') f = tree('F') g = tree('G') h = tree('H') i = tree('I') j = tree('J') k = tree('K') a.AddSuccessor(b) a.AddSuccessor(c) a.AddSuccessor(d) b.AddSuccessor(e) b.AddSuccessor(f) b.AddSuccessor(g) c.AddSuccessor(h) c.AddSuccessor(i) d.AddSuccessor(j) d.AddSuccessor(k) a.Print_DepthFirst() print(a.Get_LevelOrder()) A = a.ConvertToBinaryTree()