Skip to content

Commit

Permalink
Replace black/reorder-python-imports/flake8 with ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
lkeegan committed Jan 30, 2024
1 parent 1792e4c commit 1df31ab
Show file tree
Hide file tree
Showing 34 changed files with 233 additions and 296 deletions.
24 changes: 7 additions & 17 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ repos:
- id: mixed-line-ending
- id: check-toml

- repo: https://github.com/psf/black
rev: 23.12.1
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.15
hooks:
- id: black
- id: black-jupyter
- id: ruff
types_or: [python, pyi, jupyter]
args: [--fix]
- id: ruff-format
types_or: [python, pyi, jupyter]

- repo: https://github.com/kynan/nbstripout
rev: 0.6.1
Expand Down Expand Up @@ -46,19 +49,6 @@ repos:
--warn-redundant-casts,
]

- repo: https://github.com/asottile/reorder-python-imports
rev: v3.12.0
hooks:
- id: reorder-python-imports

- repo: https://github.com/pycqa/flake8
rev: "7.0.0"
hooks:
- id: flake8
args:
- "--max-line-length=88"
- "--ignore=E501,W503,E203"

- repo: https://github.com/rhysd/actionlint
rev: "v1.6.26"
hooks:
Expand Down
17 changes: 10 additions & 7 deletions docs/notebooks/area_calculation.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
"metadata": {},
"outputs": [],
"source": [
"from psychopy.misc import fromFile\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt"
"from psychopy.misc import fromFile"
]
},
{
Expand Down Expand Up @@ -118,9 +118,10 @@
"metadata": {},
"outputs": [],
"source": [
"from typing import List, Tuple\n",
"\n",
"from shapely.geometry import LineString\n",
"from shapely.ops import polygonize, unary_union\n",
"from typing import List, Tuple"
"from shapely.ops import polygonize, unary_union"
]
},
{
Expand Down Expand Up @@ -167,11 +168,13 @@
"outputs": [],
"source": [
"def plot_and_calculate_area(data):\n",
" colors = [\"blue\", \"green\", \"red\", \"cyan\", \"magenta\", \"yellow\", \"black\", \"orange\"]\n",
" nTrials, nReps = data.sequenceIndices.shape\n",
" for trial in range(nTrials):\n",
" for rep in range(nReps):\n",
" loc = (trial, rep)\n",
" condition = data.sequenceIndices[loc]\n",
" target_radius = data.trialList[condition][\"target_size\"]\n",
" central_target_radius = data.trialList[condition][\"central_target_size\"]\n",
"\n",
" # if condition \"automove_cursor_to_center\" is deselected, plot the line to center, fill the enclosed area and output the area\n",
Expand Down Expand Up @@ -211,7 +214,7 @@
" alpha=0.1,\n",
" )\n",
" )\n",
" print(\"%s, area: %f\" % (color, area))\n",
" print(f\"{color}, area: {area:f}\")\n",
"\n",
" ax.add_patch(\n",
" plt.Circle(\n",
Expand Down Expand Up @@ -349,9 +352,9 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
"version": "3.9.15"
}
},
"nbformat": 4,
"nbformat_minor": 1
"nbformat_minor": 4
}
5 changes: 2 additions & 3 deletions docs/notebooks/example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@
"metadata": {},
"outputs": [],
"source": [
"import vstt\n",
"import matplotlib.pyplot as plt\n",
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt"
"import vstt"
]
},
{
Expand Down
25 changes: 10 additions & 15 deletions docs/notebooks/raw_data.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,12 @@
"metadata": {},
"outputs": [],
"source": [
"from psychopy.misc import fromFile\n",
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from shapely.geometry import Polygon, LineString, MultiPolygon, LinearRing\n",
"from shapely.ops import polygonize, unary_union\n",
"from shapely.validation import make_valid\n",
"\n",
"# from matplotlib.patches import Polygon"
"import numpy as np\n",
"import pandas as pd\n",
"from psychopy.misc import fromFile\n",
"from shapely.geometry import LineString, Polygon\n",
"from shapely.ops import polygonize, unary_union"
]
},
{
Expand Down Expand Up @@ -288,7 +285,7 @@
" f\"area plot for Trial {trial}, Rep {rep} [Condition {condition}]\"\n",
" )\n",
" print(\"---------------------------------------------\")\n",
" print(\"area of Trial %d, Rep %d [Condition %s]\" % (trial, rep, condition))\n",
" print(f\"area of Trial {trial}, Rep {rep} [Condition {condition}]\")\n",
" for (\n",
" to_target_mouse_positions,\n",
" to_center_mouse_positions,\n",
Expand Down Expand Up @@ -327,7 +324,7 @@
" alpha=0.1,\n",
" )\n",
" )\n",
" print(\"%s, area: %f\" % (color, area))\n",
" print(f\"{color}, area: {area}\")\n",
"\n",
" ax.add_patch(\n",
" plt.Circle(\n",
Expand Down Expand Up @@ -370,6 +367,7 @@
"metadata": {},
"outputs": [],
"source": [
"colors = [\"blue\", \"green\", \"red\", \"cyan\", \"magenta\", \"yellow\", \"black\", \"orange\"]\n",
"nConditions = len(psydata.trialList)\n",
"nTrials, nReps = psydata.sequenceIndices.shape\n",
"fig, axs = plt.subplots(nConditions, 1, figsize=(6, 6 * nConditions))\n",
Expand Down Expand Up @@ -429,10 +427,7 @@
"central_target_radius = psydata.trialList[condition][\"central_target_size\"]\n",
"for dest, ax in zip([\"target\", \"center\"], axs):\n",
" positions = psydata.data[f\"to_{dest}_mouse_positions\"][loc][i_target]\n",
" if dest == \"target\":\n",
" target = psydata.data[\"target_pos\"][loc][i_target]\n",
" else:\n",
" target = [0, 0]\n",
" target = psydata.data[\"target_pos\"][loc][i_target] if dest == \"target\" else [0, 0]\n",
" times = psydata.data[f\"to_{dest}_timestamps\"][loc][i_target]\n",
" ax.set_title(f\"Mouse movements to {dest}\")\n",
" ax.plot(times, positions[:, 0], label=\"x\")\n",
Expand All @@ -459,7 +454,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
"version": "3.9.15"
}
},
"nbformat": 4,
Expand Down
20 changes: 20 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,23 @@ version = { attr = "vstt.__version__" }

