Example #1
0
def set_levels_of_graphics_method(method, levels, data, data2=None):
    if levels != []:
        method.levels = levels

    if method.levels == [[1.0000000200408773e+20, 1.0000000200408773e+20]]:
        if data2 is None:
            method.levels = vcs.mkscale(data.min(), data.max())
        else:
            method.levels = vcs.mkscale(min(data.min(), data2.min()), max(data.max(), data2.max()))
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)
Example #3
0
    def getlevels(self, varmin, varmax):
        if self.boxfill_type == "custom":
            return self.levels

        nlev = float(self.color_2 - self.color_1 + 1)
        autolevels = False

        if numpy.allclose(self.level_1, 1.e20) or numpy.allclose(
                self.level_2, 1.e20):
            autolevels = True
            low_end = varmin
            high_end = varmax
        else:
            low_end = self.level_1
            high_end = self.level_2

        if self.boxfill_type == "log10":
            low_end = numpy.ma.log10(low_end)
            high_end = numpy.ma.log10(high_end)

        if autolevels:
            # Use nice values for the scale
            scale = vcs.mkscale(low_end, high_end)
            low_end = scale[0]
            high_end = scale[-1]

        dx = (high_end - low_end) / nlev

        if dx == 0:
            high_end += .00001
            return [low_end, high_end]
        float_epsilon = numpy.finfo(numpy.float32).eps
        contourLevels = numpy.arange(low_end, high_end + float_epsilon, dx)

        return contourLevels
Example #4
0
    def prep_plot(self,xmn,xmx,ymn,ymx):

        self.save()

        if self.datawc_x1!=1.e20:
            xmn = self.datawc_x1
        if self.datawc_x2!=1.e20:
            xmx = self.datawc_x2
        if self.datawc_y1!=1.e20:
            ymn = self.datawc_y1
        if self.datawc_y2!=1.e20:
            ymx = self.datawc_y2

        self.datawc_x1=xmn
        self.datawc_x2=xmx
        self.datawc_y1=ymn
        self.datawc_y2=ymx

        for axes in ['x','y']:
            for sec in ['mtics','ticlabels']:
                for n in ['1','2']:
                    if getattr(self,axes+sec+n) == '*':
                        sc = vcs.mkscale(getattr(self,'datawc_'+axes+'1'),getattr(self,'datawc_'+axes+'2'))
                        setattr(self,axes+sec+n,vcs.mklabels(sc))
        return xmn,xmx,ymn,ymx
Example #5
0
    def getlevels(self, varmin, varmax):
        if self.boxfill_type == "custom":
            return self.levels

        nlev = float(self.color_2 - self.color_1 + 1)
        autolevels = False

        if numpy.allclose(self.level_1, 1.e20) or numpy.allclose(self.level_2, 1.e20):
            autolevels = True
            low_end = varmin
            high_end = varmax
        else:
            low_end = self.level_1
            high_end = self.level_2

        if self.boxfill_type == "log10":
            low_end = numpy.ma.log10(low_end)
            high_end = numpy.ma.log10(high_end)

        if autolevels:
            # Use nice values for the scale
            scale = vcs.mkscale(low_end, high_end)
            low_end = scale[0]
            high_end = scale[-1]

        dx = (high_end - low_end) / nlev

        if dx == 0:
            high_end += .00001
            return [low_end, high_end]
        float_epsilon = numpy.finfo(numpy.float32).eps
        contourLevels = numpy.arange(low_end, high_end + float_epsilon, dx)

        return contourLevels
Example #6
0
    def _updateContourLevelsAndColorsForCustomBoxfill(self):
        """Set contour information for a custom boxfill."""
        self._contourLevels = self._gm.levels

        if numpy.allclose(self._contourLevels[0], [0., 1.e20]) or \
              numpy.allclose(self._contourLevels, 1.e20):
            levs2 = vcs.mkscale(self._scalarRange[0], self._scalarRange[1])
            if len(levs2) == 1:  # constant value ?
                levs2 = [levs2[0], levs2[0] + .00001]
            self._contourLevels = []
            if self._gm.ext_1:
                ## user wants arrow at the end
                levs2[0] = -1.e20
            if self._gm.ext_2:
                ## user wants arrow at the end
                levs2[-1] = 1.e20
            for i in range(len(levs2) - 1):
                self._contourLevels.append([levs2[i], levs2[i + 1]])
        else:
            if not isinstance(self._gm.levels[0], (list, tuple)):
                self._contourLevels = []
                levs2 = self._gm.levels
                if numpy.allclose(levs2[0], 1.e20):
                    levs2[0] = 0
                for i in range(len(levs2) - 1):
                    self._contourLevels.append([levs2[i], levs2[i + 1]])

        # Contour colors:
        self._contourColors = self._gm.fillareacolors
        if self._contourColors is None:
            # TODO BUG levs2 may not be defined here...
            self._contourColors = vcs.getcolors(levs2, split=0)
Example #7
0
    def getlegendlabels(self, levels):
        if self.legend:
            return self.legend

        if numpy.allclose(self.level_1, 1.e20) or numpy.allclose(self.level_2, 1.e20):
            autolevels = True
        else:
            autolevels = False

        if len(levels) > 12:
            scale = vcs.mkscale(levels[0], levels[-1])
            if autolevels:
                return vcs.mklabels(scale)
            else:
                # Create our own scale
                dx = (self.level_2 - self.level_1) / float(len(scale) - 1)
                real_values = [self.level_1, self.level_2]
                float_epsilon = numpy.finfo(numpy.float32).eps
                levels = numpy.arange(levels[0], levels[-1] + float_epsilon, dx)
        else:
            real_values = levels

        # Need to line up the levels and the labels, so we'll massage the label positions
        max_round = 0
        for l in real_values:
            round_pos = 0
            while numpy.round(l, round_pos) != l:
                round_pos += 1
            max_round = max(max_round, round_pos)

        round_values = [numpy.round(l, round_pos) for l in levels]
        round_labels = vcs.mklabels(round_values, "list")

        return {lev: label for lev, label in zip(levels, round_labels)}
Example #8
0
    def getlegendlabels(self, levels):
        if self.legend:
            return self.legend

        if numpy.allclose(self.level_1, 1.e20) or numpy.allclose(self.level_2, 1.e20):
            autolevels = True
        else:
            autolevels = False

        if len(levels) > 12:
            scale = vcs.mkscale(levels[0], levels[-1])
            if autolevels:
                return vcs.mklabels(scale)
            else:
                # Create our own scale
                dx = (self.level_2 - self.level_1) / float(len(scale) - 1)
                real_values = [self.level_1, self.level_2]
                float_epsilon = numpy.finfo(numpy.float32).eps
                levels = numpy.arange(levels[0], levels[-1] + float_epsilon, dx)
        else:
            real_values = levels

        # Need to line up the levels and the labels, so we'll massage the label positions
        max_round = 0
        for l in real_values:
            round_pos = 0
            while numpy.round(l, round_pos) != l:
                round_pos += 1
            max_round = max(max_round, round_pos)

        round_values = [numpy.round(l, round_pos) for l in levels]
        round_labels = vcs.mklabels(round_values, "list")

        return {lev: label for lev, label in zip(levels, round_labels)}
Example #9
0
    def getlevels(self, varmin, varmax):
        """Given a minimum and a maximum, will generate levels for the boxfill
        starting at varmin and ending at varmax.

        :Example:

            .. doctest:: boxfill_getlevels

                >>> b=vcs.createboxfill()
                >>> lvls = b.getlevels(0,100) # 257 levels from 0-100
                >>> b.levels = list(lvls) # set boxfill's levels attribute

        :param varmin: The smallest number desired for the boxfill's levels
            attribute.
        :type varmin: float

        :param varmax: The largest number desired for the boxfill's levels
            attribute.
        :type varmin: float

        :return: A numpy array of 257 floats, evenly distributed from varmin to
            varmax.
        :rtype: numpy.ndarray
        """
        if self.boxfill_type == "custom":
            return self.levels

        nlev = float(self.color_2 - self.color_1 + 1)
        autolevels = False

        if numpy.allclose(self.level_1, 1.e20) or numpy.allclose(
                self.level_2, 1.e20):
            autolevels = True
            low_end = varmin
            high_end = varmax
        else:
            low_end = self.level_1
            high_end = self.level_2

        if self.boxfill_type == "log10":
            low_end = numpy.ma.log10(low_end)
            high_end = numpy.ma.log10(high_end)

        if autolevels:
            # Use nice values for the scale
            scale = vcs.mkscale(low_end, high_end)
            low_end = scale[0]
            high_end = scale[-1]

        dx = (high_end - low_end) / nlev

        if dx == 0:
            high_end += .00001
            return [low_end, high_end]
        float_epsilon = numpy.finfo(numpy.float32).eps
        if float_epsilon > (high_end - low_end):
            float_epsilon = numpy.finfo(numpy.float64).eps
        contourLevels = numpy.arange(low_end, high_end + float_epsilon, dx)

        return contourLevels
Example #10
0
    def _updateContourLevelsAndColorsForCustomBoxfill(self):
        """Set contour information for a custom boxfill."""
        self._contourLevels = self._gm.levels

        if numpy.allclose(self._contourLevels[0], [0., 1.e20]) or \
              numpy.allclose(self._contourLevels, 1.e20):
            levs2 = vcs.mkscale(self._scalarRange[0],
                                self._scalarRange[1])
            if len(levs2) == 1: # constant value ?
                levs2 = [levs2[0], levs2[0] + .00001]
            self._contourLevels = []
            if self._gm.ext_1:
                ## user wants arrow at the end
                levs2[0] = -1.e20
            if self._gm.ext_2:
                ## user wants arrow at the end
                levs2[-1] = 1.e20
            for i in range(len(levs2) - 1):
                self._contourLevels.append([levs2[i], levs2[i+1]])
        else:
            if not isinstance(self._gm.levels[0], (list, tuple)):
                self._contourLevels = []
                levs2 = self._gm.levels
                if numpy.allclose(levs2[0], 1.e20):
                    levs2[0] = 0
                for i in range(len(levs2) - 1):
                    self._contourLevels.append([levs2[i], levs2[i+1]])

        # Contour colors:
        self._contourColors = self._gm.fillareacolors
        if self._contourColors is None:
            # TODO BUG levs2 may not be defined here...
            self._contourColors = vcs.getcolors(levs2, split=0)
Example #11
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 #12
0
    def levels(self):
        """Used internally, don't worry about it."""
        levs = list(self._gm.levels)
        # Check if they're autolevels
        if numpy.allclose(levs, 1e20):
            if vcs.isboxfill(self._gm) == 1:
                nlevs = self.color_2 - self.color_1 + 1
                minval, maxval = vcs.minmax(self._var)
                levs = vcs.mkscale(minval, maxval)
                if len(levs) == 1:
                    levs.append(levs[0] + .00001)
                delta = (levs[-1] - levs[0]) / nlevs
                levs = list(numpy.arange(levs[0], levs[-1] + delta, delta))
            else:
                levs = vcs.mkscale(*vcs.minmax(self._var))

        # Now adjust for ext_1 nad ext_2
        if self.ext_left:
            levs.insert(0, -1e20)
        if self.ext_right:
            levs.append(1e20)

        return levs
Example #13
0
    def levels(self):
        """Used internally, don't worry about it."""
        levs = list(self._gm.levels)
        # Check if they're autolevels
        if numpy.allclose(levs, 1e20):
            if vcs.isboxfill(self._gm) == 1:
                nlevs = self.color_2 - self.color_1 + 1
                minval, maxval = vcs.minmax(self._var)
                levs = vcs.mkscale(minval, maxval)
                if len(levs) == 1:
                    levs.append(levs[0] + .00001)
                delta = (levs[-1] - levs[0]) / nlevs
                levs = list(numpy.arange(levs[0], levs[-1] + delta, delta))
            else:
                levs = vcs.mkscale(*vcs.minmax(self._var))

        # Now adjust for ext_1 nad ext_2
        if self.ext_left:
            levs.insert(0, -1e20)
        if self.ext_right:
            levs.append(1e20)

        return levs
Example #14
0
 def _updateContourLevelsAndColors(self):
     """Overrides baseclass implementation."""
     # Contour values:
     self._contourLevels = self._gm.levels
     if numpy.allclose(self._contourLevels[0], [0., 1.e20]) or \
        numpy.allclose(self._contourLevels, 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]
     else:
         if isinstance(self._gm.levels[0], (list, tuple)):
             self._contourLevels = [x[0] for x in self._gm.levels]
         else:
             if numpy.allclose(self._contourLevels[0], 1.e20):
                 self._contourLevels[0] = -1.e20
     self._contourColors = self._gm.linecolors
     self.extendAttribute(self._contourColors, default='black')
Example #15
0
 def _updateContourLevelsAndColors(self):
     """Overrides baseclass implementation."""
     # Contour values:
     self._contourLevels = self._gm.levels
     if numpy.allclose(self._contourLevels[0], [0., 1.e20]) or \
        numpy.allclose(self._contourLevels, 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]
     else:
         if isinstance(self._gm.levels[0], (list, tuple)):
             self._contourLevels = [x[0] for x in self._gm.levels]
         else:
             if numpy.allclose(self._contourLevels[0], 1.e20):
                 self._contourLevels[0] = -1.e20
     self._contourColors = self._gm.linecolors
     self.extendAttribute(self._contourColors, default='black')
