Skip to content

Commit

Permalink
Use black and isort for autoformatting (#152)
Browse files Browse the repository at this point in the history
* Add black and isort for autoformatting
* add isort and black for tests. move pylint settings to pyproject.toml
* Updated CHANGELOG.rst
  • Loading branch information
joni-herttuainen committed Feb 28, 2022
1 parent 9e972f4 commit 778c6d9
Show file tree
Hide file tree
Showing 49 changed files with 2,720 additions and 2,040 deletions.
44 changes: 0 additions & 44 deletions .pylintrc

This file was deleted.

7 changes: 7 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
Changelog
=========

Version v0.13.2
---------------

Improvements
~~~~~~~~~~~~
- Add black & isort to handle formatting

Version v0.13.1
---------------

Expand Down
2 changes: 1 addition & 1 deletion bluepysnap/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@

from bluepysnap.circuit import Circuit
from bluepysnap.config import Config
from bluepysnap.simulation import Simulation
from bluepysnap.exceptions import BluepySnapError
from bluepysnap.simulation import Simulation
10 changes: 6 additions & 4 deletions bluepysnap/_doctools.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
# along with this library; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Module containing tools related to the documentation and docstrings."""
import abc
import functools
import inspect
import types
import functools
import abc


def _word_swapper(doc, source_word, target_word):
Expand All @@ -32,8 +32,9 @@ def _word_swapper(doc, source_word, target_word):

def _copy_func(f):
"""Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)."""
g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__,
closure=f.__closure__)
g = types.FunctionType(
f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__
)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
return g
Expand All @@ -52,6 +53,7 @@ class DocSubstitutionMeta(type):
<class 'bluepysnap.CircuitNodeIds'>
It works well with Sphinx also.
"""

def __new__(mcs, name, parents, attrs, source_word=None, target_word=None):
"""Define the new class to return."""
original_attrs = attrs.copy()
Expand Down
74 changes: 40 additions & 34 deletions bluepysnap/_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Plotting module for the different snap objects."""
import logging

import numpy as np
import pandas as pd
from more_itertools import roundrobin
Expand Down Expand Up @@ -64,30 +65,31 @@ def spikes_firing_rate_histogram(filtered_report, time_binsize=None, ax=None):
spike_report = filtered_report.spike_report

times = filtered_report.report.index
node_count = filtered_report.report[['ids', 'population']].drop_duplicates().shape[0]
node_count = filtered_report.report[["ids", "population"]].drop_duplicates().shape[0]

if len(times) == 0:
raise BluepySnapError("No data to display. You should check your "
f"'group' query: {spike_report.group}.")
raise BluepySnapError(
"No data to display. You should check your " f"'group' query: {spike_report.group}."
)

time_start = np.min(times)
time_stop = np.max(times)

if time_binsize is None:
# heuristic for a nice bin size (~100 spikes per bin on average)
time_binsize = min(50.0, (time_stop - time_start) / ((len(times) / 100.) + 1.))
time_binsize = min(50.0, (time_stop - time_start) / ((len(times) / 100.0) + 1.0))

bins = np.append(np.arange(time_start, time_stop, time_binsize), time_stop)
hist, bin_edges = np.histogram(times, bins=bins)
freq = 1.0 * hist / node_count / (0.001 * time_binsize)

if ax is None:
ax = plt.gca()
ax.set_xlabel('Time [ms]')
ax.set_ylabel('PSTH [Hz]')
ax.set_xlabel("Time [ms]")
ax.set_ylabel("PSTH [Hz]")

# use the middle of the bins instead of the start of the bin
ax.plot(0.5 * (bin_edges[1:] + bin_edges[:-1]), freq, label="PSTH", drawstyle='steps-mid')
ax.plot(0.5 * (bin_edges[1:] + bin_edges[:-1]), freq, label="PSTH", drawstyle="steps-mid")
return ax


Expand All @@ -114,12 +116,13 @@ def spike_raster(filtered_report, y_axis=None, ax=None): # pragma: no cover
spike_report = filtered_report.spike_report
population_names = filtered_report.spike_report.population_names

props = {"node_id_offset": 0,
"pop_separators": [],
"categorical_values": set(),
"ymin": np.inf,
"ymax": -np.inf
}
props = {
"node_id_offset": 0,
"pop_separators": [],
"categorical_values": set(),
"ymin": np.inf,
"ymax": -np.inf,
}