[tool.pytest.ini_options]
testpaths = ["tests"]

[tool.ruff]
extend-include = ["*.ipynb"]

[tool.ruff.lint]
select = [
# pycodestyle
"E",
# Pyflakes
"F",
# pyupgrade
"UP",
# flake8-bugbear
"B",
# flake8-simplify
"SIM",
# isort
"I",
]
ignore = ["E501"]
4 changes: 2 additions & 2 deletions src/vstt/__main__.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
from __future__ import annotations

import logging
from typing import Optional

import click
from psychopy.gui.qtgui import ensureQtApp
from qtpy import QtWidgets

from vstt.gui import Gui


@click.command()
@click.argument("filename", required=False)
def main(filename: Optional[str]) -> None:
def main(filename: str | None) -> None:
logging.basicConfig(
format="%(levelname)s %(module)s.%(funcName)s.%(lineno)d :: %(message)s"
)
Expand Down
11 changes: 3 additions & 8 deletions src/vstt/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,9 @@

import copy
import logging
from typing import Any
from typing import Mapping
from typing import Type
from typing import TypeVar
from typing import Any, Mapping, TypeVar

from vstt.vtypes import DisplayOptions
from vstt.vtypes import Metadata
from vstt.vtypes import Trial
from vstt.vtypes import DisplayOptions, Metadata, Trial

VsttTypedDict = TypeVar(
"VsttTypedDict",
Expand All @@ -19,7 +14,7 @@
)


def _has_valid_type(var: Any, correct_type: Type) -> bool:
def _has_valid_type(var: Any, correct_type: type) -> bool:
if isinstance(var, correct_type):
# var has the correct type
return True
Expand Down
4 changes: 1 addition & 3 deletions src/vstt/display.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from __future__ import annotations

from typing import Dict

import vstt


Expand Down Expand Up @@ -33,7 +31,7 @@ def default_display_options() -> vstt.vtypes.DisplayOptions:
}


