_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q22200 | normalize_per_cell | train | def normalize_per_cell(
data,
counts_per_cell_after=None,
counts_per_cell=None,
key_n_counts=None,
copy=False,
layers=[],
use_rep=None,
min_counts=1,
) -> Optional[AnnData]:
"""Normalize total counts per cell.
.. warning::
.. deprecated:: 1.3.7
Use :func:`~sc... | python | {
"resource": ""
} |
q22201 | scale | train | def scale(data, zero_center=True, max_value=None, copy=False) -> Optional[AnnData]:
"""Scale data to unit variance and zero mean.
.. note::
Variables (genes) that do not display any variation (are constant across
all observations) are retained and set to 0 during this operation. In
the ... | python | {
"resource": ""
} |
q22202 | subsample | train | def subsample(data, fraction=None, n_obs=None, random_state=0, copy=False) -> Optional[AnnData]:
"""Subsample to a fraction of the number of observations.
Parameters
----------
data : :class:`~anndata.AnnData`, `np.ndarray`, `sp.sparse`
The (annotated) data matrix of shape `n_obs` × `n_vars`. R... | python | {
"resource": ""
} |
q22203 | downsample_counts | train | def downsample_counts(
adata: AnnData,
counts_per_cell: Optional[Union[int, Collection[int]]] = None,
total_counts: Optional[int] = None,
random_state: Optional[int] = 0,
replace: bool = False,
copy: bool = False,
) -> Optional[AnnData]:
"""Downsample counts from count matrix.
If `count... | python | {
"resource": ""
} |
q22204 | _downsample_array | train | def _downsample_array(col: np.array, target: int, random_state: int=0,
replace: bool = True, inplace: bool=False):
"""
Evenly reduce counts in cell to target amount.
This is an internal function and has some restrictions:
* `dtype` of col must be an integer (i.e. satisfy issubcla... | python | {
"resource": ""
} |
q22205 | _sec_to_str | train | def _sec_to_str(t):
"""Format time in seconds.
Parameters
----------
t : int
Time in seconds.
"""
from functools import reduce
return "%d:%02d:%02d.%02d" % \
reduce(lambda ll, b: divmod(ll[0], b) + ll[1:],
[(t*100,), 100, 60, 60]) | python | {
"resource": ""
} |
q22206 | paga_degrees | train | def paga_degrees(adata) -> List[int]:
"""Compute the degree of each node in the abstracted graph.
Parameters
----------
adata : AnnData
Annotated data matrix.
Returns
-------
List of degrees for each node.
"""
import networkx as nx
g = nx.Graph(adata.uns['paga']['connec... | python | {
"resource": ""
} |
q22207 | paga_expression_entropies | train | def paga_expression_entropies(adata) -> List[float]:
"""Compute the median expression entropy for each node-group.
Parameters
----------
adata : AnnData
Annotated data matrix.
Returns
-------
Entropies of median expressions for each node.
"""
from scipy.stats import entropy... | python | {
"resource": ""
} |
q22208 | _calc_density | train | def _calc_density(
x: np.ndarray,
y: np.ndarray,
):
"""
Function to calculate the density of cells in an embedding.
"""
# Calculate the point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)
min_z = np.min(z)
max_z = np.max(z)
# Scale between 0 and 1
scaled_z... | python | {
"resource": ""
} |
q22209 | read_10x_h5 | train | def read_10x_h5(filename, genome=None, gex_only=True) -> AnnData:
"""Read 10x-Genomics-formatted hdf5 file.
Parameters
----------
filename : `str` | :class:`~pathlib.Path`
Filename.
genome : `str`, optional (default: ``None``)
Filter expression to this genes within this genome. For ... | python | {
"resource": ""
} |
q22210 | _read_legacy_10x_h5 | train | def _read_legacy_10x_h5(filename, genome=None):
"""
Read hdf5 file from Cell Ranger v2 or earlier versions.
"""
with tables.open_file(str(filename), 'r') as f:
try:
children = [x._v_name for x in f.list_nodes(f.root)]
if not genome:
if len(children) > 1:
... | python | {
"resource": ""
} |
q22211 | _read_v3_10x_h5 | train | def _read_v3_10x_h5(filename):
"""
Read hdf5 file from Cell Ranger v3 or later versions.
"""
with tables.open_file(str(filename), 'r') as f:
try:
dsets = {}
for node in f.walk_nodes('/matrix', 'Array'):
dsets[node.name] = node.read()
from scipy... | python | {
"resource": ""
} |
q22212 | read_10x_mtx | train | def read_10x_mtx(path, var_names='gene_symbols', make_unique=True, cache=False, gex_only=True) -> AnnData:
"""Read 10x-Genomics-formatted mtx directory.
Parameters
----------
path : `str`
Path to directory for `.mtx` and `.tsv` files,
e.g. './filtered_gene_bc_matrices/hg19/'.
var_na... | python | {
"resource": ""
} |
q22213 | _read_legacy_10x_mtx | train | def _read_legacy_10x_mtx(path, var_names='gene_symbols', make_unique=True, cache=False):
"""
Read mex from output from Cell Ranger v2 or earlier versions
"""
path = Path(path)
adata = read(path / 'matrix.mtx', cache=cache).T # transpose the data
genes = pd.read_csv(path / 'genes.tsv', header=No... | python | {
"resource": ""
} |
q22214 | read_params | train | def read_params(filename, asheader=False, verbosity=0) -> Dict[str, Union[int, float, bool, str, None]]:
"""Read parameter dictionary from text file.
Assumes that parameters are specified in the format:
par1 = value1
par2 = value2
Comments that start with '#' are allowed.
Parameters
... | python | {
"resource": ""
} |
q22215 | write_params | train | def write_params(path, *args, **dicts):
"""Write parameters to file, so that it's readable by read_params.
Uses INI file format.
"""
path = Path(path)
if not path.parent.is_dir():
path.parent.mkdir(parents=True)
if len(args) == 1:
d = args[0]
with path.open('w') as f:
... | python | {
"resource": ""
} |
q22216 | get_params_from_list | train | def get_params_from_list(params_list):
"""Transform params list to dictionary.
"""
params = {}
for i in range(0, len(params_list)):
if '=' not in params_list[i]:
try:
if not isinstance(params[key], list): params[key] = [params[key]]
params[key] += [par... | python | {
"resource": ""
} |
q22217 | _slugify | train | def _slugify(path: Union[str, PurePath]) -> str:
"""Make a path into a filename."""
if not isinstance(path, PurePath):
path = PurePath(path)
parts = list(path.parts)
if parts[0] == '/':
parts.pop(0)
elif len(parts[0]) == 3 and parts[0][1:] == ':\\':
parts[0] = parts[0][0] # ... | python | {
"resource": ""
} |
q22218 | _read_softgz | train | def _read_softgz(filename) -> AnnData:
"""Read a SOFT format data file.
The SOFT format is documented here
http://www.ncbi.nlm.nih.gov/geo/info/soft2.html.
Notes
-----
The function is based on a script by Kerby Shedden.
http://dept.stat.lsa.umich.edu/~kshedden/Python-Workshop/gene_expressi... | python | {
"resource": ""
} |
q22219 | convert_bool | train | def convert_bool(string):
"""Check whether string is boolean.
"""
if string == 'True':
return True, True
elif string == 'False':
return True, False
else:
return False, False | python | {
"resource": ""
} |
q22220 | convert_string | train | def convert_string(string):
"""Convert string to int, float or bool.
"""
if is_int(string):
return int(string)
elif is_float(string):
return float(string)
elif convert_bool(string)[0]:
return convert_bool(string)[1]
elif string == 'None':
return None
else:
... | python | {
"resource": ""
} |
q22221 | get_used_files | train | def get_used_files():
"""Get files used by processes with name scanpy."""
import psutil
loop_over_scanpy_processes = (proc for proc in psutil.process_iter()
if proc.name() == 'scanpy')
filenames = []
for proc in loop_over_scanpy_processes:
try:
f... | python | {
"resource": ""
} |
q22222 | check_datafile_present_and_download | train | def check_datafile_present_and_download(path, backup_url=None):
"""Check whether the file is present, otherwise download.
"""
path = Path(path)
if path.is_file(): return True
if backup_url is None: return False
logg.info('try downloading from url\n' + backup_url + '\n' +
'... this ... | python | {
"resource": ""
} |
q22223 | is_valid_filename | train | def is_valid_filename(filename, return_ext=False):
"""Check whether the argument is a filename."""
ext = Path(filename).suffixes
if len(ext) > 2:
logg.warn('Your filename has more than two extensions: {}.\n'
'Only considering the two last: {}.'.format(ext, ext[-2:]))
ext =... | python | {
"resource": ""
} |
q22224 | correlation_matrix | train | def correlation_matrix(adata,groupby=None ,group=None, corr_matrix=None, annotation_key=None):
"""Plot correlation matrix.
Plot a correlation matrix for genes strored in sample annotation using rank_genes_groups.py
Parameters
----------
adata : :class:`~anndata.AnnD... | python | {
"resource": ""
} |
q22225 | tqdm_hook | train | def tqdm_hook(t):
"""
Wraps tqdm instance.
Don't forget to close() or __exit__()
the tqdm instance once you're done with it (easiest using `with` syntax).
Example
-------
>>> with tqdm(...) as t:
... reporthook = my_hook(t)
... urllib.urlretrieve(..., reporthook=reporthook)
... | python | {
"resource": ""
} |
q22226 | matrix | train | def matrix(matrix, xlabel=None, ylabel=None, xticks=None, yticks=None,
title=None, colorbar_shrink=0.5, color_map=None, show=None,
save=None, ax=None):
"""Plot a matrix."""
if ax is None: ax = pl.gca()
img = ax.imshow(matrix, cmap=color_map)
if xlabel is not None: ax.set_xlabel(xla... | python | {
"resource": ""
} |
q22227 | timeseries | train | def timeseries(X, **kwargs):
"""Plot X. See timeseries_subplot."""
pl.figure(figsize=(2*rcParams['figure.figsize'][0], rcParams['figure.figsize'][1]),
subplotpars=sppars(left=0.12, right=0.98, bottom=0.13))
timeseries_subplot(X, **kwargs) | python | {
"resource": ""
} |
q22228 | timeseries_subplot | train | def timeseries_subplot(X,
time=None,
color=None,
var_names=(),
highlightsX=(),
xlabel='',
ylabel='gene expression',
yticks=None,
xlim=No... | python | {
"resource": ""
} |
q22229 | timeseries_as_heatmap | train | def timeseries_as_heatmap(X, var_names=None, highlightsX=None, color_map=None):
"""Plot timeseries as heatmap.
Parameters
----------
X : np.ndarray
Data array.
var_names : array_like
Array of strings naming variables stored in columns of X.
"""
if highlightsX is None:
... | python | {
"resource": ""
} |
q22230 | savefig | train | def savefig(writekey, dpi=None, ext=None):
"""Save current figure to file.
The `filename` is generated as follows:
filename = settings.figdir + writekey + settings.plot_suffix + '.' + settings.file_format_figs
"""
if dpi is None:
# we need this as in notebooks, the internal figures are... | python | {
"resource": ""
} |
q22231 | scatter_group | train | def scatter_group(ax, key, imask, adata, Y, projection='2d', size=3, alpha=None):
"""Scatter of group using representation of data Y.
"""
mask = adata.obs[key].cat.categories[imask] == adata.obs[key].values
color = adata.uns[key + '_colors'][imask]
if not isinstance(color[0], str):
from matp... | python | {
"resource": ""
} |
q22232 | setup_axes | train | def setup_axes(
ax=None,
panels='blue',
colorbars=[False],
right_margin=None,
left_margin=None,
projection='2d',
show_ticks=False):
"""Grid of axes for plotting, legends and colorbars.
"""
if '3d' in projection: from mpl_toolkits.mplot3d import Axes3D
... | python | {
"resource": ""
} |
q22233 | arrows_transitions | train | def arrows_transitions(ax, X, indices, weight=None):
"""
Plot arrows of transitions in data matrix.
Parameters
----------
ax : matplotlib.axis
Axis object from matplotlib.
X : np.array
Data array, any representation wished (X, psi, phi, etc).
indices : array_like
Ind... | python | {
"resource": ""
} |
q22234 | scale_to_zero_one | train | def scale_to_zero_one(x):
"""Take some 1d data and scale it so that min matches 0 and max 1.
"""
xscaled = x - np.min(x)
xscaled /= np.max(xscaled)
return xscaled | python | {
"resource": ""
} |
q22235 | hierarchy_pos | train | def hierarchy_pos(G, root, levels=None, width=1., height=1.):
"""Tree layout for networkx graph.
See https://stackoverflow.com/questions/29586520/can-one-get-hierarchical-graphs-from-networkx-with-python-3
answer by burubum.
If there is a cycle that is reachable from root, then this will see
... | python | {
"resource": ""
} |
q22236 | zoom | train | def zoom(ax, xy='x', factor=1):
"""Zoom into axis.
Parameters
----------
"""
limits = ax.get_xlim() if xy == 'x' else ax.get_ylim()
new_limits = (0.5*(limits[0] + limits[1])
+ 1./factor * np.array((-0.5, 0.5)) * (limits[1] - limits[0]))
if xy == 'x':
ax.set_xlim(ne... | python | {
"resource": ""
} |
q22237 | get_ax_size | train | def get_ax_size(ax, fig):
"""Get axis size
Parameters
----------
ax : matplotlib.axis
Axis object from matplotlib.
fig : matplotlib.Figure
Figure.
"""
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
wi... | python | {
"resource": ""
} |
q22238 | axis_to_data | train | def axis_to_data(ax, width):
"""For a width in axis coordinates, return the corresponding in data
coordinates.
Parameters
----------
ax : matplotlib.axis
Axis object from matplotlib.
width : float
Width in xaxis coordinates.
"""
xlim = ax.get_xlim()
widthx = width*(x... | python | {
"resource": ""
} |
q22239 | axis_to_data_points | train | def axis_to_data_points(ax, points_axis):
"""Map points in axis coordinates to data coordinates.
Uses matplotlib.transform.
Parameters
----------
ax : matplotlib.axis
Axis object from matplotlib.
points_axis : np.array
Points in axis coordinates.
"""
axis_to_data = ax.t... | python | {
"resource": ""
} |
q22240 | console_main | train | def console_main():
"""This serves as CLI entry point and will not show a Python traceback if a called command fails"""
cmd = main(check=False)
if cmd is not None:
sys.exit(cmd.returncode) | python | {
"resource": ""
} |
q22241 | filter_rank_genes_groups | train | def filter_rank_genes_groups(adata, key=None, groupby=None, use_raw=True, log=True,
key_added='rank_genes_groups_filtered',
min_in_group_fraction=0.25, min_fold_change=2,
max_out_group_fraction=0.5):
"""Filters out genes based on... | python | {
"resource": ""
} |
q22242 | blobs | train | def blobs(n_variables=11, n_centers=5, cluster_std=1.0, n_observations=640) -> AnnData:
"""Gaussian Blobs.
Parameters
----------
n_variables : `int`, optional (default: 11)
Dimension of feature space.
n_centers : `int`, optional (default: 5)
Number of cluster centers.
cluster_st... | python | {
"resource": ""
} |
q22243 | toggleswitch | train | def toggleswitch() -> AnnData:
"""Simulated toggleswitch.
Data obtained simulating a simple toggleswitch `Gardner *et al.*, Nature
(2000) <https://doi.org/10.1038/35002131>`__.
Simulate via :func:`~scanpy.api.sim`.
Returns
-------
Annotated data matrix.
"""
filename = os.path.dirn... | python | {
"resource": ""
} |
q22244 | pbmc68k_reduced | train | def pbmc68k_reduced() -> AnnData:
"""Subsampled and processed 68k PBMCs.
10x PBMC 68k dataset from
https://support.10xgenomics.com/single-cell-gene-expression/datasets
The original PBMC 68k dataset was preprocessed using scanpy and was saved
keeping only 724 cells and 221 highly variable genes.
... | python | {
"resource": ""
} |
q22245 | OnFlySymMatrix.restrict | train | def restrict(self, index_array):
"""Generate a view restricted to a subset of indices.
"""
new_shape = index_array.shape[0], index_array.shape[0]
return OnFlySymMatrix(self.get_row, new_shape, DC_start=self.DC_start,
DC_end=self.DC_end,
... | python | {
"resource": ""
} |
q22246 | Neighbors.compute_neighbors | train | def compute_neighbors(
self,
n_neighbors: int = 30,
knn: bool = True,
n_pcs: Optional[int] = None,
use_rep: Optional[str] = None,
method: str = 'umap',
random_state: Optional[Union[RandomState, int]] = 0,
write_knn_indices: bool = False,
metric: st... | python | {
"resource": ""
} |
q22247 | Neighbors.compute_transitions | train | def compute_transitions(self, density_normalize=True):
"""Compute transition matrix.
Parameters
----------
density_normalize : `bool`
The density rescaling of Coifman and Lafon (2006): Then only the
geometry of the data matters, not the sampled density.
... | python | {
"resource": ""
} |
q22248 | Neighbors.compute_eigen | train | def compute_eigen(self, n_comps=15, sym=None, sort='decrease'):
"""Compute eigen decomposition of transition matrix.
Parameters
----------
n_comps : `int`
Number of eigenvalues/vectors to be computed, set `n_comps = 0` if
you need all eigenvectors.
sym : ... | python | {
"resource": ""
} |
q22249 | Neighbors._set_pseudotime | train | def _set_pseudotime(self):
"""Return pseudotime with respect to root point.
"""
self.pseudotime = self.distances_dpt[self.iroot].copy()
self.pseudotime /= np.max(self.pseudotime[self.pseudotime < np.inf]) | python | {
"resource": ""
} |
q22250 | Neighbors._set_iroot_via_xroot | train | def _set_iroot_via_xroot(self, xroot):
"""Determine the index of the root cell.
Given an expression vector, find the observation index that is closest
to this vector.
Parameters
----------
xroot : np.ndarray
Vector that marks the root cell, the vector storin... | python | {
"resource": ""
} |
q22251 | mitochondrial_genes | train | def mitochondrial_genes(host, org) -> pd.Index:
"""Mitochondrial gene symbols for specific organism through BioMart.
Parameters
----------
host : {{'www.ensembl.org', ...}}
A valid BioMart host URL.
org : {{'hsapiens', 'mmusculus', 'drerio'}}
Organism to query. Currently available a... | python | {
"resource": ""
} |
q22252 | highest_expr_genes | train | def highest_expr_genes(
adata, n_top=30, show=None, save=None,
ax=None, gene_symbols=None, **kwds
):
"""\
Fraction of counts assigned to each gene over all cells.
Computes, for each gene, the fraction of counts assigned to that gene within
a cell. The `n_top` genes with the highest ... | python | {
"resource": ""
} |
q22253 | filter_genes_cv_deprecated | train | def filter_genes_cv_deprecated(X, Ecutoff, cvFilter):
"""Filter genes by coefficient of variance and mean.
See `filter_genes_dispersion`.
Reference: Weinreb et al. (2017).
"""
if issparse(X):
raise ValueError('Not defined for sparse input. See `filter_genes_dispersion`.')
mean_filter =... | python | {
"resource": ""
} |
q22254 | filter_genes_fano_deprecated | train | def filter_genes_fano_deprecated(X, Ecutoff, Vcutoff):
"""Filter genes by fano factor and mean.
See `filter_genes_dispersion`.
Reference: Weinreb et al. (2017).
"""
if issparse(X):
raise ValueError('Not defined for sparse input. See `filter_genes_dispersion`.')
mean_filter = np.mean(X,... | python | {
"resource": ""
} |
q22255 | materialize_as_ndarray | train | def materialize_as_ndarray(a):
"""Convert distributed arrays to ndarrays."""
if type(a) in (list, tuple):
if da is not None and any(isinstance(arr, da.Array) for arr in a):
return da.compute(*a, sync=True)
return tuple(np.asarray(arr) for arr in a)
return np.asarray(a) | python | {
"resource": ""
} |
q22256 | mnn_concatenate | train | def mnn_concatenate(*adatas, geneset=None, k=20, sigma=1, n_jobs=None, **kwds):
"""Merge AnnData objects and correct batch effects using the MNN method.
Batch effect correction by matching mutual nearest neighbors [Haghverdi18]_
has been implemented as a function 'mnnCorrect' in the R package
`scran <h... | python | {
"resource": ""
} |
q22257 | _design_matrix | train | def _design_matrix(
model: pd.DataFrame,
batch_key: str,
batch_levels: Collection[str],
) -> pd.DataFrame:
"""
Computes a simple design matrix.
Parameters
--------
model
Contains the batch annotation
batch_key
Name of the batch column
batch_levels
... | python | {
"resource": ""
} |
q22258 | _standardize_data | train | def _standardize_data(
model: pd.DataFrame,
data: pd.DataFrame,
batch_key: str,
) -> Tuple[pd.DataFrame, pd.DataFrame, np.ndarray, np.ndarray]:
"""
Standardizes the data per gene.
The aim here is to make mean and variance be comparable across batches.
Parameters
--------
model
... | python | {
"resource": ""
} |
q22259 | _it_sol | train | def _it_sol(s_data, g_hat, d_hat, g_bar, t2, a, b, conv=0.0001) -> Tuple[float, float]:
"""
Iteratively compute the conditional posterior means for gamma and delta.
gamma is an estimator for the additive batch effect, deltat is an estimator
for the multiplicative batch effect. We use an EB framework to... | python | {
"resource": ""
} |
q22260 | top_proportions | train | def top_proportions(mtx, n):
"""
Calculates cumulative proportions of top expressed genes
Parameters
----------
mtx : `Union[np.array, sparse.spmatrix]`
Matrix, where each row is a sample, each column a feature.
n : `int`
Rank to calculate proportions up to. Value is treated as ... | python | {
"resource": ""
} |
q22261 | top_segment_proportions | train | def top_segment_proportions(mtx, ns):
"""
Calculates total percentage of counts in top ns genes.
Parameters
----------
mtx : `Union[np.array, sparse.spmatrix]`
Matrix, where each row is a sample, each column a feature.
ns : `Container[Int]`
Positions to calculate cumulative prop... | python | {
"resource": ""
} |
q22262 | add_args | train | def add_args(p):
"""
Update parser with tool specific arguments.
This overwrites was is done in utils.uns_args.
"""
# dictionary for adding arguments
dadd_args = {
'--opfile': {
'default': '',
'metavar': 'f',
'type': str,
'help': 'Specify ... | python | {
"resource": ""
} |
q22263 | _check_branching | train | def _check_branching(X,Xsamples,restart,threshold=0.25):
"""\
Check whether time series branches.
Parameters
----------
X (np.array): current time series data.
Xsamples (np.array): list of previous branching samples.
restart (int): counts number of restart trials.
threshold (float, opti... | python | {
"resource": ""
} |
q22264 | check_nocycles | train | def check_nocycles(Adj, verbosity=2):
"""\
Checks that there are no cycles in graph described by adjacancy matrix.
Parameters
----------
Adj (np.array): adjancancy matrix of dimension (dim, dim)
Returns
-------
True if there is no cycle, False otherwise.
"""
dim = Adj.shape[0]
... | python | {
"resource": ""
} |
q22265 | sample_coupling_matrix | train | def sample_coupling_matrix(dim=3,connectivity=0.5):
"""\
Sample coupling matrix.
Checks that returned graphs contain no self-cycles.
Parameters
----------
dim : int
dimension of coupling matrix.
connectivity : float
fraction of connectivity, fully connected means 1.,
... | python | {
"resource": ""
} |
q22266 | GRNsim.sim_model | train | def sim_model(self,tmax,X0,noiseDyn=0,restart=0):
""" Simulate the model.
"""
self.noiseDyn = noiseDyn
#
X = np.zeros((tmax,self.dim))
X[0] = X0 + noiseDyn*np.random.randn(self.dim)
# run simulation
for t in range(1,tmax):
if self.modelType == ... | python | {
"resource": ""
} |
q22267 | GRNsim.Xdiff_hill | train | def Xdiff_hill(self,Xt):
""" Build Xdiff from coefficients of boolean network,
that is, using self.boolCoeff. The employed functions
are Hill type activation and deactivation functions.
See Wittmann et al., BMC Syst. Biol. 3, 98 (2009),
doi:10.1186/1752-0509-3-98... | python | {
"resource": ""
} |
q22268 | GRNsim.hill_a | train | def hill_a(self,x,threshold=0.1,power=2):
""" Activating hill function. """
x_pow = np.power(x,power)
threshold_pow = np.power(threshold,power)
return x_pow / (x_pow + threshold_pow) | python | {
"resource": ""
} |
q22269 | GRNsim.hill_i | train | def hill_i(self,x,threshold=0.1,power=2):
""" Inhibiting hill function.
Is equivalent to 1-hill_a(self,x,power,threshold).
"""
x_pow = np.power(x,power)
threshold_pow = np.power(threshold,power)
return threshold_pow / (x_pow + threshold_pow) | python | {
"resource": ""
} |
q22270 | GRNsim.nhill_a | train | def nhill_a(self,x,threshold=0.1,power=2,ichild=2):
""" Normalized activating hill function. """
x_pow = np.power(x,power)
threshold_pow = np.power(threshold,power)
return x_pow / (x_pow + threshold_pow) * (1 + threshold_pow) | python | {
"resource": ""
} |
q22271 | GRNsim.nhill_i | train | def nhill_i(self,x,threshold=0.1,power=2):
""" Normalized inhibiting hill function.
Is equivalent to 1-nhill_a(self,x,power,threshold).
"""
x_pow = np.power(x,power)
threshold_pow = np.power(threshold,power)
return threshold_pow / (x_pow + threshold_pow) * (1 - x_pow... | python | {
"resource": ""
} |
q22272 | GRNsim.read_model | train | def read_model(self):
""" Read the model and the couplings from the model file.
"""
if self.verbosity > 0:
settings.m(0,'reading model',self.model)
# read model
boolRules = []
for line in open(self.model):
if line.startswith('#') and 'modelType =' ... | python | {
"resource": ""
} |
q22273 | GRNsim.set_coupl_old | train | def set_coupl_old(self):
""" Using the adjacency matrix, sample a coupling matrix.
"""
if self.model == 'krumsiek11' or self.model == 'var':
# we already built the coupling matrix in set_coupl20()
return
self.Coupl = np.zeros((self.dim,self.dim))
for i in ... | python | {
"resource": ""
} |
q22274 | GRNsim.coupl_model1 | train | def coupl_model1(self):
""" In model 1, we want enforce the following signs
on the couplings. Model 2 has the same couplings
but arbitrary signs.
"""
self.Coupl[0,0] = np.abs(self.Coupl[0,0])
self.Coupl[0,1] = -np.abs(self.Coupl[0,1])
self.Coupl[1,1] = np.... | python | {
"resource": ""
} |
q22275 | GRNsim.coupl_model5 | train | def coupl_model5(self):
""" Toggle switch.
"""
self.Coupl = -0.2*self.Adj
self.Coupl[2,0] *= -1
self.Coupl[3,0] *= -1
self.Coupl[4,1] *= -1
self.Coupl[5,1] *= -1 | python | {
"resource": ""
} |
q22276 | GRNsim.coupl_model8 | train | def coupl_model8(self):
""" Variant of toggle switch.
"""
self.Coupl = 0.5*self.Adj_signed
# reduce the value of the coupling of the repressing genes
# otherwise completely unstable solutions are obtained
for x in np.nditer(self.Coupl,op_flags=['readwrite']):
... | python | {
"resource": ""
} |
q22277 | GRNsim.sim_model_backwards | train | def sim_model_backwards(self,tmax,X0):
""" Simulate the model backwards in time.
"""
X = np.zeros((tmax,self.dim))
X[tmax-1] = X0
for t in range(tmax-2,-1,-1):
sol = sp.optimize.root(self.sim_model_back_help,
X[t+1],
... | python | {
"resource": ""
} |
q22278 | GRNsim.parents_from_boolRule | train | def parents_from_boolRule(self,rule):
""" Determine parents based on boolean updaterule.
Returns list of parents.
"""
rule_pa = rule.replace('(','').replace(')','').replace('or','').replace('and','').replace('not','')
rule_pa = rule_pa.split()
# if there are no paren... | python | {
"resource": ""
} |
q22279 | GRNsim.build_boolCoeff | train | def build_boolCoeff(self):
''' Compute coefficients for tuple space.
'''
# coefficients for hill functions from boolean update rules
self.boolCoeff = collections.OrderedDict([(s,[]) for s in self.varNames.keys()])
# parents
self.pas = collections.OrderedDict([(s,[]) for s... | python | {
"resource": ""
} |
q22280 | GRNsim.process_rule | train | def process_rule(self,rule,pa,tuple):
''' Process a string that denotes a boolean rule.
'''
for i,v in enumerate(tuple):
rule = rule.replace(pa[i],str(v))
return eval(rule) | python | {
"resource": ""
} |
q22281 | StaticCauseEffect.sim_givenAdj | train | def sim_givenAdj(self, Adj: np.array, model='line'):
"""\
Simulate data given only an adjacancy matrix and a model.
The model is a bivariate funtional dependence. The adjacancy matrix
needs to be acyclic.
Parameters
----------
Adj
adjacancy matrix of... | python | {
"resource": ""
} |
q22282 | StaticCauseEffect.sim_combi | train | def sim_combi(self):
""" Simulate data to model combi regulation.
"""
n_samples = 500
sigma_glob = 1.8
X = np.zeros((n_samples,3))
X[:,0] = np.random.uniform(-sigma_glob,sigma_glob,n_samples)
X[:,1] = np.random.uniform(-sigma_glob,sigma_glob,n_samples)
... | python | {
"resource": ""
} |
q22283 | _calc_overlap_count | train | def _calc_overlap_count(
markers1: dict,
markers2: dict,
):
"""Calculate overlap count between the values of two dictionaries
Note: dict values must be sets
"""
overlaps=np.zeros((len(markers1), len(markers2)))
j=0
for marker_group in markers1:
tmp = [len(markers2[i].intersecti... | python | {
"resource": ""
} |
q22284 | _calc_overlap_coef | train | def _calc_overlap_coef(
markers1: dict,
markers2: dict,
):
"""Calculate overlap coefficient between the values of two dictionaries
Note: dict values must be sets
"""
overlap_coef=np.zeros((len(markers1), len(markers2)))
j=0
for marker_group in markers1:
tmp = [len(markers2[i].i... | python | {
"resource": ""
} |
q22285 | _calc_jaccard | train | def _calc_jaccard(
markers1: dict,
markers2: dict,
):
"""Calculate jaccard index between the values of two dictionaries
Note: dict values must be sets
"""
jacc_results=np.zeros((len(markers1), len(markers2)))
j=0
for marker_group in markers1:
tmp = [len(markers2[i].intersection... | python | {
"resource": ""
} |
q22286 | pca_overview | train | def pca_overview(adata, **params):
"""\
Plot PCA results.
The parameters are the ones of the scatter plot. Call pca_ranking separately
if you want to change the default settings.
Parameters
----------
adata : :class:`~anndata.AnnData`
Annotated data matrix.
color : string or li... | python | {
"resource": ""
} |
q22287 | pca_loadings | train | def pca_loadings(adata, components=None, show=None, save=None):
"""Rank genes according to contributions to PCs.
Parameters
----------
adata : :class:`~anndata.AnnData`
Annotated data matrix.
components : str or list of integers, optional
For example, ``'1,2,3'`` means ``[1, 2, 3]``... | python | {
"resource": ""
} |
q22288 | pca_variance_ratio | train | def pca_variance_ratio(adata, n_pcs=30, log=False, show=None, save=None):
"""Plot the variance ratio.
Parameters
----------
n_pcs : `int`, optional (default: `30`)
Number of PCs to show.
log : `bool`, optional (default: `False`)
Plot on logarithmic scale..
show : `bool`, optio... | python | {
"resource": ""
} |
q22289 | dpt_timeseries | train | def dpt_timeseries(adata, color_map=None, show=None, save=None, as_heatmap=True):
"""Heatmap of pseudotime series.
Parameters
----------
as_heatmap : bool (default: False)
Plot the timeseries as heatmap.
"""
if adata.n_vars > 100:
logg.warn('Plotting more than 100 genes might ta... | python | {
"resource": ""
} |
q22290 | dpt_groups_pseudotime | train | def dpt_groups_pseudotime(adata, color_map=None, palette=None, show=None, save=None):
"""Plot groups and pseudotime."""
pl.figure()
pl.subplot(211)
timeseries_subplot(adata.obs['dpt_groups'].cat.codes,
time=adata.obs['dpt_order'].values,
color=np.asarray(ada... | python | {
"resource": ""
} |
q22291 | _rank_genes_groups_plot | train | def _rank_genes_groups_plot(adata, plot_type='heatmap', groups=None,
n_genes=10, groupby=None, key=None,
show=None, save=None, **kwds):
"""\
Plot ranking of genes using the specified plot type
Parameters
----------
adata : :class:`~anndata.Ann... | python | {
"resource": ""
} |
q22292 | sim | train | def sim(adata, tmax_realization=None, as_heatmap=False, shuffle=False,
show=None, save=None):
"""Plot results of simulation.
Parameters
----------
as_heatmap : bool (default: False)
Plot the timeseries as heatmap.
tmax_realization : int or None (default: False)
Number of obs... | python | {
"resource": ""
} |
q22293 | cellbrowser | train | def cellbrowser(
adata, data_dir, data_name,
embedding_keys = None,
annot_keys = ["louvain", "percent_mito", "n_genes", "n_counts"],
cluster_field = "louvain",
nb_marker = 50,
skip_matrix = False,
html_dir = None,
port = None,
do_debug = False
):
"""
Export adata to a UCSC Ce... | python | {
"resource": ""
} |
q22294 | umap | train | def umap(adata, **kwargs) -> Union[Axes, List[Axes], None]:
"""\
Scatter plot in UMAP basis.
Parameters
----------
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
"""
r... | python | {
"resource": ""
} |
q22295 | tsne | train | def tsne(adata, **kwargs) -> Union[Axes, List[Axes], None]:
"""\
Scatter plot in tSNE basis.
Parameters
----------
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
"""
r... | python | {
"resource": ""
} |
q22296 | diffmap | train | def diffmap(adata, **kwargs) -> Union[Axes, List[Axes], None]:
"""\
Scatter plot in Diffusion Map basis.
Parameters
----------
{adata_color_etc}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
"""
return p... | python | {
"resource": ""
} |
q22297 | draw_graph | train | def draw_graph(adata, layout=None, **kwargs) -> Union[Axes, List[Axes], None]:
"""\
Scatter plot in graph-drawing basis.
Parameters
----------
{adata_color_etc}
layout : {{'fa', 'fr', 'drl', ...}}, optional (default: last computed)
One of the `draw_graph` layouts, see
:func:`~sc... | python | {
"resource": ""
} |
q22298 | pca | train | def pca(adata, **kwargs) -> Union[Axes, List[Axes], None]:
"""\
Scatter plot in PCA coordinates.
Parameters
----------
{adata_color_etc}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
"""
return plot_scat... | python | {
"resource": ""
} |
q22299 | _add_legend_or_colorbar | train | def _add_legend_or_colorbar(adata, ax, cax, categorical, value_to_plot, legend_loc,
scatter_array, legend_fontweight, legend_fontsize,
groups, multi_panel):
"""
Adds a color bar or a legend to the given ax. A legend is added when the
data is categorica... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.