Skip to content

Commit

Permalink
Utilize magic comma in new black update (scverse#1394)
Browse files Browse the repository at this point in the history
  • Loading branch information
flying-sheep authored Aug 28, 2020
1 parent 8829f2b commit 43379e0
Show file tree
Hide file tree
Showing 23 changed files with 129 additions and 132 deletions.
3 changes: 3 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
dist: xenial
language: python
branches:
only:
- master # All other branches should become (draft) PRs and be build that way
matrix:
include:
- name: "static analysis"
Expand Down
2 changes: 1 addition & 1 deletion docs/extensions/function_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@


def insert_function_images(
app: Sphinx, what: str, name: str, obj: Any, options: Options, lines: List[str],
app: Sphinx, what: str, name: str, obj: Any, options: Options, lines: List[str]
):
path = app.config.api_dir / f'{name}.png'
if what != 'function' or not path.is_file():
Expand Down
2 changes: 1 addition & 1 deletion docs/extensions/github_links.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def __call__(
):
url = self.url_template.format(text)
title = self.title_template.format(text)
options = {**dict(classes=[self.class_name],), **options}
options = {**dict(classes=[self.class_name]), **options}
node = nodes.reference(rawtext, title, refuri=url, **options)
return [node], []

Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ exclude = '''
|_paga
|_umap
|_utils
|_leiden
|_louvain
|_tsne_fix
|_top_genes
Expand Down
10 changes: 3 additions & 7 deletions scanpy/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@
class _DelegatingSubparsersAction(_SubParsersAction):
"""Like a normal subcommand action, but uses a delegator for more choices"""

def __init__(
self, *args, _command: str, _runargs: Dict[str, Any], **kwargs,
):
def __init__(self, *args, _command: str, _runargs: Dict[str, Any], **kwargs):
super().__init__(*args, **kwargs)
self.command = _command
self._name_parser_map = self.choices = _CommandDelegator(
Expand All @@ -38,9 +36,7 @@ class _CommandDelegator(cabc.MutableMapping):
but don’t calculate the whole list until necessary
"""

def __init__(
self, command: str, action: _DelegatingSubparsersAction, **runargs,
):
def __init__(self, command: str, action: _DelegatingSubparsersAction, **runargs):
self.command = command
self.action = action
self.parser_map = {}
Expand Down Expand Up @@ -120,7 +116,7 @@ def _cmd_settings() -> None:


def main(
argv: Optional[Sequence[str]] = None, *, check: bool = True, **runargs,
argv: Optional[Sequence[str]] = None, *, check: bool = True, **runargs
) -> Optional[CompletedProcess]:
"""\
Run a builtin scanpy command or a scanpy-* subcommand.
Expand Down
6 changes: 4 additions & 2 deletions scanpy/datasets/_ebi_expression_atlas.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,12 @@ def download_experiment(accession: str):
experiment_dir.mkdir(parents=True, exist_ok=True)

_download(
design_url + "experiment-design", experiment_dir / "experimental_design.tsv",
design_url + "experiment-design",
experiment_dir / "experimental_design.tsv",
)
_download(
mtx_url + "quantification-raw", experiment_dir / "expression_archive.zip",
mtx_url + "quantification-raw",
experiment_dir / "expression_archive.zip",
)


Expand Down
15 changes: 9 additions & 6 deletions scanpy/plotting/_anndata.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,12 @@ def add_centroid(centroids, name, Y, mask):
if projection == '3d':
data.append(Y[mask_remaining, 2])
axs[ikey].scatter(
*data, marker='.', c='lightgrey', s=size, edgecolors='none', zorder=-1,
*data,
marker='.',
c='lightgrey',
s=size,
edgecolors='none',
zorder=-1,
)
legend = None
if legend_loc.startswith('on data'):
Expand Down Expand Up @@ -737,9 +742,7 @@ def violin(
y = ys[0]
g = sns.FacetGrid(obs_tidy, col=x, col_order=keys, sharey=False)
# don't really know why this gives a warning without passing `order`
g = g.map(
sns.violinplot, y, orient='vertical', scale=scale, order=keys, **kwds,
)
g = g.map(sns.violinplot, y, orient='vertical', scale=scale, order=keys, **kwds)
if stripplot:
g = g.map(
sns.stripplot,
Expand Down Expand Up @@ -1116,7 +1119,7 @@ def heatmap(
if dendrogram:
dendro_ax = fig.add_subplot(axs[1, 2], sharey=heatmap_ax)
_plot_dendrogram(
dendro_ax, adata, groupby, ticks=ticks, dendrogram_key=dendrogram,
dendro_ax, adata, groupby, ticks=ticks, dendrogram_key=dendrogram
)

# plot group legends on top of heatmap_ax (if given)
Expand Down Expand Up @@ -1191,7 +1194,7 @@ def heatmap(
if categorical:
groupby_ax = fig.add_subplot(axs[2, 0])
ticks, labels, groupby_cmap, norm = _plot_categories_as_colorblocks(
groupby_ax, obs_tidy, colors=groupby_colors, orientation='bottom',
groupby_ax, obs_tidy, colors=groupby_colors, orientation='bottom'
)
# add lines to main heatmap
line_positions = (
Expand Down
8 changes: 3 additions & 5 deletions scanpy/plotting/_baseplot_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
cmap
String denoting matplotlib color map.
standard_scale
Whether or not to standardize the given dimension between 0 and 1, meaning for
Whether or not to standardize the given dimension between 0 and 1, meaning for
each variable or group, subtract the minimum and divide each by its maximum.
swap_axes
By default, the x axis contains `var_names` (e.g. genes) and the y axis
Expand Down Expand Up @@ -515,7 +515,7 @@ def _plot_legend(self, legend_ax, return_ax_dict, normalize):
legend_height,
]
fig, legend_gs = make_grid_spec(
legend_ax, nrows=2, ncols=1, height_ratios=height_ratios,
legend_ax, nrows=2, ncols=1, height_ratios=height_ratios
)

color_legend_ax = fig.add_subplot(legend_gs[1])
Expand Down Expand Up @@ -792,9 +792,7 @@ def savefig(self, filename: str, bbox_inches: Optional[str] = 'tight', **kwargs)
self.make_figure()
pl.savefig(filename, bbox_inches=bbox_inches, **kwargs)

def _reorder_categories_after_dendrogram(
self, dendrogram,
):
def _reorder_categories_after_dendrogram(self, dendrogram):
"""\
Function used by plotting functions that need to reorder the the groupby
observations based on the dendrogram results.
Expand Down
4 changes: 2 additions & 2 deletions scanpy/plotting/_dotplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ def _plot_legend(self, legend_ax, return_ax_dict, normalize):
cbar_legend_height,
]
fig, legend_gs = make_grid_spec(
legend_ax, nrows=4, ncols=1, height_ratios=height_ratios,
legend_ax, nrows=4, ncols=1, height_ratios=height_ratios
)

if self.show_size_legend:
Expand Down Expand Up @@ -943,7 +943,7 @@ def dotplot(
dot_min=dot_min,
smallest_dot=smallest_dot,
dot_edge_lw=kwds.pop('linewidth', DotPlot.DEFAULT_DOT_EDGELW),
).legend(colorbar_title=colorbar_title, size_title=size_title,)
).legend(colorbar_title=colorbar_title, size_title=size_title)

if return_fig:
return dp
Expand Down
6 changes: 2 additions & 4 deletions scanpy/plotting/_stacked_violin.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,17 +524,15 @@ def _setup_violin_axes_ticks(self, row_ax, num_cols):
row_ax.axis('off')
# remove labels
row_ax.set_yticklabels([])
row_ax.tick_params(
axis='y', left=False, right=False,
)
row_ax.tick_params(axis='y', left=False, right=False)

row_ax.set_ylabel('')

row_ax.set_xlabel('')

row_ax.set_xticklabels([])
row_ax.tick_params(
axis='x', bottom=False, top=False, labeltop=False, labelbottom=False,
axis='x', bottom=False, top=False, labeltop=False, labelbottom=False
)


Expand Down
17 changes: 8 additions & 9 deletions scanpy/plotting/_tools/scatterplots.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,9 +219,7 @@ def embedding(

if (
size is not None
and isinstance(
size, (cabc.Sequence, pandas.core.series.Series, np.ndarray,)
)
and isinstance(size, (cabc.Sequence, pandas.core.series.Series, np.ndarray))
and len(size) == adata.shape[0]
):
size = np.array(size, dtype=float)
Expand Down Expand Up @@ -425,7 +423,7 @@ def embedding(

if legend_fontoutline is not None:
path_effect = [
patheffects.withStroke(linewidth=legend_fontoutline, foreground='w',)
patheffects.withStroke(linewidth=legend_fontoutline, foreground='w')
]
else:
path_effect = None
Expand Down Expand Up @@ -681,7 +679,7 @@ def diffmap(adata, **kwargs) -> Union[Axes, List[Axes], None]:
show_save_ax=doc_show_save_ax,
)
def draw_graph(
adata: AnnData, *, layout: Optional[_IGraphLayout] = None, **kwargs,
adata: AnnData, *, layout: Optional[_IGraphLayout] = None, **kwargs
) -> Union[Axes, List[Axes], None]:
"""\
Scatter plot in graph-drawing basis.
Expand Down Expand Up @@ -786,7 +784,8 @@ def spatial(
spatial_data = adata.uns['spatial'][library_id]
if img_key is _empty:
img_key = next(
(k for k in ['hires', 'lowres'] if k in spatial_data['images']), None,
(k for k in ['hires', 'lowres'] if k in spatial_data['images']),
None,
)

if size is None:
Expand Down Expand Up @@ -919,7 +918,7 @@ def _get_data_points(
if f"tissue_{img_key}_scalef" in spatial_data['scalefactors'].keys():
scalef_key = f"tissue_{img_key}_scalef"
data_points[0] = np.multiply(
data_points[0], spatial_data['scalefactors'][scalef_key],
data_points[0], spatial_data['scalefactors'][scalef_key]
)
else:
raise KeyError(
Expand Down Expand Up @@ -999,7 +998,7 @@ def _add_categorical_legend(


def _get_color_source_vector(
adata, value_to_plot, use_raw=False, gene_symbols=None, layer=None, groups=None,
adata, value_to_plot, use_raw=False, gene_symbols=None, layer=None, groups=None
):
"""
Get array from adata that colors will be based on.
Expand All @@ -1024,7 +1023,7 @@ def _get_color_source_vector(
else:
values = adata.obs_vector(value_to_plot, layer=layer)
if groups and is_categorical_dtype(values):
values = values.replace(values.categories.difference(groups), np.nan,)
values = values.replace(values.categories.difference(groups), np.nan)
return values


Expand Down
55 changes: 24 additions & 31 deletions scanpy/plotting/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def timeseries_subplot(


def timeseries_as_heatmap(
X: np.ndarray, var_names: Collection[str] = (), highlights_x=(), color_map=None,
X: np.ndarray, var_names: Collection[str] = (), highlights_x=(), color_map=None
):
"""\
Plot timeseries as heatmap.
Expand Down Expand Up @@ -357,7 +357,7 @@ def _validate_palette(adata, key):


def _set_colors_for_categorical_obs(
adata, value_to_plot, palette: Union[str, Sequence[str], Cycler],
adata, value_to_plot, palette: Union[str, Sequence[str], Cycler]
):
"""
Sets the adata.uns[value_to_plot + '_colors'] according to the given palette
Expand Down Expand Up @@ -541,8 +541,7 @@ def plot_arrows(axs, adata, basis, arrows_kwds=None):


def scatter_group(ax, key, imask, adata, Y, projection='2d', size=3, alpha=None):
"""Scatter of group using representation of data Y.
"""
"""Scatter of group using representation of data Y."""
mask = adata.obs[key].cat.categories[imask] == adata.obs[key].values
color = adata.uns[key + '_colors'][imask]
if not isinstance(color[0], str):
Expand Down Expand Up @@ -576,8 +575,7 @@ def setup_axes(
projection: Literal['2d', '3d'] = '2d',
show_ticks=False,
):
"""Grid of axes for plotting, legends and colorbars.
"""
"""Grid of axes for plotting, legends and colorbars."""
make_projection_available(projection)
if left_margin is not None:
raise NotImplementedError('We currently don’t support `left_margin`.')
Expand Down Expand Up @@ -738,7 +736,7 @@ def scatter_base(
fig = pl.gcf()
ax_cb = fig.add_axes(rectangle)
cb = pl.colorbar(
sct, format=ticker.FuncFormatter(ticks_formatter), cax=ax_cb,
sct, format=ticker.FuncFormatter(ticks_formatter), cax=ax_cb
)
# set the title
if title is not None:
Expand Down Expand Up @@ -814,9 +812,7 @@ def scatter_single(ax: Axes, Y: np.ndarray, *args, **kwargs):
ax.set_yticks([])


def arrows_transitions(
ax: Axes, X: np.ndarray, indices: Sequence[int], weight=None,
):
def arrows_transitions(ax: Axes, X: np.ndarray, indices: Sequence[int], weight=None):
"""
Plot arrows of transitions in data matrix.
Expand Down Expand Up @@ -876,14 +872,12 @@ def ticks_formatter(x, pos):


def pimp_axis(x_or_y_ax):
"""Remove trailing zeros.
"""
"""Remove trailing zeros."""
x_or_y_ax.set_major_formatter(ticker.FuncFormatter(ticks_formatter))


def scale_to_zero_one(x):
"""Take some 1d data and scale it so that min matches 0 and max 1.
"""
"""Take some 1d data and scale it so that min matches 0 and max 1."""
xscaled = x - np.min(x)
xscaled /= np.max(xscaled)
return xscaled
Expand All @@ -892,28 +886,27 @@ def scale_to_zero_one(x):
def hierarchy_pos(G, root, levels=None, width=1.0, height=1.0):
"""Tree layout for networkx graph.
See https://stackoverflow.com/questions/29586520/can-one-get-hierarchical-graphs-from-networkx-with-python-3
answer by burubum.
If there is a cycle that is reachable from root, then this will see
infinite recursion.
Parameters
----------
G: the graph
root: the root node
levels: a dictionary
key: level number (starting from 0)
value: number of nodes in this level
width: horizontal space allocated for drawing
height: vertical space allocated for drawing
See https://stackoverflow.com/questions/29586520/can-one-get-hierarchical-graphs-from-networkx-with-python-3
answer by burubum.
If there is a cycle that is reachable from root, then this will see
infinite recursion.
Parameters
----------
G: the graph
root: the root node
levels: a dictionary
key: level number (starting from 0)
value: number of nodes in this level
width: horizontal space allocated for drawing
height: vertical space allocated for drawing
"""
TOTAL = "total"
CURRENT = "current"

def make_levels(levels, node=root, currentLevel=0, parent=None):
"""Compute the number of nodes for each level
"""
"""Compute the number of nodes for each level"""
if currentLevel not in levels:
levels[currentLevel] = {TOTAL: 0, CURRENT: 0}
levels[currentLevel][TOTAL] += 1
Expand Down
Loading

0 comments on commit 43379e0

Please sign in to comment.