Example #1
0
    def __init__(self, variable, levels=None):
        super(LevelEditor, self).__init__()

        layout = QtGui.QVBoxLayout()
        self.set_title("%s Levels" % variable.id)
        self.variable = variable
        self._levels = levels

        self.level_label = QtGui.QLabel()

        def update_level_label(levels):
            self.level_label.setText(repr(levels))

        # Connect this to your object's signal
        def set_levels(levels):
            self.levels = levels

        minval, maxval = vcs.minmax(variable)
        if levels is None:
            levels = vcs.utils.mkscale(*vcs.minmax(self.variable))
        self.sliderWidget = SliderWidget.AdjustValues()
        self.sliderWidget.update(minval, maxval, levels)
        self.sliderWidget.valuesChanged.connect(set_levels)
        self.levelsChanged.connect(update_level_label)

        layout.addWidget(self.level_label)
        layout.addWidget(self.sliderWidget)
        self.setLayout(layout)
Example #2
0
 def numticks(self, num):
     if num > 0:
         # Interpolate between left and right num times
         left, right = vcs.minmax(self.axis)
         step = (right - left) / float(num)
         self.ticks = {left + n * step: left + n * step for n in range(num)}
     else:
         left, right = vcs.minmax(self.axis)
         step = (right - left) / float(num)
         self.ticks = {right + n * step: right + n * step for n in range(-1 * num)}
Example #3
0
 def numticks(self, num):
     if num > 0:
         # Interpolate between left and right num times
         left, right = vcs.minmax(self.axis)
         step = (right - left) / float(num)
         self.ticks = {left + n * step: left + n * step for n in range(num)}
     else:
         left, right = vcs.minmax(self.axis)
         step = (right - left) / float(num)
         self.ticks = {
             right + n * step: right + n * step
             for n in range(-1 * num)
         }
Example #4
0
    def test1DMany(self):

        d = numpy.sin(numpy.arange(100))
        d = numpy.reshape(d, (10, 10))

        one = self.x.create1d()

        print("glob min mac::", vcs.minmax(d))
        print("plt minmax: ", vcs.minmax(d[0]))
        self.x.plot(d, one, bg=self.bg)

        fnm = "test_vcs_1D_with_manyDs.png"
        self.checkImage(fnm)
Example #5
0
 def step(self):
     ticks = self.ticks
     if isinstance(ticks, str):
         ticks = vcs.elements["list"][ticks]
     ticks = sorted(ticks)
     left, right = vcs.minmax(self.axis)
     return (right - left) / len(ticks)
Example #6
0
 def step(self):
     ticks = self.ticks
     if isinstance(ticks, str):
         ticks = vcs.elements["list"][ticks]
     ticks = sorted(ticks)
     left, right = vcs.minmax(self.axis)
     return (right - left) / len(ticks)
Example #7
0
    def levels(self):
        if self._levels is None:
            if self.variable is not None:
                return vcs.utils.mkscale(*vcs.minmax(self.variable))
            else:
                self._levels = []

        return self._levels
Example #8
0
    def _plotInternalCustomBoxfill(self):
        """Implements the logic to render a custom boxfill."""
        self._mappers = []

        self._customBoxfillArgs = self._prepContours()
        tmpLevels = self._customBoxfillArgs["tmpLevels"]
        tmpColors = self._customBoxfillArgs["tmpColors"]
        tmpOpacities = self._customBoxfillArgs["tmpOpacities"]

        style = self._gm.fillareastyle

        luts = []
        geos = []
        wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1)
        _colorMap = self.getColorMap()
        for i, l in enumerate(tmpLevels):
            # Ok here we are trying to group together levels can be, a join
            # will happen if: next set of levels continues where one left off
            # AND pattern is identical

            # TODO this should really just be a single polydata/mapper/actor:
            for j, color in enumerate(tmpColors[i]):
                mapper = vtk.vtkPolyDataMapper()
                lut = vtk.vtkLookupTable()
                th = vtk.vtkThreshold()
                th.ThresholdBetween(l[j], l[j + 1])
                # th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
                th.SetInputData(self._vtkDataSetFittedToViewport)
                geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                geoFilter2.SetInputConnection(th.GetOutputPort())
                # Make the polydata output available here for patterning later
                geoFilter2.Update()
                geos.append(geoFilter2)
                mapper.SetInputConnection(geoFilter2.GetOutputPort())
                lut.SetNumberOfTableValues(1)
                r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color)
                if style == 'solid':
                    tmpOpacity = tmpOpacities[j]
                    if tmpOpacity is None:
                        tmpOpacity = a / 100.
                    else:
                        tmpOpacity = tmpOpacities[j] / 100.
                    lut.SetTableValue(0, r / 100., g / 100., b / 100.,
                                      tmpOpacity)
                else:
                    lut.SetTableValue(0, 1., 1., 1., 0.)
                mapper.SetLookupTable(lut)
                mapper.SetScalarRange(l[j], l[j + 1])
                luts.append([lut, [l[j], l[j + 1], False]])
                # Store the mapper only if it's worth it?
                # Need to do it with the whole slab min/max for animation
                # purposes
                if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax):
                    self._mappers.append(mapper)

        self._resultDict["vtk_backend_luts"] = luts
        if len(geos) > 0:
            self._resultDict["vtk_backend_geofilters"] = geos
Example #9
0
 def gm(self, value):
     self._gm = value
     self.orig_levs = value.levels
     if self.has_set_gm_levels() and self.var is not None:
         levs = self._gm.levels
         flat = self._var.flatten()
         var_min, var_max = vcs.minmax(flat)
         self.value_sliders.update(var_min, var_max, levs)
         self.update_levels(levs, clear=True)
Example #10
0
    def _plotInternalCustomBoxfill(self):
        """Implements the logic to render a custom boxfill."""
        self._mappers = []

        self._customBoxfillArgs = self._prepContours()
        tmpLevels = self._customBoxfillArgs["tmpLevels"]
        tmpColors = self._customBoxfillArgs["tmpColors"]
        tmpOpacities = self._customBoxfillArgs["tmpOpacities"]

        style = self._gm.fillareastyle

        luts = []
        geos = []
        wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1)
        _colorMap = self.getColorMap()
        assert(style != 'solid' or len(tmpLevels) == 1)
        for i, l in enumerate(tmpLevels):
            # Ok here we are trying to group together levels can be, a join
            # will happen if: next set of levels continues where one left off
            # AND pattern is identical

            # TODO this should really just be a single polydata/mapper/actor:
            for j, color in enumerate(tmpColors[i]):
                mapper = vtk.vtkPolyDataMapper()
                lut = vtk.vtkLookupTable()
                th = vtk.vtkThreshold()
                th.ThresholdBetween(l[j], l[j + 1])
                th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
                geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                geoFilter2.SetInputConnection(th.GetOutputPort())
                # Make the polydata output available here for patterning later
                geoFilter2.Update()
                geos.append(geoFilter2)
                mapper.SetInputConnection(geoFilter2.GetOutputPort())
                lut.SetNumberOfTableValues(1)
                r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color)
                if style == 'solid':
                    tmpOpacity = tmpOpacities[j]
                    if tmpOpacity is None:
                        tmpOpacity = a / 100.
                    else:
                        tmpOpacity = tmpOpacities[j] / 100.
                    lut.SetTableValue(0, r / 100., g / 100., b / 100., tmpOpacity)
                else:
                    lut.SetTableValue(0, 1., 1., 1., 0.)
                mapper.SetLookupTable(lut)
                mapper.SetScalarRange(l[j], l[j + 1])
                luts.append([lut, [l[j], l[j + 1], False]])
                # Store the mapper only if it's worth it?
                # Need to do it with the whole slab min/max for animation
                # purposes
                if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax):
                    self._mappers.append(mapper)

        self._resultDict["vtk_backend_luts"] = luts
        if len(geos) > 0:
            self._resultDict["vtk_backend_geofilters"] = geos
Example #11
0
 def gm(self, value):
     self._gm = value
     self.orig_levs = value.levels
     if self.has_set_gm_levels() and self.var is not None:
         levs = self._gm.levels
         flat = self._var.flatten()
         var_min, var_max = vcs.minmax(flat)
         self.value_sliders.update(var_min, var_max, levs)
         self.update_levels(levs, clear=True)
Example #12
0
    def plot(self, data1, data2, tmpl, grid, transform, **kargs):
        """Overrides baseclass implementation."""
        # Clear old results:
        self._resultDict = {}

        self._template = tmpl
        self._originalData1 = data1
        self._originalData2 = data2
        self._vtkDataSet = grid
        self._vtkGeoTransform = transform

        # Preprocess the input scalar data:
        self._updateScalarData()
        self._min = self._data1.min()
        self._max = self._data1.max()
        self._scalarRange = vcs.minmax(self._data1)

        # Create/update the VTK dataset.
        plotBasedDualGrid = kargs.get('plot_based_dual_grid', True)
        self._updateVTKDataSet(plotBasedDualGrid)

        if (self._needsVectors):
            vectors = self._vtkDataSet.GetPointData().GetVectors()
            vectors.GetRange(self._vectorRange, -1)

        # Update the results:
        self._resultDict["vtk_backend_grid"] = self._vtkDataSet
        self._resultDict["vtk_backend_geo"] = self._vtkGeoTransform
        self._resultDict["vtk_backend_wrap"] = self._dataWrapModulo
        self._resultDict["dataset_bounds"] = self._vtkDataSetBounds

        # Determine and format the contouring information:
        self._updateContourLevelsAndColors()

        # Create the polydata filter:
        self._vtkDataSetBoundsNoMask = self._vtkDataSet.GetBounds()

        # Generate a mapper to render masked data:
        self._createMaskedDataMapper()

        self._createPolyDataFilter()

        if (kargs.get('ratio', '0') == 'autot' and
                # atot is implemented for linear plots at vcs level
                # for geographic projections we implement it here.
                self._vtkGeoTransform):
            self._resultDict['ratio_autot_viewport'] = self._processRatioAutot(
                self._template, self._vtkDataSet)

        # Plot specific rendering:
        self._plotInternal()

        return self._resultDict
Example #13
0
def run_minmax(inpath, varname, i):

    mins = []
    maxs = []
    filedata = cdms2.open(inpath)
    vardata = filedata[varname]
    for step in range(vardata.shape[0]):
        stepdata = vardata[step]
        minmax = vcs.minmax(stepdata)
        mins.append(minmax[0])
        maxs.append(minmax[1])
    return mins, maxs, i
Example #14
0
def adjuster():
    cdmsfile = cdms2.open(vcs.sample_data + "/clt.nc")
    clt = cdmsfile("clt")
    min, max = vcs.minmax(clt)
    levels = vcs.utils.mkscale(*vcs.minmax(clt))
    print len(levels)

    edit = SliderWidget.AdjustValues()
    edit.update(min, max, levels)
    first = (edit, levels, min, max)

    edit = SliderWidget.AdjustValues()
    edit.update(min, max, levels)

    new_vals = [1, 2, 5, 8, 20, 45, 70, 155, 139]
    min = 0
    max = 200
    edit.update(min, max, new_vals)

    second = (edit, new_vals, min, max)

    return first, second
Example #15
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 #16
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 #17
0
    def var(self, value):
        self._var = value
        flat = self._var.flatten()
        var_min, var_max = vcs.minmax(flat)
        # Check if we're using auto levels
        if self._gm is None or not self.has_set_gm_levels():
            # Update the automatic levels with this variable
            levs = vcs.utils.mkscale(var_min, var_max)
        else:
            # Otherwise, just use what the levels are
            levs = self._gm.levels

        self.canvas.clear()
        self.value_sliders.update(var_min, var_max, levs)
        self.update_levels(levs, clear=True)
Example #18
0
    def var(self, value):
        self._var = value
        flat = self._var.flatten()
        var_min, var_max = vcs.minmax(flat)
        # Check if we're using auto levels
        if self._gm is None or not self.has_set_gm_levels():
            # Update the automatic levels with this variable
            levs = vcs.utils.mkscale(var_min, var_max)
        else:
            # Otherwise, just use what the levels are
            levs = self._gm.levels

        self.canvas.clear()
        self.value_sliders.update(var_min, var_max, levs)
        self.update_levels(levs, clear=True)
