BioOcto / bioagent-bench /UNCOMMITTED_CHANGES.patch
czty's picture
BioOcto code and data release (snapshot 2026-11-27, resumed) (part 35)
d535b11 verified
Raw History Blame Contribute Delete
125 kB
diff --git a/tasks/alzheimer-mouse/environment.yml b/tasks/alzheimer-mouse/environment.yml deleted file mode 100644 index 5d78096..0000000 --- a/tasks/alzheimer-mouse/environment.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: alzheimer-analysis -channels: - - bioconda - - conda-forge - - defaults -dependencies: - - pandas - - numpy - - mygene - - scipy - - statsmodels - - requests - - networkx - - pip - - pip: - - gseapy diff --git a/tasks/alzheimer-mouse/run_analysis.py b/tasks/alzheimer-mouse/run_analysis.py deleted file mode 100644 index ee8ea99..0000000 --- a/tasks/alzheimer-mouse/run_analysis.py +++ /dev/null @@ -1,252 +0,0 @@ -import os -import pandas as pd -import numpy as np -import mygene -from scipy.stats import ttest_ind -from statsmodels.stats.multitest import multipletests -import gseapy as gp -import requests -import networkx as nx -from io import StringIO -import logging - - -def setup_logging(): - """Configure logging settings""" - os.makedirs("outputs", exist_ok=True) - logging.basicConfig( - level=logging.INFO, - format='%(asctime)s - %(levelname)s - %(message)s', - handlers=[ - logging.FileHandler('outputs/analysis.log'), - logging.StreamHandler() - ] - ) - -def annotate_genes(df): - logging.info(f"Starting gene annotation for {len(df)} genes") - mg = mygene.MyGeneInfo() - ensembl_ids = df.index.str.split(".").str[0].tolist() - gene_info = mg.querymany(ensembl_ids, scopes='ensembl.gene', fields='symbol', species='mouse') - gene_df = pd.DataFrame(gene_info).dropna(subset=['symbol']).drop_duplicates(subset='query') - df.index = ensembl_ids - df['Gene_Name'] = df.index.map(gene_df.set_index('query')['symbol']) - cols = ['Gene_Name'] + [col for col in df.columns if col != 'Gene_Name'] - logging.info(f"Completed gene annotation. Found symbols for {len(gene_df)} genes") - return df[cols] - -def filter_normalize(data, min_cpm=0.7, min_samples=2): - logging.info(f"Starting filtering and normalization. Initial genes: {len(data)}") - gene_names = data.iloc[:, 0] - raw_counts = data.iloc[:, 1:] - cpm = raw_counts.apply(lambda x: (x / x.sum()) * 1e6, axis=0) - mask = (cpm > min_cpm).sum(axis=1) >= min_samples - filtered_counts = raw_counts[mask] - filtered_gene_names = gene_names[mask] - logging.info(f"After filtering: {len(filtered_counts)} genes remaining") - - geometric_means = filtered_counts.apply(lambda row: np.exp(np.log(row[row > 0]).mean()), axis=1) - size_factors = filtered_counts.div(geometric_means, axis=0).median(axis=0) - normalized_counts = filtered_counts.div(size_factors, axis=1) - logging.info("Normalization completed") - return pd.concat([filtered_gene_names, normalized_counts], axis=1) - -def perform_dea(df, treated_columns, control_columns): - logging.info(f"Starting differential expression analysis with {len(df)} genes") - logging.info(f"Treatment samples: {len(treated_columns)}, Control samples: {len(control_columns)}") - - results = [] - for gene in df.index: - treated = pd.to_numeric(df.loc[gene, treated_columns], errors='coerce').dropna() - control = pd.to_numeric(df.loc[gene, control_columns], errors='coerce').dropna() - if treated.empty or control.empty: - continue - log2fc = np.log2((treated.mean() + 1) / (control.mean() + 1)) - t_stat, p_val = ttest_ind(treated, control) - results.append({ - "gene": gene, - "Gene_Name": df.loc[gene, "Gene_Name"], - "log2fc": log2fc, - "t_stat": t_stat, - "p_val": p_val - }) - - results_df = pd.DataFrame(results) - results_df['p_val'] = pd.to_numeric(results_df['p_val'], errors='coerce') - results_df = results_df.dropna(subset=['p_val']) - results_df['p_adj'] = multipletests(results_df['p_val'], method='fdr_bh')[1] - results_df['abs_log2fc'] = results_df['log2fc'].abs() - - final_results = results_df[(results_df['p_adj'] < 0.075) & (results_df['abs_log2fc'] > 0.75)] - logging.info(f"DEA completed. Found {len(final_results)} significant genes") - return final_results - -def fetch_string_ppi(gene_list, species='10090'): - logging.info(f"Fetching STRING PPI data for {len(gene_list)} genes") - base_url = "https://string-db.org/api/tsv/network" - genes = "\n".join(gene_list) - params = {'identifiers': genes, 'species': species, 'limit': 1} - try: - response = requests.post(base_url, data=params) - if response.status_code == 200: - logging.info("Successfully retrieved PPI data from STRING") - return response.text - else: - logging.error(f"Failed to fetch PPI data. Status code: {response.status_code}") - return None - except Exception as e: - logging.error(f"Error fetching PPI data: {str(e)}") - return None - - -def compare_pathway_enrichment(kegg_files, output_file="results/pathway_comparison.csv"): - """ - Compare pathway enrichment across different mouse models. - Only outputs pathways that are shared between all models with their respective p-values. - - Args: - kegg_files: Dict of {model_name: kegg_file_path} - output_file: Path to save comparison CSV - """ - model_pathways = {} - all_pathways = set() - - # Load pathway data for each model - for model, file in kegg_files.items(): - df = pd.read_csv(file) - model_pathways[model] = df - all_pathways.update(df['Term'].values) - - # Create comparison matrix - results = [] - for pathway in all_pathways: - is_shared = True - row = {'Pathway': pathway} - - # Add p-value for each model - for model, df in model_pathways.items(): - pathway_data = df[df['Term'] == pathway] - if not pathway_data.empty: - row[f"{model}_pvalue"] = pathway_data['P-value'].iloc[0] - else: - is_shared = False - break - - # Only add pathways that are present in all models - if is_shared: - results.append(row) - - # Create DataFrame and sort by minimum p-value across models - pathway_df = pd.DataFrame(results) - - if not pathway_df.empty: - # Calculate minimum p-value for sorting - pvalue_cols = [f"{model}_pvalue" for model in model_pathways.keys()] - pathway_df['min_pvalue'] = pathway_df[pvalue_cols].min(axis=1) - - # Sort by minimum p-value and remove the temporary column - pathway_df = pathway_df.sort_values('min_pvalue') - pathway_df = pathway_df.drop('min_pvalue', axis=1) - - # Reorder columns to put Pathway first - cols = ['Pathway'] + [f"{model}_pvalue" for model in model_pathways.keys()] - pathway_df = pathway_df[cols] - - # Save to CSV - pathway_df.to_csv(output_file, index=False) - logging.info(f"Found {len(pathway_df)} pathways shared across all models") - logging.info(f"Pathway comparison saved to {output_file}") - - # Log top 5 most significant shared pathways - logging.info("\nTop 5 most significant shared pathways:") - for _, row in pathway_df.head().iterrows(): - pathway = row['Pathway'] - pvals = [f"{row[f'{model}_pvalue']:.2e}" for model in model_pathways.keys()] - logging.info(f"{pathway}: {', '.join(pvals)}") - else: - logging.info("No pathways found that are shared across all models") - - -def main(): - setup_logging() - logging.info("Starting Alzheimer's mouse model analysis") - - os.makedirs("outputs", exist_ok=True) - - # 1. Load and annotate datasets - logging.info("Loading 5xFAD dataset") - countlist_5xFAD = pd.read_csv("./data/GSE168137_countList.txt", sep="\t", index_col=0) - countlist_5xFAD = countlist_5xFAD.loc[:, countlist_5xFAD.columns.str.contains('cortex_8mo')] - countlist_5xFAD.columns = [ - "5xFAD_cortex_8mon_Female_295", "5xFAD_cortex_8mon_Female_312", "5xFAD_cortex_8mon_Female_339", "5xFAD_cortex_8mon_Female_341", "5xFAD_cortex_8mon_Female_342", - "5xFAD_cortex_8mon_Male_299", "5xFAD_cortex_8mon_Male_300", "5xFAD_cortex_8mon_Male_307", "5xFAD_cortex_8mon_Male_387", "5xFAD_cortex_8mon_Male_390", - "BL6_cortex_8mon_Female_322", "BL6_cortex_8mon_Female_338", "BL6_cortex_8mon_Female_340", "BL6_cortex_8mon_Female_348", "BL6_cortex_8mon_Female_351", - "BL6_cortex_8mon_Male_389", "BL6_cortex_8mon_Male_396", "BL6_cortex_8mon_Male_399", "BL6_cortex_8mon_Male_410", "BL6_cortex_8mon_Male_412" - ] - countlist_5xFAD = annotate_genes(countlist_5xFAD) - - logging.info("Loading 3xTG_AD dataset") - countlist_3xTG_AD = pd.read_csv("./data/GSE161904_Raw_gene_counts_cortex.txt", sep="\t", index_col=0) - countlist_3xTG_AD = countlist_3xTG_AD.loc[:, countlist_3xTG_AD.columns.str.contains('G3')] - countlist_3xTG_AD.columns = ['3xTG_AD_Cortex_R1', '3xTG_AD_Cortex_R3', '3xTG_AD_Cortex_R4', 'WT_Cortex_R10', 'WT_Cortex_R17', 'WT_Cortex_R9'] - countlist_3xTG_AD = annotate_genes(countlist_3xTG_AD) - - logging.info("Loading PS3O1S dataset") - DEA_PS3O1S = pd.read_csv("./data/DEA_PS3O1S.csv") - - # 2. Normalize - logging.info("Starting data normalization") - norm_5xFAD = filter_normalize(countlist_5xFAD, min_cpm=0.7) - norm_3xTG_AD = filter_normalize(countlist_3xTG_AD, min_cpm=0.7, min_samples=1) - - # 3. DEA - logging.info("Performing differential expression analysis") - deg_5xFAD = perform_dea(norm_5xFAD, - treated_columns=[col for col in norm_5xFAD.columns if "5xFAD" in col], - control_columns=[col for col in norm_5xFAD.columns if "BL6" in col]) - deg_3xTG_AD = perform_dea(norm_3xTG_AD, - treated_columns=['3xTG_AD_Cortex_R1','3xTG_AD_Cortex_R3','3xTG_AD_Cortex_R4'], - control_columns=['WT_Cortex_R10','WT_Cortex_R17','WT_Cortex_R9']) - DEA_PS3O1S['abs_log2fc'] = DEA_PS3O1S['log2fc'].abs() - deg_PS3O1S = DEA_PS3O1S[(DEA_PS3O1S['abs_log2fc'] > 0.75) & (DEA_PS3O1S['pval'] < 0.075)] - - deg_5xFAD.to_csv("outputs/DEG_5xFAD.csv", index=False) - deg_3xTG_AD.to_csv("outputs/DEG_3xTG_AD.csv", index=False) - deg_PS3O1S.to_csv("outputs/DEG_PS3O1S.csv", index=False) - - # 4. GO Enrichment - logging.info("Starting GO enrichment analysis") - for label, gene_list in zip( - ["5xFAD", "3xTG_AD", "PS3O1S"], - [deg_5xFAD['Gene_Name'], deg_3xTG_AD['Gene_Name'], deg_PS3O1S['gene_name']] - ): - logging.info(f"Running GO enrichment for {label}") - try: - enr = gp.enrichr(gene_list=gene_list.dropna().tolist(), gene_sets=["GO_Biological_Process_2018"], organism='mouse') - enr.results.to_csv(f"outputs/GO_BP_{label}.csv", index=False) - except Exception as e: - logging.error(f"Error in GO enrichment for {label}: {str(e)}") - - # 5. Pathway Enrichment - for label, gene_list in zip( - ["5xFAD", "3xTG_AD", "PS3O1S"], - [deg_5xFAD['Gene_Name'], deg_3xTG_AD['Gene_Name'], deg_PS3O1S['gene_name']] - ): - enr = gp.enrichr(gene_list=gene_list.dropna().tolist(), gene_sets=["KEGG_2016"], organism='mouse') - enr.results.to_csv(f"outputs/KEGG_{label}.csv", index=False) - - - # Prepare file paths for pathway analysis - kegg_files = { - '5xFAD': 'outputs/KEGG_5xFAD.csv', - '3xTG_AD': 'outputs/KEGG_3xTG_AD.csv', - 'PS3O1S': 'outputs/KEGG_PS3O1S.csv' - } - - # Run pathway comparison - compare_pathway_enrichment(kegg_files) - - logging.info("Analysis complete! All outputs and results saved to the appropriate directory") - -if __name__ == "__main__": - main() diff --git a/tasks/alzheimer-mouse/run_script.sh b/tasks/alzheimer-mouse/run_script.sh deleted file mode 100755 index ecf872e..0000000 --- a/tasks/alzheimer-mouse/run_script.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash - -source ~/miniforge3/etc/profile.d/conda.sh -source ~/miniforge3/etc/profile.d/mamba.sh - -mamba env create -f environment.yml || true - -mamba activate alzheimer-analysis - -mkdir -p ./data -mkdir -p ./outputs -mkdir -p ./results - -wget -O ./data/alzheimer_mouse_data.tar.gz "https://osf.io/download/6833661cfe08c0f335d6a716/" -tar -xzf ./data/alzheimer_mouse_data.tar.gz -C ./data --strip-components=1 - -# Remove the tar.gz file to save space -rm ./data/alzheimer_mouse_data.tar.gz - -python run_analysis.py \ No newline at end of file diff --git a/tasks/comparative-geno/Dockerfile b/tasks/comparative-geno/Dockerfile deleted file mode 100644 index 2b04f1c..0000000 --- a/tasks/comparative-geno/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM condaforge/mambaforge:24.9.2-0 - -# Set working directory -WORKDIR /app - -# Copy your scripts and environment files -COPY run_script.sh /app/ -COPY run_comparative.R /app/ -COPY environment.yml /app/ - -# Initialize mamba for shell usage and create environments from yml files -RUN mamba init bash && \ - . ~/.bashrc && \ - # Create the main environment from environment.yml - mamba env create -f environment.yml && \ - # Make script executable - chmod +x /app/run_script.sh - -# Set bash as the shell and ensure mamba is available -SHELL ["/bin/bash", "--login", "-c"] - - -CMD ["mamba", "run", "-n", "comparative", "/app/run_script.sh"] \ No newline at end of file diff --git a/tasks/comparative-geno/environment.yml b/tasks/comparative-geno/environment.yml deleted file mode 100644 index 10649ef..0000000 --- a/tasks/comparative-geno/environment.yml +++ /dev/null @@ -1,11 +0,0 @@ -name: comparative -channels: - - bioconda - - conda-forge - - defaults -dependencies: - - r-base - - r-biocmanager - - bioconductor-decipher - - bioconductor-synextend - - r-igraph \ No newline at end of file diff --git a/tasks/comparative-geno/run_comparative.R b/tasks/comparative-geno/run_comparative.R deleted file mode 100644 index 374dc8f..0000000 --- a/tasks/comparative-geno/run_comparative.R +++ /dev/null @@ -1,575 +0,0 @@ -library(DECIPHER) -library(SynExtend) - -# Enable debugging output -cat("=== COMPARATIVE GENOMICS ANALYSIS DEBUG MODE ===\n") -cat("Script started at:", as.character(Sys.time()), "\n\n") - -# Set working directory and check data -setwd('.') -COGExampleDir <- 'data' - -cat("Step 1: Checking data directory...\n") -if (!dir.exists(COGExampleDir)) { - stop("ERROR: Data directory '", COGExampleDir, "' does not exist!") -} - -cat("Data directory found:", COGExampleDir, "\n") -cat("Creating temporary database...\n") -DBPATH <- tempfile() -cat("Database path:", DBPATH, "\n") - -cat("\nStep 2: Finding genome directories...\n") -genomedirs <- list.files(COGExampleDir, full.names = TRUE) -genomedirs <- genomedirs[grep('json', genomedirs, fixed=T, invert=T)] -genomedirs <- genomedirs[grep('RData', genomedirs, fixed=T, invert=T)] -cat("Found", length(genomedirs), "genome directories:\n") -for (i in seq_along(genomedirs)) { - cat(" ", i, ":", basename(genomedirs[i]), "\n") -} - -if (length(genomedirs) == 0) { - stop("ERROR: No genome directories found!") -} - -cat("\nStep 3: Processing genome files and building database...\n") -GeneCalls <- vector('list', length=length(genomedirs)) - -for (i in seq_along(genomedirs)){ - cat("Processing genome", i, "of", length(genomedirs), ":", basename(genomedirs[i]), "\n") - - tryCatch({ - subfiles <- list.files(genomedirs[i], full.names = TRUE) - cat(" Found", length(subfiles), "files in directory\n") - - fna_file <- subfiles[which(grepl('.*fna$', subfiles))] - gff_file <- subfiles[which(grepl('.*gff$', subfiles))] - - if (length(fna_file) == 0) { - stop("No .fna file found in ", genomedirs[i]) - } - if (length(gff_file) == 0) { - stop("No .gff file found in ", genomedirs[i]) - } - - cat(" FNA file:", basename(fna_file), "\n") - cat(" GFF file:", basename(gff_file), "\n") - - cat(" Adding sequences to database...\n") - Seqs2DB(seqs = fna_file, - type = "FASTA", - dbFile = DBPATH, - identifier = as.character(i), - verbose = TRUE) - - cat(" Parsing GFF file...\n") - GeneCalls[[i]] <- gffToDataFrame(GFF = gff_file, - Verbose = TRUE) - cat(" Found", nrow(GeneCalls[[i]]), "gene calls\n") - - }, error = function(e) { - cat("ERROR processing genome", i, ":", e$message, "\n") - stop("Failed at genome processing step") - }) -} -names(GeneCalls) <- seq_along(GeneCalls) -cat("Successfully processed all genomes!\n") - -cat("\nStep 4: Finding synteny...\n") -tryCatch({ - Syn <- FindSynteny(dbFile = DBPATH, - verbose = TRUE) - cat("Synteny analysis completed successfully\n") -}, error = function(e) { - cat("ERROR in FindSynteny:", e$message, "\n") - stop("Failed at synteny step") -}) - -cat("\nStep 5: Finding nucleotide overlaps...\n") -tryCatch({ - Overlaps <- NucleotideOverlap(SyntenyObject = Syn, - GeneCalls = GeneCalls, - Verbose = TRUE) - cat("Nucleotide overlap analysis completed successfully\n") -}, error = function(e) { - cat("ERROR in NucleotideOverlap:", e$message, "\n") - stop("Failed at nucleotide overlap step") -}) - -cat("\nStep 6: Generating pair summaries...\n") -tryCatch({ - Pairs <- PairSummaries(SyntenyLinks = Overlaps, - GeneCalls = GeneCalls, - DBPATH = DBPATH, - PIDs = TRUE, - Score = TRUE, - Verbose = TRUE, - processors=NULL) - - P02 <- BlockExpansion(Pairs = Pairs, - DBPATH = DBPATH, - Verbose = TRUE, - NewPairsOnly = FALSE) - P03 <- BlockReconciliation(Pairs = P02, - PIDThreshold = 0.75, - SCOREThreshold = 200, - Verbose = TRUE) - Pairs <- P03[P03$PID > 0.4, ] - - cat("Pair summaries completed successfully, found", nrow(Pairs), "pairs\n") -}, error = function(e) { - cat("ERROR in PairSummaries:", e$message, "\n") - stop("Failed at pair summaries step") -}) - -cat("\nStep 7: Finding COGs (Clusters of Orthologous Groups)...\n") -tryCatch({ - COGSets <- DisjointSet(Pairs = Pairs, - Verbose = TRUE) - cat("Found", length(COGSets), "COG sets\n") - - # Print size distribution - sizes <- lengths(COGSets) - cat("COG size distribution:\n") - cat(" Min:", min(sizes), "Max:", max(sizes), "Mean:", round(mean(sizes), 2), "\n") - cat(" COGs with ≥5 members:", sum(sizes >= 5), "\n") -}, error = function(e) { - cat("ERROR in DisjointSet:", e$message, "\n") - stop("Failed at COG finding step") -}) - -cat("\nStep 8: Extracting sequences for large COGs...\n") -tryCatch({ - # Extract sequences for COGs with at least 5 orthologs - largeCOGs <- COGSets[lengths(COGSets) >= 5] - cat("Extracting sequences for", length(largeCOGs), "COGs with ≥5 members\n") - - Sequences <- ExtractBy(x = Pairs, - y = DBPATH, - z = largeCOGs, - Verbose = TRUE) - cat("Successfully extracted sequences for", length(Sequences), "COGs\n") -}, error = function(e) { - cat("ERROR in ExtractBy:", e$message, "\n") - stop("Failed at sequence extraction step") -}) - -cat("\nStep 9: Matching COG sets with sequences...\n") -tryCatch({ - # These come back in different orders, so let's match them up - allnames <- lapply(Sequences, names) - COGMapping <- sapply(COGSets, function(x) { - which(sapply(allnames, function(y) setequal(x, y))) - }) - COGMapping <- COGMapping[sapply(COGMapping, function(x) length(x) > 0)] - - MatchedCOGSets <- COGSets[names(COGMapping)] - MatchedSequences <- Sequences[unlist(COGMapping)] - names(MatchedSequences) <- names(COGMapping) - - cat("Successfully matched", length(MatchedSequences), "COG sets with sequences\n") -}, error = function(e) { - cat("ERROR in COG matching:", e$message, "\n") - stop("Failed at COG matching step") -}) - -cat("\nStep 9.1: Saving intermediate results (before filtering)...\n") -tryCatch({ - # Create outputs directory if it doesn't exist - if (!dir.exists("./outputs")) { - dir.create("./outputs", recursive = TRUE) - } - - # Save all intermediate results up to this point (before filtering) - save(GeneCalls, Syn, Overlaps, Pairs, COGSets, MatchedCOGSets, - MatchedSequences, Sequences, genomedirs, - file = "./outputs/intermediate_step9.RData") - - cat("Successfully saved intermediate results to ./outputs/intermediate_step9.RData\n") - cat("You can resume from this point by loading this file if needed.\n") -}, error = function(e) { - cat("ERROR saving intermediate results:", e$message, "\n") - stop("Failed at saving intermediate results step") -}) - -cat("\nStep 9.5: Early COG filtering (sequence-based)...\n") -tryCatch({ - # Get assembly identifiers for each COG - truncCOGs <- lapply(MatchedSequences, function(x) sort(as.integer(gsub('^([0-9]+)_.*', '\\1', names(x))))) - - - noParas <- sapply(truncCOGs, function(x) length(x) == length(unique(x))) - inFiveOrMore <- sapply(truncCOGs, function(x) length(unique(x)) <= 4) - - # Early filtering (combine all desired filters) - EarlyFiltered <- inFiveOrMore - - # Subset data before expensive tree building - PreFilteredSequences <- MatchedSequences[EarlyFiltered] - - cat("COGs before early filtering:", length(MatchedSequences), "\n") - cat("COGs after early filtering:", length(PreFilteredSequences), "\n") - cat("Breakdown of early filters:\n") - cat(" In 4 or less organisms:", sum(inFiveOrMore), "\n") - cat(" Combined filters passed:", sum(EarlyFiltered), "\n") -}, error = function(e) { - cat("ERROR in early filtering:", e$message, "\n") - stop("Failed at early filtering step") -}) - -# Move functional annotation before tree building for better efficiency - -cat("\nStep 10: Functional annotation...\n") -tryCatch({ - # Create a list to store all the annotations - CogsAnnot <- vector("list", length=length(PreFilteredSequences)) - names(CogsAnnot) <- names(PreFilteredSequences) - - # Translate the sequences - cat("Translating sequences...\n") - geneSeqs <- lapply(PreFilteredSequences, translate) - - # Load the training set for taxonomic classification - cat("Loading training set...\n") - if (!file.exists('data/Actinobacteria.RData')) { - stop("Training set file 'data/Actinobacteria.RData' not found!") - } - load('data/Actinobacteria.RData') # This loads 'trainingSet' - cat("Training set loaded successfully\n") - - # Loop through each COG and annotate it - cat("Annotating", length(geneSeqs), "COGs...\n") - for (i in seq_along(geneSeqs)) { - cat("Annotating COG", i, "of", length(geneSeqs), "\n") - - tryCatch({ - # Get the current COG protein sequences - currentProtein <- geneSeqs[[i]] - CogsAnnot[[i]] <- IdTaxa(currentProtein, trainingSet, processors=NULL) - - }, error = function(e) { - cat("WARNING: Failed to annotate COG", i, ":", e$message, "\n") - CogsAnnot[[i]] <- NULL - }) - } - - successful_annotations <- !sapply(CogsAnnot, is.null) - cat("Successfully annotated", sum(successful_annotations), "COGs out of", length(CogsAnnot), "attempted\n") - -}, error = function(e) { - cat("ERROR in functional annotation:", e$message, "\n") - stop("Failed at functional annotation step") -}) - -cat("\nStep 11: Filtering COGs (annotation-based)...\n") -tryCatch({ - # Apply annotation-based filters - - # Make sure COGs are coding elements - codingCOGs <- sapply(CogsAnnot, function(x) is(x, 'Taxa')) - - # At least one high confidence annotation - highConf <- sapply(CogsAnnot, function(x) - if(is(x, 'Taxa')) - max(sapply(x, function(y) - y$confidence[length(y$confidence)])) > 50 - else FALSE - ) - - # Check for valid functional annotations (no NAs or poor annotations) - validAnnots <- sapply(CogsAnnot, function(x) { - if(!is(x, 'Taxa')) return(FALSE) # Must be a Taxa object - - # Get all annotations - annots <- sapply(x, function(y) y$taxon[length(y$taxon)]) - annots <- annots[annots != 'unclassified_Root'] - - # Must have at least one good annotation - return(length(annots) > 0) - }) - - # Apply annotation-based filters - FilteredCOGs <- codingCOGs & highConf & validAnnots - - # Subset our data for final filtered set - FilteredSequences <- PreFilteredSequences[FilteredCOGs] - FilteredAnnots <- CogsAnnot[FilteredCOGs] - - # Print summary of filtering - cat("COGs after early filtering (Step 9.5):", length(PreFilteredSequences), "\n") - cat("COGs after annotation filtering:", length(FilteredSequences), "\n") - cat("Breakdown of annotation filters:\n") - cat(" Coding elements:", sum(codingCOGs), "\n") - cat(" High confidence annotation:", sum(highConf), "\n") - cat(" Valid annotations:", sum(validAnnots), "\n") - - if (length(FilteredSequences) == 0) { - stop("ERROR: No COGs passed all filtering criteria!") - } - -}, error = function(e) { - cat("ERROR in COG filtering:", e$message, "\n") - stop("Failed at COG filtering step") -}) - -cat("\nStep 12: Creating consensus annotations...\n") -tryCatch({ - consAnnots <- vector('character', length=length(FilteredAnnots)) - for (i in seq_along(FilteredAnnots)) { - taxaentry <- FilteredAnnots[[i]] - - # If no annotation, it's a noncoding gene - if (!is(taxaentry, 'Taxa')) { - consAnnots[i] <- 'NONCODING' - } - # Otherwise it's a coding gene - else { - # Extract all annotations with better error handling - all_annots <- character(0) - - tryCatch({ - # Get annotations from each sequence in the taxa entry - for (j in seq_along(taxaentry)) { - if (length(taxaentry[[j]]$taxon) > 0) { - # Get the most specific annotation (last element) - annotation <- taxaentry[[j]]$taxon[length(taxaentry[[j]]$taxon)] - if (!is.null(annotation) && !is.na(annotation) && annotation != "") { - all_annots <- c(all_annots, annotation) - } - } - } - }, error = function(e) { - cat("Warning: Error extracting annotations for COG", i, ":", e$message, "\n") - }) - - # Filter annotations - keep unclassified only if it has meaningful text - filtered_annots <- character(0) - for (annot in all_annots) { - # Keep annotation if: - # 1. It's not unclassified_Root (too generic) - # 2. It's meaningful text (more than just "unclassified") - # 3. It's not empty or NA - - if (!is.na(annot) && annot != "" && annot != "unclassified_Root") { - # Allow unclassified annotations if they have additional meaningful text - if (grepl("unclassified", annot, ignore.case = TRUE)) { - # Keep if it has more than just "unclassified" (e.g., "unclassified Bacteria") - if (nchar(annot) > 12 && !grepl("^unclassified$", annot, ignore.case = TRUE)) { - filtered_annots <- c(filtered_annots, annot) - } - } else { - # Keep all non-unclassified annotations - filtered_annots <- c(filtered_annots, annot) - } - } - } - - # Assign consensus annotation - if (length(filtered_annots) == 0) { - consAnnots[i] <- 'Uncharacterized' - } else { - # Take the most common meaningful annotation - annot_table <- table(filtered_annots) - consAnnots[i] <- names(sort(annot_table, decreasing=TRUE))[1] - } - - # Additional debugging for first few COGs - if (i <= 3) { - cat("COG", i, "debug:\n") - cat(" Raw annotations found:", length(all_annots), "\n") - cat(" Filtered annotations:", length(filtered_annots), "\n") - cat(" Final annotation:", consAnnots[i], "\n") - if (length(filtered_annots) > 0) { - cat(" Top annotations:", paste(head(names(sort(table(filtered_annots), decreasing=TRUE)), 3), collapse=", "), "\n") - } - } - } - } - - # Summary of annotation results - cat("Created consensus annotations for", length(consAnnots), "COGs\n") - annotation_summary <- table(consAnnots) - cat("Annotation summary:\n") - for (annot_type in names(sort(annotation_summary, decreasing=TRUE))) { - cat(" ", annot_type, ":", annotation_summary[annot_type], "\n") - } - -}, error = function(e) { - cat("ERROR creating consensus annotations:", e$message, "\n") - stop("Failed at consensus annotation step") -}) - -cat("\nStep 13: Building phylogenetic trees (final filtered set)...\n") -tryCatch({ - # Build phylogenetic trees for each COG (using final filtered set) - # Create a list to store all the trees - COGTrees <- vector("list", length=length(FilteredSequences)) - names(COGTrees) <- names(FilteredSequences) - - cat("Building trees for", length(FilteredSequences), "COGs (final filtered set)\n") - - # Loop through each COG and build a tree - for (i in seq_along(FilteredSequences)) { - cat("Building tree", i, "of", length(FilteredSequences), "\n") - - tryCatch({ - # Get the current COG sequences - currentCOG <- FilteredSequences[[i]] - - # Since these are coding regions, align using AlignTranslation - alignedCOG <- AlignTranslation(currentCOG) - - # Build a tree with ancestral state reconstruction - # Using a reasonable time limit to balance accuracy and runtime - distMatrix <- DistanceMatrix(alignedCOG) - COGTrees[[i]] <- TreeLine(myDistMatrix=distMatrix, - myXStringSet=alignedCOG, - method = "UPGMA", - reconstruct = TRUE, - processors=NULL) - - }, error = function(e) { - cat("WARNING: Failed to build tree for COG", i, ":", e$message, "\n") - COGTrees[[i]] <- NULL - }) - } - - # Remove failed trees - successful_trees <- !sapply(COGTrees, is.null) - cat("Successfully built", sum(successful_trees), "trees out of", length(COGTrees), "attempted\n") - -}, error = function(e) { - cat("ERROR in tree building:", e$message, "\n") - stop("Failed at tree building step") -}) - -cat("\nStep 14: Saving trees, sequences and annotations...\n") -tryCatch({ - save(FilteredSequences, FilteredAnnots, COGTrees, consAnnots, file = "./outputs/COG_trees_sequences_annotations.RData") - cat("Successfully saved trees, sequences and annotations to output/\n") -}, error = function(e) { - cat("ERROR saving trees, sequences and annotations:", e$message, "\n") - stop("Failed at saving step") -}) - -cat("\nStep 15: Creating EvoWeaver object...\n") -tryCatch({ - pw <- EvoWeaver(COGTrees) - cat("EvoWeaver object created successfully\n") -}, error = function(e) { - cat("ERROR creating EvoWeaver object:", e$message, "\n") - stop("Failed at EvoWeaver creation step") -}) - -cat("\nStep 16: Making predictions...\n") -tryCatch({ - preds <- predict(pw, Method="Jaccard") - cat("Predictions completed successfully\n") - print(preds) -}, error = function(e) { - cat("ERROR making predictions:", e$message, "\n") - stop("Failed at prediction step") -}) - -cat("\nStep 17: Clustering analysis...\n") -tryCatch({ - # Find clusters of coevolving COGs using igraph - library(igraph) - - adjMatrix <- as.matrix(preds) - g <- graph_from_adjacency_matrix(adjMatrix, weighted=TRUE, - mode='undirected', diag=FALSE) - - clusters <- cluster_louvain(g) - cat("Clustering completed, found", length(clusters), "clusters\n") - - # Getting the clusters & identifying COGs by consensus annotation - clusterLabels <- vector('list', length(clusters)) - for (i in seq_along(clusterLabels)) { - cluster <- communities(clusters)[[i]] - labs <- consAnnots[as.integer(cluster)] - clusterLabels[[i]] <- labs[order(sapply(labs, function(x) - ifelse(grepl(" ", x), - strsplit(x, ' ')[[1]][3], - x)))] - } - - cat("Cluster labels created successfully\n") -}, error = function(e) { - cat("ERROR in clustering analysis:", e$message, "\n") - stop("Failed at clustering step") -}) - -cat("\nStep 18: Saving final results...\n") -tryCatch({ - # Create results directory if it doesn't exist - if (!dir.exists("./results")) { - dir.create("./results", recursive = TRUE) - } - - save(preds, clusters, clusterLabels, consAnnots, file = "./results/EvoWeaver_results.RData") - cat("Final results saved successfully\n") -}, error = function(e) { - cat("ERROR saving final results:", e$message, "\n") - stop("Failed at saving final results step") -}) - -cat("\nStep 19: Creating cluster-to-annotation CSV mapping...\n") -tryCatch({ - # Create a data frame with cluster assignments and KEGG annotations - cluster_annotation_df <- data.frame( - cluster_number = integer(0), - consensus_annotation = character(0), - stringsAsFactors = FALSE - ) - - # Get cluster membership for each COG - cluster_membership <- membership(clusters) - - # Create the mapping - for (i in seq_along(cluster_membership)) { - cluster_num <- cluster_membership[i] - annotation <- consAnnots[i] - - cluster_annotation_df <- rbind(cluster_annotation_df, data.frame( - cluster_number = cluster_num, - consensus_annotation = annotation, - stringsAsFactors = FALSE - )) - } - - # Sort by cluster number then by annotation - cluster_annotation_df <- cluster_annotation_df[order(cluster_annotation_df$cluster_number, cluster_annotation_df$consensus_annotation), ] - - # Write to CSV - write.csv(cluster_annotation_df, file = "./results/cluster_annotation_mapping.csv", row.names = FALSE) - cat("Successfully created cluster-to-annotation CSV mapping with", nrow(cluster_annotation_df), "entries\n") - cat("CSV saved to /results/cluster_annotation_mapping.csv\n") -}, error = function(e) { - cat("ERROR creating cluster-to-annotation CSV:", e$message, "\n") - stop("Failed at CSV creation step") -}) - -cat("\nStep 20: Generating final report...\n") -# Print information about the clusters -cat("Number of clusters identified:", length(clusters), "\n") -for (i in seq_along(clusterLabels)) { - cat("\nCluster", i, "contains", length(clusterLabels[[i]]), "COGs\n") - if (length(clusterLabels[[i]]) <= 10) { - cat("Annotations:\n") - for (j in seq_along(clusterLabels[[i]])) { - cat(" ", clusterLabels[[i]][j], "\n") - } - } else { - cat("First 10 annotations:\n") - for (j in 1:10) { - cat(" ", clusterLabels[[i]][j], "\n") - } - cat(" ... and", length(clusterLabels[[i]]) - 10, "more\n") - } -} - -cat("\n=== ANALYSIS COMPLETE ===\n") -cat("Script completed successfully at:", as.character(Sys.time()), "\n") -cat("Results saved to /results/EvoWeaver_results.RData\n") -cat("Cluster-to-annotation mapping saved to /results/cluster_annotation_mapping.csv\n") \ No newline at end of file diff --git a/tasks/comparative-geno/run_script.sh b/tasks/comparative-geno/run_script.sh deleted file mode 100644 index 3eac711..0000000 --- a/tasks/comparative-geno/run_script.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash -set -e - -# Get the absolute path of the script directory -SCRIPT_DIR="/app" - -# Create output directories -mkdir -p "${SCRIPT_DIR}/data" -mkdir -p "${SCRIPT_DIR}/outputs" -mkdir -p "${SCRIPT_DIR}/results" - -# Download data if it doesn't exist -echo "Downloading comparative genomics data..." -if [ ! -f "${SCRIPT_DIR}/data/micrococcus_data.tar.gz" ]; then - wget -O "${SCRIPT_DIR}/data/micrococcus_data.tar.gz" "https://osf.io/download/nz3sq/" -fi - -# Extract data if not already extracted -if [ ! -d "${SCRIPT_DIR}/data/genome_1" ]; then - echo "Extracting data..." - tar -xzf "${SCRIPT_DIR}/data/micrococcus_data.tar.gz" -C "${SCRIPT_DIR}/data" - rm "${SCRIPT_DIR}/data/micrococcus_data.tar.gz" -fi - -# Run R analysis (staying in the same environment since R is already installed) -echo "Running comparative genomics analysis..." -Rscript run_comparative.R - -echo "Analysis complete! Check the results in the outputs/ and results/ directories." \ No newline at end of file diff --git a/tasks/cystic-fibrosis/Dockerfile b/tasks/cystic-fibrosis/Dockerfile deleted file mode 100644 index 76c9bb0..0000000 --- a/tasks/cystic-fibrosis/Dockerfile +++ /dev/null @@ -1,26 +0,0 @@ -FROM condaforge/mambaforge:latest - -# Set working directory -WORKDIR /app - -# Copy environment file and install dependencies -COPY environment.yml /app/ -RUN mamba env create -f environment.yml - -RUN apt-get update && apt-get install -y unzip - -# Add conda initialization to bash profile and activate environment -RUN echo ". /opt/conda/etc/profile.d/conda.sh" >> ~/.bashrc && \ - echo "conda activate fibrosis_env" >> ~/.bashrc - -# Make RUN commands use the conda environment -SHELL ["conda", "run", "-n", "fibrosis_env", "/bin/bash", "-c"] - -# Copy the analysis script and set permissions -COPY docker_run_script.sh /app/ -RUN chmod +x /app/docker_run_script.sh && \ - mkdir -p /app/data - -# Set entrypoint to run with conda environment -ENTRYPOINT ["/bin/bash", "-l"] -CMD ["/app/docker_run_script.sh"] \ No newline at end of file diff --git a/tasks/cystic-fibrosis/docker_run_script.sh b/tasks/cystic-fibrosis/docker_run_script.sh deleted file mode 100755 index 9cc1092..0000000 --- a/tasks/cystic-fibrosis/docker_run_script.sh +++ /dev/null @@ -1,89 +0,0 @@ -#!/bin/bash -set -e - -# Function for logging with timestamps -log() { - echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" -} - -# # Get the absolute path of the script directory -SCRIPT_DIR="/app" -OUTPUT_DIR="${SCRIPT_DIR}/output" - -AVAILABLE_MEM_GB=4 - -log "Starting fibrosis analysis pipeline..." - -# Create necessary directories -log "Creating directories..." -mkdir -p "${SCRIPT_DIR}/data" -mkdir -p "${OUTPUT_DIR}" - -# Download reference data -log "Downloading SNPEff reference data (GRCh37.75)..." -snpEff download -v GRCh37.75 - -# Download and extract source data -log "Downloading and extracting protocol data..." -wget -O "${SCRIPT_DIR}/data/protocols.zip" \ - "http://sourceforge.net/projects/snpeff/files/protocols.zip" -unzip "${SCRIPT_DIR}/data/protocols.zip" -d "${SCRIPT_DIR}/data/" -rm "${SCRIPT_DIR}/data/protocols.zip" - -# Run SNP effect prediction -log "Running SNP effect prediction..." -snpEff \ - -Xmx${AVAILABLE_MEM_GB}g \ - -v -lof -motif -nextProt \ - GRCh37.75 \ - "${SCRIPT_DIR}/data/protocols/ex1.vcf" \ - > "${OUTPUT_DIR}/ex1.eff.vcf" -log "SNP effect prediction completed" - -# Run case-control analysis -log "Running case-control analysis..." -SnpSift \ - -Xmx${AVAILABLE_MEM_GB}g \ - caseControl -v \ - -tfam "${SCRIPT_DIR}/data/protocols/pedigree.tfam" \ - "${OUTPUT_DIR}/ex1.eff.vcf" \ - > "${OUTPUT_DIR}/ex1.eff.cc.vcf" -log "Case-control analysis completed" - -# Filter variants based on case-control and effect impact -log "Filtering variants..." -cat "${OUTPUT_DIR}/ex1.eff.cc.vcf" \ - | SnpSift filter \ - "(Cases[0] = 3) & (Controls[0] = 0) & ((EFF[*].IMPACT = 'HIGH') | (EFF[*].IMPACT = 'MODERATE'))" \ - > "${OUTPUT_DIR}/ex1.filtered.vcf" - -Download and prepare ClinVar data -log "Downloading and preparing ClinVar data..." -wget -O "${SCRIPT_DIR}/data/clinvar.vcf.gz" \ - https://ftp.ncbi.nlm.nih.gov/pub/clinvar/vcf_GRCh37/clinvar.vcf.gz -gunzip -k "${SCRIPT_DIR}/data/clinvar.vcf.gz" - -# Annotate with ClinVar -log "Annotating with ClinVar..." -SnpSift \ - -Xmx${AVAILABLE_MEM_GB}g \ - annotate -v \ - "${SCRIPT_DIR}/data/clinvar.vcf" \ - "${OUTPUT_DIR}/ex1.eff.cc.vcf" \ - > "${OUTPUT_DIR}/ex1.eff.cc.clinvar.vcf" -log "ClinVar annotation completed" - -# Filter for CFTR variants -log "Filtering for CFTR variants..." -cat "${OUTPUT_DIR}/ex1.eff.cc.clinvar.vcf" \ - | SnpSift filter \ - "(GENEINFO[*] =~ 'CFTR') & ((EFF[*].IMPACT = 'HIGH') | (EFF[*].IMPACT = 'MODERATE')) & (Cases[0] = 3) & (Controls[0] = 0)" \ - > "${OUTPUT_DIR}/output_cf_variant.txt" - -log "Pipeline completed successfully!" - -# Convert VCF to CSV format -log "Converting VCF to CSV format..." -mkdir -p results -python3 vcf_to_csv.py -log "Conversion completed. Results available in results/cf_variants.csv" \ No newline at end of file diff --git a/tasks/cystic-fibrosis/environment.yml b/tasks/cystic-fibrosis/environment.yml deleted file mode 100644 index 2d42a27..0000000 --- a/tasks/cystic-fibrosis/environment.yml +++ /dev/null @@ -1,8 +0,0 @@ -name: fibrosis_env -channels: - - bioconda - - conda-forge - - defaults -dependencies: - - snpeff - - snpsift diff --git a/tasks/cystic-fibrosis/run_script.sh b/tasks/cystic-fibrosis/run_script.sh deleted file mode 100755 index 69f3096..0000000 --- a/tasks/cystic-fibrosis/run_script.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/bin/bash -set -e - -# Get the absolute path of the script directory -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -# Calculate optimal memory (70% of total system memory) -TOTAL_MEM_KB=$(grep MemTotal /proc/meminfo | awk '{print $2}') -AVAILABLE_MEM_GB=$((TOTAL_MEM_KB * 7 / (1024 * 1024 * 10))) - -source ~/miniforge3/etc/profile.d/conda.sh -source ~/miniforge3/etc/profile.d/mamba.sh - -# Create directory structure -mkdir -p "${SCRIPT_DIR}/data" - -# Download and extract source data -wget -O "${SCRIPT_DIR}/data/protocols.zip" \ - "http://sourceforge.net/projects/snpeff/files/protocols.zip" -unzip "${SCRIPT_DIR}/data/protocols.zip" -d "${SCRIPT_DIR}/data/" -rm "${SCRIPT_DIR}/data/protocols.zip" # Clean up zip file after extraction - -# Set up environment -mamba env create -f "${SCRIPT_DIR}/environment.yml" || true -mamba activate fibrosis_env - -# Download reference data -snpEff download -v GRCh37.75 - -# Run SNP effect prediction -snpEff \ - -Xmx${AVAILABLE_MEM_GB}g \ - -v -lof -motif -nextProt \ - GRCh37.75 \ - "${SCRIPT_DIR}/data/protocols/ex1.vcf" \ - > "${SCRIPT_DIR}/data/ex1.eff.vcf" - -# Run case-control analysis -SnpSift \ - -Xmx${AVAILABLE_MEM_GB}g \ - caseControl -v \ - -tfam "${SCRIPT_DIR}/data/protocols/pedigree.tfam" \ - "${SCRIPT_DIR}/data/ex1.eff.vcf" \ - > "${SCRIPT_DIR}/data/ex1.eff.cc.vcf" - -# Filter variants based on case-control and effect impact -cat "${SCRIPT_DIR}/data/ex1.eff.cc.vcf" \ - | SnpSift filter \ - "(Cases[0] = 3) & (Controls[0] = 0) & ((EFF[*].IMPACT = 'HIGH') | (EFF[*].IMPACT = 'MODERATE'))" \ - > "${SCRIPT_DIR}/data/ex1.filtered.vcf" - -# Download and prepare ClinVar data -wget -O "${SCRIPT_DIR}/data/clinvar_2025.vcf.gz" \ - https://ftp.ncbi.nlm.nih.gov/pub/clinvar/vcf_GRCh37/clinvar_20250521.vcf.gz -gunzip -k "${SCRIPT_DIR}/data/clinvar_2025.vcf.gz" - -# Annotate with ClinVar -SnpSift \ - -Xmx${AVAILABLE_MEM_GB}g \ - annotate -v \ - "${SCRIPT_DIR}/data/clinvar_2025.vcf" \ - "${SCRIPT_DIR}/data/ex1.eff.cc.vcf" \ - > "${SCRIPT_DIR}/data/ex1.eff.cc.clinvar.vcf" - -# Filter for CFTR variants -cat "${SCRIPT_DIR}/data/ex1.eff.cc.clinvar.vcf" \ - | SnpSift filter \ - "(GENEINFO[*] =~ 'CFTR') & ((EFF[*].IMPACT = 'HIGH') | (EFF[*].IMPACT = 'MODERATE')) & (Cases[0] = 3) & (Controls[0] = 0)" \ - > "${SCRIPT_DIR}/output_cf_variant.txt" diff --git a/tasks/deseq/Dockerfile b/tasks/deseq/Dockerfile deleted file mode 100644 index e06adbd..0000000 --- a/tasks/deseq/Dockerfile +++ /dev/null @@ -1,24 +0,0 @@ -# Use mambaforge as base image -FROM condaforge/mambaforge:latest - -# Set working directory -WORKDIR /app - -# Copy your scripts and environment files -COPY ./run_script.sh /app/ -COPY ./run_deseq.py /app/ -COPY ./environment.yml /app/ - -# Initialize mamba for shell usage and create environments from yml files -RUN mamba init bash && \ - . ~/.bashrc && \ - # Create the main environment from environment.yml - mamba env create -f environment.yml && \ - # Make script executable - chmod +x /app/run_script.sh - -# Set bash as the shell and source bashrc -SHELL ["/bin/bash", "--login", "-c"] - -# Default command -CMD ["/app/run_script.sh"] diff --git a/tasks/deseq/environment.yml b/tasks/deseq/environment.yml deleted file mode 100644 index dd05eec..0000000 --- a/tasks/deseq/environment.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: rnaseq -channels: - - bioconda - - conda-forge - - defaults -dependencies: - - sra-tools - - fastqc=0.12.1 - - multiqc=1.27.1 - - trimmomatic - - star - - gffread - - pydeseq2 - - goatools - - pandas \ No newline at end of file diff --git a/tasks/deseq/run_deseq.py b/tasks/deseq/run_deseq.py deleted file mode 100644 index 906579a..0000000 --- a/tasks/deseq/run_deseq.py +++ /dev/null @@ -1,106 +0,0 @@ -import pandas as pd -import numpy as np -from pydeseq2.dds import DeseqDataSet -from pydeseq2.ds import DeseqStats -import os -from goatools.base import download_go_basic_obo -from goatools.obo_parser import GODag -from goatools.goea.go_enrichment_ns import GOEnrichmentStudyNS -from goatools.associations import dnld_assc - -# Set working directory -os.chdir("/app") - -# Read count data from multiple files -count_files = [ - "data/processing/7_mapping/SRR1278968_ReadsPerGene.out.tab", - "data/processing/7_mapping/SRR1278969_ReadsPerGene.out.tab", - "data/processing/7_mapping/SRR1278970_ReadsPerGene.out.tab", - "data/processing/7_mapping/SRR1278971_ReadsPerGene.out.tab", - "data/processing/7_mapping/SRR1278972_ReadsPerGene.out.tab", - "data/processing/7_mapping/SRR1278973_ReadsPerGene.out.tab", -] - -sample_names = [ - "SRR1278968", - "SRR1278969", - "SRR1278970", - "SRR1278971", - "SRR1278972", - "SRR1278973", -] - -# Read and combine count data -count_data = [] -gene_ids = None - -for i, file_path in enumerate(count_files): - df = pd.read_csv(file_path, sep="\t", header=0) - if gene_ids is None: - gene_ids = df.iloc[:, 0] # First column contains gene IDs - count_data.append(df.iloc[:, 3]) # Fourth column contains counts - -# Create count matrix -count_matrix = pd.concat(count_data, axis=1) -count_matrix.columns = sample_names -count_matrix.index = gene_ids - -# Remove first 3 rows (summary statistics from STAR) -count_matrix = count_matrix.iloc[3:] - -# Create sample metadata -sample_info = pd.DataFrame( - { - "sample": sample_names, - "condition": [ - "Plankton", - "Plankton", - "Plankton", - "Biofilm", - "Biofilm", - "Biofilm", - ], - } -) -sample_info = sample_info.set_index("sample") - -# Transpose count matrix to have samples as rows and genes as columns -count_matrix_t = count_matrix.T # Transpose: samples as rows, genes as columns - -print("Count matrix shape (samples x genes):", count_matrix_t.shape) -print("Sample info shape:", sample_info.shape) -print("Count matrix index (samples):", count_matrix_t.index.tolist()) -print("Sample info index (samples):", sample_info.index.tolist()) - -# Run DESeq2 analysis -dds = DeseqDataSet( - counts=count_matrix_t, - metadata=sample_info, - design_factors="condition", - refit_cooks=True, -) - -dds.deseq2() - -# Get results - comparing Biofilm vs Plankton -stat_res = DeseqStats(dds, contrast=("condition", "Biofilm", "Plankton")) -stat_res.summary() -results_df = stat_res.results_df - -# Filter for significantly upregulated genes in biofilm -# log2FoldChange > 2 and padj < 0.01 -upreg_mask = ( - (results_df["log2FoldChange"] > 2) - & (results_df["padj"] < 0.01) - & (~results_df["padj"].isna()) -) -upreg_in_biofilm = results_df[upreg_mask].index.tolist() - -# Save upregulated genes as CSV with statistics -upreg_results = results_df[upreg_mask][["log2FoldChange", "pvalue", "padj"]].copy() -upreg_results.index.name = "gene_id" -upreg_results.to_csv("results/up_regulated_genes.csv", index=True) - -print(f"Found {len(upreg_in_biofilm)} upregulated genes in biofilm condition") - -print("Analysis complete!") \ No newline at end of file diff --git a/tasks/deseq/run_script.sh b/tasks/deseq/run_script.sh deleted file mode 100755 index 5028be3..0000000 --- a/tasks/deseq/run_script.sh +++ /dev/null @@ -1,115 +0,0 @@ -#!/bin/bash -set -e - -# Get the absolute path of the script directory -SCRIPT_DIR="/app" -# Calculate optimal thread count (75% of available cores) -THREADS=$(( $(nproc) * 3 / 4 )) - -# Activate the main environment -# source ~/.bashrc -# mamba activate rnaseq - -# Create output directories -mkdir -p "${SCRIPT_DIR}/data/processing"/{0_fasterqdump,1_fastqc,2_multiqc,3_trimming,4_fastqc_trimmed,5_multiqc_trimmed,6_indexing,7_mapping,8_deseq,9_gorich} -mkdir -p "${SCRIPT_DIR}/data/reference" - -# Download SRA files if they don't exist -prefetch SRR1278968 SRR1278969 SRR1278970 SRR1278971 SRR1278972 SRR1278973 \ - -O "${SCRIPT_DIR}/data/" - -# Convert SRA to FASTQ -echo "Converting SRA to FASTQ..." -for sra_file in "${SCRIPT_DIR}"/data/SRR*/*.sra; do - fasterq-dump "$sra_file" -O "${SCRIPT_DIR}/data/processing/0_fasterqdump" -done - -# Run FastQC on raw data -echo "Running FastQC on raw data..." -fastqc "${SCRIPT_DIR}/data/processing/0_fasterqdump/"*fastq \ - -o "${SCRIPT_DIR}/data/processing/1_fastqc" \ - -t "${THREADS}" -multiqc "${SCRIPT_DIR}/data/processing/1_fastqc" \ - -o "${SCRIPT_DIR}/data/processing/2_multiqc" - -# Trim reads -echo "Trimming reads..." -for file in "${SCRIPT_DIR}/data/processing/0_fasterqdump/"*_1.fastq; do - base=$(basename "$file" _1.fastq) - trimmomatic PE -threads "${THREADS}" \ - "${SCRIPT_DIR}/data/processing/0_fasterqdump/${base}_1.fastq" \ - "${SCRIPT_DIR}/data/processing/0_fasterqdump/${base}_2.fastq" \ - "${SCRIPT_DIR}/data/processing/3_trimming/${base}_1P.fastq" \ - "${SCRIPT_DIR}/data/processing/3_trimming/${base}_1U.fastq" \ - "${SCRIPT_DIR}/data/processing/3_trimming/${base}_2P.fastq" \ - "${SCRIPT_DIR}/data/processing/3_trimming/${base}_2U.fastq" \ - LEADING:20 TRAILING:20 SLIDINGWINDOW:4:20 MINLEN:50 -done - -# Run FastQC on trimmed data -echo "Running FastQC on trimmed data..." -fastqc "${SCRIPT_DIR}/data/processing/3_trimming/"*fastq \ - -o "${SCRIPT_DIR}/data/processing/4_fastqc_trimmed" \ - -t "${THREADS}" -multiqc "${SCRIPT_DIR}/data/processing/4_fastqc_trimmed" \ - -o "${SCRIPT_DIR}/data/processing/5_multiqc_trimmed" - -# Download reference data if it doesn't exist -echo "Downloading reference data..." -if [ ! -f "${SCRIPT_DIR}/data/reference/C_parapsilosis_CDC317_current_chromosomes.fasta" ]; then - wget -O "${SCRIPT_DIR}/data/reference/C_parapsilosis_CDC317_current_chromosomes.fasta.gz" \ - http://www.candidagenome.org/download/sequence/C_parapsilosis_CDC317/current/C_parapsilosis_CDC317_current_chromosomes.fasta.gz - gunzip "${SCRIPT_DIR}/data/reference/C_parapsilosis_CDC317_current_chromosomes.fasta.gz" -fi - -if [ ! -f "${SCRIPT_DIR}/data/reference/C_parapsilosis_CDC317_current_features.gff" ]; then - wget -O "${SCRIPT_DIR}/data/reference/C_parapsilosis_CDC317_current_features.gff" \ - http://www.candidagenome.org/download/gff/C_parapsilosis_CDC317/C_parapsilosis_CDC317_current_features.gff -fi - -# Generate STAR index -echo "Generating STAR index..." -STAR --runThreadN "${THREADS}" \ - --runMode genomeGenerate \ - --genomeDir "${SCRIPT_DIR}/data/processing/6_indexing/" \ - --genomeFastaFiles "${SCRIPT_DIR}/data/reference/C_parapsilosis_CDC317_current_chromosomes.fasta" \ - --genomeSAindexNbases 10 - -# Convert GFF to GTF -echo "Converting GFF to GTF..." -gffread "${SCRIPT_DIR}/data/reference/C_parapsilosis_CDC317_current_features.gff" \ - -T -o "${SCRIPT_DIR}/data/processing/6_indexing/C_parapsilosis_CDC317_current_features.gtf" - -# Run STAR mapping -echo "Running STAR mapping..." -for file in "${SCRIPT_DIR}/data/processing/0_fasterqdump/"*_1.fastq; do - base=$(basename "$file" _1.fastq) - STAR --runThreadN "${THREADS}" \ - --genomeDir "${SCRIPT_DIR}/data/processing/6_indexing" \ - --sjdbGTFfile "${SCRIPT_DIR}/data/processing/6_indexing/C_parapsilosis_CDC317_current_features.gtf" \ - --readFilesIn "${SCRIPT_DIR}/data/processing/3_trimming/${base}_1P.fastq" \ - "${SCRIPT_DIR}/data/processing/3_trimming/${base}_2P.fastq" \ - --outFileNamePrefix "${SCRIPT_DIR}/data/processing/7_mapping/${base}_" \ - --outSAMtype BAM SortedByCoordinate \ - --limitBAMsortRAM 100000000000 \ - --quantMode GeneCounts -done - -# Generate mapping QC report -echo "Generating mapping QC report..." -multiqc "${SCRIPT_DIR}/data/processing/7_mapping" \ - -o "${SCRIPT_DIR}/data/processing/7_mapping" - -# Download GO annotations -echo "Downloading GO annotations..." -if [ ! -f "${SCRIPT_DIR}/data/processing/9_gorich/gene_association.cgd" ]; then - wget -O "${SCRIPT_DIR}/data/processing/9_gorich/gene_association.cgd.gz" \ - http://www.candidagenome.org/download/go/gene_association.cgd.gz - gunzip "${SCRIPT_DIR}/data/processing/9_gorich/gene_association.cgd.gz" -fi - -# Run R analysis -mkdir -p results -python run_deseq.py - -echo "Analysis complete! Check the results in the data/processing directory." \ No newline at end of file diff --git a/tasks/evolution/Dockerfile b/tasks/evolution/Dockerfile deleted file mode 100644 index ba01884..0000000 --- a/tasks/evolution/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM condaforge/mambaforge:24.9.2-0 - -WORKDIR /app - -COPY run_script.sh /app/ -COPY environment.yml /app/ - -RUN mamba init bash && \ - . ~/.bashrc && \ - # Create the main environment from environment.yml - mamba env create -f environment.yml && \ - # Make script executable - chmod +x /app/run_script.sh - - -SHELL ["/bin/bash", "--login", "-c"] - -CMD ["/app/run_script.sh"] \ No newline at end of file diff --git a/tasks/evolution/environment.yml b/tasks/evolution/environment.yml deleted file mode 100644 index 7ac5ad5..0000000 --- a/tasks/evolution/environment.yml +++ /dev/null @@ -1,11 +0,0 @@ -name: evolution -channels: - - bioconda - - conda-forge - - defaults -dependencies: - - mamba - - wget - - tar - - pip - - setuptools \ No newline at end of file diff --git a/tasks/evolution/run_script.sh b/tasks/evolution/run_script.sh deleted file mode 100755 index 4471b01..0000000 --- a/tasks/evolution/run_script.sh +++ /dev/null @@ -1,340 +0,0 @@ -#!/bin/bash -set -e - -# Set dynamic thread count -THREADS=$(nproc) - -# Logging functions -TOTAL_STEPS=12 -CURRENT_STEP=0 - -log_step() { - CURRENT_STEP=$((CURRENT_STEP + 1)) - echo "==================================================================" - echo "STEP $CURRENT_STEP/$TOTAL_STEPS: $1" - echo "==================================================================" - echo "Started at: $(date)" - echo "" -} - -log_substep() { - echo " → $1" -} - -log_completion() { - echo "" - echo "Completed at: $(date)" - echo "" -} - -env_exists() { - local env_name=$1 - mamba env list | grep -q "^${env_name} " -} - -# STEP 1: Environment Setup -log_step "Setting up conda environments" - -# Sometimes these environments get spastic and this is easier -if ! env_exists "fastp_env"; then - log_substep "Creating fastp environment" - mamba create -n fastp_env bioconda::fastp -y -fi - -if ! env_exists "fastqc_env"; then - log_substep "Creating fastqc environment" - mamba create -n fastqc_env bioconda::fastqc -y -fi - -if ! env_exists "multiqc_env"; then - log_substep "Creating multiqc environment" - mamba create -n multiqc_env bioconda::multiqc -y -fi - -if ! env_exists "spades_env"; then - log_substep "Creating spades environment" - mamba create -n spades_env bioconda::spades -y -fi - -if ! env_exists "quast_env"; then - log_substep "Creating quast environment" - mamba create -n quast_env bioconda::quast -y -fi - -if ! env_exists "mapping_env"; then - log_substep "Creating mapping environment" - mamba create -y -n mapping_env -c bioconda samtools bwa -fi - -if ! env_exists "variant_env"; then - log_substep "Creating variant calling environment" - mamba create -y -n variant_env -c bioconda samtools bamtools freebayes -fi - -if ! env_exists "compleasm_env"; then - log_substep "Creating compleasm environment" - mamba create -y -n compleasm_env bioconda::compleasm -fi - -if ! env_exists "prokka_env"; then - log_substep "Creating prokka environment" - mamba create -y -n prokka_env bioconda::prokka -fi - -if ! env_exists "voi_env"; then - log_substep "Creating variant annotation environment" - mamba create -y -n voi_env -c bioconda snpeff genometools-genometools -fi - -if ! env_exists "bcf_env"; then - log_substep "Creating bcf tools environment" - mamba create -y -n bcf_env -c bioconda bcftools -fi - -log_completion - -# Create directory structure -mkdir -p data -mkdir -p outputs/trimmed -mkdir -p outputs/trimmed-fastqc -mkdir -p outputs/assembly -mkdir -p outputs/mappings -mkdir -p outputs/variants -mkdir -p outputs/annotation -mkdir -p outputs/voi -mkdir -p outputs/bcf -mkdir -p results - -# Download the data to data folder -cd data -wget -O data.tar.gz https://osf.io/2jc4a/download -tar -xvzf data.tar.gz --strip-components=1 -cd .. - -# STEP 2: Quality Control - Adapter Trimming -log_step "Quality control - trimming adapters" - -log_substep "Trimming adapters for ancestral sample" -mamba run -n fastp_env fastp --detect_adapter_for_pe --overrepresentation_analysis --correction --cut_right --thread $THREADS \ - --html ./outputs/trimmed/anc.fastp.html --json ./outputs/trimmed/anc.fastp.json -i ./data/anc_R1.fastq.gz \ - -I ./data/anc_R2.fastq.gz -o ./outputs/trimmed/anc_R1.fastq.gz -O ./outputs/trimmed/anc_R2.fastq.gz - -log_substep "Trimming adapters for evolved sample 1" -mamba run -n fastp_env fastp --detect_adapter_for_pe --overrepresentation_analysis --correction --cut_right --thread $THREADS \ - --html ./outputs/trimmed/evol1.fastp.html --json ./outputs/trimmed/evol1.fastp.json -i ./data/evol1_R1.fastq.gz \ - -I ./data/evol1_R2.fastq.gz -o ./outputs/trimmed/evol1_R1.fastq.gz -O ./outputs/trimmed/evol1_R2.fastq.gz - -log_substep "Trimming adapters for evolved sample 2" -mamba run -n fastp_env fastp --detect_adapter_for_pe --overrepresentation_analysis --correction --cut_right --thread $THREADS \ - --html ./outputs/trimmed/evol2.fastp.html --json ./outputs/trimmed/evol2.fastp.json -i ./data/evol2_R1.fastq.gz \ - -I ./data/evol2_R2.fastq.gz -o ./outputs/trimmed/evol2_R1.fastq.gz -O ./outputs/trimmed/evol2_R2.fastq.gz - -log_completion - -# STEP 3: Quality Control - FastQC Analysis -log_step "Quality control - FastQC analysis" - -log_substep "Running FastQC on trimmed reads" -mamba run -n fastqc_env fastqc -t $THREADS -o ./outputs/trimmed-fastqc ./outputs/trimmed/*.fastq.gz - -log_completion - -# STEP 4: Quality Control - MultiQC Visualization -log_step "Quality control - MultiQC visualization" - -log_substep "Generating MultiQC report" -mamba run -n multiqc_env multiqc ./outputs/trimmed-fastqc ./outputs/trimmed -o ./outputs - -log_completion - -# STEP 5: Genome Assembly -log_step "Genome assembly with SPAdes" - -log_substep "Running SPAdes assembly" -mamba run -n spades_env spades.py -o ./outputs/assembly --careful -t $THREADS -1 ./outputs/trimmed/anc_R1.fastq.gz -2 ./outputs/trimmed/anc_R2.fastq.gz - -log_completion - -# STEP 6: Assembly Quality Assessment -log_step "Assembly quality assessment with QUAST" - -log_substep "Running QUAST quality assessment" -mamba run -n quast_env quast -t $THREADS -o ./outputs/assembly/quast ./outputs/assembly/scaffolds.fasta - -log_completion - -# STEP 7: Read Mapping -log_step "Read mapping to reference genome" - -log_substep "Preparing reference genome" -cp ./outputs/assembly/scaffolds.fasta ./outputs/mappings/scaffolds.fasta -mamba run -n mapping_env bwa index ./outputs/mappings/scaffolds.fasta - -# log_substep "Mapping evolved sample 1 reads" -mamba run -n mapping_env bash -c "bwa mem -t $THREADS ./outputs/mappings/scaffolds.fasta ./outputs/trimmed/evol1_R1.fastq.gz ./outputs/trimmed/evol1_R2.fastq.gz > ./outputs/mappings/evol1.sam" - -# log_substep "Mapping evolved sample 2 reads" -mamba run -n mapping_env bash -c "bwa mem -t $THREADS ./outputs/mappings/scaffolds.fasta ./outputs/trimmed/evol2_R1.fastq.gz ./outputs/trimmed/evol2_R2.fastq.gz > ./outputs/mappings/evol2.sam" - -log_completion - -# STEP 8: Post-processing Mappings -log_step "Post-processing mapping files" - -log_substep "Processing evolved sample 1 mappings" -# Evol1 line -mamba run -n mapping_env bash -c "samtools sort -@ $THREADS -n -O sam ./outputs/mappings/evol1.sam | samtools fixmate -m -O bam - ./outputs/mappings/evol1.fixmate.bam" -mamba run -n mapping_env samtools sort -@ $THREADS -O bam -o ./outputs/mappings/evol1.sorted.bam ./outputs/mappings/evol1.fixmate.bam -mamba run -n mapping_env samtools markdup -@ $THREADS -r -S ./outputs/mappings/evol1.sorted.bam ./outputs/mappings/evol1.sorted.dedup.bam -mamba run -n mapping_env bash -c "samtools view -@ $THREADS -h -b -q 20 ./outputs/mappings/evol1.sorted.dedup.bam > ./outputs/mappings/evol1.sorted.dedup.q20.bam" -mamba run -n mapping_env bash -c "samtools view -@ $THREADS -b -f 4 ./outputs/mappings/evol1.sorted.dedup.bam > ./outputs/mappings/evol1.sorted.unmapped.bam" -rm ./outputs/mappings/evol1.sam -rm ./outputs/mappings/evol1.fixmate.bam -rm ./outputs/mappings/evol1.sorted.bam -rm ./outputs/mappings/evol1.sorted.dedup.bam - -log_substep "Processing evolved sample 2 mappings" -# Evol2 line -mamba run -n mapping_env bash -c "samtools sort -@ $THREADS -n -O sam ./outputs/mappings/evol2.sam | samtools fixmate -m -O bam - ./outputs/mappings/evol2.fixmate.bam" -mamba run -n mapping_env samtools sort -@ $THREADS -O bam -o ./outputs/mappings/evol2.sorted.bam ./outputs/mappings/evol2.fixmate.bam -mamba run -n mapping_env samtools markdup -@ $THREADS -r -S ./outputs/mappings/evol2.sorted.bam ./outputs/mappings/evol2.sorted.dedup.bam -mamba run -n mapping_env bash -c "samtools view -@ $THREADS -h -b -q 20 ./outputs/mappings/evol2.sorted.dedup.bam > ./outputs/mappings/evol2.sorted.dedup.q20.bam" -mamba run -n mapping_env bash -c "samtools view -@ $THREADS -b -f 4 ./outputs/mappings/evol2.sorted.dedup.bam > ./outputs/mappings/evol2.sorted.unmapped.bam" - -rm ./outputs/mappings/evol2.sam -rm ./outputs/mappings/evol2.fixmate.bam -rm ./outputs/mappings/evol2.sorted.bam -rm ./outputs/mappings/evol2.sorted.dedup.bam - -log_completion - -# STEP 9: Variant Calling -log_step "Variant calling with FreeBayes" - -log_substep "Preparing reference genome index" -mamba run -n mapping_env samtools faidx ./outputs/assembly/scaffolds.fasta - -log_substep "Calling variants for evolved sample 1" -mamba run -n variant_env bamtools index -in ./outputs/mappings/evol1.sorted.dedup.q20.bam -# p 1 for bacteria -mamba run -n variant_env bash -c "freebayes -p 1 -f ./outputs/assembly/scaffolds.fasta ./outputs/mappings/evol1.sorted.dedup.q20.bam > ./outputs/variants/evol1.freebayes.vcf" -mamba run -n variant_env bgzip -f ./outputs/variants/evol1.freebayes.vcf -mamba run -n variant_env tabix -p vcf ./outputs/variants/evol1.freebayes.vcf.gz -mamba run -n variant_env bash -c "zcat ./outputs/variants/evol1.freebayes.vcf.gz | vcffilter -f \"QUAL > 1 & QUAL / AO > 10 & SAF > 0 & SAR > 0 & RPR > 1 & RPL > 1\" | bgzip > ./outputs/variants/evol1.freebayes.filtered.vcf.gz" -mamba run -n variant_env tabix -p vcf ./outputs/variants/evol1.freebayes.filtered.vcf.gz - -log_substep "Calling variants for evolved sample 2" -mamba run -n variant_env bamtools index -in ./outputs/mappings/evol2.sorted.dedup.q20.bam -mamba run -n variant_env bash -c "freebayes -p 1 -f ./outputs/assembly/scaffolds.fasta ./outputs/mappings/evol2.sorted.dedup.q20.bam > ./outputs/variants/evol2.freebayes.vcf" -mamba run -n variant_env bgzip -f ./outputs/variants/evol2.freebayes.vcf -mamba run -n variant_env tabix -p vcf ./outputs/variants/evol2.freebayes.vcf.gz -mamba run -n variant_env bash -c "zcat ./outputs/variants/evol2.freebayes.vcf.gz | vcffilter -f \"QUAL > 1 & QUAL / AO > 10 & SAF > 0 & SAR > 0 & RPR > 1 & RPL > 1\" | bgzip > ./outputs/variants/evol2.freebayes.filtered.vcf.gz" -mamba run -n variant_env tabix -p vcf ./outputs/variants/evol2.freebayes.filtered.vcf.gz - -log_completion - -# STEP 10: Genome Annotation -log_step "Genome annotation" - -log_substep "Running BUSCO completeness assessment" -mamba run -n compleasm_env compleasm run -a ./outputs/assembly/scaffolds.fasta -o ./outputs/annotation -l bacteria_odb10 -t $THREADS - -log_substep "Running Prokka gene annotation" -mamba run -n prokka_env prokka --cpus $THREADS --kingdom Bacteria --genus Escherichia --species coli --outdir ./outputs/annotation/prokka ./outputs/assembly/scaffolds.fasta - -log_substep "Preparing SnpEff annotation database" -mkdir -p ./outputs/voi/data/mygenome -cp ./outputs/assembly/scaffolds.fasta ./outputs/voi/data/mygenome/sequences.fa -gzip ./outputs/voi/data/mygenome/sequences.fa -cp ./outputs/annotation/prokka/*.gff ./outputs/voi/data/mygenome/genes.gff -gzip ./outputs/voi/data/mygenome/genes.gff - -SNPEFF_CONFIG=$(mamba run -n voi_env bash -c "find ~ -name snpEff.config | head -n 1") -cp "$SNPEFF_CONFIG" ./outputs/voi/snpEff.config -sed -i 's|^data.dir.*|data.dir = data/|' ./outputs/voi/snpEff.config - -# Add custom genome configuration to snpEff.config -cat >> ./outputs/voi/snpEff.config << EOF -# Custom genome configuration -mygenome.genome : EColiMut -mygenome.codonTable : Bacterial_and_Plant_Plastid -mygenome.checkProtein : false -mygenome.checkCds : false -EOF - -log_substep "Building SnpEff database" -mamba run -n voi_env snpEff build -c ./outputs/voi/snpEff.config -gff3 -v mygenome -noCheckCds -noCheckProtein - -log_completion - -# STEP 11: Variant Annotation -log_step "Variant annotation with SnpEff" - -log_substep "Annotating variants for evolved sample 1" -gunzip -k ./outputs/variants/evol1.freebayes.filtered.vcf.gz -mamba run -n voi_env bash -c "snpEff -c ./outputs/voi/snpEff.config -Xmx16g mygenome ./outputs/variants/evol1.freebayes.filtered.vcf > ./outputs/variants/evol1.freebayes.filtered.anno.vcf" - -log_substep "Annotating variants for evolved sample 2" -gunzip -k ./outputs/variants/evol2.freebayes.filtered.vcf.gz -mamba run -n voi_env bash -c "snpEff -c ./outputs/voi/snpEff.config -Xmx16g mygenome ./outputs/variants/evol2.freebayes.filtered.vcf > ./outputs/variants/evol2.freebayes.filtered.anno.vcf" - -log_completion - -# STEP 12: Final Analysis and Results Generation -log_step "Generating final results" - -log_substep "Comparing variants between evolved samples" -mamba run -n bcf_env bash -c ' - bcftools view -Oz -o ./outputs/variants/evol1.vcf.gz \ - ./outputs/variants/evol1.freebayes.filtered.anno.vcf && \ - bcftools index -t ./outputs/variants/evol1.vcf.gz -' - -mamba run -n bcf_env bash -c ' - bcftools view -Oz -o ./outputs/variants/evol2.vcf.gz \ - ./outputs/variants/evol2.freebayes.filtered.anno.vcf && \ - bcftools index -t ./outputs/variants/evol2.vcf.gz -' - -mamba run -n bcf_env bcftools isec -p ./outputs/bcf -Oz \ - ./outputs/variants/evol1.vcf.gz \ - ./outputs/variants/evol2.vcf.gz - -log_substep "Extracting shared high-impact variants" -# Create shared variants CSV with high/moderate impact mutations -mamba run -n bcf_env bash -c ' -bcftools query -f "%CHROM\t%POS\t%REF\t%ALT\t%INFO/ANN\n" \ - ./outputs/bcf/0002.vcf.gz \ -| awk -F"\t" '\''BEGIN{OFS=","; print "CHROM,POS,REF,ALT,GENE,IMPACT,EFFECT,STATUS"} - { - split($5, ann, "|"); # ann[3] = IMPACT, ann[4] = Gene_Name, ann[2] = Annotation/EFFECT - impact = ann[3]; - gene = ann[4]; - effect = ann[2]; - if ((impact=="HIGH" || impact=="MODERATE") && !seen[gene]++) { - print $1,$2,$3,$4,gene,impact,effect,"shared"; - } - } -'\'' > ./results/variants_shared.csv -' - -log_substep "Generating gene annotations for variants" -# Create detailed gene annotations CSV -echo "Gene_Name,COG,Function" > ./results/gene_annotations.csv -if [ -s ./results/variants_shared.csv ] && [ $(wc -l < ./results/variants_shared.csv) -gt 1 ]; then - grep -Ff <(tail -n +2 ./results/variants_shared.csv | cut -d, -f5) \ - ./outputs/annotation/prokka/*.tsv | \ - awk -F'\t' 'BEGIN { OFS="," } - { - if (NF < 7) next - gene_name = $4 - cog = $6 - function_desc = $7 - if (gene_name == "") gene_name = "unknown" - if (cog == "") cog = "no_COG" - if (function_desc == "") function_desc = "hypothetical protein" - gsub(/,/, ";", function_desc) - gsub(/"/, "", function_desc) - print gene_name, cog, function_desc - }' >> ./results/gene_annotations.csv -fi \ No newline at end of file diff --git a/tasks/giab/environment.yml b/tasks/giab/environment.yml deleted file mode 100644 index 58e36c8..0000000 --- a/tasks/giab/environment.yml +++ /dev/null @@ -1,6 +0,0 @@ -name: giab -channels: - - conda-forge - - bioconda -dependencies: - - nextflow \ No newline at end of file diff --git a/tasks/giab/run_script.sh b/tasks/giab/run_script.sh deleted file mode 100755 index bbf09c4..0000000 --- a/tasks/giab/run_script.sh +++ /dev/null @@ -1,219 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Minimal nf-core/sarek germline run + hap.py benchmarking (NA12878 WES) -# Requires: Nextflow + Docker. Downloads test FASTQs, BED, GIAB truth set, and GRCh38 FASTA. -# Includes automated evaluation using hap.py after variant calling completes. - -CWD="$(pwd)" -OUTDIR="$CWD/results" -WORKDIR="$CWD/output" -DATADIR="$CWD/data" -BENCHDIR="$CWD/benchmark_ref" -EVALDIR="$CWD/evaluation" -SAREK_RELEASE="3.5.1" -PROFILE="docker" - -SAMPLE_ID="A006850052_NA12878_75M" -R1="$DATADIR/A006850052_NA12878_75M_R1.fq.gz" -R2="$DATADIR/A006850052_NA12878_75M_R2.fq.gz" -BED_FILE="$DATADIR/Agilent_v7.bed" # panel/exome targets (restricts Sarek + benchmarking) -THREADS=${THREADS:-64} - -# ----------------------------- -# Data URLs (Zenodo NA12878 Agilent 75M WES) -# ----------------------------- -R1_URL="https://zenodo.org/records/6513789/files/A006850052_NA12878_75M_R1.fq.gz?download=1" -R2_URL="https://zenodo.org/records/6513789/files/A006850052_NA12878_75M_R2.fq.gz?download=1" -BED_URL="https://zenodo.org/records/6513789/files/Agilent_v7.bed?download=1" - -# ----------------------------- -# GIAB truth set (HG001 / NA12878, GRCh38 v4.2.1) -# ----------------------------- -GIAB_DIR="$BENCHDIR/GIAB_HG001_GRCh38_v4.2.1" -TRUTH_VCF="$GIAB_DIR/HG001_GRCh38_1_22_v4.2.1_benchmark.vcf.gz" -TRUTH_BED="$GIAB_DIR/HG001_GRCh38_1_22_v4.2.1_benchmark.bed" -TRUTH_BASE="https://ftp-trace.ncbi.nlm.nih.gov/ReferenceSamples/giab/release/NA12878_HG001/NISTv4.2.1/GRCh38" -# ----------------------------- -# Reference FASTA (GRCh38) -# If you already have a matching GRCh38 FASTA, set REF_FASTA to it and skip download. -# ----------------------------- -REF_DIR="$BENCHDIR/ref_GRCh38" -REF_FASTA="${REF_FASTA:-$REF_DIR/Homo_sapiens_assembly38.fasta}" -REF_FASTA_URL="https://storage.googleapis.com/genomics-public-data/resources/broad/hg38/v0/Homo_sapiens_assembly38.fasta" -REF_DICT_URL="https://storage.googleapis.com/genomics-public-data/resources/broad/hg38/v0/Homo_sapiens_assembly38.dict" # dict is small -# (fai will be built locally; we also work fine if you already have .fai / bwa indexes) - -mkdir -p "$OUTDIR" "$WORKDIR" "$DATADIR" "$BENCHDIR" "$GIAB_DIR" "$REF_DIR" "$EVALDIR" - -echo "== Checking input WES dataset ==" -if [[ ! -f "$R1" ]]; then wget -O "$R1" "$R1_URL"; fi -if [[ ! -f "$R2" ]]; then wget -O "$R2" "$R2_URL"; fi -if [[ ! -f "$BED_FILE" ]]; then wget -O "$BED_FILE" "$BED_URL"; fi - -BED_FILE_CHR="$DATADIR/Agilent_v7.chr.bed" -awk 'BEGIN{OFS="\t"} - /^track|^browser|^#/ {print; next} - { if ($1 !~ /^chr/) $1="chr"$1; print }' "$BED_FILE" > "$BED_FILE_CHR" -BED_FILE="$BED_FILE_CHR" - -echo "== Fetching GIAB truth set (HG001 GRCh38 v4.2.1) ==" -if [[ ! -f "$TRUTH_VCF" ]]; then wget -O "$TRUTH_VCF" "${TRUTH_BASE}/HG001_GRCh38_1_22_v4.2.1_benchmark.vcf.gz"; fi -if [[ ! -f "${TRUTH_VCF}.tbi" ]]; then wget -O "${TRUTH_VCF}.tbi" "${TRUTH_BASE}/HG001_GRCh38_1_22_v4.2.1_benchmark.vcf.gz.tbi"; fi -if [[ ! -f "$TRUTH_BED" ]]; then wget -O "$TRUTH_BED" "${TRUTH_BASE}/HG001_GRCh38_1_22_v4.2.1_benchmark.bed"; fi - -echo "== Preparing GRCh38 reference for hap.py ==" -if [[ ! -f "$REF_FASTA" ]]; then - # Download the GRCh38 FASTA (GATK bundle mirror on GCS) - it's already uncompressed - wget -O "$REF_FASTA" "$REF_FASTA_URL" -fi -if [[ ! -f "${REF_FASTA}.fai" ]]; then samtools faidx "$REF_FASTA"; fi -# Optional: dictionary (not strictly required by hap.py, but handy) -if [[ ! -f "${REF_DIR}/Homo_sapiens_assembly38.dict" ]]; then - wget -O "${REF_DIR}/Homo_sapiens_assembly38.dict" "$REF_DICT_URL" || true -fi - -echo "== Build Sarek samplesheet ==" -SAMPLESHEET="$OUTDIR/samplesheet.csv" -echo "patient,status,sample,lane,fastq_1,fastq_2" > "$SAMPLESHEET" -echo "${SAMPLE_ID},0,${SAMPLE_ID},lane_1,${R1},${R2}" >> "$SAMPLESHEET" - -echo "== Run Sarek (germline, WES, intervals) ==" -set -x -nextflow run nf-core/sarek -r "$SAREK_RELEASE" \ - -profile "$PROFILE" \ - --fasta "$REF_FASTA" \ - --input "$SAMPLESHEET" \ - --analysis_type germline \ - --tools deepvariant,haplotypecaller \ - --wes \ - --intervals "$BED_FILE" \ - --outdir "$OUTDIR" \ - --max_cpus "$THREADS" \ - --max_memory "120.GB" \ - -work-dir "$WORKDIR" -set +x - -echo "Sarek results: $OUTDIR" - -echo "" -echo "===============================================" -echo "Starting variant calling evaluation with hap.py" -echo "===============================================" - -# Define paths to variant calling outputs from Sarek -DEEPVARIANT_VCF="$OUTDIR/variant_calling/deepvariant/$SAMPLE_ID/${SAMPLE_ID}.deepvariant.vcf.gz" -HAPLOTYPECALLER_VCF="$OUTDIR/variant_calling/haplotypecaller/$SAMPLE_ID/${SAMPLE_ID}.haplotypecaller.filtered.vcf.gz" - -# Environment name for hap.py -HAP_ENV="hap_env" - -echo "== Checking required input files for evaluation ==" -for file in "$TRUTH_VCF" "$TRUTH_BED" "$REF_FASTA" "$BED_FILE" "$DEEPVARIANT_VCF" "$HAPLOTYPECALLER_VCF"; do - if [[ ! -f "$file" ]]; then - echo "ERROR: Required file not found: $file" - echo "Variant calling may have failed or files are in unexpected locations" - exit 1 - fi -done - -echo "== Setting up hap.py environment ==" -# Check if mamba is available, fallback to conda -if command -v mamba &> /dev/null; then - CONDA_CMD="mamba" -elif command -v conda &> /dev/null; then - CONDA_CMD="conda" -else - echo "ERROR: Neither mamba nor conda found. Please install mamba or conda first." - exit 1 -fi - -# Check if environment exists, create if not -if ! $CONDA_CMD env list | grep -q "^${HAP_ENV}\s"; then - echo "Creating hap.py environment..." - $CONDA_CMD create -n "$HAP_ENV" -c bioconda -c conda-forge hap.py rtg-tools -y -else - echo "hap.py environment already exists" -fi - -# Function to run hap.py evaluation -run_happy_eval() { - local vcf_file="$1" - local caller_name="$2" - local output_prefix="$EVALDIR/${SAMPLE_ID}_${caller_name}" - - echo "== Running hap.py evaluation for $caller_name ==" - echo "Input VCF: $vcf_file" - echo "Output prefix: $output_prefix" - - $CONDA_CMD run -n "$HAP_ENV" hap.py \ - "$TRUTH_VCF" \ - "$vcf_file" \ - -f "$TRUTH_BED" \ - -T "$BED_FILE" \ - -r "$REF_FASTA" \ - -o "$output_prefix" \ - --pass-only \ - --verbose - - echo "Completed evaluation for $caller_name" - echo "Results saved to: ${output_prefix}.*" -} - -# Run evaluations for both variant callers -run_happy_eval "$DEEPVARIANT_VCF" "deepvariant" -run_happy_eval "$HAPLOTYPECALLER_VCF" "haplotypecaller" - -echo "== Generating summary report ==" -SUMMARY_REPORT="$EVALDIR/evaluation_summary.txt" -{ - echo "=========================================" - echo "Variant Calling Evaluation Summary" - echo "Sample: $SAMPLE_ID" - echo "Date: $(date)" - echo "=========================================" - echo "" - - for caller in deepvariant haplotypecaller; do - summary_file="$EVALDIR/${SAMPLE_ID}_${caller}.summary.csv" - if [[ -f "$summary_file" ]]; then - echo "--- $caller Results ---" - echo "Summary file: $summary_file" - # Extract key metrics from summary - if [[ -f "$summary_file" ]]; then - echo "Key metrics:" - head -n 20 "$summary_file" | grep -E "(Type|TRUTH|QUERY|Recall|Precision|F1_Score)" || echo "Summary format may differ" - fi - echo "" - else - echo "--- $caller Results ---" - echo "WARNING: Summary file not found: $summary_file" - echo "" - fi - done - - echo "Detailed results available in:" - echo "- $EVALDIR/" - echo "" - echo "Files generated:" - ls -la "$EVALDIR"/ || true - -} > "$SUMMARY_REPORT" - -echo "== Pipeline Complete ==" -echo "" -echo "=========================================" -echo "All results:" -echo "=========================================" -echo "- Sarek results: $OUTDIR" -echo "- Evaluation results: $EVALDIR" -echo "- Summary report: $SUMMARY_REPORT" -echo "" -echo "Key evaluation files:" -echo "- DeepVariant evaluation: $EVALDIR/${SAMPLE_ID}_deepvariant.*" -echo "- HaplotypeCaller evaluation: $EVALDIR/${SAMPLE_ID}_haplotypecaller.*" -echo "" -echo "To view the evaluation summary:" -echo "cat $SUMMARY_REPORT" -echo "" -echo "To examine detailed metrics, check the .summary.csv files in $EVALDIR/" diff --git a/tasks/metagenomics/Dockerfile b/tasks/metagenomics/Dockerfile deleted file mode 100644 index c263c0c..0000000 --- a/tasks/metagenomics/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -FROM condaforge/mambaforge:24.9.2-0 - -WORKDIR /app - -COPY run_script.sh /app/ -COPY environment.yml /app/ - -RUN mamba init bash && \ - . ~/.bashrc && \ - mamba env create -f environment.yml && \ - chmod +x /app/run_script.sh - - -SHELL ["/bin/bash", "--login", "-c"] - -CMD ["/app/run_script.sh"] \ No newline at end of file diff --git a/tasks/metagenomics/environment.yml b/tasks/metagenomics/environment.yml deleted file mode 100644 index 8bd2471..0000000 --- a/tasks/metagenomics/environment.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: metagenomics -channels: - - conda-forge - - bioconda - - defaults -dependencies: - - wget - - unzip - - gzip - - - fastqc=0.12.1 - - multiqc=1.21 - - - trimmomatic=0.39 - - spades=4.0.0 - - kraken2=2.1.3 - - kraken-biom=1.2.0 - - - r-base=4.3.2 - - bioconductor-phyloseq=1.46.0 - - r-ggplot2 - - r-dplyr - - r-tidyr - - r-rcolorbrewer - - r-patchwork \ No newline at end of file diff --git a/tasks/metagenomics/run_phyloseq.R b/tasks/metagenomics/run_phyloseq.R deleted file mode 100755 index d0a0cc0..0000000 --- a/tasks/metagenomics/run_phyloseq.R +++ /dev/null @@ -1,50 +0,0 @@ -if (!requireNamespace("BiocManager", quietly = TRUE)) { - install.packages("BiocManager", repos = "https://cloud.r-project.org") -} - -if (!requireNamespace("phyloseq", quietly = TRUE)) { - BiocManager::install("phyloseq") -} - -if (!requireNamespace("RColorBrewer", quietly = TRUE) || - !requireNamespace("patchwork", quietly = TRUE) || - !requireNamespace("dplyr", quietly = TRUE) || - !requireNamespace("tidyr", quietly = TRUE)) { - install.packages(c("RColorBrewer", "patchwork", "dplyr", "tidyr"), repos = "https://cloud.r-project.org") -} - -setwd(".") - -library("phyloseq") -library("ggplot2") -library("RColorBrewer") -library("patchwork") -library("dplyr") -library("tidyr") - -merged_metagenomes <- import_biom("outputs/5_biom/cuatroc.biom") - -merged_metagenomes@tax_table@.Data <- substring(merged_metagenomes@tax_table@.Data, 4) -colnames(merged_metagenomes@tax_table@.Data)<- c("Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species") - -merged_metagenomes <- subset_taxa(merged_metagenomes, Kingdom == "Bacteria") -merged_metagenomes <- subset_taxa(merged_metagenomes, Genus != "") -percentages <- transform_sample_counts(merged_metagenomes, function(x) x*100 / sum(x) ) -percentages_glom <- tax_glom(percentages, taxrank = 'Phylum') -percentages_df <- psmelt(percentages_glom) -percentages_df$Phylum <- as.factor(percentages_df$Phylum) -phylum_colors_rel<- colorRampPalette(brewer.pal(8,"Dark2")) (length(levels(percentages_df$Phylum))) -relative_plot <- ggplot(data=percentages_df, aes(x=Sample, y=Abundance, fill=Phylum))+ - geom_bar(aes(), stat="identity", position="stack")+ - scale_fill_manual(values = phylum_colors_rel) - -wide_percentages_df <- percentages_df %>% - select(OTU, Sample, Abundance, Kingdom, Phylum) %>% - tidyr::pivot_wider( - names_from = Sample, - values_from = Abundance, - values_fill = 0 - ) - -write.csv(wide_percentages_df, "./results/phylum_relative_abundances.csv", row.names = FALSE) -ggsave("./results/phylum_relative_abundances.pdf", relative_plot, width = 10, height = 6) diff --git a/tasks/metagenomics/run_script.sh b/tasks/metagenomics/run_script.sh deleted file mode 100755 index 40ac6b0..0000000 --- a/tasks/metagenomics/run_script.sh +++ /dev/null @@ -1,181 +0,0 @@ -#!/bin/bash -set -e - -# Set dynamic thread count -THREADS=$(nproc) - -# Logging functions -TOTAL_STEPS=8 -CURRENT_STEP=0 - -log_step() { - CURRENT_STEP=$((CURRENT_STEP + 1)) - echo "==================================================================" - echo "STEP $CURRENT_STEP/$TOTAL_STEPS: $1" - echo "==================================================================" - echo "Started at: $(date)" - echo "" -} - -log_substep() { - echo " → $1" -} - -log_completion() { - echo "" - echo "Completed at: $(date)" - echo "" -} - -env_exists() { - local env_name=$1 - mamba env list | grep -q "^${env_name} " -} - -# STEP 1: Environment Setup -log_step "Setting up conda environments" - -if ! env_exists "metagenomics"; then - log_substep "Creating metagenomics environment" - mamba env create -f environment.yml -y -fi - -log_completion - -# Create directory structure -mkdir -p data -mkdir -p outputs/0_fastqc -mkdir -p outputs/1_trimmed -mkdir -p outputs/2_fastqc -mkdir -p outputs/3_assembly -mkdir -p outputs/4_taxonomy -mkdir -p outputs/5_biom -mkdir -p results -mkdir -p data/reference - -# STEP 2: Data Download -log_step "Downloading metagenomics data" - -log_substep "Downloading data" -if [ ! -f "data/metagenomics.zip" ]; then - wget -O data/metagenomics.zip https://zenodo.org/records/7010950/files/dc_workshop.zip -fi - -log_substep "Downloading metadata" -if [ ! -f "data/MGRAST_MetaData_JP.xlsx" ]; then - wget -O data/MGRAST_MetaData_JP.xlsx https://zenodo.org/records/7010950/files/MGRAST_MetaData_JP.xlsx -fi - -log_substep "Downloading Kraken2 standard database" -if [ ! -f "data/k2_standard_16gb_20241228.tar.gz" ]; then - wget -v -O data/k2_standard_16gb_20241228.tar.gz https://genome-idx.s3.amazonaws.com/kraken/k2_standard_16gb_20241228.tar.gz -fi - -log_substep "Extracting data" -unzip data/metagenomics.zip -d data/ - -log_substep "Moving extracted files to expected locations" -mv data/dc_workshop/data/untrimmed_fastq data/ - -log_substep "Extracting Kraken2 database" -if [ ! -d "data/reference/hash.k2d" ]; then - tar -xvf data/k2_standard_16gb_20241228.tar.gz -C data/reference -fi - -log_completion - -# STEP 3: Initial Quality Control -log_step "Initial quality control with FastQC" - -log_substep "Running FastQC on raw reads" -mamba run -n metagenomics fastqc data/untrimmed_fastq/*fastq.gz -o outputs/0_fastqc -t $THREADS - -log_completion - -# STEP 4: Read Trimming -log_step "Trimming reads with Trimmomatic" - -log_substep "Decompressing FASTQ files" -for file in data/untrimmed_fastq/*.fastq.gz; do - gunzip -k $file -done - -log_substep "Trimming paired-end reads" -for file in data/untrimmed_fastq/*_R1.fastq; do - base=$(basename "$file" _R1.fastq) - log_substep "Processing sample: $base" - mamba run -n metagenomics trimmomatic PE -threads $THREADS \ - data/untrimmed_fastq/${base}_R1.fastq \ - data/untrimmed_fastq/${base}_R2.fastq \ - outputs/1_trimmed/${base}_1P.fastq \ - outputs/1_trimmed/${base}_1U.fastq \ - outputs/1_trimmed/${base}_2P.fastq \ - outputs/1_trimmed/${base}_2U.fastq \ - SLIDINGWINDOW:4:20 MINLEN:35 ILLUMINACLIP:data/untrimmed_fastq/TruSeq3-PE.fa:2:40:15 -done - -log_completion - -# STEP 5: Post-trimming Quality Control -log_step "Post-trimming quality control" - -log_substep "Running FastQC on trimmed reads" -mamba run -n metagenomics fastqc outputs/1_trimmed/*.fastq -o outputs/2_fastqc -t $THREADS - -log_substep "Generating MultiQC report" -mamba run -n metagenomics multiqc outputs/2_fastqc -o outputs/2_fastqc - -log_completion - -# STEP 6: Metagenomic Assembly -log_step "Metagenomic assembly with SPAdes" - -log_substep "Assembling JC1A sample" -mamba run -n metagenomics metaspades.py -1 outputs/1_trimmed/JC1A_1P.fastq \ - -2 outputs/1_trimmed/JC1A_2P.fastq \ - -o outputs/3_assembly/assembly_JC1A \ - -t $THREADS - -log_substep "Assembling JP4D sample" -mamba run -n metagenomics metaspades.py -1 outputs/1_trimmed/JP4D_1P.fastq \ - -2 outputs/1_trimmed/JP4D_2P.fastq \ - -o outputs/3_assembly/assembly_JP4D \ - -t $THREADS - -log_completion - -# STEP 7: Taxonomic Classification -log_step "Taxonomic classification with Kraken2" - -log_substep "Classifying JC1A assembly" -mamba run -n metagenomics kraken2 --db data/reference --threads $THREADS \ - outputs/3_assembly/assembly_JC1A/contigs.fasta \ - --output "outputs/4_taxonomy/JC1A.kraken" \ - --report "outputs/4_taxonomy/JC1A.report" - -log_substep "Classifying JP4D assembly" -mamba run -n metagenomics kraken2 --db data/reference --threads $THREADS \ - outputs/3_assembly/assembly_JP4D/contigs.fasta \ - --output "outputs/4_taxonomy/JP4D.kraken" \ - --report "outputs/4_taxonomy/JP4D.report" - -log_substep "Converting to BIOM format" -mamba run -n metagenomics kraken-biom outputs/4_taxonomy/JC1A.report \ - outputs/4_taxonomy/JP4D.report \ - --fmt json -o outputs/5_biom/cuatroc.biom - -log_completion - -# STEP 8: Phyloseq Analysis -log_step "Running phyloseq analysis" - -log_substep "Executing R phyloseq script" -mamba run -n metagenomics Rscript run_phyloseq.R - -log_completion - -echo "==================================================================" -echo "METAGENOMICS PIPELINE COMPLETED SUCCESSFULLY" -echo "==================================================================" -echo "Results are available in results/" -echo "Completed at: $(date)" \ No newline at end of file diff --git a/tasks/single-cell/Dockerfile b/tasks/single-cell/Dockerfile deleted file mode 100644 index 3507ec2..0000000 --- a/tasks/single-cell/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -FROM condaforge/mambaforge:24.9.2-0 - -WORKDIR /app - -COPY run_script.sh /app/ -COPY environment.yml /app/ -COPY run_analysis.py /app/ - -RUN mamba init bash && \ - . ~/.bashrc && \ - mamba env create -f environment.yml && \ - chmod +x /app/run_script.sh - - -SHELL ["/bin/bash", "--login", "-c"] - -CMD ["/app/run_script.sh"] diff --git a/tasks/single-cell/environment.yml b/tasks/single-cell/environment.yml deleted file mode 100644 index 0c686c5..0000000 --- a/tasks/single-cell/environment.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: single-cell -channels: - - conda-forge - - bioconda - - defaults -dependencies: - - scanpy - - leidenalg - - pandas - - numpy - - anndata - - matplotlib - - seaborn - - scikit-learn - - scipy - - python-igraph - - openpyxl - - pip - - pip: - - gzip-reader \ No newline at end of file diff --git a/tasks/single-cell/run_analysis.py b/tasks/single-cell/run_analysis.py deleted file mode 100644 index 66826ce..0000000 --- a/tasks/single-cell/run_analysis.py +++ /dev/null @@ -1,584 +0,0 @@ -import os -import sys -import json -from pathlib import Path -from typing import List, Dict, Tuple - -import numpy as np -import pandas as pd -import scipy.sparse as sp - -import matplotlib.pyplot as plt -import seaborn as sns - -from sklearn.metrics import silhouette_score - -import scanpy as sc -import anndata as an - -# Configure matplotlib to save plots instead of showing them -plt.ioff() # Turn off interactive mode - - -def load_local_scRNA_data(samples: List[Dict[str, str]], data_dir: str = "./data") -> an.AnnData: - """Loads and processes scRNA-seq data files from local directory into a single AnnData object.""" - data_path = Path(data_dir) - - if not data_path.exists(): - raise FileNotFoundError(f"Data directory {data_dir} does not exist") - - adatas = [] - labels = [] - - for sample in samples: - # Extract sample info - file_prefix = sample['file_prefix'] - label = sample['label'] - - # Define file paths - files = { - 'matrix': f"{file_prefix}_matrix.mtx", - 'barcodes': f"{file_prefix}_barcodes.tsv", - 'features': f"{file_prefix}_features.tsv" - } - file_paths = {k: data_path / v for k, v in files.items()} - - # Check if all files exist - for file_type, file_path in file_paths.items(): - if not file_path.exists(): - raise FileNotFoundError(f"Required file {file_path} not found") - - print(f"Loading sample {label} from {file_prefix}") - - # Create AnnData object - adata = sc.read_mtx(file_paths['matrix']).T - - # Add barcodes with unique sample prefix - barcodes = pd.read_csv(file_paths['barcodes'], header=None)[0] - adata.obs_names = [f"{label}_{bc}" for bc in barcodes] - - # Add feature information - features = pd.read_csv(file_paths['features'], sep='\t', header=None) - adata.var_names = features[0] # Ensembl IDs - adata.var['gene_ids'] = features[1].values # Gene symbols - - # Add feature types if available - if features.shape[1] > 2: - adata.var['feature_type'] = features[2].values - - # Add sample metadata - for k, v in sample.items(): - if k not in ['accession', 'file_prefix']: - adata.obs[k] = v - - adatas.append(adata) - labels.append(label) - - # Combine AnnData objects - adata_combined = an.concat(adatas, axis=0, join='outer', label='batch', keys=labels) - - # Make observation names unique - adata_combined.obs_names_make_unique() - - # Use gene symbols instead of Ensembl IDs - features_file = data_path / f"{samples[0]['file_prefix']}_features.tsv" - features_df = pd.read_csv(features_file, sep='\t', header=None) - ensembl_to_symbol = dict(zip(features_df[0], features_df[1])) - adata_combined.var_names = [ensembl_to_symbol.get(id, id) for id in adata_combined.var_names] - adata_combined.var_names_make_unique() - - # Identify mitochondrial genes - adata_combined.var['mt'] = adata_combined.var_names.str.startswith('MT-') - - print(f"Created AnnData object with {adata_combined.shape[0]} cells and {adata_combined.shape[1]} genes") - return adata_combined - -if __name__ == "__main__": - # Create output directories - os.makedirs("./outputs", exist_ok=True) - os.makedirs("./results", exist_ok=True) - - # Define sample metadata - samples = [ - {'accession': 'GSM6611295', 'file_prefix': 'GSM6611295_P15306_5001', 'condition': 'pre', 'subject': '1', 'label': 'subject1_pre'}, - {'accession': 'GSM6611296', 'file_prefix': 'GSM6611296_P15306_5002', 'condition': 'post', 'subject': '1', 'label': 'subject1_post'}, - {'accession': 'GSM6611297', 'file_prefix': 'GSM6611297_P14601_4004', 'condition': 'pre', 'subject': '2', 'label': 'subject2_pre'}, - {'accession': 'GSM6611298', 'file_prefix': 'GSM6611298_P14601_4005', 'condition': 'post', 'subject': '2', 'label': 'subject2_post'}, - {'accession': 'GSM6611299', 'file_prefix': 'GSM6611299_P15306_5003', 'condition': 'pre', 'subject': '3', 'label': 'subject3_pre'}, - {'accession': 'GSM6611300', 'file_prefix': 'GSM6611300_P15306_5004', 'condition': 'post', 'subject': '3', 'label': 'subject3_post'}] - - # Load data from local directory - adata = load_local_scRNA_data(samples) - -num_genes = adata.n_vars # variables = columns (genes) -print(f"Number of Genes: {num_genes}") - -num_cells = adata.n_obs # observations = rows (cells IDs) -print(f"Number of Cells: {num_cells}") - -# Check for NaN values (with handling for sparse matrices) -if sp.issparse(adata.X): - print("Sparse matrix detected, checking for invalid values in non-zero elements...") - if np.isnan(adata.X.data).any(): - print(f"Number of NaNs in non-zero elements: {np.sum(np.isnan(adata.X.data))}") - else: - print("No NaN values found in non-zero elements.") -else: - nan_rows = np.isnan(adata.X).any(axis=1) - nan_cols = np.isnan(adata.X).any(axis=0) - print(f"Number of rows with NaN values: {np.sum(nan_rows)}") - print(f"Number of columns with NaN values: {np.sum(nan_cols)}") - -# Calculate comprehensive QC metrics -sc.pp.calculate_qc_metrics(adata, qc_vars=[], percent_top=None, log1p=False, inplace=True) - -# Identify and calculate mitochondrial content -mt_gene_mask = adata.var_names.str.startswith(('MT-', 'mt-')) -mt_count = np.sum(mt_gene_mask) -print(f"Found {mt_count} mitochondrial genes") - -if mt_count > 0: - adata.var['mt'] = mt_gene_mask - sc.pp.calculate_qc_metrics(adata, qc_vars=['mt'], percent_top=None, log1p=False, inplace=True) - print("Mitochondrial metrics calculated.") -else: - print("No mitochondrial genes found with standard prefixes.") - adata.obs['pct_counts_mt'] = 0 - -# Visualize QC metrics with improved plots -fig, axes = plt.subplots(2, 2, figsize=(16, 12)) - -# Plot 1: Distribution of genes per cell -sns.histplot(adata.obs['n_genes_by_counts'], bins=50, kde=True, ax=axes[0, 0]) -axes[0, 0].set_xlabel('Number of Genes per Cell') -axes[0, 0].set_ylabel('Number of Cells') -axes[0, 0].set_title('Distribution of Number of Genes per Cell') -axes[0, 0].axvline(200, color='red', linestyle='--', label='Filter threshold (200)') -axes[0, 0].legend() - -# Plot 2: Distribution of UMI counts per cell -sns.histplot(adata.obs['total_counts'], bins=50, kde=True, ax=axes[0, 1]) -axes[0, 1].set_xlabel('Total UMI Counts per Cell') -axes[0, 1].set_ylabel('Number of Cells') -axes[0, 1].set_title('Distribution of UMI Counts per Cell') -axes[0, 1].set_xscale('log') - -# Plot 3: Distribution of mitochondrial gene percentage -sns.histplot(adata.obs['pct_counts_mt'], bins=50, kde=True, ax=axes[1, 0]) -axes[1, 0].set_xlabel('Percentage of Mitochondrial Genes') -axes[1, 0].set_ylabel('Number of Cells') -axes[1, 0].set_title('Distribution of Mitochondrial Gene % per Cell') -axes[1, 0].axvline(20, color='red', linestyle='--', label='Typical threshold (20%)') -axes[1, 0].legend() - -# Plot 4: Scatter plot of UMI count vs genes per cell, colored by mito percent -scatter = axes[1, 1].scatter(adata.obs['total_counts'], adata.obs['n_genes_by_counts'], c=adata.obs['pct_counts_mt'], cmap='viridis', s=10, alpha=0.7) -axes[1, 1].set_xlabel('Total UMI Counts per Cell') -axes[1, 1].set_ylabel('Number of Genes per Cell') -axes[1, 1].set_title('Genes vs UMIs, Colored by Mito%') -axes[1, 1].set_xscale('log') -cbar = plt.colorbar(scatter, ax=axes[1, 1]) -cbar.set_label('Mitochondrial %') -plt.tight_layout() -plt.savefig('./outputs/qc_metrics_overview.png', dpi=300, bbox_inches='tight') -plt.close() - -# Visualize QC metrics by sample to identify batch effects -fig, axes = plt.subplots(1, 3, figsize=(18, 6)) - -# UMI counts by batch -sc.pl.violin(adata, 'total_counts', groupby='batch', ax=axes[0], show=False) -axes[0].set_title('UMI Counts by Sample') -axes[0].set_ylabel('Total UMI Counts') -axes[0].set_yscale('log') - -# Genes per cell by batch -sc.pl.violin(adata, 'n_genes_by_counts', groupby='batch', ax=axes[1], show=False) -axes[1].set_title('Genes per Cell by Sample') -axes[1].set_ylabel('Number of Genes') - -# Mitochondrial % by batch -sc.pl.violin(adata, 'pct_counts_mt', groupby='batch', ax=axes[2], show=False) -axes[2].set_title('Mitochondrial % by Sample') -axes[2].set_ylabel('Mitochondrial %') -plt.tight_layout() -plt.savefig('./outputs/qc_metrics_by_sample.png', dpi=300, bbox_inches='tight') -plt.close() - -# Set filtering thresholds based on QC metrics -min_genes = 300 # Minimum genes per cell -min_cells = 20 # Minimum cells per gene -max_mito = 15 # Maximum percentage of mitochondrial genes (adjust based on your data) -min_counts = 1000 # Minimum UMI counts per cell -max_counts = 15000 # Maximum UMI counts - -print(f"Before filtering: {adata.n_obs} cells, {adata.n_vars} genes") - -# Filter cells based on QC metrics -adata_filtered = adata[(adata.obs['n_genes_by_counts'] >= min_genes) & (adata.obs['pct_counts_mt'] <= max_mito)] - -if min_counts: - adata_filtered = adata_filtered[adata_filtered.obs['total_counts'] >= min_counts] - -if max_counts: - adata_filtered = adata_filtered[adata_filtered.obs['total_counts'] <= max_counts] - -# Filter genes based on minimum cells -sc.pp.filter_genes(adata_filtered, min_cells=min_cells) -print(f"After filtering: {adata_filtered.n_obs} cells, {adata_filtered.n_vars} genes") - -# Normalization and log transformation -print("Normalizing data...") -sc.pp.normalize_total(adata_filtered, target_sum=1e4) -sc.pp.log1p(adata_filtered) - -# Highly variable gene selection with improved parameters -print("Identifying highly variable genes...") -sc.pp.highly_variable_genes(adata_filtered, n_top_genes=2000, subset=True) - -# apply z-transformation -sc.pp.scale(adata_filtered, zero_center=True) -# perform dimensionality reduction via PCA -sc.tl.pca(adata_filtered, svd_solver='arpack') - -# construct graph of nearest neighbors -sc.pp.neighbors(adata_filtered, n_neighbors=20, n_pcs=30) -# apply leiden clustering algorithm -sc.tl.leiden(adata_filtered, key_added='clusters', resolution=0.3, n_iterations=3, flavor='igraph', directed=False) -# create and visualize UMAP -sc.tl.umap(adata_filtered) -sc.pl.umap(adata_filtered, color='clusters', add_outline=True, legend_loc='on data', legend_fontsize=12, legend_fontoutline=2, frameon=True, save='_clusters.pdf', show=False) -plt.savefig('./outputs/umap_clusters.png', dpi=300, bbox_inches='tight') -plt.close() - -labels = adata_filtered.obs['clusters'] -sil_score = silhouette_score(adata_filtered.obsm['X_pca'], labels) -print(f'Silhouette Score: {sil_score}') - -sc.tl.rank_genes_groups(adata_filtered, groupby='clusters', method='wilcoxon', corr_method='bonferroni') -top_markers = sc.get.rank_genes_groups_df(adata_filtered, group=None) -top_markers_df = pd.DataFrame(top_markers) - -# initialize a dictionary to store top markers for each cluster -top_genes_per_cluster = {} -# store list of clusters -clusters = adata_filtered.uns['rank_genes_groups']['names'].dtype.names -# iterate over each cluster to get top markers and store them in top_genes_per_cluster dictioary -for cluster in clusters: - top_genes = top_markers_df[top_markers_df['group'] == cluster].head(3) - top_genes_per_cluster[cluster] = top_genes -# convert dictionary to data frame -top_genes_summary = pd.concat(top_genes_per_cluster.values(), keys=top_genes_per_cluster.keys()) -print(top_genes_summary) - -def annotate_with_custom_db(adata, top_n=50): - """ - Annotate clusters using the CellMarker database from xlsx file - """ - print("Starting CellMarker database annotation...") - - # Load the CellMarker database - try: - import pandas as pd - cellmarker_df = pd.read_excel('./reference/Cell_marker_Seq.xlsx') - print(f"Loaded CellMarker database with {len(cellmarker_df)} records and {cellmarker_df['cell_name'].nunique()} unique cell types") - except Exception as e: - print(f"Error loading CellMarker database: {e}") - return {} - - # Create cell marker database structured for efficient lookup - cell_markers = {} - marker_to_celltype = {} - - # Group markers by cell type - for _, row in cellmarker_df.iterrows(): - cell_type = row['cell_name'] - marker = row['marker'] - - # Skip rows with missing data - if pd.isna(cell_type) or pd.isna(marker): - continue - - # Clean up marker names (remove special characters, whitespace) - marker = str(marker).strip().replace('\xa0', '').upper() - - # Add to cell_markers dictionary - if cell_type not in cell_markers: - cell_markers[cell_type] = [] - if marker not in cell_markers[cell_type]: - cell_markers[cell_type].append(marker) - - # Add to reverse lookup - if marker not in marker_to_celltype: - marker_to_celltype[marker] = [] - if cell_type not in marker_to_celltype[marker]: - marker_to_celltype[marker].append(cell_type) - - - print(f"Marker database contains {len(marker_to_celltype)} unique genes across {len(cell_markers)} cell types") - - # Get clusters - clusters = adata.uns['rank_genes_groups']['names'].dtype.names - cluster_annotations = {} - print(f"Annotating {len(clusters)} clusters...") - - # Process each cluster - for cluster in clusters: - print(f"Processing cluster {cluster}") - # Get top markers for this cluster - top_markers = [] - for i in range(min(top_n, len(adata.uns['rank_genes_groups']['names'][cluster]))): - marker = adata.uns['rank_genes_groups']['names'][cluster][i] - score = adata.uns['rank_genes_groups']['scores'][cluster][i] - pval = adata.uns['rank_genes_groups']['pvals'][cluster][i] - if pval < 0.05: # Only consider statistically significant markers - top_markers.append((marker, score, i)) - - # Match markers to cell types (case-insensitive matching) - cell_type_matches = {} - for marker, score, rank in top_markers: - marker_upper = marker.upper() - if marker_upper in marker_to_celltype: - for cell_type in marker_to_celltype[marker_upper]: - if cell_type not in cell_type_matches: - cell_type_matches[cell_type] = [] - # Store marker, score, and rank - cell_type_matches[cell_type].append((marker, score, rank)) - - # Score cell types (weighted by marker rank and score) - cell_type_scores = {} - for cell_type, matches in cell_type_matches.items(): - # Calculate a combined score based on: - # 1. Number of markers - # 2. Rank of markers (earlier = better) - # 3. Score of markers (higher = better) - score = sum([m[1] * (1 - m[2]/top_n) for m in matches]) - # Also consider the proportion of cell type markers found - proportion = len(matches) / len(cell_markers[cell_type]) - final_score = score * (1 + proportion) - cell_type_scores[cell_type] = (final_score, [m[0] for m in matches]) - - # Get top cell types - sorted_cell_types = sorted(cell_type_scores.items(), key=lambda x: x[1][0], reverse=True) - - if sorted_cell_types: - # Take the top match only (use the exact cell_name from xlsx) - top_cell_type = sorted_cell_types[0][0] - cluster_annotations[cluster] = top_cell_type - else: - # If no matches, use top marker genes - markers = [m[0] for m in top_markers[:3]] if top_markers else ["No significant markers"] - cluster_annotations[cluster] = f"Unknown (Top genes: {', '.join(markers)})" - - # Add annotations to adata - adata.obs['custom_cell_type'] = adata.obs['clusters'].map(cluster_annotations) - print("Cell type annotation complete.") - return cluster_annotations - -# Run the annotation function -cluster_annotations = annotate_with_custom_db(adata_filtered) - -# Print the cluster annotations -print("\nCluster Annotations:") -for cluster, annotation in cluster_annotations.items(): - print(f"Cluster {cluster}: {annotation}") - -# Visualize the annotated clusters on UMAP -sc.pl.umap(adata_filtered, color='custom_cell_type', legend_loc='on data', - legend_fontsize=8, title='Cell Types (Custom DB)', save='_cell_types.pdf', show=False) -plt.savefig('./outputs/umap_cell_types.png', dpi=300, bbox_inches='tight') -plt.close() - -# Also visualize the clusters with their numeric IDs for reference -sc.pl.umap(adata_filtered, color='clusters', legend_loc='on data', - legend_fontsize=10, title='Cluster IDs', save='_cluster_ids.pdf', show=False) -plt.savefig('./outputs/umap_cluster_ids.png', dpi=300, bbox_inches='tight') -plt.close() - -# get the counts of cells in each cluster -cluster_counts = adata_filtered.obs['clusters'].value_counts() - -# calculate the total number of cells -total_cells = len(adata_filtered.obs) - -# calculate the percentage of cells in each cluster -cluster_percentages = (cluster_counts / total_cells) * 100 - -# display the results -print("\nPercentage of cells in each cluster:") -print(cluster_percentages) - -# Create a function to visualize top marker genes for all clusters -def visualize_top_markers(adata, n_genes=10): - # Get results for each cluster - cluster_markers = {} - - for cluster in adata.obs['clusters'].unique(): - # Get top markers for this cluster - markers = pd.DataFrame( - { - 'names': adata.uns['rank_genes_groups']['names'][cluster][:n_genes], - 'scores': adata.uns['rank_genes_groups']['scores'][cluster][:n_genes], - 'pvals': adata.uns['rank_genes_groups']['pvals'][cluster][:n_genes], - 'pvals_adj': adata.uns['rank_genes_groups']['pvals_adj'][cluster][:n_genes]}) - cluster_markers[cluster] = markers - - # Get unique top markers across all clusters - all_markers = [] - for cluster, markers in cluster_markers.items(): - all_markers.extend(markers['names'].tolist()) - - # Remove duplicates while preserving order - unique_markers = [] - seen = set() - for marker in all_markers: - if marker not in seen: - unique_markers.append(marker) - seen.add(marker) - - # Limit to a reasonable number for visualization - if len(unique_markers) > 50: - unique_markers = unique_markers[:50] - - # Create dotplot of marker genes - sc.pl.dotplot(adata, unique_markers, groupby='clusters', dendrogram=True, save='_marker_genes.pdf', show=False) - plt.savefig('./outputs/dotplot_marker_genes.png', dpi=300, bbox_inches='tight') - plt.close() - - # Create heatmap - sc.pl.heatmap(adata, unique_markers, groupby='clusters', - swap_axes=True, show_gene_labels=True, - vmin=-2, vmax=2, cmap='viridis', save='_marker_heatmap.pdf', show=False) - plt.savefig('./outputs/heatmap_marker_genes.png', dpi=300, bbox_inches='tight') - plt.close() - return cluster_markers - -cluster_markers = visualize_top_markers(adata_filtered, n_genes=10) - -def intra_cluster_de_analysis(adata, cluster_key='clusters', condition_key='condition', pval_cutoff=0.05, min_cells=3): - print(f"Performing differential expression analysis between conditions for each cluster") - - # Check that we have exactly 2 conditions - conditions = adata.obs[condition_key].unique() - if len(conditions) != 2: - raise ValueError(f"Expected exactly 2 conditions, but found {len(conditions)}") - - condition_a, condition_b = conditions - print(f"Comparing '{condition_b}' vs '{condition_a}' (reference) for each cluster") - - # Dictionary to store results - results_dict = {} - - # For each cluster, perform DE analysis between conditions - for cluster in adata.obs[cluster_key].unique(): - print(f"\nAnalyzing cluster {cluster}...") - - # Subset data to cells from this cluster - cluster_adata = adata[adata.obs[cluster_key] == cluster].copy() - - # Check if we have cells from both conditions in this cluster - condition_counts = cluster_adata.obs[condition_key].value_counts() - - # Get counts safely - count_a = condition_counts.get(condition_a, 0) - count_b = condition_counts.get(condition_b, 0) - - print(f" Cells: {count_a} {condition_a}, {count_b} {condition_b}") - - # Skip if any condition has fewer than min_cells - if count_a < min_cells or count_b < min_cells: - print(f" Skipping - insufficient cells in at least one condition (minimum {min_cells} required)") - continue - - # Perform DE analysis - try: - sc.tl.rank_genes_groups(cluster_adata, groupby=condition_key, groups=[condition_b], reference=condition_a, method='wilcoxon', corr_method='bonferroni') - - # Extract results to dataframe - de_results = sc.get.rank_genes_groups_df(cluster_adata, group=condition_b) - - # Filter for significant genes - sig_results = de_results[de_results['pvals_adj'] < pval_cutoff] - - # Handle results - if not sig_results.empty: - # Handle possible NaN values in logfoldchanges - sig_results = sig_results.dropna(subset=['logfoldchanges']) - - if not sig_results.empty: - sig_results['direction'] = sig_results['logfoldchanges'].apply( - lambda x: 'up' if x > 0 else 'down') - sig_results['abs_logfc'] = abs(sig_results['logfoldchanges']) - - # Count up/down regulated genes - n_up = sum(sig_results['direction'] == 'up') - n_down = sum(sig_results['direction'] == 'down') - - print(f" Found {len(sig_results)} significant DE genes (adj p < {pval_cutoff})") - print(f" {n_up} upregulated in {condition_b}, {n_down} downregulated in {condition_b}") - - # Store results - results_dict[cluster] = sig_results.sort_values('abs_logfc', ascending=False) - else: - print(f" No genes with valid fold changes in cluster {cluster}") - results_dict[cluster] = None - else: - print(f" No significantly differentially expressed genes found in cluster {cluster}") - results_dict[cluster] = None - - except ValueError as e: - print(f" Error: {e}") - results_dict[cluster] = None - - return results_dict - -# Execute the analysis with minimum cell count requirement -# Note: the condition column in samples.json is called 'condition' and contains 'pre-exercise' and 'post-exercise' -de_dict = intra_cluster_de_analysis(adata_filtered, condition_key='condition', min_cells=5) - -# Save individual cluster results to outputs -for cluster, results in de_dict.items(): - if results is not None and not results.empty: - results.to_csv(f'./outputs/cluster_{cluster}_de_genes.csv', index=False) - # Print top DE genes for each cluster - print(f"\nTop 5 DE genes for cluster {cluster}:") - print(results[['names', 'logfoldchanges', 'pvals_adj', 'direction']].head(5)) - -# Create the final collated CSV for results directory -print("\nCreating final results CSV...") -annotations = cluster_annotations - -# COLLATE to single CSV: all_clusters_de_genes.csv -# Columns required: -# cluster_id,predicted_cell_type,gene_name,logfoldchanges,pvals,pvals_adj,direction,abs_logfc -rows = [] -for cl, df in de_dict.items(): - pred = annotations.get(str(cl), "Unknown") - if df is None or df.empty: - continue - # df columns from scanpy: ['names', 'scores', 'logfoldchanges', 'pvals', 'pvals_adj', ...] - sub = df[["names", "logfoldchanges", "pvals", "pvals_adj", "direction", "abs_logfc"]].copy() - sub.insert(0, "predicted_cell_type", pred) - sub.insert(0, "cluster_id", str(cl)) - sub.rename(columns={"names": "gene_name"}, inplace=True) - rows.append(sub) - -if rows: - out_df = pd.concat(rows, axis=0, ignore_index=True) -else: - out_df = pd.DataFrame(columns=[ - "cluster_id", "predicted_cell_type", "gene_name", - "logfoldchanges", "pvals", "pvals_adj", "direction", "abs_logfc" - ]) - -out_csv = Path("./results") / "all_clusters_de_genes.csv" -out_df.to_csv(out_csv, index=False) -print(f"[ok] Wrote {out_csv}") - -# Save QC summary to outputs -qc_summary = pd.DataFrame({ - 'metric': ['total_cells', 'total_genes', 'silhouette_score'], - 'value': [adata_filtered.n_obs, adata_filtered.n_vars, sil_score] -}) -qc_summary.to_csv("./outputs/qc_summary.csv", index=False) -print("[ok] Wrote ./outputs/qc_summary.csv") \ No newline at end of file diff --git a/tasks/single-cell/run_script.sh b/tasks/single-cell/run_script.sh deleted file mode 100755 index 7f984f4..0000000 --- a/tasks/single-cell/run_script.sh +++ /dev/null @@ -1,74 +0,0 @@ -#!/bin/bash -set -e - -mkdir -p ./data -mkdir -p ./reference -mkdir -p ./results - -echo "Downloading scRNA-seq data files..." - -declare -a samples=( - "GSM6611295:GSM6611295_P15306_5001" - "GSM6611296:GSM6611296_P15306_5002" - "GSM6611297:GSM6611297_P14601_4004" - "GSM6611298:GSM6611298_P14601_4005" - "GSM6611299:GSM6611299_P15306_5003" - "GSM6611300:GSM6611300_P15306_5004" -) - -download_and_decompress() { - local accession=$1 - local file_prefix=$2 - local file_type=$3 - local ext=$4 - - local gz_file="./data/${file_prefix}_${file_type}.${ext}.gz" - local target_file="./data/${file_prefix}_${file_type}.${ext}" - - if [ -f "$target_file" ]; then - echo "File $target_file already exists, skipping download" - return - fi - - if [ ! -f "$gz_file" ]; then - local encoded_prefix=$(echo "$file_prefix" | sed 's/_/%5F/g' | sed 's/\./%2E/g') - local url="https://www.ncbi.nlm.nih.gov/geo/download/?acc=${accession}&format=file&file=${encoded_prefix}%5F${file_type}.${ext}.gz" - - echo "Downloading ${file_type} file for ${accession}..." - curl -L -o "$gz_file" "$url" - - if [ $? -ne 0 ]; then - echo "Error downloading $gz_file" - exit 1 - fi - fi - - echo "Decompressing $gz_file..." - gunzip -f "$gz_file" -} - -for sample in "${samples[@]}"; do - IFS=':' read -r accession file_prefix <<< "$sample" - - echo "Processing sample: $accession ($file_prefix)" - - download_and_decompress "$accession" "$file_prefix" "matrix" "mtx" - download_and_decompress "$accession" "$file_prefix" "barcodes" "tsv" - download_and_decompress "$accession" "$file_prefix" "features" "tsv" -done - -echo "Data download completed!" - -echo "Downloading cell marker database..." -if [ ! -f "./reference/Cell_marker_Seq.xlsx" ]; then - curl -L -o "./reference/Cell_marker_Seq.xlsx" "http://www.bio-bigdata.center/CellMarker_download_files/file/Cell_marker_Seq.xlsx" - if [ $? -ne 0 ]; then - echo "Error downloading cell marker database" - exit 1 - fi - echo "Cell marker database downloaded successfully!" -else - echo "Cell marker database already exists, skipping download" -fi - -python run_analysis.py \ No newline at end of file diff --git a/tasks/transcript-quant/Dockerfile b/tasks/transcript-quant/Dockerfile deleted file mode 100644 index fd2cd67..0000000 --- a/tasks/transcript-quant/Dockerfile +++ /dev/null @@ -1,24 +0,0 @@ -# Use a base image with conda -FROM continuumio/miniconda3:latest - -RUN apt-get update && apt-get install -y wget && rm -rf /var/lib/apt/lists/* -WORKDIR /app - -RUN mkdir -p /app/data -RUN wget -O /app/data/data.tar.gz "https://osf.io/download/684fefc97139f9f5536df7a8/" - -RUN cd /app/data && tar -xzf data.tar.gz && rm data.tar.gz - -# Copy the script -COPY run_script.sh /app/ -COPY environment.yml /app/ -RUN chmod +x /app/run_script.sh - -# Create and activate the conda environment with salmon -RUN conda env create -f environment.yml && \ - echo "source activate t-quant" > ~/.bashrc - -# Make sure conda environment is activated -SHELL ["conda", "run", "-n", "t-quant", "/bin/bash", "-c"] -ENTRYPOINT ["conda", "run", "-n", "t-quant"] -CMD ["./run_script.sh"] \ No newline at end of file diff --git a/tasks/transcript-quant/environment.yml b/tasks/transcript-quant/environment.yml deleted file mode 100644 index 54b7072..0000000 --- a/tasks/transcript-quant/environment.yml +++ /dev/null @@ -1,7 +0,0 @@ -name: t-quant -channels: - - bioconda - - conda-forge -dependencies: - - fastqc=0.12.1 - - salmon=1.10.3 \ No newline at end of file diff --git a/tasks/transcript-quant/run_script.sh b/tasks/transcript-quant/run_script.sh deleted file mode 100755 index 3c86f88..0000000 --- a/tasks/transcript-quant/run_script.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash - -# Exit on error -set -e - -# Get number of available CPU threads -THREADS=$(nproc) - -# Create necessary directories -mkdir -p processing/index -mkdir -p processing/quant -mkdir -p results - -# Define input/output paths -TRANSCRIPTS="data/transcriptome.fa" -INDEX_DIR="processing/index" -QUANT_DIR="processing/quant" -READS1="data/reads_1.fq.gz" -READS2="data/reads_2.fq.gz" -FINAL_RESULTS="results/results.tsv" - -# Run Salmon index -echo "Running Salmon index..." -salmon index -t "$TRANSCRIPTS" -i "$INDEX_DIR" 2>&1 | tee "$INDEX_DIR/index.log" - -# Run Salmon quant -echo "Running Salmon quant..." -salmon quant \ - -i "$INDEX_DIR" \ - -l A \ - -p "$THREADS" \ - -1 "$READS1" \ - -2 "$READS2" \ - --validateMappings \ - -o "$QUANT_DIR" 2>&1 | tee "$QUANT_DIR/quant.log" - -# Process the quant.sf file to match the truth.tsv format -echo "Processing results..." -awk 'NR>1 {print $1 "\t" int($5)}' "$QUANT_DIR/quant.sf" > "$FINAL_RESULTS" - -echo "Analysis complete! Results saved to $FINAL_RESULTS" \ No newline at end of file diff --git a/tasks/viral-metagenomics/environment.yml b/tasks/viral-metagenomics/environment.yml deleted file mode 100644 index 242a421..0000000 --- a/tasks/viral-metagenomics/environment.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: viral-metagenomics -channels: - - bioconda - - conda-forge - - defaults -dependencies: - - fastp - - bowtie2 - - kaiju - - krona - - megahit - - prokka diff --git a/tasks/viral-metagenomics/run_script.sh b/tasks/viral-metagenomics/run_script.sh deleted file mode 100755 index dc075a4..0000000 --- a/tasks/viral-metagenomics/run_script.sh +++ /dev/null @@ -1,92 +0,0 @@ -#!/bin/bash - -# Get the absolute path of the script directory -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# Calculate optimal thread count (75% of available cores) -THREADS=$(( $(nproc) * 3 / 4 )) - -source ~/miniforge3/etc/profile.d/conda.sh -source ~/miniforge3/etc/profile.d/mamba.sh - -mamba env create -f "${SCRIPT_DIR}/environment.yml" || true -mamba activate viral-metagenomics - -# Create directory structure -mkdir -p "${SCRIPT_DIR}/data" -mkdir -p "${SCRIPT_DIR}/outputs" - -# Download input data -wget -O "${SCRIPT_DIR}/data/Dol1_S19_L001_R1_001.fastq.gz" https://osf.io/4x6qs/download -wget -O "${SCRIPT_DIR}/data/Dol1_S19_L001_R2_001.fastq.gz" https://osf.io/z2xed/download - -# Download reference data -mkdir -p "${SCRIPT_DIR}/data/reference" -wget -O "${SCRIPT_DIR}/data/reference/Tursiops_truncatus.turTru1.dna.toplevel.fa.gz" https://ftp.ensembl.org/pub/release-113/fasta/tursiops_truncatus/dna/Tursiops_truncatus.turTru1.dna.toplevel.fa.gz - -# 1. Trimming -mkdir -p "${SCRIPT_DIR}/outputs/1_trimming" -fastp -i "${SCRIPT_DIR}/data/Dol1_S19_L001_R1_001.fastq.gz" \ - -o "${SCRIPT_DIR}/outputs/1_trimming/Dol1_trimmed_R1.fastq" \ - -I "${SCRIPT_DIR}/data/Dol1_S19_L001_R2_001.fastq.gz" \ - -O "${SCRIPT_DIR}/outputs/1_trimming/Dol1_trimmed_R2.fastq" \ - --detect_adapter_for_pe --length_required 30 \ - --cut_front --cut_tail --cut_mean_quality 10 \ - --thread ${THREADS} - -# Prepare reference -gunzip -k "${SCRIPT_DIR}/data/reference/Tursiops_truncatus.turTru1.dna.toplevel.fa.gz" - -# 2. Indexing and 3. Mapping -mkdir -p "${SCRIPT_DIR}/outputs/2_indexing" -mkdir -p "${SCRIPT_DIR}/outputs/3_mapping" - -bowtie2-build "${SCRIPT_DIR}/data/reference/Tursiops_truncatus.turTru1.dna.toplevel.fa" \ - "${SCRIPT_DIR}/outputs/2_indexing/Tursiops_truncatus" \ - --threads ${THREADS} - -bowtie2 -x "${SCRIPT_DIR}/outputs/2_indexing/Tursiops_truncatus" \ - -1 "${SCRIPT_DIR}/outputs/1_trimming/Dol1_trimmed_R1.fastq" \ - -2 "${SCRIPT_DIR}/outputs/1_trimming/Dol1_trimmed_R2.fastq" \ - -S "${SCRIPT_DIR}/outputs/3_mapping/dol_map.sam" \ - --un-conc "${SCRIPT_DIR}/outputs/3_mapping/Dol_reads_unmapped.fastq" \ - --threads ${THREADS} - -# 4. Assembly -mkdir -p "${SCRIPT_DIR}/outputs/4_assembly" -megahit -1 "${SCRIPT_DIR}/outputs/3_mapping/Dol_reads_unmapped.1.fastq" \ - -2 "${SCRIPT_DIR}/outputs/3_mapping/Dol_reads_unmapped.2.fastq" \ - --num-cpu-threads ${THREADS} \ - -o "${SCRIPT_DIR}/outputs/4_assembly/megahit_out" - -# 5. Classification -mkdir -p "${SCRIPT_DIR}/outputs/5_classification" -cd "${SCRIPT_DIR}/outputs/5_classification" -wget https://kaiju-idx.s3.eu-central-1.amazonaws.com/2024/kaiju_db_viruses_2024-08-15.tgz -tar xzf kaiju_db_viruses_2024-08-15.tgz -rm kaiju_db_viruses_2024-08-15.tgz - -kaiju -t "${SCRIPT_DIR}/outputs/5_classification/nodes.dmp" \ - -f "${SCRIPT_DIR}/outputs/5_classification/kaiju_db_viruses.fmi" \ - -i "${SCRIPT_DIR}/outputs/4_assembly/megahit_out/final.contigs.fa" \ - -o "${SCRIPT_DIR}/outputs/5_classification/Dol1_contigs_kaiju.out" \ - -z ${THREADS} - -kaiju2krona -t "${SCRIPT_DIR}/outputs/5_classification/nodes.dmp" \ - -n "${SCRIPT_DIR}/outputs/5_classification/names.dmp" \ - -i "${SCRIPT_DIR}/outputs/5_classification/Dol1_contigs_kaiju.out" \ - -o "${SCRIPT_DIR}/outputs/5_classification/Dol1_contigs_kaiju.krona" \ - -u - -ktImportText -o "${SCRIPT_DIR}/outputs/5_classification/Dol1_contigs_kaiju.krona.html" \ - "${SCRIPT_DIR}/outputs/5_classification/Dol1_contigs_kaiju.krona" - -# Results -mkdir -p "${SCRIPT_DIR}/results" - -# Create viral taxonomy results -echo "contig_count,domain,species" > "${SCRIPT_DIR}/results/taxonomy.csv" -awk -F'\t' 'NF>1 { - species = $(NF); # Last column - if (NF == 1) species = "NA"; # Handle Unclassified case - print $1 "," $3 "," species -}' "${SCRIPT_DIR}/outputs/5_classification/Dol1_contigs_kaiju.krona" >> "${SCRIPT_DIR}/results/taxonomy.csv" \ No newline at end of file
diff --git a/tasks/alzheimer-mouse/environment.yml b/tasks/alzheimer-mouse/environment.yml
deleted file mode 100644
index 5d78096..0000000
--- a/tasks/alzheimer-mouse/environment.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-name: alzheimer-analysis
-channels:
- - bioconda
- - conda-forge
- - defaults
-dependencies:
- - pandas
- - numpy
- - mygene
- - scipy
- - statsmodels
- - requests
- - networkx
- - pip
- - pip:
- - gseapy
diff --git a/tasks/alzheimer-mouse/run_analysis.py b/tasks/alzheimer-mouse/run_analysis.py
deleted file mode 100644
index ee8ea99..0000000
--- a/tasks/alzheimer-mouse/run_analysis.py
+++ /dev/null
@@ -1,252 +0,0 @@
-import os
-import pandas as pd
-import numpy as np
-import mygene
-from scipy.stats import ttest_ind
-from statsmodels.stats.multitest import multipletests
-import gseapy as gp
-import requests
-import networkx as nx
-from io import StringIO
-import logging
-
-
-def setup_logging():
- """Configure logging settings"""
- os.makedirs("outputs", exist_ok=True)
- logging.basicConfig(
- level=logging.INFO,
- format='%(asctime)s - %(levelname)s - %(message)s',
- handlers=[
- logging.FileHandler('outputs/analysis.log'),
- logging.StreamHandler()
- ]
- )
-
-def annotate_genes(df):
- logging.info(f"Starting gene annotation for {len(df)} genes")
- mg = mygene.MyGeneInfo()
- ensembl_ids = df.index.str.split(".").str[0].tolist()
- gene_info = mg.querymany(ensembl_ids, scopes='ensembl.gene', fields='symbol', species='mouse')
- gene_df = pd.DataFrame(gene_info).dropna(subset=['symbol']).drop_duplicates(subset='query')
- df.index = ensembl_ids
- df['Gene_Name'] = df.index.map(gene_df.set_index('query')['symbol'])
- cols = ['Gene_Name'] + [col for col in df.columns if col != 'Gene_Name']
- logging.info(f"Completed gene annotation. Found symbols for {len(gene_df)} genes")
- return df[cols]
-
-def filter_normalize(data, min_cpm=0.7, min_samples=2):
- logging.info(f"Starting filtering and normalization. Initial genes: {len(data)}")
- gene_names = data.iloc[:, 0]
- raw_counts = data.iloc[:, 1:]
- cpm = raw_counts.apply(lambda x: (x / x.sum()) * 1e6, axis=0)
- mask = (cpm > min_cpm).sum(axis=1) >= min_samples
- filtered_counts = raw_counts[mask]
- filtered_gene_names = gene_names[mask]
- logging.info(f"After filtering: {len(filtered_counts)} genes remaining")
-
- geometric_means = filtered_counts.apply(lambda row: np.exp(np.log(row[row > 0]).mean()), axis=1)
- size_factors = filtered_counts.div(geometric_means, axis=0).median(axis=0)
- normalized_counts = filtered_counts.div(size_factors, axis=1)
- logging.info("Normalization completed")
- return pd.concat([filtered_gene_names, normalized_counts], axis=1)
-
-def perform_dea(df, treated_columns, control_columns):
- logging.info(f"Starting differential expression analysis with {len(df)} genes")
- logging.info(f"Treatment samples: {len(treated_columns)}, Control samples: {len(control_columns)}")
-
- results = []
- for gene in df.index:
- treated = pd.to_numeric(df.loc[gene, treated_columns], errors='coerce').dropna()
- control = pd.to_numeric(df.loc[gene, control_columns], errors='coerce').dropna()
- if treated.empty or control.empty:
- continue
- log2fc = np.log2((treated.mean() + 1) / (control.mean() + 1))
- t_stat, p_val = ttest_ind(treated, control)
- results.append({
- "gene": gene,
- "Gene_Name": df.loc[gene, "Gene_Name"],
- "log2fc": log2fc,
- "t_stat": t_stat,
- "p_val": p_val
- })