Skip to content

colors

Add/adjust alpha for color.

Source code in navis/plotting/colors.py
576
577
578
def add_alpha(c, alpha):
    """Add/adjust alpha for color."""
    return (c[0], c[1], c[2], alpha)

Convert color to int-packed color.

See also StackOverflow: https://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python?rq=1

PARAMETER DESCRIPTION
color
    A single color either as str (name or hex) or as RGB(A). RGB
    tuple must be in range 0-255! Alpha channel is ignored. Integers
    are just passed-through.

TYPE: str | tuple

Examples:

>>> from navis.plotting.colors import color_to_int
>>> color_to_int('r')
16711680
>>> color_to_int((255, 0, 0))
16711680
>>> color_to_int((0, 255, 0))
65280
Source code in navis/plotting/colors.py
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
def color_to_int(color: AnyColor) -> int:
    """Convert color to int-packed color.

    See also StackOverflow:
    https://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python?rq=1

    Parameters
    ----------
    color :     str | tuple
                A single color either as str (name or hex) or as RGB(A). RGB
                tuple must be in range 0-255! Alpha channel is ignored. Integers
                are just passed-through.

    Examples
    --------
    >>> from navis.plotting.colors import color_to_int
    >>> color_to_int('r')
    16711680
    >>> color_to_int((255, 0, 0))
    16711680
    >>> color_to_int((0, 255, 0))
    65280

    """
    if isinstance(color, int):
        return color
    elif isinstance(color, str):
        color = np.array(mcl.to_rgb(color)) * 255
    else:
        color = np.asarray(color)

    r, g, b = color.astype(int)[:3]

    return int('%02x%02x%02x' % (r, g, b), 16)

Divide colorspace into N evenly distributed colors.

RETURNS DESCRIPTION
colormap

[(r, g, b), (r, g, b), ...]

TYPE: list

Source code in navis/plotting/colors.py
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
def generate_colors(N: int,
                    palette: str = 'hls',
                    color_range: Union[Literal[1],
                                       Literal[255]] = 1
                    ) -> List[Tuple[float, float, float]]:
    """Divide colorspace into N evenly distributed colors.

    Returns
    -------
    colormap :  list
                [(r, g, b), (r, g, b), ...]

    """
    if N == 1:
        return [eval_color(config.default_color, color_range)]
    elif N == 0:
        return []

    if not isinstance(palette, str):
        palette = 'hls'

    colormap = sns.color_palette(palette, N)

    if color_range == 255:
        colormap = [(int(c[0] * 255), int(c[1] * 255), int(c[2] * 255)) for c in colormap]

    return colormap

Convert hex to rgb.

Source code in navis/plotting/colors.py
638
639
640
641
642
def hex_to_rgb(value: str) -> Tuple[int, int, int]:
    """Convert hex to rgb."""
    value = value.lstrip('#')
    lv = len(value)
    return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))  # type: ignore

Map color(s) onto list of objects.

PARAMETER DESCRIPTION
colors
        Color(s) to map onto `objects`. Can be::

          str: e.g. "blue", "k" or "y"
          tuple: (0, 0, 1), (0, 0, 0) or (0, 1, 1)
          list-like of the above: [(0, 0, 1), 'r', 'k', ...]
          dict mapping objects to colors: {object1: 'r',
                                           object2: (1, 1, 1)}

        If list-like or dict do not cover all `objects`, will
        fall back to `navis.config.default_color`. If `None`,
        will generate evenly spread out colors.

TYPE: None | str | tuple | list-like | dict | None

objects
        Object(s) to map color onto.

TYPE: list-like

color_range

TYPE: int DEFAULT: 255

RETURNS DESCRIPTION
list of tuples

Will match length of objects.

Source code in navis/plotting/colors.py
 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
