color_setContour.py 5.08 KB
title = "SetContour"
tip = "applies contouring and gamma correction to colorbar"
onein = True

import numpy as np

import guiqwt.colormap as cm
from guidata.qt.QtGui import QMessageBox
from guidata.dataset.datatypes import DataSet
from guidata.dataset.dataitems import (IntItem, StringItem, ChoiceItem, FloatItem, BoolItem)
#from guiqwt.colormap import get_colormap_list, get_cmap, register_extra_colormap
from guiqwt.config import _

from guiqwt.transitional import QwtLinearColorMap, QwtDoubleInterval
FULLRANGE = QwtDoubleInterval(0.0, 1.0)

def nint(x):
    if x > 0: return int(x+0.5)
    else: return int(x-0.5)

def makeMappingArray(N, data, gamma=1.0):
    """Create an *N* -element 1-d lookup table

    *data* represented by a list of x,y0,y1 mapping correspondences.
    Each element in this list represents how a value between 0 and 1
    (inclusive) represented by x is mapped to a corresponding value
    between 0 and 1 (inclusive). The two values of y are to allow
    for discontinuous mapping functions (say as might be found in a
    sawtooth) where y0 represents the value of y for values of x
    <= to that given, and y1 is the value to be used for x > than
    that given). The list must start with x=0, end with x=1, and
    all values of x must be in increasing order. Values between
    the given mapping points are determined by simple linear interpolation.

    Alternatively, data can be a function mapping values between 0 - 1
    to 0 - 1.

    The function returns an array "result" where ``result[x*(N-1)]``
    gives the closest value for values of x between 0 and 1.
    """

    if callable(data):
       xind = np.linspace(0, 1, N)**gamma
       lut = np.clip(np.array(data(xind), dtype=np.float), 0, 1)
       return lut

    try:
       adata = np.array(data)
    except:
       raise TypeError("data must be convertable to an array")
    shape = adata.shape
    if len(shape) != 2 and shape[1] != 3:
       raise ValueError("data must be nx3 format")

    x  = adata[:,0]
    y0 = adata[:,1]
    y1 = adata[:,2]

    if x[0] != 0. or x[-1] != 1.0:
       raise ValueError(
           "data mapping points must start with x=0. and end with x=1")
    if np.sometrue(np.sort(x)-x):
       raise ValueError(
           "data mapping points must have x in increasing order")
    # begin generation of lookup table
    x = x * (N-1)
    xind = (N - 1) * np.linspace(0, 1, N)**gamma
    ind = np.searchsorted(x, xind)

    Lut = ( ((xind - x[ind-1]) / (x[ind] - x[ind-1]))
                * (y0[ind] - y1[ind-1]) + y1[ind-1])
    lut = []
    scale = 1.0/len(Lut)
    di = 1.0-1./256.0
    for i in range(len(Lut)):
        n = max(0.0, min(1.0, float(i)*scale))
        lut.append((n, Lut[i], Lut[i]))
        n = max(0.0, min(1.0, float(i+di)*scale))
        lut.append((n, Lut[i], Lut[i]))
    return lut


class NOD3_App:

    def __init__(self, parent):
        self.parent = parent
        self.parent.activateWindow()

    def Error(self, msg):
        QMessageBox.critical(self.parent.parent(), title,
                              _(u"Error:")+"\n%s" % str(msg))

    def compute_app(self, **args):
        class FuncParam(DataSet):
            steps = IntItem('Steps', default=10, min=5, max=100)
            gamma = FloatItem('Gamma', default=1.0, min=0.01, max=10.0)
        name = title.replace(" ", "")
        if args == {}:
           param = FuncParam(_(title), "Set colour steps in colormap:")
        else:
           param = self.parent.ScriptParameter(name, args)

        # if no parameter needed set param to None. activate next line
        #param = None
        self.parent.compute_11(name, lambda m, p: self.function(m, p), param, onein) 

    def get_rgb(self, a, f=255.0):
        y = hex(a)[2:-1]
        x = [ord(c) for c in y.decode('hex')]
        r = (float(x[1])/f)
        g = (float(x[2])/f)
        b = (float(x[3])/f)
        return r, g, b

    def setup_color_map(self, nsteps, gamma=1, f=255.0):
        cmap_name = self.parent.cmap
        table = cm.get_cmap(cmap_name)
        cmap = table.colorTable(FULLRANGE)
        #item = self.parent.items[self.parent.row]
        #cmap = item.get_color_map().colorTable(FULLRANGE)
        lut = {'red': [], 'green': [], 'blue': []}
        for i in range(len(cmap)):
            j = int(f*((float(i)/f)))
            r, g, b = self.get_rgb(cmap[j])
            lut['red'].append((float(i)/f, r, r))
            lut['green'].append((float(i)/f, g, g))
            lut['blue'].append((float(i)/f, b, b))
        lut['red'] = makeMappingArray(nsteps, lut['red'], gamma=gamma)
        lut['green'] = makeMappingArray(nsteps, lut['green'], gamma=gamma)
        lut['blue'] = makeMappingArray(nsteps, lut['blue'], gamma=gamma)
        return lut

    def function(self, m, p):
        cmdata = self.setup_color_map(p.steps, 1.0/p.gamma)
        my_cmap = QwtLinearColorMap()
        cname = self.parent.cmap + "_steps"
        cm._setup_colormap(my_cmap, cmdata)
        cm.register_extra_colormap(cname, my_cmap)
        item = self.parent.items[self.parent.row]
        item.set_color_map(cname)
        plot = item.plot()
        if plot:
           plot.replot()
        return [], p