class FieldView: def __init__(self, data, title, color_range=None): self.G = Gnuplot(persist=True) self.G('set border 4095 lt 1.000') self.G('set view map') self.G('set samples 50,50') self.G('set isosamples 50,50') self.G('unset surface') self.G('set style data pm3d') self.G('set style function pm3d') self.G('set ticslevel 0') self.G('set terminal x11') self.G('set pm3d at b') if color_range: self.G('set cbrange [%d:%d]' % color_range) self.data = data self.gdata = GridData(self.data) self.change_title(title) self.change_data(data) return def change_title(self, title): temp = 'set title "' + title + '"' self.G(temp) self.G.splot(self.gdata) return def change_data(self, data): self.data = data self.gdata = GridData(self.data) self.G.splot(self.gdata) return
def main(): filename = '../tmp/config.txt' c = ConfigReader() c.parse(filename) cluster = c.readCluster() maxPerf = getMaxPerformance(cluster.availableServers) outline = readOutlineFile('../tmp/outline.txt') trace = generateTrace(outline, maxPerf, 20) if Gnuplot is not None: data = Data(trace, with_='l') g = Gnuplot() g('set ytics 0, 100') g('set xtics 0, 20') g('set grid') g.plot(data) raw_input() file = open('../tmp/trace_gen.txt','w') for value in trace: file.write('%f\n' % value) file.close()
class moments(etData): def __init__(self,allign="para"): etData.__init__(self) self.name="moments%scoreff2.dat"%(allign) self.load() self.gphist=Gnuplot() self.gphist("set title '%s'"%(allign)) def load(self): infile=open(self.name,"r") keys=(infile.readline()).split() dat=loadtxt(infile) for i,key in enumerate(keys): self.data[key]=copy.deepcopy(dat[:,i]) def plot_hist(self,arg,xvals,xlabel=None,ylabel=None,save=False,title=None,reset=False): print self.get_hist(arg,xvals)[0],self.get_hist(arg,xvals)[1] if reset: self.gphist.reset() if ylabel: self.gphist("set ylabel '%s'"%(ylabel)) if xlabel: self.gphist("set xlabel '%s'"%(xlabel)) if not title: title=arg self.gphist.replot(Data(self.get_hist(arg,xvals)[0],self.get_hist(arg,xvals)[1],with_="histeps lw 3",title=title)) if ylabel or xlabel: self.gphist("unset xlabel")
def __init__(self, data, angular_bins, radial_bins): """ Method: __init__(data,angular_bins,radial_bins) The polar3D class is used to creates a color contour plot using Gnuplot.py in polar coordinates. The countour pixel will therefore be small fraction of a circles depending on the chosen angular bins and radial bins. Typical application would be to show the angular dependence of a spectrum. INPUT: data - which should be a list or numpy array containing the bin intensity for each angular bin and radial bin. Must have the dimension: [x: len(angular_bins), y: len(radial_bins)] angular_bins - should be a list or numpy array of the linear-spaced angular bins used in 'data' radial_bins - should be a list or numpy array of the linear-spaced radial bins used in 'data' Available Methods: (use help('method') in ipython to learn more) self.plot() - Plots the data self.reset() - Resets the plot self.save(filename) - saves the plot to an eps self.set_title(arg) - set the plot title self.set_label(arg) - set the plot xy label self.set_cblabel(arg) - set the plot colorbar label self.set_range(arg) - set the maximum r-range of the plot self.set_tics(ticlist,ticlabels=arg) - define your own tics self.add_2ddata(data) - This adds additional 2d date to the plot self.cbtics(cbtics,cb_labels=arg) - define you own cb tics self.grid(trig,angles=arg,color=arg,solid=arg) - turn on the polar grid self.set_log(arg) -Turn on logarithmic cb AN EXAMPLE HOW TO USE THIS CLASS IS SHOWN AT THE END OF THIS FILE! """ self.data = array(data) self.angular_bins = array(angular_bins) self.radial_bins = array(radial_bins) self.data2d = [] if len(self.data[:, 0]) != len(self.angular_bins) or len( self.data[0, :]) != len(self.radial_bins): print "--- Dimension of DATA %s differs from angular bins %s or radial bins %s! ---" % ( self.data.shape, self.angular_bins.shape, self.radial_bins.shape) print "--- Press Enter to Exit! ---" raw_input() exit() self.log = 0 self.gp = Gnuplot() self.gp("set terminal x11 enhanced") self.gp("set size square") self.gp("set xrange [-%s:%s]" % (self.radial_bins[-1], self.radial_bins[-1])) self.gp("set yrange [-%s:%s]" % (self.radial_bins[-1], self.radial_bins[-1])) self.gp("set xlabel ''") self.gp("set ylabel ''") self.gp("set xtics out autofreq") self.gp("set ytics out autofreq") self.gp("set mxtics") self.gp("set mytics") self.gp("unset title") self.gp("unset grid") self.gp("set angles degrees")
def do_plots(func, *pots, **kwds): try: persist = kwds.pop('kwds') except KeyError: persist = True gp = Gnuplot(persist=persist) gp.xlabel('Separation Distance (nm)') gp.plot(*list(func(pot, **kwds) for pot in pots)) return gp
def plot_pi_gnuplot(npts=100): from Gnuplot import Gnuplot,Data g = Gnuplot() g.title("Pi computed using different approximations") g("set yrange [2:4]") steps = range(npts) data = [] for func in sequences: data.append(Data(steps,func(npts),with='lines',title=func.__name__)) apply(g.plot,data) return
def __init__(self, year, timeframe): self.year = year self.timeframe = timeframe self.hedata = loadswicsiondata("He2+", 720., self.year, self.timeframe, "/data/etph/ace/") self.odata = loadswicsiondata("O6+", 720., self.year, self.timeframe, "/data/etph/ace/") self.hdata = swicsdcrtcr("H1+", self.year, self.timeframe, "/data/etph/ace/pui/12mdata/") self.swedata = swepamdata(64., self.year, self.timeframe, "/data/etph/ace/swepam/") self.swedata.sync_h(self.hedata) self.mag = magdata(1., self.year, self.timeframe, "/data/etph/ace/mag/") self.mag.sync_mag(self.hedata) self.theta = arccos(cos(self.mag.phi) * cos(self.mag.theta)) self.valf = 21.8 / sqrt(self.swedata.dens) * (self.mag.magb) self.valf[isinf(self.valf)] = -1. self.valf[isnan(self.valf)] = -2. self.effh = zeros([58]) self.effhe = zeros([58]) self.effo = zeros([58]) self.gp = Gnuplot() self.gp("set xr [-2:3]") self.gp("set yr [0:1]") self.gp("set xlabel '(v-v_{sw})/C_{A}'") self.stdhe = [] self.stdo = [] self.stdh = [] self.skewhe = [] self.skewo = [] self.skewh = [] self.kurthe = [] self.kurto = [] self.kurth = [] self.meanvhe = [] self.meanvo = [] self.meanvh = [] self.maxvhe = [] self.maxvo = [] self.maxvh = [] self.time = [] self.years = [] self.valfs = [] self.magb = [] self.thetas = [] self.sigtheta = [] self.vsw = [] self.dsw = [] self.tsw = [] self.load_eff()
def plot(self, plot_idle=False, show=True, to_file=None): assert self.processed from Gnuplot import Gnuplot g= Gnuplot() g('set style data linespoints') all_pids= set([cs.pid for cs in self.trace]) process_data= [filter(lambda s:s.pid==pid, self.trace) for pid in all_pids] data=[ [(state.clock, state.clocks_done) for state in states] for states in process_data] if not plot_idle: data[0]=[(0,0)] if show: g.plot(*data) if not to_file is None: g.hardcopy(to_file, enhanced=1, color=1) raw_input("Press any key to close...")
def plot_qv(base, means, stdevs): ''' Generate a quality plot and return the URL to the output file. ''' filename = "%s/%s" % (CONFIG.httptmpdir, base) url = "%s/%s" % (CONFIG.httptmpurl, base) # There's almost certainly a prettier way to do this in the Gnuplot # package; this is a straight port from piping commands to the # gnuplot program (Update FIXME seems like gnuplotlib is the way to # go, or move to something completely unrelated to gnuplot like # matplotlib or seaborn): g = Gnuplot() g('set terminal png size 400,300') g("set output \"%s\"" % filename) g("plot [0:%d] [-1:41] \"-\" with errorbars notitle," % (len(means) + 1, ) + " \"-\" with linespoints notitle") for i in range(len(means)): g("%d %f %f" % (i + 1, means[i], stdevs[i])) g("e") for i in range(len(means)): g("%d %f %f" % (i + 1, means[i], stdevs[i])) g("e") g("set output") return url
def MakePlot(details, final, counts, pickVects, nModels, nTrueActs=-1): if not hasattr(details, 'plotFile') or not details.plotFile: return dataFileName = '%s.dat' % (details.plotFile) outF = open(dataFileName, 'w+') i = 0 while i < len(final) and counts[i] != 0: if nModels > 1: _, sd = Stats.MeanAndDev(pickVects[i]) confInterval = Stats.GetConfidenceInterval(sd, len(pickVects[i]), level=90) outF.write('%d %f %f %d %f\n' % (i + 1, final[i][0] / counts[i], final[i][1] / counts[i], counts[i], confInterval)) else: outF.write('%d %f %f %d\n' % (i + 1, final[i][0] / counts[i], final[i][1] / counts[i], counts[i])) i += 1 outF.close() plotFileName = '%s.gnu' % (details.plotFile) gnuF = open(plotFileName, 'w+') gnuHdr = """# Generated by EnrichPlot.py version: %s set size square 0.7 set xr [0:] set data styl points set ylab 'Num Correct Picks' set xlab 'Num Picks' set grid set nokey set term postscript enh color solid "Helvetica" 16 set term X """ % (__VERSION_STRING) print(gnuHdr, file=gnuF) if nTrueActs > 0: print('set yr [0:%d]' % nTrueActs, file=gnuF) print('plot x with lines', file=gnuF) if nModels > 1: everyGap = i / 20 print('replot "%s" using 1:2 with lines,' % (dataFileName), end='', file=gnuF) print('"%s" every %d using 1:2:5 with yerrorbars' % (dataFileName, everyGap), file=gnuF) else: print('replot "%s" with points' % (dataFileName), file=gnuF) gnuF.close() if hasattr(details, 'showPlot') and details.showPlot: try: from Gnuplot import Gnuplot p = Gnuplot() p('load "%s"' % (plotFileName)) input('press return to continue...\n') except Exception: import traceback traceback.print_exc()
def plot(self): self.gp = Gnuplot() self.generatebox() for panel in range(len(self.panel)): self.plotpanel(panel) #self.gp("unset tmargin") #self.gp("unset title") #self.gp("unset multiplot") #self.gp("set size 1,1") #self.gp("set xtics") self.gp("set autoscale") self.gp.sync() os.system("ps2eps -f -B -l %s.ps" % (self.outname)) os.system("rm %s.ps" % (self.outname)) if (self.gv): os.system("okular %s.eps" % (self.outname)) del self.gp
def geterror(self): gp=Gnuplot() # gp("set yrange[0:1e20]") gp("a=%f" %(self.counts)) print len(self.histogram[0]) gp("b=5.") gp("c=200.") gp("f(x)=c/(sqrt(2.*pi)*b)*exp(-((x-a)**2/(2.*b**2)))") self.gphist=Data(self.histogram[0]) self.gphist.set_option_colonsep("with","boxes") if (len(self.histogram[0])>3): gp("fit f(x) '"+self.gphist.filename+"' using 1:2 via a,b") gp("fit f(x) '"+self.gphist.filename+"' using 1:2 via b") else: gp("b=0.1") # gp.plot(self.gphist,"f(x)") # gp("pause 3") self.error=gp.eval("b")/self.counts print self.error
def __init__(self): self.verbose = True self.origin = (0,0) self.data2 = [] self.data3 = [] self.g = Gnuplot() self.g('set data style points') self.g('set key left top Left title \'Legend\' box 3') self.title = 'title' self.xlabel = 'x' self.ylabel = 'y' self.zlabel = 'z'
def __init__(self, angular_bins, *datasets): """ Method: __init__(data,angular_bins) The polar2D class is used to create a plot using Gnuplot.py in polar coordinates. Typical application would be to show the angular dependence of Count Rates. INPUT: datasets - a list of CR, that have the same dimension as angular_bins angular_bins - should be a list or numpy array of the linear-spaced angular bins used in 'data' Available Methods: (use help('method') in ipython to learn more) AN EXAMPLE HOW TO USE THIS CLASS IS SHOWN AT THE END OF THIS FILE! """ self.data = [] for d in datasets: self.data.append(array(d)) self.len_data = len(self.data) self.angular_bins = array(angular_bins) if len(self.data[0]) != len(self.angular_bins): print "--- Dimension of DATA %s differs from angular bins %s! ---" % ( self.data[0].shape, self.angular_bins.shape) print "--- Press Enter to Exit! ---" raw_input() exit() self.log = 0 self.gp = Gnuplot() self.gp("set terminal x11 enhanced") self.gp("set size square") self.gp("set xlabel ''") self.gp("set ylabel ''") self.gp("set xtics out autofreq") self.gp("set ytics out autofreq") self.gp("set mxtics") self.gp("set mytics") self.gp("unset title") self.gp("unset grid") self.gp("set angles degrees") self.plotmode = 'S' self.set_data_label(["" for i in range(self.len_data)])
def reset(self): """ This routine resets the current plot window to standard options If you change certain parameters (like self.log) you may want to run this again to update the data This also """ self.__create_gpdata__() self.gp = Gnuplot() self.gp("set xrange [-%s:%s]" % (self.radial_bins[-1], self.radial_bins[-1])) self.gp("set yrange [-%s:%s]" % (self.radial_bins[-1], self.radial_bins[-1])) self.gp("set xlabel ''") self.gp("set ylabel ''") self.gp("set xtics out autofreq") self.gp("set ytics out autofreq") self.gp("set mxtics") self.gp("set mytics") self.gp("unset title") self.gp("unset grid") self.gp("unset label") self.gp("unset title") self.cb_labels = None self.__det_cbtics__()
class Plot: def __init__(self, fn=None): self.gp = Gnuplot() if fn: self.gp('load "%s"' % fn) self.items = [] self.needs_update = False def markdirty(self, d=True): """ Update will be necessary. """ self.needs_update = d def update(self): """ Update the plot, but only if it necessary. """ if self.needs_update: # only items with 'only_append'? # ao=all([i.only_append for i in self.items]) python2.5 ao = sum([i.only_append for i in self.items]) == len(self.items) for i in self.items: if i.needs_init_plot: ao = False break if not ao: self.gp.plot() # start with empty plot for i in self.items: if i.needs_update: i.update() i.needs_update = False if not ao and not i.empty(): self.gp.replot(i) i.needs_init_plot = False if ao: self.gp.replot( ) # simply cause plot update (FIXME: is this true?) self.needs_update = False def add(self, item): if not item in self.items: self.items += [item] self.needs_update = True connect(self.markdirty, item.changed, weak=False) connect(item.mouseclick, self.mouseclick, weak=False) def remove(self, item): if item in self.items: self.items.remove(item) disconnect(self.markdirty, item.changed) disconnect(item.mouseclick, self.mouseclick) self.needs_update = True def mouseclick(self, x, y, btn): send(self.mouseclick, self, x, y, btn)
def plot(self): self.gp = Gnuplot() #self.gp("set autoscale") self.gp("set size square") self.gp("set xrange[0.01:.1]") self.gp("set yrange[100.:1000.]") self.gp("set format xy '10^%T'") self.gp("set xlabel '{/Symbol w} [Hz]'") self.gp("set ylabel 'Wave Power [arb.]'") self.gp("set logscale xy") self.pParr = Data(self.Parr) self.pParr.set_option_colonsep("with", "lp") self.gp.plot(self.pParr) #self.gp.replot(Data(self.dParr2)) #self.gp.replot(Data(self.dParr2)) self.gp("a=%f" % (self.power)) self.gp("k=%f" % (self.index)) self.gp("f(x)=a*x**-k") self.gp("f2(x)=(a*.7)*x**-(k+.1)") self.gp("f3(x)=(a*1e-5)*x**-(k+4.)") #self.gp.replot("f(x) with l lt 3","f2(x) with l lt 4","f3(x) with l lt 5") self.gp("set term postscript color 18 lw 2 eps") self.gp.hardcopy("Pcascall.ps", color="true", fontsize=18) self.gp2 = Gnuplot() self.gp2("set logscale xy") self.gp2("set title 'theocasc dE'") #gp2("set yrange[1:1.1]") first = 1 for j in range(self.dim): if (first == 1): self.gp2.plot(self.pdParr[j]) first = 0 else: self.gp2.replot(self.pdParr[j]) self.gp3 = Gnuplot() self.gp3("set logscale xy") self.gp3("set title 'theocasc dV'") first = 1 for j in range(self.dim): if (first == 1): self.gp3.plot(self.pdVarr[j]) first = 0 else: self.gp3.replot(self.pdVarr[j])
class polar3D: def __init__(self, data, angular_bins, radial_bins): """ Method: __init__(data,angular_bins,radial_bins) The polar3D class is used to creates a color contour plot using Gnuplot.py in polar coordinates. The countour pixel will therefore be small fraction of a circles depending on the chosen angular bins and radial bins. Typical application would be to show the angular dependence of a spectrum. INPUT: data - which should be a list or numpy array containing the bin intensity for each angular bin and radial bin. Must have the dimension: [x: len(angular_bins), y: len(radial_bins)] angular_bins - should be a list or numpy array of the linear-spaced angular bins used in 'data' radial_bins - should be a list or numpy array of the linear-spaced radial bins used in 'data' Available Methods: (use help('method') in ipython to learn more) self.plot() - Plots the data self.reset() - Resets the plot self.save(filename) - saves the plot to an eps self.set_title(arg) - set the plot title self.set_label(arg) - set the plot xy label self.set_cblabel(arg) - set the plot colorbar label self.set_range(arg) - set the maximum r-range of the plot self.set_tics(ticlist,ticlabels=arg) - define your own tics self.add_2ddata(data) - This adds additional 2d date to the plot self.cbtics(cbtics,cb_labels=arg) - define you own cb tics self.grid(trig,angles=arg,color=arg,solid=arg) - turn on the polar grid self.set_log(arg) -Turn on logarithmic cb AN EXAMPLE HOW TO USE THIS CLASS IS SHOWN AT THE END OF THIS FILE! """ self.data = array(data) self.angular_bins = array(angular_bins) self.radial_bins = array(radial_bins) self.data2d = [] if len(self.data[:, 0]) != len(self.angular_bins) or len( self.data[0, :]) != len(self.radial_bins): print "--- Dimension of DATA %s differs from angular bins %s or radial bins %s! ---" % ( self.data.shape, self.angular_bins.shape, self.radial_bins.shape) print "--- Press Enter to Exit! ---" raw_input() exit() self.log = 0 self.gp = Gnuplot() self.gp("set terminal x11 enhanced") self.gp("set size square") self.gp("set xrange [-%s:%s]" % (self.radial_bins[-1], self.radial_bins[-1])) self.gp("set yrange [-%s:%s]" % (self.radial_bins[-1], self.radial_bins[-1])) self.gp("set xlabel ''") self.gp("set ylabel ''") self.gp("set xtics out autofreq") self.gp("set ytics out autofreq") self.gp("set mxtics") self.gp("set mytics") self.gp("unset title") self.gp("unset grid") self.gp("set angles degrees") def __polar_to_cart__(self, r, phi): """ This routine transforms polar coordinates to carthesian coordiantes INPUT: r, phi (polar coord (phi in degree from 0 to 360)) OUTPUT: x, y in carth. coord """ phi = 360. - phi deg_to_arcsec = (2 * pi) / 360. x = r * cos(phi * deg_to_arcsec) y = r * sin(phi * deg_to_arcsec) return x, y def __det_rgb__(self, rgb_color): """ This routine calculated the RGB from an rgb value (0-1020; calculated like i long(1020.*(counts-min_counts)/(max_counts-min_counts))). INPUT: rgb color value (0,1020) OUTPUT: r, g, b (0-255,0-255,0-255) """ if rgb_color >= 765: r = 255 g = 1020 - rgb_color b = 0 elif 765 > rgb_color > 510: r = rgb_color - 510 g = 255 b = 0 elif 510 >= rgb_color > 255: r = 0 g = rgb_color - 255 b = 510 - rgb_color elif 255 >= rgb_color > 0: r, g = 0, 0 b = rgb_color else: r, g, b = 0, 0, 0 if rgb_color == -1: r, g, b = 0, 0, 1 if rgb_color == 0: r, g, b = 255, 255, 255 if rgb_color == 0: r, g, b = 1, 0, 0 return r, g, b def __create_gpdata__(self): """ This routine create a Gnuplot data object from the given data, angular bins and radial bins """ self.__det_cbtics__() if self.log: max_counts = log10(max(self.data[nonzero(self.data)])) min_counts = log10(min(self.data[nonzero(self.data)])) else: max_counts = max(self.data) min_counts = min(self.data[nonzero(self.data)]) self.gparray = [] for rindex, radius in enumerate(self.radial_bins): for aindex, angle in enumerate(self.angular_bins): counts = self.data[aindex, rindex] if counts > 0: if self.log: counts = log10(counts) rgb_color = long(1020. * (counts - min_counts) / (max_counts - min_counts)) r, g, b = self.__det_rgb__(rgb_color) r_s = radius - (self.radial_bins[1] - self.radial_bins[0]) / 2. r_e = radius + (self.radial_bins[1] - self.radial_bins[0]) / 2. a_s = angle - (self.angular_bins[1] - self.angular_bins[0]) / 2. a_e = angle + (self.angular_bins[1] - self.angular_bins[0]) / 2. a_s = angle a_e = angle + (self.angular_bins[1] - self.angular_bins[0]) bin_koord = [] x1, y1 = self.__polar_to_cart__(r_s, a_s) x2, y2 = self.__polar_to_cart__(r_e, a_s) x3, y3 = self.__polar_to_cart__(r_e, a_e) x4, y4 = self.__polar_to_cart__(r_s, a_e) bin_koord.append([x1, y1]) bin_koord.append([x2, y2]) bin_koord.append([x3, y3]) bin_koord.append([x4, y4]) bin_koord.append([x1, y1]) dataobj = Data( bin_koord, with_='filledcurves lc rgb "#%02X%02X%02X"' % (r, g, b)) self.gparray.append(dataobj) def __det_cbtics__(self): """ This routine determines the cb tics drawn onto the colorbar """ max_counts = max(self.data) min_counts = min(self.data[nonzero(self.data)]) cbrange = max_counts - min_counts tic_interval = [1, 2, 5] tic_level = range(long(log10(min_counts) - 1), long(log10(max_counts) + 1) + 1) ntic_tmp = 1e9 for ti in tic_interval: for tl in tic_level: ntic = abs(round(cbrange / (ti * 10**tl)) - 10) if ntic < ntic_tmp: cti, ctl = ti, tl ntic_tmp = ntic if cti == 5: self.mtn = 5. if cti == 1: self.mtn = 10. if cti == 2: self.mtn = 4. if self.log: self.cb_tics = arange(tic_level[0], tic_level[-1]) else: self.cb_tics = arange(10**tic_level[0], 10**tic_level[-1], cti * 10**ctl) - 10**tic_level[0] self.cb_labels = None def __create_colorbar__(self): """ This routine creates the colorbar for the contour plot """ if self.log: max_counts = log10(max(self.data[nonzero(self.data)])) min_counts = log10(min(self.data[nonzero(self.data)])) else: max_counts = max(self.data) min_counts = min(self.data[nonzero(self.data)]) cbrange = max_counts - min_counts if self.log: mtn = 10. else: mtn = self.mtn cb_tics = self.cb_tics cbw = self.cb_tics[1] - self.cb_tics[0] xs, xe = 1.05, 1.1 self.gp( "set arrow from graph %s, graph -0.01 to graph %s, graph 1. nohead" % (xs, xs)) self.gp( "set arrow from graph %s, graph -0.01 to graph %s, graph 1. nohead" % (xe, xe)) self.gp( "set arrow from graph %s, graph -0.01 to graph %s, graph -0.01 nohead" % (xs, xe)) self.gp( "set arrow from graph %s, graph 1. to graph %s, graph 1. nohead" % (xs, xe)) for rgb_color in arange(0, 1020.): r, g, b = self.__det_rgb__(rgb_color) ys = rgb_color / 1020. - 0.01 ye = rgb_color / 1020. self.gp( 'set obj %s rect from graph %s, graph %s to graph %s, graph %s fc rgb "#%02X%02X%02X" fs noborder' % (rgb_color + 1, xs, ys, xe, ye, r, g, b)) for index, t in enumerate(cb_tics): rgb_color = long(1020. * (float(t) - min_counts) / cbrange) ye = rgb_color / 1020. if t > min_counts and t < max_counts: self.gp( "set arrow from graph %s, graph %s to graph %s, graph %s nohead" % (xs, ye, xs + (xe - xs) * 0.3, ye)) self.gp( "set arrow from graph %s, graph %s to graph %s, graph %s nohead" % (xe, ye, xe - (xe - xs) * 0.3, ye)) if self.cb_labels == None: if self.log: self.gp( "set label '10^{%s}' at graph %s, graph %s front" % (t, xe + (xe - xs) * 0.4, ye)) else: self.gp("set label '%s' at graph %s, graph %s front" % (t, xe + (xe - xs) * 0.4, ye)) else: self.gp("set label '%s' at graph %s, graph %s front" % (self.cb_labels[index], xe + (xe - xs) * 0.4, ye)) if self.log: mts = log10(arange(10**t, 10**(t + 1), 10**t)) #HIER WEITER else: mts = range(long(mtn)) #HIER WEITER for mt in mts: if self.log: mtic = mt else: mtic = t + (mt / mtn) * cbw if mtic > min_counts and mtic < max_counts: if self.log: rgb_color = long(1020. * (mtic - min_counts) / cbrange) else: rgb_color = long( 1020. * (t + (mt / mtn) * cbw - min_counts) / cbrange) ye = rgb_color / 1020. self.gp( "set arrow from graph %s, graph %s to graph %s, graph %s nohead" % (xs, ye, xs + (xe - xs) * 0.15, ye)) self.gp( "set arrow from graph %s, graph %s to graph %s, graph %s nohead" % (xe, ye, xe - (xe - xs) * 0.15, ye)) def reset(self): """ This routine resets the current plot window to standard options If you change certain parameters (like self.log) you may want to run this again to update the data This also """ self.__create_gpdata__() self.gp = Gnuplot() self.gp("set xrange [-%s:%s]" % (self.radial_bins[-1], self.radial_bins[-1])) self.gp("set yrange [-%s:%s]" % (self.radial_bins[-1], self.radial_bins[-1])) self.gp("set xlabel ''") self.gp("set ylabel ''") self.gp("set xtics out autofreq") self.gp("set ytics out autofreq") self.gp("set mxtics") self.gp("set mytics") self.gp("unset title") self.gp("unset grid") self.gp("unset label") self.gp("unset title") self.cb_labels = None self.__det_cbtics__() def set_title(self, title, corner=0): """ This routine sets the title INPUT: title - title of the plot as a string corner - if 0 title is put on top of the plot, if 1 title is put in lower left corner """ if corner == 0: self.gp("set title '%s'" % (title)) else: self.gp("set label '%s' at graph %s, graph %s" % (title, 0.02, 0.03)) def set_label(self, label): """ This routine set the x and y label """ self.gp("set xlabel '%s'" % (label)) self.gp("set ylabel '%s'" % (label)) def set_cblabel(self, label, xoff=0, yoff=0): """ This routine sets the cb label INPUT: label - string of the cblabel xoff - optional offset to the label in x direction yoff - optional offset to the label in y direction """ x, y = 1.23, 0.6 self.gp( "set label '%s' at graph %s, graph %s rotate by 90 right front" % (label, x + xoff, y + yoff)) def set_range(self, arg): """ This routine sets the r-range of the plot """ self.gp("set xrange [-%s:%s]" % (arg, arg)) self.gp("set yrange [-%s:%s]" % (arg, arg)) def set_tics(self, tics, ticlabels=None): """ Explicitly gives tics to the plot. This also affects at what location the polar grid is drawn INPUT: tics - list of tics (e.g. [0,10,12,13,25]) ticlabels - corresponding tic labels (e.g. ["ZERO","TEN","TWELVE","THIRTEEN","TWENTYFIVE"]) -- if names is not given, the tic location is used as a ticlabel instead -- """ ticlabel = "" if ticlabels != None: if len(tics) != len(ticlabels): print " --- Tics and ticlabels must have the same size! ---" print " --- Ignoring call of set_tics! ---" return 0 for index, tic in enumerate(tics): if ticlabels != None: ticlabel += "'%s' %s," % (ticlabels[index], tic) else: ticlabel += "'%s' %s," % (tic, tic) self.gp("set xtics out (%s) rotate by -90" % (ticlabel[0:-1])) self.gp("set ytics out (%s)" % (ticlabel[0:-1])) def set_cbtics(self, cb_tics, cb_labels=None): """ This routine sets the tics for the colorbar INPUT: cbtics - list of cbtics (e.g. [10,100,1000]) cb_labels - list of cbticlabels -- if cbticlabels are not given, the cbtics are used as labels instead """ self.cb_tics = cb_tics self.cb_labels = cb_labels self.mtn = 0 def add_2ddata(self, data, linewidth=2, color='red'): """ Here you can add additional 2 dimensional data to the color contour plot INPUT: data (must be of dimension of angular_bins, values must be in range of radial_bins) linewidth of the data color of the data """ from numpy import append datax, datay = self.__polar_to_cart__( append(data, data[0]), append(self.angular_bins, self.angular_bins[0])) dataobj = Data(datax, datay, with_="lines lw %s lc rgb '%s'" % (linewidth, color)) self.data2d.append(dataobj) def set_grid(self, trig, angles=45, color='black', solid=1, linewidth=0.5): """ Here you can turn the grid on and off INPUT: trig - (0 for 'off', 1 for 'on') angles - number of radial lines in polar grid color - color of the grid INPUT: trig - (0 for 'off', 1 for 'on') """ if trig == 1: self.gp("set grid xtics nomxtics polar %s" % (angles)) self.gp("set grid xtics front lw %s" % (linewidth)) self.gp("set grid linecolor rgb '%s'" % (color)) if solid == 1: self.gp("set grid linetype 1") else: self.gp("set grid linetype 0") for ang in arange(0, 360, angles): x, y = self.__polar_to_cart__(0.45, ang) self.gp( "set label '%s {/Symbol \260}' at graph %s, graph %s textcolor rgb '%s' front" % (ang, x + 0.47, y + 0.49, color)) else: self.gp("unset grid") def set_log(self, trig): """ Here you can turn on an logarithmic plot INPUT: trig - (0 for 'off', 1 for 'on') -- Data set muste be reloaded, which could take while --- """ if trig == 1: self.log = trig else: self.log = 0 def save(self, filename='polar.eps', font="Helvetica", fontsize=15): """ This routine saves the plot into an eps file INPUT: filename - filename font - name of the eps font fontsize- size of eps font """ self.gp.hardcopy(filename, enhanced=1, color=1, solid=1, fontname=font, fontsize=fontsize) def plot(self): """ This routine creates the Gnuplot plot """ self.__create_gpdata__() self.__create_colorbar__() if self.data2d: for d in self.data2d: self.gparray.append(d) self.gp.plot(*self.gparray) def kill_plot(self): """ Routines that kills the Gnuplot window """ del self.gp
#!/usr/bin/python from Gnuplot import Gnuplot from func_ext import * gp = Gnuplot() ef = ExternalFunction(gp, "test", ["a"], lambda x, a: a * x * x) gp("a=3") gp.plot("test(x)")
from scipy import zeros, dot from numpy import float from Gnuplot import Gnuplot, GridData from math import sin, cos, tan, asin, acos, atan, exp, pi from os import popen2 from sys import stdin import random from scipy.integrate import quad from Gnuplot.func_ext import * #from functions import * from libacepy.frange import frange import random Float = float matrixmultiply = dot gp = Gnuplot() c = zeros([101], Float) t_data = zeros([512, 3], Float) e_data = zeros([128, 3], Float) ions = [ "He2", "O8", "N7", "C6", "13C6", "O7", "N6", "C5", "Mg10", "Ne8", "O6", "N5", "Si12", "Si9", "Si10", "Si11", "C4", "O5" ] ions1 = [ "He2", "O8", "N7", "C6", "13C6", "O7", "N6", "C5", "Mg10", "Ne8", "O6", "N5" ] ions2 = [ "He2", "O8", "N7", "C6", "13C6", "O7", "N6", "C5", "Mg10", "Ne8", "O6", "N5", "Si12", "Si9", "Si10", "Si11", "C4", "O5"
plottemp=[] for ion in range(len(ionnames)): if (len(iontemp[ion])>1): tmpplottemp=Data(iontemp[ion]) else: tmpplottemp=Data([[0.,0.]]) # tmpplottemp=Data(iontemp[ion]) # tmpplotdata.set_option_colonsep("using", "1:4 ") tmpplottemp.set_option_colonsep("title", "'%s Temperatur'" %(ionnames[ion])) tmpplottemp.set_option_colonsep("with", "points") plottemp.append(tmpplottemp) gp=Gnuplot() #gp("set yrange[0:1000]") gp("set style data dots") gp("set xlabel 'Day'") gp("set ylabel 'Density[1/cm³]*10^10,Velocity[km/s]*10^3,Temperatur[K]'") gp("set logscale y") #bestimmte Ionen plotten o6pos=0 o7pos=0 o7o6fac=100000000. for ion in range(len(ionnames)): if (ionnames[ion]=="O6+"): o6pos=ion if (ionnames[ion]=="O7+"): o7pos=ion
plotdens=[] for ion in range(len(ion_list)): tmpdensplot=[] for time in range(len(data)): for ion2 in range(len(data[time])): if (ion_list[ion]==data[time][ion2][0]): tmpdensplot.append([(279.+time*5.*0.00833),data[time][ion2][7]]) plotdens.append(Data(tmpdensplot)) for ion in range(len(ion_list)): plottemp[ion].set_option_colonsep("title", "'%s'" %(ion_list[ion])) plotdens[ion].set_option_colonsep("title", "'%s'" %(ion_list[ion])) plotvel[ion].set_option_colonsep("title", "'%s'" %(ion_list[ion])) gp=Gnuplot() gp("set logscale y") #gp("set yrange[0.00001:100]") gp.plot(plotswepamd) for ion in range(len(plotdens)): gp.replot(plotdens[ion]) gp.replot(plotswepamr) gp("set xlabel 'DoY'") gp("set ylabel 'Density [1/cm^{3}]'") gp("set title ''") gp("set term postscript color 18 lw 3 eps") gp.hardcopy("density.ps", color=True, fontsize=18) """ gp.plot(plotswepamt) for ion in range(len(plottemp)):
""" mag = magdata(240, 2007, 1., 362., magpath) mag.load() magsync = sync_mag(mag, he) o = swicselemdata("O", timeframequietplot, swicspath) fe = swicselemdata("Fe", timeframequietplot, swicspath) o.load() fe.load() feoheh = [] feoheh2 = [] feoheh3 = [] feoheh4 = [] feoheh5 = [] gp = Gnuplot() hehmag = [] mfe = 0. mhe = 0. nm = 0. mfe2 = 0. mhe2 = 0. nm2 = 0. """ for i in range(len(he.time)): if (hswics.dens[i][0]>0. and o.dens[i][1]>0. and he.vel[i]>600. and fe.dens[i][1]>0.): hehmag.append([acos(abs(cos(magsync.phi[i][1])*cos(magsync.theta[i][1]))),he.dens[i][0]/hswics.dens[i][0]]) acos(abs(cos(magsync.phi[i][1])*cos(magsync.theta[i][1]))) """ for i in range(len(he.time)): if (hsync.dens[i][1] > 0. and he.vel[i] > 600. and he.vel[i] > 600.):
from scipy import zeros, dot from numpy import float from Gnuplot import Gnuplot, GridData from math import sin, cos, tan, asin, acos, atan, exp, pi from os import popen2 from sys import stdin import random from scipy.integrate import quad from Gnuplot.func_ext import * #from functions import * from libacepy.frange import frange import random Float = float matrixmultiply = dot gp = Gnuplot() #de=0.682817 # bis februar 09 #dt=5.80315 # bis februar 09 de = 0.448 # neuer fit, februar 09 dt = 6.41 # neuer fit, februar 09 de = 0.448055 # wie vorher nur genauer dt = 6.41082818114 # wie vorher nur genauer #de=0.451238 # paps=23.8, thick=2.3 #dt=6.48819922535 # paps=23.8, thick=2.3 de = 1.448055 # wie vorher nur genauer dt = 7.41082818114 # wie vorher nur genauer #de=1.451238 # paps=23.8, thick=2.3 #dt=7.48819922535 # paps=23.8, thick=2.3 ions = ["he2"]
phist.append(Data(spec)) phist[len(phist) - 1].set_option_colonsep("title", "'%s'" % (fedata[i].name)) phist[len(phist) - 1].set_option_colonsep("with", "xyerrorbars") phist[len(phist) - 1].set_option_colonsep("using", "1:2:4:3") i += 1 psumhist = Data(sumhist) psumhist.set_option_colonsep("title", "'Fe'") psumhist.set_option_colonsep("with", "xyerrorbars lw 3") psumhist.set_option_colonsep("using", "1:2:4:3") print "astring = ", astring # Plot wird initialisiert + geplottet gp = Gnuplot() #gp("f(x)=3.e6*x**-5.7") gp("set size square") #gp("set grid front") #gp("unset grid") gp("set key default") gp("set key box below") gp("unset key") gp("set log xy") gp("set yrange[1e2:1e7]") gp("set xrange[1.:20.]") gp("set xlabel 'keV/amu'") gp("set ylabel 'Fe Flux (cts/cm^{2} sr MeV/n)'") #gp("set boxwidth %f"%(step/2.)) gp("set mytics 10") gp("set mxtics 10")
from Gnuplot import Gnuplot pin = open("/home/ivar/berger/projects/ionpositions/ion_para.dat") hepos = [] o6pos = [] o7pos = [] for step in range(58): s = pin.readline() k = s.split() ions = float(k[5]) s = pin.readline() for i in range(ions): s = pin.readline() k = s.split() if (k[0] == "He2+"): hepos.append([float(k[7]), float(k[2])]) if (k[0] == "O6+"): o6pos.append([float(k[7]), float(k[2])]) if (k[0] == "O7+"): o7pos.append([float(k[7]), float(k[2])]) pin.close() gp = Gnuplot() gp("f(x)=8") gp("set yrange[5:10]") gp("set xrange[200:700]") gp.plot(hepos, "f(x)") #gp.plot(hepos,o6pos,o6pos,o7pos)
def coevolution(n=200,nsteps=6000): fitness = [random() for i in range(n)] least_fit_sites = [] for step in range(nsteps): # Determine the least fit site worst = fitness.index(min(fitness)) left = (worst-1)%n right = (worst+1)%n # Add that site to the least_fit_sites list least_fit_sites.append(worst) # Reinitialize the site and its neighbors fitness[worst] = random() fitness[left] = random() fitness[right] = random() # Plot how the least fit site changes with time p = Gnuplot() p.title("Coevolution data for %d steps with %d species" % (nsteps,n)) p.xlabel("Step") d = Data(range(nsteps),least_fit_sites) p.plot(d) raw_input("press any key to continue") # Plot the frequency of the sites in the least_fit_site list: p2 = Gnuplot() p2.title("Frequency of least fit site") d2 = Data(range(n),frequency(n,least_fit_sites)) p2.plot(d2) return
class multiplot: """ docstring should be added ... """ def __init__(self, panels, setformat=0): self.panel = [] for i in range(panels): self.panel.append(plotdata()) self.xrange = [0., 100.] self.xlabel = "DoY" self.xaxis_flag = 0 self.title = "" self.gv = 1 self.format = setformat #0 Querformat, 1 Hochformat self.outname = "multiplot" self.plotmarks = [] def addplotmark(self, style, lt=5): self.plotmarks.append(plotmark(style, lt)) def addpanel(self, data): self.panel.append(plotdata()) def setxrange(self, a, b): self.xrange[0] = a self.xrange[1] = b def settitle(self, a): self.title = a def setgv(self, a): self.gv = a def setxaxis2(self, a): """ This routine plots a seconds xaxis on top of the screen. Input must be a list of lists containing the x2label and xposition of that label: e.g: [["Jan",30],["Feb",58]...] """ self.xaxis_flag = 1 try: b = a[0][0] b = a[0][1] except: print "Wrong input for SELF.SETXAXIS2()" print "Input must be of the form of [['label',xpos],['label',xpos],[],[],...,[]]" print "Second x axis is omitted. Hit ENTER to proceed" blub = raw_input() self.xaxis2 = a def setxlabel(self, a): self.xlabel = str(a) def setname(self, a): self.outname = str(a) def build_xaxis2(self): """ This routine builds the seconds xaxis from self.xaxis2 """ for label in self.xaxis2: if label[1] > self.xrange[0] and label[1] < self.xrange[1]: self.gp( "set label center'{/Helvetica=5 %s}' at first %f, screen 1.00" % (label[0], label[1])) self.xaxis_flag = 0 def plot(self): self.gp = Gnuplot() self.generatebox() for panel in range(len(self.panel)): self.plotpanel(panel) #self.gp("unset tmargin") #self.gp("unset title") #self.gp("unset multiplot") #self.gp("set size 1,1") #self.gp("set xtics") self.gp("set autoscale") self.gp.sync() os.system("ps2eps -f -B -l %s.ps" % (self.outname)) os.system("rm %s.ps" % (self.outname)) if (self.gv): os.system("okular %s.eps" % (self.outname)) del self.gp def generatebox(self): self.gp("set term postscript solid enhanced color") self.gp("set output '%s.ps'" % (self.outname)) self.gp("set border front") self.gp("unset key") self.gp("unset colorbox") self.gp( "set palette model RGB functions gray<1.e-20 ? 1 : gray<0.5 ? gray*2 : 1 , gray<1.e-20 ? 1 : gray<0.5 ? gray*2 : 2-gray*2, gray <1.e-20 ? 1 : gray<0.5 ? 1-sqrt(gray*2) : 0" ) if (self.format): self.gp("set xtics nomirror font 'Helvetica,9'") else: self.gp("set xtics nomirror") self.gp("set multiplot") self.gp("set xlabel 0,0.1") if (self.format): self.gp("set xlabel '%s' font 'Helvetica,9'" % (self.xlabel)) else: self.gp("set xlabel '%s' font 'Helvetica,12'" % (self.xlabel)) self.gp("set xrange[%e:%e]" % (float(self.xrange[0]), float(self.xrange[1]))) if (self.format): self.gp("set ytics font 'Helvetica,9'") else: self.gp("set ytics") #self.gp("set autoscale") self.gp("set key right samplen 0.5") self.gp("set key spacing 0.8") self.gp("unset xtics") self.gp("unset xlabel") self.gp("set border front") if self.xaxis_flag == 1: self.build_xaxis2() def plotpanel(self, panel): self.buildplotmarks(panel) first = 1 self.gp("unset key") self.gp( "set label center'{/Helvetica=9 %s}' at screen 0.3, screen 1.02" % (self.title)) self.gp("set border front") #self.gp("unset label") if (self.panel[panel].grid): self.gp("set grid xtics front") else: self.gp("set grid xtics front") self.gp("unset grid") size = (.86 / (float(len(self.panel)))) + 0.06 size2 = .86 self.gp("unset xlabel") self.gp("set format x ''") self.buildytics(panel) if (panel == 0): size = (.86 / float((len(self.panel)))) + 0.1 self.gp("set xlabel 0,0.2") if (self.format): self.gp("set xlabel '%s' font 'Helvetica,9'" % (self.xlabel)) else: self.gp("set xlabel '%s' font 'Helvetica,12'" % (self.xlabel)) self.gp("set format x") if (self.format): self.gp("set xtics font 'Helvetica,9'") else: self.gp("set xtics") self.gp("set mxtics 10") if (self.panel[panel].type == "plot"): self.gp("set size 1.,%f" % (size)) if (self.format): self.gp("set size 0.6,%f" % (size)) elif (self.panel[panel].type == "splot"): self.gp("set size 1.2935,%f" % (size * 1.65)) if (panel == 0): self.gp("set origin 0,%f" % (0.05)) else: if (self.panel[panel].type == "plot"): self.gp("set origin 0,%f" % (0.09 + float(panel) * (size - 0.06))) elif (self.panel[panel].type == "splot"): self.gp("set origin -.147,%f" % ((0.09 + float(panel) * (size - 0.06)) - .1315)) self.gp("set lmargin 8") if (self.format): self.gp( "set label '%s' at screen 0.05,%f center rotate by 90 font 'Helvetica,9'" % ((self.panel[panel].ylabel), (0.09 + float(panel) * (size - 0.06) + size / 2.))) else: self.gp( "set label '%s' at screen 0.03,%f center rotate by 90 font 'Helvetica,12'" % ((self.panel[panel].ylabel), (0.09 + float(panel) * (size - 0.06) + size / 2.))) self.gp("set yrange[%e:%e]" % (self.panel[panel].yrange[0], self.panel[panel].yrange[1])) if self.panel[panel].xrange[0] != "NAN": self.gp("set xrange[%e:%e]" % (self.panel[panel].xrange[0], self.panel[panel].xrange[1])) # plot marks for mark in self.plotmarks: doplotmark = 0 for i in mark.panels: if (i == -1 or i == panel and self.panel[panel].type == "plot"): doplotmark = 1 if (doplotmark): doplotlabel = 0 if (mark.label != ""): for i in mark.labelpanels: if (i == -1 or i == panel): doplotlabel = 1 if (mark.style == "vline"): head = "" if (mark.arrowhead == 0): head = "nohead" elif (mark.arrowhead == 1): head = "head filled" mark.plot[panel].set_option_colonsep( "with", "vectors %s lt %i lw %i" % (head, mark.linetype, mark.linewidth)) #self.gp("plot 'testvector.dat' with vectors") if (doplotlabel): if (self.format): self.gp( "set label '%s' at graph %f,%f tc lt %i font 'Helvetica,9' front" % ((mark.label, mark.pos[0][0] / (self.xrange[1] - self.xrange[0]) + 0.01, 0.8, mark.linetype))) else: self.gp( "set label '%s' at graph %f,%f tc lt %i font 'Helvetica,12' front" % ((mark.label, mark.pos[0][0] / (self.xrange[1] - self.xrange[0]) + 0.01, 0.8, mark.linetype))) if (first): self.gp.plot(mark.plot[panel]) first = 0 else: self.gp.replot(mark.plot[panel]) if (mark.style == "box"): mark.plot[panel].set_option_colonsep("using", "1:2:3") mark.plot[panel].set_option_colonsep( "with", "filledcurves lt %i" % (mark.linetype)) if (doplotlabel): if (self.format): self.gp( "set label '%s' at graph %f,%f tc lt %i font 'Helvetica,9' center front" % (mark.label, (mark.pos[0][0] + (mark.pos[0][2] - mark.pos[0][0]) / 2.) / (self.xrange[1] - self.xrange[0]), 0.8, 0)) else: self.gp( "set label '%s' at graph %f,%f tc lt %i font 'Helvetica,12' center front" % (mark.label, (mark.pos[0][0] + (mark.pos[0][2] - mark.pos[0][0]) / 2.) / (self.xrange[1] - self.xrange[0]), 0.8, 0)) if (first): self.gp.plot(mark.plot[panel]) first = 0 else: self.gp.replot(mark.plot[panel]) if (mark.style == "hline"): head = "" if (mark.arrowhead == 0): head = "nohead" elif (mark.arrowhead == 1): head = "head filled" mark.plot[panel].set_option_colonsep( "with", "vectors %s lt %i lw %i" % (head, mark.linetype, mark.linewidth)) #self.gp("plot 'testvector.dat' with vectors") if (doplotlabel): if (self.format): self.gp( "set label '%s' at graph %f,%f tc lt %i font 'Helvetica,9' front" % ((mark.label, mark.pos[0][0] / (self.xrange[1] - self.xrange[0]) + 0.01, 0.8, mark.linetype))) else: self.gp( "set label '%s' at graph %f,%f tc lt %i font 'Helvetica,12' front" % ((mark.label, mark.pos[0][0] / (self.xrange[1] - self.xrange[0]) + 0.01, 0.8, mark.linetype))) if (first): self.gp.plot(mark.plot[panel]) first = 0 else: self.gp.replot(mark.plot[panel]) if (mark.style == "function"): if (first): self.gp.plot(mark.plot[panel]) else: self.gp.replot(mark.plot[panel]) if (first and self.panel[panel].type == "plot"): if len(self.panel[panel].data) == 1: self.gp("%s" % (self.panel[panel].key)) self.gp.plot(self.panel[panel].data[0]) first = 0 elif (first and self.panel[panel].type == "splot"): self.gp("set pm3d map") self.gp.splot(self.panel[panel].data[0]) first = 0 else: self.gp.replot(self.panel[panel].data[0]) for i in range(len(self.panel[panel].data) - 1): if i == len(self.panel[panel].data) - 2: self.gp("%s" % (self.panel[panel].key)) self.gp.replot(self.panel[panel].data[i + 1]) self.gp("unset pm3d") def buildplotmarks(self, panel): for mark in self.plotmarks: tmpmark = [] if (mark.style == "vline"): tmppos = mark.pos tmppos[0][1] = self.panel[panel].yrange[0] * 1.01 tmppos[0][3] = (self.panel[panel].yrange[1] - self.panel[panel].yrange[0]) * 0.99 tmpmark = Data(tmppos) if (mark.style == "hline"): tmppos = mark.pos tmppos[0][0] = self.xrange[0] * 1.01 tmppos[0][2] = (self.xrange[1] - self.xrange[0]) * 0.99 tmpmark = Data(tmppos) if (mark.style == "box"): if mark.pos[0][2] == 1e-20: ymin = self.panel[panel].yrange[0] else: ymin = mark.pos[0][2] if mark.pos[0][3] == 1e20: ymax = self.panel[panel].yrange[1] else: ymax = mark.pos[0][3] tmppos = [[mark.pos[0][0], ymin, ymax], [mark.pos[0][1], ymin, ymax]] #tmppos=[[mark.pos[0][0],self.panel[panel].yrange[1],self.panel[panel].yrange[0]],[mark.pos[0][2],self.panel[panel].yrange[1],self.panel[panel].yrange[0]]] tmpmark = Data(tmppos) if (mark.style == "function"): tmpmark = mark.function if (tmpmark != []): mark.addplot(tmpmark) def buildytics(self, panel): # the tics for panel=panel are set. The cases logscale and linear scale are handled. In the first panel (panel==0) all tics are labeled set # in all other panels the first tic is unlabeled to avoid overlapp with the tics from the panel below. # logscale tics are set ---> if yrange is smaller than 7 orders of magnitude the tics are set each order of magnitude and 8 minor tics # corresponding to 2*,3*,...,9* are set (will fail if yrange is smaller than one order of magnitude # if yrange is greater than # linearscale tics are set ---> if (self.panel[panel].ytics != ""): if (self.format): self.gp("set ytics %s font 'Helvetica,9'" % (self.panel[panel].ytics)) else: self.gp("set ytics %s" % (self.panel[panel].ytics)) if (self.panel[panel].logscale): self.gp("set logscale y") return # begin if logscale if (self.panel[panel].logscale): self.gp("unset ytics") self.gp("set logscale y") self.gp("set format y '10^{%2T}'") adjust = 0 i = 1.e0 while (not adjust): i = i * 10. tmp = self.panel[panel].yrange[0] tmp = tmp * i**6 if (tmp >= self.panel[panel].yrange[1]): adjust = 1 if (self.panel[panel].minor < 0): if (i <= 10.): minor = 8 else: minor = int(log(i, 10.) + .01) minor2 = 2 if (self.panel[panel].minor == 0): if (i <= 10.): minor = 0 else: minor = int(log(i, 10.) + .01) minor2 = 1 if (self.panel[panel].minor > 0): if (i <= 10.): minor = self.panel[panel].minor else: minor = int(log(i, 10.) + .01) minor2 = 2 tic = self.panel[panel].yrange[0] utic = tic if (i <= 10.): j = -1 while (utic <= self.panel[panel].yrange[1]): j += 1 utic = tic * i**j if (j == 0): if (panel == 0): if (self.format): self.gp("set ytics (%e) font 'Helvetica,9'" % (utic)) else: self.gp("set ytics (%e)" % (utic)) else: if (self.format): self.gp( "set ytics (' ' %e) font 'Helvetica,9'" % (float(utic))) else: self.gp("set ytics (' ' %e)" % (float(utic))) else: self.gp("set ytics add (%e)" % (utic)) for l in range(minor): self.gp( "set ytics add ('' %e 1)" % (utic + (utic * 9. / float(minor + 1) * float(l + 1)))) else: j = -1 while (utic <= self.panel[panel].yrange[1]): j += 1 utic = tic * i**j if (j == 0): if (panel == 0): if (self.format): self.gp("set ytics (%e) font 'Helvetica,9'" % (utic)) else: self.gp("set ytics (%e)" % (utic)) else: if (self.format): self.gp( "set ytics (' ' %e) font 'Helvetica,9'" % (float(utic))) else: self.gp("set ytics (' ' %e)" % (float(utic))) else: self.gp("set ytics add (%e)" % (utic)) for k in range(minor): for l in range(minor2): if (not (k == minor - 1 and l == minor2 - 1)): if (l == minor2 - 1): self.gp( "set ytics add ('' %e)" % (float(utic) * float(10**k) * float( (l + 1) * 10. / float(minor2)))) else: self.gp( "set ytics add ('' %e 1)" % (float(utic) * float(10**k) * float( (l + 1) * 10. / float(minor2)))) # begin if linear scale else: self.gp("unset ytics") self.gp("unset logscale y") self.gp("set format y '%6g'") i = .1 while (self.panel[panel].yrange[1] - self.panel[panel].yrange[0] > i): i = i * 10. minor = 9 if (i / 4. >= self.panel[panel].yrange[1] - self.panel[panel].yrange[0]): i = i / 4. minor = 4 elif (i / 2. >= self.panel[panel].yrange[1] - self.panel[panel].yrange[0]): i = i / 2. minor = 9 if (self.panel[panel].minor == 0): minor = 0 elif (self.panel[panel].minor > 0): minor = self.panel[panel].minor if (i > 10.): for j in range(6): if (j == 0): if (panel == 0): if (self.format): self.gp("set ytics (%i) font 'Helvetica,9'" % (int(self.panel[panel].yrange[0]))) else: self.gp("set ytics (%i)" % (int(self.panel[panel].yrange[0]))) else: if (self.format): self.gp( "set ytics (' ' %i) font 'Helvetica,9'" % (int(self.panel[panel].yrange[0]))) else: self.gp("set ytics (' ' %i)" % (int(self.panel[panel].yrange[0]))) else: self.gp( "set ytics add (%i)" % (int(self.panel[panel].yrange[0] + i / 5. * j))) print "minor = ", minor for k in range(minor): if ((minor + 1) % 5 == 0 and (k + 1) % 5 == 0): self.gp( "set ytics add (' ' %i)" % (int(self.panel[panel].yrange[0] + j * i / 5. + (i / 5. / float(minor + 1) * float(k + 1))))) else: self.gp( "set ytics add (' ' %i 1)" % (int(self.panel[panel].yrange[0] + j * i / 5. + (i / 5. / float(minor + 1) * float(k + 1))))) else: for j in range(6): if (j == 0): if (panel == 0): if (self.format): self.gp("set ytics (%f) font 'Helvetica,9'" % (self.panel[panel].yrange[0])) else: self.gp("set ytics (%f)" % (self.panel[panel].yrange[0])) else: if (self.format): self.gp( "set ytics (' ' %f) font 'Helvetica,9'" % (self.panel[panel].yrange[0])) else: self.gp("set ytics (' ' %f)" % (self.panel[panel].yrange[0])) else: self.gp("set ytics add (%f)" % (self.panel[panel].yrange[0] + i / 5. * j)) for k in range(minor): if ((minor + 1) % 5 == 0 and (k + 1) % 5 == 0): self.gp( "set ytics add (' ' %f)" % (self.panel[panel].yrange[0] + j * i / 5. + (i / 5. / float(minor + 1) * float(k + 1)))) else: self.gp( "set ytics add (' ' %f 1)" % (self.panel[panel].yrange[0] + j * i / 5. + (i / 5. / float(minor + 1) * float(k + 1))))
def main(): traceFilename = '../../tmp/wc98_1.txt' configFilename = '../../tmp/dynGamma.txt' cReader = ConfigReader() cReader.parse(configFilename) cluster = cReader.readCluster() predictor = cReader.readPredictor() lb = cReader.readLoadBalancer(cluster) cluster.loadBalancer = lb config = cluster._availableServers[:] bestConfig = config[:] predConfig = config[:] reactiveConfig = config[:] bestConfigurator = cReader.readConfigurator(cluster, DummyFilter()) bestConfigurator.setEfficientServerList(cluster._availableServers) bestConfigurator.gamma = 1.0 #do not change!! predConfigurator = cReader.readConfigurator(cluster, predictor) predConfigurator.setEfficientServerList(cluster._availableServers) predConfigurator._gamma = 1.0 reactiveConfigurator = cReader.readConfigurator(cluster, DummyFilter()) reactiveConfigurator.setEfficientServerList(cluster._availableServers) #reactiveConfigurator._gamma = 0.55 step = predConfigurator.windowSize #reads the trace file data = file2data(1, traceFilename)[0] scale(data, cluster.availableServers) predCounter, reactiveCounter, bestCounter = 0, 0, 0 #configuration counter pred_upCounter, pred_downCounter = 0, 0 best_upCounter, best_downCounter = 0, 0 reactive_upCounter, reactive_downCounter = 0, 0 bestPerf = getMaxPerformance(bestConfig) reactivePerf = getMaxPerformance(bestConfig) predPerf = getMaxPerformance(bestConfig) avgs = [] reactivePerfs = [] predPerfs = [] bestPerfs = [] gammas = [] for i in range(len(data) / step): avgData = 0.0 for j in range(step): avgData += data[i * step + j] avgData /= step avgs.append(avgData) reactivePerfs.append(reactivePerf) predPerfs.append(predPerf) optimumConfig = None ''' Will use the efficient list to create the optimumConfig ''' optimumConfig = [bestConfigurator._efficientServerList[0]] k = 1 while getMaxPerformance(optimumConfig) < avgData: optimumConfig.append(bestConfigurator._efficientServerList[k]) k += 1 ''' Calculates the appropriate configuration, 'knowing' that avgData is true ''' if i > 0: #calculates false alarms tmp = bestConfigurator.getConfiguration(avgData, bestConfig, bestConfigurator._gamma) if tmp != bestConfig: bestCounter += 1 bestConfig = tmp bestPerf = getMaxPerformance(bestConfig) bestPerfs.append(bestPerf) ''' Compares the chosen configuration with a least powerful one ''' if avgData > bestPerf: best_downCounter += 1 elif getMaxPerformance(bestConfig) > getMaxPerformance( optimumConfig): best_upCounter += 1 if avgData > reactivePerf: reactive_downCounter += 1 elif getMaxPerformance(reactiveConfig) > getMaxPerformance( optimumConfig): reactive_upCounter += 1 if avgData > predPerf: pred_downCounter += 1 elif getMaxPerformance(predConfig) > getMaxPerformance( optimumConfig): pred_upCounter += 1 elif len(bestConfig) < len(predConfig): pred_upCounter += 1 prediction = predictor.apply(avgData) #actuation = prediction actuation = max(prediction, avgData) tmp = predConfigurator.getConfiguration(actuation, predConfig, predConfigurator._gamma) if set(tmp) != set(predConfig): predCounter += 1 predConfig = tmp predPerf = getMaxPerformance(predConfig) if reactiveConfigurator.dynGamma: idealConfig = bestConfigurator.getConfiguration( avgData, reactiveConfig, reactiveConfigurator.MAX_GAMMA) idealPerf = round(getMaxPerformance(idealConfig), 5) currPerf = round(getMaxPerformance(reactiveConfig), 5) reactiveConfigurator._gamma = reactiveConfigurator.adjustGamma( currPerf - idealPerf) gammas.append(reactiveConfigurator._gamma) tmp = reactiveConfigurator.getConfiguration( avgData, reactiveConfig, reactiveConfigurator._gamma) if set(tmp) != set(reactiveConfig): reactiveCounter += 1 reactiveConfig = tmp reactivePerf = getMaxPerformance(reactiveConfig) print 'Best - False alarms: up = %d, down = %d' % (best_upCounter, best_downCounter) print 'Predictive - False alarms: up = %d, down = %d' % (pred_upCounter, pred_downCounter) print 'Reactive - False alarms: up = %d, down = %d' % ( reactive_upCounter, reactive_downCounter) print 'Best Configs = %d, Predictive Configs = %d, Reactive Configs = %d' %\ (bestCounter, predCounter, reactiveCounter) g = Gnuplot(debug=0) g('reset') #g('set size 0.65,0.65') g('set encoding iso_8859_1') g('set terminal postscript eps enhanced monochrome') g('set output "carlos2.ps"') g('set key top left') g('set xlabel "Tempo (s)"') g('set xrange [0:%d]' % (len(data) / step)) spacing = 15 tics = ','.join([ '"%d" %d' % (x * step * spacing, x * spacing) for x in range(1, len(data) / (step * spacing) + 1) ]) g('set xtics (%s)' % tics) g('set ylabel "Requisições"'.encode('iso_8859_1')) g('set grid') #plot incoming requests avg with_plot = 'steps' #plot configurations pi1 = Data(avgs, with_=with_plot, title='Carga') pi2 = Data(reactivePerfs, with_=with_plot, title='Reativo') pi_gamma = Data(gammas, with_=with_plot, title='Gamma') #pi3 = Data(predPerfs, with_=with_plot,title='Preditivo') #pi4 = Data(bestPerfs, with_=with_plot,title='Perfect') #g.plot(pi1,pi2) #g.plot(pi_gamma) #raw_input() print 'Done'
#a = -7.61996e-12 +/- 2.396e-15 (0.03145%) #b = 0.000565656 +/- 4.014e-09 (0.0007097%) #c = 104.733 +/- 0.00141 (0.001346%) def tstep2bin2(tstep): a = -7.61996e-12 b = 0.000565656 c = 104.733 return a*tstep*tstep+b*tstep+c funct2=zeros([xdim],Float) for i in range(xdim): funct2[i]=tstep2bin2(i) gp=Gnuplot() gp("c=1.") gp("a=1.") gp("b=1.") #gp("set outp X11") #gp("f(x)=a*x**2+b*x+c") #gp("fit f(x) 'tmp.dat' via a,b,c") gp("set data style dots") gp("set xrange[500000:1000000]") gp.plot(data,funct2)
def plot(energies): from Gnuplot import Gnuplot, Data p = Gnuplot() d = Data(range(len(energies)),energies) p.plot(d) return
class Plot: def __init__(self): self.verbose = True self.origin = (0,0) self.data2 = [] self.data3 = [] self.g = Gnuplot() self.g('set data style points') self.g('set key left top Left title \'Legend\' box 3') self.title = 'title' self.xlabel = 'x' self.ylabel = 'y' self.zlabel = 'z' def __call__(self,value): self.g(value) def setOrigin(self,x,y): """ @type x: float @type y: float """ self.origin = (x,y) def setVerbose(self,verbose): """ @type verbose: binary """ self.verbose = verbose def addArrayTuples(self, data, name = ''): """ @param data: data to be added to 2d plot @type data: (float,float)[] """ d = Data(data, title = name) self.data2.append(d) def add2Arrays(self,x,y): """ @type x: float[] @type y: float[] """ if len(x) != len(y): return 'arrays not of equal length' else: array2 = [] for i in range(len(array)): value = (x[i],y[i]) array2.append(value) self.addArrayTuples(array2) def addArrayTriples(self, data): """ @param data: data to be added to 3d plot @type data: (float, float, float)[] """ self.data3.append(data) def add3Arrays(self,x,y,z): """ @type x: float[] @type y: float[] @type z: float[] """ if (len(x) == len(y) == len(z)): array3 = [] for i in range(len(x)): value = (x[i],y[i],z[i]) array3.append(value) self.addArrayTriples(array3) else: print 'arrays not of equal length' def setLabels(self,title='title',xlabel='x',ylabel='y',zlabel='z'): """ @type title: string @type xlabel: string @type ylable: string @type zlable: string """ self.title = title self.xlabel = xlabel self.ylabel = ylabel self.zlabel = zlabel def _plot2D(self): self.g.title(self.title) self.g.xlabel(self.xlabel) self.g.ylabel(self.ylabel) if len(self.data2) == 0: return False self.g.title(self.title) self.g.xlabel(self.xlabel) self.g.ylabel(self.ylabel) self.g.plot(self.data2[0]) for d in self.data2[1:]: self.g.replot(d) return True def plot2DtoScreen(self): if not self._plot2D(): return None raw_input('Please press return to continue...\n') def plot2DtoFile(self, fileName): """ @type fileName: string """ self.g('set term post eps') self.g('set output \'%s\'' % fileName) if not self._plot2D(): return None self.g.hardcopy(fileName, enhanced=1, color=1) if self.verbose: print ('\n******** Saved plot to postscript file %s ********\n' % fileName) def _plot3d(self): if len(self.data3) == 0: return False self.g.title(self.title) self.g.xlabel(self.xlabel) self.g.ylabel(self.ylabel) self.g('set zlabel \"%s\"' % self.zlabel) self.g.plot([self.data3[0]]) for d in self.data3[1:]: self.g.replot(d) return True def plot3DtoScreen(self): if not self._plot3D(): return None raw_input('Please press return to continue...\n') def plot3DtoFile(self,fileName): """ @type fileName: string """ self.g('set term post eps') self.g('set output \'%s\'' % fileName) if not self._plot3d(): return None self.g.hardcopy(fileName, enhanced=1, color=1) if self.verbose: print ('\n******** Saved plot to postscript file %s ********\n' % fileName)
alphanfft = [] for i in range(N): alphanfft.append(alphan[i][1]) psdnraw = fft(alphanfft) psdnges = [] for i in range(len(psdnraw) / 2 + 1): psdnges.append([ (float(i) / (float(N) * timeres)), 2. * abs(psdnraw[i].imag) / N + 2. * abs(psdnraw[i].real) / N ]) if (bin == 0): psdngessum = psdnges if (bin != 0): for i in range(len(psdngessum)): psdngessum[i][1] += psdnges[i][1] plotpsdngessum = Data(psdngessum) plotpsdngessum.set_option_colonsep("with", "lines") gp = Gnuplot() gp("set title '%f , gap = %i'" % (doy, gap)) gp("set logscale x") gp("set logscale y") gp("set yrange[1e-5:0.1]") gp("set xrange[0.001:1.]") gp.plot(plotpsdngessum) gp.hardcopy("%f_%is_%i_%i.ps" % (doy, int(timeres), N, binning), color=True, fontsize=18) del gp
# Often we need to take the factorials of small numbers over and over; # the cached values make this much faster. fact_cache = [1,1,2,6,24,120,720,5040] def fact(n): if n < len(fact_cache): return fact_cache[n] return n*fact(n-1) def stirling(n): return sqrt(2*pi*n)*pow(n/e,n) def plot_fact(n=6): from Gnuplot import Gnuplot,Data f = [] s = [] for i in range(n): f.append(fact(i)) s.append(stirling(i)) steps = range(len(s)) d1 = Data(steps,f,title='Factorial',with='lines') d2 = Data(steps,s,title='Stirling',with='lines') g = Gnuplot() g.plot(d1,d2) raw_input('Press any key...') return if __name__ == '__main__': plot_fact()
#for i in range(len(he1.time)): # summ=0. # for val in he1.countspec[i]: # summ+=val[1] # he1ts.append([he1.time[i],summ]) #h1ts=[] #for i in range(len(h1.time)): # summ=0. # for val in h1.countspec[i]: # if (val[0]<1300.): # summ+=val[1] # h1ts.append([h1.time[i],summ]) #sumts=[] #for i in range(len(o1ts)): # sumts.append([o1ts[i][0],o1ts[i][1]]) gp = Gnuplot() #gp("set xrange [1:365.]") #gp.plot(o1ts,c1ts,c1ts,ne1ts,si1ts,vel) #gp.plot(vel,sumts,sumts) #gp.plot(o12ts,o13ts,o14ts,o15ts,o16ts,o17ts,o18ts) #gp.hardcopy("o1p1h2007.ps",color="true") #gp.plot(pwhist) gp2 = Gnuplot() gp2.plot(o11ts, o12ts, o13ts, o14ts, o15ts, o16ts, o17ts, o18ts) #gp2("set xrange [1:365.]") #gp2.plot(dens)
for i, val in enumerate(k): dcr[step, i] = float(val) print dcr[step] for i in range(127): s = datain.readline() step, tof = nonzero(dcr) dcrcounts = dcr[step, tof] save = zeros([3, len(step)]) save[0] = step save[1] = tof save[2] = dcrcounts savetxt(dataout, save, fmt='%.1f') """ for i in range(len): for val in dcr[step]: dataout.write("%f "%(val)) dataout.write("\n") """ dataout.close() datain.close() return dcr dcr = extractdcr("axlv2_et_slices_2003_018_23.52.56_2003_019_00.04.56.dat") gp = Gnuplot() gp("set pm3d map corners2color c1") gp("set cbrange[0.1:%f]" % (amax(dcr))) gp("set log cb") gp.splot(GridData(dcr))
#!/usr/bin/python from numpy import float from Gnuplot import Gnuplot from scipy import zeros import os gp = Gnuplot() gp("f(x)=x") gp("set term postscript enhanced color") gp("set output 'testmulti.ps'") gp("unset key") gp("set grid") gp("set xtics nomirror") gp("set multiplot") gp("set size 0.916,1.001") gp("set origin 0.083,0.001") gp("set xlabel 0,0.2") gp("set xlabel 'Time in doy'") gp("unset ytics") gp("set yrange [-5:-4]") gp("plot sin(x)") gp("set ytics") gp("set autoscale") gp("set xrange[1:1e11]") gp("set key box") gp("unset xtics") gp("unset xlabel") gp("set size 1,0.285") gp("set origin 0,0.045") gp("set lmargin 10") gp("set logscale y")
from scipy import zeros, dot from numpy import float from Gnuplot import Gnuplot, GridData from math import sin,cos,tan,asin,acos,atan,exp,pi from os import popen2 from sys import stdin import random from scipy.integrate import quad from Gnuplot.func_ext import * from libacepy.frange import frange import random Float=float matrixmultiply=dot gp=Gnuplot() data=zeros([128,512],Float) data2=zeros([128,512],Float) data3=zeros([128,512],Float) year=2001 v_int=345 for year in range(2001,2008): for v_int in range(345,850,10): for i in range(60): path1="/data/wimmer/mu/jahresdaten/"+str(year)+"_data/step_files/"+str(v_int)+"_he/step_"+str(i) path2="/data/wimmer/mu/jahresdaten/"+str(year)+"_data/step_files/"+str(v_int)+"_he/cme_step_"+str(i) path3="/data/wimmer/mu/jahresdaten/"+str(year)+"_data/step_files/"+str(v_int)+"_he/step_"+str(i)+"_o_cme" data=zeros([128,512],Float) data2=zeros([128,512],Float) data3=zeros([128,512],Float) print year, v_int, i
def __init__(self, data_dic): print data_dic try: self.port = int(data_dic["port"]) except: raise MissingInformation("port") try: self.ip = data_dic["ip"] except: raise MissingInformation("ip") self.register_list = data_dic["reg"] self.bof_path = data_dic["bof_path"] self.bitstream = str(data_dic["name"] + ".bof") self.brams_info = data_dic["bram"] self.program = data_dic["progdev"] self.plot_brams = [] self.store_drams = [] for cont in range(len(self.brams_info)): self.brams_info[cont]["prev_acc"] = 0 for cont in range(len(self.brams_info)): aplot = lambda x: x if self.brams_info[cont]["plot"]: aplot = Gnuplot(debug=1) aplot.clear() aplot("set style data linespoints") aplot.ylabel("Power AU (dB)") aplot("set xrange [-50:2098]") aplot("set yrange [0:100]") aplot("set ytics 10") aplot("set xtics 256") aplot("set grid y") aplot("set grid x") self.brams_info[cont]["plot_"] = aplot class a: def close(self): pass def writerow(self, x): pass astore = (a(), a()) if self.brams_info[cont]["store"]: ts = time.time() time_stamp = datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") print self.brams_info[cont].keys() file_name = ( self.bof_path[: -len(".bof")] + "-" + self.brams_info[cont]["array_id"] + "-" + time_stamp + ".csv" ) file = open(file_name, "w") csv_writer = csv.writer(file, delimiter=",") astore = (csv_writer, file) self.brams_info[cont]["store_"] = astore self.fpga = None self.last_acc_count = {} self.handler = corr.log_handlers.DebugLogHandler() self.logger = logging.getLogger(self.ip) self.logger.addHandler(self.handler) self.logger.setLevel(10)