Example #16
0
    def _updateContourLevelsAndColorsGeneric(self):
        # Contour values:
        self._contourLevels = self._gm.levels
        if numpy.allclose(self._contourLevels[0], [0., 1.e20]) or \
                numpy.allclose(self._contourLevels, 1.e20):
            levs2 = vcs.mkscale(self._scalarRange[0],
                                self._scalarRange[1])
            if len(levs2) == 1:  # constant value ?
                levs2 = [levs2[0], levs2[0] + .00001]
            self._contourLevels = []
            if self._gm.ext_1:
                # user wants arrow at the end
                levs2[0] = -1.e20
            if self._gm.ext_2:
                # user wants arrow at the end
                levs2[-1] = 1.e20
            for i in range(len(levs2) - 1):
                self._contourLevels.append([levs2[i], levs2[i + 1]])
        else:
            if not isinstance(self._gm.levels[0], (list, tuple)):
                self._contourLevels = []
                levs2 = self._gm.levels
                if numpy.allclose(levs2[0], 1.e20):
                    levs2[0] = -1.e20
                for i in range(len(levs2) - 1):
                    self._contourLevels.append([levs2[i], levs2[i + 1]])
            else:
                levs2 = self._gm.levels

        if isinstance(self._contourLevels, numpy.ndarray):
            self._contourLevels = self._contourLevels.tolist()

        # Figure out colors
        self._contourColors = self._gm.fillareacolors
        if self._contourColors == [1] or self._contourColors is None:
            # TODO BUG It's possible that levs2 may not exist here...
            self._contourColors = vcs.getcolors(levs2, split=0)
            if isinstance(self._contourColors, (int, float)):
                self._contourColors = [self._contourColors]
Example #17
0
 def testUpdateArray(self):
     f = cdms2.open(
         os.path.join(cdat_info.get_sampledata_path(),
                      "ta_ncep_87-6-88-4.nc"))
     data = f("ta")
     levels = vcs.mkscale(*vcs.minmax(data))
     levels.insert(0, 1.e20)
     levels.append(1.e20)
     colors = vcs.getcolors(levels)
     isof = vcs.createisofill()
     isof.levels = levels
     isof.fillareacolors = colors
     isol = vcs.createisoline()
     isol.levels = levels
     tmpl = self.x.gettemplate("top_of2")
     self.x.portrait()
     self.x.plot(data, isof, tmpl)
     tmpl = self.x.gettemplate("bot_of2")
     disp = self.x.plot(data, isof, tmpl)
     kw = {"time": slice(3, 4), "level": slice(6, 7)}
     new = disp.array[0](**kw)
     self.x.backend.update_input(disp.backend, new)
     self.checkImage("test_vcs_update_array_extensions.png")
Example #18
0
    def _updateContourLevelsAndColors(self):
        """Overrides baseclass implementation."""
        # Contour values:
        self._contourLevels = self._gm.levels
        if numpy.allclose(self._contourLevels[0], [0., 1.e20]) or \
           numpy.allclose(self._contourLevels, 1.e20):
            levs2 = vcs.mkscale(self._scalarRange[0], self._scalarRange[1])
            if len(levs2) == 1:  # constant value ?
                levs2 = [levs2[0], levs2[0] + .00001]
            self._contourLevels = []
            if self._gm.ext_1:
                # user wants arrow at the end
                levs2[0] = -1.e20
            if self._gm.ext_2:
                # user wants arrow at the end
                levs2[-1] = 1.e20
            for i in range(len(levs2) - 1):
                self._contourLevels.append([levs2[i], levs2[i+1]])
        else:
            if not isinstance(self._contourLevels[0], (list, tuple)):
                self._contourLevels = []
                levs2 = self._gm.levels
                if numpy.allclose(levs2[0], 1.e20):
                    levs2[0] = -1.e20
                for i in range(len(levs2) - 1):
                    self._contourLevels.append([levs2[i], levs2[i+1]])

        # Contour colors:
        self._contourColors = self._gm.fillareacolors
        if self._contourColors == [1]:
            # TODO BUG levs2 may be uninitialized here
            self._contourColors = vcs.getcolors(levs2, split=0)
            if isinstance(self._contourColors, (int, float)):
                self._contourColors = [self._contourColors]

        if isinstance(self._contourLevels, numpy.ndarray):
            self._contourLevels = self._contourLevels.tolist()
Example #19
0
    def finalize( self, flip_x=False, flip_y=False ):
        """By the time this is called, all synchronize operations should have been done.  But even
        so, each variable has a min and max and a min and max for each of its axes.  We need to
        simplify further for the plot package.
        The options flip_x and flip_y may be set to True to flip the axis.  That is, in x right
        to left and left to right, and in y top to bottom and bottom to top."""
        # old test:
        #if self.presentation.__class__.__name__=="GYx" or\
        #        self.presentation.__class__.__name__=="Gfi":
        # interim test here and below.  Once all the is* functions work, I should
        # drop the tests on self.presentation.__class__.__name__ :
        if vcs.isscatter(self.presentation):
            ylabel, xlabel = string.split(self.title, ' vs ')
            #pdb.set_trace()
            #in the case of scatter plots there are 2 variables packed together
            var = self.vars[0]
            [xMIN, xMAX], [yMIN, yMAX] = self.make_ranges(var)

            #print xMIN, xMAX, yMIN, yMAX
            #print vcs.mkscale(xMIN, xMAX)
            #print vcs.mkscale(yMIN, yMAX)
            self.presentation.xticlabels1 = vcs.mklabels(vcs.mkscale(xMIN, xMAX))
            self.presentation.datawc_x1 = xMIN
            self.presentation.datawc_x2 = xMAX
            self.presentation.xticlabels2 = {(xMIN+xMAX)/2.: xlabel}
            if flip_y:
                self.presentation.datawc_y2 = yMIN
                self.presentation.datawc_y1 = yMAX
                self.presentation.flip = True
            else:
                self.presentation.datawc_y1 = yMIN
                self.presentation.datawc_y2 = yMAX   
            self.presentation.yticlabels1 = vcs.mklabels(vcs.mkscale(yMIN, yMAX))
            self.presentation.yticlabels2 = {(yMIN+yMAX)/2.: ylabel}
            self.presentation.linewidth = 0
            self.presentation.markercolor = 1
            self.presentation.markersize = 5
            #add overplotline is a total kludge
            self.presentation.overplotline = self.overplotline
            if flip_y:
                self.presentation.flip = True
            #self.presentation.list()              
        elif vcs.isyxvsx(self.presentation) or\
                vcs.isisofill(self.presentation) or\
                vcs.isboxfill(self.presentation) or\
                self.presentation.__class__.__name__=="GYx" or\
                self.presentation.__class__.__name__=="G1d" or\
                self.presentation.__class__.__name__=="Gv":
            #pdb.set_trace()
            if flip_y:
                self.presentation.flip = True
            var = self.vars[0]
            axmax = self.axmax[seqgetattr(var,'id','')]
            axmin = self.axmin[seqgetattr(var,'id','')]
            varmax = self.varmax[seqgetattr(var,'id','')]
            varmin = self.varmin[seqgetattr(var,'id','')]
            for v in self.vars[1:]:
                for ax in axmax.keys():
                    axmax[ax] = max(axmax[ax],self.axmax[seqgetattr(v,'id','')][ax])
                    axmin[ax] = min(axmin[ax],self.axmin[seqgetattr(v,'id','')][ax])
                varmax = max(varmax,self.varmax[v.id])
                varmin = min(varmin,self.varmin[v.id])                 
            if vcs.isyxvsx(self.presentation) or\
                    self.presentation.__class__.__name__=="GYx" or\
                    self.presentation.__class__.__name__=="G1d":
                if len(axmax.keys())<=0:
                    return None
                # VCS Yxvsx
                ax = axmax.keys()[0]
                if flip_x:
                    self.presentation.datawc_x2 = axmin[ax]
                    self.presentation.datawc_x1 = axmax[ax]
                else:
                    self.presentation.datawc_x1 = axmin[ax]
                    self.presentation.datawc_x2 = axmax[ax]
                if flip_y:
                    self.presentation.datawc_y2 = varmin
                    self.presentation.datawc_y1 = varmax
                else:
                    self.presentation.datawc_y1 = varmin
                    self.presentation.datawc_y2 = varmax
                #print "DEBUG, in finalize for line plot, datawc_{x1,x2,y1,y2}=",\
                #    self.presentation.datawc_x1, self.presentation.datawc_x2,\
                #    self.presentation.datawc_y1, self.presentation.datawc_y2
            if vcs.isisofill(self.presentation) or self.presentation.__class__.__name__=="Gfi"\
                    or vcs.isboxfill(self.presentation):
                # VCS Isofill or Boxfill

                # First we have to identify which axes will be plotted as X and Y.
                # If the axes each had an 'axis' attribute, axaxi will look something like
                # {'X':'axis1id', 'Y':'axis2id'}.  If one misses the attribute, 'axis0id':'axis0id'.
                axaxi = {ax:id for id,ax in self.axax[seqgetattr(var,'id','')].items()}
                if 'X' in axaxi.keys() and 'Y' in axaxi.keys():
                    axx = axaxi['X']
                    axy = axaxi['Y']
                elif 'Y' in axaxi.keys() and 'Z' in axaxi.keys():
                    axx = axaxi['Y']
                    axy = axaxi['Z']
                #added case of time vs variable
                elif 'T' in axaxi.keys() and 'Y' in axaxi.keys():
                    axx = axaxi['T']
                    axy = axaxi['Y']
                    if axx == 'time':
                        t=var.getTime()
                        if 'units' in dir(t) and t.units == "months since 1800":
                            time_lables = {}
                            months_names = get_month_strings(length=3)             
                            tc=t.asComponentTime()
                            for i, v in enumerate(t):
                                time_lables[v] = months_names[tc[i].month-1]
                            self.presentation.xticlabels1 = time_lables
                            self.presentation.datawc_timeunits = t.units
                            #self.presentation.list()
                elif len(axaxi.keys())==2:
                    # It's not clear what should be the X variable and what the Y variable,
                    # but it's worth trying to do something
                    axx = None
                    axy = None
                    for axetc in var.getDomain()[:]:
                        ax = axetc[0]
                        if getattr(ax,'units',None)=='mbar':
                            # probably pressure levels, a vertical axis
                            axy = ax.id
                        else:
                            axx = ax.id
                    if axx is None or axy is None:
                        # last resort
                        axy = axaxi[axaxi.keys()[0]]
                        axx = axaxi[axaxi.keys()[1]]
                else:
                    return None

                # Now send the plotted min,max for the X,Y axes to the graphics:
                # and if it is not a polar projection
                if vcs.getprojection(self.presentation.projection)._type!=-3:
                    if flip_x:
                        self.presentation.datawc_x2 = axmin[axx]
                        self.presentation.datawc_x1 = axmax[axx]
                    else:
                        self.presentation.datawc_x1 = axmin[axx]
                        self.presentation.datawc_x2 = axmax[axx]
                    if flip_y:
                        self.presentation.datawc_y2 = axmin[axy]
                        self.presentation.datawc_y1 = axmax[axy]
                    else:
                        self.presentation.datawc_y1 = axmin[axy]
                        self.presentation.datawc_y2 = axmax[axy]

                # The variable min and max, varmin and varmax, should be passed on to the graphics
                # for setting the contours.  But apparently you can't tell VCS just the min and max;
                # you have to give it all the contour levels.  So...
                if vcs.isboxfill(self.presentation):
                    self.presentation.boxfill_type = 'custom'  # without this, can't set levels
                nlevels = 16
                try:
                    levels = [float(v) for v in vcs.mkscale( varmin, varmax, nlevels )]
                    # Exceptions occur because mkscale doesn't always work.  E.g. vcs.mkscale(0,1.e35,16)
                except RuntimeWarning:
                    levels = []
                if levels==[]:
                    ## Here's how to do it with percentiles (clip out large values first).
                    #pc05 = numpy.percentile(self.vars[0],0.05)
                    #pc95 = numpy.percentile(self.vars[0],0.95)
                    #levels = [float(v) for v in vcs.mkscale( pc05, pc95, nlevels-2 )]
                    #levels = [varmin]+levels+[varmax]
                    # Evenly distributed levels, after clipping out large values:
                    # This cannot be expected to work always, but it's better than doing nothing.
                    amed = numpy.median(self.vars[0]._data)
                    vclip = amed * 1.0e6
                    print "WARNING graphics problems, clipping some data at",vclip
                    self.vars[0]._data[ self.vars[0]._data > vclip ] = vclip
                    a = numpy.sort(self.vars[0]._data.flatten())
                    asp = numpy.array_split(a,nlevels)
                    afirsts = [c[0] for c in asp]+[asp[-1][-1]]
                    alasts = [asp[0][0]]+[c[-1] for c in asp]
                    levels = [0.5*(afirsts[i]+alasts[i]) for i in range(len(afirsts))]
                    levf = levels[0]
                    levl = levels[-1]
                    levels = [ round(lv,2) for lv in levels ]
                    levels[0] = round(1.1*levels[0]-0.1*levels[1],2)
                    levels[-1] = round(1.1*levels[-1]-0.1*levels[-2],2)

                # ... mkscale returns numpy.float64, which behaves unexpectedly in _setlevels when
                # passed a tuple value
                if levels is not None and len(levels)>0:
                    self.presentation.levels = levels
                #nlevels = max(1, len(levels) - 1)
                #nlrange = range(nlevels+1)
                #nlrange.reverse()
                #self.presentation.legend = vcs.mklabels( self.presentation.levels )
                ## Once you set the levels, the VCS default color choice looks bad.  So you really
                ## have to set contour fill colors (integers from 0 through 255) too:
                #cmin = 32./nlevels
                #cmax = 255./nlevels
                ## A more flexible way to do what's going on here, thanks to Charles Doutriaux:
                ## r=10
                ## g=16
                ## b=20
                ## X.setcolorcell(16,r,g,b)
                ## colors = [16,17,18,...] etc.
                ## vcs.getcolors is useful, more complicated - see its doc string
                #colors =  [int(round(a*cmin+(nlevels-a)*cmax)) for a in nlrange]
                #self.presentation.fillareacolors = colors
                ##self.presentation.fillareacolors=[32,48,64,80,96,112,128,144,160,176,240]
            elif vcs.isvector(self.presentation) or self.presentation.__class__.__name__=="Gv":
                # axis min,max copied from isofill
                axaxi = {ax:id for id,ax in self.axax[seqgetattr(var,'id','')].items()}
                if 'X' in axaxi.keys() and 'Y' in axaxi.keys():
                    axx = axaxi['X']
                    axy = axaxi['Y']
                elif 'Y' in axaxi.keys() and 'Z' in axaxi.keys():
                    axx = axaxi['Y']
                    axy = axaxi['Z']
                self.presentation.datawc_x1 = axmin[axx]
                self.presentation.datawc_x2 = axmax[axx]
                self.presentation.datawc_y1 = axmin[axy]
                self.presentation.datawc_y2 = axmax[axy]

                vec = self.presentation
                vec.scale = min(vcsx.bgX,vcsx.bgY)/ 10.
                if hasattr(self.vars[0],'__getitem__') and not hasattr( self.vars[0], '__cdms_internals__'):
                    # generally a tuple of variables - we need 2 variables to describe a vector
                    v = self.vars[0][0]
                    w = self.vars[0][1]
                else:   # We shouldn't get here, but may as well try to make it work if possible:
                    print "WARNING trying to make a vector plot without tuples!  Variables involved are:"
                    v = self.vars[0]
                    print "variable",v.id
                    v = self.vars[1]
                    print "variable",v.id
                nlats = latAxis(v).shape[0]
                nlons = lonAxis(w).shape[0]
                nlatvs = vcsx.bgY/16   # how many vectors we want in lat direction
                nlonvs = vcsx.bgX/16
                #self.strideX = int( 0.9* vcsx.bgX/nlons )
                #self.strideY = int( 0.6* vcsx.bgY/nlats )
                self.strideX = max(1, int( nlons/nlonvs )) # stride values must be at least 1
                self.strideY = max(1, int( nlats/nlatvs ))
        else:
            print "ERROR cannot identify graphics method",self.presentation.__class__.__name__
