def about(self): """Display overview of program in window""" self.about_window = Window(title="About") path_file = path.resource_path("about.txt") print(f"\nOpened file at {path_file}\n") f = open(path_file, "r") about_text = f.read() text_widget = Text(self.about_window) text_widget.insert("1.0", about_text) text_widget.pack(expand=True, fill="both") text_widget.config(state="disabled")
def manual(self): """Display program manual in window""" self.manual_window = Window(title="Manual", width=self.scaled_width, height=self.scaled_height // 2) path_file = path.resource_path("manual.txt") print(f"\nOpened file at {path_file}\n") f = open(path_file, "r") manual_text = f.read() text_widget = Text(self.manual_window, width=30) text_widget.insert("1.0", manual_text) scroll = Scrollbar(text_widget, command=text_widget.yview) text_widget['yscrollcommand'] = scroll.set scroll.pack(side="right", fill="y") text_widget.pack(expand=True, fill="both") text_widget.config(state="disabled")
# arguments for selenium to help speed up chromedriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("no-sandbox") chrome_options.add_argument('--lang=en_US') chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-extensions") chrome_options.add_argument('window-size=800,600') chrome_options.add_argument('--blink-settings=imagesEnabled=false') chrome_options.add_experimental_option("useAutomationExtension", False) prefs = {"profile.managed_default_content_settings.images": 2} chrome_options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(resource_path('chromedriver_dir/chromedriver'), options=chrome_options) # erases a test logger and makes a new one at INFO level # os.remove(resource_path('test.log')) FORMAT = f'[%(asctime)-15s][{skuId}] %(message)s' root = logging.getLogger() root.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter(FORMAT) handler.setFormatter(formatter) root.addHandler(handler)
import pygame as pg from path import resource_path pg.init() X = pg.image.load(resource_path('X.png')) O = pg.image.load(resource_path('O.png')) Board = pg.image.load(resource_path('Board.png'))
def rspr_pairwise(trees): """ Takes a list of trees and runs rspr for every pair of trees Parameters ---------- trees : list[str] Array of trees in newick format Returns ------- tuple(list[str], list[str], list[Tree]) Tuple of distance array, clusters array and trees array """ #Calculating total number of comparisons num_comparisons = 0 for i in range(len(trees) + 1): num_comparisons += i print("\nPerforming pairwise distance calculation...") length = len(trees) tree_error_text = "Error with format. Check that tree has correct number of opening and closing brackets and terminates with semicolon." trees_array = [None] * length for i, tree_string in enumerate(trees): trees_array[i] = f"t{i+1}:\n{tree_string};\n{tree_error_text}\n" distance_array = [["-" for i in range(length)] for j in range(length)] clusters_array = [["-" for i in range(length)] for j in range(length)] compare_count = 1 file = path.resource_path("rspr.exe") print(f" Opening file at {file}") for i in range(len(trees)): for j in range(i, len(trees)): try: compare_count += 1 t1 = Tree(trees[i] + ";", f"t{i+1}") t2 = Tree(trees[j] + ";", f"t{j+1}") trees_array[i] = t1 #Check if leaf set the same t1_leaves = t1.labelled_leaves t2_leaves = t2.labelled_leaves if t1.has_unlabelled_leaf() or t2.has_unlabelled_leaf(): distance_array[i][j] = "X" clusters_array[i][j] = [ "Error occured. Tree(s) contain unlabelled leaves. Make sure all leaves are labelled." ] elif t1_leaves == t2_leaves: (distance, clusters) = rspr(t1.eNewick(), t2.eNewick()) distance_array[i][j] = distance clusters_array[i][j] = clusters else: missing_leaves = (t1_leaves.difference(t2_leaves)).union( t2_leaves.difference(t1_leaves)) distance_array[i][j] = "X" clusters_array[i][j] = [ f"Error occured. Trees don't have same taxa set. Missing taxa: {', '.join(missing_leaves)}" ] print( f'\r {round(compare_count / num_comparisons*100)}% complete: Calculating between t{i+1} and t{j+1}', end="\r", flush=True) except MalformedNewickException: distance_array[i][j] = "X" clusters_array[i][j] = [ "Error occured. Check tree newick string." ] print( f'\r 100% complete: pairwise distance calculated for {len(trees)} trees\n' ) return (distance_array, clusters_array, trees_array)
def calculate_drspr(trees): """ Calculates drSPR. If more than 2 trees are given, distances are calculated pairwise Parameters ---------- trees_array : list[str] Array of trees in newick format. String of input trees split by semicolon. Returns ------- tuple[list[str], list[str], Trees] Tuple of distance array, clusters array and Trees object """ length = len(trees) if length < 2: raise MalformedNewickException elif length == 2: trees_array = [None] * length for i, tree_newick in enumerate(trees): trees_array[i] = f"t{i+1}:\n{tree_newick};" for i in range(len(trees_array)): try: trees_array[i] = Tree(trees[i] + ";", f"t{i+1}") except MalformedNewickException: trees_array[ i] = f"{trees_array[i]}\nError with format. Check that tree has correct number of opening and closing brackets and terminates with semicolon.\n" distances = ["X"] clusters = ["Error occured. Check tree newick strings."] #return (distances, clusters, Trees(trees_array)) try: t1_leaves = trees_array[0].labelled_leaves t2_leaves = trees_array[1].labelled_leaves t1_unlabelled_leaves = trees_array[0].has_unlabelled_leaf() t2_unlabelled_leaves = trees_array[1].has_unlabelled_leaf() if t1_unlabelled_leaves or t2_unlabelled_leaves: return (["X"], [ "Error occured. Tree(s) contain unlabelled leaves. Make sure all leaves are labelled." ], Trees(trees_array)) elif t1_leaves == t2_leaves: file = path.resource_path("rspr.exe") print(f" Opening file at {file}") (distances, clusters) = rspr(trees_array[0].eNewick(), trees_array[1].eNewick()) else: missing_leaves = (t1_leaves.difference(t2_leaves)).union( t2_leaves.difference(t1_leaves)) return (["X"], [ f"Error occured. Trees don't have same taxa set. Missing taxa: {', '.join(missing_leaves)}" ], Trees(trees_array)) except AttributeError: return (distances, clusters, Trees(trees_array)) else: (distances, clusters, trees_array) = rspr_pairwise(trees) trees_obj = Trees(trees_array) return (distances, clusters, trees_obj)
def rspr(tree1, tree2): """ Runs an external executable that calculates the rspr of 2 binary phylogenetic trees Parameters ---------- tree1 : str tree2 : str Two trees to compute distance Returns ------- tuple[list[str], list[str]] Tuple of array of distances and array of clusters """ input_string = tree1 + "\n" + tree2 if platform.system() == "Windows": file = path.resource_path("rspr.exe") executable = Popen(executable=file, args="", stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True) out, err = executable.communicate(input=input_string) executable.wait() executable.kill() else: file = path.resource_path("rspr") file = file.replace(" ", "\ ") executable = subprocess.run(file, stdout=PIPE, stderr=PIPE, input=input_string.encode("utf-8"), shell=True) out = executable.stdout.decode("utf-8") err = executable.stderr.decode("utf-8") out = out.strip() output_list = out.split("\n") if err: print(err) print("Error occured in rspr") length = len(output_list) forest = output_list[length - 3] distance = output_list[-1].split() distance = distance[-1] equals_index = distance.index("=") distance = distance[equals_index + 1:] clusters = forest.split()[2:] return (distance, clusters)
def spr_dense_graph(self): """Gets neighbours of a single tree""" trees_string = "\n".join(self.valid_trees) if platform.system() == "Windows": file = path.resource_path("spr_dense_graph.exe") executable = Popen(executable=file, args="", stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True) out, err = executable.communicate(input=trees_string) executable.wait() executable.kill() else: file = path.resource_path("spr_dense_graph") file = file.replace(" ", "\ ") executable = subprocess.run(file, stdout=PIPE, stderr=PIPE, input=trees_string.encode("utf-8"), shell=True) out = executable.stdout.decode("utf-8") err = executable.stderr.decode("utf-8") out = out.strip() print(f"\nOpening file at {file}") if err: print(err) print("Error occured in spr_dense_graph") #Create adjacency dict output_lines = out.split() self.adjacency_dict = {} print("\nCreating adjacency list") total_lines = len(output_lines) for i, line in enumerate(output_lines): array = line.split(",") node_index = int(array[0]) neighbour_index = int(array[1]) node_tree = self.valid_trees[node_index] neighbour_tree = self.valid_trees[neighbour_index] node = self.tree_label_dict[node_tree] neighbour = self.tree_label_dict[neighbour_tree] if node in self.adjacency_dict: self.adjacency_dict[node].append(neighbour) else: self.adjacency_dict[node] = [neighbour] print( f'\r {round(i / total_lines * 100)}% complete: Processed {i} / {total_lines} lines', end="\r", flush=True) print(" 100% complete: rSPR graph adjacency list complete")