def setLineObject(self, lineobject): self.lineobj = lineobject tmpobj = vcs.createline(source=self.lineobj) tmpobj.x = [.25, .75] tmpobj.y = [.5, .5] self.clear() self.plot(tmpobj)
def test_setlineattributes(self): l = vcs.createline("vcs_test_set_line") l.color = 242 l.width = 5.6 l.type = "dash" self.assertEqual(l.color, [242]) self.assertEqual(l.width, [5.6]) self.assertEqual(l.type, ["dash"]) v = vcs.createvector() v.setLineAttributes("vcs_test_set_line") self.assertEqual(v.linecolor, 242) self.assertEqual(v.linewidth, 5.6) self.assertEqual(v.linetype, "dash") yx = vcs.create1d() yx.setLineAttributes(l) self.assertEqual(yx.linecolor, 242) self.assertEqual(yx.linewidth, 5.6) self.assertEqual(yx.linetype, "dash") iso = vcs.createisoline() # Note "solid" is a line name. iso.setLineAttributes([l, "solid", l]) self.assertEqual(iso.linecolors, [242, 1, 242]) self.assertEqual(iso.linewidths, [5.6, 1, 5.6]) self.assertEqual(iso.linetypes, ['dash', 'solid', 'dash'])
def test_preview(): prev = LinePreviewWidget() line = vcs.createline() prev.setLineObject(line) assert prev.lineobj == line line.type = "dot" prev.update() assert prev.lineobj.type == ["dot"]
def straightLine(coord, direction="horizontal", color="grey", type="dot"): ln = vcs.createline() if direction[0].lower() == "h": ln.x = [0.001, .999] ln.y = [coord, coord] else: ln.x = [coord, coord] ln.y = [0., 1.] ln.type = type ln.color = [color] canvas.plot(ln)
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 test_pcoord(self): import vcs import vcsaddons J = self.loadJSON() rms_xyt = J(statistic=["rms_xyt"], season=["ann"], region="global")(squeeze=1) x = vcs.init(geometry=(1200, 600), bg=bg) gm = vcsaddons.createparallelcoordinates(x=x) t = vcs.createtemplate() to = x.createtextorientation() to.angle = -45 to.halign = "right" t.xlabel1.textorientation = to.name t.reset('x', 0.05, 0.9, t.data.x1, t.data.x2) #t.reset('y',0.5,0.9,t.data.y1,t.data.y2) ln = vcs.createline() ln.color = [[0, 0, 0, 0]] t.legend.line = ln t.box1.priority = 0 t.legend.x1 = .91 t.legend.x2 = .99 t.legend.y1 = t.data.y1 t.legend.y2 = t.data.y2 # Set variable name rms_xyt.id = "RMS" # Set units of each variables on axis rms_xyt.getAxis(-2).units = [ "mm/day", "mm/day", "hPa", "W/m2", "W/m2", "W/m2", "K", "K", "K", "m/s", "m/s", "m/s", "m/s", "m" ] # Sets title rms_xyt.title = "Annual Mean Error" gm.plot(rms_xyt, template=t, bg=bg) src = os.path.join(os.path.dirname(__file__), "testParallelCoordinates.png") print src fnm = os.path.join(os.getcwd(), "testParallelCoordinates.png") x.png(fnm) ret = vcs.testing.regression.check_result_image(fnm, src) if ret != 0: sys.exit(ret)
def test_pcoord(self): import vcs import vcsaddons J=self.loadJSON() rms_xyt = J(statistic=["rms_xyt"],season=["ann"],region="global")(squeeze=1) x=vcs.init(geometry=(1200,600),bg=bg) gm = vcsaddons.createparallelcoordinates(x=x) t = vcs.createtemplate() to=x.createtextorientation() to.angle=-45 to.halign="right" t.xlabel1.textorientation = to.name t.reset('x',0.05,0.9,t.data.x1,t.data.x2) #t.reset('y',0.5,0.9,t.data.y1,t.data.y2) ln = vcs.createline() ln.color = [[0,0,0,0]] t.legend.line = ln t.box1.priority=0 t.legend.x1 = .91 t.legend.x2 = .99 t.legend.y1 = t.data.y1 t.legend.y2 = t.data.y2 # Set variable name rms_xyt.id = "RMS" # Set units of each variables on axis rms_xyt.getAxis(-2).units = ["mm/day","mm/day","hPa","W/m2","W/m2","W/m2", "K","K","K","m/s","m/s","m/s","m/s","m"] # Sets title rms_xyt.title = "Annual Mean Error" gm.plot(rms_xyt,template=t,bg=bg) src = os.path.join(os.path.dirname(__file__), "testParallelCoordinates.png") print src fnm = os.path.join(os.getcwd(), "testParallelCoordinates.png") x.png(fnm) ret = vcs.testing.regression.check_result_image( fnm, src) if ret != 0: sys.exit(ret)
def test_pcoord(self): import vcs import vcsaddons J=self.loadJSON() rms_xyt = J(statistic=["rms_xyt"],season=["ann"],region="global")(squeeze=1) gm = vcsaddons.createparallelcoordinates(x=self.x) t = vcs.createtemplate() to = vcs.createtextorientation() to.angle=-45 to.halign="right" t.xlabel1.textorientation = to.name t.data.list() t.reset('x',0.05,0.9,t.data.x1,t.data.x2) t.data.list() #t.reset('y',0.5,0.9,t.data.y1,t.data.y2) ln = vcs.createline() ln.color = [[0,0,0,0]] t.legend.line = ln t.box1.priority=0 t.legend.x1 = .91 t.legend.x2 = .99 t.legend.y1 = t.data.y1 t.legend.y2 = t.data.y2 # Set variable name rms_xyt.id = "RMS" # Set units of each variables on axis rms_xyt.getAxis(-2).units = ["mm/day","mm/day","hPa","W/m2","W/m2","W/m2", "K","K","K","m/s","m/s","m/s","m/s","m"] # Sets title rms_xyt.title = "Annual Mean Error" gm.plot(rms_xyt,template=t) fnm = os.path.join(os.getcwd(), "testParallelCoordinates.png") self.checkImage(fnm)
def histogram(canvas, values, xaxis=None, yaxis=None): fa = canvas.createfillarea() t = canvas.gettemplate("default") fa.viewport = [t.data.x1, t.data.x2, t.data.y1, t.data.y2] num_fills = len(values) fa.color = vcs.getcolors(range(num_fills)) x, y = [], [] for i in range(num_fills): point1, point2 = i / float(num_fills), (i + 1) / float(num_fills) xl = [point1, point1, point2, point2] yl = [0, values[i], values[i], 0] x.append(xl) y.append(yl) fa.x = x fa.y = y outline = vcs.createline(source="default") outline.viewport = fa.viewport outline.x = x outline.y = y canvas.plot(fa) canvas.plot(outline)
def editor(): editor = LineEditorWidget() line = vcs.createline() editor.setLineObject(line) return editor
boxfill.levels = [1, 100] # Pick a color, any color boxfill.fillareacolors = [242] dataonly = vcs.createtemplate() dataonly.blank() dataonly.data.priority = 1 multitemplate = EzTemplate.Multi(template=dataonly, rows=4, columns=3) line_styles = ['long-dash', 'dot', 'dash', 'dash-dot', 'solid'] for i in range(12): cont_index = i % 6 + 1 cont_line = vcs.createline() cont_line.width = i % 3 + 1 cont_line.type = line_styles[i % 5] print "Cont_line_rtype:",line_styles[i % 5] cont_line.color = i + 200 template = multitemplate.get(i) if cont_index != 3 and i != 4 and i != 11: canvas.plot(clt, template, boxfill, continents=cont_index, continents_line=cont_line, bg=1) elif cont_index == 3: canvas.setcontinentsline(cont_line) canvas.setcontinentstype(3) canvas.plot(clt, template, boxfill, bg=1) elif i == 4: canvas.setcontinentstype(0) # Make sure absolute path works path = os.path.join(vcs.prefix, "share", "vcs", "data_continent_political")
import vcs, cdms2 f = cdms2.open(vcs.sample_data + '/clt.nc') s = f("clt", squeeze=1, time="1979-1") zeroed = cdms2.createVariable([[0 for _ in range(s.shape[1])] for _ in range(s.shape[0])], axes=s.getAxisList(), grid=s.getGrid()) x = vcs.init() box = vcs.createboxfill() box.boxfill_type = "custom" box.levels = [1, 100] box.fillareacolors = [242] light = vcs.createline() colormap = vcs.createcolormap() colormap.index[1] = [10, 10, 10] light.colormap = colormap light.type = "dash-dot" dark = vcs.createline() dark.width = 2 justdata = vcs.createtemplate() justdata.blank() justdata.data.priority = 1 x.plot(s, continents=4, continents_line=light, bg=1) x.plot(zeroed, justdata, box, continents=1, continents_line=dark, bg=1) x.png("nice_continents")
def init_polar(): # Create nice polar template try: t = vcs.createtemplate("polar_oned") t.data.x1 = .2 t.data.x2 = .8 t.data.y1 = .2 t.data.y2 = .8 t.legend.x1 = .85 t.legend.x2 = 1 t.legend.y1 = .15 t.legend.y2 = .85 dash = vcs.createline() dash.type = "dash" dot = vcs.createline() dot.type = "dot" t.xtic1.line = dash t.ytic1.line = dot left_aligned = vcs.createtextorientation() left_aligned.halign = "left" left_aligned.valign = "half" t.legend.textorientation = left_aligned except vcs.vcsError: # Template already exists pass # Create some nice default polar GMs degree_polar = Gpo("degrees", template="polar_oned") degree_polar.negative_magnitude = True degree_polar.datawc_x1 = 0 degree_polar.datawc_x2 = 360 degree_polar.xticlabels1 = {i: str(i) for i in range(0, 360, 45)} clock_24 = Gpo("diurnal", template="polar_oned") clock_24.negative_magnitude = True clock_24.datawc_x1 = 0 clock_24.datawc_x2 = 24 clock_24.clockwise = True # 6 AM on the right clock_24.theta_offset = -6 clock_24.xticlabels1 = {i: str(i) for i in range(0, 24, 3)} clock_24_meridiem = Gpo("diurnal_12_hour", source="diurnal", template="polar_oned") clock_24_meridiem.xticlabels1 = { 0: "12 AM", 3: "3 AM", 6: "6 AM", 9: "9 AM", 12: "12 PM", 15: "3 PM", 18: "6 PM", 21: "9 PM" } clock_12 = Gpo("semidiurnal", source="diurnal", template="polar_oned") clock_12.negative_magnitude = True clock_12.datawc_x2 = 12 clock_12.xticlabels1 = {i: str(i) for i in range(3, 13, 3)} # 3 on the right clock_12.theta_offset = -3 annual_cycle = Gpo("annual_cycle", template="polar_oned") annual_cycle.negative_magnitude = True annual_cycle.datawc_x1 = 1 annual_cycle.datawc_x2 = 13 annual_cycle.clockwise = True annual_cycle.xticlabels1 = { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec" } # Put December on the top annual_cycle.theta_offset = -2 seasonal = Gpo("seasonal", template="polar_oned") seasonal.negative_magnitude = True seasonal.datawc_x1 = 0 seasonal.datawc_x2 = 4 seasonal.xticlabels1 = {0: "DJF", 1: "MAM", 2: "JJA", 3: "SON"} seasonal.clockwise = True # DJF on top seasonal.theta_offset = -1
def plot(self, var, theta=None, template=None, bg=0, x=None): """ Plots a polar plot of your data. If var is an ndarray with the second dimension being 2, it will use the first value as magnitude and the second as theta. Otherwise, if theta is provided, it uses var as magnitude and the theta given. """ if x is None: if self.x is None: self.x = vcs.init() x = self.x if template is None: template = self.template if self.markercolorsource.lower() not in ("group", "magnitude", "theta"): raise ValueError("polar.markercolorsource must be one of: 'group', 'magnitude', 'theta'") magnitudes, thetas, names = convert_arrays(var, theta) if self.group_names: names = self.group_names while len(names) < len(magnitudes): names.append(None) flat_magnitude = [] for i in magnitudes: flat_magnitude.extend(i) flat_theta = [] for i in thetas: flat_theta.extend(i) canvas = x # Determine aspect ratio for plotting the circle canvas_info = canvas.canvasinfo() # Calculate aspect ratio of window window_aspect = canvas_info["width"] / float(canvas_info["height"]) if window_aspect > 1: ymul = window_aspect xmul = 1 else: ymul = 1 xmul = window_aspect # Use window_aspect to adjust size of template.data x0, x1 = template.data.x1, template.data.x2 y0, y1 = template.data.y1, template.data.y2 xdiff = abs(x1 - x0) ydiff = abs(y1 - y0) center = x0 + xdiff / 2., y0 + ydiff / 2. diameter = min(xdiff, ydiff) radius = diameter / 2. plot_kwargs = {"render": False, "bg": bg, "donotstoredisplay": True} # Outer line if template.box1.priority > 0: outer = vcs.createline(source=template.box1.line) x, y = circle_points(center, radius, ratio=window_aspect) outer.x = x outer.y = y canvas.plot(outer, **plot_kwargs) del vcs.elements["line"][outer.name] if numpy.allclose((self.datawc_y1, self.datawc_y2), 1e20): if self.magnitude_ticks == "*": m_scale = vcs.mkscale(*vcs.minmax(flat_magnitude)) else: if isinstance(self.magnitude_ticks, (str, unicode)): ticks = vcs.elements["list"][self.magnitude_ticks] else: ticks = self.magnitude_ticks m_scale = ticks else: m_scale = vcs.mkscale(self.datawc_y1, self.datawc_y2) if template.ytic1.priority > 0: m_ticks = vcs.createline(source=template.ytic1.line) m_ticks.x = [] m_ticks.y = [] if template.ylabel1.priority > 0: to = self.text_orientation_for_angle(self.magnitude_tick_angle, source=template.ylabel1.textorientation) m_labels = self.create_text(template.ylabel1.texttable, to) m_labels.x = [] m_labels.y = [] m_labels.string = [] if self.yticlabels1 == "*": mag_labels = vcs.mklabels(m_scale) else: mag_labels = self.yticlabels1 else: m_labels = None for lev in m_scale: lev_radius = radius * self.magnitude_from_value(lev, (m_scale[0], m_scale[-1])) x, y = circle_points(center, lev_radius, ratio=window_aspect) if m_labels is not None: if lev in mag_labels: m_labels.string.append(mag_labels[lev]) m_labels.x.append(xmul * lev_radius * numpy.cos(self.magnitude_tick_angle) + center[0]) m_labels.y.append(ymul * lev_radius * numpy.sin(self.magnitude_tick_angle) + center[1]) m_ticks.x.append(x) m_ticks.y.append(y) canvas.plot(m_ticks, **plot_kwargs) del vcs.elements["line"][m_ticks.name] if m_labels is not None: canvas.plot(m_labels, **plot_kwargs) del vcs.elements["textcombined"][m_labels.name] if template.ymintic1.priority > 0 and self.magnitude_mintics is not None: mag_mintics = vcs.createline(source=template.ymintic1.line) mag_mintics.x = [] mag_mintics.y = [] mintics = self.magnitude_mintics if isinstance(mintics, (str, unicode)): mintics = vcs.elements["list"][mintics] for mag in mintics: mintic_radius = radius * self.magnitude_from_value(mag, (m_scale[0], m_scale[-1])) x, y = circle_points(center, mintic_radius, ratio=window_aspect) mag_mintics.x.append(x) mag_mintics.y.append(y) canvas.plot(mag_mintics, **plot_kwargs) del vcs.elements["line"][mag_mintics.name] if self.xticlabels1 == "*": if numpy.allclose((self.datawc_x1, self.datawc_x2), 1e20): tick_thetas = list(numpy.arange(0, numpy.pi * 2, numpy.pi / 4)) tick_labels = {t: str(t) for t in tick_thetas} else: d_theta = (self.datawc_x2 - self.datawc_x1) / float(self.theta_tick_count) tick_thetas = numpy.arange(self.datawc_x1, self.datawc_x2 + .0001, d_theta) tick_labels = vcs.mklabels(tick_thetas) else: tick_thetas = self.xticlabels1.keys() tick_labels = self.xticlabels1 if template.xtic1.priority > 0: t_ticks = vcs.createline(source=template.xtic1.line) t_ticks.x = [] t_ticks.y = [] if template.xlabel1.priority > 0: t_labels = [] theta_labels = tick_labels else: t_labels = None for t in tick_thetas: angle = self.theta_from_value(t) x0 = center[0] + (xmul * radius * numpy.cos(angle)) x1 = center[0] y0 = center[1] + (ymul * radius * numpy.sin(angle)) y1 = center[1] if t_labels is not None: label = self.create_text(template.xlabel1.texttable, self.text_orientation_for_angle(angle, source=template.xlabel1.textorientation)) label.string = [theta_labels[t]] label.x = [x0] label.y = [y0] t_labels.append(label) t_ticks.x.append([x0, x1]) t_ticks.y.append([y0, y1]) canvas.plot(t_ticks, **plot_kwargs) del vcs.elements["line"][t_ticks.name] if t_labels is not None: for l in t_labels: canvas.plot(l, **plot_kwargs) del vcs.elements["textcombined"][l.name] values = vcs.createmarker() values.type = self.markers values.size = self.markersizes values.color = self.markercolors values.colormap = self.colormap values.priority = self.markerpriority values.x = [] values.y = [] if template.legend.priority > 0: # Only labels that are set will show up in the legend label_count = len(names) - len([i for i in names if i is None]) labels = self.create_text(template.legend.texttable, template.legend.textorientation) labels.x = [] labels.y = [] labels.string = [] if self.draw_lines: line = vcs.createline() line.x = [] line.y = [] line.type = self.lines line.color = self.linecolors if self.linecolors is not None else self.markercolors line.width = self.linewidths line.priority = self.linepriority # This is up here because when it's part of the main loop, we can lose "order" of points when we flatten them. for mag, theta in zip(magnitudes, thetas): x = [] y = [] for m, t in zip(mag, theta): t = self.theta_from_value(t) r = self.magnitude_from_value(m, (m_scale[0], m_scale[-1])) * radius x.append(xmul * numpy.cos(t) * r + center[0]) y.append(ymul * numpy.sin(t) * r + center[1]) if self.connect_groups: line.x.extend(x) line.y.extend(y) else: line.x.append(x) line.y.append(y) if self.markercolorsource.lower() in ('magnitude', "theta"): # Regroup the values using the appropriate metric mag_flat = numpy.array(magnitudes).flatten() theta_flat = numpy.array(thetas).flatten() if self.markercolorsource.lower() == "magnitude": scale = m_scale vals = mag_flat else: scale = theta_ticks vals = theta_flat indices = [numpy.where(numpy.logical_and(vals >= scale[i], vals <= scale[i + 1])) for i in range(len(scale) - 1)] magnitudes = [mag_flat[inds] for inds in indices] thetas = [theta_flat[inds] for inds in indices] names = vcs.mklabels(scale, output="list") names = [names[i] + " - " + names[i + 1] for i in range(len(names) - 1)] label_count = len(names) for mag, theta, name in zip(magnitudes, thetas, names): x = [] y = [] for m, t in zip(mag, theta): t = self.theta_from_value(t) r = self.magnitude_from_value(m, (m_scale[0], m_scale[-1])) * radius x.append(xmul * numpy.cos(t) * r + center[0]) y.append(ymul * numpy.sin(t) * r + center[1]) if template.legend.priority > 0 and name is not None: y_offset = len(labels.x) / float(label_count) * (template.legend.y2 - template.legend.y1) lx, ly = template.legend.x1, template.legend.y1 + y_offset x.append(lx) y.append(ly) labels.x.append(lx + .01) labels.y.append(ly) labels.string.append(str(name)) values.x.append(x) values.y.append(y) if template.legend.priority > 0: canvas.plot(labels, **plot_kwargs) del vcs.elements["textcombined"][labels.name] if self.draw_lines: canvas.plot(line, **plot_kwargs) del vcs.elements["line"][line.name] for el in self.to_cleanup: if vcs.istexttable(el): if el.name in vcs.elements["texttable"]: del vcs.elements["texttable"][el.name] else: if el.name in vcs.elements["textorientation"]: del vcs.elements["textorientation"][el.name] self.to_cleanup = [] # Prune unneeded levels from values to_prune = [] for ind, (x, y) in enumerate(zip(values.x, values.y)): if x and y: continue else: to_prune.append(ind) for prune_ind in to_prune[::-1]: del values.x[prune_ind] del values.y[prune_ind] if len(values.color) > prune_ind and len(values.color) > 1: del values.color[prune_ind] if len(values.size) > prune_ind and len(values.size) > 1: del values.size[prune_ind] if len(values.type) > prune_ind and len(values.type) > 1: del values.type[prune_ind] canvas.plot(values, bg=bg, donotstoredisplay=True) del vcs.elements["marker"][values.name] return canvas
src=sys.argv[1] if os.path.exists("test_vcs_dump_json.json"): os.remove("test_vcs_dump_json.json") b = vcs.createboxfill("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createisofill("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createisoline("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createmeshfill("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createoneD("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createfillarea("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createtext("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createline("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createmarker("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createtemplate("Charles.Doutriaux") b.script("test_vcs_dump_json","a") b = vcs.createprojection("Charles.Doutriaux") b.script("test_vcs_dump_json","a") assert(filecmp.cmp("test_vcs_dump_json.json",src))
import vcs l = vcs.createline("vcs_test_set_line") l.color=242 l.width = 5.6 l.type = "dash" v=vcs.createvector() v.setLineAttributes("vcs_test_set_line") assert(v.linecolor == 242) assert(v.linewidth == 5.6) assert(v.linetype == "dash") yx = vcs.create1d() yx.setLineAttributes(l) assert(yx.linecolor == 242) assert(yx.linewidth == 5.6) assert(yx.linetype == "dash") iso = vcs.createisoline() # Note "solid" is a line name. iso.setLineAttributes([l, "solid", l]) assert(iso.linecolors == [242, 1, 242]) assert(iso.linewidths == [5.6, 1, 5.6]) assert(iso.linetypes == ['dash', 'solid', 'dash'])
import vcs, os, filecmp import vcs, numpy, os, sys src = sys.argv[1] if os.path.exists("test_vcs_dump_json.json"): os.remove("test_vcs_dump_json.json") b = vcs.createboxfill("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createisofill("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createisoline("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createmeshfill("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createoneD("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createfillarea("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createtext("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createline("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createmarker("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createtemplate("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") b = vcs.createprojection("Charles.Doutriaux") b.script("test_vcs_dump_json", "a") assert (filecmp.cmp("test_vcs_dump_json.json", src))
os.remove("test_vcs_dump_json.json") b = vcs.createboxfill("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createisofill("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createisoline("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createmeshfill("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.create1d("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createfillarea("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createvector("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createtext("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createline("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createmarker("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createtemplate("vcs_instance") b.script("test_vcs_dump_json","a") b = vcs.createprojection("vcs_instance") b.script("test_vcs_dump_json","a") assert(filecmp.cmp("test_vcs_dump_json.json", src))
import vcs x = vcs.init() l = vcs.createline() l.x = [(.15, .85), (.85, .15), (.15, .85), (.85, .15), (.15, .85)] l.y = [(0, .2), (.2, .4), (.4, .6), (.6, .8), (.8, 1)] l.type = ["solid", "dot", "dot", "solid", "dash"] l.color = range(10, 110, 20) x.plot(l) raw_input("Enter")
variables = [] for i in range(6): tas = f("tas", slice(i * 12, (i + 1) * 12)) # Extract one year # Assign an ID that will distinguish the years tas.id = "tas_%i" % tas.getTime().asComponentTime()[0].year # Manipulating the variable changes the id; we'll save it here. saved_id = tas.id # Make sure the data is bounded before averaging cdutil.setTimeBoundsMonthly(tas) var = cdutil.averager(tas(squeeze=1), axis="xy") var = cdutil.ANNUALCYCLE.climatology(var) var.id = saved_id variables.append(var) # Customize the lines used to draw the plots line = vcs.createline() line.width = 2 line.color = [ "red", "blue", "salmon", "medium aquamarine", "orange", "chartreuse" ] line.type = ["dot", "dash", "dash-dot", "long-dash", "solid", "dash"] # Customize the markers drawn marker = vcs.createmarker() marker.size = 6 # You can just use the same colors as the lines marker.color = line.color marker.type = [ "triangle_up", "plus", "diamond", "circle", "cross", "triangle_down" ]
# Set levels to ignore 0 boxfill.levels = [1, 100] # Pick a color, any color boxfill.fillareacolors = [242] dataonly = vcs.createtemplate() dataonly.blank() dataonly.data.priority = 1 multitemplate = EzTemplate.Multi(template=dataonly, rows=4, columns=3) line_styles = ['long-dash', 'dot', 'dash', 'dash-dot', 'solid'] for i in range(12): cont_index = i % 6 + 1 cont_line = vcs.createline() cont_line.width = i % 3 + 1 cont_line.type = line_styles[i % 5] cont_line.color = i + 200 template = multitemplate.get(i) canvas.plot(clt, template, boxfill, continents=cont_index, continents_line=cont_line, bg=1) # Load the image testing module: testingDir = os.path.join(os.path.dirname(__file__), "..") sys.path.append(testingDir) import checkimage # Create the test image and compare: baseline = sys.argv[1] testFile = "test_continents.png" canvas.png(testFile)
def straightLine(coord, direction="horizontal", color="grey", type="dot"): ln = vcs.createline() if direction[0].lower() == "h": ln.x = [0.001, .999] ln.y = [coord, coord] else: ln.x = [coord, coord] ln.y = [0., 1.] ln.type = type ln.color = [color] canvas.plot(ln) # draw line around the cnavas ln = vcs.createline() ln.width = 6 ln.x = [0, 1, 1, 0, 0] ln.y = [0, 0, 1, 1, 0] canvas.plot(ln) # Viewport coordinates text("[0,0] [Canvas Bottom/Left Viewport Origin]", 0.01, 0.01, "left", "bottom") text("[Canvas Top/Right Viewport Origin] [1, 1]", 0.99, .99, "right", "top") # create the "viewport" area section fa = vcs.createfillarea() fa.x = [vp[0], vp[1], vp[1], vp[0]] fa.y = [vp[2], vp[2], vp[3], vp[3]] fa.color = "lightgrey"
def editor(): editor = LineEditor.LineEditorWidget() line = vcs.createline() editor.setLineObject(line) return editor
def init_polar(): # Create nice polar template try: t = vcs.createtemplate("polar_oned") t.data.x1 = .2 t.data.x2 = .8 t.data.y1 = .2 t.data.y2 = .8 t.legend.x1 = .85 t.legend.x2 = 1 t.legend.y1 = .15 t.legend.y2 = .85 dash = vcs.createline() dash.type = "dash" dot = vcs.createline() dot.type = "dot" t.xtic1.line = dash t.ytic1.line = dot left_aligned = vcs.createtextorientation() left_aligned.halign = "left" left_aligned.valign = "half" t.legend.textorientation = left_aligned except vcs.vcsError: # Template already exists pass # Create some nice default polar GMs degree_polar = polar.Gpo("degrees", template="polar_oned") degree_polar.datawc_x1 = 0 degree_polar.datawc_x2 = 360 degree_polar.xticlabels1 = { i: str(i) for i in range(0, 360, 45) } clock_24 = polar.Gpo("diurnal", template="polar_oned") clock_24.datawc_x1 = 0 clock_24.datawc_x2 = 24 clock_24.clockwise = True # 6 AM on the right clock_24.theta_offset = -6 clock_24.xticlabels1 = { i: str(i) for i in range(0, 24, 3) } clock_24_meridiem = polar.Gpo("diurnal_12_hour", source="diurnal", template="polar_oned") clock_24_meridiem.xticlabels1 = { 0: "12 AM", 3: "3 AM", 6: "6 AM", 9: "9 AM", 12: "12 PM", 15: "3 PM", 18: "6 PM", 21: "9 PM" } clock_12 = polar.Gpo("semidiurnal", source="diurnal", template="polar_oned") clock_12.datawc_x2 = 12 clock_12.xticlabels1 = { i: str(i) for i in range(3, 13, 3) } # 3 on the right clock_12.theta_offset = -3 annual_cycle = polar.Gpo("annual_cycle", template="polar_oned") annual_cycle.datawc_x1 = 1 annual_cycle.datawc_x2 = 13 annual_cycle.clockwise = True annual_cycle.xticlabels1 = { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec" } # Put December on the top annual_cycle.theta_offset = -2 seasonal = polar.Gpo("seasonal", template="polar_oned") seasonal.datawc_x1 = 0 seasonal.datawc_x2 = 4 seasonal.xticlabels1 = {0: "DJF", 1: "MAM", 2: "JJA", 3: "SON"} seasonal.clockwise = True # DJF on top seasonal.theta_offset = -1
def plot(self, var, theta=None, template=None, bg=0, x=None): """ Plots a polar plot of your data. If var is an ndarray with the second dimension being 2, it will use the first value as magnitude and the second as theta. Otherwise, if theta is provided, it uses var as magnitude and the theta given. """ if x is None: if self.x is None: self.x = vcs.init() x = self.x if template is None: template = self.template if self.markercolorsource.lower() not in ("group", "magnitude", "theta"): raise ValueError( "polar.markercolorsource must be one of: 'group', 'magnitude', 'theta'" ) magnitudes, thetas, names = convert_arrays(var, theta) if not self.negative_magnitude: # negative amplitude means 180 degree shift neg = numpy.ma.less(magnitudes, 0.0) magnitudes = numpy.ma.abs(magnitudes) thetas = numpy.ma.where(neg, theta + numpy.pi, theta) if self.group_names: names = self.group_names while len(names) < len(magnitudes): names.append(None) flat_magnitude = numpy.ravel(magnitudes) canvas = x # Determine aspect ratio for plotting the circle canvas_info = canvas.canvasinfo() # Calculate aspect ratio of window window_aspect = canvas_info["width"] / float(canvas_info["height"]) if window_aspect > 1: ymul = window_aspect xmul = 1 else: ymul = 1 xmul = window_aspect # Use window_aspect to adjust size of template.data x0, x1 = template.data.x1, template.data.x2 y0, y1 = template.data.y1, template.data.y2 xdiff = abs(x1 - x0) ydiff = abs(y1 - y0) center = x0 + xdiff / 2., y0 + ydiff / 2. diameter = min(xdiff, ydiff) radius = diameter / 2. plot_kwargs = {"render": False, "bg": bg, "donotstoredisplay": True} # Outer line if template.box1.priority > 0: outer = vcs.createline(source=template.box1.line) x, y = circle_points(center, radius, ratio=window_aspect) outer.x = x outer.y = y canvas.plot(outer, **plot_kwargs) del vcs.elements["line"][outer.name] if numpy.allclose((self.datawc_y1, self.datawc_y2), 1e20): if self.magnitude_ticks == "*": m_scale = vcs.mkscale(*vcs.minmax(flat_magnitude)) else: if isinstance(self.magnitude_ticks, str): ticks = vcs.elements["list"][self.magnitude_ticks] else: ticks = self.magnitude_ticks m_scale = ticks else: m_scale = vcs.mkscale(self.datawc_y1, self.datawc_y2) if template.ytic1.priority > 0: m_ticks = vcs.createline(source=template.ytic1.line) m_ticks.x = [] m_ticks.y = [] if template.ylabel1.priority > 0: to = self.text_orientation_for_angle( self.magnitude_tick_angle + self.theta_offset, source=template.ylabel1.textorientation) m_labels = self.create_text(template.ylabel1.texttable, to) m_labels.x = [] m_labels.y = [] m_labels.string = [] if self.yticlabels1 == "*": mag_labels = vcs.mklabels(m_scale) else: mag_labels = self.yticlabels1 else: m_labels = None for lev in m_scale: lev_radius = radius * self.magnitude_from_value(lev, m_scale) x, y = circle_points(center, lev_radius, ratio=window_aspect) if m_labels is not None: if lev in mag_labels: m_labels.string.append(mag_labels[lev]) m_labels.x.append(xmul * lev_radius * numpy.cos(self.magnitude_tick_angle + self.theta_offset) + center[0]) m_labels.y.append(ymul * lev_radius * numpy.sin(self.magnitude_tick_angle + self.theta_offset) + center[1]) m_ticks.x.append(x) m_ticks.y.append(y) canvas.plot(m_ticks, **plot_kwargs) del vcs.elements["line"][m_ticks.name] if m_labels is not None: canvas.plot(m_labels, **plot_kwargs) del vcs.elements["textcombined"][m_labels.name] if template.ymintic1.priority > 0 and self.magnitude_mintics is not None: mag_mintics = vcs.createline(source=template.ymintic1.line) mag_mintics.x = [] mag_mintics.y = [] mintics = self.magnitude_mintics if isinstance(mintics, str): mintics = vcs.elements["list"][mintics] for mag in mintics: mintic_radius = radius * \ self.magnitude_from_value(mag, m_scale) x, y = circle_points(center, mintic_radius, ratio=window_aspect) mag_mintics.x.append(x) mag_mintics.y.append(y) canvas.plot(mag_mintics, **plot_kwargs) del vcs.elements["line"][mag_mintics.name] if self.xticlabels1 == "*": if numpy.allclose((self.datawc_x1, self.datawc_x2), 1e20): tick_thetas = list(numpy.arange(0, numpy.pi * 2, numpy.pi / 4)) tick_labels = {t: str(t) for t in tick_thetas} else: d_theta = (self.datawc_x2 - self.datawc_x1) / \ float(self.theta_tick_count) tick_thetas = numpy.arange(self.datawc_x1, self.datawc_x2 + .0001, d_theta) tick_labels = vcs.mklabels(tick_thetas) else: tick_thetas = sorted(list(self.xticlabels1.keys())) tick_labels = self.xticlabels1 if template.xtic1.priority > 0: t_ticks = vcs.createline(source=template.xtic1.line) t_ticks.x = [] t_ticks.y = [] if template.xlabel1.priority > 0: t_labels = [] theta_labels = tick_labels else: t_labels = None for t in tick_thetas: angle = self.theta_from_value(t) x0 = center[0] + (xmul * radius * numpy.cos(angle)) x1 = center[0] y0 = center[1] + (ymul * radius * numpy.sin(angle)) y1 = center[1] if t_labels is not None: label = self.create_text( template.xlabel1.texttable, self.text_orientation_for_angle( angle, source=template.xlabel1.textorientation)) label.string = [theta_labels[t]] label.x = [x0] label.y = [y0] t_labels.append(label) t_ticks.x.append([x0, x1]) t_ticks.y.append([y0, y1]) canvas.plot(t_ticks, **plot_kwargs) del vcs.elements["line"][t_ticks.name] if t_labels is not None: for l in t_labels: canvas.plot(l, **plot_kwargs) del vcs.elements["textcombined"][l.name] values = vcs.createmarker() values.type = self.markertypes values.size = self.markersizes values.color = self.markercolors values.colormap = self.colormap values.priority = self.markerpriority values.x = [] values.y = [] if template.legend.priority > 0: # Only labels that are set will show up in the legend label_count = len(names) - len([i for i in names if i is None]) labels = self.create_text(template.legend.texttable, template.legend.textorientation) labels.x = [] labels.y = [] labels.string = [] if self.linepriority > 0: line = vcs.createline() line.x = [] line.y = [] line.type = self.linetypes line.color = self.linecolors if self.linecolors is not None else self.markercolors line.width = self.linewidths line.priority = self.linepriority # This is up here because when it's part of the main loop, we can # lose "order" of points when we flatten them. for mag, theta in zip(magnitudes, thetas): x = [] y = [] for m, t in zip(mag, theta): t = self.theta_from_value(t) r = self.magnitude_from_value(m, m_scale) * radius if r == numpy.nan: continue x.append(xmul * numpy.cos(t) * r + center[0]) y.append(ymul * numpy.sin(t) * r + center[1]) if self.connect_groups: line.x.extend(x) line.y.extend(y) else: line.x.append(x) line.y.append(y) if self.markercolorsource.lower() in ('magnitude', "theta"): # Regroup the values using the appropriate metric mag_flat = numpy.array(magnitudes).flatten() theta_flat = numpy.array(thetas).flatten() if self.markercolorsource.lower() == "magnitude": scale = m_scale vals = mag_flat else: scale = tick_thetas vals = theta_flat indices = [ numpy.where( numpy.logical_and(vals >= scale[i], vals <= scale[i + 1])) for i in range(len(scale) - 1) ] magnitudes = [mag_flat[inds] for inds in indices] thetas = [theta_flat[inds] for inds in indices] names = vcs.mklabels(scale, output="list") names = [ names[i] + " - " + names[i + 1] for i in range(len(names) - 1) ] label_count = len(names) for mag, theta, name in zip(magnitudes, thetas, names): x = [] y = [] for m, t in zip(mag, theta): t = self.theta_from_value(t) r = self.magnitude_from_value(m, m_scale) * radius x.append(xmul * numpy.cos(t) * r + center[0]) y.append(ymul * numpy.sin(t) * r + center[1]) if template.legend.priority > 0 and name is not None: y_offset = len(labels.x) / float(label_count) * \ (template.legend.y2 - template.legend.y1) lx, ly = template.legend.x1, template.legend.y1 + y_offset x.append(lx) y.append(ly) labels.x.append(lx + .01) labels.y.append(ly) labels.string.append(str(name)) values.x.append(x) values.y.append(y) if template.legend.priority > 0: canvas.plot(labels, **plot_kwargs) del vcs.elements["textcombined"][labels.name] if self.linepriority > 0: canvas.plot(line, **plot_kwargs) del vcs.elements["line"][line.name] for el in self.to_cleanup: if vcs.istexttable(el): if el.name in vcs.elements["texttable"]: del vcs.elements["texttable"][el.name] else: if el.name in vcs.elements["textorientation"]: del vcs.elements["textorientation"][el.name] self.to_cleanup = [] # Prune unneeded levels from values to_prune = [] for ind, (x, y) in enumerate(zip(values.x, values.y)): if x and y: continue else: to_prune.append(ind) for prune_ind in to_prune[::-1]: del values.x[prune_ind] del values.y[prune_ind] if len(values.color) > prune_ind and len(values.color) > 1: del values.color[prune_ind] if len(values.size) > prune_ind and len(values.size) > 1: del values.size[prune_ind] if len(values.type) > prune_ind and len(values.type) > 1: del values.type[prune_ind] canvas.plot(values, bg=bg, donotstoredisplay=True) del vcs.elements["marker"][values.name] return canvas
os.remove("test_vcs_dump_json.json") b = vcs.createboxfill("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createisofill("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createisoline("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createmeshfill("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.create1d("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createfillarea("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createvector("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createtext("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createline("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createmarker("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createtemplate("vcs_instance") b.script("test_vcs_dump_json", "a") b = vcs.createprojection("vcs_instance") b.script("test_vcs_dump_json", "a") print "Comparing:", os.path.realpath("test_vcs_dump_json.json"), src assert (filecmp.cmp("test_vcs_dump_json.json", src)) os.remove("test_vcs_dump_json.json")
import vcs l = vcs.createline("vcs_test_set_line") l.color = 242 l.width = 5.6 l.type = "dash" v = vcs.createvector() v.setLineAttributes("vcs_test_set_line") assert (v.linecolor == 242) assert (v.linewidth == 5.6) assert (v.linetype == "dash") yx = vcs.create1d() yx.setLineAttributes(l) assert (yx.linecolor == 242) assert (yx.linewidth == 5.6) assert (yx.linetype == "dash") iso = vcs.createisoline() # Note "solid" is a line name. iso.setLineAttributes([l, "solid", l]) assert (iso.linecolors == [242, 1, 242]) assert (iso.linewidths == [5.6, 1, 5.6]) assert (iso.linetypes == ['dash', 'solid', 'dash'])