Skip to content

Commit bcbfb78

Browse files
matthew-bretteffigies
authored andcommitted
RF: refactor labeltable checking
Put labeltable value checking into Cifti2Label class. Add converter to check float is between 0 and 1.
1 parent f5866a9 commit bcbfb78

File tree

2 files changed

+56
-48
lines changed

2 files changed

+56
-48
lines changed

nibabel/cifti2/cifti2.py

Lines changed: 37 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@
2828
from ..nifti2 import Nifti2Image
2929

3030

31+
def _float_01(val):
32+
out = float(val)
33+
if out < 0 or out > 1:
34+
raise ValueError('Float must be between 0 and 1 inclusive')
35+
return out
36+
37+
3138
class CIFTI2HeaderError(Exception):
3239
""" Error in CIFTI2 header
3340
"""
@@ -171,26 +178,14 @@ def __setitem__(self, key, value):
171178
if key != value.key:
172179
raise ValueError("The key and the label's key must agree")
173180
self._labels[key] = value
174-
else:
175-
try:
176-
key = int(key)
177-
v = (str(value[0]),) + tuple(float(v) for v in value[1:] if 0 <= float(v) <= 1)
178-
if len(v) != 5:
179-
raise ValueError
180-
except:
181-
raise ValueError(
182-
'Key must be integer and value a string and 4-tuple of floats between 0 and 1'
183-
)
184-
185-
label = Cifti2Label(
186-
key=key,
187-
label=v[0],
188-
red=v[1],
189-
green=v[2],
190-
blue=v[3],
191-
alpha=v[4]
192-
)
193-
self._labels[key] = label
181+
return
182+
if len(value) != 5:
183+
raise ValueError('Value should be length 5')
184+
try:
185+
self._labels[key] = Cifti2Label(*([key] + list(value)))
186+
except ValueError:
187+
raise ValueError('Key should be int, value should be sequence '
188+
'of str and 4 floats between 0 and 1')
194189

195190
def __delitem__(self, key):
196191
del self._labels[key]
@@ -215,27 +210,26 @@ class Cifti2Label(xml.XmlSerializable):
215210
216211
Attributes
217212
----------
218-
key : int
213+
key : int, optional
219214
Integer, data value which is assigned this name and color.
220-
label : str
215+
label : str, optional
221216
Name of the label.
222-
red : None or float
223-
Red color component for label.
224-
green : None or float
225-
Green color component for label.
226-
blue : None or float
227-
Blue color component for label.
228-
alpha : None or float
229-
Alpha color component for label.
217+
red : float, optional
218+
Red color component for label (between 0 and 1).
219+
green : float, optional
220+
Green color component for label (between 0 and 1).
221+
blue : float, optional
222+
Blue color component for label (between 0 and 1).
223+
alpha : float, optional
224+
Alpha color component for label (between 0 and 1).
230225
"""
231-
def __init__(self, key=0, label='', red=0, green=0, blue=0,
232-
alpha=0):
233-
self.key = key
234-
self.label = label
235-
self.red = red
236-
self.green = green
237-
self.blue = blue
238-
self.alpha = alpha
226+
def __init__(self, key=0, label='', red=0., green=0., blue=0., alpha=0.):
227+
self.key = int(key)
228+
self.label = str(label)
229+
self.red = _float_01(red)
230+
self.green = _float_01(green)
231+
self.blue = _float_01(blue)
232+
self.alpha = _float_01(alpha)
239233

240234
@property
241235
def rgba(self):
@@ -251,21 +245,20 @@ def _to_xml_element(self):
251245
raise CIFTI2HeaderError('The key must be an integer')
252246
for c_ in ('red', 'blue', 'green', 'alpha'):
253247
try:
254-
v = float(getattr(self, c_))
255-
if not (0 <= v <= 1):
256-
raise ValueError
248+
v = _float_01(getattr(self, c_))
257249
except ValueError:
258250
raise CIFTI2HeaderError(
259-
'Label invalid %s needs to be a float between 0 and 1. and it is %s' %
260-
(c_, v)
251+
'Label invalid %s needs to be a float between 0 and 1. '
252+
'and it is %s' % (c_, v)
261253
)
262254

263255
lab = xml.Element('Label')
264256
lab.attrib['Key'] = str(self.key)
265257
lab.text = str(self.label)
266258

267259
for name in ('red', 'green', 'blue', 'alpha'):
268-
attr = str(getattr(self, name))
260+
val = getattr(self, name)
261+
attr = '0' if val == 0 else '1' if val == 1 else str(val)
269262
lab.attrib[name.capitalize()] = attr
270263
return lab
271264

nibabel/cifti2/tests/test_cifti2.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@
66
import numpy as np
77

88
from nibabel import cifti2 as ci
9+
from nibabel.cifti2.cifti2 import _float_01
910

10-
from nose.tools import assert_equal, assert_raises, assert_is_none
11+
from nose.tools import assert_true, assert_equal, assert_raises, assert_is_none
1112

1213

1314
def compare_xml_leaf(str1, str2):
@@ -57,6 +58,18 @@ def test_cifti2_metadata():
5758
'<MetaData><MD><Name>b</Name><Value>bval</Value></MD></MetaData>')
5859

5960

61+
def test__float_01():
62+
assert_equal(_float_01(0), 0)
63+
assert_equal(_float_01(1), 1)
64+
assert_equal(_float_01('0'), 0)
65+
assert_equal(_float_01('0.2'), 0.2)
66+
assert_raises(ValueError, _float_01, 1.1)
67+
assert_raises(ValueError, _float_01, -0.1)
68+
assert_raises(ValueError, _float_01, 2)
69+
assert_raises(ValueError, _float_01, -1)
70+
assert_raises(ValueError, _float_01, 'foo')
71+
72+
6073
def test_cifti2_labeltable():
6174
lt = ci.Cifti2LabelTable()
6275
assert_equal(len(lt), 0)
@@ -84,14 +97,16 @@ def test_cifti2_labeltable():
8497

8598
assert_raises(ValueError, lt.__setitem__, 1, label)
8699
assert_raises(ValueError, lt.__setitem__, 0, test_tuple[:-1])
87-
100+
assert_raises(ValueError, lt.__setitem__, 0, ('foo', 1.1, 0, 0, 1))
101+
assert_raises(ValueError, lt.__setitem__, 0, ('foo', 1.0, -1, 0, 1))
102+
assert_raises(ValueError, lt.__setitem__, 0, ('foo', 1.0, 0, -0.1, 1))
88103

89104
def test_cifti2_label():
90105
lb = ci.Cifti2Label()
91106
lb.label = 'Test'
92107
lb.key = 0
93108
assert_equal(lb.rgba, (0, 0, 0, 0))
94-
assert(compare_xml_leaf(
109+
assert_true(compare_xml_leaf(
95110
lb.to_xml().decode('utf-8'),
96111
"<Label Key='0' Red='0' Green='0' Blue='0' Alpha='0'>Test</Label>"
97112
))
@@ -102,7 +117,7 @@ def test_cifti2_label():
102117
lb.alpha = 0.3
103118
assert_equal(lb.rgba, (0, 0.1, 0.2, 0.3))
104119

105-
assert(compare_xml_leaf(
120+
assert_true(compare_xml_leaf(
106121
lb.to_xml().decode('utf-8'),
107122
"<Label Key='0' Red='0' Green='0.1' Blue='0.2' Alpha='0.3'>Test</Label>"
108123
))

0 commit comments

Comments
 (0)