def map_colors(colors: Optional[Union[str,
                                      Tuple[float, float, float],
                                      Dict[Any, str],
                                      Dict[Any, Tuple[float, float, float]],
                                      List[Union[str,
                                                 Tuple[float, float, float]]
                                           ]
                                      ]
                                ],
               objects: Sequence[Any],
               color_range: Union[Literal[1], Literal[255]] = 255
               ) -> List[Tuple[float, float, float]]:
    """Map color(s) onto list of objects.

    Parameters
    ----------
    colors :        None | str | tuple | list-like | dict | None
                    Color(s) to map onto `objects`. Can be::

                      str: e.g. "blue", "k" or "y"
                      tuple: (0, 0, 1), (0, 0, 0) or (0, 1, 1)
                      list-like of the above: [(0, 0, 1), 'r', 'k', ...]
                      dict mapping objects to colors: {object1: 'r',
                                                       object2: (1, 1, 1)}

                    If list-like or dict do not cover all `objects`, will
                    fall back to `navis.config.default_color`. If `None`,
                    will generate evenly spread out colors.

    objects :       list-like
                    Object(s) to map color onto.
    color_range :   int, optional

    Returns
    -------
    list of tuples
                    Will match length of `objects`.

    """
    if not utils.is_iterable(objects):
        objects = [objects]

    # If no colors, generate random colors
    if isinstance(colors, type(None)):
        if len(objects) == 1:
            return [eval_color(config.default_color, color_range)]
        return generate_colors(len(objects),
                               color_range=color_range)

    # Bring colors in the right space
    colors = eval_color(colors, color_range=color_range)

    # Match them to objects
    if isinstance(colors, dict):
        # If dict, try mapping to objects
        if set(objects) - set(colors.keys()):
            logger.warning('Objects w/o colors - falling back to default.')
        return [colors.get(o, config.default_color) for o in objects]
    elif isinstance(colors, tuple):
        # If single color map to each object
        return [colors] * len(objects)
    elif isinstance(colors, list):
        # If list of correct length, map onto objets
        if len(colors) != len(objects):
            logger.warning('N colours does not match N objects.')
        miss = len(objects) - len(colors) if len(objects) > len(colors) else 0
        return colors[: len(objects)] + [config.default_color] * miss
    else:
        raise TypeError(f'Unable to interpret colors of type "{type(colors)}"')

Map color(s) to neuron/dotprop colorlists.