Example #20
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
 def testMakeScale(self):
     self.assertEqual(vcs.mkscale(3.5, 3.5, 16), [
         3.5,
     ])
Example #22
0
    def plot(self, var, theta=None, template=None, bg=0, x=None):
        """
        Plots a polar plot of your data.

        If var is an ndarray with the second dimension being 2, it will use the first value
        as magnitude and the second as theta.

        Otherwise, if theta is provided, it uses var as magnitude and the theta given.
        """
        if x is None:
            if self.x is None:
                self.x = vcs.init()
            x = self.x
        if template is None:
            template = self.template

        if self.markercolorsource.lower() not in ("group", "magnitude", "theta"):
            raise ValueError("polar.markercolorsource must be one of: 'group', 'magnitude', 'theta'")

        magnitudes, thetas, names = convert_arrays(var, theta)
        if self.group_names:
            names = self.group_names
            while len(names) < len(magnitudes):
                names.append(None)

        flat_magnitude = []
        for i in magnitudes:
            flat_magnitude.extend(i)
        flat_theta = []
        for i in thetas:
            flat_theta.extend(i)

        canvas = x
        # Determine aspect ratio for plotting the circle
        canvas_info = canvas.canvasinfo()
        # Calculate aspect ratio of window
        window_aspect = canvas_info["width"] / float(canvas_info["height"])
        if window_aspect > 1:
            ymul = window_aspect
            xmul = 1
        else:
            ymul = 1
            xmul = window_aspect
        # Use window_aspect to adjust size of template.data
        x0, x1 = template.data.x1, template.data.x2
        y0, y1 = template.data.y1, template.data.y2

        xdiff = abs(x1 - x0)
        ydiff = abs(y1 - y0)

        center = x0 + xdiff / 2., y0 + ydiff / 2.
        diameter = min(xdiff, ydiff)
        radius = diameter / 2.
        plot_kwargs = {"render": False, "bg": bg, "donotstoredisplay": True}
        # Outer line
        if template.box1.priority > 0:
            outer = vcs.createline(source=template.box1.line)
            x, y = circle_points(center, radius, ratio=window_aspect)
            outer.x = x
            outer.y = y
            canvas.plot(outer, **plot_kwargs)
            del vcs.elements["line"][outer.name]

        if numpy.allclose((self.datawc_y1, self.datawc_y2), 1e20):
            if self.magnitude_ticks == "*":
                m_scale = vcs.mkscale(*vcs.minmax(flat_magnitude))
            else:
                if isinstance(self.magnitude_ticks, (str, unicode)):
                    ticks = vcs.elements["list"][self.magnitude_ticks]
                else:
                    ticks = self.magnitude_ticks
                m_scale = ticks
        else:
            m_scale = vcs.mkscale(self.datawc_y1, self.datawc_y2)

        if template.ytic1.priority > 0:
            m_ticks = vcs.createline(source=template.ytic1.line)
            m_ticks.x = []
            m_ticks.y = []

            if template.ylabel1.priority > 0:
                to = self.text_orientation_for_angle(self.magnitude_tick_angle,
                                                     source=template.ylabel1.textorientation)
                m_labels = self.create_text(template.ylabel1.texttable, to)
                m_labels.x = []
                m_labels.y = []
                m_labels.string = []
                if self.yticlabels1 == "*":
                    mag_labels = vcs.mklabels(m_scale)
                else:
                    mag_labels = self.yticlabels1
            else:
                m_labels = None

            for lev in m_scale:
                lev_radius = radius * self.magnitude_from_value(lev, (m_scale[0], m_scale[-1]))
                x, y = circle_points(center, lev_radius, ratio=window_aspect)
                if m_labels is not None:
                    if lev in mag_labels:
                        m_labels.string.append(mag_labels[lev])
                        m_labels.x.append(xmul * lev_radius * numpy.cos(self.magnitude_tick_angle) + center[0])
                        m_labels.y.append(ymul * lev_radius * numpy.sin(self.magnitude_tick_angle) + center[1])
                m_ticks.x.append(x)
                m_ticks.y.append(y)
            canvas.plot(m_ticks, **plot_kwargs)
            del vcs.elements["line"][m_ticks.name]
            if m_labels is not None:
                canvas.plot(m_labels, **plot_kwargs)
                del vcs.elements["textcombined"][m_labels.name]

        if template.ymintic1.priority > 0 and self.magnitude_mintics is not None:
            mag_mintics = vcs.createline(source=template.ymintic1.line)
            mag_mintics.x = []
            mag_mintics.y = []

            mintics = self.magnitude_mintics
            if isinstance(mintics, (str, unicode)):
                mintics = vcs.elements["list"][mintics]

            for mag in mintics:
                mintic_radius = radius * self.magnitude_from_value(mag, (m_scale[0], m_scale[-1]))
                x, y = circle_points(center, mintic_radius, ratio=window_aspect)
                mag_mintics.x.append(x)
                mag_mintics.y.append(y)
            canvas.plot(mag_mintics, **plot_kwargs)
            del vcs.elements["line"][mag_mintics.name]

        if self.xticlabels1 == "*":
            if numpy.allclose((self.datawc_x1, self.datawc_x2), 1e20):
                tick_thetas = list(numpy.arange(0, numpy.pi * 2, numpy.pi / 4))
                tick_labels = {t: str(t) for t in tick_thetas}
            else:
                d_theta = (self.datawc_x2 - self.datawc_x1) / float(self.theta_tick_count)
                tick_thetas = numpy.arange(self.datawc_x1, self.datawc_x2 + .0001, d_theta)
                tick_labels = vcs.mklabels(tick_thetas)
        else:
            tick_thetas = self.xticlabels1.keys()
            tick_labels = self.xticlabels1

        if template.xtic1.priority > 0:
            t_ticks = vcs.createline(source=template.xtic1.line)
            t_ticks.x = []
            t_ticks.y = []

            if template.xlabel1.priority > 0:
                t_labels = []
                theta_labels = tick_labels
            else:
                t_labels = None

            for t in tick_thetas:
                angle = self.theta_from_value(t)
                x0 = center[0] + (xmul * radius * numpy.cos(angle))
                x1 = center[0]
                y0 = center[1] + (ymul * radius * numpy.sin(angle))
                y1 = center[1]
                if t_labels is not None:
                    label = self.create_text(template.xlabel1.texttable,
                                             self.text_orientation_for_angle(angle,
                                                                             source=template.xlabel1.textorientation))
                    label.string = [theta_labels[t]]
                    label.x = [x0]
                    label.y = [y0]
                    t_labels.append(label)
                t_ticks.x.append([x0, x1])
                t_ticks.y.append([y0, y1])
            canvas.plot(t_ticks, **plot_kwargs)
            del vcs.elements["line"][t_ticks.name]
            if t_labels is not None:
                for l in t_labels:
                    canvas.plot(l, **plot_kwargs)
                    del vcs.elements["textcombined"][l.name]

        values = vcs.createmarker()
        values.type = self.markers
        values.size = self.markersizes
        values.color = self.markercolors
        values.colormap = self.colormap
        values.priority = self.markerpriority
        values.x = []
        values.y = []

        if template.legend.priority > 0:
            # Only labels that are set will show up in the legend
            label_count = len(names) - len([i for i in names if i is None])
            labels = self.create_text(template.legend.texttable, template.legend.textorientation)
            labels.x = []
            labels.y = []
            labels.string = []

        if self.draw_lines:
            line = vcs.createline()
            line.x = []
            line.y = []
            line.type = self.lines
            line.color = self.linecolors if self.linecolors is not None else self.markercolors
            line.width = self.linewidths
            line.priority = self.linepriority

            # This is up here because when it's part of the main loop, we can lose "order" of points when we flatten them.
            for mag, theta in zip(magnitudes, thetas):
                x = []
                y = []

                for m, t in zip(mag, theta):
                    t = self.theta_from_value(t)
                    r = self.magnitude_from_value(m, (m_scale[0], m_scale[-1])) * radius
                    x.append(xmul * numpy.cos(t) * r + center[0])
                    y.append(ymul * numpy.sin(t) * r + center[1])

                if self.connect_groups:
                    line.x.extend(x)
                    line.y.extend(y)
                else:
                    line.x.append(x)
                    line.y.append(y)

        if self.markercolorsource.lower() in ('magnitude', "theta"):
            # Regroup the values using the appropriate metric

            mag_flat = numpy.array(magnitudes).flatten()
            theta_flat = numpy.array(thetas).flatten()

            if self.markercolorsource.lower() == "magnitude":
                scale = m_scale
                vals = mag_flat
            else:
                scale = theta_ticks
                vals = theta_flat

            indices = [numpy.where(numpy.logical_and(vals >= scale[i], vals <= scale[i + 1]))
                       for i in range(len(scale) - 1)]
            magnitudes = [mag_flat[inds] for inds in indices]
            thetas = [theta_flat[inds] for inds in indices]
            names = vcs.mklabels(scale, output="list")
            names = [names[i] + " - " + names[i + 1] for i in range(len(names) - 1)]
            label_count = len(names)

        for mag, theta, name in zip(magnitudes, thetas, names):
            x = []
            y = []
            for m, t in zip(mag, theta):
                t = self.theta_from_value(t)
                r = self.magnitude_from_value(m, (m_scale[0], m_scale[-1])) * radius
                x.append(xmul * numpy.cos(t) * r + center[0])
                y.append(ymul * numpy.sin(t) * r + center[1])

            if template.legend.priority > 0 and name is not None:
                y_offset = len(labels.x) / float(label_count) * (template.legend.y2 - template.legend.y1)
                lx, ly = template.legend.x1, template.legend.y1 + y_offset
                x.append(lx)
                y.append(ly)
                labels.x.append(lx + .01)
                labels.y.append(ly)
                labels.string.append(str(name))
            values.x.append(x)
            values.y.append(y)

        if template.legend.priority > 0:
            canvas.plot(labels, **plot_kwargs)
            del vcs.elements["textcombined"][labels.name]
        if self.draw_lines:
            canvas.plot(line, **plot_kwargs)
            del vcs.elements["line"][line.name]

        for el in self.to_cleanup:
            if vcs.istexttable(el):
                if el.name in vcs.elements["texttable"]:
                    del vcs.elements["texttable"][el.name]
            else:
                if el.name in vcs.elements["textorientation"]:
                    del vcs.elements["textorientation"][el.name]
        self.to_cleanup = []

        # Prune unneeded levels from values
        to_prune = []
        for ind, (x, y) in enumerate(zip(values.x, values.y)):
            if x and y:
                continue
            else:
                to_prune.append(ind)

        for prune_ind in to_prune[::-1]:
            del values.x[prune_ind]
            del values.y[prune_ind]
            if len(values.color) > prune_ind and len(values.color) > 1:
                del values.color[prune_ind]
            if len(values.size) > prune_ind and len(values.size) > 1:
                del values.size[prune_ind]
            if len(values.type) > prune_ind and len(values.type) > 1:
                del values.type[prune_ind]

        canvas.plot(values, bg=bg, donotstoredisplay=True)
        del vcs.elements["marker"][values.name]
        return canvas