Example #19
0
 def set_anim_min_max(self):
     # Save the min and max values for the graphics methods.
     # Will need to restore values back when animation is done.
     self.save_original_min_max()
     # Note: cannot set the min and max values if the default graphics
     # method is set.
     do_min_max = 'yes'
     try:
         if (parent is not None) and (parent.iso_spacing == 'Log'):
             do_min_max = 'no'
     except:
         pass
     if (do_min_max == 'yes'):
         minv = []
         maxv = []
         if (self.create_params.a_min is None
                 or self.create_params.a_max is None):
             for i in xrange(len(self.animate_info)):
                 minv.append(1.0e77)
                 maxv.append(-1.0e77)
             for i in xrange(len(self.animate_info)):
                 dpy, slab = self.animate_info[i]
                 mins, maxs = vcs.minmax(slab)
                 minv[i] = float(numpy.minimum(float(minv[i]), float(mins)))
                 maxv[i] = float(numpy.maximum(float(maxv[i]), float(maxs)))
         elif (isinstance(self.create_params.a_min, list)
               or isinstance(self.create_params.a_max, list)):
             for i in xrange(len(self.animate_info)):
                 try:
                     minv.append(self.create_params.a_min[i])
                 except:
                     minv.append(self.create_params.a_min[-1])
                 try:
                     maxv.append(self.create_params.a_max[i])
                 except:
                     maxv.append(self.create_params.a_max[-1])
         else:
             for i in xrange(len(self.animate_info)):
                 minv.append(self.create_params.a_min)
                 maxv.append(self.create_params.a_max)
         # Set the min an max for each plot in the page. If the same graphics method is used
         # to display the plots, then the last min and max setting of the data set will be used.
         for i in xrange(len(self.animate_info)):
             try:
                 self.set_animation_min_max(minv[i], maxv[i], i)
             except Exception, err:
                 pass  # if it is default, then you cannot set the min and max, so pass.
Example #20
0
    def plot(self, data1, data2, tmpl, grid, transform, **kargs):
        """Overrides baseclass implementation."""
        # Clear old results:
        self._resultDict = {}

        self._template = tmpl
        self._originalData1 = data1
        self._originalData2 = data2
        self._vtkDataSet = grid
        self._vtkGeoTransform = transform

        # Preprocess the input scalar data:
        self._updateScalarData()
        self._min = self._data1.min()
        self._max = self._data1.max()
        self._scalarRange = vcs.minmax(self._data1)

        # Create/update the VTK dataset.
        plotBasedDualGrid = kargs.get('plot_based_dual_grid', True)
        self._updateVTKDataSet(plotBasedDualGrid)

        # Update the results:
        self._resultDict["vtk_backend_grid"] = self._vtkDataSet
        self._resultDict["vtk_backend_geo"] = self._vtkGeoTransform
        self._resultDict["vtk_backend_wrap"] = self._dataWrapModulo
        self._resultDict["dataset_bounds"] = self._vtkDataSetBounds

        # Determine and format the contouring information:
        self._updateContourLevelsAndColors()

        # Generate a mapper to render masked data:
        self._createMaskedDataMapper()

        # Create the polydata filter:
        self._createPolyDataFilter()

        if (kargs.get('ratio', '0') == 'autot' and
                # atot is implemented for linear plots at vcs level
                # for geographic projections we implement it here.
                self._vtkGeoTransform):
            self._resultDict['ratio_autot_viewport'] = self._processRatioAutot(
                self._template, self._vtkDataSet)

        # Plot specific rendering:
        self._plotInternal()

        return self._resultDict
Example #21
0
 def set_anim_min_max(self):
   # Save the min and max values for the graphics methods.
   # Will need to restore values back when animation is done.
   self.save_original_min_max()
   # Note: cannot set the min and max values if the default graphics
   # method is set.
   do_min_max = 'yes'
   try:
      if (parent is not None) and (parent.iso_spacing == 'Log'):
         do_min_max = 'no'
   except:
      pass
   if ( do_min_max == 'yes' ):
        minv = []
        maxv=[]
        if (self.create_params.a_min is None or 
            self.create_params.a_max is None):
           for i in xrange(len(self.animate_info)):
              minv.append( 1.0e77 )
              maxv.append( -1.0e77 )
           for i in xrange(len(self.animate_info)):
              dpy, slab = self.animate_info[i]
              mins, maxs = vcs.minmax(slab)
              minv[i] = float(numpy.minimum(float(minv[i]), float(mins)))
              maxv[i] = float(numpy.maximum(float(maxv[i]), float(maxs)))
        elif (isinstance(self.create_params.a_min,list) or 
              isinstance(self.create_params.a_max,list)):
           for i in xrange(len(self.animate_info)):
              try:
                 minv.append( self.create_params.a_min[i] )
              except:
                 minv.append( self.create_params.a_min[-1] )
              try:
                 maxv.append( self.create_params.a_max[i] )
              except:
                 maxv.append( self.create_params.a_max[-1] )
        else:
           for i in xrange(len(self.animate_info)):
               minv.append( self.create_params.a_min )
               maxv.append( self.create_params.a_max )
        # Set the min an max for each plot in the page. If the same graphics method is used
        # to display the plots, then the last min and max setting of the data set will be used.
        for i in xrange(len(self.animate_info)):
           try:
              self.set_animation_min_max( minv[i], maxv[i], i )
           except Exception,err:
              pass # if it is default, then you cannot set the min and max, so pass.
Example #22
0
    def step(self, value):
        left, right = vcs.minmax(self.axis)
        tick_vals = []

        value = float(value)
        if value < 0:
            cur_val = right
            target = left
            comp = target.__le__
        else:
            cur_val = left
            target = right
            comp = target.__ge__

        while comp(cur_val):
            tick_vals.append(cur_val)
            cur_val += value

        self.ticks = {i: i for i in tick_vals}
Example #23
0
    def step(self, value):
        left, right = vcs.minmax(self.axis)
        tick_vals = []

        value = float(value)
        if value < 0:
            cur_val = right
            target = left
            comp = target.__le__
        else:
            cur_val = left
            target = right
            comp = target.__ge__

        while comp(cur_val):
            tick_vals.append(cur_val)
            cur_val += value

        self.ticks = {i: i for i in tick_vals}
Example #24
0
def calculateStats(var):
    """Creates the statistical outputs needed."""
    print "Taking ensemble average as main line, max, min as one lot and +/- standard dev as other."
    cdms.setAutoBounds("on")
    av=cdutil.averager(var, axis="1")
    stddev=genutil.statistics.std(var, axis="1")
    cdms.setAutoBounds("off")

    maxList=[]
    minList=[]
    stddevUpper=[av[i]+stddev[i] for i in range(len(av))]
    stddevLower=[av[i]-stddev[i] for i in range(len(av))]

    for t in var:
        (mini, maxi)=vcs.minmax(t)
        minList.append(mini)
        maxList.append(maxi)
     
    return (av, maxList, minList, stddevUpper, stddevLower)
Example #25
0
    def plot(self, data1, data2, tmpl, gm, grid, transform):
        """Overrides baseclass implementation."""
        # Clear old results:
        self._resultDict = {}

        self._gm = gm
        self._template = tmpl
        self._originalData1 = data1
        self._originalData2 = data2
        self._vtkDataSet = grid
        self._vtkGeoTransform = transform
        self._colorMap = \
            vcs.elements["colormap"][self._context.canvas.getcolormapname()]

        # Preprocess the input scalar data:
        self._updateScalarData()
        self._scalarRange = vcs.minmax(self._data1)

        # Create/update the VTK dataset.
        self._updateVTKDataSet()

        # Update the results:
        self._resultDict["vtk_backend_grid"] = self._vtkDataSet
        self._resultDict["vtk_backend_geo"] = self._vtkGeoTransform
        self._resultDict["vtk_backend_wrap"] = self._dataWrapModulo

        # Determine and format the contouring information:
        self._updateContourLevelsAndColors()

        # Generate a mapper to render masked data:
        self._createMaskedDataMapper()

        # Create the polydata filter:
        self._createPolyDataFilter()

        # Plot specific rendering:
        self._plotInternal()

        return self._resultDict
Example #26
0
    def plot(self, data1, data2, tmpl, gm, grid, transform):
        """Overrides baseclass implementation."""
        # Clear old results:
        self._resultDict = {}

        self._gm = gm
        self._template = tmpl
        self._originalData1 = data1
        self._originalData2 = data2
        self._vtkDataSet = grid
        self._vtkGeoTransform = transform
        self._colorMap = \
            vcs.elements["colormap"][self._context.canvas.getcolormapname()]

        # Preprocess the input scalar data:
        self._updateScalarData()
        self._scalarRange = vcs.minmax(self._data1)

        # Create/update the VTK dataset.
        self._updateVTKDataSet()

        # Update the results:
        self._resultDict["vtk_backend_grid"] = self._vtkDataSet
        self._resultDict["vtk_backend_geo"] = self._vtkGeoTransform
        self._resultDict["vtk_backend_wrap"] = self._dataWrapModulo

        # Determine and format the contouring information:
        self._updateContourLevelsAndColors()

        # Generate a mapper to render masked data:
        self._createMaskedDataMapper()

        # Create the polydata filter:
        self._createPolyDataFilter()

        # Plot specific rendering:
        self._plotInternal()

        return self._resultDict
Example #27
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 #28
0
def plotminmax(outpath, mins, maxs, varname):
    canvas = vcs.init()

    gm = vcs.create1d()
    mn, mx = vcs.minmax(mins, maxs)
    gm.datawc_y1 = mn
    gm.datawc_y2 = mx

    template = vcs.createtemplate()
    template.scale(.95)
    template.move(.05, 'x')

    template.blank(["max", "mean"])
    canvas.plot(mins, gm, template, id=varname)

    template = vcs.createtemplate()
    template.scale(.95)
    template.move(.05, 'x')

    template.blank(["min", "mean"])
    canvas.plot(maxs, gm, template, id=varname)

    canvas.png(outpath)
    canvas.clear()
