Example #1
0
    def _updateContourLevelsAndColorsForBoxfill(self):
        """Set contour information for a standard boxfill."""
        # Compute levels
        nlev = (self._gm.color_2 - self._gm.color_1) + 1
        if numpy.allclose(self._gm.level_1, 1.e20) or \
           numpy.allclose(self._gm.level_2, 1.e20):
            self._contourLevels = vcs.mkscale(self._scalarRange[0],
                                              self._scalarRange[1])
            if len(self._contourLevels) == 1:  # constant value ?
                self._contourLevels = [
                    self._contourLevels[0], self._contourLevels[0] + .00001
                ]
            self._contourLabels = vcs.mklabels(self._contourLevels)
            dx = (self._contourLevels[-1] - self._contourLevels[0]) / nlev
            self._contourLevels = numpy.arange(self._contourLevels[0],
                                               self._contourLevels[-1] + dx,
                                               dx)
        else:
            if self._gm.boxfill_type == "log10":
                levslbls = vcs.mkscale(numpy.ma.log10(self._gm.level_1),
                                       numpy.ma.log10(self._gm.level_2))
                self._contourLevels = \
                      vcs.mkevenlevels(numpy.ma.log10(self._gm.level_1),
                                       numpy.ma.log10(self._gm.level_2),
                                       nlev=nlev)
            else:
                levslbls = vcs.mkscale(self._gm.level_1, self._gm.level_2)
                self._contourLevels = vcs.mkevenlevels(self._gm.level_1,
                                                       self._gm.level_2,
                                                       nlev=nlev)
            if len(self._contourLevels) > 25:
                ## Too many colors/levels need to prettyfy this for legend
                self._contourLabels = vcs.mklabels(levslbls)
                ## Make sure extremes are in
                legd2 = vcs.mklabels(
                    [self._contourLevels[0], self._contourLevels[-1]])
                self._contourLabels.update(legd2)
            else:
                self._contourLabels = vcs.mklabels(self._contourLevels)
            if self._gm.boxfill_type == "log10":
                logLabels = {}
                for key in self._contourLabels.keys():
                    value = self._contourLabels[key]
                    newKey = float(numpy.ma.log10(value))
                    logLabels[newKey] = value
                self._contourLabels = logLabels

        # Use consecutive colors:
        self._contourColors = range(self._gm.color_1, self._gm.color_2 + 1)
Example #2
0
    def _updateContourLevelsAndColorsForBoxfill(self):
        """Set contour information for a standard boxfill."""
        # Compute levels
        nlev = (self._gm.color_2 - self._gm.color_1) + 1
        if numpy.allclose(self._gm.level_1, 1.e20) or \
           numpy.allclose(self._gm.level_2, 1.e20):
            self._contourLevels = vcs.mkscale(self._scalarRange[0],
                                              self._scalarRange[1])
            if len(self._contourLevels) == 1: # constant value ?
                self._contourLevels = [self._contourLevels[0],
                                       self._contourLevels[0] + .00001]
            self._contourLabels = vcs.mklabels(self._contourLevels)
            dx = (self._contourLevels[-1] - self._contourLevels[0]) / nlev
            self._contourLevels = numpy.arange(self._contourLevels[0],
                                               self._contourLevels[-1] + dx, dx)
        else:
            if self._gm.boxfill_type == "log10":
                levslbls = vcs.mkscale(numpy.ma.log10(self._gm.level_1),
                                       numpy.ma.log10(self._gm.level_2))
                self._contourLevels = \
                      vcs.mkevenlevels(numpy.ma.log10(self._gm.level_1),
                                       numpy.ma.log10(self._gm.level_2),
                                       nlev=nlev)
            else:
                levslbls = vcs.mkscale(self._gm.level_1, self._gm.level_2)
                self._contourLevels = vcs.mkevenlevels(self._gm.level_1,
                                                       self._gm.level_2,
                                                       nlev=nlev)
            if len(self._contourLevels) > 25:
                ## Too many colors/levels need to prettyfy this for legend
                self._contourLabels = vcs.mklabels(levslbls)
                ## Make sure extremes are in
                legd2 = vcs.mklabels([self._contourLevels[0],
                                      self._contourLevels[-1]])
                self._contourLabels.update(legd2)
            else:
                self._contourLabels = vcs.mklabels(self._contourLevels)
            if self._gm.boxfill_type == "log10":
                logLabels = {}
                for key in self._contourLabels.keys():
                    value = self._contourLabels[key]
                    newKey = float(numpy.ma.log10(value))
                    logLabels[newKey] = value
                self._contourLabels = logLabels

        # Use consecutive colors:
        self._contourColors = range(self._gm.color_1, self._gm.color_2 + 1)
t_asd.max.textorientation = to1_max
t_asd.legend.textorientation = to1_legend

to1_xname.height = 20
to1_yname.height = 20
to1_xlabel1.height = 20
to1_ylabel1.height = 20
to1_mean.height = 17
to1_min.height = 17
to1_max.height = 17
to1_legend.height = 17

