def plotVectorField2d(dataBase, fieldList, plotGhosts=False, vectorMultiplier=1.0, colorNodeLists=False, colorDomains=False, title=""): assert colorNodeLists + colorDomains <= 1 # Gather the node positions and vectors across all domains. # Loop over all the NodeLists. localNumNodes = [] xNodes = [] yNodes = [] vxNodes = [] vyNodes = [] for i in xrange(dataBase.numNodeLists): nodeList = dataBase.nodeLists()[i] assert i < fieldList.numFields vectorField = fieldList[i] if plotGhosts: n = nodeList.numNodes else: n = nodeList.numInternalNodes localNumNodes.append(n) xNodes += numpy.array( map(lambda x: x.x, list(nodeList.positions())[:n])) yNodes += numpy.array( map(lambda x: x.y, list(nodeList.positions())[:n])) vxNodes += numpy.array(map(lambda x: x.x, list(vectorField)[:n])) * vectorMultiplier vyNodes += numpy.array(map(lambda x: x.y, list(vectorField)[:n])) * vectorMultiplier assert len(xNodes) == len(yNodes) == len(vxNodes) == len(vyNodes) numDomainNodes = [len(xNodes)] numNodesPerDomain = mpi.gather(numDomainNodes) globalNumNodes = mpi.gather(localNumNodes) globalXNodes = mpi.gather(xNodes) globalYNodes = mpi.gather(yNodes) globalVxNodes = mpi.gather(vxNodes) globalVyNodes = mpi.gather(vyNodes) if mpi.rank == 0: plot = generateNewGnuPlot() plot("set size square") plot.title = title if colorDomains: cumulativeN = 0 for domain in xrange(len(numNodesPerDomain)): n = numNodesPerDomain[domain] x = numpy.array(globalXNodes[cumulativeN:cumulativeN + n]) y = numpy.array(globalYNodes[cumulativeN:cumulativeN + n]) vx = numpy.array(globalVxNodes[cumulativeN:cumulativeN + n]) vy = numpy.array(globalVyNodes[cumulativeN:cumulativeN + n]) cumulativeN += n ## plot("set linestyle %i lt %i pt %i" % (domain + 1, ## domain + 1, ## domain + 1)) data = Gnuplot.Data(x, y, vx, vy, with_="vector ls %i" % (domain + 1), inline=True) plot.replot(data) SpheralGnuPlotCache.append(data) elif colorNodeLists: cumulativeN = 0 for i in xrange(len(globalNumNodes)): n = globalNumNodes[i] if n > 0: iNodeList = i % dataBase.numNodeLists x = numpy.array(globalXNodes[cumulativeN:cumulativeN + n]) y = numpy.array(globalYNodes[cumulativeN:cumulativeN + n]) vx = numpy.array(globalVxNodes[cumulativeN:cumulativeN + n]) vy = numpy.array(globalVyNodes[cumulativeN:cumulativeN + n]) cumulativeN += n ## plot("set linestyle %i lt %i pt %i" % (iNodeList + 1, ## iNodeList + 1, ## iNodeList + 1)) data = Gnuplot.Data(x, y, vx, vy, with_="vector ls %i" % (iNodeList + 1), inline=True) plot.replot(data) SpheralGnuPlotCache.append(data) else: x = numpy.array(globalXNodes) y = numpy.array(globalYNodes) vx = numpy.array(globalVxNodes) vy = numpy.array(globalVyNodes) data = Gnuplot.Data(x, y, vx, vy, with_="vector", inline=True) plot.replot(data) SpheralGnuPlotCache.append(data) return plot else: SpheralGnuPlotCache.append(data)
#------------------------------------------------------------------------------- # Plot the result with strength. #------------------------------------------------------------------------------- dataDir = "dumps-RotatingSteelRod-2d-%ix%i-nph=%4.2f" % (nx, ny, nPerh) restartDir = dataDir + "/restarts" restartBaseName = restartDir + "/RotatingSteelRod-%ix%i" % (nx, ny) restoreCycle = findLastRestart(restartBaseName) control.setRestartBaseName(restartBaseName) control.loadRestartFile(restoreCycle) Lz0 = [x.z for x in control.conserve.amomHistory] import Gnuplot from SpheralGnuPlotUtilities import generateNewGnuPlot d0 = Gnuplot.Data(control.conserve.timeHistory, Lz0, title = "With strength", with = "linespoints", inline = True) p = generateNewGnuPlot() p.plot(d0) ## import pylab ## if mpi.rank == 0: ## pylab.plot(control.conserve.timeHistory, Lz0, ## "b-", ## label = "With strength") #------------------------------------------------------------------------------- # Plot the result without strength. #------------------------------------------------------------------------------- dataDir = "dumps-RotatingSteelRod-2d-%ix%i-nostrength" % (nx, ny)
iter = -1 print "File, nbins:", fname, nbins of = NetCDFFile(fname) print "Dimensions:", of.dimensions dmin = of.variables['dm_in'][iter, 0, :] print len(dmin) hin = Histo(dmin[:], nbins) print hin.min, hin.max dmout = of.variables['dm_out'][iter, 0, :] print len(dmout) hout = Histo(dmout[:], nbins) print hout.min, hout.max g = Gnuplot.Gnuplot(debug=1) g('set data style linespoints') # give gnuplot an arbitrary command d1 = Gnuplot.Data(hin.bins, hin.h) d2 = Gnuplot.Data(hout.bins, hout.h) g.plot(d1, d2) raw_input('Please press return to continue...\n') #p=biggles.FramedPlot(title=fname) #p.add(biggles.Curve(h.bins,h.h)) #p.show() #p.save_as_img( "gif", 400, 400, fname+".temp.gif" )
if not steps is None: control.step(steps) else: control.advance(goalTime) control.dropRestartFile() #------------------------------------------------------------------------------- # Plot the final flaw distribution, if requested. #------------------------------------------------------------------------------- if plotFlaws and DamageModelConstructor is StochasticWeibullTensorDamageModel2d: from SpheralGnuPlotUtilities import generateNewGnuPlot import Gnuplot flaws = [x for x in damageModel.sortedFlaws()] f = [i / volume for i in xrange(len(flaws))] fans = [kWeibull * x**mWeibull for x in flaws] d = Gnuplot.Data(flaws, f, title="Simulation", inline=True) dans = Gnuplot.Data(flaws, fans, with_="lines", title="Analytic", inline=True) p = generateNewGnuPlot() p("set logscale xy") p("set key top left") p.plot(d) p.replot(dans) #------------------------------------------------------------------------------- # Compute the fragment properties and spit them out to a file. #------------------------------------------------------------------------------- ## import pickle
def graphique(FORMAT, L_F, res_exp, reponses, iter, UL_out, pilote, fichier=None, INFO=0): if iter: txt_iter = 'Iteration : ' + str(iter) else: txt_iter = '' # Le try/except est la pour eviter de planter betement dans un trace de # courbes (DISPLAY non defini, etc...) try: if FORMAT == 'XMGRACE': for i in range(len(L_F)): _tmp = [] courbe1 = res_exp[i] _tmp.append({'ABSCISSE': courbe1[:, 0].tolist(), 'ORDONNEE': courbe1[ :, 1].tolist(), 'COULEUR': 1, 'LEGENDE': 'Expérience'}) courbe2 = L_F[i] _tmp.append({'ABSCISSE': courbe2[:, 0].tolist(), 'ORDONNEE': courbe2[ :, 1].tolist(), 'COULEUR': 2, 'LEGENDE': 'Calcul'}) motscle2 = {'COURBE': _tmp} motscle2['PILOTE'] = pilote IMPR_FONCTION(FORMAT='XMGRACE', UNITE=int(UL_out), TITRE='Courbe : ' + reponses[i][0], SOUS_TITRE=txt_iter, LEGENDE_X=reponses[i][1], LEGENDE_Y=reponses[i][2], **motscle2 ) dic = {'': '', 'POSTSCRIPT': '.ps', 'EPS': '.eps', 'MIF': '.mif', 'SVG': '.svg', 'PNM': '.pnm', 'PNG': '.png', 'JPEG': '.jpg', 'PDF': '.pdf', 'INTERACTIF': '.agr' } ext = dic[pilote] if ext != '': os.system('mv ./fort.%s ./REPE_OUT/courbes_%s_iter_%s%s' % (str(UL_out), reponses[i][0], str(iter), ext)) elif FORMAT == 'GNUPLOT': if fichier: if INFO >= 2: UTMESS('I', 'RECAL0_41', valk=fichier) # On efface les anciens graphes liste = glob.glob(fichier + '*.ps') for fic in liste: try: os.remove(fic) except: pass graphe = [] impr = Gnuplot.Gnuplot() Gnuplot.GnuplotOpts.prefer_inline_data = 1 impr('set data style linespoints') impr('set grid') impr('set pointsize 1.') impr('set terminal postscript color') impr('set output "fort.' + str(UL_out) + '"') for i in range(len(L_F)): graphe.append(Gnuplot.Gnuplot(persist=0)) graphe[i]('set data style linespoints') graphe[i]('set grid') graphe[i]('set pointsize 1.') graphe[i].xlabel(reponses[i][1]) graphe[i].ylabel(reponses[i][2]) graphe[i].title(reponses[i][0] + ' ' + txt_iter) graphe[i].plot(Gnuplot.Data(L_F[i], title='Calcul'), Gnuplot.Data(res_exp[i], title='Experimental')) if pilote == 'INTERACTIF': graphe[i]('pause 5') else: if fichier: if INFO >= 2: UTMESS( 'I', 'RECAL0_41', valk=fichier + '_' + str(i) + '.ps') graphe[i].hardcopy( fichier + '_' + str(i) + '.ps', enhanced=1, color=1) impr.xlabel(reponses[i][1]) impr.ylabel(reponses[i][2]) impr.title(reponses[i][0] + ' Iteration ' + str(iter)) impr.plot(Gnuplot.Data(L_F[i], title='Calcul'), Gnuplot.Data( res_exp[i], title='Experimental')) except Exception, err: UTMESS('A', 'RECAL0_42', valk=str(err))
from numpy import * import Gnuplot, math import time def f(x): return (11*x - 6)*(2*x - 3) gp = Gnuplot.Gnuplot(debug=0) x = arange(10, dtype='float_') y = x**2 # save plots for displaying later plot1 = Gnuplot.Data(x, y, title='squares', with_='points 3 3') plot2 = Gnuplot.Func('x**2', title='calculated by gnuplot') # Plot gp.title('The function x**2') gp.xlabel('x') gp.ylabel('x**2') min = -1000 max = +1000 # keep replotting graph to animate for i in range(min, max): x = i y = f(x) plot1 = Gnuplot.Data([min,x,max], [0,y,f(max)], with_='points 1 3')
def make_audio_plot(time, data, maxpoints=10000): """ create gnuplot plot from an audio file """ import Gnuplot, Gnuplot.funcutils x, y = downsample_audio(time, data, maxpoints=maxpoints) return Gnuplot.Data(x, y, with_='lines')
legend = string.split(lines[0][:-1], "\t") data = map(lambda x: map(string.atof, string.split(x[:-1], "\t")), lines[1:]) g.clear() if param_title: g.title(param_title) g.xlabel(legend[0]) for x in range(1, len(legend)): g.replot( Gnuplot.Data(data, cols=(0, x), xwith=param_with, title=legend[x])) if param_fit: g.replot(Fit(data, cols=(0, x))) if param_function: for f in param_function: g.replot(Gnuplot.Func(f)) g.refresh() if param_hardcopy: g.hardcopy(param_hardcopy, terminal=param_terminal) ## g.replot( Gnuplot.File( fn1,
from numpy import * import random import array import Gnuplot, Gnuplot.funcutils a = array.array('i', []) n = int(input("Enter the number of persons:")) #no of persons t = int(input("Enter the number of items:")) #no of items for i in range(n): x = random.randint(100, 1000) a.append(x) a = sorted(a) for i in range(n): print(a[i]) print("payment is :") print(a[n - t]) g = Gnuplot.Gnuplot(debug=1) g.title('2nd Price Auction') x = arange(a[n - t], dtype='float_') y = n d = Gnuplot.Data(x, y, title='calculated by python', with_='points 3 3')
import Gnuplot, Numeric f = file('spline_slow_vareps.txt') max_slow_inf = [] eps = [] g = Gnuplot.Gnuplot(persist=1) g._clear_queue() g('set logscale xy') g.xlabel('epsilon') g.ylabel('({/Symbol w}^2-{/Symbol w}_{/Symbol \245}^2)/{/Symbol w}_{/Symbol \245}^2') g.title('Illustration of slow discrete->continuum transition with Appert coords in Guazzotto approach') for k in range(20): try: eps.append(float(f.readline())) max_slow_inf.append(float(f.readline())) if eps[k] == 0: eps[k] = 9.e-7 npts = int(f.readline()) evals = Numeric.zeros(npts,typecode=Numeric.Float) for i in range(npts): evals[i] = float(f.readline()) f.readline() d1 = Gnuplot.Data([eps[k]]*npts,evals,with='points 1') g._add_to_queue([d1]) except: break #print eps,max_slow_inf g.replot(Gnuplot.Data(eps[1:],max_slow_inf[1:],title='max of continuum',with='lines 2')) g.hardcopy('bspline/spline_slow_vareps.eps')
for k in xrange(-npoints, npoints): eta = sqrt((i * deta)**2 + (j * deta)**2 + (k * deta)**2) if eta > 1.0e-5: Wsum += abs(WT.gradValue(eta, 1.0)) Wsum = Wsum**(1.0 / nDim) result = WT.equivalentNodesPerSmoothingScale(Wsum) Wsumarray.append(Wsum) actualnperh.append(nperh) lookupnperh.append(result) # Plot the lookup results. actualdata = Gnuplot.Data(Wsumarray, actualnperh, with_="lines", title="Actual n per h", inline=True) lookupdata = Gnuplot.Data(Wsumarray, lookupnperh, with_="points", title="Lookup n per h", inline=True) nperhdata = Gnuplot.Data(actualnperh, lookupnperh, with_="points", title=None, inline=True) data.extend([actualdata, lookupdata, nperhdata]) plot = generateNewGnuPlot()
#!/usr/bin/env python # # Author: Patrick Hung (patrickh @caltech) # Copyright (c) 1997-2016 California Institute of Technology. # Copyright (c) 2016-2020 The Uncertainty Quantification Foundation. # License: 3-clause BSD. The full license text is available at: # - https://github.com/uqfoundation/mystic/blob/master/LICENSE from mystic.tools import getch import Gnuplot, numpy g = Gnuplot.Gnuplot(debug=1) g.clear() x = numpy.arange(-4, 4, 0.01) y = numpy.cos(x) y2 = numpy.cos(2 * x) kwds = {'with': 'line'} g.plot(Gnuplot.Data(x, y, **kwds)) getch('next: any key') g.plot(Gnuplot.Data(x, y2, **kwds)) getch('any key to quit') # end of file
# asm4: make the whole picture smaller so that the font appears larger. g('set size 0.8,0.8') # Set graph properties if opts.legend: g('set key bottom right') else: g('set nokey') if opts.term: g('set term ' + opts.term) if opts.title: g.title(opts.title) if opts.xlabel: g.xlabel(opts.xlabel) if opts.ylabel: g.ylabel(opts.ylabel) # Generate arguments for the gplot command plotargs = [] for s in range(nsolvs): sname = solvers[s] srats = pprofs.solv_ratios(s) plotargs.append( Gnuplot.Data(srats, ydata, title=sname, inline=0, with_=opts.linestyl)) # Create the plot apply(g.plot, plotargs) # This fixes a Gnuplot bug. (Thanks to Matt Knepley.) g.gnuplot.gnuplot.close()
gp = Gnuplot.Gnuplot() import numpy xpts = numpy.arange(-1.5, 1.5, 0.1) ypts = numpy.arange(-1.5, 1.5, 0.1) gp("set zrange [-3:3]") for bfi, bf in zip(tri.generate_mode_identifiers(), tri.basis_functions()): lines = [] for x in xpts: values = [] for y in ypts: values.append((x, y, bf(numpy.array((x, y))))) lines.append(Gnuplot.Data(values, with_="lines")) for y in xpts: values = [] for x in ypts: values.append((x, y, bf(numpy.array((x, y))))) lines.append(Gnuplot.Data(values, with_="lines")) tri = numpy.array([ (-1, -1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0), ]) lines.append(Gnuplot.Data(tri, with_="lines"))
test = HvEDA(100,FonctionObject01) test.Evaluate() def Generation(gen): print "Starting" for i in range(gen): print "Iteration ",i ," ",len(test.ListNonDominated) test.Evaluate_After() print "Starting" gplot = Gnuplot.Gnuplot() for i in range(10): if (i%5 ==0): print "Iteration ",i ," ",len(test.ListNonDominated) d=Gnuplot.Data(test.ApplyFunctions(test.ListNonDominated)) gplot.plot(d) test.Evaluate_After() #job = [] #job.append(Process(target=Generation, args=(30,))) #job.append(Process(target=Generation, args=(30,))) # #for j in job: # j.start() #for j in job: # j.join()
#g('set ytic 1') g('set style line 1 ps 0.5 lc rgb "#ff0000"') g('set style line 2 ps 0.5 lc rgb "#ff4f00"') g('set style line 3 ps 0.4 lc rgb "#0000ff"') g('set style line 4 ps 0.4 lc rgb "#0099ff"') g('set style line 5 ps 0.4 lc rgb "#00ff00"') g('set style line 6 ps 0.4 lc rgb "#00ff99"') #g('set label "Pure Share Memory" at graph 0.5, 1.035 center font "Arial,11"') g('set logscale y') x = numpy.arange(start=2, stop=24, step=0.5, dtype='float_') y1 = rainfall_intensity_t10(x) # yields another numpy.arange object y2 = rainfall_intensity_t50(x) # ... y3 = rainfall_intensity_t80(x) # ... d1 = Gnuplot.Data(x, y1, title="intensity i (T=10)", with_="lines ls 4") d2 = Gnuplot.Data(x, y2, title="intensity i (T=50)", with_="lines ls 5") d3 = Gnuplot.Data(x, y3, title="intensity i (T=80)", with_="lines ls 6") g("set terminal qt") g.plot(d1, d2, d3) # write pdf data directly to stdout ... raw_input("\nPress return to exit") g.hardcopy(filename='rainfall-intensity.pdf', terminal='pdf') # write last plot to another terminal #g.hardcopy (filename='rainfall-intensity.png', terminal='png') # write last plot to another terminal #g.hardcopy (filename='rainfall-intensity.svg', terminal='svg') # ... del g
from numpy import * import Gnuplot, Gnuplot.funcutils g = Gnuplot.Gnuplot(debug=1) g.title('CDF plot test') # (optional) x = range(1, 1001) x = [float(a) / 1000 for a in x] y1 = random.normal(0, 1, 1000) y1.sort() y2 = random.normal(10, 5, 1000) y2.sort() y3 = random.normal(20, 10, 1000) y3.sort() d1 = Gnuplot.Data(y1, x, title='mean: 0, deviation: 1', with_='lines') d2 = Gnuplot.Data(y2, x, title='mean: 10, deviation: 5', with_='lines') d3 = Gnuplot.Data(y3, x, title='mean: 20, deviation: 10', with_='lines') g.xlabel('distribution') g.ylabel('percentage') g.plot(d1, d2, d3) raw_input('Please press return to exit.\n')
def main(argv): csvfilename = argv[0] print(csvfilename) with open(csvfilename, 'r') as csvfile: #fn = OrderedDict([('die',None),('frequency',None),('voltage',None),('hashrate',None),('hashes',None),('nonces',None), # ('lhw',None),('dhw',None),('chw',None),('temperature',None),('core_voltage',None),('thermal_cutoff',None)]) csvreader = csv.DictReader(csvfile) #, fn) # A straightforward use of gnuplot. The `debug=1' switch is used # in these examples so that the commands that are sent to gnuplot # are also output on stderr. g = Gnuplot.Gnuplot(debug=0) # frequency on the x-axis fmin = 800 fmax = 1050 fstep = 12.5 f = arange(fmin, fmax, fstep) def findex(frq): assert frq >= fmin and frq < fmax return int( (frq - fmin +1) / fstep ) # voltage on the y-axis vmin = 840 vmax = 1100 vstep = 5 v = arange(vmin, vmax, vstep) def vindex(vlt): assert vlt >= vmin and vlt < vmax return (vlt - vmin) / vstep dies = [ {'die':i, 'results':None, 'x':None, 'y':None, 'hashrate':None } for i in range(4)] for i in range(4): die = dies[i] x = f[:,newaxis] y = v[newaxis,:] die['results'] = [] die['x'] = f die['y'] = v die['hashrate'] = (x * y).astype(float) die['hashrate'].fill(nan) die['temperature'] = (x * y).astype(float) die['temperature'].fill(nan) for result in csvreader: # data die = result['die'] = int(result['die']) frq = result['frequency'] = int(result['frequency']) vlt = result['voltage'] = int(result['voltage']) result['core_voltage'] = float(result['core_voltage']) # did the die hit thermal result['thermal_cutoff'] = int(result['thermal_cutoff']) if result['thermal_cutoff'] is not 1: result['temperature'] = float(result['temperature']) else: result['temperature'] = nan # did the die compute enough hashes to compare result['hashes'] = int(result['hashes']) / 10**9 if result['hashes'] > 30000: result['hashrate'] = float(result['hashrate']) / 10**9 result['nonces'] = int(result['nonces']) result['lhw'] = int(result['lhw']) result['dhw'] = int(result['dhw']) result['chw'] = int(result['chw']) else: result['hashes'] = nan result['hashrate'] = nan result['nonces'] = nan result['lhw'] = nan result['dhw'] = nan result['chw'] = nan # fill each die properties die = dies[die] die['results'].append(result) die['hashrate'][findex(frq), vindex(vlt)] = result['hashrate'] die['temperature'][findex(frq), vindex(vlt)] = result['temperature'] # make output try: os.mkdir('{0}'.format(csvfilename[:-4])) except OSError: pass for d in dies: g.title('HashFast HashRate Die {}'.format(d['die'])) g.xlabel('Frequency (MHz)') g.ylabel('Voltage (mV)') g.zlabel('HR (GH/s)') # set gnuplot options g('set parametric') g('set style data pm3d') #g('set hidden') g('set contour base') g('set datafile missing "nan"') #g('set palette rgbformulae 31,-11,32') g('set zrange [80:180]') g('set xtics 25') g('set mxtics 2') g('set grid xtics mxtics ytics ztics') # The `binary=1' option would cause communication with gnuplot to # be in binary format, which is considerably faster and uses less # disk space. (This only works with the splot command due to # limitations of gnuplot.) `binary=1' is the default, but here we # disable binary because older versions of gnuplot don't allow # binary data. Change this to `binary=1' (or omit the binary # option) to get the advantage of binary format. data_hashrate = Gnuplot.GridData(d['hashrate'], d['x'], d['y'], binary=0) data_temperature = Gnuplot.GridData(d['temperature'], d['x'], d['y'], binary=0, with_="pm3d at b") g.splot(data_hashrate, data_temperature) #g('set pm3d at b') #g.splot(Gnuplot.GridData(d['temperature'], d['x'], d['y'], binary=0)) # show the plot to allow reposition #raw_input('Please press return to save plot...\n') # Save what we just plotted as a color postscript file. #g.hardcopy("{0}_die{1}.ps".format(csvfilename[:-4], d['die']), enhanced=1, color=1) g.hardcopy("{0}/{0}_die{1}.eps".format(csvfilename[:-4], d['die']), enhanced=1, color=1, mode='eps') g.hardcopy("{0}/{0}_die{1}.png".format(csvfilename[:-4], d['die']), terminal='png', fontsize='small') print('\n******** Saved plot to file ********\n') for d in dies: g.title('HashFast HashRate Die {}'.format(d['die'])) g.xlabel('Voltage (mV)') g.ylabel('HashRate (GH/s)') # set gnuplot options #g('set parametric') g('set style data lines') #g('set hidden') g('set datafile missing "nan"') g('set yrange [140:190]') g('set key left') g('set mxtics 4') g('set mytics 10') g('set grid xtics mxtics ytics lw 1') frqs = [nan]*len(f) for frq in f: i = findex(frq) frqs[i] = Gnuplot.Data(v, d['hashrate'][i], title='{}MHz'.format(int(frq)))#, with_='') # Plot data alongside the Data PlotItem defined above: g.plot(*frqs) #g('set pm3d at b') #g.splot(Gnuplot.GridData(d['temperature'], d['x'], d['y'], binary=0)) # show the plot to allow reposition #raw_input('Please press return to save plot...\n') # Save what we just plotted as a color postscript file. #g.hardcopy("{0}_die{1}_flat.ps".format(csvfilename[:-4], d['die']), enhanced=1, color=1) g.hardcopy("{0}/{0}_die{1}_flat.eps".format(csvfilename[:-4], d['die']), enhanced=1, color=1, mode='eps') g.hardcopy("{0}/{0}_die{1}_flat.png".format(csvfilename[:-4], d['die']), terminal='png', fontsize='small') print('\n******** Saved plot to file ********\n')
print "Maximum errors (interpolation): SPH = %g, SVPH = %g" % (maxySPHerror, maxySVPHerror) print "Maximum errors (derivatives): SPH = %g, SVPH = %g" % (maxdySPHerror, maxdySVPHerror) #------------------------------------------------------------------------------- # Plot the things. #------------------------------------------------------------------------------- if graphics: from SpheralGnuPlotUtilities import * import Gnuplot # Interpolated values. ansdata = Gnuplot.Data(xans, yans, with_="lines", title="Answer", inline=True) SPHdata = Gnuplot.Data(xans, ySPH, with_="points", title="SPH", inline=True) SVPHdata = Gnuplot.Data(xans, ySVPH, with_="points", title="SVPH", inline=True) errSPHdata = Gnuplot.Data(xans, errySPH, with_="points",
def demo(): """Demonstrate the Gnuplot package.""" # A straightforward use of gnuplot. The `debug=1' switch is used # in these examples so that the commands that are sent to gnuplot # are also output on stderr. g = Gnuplot.Gnuplot(debug=1) g.title('A simple example') # (optional) g('set data style linespoints') # give gnuplot an arbitrary command # Plot a list of (x, y) pairs (tuples or a numpy array would # also be OK): g.plot([[0, 1.1], [1, 5.8], [2, 3.3], [3, 4.2]]) #raw_input('Please press return to continue...\n') g.reset() # Plot one dataset from an array and one via a gnuplot function; # also demonstrate the use of item-specific options: x = arange(10, dtype='float_') y1 = x**2 # Notice how this plotitem is created here but used later? This # is convenient if the same dataset has to be plotted multiple # times. It is also more efficient because the data need only be # written to a temporary file once. d = Gnuplot.Data(x, y1, title='calculated by python', with_='points 3 3') g.title('Data can be computed by python or gnuplot') g.xlabel('x') g.ylabel('x squared') # Plot a function alongside the Data PlotItem defined above: g.plot(Gnuplot.Func('x**2', title='calculated by gnuplot'), d) #raw_input('Please press return to continue...\n') # Save what we just plotted as a color postscript file. # With the enhanced postscript option, it is possible to show `x # squared' with a superscript (plus much, much more; see `help set # term postscript' in the gnuplot docs). If your gnuplot doesn't # support enhanced mode, set `enhanced=0' below. g.ylabel('x^2') # take advantage of enhanced postscript mode g.hardcopy('gp_test.ps', enhanced=1, color=1) #print ('\n******** Saved plot to postscript file "gp_test.ps" ********\n') #raw_input('Please press return to continue...\n') g.reset() # Demonstrate a 3-d plot: # set up x and y values at which the function will be tabulated: x = arange(35) / 2.0 y = arange(30) / 10.0 - 1.5 # Make a 2-d array containing a function of x and y. First create # xm and ym which contain the x and y values in a matrix form that # can be `broadcast' into a matrix of the appropriate shape: xm = x[:, newaxis] ym = y[newaxis, :] m = (sin(xm) + 0.1 * xm) - ym**2 g('set parametric') g('set data style lines') g('set hidden') g('set contour base') g.title('An example of a surface plot') g.xlabel('x') g.ylabel('y') # The `binary=1' option would cause communication with gnuplot to # be in binary format, which is considerably faster and uses less # disk space. (This only works with the splot command due to # limitations of gnuplot.) `binary=1' is the default, but here we # disable binary because older versions of gnuplot don't allow # binary data. Change this to `binary=1' (or omit the binary # option) to get the advantage of binary format. g.splot(Gnuplot.GridData(m, x, y, binary=0)) #raw_input('Please press return to continue...\n') # plot another function, but letting GridFunc tabulate its values # automatically. f could also be a lambda or a global function: def f(x, y): return 1.0 / (1 + 0.01 * x**2 + 0.5 * y**2) g.splot(Gnuplot.funcutils.compute_GridData(x, y, f, binary=0))
control.loadRestartFile(restoreCycle) #------------------------------------------------------------------------------- # Advance to the end time. #------------------------------------------------------------------------------- if not steps is None: control.step(steps) else: control.advance(goalTime) # Plot the final state. x1 = [stuff[1]/AU for stuff in history.sampleHistory] y1 = [stuff[2]/AU for stuff in history.sampleHistory] x2 = [stuff[8]/AU for stuff in history.sampleHistory] y2 = [stuff[9]/AU for stuff in history.sampleHistory] import Gnuplot gdata1 = Gnuplot.Data(x1, y1, with_ = 'linespoints', title = 'Particle 1') gdata2 = Gnuplot.Data(x2, y2, with_ = 'linespoints', title = 'Particle 2') plot = Gnuplot.Gnuplot() plot.plot(gdata1) plot.replot(gdata2) plot('set size square; set xrange [-1.1:1.1]; set yrange [-1.1:1.1]') plot.xlabel = 'x' plot.ylabel = 'y' plot.refresh()
plots = [] for i in xpts: bm = scipy.where(x == i) a = numpy.array(t[bm]).view(numpy.recarray) duplicates = numpy.core.records.find_duplicate(a) for dup in duplicates: dup_bm = scipy.where((x == i) & (t == dup))[0] x = numpy.delete(x, dup_bm[-1]) t = numpy.delete(t, dup_bm[-1]) y = numpy.delete(y, dup_bm[-1]) bm = scipy.where(x == i) #plots.append(Gnuplot.Data(y[bm], with_='lines')) #dosage.append(scipy.integrate.simps(y[bm])) plots.append(Gnuplot.Data(t[bm], y[bm], with_='lines')) dosage.append(scipy.integrate.simps(y[bm], x=t[bm])) sig.append(numpy.std(y[bm])) means.append(numpy.mean(y[bm])) plt.plot(plots[-1]) dosage = numpy.array(dosage) sig = numpy.array(sig) means = numpy.array(means) out = open('./plots/' + of_name, 'w') out_dosage = dosage / max(dosage) for dat in zip(xpts, out_dosage): out.write(str(dat[0]) + ' ' + str(dat[1]) + '\n') out.close()
while run == True: time.sleep(3) client.CChaltcpu() rssi = [] mrssi = [] d0 = [] d1 = [] dn = 0 dm = 0 round=round+1 #g.show() for entry in range(0,maxchan): adr=chanstart+entry*8; rssi.append(client.CCpeekdatabyte(adr+6)); mrssi.append(client.CCpeekdatabyte(adr+7)); #print "%03i %3.3f %03i" % (round,freqs[entry],rssi); d0.append((freqs,rssi)) d1.append((freqs,mrssi)) dn = plt.Data(d0) dm = plt.Data(d1) g.title(title+str(round)) #g.plot(dn) g.plot(dn,dm) if round != 1: g.refresh() client.CCreleasecpu();
def __init__(self, eigenfile, namefile=None, debug=0, dimensions=2, title=None, datatitle=None, showpoints=1, showlabels=1, components=[0, 1, 2]): self.gp = Gnuplot.Gnuplot(debug=debug) self.dimensions = dimensions self.showpoints = showpoints self.showlabels = showlabels self.components = components # read in eigenvalues, names efp = open(eigenfile, "r") if namefile: nfp = open(namefile, "r") else: nfp = None eline = efp.readline() if nfp: nline = nfp.readline() else: nline = eline.split()[-1] dataset = [] while eline: eline = eline.strip() if nfp: label = nline.strip() else: label = eline.split()[-1] data = eline.split(" ") if dimensions == 2: if label and showlabels: self.gp('set label "%s" at %f,%f' % (label, float(data[self.components[0]]), float(data[self.components[1]]))) dataset.append((float(data[self.components[0]]), float(data[self.components[1]]))) elif dimensions == 3: if label and showlabels: self.gp('set label "%s" at %f,%f,%f' % (label, float(data[self.components[0]]), float(data[self.components[1]]), float(data[self.components[2]]))) dataset.append((float(data[self.components[0]]), float(data[self.components[1]]), float(data[self.components[2]]))) else: raise Exception("DimensionError", "cannot handle dimensions of %d" % dimensions) eline = efp.readline() if nfp: nline = nfp.readline() efp.close() if nfp: nfp.close() self.data = Gnuplot.Data(dataset) if showpoints: self.gp('set data style points') else: self.gp('set data style dots') self.gp.title(title) self.data.set_option(title=datatitle)
if 'rwm' in sys.argv: minr = 0 maxr = .1 rwm_inds = Numeric.nonzero((unst.real>minr)*(unst.real<maxr)) evec_num = EV.unst_inds[rwm_inds[unst_ind]] #print evec_num #print EV.evals[evec_num] (y,yl) = EV.get_evec1(coord,evec_num,x) ereal = ((EV.evals[evec_num])).real eimag = ((EV.evals[evec_num])).imag evr.append(ereal) evi.append(eimag) ylabels.append( '%s=%g'%(var_key,EV.data[var_key])) if var_key=='ngrid': ylabels[-1] = 'N_{eff}=%g'%(int(EV.data['a']/min(EV.grid[1:]-EV.grid[:-1]))+1) dr = Gnuplot.Data(x,y.real,title='Real',with='lines 3') di = Gnuplot.Data(x,y.imag,title='Imag',with='lines 2') inds = Numeric.nonzero((EV.grid>=minx)*(EV.grid<=maxx)) dg = Gnuplot.Data(Numeric.take(EV.grid,inds),0*inds,with='points 1',title='Grid') d.append([dg,dr,di]) if EV.data['vcyl'] and eimag!=0: if EV.data['tw'] <= 0 and abs(eimag)>0: evec_num = int(round(evec_num+eimag/abs(eimag))) else: EV.imag = True del EV.sevecs (y1,yl) = EV.get_evec1(coord,evec_num,x) acoef = EV.get_EVrot(minr=minr,maxr=maxr) y2 = (acoef*y+1j*acoef*y1).real y3 = (acoef*y+1j*acoef*y1).imag #print acoef, y[-1],y1[-1],y2[-1],y3[-1]
def iterate(self, params, rep, n): if params['name'].startswith("content"): item_score = dict.fromkeys(self.user.pkg_profile, 1) # Prepare partition sample = {} for i in range(self.sample_size): key = random.choice(item_score.keys()) sample[key] = item_score.pop(key) # Get full recommendation user = User(item_score) recommendation = self.rec.get_recommendation(user, self.repo_size) # Write recall log recall_file = "results/content/recall/%s-%s-%.2f-%d" % \ (params['strategy'], params[ 'weight'], params['sample'], n) output = open(recall_file, 'w') output.write("# weight=%s\n" % params['weight']) output.write("# strategy=%s\n" % params['strategy']) output.write("# sample=%f\n" % params['sample']) output.write("\n%d %d %d\n" % (self.repo_size, len(item_score), self.sample_size)) notfound = [] ranks = [] for pkg in sample.keys(): if pkg in recommendation.ranking: ranks.append(recommendation.ranking.index(pkg)) else: notfound.append(pkg) for r in sorted(ranks): output.write(str(r) + "\n") if notfound: output.write("Out of recommendation:\n") for pkg in notfound: output.write(pkg + "\n") output.close() # Plot metrics summary accuracy = [] precision = [] recall = [] f1 = [] g = Gnuplot.Gnuplot() g('set style data lines') g.xlabel('Recommendation size') for size in range(1, len(recommendation.ranking) + 1, 100): predicted = RecommendationResult( dict.fromkeys(recommendation.ranking[:size], 1)) real = RecommendationResult(sample) evaluation = Evaluation(predicted, real, self.repo_size) accuracy.append([size, evaluation.run(Accuracy())]) precision.append([size, evaluation.run(Precision())]) recall.append([size, evaluation.run(Recall())]) f1.append([size, evaluation.run(F1())]) g.plot(Gnuplot.Data(accuracy, title="Accuracy"), Gnuplot.Data(precision, title="Precision"), Gnuplot.Data(recall, title="Recall"), Gnuplot.Data(f1, title="F1")) g.hardcopy(recall_file + "-plot.ps", enhanced=1, color=1) # Iteration log result = {'iteration': n, 'weight': params['weight'], 'strategy': params['strategy'], 'accuracy': accuracy[20], 'precision': precision[20], 'recall:': recall[20], 'f1': f1[20]} return result
$NetBSD$ * After 2.6, with is reserved and must not be used as variable. --- python/aubio/task/notes.py.orig 2006-07-26 23:27:19.000000000 +0000 +++ python/aubio/task/notes.py @@ -95,15 +95,15 @@ class tasknotes(task): import numarray import Gnuplot - oplots.append(Gnuplot.Data(now,freq,with='lines', + oplots.append(Gnuplot.Data(now,freq,with_='lines', title=self.params.pitchmode)) - oplots.append(Gnuplot.Data(now,ifreq,with='lines', + oplots.append(Gnuplot.Data(now,ifreq,with_='lines', title=self.params.pitchmode)) temponsets = [] for i in onset: temponsets.append(i*1000) - oplots.append(Gnuplot.Data(now,temponsets,with='impulses', + oplots.append(Gnuplot.Data(now,temponsets,with_='impulses', title=self.params.pitchmode)) def plotplot(self,wplot,oplots,outplot=None,multiplot = 0): @@ -117,10 +117,10 @@ class tasknotes(task): # check if ground truth exists #timet,pitcht = self.gettruth() #if timet and pitcht: - # oplots = [Gnuplot.Data(timet,pitcht,with='lines', + # oplots = [Gnuplot.Data(timet,pitcht,with_='lines',
g('set linetype 1 lc rgb "black"') # this works for black and white g('set style data line') g('set surface') g('unset key') g('unset contour') #g('set dgrid3d 80,80,30') g('set dgrid3d 80,80,30') g('set xlabel "metres WE"') g('set ylabel "metres NS"') #g('set label "signal intensity" at -100,0,100') g('set view 60,20') g.title("artlab 13102019 cosmic rays") g('set term png size 14043,9933') # A0 #g('set term png size 1024,768') # example g('set term png size 3508,2480' ) # 2480 pixels x 3508 pixels (print resolution) a4 #g('set style lines 1 linetype black') g('set output "artlabmuon13102019_cosmicA4.png"') #g.splot(Gnuplot.Data(newy, using=(1,2,3), with='lines'),Gnuplot.Data(newy, using=(1,2,4), with='lines')) #g.splot(Gnuplot.Data(newy, using=(1,2,3)),Gnuplot.Data(newy, using=(1,2,4))) g.splot(Gnuplot.Data(newy, using=(1, 2, 4))) #g.splot(Gnuplot.Data(newy, using=(1,2,3))) #print newy # how to find LONG. LAT of max and min entropy????
break m_Omega.append(m*math.sqrt(2/rho0)/ar*Bt0[k]) npts = int(f.readline()) evalsr = Numeric.zeros(npts,typecode=Numeric.Float) evalsi = Numeric.zeros(npts,typecode=Numeric.Float) for i in range(npts): evalsr[i] = float(f.readline()) for i in range(npts): evalsi[i] = float(f.readline()) f.readline() inds = Numeric.nonzero(evalsi>1) if len(inds)>0: maxval = max(max(Numeric.take(evalsr,inds)),maxval) minval = min(min(Numeric.take(evalsr,inds)),minval) dr = Gnuplot.Data([Bt0[k]]*npts,evalsr,with='points 1') di = Gnuplot.Data([Bt0[k]]*npts,evalsi,with='points 1') dri = Gnuplot.Data(evalsr,evalsi+k,with='points',title='Bt0 = %g'%(Bt0[k])) g._add_to_queue([dr]) g1._add_to_queue([di]) g2._add_to_queue([dri]) g.replot(Gnuplot.Data(Bt0,m_Omega,title='Doppler shift (m*{/Symbol W})',with='lines 2')) g.hardcopy('bspline/spline_var_Bt0_real.eps',size=(1,.50)) g1.refresh() g1.hardcopy('bspline/spline_var_Bt0_imag.eps',size=(1,.50)) g2('set xrange [%g:%g]'%(minval/10.,maxval*10.)) g2('set logscale x') g2.title('{/Symbol w} in complex plane with k=%g'%(kz)) g2.refresh() g2.hardcopy('bspline/spline_var_Bt0_complex.eps')
def plotNodePositions2d(thingy, xFunction="%s.x", yFunction="%s.y", plotGhosts=False, colorNodeLists=True, colorDomains=False, title="", style="points", persist=None): assert colorNodeLists + colorDomains <= 1 if isinstance(thingy, DataBase2d): nodeLists = thingy.nodeLists() else: nodeLists = thingy # Gather the node positions across all domains. # Loop over all the NodeLists. xNodes = [] yNodes = [] for nodeList in nodeLists: if plotGhosts: pos = nodeList.positions().allValues() else: pos = nodeList.positions().internalValues() xNodes.append([eval(xFunction % "x") for x in pos]) yNodes.append([eval(yFunction % "x") for x in pos]) assert len(xNodes) == len(nodeLists) assert len(xNodes) == len(yNodes) globalXNodes = mpi.gather(xNodes) globalYNodes = mpi.gather(yNodes) if mpi.rank == 0: assert len(globalXNodes) == mpi.procs assert len(globalYNodes) == mpi.procs xlist, ylist = [], [] if colorDomains: for xDomain, yDomain in zip(globalXNodes, globalYNodes): assert len(xDomain) == len(nodeLists) assert len(yDomain) == len(nodeLists) xlist.append([]) ylist.append([]) for xx in xDomain: xlist[-1].extend(xx) for yy in yDomain: ylist[-1].extend(yy) assert len(xlist) == mpi.procs assert len(ylist) == mpi.procs elif colorNodeLists: for i in xrange(len(nodeLists)): xlist.append([]) ylist.append([]) for xDomain, yDomain in zip(globalXNodes, globalYNodes): assert len(xDomain) == len(nodeLists) assert len(yDomain) == len(nodeLists) for i in xrange(len(nodeLists)): xlist[i].extend(xDomain[i]) ylist[i].extend(yDomain[i]) assert len(xlist) == len(nodeLists) assert len(ylist) == len(nodeLists) else: xlist, ylist = [[]], [[]] for xDomain, yDomain in zip(globalXNodes, globalYNodes): print len(xDomain), len(nodeLists) assert len(xDomain) == len(nodeLists) assert len(yDomain) == len(nodeLists) for i in xrange(len(nodeLists)): xlist[0].extend(xDomain[i]) ylist[0].extend(yDomain[i]) plot = generateNewGnuPlot(persist=persist) plot("set size square") plot.title = title assert len(xlist) == len(ylist) for x, y in zip(xlist, ylist): data = Gnuplot.Data(x, y, with_=style, inline=True) plot.replot(data) SpheralGnuPlotCache.append(data) return plot else: return fakeGnuplot()