Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions nibabies/utils/bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def parse_bids_for_age_months(

scans_tsv = session_level / f'{prefix}_scans.tsv'
if scans_tsv.exists():
age = _get_age_from_tsv(scans_tsv)
age = _get_age_from_tsv(scans_tsv, is_scans_tsv = True)

if age is not None:
return age
Expand All @@ -264,8 +264,8 @@ def parse_bids_for_age_months(


def _get_age_from_tsv(
bids_tsv: Path, index_column: str | None = None, index_val: str | None = None
) -> int | None:
bids_tsv: Path, index_column: str | None = None, index_val: str | None = None,
is_scans_tsv: bool = False) -> float | None:
import pandas as pd

df = pd.read_csv(str(bids_tsv), sep='\t')
Expand All @@ -277,6 +277,14 @@ def _get_age_from_tsv(
break
if age_col is None:
return

if is_scans_tsv: #If it is a scans.tsv, grab try to grab age from first anat file
try:
index_column = 'filename'
index_val = df.loc[df['filename'].str.startswith('anat'), 'filename'].iloc[0]
except:
index_column = None
index_val = None

if not index_column or not index_val: # Just grab first value
idx = df.index[0]
Expand All @@ -285,7 +293,7 @@ def _get_age_from_tsv(

try:
# extract age value from row
age = int(df.loc[idx, age_col].item())
age = float(df.loc[idx, age_col].item())
except Exception: # noqa: BLE001
return

Expand Down Expand Up @@ -318,12 +326,14 @@ def _get_age_units(bids_json: Path) -> ty.Literal['weeks', 'months', 'years', Fa
return False


def age_to_months(age: int, units: ty.Literal['weeks', 'months', 'years']) -> int:
def age_to_months(age: float, units: ty.Literal['weeks', 'months', 'years']) -> int:
"""
Convert a given age, in either "weeks", "months", or "years", into months.

>>> age_to_months(1, 'years')
12
>>> age_to_months(0.5, 'years')
6
>>> age_to_months(2, 'weeks')
0
>>> age_to_months(3, 'weeks')
Expand All @@ -337,5 +347,7 @@ def age_to_months(age: int, units: ty.Literal['weeks', 'months', 'years']) -> in
if units == 'weeks':
age = round(age * WEEKS_TO_MONTH)
elif units == 'years':
age *= YEARS_TO_MONTH
age = round(age * YEARS_TO_MONTH)
elif units == 'months':
age = round(age)
return age