# Set Isofill Method Attributes for qr_z
g_method_isofl = canvas1.getisofill('ASD')
g_method_isofl.projection = 'linear'
levs = vcs.mkevenlevels(0, 0.016, nlev=8)
g_method_isofl.levels = levs
g_method_isofl.fillareacolors = vcs.getcolors(levs)
g_method_isofl.yticlabels1 = {
    0: '0',
    5000: '5',
    10000: '10',
    15000: '15',
    20000: '20'
}
g_method_isofl.yticlabels2 = {0: '', 5000: '', 10000: '', 15000: '', 20000: ''}
g_method_isofl.xticlabels1 = {
    2000: '0',
    22000: '20',
    42000: '40',
    62000: '60',
Example #4
0
    def plotIsos(self, template=None, bg=0):
        if template is None:
            template = 'thdiags_template'
        elif type(template) != type(''):
            template = template.name
        try:
            isotemplate = self.x.createtemplate(template)
        except:
            isotemplate = self.x.gettemplate(template)

        att = dir(isotemplate)
        for a in att:
            try:
                b = getattr(isotemplate, a)
                setattr(b, 'priority', 0)
            except:
                pass

        isotemplate.data.priority = 1
        isotemplate.box1.priority = 1
        isotemplate.box1.x1 = isotemplate.data.x1
        isotemplate.box1.x2 = isotemplate.data.x2
        isotemplate.box1.y1 = isotemplate.data.y1
        isotemplate.box1.y2 = isotemplate.data.y2

        dX = self.xmax - self.xmin
        dY = self.ymax - self.ymin
        X = numpy.ma.arange(self.detail, dtype=MV2.float)
        X = X * dX / (self.detail - 1) + self.xmin
        Xaxis = cdms2.createAxis(X)
        X = numpy.ma.resize(X, (self.detail, self.detail))
        Y = numpy.ma.arange(self.detail, dtype=MV2.float)
        Y = Y * dY / (self.detail - 1) + self.ymin
        Yaxis = cdms2.createAxis(Y)
        Y = numpy.ma.resize(Y, (self.detail, self.detail))
        Y = numpy.ma.transpose(Y)

        # Computes T,P on this grid
        T, P = self.XY2TP(X, Y)
        T = MV2.array(T)

        # Potential Temperature
        Tp = T / numpy.ma.power(P / 100000., self.k)

        ws = Ws(T, P)
        # Seems like we need not ws after 600mb
        ws = numpy.ma.masked_where(
            numpy.ma.less(P, self.Pmaxmixingratio * 100.), ws)

        T = T - 273.16
        Tmin, Tmax = vcs.minmax(T)

        Tvalues = self.isotherms.level
        if Tvalues == [[0.0, 1.0000000200408773e+20]]:
            Tvalues = vcs.mkscale(Tmin, Tmax)
            ## Now sets the isothermsfilled
            Tvalues2 = []
            for i in range(len(Tvalues) / 2 - 1):
                t1, t2 = Tvalues[2 * i], Tvalues[2 * i + 1]
                if isinstance(t1, (list, tuple)):
                    t1, t2 = t1[0], t2[0]
                Tvalues2.append([t1, t2])
        else:
            Tvalues2 = self.isothermsfilled.levels
        self.setIso(self.isotherms, Tvalues)
        ##         self.setIso(self.isothermsfilled,Tvalues2)

        P = P / 100.
        Pvalues = vcs.mkscale(self.datawc_y2, self.datawc_y1)
        self.setIso(self.isobars, Pvalues)

        Tp = Tp - 273.16
        Tpvalues = self.dryadiabats.level
        if Tpvalues == [[0.0, 1.0000000200408773e+20]]:
            min, max = vcs.minmax(Tp)
            Tpvalues = vcs.mkscale(min, max)
        self.setIso(self.dryadiabats, Tpvalues)

        ## Pseudoadiabats
        Thevalues = self.pseudoadiabats.level
        if Thevalues == [[0.0, 1.0000000200408773e+20]]:
            Thevalues = vcs.mkevenlevels(-40, 40, 40)
        self.setIso(self.pseudoadiabats, Thevalues)

        ## Mixing Ratio
        ws = ws * 1000.
        wsvalues = self.mixingratio.level
        if wsvalues == [[0.0, 1.0000000200408773e+20]]:
            min, max = vcs.minmax(ws)
            wsvalues = vcs.mkscale(min, max)
        self.setIso(self.mixingratio, wsvalues)

        # Figures out where to plot the P labels
        dicP = {}
        dicPl = vcs.mklabels(Pvalues)
        for p in Pvalues:
            X, Y = self.TP2XY(self.datawc_x1 + 273.15, p * 100)
            if not numpy.ma.isMA(X):
                dicP[Y] = dicPl[p]
        try:
            ttp = self.x.createtexttable('Plabels')
        except:
            ttp = self.x.gettexttable('Plabels')
        ttp.color = self.isobars.linecolors[0]
        isotemplate.ylabel1.texttable = ttp
        dicT = {}
        Tvalues = list(numpy.ma.array(Tvalues).filled().ravel())
        dicTl = vcs.mklabels(Tvalues)
        for t in Tvalues:
            X, Y = self.TP2XY(t + 273.15, self.datawc_y1 * 100)
            dicT[X] = dicTl[t]
        try:
            ttp = self.x.createtexttable('Tlabels')
        except:
            ttp = self.x.gettexttable('Tlabels')
        ttp.color = self.isotherms.linecolors[0]
        isotemplate.xlabel1.texttable = ttp
        isotemplate.ylabel1.priority = 1
        isotemplate.xlabel1.priority = 1
        isotemplate.data.x1 = isotemplate.data.x1
        isotemplate.data.x2 = isotemplate.data.x2
        isotemplate.data.y1 = isotemplate.data.y1
        isotemplate.data.y2 = isotemplate.data.y2
        self.isotherms.yticlabels1 = dicP
        self.isotherms.xticlabels1 = dicT
        self.isobars.yticlabels1 = {}
        self.isobars.xticlabels1 = {}
        self.dryadiabats.yticlabels1 = {}
        self.dryadiabats.xticlabels1 = {}
        self.pseudoadiabats.yticlabels1 = {}
        self.pseudoadiabats.xticlabels1 = {}
        self.mixingratio.yticlabels1 = {}
        self.mixingratio.xticlabels1 = {}
        self.isothermsfilled.datawc_x1 = self.isothermsfilled.datawc_x1
        self.isothermsfilled.datawc_x2 = self.isothermsfilled.datawc_x2
        self.isothermsfilled.datawc_y1 = self.isothermsfilled.datawc_y1
        self.isothermsfilled.datawc_x2 = self.isothermsfilled.datawc_y2
        # Puts the dims on it
        T.id = 'T'
        T.setAxis(0, Yaxis)
        T.setAxis(1, Xaxis)
        P = MV2.array(P)
        P.id = 'P'
        P.setAxis(0, Yaxis)
        P.setAxis(1, Xaxis)
        Tp = MV2.array(Tp)
        Tp.setAxis(0, Yaxis)
        Tp.setAxis(1, Xaxis)
        ws = MV2.array(ws)
        ws.setAxis(0, Yaxis)
        ws.setAxis(1, Xaxis)

        # plot if self.drawisothermsfilled:
        if self.drawisothermsfilled:
            self.displays.append(
                self.x.plot(T, isotemplate, self.isothermsfilled, bg=bg))
        if self.drawisotherms:
            self.displays.append(
                self.x.plot(T, isotemplate, self.isotherms, bg=bg))
        if self.drawisobars:
            self.displays.append(
                self.x.plot(P, isotemplate, self.isobars, bg=bg))
        if self.drawdryadiabats:
            self.displays.append(
                self.x.plot(Tp, isotemplate, self.dryadiabats, bg=bg))
        if self.drawpseudoadiabats:
            self.plot_pseudo(isotemplate, bg=bg)
        if self.drawmixingratio:
            self.displays.append(
                self.x.plot(ws, isotemplate, self.mixingratio, bg=bg))
        return
Example #5
0
import sys,cdms2,vcs
x=vcs.init()
f=cdms2.open(vcs.prefix+"/sample_data/clt.nc")
s=f("clt",time=slice(0,23))
#f=cdms2.open(sys.prefix+"/sample_data/sampleCurveGrid4.nc")
#f=cdms2.open(sys.prefix+"/sample_data/sampleGenGrid3.nc")
#s=f("sample")
gm = x.createisofill()
gm = x.createboxfill()
#gm=x.createisoline()
levs = vcs.mkevenlevels(20,80)
gm.levels= levs
gm.fillareacolors = vcs.getcolors(levs)
#gm = x.createmeshfill()
d = x.plot(s,gm)
#d = x.plot(s.filled())
raw_input("Press enter")
x.animate.create(thread_it=False,min=20,max=80)
x.animate.fps(5000)
x.animate.run()
raw_input("Press enter to end")
x.animate.stop()

Example #6
0
t_asd.max.textorientation = to1_max
t_asd.legend.textorientation = to1_legend

to1_xname.height = 20
to1_yname.height = 20
to1_xlabel1.height = 20
to1_ylabel1.height = 20
to1_mean.height = 17
to1_min.height = 17
to1_max.height = 17
to1_legend.height = 17

# Set Isofill Method Attributes for qc_z
g_method_isofl = canvas1.getisofill('ASD')
g_method_isofl.projection = 'linear'
levs = vcs.mkevenlevels(0, 0.006, nlev=6)
g_method_isofl.levels = levs
g_method_isofl.fillareacolors = vcs.getcolors(levs)
g_method_isofl.yticlabels1 = {
    0: '0',
    5000: '5',
    10000: '10',
    15000: '15',
    20000: '20'
}
g_method_isofl.yticlabels2 = {0: '', 5000: '', 10000: '', 15000: '', 20000: ''}
g_method_isofl.xticlabels1 = {
    2000: '0',
    22000: '20',
    42000: '40',
    62000: '60',
Example #7
0
    def plotIsos(self, template=None, bg=0):
        if template is None:
            template = "thdiags_template"
        elif not isinstance(template, type("")):
            template = template.name
        try:
            isotemplate = self.x.createtemplate(template)
        except:
            isotemplate = self.x.gettemplate(template)

        att = dir(isotemplate)
        for a in att:
            try:
                b = getattr(isotemplate, a)
                setattr(b, "priority", 0)
            except:
                pass

        isotemplate.data.priority = 1
        isotemplate.box1.priority = 1
        isotemplate.box1.x1 = isotemplate.data.x1
        isotemplate.box1.x2 = isotemplate.data.x2
        isotemplate.box1.y1 = isotemplate.data.y1
        isotemplate.box1.y2 = isotemplate.data.y2

        dX = self.xmax - self.xmin
        dY = self.ymax - self.ymin
        X = numpy.ma.arange(self.detail, dtype=MV2.float)
        X = X * dX / (self.detail - 1) + self.xmin
        Xaxis = cdms2.createAxis(X)
        X = numpy.ma.resize(X, (self.detail, self.detail))
        Y = numpy.ma.arange(self.detail, dtype=MV2.float)
        Y = Y * dY / (self.detail - 1) + self.ymin
        Yaxis = cdms2.createAxis(Y)
        Y = numpy.ma.resize(Y, (self.detail, self.detail))
        Y = numpy.ma.transpose(Y)

        # Computes T,P on this grid
        T, P = self.XY2TP(X, Y)
        T = MV2.array(T)

        # Potential Temperature
        Tp = T / numpy.ma.power(P / 100000.0, self.k)

        ws = Ws(T, P)
        # Seems like we need not ws after 600mb
        ws = numpy.ma.masked_where(numpy.ma.less(P, self.Pmaxmixingratio * 100.0), ws)

        T = T - 273.16
        Tmin, Tmax = vcs.minmax(T)

        Tvalues = self.isotherms.level
        if Tvalues == [[0.0, 1.0000000200408773e20]]:
            Tvalues = vcs.mkscale(Tmin, Tmax)
            # Now sets the isothermsfilled
            Tvalues2 = []
            for i in range(len(Tvalues) / 2 - 1):
                t1, t2 = Tvalues[2 * i], Tvalues[2 * i + 1]
                if isinstance(t1, (list, tuple)):
                    t1, t2 = t1[0], t2[0]
                Tvalues2.append([t1, t2])
        else:
            Tvalues2 = self.isothermsfilled.levels
        self.setIso(self.isotherms, Tvalues)
        # self.setIso(self.isothermsfilled,Tvalues2)

        P = P / 100.0
        Pvalues = vcs.mkscale(self.datawc_y2, self.datawc_y1)
        self.setIso(self.isobars, Pvalues)

        Tp = Tp - 273.16
        Tpvalues = self.dryadiabats.level
        if Tpvalues == [[0.0, 1.0000000200408773e20]]:
            min, max = vcs.minmax(Tp)
            Tpvalues = vcs.mkscale(min, max)
        self.setIso(self.dryadiabats, Tpvalues)

        # Pseudoadiabats
        Thevalues = self.pseudoadiabats.level
        if Thevalues == [[0.0, 1.0000000200408773e20]]:
            Thevalues = vcs.mkevenlevels(-40, 40, 40)
        self.setIso(self.pseudoadiabats, Thevalues)

        # Mixing Ratio
        ws = ws * 1000.0
        wsvalues = self.mixingratio.level
        if wsvalues == [[0.0, 1.0000000200408773e20]]:
            min, max = vcs.minmax(ws)
            wsvalues = vcs.mkscale(min, max)
        self.setIso(self.mixingratio, wsvalues)

        # Figures out where to plot the P labels
        dicP = {}
        dicPl = vcs.mklabels(Pvalues)
        for p in Pvalues:
            X, Y = self.TP2XY(self.datawc_x1 + 273.15, p * 100)
            if not numpy.ma.isMA(X):
                dicP[Y] = dicPl[p]
        try:
            ttp = self.x.createtexttable("Plabels")
        except:
            ttp = self.x.gettexttable("Plabels")
        ttp.color = self.isobars.linecolors[0]
        isotemplate.ylabel1.texttable = ttp
        dicT = {}
        Tvalues = list(numpy.ma.array(Tvalues).filled().ravel())
        dicTl = vcs.mklabels(Tvalues)
        for t in Tvalues:
            X, Y = self.TP2XY(t + 273.15, self.datawc_y1 * 100)
            dicT[X] = dicTl[t]
        try:
            ttp = self.x.createtexttable("Tlabels")
        except:
            ttp = self.x.gettexttable("Tlabels")
        ttp.color = self.isotherms.linecolors[0]
        isotemplate.xlabel1.texttable = ttp
        isotemplate.ylabel1.priority = 1
        isotemplate.xlabel1.priority = 1
        isotemplate.data.x1 = isotemplate.data.x1
        isotemplate.data.x2 = isotemplate.data.x2
        isotemplate.data.y1 = isotemplate.data.y1
        isotemplate.data.y2 = isotemplate.data.y2
        self.isotherms.yticlabels1 = dicP
        self.isotherms.xticlabels1 = dicT
        self.isobars.yticlabels1 = {}
        self.isobars.xticlabels1 = {}
        self.dryadiabats.yticlabels1 = {}
        self.dryadiabats.xticlabels1 = {}
        self.pseudoadiabats.yticlabels1 = {}
        self.pseudoadiabats.xticlabels1 = {}
        self.mixingratio.yticlabels1 = {}
        self.mixingratio.xticlabels1 = {}
        self.isothermsfilled.datawc_x1 = self.isothermsfilled.datawc_x1
        self.isothermsfilled.datawc_x2 = self.isothermsfilled.datawc_x2
        self.isothermsfilled.datawc_y1 = self.isothermsfilled.datawc_y1
        self.isothermsfilled.datawc_x2 = self.isothermsfilled.datawc_y2
        # Puts the dims on it
        T.id = "T"
        T.setAxis(0, Yaxis)
        T.setAxis(1, Xaxis)
        P = MV2.array(P)
        P.id = "P"
        P.setAxis(0, Yaxis)
        P.setAxis(1, Xaxis)
        Tp = MV2.array(Tp)
        Tp.setAxis(0, Yaxis)
        Tp.setAxis(1, Xaxis)
        ws = MV2.array(ws)
        ws.setAxis(0, Yaxis)
        ws.setAxis(1, Xaxis)

        # plot if self.drawisothermsfilled:
        if self.drawisothermsfilled:
            self.displays.append(self.x.plot(T, isotemplate, self.isothermsfilled, bg=bg))
        if self.drawisotherms:
            self.displays.append(self.x.plot(T, isotemplate, self.isotherms, bg=bg))
        if self.drawisobars:
            self.displays.append(self.x.plot(P, isotemplate, self.isobars, bg=bg))
        if self.drawdryadiabats:
            self.displays.append(self.x.plot(Tp, isotemplate, self.dryadiabats, bg=bg))
        if self.drawpseudoadiabats:
            self.plot_pseudo(isotemplate, bg=bg)
        if self.drawmixingratio:
            self.displays.append(self.x.plot(ws, isotemplate, self.mixingratio, bg=bg))
        return
Example #8
0
import sys
import os
import support

f = cdms.open(
    os.path.join(cdms.__path__[0], '..', '..', '..', '..', 'sample_data',
                 'meshfill.nc'))
M = f('Mesh')
s = f('Data')

x = vcs.init()
x.scriptrun(
    os.path.join(cdms.__path__[0], '..', '..', '..', '..', 'bin', 'ASD.scr'))
m = x.getmeshfill('ASD')
m.wrap = [0, 360]
m.mesh = 'y'
#mn,mx=vcs.minmax(s)
levs = vcs.mkscale(-10, 30)
#print levs
levs = vcs.mkevenlevels(levs[0], levs[-1], 256)
levs2 = levs[::25]
if levs2[-1] != levs[-1]: levs2.append(levs[-1])
lbls = vcs.mklabels(levs2)
#print levs
m.legend = lbls
m.levels = levs[::-1]
m.fillareacolors = vcs.getcolors(levs)
## m.list()
x.plot(s, M, m, bg=support.bg)
support.check_plot(x)
Example #9
0
dsw.Write()

cot = vtk.vtkBandedPolyDataContourFilter()
#cot = vtk.vtkContourFilter()
cot.SetInputData(sFilter.GetOutput())
mn,mx = s.min(),s.max()
Nlevs = 10
#cot.GenerateValues(Nlevs+1,mn,mx)
cot.SetNumberOfContours(Nlevs+1)

#At that point let's try to tweak color table
lut = vtk.vtkLookupTable()
#lut.SetNumberOfColors(Nlevs)
lut.SetNumberOfTableValues(Nlevs)
#lut.SetTableRange(0,Nlevs)
levs=vcs.mkevenlevels(mn,mx,Nlevs)
cols=vcs.getcolors(levs)
cmap=vcs.colormap.Cp("rainbow","defaultvcs")

for i in range(Nlevs):
  cot.SetValue(i,levs[i])
  r,g,b = cmap.index[cols[i]]
  lut.SetTableValue(i,r/100.,g/100.,b/100.)
  print i,levs[i],r,g,b
cot.SetValue(Nlevs,levs[-1])

#cot.SetScalarModeToValue()
cot.Update()
# the next two are the same thing, see setter/getter macro definitions in vtkSetGet.h
#cot.SetComputeScalars(1)
#cot.ComputeScalarsOn()
Example #10
0
s = f('Data')

x = vcs.init()
x.scriptrun(
    os.path.join(
        cdms.__path__[0],
        '..',
        '..',
        '..',
        '..',
        'bin',
        'ASD.scr'))
m = x.getmeshfill('ASD')
m.wrap = [0, 360]
m.mesh = 'y'
# mn,mx=vcs.minmax(s)
levs = vcs.mkscale(-10, 30)
# print levs
levs = vcs.mkevenlevels(levs[0], levs[-1], 256)
levs2 = levs[::25]
if levs2[-1] != levs[-1]:
    levs2.append(levs[-1])
lbls = vcs.mklabels(levs2)
# print levs
m.legend = lbls
m.levels = levs[::-1]
m.fillareacolors = vcs.getcolors(levs)
# m.list()
x.plot(s, M, m, bg=support.bg)
support.check_plot(x)
Example #11
0
  def plot2D(self,data1,data2,tmpl,gm):
    #Preserve time and z axis for plotting these inof in rendertemplate
    t = data1.getTime()
    if data1.ndim>2:
        z = data1.getAxis(-3)
    else:
        z = None
    data1 = self.trimData2D(data1) # Ok get3 only the last 2 dims
    if gm.g_name!="Gfm":
      data2 = self.trimData2D(data2)
    ug,xm,xM,ym,yM,continents,wrap,geo,cellData = vcs2vtk.genGrid(data1,data2,gm,deep=False)
    #Now applies the actual data on each cell
    if isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="log10":
        data1=numpy.ma.log10(data1)
    data = vcs2vtk.numpy_to_vtk_wrapper(data1.filled(0.).flat, deep=False)
    if cellData:
        ug.GetCellData().SetScalars(data)
    else:
        ug.GetPointData().SetScalars(data)

    try:
      cmap = vcs.elements["colormap"][cmap]
    except:
      cmap = vcs.elements["colormap"][self.canvas.getcolormapname()]

    color = getattr(gm,"missing",None)
    if color is not None:
        color = cmap.index[color]
    missingMapper = vcs2vtk.putMaskOnVTKGrid(data1,ug,color,cellData,deep=False)
    lut = vtk.vtkLookupTable()
    mn,mx=vcs.minmax(data1)
    #Ok now we have grid and data let's use the mapper
    mapper = vtk.vtkPolyDataMapper()
    legend = None
    if isinstance(gm,(meshfill.Gfm,boxfill.Gfb)):
      geoFilter = vtk.vtkDataSetSurfaceFilter()
      if cellData:
          p2c = vtk.vtkPointDataToCellData()
          p2c.SetInputData(ug)
          geoFilter.SetInputConnection(p2c.GetOutputPort())
      else:
        geoFilter.SetInputData(ug)
      geoFilter.Update()

    if isinstance(gm,(isofill.Gfi,isoline.Gi,meshfill.Gfm)) or \
        (isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="custom"):

      #Now this filter seems to create the good polydata
      sFilter = vtk.vtkDataSetSurfaceFilter()
      if cellData:
          # Sets data to point instead of just cells
          c2p = vtk.vtkCellDataToPointData()
          c2p.SetInputData(ug)
          c2p.Update()
          if self.debug:
            vcs2vtk.dump2VTK(c2p)
          #For contouring duplicate points seem to confuse it
          if ug.IsA("vtkUntructuredGrid"):
              cln = vtk.vtkCleanUnstructuredGrid()
              cln.SetInputConnection(c2p.GetOutputPort())
              if self.debug:
                vcs2vtk.dump2VTK(cln)
              sFilter.SetInputConnection(cln.GetOutputPort())
          else:
              sFilter.SetInputConnection(c2p.GetOutputPort())
      else:
          sFilter.SetInputData(ug)
      sFilter.Update()
      if self.debug:
        vcs2vtk.dump2VTK(sFilter)
      if isinstance(gm,isoline.Gi):
        cot = vtk.vtkContourFilter()
        if cellData:
          cot.SetInputData(sFilter.GetOutput())
        else:
          cot.SetInputData(ug)


      levs = gm.levels
      if (isinstance(gm,isoline.Gi) and numpy.allclose( levs[0],[0.,1.e20])) or numpy.allclose(levs,1.e20):
        levs = vcs.mkscale(mn,mx)
        if len(levs)==1: # constant value ?
          levs = [levs[0],levs[0]+.00001]
        Ncolors = len(levs)
        if isinstance(gm,(isofill.Gfi,meshfill.Gfm)):
          levs2 = vcs.mkscale(mn,mx)
          if len(levs2)==1: # constant value ?
            levs2 = [levs2[0],levs2[0]+.00001]
          levs=[]
          for i in range(len(levs2)-1):
            levs.append([levs2[i],levs2[i+1]])
      else:
        if isinstance(gm.levels[0],(list,tuple)):
          if isinstance(gm,isoline.Gi):
            levs = [x[0] for x in gm.levels]
          else:
            levs = gm.levels
        else:
          levs = []
          levs2=gm.levels
          if numpy.allclose(levs2[0],1.e20):
            levs2[0]=-1.e20
          for i in range(len(levs2)-1):
            levs.append([levs2[i],levs2[i+1]])
          if isinstance(gm,isoline.Gi):
            levs = levs2
      Nlevs=len(levs)
      Ncolors = Nlevs
      ## Figure out colors
      if isinstance(gm,boxfill.Gfb):
        cols = gm.fillareacolors
        if cols is None:
          cols = vcs.getcolors(levs2,split=0)
      elif isinstance(gm,(isofill.Gfi,meshfill.Gfm)):
        cols = gm.fillareacolors
        if cols==[1,]:
          cols = vcs.getcolors(levs2,split=0)
          if isinstance(cols,(int,float)):
              cols=[cols,]
      elif isinstance(gm,isoline.Gi):
        cols = gm.linecolors

      if isinstance(gm,isoline.Gi):
        cot.SetNumberOfContours(Nlevs)
        if levs[0]==1.e20:
          levs[0]=-1.e20
        for i in range(Nlevs):
          cot.SetValue(i,levs[i])
        cot.SetValue(Nlevs,levs[-1])
        cot.Update()
        mapper.SetInputConnection(cot.GetOutputPort())
        mappers = []
      else:
        mappers = []
        LEVS = []
        INDX = []
        COLS = []
        indices = gm.fillareaindices
        if indices is None:
            indices=[1,]
        while len(indices)<len(cols):
            indices.append(indices[-1])
        for i,l in enumerate(levs):
            if i==0:
                C = [cols[i],]
                if numpy.allclose(levs[0][0],-1.e20):
                    ## ok it's an extension arrow
                    L=[mn-1.,levs[0][1]]
                else:
                    L = list(levs[i])
                I = [indices[i],]
            else:
                if l[0] == L[-1] and I[-1]==indices[i]:
                    # Ok same type lets keep going
                    if numpy.allclose(l[1],1.e20):
                        L.append(mx+1.)
                    else:
                        L.append(l[1])
                    C.append(cols[i])
                else: # ok we need new contouring
                    LEVS.append(L)
                    COLS.append(C)
                    INDX.append(I)
                    C = [cols[i],]
                    L = levs[i]
                    I = [indices[i],]
        LEVS.append(L)
        COLS.append(C)
        INDX.append(I)


        for i,l in enumerate(LEVS):
          # Ok here we are trying to group together levels can be, a join will happen if:
          # next set of levels contnues where one left off AND pattern is identical

          if isinstance(gm,isofill.Gfi):
              mapper = vtk.vtkPolyDataMapper()
              lut = vtk.vtkLookupTable()
              cot = vtk.vtkBandedPolyDataContourFilter()
              cot.ClippingOn()
              cot.SetInputData(sFilter.GetOutput())
              cot.SetNumberOfContours(len(l))
              cot.SetClipTolerance(0.)
              for j,v in enumerate(l):
                cot.SetValue(j,v)
              #cot.SetScalarModeToIndex()
              cot.Update()
              mapper.SetInputConnection(cot.GetOutputPort())
              lut.SetNumberOfTableValues(len(COLS[i]))
              for j,color in enumerate(COLS[i]):
                  r,g,b = cmap.index[color]
                  lut.SetTableValue(j,r/100.,g/100.,b/100.)
                  #print l[j],vcs.colors.rgb2str(r*2.55,g*2.55,b*2.55),l[j+1]
              mapper.SetLookupTable(lut)
              mapper.SetScalarRange(0,len(l)-1)
              mapper.SetScalarModeToUseCellData()
          else:
              for j,color in enumerate(COLS[i]):
                  mapper = vtk.vtkPolyDataMapper()
                  lut = vtk.vtkLookupTable()
                  th = vtk.vtkThreshold()
                  th.ThresholdBetween(l[j],l[j+1])
                  th.SetInputConnection(geoFilter.GetOutputPort())
                  geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                  geoFilter2.SetInputConnection(th.GetOutputPort())
                  mapper.SetInputConnection(geoFilter2.GetOutputPort())
                  lut.SetNumberOfTableValues(1)
                  r,g,b = cmap.index[color]
                  lut.SetTableValue(0,r/100.,g/100.,b/100.)
                  mapper.SetLookupTable(lut)
                  mapper.SetScalarRange(l[j],l[j+1])
                  mappers.append([mapper,])

          #png = vtk.vtkPNGReader()
          #png.SetFileName("/git/uvcdat/Packages/vcs/Share/uvcdat_texture.png")
          #T=vtk.vtkTexture()
          #T.SetInputConnection(png.GetOutputPort())
          if isinstance(gm,isofill.Gfi):
              mappers.append([mapper,])

    else: #Boxfill (non custom)/Meshfill
      if isinstance(gm,boxfill.Gfb):
        if numpy.allclose(gm.level_1,1.e20) or numpy.allclose(gm.level_2,1.e20):
          levs = vcs.mkscale(mn,mx)
          if len(levs)==1: # constant value ?
              levs = [levs[0],levs[0]+.00001]
          legend = vcs.mklabels(levs)
          dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1)
          levs = numpy.arange(levs[0],levs[-1]+dx,dx)
        else:
          if gm.boxfill_type=="log10":
              levslbls = vcs.mkscale(numpy.ma.log10(gm.level_1),numpy.ma.log10(gm.level_2))
              levs = vcs.mkevenlevels(numpy.ma.log10(gm.level_1),
                      numpy.ma.log10(gm.level_2),
                      nlev=(gm.color_2-gm.color_1)+1)
          else:
              levslbls = vcs.mkscale(gm.level_1,gm.level_2)
              levs = vcs.mkevenlevels(gm.level_1,gm.level_2,nlev=(gm.color_2-gm.color_1)+1)
          if len(levs)>25:
              ## Too many colors/levels need to prettyfy this for legend
              legend = vcs.mklabels(levslbls)
              ## Make sure extremes are in
              legd2=vcs.mklabels([levs[0],levs[-1]])
              legend.update(legd2)
          else:
              legend = vcs.mklabels(levs)
          if gm.boxfill_type=="log10":
              for k in legend.keys():
                  legend[float(numpy.ma.log10(legend[k]))] = legend[k]
                  del(legend[k])
          #dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1)
          #levs = numpy.arange(levs[0],levs[-1]+dx,dx)

        cols = range(gm.color_1,gm.color_2+1)
      else:
        if numpy.allclose(gm.levels,1.e20):
          levs = vcs.mkscale(mn,mx)
        else:
          levs = gm.levels
          if numpy.allclose(levs[0],1.e20):
            levs[0]=-1.e20
        cols = gm.fillareacolors
        if cols==[1,]:
          cols = vcs.getcolors(levs)
      Nlevs = len(levs)
      Ncolors = Nlevs-1
      #Prep mapper
      mappers=[]
      mapper = vtk.vtkPolyDataMapper()
      thr = vtk.vtkThreshold()
      thr.SetInputConnection(geoFilter.GetOutputPort())
      if not gm.ext_1 in ["y",1,True]  and not gm.ext_2 in ["y",1,True] :
          thr.ThresholdBetween(levs[0],levs[-1])
      elif gm.ext_1 in ["y",1,True]  and not gm.ext_2 in ["y",1,True] :
          thr.ThresholdByLower(levs[-1])
      elif not gm.ext_1 in ["y",1,True]  and gm.ext_2 in ["y",1,True] :
          thr.ThresholdByUpper(levs[0])
      thr.Update()
      geoFilter2 = vtk.vtkDataSetSurfaceFilter()
      geoFilter2.SetInputConnection(thr.GetOutputPort())
      if gm.ext_1 in ["y",1,True]  and gm.ext_2 in ["y",1,True] :
          mapper.SetInputConnection(geoFilter.GetOutputPort())
      else:
          mapper.SetInputConnection(geoFilter2.GetOutputPort())

    if mappers == []: # ok didn't need to have special banded contours
      mappers=[mapper,]
      ## Colortable bit
      # make sure length match
      while len(cols)<Ncolors:
        cols.append(cols[-1])

      lut.SetNumberOfTableValues(Ncolors)
      for i in range(Ncolors):
        r,g,b = cmap.index[cols[i]]
        lut.SetTableValue(i,r/100.,g/100.,b/100.)

      mapper.SetLookupTable(lut)
      if numpy.allclose(levs[0],-1.e20):
        lmn = mn-1.
      else:
        lmn= levs[0]
      if numpy.allclose(levs[-1],1.e20):
        lmx = mx+1.
      else:
        lmx= levs[-1]
      mapper.SetScalarRange(lmn,lmx)

    if missingMapper is not None:
      if isinstance(gm,meshfill.Gfm):
        mappers.append(missingMapper)
      else:
        mappers.insert(0,missingMapper)

    x1,x2,y1,y2 = vcs2vtk.getRange(gm,xm,xM,ym,yM)

    if tmpl.data.priority != 0:
      # And now we need actors to actually render this thing
      for mapper in mappers:
        act = vtk.vtkActor()
        if isinstance(mapper,list):
          act.SetMapper(mapper[0])
        else:
          mapper.Update()
          act.SetMapper(mapper)
        if geo is None:
          act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap)
        if isinstance(mapper,list):
          #act.GetMapper().ScalarVisibilityOff()
          #act.SetTexture(mapper[1])
          pass
        # create a new renderer for this mapper
        # (we need one for each mapper because of cmaera flips)
        ren = self.createRenderer()
        self.renWin.AddRenderer(ren)
        self.setLayer(ren,tmpl.data.priority)
        ren.AddActor(act)
        vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],wc=[x1,x2,y1,y2],geo=geo)

    if isinstance(gm,meshfill.Gfm):
      tmpl.plot(self.canvas,data1,gm,
                bg=self.bg,
                X=numpy.arange(xm,xM*1.1,(xM-xm)/10.),
                Y=numpy.arange(ym,yM*1.1,(yM-ym)/10.))
    else:
      self.renderTemplate(tmpl,data1,gm,t,z)
    if isinstance(gm,(isofill.Gfi,meshfill.Gfm,boxfill.Gfb)):
      if getattr(gm,"legend",None) is not None:
        legend = gm.legend
      if gm.ext_1 in ["y",1,True] and not numpy.allclose(levs[0],-1.e20):
          if isinstance(levs,numpy.ndarray):
              levs=levs.tolist()
          if not (isinstance(levs[0],list) and numpy.less_equal(levs[0][0],-1.e20)):
            levs.insert(0,-1.e20)
      if gm.ext_2 in ["y",1,True] and not numpy.allclose(levs[-1],1.e20):
          if isinstance(levs,numpy.ndarray):
              levs=levs.tolist()
          if not (isinstance(levs[-1],list) and numpy.greater_equal(levs[-1][-1],1.e20)):
            levs.append(1.e20)

      self.renderColorBar(tmpl,levs,cols,legend,cmap)
    if self.canvas._continents is None:
      continents = False
    if continents:
        projection = vcs.elements["projection"][gm.projection]
        self.plotContinents(x1,x2,y1,y2,projection,wrap,tmpl)
Example #12
0
import cdms2
import vcs
x = vcs.init()
f = cdms2.open(vcs.sample_data + "/clt.nc")
s = f("clt", time=slice(0, 23))
gm = x.createboxfill()
levs = vcs.mkevenlevels(20, 80)
gm.levels = levs
gm.fillareacolors = vcs.getcolors(levs)
d = x.plot(s, gm)
raw_input("Press enter")
x.animate.create(thread_it=False, min=20, max=80)
x.animate.fps(5000)
x.animate.run()
raw_input("Press enter to end")
x.animate.stop()