Beispiel #1
0
 def _doit(self, it, u):
     if __debug__:
         self.log.debug("Plotting iteration %i with data %s" % (it, str(u)))
     x, f = self.datafunc(it, u, self.system)
     f = np.atleast_2d(f)
     if __debug__:
         self.log.debug("Data after processing by self.datafunc is %s" % f)
         self.log.debug("Shape of domain to plot over is (%s,%s)" %
                        (x[0].shape[0], x[1].shape[0]))
     graphs = []
     self.device('set title "%s" enhanced' % self.title % (it, u.time))
     for i in range(f.shape[0]):
         if self.components is None:
             graphs += [
                 Gnuplot.GridData(f[i, :, :],
                                  xvals=x[0],
                                  yvals=x[1],
                                  filename="deleteme.gp",
                                  title="Component %i" % i,
                                  binary=0)
             ]
         else:
             graphs += [
                 Gnuplot.GridData(f[i, :, :],
                                  xvals=x[0],
                                  yvals=x[1],
                                  filename="deleteme.gp",
                                  title=self.components[i],
                                  binary=0)
             ]
     self.device.splot(*graphs)
     time.sleep(self.delay)
Beispiel #2
0
def plot_linreg(points, weights):
    g = Gnuplot.Gnuplot(debug=1)
    x_cir = arange(16) * 0.1 + (-1 * math.sqrt(0.6))
    y_cir = arange(21) * 0.1 + -1
    xm = x_cir[:, newaxis]
    ym = y_cir[newaxis, :]
    m = x_cir**2 + y_cir**2 - 0.6
    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_cir, y_cir, binary=0))

    #    x1 = array([ (-1+x*0.1) for x in range(20) ])
    #    y2 = (-1/weights[-1])*(weights[0]+weights[1]*x1)
    #    d2 = Gnuplot.Data(x1, y2, with_="lines", title="linreg_func")
    #    g('set data style linespoints') # give gnuplot an arbitrary command
    #
    #    g.plot(points, d1, d3, d2)
    raw_input('Please press return to continue...\n')
Beispiel #3
0
def plot_spec(filename, g, options):
    import Gnuplot
    data, time, freq = audio_to_spec(filename,
                                     minf=options.minf,
                                     maxf=options.maxf,
                                     bufsize=options.bufsize,
                                     hopsize=options.hopsize)
    xorig = 0.
    if max(time) < 1.:
        time = [t * 1000. for t in time]
        g.xlabel('Time (ms)')
    else:
        g.xlabel('Time (s)')
    if options.xsize < 0.5 and not options.log and max(time) > 1.:
        freq = [f / 1000. for f in freq]
        options.minf /= 1000.
        options.maxf /= 1000.
        g.ylabel('Frequency (kHz)')
    else:
        g.ylabel('Frequency (Hz)')
    g('set pm3d map')
    g('set palette rgbformulae -25,-24,-32')
    g('set cbtics 20')
    #g('set colorbox horizontal')
    g('set xrange [0.:%f]' % time[-1])
    if options.log:
        g('set log y')
        g('set yrange [%f:%f]' % (max(10, options.minf), options.maxf))
    else:
        g('set yrange [%f:%f]' % (options.minf, options.maxf))
    g.splot(Gnuplot.GridData(data, time, freq, binary=1))
Beispiel #4
0
 def __call__(self, u, xv, yv, t):
     if self.plot:
         data = Gnuplot.GridData(u, xv[:,0], yv[0,:], binary=0)
         self.g.splot(data)
         self.g('set title "t=%g"' % t)
     if self.plot == 2:
         self.g.hardcopy(filename='tmp_%020f.ps' % t,
                         enhanced=1, mode='eps', fontsize=14,
                         color=0, fontname='Times-Roman')
         time.sleep(0.8)   # pause to finish plot
Beispiel #5
0
def plot_Gnuplot(grid, func_values):
    import Gnuplot
    g = Gnuplot.Gnuplot(persist=1)
    g('set parametric')
    g('set data style lines')
    g('set hidden')
    g('set contour base')
    g.splot(Gnuplot.GridData(func_values, grid.xcoor, grid.ycoor))
    time.sleep(2)  # give Gnuplot some time to make the plot
    """
Beispiel #6
0
 def plot(self, func_values):
     self.g = Gnuplot.Gnuplot(persist=1)
     self.g('set parametric')
     self.g('set data style lines')
     self.g('set hidden')
     self.g('set contour base')
     self.g.splot(Gnuplot.GridData(
         func_values, self.xcoor, self.ycoor))
     time.sleep(2)  # give Gnuplot some time to make the plot
     """
