def save_template_changes(state): for new, source in self.templates.iteritems(): if source != "default": sync_template(vcs.gettemplate(new), vcs.gettemplate(source)) for display in self.displays: if display.g_type not in ("fillarea", "text", "marker", "line"): # Remove the dummy template now that changes are synced new, source = display.template, self.templates[display.template] display.template = source display._template_origin = source self.canvas.saveinitialfile() self.canvas.update()
def settemplate(self, name, newValues): """Finds the template 'name' and applies each value in newValues to it""" template = vcs.gettemplate(name) for outer_key in newValues: if isinstance(newValues[outer_key], dict): template_inner_obj = getattr(template, outer_key) for inner_name in newValues[outer_key]: setattr(template_inner_obj, inner_name, newValues[outer_key][inner_name])
def save_template_changes(state): for new, source in self.templates.iteritems(): if source != "default": sync_template(vcs.gettemplate(new), vcs.gettemplate(source)) for display in self.displays: if display.g_type not in ("fillarea", "text", "marker", "line"): # Remove the dummy template now that changes are synced new, source = display.template, self.templates[ display.template] display.template = source display._template_origin = source self.canvas.saveinitialfile() self.canvas.update()
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 loadTemplate(nm,vals): try: t = vcs.gettemplate(nm) except: t = vcs.createtemplate(nm) for k,v in vals.iteritems(): A = getattr(t,k) for a,v in v.iteritems(): setattr(A,a,v)
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 diagnostics_template(): """creates and returns a VCS template suitable for diagnostics plots""" if 'diagnostic' in vcs.listelements('template'): tm = vcs.gettemplate('diagnostic') else: tm = vcs.createtemplate( 'diagnostic', 'default' ) # ...creates a template named 'diagnostic', as a copy of the one named 'default'. tm.title.x = 0.5 to = vcs.createtextorientation() to.halign = 'center' tm.title.textorientation = to tm.dataname.priority = 0 tm.units.priority = 0 return tm
def __init__(self, canvas, *arg, **kw): self._width = kw.get('width', 800) self._height = kw.get('height', 600) if (canvas != None): self._canvas = canvas else: self._canvas = vcs.init( geometry={'width': self._width, 'height':self._height}, bg=1) self._canvas.open() self._canvas.backend.renWin.AddObserver("ModifiedEvent", self.modifiedEvent) self._plot = PlotManager(self._canvas) self._plot.graphics_method = vcs.getisofill() # default self._plot.template = vcs.gettemplate('default') # default self._insideModifiedEvent = False
def setTemplate(self, template): if isinstance(template, dict): my_tmpl = vcs.createtemplate() for attr in template: if attr == "name": continue if attr == "p_name": continue for key in template[attr]: if key == "member": continue tmpl_attr = getattr(my_tmpl, attr) new_val = template[attr][key] setattr(tmpl_attr, key, new_val) else: my_tmpl = vcs.gettemplate(str(template)) self._plot.template = my_tmpl
def __init__(self, canvas, *arg, **kw): self._width = kw.get('width', 800) self._height = kw.get('height', 600) if (canvas != None): self._canvas = canvas else: self._canvas = vcs.init(geometry={ 'width': self._width, 'height': self._height }, bg=1) self._canvas.open() self._canvas.backend.renWin.AddObserver("ModifiedEvent", self.modifiedEvent) self._plot = PlotManager(self._canvas) self._plot.graphics_method = vcs.getisofill() # default self._plot.template = vcs.gettemplate('default') # default self._insideModifiedEvent = False
def test_save_loaded_script(tmpdir): _ = vcs.init() dirpath = os.path.dirname(__file__) load_file = os.path.join(dirpath, "data", "clt_u_v_iso.py") save_file = tmpdir.join("clt_u_v_iso.py") loaded = import_script(load_file) canvases = [vcs.init() for _ in range(loaded.num_canvases)] canvas_displays = loaded.plot(canvases) for canvas in canvases: canvas.close() plot_managers = [] for display_group in canvas_displays: pm_group = [] for display in display_group: pm = PlotManager(mocks.PlotInfo) # Determine which of the graphics methods created in loaded gm = vcs.getgraphicsmethod(display.g_type, display.g_name) pm.graphics_method = closest(gm, loaded.graphics_methods) pm.template = vcs.gettemplate(display._template_origin) pm.variables = display.array pm_group.append(pm) plot_managers.append(pm_group) mocks.PlotInfo.canvas.close() export_script(str(save_file), loaded.variables.values(), plot_managers) saved = import_script(str(save_file)) assert saved.rows == loaded.rows assert saved.columns == loaded.columns assert saved.num_canvases == loaded.num_canvases assert len(saved.files) == len(loaded.files) assert saved.files[0].id == loaded.files[0].id assert len(saved.variables) == len(loaded.variables) for save_var, load_var in zip(saved.variables.values(), loaded.variables.values()): assert save_var.id == load_var.id assert len(saved.graphics_methods) == len(loaded.graphics_methods) assert len(saved.templates) == len(loaded.templates)
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 test_save_and_load_script(tmpdir): save_file = tmpdir.join("simple_vis.py") # File shouldn't exist assert save_file.exists() is False path = str(save_file.realpath()) pm = PlotManager(mocks.PlotInfo) pm.graphics_method = vcs.getboxfill("default") pm.template = vcs.gettemplate('default') f = cdms2.open(vcs.sample_data + "/clt.nc") fmw = FileMetadataWrapper(f) clt = fmw["clt"] pm.variables = [clt.var, None] mocks.PlotInfo.canvas.close() export_script(path, [clt], [[pm]]) # Make sure the file now exists assert save_file.exists() # Import it obj = import_script(path) # Now we make sure that everything was preserved correctly assert obj.path == path assert obj.rows == 1 assert obj.columns == 1 assert obj.num_canvases == 1 assert len(obj.files) == 1 assert type(obj.files[0]) == FileMetadataWrapper assert len(obj.variables) == 1 for var_id, variable in obj.variables.iteritems(): assert var_id == variable.id assert type(variable) == VariableMetadataWrapper assert len(obj.graphics_methods) == 1 assert len(obj.templates) == 1
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 plot(self): if self.variables is None: raise ValueError("No variables specified") if self.dp is not None: # Set the slabs appropriately self.dp.array[0] = self.variables[0] self.dp.array[1] = self.variables[1] # Update the template self.dp._template_origin = self.template.name # Update the graphics method self.dp.g_name = self.graphics_method.name self.dp.g_type = vcs.graphicsmethodtype(self.graphics_method) # Update the canvas self.canvas.update() else: args = [] for var in self.variables: if var is not None: args.append(var) if self.template is not None: args.append(self.template.name) else: args.append("default") if self.graphics_method is not None: args.append(vcs.graphicsmethodtype(self.graphics_method)) args.append(self.graphics_method.name) self.dp = self.canvas.plot(*args) if self.template is None: self._template = vcs.gettemplate(self.dp._template_origin) if self.graphics_method is None: self._gm = vcs.getgraphicsmethod(self.dp.g_type, self.dp.g_name)
def plot(ref, test, diff, metrics_dict, parameters): vcs_canvas = vcs.init(bg=True, geometry=(parameters.canvas_size_w, parameters.canvas_size_h)) # Line options, see here: https://uvcdat.llnl.gov/documentation/vcs/vcs-10.html # Other options not in the above link: https://uvcdat.llnl.gov/docs/vcs/graphics/unified1D.html ref_plot_linetype = 0 ref_plot_color = 215 # 6 to 239 ref_plot_width = 3 # 1 to 100 ref_plot_marker = 1 ref_plot_markersize = 1 ref_plot_markercolor = 215 test_plot_linetype = 0 test_plot_color = 1 test_plot_width = 3 test_plot_marker = 1 test_plot_markersize = 1 test_plot_markercolor = 1 diff_plot_linetype = 0 diff_plot_color = 1 diff_plot_width = 3 diff_plot_marker = 1 diff_plot_markersize = 1 diff_plot_markercolor = 1 file_path = os.path.join(sys.prefix, 'share', 'acme_diags', 'set3') vcs_canvas.scriptrun(os.path.join(file_path, 'plot_set_3.json')) set_units(test, parameters.test_units) set_units(ref, parameters.reference_units) set_units(diff, parameters.diff_units) if hasattr(test, 'long_name'): test.long_name = parameters.test_title if parameters.test_title is not '' else test.long_name if hasattr(ref, 'long_name'): ref.long_name = parameters.reference_title if parameters.reference_title is not '' else ref.long_name if hasattr(diff, 'long_name'): diff.long_name = parameters.diff_title if parameters.diff_title is not '' else diff.long_name test.id = str( parameters.test_name) if parameters.test_name is not '' else test.id ref.id = str(parameters.reference_name ) if parameters.reference_name is not '' else ref.id diff.id = str( parameters.diff_name) if parameters.diff_name is not '' else diff.id # use vcs_canvas.show('colormap') to view all colormaps vcs_canvas.setcolormap( 'rainbow') # 6 to 239 are purple to red in rainbow order ref_test_template = vcs.gettemplate('ref_test_template') ref_test_yaxis_title = managetextcombined('ref_test_yaxis_title', 'ref_test_yaxis_title', vcs_canvas) ref_test_yaxis_title.angle = 270 ref_test_yaxis_title.halign = 'center' ref_test_yaxis_title.y = (ref_test_template.data.y1 + ref_test_template.data.y2) / 2 ref_test_yaxis_title.x = ref_test_template.data.x1 - 0.08 ref_test_yaxis_title.string = test.long_name + ' (' + test.units + ')' vcs_canvas.plot(ref_test_yaxis_title) ref_test_template.legend.priority = 0 ref_test_template.title.priority = 0 # make all of the elements listed have priority = 0 # ref_test_template.blank(["mean", "max", "min", "zvalue", "crtime", "ytic2", "xtic2"]) # the actual box around the plot ref_test_template.box1.x1 = 0.1223 ref_test_template.box1.x2 = 0.96 ref_test_template.box1.y1 = 0.55 ref_test_template.box1.y2 = 0.90 # data (the lines) need to be offset accordingly ref_test_template.data.x1 = 0.1223 ref_test_template.data.x2 = 0.96 ref_test_template.data.y1 = 0.55 ref_test_template.data.y2 = 0.90 # ref_test_template.legend.x1 = 0.88 # ref_test_template.legend.x2 = 0.98 # ref_test_template.legend.y1 = 0.96 # ref_test_template.legend.y2 = 0.88 # ref_test_template.legend.textorientation = 'defright' # ref_test_template.title.x = 0.5 # ref_test_template.title.textorientation = 'defcenter' ref_test_template.units.textorientation = 'defright' ref_test_template.units.x = 0.96 ref_test_template.units.y = 0.91 # labels on xaxis ref_test_template.xlabel1.y = (0.55) - 0.02 # no xlabel1.x attribute # actual ticks on xaxis ref_test_template.xtic1.y1 = (0.55 - 0.005) + 0.01 ref_test_template.xtic1.y2 = (0.55 - 0.005) # name of xaxis # ref_test_template.xname.y += 0.29 # labels on yaxis ref_test_template.ylabel1.x = 0.11 # no ylabel1.y attribute # actual ticks on yaxis ref_test_template.ytic1.x1 = (0.1223 - 0.006) + 0.01 ref_test_template.ytic1.x2 = (0.1223 - 0.006) diff_template = vcs.gettemplate('diff_template') diff_yaxis_title = managetextcombined('diff_yaxis_title', 'diff_yaxis_title', vcs_canvas) diff_yaxis_title.angle = 270 diff_yaxis_title.halign = 'center' diff_yaxis_title.y = (diff_template.data.y1 + diff_template.data.y2) / 2 diff_yaxis_title.x = diff_template.data.x1 - 0.08 diff_yaxis_title.string = test.long_name + ' (' + test.units + ')' vcs_canvas.plot(diff_yaxis_title) diff_template.units.textorientation = 'defright' diff_template.units.x += 0.01 diff_template.legend.priority = 0 diff_template.ytic1.x1 = (0.1223 - 0.006) + 0.01 diff_template.ytic1.x2 = (0.1223 - 0.006) diff_template.ylabel1.x = 0.11 # no ylabel1.y attribute diff_template.units.textorientation = 'defright' diff_template.units.x = 0.96 ''' diff_template.box1.y1 -= 0.47 diff_template.box1.y2 -= 0.47 diff_template.data.y1 -= 0.47 diff_template.data.y2 -= 0.47 diff_template.legend.y1 -= 0.47 diff_template.legend.y2 -= 0.47 diff_template.title.y -= 0.47 diff_template.units.y -= 0.47 diff_template.xlabel1.y -= 0.47 diff_template.xtic1.y1 -= 0.47 diff_template.xtic1.y2 -= 0.47 diff_template.xname.y -= 0.47 diff_template.yname.y -= 0.47 ''' ref_line = vcs_canvas.getxvsy('ref_plot') ref_line.datawc_y1 = min(ref.min(), test.min()) ref_line.datawc_y2 = max(ref.max(), test.max()) ref_line.datawc_x1 = -90 ref_line.datawc_x2 = 90 ref_line.xticlabels1 = { -90: "90S", -60: "60S", -30: "30S", 0: "Eq", 30: "30N", 60: "60N", 90: "90N" } test_line = vcs_canvas.getxvsy('test_plot') test_line.datawc_y1 = min(ref.min(), test.min()) test_line.datawc_y2 = max(ref.max(), test.max()) test_line.datawc_x1 = -90 test_line.datawc_x2 = 90 diff_line = vcs_canvas.getxvsy('diff_plot') diff_line.datawc_y1 = diff.min() diff_line.datawc_y2 = diff.max() diff_line.datawc_x1 = -90 diff_line.datawc_x2 = 90 diff_line.xticlabels1 = { -90: "90S", -60: "60S", -30: "30S", 0: "Eq", 30: "30N", 60: "60N", 90: "90N" } #ref_line.line = ref_plot_linetype ref_line.linetype = ref_plot_linetype ref_line.linecolor = ref_plot_color ref_line.linewidth = ref_plot_width ref_line.marker = ref_plot_marker ref_line.markersize = ref_plot_markersize ref_line.markercolor = ref_plot_markercolor #test_line.line = test_plot_linetype test_line.linetype = test_plot_linetype test_line.linecolor = test_plot_color test_line.linewidth = test_plot_width test_line.marker = test_plot_marker test_line.markersize = test_plot_markersize test_line.markercolor = test_plot_markercolor # test_line.smooth = 1 #diff_line.line = diff_plot_linetype diff_line.linetype = diff_plot_linetype diff_line.linecolor = diff_plot_color diff_line.linewidth = diff_plot_width diff_line.marker = diff_plot_marker diff_line.markersize = diff_plot_markersize diff_line.markercolor = diff_plot_markercolor blank_template = vcs_canvas.gettemplate('blank_template') blank_template.legend.priority = 0 #blank_template.blank() #blank_template.legend.priority = 1 #blank_template.legend.y1 -= 0.05 #blank_template.legend.y2 -= 0.05 # vcs_canvas.plot(ref, ref_line, ref_test_template, xname='Latitude') vcs_canvas.plot(ref, ref_line, ref_test_template) vcs_canvas.plot(test, test_line, blank_template) # vcs_canvas.plot(diff, diff_line, diff_template, xname='Latitude') vcs_canvas.plot(diff, diff_line, diff_template) # Plot the main title main_title = managetextcombined('main_title', 'main_title', vcs_canvas) main_title.string = parameters.main_title vcs_canvas.portrait( ) # for some reason, this needs to be before a call to vcs_canvas.plot() vcs_canvas.plot(main_title) test_title = managetextcombined('test_title', 'test_title', vcs_canvas) test_title.string = "Test: " + str(parameters.test_name) test_title.color = 1 test_title.x = ref_test_template.data.x1 - 0.05 test_title.y = ref_test_template.data.y2 + 0.045 test_title.height = 12 vcs_canvas.plot(test_title) ref_title = managetextcombined('ref_title', 'ref_title', vcs_canvas) ref_title.string = "Reference: " + str(parameters.reference_name) ref_title.color = 215 ref_title.x = ref_test_template.data.x1 - 0.05 ref_title.y = ref_test_template.data.y2 + 0.025 ref_title.height = 12 vcs_canvas.plot(ref_title) if not parameters.logo: vcs_canvas.drawlogooff() # ref_test_template.script('plot_set_3.json') # blank_template.script('plot_set_3.json') # diff_template.script('plot_set_3.json') # ref_line.script('plot_set_3.json') # test_line.script('plot_set_3.json') # diff_line.script('plot_set_3.json') # main_title.script('plot_set_3.json') # ref_test_yaxis_title.script('plot_set_3.json') # diff_yaxis_title.script('plot_set_3.json') # test_title.script('plot_set_3.json') # ref_title.script('plot_set_3.json') fnm = os.path.join(get_output_dir('3', parameters), parameters.output_file) for f in parameters.output_format: f = f.lower().split('.')[-1] if f == 'png': vcs_canvas.png(fnm) elif f == 'pdf': vcs_canvas.pdf(fnm) elif f == 'svg': vcs_canvas.svg(fnm) print('Plot saved in: ' + fnm + '.' + f) vcs_canvas.clear()
def vcstemp(name): """ Retrieves template by name """ return vcs.gettemplate(name)
def reset_template_changes(state): for new, source in self.templates.iteritems(): sync_template(vcs.gettemplate(source), vcs.gettemplate(new)) self.canvas.update()
def export_script(path, variables, plotters, rows=1, columns=1): files = {} for var in variables: new_files = var.get_files() for f in new_files: if f.uri not in files: files[f.uri] = f files = files.values() v = variables tree = VariableTree(variables, files) # Have to call tree.serialize before file_loads, in case of any hidden file references variable_prep = tree.serialize() file_loads = tree.get_file_lines() file_script = "\n ".join(file_loads) file_return = ", ".join([tree.file_name(f) for f in files]) variables = "\n ".join(variable_prep) var_return = ", ".join( [tree.var_name(v) for v in tree.used_variables.values()]) gms = OrderedDict() tmpls = OrderedDict() default_template = vcs.gettemplate("default") for plotter_group in plotters: for plotter in plotter_group: dp = plotter.dp if dp is None or dp.g_type not in vcs.graphicsmethodlist(): # TODO: Support Secondaries continue gm = plotter.graphics_method key = (dp.g_type, gm.name) if key not in gms: gms[key] = diff_gm(gm) template = plotter.template if template.name not in tmpls: tmpls[template.name] = diff(template, default_template) gm_body = [] for gm_key, gm_props in gms.iteritems(): gm_body.append( serialize_gm("gm_%d" % len(gm_body), gm_key[0], gm_props)) gm_body = "\n\n ".join(gm_body) gnames = ["gm_%d" % i for i in range(len(gms))] gnames = ", ".join(gnames) tmpl_body = [] for tmpl in tmpls.values(): tmpl_body.append(serialize_tmpl("tmpl_%d" % len(tmpl_body), tmpl)) tmpl_names = ["tmpl_%d" % i for i in range(len(tmpl_body))] tmpl_names = ", ".join(tmpl_names) tmpl_body = "\n\n ".join(tmpl_body) plot_calls = [] for i, plotter_group in enumerate(plotters): for plot in plotter_group: plot_calls.append( serialize_plot(plot, "canvases[%d]" % i, v, gms.keys(), tmpls.keys())) plot_calls = "\n ".join(plot_calls) num_canvases = len(plotters) with open(path, "w") as script: script.write(get_template().format(shell_script=sys.executable, files=file_script, file_ret=file_return, variables=variables, variable_ret=var_return, gms=gm_body, gm_names=gnames, tmpls=tmpl_body, template_ret=tmpl_names, plot_calls=plot_calls, num_canvas=num_canvases, rows=rows, cols=columns)) script.write(main)
def load(self, display): self.dp = display self._gm = vcs.getgraphicsmethod(display.g_type, display.g_name) self._vars = display.array self._template = vcs.gettemplate(display._template_origin)
def t(name): return vcs.gettemplate(name)
def template(name): try: obj = vcs.gettemplate(str(name)) except: abort(404) return jsonify(vcs.utils.dumpToDict(obj)[0])
def export_script(path, variables, plotters, rows=1, columns=1): files = {} for var in variables: new_files = var.get_files() for f in new_files: if f.uri not in files: files[f.uri] = f files = files.values() v = variables tree = VariableTree(variables, files) # Have to call tree.serialize before file_loads, in case of any hidden file references variable_prep = tree.serialize() file_loads = tree.get_file_lines() file_script = "\n ".join(file_loads) file_return = ", ".join([tree.file_name(f) for f in files]) variables = "\n ".join(variable_prep) var_return = ", ".join([tree.var_name(v) for v in tree.used_variables.values()]) gms = OrderedDict() tmpls = OrderedDict() default_template = vcs.gettemplate("default") for plotter_group in plotters: for plotter in plotter_group: dp = plotter.dp if dp is None or dp.g_type not in vcs.graphicsmethodlist(): # TODO: Support Secondaries continue gm = plotter.graphics_method key = (dp.g_type, gm.name) if key not in gms: gms[key] = diff_gm(gm) template = plotter.template if template.name not in tmpls: tmpls[template.name] = diff(template, default_template) gm_body = [] for gm_key, gm_props in gms.iteritems(): gm_body.append(serialize_gm("gm_%d" % len(gm_body), gm_key[0], gm_props)) gm_body = "\n\n ".join(gm_body) gnames = ["gm_%d" % i for i in range(len(gms))] gnames = ", ".join(gnames) tmpl_body = [] for tmpl in tmpls.values(): tmpl_body.append(serialize_tmpl("tmpl_%d" % len(tmpl_body), tmpl)) tmpl_names = ["tmpl_%d" % i for i in range(len(tmpl_body))] tmpl_names = ", ".join(tmpl_names) tmpl_body = "\n\n ".join(tmpl_body) plot_calls = [] for i, plotter_group in enumerate(plotters): for plot in plotter_group: plot_calls.append(serialize_plot(plot, "canvases[%d]" % i, v, gms.keys(), tmpls.keys())) plot_calls = "\n ".join(plot_calls) num_canvases = len(plotters) with open(path, "w") as script: script.write(get_template().format(shell_script=sys.executable, files=file_script, file_ret=file_return, variables=variables, variable_ret=var_return, gms=gm_body, gm_names=gnames, tmpls=tmpl_body, template_ret=tmpl_names, plot_calls=plot_calls, num_canvas=num_canvases, rows=rows, cols=columns)) script.write(main)
def axisToPngCoords(values, gm, template, axis='x1', worldCoordinates=[0, 360, -90, 90], png=None, geometry=None): """ Given a set of axis values/labels, a graphic method and a template, maps each label to an area on pmg Warning does not handle projections yet. :Example: .. doctest:: utils_axisToPngCoords >>> a=vcs.init(bg=True) >>> box=vcs.createboxfill() >>> array=[range(10) for _ in range(10)] >>> a.plot(box,array) # plot something on canvas <vcs.displayplot.Dp ...> >>> a.png('box.png', width=1536, height=1186) # make a png >>> fnm = cdat_info.get_sampledata_path()+"/clt.nc" >>> f=cdms2.open(fnm) >>> clt=f("clt",time=slice(0,1),squeeze=1) >>> box = vcs.createboxfill() >>> template = vcs.createtemplate() >>> areas = axisToPngCoords(clt.getLongitude(), box, template) """ if png is None and geometry is None: x = vcs.init() x.open() ci = x.canvasinfo() x.close() del (x) pwidth = width = ci["width"] pheight = height = ci["height"] if png is not None: pwidth, pheight = getPngDimensions(png) if geometry is None: width, height = pwidth, pheight if geometry is not None: width, height = geometry if isinstance(template, str): template = vcs.gettemplate(template) x = vcs.init(geometry=(width, height), bg=True) # x/y ratio to original png xRatio = float(width) / pwidth yRatio = float(height) / pheight # Prepare dictionary of values, labels pairs mapped = [] direction = axis[0] if direction == "x": other_direction = "y" c1 = int(width * template.data.x1 * xRatio) c2 = int(width * template.data.x2 * xRatio) else: other_direction = "x" c1 = int(height * template.data.y1 * yRatio) c2 = int(height * template.data.y2 * yRatio) location = axis[-1] datawc1 = getattr(gm, "datawc_{}1".format(direction)) if datawc1 == 1.e20: start = values[0] end = values[-1] else: start = datawc1 end = getattr(gm, "datawc_{}2".format(direction)) label = getattr(template, "{}label{}".format(direction, location)) Tt_source = label.texttable To_source = label.textorientation text = vcs.createtext(Tt_source=Tt_source, To_source=To_source) setattr(text, other_direction, getattr(label, other_direction)) if direction == "x": text.worldcoordinate = [start, end, 0, 1] else: text.worldcoordinate = [0, 1, start, end] ticlabels = getattr(gm, "{}ticlabels{}".format(direction, location)) if ticlabels == "*": lbls = vcs.mklabels(vcs.mkscale(start, end)) else: lbls = ticlabels # now loops thru all labels and get extents for v, l in lbls.items(): if start <= v and v <= end: text.string = str(l) setattr(text, direction, v) box = x.gettextbox(text)[0] if direction == "x": xs = worldToPixel(box[0], start, end, c1, c2).tolist() ys = [height * yRatio * (1 - c) for c in box[1]] else: xs = [width * xRatio * c for c in box[0]] ys = (height * yRatio - worldToPixel(box[1], start, end, c1, c2)).tolist() mapped.append([xs, ys]) return numpy.array(mapped)
def spaghetti_plot(variables, template=None, min_y=None, max_y=None, left_label=None, right_label=None, tick_sides=None, line="default", marker="default", x_labels="*", y_labels="*", canvas=None): """ This file is ready to be imported by your scripts, and you can just call this function. Sample usage is below. variables: List of variables to plot template: The template to use as the base for the plot. min_y: If you want to adjust the y axis bounds, you can set a minimum value. Will be derived from data if not specified. max_y: If you want to adjust the y axis bounds, you can set a maximum value. Will be derived from data if not specified. left_label: Text to put on the left Y axis right_label: Text to put on the right Y axis tick_sides: A list of "left" or "right" values indicating which side of the chart you want the variable axes to be displayed. line: A line object or name of a line object used to describe the lines plotted. Set to None to hide. marker: A marker object or name of a marker object used to describe the markers plotted. Set to None to hide. x_labels: Dictionary for setting axis tick labels y_labels: Dictionary for setting axis tick labels """ if canvas is None: canvas = vcs.init() if isinstance(template, (str, unicode)): template = vcs.gettemplate(template) if template is None: # Use our custom default template for 1ds template = vcs.createtemplate() # Shrink the template a bit template.scale(.78, "x") template.move(.02, "x") template.yname.x = .01 template.data.y1 = .1 template.box1.y1 = .1 ticlen = template.xtic1.y2 - template.xtic1.y1 template.xtic1.y1 = template.data.y1 template.xtic1.y2 = template.xtic1.y1 + ticlen template.xtic2.priority = 0 template.xlabel1.y = template.xtic1.y2 - .01 template.legend.x1 = template.data.x2 + (1 - template.data.x2) / 3. template.legend.x2 = .95 template.legend.y1 = template.data.y1 template.legend.y2 = template.data.y2 template.yname.y = (template.data.y1 + template.data.y2)/2. template.xname.y = template.xlabel1.y - .05 # The labels don't make any sense with multiple values; hide them. template.min.priority = 0 template.max.priority = 0 template.mean.priority = 0 template.dataname.priority = 0 templates = EzTemplate.oneD(len(variables), template=template) templates.x = canvas if tick_sides is None: tick_sides = ["left"] * len(variables) clean_ticks = [] for t in tick_sides: if t.lower() not in ('left', 'right'): raise ValueError("tick_sides must be a list of 'left' or 'right' values; found '%s'." % t) clean_ticks.append(t.lower()) tick_sides = clean_ticks if len(tick_sides) < len(variables): tick_sides += tick_sides[-1:] * len(variables) # Store min/max per side for appropriate scaling min_vals = {"left": min_y, "right": min_y} if min_y is None: for i, var in enumerate(variables): v_min = min(var) min_y = min_vals[tick_sides[i]] if min_y is None or min_y > v_min: min_vals[tick_sides[i]] = v_min max_vals = {"left": max_y, "right": max_y} if max_y is None: for i, var in enumerate(variables): v_max = max(var) max_y = max_vals[tick_sides[i]] if max_y is None or max_y < v_max: max_vals[tick_sides[i]] = v_max if isinstance(line, (str, unicode)): line = vcs.getline(line) if isinstance(marker, (str, unicode)): marker = vcs.getmarker(marker) to_pad = [] if line is not None: widths = line.width to_pad.append(widths) styles = line.type to_pad.append(styles) colors = line.color to_pad.append(colors) if marker is not None: markers = marker.type to_pad.append(markers) marker_colors = marker.color to_pad.append(marker_colors) marker_sizes = marker.size to_pad.append(marker_sizes) for padded in to_pad: if len(padded) < len(variables): padded += padded[-1:] * (len(variables) - len(padded)) for n in range(len(variables)): gm = vcs.create1d() if line is not None: gm.line = styles[n] gm.linewidth = widths[n] gm.linecolor = colors[n] else: gm.linewidth = 0 if marker is not None: gm.marker = markers[n] gm.markersize = marker_sizes[n] gm.markercolor = marker_colors[n] else: gm.marker = None gm.datawc_y1 = min_vals[tick_sides[n]] gm.datawc_y2 = max_vals[tick_sides[n]] template = templates.get(n) gm.xticlabels1 = x_labels if tick_sides[n] == "left": if tick_sides.index("left") == n: template.ylabel1.priority = 1 if left_label is not None: template.yname.priority = 0 left_text = vcs.createtext(Tt_source=template.yname.texttable, To_source=template.yname.textorientation) left_text.x = template.yname.x left_text.y = template.yname.y left_text.string = [left_label] templates.x.plot(left_text) else: template.ylabel1.priority = 0 template.yname.priority = 0 template.ylabel2.priority = 0 gm.yticlabels1 = y_labels gm.yticlabels2 = "" else: template.ylabel1.priority = 0 if tick_sides.index("right") == n: template.ylabel2.priority = 1 if right_label is not None: right_text = vcs.createtext(Tt_source=template.yname.texttable, To_source=template.yname.textorientation) right_text.x = template.data.x2 + (template.data.x1 - template.yname.x) right_text.y = template.yname.y right_text.string = [right_label] templates.x.plot(right_text) else: template.ylabel2.priority = 0 gm.yticlabels1 = "" gm.yticlabels2 = y_labels if n != 0: template.xlabel1.priority = 0 template.xname.priority = 0 var = variables[n] templates.x.plot(var, gm, template) return templates.x
def spaghetti_plot(variables, template=None, min_y=None, max_y=None, left_label=None, right_label=None, tick_sides=None, line="default", marker="default", x_labels="*", y_labels="*", canvas=None): """ This file is ready to be imported by your scripts, and you can just call this function. Sample usage is below. variables: List of variables to plot template: The template to use as the base for the plot. min_y: If you want to adjust the y axis bounds, you can set a minimum value. Will be derived from data if not specified. max_y: If you want to adjust the y axis bounds, you can set a maximum value. Will be derived from data if not specified. left_label: Text to put on the left Y axis right_label: Text to put on the right Y axis tick_sides: A list of "left" or "right" values indicating which side of the chart you want the variable axes to be displayed. line: A line object or name of a line object used to describe the lines plotted. Set to None to hide. marker: A marker object or name of a marker object used to describe the markers plotted. Set to None to hide. x_labels: Dictionary for setting axis tick labels y_labels: Dictionary for setting axis tick labels """ if canvas is None: canvas = vcs.init() if isinstance(template, (str, unicode)): template = vcs.gettemplate(template) if template is None: # Use our custom default template for 1ds template = vcs.createtemplate() # Shrink the template a bit template.scale(.78, "x") template.move(.02, "x") template.yname.x = .01 template.data.y1 = .1 template.box1.y1 = .1 ticlen = template.xtic1.y2 - template.xtic1.y1 template.xtic1.y1 = template.data.y1 template.xtic1.y2 = template.xtic1.y1 + ticlen template.xtic2.priority = 0 template.xlabel1.y = template.xtic1.y2 - .01 template.legend.x1 = template.data.x2 + (1 - template.data.x2) / 3. template.legend.x2 = .95 template.legend.y1 = template.data.y1 template.legend.y2 = template.data.y2 template.yname.y = (template.data.y1 + template.data.y2) / 2. template.xname.y = template.xlabel1.y - .05 # The labels don't make any sense with multiple values; hide them. template.min.priority = 0 template.max.priority = 0 template.mean.priority = 0 template.dataname.priority = 0 templates = EzTemplate.oneD(len(variables), template=template) templates.x = canvas if tick_sides is None: tick_sides = ["left"] * len(variables) clean_ticks = [] for t in tick_sides: if t.lower() not in ('left', 'right'): raise ValueError( "tick_sides must be a list of 'left' or 'right' values; found '%s'." % t) clean_ticks.append(t.lower()) tick_sides = clean_ticks if len(tick_sides) < len(variables): tick_sides += tick_sides[-1:] * len(variables) # Store min/max per side for appropriate scaling min_vals = {"left": min_y, "right": min_y} if min_y is None: for i, var in enumerate(variables): v_min = min(var) min_y = min_vals[tick_sides[i]] if min_y is None or min_y > v_min: min_vals[tick_sides[i]] = v_min max_vals = {"left": max_y, "right": max_y} if max_y is None: for i, var in enumerate(variables): v_max = max(var) max_y = max_vals[tick_sides[i]] if max_y is None or max_y < v_max: max_vals[tick_sides[i]] = v_max if isinstance(line, (str, unicode)): line = vcs.getline(line) if isinstance(marker, (str, unicode)): marker = vcs.getmarker(marker) to_pad = [] if line is not None: widths = line.width to_pad.append(widths) styles = line.type to_pad.append(styles) colors = line.color to_pad.append(colors) if marker is not None: markers = marker.type to_pad.append(markers) marker_colors = marker.color to_pad.append(marker_colors) marker_sizes = marker.size to_pad.append(marker_sizes) for padded in to_pad: if len(padded) < len(variables): padded += padded[-1:] * (len(variables) - len(padded)) for n in range(len(variables)): gm = vcs.create1d() if line is not None: gm.line = styles[n] gm.linewidth = widths[n] gm.linecolor = colors[n] else: gm.linewidth = 0 if marker is not None: gm.marker = markers[n] gm.markersize = marker_sizes[n] gm.markercolor = marker_colors[n] else: gm.marker = None gm.datawc_y1 = min_vals[tick_sides[n]] gm.datawc_y2 = max_vals[tick_sides[n]] template = templates.get(n) gm.xticlabels1 = x_labels if tick_sides[n] == "left": if tick_sides.index("left") == n: template.ylabel1.priority = 1 if left_label is not None: template.yname.priority = 0 left_text = vcs.createtext( Tt_source=template.yname.texttable, To_source=template.yname.textorientation) left_text.x = template.yname.x left_text.y = template.yname.y left_text.string = [left_label] templates.x.plot(left_text) else: template.ylabel1.priority = 0 template.yname.priority = 0 template.ylabel2.priority = 0 gm.yticlabels1 = y_labels gm.yticlabels2 = "" else: template.ylabel1.priority = 0 if tick_sides.index("right") == n: template.ylabel2.priority = 1 if right_label is not None: right_text = vcs.createtext( Tt_source=template.yname.texttable, To_source=template.yname.textorientation) right_text.x = template.data.x2 + (template.data.x1 - template.yname.x) right_text.y = template.yname.y right_text.string = [right_label] templates.x.plot(right_text) else: template.ylabel2.priority = 0 gm.yticlabels1 = "" gm.yticlabels2 = y_labels if n != 0: template.xlabel1.priority = 0 template.xname.priority = 0 var = variables[n] templates.x.plot(var, gm, template) return templates.x
def createtemplate(self, templateName, nameSource): """Creates a template with name 'templateName' using 'nameSource' as the base template""" base_template = vcs.gettemplate(nameSource) vcs.createtemplate(templateName, base_template)
def removetemplate(self, templateName): """Deletes the template named 'templateName' """ template = vcs.gettemplate(templateName) vcs.removeP(template)
def meshToPngCoords(mesh, template, worldCoordinates=[0, 360, -90, 90], png=None, geometry=None): """ Given a mesh object, a vcs template and a graphic methods woorldcoordinate, maps each 'box' to an area on png Warning does not handle projections yet. Would only work for boxfill and meshfill. May be adapted in the future to isofill as well. :Example: .. doctest:: utils_meshToPngCoords >>> a=vcs.init(bg=True) >>> box=vcs.createboxfill() >>> array=[range(10) for _ in range(10)] >>> a.plot(box,array) # plot something on canvas <vcs.displayplot.Dp ...> >>> a.png('box.png', width=1536, height=1186) # make a png >>> fnm = cdat_info.get_sampledata_path()+"/clt.nc" >>> f=cdms2.open(fnm) >>> clt=f("clt",time=slice(0,1),squeeze=1) >>> mesh = clt.getGrid().getMesh() >>> template = vcs.createtemplate() >>> areas = meshToPngCoords(mesh, template, worldCoordinates=[gm.datawc_x1, gm.datawc_x2, gm.datawc_y1, gm.datawc_y2], png='box.png') :param mesh: array of shape (Nelements,2,nVertices) defining the polygon of each cell :type : `numpy.ndarray`_ :param template: template used by vcs when plotting :type template: `vcs.template.P`_ :param worldCoordinates: list of world coordinates for the "data" area of the templte [x1, x2, y1, y2] :type worldCoordinates: `list`_ :param png: png file produced by vcs (used to get dimensions) :type png: `str`_ :param geometry: (width, height) of image on html page :type width: `list`_ :return: A numpy array of pixels mapping the input mesh onto the png passed :rtype: `numpy.ndarray`_ """ mesh = mesh * 1. # essentially copy it if png is None and geometry is None: x = vcs.init() x.open() ci = x.canvasinfo() x.close() del (x) pwidth = width = ci["width"] pheight = height = ci["height"] if png is not None: pwidth, pheight = getPngDimensions(png) if geometry is None: width, height = pwidth, pheight if geometry is not None: width, height = geometry if isinstance(template, str): template = vcs.gettemplate(template) # print("WC:",worldCoordinates) # x/y ratio to original png xRatio = float(width) / pwidth yRatio = float(height) / pheight # print("RATIOS",xRatio,yRatio) # Determine pixels where data actually sits, on the destination x1 = int(width * template.data.x1 * xRatio) x2 = int(width * template.data.x2 * xRatio) y1 = int(height * template.data.y1 * yRatio) y2 = int(height * template.data.y2 * yRatio) # html (0,0) is top/left vcs is bottom/left mesh[:, 0] = height * yRatio - \ worldToPixel(mesh[:, 0], worldCoordinates[2], worldCoordinates[3], y1, y2) mesh[:, 1] = worldToPixel(mesh[:, 1], worldCoordinates[0], worldCoordinates[1], x1, x2) # expecting xs first we need to flip mesh = mesh[:, ::-1] return mesh.astype(int)