Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add LIANA #129

Merged
merged 9 commits into from
Nov 11, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions conf/modules.config
Original file line number Diff line number Diff line change
Expand Up @@ -339,22 +339,30 @@ process {
}

withName: SCANPY_PAGA {
ext.obs_key = { meta.id + '_leiden' }
ext.prefix = { meta.id + '_paga' }

publishDir = [
path: { "${params.outdir}/cluster_dimred/${meta.integration}/paga" },
path: { "${params.outdir}/per_group/${meta.id}/paga" },
mode: params.publish_dir_mode,
saveAs: { filename -> filename.equals('versions.yml') || filename.endsWith('.json') ? null : filename }
]
}

withName: LIANA_RANKAGGREGATE {
ext.prefix = { meta.id + '_liana' }

publishDir = [
path: { "${params.outdir}/per_group/${meta.id}/liana" },
mode: params.publish_dir_mode,
saveAs: { filename -> filename.equals('versions.yml') || filename.endsWith('.json') ? null : filename }
]
}

withName: SCANPY_RANKGENESGROUPS {
ext.obs_key = { meta.id + '_leiden' }
ext.prefix = { meta.id + '_characteristic_genes' }

publishDir = [
path: { "${params.outdir}/cluster_dimred/${meta.integration}/characteristic_genes" },
path: { "${params.outdir}/per_group/${meta.id}/characteristic_genes" },
mode: params.publish_dir_mode,
saveAs: { filename -> filename.equals('versions.yml') || filename.endsWith('.json') ? null : filename }
]
Expand Down
3 changes: 3 additions & 0 deletions modules/local/adata/unify/templates/unify.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@ def to_Florent_case(s: str):

adata.var.index = adata.var.index.map(lambda x: mapping.get(x, x))

# Replace all underlines and dots with dashes
adata.var.index = adata.var.index.str.replace(r"[\\._]", "-")

nictru marked this conversation as resolved.
Show resolved Hide resolved
# Aggregate duplicate genes
method = "${params.var_aggr_method}"
if not method in ["mean", "sum", "max"]:
Expand Down
5 changes: 5 additions & 0 deletions modules/local/liana/rankaggregate/environment.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
channels:
- conda-forge
- bioconda
dependencies:
- bioconda::liana=1.4.0
25 changes: 25 additions & 0 deletions modules/local/liana/rankaggregate/main.nf
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
process LIANA_RANKAGGREGATE {
tag "$meta.id"
label 'process_medium'

conda "${moduleDir}/environment.yml"
container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ?
'https://depot.galaxyproject.org/singularity/liana:1.4.0--pyhdfd78af_0':
'biocontainers/liana:1.4.0--pyhdfd78af_0' }"

input:
tuple val(meta), path(h5ad)

output:
tuple val(meta), path("*.h5ad"), emit: h5ad, optional: true
path("*.pkl") , emit: uns, optional: true
path "versions.yml" , emit: versions

when:
task.ext.when == null || task.ext.when

script:
obs_key = meta.obs_key ?: "leiden"
prefix = task.ext.prefix ?: "${meta.id}"
template 'rank_aggregate.py'
}
62 changes: 62 additions & 0 deletions modules/local/liana/rankaggregate/templates/rank_aggregate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#!/usr/bin/env python3

import os
import platform
import json
import base64
import pickle

os.environ["NUMBA_CACHE_DIR"] = "./tmp/numba"
os.environ["MPLCONFIGDIR"] = "./tmp/matplotlib"

import pandas as pd
import scanpy as sc
import liana as li

from threadpoolctl import threadpool_limits
threadpool_limits(int("${task.cpus}"))

def format_yaml_like(data: dict, indent: int = 0) -> str:
"""Formats a dictionary to a YAML-like string.

Args:
data (dict): The dictionary to format.
indent (int): The current indentation level.

Returns:
str: A string formatted as YAML.
"""
yaml_str = ""
for key, value in data.items():
spaces = " " * indent
if isinstance(value, dict):
yaml_str += f"{spaces}{key}:\\n{format_yaml_like(value, indent + 1)}"
else:
yaml_str += f"{spaces}{key}: {value}\\n"
return yaml_str

adata = sc.read_h5ad("${h5ad}")
prefix = "${prefix}"
obs_key = "${obs_key}"

if adata.obs[obs_key].nunique() > 1:
if (adata.X < 0).nnz == 0:
sc.pp.log1p(adata)
li.mt.rank_aggregate(adata, obs_key, use_raw=False, verbose=True)
df: pd.DataFrame = adata.uns["liana_res"]

