Skip to content

Commit

Permalink
Minor refactoring (renaming) and doc tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelzwiers committed Oct 2, 2023
1 parent da4e1a5 commit 636d692
Show file tree
Hide file tree
Showing 9 changed files with 30 additions and 32 deletions.
26 changes: 13 additions & 13 deletions bidscoin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,23 +56,23 @@
"""

# Define the default paths
tracking = {'url': 'https://telemetry.donders.ru.nl/bidscoin', 'sleep': 1} # Sleep = Nr of sleeping hours during which usage is not tracked
tutorialurl = 'https://surfdrive.surf.nl/files/index.php/s/HTxdUbykBZm2cYM/download'
bidscoinfolder = Path(__file__).parent
schemafolder = bidscoinfolder/'schema'
pluginfolder = bidscoinfolder/'plugins'
tracking = {'url': 'https://telemetry.donders.ru.nl/bidscoin', 'sleep': 1} # Sleep = Nr of sleeping hours during which usage is not tracked
tutorialurl = 'https://surfdrive.surf.nl/files/index.php/s/HTxdUbykBZm2cYM/download'
bidscoinfolder = Path(__file__).parent
schemafolder = bidscoinfolder/'schema'
pluginfolder = bidscoinfolder/'plugins'

# Create a BIDScoin user configuration directory if needed and load the BIDScoin user settings
configfile = Path.home()/'.bidscoin'/__version__/'config.toml'
heuristicsfolder = configfile.parent/'templates'
heuristicsfolder.mkdir(parents=True, exist_ok=True)
configfile = Path.home()/'.bidscoin'/__version__/'config.toml'
templatefolder = configfile.parent/'templates'
templatefolder.mkdir(parents=True, exist_ok=True)
if not configfile.is_file():
configfile.write_text(f"[bidscoin]\n"
f"bidsmap_template = '{configfile.parent}/templates/bidsmap_dccn.yaml' # The default template bidsmap\n"
f"trackusage = 'yes'\t# Upload anonymous usage data if 'yes' (maximally 1 upload every {tracking['sleep']} hour) (see `bidscoin --tracking show`)\n")
f"bidsmap_template = '{templatefolder}/bidsmap_dccn.yaml' # The default template bidsmap (change to use a different default)\n"
f"trackusage = 'yes' # Upload anonymous usage data if 'yes' (maximally 1 upload every {tracking['sleep']} hour) (see `bidscoin --tracking show`)\n")
for template in (bidscoinfolder/'heuristics').glob('*.yaml'):
if not (heuristicsfolder/template.name).is_file():
shutil.copyfile(template, heuristicsfolder/template.name)
if not (templatefolder/template.name).is_file():
shutil.copyfile(template, templatefolder/template.name)
with configfile.open('+rb') as fid:
config = tomllib.load(fid)
bidsmap_template = Path(config['bidscoin']['bidsmap_template'])
Expand Down Expand Up @@ -162,6 +162,6 @@ def trackusage(event: str, dryrun: bool=False) -> dict:
req = urllib.request.Request(f"{tracking['url']}?{urllib.parse.urlencode(data)}", headers={'User-agent': 'bidscoin-telemetry'})
with urllib.request.urlopen(req, timeout=5) as f: pass
except urllib.error.URLError as urlerror:
print(urlerror)
print(f"{tracking['url']}:\n{urlerror}")

return data
10 changes: 5 additions & 5 deletions bidscoin/bcoin.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from importlib.util import find_spec
if find_spec('bidscoin') is None:
sys.path.append(str(Path(__file__).parents[1]))
from bidscoin import heuristicsfolder, pluginfolder, bidsmap_template, tutorialurl, trackusage, tracking, configfile, config
from bidscoin import templatefolder, pluginfolder, bidsmap_template, tutorialurl, trackusage, tracking, configfile, config

yaml = YAML()

Expand Down Expand Up @@ -204,9 +204,9 @@ def list_plugins(show: bool=False) -> Tuple[List[Path], List[Path]]:
:return: List of the installed plugins and template bidsmaps
"""

if show: LOGGER.info(f"Installed template bidsmaps ({heuristicsfolder}):")
if show: LOGGER.info(f"Installed template bidsmaps ({templatefolder}):")
templates = []
for template in heuristicsfolder.glob('*.yaml'):
for template in templatefolder.glob('*.yaml'):
if template.stem != '__init__':
templates.append(template)
if show: LOGGER.info(f"- {template.stem}{' (default)' if template.samefile(bidsmap_template) else ''}")
Expand Down Expand Up @@ -241,7 +241,7 @@ def install_plugins(filenames: List[str]=()) -> None:
for file in files:

# Copy the file to their target folder
targetfolder = heuristicsfolder if file.suffix == '.yaml' else pluginfolder
targetfolder = templatefolder if file.suffix == '.yaml' else pluginfolder
LOGGER.info(f"Installing: '{file}'")
try:
shutil.copyfile(file, targetfolder/file.name)
Expand Down Expand Up @@ -301,7 +301,7 @@ def uninstall_plugins(filenames: List[str]=(), wipe: bool=True) -> None:

