Source

unplot.py / mk-test-plot.py

from opster import command
from pylab import *
from unplot import unplot_file

def f(x):
    "Test function"
    return sin(x)+0.5*cos(2*x)+0.25*sin(4*(x+pi/4))

options = \
  [ ("w", "linewidth", 3, "linewidth to use on a plot")
  , ("s", "show", False, "show the plot")
  ]

@command(usage="%name [options]", options=options)
def main(**opts):
    """
Plot a function and recover the data back. Compare to the
original. Save test-plot.png and test-plot-unplotted.png in the
current directory. To change the function, edit source.
    """
    xs = linspace(0,2*pi,100)
    ys = f(xs)
    lw = opts.get("linewidth")

    plot(xs,ys,'r-',linewidth=lw)
    savefig("test-plot.png")
    xb,xt = xlim()
    yb,yt = ylim()
    
    # assuming default plot geometry of 800x600 plot
    bot_left_px = (100,541)
    top_right_px = (719,63)
    bot_left_val = (xb,yb)
    top_right_val = (xt,yt)
    
    pts = unplot_file("test-plot.png", (bot_left_px,top_right_px), (bot_left_val, top_right_val))
    errs = [ y-f(x) for x,y in pts ]
    
    xs2, ys2 = zip(*pts)
    
    res = (top_right_val[1] - bot_left_val[1]) / (bot_left_px[1] - top_right_px[1])
    every=20
    clf()
    title("Mean error: %.3g @ resolution: %.3g [1/px]" % (mean(errs), res))
    plot(xs,ys,'b-',linewidth=lw,alpha=0.25,label="original")
    plot(xs2,ys2,'r-',linewidth=1,label="unplotted")
    errorbar(xs2[::every], ys2[::every], abs(array(errs))[::every], fmt=None, ecolor='r')
    legend()
    savefig("test-plot-unplotted.png")

    if opts.get("show"):
        show()
    
if "__main__" == __name__:
    main()