def buildOpeningTree(openings): tree = tr.Tree() for x in reversed(openings): li = openings[x].split(" ") tree.builder(tree.root, x, li) return tree
def __init__(self, expr = '#', nome = ''): self.expr = expr self.nome = nome self.syntax_tree = tree.Tree()
import tree import plot set_up_times = {} match_times = {} abscissa = [90, 900, 9000, 90000, 900000] if __name__ == '__main__': # load data dataload.load() # simulate for route_basic_count in abscissa: # generate [route_numbers, route_lengths] = dataload.get_with_random(route_basic_count) new_tree = tree.Tree(numbers=route_numbers, lengths=route_lengths) set_up_time = new_tree.generate() set_up_times[route_basic_count] = set_up_time # match match_cost = {} for route_match_count in abscissa: match_time = new_tree.match_all(route_match_count) match_cost[route_match_count] = match_time match_times[route_basic_count] = match_cost # plot print(set_up_times) print(match_times) plot.plot(abscissa=abscissa, set_up_times=set_up_times, match_times=match_times)
def create_bst(arr): t = tree.Tree() t.root = create_subtree(arr) return t
# Spring 2015 # CS 151 Project 10 # # project10lsystemtest.py version 1 #--------------------------------------------- #imports import lsystem as ls import shapes as s import turtle as t import turtle_interpreter as it import tree #=========================================================== t.tracer(False) t1 = tree.Tree(filename= 'project11extension2a.txt') t1.setIterations(3) t1.setColor('OliveDrab') t1.draw(-230, -200, 2, 90) t2 = tree.Tree(filename= 'project11extension2b.txt') t2.setIterations(3) t2.setColor('LawnGreen') t2.draw(215, -200, 2, 90) if __name__ == "__main__": raw_input("Press enter to continue")
def plugWords(T): global curSent for x in T.ch: if len(x.ch) == 0: if len(curSent) > 0: x.c = curSent.pop(0) else: curSent = words.next().split() x.c = curSent.pop(0) else: plugWords(x) T = tree.Tree() # test = '(S-lS (S (Q-bA Are) (A-lA (N-lA (N tourists) (A-aN-lM (A-aN-v enticed) (R-aN-lM (R-aN-bN by) (N-lA (R-aN-x-lM (R-aN-x these)) (N attractions))))) (A-aN (A-aN-bN threatening) (N-lA (D-lA (D their)) (N-aD (A-aN-x-lM (A-aN-x very)) (N-aD existence)))))) (. ?))' # testwrds = 'Are tourists enticed by these attractions threatening their very existence ?' # T.read(test) # plugWords(T, testwrds.split()) # print T for line in trees: T.read(line) plugWords(T) print T words.close() trees.close()
def WriteResults(species_tree_fn_or_text, roots, S, clades, clusters_counter, output_dir): # for c in clusters_counter: # print((clusters_counter[c], c)) print("\nResults written to:\n" + os.path.realpath(output_dir)) # Label species tree nodes species_tree = tree.Tree(species_tree_fn_or_text) thisRoot = roots[0] species_tree = RootAtClade(species_tree, thisRoot) iNode = 0 for n in species_tree.traverse(): if not n.is_leaf(): n.name = "N%d" % iNode iNode+=1 species_tree.write(outfile=output_dir + "Species_tree_labelled.tre", format=1) # print(species_tree) # species_tree = tree.Tree(output_dir + "Species_tree_labelled.tre", format=1) # Calculate probabilities qBinary = True for n in species_tree.traverse(): if len(n.get_children()) > 2: qBinary = False if qBinary: p_final = probroot.GetProbabilities(species_tree, S, clades, clusters_counter) else: print("Probability distribution for root location is not supported for non-binary trees") print("To get a probability distribution for the root, please supply a fully resolved input species tree") # Write numbers of duplications table = dict() new_tree = tree.Tree(output_dir + "Species_tree_labelled.tre", format=1) for clade in clades + [frozenset([s]) for s in S]: qAnti = False anticlade = S.difference(clade) if len(clade) == 1: node = new_tree & list(clade)[0] else: node = new_tree.get_common_ancestor(clade) if node == new_tree: node = new_tree.get_common_ancestor(anticlade) qAnti = True x = anticlade if qAnti else clade y = clade if qAnti else anticlade X = ("(%d)" % clusters_counter[x]) if len(clade) == 1 else clusters_counter[x] if qBinary: p = p_final[clade] if clade in p_final else p_final[anticlade] else: p = 0. table[node.name] = [node.name, "X" if (clade in roots or anticlade in roots) else "", "%0.1f%%" % (100.*p) , X, clusters_counter[y]] with open(output_dir + "Duplication_counts.tsv", 'wb') as outfile: writer = csv.writer(outfile, delimiter="\t") writer.writerow(["Branch", "MP Root", "Probability", "Duplications supporting clade", "Duplications supporting opposite clade"]) qSingle = len(thisRoot) == 1 root_branches = [n.name for n in new_tree.get_children()] writer.writerow([root_branches[0] + " (& " + root_branches[1] + ")"] + table[root_branches[0]][1:]) for i in range(2 if qSingle else 3, iNode): name = "N%d" % i if name in table: writer.writerow(table[name]) else: print("Skipping %s" % name) for sp in S: if sp in table: if qSingle and sp in thisRoot: continue writer.writerow(table[sp])
args = parser.parse_args() # Show CAE window and get window ID # A new logger's handler is created here if os.name == 'nt': w = gui.window.Windows_window(p, s) else: w = gui.window.Linux_window(p, s) w.show() w.wid1 = w.get_wid('CalculiX Advanced Environment') if s.align_windows: w.align() # Main block m = model.Model() # generate FEM model t = tree.Tree(p, s, w, m) # create treeView items based on KOM j = model.job.Job(p, s, w, m) # create job object actions.actions(p, s, w, m, t, j) # window actions # Import default model if len(args.inp): start_model = os.path.join(p.app_home_dir, args.inp) importer.import_file(p, s, w, m, t, j, start_model) # Or start empty else: logging.warning('No default start model specified.') m.KOM = model.kom.KOM(p, s) t.generateTreeView(m) logging.info('Started in {:.1f} seconds.\n'.format(time.perf_counter() -
f = Cx[t,'f'] j = s pretrm = Cx[t,'p'] ancstr = Cx[t-1].getAncstr(f) lchild = Cx[t-1].getLchild(f,pretrm) opL = getOp( tr.ch[0].c, tr.ch[1].c, tr.c ) opR = getOp( tr.ch[1].c, tr.ch[0].c, tr.c ) print 'J', ','.join(Cx[t-1].calcJoinPredictors(f,pretrm)), ':', ('j1' if j==1 else 'j0') + '&' + opL + '&' + opR print 'A', ' '.join(Cx[t-1].calcApexCatPredictors(f,j,opL,pretrm)), ':', re.sub('-l.','',tr.c) print 'B', ' '.join(Cx[t-1].calcBrinkCatPredictors(f,j,opL,opR,pretrm,re.sub('-l.','',tr.c))), ':', re.sub('-l.','',tr.ch[1].c) Cx[t] = StoreState( Cx[t-1], f, j, opL, opR, re.sub('-l.','',tr.c), re.sub(':','Pk',re.sub('-l.','',tr.ch[1].c)), pretrm ) # print str(Cx[t-1]) + ' ===(' + str(lchild.sk) + ')==> ' + str(Cx[t]) ## traverse right child... t = calccontext ( tr.ch[1], Cx, t, 1, d ) return t for line in sys.stdin: # print line tr = tree.Tree() tr.read ( line ) Cx = collections.defaultdict(list) Cx[0] = StoreState() t = calccontext ( tr, Cx ) print 'J', ','.join(Cx[t-1].calcJoinPredictors(Cx[t,'f'],Cx[t,'p'])), ': j1&S&I' # for k in sorted(Cx): # print str(k) + str(Cx[k])
time = 18 #For mp4 saving purposes numTrees = 8 print("Running") # Create new Figure with black background fig = plt.figure(figsize=(16, 8), facecolor=bgColor) # Add a subplot with no frame ax = plt.subplot(111, frameon=False) Xdim = 800 Ydim = 400 T = [] for i in range(0, numTrees): X0 = -Xdim / 2 + Xdim / (2 * numTrees) + i * Xdim / numTrees T.append(tree.Tree(120, 50, 12, 1.2, X0, Xdim, Ydim, 2)) def init(): ax.set_xlim(-Xdim / 2 - 10, Xdim / 2 + 10) ax.set_ylim(-Ydim / 2 - 10, Ydim / 2 + 10) ax.set_xticks([]) ax.set_yticks([]) # Title ax.text(0.44, 1.0, "Treez", transform=ax.transAxes, ha="center", va="bottom", color=np.random.randint(101, size=3) / 100,
[6.642287351,3.319983761,1]] dataset = np.asarray(dataset) train_data = np.delete(dataset, 2, axis=1) train_labels = np.delete(dataset, (0,1), axis=1) print(rF.entropy((train_labels.reshape(1,10)[0].tolist()))) r_d,r_l,l_d,l_l = rF.split_data(train_data, train_labels, 0, 2) print(r_d,r_l,l_d,l_l) #Dataset = namedtuple("Dataset", ["image_names", "orientations", "pixel_values", "size"]) test_split_data() data = read_data("train-data.txt") train_data = data[2][:100] train_labels = data[1][:100] a = rF.Tree(-1) #dict_ = rF.load_json('random_forest.model') #a.build(train_data, train_labels) #a.build(train_data, train_labels) #dict_ = a.create_dict() filepath = 'random_forest.model' #rF.save_json(dict_,filepath) dict_ = rF.load_json(filepath) a.assign_json(dict_) a.traverse_tree() a.traverse_tree() print(a.check_input(train_data[:1][0])) #a.save_json('random_forest.model')
def test_creation(self): my_tree = tree.Tree("root node") self.assertEqual(my_tree.data, "root node") self.assertIsNone(my_tree.parent) self.assertEqual(my_tree.children, [])
child.node in [ b'objc', b'obji', b'subjc', b'rel', b'neb', b'vroot', b'comma', b'aux' ] or child.node.startswith(b'kon') or child.node.startswith(b'obji')): node.insert(i, avz) del node[avz_pos] avz = None comma_enclosure(node[i - 1]) # we insert avz as last dependent if we haven't already if v_pos is not None and avz is not None: node.append(avz) del node[avz_pos] comma_enclosure(node[-2]) if __name__ == '__main__': for line in sys.stdin: my_tree = tree.Tree(line) convert_ptkvz(my_tree) if '--tree' in sys.argv: sys.stdout.write( my_tree._pprint_flat(nodesep=b'', parens=b'[]', quotes=False) + b'\n') else: sys.stdout.write(b' '.join([ leaf for leaf in my_tree.leaves() if leaf not in [b'<s>', b'</s>'] ]) + b'\n')
def main(): t = tree.Tree() num = [1, 2, 3, 4, 5, 6] t.buildTree(num) s = Solution() print(s.isBalanced(t.getRoot())[0])
def GetOrthologues_from_tree(iog, treeFN, species_tree_rooted, GeneToSpecies, neighbours, qWrite=False, dupsWriter=None, seqIDs=None, spIDs=None, all_stride_dup_genes=None, qNoRecon=False): """ if dupsWriter != None then seqIDs and spIDs must also be provided""" qPrune = True orthologues = [] if (not os.path.exists(treeFN)) or os.stat(treeFN).st_size == 0: return set(orthologues), treeFN, set() try: tree = tree_lib.Tree(treeFN) except: tree = tree_lib.Tree(treeFN, format=3) # if qPrune: tree.prune(tree.get_leaf_names()) if len(tree) == 1: return set(orthologues), tree, set() root = GetRoot(tree, species_tree_rooted, GeneToSpecies) if root == None: return set(orthologues), tree, set() # Pick the first root for now if root != tree: tree.set_outgroup(root) if not qNoRecon: tree = Resolve(tree, GeneToSpecies) if qPrune: tree.prune(tree.get_leaf_names()) # tree.write(outfile="/home/david/projects/OrthoFinder/Development/Orthologues/ReplacingDLCpar/Overlaps/Orthologues_M3/" + os.path.split(treeFN)[1] + ".rec.txt") if len(tree) == 1: return set(orthologues), tree, set() """ At this point need to label the tree nodes """ iNode = 1 tree.name = "n0" suspect_genes = set() empty_set = set() # preorder traverse so that suspect genes can be identified first, before their closer ortholgoues are proposed for n in tree.traverse('preorder'): if n.is_leaf(): continue if not n.is_root(): n.name = "n%d" % iNode iNode += 1 ch = n.get_children() if len(ch) == 2: oSize, overlap, sp0, sp1 = OverlapSize(n, GeneToSpecies) if oSize != 0: qResolved, misplaced_genes = ResolveOverlap( overlap, sp0, sp1, ch, tree, neighbours, GeneToSpecies) else: misplaced_genes = empty_set if oSize != 0 and not qResolved: if dupsWriter != None: sp_present = sp0.union(sp1) if len(sp_present) == 1: stNode = species_tree_rooted & next( sp for sp in sp_present) isSTRIDE = "Terminal" else: stNode = species_tree_rooted.get_common_ancestor( sp_present) isSTRIDE = "Non-Terminal" if all_stride_dup_genes == None else "Non-Terminal: STRIDE" if frozenset( n.get_leaf_names( )) in all_stride_dup_genes else "Non-Terminal" dupsWriter.writerow([ "OG%07d" % iog, spIDs[stNode.name] if len(stNode) == 1 else stNode.name, n.name, float(oSize) / (len(stNode)), isSTRIDE, ", ".join([seqIDs[g] for g in ch[0].get_leaf_names()]), ", ".join([seqIDs[g] for g in ch[1].get_leaf_names()]) ]) else: # sort out bad genes - no orthology for all the misplaced genes at this level (misplaced_genes). # For previous levels, (suspect_genes) have their orthologues written to suspect orthologues file d0 = defaultdict(list) d0_sus = defaultdict(list) for g in [ g for g in ch[0].get_leaf_names() if g not in misplaced_genes ]: sp, seq = g.split("_") if g in suspect_genes: d0_sus[sp].append(seq) else: d0[sp].append(seq) # if len(d0_sus) > 0: print(d0_sus) d1 = defaultdict(list) d1_sus = defaultdict(list) for g in [ g for g in ch[1].get_leaf_names() if g not in misplaced_genes ]: sp, seq = g.split("_") if g in suspect_genes: d1_sus[sp].append(seq) else: d1[sp].append(seq) orthologues.append((d0, d1, d0_sus, d1_sus)) suspect_genes.update(misplaced_genes) elif len(ch) > 2: species = [{GeneToSpecies(l) for l in n.get_leaf_names()} for n in ch] for (n0, s0), (n1, s1) in itertools.combinations(zip(ch, species), 2): if len(s0.intersection(s1)) == 0: d0 = defaultdict(list) d0_sus = defaultdict(list) for g in n0.get_leaf_names(): sp, seq = g.split("_") if g in suspect_genes: d0_sus[sp].append(seq) else: d0[sp].append(seq) d1 = defaultdict(list) d1_sus = defaultdict(list) for g in n1.get_leaf_names(): sp, seq = g.split("_") if g in suspect_genes: d1_sus[sp].append(seq) else: d1[sp].append(seq) orthologues.append((d0, d1, d0_sus, d1_sus)) # raise Exception("WriteQfO2") if qWrite: directory = os.path.split(treeFN)[0] WriteQfO2(orthologues, directory + "/../Orthologues_M3/" + os.path.split(treeFN)[1], qAppend=False) return orthologues, tree, suspect_genes
def __init__(self): self.T = tree.Tree() pass
def DoOrthologuesForOrthoFinder(ogSet, species_tree_rooted_fn, GeneToSpecies, all_stride_dup_genes, qNoRecon): """ """ # Create directory structure speciesDict = ogSet.SpeciesDict() SequenceDict = ogSet.SequenceDict() # Write directory and file structure qInitialisedSuspectGenesDirs = False speciesIDs = ogSet.speciesToUse nspecies = len(speciesIDs) dResultsOrthologues = files.FileHandler.GetOrthologuesDirectory() for index1 in xrange(nspecies): d = dResultsOrthologues + "Orthologues_" + speciesDict[str( speciesIDs[index1])] + "/" if not os.path.exists(d): os.mkdir(d) for index2 in xrange(nspecies): if index2 == index1: continue with open( d + '%s__v__%s.tsv' % (speciesDict[str(speciesIDs[index1])], speciesDict[str( speciesIDs[index2])]), 'wb') as outfile: writer1 = csv.writer(outfile, delimiter="\t") writer1.writerow( ("Orthogroup", speciesDict[str(speciesIDs[index1])], speciesDict[str(speciesIDs[index2])])) # Infer orthologues and write them to file species_tree_rooted = tree_lib.Tree(species_tree_rooted_fn) neighbours = GetSpeciesNeighbours(species_tree_rooted) # Label nodes of species tree species_tree_rooted.name = "N0" iNode = 1 for n in species_tree_rooted.traverse(): if (not n.is_leaf()) and (not n.is_root()): n.name = "N%d" % iNode iNode += 1 nOgs = len(ogSet.OGs()) nOrthologues_SpPair = util.nOrtho_sp(nspecies) species = speciesDict.keys() reconTreesRenamedDir = files.FileHandler.GetOGsReconTreeDir(True) with open(files.FileHandler.GetDuplicationsFN(), 'wb') as outfile: dupWriter = csv.writer(outfile, delimiter="\t") dupWriter.writerow([ "Orthogroup", "Species Tree Node", "Gene Tree Node", "Support", "Type", "Genes 1", "Genes 2" ]) for iog in xrange(nOgs): orthologues, recon_tree, suspect_genes = GetOrthologues_from_tree( iog, files.FileHandler.GetOGsTreeFN(iog), species_tree_rooted, GeneToSpecies, neighbours, dupsWriter=dupWriter, seqIDs=ogSet.Spec_SeqDict(), spIDs=ogSet.SpeciesDict(), all_stride_dup_genes=all_stride_dup_genes, qNoRecon=qNoRecon) qContainsSuspectGenes = len(suspect_genes) > 0 if (not qInitialisedSuspectGenesDirs) and qContainsSuspectGenes: qInitialisedSuspectGenesDirs = True dSuspectGenes = files.FileHandler.GetSuspectGenesDir() dSuspectOrthologues = files.FileHandler.GetPutativeXenelogsDir( ) for index1 in xrange(nspecies): with open( dSuspectOrthologues + '%s.tsv' % speciesDict[str(speciesIDs[index1])], 'wb') as outfile: writer1 = csv.writer(outfile, delimiter="\t") writer1.writerow( ("Orthogroup", speciesDict[str(speciesIDs[index1])], "Other")) for index0 in xrange(nspecies): strsp0 = species[index0] strsp0_ = strsp0 + "_" these_genes = [ g for g in suspect_genes if g.startswith(strsp0_) ] if len(these_genes) > 0: with open(dSuspectGenes + speciesDict[strsp0] + ".txt", 'ab') as outfile: outfile.write("\n".join([SequenceDict[g]]) + "\n") allOrthologues = [(iog, orthologues)] util.RenameTreeTaxa(recon_tree, reconTreesRenamedDir + "OG%07d_tree.txt" % iog, ogSet.Spec_SeqDict(), qSupport=False, qFixNegatives=True, label='n') if iog >= 0 and divmod( iog, 10 if nOgs <= 200 else 100 if nOgs <= 2000 else 1000)[1] == 0: util.PrintTime("Done %d of %d" % (iog, nOgs)) nOrthologues_SpPair += AppendOrthologuesToFiles( allOrthologues, speciesDict, ogSet.speciesToUse, SequenceDict, dResultsOrthologues, qContainsSuspectGenes) return nOrthologues_SpPair
def paintings(): # painting number 1 '''hand drawn with jitter style''' art = s.Square(300, ('Black')) art.setStyle('jitter3') art.setJitter(4) art.draw(-600, -100, 1, 90) '''now i will add art to the painting''' #pentagon with jitter3 style p = s.Pentagon(75, (0, 0, 0)) p.setColor('DarkOrchid') p.setStyle('jitter3') p.setJitter(4) p.draw(-100, -50, 1, 90) #normal star st = s.Star(50, (0, 0, 0)) st.setColor('Red') st.draw(50, 120, 1, 90) #normal diamond d = s.Diamond(50, (0, 0, 0)) d.setColor('Blue') d.draw(-100, 125, 1, 90) # painting number 2 '''hand drawn with dotted style''' art1 = s.Square(300, ('Black')) art1.setStyle('dotted') art1.setDotSize(3) art1.draw(-150, -100, 1, 90) '''now i will add art to the painting''' #diamond with jitter style d = s.Diamond(50, (0, 0, 0)) d.setColor('CadetBlue') d.setStyle('jitter') d.setJitter(3) d.draw(-400, 125, 1, 90) #cross with dotted style c = s.Cross(30, (0, 0, 0)) c.setColor('LightCoral') c.setStyle('dotted') c.setDotSize(3) c.draw(-500, 45, 1, 90) # painting number 3 '''hand drawn with jitter3 style''' art2 = s.Square(300, ('Black')) art2.setStyle('jitter3') art2.setJitter(5) art2.draw(300, -100, 1, 90) '''now i will add art to the painting''' #normal cross c = s.Cross(15, (0, 0, 0)) c.setColor('LightCoral') c.draw(350, 110, 1, 90) #pentagon with dotted style p = s.Pentagon(75, (0, 0, 0)) p.setColor('OliveDrab') p.setStyle('dotted') p.setDotSize(3) p.draw(370, -65, 1, 90) #star with jitter3 style st = s.Star(50, (0, 0, 0)) st.setColor('Goldenrod') st.setStyle('jitter3') st.setJitter(4) st.draw(500, 120, 1, 90) #trees for museum decoration t1 = tree.Tree(filename='project10lsystem.txt') t1.setIterations(3) t1.setColor('OliveDrab') t1.draw(-230, -200, 1, 90) t2 = tree.Tree(filename='project10lsystem.txt') t2.setIterations(3) t2.setColor('LawnGreen') t2.draw(215, -200, 1, 90)
def SupportedHierachies(t, G, S, GeneToSpecies, species, dict_clades, clade_names, treeName, qWriteDupTrees=False): """ Only get the species sets in the first instance as work out the clades as and when """ qAncient = False supported = defaultdict(int) genesPostDup = set() # Pre-calcualte species sets on tree: traverse tree from leaves inwards StoreSpeciesSets(t, GeneToSpecies, G) if qWriteDupTrees: t_write = None StoreGeneSets(t) for n in t.traverse(): if n.is_root(): continue iExample = 0 for counter, n in enumerate(t.traverse()): if n.is_leaf(): continue # just get the list of putative descendant species at this point without worrying about grandchild clades spSets = GetStoredSpeciesSets(n) if spSets == None: continue # non-binary clades = None # check each of three directions to the root for i, j in itertools.combinations(range(3), 2): s1 = spSets[i] s2 = spSets[j] # check for terminal duplications if len(s1) == 1 and s1 == s2: supported[frozenset(s1)] += 1 if min(len(s1), len(s2)) < 2: continue k1 = frozenset(species) k2 = frozenset(species) for kk in dict_clades: if s1.issubset(kk) and len(kk) < len(k1): k1 = kk if s2.issubset(kk) and len(kk) < len(k2): k2 = kk edges1 = set([kk for kk in dict_clades if s1.issubset(kk) and len(kk) == len(k1)]) edges2 = set([kk for kk in dict_clades if s2.issubset(kk) and len(kk) == len(k2)]) for k1 in edges1.intersection(edges2): if len(k1) == 1: # terminal duplciations dealt with above (since no extra info about species tree topology is needed) break elif k1 == species: # putative ancient duplication if not qAncient: #print(treeName) qAncient = True break elif all([not clade.isdisjoint(s1) for clade0 in dict_clades[k1] for clade in clade0]) and all([not clade.isdisjoint(s2) for clade0 in dict_clades[k1] for clade in clade0]): # Passed the check that the required species are present but at this point don't know where in the tree # Get grandchild clades as required (could still avoid the more costly up clade if it's not required) if clades == None: N = Node(n) clades = N.get_grandrelative_clades_stored() if Join(clades[0]) != spSets[0] or Join(clades[1]) != spSets[1] or Join(clades[2]) != spSets[2]: print(clades[0]) print(spSets[0]) print("") print(clades[1]) print(spSets[1]) print("") print(clades[2]) print(spSets[2]) print("") raise Exception("Mismatch") if clades == None: break # locally non-binary in vicinity of node, skip to next node if not LocalCheck_clades(clades[i], clades[j], dict_clades[k1], GeneToSpecies): continue supported[frozenset(k1)] +=1 genes = N.get_gene_sets(i, j) genesPostDup.add(genes[0].union(genes[1])) if qWriteDupTrees: if t_write == None: try: t_write = t.copy() except: t_write = tree.Tree(treeName, format=1) ii = 0 if (0!= i and 0!=j) else 1 if (1!=i and 1!=j) else 2 gSets = GetStoredGeneSets(n) SaveTree(t_write, gSets[ii], clade_names[k1], treeName, iExample) iExample += 1 return supported, genesPostDup
def GetOrthologuesStandalone_Parallel(trees_dir, species_tree_rooted_fn, GeneToSpecies, output_dir, qSingleTree): species_tree_rooted = tree_lib.Tree(species_tree_rooted_fn) neighbours = GetSpeciesNeighbours(species_tree_rooted) args_queue = mp.Queue() for treeFn in glob.glob(trees_dir + ("*" if qSingleTree else "/*")): args_queue.put((0, treeFn, species_tree_rooted, GeneToSpecies, neighbours, True)) util.RunMethodParallel(GetOrthologues_from_tree, args_queue, 8)
startState = inputFile.readline().rsplit()[0] startState = [char for char in startState] goalState = inputFile.readline().rsplit()[0] goalState = [char for char in goalState] forbidden = [] try: forbiddenString = inputFile.readline().split(",") except: pass if forbiddenString != ['']: for i in range(len(forbiddenString)): forbidden.append([char for char in forbiddenString[i]]) root = tree.Tree(data=startState, isGoal=(startState == goalState)) fringe = [] expanded = [] pathFound = [] # Call algorithms if algo == 'B': pathFound = algorithms.bfs(root, goalState, forbidden, fringe, expanded) elif algo == 'D': pathFound = algorithms.dfs(root, goalState, forbidden, fringe, expanded) elif algo == 'I': pathFound = algorithms.ids(root, goalState, forbidden, fringe, expanded) elif algo == 'G': pathFound = algorithms.greedy(root, goalState, forbidden, fringe, expanded) elif algo == 'A':
class Solution(object): def findTilt(self, root): """ :type root: TreeNode :rtype: int """ self.sum = 0 def find(root): if root is None: return 0 left_sum = find(root.left) right_sum = find(root.right) self.sum += abs(left_sum - right_sum) #返回左子树加上右子树和根结点的值 return root.elem + left_sum + right_sum find(root) return self.sum elems = range(1, 4) #生成十个数据作为树节点 treeNode = tree.Tree() #新建一个树对象 for elem in elems: treeNode.add(elem) #逐个加入树的节点 ss = Solution() print ss.findTilt(treeNode.root)
def init_tree(service): tree = t.Tree(service) tree.expandTree(tree.getRoot()) return tree
def cb_element(self, element, facts): newfacts = {} if "cardinality" in facts: newfacts["cardinality"] = facts["cardinality"] if "name" in element.keys(): newfacts["name"] = element.get("name") else: debug.deprint("Warning: Encountered element with no name") newfacts['schemaname'] = self.tree.getpath(element) for child in self.element_children(element): tag = self.tag(child) if tag not in [ 'element', 'optional', 'zeroOrMore', 'oneOrMore', 'ignore' ]: f = self.callbacks[tag] x = f(child, newfacts) try: d = newfacts["datatype"] if isinstance(d, tuple): new_d = [] for x in d: if x is not None: new_d.append(x) d = tuple(new_d) newfacts["datatype"] = d if len(d) == 0: newfacts["datatype"] = None elif len(d) == 1 and isinstance(d[0], plist.List): newfacts["datatype"] = d[0] else: l_values = [] l_data = [] for x in d: if isinstance(x, str): l_values.append(x) else: l_data.append(x) if len(l_data) > 1: if "name" in element.keys(): debug.deprint( "Warning: Element %s has multiple datatypes - using first one" % newfacts["name"]) else: debug.deprint( "Warning: Unnamed element has multiple datatypes - using first one" ) if len(l_data) > 0: if len(l_values) == 0: newfacts["datatype"] = l_data[0] else: newfacts["datatype"] = tuple([tuple(l_values)] + l_data[0]) except KeyError: pass return tree.Tree(**newfacts)
addRule(arg, ops[op][1]) addRule(t, '*TC') return ruleApp def isTerminal(t): if len(t.ch) == 1: if len(t.ch[0].ch) == 0: return True return False def addRule(t, rule): if isTerminal(t): newTree = tree.Tree() tmp = t.ch t.ch = [] newTree.c = t.c newTree.ch = tmp t.ch.append(newTree) t.c += '-l' + rule else: t.c += '-l' + rule for line in sys.stdin: if (line.strip() !='') and (line.strip()[0] != '%'): inputTree = tree.Tree() inputTree.read(line) reannotate(inputTree) print(inputTree)
def addName ( tr, beg, end ): ls = smallestContainingCat ( tr, beg-1, end )[1] return getHead ( ls[0] ) if len(ls) > 0 else tree.Tree()
def create_tree(self, expr): tr = tree.Tree() l = len(expr)-1 if l == 0: tr.value = expr[0] return tr elif l < 0: return tr else: count = 0 if expr[l] == ')': i = 1 while i != 0: count = count + 1 if count > len(expr): return -1 if expr[l-count] == ')': i = i + 1 elif expr[l-count] == '(': i = i - 1 tr.setRight(self.create_tree(expr[l-count+1:l])) elif expr[l] == '*': count = 0 if expr[l-1] == ')': i = 1 while i != 0: count = count + 1 if count > l: return -1 if expr[l-count-1] == ')': i = i + 1 elif expr[l-count-1] == '(': i = i - 1 if l-count-2<0: print('terminando o *', expr[l-count:-2]) tr.value = '*' tr.setLeft(self.create_tree(expr[l-count:-2])) return tr else: print('passando pelo *', expr[l-count-1:]) tr.setRight(self.create_tree(expr[l-count-1:])) count = count + 1 else: if l-2 < 0: tr.value = '*' tr.setLeft(self.create_tree(expr[:-1])) return tr else: tr.setRight(self.create_tree(expr[l-1:])) else: tr.setRight(self.create_tree(expr[l])) l = l - 1 - count print('fim', expr[:l+1]) if expr[l] == '|': tr.value = expr[l] tr.setLeft(self.create_tree(expr[:l])) else: #OK tr.value = '+' tr.setLeft(self.create_tree(expr[:l+1])) self.arvore = tr return tr
if __name__ == "__main__": # RootAllTrees() parser = argparse.ArgumentParser() parser.add_argument("trees_dir") parser.add_argument("rooted_species_tree") # parser.add_argument("-p", "--prune", action='store_true') parser.add_argument( "-s", "--separator", choices=("dot", "dash", "second_dash", "3rd_dash", "hyphen"), help="Separator been species name and gene name in gene tree taxa") args = parser.parse_args() output_dir = os.path.split(args.trees_dir)[0] qSingleTree = False try: tree_lib.Tree(args.trees_dir) qSingleTree = True print("Analysing single tree") except: try: tree = tree_lib.Tree(args.trees_dir) qSingleTree = True except: pass if not os.path.exists(output_dir): os.mkdir(output_dir) GeneToSpecies = GetGeneToSpeciesMap(args) output_dir = output_dir + "/../Orthologues_M3/" print(output_dir) if not os.path.exists(output_dir):
import tree import printstmt # This will traverse through each row of the 2D rowToken = 0 # This will traverse through each value in the row columnToken = 0 errorCounter = 0 cst = tree.Tree() test = [] test2 = [] def match(tokenList, expectedToken): global rowToken, columnToken notVal = False if rowToken < len(tokenList): if expectedToken == tokenList[rowToken][columnToken].kind: notVal = True return notVal def printErrorStmt(tokenList, expectedToken): global rowToken, columnToken raise Exception("Failed - Expected " + str(expectedToken) + " but found " + str(tokenList[rowToken][columnToken].kind) + " with value '" + str(tokenList[rowToken][columnToken].value) + "' on line " + str(tokenList[rowToken][columnToken].lineNum))
sequences.append(str(record.seq)[:50]) model = JukesCantor() all_sites = [] sites = len(sequences[0]) for site in range(0, sites): all_sites.append([e[site] for e in sequences]) all_trees = [] analyzed = 0 for site in all_sites: analyzed += 1 print "analysing site %s of %s..." % (analyzed, sites) init_t = tree.Tree(site, from_leaves=True) init_internals = assign_internal_nodes(init_t) t = init_t p = get_tree_likelihood(t, model, init_internals) for i in range(0, 1000): p_0, t_0 = random_tree_likelihood(site, model) q = p_0 / p if q > 1: t = t_0 p = p_0 all_trees.append(t)