df.to_pickle(f"{prefix}.pkl")
adata.write_h5ad(f"{prefix}.h5ad")
else:
print(f"Skipping rank aggregation because the column {obs_key} has only one unique value.")

# Versions

versions = {
"python": platform.python_version(),
"scanpy": sc.__version__,
"liana": li.__version__,
}

with open("versions.yml", "w") as f:
f.write(format_yaml_like(versions))
3 changes: 3 additions & 0 deletions modules/local/scanpy/combat/templates/combat.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import scanpy as sc
import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix

from threadpoolctl import threadpool_limits
threadpool_limits(int("${task.cpus}"))
Expand Down Expand Up @@ -37,6 +38,8 @@ def format_yaml_like(data: dict, indent: int = 0) -> str:
prefix = "${prefix}"

sc.pp.combat(adata, key="batch")
adata.X = csr_matrix(adata.X)

sc.pp.pca(adata)
adata.obsm["X_emb"] = adata.obsm["X_pca"]

Expand Down
12 changes: 6 additions & 6 deletions modules/local/scanpy/paga/main.nf
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,18 @@ process SCANPY_PAGA {
tuple val(meta), path(h5ad)

output:
tuple val(meta), path("*.h5ad"), emit: h5ad
path("*.pkl") , emit: uns
path("*.npy") , emit: obsp
path("*.png") , emit: plot
path("*_mqc.json") , emit: multiqc_files
tuple val(meta), path("*.h5ad"), emit: h5ad, optional: true
path("*.pkl") , emit: uns, optional: true
path("*.npy") , emit: obsp, optional: true
path("*.png") , emit: plot, optional: true
path("*_mqc.json") , emit: multiqc_files, optional: true
path "versions.yml" , emit: versions

when:
task.ext.when == null || task.ext.when

script:
obs_key = task.ext.obs_key ?: "leiden"
obs_key = meta.obs_key ?: "leiden"
prefix = task.ext.prefix ?: "${meta.id}"
template 'paga.py'
}
51 changes: 27 additions & 24 deletions modules/local/scanpy/paga/templates/paga.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,38 +41,41 @@ def format_yaml_like(data: dict, indent: int = 0) -> str:
prefix = "${prefix}"
obs_key = "${obs_key}"

sc.tl.paga(adata, groups=obs_key if obs_key else None)
if adata.obs[obs_key].value_counts().size > 1:
sc.tl.paga(adata, groups=obs_key)

paga_dict = adata.uns["paga"]
paga_dict = adata.uns["paga"]

# Save PAGA data
pickle.dump(paga_dict, open(f"{prefix}.pkl", "wb"))
# Save PAGA data
pickle.dump(paga_dict, open(f"{prefix}.pkl", "wb"))

np.save(f"{prefix}_connectivities.npy", adata.obsp["connectivities"])
adata.write_h5ad(f"{prefix}.h5ad")
np.save(f"{prefix}_connectivities.npy", adata.obsp["connectivities"])
adata.write_h5ad(f"{prefix}.h5ad")

# Plot
sc.pl.paga(adata, title="${meta.id} PAGA", show=False)
path = f"{prefix}.png"
plt.savefig(path)
# Plot
sc.pl.paga(adata, title="${meta.id} PAGA", show=False)
path = f"{prefix}.png"
plt.savefig(path)

# MultiQC
with open(path, "rb") as f_plot, open("${prefix}_mqc.json", "w") as f_json:
image_string = base64.b64encode(f_plot.read()).decode("utf-8")
image_html = f'<div class="mqc-custom-content-image"><img src="data:image/png;base64,{image_string}" /></div>'
# MultiQC
with open(path, "rb") as f_plot, open("${prefix}_mqc.json", "w") as f_json:
image_string = base64.b64encode(f_plot.read()).decode("utf-8")
image_html = f'<div class="mqc-custom-content-image"><img src="data:image/png;base64,{image_string}" /></div>'

custom_json = {
"id": "${prefix}",
"parent_id": "${meta.integration}",
"parent_name": "${meta.integration}",
"parent_description": "Results of the ${meta.integration} integration.",
custom_json = {
"id": "${prefix}",
"parent_id": "${meta.integration}",
"parent_name": "${meta.integration}",
"parent_description": "Results of the ${meta.integration} integration.",

"section_name": "${meta.id} PAGA",
"plot_type": "image",
"data": image_html,
}
"section_name": "${meta.id} PAGA",
"plot_type": "image",
"data": image_html,
}

json.dump(custom_json, f_json)
json.dump(custom_json, f_json)
else:
print(f"Skipping PAGA computation for {obs_key} as it has less than 2 unique values.")

# Versions