Beispiel #7
0
 def action(u, xv, yv, t):
     #print 'action, t=',t,'\nu=',u, '\nx=',x, '\ny=', y
     if plot:
         data = Gnuplot.GridData(u, xv[:,0], yv[0,:], binary=0)
         g.splot(data)
         g('set title "t=%g"' % t)
         if plot == 2:
             g.hardcopy(filename='tmp_%020f.ps' % t, enhanced=1, mode='eps',
                        color=0, fontname='Times-Roman', fontsize=14)
             time.sleep(1)
         time.sleep(0.2) # pause between frames
Beispiel #8
0
def demo():
    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)  (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()
    x = arange(10, dtype='float_')
    y1 = x**2
    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.
    g.ylabel('x^2')
    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:
    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
    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')

    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
    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))
    raw_input('Please press return to continue...\n')
Beispiel #9
0
def compute_GridData(xvals, yvals, f, ufunc=0, **keyw):
    """Evaluate a function of 2 variables and store the results in a GridData.

    Computes a function 'f' of two variables on a rectangular grid
    using 'tabulate_function', then store the results into a
    'GridData' so that it can be plotted.  After calculation the data
    are written to a file; no copy is kept in memory.  Note that this
    is quite different than 'Func' (which tells gnuplot to evaluate
    the function).

    Arguments:

        'xvals' -- a 1-d array with dimension 'numx'

        'yvals' -- a 1-d array with dimension 'numy'

        'f' -- the function to plot--a callable object for which
            'f(x,y)' returns a number.

        'ufunc=<bool>' -- evaluate 'f' as a ufunc?

     Other keyword arguments are passed to the 'GridData' constructor.

    'f' should be a callable object taking two arguments.
    'f(x,y)' will be computed at all grid points obtained by
    combining elements from 'xvals' and 'yvals'.

    If called with 'ufunc=1', then 'f' should be a function that is
    composed entirely of ufuncs, and it will be passed the 'xvals' and
    'yvals' as rectangular matrices.

    Thus if you have a function 'f' and two vectors 'xvals' and
    'yvals' and a Gnuplot instance called 'g', you can plot the
    function by typing 'g.splot(compute_GridData(f, xvals, yvals))'.

    """

    xvals = utils.float_array(xvals)
    yvals = utils.float_array(yvals)

    # evaluate function:
    data = tabulate_function(f, xvals, yvals, ufunc=ufunc)

    return Gnuplot.GridData(data, xvals, yvals, **keyw)
Beispiel #10
0
def rotation():
    """Demonstrate the Gnuplot package."""
    # Create arrays of points
    xCorrection = [0, 1, 2, 3, 4, 5]
    yCorrection = [1.1, 3, 7.5, 8, 1, 2]
    # 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('set multiplot')
    g('set data style points')  # give gnuplot an arbitrary command
    # Plot a list of (x, y) pairs (tuples or a numpy array would
    # also be OK):
    for i in range(0, 5):
        g.plot([xCorrection[i], yCorrection[i]])

    g.title('Rotation')  # (optional)
    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))
    raw_input('Please press return to continue...\n')