Example #29
0
    def _plotInternal(self):

        prepedContours = self._prepContours()
        tmpLevels = prepedContours["tmpLevels"]
        tmpIndices = prepedContours["tmpIndices"]
        tmpColors = prepedContours["tmpColors"]
        tmpOpacities = prepedContours["tmpOpacities"]

        style = self._gm.fillareastyle
        fareapixelspacing, fareapixelscale = self._patternSpacingAndScale()

        mappers = []
        luts = []
        geos = []
        wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1)
        plotting_dataset_bounds = self.getPlottingBounds()
        x1, x2, y1, y2 = plotting_dataset_bounds
        _colorMap = self.getColorMap()
        for i, l in enumerate(tmpLevels):
            # 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
            # TODO this should really just be a single polydata that is
            # colored by scalars:
            for j, color in enumerate(tmpColors[i]):
                mapper = vtk.vtkPolyDataMapper()
                lut = vtk.vtkLookupTable()
                th = vtk.vtkThreshold()
                th.ThresholdBetween(l[j], l[j + 1])
                th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
                geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                geoFilter2.SetInputConnection(th.GetOutputPort())
                # Make the polydata output available here for patterning later
                geoFilter2.Update()
                geos.append(geoFilter2)
                mapper.SetInputConnection(geoFilter2.GetOutputPort())
                lut.SetNumberOfTableValues(1)
                r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color)
                if style == 'solid':
                    tmpOpacity = tmpOpacities[j]
                    if tmpOpacity is None:
                        tmpOpacity = a / 100.
                    else:
                        tmpOpacity = tmpOpacities[j] / 100.
                    lut.SetTableValue(0, r / 100., g / 100., b / 100.,
                                      tmpOpacity)
                else:
                    lut.SetTableValue(0, 1., 1., 1., 0.)
                mapper.SetLookupTable(lut)
                mapper.SetScalarRange(l[j], l[j + 1])
                luts.append([lut, [l[j], l[j + 1], True]])
                # Store the mapper only if it's worth it?
                # Need to do it with the whole slab min/max for animation
                # purposes
                if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax):
                    mappers.append(mapper)

        self._resultDict["vtk_backend_luts"] = luts
        if len(geos) > 0:
            self._resultDict["vtk_backend_geofilters"] = geos
        """
        numLevels = len(self._contourLevels)
        if mappers == []:  # ok didn't need to have special banded contours
            mapper = vtk.vtkPolyDataMapper()
            mappers = [mapper]
            # Colortable bit
            # make sure length match
            while len(self._contourColors) < numLevels:
                self._contourColors.append(self._contourColors[-1])

            lut = vtk.vtkLookupTable()
            lut.SetNumberOfTableValues(numLevels)
            for i in range(numLevels):
                r, g, b, a = self._colorMap.index[self._contourColors[i]]
                lut.SetTableValue(i, r / 100., g / 100., b / 100., a / 100.)

            mapper.SetLookupTable(lut)
            if numpy.allclose(self._contourLevels[0], -1.e20):
                lmn = self._min - 1.
            else:
                lmn = self._contourLevels[0]
            if numpy.allclose(self._contourLevels[-1], 1.e20):
                lmx = self._max + 1.
            else:
                lmx = self._contourLevels[-1]
            mapper.SetScalarRange(lmn, lmx)
            self._resultDict["vtk_backend_luts"] = [[lut, [lmn, lmx, True]]]
            """

        if self._maskedDataMapper is not None:
            # Note that this is different for meshfill -- others prepend.
            mappers.append(self._maskedDataMapper)

        # Add a second mapper for wireframe meshfill:
        if self._gm.mesh:
            lineMappers = []
            wireLUT = vtk.vtkLookupTable()
            wireLUT.SetNumberOfTableValues(1)
            wireLUT.SetTableValue(0, 0, 0, 0)
            for polyMapper in mappers:
                lineMapper = vtk.vtkPolyDataMapper()
                lineMapper.SetInputConnection(
                    polyMapper.GetInputConnection(0, 0))
                lineMapper._useWireFrame = True

                # 'noqa' comments disable pep8 checking for these lines. There
                # is not a readable way to shorten them due to the unwieldly
                # method name.
                #
                # Setup depth resolution so lines stay above points:
                polyMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(
                    0, 1)  # noqa
                polyMapper.SetResolveCoincidentTopologyToPolygonOffset()
                lineMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(
                    1, 1)  # noqa
                lineMapper.SetResolveCoincidentTopologyToPolygonOffset()
                lineMapper.SetLookupTable(wireLUT)

                lineMappers.append(lineMapper)
            mappers.extend(lineMappers)

        # And now we need actors to actually render this thing
        actors = []
        vp = self._resultDict.get('ratio_autot_viewport', [
            self._template.data.x1, self._template.data.x2,
            self._template.data.y1, self._template.data.y2
        ])
        dataset_renderer = None
        xScale, yScale = (1, 1)
        cti = 0
        ctj = 0
        for mapper in mappers:
            act = vtk.vtkActor()
            act.SetMapper(mapper)

            wireframe = False
            if hasattr(mapper, "_useWireFrame"):
                prop = act.GetProperty()
                prop.SetRepresentationToWireframe()
                wireframe = True

            # create a new renderer for this mapper
            # (we need one for each mapper because of cmaera flips)
            dataset_renderer, xScale, yScale = self._context().fitToViewport(
                act,
                vp,
                wc=plotting_dataset_bounds,
                geoBounds=self._vtkDataSetBoundsNoMask,
                geo=self._vtkGeoTransform,
                priority=self._template.data.priority,
                create_renderer=(dataset_renderer is None),
                add_actor=(wireframe or (style == "solid")))

            # TODO See comment in boxfill.
            if mapper is self._maskedDataMapper:
                actors.append(
                    [act, self._maskedDataMapper, plotting_dataset_bounds])
            else:
                actors.append([act, plotting_dataset_bounds])

                if not wireframe:
                    # Since pattern creation requires a single color, assuming the
                    # first
                    if ctj >= len(tmpColors[cti]):
                        ctj = 0
                        cti += 1
                    c = self.getColorIndexOrRGBA(_colorMap,
                                                 tmpColors[cti][ctj])

                    # Get the transformed contour data
                    transform = act.GetUserTransform()
                    transformFilter = vtk.vtkTransformFilter()
                    transformFilter.SetInputData(mapper.GetInput())
                    transformFilter.SetTransform(transform)
                    transformFilter.Update()

                    patact = fillareautils.make_patterned_polydata(
                        transformFilter.GetOutput(),
                        fillareastyle=style,
                        fillareaindex=tmpIndices[cti],
                        fillareacolors=c,
                        fillareaopacity=tmpOpacities[cti],
                        fillareapixelspacing=fareapixelspacing,
                        fillareapixelscale=fareapixelscale,
                        size=self._context().renWin.GetSize(),
                        renderer=dataset_renderer)
                    ctj += 1
                if patact is not None:
                    actors.append([patact, plotting_dataset_bounds])
                    dataset_renderer.AddActor(patact)

        t = self._originalData1.getTime()
        if self._originalData1.ndim > 2:
            z = self._originalData1.getAxis(-3)
        else:
            z = None
        self._resultDict["vtk_backend_actors"] = actors
        kwargs = {
            "vtk_backend_grid": self._vtkDataSet,
            "dataset_bounds": self._vtkDataSetBounds,
            "plotting_dataset_bounds": plotting_dataset_bounds,
            "vtk_dataset_bounds_no_mask": self._vtkDataSetBoundsNoMask,
            "vtk_backend_geo": self._vtkGeoTransform
        }
        if ("ratio_autot_viewport" in self._resultDict):
            kwargs["ratio_autot_viewport"] = vp
        self._resultDict.update(self._context().renderTemplate(
            self._template,
            self._data1,
            self._gm,
            t,
            z,
            X=numpy.arange(min(x1, x2),
                           max(x1, x2) * 1.1,
                           abs(x2 - x1) / 10.),
            Y=numpy.arange(min(y1, y2),
                           max(y1, y2) * 1.1,
                           abs(y2 - y1) / 10.),
            **kwargs))

        legend = getattr(self._gm, "legend", None)

        if self._gm.ext_1:
            if isinstance(self._contourLevels[0], list):
                if numpy.less(abs(self._contourLevels[0][0]), 1.e20):
                    # Ok we need to add the ext levels
                    self._contourLevels.insert(
                        0, [-1.e20, self._contourLevels[0][0]])
            else:
                if numpy.less(abs(self._contourLevels[0]), 1.e20):
                    # need to add an ext
                    self._contourLevels.insert(0, -1.e20)
        if self._gm.ext_2:
            if isinstance(self._contourLevels[-1], list):
                if numpy.less(abs(self._contourLevels[-1][1]), 1.e20):
                    # need ext
                    self._contourLevels.append(
                        [self._contourLevels[-1][1], 1.e20])
            else:
                if numpy.less(abs(self._contourLevels[-1]), 1.e20):
                    # need exts
                    self._contourLevels.append(1.e20)

        patternArgs = {}
        patternArgs['style'] = self._gm.fillareastyle
        patternArgs['index'] = self._gm.fillareaindices
        if patternArgs['index'] is None:
            patternArgs['index'] = [
                1,
            ]
        # Compensate for the different viewport size of the colorbar
        patternArgs['opacity'] = self._gm.fillareaopacity
        patternArgs['pixelspacing'] = [
            int(fareapixelspacing[0] / (vp[1] - vp[0])),
            int(fareapixelspacing[1] / (vp[3] - vp[2]))
        ]
        patternArgs['pixelscale'] = fareapixelscale / (vp[1] - vp[0])
        self._resultDict.update(self._context().renderColorBar(
            self._template, self._contourLevels, self._contourColors, legend,
            self.getColorMap(), **patternArgs))

        if self._context().canvas._continents is None:
            self._useContinents = False
        if self._useContinents:
            projection = vcs.elements["projection"][self._gm.projection]
            continents_renderer, xScale, yScale = self._context(
            ).plotContinents(plotting_dataset_bounds, projection,
                             self._dataWrapModulo, vp,
                             self._template.data.priority, **kwargs)
Example #30
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
Example #31
0
    def create(self,
               parent=None,
               min=None,
               max=None,
               save_file=None,
               thread_it=1,
               rate=None,
               bitrate=None,
               ffmpegoptions=''):
        from vcs import minmax
        from numpy.ma import maximum, minimum
        ##from tkMessageBox import showerror

        # Cannot "Run" or "Create" an animation while already creating an animation
        if self.run_flg == 1: return
        if self.vcs_self.canvas.creating_animation() == 1: return

        if self.vcs_self.animate_info == []:
            str = "No data found!"
            showerror("Error Message to User", str)
            return
        finish_queued_X_server_requests(self.vcs_self)
        self.vcs_self.canvas.BLOCK_X_SERVER()

        # Stop the (thread) execution of the X main loop (if it is running).
        self.vcs_self.canvas.stopxmainloop()

        # Force VCS to update its orientation, needed when the user changes the
        # VCS Canvas size.
        self.vcs_self.canvas.updateorientation()

        # Make sure the animate information is up-to-date for creating images
        if ((self.gui_popup == 1) and (self.create_flg == 0)):
            self.update_animate_display_list()

        # Save the min and max values for the graphics methods.
        # Will need to restore values back when animation is done.
        self.save_original_min_max()

        # Set up the animation min and max values by changing the graphics method
        # Note: cannot set the min and max values if the default graphics method is set.
        do_min_max = 'yes'
        try:
            if (parent is not None) and (parent.iso_spacing == 'Log'):
                do_min_max = 'no'
        except:
            pass

        # Draw specified continental outlines if needed.
        self.continents_hold_value = self.vcs_self.canvas.getcontinentstype()
        self.vcs_self.canvas.setcontinentstype(self.continents_value)

        if (do_min_max == 'yes'):
            minv = []
            maxv = []
            if (min is None) or (max is None):
                for i in range(len(self.vcs_self.animate_info)):
                    minv.append(1.0e77)
                    maxv.append(-1.0e77)
                for i in range(len(self.vcs_self.animate_info)):
                    dpy, slab = self.vcs_self.animate_info[i]
                    mins, maxs = minmax(slab)
                    minv[i] = float(minimum(float(minv[i]), float(mins)))
                    maxv[i] = float(maximum(float(maxv[i]), float(maxs)))
            if isinstance(min, list) or isinstance(max, list):
                for i in range(len(self.vcs_self.animate_info)):
                    try:
                        minv.append(min[i])
                    except:
                        minv.append(min[-1])
                    try:
                        maxv.append(max[i])
                    except:
                        maxv.append(max[-1])
            else:
                for i in range(len(self.vcs_self.animate_info)):
                    minv.append(min)
                    maxv.append(max)

            # Set the min an max for each plot in the page. If the same graphics method is used
            # to display the plots, then the last min and max setting of the data set will be used.
            for i in range(len(self.vcs_self.animate_info)):
                try:
                    self.set_animation_min_max(minv[i], maxv[i], i)
                except Exception, err:
                    pass  # if it is default, then you cannot set the min and max, so pass.
Example #32
0
    def plot(self,data=None,template = None, bg=0, x=None):
        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):
            raise "Error did not know what to do with template: %s" % template

        if data.getLongitude() is None or data.getLatitude() is None:
            raise Exception,["Error data do not have lat/lon"]
        if data is None:
            xmn=-180.
            xmx=180
            ymn=-90
            ymx=90
        else:
            xmn,xmx = vcs.minmax(data.getLongitude()[:])
            ymn,ymx = vcs.minmax(data.getLatitude()[:])
            
        xmn,xmx,ymn,ymx = self.prep_plot(xmn,xmx,ymn,ymx)

        n = len(self.sources)
        for i in range(n):
            type = self.types[i]
            source = self.sources[i]
            if type == 'ngdc' or type == 1:
                fnm = self.gen_cont_file(xmn,xmx,ymn,ymx,source)
                f=open(fnm)
                data=f.read()
                f.close()
                if self.HAVE_BZ2:
                    import bz2
                    data = bz2.decompress(data)
            elif type == "file" or type == 0:
                source = self.sources[i]
                f=open(source)
                data=f.read()
                f.close()
                if fnm[-3:]=='bz2':
                    if self.HAVE_BZ2 :
                        import bz2
                        data = bz2.decompress(data)
                    else:
                        raise Excetpion, ["Cannot uncompress bzipped data"]
            elif type == "shapefile" or type==2:
                source = self.sources[i]
                data = self.load_shapefile(source)
            f = open(os.path.join(os.environ.get("HOME","."),"PCMDI_GRAPHICS","data_continent_other10"),"w")
            f.write(data)
            f.close()
            c = x.createcontinents()
            j=i
            if i>=len(self.colors):
                j=-1
            c.linecolor=self.colors[j]
            j=i
            if i>=len(self.widths):
                j=-1
            c.linewidth=self.widths[j]
            j=i
            if i>=len(self.lines):
                j=-1
            c.line=self.lines[j]
            c.type=10

            c.datawc_x1 = xmn
            c.datawc_x2 = xmx
            c.datawc_y1 = ymn
            c.datawc_y2 = ymx
            c.xmtics1=self.xmtics1
            c.xmtics2=self.xmtics2
            c.ymtics1=self.ymtics1
            c.ymtics2=self.ymtics2
            c.xticlabels1=self.xticlabels1
            c.xticlabels2=self.xticlabels2
            c.yticlabels1=self.yticlabels1
            c.yticlabels2=self.yticlabels2
            c.xaxisconvert=self.xaxisconvert
            c.yaxisconvert= self.yaxisconvert
            c.legend = self.legend
            c.projection=self.projection

            self.x.plot(c,template,bg=bg)