Source code in navis/plotting/colors.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
def prepare_colormap(colors,
                     neurons: Optional['core.NeuronObject'] = None,
                     volumes: Optional[List] = None,
                     alpha: Optional[float] = None,
                     color_by: Optional[List[Any]] = None,
                     palette: Optional[str] = None,
                     color_range: Union[Literal[1],
                                        Literal[255]] = 255):
    """Map color(s) to neuron/dotprop colorlists."""
    # Prepare dummies in case either no neuron data, no dotprops or no volumes
    if isinstance(neurons, type(None)):
        neurons = core.NeuronList([])
    elif not isinstance(neurons, core.NeuronList):
        neurons = core.NeuronList((neurons))

    if isinstance(volumes, type(None)):
        volumes = np.array([])

    if not isinstance(volumes, np.ndarray):
        volumes = np.array(volumes)

    # Only neurons absolutely REQUIRE a color
    # (Volumes are second class citiziens here)
    colors_required = neurons.shape[0]

    if not colors_required and not len(volumes):
        # If no neurons to plot, just return None
        # This happens when there is only a scatter plot
        return [None], [None]

    # If labels are provided override all existing colors
    if not isinstance(color_by, type(None)):
        if isinstance(color_by, str):
            color_by = getattr(neurons, color_by)

        color_by = utils.make_iterable(color_by)
        if len(color_by) != len(neurons):
            raise ValueError('Must provide a label for all neurons: got '
                             f'{len(color_by)} groups for {len(neurons)} neurons')

        # Turn e.g. labels into colors
        cmap = {g: c for g, c in zip(np.unique(color_by),
                                     generate_colors(len(np.unique(color_by)),
                                                     palette=palette,
                                                     color_range=color_range))}

        colors = []
        for cb in color_by:
            if utils.is_iterable(cb):
                colors.append(np.array([cmap[g] for g in cb]))
            else:
                colors += [cmap[cb]]

        colors += [getattr(v, 'color', (1, 1, 1)) for v in volumes]

    # If no colors, generate random colors
    if isinstance(colors, type(None)):
        colors = []
        colors += generate_colors(colors_required,
                                  palette=palette,
                                  color_range=color_range)
        colors += [getattr(v, 'color', (1, 1, 1)) for v in volumes]

    # We need to parse once here to convert named colours to rgb
    colors = eval_color(colors, color_range=color_range)

    # If dictionary, map colors to neuron IDs
    neuron_cmap = []
    volumes_cmap = []
    dc = config.default_color
    if isinstance(colors, dict):
        # Try finding color first by neuron, then uuid and finally by name
        neuron_cmap = []
        for n in neurons:
            this_c = dc
            for k in [n, n.id, n.name]:
                if k in colors:
                    this_c = colors[k]
                    break
            neuron_cmap.append(this_c)

        # Try finding color first by volume, then uuid and finally by name
        # If no color found, fall back to color property
        volumes_cmap = []
        for v in volumes:
            this_c = getattr(v, 'color', (.95, .95, .95, .1))
            for k in [v, v.id, getattr(v, 'name', None)]:
                if k and k in colors:
                    this_c = colors[k]
                    break
            volumes_cmap.append(this_c)
    elif isinstance(colors, mcl.Colormap):
        # Generate colors for neurons and dotprops
        neuron_cmap = [colors(i / len(neurons)) for i in range(len(neurons))]

        # Colormaps are not applied to volumes
        volumes_cmap = [getattr(v, 'color', (.95, .95, .95, .1)) for v in volumes]
    # If list of colors
    elif isinstance(colors, (list, tuple, np.ndarray)):
        if isinstance(colors, np.ndarray):
            # If this is an array of a single color convert to rgba tuple
            if colors.ndim == 1 and colors.shape[0] in (3, 4):
                colors = colors.tolist()
            # If this is an array of multiple colors convert to list of rgba arrays
            elif colors.ndim == 2:
                colors = [c for c in colors]

        # If color is a single color, convert to list of colors, one for each neuron
        if all([isinstance(elem, numbers.Number) for elem in colors]):
            # Generate at least one color
            colors = [colors] * max(colors_required, 1)

        if len(colors) < colors_required:
            raise ValueError(f'Need colors for {colors_required} neurons, '
                             f'got {len(colors)}')
        elif len(colors) > colors_required:
            logger.debug(f'More colors than required: got {len(colors)}, '
                         f'needed {colors_required}')

        if len(neurons):
            neuron_cmap = [colors.pop(0) for i in range(neurons.shape[0])]

        if len(volumes):
            # Volume have their own color property as fallback
            volumes_cmap = []
            for v in volumes:
                if colors:
                    volumes_cmap.append(colors.pop(0))
                else:
                    volumes_cmap.append(getattr(v, 'color', (.8, .8, .8, .2)))
    else:
        raise TypeError(f'Unable to parse colors of type "{type(colors)}"')

    # If alpha is given, we will override all values
    if not isinstance(alpha, type(None)):
        if isinstance(alpha, numbers.Number):
            neuron_cmap = [add_alpha(c, alpha) for c in neuron_cmap]
        elif isinstance(alpha, (list, tuple, np.ndarray)):
            if len(alpha) != len(neurons):
                raise ValueError(f'Need alpha for {len(neurons)} neurons, '
                                 f'got {len(alpha)}')
            neuron_cmap = [add_alpha(c, a) for c, a in zip(neuron_cmap, alpha)]
        else:
            raise TypeError(f'Unable to parse alpha of type "{type(alpha)}"')

        # Only apply to volumes if there aren't any neurons
        if not neuron_cmap:
            if not isinstance(alpha, numbers.Number):
                raise ValueError('Must provide single alpha value for volumes.')
            volumes_cmap = [add_alpha(c, alpha) for c in volumes_cmap]

    # Make sure colour range checks out
    neuron_cmap = [eval_color(c, color_range=color_range)
                   for c in neuron_cmap]
    volumes_cmap = [eval_color(c, color_range=color_range)
                    for c in volumes_cmap]

    logger.debug('Neuron colormap: ' + str(neuron_cmap))
    logger.debug('Volumes colormap: ' + str(volumes_cmap))

    return neuron_cmap, volumes_cmap

