def residgraph(w,h0,h1,ax,ay0,ay1,k=None): """Canvas with linked-axis graphs for residuals plot""" c = canvas.canvas() g0 = c.insert(graph.graphxy(width=w, height=h0, x=ax, y=ay0)) g1 = c.insert(graph.graphxy(width=w, height=h1, ypos=g0.height+0.1, key=k, x=graph.axis.linkedaxis(g0.axes["x"]), y=ay1)) return c,g0,g1
def example4(): g = graph.graphxy( width=8, x=axis.lin(title=r'$x_1$'), y=axis.lin(min=-1,max=1.5,title=r'$y_1$'), ) g.plot( graph.data.function("y(x)=2*exp(-30*x)-exp(-3*x)", min=0, max=1), ) insetparams = dict( #height = width*float(image.shape[0])/image.shape[1] labeldist=0.2, labelattrs=[text.size.footnotesize], ) p=axis.painter.regular(**insetparams) gi = graph.graphxy( width=3, x=axis.lin(min=0, max=2, painter=p), y=axis.lin(painter=p), ) gi.plot(graph.data.function("y(x)=cos(20*x)*exp(-2*x)", min=0,max=2)) x, y = g.vpos(0.9, 0.9) g.insert(gi, [trafo.translate(x-gi.bbox().right(), y-gi.bbox().top())]) g.writePDFfile("example4.pdf")
def example3(): """ 0,0 is bottom left in pyx land, but it is more common for "first" to be upper left """ c = canvas.canvas() g1 = graph.graphxy( width=8, x=axis.lin(title=r'$x_1$'), y=axis.lin(title=r'$y_1$'), ) g1.plot( [graph.data.function("y(x)=0", min=0, max=1), graph.data.function("y(x)=2*exp(-30*x)-exp(-3*x)", min=0, max=1)], ) c.insert(g1) g2 = graph.graphxy( width=8, ypos=g1.height+1.5, x=axis.lin(title=r'$x_2$'), y=axis.lin(title=r'$y_2$'), ) c.insert(g2) g2.plot(graph.data.function("y(x)=cos(20*x)*exp(-2*x)",min=0,max=2)) g3 = graph.graphxy( width=8, ypos=g1.height+1.5, xpos=g1.width+2.0, x=axis.lin(title=r'$x_3$'), y=axis.lin(title=r'$y_3$'), ) g3.plot(graph.data.function("y(x)=cos(20*x)*exp(-2*x)",min=0,max=2)) c.insert(g3) g4 = graph.graphxy( width=8, #ypos=g1.height, xpos=g1.width+2.0, x=axis.lin(title=r'$x_4$'), y=axis.lin(title=r'$y_4$'), ) g4.plot(graph.data.function("y(x)=cos(20*x)*exp(-2*x)",min=0,max=2)) c.insert(g4) c.writePDFfile("example3.pdf") c.writeGSfile("example3.png")
def plot_scans(fname): scans = load_scans(fname) cols = rainbow(len(scans)) gPhi = graph.graphxy(width=10,height=6, x=graph.axis.lin(title="position [cm]", min = -0.5, max = 3), y=graph.axis.lin(title="potential [kV]", max = 0.04)) gEt = graph.graphxy(width=12,height=8, x=graph.axis.lin(title="position [cm]", min = -8, max = 8), y=graph.axis.lin(title="transverse field [V/cm]", min = -4, max = 0.5), key=graph.key.key(pos="bl")) gEa = graph.graphxy(width=10,height=6, x=graph.axis.lin(title="position [cm]", min = -1, max = 1), y=graph.axis.lin(title="axial field [V/cm]")) V = 4.1 BC1 = BesselCalcs(5.5) BC1.add_endcircle(4.14, V) BC2 = BesselCalcs(10.) BC2.add_endcircle(10, 3*V) BC2.add_endcircle(6.5, -3*V) BC2.add_endcircle(3.928, V) BC2 = TwoEndedBessel(10, BC2) def bccombo(r,z): if z < 0: return BC1.Er(r,-z) return BC2.Er(r,z) for (n,sc) in enumerate(scans): print sc.r(), sc.npts gdat = [(p.x[2], p.phi, p.Er, p.E[0], p.E[1], p.E[2]) for p in sc.pts] gtitle = "$r = %.1f$ cm"%sc.r() plotl = [graph.style.line([cols[n], style.linewidth.thin])] plotl2 = [graph.style.line([cols[n], style.linestyle.dashed, style.linewidth.THin])] gPhi.plot(graph.data.points(gdat,x=1,y=2), plotl) gEt.plot(graph.data.points(gdat,x=1,y=3,title=gtitle), plotl) #gEt.plot(graph.data.points(gdat,x=1,y=5), plotl2) gEa.plot(graph.data.points(gdat,x=1,y=6), plotl) gdat_endsim = [(p.x[2], bccombo(p.r(),p.x[2])) for p in sc.pts[::5]] gEt.plot(graph.data.points(gdat_endsim,x=1,y=2,title=None), plotl2) gPhi.writetofile("FieldScans.pdf") gEt.writetofile("FieldScans_Et.pdf") gEa.writetofile("FieldScans_Ea.pdf")
def example5(): data = numpy.random.normal(loc=0.2, scale=1.2, size=1000) x = numpy.linspace(-3.5, 3.5, 30) y = numpy.exp( - 0.5*(x-0.1)**2 ) key=graph.key.key(pos='tl') g = graph.graphxy( width=8, x=axis.lin(title=r'$score$'), y=axis.lin(min=0, max=1.1), key=key, ) d = graph.data.values( x=x, y=y, title='data', ) lineattrs=[colors('blue')] styles=[ graph.style.histogram(lineattrs=lineattrs,steps=1), ] g.plot(d, styles=styles) g.writePDFfile("example5.pdf") g.writeGSfile("example5.png")
def plot_gluck1993_a_cxn(): npts = 100 gdat = [] for i in range(npts+1)[1:]: E = m + i*(D-m)/npts a0p = a_ideal(E,0) a0m = a_ideal(E,pi) r_e = 0.01*gluck_1993_r_e(E) ap = a0p*(1 + r_e + 0.01*gluck_1993_r_enu(E,0)) am = a0m*(1 + r_e + 0.01*gluck_1993_r_enu(E,pi)) print E, a0p, a0m print "\t", ap, am print "\t", gluck_1993_r_enu(E,0), gluck_1993_r_enu(E,pi) a0 = (a0p-a0m)/(a0p+a0m) a = (ap-am)/(ap+am) gdat.append([E-m,(a-a0)/a0*100, 100*alpha*hmg(E)/(2*pi)]) g = graph.graphxy(width=10,height=6, x=graph.axis.lin(title="kinetic energy [keV]",min=0,max=D-m), y=graph.axis.lin(title="$(a_{\\rm meas}-a_0)/a_0$ [\\%]"), key=graph.key.key(pos="bl")) g.plot(graph.data.points(gdat,x=1,y=2,title='Gl\\"uck'),[graph.style.line([style.linewidth.THick])]) g.plot(graph.data.points(gdat,x=1,y=3,title="Garc\\'ia-Maya"),[graph.style.line([style.linewidth.Thick, style.linestyle.dotted])]) g.writetofile("Gluck_1993_a_cxn.pdf")
def transverse_field_study(): GT = load_Gordon_tables() Brange = 0.2 gMagF = graph.graphxy( width=10, height=6, x=graph.axis.lin(title="position [m]", min=0, max=3), y=graph.axis.lin(title="$B_r$ [Gauss]", max=Brange, min=-Brange), key=graph.key.key(pos="tl", columns=2), ) nr = 7 cls = rainbow(nr) for r in range(nr): ttl = "r = %i cm" % r gMagF.plot( graph.data.points(GT[0].get_radius_dat(r, 1), x=1, y=2, title=ttl), [graph.style.line([style.linewidth.Thick, cls[r]])], ) M = MPM_Table("Sym_Fat_2") Bt = transverse_from_axial(M.get_zdat(), 0.01 * (nr - 1), 1) # GT[0].get_radius_dat(0), 0.01*(nr-1)) gMagF.plot( graph.data.points(Bt, x=1, y=2, title="MPM r=%i" % (nr - 1)), [graph.style.line([style.linewidth.Thick])] ) gMagF.writetofile("MagF_transverse.pdf")
def errorBand(g, gdat, nx, ny, ndy, xerr=False): """error band path""" g0 = graph.graphxy(width=g.width, height=g.height, x=graph.axis.linkedaxis(g.axes["x"]), y=graph.axis.linkedaxis(g.axes["y"])) d1, d2 = (None, None) if xerr: d1 = g0.plot( graph.data.points([(g[nx] - g[ndy], g[ny]) for g in gdat], x=1, y=2), [graph.style.line()]) d2 = g0.plot( graph.data.points([(g[nx] + g[ndy], g[ny]) for g in gdat], x=1, y=2), [graph.style.line()]) else: d1 = g0.plot( graph.data.points([(g[nx], g[ny] - g[ndy]) for g in gdat], x=1, y=2), [graph.style.line()]) d2 = g0.plot( graph.data.points([(g[nx], g[ny] + g[ndy]) for g in gdat], x=1, y=2), [graph.style.line()]) g0.finish() p1 = d1.path p2 = d2.path area = (p1 << p2.reversed()) return area
def plot2d(data, mytitle, result_dir=None, xaxistitle="X", yaxistitle="Y", mycolor=(0, 0, 0), minpoint=None, maxpoint=None): ''' data: list of tuples of (x,y) mytitle: determines the name of the of PDF file. Graphs min/max is automatically chosen as to cover the range with 0,1 being covered. To override, provide the defaults minpoint (x,y) and maxpoint(x,y) ''' try: fnameprefix = '-'.join(mytitle.split()) + '-2d' if result_dir: fnameprefix = os.path.join(result_dir, fnameprefix) datafile = fnameprefix + '.dat' with open(datafile, 'w') as f: f.write('\n'.join(['%s\t%s' % (x, y) for x, y in data])) f.close() print 'Data File written: %s' % datafile except: print '%s: Failed to save data file %s' % (mytitle, datafile) traceback.print_exc() try: if minpoint: xmin, ymin = minpoint else: xmin = min(0, min([x for x, y in data])) ymin = min(0, min([y for x, y in data])) if maxpoint: xmax, ymax = maxpoint else: xmax = max([x for x, y in data]) ymax = max([y for x, y in data]) print 'xmin=%s, xmax=%s' % (xmin, xmax) print 'ymin=%s, ymax=%s' % (ymin, ymax) g = graph.graphxy(width=8, x=graph.axis.linear(min=xmin, max=xmax, title=xaxistitle), y=graph.axis.linear(min=ymin, max=ymax, title=yaxistitle)) g.plot(graph.data.points(data, x=1, y=2), styles=[graph.style.line([style.linestyle.solid])]) g.text(g.width / 2, g.height + 0.2, mytitle, [text.halign.center, text.valign.bottom, text.size.large]) g.writePDFfile(fnameprefix) print 'Graph PDF File written: %s.pdf' % fnameprefix except: print '%s: Failed to create Graph' % mytitle traceback.print_exc()
def plot_single_range(data, binsize, width, height): plot_width = width plot_height = height c = canvas.canvas() xmax = 0.0 methods = data.keys() methods.sort() for method in methods: where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'cis') * (data[method]['range'] > 0)) if where[0].shape[0] > 0: xmax = max(xmax, numpy.amax(data[method]['range'][where])) X = data[method]['range'][where] X = numpy.r_[0, X] X[0] = X[1]**2.0 / X[2] xmin = X[0] g = graph.graphxy(width=plot_width, height=plot_height, x=graph.axis.log(painter=painter, min=X[0], max=xmax), y=graph.axis.lin(painter=painter), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) for x in X[1:-1]: pos = ((log(x) - log(xmin)) / (log(xmax) - log(xmin)) * plot_width) g.stroke(path.line(pos, 0, pos, plot_height), [style.linestyle.dotted, style.linewidth.THin]) X = (X[1:]**0.5) * (X[:-1]**0.5) for method in methods: where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'cis') * (data[method]['range'] > 0)) if where[0].shape[0] > 0: Y = data[method]['correlation'][where] g.plot(graph.data.points(zip(X, Y), x=1, y=2), [ graph.style.line( lineattrs=[method_colors[method], style.linewidth.Thick]) ]) if binsize / 1000000 > 0: binstring = "%iMb" % (binsize / 1000000) elif binsize / 1000 > 0: binstring = "%iKb" % (binsize / 1000) else: binstring = str(binsize) g.text(plot_width / 2, plot_height + 0.3, "%s binning" % (binstring), [text.halign.center, text.valign.top, text.size(-2)]) c.insert(g) return c
def make_sourcecal(sdata): g = graph.graphxy(width=10,height=6, x=graph.axis.lin(title="PMT sum [ADC channels]", min=0), y=graph.axis.lin(title="Expected energy [keV]", min=0), key = graph.key.key(pos="tl")) gdat = [(pks["ADC_sum"].center, pks["ADC_sum"].dcenter, pks["MC"].center) for pks in sdata.itervalues()] g.plot(graph.data.points(gdat, x=1, dx=2, y=3, title=None),[graph.style.symbol(symbol.circle)]) LF = LinearFitter(terms=[polyterm(i) for i in range(2)]) LF.fit(gdat,cols=(0,2)) g.plot(graph.data.points(LF.fitcurve(0,4e4), x=1, y=2, title="$%s$"%LF.toLatex(cfmt=".5g")),[graph.style.line(lineattrs=[style.linewidth.Thick])]) g.writetofile("ADCSum_Cal.pdf")
def plot_overall(data, width, height, name): vo = 0.55 ho = 0.7 plot_width = width - ho plot_height = height - vo - 0.3 c = canvas.canvas() methods = data.keys() methods.sort() bar_colors = [] cis_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(data[methods[0]]['interaction'] == 'cis')]) trans_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(data[methods[0]]['interaction'] == 'trans')]) Y = numpy.zeros((len(methods), cis_binsizes.shape[0] + trans_binsizes.shape[0]), dtype=numpy.float32) for i, method in enumerate(methods): for j, binsize in enumerate(cis_binsizes): where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'cis') * (data[method]['range'] == 0)) if where[0].shape[0] > 0: Y[i, j] = data[method]['correlation'][where] for j, binsize in enumerate(trans_binsizes): where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'trans') * (data[method]['range'] == 0)) if where[0].shape[0] > 0: Y[i, j + cis_binsizes.shape[0]] = data[method]['correlation'][where] bar_colors.append(method_colors[method]) Y = numpy.array(Y) g = graph.graphxy(width=plot_width, height=plot_height, x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)), y=graph.axis.lin(painter=painter), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) for i in range(len(methods)): g.plot(graph.data.points(zip(zip(range(Y.shape[1]), [i] * Y.shape[1]), Y[i, :]), xname=1, y=2), [graph.style.changebar([method_colors[methods[i]]])]) c.insert(g, [trafo.translate(ho, vo)]) for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb", "250Kb", "1Mb"]): c.text(ho + plot_width * (i + 0.5) / 6.0, vo - 0.05, "%s" % label, [text.halign.center, text.valign.top, text.size(-3)]) c.text(ho + plot_width * 2.0 / 6.0, 0.05, "cis", [text.halign.center, text.valign.bottom, text.size(-3)]) c.stroke(path.line(ho + 0.2, vo * 0.5, ho - 0.2 + plot_width * 4.0 / 6.0, vo * 0.5), [style.linewidth.THin]) c.text(ho + plot_width * 5.0 / 6.0, 0.05, "trans", [text.halign.center, text.valign.bottom, text.size(-3)]) c.stroke(path.line(ho + 0.2 + plot_width * 4.0 / 6.0, vo * 0.5, ho - 0.2 + plot_width, vo * 0.5), [style.linewidth.THin]) c.text(0, plot_height * 0.5 + vo, "Correlation", [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)]) c.text(plot_width * 0.5 + ho, height, name, [text.halign.center, text.valign.top, text.size(-3)]) return c
def plot(data, xmin, xmax, ymin, ymax): g = graph.graphxy(height=8, width=8, x=graph.axis.linear(min=xmin, max=xmax, title=r"$\mathrm{Re}(c)$"), y=graph.axis.linear(min=ymin, max=ymax, title=r'$\mathrm{Im}(c)$')) g.plot(graph.data.points(data, x=1, y=2, color=3), [ graph.style.density(gradient=color.gradient.ReverseJet, keygraph=None) ]) g.writePDFfile() g.writeGSfile(device="png16m", resolution=600)
def plot_overall(data, width, height, int_type): methods = data.keys() methods.sort() vo = 0.3 ho = 0.8 plot_width = width - ho plot_height = height - vo - 0.3 c = canvas.canvas() bar_colors = [] binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(data[methods[0]]['interaction'] == int_type)]) Y = numpy.zeros((len(methods), binsizes.shape[0]), dtype=numpy.float32) for i, method in enumerate(methods): for j, binsize in enumerate(binsizes): where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == int_type) * (data[method]['range'] == 0)) if where[0].shape[0] > 0: Y[i, j] = data[method]['correlation'][where] bar_colors.append(method_colors[method]) Y = numpy.array(Y) minY = numpy.amin(Y) maxY = numpy.amax(Y) spanY = maxY - minY minY -= spanY * 0.05 maxY += spanY * 0.05 g = graph.graphxy(width=plot_width, height=plot_height, x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)), y=graph.axis.lin(painter=painter, min=minY, max=maxY), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) for i in range(len(methods)): g.plot(graph.data.points(zip(zip(range(Y.shape[1]), [i] * Y.shape[1]), Y[i, :]), xname=1, y=2), [graph.style.changebar([method_colors[methods[i]]])]) c.insert(g, [trafo.translate(ho, vo)]) if int_type == 'cis': for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb"]): c.text(ho + plot_width * (i + 0.5) / 4.0, vo - 0.05, "%s" % label, [text.halign.center, text.valign.top, text.size(-3)]) c.text(ho + plot_width * 0.5, height, "Cis", [text.halign.center, text.valign.top, text.size(-2)]) else: for i, label in enumerate(["250Kb", "1Mb"]): c.text(ho + plot_width * (i + 0.5) / 2.0, vo - 0.05, "%s" % label, [text.halign.center, text.valign.top, text.size(-3)]) c.text(ho + plot_width * 0.5, height, "Trans", [text.halign.center, text.valign.top, text.size(-2)]) c.text(0, plot_height * 0.5 + vo, "Correlation", [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)]) return c
def plot_correlated(SP1, SP2): gdat = combo_series_dat((SP1,SP2)) g = graph.graphxy(width=12,height=12, x=SP1.yaxis, y=SP2.yaxis, key=graph.key.key(pos="tl")) g.plot(graph.data.points(gdat,x=2,dx=3,y=4,dy=5,title=None),[graph.style.errorbar(), graph.style.symbol(symbol.circle,size=0.1,symbolattrs=[deco.filled([color.rgb(1,1,1)])])]) LF = LinearFitter(terms=[polyterm(i) for i in range(2)]) LF.fit(gdat, cols=(1,3,4), errorbarWeights = True) chi2 = LF.chisquared() nu = LF.nu() ttl = "$"+LF.toLatex(cfmt=".3g")+"$; $\\chi^2/\\nu = %.1f/%i$"%(chi2,nu) if stats: ttl += " ($P = %.2f$)"%stats.chisqprob(chi2,nu) g.plot(graph.data.points(LF.fittedpoints(True), x=1,y=3,title=ttl), [graph.style.line(lineattrs=[rgb.red])]) g.writetofile(SP1.basepath+SP2.name+"_VS_"+SP1.name+".pdf")
def plot_correlation_diffs(corr1, corr2, name, width, height): ho = 1.2 vo = 0.4 plot_width = width - ho plot_height = height - vo diffs = {} ymin = numpy.inf ymax = -numpy.inf for n in ['Phillips', 'Nora']: for meth in meth_names.keys(): cname = "%s_%s" % (meth, n) diff = corr2[cname] - corr1[cname] ymin = min(ymin, diff) ymax = max(ymax, diff) for meth in meth_names.keys(): cname = "%s_%s" % (meth, name) diffs[meth] = corr2[cname] - corr1[cname] yspan = ymax - ymin ymin -= yspan * 0.05 ymax += yspan * 0.05 yspan = ymax - ymin c = canvas.canvas() g = graph.graphxy( width=plot_width, height=plot_height, x=graph.axis.bar(painter=graph.axis.painter.bar(nameattrs=None)), y=graph.axis.lin(painter=painter, min=ymin, max=ymax), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) w = plot_width / float(len(meth_names) + 1) y0 = -ymin / yspan * plot_height for i, meth in enumerate(methods): col = method_colors[meth] g.stroke( path.rect((i + 0.5) * w, y0, w, diffs[meth] / yspan * plot_height), [deco.filled([col])]) g.stroke(path.line(0, y0, plot_width, y0), [style.linestyle.dotted, style.linewidth.THin]) c.insert(g, [trafo.translate(ho, vo)]) c.text( 0, plot_height * 0.5 + vo, r"$r_{0K} - r_{50K}$", [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)]) c.text(plot_width * 0.5 + ho, vo * 0.5, name, [text.halign.center, text.valign.middle, text.size(-3)]) return c
def make_graph(self, curs): self.xaxis = graph.axis.lin(title = "Series") self.yaxis = graph.axis.lin(title = self.ytitle) if not self.gdat: self.make_gdat(curs) g = graph.graphxy(width=15, height=6, x=self.xaxis, y=self.yaxis, key=graph.key.key(pos="tl")) g.plot(graph.data.points(self.gdat,x=1,y=2,dy=3,title=None), [graph.style.errorbar(errorbarattrs=[color.rgb.blue]), graph.style.symbol(symbol.circle,size=0.1,symbolattrs=[color.rgb.blue, deco.filled([color.rgb(1,1,1)])])]) self.auxfits(g) outf = self.basepath+self.name+".pdf" print "Saving plot to",outf g.writetofile(outf)
def plot_energy_survival(): B = 364 # magnetic field [Gauss] l = 2.75 # electron collimator radius [cm] Emax = 1000 g = graph.graphxy(width=10,height=6, x=graph.axis.lin(title="energy [keV]", min=0, max=Emax), y=graph.axis.log(title="collimator pass fraction", min=0.001, max=1), key = graph.key.key(pos="tr")) gdat = [(KE, sphere_survival_fraction(l, 0, electron_Larmor(KE,B)), distrib_vertex_survival(l,electron_Larmor(KE,B)) ) for KE in unifrange(0, Emax, 500)] g.plot(graph.data.points(gdat,x=1,y=2,title="centered"),[graph.style.line([style.linewidth.Thick])]) g.plot(graph.data.points(gdat,x=1,y=3,title="volume averaged"),[graph.style.line([style.linewidth.Thick,style.linestyle.dashed])]) g.writetofile("Survival.pdf")
def plot2d(data, mytitle, result_dir=None, xaxistitle="X", yaxistitle="Y", mycolor=(0,0,0), minpoint=None, maxpoint=None): ''' data: list of tuples of (x,y) mytitle: determines the name of the of PDF file. Graphs min/max is automatically chosen as to cover the range with 0,1 being covered. To override, provide the defaults minpoint (x,y) and maxpoint(x,y) ''' try: fnameprefix = '-'.join(mytitle.split()) + '-2d' if result_dir: fnameprefix = os.path.join(result_dir, fnameprefix) datafile = fnameprefix + '.dat' with open(datafile, 'w') as f: f.write('\n'.join(['%s\t%s' % (x,y) for x,y in data])) f.close() print 'Data File written: %s' % datafile except: print '%s: Failed to save data file %s' % (mytitle, datafile) traceback.print_exc() try: if minpoint: xmin,ymin = minpoint else: xmin = min(0,min([x for x,y in data])) ymin = min(0,min([y for x,y in data])) if maxpoint: xmax,ymax = maxpoint else: xmax = max([x for x,y in data]) ymax = max([y for x,y in data]) print 'xmin=%s, xmax=%s' % (xmin, xmax) print 'ymin=%s, ymax=%s' % (ymin, ymax) g = graph.graphxy(width=8, x = graph.axis.linear(min=xmin, max=xmax,title=xaxistitle), y = graph.axis.linear(min=ymin, max=ymax,title=yaxistitle)) g.plot(graph.data.points(data, x=1,y=2), styles = [ graph.style.line([ style.linestyle.solid]) ] ) g.text(g.width/2, g.height + 0.2, mytitle, [text.halign.center, text.valign.bottom,text.size.large]) g.writePDFfile(fnameprefix) print 'Graph PDF File written: %s.pdf' % fnameprefix except: print '%s: Failed to create Graph' % mytitle traceback.print_exc()
def plot_single_range(data, binsize, width, height): plot_width = width plot_height = height c = canvas.canvas() xmax = 0.0 methods = data.keys() methods.sort() for method in methods: where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'cis') * (data[method]['range'] > 0)) if where[0].shape[0] > 0: xmax = max(xmax, numpy.amax(data[method]['range'][where])) X = data[method]['range'][where] X = numpy.r_[0, X] X[0] = X[1] ** 2.0 / X[2] xmin = X[0] g = graph.graphxy(width=plot_width, height=plot_height, x=graph.axis.log(painter=painter, min=X[0], max=xmax), y=graph.axis.lin(painter=painter), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) for x in X[1:-1]: pos = ((log(x) - log(xmin)) / (log(xmax) - log(xmin)) * plot_width) g.stroke(path.line(pos, 0, pos, plot_height), [style.linestyle.dotted, style.linewidth.THin]) X = (X[1:] ** 0.5) * (X[:-1] ** 0.5) for method in methods: where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'cis') * (data[method]['range'] > 0)) if where[0].shape[0] > 0: Y = data[method]['correlation'][where] g.plot(graph.data.points(zip(X, Y), x=1, y=2), [graph.style.line(lineattrs=[method_colors[method], style.linewidth.Thick])]) if binsize / 1000000 > 0: binstring = "%iMb" % (binsize / 1000000) elif binsize / 1000 > 0: binstring = "%iKb" % (binsize / 1000) else: binstring = str(binsize) g.text(plot_width / 2, plot_height + 0.3, "%s binning" % (binstring), [text.halign.center, text.valign.top, text.size(-2)]) c.insert(g) return c
def render(logset, width=100, only_current=True, plot_current=True, low=-500, high=500, before='', since='', accounts=''): all_accts = fsudb.Account.All() if accounts: aids = [int(i) for i in accounts.split(',')] logset = [i for i in logset if i[2] in aids] if since: since = time.mktime(time.strptime(since, ISO_TIME)) logset = [i for i in logset if i[0] >= since] if before: before = time.mktime(time.strptime(before, ISO_TIME)) logset = [i for i in logset if i[0] <= before] if plot_current: for acct in all_accts: values = [i[5] for i in logset if i[2] == acct.aid] if not values: continue lastval = values[-1] logset.append([time.time(), 'renderer', acct.aid, 'balance', lastval, acct.balance, 'TEMPORARY entry to plot correctly']) series = [] accts = set([i[2] for i in logset if i[3] == 'balance']) if only_current: accts -= set([i[2] for i in logset if i[3] == 'aid' and i[5] is None]) for acct in sorted(list(accts)): names = [i.name for i in all_accts if i.aid == acct] if names: name = names[-1] else: name = '' points = [] for entry in logset: if entry[2] != acct or entry[3] != 'balance': continue points.extend([(entry[0], clamp(entry[4], low, high)), (entry[0], clamp(entry[5], low, high))]) series.append(graph.data.points(points, x=1, y=2, title=('Account %d (%s)'%(acct, tex_escape(name))))) g = graph.graphxy(width=width, x=graph.axis.lin(texter=graph_axis_time()), key=graph.key.key(pos='br', dist=0.1)) g.plot(series, [graph.style.line([style.linestyle.solid, color.gradient.Rainbow])]) if plot_current: all_values = [i[4] for i in logset if i[3] == 'balance' and i[4] is not None] + [i[5] for i in logset if i[3] == 'balance' and i[5] is not None] actual_min = max(min(all_values), low) actual_max = min(max(all_values), high) g.plot(graph.data.values(x=[time.time(), time.time()], y=[actual_min, actual_max], title=time.strftime(ISO_TIME)), [graph.style.line()]) output = StringIO() g.writeSVGfile(output) return output
def plot_overall(data, width, height): plot_width = width - 0.4 plot_height = height - 0.4 c = canvas.canvas() methods = data.keys() methods.sort() bar_colors = [] cis_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(data[methods[0]]['interaction'] == 'cis')]) trans_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(data[methods[0]]['interaction'] == 'trans')]) Y = numpy.zeros((len(methods), cis_binsizes.shape[0] + trans_binsizes.shape[0]), dtype=numpy.float32) for i, method in enumerate(methods): for j, binsize in enumerate(cis_binsizes): where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'cis') * (data[method]['range'] == 0)) if where[0].shape[0] > 0: Y[i, j] = data[method]['correlation'][where] for j, binsize in enumerate(trans_binsizes): where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'trans') * (data[method]['range'] == 0)) if where[0].shape[0] > 0: Y[i, j + cis_binsizes.shape[0]] = data[method]['correlation'][where] bar_colors.append(method_colors[method]) Y = numpy.array(Y) g = graph.graphxy(width=plot_width, height=plot_height, x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)), y=graph.axis.lin(painter=painter), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) for i in range(len(methods)): g.plot(graph.data.points(zip(zip(range(Y.shape[1]), [i] * Y.shape[1]), Y[i, :]), xname=1, y=2), [graph.style.changebar([method_colors[methods[i]]])]) step = plot_width / (cis_binsizes.shape[0] + trans_binsizes.shape[0]) for i, binsize in enumerate(cis_binsizes): g.text(step * (0.5 + i), -0.05, "%s cis" % (str(binsize/1000) + 'Kb').replace('000Kb', 'Mb'), [text.halign.right, text.valign.middle, text.size(-4), trafo.rotate(45)]) for i, binsize in enumerate(trans_binsizes): g.text(step * (0.5 + i + cis_binsizes.shape[0]), -0.05, "%s trans" % (str(binsize/1000) + 'Kb').replace('000Kb', 'Mb'), [text.halign.right, text.valign.middle, text.size(-4), trafo.rotate(45)]) c.insert(g, [trafo.translate(0.7, 0.4)]) c.text(0, plot_height / 2.0 + 0.4, "Dataset Correlation", [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)]) return c
def errorBand(g,gdat,nx,ny,ndy,xerr=False): """error band path""" g0=graph.graphxy(width=g.width,height=g.height, x=graph.axis.linkedaxis(g.axes["x"]), y=graph.axis.linkedaxis(g.axes["y"])) d1,d2 = (None,None) if xerr: d1 = g0.plot(graph.data.points([(g[nx]-g[ndy],g[ny]) for g in gdat],x=1,y=2), [graph.style.line()]) d2 = g0.plot(graph.data.points([(g[nx]+g[ndy],g[ny]) for g in gdat],x=1,y=2), [graph.style.line()]) else: d1 = g0.plot(graph.data.points([(g[nx],g[ny]-g[ndy]) for g in gdat],x=1,y=2), [graph.style.line()]) d2 = g0.plot(graph.data.points([(g[nx],g[ny]+g[ndy]) for g in gdat],x=1,y=2), [graph.style.line()]) g0.finish() p1 = d1.path p2 = d2.path area = (p1 << p2.reversed()) return area
def plot_bilenkii_a_cxn(): npts = 100 gdat = [] for i in range(npts+1): E = m + i*(D-m)/npts a0p = a_ideal(E,0) a0m = a_ideal(E,pi) ap = bilenkii_1959_a_cxn(E,0) am = bilenkii_1959_a_cxn(E,pi) a0 = (a0p-a0m)/(a0p+a0m) a = (ap-am)/(ap+am) gdat.append([E-m,(a-a0)/a0*100,]) g = graph.graphxy(width=10,height=6, x=graph.axis.lin(title="kinetic energy [keV]",min=0,max=D-m), y=graph.axis.lin(title="$(a_{\\rm meas}-a_0)/a_0$ [\\%]")) g.plot(graph.data.points(gdat,x=1,y=2),[graph.style.line([style.linewidth.THIck])]) g.writetofile("Bilenkii_1959_a_cxn.pdf")
def plot_correlation_diffs(corr1, corr2, name, width, height): ho = 1.2 vo = 0.4 plot_width = width - ho plot_height = height - vo diffs = {} ymin = numpy.inf ymax = -numpy.inf for n in ['Phillips', 'Nora']: for meth in meth_names.keys(): cname = "%s_%s" % (meth, n) diff = corr2[cname] - corr1[cname] ymin = min(ymin, diff) ymax = max(ymax, diff) for meth in meth_names.keys(): cname = "%s_%s" % (meth, name) diffs[meth] = corr2[cname] - corr1[cname] yspan = ymax - ymin ymin -= yspan * 0.05 ymax += yspan * 0.05 yspan = ymax - ymin c = canvas.canvas() g = graph.graphxy(width=plot_width, height=plot_height, x=graph.axis.bar(painter=graph.axis.painter.bar(nameattrs=None)), y=graph.axis.lin(painter=painter, min=ymin, max=ymax), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) w = plot_width / float(len(meth_names) + 1) y0 = -ymin / yspan * plot_height for i, meth in enumerate(methods): col = method_colors[meth] g.stroke( path.rect((i + 0.5) * w, y0, w, diffs[meth] / yspan * plot_height), [deco.filled([col])]) g.stroke( path.line(0, y0, plot_width, y0), [style.linestyle.dotted, style.linewidth.THin]) c.insert(g, [trafo.translate(ho, vo)]) c.text(0, plot_height * 0.5 + vo, r"$r_{0K} - r_{50K}$", [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)]) c.text(plot_width * 0.5 + ho, vo * 0.5, name, [text.halign.center, text.valign.middle, text.size(-3)]) return c
def _get_graph_and_axes(self, **kw): if 'aspect_ratio' in kw: kw['ratio'] = kw['aspect_ratio'] key = kw.pop('key',None) gkw=_unpack_graphxy_keywords(kw) gkw['width'] = gkw.get('width',8) height=gkw.get('height',None) if height is None: aspect_ratio = gkw xaxis,xlog,yaxis,ylog = _get_axes(kw) g = graph.graphxy( x=xaxis, y=yaxis, key=key, #title='blah', **gkw) return g
def gluck_1993_cnxs(): xr_e = [ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95 ] r_e = [ 1.82, 1.74, 1.65, 1.53, 1.40, 1.25, 1.07, 0.84, 0.50, 0.21 ] # Table V, [[c, [r_enu(x)...]], ... ] r_enu = [ [0.9, [ 0.03, 0.04, 0.06, 0.08, 0.10, 0.12, 0.14, 0.16 ]], [0.7, [ 0.03, 0.04, 0.05, 0.07, 0.08, 0.10, 0.11, 0.13 ]], [0.5, [ 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09 ]], [0.3, [ 0.02, 0.02, 0.03, 0.03, 0.04, 0.04, 0.05, 0.06 ]], [0.1, [ 0.01, 0.01, 0.01, 0.02, 0.02, 0.02, 0.02, 0.03 ]], [-0.1,[ 0.01, 0.00, 0.00, -0.00, -0.00, -0.00, -0.01, -0.00 ]], [-0.3,[ -0.00, -0.01, -0.01, -0.02, -0.02, -0.03, -0.03, -0.03 ]], [-0.5,[ -0.01, -0.02, -0.02, -0.05, -0.04, -0.05, -0.05, -0.06 ]], [-0.7,[ -0.01, -0.02, -0.02, -0.05, -0.06, -0.07, -0.08, -0.08 ]], [-0.9,[ -0.02, -0.03, -0.05, -0.06, -0.08, -0.09, -0.10, -0.11 ]] ] # w = F(E)*[1+a*beta*c]*[1 + 0.01*r_e(x) + 0.01*r_enu(x,c)] gx = graph.graphxy(width=10,height=6, x=graph.axis.lin(title='$x$',min=0,max=1), y=graph.axis.lin(title='Gl\\"uck $r_e(x) + r_{e\\nu}(x,c)$')) gc = graph.graphxy(width=10,height=6, x=graph.axis.lin(title='$c$',min=-1,max=1), y=graph.axis.lin(title='Gl\\"uck $r_{e\\nu}(x,c)$'), key=graph.key.key(pos="tl",columns=2)) ccols = rainbowDict([r[0] for r in r_enu]) xcols = rainbowDict(xr_e[1:-1]) cdat = [[x,[]] for x in xr_e[1:-1]] for (c, r) in r_enu: for (n,rr) in enumerate(r): cdat[n][1].append([c,rr]) gdat = [(xr_e[n+1], r_e[n+1]+rr) for (n,rr) in enumerate(r)] gx.plot(graph.data.points(gdat,x=1,y=2),[graph.style.symbol(symbol.circle,size=0.1,symbolattrs=[ccols[c]]), graph.style.line(lineattrs=[ccols[c]])]) gx.writetofile("Gluck_1993_a_cxn_x.pdf") paramdat = [] for (x,gdat) in cdat: LF = LinearFitter(terms=[(lambda z: 1), (lambda z: z)]) LF.fit(gdat) paramdat.append([x,LF.coeffs[0],LF.coeffs[1]]) gc.plot(graph.data.points(gdat,x=1,y=2,title="$x = %g$"%x),[graph.style.symbol(symbol.circle,size=0.1,symbolattrs=[xcols[x]])]) gc.plot(graph.data.points(LF.fitcurve(-1,1),x=1,y=2,title=None),[graph.style.line(lineattrs=[xcols[x]])]) gc.writetofile("Gluck_1993_a_cxn_c.pdf") gcparam = graph.graphxy(width=10,height=6, x=graph.axis.lin(title='$x$',min=0,max=1), y=graph.axis.lin(title='$r_{e\\nu}$ parametrization term',min=0, max=0.2), key=graph.key.key(pos="tl")) LF.fit(paramdat,cols=(0,1)) gcparam.plot(graph.data.points(paramdat,x=1,y=2,title="$r_{e\\nu}^0(x) \\approx %.3f+%.3f \\cdot x$"%tuple(LF.coeffs)),[graph.style.symbol(symbol.circle,size=0.1,symbolattrs=[rgb.red])]) gcparam.plot(graph.data.points(LF.fitcurve(0,1),x=1,y=2,title=None),[graph.style.line(lineattrs=[rgb.red])]) LF.fit(paramdat,cols=(0,2)) gcparam.plot(graph.data.points(paramdat,x=1,y=3,title="$r_{e\\nu}^1(x) \\approx %.3f+%.3f \\cdot x$"%tuple(LF.coeffs)),[graph.style.symbol(symbol.circle,size=0.1,symbolattrs=[rgb.blue])]) gcparam.plot(graph.data.points(LF.fitcurve(0,1),x=1,y=2,title=None),[graph.style.line(lineattrs=[rgb.blue])]) gcparam.writetofile("Gluck_1993_a_cxn_cparam.pdf")
with open(cpu + '.dat') as fh: for line in fh: nr, t4, t1 = line.rstrip('\n').split() nr = int(nr) t1 = float(t1) t4 = float(t4) data[cpu].append((t1, t4)) data[cpu] = [(2**nr, data[cpu][0][0] / t4, t1 / t4) for nr, (t1, t4) in enumerate(data[cpu])] logparter = graph.axis.parter.log(tickpreexps=[ graph.axis.parter.preexp([graph.axis.tick.rational(1, 1)], 2) ]) g = graph.graphxy(width=8, x=graph.axis.log(min=1, max=128, parter=logparter, title='number of divisions per axis'), y=graph.axis.lin(min=0, max=6.5, title='acceleration')) for nr, cpu in enumerate(cpus): g.plot(graph.data.points(data[cpu], x=1, y=2), [ graph.style.line(lineattrs=[style.linestyle.dotted]), graph.style.symbol(symbol=graph.style.symbol.circle, size=0.1, symbolattrs=[deco.filled([color.grey(nr)])]) ]) g.plot(graph.data.points(data[cpu], x=1, y=3), [ graph.style.line(lineattrs=[style.linestyle.solid]), graph.style.symbol(symbol=graph.style.symbol.circle, size=0.1, symbolattrs=[deco.filled([color.grey(nr)])]) ])
def plot_bargraph(data, width, height): methods = ['HiCLib', 'HiCPipe', 'HiCNorm', 'HiFive-Probability', 'HiFive-Binning', 'HiFive-Express', 'HiFive-ExpressKR', 'HiFive-ExpressKR w/distance'] ho = 4.0 left_width = (width - ho) * 0.45 mid_width1 = (width - ho) * 0.3 mid_width2 = (width - ho) * 0.125 right_width = (width - ho) * 0.125 bar_height = height / len(methods) - 0.1 data_totals = {} ranges = numpy.zeros((4, 2), dtype=numpy.float32) for meth in data: data_totals[meth] = find_total(data[meth]) if meth == 'HiCPipe': ranges[1, 1] = data_totals[meth] elif meth == 'HiCNorm': ranges[2, 1] = data_totals[meth] elif meth == 'HiFive-Probability': ranges[3, 1] = data_totals[meth] else: ranges[0, 1] = max(ranges[0, 1], data_totals[meth]) ranges /= 60.0 ranges[0, 1] = 28.0 ranges[1, 0] = ranges[1, 1] - ranges[0, 1] / 0.45 * 0.3 * 0.9 ranges[1, 1] = ranges[1, 1] + ranges[0, 1] / 0.45 * 0.3 * 0.1 ranges[2, 0] = ranges[2, 1] - ranges[0, 1] / 0.45 * 0.125 * 0.5 ranges[2, 1] = ranges[2, 1] + ranges[0, 1] / 0.45 * 0.125 * 0.5 ranges[3, 0] = ranges[3, 1] - ranges[0, 1] / 0.45 * 0.125 * 0.5 ranges[3, 1] = ranges[3, 1] + ranges[0, 1] / 0.45 * 0.125 * 0.5 c = canvas.canvas() g1 = graph.graphxy(width=left_width, height=height, x=graph.axis.lin(painter=painter, min=0, max=ranges[0, 1]), x2=graph.axis.lin(parter=None, min=0, max=ranges[0, 1]), y=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(painter=None, min=0, max=1)) c.insert(g1) g2 = graph.graphxy(width=mid_width1, height=height, x=graph.axis.lin(painter=painter, min=ranges[1, 0], max=ranges[1, 1]), x2=graph.axis.lin(parter=None, min=ranges[1, 0], max=ranges[1, 1]), y2=graph.axis.lin(painter=None, min=0, max=1), y=graph.axis.lin(painter=None, min=0, max=1)) c.insert(g2, [trafo.translate(left_width, 0)]) g3 = graph.graphxy(width=mid_width2, height=height, x=graph.axis.lin(painter=painter, min=ranges[2, 0], max=ranges[2, 1]), x2=graph.axis.lin(parter=None, min=ranges[2, 0], max=ranges[2, 1]), y2=graph.axis.lin(painter=None, min=0, max=1), y=graph.axis.lin(painter=None, min=0, max=1)) c.insert(g3, [trafo.translate(left_width + mid_width1, 0)]) g4 = graph.graphxy(width=right_width, height=height, x=graph.axis.lin(painter=painter, min=ranges[3, 0], max=ranges[3, 1]), x2=graph.axis.lin(parter=None, min=ranges[3, 0], max=ranges[3, 1]), y2=graph.axis.lin(parter=None, min=0, max=1), y=graph.axis.lin(painter=None, min=0, max=1)) c.insert(g4, [trafo.translate(left_width + mid_width1 + mid_width2, 0)]) split = canvas.canvas() split.fill(path.path(path.moveto(-0.15, -0.2), path.lineto(0.05, 0.2), path.lineto(.15, 0.2), path.lineto(-0.05, -0.2), path.closepath()), [color.cmyk.White]) split.stroke(path.line(-0.15, -0.2, 0.05, 0.2)) split.stroke(path.line(-0.05, -0.2, 0.15, 0.2)) c.insert(split, [trafo.translate(left_width, 0)]) c.insert(split, [trafo.translate(left_width, height)]) c.insert(split, [trafo.translate(left_width + mid_width1, 0)]) c.insert(split, [trafo.translate(left_width + mid_width1, height)]) c.insert(split, [trafo.translate(left_width + mid_width1 + mid_width2, 0)]) c.insert(split, [trafo.translate(left_width + mid_width1 + mid_width2, height)]) for i, meth in enumerate(methods): c.insert(plot_bar(data[meth], ranges, bar_height, left_width / ranges[0, 1], split), [trafo.translate(0, height - 0.05 - bar_height * (i + 1) - i * 0.1)]) c.text(-0.1, height * (len(methods) - i - 0.5) / len(methods), meth, [text.halign.right, text.valign.middle, text.size(-2)]) c.text((width - ho) / 2.0, -0.35, "Runtime (minutes)", [text.halign.center, text.valign.top, text.size(-2)]) return c
def field_shaper(with_Ed=False): GT = load_Gordon_tables(with_Ed) B0 = 370 Bmin = 200 if with_Ed: Bmin = 0 gMagF = graph.graphxy( width=10, height=6, x=graph.axis.lin(title="position [m]", min=0, max=3), y=graph.axis.lin(title="$B_z$ [Gauss]", min=Bmin, max=B0 + 10), key=graph.key.key(pos="bl"), ) gMagFNarrow = graph.graphxy( width=10, height=6, x=graph.axis.lin(title="position [m]", min=0, max=3), y=graph.axis.lin(title="$B_z$ [Gauss]", min=350, max=380), ) if with_Ed: targf = make_target([p[0] for p in GT[0].get_radius_dat(0)]) LF = LinearFitter( terms=[fitdict(G.get_radius_dat(0)) for G in GT[1:]], fixparams={1: 1.4, 3: 1.4, 5: 1.4, 8: 5} ) LF.fit(targf, cols=(0, 1, 2)) print LF.coeffs gMagF.plot( graph.data.points(LF.fittedpoints(), x=1, y=3, title=None), [graph.style.symbol(symbol.circle, size=0.02)] ) gMagF.plot( graph.data.points(LF.fittedpoints(), x=1, y=2, title=None), [graph.style.line([style.linewidth.thin, style.linestyle.dotted])], ) gMagFNarrow.plot( graph.data.points(LF.fittedpoints(), x=1, y=3, title=None), [graph.style.symbol(symbol.circle, size=0.02)] ) gMagFNarrow.plot( graph.data.function("y(x) = 368"), [graph.style.line([style.linewidth.thin, style.linestyle.dotted])] ) cls = rainbow(len(GT)) for (n, G) in enumerate(GT): ttl = None if n and with_Ed: ttl = "Scaled by %g" % LF.coeffs[n - 1] # elif with_Ed and not n: # continue lstyle = graph.style.line([style.linewidth.Thick, cls[n]]) if n > 6: lstyle = graph.style.line([style.linewidth.thick, style.linestyle.dotted, cls[n]]) gMagF.plot(graph.data.points(G.get_radius_dat(0, mul=1.0 + (n > 1) * 0), x=1, y=2, title=ttl), [lstyle]) if not n: gMagFNarrow.plot( graph.data.points(G.get_radius_dat(0, mul=1.0 + (n > 1) * 0), x=1, y=2, title=ttl), [graph.style.line([style.linewidth.Thick, cls[n]])], ) if not with_Ed: # M = MPM_Table("Baseline") M = MPM_Table("Baseline") M2 = MPM_Table("Sym_Fat_2") gMagF.plot(graph.data.points(M.get_zdat(), x=1, y=2, title=None), [graph.style.line([style.linewidth.thin])]) gMagF.plot( graph.data.points(M2.get_zdat(), x=1, y=2, title=None), [graph.style.line([style.linewidth.thin, style.linestyle.dashed])], ) gMagF.writetofile("MagF.pdf") gMagFNarrow.writetofile("MagF_Detail.pdf")
def slepc(Gx, Gz, Hx, Hz, Rx, Rz, Pxt, Qx, Pz, Tx, **kw): name = argv.get("name", "ex3.tmp.c") print("slepc: name=%s"%name) r = len(Rx) n = 2**r assert (r<40), "ugh" #code = Code("body.h") code = Code() code.append("#define DIMS (%d)"%n) code.append("static void matmult(PetscScalar *py, const PetscScalar *px, long nx)") code.begin() code.append("assert(DIMS == %d);"%n) code.append("assert(nx == %d);"%n) code.append("memset(py, 0, sizeof(PetscScalar)*nx);") offset = argv.get("offset", None) mz = len(Gz) t = None #excite = argv.excite #if excite is None: excite = kw.get("excite") or argv.excite if excite is not None: print("excite:", excite) if type(excite) is tuple: t = Tx[excite[0]] for i in range(1, len(excite)): t = (t + Tx[excite[i]])%2 else: assert type(excite) in (int, int) t = Tx[excite] print("t:", shortstr(t)) Gzt = dot2(Gz, t) print("Gzt:", shortstr(Gzt)) weights = kw.get("weights") if weights is not None: assert len(weights)==len(Gx) RR = dot2(Gz, Rx.transpose()) PxtQx = dot2(Pxt, Qx) gxs = [getnum(dot2(gx, PxtQx)) for gx in Gx] gxs.sort() uniq_gxs = list(set(gxs)) uniq_gxs.sort() code.append("long v;") code.append("int k;") code.append("struct timeval t0, t1;") code.append("gettimeofday(&t0, NULL);") code.append("for(v=0; v<%d; v++)"%n) code.begin() code.append("double pxv = px[v];") if n >= 128: code.append(r'if((v+1) %% %d == 0)' % (n//128)) code.begin() code.append("gettimeofday(&t1, NULL);") code.append("long delta = t1.tv_sec-t0.tv_sec;") code.append("if(delta>1)") code.append('{printf("[%lds]", delta);fflush(stdout);}') code.append('t0 = t1;') code.end() code.append("k = 0;") for i, row in enumerate(RR): if t is not None and Gzt[i]==1: code.append("k += (countbits_fast(v&%s)+1) %% 2;" % getnum(row)) else: code.append("k += countbits_fast(v&%s) %% 2;" % getnum(row)) cutoff = argv.cutoff if cutoff is not None: code.append("if(k>%d) continue; // <-------- continue" % cutoff) else: code.append("if(k>cutoff) continue; // <-------- continue") code.append("py[v] += pxv * (%d - 2*k);" % mz) if weights is None: for gx in uniq_gxs: s = '+'.join(['pxv']*gxs.count(gx)) code.append("py[v^%s] += %s;" % (gx, s)) else: gxs = [getnum(dot2(gx, PxtQx)) for gx in Gx] for i, gx in enumerate(gxs): code.append("py[v^%s] += %s*pxv;" % (gx, weights[i])) code.end() code.end() if name is None: return s = code.output() src = open("ex3.c").read() match = '\n#include "body.h"\n' assert match in src src = src.replace(match, s) assert name and name.endswith(".c") f = open(name, 'w') tag = hash(src) print(("hash(src):", tag)) f.write(src) f.close() import socket host = socket.gethostname() if host == "bucket": cmd = "gcc MATCH.c -O3 -o MATCH -I/home/simon/local/petsc/arch-linux2-c-debug/include -I/home/simon/local/petsc/include/petsc/mpiuni -I/home/simon/local/petsc/include -I/home/simon/local/slepc-3.7.1/include -I/home/simon/local/slepc-3.7.1/arch-linux2-c-debug/include/ -L/home/simon/local/petsc/arch-linux2-c-debug/lib -L/home/simon/local/slepc-3.7.1/arch-linux2-c-debug/lib -lpetsc -lslepc" elif host == "hero": cmd = "gcc MATCH.c -O3 -o MATCH -I/usr/include/openmpi -I/usr/include/petsc -I/usr/include/slepc -lpetsc -lslepc -lmpi" else: cmd = "gcc -O3 MATCH.c -I/suphys/sburton/include/ -o MATCH -lpetsc -L$PETSC_DIR/$PETSC_ARCH/lib -L$SLEPC_DIR/$PETSC_ARCH/lib -lslepc" cmd = cmd.replace("MATCH.c", name) stem = name[:-2] cmd = cmd.replace("MATCH", stem) rval = os.system(cmd) assert rval == 0 #print("exec:", hash(open(stem).read())) nev = argv.get("nev", 1) cmd = "./%s -eps_nev %d -eps_ncv %d -eps_largest_real" if argv.plot: cmd += " -eps_view_vectors binary:evec.bin " cmd = cmd%(stem, nev, max(2*nev, 4)) eps_tol = argv.get("eps_tol", 1e-4) if eps_tol is not None: cmd += " -eps_tol %s "%eps_tol #cmd += " -eps_type arnoldi -info -eps_monitor -eps_tol 1e-3" print(cmd) #rval = os.system(cmd) #assert rval == 0 f = os.popen(cmd) s = f.read() #print(s) lines = s.split('\n') vals = [] for line in lines: line = line.strip() flds = line.split() #print("parse", flds) try: a, b = flds a = float(a) b = float(b) vals.append(a) except: pass if not argv.plot: print(("vals:", vals)) return vals assert argv.plot.endswith(".pdf") s = open("evec.bin").read() sz = 8*2**r if len(s)==sz+8: s = s[8:] elif len(s)==sz+16: s = s[16:] #elif len(s)==2*(sz+16): # got two vectors # s = s[16:16+sz] # pick the first vector elif len(s)%(sz+16) == 0: count = len(s)/(sz+16) # s = s[16:16+sz] # pick the first vector ev_idx = argv.get("ev_idx", 0) s = s[16+ev_idx*(16+sz):(ev_idx+1)*(16+sz)] else: assert 0, "sz=%d but s=%s"%(sz, len(s)) vec0 = numpy.fromstring(s, dtype=">d") assert len(vec0)==2**r assert excite is None print("graphing...") gz, n = Gz.shape xdata = [] lookup = {} GzRxt = dot2(Gz, Rx.transpose()) for i, v in enumerate(genidx((2,)*r)): v = array2(v) lookup[v.tobytes()] = i syndrome = dot2(GzRxt, v) value = gz - 2*syndrome.sum() xdata.append(value) pdata = {} ndata = {} my = 20. # mul y EPSILON = argv.get("EPSILON", 1e-6) def yfunc(y): y = log2(abs(y)) y = int(round(my*y)) return y for i in range(len(vec0)): x = xdata[i] # integer y = vec0[i] if abs(y) < EPSILON: continue if y > 0.: y = yfunc(y) pdata[x, y] = pdata.get((x, y), 0) + 1 else: y = yfunc(y) ndata[x, y] = ndata.get((x, y), 0) + 1 from pyx import graph, canvas, path, trafo, color, deco, text north = [text.halign.boxcenter, text.valign.top] northeast = [text.halign.boxright, text.valign.top] northwest = [text.halign.boxleft, text.valign.top] south = [text.halign.boxcenter, text.valign.bottom] southeast = [text.halign.boxright, text.valign.bottom] southwest = [text.halign.boxleft, text.valign.bottom] east = [text.halign.boxright, text.valign.middle] west = [text.halign.boxleft, text.valign.middle] center = [text.halign.boxcenter, text.valign.middle] c = canvas.canvas() sx = 0.4 sy = 1.4 tr = trafo.scale(sx, sy) green = color.rgb(0.2,0.6,0.2) brown = color.rgb(0.8,0.2,0.2) grey = color.rgb(0.4,0.4,0.4) lgrey = color.rgb(0.8,0.8,0.8) W = 2*gz H = log2(EPSILON) dy = 0.5 * 1.2/my X0 = -gz Y0 = 0. def showp(gx, radius): v = dot2(gx, PxtQx) syndrome = dot2(GzRxt, v) x = gz - 2*syndrome.sum() i = lookup[v.tobytes()] #print syndrome, syndrome.sum(), vec0[i] y = (1./my)*yfunc(vec0[i]) + 0.5*dy #y = 0.5*dy + log2(abs(vec0[i])) c.fill(path.circle(-x*sx, y*sy, radius), [lgrey]) showp(zeros2(n), 0.8) for gx in Gx: showp(gx, 0.4) for gx0 in Gx: for gx1 in Gx: gx = (gx0+gx1)%2 if gx.sum()==0: continue showp(gx, 0.2) for i in range(0, gz+1): x, y = X0+2*i, Y0 c.stroke(path.line(x, y, x, y+H), [tr, grey]) if i%2 == 0: c.text(x*sx, y*sy + 0.2, "%d"%i, south) c.stroke(path.line(X0, Y0, X0+1.0*W+3.5, Y0), [tr, deco.earrow(size=0.5)]) c.stroke(path.line(X0, Y0, X0, Y0+1.0*H-0.5), [tr, deco.earrow(size=0.5)]) y = 1.0 i = 0 while y > EPSILON: x = X0*sx y1 = sy*(1./my)*yfunc(y) c.stroke(path.line(x, y1, x-0.1, y1)) c.text(x-0.3, y1, "%d"%i, east) y /= 2. i -= 1 R = 0.15 for key, value in list(pdata.items()): x, y = key y = y/my x = -x value = 1 + math.log(value) r = R*value #c.stroke(path.circle(x, y, r)) #c.stroke(path.line(x, y, x+r, y), [brown, tr]) c.fill(path.rect(x, y, r, dy), [brown, tr]) for key, value in list(ndata.items()): x, y = key y = y/my x = -x value = 1 + math.log(value) r = R*value #c.stroke(path.circle(x, y, r)) #c.stroke(path.line(x-r, y, x, y), [green, tr]) c.fill(path.rect(x-r, y, r, dy), [green, tr]) c.writePDFfile(argv.plot) if 0: print("graph..") g = graph.graphxy( width=16, x=graph.axis.linear(reverse=True), y=graph.axis.linear()) #y=graph.axis.log(min=0.8*vec0.min(), max=1.2*vec0.max())) g.plot(graph.data.values(x=xdata, y=ydata)) g.writePDFfile(argv.plot)
def plot_bargraph(data, width, height): methods = [ 'HiCLib', 'HiCPipe', 'HiCNorm', 'HiFive-Probability', 'HiFive-Binning', 'HiFive-Express', 'HiFive-ExpressKR', 'HiFive-ExpressKR w/distance' ] ho = 4.0 left_width = (width - ho) * 0.45 mid_width1 = (width - ho) * 0.3 mid_width2 = (width - ho) * 0.125 right_width = (width - ho) * 0.125 bar_height = height / len(methods) - 0.1 data_totals = {} ranges = numpy.zeros((4, 2), dtype=numpy.float32) for meth in data: data_totals[meth] = find_total(data[meth]) if meth == 'HiCPipe': ranges[1, 1] = data_totals[meth] elif meth == 'HiCNorm': ranges[2, 1] = data_totals[meth] elif meth == 'HiFive-Probability': ranges[3, 1] = data_totals[meth] else: ranges[0, 1] = max(ranges[0, 1], data_totals[meth]) ranges /= 60.0 ranges[0, 1] = 28.0 ranges[1, 0] = ranges[1, 1] - ranges[0, 1] / 0.45 * 0.3 * 0.9 ranges[1, 1] = ranges[1, 1] + ranges[0, 1] / 0.45 * 0.3 * 0.1 ranges[2, 0] = ranges[2, 1] - ranges[0, 1] / 0.45 * 0.125 * 0.5 ranges[2, 1] = ranges[2, 1] + ranges[0, 1] / 0.45 * 0.125 * 0.5 ranges[3, 0] = ranges[3, 1] - ranges[0, 1] / 0.45 * 0.125 * 0.5 ranges[3, 1] = ranges[3, 1] + ranges[0, 1] / 0.45 * 0.125 * 0.5 c = canvas.canvas() g1 = graph.graphxy(width=left_width, height=height, x=graph.axis.lin(painter=painter, min=0, max=ranges[0, 1]), x2=graph.axis.lin(parter=None, min=0, max=ranges[0, 1]), y=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(painter=None, min=0, max=1)) c.insert(g1) g2 = graph.graphxy(width=mid_width1, height=height, x=graph.axis.lin(painter=painter, min=ranges[1, 0], max=ranges[1, 1]), x2=graph.axis.lin(parter=None, min=ranges[1, 0], max=ranges[1, 1]), y2=graph.axis.lin(painter=None, min=0, max=1), y=graph.axis.lin(painter=None, min=0, max=1)) c.insert(g2, [trafo.translate(left_width, 0)]) g3 = graph.graphxy(width=mid_width2, height=height, x=graph.axis.lin(painter=painter, min=ranges[2, 0], max=ranges[2, 1]), x2=graph.axis.lin(parter=None, min=ranges[2, 0], max=ranges[2, 1]), y2=graph.axis.lin(painter=None, min=0, max=1), y=graph.axis.lin(painter=None, min=0, max=1)) c.insert(g3, [trafo.translate(left_width + mid_width1, 0)]) g4 = graph.graphxy(width=right_width, height=height, x=graph.axis.lin(painter=painter, min=ranges[3, 0], max=ranges[3, 1]), x2=graph.axis.lin(parter=None, min=ranges[3, 0], max=ranges[3, 1]), y2=graph.axis.lin(parter=None, min=0, max=1), y=graph.axis.lin(painter=None, min=0, max=1)) c.insert(g4, [trafo.translate(left_width + mid_width1 + mid_width2, 0)]) split = canvas.canvas() split.fill( path.path(path.moveto(-0.15, -0.2), path.lineto(0.05, 0.2), path.lineto(.15, 0.2), path.lineto(-0.05, -0.2), path.closepath()), [color.cmyk.White]) split.stroke(path.line(-0.15, -0.2, 0.05, 0.2)) split.stroke(path.line(-0.05, -0.2, 0.15, 0.2)) c.insert(split, [trafo.translate(left_width, 0)]) c.insert(split, [trafo.translate(left_width, height)]) c.insert(split, [trafo.translate(left_width + mid_width1, 0)]) c.insert(split, [trafo.translate(left_width + mid_width1, height)]) c.insert(split, [trafo.translate(left_width + mid_width1 + mid_width2, 0)]) c.insert(split, [trafo.translate(left_width + mid_width1 + mid_width2, height)]) for i, meth in enumerate(methods): c.insert( plot_bar(data[meth], ranges, bar_height, left_width / ranges[0, 1], split), [ trafo.translate(0, height - 0.05 - bar_height * (i + 1) - i * 0.1) ]) c.text(-0.1, height * (len(methods) - i - 0.5) / len(methods), meth, [text.halign.right, text.valign.middle, text.size(-2)]) c.text((width - ho) / 2.0, -0.35, "Runtime (minutes)", [text.halign.center, text.valign.top, text.size(-2)]) return c
from pyx import color, deco, graph, style with open('numba_parallel.dat') as fh: t_cpu = float(fh.readline().rstrip('\n').split()[1]) t_parallel = [(1, t_cpu)] for _ in range(7): elems = fh.readline().rstrip('\n').split() t_parallel.append((int(elems[0]), float(elems[1]))) t_parallel = [(n, t_cpu / t) for n, t in t_parallel] g = graph.graphxy(width=8, x=graph.axis.linear(min=1, max=8, title="number of threads"), y=graph.axis.linear(title="acceleration")) g.plot(graph.data.points(t_parallel, x=1, y=2), [ graph.style.line([]), graph.style.symbol(symbol=graph.style.symbol.circle, size=0.1, symbolattrs=[deco.filled([color.grey(1)])]) ]) g.writePDFfile() g.writeGSfile(device="png16m", resolution=600)
import numpy as np import numpy.polynomial.polynomial as P from pyx import color, deco, graph, style, text, unit np.random.seed(987) x = np.pi*np.linspace(0, 1, 100) y = np.sin(x)+0.1*np.random.rand(100) fit = P.Polynomial(P.polyfit(x, y, 2)) text.set(text.LatexRunner) text.preamble(r'\usepackage[sfdefault,scaled=.85,lining]{FiraSans}\usepackage{newtxsf}') unit.set(xscale=1.2) g = graph.graphxy(width=8, x=graph.axis.lin(title=r'\Large $x$', divisor=np.pi, texter=graph.axis.texter.rational(suffix=r'\pi')), y=graph.axis.lin(min=0, max=1.1, title=r'\Large $y$', parter=graph.axis.parter.lin(tickdists=[0.2]))) origdata = list(zip(x, y)) symbolattrs = [deco.filled, color.hsb(0.6, 1, 0.7)] g.plot(graph.data.points(origdata, x=1, y=2), [graph.style.symbol(graph.style.symbol.circle, 0.07, symbolattrs=symbolattrs)]) fitdata = list(zip(x, fit(x))) lineattrs = [color.hsb(0.05, 1, 0.7), style.linewidth.THick] g.plot(graph.data.points(fitdata, x=1, y=2), [graph.style.line(lineattrs=lineattrs)]) g.writePDFfile()
titleattrs=[text.halign.right]) painter_y = painter.regular(basepathattrs=[deco.earrow], titlepos=1.03, titledist=0.15, titleattrs=[text.valign.top], titledirection=None) g1 = c.insert( graphxy(width=5, height=2, xaxisat=0, yaxisat=0, x=axis.linear(title="$x$", min=0, max=xrange, painter=painter_x, parter=None), y=axis.linear(title=r"$I(x)$", max=1.2, painter=painter_y, parter=None))) x2 = np.linspace(0, (0.93 * xrange)**2, 800) factor = sqrt(0.5 * pi) _, integral = fresnel(np.sqrt(x2) / factor) integral = factor * integral g1.plot(data.points(list(zip(np.sqrt(x2), integral)), x=1, y=2), lineproperties) g2 = c.insert(
def plot_memory(data, width, height): plot_width = width - 4.0 plot_height = height - 0.8 left_width = plot_width * 0.6 right_width = plot_width * 0.2 prob = data['HiFive-Probability']['3'] norm = data['HiCNorm']['3'] prob_min = prob - right_width * 2.2e4 / left_width * 0.7 prob_max = prob + right_width * 2.2e4 / left_width * 0.3 norm_min = norm - right_width * 2.2e4 / left_width * 0.6 norm_max = norm + right_width * 2.2e4 / left_width * 0.4 c1 = canvas.canvas() g1 = graph.graphxy(width=left_width, height=plot_height, y=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)), x=graph.axis.lin(painter=painter, texter=graph.axis.texter.exponential(mantissaexp=r"{{%s}e%s}", nomantissaexp=r"{e%s}"), min=0, max=2.2e4), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(painter=None, min=0, max=1)) c1.insert(g1, [trafo.translate(0, 0)]) g2 = graph.graphxy(width=right_width, height=plot_height, y=graph.axis.lin(painter=None, min=0, max=1), x=graph.axis.lin(painter=painter, texter=graph.axis.texter.exponential(mantissaexp=r"{{%s}e%s}", nomantissaexp=r"{e%s}"), min=prob_min, max=prob_max), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(painter=None, min=0, max=1)) c1.insert(g2, [trafo.translate(left_width, 0)]) g3 = graph.graphxy(width=right_width, height=plot_height, y=graph.axis.lin(painter=None, min=0, max=1), x=graph.axis.lin(painter=painter, texter=graph.axis.texter.exponential(mantissaexp=r"{{%s}e%s}", nomantissaexp=r"{e%s}"), parter=graph.axis.parter.linear(tickdists=[5000]), min=norm_min, max=norm_max), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) c1.insert(g3, [trafo.translate(left_width + right_width, 0)]) split = canvas.canvas() split.fill(path.path(path.moveto(-0.15, -0.2), path.lineto(0.05, 0.2), path.lineto(.15, 0.2), path.lineto(-0.05, -0.2), path.closepath()), [color.cmyk.White]) split.stroke(path.line(-0.15, -0.2, 0.05, 0.2)) split.stroke(path.line(-0.05, -0.2, 0.15, 0.2)) c1.insert(split, [trafo.translate(left_width, 0)]) c1.insert(split, [trafo.translate(left_width, plot_height)]) c1.insert(split, [trafo.translate(left_width + right_width, 0)]) c1.insert(split, [trafo.translate(left_width + right_width, plot_height)]) methods = ['HiCLib', 'HiCPipe', 'HiCNorm', 'HiFive-Probability', 'HiFive-Binning', 'HiFive-Express', 'HiFive-ExpressKR', 'HiFive-ExpressKR w/distance'] hstep = plot_height / len(methods) substep = hstep / 6.0 scale = left_width / 2.2e4 for i, meth in enumerate(methods[::-1]): for j in range(5): if str(j) not in data[meth]: continue if meth not in ['HiCNorm', 'HiFive-Probability'] or j != 3: c1.fill(path.rect(0, hstep * i + (4.5 - j) * substep, data[meth][str(j)] * scale, substep), [step_colors[j]]) elif meth == 'HiCNorm': c1.fill(path.rect(0, hstep * i + (4.5 - j) * substep, left_width + right_width * 1.7, substep), [step_colors[j]]) c1.insert(split, [trafo.translate(left_width, hstep * i + (5 - j) * substep)]) c1.insert(split, [trafo.translate(left_width + right_width, hstep * i + (5 - j) * substep)]) else: c1.fill(path.rect(0, hstep * i + (4.5 - j) * substep, left_width + right_width * 0.6, substep), [step_colors[j]]) c1.insert(split, [trafo.translate(left_width, hstep * i + (5 - j) * substep)]) c = canvas.canvas() c.insert(c1, [trafo.translate(4.0, 0.8)]) for i, meth in enumerate(methods): c.text(3.9, height - plot_height / len(methods) * (i + 0.5), meth, [text.halign.right, text.valign.middle, text.size(-2)]) c.text(4.0 + plot_width / 2, 0, "Maximum RAM usage (resident set size, Mbytes)", [text.halign.center, text.valign.bottom, text.size(-2)]) return c
from math import exp, expm1 from pyx import color, deco, graph, style, text, unit text.set(text.LatexEngine) mypainter = graph.axis.painter.regular(innerticklength=None, outerticklength=graph.axis.painter.ticklength.normal) g = graph.graphxy(width=8, x=graph.axis.log(title="$x$", painter=mypainter), y=graph.axis.lin(title=r"$f(x)-1$", min=-1.1e-6, max=1.1e-6, painter=mypainter, parter=graph.axis.parter.lin(tickdists=[1e-6])), key=graph.key.key(pos="tr") ) g.plot(graph.data.function("y(x)=(exp(x)-1)/x-1", min=1e-10, max=1e-6, title=r"\textsf{\big(exp(x)-1\big)/x}"), [graph.style.symbol(symbol=graph.style.symbol.circle, size=0.15*unit.v_cm, symbolattrs=[deco.filled([color.rgb(0.2, 0.2, 1)]), deco.stroked([color.grey(1)])])]) g.plot(graph.data.function("y(x)=expm1(x)/x-1", min=1e-10, max=1e-6, title=r"\textsf{expm1(x)/x}", context={"expm1": expm1}), [graph.style.line([color.rgb(1, 0.5, 0), style.linewidth.Thick])]) g.writeGSfile("expm1.png", resolution=300)
from pyx import color, deco, graph, style, unit unit.set(xscale=1.3) g = graph.graphxy(width=8, x=graph.axis.linear(title="$x$"), y=graph.axis.linear(title="$y$")) g.plot(graph.data.file("pyx1.dat", x=1, y=2), [ graph.style.line([style.linestyle.dashed, color.rgb(0, 0, 1)]), graph.style.symbol(graph.style.symbol.circle, size=0.1, symbolattrs=[ deco.filled([color.rgb.red]), deco.stroked([color.grey(0)]) ]) ]) g.writePDFfile() g.writeGSfile(device="png16m", resolution=800)
from pyx import graph g = graph.graphxy(width=8) g.plot(graph.data.file("pyx1.dat", x=1, y=2)) g.writePDFfile() g.writeGSfile(device="pnggray", resolution=800)
def plot_overall(data, width, height): plot_width = width - 0.4 plot_height = height - 0.4 c = canvas.canvas() methods = data.keys() methods.sort() bar_colors = [] cis_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where( data[methods[0]]['interaction'] == 'cis')]) trans_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where( data[methods[0]]['interaction'] == 'trans')]) Y = numpy.zeros( (len(methods), cis_binsizes.shape[0] + trans_binsizes.shape[0]), dtype=numpy.float32) for i, method in enumerate(methods): for j, binsize in enumerate(cis_binsizes): where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'cis') * (data[method]['range'] == 0)) if where[0].shape[0] > 0: Y[i, j] = data[method]['correlation'][where] for j, binsize in enumerate(trans_binsizes): where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'trans') * (data[method]['range'] == 0)) if where[0].shape[0] > 0: Y[i, j + cis_binsizes.shape[0]] = data[method]['correlation'][where] bar_colors.append(method_colors[method]) Y = numpy.array(Y) g = graph.graphxy( width=plot_width, height=plot_height, x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)), y=graph.axis.lin(painter=painter), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) for i in range(len(methods)): g.plot( graph.data.points(zip(zip(range(Y.shape[1]), [i] * Y.shape[1]), Y[i, :]), xname=1, y=2), [graph.style.changebar([method_colors[methods[i]]])]) step = plot_width / (cis_binsizes.shape[0] + trans_binsizes.shape[0]) for i, binsize in enumerate(cis_binsizes): g.text(step * (0.5 + i), -0.05, "%s cis" % (str(binsize / 1000) + 'Kb').replace('000Kb', 'Mb'), [ text.halign.right, text.valign.middle, text.size(-4), trafo.rotate(45) ]) for i, binsize in enumerate(trans_binsizes): g.text( step * (0.5 + i + cis_binsizes.shape[0]), -0.05, "%s trans" % (str(binsize / 1000) + 'Kb').replace('000Kb', 'Mb'), [ text.halign.right, text.valign.middle, text.size(-4), trafo.rotate(45) ]) c.insert(g, [trafo.translate(0.7, 0.4)]) c.text( 0, plot_height / 2.0 + 0.4, "Dataset Correlation", [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)]) return c
def plot_overall(data, width, height, name): vo = 0.55 ho = 0.7 plot_width = width - ho plot_height = height - vo - 0.3 c = canvas.canvas() methods = data.keys() methods.sort() bar_colors = [] cis_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where( data[methods[0]]['interaction'] == 'cis')]) trans_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where( data[methods[0]]['interaction'] == 'trans')]) Y = numpy.zeros( (len(methods), cis_binsizes.shape[0] + trans_binsizes.shape[0]), dtype=numpy.float32) for i, method in enumerate(methods): for j, binsize in enumerate(cis_binsizes): where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'cis') * (data[method]['range'] == 0)) if where[0].shape[0] > 0: Y[i, j] = data[method]['correlation'][where] for j, binsize in enumerate(trans_binsizes): where = numpy.where((data[method]['binsize'] == binsize) * (data[method]['interaction'] == 'trans') * (data[method]['range'] == 0)) if where[0].shape[0] > 0: Y[i, j + cis_binsizes.shape[0]] = data[method]['correlation'][where] bar_colors.append(method_colors[method]) Y = numpy.array(Y) g = graph.graphxy( width=plot_width, height=plot_height, x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)), y=graph.axis.lin(painter=painter), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) for i in range(len(methods)): g.plot( graph.data.points(zip(zip(range(Y.shape[1]), [i] * Y.shape[1]), Y[i, :]), xname=1, y=2), [graph.style.changebar([method_colors[methods[i]]])]) c.insert(g, [trafo.translate(ho, vo)]) for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb", "250Kb", "1Mb"]): c.text(ho + plot_width * (i + 0.5) / 6.0, vo - 0.05, "%s" % label, [text.halign.center, text.valign.top, text.size(-3)]) c.text(ho + plot_width * 2.0 / 6.0, 0.05, "cis", [text.halign.center, text.valign.bottom, text.size(-3)]) c.stroke( path.line(ho + 0.2, vo * 0.5, ho - 0.2 + plot_width * 4.0 / 6.0, vo * 0.5), [style.linewidth.THin]) c.text(ho + plot_width * 5.0 / 6.0, 0.05, "trans", [text.halign.center, text.valign.bottom, text.size(-3)]) c.stroke( path.line(ho + 0.2 + plot_width * 4.0 / 6.0, vo * 0.5, ho - 0.2 + plot_width, vo * 0.5), [style.linewidth.THin]) c.text( 0, plot_height * 0.5 + vo, "Correlation", [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)]) c.text(plot_width * 0.5 + ho, height, name, [text.halign.center, text.valign.top, text.size(-3)]) return c
def plot_overall(data0, data1, width, height): vo = 1.15 ho = 1.15 plot_width = width - ho plot_height = height - vo c = canvas.canvas() cis_binsizes = numpy.unique(data0['binsize'][numpy.where(data0['interaction'] == 'cis')]) trans_binsizes = numpy.unique(data0['binsize'][numpy.where(data0['interaction'] == 'trans')]) ymin = numpy.inf ymax = -numpy.inf Y = numpy.zeros((cis_binsizes.shape[0] + trans_binsizes.shape[0]), dtype=numpy.float32) for j, binsize in enumerate(cis_binsizes): where = numpy.where((data0['binsize'] == binsize) * (data0['interaction'] == 'cis') * (data0['range'] < 0)) where1 = numpy.where((data1['binsize'] == binsize) * (data1['interaction'] == 'cis') * (data1['range'] < 0)) if where[0].shape[0] > 0: Y[j] = (data1['correlation'][where1] - data0['correlation'][where]) ymin = min(ymin, Y[j]) ymax = max(ymax, Y[j]) for j, binsize in enumerate(trans_binsizes): where = numpy.where((data0['binsize'] == binsize) * (data0['interaction'] == 'trans') * (data0['range'] < 0)) where1 = numpy.where((data1['binsize'] == binsize) * (data1['interaction'] == 'trans') * (data1['range'] < 0)) if where[0].shape[0] > 0: Y[j + cis_binsizes.shape[0]] = (data1['correlation'][where1] - data0['correlation'][where]) ymin = min(ymin, Y[j + cis_binsizes.shape[0]]) ymax = max(ymax, Y[j + cis_binsizes.shape[0]]) yspan = ymax - ymin ymin -= yspan * 0.05 ymax += yspan * 0.05 Y = numpy.array(Y) g = graph.graphxy(width=plot_width, height=plot_height, x=graph.axis.bar(painter=graph.axis.painter.bar(nameattrs=None)), y=graph.axis.lin(painter=painter, min=ymin, max=ymax), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) y0 = plot_height * (-ymin) / (ymax - ymin) g.stroke(path.line(0, plot_height * (-ymin) / (ymax - ymin), plot_width, plot_height * (-ymin) / (ymax - ymin)), [style.linestyle.dotted, style.linewidth.THin]) w0 = plot_width / Y.shape[0] w1 = w0 / 1.5 for j in range(Y.shape[0]): x = j * w0 + 0.25 * w1 y = plot_height * (Y[j] - ymin) / (ymax - ymin) g.fill( path.rect(x, y0, w1, y - y0) ) c.insert(g, [trafo.translate(ho, vo)]) for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb", "250Kb", "1Mb"]): c.text(ho + plot_width * (i + 0.5) / 6.0, vo - 0.05, "%s" % label, [text.halign.right, text.valign.middle, text.size(-3), trafo.rotate(90)]) c.text(ho + plot_width * 2.0 / 6.0, 0, "cis", [text.halign.center, text.valign.bottom, text.size(-3)]) c.stroke(path.line(ho + 0.2, 0.3, ho - 0.2 + plot_width * 4.0 / 6.0, 0.3), [style.linewidth.THin]) c.text(ho + plot_width * 5.0 / 6.0, 0, "trans", [text.halign.center, text.valign.bottom, text.size(-3)]) c.stroke(path.line(ho + 0.2 + plot_width * 4.0 / 6.0, 0.3, ho - 0.2 + plot_width, 0.3), [style.linewidth.THin]) c.text(0, plot_height * 0.5 + vo, r"$r_{Poisson} - r_{binomial}$", [text.halign.center, text.valign.top, text.size(-2), trafo.rotate(90)]) c.text(0, height, 'b', [text.halign.left, text.valign.top, text.size(-1)]) return c
def plot_single_range(data0, data1, binsize, width, height, ylabel): plot_width = width plot_height = height c = canvas.canvas() xmax = 0.0 where = numpy.where( (data0['binsize'] == binsize) * (data0['interaction'] == 'cis') * (data0['range'] >= 0)) if where[0].shape[0] > 0: xmax = max(xmax, numpy.amax(data0['range'][where])) X = data0['range'][where] X = numpy.r_[0, X] X[0] = X[1]**2.0 / X[2] xmin = X[0] ymin = numpy.inf ymax = -numpy.inf binsizes = numpy.unique(data0['binsize']) for b in binsizes: where = numpy.where( (data0['binsize'] == b) * (data0['interaction'] == 'cis') * (data0['range'] >= 0)) where1 = numpy.where( (data1['binsize'] == b) * (data1['interaction'] == 'cis') * (data1['range'] >= 0)) if where[0].shape[0] > 0: Y = (data1['correlation'][where1] - data0['correlation'][where]) ymin = min(ymin, numpy.amin(Y)) ymax = max(ymax, numpy.amax(Y)) yspan = ymax - ymin ymin -= yspan * 0.05 ymax += yspan * 0.05 if ylabel: yaxis = graph.axis.lin(painter=painter, min=ymin, max=ymax) else: yaxis = graph.axis.lin(painter=None, min=ymin, max=ymax) g = graph.graphxy(width=plot_width, height=plot_height, x=graph.axis.log(painter=painter, min=X[0], max=xmax), y=yaxis, x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) g.stroke(path.line(0, 0, 0, plot_height)) for x in X[1:-1]: pos = ((log(x) - log(xmin)) / (log(xmax) - log(xmin)) * plot_width) g.stroke(path.line(pos, 0, pos, plot_height), [style.linestyle.dotted, style.linewidth.THin]) X = (X[1:]**0.5) * (X[:-1]**0.5) where = numpy.where((data0['binsize'] == binsize) * (data0['interaction'] == 'cis') * (data0['range'] > 0)) where1 = numpy.where( (data1['binsize'] == binsize) * (data1['interaction'] == 'cis') * (data1['range'] > 0)) if where[0].shape[0] > 0: Y = (data1['correlation'][where1] - data0['correlation'][where]) g.plot(graph.data.points(zip(X, Y), x=1, y=2), [graph.style.line(lineattrs=[style.linewidth.Thick])]) g.stroke( path.line(0, plot_height * (-ymin) / (ymax - ymin), plot_width, plot_height * (-ymin) / (ymax - ymin)), [style.linestyle.dotted, style.linewidth.THin]) if binsize / 1000000 > 0: binstring = "%iMb" % (binsize / 1000000) elif binsize / 1000 > 0: binstring = "%iKb" % (binsize / 1000) else: binstring = str(binsize) g.text(plot_width / 2, plot_height + 0.3, "%s binning" % (binstring), [text.halign.center, text.valign.top, text.size(-2)]) c.insert(g) return c
def plot_overall(data0, data1, width, height): vo = 1.15 ho = 1.15 plot_width = width - ho plot_height = height - vo c = canvas.canvas() cis_binsizes = numpy.unique( data0['binsize'][numpy.where(data0['interaction'] == 'cis')]) trans_binsizes = numpy.unique( data0['binsize'][numpy.where(data0['interaction'] == 'trans')]) ymin = numpy.inf ymax = -numpy.inf Y = numpy.zeros((cis_binsizes.shape[0] + trans_binsizes.shape[0]), dtype=numpy.float32) for j, binsize in enumerate(cis_binsizes): where = numpy.where( (data0['binsize'] == binsize) * (data0['interaction'] == 'cis') * (data0['range'] < 0)) where1 = numpy.where( (data1['binsize'] == binsize) * (data1['interaction'] == 'cis') * (data1['range'] < 0)) if where[0].shape[0] > 0: Y[j] = (data1['correlation'][where1] - data0['correlation'][where]) ymin = min(ymin, Y[j]) ymax = max(ymax, Y[j]) for j, binsize in enumerate(trans_binsizes): where = numpy.where( (data0['binsize'] == binsize) * (data0['interaction'] == 'trans') * (data0['range'] < 0)) where1 = numpy.where( (data1['binsize'] == binsize) * (data1['interaction'] == 'trans') * (data1['range'] < 0)) if where[0].shape[0] > 0: Y[j + cis_binsizes.shape[0]] = (data1['correlation'][where1] - data0['correlation'][where]) ymin = min(ymin, Y[j + cis_binsizes.shape[0]]) ymax = max(ymax, Y[j + cis_binsizes.shape[0]]) yspan = ymax - ymin ymin -= yspan * 0.05 ymax += yspan * 0.05 Y = numpy.array(Y) g = graph.graphxy( width=plot_width, height=plot_height, x=graph.axis.bar(painter=graph.axis.painter.bar(nameattrs=None)), y=graph.axis.lin(painter=painter, min=ymin, max=ymax), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) y0 = plot_height * (-ymin) / (ymax - ymin) g.stroke( path.line(0, plot_height * (-ymin) / (ymax - ymin), plot_width, plot_height * (-ymin) / (ymax - ymin)), [style.linestyle.dotted, style.linewidth.THin]) w0 = plot_width / Y.shape[0] w1 = w0 / 1.5 for j in range(Y.shape[0]): x = j * w0 + 0.25 * w1 y = plot_height * (Y[j] - ymin) / (ymax - ymin) g.fill(path.rect(x, y0, w1, y - y0)) c.insert(g, [trafo.translate(ho, vo)]) for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb", "250Kb", "1Mb"]): c.text(ho + plot_width * (i + 0.5) / 6.0, vo - 0.05, "%s" % label, [ text.halign.right, text.valign.middle, text.size(-3), trafo.rotate(90) ]) c.text(ho + plot_width * 2.0 / 6.0, 0, "cis", [text.halign.center, text.valign.bottom, text.size(-3)]) c.stroke(path.line(ho + 0.2, 0.3, ho - 0.2 + plot_width * 4.0 / 6.0, 0.3), [style.linewidth.THin]) c.text(ho + plot_width * 5.0 / 6.0, 0, "trans", [text.halign.center, text.valign.bottom, text.size(-3)]) c.stroke( path.line(ho + 0.2 + plot_width * 4.0 / 6.0, 0.3, ho - 0.2 + plot_width, 0.3), [style.linewidth.THin]) c.text( 0, plot_height * 0.5 + vo, r"$r_{Poisson} - r_{binomial}$", [text.halign.center, text.valign.top, text.size(-2), trafo.rotate(90)]) c.text(0, height, 'b', [text.halign.left, text.valign.top, text.size(-1)]) return c
def doplot(self, d, xlabel=None, xlog=False, ymin=-0.0029, ymax=0.0029, xmin=None, xmax=None, nocorr=False, fitlines=False, **kw): """ plot the results parameters ---------- d: dict result of running something like process_run or process_flist **kw: extra plotting keywords """ import pyxtools from pyx import graph, deco, style from pyx.graph import axis if xlabel is None: xlabel = 'x' xdensity = kw.get('xdensity', 1.5) ydensity = kw.get('ydensity', 1.5) red = pyxtools.colors('red') blue = pyxtools.colors('blue') xvals = self._extract_xvals(d) if nocorr: sh = d['shear_nocorr']['shear'] sherr = d['shear_nocorr']['shear_err'] else: sh = d['shear']['shear'] sherr = d['shear']['shear_err'] if xlog: xcls = axis.log else: xcls = axis.lin xaxis = xcls( title=xlabel, density=xdensity, min=xmin, max=xmax, ) yaxis = axis.lin( title=r"$\langle g \rangle$", density=ydensity, min=ymin, max=ymax, ) key = graph.key.key(pos='bl') g = graph.graphxy( width=8, ratio=1.2, key=key, x=xaxis, y=yaxis, ) c = graph.data.function( "y(x)=0", title=None, min=xvals[0], max=xvals[-1], ) g.plot(c) g1values = graph.data.values( x=list(xvals), y=list(sh[:, 0]), dy=list(sherr[:, 0]), title=r'$g_1$', ) g2values = graph.data.values( x=list(xvals), y=list(sh[:, 1]), dy=list(sherr[:, 1]), title=r'$g_2$', ) symbol1 = graph.style.symbol( symbol=graph.style.symbol.circle, symbolattrs=[red, deco.filled([red])], size=0.1, ) symbol2 = graph.style.symbol( symbol=graph.style.symbol.triangle, symbolattrs=[blue, deco.filled([blue])], size=0.1, ) g.plot(g1values, [symbol1, graph.style.errorbar(errorbarattrs=[red])]) g.plot(g2values, [symbol2, graph.style.errorbar(errorbarattrs=[blue])]) use_errors = True if fitlines and not use_errors: res1 = fitline(xvals, sh[:, 0]) res2 = fitline(xvals, sh[:, 1]) fmt = '(%(slope).3g +/- %(slope_err).3g) x + (%(offset).3g +/- %(offset_err).3g)' print("line1: " + fmt % res1) print("line2: " + fmt % res2) if self.element is not None: tit1 = r'$g_1=%.2g ~g^{psf}_%d + %.2g$' % ( res1['slope'], self.element + 1, res1['offset']) tit2 = r'$g_2=%.2g ~g^{psf}_%d + %.2g$' % ( res2['slope'], self.element + 1, res2['offset']) else: tit1 = r'$g_1=%.2g ~x + %.2g$' % (res1['slope'], res1['offset']) tit2 = r'$g_2=%.2g ~x + %.2g$' % (res1['slope'], res1['offset']) c1 = graph.data.function( "y(x)=%g*x + %g" % tuple((res1['slope'], res1['offset'])), title=tit1, min=xvals[0], max=xvals[-1], ) c2 = graph.data.function( "y(x)=%g*x + %g" % tuple((res2['slope'], res2['offset'])), title=tit2, min=xvals[0], max=xvals[-1], ) styles1 = [ graph.style.line([red, style.linestyle.solid]), ] styles2 = [ graph.style.line([blue, style.linestyle.dashed]), ] g.plot(c1, styles1) g.plot(c2, styles2) if fitlines and use_errors: # old code import fitting l1 = fitting.fit_line(xvals, sh[:, 0], yerr=sherr[:, 0]) l2 = fitting.fit_line(xvals, sh[:, 1], yerr=sherr[:, 1]) res1 = l1.get_result() res2 = l2.get_result() pars1, err1 = res1['pars'], res1['perr'] pars2, err2 = res2['pars'], res2['perr'] fmt = '(%.3g +/- %.3g) x + (%.3g +/- %.3g)' print("line1: " + fmt % (pars1[0], err1[0], pars1[1], err1[1])) print("line2: " + fmt % (pars2[0], err2[0], pars2[1], err2[1])) if self.element is not None: tit1 = r'$g_1=%.2g ~g^{psf}_%d + %.2g$' % ( pars1[0], self.element + 1, pars1[1]) tit2 = r'$g_2=%.2g ~g^{psf}_%d + %.2g$' % ( pars2[0], self.element + 1, pars2[1]) else: tit1 = r'$g_1=%.2g ~x + %.2g$' % (pars1[0], pars1[1]) tit2 = r'$g_2=%.2g ~x + %.2g$' % (pars2[0], pars2[1]) c1 = graph.data.function( "y(x)=%g*x + %g" % tuple(pars1), title=tit1, min=xvals[0], max=xvals[-1], ) c2 = graph.data.function( "y(x)=%g*x + %g" % tuple(pars2), title=tit2, min=xvals[0], max=xvals[-1], ) styles1 = [ graph.style.line([red, style.linestyle.solid]), ] styles2 = [ graph.style.line([blue, style.linestyle.dashed]), ] g.plot(c1, styles1) g.plot(c2, styles2) if 'file' in kw: print("writing:", kw['file']) pyxtools.write(g, kw['file'], dpi=200) if fitlines and 'fitfile' in kw: print("writing:", kw['fitfile']) with open(kw['fitfile'], 'w') as fobj: fobj.write(repr(l1)) fobj.write('\n') fobj.write(repr(l2)) fobj.write('\n') return g
julia_c = -0.8 + 0.156j schwelle = 50000 maxit = 600 julia_daten = [] for y in np.linspace(ymin, ymax, seitenlaenge): for x in np.linspace(xmin, xmax, seitenlaenge): iterationen = julia_iteration(x, y, julia_c, schwelle, maxit) julia_daten.append((x, y, iterationen / maxit)) c = canvas.canvas() dx = 0.3 h = 4 w = 6.5 p = path.rect(-dx, -dx, w + 2 * dx, h + 2 * dx) p = deformer.smoothed(0.5).deform(p) c.fill(p, [color.grey(0.5), trafo.translate(0.05, -0.05)]) c1 = canvas.canvas([canvas.clip(p)]) g = graph.graphxy(height=8, width=8, x=graph.axis.linear(min=xmin, max=xmax), y=graph.axis.linear(min=ymin, max=ymax)) g.plot(graph.data.points(julia_daten, x=1, y=2, color=3, title="iterations"), [graph.style.density(gradient=color.rgbgradient.Rainbow)]) c1.insert(g, [trafo.translate(-0.1 * w, -0.5 * h)]) c.insert(c1) c.writeGSfile(device="png16m", resolution=300)
def plot_overall(data0, data1, width, height): vo = 0.55 ho = 1.1 plot_width = width - ho plot_height = height - vo c = canvas.canvas() methods = data0.keys() methods.sort() bar_colors = [] cis_binsizes = numpy.unique(data0[methods[0]]['binsize'][numpy.where( data0[methods[0]]['interaction'] == 'cis')]) trans_binsizes = numpy.unique(data0[methods[0]]['binsize'][numpy.where( data0[methods[0]]['interaction'] == 'trans')]) ymin = numpy.inf ymax = -numpy.inf Y = numpy.zeros( (len(methods), cis_binsizes.shape[0] + trans_binsizes.shape[0]), dtype=numpy.float32) for i, method in enumerate(methods): for j, binsize in enumerate(cis_binsizes): where = numpy.where((data0[method]['binsize'] == binsize) * (data0[method]['interaction'] == 'cis') * (data0[method]['range'] < 0)) where1 = numpy.where((data1[method]['binsize'] == binsize) * (data1[method]['interaction'] == 'cis') * (data1[method]['range'] < 0)) if where[0].shape[0] > 0: Y[i, j] = (data1[method]['correlation'][where1] - data0[method]['correlation'][where]) ymin = min(ymin, Y[i, j]) ymax = max(ymax, Y[i, j]) for j, binsize in enumerate(trans_binsizes): where = numpy.where((data0[method]['binsize'] == binsize) * (data0[method]['interaction'] == 'trans') * (data0[method]['range'] < 0)) where1 = numpy.where((data1[method]['binsize'] == binsize) * (data1[method]['interaction'] == 'trans') * (data1[method]['range'] < 0)) if where[0].shape[0] > 0: Y[i, j + cis_binsizes.shape[0]] = ( data1[method]['correlation'][where1] - data0[method]['correlation'][where]) ymin = min(ymin, Y[i, j + cis_binsizes.shape[0]]) ymax = max(ymax, Y[i, j + cis_binsizes.shape[0]]) bar_colors.append(method_colors[method]) yspan = ymax - ymin ymin -= yspan * 0.05 ymax += yspan * 0.05 Y = numpy.array(Y) g = graph.graphxy( width=plot_width, height=plot_height, x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)), y=graph.axis.lin(painter=painter, min=ymin, max=ymax), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) y0 = plot_height * (-ymin) / (ymax - ymin) g.stroke( path.line(0, plot_height * (-ymin) / (ymax - ymin), plot_width, plot_height * (-ymin) / (ymax - ymin)), [style.linestyle.dotted, style.linewidth.THin]) w0 = plot_width / Y.shape[1] w1 = w0 / (len(methods) + 0.5) for i in range(len(methods)): for j in range(Y.shape[1]): x = j * w0 + (i + 0.25) * w1 y = plot_height * (Y[i, j] - ymin) / (ymax - ymin) g.stroke(path.rect(x, y0, w1, y - y0), [deco.filled([method_colors[methods[i]]])]) c.insert(g, [trafo.translate(ho, vo)]) for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb", "250Kb", "1Mb"]): c.text(ho + plot_width * (i + 0.5) / 6.0, vo - 0.05, "%s" % label, [text.halign.center, text.valign.top, text.size(-3)]) c.text(ho + plot_width * 2.0 / 6.0, 0.05, "cis", [text.halign.center, text.valign.bottom, text.size(-3)]) c.stroke( path.line(ho + 0.2, vo * 0.5, ho - 0.2 + plot_width * 4.0 / 6.0, vo * 0.5), [style.linewidth.THin]) c.text(ho + plot_width * 5.0 / 6.0, 0.05, "trans", [text.halign.center, text.valign.bottom, text.size(-3)]) c.stroke( path.line(ho + 0.2 + plot_width * 4.0 / 6.0, vo * 0.5, ho - 0.2 + plot_width, vo * 0.5), [style.linewidth.THin]) c.text( 0, plot_height * 0.5 + vo, r"$r_{0K} - r_{500K}$", [text.halign.center, text.valign.top, text.size(-2), trafo.rotate(90)]) return c
for r in results: nx, ny, procid, partialdata = r for mx, my in product(range(nlen), repeat=2): cval = c[nx * nlen + mx, ny * nlen + my] data.append((cval.real, cval.imag, partialdata[mx, my])) procdict[(nx, ny)] = procid procids = set(procdict.values()) colors = [ color.hsb(n / (len(procids) - 1) * 0.67, 1, 1) for n in range(len(procids)) ] proccolors = dict(zip(procids, colors)) text.set(text.LatexRunner) text.preamble(r'\usepackage{arev}\usepackage[T1]{fontenc}') g = graph.graphxy(width=8, height=8, x=graph.axis.lin(title=r'$\mathrm{Re}(c)$'), y=graph.axis.lin(title=r'$\mathrm{Im}(c)$')) g.plot(graph.data.points(data, x=1, y=2, color=3), [graph.style.density(keygraph=None)]) dx = (xmax - xmin) / n dy = (ymax - ymin) / n for k, v in procdict.items(): nx, ny = k tilecolor = proccolors[v] xll, yll = g.pos(xmin + dx * nx, ymin + dy * ny) xur, yur = g.pos(xmin + dx * (nx + 1), ymin + dy * (ny + 1)) g.fill(path.rect(xll, yll, xur - xll, yur - yll), [deco.stroked([color.grey(0)]), tilecolor, color.transparency(0.5)]) g.writePDFfile()
VermillonU = rgb256pyx(244, 65, 0) text.set(cls=text.LatexRunner, texenc='utf-8') text.preamble(r'\usepackage[utf8]{inputenc}') text.preamble(r'\usepackage{textgreek}') text.preamble(r'\usepackage{fixltx2e}') text.preamble(r'\usepackage{libertine}') text.preamble(r'\renewcommand{\familydefault}{\sfdefault}') text.preamble(r'\usepackage{sansmath}') g = graphxy( width=5.0, height=2.4, x=fakebaraxis(ticks=protein_keys, texter=texter.decimal(labelattrs=[text.clearmathmode])), x2=emptyaxis(), y=axis.linear(min=0.0, max=12.0, parter=parter.linear(tickdists=[4.0, 2.0]), texter=texter.decimal(labelattrs=[text.clearmathmode]), title=r"C\textsubscript{α} RMSD ± std (Å)")) i = 0 time, rmsd = read_dat("rmsd_Ahc.xvg", [float, float]) rmsd = [x * 10 for x in rmsd] cloudplot(g, i, clouddata(rmsd), BlueU, ya=True) boxplot(g, i, boxdata(rmsd), ya=True) i = 1 time, rmsd = read_dat("rmsd_B2m.xvg", [float, float]) rmsd = [x * 10 for x in rmsd]
titledist=-0.4, titleattrs=[text.halign.right]) painter_y = graph.axis.painter.regular(basepathattrs=[deco.earrow], titlepos=1.03, titledist=0.15, titleattrs=[text.valign.top], titledirection=None) g = graph.graphxy(width=5, height=2, xaxisat=0, yaxisat=0, x=graph.axis.linear(title="$t$", min=0, max=trange, painter=painter_x, parter=None), y=graph.axis.linear(title=r"$x$", max=1.2, painter=painter_y, parter=None)) for np in range(-3, 4): p = 0.2 * np g.plot( graph.data.function("y(x) = 0.5*cos(x)+{}*sin(x)".format(p), max=trange - 0.7), [graph.style.line([style.linestyle.solid, linecolor])]) textattrs = [text.halign.center]
print "Recovered phase shift: %.2f pi" % (recovered_phase_shift/pi) pyplot.plot(t, ) pyplot.show() quit() from pyx import canvas, graph, text, color, style, trafo, unit from pyx.graph import axis, key text.set(mode="latex") text.preamble(r"\usepackage{txfonts}") figwidth = 12 gkey = key.key(pos=None, hpos=0.05, vpos=0.8) xaxis = axis.linear(title=r"Time, \(t\)") yaxis = axis.linear(title="Signal", min=-5, max=17) g = graph.graphxy(width=figwidth, x=xaxis, y=yaxis, key=gkey) plotdata = [graph.data.values(x=t, y=signal+offset, title=label) for label, signal, offset in (r"\(A(t) = \mathrm{square}(2\pi t/T)\)", A, 2.5), (r"\(B(t) = \mathrm{sawtooth}(\phi + 2 \pi t/T)\)", B, -2.5)] linestyles = [style.linestyle.solid, style.linejoin.round, style.linewidth.Thick, color.gradient.Rainbow, color.transparency(0.5)] plotstyles = [graph.style.line(linestyles)] g.plot(plotdata, plotstyles) g.plot(graph.data.values(x=t, y=listX, title="Blah"), plotstyles) g.text(10*unit.x_pt, 0.56*figwidth, r"\textbf{Cross correlation of noisy anharmonic signals}") g.text(10*unit.x_pt, 0.33*figwidth, "Phase shift: input \(\phi = %.2f \,\pi\), recovered \(\phi = %.2f \,\pi\)" % (phase_shift/pi, recovered_phase_shift/pi)) xxaxis = axis.linear(title=r"Time Lag, \(\Delta t\)", min=-1.5, max=1.5) yyaxis = axis.linear(title=r"\(A(t) \star B(t)\)") gg = graph.graphxy(width=0.2*figwidth, x=xxaxis, y=yyaxis) plotstyles = [graph.style.line(linestyles + [color.rgb(0.2,0.5,0.2)])] #gg.plot(graph.data.values(x=dt, y=xcorr), plotstyles) gg.plot(graph.data.values(x=dt, y=xcorr, title="Blah"), plotstyles) gg.stroke(gg.xgridpath(recovered_time_shift), [style.linewidth.THIck, color.gray(0.5), color.transparency(0.7)]) ggtrafos = [trafo.translate(0.75*figwidth, 0.45*figwidth)]
from math import pi, cos from pyx import * from pyx.deco import barrow, earrow from pyx.style import linewidth, linestyle from pyx.graph import graphxy from pyx.graph.axis import linear from pyx.graph.axis.painter import regular from pyx.graph.style import line from pyx.graph.data import function mypainter = regular(basepathattrs=[earrow.normal], titlepos=1) def mycos(x): return -cos(x)+.10*x g = graphxy(height=5, x2=None, y2=None, x=linear(min=-2.5*pi, max=3.3*pi, parter=None, painter=mypainter, title=r"$\delta\phi$"), y=linear(min=-2.3, max=2, painter=None)) g.plot(function("y(x)=mycos(x)", context=locals()), [line(lineattrs=[linewidth.Thick])]) g.finish() x1, y1 = g.pos(-pi+.1, mycos(-pi+.1)) x2, y2 = g.pos(-.1, mycos(-.1)) x3, y3 = g.pos(pi+.1, mycos(pi+.1)) g.stroke(path.line(x1-.5, y1, x1+.5, y1), [linestyle.dashed]) g.stroke(path.line(x1-.5, y3, x3+.5, y3), [linestyle.dashed]) g.stroke(path.line(x2-.5, y2, x3+.5, y2), [linestyle.dashed]) g.stroke(path.line(x1, y1, x1, y3), [barrow.normal, earrow.normal]) g.stroke(path.line(x3, y2, x3, y3), [barrow.normal, earrow.normal]) g.text(x1+.2, 0.5*(y1+y3), r"$2\pi\gamma k\Omega$", [text.vshift.middlezero])
def dense(Gx, Gz, Hx, Hz, Rx, Rz, Pxt, Qx, Pz, Tx, **kw): r, n = Rx.shape N = 2**r gz = len(Gz) # print "Hz:" # print shortstr(Hz) print("Hx|Tx:") print(shortstrx(Hx, Tx)) print("Hx:") for i, h in enumerate(Hx): print(i, shortstr(h), h.sum()) print("GzTx") GzTx = dot2(Gz, Tx.transpose()) for i, h in enumerate(GzTx.transpose()): print(i, shortstr(h), h.sum()) # print "Rx:" # print shortstr(Rx) print("Tx:", len(Tx)) #print shortstr(Tx) RR = dot2(Gz, Rx.transpose()) PxtQx = dot2(Pxt, Qx) excite = argv.excite if excite is None: excite = kw.get("excite") if excite: excites = [excite] else: excites = genidx((2,)*len(Tx)) vec0 = None eigvals = [] for excite in excites: print("excite:", excite) assert len(excite)==len(Tx) t = zeros2(n) for i, ex in enumerate(excite): if ex: t = (t + Tx[i])%2 #print "t:", shortstr(t) Gzt = dot2(Gz, t) #print "Gzt:", shortstr(Gzt) if N<=1024: H = numpy.zeros((N, N)) else: H = None A = {} U = [] #for i in range(N): pos = neg = 0 for i, v in enumerate(genidx((2,)*r)): v = array2(v) syndrome = (dot2(Gz, Rx.transpose(), v) + Gzt)%2 value = gz - 2*syndrome.sum() #print shortstr(dot2(Rx.transpose(), v)), value if H is not None: H[i, i] = value U.append(value) for i, v in enumerate(genidx((2,)*r)): v = array2(v) #print shortstr(v), for g in Gx: u = (v + dot2(g, PxtQx))%2 j = eval('0b'+shortstr(u, zero='0')) if H is not None: H[i, j] += 1 A[i, j] = A.get((i, j), 0) + 1 #print H if argv.orbigraph: vals, vecs = do_orbigraph(A, U) show_eigs(vals) #if vec0 is not None: # Hv = numpy.dot(H, vec0) # print numpy.dot(vec0, Hv), # Hv /= numpy.linalg.norm(Hv) # print numpy.dot(vec0, Hv) if argv.solve: assert N <= 1024 assert numpy.allclose(H, H.transpose()) vals, vecs = numpy.linalg.eigh(H) if argv.show_eigs: show_eigs(vals) vals = list(vals) vals.sort() val0 = vals[-1] # top one is last assert vals[-2] < val0 - 1e-4 #print "excite:", excite, print("eigval:", val0) eigvals.append(val0) vec0 = vecs[:,-1] if vec0[0] < 0: vec0 = -vec0 #break if argv.plot: from pyx import graph xdata = U ydata = list(vec0) g = graph.graphxy( width=16, x=graph.axis.linear(reverse=True), y=graph.axis.log(min=0.8*vec0.min(), max=1.0)) # either provide lists of the individual coordinates g.plot(graph.data.values(x=xdata, y=ydata)) # or provide one list containing the whole points #g.plot(graph.data.points(list(zip(range(10), range(10))), x=1, y=2)) g.writePDFfile("pic-groundstate.pdf") return if eigvals: top = max(eigvals) idx = eigvals.index(top) eigvals.pop(idx) second = max(eigvals) print("gap:", top-second)
BC1.cns[n], BC2.cns[n] = (BC1.cns[n]-ez*BC2.cns[n])*k, (-ez*BC1.cns[n]+BC2.cns[n])*k self.BC1 = BC1 self.BC2 = BC2 self.dz = dz def V(self, r, z): return self.BC1.V(r,z) + self.BC2.V(r, self.dz-z) def Er(self, r, z): return self.BC1.Er(r,z) + self.BC2.Er(r, self.dz-z) def Ez(self, r, z): return self.BC1.Ez(r,z) - self.BC2.Ez(r, self.dz-z) if __name__ == "__main__": BC = BesselCalcs() print BC.j0n for n in range(200)[1:]: print "\t%i\t& %g\t\\\\"%(n, BC.cn(n)) g = graph.graphxy(width=10,height=6, x=graph.axis.lin(title="radial position $r/r_0$"), y=graph.axis.lin(title="endcap contribution $V(r,z)/V_1$")) for z in [0.1*n for n in range(25)]: npts = 50 if z==0: npts = 600 gdat = [ (r, BC.V(r,z)) for r in numpy.linspace(0,1,400) ] g.plot(graph.data.points(gdat,x=1,y=2),[graph.style.line(lineattrs=[style.linewidth.thin,rgb.blue])]) g.writetofile("endfield.pdf")
def main(): out_fname = sys.argv[1] basedir = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]) hic_phillips_fname1 = "%s/Data/HiC/HiCPipe/HM/mm9_ESC_NcoI_Phillips.hch" % basedir hic_phillips_fname2 = "%s/Data/HiC/HiCPipe/HM/mm9_ESC_HindIII_Phillips.hch" % basedir hic_nora_fname1 = "%s/Data/HiC/HiCPipe/HM/mm9_ESC_NcoI_Nora.hch" % basedir hic_nora_fname2 = "%s/Data/HiC/HiCPipe/HM/mm9_ESC_HindIII_Nora.hch" % basedir hic_phillips1 = h5py.File(hic_phillips_fname1, 'r') hic_phillips2 = h5py.File(hic_phillips_fname2, 'r') hic_nora1 = h5py.File(hic_nora_fname1, 'r') hic_nora2 = h5py.File(hic_nora_fname2, 'r') hm_phillips = {} hm_nora = {} for key in hic_phillips1.keys(): if key.count('unbinned_counts') == 0: continue region = int(key.split('.')[0]) hm_phillips[region] = dynamically_bin(hic_phillips1, hic_phillips2, region) for key in hic_nora1.keys(): if key.count('unbinned_counts') == 0: continue region = int(key.split('.')[0]) hm_nora[region] = dynamically_bin(hic_nora1, hic_nora2, region) fivec_fnames = { "Prob_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_probnodist.fcp" % basedir, "Prob_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_probnodist.fcp" % basedir, "Bin_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_binnodist.fcp" % basedir, "Bin_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_binnodist.fcp" % basedir, "Exp_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_expnodist.fcp" % basedir, "Exp_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_expnodist.fcp" % basedir, "Exp-KR_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_expKRnodist.fcp" % basedir, "Exp-KR_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_expKRnodist.fcp" % basedir, } data = {} imgs = {} ratio1 = 0 ratio2 = 0 for meth in ['Prob', 'Bin', 'Exp', 'Exp-KR']: fc = hifive.FiveC(fivec_fnames["%s_Phillips" % meth]) fragments = fc.frags['fragments'][...] regions = fc.frags['regions'][...] counts = numpy.zeros(0, dtype=numpy.float64) expected = numpy.zeros(0, dtype=numpy.float64) hic_counts = numpy.zeros(0, dtype=numpy.float64) hic_expected = numpy.zeros(0, dtype=numpy.float64) skipped = [] for i in range(fc.frags['regions'].shape[0]): temp = fc.cis_heatmap(i, datatype='fragment', arraytype='compact', binsize=0, skipfiltered=True) if temp is None: skipped.append(i) continue counts = numpy.hstack((counts, temp[:, :, 0].ravel())) expected = numpy.hstack((expected, temp[:, :, 1].ravel())) if i == 6: ratio1 = temp.shape[1] / float(temp.shape[0]) imgs["%s_Phillips" % meth] = hifive.plotting.plot_full_array(temp, symmetricscaling=False) if meth == 'Prob': temp1 = numpy.zeros((temp.shape[0], temp.shape[1]), dtype=numpy.float32) temp1[numpy.where(temp[:, :, 0] > 0.0)] = 1 if i == 6: imgs["Raw_Phillips"] = hifive.plotting.plot_full_array( numpy.dstack((temp[:, :, 0], temp1)), symmetricscaling=False) binbounds = numpy.hstack(( fragments['start'][regions['start_frag'][i]:regions['stop_frag'][i]].reshape(-1, 1), fragments['stop'][regions['start_frag'][i]:regions['stop_frag'][i]].reshape(-1, 1))) valid = numpy.where(fc.filter[regions['start_frag'][i]:regions['stop_frag'][i]])[0] binbounds = binbounds[valid, :] temp = hm_phillips[i] strands = fragments['strand'][regions['start_frag'][i]:regions['stop_frag'][i]][valid] temp = temp[numpy.where(strands == 0)[0], :, :][:, numpy.where(strands == 1)[0], :] hic_counts = numpy.hstack((hic_counts, temp[:, :, 0].ravel())) hic_expected = numpy.hstack((hic_expected, temp[:, :, 1].ravel())) if i == 6: imgs["HiC_Phillips"] = hifive.plotting.plot_full_array(temp, symmetricscaling=False) if meth == 'Prob': data["Raw_Phillips"] = numpy.copy(counts) where = numpy.where(hic_expected > 0.0)[0] hic_counts[where] /= hic_expected[where] data["HiC_Phillips"] = numpy.copy(hic_counts) where = numpy.where(expected > 0.0)[0] counts[where] /= expected[where] data["%s_Phillips" % meth] = numpy.copy(counts) fc = hifive.FiveC(fivec_fnames["%s_Nora" % meth]) temp = fc.cis_heatmap(0, datatype='fragment', arraytype='compact', binsize=0, skipfiltered=True) ratio2 = temp.shape[1] / float(temp.shape[0]) imgs["%s_Nora" % meth] = hifive.plotting.plot_full_array(temp, symmetricscaling=False) counts = temp[:, :, 0].ravel() expected = temp[:, :, 1].ravel() if meth == 'Prob': temp1 = numpy.zeros((temp.shape[0], temp.shape[1]), dtype=numpy.float32) temp1[numpy.where(temp[:, :, 0] > 0.0)] = 1 imgs["Raw_Nora"] = hifive.plotting.plot_full_array( numpy.dstack((temp[:, :, 0], temp1)), symmetricscaling=False) data["Raw_Nora"] = numpy.copy(counts) fragments = fc.frags['fragments'][...] regions = fc.frags['regions'][...] binbounds = numpy.hstack(( fragments['start'][regions['start_frag'][0]:regions['stop_frag'][0]].reshape(-1, 1), fragments['stop'][regions['start_frag'][0]:regions['stop_frag'][0]].reshape(-1, 1))) binbounds = binbounds[numpy.where(fc.filter[regions['start_frag'][0]:regions['stop_frag'][0]])[0], :] temp = hm_nora[0] strands = fragments['strand'][regions['start_frag'][0]:regions['stop_frag'][0]] temp = temp[numpy.where(strands==0)[0], :, :][:, numpy.where(strands == 1)[0], :] imgs["HiC_Nora"] = hifive.plotting.plot_full_array(temp, symmetricscaling=False) hic_counts = temp[:, :, 0].ravel() hic_expected = temp[:, :, 1].ravel() where = numpy.where(hic_expected > 0.0)[0] hic_counts[where] /= hic_expected[where] data["HiC_Nora"] = numpy.copy(hic_counts) where = numpy.where(expected > 0.0)[0] counts[where] /= expected[where] data["%s_Nora" % meth] = numpy.copy(counts) correlations = {} output = open(out_fname.replace('pdf', 'txt'), 'w') print >> output, "Method\tPhillips\tNora" for meth in methods: temp = [meth] for name in ["Phillips", "Nora"]: valid = numpy.where((data["%s_%s" % (meth, name)] > 0.0) * (data["HiC_%s" % name] > 0.0)) correlations["%s_%s" % (meth, name)] = numpy.corrcoef(numpy.log(data["%s_%s" % (meth, name)][valid]), numpy.log(data["HiC_%s" % name][valid]))[0, 1] temp.append(str(correlations["%s_%s" % (meth, name)])) print >> output, '\t'.join(temp) output.close() width = 16.8 spacer = 0.3 c = canvas.canvas() plot_width = (width - spacer * 3.0 - 0.4) / 4.0 for i, meth in enumerate(["Raw", "Prob", "HiC"]): meth_names = {"Raw":"Raw", "Prob":"HiFive", "HiC":"HiC"} c.text(plot_width * (i + 1.5) + spacer * (i + 1), (ratio1 + ratio2) * plot_width + spacer + 0.1, "%s" % meth_names[meth], [text.halign.center, text.valign.bottom, text.size(-2)]) c.insert(bitmap.bitmap(0, 0, imgs["%s_Phillips" % meth], width=plot_width), [trafo.translate((i + 1) * (plot_width + spacer), plot_width * ratio2 + spacer)]) c.insert(bitmap.bitmap(0, 0, imgs["%s_Nora" % meth], width=plot_width), [trafo.translate((i + 1) * (plot_width + spacer), 0)]) g = graph.graphxy(width=plot_width - 0.8, height=plot_width * ratio1, x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)), y=graph.axis.lin(painter=painter), x2=graph.axis.lin(parter=None, min=0, max=1), y2=graph.axis.lin(parter=None, min=0, max=1)) for i, meth in enumerate(methods): Y = numpy.zeros(2, dtype=numpy.float32) col = method_colors[meth] for j, name in enumerate(["Phillips", "Nora"]): Y[j] = correlations["%s_%s" % (meth, name)] g.plot(graph.data.points(zip(zip(range(Y.shape[0]), [i] * Y.shape[0]), Y), xname=1, y=2), [graph.style.changebar([col])]) g.text(-0.8, plot_width * ratio1 * 0.5, "Correlation", [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)]) g.text((plot_width - 0.8) * 0.25, -0.1, "Phillips", [text.halign.center, text.valign.top, text.size(-3)]) g.text((plot_width - 0.8) * 0.75, -0.1, "Nora", [text.halign.center, text.valign.top, text.size(-3)]) c.insert(g, [trafo.translate(0.8, plot_width * ratio2 + spacer)]) c.text(width, (ratio1 + ratio2 * 0.5) * plot_width + spacer, "Phillips", [text.halign.center, text.valign.top, trafo.rotate(-90), text.size(-2)]) c.text(width, ratio1 * 0.5 * plot_width, "Nora", [text.halign.center, text.valign.top, trafo.rotate(-90), text.size(-2)]) meth_names = {"Raw":"Raw", "Prob":"HiFive-Probability", "Exp":"HiFive-Express", "Bin":"HiFive-Binning", "Exp-KR":"HiFive-ExpressKR", "Exp-KR-dist":"HiFive-ExpressKR-dist"} for i, meth in enumerate(methods): c.fill(path.rect(1.0, plot_width * ratio1 - 1.0 - i * 0.5, 0.2, 0.2), [method_colors[meth]]) c.text(1.3, plot_width * ratio1 - 0.9 - i * 0.5, "%s" % meth_names[meth], [text.halign.left, text.valign.middle, text.size(-3)]) c.writePDFfile(out_fname)
p = painter.regular(basepathattrs=[earrow.normal], titlepos=0.95, outerticklength=painter.ticklength.normal, titledist=-0.3, titledirection=None) # horizontal text g = graphxy( width=10, xaxisat=0, yaxisat=0, x=axis.linear( title="$x$", min=-range, max=+range, painter=p, # suppress some ticks by overwriting ... manualticks=[tick.tick(0, None, None), tick.tick(range, None, None)]), y=axis.linear( title=r"$x\sin(x^2)$", painter=p, manualticks=[tick.tick(0, None, None), tick.tick(3, None, None)])) g.plot( data.function("y(x)=x*sin(x**2)"), # Line style is set before symbol style -> symbols will be draw # above the line. [ graph.style.line([style.linewidth.Thin, style.linestyle.solid]),