--- title: "14-functional-annotation" author: "Kathleen Durkin" date: "`r Sys.Date()`" always_allow_html: true output: github_document: toc: true toc_depth: 3 number_sections: true html_preview: true bookdown::html_document2: theme: cosmo toc: true toc_float: true number_sections: true code_folding: show code_download: true --- We've called DMLs and DMRs from both parents and offspring, and found overlap among those sets. Now that we have DML/DMR sets of interest, we need to know more information about where they're located in the genome, including genomic distribution (representation among introns, exons, intergenetic regions, etc.) and, for intragenic features, the function of those genes. Here I'll build a Uniprot/Swissprot lookup table of GO terms for the *C. virginica* genome (3.0) so that I can functionally annotate our features of interest I'll largely be following the [Roberts Lab Handbook's GO/GOslim workflow](https://robertslab.github.io/resources/bio-Annotation/#retrieve-go-terms-from-uniprot-using-swissprot-ids) # Setup ```{r setup, message=FALSE, warning=FALSE} # Install if needed: # if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager") # BiocManager::install(c("GSEABase", "GO.db")) library(GSEABase) library(GO.db) library(readr) library(dplyr) library(tidyr) library(purrr) library(stringr) library(tibble) # BLAST e-value cutoff evalue_cutoff <- 1e-10 ``` # Download genome/proteome NCBI proteome and GFF for C_virginica-3.0 (same assembly as `Cvirginica_v300.fa`) ```{r download-ncbi, engine='bash', eval=FALSE} # --no-clobber: skips re-downloading files already present wget \ --directory-prefix ../data \ --no-clobber \ --quiet \ https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/002/022/765/GCF_002022765.2_C_virginica-3.0/GCF_002022765.2_C_virginica-3.0_protein.faa.gz \ https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/002/022/765/GCF_002022765.2_C_virginica-3.0/GCF_002022765.2_C_virginica-3.0_genomic.gff.gz gunzip -k ../data/GCF_002022765.2_C_virginica-3.0_protein.faa.gz echo "How many proteins?" grep -c ">" ../data/GCF_002022765.2_C_virginica-3.0_protein.faa ``` SwissProt (reviewed UniProt) database. SwissProt is updated regularly, so saving the release date for reproducibility. ```{r download-swissprot, engine='bash', eval=FALSE} cd ../data/blast-db wget --quiet --no-clobber https://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/complete/uniprot_sprot.fasta.gz wget --quiet --no-clobber https://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/complete/reldate.txt cat reldate.txt ``` Rename uniprot files to specify access date and unzip ```{r rename-swissprot, engine='bash', eval=FALSE} mv ../data/blast-db/uniprot_sprot.fasta.gz ../data/blast-db/uniprot_sprot_2026_11_04.fasta.gz gunzip -k ../data/blast-db/uniprot_sprot_2026_11_04.fasta.gz ``` # BLAST against SwissProt make BLAST database ```{r make-blastdb, engine='bash', eval=FALSE} /home/shared/ncbi-blast-2.15.0+/bin/makeblastdb \ -in ../data/blast-db/uniprot_sprot_2026_11_04.fasta \ -dbtype prot \ -out ../data/blast-db/uniprot_sprot ``` `blastp` of all *C. virginica* proteins against SwissProt, keeping only the top hit per protein (`-max_target_seqs 1`). NOTE: this may take several hours with 20 threads. For `GCF_002022765.2_C_virginica-3.0_protein.faa`, took ~5 hours on Raven with 20 threads ```{r blastp, engine='bash', eval=FALSE} /home/shared/ncbi-blast-2.15.0+/bin/blastp \ -query ../data/GCF_002022765.2_C_virginica-3.0_protein.faa \ -db ../data/blast-db/uniprot_sprot \ -out ../output/14-functional-annotation/Cvirginica_protein_blastp_sprot.tab \ -evalue 1E-05 \ -num_threads 20 \ -max_target_seqs 1 \ -max_hsps 1 \ -outfmt 6 ``` check ```{r, engine='bash', eval=FALSE} head -3 ../output/14-functional-annotation/Cvirginica_protein_blastp_sprot.tab echo "How many proteins have a SwissProt hit?" cut -f1 ../output/14-functional-annotation/Cvirginica_protein_blastp_sprot.tab | sort -u | wc -l ``` # Map proteins to genes The DMR analyses use gene IDs (`LOC...`), but BLAST results are per protein (`XP_...`). Each gene can have multiple protein isoforms. The `CDS` lines in the NCBI GFF list both `protein_id=` and `gene=`, so use it to build a protien -> gene key. ```{r protein-gene-key} gff <- read_tsv("../data/GCF_002022765.2_C_virginica-3.0_genomic.gff.gz", comment = "#", col_types = "ccciicccc", col_names = c("chr", "source", "type", "start", "end", "score", "strand", "phase", "attributes")) protein_gene_key <- gff %>% filter(type == "CDS") %>% transmute(protein_id = str_extract(attributes, "(?<=protein_id=)[^;]+"), gene_id = str_extract(attributes, "(?<=gene=)[^;]+")) %>% filter(!is.na(protein_id)) %>% distinct() rm(gff); gc() # summary n_distinct(protein_gene_key$protein_id) n_distinct(protein_gene_key$gene_id) ``` Read in BLAST results and keep the best hit per gene (lowest e-value, then highest bitscore), after applying the e-value cutoff ```{r best-hit-per-gene} blast <- read_tsv("../output/14-functional-annotation/Cvirginica_protein_blastp_sprot.tab", col_types = "ccdiiiiiiidd", col_names = c("protein_id", "sseqid", "pident", "length", "mismatch", "gapopen", "qstart", "qend", "sstart", "send", "evalue", "bitscore")) # SwissProt IDs look like "sp|Q86IC9|CAMT1_DICDI", want just the accession (Q86IC9) # (depending on BLAST version/makeblastdb options, sseqid may instead just be the accession w/ version) blast <- blast %>% mutate(SPID = if_else(str_detect(sseqid, "\\|"), str_split_i(sseqid, "\\|", 2), str_remove(sseqid, "\\.\\d+$"))) gene_blast <- blast %>% filter(evalue <= evalue_cutoff) %>% inner_join(protein_gene_key, by = "protein_id") %>% group_by(gene_id) %>% arrange(evalue, desc(bitscore), .by_group = TRUE) %>% slice(1) %>% ungroup() %>% dplyr::select(gene_id, protein_id, SPID, pident, evalue, bitscore) # summary knitr::kable(tibble(n_genes_total = n_distinct(protein_gene_key$gene_id), n_genes_annotated = nrow(gene_blast), pct_annotated = 100 * n_genes_annotated / n_genes_total, n_unique_SPIDs = n_distinct(gene_blast$SPID)), digits = 1) # write newline-delimited SwissProt IDs for UniProt retrieval write_lines(unique(gene_blast$SPID), "../output/14-functional-annotation/SPIDS.txt") ``` 61% of genes have functional annotations available -- not terrible in the invert world! # Retrieve GO terms from UniProt This uses the UniProt REST API (Python script from the handbook tutorial). Requires Python >= 3, and the `requests` package. NOte: had to drop batch size from 500 to 100 (Uniprot set new limit on max batch size per query) ```{r write-uniprot-script, engine='bash', eval=FALSE} cat > ../code/14-uniprot-retrieval.py << 'EOF' import re import zlib import gzip import requests from requests.adapters import HTTPAdapter, Retry import sys import shutil import os re_next_link = re.compile(r'<(.+)>; rel="next"') retries = Retry(total=5, backoff_factor=0.25, status_forcelist=[500, 502, 503, 504]) session = requests.Session() session.mount("https://", HTTPAdapter(max_retries=retries)) def get_next_link(headers): if "Link" in headers: match = re_next_link.match(headers["Link"]) if match: return match.group(1) def get_batch(batch_url): while batch_url: response = session.get(batch_url) response.raise_for_status() total = response.headers["x-total-results"] yield response, total batch_url = get_next_link(response.headers) def process_accessions(accessions): accession_batches = [accessions[i:i+100] for i in range(0, len(accessions), 100)] all_lines = [] for accession_batch in accession_batches: accession_query = '%29%20OR%20%28accession%3A'.join(accession_batch) url = f"https://rest.uniprot.org/uniprotkb/search?compressed=true&fields=accession%2Creviewed%2Cid%2Cprotein_name%2Cgene_names%2Corganism_name%2Clength%2Cgo_p%2Cgo_c%2Cgo%2Cgo_f%2Cgo_id&format=tsv&query=%28%28accession%3A{accession_query}%29%29&size=500" progress = 0 lines = [] for batch, total in get_batch(url): # Decompress each batch as we want to extract the header decompressed = zlib.decompress(batch.content, 16 + zlib.MAX_WBITS) batch_lines = [line for line in decompressed.decode("utf-8").split("\n") if line] if not progress: # First line so print TSV header lines = [batch_lines[0]] lines += batch_lines[1:] progress = len(lines) - 1 print(f"{progress} / {total}") all_lines.extend(lines) return all_lines def main(accession_file, output_dir): with open(accession_file, 'r') as f: accessions = f.read().splitlines() retrieved_data = process_accessions(accessions) # Write to a temporary gzip file temp_filename = "uniprot-retrieval-temp.tsv.gz" with gzip.open(temp_filename, "wt", encoding="utf-8") as f: f.write('\n'.join(retrieved_data)) # Determine the full output path output_path = os.path.join(output_dir, "uniprot-retrieval.tsv.gz") # Merge the temporary file with the existing output file (if it exists) try: with gzip.open(output_path, "rb") as f_existing, open(temp_filename, "rb") as f_temp: with gzip.open("uniprot-retrieval-merged.tsv.gz", "wb") as f_merged: shutil.copyfileobj(f_existing, f_merged) shutil.copyfileobj(f_temp, f_merged) # Replace the original output file with the merged file shutil.move("uniprot-retrieval-merged.tsv.gz", output_path) except FileNotFoundError: # If the existing output file doesn't exist, rename the temporary file shutil.move(temp_filename, output_path) if __name__ == '__main__': if len(sys.argv) < 3: print("Usage: python uniprot-retrieval.py ") sys.exit(1) accession_file = sys.argv[1] output_dir = sys.argv[2] if not os.path.exists(output_dir): os.makedirs(output_dir) main(accession_file, output_dir) EOF ``` ```{r run-uniprot-retrieval, engine='bash', eval=FALSE} # remove existing output (script appends rather than overwrites) rm -f ../output/14-functional-annotation/uniprot-retrieval.tsv.gz python3 ../code/14-uniprot-retrieval.py \ ../output/14-functional-annotation/SPIDS.txt \ ../output/14-functional-annotation/ gunzip -f ../output/14-functional-annotation/uniprot-retrieval.tsv.gz head -3 ../output/14-functional-annotation/uniprot-retrieval.tsv ``` Read in UniProt results. Since each 100-accession batch is written with its own header line, drop the repeated header rows. ```{r read-uniprot} uniprot <- read_tsv("../output/14-functional-annotation/uniprot-retrieval.tsv", col_types = cols(.default = "c")) %>% filter(Entry != "Entry") %>% distinct() %>% dplyr::select(SPID = Entry, entry_name = `Entry Name`, protein_names = `Protein names`, gene_names = `Gene Names`, organism = Organism, GO_BP = `Gene Ontology (biological process)`, GO_CC = `Gene Ontology (cellular component)`, GO_MF = `Gene Ontology (molecular function)`, GO_IDs = `Gene Ontology IDs`) # how many SPIDs were retrieved, and how many have GO terms? knitr::kable(tibble(n_SPIDs_queried = n_distinct(gene_blast$SPID), n_SPIDs_retrieved = nrow(uniprot), n_with_GO = sum(!is.na(uniprot$GO_IDs)))) ``` # Map GO IDs to GOslims Join GO IDs to genes, clean whitespace around ";", and drop genes without GO IDs ```{r gene-GO} gene_GO <- gene_blast %>% left_join(uniprot, by = "SPID") %>% mutate(GO_IDs = str_replace_all(GO_IDs, "\\s*;\\s*", ";")) %>% filter(!is.na(GO_IDs) & GO_IDs != "") %>% dplyr::select(gene_id, GO_IDs) # flatten so there's one GO ID per gene per row flat_gene_GO <- gene_GO %>% separate_rows(GO_IDs, sep = ";") # vector of unique GO IDs go_ids <- unique(flat_gene_GO$GO_IDs) length(go_ids) ``` Download the generic GOslim OBO file. The handbook version saves this into the GSEABase package directory, but I'll save it with the other outputs instead (so it's versioned alongside this analysis) and pass the path directly to `getOBOCollection()`. ```{r download-goslim-obo} goslims_url <- "http://current.geneontology.org/ontology/subsets/goslim_generic.obo" goslims_obo <- "../output/14-functional-annotation/goslim_generic.obo" if (!file.exists(goslims_obo)) download.file(url = goslims_url, destfile = goslims_obo) ``` Create a GOCollection of our GO IDs, then retrieve Biological Process (BP) GOslims associated with them ```{r retrieve-BP-GOslims} my_collection <- GOCollection(go_ids) slim <- getOBOCollection(goslims_obo) slimdf <- goSlim(my_collection, slim, "BP", verbose = FALSE) str(slimdf) ``` Map GO IDs to GOslims. `GOBPOFFSPRING` gives all child terms of each GOslim, so intersect with our GO IDs to get which of our GO IDs fall under each GOslim. A GO ID that *is* itself a GOslim term isn't its own offspring, so add those self-matches back in too. (The mapping steps come from [this Bioconductor forum response](https://support.bioconductor.org/p/128407/#128409), via the handbook.) ```{r map-GO-to-GOslims} # all offspring GO IDs of each GOslim gomap <- as.list(GOBPOFFSPRING[rownames(slimdf)]) # keep only our GO IDs, and add any self-matching GOslim IDs mapped <- map2(rownames(slimdf), gomap, ~ union(intersect(.y, ids(my_collection)), if (.x %in% go_ids) .x else character(0))) slimdf$GO_IDs <- map_chr(mapped, ~ paste(.x, collapse = ";")) # flatten so each row is a single GO ID with its corresponding GOslim # (rownames_to_column needed to retain GOslim IDs) GO_to_slim <- slimdf %>% rownames_to_column("GOslim") %>% separate_rows(GO_IDs, sep = ";") %>% filter(!is.na(GO_IDs) & GO_IDs != "") %>% dplyr::select(GO_IDs, GOslim, GOslim_term = Term) str(GO_to_slim) ``` GOslim counts (# of our GO IDs mapping to each GOslim), sorted ```{r slim-counts} slimdf %>% arrange(desc(Count)) %>% dplyr::select(Term, Count, Percent) %>% head(20) %>% knitr::kable(digits = 1) ``` # Build gene annotation lookup table Join GOslims back to genes. A gene can map to multiple GOslims (through one or more of its GO IDs), so collapse to one row per gene with ";"-delimited GOslim IDs/terms. ```{r gene-GOslim} gene_slim <- flat_gene_GO %>% inner_join(GO_to_slim, by = "GO_IDs", relationship = "many-to-many") %>% distinct(gene_id, GOslim, GOslim_term) %>% group_by(gene_id) %>% summarise(GOslim_BP_IDs = paste(GOslim, collapse = ";"), GOslim_BP_terms = paste(GOslim_term, collapse = ";"), .groups = "drop") ``` Combine BLAST, UniProt, and GOslim info ```{r lookup-table} gene_annot <- gene_blast %>% left_join(uniprot, by = "SPID") %>% mutate(GO_IDs = str_replace_all(GO_IDs, "\\s*;\\s*", ";")) %>% left_join(gene_slim, by = "gene_id") # summary knitr::kable(tibble(n_genes_annotated = nrow(gene_annot), n_with_GO = sum(!is.na(gene_annot$GO_IDs) & gene_annot$GO_IDs != ""), n_with_GOslim_BP = sum(!is.na(gene_annot$GOslim_BP_IDs)))) head(gene_annot) ``` # Save outputs ```{r} write_tsv(gene_annot, "../output/14-functional-annotation/Cvirginica_gene_annotation.tsv", na = "") ``` Next steps: annotate DMRs (`13-DMR-overlap-CTmask` overlaps and per-stage/sex DMRs from `10.01`/`10.11`) with overlapping/nearby genes using the GFF, then join to this lookup table by `gene_id`.