Look for "label" or "type" column in connector tables and generates a color for every unique type. See navis.set_default_connector_colors.

RETURNS DESCRIPTION
dict

Maps type to color. Will be empty if no types.

Source code in navis/plotting/colors.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def prepare_connector_cmap(x) -> Dict[str, Tuple[float, float, float]]:
    """Look for "label" or "type" column in connector tables and generates
    a color for every unique type. See `navis.set_default_connector_colors`.

    Returns
    -------
    dict
            Maps type to color. Will be empty if no types.

    """
    if isinstance(x, (core.NeuronList, core.TreeNeuron)):
        connectors = getattr(x, 'connectors', None)

        if not isinstance(connectors, pd.DataFrame) or connectors.empty:
            unique: List[str] = []
        elif 'type' in connectors:
            unique = connectors.type.unique()
        elif 'label' in connectors:
            unique = connectors.label.unique()
        elif 'relation' in connectors:
            unique = connectors.relation.unique()
        else:
            unique = []
    else:
        unique = list(set(x))

    colors = config.default_connector_colors
    if isinstance(colors, (list, np.ndarray)):
        if len(unique) > len(colors):
            raise ValueError('Must define more default connector colors. See'
                             'navis.set_default_connector_colors')

        return {t: config.default_connector_colors[i] for i, t in enumerate(unique)}
    elif isinstance(colors, dict):
        miss = [l for l in unique if l not in colors]
        if miss:
            raise ValueError(f'Connector labels/types {",".join(miss)} are not'
                             ' defined in default connector colors. '
                             'See navis.set_default_connector_colors')
        return colors
    else:
        raise TypeError('config.default_color must be dict or iterable, '
                        f'not {type(config.default_color)}')

Set alpha channel for given color.

Will add alpha channel if not present.

PARAMETER DESCRIPTION
color
Single RGB or RGBA color or array of colors.

TYPE: (array - like, shape(..., 3) or (..., 4))

alpha
Alpha value to set, in range [0, 1].

TYPE: float

Source code in navis/plotting/colors.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
def set_alpha(color: Union[np.ndarray, list, tuple], alpha: float):
    """Set alpha channel for given color.

    Will add alpha channel if not present.

    Parameters
    ----------
    color : array-like, shape (..., 3) or (..., 4)
            Single RGB or RGBA color or array of colors.
    alpha : float
            Alpha value to set, in range [0, 1].

    """
    if isinstance(color, np.ndarray):
        color = color.copy()
        if color.ndim == 2:
            if color.shape[1] == 3:
                alpha_channel = np.full((color.shape[0], 1), alpha)
                color = np.hstack((color, alpha_channel))
            elif color.shape[1] == 4:
                color[:, 3] = alpha
            else:
                raise ValueError("Color array must have shape (..., 3) or (..., 4).")
        elif color.ndim == 1:
            if color.shape[0] == 3:
                color = np.append(color, alpha)
            elif color.shape[0] == 4:
                color[3] = alpha
            else:
                raise ValueError("Color array must have shape (..., 3) or (..., 4).")
        else:
            raise ValueError("Color array must have shape (..., 3) or (..., 4).")
    elif isinstance(color, list):
        color = color.copy()
        if len(color) == 3:
            color.append(alpha)
        elif len(color) == 4:
            color[3] = alpha
        else:
            raise ValueError("Color list must have length 3 or 4.")
    elif isinstance(color, tuple):
        if len(color) == 3:
            color = list(color) + [alpha]
        elif len(color) == 4:
            color = list(color)
            color[3] = alpha
        else:
            raise ValueError("Color tuple must have length 3 or 4.")
        color = tuple(color)
    else:
        raise TypeError("Color must be a numpy array, list, or tuple.")

    return color