### Install Development Packages Source: https://github.com/pyranges/pyranges0/blob/master/docs/developer_guide.md Install necessary packages for testing, linting, and documentation checks. ```bash pip install flake8 black isort hypothesis pytest \ pytest-watch sphinx sphinx-autoapi sphinxcontrib-napoleon \ pyfaidx pyBigWig sphinx_rtd_theme ``` -------------------------------- ### Install Optional Dependency: Ray Source: https://github.com/pyranges/pyranges0/blob/master/docs/_iframe.html Install Ray using pip for multicpu support. ```bash pip install -U ray ``` -------------------------------- ### Install pyranges_db Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Instructions for installing the `pyranges_db` add-on, used for fetching chromosome sizes required by `to_bigwig`. ```bash pip install pyranges_db ``` -------------------------------- ### Install bamread library Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Instructions for installing the optional `bamread` library, which is required for reading BAM files with PyRanges. It can be installed using either Conda or pip. ```default conda install -c bioconda bamread ``` ```default pip install bamread ``` -------------------------------- ### Install PyRanges with Pip Source: https://github.com/pyranges/pyranges0/blob/master/docs/_iframe.html Use this command to install PyRanges using pip. ```bash pip install pyranges ``` -------------------------------- ### Install Optional Dependency: BamRead (Pip) Source: https://github.com/pyranges/pyranges0/blob/master/docs/_iframe.html Install bamread using pip if you need to read BAM files. ```bash pip install bamread ``` -------------------------------- ### Install Optional Dependency: pyfaidx Source: https://github.com/pyranges/pyranges0/blob/master/docs/_iframe.html Install pyfaidx using pip if you need to fetch sequences from FASTA files. ```bash pip install pyfaidx ``` -------------------------------- ### Install Optional Dependency: ray Source: https://github.com/pyranges/pyranges0/blob/master/docs/installation.md Install ray using pip for multicpu functionality. Use the -U flag for upgrade. ```none # ray: multicpu pip install -U ray ``` -------------------------------- ### Access Example Datasets Source: https://github.com/pyranges/pyranges0/blob/master/CHANGELOG.txt Convenient functions are available to access example datasets, such as `exons()` and `cpg()`, for testing and demonstration purposes. ```python pr.data.exons(), pr.data.cpg() ``` -------------------------------- ### Install Optional Dependency: Fisher (Pip) Source: https://github.com/pyranges/pyranges0/blob/master/docs/_iframe.html Install fisher using pip for fast Fisher's exact test. ```bash pip install fisher ``` -------------------------------- ### Method Chaining Example Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Demonstrates method chaining with `to_csv` and `chain=True` for intermediate result storage. ```default pr.data().f1().to_csv("bla", chain=True).merge()... ``` -------------------------------- ### Install Optional Dependency: bamread Source: https://github.com/pyranges/pyranges0/blob/master/docs/installation.md Install bamread using pip for reading BAM files. Alternatively, use conda. ```none # bamread: read bam files pip install bamread # or conda install -c bioconda bamread ``` -------------------------------- ### Filter PyRanges by sequence start Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md This example shows how to filter the PyRanges object based on the content of the 'Sequence' column, specifically selecting intervals whose sequences start with 'G'. ```python sg[sg.Sequence.str.startswith('G')] ``` -------------------------------- ### Install pyfaidx with conda Source: https://github.com/pyranges/pyranges0/blob/master/docs/tutorial.md Install the pyfaidx optional module using conda for enhanced functionality. ```shell conda install -c bioconda pyfaidx ``` -------------------------------- ### Install Optional Dependency: PyBigWig (Pip) Source: https://github.com/pyranges/pyranges0/blob/master/docs/_iframe.html Install pybigwig using pip if you need to write BigWig files. ```bash pip install pybigwig ``` -------------------------------- ### Install PyRanges with Conda Source: https://github.com/pyranges/pyranges0/blob/master/docs/_iframe.html Use this command to install PyRanges via the bioconda channel. ```bash conda install -c bioconda pyranges ``` -------------------------------- ### Install pybigwig Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_pages.md Installs the pybigwig library using conda or pip. This library is required for writing BigWig files. ```bash conda install -c bioconda pybigwig ``` ```bash pip install pybigwig ``` -------------------------------- ### Run Pyranges Doctests Source: https://github.com/pyranges/pyranges0/blob/master/docs/developer_guide.md Run the doctests for Pyranges to verify examples in the documentation. This helps ensure that code examples are accurate and functional. ```bash py.test tests/tutorial_doctest ``` -------------------------------- ### Install PyRanges in Editable Mode Source: https://github.com/pyranges/pyranges0/blob/master/docs/developer_guide.md Install PyRanges locally using pip in editable mode, so code changes are reflected immediately. ```bash cd pyranges0 pip install -e . ``` -------------------------------- ### Install Optional Dependency: Fisher (Conda) Source: https://github.com/pyranges/pyranges0/blob/master/docs/_iframe.html Install fisher using the bioconda channel for fast Fisher's exact test. ```bash conda install -c bioconda fisher ``` -------------------------------- ### Install Optional Dependency: BamRead (Conda) Source: https://github.com/pyranges/pyranges0/blob/master/docs/_iframe.html Install bamread using the bioconda channel if you need to read BAM files. ```bash conda install -c bioconda bamread ``` -------------------------------- ### Install pyfaidx Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_pages.md Installs the pyfaidx library using conda or pip. This library is used to derive chromosome sizes from FASTA files. ```bash conda install -c bioconda pyfaidx ``` ```bash pip install pyfaidx ``` -------------------------------- ### Install Optional Dependency: pybigwig Source: https://github.com/pyranges/pyranges0/blob/master/docs/installation.md Install pybigwig using pip for writing bigwig files. Alternatively, use conda. ```none # pybigwig: write bigwigs pip install pybigwig # or conda install -c bioconda pybigwig ``` -------------------------------- ### Print PyRanges Data Overview Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Use the `print()` method to get a formatted overview of your PyRanges object, including chromosome, start, end, name, score, and strand. This method is also invoked when requesting a string representation. ```python >>> import pyranges as pr >>> gr = pr.data.chipseq() >>> gr.print() ``` ```python >>> print(str(gr)) ``` -------------------------------- ### Install Optional Dependency: PyBigWig (Conda) Source: https://github.com/pyranges/pyranges0/blob/master/docs/_iframe.html Install pybigwig using the bioconda channel if you need to write BigWig files. ```bash conda install -c bioconda pybigwig ``` -------------------------------- ### PyRanges DB on PyPI Source: https://github.com/pyranges/pyranges0/blob/master/CHANGELOG.txt The `pyranges_db` module is now available on PyPI, making it easier to install and use database-related functionalities. ```python pyranges_db now out on PyPI ``` -------------------------------- ### Keyword Arguments for `apply` and `apply_pair` Source: https://github.com/pyranges/pyranges0/blob/master/CHANGELOG.txt The `apply` and `apply_pair` methods now accept keyword arguments, providing more flexibility in how these functions are used. Refer to the documentation for specific examples. ```python allow keyword-arguments to apply, apply_pair (see example in the docs) ``` -------------------------------- ### Create a second PyRanges object Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Initializes a second PyRanges object from a different set of genomic intervals, similar to the first example. ```python f2 = """Chromosome Start End Score Strand chr1 5 6 -0.01 - chr1 9 12 200 + chr3 0 14 21.21 -""" df2 = pd.read_csv(StringIO(f2), sep="\s+") gr2 = PyRanges(df2) ``` -------------------------------- ### Selecting Genomic Regions on 'chrY' Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_pages.md This example shows how bracket notation with a chromosome name selects genomic regions on that chromosome. ```python >>> gr['chrY'] +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chrY | 12930373 | 12930398 | U0 | 0 | + | | chrY | 15548022 | 15548047 | U0 | 0 | + | | chrY | 7194340 | 7194365 | U0 | 0 | + | | chrY | 21559181 | 21559206 | U0 | 0 | + | | ... | ... | ... | ... | ... | ... | | chrY | 15224235 | 15224260 | U0 | 0 | - | | chrY | 13517892 | 13517917 | U0 | 0 | - | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 23 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. ``` -------------------------------- ### Count ATG Start Codons Source: https://github.com/pyranges/pyranges0/blob/master/docs/tutorial.md Converts sequences to uppercase and counts the occurrences of 'ATG' as a start codon using pandas. It also stores the IDs of CDSs with ATG codons. ```python seq_first.Sequence = seq_first.Sequence.str.upper() is_atg = (seq_first.Sequence == 'ATG') is_atg_ids = seq_first[is_atg].ID n_atg = is_atg.sum() print(f'There are {n_atg} ATG start codons out of 'f'{len(seq_first)} CDSs => {n_atg/len(seq_first):.2%}') ``` -------------------------------- ### Instantiate PyRanges from DataFrame Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_pages.md Shows how to create a PyRanges object by passing a Pandas DataFrame to the PyRanges constructor. The DataFrame must contain at least 'Chromosome', 'Start', and 'End' columns. ```python p=pr.PyRanges(df) print(p) ``` -------------------------------- ### Direct PyRanges Constructor Source: https://context7.com/pyranges/pyranges0/llms.txt Initialize PyRanges directly from a pandas DataFrame or from individual coordinate arrays. The DataFrame method requires 'Chromosome', 'Start', and 'End' columns. The array method accepts 'chromosomes', 'starts', 'ends', and optional 'strands'. ```python import pyranges as pr import pandas as pd # From DataFrame df = pd.DataFrame({ "Chromosome": ["chr1", "chr2"], "Start": [100, 200], "End": [150, 201] }) gr = pr.PyRanges(df) # From individual arrays gr2 = pr.PyRanges( chromosomes="chr1", starts=(1, 5), ends=[3, 149], strands=("+", "-") ) print(gr2) ``` -------------------------------- ### Create PyRanges from a DataFrame Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Demonstrates creating a PyRanges object from a pandas DataFrame. Ensure the DataFrame has 'Chromosome', 'Start', and 'End' columns. ```python f1 = """Chromosome Start End Score Strand chr1 4 7 23.8 + chr1 6 11 0.13 - chr2 0 14 42.42 +""" df1 = pd.read_csv(StringIO(f1), sep="\s+") gr1 = PyRanges(df1) ``` -------------------------------- ### Create Pandas DataFrame for PyRanges Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_pages.md Demonstrates creating a Pandas DataFrame with required 'Chromosome', 'Start', and 'End' columns, along with optional 'Strand' and other metadata columns. This DataFrame can then be used to instantiate a PyRanges object. ```python import pandas as pd, pyranges as pr df=pd.DataFrame( {'Chromosome':['chr1', 'chr1', 'chr1', 'chr3'], 'Start': [5, 20, 80, 10], 'End': [10, 28, 95, 38], 'Strand':['+', '+', '-', '+'], 'title': ['a', 'b', 'c', 'd']} ) print(df) ``` -------------------------------- ### Create a PyRanges object from a dictionary Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md This code shows how to initialize a PyRanges object using a dictionary. The dictionary must contain columns for 'Chromosome', 'Start', 'End', 'name', and 'Strand'. ```python sg = pr.from_dict({"Chromosome": ["chrZ", "chrZ", "chrZ", "chrZ"], "Start": [0, 5, 10, 10], "End": [3, 8, 20, 20], "name":["a", "a", "b", "c"], "Strand":["+", "+", "+", "-"] }) ``` -------------------------------- ### Instantiate PyRanges with Split Strings and Lists Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_pages.md Construct a PyRanges object by splitting strings for chromosomes and strands, and providing lists for starts and ends. This allows for creating ranges across multiple chromosomes with different strands. ```python >>> gr = pr.PyRanges(chromosomes="chr1 chr2 chr3".split(), strands="+ - +".split(), starts=[0, 1, 2], ends=(3, 4, 5)) >>> print(gr) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 0 | 3 | + | | chr2 | 1 | 4 | - | | chr3 | 2 | 5 | + | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. ``` -------------------------------- ### Instantiate PyRanges with Single Values and Lists Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_pages.md Create a PyRanges object using a single string for chromosomes and strands, and lists for starts and ends. This is useful for creating uniform ranges. ```python >>> gr = pr.PyRanges(chromosomes="chr1", strands="+", starts=[0, 1, 2], ends=(3, 4, 5)) >>> print(gr) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 0 | 3 | + | | chr1 | 1 | 4 | + | | chr1 | 2 | 5 | + | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. ``` -------------------------------- ### Instantiate PyRanges with Pandas Series Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_pages.md Use constructor keywords to create a PyRanges object from Pandas Series. Ensure the Series correspond to 'chromosomes', 'starts', and 'ends'. ```python >>> gr = pr.PyRanges(chromosomes=df.Chromosome, starts=df.Start, ends=df.End) >>> print(gr) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 100079649 | 100079674 | | chr1 | 212609534 | 212609559 | | chr1 | 223587418 | 223587443 | | chr1 | 202450161 | 202450186 | | ... | ... | ... | | chrY | 11942770 | 11942795 | | chrY | 8316773 | 8316798 | | chrY | 7463444 | 7463469 | | chrY | 7405376 | 7405401 | +--------------+-----------+-----------+ Unstranded PyRanges object has 10,000 rows and 3 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome. ``` -------------------------------- ### Create PyRanges from Dictionary Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_pages.md Initialize a PyRanges object from a Python dictionary. Ensure the dictionary contains keys for 'Chromosome', 'Start', 'End', and optionally 'Strand' and other metadata. ```python >>> d = {"Chromosome": [1, 1, 1, 2, 2], ... "Start": [1, 1, 2, 1, 8], ... "End": [4, 4, 9, 4, 12], ... "Strand": ["+", "+", "+", "+","-"], ... "ID": ["a", "b", "c", "d", "e"]} >>> p = pr.from_dict(d) ``` -------------------------------- ### Get Transcription Start Sites (TSS) Source: https://context7.com/pyranges/pyranges0/llms.txt Returns the 5' end (TSS) for all transcript features. This operation is performed on a PyRanges object containing transcript features. ```python import pyranges as pr gr = pr.data.ensembl_gtf()[["Source", "Feature"]] # Get TSS for all transcripts tss = gr.features.tss() print(tss) ``` -------------------------------- ### Build Sphinx Documentation Source: https://github.com/pyranges/pyranges0/blob/master/docs/developer_guide.md Navigate to the docs directory and run 'make html' to build the project's documentation locally. This allows for inspection before deployment. ```bash cd docs make html cd - ``` -------------------------------- ### Get Last Codon Sequence Source: https://github.com/pyranges/pyranges0/blob/master/docs/tutorial.md Retrieves the last three nucleotides of each CDS using `spliced_subsequence` with negative start and end arguments. This is useful for analyzing stop codons. ```python last = cds.spliced_subsequence(start=-3, by='ID') ``` -------------------------------- ### Create a toy FASTA file Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md This snippet demonstrates how to create a simple FASTA file for testing purposes. Ensure the file is created before attempting to read sequences from it. ```python with open('minigenome.fa', 'w') as fw: fw.write('>chrZ\n') fw.write('AAAGGGCCCTTTAAAGGGCCCTTTAAAGGGCCCTTT\n') ``` -------------------------------- ### Instantiate PyRanges with Multiple Chromosomes and Strands Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Create a PyRanges object by providing lists of chromosomes and strands, along with lists or tuples for start and end positions. This allows for the creation of ranges across multiple chromosomes with specified strands. ```python >>> gr = pr.PyRanges(chromosomes="chr1 chr2 chr3".split(), strands="+ - +".split(), starts=[0, 1, 2], ends=(3, 4, 5)) >>> print(gr) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int32) | (int32) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 0 | 3 | + | | chr2 | 1 | 4 | - | | chr3 | 2 | 5 | + | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. ``` -------------------------------- ### Instantiate PyRanges with DataFrame Columns Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Create a PyRanges object by passing DataFrame columns for chromosomes, starts, and ends to the constructor. This is useful when your genomic intervals are already stored in a pandas DataFrame. ```python >>> gr = pr.PyRanges(chromosomes=df.Chromosome, starts=df.Start, ends=df.End) >>> print(gr) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int32) | (int32) | |--------------+-----------+-----------| | chr1 | 100079649 | 100079674 | | chr1 | 212609534 | 212609559 | | chr1 | 223587418 | 223587443 | | chr1 | 202450161 | 202450186 | | ... | ... | ... | | chrY | 11942770 | 11942795 | | chrY | 8316773 | 8316798 | | chrY | 7463444 | 7463469 | | chrY | 7405376 | 7405401 | +--------------+-----------+-----------+ Unstranded PyRanges object has 10,000 rows and 3 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome. ``` -------------------------------- ### Download Tutorial Data Source: https://github.com/pyranges/pyranges0/blob/master/docs/tutorial.md Use curl to download the tutorial data archive. Unpack the archive using tar. ```bash curl -O https://mariottigenomicslab.bio.ub.edu/pyranges_data/pyranges_tutorial_data.tar.gz tar zxf pyranges_tutorial_data.tar.gz ``` -------------------------------- ### Create PyRanges Object from Dictionary Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_pages.md Initializes a PyRanges object from a dictionary containing chromosome, start, end, name, and strand information. Ensure data types are appropriate for PyRanges. ```python sg = pr.from_dict({"Chromosome": ["chrZ", "chrZ", "chrZ", "chrZ"], "Start": [0, 5, 10, 10], "End": [3, 8, 20, 20], "name":["a", "a", "b", "c"], "Strand":["+", "+", "+", "-"] }) ``` -------------------------------- ### Describe PyRanges DataFrame Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Use the describe() method to get a statistical summary of the DataFrame, including count, mean, standard deviation, min, max, and quartiles for numerical columns. ```python >>> gr.df.describe() ``` -------------------------------- ### Instantiate PyRanges with Single Chromosome and Lists Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Construct a PyRanges object using a single chromosome name, a list of strands, and lists/tuples for start and end positions. This method is suitable for creating ranges on a specific chromosome with defined strands. ```python >>> gr = pr.PyRanges(chromosomes="chr1", strands="+", starts=[0, 1, 2], ends=(3, 4, 5)) >>> print(gr) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int32) | (int32) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 0 | 3 | + | | chr1 | 1 | 4 | + | | chr1 | 2 | 5 | + | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. ``` -------------------------------- ### Create Conda Environment Source: https://github.com/pyranges/pyranges0/blob/master/docs/developer_guide.md Create and activate a dedicated Conda environment for PyRanges development. ```bash conda create -n prdev python pip conda activate prdev ``` -------------------------------- ### Display Genome Assembly Headers Source: https://github.com/pyranges/pyranges0/blob/master/docs/tutorial.md Use grep to display the first few header lines of a FASTA file, showing sequence names. ```bash grep ">" Dgyro_genome.fa | head ``` -------------------------------- ### Import necessary libraries Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Imports PyRanges, pandas, and StringIO for data manipulation. ```python from pyranges import PyRanges import pandas as pd from io import StringIO ``` -------------------------------- ### Use `to_bed` for Output Methods Source: https://github.com/pyranges/pyranges0/blob/master/CHANGELOG.txt Output methods now use `gr.to_bed` instead of `gr.out.bed`. The `copy_df` flag in the constructor has been removed, encouraging the use of `df.copy()` for explicit copying. ```python Use gr.to_bed for output_methods, not gr.out.bed Remove copy_df flag in constructor; using df.copy() is terser ``` -------------------------------- ### Filter Promoters with Negative Start Coordinates Source: https://github.com/pyranges/pyranges0/blob/master/docs/tutorial.md Filters the promoter intervals to find those where the 'Start' coordinate is less than 0. This indicates intervals that extended beyond the chromosome's beginning. ```pycon >>> prom[prom.Start<0] +--------------+-----------+-----------+--------------+---------------------+ | Chromosome | Start | End | Strand | ID | | (category) | (int64) | (int64) | (category) | (object) | |--------------+-----------+-----------+--------------+---------------------| | 12.1 | -129 | 171 | + | cds-DGYR_LOCUS8189 | | 18.1 | -12 | 288 | + | cds-DGYR_LOCUS10365 | ``` -------------------------------- ### Method Chaining in PyRanges Source: https://context7.com/pyranges/pyranges0/llms.txt Demonstrates method chaining for performing multiple PyRanges operations in a single expression. The `pc()` method can be used to print intermediate results and continue the chain. ```python import pyranges as pr # Load annotation, filter for CDS, add length, sort result = ( pr.read_gtf(pr.get_example_path("ensembl.gtf")) .subset(lambda x: x.Feature == "CDS") .assign("Length", lambda x: x.End - x.Start) .drop(["Source", "Score", "Frame"]) .sort("Length") ) ``` ```python # Using pc() to print intermediate results result = ( pr.data.chipseq() .subset(lambda x: x.Score == 0) .pc() # Print and continue chain .merge() .print() ) ``` ```python # Apply custom function to each chromosome/strand group custom = ( pr.data.ensembl_gtf() .subset(lambda x: x.Feature == "CDS") .apply(lambda df: df.groupby("gene_id", as_index=False).first()) ) ``` -------------------------------- ### Simple Print Methods for Chaining Source: https://github.com/pyranges/pyranges0/blob/master/CHANGELOG.txt New simple methods for printing (`p`, `mp`, `sp`, `tmp`, `rp`) have been introduced. These methods allow printing without breaking the method chain, preserving the ability to perform further operations. ```python add simple methods for printing without breaking the chain (p, mp, sp, tmp, rp) ``` -------------------------------- ### Get Transcript Sequences Grouped by ID Source: https://github.com/pyranges/pyranges0/blob/master/docs/tutorial.md Use `get_transcript_sequence` to get the full sequence of transcripts, grouped by a specified ID. Requires a genome FASTA file. Returns a pandas DataFrame. ```python seq_first = pr.get_transcript_sequence( first, group_by='ID', path='Dgyro_genome.fa' ) ``` -------------------------------- ### Filter for Canonical CDS IDs Source: https://github.com/pyranges/pyranges0/blob/master/docs/tutorial.md Use set intersection to find CDS IDs that start with ATG and end with a stop codon. This requires pre-existing sets of IDs for start and stop codons. ```python >>> clean_ids = set(is_atg_ids).intersection(set(is_stop_ids)) ``` -------------------------------- ### intersect - Get Overlapping Regions Source: https://context7.com/pyranges/pyranges0/llms.txt Returns the actual overlapping portions of intervals, not just which intervals overlap. ```APIDOC ## intersect - Get Overlapping Regions ### Description Returns the actual overlapping portions of intervals, not just which intervals overlap. ### Method `gr1.intersect(gr2, strandedness=True)` ### Parameters #### Path Parameters - **other** (PyRanges) - The PyRanges object to intersect with. #### Query Parameters - **strandedness** (bool) - Optional - If True, only consider overlaps between intervals on the same strand. Defaults to True. ### Request Example ```python import pyranges as pr gr1 = pr.from_dict({ "Chromosome": ["chr1", "chr1"], "Start": [3, 5], "End": [9, 12], "Name": ["a", "b"] }) gr2 = pr.from_dict({ "Chromosome": ["chr1", "chr1"], "Start": [1, 8], "End": [6, 15] }) # Get intersection regions intersected = gr1.intersect(gr2) print(intersected) # Without strand consideration intersected = gr1.intersect(gr2, strandedness=False) ``` ### Response #### Success Response (200) - **PyRanges object** - Contains the actual overlapping regions between `gr1` and `gr2`. ``` -------------------------------- ### pr.read_bam - Read BAM Files Source: https://context7.com/pyranges/pyranges0/llms.txt Reads BAM alignment files. Requires the `bamread` library to be installed. ```APIDOC ## pr.read_bam - Read BAM Files ### Description Reads BAM alignment files. Requires the `bamread` library to be installed. ### Method `pr.read_bam` ### Parameters #### Query Parameters - **mapq** (int) - Optional - Minimum mapping quality score to include alignments. - **filter_flag** (int) - Optional - Bitmask for filtering BAM flags. Default is 1540 (removes unmapped, failed QC, duplicates). - **required_flag** (int) - Optional - Bitmask for required BAM flags. Default is 0. - **sparse** (bool) - Optional - If False, returns full alignment information; otherwise, returns sparse representation. ### Request Example ```python import pyranges as pr # Read BAM file with default filters path = pr.get_example_path("control.bam") gr = pr.read_bam(path).sort() print(gr) # Read with custom quality filter gr = pr.read_bam("reads.bam", mapq=30) # Read with flag filtering (default filter_flag=1540 removes unmapped, failed QC, duplicates) gr = pr.read_bam("reads.bam", filter_flag=1540, required_flag=0) # Get full alignment information gr = pr.read_bam("reads.bam", sparse=False) ``` ### Response #### Success Response (200) - **PyRanges object** - Contains the genomic ranges and alignment information from the BAM file. ``` -------------------------------- ### Format and Lint Pyranges Code Source: https://github.com/pyranges/pyranges0/blob/master/docs/developer_guide.md Use Black for formatting, isort for import sorting, and Flake8 for linting. These commands ensure code consistency and quality across the project. ```bash black -l 120 pyranges/ ``` ```bash isort --profile black -l 120 tests pyranges ``` ```bash flake8 --max-line-length=120 --ignore E203,E501,W503 tests pyranges ``` -------------------------------- ### Write BigWig Files with PyRanges Source: https://context7.com/pyranges/pyranges0/llms.txt Writes score data to BigWig format. Requires the pybigwig library to be installed. ```python import pyranges as pr import numpy as np gr = pr.from_dict({ "Chromosome": ["chr1", "chr1"], "Start": [100, 500], "End": [200, 700], "Score": [1.5, 2.3] }) chromsizes = pr.data.chromsizes() pr.to_bigwig(gr, "output.bw", chromsizes) # Requires pybigwig: pip install pybigwig ``` -------------------------------- ### Rename `tile`/`window` Methods Source: https://github.com/pyranges/pyranges0/blob/master/CHANGELOG.txt The methods previously named `tiles` and `windows` have been renamed to `tile` and `window` respectively for consistency. ```python methods called tile/window instead of tiles/windows ``` -------------------------------- ### to_bed - Write BED Files Source: https://context7.com/pyranges/pyranges0/llms.txt Writes PyRanges to BED format. ```APIDOC ## to_bed - Write BED Files ### Description Writes PyRanges to BED format. ### Method N/A (Method is called on a PyRanges object) ### Endpoint N/A (This is a method of the PyRanges object) ### Parameters #### Path Parameters - **filename** (str) - Required - The name of the output BED file. ### Request Example ```python import pyranges as pr gr = pr.data.chipseq() # Write to BED gr.to_bed("output.bed") ``` ### Response No explicit return value; the function writes data to the specified BED file. ``` -------------------------------- ### Get 3' Interval Ends Source: https://context7.com/pyranges/pyranges0/llms.txt Returns single-nucleotide intervals representing the 3' ends of the original intervals. The result is strand-aware. ```python import pyranges as pr gr = pr.from_dict({ "Chromosome": ["chr1", "chr1"], "Start": [3, 5], "End": [9, 7], "Strand": ["+", "-"] }) # Get 3' ends three_prime = gr.three_end() ``` -------------------------------- ### Get 5' Interval Ends Source: https://context7.com/pyranges/pyranges0/llms.txt Returns single-nucleotide intervals representing the 5' ends of the original intervals. The result is strand-aware. ```python import pyranges as pr gr = pr.from_dict({ "Chromosome": ["chr1", "chr1"], "Start": [3, 5], "End": [9, 7], "Strand": ["+", "-"] }) # Get 5' ends (start of + strand, end of - strand) five_prime = gr.five_end() print(five_prime) ``` -------------------------------- ### Run Pyranges Unit Tests Source: https://github.com/pyranges/pyranges0/blob/master/docs/developer_guide.md Execute the unit tests for Pyranges using py.test. Ensure all tests pass without errors before proceeding. ```bash py.test tests/unit ``` -------------------------------- ### Get PyRanges Data Types Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Retrieves the data types of all columns in a PyRanges object. Useful for understanding the nature of the data in each column. ```python >>> gr.dtypes Chromosome category Start int32 End int32 Name object Score int64 Strand category new_col object another_col int64 dtype: object ``` -------------------------------- ### Get Overlapping Regions with PyRanges Source: https://context7.com/pyranges/pyranges0/llms.txt Returns the actual overlapping portions of intervals, not just which intervals overlap. Can be used with or without strand consideration. ```python import pyranges as pr gr1 = pr.from_dict({ "Chromosome": ["chr1", "chr1"], "Start": [3, 5], "End": [9, 12], "Name": ["a", "b"] }) gr2 = pr.from_dict({ "Chromosome": ["chr1", "chr1"], "Start": [1, 8], "End": [6, 15] }) # Get intersection regions intersected = gr1.intersect(gr2) print(intersected) # +--------------+-----------+-----------+------------+ # | Chromosome | Start | End | Name | # |--------------+-----------+-----------+------------| # | chr1 | 3 | 6 | a | # | chr1 | 8 | 9 | a | # | chr1 | 5 | 6 | b | # | chr1 | 8 | 12 | b | # +--------------+-----------+-----------+------------+ # Without strand consideration intersected = gr1.intersect(gr2, strandedness=False) ``` -------------------------------- ### WebSocket for Live Updates Source: https://github.com/pyranges/pyranges0/blob/master/docs/_index.rst.html Establishes a WebSocket connection to reload content when messages are received. Handles connection errors. ```javascript var ws = new WebSocket("ws://localhost:36081/ws") ws.onmessage = function(event) { console.log('updating'); document.getElementById("rst").contentWindow.location.reload(); }; ws.onerror = function(event){ console.log("Error ", event) } ``` -------------------------------- ### Add All Modified Files with Git Source: https://github.com/pyranges/pyranges0/blob/master/docs/developer_guide.md Stage all modified files for commit using 'git add .'. Use '--dry-run' first to review the list of files that will be added. ```bash git add . --dry-run ``` ```bash git add . ``` -------------------------------- ### Subset PyRanges by chromosome and position Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Selects intervals from a PyRanges object that fall within a specific chromosome and a given start and end range. ```python print(gr1["chr1", 0:5]) ``` -------------------------------- ### Get PyRanges Columns Source: https://github.com/pyranges/pyranges0/blob/master/CHANGELOG.txt The `columns` attribute returns a list of all column names present in the PyRanges object. This is helpful for inspecting the structure of the data. ```python gr.columns: return the columns in the pyranges ``` -------------------------------- ### Print PyRanges object Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Displays the contents of a PyRanges object, including chromosome, start, end, and metadata columns. The output is sorted by Chromosome and Strand. ```python print(gr1) ``` -------------------------------- ### Get Transcription End Sites (TES) Source: https://context7.com/pyranges/pyranges0/llms.txt Extracts the 3' end (TES) for all transcript features from a GTF annotation. Requires the 'Source' and 'Feature' columns. ```python import pyranges as pr gr = pr.data.ensembl_gtf()[["Source", "Feature"]] # Get TES for all transcripts tes = gr.features.tes() print(tes) ``` -------------------------------- ### to_gtf / to_gff3 - Write Annotation Files Source: https://context7.com/pyranges/pyranges0/llms.txt Writes PyRanges to GTF or GFF3 format files. ```APIDOC ## to_gtf / to_gff3 - Write Annotation Files ### Description Writes PyRanges to GTF or GFF3 format files. ### Method N/A (Methods are called on a PyRanges object) ### Endpoint N/A (These are methods of the PyRanges object) ### Parameters #### Path Parameters - **filename** (str) - Required - The name of the output file. ### Request Example ```python import pyranges as pr gr = pr.data.ensembl_gtf() # Write to GTF gr.to_gtf("output.gtf") # Write to GFF3 gr.to_gff3("output.gff3") ``` ### Response No explicit return value; the function writes data to the specified file. ``` -------------------------------- ### Extract Genomic Sequences Source: https://context7.com/pyranges/pyranges0/llms.txt Extracts DNA sequences for each interval from a FASTA file. For intervals on the minus strand, reverse-complements are automatically applied. Requires `pyfaidx` to be installed. ```python import pyranges as pr gr = pr.from_dict({ "Chromosome": ["chr1", "chr1"], "Start": [100, 200], "End": [110, 215], "Strand": ["+", "-"] }) # Get sequences (reverse-complements minus strand automatically) gr.Sequence = pr.get_sequence(gr, "genome.fa") print(gr) # Each row now has a Sequence column with the DNA sequence # Requires pyfaidx: pip install pyfaidx ``` -------------------------------- ### Create Empty PyRanges Source: https://github.com/pyranges/pyranges0/blob/master/CHANGELOG.txt An empty PyRanges object can now be created by calling the `PyRanges()` constructor without any arguments. Previously, an empty dictionary was required. ```python pr.PyRanges() returns empty PyRange # before you needed pr.PyRanges({}) ``` -------------------------------- ### Create PyRanges from Multiline String Source: https://context7.com/pyranges/pyranges0/llms.txt Use `pr.from_string` to create a PyRanges object from a whitespace-separated multiline string. This method is convenient for quick testing and documentation examples. ```python import pyranges as pr s = '''Chromosome Start End Strand Gene chr1 246719402 246719502 + TP53 chr5 15400908 15401008 + BRCA1 chr9 68366534 68366634 + EGFR chr14 79220091 79220191 + AKT1''' gr = pr.from_string(s) print(gr) ``` -------------------------------- ### Run Pyranges Property-Based Tests Source: https://github.com/pyranges/pyranges0/blob/master/docs/developer_guide.md Execute the non-compulsory property-based tests for Pyranges. These tests help uncover potential bugs by testing a wide range of inputs. ```bash py.test tests/property_based/ ``` -------------------------------- ### Clone PyRanges Fork Source: https://github.com/pyranges/pyranges0/blob/master/docs/developer_guide.md Clone your forked PyRanges repository to your local machine. ```bash mkdir pr_debug cd pr_debug git clone PASTE_GITHUB_HTTPS ``` -------------------------------- ### Print Short PyRanges Source: https://github.com/pyranges/pyranges0/blob/master/CHANGELOG.txt A fix has been implemented for printing PyRanges when the number of entries is less than a specified threshold. This ensures correct display for small datasets. ```python fix print when len(pr) < entries to print ``` -------------------------------- ### Create PyRanges from DataFrame Source: https://github.com/pyranges/pyranges0/blob/master/docs/how_to_book_old_version.md Instantiates a PyRanges object directly from a Pandas DataFrame. The DataFrame must contain 'Chromosome', 'Start', and 'End' columns, with 'Strand' being optional. ```python >>> print(pr.PyRanges(df)) ``` -------------------------------- ### Assign Column as First Argument Source: https://github.com/pyranges/pyranges0/blob/master/CHANGELOG.txt The `assign` method now takes the column name as the first argument, simplifying the syntax for assigning values to columns. ```python Make col first argument of assign ```