# Remove the file from the target folder
LOGGER.info(f"Uninstalling: '{file}'")
sourcefolder = heuristicsfolder if file.suffix == '.yaml' else pluginfolder
sourcefolder = templatefolder if file.suffix == '.yaml' else pluginfolder
try:
(sourcefolder/file.name).unlink()
except IOError as uninstall_error:
Expand Down
8 changes: 4 additions & 4 deletions bidscoin/bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
if find_spec('bidscoin') is None:
import sys
sys.path.append(str(Path(__file__).parents[1]))
from bidscoin import bcoin, schemafolder, heuristicsfolder, bidsmap_template, lsdirs, __version__
from bidscoin import bcoin, schemafolder, templatefolder, bidsmap_template, lsdirs, __version__
from bidscoin.utilities import dicomsort
from ruamel.yaml import YAML
yaml = YAML()
Expand Down Expand Up @@ -866,7 +866,7 @@ def load_bidsmap(yamlfile: Path, folder: Path=Path(), plugins:Union[tuple,list]=

# Input checking
if not folder.name or not folder.is_dir():
folder = heuristicsfolder
folder = templatefolder
if not yamlfile.name:
yamlfile = folder/'bidsmap.yaml'
if not yamlfile.is_file():
Expand All @@ -881,7 +881,7 @@ def load_bidsmap(yamlfile: Path, folder: Path=Path(), plugins:Union[tuple,list]=
if (folder/yamlfile).is_file():
yamlfile = folder/yamlfile
else:
yamlfile = heuristicsfolder/yamlfile
yamlfile = templatefolder/yamlfile

if not yamlfile.is_file():
LOGGER.verbose(f"No existing bidsmap file found: {yamlfile}")
Expand Down Expand Up @@ -916,7 +916,7 @@ def load_bidsmap(yamlfile: Path, folder: Path=Path(), plugins:Union[tuple,list]=
if not bidsmap['Options']['plugins'].get(plugin):
LOGGER.info(f"Adding default bidsmap options from the {plugin} plugin")
bidsmap['Options']['plugins'][plugin] = module.OPTIONS if 'OPTIONS' in dir(module) else {}
if 'BIDSMAP' in dir(module) and yamlfile.parent == heuristicsfolder:
if 'BIDSMAP' in dir(module) and yamlfile.parent == templatefolder:
for dataformat, bidsmappings in module.BIDSMAP.items():
if dataformat not in bidsmap:
LOGGER.info(f"Adding default bidsmappings from the {plugin} plugin")
Expand Down
5 changes: 3 additions & 2 deletions bidscoin/cli/_bcoin.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
$ bidsmapper sourcefolder bidsfolder # This produces a study bidsmap and launches a GUI
$ bidscoiner sourcefolder bidsfolder # This converts your data to BIDS according to the study bidsmap
Set the environment variable BIDSCOIN_DEBUG=TRUE in your console to run BIDScoin in its more verbose DEBUG logging mode
Set the environment variable BIDSCOIN_DEBUG=TRUE in your console to run BIDScoin in its more verbose DEBUG logging mode.
Default setting are stored in the ".bidscoin" folder in your home directory
For more documentation see: https://bidscoin.readthedocs.io
"""
Expand Down Expand Up @@ -46,7 +47,7 @@ def get_parser() -> argparse.ArgumentParser:
parser.add_argument('-d', '--download', help='Download tutorial MRI data to the DOWNLOAD folder')
parser.add_argument('-t', '--test', help='Test the bidscoin installation and template bidsmap', nargs='?', const=bidsmap_template)
parser.add_argument('-b', '--bidsmaptest', help='Test the run-items and their bidsnames of all normal runs in the study bidsmap. Provide the bids-folder or the bidsmap filepath')
parser.add_argument( '--tracking', help='Show the usage tracking info [show], or set usage tracking to [yes] or [no]', choices=['yes','no','show'])
parser.add_argument( '--tracking', help='Show the usage tracking info {show}, or set usage tracking to {yes} or {no}', choices=['yes','no','show'])
parser.add_argument('-v', '--version', help='Show the installed version and check for updates', action='version', version=f"BIDS-version:\t\t{bidsversion()}\nBIDScoin-version:\t{__version__}, {versionmessage}")

return parser
2 changes: 1 addition & 1 deletion docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ All notable changes to this project will be documented in this file. The format
- Optional usage tracking (github issue #200)

### Changed
- The template bidsmaps are now stored in `[home]/.bidscoin/templates`
- The template bidsmaps are now stored in `[home]/.bidscoin/[version]/templates`

## [4.1.1] - 2023-09-14

Expand Down
5 changes: 1 addition & 4 deletions docs/bidsmap.rst
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ The run-items in the default 'bidsmap_dccn' template bidsmap have values that ar
- Finally, it is a good practice for the first run-item in each BIDS datatype section of your template bidsmap to have all empty `properties` and `attributes` values. The benefit of this is that you can dereference ('copy') it in other run-items (see the editing section below), and in this way improve your consistency and reduce the maintenance burden of keeping your template bidsmap up-to-date. The first run-item is also the item that is selected when a user manually sets the run-item to this BIDS datatype in the bidseditor GUI.

.. tip::
- Make a copy of the DCCN template (``[home]/.bidscoin/templates/bidsmap_dccn.yaml``) as a starting point for your own template bidsmap, and adapt it to your needs. You can set your copy as the new default by editing the ``[home]/.bidscoin/config.toml`` file.
- Make a copy of the DCCN template (``[home]/.bidscoin/[version]/templates/bidsmap_dccn.yaml``) as a starting point for your own template bidsmap, and adapt it to your needs. You can set your copy as the new default template by editing the ``[home]/.bidscoin/config.toml`` file. Default templates and config file are automatically recreated from source when deleted
- The power of regular expressions is nearly unlimited, you can e.g. use `negative look aheads <https://docs.python.org/3/howto/regex.html#lookahead-assertions>`__ to **not** match (exclude) certain strings
- When creating new run-items, make sure to adhere to the YAML format and to the definitions in the BIDS schema files (``[path_to_bidscoin]/bidscoin/schema/datatypes``). You can test your YAML syntax using an online `YAML-validator <https://www.yamllint.com>`__ and your compliance with the BIDS standard with ``bidscoin -t your_template_bidsmap``. If all seems well you can install it using ``bidscoin -i your_template_bidsmap``.

Expand Down Expand Up @@ -148,6 +148,3 @@ Editing the template bidsmap
suffix: T2w
*Snippet derived from the bidsmap_dccn template, showing a "DICOM" section with a void "anat" run-item and two normal run-items that dereference the first run-item* (e.g. the ``&anatattributes_dicom`` anchor is dereferenced with the ``<<: *anatattributes_dicom`` alias)

.. tip::
The path of the default template bidsmap is set in the ``.bidscoin'/version/'config.toml`` file in your home directory
2 changes: 1 addition & 1 deletion docs/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Dcm2niix installation

The default 'dcm2niix2bids' plugin relies on an external application named `dcm2niix <https://www.nitrc.org/plugins/mwiki/index.php/dcm2nii:MainPage>`__ for converting DICOM and PAR/REC source data to NIfTI. To use the plugin you must pip-install dcm2niix when installing BIDScoin or install it yourself (e.g. when pip-installing dcm2niix does not work for your platform) as explained in the `dcm2niix installation instructions <https://github.com/rordenlab/dcm2niix#install>`__. When done, make sure that the dcm2niix executable is on your user or system path (Windows users can add the path permanently, e.g. by running: ``setx path "%path%;C:\Program Files\dcm2niix"``). Otherwise (for instance when you want to use the linux module system or fixate the software version), make sure that the command to run the dcm2niix executable (exactly as if you would run it yourself in your command terminal) is set correctly in the `Options`_ section in your bidsmap. This can be done in two ways:

1. Open your template bidsmap with a text editor and adjust the settings as needed. The default template bidsmap is located in your ``[home]/.bidscoin/templates`` folder (see the output of ``bidscoin -p`` for the fullpath location on your system).
1. Open your template bidsmap with a text editor and adjust the settings as needed. The default template bidsmap is located in your ``[home]/.bidscoin/[version]/templates`` folder (see the output of ``bidscoin -p`` for the fullpath location on your system).
2. Go to the `Options`_ tab the first time the BIDScoin GUI is launched and adjust the settings as needed. Then click the [Set as default] button to save the settings to your default template bidsmap.

.. tip::
Expand Down
2 changes: 1 addition & 1 deletion docs/options.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ BIDScoin has different options and settings (see below) that can be adjusted per
The bidseditor options window with the different settings for BIDScoin and its plugins. The user can manage the plugins that will be used with the [Add] (as shown here) and [Remove] buttons, and save the current options to the template bidsmap by using the [Set as default] button.

.. note::
A few more adjustable global settings can be found in the ``.bidscoin'/version/'config.toml`` file in your home directory
A few more adjustable global settings can be found in your ``[home]/.bidscoin'/[version]/'config.toml`` file (the original file will be automatically recreated from source when deleted)

BIDScoin
--------
Expand Down
2 changes: 1 addition & 1 deletion tests/test_bcoin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
bcoin.setup_logging()

assert bidscoin.schemafolder.is_dir()
assert bidscoin.heuristicsfolder.is_dir()
assert bidscoin.templatefolder.is_dir()
assert bidscoin.pluginfolder.is_dir()
assert bidscoin.bidsmap_template.is_file()

Expand Down

0 comments on commit 636d692

Please sign in to comment.