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

[WIP]: Simulation adjustment #62

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion bin/composition_baseline.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def get_local_sample_representation(self):
freqs = (
comps.loc[:, [self.sample_key, self.subcluster_key, "freqs"]]
.set_index([self.sample_key, self.subcluster_key])
.squeeze()
.squeeze(axis=1)
.unstack()
)
freqs_all[unique_cluster] = freqs
Expand Down
37 changes: 33 additions & 4 deletions bin/fit_scviv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def fit_scviv2(
use_attention_no_prior_mog: str = "false",
use_attention_mog: str = "false",
use_attention_no_prior_mog_large: str = "false",
use_ibd_config: str = "false",
) -> scvi_v2.MrVI:
"""
Train a MrVI model.
Expand All @@ -38,7 +39,10 @@ def fit_scviv2(
use_attention_smallu = use_attention_smallu.lower() == "true"
use_attention_noprior = use_attention_noprior.lower() == "true"
use_attention_no_prior_mog = use_attention_no_prior_mog.lower() == "true"
use_attention_no_prior_mog_large = use_attention_no_prior_mog_large.lower() == "true"
use_attention_no_prior_mog_large = (
use_attention_no_prior_mog_large.lower() == "true"
)
use_ibd_config = use_ibd_config.lower() == "true"

config = load_config(config_in)
batch_key = config.get("batch_key", None)
Expand Down Expand Up @@ -121,19 +125,19 @@ def fit_scviv2(
"use_map": True,
"stop_gradients": False,
"stop_gradients_mlp": True,
"dropout_rate": 0.03
"dropout_rate": 0.03,
},
"px_kwargs": {
"stop_gradients": False,
"stop_gradients_mlp": True,
"h_activation": nn.softmax,
"dropout_rate": 0.03,
"low_dim_batch": True
"low_dim_batch": True,
},
"learn_z_u_prior_scale": False,
"z_u_prior": True,
"u_prior_mixture": False,
}
}
)
if use_attention_no_prior_mog:
model_kwargs.update(
Expand Down Expand Up @@ -209,6 +213,31 @@ def fit_scviv2(
"u_prior_mixture_k": 20,
}
)
if use_ibd_config:
model_kwargs = {
"n_latent": 200,
"n_latent_u": 10,
"qz_nn_flavor": "attention",
"px_nn_flavor": "attention",
"qz_kwargs": {
"use_map": False,
"stop_gradients": False,
"stop_gradients_mlp": True,
"dropout_rate": 0.03,
},
"px_kwargs": {
"stop_gradients": False,
"stop_gradients_mlp": True,
"h_activation": nn.softmax,
"dropout_rate": 0.03,
"low_dim_batch": True,
},
"learn_z_u_prior_scale": False,
"z_u_prior": False,
"u_prior_mixture": True,
"u_prior_mixture_k": 100,
}

model = scvi_v2.MrVI(adata, **model_kwargs)
model.train(**train_kwargs)

Expand Down
3 changes: 2 additions & 1 deletion bin/get_latent_scviv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def get_latent_scviv2(
Path(cell_representations_out).touch()

cell_dists = model.get_local_sample_distances(
adata, keep_cell=False, groupby=labels_key
adata, keep_cell=False, groupby=labels_key, batch_size=32
)
make_parents(distance_matrices_out)
cell_dists.to_netcdf(distance_matrices_out)
Expand All @@ -76,6 +76,7 @@ def get_latent_scviv2(
normalize_distances=True,
keep_cell=False,
groupby=labels_key,
batch_size=32,
)
cell_normalized_dists.to_netcdf(normalized_distance_matrices_out)
del cell_normalized_dists
Expand Down
48 changes: 40 additions & 8 deletions bin/preprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@ def _process_semisynth2(
n_genes_for_subclustering = semisynth_config["n_genes_for_subclustering"]
if subsample:
selected_subsample_cluster = semisynth_config["selected_subsample_cluster"]
selected_oversample_cluster = semisynth_config["selected_oversample_cluster"]
subsample_rates = semisynth_config["subsample_rates"]

# use SCVI to obtain latent space
Expand Down Expand Up @@ -517,7 +518,14 @@ def _process_semisynth2(
.astype(int)
)

subsampled_adatas = [adata[adata.obs.leiden != str(selected_subsample_cluster)]]
# subsampled_adatas = [adata[adata.obs.leiden != str(selected_subsample_cluster)]]
subsampled_adatas = [
adata[
~adata.obs.leiden.isin(
[str(selected_subsample_cluster), str(selected_oversample_cluster)]
)
]
]
subsample_info_df = pd.DataFrame()
for rank, subsample_rate in enumerate(subsample_rates, 1):
samples_to_subsample = sample_assignment_mapping[
Expand All @@ -538,16 +546,31 @@ def _process_semisynth2(
(adata.obs.sample_assignment == str(sample))
& (adata.obs["leiden"] == str(selected_subsample_cluster))
]
subsample_adata = subsample_adata[
np.random.choice(
subsample_adata.shape[0],
int(subsample_adata.shape[0] * subsample_rate),
replace=False,
)
]
n_subsampled = int(subsample_adata.shape[0] * subsample_rate)
n_removed = subsample_adata.shape[0] - n_subsampled
subsampled_idx = np.random.choice(
subsample_adata.shape[0],
n_subsampled,
replace=False,
)
subsample_adata = subsample_adata[subsampled_idx]
subsampled_adatas.append(subsample_adata)

# Add cells to ensure total number of cells is the same
oversample_adata = adata[
(adata.obs.sample_assignment == str(sample))
& (adata.obs["leiden"] == str(selected_oversample_cluster))
]
oversample_idx = np.random.choice(
oversample_adata.shape[0],
oversample_adata.shape[0] + n_removed,
replace=True,
)
oversample_adata = oversample_adata[oversample_idx]
subsampled_adatas.append(oversample_adata)

res = sc.concat(subsampled_adatas)
res.obs_names_make_unique()
subsample_info_df = subsample_info_df.astype({"sample": str}).set_index(
"sample"
)
Expand All @@ -561,13 +584,22 @@ def _process_semisynth2(
res.obs.loc[:, "sample_metadata2"] = (
res.obs[f"subsample_rate_in_leiden{selected_subsample_cluster}"] <= 0.8
)

one_hot_groupnames = []
for unique_group in res.obs["sample_group"].unique():
new_key = f"group_{unique_group}"
res.obs.loc[:, new_key] = (res.obs["sample_group"] == unique_group).astype(
int
)
one_hot_groupnames.append(new_key)
res = sc.AnnData(
X=res.X,
obs=res.obs,
obsm=res.obsm,
var=adata.var,
uns=adata.uns,
)
res.uns["one_hot_groupnames"] = one_hot_groupnames
return res
return adata

Expand Down
Loading