Beispiel #1
0
  def plot2D(self,data1,data2,tmpl,gm):
    ug,xm,xM,ym,yM,continents,wrap,geo,cellData = vcs2vtk.genGrid(data1,data2,gm)
    #Now applies the actual data on each cell
    if isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="log10":
        data1=numpy.ma.log10(data1)
    data = VN.numpy_to_vtk(data1.filled(0.).flat,deep=True)
    if cellData:
        ug.GetCellData().SetScalars(data)
    else:
        ug.GetPointData().SetScalars(data)
    
    try:
      cmap = vcs.elements["colormap"][cmap]
    except:
      cmap = vcs.elements["colormap"][self.canvas.getcolormapname()]

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

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


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

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

        
        for i,l in enumerate(LEVS):
          # Ok here we are trying to group together levels can be, a join will happen if:
          # next set of levels contnues where one left off AND pattern is identical
           
          if isinstance(gm,isofill.Gfi):
              mapper = vtk.vtkPolyDataMapper()
              lut = vtk.vtkLookupTable()
              cot = vtk.vtkBandedPolyDataContourFilter()
              cot.ClippingOn()
              cot.SetInputData(sFilter.GetOutput())
              cot.SetNumberOfContours(len(l))
              for j,v in enumerate(l):
                  cot.SetValue(j,v)
              #cot.SetScalarModeToIndex()
              cot.Update()
              mapper.SetInputConnection(cot.GetOutputPort())
              lut.SetNumberOfTableValues(len(COLS[i]))
              for j,color in enumerate(COLS[i]):
                  r,g,b = cmap.index[color]      
                  lut.SetTableValue(j,r/100.,g/100.,b/100.)
                  #print l[j],vcs.colors.rgb2str(r*2.55,g*2.55,b*2.55),l[j+1]
              mapper.SetLookupTable(lut)
              mapper.SetScalarRange(0,len(l)-1)
              mapper.SetScalarModeToUseCellData()
          else:
              for j,color in enumerate(COLS[i]):
                  mapper = vtk.vtkPolyDataMapper()
                  lut = vtk.vtkLookupTable()
                  th = vtk.vtkThreshold()
                  th.ThresholdBetween(l[j],l[j+1])
                  th.SetInputConnection(geoFilter.GetOutputPort())
                  geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                  geoFilter2.SetInputConnection(th.GetOutputPort())
                  mapper.SetInputConnection(geoFilter2.GetOutputPort())
                  lut.SetNumberOfTableValues(1)
                  r,g,b = cmap.index[color]      
                  lut.SetTableValue(0,r/100.,g/100.,b/100.)
                  mapper.SetLookupTable(lut)
                  mapper.SetScalarRange(l[j],l[j+1])
                  mappers.append([mapper,])

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

    else: #Boxfill (non custom)/Meshfill
      if isinstance(gm,boxfill.Gfb):
        if numpy.allclose(gm.level_1,1.e20) or numpy.allclose(gm.level_2,1.e20):
          levs = vcs.mkscale(mn,mx)
          legend = vcs.mklabels(levs)
          dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1)
          levs = numpy.arange(levs[0],levs[-1]+dx,dx)
        else:
          if gm.boxfill_type=="log10":
              levs = vcs.mkscale(numpy.ma.log10(gm.level_1),numpy.ma.log10(gm.level_2))
          else:
              levs = vcs.mkscale(gm.level_1,gm.level_2)
          legend = vcs.mklabels(levs)
          if gm.boxfill_type=="log10":
              for k in legend.keys():
                  legend[float(numpy.ma.log10(legend[k]))] = legend[k]
                  del(legend[k])
          dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1)
          levs = numpy.arange(levs[0],levs[-1]+dx,dx)

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

    if mappers == []: # ok didn't need to have special banded contours
      mappers=[mapper,]
      ## Colortable bit
      # make sure length match
      while len(cols)<Ncolors:
        cols.append(cols[-1])
      
      lut.SetNumberOfTableValues(Ncolors)
      for i in range(Ncolors):
        r,g,b = cmap.index[cols[i]]
        lut.SetTableValue(i,r/100.,g/100.,b/100.)

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

    if missingMapper is not None:
        mappers.insert(0,missingMapper)

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

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

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

      self.renderColorBar(tmpl,levs,cols,legend,cmap)
    if self.canvas._continents is None:
      continents = False
    if continents:
        projection = vcs.elements["projection"][gm.projection]
        self.plotContinents(x1,x2,y1,y2,projection,wrap,tmpl)