def _update_raster_properties():
if y_axis is None:
Expand Down Expand Up @@ -159,7 +162,7 @@ def _update_raster_properties():
ax = plt.gca()
ax.xaxis.grid()
ax.set_xlabel("Time [ms]")
ax.tick_params(axis='y', which='both', length=0)
ax.tick_params(axis="y", which="both", length=0)
ax.set_xlim(spike_report.time_start, spike_report.time_stop)
if y_axis is None:
ax.set_ylim(0, props["node_id_offset"])
Expand All @@ -176,10 +179,10 @@ def _update_raster_properties():
ax.set_ylim(-0.5, len(labels) - 0.5)
ax.set_ylabel(y_axis)

ax.scatter(data.index.to_numpy(), data.to_numpy(), s=10, marker='|')
ax.scatter(data.index.to_numpy(), data.to_numpy(), s=10, marker="|")
if len(props["pop_separators"]) > 1:
for separator in props["pop_separators"]:
ax.axhline(y=separator, color='black', lw=2)
ax.axhline(y=separator, color="black", lw=2)
return ax


Expand Down Expand Up @@ -210,31 +213,34 @@ def spikes_isi(filtered_report, use_frequency=False, binsize=None, ax=None): #
values = np.concatenate([np.diff(node_spikes.index.to_numpy()) for _, node_spikes in gb])

if len(values) == 0:
raise BluepySnapError("No data to display. You should check your "
f"'group' query: {filtered_report.spike_report.group}.")
raise BluepySnapError(
"No data to display. You should check your "
f"'group' query: {filtered_report.spike_report.group}."
)
if use_frequency:
values = values[values > 0] # filter out zero intervals
values = 1000.0 / values

if binsize is None:
bins = 'auto'
bins = "auto"
else:
bins = np.arange(0, np.max(values), binsize)

if ax is None:
ax = plt.gca()
if use_frequency:
ax.set_xlabel('Frequency [Hz]')
ax.set_xlabel("Frequency [Hz]")
else:
ax.set_xlabel('Interspike interval [ms]')
ax.set_ylabel('Bin weight')
ax.set_xlabel("Interspike interval [ms]")
ax.set_ylabel("Bin weight")

ax.hist(values, bins=bins, edgecolor='black', density=True)
ax.hist(values, bins=bins, edgecolor="black", density=True)
return ax


def spikes_firing_animation(filtered_report, x_axis=Node.X, y_axis=Node.Y,
dt=20, ax=None): # pragma: no cover
def spikes_firing_animation(
filtered_report, x_axis=Node.X, y_axis=Node.Y, dt=20, ax=None
): # pragma: no cover
# pylint: disable=too-many-locals,too-many-arguments,anomalous-backslash-in-string
"""Simple animation of simulation spikes.
Expand Down Expand Up @@ -275,7 +281,7 @@ def _check_axis(axis):
"""Verifies axes values."""
axes = {Node.X, Node.Y, Node.Z}
if axis not in axes:
raise BluepySnapError(f'{axis} is not a valid axis')
raise BluepySnapError(f"{axis} is not a valid axis")

_check_axis(x_axis)
_check_axis(y_axis)
Expand All @@ -302,22 +308,22 @@ def _check_axis(axis):
if ax is None:
fig = plt.figure()
ax = plt.gca()
ax.set_title(f'time = {np.min(data.index)}ms')
ax.set_title(f"time = {np.min(data.index)}ms")
x_limits = [data[x_axis].min(), data[x_axis].max()]
y_limits = [data[y_axis].min(), data[y_axis].max()]
ax.set_xlim(*x_limits)
ax.set_ylim(*y_limits)
ax.set_xlabel(rf'{x_axis} $\mu$m') # noqa
ax.set_ylabel(rf'{y_axis} $\mu$m') # noqa
ax.set_xlabel(rf"{x_axis} $\mu$m") # noqa
ax.set_ylabel(rf"{y_axis} $\mu$m") # noqa

else:
fig = ax.figure

dots = ax.plot([], [], '.k')
dots = ax.plot([], [], ".k")

def update_animation(frame):
"""Update the animation plots and axes."""
ax.set_title('time = ' + str(frame * dt) + ' ms')
ax.set_title("time = " + str(frame * dt) + " ms")
mask = (data.index >= frame * dt) & (data.index <= (frame + 1) * dt)
positions = data.loc[mask, [x_axis, y_axis]].values
x = positions[:, 0]
Expand All @@ -330,7 +336,7 @@ def update_animation(frame):
return anim, ax


def frame_trace(filtered_report, plot_type='mean', ax=None): # pragma: no cover
def frame_trace(filtered_report, plot_type="mean", ax=None): # pragma: no cover
"""Returns a plot displaying the voltage of a node or a compartment as a function of time.
Args:
Expand All @@ -349,9 +355,9 @@ def frame_trace(filtered_report, plot_type='mean', ax=None): # pragma: no cover
ax = plt.gca()
data_units = filtered_report.frame_report.data_units
if plot_type == "mean":
ax.set_ylabel(f'Avg volt. [{data_units}]')
ax.set_ylabel(f"Avg volt. [{data_units}]")
elif plot_type == "all":
ax.set_ylabel(f'Voltage [{data_units}]')
ax.set_ylabel(f"Voltage [{data_units}]")
ax.set_xlabel(f"Time [{filtered_report.frame_report.time_units}]")
ax.set_xlim([filtered_report.report.index.min(), filtered_report.report.index.max()])

