-
Notifications
You must be signed in to change notification settings - Fork 14
Pseudobulks #1042
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
Merged
Merged
Pseudobulks #1042
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
cf851ba
wip
dorien-er 0c14878
wip
dorien-er ca2d381
wip
dorien-er 3c6a5ca
wip
dorien-er c044b25
update_tests
dorien-er 7d096e0
Merge remote-tracking branch 'origin/main' into pseudobulks
dorien-er 73a2412
typos
dorien-er 8868be1
remove edger
dorien-er 9a5ccf9
linting
dorien-er eac9f99
update test resources
dorien-er 3b1bf7b
address pr comments
dorien-er e1b38bc
address pr comments
dorien-er 737910b
add changelog entry
dorien-er 369931f
Merge branch 'main' into pseudobulks
dorien-er cb3f7a3
update description
dorien-er File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
111 changes: 111 additions & 0 deletions
111
src/differential_expression/create_pseudobulk/config.vsh.yaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| name: differential_expression | ||
| namespace: "create_pseudobulk" | ||
| scope: "public" | ||
| description: | | ||
| Generation of pseudobulk samples from single-cell transcriptomics data, | ||
| by aggregating raw gene expression counts from individual cells to create | ||
| bulk-like expression profiles suitable for differential expression analysis | ||
| with methods designed for bulk differential expression analysis. | ||
| Note that this componentonly considers factors as explanatory variables, | ||
| and excludes covariates from the analysis. | ||
|
|
||
| authors: | ||
| - __merge__: /src/authors/dorien_roosen.yaml | ||
| roles: [ author ] | ||
| - __merge__: /src/authors/jakub_majercik.yaml | ||
| roles: [ author ] | ||
| - __merge__: /src/authors/dries_de_maeyer.yaml | ||
| roles: [ contributor ] | ||
| - __merge__: /src/authors/weiwei_schultz.yaml | ||
| roles: [ contributor ] | ||
|
|
||
| argument_groups: | ||
| - name: Inputs | ||
| arguments: | ||
| - name: "--input" | ||
| alternatives: ["-i"] | ||
| type: file | ||
| description: Input h5mu file. | ||
| direction: input | ||
| required: true | ||
| - name: "--modality" | ||
| description: | | ||
| Which modality from the input MuData file to process. | ||
| type: string | ||
| default: "rna" | ||
| required: false | ||
| - name: "--input_layer" | ||
| type: string | ||
| required: false | ||
| description: "Input layer to use. If None, X is used. This layer must contain raw counts." | ||
| - name: "--obs_label" | ||
| type: string | ||
| required: true | ||
| description: ".obs field containing the variable to group on. Typically this field contains cell groups such as annotated cell types or clusters." | ||
| - name: "--obs_groups" | ||
| type: string | ||
| multiple: true | ||
| description: ".obs fields containing the experimental condition(s) to create pseudobulk samples for." | ||
|
|
||
| - name: Arguments | ||
| arguments: | ||
| - name: "--aggregation_method" | ||
| type: string | ||
| choices: ["sum", "mean"] | ||
| default: "sum" | ||
| description: "Method to aggregate the raw counts for pseudoreplicates. Either sum or mean." | ||
| - name: "--min_obs_per_sample" | ||
| type: integer | ||
| min: 1 | ||
| default: 30 | ||
| description: "Minimum number of cells per pseudobulk sample." | ||
| - name: --random_state | ||
| type: integer | ||
| description: | | ||
| The random seed for sampling. | ||
| min: 0 | ||
| default: 0 | ||
| required: false | ||
| - name: "--obs_cell_count" | ||
| type: string | ||
| default: "n_cells" | ||
| description: "The .obs field to store the number of observations per pseudobulk sample." | ||
|
|
||
| - name: Outputs | ||
| arguments: | ||
| - name: "--output" | ||
| type: file | ||
| description: Output h5mu file containing the aggregated pseudobulk samples. | ||
| direction: output | ||
| required: true | ||
| - name: "--output_compression" | ||
| type: string | ||
| description: | | ||
| The compression format to be used on the output h5mu object. | ||
| choices: ["gzip", "lzf"] | ||
| required: false | ||
| example: "gzip" | ||
|
|
||
| resources: | ||
| - type: python_script | ||
| path: script.py | ||
| - path: /src/utils/setup_logger.py | ||
|
|
||
| test_resources: | ||
| - type: python_script | ||
| path: test.py | ||
| - path: /resources_test/annotation_test_data/TS_Blood_filtered.h5mu | ||
|
|
||
| engines: | ||
| - type: docker | ||
| image: python:3.12 | ||
| setup: | ||
| - type: python | ||
| __merge__: [/src/base/requirements/anndata_mudata.yaml, /src/base/requirements/scanpy.yaml ] | ||
| __merge__: [ /src/base/requirements/python_test_setup.yaml, .] | ||
|
|
||
| runners: | ||
| - type: executable | ||
| - type: nextflow | ||
| directives: | ||
| label: [lowcpu, lowmem] | ||
107 changes: 107 additions & 0 deletions
107
src/differential_expression/create_pseudobulk/script.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| import numpy as np | ||
| import mudata as mu | ||
| import pandas as pd | ||
| import sys | ||
| import scanpy as sc | ||
| import scipy.sparse as sp | ||
|
|
||
| ## VIASH START | ||
| par = { | ||
| "input": "resources_test/annotation_test_data/TS_Blood_filtered.h5mu", | ||
| "modality": "rna", | ||
| "input_layer": None, | ||
| "obs_label": "cell_type", | ||
| "obs_groups": ["treatment", "donor_id", "disease"], | ||
| "obs_cell_count": "n_cells", | ||
| "min_obs_per_sample": 5, | ||
| "random_state": 0, | ||
| "output": "test.h5mu", | ||
| "output_compression": "gzip", | ||
| } | ||
| meta = {"resources_dir": "src/utils"} | ||
| ## VIASH END | ||
|
|
||
| sys.path.append(meta["resources_dir"]) | ||
| from setup_logger import setup_logger | ||
|
|
||
| logger = setup_logger() | ||
|
|
||
|
|
||
| def is_normalized(layer): | ||
| if sp.issparse(layer): | ||
| row_sums = np.array(layer.sum(axis=1)).flatten() | ||
| else: | ||
| row_sums = layer.sum(axis=1) | ||
|
|
||
| return np.allclose(row_sums, 1) | ||
|
|
||
|
|
||
| def count_obs(adata, pb_adata, obs_cols): | ||
| counts = [] | ||
| for i in range(pb_adata.n_obs): | ||
| values = pb_adata.obs.iloc[i][obs_cols] | ||
|
|
||
| mask = pd.Series([True] * adata.n_obs) | ||
| for col in obs_cols: | ||
| mask &= (adata.obs[col] == values[col]).values | ||
|
|
||
| count = mask.sum() | ||
| counts.append(count) | ||
|
|
||
| return counts | ||
|
|
||
|
|
||
| def main(): | ||
| # Read in data | ||
| logger.info(f"Reading input data {par['input']}...") | ||
| adata = mu.read_h5ad(par["input"], mod=par["modality"]).copy() | ||
|
|
||
| # Make sure .X contains raw counts | ||
| if par["input_layer"]: | ||
| adata.X = adata.layers[par["input_layer"]] | ||
| if is_normalized(adata.X): | ||
| raise ValueError("Input layer must contain raw counts.") | ||
|
|
||
| # Sanitize pseudobulk aggregation fields | ||
| pseudobulk_cols = [par["obs_label"]] | ||
| if par["obs_groups"]: | ||
| pseudobulk_cols += par["obs_groups"] | ||
|
|
||
| for col in pseudobulk_cols: | ||
| if col not in adata.obs.columns: | ||
| raise ValueError(f"Required column '{col}' not found in .obs.") | ||
| adata.obs[col] = ( | ||
| adata.obs[col] | ||
| .astype(str) | ||
| .str.replace(" ", "_") | ||
| .str.replace("+", "") | ||
| .astype("category") | ||
| ) | ||
|
|
||
| # Aggregate pseudobulk data per cell group | ||
| logger.info("Creating pseudobulk samples...") | ||
| adata_pb = sc.get.aggregate(adata, by=pseudobulk_cols, func="sum", axis=0) | ||
| adata_pb.X = adata_pb.layers["sum"] | ||
| del adata_pb.layers["sum"] | ||
|
|
||
| adata_pb.obs_names = [ | ||
| "_".join(values) | ||
| for values in zip(*[adata_pb.obs[col] for col in pseudobulk_cols]) | ||
| ] | ||
|
|
||
| # Filter pseudobulk samples based on minimum observation count | ||
| logger.info("Filtering pseudobulk samples based on minimum observation count...") | ||
| adata_pb.obs[par["obs_cell_count"]] = count_obs(adata, adata_pb, pseudobulk_cols) | ||
| adata_pb = adata_pb[adata_pb.obs[par["obs_cell_count"]] > par["min_obs_per_sample"]] | ||
|
|
||
| logger.info( | ||
| f"Final dataset: {adata_pb.n_obs} pseudobulk samples, {adata_pb.n_vars} genes" | ||
| ) | ||
|
|
||
| logger.info("Writing output data...") | ||
| mdata_pb = mu.MuData({"rna": adata_pb}) | ||
| mdata_pb.write_h5mu(par["output"], compression=par["output_compression"]) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.