Skip to content

Commit

Permalink
Refactor into a CLI (nipoppy#205)
Browse files Browse the repository at this point in the history
* move everything to legacy folder

* copy previous pyproject.toml

* bump version and clean up pyproject.toml

* add/update fields in pyproject.toml

* add minimal README

* remove empty .gitmodules

* add license

* add linting to pre-commit

* add dev setup to README

* add shields for license and black

* add flake8 config

* add very basic parsers

* add isort to pre-commit

* add very basic CLI

* add very basic logger

* add rich formatting for CLI

* ignore VS Code config files

* fix isort and black conflict

* add verbosity argument

* add dataset_root arg and do light cleanup

* add init subparser and refactor args/parsers

* add DatasetLayout class

* add method to create empty dataset

* add base class

* remove DatasetLayout.create(), to be used in workflow/runner

* add name parameter to logger

* add _Workflow class

* remove function docstrings from test files

* make _Base an abstract class

* refactor test function names

* add run methods to _Workflow class

* add DatasetInitWorkflow for nipoppy init

* fix typo in log_prefix_run_stdout

* catch all workflow/command exceptions in run.py

* add --dry-run flag

* add common/global option group

* use rich exception tracebacks

* improve default __str__ method and add tests for _Base

* add logging to file (but not for init)

* add CLI test for init

* add/update docstrings

* remove redundant license file

* add Pydantic config model for reading global configs

* add layout validation

* copy sample config file during init

* move workflows

* fix bad import

* try implementing a Manifest class with a schema (model)

* refactor manifest using abstract _Tabular class

* remove useless "after" validator

* implement basic doughnut class

* copy sample manifest file during init

* update warning message in init and remove cli return statement

* add config and manifest properties to _Workflow

* validate manifest visits/sessions against list

* add save_json util function (not used currently)

* add save() method to Config

* validate manifest sessions/visits (based on config) in _Workflow

* add add_record method to _Tabular

* add _Tabular.add_records() for list of records

* add tabular utilities for checking equality, sorting, saving to file

* add preliminary work on doughnut update workflow

* add working DoughnutWorkflow

* fix verbosity not parsed correctly

* minor changes to package structure and other things

* add _Workflow.doughnut property that automatically generates the doughnut if is missing

* add preliminary work on PipelineWorkflow

* make minor changes to logger, logger typing and workflow init arguments

* add generic pipeline utilities

* rename nipoppy.workflows.workflow -> nipoppy.workflow.base

* add boutiques and implement PipelineRunner

* update pipeline workflows and related things (MRIQC working)

* add/fix tests

* add `PipelineRunner` to CLI

* update pipeline-related workflows (fMRIPrep working)

* clean up _Workflow.run_command()

* light refactoring of package structure

* move PipelineRunner and PipelineTracker into their own files

* catch exceptions in run_single (don't crash)

* add basic tracking (only supports SUCCES and FAIL, only for pipeline_complete)

* add DicomReorgWorkflow

* add BIDS conversion workflow and descriptor for HeuDiConv

* fix Singularity/Boutiques config templating not being processed in runner

* add DESCRIPTOR_FILE field to config and make dcm2bids steps work

* move refactored code into subdirectory and move legacy code back out

* change new version to 1.0.0

* refactor DatasetLayout to use config and add custom layout option to workflows

* add top-level __init__.py

* fix workflows failing due to partial datasets

* add test checking that built-in pipelines and sample config work in simulate mode

* fix BIDS database tests after updating FIDS

* allow manifest to have extra columns and rename test data files

* minor improvements to tabular data handling, logging, and path utilities

* make DicomReorgWorkflow more modular so that it can be easily subclassed if needed

* add helpers for filesystem utilities for workflows so that they respect dry_run

* fix symlink bug and pass participant and session to DICOM reorg renaming function

* add workflow for running tests in `nipoppy_new`

* add __init__.py to tests directory

* fix conftest import statement so that tests hopefully run in CI

* update parser so that it renders better in docs

* apply precommit

* apply sourcery refactor suggestions

* accept suggestions for pytest options

Co-authored-by: Remi Gau <[email protected]>

* specify pytest version

Co-authored-by: Remi Gau <[email protected]>

* update tests based on Rémi comments

* rename nipoppy_new -> nipoppy_cli

* rename sample_data -> examples

* rename convert/converted -> bidsify/bidsfied

* remove "copy" log messages in InitWorkflow

* rename nipoppy.config.base -> nipoppy.config.main

* make VISITS (not SESSIONS) mandatory in Config

* rename Singularity things to "container" and use "apptainer" instead of "singularity"

* update author list

* rename data/layout -> data/layouts

* revert derivatives subdirectories to <pipeline_name>/<pipeline_version>

* address comments related to docstrings

* add Codecov for new test suite

* add tests for tracker

---------

Co-authored-by: Remi Gau <[email protected]>
  • Loading branch information
michellewang and Remi-Gau authored Apr 29, 2024
1 parent a84a0c8 commit 31da023
Show file tree
Hide file tree
Showing 87 changed files with 11,449 additions and 10 deletions.
11 changes: 9 additions & 2 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ exclude =
venv,
per-file-ignores =
# - docstrings rules that should not be applied to tests
tests/*: D100, D103, D104
**/test_*: D100, D103, D104
__init__.py:F401
# allow "weird indentation"
tests/test_workflow_*.py: D100, D103, D104, E131, E127, E501
max-line-length = 90
docstring-convention = numpy
max_complexity = 12
max_function_length = 150
# for compatibility with black
# https://black.readthedocs.io/en/stable/guides/using_black_with_other_tools.html#flake8
max-line-length = 88
extend-ignore = D105, E203, E704
49 changes: 49 additions & 0 deletions .github/workflows/run_tests_new.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
name: Run tests

on:
push:
branches: ['*']
pull_request:
branches: ['*']

# cancel previous runs if new one is triggered
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:

test:

runs-on: ubuntu-latest

# only trigger on upstream repo
if: github.repository_owner == 'neurodatascience' && github.event.repository.name == 'nipoppy'

steps:

- uses: actions/checkout@v3
with:
submodules: recursive

- uses: actions/setup-python@v4
with:
python-version: '3.11'

- name: Install package
run: |
cd nipoppy_cli
pip install -U pip
pip install .[tests]
- name: Run tests
run: |
python -m pytest nipoppy_cli --cov=nipoppy_cli/nipoppy --cov-report=xml
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v4
with:
file: ./coverage.xml
name: codecov-umbrella
token: ${{ secrets.CODECOV_TOKEN }}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,6 @@ htmlcov


env/

# VS Code
.vscode/
21 changes: 17 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
# See https://pre-commit.com/hooks.html for more hooks

repos:

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: check-ast
- id: check-case-conflict
Expand All @@ -15,9 +14,23 @@ repos:
- id: end-of-file-fixer
- id: trailing-whitespace
- id: check-toml

- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 23.12.1
hooks:
- id: black
args: [--config=pyproject.toml]
- repo: https://github.com/pyCQA/flake8
rev: 7.0.0
hooks:
- id: flake8
args: [--verbose, --config, .flake8]
additional_dependencies: [flake8-docstrings]
- repo: https://github.com/codespell-project/codespell
rev: v2.2.5
rev: v2.2.6
hooks:
- id: codespell
args: [--toml=pyproject.toml]
Expand Down
21 changes: 21 additions & 0 deletions nipoppy_cli/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 NeuroDataScience

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
26 changes: 26 additions & 0 deletions nipoppy_cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
![License](https://img.shields.io/badge/license-MIT-blue.svg)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.8084759.svg)](https://doi.org/10.5281/zenodo.8084759)
![https://github.com/psf/black](https://img.shields.io/badge/code%20style-black-000000.svg)

# Nipoppy

A framework for standardized organization and processing of neuroimaging-clinical datasets.

## Developer setup

Clone this repo:

```bash
git clone https://github.com/neurodatascience/nipoppy.git
```

Install `nipoppy` in editable mode with `dev` dependencies:
```bash
cd nipoppy
pip install -e .[dev]
```

Set up `pre-commit`:
```bash
pre-commit install
```
1 change: 1 addition & 0 deletions nipoppy_cli/nipoppy/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Nipoppy."""
71 changes: 71 additions & 0 deletions nipoppy_cli/nipoppy/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Base class."""

import inspect
from abc import ABC
from typing import Optional, Sequence


class Base(ABC):
"""Base class with utilities for pretty string representations."""

def _str_helper(
self,
components: Optional[Sequence] = None,
names: Optional[Sequence[str]] = None,
sep=", ",
) -> str:
"""Generate a custom string representation of an object.
The output string is of the form: ClassName(component1[sep]component2[sep]...)
Parameters
----------
components : Sequence, optional
Components to concatenate, by default None
names : Sequence[str], optional
Name of attributes to be added to the components as key-value pairs,
by default None
sep : str, optional
Separator between components, by default ", "
Returns
-------
str
String representation of the object.
"""
if components is None:
components = []

if names is not None:
for name in names:
components.append(f"{name}={getattr(self, name)}")

return f"{type(self).__name__}({sep.join([str(c) for c in components])})"

def __str__(self) -> str:
"""Return a string representation of the object based on its __init__ arguments.
Raises
------
RuntimeError
If the parameter names obtained from the __init__ method do not match the
attributes of the object.
"""
signature = inspect.signature(type(self))
names = [
name
for name, parameter in signature.parameters.items()
if parameter.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
]
try:
return self._str_helper(names=names)
except AttributeError:
raise RuntimeError(
f"The __init__ method of the {type(self)} class has positional and/or"
" keyword arguments that are not set as attributes of the object"
". Failed to build string representation: need to override the"
" __str__ method"
)

def __repr__(self) -> str:
return self.__str__()
1 change: 1 addition & 0 deletions nipoppy_cli/nipoppy/cli/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Parsers and entrypoint for the command-line interface."""
Loading

0 comments on commit 31da023

Please sign in to comment.