Example #33
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
Example #34
0
    def plot(self, data, data2, template=None, bg=0, x=None):
        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):
            raise "Error did not know what to do with template: %s" % template

        if not isinstance(data, cdms2.tvariable.TransientVariable):
            mode = cdms2.getAutoBounds()
            cdms2.setAutoBounds("on")
            data = MV2.array(data)
            data.getAxis(-1).getBounds()
            cdms2.setAutoBounds(mode)

        while data.ndim > 1:
            data = data[0]
        while data2.ndim > 1:
            data2 = data2[0]

        # ok now we have a good x and a good data

        # 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
        ]
        ax = data.getAxis(0)[:]
        ax2 = data.getAxis(0)[:]
        xmn, xmx = vcs.minmax(ax, ax2)
        ymn, ymx = vcs.minmax(data, data2)

        xmn, xmx, ymn, ymx = self.prep_plot(xmn, xmx, ymn, ymx)

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

        fill.style = [
            self.fillareastyle,
        ]
        fill.color = [
            self.fillareacolor,
        ]
        fill.index = [
            self.fillareaindex,
        ]

        line.type = [
            self.linetype,
        ]
        line.width = [
            self.linewidth,
        ]
        line.color = [
            self.linecolor,
        ]

        xs = []
        ys = []

        xs = numpy.concatenate((ax[:], ax2[::-1])).tolist()
        ys = numpy.concatenate((data[:], data2[::-1])).tolist()

        xs.append(xs[0])
        ys.append(ys[0])

        fill.x = xs
        fill.y = ys

        line.x = xs
        line.y = ys

        displays = []
        displays.append(x.plot(fill, bg=bg))
        displays.append(x.plot(line, bg=bg))

        x.worldcoordinate = fill.worldcoordinate

        dsp = template.plot(x, data, self, bg=bg)
        for d in dsp:
            displays.append(d)

        self.restore()
        return displays
Example #35
0
# Show fewer xticlabels in order to actually be able to read them
reduced_labels = vcs.createisofill("reduced", "default")
# You use a dictionary that maps values 0 <= x < 360 to strings
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
Example #36
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 not self.negative_magnitude:  # negative amplitude means 180 degree shift
            neg = numpy.ma.less(magnitudes, 0.0)
            magnitudes = numpy.ma.abs(magnitudes)
            thetas = numpy.ma.where(neg, theta + numpy.pi, theta)
        if self.group_names:
            names = self.group_names
            while len(names) < len(magnitudes):
                names.append(None)

        flat_magnitude = numpy.ravel(magnitudes)

        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):
                    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 + self.theta_offset,
                    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)
                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 +
                                                    self.theta_offset) +
                                          center[0])
                        m_labels.y.append(ymul * lev_radius *
                                          numpy.sin(self.magnitude_tick_angle +
                                                    self.theta_offset) +
                                          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):
                mintics = vcs.elements["list"][mintics]

            for mag in mintics:
                mintic_radius = radius * \
                    self.magnitude_from_value(mag, m_scale)
                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 = sorted(list(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.markertypes
        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.linepriority > 0:
            line = vcs.createline()
            line.x = []
            line.y = []
            line.type = self.linetypes
            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) * radius
                    if r == numpy.nan:
                        continue
                    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 = tick_thetas
                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) * 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.linepriority > 0:
            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 #37
0
    def create(self, parent=None, min=None, max=None, save_file=None,
               thread_it=1, rate=None, bitrate=None, ffmpegoptions=''):
        from vcs import minmax
        from numpy.ma import maximum, minimum

        # Cannot "Run" or "Create" an animation while already creating an
        # animation
        if self.run_flg == 1:
            return
        if self.vcs_self.canvas.creating_animation() == 1:
            return

        if self.vcs_self.animate_info == []:
            str = "No data found!"
            showerror("Error Message to User", str)
            return

        # Stop the (thread) execution of the X main loop (if it is running).
        self.vcs_self.canvas.stopxmainloop()

        # Force VCS to update its orientation, needed when the user changes the
        # VCS Canvas size.
        self.vcs_self.canvas.updateorientation()

        # Make sure the animate information is up-to-date for creating images
        if ((self.gui_popup == 1) and (self.create_flg == 0)):
            self.update_animate_display_list()

        # Save the min and max values for the graphics methods.
        # Will need to restore values back when animation is done.
        self.save_original_min_max()

        # Set up the animation min and max values by changing the graphics method
        # Note: cannot set the min and max values if the default graphics
        # method is set.
        do_min_max = 'yes'
        try:
            if (parent is not None) and (parent.iso_spacing == 'Log'):
                do_min_max = 'no'
        except:
            pass

        # Draw specified continental outlines if needed.
        self.continents_hold_value = self.vcs_self.canvas.getcontinentstype()
        self.vcs_self.canvas.setcontinentstype(self.continents_value)

        if (do_min_max == 'yes'):
            minv = []
            maxv = []
            if (min is None) or (max is None):
                for i in range(len(self.vcs_self.animate_info)):
                    minv.append(1.0e77)
                    maxv.append(-1.0e77)
                for i in range(len(self.vcs_self.animate_info)):
                    dpy, slab = self.vcs_self.animate_info[i]
                    mins, maxs = minmax(slab)
                    minv[i] = float(minimum(float(minv[i]), float(mins)))
                    maxv[i] = float(maximum(float(maxv[i]), float(maxs)))
            if isinstance(min, list) or isinstance(max, list):
                for i in range(len(self.vcs_self.animate_info)):
                    try:
                        minv.append(min[i])
                    except:
                        minv.append(min[-1])
                    try:
                        maxv.append(max[i])
                    except:
                        maxv.append(max[-1])
            else:
                for i in range(len(self.vcs_self.animate_info)):
                    minv.append(min)
                    maxv.append(max)

            # Set the min an max for each plot in the page. If the same graphics method is used
            # to display the plots, then the last min and max setting of the
            # data set will be used.
            for i in range(len(self.vcs_self.animate_info)):
                try:
                    self.set_animation_min_max(minv[i], maxv[i], i)
                except:
                    # if it is default, then you cannot set the min and max, so
                    # pass.
                    pass

        if save_file is None or save_file.split('.')[-1].lower() == 'ras':
            if thread_it:
                thread.start_new_thread(
                    self.vcs_self.canvas.animate_init, (save_file,))
            else:
                self.vcs_self.canvas.animate_init(save_file)
        else:  # ffmpeg stuff
            save_info = self.vcs_self.animate_info
            animation_info = self.animate_info_from_python()
            slabs = []
            templates = []
            dpys = []
            for i in range(len(self.vcs_self.animate_info)):
                dpy, slab = self.vcs_self.animate_info[i]
                slabs.append(slab)
                dpys.append(dpy)
                templates.append(dpy.template)
            sh = slabs[0].shape
            if dpy.g_type in ['boxfill', 'isofill', 'isoline', 'meshfill',
                              'outfill', 'outline', 'taylordiagram', 'vector', ]:
                r = len(sh) - 2
            else:
                r = len(sh) - 1
            # now create the list of all previous indices to plot
            indices = []
            for i in range(r):
                this = list(range(sh[i]))
                tmp = []
                if indices == []:
                    for k in this:
                        indices.append([k, ])
                else:
                    for j in range(len(indices)):
                        for k in this:
                            tmp2 = copy.copy(indices[j])
                            tmp2.append(k)
                            tmp.append(tmp2)
                    indices = tmp
            count = 1
            white_square = self.vcs_self.createfillarea()
            white_square.color = 240
            white_square.x = [0, 1, 1, 0]
            white_square.y = [0, 0, 1, 1]
            new_vcs = self.vcs_self
            if self.vcs_self.orientation() == 'portrait':
                new_vcs.portrait()
            # self.vcs_self.close()

            for index in indices:
                new_vcs.clear()
                new_vcs.plot(white_square, bg=1)
                for i in range(len(save_info)):
                    slab = slabs[i]
                    template = templates[i]
                    gtype = animation_info["gtype"][i].lower()
                    gname = animation_info["gname"][i]
                    gm = None  # for flake8 to be happy
                    exec("gm = new_vcs.get%s('%s')" % (gtype, gname))
                    for j in index:
                        slab = slab[j]
                    new_vcs.plot(slab, gm, new_vcs.gettemplate(template), bg=1)
                new_vcs.png("tmp_anim_%i" % count)
                count += 1
            new_vcs.ffmpeg(
                save_file,
                "tmp_anim_%d.png",
                bitrate=bitrate,
                rate=rate,
                options=ffmpegoptions)
            for i in range(count - 1):
                os.remove("tmp_anim_%i.png" % (i + 1))
            del(new_vcs)
        self.create_flg = 1
Example #38
0
   def create( self, parent=None, min=None, max=None, save_file=None, thread_it = 1, rate=None, bitrate=None, ffmpegoptions='' ):
      from vcs import minmax
      from numpy.ma import maximum,minimum
      ##from tkMessageBox import showerror

      # Cannot "Run" or "Create" an animation while already creating an animation
      if self.run_flg == 1: return
      if self.vcs_self.canvas.creating_animation() == 1: return

      if self.vcs_self.animate_info == []:
         str = "No data found!"
         showerror( "Error Message to User", str )
         return
      finish_queued_X_server_requests( self.vcs_self )
      self.vcs_self.canvas.BLOCK_X_SERVER()

      # Stop the (thread) execution of the X main loop (if it is running).
      self.vcs_self.canvas.stopxmainloop( )

      # Force VCS to update its orientation, needed when the user changes the
      # VCS Canvas size.
      self.vcs_self.canvas.updateorientation()

      # Make sure the animate information is up-to-date for creating images
      if ((self.gui_popup == 1) and (self.create_flg == 0)):
         self.update_animate_display_list( )

      # Save the min and max values for the graphics methods.
      # Will need to restore values back when animation is done.
      self.save_original_min_max()

      # Set up the animation min and max values by changing the graphics method
      # Note: cannot set the min and max values if the default graphics method is set.
      do_min_max = 'yes'
      try:
         if (parent is not None) and (parent.iso_spacing == 'Log'):
            do_min_max = 'no'
      except:
         pass

      # Draw specified continental outlines if needed.
      self.continents_hold_value = self.vcs_self.canvas.getcontinentstype( )
      self.vcs_self.canvas.setcontinentstype( self.continents_value )

      if ( do_min_max == 'yes' ):
         minv = []
         maxv=[]
         if (min is None) or (max is None):
            for i in range(len(self.vcs_self.animate_info)):
               minv.append( 1.0e77 )
               maxv.append( -1.0e77 )
            for i in range(len(self.vcs_self.animate_info)):
               dpy, slab = self.vcs_self.animate_info[i]
               mins, maxs = minmax(slab)
               minv[i] = float(minimum(float(minv[i]), float(mins)))
               maxv[i] = float(maximum(float(maxv[i]), float(maxs)))
         if isinstance(min,list) or isinstance(max,list):
            for i in range(len(self.vcs_self.animate_info)):
               try:
                  minv.append( min[i] )
               except:
                  minv.append( min[-1] )
               try:
                  maxv.append( max[i] )
               except:
                  maxv.append( max[-1] )
         else:
            for i in range(len(self.vcs_self.animate_info)):
                minv.append( min )
                maxv.append( max )

         # Set the min an max for each plot in the page. If the same graphics method is used
         # to display the plots, then the last min and max setting of the data set will be used.
         for i in range(len(self.vcs_self.animate_info)):
            try:
               self.set_animation_min_max( minv[i], maxv[i], i )
            except Exception,err:
               pass # if it is default, then you cannot set the min and max, so pass.
Example #39
0
 def return_animation_min_max(self):
     dpy, slab = self.vcs_self.animate_info[0]
     return vcs.minmax(slab)
