14-functional-annotation ================ Kathleen Durkin 2026-11-11 - [1 Setup](#1-setup) - [2 Download genome/proteome](#2-download-genomeproteome) - [3 BLAST against SwissProt](#3-blast-against-swissprot) - [4 Map proteins to genes](#4-map-proteins-to-genes) - [5 Retrieve GO terms from UniProt](#5-retrieve-go-terms-from-uniprot) - [6 Map GO IDs to GOslims](#6-map-go-ids-to-goslims) - [7 Build gene annotation lookup table](#7-build-gene-annotation-lookup-table) - [8 Save outputs](#8-save-outputs) 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) # 1 Setup ``` r # 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 ``` # 2 Download genome/proteome NCBI proteome and GFF for C_virginica-3.0 (same assembly as `Cvirginica_v300.fa`) ``` bash # --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. ``` bash 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 ``` bash 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 ``` # 3 BLAST against SwissProt make BLAST database ``` bash /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 ``` bash /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 ``` bash 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 ``` # 4 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 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() ``` ## used (Mb) gc trigger (Mb) max used (Mb) ## Ncells 4068934 217.4 9168215 489.7 6891758 368.1 ## Vcells 8050315 61.5 54039028 412.3 62000794 473.1 ``` r # summary n_distinct(protein_gene_key$protein_id) ``` ## [1] 60213 ``` r n_distinct(protein_gene_key$gene_id) ``` ## [1] 34608 Read in BLAST results and keep the best hit per gene (lowest e-value, then highest bitscore), after applying the e-value cutoff ``` r 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) ``` | n_genes_total | n_genes_annotated | pct_annotated | n_unique_SPIDs | |--------------:|------------------:|--------------:|---------------:| | 34608 | 21123 | 61 | 11063 | ``` r # 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! # 5 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) ``` bash 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 ``` ``` bash # 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 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)))) ``` | n_SPIDs_queried | n_SPIDs_retrieved | n_with_GO | |----------------:|------------------:|----------:| | 11063 | 11063 | 10784 | # 6 Map GO IDs to GOslims Join GO IDs to genes, clean whitespace around “;”, and drop genes without GO IDs ``` r 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) ``` ## [1] 15088 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 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 my_collection <- GOCollection(go_ids) slim <- getOBOCollection(goslims_obo) slimdf <- goSlim(my_collection, slim, "BP", verbose = FALSE) str(slimdf) ``` ## 'data.frame': 72 obs. of 3 variables: ## $ Count : int 112 28 21 550 82 107 32 5 104 60 ... ## $ Percent: num 1.148 0.287 0.215 5.636 0.84 ... ## $ Term : chr "mitotic cell cycle" "cytokinesis" "cytoplasmic translation" "immune system process" ... 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 # 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) ``` ## tibble [9,759 × 3] (S3: tbl_df/tbl/data.frame) ## $ GO_IDs : chr [1:9759] "GO:0000022" "GO:0000070" "GO:0000082" "GO:0000086" ... ## $ GOslim : chr [1:9759] "GO:0000278" "GO:0000278" "GO:0000278" "GO:0000278" ... ## $ GOslim_term: chr [1:9759] "mitotic cell cycle" "mitotic cell cycle" "mitotic cell cycle" "mitotic cell cycle" ... GOslim counts (# of our GO IDs mapping to each GOslim), sorted ``` r slimdf %>% arrange(desc(Count)) %>% dplyr::select(Term, Count, Percent) %>% head(20) %>% knitr::kable(digits = 1) ``` | | Term | Count | Percent | |--------------|:-------------------------------------------------------|------:|--------:| | | anatomical structure development | 2068 | 21.2 | | | cell differentiation | 914 | 9.4 | | | signaling | 909 | 9.3 | | | immune system process | 550 | 5.6 | | | lipid metabolic process | 323 | 3.3 | | | reproductive process | 310 | 3.2 | | | carbohydrate derivative metabolic process | 293 | 3.0 | | | transmembrane transport | 239 | 2.4 | | | nucleobase-containing small molecule metabolic process | 234 | 2.4 | | | vesicle-mediated transport | 228 | 2.3 | | | cell motility | 196 | 2.0 | | | programmed cell death | 194 | 2.0 | | | cytoskeleton organization | 190 | 1.9 | | | protein-containing complex assembly | 160 | 1.6 | | | membrane organization | 154 | 1.6 | | | cell junction organization | 122 | 1.3 | | | cell adhesion | 118 | 1.2 | | | mitotic cell cycle | 112 | 1.1 | | | circulatory system process | 107 | 1.1 | | | carbohydrate metabolic process | 104 | 1.1 | # 7 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_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 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)))) ``` | n_genes_annotated | n_with_GO | n_with_GOslim_BP | |------------------:|----------:|-----------------:| | 21123 | 20516 | 16372 | ``` r head(gene_annot) ``` ## # A tibble: 6 × 16 ## gene_id protein_id SPID pident evalue bitscore entry_name protein_names ## ## 1 COX1 YP_254649… P127… 61.4 0 603 COX1_PARLI Cytochrome c… ## 2 COX2 YP_254652… P506… 45.6 2.53e- 68 212 COX2_AEDAE Cytochrome c… ## 3 COX3 YP_254650… O476… 47.8 3.49e- 72 224 COX3_DAMLU Cytochrome c… ## 4 CYTB YP_254651… Q9TA… 46.0 4.81e-109 328 CYB_CORCD Cytochrome b… ## 5 LOC111099… XP_022313… A7T1… 23.4 8.74e- 94 339 TMP2L_NEM… Transient re… ## 6 LOC111099… XP_022286… Q9Z2… 43.7 6.84e-168 494 S23A1_MOU… Solute carri… ## # ℹ 8 more variables: gene_names , organism , GO_BP , ## # GO_CC , GO_MF , GO_IDs , GOslim_BP_IDs , ## # GOslim_BP_terms # 8 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`.