### Install and Activate Development Environment with Pixi Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/index.rst Use Pixi to install development dependencies and enter the shell for development workflows. ```console $ pixi run install $ pixi shell ``` -------------------------------- ### Install Biotite from source (standard) Source: https://github.com/biotite-dev/biotite/blob/main/doc/install.rst Install Biotite from its source repository. This method also builds the Chemical Component Dictionary (CCD). ```console $ pip install . $ python -m biotite.setup_ccd ``` -------------------------------- ### Verify Biotite Installation Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/index.rst Import the sequence module and print a sample protein sequence to verify that Biotite has been installed successfully. ```python import biotite.sequence as seq print(seq.ProteinSequence("BIQTITE*IS*INSTALLED")) ``` -------------------------------- ### Build documentation without gallery and tutorial Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/documentation.rst Command to build the documentation excluding the example gallery and tutorial. ```console $ sphinx-build -D plot_gallery=0 doc build/doc ``` -------------------------------- ### Install Biotite using Pip Source: https://github.com/biotite-dev/biotite/blob/main/README.rst Install Biotite using pip. Ensure you have the necessary dependencies installed beforehand. ```console $ pip install biotite ``` -------------------------------- ### Install Biotite with Test Dependencies Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/testing.rst Install the local repository clone in editable mode with the test dependencies. This command is used before running unit tests. ```console $ pip install -e ".[test]" ``` -------------------------------- ### Install Biotite using Pixi Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/testing.rst Install the local repository clone in editable mode using Pixi. This is a prerequisite for running tests in a Pixi-managed environment. ```console $ pixi run install ``` -------------------------------- ### Format Code with Pixi Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/development.rst Execute this command to format code when using a Pixi setup. ```console $ pixi run format ``` -------------------------------- ### Visualize Guide Tree Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/align_multiple.rst Visualizes the automatically computed guide tree used for the multiple sequence alignment. ```python fig, ax = plt.subplots(figsize=(6.0, 3.0), constrained_layout=True) graphics.plot_dendrogram( ax, guide_tree, orientation="top", labels=list(sequences.keys()), show_distance=False ) _ = ax.set_yticks([]) ``` -------------------------------- ### Get Guide Tree from MUSCLE Alignment Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/application/msa.rst Retrieves the guide tree used during the MUSCLE alignment process. Requires `matplotlib.pyplot` and `biotite.sequence.graphics`. The tree can be plotted using `graphics.plot_dendrogram`. ```python import matplotlib.pyplot as plt import biotite.sequence.graphics as graphics tree = app.get_guide_tree() fig, ax = plt.subplots(figsize=(6.0, 3.0), constrained_layout=True) graphics.plot_dendrogram(ax, tree, orientation="left", show_distance=True) _ = ax.set_xlabel("Distance") ``` -------------------------------- ### Configure Biotite build with environment variables Source: https://github.com/biotite-dev/biotite/blob/main/doc/install.rst Use environment variables to control the compilation process during installation from source. For example, skip building Rust extensions. ```console $ BIOTITE_OMIT_RUST=1 pip install -e . ``` -------------------------------- ### Install Biotite using Conda Source: https://github.com/biotite-dev/biotite/blob/main/README.rst Install Biotite from the conda-forge channel. This is the recommended installation method. ```console $ conda install -c conda-forge biotite ``` -------------------------------- ### Compute Guide Tree with UPGMA Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/align_multiple.rst Computes a guide tree from a custom distance matrix using the UPGMA algorithm. ```python guide_tree = phylo.upgma(distances) fig, ax = plt.subplots(figsize=(6.0, 3.0), constrained_layout=True) graphics.plot_dendrogram( ax, guide_tree, orientation="top", labels=list(sequences.keys()), show_distance=False ) ``` -------------------------------- ### Install Biotite via pip Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/index.rst Use this command to install Biotite using the pip package manager. ```console $ pip install biotite ``` -------------------------------- ### Install Biotite from source (editable) Source: https://github.com/biotite-dev/biotite/blob/main/doc/install.rst Install Biotite from its source repository in editable mode, allowing direct changes to the source code. This method also builds the Chemical Component Dictionary (CCD). ```console $ pip install -e . $ python -m biotite.setup_ccd ``` -------------------------------- ### AtomArrayStack Indexing Examples Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/structure/filter.rst Demonstrates indexing an AtomArrayStack to retrieve individual AtomArrays (models) or substacks using slices. ```python # Get an atom array from the first model subarray = stack[0] # Get a substack containing the first 10 models substack = stack[:10] ``` -------------------------------- ### Optimal Alignment Example Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/align_heuristic.rst Demonstrates optimal alignment for comparison. This is not recommended for large datasets due to performance limitations. ```python import numpy as np import biotite.sequence as seq import biotite.sequence.align as align # Cyclotide F reference = seq.ProteinSequence("GIPCGESCVFIPCISSVVGCSCKSKVCYLD") # Cyclotide E query = seq.ProteinSequence("GIPCAESCVWIPCTVTALLGCSCKDKVCYLD") # This is the alignment we would expect in the end matrix = align.SubstitutionMatrix.std_protein_matrix() print(align.align_optimal(reference, query, matrix)[0]) ``` -------------------------------- ### Align Multiple Sequences with Custom Guide Tree Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/align_multiple.rst Performs multiple sequence alignment using a provided guide tree. Ensure sequences and the guide tree are correctly formatted. The resulting alignment and order are then processed for visualization. ```python alignment, order, _, _ = align.align_multiple( list(sequences.values()), matrix=align.SubstitutionMatrix.std_protein_matrix(), gap_penalty=-5, guide_tree=guide_tree ) alignment = alignment[:, order.tolist()] labels = np.array(list(sequences.keys()))[order] fig, ax = plt.subplots(figsize=(6.0, 3.0), constrained_layout=True) graphics.plot_alignment_type_based( ax, alignment, color_scheme="blossom", symbols_per_line=len(alignment), symbol_size=10, labels=labels, label_size=12, ) ``` -------------------------------- ### Install Biotite in Editable Mode Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/testing.rst Install the local repository clone in editable mode to ensure that the imported package points to your current code. This is useful for in-development testing. ```console $ pip install -e . ``` -------------------------------- ### Run DSSP Application and Annotate SSE Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/application/dssp.rst Instantiate DsspApp with a structure, start the application, wait for it to finish, and retrieve the secondary structure elements. This is useful for direct control over the DSSP process. ```python from tempfile import gettempdir import biotite.database.rcsb as rcsb import biotite.application.dssp as dssp import biotite.structure.io.pdbx as pdbx pdbx_file = pdbx.BinaryCIFFile.read(rcsb.fetch("1l2y", "bcif", gettempdir())) atom_array = pdbx.get_structure(pdbx_file, model=1) app = dssp.DsspApp(atom_array) app.start() app.join() sse = app.get_sse() print("".join(sse)) ``` -------------------------------- ### Run Tests with Pixi Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/testing.rst In a Pixi-managed environment, this command installs the local repository clone and runs the unit tests. It is a convenient alternative to pip and pytest commands. ```console $ pixi run test ``` -------------------------------- ### Include static image in gallery example Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/documentation.rst Special comment to include a static image in a Sphinx-Gallery example. The image file must be in the same directory as the script. ```python # sphinx_gallery_static_image = .png ``` -------------------------------- ### Download and Align Protein Sequences with Biotite Source: https://github.com/biotite-dev/biotite/blob/main/README.rst This example demonstrates downloading protein sequences from NCBI Entrez, parsing them from a FASTA file, and performing an optimal sequence alignment using the BLOSUM62 matrix with affine gap penalties. Requires 'biotite', 'numpy', 'requests', 'msgpack', and 'networkx'. Matplotlib is needed for plotting. ```python import biotite.sequence.align as align import biotite.sequence.io.fasta as fasta import biotite.database.entrez as entrez # Download FASTA file for the sequences of avidin and streptavidin file_name = entrez.fetch_single_file( uids=["CAC34569", "ACL82594"], file_name="sequences.fasta", db_name="protein", ret_type="fasta" ) # Parse the downloaded FASTA file # and create 'ProteinSequence' objects from it fasta_file = fasta.FastaFile.read(file_name) avidin_seq, streptavidin_seq = fasta.get_sequences(fasta_file).values() # Align sequences using the BLOSUM62 matrix with affine gap penalty matrix = align.SubstitutionMatrix.std_protein_matrix() alignments = align.align_optimal( avidin_seq, streptavidin_seq, matrix, gap_penalty=(-10, -1), terminal_penalty=False ) print(alignments[0]) ``` ```text MVHATSPLLLLLLLSLALVAPGLSAR------KCSLTGKWDNDLGSNMTIGAVNSKGEFTGTYTTAV-TA -------------------DPSKESKAQAAVAEAGITGTWYNQLGSTFIVTA-NPDGSLTGTYESAVGNA TSNEIKESPLHGTQNTINKRTQPTFGFTVNWKFS----ESTTVFTGQCFIDRNGKEV-LKTMWLLRSSVN ESRYVLTGRYDSTPATDGSGT--ALGWTVAWKNNYRNAHSATTWSGQYV---GGAEARINTQWLLTSGTT DIGDDWKATRVGINIFTRLRTQKE--------------------- -AANAWKSTLVGHDTFTKVKPSAASIDAAKKAGVNNGNPLDAVQQ ``` -------------------------------- ### Install Biotite via Conda Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/index.rst Use this command to install Biotite using the Conda package manager from the conda-forge channel. ```console $ conda install -c conda-forge biotite ``` -------------------------------- ### Read XTC Trajectory File and Get Coordinates Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/structure/trajectories.rst Demonstrates reading an XTC trajectory file and extracting all coordinates. Requires downloading a sample file for demonstration. ```python from tempfile import NamedTemporaryFile, gettempdir import requests import biotite.structure.io.xtc as xtc # Download 1L2Y as XTC file for demonstration purposes temp_xtc_file = NamedTemporaryFile("wb", suffix=".xtc", delete=False) response = requests.get( "https://raw.githubusercontent.com/biotite-dev/biotite/master/" "tests/structure/data/1l2y.xtc" ) temp_xtc_file.write(response.content) traj_file = xtc.XTCFile.read(temp_xtc_file.name) coord = traj_file.get_coord() print(coord.shape) ``` -------------------------------- ### PBC-Aware Measurements on Trajectories Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/structure/trajectories.rst Demonstrates PBC-aware distance and radial distribution function calculations on trajectory data. Note: The box information in this example is a placeholder. ```python # PBC-aware distance between first and second CA atoms distances = struc.distance( trajectory[:, 0], trajectory[:, 1], box=trajectory.box ) # PBC-aware radial distribution function of each CA atom to all CA atoms bins, rdf = struc.rdf( center=trajectory, atoms=trajectory, interval=(0, 10), periodic=True ) ``` -------------------------------- ### Get and Set Structure from BinaryCIF File Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/structure/io.rst Shows how to retrieve a structure from a BinaryCIF file into an AtomArrayStack and then set it back into the file. This is a common workflow for processing structural data. ```python tc5b = pdbx.get_structure(bcif_file) # Do some fancy stuff pdbx.set_structure(bcif_file, tc5b) ``` -------------------------------- ### Launch PyMOL in Library Mode Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/interface/pymol.rst Starts PyMOL in object-oriented library mode without a GUI. This is the default mode for interacting with PyMOL via its Python API. ```python import biotite.interface.pymol as pymol_interface pymol_interface.launch_pymol() ``` -------------------------------- ### Run MUSCLE Alignment Application Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/application/index.rst Instantiate and run the MUSCLE alignment application with protein sequences. The application runs in the background after ``start()`` and results are collected with ``join()``. ```python from biotite.sequence import ProteinSequence from biotite.application.muscle import MuscleApp app = MuscleApp([ProteinSequence("BIQTITE"), ProteinSequence("IQLITE")]) app.start() # The application is running in the background app.join() ``` -------------------------------- ### Get Structure and Bonds Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/structure/bonds.rst Obtain a structure from a PDB file and connect residues by their names to establish bonds. This snippet demonstrates how to retrieve bond information as an array of indices and atom names. ```python stack = pdbx.get_structure(pdbx_file, include_bonds=False) stack.bonds = struc.connect_via_residue_names(stack) tyrosine = stack[:, (stack.res_id == 3)] print("Bonds (indices):") print(tyrosine.bonds.as_array()) print("Bonds (atoms names):") print(tyrosine.atom_name[tyrosine.bonds.as_array()[:, :2]]) ``` -------------------------------- ### AtomArray Indexing Examples Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/structure/filter.rst Shows various ways to index an AtomArray, including selecting single atoms, subarrays by list, ranges using slices, and filtering based on element and residue ID, or coordinate values. ```python # Get the first atom atom = array[0] # Get a subarray containing the first and third atom subarray = array[[0,2]] # Get a subarray containing a range of atoms using slices subarray = array[100:200] # Filter all carbon atoms in residue 1 subarray = array[(array.element == "C") & (array.res_id == 1)] # Filter all atoms where the X-coordinate is smaller than 2 subarray = array[array.coord[:,0] < 2] ``` -------------------------------- ### Encode and Decode Symbols with Alphabet Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/encoding.rst Demonstrates how to get allowed symbols, encode a symbol to its integer code, and decode an integer code back to a symbol using an unambiguous nucleotide alphabet. ```python import biotite.sequence as seq alph = seq.NucleotideSequence.unambiguous_alphabet() print("Allowed symbols:", alph.get_symbols()) print("G is encoded to", alph.encode("G")) print("2 is decoded to", alph.decode(2)) ``` -------------------------------- ### Build documentation with Pixi (simplified) Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/documentation.rst Simplified Pixi command to build documentation, excluding gallery and tutorial. ```console $ pixi run doc ``` -------------------------------- ### Set up and Run OpenMM Simulation Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/interface/openmm.rst Creates an OpenMM System, Integrator, and Simulation object, performs energy minimization, and runs the simulation, recording states at specified intervals. ```python TIME_STEP = 0.004 FRAME_STEP = 2.0 N_FRAMES = 60 system = force_field.createSystem( topology, nonbondedMethod=app.PME, nonbondedCutoff=1 * nanometer, constraints=app.HBonds, ) integrator = openmm.LangevinMiddleIntegrator( 300 * kelvin, 1 / picosecond, TIME_STEP * picosecond ) simulation = app.Simulation(topology, system, integrator) simulation.context.setPositions(modeller.positions) simulation.minimizeEnergy() # Run simulation and record the current state (the coordinates) # every FRAME_STEP picoseconds states = [] for i in range(N_FRAMES): simulation.step(FRAME_STEP // TIME_STEP) states.append(simulation.context.getState(getPositions=True)) ``` -------------------------------- ### Build documentation with Pixi Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/documentation.rst Command to build the full documentation using Pixi in a managed environment. ```console $ pixi run doc-full ``` -------------------------------- ### Build documentation with Sphinx Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/documentation.rst Command to build the full documentation using Sphinx from the repository root. ```console $ sphinx-build doc build/doc ``` -------------------------------- ### Set Up Development Environment with Conda Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/index.rst Create and activate a development environment using a Conda environment file. Note: This method is deprecated. ```console $ conda env create -f environment.yml $ conda activate biotite-dev ``` -------------------------------- ### Create and Inspect BondList Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/structure/bonds.rst Demonstrates the creation of an AtomArray and a BondList, then prints the bond information in different formats. Use this to manually define bonds for a small set of atoms. ```python import biotite.structure as struc import numpy as np array = struc.array([ struc.Atom([0,0,0], atom_name="N"), struc.Atom([0,0,0], atom_name="CA"), struc.Atom([0,0,0], atom_name="C"), struc.Atom([0,0,0], atom_name="CB") ]) print("Atoms:", array.atom_name) bond_list = struc.BondList( array.array_length(), np.array([[1,0], [1,2], [1,3]]) ) print("Bonds (indices and type):") print(bond_list.as_array()) print("Bonds (atoms names):") print(array.atom_name[bond_list.as_array()[:, :2]]) ca_bonds, ca_bond_types = bond_list.get_bonds(1) print("Bonds of CA:", array.atom_name[ca_bonds]) ``` -------------------------------- ### Create Simulation Box Vectors Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/structure/trajectories.rst Shows how to create simulation box vectors from unit cell dimensions and angles using :func:`vectors_from_unitcell`. Also demonstrates calculating box volume, checking for orthogonality, and converting vectors back to unit cell parameters. ```python import numpy as np # The function uses angles in radians box = struc.vectors_from_unitcell(10, 20, 30, np.pi/2, np.pi/2, np.pi/2) print("Box:") print(box) print("Box volume:", struc.box_volume(box)) print("Is the box orthogonal?", struc.is_orthogonal(box)) len_a, len_b, len_c, alpha, beta, gamma = struc.unitcell_from_vectors(box) print("Cell lengths:") print(len_a, len_b, len_c) print("Cell angles:") print(np.rad2deg(alpha), np.rad2deg(beta), np.rad2deg(gamma)) ``` -------------------------------- ### Install C-compiler via Conda Source: https://github.com/biotite-dev/biotite/blob/main/doc/install.rst If you encounter GCC compiler errors on certain Linux distributions when building Biotite from source, install a C-compiler using Conda. ```console $ conda install -c conda-forge c-compiler ``` -------------------------------- ### Include tutorial preamble Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/documentation.rst RST directive to include the preamble for tutorial pages, necessary for jupyter-sphinx integration. ```rst .. include:: /tutorial/preamble.rst ``` -------------------------------- ### Create and Print a Tree Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/align_multiple.rst Demonstrates creating a tree from TreeNode objects and converting it to Newick format with and without distances. Also shows how to calculate distances between nodes. ```python import biotite.sequence.phylo as phylo # The reference objects fruits = ["Apple", "Pear", "Orange", "Lemon", "Banana"] # Create nodes apple = phylo.TreeNode(index=fruits.index("Apple")) pear = phylo.TreeNode(index=fruits.index("Pear")) orange = phylo.TreeNode(index=fruits.index("Orange")) lemon = phylo.TreeNode(index=fruits.index("Lemon")) banana = phylo.TreeNode(index=fruits.index("Banana")) intermediate1 = phylo.TreeNode( children=(apple, pear), distances=(2.0, 2.0) ) intermediate2 = phylo.TreeNode((orange, lemon), (1.0, 1.0)) intermediate3 = phylo.TreeNode((intermediate2, banana), (2.0, 3.0)) root = phylo.TreeNode((intermediate1, intermediate3), (2.0, 1.0)) # Create tree from root node tree = phylo.Tree(root=root) # Trees can be converted into Newick notation print("Tree:", tree.to_newick(labels=fruits)) # Distances can be omitted print( "Tree w/o distances", tree.to_newick(labels=fruits, include_distance=False) ) # Distances can be measured distance = tree.get_distance(fruits.index("Apple"), fruits.index("Banana")) print("Distance Apple-Banana:", distance) ``` -------------------------------- ### Query RCSB PDB for Structures Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/database/rcsb.rst Construct a query to find structures in the RCSB PDB. This example searches for 'Lysozyme' descriptions from 'Homo sapiens'. ```python query = ( rcsb.FieldQuery("rcsb_polymer_entity.pdbx_description", contains_phrase="Lysozyme") & rcsb.FieldQuery( "rcsb_entity_source_organism.scientific_name", exact_match="Homo sapiens" ) ) ids = rcsb.search(query, content_types=("computational",)) print(ids) ``` -------------------------------- ### Perform Multiple Sequence Alignment Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/align_multiple.rst Performs a progressive multiple sequence alignment using the fetched sequences. A guide tree is automatically computed if not provided. ```python alignment, order, guide_tree, distance_matrix = align.align_multiple( list(sequences.values()), matrix=align.SubstitutionMatrix.std_protein_matrix(), gap_penalty=-5, ) # Order alignment according to guide tree alignment = alignment[:, order.tolist()] labels = np.array(list(sequences.keys()))[order] fig, ax = plt.subplots(figsize=(6.0, 3.0), constrained_layout=True) graphics.plot_alignment_type_based( ax, alignment, color_scheme="blossom", symbols_per_line=len(alignment), symbol_size=10, labels=labels, label_size=12, ) ``` -------------------------------- ### Create Test Structures Source: https://github.com/biotite-dev/biotite/blob/main/tests/structure/data/README.rst Use this command to generate test structure files from a list of PDB IDs. Ensure you have the 'create_test_structures.py' script and an 'ids.txt' file containing the desired PDB IDs. ```console $ python create_test_structures.py -f ids.txt ``` -------------------------------- ### Set PyMOL Command Parameters Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/interface/pymol.rst Sets a specific PyMOL command parameter using the `pymol.cmd` interface. This example sets the sphere scaling factor. ```python pymol_interface.cmd.set("sphere_scale", 1.5) ``` -------------------------------- ### Run Common Development Workflows with Pixi Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/index.rst Execute common development tasks like testing, linting, formatting, and documentation generation using Pixi. ```console $ pixi run test $ pixi run lint $ pixi run format $ pixi run doc ``` -------------------------------- ### Get Sequence object from FastqFile Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/io.rst Retrieves a Sequence object and its corresponding quality scores from a FastqFile object. It prints the representation of the Sequence object and the scores. ```python seq, scores = fastq.get_sequence(fastq_file) print(repr(seq)) print(scores) ``` -------------------------------- ### Convert OpenMM States to Biotite Trajectory and Visualize Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/interface/openmm.rst Converts OpenMM simulation states into a Biotite AtomArrayStack, superimposes the frames, and visualizes the resulting trajectory using PyMOL. ```python # In this case we can reuse the input structure as template, # as not atoms have been added or removed trajectory = openmm_interface.from_states(water, states) # Superimpose the frames trajectory, _ = struc.superimpose(trajectory[0], trajectory) # Remove the box from the previous visualization del box pymol_object = pymol_interface.PyMOLObject.from_structure(trajectory) # Visualize as stick model pymol_interface.cmd.set("stick_radius", 0.15) pymol_interface.cmd.set("sphere_scale", 0.25) pymol_interface.cmd.set("sphere_quality", 4) # Visualize docked model pymol_object.show("spheres") pymol_object.show("sticks") pymol_object.set("stick_color", "black") pymol_object.orient() pymol_interface.cmd.mset() # Play as looping GIF pymol_interface.play((300, 300)) ``` -------------------------------- ### Get Sequence objects from FastaFile Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/io.rst Converts a FastaFile object into a dictionary of Sequence objects (NucleotideSequence or ProteinSequence). It prints the header and the representation of each sequence object. ```python dna_sequences = fasta.get_sequences(fasta_file) for header, sequence in dna_sequences.items(): print("Header:", header) # Note that this time we have a Sequence object instead of a string print("Sequence:", repr(sequence)) print() ``` -------------------------------- ### Automatic Compression of BinaryCIFData Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/structure/io.rst Demonstrates the use of the `compress()` function to automatically find optimal encodings for BinaryCIFData, comparing the resulting sizes. ```python uncompressed_data = pdbx.BinaryCIFData(np.arange(100)) print(f"Uncompressed size: {len(uncompressed_data.serialize()["data"])} bytes") compressed_data = pdbx.compress(uncompressed_data) print(f"Compressed size: {len(compressed_data.serialize()["data"])} bytes") ``` -------------------------------- ### Draw a Box Shape Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/interface/pymol.rst Draws a box shape in PyMOL using predefined CGO combinations. This example creates a white box with specified dimensions and origin. ```python box = pymol_interface.draw_box( np.diag([10, 10, 10]), origin=[-2.5, -5.0, -5.0], width=5, # white color=(1, 1, 1), ) box.zoom(buffer=2) pymol_interface.show(PNG_SIZE, use_ray=True) ``` -------------------------------- ### Download FASTA file from NCBI Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/io.rst Downloads FASTA files for specified protein IDs from the NCBI Entrez database. The downloaded content is printed to the console. ```python from tempfile import gettempdir, NamedTemporaryFile import biotite.sequence as seq import biotite.sequence.io.fasta as fasta import biotite.database.entrez as entrez temp_file = NamedTemporaryFile(suffix=".fasta", delete=False) file_path = entrez.fetch_single_file( ["6BB5_A", "6BB5_B"], temp_file.name, db_name="protein", ret_type="fasta" ) with open(file_path) as file: print(file.read()) ``` -------------------------------- ### Get and Print Annotated Sequence Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/annotations.rst Retrieves the annotated sequence from a GenBank file and prints its first 60 characters. Verifies if the annotation matches the retrieved one. ```python annot_seq = gb.get_annotated_sequence(file) print("Same annotation as before?", (annotation == annot_seq.annotation)) print(annot_seq.sequence[:60], " ...") ``` -------------------------------- ### Initialize E-value Estimator Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/align_heuristic.rst Initializes an EValueEstimator with a scoring matrix, gap penalty, and uniform background frequencies. The `sample_length` parameter is reduced for faster execution in this tutorial. ```python estimator = align.EValueEstimator.from_samples( seq.ProteinSequence.alphabet, matrix, gap_penalty=-5, frequencies=np.ones(len(seq.ProteinSequence.alphabet)), # Trade accuracy for a shorter run time for this tutorial sample_length=200 ) ``` -------------------------------- ### Format and Lint Python Code Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/development.rst Run these commands to format and lint Python code according to Biotite's standards using Ruff. ```console $ ruff format $ ruff check --fix ``` -------------------------------- ### Define Custom Sequence by Subclassing Sequence Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/types.rst Subclass `Sequence` when your custom sequence requires type-specific methods. This example defines a custom alphabet and a `MySequence` class that uses it. ```python custom_alphabet = seq.Alphabet(["foo", "bar", 42]) class MySequence(seq.Sequence): def get_alphabet(self): return custom_alphabet custom_seq = MySequence(["foo", "bar", 42, 42, "foo"]) print(custom_seq) ``` -------------------------------- ### Get Sequence Alphabet Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/index.rst Access the alphabet associated with a sequence object to understand the set of valid symbols it can contain. For DNA, this typically includes A, C, G, and T. ```python print(dna.alphabet) ``` -------------------------------- ### Run Unit Tests with Pytest Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/testing.rst Execute the unit tests for the Biotite package using the pytest framework. Ensure you have installed the package in editable mode with test dependencies first. ```console $ pytest ``` -------------------------------- ### Create Substitution Matrix from Profile Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/profiles.rst Create a SubstitutionMatrix from a profile's log-odds matrix. Requires a positional sequence alphabet and the query sequence alphabet. Scores are multiplied by 10 and converted to integers. ```python positional_seq = seq.PositionalSequence(profile.to_consensus()) matrix = align.SubstitutionMatrix( positional_seq.alphabet, seq.ProteinSequence.alphabet, # Substitution matrices require integer scores # Multiply by 10 to increase value range and convert to integer (log_odds * 10).astype(int) ) alignment = align.align_optimal( positional_seq, query, matrix, gap_penalty=-5, max_number=1 )[0] print(alignment) ``` -------------------------------- ### Create OpenMM System from Biotite Structure Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/interface/openmm.rst Constructs an OpenMM System for a water molecule using Biotite's structure information. This is useful for custom force field setups. ```python import biotite.structure.info as info TIME_STEP = 0.001 FRAME_STEP = 0.1 N_FRAMES = 120 water = info.residue("HOH") system = openmm_interface.to_system(water) ``` -------------------------------- ### Fetch PDB file with overwrite Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/database/rcsb.rst Downloads a PDB file, overwriting it if it already exists in the target directory by setting `overwrite=True`. ```python # Download file in the fast and small BinaryCIF format file_path = rcsb.fetch("1l2y", "bcif", gettempdir(), overwrite=True) ``` -------------------------------- ### Convert Structure to 3Di Sequence Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/structure/alphabet.rst Fetches a protein structure from the PDB, filters for amino acids, and converts it into a 3Di structural sequence. Returns the sequences and chain start indices. ```python import biotite.database.rcsb as rcsb import biotite.structure as struc import biotite.structure.alphabet as strucalph import biotite.structure.io.pdbx as pdbx # You can actually directly read the downloaded PDBx file content # without an intermediate file pdbx_file = pdbx.BinaryCIFFile.read(rcsb.fetch("2ZVS", "bcif")) ec_ferredoxin = pdbx.get_structure(pdbx_file, model=1) # This structural alphabet expects a peptide chain ec_ferredoxin = ec_ferredoxin[struc.filter_amino_acids(ec_ferredoxin)] structural_sequences, chain_starts = strucalph.to_3di(ec_ferredoxin) print(structural_sequences) print(chain_starts) ``` -------------------------------- ### Align Sequences with MUSCLE Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/application/msa.rst Aligns a list of sequences using the MUSCLE application. Requires `biotite.application.muscle`. The `start()`, `join()`, and `get_alignment()` methods are used to manage the application and retrieve the results. ```python import biotite.application.muscle as muscle app = muscle.MuscleApp(sequences) app.start() app.join() alignment = app.get_alignment() print(alignment) ``` -------------------------------- ### Draw Custom Shapes with CGOs Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/interface/pymol.rst Draws custom geometric shapes using Compiled Graphics Objects (CGOs) in PyMOL. This example creates spheres connected by a colored gradient cylinder. ```python PNG_SIZE = (1500, 750) RED = to_rgb("#db3a35") BLUE = to_rgb("#1772f0") gradient_bond = pymol_interface.draw_cgo( [ pymol_interface.get_sphere_cgo(pos=(0, 0, 0), radius=1.0, color=RED), pymol_interface.get_cylinder_cgo( start=(0, 0, 0), end=(5, 0, 0), radius=0.5, start_color=RED, end_color=BLUE ), pymol_interface.get_sphere_cgo(pos=(5, 0, 0), radius=1.0, color=BLUE), ], ) # Zomm a little bit out gradient_bond.zoom(buffer=2) pymol_interface.show(PNG_SIZE, use_ray=True) ``` -------------------------------- ### Format and Lint Rust Code Source: https://github.com/biotite-dev/biotite/blob/main/doc/contribution/development.rst Run these commands to format and lint Rust code using Cargo. ```console $ cargo fmt $ cargo clippy --fix --allow-dirty ``` -------------------------------- ### Create Protein Substitution Matrix Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/align_optimal.rst Demonstrates various ways to create a SubstitutionMatrix for protein sequences, including loading predefined matrices (BLOSUM62, BLOSUM50), modifying dictionary representations, and creating a matrix from a NumPy array. ```python import biotite.sequence as seq import biotite.sequence.align as align import numpy as np alph = seq.ProteinSequence.alphabet # Load the standard protein substitution matrix, which is BLOSUM62 matrix = align.SubstitutionMatrix.std_protein_matrix() print("\nBLOSUM62\n") print(matrix) # Load another matrix from internal database matrix = align.SubstitutionMatrix(alph, alph, "BLOSUM50") # Load a matrix dictionary representation, # modify it, and create the SubstitutionMatrix # (The dictionary could be alternatively loaded from a string containing # the matrix in NCBI format) matrix_dict = align.SubstitutionMatrix.dict_from_db("BLOSUM62") matrix_dict[("P","Y")] = 100 matrix = align.SubstitutionMatrix(alph, alph, matrix_dict) # And now create a matrix by directly providing the ndarray # containing the similarity scores # (identity matrix in our case) scores = np.identity(len(alph), dtype=int) matrix = align.SubstitutionMatrix(alph, alph, scores) print("\n\nIdentity matrix\n") print(matrix) ``` -------------------------------- ### Use and Load Codon Tables Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/types.rst Shows how to use the default `CodonTable` for mapping codons to amino acids and vice versa. It also demonstrates loading official NCBI codon tables by name or ID. ```python table = seq.CodonTable.default_table() # Find the amino acid encoded by a given codon print(table["TAC"]) # Find the codons encoding a given amino acid print(table["Y"]) # Works also for codes instead of symbols print(table[(1,2,3)]) print(table[14]) ``` ```python # Use the official NCBI table name table = seq.CodonTable.load("Yeast Mitochondrial") print("Yeast Mitochondrial:") print(table) print() # Use the official NCBI table ID table = seq.CodonTable.load(11) print("Bacterial:") print(table) ``` -------------------------------- ### K-mer Table Creation Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/align_heuristic.rst Creates a k-mer index table from reference sequences. This table maps k-mers to their positions, enabling efficient lookup of potential matches. ```python # Create a k-mer index table from the k-mers of the reference sequence kmer_table = align.KmerTable.from_sequences( # Use 3-mers k=3, # Add only the reference sequence to the table sequences=[reference], # The purpose of the reference ID is to identify the sequence # As there is only one sequence in this simple example, # there is only one ID ref_ids=[0] ) for ref_id, position in kmer_table[kmer_alphabet.encode("IPC")]: print(position) ``` -------------------------------- ### Create Nucleotide Sequences Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/types.rst Demonstrates creating NucleotideSequence objects from strings and lists. The constructor automatically determines the required alphabet, supporting both unambiguous and ambiguous bases. ```python import biotite.sequence as seq # Create a nucleotide sequence using a string # The constructor can take any iterable object (e.g. a list of symbols) seq1 = seq.NucleotideSequence("ACCGTATCAAG") print(seq1.get_alphabet()) # Constructing a sequence with ambiguous nucleic bases seq2 = seq.NucleotideSequence("TANNCGNGG") print(seq2.get_alphabet()) ``` -------------------------------- ### BLAST search for a protein sequence Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/application/blast.rst Use BlastWebApp to find homologous sequences for a given protein sequence. After the application starts and finishes, alignments can be retrieved and details of the best alignment are printed. ```python import biotite.application.blast as blast import biotite.sequence as seq tc5b_seq = seq.ProteinSequence("NLYIQWLKDGGPSSGRPPPS") app = blast.BlastWebApp("blastp", tc5b_seq) app.start() app.join() alignments = app.get_alignments() best_ali = alignments[0] print(best_ali) print() print("HSP position in query: ", best_ali.query_interval) print("HSP position in hit: ", best_ali.hit_interval) print("Score: ", best_ali.score) print("E-value: ", best_ali.e_value) print("Hit UID: ", best_ali.hit_id) print("Hit name: ", best_ali.hit_definition) ``` -------------------------------- ### Extract and Print Poly-A Signal Sequence Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/annotations.rst Indexes an annotated sequence to extract a specific region (poly-A signal) and prints its sequence and the new sequence start position. Demonstrates slicing an AnnotatedSequence. ```python print("Sequence start before indexing:", annot_seq.sequence_start) for feature in annot_seq.annotation: if feature.key == "regulatory" \ and feature.qual["regulatory_class"] == "polyA_signal_sequence": polya_feature = feature loc = list(polya_feature.locs)[0] # Get annotated sequence containing only the poly-A signal region poly_a = annot_seq[loc.first : loc.last + 1] print("Sequence start after indexing:", poly_a.sequence_start) print(poly_a.sequence) ``` -------------------------------- ### Write sequences to FASTA file Source: https://github.com/biotite-dev/biotite/blob/main/doc/tutorial/sequence/io.rst Creates a new empty FastaFile, appends sequences using set_sequence() and dictionary-style assignment, and writes the content to a temporary file. The FastaFile object's content is printed before writing. ```python # Create new empty FASTA file fasta_file = fasta.FastaFile() # PROTIP: Let your cat walk over the keyboard dna_seq1 = seq.NucleotideSequence("ATCGGATCTATCGATGCTAGCTACAGCTAT") dna_seq2 = seq.NucleotideSequence("ACGATCTACTAGCTGATGTCGTGCATGTACG") # Append entries to file... # ... via set_sequence() fasta.set_sequence(fasta_file, dna_seq1, header="gibberish") # .. or dictionary style fasta_file["more gibberish"] = str(dna_seq2) print(fasta_file) temp_file = NamedTemporaryFile(suffix=".fasta", delete=False) fasta_file.write(temp_file.name) temp_file.close() ```