colormap.py 2.32 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1 2
from __future__ import division
from builtins import str
Martin Reinecke's avatar
Martin Reinecke committed
3
from ..plotly_wrapper import PlotlyWrapper
4 5 6 7 8 9 10 11 12 13 14 15 16 17


class Colormap(PlotlyWrapper):
    def __init__(self, name, red, green, blue):
        self.name = name
        self.red = red
        self.green = green
        self.blue = blue

    def validate_map(self):
        def validade(m):
            #TODO: implement validation
            pass

18
    # no discontinuities only
19
    @staticmethod
20
    def from_matplotlib_colormap_internal(name, mpl_cmap):
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
        red = [(c[0], c[2]) for c in mpl_cmap['red']]
        green = [(c[0], c[2]) for c in mpl_cmap['green']]
        blue = [(c[0], c[2]) for c in mpl_cmap['blue']]
        return Colormap(name, red, green, blue)

    def to_plotly(self):
        r, g, b = 0, 0, 0
        converted = list()
        prev_split, prev_r, prev_g, prev_b = 0., 0., 0., 0.

        while prev_split < 1:
            next_split = min(self.red[r][0], self.blue[b][0], self.green[g][0])

            if next_split == self.red[r][0]:
                red_val = self.red[r][1]
                r += 1
            else:
                slope = (self.red[r][1]-prev_r) / (self.red[r][0] - prev_split)
                y = prev_r - slope * prev_split
                red_val = slope * next_split + y

            if next_split == self.green[g][0]:
                green_val = self.green[g][1]
                g += 1
            else:
46 47
                slope = ((self.green[g][1] - prev_g) /
                         (self.green[g][0] - prev_split))
48 49 50 51 52 53 54
                y = prev_g - slope * prev_split
                green_val = slope * next_split + y

            if next_split == self.blue[b][0]:
                blue_val = self.blue[b][1]
                b += 1
            else:
55 56
                slope = ((self.blue[b][1] - prev_b) /
                         (self.blue[b][0] - prev_split))
57 58 59
                y = prev_r - slope * prev_split
                blue_val = slope * next_split + y

60 61 62 63 64
            prev_split = next_split
            prev_r = red_val
            prev_g = green_val
            prev_b = blue_val

65 66 67 68 69 70 71 72 73 74 75 76
            converted.append([next_split,
                              'rgb(' +
                              str(int(red_val*255)) + "," +
                              str(int(green_val*255)) + "," +
                              str(int(blue_val*255)) + ")"])

        return converted