def showTreeInGrid(gid,biome,grid_level=14,taxonomic_level='sp'): """ Performs a selection, spatial filter and returns an image. grid_level is the grid layer. taxonomic_level is the taxonomic level to be shown. Options are: sp, gns, fam, ord, cls, phy, king """ mesh = initMesh(grid_level) try: cell = mesh.objects.get(id=id) except: logger.error("Selected id does not exist in selected grid") return None gb=GriddedTaxonomy(biome,cell,generate_tree_now=True) forest = gb.taxonomies[0].forest ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 # 0 degrees = 3 o'clock ts.arc_span = 360 forest[taxonomic_level].show(tree_style=ts) return 'Parece que se tiene que ver algo'
def ete_tree(aln): """Tree showing alleles""" from ete2 import Tree, PhyloTree, TreeStyle, NodeStyle t = Tree('temp.dnd') ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 ts.arc_span = 180 cutoff = 0.25 def func(node): if node.name == 'NoName': #or not node.name in metric: return False #if metric[node.name]<=cutoff: # return True matches = filter(func, t.traverse()) print(len(matches), "nodes have distance <=%s" % cutoff) nst1 = NodeStyle() nst1["bgcolor"] = "Yellow" for n in matches: n.set_style(nst1) nst2 = NodeStyle() nst2["bgcolor"] = "LightGreen" #hlanodes = [t.get_leaves_by_name(name=r)[0] for r in refalleles] #for n in hlanodes: # n.set_style(nst2) t.show(tree_style=ts) return
def showTreeInGrid(gid, biome, grid_level=14, taxonomic_level='sp'): """ Performs a selection, spatial filter and returns an image. grid_level is the grid layer. taxonomic_level is the taxonomic level to be shown. Options are: sp, gns, fam, ord, cls, phy, king """ mesh = initMesh(grid_level) try: cell = mesh.objects.get(id=id) except: logger.error("Selected id does not exist in selected grid") return None gb = GriddedTaxonomy(biome, cell, generate_tree_now=True) forest = gb.taxonomies[0].forest ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 # 0 degrees = 3 o'clock ts.arc_span = 360 forest[taxonomic_level].show(tree_style=ts) return 'Parece que se tiene que ver algo'
def ETETree(seqs, ref, metric): """Tree showing bola alleles covered by tepitope""" from ete2 import Tree,PhyloTree,TreeStyle,NodeStyle aln = Genome.clustalAlignment(seqs=seqs) t = Tree('temp.dnd') #t.set_outgroup(t&ref) ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 ts.arc_span = 180 cutoff=0.25 def func(node): if node.name=='NoName' or not node.name in metric: return False if metric[node.name]<=cutoff: return True matches = filter(func, t.traverse()) print len(matches), "nodes have distance <=%s" %cutoff nst1 = NodeStyle() nst1["bgcolor"] = "Yellow" for n in matches: n.set_style(nst1) nst2 = NodeStyle() nst2["bgcolor"] = "LightGreen" hlanodes = [t.get_leaves_by_name(name=r)[0] for r in refalleles] for n in hlanodes: n.set_style(nst2) t.show(tree_style=ts) return
def ETETree(seqs, ref, metric): """Tree showing bola alleles covered by tepitope""" from ete2 import Tree, PhyloTree, TreeStyle, NodeStyle aln = Genome.clustalAlignment(seqs=seqs) t = Tree('temp.dnd') #t.set_outgroup(t&ref) ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 ts.arc_span = 180 cutoff = 0.25 def func(node): if node.name == 'NoName' or not node.name in metric: return False if metric[node.name] <= cutoff: return True matches = filter(func, t.traverse()) print len(matches), "nodes have distance <=%s" % cutoff nst1 = NodeStyle() nst1["bgcolor"] = "Yellow" for n in matches: n.set_style(nst1) nst2 = NodeStyle() nst2["bgcolor"] = "LightGreen" hlanodes = [t.get_leaves_by_name(name=r)[0] for r in refalleles] for n in hlanodes: n.set_style(nst2) t.show(tree_style=ts) return
def setUp(self): tree = Tree() root = tree.get_tree_root() root.dist = 0 root.name = "root" node = root.add_child(name="Left") node.add_child(name="Alpha") node.add_child(name="Beta") node = root.add_child(name="Right") node.add_child(name="Gamma") node.add_child(name="Delta") for desc in tree.iter_descendants(): desc.dist = 0 ts = TreeStyle() ts.show_leaf_name = True ts.show_branch_length = False ts.mode = "c" ts.arc_start = 0 ts.arc_span = 360 self.circular_style = ts self.exampleTree = tree self.alignment = MultipleSeqAlignment([ SeqRecord(Seq("AAG", generic_dna), id="Alpha"), SeqRecord(Seq("AGA", generic_dna), id="Beta"), SeqRecord(Seq("AAA", generic_dna), id="Gamma"), SeqRecord(Seq("GGA", generic_dna), id="Delta"), ])
def build_vis(): ts = TreeStyle() ts.mode = "c" ts.arc_start = 0 # 0 degrees = 3 o'clock ts.arc_span = 360 ts.layout_fn = my_layout # Use custom layout return ts
def showTreeInGrid(request): """ .. showTreeInGrid: Performs a selection, spatial filter and returns an image. Parameters in GET variable =========================== grid_level : int The grid layer. taxonomic_level : string The taxonomic level to be shown. Options are: sp, gns, fam, ord, cls, phy, king Returns ======= HTTP RESPONSE with an image showing the tree. See figure: .. image:: """ from ete2.treeview import drawer from PyQt4 import QtCore import ipdb response = HttpResponse() get = request.GET try: gid = int(get['gid']) grid_level = int(get['g_l']) taxonomic_level = get['tax_lvl'] except: response.content='Bad request. Check GET variable definitions' response.status_code = 500 return response biome = Occurrence.objects.all() mesh = initMesh(grid_level) try: cell = mesh.objects.get(id=gid) except: logger.error("Selected id does not exist in selected grid") return None import os.path head_path = settings.PATH_IMAGES filename = "%s-%s-%s.png" %(grid_level,gid,taxonomic_level) file_ = head_path+filename logger.info('Writing in: %s'%file_) if not os.path.isfile(file_): logger.info("The image doens't exist") gb=GriddedTaxonomy(biome,cell,generate_tree_now=True) forest = gb.taxonomies[0].forest ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 # 0 degrees = 3 o'clock ts.arc_span = 360 try: #ipdb.set_trace() forest[taxonomic_level].render(file_, w=100, units="mm",tree_style=ts) #drawer.exit_gui(1, 1) #logger.info(QtCore.QThreadPool) del(forest[taxonomic_level]) except: logger.error('Something went wrong with the image rendering') #del(forest) #ipdb.set_trace() template = get_template('base.html') html = template.render(Context({'gid':gid,'taxonomic_level':taxonomic_level,'grid_level':grid_level,'image_path':filename})) response.content=(html) #response.content=str(forest[taxonomic_level]) response.status_code = 200 return response
def showAllLevelsInTreeInGrid(request): """ Performs a selection, spatial filter and returns an image. grid_level is the grid layer. taxonomic_level is the taxonomic level to be shown. Options are: sp, gns, fam, ord, cls, phy, king """ import ipdb response = HttpResponse() get = request.GET try: gid = int(get['gid']) grid_level = int(get['g_l']) names = int(get['names']) if names > 0: only_id = False else: only_id = True #taxonomic_level = get['tax_lvl'] except: response.content='Bad request. Check GET variable definitions' response.status_code = 500 return response biome = Occurrence.objects.all() mesh = initMesh(grid_level) try: cell = mesh.objects.get(id=gid) except: logger.error("Selected id does not exist in selected grid") return None import os.path tax_levels = ['sp','gns','fam','cls','ord','phy','kng'] tax_keys = {'sp':'1.Species','gns':'2. Genera','fam':'3. Families','ord':'4. Orders','cls':'5. Classes','phy':'6. Phyla','kng':'7. Kingdoms'} rich_keys = { 'oc':'occurrences','sp' :'species','gns':'genera','fam':'families','cls':'classes','ord':'orders','phy':'phyla','kng':'kingdoms'} img_paths = {} #THIS IS VERY VERY WRONG AND I WOULD SUGGEST A REFACTORING like the use of a binary written copy in disk about the object in question (cached) gb=GriddedTaxonomy(biome,cell,generate_tree_now=True,use_id_as_name=only_id) taxonomy = gb.taxonomies[0] #ipdb.set_trace() mat_complex = taxonomy.calculateIntrinsicComplexity() for taxonomic_level in tax_levels: head_path = settings.PATH_IMAGES filename = "%s-%s-%s.png" %(grid_level,gid,taxonomic_level) file_ = head_path+filename logger.info('Writing in: %s'%file_) if not os.path.isfile(file_): logger.info("The image doens't exist") try: if gb not in locals(): #gb=GriddedTaxonomy(biome,cell,generate_tree_now=True) logger.info("Gridded taxonomy doesn't found") except: gb=GriddedTaxonomy(biome,cell,generate_tree_now=True,use_id_as_name=only_id) forest = taxonomy.forest ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 # 0 degrees = 3 o'clock ts.arc_span = 360 ts.show_scale = False try: #ipdb.set_trace() forest[taxonomic_level].render(file_,h=500, w=500, units="px",tree_style=ts) #drawer.exit_gui(1, 1) #logger.info(QtCore.QThreadPool) #del(forest[taxonomic_level]) except: logger.error('Something went wrong with the image rendering') img_paths[taxonomic_level] = {'name': tax_keys[taxonomic_level],'path':filename,'richness':taxonomy.richness[rich_keys[taxonomic_level]]} else: img_paths[taxonomic_level] = {'name': tax_keys[taxonomic_level],'path':filename,'richness':taxonomy.richness[rich_keys[taxonomic_level]]} #del(forest) # #dic_richness = gb.taxonomies[0].richness det_complex = gb.taxonomies[0].vectorIntrinsic template = get_template('base.html') submatrices = map(lambda i : mat_complex[0:i,0:i],range(1,len(mat_complex))) #ipdb.set_trace() import numpy as np tras = map(lambda mat : np.linalg.eigvals(mat),submatrices) #ipdb.set_trace() try: eigenv = np.linalg.eigvals(mat_complex).tolist() svd = np.linalg.svd(mat_complex) except: eigenv =[] svd = [[],[],[]] #ipdb.set_trace() html = template.render(Context({'gid':gid,'taxonomic_level':taxonomic_level,'grid_level':grid_level,'image_path':sorted(img_paths.itervalues()),'complexity':mat_complex.tolist(),'vect_comp':det_complex,'eigenv':eigenv,'left_eig_vect':svd[0].tolist(),'svd':svd[1].tolist(),'right_eig_vect':svd[2].tolist()})) response.content=(html) #response.content=str(forest[taxonomic_level]) response.status_code = 200 return response
#!/usr/bin/python # drawunrootedcircular.py # Use ete2 to render an unrooted tree from an input Newick formatted tree file. # Render the tree as circular. # sys.argv[1] -- filename for tree file # sys.argv[2] -- filename for output .png file import sys from ete2 import Tree, TreeStyle if( len(sys.argv) != 3 ): print "Usage: python drawunrootedcircular.py <Newick_file> <Tree_png>" exit(-1) t = Tree(sys.argv[1]) c = TreeStyle() c.mode = "c" c.scale = 50 c.arc_start = -90 c.arc_span = 360 t.render(sys.argv[2], w=720, units="px", tree_style=c)
import dateutil.parser #from models import Count,Sum,Avg from django.contrib.gis.db.models import Extent, Union, Collect,Count,Min from gbif.models import Specie,Genus,Family,Order,Class,Phylum,Kingdom from mesh.models import NestedMesh from django.contrib.gis.db.models.query import GeoQuerySet logger = logging.getLogger('biospatial.gbif.general_test') import biospatial.settings as settings # Create your tests here. from ete2 import Tree, TreeStyle t = Tree() ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 # 0 degrees = 3 o'clock ts.arc_span = 360 from gbif.taxonomy import Taxonomy,embedTaxonomyInGrid,embedTaxonomyInNestedGrid,NestedTaxonomy def createShapefile(taxonomy_list,name='default_name',store='out_maps'): """ This function creates a shapefile for a given list of Taxonomies. Do note that the list of taxonomies is a mapping to the cells in a mesh. """ #Method for generating the shapefile object from osgeo import ogr #from shapely.geometry import Polygon
faces.add_face_to_node(f, node, 0, position="aligned") f.border.width = 0 #f = faces.CircleFace(20, "red") #f = faces.AttrFace("name", fsize=20) f = faces.TextFace("NAME", fsize=10) #faces.add_face_to_node(f, node, 0, position="branch-right") f.border.width = 0 #node.img_style["bgcolor"] = random_color() #Tree().show() ts = TreeStyle() ts.mode = "c" ts.layout_fn = layout ts.show_leaf_name = False ts.arc_span = 340 ts.arc_start = -70 #ts.allow_face_overlap = True #ts.show_branch_length = True ts.draw_guiding_lines = False ts.optimal_scale_level = "mid" ts.extra_branch_line_color = "red" ts.root_opening_factor = 0.50 ts.show_border = True ts.scale = None t = Tree() t.populate(200, random_branches=True, branch_range=(0, 0)) t.dist = 0.0 dists = [n.dist for n in t.traverse() if n.dist != 0] #print max(dists), min(dists) t.write(outfile="test.nw") #for s in [5, None]:
## Bonus ETE dendrogram plotting # Configure output path for image #ete_output_path="eteTree.png" width = 600 # For other output args, see http://etetoolkit.org/docs/latest/tutorial/tutorial_drawing.html#rendering-trees-as-images # Configure tree styles ts = TreeStyle() ts.show_leaf_name = True ts.show_branch_length = True ts.show_scale = False ts.scale = None ts.mode = "c" # draw tree in circular style ts.arc_start = 0 ts.arc_span = 360 if orientation == "top": ts.rotation = 90 ts.branch_vertical_margin = 10 # 10 pixels between adjacent branches # Remove the default small red spheres for each node nstyle = NodeStyle() nstyle["size"] = 0 for leaf in tree: k = leaf.name k = int(k) leaf.name = labels[k] # Apply node styles to nodes
import dateutil.parser #from models import Count,Sum,Avg from django.contrib.gis.db.models import Extent, Union, Collect, Count, Min from gbif.models import Specie, Genus, Family, Order, Class, Phylum, Kingdom from mesh.models import NestedMesh from django.contrib.gis.db.models.query import GeoQuerySet logger = logging.getLogger('biospatial.gbif.general_test') import biospatial.settings as settings # Create your tests here. from ete2 import Tree, TreeStyle t = Tree() ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 # 0 degrees = 3 o'clock ts.arc_span = 360 from gbif.taxonomy import Taxonomy, embedTaxonomyInGrid, embedTaxonomyInNestedGrid, NestedTaxonomy def createShapefile(taxonomy_list, name='default_name', store='out_maps'): """ This function creates a shapefile for a given list of Taxonomies. Do note that the list of taxonomies is a mapping to the cells in a mesh. """ #Method for generating the shapefile object from osgeo import ogr #from shapely.geometry import Polygon # Now convert it to a shapefile with OGR driver = ogr.GetDriverByName('Esri Shapefile')