Example #23
0
 def set_animation_min_max(self, min, max, i):
     from vcs import mkscale, mklabels, getcolors
     animation_info = self.animate_info_from_python()
     gtype = animation_info["gtype"][i].lower()
     levs = mkscale(min, max)
     dic = mklabels(levs)
     cols = getcolors(levs)
     if gtype == "boxfill":
         gm = self.vcs_self.getboxfill(animation_info['gname'][i])
         if gm.boxfill_type == 'custom':
             gm.fillareacolors = cols
             gm.levels = levs
         else:
             gm.level_1 = levs[0]
             gm.level_2 = levs[-1]
             gm.legend = None
     elif (gtype == "meshfill"):
         gm = self.vcs_self.getmeshfill(animation_info['gname'][i])
         if (min == 1e20) and (max == 1e20):
             gm.levels = (1e20, 1e20)
         else:
             gm.levels = levs
             gm.fillareacolors = cols
     elif (gtype == "isofill"):
         gm = self.vcs_self.getisofill(animation_info['gname'][i])
         if (min == 1e20) and (max == 1e20):
             gm.levels = (1e20, 1e20)
         else:
             gm.levels = levs
             gm.fillareacolors = cols
     elif (gtype == "isoline"):
         gm = self.vcs_self.getisoline(animation_info['gname'][i])
         if (min == 1e20) and (max == 1e20):
             gm.levels = (1e20, 1e20)
         else:
             gm.levels = levs
             gm.fillareacolors = cols
     elif (gtype == "yxvsx"):
         gm = self.vcs_self.getyxvsx(animation_info['gname'][i])
         if (min != 1e20) and (max != 1e20):
             gm.yticlabels1 = dic
             gm.yticlabels2 = dic
             min = levs[0]
             max = levs[-1]
         gm.datawc_y1 = min
         gm.datawc_y2 = max
     elif (gtype == "xyvsy"):
         gm = self.vcs_self.getxyvsy(animation_info['gname'][i])
         if (min != 1e20) and (max != 1e20):
             gm.xticlabels1 = dic
             gm.xticlabels2 = dic
             min = levs[0]
             max = levs[-1]
         gm.datawc_x1 = min
         gm.datawc_x2 = max
     elif (gtype == "vector"):
         gm = self.vcs_self.getvector(animation_info['gname'][i])
         mean_veloc = 1e20
         if (min != 1e20) and (max != 1e20):
             mean_veloc = float(int(numpy.sqrt((min ** 2) + (max ** 2))))
         gm.reference = mean_veloc
     animation_info['gname'][i] = gm.name
Example #24
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 #25
0
		m.drawparallels(vcs.mkscale(genutil.minmax(lat)),labels=[1,0,0,0])
		m.drawmeridians(vcs.mkscale(genutil.minmax(lon)),labels=[0,0,0,1])
	figtext(.5,1.,"\n%s [%s]" % ("El Nino phase composites\nSea surface temperature", composites.units))
	savefig(sys.argv[0].replace(".py",".png"))
	show()
	

# Fall back to vcs because we have it!
except:
	# Plot 1 phase over two, then a time series
	# TODO: we must do something nicer!!
	import vcs,EzTemplate
	x=vcs.init()
	T=EzTemplate.Multi(rows=nrow,columns=ncol) # Nrow added 1 for original data row
	mn,mx=-1,1
	levels = vcs.mkscale(mn,mx)
	levels.insert(0,-1.e20) # extension left side
	levels.append(1.e20) # extension right side
	colors = vcs.getcolors(levels)
	iso = x.createisofill('spanlib')
	iso.levels = levels
	iso.fillareacolors = colors
	f=cdms.open('tmp.nc','w')
	f.write(out,id='composites',typecode='f')
	f.close()
	for i in xrange(nslice):
		print i
		templ = T.get(font=0)
		x.plot(out[i],templ,iso,ratio='autot',bg=1,title="Phase composites of the first MSSA oscillation")
	x.postscript('crap')
	x.showbg()
Example #26
0
    def plot(self, data, template=None, bg=0, x=None, **kwargs):
        if x is None:
            x = self.x
        if template is None:
            template = self.template
        elif isinstance(template, str):
            template = x.gettemplate(template)
        elif not vcs.istemplate(template):  # pragma: no cover
            raise ValueError("Error did not know what to do with template: %s" % template)  # pragma: no cover
        try:
            data_name = data.title
        except AttributeError:
            try:
                data_name = data.long_name
            except AttributeError:
                try:
                    data_name = data.id + data.units
                except AttributeError:
                    try:
                        data_name = data.id
                    except AttributeError:
                        data_name = "array"

        # We'll just flatten the data... if they want to be more precise, should pass in more precise data
        if isinstance(data, cdms2.avariable.AbstractVariable):
            data = data.asma()
        data = data.flatten()

        # ok now we have a good x and a good data
        if not self.bins:
            self.bins = vcs.utils.mkscale(*vcs.minmax(data))

        # Sort the bins
        self.bins.sort()

        # Prune duplicates
        pruned_bins = []
        for bin in self.bins:
            if pruned_bins and numpy.allclose(bin, pruned_bins[-1]):
                continue
            pruned_bins.append(bin)
        self.bins = pruned_bins
        data_bins = numpy.digitize(data, self.bins) - 1
        binned = [data[data_bins==i] for i in range(len(self.bins))]
        means = []
        stds = []

        max_possible_deviance = 0

        for ind, databin in enumerate(binned):
            if len(databin) > 0:
                means.append(databin.mean())
                stds.append(databin.std())
            else:
                means.append(0)
                stds.append(0)
            if len(self.bins) > ind + 1:
                max_possible_deviance = max(means[ind] - self.bins[ind], self.bins[ind + 1] - means[ind], max_possible_deviance)
            else:
                max_possible_deviance = max(means[ind] - self.bins[ind], max_possible_deviance)
        color_values = [std / max_possible_deviance for std in stds]
        y_values = [len(databin) for databin in binned]
        nbars = len(self.bins) - 1

        # create the primitive
        fill = x.createfillarea()
        line = x.createline()
        fill.viewport = [
            template.data.x1, template.data.x2, template.data.y1, template.data.y2]
        line.viewport = [
            template.data.x1, template.data.x2, template.data.y1, template.data.y2]

        vcs_min_max = vcs.minmax(self.bins)
        if numpy.allclose(self.datawc_x1, 1e20):
            xmn = vcs_min_max[0]
        else:
            xmn = self.datawc_x1

        if numpy.allclose(self.datawc_x2, 1e20):
            xmx = vcs_min_max[1]
        else:
            xmx = self.datawc_x2

        if numpy.allclose(self.datawc_y2, 1e20):
            # Make the y scale be slightly larger than the largest bar
            ymx = max(y_values) * 1.25
        else:
            ymx = self.datawc_y2

        if numpy.allclose(self.datawc_y1, 1e20):
            ymn = 0
        else:
            ymn = self.datawc_y1

        fill.worldcoordinate = [xmn, xmx, ymn, ymx]
        line.worldcoordinate = [xmn, xmx, ymn, ymx]

        styles = []
        cols = []
        indices = []
        lt = []
        lw = []
        lc = []
        xs = []
        ys = []

        levels = [.1 * i for i in range(11)]

        # Extend fillarea and line attrs to levels
        if self.fillareastyles:
            while len(self.fillareastyles) < (len(levels) - 1):
                self.fillareastyles.append(self.fillareastyles[-1])
        else:
            self.fillareastyles = ["solid"] * (len(levels) - 1)

        if self.fillareacolors:
            while len(self.fillareacolors) < (len(levels) - 1):
                self.fillareacolors.append(self.fillareacolors[-1])
        else:
            for lev in levels[:-1]:
                self.fillareacolors.append(int((self.color_2 - self.color_1) * lev) + self.color_1)

        if self.fillareaindices:
            while len(self.fillareaindices) < (len(levels) - 1):
                self.fillareaindices.append(self.fillareaindices[-1])
        else:
            self.fillareaindices = [1] * (len(levels) - 1)

        if self.line:
            while len(self.line) < (len(levels) - 1):
                self.line.append(self.line[-1])
        else:
            self.line = ["solid"] * (len(levels) - 1)

        if self.linewidth:
            while len(self.linewidth) < (len(levels) - 1):
                self.linewidth.append(self.linewidth[-1])
        else:
            self.linewidth = [1] * (len(levels) - 1)

        if self.linecolors:
            while len(self.linecolors) < (len(levels) - 1):
                self.linecolors.append(self.linecolors[-1])
        else:
            self.linecolors = ["black"] * (len(levels) - 1)

        for i in range(nbars):
            # Calculate level for bar
            value = color_values[i]
            for lev_ind in range(len(levels)):
                if levels[lev_ind] > value:
                    if lev_ind > 0:
                        lev_ind -= 1
                        break
                    else:
                        # Shouldn't ever get here since level 0 is 0
                        assert False  # pragma: no cover
            else:
                assert False  # pragma: no cover
            styles.append(self.fillareastyles[lev_ind])
            cols.append(self.fillareacolors[lev_ind])
            indices.append(self.fillareaindices[lev_ind])
            lt.append(self.line[lev_ind])
            lw.append(self.linewidth[lev_ind])
            lc.append(self.linecolors[lev_ind])

            xs.append([self.bins[i], self.bins[i], self.bins[i + 1], self.bins[i + 1]])
            ys.append([0, y_values[i], y_values[i], 0])

        fill.style = styles
        fill.x = xs
        fill.y = ys
        fill.style
        fill.index = indices
        fill.color = cols
        fill.colormap = self.colormap
        line.x = xs
        line.y = ys
        line.type = lt
        line.width = lw
        line.color = lc
        displays = []

        x_axis = cdms2.createAxis(self.bins, id=data_name)
        y_axis = cdms2.createAxis(vcs.mkscale(ymn, ymx), id="bin_size")

        displays.append(x.plot(fill, bg=bg, render=False))
        arr = MV2.masked_array(y_values)
        arr.setAxis(0, x_axis)
        dsp = template.plot(x, arr, self, bg=bg, X=x_axis, Y=y_axis)
        for d in dsp:
            if d is not None:
                displays.append(d)
        legend_labels = {0: "No Variance",
                         .1: "",
                         .2: "",
                         .3: "",
                         .4: "",
                         .5: "",
                         .6: "",
                         .7: "",
                         .8: "",
                         .9: "",
                         1: "High Variance"}
        template.drawColorBar(self.fillareacolors, levels,
                              legend=legend_labels, x=x,
                              style=self.fillareastyles,
                              index=self.fillareaindices)

        displays.append(x.plot(line, bg=bg))

        x.worldcoordinate = fill.worldcoordinate

        self.restore()
        return displays
import vcs

assert vcs.mkscale(3.5,3.5,16)==[3.5,]
Example #28
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 #29
0
def createTemplateandGM(x,
                        min,
                        max,
                        deltaisof=None,
                        deltaisol=None,
                        days_line=(
                            30,
                            6,
                            3,
                            2,
                        ),
                        ntemplate=1,
                        orientation='landscape'):

    # x.scriptrun('resol_24.scr')
    # x.setcolormap('cmap')
    dot = x.createline()
    dot.type = 'dot'
    if orientation[0].lower() == 'p':
        x.portrait()
    tmpl = x.createtemplate()

    # Turns off everything
    for a in dir(tmpl):
        try:
            setattr(getattr(tmpl, a), 'priority', 0)
        except BaseException:
            pass

    # Turns on what we want
    tmpl.data.priority = 1
    tmpl.box1.priority = 1
    tmpl.legend.priority = 1
    tmpl.xlabel1.priority = 1
    tmpl.xlabel2.priority = 1
    tmpl.ylabel1.priority = 2
    tmpl.ylabel2.priority = 2
    tmpl.xtic1.priority = 2
    tmpl.xtic2.priority = 2
    tmpl.ytic1.priority = 2
    tmpl.ytic2.priority = 2
    tmpl.xname.priority = 1
    tmpl.yname.priority = 1
    tmpl.dataname.priority = 1

    if ntemplate == 2:
        tmpl.reset('x', .06, .44, tmpl.data.x1, tmpl.data.x2)
    else:
        tmpl.reset('x', .2, .9, tmpl.data.x1, tmpl.data.x2)
    tmpl.reset('y', .2, .9, tmpl.data.y1, tmpl.data.y2)
    tmpl.ytic2.x1 = tmpl.data.x1
    tmpl.ytic2.x2 = tmpl.data.x2
    tmpl.ytic2.line = dot

    to = x.createtextorientation()
    to.halign = 'center'
    tmpl.dataname.x = (tmpl.data.x1 + tmpl.data.x2) / 2.
    tmpl.dataname.y = tmpl.data.y2 + .03
    tmpl.dataname.textorientation = to

    tmpl.yname.x = tmpl.yname.x - .01
    tmpl.xname.y = tmpl.xname.y - .075

    tmpl.xtic2.y1 = tmpl.data.y1
    tmpl.xtic2.y2 = tmpl.data.y2
    tmpl.xtic2.line = dot
    tmpl.scalefont(.8)

    tmpl.legend.x1 = tmpl.data.x1 * 1.1
    tmpl.legend.x2 = tmpl.data.x2 * .985

    tmplnoleg = x.createtemplate(source=tmpl.name)
    tmplnoleg.legend.priority = 0
    isof = x.createisofill()
    if deltaisof is None:
        levs2 = vcs.mkscale(min, max)
    else:
        levs2 = list(numpy.arange(min, max, deltaisof))
        for i, v in enumerate(levs2):
            if numpy.allclose(v, 0.):
                levs2[i] = 0.
    if deltaisol is None:
        levs1a = vcs.mkscale(min, 0)
        levs1b = vcs.mkscale(0, max)
    else:
        levs1a = list(numpy.arange(min, 0, deltaisol))
        levs1b = list(numpy.arange(0, max, deltaisol))
    isof.levels = levs2
    colors = vcs.getcolors(levs2, colors=list(range(16, 40)), white="white")
    lbls = vcs.mklabels(levs2)
    isof.legend = lbls
    isof.fillareacolors = colors

    levs1a = list(numpy.arange(min, 0, deltaisol))
    levs1b = list(numpy.arange(0, max, deltaisol))

    isol1 = x.createisoline()
    isol1.level = levs1a
    isol1.label = 'y'
    isol1.linetypes = ['dot']
    isol2 = x.createisoline()
    isol2.level = levs1b
    isol2.label = 'y'

    tick2 = {}
    for i in days_line:
        tick2[1. / i] = str(i) + ' days'
    tick1 = {}
    for i in (0, ):
        tick1[i] = ' '

    for gm in [isof, isol1, isol2]:
        gm.datawc_x1 = -15
        gm.datawc_x2 = 15
        gm.datawc_y1 = 0.
        gm.datawc_y2 = .8
        gm.yticlabels2 = tick2
        gm.xticlabels2 = tick1

    return tmpl, tmplnoleg, isof, isol1, isol2
