def stats_gnuplot(tm, num_pods, num_tors_per_pod): num_tors = num_pods * num_tors_per_pod idx = 0 pod_tr = {} sid = 0 for spod in xrange(num_pods): for stor in xrange(num_tors_per_pod): sid += 1 did = 0 for dpod in xrange(num_pods): for dtor in xrange(num_tors_per_pod): did += 1 key = (sid, did) if key not in tm: continue bw = tm[key] idx += 1 key = (spod, dpod) if spod == dpod: key = (0, 0) if key not in pod_tr: pod_tr[key] = [] pod_tr[key].append(bw) data = sorted(pod_tr[(0, 0)]) dlen = len(data) data_max = data[-1] y = map(lambda x: (float(x) / dlen), xrange(dlen)) x = data g = Gnuplot.Gnuplot(debug=0) g('set terminal png') g('set output "test.png"') for i in range(1, 9): dm = data_max * i / 8 print dm g("set arrow from %d,0 to %d,1 nohead lc rgb 'red'" % (dm, dm)) g.plot(Gnuplot.Data(zip(x, y))) exit(1)
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 style data 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]]) 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) 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') 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 style data 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)) 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)) input('Please press return to continue...\n')
def mainFollow(self, x): """ Main following algorithm [Nesterov, p. 202] Args: x (Matrix): good approximation of the analytic center, used as the starting point of the algorithm Returns: Matrix: found optimal solution of the problem """ if self.drawPlot: x0All = [x[0, 0]] x1All = [x[1, 0]] self.xMF = x # Main path-following scheme [Nesterov, p. 202] self.logStdout.info('\nMAIN PATH-FOLLOWING') # initialization of the iteration process t = 0 k = 0 # print the input condition to verify that is satisfied if self.logStdout.isEnabledFor(logging.INFO): Fd, Fdd, _ = Utils.gradientHessian(self.AAll, x) self.logStdout.info('Input condition = ' + str(Utils.LocalNormA(Fd, Fdd))) while True: k += 1 if self.logStdout.isEnabledFor(logging.INFO): self.logStdout.info('\nk = ' + str(k)) # gradient and hessian Fd, Fdd, A = Utils.gradientHessian(self.AAll, x) # iteration step t = t + self.gamma / Utils.LocalNormA(self.c, Fdd) x = x - solve(Fdd, (t * self.c + Fd)) if self.drawPlot: x0All.append(x[0, 0]) x1All.append(x[1, 0]) self.xMF = hstack((self.xMF, x)) if self.logStdout.isEnabledFor(logging.INFO): self.logStdout.info('t = ' + str(t)) self.logStdout.info('x = ' + str(x)) # print eigenvalues if self.logStdout.isEnabledFor(logging.INFO): for i in range(0, len(A)): eigs, _ = eig(A[i]) eigs.sort() self.logStdout.info('EIG[' + str(i) + '] = ' + str(eigs)) # breaking condition if self.logStdout.isEnabledFor(logging.INFO): self.logStdout.info('Breaking condition = ' + str(self.eps * t)) if self.eps * t >= self.nu + ( self.beta + sqrt(self.nu)) * self.beta / (1 - self.beta): break self.solved = True self.result = x self.resultA = A self.iterations += k # plot main path if self.drawPlot: self.mainPathPlotFile = tempfile.NamedTemporaryFile() self.gnuplot.replot( gp.Data(x0All, x1All, title='Main path', with_='points pt 1', filename=self.mainPathPlotFile.name)) print('\nPress enter to continue') input() return x
def dampedNewton(self, start): """ Damped Newton method for analytics center [Nesterov, p. 204] Args: start (Matrix): the starting point of the algorithm Returns: Matrix: approximation of the analytic center """ k = 0 # starting point y = start if self.drawPlot: y0All = [y[0, 0]] y1All = [y[1, 0]] self.xAC = y # gradient and hessian Fd, Fdd, _ = Utils.gradientHessian(self.AAll, y) FdLN = Utils.LocalNormA(Fd, Fdd) self.logStdout.info('AUXILIARY PATH-FOLLOWING') while True: k += 1 if self.logStdout.isEnabledFor(logging.INFO): self.logStdout.info('\nk = ' + str(k)) # iteration step y = y - solve(Fdd, Fd) / (1 + FdLN) if self.logStdout.isEnabledFor(logging.INFO): self.logStdout.info('y = ' + str(y)) if self.drawPlot: y0All.append(y[0, 0]) y1All.append(y[1, 0]) self.xAC = hstack((self.xAC, y)) # gradient and hessian Fd, Fdd, A = Utils.gradientHessian(self.AAll, y) FdLN = Utils.LocalNormA(Fd, Fdd) # print eigenvalues if self.logStdout.isEnabledFor(logging.INFO): for i in range(0, len(A)): eigs, _ = eig(A[i]) eigs.sort() self.logStdout.info('EIG[' + str(i) + '] = ' + str(eigs)) # breaking condition if FdLN <= self.beta: break # save number of iterations self.iterations = k # plot auxiliary path if self.drawPlot: self.dampedNewtonPlotFile = tempfile.NamedTemporaryFile() self.gnuplot.replot( gp.Data(y0All, y1All, title='Damped Newton', with_='points pt 1', filename=self.dampedNewtonPlotFile.name)) return y
def auxFollow(self, start): """ Auxiliary path-following algorithm [Nesterov, p. 205] Warning: This function appears to be unstable. Please use dampedNewton instead. Args: start (Matrix): the starting point of the algorithm Returns: Matrix: approximation of the analytic center """ t = 1 k = 0 # starting point y = start if self.drawPlot: y0All = [y[0, 0]] y1All = [y[1, 0]] # gradient and hessian Fd, Fdd, A = Utils.gradientHessian(self.AAll, y) Fd0 = Fd FddInv = inv(Fdd) # print eigenvalues if self.logStdout.isEnabledFor(logging.INFO): for i in range(0, len(A)): eigs, _ = eig(A[i]) eigs.sort() self.logStdout.info('EIG[' + str(i) + '] = ' + str(eigs)) self.logStdout.info('AUXILIARY PATH-FOLLOWING') while True: k += 1 self.logStdout.info('\nk = ' + str(k)) # iteration step t = t - self.gamma / Utils.LocalNorm(Fd0, FddInv) y = y - dot(FddInv, (t * Fd0 + Fd)) #self.logStdout.info('t = ' + str(t)) self.logStdout.info('y = ' + str(y)) if self.drawPlot: y0All.append(y[0, 0]) y1All.append(y[1, 0]) # gradient and hessian Fd, Fdd, A = Utils.gradientHessian(self.AAll, y) FddInv = inv(Fdd) # print eigenvalues if self.logStdout.isEnabledFor(logging.INFO): for i in range(0, len(A)): eigs, _ = eig(A[i]) eigs.sort() self.logStdout.info('EIG[' + str(i) + '] = ' + str(eigs)) # breaking condition if Utils.LocalNorm( Fd, FddInv) <= sqrt(self.beta) / (1 + sqrt(self.beta)): break # prepare x x = y - dot(FddInv, Fd) # save number of iterations self.iterations = k # plot auxiliary path if self.drawPlot: self.gnuplot.replot( gp.Data(y0All, y1All, title='Auxiliary path', with_='points pt 1', filename='tmp/auxiliaryPath.dat')) return x
def main(): """Exercise the Gnuplot module.""" print ( 'This program exercises many of the features of Gnuplot.py. The\n' 'commands that are actually sent to gnuplot are printed for your\n' 'enjoyment.' ) wait('Popping up a blank gnuplot window on your screen.') g = gnuplot.Gnuplot(debug=1) g.clear() # Make two temporary files: if hasattr(tempfile, 'mkstemp'): (fd, filename1,) = tempfile.mkstemp(text=1) f = os.fdopen(fd, 'w') (fd, filename2,) = tempfile.mkstemp(text=1) else: filename1 = tempfile.mktemp() f = open(filename1, 'w') filename2 = tempfile.mktemp() try: for x in numpy.arange(100.)/5. - 10.: f.write('%s %s %s\n' % (x, math.cos(x), math.sin(x))) f.close() print ('############### test Func ###################################') wait('Plot a gnuplot-generated function') g.plot(gnuplot.Func('sin(x)')) wait('Set title and axis labels and try replot()') g.title('Title') g.xlabel('x') g.ylabel('y') g.replot() wait('Style linespoints') g.plot(gnuplot.Func('sin(x)', with_='linespoints')) wait('title=None') g.plot(gnuplot.Func('sin(x)', title=None)) wait('title="Sine of x"') g.plot(gnuplot.Func('sin(x)', title='Sine of x')) wait('axes=x2y2') g.plot(gnuplot.Func('sin(x)', axes='x2y2', title='Sine of x')) print ('Change Func attributes after construction:') f = gnuplot.Func('sin(x)') wait('Original') g.plot(f) wait('Style linespoints') f.set_option(with_='linespoints') g.plot(f) wait('title=None') f.set_option(title=None) g.plot(f) wait('title="Sine of x"') f.set_option(title='Sine of x') g.plot(f) wait('axes=x2y2') f.set_option(axes='x2y2') g.plot(f) print ('############### test File ###################################') wait('Generate a File from a filename') g.plot(gnuplot.File(filename1)) wait('Style lines') g.plot(gnuplot.File(filename1, with_='lines')) wait('using=1, using=(1,)') g.plot(gnuplot.File(filename1, using=1, with_='lines'), gnuplot.File(filename1, using=(1,), with_='points')) wait('using=(1,2), using="1:3"') g.plot(gnuplot.File(filename1, using=(1,2)), gnuplot.File(filename1, using='1:3')) wait('every=5, every=(5,)') g.plot(gnuplot.File(filename1, every=5, with_='lines'), gnuplot.File(filename1, every=(5,), with_='points')) wait('every=(10,None,0), every="10::5"') g.plot(gnuplot.File(filename1, with_='lines'), gnuplot.File(filename1, every=(10,None,0)), gnuplot.File(filename1, every='10::5')) wait('title=None') g.plot(gnuplot.File(filename1, title=None)) wait('title="title"') g.plot(gnuplot.File(filename1, title='title')) print ('Change File attributes after construction:') f = gnuplot.File(filename1) wait('Original') g.plot(f) wait('Style linespoints') f.set_option(with_='linespoints') g.plot(f) wait('using=(1,3)') f.set_option(using=(1,3)) g.plot(f) wait('title=None') f.set_option(title=None) g.plot(f) print ('############### test Data ###################################') x = numpy.arange(100)/5. - 10. y1 = numpy.cos(x) y2 = numpy.sin(x) d = numpy.transpose((x,y1,y2)) wait('Plot Data against its index') g.plot(gnuplot.Data(y2, inline=0)) wait('Plot Data, specified column-by-column') g.plot(gnuplot.Data(x,y2, inline=0)) wait('Same thing, saved to a file') gnuplot.Data(x,y2, inline=0, filename=filename1) g.plot(gnuplot.File(filename1)) wait('Same thing, inline data') g.plot(gnuplot.Data(x,y2, inline=1)) wait('Plot Data, specified by an array') g.plot(gnuplot.Data(d, inline=0)) wait('Same thing, saved to a file') gnuplot.Data(d, inline=0, filename=filename1) g.plot(gnuplot.File(filename1)) wait('Same thing, inline data') g.plot(gnuplot.Data(d, inline=1)) wait('with_="lp 4 4"') g.plot(gnuplot.Data(d, with_='lp 4 4')) wait('cols=0') g.plot(gnuplot.Data(d, cols=0)) wait('cols=(0,1), cols=(0,2)') g.plot(gnuplot.Data(d, cols=(0,1), inline=0), gnuplot.Data(d, cols=(0,2), inline=0)) wait('Same thing, saved to files') gnuplot.Data(d, cols=(0,1), inline=0, filename=filename1) gnuplot.Data(d, cols=(0,2), inline=0, filename=filename2) g.plot(gnuplot.File(filename1), gnuplot.File(filename2)) wait('Same thing, inline data') g.plot(gnuplot.Data(d, cols=(0,1), inline=1), gnuplot.Data(d, cols=(0,2), inline=1)) wait('Change title and replot()') g.title('New title') g.replot() wait('title=None') g.plot(gnuplot.Data(d, title=None)) wait('title="Cosine of x"') g.plot(gnuplot.Data(d, title='Cosine of x')) print ('############### test compute_Data ###########################') x = numpy.arange(100)/5. - 10. wait('Plot Data, computed by Gnuplot.py') g.plot( gnuplot.funcutils.compute_Data(x, lambda x: math.cos(x), inline=0) ) wait('Same thing, saved to a file') gnuplot.funcutils.compute_Data( x, lambda x: math.cos(x), inline=0, filename=filename1 ) g.plot(gnuplot.File(filename1)) wait('Same thing, inline data') g.plot(gnuplot.funcutils.compute_Data(x, math.cos, inline=1)) wait('with_="lp 4 4"') g.plot(gnuplot.funcutils.compute_Data(x, math.cos, with_='lp 4 4')) print ('############### test hardcopy ###############################') print ('******** Generating postscript file "gp_test.ps" ********') wait() g.plot(gnuplot.Func('cos(0.5*x*x)', with_='linespoints 2 2', title='cos(0.5*x^2)')) g.hardcopy('gp_test.ps') wait('Testing hardcopy options: mode="eps"') g.hardcopy('gp_test.ps', mode='eps') wait('Testing hardcopy options: mode="landscape"') g.hardcopy('gp_test.ps', mode='landscape') wait('Testing hardcopy options: mode="portrait"') g.hardcopy('gp_test.ps', mode='portrait') wait('Testing hardcopy options: eps=1') g.hardcopy('gp_test.ps', eps=1) wait('Testing hardcopy options: mode="default"') g.hardcopy('gp_test.ps', mode='default') wait('Testing hardcopy options: enhanced=1') g.hardcopy('gp_test.ps', enhanced=1) wait('Testing hardcopy options: enhanced=0') g.hardcopy('gp_test.ps', enhanced=0) wait('Testing hardcopy options: color=1') g.hardcopy('gp_test.ps', color=1) # For some reason, # g.hardcopy('gp_test.ps', color=0, solid=1) # doesn't work here (it doesn't activate the solid option), even # though the command sent to gnuplot looks correct. I'll # tentatively conclude that it is a gnuplot bug. ### wait('Testing hardcopy options: color=0') g.hardcopy('gp_test.ps', color=0) wait('Testing hardcopy options: solid=1') g.hardcopy('gp_test.ps', solid=1) wait('Testing hardcopy options: duplexing="duplex"') g.hardcopy('gp_test.ps', solid=0, duplexing='duplex') wait('Testing hardcopy options: duplexing="defaultplex"') g.hardcopy('gp_test.ps', duplexing='defaultplex') wait('Testing hardcopy options: fontname="Times-Italic"') g.hardcopy('gp_test.ps', fontname='Times-Italic') wait('Testing hardcopy options: fontsize=20') g.hardcopy('gp_test.ps', fontsize=20) print ('******** Generating svg file "gp_test.svg" ********') wait() g.plot(gnuplot.Func('cos(0.5*x*x)', with_='linespoints 2 2', title='cos(0.5*x^2)')) g.hardcopy('gp_test.svg', terminal='svg') wait('Testing hardcopy svg options: enhanced') g.hardcopy('gp_test.ps', terminal='svg', enhanced='1') print ('############### test shortcuts ##############################') wait('plot Func and Data using shortcuts') g.plot('sin(x)', d) print ('############### test splot ##################################') wait('a 3-d curve') g.splot(gnuplot.Data(d, with_='linesp', inline=0)) wait('Same thing, saved to a file') gnuplot.Data(d, inline=0, filename=filename1) g.splot(gnuplot.File(filename1, with_='linesp')) wait('Same thing, inline data') g.splot(gnuplot.Data(d, with_='linesp', inline=1)) print ('############### test GridData and compute_GridData ##########') # set up x and y values at which the function will be tabulated: x = numpy.arange(35)/2.0 y = numpy.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[:,numpy.newaxis] ym = y[numpy.newaxis,:] m = (numpy.sin(xm) + 0.1*xm) - ym**2 wait('a function of two variables from a GridData file') g('set parametric') g('set style data lines') g('set hidden') g('set contour base') g.xlabel('x') g.ylabel('y') g.splot(gnuplot.GridData(m,x,y, binary=0, inline=0)) wait('Same thing, saved to a file') gnuplot.GridData(m,x,y, binary=0, inline=0, filename=filename1) g.splot(gnuplot.File(filename1, binary=0)) wait('Same thing, inline data') g.splot(gnuplot.GridData(m,x,y, binary=0, inline=1)) wait('The same thing using binary mode') g.splot(gnuplot.GridData(m,x,y, binary=1)) wait('Same thing, using binary mode and an intermediate file') gnuplot.GridData(m,x,y, binary=1, filename=filename1) g.splot(gnuplot.File(filename1, binary=1)) wait('The same thing using compute_GridData to tabulate function') g.splot(gnuplot.funcutils.compute_GridData( x,y, lambda x,y: math.sin(x) + 0.1*x - y**2, )) wait('Same thing, with an intermediate file') gnuplot.funcutils.compute_GridData( x,y, lambda x,y: math.sin(x) + 0.1*x - y**2, filename=filename1) g.splot(gnuplot.File(filename1, binary=1)) wait('Use compute_GridData in ufunc and binary mode') g.splot(gnuplot.funcutils.compute_GridData( x,y, lambda x,y: numpy.sin(x) + 0.1*x - y**2, ufunc=1, binary=1, )) wait('Same thing, with an intermediate file') gnuplot.funcutils.compute_GridData( x,y, lambda x,y: numpy.sin(x) + 0.1*x - y**2, ufunc=1, binary=1, filename=filename1) g.splot(gnuplot.File(filename1, binary=1)) wait('And now rotate it a bit') for view in range(35,70,5): g('set view 60, %d' % view) g.replot() time.sleep(1.0) wait(prompt='Press return to end the test.\n') finally: os.unlink(filename1) os.unlink(filename2)
gnuplot = gp.Gnuplot() gnuplot('set xlabel "Dimension"') gnuplot('set ylabel "Time [s]"') gnuplot('set title "Performance of the POP solver based on the number of variables."') # plot data tempFiles = [] for df in range(0, shape[1]): for dr in range(0, shape[2]): dataSliced = data[:, df, dr] noNan = nonzero([~isnan(dataSliced)])[1] a = dataSliced[noNan] if a.shape[0] != 0: plotFile = tempfile.NamedTemporaryFile() tempFiles.append(plotFile) plot = gnuplot.replot(gp.Data(noNan, a, title = 'df = ' + str(df) + ', relaxOrder = ' + str(dr), with_ = 'lines lw 1.5', filename=plotFile.name)) print('\nPress enter to continue') input() # close temp file for tempFile in tempFiles: tempFile.close() # based on relaxation order if args.relaxOrder: # start GnuPlot gnuplot = gp.Gnuplot() gnuplot('set xlabel "Relaxation order"') gnuplot('set ylabel "Time [s]"') gnuplot('set title "Performance of the POP solver based on the relaxation order."')
parts = path[:-4].split('_') print(parts) date = parts[1][0:4] + '.' + parts[1][4:6] + '.' + parts[1][ 6:8] + ' ' + parts[2][0:2] + ':' + parts[2][2:4] # plot them dims = [] plotData = [] for n in range(0, shape[0]): if not isnan(data[n]): dims.append(n) plotData.append(data[n]) # plot plotFile = tempfile.NamedTemporaryFile() tempFiles.append(plotFile) plot = gnuplot.replot( gp.Data(dims, plotData, title=date + ' ' + parts[3], with_='lines linewidth 1.5', filename=plotFile.name)) print('\nPress enter to continue') input() # close temp files for tempFile in tempFiles: tempFile.close()