Expand Down
8 changes: 4 additions & 4 deletions bluepysnap/bbp.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@

from bluepysnap.sonata_constants import DYNAMICS_PREFIX, Edge, Node

NODE_TYPES = {'biophysical', 'virtual', 'astrocyte', 'single_compartment', 'point_neuron'}
EDGE_TYPES = {'chemical', 'electrical', 'synapse_astrocyte', 'endfoot'}
NODE_TYPES = {"biophysical", "virtual", "astrocyte", "single_compartment", "point_neuron"}
EDGE_TYPES = {"chemical", "electrical", "synapse_astrocyte", "endfoot"}


class Cell(Node):
Expand All @@ -32,8 +32,8 @@ class Cell(Node):
LAYER = "layer" #:
REGION = "region" #:
SYNAPSE_CLASS = "synapse_class" #:
HOLDING_CURRENT = DYNAMICS_PREFIX + 'holding_current' #:
THRESHOLD_CURRENT = DYNAMICS_PREFIX + 'threshold_current' #:
HOLDING_CURRENT = DYNAMICS_PREFIX + "holding_current" #:
THRESHOLD_CURRENT = DYNAMICS_PREFIX + "threshold_current" #:


class Synapse(Edge):
Expand Down
2 changes: 1 addition & 1 deletion bluepysnap/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
from cached_property import cached_property

from bluepysnap.config import Config
from bluepysnap.edges import Edges
from bluepysnap.node_sets import NodeSets
from bluepysnap.nodes import Nodes
from bluepysnap.edges import Edges


class Circuit:
Expand Down
26 changes: 18 additions & 8 deletions bluepysnap/circuit_ids.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@
import pandas as pd

from bluepysnap import utils
from bluepysnap.exceptions import BluepySnapError
from bluepysnap._doctools import AbstractDocSubstitutionMeta

from bluepysnap.exceptions import BluepySnapError

CircuitNodeId = namedtuple("CircuitNodeId", ("population", "id"))
CircuitEdgeId = namedtuple("CircuitEdgeId", ("population", "id"))
Expand All @@ -40,6 +39,7 @@ class CircuitIds(abc.ABC):
A global circuit node id is the combination of a population and an ID inside this
population.
"""

def __init__(self, index, sort_index=True):
"""Return an instance of CircuitIds.
Expand Down Expand Up @@ -79,8 +79,10 @@ def from_arrays(cls, populations, population_ids, sort_index=True):
population_ids = utils.ensure_ids(population_ids)

if len(populations) != len(population_ids):
raise BluepySnapError("populations and population_ids must have the same size. "
f"{len(populations)} != {len(population_ids)}")
raise BluepySnapError(
"populations and population_ids must have the same size. "
f"{len(populations)} != {len(population_ids)}"
)

index = pd.MultiIndex.from_arrays([populations, population_ids])
return cls(index, sort_index=sort_index)
Expand Down Expand Up @@ -288,8 +290,12 @@ def __getitem__(self, item): # pragma: no cover
"""Getter on the CircuitIds."""


class CircuitNodeIds(CircuitIds, metaclass=AbstractDocSubstitutionMeta,
source_word="CircuitId", target_word="CircuitNodeId"):
class CircuitNodeIds(
CircuitIds,
metaclass=AbstractDocSubstitutionMeta,
source_word="CircuitId",
target_word="CircuitNodeId",
):
"""High performances CircuitNodeID container."""

def __init__(self, index, sort_index=True):
Expand All @@ -313,8 +319,12 @@ def __getitem__(self, item):
return CircuitNodeId(*self.index[item])


class CircuitEdgeIds(CircuitIds, metaclass=AbstractDocSubstitutionMeta,
source_word="CircuitId", target_word="CircuitEdgeId"):
class CircuitEdgeIds(
CircuitIds,
metaclass=AbstractDocSubstitutionMeta,
source_word="CircuitId",
target_word="CircuitEdgeId",
):
"""High performances CircuitEdgeID container."""

def __init__(self, index, sort_index=True):
Expand Down

0 comments on commit 778c6d9

Please sign in to comment.