### Install ETE4 using pip Source: https://github.com/etetoolkit/ete/blob/ete4/README.md Installs the latest release of ETE4 from PyPI. This is the quickest way to get started. ```sh pip install ete4 ``` -------------------------------- ### API Usage Examples Source: https://github.com/etetoolkit/ete/blob/ete4/doc/internals/internals_api.md Examples demonstrating how to interact with the ETE Toolkit API using `httpie`. ```APIDOC ## API Usage Examples ### Get all trees ```bash $ http :5000/trees HTTP/1.1 200 OK [ "my-test-tree" ] ``` ### Add a new tree ```bash $ http POST :5000/trees name='my-new-tree' newick='(a,(b,c));' HTTP/1.1 201 Created { "ids": [ "my-new-tree" ], "message": "ok" } ``` ### Get tree size ```bash $ http :5000/trees/my-new-tree/size HTTP/1.1 200 OK { "height": 3.0, "width": 2.0 } ``` ``` -------------------------------- ### Install ETE4 from GitHub repository Source: https://github.com/etetoolkit/ete/blob/ete4/README.md Installs the very latest version of ETE4 directly from the GitHub repository. Use this if you need the most recent commits, even before a release. ```sh pip install --force-reinstall https://github.com/etetoolkit/ete/archive/ete4.zip ``` -------------------------------- ### Graphical Command Example Source: https://github.com/etetoolkit/ete/blob/ete4/doc/internals/internals_drawing.md Represents a basic graphic item, starting with a command name followed by parameters. This format is used to create a Domain-Specific Language (DSL) for drawing. ```default ['hz-line', [0.0, 0.5], [8.0, 0.5], [], ''] ``` -------------------------------- ### Install ETE4 with optional dependencies Source: https://github.com/etetoolkit/ete/blob/ete4/README.md Installs ETE4 with additional modules for specific functionalities like tree viewing, testing, documentation generation, or smartview rendering. ```sh pip install -e .[treeview] ``` ```sh pip install -e .[treeview,test,doc,render_sm] ``` -------------------------------- ### Start extended server Source: https://github.com/etetoolkit/ete/blob/ete4/doc/internals/internals_api.md This Python code starts the ETE server with the extended API endpoints defined. It includes a prompt to keep the server running until Enter is pressed. ```python exp.start_server() input('Press enter to stop the server and finish.') ``` -------------------------------- ### Install ETE4 for local development Source: https://github.com/etetoolkit/ete/blob/ete4/README.md Installs ETE4 in editable mode from a local clone of the repository. This is useful for developers contributing to ETE. ```sh pip install -e . ``` -------------------------------- ### Interactive Tree Exploration: Basic Exploration Source: https://context7.com/etetoolkit/ete/llms.txt Launches a web-based GUI for interactive tree visualization. This basic example populates a tree with random distances and supports, then opens it in a browser. ```python from ete4 import Tree from random import random # Create and explore tree t = Tree() t.populate(100, dist_fn=random, support_fn=random) # Basic exploration t.explore() ``` -------------------------------- ### List all trees Source: https://github.com/etetoolkit/ete/blob/ete4/doc/internals/internals_api.md Use this endpoint to retrieve a list of all existing trees on the server. This is a simple GET request. ```bash $ http :5000/trees # same as "http http://localhost:5000/trees" HTTP/1.1 200 OK [ "my-test-tree" ] ``` -------------------------------- ### Installing ETE 4 from PyPI Source: https://github.com/etetoolkit/ete/blob/ete4/doc/internals/internals_development.md Standard command to install the ETE 4 package using pip. This assumes the package is available on the Python Package Index. ```bash $ pip install ete4 ``` -------------------------------- ### Subsequent Draw API Call Example Source: https://github.com/etetoolkit/ete/blob/ete4/doc/internals/internals_drawing.md An example of a typical draw API call made when navigating or zooming within a tree, showing dynamic parameters. ```http /trees/tree-1/draw?shape=rectangular&node_height_min=30&content_height_min=4&zx=1.4[...] ``` -------------------------------- ### Install ETE4 using conda Source: https://github.com/etetoolkit/ete/blob/ete4/README.md Installs ETE4 from the conda-forge channel. Recommended if you are already using conda for environment management. ```sh conda install conda-forge::ete4 ``` -------------------------------- ### Iterate Over Tree Leaves Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_trees.md Demonstrates how to iterate over tree leaves using a simple syntax and access their properties. Also shows how to get the first leaf and check root relationships. ```python for leaf in t: print(leaf.name) n = next(iter(t)) # take the first leaf (same as next(t.leaves())) print('First leaf name:', n.name) print('First leaf distance:', n.dist) print('t.is_leaf = %s n.is_leaf = %s' % (t.is_leaf, n.is_leaf)) print(n.root == t) # True print(t.children[0].root == t) # True too print(t.children[0].children[0].root == t) # and True again ``` -------------------------------- ### Create an Empty Tree Node Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_trees.md Initializes an empty tree, which consists of a single root node. This is the most basic way to start creating a tree structure. ```python from ete4 import Tree # Empty tree (single node). t = Tree() ``` -------------------------------- ### Visualize Phylogenetic Tree with Alignment Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_phylogeny.md Initializes a PhyloTree instance with a large alignment string. This setup is typically followed by visualization steps, leveraging the built-in phylogenetic layout engine. ```python from ete4 import PhyloTree from ete4.treeview import TreeStyle alg = """ >Dme_001 MAEIPDETIQQFMALT---HNIAVQYLSEFGDLNEAL--YYASQTDDIKDRREEAH >Dme_002 MAEIPDATIQQFMALTNVSHNIAVQY--EFGDLNEALNSYYAYQTDDQKDRREEAH >Cfa_001 MAEIPDATIQ---ALTNVSHNIAVQYLSEFGDLNEALNSYYASQTDDQPDRREEAH >Mms_001 MAEAPDETIQQFMALTNVSHNIAVQYLSEFGDLNEAL--------------REEAH >Hsa_001 MAEIPDETIQQFMALT---HNIAVQYLSEFGDLNEALNSYYASQTDDIKDRREEAH >Ptr_002 MAEIPDATIQ-FMALTNVSHNIAVQY--EFGDLNEALNSY--YQTDDQKDRREEAH >Mmu_002 MAEIPDATIQ---ALTNVSHNIAVQYLSEFGDLNEALNSYYASQTDDQPDRREEAH >Hsa_002 MAEAPDETIQQFM-LTNVSHNIAVQYLSEFGDLNEAL--------------REEAH >Mmu_001 MAEIPDETIQQFMALT---HNIAVQYLSEFGDLNEALNSYYASQTDDIKDRREEAH >Ptr_001 MAEIPDATIQ-FMALTNVSHNIAVQY--EFGDLNEALNSY--YQTDDQKDRREEAH >Mmu_001 MAEIPDATIQ---ALTNVSHNIAVQYLSEFGDLNEALNSYYASQTDDQPDRREEAH """ # PhyloTree instances are, by default, attached to a layout for tree visualization. ``` -------------------------------- ### Load and explore a tree in Python Source: https://github.com/etetoolkit/ete/blob/ete4/README.md Loads a tree from a file into an ETE Tree object and opens an interactive exploration interface in a web browser. Ensure the 'ete4' library is installed. ```python from ete4 import Tree t = Tree(open('my_tree.nw')) t.explore() ``` -------------------------------- ### Keep Explorer Server Running Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_smartview.md Starts the interactive tree exploration and keeps the server running after the initial visualization. This is useful for standalone scripts where you want the server to persist until manually stopped. ```python t.explore(keep_server=True) ``` -------------------------------- ### Start Tree Exploration Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_smartview.md Initiates the interactive web-based exploration of a Tree object. This will open a web browser session to visualize and interact with the tree. The function returns immediately, allowing further interaction in the console. ```python t.explore() ``` -------------------------------- ### Run Unittest Sequence Group Test Source: https://github.com/etetoolkit/ete/blob/ete4/tests/redundant/readme.md Use this command to run a specific unittest test case for sequence groups. This is an example of legacy testing practices. ```sh python -m unittest tests.redundant.test_seqgroup ``` -------------------------------- ### Explore Tree and Wait for Input Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_smartview.md Starts the interactive tree exploration and then pauses the script execution, waiting for user input before proceeding. This allows the user to interact with the visualization before the script terminates the server. ```python t.explore() print('Press enter to stop the server and finish.') input() ``` -------------------------------- ### Create Phylogenetic Tree and Assign Relative Ages Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_phylogeny.md This example demonstrates creating a gene phylogeny using ETE and defining a dictionary to map species codes to relative ages. The `sp_naming_function` is crucial for correctly identifying species codes from node names. ```python from ete4 import PhyloTree # Create a gene phylogeny with several duplication events at different # levels. Note that we are using the default method for detecting the # species code of leaves (three first lettes in the node name are # considered the species code). nw = """ ((Dme_001,Dme_002),(((Cfa_001,Mms_001),((((Hsa_001,Hsa_003),Ptr_001), Mmu_001),((Hsa_004,Ptr_004),Mmu_004))),(Ptr_002,(Hsa_002,Mmu_002)))); " t = PhyloTree(nw, sp_naming_function=lambda name: name[:3]) print(t) # ╭─┬╴Dme_001 # │ ╰╴Dme_002 # │ ╭─┬╴Cfa_001 # ─┤ │ ╰╴Mms_001 # │ ╭─┤ ╭─┬╴Hsa_001 # │ │ │ ╭─┤ ╰╴Hsa_003 # │ │ │ ╭─┤ ╰╴Ptr_001 # ╰─┤ ╰─┤ ╰╴Mmu_001 # │ │ ╭─┬╴Hsa_004 # │ ╰─┤ ╰╴Ptr_004 # │ ╰╴Mmu_004 # ╰─┬╴Ptr_002 # ╰─┬╴Hsa_002 # ╰╴Mmu_002 # Create a dictionary with relative ages for the species present in # the phylogenetic tree. Note that ages are only relative numbers to # define which species are older, and that different species can # belong to the same age. species2age = { 'Hsa': 1, # Homo sapiens (Hominids) 'Ptr': 2, # P. troglodytes (primates) 'Mmu': 2, # Macaca mulata (primates) 'Mms': 3, # Mus musculus (mammals) 'Cfa': 3, # Canis familiaris (mammals) 'Dme': 4 # Drosophila melanogaster (metazoa) } ``` -------------------------------- ### NCBI Taxonomy Integration: Get Lineage Source: https://context7.com/etetoolkit/ete/llms.txt Retrieves the full lineage of a given NCBI Taxonomy ID, starting from the root. The result is a list of taxids representing the lineage. ```python from ete4 import NCBITaxa, PhyloTree ncbi = NCBITaxa() # Get lineage lineage = ncbi.get_lineage(9606) print(lineage) # [1, 131567, 2759, ..., 9606] names = ncbi.get_taxid_translator(lineage) print([names[tid] for tid in lineage]) # ['root', 'cellular organisms', ..., 'Homo sapiens'] ``` -------------------------------- ### Show Interactive Tree Visualization Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_treeview.md Use the `show` method to launch the interactive GUI for exploring and manipulating a tree. Changes made in the GUI persist after closing. ```python from ete4 import Tree t = Tree('((a,b),c);') t.show() ``` -------------------------------- ### Create and Populate Tree Nodes Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_trees.md Demonstrates creating an empty tree and adding child nodes with names. The `populate()` method can be used to add a specified number of random leaves with a given name library. ```python t = Tree() # create an empty tree A = t.add_child(name='A') # add new child to the tree root and return it B = t.add_child(name='B') C = A.add_child(name='C') # add new child to one of the branches D = C.add_sister(name='D') # add a second child to same branch as before # Note that the last one did it by using a sister as the starting point. R = A.add_child(name='R') # add a third child (multifurcations are ok) # Add 6 random leaves to the R branch, with names 'r1' to 'r6'. R.populate(6, names_library=['r1', 'r2', 'r3', 'r4', 'r5', 'r6']) print(t) # ╭╴C # ╭─┼╴D # │ ╰─┬╴r6 # │ ╰─┬╴r5 # ─┤ ╰─┬╴r4 # │ ╰─┬╴r3 # │ ╰─┬╴r2 # │ ╰╴r1 # ╰╴B ``` ```python t = Tree() t.populate(100) ``` -------------------------------- ### Explore a tree using ete4 utility Source: https://github.com/etetoolkit/ete/blob/ete4/README.md Launches an interactive tree exploration interface in a web browser by specifying the tree file. Requires the `ete4` command-line tool. ```sh ete4 explore -t my_tree.nw ``` -------------------------------- ### Installing ETE 4 from Conda-forge Source: https://github.com/etetoolkit/ete/blob/ete4/doc/internals/internals_development.md Command to install the ETE 4 package using the conda package manager, specifying the conda-forge channel. ```bash $ conda install conda-forge::ete4 ``` -------------------------------- ### Build and Modify Tree Topology Source: https://context7.com/etetoolkit/ete/llms.txt Demonstrates building a tree from scratch, adding children and sisters, populating nodes, detaching subtrees, deleting nodes while preserving descendants, pruning trees, and concatenating trees. ```python from ete4 import Tree # Build tree from scratch t = Tree() A = t.add_child(name='A') B = t.add_child(name='B') C = A.add_child(name='C') D = C.add_sister(name='D') R = A.add_child(name='R') R.populate(6, names_library=['r1', 'r2', 'r3', 'r4', 'r5', 'r6']) print(t) ``` ```python # Remove/detach node (removes entire subtree) t = Tree('((((H,K)D,(F,I)G)B,E)A,((L,(N,Q)O)J,(P,S)M)C);', parser=1) J = t['J'] removed = J.detach() # J and all descendants are removed # Alternative: parent.remove_child(J) ``` ```python # Delete node (keeps descendants, reattaches to parent) G = t['G'] G.delete() # F and I now hang directly from B ``` ```python # Pruning - keep only specified nodes t = Tree('((((H,K),(F,I)G),E),((L,(N,Q)O),(P,S)));', parser=1) t.prune(['H', 'F', 'E', 'Q', 'P']) print(t) ``` ```python # Concatenate trees t1 = Tree('(A,(B,C));') t2 = Tree('((D,E),(F,G));') node_A = t1['A'] node_A.add_child(t2) print(t1) ``` -------------------------------- ### Add Properties and Write NHX Notation Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_trees.md Demonstrates adding properties like 'vowel' and 'confidence' to tree leaves and then writing the tree in NHX notation, either including specific properties or all node data. ```python t = Tree('((H:0.3,I:0.1),A:1,(B:0.4,(C:0.5,(J:1.3,(F:1.2,D:0.1)))));') print(t) # ╭─┬╴H # ─┤ ╰╴I # ├╴A # ╰─┬╴B # ╰─┬╴C # ╰─┬╴J # ╰─┬╴F # ╰╴D # Add some more properties to leaves: for leaf in t: is_vowel = leaf.name in 'AEIOU' leaf.add_props(vowel=is_vowel, confidence=1) print('NHX notation including vowel and confidence properties:') print(t.write(props=['vowel'])) print('NHX notation including all data in the nodes:') print(t.write(props=None)) ``` -------------------------------- ### Create and Load Trees in ETE4 Source: https://context7.com/etetoolkit/ete/llms.txt Demonstrates various methods to create and load tree structures using the Ete4 library. Includes creating empty trees, trees with properties, and parsing from Newick strings or files. Supports different parsers for internal node values. ```python from ete4 import Tree # Create an empty tree (single node) t = Tree() # Create a tree with node properties t = Tree({'name': 'root', 'dist': 1.0, 'support': 0.5}) # Load from Newick string (default parser=0 interprets internal values as support) t = Tree('(A:1,(B:1,(E:1,D:1):0.5):0.5);') # Load from file t = Tree(open('genes_tree.nw')) # Use parser=1 to interpret internal node values as names instead of support t = Tree('(A:1,(B:1,(E:1,D:1)E:0.5)F:0.5);', parser=1) # Populate with random topology (useful for testing) t = Tree() t.populate(100) print(t) # ╭─┬╴A # ╭─┤ ╰╴B # ─┤ ╰─┬╴E # │ ╰╴D # ╰╴C ``` -------------------------------- ### Get Descendants Source: https://github.com/etetoolkit/ete/blob/ete4/doc/3to4.md Use `t.descendants()` for iterating over descendants. The older `t.get_descendants()` and `t.iter_descendants()` are deprecated. ```python t.get_descendants() ``` ```python t.iter_descendants() ``` ```python t.descendants() ``` -------------------------------- ### Tree Copying and Data Caching Source: https://context7.com/etetoolkit/ete/llms.txt Demonstrates various methods for copying trees, including Newick, extended Newick, pickle, and deepcopy, each with different preservation levels. Also shows how to cache node content for performance. ```python from ete4 import Tree t = Tree('((A,B)Internal_1:0.7,(C,D)Internal_2:0.5)root:1.3;', parser=1) t['A'].add_props(label='custom', complex=[[0,1], [2,3]]) # Fast newick-based copy (loses complex features) t_copy1 = t.copy('newick') # Extended newick copy (features as strings) t_copy2 = t.copy('newick-extended') # Full copy with pickle (preserves everything) t_copy3 = t.copy('cpickle') # default t_copy4 = t.copy() # same as cpickle # Deep copy (slowest, handles lambda functions) t_copy5 = t.copy('deepcopy') # Cache node content for fast lookups t = Tree() t.populate(50) node2leaves = t.get_cached_content() # cache leaf nodes node2names = t.get_cached_content('name') # cache leaf names for n in t.traverse(): print(f'Node {n.name}: {len(node2leaves[n])} leaves') ``` -------------------------------- ### Getting Midpoint Outgroup Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_trees.md Explains how to find and set the midpoint outgroup for a balanced tree rooting. ```APIDOC ## Getting Midpoint Outgroup ### Description This section describes how to obtain a balanced rooting of a tree by identifying and setting the midpoint outgroup. The midpoint outgroup is the partition that splits the tree into two equally distant clusters based on branch lengths. ### Method `Tree.get_midpoint_outgroup()` `Tree.set_outgroup(node)` ### Endpoint N/A (This is a library function, not a web API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from ete3 import Tree # Generate a random tree t = Tree() t.populate(15) # Calculate the midpoint outgroup R = t.get_midpoint_outgroup() # Set it as the tree outgroup t.set_outgroup(R) print(t) ``` ### Response #### Success Response (200) N/A (This is a library function, output is printed to console) #### Response Example ``` # Example output (structure may vary due to random tree generation): # ╭─┬╴k # │ ╰─┬╴l # ╭─┤ ╰╴m # │ │ ╭─┬╴n # ╭─┤ ╰─┤ ╰╴o # │ │ ╰─┬╴a # │ │ ╰╴b # ─┤ ╰─┬╴c # │ ╰─┬╴d # │ ╰╴e # │ ╭─┬╴f # ╰─┤ ╰─┬╴g # │ ╰╴h # ╰─┬╴i # ╰╴j ``` ``` -------------------------------- ### Tree Rooting with set_outgroup Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_trees.md Demonstrates how to root a tree using the `set_outgroup` method with different criteria, including common ancestors and specific nodes. ```APIDOC ## Tree Rooting with set_outgroup ### Description This section illustrates how to manipulate the rooting of a phylogenetic tree using the `set_outgroup` method in the ETE Toolkit. It shows how to define an outgroup based on common ancestors or specific nodes to alter the tree's interpretation. ### Method `set_outgroup(node)` ### Endpoint N/A (This is a library function, not a web API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from ete3 import Tree # Example 1: Rooting using a common ancestor t = Tree('(((A,B),C),D);') ancestor = t.common_ancestor(['E', 'D']) t.set_outgroup(ancestor) print(t) # Example 2: Rooting using a specific node t.set_outgroup(t['A']) print(t) # Example 3: Independent rooting of subtrees t = Tree('(((A,C),((H,F),(L,M))),((B,(J,K)),(E,D)));') node1 = t.common_ancestor(['A', 'H']) node2 = t.common_ancestor(['B', 'D']) node1.set_outgroup('H') node2.set_outgroup('E') print(t) ``` ### Response #### Success Response (200) N/A (This is a library function, output is printed to console or returned as a Tree object) #### Response Example ``` # Output for Example 1: # ╭─┬╴E # ─┤ ╰╴D # ╰─┬╴B # ╰─┬╴A # ╰─┬╴H # ╰╴F # Output for Example 2: # ╭╴A # ─┤ ╭─┬╴H # │ ╰─┤ ╰╴F # │ ╰─┬╴B # │ ╰─┬╴E # │ ╰╴D # Output for Example 3: # ╭╴H # ╭─┤ ╭╴F # │ ╰─┤ ╭─┬╴L # ─┤ ╰─┤ ╰╴M # │ ╰─┬╴A # │ ╰╴C # ╰─┬╴E # ╰─┬╴D # ╰─┬╴B # ╰─┬╴J # ╰╴K ``` ``` -------------------------------- ### Get Leaves by Name Source: https://github.com/etetoolkit/ete/blob/ete4/doc/3to4.md Use `t.search_leaves_by_name()` for searching leaves by name. The older `t.get_leaves_by_name()` is deprecated. ```python t.get_leaves_by_name() ``` ```python t.search_leaves_by_name() ``` -------------------------------- ### Get Leaf Names Source: https://github.com/etetoolkit/ete/blob/ete4/doc/3to4.md Use `t.leaf_names()` for retrieving leaf names. The older `t.get_leaf_names()` is deprecated. ```python t.get_leaf_names() ``` ```python t.leaf_names() ``` -------------------------------- ### Get Tree Edges Source: https://github.com/etetoolkit/ete/blob/ete4/doc/3to4.md Use `t.edges()` for iterating over tree edges. The older `t.get_edges()` and `t.iter_edges()` are deprecated. ```python t.get_edges() ``` ```python t.iter_edges() ``` ```python t.edges() ``` -------------------------------- ### Run ETE Tests Source: https://github.com/etetoolkit/ete/blob/ete4/CONTRIBUTING.md Execute the test suite for the ETE project. Use `--list` to see available tests or `--help` for all options. ```shell ./run_tests.py ``` -------------------------------- ### Get Rank by TaxID (NCBI) Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_taxonomy.md Retrieves the taxonomic rank for a given list of taxids using the NCBI taxonomy database. ```python from ete4 import NCBITaxa ncbi = NCBITaxa() print(ncbi.get_rank([9606, 9443])) # {9443: 'order', 9606: 'species'} ``` -------------------------------- ### Get Lineage and Taxid Translator (NCBI) Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_taxonomy.md Fetches the lineage for a given taxid and translates taxids to names. Requires the ete4 library. ```python from ete4 import NCBITaxa ncbi = NCBITaxa() lineage = ncbi.get_lineage(9606) print(lineage) names = ncbi.get_taxid_translator(lineage) print([names[taxid] for taxid in lineage]) ``` -------------------------------- ### Traverse Trees in ETE4 Source: https://context7.com/etetoolkit/ete/llms.txt Illustrates different tree traversal strategies in ETE4, including postorder, preorder, and iterating over descendants and leaves. Also shows how to traverse from a leaf to the root and use custom leaf definitions for collapsing trees. ```python from ete4 import Tree t = Tree('((((H,K)D,(F,I)G)B,E)A,((L,(N,Q)O)J,(P,S)M)C);', parser=1) # Traverse in postorder (children before parent) for node in t.traverse('postorder'): print(node.name) # Traverse only descendants (excluding root) for node in t.descendants('preorder'): print(node.name) # Iterate over leaves only (default behavior of __iter__) for leaf in t: print(leaf.name) # Get all leaves as a list leaves = list(t.leaves()) # Traverse from leaf to root node = t['C'] while node: print(node.name, node.dist) node = node.up # Traverse with custom leaf definition (collapsing) node2labels = t.get_cached_content('name') def collapsed_leaf(node): return len(node2labels[node]) == 1 # Export collapsed tree print(t.write(parser=1, is_leaf_fn=collapsed_leaf)) ``` -------------------------------- ### Get tree size Source: https://github.com/etetoolkit/ete/blob/ete4/doc/internals/internals_api.md Retrieve the dimensions (width and height) of a specific tree. This is useful for understanding the tree's graphical representation. ```bash $ http :5000/trees/my-new-tree/size HTTP/1.1 200 OK { "height": 3.0, "width": 2.0 } ``` -------------------------------- ### Tagging and Pushing a New Release Source: https://github.com/etetoolkit/ete/blob/ete4/doc/internals/internals_development.md Commands to tag a new version and push it to the origin repository. Ensure the version number is correctly substituted. ```bash $ git tag -a $version # with the appropriate value of $version $ git push origin $version ``` -------------------------------- ### Initial API Calls for Tree Browsing Source: https://github.com/etetoolkit/ete/blob/ete4/doc/internals/internals_drawing.md Lists the sequence of API calls made when initially browsing a tree, covering fetching data, layouts, styles, and drawing parameters. ```http /trees /trees/tree-1/layouts /trees/tree-1/style?active=["basic","Example+layout"] /trees/tree-1/size /trees/tree-1/nodecount /trees/tree-1/properties /static/images/spritesheet.json /static/images/spritesheet.png /trees/tree-1/draw?shape=rectangular&node_height_min=30&content_height_min=4&zx=1.2&zy=362.7&x=-0.3&y=-0.1&w=3.3&h=3.3&collapsed_shape=skeleton&collapsed_ids=[]&layouts=["basic","Example+layout"]&labels=[] ``` -------------------------------- ### Get Common Ancestor Source: https://github.com/etetoolkit/ete/blob/ete4/doc/3to4.md Use `t.common_ancestor()` for finding the common ancestor of nodes. It accepts a list of nodes and has a shorter name than the older `t.get_common_ancestor()`. ```python t.get_common_ancestor(n1, n2, n3) ``` ```python t.common_ancestor(n1, n2, n3) ``` -------------------------------- ### ETE 4 Tree Initialization with Parser Alias Source: https://github.com/etetoolkit/ete/blob/ete4/doc/3to4.md Demonstrates initializing an ETE 4 tree using a string alias for the parser. 'support' is an alias for `parser=0`, interpreting internal node fields as support values. ```python Tree(nw, parser='support') ``` -------------------------------- ### Get ASCII Representation Source: https://github.com/etetoolkit/ete/blob/ete4/doc/3to4.md Use `t.to_str()` for a modern text representation. It allows fine-tuning with arguments and produces a nicer output compared to `t.get_ascii()`. ```python t.get_ascii() ``` ```python t.to_str() ``` -------------------------------- ### Get Lineage by TaxID (NCBI) Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_taxonomy.md Retrieves the lineage (a list of taxids from root to the given taxid) for a specific taxid using the NCBI taxonomy database. ```python from ete4 import NCBITaxa ncbi = NCBITaxa() print(ncbi.get_lineage(9606)) # [1, 131567, 2759, 33154, 33208, 6072, 33213, 33511, 7711, 89593, 7742, ``` -------------------------------- ### NCBI Taxonomy Integration: Get Rank Source: https://context7.com/etetoolkit/ete/llms.txt Determines the taxonomic rank for a list of NCBI Taxonomy IDs. Returns a dictionary mapping taxids to their ranks. ```python from ete4 import NCBITaxa, PhyloTree ncbi = NCBITaxa() # Get rank information print(ncbi.get_rank([9606, 9443])) # {9443: 'order', 9606: 'species'} ``` -------------------------------- ### View Test Runner Options Source: https://github.com/etetoolkit/ete/wiki/Contributing Display all available command-line options for the test runner script. Use this to customize test execution. ```sh ./run_tests.py -h ``` -------------------------------- ### Specify Basic Layout Explicitly in ETE Explorer Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_smartview.md When not explicitly passing the layouts argument, ETE uses the BASIC_LAYOUT by default. This example shows how to explicitly specify it. ```python from ete4.smartview import BASIC_LAYOUT t.explore(layouts=[BASIC_LAYOUT]) ``` -------------------------------- ### Explore Tree with ETE Standalone Source: https://github.com/etetoolkit/ete/blob/ete4/doc/faqs.md Use the 'ete4 explore' command to quickly visualize a tree from a file in the terminal. ```bash ete4 explore -t mytreefile.nw ``` -------------------------------- ### Get Descendant Taxa (NCBI) Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_taxonomy.md Retrieves descendant taxa for a given taxid or name in the NCBI taxonomy. Can optionally collapse subspecies and return an annotated tree. ```python from ete4 import NCBITaxa ncbi = NCBITaxa() descendants = ncbi.get_descendant_taxa('Homo') print(ncbi.translate_to_names(descendants)) ``` ```python descendants = ncbi.get_descendant_taxa('Homo', collapse_subspecies=True) print(ncbi.translate_to_names(descendants)) ``` ```python tree = ncbi.get_descendant_taxa('Homo', collapse_subspecies=True, return_tree=True) print(tree.to_str(props=['sci_name','taxid'])) ``` -------------------------------- ### ETE Tree Manipulation Methods Source: https://github.com/etetoolkit/ete/blob/ete4/doc/3to4.md Illustrates the syntax for getting distances and swapping/reversing children in ETE trees. Note that `t.swap_children()` has specific behavior for two children. ```python A.get_distance(B) ``` ```python t.get_distance(A, B) ``` ```python t.swap_children() ``` ```python t.reverse_children() ``` -------------------------------- ### NCBI Taxonomy Integration: Get Descendant Taxa Source: https://context7.com/etetoolkit/ete/llms.txt Fetches descendant taxa for a given NCBI taxon name or ID. Can optionally collapse subspecies to simplify results. ```python from ete4 import NCBITaxa, PhyloTree ncbi = NCBITaxa() # Get descendant taxa descendants = ncbi.get_descendant_taxa('Homo', collapse_subspecies=True) print(ncbi.translate_to_names(descendants)) ``` -------------------------------- ### Get Tree Root in ETE 4 Source: https://github.com/etetoolkit/ete/blob/ete4/doc/3to4.md Access the root of the tree directly using the `.root` attribute in ETE 4, which replaces the `t.get_tree_root()` method from ETE 3. ```python t.root ``` -------------------------------- ### Display Leaf Names, Branch Length, and Support Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_treeview.md Displays a tree with leaf node names, branch lengths, and branch support information enabled. Requires importing TreeStyle from ete4.treeview. ```python from ete4 import Tree from ete4.treeview import TreeStyle t = Tree() t.populate(10, random_branches=True) ts = TreeStyle() ts.show_leaf_name = True ts.show_branch_length = True ts.show_branch_support = True t.show(tree_style=ts) ``` -------------------------------- ### Create a Basic ETE Layout Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_smartview.md This snippet shows how to create a basic Layout object with a custom name. It's useful for creating custom visualization layouts that can be explored in the GUI. ```python from ete4 import Tree from ete4.smartview import Layout t = Tree() t.populate(20) layout = Layout(name='I am a layout doing nothing') t.explore(layouts=[layout]) ``` -------------------------------- ### Extended Newick Representation (NHX) Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_trees.md Example of an extended Newick format (NHX) with extra information added to an internal node. NHX uses brackets to enclose additional data. ```default (A:0.3,(B:0.7,(D:0.6,G:0.1):0.6[&&NHX:conf=0.1:name=internal]):0.5); ``` -------------------------------- ### Use Image Faces for Leaves Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_treeview.md Demonstrates how to use image faces to represent leaves in a tree. This involves setting image paths and creating ImgFace objects for each leaf. ```python # Import Tree instance and faces module. from ete4 import Tree from ete4.treeview import faces, TreeStyle # Load an example tree. nw = """ (((Dre:0.008339,Dme:0.300613)1.000000:0.596401, (Cfa:0.640858,Hsa:0.753230)1.000000:0.182035)1.000000:0.106234, ((Dre:0.271621,Cfa:0.046042)1.000000:0.953250, (Hsa:0.061813,Mms:0.110769)1.000000:0.204419)1.000000:0.973467); " t = Tree(nw) # You can create any random tree containing the same leaf names, and # layout will work equally. For example, creating a random tree with 6 # leaves using a given set of names: # t = Tree() # t.populate(6, ['Dme', 'Dre', 'Hsa', 'Ptr', 'Cfa', 'Mms']) # Set the path where images are located. img_path = './' # Create faces based on external images. humanFace = faces.ImgFace(img_path+'human.png') mouseFace = faces.ImgFace(img_path+'mouse.png') dogFace = faces.ImgFace(img_path+'dog.png') chimpFace = faces.ImgFace(img_path+'chimp.png') fishFace = faces.ImgFace(img_path+'fish.png') flyFace = faces.ImgFace(img_path+'fly.png') # Create a face ready to read the name attribute of nodes. nameFace = faces.AttrFace('name', fsize=20, fgcolor='#009000') # Create a conversion between leaf names and real names. code2name = { 'Dre': 'Drosophila melanogaster', 'Dme': 'Danio rerio', 'Hsa': 'Homo sapiens', 'Ptr': 'Pan troglodytes', 'Mms': 'Mus musculus', 'Cfa': 'Canis familiaris'} ``` -------------------------------- ### Tree Visualization and Attributes Source: https://github.com/etetoolkit/ete/blob/ete4/doc/tutorial/tutorial_trees.md Demonstrates basic tree operations including printing a text visualization, accessing children and parent nodes, and populating a tree with a specified number of leaves. ```python # Create a tree with random topology. t = Tree() t.populate(15) print(t) # text visualization of the tree print(t.children) # list of children nodes directly hanging from the root print(t.up) # should be None, since t is the root ``` -------------------------------- ### ETE4 Node ID Property Source: https://github.com/etetoolkit/ete/wiki/3to4 Each node in ETE4 has an `id` attribute, which is a tuple representing its position in the tree, starting from the root. This provides a unique identifier for each node based on its path. ```python from ete4 import Tree t = Tree("((A:1,B:2)C:3,D:4);") # Get the ID of the root node root_id = t.id # Get the ID of a child node child_node = t.children[0] child_id = child_node.id print(f"Root ID: {root_id}") print(f"Child ID: {child_id}") ```