Skip to content

Commit 4151ec9

Browse files
janezdastaric
authored andcommitted
Merge pull request biolab#1807 from kernc/discretevar/ncolors--nvalues
DiscreteVariable: reset colors when new values added (cherry picked from commit 5fabe61)
1 parent e8b8156 commit 4151ec9

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

Orange/data/variable.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -568,14 +568,11 @@ def __init__(self, name="", values=(), ordered=False, base_value=-1, compute_val
568568
@property
569569
def colors(self):
570570
if self._colors is None:
571-
if "colors" in self.attributes:
572-
self._colors = np.array(
573-
[hex_to_color(col) for col in self.attributes["colors"]],
574-
dtype=np.uint8)
575-
else:
576-
from Orange.widgets.utils.colorpalette import \
577-
ColorPaletteGenerator
578-
self._colors = ColorPaletteGenerator.palette(self)
571+
from Orange.widgets.utils.colorpalette import ColorPaletteGenerator
572+
self._colors = ColorPaletteGenerator.palette(self)
573+
colors = self.attributes.get('colors')
574+
if colors:
575+
self._colors[:len(colors)] = [hex_to_color(color) for color in colors]
579576
self._colors.flags.writeable = False
580577
return self._colors
581578

@@ -636,6 +633,7 @@ def add_value(self, s):
636633
""" Add a value `s` to the list of values.
637634
"""
638635
self.values.append(s)
636+
self._colors = None
639637

640638
def val_from_str_add(self, s):
641639
"""

Orange/tests/test_variable.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ def test_repr(self):
215215
repr(var),
216216
"DiscreteVariable('a', values=['1', '2', '3', '4', '5', ...])")
217217

218-
@unittest.skipUnless(is_on_path("PyQt4"), "PyQt4 is not importable")
218+
@unittest.skipUnless(is_on_path("PyQt4") or is_on_path("PyQt5"), "PyQt is not importable")
219219
def test_colors(self):
220220
var = DiscreteVariable.make("a", values=["F", "M"])
221221
self.assertIsNone(var._colors)
@@ -236,6 +236,17 @@ def test_colors(self):
236236
var.attributes["colors"] = ['#0a0b0c', '#0d0e0f']
237237
np.testing.assert_almost_equal(var.colors, [[10, 11, 12], [13, 14, 15]])
238238

239+
# Test ncolors adapts to nvalues
240+
var = DiscreteVariable.make('foo', values=['d', 'r'])
241+
self.assertEqual(len(var.colors), 2)
242+
var.add_value('e')
243+
self.assertEqual(len(var.colors), 3)
244+
user_defined = (0, 0, 0)
245+
var.set_color(2, user_defined)
246+
var.add_value('k')
247+
self.assertEqual(len(var.colors), 4)
248+
np.testing.assert_array_equal(var.colors[2], user_defined)
249+
239250

240251
@variabletest(ContinuousVariable)
241252
class TestContinuousVariable(VariableTest):

0 commit comments

Comments
 (0)