Beispiel #11
0
	def plotplot(self,wplot,oplots,outplot=None,extension=None,xsize=1.,ysize=1.,spectro=False):
		from aubio.gnuplot import gnuplot_create, audio_to_array, make_audio_plot, audio_to_spec
		import re
		# prepare the plot
		g = gnuplot_create(outplot=outplot, extension=extension)
		g('set title \'%s\'' % (re.sub('.*/','',self.input)))
		if spectro:
			g('set size %f,%f' % (xsize,1.3*ysize) )
		else:
			g('set size %f,%f' % (xsize,ysize) )
		g('set multiplot')

		# hack to align left axis
		g('set lmargin 3')
		g('set rmargin 6')

		if spectro:
			import Gnuplot
			minf = 50
			maxf = 500 
			data,time,freq = audio_to_spec(self.input,minf=minf,maxf=maxf)
			g('set size %f,%f' % (1.24*xsize , 0.34*ysize) )
			g('set origin %f,%f' % (-0.12,0.65*ysize))
			g('set xrange [0.:%f]' % time[-1]) 
			g('set yrange [%f:%f]' % (minf,maxf))
			g('set pm3d map')
			g('unset colorbox')
			g('set lmargin 0')
			g('set rmargin 0')
			g('set tmargin 0')
			g('set palette rgbformulae -25,-24,-32')
			g.xlabel('time (s)',offset=(0,1.))
			g.ylabel('freq (Hz)')
			g('set origin 0,%f' % (1.0*ysize) ) 
			g('set format x "%1.1f"')
			#if log:
			#	g('set yrange [%f:%f]' % (max(10,minf),maxf))
			#	g('set log y')
			g.splot(Gnuplot.GridData(data,time,freq, binary=1, title=''))
		else:
			# plot waveform and onsets
			time,data = audio_to_array(self.input)
			wplot = [make_audio_plot(time,data)] + wplot
			g('set origin 0,%f' % (0.7*ysize) )
			g('set size %f,%f' % (xsize,0.3*ysize))
			g('set format y "%1f"')
			g('set xrange [0:%f]' % max(time)) 
			g('set yrange [-1:1]') 
			g('set noytics')
			g('set y2tics -1,1')
			g.xlabel('time (s)',offset=(0,0.7))
			g.ylabel('amplitude')
			g.plot(*wplot)

		# default settings for next plots
		g('unset title')
		g('set format x ""')
		g('set format y "%3e"')
		g('set tmargin 0')
		g.xlabel('')

		N = len(oplots)
		y = 0.7*ysize # the vertical proportion of the plot taken by onset functions
		delta = 0.035 # the constant part of y taken by last plot label and data
		for i in range(N):
			# plot onset detection functions
			g('set size %f,%f' % ( xsize, (y-delta)/N))
			g('set origin 0,%f' % ((N-i-1)*(y-delta)/N + delta ))
			g('set nokey')
			g('set xrange [0:%f]' % (self.lenofunc*self.params.step))
			g('set yrange [0:%f]' % (1.1*oplots[i][2]))
			g('set y2tics ("0" 0, "%d" %d)' % (round(oplots[i][2]),round(oplots[i][2])))
			g.ylabel(oplots[i][1])
			if i == N-1:
				g('set size %f,%f' % ( xsize, (y-delta)/N + delta ) )
				g('set origin 0,0')
				g.xlabel('time (s)', offset=(0,0.7))
				g('set format x')
			g.plot(*oplots[i][0])

		g('unset multiplot')
Beispiel #12
0
ym = vec_mag[numpy.newaxis,:]
zm = vec_prof[numpy.newaxis,:]

