PKNȤscgen/__init__.py"""ScGen - Predicting single cell perturbations""" from .models import * from .read_load import load_file from . import plotting __author__ = ', '.join([ 'Mohammad Lotfollahi', 'Mohsen Naghipourfar' ]) __email__ = ', '.join([ 'Mohammad.lotfollahi@helmholtz-muenchen.de', 'mohsen.naghipourfar@gmail.com' ]) from get_version import get_version __version__ = get_version(__file__) del get_version PKNIwQ scgen/data_generator.pyfrom copy import deepcopy from scipy.ndimage import imread import numpy as np import pandas as pd import anndata import os # data_name = "horse2zebra" # data_path = "../data/" + data_name # # train_images = [] # for image in os.listdir(os.path.join(data_path, "trainA")): # if image.endswith(".jpg"): # image = imread(fname=os.path.join(data_path, "trainA", image)) # image = np.reshape(image, newshape=(256 * 256 * 3, )) # image = image.tolist() # train_images.append(image) # # n_horses = len(train_images) # # for image in os.listdir(os.path.join(data_path, "trainB")): # if image.endswith(".jpg"): # image = imread(fname=os.path.join(data_path, "trainB", image)) # if len(image.shape) == 3: # image = np.reshape(image, newshape=(256 * 256 * 3, )) # image = image.tolist() # train_images.append(image) # # train_images = np.array(train_images) # print(train_images.shape) # n_zebras = train_images.shape[0] - n_horses # # conditions = ["horse"] * n_horses # conditions += ["zebra"] * n_zebras # train_adata = anndata.AnnData(train_images, obs={"condition": conditions}) # train_adata.write_h5ad(filename="../data/h2z.h5ad") # # # import scanpy as sc # mnist_data = sc.read("../data/normal_thick.h5ad") # mnist_data = mnist_data.copy()[mnist_data.obs["condition"] == "normal"] # mnist_data.obs["condition"] = mnist_data.copy().obs["labels"].values.astype(dtype=np.str) # # mnist_data.obs["labels"] = np.reshape(mnist_data.obs["labels"].values, (-1, 1)) # mnist_data.write_h5ad("../data/mnist.h5ad") # mnist_data = sc.read("../data/mnist.h5ad") # mnist_data.obs["condition"] = mnist_data.obs["condition"].astype(np.str) # print(mnist_data) # print(mnist_data.obs) # print(mnist_data[mnist_data.obs["labels"] == 2]) def load_mnist(path, kind='train'): import os import gzip import numpy as np """Load MNIST data from `path`""" labels_path = os.path.join(path, '%s-labels-idx1-ubyte.gz' % kind) images_path = os.path.join(path, '%s-images-idx3-ubyte.gz' % kind) with gzip.open(labels_path, 'rb') as lbpath: labels = np.frombuffer(lbpath.read(), dtype=np.uint8, offset=8) with gzip.open(images_path, 'rb') as imgpath: images = np.frombuffer(imgpath.read(), dtype=np.uint8, offset=16).reshape(len(labels), 784) return images, labels x_train, y_train = load_mnist(path="../data/fashion/") fashion_adata = anndata.AnnData(X=x_train, obs={"condition": y_train, "labels": y_train}) print(fashion_adata) fashion_adata.write_h5ad("../data/fashion.h5ad")PKnNssscgen/hyperoptim.pyfrom __future__ import print_function import numpy as np import scanpy as sc from hyperas import optim from hyperas.distributions import choice from hyperopt import Trials, STATUS_OK, tpe import scgen def data(): x_train = sc.read("./data/train.h5ad") return x_train def create_model(x_train): network = scgen.VAEArith(x_dimension=x_train.X.shape[1], z_dimension={{choice([10, 20, 50, 75, 100])}}, learning_rate={{choice([0.1, 0.01, 0.001, 0.0001])}}, alpha={{choice([0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001])}}, dropout_rate={{choice([0.2, 0.25, 0.5, 0.75, 0.8])}}, model_path=f"./") result = network.train(x_train, n_epochs={{choice([100, 150, 200, 250])}}, batch_size={{choice([32, 64, 128, 256])}}, verbose=2, shuffle=True, save=False) best_loss = np.amin(result.history['loss']) print('Best Loss of model:', best_loss) return {'loss': best_loss, 'status': STATUS_OK, 'model': network.vae_model} if __name__ == '__main__': best_run, best_model = optim.minimize(model=create_model, data=data, algo=tpe.suggest, max_evals=100, trials=Trials()) x_train = data() # print("Evalutation of best performing model:") # print(best_model.evaluate([x_train.X])) print("Best performing model chosen hyper-parameters:") print(best_run) """ best run for VAE Arithmetic: alpha = .01 batch_size = 256 dropout_rate = 0.75 learning_rate = 0.1 n_epochs = 100 z_dimension = 20 """PK՘N66scgen/plotting.pyimport numpy import scanpy as sc from matplotlib import pyplot import pandas as pd from scipy import stats, sparse from adjustText import adjust_text import matplotlib font = {'family' : 'Arial', # 'weight' : 'bold', 'size' : 14} matplotlib.rc('font', **font) matplotlib.rc('ytick', labelsize=14) matplotlib.rc('xtick', labelsize=14) def reg_mean_plot(adata, condition_key, axis_keys, labels, path_to_save="./reg_mean.pdf", gene_list=None, top_100_genes=None, show=False, verbose=False, legend=True, title=None, x_coeff=0.30, y_coeff=0.8, fontsize=14, **kwargs): """ Plots mean matching figure for a set of specific genes. # Parameters adata: `~anndata.AnnData` Annotated Data Matrix. condition_key: basestring Condition state to be used. axis_keys: dict dictionary of axes labels. path_to_save: basestring path to save the plot. gene_list: list list of gene names to be plotted. show: bool if `True`: will show to the plot after saving it. # Example ```python import anndata import scgen import scanpy as sc train = sc.read("./tests/data/train.h5ad", backup_url="https://goo.gl/33HtVh") network = scgen.VAEArith(x_dimension=train.shape[1], model_path="../models/test") network.train(train_data=train, n_epochs=0) unperturbed_data = train[((train.obs["cell_type"] == "CD4T") & (train.obs["condition"] == "control"))] condition = {"ctrl": "control", "stim": "stimulated"} pred, delta = network.predict(adata=train, adata_to_predict=unperturbed_data, conditions=condition) pred_adata = anndata.AnnData(pred, obs={"condition": ["pred"] * len(pred)}, var={"var_names": train.var_names}) CD4T = train[train.obs["cell_type"] == "CD4T"] all_adata = CD4T.concatenate(pred_adata) scgen.plotting.reg_mean_plot(all_adata, condition_key="condition", axis_keys={"x": "control", "y": "pred", "y1": "stimulated"}, gene_list=["ISG15", "CD3D"], path_to_save="tests/reg_mean.pdf", show=False) network.sess.close() ``` """ import seaborn as sns sns.set() sns.set(color_codes=True) if sparse.issparse(adata.X): adata.X = adata.X.A diff_genes = top_100_genes stim = adata[adata.obs[condition_key] == axis_keys["y"]] ctrl = adata[adata.obs[condition_key] == axis_keys["x"]] if diff_genes is not None: if hasattr(diff_genes, "tolist"): diff_genes = diff_genes.tolist() adata_diff = adata[:, diff_genes] stim_diff = adata_diff[adata_diff.obs[condition_key] == axis_keys["y"]] ctrl_diff = adata_diff[adata_diff.obs[condition_key] == axis_keys["x"]] x_diff = numpy.average(ctrl_diff.X, axis=0) y_diff = numpy.average(stim_diff.X, axis=0) m, b, r_value_diff, p_value_diff, std_err_diff = stats.linregress(x_diff, y_diff) if verbose: print('top_100 DEGs mean: ', r_value_diff ** 2) if "y1" in axis_keys.keys(): real_stim = adata[adata.obs[condition_key] == axis_keys["y1"]] x = numpy.average(ctrl.X, axis=0) y = numpy.average(stim.X, axis=0) m, b, r_value, p_value, std_err = stats.linregress(x, y) if verbose: print('All genes mean: ', r_value ** 2) df = pd.DataFrame({axis_keys["x"]: x, axis_keys["y"]: y}) ax = sns.regplot(x=axis_keys["x"], y=axis_keys["y"], data=df) ax.tick_params(labelsize=fontsize) if "range" in kwargs: start, stop, step = kwargs.get("range") ax.set_xticks(numpy.arange(start, stop, step)) ax.set_yticks(numpy.arange(start, stop, step)) # _p1 = pyplot.scatter(x, y, marker=".", label=f"{axis_keys['x']}-{axis_keys['y']}") # pyplot.plot(x, m * x + b, "-", color="green") ax.set_xlabel(labels["x"], fontsize=fontsize) ax.set_ylabel(labels["y"], fontsize=fontsize) # if "y1" in axis_keys.keys(): # y1 = numpy.average(real_stim.X, axis=0) # _p2 = pyplot.scatter(x, y1, marker="*", c="red", alpha=.5, label=f"{axis_keys['x']}-{axis_keys['y1']}") if gene_list is not None: texts = [] for i in gene_list: j = adata.var_names.tolist().index(i) x_bar = x[j] y_bar = y[j] texts.append(pyplot.text(x_bar, y_bar , i, fontsize=11, color ="black")) pyplot.plot(x_bar, y_bar, 'o', color="red", markersize=5) # if "y1" in axis_keys.keys(): # y1_bar = y1[j] # pyplot.text(x_bar, y1_bar, i, fontsize=11, color="black") if gene_list is not None: adjust_text(texts, x=x, y=y, arrowprops=dict(arrowstyle="->", color='grey', lw=0.5), force_points=(0.0, 0.0)) if legend: pyplot.legend(loc='center left', bbox_to_anchor=(1, 0.5)) if title is None: pyplot.title(f"", fontsize=fontsize) else: pyplot.title(title, fontsize=fontsize) ax.text(max(x) - max(x) * x_coeff, max(y) - y_coeff * max(y), r'$\mathrm{R^2_{\mathrm{\mathsf{all\ genes}}}}$= ' + f"{r_value ** 2:.2f}", fontsize=kwargs.get("textsize", fontsize)) if diff_genes is not None: ax.text(max(x) - max(x) * x_coeff, max(y) - (y_coeff+0.15) * max(y), r'$\mathrm{R^2_{\mathrm{\mathsf{top\ 100\ DEGs}}}}$= ' + f"{r_value_diff ** 2:.2f}", fontsize=kwargs.get("textsize", fontsize)) pyplot.savefig(f"{path_to_save}", bbox_inches='tight', dpi=100) if show: pyplot.show() pyplot.close() return r_value ** 2, r_value_diff ** 2 def reg_var_plot(adata, condition_key, axis_keys, labels, path_to_save="./reg_var.pdf", gene_list=None, top_100_genes=None, show=False, legend=True, title=None, verbose=False, x_coeff=0.30, y_coeff=0.8, fontsize=14, **kwargs): """ Plots variance matching figure for a set of specific genes. # Parameters adata: `~anndata.AnnData` Annotated Data Matrix. condition_key: basestring Condition state to be used. axis_keys: dict dictionary of axes labels. path_to_save: basestring path to save the plot. gene_list: list list of gene names to be plotted. show: bool if `True`: will show to the plot after saving it. # Example ```python import anndata import scgen import scanpy as sc train = sc.read("./tests/data/train.h5ad", backup_url="https://goo.gl/33HtVh") network = scgen.VAEArith(x_dimension=train.shape[1], model_path="../models/test") network.train(train_data=train, n_epochs=0) unperturbed_data = train[((train.obs["cell_type"] == "CD4T") & (train.obs["condition"] == "control"))] condition = {"ctrl": "control", "stim": "stimulated"} pred, delta = network.predict(adata=train, adata_to_predict=unperturbed_data, conditions=condition) pred_adata = anndata.AnnData(pred, obs={"condition": ["pred"] * len(pred)}, var={"var_names": train.var_names}) CD4T = train[train.obs["cell_type"] == "CD4T"] all_adata = CD4T.concatenate(pred_adata) scgen.plotting.reg_var_plot(all_adata, condition_key="condition", axis_keys={"x": "control", "y": "pred", "y1": "stimulated"}, gene_list=["ISG15", "CD3D"], path_to_save="tests/reg_var4.pdf", show=False) network.sess.close() ``` """ import seaborn as sns sns.set() sns.set(color_codes=True) if sparse.issparse(adata.X): adata.X = adata.X.A sc.tl.rank_genes_groups(adata, groupby=condition_key, n_genes=100, method="wilcoxon") diff_genes = top_100_genes stim = adata[adata.obs[condition_key] == axis_keys["y"]] ctrl = adata[adata.obs[condition_key] == axis_keys["x"]] if diff_genes is not None: if hasattr(diff_genes, "tolist"): diff_genes = diff_genes.tolist() adata_diff = adata[:, diff_genes] stim_diff = adata_diff[adata_diff.obs[condition_key] == axis_keys["y"]] ctrl_diff = adata_diff[adata_diff.obs[condition_key] == axis_keys["x"]] x_diff = numpy.var(ctrl_diff.X, axis=0) y_diff = numpy.var(stim_diff.X, axis=0) m, b, r_value_diff, p_value_diff, std_err_diff = stats.linregress(x_diff, y_diff) if verbose: print('Top 100 DEGs var: ', r_value_diff ** 2) if "y1" in axis_keys.keys(): real_stim = adata[adata.obs[condition_key] == axis_keys["y1"]] x = numpy.var(ctrl.X, axis=0) y = numpy.var(stim.X, axis=0) m, b, r_value, p_value, std_err = stats.linregress(x, y) if verbose: print('All genes var: ', r_value ** 2) df = pd.DataFrame({axis_keys["x"]: x, axis_keys["y"]: y}) ax = sns.regplot(x=axis_keys["x"], y=axis_keys["y"], data=df) ax.tick_params(labelsize=fontsize) if "range" in kwargs: start, stop, step = kwargs.get("range") ax.set_xticks(numpy.arange(start, stop, step)) ax.set_yticks(numpy.arange(start, stop, step)) # _p1 = pyplot.scatter(x, y, marker=".", label=f"{axis_keys['x']}-{axis_keys['y']}") # pyplot.plot(x, m * x + b, "-", color="green") ax.set_xlabel(labels['x'], fontsize=fontsize) ax.set_ylabel(labels['y'], fontsize=fontsize) if "y1" in axis_keys.keys(): y1 = numpy.var(real_stim.X, axis=0) _p2 = pyplot.scatter(x, y1, marker="*", c="grey", alpha=.5, label=f"{axis_keys['x']}-{axis_keys['y1']}") if gene_list is not None: for i in gene_list: j = adata.var_names.tolist().index(i) x_bar = x[j] y_bar = y[j] pyplot.text(x_bar, y_bar, i, fontsize=11, color="black") pyplot.plot(x_bar, y_bar, 'o', color="red", markersize=5) if "y1" in axis_keys.keys(): y1_bar = y1[j] pyplot.text(x_bar, y1_bar, '*', color="black", alpha=.5) if legend: pyplot.legend(loc='center left', bbox_to_anchor=(1, 0.5)) if title is None: pyplot.title(f"", fontsize=12) else: pyplot.title(title, fontsize=12) ax.text(max(x) - max(x) * x_coeff, max(y) - y_coeff * max(y), r'$\mathrm{R^2_{\mathrm{\mathsf{all\ genes}}}}$= ' + f"{r_value ** 2:.2f}", fontsize=kwargs.get("textsize", fontsize)) if diff_genes is not None: ax.text(max(x) - max(x) * x_coeff, max(y) - (y_coeff + 0.15) * max(y), r'$\mathrm{R^2_{\mathrm{\mathsf{top\ 100\ DEGs}}}}$= ' + f"{r_value_diff ** 2:.2f}", fontsize=kwargs.get("textsize", fontsize)) pyplot.savefig(f"{path_to_save}", bbox_inches='tight', dpi=100) if show: pyplot.show() pyplot.close() return r_value**2, r_value_diff**2 def binary_classifier(scg_object, adata, delta, condition_key, conditions, path_to_save, fontsize=14): """ Builds a linear classifier based on the dot product between the difference vector and the latent representation of each cell and plots the dot product results between delta and latent representation. # Parameters scg_object: `~scgen.models.VAEArith` one of scGen models object. adata: `~anndata.AnnData` Annotated Data Matrix. delta: float Difference between stimulated and control cells in latent space condition_key: basestring Condition state to be used. conditions: dict dictionary of conditions. path_to_save: basestring path to save the plot. # Example ```python import anndata import scgen import scanpy as sc train = sc.read("./tests/data/train.h5ad", backup_url="https://goo.gl/33HtVh") network = scgen.VAEArith(x_dimension=train.shape[1], model_path="../models/test") network.train(train_data=train, n_epochs=0) unperturbed_data = train[((train.obs["cell_type"] == "CD4T") & (train.obs["condition"] == "control"))] condition = {"ctrl": "control", "stim": "stimulated"} pred, delta = network.predict(adata=train, adata_to_predict=unperturbed_data, conditions=condition) scgen.plotting.binary_classifier(network, train, delta, condtion_key="condition", conditions={"ctrl": "control", "stim": "stimulated"}, path_to_save="tests/binary_classifier.pdf") network.sess.close() ``` """ # matplotlib.rcParams.update(matplotlib.rcParamsDefault) pyplot.close("all") if sparse.issparse(adata.X): adata.X = adata.X.A cd = adata[adata.obs[condition_key] == conditions["ctrl"], :] stim = adata[adata.obs[condition_key] == conditions["stim"], :] all_latent_cd = scg_object.to_latent(cd.X) all_latent_stim = scg_object.to_latent(stim.X) dot_cd = numpy.zeros((len(all_latent_cd))) dot_sal = numpy.zeros((len(all_latent_stim))) for ind, vec in enumerate(all_latent_cd): dot_cd[ind] = numpy.dot(delta, vec) for ind, vec in enumerate(all_latent_stim): dot_sal[ind] = numpy.dot(delta, vec) pyplot.hist(dot_cd, label=conditions["ctrl"], bins=50, ) pyplot.hist(dot_sal, label=conditions["stim"], bins=50) # pyplot.legend(loc=1, prop={'size': 7}) pyplot.axvline(0, color='k', linestyle='dashed', linewidth=1) pyplot.title(" ", fontsize=fontsize) pyplot.xlabel(" ", fontsize=fontsize) pyplot.ylabel(" ", fontsize=fontsize) pyplot.xticks(fontsize=fontsize) pyplot.yticks(fontsize=fontsize) ax = pyplot.gca() ax.grid(False) pyplot.savefig(f"{path_to_save}", bbox_inches='tight', dpi=100) pyplot.show() PKN  AAscgen/read_load.pyimport os from pathlib import Path from urllib.request import urlretrieve import numpy as np import pandas as pd import anndata def load_file(filename, backup_url=None, **kwargs):#TODO : what if several fileS provided as csv or h5 e.g. x, label1, label2 """ Loads file in any of pandas, numpy or AnnData's extension. # Parameters filename: basestring name of the file which is going to be loaded. backup_url: basestring backup url for downloading data if the file with the specified `filename` does not exists. kwargs: dict dictionary of additional arguments for loading data with each package. # Returns The annotated matrix of loaded data. # Example ```python import scgen train_data_filename = "./data/train.h5ad" train_data = scgen.load_file(train_data_filename) ``` """ numpy_ext = {'npy', 'npz'} pandas_ext = {'csv', 'h5'} adata_ext = {"h5ad"} if not os.path.exists(filename) and backup_url is None: raise FileNotFoundError('Did not find file {}.'.format(filename)) elif not os.path.exists(filename): d = os.path.dirname(filename) if not os.path.exists(d): os.makedirs(d) urlretrieve(backup_url, filename) ext = Path(filename).suffixes[-1][1:] if ext in numpy_ext: return np.load(filename, **kwargs) elif ext in pandas_ext: return pd.read_csv(filename, **kwargs) elif ext in adata_ext: return anndata.read(filename, **kwargs) else: raise ValueError('"{}" does not end on a valid extension.\n' 'Please, provide one of the available extensions.\n{}\n' .format(filename, numpy_ext | pandas_ext)) PKnNk.5scgen/models/__init__.pyfrom ._vae_keras import VAEArithKeras from ._vae import VAEArith from .util import batch_removal, label_encoder, visualize_trained_network_results, data_remover, balancer PKfO]6ZZscgen/models/_vae.pyimport logging import os import numpy import tensorflow as tf from scipy import sparse from .util import balancer, extractor, shuffle_data log = logging.getLogger(__file__) class VAEArith: """ VAE with Arithmetic vector Network class. This class contains the implementation of Variational Auto-encoder network with Vector Arithmetics. # Parameters kwargs: key: `validation_data` : AnnData must be fed if `use_validation` is true. key: `dropout_rate`: float dropout rate key: `learning_rate`: float learning rate of optimization algorithm key: `model_path`: basestring path to save the model after training x_dimension: integer number of gene expression space dimensions. z_dimension: integer number of latent space dimensions. """ def __init__(self, x_dimension, z_dimension=100, **kwargs): self.x_dim = x_dimension self.z_dim = z_dimension self.learning_rate = kwargs.get("learning_rate", 0.001) self.dropout_rate = kwargs.get("dropout_rate", 0.2) self.model_to_use = kwargs.get("model_path", "./models/scgen") self.alpha = kwargs.get("alpha", 0.00005) self.is_training = tf.placeholder(tf.bool, name='training_flag') self.x = tf.placeholder(tf.float32, shape=[None, self.x_dim], name="data") self.z = tf.placeholder(tf.float32, shape=[None, self.z_dim], name="latent") self.init_w = tf.contrib.layers.xavier_initializer() self._create_network() self._loss_function() self.sess = tf.Session() self.saver = tf.train.Saver(max_to_keep=1) self.init = tf.global_variables_initializer().run(session=self.sess) def _encoder(self): """ Constructs the encoder sub-network of VAE. This function implements the encoder part of Variational Auto-encoder. It will transform primary data in the `n_vars` dimension-space to the `z_dimension` latent space. # Parameters No parameters are needed. # Returns mean: Tensor A dense layer consists of means of gaussian distributions of latent space dimensions. log_var: Tensor A dense layer consists of log transformed variances of gaussian distributions of latent space dimensions. """ with tf.variable_scope("encoder", reuse=tf.AUTO_REUSE): h = tf.layers.dense(inputs=self.x, units=800, kernel_initializer=self.init_w, use_bias=False) h = tf.layers.batch_normalization(h, axis=1, training=self.is_training) h = tf.nn.leaky_relu(h) h = tf.layers.dropout(h, self.dropout_rate, training=self.is_training) h = tf.layers.dense(inputs=h, units=800, kernel_initializer=self.init_w, use_bias=False) h = tf.layers.batch_normalization(h, axis=1, training=self.is_training) h = tf.nn.leaky_relu(h) h = tf.layers.dropout(h, self.dropout_rate, training=self.is_training) mean = tf.layers.dense(inputs=h, units=self.z_dim, kernel_initializer=self.init_w) log_var = tf.layers.dense(inputs=h, units=self.z_dim, kernel_initializer=self.init_w) return mean, log_var def _decoder(self): """ Constructs the decoder sub-network of VAE. This function implements the decoder part of Variational Auto-encoder. It will transform constructed latent space to the previous space of data with n_dimensions = n_vars. # Parameters No parameters are needed. # Returns h: Tensor A Tensor for last dense layer with the shape of [n_vars, ] to reconstruct data. """ with tf.variable_scope("decoder", reuse=tf.AUTO_REUSE): h = tf.layers.dense(inputs=self.z_mean, units=800, kernel_initializer=self.init_w, use_bias=False) h = tf.layers.batch_normalization(h, axis=1, training=self.is_training) h = tf.nn.leaky_relu(h) h = tf.layers.dropout(h, self.dropout_rate, training=self.is_training) h = tf.layers.dense(inputs=h, units=800, kernel_initializer=self.init_w, use_bias=False) tf.layers.batch_normalization(h, axis=1, training=self.is_training) h = tf.nn.leaky_relu(h) h = tf.layers.dropout(h, self.dropout_rate, training=self.is_training) h = tf.layers.dense(inputs=h, units=self.x_dim, kernel_initializer=self.init_w, use_bias=True) h = tf.nn.relu(h) return h def _sample_z(self): """ Samples from standard Normal distribution with shape [size, z_dim] and applies re-parametrization trick. It is actually sampling from latent space distributions with N(mu, var) computed in `_encoder` function. # Parameters No parameters are needed. # Returns The computed Tensor of samples with shape [size, z_dim]. """ batch_size = tf.shape(self.mu)[0] eps = tf.random_normal(shape=[batch_size, self.z_dim]) return self.mu + tf.exp(self.log_var / 2) * eps def _create_network(self): """ Constructs the whole VAE network. It is step-by-step constructing the VAE network. First, It will construct the encoder part and get mu, log_var of latent space. Second, It will sample from the latent space to feed the decoder part in next step. Finally, It will reconstruct the data by constructing decoder part of VAE. # Parameters No parameters are needed. # Returns Nothing will be returned. """ self.mu, self.log_var = self._encoder() self.z_mean = self._sample_z() self.x_hat = self._decoder() def _loss_function(self): """ Defines the loss function of VAE network after constructing the whole network. This will define the KL Divergence and Reconstruction loss for VAE and also defines the Optimization algorithm for network. The VAE Loss will be weighted sum of reconstruction loss and KL Divergence loss. # Parameters No parameters are needed. # Returns Nothing will be returned. """ kl_loss = 0.5 * tf.reduce_sum( tf.exp(self.log_var) + tf.square(self.mu) - 1. - self.log_var, 1) recon_loss = 0.5 * tf.reduce_sum(tf.square((self.x - self.x_hat)), 1) self.vae_loss = tf.reduce_mean(recon_loss + self.alpha * kl_loss) with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)): self.solver = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.vae_loss) def to_latent(self, data): """ Map `data` in to the latent space. This function will feed data in encoder part of VAE and compute the latent space coordinates for each sample in data. # Parameters data: numpy nd-array Numpy nd-array to be mapped to latent space. `data.X` has to be in shape [n_obs, n_vars]. # Returns latent: numpy nd-array Returns array containing latent space encoding of 'data' """ latent = self.sess.run(self.z_mean, feed_dict={self.x: data, self.is_training: False}) return latent def _avg_vector(self, data): """ Computes the average of points which computed from mapping `data` to encoder part of VAE. # Parameters data: numpy nd-array Numpy nd-array matrix to be mapped to latent space. Note that `data.X` has to be in shape [n_obs, n_vars]. # Returns The average of latent space mapping in numpy nd-array. """ latent = self.to_latent(data) latent_avg = numpy.average(latent, axis=0) return latent_avg def reconstruct(self, data, use_data=False): """ Map back the latent space encoding via the decoder. # Parameters data: `~anndata.AnnData` Annotated data matrix whether in latent space or gene expression space. use_data: bool This flag determines whether the `data` is already in latent space or not. if `True`: The `data` is in latent space (`data.X` is in shape [n_obs, z_dim]). if `False`: The `data` is not in latent space (`data.X` is in shape [n_obs, n_vars]). # Returns rec_data: 'numpy nd-array' Returns 'numpy nd-array` containing reconstructed 'data' in shape [n_obs, n_vars]. """ if use_data: latent = data else: latent = self.to_latent(data) rec_data = self.sess.run(self.x_hat, feed_dict={self.z_mean: latent, self.is_training: False}) return rec_data def linear_interpolation(self, source_adata, dest_adata, n_steps): """ Maps `source_adata` and `dest_adata` into latent space and linearly interpolate `n_steps` points between them. # Parameters source_adata: `~anndata.AnnData` Annotated data matrix of source cells in gene expression space (`x.X` must be in shape [n_obs, n_vars]) dest_adata: `~anndata.AnnData` Annotated data matrix of destinations cells in gene expression space (`y.X` must be in shape [n_obs, n_vars]) n_steps: int Number of steps to interpolate points between `source_adata`, `dest_adata`. # Returns interpolation: numpy nd-array Returns the `numpy nd-array` of interpolated points in gene expression space. # Example ```python import anndata import scgen train_data = anndata.read("./data/train.h5ad") validation_data = anndata.read("./data/validation.h5ad") network = scgen.VAEArith(x_dimension= train_data.shape[1], model_path="./models/test" ) network.train(train_data=train_data, use_validation=True, valid_data=validation_data, shuffle=True, n_epochs=2) souece = train_data[((train_data.obs["cell_type"] == "CD8T") & (train_data.obs["condition"] == "control"))] destination = train_data[((train_data.obs["cell_type"] == "CD8T") & (train_data.obs["condition"] == "stimulated"))] interpolation = network.linear_interpolation(souece, destination, n_steps=25) ``` """ if sparse.issparse(source_adata.X): source_average = source_adata.X.A.mean(axis=0).reshape((1, source_adata.shape[1])) else: source_average = source_adata.X.mean(axis=0).reshape((1, source_adata.shape[1])) if sparse.issparse(dest_adata.X): dest_average = dest_adata.X.A.mean(axis=0).reshape((1, dest_adata.shape[1])) else: dest_average = dest_adata.X.mean(axis=0).reshape((1, dest_adata.shape[1])) start = self.to_latent(source_average) end = self.to_latent(dest_average) vectors = numpy.zeros((n_steps, start.shape[1])) alpha_values = numpy.linspace(0, 1, n_steps) for i, alpha in enumerate(alpha_values): vector = start * (1 - alpha) + end * alpha vectors[i, :] = vector vectors = numpy.array(vectors) interpolation = self.reconstruct(vectors, use_data=True) return interpolation def predict(self, adata, conditions, cell_type_key, condition_key, adata_to_predict=None, celltype_to_predict=None, obs_key="all", biased=False): """ Predicts the cell type provided by the user in stimulated condition. # Parameters celltype_to_predict: basestring The cell type you want to be predicted. obs_key: basestring or dict Dictionary of celltypes you want to be observed for prediction. adata_to_predict: `~anndata.AnnData` Adata for unpertubed cells you want to be predicted. # Returns predicted_cells: numpy nd-array `numpy nd-array` of predicted cells in primary space. delta: float Difference between stimulated and control cells in latent space # Example ```python import anndata import scgen train_data = anndata.read("./data/train.h5ad" validation_data = anndata.read("./data/validation.h5ad") network = scgen.VAEArith(x_dimension= train_data.shape[1], model_path="./models/test" ) network.train(train_data=train_data, use_validation=True, valid_data=validation_data, shuffle=True, n_epochs=2) prediction, delta = network.predict(adata= train_data, celltype_to_predict= "CD4T", conditions={"ctrl": "control", "stim": "stimulated"}) ``` """ if obs_key == "all": ctrl_x = adata[adata.obs[condition_key] == conditions["ctrl"], :] stim_x = adata[adata.obs[condition_key] == conditions["stim"], :] if not biased: ctrl_x = balancer(ctrl_x, cell_type_key=cell_type_key, condition_key=condition_key) stim_x = balancer(stim_x, cell_type_key=cell_type_key, condition_key=condition_key) else: key = list(obs_key.keys())[0] values = obs_key[key] subset = adata[adata.obs[key].isin(values)] ctrl_x = subset[subset.obs[condition_key] == conditions["ctrl"], :] stim_x = subset[subset.obs[condition_key] == conditions["stim"], :] if len(values) > 1 and not biased: ctrl_x = balancer(ctrl_x, cell_type_key=cell_type_key, condition_key=condition_key) stim_x = balancer(stim_x, cell_type_key=cell_type_key, condition_key=condition_key) if celltype_to_predict is not None and adata_to_predict is not None: raise Exception("Please provide either a cell type or adata not both!") if celltype_to_predict is None and adata_to_predict is None: raise Exception("Please provide a cell type name or adata for your unperturbed cells") if celltype_to_predict is not None: ctrl_pred = extractor(adata, celltype_to_predict, conditions, cell_type_key, condition_key)[1] else: ctrl_pred = adata_to_predict if not biased: eq = min(ctrl_x.X.shape[0], stim_x.X.shape[0]) cd_ind = numpy.random.choice(range(ctrl_x.shape[0]), size=eq, replace=False) stim_ind = numpy.random.choice(range(stim_x.shape[0]), size=eq, replace=False) else: cd_ind = numpy.random.choice(range(ctrl_x.shape[0]), size=ctrl_x.shape[0], replace=False) stim_ind = numpy.random.choice(range(stim_x.shape[0]), size=stim_x.shape[0], replace=False) if sparse.issparse(ctrl_x.X) and sparse.issparse(stim_x.X): latent_ctrl = self._avg_vector(ctrl_x.X.A[cd_ind, :]) latent_sim = self._avg_vector(stim_x.X.A[stim_ind, :]) else: latent_ctrl = self._avg_vector(ctrl_x.X[cd_ind, :]) latent_sim = self._avg_vector(stim_x.X[stim_ind, :]) delta = latent_sim - latent_ctrl if sparse.issparse(ctrl_pred.X): latent_cd = self.to_latent(ctrl_pred.X.A) else: latent_cd = self.to_latent(ctrl_pred.X) stim_pred = delta + latent_cd predicted_cells = self.reconstruct(stim_pred, use_data=True) return predicted_cells, delta def predict_cross(self, train, data, conditions): cd_x = train.copy()[train.obs["condition"] == conditions["ctrl"], :] cd_x = balancer(cd_x) stim_x = train.copy()[train.obs["condition"] == conditions["stim"], :] stim_x = balancer(stim_x) cd_y = data.copy() eq = min(cd_x.X.shape[0], stim_x.X.shape[0]) cd_ind = numpy.random.choice(range(cd_x.shape[0]), size=eq, replace=False) stim_ind = numpy.random.choice(range(stim_x.shape[0]), size=eq, replace=False) lat_cd = self._avg_vector(cd_x.X[cd_ind, :]) lat_stim = self._avg_vector(stim_x.X[stim_ind, :]) delta = lat_stim - lat_cd latent_cd = self.to_latent(cd_y.X) stim_pred = delta + latent_cd predicted_cells = self.reconstruct(stim_pred, use_data=True) return predicted_cells, delta def restore_model(self): """ restores model weights from `model_to_use`. # Parameters No parameters are needed. # Returns Nothing will be returned. # Example ```python import anndata import scgen train_data = anndata.read("./data/train.h5ad") validation_data = anndata.read("./data/validation.h5ad") network = scgen.VAEArith(x_dimension= train_data.shape[1], model_path="./models/test" ) network.restore_model() ``` """ self.saver.restore(self.sess, self.model_to_use) def train(self, train_data, use_validation=False, valid_data=None, n_epochs=25, batch_size=32, early_stop_limit=20, threshold=0.0025, initial_run=True, shuffle=True, save=True, verbose=False): """ Trains the network `n_epochs` times with given `train_data` and validates the model using validation_data if it was given in the constructor function. This function is using `early stopping` technique to prevent over-fitting. # Parameters train_data: scanpy AnnData Annotated Data Matrix for training VAE network. use_validation: bool if `True`: must feed a valid AnnData object to `valid_data` argument. valid_data: scanpy AnnData Annotated Data Matrix for validating VAE network after each epoch. n_epochs: int Number of epochs to iterate and optimize network weights batch_size: integer size of each batch of training dataset to be fed to network while training. early_stop_limit: int Number of consecutive epochs in which network loss is not going lower. After this limit, the network will stop training. threshold: float Threshold for difference between consecutive validation loss values if the difference is upper than this `threshold`, this epoch will not considered as an epoch in early stopping. initial_run: bool if `True`: The network will initiate training and log some useful initial messages. if `False`: Network will resume the training using `restore_model` function in order to restore last model which has been trained with some training dataset. shuffle: bool if `True`: shuffles the training dataset # Returns Nothing will be returned # Example ```python import anndata import scgen train_data = anndata.read("./data/train.h5ad" validation_data = anndata.read("./data/validation.h5ad" network = scgen.VAEArith(x_dimension= train_data.shape[1], model_path="./models/test") network.train(train_data=train_data, use_validation=True, valid_data=validation_data, shuffle=True, n_epochs=2) ``` """ if initial_run: log.info("----Training----") if not initial_run: self.saver.restore(self.sess, self.model_to_use) if use_validation and valid_data is None: raise Exception("valid_data is None but use_validation is True.") if shuffle: train_data = shuffle_data(train_data) loss_hist = [] patience = early_stop_limit min_delta = threshold patience_cnt = 0 for it in range(n_epochs): train_loss = 0.0 for lower in range(0, train_data.shape[0], batch_size): upper = min(lower + batch_size, train_data.shape[0]) if sparse.issparse(train_data.X): x_mb = train_data[lower:upper, :].X.A else: x_mb = train_data[lower:upper, :].X if upper - lower > 1: _, current_loss_train = self.sess.run([self.solver, self.vae_loss], feed_dict={self.x: x_mb, self.is_training: True}) train_loss += current_loss_train if use_validation: valid_loss = 0 for lower in range(0, valid_data.shape[0], batch_size): upper = min(lower + batch_size, valid_data.shape[0]) if sparse.issparse(valid_data.X): x_mb = valid_data[lower:upper, :].X.A else: x_mb = valid_data[lower:upper, :].X current_loss_valid = self.sess.run(self.vae_loss, feed_dict={self.x: x_mb, self.is_training: False}) valid_loss += current_loss_valid loss_hist.append(valid_loss / valid_data.shape[0]) if it > 0 and loss_hist[it - 1] - loss_hist[it] > min_delta: patience_cnt = 0 else: patience_cnt += 1 if patience_cnt > patience: save_path = self.saver.save(self.sess, self.model_to_use) break if verbose: print(f"Epoch {it}: Train Loss: {train_loss / (train_data.shape[0] // batch_size)} Valid Loss: {valid_loss / (valid_data.shape[0] // batch_size)}") else: if verbose: print(f"Epoch {it}: Train Loss: {train_loss / (train_data.shape[0] // batch_size)}") if save: os.makedirs(self.model_to_use, exist_ok=True) save_path = self.saver.save(self.sess, self.model_to_use) log.info(f"Model saved in file: {save_path}. Training finished") PKfO`RPX/X/Xscgen/models/_vae_keras.pyimport logging import os import keras import numpy import tensorflow as tf from keras import backend as K, Model from keras.callbacks import CSVLogger, LambdaCallback, EarlyStopping from keras.layers import Input, Dense, BatchNormalization, LeakyReLU, Dropout, Lambda from keras.models import load_model from scipy import sparse import scgen from .util import balancer, extractor, shuffle_data log = logging.getLogger(__file__) class VAEArithKeras: """ VAE with Arithmetic vector Network class. This class contains the implementation of Variational Auto-encoder network with Vector Arithmetics. Parameters ---------- kwargs: :key `validation_data` : AnnData must be fed if `use_validation` is true. :key dropout_rate: float dropout rate :key learning_rate: float learning rate of optimization algorithm :key model_path: basestring path to save the model after training x_dimension: integer number of gene expression space dimensions. z_dimension: integer number of latent space dimensions. See also -------- CVAE from scgen.models._cvae : Conditional VAE implementation. """ def __init__(self, x_dimension, z_dimension=100, **kwargs): self.x_dim = x_dimension self.z_dim = z_dimension self.learning_rate = kwargs.get("learning_rate", 0.001) self.dropout_rate = kwargs.get("dropout_rate", 0.2) self.model_to_use = kwargs.get("model_path", "./models/") self.alpha = kwargs.get("alpha", 0.00005) self.x = Input(shape=(x_dimension,), name="input") self.z = Input(shape=(z_dimension,), name="latent") self.init_w = keras.initializers.glorot_normal() self._create_network() self._loss_function() self.vae_model.summary() def _encoder(self): """ Constructs the encoder sub-network of VAE. This function implements the encoder part of Variational Auto-encoder. It will transform primary data in the `n_vars` dimension-space to the `z_dimension` latent space. Parameters ---------- No parameters are needed. Returns ------- mean: Tensor A dense layer consists of means of gaussian distributions of latent space dimensions. log_var: Tensor A dense layer consists of log transformed variances of gaussian distributions of latent space dimensions. """ h = Dense(800, kernel_initializer=self.init_w, use_bias=False)(self.x) h = BatchNormalization(axis=1)(h) h = LeakyReLU()(h) h = Dropout(self.dropout_rate)(h) h = Dense(800, kernel_initializer=self.init_w, use_bias=False)(h) h = BatchNormalization(axis=1)(h) h = LeakyReLU()(h) h = Dropout(self.dropout_rate)(h) # h = Dense(512, kernel_initializer=self.init_w, use_bias=False)(h) # h = BatchNormalization()(h) # h = LeakyReLU()(h) # h = Dropout(self.dropout_rate)(h) # h = Dense(256, kernel_initializer=self.init_w, use_bias=False)(h) # h = BatchNormalization()(h) # h = LeakyReLU()(h) # h = Dropout(self.dropout_rate)(h) mean = Dense(self.z_dim, kernel_initializer=self.init_w)(h) log_var = Dense(self.z_dim, kernel_initializer=self.init_w)(h) z = Lambda(self._sample_z, output_shape=(self.z_dim,), name="Z")([mean, log_var]) self.encoder_model = Model(inputs=self.x, outputs=z, name="encoder") return mean, log_var def _decoder(self): """ Constructs the decoder sub-network of VAE. This function implements the decoder part of Variational Auto-encoder. It will transform constructed latent space to the previous space of data with n_dimensions = n_vars. Parameters ---------- No parameters are needed. Returns ------- h: Tensor A Tensor for last dense layer with the shape of [n_vars, ] to reconstruct data. """ h = Dense(800, kernel_initializer=self.init_w, use_bias=False)(self.z) h = BatchNormalization(axis=1)(h) h = LeakyReLU()(h) h = Dropout(self.dropout_rate)(h) h = Dense(800, kernel_initializer=self.init_w, use_bias=False)(h) h = BatchNormalization(axis=1)(h) h = LeakyReLU()(h) h = Dropout(self.dropout_rate)(h) # h = Dense(768, kernel_initializer=self.init_w, use_bias=False)(h) # h = BatchNormalization()(h) # h = LeakyReLU()(h) # h = Dropout(self.dropout_rate)(h) # h = Dense(1024, kernel_initializer=self.init_w, use_bias=False)(h) # h = BatchNormalization()(h) # h = LeakyReLU()(h) # h = Dropout(self.dropout_rate)(h) h = Dense(self.x_dim, kernel_initializer=self.init_w, use_bias=True)(h) self.decoder_model = Model(inputs=self.z, outputs=h, name="decoder") return h @staticmethod def _sample_z(args): """ Samples from standard Normal distribution with shape [size, z_dim] and applies re-parametrization trick. It is actually sampling from latent space distributions with N(mu, var) computed in `_encoder` function. Parameters ---------- No parameters are needed. Returns ------- The computed Tensor of samples with shape [size, z_dim]. """ mu, log_var = args batch_size = K.shape(mu)[0] z_dim = K.shape(mu)[1] eps = K.random_normal(shape=[batch_size, z_dim]) return mu + K.exp(log_var / 2) * eps def _create_network(self): """ Constructs the whole VAE network. It is step-by-step constructing the VAE network. First, It will construct the encoder part and get mu, log_var of latent space. Second, It will sample from the latent space to feed the decoder part in next step. Finally, It will reconstruct the data by constructing decoder part of VAE. Parameters ---------- No parameters are needed. Returns ------- Nothing will be returned. """ self.mu, self.log_var = self._encoder() self.x_hat = self._decoder() self.vae_model = Model(inputs=self.x, outputs=self.decoder_model(self.encoder_model(self.x)), name="VAE") def _loss_function(self): """ Defines the loss function of VAE network after constructing the whole network. This will define the KL Divergence and Reconstruction loss for VAE and also defines the Optimization algorithm for network. The VAE Loss will be weighted sum of reconstruction loss and KL Divergence loss. Parameters ---------- No parameters are needed. Returns ------- Nothing will be returned. """ def vae_loss(y_true, y_pred): return K.mean(recon_loss(y_true, y_pred) + self.alpha * kl_loss(y_true, y_pred)) def kl_loss(y_true, y_pred): return 0.5 * K.sum(K.exp(self.log_var) + K.square(self.mu) - 1. - self.log_var, axis=1) def recon_loss(y_true, y_pred): return 0.5 * K.sum(K.square((y_true - y_pred)), axis=1) self.vae_optimizer = keras.optimizers.Adam(lr=self.learning_rate) self.vae_model.compile(optimizer=self.vae_optimizer, loss=vae_loss, metrics=[kl_loss, recon_loss]) def to_latent(self, data): """ Map `data` in to the latent space. This function will feed data in encoder part of VAE and compute the latent space coordinates for each sample in data. Parameters ---------- data: numpy nd-array Numpy nd-array to be mapped to latent space. `data.X` has to be in shape [n_obs, n_vars]. Returns ------- latent: numpy nd-array Returns array containing latent space encoding of 'data' """ latent = self.encoder_model.predict(data) return latent def _avg_vector(self, data): """ Computes the average of points which computed from mapping `data` to encoder part of VAE. Parameters ---------- data: numpy nd-array Numpy nd-array matrix to be mapped to latent space. Note that `data.X` has to be in shape [n_obs, n_vars]. Returns ------- The average of latent space mapping in numpy nd-array. """ latent = self.to_latent(data) latent_avg = numpy.average(latent, axis=0) return latent_avg def reconstruct(self, data): """ Map back the latent space encoding via the decoder. Parameters ---------- data: `~anndata.AnnData` Annotated data matrix whether in latent space or gene expression space. use_data: bool This flag determines whether the `data` is already in latent space or not. if `True`: The `data` is in latent space (`data.X` is in shape [n_obs, z_dim]). if `False`: The `data` is not in latent space (`data.X` is in shape [n_obs, n_vars]). Returns ------- rec_data: 'numpy nd-array' Returns 'numpy nd-array` containing reconstructed 'data' in shape [n_obs, n_vars]. """ rec_data = self.decoder_model.predict(x=data) return rec_data def linear_interpolation(self, source_adata, dest_adata, n_steps): """ Maps `source_adata` and `dest_adata` into latent space and linearly interpolate `n_steps` points between them. Parameters ---------- source_adata: `~anndata.AnnData` Annotated data matrix of source cells in gene expression space (`x.X` must be in shape [n_obs, n_vars]) dest_adata: `~anndata.AnnData` Annotated data matrix of destinations cells in gene expression space (`y.X` must be in shape [n_obs, n_vars]) n_steps: int Number of steps to interpolate points between `source_adata`, `dest_adata`. Returns ------- interpolation: numpy nd-array Returns the `numpy nd-array` of interpolated points in gene expression space. Example -------- >>> import anndata >>> import scgen >>> train_data = anndata.read("./data/train.h5ad") >>> validation_data = anndata.read("./data/validation.h5ad") >>> network = scgen.VAEArith(x_dimension= train_data.shape[1], model_path="./models/test" ) >>> network.train(train_data=train_data, use_validation=True, validation_data=validation_data, shuffle=True, n_epochs=2) >>> souece = train_data[((train_data.obs["cell_type"] == "CD8T") & (train_data.obs["condition"] == "control"))] >>> destination = train_data[((train_data.obs["cell_type"] == "CD8T") & (train_data.obs["condition"] == "stimulated"))] >>> interpolation = network.linear_interpolation(souece, destination, n_steps=25) """ if sparse.issparse(source_adata.X): source_average = source_adata.X.A.mean(axis=0).reshape((1, source_adata.shape[1])) else: source_average = source_adata.X.A.mean(axis=0).reshape((1, source_adata.shape[1])) if sparse.issparse(dest_adata.X): dest_average = dest_adata.X.A.mean(axis=0).reshape((1, dest_adata.shape[1])) else: dest_average = dest_adata.X.A.mean(axis=0).reshape((1, dest_adata.shape[1])) start = self.to_latent(source_average) end = self.to_latent(dest_average) vectors = numpy.zeros((n_steps, start.shape[1])) alpha_values = numpy.linspace(0, 1, n_steps) for i, alpha in enumerate(alpha_values): vector = start * (1 - alpha) + end * alpha vectors[i, :] = vector vectors = numpy.array(vectors) interpolation = self.reconstruct(vectors) return interpolation def predict(self, adata, conditions, cell_type_key, condition_key, adata_to_predict=None, celltype_to_predict=None, obs_key="all"): """ Predicts the cell type provided by the user in stimulated condition. Parameters ---------- celltype_to_predict: basestring The cell type you want to be predicted. obs_key: basestring or dict Dictionary of celltypes you want to be observed for prediction. adata_to_predict: `~anndata.AnnData` Adata for unpertubed cells you want to be predicted. Returns ------- predicted_cells: numpy nd-array `numpy nd-array` of predicted cells in primary space. delta: float Difference between stimulated and control cells in latent space Example -------- >>> import anndata >>> import scgen >>> train_data = anndata.read("./data/train.h5ad" >>> validation_data = anndata.read("./data/validation.h5ad") >>> network = scgen.VAEArith(x_dimension= train_data.shape[1], model_path="./models/test" ) >>> network.train(train_data=train_data, use_validation=True, validation_data=validation_data, shuffle=True, n_epochs=2) >>> prediction, delta = network.predict(adata= train_data, celltype_to_predict= "CD4T", conditions={"ctrl": "control", "stim": "stimulated"}) """ if obs_key == "all": ctrl_x = adata[adata.obs["condition"] == conditions["ctrl"], :] stim_x = adata[adata.obs["condition"] == conditions["stim"], :] ctrl_x = balancer(ctrl_x, cell_type_key=cell_type_key, condition_key=condition_key) stim_x = balancer(stim_x, cell_type_key=cell_type_key, condition_key=condition_key) else: key = list(obs_key.keys())[0] values = obs_key[key] subset = adata[adata.obs[key].isin(values)] ctrl_x = subset[subset.obs["condition"] == conditions["ctrl"], :] stim_x = subset[subset.obs["condition"] == conditions["stim"], :] if len(values) > 1: ctrl_x = balancer(ctrl_x, cell_type_key=cell_type_key, condition_key=condition_key) stim_x = balancer(stim_x, cell_type_key=cell_type_key, condition_key=condition_key) if celltype_to_predict is not None and adata_to_predict is not None: raise Exception("Please provide either a cell type or adata not both!") if celltype_to_predict is None and adata_to_predict is None: raise Exception("Please provide a cell type name or adata for your unperturbed cells") if celltype_to_predict is not None: ctrl_pred = extractor(adata, celltype_to_predict, conditions, cell_type_key, condition_key)[1] else: ctrl_pred = adata_to_predict eq = min(ctrl_x.X.shape[0], stim_x.X.shape[0]) cd_ind = numpy.random.choice(range(ctrl_x.shape[0]), size=eq, replace=False) stim_ind = numpy.random.choice(range(stim_x.shape[0]), size=eq, replace=False) if sparse.issparse(ctrl_x.X) and sparse.issparse(stim_x.X): latent_ctrl = self._avg_vector(ctrl_x.X.A[cd_ind, :]) latent_sim = self._avg_vector(stim_x.X.A[stim_ind, :]) else: latent_ctrl = self._avg_vector(ctrl_x.X[cd_ind, :]) latent_sim = self._avg_vector(stim_x.X[stim_ind, :]) delta = latent_sim - latent_ctrl if sparse.issparse(ctrl_pred.X): latent_cd = self.to_latent(ctrl_pred.X.A) else: latent_cd = self.to_latent(ctrl_pred.X) stim_pred = delta + latent_cd predicted_cells = self.reconstruct(stim_pred) return predicted_cells, delta def restore_model(self): """ restores model weights from `model_to_use`. Parameters ---------- No parameters are needed. Returns ------- Nothing will be returned. Example -------- >>> import anndata >>> import scgen >>> train_data = anndata.read("./data/train.h5ad") >>> validation_data = anndata.read("./data/validation.h5ad") >>> network = scgen.VAEArith(x_dimension= train_data.shape[1], model_path="./models/test" ) >>> network.restore_model() """ self.vae_model = load_model(os.path.join(self.model_to_use, 'vae.h5'), compile=False) self.encoder_model = load_model(os.path.join(self.model_to_use, 'encoder.h5'), compile=False) self.decoder_model = load_model(os.path.join(self.model_to_use, 'decoder.h5'), compile=False) self._loss_function() def train(self, train_data, validation_data=None, n_epochs=25, batch_size=32, early_stop_limit=20, threshold=0.0025, initial_run=True, shuffle=True, verbose=1, save=True, checkpoint=50, **kwargs): """ Trains the network `n_epochs` times with given `train_data` and validates the model using validation_data if it was given in the constructor function. This function is using `early stopping` technique to prevent over-fitting. Parameters ---------- train_data: scanpy AnnData Annotated Data Matrix for training VAE network. validation_data: scanpy AnnData Annotated Data Matrix for validating VAE network after each epoch. n_epochs: int Number of epochs to iterate and optimize network weights batch_size: integer size of each batch of training dataset to be fed to network while training. early_stop_limit: int Number of consecutive epochs in which network loss is not going lower. After this limit, the network will stop training. threshold: float Threshold for difference between consecutive validation loss values if the difference is upper than this `threshold`, this epoch will not considered as an epoch in early stopping. initial_run: bool if `True`: The network will initiate training and log some useful initial messages. if `False`: Network will resume the training using `restore_model` function in order to restore last model which has been trained with some training dataset. shuffle: bool if `True`: shuffles the training dataset Returns ------- Nothing will be returned Example -------- ```python import anndata import scgen train_data = anndata.read("./data/train.h5ad" validation_data = anndata.read("./data/validation.h5ad" network = scgen.VAEArith(x_dimension= train_data.shape[1], model_path="./models/test") network.train(train_data=train_data, use_validation=True, valid_data=validation_data, shuffle=True, n_epochs=2) ``` """ if initial_run: log.info("----Training----") if shuffle: train_data = shuffle_data(train_data) if sparse.issparse(train_data.X): train_data.X = train_data.X.A # def on_epoch_end(epoch, logs): # if epoch % checkpoint == 0: # path_to_save = os.path.join(kwargs.get("path_to_save"), f"epoch_{epoch}") + "/" # scgen.visualize_trained_network_results(self, vis_data, kwargs.get("cell_type"), # kwargs.get("conditions"), # kwargs.get("condition_key"), kwargs.get("cell_type_key"), # path_to_save, # plot_umap=False, # plot_reg=True) callbacks = [ # LambdaCallback(on_epoch_end=on_epoch_end), # EarlyStopping(patience=early_stop_limit, monitor='loss', min_delta=threshold), CSVLogger(filename="./csv_logger.log") ] if validation_data is not None: result = self.vae_model.fit(x=train_data.X, y=train_data.X, epochs=n_epochs, batch_size=batch_size, validation_data=(validation_data.X, validation_data.X), shuffle=shuffle, callbacks=callbacks, verbose=verbose) else: result = self.vae_model.fit(x=train_data.X, y=train_data.X, epochs=n_epochs, batch_size=batch_size, shuffle=shuffle, callbacks=callbacks, verbose=verbose) if save is True: os.makedirs(self.model_to_use, exist_ok=True) self.vae_model.save(os.path.join("vae.h5"), overwrite=True) self.encoder_model.save(os.path.join("encoder.h5"), overwrite=True) self.decoder_model.save(os.path.join("decoder.h5"), overwrite=True) log.info(f"Models are saved in file: {self.model_to_use}. Training finished") return result PK&tOY䂱,j,jscgen/models/util.pyimport os from random import shuffle import anndata import numpy as np import scanpy as sc from matplotlib import pyplot as plt from scipy import sparse from sklearn import preprocessing import pandas as pd import scgen def data_remover(adata, remain_list, remove_list, cell_type_key, condition_key): """ Removes specific cell type in stimulated condition form `adata`. # Parameters adata: `~anndata.AnnData` Annotated data matrix remain_list: list list of cell types which are going to be remained in `adata`. remove_list: list list of cell types which are going to be removed from `adata`. # Returns merged_data: list returns array of specified cell types in stimulated condition # Example ```python import scgen import anndata train_data = anndata.read("./data/train_kang.h5ad") remove_list = ["CD14+Mono", "CD8T"] remain_list = ["CD4T", "Dendritic"] filtered_data = data_remover(train_data, remain_list, remove_list) ``` """ source_data = [] for i in remain_list: source_data.append(extractor(adata, i, conditions={"ctrl": "control", "stim": "stimulated"}, cell_type_key=cell_type_key, condition_key=condition_key)[3]) target_data = [] for i in remove_list: target_data.append(extractor(adata, i, conditions={"ctrl": "control", "stim": "stimulated"}, cell_type_key=cell_type_key, condition_key=condition_key)[1]) merged_data = training_data_provider(source_data, target_data) merged_data.var_names = adata.var_names return merged_data def extractor(data, cell_type, conditions, cell_type_key="cell_type", condition_key="condition"): """ Returns a list of `data` files while filtering for a specific `cell_type`. # Parameters data: `~anndata.AnnData` Annotated data matrix cell_type: basestring specific cell type to be extracted from `data`. conditions: dict dictionary of stimulated/control of `data`. # Returns list of `data` files while filtering for a specific `cell_type`. # Example ```python import scgen import anndata train_data = anndata.read("./data/train.h5ad") test_data = anndata.read("./data/test.h5ad") train_data_extracted_list = extractor(train_data, "CD4T", conditions={"ctrl": "control", "stim": "stimulated"}) ``` """ cell_with_both_condition = data[data.obs[cell_type_key] == cell_type] condtion_1 = data[(data.obs[cell_type_key] == cell_type) & (data.obs[condition_key] == conditions["ctrl"])] condtion_2 = data[(data.obs[cell_type_key] == cell_type) & (data.obs[condition_key] == conditions["stim"])] training = data[~((data.obs[cell_type_key] == cell_type) & (data.obs[condition_key] == conditions["stim"]))] return [training, condtion_1, condtion_2, cell_with_both_condition] def training_data_provider(train_s, train_t): """ Concatenates two lists containing adata files # Parameters train_s: `~anndata.AnnData` Annotated data matrix. train_t: `~anndata.AnnData` Annotated data matrix. # Returns Concatenated Annotated data matrix. # Example ```python import scgen import anndata train_data = anndata.read("./data/train_kang.h5ad") test_data = anndata.read("./data/test.h5ad") whole_data = training_data_provider(train_data, test_data) ``` """ train_s_X = [] train_s_diet = [] train_s_groups = [] for i in train_s: train_s_X.append(i.X.A) train_s_diet.append(i.obs["condition"].tolist()) train_s_groups.append(i.obs["cell_type"].tolist()) train_s_X = np.concatenate(train_s_X) temp = [] for i in train_s_diet: temp = temp + i train_s_diet = temp temp = [] for i in train_s_groups: temp = temp + i train_s_groups = temp train_t_X = [] train_t_diet = [] train_t_groups = [] for i in train_t: train_t_X.append(i.X.A) train_t_diet.append(i.obs["condition"].tolist()) train_t_groups.append(i.obs["cell_type"].tolist()) temp = [] for i in train_t_diet: temp = temp + i train_t_diet = temp temp = [] for i in train_t_groups: temp = temp + i train_t_groups = temp train_t_X = np.concatenate(train_t_X) train_real = np.concatenate([train_s_X, train_t_X]) # concat all train_real = anndata.AnnData(train_real) train_real.obs["condition"] = train_s_diet + train_t_diet train_real.obs["cell_type"] = train_s_groups + train_t_groups return train_real def balancer(adata, cell_type_key="cell_type", condition_key="condition"): """ Makes cell type population equal. # Parameters adata: `~anndata.AnnData` Annotated data matrix. # Returns balanced_data: `~anndata.AnnData` Equal cell type population Annotated data matrix. # Example ```python import scgen import anndata train_data = anndata.read("./train_kang.h5ad") train_ctrl = train_data[train_data.obs["condition"] == "control", :] train_ctrl = balancer(train_ctrl) ``` """ class_names = np.unique(adata.obs[cell_type_key]) class_pop = {} for cls in class_names: class_pop[cls] = adata.copy()[adata.obs[cell_type_key] == cls].shape[0] max_number = np.max(list(class_pop.values())) all_data_x = [] all_data_label = [] all_data_condition = [] for cls in class_names: temp = adata.copy()[adata.obs[cell_type_key] == cls] index = np.random.choice(range(len(temp)), max_number) if sparse.issparse(temp.X): temp_x = temp.X.A[index] else: temp_x = temp.X[index] all_data_x.append(temp_x) temp_ct = np.repeat(cls, max_number) all_data_label.append(temp_ct) temp_cc = np.repeat(np.unique(temp.obs[condition_key]), max_number) all_data_condition.append(temp_cc) balanced_data = anndata.AnnData(np.concatenate(all_data_x)) balanced_data.obs[cell_type_key] = np.concatenate(all_data_label) balanced_data.obs[condition_key] = np.concatenate(all_data_label) class_names = np.unique(balanced_data.obs[cell_type_key]) class_pop = {} for cls in class_names: class_pop[cls] = len(balanced_data[balanced_data.obs[cell_type_key] == cls]) return balanced_data def shuffle_data(adata, labels=None): """ Shuffles the `adata`. # Parameters adata: `~anndata.AnnData` Annotated data matrix. labels: numpy nd-array list of encoded labels # Returns adata: `~anndata.AnnData` Shuffled annotated data matrix. labels: numpy nd-array Array of shuffled labels if `labels` is not None. # Example ```python import scgen import anndata import pandas as pd train_data = anndata.read("./data/train.h5ad") train_labels = pd.read_csv("./data/train_labels.csv", header=None) train_data, train_labels = shuffle_data(train_data, train_labels) ``` """ ind_list = [i for i in range(adata.shape[0])] shuffle(ind_list) if sparse.issparse(adata.X): x = adata.X.A[ind_list, :] else: x = adata.X[ind_list, :] if labels is not None: labels = labels[ind_list] adata = anndata.AnnData(x, obs={"labels": list(labels)}) return adata, labels else: return anndata.AnnData(x, obs=adata.obs) def batch_removal(network, adata, batch_key="batch", cell_label_key="cell_type"): """ Removes batch effect of adata # Parameters network: `scgen VAE` Variational Auto-encoder class object after training the network. adata: `~anndata.AnnData` Annotated data matrix. adata must have `batch` and `cell_type` column in its obs. # Returns corrected: `~anndata.AnnData` Annotated matrix of corrected data consisting of all cell types whether they have batch effect or not. # Example ```python import scgen import anndata train = anndata.read("data/pancreas.h5ad") train.obs["cell_type"] = train.obs["celltype"].tolist() network = scgen.VAEArith(x_dimension=train.shape[1], model_path="./models/batch") network.train(train_data=train, n_epochs=20) corrected_adata = scgen.batch_removal(network, train) ``` """ if sparse.issparse(adata.X): latent_all = network.to_latent(adata.X.A) else: latent_all = network.to_latent(adata.X) adata_latent = anndata.AnnData(latent_all) adata_latent.obs = adata.obs.copy(deep=True) unique_cell_types = np.unique(adata_latent.obs[cell_label_key]) shared_ct = [] not_shared_ct = [] for cell_type in unique_cell_types: temp_cell = adata_latent[adata_latent.obs[cell_label_key] == cell_type] if len(np.unique(temp_cell.obs[batch_key])) < 2: cell_type_ann = adata_latent[adata_latent.obs[cell_label_key] == cell_type] not_shared_ct.append(cell_type_ann) continue temp_cell = adata_latent[adata_latent.obs[cell_label_key] == cell_type] batch_list = {} batch_ind = {} max_batch = 0 max_batch_ind = "" batches = np.unique(temp_cell.obs[batch_key]) for i in batches: temp = temp_cell[temp_cell.obs[batch_key] == i] temp_ind = temp_cell.obs[batch_key] == i if max_batch < len(temp): max_batch = len(temp) max_batch_ind = i batch_list[i] = temp batch_ind[i] = temp_ind max_batch_ann = batch_list[max_batch_ind] for study in batch_list: delta = np.average(max_batch_ann.X, axis=0) - np.average(batch_list[study].X, axis=0) batch_list[study].X = delta + batch_list[study].X temp_cell[batch_ind[study]].X = batch_list[study].X shared_ct.append(temp_cell) all_shared_ann = anndata.AnnData.concatenate(*shared_ct, batch_key="concat_batch") if "concat_batch" in all_shared_ann.obs.columns: del all_shared_ann.obs["concat_batch"] if len(not_shared_ct) < 1: corrected = anndata.AnnData(network.reconstruct(all_shared_ann.X, use_data=True)) corrected.obs = all_shared_ann.obs.copy(deep=True) corrected.var_names = adata.var_names.tolist() corrected.obs_names = adata.obs_names.tolist() return corrected else: all_not_shared_ann = anndata.AnnData.concatenate(*not_shared_ct, batch_key="concat_batch") all_corrected_data = anndata.AnnData.concatenate(all_shared_ann, all_not_shared_ann, batch_key="concat_batch") if "concat_batch" in all_shared_ann.obs.columns: del all_corrected_data.obs["concat_batch"] corrected = anndata.AnnData(network.reconstruct(all_corrected_data.X, use_data=True), ) corrected.obs = pd.concat([all_shared_ann.obs, all_not_shared_ann.obs]) corrected.var_names = adata.var_names.tolist() corrected.obs_names = adata.obs_names.tolist() return corrected def label_encoder(adata): """ Encode labels of Annotated `adata` matrix using sklearn.preprocessing.LabelEncoder class. Parameters ---------- adata: `~anndata.AnnData` Annotated data matrix. Returns ------- labels: numpy nd-array Array of encoded labels Example -------- >>> import scgen >>> import scanpy as sc >>> train_data = sc.read("./data/train.h5ad") >>> train_labels, label_encoder = label_encoder(train_data) """ le = preprocessing.LabelEncoder() labels = le.fit_transform(adata.obs["condition"].tolist()) return labels.reshape(-1, 1), le def visualize_trained_network_results(network, train, cell_type, conditions={"ctrl": "control", "stim": "stimulated"}, condition_key="condition", cell_type_key="cell_type", path_to_save="./figures/", plot_umap=True, plot_reg=True): plt.close("all") os.makedirs(path_to_save, exist_ok=True) sc.settings.figdir = os.path.abspath(path_to_save) if isinstance(network, scgen.VAEArithKeras): if sparse.issparse(train.X): latent = network.to_latent(train.X.A) else: latent = network.to_latent(train.X) latent = sc.AnnData(X=latent, obs={condition_key: train.obs[condition_key].tolist(), cell_type_key: train.obs[cell_type_key].tolist()}) if plot_umap: sc.pp.neighbors(latent) sc.tl.umap(latent) sc.pl.umap(latent, color=[condition_key, cell_type_key], save=f"_latent", show=False) cell_type_data = train[train.obs[cell_type_key] == cell_type] pred, delta = network.predict(adata=cell_type_data, conditions=conditions, cell_type_key=cell_type_key, condition_key=condition_key, celltype_to_predict=cell_type) pred_adata = anndata.AnnData(pred, obs={condition_key: ["pred"] * len(pred)}, var={"var_names": cell_type_data.var_names}) all_adata = cell_type_data.concatenate(pred_adata) sc.tl.rank_genes_groups(cell_type_data, groupby=condition_key, n_genes=100) diff_genes = cell_type_data.uns["rank_genes_groups"]["names"][conditions["stim"]] if plot_reg: scgen.plotting.reg_mean_plot(all_adata, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_mean_all_genes.pdf")) scgen.plotting.reg_var_plot(all_adata, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_var_all_genes.pdf")) all_adata_top_100_genes = all_adata.copy()[:, diff_genes.tolist()] scgen.plotting.reg_mean_plot(all_adata_top_100_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_mean_top_100_genes.pdf")) scgen.plotting.reg_var_plot(all_adata_top_100_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_var_top_100_genes.pdf")) all_adata_top_50_genes = all_adata.copy()[:, diff_genes.tolist()[:50]] scgen.plotting.reg_mean_plot(all_adata_top_50_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_mean_top_50_genes.pdf")) scgen.plotting.reg_var_plot(all_adata_top_50_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_var_top_50_genes.pdf")) if plot_umap: sc.pp.neighbors(all_adata) sc.tl.umap(all_adata) sc.pl.umap(all_adata, color=condition_key, save="pred_all_genes", show=False) sc.pp.neighbors(all_adata_top_100_genes) sc.tl.umap(all_adata_top_100_genes) sc.pl.umap(all_adata_top_100_genes, color=condition_key, save="pred_top_100_genes", show=False) sc.pp.neighbors(all_adata_top_50_genes) sc.tl.umap(all_adata_top_50_genes) sc.pl.umap(all_adata_top_50_genes, color=condition_key, save="pred_top_50_genes", show=False) sc.pl.violin(all_adata, keys=diff_genes.tolist()[0], groupby=condition_key, save=f"_{diff_genes.tolist()[0]}", show=False) plt.close("all") elif isinstance(network, scgen.VAEArith): if sparse.issparse(train.X): latent = network.to_latent(train.X.A) else: latent = network.to_latent(train.X) latent = sc.AnnData(X=latent, obs={condition_key: train.obs[condition_key].tolist(), cell_type_key: train.obs[cell_type_key].tolist()}) if plot_umap: sc.pp.neighbors(latent) sc.tl.umap(latent) sc.pl.umap(latent, color=[condition_key, cell_type_key], save=f"_latent", show=False) cell_type_data = train[train.obs[cell_type_key] == cell_type] pred, delta = network.predict(adata=cell_type_data, conditions=conditions, cell_type_key=cell_type_key, condition_key=condition_key, celltype_to_predict=cell_type) pred_adata = anndata.AnnData(pred, obs={condition_key: ["pred"] * len(pred)}, var={"var_names": cell_type_data.var_names}) all_adata = cell_type_data.concatenate(pred_adata) sc.tl.rank_genes_groups(cell_type_data, groupby=condition_key, n_genes=100) diff_genes = cell_type_data.uns["rank_genes_groups"]["names"][conditions["stim"]] if plot_reg: scgen.plotting.reg_mean_plot(all_adata, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_mean_all_genes.pdf")) scgen.plotting.reg_var_plot(all_adata, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_var_all_genes.pdf")) all_adata_top_100_genes = all_adata.copy()[:, diff_genes.tolist()] scgen.plotting.reg_mean_plot(all_adata_top_100_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_mean_top_100_genes.pdf")) scgen.plotting.reg_var_plot(all_adata_top_100_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_var_top_100_genes.pdf")) all_adata_top_50_genes = all_adata.copy()[:, diff_genes.tolist()[:50]] scgen.plotting.reg_mean_plot(all_adata_top_50_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_mean_top_50_genes.pdf")) scgen.plotting.reg_var_plot(all_adata_top_50_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_var_top_50_genes.pdf")) if plot_umap: sc.pp.neighbors(all_adata) sc.tl.umap(all_adata) sc.pl.umap(all_adata, color=condition_key, save="pred_all_genes", show=False) sc.pp.neighbors(all_adata_top_100_genes) sc.tl.umap(all_adata_top_100_genes) sc.pl.umap(all_adata_top_100_genes, color=condition_key, save="pred_top_100_genes", show=False) sc.pp.neighbors(all_adata_top_50_genes) sc.tl.umap(all_adata_top_50_genes) sc.pl.umap(all_adata_top_50_genes, color=condition_key, save="pred_top_50_genes", show=False) sc.pl.violin(all_adata, keys=diff_genes.tolist()[0], groupby=condition_key, save=f"_{diff_genes.tolist()[0]}", show=False) plt.close("all") elif isinstance(network, scgen.CVAE): true_labels, _ = scgen.label_encoder(train) if sparse.issparse(train.X): latent = network.to_latent(train.X.A, labels=true_labels) else: latent = network.to_latent(train.X, labels=true_labels) latent = sc.AnnData(X=latent, obs={condition_key: train.obs[condition_key].tolist(), cell_type_key: train.obs[cell_type_key].tolist()}) if plot_umap: sc.pp.neighbors(latent) sc.tl.umap(latent) sc.pl.umap(latent, color=[condition_key, cell_type_key], save=f"_latent", show=False) cell_type_data = train[train.obs[cell_type_key] == cell_type] fake_labels = np.ones(shape=(cell_type_data.shape[0], 1)) pred = network.predict(data=cell_type_data, labels=fake_labels) pred_adata = anndata.AnnData(pred, obs={condition_key: ["pred"] * len(pred)}, var={"var_names": cell_type_data.var_names}) all_adata = cell_type_data.concatenate(pred_adata) sc.tl.rank_genes_groups(cell_type_data, groupby=condition_key, n_genes=100) diff_genes = cell_type_data.uns["rank_genes_groups"]["names"][conditions["stim"]] if plot_reg: scgen.plotting.reg_mean_plot(all_adata, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_mean_all_genes.pdf")) scgen.plotting.reg_var_plot(all_adata, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_var_all_genes.pdf")) all_adata_top_100_genes = all_adata.copy()[:, diff_genes.tolist()] scgen.plotting.reg_mean_plot(all_adata_top_100_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_mean_top_100_genes.pdf")) scgen.plotting.reg_var_plot(all_adata_top_100_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_var_top_100_genes.pdf")) all_adata_top_50_genes = all_adata.copy()[:, diff_genes.tolist()[:50]] scgen.plotting.reg_mean_plot(all_adata_top_50_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_mean_top_50_genes.pdf")) scgen.plotting.reg_var_plot(all_adata_top_50_genes, condition_key=condition_key, axis_keys={"x": "pred", "y": conditions["stim"]}, gene_list=diff_genes[:5], path_to_save=os.path.join(path_to_save, f"reg_var_top_50_genes.pdf")) if plot_umap: sc.pp.neighbors(all_adata) sc.tl.umap(all_adata) sc.pl.umap(all_adata, color=condition_key, save="pred_all_genes", show=False) sc.pp.neighbors(all_adata_top_100_genes) sc.tl.umap(all_adata_top_100_genes) sc.pl.umap(all_adata_top_100_genes, color=condition_key, save="pred_top_100_genes", show=False) sc.pp.neighbors(all_adata_top_50_genes) sc.tl.umap(all_adata_top_50_genes) sc.pl.umap(all_adata_top_50_genes, color=condition_key, save="pred_top_50_genes", show=False) sc.pl.violin(all_adata, keys=diff_genes.tolist()[0], groupby=condition_key, save=f"_{diff_genes.tolist()[0]}", show=False) plt.close("all") PKN ~~scgen-1.1.3.dist-info/LICENSE GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. PK!HMuSascgen-1.1.3.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UD"PK!H7ʒscgen-1.1.3.dist-info/METADATAWr6}W`'/YČd֞ڱĒUՖjkH08~T>$ߴMi]%>}4p!(/:e ;ɥ儹|&d=q̏SW.'S~.++ {̘Z\jZi}g3%oM-V`uh|e<7WR9-Q|z^5sY xH+42cf,Kί?&寝ҥVvK3󘇇Si(].v9 ~glL\[W|&{-RUgdc vv=H* O /W˫w_+eI^vvɕH1 ?: ߹x0W.CG/2+Z8d}m 6yWnεRTqcg#̽8F/zΈroc6p/.WyZ͚ȌXlG^𶙽bqm'ϑػ[St9"Su&HS$>1S-y5Bj k2 ZC%'rkBQ9JtS0'\ oJK-A6oP QF@TxE|d1܁6+I̒( .Qj  )eQp}<6juHǔU:gSrlj &@PܡOԶ3 (b#:tCx\&k WЮs6q,Z@x4Rg-h[71#׍ţu"r[{S pqF+恏YjpHXl!_\^Yo"%mчVR+Y${@Wh0a\' kN9Lն|N)=e;nWC8'fl/ rA"C /Hś> }!l؂b 4oٿ:lYHݣXkR4%OL`mqOEݫ.6Ekar±:fI kwD9յԌ.JG1 -˲YP2Hnq5a_57o8fqtުɔ:SjmP‡X[gӞ=:Y}LtCnT6Qڼn. \r@0.2'xi}Ww|px|m[["x&Gم^yPK!H4sscgen-1.1.3.dist-info/RECORDuɒ@{? TZȢ7A@~vY/2 y%=oLDKHU(iZ{Wax8`v7w R/({{QuLIm&ZPALj# ļ1+ׇ $ctjnzgG v!&jߩ2ve4g[3()e5e%y:xFC Q0oF[$HWkX-]1 l#?߬+@'02S