Example #30
0
reduced_labels.xticlabels1 = {0: "0", 60: "60E", 120: "120E", 180: "180W",
                              240: "120W", 300: "60W", 360: "0"}

# isofill will use the naive minmax approach
isofill = vcs.createisofill("minmax", "reduced")

# Extract the minimum and maximum levels of sphu
# This will extract the minimum and maximum values from
# all time slices, which may be an issue for your dataset.
# If you want to do an animation, it's a good appraoch.
# If you're just looking at a single time slice, you're better off
# using our automatic level generator.
minval, maxval = vcs.minmax(sphu)
# Automatically create levels based on a minimum and maximum value
# It will round to surround the min and max
isofill.levels = vcs.mkscale(minval, maxval)
# Automatically retrieve colors for the scale
isofill.fillareacolors = vcs.getcolors(isofill.levels)

# isofill2 uses curated levels
# I used the built-in levels, took a look at the visualization, and selected
# the band of values that took up the most space in the heatmap.
isofill2 = vcs.createisofill("manual", "reduced")
isofill2.levels = vcs.mkscale(.2 * 10 ** -5, .5 * 10 ** -5)
# Since there are values outside of the upper and lower bounds I provided,
# let's turn on extensions to allow those values to be accomodated for.
isofill2.ext_1 = True
isofill2.ext_2 = True
isofill2.fillareacolors = vcs.getcolors(isofill2.levels)

grid_dest=dummy.getGrid()
s.id="orig"
s_regrid2 = s.regrid(grid_dest,regridTool="regrid2")
s_regrid2.id="regrid2"
s_esmf_lin = s.regrid(grid_dest)
s_esmf_lin.id = "ESMF Linear"
s_esmf_con = s.regrid(grid_dest,regridTool="esmf",regridMethod="conservative")
s_esmf_lin.id = "ESMF Conservative"

x=regression.init()
t=x.createtemplate()
t.blank()
t.data.priority=1
t.legend.priority=1
t.dataname.priority=1
t.dataname.y=t.dataname.y*.95
M=EzTemplate.Multi(template=t,x=x,rows=2,columns=2)
gm=x.createboxfill()
levels= vcs.mkscale(*vcs.minmax(s))
cols = vcs.getcolors(levels)
gm.boxfill_type = "custom"
gm.fillareacolors = cols
gm.levels = levels
x.plot(s,M.get(),gm,bg=1)
x.plot(s_regrid2,M.get(),gm,bg=1)
x.plot(s_esmf_lin,M.get(),gm,bg=1)
x.plot(s_esmf_con,M.get(),gm,bg=1)

ret = regression.run(x, "esmf_issue_1125.png", png)
Example #32
0
def setTicksandLabels(gm,datawc_x1,datawc_x2,datawc_y1,datawc_y2,x=None,y=None):
    """ Sets the labels and ticks for a graphics method made in python
    Usage setTicksandLabels(gm,datawc_x1,datawc_x2,datawc_y1,datawc_y2,x=None,y=None)
    datawc are world coordinates
    
    """
    if isinstance(gm,vcs.taylor.Gtd):
        return
    # Now the template stuff
    # first create the dictionary to remember which ones are changed
    dic={}
    for i in ('xticlabels1','xmtics1','xticlabels2','xmtics2','yticlabels1','ymtics1','yticlabels2','ymtics2'):
        dic[i]=False
    #xticklabels1
    if gm.xticlabels1 is None or gm.xticlabels1=='*':
        if x=="longitude" and abs(datawc_x2-datawc_x1)>30:
          ticks="lon30"
        else:
          ticks=vcs.mkscale(datawc_x1,datawc_x2)
          ticks=prettifyAxisLabels(vcs.mklabels(ticks),x)
        ## for k in ticks.keys() : # make sure you're in the range
        ##     if k<numpy.minimum(datawc_x1,datawc_x2) or k>numpy.maximum(datawc_x2,datawc_x1):
        ##         del(ticks[k])
        setattr(gm,'xticlabels1',ticks)
        dic['xticlabels1']=True
    #xmtics1
    if gm.xmtics1 is None or gm.xmtics1=='*':
        ticks=vcs.mkscale(datawc_x1,datawc_x2)
        tick2=[]
        for i in range(len(ticks)-1):
            tick2.append((ticks[i]+ticks[i+1])/2.)
        ticks=prettifyAxisLabels(vcs.mklabels(tick2),x)
        ## for k in ticks.keys() : # make sure you're in the range
        ##     if k<numpy.minimum(datawc_x1,datawc_x2) or k>numpy.maximum(datawc_x2,datawc_x1):
        ##         del(ticks[k])
        setattr(gm,'xmtics1',ticks)
        dic['xmtics1']=True
    #xticklabels2
    if  hasattr(gm,"xticlabels2") and (gm.xticlabels2 is None or gm.xticlabels2=='*'):
        ticks=vcs.mkscale(datawc_x1,datawc_x2)
        ticks=prettifyAxisLabels(vcs.mklabels(ticks),x)
        ## for k in ticks.keys():
        ##     ticks[k]=''
        ##     if k<numpy.minimum(datawc_x1,datawc_x2) or k>numpy.maximum(datawc_x2,datawc_x1):
        ##         del(ticks[k])
        setattr(gm,'xticlabels2',ticks)
        dic['xticlabels2']=True
    #xmtics2
    if hasattr(gm,"xmtics2") and (gm.xmtics2 is None or gm.xmtics2=='*'):
        ticks=vcs.mkscale(datawc_x1,datawc_x2)
        tick2=[]
        for i in range(len(ticks)-1):
            tick2.append((ticks[i]+ticks[i+1])/2.)
        ticks=prettifyAxisLabels(vcs.mklabels(tick2),x)
        ## for k in ticks.keys() : # make sure you're in the range
        ##     if k<numpy.minimum(datawc_x1,datawc_x2) or k>numpy.maximum(datawc_x2,datawc_x1):
        ##         del(ticks[k])
        setattr(gm,'xmtics2',ticks)
        dic['xmtics2']=True
    #yticklabels1
    if gm.yticlabels1 is None or gm.yticlabels1=='*':
        if y=="latitude" and abs(datawc_y2-datawc_y1)>20:
          ticks="lat20"
        else:
          ticks=vcs.mkscale(datawc_y1,datawc_y2)
          ticks=prettifyAxisLabels(vcs.mklabels(ticks),y)
        ## for k in ticks.keys() : # make sure you're in the range
        ##     if k<numpy.minimum(datawc_y1,datawc_y2) or k>numpy.maximum(datawc_y2,datawc_y1):
        ##         del(ticks[k])
        setattr(gm,'yticlabels1',ticks)
        dic['yticlabels1']=True
    #ymtics1
    if gm.ymtics1 is None or gm.ymtics1=='*':
        ticks=vcs.mkscale(datawc_y1,datawc_y2)
        tick2=[]
        for i in range(len(ticks)-1):
            tick2.append((ticks[i]+ticks[i+1])/2.)
        ticks=prettifyAxisLabels(vcs.mklabels(tick2),y)
        ## for k in ticks.keys() : # make sure you're in the range
        ##     if k<numpy.minimum(datawc_y1,datawc_y2) or k>numpy.maximum(datawc_y2,datawc_y1):
        ##         del(ticks[k])
        setattr(gm,'ymtics1',ticks)
        dic['ymtics1']=True
    #yticklabels2
    if hasattr(gm,"yticlabels2") and (gm.yticlabels2 is None or gm.yticlabels2=='*'):
        ticks=vcs.mkscale(datawc_y1,datawc_y2)
        ticks=prettifyAxisLabels(vcs.mklabels(ticks),y)
        ## for k in ticks.keys():
        ##     ticks[k]=''
        ##     if k<numpy.minimum(datawc_y1,datawc_y2) or k>numpy.maximum(datawc_y2,datawc_y1):
        ##         del(ticks[k])
        setattr(gm,'yticlabels2',ticks)
        dic['yticlabels2']=True
    #ymtics2
    if hasattr(gm,"ymtics2") and (gm.ymtics2 is None or gm.ymtics2=='*'):
        ticks=vcs.mkscale(datawc_y1,datawc_y2)
        tick2=[]
        for i in range(len(ticks)-1):
            tick2.append((ticks[i]+ticks[i+1])/2.)
        ticks=prettifyAxisLabels(vcs.mklabels(tick2),y)
        ## for k in ticks.keys() : # make sure you're in the range
        ##     if k<numpy.minimum(datawc_y1,datawc_y2) or k>numpy.maximum(datawc_y2,datawc_y1):
        ##         del(ticks[k])
        setattr(gm,'ymtics2',ticks)
        dic['ymtics2']=True
    return dic