Example #40
0
    def _plotInternal(self):
        tmpLevels = []
        tmpColors = []
        indices = self._gm.fillareaindices
        if indices is None:
            indices = [1]
        while len(indices) < len(self._contourColors):
            indices.append(indices[-1])
        if len(self._contourLevels) > len(self._contourColors):
            raise RuntimeError(
                "You asked for %i levels but provided only %i colors\n"
                "Graphic Method: %s of type %s\nLevels: %s"
                % (len(self._contourLevels), len(self._contourColors),
                   self._gm.name, self._gm.g_name,
                   repr(self._contourLevels)))
        elif len(self._contourLevels) < len(self._contourColors) - 1:
            warnings.warn(
                "You asked for %i lgridevels but provided %i colors, extra "
                "ones will be ignored\nGraphic Method: %s of type %s"
                % (len(self._contourLevels), len(self._contourColors),
                   self._gm.name, self._gm.g_name))
        for i, l in enumerate(self._contourLevels):
            if i == 0:
                C = [self._contourColors[i]]
                if numpy.allclose(self._contourLevels[0][0], -1.e20):
                    # ok it's an extension arrow
                    L = [self._scalarRange[0] - 1., self._contourLevels[0][1]]
                else:
                    L = list(self._contourLevels[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(self._scalarRange[1] + 1.)
                    else:
                        L.append(l[1])
                    C.append(self._contourColors[i])
                else:  # ok we need new contouring
                    tmpLevels.append(L)
                    tmpColors.append(C)
                    C = [self._contourColors[i]]
                    L = self._contourLevels[i]
                    I = [indices[i]]
        tmpLevels.append(L)
        tmpColors.append(C)

        mappers = []
        luts = []
        geos = []
        for i, l in enumerate(tmpLevels):
            # 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
            wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1)
            # TODO this should really just be a single polydata that is
            # colored by scalars:
            for j, color in enumerate(tmpColors[i]):
                mapper = vtk.vtkPolyDataMapper()
                lut = vtk.vtkLookupTable()
                th = vtk.vtkThreshold()
                th.ThresholdBetween(l[j], l[j + 1])
                th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
                geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                geoFilter2.SetInputConnection(th.GetOutputPort())
                geos.append(geoFilter2)
                mapper.SetInputConnection(geoFilter2.GetOutputPort())
                lut.SetNumberOfTableValues(1)
                r, g, b = self._colorMap.index[color]
                lut.SetTableValue(0, r / 100., g / 100., b / 100.)
                mapper.SetLookupTable(lut)
                mapper.SetScalarRange(l[j], l[j + 1])
                luts.append([lut, [l[j], l[j + 1], True]])
                # Store the mapper only if it's worth it?
                # Need to do it with the whole slab min/max for animation
                # purposes
                if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax):
                    mappers.append(mapper)

        self._resultDict["vtk_backend_luts"] = luts
        if len(geos) > 0:
            self._resultDict["vtk_backend_geofilters"] = geos

        numLevels = len(self._contourLevels)
        if mappers == []:  # ok didn't need to have special banded contours
            mapper = vtk.vtkPolyDataMapper()
            mappers = [mapper]
            # Colortable bit
            # make sure length match
            while len(self._contourColors) < numLevels:
                self._contourColors.append(self._contourColors[-1])

            lut = vtk.vtkLookupTable()
            lut.SetNumberOfTableValues(numLevels)
            for i in range(numLevels):
                r, g, b = self._colorMap.index[self._contourColors[i]]
                lut.SetTableValue(i, r / 100., g / 100., b / 100.)

            mapper.SetLookupTable(lut)
            if numpy.allclose(self._contourLevels[0], -1.e20):
                lmn = self._min - 1.
            else:
                lmn = self._contourLevels[0]
            if numpy.allclose(self._contourLevels[-1], 1.e20):
                lmx = self._max + 1.
            else:
                lmx = self._contourLevels[-1]
            mapper.SetScalarRange(lmn, lmx)
            self._resultDict["vtk_backend_luts"] = [[lut, [lmn, lmx, True]]]

        if self._maskedDataMapper is not None:
            # Note that this is different for meshfill -- others prepend.
            mappers.append(self._maskedDataMapper)

        # This is also different for meshfill, others use
        # vcs.utils.getworldcoordinates
        x1, x2, y1, y2 = vcs2vtk.getRange(self._gm,
                                          self._vtkDataSetBounds[0],
                                          self._vtkDataSetBounds[1],
                                          self._vtkDataSetBounds[2],
                                          self._vtkDataSetBounds[3])

        # Add a second mapper for wireframe meshfill:
        if self._gm.mesh:
            lineMappers = []
            wireLUT = vtk.vtkLookupTable()
            wireLUT.SetNumberOfTableValues(1)
            wireLUT.SetTableValue(0, 0, 0, 0)
            for polyMapper in mappers:
                lineMapper = vtk.vtkPolyDataMapper()
                lineMapper.SetInputConnection(
                    polyMapper.GetInputConnection(0, 0))
                lineMapper._useWireFrame = True

                # 'noqa' comments disable pep8 checking for these lines. There
                # is not a readable way to shorten them due to the unwieldly
                # method name.
                #
                # Setup depth resolution so lines stay above points:
                polyMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(0, 1)  # noqa
                polyMapper.SetResolveCoincidentTopologyToPolygonOffset()
                lineMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(1, 1)  # noqa
                lineMapper.SetResolveCoincidentTopologyToPolygonOffset()
                lineMapper.SetLookupTable(wireLUT)

                lineMappers.append(lineMapper)
            mappers.extend(lineMappers)

        # And now we need actors to actually render this thing
        actors = []
        for mapper in mappers:
            act = vtk.vtkActor()
            act.SetMapper(mapper)

            if hasattr(mapper, "_useWireFrame"):
                prop = act.GetProperty()
                prop.SetRepresentationToWireframe()

            if self._vtkGeoTransform is None:
                # If using geofilter on wireframed does not get wrppaed not
                # sure why so sticking to many mappers
                act = vcs2vtk.doWrap(act, [x1, x2, y1, y2],
                                     self._dataWrapModulo)

            # TODO See comment in boxfill.
            if mapper is self._maskedDataMapper:
                actors.append([act, self._maskedDataMapper, [x1, x2, y1, y2]])
            else:
                actors.append([act, [x1, x2, y1, y2]])

            # create a new renderer for this mapper
            # (we need one for each mapper because of cmaera flips)
            self._context().fitToViewport(
                act, [self._template.data.x1,
                      self._template.data.x2,
                      self._template.data.y1,
                      self._template.data.y2],
                wc=[x1, x2, y1, y2], geo=self._vtkGeoTransform,
                priority=self._template.data.priority,
                create_renderer=True)

        self._resultDict["vtk_backend_actors"] = actors

        self._template.plot(self._context().canvas, self._data1, self._gm,
                            bg=self._context().bg,
                            X=numpy.arange(self._vtkDataSetBounds[0],
                                           self._vtkDataSetBounds[1] * 1.1,
                                           (self._vtkDataSetBounds[1] -
                                            self._vtkDataSetBounds[0]) / 10.),
                            Y=numpy.arange(self._vtkDataSetBounds[2],
                                           self._vtkDataSetBounds[3] * 1.1,
                                           (self._vtkDataSetBounds[3] -
                                            self._vtkDataSetBounds[2]) / 10.))

        legend = getattr(self._gm, "legend", None)

        if self._gm.ext_1:
            if isinstance(self._contourLevels[0], list):
                if numpy.less(abs(self._contourLevels[0][0]), 1.e20):
                    # Ok we need to add the ext levels
                    self._contourLevels.insert(
                        0, [-1.e20, self._contourLevels[0][0]])
            else:
                if numpy.less(abs(self._contourLevels[0]), 1.e20):
                    # need to add an ext
                    self._contourLevels.insert(0, -1.e20)
        if self._gm.ext_2:
            if isinstance(self._contourLevels[-1], list):
                if numpy.less(abs(self._contourLevels[-1][1]), 1.e20):
                    # need ext
                    self._contourLevels.append([self._contourLevels[-1][1],
                                                1.e20])
            else:
                if numpy.less(abs(self._contourLevels[-1]), 1.e20):
                    # need exts
                    self._contourLevels.append(1.e20)

        self._resultDict.update(
            self._context().renderColorBar(self._template, self._contourLevels,
                                           self._contourColors, legend,
                                           self._colorMap))

        if self._context().canvas._continents is None:
            self._useContinents = False
        if self._useContinents:
            projection = vcs.elements["projection"][self._gm.projection]
            self._context().plotContinents(x1, x2, y1, y2, projection,
                                           self._dataWrapModulo,
                                           self._template)
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 #42
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)
Example #43
0
    def _plotInternal(self):

        prepedContours = self._prepContours()
        tmpLevels = prepedContours["tmpLevels"]
        tmpIndices = prepedContours["tmpIndices"]
        tmpColors = prepedContours["tmpColors"]
        tmpOpacities = prepedContours["tmpOpacities"]

        style = self._gm.fillareastyle
        fareapixelspacing, fareapixelscale = self._patternSpacingAndScale()

        mappers = []
        luts = []
        geos = []
        wholeDataMin, wholeDataMax = vcs.minmax(self._data1)
        plotting_dataset_bounds = self.getPlottingBounds()
        x1, x2, y1, y2 = plotting_dataset_bounds
        # We need to do the convertion thing
        _convert = self._gm.yaxisconvert
        _func = vcs.utils.axisConvertFunctions[_convert]["forward"]
        y1 = _func(y1)
        y2 = _func(y2)
        _convert = self._gm.xaxisconvert
        _func = vcs.utils.axisConvertFunctions[_convert]["forward"]
        x1 = _func(x1)
        x2 = _func(x2)
        _colorMap = self.getColorMap()
        for i, l in enumerate(tmpLevels):
            # 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
            # TODO this should really just be a single polydata that is
            # colored by scalars:
            for j, color in enumerate(tmpColors[i]):
                mapper = vtk.vtkPolyDataMapper()
                lut = vtk.vtkLookupTable()
                th = vtk.vtkThreshold()
                th.ThresholdBetween(l[j], l[j + 1])
                # th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
                th.SetInputData(self._vtkDataSetFittedToViewport)
                geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                geoFilter2.SetInputConnection(th.GetOutputPort())
                # Make the polydata output available here for patterning later
                geoFilter2.Update()
                geos.append(geoFilter2)
                mapper.SetInputConnection(geoFilter2.GetOutputPort())
                lut.SetNumberOfTableValues(1)
                r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color)
                if style == 'solid':
                    tmpOpacity = tmpOpacities[j]
                    if tmpOpacity is None:
                        tmpOpacity = a / 100.
                    else:
                        tmpOpacity = tmpOpacities[j] / 100.
                    lut.SetTableValue(0, r / 100., g / 100., b / 100.,
                                      tmpOpacity)
                else:
                    lut.SetTableValue(0, 1., 1., 1., 0.)
                mapper.SetLookupTable(lut)
                mapper.SetScalarRange(l[j], l[j + 1])
                luts.append([lut, [l[j], l[j + 1], True]])
                # Store the mapper only if it's worth it?
                # Need to do it with the whole slab min/max for animation
                # purposes
                if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax):
                    mappers.append(mapper)

        self._resultDict["vtk_backend_luts"] = luts
        if len(geos) > 0:
            self._resultDict["vtk_backend_geofilters"] = geos

        if self._maskedDataMapper is not None:
            # Note that this is different for meshfill -- others prepend.
            mappers.append(self._maskedDataMapper)

        wireColor = [0, 0, 0, 255]

        # Add a second mapper for wireframe meshfill:
        if self._gm.mesh:
            lineMappers = []
            for polyMapper in mappers:
                edgeFilter = vtk.vtkExtractEdges()
                edgeFilter.SetInputConnection(
                    polyMapper.GetInputConnection(0, 0))

                lineMapper = vtk.vtkPolyDataMapper()
                lineMapper.SetInputConnection(edgeFilter.GetOutputPort(0))

                lineMapper._useWireFrame = True

                lineMappers.append(lineMapper)
            mappers.extend(lineMappers)

        # And now we need actors to actually render this thing
        actors = []
        vp = self._resultDict.get('ratio_autot_viewport', [
            self._template.data.x1, self._template.data.x2,
            self._template.data.y1, self._template.data.y2
        ])
        cti = 0
        ctj = 0

        # view and interactive area
        view = self._context().contextView
        area = vtk.vtkInteractiveArea()
        view.GetScene().AddItem(area)

        adjusted_plotting_bounds = vcs2vtk.getProjectedBoundsForWorldCoords(
            plotting_dataset_bounds, self._gm.projection)
        drawAreaBounds = vcs2vtk.computeDrawAreaBounds(
            adjusted_plotting_bounds)

        [renWinWidth, renWinHeight] = self._context().renWin.GetSize()
        geom = vtk.vtkRecti(int(round(vp[0] * renWinWidth)),
                            int(round(vp[2] * renWinHeight)),
                            int(round((vp[1] - vp[0]) * renWinWidth)),
                            int(round((vp[3] - vp[2]) * renWinHeight)))

        vcs2vtk.configureContextArea(area, drawAreaBounds, geom)

        for mapper in mappers:
            act = vtk.vtkActor()
            act.SetMapper(mapper)
            mapper.Update()
            poly = mapper.GetInput()

            item = None

            wireframe = False
            if hasattr(mapper, "_useWireFrame"):
                wireframe = True

            if wireframe:
                item = vtk.vtkPolyDataItem()
                item.SetPolyData(poly)

                colorArray = vtk.vtkUnsignedCharArray()
                colorArray.SetNumberOfComponents(4)
                for i in range(poly.GetNumberOfCells()):
                    colorArray.InsertNextTypedTuple(wireColor)

                item.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_CELL_DATA)
                item.SetMappedColors(colorArray)
                area.GetDrawAreaItem().AddItem(item)
            elif style == "solid":
                if self._needsCellData:
                    attrs = poly.GetCellData()
                else:
                    attrs = poly.GetPointData()

                data = attrs.GetScalars()
                deleteColors = False

                if data:
                    lut = mapper.GetLookupTable()
                    scalarRange = mapper.GetScalarRange()
                    lut.SetRange(scalarRange)
                    mappedColors = lut.MapScalars(data,
                                                  vtk.VTK_COLOR_MODE_DEFAULT,
                                                  0)
                    deleteColors = True
                else:
                    loc = 'point'
                    numTuples = poly.GetNumberOfPoints()
                    if self._needsCellData:
                        loc = 'cell'
                        numTuples = poly.GetNumberOfCells()
                    msg = 'WARNING: meshfill pipeline: poly does not have Scalars '
                    msg = msg + 'array on {0} data, using solid color'.format(
                        loc)
                    print(msg)
                    color = [0, 0, 0, 255]
                    mappedColors = vcs2vtk.generateSolidColorArray(
                        numTuples, color)

                mappedColors.SetName('Colors')

                item = vtk.vtkPolyDataItem()
                item.SetPolyData(poly)

                if self._needsCellData:
                    item.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_CELL_DATA)
                else:
                    item.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_POINT_DATA)

                item.SetMappedColors(mappedColors)
                if deleteColors:
                    mappedColors.FastDelete()
                area.GetDrawAreaItem().AddItem(item)

            # TODO See comment in boxfill.
            if item is not None:
                if mapper is self._maskedDataMapper:
                    actors.append([
                        item, self._maskedDataMapper, plotting_dataset_bounds
                    ])
                else:
                    actors.append([item, plotting_dataset_bounds])

            if mapper is not self._maskedDataMapper:

                if not wireframe:
                    # Since pattern creation requires a single color, assuming the
                    # first
                    if ctj >= len(tmpColors[cti]):
                        ctj = 0
                        cti += 1
                    c = self.getColorIndexOrRGBA(_colorMap,
                                                 tmpColors[cti][ctj])

                    patact = fillareautils.make_patterned_polydata(
                        poly,
                        fillareastyle=style,
                        fillareaindex=tmpIndices[cti],
                        fillareacolors=c,
                        fillareaopacity=tmpOpacities[cti],
                        fillareapixelspacing=fareapixelspacing,
                        fillareapixelscale=fareapixelscale,
                        size=self._context().renWin.GetSize(),
                        screenGeom=self._context().renWin.GetSize())
                    ctj += 1

                    if patact is not None:
                        actors.append([patact, plotting_dataset_bounds])

                        patMapper = patact.GetMapper()
                        patMapper.Update()
                        patPoly = patMapper.GetInput()

                        patItem = vtk.vtkPolyDataItem()
                        patItem.SetPolyData(patPoly)

                        patItem.SetScalarMode(
                            vtk.VTK_SCALAR_MODE_USE_CELL_DATA)
                        colorArray = patPoly.GetCellData().GetArray('Colors')

                        patItem.SetMappedColors(colorArray)
                        area.GetDrawAreaItem().AddItem(patItem)

                        actors.append([patItem, plotting_dataset_bounds])

        z, t = self.getZandT()

        self._resultDict["vtk_backend_actors"] = actors
        kwargs = {
            "vtk_backend_grid":
            self._vtkDataSet,
            "dataset_bounds":
            self._vtkDataSetBounds,
            "plotting_dataset_bounds":
            plotting_dataset_bounds,
            "vtk_dataset_bounds_no_mask":
            self._vtkDataSetBoundsNoMask,
            "vtk_backend_geo":
            self._vtkGeoTransform,
            "vtk_backend_draw_area_bounds":
            drawAreaBounds,
            "vtk_backend_viewport_scale":
            [self._context_xScale, self._context_yScale]
        }
        if ("ratio_autot_viewport" in self._resultDict):
            kwargs["ratio_autot_viewport"] = vp
        self._resultDict.update(self._context().renderTemplate(
            self._template,
            self._data1,
            self._gm,
            t,
            z,
            X=numpy.arange(min(x1, x2),
                           max(x1, x2) * 1.1,
                           abs(x2 - x1) / 10.),
            Y=numpy.arange(min(y1, y2),
                           max(y1, y2) * 1.1,
                           abs(y2 - y1) / 10.),
            **kwargs))

        legend = getattr(self._gm, "legend", None)

        if self._gm.ext_1:
            if isinstance(self._contourLevels[0], list):
                if numpy.less(abs(self._contourLevels[0][0]), 1.e20):
                    # Ok we need to add the ext levels
                    self._contourLevels.insert(
                        0, [-1.e20, self._contourLevels[0][0]])
            else:
                if numpy.less(abs(self._contourLevels[0]), 1.e20):
                    # need to add an ext
                    self._contourLevels.insert(0, -1.e20)
        if self._gm.ext_2:
            if isinstance(self._contourLevels[-1], list):
                if numpy.less(abs(self._contourLevels[-1][1]), 1.e20):
                    # need ext
                    self._contourLevels.append(
                        [self._contourLevels[-1][1], 1.e20])
            else:
                if numpy.less(abs(self._contourLevels[-1]), 1.e20):
                    # need exts
                    self._contourLevels.append(1.e20)

        patternArgs = {}
        patternArgs['style'] = self._gm.fillareastyle
        patternArgs['index'] = self._gm.fillareaindices
        if patternArgs['index'] is None:
            patternArgs['index'] = [
                1,
            ]
        # Compensate for the different viewport size of the colorbar
        patternArgs['opacity'] = self._gm.fillareaopacity
        patternArgs['pixelspacing'] = [
            int(fareapixelspacing[0] / (vp[1] - vp[0])),
            int(fareapixelspacing[1] / (vp[3] - vp[2]))
        ]
        patternArgs['pixelscale'] = fareapixelscale / (vp[1] - vp[0])
        self._resultDict.update(self._context().renderColorBar(
            self._template, self._contourLevels, self._contourColors, legend,
            self.getColorMap(), **patternArgs))

        projection = vcs.elements["projection"][self._gm.projection]
        kwargs['xaxisconvert'] = self._gm.xaxisconvert
        kwargs['yaxisconvert'] = self._gm.yaxisconvert
        self._context().plotContinents(
            self._plot_kargs.get("continents", self._useContinents),
            plotting_dataset_bounds, projection, self._dataWrapModulo, vp,
            self._template.data.priority, **kwargs)