Beispiel #2
0
  def plotVector(self,data1,data2,tmpl,gm):
    ug,xm,xM,ym,yM,continents,wrap,geo,cellData = vcs2vtk.genGrid(data1,data2,gm)
    if cellData:
        c2p = vtk.vtkCellDataToPointData()
        c2p.SetInputData(ug)
        c2p.Update()
        #For contouring duplicate points seem to confuse it
        if ug.IsA("vtkUnstructuredGrid"):
            cln = vtk.vtkCleanUnstructuredGrid()
            cln.SetInputConnection(c2p.GetOutputPort())

    missingMapper = vcs2vtk.putMaskOnVTKGrid(data1,ug,None,cellData)

    u=numpy.ma.ravel(data1)
    v=numpy.ma.ravel(data2)
    sh = list(u.shape)
    sh.append(1)
    u = numpy.reshape(u,sh)
    v = numpy.reshape(v,sh)
    z = numpy.zeros(u.shape)
    w = numpy.concatenate((u,v),axis=1)
    w = numpy.concatenate((w,z),axis=1)
    w = VN.numpy_to_vtk(w,deep=True)
    w.SetName("vectors")
    ug.GetPointData().AddArray(w)
    ## Vector attempt
    arrow = vtk.vtkArrowSource()
    l = gm.line
    if l is None:
        l = "default"
    try:
      l = vcs.getline(l)
      lwidth = l.width[0]
      lcolor = l.color[0]
      lstyle = l.type[0]
    except:
      lstyle = "solid"
      lwidth = 1.
      lcolor = 0
    if gm.linewidth is not None:
        lwidth = gm.linewidth
    if gm.linecolor is not None:
        lcolor = gm.linecolor


    arrow.SetTipRadius(.1*lwidth)
    arrow.SetShaftRadius(.03*lwidth)
    arrow.Update()
    glyphFilter = vtk.vtkGlyph2D()
    glyphFilter.SetSourceConnection(arrow.GetOutputPort())
    glyphFilter.OrientOn()
    glyphFilter.SetVectorModeToUseVector()
    glyphFilter.SetInputArrayToProcess(1,0,0,0,"vectors")
    glyphFilter.SetScaleFactor(2.*gm.scale)
    if cellData:
        if ug.IsA("vtkUnstructuredGrid"):
            glyphFilter.SetInputConnection(cln.GetOutputPort())
        else:
            glyphFilter.SetInputConnection(c2p.GetOutputPort())
    else:
        glyphFilter.SetInputData(ug)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyphFilter.GetOutputPort())
    act = vtk.vtkActor()
    act.SetMapper(mapper)
    try:
      cmap = vcs.elements["colormap"][cmap]
    except:
      cmap = vcs.elements["colormap"][self.canvas.getcolormapname()]
    r,g,b = cmap.index[lcolor]
    act.GetProperty().SetColor(r/100.,g/100.,b/100.)
    x1,x2,y1,y2 = vcs2vtk.getRange(gm,xm,xM,ym,yM)
    act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap)
    ren=vtk.vtkRenderer()
    self.renWin.AddRenderer(ren)
    self.setLayer(ren,tmpl.data.priority)
    vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],[x1,x2,y1,y2])
    if tmpl.data.priority!=0:
        ren.AddActor(act)
    self.renderTemplate(tmpl,data1,gm)
    if self.canvas._continents is None:
      continents = False
    if continents:
        projection = vcs.elements["projection"][gm.projection]
        self.plotContinents(x1,x2,y1,y2,projection,wrap,tmpl)