Expand Down
10 changes: 5 additions & 5 deletions modules/local/scanpy/rankgenesgroups/main.nf
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ process SCANPY_RANKGENESGROUPS {
tuple val(meta), path(h5ad)

output:
tuple val(meta), path("*.h5ad"), emit: h5ad
path "*.pkl" , emit: uns
path "*.png" , emit: plots
path "*_mqc.json" , emit: multiqc_files
tuple val(meta), path("*.h5ad"), emit: h5ad, optional: true
path "*.pkl" , emit: uns, optional: true
path "*.png" , emit: plots, optional: true
path "*_mqc.json" , emit: multiqc_files, optional: true
path "versions.yml" , emit: versions

when:
task.ext.when == null || task.ext.when

script:
obs_key = task.ext.obs_key ?: "leiden"
obs_key = meta.obs_key ?: "leiden"
prefix = task.ext.prefix ?: "${meta.id}"
template 'rank_genes_groups.py'
}
96 changes: 48 additions & 48 deletions modules/local/scanpy/rankgenesgroups/templates/rank_genes_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,55 +46,55 @@ def format_yaml_like(data: dict, indent: int = 0) -> str:
"pts": True
}


if use_gpu:
os.environ["CUPY_CACHE_DIR"] = "./tmp/cupy"

import rapids_singlecell as rsc
import rmm
from rmm.allocators.cupy import rmm_cupy_allocator
import cupy as cp
rmm.reinitialize(
managed_memory=True,
pool_allocator=False,
)
cp.cuda.set_allocator(rmm_cupy_allocator)

rsc.get.anndata_to_GPU(adata)
rsc.pp.log1p(adata)
rsc.tl.rank_genes_groups_logreg(adata, **kwargs)
rsc.get.anndata_to_CPU(adata)
if adata.obs["${obs_key}"].value_counts().size > 1:
if use_gpu:
import rapids_singlecell as rsc
import rmm
from rmm.allocators.cupy import rmm_cupy_allocator
import cupy as cp
rmm.reinitialize(
managed_memory=True,
pool_allocator=False,
)
cp.cuda.set_allocator(rmm_cupy_allocator)

rsc.get.anndata_to_GPU(adata)
rsc.pp.log1p(adata)
rsc.tl.rank_genes_groups_logreg(adata, **kwargs)
rsc.get.anndata_to_CPU(adata)
else:
sc.pp.log1p(adata)
sc.tl.rank_genes_groups(adata, **kwargs)

rgg_dict = adata.uns["rank_genes_groups"]

pickle.dump(rgg_dict, open(f"{prefix}.pkl", "wb"))
adata.write_h5ad(f"{prefix}.h5ad")

# Plot
sc.pl.rank_genes_groups(adata, show=False)
path = f"{prefix}.png"
plt.savefig(path)

# MultiQC
with open(path, "rb") as f_plot, open("${prefix}_mqc.json", "w") as f_json:
image_string = base64.b64encode(f_plot.read()).decode("utf-8")
image_html = f'<div class="mqc-custom-content-image"><img src="data:image/png;base64,{image_string}" /></div>'

custom_json = {
"id": "${prefix}",
"parent_id": "${meta.integration}",
"parent_name": "${meta.integration}",
"parent_description": "Results of the ${meta.integration} integration.",

"section_name": "${meta.id} characteristic genes",
"plot_type": "image",
"data": image_html,
}

json.dump(custom_json, f_json)
else:
sc.pp.log1p(adata)
sc.tl.rank_genes_groups(adata, **kwargs)

rgg_dict = adata.uns["rank_genes_groups"]

pickle.dump(rgg_dict, open(f"{prefix}.pkl", "wb"))
adata.write_h5ad(f"{prefix}.h5ad")

# Plot
sc.pl.rank_genes_groups(adata, show=False)
path = f"{prefix}.png"
plt.savefig(path)

# MultiQC
with open(path, "rb") as f_plot, open("${prefix}_mqc.json", "w") as f_json:
image_string = base64.b64encode(f_plot.read()).decode("utf-8")
image_html = f'<div class="mqc-custom-content-image"><img src="data:image/png;base64,{image_string}" /></div>'

custom_json = {
"id": "${prefix}",
"parent_id": "${meta.integration}",
"parent_name": "${meta.integration}",
"parent_description": "Results of the ${meta.integration} integration.",

"section_name": "${meta.id} characteristic genes",
"plot_type": "image",
"data": image_html,
}

json.dump(custom_json, f_json)
print("Skipping rank_genes_groups computation as the group has less than 2 unique values.")

# Versions

Expand Down
Loading
Loading