Example #44
0
    def plotIsos(self, template=None, bg=0):
        if template is None:
            template = "thdiags_template"
        elif not isinstance(template, type("")):
            template = template.name
        try:
            isotemplate = self.x.createtemplate(template)
        except:
            isotemplate = self.x.gettemplate(template)

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

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

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

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

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

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

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

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

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

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

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

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

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

        # plot if self.drawisothermsfilled:
        if self.drawisothermsfilled:
            self.displays.append(self.x.plot(T, isotemplate, self.isothermsfilled, bg=bg))
        if self.drawisotherms:
            self.displays.append(self.x.plot(T, isotemplate, self.isotherms, bg=bg))
        if self.drawisobars:
            self.displays.append(self.x.plot(P, isotemplate, self.isobars, bg=bg))
        if self.drawdryadiabats:
            self.displays.append(self.x.plot(Tp, isotemplate, self.dryadiabats, bg=bg))
        if self.drawpseudoadiabats:
            self.plot_pseudo(isotemplate, bg=bg)
        if self.drawmixingratio:
            self.displays.append(self.x.plot(ws, isotemplate, self.mixingratio, bg=bg))
        return
Example #45
0
    def _plotInternal(self):
        tmpLevels = []
        tmpColors = []
        indices = self._gm.fillareaindices
        if indices is None:
            indices = [1]
        while len(indices) < len(self._contourColors):
            indices.append(indices[-1])
        if len(self._contourLevels) > len(self._contourColors):
            raise RuntimeError(
                  "You asked for %i levels but provided only %i colors\n"
                  "Graphic Method: %s of type %s\nLevels: %s"
                  % (len(self._contourLevels), len(self._contourColors),
                     self._gm.name, self._gm.g_name,
                     repr(self._contourLevels)))
        elif len(self._contourLevels) < len(self._contourColors) - 1:
            warnings.warn(
                  "You asked for %i lgridevels but provided %i colors, extra "
                  "ones will be ignored\nGraphic Method: %s of type %s"
                  % (len(self._contourLevels), len(self._contourColors),
                     self._gm.name, self._gm.g_name))
        for i, l in enumerate(self._contourLevels):
            if i == 0:
                C = [self._contourColors[i]]
                if numpy.allclose(self._contourLevels[0][0], -1.e20):
                    # ok it's an extension arrow
                    L = [self._scalarRange[0] - 1., self._contourLevels[0][1]]
                else:
                    L = list(self._contourLevels[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(self._scalarRange[1] + 1.)
                    else:
                        L.append(l[1])
                    C.append(self._contourColors[i])
                else:  # ok we need new contouring
                    tmpLevels.append(L)
                    tmpColors.append(C)
                    C = [self._contourColors[i]]
                    L = self._contourLevels[i]
                    I = [indices[i]]
        tmpLevels.append(L)
        tmpColors.append(C)

        mappers = []
        luts = []
        cots = []
        geos = []
        for i, l in enumerate(tmpLevels):
            # 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
            wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1)
            # TODO this should really just be a single polydata that is
            # colored by scalars:
            for j, color in enumerate(tmpColors[i]):
                mapper = vtk.vtkPolyDataMapper()
                lut = vtk.vtkLookupTable()
                th = vtk.vtkThreshold()
                th.ThresholdBetween(l[j], l[j+1])
                th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
                geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                geoFilter2.SetInputConnection(th.GetOutputPort())
                geos.append(geoFilter2)
                mapper.SetInputConnection(geoFilter2.GetOutputPort())
                lut.SetNumberOfTableValues(1)
                r, g, b = self._colorMap.index[color]
                lut.SetTableValue(0, r/100., g/100., b/100.)
                mapper.SetLookupTable(lut)
                mapper.SetScalarRange(l[j], l[j+1])
                luts.append([lut, [l[j], l[j+1], True]])
                # Store the mapper only if it's worth it?
                # Need to do it with the whole slab min/max for animation
                # purposes
                if not (l[j+1] < wholeDataMin or l[j] > wholeDataMax):
                    mappers.append(mapper)

        self._resultDict["vtk_backend_luts"] = luts
        if len(cots) > 0:
            self._resultDict["vtk_backend_contours"] = cots
        if len(geos) > 0:
            self._resultDict["vtk_backend_geofilters"] = geos

        numLevels = len(self._contourLevels)
        if mappers == []:  # ok didn't need to have special banded contours
            mapper = vtk.vtkPolyDataMapper()
            mappers = [mapper]
            # Colortable bit
            # make sure length match
            while len(self._contourColors) < numLevels:
                self._contourColors.append(self._contourColors[-1])

            lut = vtk.vtkLookupTable()
            lut.SetNumberOfTableValues(numLevels)
            for i in range(numLevels):
                r, g, b = self._colorMap.index[self._contourColors[i]]
                lut.SetTableValue(i, r / 100., g / 100., b / 100.)

            mapper.SetLookupTable(lut)
            if numpy.allclose(self._contourLevels[0], -1.e20):
                lmn = mn - 1.
            else:
                lmn = self._contourLevels[0]
            if numpy.allclose(self._contourLevels[-1], 1.e20):
                lmx = mx + 1.
            else:
                lmx = self._contourLevels[-1]
            mapper.SetScalarRange(lmn, lmx)
            self._resultDict["vtk_backend_luts"] = [[lut, [lmn, lmx, True]]]

        if self._maskedDataMapper is not None:
            # Note that this is different for meshfill -- others prepend.
            mappers.append(self._maskedDataMapper)

        # This is also different for meshfill, others use
        # vcs.utils.getworldcoordinates
        x1, x2, y1, y2 = vcs2vtk.getRange(self._gm,
                                          self._vtkDataSetBounds[0],
                                          self._vtkDataSetBounds[1],
                                          self._vtkDataSetBounds[2],
                                          self._vtkDataSetBounds[3])

        # Add a second mapper for wireframe meshfill:
        if self._gm.mesh:
            lineMappers = []
            wireLUT = vtk.vtkLookupTable()
            wireLUT.SetNumberOfTableValues(1)
            wireLUT.SetTableValue(0, 0, 0, 0)
            for polyMapper in mappers:
                lineMapper = vtk.vtkPolyDataMapper()
                lineMapper.SetInputConnection(
                    polyMapper.GetInputConnection(0, 0))
                lineMapper._useWireFrame = True

                # 'noqa' comments disable pep8 checking for these lines. There
                # is not a readable way to shorten them due to the unwieldly
                # method name.
                #
                # Setup depth resolution so lines stay above points:
                polyMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(0, 1)  # noqa
                polyMapper.SetResolveCoincidentTopologyToPolygonOffset()
                lineMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(1, 1)  # noqa
                lineMapper.SetResolveCoincidentTopologyToPolygonOffset()
                lineMapper.SetLookupTable(wireLUT)

                lineMappers.append(lineMapper)
            mappers.extend(lineMappers)

        # And now we need actors to actually render this thing
        actors = []
        for mapper in mappers:
            act = vtk.vtkActor()
            act.SetMapper(mapper)

            if hasattr(mapper, "_useWireFrame"):
                prop = act.GetProperty()
                prop.SetRepresentationToWireframe()

            if self._vtkGeoTransform is None:
                # If using geofilter on wireframed does not get wrppaed not
                # sure why so sticking to many mappers
                act = vcs2vtk.doWrap(act, [x1, x2, y1, y2],
                                     self._dataWrapModulo)

            # TODO See comment in boxfill.
            if mapper is self._maskedDataMapper:
                actors.append([act, self._maskedDataMapper, [x1, x2, y1, y2]])
            else:
                actors.append([act, [x1, x2, y1, y2]])

            # create a new renderer for this mapper
            # (we need one for each mapper because of cmaera flips)
            ren = self._context.fitToViewport(
                  act, [self._template.data.x1,
                        self._template.data.x2,
                        self._template.data.y1,
                        self._template.data.y2],
                  wc=[x1, x2, y1, y2], geo=self._vtkGeoTransform,
                  priority=self._template.data.priority)

        self._resultDict["vtk_backend_actors"] = actors

        self._template.plot(self._context.canvas, self._data1, self._gm,
                            bg=self._context.bg,
                            X=numpy.arange(self._vtkDataSetBounds[0],
                                           self._vtkDataSetBounds[1] * 1.1,
                                           (self._vtkDataSetBounds[1] -
                                            self._vtkDataSetBounds[0]) / 10.),
                            Y=numpy.arange(self._vtkDataSetBounds[2],
                                           self._vtkDataSetBounds[3] * 1.1,
                                           (self._vtkDataSetBounds[3] -
                                            self._vtkDataSetBounds[2]) / 10.))

        legend = getattr(self._gm, "legend", None)

        if self._gm.ext_1:
            if isinstance(self._contourLevels[0], list):
                if numpy.less(abs(self._contourLevels[0][0]), 1.e20):
                    # Ok we need to add the ext levels
                    self._contourLevels.insert(0, [-1.e20, levs[0][0]])
            else:
                if numpy.less(abs(self._contourLevels[0]), 1.e20):
                    # need to add an ext
                    self._contourLevels.insert(0, -1.e20)
        if self._gm.ext_2:
            if isinstance(self._contourLevels[-1], list):
                if numpy.less(abs(self._contourLevels[-1][1]), 1.e20):
                    # need ext
                    self._contourLevels.append([self._contourLevels[-1][1],
                                                1.e20])
            else:
                if numpy.less(abs(self._contourLevels[-1]), 1.e20):
                    # need exts
                    self._contourLevels.append(1.e20)

        self._resultDict.update(
            self._context.renderColorBar(self._template, self._contourLevels,
                                         self._contourColors, legend,
                                         self._colorMap))

        if self._context.canvas._continents is None:
            self._useContinents = False
        if self._useContinents:
            projection = vcs.elements["projection"][self._gm.projection]
            self._context.plotContinents(x1, x2, y1, y2, projection,
                                         self._dataWrapModulo, self._template)
Example #46
0
    def plotIsos(self, template=None, bg=0):
        if template is None:
            template = 'thdiags_template'
        elif type(template) != type(''):
            template = template.name
        try:
            isotemplate = self.x.createtemplate(template)
        except:
            isotemplate = self.x.gettemplate(template)

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

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

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

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

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

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

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

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

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

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

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

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

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

        # plot if self.drawisothermsfilled:
        if self.drawisothermsfilled:
            self.displays.append(
                self.x.plot(T, isotemplate, self.isothermsfilled, bg=bg))
        if self.drawisotherms:
            self.displays.append(
                self.x.plot(T, isotemplate, self.isotherms, bg=bg))
        if self.drawisobars:
            self.displays.append(
                self.x.plot(P, isotemplate, self.isobars, bg=bg))
        if self.drawdryadiabats:
            self.displays.append(
                self.x.plot(Tp, isotemplate, self.dryadiabats, bg=bg))
        if self.drawpseudoadiabats:
            self.plot_pseudo(isotemplate, bg=bg)
        if self.drawmixingratio:
            self.displays.append(
                self.x.plot(ws, isotemplate, self.mixingratio, bg=bg))
        return
Example #47
0
# Adapted for numpy/ma/cdms2 by convertcdms.py
import sys,cdms2 as cdms,vcs,cdtime,support,os

t0=cdtime.comptime(1987,8)
t1=cdtime.comptime(1988,12)
f=cdms.open(os.path.join(cdms.__path__[0],'..','..','..','..','sample_data','ta_ncep_87-6-88-4.nc'))

s=f('ta',latitude=slice(5,6),level=slice(0,1),squeeze=1)
mn,mx=vcs.minmax(s)
s=s/mx
s2=s()
## s.info()
## print s.shape
t2=s2.getTime()
t2.units='months since 1949-5'
x=vcs.init()
y=vcs.init()



b=x.createoutline('new2')
b.datawc_y1=t0
b.datawc_y2=t1
#b.list()

x.plot(s,b,bg=support.bg)
support.check_plot(x)
y.plot(s2,b,bg=support.bg)
support.check_plot(y)
x.clear()
y.clear()
 def _actualCreate( self, parent=None, min=None, max=None, save_file=None, rate=5., bitrate=None, ffmpegoptions='', axis=0, sender=None):
     alen = None
     dims = self.vcs_self.canvasinfo()
     if dims['height']<500:
         factor = 2
     else:
         factor=1
     if dims["width"]<dims["height"]:
         self.canvas.portrait(width=dims["width"],height=dims["height"])
     self.canvas.setbgoutputdimensions(width = dims['width']*factor,height=dims['height']*factor,units='pixel')
     truncated = False
     vcs_ai = list(self.vcs_self.animate_info)
     self.vcs_self.clear()
     for I in vcs_ai:
         if alen is None:
             alen = I[1][0].shape[axis]
         else:
             l = I[1][0].shape[axis]
             if l!=alen:
                 alen = numpy.minimum(alen,l)
                 truncated = True
     if truncated:
         warnings.warn("Because of inconsistent shapes over axis: %i, the animation length will be truncated to: %i\n" % (axis,alen))
     if self.animation_seed is not None:
         if self.animation_files != []:
             for fnm in self.animation_files:
                 os.remove(fnm)
     self.animation_seed = None
     self.animation_files = []
     # Save the min and max values for the graphics methods.
     # Will need to restore values back when animation is done.
     self.save_original_min_max()
     # Note: cannot set the min and max values if the default graphics method is set.
     do_min_max = 'yes'
     try:
        if (parent is not None) and (parent.iso_spacing == 'Log'):
           do_min_max = 'no'
     except:
        pass
     if ( do_min_max == 'yes' ):
          minv = []
          maxv=[]
          if (min is None) or (max is None):
             for i in range(len(self.vcs_self.animate_info)):
                minv.append( 1.0e77 )
                maxv.append( -1.0e77 )
             for i in range(len(self.vcs_self.animate_info)):
                dpy, slab = self.vcs_self.animate_info[i]
                mins, maxs = vcs.minmax(slab)
                minv[i] = float(numpy.minimum(float(minv[i]), float(mins)))
                maxv[i] = float(numpy.maximum(float(maxv[i]), float(maxs)))
          elif isinstance(min,list) or isinstance(max,list):
             for i in range(len(self.vcs_self.animate_info)):
                try:
                   minv.append( min[i] )
                except:
                   minv.append( min[-1] )
                try:
                   maxv.append( max[i] )
                except:
                   maxv.append( max[-1] )
          else:
             for i in range(len(self.vcs_self.animate_info)):
                 minv.append( min )
                 maxv.append( max )
          # Set the min an max for each plot in the page. If the same graphics method is used
          # to display the plots, then the last min and max setting of the data set will be used.
          for i in range(len(self.vcs_self.animate_info)):
             try:
                self.set_animation_min_max( minv[i], maxv[i], i )
             except Exception,err:
                pass # if it is default, then you cannot set the min and max, so pass.
Example #49
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
    canvas.bgY = 750

    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]