Example #33
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 #34
0
    def plot(self, data=None, mesh=None, template=None,
             meshfill=None, x=None, bg=0, multiple=1.1):
        self.bg = bg
        # Create the vcs canvas
        if x is not None:
            self.x = x

        # Continents bug
        # x.setcontinentstype(0)
        # gets the thing to plot !
        if data is None:
            data = self.get()

        # Do we use a predefined template ?
        if template is None:
            template = self.generateTemplate()
        else:
            if isinstance(template, vcs.template.P):
                tid = template.name
            elif isinstance(template, str):
                tid = template
            else:
                raise 'Error cannot understand what you mean by template=' + \
                    str(template)

            template = vcs.createtemplate(source=tid)

        # Do we use a predefined meshfill ?
        if meshfill is None:
            mtics = {}
            for i in range(100):
                mtics[i - .5] = ''
            meshfill = vcs.createmeshfill()
            meshfill.xticlabels1 = eval(data.getAxis(1).names)
            meshfill.yticlabels1 = eval(data.getAxis(0).names)

            meshfill.datawc_x1 = -.5
            meshfill.datawc_x2 = data.shape[1] - .5
            meshfill.datawc_y1 = -.5
            meshfill.datawc_y2 = data.shape[0] - .5
            meshfill.mesh = self.PLOT_SETTINGS.draw_mesh
            meshfill.missing = self.PLOT_SETTINGS.missing_color
            meshfill.xticlabels2 = mtics
            meshfill.yticlabels2 = mtics
            if self.PLOT_SETTINGS.colormap is None:
                self.set_colormap()
            elif self.x.getcolormapname() != self.PLOT_SETTINGS.colormap:
                self.x.setcolormap(self.PLOT_SETTINGS.colormap)

            if self.PLOT_SETTINGS.levels is None:
                min, max = vcs.minmax(data)
                if max != 0:
                    max = max + .000001
                levs = vcs.mkscale(min, max)
            else:
                levs = self.PLOT_SETTINGS.levels

            if len(levs) > 1:
                meshfill.levels = levs
                if self.PLOT_SETTINGS.fillareacolors is None:
                    if self.PLOT_SETTINGS.colormap is None:
                        # Default colormap only use range 16->40
                        cols = vcs.getcolors(levs, list(range(16, 40)), split=1)
                    else:
                        cols = vcs.getcolors(levs, split=1)
                    meshfill.fillareacolors = cols
                else:
                    meshfill.fillareacolors = self.PLOT_SETTINGS.fillareacolors

            # Now creates the mesh associated
            n = int(multiple)
            ntot = int((multiple - n) * 10 + .1)
            sh = list(data.shape)
            sh.append(2)
            Indx = MV2.indices((sh[0], sh[1]))
            Y = Indx[0]
            X = Indx[1]

            if ntot == 1:
                sh.append(4)
                M = MV2.zeros(sh)
                M[:, :, 0, 0] = Y - .5
                M[:, :, 1, 0] = X - .5
                M[:, :, 0, 1] = Y - .5
                M[:, :, 1, 1] = X + .5
                M[:, :, 0, 2] = Y + .5
                M[:, :, 1, 2] = X + .5
                M[:, :, 0, 3] = Y + .5
                M[:, :, 1, 3] = X - .5
                M = MV2.reshape(M, (sh[0] * sh[1], 2, 4))
            elif ntot == 2:
                sh.append(3)
                M = MV2.zeros(sh)
                M[:, :, 0, 0] = Y - .5
                M[:, :, 1, 0] = X - .5
                M[:, :, 0, 1] = Y + .5 - (n - 1)
                M[:, :, 1, 1] = X - 0.5 + (n - 1)
                M[:, :, 0, 2] = Y + .5
                M[:, :, 1, 2] = X + .5
                M = MV2.reshape(M, (sh[0] * sh[1], 2, 3))
            elif ntot == 3:
                design = int((multiple - n) * 100 + .1)
                if design == 33:
                    sh.append(3)
                    M = MV2.zeros(sh)
                    if n == 1:
                        M[:, :, 0, 0] = Y - .5
                        M[:, :, 1, 0] = X - .5
                        M[:, :, 0, 1] = Y + .5
                        M[:, :, 1, 1] = X
                        M[:, :, 0, 2] = Y + .5
                        M[:, :, 1, 2] = X - .5
                    elif n == 2:
                        M[:, :, 0, 0] = Y - .5
                        M[:, :, 1, 0] = X - .5
                        M[:, :, 0, 1] = Y + .5
                        M[:, :, 1, 1] = X
                        M[:, :, 0, 2] = Y - .5
                        M[:, :, 1, 2] = X + .5
                    elif n == 3:
                        M[:, :, 0, 0] = Y + .5
                        M[:, :, 1, 0] = X + .5
                        M[:, :, 0, 1] = Y + .5
                        M[:, :, 1, 1] = X
                        M[:, :, 0, 2] = Y - .5
                        M[:, :, 1, 2] = X + .5
                    M = MV2.reshape(M, (sh[0] * sh[1], 2, 3))
                elif design == 32:
                    sh.append(5)
                    M = MV2.zeros(sh)
                    M[:, :, 0, 0] = Y
                    M[:, :, 1, 0] = X
                    d = .5 / MV2.sqrt(3.)
                    if n == 1:
                        M[:, :, 0, 1] = Y + .5
                        M[:, :, 1, 1] = X
                        M[:, :, 0, 2] = Y + .5
                        M[:, :, 1, 2] = X - .5
                        M[:, :, 0, 3] = Y - d
                        M[:, :, 1, 3] = X - .5
                        # dummy point for n==1 or 3
                        M[:, :, 0, 4] = Y
                        M[:, :, 1, 4] = X
                    if n == 2:
                        M[:, :, 0, 1] = Y - d
                        M[:, :, 1, 1] = X - .5
                        M[:, :, 0, 2] = Y - .5
                        M[:, :, 1, 2] = X - .5
                        M[:, :, 0, 3] = Y - .5
                        M[:, :, 1, 3] = X + .5
                        M[:, :, 0, 4] = Y - d
                        M[:, :, 1, 4] = X + .5
                    elif n == 3:
                        M[:, :, 0, 1] = Y + .5
                        M[:, :, 1, 1] = X
                        M[:, :, 0, 2] = Y + .5
                        M[:, :, 1, 2] = X + .5
                        M[:, :, 0, 3] = Y - d
                        M[:, :, 1, 3] = X + .5
                        # dummy point for n==1 or 3
                        M[:, :, 0, 4] = Y
                        M[:, :, 1, 4] = X
                    M = MV2.reshape(M, (sh[0] * sh[1], 2, 5))
                else:
                    sh.append(5)
                    M = MV2.zeros(sh)
                    M[:, :, 0, 0] = Y
                    M[:, :, 1, 0] = X
                    d = 1. / 3.
                    if n == 1:
                        M[:, :, 0, 1] = Y + .5
                        M[:, :, 1, 1] = X
                        M[:, :, 0, 2] = Y + .5
                        M[:, :, 1, 2] = X - .5
                        M[:, :, 0, 3] = Y - d

                        M[:, :, 1, 3] = X - .5
                        # dummy point for n==1 or 3
                        M[:, :, 0, 4] = Y
                        M[:, :, 1, 4] = X
                    if n == 2:
                        M[:, :, 0, 1] = Y - d
                        M[:, :, 1, 1] = X - .5
                        M[:, :, 0, 2] = Y - .5
                        M[:, :, 1, 2] = X - .5
                        M[:, :, 0, 3] = Y - .5
                        M[:, :, 1, 3] = X + .5
                        M[:, :, 0, 4] = Y - d
                        M[:, :, 1, 4] = X + .5
                    elif n == 3:
                        M[:, :, 0, 1] = Y + .5
                        M[:, :, 1, 1] = X
                        M[:, :, 0, 2] = Y + .5
                        M[:, :, 1, 2] = X + .5
                        M[:, :, 0, 3] = Y - d
                        M[:, :, 1, 3] = X + .5
                        # dummy point for n==1 or 3
                        M[:, :, 0, 4] = Y
                        M[:, :, 1, 4] = X
                    M = MV2.reshape(M, (sh[0] * sh[1], 2, 5))
            elif ntot == 4:
                sh.append(3)
                M = MV2.zeros(sh)
                M[:, :, 0, 0] = Y
                M[:, :, 1, 0] = X
                if n == 1:
                    M[:, :, 0, 1] = Y + .5
                    M[:, :, 1, 1] = X + .5
                    M[:, :, 0, 2] = Y + .5
                    M[:, :, 1, 2] = X - .5
                elif n == 2:
                    M[:, :, 0, 1] = Y + .5
                    M[:, :, 1, 1] = X - .5
                    M[:, :, 0, 2] = Y - .5
                    M[:, :, 1, 2] = X - .5
                elif n == 3:
                    M[:, :, 0, 1] = Y - .5
                    M[:, :, 1, 1] = X - .5
                    M[:, :, 0, 2] = Y - .5
                    M[:, :, 1, 2] = X + .5
                elif n == 4:
                    M[:, :, 0, 1] = Y - .5
                    M[:, :, 1, 1] = X + .5
                    M[:, :, 0, 2] = Y + .5
                    M[:, :, 1, 2] = X + .5
                M = MV2.reshape(M, (sh[0] * sh[1], 2, 3))
        else:
            if isinstance(meshfill, vcs.meshfill.P):
                tid = mesh.id
            elif isinstance(meshfill, str):
                tid = mesh
            else:
                raise 'Error cannot understand what you mean by meshfill=' + \
                    str(meshfill)
            meshfill = vcs.createmeshfill(source=tid)

        if mesh is None:
            mesh = M

        raveled = MV2.ravel(data)
        self.x.plot(raveled, mesh, template, meshfill, bg=self.bg)

        # If required plot values
        if self.PLOT_SETTINGS.values.show:
            self.draw_values(raveled, mesh, meshfill, template)

        # Now prints the rest of the title, etc...
        # but only if n==1
        if n == 1:
            axes_param = []
            for a in data.getAxis(0).id.split('___'):
                axes_param.append(a)
            for a in data.getAxis(1).id.split('___'):
                axes_param.append(a)
            nparam = 0
            for p in self.parameters_list:
                if p not in self.dummies and \
                        p not in self.auto_dummies and \
                        p not in axes_param:
                    nparam += 1

            if self.verbose:
                print('NPARAM:', nparam)
            if nparam > 0:
                for i in range(nparam):
                    j = MV2.ceil(float(nparam) / (i + 1.))
                    if j <= i:
                        break
                npc = i  # number of lines
                npl = int(j)  # number of coulmns
                if npc * npl < nparam:
                    npl += 1
                # computes space between each line
                dl = (.95 - template.data.y2) / npl
                dc = .9 / npc
                npci = 0  # counter for columns
                npli = 0  # counter for lines
                for p in self.parameters_list:
                    if p not in self.dummies and \
                            p not in self.auto_dummies and \
                            p not in axes_param:
                        txt = self.x.createtext(
                            None,
                            self.PLOT_SETTINGS.parametertable.name,
                            None,
                            self.PLOT_SETTINGS.parameterorientation.name)
                        value = getattr(self, p)
                        if (isinstance(value, (list, tuple)) and
                                len(value) == 1):
                            txt.string = p + ':' + \
                                str(self.makestring(p, value[0]))
                            display = 1
                        elif isinstance(value, (str, int, float)):
                            txt.string = p + ':' + \
                                str(self.makestring(p, value))
                            display = 1
                        else:
                            display = 0

                        if display:
                            # Now figures out where to put these...
                            txt.x = [(npci) * dc + dc / 2. + .05]
                            txt.y = [1. - (npli) * dl - dl / 2.]
                            npci += 1
                            if npci >= npc:
                                npci = 0
                                npli += 1
                            if p in list(self.altered.keys()):
                                dic = self.altered[p]
                                if dic['size'] is not None:
                                    txt.size = dic['size']
                                if dic['color'] is not None:
                                    txt.color = dic['color']
                                if dic['x'] is not None:
                                    txt.x = dic['x']
                                if dic['y'] is not None:
                                    txt.y = dic['y']
                            self.x.plot(txt, bg=self.bg, continents=0)
            if self.PLOT_SETTINGS.time_stamp is not None:
                sp = time.ctime().split()
                sp = sp[:3] + [sp[-1]]
                self.PLOT_SETTINGS.time_stamp.string = ''.join(sp)
                self.x.plot(
                    self.PLOT_SETTINGS.time_stamp,
                    bg=self.bg,
                    continents=0)
            if self.PLOT_SETTINGS.logo is not None:
                self.PLOT_SETTINGS.logo.plot(self.x, bg=self.bg)
        return mesh, template, meshfill
if con == 1:
    # lets mask other than regions
    data = maskOutOfRegions(data, [region1, region2])
    status = 'Masked'
elif con == 2:
    # lets mask other than regions
    data = maskOutOfRegions(data, [region1, region2], fillvalue=0.4)
    status = 'Filled'
# end of if con == 1:

print "data after masked out of regions", data 

mindata = data.min() 
maxdata = data.max() 
levels = vcs.mkscale(mindata, maxdata, 10, zero=1)

myisofill = v.createisofill()
myisofill.levels = levels
myisofill.fillareacolors = vcs.getcolors(levels, split=0)

###
# make portrait in v object is essential to work perfectly in uv-cdat.
v.portrait()
gen = genTemplate()

dirname = 'outplots_maskOutOfRegions'
if not os.path.isdir(dirname): os.mkdir(dirname)

tit = "TRMM 3A25 v7 - Conv Mean Rain Rate "
cm = "2 Regions Demo - %s out of needed regions - [mm/hr]" % status
Example #36
0
  def plot2D(self,data1,data2,tmpl,gm,ren):
    self.setLayer(ren,tmpl.data.priority)
    ug,xm,xM,ym,yM,continents,wrap = vcs2vtk.genUnstructuredGrid(data1,data2,gm)
    #Now applies the actual data on each cell
    if isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="log10":
        data1=numpy.ma.log10(data1)
    data = VN.numpy_to_vtk(data1.filled(0.).flat,deep=True)
    if ug.IsA("vtkUnstructuredGrid"):
        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)
    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,boxfill.Gfb):
      geoFilter = vtk.vtkGeometryFilter()
      if ug.IsA("vtkUnstructuredGrid"):
        geoFilter.SetInputData(ug)
      else:
          p2c = vtk.vtkPointDataToCellData()
          p2c.SetInputData(ug)
          geoFilter = vtk.vtkDataSetSurfaceFilter()
          geoFilter.SetInputConnection(p2c.GetOutputPort())
      geoFilter.Update()

    if isinstance(gm,(isofill.Gfi,isoline.Gi,meshfill.Gfm)) or \
        (isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="custom"):
      
      if ug.IsA("vtkUnstructuredGrid"):
          # 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
          cln = vtk.vtkCleanUnstructuredGrid()
          cln.SetInputConnection(c2p.GetOutputPort())
          if self.debug:
            vcs2vtk.dump2VTK(cln)
      #Now this filter seems to create the good polydata
      sFilter = vtk.vtkDataSetSurfaceFilter()
      if ug.IsA("vtkUnstructuredGrid"):
        sFilter.SetInputConnection(cln.GetOutputPort())
      else:
        sFilter.SetInputData(ug)
      sFilter.Update()
      if self.debug:
        vcs2vtk.dump2VTK(sFilter)
      if isinstance(gm,isoline.Gi):
        cot = vtk.vtkContourFilter()
        if ug.IsA("vtkUnstructuredGrid"):
          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)
        Ncolors = len(levs)
        if isinstance(gm,(isofill.Gfi,meshfill.Gfm)):
          levs2 = vcs.mkscale(mn,mx)
          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):
        cols = gm.fillareacolors
        if cols==[1,]:
          cols = vcs.getcolors(levs2,split=0)
      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 = 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))
              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/Meshfill
      mappers=[]
      mapper.SetInputData(geoFilter.GetOutput())
      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)
          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":
              levs = vcs.mkscale(numpy.ma.log10(gm.level_1),numpy.ma.log10(gm.level_2))
          else:
              levs = vcs.mkscale(gm.level_1,gm.level_2)
          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])
          levs = numpy.arange(levs[0],levs[1],(levs[1]-levs[0])/(gm.color_2-gm.color_1+1))

        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


    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:
        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)
        #act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap)
        if isinstance(mapper,list):
          #act.GetMapper().ScalarVisibilityOff()
          #act.SetTexture(mapper[1])
          pass
        ren.AddActor(act)
        vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],[x1,x2,y1,y2])

    self.renderTemplate(ren,tmpl,data1,gm)
    if isinstance(gm,(isofill.Gfi,meshfill.Gfm,boxfill.Gfb)):
      if getattr(gm,"legend",None) is not None:
        legend = gm.legend
      self.renderColorBar(ren,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,ren,tmpl)
import vcs,numpy

assert numpy.allclose(vcs.mkscale(0,1.e35,16) , [0.0, 9.9999999999999995e+33, 1.9999999999999999e+34, 2.9999999999999997e+34, 3.9999999999999998e+34, 4.9999999999999998e+34, 5.9999999999999994e+34, 7e+34, 7.9999999999999996e+34, 9.0000000000000001e+34, 9.9999999999999997e+34])
    levs = levels(var, partition_count=10)

    stat_iso = vcs.createisofill()
    int_levs = []
    for l in levs:
        int_levs.append(int(l))
    stat_iso.levels = int_levs
    stat_iso.ext_2 = True
    stat_iso.ext_1 = True
    stat_iso.missing = 1
    stat_iso.fillareacolors = vcs.getcolors(stat_iso.levels, split=0)
    
    iso = vcs.createisofill()
    v_min, v_max = vcs.minmax(var[0])
    scale = vcs.mkscale(v_min, v_max)
    iso.levels = scale
    iso.ext_2 = True
    iso.ext_1 = True
    iso.missing = 1
    iso.fillareacolors = vcs.getcolors(iso.levels, split=0)

    flat = var.flatten().data
    stats_variance, stats_binned = calculate_variance(levs, flat)
    auto_variance, auto_binned = calculate_variance(scale, flat)
    stats_counts = []
    auto_counts = []
    for index in range(len(levs)):
        stat_var = stats_variance[index]
        auto_var = auto_variance[index]
        stats_vals = flat[stats_binned == index]
