id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
24,400
pythongssapi/python-gssapi
gssapi/_utils.py
catch_and_return_token
def catch_and_return_token(func, self, *args, **kwargs): """Optionally defer exceptions and return a token instead When `__DEFER_STEP_ERRORS__` is set on the implementing class or instance, methods wrapped with this wrapper will catch and save their :python:`GSSError` exceptions and instead return the result token attached to the exception. The exception can be later retrived through :python:`_last_err` (and :python:`_last_tb` when Python 2 is in use). """ try: return func(self, *args, **kwargs) except GSSError as e: if e.token is not None and self.__DEFER_STEP_ERRORS__: self._last_err = e # skip the "return func" line above in the traceback if six.PY2: self._last_tb = sys.exc_info()[2].tb_next.tb_next else: self._last_err.__traceback__ = e.__traceback__.tb_next return e.token else: raise
python
def catch_and_return_token(func, self, *args, **kwargs): try: return func(self, *args, **kwargs) except GSSError as e: if e.token is not None and self.__DEFER_STEP_ERRORS__: self._last_err = e # skip the "return func" line above in the traceback if six.PY2: self._last_tb = sys.exc_info()[2].tb_next.tb_next else: self._last_err.__traceback__ = e.__traceback__.tb_next return e.token else: raise
[ "def", "catch_and_return_token", "(", "func", ",", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "GSSError", "as", "e", ":", "if", ...
Optionally defer exceptions and return a token instead When `__DEFER_STEP_ERRORS__` is set on the implementing class or instance, methods wrapped with this wrapper will catch and save their :python:`GSSError` exceptions and instead return the result token attached to the exception. The exception can be later retrived through :python:`_last_err` (and :python:`_last_tb` when Python 2 is in use).
[ "Optionally", "defer", "exceptions", "and", "return", "a", "token", "instead" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L114-L139
24,401
pythongssapi/python-gssapi
gssapi/_utils.py
check_last_err
def check_last_err(func, self, *args, **kwargs): """Check and raise deferred errors before running the function This method checks :python:`_last_err` before running the wrapped function. If present and not None, the exception will be raised with its original traceback. """ if self._last_err is not None: try: if six.PY2: six.reraise(type(self._last_err), self._last_err, self._last_tb) else: # NB(directxman12): not using six.reraise in Python 3 leads # to cleaner tracebacks, and raise x is valid # syntax in Python 3 (unlike raise x, y, z) raise self._last_err finally: if six.PY2: del self._last_tb # in case of cycles, break glass self._last_err = None else: return func(self, *args, **kwargs) @deco.decorator def check_last_err(func, self, *args, **kwargs): if self._last_err is not None: try: raise self._last_err finally: self._last_err = None else: return func(self, *args, **kwargs)
python
def check_last_err(func, self, *args, **kwargs): if self._last_err is not None: try: if six.PY2: six.reraise(type(self._last_err), self._last_err, self._last_tb) else: # NB(directxman12): not using six.reraise in Python 3 leads # to cleaner tracebacks, and raise x is valid # syntax in Python 3 (unlike raise x, y, z) raise self._last_err finally: if six.PY2: del self._last_tb # in case of cycles, break glass self._last_err = None else: return func(self, *args, **kwargs) @deco.decorator def check_last_err(func, self, *args, **kwargs): if self._last_err is not None: try: raise self._last_err finally: self._last_err = None else: return func(self, *args, **kwargs)
[ "def", "check_last_err", "(", "func", ",", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_last_err", "is", "not", "None", ":", "try", ":", "if", "six", ".", "PY2", ":", "six", ".", "reraise", "(", "type", "(", ...
Check and raise deferred errors before running the function This method checks :python:`_last_err` before running the wrapped function. If present and not None, the exception will be raised with its original traceback.
[ "Check", "and", "raise", "deferred", "errors", "before", "running", "the", "function" ]
b6efe72aa35a4c1fe21b397e15fcb41611e365ce
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L143-L177
24,402
theislab/scvelo
scvelo/plotting/velocity_graph.py
velocity_graph
def velocity_graph(adata, basis=None, vkey='velocity', which_graph='velocity', n_neighbors=10, alpha=.8, perc=90, edge_width=.2, edge_color='grey', color=None, use_raw=None, layer=None, color_map=None, colorbar=True, palette=None, size=None, sort_order=True, groups=None, components=None, projection='2d', legend_loc='on data', legend_fontsize=None, legend_fontweight=None, right_margin=None, left_margin=None, xlabel=None, ylabel=None, title=None, fontsize=None, figsize=None, dpi=None, frameon=None, show=True, save=None, ax=None): """\ Plot of the velocity graph. Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` or `None` (default: `None`) Key for annotations of observations/cells or variables/genes. which_graph: `'velocity'` or `'neighbors'` (default: `'velocity'`) Whether to show transitions from velocity graph or connectivities from neighbors graph. {scatter} Returns ------- `matplotlib.Axis` if `show==False` """ basis = default_basis(adata) if basis is None else basis title = which_graph + ' graph' if title is None else title scatter_kwargs = {"basis": basis, "perc": perc, "use_raw": use_raw, "sort_order": sort_order, "alpha": alpha, "components": components, "projection": projection, "legend_loc": legend_loc, "groups": groups, "legend_fontsize": legend_fontsize, "legend_fontweight": legend_fontweight, "palette": palette, "color_map": color_map, "frameon": frameon, "title": title, "xlabel": xlabel, "ylabel": ylabel, "right_margin": right_margin, "left_margin": left_margin, "colorbar": colorbar, "dpi": dpi, "fontsize": fontsize, "show": False, "save": None, "figsize": figsize, } ax = scatter(adata, layer=layer, color=color, size=size, ax=ax, zorder=0, **scatter_kwargs) from networkx import Graph, draw_networkx_edges if which_graph == 'neighbors': T = adata.uns['neighbors']['connectivities'] if perc is not None: threshold = np.percentile(T.data, perc) T.data[T.data < threshold] = 0 T.eliminate_zeros() else: T = transition_matrix(adata, vkey=vkey, weight_indirect_neighbors=0, n_neighbors=n_neighbors, perc=perc) with warnings.catch_warnings(): warnings.simplefilter("ignore") edges = draw_networkx_edges(Graph(T), adata.obsm['X_' + basis], width=edge_width, edge_color=edge_color, ax=ax) edges.set_zorder(-2) edges.set_rasterized(settings._vector_friendly) savefig_or_show('' if basis is None else basis, dpi=dpi, save=save, show=show) if not show: return ax
python
def velocity_graph(adata, basis=None, vkey='velocity', which_graph='velocity', n_neighbors=10, alpha=.8, perc=90, edge_width=.2, edge_color='grey', color=None, use_raw=None, layer=None, color_map=None, colorbar=True, palette=None, size=None, sort_order=True, groups=None, components=None, projection='2d', legend_loc='on data', legend_fontsize=None, legend_fontweight=None, right_margin=None, left_margin=None, xlabel=None, ylabel=None, title=None, fontsize=None, figsize=None, dpi=None, frameon=None, show=True, save=None, ax=None): basis = default_basis(adata) if basis is None else basis title = which_graph + ' graph' if title is None else title scatter_kwargs = {"basis": basis, "perc": perc, "use_raw": use_raw, "sort_order": sort_order, "alpha": alpha, "components": components, "projection": projection, "legend_loc": legend_loc, "groups": groups, "legend_fontsize": legend_fontsize, "legend_fontweight": legend_fontweight, "palette": palette, "color_map": color_map, "frameon": frameon, "title": title, "xlabel": xlabel, "ylabel": ylabel, "right_margin": right_margin, "left_margin": left_margin, "colorbar": colorbar, "dpi": dpi, "fontsize": fontsize, "show": False, "save": None, "figsize": figsize, } ax = scatter(adata, layer=layer, color=color, size=size, ax=ax, zorder=0, **scatter_kwargs) from networkx import Graph, draw_networkx_edges if which_graph == 'neighbors': T = adata.uns['neighbors']['connectivities'] if perc is not None: threshold = np.percentile(T.data, perc) T.data[T.data < threshold] = 0 T.eliminate_zeros() else: T = transition_matrix(adata, vkey=vkey, weight_indirect_neighbors=0, n_neighbors=n_neighbors, perc=perc) with warnings.catch_warnings(): warnings.simplefilter("ignore") edges = draw_networkx_edges(Graph(T), adata.obsm['X_' + basis], width=edge_width, edge_color=edge_color, ax=ax) edges.set_zorder(-2) edges.set_rasterized(settings._vector_friendly) savefig_or_show('' if basis is None else basis, dpi=dpi, save=save, show=show) if not show: return ax
[ "def", "velocity_graph", "(", "adata", ",", "basis", "=", "None", ",", "vkey", "=", "'velocity'", ",", "which_graph", "=", "'velocity'", ",", "n_neighbors", "=", "10", ",", "alpha", "=", ".8", ",", "perc", "=", "90", ",", "edge_width", "=", ".2", ",", ...
\ Plot of the velocity graph. Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` or `None` (default: `None`) Key for annotations of observations/cells or variables/genes. which_graph: `'velocity'` or `'neighbors'` (default: `'velocity'`) Whether to show transitions from velocity graph or connectivities from neighbors graph. {scatter} Returns ------- `matplotlib.Axis` if `show==False`
[ "\\", "Plot", "of", "the", "velocity", "graph", "." ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/plotting/velocity_graph.py#L13-L63
24,403
theislab/scvelo
scvelo/preprocessing/utils.py
cleanup
def cleanup(data, clean='layers', keep=None, copy=False): """Deletes attributes not needed. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. clean: `str` or list of `str` (default: `layers`) Which attributes to consider for freeing memory. keep: `str` or list of `str` (default: None) Which attributes to keep. copy: `bool` (default: `False`) Return a copy instead of writing to adata. Returns ------- Returns or updates `adata` with selection of attributes kept. """ adata = data.copy() if copy else data keep = list([keep]) if isinstance(keep, str) else list() if keep is None else list(keep) keep.extend(['spliced', 'unspliced', 'Ms', 'Mu', 'clusters', 'neighbors']) ann_dict = {'obs': adata.obs_keys(), 'var': adata.var_keys(), 'uns': adata.uns_keys(), 'layers': list(adata.layers.keys())} if 'all' not in clean: ann_dict = {ann: values for (ann, values) in ann_dict.items() if ann in clean} for (ann, values) in ann_dict.items(): for value in values: if value not in keep: del(getattr(adata, ann)[value]) return adata if copy else None
python
def cleanup(data, clean='layers', keep=None, copy=False): adata = data.copy() if copy else data keep = list([keep]) if isinstance(keep, str) else list() if keep is None else list(keep) keep.extend(['spliced', 'unspliced', 'Ms', 'Mu', 'clusters', 'neighbors']) ann_dict = {'obs': adata.obs_keys(), 'var': adata.var_keys(), 'uns': adata.uns_keys(), 'layers': list(adata.layers.keys())} if 'all' not in clean: ann_dict = {ann: values for (ann, values) in ann_dict.items() if ann in clean} for (ann, values) in ann_dict.items(): for value in values: if value not in keep: del(getattr(adata, ann)[value]) return adata if copy else None
[ "def", "cleanup", "(", "data", ",", "clean", "=", "'layers'", ",", "keep", "=", "None", ",", "copy", "=", "False", ")", ":", "adata", "=", "data", ".", "copy", "(", ")", "if", "copy", "else", "data", "keep", "=", "list", "(", "[", "keep", "]", ...
Deletes attributes not needed. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. clean: `str` or list of `str` (default: `layers`) Which attributes to consider for freeing memory. keep: `str` or list of `str` (default: None) Which attributes to keep. copy: `bool` (default: `False`) Return a copy instead of writing to adata. Returns ------- Returns or updates `adata` with selection of attributes kept.
[ "Deletes", "attributes", "not", "needed", "." ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/preprocessing/utils.py#L30-L63
24,404
theislab/scvelo
scvelo/preprocessing/utils.py
filter_genes
def filter_genes(data, min_counts=None, min_cells=None, max_counts=None, max_cells=None, min_counts_u=None, min_cells_u=None, max_counts_u=None, max_cells_u=None, min_shared_counts=None, min_shared_cells=None, copy=False): """Filter genes based on number of cells or counts. Keep genes that have at least `min_counts` counts or are expressed in at least `min_cells` cells or have at most `max_counts` counts or are expressed in at most `max_cells` cells. Only provide one of the optional parameters `min_counts`, `min_cells`, `max_counts`, `max_cells` per call. Parameters ---------- data : :class:`~anndata.AnnData`, `np.ndarray`, `sp.spmatrix` The (annotated) data matrix of shape `n_obs` × `n_vars`. Rows correspond to cells and columns to genes. min_counts : `int`, optional (default: `None`) Minimum number of counts required for a gene to pass filtering. min_cells : `int`, optional (default: `None`) Minimum number of cells expressed required for a gene to pass filtering. max_counts : `int`, optional (default: `None`) Maximum number of counts required for a gene to pass filtering. max_cells : `int`, optional (default: `None`) Maximum number of cells expressed required for a gene to pass filtering. min_counts_u : `int`, optional (default: `None`) Minimum number of unspliced counts required for a gene to pass filtering. min_cells_u : `int`, optional (default: `None`) Minimum number of unspliced cells expressed required for a gene to pass filtering. max_counts_u : `int`, optional (default: `None`) Maximum number of unspliced counts required for a gene to pass filtering. max_cells_u : `int`, optional (default: `None`) Maximum number of unspliced cells expressed required for a gene to pass filtering. min_shared_counts: `int`, optional (default: `None`) Minimum number of counts (in cells expressed simultaneously in unspliced and spliced) required for a gene. min_shared_cells: `int`, optional (default: `None`) Minimum number of cells required for a gene to be expressed simultaneously in unspliced and spliced. copy : `bool`, optional (default: `False`) Determines whether a copy is returned. Returns ------- Filters the object and adds `n_counts` to `adata.var`. """ adata = data.copy() if copy else data # set initial cell sizes before filtering set_initial_size(adata) layers = [layer for layer in ['spliced', 'unspliced'] if layer in adata.layers.keys()] if min_shared_counts is not None or min_shared_cells is not None: layers.extend(['shared']) for layer in layers: if layer is 'spliced': _min_counts, _min_cells, _max_counts, _max_cells = min_counts, min_cells, max_counts, max_cells elif layer is 'unspliced': _min_counts, _min_cells, _max_counts, _max_cells = min_counts_u, min_cells_u, max_counts_u, max_cells_u else: # shared counts/cells _min_counts, _min_cells, _max_counts, _max_cells = min_shared_counts, min_shared_cells, None, None if layer in adata.layers.keys(): X = adata.layers[layer] else: # shared counts/cells Xs, Xu = adata.layers['spliced'], adata.layers['unspliced'] nonzeros = (Xs > 0).multiply(Xu > 0) if issparse(Xs) else (Xs > 0) * (Xu > 0) X = nonzeros.multiply(Xs) + nonzeros.multiply(Xu) if issparse(nonzeros) else nonzeros * (Xs + Xu) gene_subset = np.ones(adata.n_vars, dtype=bool) if _min_counts is not None or _max_counts is not None: gene_subset, _ = filter(X, min_counts=_min_counts, max_counts=_max_counts) adata._inplace_subset_var(gene_subset) if _min_cells is not None or _max_cells is not None: gene_subset, _ = filter(X, min_cells=_min_cells, max_cells=_max_cells) adata._inplace_subset_var(gene_subset) s = np.sum(~gene_subset) if s > 0: logg.info('Filtered out {} genes that are detected'.format(s), end=' ') if _min_cells is not None or _min_counts is not None: logg.info('in less than', str(_min_cells) + ' cells (' + str(layer) + ').' if _min_counts is None else str(_min_counts) + ' counts (' + str(layer) + ').', no_indent=True) if max_cells is not None or max_counts is not None: logg.info('in more than ', str(_max_cells) + ' cells(' + str(layer) + ').' if _max_counts is None else str(_max_counts) + ' counts (' + str(layer) + ').', no_indent=True) return adata if copy else None
python
def filter_genes(data, min_counts=None, min_cells=None, max_counts=None, max_cells=None, min_counts_u=None, min_cells_u=None, max_counts_u=None, max_cells_u=None, min_shared_counts=None, min_shared_cells=None, copy=False): adata = data.copy() if copy else data # set initial cell sizes before filtering set_initial_size(adata) layers = [layer for layer in ['spliced', 'unspliced'] if layer in adata.layers.keys()] if min_shared_counts is not None or min_shared_cells is not None: layers.extend(['shared']) for layer in layers: if layer is 'spliced': _min_counts, _min_cells, _max_counts, _max_cells = min_counts, min_cells, max_counts, max_cells elif layer is 'unspliced': _min_counts, _min_cells, _max_counts, _max_cells = min_counts_u, min_cells_u, max_counts_u, max_cells_u else: # shared counts/cells _min_counts, _min_cells, _max_counts, _max_cells = min_shared_counts, min_shared_cells, None, None if layer in adata.layers.keys(): X = adata.layers[layer] else: # shared counts/cells Xs, Xu = adata.layers['spliced'], adata.layers['unspliced'] nonzeros = (Xs > 0).multiply(Xu > 0) if issparse(Xs) else (Xs > 0) * (Xu > 0) X = nonzeros.multiply(Xs) + nonzeros.multiply(Xu) if issparse(nonzeros) else nonzeros * (Xs + Xu) gene_subset = np.ones(adata.n_vars, dtype=bool) if _min_counts is not None or _max_counts is not None: gene_subset, _ = filter(X, min_counts=_min_counts, max_counts=_max_counts) adata._inplace_subset_var(gene_subset) if _min_cells is not None or _max_cells is not None: gene_subset, _ = filter(X, min_cells=_min_cells, max_cells=_max_cells) adata._inplace_subset_var(gene_subset) s = np.sum(~gene_subset) if s > 0: logg.info('Filtered out {} genes that are detected'.format(s), end=' ') if _min_cells is not None or _min_counts is not None: logg.info('in less than', str(_min_cells) + ' cells (' + str(layer) + ').' if _min_counts is None else str(_min_counts) + ' counts (' + str(layer) + ').', no_indent=True) if max_cells is not None or max_counts is not None: logg.info('in more than ', str(_max_cells) + ' cells(' + str(layer) + ').' if _max_counts is None else str(_max_counts) + ' counts (' + str(layer) + ').', no_indent=True) return adata if copy else None
[ "def", "filter_genes", "(", "data", ",", "min_counts", "=", "None", ",", "min_cells", "=", "None", ",", "max_counts", "=", "None", ",", "max_cells", "=", "None", ",", "min_counts_u", "=", "None", ",", "min_cells_u", "=", "None", ",", "max_counts_u", "=", ...
Filter genes based on number of cells or counts. Keep genes that have at least `min_counts` counts or are expressed in at least `min_cells` cells or have at most `max_counts` counts or are expressed in at most `max_cells` cells. Only provide one of the optional parameters `min_counts`, `min_cells`, `max_counts`, `max_cells` per call. Parameters ---------- data : :class:`~anndata.AnnData`, `np.ndarray`, `sp.spmatrix` The (annotated) data matrix of shape `n_obs` × `n_vars`. Rows correspond to cells and columns to genes. min_counts : `int`, optional (default: `None`) Minimum number of counts required for a gene to pass filtering. min_cells : `int`, optional (default: `None`) Minimum number of cells expressed required for a gene to pass filtering. max_counts : `int`, optional (default: `None`) Maximum number of counts required for a gene to pass filtering. max_cells : `int`, optional (default: `None`) Maximum number of cells expressed required for a gene to pass filtering. min_counts_u : `int`, optional (default: `None`) Minimum number of unspliced counts required for a gene to pass filtering. min_cells_u : `int`, optional (default: `None`) Minimum number of unspliced cells expressed required for a gene to pass filtering. max_counts_u : `int`, optional (default: `None`) Maximum number of unspliced counts required for a gene to pass filtering. max_cells_u : `int`, optional (default: `None`) Maximum number of unspliced cells expressed required for a gene to pass filtering. min_shared_counts: `int`, optional (default: `None`) Minimum number of counts (in cells expressed simultaneously in unspliced and spliced) required for a gene. min_shared_cells: `int`, optional (default: `None`) Minimum number of cells required for a gene to be expressed simultaneously in unspliced and spliced. copy : `bool`, optional (default: `False`) Determines whether a copy is returned. Returns ------- Filters the object and adds `n_counts` to `adata.var`.
[ "Filter", "genes", "based", "on", "number", "of", "cells", "or", "counts", ".", "Keep", "genes", "that", "have", "at", "least", "min_counts", "counts", "or", "are", "expressed", "in", "at", "least", "min_cells", "cells", "or", "have", "at", "most", "max_co...
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/preprocessing/utils.py#L99-L185
24,405
theislab/scvelo
scvelo/preprocessing/utils.py
filter_genes_dispersion
def filter_genes_dispersion(data, flavor='seurat', min_disp=None, max_disp=None, min_mean=None, max_mean=None, n_bins=20, n_top_genes=None, log=True, copy=False): """Extract highly variable genes. The normalized dispersion is obtained by scaling with the mean and standard deviation of the dispersions for genes falling into a given bin for mean expression of genes. This means that for each bin of mean expression, highly variable genes are selected. Parameters ---------- data : :class:`~anndata.AnnData`, `np.ndarray`, `sp.sparse` The (annotated) data matrix of shape `n_obs` × `n_vars`. Rows correspond to cells and columns to genes. flavor : {'seurat', 'cell_ranger', 'svr'}, optional (default: 'seurat') Choose the flavor for computing normalized dispersion. If choosing 'seurat', this expects non-logarithmized data - the logarithm of mean and dispersion is taken internally when `log` is at its default value `True`. For 'cell_ranger', this is usually called for logarithmized data - in this case you should set `log` to `False`. In their default workflows, Seurat passes the cutoffs whereas Cell Ranger passes `n_top_genes`. min_mean=0.0125, max_mean=3, min_disp=0.5, max_disp=`None` : `float`, optional If `n_top_genes` unequals `None`, these cutoffs for the means and the normalized dispersions are ignored. n_bins : `int` (default: 20) Number of bins for binning the mean gene expression. Normalization is done with respect to each bin. If just a single gene falls into a bin, the normalized dispersion is artificially set to 1. You'll be informed about this if you set `settings.verbosity = 4`. n_top_genes : `int` or `None` (default: `None`) Number of highly-variable genes to keep. log : `bool`, optional (default: `True`) Use the logarithm of the mean to variance ratio. copy : `bool`, optional (default: `False`) If an :class:`~anndata.AnnData` is passed, determines whether a copy is returned. Returns ------- If an AnnData `adata` is passed, returns or updates `adata` depending on \ `copy`. It filters the `adata` and adds the annotations """ adata = data.copy() if copy else data set_initial_size(adata) if n_top_genes is not None and adata.n_vars < n_top_genes: logg.info('Skip filtering by dispersion since number of variables are less than `n_top_genes`') else: if flavor is 'svr': mu = adata.X.mean(0).A1 if issparse(adata.X) else adata.X.mean(0) sigma = np.sqrt(adata.X.multiply(adata.X).mean(0).A1 - mu ** 2) if issparse(adata.X) else adata.X.std(0) log_mu = np.log2(mu) log_cv = np.log2(sigma / mu) from sklearn.svm import SVR clf = SVR(gamma=150. / len(mu)) clf.fit(log_mu[:, None], log_cv) score = log_cv - clf.predict(log_mu[:, None]) nth_score = np.sort(score)[::-1][n_top_genes] adata._inplace_subset_var(score >= nth_score) else: from scanpy.api.pp import filter_genes_dispersion filter_genes_dispersion(adata, flavor=flavor, min_disp=min_disp, max_disp=max_disp, min_mean=min_mean, max_mean=max_mean, n_bins=n_bins, n_top_genes=n_top_genes, log=log) return adata if copy else None
python
def filter_genes_dispersion(data, flavor='seurat', min_disp=None, max_disp=None, min_mean=None, max_mean=None, n_bins=20, n_top_genes=None, log=True, copy=False): adata = data.copy() if copy else data set_initial_size(adata) if n_top_genes is not None and adata.n_vars < n_top_genes: logg.info('Skip filtering by dispersion since number of variables are less than `n_top_genes`') else: if flavor is 'svr': mu = adata.X.mean(0).A1 if issparse(adata.X) else adata.X.mean(0) sigma = np.sqrt(adata.X.multiply(adata.X).mean(0).A1 - mu ** 2) if issparse(adata.X) else adata.X.std(0) log_mu = np.log2(mu) log_cv = np.log2(sigma / mu) from sklearn.svm import SVR clf = SVR(gamma=150. / len(mu)) clf.fit(log_mu[:, None], log_cv) score = log_cv - clf.predict(log_mu[:, None]) nth_score = np.sort(score)[::-1][n_top_genes] adata._inplace_subset_var(score >= nth_score) else: from scanpy.api.pp import filter_genes_dispersion filter_genes_dispersion(adata, flavor=flavor, min_disp=min_disp, max_disp=max_disp, min_mean=min_mean, max_mean=max_mean, n_bins=n_bins, n_top_genes=n_top_genes, log=log) return adata if copy else None
[ "def", "filter_genes_dispersion", "(", "data", ",", "flavor", "=", "'seurat'", ",", "min_disp", "=", "None", ",", "max_disp", "=", "None", ",", "min_mean", "=", "None", ",", "max_mean", "=", "None", ",", "n_bins", "=", "20", ",", "n_top_genes", "=", "Non...
Extract highly variable genes. The normalized dispersion is obtained by scaling with the mean and standard deviation of the dispersions for genes falling into a given bin for mean expression of genes. This means that for each bin of mean expression, highly variable genes are selected. Parameters ---------- data : :class:`~anndata.AnnData`, `np.ndarray`, `sp.sparse` The (annotated) data matrix of shape `n_obs` × `n_vars`. Rows correspond to cells and columns to genes. flavor : {'seurat', 'cell_ranger', 'svr'}, optional (default: 'seurat') Choose the flavor for computing normalized dispersion. If choosing 'seurat', this expects non-logarithmized data - the logarithm of mean and dispersion is taken internally when `log` is at its default value `True`. For 'cell_ranger', this is usually called for logarithmized data - in this case you should set `log` to `False`. In their default workflows, Seurat passes the cutoffs whereas Cell Ranger passes `n_top_genes`. min_mean=0.0125, max_mean=3, min_disp=0.5, max_disp=`None` : `float`, optional If `n_top_genes` unequals `None`, these cutoffs for the means and the normalized dispersions are ignored. n_bins : `int` (default: 20) Number of bins for binning the mean gene expression. Normalization is done with respect to each bin. If just a single gene falls into a bin, the normalized dispersion is artificially set to 1. You'll be informed about this if you set `settings.verbosity = 4`. n_top_genes : `int` or `None` (default: `None`) Number of highly-variable genes to keep. log : `bool`, optional (default: `True`) Use the logarithm of the mean to variance ratio. copy : `bool`, optional (default: `False`) If an :class:`~anndata.AnnData` is passed, determines whether a copy is returned. Returns ------- If an AnnData `adata` is passed, returns or updates `adata` depending on \ `copy`. It filters the `adata` and adds the annotations
[ "Extract", "highly", "variable", "genes", ".", "The", "normalized", "dispersion", "is", "obtained", "by", "scaling", "with", "the", "mean", "and", "standard", "deviation", "of", "the", "dispersions", "for", "genes", "falling", "into", "a", "given", "bin", "for...
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/preprocessing/utils.py#L188-L251
24,406
theislab/scvelo
scvelo/preprocessing/utils.py
normalize_per_cell
def normalize_per_cell(data, counts_per_cell_after=None, counts_per_cell=None, key_n_counts=None, max_proportion_per_cell=None, use_initial_size=True, layers=['spliced', 'unspliced'], enforce=False, copy=False): """Normalize each cell by total counts over all genes. Parameters ---------- data : :class:`~anndata.AnnData`, `np.ndarray`, `sp.sparse` The (annotated) data matrix of shape `n_obs` × `n_vars`. Rows correspond to cells and columns to genes. counts_per_cell_after : `float` or `None`, optional (default: `None`) If `None`, after normalization, each cell has a total count equal to the median of the *counts_per_cell* before normalization. counts_per_cell : `np.array`, optional (default: `None`) Precomputed counts per cell. key_n_counts : `str`, optional (default: `'n_counts'`) Name of the field in `adata.obs` where the total counts per cell are stored. max_proportion_per_cell : `int` (default: `None`) Exclude genes counts that account for more than a specific proportion of cell size, e.g. 0.05. use_initial_size : `bool` (default: `True`) Whether to use initial cell sizes oder actual cell sizes. layers : `str` or `list` (default: `{'spliced', 'unspliced'}`) Keys for layers to be also considered for normalization. copy : `bool`, optional (default: `False`) If an :class:`~anndata.AnnData` is passed, determines whether a copy is returned. Returns ------- Returns or updates `adata` with normalized version of the original `adata.X`, depending on `copy`. """ adata = data.copy() if copy else data layers = adata.layers.keys() if layers is 'all' else [layers] if isinstance(layers, str) \ else [layer for layer in layers if layer in adata.layers.keys()] layers = ['X'] + layers modified_layers = [] for layer in layers: X = adata.X if layer is 'X' else adata.layers[layer] if not_yet_normalized(X) or enforce: counts = counts_per_cell if counts_per_cell is not None \ else get_initial_size(adata, layer) if use_initial_size else get_size(adata, layer) if max_proportion_per_cell is not None and (0 < max_proportion_per_cell < 1): counts = counts_per_cell_quantile(X, max_proportion_per_cell, counts) # equivalent to scanpy.pp.normalize_per_cell(X, counts_per_cell_after, counts) counts_after = np.median(counts) if counts_per_cell_after is None else counts_per_cell_after counts /= counts_after + (counts_after == 0) counts += counts == 0 # to avoid division by zero if issparse(X): sparsefuncs.inplace_row_scale(X, 1 / counts) else: X /= np.array(counts[:, None]) modified_layers.append(layer) adata.obs['n_counts' if key_n_counts is None else key_n_counts] = get_size(adata) if len(modified_layers) > 0: logg.info('Normalized count data:', ', '.join(modified_layers) + '.') return adata if copy else None
python
def normalize_per_cell(data, counts_per_cell_after=None, counts_per_cell=None, key_n_counts=None, max_proportion_per_cell=None, use_initial_size=True, layers=['spliced', 'unspliced'], enforce=False, copy=False): adata = data.copy() if copy else data layers = adata.layers.keys() if layers is 'all' else [layers] if isinstance(layers, str) \ else [layer for layer in layers if layer in adata.layers.keys()] layers = ['X'] + layers modified_layers = [] for layer in layers: X = adata.X if layer is 'X' else adata.layers[layer] if not_yet_normalized(X) or enforce: counts = counts_per_cell if counts_per_cell is not None \ else get_initial_size(adata, layer) if use_initial_size else get_size(adata, layer) if max_proportion_per_cell is not None and (0 < max_proportion_per_cell < 1): counts = counts_per_cell_quantile(X, max_proportion_per_cell, counts) # equivalent to scanpy.pp.normalize_per_cell(X, counts_per_cell_after, counts) counts_after = np.median(counts) if counts_per_cell_after is None else counts_per_cell_after counts /= counts_after + (counts_after == 0) counts += counts == 0 # to avoid division by zero if issparse(X): sparsefuncs.inplace_row_scale(X, 1 / counts) else: X /= np.array(counts[:, None]) modified_layers.append(layer) adata.obs['n_counts' if key_n_counts is None else key_n_counts] = get_size(adata) if len(modified_layers) > 0: logg.info('Normalized count data:', ', '.join(modified_layers) + '.') return adata if copy else None
[ "def", "normalize_per_cell", "(", "data", ",", "counts_per_cell_after", "=", "None", ",", "counts_per_cell", "=", "None", ",", "key_n_counts", "=", "None", ",", "max_proportion_per_cell", "=", "None", ",", "use_initial_size", "=", "True", ",", "layers", "=", "["...
Normalize each cell by total counts over all genes. Parameters ---------- data : :class:`~anndata.AnnData`, `np.ndarray`, `sp.sparse` The (annotated) data matrix of shape `n_obs` × `n_vars`. Rows correspond to cells and columns to genes. counts_per_cell_after : `float` or `None`, optional (default: `None`) If `None`, after normalization, each cell has a total count equal to the median of the *counts_per_cell* before normalization. counts_per_cell : `np.array`, optional (default: `None`) Precomputed counts per cell. key_n_counts : `str`, optional (default: `'n_counts'`) Name of the field in `adata.obs` where the total counts per cell are stored. max_proportion_per_cell : `int` (default: `None`) Exclude genes counts that account for more than a specific proportion of cell size, e.g. 0.05. use_initial_size : `bool` (default: `True`) Whether to use initial cell sizes oder actual cell sizes. layers : `str` or `list` (default: `{'spliced', 'unspliced'}`) Keys for layers to be also considered for normalization. copy : `bool`, optional (default: `False`) If an :class:`~anndata.AnnData` is passed, determines whether a copy is returned. Returns ------- Returns or updates `adata` with normalized version of the original `adata.X`, depending on `copy`.
[ "Normalize", "each", "cell", "by", "total", "counts", "over", "all", "genes", "." ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/preprocessing/utils.py#L266-L325
24,407
theislab/scvelo
scvelo/preprocessing/utils.py
filter_and_normalize
def filter_and_normalize(data, min_counts=None, min_counts_u=None, min_cells=None, min_cells_u=None, min_shared_counts=None, min_shared_cells=None, n_top_genes=None, flavor='seurat', log=True, copy=False): """Filtering, normalization and log transform Expects non-logarithmized data. If using logarithmized data, pass `log=False`. Runs the following steps .. code:: python scv.pp.filter_genes(adata) scv.pp.normalize_per_cell(adata) if n_top_genes is not None: scv.pp.filter_genes_dispersion(adata) if log: scv.pp.log1p(adata) Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. min_counts: `int` (default: `None`) Minimum number of counts required for a gene to pass filtering (spliced). min_counts_u: `int` (default: `None`) Minimum number of counts required for a gene to pass filtering (unspliced). min_cells: `int` (default: `None`) Minimum number of cells expressed required for a gene to pass filtering (spliced). min_cells_u: `int` (default: `None`) Minimum number of cells expressed required for a gene to pass filtering (unspliced). min_shared_counts: `int`, optional (default: `None`) Minimum number of counts (in cells expressed simultaneously in unspliced and spliced) required for a gene. min_shared_cells: `int`, optional (default: `None`) Minimum number of cells required for a gene to be expressed simultaneously in unspliced and spliced. n_top_genes: `int` (default: `None`) Number of genes to keep. flavor: {'seurat', 'cell_ranger', 'svr'}, optional (default: 'seurat') Choose the flavor for computing normalized dispersion. If choosing 'seurat', this expects non-logarithmized data. log: `bool` (default: `True`) Take logarithm. copy: `bool` (default: `False`) Return a copy of `adata` instead of updating it. Returns ------- Returns or updates `adata` depending on `copy`. """ adata = data.copy() if copy else data if 'spliced' not in adata.layers.keys() or 'unspliced' not in adata.layers.keys(): raise ValueError('Could not find spliced / unspliced counts.') filter_genes(adata, min_counts=min_counts, min_counts_u=min_counts_u, min_cells=min_cells, min_cells_u=min_cells_u, min_shared_counts=min_shared_counts, min_shared_cells=min_shared_cells,) normalize_per_cell(adata) if n_top_genes is not None: filter_genes_dispersion(adata, n_top_genes=n_top_genes, flavor=flavor) log_advised = np.allclose(adata.X[:10].sum(), adata.layers['spliced'][:10].sum()) if log and log_advised: log1p(adata) logg.info('Logarithmized X.' if log and log_advised else 'Did not modify X as it looks preprocessed already.' if log else 'Consider logarithmizing X with `scv.pp.log1p` for better results.' if log_advised else '') return adata if copy else None
python
def filter_and_normalize(data, min_counts=None, min_counts_u=None, min_cells=None, min_cells_u=None, min_shared_counts=None, min_shared_cells=None, n_top_genes=None, flavor='seurat', log=True, copy=False): adata = data.copy() if copy else data if 'spliced' not in adata.layers.keys() or 'unspliced' not in adata.layers.keys(): raise ValueError('Could not find spliced / unspliced counts.') filter_genes(adata, min_counts=min_counts, min_counts_u=min_counts_u, min_cells=min_cells, min_cells_u=min_cells_u, min_shared_counts=min_shared_counts, min_shared_cells=min_shared_cells,) normalize_per_cell(adata) if n_top_genes is not None: filter_genes_dispersion(adata, n_top_genes=n_top_genes, flavor=flavor) log_advised = np.allclose(adata.X[:10].sum(), adata.layers['spliced'][:10].sum()) if log and log_advised: log1p(adata) logg.info('Logarithmized X.' if log and log_advised else 'Did not modify X as it looks preprocessed already.' if log else 'Consider logarithmizing X with `scv.pp.log1p` for better results.' if log_advised else '') return adata if copy else None
[ "def", "filter_and_normalize", "(", "data", ",", "min_counts", "=", "None", ",", "min_counts_u", "=", "None", ",", "min_cells", "=", "None", ",", "min_cells_u", "=", "None", ",", "min_shared_counts", "=", "None", ",", "min_shared_cells", "=", "None", ",", "n...
Filtering, normalization and log transform Expects non-logarithmized data. If using logarithmized data, pass `log=False`. Runs the following steps .. code:: python scv.pp.filter_genes(adata) scv.pp.normalize_per_cell(adata) if n_top_genes is not None: scv.pp.filter_genes_dispersion(adata) if log: scv.pp.log1p(adata) Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. min_counts: `int` (default: `None`) Minimum number of counts required for a gene to pass filtering (spliced). min_counts_u: `int` (default: `None`) Minimum number of counts required for a gene to pass filtering (unspliced). min_cells: `int` (default: `None`) Minimum number of cells expressed required for a gene to pass filtering (spliced). min_cells_u: `int` (default: `None`) Minimum number of cells expressed required for a gene to pass filtering (unspliced). min_shared_counts: `int`, optional (default: `None`) Minimum number of counts (in cells expressed simultaneously in unspliced and spliced) required for a gene. min_shared_cells: `int`, optional (default: `None`) Minimum number of cells required for a gene to be expressed simultaneously in unspliced and spliced. n_top_genes: `int` (default: `None`) Number of genes to keep. flavor: {'seurat', 'cell_ranger', 'svr'}, optional (default: 'seurat') Choose the flavor for computing normalized dispersion. If choosing 'seurat', this expects non-logarithmized data. log: `bool` (default: `True`) Take logarithm. copy: `bool` (default: `False`) Return a copy of `adata` instead of updating it. Returns ------- Returns or updates `adata` depending on `copy`.
[ "Filtering", "normalization", "and", "log", "transform" ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/preprocessing/utils.py#L347-L414
24,408
theislab/scvelo
scvelo/datasets.py
toy_data
def toy_data(n_obs): """ Randomly samples from the Dentate Gyrus dataset. Arguments --------- n_obs: `int` Size of the sampled dataset Returns ------- Returns `adata` object """ """Random samples from Dentate Gyrus. """ adata = dentategyrus() indices = np.random.choice(adata.n_obs, n_obs) adata = adata[indices] adata.obs_names = np.array(range(adata.n_obs), dtype='str') adata.var_names_make_unique() return adata
python
def toy_data(n_obs): """Random samples from Dentate Gyrus. """ adata = dentategyrus() indices = np.random.choice(adata.n_obs, n_obs) adata = adata[indices] adata.obs_names = np.array(range(adata.n_obs), dtype='str') adata.var_names_make_unique() return adata
[ "def", "toy_data", "(", "n_obs", ")", ":", "\"\"\"Random samples from Dentate Gyrus.\n \"\"\"", "adata", "=", "dentategyrus", "(", ")", "indices", "=", "np", ".", "random", ".", "choice", "(", "adata", ".", "n_obs", ",", "n_obs", ")", "adata", "=", "adata",...
Randomly samples from the Dentate Gyrus dataset. Arguments --------- n_obs: `int` Size of the sampled dataset Returns ------- Returns `adata` object
[ "Randomly", "samples", "from", "the", "Dentate", "Gyrus", "dataset", "." ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/datasets.py#L10-L31
24,409
theislab/scvelo
scvelo/datasets.py
forebrain
def forebrain(): """Developing human forebrain. Forebrain tissue of a week 10 embryo, focusing on the glutamatergic neuronal lineage. Returns ------- Returns `adata` object """ filename = 'data/ForebrainGlut/hgForebrainGlut.loom' url = 'http://pklab.med.harvard.edu/velocyto/hgForebrainGlut/hgForebrainGlut.loom' adata = read(filename, backup_url=url, cleanup=True, sparse=True, cache=True) adata.var_names_make_unique() return adata
python
def forebrain(): filename = 'data/ForebrainGlut/hgForebrainGlut.loom' url = 'http://pklab.med.harvard.edu/velocyto/hgForebrainGlut/hgForebrainGlut.loom' adata = read(filename, backup_url=url, cleanup=True, sparse=True, cache=True) adata.var_names_make_unique() return adata
[ "def", "forebrain", "(", ")", ":", "filename", "=", "'data/ForebrainGlut/hgForebrainGlut.loom'", "url", "=", "'http://pklab.med.harvard.edu/velocyto/hgForebrainGlut/hgForebrainGlut.loom'", "adata", "=", "read", "(", "filename", ",", "backup_url", "=", "url", ",", "cleanup",...
Developing human forebrain. Forebrain tissue of a week 10 embryo, focusing on the glutamatergic neuronal lineage. Returns ------- Returns `adata` object
[ "Developing", "human", "forebrain", ".", "Forebrain", "tissue", "of", "a", "week", "10", "embryo", "focusing", "on", "the", "glutamatergic", "neuronal", "lineage", "." ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/datasets.py#L68-L80
24,410
theislab/scvelo
scvelo/settings.py
set_rcParams_scvelo
def set_rcParams_scvelo(fontsize=8, color_map=None, frameon=None): """Set matplotlib.rcParams to scvelo defaults.""" # dpi options (mpl default: 100, 100) rcParams['figure.dpi'] = 100 rcParams['savefig.dpi'] = 150 # figure (mpl default: 0.125, 0.96, 0.15, 0.91) rcParams['figure.figsize'] = (7, 5) rcParams['figure.subplot.left'] = 0.18 rcParams['figure.subplot.right'] = 0.96 rcParams['figure.subplot.bottom'] = 0.15 rcParams['figure.subplot.top'] = 0.91 # lines (defaults: 1.5, 6, 1) rcParams['lines.linewidth'] = 1.5 # the line width of the frame rcParams['lines.markersize'] = 6 rcParams['lines.markeredgewidth'] = 1 # font rcParams['font.sans-serif'] = \ ['Arial', 'Helvetica', 'DejaVu Sans', 'Bitstream Vera Sans', 'sans-serif'] fontsize = fontsize labelsize = 0.92 * fontsize # fonsizes (mpl default: 10, medium, large, medium) rcParams['font.size'] = fontsize rcParams['legend.fontsize'] = labelsize rcParams['axes.titlesize'] = fontsize rcParams['axes.labelsize'] = labelsize # legend (mpl default: 1, 1, 2, 0.8) rcParams['legend.numpoints'] = 1 rcParams['legend.scatterpoints'] = 1 rcParams['legend.handlelength'] = 0.5 rcParams['legend.handletextpad'] = 0.4 # color cycle rcParams['axes.prop_cycle'] = cycler(color=vega_10) # axes rcParams['axes.linewidth'] = 0.8 rcParams['axes.edgecolor'] = 'black' rcParams['axes.facecolor'] = 'white' # ticks (mpl default: k, k, medium, medium) rcParams['xtick.color'] = 'k' rcParams['ytick.color'] = 'k' rcParams['xtick.labelsize'] = labelsize rcParams['ytick.labelsize'] = labelsize # axes grid (mpl default: False, #b0b0b0) rcParams['axes.grid'] = False rcParams['grid.color'] = '.8' # color map rcParams['image.cmap'] = 'RdBu_r' if color_map is None else color_map # frame (mpl default: True) frameon = False if frameon is None else frameon global _frameon _frameon = frameon
python
def set_rcParams_scvelo(fontsize=8, color_map=None, frameon=None): # dpi options (mpl default: 100, 100) rcParams['figure.dpi'] = 100 rcParams['savefig.dpi'] = 150 # figure (mpl default: 0.125, 0.96, 0.15, 0.91) rcParams['figure.figsize'] = (7, 5) rcParams['figure.subplot.left'] = 0.18 rcParams['figure.subplot.right'] = 0.96 rcParams['figure.subplot.bottom'] = 0.15 rcParams['figure.subplot.top'] = 0.91 # lines (defaults: 1.5, 6, 1) rcParams['lines.linewidth'] = 1.5 # the line width of the frame rcParams['lines.markersize'] = 6 rcParams['lines.markeredgewidth'] = 1 # font rcParams['font.sans-serif'] = \ ['Arial', 'Helvetica', 'DejaVu Sans', 'Bitstream Vera Sans', 'sans-serif'] fontsize = fontsize labelsize = 0.92 * fontsize # fonsizes (mpl default: 10, medium, large, medium) rcParams['font.size'] = fontsize rcParams['legend.fontsize'] = labelsize rcParams['axes.titlesize'] = fontsize rcParams['axes.labelsize'] = labelsize # legend (mpl default: 1, 1, 2, 0.8) rcParams['legend.numpoints'] = 1 rcParams['legend.scatterpoints'] = 1 rcParams['legend.handlelength'] = 0.5 rcParams['legend.handletextpad'] = 0.4 # color cycle rcParams['axes.prop_cycle'] = cycler(color=vega_10) # axes rcParams['axes.linewidth'] = 0.8 rcParams['axes.edgecolor'] = 'black' rcParams['axes.facecolor'] = 'white' # ticks (mpl default: k, k, medium, medium) rcParams['xtick.color'] = 'k' rcParams['ytick.color'] = 'k' rcParams['xtick.labelsize'] = labelsize rcParams['ytick.labelsize'] = labelsize # axes grid (mpl default: False, #b0b0b0) rcParams['axes.grid'] = False rcParams['grid.color'] = '.8' # color map rcParams['image.cmap'] = 'RdBu_r' if color_map is None else color_map # frame (mpl default: True) frameon = False if frameon is None else frameon global _frameon _frameon = frameon
[ "def", "set_rcParams_scvelo", "(", "fontsize", "=", "8", ",", "color_map", "=", "None", ",", "frameon", "=", "None", ")", ":", "# dpi options (mpl default: 100, 100)", "rcParams", "[", "'figure.dpi'", "]", "=", "100", "rcParams", "[", "'savefig.dpi'", "]", "=", ...
Set matplotlib.rcParams to scvelo defaults.
[ "Set", "matplotlib", ".", "rcParams", "to", "scvelo", "defaults", "." ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/settings.py#L84-L147
24,411
theislab/scvelo
scvelo/read_load.py
merge
def merge(adata, ldata, copy=True): """Merges two annotated data matrices. Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix (reference data set). ldata: :class:`~anndata.AnnData` Annotated data matrix (to be merged into adata). Returns ------- Returns a :class:`~anndata.AnnData` object """ if 'spliced' in ldata.layers.keys() and 'initial_size_spliced' not in ldata.obs.keys(): set_initial_size(ldata) elif 'spliced' in adata.layers.keys() and 'initial_size_spliced' not in adata.obs.keys(): set_initial_size(adata) common_obs = adata.obs_names.intersection(ldata.obs_names) common_vars = adata.var_names.intersection(ldata.var_names) if len(common_obs) == 0: clean_obs_names(adata) clean_obs_names(ldata) common_obs = adata.obs_names.intersection(ldata.obs_names) if copy: _adata = adata[common_obs].copy() if adata.shape[1] >= ldata.shape[1] else ldata[common_obs].copy() _ldata = ldata[common_obs].copy() if adata.shape[1] >= ldata.shape[1] else adata[common_obs].copy() else: adata._inplace_subset_obs(common_obs) _adata, _ldata = adata, ldata[common_obs] same_vars = (len(_adata.var_names) == len(_ldata.var_names) and np.all(_adata.var_names == _ldata.var_names)) if len(common_vars) > 0 and not same_vars: _adata._inplace_subset_var(common_vars) _ldata._inplace_subset_var(common_vars) for attr in _ldata.obs.keys(): _adata.obs[attr] = _ldata.obs[attr] for attr in _ldata.obsm.keys(): _adata.obsm[attr] = _ldata.obsm[attr] for attr in _ldata.uns.keys(): _adata.uns[attr] = _ldata.uns[attr] for attr in _ldata.layers.keys(): _adata.layers[attr] = _ldata.layers[attr] if _adata.shape[1] == _ldata.shape[1]: same_vars = (len(_adata.var_names) == len(_ldata.var_names) and np.all(_adata.var_names == _ldata.var_names)) if same_vars: for attr in _ldata.var.keys(): _adata.var[attr] = _ldata.var[attr] for attr in _ldata.varm.keys(): _adata.varm[attr] = _ldata.varm[attr] else: raise ValueError('Variable names are not identical.') return _adata if copy else None
python
def merge(adata, ldata, copy=True): if 'spliced' in ldata.layers.keys() and 'initial_size_spliced' not in ldata.obs.keys(): set_initial_size(ldata) elif 'spliced' in adata.layers.keys() and 'initial_size_spliced' not in adata.obs.keys(): set_initial_size(adata) common_obs = adata.obs_names.intersection(ldata.obs_names) common_vars = adata.var_names.intersection(ldata.var_names) if len(common_obs) == 0: clean_obs_names(adata) clean_obs_names(ldata) common_obs = adata.obs_names.intersection(ldata.obs_names) if copy: _adata = adata[common_obs].copy() if adata.shape[1] >= ldata.shape[1] else ldata[common_obs].copy() _ldata = ldata[common_obs].copy() if adata.shape[1] >= ldata.shape[1] else adata[common_obs].copy() else: adata._inplace_subset_obs(common_obs) _adata, _ldata = adata, ldata[common_obs] same_vars = (len(_adata.var_names) == len(_ldata.var_names) and np.all(_adata.var_names == _ldata.var_names)) if len(common_vars) > 0 and not same_vars: _adata._inplace_subset_var(common_vars) _ldata._inplace_subset_var(common_vars) for attr in _ldata.obs.keys(): _adata.obs[attr] = _ldata.obs[attr] for attr in _ldata.obsm.keys(): _adata.obsm[attr] = _ldata.obsm[attr] for attr in _ldata.uns.keys(): _adata.uns[attr] = _ldata.uns[attr] for attr in _ldata.layers.keys(): _adata.layers[attr] = _ldata.layers[attr] if _adata.shape[1] == _ldata.shape[1]: same_vars = (len(_adata.var_names) == len(_ldata.var_names) and np.all(_adata.var_names == _ldata.var_names)) if same_vars: for attr in _ldata.var.keys(): _adata.var[attr] = _ldata.var[attr] for attr in _ldata.varm.keys(): _adata.varm[attr] = _ldata.varm[attr] else: raise ValueError('Variable names are not identical.') return _adata if copy else None
[ "def", "merge", "(", "adata", ",", "ldata", ",", "copy", "=", "True", ")", ":", "if", "'spliced'", "in", "ldata", ".", "layers", ".", "keys", "(", ")", "and", "'initial_size_spliced'", "not", "in", "ldata", ".", "obs", ".", "keys", "(", ")", ":", "...
Merges two annotated data matrices. Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix (reference data set). ldata: :class:`~anndata.AnnData` Annotated data matrix (to be merged into adata). Returns ------- Returns a :class:`~anndata.AnnData` object
[ "Merges", "two", "annotated", "data", "matrices", "." ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/read_load.py#L102-L158
24,412
theislab/scvelo
scvelo/tools/velocity_graph.py
velocity_graph
def velocity_graph(data, vkey='velocity', xkey='Ms', tkey=None, basis=None, n_neighbors=None, n_recurse_neighbors=None, random_neighbors_at_max=None, sqrt_transform=False, approx=False, copy=False): """Computes velocity graph based on cosine similarities. The cosine similarities are computed between velocities and potential cell state transitions. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name of velocity estimates to be used. n_neighbors: `int` or `None` (default: None) Use fixed number of neighbors or do recursive neighbor search (if `None`). n_recurse_neighbors: `int` (default: 2) Number of recursions to be done for neighbors search. random_neighbors_at_max: `int` or `None` (default: `None`) If number of iterative neighbors for an individual cell is higher than this threshold, a random selection of such are chosen as reference neighbors. sqrt_transform: `bool` (default: `False`) Whether to variance-transform the cell states changes and velocities before computing cosine similarities. copy: `bool` (default: `False`) Return a copy instead of writing to adata. Returns ------- Returns or updates `adata` with the attributes velocity_graph: `.uns` sparse matrix with transition probabilities """ adata = data.copy() if copy else data if vkey not in adata.layers.keys(): velocity(adata, vkey=vkey) vgraph = VelocityGraph(adata, vkey=vkey, xkey=xkey, tkey=tkey, basis=basis, n_neighbors=n_neighbors, approx=approx, n_recurse_neighbors=n_recurse_neighbors, random_neighbors_at_max=random_neighbors_at_max, sqrt_transform=sqrt_transform, report=True) logg.info('computing velocity graph', r=True) vgraph.compute_cosines() adata.uns[vkey+'_graph'] = vgraph.graph adata.uns[vkey+'_graph_neg'] = vgraph.graph_neg logg.info(' finished', time=True, end=' ' if settings.verbosity > 2 else '\n') logg.hint( 'added \n' ' \'' + vkey + '_graph\', sparse matrix with cosine correlations (adata.uns)') return adata if copy else None
python
def velocity_graph(data, vkey='velocity', xkey='Ms', tkey=None, basis=None, n_neighbors=None, n_recurse_neighbors=None, random_neighbors_at_max=None, sqrt_transform=False, approx=False, copy=False): adata = data.copy() if copy else data if vkey not in adata.layers.keys(): velocity(adata, vkey=vkey) vgraph = VelocityGraph(adata, vkey=vkey, xkey=xkey, tkey=tkey, basis=basis, n_neighbors=n_neighbors, approx=approx, n_recurse_neighbors=n_recurse_neighbors, random_neighbors_at_max=random_neighbors_at_max, sqrt_transform=sqrt_transform, report=True) logg.info('computing velocity graph', r=True) vgraph.compute_cosines() adata.uns[vkey+'_graph'] = vgraph.graph adata.uns[vkey+'_graph_neg'] = vgraph.graph_neg logg.info(' finished', time=True, end=' ' if settings.verbosity > 2 else '\n') logg.hint( 'added \n' ' \'' + vkey + '_graph\', sparse matrix with cosine correlations (adata.uns)') return adata if copy else None
[ "def", "velocity_graph", "(", "data", ",", "vkey", "=", "'velocity'", ",", "xkey", "=", "'Ms'", ",", "tkey", "=", "None", ",", "basis", "=", "None", ",", "n_neighbors", "=", "None", ",", "n_recurse_neighbors", "=", "None", ",", "random_neighbors_at_max", "...
Computes velocity graph based on cosine similarities. The cosine similarities are computed between velocities and potential cell state transitions. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name of velocity estimates to be used. n_neighbors: `int` or `None` (default: None) Use fixed number of neighbors or do recursive neighbor search (if `None`). n_recurse_neighbors: `int` (default: 2) Number of recursions to be done for neighbors search. random_neighbors_at_max: `int` or `None` (default: `None`) If number of iterative neighbors for an individual cell is higher than this threshold, a random selection of such are chosen as reference neighbors. sqrt_transform: `bool` (default: `False`) Whether to variance-transform the cell states changes and velocities before computing cosine similarities. copy: `bool` (default: `False`) Return a copy instead of writing to adata. Returns ------- Returns or updates `adata` with the attributes velocity_graph: `.uns` sparse matrix with transition probabilities
[ "Computes", "velocity", "graph", "based", "on", "cosine", "similarities", "." ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/tools/velocity_graph.py#L120-L168
24,413
theislab/scvelo
scvelo/tools/optimization.py
optimize_NxN
def optimize_NxN(x, y, fit_offset=False, perc=None): """Just to compare with closed-form solution """ if perc is not None: if not fit_offset and isinstance(perc, (list, tuple)): perc = perc[1] weights = get_weight(x, y, perc).astype(bool) if issparse(weights): weights = weights.A else: weights = None x, y = x.astype(np.float64), y.astype(np.float64) n_vars = x.shape[1] offset, gamma = np.zeros(n_vars), np.zeros(n_vars) for i in range(n_vars): xi = x[:, i] if weights is None else x[:, i][weights[:, i]] yi = y[:, i] if weights is None else y[:, i][weights[:, i]] if fit_offset: offset[i], gamma[i] = minimize(lambda m: np.sum((-yi + xi * m[1] + m[0])**2), method="L-BFGS-B", x0=(0, 0.1), bounds=[(0, None), (None, None)]).x else: gamma[i] = minimize(lambda m: np.sum((-yi + xi * m) ** 2), x0=0.1, method="L-BFGS-B").x offset[np.isnan(offset)], gamma[np.isnan(gamma)] = 0, 0 return offset, gamma
python
def optimize_NxN(x, y, fit_offset=False, perc=None): if perc is not None: if not fit_offset and isinstance(perc, (list, tuple)): perc = perc[1] weights = get_weight(x, y, perc).astype(bool) if issparse(weights): weights = weights.A else: weights = None x, y = x.astype(np.float64), y.astype(np.float64) n_vars = x.shape[1] offset, gamma = np.zeros(n_vars), np.zeros(n_vars) for i in range(n_vars): xi = x[:, i] if weights is None else x[:, i][weights[:, i]] yi = y[:, i] if weights is None else y[:, i][weights[:, i]] if fit_offset: offset[i], gamma[i] = minimize(lambda m: np.sum((-yi + xi * m[1] + m[0])**2), method="L-BFGS-B", x0=(0, 0.1), bounds=[(0, None), (None, None)]).x else: gamma[i] = minimize(lambda m: np.sum((-yi + xi * m) ** 2), x0=0.1, method="L-BFGS-B").x offset[np.isnan(offset)], gamma[np.isnan(gamma)] = 0, 0 return offset, gamma
[ "def", "optimize_NxN", "(", "x", ",", "y", ",", "fit_offset", "=", "False", ",", "perc", "=", "None", ")", ":", "if", "perc", "is", "not", "None", ":", "if", "not", "fit_offset", "and", "isinstance", "(", "perc", ",", "(", "list", ",", "tuple", ")"...
Just to compare with closed-form solution
[ "Just", "to", "compare", "with", "closed", "-", "form", "solution" ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/tools/optimization.py#L55-L80
24,414
theislab/scvelo
scvelo/tools/velocity_confidence.py
velocity_confidence
def velocity_confidence(data, vkey='velocity', copy=False): """Computes confidences of velocities. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name of velocity estimates to be used. copy: `bool` (default: `False`) Return a copy instead of writing to adata. Returns ------- Returns or updates `adata` with the attributes velocity_length: `.obs` Length of the velocity vectors for each individual cell velocity_confidence: `.obs` Confidence for each cell """ adata = data.copy() if copy else data if vkey not in adata.layers.keys(): raise ValueError( 'You need to run `tl.velocity` first.') idx = np.array(adata.var[vkey + '_genes'].values, dtype=bool) X, V = adata.layers['Ms'][:, idx].copy(), adata.layers[vkey][:, idx].copy() indices = get_indices(dist=adata.uns['neighbors']['distances'])[0] V -= V.mean(1)[:, None] V_norm = norm(V) R = np.zeros(adata.n_obs) for i in range(adata.n_obs): Vi_neighs = V[indices[i]] Vi_neighs -= Vi_neighs.mean(1)[:, None] R[i] = np.mean(np.einsum('ij, j', Vi_neighs, V[i]) / (norm(Vi_neighs) * V_norm[i])[None, :]) adata.obs[vkey + '_length'] = V_norm.round(2) adata.obs[vkey + '_confidence'] = R logg.hint('added \'' + vkey + '_confidence\' (adata.obs)') if vkey + '_confidence_transition' not in adata.obs.keys(): velocity_confidence_transition(adata, vkey) return adata if copy else None
python
def velocity_confidence(data, vkey='velocity', copy=False): adata = data.copy() if copy else data if vkey not in adata.layers.keys(): raise ValueError( 'You need to run `tl.velocity` first.') idx = np.array(adata.var[vkey + '_genes'].values, dtype=bool) X, V = adata.layers['Ms'][:, idx].copy(), adata.layers[vkey][:, idx].copy() indices = get_indices(dist=adata.uns['neighbors']['distances'])[0] V -= V.mean(1)[:, None] V_norm = norm(V) R = np.zeros(adata.n_obs) for i in range(adata.n_obs): Vi_neighs = V[indices[i]] Vi_neighs -= Vi_neighs.mean(1)[:, None] R[i] = np.mean(np.einsum('ij, j', Vi_neighs, V[i]) / (norm(Vi_neighs) * V_norm[i])[None, :]) adata.obs[vkey + '_length'] = V_norm.round(2) adata.obs[vkey + '_confidence'] = R logg.hint('added \'' + vkey + '_confidence\' (adata.obs)') if vkey + '_confidence_transition' not in adata.obs.keys(): velocity_confidence_transition(adata, vkey) return adata if copy else None
[ "def", "velocity_confidence", "(", "data", ",", "vkey", "=", "'velocity'", ",", "copy", "=", "False", ")", ":", "adata", "=", "data", ".", "copy", "(", ")", "if", "copy", "else", "data", "if", "vkey", "not", "in", "adata", ".", "layers", ".", "keys",...
Computes confidences of velocities. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name of velocity estimates to be used. copy: `bool` (default: `False`) Return a copy instead of writing to adata. Returns ------- Returns or updates `adata` with the attributes velocity_length: `.obs` Length of the velocity vectors for each individual cell velocity_confidence: `.obs` Confidence for each cell
[ "Computes", "confidences", "of", "velocities", "." ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/tools/velocity_confidence.py#L10-L56
24,415
theislab/scvelo
scvelo/tools/velocity_confidence.py
velocity_confidence_transition
def velocity_confidence_transition(data, vkey='velocity', scale=10, copy=False): """Computes confidences of velocity transitions. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name of velocity estimates to be used. scale: `float` (default: 10) Scale parameter of gaussian kernel. copy: `bool` (default: `False`) Return a copy instead of writing to adata. Returns ------- Returns or updates `adata` with the attributes velocity_confidence_transition: `.obs` Confidence of transition for each cell """ adata = data.copy() if copy else data if vkey not in adata.layers.keys(): raise ValueError( 'You need to run `tl.velocity` first.') idx = np.array(adata.var[vkey + '_genes'].values, dtype=bool) T = transition_matrix(adata, vkey=vkey, scale=scale) dX = T.dot(adata.layers['Ms'][:, idx]) - adata.layers['Ms'][:, idx] dX -= dX.mean(1)[:, None] V = adata.layers[vkey][:, idx].copy() V -= V.mean(1)[:, None] adata.obs[vkey + '_confidence_transition'] = prod_sum_var(dX, V) / (norm(dX) * norm(V)) logg.hint('added \'' + vkey + '_confidence_transition\' (adata.obs)') return adata if copy else None
python
def velocity_confidence_transition(data, vkey='velocity', scale=10, copy=False): adata = data.copy() if copy else data if vkey not in adata.layers.keys(): raise ValueError( 'You need to run `tl.velocity` first.') idx = np.array(adata.var[vkey + '_genes'].values, dtype=bool) T = transition_matrix(adata, vkey=vkey, scale=scale) dX = T.dot(adata.layers['Ms'][:, idx]) - adata.layers['Ms'][:, idx] dX -= dX.mean(1)[:, None] V = adata.layers[vkey][:, idx].copy() V -= V.mean(1)[:, None] adata.obs[vkey + '_confidence_transition'] = prod_sum_var(dX, V) / (norm(dX) * norm(V)) logg.hint('added \'' + vkey + '_confidence_transition\' (adata.obs)') return adata if copy else None
[ "def", "velocity_confidence_transition", "(", "data", ",", "vkey", "=", "'velocity'", ",", "scale", "=", "10", ",", "copy", "=", "False", ")", ":", "adata", "=", "data", ".", "copy", "(", ")", "if", "copy", "else", "data", "if", "vkey", "not", "in", ...
Computes confidences of velocity transitions. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name of velocity estimates to be used. scale: `float` (default: 10) Scale parameter of gaussian kernel. copy: `bool` (default: `False`) Return a copy instead of writing to adata. Returns ------- Returns or updates `adata` with the attributes velocity_confidence_transition: `.obs` Confidence of transition for each cell
[ "Computes", "confidences", "of", "velocity", "transitions", "." ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/tools/velocity_confidence.py#L59-L96
24,416
theislab/scvelo
scvelo/tools/terminal_states.py
cell_fate
def cell_fate(data, groupby='clusters', disconnected_groups=None, self_transitions=False, n_neighbors=None, copy=False): """Computes individual cell endpoints Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. groupby: `str` (default: `'clusters'`) Key to which to assign the fates. disconnected_groups: list of `str` (default: `None`) Which groups to treat as disconnected for fate assignment. n_neighbors: `int` (default: `None`) Number of neighbors to restrict transitions to. copy: `bool` (default: `False`) Return a copy instead of writing to `adata`. Returns ------- Returns or updates `adata` with the attributes cell_fate: `.obs` most likely cell fate for each individual cell cell_fate_confidence: `.obs` confidence of transitioning to the assigned fate """ adata = data.copy() if copy else data logg.info('computing cell fates', r=True) n_neighbors = 10 if n_neighbors is None else n_neighbors _adata = adata.copy() vgraph = VelocityGraph(_adata, n_neighbors=n_neighbors, approx=True, n_recurse_neighbors=1) vgraph.compute_cosines() _adata.uns['velocity_graph'] = vgraph.graph _adata.uns['velocity_graph_neg'] = vgraph.graph_neg T = transition_matrix(_adata, self_transitions=self_transitions) I = np.eye(_adata.n_obs) fate = np.linalg.inv(I - T) if issparse(T): fate = fate.A cell_fates = np.array(_adata.obs[groupby][fate.argmax(1)]) if disconnected_groups is not None: idx = _adata.obs[groupby].isin(disconnected_groups) cell_fates[idx] = _adata.obs[groupby][idx] adata.obs['cell_fate'] = cell_fates adata.obs['cell_fate_confidence'] = fate.max(1) / fate.sum(1) strings_to_categoricals(adata) logg.info(' finished', time=True, end=' ' if settings.verbosity > 2 else '\n') logg.hint( 'added\n' ' \'cell_fate\', most likely cell fate (adata.obs)\n' ' \'cell_fate_confidence\', confidence of transitioning to the assigned fate (adata.obs)') return adata if copy else None
python
def cell_fate(data, groupby='clusters', disconnected_groups=None, self_transitions=False, n_neighbors=None, copy=False): adata = data.copy() if copy else data logg.info('computing cell fates', r=True) n_neighbors = 10 if n_neighbors is None else n_neighbors _adata = adata.copy() vgraph = VelocityGraph(_adata, n_neighbors=n_neighbors, approx=True, n_recurse_neighbors=1) vgraph.compute_cosines() _adata.uns['velocity_graph'] = vgraph.graph _adata.uns['velocity_graph_neg'] = vgraph.graph_neg T = transition_matrix(_adata, self_transitions=self_transitions) I = np.eye(_adata.n_obs) fate = np.linalg.inv(I - T) if issparse(T): fate = fate.A cell_fates = np.array(_adata.obs[groupby][fate.argmax(1)]) if disconnected_groups is not None: idx = _adata.obs[groupby].isin(disconnected_groups) cell_fates[idx] = _adata.obs[groupby][idx] adata.obs['cell_fate'] = cell_fates adata.obs['cell_fate_confidence'] = fate.max(1) / fate.sum(1) strings_to_categoricals(adata) logg.info(' finished', time=True, end=' ' if settings.verbosity > 2 else '\n') logg.hint( 'added\n' ' \'cell_fate\', most likely cell fate (adata.obs)\n' ' \'cell_fate_confidence\', confidence of transitioning to the assigned fate (adata.obs)') return adata if copy else None
[ "def", "cell_fate", "(", "data", ",", "groupby", "=", "'clusters'", ",", "disconnected_groups", "=", "None", ",", "self_transitions", "=", "False", ",", "n_neighbors", "=", "None", ",", "copy", "=", "False", ")", ":", "adata", "=", "data", ".", "copy", "...
Computes individual cell endpoints Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. groupby: `str` (default: `'clusters'`) Key to which to assign the fates. disconnected_groups: list of `str` (default: `None`) Which groups to treat as disconnected for fate assignment. n_neighbors: `int` (default: `None`) Number of neighbors to restrict transitions to. copy: `bool` (default: `False`) Return a copy instead of writing to `adata`. Returns ------- Returns or updates `adata` with the attributes cell_fate: `.obs` most likely cell fate for each individual cell cell_fate_confidence: `.obs` confidence of transitioning to the assigned fate
[ "Computes", "individual", "cell", "endpoints" ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/tools/terminal_states.py#L12-L64
24,417
theislab/scvelo
scvelo/preprocessing/moments.py
moments
def moments(data, n_neighbors=30, n_pcs=30, mode='connectivities', method='umap', metric='euclidean', use_rep=None, recurse_neighbors=False, renormalize=False, copy=False): """Computes moments for velocity estimation. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. n_neighbors: `int` (default: 30) Number of neighbors to use. n_pcs: `int` (default: 30) Number of principal components to use. mode: `'connectivities'` or `'distances'` (default: `'connectivities'`) Distance metric to use for moment computation. renormalize: `bool` (default: `False`) Renormalize the moments by total counts per cell to its median. copy: `bool` (default: `False`) Return a copy instead of writing to adata. Returns ------- Returns or updates `adata` with the attributes Ms: `.layers` dense matrix with first order moments of spliced counts. Mu: `.layers` dense matrix with first order moments of unspliced counts. """ adata = data.copy() if copy else data if 'spliced' not in adata.layers.keys() or 'unspliced' not in adata.layers.keys(): raise ValueError('Could not find spliced / unspliced counts.') if any([not_yet_normalized(adata.layers[layer]) for layer in {'spliced', 'unspliced'}]): normalize_per_cell(adata) if 'neighbors' not in adata.uns.keys() or neighbors_to_be_recomputed(adata, n_neighbors=n_neighbors): if use_rep is None: use_rep = 'X_pca' neighbors(adata, n_neighbors=n_neighbors, use_rep=use_rep, n_pcs=n_pcs, method=method, metric=metric) if mode not in adata.uns['neighbors']: raise ValueError('mode can only be \'connectivities\' or \'distances\'') logg.info('computing moments based on ' + str(mode), r=True) connectivities = get_connectivities(adata, mode, n_neighbors=n_neighbors, recurse_neighbors=recurse_neighbors) adata.layers['Ms'] = csr_matrix.dot(connectivities, csr_matrix(adata.layers['spliced'])).astype(np.float32).A adata.layers['Mu'] = csr_matrix.dot(connectivities, csr_matrix(adata.layers['unspliced'])).astype(np.float32).A if renormalize: normalize_per_cell(adata, layers={'Ms', 'Mu'}, enforce=True) logg.info(' finished', time=True, end=' ' if settings.verbosity > 2 else '\n') logg.hint( 'added \n' ' \'Ms\' and \'Mu\', moments of spliced/unspliced abundances (adata.layers)') return adata if copy else None
python
def moments(data, n_neighbors=30, n_pcs=30, mode='connectivities', method='umap', metric='euclidean', use_rep=None, recurse_neighbors=False, renormalize=False, copy=False): adata = data.copy() if copy else data if 'spliced' not in adata.layers.keys() or 'unspliced' not in adata.layers.keys(): raise ValueError('Could not find spliced / unspliced counts.') if any([not_yet_normalized(adata.layers[layer]) for layer in {'spliced', 'unspliced'}]): normalize_per_cell(adata) if 'neighbors' not in adata.uns.keys() or neighbors_to_be_recomputed(adata, n_neighbors=n_neighbors): if use_rep is None: use_rep = 'X_pca' neighbors(adata, n_neighbors=n_neighbors, use_rep=use_rep, n_pcs=n_pcs, method=method, metric=metric) if mode not in adata.uns['neighbors']: raise ValueError('mode can only be \'connectivities\' or \'distances\'') logg.info('computing moments based on ' + str(mode), r=True) connectivities = get_connectivities(adata, mode, n_neighbors=n_neighbors, recurse_neighbors=recurse_neighbors) adata.layers['Ms'] = csr_matrix.dot(connectivities, csr_matrix(adata.layers['spliced'])).astype(np.float32).A adata.layers['Mu'] = csr_matrix.dot(connectivities, csr_matrix(adata.layers['unspliced'])).astype(np.float32).A if renormalize: normalize_per_cell(adata, layers={'Ms', 'Mu'}, enforce=True) logg.info(' finished', time=True, end=' ' if settings.verbosity > 2 else '\n') logg.hint( 'added \n' ' \'Ms\' and \'Mu\', moments of spliced/unspliced abundances (adata.layers)') return adata if copy else None
[ "def", "moments", "(", "data", ",", "n_neighbors", "=", "30", ",", "n_pcs", "=", "30", ",", "mode", "=", "'connectivities'", ",", "method", "=", "'umap'", ",", "metric", "=", "'euclidean'", ",", "use_rep", "=", "None", ",", "recurse_neighbors", "=", "Fal...
Computes moments for velocity estimation. Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. n_neighbors: `int` (default: 30) Number of neighbors to use. n_pcs: `int` (default: 30) Number of principal components to use. mode: `'connectivities'` or `'distances'` (default: `'connectivities'`) Distance metric to use for moment computation. renormalize: `bool` (default: `False`) Renormalize the moments by total counts per cell to its median. copy: `bool` (default: `False`) Return a copy instead of writing to adata. Returns ------- Returns or updates `adata` with the attributes Ms: `.layers` dense matrix with first order moments of spliced counts. Mu: `.layers` dense matrix with first order moments of unspliced counts.
[ "Computes", "moments", "for", "velocity", "estimation", "." ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/preprocessing/moments.py#L10-L61
24,418
theislab/scvelo
scvelo/tools/transition_matrix.py
transition_matrix
def transition_matrix(adata, vkey='velocity', basis=None, backward=False, self_transitions=True, scale=10, perc=None, use_negative_cosines=False, weight_diffusion=0, scale_diffusion=1, weight_indirect_neighbors=None, n_neighbors=None, vgraph=None): """Computes transition probabilities from velocity graph Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name of velocity estimates to be used. basis: `str` or `None` (default: `None`) Restrict transition to embedding if specified backward: `bool` (default: `False`) Whether to use the transition matrix to push forward (`False`) or to pull backward (`True`) scale: `float` (default: 10) Scale parameter of gaussian kernel. weight_diffusion: `float` (default: 0) Relative weight to be given to diffusion kernel (Brownian motion) scale_diffusion: `float` (default: 1) Scale of diffusion kernel. Returns ------- Returns sparse matrix with transition probabilities. """ if vkey+'_graph' not in adata.uns: raise ValueError('You need to run `tl.velocity_graph` first to compute cosine correlations.') graph = csr_matrix(adata.uns[vkey + '_graph']).copy() if vgraph is None else vgraph.copy() if self_transitions: confidence = graph.max(1).A.flatten() ub = np.percentile(confidence, 98) self_prob = np.clip(ub - confidence, 0, 1) graph.setdiag(self_prob) T = np.expm1(graph * scale) # equivalent to np.exp(graph.A * scale) - 1 if vkey + '_graph_neg' in adata.uns.keys(): graph_neg = adata.uns[vkey + '_graph_neg'] if use_negative_cosines: T -= np.expm1(-graph_neg * scale) else: T += np.expm1(graph_neg * scale) T.data += 1 # weight direct and indirect (recursed) neighbors if 'neighbors' in adata.uns.keys() and weight_indirect_neighbors is not None and weight_indirect_neighbors < 1: direct_neighbors = adata.uns['neighbors']['distances'] > 0 direct_neighbors.setdiag(1) w = weight_indirect_neighbors T = w * T + (1-w) * direct_neighbors.multiply(T) if backward: T = T.T T = normalize(T) if n_neighbors is not None: T = T.multiply(get_connectivities(adata, mode='distances', n_neighbors=n_neighbors, recurse_neighbors=True)) if perc is not None: threshold = np.percentile(T.data, perc) T.data[T.data < threshold] = 0 T.eliminate_zeros() if 'X_' + str(basis) in adata.obsm.keys(): dists_emb = (T > 0).multiply(squareform(pdist(adata.obsm['X_' + basis]))) scale_diffusion *= dists_emb.data.mean() diffusion_kernel = dists_emb.copy() diffusion_kernel.data = np.exp(-.5 * dists_emb.data ** 2 / scale_diffusion ** 2) T = T.multiply(diffusion_kernel) # combine velocity based kernel with diffusion based kernel if 0 < weight_diffusion < 1: # add another diffusion kernel (Brownian motion - like) diffusion_kernel.data = np.exp(-.5 * dists_emb.data ** 2 / (scale_diffusion/2) ** 2) T = (1-weight_diffusion) * T + weight_diffusion * diffusion_kernel T = normalize(T) return T
python
def transition_matrix(adata, vkey='velocity', basis=None, backward=False, self_transitions=True, scale=10, perc=None, use_negative_cosines=False, weight_diffusion=0, scale_diffusion=1, weight_indirect_neighbors=None, n_neighbors=None, vgraph=None): if vkey+'_graph' not in adata.uns: raise ValueError('You need to run `tl.velocity_graph` first to compute cosine correlations.') graph = csr_matrix(adata.uns[vkey + '_graph']).copy() if vgraph is None else vgraph.copy() if self_transitions: confidence = graph.max(1).A.flatten() ub = np.percentile(confidence, 98) self_prob = np.clip(ub - confidence, 0, 1) graph.setdiag(self_prob) T = np.expm1(graph * scale) # equivalent to np.exp(graph.A * scale) - 1 if vkey + '_graph_neg' in adata.uns.keys(): graph_neg = adata.uns[vkey + '_graph_neg'] if use_negative_cosines: T -= np.expm1(-graph_neg * scale) else: T += np.expm1(graph_neg * scale) T.data += 1 # weight direct and indirect (recursed) neighbors if 'neighbors' in adata.uns.keys() and weight_indirect_neighbors is not None and weight_indirect_neighbors < 1: direct_neighbors = adata.uns['neighbors']['distances'] > 0 direct_neighbors.setdiag(1) w = weight_indirect_neighbors T = w * T + (1-w) * direct_neighbors.multiply(T) if backward: T = T.T T = normalize(T) if n_neighbors is not None: T = T.multiply(get_connectivities(adata, mode='distances', n_neighbors=n_neighbors, recurse_neighbors=True)) if perc is not None: threshold = np.percentile(T.data, perc) T.data[T.data < threshold] = 0 T.eliminate_zeros() if 'X_' + str(basis) in adata.obsm.keys(): dists_emb = (T > 0).multiply(squareform(pdist(adata.obsm['X_' + basis]))) scale_diffusion *= dists_emb.data.mean() diffusion_kernel = dists_emb.copy() diffusion_kernel.data = np.exp(-.5 * dists_emb.data ** 2 / scale_diffusion ** 2) T = T.multiply(diffusion_kernel) # combine velocity based kernel with diffusion based kernel if 0 < weight_diffusion < 1: # add another diffusion kernel (Brownian motion - like) diffusion_kernel.data = np.exp(-.5 * dists_emb.data ** 2 / (scale_diffusion/2) ** 2) T = (1-weight_diffusion) * T + weight_diffusion * diffusion_kernel T = normalize(T) return T
[ "def", "transition_matrix", "(", "adata", ",", "vkey", "=", "'velocity'", ",", "basis", "=", "None", ",", "backward", "=", "False", ",", "self_transitions", "=", "True", ",", "scale", "=", "10", ",", "perc", "=", "None", ",", "use_negative_cosines", "=", ...
Computes transition probabilities from velocity graph Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name of velocity estimates to be used. basis: `str` or `None` (default: `None`) Restrict transition to embedding if specified backward: `bool` (default: `False`) Whether to use the transition matrix to push forward (`False`) or to pull backward (`True`) scale: `float` (default: 10) Scale parameter of gaussian kernel. weight_diffusion: `float` (default: 0) Relative weight to be given to diffusion kernel (Brownian motion) scale_diffusion: `float` (default: 1) Scale of diffusion kernel. Returns ------- Returns sparse matrix with transition probabilities.
[ "Computes", "transition", "probabilities", "from", "velocity", "graph" ]
c7a96d70edfe705e86bf364434a9527d4fd8df11
https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/tools/transition_matrix.py#L9-L87
24,419
rochars/trade
trade/context.py
Context.apply
def apply(self): """Apply the rules of the context to its occurrences. This method executes all the functions defined in self.tasks in the order they are listed. Every function that acts as a context task receives the Context object itself as its only argument. The contextualized occurrences are then stored in Context.contextualized. The original Occurrence instances are not modified. """ raw_operations = copy.deepcopy(self.occurrences) for task in self.tasks: task(self) self.occurrences = raw_operations
python
def apply(self): raw_operations = copy.deepcopy(self.occurrences) for task in self.tasks: task(self) self.occurrences = raw_operations
[ "def", "apply", "(", "self", ")", ":", "raw_operations", "=", "copy", ".", "deepcopy", "(", "self", ".", "occurrences", ")", "for", "task", "in", "self", ".", "tasks", ":", "task", "(", "self", ")", "self", ".", "occurrences", "=", "raw_operations" ]
Apply the rules of the context to its occurrences. This method executes all the functions defined in self.tasks in the order they are listed. Every function that acts as a context task receives the Context object itself as its only argument. The contextualized occurrences are then stored in Context.contextualized. The original Occurrence instances are not modified.
[ "Apply", "the", "rules", "of", "the", "context", "to", "its", "occurrences", "." ]
3b8d386e1394923919b7dc7a30dc93441558d5bc
https://github.com/rochars/trade/blob/3b8d386e1394923919b7dc7a30dc93441558d5bc/trade/context.py#L70-L87
24,420
rochars/trade
trade/occurrence.py
average_price
def average_price(quantity_1, price_1, quantity_2, price_2): """Calculates the average price between two asset states.""" return (quantity_1 * price_1 + quantity_2 * price_2) / \ (quantity_1 + quantity_2)
python
def average_price(quantity_1, price_1, quantity_2, price_2): return (quantity_1 * price_1 + quantity_2 * price_2) / \ (quantity_1 + quantity_2)
[ "def", "average_price", "(", "quantity_1", ",", "price_1", ",", "quantity_2", ",", "price_2", ")", ":", "return", "(", "quantity_1", "*", "price_1", "+", "quantity_2", "*", "price_2", ")", "/", "(", "quantity_1", "+", "quantity_2", ")" ]
Calculates the average price between two asset states.
[ "Calculates", "the", "average", "price", "between", "two", "asset", "states", "." ]
3b8d386e1394923919b7dc7a30dc93441558d5bc
https://github.com/rochars/trade/blob/3b8d386e1394923919b7dc7a30dc93441558d5bc/trade/occurrence.py#L134-L137
24,421
rochars/trade
trade/occurrence.py
Occurrence.update_holder
def update_holder(self, holder): """Udpate the Holder state according to the occurrence. This implementation is a example of how a Occurrence object can update the Holder state; this method should be overriden by classes that inherit from the Occurrence class. This sample implementation simply update the quantity and the average price of the Subject in the Holder's possession every time objects from this class are passed to Holder.trade(). This sample implementation considers the following signature for the Holder.state dict: .. code:: python { "SUBJECT SYMBOL": { "quantity": 0, "value": 0 } } And the following signature for the Occurrance.details dict: .. code:: python { "quantity": 0, "value": 0 } """ subject_symbol = self.subject.symbol # If the Holder already have a state regarding this Subject, # update that state if subject_symbol in holder.state: # If the Holder have zero units of this subject, the average # value paid/received for the subject is the value of the trade itself if not holder.state[subject_symbol]['quantity']: holder.state[subject_symbol]['value'] = self.details['value'] # If the Holder owns units of this subject then the average value # paid/received for the subject may need to be updated with # this occurrence details # If the occurrence have the same sign as the quantity in the Holder # state, a new average value needs to be calculated for the subject elif same_sign( holder.state[subject_symbol]['quantity'], self.details['quantity']): holder.state[subject_symbol]['value'] = average_price( holder.state[subject_symbol]['quantity'], holder.state[subject_symbol]['value'], self.details['quantity'], self.details['value'] ) # If the occurrence does not have the same sign of the quantity in the # Holder state, then do other stuff. # A trade app would normally implement some sort of profit/loss logic # here. # This sample implementation only checks if the average value # of the subject needs to be updated and then update it as needed. else: if same_sign( self.details['quantity'], holder.state[subject_symbol]['quantity'] + self.details['quantity']): holder.state[subject_symbol]['value'] = self.details['value'] # Update the quantity of the subject in the Holder's posession holder.state[subject_symbol]['quantity'] += self.details['quantity'] # If the Holder don't have a state with this occurrence's Subject, # then register this occurrence as the first state of the Subject # in the Holder's possession else: holder.state[subject_symbol] = { 'quantity': self.details['quantity'], 'value': self.details['value'] } # If the Holder knows about this Subject but don't have any unit # of it, the paid value of the subject in the Holder state should # be zero. if not holder.state[subject_symbol]['quantity']: holder.state[subject_symbol]['value'] = 0
python
def update_holder(self, holder): subject_symbol = self.subject.symbol # If the Holder already have a state regarding this Subject, # update that state if subject_symbol in holder.state: # If the Holder have zero units of this subject, the average # value paid/received for the subject is the value of the trade itself if not holder.state[subject_symbol]['quantity']: holder.state[subject_symbol]['value'] = self.details['value'] # If the Holder owns units of this subject then the average value # paid/received for the subject may need to be updated with # this occurrence details # If the occurrence have the same sign as the quantity in the Holder # state, a new average value needs to be calculated for the subject elif same_sign( holder.state[subject_symbol]['quantity'], self.details['quantity']): holder.state[subject_symbol]['value'] = average_price( holder.state[subject_symbol]['quantity'], holder.state[subject_symbol]['value'], self.details['quantity'], self.details['value'] ) # If the occurrence does not have the same sign of the quantity in the # Holder state, then do other stuff. # A trade app would normally implement some sort of profit/loss logic # here. # This sample implementation only checks if the average value # of the subject needs to be updated and then update it as needed. else: if same_sign( self.details['quantity'], holder.state[subject_symbol]['quantity'] + self.details['quantity']): holder.state[subject_symbol]['value'] = self.details['value'] # Update the quantity of the subject in the Holder's posession holder.state[subject_symbol]['quantity'] += self.details['quantity'] # If the Holder don't have a state with this occurrence's Subject, # then register this occurrence as the first state of the Subject # in the Holder's possession else: holder.state[subject_symbol] = { 'quantity': self.details['quantity'], 'value': self.details['value'] } # If the Holder knows about this Subject but don't have any unit # of it, the paid value of the subject in the Holder state should # be zero. if not holder.state[subject_symbol]['quantity']: holder.state[subject_symbol]['value'] = 0
[ "def", "update_holder", "(", "self", ",", "holder", ")", ":", "subject_symbol", "=", "self", ".", "subject", ".", "symbol", "# If the Holder already have a state regarding this Subject,", "# update that state", "if", "subject_symbol", "in", "holder", ".", "state", ":", ...
Udpate the Holder state according to the occurrence. This implementation is a example of how a Occurrence object can update the Holder state; this method should be overriden by classes that inherit from the Occurrence class. This sample implementation simply update the quantity and the average price of the Subject in the Holder's possession every time objects from this class are passed to Holder.trade(). This sample implementation considers the following signature for the Holder.state dict: .. code:: python { "SUBJECT SYMBOL": { "quantity": 0, "value": 0 } } And the following signature for the Occurrance.details dict: .. code:: python { "quantity": 0, "value": 0 }
[ "Udpate", "the", "Holder", "state", "according", "to", "the", "occurrence", "." ]
3b8d386e1394923919b7dc7a30dc93441558d5bc
https://github.com/rochars/trade/blob/3b8d386e1394923919b7dc7a30dc93441558d5bc/trade/occurrence.py#L44-L132
24,422
casacore/python-casacore
casacore/fitting/fitting.py
fitserver.fitter
def fitter(self, n=0, ftype="real", colfac=1.0e-8, lmfac=1.0e-3): """Create a sub-fitter. The created sub-fitter can be used in the same way as a fitter default fitter. This function returns an identification, which has to be used in the `fid` argument of subsequent calls. The call can specify the standard constructor arguments (`n`, `type`, `colfac`, `lmfac`), or can specify them later in a :meth:`set` statement. :param n: number of unknowns :param ftype: type of solution Allowed: real, complex, separable, asreal, conjugate :param colfac: collinearity factor :param lmfac: Levenberg-Marquardt factor :param fid: the id of a sub-fitter """ fid = self._fitproxy.getid() ftype = self._gettype(ftype) n = len(self._fitids) if 0 <= fid < n: self._fitids[fid] = {} elif fid == n: self._fitids.append({}) else: # shouldn't happen raise RangeError("fit id out of range") self.init(n=n, ftype=ftype, colfac=colfac, lmfac=lmfac, fid=fid) return fid
python
def fitter(self, n=0, ftype="real", colfac=1.0e-8, lmfac=1.0e-3): fid = self._fitproxy.getid() ftype = self._gettype(ftype) n = len(self._fitids) if 0 <= fid < n: self._fitids[fid] = {} elif fid == n: self._fitids.append({}) else: # shouldn't happen raise RangeError("fit id out of range") self.init(n=n, ftype=ftype, colfac=colfac, lmfac=lmfac, fid=fid) return fid
[ "def", "fitter", "(", "self", ",", "n", "=", "0", ",", "ftype", "=", "\"real\"", ",", "colfac", "=", "1.0e-8", ",", "lmfac", "=", "1.0e-3", ")", ":", "fid", "=", "self", ".", "_fitproxy", ".", "getid", "(", ")", "ftype", "=", "self", ".", "_getty...
Create a sub-fitter. The created sub-fitter can be used in the same way as a fitter default fitter. This function returns an identification, which has to be used in the `fid` argument of subsequent calls. The call can specify the standard constructor arguments (`n`, `type`, `colfac`, `lmfac`), or can specify them later in a :meth:`set` statement. :param n: number of unknowns :param ftype: type of solution Allowed: real, complex, separable, asreal, conjugate :param colfac: collinearity factor :param lmfac: Levenberg-Marquardt factor :param fid: the id of a sub-fitter
[ "Create", "a", "sub", "-", "fitter", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/fitting/fitting.py#L46-L74
24,423
casacore/python-casacore
casacore/fitting/fitting.py
fitserver.done
def done(self, fid=0): """Terminates the fitserver.""" self._checkid(fid) self._fitids[fid] = {} self._fitproxy.done(fid)
python
def done(self, fid=0): self._checkid(fid) self._fitids[fid] = {} self._fitproxy.done(fid)
[ "def", "done", "(", "self", ",", "fid", "=", "0", ")", ":", "self", ".", "_checkid", "(", "fid", ")", "self", ".", "_fitids", "[", "fid", "]", "=", "{", "}", "self", ".", "_fitproxy", ".", "done", "(", "fid", ")" ]
Terminates the fitserver.
[ "Terminates", "the", "fitserver", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/fitting/fitting.py#L183-L187
24,424
casacore/python-casacore
casacore/fitting/fitting.py
fitserver.reset
def reset(self, fid=0): """Reset the object's resources to its initialized state. :param fid: the id of a sub-fitter """ self._checkid(fid) self._fitids[fid]["solved"] = False self._fitids[fid]["haserr"] = False if not self._fitids[fid]["looped"]: return self._fitproxy.reset(fid) else: self._fitids[fid]["looped"] = False return True
python
def reset(self, fid=0): self._checkid(fid) self._fitids[fid]["solved"] = False self._fitids[fid]["haserr"] = False if not self._fitids[fid]["looped"]: return self._fitproxy.reset(fid) else: self._fitids[fid]["looped"] = False return True
[ "def", "reset", "(", "self", ",", "fid", "=", "0", ")", ":", "self", ".", "_checkid", "(", "fid", ")", "self", ".", "_fitids", "[", "fid", "]", "[", "\"solved\"", "]", "=", "False", "self", ".", "_fitids", "[", "fid", "]", "[", "\"haserr\"", "]",...
Reset the object's resources to its initialized state. :param fid: the id of a sub-fitter
[ "Reset", "the", "object", "s", "resources", "to", "its", "initialized", "state", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/fitting/fitting.py#L189-L201
24,425
casacore/python-casacore
casacore/fitting/fitting.py
fitserver.addconstraint
def addconstraint(self, x, y=0, fnct=None, fid=0): """Add constraint.""" self._checkid(fid) i = 0 if "constraint" in self._fitids[fid]: i = len(self._fitids[fid]["constraint"]) else: self._fitids[fid]["constraint"] = {} # dict key needs to be string i = str(i) self._fitids[fid]["constraint"][i] = {} if isinstance(fnct, functional): self._fitids[fid]["constraint"][i]["fnct"] = fnct.todict() else: self._fitids[fid]["constraint"][i]["fnct"] = \ functional("hyper", len(x)).todict() self._fitids[fid]["constraint"][i]["x"] = [float(v) for v in x] self._fitids[fid]["constraint"][i]["y"] = float(y) six.print_(self._fitids[fid]["constraint"])
python
def addconstraint(self, x, y=0, fnct=None, fid=0): self._checkid(fid) i = 0 if "constraint" in self._fitids[fid]: i = len(self._fitids[fid]["constraint"]) else: self._fitids[fid]["constraint"] = {} # dict key needs to be string i = str(i) self._fitids[fid]["constraint"][i] = {} if isinstance(fnct, functional): self._fitids[fid]["constraint"][i]["fnct"] = fnct.todict() else: self._fitids[fid]["constraint"][i]["fnct"] = \ functional("hyper", len(x)).todict() self._fitids[fid]["constraint"][i]["x"] = [float(v) for v in x] self._fitids[fid]["constraint"][i]["y"] = float(y) six.print_(self._fitids[fid]["constraint"])
[ "def", "addconstraint", "(", "self", ",", "x", ",", "y", "=", "0", ",", "fnct", "=", "None", ",", "fid", "=", "0", ")", ":", "self", ".", "_checkid", "(", "fid", ")", "i", "=", "0", "if", "\"constraint\"", "in", "self", ".", "_fitids", "[", "fi...
Add constraint.
[ "Add", "constraint", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/fitting/fitting.py#L216-L234
24,426
casacore/python-casacore
casacore/fitting/fitting.py
fitserver.fitspoly
def fitspoly(self, n, x, y, sd=None, wt=1.0, fid=0): """Create normal equations from the specified condition equations, and solve the resulting normal equations. It is in essence a combination. The method expects that the properties of the fitter to be used have been initialized or set (like the number of simultaneous solutions m the type; factors). The main reason is to limit the number of parameters on the one hand, and on the other hand not to depend on the actual array structure to get the variables and type. Before fitting the x-range is normalized to values less than 1 to cater for large difference in x raised to large powers. Later a shift to make x around zero will be added as well. :param n: the order of the polynomial to solve for :param x: the abscissa values :param y: the ordinate values :param sd: standard deviation of equations (one or more values used cyclically) :param wt: an optional alternate for `sd` :param fid: the id of the sub-fitter (numerical) Example:: fit = fitserver() x = N.arange(1,11) # we have values at 10 'x' values y = 2. + 0.5*x - 0.1*x**2 # which are 2 +0.5x -0.1x^2 fit.fitspoly(3, x, y) # fit a 3-degree polynomial print fit.solution(), fit.error() # show solution and their errors """ a = max(abs(max(x)), abs(min(x))) if a == 0: a = 1 a = 1.0 / a b = NUM.power(a, range(n + 1)) if self.set(n=n + 1, fid=fid): self.linear(poly(n), x * a, y, sd, wt, fid) self._fitids[fid]["sol"] *= b self._fitids[fid]["error"] *= b return self.linear(poly(n), x, y, sd, wt, fid)
python
def fitspoly(self, n, x, y, sd=None, wt=1.0, fid=0): a = max(abs(max(x)), abs(min(x))) if a == 0: a = 1 a = 1.0 / a b = NUM.power(a, range(n + 1)) if self.set(n=n + 1, fid=fid): self.linear(poly(n), x * a, y, sd, wt, fid) self._fitids[fid]["sol"] *= b self._fitids[fid]["error"] *= b return self.linear(poly(n), x, y, sd, wt, fid)
[ "def", "fitspoly", "(", "self", ",", "n", ",", "x", ",", "y", ",", "sd", "=", "None", ",", "wt", "=", "1.0", ",", "fid", "=", "0", ")", ":", "a", "=", "max", "(", "abs", "(", "max", "(", "x", ")", ")", ",", "abs", "(", "min", "(", "x", ...
Create normal equations from the specified condition equations, and solve the resulting normal equations. It is in essence a combination. The method expects that the properties of the fitter to be used have been initialized or set (like the number of simultaneous solutions m the type; factors). The main reason is to limit the number of parameters on the one hand, and on the other hand not to depend on the actual array structure to get the variables and type. Before fitting the x-range is normalized to values less than 1 to cater for large difference in x raised to large powers. Later a shift to make x around zero will be added as well. :param n: the order of the polynomial to solve for :param x: the abscissa values :param y: the ordinate values :param sd: standard deviation of equations (one or more values used cyclically) :param wt: an optional alternate for `sd` :param fid: the id of the sub-fitter (numerical) Example:: fit = fitserver() x = N.arange(1,11) # we have values at 10 'x' values y = 2. + 0.5*x - 0.1*x**2 # which are 2 +0.5x -0.1x^2 fit.fitspoly(3, x, y) # fit a 3-degree polynomial print fit.solution(), fit.error() # show solution and their errors
[ "Create", "normal", "equations", "from", "the", "specified", "condition", "equations", "and", "solve", "the", "resulting", "normal", "equations", ".", "It", "is", "in", "essence", "a", "combination", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/fitting/fitting.py#L240-L279
24,427
casacore/python-casacore
casacore/fitting/fitting.py
fitserver.functional
def functional(self, fnct, x, y, sd=None, wt=1.0, mxit=50, fid=0): """Make a non-linear least squares solution. This will make a non-linear least squares solution for the points through the ordinates at the abscissa values, using the specified `fnct`. Details can be found in the :meth:`linear` description. :param fnct: the functional to fit :param x: the abscissa values :param y: the ordinate values :param sd: standard deviation of equations (one or more values used cyclically) :param wt: an optional alternate for `sd` :param mxit: the maximum number of iterations :param fid: the id of the sub-fitter (numerical) """ self._fit(fitfunc="functional", fnct=fnct, x=x, y=y, sd=sd, wt=wt, mxit=mxit, fid=fid)
python
def functional(self, fnct, x, y, sd=None, wt=1.0, mxit=50, fid=0): self._fit(fitfunc="functional", fnct=fnct, x=x, y=y, sd=sd, wt=wt, mxit=mxit, fid=fid)
[ "def", "functional", "(", "self", ",", "fnct", ",", "x", ",", "y", ",", "sd", "=", "None", ",", "wt", "=", "1.0", ",", "mxit", "=", "50", ",", "fid", "=", "0", ")", ":", "self", ".", "_fit", "(", "fitfunc", "=", "\"functional\"", ",", "fnct", ...
Make a non-linear least squares solution. This will make a non-linear least squares solution for the points through the ordinates at the abscissa values, using the specified `fnct`. Details can be found in the :meth:`linear` description. :param fnct: the functional to fit :param x: the abscissa values :param y: the ordinate values :param sd: standard deviation of equations (one or more values used cyclically) :param wt: an optional alternate for `sd` :param mxit: the maximum number of iterations :param fid: the id of the sub-fitter (numerical)
[ "Make", "a", "non", "-", "linear", "least", "squares", "solution", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/fitting/fitting.py#L333-L351
24,428
casacore/python-casacore
casacore/fitting/fitting.py
fitserver.linear
def linear(self, fnct, x, y, sd=None, wt=1.0, fid=0): """Make a linear least squares solution. Makes a linear least squares solution for the points through the ordinates at the x values, using the specified fnct. The x can be of any dimension, depending on the number of arguments needed in the functional evaluation. The values should be given in the order: x0[1], x0[2], ..., x1[1], ..., xn[m] if there are n observations, and m arguments. x should be a vector of m*n length; y (the observations) a vector of length n. :param fnct: the functional to fit :param x: the abscissa values :param y: the ordinate values :param sd: standard deviation of equations (one or more values used cyclically) :param wt: an optional alternate for `sd` :param fid: the id of the sub-fitter (numerical) """ self._fit(fitfunc="linear", fnct=fnct, x=x, y=y, sd=sd, wt=wt, fid=fid)
python
def linear(self, fnct, x, y, sd=None, wt=1.0, fid=0): self._fit(fitfunc="linear", fnct=fnct, x=x, y=y, sd=sd, wt=wt, fid=fid)
[ "def", "linear", "(", "self", ",", "fnct", ",", "x", ",", "y", ",", "sd", "=", "None", ",", "wt", "=", "1.0", ",", "fid", "=", "0", ")", ":", "self", ".", "_fit", "(", "fitfunc", "=", "\"linear\"", ",", "fnct", "=", "fnct", ",", "x", "=", "...
Make a linear least squares solution. Makes a linear least squares solution for the points through the ordinates at the x values, using the specified fnct. The x can be of any dimension, depending on the number of arguments needed in the functional evaluation. The values should be given in the order: x0[1], x0[2], ..., x1[1], ..., xn[m] if there are n observations, and m arguments. x should be a vector of m*n length; y (the observations) a vector of length n. :param fnct: the functional to fit :param x: the abscissa values :param y: the ordinate values :param sd: standard deviation of equations (one or more values used cyclically) :param wt: an optional alternate for `sd` :param fid: the id of the sub-fitter (numerical)
[ "Make", "a", "linear", "least", "squares", "solution", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/fitting/fitting.py#L355-L375
24,429
casacore/python-casacore
casacore/fitting/fitting.py
fitserver.constraint
def constraint(self, n=-1, fid=0): """Obtain the set of orthogonal equations that make the solution of the rank deficient normal equations possible. :param fid: the id of the sub-fitter (numerical) """ c = self._getval("constr", fid) if n < 0 or n > self.deficiency(fid): return c else: raise RuntimeError("Not yet implemented")
python
def constraint(self, n=-1, fid=0): c = self._getval("constr", fid) if n < 0 or n > self.deficiency(fid): return c else: raise RuntimeError("Not yet implemented")
[ "def", "constraint", "(", "self", ",", "n", "=", "-", "1", ",", "fid", "=", "0", ")", ":", "c", "=", "self", ".", "_getval", "(", "\"constr\"", ",", "fid", ")", "if", "n", "<", "0", "or", "n", ">", "self", ".", "deficiency", "(", "fid", ")", ...
Obtain the set of orthogonal equations that make the solution of the rank deficient normal equations possible. :param fid: the id of the sub-fitter (numerical)
[ "Obtain", "the", "set", "of", "orthogonal", "equations", "that", "make", "the", "solution", "of", "the", "rank", "deficient", "normal", "equations", "possible", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/fitting/fitting.py#L457-L468
24,430
casacore/python-casacore
casacore/fitting/fitting.py
fitserver.fitted
def fitted(self, fid=0): """Test if enough Levenberg-Marquardt loops have been done. It returns True if no improvement possible. :param fid: the id of the sub-fitter (numerical) """ self._checkid(fid) return not (self._fitids[fid]["fit"] > 0 or self._fitids[fid]["fit"] < -0.001)
python
def fitted(self, fid=0): self._checkid(fid) return not (self._fitids[fid]["fit"] > 0 or self._fitids[fid]["fit"] < -0.001)
[ "def", "fitted", "(", "self", ",", "fid", "=", "0", ")", ":", "self", ".", "_checkid", "(", "fid", ")", "return", "not", "(", "self", ".", "_fitids", "[", "fid", "]", "[", "\"fit\"", "]", ">", "0", "or", "self", ".", "_fitids", "[", "fid", "]",...
Test if enough Levenberg-Marquardt loops have been done. It returns True if no improvement possible. :param fid: the id of the sub-fitter (numerical)
[ "Test", "if", "enough", "Levenberg", "-", "Marquardt", "loops", "have", "been", "done", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/fitting/fitting.py#L470-L479
24,431
casacore/python-casacore
casacore/measures/__init__.py
measures.set_data_path
def set_data_path(self, pth): """Set the location of the measures data directory. :param pth: The absolute path to the measures data directory. """ if os.path.exists(pth): if not os.path.exists(os.path.join(pth, 'data', 'geodetic')): raise IOError("The given path doesn't contain a 'data' " "subdirectory") os.environ["AIPSPATH"] = "%s dummy dummy" % pth
python
def set_data_path(self, pth): if os.path.exists(pth): if not os.path.exists(os.path.join(pth, 'data', 'geodetic')): raise IOError("The given path doesn't contain a 'data' " "subdirectory") os.environ["AIPSPATH"] = "%s dummy dummy" % pth
[ "def", "set_data_path", "(", "self", ",", "pth", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "pth", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "pth", ",", "'data'", ",", "'geode...
Set the location of the measures data directory. :param pth: The absolute path to the measures data directory.
[ "Set", "the", "location", "of", "the", "measures", "data", "directory", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/measures/__init__.py#L91-L100
24,432
casacore/python-casacore
casacore/measures/__init__.py
measures.asbaseline
def asbaseline(self, pos): """Convert a position measure into a baseline measure. No actual baseline is calculated, since operations can be done on positions, with subtractions to obtain baselines at a later stage. :param pos: a position measure :returns: a baseline measure """ if not is_measure(pos) or pos['type'] not in ['position', 'baseline']: raise TypeError('Argument is not a position/baseline measure') if pos['type'] == 'position': loc = self.measure(pos, 'itrf') loc['type'] = 'baseline' return self.measure(loc, 'j2000') return pos
python
def asbaseline(self, pos): if not is_measure(pos) or pos['type'] not in ['position', 'baseline']: raise TypeError('Argument is not a position/baseline measure') if pos['type'] == 'position': loc = self.measure(pos, 'itrf') loc['type'] = 'baseline' return self.measure(loc, 'j2000') return pos
[ "def", "asbaseline", "(", "self", ",", "pos", ")", ":", "if", "not", "is_measure", "(", "pos", ")", "or", "pos", "[", "'type'", "]", "not", "in", "[", "'position'", ",", "'baseline'", "]", ":", "raise", "TypeError", "(", "'Argument is not a position/baseli...
Convert a position measure into a baseline measure. No actual baseline is calculated, since operations can be done on positions, with subtractions to obtain baselines at a later stage. :param pos: a position measure :returns: a baseline measure
[ "Convert", "a", "position", "measure", "into", "a", "baseline", "measure", ".", "No", "actual", "baseline", "is", "calculated", "since", "operations", "can", "be", "done", "on", "positions", "with", "subtractions", "to", "obtain", "baselines", "at", "a", "late...
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/measures/__init__.py#L599-L614
24,433
casacore/python-casacore
casacore/measures/__init__.py
measures.getvalue
def getvalue(self, v): """ Return a list of quantities making up the measures' value. :param v: a measure """ if not is_measure(v): raise TypeError('Incorrect input type for getvalue()') import re rx = re.compile("m\d+") out = [] keys = v.keys()[:] keys.sort() for key in keys: if re.match(rx, key): out.append(dq.quantity(v.get(key))) return out
python
def getvalue(self, v): if not is_measure(v): raise TypeError('Incorrect input type for getvalue()') import re rx = re.compile("m\d+") out = [] keys = v.keys()[:] keys.sort() for key in keys: if re.match(rx, key): out.append(dq.quantity(v.get(key))) return out
[ "def", "getvalue", "(", "self", ",", "v", ")", ":", "if", "not", "is_measure", "(", "v", ")", ":", "raise", "TypeError", "(", "'Incorrect input type for getvalue()'", ")", "import", "re", "rx", "=", "re", ".", "compile", "(", "\"m\\d+\"", ")", "out", "="...
Return a list of quantities making up the measures' value. :param v: a measure
[ "Return", "a", "list", "of", "quantities", "making", "up", "the", "measures", "value", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/measures/__init__.py#L618-L634
24,434
casacore/python-casacore
casacore/measures/__init__.py
measures.doframe
def doframe(self, v): """This method will set the measure specified as part of a frame. If conversion from one type to another is necessary (with the measure function), the following frames should be set if one of the reference types involved in the conversion is as in the following lists: **Epoch** * UTC * TAI * LAST - position * LMST - position * GMST1 * GAST * UT1 * UT2 * TDT * TCG * TDB * TCD **Direction** * J2000 * JMEAN - epoch * JTRUE - epoch * APP - epoch * B1950 * BMEAN - epoch * BTRUE - epoch * GALACTIC * HADEC - epoch, position * AZEL - epoch, position * SUPERGALACTIC * ECLIPTIC * MECLIPTIC - epoch * TECLIPTIC - epoch * PLANET - epoch, [position] **Position** * WGS84 * ITRF **Radial Velocity** * LSRK - direction * LSRD - direction * BARY - direction * GEO - direction, epoch * TOPO - direction, epoch, position * GALACTO - direction * **Doppler** * RADIO * OPTICAL * Z * RATIO * RELATIVISTIC * BETA * GAMMA * **Frequency** * REST - direction, radialvelocity * LSRK - direction * LSRD - direction * BARY - direction * GEO - direction, epoch * TOPO - direction, epoch, position * GALACTO """ if not is_measure(v): raise TypeError('Argument is not a measure') if (v["type"] == "frequency" and v["refer"].lower() == "rest") \ or _measures.doframe(self, v): self._framestack[v["type"]] = v return True return False
python
def doframe(self, v): if not is_measure(v): raise TypeError('Argument is not a measure') if (v["type"] == "frequency" and v["refer"].lower() == "rest") \ or _measures.doframe(self, v): self._framestack[v["type"]] = v return True return False
[ "def", "doframe", "(", "self", ",", "v", ")", ":", "if", "not", "is_measure", "(", "v", ")", ":", "raise", "TypeError", "(", "'Argument is not a measure'", ")", "if", "(", "v", "[", "\"type\"", "]", "==", "\"frequency\"", "and", "v", "[", "\"refer\"", ...
This method will set the measure specified as part of a frame. If conversion from one type to another is necessary (with the measure function), the following frames should be set if one of the reference types involved in the conversion is as in the following lists: **Epoch** * UTC * TAI * LAST - position * LMST - position * GMST1 * GAST * UT1 * UT2 * TDT * TCG * TDB * TCD **Direction** * J2000 * JMEAN - epoch * JTRUE - epoch * APP - epoch * B1950 * BMEAN - epoch * BTRUE - epoch * GALACTIC * HADEC - epoch, position * AZEL - epoch, position * SUPERGALACTIC * ECLIPTIC * MECLIPTIC - epoch * TECLIPTIC - epoch * PLANET - epoch, [position] **Position** * WGS84 * ITRF **Radial Velocity** * LSRK - direction * LSRD - direction * BARY - direction * GEO - direction, epoch * TOPO - direction, epoch, position * GALACTO - direction * **Doppler** * RADIO * OPTICAL * Z * RATIO * RELATIVISTIC * BETA * GAMMA * **Frequency** * REST - direction, radialvelocity * LSRK - direction * LSRD - direction * BARY - direction * GEO - direction, epoch * TOPO - direction, epoch, position * GALACTO
[ "This", "method", "will", "set", "the", "measure", "specified", "as", "part", "of", "a", "frame", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/measures/__init__.py#L673-L756
24,435
casacore/python-casacore
casacore/tables/msutil.py
addImagingColumns
def addImagingColumns(msname, ack=True): """ Add the columns to an MS needed for the casa imager. It adds the columns MODEL_DATA, CORRECTED_DATA, and IMAGING_WEIGHT. It also sets the CHANNEL_SELECTION keyword needed for the older casa imagers. A column is not added if already existing. """ # numpy is needed import numpy as np # Open the MS t = table(msname, readonly=False, ack=False) cnames = t.colnames() # Get the description of the DATA column. try: cdesc = t.getcoldesc('DATA') except: raise ValueError('Column DATA does not exist') # Determine if the DATA storage specification is tiled. hasTiled = False try: dminfo = t.getdminfo("DATA") if dminfo['TYPE'][:5] == 'Tiled': hasTiled = True except: hasTiled = False # Use TiledShapeStMan if needed. if not hasTiled: dminfo = {'TYPE': 'TiledShapeStMan', 'SPEC': {'DEFAULTTILESHAPE': [4, 32, 128]}} # Add the columns(if not existing). Use the description of the DATA column. if 'MODEL_DATA' in cnames: six.print_("Column MODEL_DATA not added; it already exists") else: dminfo['NAME'] = 'modeldata' cdesc['comment'] = 'The model data column' t.addcols(maketabdesc(makecoldesc('MODEL_DATA', cdesc)), dminfo) if ack: six.print_("added column MODEL_DATA") if 'CORRECTED_DATA' in cnames: six.print_("Column CORRECTED_DATA not added; it already exists") else: dminfo['NAME'] = 'correcteddata' cdesc['comment'] = 'The corrected data column' t.addcols(maketabdesc(makecoldesc('CORRECTED_DATA', cdesc)), dminfo) if ack: six.print_("'added column CORRECTED_DATA") if 'IMAGING_WEIGHT' in cnames: six.print_("Column IMAGING_WEIGHT not added; it already exists") else: # Add IMAGING_WEIGHT which is 1-dim and has type float. # It needs a shape, otherwise the CASA imager complains. shp = [] if 'shape' in cdesc: shp = cdesc['shape'] if len(shp) > 0: shp = [shp[0]] # use nchan from shape else: shp = [t.getcell('DATA', 0).shape[0]] # use nchan from actual data cd = makearrcoldesc('IMAGING_WEIGHT', 0, ndim=1, shape=shp, valuetype='float') dminfo = {'TYPE': 'TiledShapeStMan', 'SPEC': {'DEFAULTTILESHAPE': [32, 128]}} dminfo['NAME'] = 'imagingweight' t.addcols(maketabdesc(cd), dminfo) if ack: six.print_("added column IMAGING_WEIGHT") # Add or overwrite keyword CHANNEL_SELECTION. if 'CHANNEL_SELECTION' in t.colkeywordnames('MODEL_DATA'): t.removecolkeyword('MODEL_DATA', 'CHANNEL_SELECTION') # Define the CHANNEL_SELECTION keyword containing the channels of # all spectral windows. tspw = table(t.getkeyword('SPECTRAL_WINDOW'), ack=False) nchans = tspw.getcol('NUM_CHAN') chans = [[0, nch] for nch in nchans] t.putcolkeyword('MODEL_DATA', 'CHANNEL_SELECTION', np.int32(chans)) if ack: six.print_("defined keyword CHANNEL_SELECTION in column MODEL_DATA") # Flush the table to make sure it is written. t.flush()
python
def addImagingColumns(msname, ack=True): # numpy is needed import numpy as np # Open the MS t = table(msname, readonly=False, ack=False) cnames = t.colnames() # Get the description of the DATA column. try: cdesc = t.getcoldesc('DATA') except: raise ValueError('Column DATA does not exist') # Determine if the DATA storage specification is tiled. hasTiled = False try: dminfo = t.getdminfo("DATA") if dminfo['TYPE'][:5] == 'Tiled': hasTiled = True except: hasTiled = False # Use TiledShapeStMan if needed. if not hasTiled: dminfo = {'TYPE': 'TiledShapeStMan', 'SPEC': {'DEFAULTTILESHAPE': [4, 32, 128]}} # Add the columns(if not existing). Use the description of the DATA column. if 'MODEL_DATA' in cnames: six.print_("Column MODEL_DATA not added; it already exists") else: dminfo['NAME'] = 'modeldata' cdesc['comment'] = 'The model data column' t.addcols(maketabdesc(makecoldesc('MODEL_DATA', cdesc)), dminfo) if ack: six.print_("added column MODEL_DATA") if 'CORRECTED_DATA' in cnames: six.print_("Column CORRECTED_DATA not added; it already exists") else: dminfo['NAME'] = 'correcteddata' cdesc['comment'] = 'The corrected data column' t.addcols(maketabdesc(makecoldesc('CORRECTED_DATA', cdesc)), dminfo) if ack: six.print_("'added column CORRECTED_DATA") if 'IMAGING_WEIGHT' in cnames: six.print_("Column IMAGING_WEIGHT not added; it already exists") else: # Add IMAGING_WEIGHT which is 1-dim and has type float. # It needs a shape, otherwise the CASA imager complains. shp = [] if 'shape' in cdesc: shp = cdesc['shape'] if len(shp) > 0: shp = [shp[0]] # use nchan from shape else: shp = [t.getcell('DATA', 0).shape[0]] # use nchan from actual data cd = makearrcoldesc('IMAGING_WEIGHT', 0, ndim=1, shape=shp, valuetype='float') dminfo = {'TYPE': 'TiledShapeStMan', 'SPEC': {'DEFAULTTILESHAPE': [32, 128]}} dminfo['NAME'] = 'imagingweight' t.addcols(maketabdesc(cd), dminfo) if ack: six.print_("added column IMAGING_WEIGHT") # Add or overwrite keyword CHANNEL_SELECTION. if 'CHANNEL_SELECTION' in t.colkeywordnames('MODEL_DATA'): t.removecolkeyword('MODEL_DATA', 'CHANNEL_SELECTION') # Define the CHANNEL_SELECTION keyword containing the channels of # all spectral windows. tspw = table(t.getkeyword('SPECTRAL_WINDOW'), ack=False) nchans = tspw.getcol('NUM_CHAN') chans = [[0, nch] for nch in nchans] t.putcolkeyword('MODEL_DATA', 'CHANNEL_SELECTION', np.int32(chans)) if ack: six.print_("defined keyword CHANNEL_SELECTION in column MODEL_DATA") # Flush the table to make sure it is written. t.flush()
[ "def", "addImagingColumns", "(", "msname", ",", "ack", "=", "True", ")", ":", "# numpy is needed", "import", "numpy", "as", "np", "# Open the MS", "t", "=", "table", "(", "msname", ",", "readonly", "=", "False", ",", "ack", "=", "False", ")", "cnames", "...
Add the columns to an MS needed for the casa imager. It adds the columns MODEL_DATA, CORRECTED_DATA, and IMAGING_WEIGHT. It also sets the CHANNEL_SELECTION keyword needed for the older casa imagers. A column is not added if already existing.
[ "Add", "the", "columns", "to", "an", "MS", "needed", "for", "the", "casa", "imager", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/msutil.py#L48-L128
24,436
casacore/python-casacore
casacore/tables/msutil.py
addDerivedMSCal
def addDerivedMSCal(msname): """ Add the derived columns like HA to an MS or CalTable. It adds the columns HA, HA1, HA2, PA1, PA2, LAST, LAST1, LAST2, AZEL1, AZEL2, and UVW_J2000. They are all bound to the DerivedMSCal virtual data manager. It fails if one of the columns already exists. """ # Open the MS t = table(msname, readonly=False, ack=False) colnames = t.colnames() # Check that the columns needed by DerivedMSCal are present. # Note that ANTENNA2 and FEED2 are not required. for col in ["TIME", "ANTENNA1", "FIELD_ID", "FEED1"]: if col not in colnames: raise ValueError("Columns " + colnames + " should be present in table " + msname) scols1 = ['HA', 'HA1', 'HA2', 'PA1', 'PA2'] scols2 = ['LAST', 'LAST1', 'LAST2'] acols1 = ['AZEL1', 'AZEL2'] acols2 = ['UVW_J2000'] descs = [] # Define the columns and their units. for col in scols1: descs.append(makescacoldesc(col, 0., keywords={"QuantumUnits": ["rad"]})) for col in scols2: descs.append(makescacoldesc(col, 0., keywords={"QuantumUnits": ["d"]})) for col in acols1: descs.append(makearrcoldesc(col, 0., keywords={"QuantumUnits": ["rad", "rad"]})) for col in acols2: descs.append(makearrcoldesc(col, 0., keywords={"QuantumUnits": ["m", "m", "m"], "MEASINFO": {"Ref": "J2000", "type": "uvw"}})) # Add all columns using DerivedMSCal as data manager. dminfo = {"TYPE": "DerivedMSCal", "NAME": "", "SPEC": {}} t.addcols(maketabdesc(descs), dminfo) # Flush the table to make sure it is written. t.flush()
python
def addDerivedMSCal(msname): # Open the MS t = table(msname, readonly=False, ack=False) colnames = t.colnames() # Check that the columns needed by DerivedMSCal are present. # Note that ANTENNA2 and FEED2 are not required. for col in ["TIME", "ANTENNA1", "FIELD_ID", "FEED1"]: if col not in colnames: raise ValueError("Columns " + colnames + " should be present in table " + msname) scols1 = ['HA', 'HA1', 'HA2', 'PA1', 'PA2'] scols2 = ['LAST', 'LAST1', 'LAST2'] acols1 = ['AZEL1', 'AZEL2'] acols2 = ['UVW_J2000'] descs = [] # Define the columns and their units. for col in scols1: descs.append(makescacoldesc(col, 0., keywords={"QuantumUnits": ["rad"]})) for col in scols2: descs.append(makescacoldesc(col, 0., keywords={"QuantumUnits": ["d"]})) for col in acols1: descs.append(makearrcoldesc(col, 0., keywords={"QuantumUnits": ["rad", "rad"]})) for col in acols2: descs.append(makearrcoldesc(col, 0., keywords={"QuantumUnits": ["m", "m", "m"], "MEASINFO": {"Ref": "J2000", "type": "uvw"}})) # Add all columns using DerivedMSCal as data manager. dminfo = {"TYPE": "DerivedMSCal", "NAME": "", "SPEC": {}} t.addcols(maketabdesc(descs), dminfo) # Flush the table to make sure it is written. t.flush()
[ "def", "addDerivedMSCal", "(", "msname", ")", ":", "# Open the MS", "t", "=", "table", "(", "msname", ",", "readonly", "=", "False", ",", "ack", "=", "False", ")", "colnames", "=", "t", ".", "colnames", "(", ")", "# Check that the columns needed by DerivedMSCa...
Add the derived columns like HA to an MS or CalTable. It adds the columns HA, HA1, HA2, PA1, PA2, LAST, LAST1, LAST2, AZEL1, AZEL2, and UVW_J2000. They are all bound to the DerivedMSCal virtual data manager. It fails if one of the columns already exists.
[ "Add", "the", "derived", "columns", "like", "HA", "to", "an", "MS", "or", "CalTable", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/msutil.py#L145-L189
24,437
casacore/python-casacore
casacore/tables/msutil.py
removeDerivedMSCal
def removeDerivedMSCal(msname): """ Remove the derived columns like HA from an MS or CalTable. It removes the columns using the data manager DerivedMSCal. Such columns are HA, HA1, HA2, PA1, PA2, LAST, LAST1, LAST2, AZEL1, AZEL2, and UVW_J2000. It fails if one of the columns already exists. """ # Open the MS t = table(msname, readonly=False, ack=False) # Remove the columns stored as DerivedMSCal. dmi = t.getdminfo() for x in dmi.values(): if x['TYPE'] == 'DerivedMSCal': t.removecols(x['COLUMNS']) t.flush()
python
def removeDerivedMSCal(msname): # Open the MS t = table(msname, readonly=False, ack=False) # Remove the columns stored as DerivedMSCal. dmi = t.getdminfo() for x in dmi.values(): if x['TYPE'] == 'DerivedMSCal': t.removecols(x['COLUMNS']) t.flush()
[ "def", "removeDerivedMSCal", "(", "msname", ")", ":", "# Open the MS", "t", "=", "table", "(", "msname", ",", "readonly", "=", "False", ",", "ack", "=", "False", ")", "# Remove the columns stored as DerivedMSCal.", "dmi", "=", "t", ".", "getdminfo", "(", ")", ...
Remove the derived columns like HA from an MS or CalTable. It removes the columns using the data manager DerivedMSCal. Such columns are HA, HA1, HA2, PA1, PA2, LAST, LAST1, LAST2, AZEL1, AZEL2, and UVW_J2000. It fails if one of the columns already exists.
[ "Remove", "the", "derived", "columns", "like", "HA", "from", "an", "MS", "or", "CalTable", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/msutil.py#L192-L210
24,438
casacore/python-casacore
casacore/tables/msutil.py
msregularize
def msregularize(msname, newname): """ Regularize an MS The output MS will be such that it has the same number of baselines for each time stamp. Where needed fully flagged rows are added. Possibly missing rows are written into a separate MS <newname>-add. It is concatenated with the original MS and sorted in order of TIME, DATADESC_ID, ANTENNA1,ANTENNA2 to form a new regular MS. Note that the new MS references the input MS (it does not copy the data). It means that changes made in the new MS are also made in the input MS. If no rows were missing, the new MS is still created referencing the input MS. """ # Find out all baselines. t = table(msname) t1 = t.sort('unique ANTENNA1,ANTENNA2') nadded = 0 # Now iterate in time,band over the MS. for tsub in t.iter(['TIME', 'DATA_DESC_ID']): nmissing = t1.nrows() - tsub.nrows() if nmissing < 0: raise ValueError("A time/band chunk has too many rows") if nmissing > 0: # Rows needs to be added for the missing baselines. ant1 = str(t1.getcol('ANTENNA1')).replace(' ', ',') ant2 = str(t1.getcol('ANTENNA2')).replace(' ', ',') ant1 = tsub.getcol('ANTENNA1') ant2 = tsub.getcol('ANTENNA2') t2 = taql('select from $t1 where !any(ANTENNA1 == $ant1 &&' + ' ANTENNA2 == $ant2)') six.print_(nmissing, t1.nrows(), tsub.nrows(), t2.nrows()) if t2.nrows() != nmissing: raise ValueError("A time/band chunk behaves strangely") # If nothing added yet, create a new table. # (which has to be reopened for read/write). # Otherwise append to that new table. if nadded == 0: tnew = t2.copy(newname + "_add", deep=True) tnew = table(newname + "_add", readonly=False) else: t2.copyrows(tnew) # Set the correct time and band in the new rows. tnew.putcell('TIME', range(nadded, nadded + nmissing), tsub.getcell('TIME', 0)) tnew.putcell('DATA_DESC_ID', range(nadded, nadded + nmissing), tsub.getcell('DATA_DESC_ID', 0)) nadded += nmissing # Combine the existing table and new table. if nadded > 0: # First initialize data and flags in the added rows. taql('update $tnew set DATA=0+0i') taql('update $tnew set FLAG=True') tcomb = table([t, tnew]) tcomb.rename(newname + '_adds') tcombs = tcomb.sort('TIME,DATA_DESC_ID,ANTENNA1,ANTENNA2') else: tcombs = t.query(offset=0) tcombs.rename(newname) six.print_(newname, 'has been created; it references the original MS') if nadded > 0: six.print_(' and', newname + '_adds', 'containing', nadded, 'new rows') else: six.print_(' no rows needed to be added')
python
def msregularize(msname, newname): # Find out all baselines. t = table(msname) t1 = t.sort('unique ANTENNA1,ANTENNA2') nadded = 0 # Now iterate in time,band over the MS. for tsub in t.iter(['TIME', 'DATA_DESC_ID']): nmissing = t1.nrows() - tsub.nrows() if nmissing < 0: raise ValueError("A time/band chunk has too many rows") if nmissing > 0: # Rows needs to be added for the missing baselines. ant1 = str(t1.getcol('ANTENNA1')).replace(' ', ',') ant2 = str(t1.getcol('ANTENNA2')).replace(' ', ',') ant1 = tsub.getcol('ANTENNA1') ant2 = tsub.getcol('ANTENNA2') t2 = taql('select from $t1 where !any(ANTENNA1 == $ant1 &&' + ' ANTENNA2 == $ant2)') six.print_(nmissing, t1.nrows(), tsub.nrows(), t2.nrows()) if t2.nrows() != nmissing: raise ValueError("A time/band chunk behaves strangely") # If nothing added yet, create a new table. # (which has to be reopened for read/write). # Otherwise append to that new table. if nadded == 0: tnew = t2.copy(newname + "_add", deep=True) tnew = table(newname + "_add", readonly=False) else: t2.copyrows(tnew) # Set the correct time and band in the new rows. tnew.putcell('TIME', range(nadded, nadded + nmissing), tsub.getcell('TIME', 0)) tnew.putcell('DATA_DESC_ID', range(nadded, nadded + nmissing), tsub.getcell('DATA_DESC_ID', 0)) nadded += nmissing # Combine the existing table and new table. if nadded > 0: # First initialize data and flags in the added rows. taql('update $tnew set DATA=0+0i') taql('update $tnew set FLAG=True') tcomb = table([t, tnew]) tcomb.rename(newname + '_adds') tcombs = tcomb.sort('TIME,DATA_DESC_ID,ANTENNA1,ANTENNA2') else: tcombs = t.query(offset=0) tcombs.rename(newname) six.print_(newname, 'has been created; it references the original MS') if nadded > 0: six.print_(' and', newname + '_adds', 'containing', nadded, 'new rows') else: six.print_(' no rows needed to be added')
[ "def", "msregularize", "(", "msname", ",", "newname", ")", ":", "# Find out all baselines.", "t", "=", "table", "(", "msname", ")", "t1", "=", "t", ".", "sort", "(", "'unique ANTENNA1,ANTENNA2'", ")", "nadded", "=", "0", "# Now iterate in time,band over the MS.", ...
Regularize an MS The output MS will be such that it has the same number of baselines for each time stamp. Where needed fully flagged rows are added. Possibly missing rows are written into a separate MS <newname>-add. It is concatenated with the original MS and sorted in order of TIME, DATADESC_ID, ANTENNA1,ANTENNA2 to form a new regular MS. Note that the new MS references the input MS (it does not copy the data). It means that changes made in the new MS are also made in the input MS. If no rows were missing, the new MS is still created referencing the input MS.
[ "Regularize", "an", "MS" ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/msutil.py#L362-L429
24,439
casacore/python-casacore
casacore/tables/tablecolumn.py
tablecolumn._repr_html_
def _repr_html_(self): """Give a nice representation of columns in notebooks.""" out="<table class='taqltable'>\n" # Print column name (not if it is auto-generated) if not(self.name()[:4]=="Col_"): out+="<tr>" out+="<th><b>"+self.name()+"</b></th>" out+="</tr>" cropped=False rowcount=0 colkeywords=self.getkeywords() for row in self: out +="\n<tr>" out += "<td>" + _format_cell(row, colkeywords) + "</td>\n" out += "</tr>\n" rowcount+=1 out+="\n" if rowcount>=20: cropped=True break if out[-2:]=="\n\n": out=out[:-1] out+="</table>" if cropped: out+="<p style='text-align:center'>("+str(self.nrows()-20)+" more rows)</p>\n" return out
python
def _repr_html_(self): out="<table class='taqltable'>\n" # Print column name (not if it is auto-generated) if not(self.name()[:4]=="Col_"): out+="<tr>" out+="<th><b>"+self.name()+"</b></th>" out+="</tr>" cropped=False rowcount=0 colkeywords=self.getkeywords() for row in self: out +="\n<tr>" out += "<td>" + _format_cell(row, colkeywords) + "</td>\n" out += "</tr>\n" rowcount+=1 out+="\n" if rowcount>=20: cropped=True break if out[-2:]=="\n\n": out=out[:-1] out+="</table>" if cropped: out+="<p style='text-align:center'>("+str(self.nrows()-20)+" more rows)</p>\n" return out
[ "def", "_repr_html_", "(", "self", ")", ":", "out", "=", "\"<table class='taqltable'>\\n\"", "# Print column name (not if it is auto-generated)", "if", "not", "(", "self", ".", "name", "(", ")", "[", ":", "4", "]", "==", "\"Col_\"", ")", ":", "out", "+=", "\"<...
Give a nice representation of columns in notebooks.
[ "Give", "a", "nice", "representation", "of", "columns", "in", "notebooks", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tablecolumn.py#L305-L336
24,440
casacore/python-casacore
casacore/images/coordinates.py
coordinatesystem._get_coordinatenames
def _get_coordinatenames(self): """Create ordered list of coordinate names """ validnames = ("direction", "spectral", "linear", "stokes", "tabular") self._names = [""] * len(validnames) n = 0 for key in self._csys.keys(): for name in validnames: if key.startswith(name): idx = int(key[len(name):]) self._names[idx] = name n += 1 # reverse as we are c order in python self._names = self._names[:n][::-1] if len(self._names) == 0: raise LookupError("Coordinate record doesn't contain valid coordinates")
python
def _get_coordinatenames(self): validnames = ("direction", "spectral", "linear", "stokes", "tabular") self._names = [""] * len(validnames) n = 0 for key in self._csys.keys(): for name in validnames: if key.startswith(name): idx = int(key[len(name):]) self._names[idx] = name n += 1 # reverse as we are c order in python self._names = self._names[:n][::-1] if len(self._names) == 0: raise LookupError("Coordinate record doesn't contain valid coordinates")
[ "def", "_get_coordinatenames", "(", "self", ")", ":", "validnames", "=", "(", "\"direction\"", ",", "\"spectral\"", ",", "\"linear\"", ",", "\"stokes\"", ",", "\"tabular\"", ")", "self", ".", "_names", "=", "[", "\"\"", "]", "*", "len", "(", "validnames", ...
Create ordered list of coordinate names
[ "Create", "ordered", "list", "of", "coordinate", "names" ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/coordinates.py#L71-L87
24,441
casacore/python-casacore
casacore/images/coordinates.py
directioncoordinate.set_projection
def set_projection(self, val): """Set the projection of the given axis in this coordinate. The known projections are SIN, ZEA, TAN, NCP, AIT, ZEA """ knownproj = ["SIN", "ZEA", "TAN", "NCP", "AIT", "ZEA"] # etc assert val.upper() in knownproj self._coord["projection"] = val.upper()
python
def set_projection(self, val): knownproj = ["SIN", "ZEA", "TAN", "NCP", "AIT", "ZEA"] # etc assert val.upper() in knownproj self._coord["projection"] = val.upper()
[ "def", "set_projection", "(", "self", ",", "val", ")", ":", "knownproj", "=", "[", "\"SIN\"", ",", "\"ZEA\"", ",", "\"TAN\"", ",", "\"NCP\"", ",", "\"AIT\"", ",", "\"ZEA\"", "]", "# etc", "assert", "val", ".", "upper", "(", ")", "in", "knownproj", "sel...
Set the projection of the given axis in this coordinate. The known projections are SIN, ZEA, TAN, NCP, AIT, ZEA
[ "Set", "the", "projection", "of", "the", "given", "axis", "in", "this", "coordinate", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/coordinates.py#L250-L257
24,442
casacore/python-casacore
casacore/tables/tableutil.py
tablefromascii
def tablefromascii(tablename, asciifile, headerfile='', autoheader=False, autoshape=[], columnnames=[], datatypes=[], sep=' ', commentmarker='', firstline=1, lastline=-1, readonly=True, lockoptions='default', ack=True): """Create a table from an ASCII file. Create a table from a file in ASCII format. Columnar data as well as table and column keywords may be specified. Once the table is created from the ASCII data, it is opened in the specified mode and a table object is returned. The table columns are filled from a file containing the data values separated by a separator (one line per table row). The default separator is a blank. Blanks before and after the separator are ignored. If a non-blank separator is used, values can be empty. Such values default to 0, empty string, or F depending on the data type. E.g. 1,,2, has 4 values of which the 2nd and 4th are empty and default to 0. Similarly if fewer values are given than needed, the missing values get the default value. Either the data format can be explicitly specified or it can be found automatically. The former gives more control in ambiguous situations. Both scalar and array columns can be generated from the ASCII input. The format string determines the type and optional shape. It is possible to give the column names and their data types in various ways: - Using 2 header lines (as described below) as the first two lines in the data file or in a separate header file. This is the default way. - Derive them automatically from the data (`autoheader=True`). - Using the arguments `columnnames` and `datatypes` (as non-empty vectors of strings). It implies (`autoheader=False`). The data types should be given in the same way as done in headers. In automatic mode (`autoheader=True`) the first line of the ASCII data is analyzed to deduce the data types. Only the types I, D, and A can be recognized. A number without decimal point or exponent is I (integer), otherwise it is D (double). Any other string is A (string). Note that a number may contain a leading sign (+ or -). The `autoshape` argument can be used to specify if the input should be stored as multiple scalars (the default) or as a single array. In the latter case one axis in the shape can be defined as variable length by giving it the value 0. It means that the actual array shape in a row is determined by the number of values in the corresponding input line. Columns get the names `Column1`, `Column2`, etc.. For example: 1. `autoshape=[]` (which is the default) means that all values are to be stored as scalar columns. 2. `autoshape=0` means that all values in a row are to be stored as a variable length vector. 3. `autoshape=10` defines a fixed length vector. If an input line contains less than 10 values, the vector is filled with default values. If more than 10 values, the latter values are ignored. 4. `autoshape=[5,0]` defines a 2-dim array of which the 2nd axis is variable. Note that if an input line does not contain a multiple of 5 values, the array is filled with default values. If the format of the table is explicitly specified, it has to be done either in the first two lines of the data file (named by the argument filename), or in a separate header file (named by the argument headerfile). In both forms, table keywords may also be specified before the column definitions. The column names and types can be described by two lines: 1. The first line contains the names of the columns. These names may be enclosed in quotes (either single or double). 2. The second line contains the data type and optionally the shape of each column. Valid types are: - S for Short data - I for Integer data - R for Real data - D for Double Precision data - X for Complex data (Real followed by Imaginary) - Z for Complex data (Amplitude then Phase) - DX for Double Precision Complex data (Real followed by Imaginary) - DZ for Double Precision Complex data (Amplitude then Phase) - A for ASCII data (a value must be enclosed in single or double quotes if it contains whitespace) - B for Boolean data (False are empty string, 0, or any string starting with F, f, N, or n). If a column is an array, the shape has to be given after the data type without any whitespace. E.g. `I10` defines an integer vector of length 10. `A2,5` defines a 2-dim string array with shape [2,5]. Note that `I` is not the same as `I1` as the first one defines a scalar and the other one a vector with length 1. The last column can have one variable length axis denoted by the value 0. It "consumes" the remainder of the input line. If the argument headerfile is set then the header information is read from that file instead of the first lines of the data file. To give a simple example of the form where the header information is located at the top of the data file:: COLI COLF COLD COLX COLZ COLS I R D X Z A 1 1.1 1.11 1.12 1.13 1.14 1.15 Str1 10 11 12 13 14 15 16 "" Note that a complex number consists of 2 numbers. Also note that an empty string can be given. Let us now give an example of a separate header file that one might use to get interferometer data into casacore:: U V W TIME ANT1 ANT2 DATA R R R D I I X1,0 The data file would then look like:: 124.011 54560.0 3477.1 43456789.0990 1 2 4.327 -0.1132 34561.0 45629.3 3900.5 43456789.0990 1 3 5.398 0.4521 Note that the DATA column is defined as a 2-dim array of 1 correlation and a variable number of channels, so the actual number of channels is determined by the input. In this example both rows will have 1 channel (note that a complex value contains 2 values). Tables may have keywords in addition to the columns. The keywords are useful for holding information that is global to the entire table (such as author, revision, history, etc.). The keywords in the header definitions must preceed the column descriptions. They must be enclosed between a line that starts with ".key..." and a line that starts with ".endkey..." (where ... can be anything). A table keywordset and column keywordsets can be specified. The latter can be specified by specifying the column name after the .keywords string. Between these two lines each line should contain the following: - The keyword name, e.g., ANYKEY - The datatype and optional shape of the keyword (cf. list of valid types above) - The value or values for the keyword (the keyword may contain a scalar or an array of values). e.g., 3.14159 21.78945 Thus to continue the example above, one might wish to add keywords as follows:: .keywords DATE A "97/1/16" REVISION D 2.01 AUTHOR A "Tim Cornwell" INSTRUMENT A "VLA" .endkeywords .keywords TIME UNIT A "s" .endkeywords U V W TIME ANT1 ANT2 DATA R R R D I I X1,0 Similarly to the column format string, the keyword formats can also contain shape information. The only difference is that if no shape is given, a keyword can have multiple values (making it a vector). It is possible to ignore comment lines in the header and data file by giving the `commentmarker`. It indicates that lines starting with the given marker are ignored. Note that the marker can be a regular expression (e.g. `' *//'` tells that lines starting with // and optionally preceeded by blanks have to be ignored). With the arguments `firstline` and `lastline` one can specify which lines have to be taken from the input file. A negative value means 1 for `firstline` or end-of-file for `lastline`. Note that if the headers and data are combined in one file, these line arguments apply to the whole file. If headers and data are in separate files, these line arguments apply to the data file only. Also note that ignored comment lines are counted, thus are used to determine which lines are in the line range. The number of rows is determined by the number of lines read from the data file. """ import os.path filename = os.path.expandvars(asciifile) filename = os.path.expanduser(filename) if not os.path.exists(filename): s = "File '%s' not found" % (filename) raise IOError(s) if headerfile != '': filename = os.path.expandvars(headerfile) filename = os.path.expanduser(filename) if not os.path.exists(filename): s = "File '%s' not found" % (filename) raise IOError(s) tab = table(asciifile, headerfile, tablename, autoheader, autoshape, sep, commentmarker, firstline, lastline, _columnnames=columnnames, _datatypes=datatypes, _oper=1) six.print_('Input format: [' + tab._getasciiformat() + ']') # Close table and reopen it in correct way. tab = 0 return table(tablename, readonly=readonly, lockoptions=lockoptions, ack=ack)
python
def tablefromascii(tablename, asciifile, headerfile='', autoheader=False, autoshape=[], columnnames=[], datatypes=[], sep=' ', commentmarker='', firstline=1, lastline=-1, readonly=True, lockoptions='default', ack=True): import os.path filename = os.path.expandvars(asciifile) filename = os.path.expanduser(filename) if not os.path.exists(filename): s = "File '%s' not found" % (filename) raise IOError(s) if headerfile != '': filename = os.path.expandvars(headerfile) filename = os.path.expanduser(filename) if not os.path.exists(filename): s = "File '%s' not found" % (filename) raise IOError(s) tab = table(asciifile, headerfile, tablename, autoheader, autoshape, sep, commentmarker, firstline, lastline, _columnnames=columnnames, _datatypes=datatypes, _oper=1) six.print_('Input format: [' + tab._getasciiformat() + ']') # Close table and reopen it in correct way. tab = 0 return table(tablename, readonly=readonly, lockoptions=lockoptions, ack=ack)
[ "def", "tablefromascii", "(", "tablename", ",", "asciifile", ",", "headerfile", "=", "''", ",", "autoheader", "=", "False", ",", "autoshape", "=", "[", "]", ",", "columnnames", "=", "[", "]", ",", "datatypes", "=", "[", "]", ",", "sep", "=", "' '", "...
Create a table from an ASCII file. Create a table from a file in ASCII format. Columnar data as well as table and column keywords may be specified. Once the table is created from the ASCII data, it is opened in the specified mode and a table object is returned. The table columns are filled from a file containing the data values separated by a separator (one line per table row). The default separator is a blank. Blanks before and after the separator are ignored. If a non-blank separator is used, values can be empty. Such values default to 0, empty string, or F depending on the data type. E.g. 1,,2, has 4 values of which the 2nd and 4th are empty and default to 0. Similarly if fewer values are given than needed, the missing values get the default value. Either the data format can be explicitly specified or it can be found automatically. The former gives more control in ambiguous situations. Both scalar and array columns can be generated from the ASCII input. The format string determines the type and optional shape. It is possible to give the column names and their data types in various ways: - Using 2 header lines (as described below) as the first two lines in the data file or in a separate header file. This is the default way. - Derive them automatically from the data (`autoheader=True`). - Using the arguments `columnnames` and `datatypes` (as non-empty vectors of strings). It implies (`autoheader=False`). The data types should be given in the same way as done in headers. In automatic mode (`autoheader=True`) the first line of the ASCII data is analyzed to deduce the data types. Only the types I, D, and A can be recognized. A number without decimal point or exponent is I (integer), otherwise it is D (double). Any other string is A (string). Note that a number may contain a leading sign (+ or -). The `autoshape` argument can be used to specify if the input should be stored as multiple scalars (the default) or as a single array. In the latter case one axis in the shape can be defined as variable length by giving it the value 0. It means that the actual array shape in a row is determined by the number of values in the corresponding input line. Columns get the names `Column1`, `Column2`, etc.. For example: 1. `autoshape=[]` (which is the default) means that all values are to be stored as scalar columns. 2. `autoshape=0` means that all values in a row are to be stored as a variable length vector. 3. `autoshape=10` defines a fixed length vector. If an input line contains less than 10 values, the vector is filled with default values. If more than 10 values, the latter values are ignored. 4. `autoshape=[5,0]` defines a 2-dim array of which the 2nd axis is variable. Note that if an input line does not contain a multiple of 5 values, the array is filled with default values. If the format of the table is explicitly specified, it has to be done either in the first two lines of the data file (named by the argument filename), or in a separate header file (named by the argument headerfile). In both forms, table keywords may also be specified before the column definitions. The column names and types can be described by two lines: 1. The first line contains the names of the columns. These names may be enclosed in quotes (either single or double). 2. The second line contains the data type and optionally the shape of each column. Valid types are: - S for Short data - I for Integer data - R for Real data - D for Double Precision data - X for Complex data (Real followed by Imaginary) - Z for Complex data (Amplitude then Phase) - DX for Double Precision Complex data (Real followed by Imaginary) - DZ for Double Precision Complex data (Amplitude then Phase) - A for ASCII data (a value must be enclosed in single or double quotes if it contains whitespace) - B for Boolean data (False are empty string, 0, or any string starting with F, f, N, or n). If a column is an array, the shape has to be given after the data type without any whitespace. E.g. `I10` defines an integer vector of length 10. `A2,5` defines a 2-dim string array with shape [2,5]. Note that `I` is not the same as `I1` as the first one defines a scalar and the other one a vector with length 1. The last column can have one variable length axis denoted by the value 0. It "consumes" the remainder of the input line. If the argument headerfile is set then the header information is read from that file instead of the first lines of the data file. To give a simple example of the form where the header information is located at the top of the data file:: COLI COLF COLD COLX COLZ COLS I R D X Z A 1 1.1 1.11 1.12 1.13 1.14 1.15 Str1 10 11 12 13 14 15 16 "" Note that a complex number consists of 2 numbers. Also note that an empty string can be given. Let us now give an example of a separate header file that one might use to get interferometer data into casacore:: U V W TIME ANT1 ANT2 DATA R R R D I I X1,0 The data file would then look like:: 124.011 54560.0 3477.1 43456789.0990 1 2 4.327 -0.1132 34561.0 45629.3 3900.5 43456789.0990 1 3 5.398 0.4521 Note that the DATA column is defined as a 2-dim array of 1 correlation and a variable number of channels, so the actual number of channels is determined by the input. In this example both rows will have 1 channel (note that a complex value contains 2 values). Tables may have keywords in addition to the columns. The keywords are useful for holding information that is global to the entire table (such as author, revision, history, etc.). The keywords in the header definitions must preceed the column descriptions. They must be enclosed between a line that starts with ".key..." and a line that starts with ".endkey..." (where ... can be anything). A table keywordset and column keywordsets can be specified. The latter can be specified by specifying the column name after the .keywords string. Between these two lines each line should contain the following: - The keyword name, e.g., ANYKEY - The datatype and optional shape of the keyword (cf. list of valid types above) - The value or values for the keyword (the keyword may contain a scalar or an array of values). e.g., 3.14159 21.78945 Thus to continue the example above, one might wish to add keywords as follows:: .keywords DATE A "97/1/16" REVISION D 2.01 AUTHOR A "Tim Cornwell" INSTRUMENT A "VLA" .endkeywords .keywords TIME UNIT A "s" .endkeywords U V W TIME ANT1 ANT2 DATA R R R D I I X1,0 Similarly to the column format string, the keyword formats can also contain shape information. The only difference is that if no shape is given, a keyword can have multiple values (making it a vector). It is possible to ignore comment lines in the header and data file by giving the `commentmarker`. It indicates that lines starting with the given marker are ignored. Note that the marker can be a regular expression (e.g. `' *//'` tells that lines starting with // and optionally preceeded by blanks have to be ignored). With the arguments `firstline` and `lastline` one can specify which lines have to be taken from the input file. A negative value means 1 for `firstline` or end-of-file for `lastline`. Note that if the headers and data are combined in one file, these line arguments apply to the whole file. If headers and data are in separate files, these line arguments apply to the data file only. Also note that ignored comment lines are counted, thus are used to determine which lines are in the line range. The number of rows is determined by the number of lines read from the data file.
[ "Create", "a", "table", "from", "an", "ASCII", "file", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tableutil.py#L35-L240
24,443
casacore/python-casacore
casacore/tables/tableutil.py
makescacoldesc
def makescacoldesc(columnname, value, datamanagertype='', datamanagergroup='', options=0, maxlen=0, comment='', valuetype='', keywords={}): """Create description of a scalar column. A description for a scalar column can be created from a name for the column and a data value, which is used only to determine the type of the column. Note that a dict value is also possible. It is possible to create the column description in more detail by giving the data manager name, group, option, and comment as well. The data manager type tells which data manager (storage manager) is used to store the columns. The data manager type and group are explained in more detail in the `casacore Tables <../../casacore/doc/html/group__Tables__module.html>`_ documentation. It returns a dict with fields `name` and `desc` which can thereafter be used to build a table description using function :func:`maketabdesc`. `columname` Name of column `value` Example data value used to determine the column's data type. It is only used if argument `valuetype` is not given. `datamanagertype` Type of data manager which can be one of StandardStMan (default) or IncrementalStMan. The latter one can save disk space if many subsequent cells in the column will have the same value. `datamanagergroup` Data manager group. Only for the expert user. `options` Options. Need not be filled in. `maxlen` Maximum length of string values in a column. Default 0 means unlimited. `comment` Comment: informational for user. `valuetype` A string giving the column's data type. Possible data types are bool (or boolean), uchar (or byte), short, int (or integer), uint, float, double, complex, dcomplex, and string. 'keywords' A dict defining initial keywords for the column. For example:: scd1 = makescacoldesc("col2", "")) scd2 = makescacoldesc("col1", 1, "IncrementalStMan") td = maketabdesc([scd1, scd2]) This creates a table description consisting of an integer column `col1`, and a string column `col2`. `col1` uses the IncrementalStMan storage manager, while `col2` uses the default storage manager StandardStMan. """ vtype = valuetype if vtype == '': vtype = _value_type_name(value) rec2 = {'valueType': vtype, 'dataManagerType': datamanagertype, 'dataManagerGroup': datamanagergroup, 'option': options, 'maxlen': maxlen, 'comment': comment, 'keywords': keywords} return {'name': columnname, 'desc': rec2}
python
def makescacoldesc(columnname, value, datamanagertype='', datamanagergroup='', options=0, maxlen=0, comment='', valuetype='', keywords={}): vtype = valuetype if vtype == '': vtype = _value_type_name(value) rec2 = {'valueType': vtype, 'dataManagerType': datamanagertype, 'dataManagerGroup': datamanagergroup, 'option': options, 'maxlen': maxlen, 'comment': comment, 'keywords': keywords} return {'name': columnname, 'desc': rec2}
[ "def", "makescacoldesc", "(", "columnname", ",", "value", ",", "datamanagertype", "=", "''", ",", "datamanagergroup", "=", "''", ",", "options", "=", "0", ",", "maxlen", "=", "0", ",", "comment", "=", "''", ",", "valuetype", "=", "''", ",", "keywords", ...
Create description of a scalar column. A description for a scalar column can be created from a name for the column and a data value, which is used only to determine the type of the column. Note that a dict value is also possible. It is possible to create the column description in more detail by giving the data manager name, group, option, and comment as well. The data manager type tells which data manager (storage manager) is used to store the columns. The data manager type and group are explained in more detail in the `casacore Tables <../../casacore/doc/html/group__Tables__module.html>`_ documentation. It returns a dict with fields `name` and `desc` which can thereafter be used to build a table description using function :func:`maketabdesc`. `columname` Name of column `value` Example data value used to determine the column's data type. It is only used if argument `valuetype` is not given. `datamanagertype` Type of data manager which can be one of StandardStMan (default) or IncrementalStMan. The latter one can save disk space if many subsequent cells in the column will have the same value. `datamanagergroup` Data manager group. Only for the expert user. `options` Options. Need not be filled in. `maxlen` Maximum length of string values in a column. Default 0 means unlimited. `comment` Comment: informational for user. `valuetype` A string giving the column's data type. Possible data types are bool (or boolean), uchar (or byte), short, int (or integer), uint, float, double, complex, dcomplex, and string. 'keywords' A dict defining initial keywords for the column. For example:: scd1 = makescacoldesc("col2", "")) scd2 = makescacoldesc("col1", 1, "IncrementalStMan") td = maketabdesc([scd1, scd2]) This creates a table description consisting of an integer column `col1`, and a string column `col2`. `col1` uses the IncrementalStMan storage manager, while `col2` uses the default storage manager StandardStMan.
[ "Create", "description", "of", "a", "scalar", "column", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tableutil.py#L244-L313
24,444
casacore/python-casacore
casacore/tables/tableutil.py
makearrcoldesc
def makearrcoldesc(columnname, value, ndim=0, shape=[], datamanagertype='', datamanagergroup='', options=0, maxlen=0, comment='', valuetype='', keywords={}): """Create description of an array column. A description for a scalar column can be created from a name for the column and a data value, which is used only to determine the type of the column. Note that a dict value is also possible. It is possible to create the column description in more detail by giving the dimensionality, shape, data manager name, group, option, and comment as well. The data manager type tells which data manager (storage manager) is used to store the columns. The data manager type and group are explained in more detail in the `casacore Tables <../../casacore/doc/html/group__Tables__module.html>`_ documentation. It returns a dict with fields `name` and `desc` which can thereafter be used to build a table description using function :func:`maketabdesc`. `name` The name of the column. `value` A data value, which is only used to determine the data type of the column. It is only used if argument `valuetype` is not given. `ndim` Optionally the number of dimensions. A value > 0 means that all arrays in the column must have that dimensionality. Note that the arrays can still differ in shape unless the shape vector is also given. `shape` An optional sequence of integers giving the shape of the array in each cell. If given, it forces option FixedShape (see below) and sets the number of dimensions (if not given). All arrays in the column get the given shape and the array is created as soon as a row is added. Note that the shape vector gives the shape in each table cell; the number of rows in the table should NOT be part of it. `datamanagertype` Type of data manager which can be one of StandardStMan (default), IncrementalStMan, TiledColumnStMan, TiledCellStMan, or TiledShapeStMan. The tiled storage managers are usually used for bigger data arrays. `datamanagergroup` Data manager group. Only for the expert user. `options` Optionally numeric array options which can be added to combine them. `1` means Direct. It tells that the data are directly stored in the table. Direct forces option FixedShape. If not given, the array is indirect, which means that the data will be stored in a separate file. `4` means FixedShape. This option does not need to be given, because it is enforced if the shape is given. FixedShape means that the shape of the array must be the same in each cell of the column. Otherwise the array shapes may be different in each column cell and is it possible that a cell does not contain an array at all. Note that when given (or implicitly by option Direct), the shape argument must be given as well. Default is 0, thus indirect and variable shaped. `maxlen` Maximum length of string values in a column. Default 0 means unlimited. `comment` Comment: informational for user. `valuetype` A string giving the column's data type. Possible data types are bool (or boolean), uchar (or byte), short, int (or integer), uint, float, double, complex, dcomplex, and string. 'keywords' A dict defining initial keywords for the column. For example:: acd1= makescacoldesc("arr1", 1., 0, [2,3,4]) td = maketabdesc(acd1) This creates a table description consisting of an array column `arr1` containing 3-dim arrays of doubles with shape [2,3,4]. """ vtype = valuetype if vtype == '': vtype = _value_type_name(value) if len(shape) > 0: if ndim <= 0: ndim = len(shape) rec2 = {'valueType': vtype, 'dataManagerType': datamanagertype, 'dataManagerGroup': datamanagergroup, 'ndim': ndim, 'shape': shape, '_c_order': True, 'option': options, 'maxlen': maxlen, 'comment': comment, 'keywords': keywords} return {'name': columnname, 'desc': rec2}
python
def makearrcoldesc(columnname, value, ndim=0, shape=[], datamanagertype='', datamanagergroup='', options=0, maxlen=0, comment='', valuetype='', keywords={}): vtype = valuetype if vtype == '': vtype = _value_type_name(value) if len(shape) > 0: if ndim <= 0: ndim = len(shape) rec2 = {'valueType': vtype, 'dataManagerType': datamanagertype, 'dataManagerGroup': datamanagergroup, 'ndim': ndim, 'shape': shape, '_c_order': True, 'option': options, 'maxlen': maxlen, 'comment': comment, 'keywords': keywords} return {'name': columnname, 'desc': rec2}
[ "def", "makearrcoldesc", "(", "columnname", ",", "value", ",", "ndim", "=", "0", ",", "shape", "=", "[", "]", ",", "datamanagertype", "=", "''", ",", "datamanagergroup", "=", "''", ",", "options", "=", "0", ",", "maxlen", "=", "0", ",", "comment", "=...
Create description of an array column. A description for a scalar column can be created from a name for the column and a data value, which is used only to determine the type of the column. Note that a dict value is also possible. It is possible to create the column description in more detail by giving the dimensionality, shape, data manager name, group, option, and comment as well. The data manager type tells which data manager (storage manager) is used to store the columns. The data manager type and group are explained in more detail in the `casacore Tables <../../casacore/doc/html/group__Tables__module.html>`_ documentation. It returns a dict with fields `name` and `desc` which can thereafter be used to build a table description using function :func:`maketabdesc`. `name` The name of the column. `value` A data value, which is only used to determine the data type of the column. It is only used if argument `valuetype` is not given. `ndim` Optionally the number of dimensions. A value > 0 means that all arrays in the column must have that dimensionality. Note that the arrays can still differ in shape unless the shape vector is also given. `shape` An optional sequence of integers giving the shape of the array in each cell. If given, it forces option FixedShape (see below) and sets the number of dimensions (if not given). All arrays in the column get the given shape and the array is created as soon as a row is added. Note that the shape vector gives the shape in each table cell; the number of rows in the table should NOT be part of it. `datamanagertype` Type of data manager which can be one of StandardStMan (default), IncrementalStMan, TiledColumnStMan, TiledCellStMan, or TiledShapeStMan. The tiled storage managers are usually used for bigger data arrays. `datamanagergroup` Data manager group. Only for the expert user. `options` Optionally numeric array options which can be added to combine them. `1` means Direct. It tells that the data are directly stored in the table. Direct forces option FixedShape. If not given, the array is indirect, which means that the data will be stored in a separate file. `4` means FixedShape. This option does not need to be given, because it is enforced if the shape is given. FixedShape means that the shape of the array must be the same in each cell of the column. Otherwise the array shapes may be different in each column cell and is it possible that a cell does not contain an array at all. Note that when given (or implicitly by option Direct), the shape argument must be given as well. Default is 0, thus indirect and variable shaped. `maxlen` Maximum length of string values in a column. Default 0 means unlimited. `comment` Comment: informational for user. `valuetype` A string giving the column's data type. Possible data types are bool (or boolean), uchar (or byte), short, int (or integer), uint, float, double, complex, dcomplex, and string. 'keywords' A dict defining initial keywords for the column. For example:: acd1= makescacoldesc("arr1", 1., 0, [2,3,4]) td = maketabdesc(acd1) This creates a table description consisting of an array column `arr1` containing 3-dim arrays of doubles with shape [2,3,4].
[ "Create", "description", "of", "an", "array", "column", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tableutil.py#L317-L417
24,445
casacore/python-casacore
casacore/tables/tableutil.py
maketabdesc
def maketabdesc(descs=[]): """Create a table description. Creates a table description from a set of column descriptions. The resulting table description can be used in the :class:`table` constructor. For example:: scd1 = makescacoldesc("col2", "aa") scd2 = makescacoldesc("col1", 1, "IncrementalStMan") scd3 = makescacoldesc("colrec1", {}) acd1 = makearrcoldesc("arr1", 1, 0, [2,3,4]) acd2 = makearrcoldesc("arr2", 0.+0j) td = maketabdesc([scd1, scd2, scd3, acd1, acd2]) t = table("mytable", td, nrow=100) | This creates a table description `td` from five column descriptions and then creates a 100-row table called `mytable` from the table description. | The columns contain respectivily strings, integer scalars, records, 3D integer arrays with fixed shape [2,3,4], and complex arrays with variable shape. """ rec = {} # If a single dict is given, make a list of it. if isinstance(descs, dict): descs = [descs] for desc in descs: colname = desc['name'] if colname in rec: raise ValueError('Column name ' + colname + ' multiply used in table description') rec[colname] = desc['desc'] return rec
python
def maketabdesc(descs=[]): rec = {} # If a single dict is given, make a list of it. if isinstance(descs, dict): descs = [descs] for desc in descs: colname = desc['name'] if colname in rec: raise ValueError('Column name ' + colname + ' multiply used in table description') rec[colname] = desc['desc'] return rec
[ "def", "maketabdesc", "(", "descs", "=", "[", "]", ")", ":", "rec", "=", "{", "}", "# If a single dict is given, make a list of it.", "if", "isinstance", "(", "descs", ",", "dict", ")", ":", "descs", "=", "[", "descs", "]", "for", "desc", "in", "descs", ...
Create a table description. Creates a table description from a set of column descriptions. The resulting table description can be used in the :class:`table` constructor. For example:: scd1 = makescacoldesc("col2", "aa") scd2 = makescacoldesc("col1", 1, "IncrementalStMan") scd3 = makescacoldesc("colrec1", {}) acd1 = makearrcoldesc("arr1", 1, 0, [2,3,4]) acd2 = makearrcoldesc("arr2", 0.+0j) td = maketabdesc([scd1, scd2, scd3, acd1, acd2]) t = table("mytable", td, nrow=100) | This creates a table description `td` from five column descriptions and then creates a 100-row table called `mytable` from the table description. | The columns contain respectivily strings, integer scalars, records, 3D integer arrays with fixed shape [2,3,4], and complex arrays with variable shape.
[ "Create", "a", "table", "description", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tableutil.py#L450-L483
24,446
casacore/python-casacore
casacore/tables/tableutil.py
makedminfo
def makedminfo(tabdesc, group_spec=None): """Creates a data manager information object. Create a data manager information dictionary outline from a table description. The resulting dictionary is a bare outline and is available for the purposes of further customising the data manager via the `group_spec` argument. The resulting dictionary can be used in the :class:`table` constructor and the :meth:`default_ms` and :meth:`default_ms_subtable` functions. `tabdesc` The table description `group_spec` The SPEC for a data manager group. In practice this is useful for setting the Default Tile Size and Maximum Cache Size for the Data Manager { 'WeightColumnGroup' : { 'DEFAULTTILESHAPE': np.int32([4,4,4]), 'MAXIMUMCACHESIZE': 1000, } } This should be used with care. """ if group_spec is None: group_spec = {} class DMGroup(object): """ Keep track of the columns, type and spec of each data manager group """ def __init__(self): self.columns = [] self.type = None self.spec = None dm_groups = defaultdict(DMGroup) # Iterate through the table columns, grouping them # by their dataManagerGroup for c, d in six.iteritems(tabdesc): if c in ('_define_hypercolumn_', '_keywords_', '_private_keywords_'): continue # Extract group and data manager type group = d.get("dataManagerGroup", "StandardStMan") type_ = d.get("dataManagerType", "StandardStMan") # Set defaults if necessary if not group: group = "StandardStMan" if not type_: type_ = "StandardStMan" # Obtain the (possibly empty) data manager group dm_group = dm_groups[group] # Add the column dm_group.columns.append(c) # Set the spec if dm_group.spec is None: dm_group.spec = group_spec.get(group, {}) # Check that the data manager type is consistent across columns if dm_group.type is None: dm_group.type = type_ elif not dm_group.type == type_: raise ValueError("Mismatched dataManagerType '%s' " "for dataManagerGroup '%s' " "Previously, the type was '%s'" % (type_, group, dm_group.type)) # Output a data manager entry return { '*%d'%(i+1): { 'COLUMNS': dm_group.columns, 'TYPE': dm_group.type, 'NAME': group, 'SPEC' : dm_group.spec, 'SEQNR': i } for i, (group, dm_group) in enumerate(six.iteritems(dm_groups)) }
python
def makedminfo(tabdesc, group_spec=None): if group_spec is None: group_spec = {} class DMGroup(object): """ Keep track of the columns, type and spec of each data manager group """ def __init__(self): self.columns = [] self.type = None self.spec = None dm_groups = defaultdict(DMGroup) # Iterate through the table columns, grouping them # by their dataManagerGroup for c, d in six.iteritems(tabdesc): if c in ('_define_hypercolumn_', '_keywords_', '_private_keywords_'): continue # Extract group and data manager type group = d.get("dataManagerGroup", "StandardStMan") type_ = d.get("dataManagerType", "StandardStMan") # Set defaults if necessary if not group: group = "StandardStMan" if not type_: type_ = "StandardStMan" # Obtain the (possibly empty) data manager group dm_group = dm_groups[group] # Add the column dm_group.columns.append(c) # Set the spec if dm_group.spec is None: dm_group.spec = group_spec.get(group, {}) # Check that the data manager type is consistent across columns if dm_group.type is None: dm_group.type = type_ elif not dm_group.type == type_: raise ValueError("Mismatched dataManagerType '%s' " "for dataManagerGroup '%s' " "Previously, the type was '%s'" % (type_, group, dm_group.type)) # Output a data manager entry return { '*%d'%(i+1): { 'COLUMNS': dm_group.columns, 'TYPE': dm_group.type, 'NAME': group, 'SPEC' : dm_group.spec, 'SEQNR': i } for i, (group, dm_group) in enumerate(six.iteritems(dm_groups)) }
[ "def", "makedminfo", "(", "tabdesc", ",", "group_spec", "=", "None", ")", ":", "if", "group_spec", "is", "None", ":", "group_spec", "=", "{", "}", "class", "DMGroup", "(", "object", ")", ":", "\"\"\"\n Keep track of the columns, type and spec of each data manager...
Creates a data manager information object. Create a data manager information dictionary outline from a table description. The resulting dictionary is a bare outline and is available for the purposes of further customising the data manager via the `group_spec` argument. The resulting dictionary can be used in the :class:`table` constructor and the :meth:`default_ms` and :meth:`default_ms_subtable` functions. `tabdesc` The table description `group_spec` The SPEC for a data manager group. In practice this is useful for setting the Default Tile Size and Maximum Cache Size for the Data Manager { 'WeightColumnGroup' : { 'DEFAULTTILESHAPE': np.int32([4,4,4]), 'MAXIMUMCACHESIZE': 1000, } } This should be used with care.
[ "Creates", "a", "data", "manager", "information", "object", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tableutil.py#L485-L569
24,447
casacore/python-casacore
casacore/tables/tableutil.py
tabledefinehypercolumn
def tabledefinehypercolumn(tabdesc, name, ndim, datacolumns, coordcolumns=False, idcolumns=False): """Add a hypercolumn to a table description. It defines a hypercolumn and adds it the given table description. A hypercolumn is an entity used by the Tiled Storage Managers (TSM). It defines which columns have to be stored together with a TSM. It should only be used by expert users who want to use a TSM to its full extent. For a basic TSM s hypercolumn definition is not needed. tabledesc A table description (result from :func:`maketabdesc`). name Name of hypercolumn ndim Dimensionality of hypercolumn; normally 1 more than the dimensionality of the arrays in the data columns to be stored with the TSM datacolumns Data columns to be stored with TSM coordcolumns Optional coordinate columns to be stored with TSM idcolumns Optional id columns to be stored with TSM For example:: scd1 = makescacoldesc("col2", "aa") scd2 = makescacoldesc("col1", 1, "IncrementalStMan") scd3 = makescacoldesc("colrec1", {}) acd1 = makearrcoldesc("arr1", 1, 0, [2,3,4]) acd2 = makearrcoldesc("arr2", as_complex(0)) td = maketabdesc([scd1, scd2, scd3, acd1, acd2]) tabledefinehypercolumn(td, "TiledArray", 4, ["arr1"]) tab = table("mytable", tabledesc=td, nrow=100) | This creates a table description `td` from five column descriptions and then creates a 100-row table called mytable from the table description. | The columns contain respectivily strings, integer scalars, records, 3D integer arrays with fixed shape [2,3,4], and complex arrays with variable shape. | The first array is stored with the Tiled Storage Manager (in this case the TiledColumnStMan). """ rec = {'HCndim': ndim, 'HCdatanames': datacolumns} if not isinstance(coordcolumns, bool): rec['HCcoordnames'] = coordcolumns if not isinstance(idcolumns, bool): rec['HCidnames'] = idcolumns if '_define_hypercolumn_' not in tabdesc: tabdesc['_define_hypercolumn_'] = {} tabdesc['_define_hypercolumn_'][name] = rec
python
def tabledefinehypercolumn(tabdesc, name, ndim, datacolumns, coordcolumns=False, idcolumns=False): rec = {'HCndim': ndim, 'HCdatanames': datacolumns} if not isinstance(coordcolumns, bool): rec['HCcoordnames'] = coordcolumns if not isinstance(idcolumns, bool): rec['HCidnames'] = idcolumns if '_define_hypercolumn_' not in tabdesc: tabdesc['_define_hypercolumn_'] = {} tabdesc['_define_hypercolumn_'][name] = rec
[ "def", "tabledefinehypercolumn", "(", "tabdesc", ",", "name", ",", "ndim", ",", "datacolumns", ",", "coordcolumns", "=", "False", ",", "idcolumns", "=", "False", ")", ":", "rec", "=", "{", "'HCndim'", ":", "ndim", ",", "'HCdatanames'", ":", "datacolumns", ...
Add a hypercolumn to a table description. It defines a hypercolumn and adds it the given table description. A hypercolumn is an entity used by the Tiled Storage Managers (TSM). It defines which columns have to be stored together with a TSM. It should only be used by expert users who want to use a TSM to its full extent. For a basic TSM s hypercolumn definition is not needed. tabledesc A table description (result from :func:`maketabdesc`). name Name of hypercolumn ndim Dimensionality of hypercolumn; normally 1 more than the dimensionality of the arrays in the data columns to be stored with the TSM datacolumns Data columns to be stored with TSM coordcolumns Optional coordinate columns to be stored with TSM idcolumns Optional id columns to be stored with TSM For example:: scd1 = makescacoldesc("col2", "aa") scd2 = makescacoldesc("col1", 1, "IncrementalStMan") scd3 = makescacoldesc("colrec1", {}) acd1 = makearrcoldesc("arr1", 1, 0, [2,3,4]) acd2 = makearrcoldesc("arr2", as_complex(0)) td = maketabdesc([scd1, scd2, scd3, acd1, acd2]) tabledefinehypercolumn(td, "TiledArray", 4, ["arr1"]) tab = table("mytable", tabledesc=td, nrow=100) | This creates a table description `td` from five column descriptions and then creates a 100-row table called mytable from the table description. | The columns contain respectivily strings, integer scalars, records, 3D integer arrays with fixed shape [2,3,4], and complex arrays with variable shape. | The first array is stored with the Tiled Storage Manager (in this case the TiledColumnStMan).
[ "Add", "a", "hypercolumn", "to", "a", "table", "description", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tableutil.py#L579-L635
24,448
casacore/python-casacore
casacore/tables/tableutil.py
tabledelete
def tabledelete(tablename, checksubtables=False, ack=True): """Delete a table on disk. It is the same as :func:`table.delete`, but without the need to open the table first. """ tabname = _remove_prefix(tablename) t = table(tabname, ack=False) if t.ismultiused(checksubtables): six.print_('Table', tabname, 'cannot be deleted; it is still in use') else: t = 0 table(tabname, readonly=False, _delete=True, ack=False) if ack: six.print_('Table', tabname, 'has been deleted')
python
def tabledelete(tablename, checksubtables=False, ack=True): tabname = _remove_prefix(tablename) t = table(tabname, ack=False) if t.ismultiused(checksubtables): six.print_('Table', tabname, 'cannot be deleted; it is still in use') else: t = 0 table(tabname, readonly=False, _delete=True, ack=False) if ack: six.print_('Table', tabname, 'has been deleted')
[ "def", "tabledelete", "(", "tablename", ",", "checksubtables", "=", "False", ",", "ack", "=", "True", ")", ":", "tabname", "=", "_remove_prefix", "(", "tablename", ")", "t", "=", "table", "(", "tabname", ",", "ack", "=", "False", ")", "if", "t", ".", ...
Delete a table on disk. It is the same as :func:`table.delete`, but without the need to open the table first.
[ "Delete", "a", "table", "on", "disk", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tableutil.py#L638-L653
24,449
casacore/python-casacore
casacore/tables/tableutil.py
tableexists
def tableexists(tablename): """Test if a table exists.""" result = True try: t = table(tablename, ack=False) except: result = False return result
python
def tableexists(tablename): result = True try: t = table(tablename, ack=False) except: result = False return result
[ "def", "tableexists", "(", "tablename", ")", ":", "result", "=", "True", "try", ":", "t", "=", "table", "(", "tablename", ",", "ack", "=", "False", ")", "except", ":", "result", "=", "False", "return", "result" ]
Test if a table exists.
[ "Test", "if", "a", "table", "exists", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tableutil.py#L656-L663
24,450
casacore/python-casacore
casacore/tables/tableutil.py
tableiswritable
def tableiswritable(tablename): """Test if a table is writable.""" result = True try: t = table(tablename, readonly=False, ack=False) result = t.iswritable() except: result = False return result
python
def tableiswritable(tablename): result = True try: t = table(tablename, readonly=False, ack=False) result = t.iswritable() except: result = False return result
[ "def", "tableiswritable", "(", "tablename", ")", ":", "result", "=", "True", "try", ":", "t", "=", "table", "(", "tablename", ",", "readonly", "=", "False", ",", "ack", "=", "False", ")", "result", "=", "t", ".", "iswritable", "(", ")", "except", ":"...
Test if a table is writable.
[ "Test", "if", "a", "table", "is", "writable", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tableutil.py#L666-L674
24,451
casacore/python-casacore
casacore/tables/tableutil.py
tablestructure
def tablestructure(tablename, dataman=True, column=True, subtable=False, sort=False): """Print the structure of a table. It is the same as :func:`table.showstructure`, but without the need to open the table first. """ t = table(tablename, ack=False) six.print_(t.showstructure(dataman, column, subtable, sort))
python
def tablestructure(tablename, dataman=True, column=True, subtable=False, sort=False): t = table(tablename, ack=False) six.print_(t.showstructure(dataman, column, subtable, sort))
[ "def", "tablestructure", "(", "tablename", ",", "dataman", "=", "True", ",", "column", "=", "True", ",", "subtable", "=", "False", ",", "sort", "=", "False", ")", ":", "t", "=", "table", "(", "tablename", ",", "ack", "=", "False", ")", "six", ".", ...
Print the structure of a table. It is the same as :func:`table.showstructure`, but without the need to open the table first.
[ "Print", "the", "structure", "of", "a", "table", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tableutil.py#L723-L732
24,452
casacore/python-casacore
casacore/images/image.py
image.attrget
def attrget(self, groupname, attrname, rownr): """Get the value of an attribute in the given row in a group.""" return self._attrget(groupname, attrname, rownr)
python
def attrget(self, groupname, attrname, rownr): return self._attrget(groupname, attrname, rownr)
[ "def", "attrget", "(", "self", ",", "groupname", ",", "attrname", ",", "rownr", ")", ":", "return", "self", ".", "_attrget", "(", "groupname", ",", "attrname", ",", "rownr", ")" ]
Get the value of an attribute in the given row in a group.
[ "Get", "the", "value", "of", "an", "attribute", "in", "the", "given", "row", "in", "a", "group", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L237-L239
24,453
casacore/python-casacore
casacore/images/image.py
image.attrgetcol
def attrgetcol(self, groupname, attrname): """Get the value of an attribute for all rows in a group.""" values = [] for rownr in range(self.attrnrows(groupname)): values.append(self.attrget(groupname, attrname, rownr)) return values
python
def attrgetcol(self, groupname, attrname): values = [] for rownr in range(self.attrnrows(groupname)): values.append(self.attrget(groupname, attrname, rownr)) return values
[ "def", "attrgetcol", "(", "self", ",", "groupname", ",", "attrname", ")", ":", "values", "=", "[", "]", "for", "rownr", "in", "range", "(", "self", ".", "attrnrows", "(", "groupname", ")", ")", ":", "values", ".", "append", "(", "self", ".", "attrget...
Get the value of an attribute for all rows in a group.
[ "Get", "the", "value", "of", "an", "attribute", "for", "all", "rows", "in", "a", "group", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L241-L246
24,454
casacore/python-casacore
casacore/images/image.py
image.attrfindrows
def attrfindrows(self, groupname, attrname, value): """Get the row numbers of all rows where the attribute matches the given value.""" values = self.attrgetcol(groupname, attrname) return [i for i in range(len(values)) if values[i] == value]
python
def attrfindrows(self, groupname, attrname, value): values = self.attrgetcol(groupname, attrname) return [i for i in range(len(values)) if values[i] == value]
[ "def", "attrfindrows", "(", "self", ",", "groupname", ",", "attrname", ",", "value", ")", ":", "values", "=", "self", ".", "attrgetcol", "(", "groupname", ",", "attrname", ")", "return", "[", "i", "for", "i", "in", "range", "(", "len", "(", "values", ...
Get the row numbers of all rows where the attribute matches the given value.
[ "Get", "the", "row", "numbers", "of", "all", "rows", "where", "the", "attribute", "matches", "the", "given", "value", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L248-L251
24,455
casacore/python-casacore
casacore/images/image.py
image.attrgetrow
def attrgetrow(self, groupname, key, value=None): """Get the values of all attributes of a row in a group. If the key is an integer, the key is the row number for which the attribute values have to be returned. Otherwise the key has to be a string and it defines the name of an attribute. The attribute values of the row for which the key matches the given value is returned. It can only be used for unique attribute keys. An IndexError exception is raised if no or multiple matches are found. """ if not isinstance(key, str): return self._attrgetrow(groupname, key) # The key is an attribute name whose value has to be found. rownrs = self.attrfindrows(groupname, key, value) if len(rownrs) == 0: raise IndexError("Image attribute " + key + " in group " + groupname + " has no matches for value " + str(value)) if len(rownrs) > 1: raise IndexError("Image attribute " + key + " in group " + groupname + " has multiple matches for value " + str(value)) return self._attrgetrow(groupname, rownrs[0])
python
def attrgetrow(self, groupname, key, value=None): if not isinstance(key, str): return self._attrgetrow(groupname, key) # The key is an attribute name whose value has to be found. rownrs = self.attrfindrows(groupname, key, value) if len(rownrs) == 0: raise IndexError("Image attribute " + key + " in group " + groupname + " has no matches for value " + str(value)) if len(rownrs) > 1: raise IndexError("Image attribute " + key + " in group " + groupname + " has multiple matches for value " + str(value)) return self._attrgetrow(groupname, rownrs[0])
[ "def", "attrgetrow", "(", "self", ",", "groupname", ",", "key", ",", "value", "=", "None", ")", ":", "if", "not", "isinstance", "(", "key", ",", "str", ")", ":", "return", "self", ".", "_attrgetrow", "(", "groupname", ",", "key", ")", "# The key is an ...
Get the values of all attributes of a row in a group. If the key is an integer, the key is the row number for which the attribute values have to be returned. Otherwise the key has to be a string and it defines the name of an attribute. The attribute values of the row for which the key matches the given value is returned. It can only be used for unique attribute keys. An IndexError exception is raised if no or multiple matches are found.
[ "Get", "the", "values", "of", "all", "attributes", "of", "a", "row", "in", "a", "group", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L253-L277
24,456
casacore/python-casacore
casacore/images/image.py
image.attrput
def attrput(self, groupname, attrname, rownr, value, unit=[], meas=[]): """Put the value and optionally unit and measinfo of an attribute in a row in a group.""" return self._attrput(groupname, attrname, rownr, value, unit, meas)
python
def attrput(self, groupname, attrname, rownr, value, unit=[], meas=[]): return self._attrput(groupname, attrname, rownr, value, unit, meas)
[ "def", "attrput", "(", "self", ",", "groupname", ",", "attrname", ",", "rownr", ",", "value", ",", "unit", "=", "[", "]", ",", "meas", "=", "[", "]", ")", ":", "return", "self", ".", "_attrput", "(", "groupname", ",", "attrname", ",", "rownr", ",",...
Put the value and optionally unit and measinfo of an attribute in a row in a group.
[ "Put", "the", "value", "and", "optionally", "unit", "and", "measinfo", "of", "an", "attribute", "in", "a", "row", "in", "a", "group", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L287-L290
24,457
casacore/python-casacore
casacore/images/image.py
image.getdata
def getdata(self, blc=(), trc=(), inc=()): """Get image data. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to get a data slice. The data is returned as a numpy array. Its dimensionality is the same as the dimensionality of the image, even if an axis has length 1. """ return self._getdata(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc))
python
def getdata(self, blc=(), trc=(), inc=()): return self._getdata(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc))
[ "def", "getdata", "(", "self", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "return", "self", ".", "_getdata", "(", "self", ".", "_adjustBlc", "(", "blc", ")", ",", "self", ".", "_adjustTrc", "(", ...
Get image data. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to get a data slice. The data is returned as a numpy array. Its dimensionality is the same as the dimensionality of the image, even if an axis has length 1.
[ "Get", "image", "data", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L292-L304
24,458
casacore/python-casacore
casacore/images/image.py
image.getmask
def getmask(self, blc=(), trc=(), inc=()): """Get image mask. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to get a mask slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The mask is returned as a numpy array. Its dimensionality is the same as the dimensionality of the image, even if an axis has length 1. Note that the casacore images use the convention that a mask value True means good and False means bad. However, numpy uses the opposite. Therefore the mask will be negated, so it can be used directly in numpy operations. If the image has no mask, an array will be returned with all values set to False. """ return numpy.logical_not(self._getmask(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc)))
python
def getmask(self, blc=(), trc=(), inc=()): return numpy.logical_not(self._getmask(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc)))
[ "def", "getmask", "(", "self", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "return", "numpy", ".", "logical_not", "(", "self", ".", "_getmask", "(", "self", ".", "_adjustBlc", "(", "blc", ")", ",",...
Get image mask. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to get a mask slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The mask is returned as a numpy array. Its dimensionality is the same as the dimensionality of the image, even if an axis has length 1. Note that the casacore images use the convention that a mask value True means good and False means bad. However, numpy uses the opposite. Therefore the mask will be negated, so it can be used directly in numpy operations. If the image has no mask, an array will be returned with all values set to False.
[ "Get", "image", "mask", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L307-L327
24,459
casacore/python-casacore
casacore/images/image.py
image.get
def get(self, blc=(), trc=(), inc=()): """Get image data and mask. Get the image data and mask (see ::func:`getdata` and :func:`getmask`) as a numpy masked array. """ return nma.masked_array(self.getdata(blc, trc, inc), self.getmask(blc, trc, inc))
python
def get(self, blc=(), trc=(), inc=()): return nma.masked_array(self.getdata(blc, trc, inc), self.getmask(blc, trc, inc))
[ "def", "get", "(", "self", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "return", "nma", ".", "masked_array", "(", "self", ".", "getdata", "(", "blc", ",", "trc", ",", "inc", ")", ",", "self", "...
Get image data and mask. Get the image data and mask (see ::func:`getdata` and :func:`getmask`) as a numpy masked array.
[ "Get", "image", "data", "and", "mask", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L330-L338
24,460
casacore/python-casacore
casacore/images/image.py
image.putdata
def putdata(self, value, blc=(), trc=(), inc=()): """Put image data. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to put a data slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The data should be a numpy array. Its dimensionality must be the same as the dimensionality of the image. """ return self._putdata(value, self._adjustBlc(blc), self._adjustInc(inc))
python
def putdata(self, value, blc=(), trc=(), inc=()): return self._putdata(value, self._adjustBlc(blc), self._adjustInc(inc))
[ "def", "putdata", "(", "self", ",", "value", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "return", "self", ".", "_putdata", "(", "value", ",", "self", ".", "_adjustBlc", "(", "blc", ")", ",", "se...
Put image data. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to put a data slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The data should be a numpy array. Its dimensionality must be the same as the dimensionality of the image.
[ "Put", "image", "data", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L340-L352
24,461
casacore/python-casacore
casacore/images/image.py
image.putmask
def putmask(self, value, blc=(), trc=(), inc=()): """Put image mask. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to put a data slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The data should be a numpy array. Its dimensionality must be the same as the dimensionality of the image. Note that the casacore images use the convention that a mask value True means good and False means bad. However, numpy uses the opposite. Therefore the mask will be negated, so a numoy masked can be given directly. The mask is not written if the image has no mask and if it the entire mask is False. In that case the mask most likely comes from a getmask operation on an image without a mask. """ # casa and numpy have opposite flags return self._putmask(~value, self._adjustBlc(blc), self._adjustInc(inc))
python
def putmask(self, value, blc=(), trc=(), inc=()): # casa and numpy have opposite flags return self._putmask(~value, self._adjustBlc(blc), self._adjustInc(inc))
[ "def", "putmask", "(", "self", ",", "value", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "# casa and numpy have opposite flags", "return", "self", ".", "_putmask", "(", "~", "value", ",", "self", ".", ...
Put image mask. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to put a data slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The data should be a numpy array. Its dimensionality must be the same as the dimensionality of the image. Note that the casacore images use the convention that a mask value True means good and False means bad. However, numpy uses the opposite. Therefore the mask will be negated, so a numoy masked can be given directly. The mask is not written if the image has no mask and if it the entire mask is False. In that case the mask most likely comes from a getmask operation on an image without a mask.
[ "Put", "image", "mask", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L354-L375
24,462
casacore/python-casacore
casacore/images/image.py
image.put
def put(self, value, blc=(), trc=(), inc=()): """Put image data and mask. Put the image data and optionally the mask (see ::func:`getdata` and :func:`getmask`). If the `value` argument is a numpy masked array, but data and mask will bw written. If it is a normal numpy array, only the data will be written. """ if isinstance(value, nma.MaskedArray): self.putdata(value.data, blc, trc, inc) self.putmask(nma.getmaskarray(value), blc, trc, inc) else: self.putdata(value, blc, trc, inc)
python
def put(self, value, blc=(), trc=(), inc=()): if isinstance(value, nma.MaskedArray): self.putdata(value.data, blc, trc, inc) self.putmask(nma.getmaskarray(value), blc, trc, inc) else: self.putdata(value, blc, trc, inc)
[ "def", "put", "(", "self", ",", "value", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "if", "isinstance", "(", "value", ",", "nma", ".", "MaskedArray", ")", ":", "self", ".", "putdata", "(", "valu...
Put image data and mask. Put the image data and optionally the mask (see ::func:`getdata` and :func:`getmask`). If the `value` argument is a numpy masked array, but data and mask will bw written. If it is a normal numpy array, only the data will be written.
[ "Put", "image", "data", "and", "mask", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L377-L391
24,463
casacore/python-casacore
casacore/images/image.py
image.subimage
def subimage(self, blc=(), trc=(), inc=(), dropdegenerate=True): """Form a subimage. An image object containing a subset of an image is returned. The arguments blc (bottom left corner), trc (top right corner), and inc (stride) define the subset. Not all axes need to be specified. Missing values default to begin, end, and 1. By default axes with length 1 are left out. A subimage is a so-called virtual image. It is not stored, but only references the original image. It can be made persistent using the :func:`saveas` method. """ return image(self._subimage(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc), dropdegenerate))
python
def subimage(self, blc=(), trc=(), inc=(), dropdegenerate=True): return image(self._subimage(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc), dropdegenerate))
[ "def", "subimage", "(", "self", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ",", "dropdegenerate", "=", "True", ")", ":", "return", "image", "(", "self", ".", "_subimage", "(", "self", ".", "_adjustBlc", "(", ...
Form a subimage. An image object containing a subset of an image is returned. The arguments blc (bottom left corner), trc (top right corner), and inc (stride) define the subset. Not all axes need to be specified. Missing values default to begin, end, and 1. By default axes with length 1 are left out. A subimage is a so-called virtual image. It is not stored, but only references the original image. It can be made persistent using the :func:`saveas` method.
[ "Form", "a", "subimage", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L426-L444
24,464
casacore/python-casacore
casacore/images/image.py
image.info
def info(self): """Get coordinates, image info, and unit".""" return {'coordinates': self._coordinates(), 'imageinfo': self._imageinfo(), 'miscinfo': self._miscinfo(), 'unit': self._unit() }
python
def info(self): return {'coordinates': self._coordinates(), 'imageinfo': self._imageinfo(), 'miscinfo': self._miscinfo(), 'unit': self._unit() }
[ "def", "info", "(", "self", ")", ":", "return", "{", "'coordinates'", ":", "self", ".", "_coordinates", "(", ")", ",", "'imageinfo'", ":", "self", ".", "_imageinfo", "(", ")", ",", "'miscinfo'", ":", "self", ".", "_miscinfo", "(", ")", ",", "'unit'", ...
Get coordinates, image info, and unit".
[ "Get", "coordinates", "image", "info", "and", "unit", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L484-L490
24,465
casacore/python-casacore
casacore/images/image.py
image.tofits
def tofits(self, filename, overwrite=True, velocity=True, optical=True, bitpix=-32, minpix=1, maxpix=-1): """Write the image to a file in FITS format. `filename` FITS file name `overwrite` If False, an exception is raised if the new image file already exists. Default is True. `velocity` By default a velocity primary spectral axis is written if possible. `optical` If writing a velocity, use the optical definition (otherwise use radio). `bitpix` can be set to -32 (float) or 16 (short) only. When `bitpix` is 16 it will write BSCALE and BZERO into the FITS file. If minPix `minpix` and `maxpix` are used to determine BSCALE and BZERO if `bitpix=16`. If `minpix` is greater than `maxpix` (which is the default), the minimum and maximum pixel values will be determined from the ddta. Oherwise the supplied values will be used and pixels outside that range will be clipped to the minimum and maximum pixel values. Note that this truncation does not occur for `bitpix=-32`. """ return self._tofits(filename, overwrite, velocity, optical, bitpix, minpix, maxpix)
python
def tofits(self, filename, overwrite=True, velocity=True, optical=True, bitpix=-32, minpix=1, maxpix=-1): return self._tofits(filename, overwrite, velocity, optical, bitpix, minpix, maxpix)
[ "def", "tofits", "(", "self", ",", "filename", ",", "overwrite", "=", "True", ",", "velocity", "=", "True", ",", "optical", "=", "True", ",", "bitpix", "=", "-", "32", ",", "minpix", "=", "1", ",", "maxpix", "=", "-", "1", ")", ":", "return", "se...
Write the image to a file in FITS format. `filename` FITS file name `overwrite` If False, an exception is raised if the new image file already exists. Default is True. `velocity` By default a velocity primary spectral axis is written if possible. `optical` If writing a velocity, use the optical definition (otherwise use radio). `bitpix` can be set to -32 (float) or 16 (short) only. When `bitpix` is 16 it will write BSCALE and BZERO into the FITS file. If minPix `minpix` and `maxpix` are used to determine BSCALE and BZERO if `bitpix=16`. If `minpix` is greater than `maxpix` (which is the default), the minimum and maximum pixel values will be determined from the ddta. Oherwise the supplied values will be used and pixels outside that range will be clipped to the minimum and maximum pixel values. Note that this truncation does not occur for `bitpix=-32`.
[ "Write", "the", "image", "to", "a", "file", "in", "FITS", "format", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L492-L519
24,466
casacore/python-casacore
casacore/images/image.py
image.saveas
def saveas(self, filename, overwrite=True, hdf5=False, copymask=True, newmaskname="", newtileshape=()): """Write the image to disk. Note that the created disk file is a snapshot, so it is not updated for possible later changes in the image object. `overwrite` If False, an exception is raised if the new image file already exists. Default is True. `ashdf5` If True, the image is created in HDF5 format, otherwise in casacore format. Default is casacore format. `copymask` By default the mask is written as well if the image has a mask. 'newmaskname` If the mask is written, the name is the same the original or `mask0` if the original mask has no name. Using this argument a different mask name can be given. `tileshape` Advanced users can give a new tile shape. See the :mod:`tables` module for more information about Tiled Storage Managers. """ self._saveas(filename, overwrite, hdf5, copymask, newmaskname, newtileshape)
python
def saveas(self, filename, overwrite=True, hdf5=False, copymask=True, newmaskname="", newtileshape=()): self._saveas(filename, overwrite, hdf5, copymask, newmaskname, newtileshape)
[ "def", "saveas", "(", "self", ",", "filename", ",", "overwrite", "=", "True", ",", "hdf5", "=", "False", ",", "copymask", "=", "True", ",", "newmaskname", "=", "\"\"", ",", "newtileshape", "=", "(", ")", ")", ":", "self", ".", "_saveas", "(", "filena...
Write the image to disk. Note that the created disk file is a snapshot, so it is not updated for possible later changes in the image object. `overwrite` If False, an exception is raised if the new image file already exists. Default is True. `ashdf5` If True, the image is created in HDF5 format, otherwise in casacore format. Default is casacore format. `copymask` By default the mask is written as well if the image has a mask. 'newmaskname` If the mask is written, the name is the same the original or `mask0` if the original mask has no name. Using this argument a different mask name can be given. `tileshape` Advanced users can give a new tile shape. See the :mod:`tables` module for more information about Tiled Storage Managers.
[ "Write", "the", "image", "to", "disk", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L521-L547
24,467
casacore/python-casacore
casacore/images/image.py
image.statistics
def statistics(self, axes=(), minmaxvalues=(), exclude=False, robust=True): """Calculate statistics for the image. Statistics are returned in a dict for the given axes. E.g. if axes [0,1] is given in a 3-dim image, the statistics are calculated for each plane along the 3rd axis. By default statistics are calculated for the entire image. `minmaxvalues` can be given to include or exclude pixels with values in the given range. If only one value is given, min=-abs(val) and max=abs(val). By default robust statistics (Median, MedAbsDevMed, and Quartile) are calculated too. """ return self._statistics(self._adaptAxes(axes), "", minmaxvalues, exclude, robust)
python
def statistics(self, axes=(), minmaxvalues=(), exclude=False, robust=True): return self._statistics(self._adaptAxes(axes), "", minmaxvalues, exclude, robust)
[ "def", "statistics", "(", "self", ",", "axes", "=", "(", ")", ",", "minmaxvalues", "=", "(", ")", ",", "exclude", "=", "False", ",", "robust", "=", "True", ")", ":", "return", "self", ".", "_statistics", "(", "self", ".", "_adaptAxes", "(", "axes", ...
Calculate statistics for the image. Statistics are returned in a dict for the given axes. E.g. if axes [0,1] is given in a 3-dim image, the statistics are calculated for each plane along the 3rd axis. By default statistics are calculated for the entire image. `minmaxvalues` can be given to include or exclude pixels with values in the given range. If only one value is given, min=-abs(val) and max=abs(val). By default robust statistics (Median, MedAbsDevMed, and Quartile) are calculated too.
[ "Calculate", "statistics", "for", "the", "image", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L549-L565
24,468
casacore/python-casacore
casacore/images/image.py
image.regrid
def regrid(self, axes, coordsys, outname="", overwrite=True, outshape=(), interpolation="linear", decimate=10, replicate=False, refchange=True, forceregrid=False): """Regrid the image to a new image object. Regrid the image on the given axes to the given coordinate system. The output is stored in the given file; it no file name is given a temporary image is made. If the output shape is empty, the old shape is used. `replicate=True` means replication rather than regridding. """ return image(self._regrid(self._adaptAxes(axes), outname, overwrite, outshape, coordsys.dict(), interpolation, decimate, replicate, refchange, forceregrid))
python
def regrid(self, axes, coordsys, outname="", overwrite=True, outshape=(), interpolation="linear", decimate=10, replicate=False, refchange=True, forceregrid=False): return image(self._regrid(self._adaptAxes(axes), outname, overwrite, outshape, coordsys.dict(), interpolation, decimate, replicate, refchange, forceregrid))
[ "def", "regrid", "(", "self", ",", "axes", ",", "coordsys", ",", "outname", "=", "\"\"", ",", "overwrite", "=", "True", ",", "outshape", "=", "(", ")", ",", "interpolation", "=", "\"linear\"", ",", "decimate", "=", "10", ",", "replicate", "=", "False",...
Regrid the image to a new image object. Regrid the image on the given axes to the given coordinate system. The output is stored in the given file; it no file name is given a temporary image is made. If the output shape is empty, the old shape is used. `replicate=True` means replication rather than regridding.
[ "Regrid", "the", "image", "to", "a", "new", "image", "object", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L567-L584
24,469
casacore/python-casacore
casacore/images/image.py
image.view
def view(self, tempname='/tmp/tempimage'): """Display the image using casaviewer. If the image is not persistent, a copy will be made that the user has to delete once viewing has finished. The name of the copy can be given in argument `tempname`. Default is '/tmp/tempimage'. """ import os # Test if casaviewer can be found. # On OS-X 'which' always returns 0, so use test on top of it. if os.system('test -x `which casaviewer` > /dev/null 2>&1') == 0: six.print_("Starting casaviewer in the background ...") self.unlock() if self.ispersistent(): os.system('casaviewer ' + self.name() + ' &') elif len(tempname) > 0: six.print_(" making a persistent copy in " + tempname) six.print_(" which should be deleted after the viewer has ended") self.saveas(tempname) os.system('casaviewer ' + tempname + ' &') else: six.print_("Cannot view because the image is in memory only.") six.print_("You can browse a persistent copy of the image like:") six.print_(" t.view('/tmp/tempimage')") else: six.print_("casaviewer cannot be found")
python
def view(self, tempname='/tmp/tempimage'): import os # Test if casaviewer can be found. # On OS-X 'which' always returns 0, so use test on top of it. if os.system('test -x `which casaviewer` > /dev/null 2>&1') == 0: six.print_("Starting casaviewer in the background ...") self.unlock() if self.ispersistent(): os.system('casaviewer ' + self.name() + ' &') elif len(tempname) > 0: six.print_(" making a persistent copy in " + tempname) six.print_(" which should be deleted after the viewer has ended") self.saveas(tempname) os.system('casaviewer ' + tempname + ' &') else: six.print_("Cannot view because the image is in memory only.") six.print_("You can browse a persistent copy of the image like:") six.print_(" t.view('/tmp/tempimage')") else: six.print_("casaviewer cannot be found")
[ "def", "view", "(", "self", ",", "tempname", "=", "'/tmp/tempimage'", ")", ":", "import", "os", "# Test if casaviewer can be found.", "# On OS-X 'which' always returns 0, so use test on top of it.", "if", "os", ".", "system", "(", "'test -x `which casaviewer` > /dev/null 2>&1'"...
Display the image using casaviewer. If the image is not persistent, a copy will be made that the user has to delete once viewing has finished. The name of the copy can be given in argument `tempname`. Default is '/tmp/tempimage'.
[ "Display", "the", "image", "using", "casaviewer", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L586-L612
24,470
casacore/python-casacore
setup.py
find_library_file
def find_library_file(libname): """ Try to get the directory of the specified library. It adds to the search path the library paths given to distutil's build_ext. """ # Use a dummy argument parser to get user specified library dirs parser = argparse.ArgumentParser(add_help=False) parser.add_argument("--library-dirs", "-L", default='') args, unknown = parser.parse_known_args() user_lib_dirs = args.library_dirs.split(':') # Append default search path (not a complete list) lib_dirs = user_lib_dirs + [os.path.join(sys.prefix, 'lib'), '/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] compiler = ccompiler.new_compiler() return compiler.find_library_file(lib_dirs, libname)
python
def find_library_file(libname): # Use a dummy argument parser to get user specified library dirs parser = argparse.ArgumentParser(add_help=False) parser.add_argument("--library-dirs", "-L", default='') args, unknown = parser.parse_known_args() user_lib_dirs = args.library_dirs.split(':') # Append default search path (not a complete list) lib_dirs = user_lib_dirs + [os.path.join(sys.prefix, 'lib'), '/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] compiler = ccompiler.new_compiler() return compiler.find_library_file(lib_dirs, libname)
[ "def", "find_library_file", "(", "libname", ")", ":", "# Use a dummy argument parser to get user specified library dirs", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "parser", ".", "add_argument", "(", "\"--library-dirs\"", ",", ...
Try to get the directory of the specified library. It adds to the search path the library paths given to distutil's build_ext.
[ "Try", "to", "get", "the", "directory", "of", "the", "specified", "library", ".", "It", "adds", "to", "the", "search", "path", "the", "library", "paths", "given", "to", "distutil", "s", "build_ext", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/setup.py#L40-L57
24,471
casacore/python-casacore
setup.py
find_boost
def find_boost(): """Find the name of the boost-python library. Returns None if none is found.""" short_version = "{}{}".format(sys.version_info[0], sys.version_info[1]) boostlibnames = ['boost_python-py' + short_version, 'boost_python' + short_version, 'boost_python', ] if sys.version_info[0] == 2: boostlibnames += ["boost_python-mt"] else: boostlibnames += ["boost_python3-mt"] for libboostname in boostlibnames: if find_library_file(libboostname): return libboostname warnings.warn(no_boost_error) return boostlibnames[0]
python
def find_boost(): short_version = "{}{}".format(sys.version_info[0], sys.version_info[1]) boostlibnames = ['boost_python-py' + short_version, 'boost_python' + short_version, 'boost_python', ] if sys.version_info[0] == 2: boostlibnames += ["boost_python-mt"] else: boostlibnames += ["boost_python3-mt"] for libboostname in boostlibnames: if find_library_file(libboostname): return libboostname warnings.warn(no_boost_error) return boostlibnames[0]
[ "def", "find_boost", "(", ")", ":", "short_version", "=", "\"{}{}\"", ".", "format", "(", "sys", ".", "version_info", "[", "0", "]", ",", "sys", ".", "version_info", "[", "1", "]", ")", "boostlibnames", "=", "[", "'boost_python-py'", "+", "short_version", ...
Find the name of the boost-python library. Returns None if none is found.
[ "Find", "the", "name", "of", "the", "boost", "-", "python", "library", ".", "Returns", "None", "if", "none", "is", "found", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/setup.py#L64-L80
24,472
casacore/python-casacore
casacore/tables/tablerow.py
_tablerow.put
def put(self, rownr, value, matchingfields=True): """Put the values into the given row. The value should be a dict (as returned by method :func:`get`. The names of the fields in the dict should match the names of the columns used in the `tablerow` object. `matchingfields=True` means that the value may contain more fields and only fields matching a column name will be used. """ self._put(rownr, value, matchingfields)
python
def put(self, rownr, value, matchingfields=True): self._put(rownr, value, matchingfields)
[ "def", "put", "(", "self", ",", "rownr", ",", "value", ",", "matchingfields", "=", "True", ")", ":", "self", ".", "_put", "(", "rownr", ",", "value", ",", "matchingfields", ")" ]
Put the values into the given row. The value should be a dict (as returned by method :func:`get`. The names of the fields in the dict should match the names of the columns used in the `tablerow` object. `matchingfields=True` means that the value may contain more fields and only fields matching a column name will be used.
[ "Put", "the", "values", "into", "the", "given", "row", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tablerow.py#L52-L63
24,473
casacore/python-casacore
casacore/quanta/quantity.py
quantity
def quantity(*args): """Create a quantity. This can be from a scalar or vector. Example:: q1 = quantity(1.0, "km/s") q2 = quantity("1km/s") q1 = quantity([1.0,2.0], "km/s") """ if len(args) == 1: if isinstance(args[0], str): # use copy constructor to create quantity from string return Quantity(from_string(args[0])) elif isinstance(args[0], dict): if hasattr(args[0]["value"], "__len__"): return QuantVec(from_dict_v(args[0])) else: return Quantity(from_dict(args[0])) elif isinstance(args[0], Quantity) or isinstance(args[0], QuantVec): return args[0] else: raise TypeError("Invalid argument type for") else: if hasattr(args[0], "__len__"): return QuantVec(*args) else: return Quantity(*args)
python
def quantity(*args): if len(args) == 1: if isinstance(args[0], str): # use copy constructor to create quantity from string return Quantity(from_string(args[0])) elif isinstance(args[0], dict): if hasattr(args[0]["value"], "__len__"): return QuantVec(from_dict_v(args[0])) else: return Quantity(from_dict(args[0])) elif isinstance(args[0], Quantity) or isinstance(args[0], QuantVec): return args[0] else: raise TypeError("Invalid argument type for") else: if hasattr(args[0], "__len__"): return QuantVec(*args) else: return Quantity(*args)
[ "def", "quantity", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "str", ")", ":", "# use copy constructor to create quantity from string", "return", "Quantity", "(", "from_st...
Create a quantity. This can be from a scalar or vector. Example:: q1 = quantity(1.0, "km/s") q2 = quantity("1km/s") q1 = quantity([1.0,2.0], "km/s")
[ "Create", "a", "quantity", ".", "This", "can", "be", "from", "a", "scalar", "or", "vector", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/quanta/quantity.py#L43-L70
24,474
casacore/python-casacore
casacore/util/substitute.py
getvariable
def getvariable(name): """Get the value of a local variable somewhere in the call stack.""" import inspect fr = inspect.currentframe() try: while fr: fr = fr.f_back vars = fr.f_locals if name in vars: return vars[name] except: pass return None
python
def getvariable(name): import inspect fr = inspect.currentframe() try: while fr: fr = fr.f_back vars = fr.f_locals if name in vars: return vars[name] except: pass return None
[ "def", "getvariable", "(", "name", ")", ":", "import", "inspect", "fr", "=", "inspect", ".", "currentframe", "(", ")", "try", ":", "while", "fr", ":", "fr", "=", "fr", ".", "f_back", "vars", "=", "fr", ".", "f_locals", "if", "name", "in", "vars", "...
Get the value of a local variable somewhere in the call stack.
[ "Get", "the", "value", "of", "a", "local", "variable", "somewhere", "in", "the", "call", "stack", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/util/substitute.py#L47-L59
24,475
casacore/python-casacore
casacore/util/substitute.py
substitute
def substitute(s, objlist=(), globals={}, locals={}): """Substitute global python variables in a command string. This function parses a string and tries to substitute parts like `$name` by their value. It is uses by :mod:`image` and :mod:`table` to handle image and table objects in a command, but also other variables (integers, strings, etc.) can be substituted. The following rules apply: 1. A name must start with an underscore or alphabetic, followed by zero or more alphanumerics and underscores. 2. String parts enclosed in single or double quotes are literals and are left untouched. Furthermore a $ can be escaped by a backslash, which is useful if an environment variable is used. Note that an extra backslash is required in Python to escape the backslash. The output contains the quotes and backslashes. 3. A variable is looked up in the given local and global namespaces. 4. If the variable `name` has a vector value, its substitution is enclosed in square brackets and separated by commas. 5. A string value is enclosed in double quotes. If the value contains a double quote, that quote is enclosed in single quotes. 6. If the name's value has a type mentioned in the argument `objlist`, it is substituted by `$n` (where n is a sequence number) and its value is added to the objects of that type in `objlist`. 7. If the name is unknown or has an unknown type, it is left untouched. The `objlist` argument is a list of tuples or lists where each tuple or list has three fields: 1. The first field is the object type (e.g. `table`) 2. The second field is a prefix for the sequence number (usually empty). E.g. regions could have prefix 'r' resulting in a substitution like `$r1`. 3. The third field is a list of objects to be substituted. New objects get appended to it. Usually the list is initially empty. Apart from substituting variables, it also substitutes `$(expression)` by the expression result. It correctly handles parentheses and quotes in the expression. For example:: >>> a = 2 >>> b = 3 >>> substitute('$(a+b)+$a') '5+2' >>> substitute('$(a+b+a)') '7' >>> substitute('$((a+b)+$a)') '$((a+b)+$a)' >>> substitute('$((a+b)*(a+b))') '25' >>> substitute('$(len("ab cd( de"))') '9' Substitution is NOT recursive. E.g. if a=1 and b="$a", the result of substitute("$b") is "$a" and not 1. """ # Get the local variables at the caller level if not given. if not locals: locals = getlocals(3) # Initialize some variables. backslash = False dollar = False nparen = 0 name = '' evalstr = '' squote = False dquote = False out = '' # Loop through the entire string. for tmp in s: if backslash: out += tmp backslash = False continue # If a dollar is found, we might have a name or expression. # Alphabetics and underscore are always part of name. if dollar and nparen == 0: if tmp == '_' or ('a' <= tmp <= 'z') or ('A' <= tmp <= 'Z'): name += tmp continue # Numerics are only part if not first character. if '0' <= tmp <= '9' and name != '': name += tmp continue # $( indicates the start of an expression to evaluate. if tmp == '(' and name == '': nparen = 1 evalstr = '' continue # End of name found. Try to substitute. out += substitutename(name, objlist, globals, locals) dollar = False # Handle possible single or double quotes. if tmp == '"' and not squote: dquote = not dquote elif tmp == "'" and not dquote: squote = not squote if not dquote and not squote: # Count the number of balanced parentheses # (outside quoted strings) in the subexpression. if nparen > 0: if tmp == '(': nparen += 1 elif tmp == ')': nparen -= 1 if nparen == 0: # The last closing parenthese is found. # Evaluate the subexpression. # Add the result to the output. out += substituteexpr(evalstr, globals, locals) dollar = False evalstr += tmp continue # Set a switch if we have a dollar (outside quoted # and eval strings). if tmp == '$': dollar = True name = '' continue # No special character; add it to output or evalstr. # Set a switch if we have a backslash. if nparen == 0: out += tmp else: evalstr += tmp if tmp == '\\': backslash = True # The entire string has been handled. # Substitute a possible last name. # Insert a possible incomplete eval string as such. if dollar: out += substitutename(name, objlist, globals, locals) else: if nparen > 0: out += '$(' + evalstr return out
python
def substitute(s, objlist=(), globals={}, locals={}): # Get the local variables at the caller level if not given. if not locals: locals = getlocals(3) # Initialize some variables. backslash = False dollar = False nparen = 0 name = '' evalstr = '' squote = False dquote = False out = '' # Loop through the entire string. for tmp in s: if backslash: out += tmp backslash = False continue # If a dollar is found, we might have a name or expression. # Alphabetics and underscore are always part of name. if dollar and nparen == 0: if tmp == '_' or ('a' <= tmp <= 'z') or ('A' <= tmp <= 'Z'): name += tmp continue # Numerics are only part if not first character. if '0' <= tmp <= '9' and name != '': name += tmp continue # $( indicates the start of an expression to evaluate. if tmp == '(' and name == '': nparen = 1 evalstr = '' continue # End of name found. Try to substitute. out += substitutename(name, objlist, globals, locals) dollar = False # Handle possible single or double quotes. if tmp == '"' and not squote: dquote = not dquote elif tmp == "'" and not dquote: squote = not squote if not dquote and not squote: # Count the number of balanced parentheses # (outside quoted strings) in the subexpression. if nparen > 0: if tmp == '(': nparen += 1 elif tmp == ')': nparen -= 1 if nparen == 0: # The last closing parenthese is found. # Evaluate the subexpression. # Add the result to the output. out += substituteexpr(evalstr, globals, locals) dollar = False evalstr += tmp continue # Set a switch if we have a dollar (outside quoted # and eval strings). if tmp == '$': dollar = True name = '' continue # No special character; add it to output or evalstr. # Set a switch if we have a backslash. if nparen == 0: out += tmp else: evalstr += tmp if tmp == '\\': backslash = True # The entire string has been handled. # Substitute a possible last name. # Insert a possible incomplete eval string as such. if dollar: out += substitutename(name, objlist, globals, locals) else: if nparen > 0: out += '$(' + evalstr return out
[ "def", "substitute", "(", "s", ",", "objlist", "=", "(", ")", ",", "globals", "=", "{", "}", ",", "locals", "=", "{", "}", ")", ":", "# Get the local variables at the caller level if not given.", "if", "not", "locals", ":", "locals", "=", "getlocals", "(", ...
Substitute global python variables in a command string. This function parses a string and tries to substitute parts like `$name` by their value. It is uses by :mod:`image` and :mod:`table` to handle image and table objects in a command, but also other variables (integers, strings, etc.) can be substituted. The following rules apply: 1. A name must start with an underscore or alphabetic, followed by zero or more alphanumerics and underscores. 2. String parts enclosed in single or double quotes are literals and are left untouched. Furthermore a $ can be escaped by a backslash, which is useful if an environment variable is used. Note that an extra backslash is required in Python to escape the backslash. The output contains the quotes and backslashes. 3. A variable is looked up in the given local and global namespaces. 4. If the variable `name` has a vector value, its substitution is enclosed in square brackets and separated by commas. 5. A string value is enclosed in double quotes. If the value contains a double quote, that quote is enclosed in single quotes. 6. If the name's value has a type mentioned in the argument `objlist`, it is substituted by `$n` (where n is a sequence number) and its value is added to the objects of that type in `objlist`. 7. If the name is unknown or has an unknown type, it is left untouched. The `objlist` argument is a list of tuples or lists where each tuple or list has three fields: 1. The first field is the object type (e.g. `table`) 2. The second field is a prefix for the sequence number (usually empty). E.g. regions could have prefix 'r' resulting in a substitution like `$r1`. 3. The third field is a list of objects to be substituted. New objects get appended to it. Usually the list is initially empty. Apart from substituting variables, it also substitutes `$(expression)` by the expression result. It correctly handles parentheses and quotes in the expression. For example:: >>> a = 2 >>> b = 3 >>> substitute('$(a+b)+$a') '5+2' >>> substitute('$(a+b+a)') '7' >>> substitute('$((a+b)+$a)') '$((a+b)+$a)' >>> substitute('$((a+b)*(a+b))') '25' >>> substitute('$(len("ab cd( de"))') '9' Substitution is NOT recursive. E.g. if a=1 and b="$a", the result of substitute("$b") is "$a" and not 1.
[ "Substitute", "global", "python", "variables", "in", "a", "command", "string", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/util/substitute.py#L62-L206
24,476
casacore/python-casacore
casacore/tables/table.py
taql
def taql(command, style='Python', tables=[], globals={}, locals={}): """Execute a TaQL command and return a table object. A `TaQL <../../doc/199.html>`_ command is an SQL-like command to do a selection of rows and/or columns in a table. The default style used in a TaQL command is python, which means 0-based indexing, C-ordered arrays, and non-inclusive end in ranges. It is possible to use python variables directly in the command using `$var` where `var` is the name of the variable to use. For example:: t = table('3c343.MS') value = 5.1 t1 = taql('select from $t where COL > $value') In this example the table `$t` is replaced by a sequence number (such as `$1`) and `$value` by its value 5.1. The table object of `t` will be appended to a copy of the `tables` argument such that the sequence number inserted matches the table object in the list. The more advanced user can already use `$n` in the query string and supply the associated table object in the `tables` argument (where `n` represents the (n-1)th `tables` element). The :func:`query` command makes use of this feature. The arguments `globals` and `locals` can be used to pass in a dict containing the possible variables used in the TaQL command. They can be obtained with the python functions locals() and globals(). If `locals` is empty, the local variables in the calling function will be used, so normally one does not need to use these arguments. """ # Substitute possible tables given as $name. cmd = command # Copy the tables argument and make sure it is a list tabs = [] for tab in tables: tabs += [tab] try: import casacore.util if len(locals) == 0: # local variables in caller are 3 levels up from getlocals locals = casacore.util.getlocals(3) cmd = casacore.util.substitute(cmd, [(table, '', tabs)], globals, locals) except Exception: pass if style: cmd = 'using style ' + style + ' ' + cmd tab = table(cmd, tabs, _oper=2) result = tab._getcalcresult() # If result is empty, it was a normal TaQL command resulting in a table. # Otherwise it is a record containing calc values. if len(result) == 0: return tab return result['values']
python
def taql(command, style='Python', tables=[], globals={}, locals={}): # Substitute possible tables given as $name. cmd = command # Copy the tables argument and make sure it is a list tabs = [] for tab in tables: tabs += [tab] try: import casacore.util if len(locals) == 0: # local variables in caller are 3 levels up from getlocals locals = casacore.util.getlocals(3) cmd = casacore.util.substitute(cmd, [(table, '', tabs)], globals, locals) except Exception: pass if style: cmd = 'using style ' + style + ' ' + cmd tab = table(cmd, tabs, _oper=2) result = tab._getcalcresult() # If result is empty, it was a normal TaQL command resulting in a table. # Otherwise it is a record containing calc values. if len(result) == 0: return tab return result['values']
[ "def", "taql", "(", "command", ",", "style", "=", "'Python'", ",", "tables", "=", "[", "]", ",", "globals", "=", "{", "}", ",", "locals", "=", "{", "}", ")", ":", "# Substitute possible tables given as $name.", "cmd", "=", "command", "# Copy the tables argum...
Execute a TaQL command and return a table object. A `TaQL <../../doc/199.html>`_ command is an SQL-like command to do a selection of rows and/or columns in a table. The default style used in a TaQL command is python, which means 0-based indexing, C-ordered arrays, and non-inclusive end in ranges. It is possible to use python variables directly in the command using `$var` where `var` is the name of the variable to use. For example:: t = table('3c343.MS') value = 5.1 t1 = taql('select from $t where COL > $value') In this example the table `$t` is replaced by a sequence number (such as `$1`) and `$value` by its value 5.1. The table object of `t` will be appended to a copy of the `tables` argument such that the sequence number inserted matches the table object in the list. The more advanced user can already use `$n` in the query string and supply the associated table object in the `tables` argument (where `n` represents the (n-1)th `tables` element). The :func:`query` command makes use of this feature. The arguments `globals` and `locals` can be used to pass in a dict containing the possible variables used in the TaQL command. They can be obtained with the python functions locals() and globals(). If `locals` is empty, the local variables in the calling function will be used, so normally one does not need to use these arguments.
[ "Execute", "a", "TaQL", "command", "and", "return", "a", "table", "object", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L104-L162
24,477
casacore/python-casacore
casacore/tables/table.py
table.iter
def iter(self, columnnames, order='', sort=True): """Return a tableiter object. :class:`tableiter` lets one iterate over a table by returning in each iteration step a reference table containing equal values for the given columns. By default a sort is done on the given columns to get the correct iteration order. `order` | 'ascending' is iterate in ascending order (is the default). | 'descending' is iterate in descending order. `sort=False` do not sort (because table is already in correct order). For example, iterate by time through a measurementset table:: t = table('3c343.MS') for ts in t.iter('TIME'): print ts.nrows() """ from .tableiter import tableiter return tableiter(self, columnnames, order, sort)
python
def iter(self, columnnames, order='', sort=True): from .tableiter import tableiter return tableiter(self, columnnames, order, sort)
[ "def", "iter", "(", "self", ",", "columnnames", ",", "order", "=", "''", ",", "sort", "=", "True", ")", ":", "from", ".", "tableiter", "import", "tableiter", "return", "tableiter", "(", "self", ",", "columnnames", ",", "order", ",", "sort", ")" ]
Return a tableiter object. :class:`tableiter` lets one iterate over a table by returning in each iteration step a reference table containing equal values for the given columns. By default a sort is done on the given columns to get the correct iteration order. `order` | 'ascending' is iterate in ascending order (is the default). | 'descending' is iterate in descending order. `sort=False` do not sort (because table is already in correct order). For example, iterate by time through a measurementset table:: t = table('3c343.MS') for ts in t.iter('TIME'): print ts.nrows()
[ "Return", "a", "tableiter", "object", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L507-L530
24,478
casacore/python-casacore
casacore/tables/table.py
table.index
def index(self, columnnames, sort=True): """Return a tableindex object. :class:`tableindex` lets one get the row numbers of the rows holding given values for the columns for which the index is created. It uses an in-memory index on which a binary search is done. By default the table is sorted on the given columns to get the correct index order. For example:: t = table('3c343.MS') tinx = t.index('ANTENNA1') print tinx.rownumbers(0) # print rownrs containing ANTENNA1=0 """ from .tableindex import tableindex return tableindex(self, columnnames, sort)
python
def index(self, columnnames, sort=True): from .tableindex import tableindex return tableindex(self, columnnames, sort)
[ "def", "index", "(", "self", ",", "columnnames", ",", "sort", "=", "True", ")", ":", "from", ".", "tableindex", "import", "tableindex", "return", "tableindex", "(", "self", ",", "columnnames", ",", "sort", ")" ]
Return a tableindex object. :class:`tableindex` lets one get the row numbers of the rows holding given values for the columns for which the index is created. It uses an in-memory index on which a binary search is done. By default the table is sorted on the given columns to get the correct index order. For example:: t = table('3c343.MS') tinx = t.index('ANTENNA1') print tinx.rownumbers(0) # print rownrs containing ANTENNA1=0
[ "Return", "a", "tableindex", "object", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L532-L549
24,479
casacore/python-casacore
casacore/tables/table.py
table.toascii
def toascii(self, asciifile, headerfile='', columnnames=(), sep=' ', precision=(), usebrackets=True): """Write the table in ASCII format. It is approximately the inverse of the from-ASCII-contructor. `asciifile` The name of the resulting ASCII file. `headerfile` The name of an optional file containing the header info. If not given or if equal to argument `asciifile`, the headers are written at the beginning of the ASCII file. `columnnames` The names of the columns to be written. If not given or if the first name is empty, all columns are written. `sep` The separator to be used between values. Only the first character of a string is used. If not given or mepty, a blank is used. `precision` For each column the precision can be given. It is only used for columns containing floating point numbers. A value <=0 means using the default which is 9 for single and 18 for double precision. `usebrackets` If True, arrays and records are written enclosed in []. Multi-dimensional arrays have [] per dimension. In this way variable shaped array can be read back correctly. However, it is not supported by :func:`tablefromascii`. If False, records are not written and arrays are written linearly with the shape defined in the header as supported byI :func:`tablefromascii`. Note that columns containing records or variable shaped arrays are ignored, because they cannot be written to ASCII. It is told which columns are ignored. For example:: t = table('3c343.MS') t1 = t.query('ANTENNA1 != ANTENNA2') # do row selection t1.toascii ('3c343.txt') # write selection as ASCII """ msg = self._toascii(asciifile, headerfile, columnnames, sep, precision, usebrackets) if len(msg) > 0: six.print_(msg)
python
def toascii(self, asciifile, headerfile='', columnnames=(), sep=' ', precision=(), usebrackets=True): msg = self._toascii(asciifile, headerfile, columnnames, sep, precision, usebrackets) if len(msg) > 0: six.print_(msg)
[ "def", "toascii", "(", "self", ",", "asciifile", ",", "headerfile", "=", "''", ",", "columnnames", "=", "(", ")", ",", "sep", "=", "' '", ",", "precision", "=", "(", ")", ",", "usebrackets", "=", "True", ")", ":", "msg", "=", "self", ".", "_toascii...
Write the table in ASCII format. It is approximately the inverse of the from-ASCII-contructor. `asciifile` The name of the resulting ASCII file. `headerfile` The name of an optional file containing the header info. If not given or if equal to argument `asciifile`, the headers are written at the beginning of the ASCII file. `columnnames` The names of the columns to be written. If not given or if the first name is empty, all columns are written. `sep` The separator to be used between values. Only the first character of a string is used. If not given or mepty, a blank is used. `precision` For each column the precision can be given. It is only used for columns containing floating point numbers. A value <=0 means using the default which is 9 for single and 18 for double precision. `usebrackets` If True, arrays and records are written enclosed in []. Multi-dimensional arrays have [] per dimension. In this way variable shaped array can be read back correctly. However, it is not supported by :func:`tablefromascii`. If False, records are not written and arrays are written linearly with the shape defined in the header as supported byI :func:`tablefromascii`. Note that columns containing records or variable shaped arrays are ignored, because they cannot be written to ASCII. It is told which columns are ignored. For example:: t = table('3c343.MS') t1 = t.query('ANTENNA1 != ANTENNA2') # do row selection t1.toascii ('3c343.txt') # write selection as ASCII
[ "Write", "the", "table", "in", "ASCII", "format", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L582-L627
24,480
casacore/python-casacore
casacore/tables/table.py
table.copy
def copy(self, newtablename, deep=False, valuecopy=False, dminfo={}, endian='aipsrc', memorytable=False, copynorows=False): """Copy the table and return a table object for the copy. It copies all data in the columns and keywords. Besides the table, all its subtables are copied too. By default a shallow copy is made (usually by copying files). It means that the copy of a reference table is also a reference table. Use `deep=True` to make a deep copy which turns a reference table into a normal table. `deep=True` a deep copy of a reference table is made. `valuecopy=True` values are copied, which reorganizes normal tables and removes wasted space. It implies `deep=True`. It is slower than a normal copy. `dminfo` gives the option to specify data managers to change the way columns are stored. This is a dict as returned by method :func:`getdminfo`. `endian` specifies the endianness of the new table when a deep copy is made: | 'little' = as little endian | 'big' = as big endian | 'local' = use the endianness of the machine being used | 'aipsrc' = use as defined in an .aipsrc file (defaults to local) `memorytable=True` do not copy to disk, but to a table kept in memory. `copynorows=True` only copy the column layout and keywords, but no data. For example:: t = table('3c343.MS') t1 = t.query('ANTENNA1 != ANTENNA2') # do row selection t2 = t1.copy ('3c343.sel', True) # make deep copy t2 = t.copy ('new.tab', True, True) # reorganize storage """ t = self._copy(newtablename, memorytable, deep, valuecopy, endian, dminfo, copynorows) # copy returns a Table object, so turn that into table. return table(t, _oper=3)
python
def copy(self, newtablename, deep=False, valuecopy=False, dminfo={}, endian='aipsrc', memorytable=False, copynorows=False): t = self._copy(newtablename, memorytable, deep, valuecopy, endian, dminfo, copynorows) # copy returns a Table object, so turn that into table. return table(t, _oper=3)
[ "def", "copy", "(", "self", ",", "newtablename", ",", "deep", "=", "False", ",", "valuecopy", "=", "False", ",", "dminfo", "=", "{", "}", ",", "endian", "=", "'aipsrc'", ",", "memorytable", "=", "False", ",", "copynorows", "=", "False", ")", ":", "t"...
Copy the table and return a table object for the copy. It copies all data in the columns and keywords. Besides the table, all its subtables are copied too. By default a shallow copy is made (usually by copying files). It means that the copy of a reference table is also a reference table. Use `deep=True` to make a deep copy which turns a reference table into a normal table. `deep=True` a deep copy of a reference table is made. `valuecopy=True` values are copied, which reorganizes normal tables and removes wasted space. It implies `deep=True`. It is slower than a normal copy. `dminfo` gives the option to specify data managers to change the way columns are stored. This is a dict as returned by method :func:`getdminfo`. `endian` specifies the endianness of the new table when a deep copy is made: | 'little' = as little endian | 'big' = as big endian | 'local' = use the endianness of the machine being used | 'aipsrc' = use as defined in an .aipsrc file (defaults to local) `memorytable=True` do not copy to disk, but to a table kept in memory. `copynorows=True` only copy the column layout and keywords, but no data. For example:: t = table('3c343.MS') t1 = t.query('ANTENNA1 != ANTENNA2') # do row selection t2 = t1.copy ('3c343.sel', True) # make deep copy t2 = t.copy ('new.tab', True, True) # reorganize storage
[ "Copy", "the", "table", "and", "return", "a", "table", "object", "for", "the", "copy", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L638-L679
24,481
casacore/python-casacore
casacore/tables/table.py
table.copyrows
def copyrows(self, outtable, startrowin=0, startrowout=-1, nrow=-1): """Copy the contents of rows from this table to outtable. The contents of the columns with matching names are copied. The other arguments can be used to specify where to start copying. By default the entire input table is appended to the output table. Rows are added to the output table if needed. `startrowin` Row where to start in the input table. `startrowout` Row where to start in the output table, | -1 means write at the end of the output table. `nrow` Number of rows to copy | -1 means from startrowin till the end of the input table The following example appends row to the table itself, thus doubles the number of rows:: t:=table('test.ms',readonly=F) t.copyrows(t) """ self._copyrows(outtable, startrowin, startrowout, nrow)
python
def copyrows(self, outtable, startrowin=0, startrowout=-1, nrow=-1): self._copyrows(outtable, startrowin, startrowout, nrow)
[ "def", "copyrows", "(", "self", ",", "outtable", ",", "startrowin", "=", "0", ",", "startrowout", "=", "-", "1", ",", "nrow", "=", "-", "1", ")", ":", "self", ".", "_copyrows", "(", "outtable", ",", "startrowin", ",", "startrowout", ",", "nrow", ")" ...
Copy the contents of rows from this table to outtable. The contents of the columns with matching names are copied. The other arguments can be used to specify where to start copying. By default the entire input table is appended to the output table. Rows are added to the output table if needed. `startrowin` Row where to start in the input table. `startrowout` Row where to start in the output table, | -1 means write at the end of the output table. `nrow` Number of rows to copy | -1 means from startrowin till the end of the input table The following example appends row to the table itself, thus doubles the number of rows:: t:=table('test.ms',readonly=F) t.copyrows(t)
[ "Copy", "the", "contents", "of", "rows", "from", "this", "table", "to", "outtable", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L681-L705
24,482
casacore/python-casacore
casacore/tables/table.py
table.rownumbers
def rownumbers(self, table=None): """Return a list containing the row numbers of this table. This method can be useful after a selection or a sort. It returns the row numbers of the rows in this table with respect to the given table. If no table is given, the original table is used. For example:: t = table('W53.MS') t1 = t.selectrows([1,3,5,7,9]) # select a few rows t1.rownumbers(t) # [1 3 5 7 9] t2 = t1.selectrows([2,5]) # select rows from the selection t2.rownumbers(t1) # [2 5] # rownrs of t2 in table t1 t2.rownumbers(t) # [3 9] # rownrs of t2 in t t2.rownumbers() # [3 9] The last statements show that the method returns the row numbers referring to the given table. Table t2 contains rows 2 and 5 in table t1, which are rows 3 and 9 in table t. """ if table is None: return self._rownumbers(Table()) return self._rownumbers(table)
python
def rownumbers(self, table=None): if table is None: return self._rownumbers(Table()) return self._rownumbers(table)
[ "def", "rownumbers", "(", "self", ",", "table", "=", "None", ")", ":", "if", "table", "is", "None", ":", "return", "self", ".", "_rownumbers", "(", "Table", "(", ")", ")", "return", "self", ".", "_rownumbers", "(", "table", ")" ]
Return a list containing the row numbers of this table. This method can be useful after a selection or a sort. It returns the row numbers of the rows in this table with respect to the given table. If no table is given, the original table is used. For example:: t = table('W53.MS') t1 = t.selectrows([1,3,5,7,9]) # select a few rows t1.rownumbers(t) # [1 3 5 7 9] t2 = t1.selectrows([2,5]) # select rows from the selection t2.rownumbers(t1) # [2 5] # rownrs of t2 in table t1 t2.rownumbers(t) # [3 9] # rownrs of t2 in t t2.rownumbers() # [3 9] The last statements show that the method returns the row numbers referring to the given table. Table t2 contains rows 2 and 5 in table t1, which are rows 3 and 9 in table t.
[ "Return", "a", "list", "containing", "the", "row", "numbers", "of", "this", "table", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L819-L847
24,483
casacore/python-casacore
casacore/tables/table.py
table.getcolshapestring
def getcolshapestring(self, columnname, startrow=0, nrow=-1, rowincr=1): """Get the shapes of all cells in the column in string format. It returns the shape in a string like [10,20,30]. If the column contains fixed shape arrays, a single shape is returned. Otherwise a list of shape strings is returned. The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). """ return self._getcolshapestring(columnname, startrow, nrow, rowincr, True)
python
def getcolshapestring(self, columnname, startrow=0, nrow=-1, rowincr=1): return self._getcolshapestring(columnname, startrow, nrow, rowincr, True)
[ "def", "getcolshapestring", "(", "self", ",", "columnname", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "return", "self", ".", "_getcolshapestring", "(", "columnname", ",", "startrow", ",", "nrow", ",", "r...
Get the shapes of all cells in the column in string format. It returns the shape in a string like [10,20,30]. If the column contains fixed shape arrays, a single shape is returned. Otherwise a list of shape strings is returned. The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1).
[ "Get", "the", "shapes", "of", "all", "cells", "in", "the", "column", "in", "string", "format", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L921-L936
24,484
casacore/python-casacore
casacore/tables/table.py
table.getcellnp
def getcellnp(self, columnname, rownr, nparray): """Get data from a column cell into the given numpy array . Get the contents of a cell containing an array into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column cell. Data type coercion will be done as needed. """ if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcellvh(columnname, rownr, nparray)
python
def getcellnp(self, columnname, rownr, nparray): if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcellvh(columnname, rownr, nparray)
[ "def", "getcellnp", "(", "self", ",", "columnname", ",", "rownr", ",", "nparray", ")", ":", "if", "not", "nparray", ".", "flags", ".", "c_contiguous", "or", "nparray", ".", "size", "==", "0", ":", "raise", "ValueError", "(", "\"Argument 'nparray' has to be a...
Get data from a column cell into the given numpy array . Get the contents of a cell containing an array into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column cell. Data type coercion will be done as needed.
[ "Get", "data", "from", "a", "column", "cell", "into", "the", "given", "numpy", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L963-L975
24,485
casacore/python-casacore
casacore/tables/table.py
table.getcellslice
def getcellslice(self, columnname, rownr, blc, trc, inc=[]): """Get a slice from a column cell holding an array. The columnname and (0-relative) rownr indicate the table cell. The slice to get is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing). """ return self._getcellslice(columnname, rownr, blc, trc, inc)
python
def getcellslice(self, columnname, rownr, blc, trc, inc=[]): return self._getcellslice(columnname, rownr, blc, trc, inc)
[ "def", "getcellslice", "(", "self", ",", "columnname", ",", "rownr", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ")", ":", "return", "self", ".", "_getcellslice", "(", "columnname", ",", "rownr", ",", "blc", ",", "trc", ",", "inc", ")" ]
Get a slice from a column cell holding an array. The columnname and (0-relative) rownr indicate the table cell. The slice to get is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing).
[ "Get", "a", "slice", "from", "a", "column", "cell", "holding", "an", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L977-L990
24,486
casacore/python-casacore
casacore/tables/table.py
table.getcellslicenp
def getcellslicenp(self, columnname, nparray, rownr, blc, trc, inc=[]): """Get a slice from a column cell into the given numpy array. The columnname and (0-relative) rownr indicate the table cell. The numpy array has to be C-contiguous with a shape matching the shape of the slice. Data type coercion will be done as needed. The slice to get is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing). """ if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcellslicevh(columnname, rownr, blc, trc, inc, nparray)
python
def getcellslicenp(self, columnname, nparray, rownr, blc, trc, inc=[]): if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcellslicevh(columnname, rownr, blc, trc, inc, nparray)
[ "def", "getcellslicenp", "(", "self", ",", "columnname", ",", "nparray", ",", "rownr", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ")", ":", "if", "not", "nparray", ".", "flags", ".", "c_contiguous", "or", "nparray", ".", "size", "==", "0", ...
Get a slice from a column cell into the given numpy array. The columnname and (0-relative) rownr indicate the table cell. The numpy array has to be C-contiguous with a shape matching the shape of the slice. Data type coercion will be done as needed. The slice to get is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing).
[ "Get", "a", "slice", "from", "a", "column", "cell", "into", "the", "given", "numpy", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L992-L1011
24,487
casacore/python-casacore
casacore/tables/table.py
table.getcolnp
def getcolnp(self, columnname, nparray, startrow=0, nrow=-1, rowincr=1): """Get the contents of a column or part of it into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column (part). Data type coercion will be done as needed. If the column contains arrays, they should all have the same shape. An exception is thrown if they differ in shape. In that case the method :func:`getvarcol` should be used instead. The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). """ if (not nparray.flags.c_contiguous) or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcolvh(columnname, startrow, nrow, rowincr, nparray)
python
def getcolnp(self, columnname, nparray, startrow=0, nrow=-1, rowincr=1): if (not nparray.flags.c_contiguous) or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcolvh(columnname, startrow, nrow, rowincr, nparray)
[ "def", "getcolnp", "(", "self", ",", "columnname", ",", "nparray", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "if", "(", "not", "nparray", ".", "flags", ".", "c_contiguous", ")", "or", "nparray", ".",...
Get the contents of a column or part of it into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column (part). Data type coercion will be done as needed. If the column contains arrays, they should all have the same shape. An exception is thrown if they differ in shape. In that case the method :func:`getvarcol` should be used instead. The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1).
[ "Get", "the", "contents", "of", "a", "column", "or", "part", "of", "it", "into", "the", "given", "numpy", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1036-L1054
24,488
casacore/python-casacore
casacore/tables/table.py
table.getcolslice
def getcolslice(self, columnname, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): """Get a slice from a table column holding arrays. The slice in each array is given by blc, trc, and inc (as in getcellslice). The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). It returns a numpy array where the first axis is formed by the column cells. The other axes are the array axes. """ return self._getcolslice(columnname, blc, trc, inc, startrow, nrow, rowincr)
python
def getcolslice(self, columnname, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): return self._getcolslice(columnname, blc, trc, inc, startrow, nrow, rowincr)
[ "def", "getcolslice", "(", "self", ",", "columnname", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "return", "self", ".", "_getcolslice", "(", "colum...
Get a slice from a table column holding arrays. The slice in each array is given by blc, trc, and inc (as in getcellslice). The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). It returns a numpy array where the first axis is formed by the column cells. The other axes are the array axes.
[ "Get", "a", "slice", "from", "a", "table", "column", "holding", "arrays", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1066-L1080
24,489
casacore/python-casacore
casacore/tables/table.py
table.getcolslicenp
def getcolslicenp(self, columnname, nparray, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): """Get a slice from a table column into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column (slice). Data type coercion will be done as needed. The slice in each array is given by blc, trc, and inc (as in getcellslice). The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). It returns a numpy array where the first axis is formed by the column cells. The other axes are the array axes. """ if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcolslicevh(columnname, blc, trc, inc, startrow, nrow, rowincr, nparray)
python
def getcolslicenp(self, columnname, nparray, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcolslicevh(columnname, blc, trc, inc, startrow, nrow, rowincr, nparray)
[ "def", "getcolslicenp", "(", "self", ",", "columnname", ",", "nparray", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "if", "not", "nparray", ".", "...
Get a slice from a table column into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column (slice). Data type coercion will be done as needed. The slice in each array is given by blc, trc, and inc (as in getcellslice). The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). It returns a numpy array where the first axis is formed by the column cells. The other axes are the array axes.
[ "Get", "a", "slice", "from", "a", "table", "column", "into", "the", "given", "numpy", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1082-L1102
24,490
casacore/python-casacore
casacore/tables/table.py
table.putcell
def putcell(self, columnname, rownr, value): """Put a value into one or more table cells. The columnname and (0-relative) rownrs indicate the table cells. rownr can be a single row number or a sequence of row numbers. If multiple rownrs are given, the given value is put in all those rows. The given value has to be convertible to the data type of the column. If the column contains scalar values, the given value must be a scalar. The value for a column holding arrays can be given as: - a scalar resulting in a 1-dim array of 1 element - a sequence (list, tuple) resulting in a 1-dim array - a numpy array of any dimensionality Note that the arrays in a column may have a fixed dimensionality or shape. In that case the dimensionality or shape of the array to put has to conform. """ self._putcell(columnname, rownr, value)
python
def putcell(self, columnname, rownr, value): self._putcell(columnname, rownr, value)
[ "def", "putcell", "(", "self", ",", "columnname", ",", "rownr", ",", "value", ")", ":", "self", ".", "_putcell", "(", "columnname", ",", "rownr", ",", "value", ")" ]
Put a value into one or more table cells. The columnname and (0-relative) rownrs indicate the table cells. rownr can be a single row number or a sequence of row numbers. If multiple rownrs are given, the given value is put in all those rows. The given value has to be convertible to the data type of the column. If the column contains scalar values, the given value must be a scalar. The value for a column holding arrays can be given as: - a scalar resulting in a 1-dim array of 1 element - a sequence (list, tuple) resulting in a 1-dim array - a numpy array of any dimensionality Note that the arrays in a column may have a fixed dimensionality or shape. In that case the dimensionality or shape of the array to put has to conform.
[ "Put", "a", "value", "into", "one", "or", "more", "table", "cells", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1104-L1124
24,491
casacore/python-casacore
casacore/tables/table.py
table.putcellslice
def putcellslice(self, columnname, rownr, value, blc, trc, inc=[]): """Put into a slice of a table cell holding an array. The columnname and (0-relative) rownr indicate the table cell. Unlike putcell only a single row can be given. The slice to put is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing). As in putcell the array can be given by a scalar, sequence, or numpy array. The shape of the array to put has to match the slice shape. """ self._putcellslice(columnname, rownr, value, blc, trc, inc)
python
def putcellslice(self, columnname, rownr, value, blc, trc, inc=[]): self._putcellslice(columnname, rownr, value, blc, trc, inc)
[ "def", "putcellslice", "(", "self", ",", "columnname", ",", "rownr", ",", "value", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ")", ":", "self", ".", "_putcellslice", "(", "columnname", ",", "rownr", ",", "value", ",", "blc", ",", "trc", ","...
Put into a slice of a table cell holding an array. The columnname and (0-relative) rownr indicate the table cell. Unlike putcell only a single row can be given. The slice to put is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing). As in putcell the array can be given by a scalar, sequence, or numpy array. The shape of the array to put has to match the slice shape.
[ "Put", "into", "a", "slice", "of", "a", "table", "cell", "holding", "an", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1126-L1144
24,492
casacore/python-casacore
casacore/tables/table.py
table.putcolslice
def putcolslice(self, columnname, value, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): """Put into a slice in a table column holding arrays. Its arguments are the same as for getcolslice and putcellslice. """ self._putcolslice(columnname, value, blc, trc, inc, startrow, nrow, rowincr)
python
def putcolslice(self, columnname, value, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): self._putcolslice(columnname, value, blc, trc, inc, startrow, nrow, rowincr)
[ "def", "putcolslice", "(", "self", ",", "columnname", ",", "value", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "self", ".", "_putcolslice", "(", ...
Put into a slice in a table column holding arrays. Its arguments are the same as for getcolslice and putcellslice.
[ "Put", "into", "a", "slice", "in", "a", "table", "column", "holding", "arrays", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1171-L1179
24,493
casacore/python-casacore
casacore/tables/table.py
table.addcols
def addcols(self, desc, dminfo={}, addtoparent=True): """Add one or more columns. Columns can always be added to a normal table. They can also be added to a reference table and optionally to its parent table. `desc` contains a description of the column(s) to be added. It can be given in three ways: - a dict created by :func:`maketabdesc`. In this way multiple columns can be added. - a dict created by :func:`makescacoldesc`, :func:`makearrcoldesc`, or :func:`makecoldesc`. In this way a single column can be added. - a dict created by :func:`getcoldesc`. The key 'name' containing the column name has to be defined in such a dict. `dminfo` can be used to provide detailed data manager info to tell how the column(s) have to be stored. The dminfo of an existing column can be obtained using method :func:`getdminfo`. `addtoparent` defines if the column should also be added to the parent table in case the current table is a reference table (result of selection). If True, it will be added to the parent if it does not exist yet. For example, add a column using the same data manager type as another column:: coldmi = t.getdminfo('colarrtsm') # get dminfo of existing column coldmi["NAME"] = 'tsm2' # give it a unique name t.addcols (maketabdesc(makearrcoldesc("colarrtsm2",0., ndim=2)), coldmi) """ tdesc = desc # Create a tabdesc if only a coldesc is given. if 'name' in desc: import casacore.tables.tableutil as pt if len(desc) == 2 and 'desc' in desc: # Given as output from makecoldesc tdesc = pt.maketabdesc(desc) elif 'valueType' in desc: # Given as output of getcoldesc (with a name field added) cd = pt.makecoldesc(desc['name'], desc) tdesc = pt.maketabdesc(cd) self._addcols(tdesc, dminfo, addtoparent) self._makerow()
python
def addcols(self, desc, dminfo={}, addtoparent=True): tdesc = desc # Create a tabdesc if only a coldesc is given. if 'name' in desc: import casacore.tables.tableutil as pt if len(desc) == 2 and 'desc' in desc: # Given as output from makecoldesc tdesc = pt.maketabdesc(desc) elif 'valueType' in desc: # Given as output of getcoldesc (with a name field added) cd = pt.makecoldesc(desc['name'], desc) tdesc = pt.maketabdesc(cd) self._addcols(tdesc, dminfo, addtoparent) self._makerow()
[ "def", "addcols", "(", "self", ",", "desc", ",", "dminfo", "=", "{", "}", ",", "addtoparent", "=", "True", ")", ":", "tdesc", "=", "desc", "# Create a tabdesc if only a coldesc is given.", "if", "'name'", "in", "desc", ":", "import", "casacore", ".", "tables...
Add one or more columns. Columns can always be added to a normal table. They can also be added to a reference table and optionally to its parent table. `desc` contains a description of the column(s) to be added. It can be given in three ways: - a dict created by :func:`maketabdesc`. In this way multiple columns can be added. - a dict created by :func:`makescacoldesc`, :func:`makearrcoldesc`, or :func:`makecoldesc`. In this way a single column can be added. - a dict created by :func:`getcoldesc`. The key 'name' containing the column name has to be defined in such a dict. `dminfo` can be used to provide detailed data manager info to tell how the column(s) have to be stored. The dminfo of an existing column can be obtained using method :func:`getdminfo`. `addtoparent` defines if the column should also be added to the parent table in case the current table is a reference table (result of selection). If True, it will be added to the parent if it does not exist yet. For example, add a column using the same data manager type as another column:: coldmi = t.getdminfo('colarrtsm') # get dminfo of existing column coldmi["NAME"] = 'tsm2' # give it a unique name t.addcols (maketabdesc(makearrcoldesc("colarrtsm2",0., ndim=2)), coldmi)
[ "Add", "one", "or", "more", "columns", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1181-L1229
24,494
casacore/python-casacore
casacore/tables/table.py
table.renamecol
def renamecol(self, oldname, newname): """Rename a single table column. Renaming a column in a reference table does NOT rename the column in the referenced table. """ self._renamecol(oldname, newname) self._makerow()
python
def renamecol(self, oldname, newname): self._renamecol(oldname, newname) self._makerow()
[ "def", "renamecol", "(", "self", ",", "oldname", ",", "newname", ")", ":", "self", ".", "_renamecol", "(", "oldname", ",", "newname", ")", "self", ".", "_makerow", "(", ")" ]
Rename a single table column. Renaming a column in a reference table does NOT rename the column in the referenced table.
[ "Rename", "a", "single", "table", "column", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1231-L1239
24,495
casacore/python-casacore
casacore/tables/table.py
table.fieldnames
def fieldnames(self, keyword=''): """Get the names of the fields in a table keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub-struct can be obtained by giving a keyword name consisting of multiple parts separated by dots (e.g. 'key1.sub1.sub2'). If an empty keyword name is given (which is the default), all table keyword names are shown and its behaviour is the same as :func:`keywordnames`. Instead of a keyword name an index can be given which returns the names of the struct value of the i-th keyword. """ if isinstance(keyword, str): return self._getfieldnames('', keyword, -1) else: return self._getfieldnames('', '', keyword)
python
def fieldnames(self, keyword=''): if isinstance(keyword, str): return self._getfieldnames('', keyword, -1) else: return self._getfieldnames('', '', keyword)
[ "def", "fieldnames", "(", "self", ",", "keyword", "=", "''", ")", ":", "if", "isinstance", "(", "keyword", ",", "str", ")", ":", "return", "self", ".", "_getfieldnames", "(", "''", ",", "keyword", ",", "-", "1", ")", "else", ":", "return", "self", ...
Get the names of the fields in a table keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub-struct can be obtained by giving a keyword name consisting of multiple parts separated by dots (e.g. 'key1.sub1.sub2'). If an empty keyword name is given (which is the default), all table keyword names are shown and its behaviour is the same as :func:`keywordnames`. Instead of a keyword name an index can be given which returns the names of the struct value of the i-th keyword.
[ "Get", "the", "names", "of", "the", "fields", "in", "a", "table", "keyword", "value", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1263-L1283
24,496
casacore/python-casacore
casacore/tables/table.py
table.colfieldnames
def colfieldnames(self, columnname, keyword=''): """Get the names of the fields in a column keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub-struct can be obtained by giving a keyword name consisting of multiple parts separated by dots (e.g. 'key1.sub1.sub2'). If an empty keyword name is given (which is the default), all keyword names of the column are shown and its behaviour is the same as :func:`colkeywordnames`. Instead of a keyword name an index can be given which returns the names of the struct value of the i-th keyword. """ if isinstance(keyword, str): return self._getfieldnames(columnname, keyword, -1) else: return self._getfieldnames(columnname, '', keyword)
python
def colfieldnames(self, columnname, keyword=''): if isinstance(keyword, str): return self._getfieldnames(columnname, keyword, -1) else: return self._getfieldnames(columnname, '', keyword)
[ "def", "colfieldnames", "(", "self", ",", "columnname", ",", "keyword", "=", "''", ")", ":", "if", "isinstance", "(", "keyword", ",", "str", ")", ":", "return", "self", ".", "_getfieldnames", "(", "columnname", ",", "keyword", ",", "-", "1", ")", "else...
Get the names of the fields in a column keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub-struct can be obtained by giving a keyword name consisting of multiple parts separated by dots (e.g. 'key1.sub1.sub2'). If an empty keyword name is given (which is the default), all keyword names of the column are shown and its behaviour is the same as :func:`colkeywordnames`. Instead of a keyword name an index can be given which returns the names of the struct value of the i-th keyword.
[ "Get", "the", "names", "of", "the", "fields", "in", "a", "column", "keyword", "value", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1285-L1305
24,497
casacore/python-casacore
casacore/tables/table.py
table.getkeyword
def getkeyword(self, keyword): """Get the value of a table keyword. The value of a keyword can be a: - scalar which is returned as a normal python scalar. - an array which is returned as a numpy array. - a reference to a table which is returned as a string containing its name prefixed by 'Table :'. It can be opened using the normal table constructor which will remove the prefix. - a struct which is returned as a dict. A struct is fully nestable, thus each field in the struct can have one of the values described here. Similar to method :func:`fieldnames` a keyword name can be given consisting of multiple parts separated by dots. This represents nested structs, thus gives the value of a field in a struct (in a struct, etc.). Instead of a keyword name an index can be given which returns the value of the i-th keyword. """ if isinstance(keyword, str): return self._getkeyword('', keyword, -1) else: return self._getkeyword('', '', keyword)
python
def getkeyword(self, keyword): if isinstance(keyword, str): return self._getkeyword('', keyword, -1) else: return self._getkeyword('', '', keyword)
[ "def", "getkeyword", "(", "self", ",", "keyword", ")", ":", "if", "isinstance", "(", "keyword", ",", "str", ")", ":", "return", "self", ".", "_getkeyword", "(", "''", ",", "keyword", ",", "-", "1", ")", "else", ":", "return", "self", ".", "_getkeywor...
Get the value of a table keyword. The value of a keyword can be a: - scalar which is returned as a normal python scalar. - an array which is returned as a numpy array. - a reference to a table which is returned as a string containing its name prefixed by 'Table :'. It can be opened using the normal table constructor which will remove the prefix. - a struct which is returned as a dict. A struct is fully nestable, thus each field in the struct can have one of the values described here. Similar to method :func:`fieldnames` a keyword name can be given consisting of multiple parts separated by dots. This represents nested structs, thus gives the value of a field in a struct (in a struct, etc.). Instead of a keyword name an index can be given which returns the value of the i-th keyword.
[ "Get", "the", "value", "of", "a", "table", "keyword", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1307-L1333
24,498
casacore/python-casacore
casacore/tables/table.py
table.getcolkeyword
def getcolkeyword(self, columnname, keyword): """Get the value of a column keyword. It is similar to :func:`getkeyword`. """ if isinstance(keyword, str): return self._getkeyword(columnname, keyword, -1) else: return self._getkeyword(columnname, '', keyword)
python
def getcolkeyword(self, columnname, keyword): if isinstance(keyword, str): return self._getkeyword(columnname, keyword, -1) else: return self._getkeyword(columnname, '', keyword)
[ "def", "getcolkeyword", "(", "self", ",", "columnname", ",", "keyword", ")", ":", "if", "isinstance", "(", "keyword", ",", "str", ")", ":", "return", "self", ".", "_getkeyword", "(", "columnname", ",", "keyword", ",", "-", "1", ")", "else", ":", "retur...
Get the value of a column keyword. It is similar to :func:`getkeyword`.
[ "Get", "the", "value", "of", "a", "column", "keyword", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1335-L1344
24,499
casacore/python-casacore
casacore/tables/table.py
table.getsubtables
def getsubtables(self): """Get the names of all subtables.""" keyset = self.getkeywords() names = [] for key, value in keyset.items(): if isinstance(value, str) and value.find('Table: ') == 0: names.append(_do_remove_prefix(value)) return names
python
def getsubtables(self): keyset = self.getkeywords() names = [] for key, value in keyset.items(): if isinstance(value, str) and value.find('Table: ') == 0: names.append(_do_remove_prefix(value)) return names
[ "def", "getsubtables", "(", "self", ")", ":", "keyset", "=", "self", ".", "getkeywords", "(", ")", "names", "=", "[", "]", "for", "key", ",", "value", "in", "keyset", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ...
Get the names of all subtables.
[ "Get", "the", "names", "of", "all", "subtables", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1364-L1371