예제 #1
0
파일: nbody.py 프로젝트: jhidding/conan
    def __init__(self, B, m, C, X, P):
        self.B = B
        self.C = C
        self.X = X
        self.P = P
        self.m = m

        self.g = gp.Gnuplot(persist=True)
        self.g("set cbrange [0.2:50]", "set log cb", "set size square",
               "set xrange [0:{0}] ; set yrange [0:{0}]".format(B.N))
예제 #2
0
    def setDrawPlot(self, drawPlot):
        """
    Enables or disables the drawing of the graph.

    Args:
      drawPlot (bool): True - draw graph, False - do not draw graph
    
    Returns:
      None

    Throws:
      ValueError: the graph con not be plotted if the dimension is not 2
    """

        if (drawPlot == True) & (self.dim != 2):
            raise ValueError(
                'The graph can not be plotted. Dimension of the problem differ from 2.'
            )

        self.drawPlot = drawPlot

        if self.drawPlot:
            # symbolic variables
            x = sp.Symbol('x')
            y = sp.Symbol('y')

            # self-concordant barrier
            X = self.AAll[0][0] + self.AAll[0][1] * x + self.AAll[0][2] * y

            # create temp file for gnuplot
            self.setPlotFile = tempfile.NamedTemporaryFile()

            # plot and save the set into file
            self.gnuplot = gp.Gnuplot()
            self.gnuplot('set view map')
            self.gnuplot('set contour')
            self.gnuplot('set cntrparam levels discrete 0')
            self.gnuplot('unset surface')
            self.gnuplot('set isosamples 2000, 2000')
            self.gnuplot('set table "' + str(self.setPlotFile.name) + '"')
            setPlot = self.gnuplot.splot(str(sp.Matrix(X).det()))
            self.gnuplot('unset table')
            self.gnuplot.reset()

            # plot the set
            self.plot = self.gnuplot.plot(
                '"' + str(self.setPlotFile.name) +
                '" using 1:2 with lines title "Set boundary"')
예제 #3
0
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)
예제 #4
0
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')
예제 #5
0
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)
예제 #6
0
        results[n, dF, dR] = nanmedian(t)
  
  save('data/POP.npy', results)


# plotting
if args.plot:
  # load data form file
  data = load('data/POP.npy')
  print(data)
  shape = data.shape
  
  # based on dimension
  if args.dimension:
    # start GnuPlot
    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))