Example #39
0
    def plot(self,data=None,mesh=None,template=None,meshfill=None,x=None,bg=0,multiple=1.1):
        # Create the vcs canvas
        if x is None:
            x=vcs.init()

        ## Continents bug
        x.setcontinentstype(0)
        # gets the thing to plot !
        if data is None:
            data=self.get()
        

        # Do we use a predefined template ?
        if template is None:
            template=x.createtemplate()
            # Now sets all the things for the template...
            # Sets a bunch of template attributes to off
            for att in [
                'line1','line2','line3','line4',
                'box2','box3','box4',
                'min','max','mean',
                'xtic1','xtic2',
                'ytic1','ytic2',
                'xvalue','yvalue','zvalue','tvalue',
                'xunits','yunits','zunits','tunits',
                'source','title','dataname',
                ]:
                a=getattr(template,att)
                setattr(a,'priority',0)
            for att in [
                'xname','yname',
                ]:
                a=getattr(template,att)
                setattr(a,'priority',0)
            
            template.data.x1=self.PLOT_SETTINGS.x1
            template.data.x2=self.PLOT_SETTINGS.x2
            template.data.y1=self.PLOT_SETTINGS.y1
            template.data.y2=self.PLOT_SETTINGS.y2
            template.box1.x1=self.PLOT_SETTINGS.x1
            template.box1.x2=self.PLOT_SETTINGS.x2
            template.box1.y1=self.PLOT_SETTINGS.y1
            template.box1.y2=self.PLOT_SETTINGS.y2
            template.xname.y=self.PLOT_SETTINGS.y2+.02
            template.yname.x=self.PLOT_SETTINGS.x2+.01
            template.xlabel1.y=self.PLOT_SETTINGS.y1
            template.xlabel2.y=self.PLOT_SETTINGS.y2
            template.xlabel1.texttable=self.PLOT_SETTINGS.tictable
            template.xlabel2.texttable=self.PLOT_SETTINGS.tictable
            template.xlabel1.textorientation=self.PLOT_SETTINGS.xticorientation
            template.xlabel2.textorientation=self.PLOT_SETTINGS.xticorientation
            template.ylabel1.x=self.PLOT_SETTINGS.x1
            template.ylabel2.x=self.PLOT_SETTINGS.x2
            template.ylabel1.texttable=self.PLOT_SETTINGS.tictable
            template.ylabel2.texttable=self.PLOT_SETTINGS.tictable
            template.ylabel1.textorientation=self.PLOT_SETTINGS.yticorientation
            template.ylabel2.textorientation=self.PLOT_SETTINGS.yticorientation
            
            if self.PLOT_SETTINGS.xtic1y1 is not None:
                template.xtic1.y1=self.PLOT_SETTINGS.xtic1y1
                template.xtic1.priority=1
            if self.PLOT_SETTINGS.xtic1y2 is not None:
                template.xtic1.y2=self.PLOT_SETTINGS.xtic1y2
                template.xtic1.priority=1
            if self.PLOT_SETTINGS.xtic2y1 is not None:
                template.xtic2.y1=self.PLOT_SETTINGS.xtic2y1
                template.xtic2.priority=1
            if self.PLOT_SETTINGS.xtic2y2 is not None:
                template.xtic2.y2=self.PLOT_SETTINGS.xtic2y2
                template.xtic2.priority=1
            if self.PLOT_SETTINGS.ytic1x1 is not None:
                template.ytic1.x1=self.PLOT_SETTINGS.ytic1x1
                template.ytic1.priority=1
            if self.PLOT_SETTINGS.ytic1x2 is not None:
                template.ytic1.x2=self.PLOT_SETTINGS.ytic1x2
                template.ytic1.priority=1
            if self.PLOT_SETTINGS.ytic2x1 is not None:
                template.ytic2.priority=1
                template.ytic2.x1=self.PLOT_SETTINGS.ytic2x1
            if self.PLOT_SETTINGS.ytic2x2 is not None:
                template.ytic2.priority=1
                template.ytic2.x2=self.PLOT_SETTINGS.ytic2x2
            template.legend.x1=self.PLOT_SETTINGS.legend_x1
            template.legend.x2=self.PLOT_SETTINGS.legend_x2
            template.legend.y1=self.PLOT_SETTINGS.legend_y1
            template.legend.y2=self.PLOT_SETTINGS.legend_y2
            try:
             tmp = x.createtextorientation('crap22')
            except:
              tmp = x.gettextorientation('crap22')
            tmp.height = 12
            #tmp.halign = 'center' 
#           template.legend.texttable = tmp
            template.legend.textorientation = tmp
 
        else:
            if isinstance(template,vcs.template.P):
                tid=template.name
            elif isinstance(template,str):
                tid=template
            else:
                raise 'Error cannot understand what you mean by template='+str(template)
        
            template=x.createtemplate()

        # Do we use a predefined meshfill ?
        if meshfill is None:
            mtics={}
            for i in range(100):
                mtics[i-.5]=''
            icont = 1
            meshfill=x.createmeshfill()
            meshfill.xticlabels1=eval(data.getAxis(1).names)
            meshfill.yticlabels1=eval(data.getAxis(0).names)
            
            meshfill.datawc_x1=-.5
            meshfill.datawc_x2=data.shape[1]-.5
            meshfill.datawc_y1=-.5
            meshfill.datawc_y2=data.shape[0]-.5
            meshfill.mesh=self.PLOT_SETTINGS.draw_mesh
            meshfill.missing=self.PLOT_SETTINGS.missing_color
            meshfill.xticlabels2=mtics
            meshfill.yticlabels2=mtics
            if self.PLOT_SETTINGS.colormap is None:
                self.set_colormap(x)
            elif x.getcolormapname()!=self.PLOT_SETTINGS.colormap:
                x.setcolormap(self.PLOT_SETTINGS.colormap)
            
            if self.PLOT_SETTINGS.levels is None:
                min,max=vcs.minmax(data)
                if max!=0: max=max+.000001
                levs=vcs.mkscale(min,max)
            else:
                levs=self.PLOT_SETTINGS.levels

            if len(levs)>1:
                meshfill.levels=levs
                if self.PLOT_SETTINGS.fillareacolors is None:
                    cols=vcs.getcolors(levs,range(16,40),split=1)
                    meshfill.fillareacolors=cols
                else:
                    meshfill.fillareacolors=self.PLOT_SETTINGS.fillareacolors
            
##             self.setmeshfill(x,meshfill,levs)
##             if self.PLOT_SETTINGS.legend is None:
##                 meshfill.legend=vcs.mklabels(levs)
##             else:
##                 meshfill.legend=self.PLOT_SETTINGS.legend
            # Now creates the mesh associated
            n=int(multiple)
            ntot=int((multiple-n)*10+.1)
##             data=data
            sh=list(data.shape)
            sh.append(2)
            I=MV2.indices((sh[0],sh[1]))
            Y=I[0]
            X=I[1]
##             if ntot>1:
##                 meshfill.mesh='y'
            if ntot == 1:
                sh.append(4)
                M=MV2.zeros(sh)
                M[:,:,0,0]=Y-.5
                M[:,:,1,0]=X-.5
                M[:,:,0,1]=Y-.5
                M[:,:,1,1]=X+.5
                M[:,:,0,2]=Y+.5
                M[:,:,1,2]=X+.5
                M[:,:,0,3]=Y+.5
                M[:,:,1,3]=X-.5
                M=MV2.reshape(M,(sh[0]*sh[1],2,4))
            elif ntot==2:
                sh.append(3)
                M=MV2.zeros(sh)
                M[:,:,0,0]=Y-.5
                M[:,:,1,0]=X-.5
                M[:,:,0,1]=Y+.5-(n-1)
                M[:,:,1,1]=X-0.5+(n-1)
                M[:,:,0,2]=Y+.5
                M[:,:,1,2]=X+.5
                M=MV2.reshape(M,(sh[0]*sh[1],2,3))
            elif ntot==3:
                design=int((multiple-n)*100+.1)
                if design==33:
                    sh.append(3)
                    M=MV2.zeros(sh)
                    if n==1:
                        M[:,:,0,0]=Y-.5
                        M[:,:,1,0]=X-.5
                        M[:,:,0,1]=Y+.5
                        M[:,:,1,1]=X
                        M[:,:,0,2]=Y+.5
                        M[:,:,1,2]=X-.5
                    elif n==2:
                        M[:,:,0,0]=Y-.5
                        M[:,:,1,0]=X-.5
                        M[:,:,0,1]=Y+.5
                        M[:,:,1,1]=X
                        M[:,:,0,2]=Y-.5
                        M[:,:,1,2]=X+.5
                    elif n==3:
                        M[:,:,0,0]=Y+.5
                        M[:,:,1,0]=X+.5
                        M[:,:,0,1]=Y+.5
                        M[:,:,1,1]=X
                        M[:,:,0,2]=Y-.5
                        M[:,:,1,2]=X+.5
                    M=MV2.reshape(M,(sh[0]*sh[1],2,3))
                elif design==32:
                    sh.append(5)
                    M=MV2.zeros(sh)
                    M[:,:,0,0]=Y
                    M[:,:,1,0]=X
                    d=.5/MV2.sqrt(3.)
                    if n==1:
                        M[:,:,0,1]=Y+.5
                        M[:,:,1,1]=X
                        M[:,:,0,2]=Y+.5
                        M[:,:,1,2]=X-.5
                        M[:,:,0,3]=Y-d
                        M[:,:,1,3]=X-.5
                        # dummy point for n==1 or 3
                        M[:,:,0,4]=Y
                        M[:,:,1,4]=X
                    if n==2:
                        M[:,:,0,1]=Y-d
                        M[:,:,1,1]=X-.5
                        M[:,:,0,2]=Y-.5
                        M[:,:,1,2]=X-.5
                        M[:,:,0,3]=Y-.5
                        M[:,:,1,3]=X+.5
                        M[:,:,0,4]=Y-d
                        M[:,:,1,4]=X+.5
                    elif n==3:
                        M[:,:,0,1]=Y+.5
                        M[:,:,1,1]=X
                        M[:,:,0,2]=Y+.5
                        M[:,:,1,2]=X+.5
                        M[:,:,0,3]=Y-d
                        M[:,:,1,3]=X+.5
                        # dummy point for n==1 or 3
                        M[:,:,0,4]=Y
                        M[:,:,1,4]=X
                    M=MV2.reshape(M,(sh[0]*sh[1],2,5))
                else:
                    sh.append(5)
                    M=MV2.zeros(sh)
                    M[:,:,0,0]=Y
                    M[:,:,1,0]=X
                    d=1./3.
                    if n==1:
                        M[:,:,0,1]=Y+.5
                        M[:,:,1,1]=X
                        M[:,:,0,2]=Y+.5
                        M[:,:,1,2]=X-.5
                        M[:,:,0,3]=Y-d
                        
                        M[:,:,1,3]=X-.5
                        # dummy point for n==1 or 3
                        M[:,:,0,4]=Y
                        M[:,:,1,4]=X
                    if n==2:
                        M[:,:,0,1]=Y-d
                        M[:,:,1,1]=X-.5
                        M[:,:,0,2]=Y-.5
                        M[:,:,1,2]=X-.5
                        M[:,:,0,3]=Y-.5
                        M[:,:,1,3]=X+.5
                        M[:,:,0,4]=Y-d
                        M[:,:,1,4]=X+.5
                    elif n==3:
                        M[:,:,0,1]=Y+.5
                        M[:,:,1,1]=X
                        M[:,:,0,2]=Y+.5
                        M[:,:,1,2]=X+.5
                        M[:,:,0,3]=Y-d
                        M[:,:,1,3]=X+.5
                        # dummy point for n==1 or 3
                        M[:,:,0,4]=Y
                        M[:,:,1,4]=X                        
                    M=MV2.reshape(M,(sh[0]*sh[1],2,5))
            elif ntot==4:
                sh.append(3)
                M=MV2.zeros(sh)
                M[:,:,0,0]=Y
                M[:,:,1,0]=X
                if n==1:
                    M[:,:,0,1]=Y+.5
                    M[:,:,1,1]=X+.5
                    M[:,:,0,2]=Y+.5
                    M[:,:,1,2]=X-.5
                elif n==2:
                    M[:,:,0,1]=Y+.5
                    M[:,:,1,1]=X-.5
                    M[:,:,0,2]=Y-.5
                    M[:,:,1,2]=X-.5
                elif n==3:
                    M[:,:,0,1]=Y-.5
                    M[:,:,1,1]=X-.5
                    M[:,:,0,2]=Y-.5
                    M[:,:,1,2]=X+.5
                elif n==4:
                    M[:,:,0,1]=Y-.5
                    M[:,:,1,1]=X+.5
                    M[:,:,0,2]=Y+.5
                    M[:,:,1,2]=X+.5
                M=MV2.reshape(M,(sh[0]*sh[1],2,3))
        else:
            if isinstance(meshfill,vcs.meshfill.P):
                tid=mesh.id
            elif isinstance(meshfill,str):
                tid=mesh
            else:
                raise 'Error cannot understand what you mean by meshfill='+str(meshfill)
            meshfill=x.createmeshfill()

        if mesh is None:
            x.plot(MV2.ravel(data),M,template,meshfill,bg=bg)
        else:
            x.plot(MV2.ravel(data),mesh,template,meshfill,bg=bg)
            

        # Now prints the rest of the title, etc...
        # but only if n==1
        if n==1:
            axes_param=[]
            for a in data.getAxis(0).id.split('___'):
                axes_param.append(a)
            for a in data.getAxis(1).id.split('___'):
                axes_param.append(a)
            nparam=0
            for p in self.parameters_list:
                if not p in self.dummies and not p in self.auto_dummies and not p in axes_param:
                    nparam+=1
                    
            if self.verbose: print 'NPARAM:',nparam
            if nparam>0:
                for i in range(nparam):
                    j=MV2.ceil(float(nparam)/(i+1.))
                    if j<=i:
                        break
                npc=i # number of lines
                npl=int(j) # number of coulmns
                if npc*npl<nparam :
                    npl+=1
                # computes space between each line
                dl=(.95-template.data.y2)/npl
                dc=.9/npc
                npci=0 # counter for columns
                npli=0 # counter for lines
                for p in self.parameters_list:
                    if not p in self.dummies and not p in self.auto_dummies and not p in axes_param:
                        txt=x.createtext(None,self.PLOT_SETTINGS.parametertable.name,None,self.PLOT_SETTINGS.parameterorientation.name)
                        value=getattr(self,p)
                        if (isinstance(value,(list,tuple)) and len(value)==1):
                            txt.string=p+':'+str(self.makestring(p,value[0]))
                            display=1
                        elif isinstance(value,(str,int,float,long)):
                            txt.string=p+':'+str(self.makestring(p,value))
                            display=1
                        else:
                            display=0

                        if display:
                            # Now figures out where to put these...
                            txt.x=[(npci)*dc+dc/2.+.05]
                            txt.y=[1.-(npli)*dl-dl/2.]
                            npci+=1
                            if npci>=npc:
                                npci=0
                                npli+=1
                            if p in self.altered.keys():
                                dic=self.altered[p]
                                if dic['size'] is not None:
                                    txt.size=dic['size']
                                if dic['color'] is not None:
                                    txt.color=dic['color']
                                if dic['x'] is not none:
                                    txt.x=dic['x']
                                if dic['y'] is not none:
                                    txt.y=dic['y']
                            x.plot(txt,bg=bg,continents=0)
            if not self.PLOT_SETTINGS.logo is None:
                x.plot(self.PLOT_SETTINGS.logo,bg=bg,continents=0)
            if not self.PLOT_SETTINGS.time_stamp is None:
                import time
                sp=time.ctime().split()
                sp=sp[:3]+[sp[-1]]
                self.PLOT_SETTINGS.time_stamp.string=''.join(sp)
                x.plot(self.PLOT_SETTINGS.time_stamp,bg=bg,continents=0)