######################Grafica 3D Profundidad####################################
m = (sum_profT+zm-zm+xm-xm)
g('set terminal jpeg')
g('set output "prof3d.jpg"')
g('set pm3d')
g.title('Profundidad')
g('set zlabel "Numero de sismos" rotate parallel ')
g.xlabel('')
g.ylabel('Profundidad')
g('unset xtics')
g('set view 75,75')
g('set palette defined (0 "blue", 4 "white", 9 "red")')
g.splot(Gnuplot.GridData(m,vec_rms,vec_prof, binary=0, inline=0, with_='pm3d'))
#raw_input('Please press return to continue...\n')
############################Grafica 3D RMS####################################
del m
m = (sum_rms+ym-ym+xm-xm)
g('set pm3d')
g('set terminal jpeg')
g('set output "rms3d.jpg"')
g.title('RMS')
g('set zlabel "Numero de sismos" rotate parallel ')
g.xlabel('')
g.ylabel('RMS')
g('unset xtics')
g('set view 75,75')
g('set palette defined (0 "blue", 4 "white", 9 "red")')
g.splot(Gnuplot.GridData(m,vec_mag,vec_rms, binary=0, inline=0, with_='pm3d'))
Beispiel #13
0
        x = Numeric.arange(35)/2.0
        y = Numeric.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 = (Numeric.sin(xm) + 0.1*xm) - ym**2
        wait('a function of two variables from a GridData file')
        g('set parametric')
        g('set data style 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, 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('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('Use compute_GridData in ufunc and binary mode')
        g.splot(Gnuplot.funcutils.compute_GridData(
            x,y, lambda x,y: Numeric.sin(x) + 0.1*x - y**2,
            ufunc=1, binary=1,
Beispiel #14
0
def main():
    # parse cmd arguments
    parser = getParser()
    parser.parse_args()
    args = getArguments(parser)
    
    # load image data
    image_data = numpy.squeeze(load(args.image).get_data())
    mask_data = numpy.squeeze(load(args.mask).get_data()).astype(numpy.bool_)
    
    # sample data
    image_data = image_data[::args.sample[0], ::args.sample[1], ::args.sample[2]]
    mask_data = mask_data[::args.sample[0], ::args.sample[1], ::args.sample[2]]
    
    # check dimensions to be equal
    if image_data.shape != mask_data.shape:
        raise ArgumentError("The images dimensions are not euqal!")
    
    # extract relevant area from image_data
    highlighted_data = image_data.copy()
    highlighted_data[~mask_data] = image_data.min()
    
    # set the same values in the image to zero
    image_data[mask_data] = image_data.min()
    
    # load gnuplot
    g = Gnuplot.Gnuplot(debug=1)
    
    # set static gnuplot parameters
    g('set style data lines')
    g('set surface \n')
    g('set hidden3d\n')
    g('set view 60, 30, 1, 1\n')
    g('set key right\n')
    g('set xlabel "X"\n')
    g('set ylabel "Y"\n')
    g('set zlabel "Value"\n')
    g('set autoscale\n')

    # set default parameters
    dim = 0
    sl = 0
    getch = _Getch()
    
    # infinite loop 
    while True:
        # prepare slices
        sls =[]
        for i in range(image_data.ndim):
            if i == dim:
                sls.append(slice(sl, sl+1))
            else:
                sls.append(slice(None))
        sl_image = numpy.squeeze(image_data[sls])
        sl_highlighted = numpy.squeeze(highlighted_data[sls])
        
        # set variable gnuplot parameters
        g('set title "Topographical image axis={}/{}, slice={}/{}"\n'.format(dim + 1, image_data.ndim, sl + 1, image_data.shape[dim]))
        g('set zrange [{}:{}]\n'.format(image_data.min(), image_data.max()))
        
        # create temp files for matrix processing
        # plot
        image_plot = Gnuplot.GridData(sl_image,
                                      range(sl_image.shape[0]),
                                      range(sl_image.shape[1]),
                                      title='data outside mask',
                                      binary=0)
        #image_plot = Gnuplot.Data(sl_image, title='data out of mask')
        highlighted_plot = Gnuplot.GridData(sl_highlighted,
                                            range(sl_highlighted.shape[0]),
                                            range(sl_highlighted.shape[1]),
                                            title='data inside mask',
                                            binary=0)
        #highlighted_plot = Gnuplot.Data(sl_highlighted, title='data inside mask')
        g.splot(image_plot, highlighted_plot)
        
        # wait for key
        print "d/a = slices +/-; s/w = dimension +/-; e/q = slices +/- 10; ESC = exit\n"
        ch = getch()
        
        # check key pressed
        if 'a' == ch: # sl - 1
            sl = max(0, sl - 1)
        elif 'd' == ch: # sl + 1
            sl = min(image_data.shape[dim] - 1, sl + 1)
        elif 'w' == ch: # dimension - 1
            dim = max(0, dim - 1)
            sl = min(image_data.shape[dim] - 1, sl)
        elif 's' == ch: # dimension + 1
            dim = min(image_data.ndim - 1, dim + 1)
            sl = min(image_data.shape[dim] - 1, sl)
        elif 'q' == ch: # sl - 10
            sl = max(0, sl - 10)
        elif 'e' == ch: # sl + 10
            sl = min(image_data.shape[dim] - 1, sl + 10)
        elif "" == ch: break # ESC or other unknown char
        else: "Unrecognized key"
    
    #close the gnuplot window
    g('quit\n')
Beispiel #15
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 data style 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)
Beispiel #16
0
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')
Beispiel #17
0
x=numpy.r_[0.0:pi_c:num_points*j]
m[0,:]=numpy.sin(x)
m[num_points-1,:]=numpy.sin(x)

u = m

#******************** CALL the functions: Add your code here *******************. 

# solve in c
import time
start1 = time.clock()
u = solve_in_python(u, dx, maxiter)
ptime = time.clock() - start1
start2 = time.clock()
u = solve_in_c()
ctime = time.clock() - start2

#*****************************************************************************

#Create Plot
g = Gnuplot.Gnuplot(persist=1)
g('set pm3d')
g('set view map')
g('unset surface')
g('set size square')
g('set xrange [0:200]')
g('set yrange [0:200]')
#g('set xtics ("0" 0, "0.25" 25, "0.5" 50, "0.75" 75, "1" 100)')
#g('set ytics ("0" 0, "0.25" 25, "0.5" 50, "0.75" 75, "1" 100)')
g.splot(Gnuplot.GridData(u,binary=0,inline=0))
Beispiel #18
0
    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))
    raw_input('Please press return to continue...\n')

    # Explicit delete shouldn't be necessary, but if you are having
    # trouble with temporary files being left behind, try uncommenting
    # the following:
    #del g, d
from numpy import *
import Gnuplot
import math
import setup

g = Gnuplot.Gnuplot(debug=1)

# Demonstrate a 3-d plot:
# set up x and y values at which the function will be tabulated:
x = arange(25)
y = arange(25)

# 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 = xm**2 * 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')

g.splot(Gnuplot.GridData(m, x, y))

1