def createTreeFromBoard(board, level, tree): if (board.is_game_over() or level >= 3): return [] level = level + 1 #Create a new tree here and add all the moves and then newTree = Trees.Node(level, None) for move in board.legal_moves: #print(move.__str__().rjust(level * 5)) #Le soucis est que on veut avoir seulement les coups des blancs alors que c'est alterné avec les blancs et les noirs, donc on fait un coups dans le vide pour faire genre que les noirs ont joué #If this is the last level we put a number if (level == 2): newTree.childrens.append(Trees.Node(level, move, '1')) else: newTree.childrens.append(Trees.Node(level, move, '')) board.push(move) board.push(move) createTreeFromBoard(board, level, tree) board.pop() board.pop() tree.childrens.append(newTree)
def createGraphs(program, basepath): import UDrawGraph, ICFGs, Trees, IPGs Debug.debugMessage("Creating data structures", 1) for cfg in program.getCFGs(): functionName = cfg.getName() UDrawGraph.makeUdrawFile(cfg, basepath, "%s.%s" % (functionName, "cfg")) predomTree = Trees.Dominators(cfg, cfg.getEntryID()) reverseg = cfg.getReverseCFG() postdomTree = Trees.Dominators(reverseg, reverseg.getEntryID()) UDrawGraph.makeUdrawFile(predomTree, basepath, "%s.%s" % (functionName, "pre")) UDrawGraph.makeUdrawFile(postdomTree, basepath, "%s.%s" % (functionName, "post")) icfg = ICFGs.ICFG(cfg) icfg.setEntryID() icfg.setExitID() icfg.addExitEntryEdge() program.addICFG(icfg) UDrawGraph.makeUdrawFile(icfg, basepath, "%s.%s" % (functionName, "icfg")) lnt = Trees.LoopNests(icfg, icfg.getEntryID()) program.addLNT(lnt) UDrawGraph.makeUdrawFile(lnt, basepath, "%s.%s" % (functionName, "lnt")) ipg = IPGs.IPG(icfg, lnt) program.addIPG(ipg) icfg.addBranchDivergenceEdges(lnt) ipg.updateWithBranchDivergentPaths() UDrawGraph.makeUdrawFile(icfg, basepath, "%s.%s" % (functionName, "icfg")) UDrawGraph.makeUdrawFile(ipg, basepath, "%s.%s" % (functionName, "ipg"))
def dest(event): print(name_entry.get()) string_dish.append(name_entry.get()) prog.insert_type_string_excel(string_dish) # Ввод типа в таблицу Excel trees.insert_type_string( ) # Вывод типа в treeview (в типы и в полную таблицы) print("KILL") ins_enter.destroy() # Удаление окна
def del_tree(): """ Автор: Исмаилов Асад Цель: Вызывается кнопкой "Удалить", очищает существующий treeview Вход: Нет входных данных Выход: Пустой treeview """ trees.delete_all_trees()
def delete_str(): """ Автор: Исмаилов Асад Цель: Вызывается кнопкой "Удалить строку", удаляет данные выделенной строки и зависящих от нее строк из treeview и Excel Вход: Нет входных данных Выход: Нет выходных данных """ global note_tree trees.deleting_string(note_tree)
def open_table(): """ Автор: Исмаилов Асад, Гамидов Шамсудин Цель: Вызывается кнопкой "Открыть", открытие вводимой пользователем таблицы и вывод ее данных в treeview Вход: Нет входных данных Выход: Обновленный treeview """ file_name = filedialog.askopenfilename( ) # Получение директории папки с данными print(file_name) prog.open_table_name(file_name) trees.open_tables()
def dest(event): print(name_entry.get()) string_dish.append(name_entry.get()) string_dish.append(price_entry.get()) string_dish.append(size_entry.get()) string_dish.append(typed_entry.get()) print(string_dish) prog.insert_menu_string_excel( string_dish) # Ввод блюда в таблицу Excel trees.insert_menu_string( ) # Вывод блюда в treeview (в Меню и в полную таблицы) print("KILL") ins_enter.destroy() # Удаление окна
def expression(self): me = Trees.Tree() if self.Tok.type == "ID": # aR' # semantic: check table for id me.addNextOperand(self.Tok) if self.Works[self.boi + 1].dataC != "(": symb = self.Table.getSymbol(self.Tok.dataC) else: symb = self.Table.getFuncSymbol(self.Tok.dataC) self.sDict[ "ID"] = self.Tok.dataC # capture ID #add to druple maybe # accept: ID self.accept(self.Tok.type, "ID") expr = self.expression_prime(me) last = self.createInstruct(me.root) return self.testExpression([symb, expr]), (last, me.root) elif self.Tok.type == "INTEGER" or self.Tok.type == "FLOAT": # bX'V'T' me.root = Trees.TreeNode(self.Tok) if self.Tok.type == "FLOAT": type = "float" else: type = "int" num = Symbol(type, "NUM", self.Tok.dataC) # accept: NUM self.accept(self.Tok.type, self.Tok.type) term = self.term_prime(me) adde = self.additive_expression_prime(me) sime = self.ok_expression_prime(me) last = self.createInstruct(me.root) return self.testExpression([num, term, adde, sime]), (last, me.root) elif self.Tok.dataC == "(": # accept: ( self.accept(self.Tok.dataC, "(") expr = self.expression() last = expr[1][1] expr = expr[0] if self.Tok.dataC == ")": # accept: ) self.accept(self.Tok.dataC, ")") term = self.term_prime(me) adde = self.additive_expression_prime(me) sime = self.ok_expression_prime(me) last = self.createInstruct(me.root) return self.testExpression([expr, term, adde, sime]), (last, me.root) print("REJECT") sys.exit(0)
def dest(event): string_dish.append(0) string_dish.append(data_entry.get()) string_dish.append(time_entry.get()) string_dish.append(code_dish_entry.get()) string_dish.append(kolvo_entry.get()) print(string_dish) prog.insert_orders_string_excel( string_dish) # Ввод заказа в таблицу Excel trees.insert_orders_string( ) # Вывод заказа в treeview (в Заказы и в полную таблицу под блюдо из заказа) print("KILL") ins_enter.destroy() # Удаление окна
def experiment6(): k = 1 n_features_list = np.arange(0, 30, 2) + 2 n_data = 10**4 n_targets = 1000 results = [] for n_features in n_features_list: data = np.random.uniform(0, 1, n_data * n_features).reshape( (n_data, n_features)) targets = np.random.uniform(0, 1, n_targets * n_features).reshape( (n_targets, n_features)) model = Trees.VPTree(data, 2, similarity_metric='euclidean') number_of_comparisons = experiment_number_of_comparisons_model( targets, data, model, k, 6, 'vp_tree_2') results.append(number_of_comparisons) plt.clf() plt.boxplot(results) plt.xticks(np.arange(len(n_features_list)) + 1, n_features_list) plt.title( 'Number of comparisions in vp tree, for different dimensionalities\nNumber of data points: {0}\nNumber of trials: {1}' .format(n_data, n_targets)) plt.ylabel('number of comparisons') plt.xlabel('number of dimensions') plt.margins(0.2, 0.2) plt.savefig('simulation6_number_of_comparisons.jpg', bbox_inches='tight')
def getZoneStats(gameFrame): centerPoint = [297,280] size = 180 edgeBuffer = 10 half = size//2 threeHalf = int(1.5 *size) zoneFrame = gameFrame[(centerPoint[1] - threeHalf - edgeBuffer):(centerPoint[1] + threeHalf + edgeBuffer), (centerPoint[0] - threeHalf - edgeBuffer):(centerPoint[0] + threeHalf + edgeBuffer)] obsFrame = gameFrame[(centerPoint[1] - 60):(centerPoint[1] + 60), (centerPoint[0] - 60):(centerPoint[0] + 60)] bulletCenters = Bullets.getBulletCenters(zoneFrame) enemyCenters = GetData.getEnemiesScreen1(zoneFrame) obsMask = Trees.getObstacleMask(obsFrame,10) # 10 - Color range +/- 10 BGR values obstacle_array = getObstacles(obsMask,50) # 50 - Mean for mask value. 0 black, 255 white bulletZoneCount = getZoneCounts(zoneFrame.shape,bulletCenters,size) enemyZoneCount = getZoneCounts(zoneFrame.shape,enemyCenters,size) zoneStats = [] for i in range(0,8): zoneStats.append((obstacle_array[i],bulletZoneCount[i],enemyZoneCount[i])) return zoneStats
def proposeCanvasSize(normalTokens): """ Given a list of normalized tokens we propose a canvase size (width, height) based on the areas covered by words. The areas are determined via leaves of the corresponding quadTrees. It is assumed that tokens come sorted (DESC), i.e. bigger sized words come first. We use this assumption when enforcing the canvas size to be larger than total area of the bounding boxes of the first few tokens. """ area = 0 # the area covered by the quadTrees, i.e. the actual shape of the token boxArea = [] # the areas covered by the bounding box of the tokens for token in normalTokens: area += token.quadTree.areaCovered() boxArea.append(Trees.rectArea(token.quadTree.root.value)) ensure_space = 5 # force the sum of the total area to cover at least the first @ensure_space tokens total = area + sum(boxArea[:ensure_space]) w = int(math.sqrt(total / DESIRED_HW_RATIO)) + 1 h = int(DESIRED_HW_RATIO * w) + 1 print( 'Ratio of the area covered by trees over the total area of bounding boxes of words', area / sum(boxArea)) return w, h
def dest_type(event): print(name_entry.get()) string_dish.append(name_entry.get()) index_type = trees.changing_string(note_tree, string_dish) prog.change_type_string_excel( string_dish, index_type) # Ввод типа в таблицу Excel print("KILL") ins_enter.destroy() # Удаление окна
def main(): """Program to demonstrate trees of different types.""" # Let's make some trees of different classes (subclasses) tree_list = [ trees.Tree(), trees.EvenTree(), trees.UpsideDownTree(), trees.WideTree(), trees.QuickTree(), trees.FruitTree(), trees.PineTree() ] # display all the trees for tree in tree_list: print(tree.__class__) print(tree) print("Time to grow!") # grow them several times for _ in range(5): for tree in tree_list: tree.grow(5, 2) # display all the trees again for tree in tree_list: print(tree.__class__) print(tree)
def experiment1(): print('Running simulation 1') n_data = 10**4 n_features = 30 k = 1 data = np.random.uniform(0, 1, n_data * n_features).reshape( (n_data, n_features)) n_targets = 1000 targets = np.random.uniform(0, 1, n_targets * n_features).reshape( (n_targets, n_features)) model_names = [ 'kd-tree', 'vp-tree-2', 'vp-tree-10', 'vp-tree-100', 'pp-100-100', 'pp-1000-1000' ] results = [] for i in range(2): if i == 0: model = Trees.KDTree(data, similarity_metric='euclidean') elif i == 1: model = Trees.VPTree(data, 2, similarity_metric='euclidean') elif i == 2: model = Trees.VPTree(data, 10, similarity_metric='euclidean') elif i == 3: model = Trees.VPTree(data, 100, similarity_metric='euclidean') elif i == 4: model = NewDataStructures.PavlosIndexingSystem( data, 100, 100, similarity_metric='euclidean') else: model = NewDataStructures.PavlosIndexingSystem( data, 1000, 1000, similarity_metric='euclidean') number_of_comparisons = experiment1_model(targets, data, model, k, model_names[i]) results.append(number_of_comparisons) plt.clf() plt.boxplot(results) plt.margins(0.2, 0.2) plt.xticks(np.arange(len(model_names)) + 1, model_names, rotation='vertical') plt.title( 'Number of comparisions per model\nNumber of data points: {0}\nDimensionality: {1}\nNumber of trials: {2}\nk={3}' .format(n_data, n_features, n_targets, k)) plt.ylabel('number of comparisons') plt.savefig('simulation1_number_of_comparisons.jpg', bbox_inches='tight')
def __solveDFF(self, forwardBranches): # Initialise data structures needed vertexToReachable = {} for v in self: vertexToReachable[v] = set([]) # Do a reverse post-order. Avoid the entry vertex dfs = Trees.DepthFirstSearch(self, self._entryID) postID = self.numOfVertices() - 1 while postID >= 1: vertexID = dfs.getPostorderVertexID(postID) v = self.getVertex(vertexID) vertexToReachable[v].add(vertexID) for predID in v.getPredecessorIDs(): predv = self.getVertex(predID) vertexToReachable[v].add(predID) vertexToReachable[v].update(vertexToReachable[predv]) postID -= 1 # Now analyse the immediate post-dominator reverseg = self.getReverseCFG() postdomTree = Trees.Dominators(reverseg, reverseg.getEntryID()) for vertexID in forwardBranches: Debug.debugMessage("Vertex %d is a forward branch" % vertexID, 5) branchv = self.getVertex(vertexID) succSet = set(branchv.getSuccessorIDs()) treev = postdomTree.getVertex(vertexID) parentID = treev.getParentID() mergev = self.getVertex(parentID) Debug.debugMessage( "Analysing region (%d, %d)" % (vertexID, parentID), 5) # for succID in branchv.getSuccessorIDs(): # if succID != parentID: # self.addEdge(parentID, succID) # self.__branchDivergentEdges.append((parentID, succID)) for predID in mergev.getPredecessorIDs(): predv = self.getVertex(predID) newsuccs = set.difference(succSet, vertexToReachable[predv]) for newsuccID in newsuccs: if newsuccID not in predv.getSuccessorIDs( ) and newsuccID != predID: self.addEdge(predID, newsuccID) self.__branchDivergentEdges.append((predID, newsuccID))
def create_tree(): """ Автор: Ворожцов Михаил Цель: Вызывает функции создания tree в note_tree Вход: - Выход: - """ trees.create_tree_type(f_type, root) trees.create_tree_orders(f_orders, root) trees.create_tree_menu(f_menu, root) trees.create_tree_full(f_full, root)
def ConexComponentsDFS(self): ''' Creates all the conex components using a dfs algorithm ''' tree = Trees.Trees() for vertex in self.__vertices: if not tree.isVertex(vertex): tree.newRoot(vertex) self.DFS(tree, vertex) #print(tree.ThisRoot(vertex)) print(self.store_edges)
def getHuffmanTree(self, f): """for tupla in f: print(tupla) input()""" if len(f) == 2: """Crear y regresar arbol""" left = Trees.Tree(None, None, f[0]) rigth = Trees.Tree(None, None, f[1]) return Trees.Tree(left, rigth) etiqueta = str(f[0][2]) + "+" + str(f[1][2]) fcopy = f.copy() del fcopy[0] del fcopy[0] fcopy.append((None, None, f[0][2] + f[1][2], [etiqueta])) fcopy.sort(key=lambda tupla: tupla[2]) t = self.getHuffmanTree(fcopy) left = Trees.Tree(None, None, f[0]) rigth = Trees.Tree(None, None, f[1]) self.insertarArbol(t, left, rigth, etiqueta) return t
def dest_dish(event): print(name_entry.get()) string_dish.append(name_entry.get()) string_dish.append(price_entry.get()) string_dish.append(size_entry.get()) string_dish.append(typed_entry.get()) print(string_dish) index_dish = trees.changing_string(note_tree, string_dish) prog.change_dish_string_excel( string_dish, index_dish) # Ввод типа в таблицу Excel print("KILL") ins_enter.destroy() # Удаление окна
def loadSinks(self): self.sink_list.add(Info.init()) self.sink_list.add(Buttons.init()) self.sink_list.add(Menus.init()) self.sink_list.add(Images.init()) self.sink_list.add(Layouts.init()) self.sink_list.add(Lists.init()) self.sink_list.add(Popups.init()) self.sink_list.add(Tables.init()) self.sink_list.add(Text.init()) self.sink_list.add(Trees.init()) self.sink_list.add(Frames.init()) self.sink_list.add(Tabs.init())
def loadSinks(self): self.sink_list.addSink(Info.init()) self.sink_list.addSink(Buttons.init()) self.sink_list.addSink(Menus.init()) self.sink_list.addSink(Images.init()) self.sink_list.addSink(Layouts.init()) self.sink_list.addSink(Lists.init()) self.sink_list.addSink(Popups.init()) self.sink_list.addSink(Tables.init()) self.sink_list.addSink(Text.init()) self.sink_list.addSink(Trees.init()) self.sink_list.addSink(Frames.init()) self.sink_list.addSink(Tabs.init())
def run(self, inState): inState.mBuilder = Builder.Builder(inState.getView()) hierarchy = Trees.getMeshHierarchy(inState.getView().getOutputNode()) hierarchy = hierarchy.filterByShape(['mesh']) if hierarchy is None: raise Exception( 'Filtered hierarchy contains no valid mesh elements!') hierarchy.mDataBuilder = None # The pivot root isn't always going to be the primary root of the object, so ensure it's invalidated if len(hierarchy.mChildren) <= 1: hierarchy.mChildren[0].iterate( inState.getBuilder().fillHierarchyInfo) else: hierarchy.iterate(inState.getBuilder().fillHierarchyInfo) inState.mCachedHierarchy = hierarchy
import kNN import matplotlib import matplotlib.pyplot as plt import numpy as np import Trees import treePlotter data, labels = Trees.createDataSet() tree = treePlotter.retrieveTree(0) print(data, labels, tree) print(Trees.classify(tree, labels, [1, 1]))
# -*- coding: utf-8 -*- from numpy import * import Trees myDat, labels = Trees.createDataSet() print Trees.calcEntropy(myDat)
# -*- coding: utf-8 -*- import Trees as Tr import Independence_Polys as IP T = Tr.Tree(10) T.print_rel() P = IP.IndeP(10) print(P.The_Polynom) # print(P.The_Tree.print_rel()) # P.The_Polynom.show_graph(-10, 10) # print(P.The_Polynom.roots())
import operator import sys sys.path.append('E:\MeachineLearn\Decision_Tree\DecisionTree\Trees.py') sys.path.append('E:\MeachineLearn\Decision_Tree\DecisionTree\treePlotter.py') import Trees import treePlotter #fr = open('E:\machinelearninginaction\Ch03\lenses.txt'); #lenses = [inst.strip().split('\t') for inst in fr.readlines()] #lensesLabels = ['age','prescript','astigmatic','tearRate'] #lensesTree = Trees.createTree(lenses,lensesLabels) #print(lensesTree) #treePlotter.createPlot(lensesTree); dataSet, labels = Trees.createDataSet() print(labels) mytree = Trees.createtree(dataSet, labels) label = Trees.classify(mytree, labels, [1, 0]) print(label)
def __init__(self, size: int) -> object: self.The_Tree = trs.Tree(size) self.The_Polynom = self.ComputePOL(self.The_Tree)
>>> q8(tree.root.left.right.right) # i的下一个节点是a a """ if node.right: node = node.right while node.left: node = node.left print(node.value) return elif node.parent.left is node: print(node.parent.value) return else: while node.parent is not None: if node.parent.left is node: print(node.parent.value) return else: node = node.parent continue print(node.value) return if __name__ == '__main__': tree = Trees.BTree(with_parent=True) tree.build(pre_ord=['a', 'b', 'd', 'e', 'h', 'i', 'c', 'f', 'g'], in_ord=['d', 'b', 'h', 'e', 'i', 'a', 'f', 'c', 'g']) if not doctest.testmod().failed: print('Well Done!')
#!/usr/bin/env python #-*- coding:UTF-8 -*- #中文支持 #决策树 from numpy import * import operator import os import Trees myData,labels=Trees.createDataSet() print(myData) print(labels) print(Trees.calcShannonEnt(myData)) myData[0][-1]='maybe' print(myData) print(labels) print(Trees.calcShannonEnt(myData)) myDat,labels=Trees.createDataSet() print(myDat) print(Trees.splitDataSet(myDat,0,1)) print(Trees.splitDataSet(myData,0,0)) print(Trees.chooseBestFeatureToSplit(myDat)) myTree=Trees.createTree(myDat,labels) print(myTree)
def create_buttons(): """ Автор: Ворожцов Михаил Цель: Создает кнопки в note Вход: - Выход: """ global style_all #Таблица but_new_table = ttk.Button(f_table, text="Открыть", width=9, command=open_table) but_new_table.place(x=10, y=17) but_save = ttk.Button(f_table, text="Сохранить", width=9, command=save_table) but_save.place(x=130, y=17) but_excp = ttk.Button(f_table, text="Сохранить как", width=13, command=export_table) but_excp.place(x=250, y=17) but_del_table = ttk.Button(f_table, text="Удалить", width=9, command=del_tree) but_del_table.place(x=400, y=17) but_сustomize = ttk.Button( f_table, text="Кастомизация", width=13, command=lambda: custom.create_menu_castom(style_all, lb, root)) but_сustomize.place(x=520, y=17) #Изменить but_add_type = ttk.Button(f_insert, text="Добавить тип", width=16, command=entry_type) but_add_type.place(x=10, y=17) but_add = ttk.Button(f_insert, text="Добавить блюдо", width=16, command=entry_dish) but_add.place(x=185, y=17) but_add_orders = ttk.Button(f_insert, text="Добавить заказ", width=16, command=entry_orders) but_add_orders.place(x=360, y=17) but_change = ttk.Button(f_insert, text="Изменить строчку", width=16, command=change_str) but_change.place(x=535, y=17) but_del_row = ttk.Button(f_insert, text="Удалить строчку", width=16, command=delete_str) but_del_row.place(x=710, y=17) #Анализ combo_val_f = ["X","Дата посещения", "Время посещения","Код блюда", "Количество порций", "Сумма заказа",\ "Стоимость", "Размерность", "Тип блюда"] combo_val_t = ["Y","Дата посещения", "Время посещения","Код блюда", "Количество порций", "Сумма заказа",\ "Стоимость", "Размерность", "Тип блюда"] combo_1 = ttk.Combobox(f_analysis, width=25) combo_1["values"] = combo_val_f combo_1.current(0) combo_1.place(x=10, y=5) combo_2 = ttk.Combobox(f_analysis, width=25) combo_2["values"] = combo_val_t combo_2.current(0) combo_2.place(x=10, y=40, height=25) but_histo = ttk.Button(f_analysis, text="Гистограмма", width=21, command=lambda: trees.histo(combo_1.get())) but_histo.place(x=210, y=3) #17 but_barchart = ttk.Button( f_analysis, text="Ступенчатая диаграмма", width=21, command=lambda: trees.barchart(combo_1.get(), combo_2.get())) but_barchart.place(x=210, y=40) but_box = ttk.Button(f_analysis, text="Диаграмма размаха", width=21, command=lambda: trees.box_plot(combo_1.get())) but_box.place(x=440, y=3) but_scatter = ttk.Button( f_analysis, text="Точечная диаграмма", width=21, command=lambda: trees.scatter_plot(combo_1.get(), combo_2.get())) but_scatter.place(x=440, y=40)