Skip to content

Commit 2fe01c7

Browse files
authored
Merge pull request #1878 from nx10/cleanup-trstr2float
Refactor TR_string_to_float
2 parents e98ef2f + 173c946 commit 2fe01c7

File tree

2 files changed

+53
-5
lines changed

2 files changed

+53
-5
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import pytest
2+
3+
from CPAC.nuisance.utils import compcor
4+
5+
6+
def test_TR_string_to_float():
7+
assert abs(compcor.TR_string_to_float('123') - 123.) < 1e-08
8+
assert abs(compcor.TR_string_to_float('123s') - 123.) < 1e-08
9+
assert abs(compcor.TR_string_to_float('123ms') - 123. / 1000) < 1e-08
10+
11+
assert abs(compcor.TR_string_to_float('1.23') - 1.23) < 1e-08
12+
assert abs(compcor.TR_string_to_float('1.23s') - 1.23) < 1e-08
13+
assert abs(compcor.TR_string_to_float('1.23ms') - 1.23 / 1000) < 1e-08
14+
15+
with pytest.raises(Exception):
16+
compcor.TR_string_to_float(None)
17+
18+
with pytest.raises(Exception):
19+
compcor.TR_string_to_float(['123'])
20+
21+
with pytest.raises(Exception):
22+
compcor.TR_string_to_float(123)
23+
24+
with pytest.raises(Exception):
25+
compcor.TR_string_to_float('ms')

CPAC/nuisance/utils/compcor.py

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -181,9 +181,32 @@ def fallback_svd(a, full_matrices=True, compute_uv=True):
181181

182182

183183
def TR_string_to_float(tr):
184-
if 'ms' in tr:
185-
tr = float(tr.replace('ms', '')) / 1000
186-
else:
187-
tr = float(tr.replace('s', ''))
184+
"""
185+
Convert TR string to seconds (float). Suffixes 's' or 'ms' to indicate
186+
seconds or milliseconds.
187+
188+
Parameters
189+
----------
190+
tr : TR string representation. May use suffixes 's' or 'ms' to indicate
191+
seconds or milliseconds.
192+
193+
Returns
194+
-------
195+
tr in seconds (float)
196+
"""
197+
if not isinstance(tr, str):
198+
raise TypeError(f'Improper type for TR_string_to_float ({tr}).')
188199

189-
return tr
200+
tr_str = tr.replace(' ', '')
201+
202+
try:
203+
if tr_str.endswith('ms'):
204+
tr_numeric = float(tr_str[:-2]) * 0.001
205+
elif tr.endswith('s'):
206+
tr_numeric = float(tr_str[:-1])
207+
else:
208+
tr_numeric = float(tr_str)
209+
except Exception as exc:
210+
raise ValueError(f'Can not convert TR string to float: "{tr}".') from exc
211+
212+
return tr_numeric

0 commit comments

Comments
 (0)