Skip to content

Module dcm2bids.utils.io⚓︎

View Source
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# -*- coding: utf-8 -*-

import json

from pathlib import Path

from collections import OrderedDict

def load_json(filename):

    """ Load a JSON file

    Args:

        filename (str): Path of a JSON file

    Return:

        Dictionary of the JSON file

    """

    with open(filename, "r") as f:

        data = json.load(f, object_pairs_hook=OrderedDict)

    return data

def save_json(filename, data):

    with open(filename, "w") as f:

        json.dump(data, f, indent=4)

def write_txt(filename, lines):

    with open(filename, "w") as f:

        f.write(f"{lines}\n")

def valid_path(in_path, type="folder"):

    """Assert that file exists.

    Parameters

    ----------

    required_file: Path

        Path to be checked.

    """

    if isinstance(in_path, str):

        in_path = Path(in_path)

    if type == 'folder':

        if in_path.is_dir() or in_path.parent.is_dir():

            return in_path

        else:

            raise NotADirectoryError(in_path)

    elif type == "file":

        if in_path.is_file():

            return in_path

        else:

            raise FileNotFoundError(in_path)

    raise TypeError(type)

def update_participants_tsv(bids_dir, participant_name, logger):

    """Add a participant name to the participants.tsv file.

    Creates the participants.tsv file if it doesn't exist, and adds the

    participant name if not already present.

    Args:

        bids_dir (str or Path): Path to the BIDS directory

        participant_name (str): Name of the participant (e.g., 'sub-01')

        logger: Logger object for logging messages

    """

    if isinstance(bids_dir, str):

        bids_dir = Path(bids_dir)

    participants_file = bids_dir / "participants.tsv"

    existing_participants = set()

    # Read existing participants if file exists

    if participants_file.exists():

        with open(participants_file, "r") as f:

            lines = f.readlines()

            # Skip header line (participant_id)

            if len(lines) > 1:

                existing_participants = {line.split()[0] for line in lines[1:] if line.strip()}

    else:

        logger.info("Creating new participants.tsv file")

    # Add participant if not already present

    if participant_name not in existing_participants:

        existing_participants.add(participant_name)

        logger.info(f"Adding participant '{participant_name}' to participants.tsv")

        # Write participants.tsv with sorted participant IDs

        with open(participants_file, "w") as f:

            f.write("participant_id\n")

            for participant in sorted(existing_participants):

                f.write(f"{participant}\n")

    else:

        logger.info(f"Participant '{participant_name}' already in participants.tsv")

Functions⚓︎

load_json⚓︎

1
2
3
def load_json(
    filename
)

Load a JSON file

Parameters:

Name Type Description Default
filename str Path of a JSON file None
View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def load_json(filename):

    """ Load a JSON file

    Args:

        filename (str): Path of a JSON file

    Return:

        Dictionary of the JSON file

    """

    with open(filename, "r") as f:

        data = json.load(f, object_pairs_hook=OrderedDict)

    return data

save_json⚓︎

1
2
3
4
def save_json(
    filename,
    data
)
View Source
1
2
3
4
5
def save_json(filename, data):

    with open(filename, "w") as f:

        json.dump(data, f, indent=4)

update_participants_tsv⚓︎

1
2
3
4
5
def update_participants_tsv(
    bids_dir,
    participant_name,
    logger
)

Add a participant name to the participants.tsv file.

Creates the participants.tsv file if it doesn't exist, and adds the participant name if not already present.

Parameters:

Name Type Description Default
bids_dir str or Path Path to the BIDS directory None
participant_name str Name of the participant (e.g., 'sub-01') None
logger None Logger object for logging messages None
View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def update_participants_tsv(bids_dir, participant_name, logger):

    """Add a participant name to the participants.tsv file.

    Creates the participants.tsv file if it doesn't exist, and adds the

    participant name if not already present.

    Args:

        bids_dir (str or Path): Path to the BIDS directory

        participant_name (str): Name of the participant (e.g., 'sub-01')

        logger: Logger object for logging messages

    """

    if isinstance(bids_dir, str):

        bids_dir = Path(bids_dir)

    participants_file = bids_dir / "participants.tsv"

    existing_participants = set()

    # Read existing participants if file exists

    if participants_file.exists():

        with open(participants_file, "r") as f:

            lines = f.readlines()

            # Skip header line (participant_id)

            if len(lines) > 1:

                existing_participants = {line.split()[0] for line in lines[1:] if line.strip()}

    else:

        logger.info("Creating new participants.tsv file")

    # Add participant if not already present

    if participant_name not in existing_participants:

        existing_participants.add(participant_name)

        logger.info(f"Adding participant '{participant_name}' to participants.tsv")

        # Write participants.tsv with sorted participant IDs

        with open(participants_file, "w") as f:

            f.write("participant_id\n")

            for participant in sorted(existing_participants):

                f.write(f"{participant}\n")

    else:

        logger.info(f"Participant '{participant_name}' already in participants.tsv")

valid_path⚓︎

1
2
3
4
def valid_path(
    in_path,
    type='folder'
)

Assert that file exists.

Parameters:

Name Type Description Default
required_file Path Path to be checked. None
View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def valid_path(in_path, type="folder"):

    """Assert that file exists.

    Parameters

    ----------

    required_file: Path

        Path to be checked.

    """

    if isinstance(in_path, str):

        in_path = Path(in_path)

    if type == 'folder':

        if in_path.is_dir() or in_path.parent.is_dir():

            return in_path

        else:

            raise NotADirectoryError(in_path)

    elif type == "file":

        if in_path.is_file():

            return in_path

        else:

            raise FileNotFoundError(in_path)

    raise TypeError(type)

write_txt⚓︎

1
2
3
4
def write_txt(
    filename,
    lines
)
View Source
1
2
3
4
5
def write_txt(filename, lines):

    with open(filename, "w") as f:

        f.write(f"{lines}\n")