tmpl.legend.priority = 1
tmpl.legend.x1 = tmpl.box2.x1 - .05
tmpl.legend.x2 = tmpl.box2.x2 + .05
tmpl.legend.y1 = .03
tmpl.legend.y2 = .055
tmpl.max.priority = 1

txt = x.createtext()
txt.height = 20
txt.valign = "half"
txt.halign = "center"

tmpl.title.textorientation = txt.To_name
tmpl.title.texttable = txt.Tt_name

ice.long_name = "September sea ice fraction: 4xCO2 climate, no ocean albedo alteration "
levs = vcs.mkscale(ice.min(), ice.max())

cols = vcs.getcolors(levs)
cols[0] = 'white'

gm.levels = levs
gm.fillareacolors = cols
#gm.projection="polar"
gm.datawc_y2 = 30
gm.datawc_y1 = 90

x.plot(ice, gm, tmpl, bg=1)
fnm = os.path.split(__file__)[1][:-3] + ".png"
regression.run(x, fnm)
Example #41
0
def tylorPlot(data, reference, name, path=None, colors=[], symbols=[], 
                maxvalue=None, legendstrings=[], lcolors=[], lsymbols=[],
                markersize=[], svg=1, png=0, 
                style='landscape', plotbg=0, legendpos='topright', rms='yes'):


    global x
    if not (x and isinstance(x, vcs.Canvas.Canvas)):
        # initializing vcs
        x = vcs.init()
        # auto update vcs
        x.mode = 1
        print "one time initializing of vcs obj x"
    x.clear()
    if style == 'portrait':
        x.portrait()
        # generate the template for tylor (customized)
        tytemp = tyTemplate(xscale = 1, yscale = 1, xmove = 0.0, ymove = 0.0)
    elif style == 'landscape':
        x.landscape()
        # generate the template for tylor (customized)    
        tytemp = tyTemplate(xscale = 1, yscale = 1, xmove = 0, ymove = 0.0, scalefont = 1.4) #ymove = -0.2, 
    else:
        raise ValueError("style must be either portrait or landscape")
    
    if not legendstrings:
        raise ValueError("pass legendstrings arg ")
    
    # find out either correlations have -ve value. If yes, then make the 
    # quadrans has 2 else 1.
    correlations = data.transpose()[1]
    mincorr = min(correlations) 
    
    if mincorr < 0:
        quadrans = 2
        legendpos = 'bottomcenter'
        # swtich off the left most labels, tic, mintics of std.
        tytemp.ylabel1.priority = 0
        tytemp.ytic1.priority = 0
        tytemp.ymintic1.priority = 0
    else:
        quadrans = 1
        legendpos = 'topright'
        # swtich on the left most labels, tic, mintics of std.
        tytemp.ylabel1.priority = 1
        tytemp.ytic1.priority = 1
        tytemp.ymintic1.priority = 1
    # generate/get the taylor template
    gentylor = genTaylor(reference, colors, symbols, maxvalue, quadrans)    
    # plot the data with taylot template with values.
    # Here we just passing the defaultSkillFunction method as skill argument,
    # to plot the rms error isolines.    
    
    if rms in ['yes', 'y', 1, True]:
        # Determine Centered-pattern RMS as skill score function
        # Make a specific data-type off reference std dev value
        reference = reference_std_dev(reference)

        # Compute max_RMS: RMS for point at top left diagram corner
        # where std_dev = scale and correlation = 0.
        max_RMS = reference.compute_RMS_function (maxvalue, 0.)

        # Determine the displayed levels for the skill score
        RMS_levels = vcs.mkscale (0., max_RMS)
        gentylor.skillValues = RMS_levels[1:] # do not include the leading value wich is 0.

        # Plot the diagram with Centered-pattern RMS as skill score
        x.plot (data, gentylor, tytemp, skill = reference.compute_RMS_function,
                 title = name,  bg = plotbg)
    else:
        # Plot the diagram
        x.plot (data, gentylor, tytemp, title = name,  bg = plotbg)
   
    ##
    # Additional (legend) plots
    ##
    
    # over write the colors & symbols if user passed legend marker symbols 
    # and/or legend marker colors.
    colors = lcolors if lcolors else colors
    symbols = lsymbols if lsymbols else symbols
    
    colors_count = len(colors)
    symbols_count = len(symbols) 
    
    # create the text template to add the legend strings   
    strcount = len(legendstrings)
    xgap = 0
    ygap = 0
    
    if legendpos == 'topright':
        strX = 0.8 
        strY = 0.8
        ygap = 0.03        
        # generate the Strings X axis positions.
        sX = [strX] * strcount
        # generate the Strings Y axis positions.
        sY = list(numpy.arange(strY, strY-(ygap * strcount), -ygap))
        #create the markers template to add the legend marker
        mX = [strX - 0.02] * strcount        
        mY = sY 
        # create the legend (rectangle) box at top right corner
        lx1 = 0.75 
        lx2 = 0.9 
        ly1 = 0.83
        # increase the legend height dynamically w.r.t no of strings in the legend 
        ly2 = ly1 - (ygap * strcount) - ygap
        
    elif legendpos == 'bottomcenter':
        strX = 0.3 
        strY = 0.08
        xgap = 0.1        
        
        if strcount <=6:
            # generate the Strings X axis positions.
            sX = list(numpy.arange(strX, strX+(xgap * strcount), xgap))
            # generate the Strings Y axis positions.            
            sY = [strY] * strcount
            #create the markers template to add the legend marker
            mX = [strX - 0.02] * strcount
            mY = sY
            # create the legend (rectangle) box at bottom center 
            ly1 = 0.11
            ly2 = 0.05 
            lx1 = 0.25
            # increase the legend width dynamically w.r.t no of strings in the legend 
            lx2 = lx1 + (xgap * strcount) + (xgap / 4)
            
        elif strcount <=12:
            # generate the Strings X axis positions. 
            # take only the first 6 x pos 
            sX = list(numpy.arange(strX, strX+(xgap * 6), xgap))[:6]            
            # repeate the from the 6 x pos 
            sX += sX[: strcount-6]            
            # generate the Strings Y axis positions.
            sY = [strY] * 6 + [strY - 0.03] * (strcount - 6)    
            #create the markers template to add the legend marker
            mX = list(numpy.array(sX) - 0.02)            
            mY = sY
            # create the legend (rectangle) box at bottom center 
            ly1 = 0.11
            ly2 = 0.03 
            lx1 = 0.25
            # increase the legend width dynamically w.r.t 6 strings in the legend 
            # i.e. 6 strings printed in first line, the remaning string will 
            # be in the second line of the legend
            lx2 = lx1 + (xgap * 6) + (xgap / 4)
            
        elif strcount <=16:
            # generate the Strings X axis positions. 
            # take only the first 8 x pos 
            strX = strX - 0.07
            sX = list(numpy.arange(strX, strX+(xgap * 8), xgap))[:8]            
            # repeate the from the 8 x pos 
            sX += sX[: strcount-8]            
            # generate the Strings Y axis positions.
            sY = [strY] * 8 + [strY - 0.03] * (strcount - 8)    
            #create the markers template to add the legend marker
            mX = list(numpy.array(sX) - 0.02)            
            mY = sY
            # create the legend (rectangle) box at bottom center 
            ly1 = 0.11
            ly2 = 0.03 
            lx1 = 0.18
            # increase the legend width dynamically w.r.t 8 strings in the legend 
            # i.e. 8 strings printed in first line, the remaning string will 
            # be in the second line of the legend
            lx2 = lx1 + (xgap * 8) + (xgap / 4)
            
    txt = x.createtext()
    txt.x = sX
    txt.y = sY
    txt.color = 241
    txt.string = legendstrings
    txt.height = 25
    txt.font = 1
    # plotting the strings 
    x.plot(txt, bg = plotbg)
    
   
    # default marker size. common for all the markers.
    defmarkersize = 5
         
    # plots the multiple markers with different attibutes inside legend box.
    if colors_count > symbols_count:
        # plot same color, different types of symbols 
        for color in colors:  
            msize = markersize.pop(0) if markersize else defmarkersize
            mx = mX.pop(0)
            my = mY.pop(0)
            _plotMarker(x, mx, my, symbols[0], color, round(msize))   
    elif colors_count < symbols_count:
        # plot different colors, same type of symbol
        for symbol in symbols:            
            msize = markersize.pop(0) if markersize else defmarkersize
            mx = mX.pop(0)
            my = mY.pop(0)
            _plotMarker(x, mx, my, symbol, colors[0], round(msize))            
    else:
        # colors_count == symbols_count:
        # plot different colors & different types of symbols 
        for color, symbol in zip(colors, symbols):            
            msize = markersize.pop(0) if markersize else defmarkersize 
            mx = mX.pop(0)
            my = mY.pop(0)                         
            _plotMarker(x, mx, my, symbol, color, round(msize))            
    
    
    ln = x.createline()
    ln.x = [lx1, lx2, lx2, lx1, lx1]       # x line positions
    ln.y = [ly1, ly1, ly2, ly2, ly1]       # y line positions
    ln.width = 3                      
    ln.color = 241 
    ln.type = 'solid' 
    # plot the legend                        
    x.plot(ln, bg = plotbg)
    
    ###
    ## End of plotting
    ###

    # save the plot 
    filename = name.replace(' ', '_')

    if not path:
        # get the current workig directory
        path = os.getcwd()
    if not os.path.isdir(path):
        raise RuntimeError("The passed path doesnot exists to store the \
                            vector plots")
    if not path.endswith('/'):
        path += '/'
    if svg:
        x.svg(path + filename + '.svg')
        print "plotted and saved the %s%s.svg" % (path, filename)
    if png:
        x.png(path + filename + '.png')
        print "plotted and saved the %s%s.png" % (path, filename)
    if not (svg or png):
        raise RuntimeError("Can not set both svg, png options are zero/None.\
                            Enable any one to store the vectorPlot")
    # clear the vcs object
    x.clear()
Example #42
0
print ' Open an HDF5 file, but this time using the OMI class, this is a particular type of HDF5/EOS files'
HDF = HDF5Tools.HDF5_OMI(path+fnm)
print 'We can now list the actual variables and their shape:'
vars = HDF.listvariables()
for v in vars:
    print 'Variable:',v,HDF.variables[v].shape,HDF.variables[v]._group
print 'And the dimensions ones that have been separated with "dimension_kw" keyword'
print 'display a var'
uva = HDF('UVAerosolIndex')
x=vcs.init()
m = x.createmeshfill('omi')
m.datawc_x1=-65
m.datawc_x2=-40
m.datawc_y1=-20
m.datawc_y2=10
sc = vcs.mkscale(-2,1)
sc.insert(0,-1.E20) # Extension on the left
sc.append(1.E20) # Extension on the right
colors = vcs.getcolors(sc)
m.levels = sc
m.fillareacolors = colors
x.plot(uva,m,ratio='autot')
raw_input('press enter')

print 'Ok now will read another var, w/o reading lat/lon'
print 'We will simply pass the grid to the read call'
salb = HDF('SurfaceAlbedo',grid=uva.getGrid())
print salb.shape
salb = salb[...,0]
print salb.shape
salb=salb(latitude=(-25,15),longitude=(-70,-30))