def save_style(self, style): current_obj = self.style_editor.textObject style = str(style) if style == current_obj.name: to_name = current_obj.To_name to_src = "default" tt_name = current_obj.Tt_name tt_src = "default" else: to_name = style to_src = current_obj.To_name tt_name = style tt_src = current_obj.Tt_name try: to = vcs.gettextorientation(to_name) except ValueError: to = vcs.createtextorientation(name=to_name, source=to_src) try: tt = vcs.gettexttable(tt_name) except ValueError: tt = vcs.createtexttable(name=tt_name, source=tt_src) get_textstyles().updated(tt_name) self.current_member.texttable = tt self.current_member.textorientation = to self.current_member = None self.sync() self.labelUpdated.emit()
def __init__(self): self.x1 = .12 self.x2 = .84 self.y1 = .17 self.y2 = .8 self.levels = None self.colormap = None self.fillareacolors = None self.legend = XYs(.89, .91, self.y1, self.y2) # X ticks self.xticorientation = vcs.createtextorientation() self.xticorientation.angle = 360 - 90 self.xticorientation.halign = 'right' self.xticorientation.height = 10 # Y ticks self.yticorientation = vcs.createtextorientation() self.yticorientation.angle = 0 self.yticorientation.halign = 'right' self.yticorientation.height = 10 # Ticks table self.tictable = vcs.createtexttable() # parameters text settings self.parameterorientation = vcs.createtextorientation() self.parameterorientation.angle = 0 self.parameterorientation.halign = 'center' self.parameterorientation.height = 20 self.parametertable = vcs.createtexttable() # values in cell setting self.values = Values() # Defaults self.draw_mesh = 'y' self.missing_color = 3 self.xtic1 = Ys(None, None) self.xtic2 = Ys(None, None) self.ytic1 = Xs(None, None) self.ytic2 = Xs(None, None) # Set the logo textorientation self.logo = None # Set the time stamp time_stamp = vcs.createtext() time_stamp.height = 10 time_stamp.halign = 'center' time_stamp.path = 'right' time_stamp.valign = 'half' time_stamp.x = [0.9] time_stamp.y = [0.96] self.time_stamp = time_stamp
def __init__(self, interactor, label, dp, configurator): self.label = label self.display = dp super(LabelEditor, self).__init__(interactor, label, configurator) self.toolbar = vcs.vtk_ui.Toolbar( self.interactor, "%s Options" % label.member) template = vcs.gettemplate(dp.template) self.actor = get_actor(self.label, self.display) tprop = self.actor.GetTextProperty() self.real_bg = tprop.GetBackgroundColor() self.real_bg_opacity = tprop.GetBackgroundOpacity() tprop.SetBackgroundColor(contrasting_color(*tprop.GetColor())) tprop.SetBackgroundOpacity(.85) text_types_name = template.name + "_" + label.member try: self.tt = vcs.gettexttable(text_types_name) self.to = vcs.gettextorientation(text_types_name) except ValueError: self.tt = vcs.createtexttable(text_types_name, label.texttable) self.to = vcs.createtextorientation( text_types_name, label.textorientation) self.height_button = self.toolbar.add_slider_button( self.to.height, 1, 100, "Height", update=self.update_height) halign = self.toolbar.add_button( ["Left Align", "Center Align", "Right Align"], action=self.halign) valign = self.toolbar.add_button( ["Top Align", "Half Align", "Bottom Align"], action=self.valign) halign.set_state(self.to.halign) valign.set_state(__valign_map__[self.to.valign]) self.angle_button = self.toolbar.add_slider_button( self.to.angle, 0, 360, "Angle", update=self.update_angle) self.picker = None self.toolbar.add_button(["Change Color"], action=self.change_color) self.toolbar.show() self.label.texttable = self.tt.name self.label.textorientation = self.to.name
def __init__(self, interactor, label, dp, configurator): self.label = label self.display = dp super(LabelEditor, self).__init__(interactor, label, configurator) self.toolbar = vcs.vtk_ui.Toolbar(self.interactor, "%s Options" % label.member) template = vcs.gettemplate(dp.template) self.actor = get_actor(self.label, self.display) tprop = self.actor.GetTextProperty() self.real_bg = tprop.GetBackgroundColor() self.real_bg_opacity = tprop.GetBackgroundOpacity() tprop.SetBackgroundColor(contrasting_color(*tprop.GetColor())) tprop.SetBackgroundOpacity(.85) text_types_name = template.name + "_" + label.member try: self.tt = vcs.gettexttable(text_types_name) self.to = vcs.gettextorientation(text_types_name) except ValueError: self.tt = vcs.createtexttable(text_types_name, label.texttable) self.to = vcs.createtextorientation(text_types_name, label.textorientation) self.height_button = self.toolbar.add_slider_button( self.to.height, 1, 100, "Height", update=self.update_height) halign = self.toolbar.add_button( ["Left Align", "Center Align", "Right Align"], action=self.halign) valign = self.toolbar.add_button( ["Top Align", "Half Align", "Bottom Align"], action=self.valign) halign.set_state(self.to.halign) valign.set_state(__valign_map__[self.to.valign]) self.angle_button = self.toolbar.add_slider_button( self.to.angle, 0, 360, "Angle", update=self.update_angle) self.picker = None self.toolbar.add_button(["Change Color"], action=self.change_color) # Adds itself to self.toolbar automatically FontEditor(self.toolbar, self.set_font, current_font=vcs.getfontname(self.tt.font)) self.toolbar.show() self.label.texttable = self.tt.name self.label.textorientation = self.to.name
def testVCSreset1only(self): for gtype in vcs.listelements(): b0 = vcs.listelements(gtype) if gtype == 'colormap': b = vcs.createcolormap() xtra = vcs.createisofill() untouched = vcs.listelements("isofill") elif gtype == "template": b = vcs.createtemplate() elif gtype == "textcombined": b = vcs.createtextcombined() elif gtype == "textorientation": b = vcs.createtextorientation() elif gtype == "texttable": b = vcs.createtexttable() elif gtype == "fillarea": b = vcs.createfillarea() elif gtype == "projection": b = vcs.createprojection() elif gtype == "marker": b = vcs.createmarker() elif gtype == "line": b = vcs.createline() elif gtype in ["display", "font", "fontNumber", "list", "format"]: vcs.manageElements.reset() continue else: b = vcs.creategraphicsmethod(gtype) if gtype != "colormap": xtra = vcs.createcolormap() untouched = vcs.listelements("colormap") b1 = vcs.listelements(gtype) self.assertNotEqual(b0, b1) vcs.manageElements.reset(gtype) b2 = vcs.listelements(gtype) self.assertEqual(b0, b2) if gtype == "colormap": self.assertEqual(untouched, vcs.listelements("isofill")) else: self.assertEqual(untouched, vcs.listelements("colormap")) vcs.manageElements.reset() if gtype == "colormap": self.assertNotEqual(untouched, vcs.listelements("isofill")) else: self.assertNotEqual(untouched, vcs.listelements("colormap")) # case for 1d weirdness sc = vcs.createscatter() vcs.manageElements.reset()
def __init__(self, interactor, label, dp, configurator): self.label = label self.display = dp super(LabelEditor, self).__init__(interactor, label, configurator) self.toolbar = vcs.vtk_ui.Toolbar(self.interactor, "%s Options" % label.member) template = vcs.gettemplate(dp.template) self.actor = get_actor(self.label, self.display) text_types_name = template.name + "_" + label.member try: self.tt = vcs.gettexttable(text_types_name) self.to = vcs.gettextorientation(text_types_name) except ValueError: self.tt = vcs.createtexttable(text_types_name, label.texttable) self.to = vcs.createtextorientation(text_types_name, label.textorientation) self.height_button = self.toolbar.add_slider_button( self.to.height, 1, 100, "Height", update=self.update_height) halign = self.toolbar.add_button( ["Left Align", "Center Align", "Right Align"], action=self.halign) valign = self.toolbar.add_button( ["Top Align", "Half Align", "Bottom Align"], action=self.valign) halign.set_state(self.to.halign) valign.set_state(__valign_map__[self.to.valign]) self.angle_button = self.toolbar.add_slider_button( self.to.angle, 0, 360, "Angle", update=self.update_angle) font_editor = FontEditor(self.toolbar, self.set_font, vcs.elements["fontNumber"][self.tt.font]) self.picker = None self.toolbar.add_button(["Change Color"], action=self.change_color) self.toolbar.show() self.label.texttable = self.tt.name self.label.textorientation = self.to.name
def __init__(self, interactor, label, dp, configurator): self.label = label self.display = dp super(LabelEditor, self).__init__(interactor, label, configurator) self.toolbar = vcs.vtk_ui.Toolbar(self.interactor, "%s Options" % label.member) template = vcs.gettemplate(dp.template) self.actor = get_actor(self.label, self.display) text_types_name = template.name + "_" + label.member try: self.tt = vcs.gettexttable(text_types_name) self.to = vcs.gettextorientation(text_types_name) except ValueError: self.tt = vcs.createtexttable(text_types_name, label.texttable) self.to = vcs.createtextorientation(text_types_name, label.textorientation) self.height_button = self.toolbar.add_slider_button(self.to.height, 1, 100, "Height", update=self.update_height) halign = self.toolbar.add_button(["Left Align", "Center Align", "Right Align"], action=self.halign) valign = self.toolbar.add_button(["Top Align", "Half Align", "Bottom Align"], action=self.valign) halign.set_state(self.to.halign) valign.set_state(__valign_map__[self.to.valign]) self.angle_button = self.toolbar.add_slider_button(self.to.angle, 0, 360, "Angle", update=self.update_angle) font_editor = FontEditor(self.toolbar, self.set_font, vcs.elements["fontNumber"][self.tt.font]) self.picker = None self.toolbar.add_button(["Change Color"], action=self.change_color) self.toolbar.show() self.label.texttable = self.tt.name self.label.textorientation = self.to.name
def _plotInternal(self): """Overrides baseclass implementation.""" numLevels = len(self._contourLevels) cot = vtk.vtkContourFilter() if self._useCellScalars: cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) else: cot.SetInputData(self._vtkDataSet) cot.SetNumberOfContours(numLevels) if self._contourLevels[0] == 1.e20: self._contourLevels[0] = -1.e20 for i in range(numLevels): cot.SetValue(i, self._contourLevels[i]) cot.SetValue(numLevels, self._contourLevels[-1]) # TODO remove update cot.Update() mappers = [] lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(self._contourColors)) cmap = self._context().canvas.getcolormapname() cmap = vcs.elements["colormap"][cmap] for i, col in enumerate(self._contourColors): r, g, b = cmap.index[col] lut.SetTableValue(i, r / 100., g / 100., b / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for i, val in enumerate(self._contourLevels): tpropMap.SetTuple(i, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < numLevels: texts.append(texts[-1]) else: texts = [None] * len(self._gm.textcolors) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < numLevels: colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) for tc, colorOverride in zip(texts, colorOverrides): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" if colorOverride is not None: tt = vcs.createtexttable(None, tt) tt.color = colorOverride tt = tt.name tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), to, tt) tprops.AddItem(tprop) if colorOverride is not None: del(vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize()) tprops.AddItem(tprop) self._resultDict["vtk_backend_contours_labels_text_properties"] = \ tprops mapper = vtk.vtkLabeledContourMapper() mapper.SetTextProperties(tprops) mapper.SetTextPropertyMapping(tpropMap) mapper.SetLabelVisibility(1) mapper.SetSkipDistance(self._gm.labelskipdistance) pdMapper = mapper.GetPolyDataMapper() self._resultDict["vtk_backend_labeled_luts"] = [ [lut, [self._contourLevels[0], self._contourLevels[-1], False]]] else: # No isoline labels: mapper = vtk.vtkPolyDataMapper() pdMapper = mapper self._resultDict["vtk_backend_luts"] = \ [[lut, [self._contourLevels[0], self._contourLevels[-1], False]]] pdMapper.SetLookupTable(lut) pdMapper.SetScalarRange(self._contourLevels[0], self._contourLevels[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() mappers.append(mapper) self._resultDict["vtk_backend_contours"] = [cot] if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) x1, x2, y1, y2 = vcs.utils.getworldcoordinates(self._gm, self._data1.getAxis(-1), self._data1.getAxis(-2)) # And now we need actors to actually render this thing actors = [] for mapper in mappers: act = vtk.vtkActor() act.SetMapper(mapper) 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 t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None self._resultDict.update(self._context().renderTemplate(self._template, self._data1, self._gm, t, z)) 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)
def plot_portrait( stat_xy, # array to visualize imgName='portrait_plot', # file name plotTitle=None, # title string on top img_length=800, img_height=600, # image size in pixel colormap='viridis', clevels=None, ccolors=None, # colormap and levels xtic_textsize=None, ytic_textsize=None, # font size for axes tic labels parea=None, # plotting area in ratio, in purpose of margin control missing_color='black', # color for missing data box Annotate=False, stat_xy_annotate=None, # annotation (showing value number in each box) num_box_partitioning=1, stat_xy_2=None, stat_xy_3=None, stat_xy_4=None, # additional triangle logo=True, GridMeshLine=True, # miscellaneous ): """ NOTE: Input - stat_xy: cdms2 MV2 2D array with proper axes decorated, values to visualize. - imgName: string, file name for PNG image file (e.g., 'YOUR_PLOT.png' or 'YOUR_PLOT'. If .png is not included, it will be added, so no worry). - plotTilte: string - img_length: integer, pixels for image file length. default=800. - img_height: integer, pixels for image file height. default=600. - colormap: string or actual VCS colormap. Default is 'viridis' that is default in VCS. - clevels: list of numbers (int or float). Colorbar levels. If not given automatically generated. - ccolors: list of colors. If not given automatically generate. - xtic_textsize: int, size of text for x-axis tic. If not given automatically generated. - ytic_textsize: int, size of text for y-axis tic. If not given automatically generated. - parea: list or tuple of float numbers between 0 to 1. Plotting area: (x1, x2, y1, y2). If not given automatically placed. - missing_color: string or color code (tuple or list of R, G, B, alpha). Color for missing data box. Default is 'black' - Annotate: bool, default=False. If Annotate, show numbers in individual boxes. - stat_xy_annotate: cdms2 MV2 2D array with proper axes decorated. Only needed when number to show as value annotated is not corresponding to the colormap. Not even bother when Annotate=False. For example, color for values those normalized by median, while annotate actual value for metrics. - num_box_partitioning: integer. How many partitioning in a box? e.g., 4: 4 triangles in each box. Default=1, should be less equal than 4. - stat_xy_2: cdms2 MV2 2D array. Stat for 2nd triangle in box. Default=None - stat_xy_3: cdms2 MV2 2D array. Stat for 3rd triangle in box. Default=None - stat_xy_4: cdms2 MV2 2D array. Stat for 4th triangle in box. Default=None - logo: bool, default=True. If False, CDAT logo turned off - GridMeshLine: bool, default=True. If False, no lines for boundary of individual boxes Output - PNG image file """ # VCS Canvas x = vcs.init(bg=True, geometry=(img_length, img_height)) # CDAT logo control if not logo: x.drawlogooff() # Set up Portrait Plot """ If you are NOT using JUPYTER NOTEBOOK, it is okay to DEACTIVATE below line and ACTIVATE second below line, and skip the "Prepare the Notebook" part above. """ #P = PortraitNotebook(x) P = pcmdi_metrics.graphics.portraits.Portrait() # # Preprocessing step to "decorate" the axis # axes = stat_xy.getAxisList() xax = [t + ' ' for t in list(axes[1][:])] yax = [t + ' ' for t in list(axes[0][:])] P.decorate(stat_xy, yax, xax) # # Customize # SET = P.PLOT_SETTINGS # Viewport on the Canvas if parea is not None: SET.x1, SET.x2, SET.y1, SET.y2 = parea # Both X (horizontal) and y (VERTICAL) ticks # Text table SET.tictable = vcs.createtexttable() SET.tictable.color = "black" # X (bottom) ticks # Text Orientation SET.xticorientation = vcs.createtextorientation() SET.xticorientation.angle = -90 SET.xticorientation.halign = "right" if xtic_textsize: SET.xticorientation.height = xtic_textsize # Y (vertical) ticks SET.yticorientation = vcs.createtextorientation() SET.yticorientation.angle = 0 SET.yticorientation.halign = "right" if ytic_textsize: SET.yticorientation.height = ytic_textsize # We can turn off the "grid" if needed if GridMeshLine: SET.draw_mesh = "y" else: SET.draw_mesh = "n" # Color for missing data SET.missing_color = missing_color # Timestamp SET.time_stamp = None # Colormap SET.colormap = colormap if clevels: SET.levels = clevels if ccolors: SET.fillareacolors = ccolors # Annotated Plot (i.e. show value number in boxes) if Annotate: SET.values.show = True if stat_xy_annotate is None: SET.values.array = stat_xy else: SET.values.array = stat_xy_annotate # Check before plotting if num_box_partitioning > 4: sys.exit('ERROR: num_box_partitioning should be less equal than 4') # # Plot # P.plot(stat_xy, multiple=pp_multiple(1, num_box_partitioning), x=x) # Add triangles if needed # Decorate additional arrays with empty string axes to avoid overwriting same information (if not, font will look ugly) xax_empty = [' ' for t in stat_xy.getAxis(1)[:]] yax_empty = [' ' for t in stat_xy.getAxis(0)[:]] if stat_xy_2 is not None: P.decorate(stat_xy_2, yax_empty, xax_empty) P.plot(stat_xy_2, x=x, multiple=pp_multiple(2, num_box_partitioning)) if stat_xy_3 is not None: P.decorate(stat_xy_3, yax_empty, xax_empty) P.plot(stat_xy_3, x=x, multiple=pp_multiple(3, num_box_partitioning)) if stat_xy_4 is not None: P.decorate(stat_xy_4, yax_empty, xax_empty) P.plot(stat_xy_4, x=x, multiple=pp_multiple(4, num_box_partitioning)) # Plot title if plotTitle: plot_title = vcs.createtext() plot_title.x = .5 plot_title.y = (SET.y2 + 1) / 2. plot_title.height = 30 plot_title.halign = 'center' plot_title.valign = 'half' plot_title.color = 'black' plot_title.string = plotTitle x.plot(plot_title) # Save if imgName.split('.')[-1] not in ['PNG', 'png']: imgName = imgName + '.png' x.png(imgName) # Preserve original axes stat_xy.setAxisList(axes) return P
def _plotInternal(self): """Overrides baseclass implementation.""" tmpLevels = [] tmpColors = [] tmpLineWidths = [] tmpLineTypes = [] linewidth = self._gm.linewidths self.extendAttribute(linewidth, default=1.0) linetype = self._gm.linetypes self.extendAttribute(linetype, default='solid') plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds for i, lv_tmp in enumerate(self._contourLevels): if i == 0: W = linewidth[i] S = linetype[i] C = [self._contourColors[i]] if lv_tmp == 1.e20: L = [-1.e20] else: L = [lv_tmp] else: if W == linewidth[i] and S == linetype[i]: # Ok same style and width, lets keep going L.append(lv_tmp) C.append(self._contourColors[i]) else: tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) L = [lv_tmp] C = [self._contourColors[i]] W = linewidth[i] S = linetype[i] tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) cots = [] textprops = [] luts = [] actors = [] mappers = [] if self._gm.label and (self._gm.text or self._gm.textcolors): # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < len(self._contourLevels): texts.append(texts[-1]) else: texts = [None] * len(self._contourLevels) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < len(self._contourLevels): colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) # Custom background colors and opacities: backgroundColors = self._gm.labelbackgroundcolors if backgroundColors: while len(backgroundColors) < len(self._contourLevels): backgroundColors.append(backgroundColors[-1]) backgroundOpacities = self._gm.labelbackgroundopacities if backgroundOpacities: while len(backgroundOpacities) < len(self._contourLevels): backgroundOpacities.append(backgroundOpacities[-1]) countLevels = 0 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 i, l in enumerate(tmpLevels): numLevels = len(l) cot = vtk.vtkContourFilter() if self._hasCellData: cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) else: cot.SetInputData(self._vtkDataSet) cot.SetNumberOfContours(numLevels) for n in range(numLevels): cot.SetValue(n, l[n]) # TODO remove update cot.Update() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(tmpColors[i])) cmap = self.getColorMap() for n, col in enumerate(tmpColors[i]): r, g, b, a = self.getColorIndexOrRGBA(cmap, col) lut.SetTableValue(n, r / 100., g / 100., b / 100., a / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for n, val in enumerate(l): tpropMap.SetTuple(n, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: ttexts = texts[countLevels:(countLevels + len(l))] for idx, tc in enumerate(ttexts): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" elif isinstance(tc, str): sp = tc.split(":::") if len(sp) == 2: tt = sp[0] to = sp[1] else: # Hum don't know what do do with this if sp[0] in vcs.listelements("textcombined"): tc = vcs.gettextcombined(tc) tt, to = tuple(tc.name.split(":::")) elif sp[0] in vcs.listelements( "textorientation"): to = sp[0] tt = "default" elif sp[0] in vcs.listelements("texttable"): tt = sp[0] to = "default" colorOverride = colorOverrides[countLevels + idx] if colorOverride is not None: tt = vcs.createtexttable(None, tt) tt.color = colorOverride tt = tt.name if backgroundColors is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundcolor = backgroundColors[ countLevels + idx] if backgroundOpacities is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundopacity = backgroundOpacities[ countLevels + idx] tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty( tprop, self._context().renWin.GetSize(), to, tt, cmap=cmap) tprops.AddItem(tprop) if colorOverride is not None: del (vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), cmap=cmap) tprops.AddItem(tprop) textprops.append(tprops) mapper = vtk.vtkLabeledContourMapper() mapper.SetTextProperties(tprops) mapper.SetTextPropertyMapping(tpropMap) mapper.SetLabelVisibility(1) mapper.SetSkipDistance(self._gm.labelskipdistance) pdMapper = mapper.GetPolyDataMapper() luts.append([lut, [l[0], l[-1], False]]) else: # No isoline labels: mapper = vtk.vtkPolyDataMapper() pdMapper = mapper luts.append([lut, [l[0], l[-1], False]]) pdMapper.SetLookupTable(lut) pdMapper.SetScalarRange(l[0], l[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() mappers.append(mapper) cots.append(cot) # Create actor to add to scene act = vtk.vtkActor() act.SetMapper(mapper) # Set line properties here p = act.GetProperty() p.SetLineWidth(tmpLineWidths[i]) vcs2vtk.stippleLine(p, tmpLineTypes[i]) 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._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=(dataset_renderer is None)) countLevels += len(l) if len(textprops) > 0: self._resultDict["vtk_backend_contours_labels_text_properties"] = \ textprops if len(luts) > 0: if self._gm.label: self._resultDict["vtk_backend_labeled_luts"] = luts else: self._resultDict["vtk_backend_luts"] = luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) act = vtk.vtkActor() act.SetMapper(self._maskedDataMapper) actors.append( [act, self._maskedDataMapper, plotting_dataset_bounds]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) self._resultDict["vtk_backend_actors"] = actors t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None 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, **kwargs)) 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)
def _plotInternal(self): """Overrides baseclass implementation.""" numLevels = len(self._contourLevels) cot = vtk.vtkContourFilter() if self._useCellScalars: cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) else: cot.SetInputData(self._vtkDataSet) cot.SetNumberOfContours(numLevels) if self._contourLevels[0] == 1.e20: self._contourLevels[0] = -1.e20 for i in range(numLevels): cot.SetValue(i, self._contourLevels[i]) cot.SetValue(numLevels, self._contourLevels[-1]) # TODO remove update cot.Update() mappers = [] lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(self._contourColors)) cmap = vcs.elements["colormap"][self._context.canvas.getcolormapname()] for i, col in enumerate(self._contourColors): r, g, b = cmap.index[col] lut.SetTableValue(i, r / 100., g / 100., b / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for i, val in enumerate(self._contourLevels): tpropMap.SetTuple(i, [ val, ]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < numLevels: texts.append(texts[-1]) else: texts = [None] * len(self._gm.textcolors) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < numLevels: colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) for tc, colorOverride in zip(texts, colorOverrides): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" if colorOverride is not None: tt = vcs.createtexttable(None, tt) tt.color = colorOverride tt = tt.name tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context.renWin.GetSize(), to, tt) tprops.AddItem(tprop) if colorOverride is not None: del (vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context.renWin.GetSize()) tprops.AddItem(tprop) self._resultDict["vtk_backend_contours_labels_text_properties"] = \ tprops mapper = vtk.vtkLabeledContourMapper() mapper.SetTextProperties(tprops) mapper.SetTextPropertyMapping(tpropMap) mapper.SetLabelVisibility(1) pdMapper = mapper.GetPolyDataMapper() self._resultDict["vtk_backend_labeled_luts"] = [[ lut, [self._contourLevels[0], self._contourLevels[-1], False] ]] else: # No isoline labels: mapper = vtk.vtkPolyDataMapper() pdMapper = mapper self._resultDict["vtk_backend_luts"] = [[ lut, [self._contourLevels[0], self._contourLevels[-1], False] ]] pdMapper.SetLookupTable(lut) pdMapper.SetScalarRange(self._contourLevels[0], self._contourLevels[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() mappers.append(mapper) self._resultDict["vtk_backend_contours"] = [ cot, ] if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) x1, x2, y1, y2 = vcs.utils.getworldcoordinates(self._gm, self._data1.getAxis(-1), self._data1.getAxis(-2)) # And now we need actors to actually render this thing actors = [] for mapper in mappers: act = vtk.vtkActor() act.SetMapper(mapper) 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 t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None self._resultDict.update( self._context.renderTemplate(self._template, self._data1, self._gm, t, z)) 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)
def generate_portrait(stat_xy, imgName): # Get median median = genutil.statistics.median(stat_xy, axis=1)[0] print(median) print(median.shape) # Match shapes stat_xy, median = genutil.grower(stat_xy, median) print(stat_xy.shape) print(median.shape) # Normalize by median value median = np.array(median) stat_xy_normalized = MV2.divide(MV2.subtract(stat_xy, median), median) print(stat_xy_normalized.shape) stat_xy_normalized.setAxisList(stat_xy.getAxisList()) # # Plotting # # Set up VCS Canvas class VCSAddonsNotebook(object): def __init__(self, x): self.x = x def _repr_png_(self): fnm = tempfile.mktemp() + ".png" self.x.png(fnm) encoded = base64.b64encode(open(fnm, "rb").read()) return encoded def __call__(self): return self # VCS Canvas x = vcs.init(bg=True, geometry=(2600, 800)) show = VCSAddonsNotebook(x) # Load our "pretty" colormap x.scriptrun( os.path.join(sys.prefix, "share", "pmp", "graphics", 'vcs', 'portraits.scr')) # Set up Portrait Plot P = pcmdi_metrics.graphics.portraits.Portrait() xax = [t + ' ' for t in stat_xy_normalized.getAxis(1)[:]] yax = [t + ' ' for t in stat_xy_normalized.getAxis(0)[:]] # Preprocessing step to "decorate" the axis P.decorate(stat_xy_normalized, yax, xax) # # Customize # SET = P.PLOT_SETTINGS # Viewport on the Canvas SET.x1 = .05 SET.x2 = .88 SET.y1 = .25 SET.y2 = .9 # Both X (horizontal) and y (VERTICAL) ticks # Text table SET.tictable = vcs.createtexttable() SET.tictable.color = "black" # X (bottom) ticks tictextsize = 9 # Text Orientation SET.xticorientation = vcs.createtextorientation() SET.xticorientation.angle = -90 SET.xticorientation.halign = "right" SET.xticorientation.height = tictextsize # Y (vertical) ticks SET.yticorientation = vcs.createtextorientation() SET.yticorientation.angle = 0 SET.yticorientation.halign = "right" SET.yticorientation.height = tictextsize # We can turn off the "grid" SET.draw_mesh = "y" # Control color for missing SET.missing_color = "grey" # Tics length SET.xtic1.y1 = 0 SET.xtic1.y2 = 0 # Timestamp SET.time_stamp = None # Colormap SET.colormap = "bl_to_darkred" # level to use SET.levels = [-.5, -.4, -.3, -.2, -.1, 0, .1, .2, .3, .4, .5] SET.levels.insert(0, -1.e20) SET.levels.append(1.e20) # colors to use SET.fillareacolors = vcs.getcolors(SET.levels, split=0, colors=range(16, 240)) # Plot P.plot(stat_xy_normalized, x=x) # Save x.png(imgName + '.png') # # Annotated Plot # Annotated = False if Annotated: x.clear() SET.values.show = True SET.values.array = stat_xy P.plot(stat_xy_normalized, x=x, bg=0) x.png(imgName + '_annotated.png')
def _plotInternal(self): """Overrides baseclass implementation.""" tmpLevels = [] tmpColors = [] tmpLineWidths = [] tmpLineTypes = [] linewidth = self._gm.linewidths self.extendAttribute(linewidth, default=1.0) linetype = self._gm.linetypes self.extendAttribute(linetype, default='solid') plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds for i, lv_tmp in enumerate(self._contourLevels): if i == 0: W = linewidth[i] S = linetype[i] C = [self._contourColors[i]] if lv_tmp == 1.e20: L = [-1.e20] else: L = [lv_tmp] else: if W == linewidth[i] and S == linetype[i]: # Ok same style and width, lets keep going L.append(lv_tmp) C.append(self._contourColors[i]) else: tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) L = [lv_tmp] C = [self._contourColors[i]] W = linewidth[i] S = linetype[i] tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) cots = [] textprops = [] luts = [] actors = [] mappers = [] if self._gm.label and (self._gm.text or self._gm.textcolors): # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < len(self._contourLevels): texts.append(texts[-1]) else: texts = [None] * len(self._contourLevels) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < len(self._contourLevels): colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) # Custom background colors and opacities: backgroundColors = self._gm.labelbackgroundcolors if backgroundColors: while len(backgroundColors) < len(self._contourLevels): backgroundColors.append(backgroundColors[-1]) backgroundOpacities = self._gm.labelbackgroundopacities if backgroundOpacities: while len(backgroundOpacities) < len(self._contourLevels): backgroundOpacities.append(backgroundOpacities[-1]) else: backgroundOpacities = [100.0 for lev in self._contourLevels] countLevels = 0 vp = self._resultDict.get( 'ratio_autot_viewport', [self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2]) # 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) # FIXME: This render call is needed to work around a bug somewhere in the # FIXME: vtkContextTransform code, where the transformation represented by # FIXME: Map[To|From]Scene() isn't set up properly until after a render call. self._context().renWin.Render() for i, l in enumerate(tmpLevels): numLevels = len(l) cot = vtk.vtkContourFilter() cot.SetInputData(self._vtkDataSetFittedToViewport) cot.SetNumberOfContours(numLevels) for n in range(numLevels): cot.SetValue(n, l[n]) # TODO remove update cot.Update() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(tmpColors[i])) cmap = self.getColorMap() for n, col in enumerate(tmpColors[i]): r, g, b, a = self.getColorIndexOrRGBA(cmap, col) lut.SetTableValue(n, r / 100., g / 100., b / 100., a / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for n, val in enumerate(l): tpropMap.SetTuple(n, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: ttexts = texts[countLevels:(countLevels + len(l))] for idx, tc in enumerate(ttexts): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" elif isinstance(tc, str): sp = tc.split(":::") if len(sp) == 2: tt = sp[0] to = sp[1] else: # Hum don't know what do do with this if sp[0] in vcs.listelements("textcombined"): tc = vcs.gettextcombined(tc) tt, to = tuple(tc.name.split(":::")) elif sp[0] in vcs.listelements("textorientation"): to = sp[0] tt = "default" elif sp[0] in vcs.listelements("texttable"): tt = sp[0] to = "default" tt = vcs.createtexttable(None, tt) colorOverride = colorOverrides[countLevels + idx] if colorOverride is not None: tt.color = colorOverride tt = tt.name if backgroundColors is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundcolor = backgroundColors[countLevels + idx] if backgroundOpacities is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundopacity = backgroundOpacities[countLevels + idx] tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), to, tt, cmap=cmap) tprops.AddItem(tprop) if colorOverride is not None: del(vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), cmap=cmap) tprop.SetBackgroundOpacity(1.0) tprops.AddItem(tprop) textprops.append(tprops) item = vtk.vtkLabeledContourPolyDataItem() item.SetTextProperties(tprops) item.SetTextPropertyMapping(tpropMap) item.SetLabelVisibility(1) item.SetSkipDistance(self._gm.labelskipdistance) mapper = vtk.vtkLabeledContourMapper() pdMapper = mapper.GetPolyDataMapper() luts.append([lut, [l[0], l[-1], False]]) else: # No isoline labels: item = vtk.vtkPolyDataItem() mapper = vtk.vtkPolyDataMapper() pdMapper = mapper luts.append([lut, [l[0], l[-1], False]]) pdMapper.SetLookupTable(lut) lut.SetRange(l[0], l[-1]) pdMapper.SetScalarRange(l[0], l[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() poly = stripper.GetOutput() mappers.append(mapper) cots.append(cot) if self._needsCellData: attrs = poly.GetCellData() scalarMode = vtk.VTK_SCALAR_MODE_USE_CELL_DATA else: attrs = poly.GetPointData() scalarMode = vtk.VTK_SCALAR_MODE_USE_POINT_DATA data = attrs.GetScalars() mappedColors = lut.MapScalars(data, vtk.VTK_COLOR_MODE_DEFAULT, 0) intValue = vtk.vtkIntArray() intValue.SetNumberOfComponents(1) intValue.SetName("StippleType") intValue.InsertNextValue(vcs2vtk.getStipple(tmpLineTypes[i])) poly.GetFieldData().AddArray(intValue) floatValue = vtk.vtkFloatArray() floatValue.SetNumberOfComponents(1) floatValue.SetName("LineWidth") floatValue.InsertNextValue(tmpLineWidths[i]) poly.GetFieldData().AddArray(floatValue) item.SetPolyData(poly) item.SetScalarMode(scalarMode) item.SetMappedColors(mappedColors) mappedColors.FastDelete() area.GetDrawAreaItem().AddItem(item) actors.append([item, plotting_dataset_bounds]) countLevels += len(l) if len(textprops) > 0: self._resultDict["vtk_backend_contours_labels_text_properties"] = \ textprops if len(luts) > 0: if self._gm.label: self._resultDict["vtk_backend_labeled_luts"] = luts else: self._resultDict["vtk_backend_luts"] = luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) self._maskedDataMapper.Update() maskedData = self._maskedDataMapper.GetInput() maskedColors = vtk.vtkUnsignedCharArray() maskedColors.SetNumberOfComponents(4) for i in range(poly.GetNumberOfCells()): maskedColors.InsertNextTypedTuple([0, 0, 0, 255]) maskItem = vtk.vtkPolyDataItem() maskItem.SetPolyData(maskedData) maskItem.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_CELL_DATA) maskItem.SetMappedColors(maskedColors) area.GetDrawAreaItem().AddItem(maskItem) actors.append([maskItem, self._maskedDataMapper, plotting_dataset_bounds]) self._resultDict["vtk_backend_actors"] = actors z, t = self.getZandT() 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, **kwargs)) projection = vcs.elements["projection"][self._gm.projection] kwargs['xaxisconvert'] = self._gm.xaxisconvert kwargs['yaxisconvert'] = self._gm.yaxisconvert if self._data1.getAxis(-1).isLongitude() and self._data1.getAxis(-2).isLatitude(): self._context().plotContinents(self._plot_kargs.get("continents", self._useContinents), plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, **kwargs)
def _plotInternal(self): """Overrides baseclass implementation.""" tmpLevels = [] tmpColors = [] tmpLineWidths = [] tmpLineStyles = [] linewidth = self._gm.linewidths self.extendAttribute(linewidth, default=1.0) linestyle = self._gm.line self.extendAttribute(linestyle, default='solid') plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds for i, l in enumerate(self._contourLevels): if i == 0: W = linewidth[i] S = linestyle[i] C = [self._contourColors[i]] if l == 1.e20: L = [-1.e20] else: L = [l] else: if W == linewidth[i] and S == linestyle[i]: # Ok same style and width, lets keep going L.append(l) C.append(self._contourColors[i]) else: tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineStyles.append(S) L = [l] C = [self._contourColors[i]] W = linewidth[i] S = linestyle[i] tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineStyles.append(S) cots = [] textprops = [] luts = [] actors = [] mappers = [] if self._gm.label and (self._gm.text or self._gm.textcolors): # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < len(self._contourLevels): texts.append(texts[-1]) else: texts = [None] * len(self._contourLevels) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < len(self._contourLevels): colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) # Custom background colors and opacities: backgroundColors = self._gm.labelbackgroundcolors if backgroundColors: while len(backgroundColors) < len(self._contourLevels): backgroundColors.append(backgroundColors[-1]) backgroundOpacities = self._gm.labelbackgroundopacities if backgroundOpacities: while len(backgroundOpacities) < len(self._contourLevels): backgroundOpacities.append(backgroundOpacities[-1]) countLevels = 0 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 i, l in enumerate(tmpLevels): numLevels = len(l) cot = vtk.vtkContourFilter() if self._hasCellData: cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) else: cot.SetInputData(self._vtkDataSet) cot.SetNumberOfContours(numLevels) for n in range(numLevels): cot.SetValue(n, l[n]) # TODO remove update cot.Update() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(tmpColors[i])) cmap = self.getColorMap() for n, col in enumerate(tmpColors[i]): r, g, b, a = self.getColorIndexOrRGBA(cmap, col) lut.SetTableValue(n, r / 100., g / 100., b / 100., a / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for n, val in enumerate(l): tpropMap.SetTuple(n, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: ttexts = texts[countLevels:(countLevels + len(l))] for idx, tc in enumerate(ttexts): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" elif isinstance(tc, (str, unicode)): sp = tc.split(":::") if len(sp) == 2: tt = sp[0] to = sp[1] else: # Hum don't know what do do with this if sp[0] in vcs.listelements("textcombined"): tc = vcs.gettextcombined(tc) tt, to = tuple(tc.name.split(":::")) elif sp[0] in vcs.listelements("textorientation"): to = sp[0] tt = "default" elif sp[0] in vcs.listelements("texttable"): tt = sp[0] to = "default" colorOverride = colorOverrides[countLevels + idx] if colorOverride is not None: tt = vcs.createtexttable(None, tt) tt.color = colorOverride tt = tt.name if backgroundColors is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundcolor = backgroundColors[countLevels + idx] if backgroundOpacities is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundopacity = backgroundOpacities[countLevels + idx] tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), to, tt, cmap=cmap) tprops.AddItem(tprop) if colorOverride is not None: del(vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), cmap=cmap) tprops.AddItem(tprop) textprops.append(tprops) mapper = vtk.vtkLabeledContourMapper() mapper.SetTextProperties(tprops) mapper.SetTextPropertyMapping(tpropMap) mapper.SetLabelVisibility(1) mapper.SetSkipDistance(self._gm.labelskipdistance) pdMapper = mapper.GetPolyDataMapper() luts.append([lut, [l[0], l[-1], False]]) else: # No isoline labels: mapper = vtk.vtkPolyDataMapper() pdMapper = mapper luts.append([lut, [l[0], l[-1], False]]) pdMapper.SetLookupTable(lut) pdMapper.SetScalarRange(l[0], l[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() mappers.append(mapper) cots.append(cot) # Create actor to add to scene act = vtk.vtkActor() act.SetMapper(mapper) # Set line properties here p = act.GetProperty() p.SetLineWidth(tmpLineWidths[i]) vcs2vtk.stippleLine(p, tmpLineStyles[i]) 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) 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)) countLevels += len(l) if len(textprops) > 0: self._resultDict["vtk_backend_contours_labels_text_properties"] = \ textprops if len(luts) > 0: if self._gm.label: self._resultDict["vtk_backend_labeled_luts"] = luts else: self._resultDict["vtk_backend_luts"] = luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) act = vtk.vtkActor() act.SetMapper(self._maskedDataMapper) 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) actors.append([act, self._maskedDataMapper, plotting_dataset_bounds]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSet.GetBounds(), geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) self._resultDict["vtk_backend_actors"] = actors t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None 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._resultDict.update(self._context().renderTemplate( self._template, self._data1, self._gm, t, z, **kwargs)) 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)