def display_options_labels() -> Dict[str, str]:
def display_options_labels() -> dict[str, str]:
return {
"to_target_paths": "Display cursor paths to target",
"to_center_paths": "Display cursor paths back to center",
Expand Down
12 changes: 5 additions & 7 deletions src/vstt/display_widget.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
from __future__ import annotations

from typing import Callable
from typing import Dict
from typing import Optional

from psychopy.visual.window import Window
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy import QtCore, QtWidgets

from vstt.display import display_options_labels
from vstt.experiment import Experiment

Expand All @@ -15,20 +13,20 @@ class DisplayOptionsWidget(QtWidgets.QWidget):
experiment_modified = QtCore.Signal()

def __init__(
self, parent: Optional[QtWidgets.QWidget] = None, win: Optional[Window] = None
self, parent: QtWidgets.QWidget | None = None, win: Window | None = None
):
super().__init__(parent)
self._win = win
self._experiment: Experiment = Experiment()
self._widgets: Dict[str, QtWidgets.QCheckBox] = {}
self._widgets: dict[str, QtWidgets.QCheckBox] = {}

outer_layout = QtWidgets.QVBoxLayout()
group_box = QtWidgets.QGroupBox("Display Options")
outer_layout.addWidget(group_box)
inner_layout = QtWidgets.QVBoxLayout()
group_box.setLayout(inner_layout)
labels = display_options_labels()
for row_index, key in enumerate(labels.keys()):
for _row_index, key in enumerate(labels.keys()):
checkbox = QtWidgets.QCheckBox(f"{labels[key]}", self)
inner_layout.addWidget(checkbox)
checkbox.clicked.connect(self._update_value_callback(key))
Expand Down
32 changes: 13 additions & 19 deletions src/vstt/experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,26 @@
import pathlib
import pickle
from typing import Any
from typing import Dict
from typing import List
from typing import Optional

import pandas as pd
from psychopy.data import TrialHandlerExt
from psychopy.misc import fromFile
from vstt.display import default_display_options
from vstt.display import import_display_options
from vstt.meta import default_metadata
from vstt.meta import import_metadata
from vstt.stats import append_stats_data_to_excel
from vstt.stats import stats_dataframe
from vstt.trial import default_trial
from vstt.trial import import_and_validate_trial

from vstt.display import default_display_options, import_display_options
from vstt.meta import default_metadata, import_metadata
from vstt.stats import append_stats_data_to_excel, stats_dataframe
from vstt.trial import default_trial, import_and_validate_trial


class Experiment:
def __init__(self, filename: Optional[str] = None):
def __init__(self, filename: str | None = None):
self.filename = "default-experiment.psydat"
self.has_unsaved_changes = False
self.metadata = default_metadata()
self.display_options = default_display_options()
self.trial_list = [default_trial()]
self.trial_handler_with_results: Optional[TrialHandlerExt] = None
self.stats: Optional[pd.DataFrame] = None
self.trial_handler_with_results: TrialHandlerExt | None = None
self.stats: pd.DataFrame | None = None
if filename is not None:
self.load_file(filename)

Expand All @@ -50,7 +44,7 @@ def create_trialhandler(self) -> TrialHandlerExt:
def clear_results(self) -> None:
self.trial_handler_with_results = None

def _as_dict(self) -> Dict[str, Any]:
def _as_dict(self) -> dict[str, Any]:
return {
"metadata": self.metadata,
"display_options": self.display_options,
Expand Down Expand Up @@ -131,7 +125,7 @@ def save_json(self, filename: str) -> None:
json.dump(self._as_dict(), f)

def load_json(self, filename: str) -> None:
with open(filename, "r") as f:
with open(filename) as f:
d = json.load(f)
self.import_and_validate_dicts(
filename, d["metadata"], d["display_options"], d["trial_list"]
Expand All @@ -140,9 +134,9 @@ def load_json(self, filename: str) -> None:
def import_and_validate_dicts(
self,
filename: str,
metadata_dict: Dict,
display_options_dict: Dict,
trial_dict_list: List[Dict],
metadata_dict: dict,
display_options_dict: dict,
trial_dict_list: list[dict],
) -> None:
self.metadata = import_metadata(metadata_dict)
self.display_options = import_display_options(display_options_dict)
Expand Down
Loading

0 comments on commit 1df31ab

Please sign in to comment.