Skip to content

Commit b0e8e20

Browse files
authored
chore: setup pre-commit (#37)
1 parent 6f2fee4 commit b0e8e20

38 files changed

+120
-79
lines changed

.github/workflows/check.yml

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,27 +11,21 @@ jobs:
1111
python-version: [ "3.11", "3.12", "3.13" ]
1212

1313
steps:
14-
- uses: actions/checkout@v3
14+
- uses: actions/checkout@v4
1515

1616
- name: Set up Python ${{ matrix.python-version }}
17-
uses: actions/setup-python@v3
17+
uses: actions/setup-python@v5
1818
with:
1919
python-version: ${{ matrix.python-version }}
2020

21-
- name: Install poetry
22-
run: pipx install poetry
21+
- name: Install Poetry
22+
uses: snok/install-poetry@v1
2323

2424
- name: Install dependencies
2525
run: poetry install --with dev
2626

27-
- name: Ruff
28-
run: poetry run ruff check
27+
- name: Run Pre-commit hooks
28+
run: poetry run pre-commit run --all-files
2929

30-
- name: Install stubs
31-
run: poetry run pip install types-PyYAML types-tqdm
32-
33-
- name: Mypy
34-
run: poetry run mypy
35-
36-
- name: Pytest
37-
run: poetry run python -m pytest tests
30+
- name: Run tests
31+
run: poetry run python -m pytest tests

.pre-commit-config.yaml

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
repos:
2+
- repo: https://github.com/pre-commit/pre-commit-hooks
3+
rev: v5.0.0
4+
hooks:
5+
- id: trailing-whitespace
6+
- id: end-of-file-fixer
7+
- id: check-yaml
8+
- id: check-added-large-files
9+
- id: check-merge-conflict
10+
- id: check-ast
11+
12+
- repo: local
13+
hooks:
14+
- id: ruff-check
15+
name: ruff check
16+
entry: poetry run ruff check --fix --exit-non-zero-on-fix
17+
language: system
18+
types: [python]
19+
files: ^(mpest/|experimental_env/|tests/).*
20+
21+
- id: ruff-format
22+
name: ruff format
23+
entry: poetry run ruff format
24+
language: system
25+
types: [python]
26+
files: ^(mpest/|experimental_env/|tests/).*
27+
28+
- id: mypy
29+
name: mypy check
30+
entry: poetry run mypy
31+
language: system
32+
types: [python]
33+
pass_filenames: false

CONTRIBUTING.md

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,27 @@ git checkout -b <type>/<what-this-branch-solves>
3535

3636

3737

38-
### 3. Make and Commit Changes
38+
### 3. Set Up Your Development Environment
39+
40+
To start working on the code, you need to install the project dependencies and set up the pre-commit hooks. These hooks automatically check your code for quality and style before each commit.
41+
42+
1. **Install dependencies:**
43+
44+
Follow steps in [README.md](README.md)
45+
46+
2. **Install pre-commit hooks (Mandatory):**
47+
48+
```bash
49+
pre-commit install
50+
```
51+
52+
This command sets up the hooks in your local Git repository. **This is a required step for all contributors.**
53+
54+
Now your environment is ready. The hooks will run automatically every time you run `git commit`.
55+
56+
57+
58+
### 4. Make and Commit Changes
3959

4060
Work on the code in your new branch. When you're ready to save your changes, create a commit. We use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) to standardize commit messages.
4161

@@ -48,7 +68,7 @@ Use the following types:
4868
- `struct`: for changes related to the project structure (NOT CODE), for example, changing folder locations.
4969
- `ci`: for various CI/CD tasks.
5070
- `docs`: for changes in documentation.
51-
- `chore`: for other changes that do not affect the code or tests (e.g., updating .gitignore, README.md).
71+
- `chore`: for other changes that do not affect the code or tests (e.g., updating `.gitignore`, `README.md`).
5272

5373

5474

@@ -64,7 +84,7 @@ Try to divide commits into atomic and independent parts. That is, do not add unr
6484

6585

6686

67-
### 4. Push Changes to Your Fork
87+
### 5. Push Changes to Your Fork
6888

6989
After you have made one or more commits, push your branch to your remote fork on GitHub:
7090

@@ -74,13 +94,13 @@ git push
7494

7595

7696

77-
### 5. Create a Pull Request (PR)
97+
### 6. Create a Pull Request (PR)
7898

7999
Once your branch with the changes is in your fork, you can create a Pull Request to propose your changes to the main repository.
80100

81101
1. Go to your fork's page on GitHub (https://github.com/YOUR-USERNAME/pysatl-mpest).
82102
2. You will see a notification prompting you to create a Pull Request for your recently pushed branch. Click the **"Compare & pull request"** button.
83-
3. Ensure the base repository is PySATL/pysatl-mpest with the main branch, and the head repository is your fork and your working branch.
103+
3. Ensure the base repository is `PySATL/pysatl-mpest` with the main branch, and the head repository is your fork and your working branch.
84104
4. Give your Pull Request a meaningful title (following the [Conventional Commits](https://www.google.com/url?sa=E&q=https%3A%2F%2Fwww.conventionalcommits.org%2F) standard) and add a detailed description of the changes you've made.
85105

86106
#### Rules for Your PR to be Merged
@@ -98,6 +118,3 @@ For your Pull Request to be merged, it must meet the following requirements conf
98118
Each pull request must be reviewed by one of the maintainers:
99119

100120
* Danil Totmyanin ([iraedeus](https://github.com/iraedeus))
101-
102-
103-

docs/design.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@
6464

6565
## 1.2. Цели документации
6666

67-
Документ предназначен для описания текущего состояния проекта `pysatl-mpest`.
67+
Документ предназначен для описания текущего состояния проекта `pysatl-mpest`.
6868

6969
Целевой аудиторией являются разработчики, которые будут принимать участие в разработке/расширении библиотеки. По большей части данная документация предназначается для тех, кто будет разбираться со структурой проекта на *Летней школе*.
7070

@@ -139,7 +139,7 @@ $$
139139

140140
#### Смеси распределений
141141

142-
Работа со смесями распределений идет через класс `MixtureDistribution`, который инициализируется с помощью списка объектов `Distribution`. Конкретные реализации распределений наследуются от `AModel`, после чего оборачиваются в класс `Distribution`.
142+
Работа со смесями распределений идет через класс `MixtureDistribution`, который инициализируется с помощью списка объектов `Distribution`. Конкретные реализации распределений наследуются от `AModel`, после чего оборачиваются в класс `Distribution`.
143143

144144
Некоторые реализации EM используют оптимизацию, при которой параметры могут выйти из области определения. Таким образом необходимо нормализовать параметры для того, чтобы они были определены на всем $\mathbb{R}$. Методы объектов `AModel` использует внутренние (internal) параметры, тогда как `Distribution` использует внешние (external) параметры, которые являются общепринятыми.
145145

@@ -160,7 +160,7 @@ $$
160160
- `Python`: Как основной язык.
161161
- `scipy`: На эту библиотеку делегировано сэмплирование, а так же написаны адаптеры к их оптимизаторам.
162162
- `numpy`: Для векторизации.
163-
- `matplotlib + seaborn`: Для визуализации данных (В основном используется в экспериментальном окружении).
163+
- `matplotlib + seaborn`: Для визуализации данных (В основном используется в экспериментальном окружении).
164164

165165

166166

@@ -238,7 +238,7 @@ $$
238238
- `LikelihoodMStep` (для MLE-EM): пересчитывает параметры моделей, максимизируя взвешенную логарифмическую функцию правдоподобия. Может использовать `AOptimizer` или `AOptimizerJacobian` для численной оптимизации.
239239
- `LMomentsMStep` (для ELM): пересчитывает параметры моделей на основе вычисленных L-моментов для каждого компонента смеси.
240240

241-
241+
242242

243243
## 3.4. Вспомогательные
244244

@@ -352,7 +352,7 @@ $$
352352

353353
3. **M-шаг:** вызывается `method.m_step.step(e_result)`:
354354

355-
Реализуется M-шаг алгоритма, возвращая результирующую смесь.
355+
Реализуется M-шаг алгоритма, возвращая результирующую смесь.
356356

357357
4. **Обновление состояния смеси:**
358358

@@ -434,7 +434,7 @@ sequenceDiagram
434434

435435
### Ядро (Mpest core)
436436

437-
1. Класс `Distribution` хоть и является оберткой для `AModel`, но не реализует всех его методов (например `lpdf`). Таким образом, для вызова нереализованных методов необходимо вызывать `model`, что плохо.
437+
1. Класс `Distribution` хоть и является оберткой для `AModel`, но не реализует всех его методов (например `lpdf`). Таким образом, для вызова нереализованных методов необходимо вызывать `model`, что плохо.
438438

439439
2. Для некоторых алгоритмов (не для всех) необходимо преобразовывать параметры так, чтобы они были на всем $\mathbb{R}$. Из-за этого появляется разделение на внутренние (*internal_params*) и внешние (*external_params*) параметры. Сейчас в коде, преобразование во внутренние параметры происходит перед началом алгоритма (для всех алгосов, даже для тех, для которых это не является необходимым), а в конце происходит переход к внешним параметрам (общепринятым).
440440

docs/source/_static/EM algo.svg

Lines changed: 1 addition & 1 deletion
Loading

docs/source/index.rst

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,3 @@ documentation for details.
2121
:caption: API:
2222

2323
api/modules
24-

docs/source/intro.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@
33
:caption: Introduction:
44

55
.. include:: ../../README.md
6-
:parser: myst_parser.sphinx_
6+
:parser: myst_parser.sphinx_

experimental_env/analysis/metrics.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@
44
from itertools import permutations
55

66
import numpy as np
7-
from scipy.integrate import quad
8-
97
from mpest import MixtureDistribution
108
from mpest.utils import ANamed
9+
from scipy.integrate import quad
1110

1211

1312
class AMetric(ANamed, ABC):

experimental_env/experiment/estimators.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,16 @@
55
from concurrent.futures import as_completed
66
from concurrent.futures.process import ProcessPoolExecutor
77

8-
from tqdm import tqdm
9-
10-
from experimental_env.utils import OrderedProblem, choose_best_mle
118
from mpest import Problem
129
from mpest.em import EM
1310
from mpest.em.methods.l_moments_method import LMomentsMStep
1411
from mpest.em.methods.likelihood_method import BayesEStep, LikelihoodMStep
1512
from mpest.em.methods.method import Method
1613
from mpest.optimizers import ALL_OPTIMIZERS
1714
from mpest.utils import ANamed, Factory, ResultWithLog
15+
from tqdm import tqdm
16+
17+
from experimental_env.utils import OrderedProblem, choose_best_mle
1818

1919
METHODS: dict = {
2020
"Likelihood": [[Factory(BayesEStep), Factory(LikelihoodMStep, optimizer)] for optimizer in ALL_OPTIMIZERS],

experimental_env/experiment/experiment_description.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@
33
from collections.abc import Iterable, Iterator
44

55
import numpy as np
6-
7-
from experimental_env.preparation.dataset_description import DatasetDescrciption
86
from mpest import MixtureDistribution
97
from mpest.utils import ResultWithLog
108

9+
from experimental_env.preparation.dataset_description import DatasetDescrciption
10+
1111

1212
class StepDescription:
1313
"""

0 commit comments

Comments
 (0)