Example #51
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)
Example #52
0
    def create(self,
               parent=None,
               min=None,
               max=None,
               save_file=None,
               thread_it=1,
               rate=None,
               bitrate=None,
               ffmpegoptions=''):
        from vcs import minmax
        from numpy.ma import maximum, minimum

        # Cannot "Run" or "Create" an animation while already creating an
        # animation
        if self.run_flg == 1:
            return
        if self.vcs_self.canvas.creating_animation() == 1:
            return

        if self.vcs_self.animate_info == []:
            str = "No data found!"
            showerror("Error Message to User", str)
            return

        # Stop the (thread) execution of the X main loop (if it is running).
        self.vcs_self.canvas.stopxmainloop()

        # Force VCS to update its orientation, needed when the user changes the
        # VCS Canvas size.
        self.vcs_self.canvas.updateorientation()

        # Make sure the animate information is up-to-date for creating images
        if ((self.gui_popup == 1) and (self.create_flg == 0)):
            self.update_animate_display_list()

        # Save the min and max values for the graphics methods.
        # Will need to restore values back when animation is done.
        self.save_original_min_max()

        # Set up the animation min and max values by changing the graphics method
        # Note: cannot set the min and max values if the default graphics
        # method is set.
        do_min_max = 'yes'
        try:
            if (parent is not None) and (parent.iso_spacing == 'Log'):
                do_min_max = 'no'
        except:
            pass

        # Draw specified continental outlines if needed.
        self.continents_hold_value = self.vcs_self.canvas.getcontinentstype()
        self.vcs_self.canvas.setcontinentstype(self.continents_value)

        if (do_min_max == 'yes'):
            minv = []
            maxv = []
            if (min is None) or (max is None):
                for i in range(len(self.vcs_self.animate_info)):
                    minv.append(1.0e77)
                    maxv.append(-1.0e77)
                for i in range(len(self.vcs_self.animate_info)):
                    dpy, slab = self.vcs_self.animate_info[i]
                    mins, maxs = minmax(slab)
                    minv[i] = float(minimum(float(minv[i]), float(mins)))
                    maxv[i] = float(maximum(float(maxv[i]), float(maxs)))
            if isinstance(min, list) or isinstance(max, list):
                for i in range(len(self.vcs_self.animate_info)):
                    try:
                        minv.append(min[i])
                    except:
                        minv.append(min[-1])
                    try:
                        maxv.append(max[i])
                    except:
                        maxv.append(max[-1])
            else:
                for i in range(len(self.vcs_self.animate_info)):
                    minv.append(min)
                    maxv.append(max)

            # Set the min an max for each plot in the page. If the same graphics method is used
            # to display the plots, then the last min and max setting of the
            # data set will be used.
            for i in range(len(self.vcs_self.animate_info)):
                try:
                    self.set_animation_min_max(minv[i], maxv[i], i)
                except:
                    # if it is default, then you cannot set the min and max, so
                    # pass.
                    pass

        if save_file is None or save_file.split('.')[-1].lower() == 'ras':
            if thread_it:
                thread.start_new_thread(self.vcs_self.canvas.animate_init,
                                        (save_file, ))
            else:
                self.vcs_self.canvas.animate_init(save_file)
        else:  # ffmpeg stuff
            save_info = self.vcs_self.animate_info
            animation_info = self.animate_info_from_python()
            slabs = []
            templates = []
            dpys = []
            for i in range(len(self.vcs_self.animate_info)):
                dpy, slab = self.vcs_self.animate_info[i]
                slabs.append(slab)
                dpys.append(dpy)
                templates.append(dpy.template)
            sh = slabs[0].shape
            if dpy.g_type in [
                    'boxfill',
                    'isofill',
                    'isoline',
                    'meshfill',
                    'outfill',
                    'outline',
                    'taylordiagram',
                    'vector',
            ]:
                r = len(sh) - 2
            else:
                r = len(sh) - 1
            # now create the list of all previous indices to plot
            indices = []
            for i in range(r):
                this = list(range(sh[i]))
                tmp = []
                if indices == []:
                    for k in this:
                        indices.append([
                            k,
                        ])
                else:
                    for j in range(len(indices)):
                        for k in this:
                            tmp2 = copy.copy(indices[j])
                            tmp2.append(k)
                            tmp.append(tmp2)
                    indices = tmp
            count = 1
            white_square = self.vcs_self.createfillarea()
            white_square.color = 240
            white_square.x = [0, 1, 1, 0]
            white_square.y = [0, 0, 1, 1]
            new_vcs = self.vcs_self
            if self.vcs_self.orientation() == 'portrait':
                new_vcs.portrait()
            # self.vcs_self.close()

            for index in indices:
                new_vcs.clear()
                new_vcs.plot(white_square, bg=1)
                for i in range(len(save_info)):
                    slab = slabs[i]
                    template = templates[i]
                    gtype = animation_info["gtype"][i].lower()
                    gname = animation_info["gname"][i]
                    gm = None  # for flake8 to be happy
                    exec("gm = new_vcs.get%s('%s')" % (gtype, gname))
                    for j in index:
                        slab = slab[j]
                    new_vcs.plot(slab, gm, new_vcs.gettemplate(template), bg=1)
                new_vcs.png("tmp_anim_%i" % count)
                count += 1
            new_vcs.ffmpeg(save_file,
                           "tmp_anim_%d.png",
                           bitrate=bitrate,
                           rate=rate,
                           options=ffmpegoptions)
            for i in range(count - 1):
                os.remove("tmp_anim_%i.png" % (i + 1))
            del (new_vcs)
        self.create_flg = 1
Example #53
0
def writeOutput(infile, var, lat, lon, dav, dmax, dmin, sdupper, sdlower, location):
    """
    Writes an output file of the variables generated.
    """

    location=location.replace(" ","_").lower()
    f=cdms.open(infile)
    
    mapit={"apcp":("rainfall","l/m^2"), "tmpk":("temperature","K")} 
    varname=mapit[var][0]
    units=mapit[var][1]
    datetime=os.path.split(infile)[-1].split(".")[1]
    outfile="%s_%s_%s.nc" % (datetime, location, varname)
    outpath=os.path.split(infile)[0]
    outfile=os.path.join(outpath, outfile)
    fout=cdms.open(outfile, "w")
    latax=cdms.createAxis([lat])
    latax.units="degrees_north"
    latax.id=latax.standard_name=latax.long_name="latitude"
    lonax=cdms.createAxis([lon])
    lonax.units="degrees_east"
    lonax.id=lonax.standard_name=lonax.long_name="longitude"   
    tax=f[var].getTime() #f(var, level=slice(0,1), lat=slice(0,1), lon=slice(0,1)).getTime()
    timeax=cdms.createAxis(Numeric.array(tax[0:tlen],'d'))
    timeax.designateTime()
    timeax.units=tax.units
    #timeax.id=timeax.standard_name=timeax.long_name="time"
    timeax.id="time"
    timeax.title=tax.title
    timeax.delta_t=tax.delta_t
    timeax.init_time=tax.init_time
    timeax.actual_range=tax.actual_range
    del timeax.axis
    del timeax.calendar
    metadata=f[var]
    fv=metadata.missing_value
    newshape=(len(timeax), len(latax), len(lonax))
    
    maxFound=20. # Set as our max value if not greater
    
    for v in ((dav, "average"), (dmax, "maximum"), (dmin, "minimum"), \
      (sdupper, "plus_std_dev"), (sdlower, "minus_std_dev"), ("always10", "always10")):
        if type(v[0])==type("jlj") and v[0]=="always10": 
            print "Creating always equal to 10 variable."
            always10=MA.zeros(newshape, 'f')+10.
            #print always10.shape, dav.shape, type(dav)
            newvar=cdms.createVariable(always10,  axes=[timeax, latax, lonax], id=v[1], fill_value=fv)
            newvar.longname="always10"
        else:
            data=v[0]
            name=varname+"_"+v[1]
            if not type(data)==type([1,2]):
                data=data(squeeze=1)
            data=MA.resize(data, newshape)
            newvar=cdms.createVariable(data, axes=[timeax, latax, lonax], id=name, fill_value=fv)
            newvar.long_name="%s - %s" % (varname.title(), v[1].replace("_", " "))
            newvar.units=metadata.units

        (dummy,vmax)=vcs.minmax(newvar)
        if vmax>maxFound:
            maxFound=vmax
        fout.write(newvar)
        fout.sync()
        del newvar

    fout.close()
    return (outfile, varname, datetime, maxFound)
Example #54
0
    def _plotInternal(self):

        prepedContours = self._prepContours()
        tmpLevels = prepedContours["tmpLevels"]
        tmpIndices = prepedContours["tmpIndices"]
        tmpColors = prepedContours["tmpColors"]
        tmpOpacities = prepedContours["tmpOpacities"]

        style = self._gm.fillareastyle
        # self._patternActors = []

        mappers = []
        luts = []
        geos = []
        wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1)
        plotting_dataset_bounds = self.getPlottingBounds()
        x1, x2, y1, y2 = plotting_dataset_bounds
        _colorMap = self.getColorMap()
        self._patternActors = []
        for i, l in enumerate(tmpLevels):
            # 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
            # TODO this should really just be a single polydata that is
            # colored by scalars:
            for j, color in enumerate(tmpColors[i]):
                mapper = vtk.vtkPolyDataMapper()
                lut = vtk.vtkLookupTable()
                th = vtk.vtkThreshold()
                th.ThresholdBetween(l[j], l[j + 1])
                th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
                geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                geoFilter2.SetInputConnection(th.GetOutputPort())
                # Make the polydata output available here for patterning later
                geoFilter2.Update()
                geos.append(geoFilter2)
                mapper.SetInputConnection(geoFilter2.GetOutputPort())
                lut.SetNumberOfTableValues(1)
                r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color)
                if style == 'solid':
                    tmpOpacity = tmpOpacities[j]
                    if tmpOpacity is None:
                        tmpOpacity = a / 100.
                    else:
                        tmpOpacity = tmpOpacities[j] / 100.
                    lut.SetTableValue(
                        0, r / 100., g / 100., b / 100., tmpOpacity)
                else:
                    lut.SetTableValue(0, 1., 1., 1., 0.)
                mapper.SetLookupTable(lut)
                mapper.SetScalarRange(l[j], l[j + 1])
                luts.append([lut, [l[j], l[j + 1], True]])
                # Store the mapper only if it's worth it?
                # Need to do it with the whole slab min/max for animation
                # purposes
                if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax):
                    mappers.append(mapper)

            # Since pattern creation requires a single color, assuming the
            # first
            c = self.getColorIndexOrRGBA(_colorMap, tmpColors[i][0])
            act = fillareautils.make_patterned_polydata(geoFilter2.GetOutput(),
                                                        fillareastyle=style,
                                                        fillareaindex=tmpIndices[i],
                                                        fillareacolors=c,
                                                        fillareaopacity=tmpOpacities[i],
                                                        size=(x2 - x1, y2 - y1))
            if act is not None:
                self._patternActors.append(act)

        self._resultDict["vtk_backend_luts"] = luts
        if len(geos) > 0:
            self._resultDict["vtk_backend_geofilters"] = geos

        """
        numLevels = len(self._contourLevels)
        if mappers == []:  # ok didn't need to have special banded contours
            mapper = vtk.vtkPolyDataMapper()
            mappers = [mapper]
            # Colortable bit
            # make sure length match
            while len(self._contourColors) < numLevels:
                self._contourColors.append(self._contourColors[-1])

            lut = vtk.vtkLookupTable()
            lut.SetNumberOfTableValues(numLevels)
            for i in range(numLevels):
                r, g, b, a = self._colorMap.index[self._contourColors[i]]
                lut.SetTableValue(i, r / 100., g / 100., b / 100., a / 100.)

            mapper.SetLookupTable(lut)
            if numpy.allclose(self._contourLevels[0], -1.e20):
                lmn = self._min - 1.
            else:
                lmn = self._contourLevels[0]
            if numpy.allclose(self._contourLevels[-1], 1.e20):
                lmx = self._max + 1.
            else:
                lmx = self._contourLevels[-1]
            mapper.SetScalarRange(lmn, lmx)
            self._resultDict["vtk_backend_luts"] = [[lut, [lmn, lmx, True]]]
            """

        if self._maskedDataMapper is not None:
            # Note that this is different for meshfill -- others prepend.
            mappers.append(self._maskedDataMapper)

        # Add a second mapper for wireframe meshfill:
        if self._gm.mesh:
            lineMappers = []
            wireLUT = vtk.vtkLookupTable()
            wireLUT.SetNumberOfTableValues(1)
            wireLUT.SetTableValue(0, 0, 0, 0)
            for polyMapper in mappers:
                lineMapper = vtk.vtkPolyDataMapper()
                lineMapper.SetInputConnection(
                    polyMapper.GetInputConnection(0, 0))
                lineMapper._useWireFrame = True

                # 'noqa' comments disable pep8 checking for these lines. There
                # is not a readable way to shorten them due to the unwieldly
                # method name.
                #
                # Setup depth resolution so lines stay above points:
                polyMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(0, 1)  # noqa
                polyMapper.SetResolveCoincidentTopologyToPolygonOffset()
                lineMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(1, 1)  # noqa
                lineMapper.SetResolveCoincidentTopologyToPolygonOffset()
                lineMapper.SetLookupTable(wireLUT)

                lineMappers.append(lineMapper)
            mappers.extend(lineMappers)

        # And now we need actors to actually render this thing
        actors = []
        vp = self._resultDict.get(
            'ratio_autot_viewport',
            [self._template.data.x1, self._template.data.x2,
             self._template.data.y1, self._template.data.y2])
        dataset_renderer = None
        xScale, yScale = (1, 1)
        for mapper in mappers:
            act = vtk.vtkActor()
            act.SetMapper(mapper)

            if hasattr(mapper, "_useWireFrame"):
                prop = act.GetProperty()
                prop.SetRepresentationToWireframe()

            if self._vtkGeoTransform is None:
                # If using geofilter on wireframed does not get wrppaed not
                # sure why so sticking to many mappers
                act = vcs2vtk.doWrap(act, plotting_dataset_bounds,
                                     self._dataWrapModulo)

            # TODO See comment in boxfill.
            if mapper is self._maskedDataMapper:
                actors.append([act, self._maskedDataMapper, plotting_dataset_bounds])
            else:
                actors.append([act, plotting_dataset_bounds])

            # create a new renderer for this mapper
            # (we need one for each mapper because of cmaera flips)
            dataset_renderer, xScale, yScale = self._context().fitToViewport(
                act, vp,
                wc=plotting_dataset_bounds, geoBounds=self._vtkDataSet.GetBounds(),
                geo=self._vtkGeoTransform,
                priority=self._template.data.priority,
                create_renderer=(dataset_renderer is None))
        for act in self._patternActors:
            if self._vtkGeoTransform is None:
                # If using geofilter on wireframed does not get wrapped not sure
                # why so sticking to many mappers
                self._context().fitToViewport(
                    act, vp,
                    wc=plotting_dataset_bounds, geoBounds=self._vtkDataSet.GetBounds(),
                    geo=self._vtkGeoTransform,
                    priority=self._template.data.priority,
                    create_renderer=True)
                actors.append([act, plotting_dataset_bounds])

        self._resultDict["vtk_backend_actors"] = actors
        kwargs = {"vtk_backend_grid": self._vtkDataSet,
                  "dataset_bounds": self._vtkDataSetBounds,
                  "plotting_dataset_bounds": plotting_dataset_bounds,
                  "vtk_backend_geo": self._vtkGeoTransform}
        if ("ratio_autot_viewport" in self._resultDict):
            kwargs["ratio_autot_viewport"] = vp
        self._template.plot(self._context().canvas, self._data1, self._gm,
                            bg=self._context().bg,
                            X=numpy.arange(min(x1, x2),
                                           max(x1, x2) * 1.1,
                                           abs(x2 - x1) / 10.),
                            Y=numpy.arange(min(y1, y2),
                                           max(y1, y2) * 1.1,
                                           abs(y2 - y1) / 10.), **kwargs)

        legend = getattr(self._gm, "legend", None)

        if self._gm.ext_1:
            if isinstance(self._contourLevels[0], list):
                if numpy.less(abs(self._contourLevels[0][0]), 1.e20):
                    # Ok we need to add the ext levels
                    self._contourLevels.insert(
                        0, [-1.e20, self._contourLevels[0][0]])
            else:
                if numpy.less(abs(self._contourLevels[0]), 1.e20):
                    # need to add an ext
                    self._contourLevels.insert(0, -1.e20)
        if self._gm.ext_2:
            if isinstance(self._contourLevels[-1], list):
                if numpy.less(abs(self._contourLevels[-1][1]), 1.e20):
                    # need ext
                    self._contourLevels.append([self._contourLevels[-1][1],
                                                1.e20])
            else:
                if numpy.less(abs(self._contourLevels[-1]), 1.e20):
                    # need exts
                    self._contourLevels.append(1.e20)

        patternArgs = {}
        patternArgs['style'] = self._gm.fillareastyle
        patternArgs['index'] = self._gm.fillareaindices
        if patternArgs['index'] is None:
            patternArgs['index'] = [1, ]
        patternArgs['opacity'] = self._gm.fillareaopacity
        self._resultDict.update(
            self._context().renderColorBar(self._template, self._contourLevels,
                                           self._contourColors,
                                           legend,
                                           self.getColorMap(),
                                           **patternArgs))

        if self._context().canvas._continents is None:
            self._useContinents = False
        if self._useContinents:
            projection = vcs.elements["projection"][self._gm.projection]
            continents_renderer, xScale, yScale = self._context().plotContinents(
                plotting_dataset_bounds, projection,
                self._dataWrapModulo,
                vp, self._template.data.priority,
                vtk_backend_grid=self._vtkDataSet,
                dataset_bounds=self._vtkDataSetBounds)
Example #55
0
 def return_animation_min_max(self):
     dpy, slab = self.vcs_self.animate_info[0]
     return vcs.minmax(slab)