Open main menu

Changes

=Introduction=
 
'''After [http://www.ntg.nl/EuroTeX2009 eurotex meeting 2009],
I'm going to fix some typos here and there and
maybe expand some examples too. I estimated that around 20 September article and site will be in synch.'''
 
 
----
'''!! W A R N I N G !! '''
For more infos, see [http://root.cern.ch here] ([http://root.cern.ch/cgi-bin/print_hit_bold.pl/root/HowtoPyROOT.html?python#first_hit here] for python stuffs).
Under Linux installation is not difficult at all, so but in this case I choose to not create a luatex-lunatic apart, as done above for sagemath.<br/>See an example [[#ROOT| here]] .
= ConTeXt mkIV examples=This example shot how to literally embedHere I will collect some tex snippets,just to show some ideasoriginal python source code .
== Scipy ==Watch how python code <tttable> z = x*np.exp(-x**2-y**2) </tttr>is translated in lua code <tttd> z = x.__mul__( np.exp( (x.__pow__(2).__add__(y.__pow__(2))).__neg__() ) )</tt>  {| class="wikitable" |-|<texcode>
\startluacode
function testSCIPYtest_ROOT(figname,dpifilename)
require("python")
pg = python.globals()
python.apply = python.eval('apply') or {}
np = python.import("numpy")
mlab = python.import("matplotlib.mlab")
griddata = mlab.griddata
plt = python.import("matplotlib.pyplot")
ma = np.ma
random = python.import("numpy.random")
uniform = random.uniform
-- make up some randomly distributed data npts = 200 x = uniform(-2,2,npts) y = uniform(-2,2,npts) -- z = x*nppython.expexecute(-x**2-y**2)[[ z = x.__mul__( np.exp( (x.__pow__def run(2).__add__(y.__pow__(2))).__neg__() ) ) -- define grid. xi = np.linspace(-2.1,2.1,100filename): yi = np.linspace(-2.1 from ROOT import TCanvas,2.1,100)TGraph -- grid the data. from ROOT import gROOT zi = griddata(x,y,z,xi,yi) from math import sin -- contour the gridded data, plotting dots from array import array -- at the randomly spaced data points. -- we put this in python globals space -- CS = plt gROOT.contourReset(xi,yi,zi,15,linewidths=0.5,colors='k') pg.xi = xi ; pg.yi = yi ; pg.zi = zi args c1 = python.evalTCanvas("[xi,yi,zi,15]") kv = python.eval("{'linewidthc1': 0.5 ,'colors' :'kA Simple Graph Example'}") CS = python.apply(plt.contour, args,kv) -- pg.jet = plt.cm.jet args = python.eval("[xi200,yi10,zi700,15]"500 ) kv = python.eval("{'cmap': jet}") CS = python c1.applySetFillColor(plt.contourf, args,kv42 ) -- draw colorbar plt c1.colorbarSetGrid() -- plot data points. pg.x n = x; pg.y = y 20 args = python.eval("[ x,y]") kv = python.evalarray("{'marker': 'od'), array( 'cd':'b','s':5}") CS = python.apply(plt.scatter, args,kv) plt.xlim(-2,2) plt.ylim for i in range(-2,2n ): plt x.titleappend(string0.format('griddata test (%1*i points)',npts)) --plt y.savefigappend(figname, dpi, 'white') -- pg.figname = figname ; pg.dpi = dpi args = python.eval10*sin("x[fignamei]") kv = python+0.eval("{'dpi': dpi ,'facecolor' :'white'}"2 ) CS = python.apply(plt.savefig, args,kv)end\stopluacode
gr = TGraph( n, x, y ) gr.SetLineColor( 2 ) gr.SetLineWidth( 4 ) gr.SetMarkerColor( 4 ) gr.SetMarkerStyle( 21 ) gr.SetTitle( 'a simple graph' ) gr.GetXaxis().SetTitle( 'X title' )\def\testSCIPY[#1]{% gr.GetYaxis().SetTitle( 'Y title' ) gr.Draw( 'ACP' ) c1.Update() c1.Print(filename)\getparameters[scipy][#1]%)\ctxlua{testSCIPY run = pg.run run("\csname scipyfigname\endcsname",filename) "\csname scipydpi\endcsname")}%end\externalfigure[\csname scipyfigname\endcsname]%}stopluacode
\starttext
\startTEXpage
\testSCIPYctxlua{test_ROOT("testsin.pdf")}\rotate[fignamerotation=90]{test-scipy-1\externalfigure[testsin.pdf},dpi][width={1505cm]}]
\stopTEXpage
\stoptext
</texcode>|| </td><td> [[Image:Test-scipyTestsin.pngjpg|600px512px]] </td> |}</tr></table>
== Python Imaging Library We can do a bit better: separate python code from lua code .<br/>Save this in <tt>test-ROOT1.py</tt> (PILso it's also easy to test) ==:<pre>from ROOT import TCanvas, TGraph ,TGraphErrors,TMultiGraph{| class="wikitable" from ROOT import gROOT|-from math import sin|<texcode>from array import array\startluacodefunction testPILdef run(imageorig,imagesepiafilename): require c1 = TCanvas("pythonc1") PIL_Image = python.import(,"PIL.Imagemultigraph",200,10,700,500) PIL_ImageOps = python c1.importSetGrid("PIL.ImageOps") python.execute([[def make_linear_ramp # draw a frame to define the range mg = TMultiGraph(white): ramp = []# create first graph r, g, b n = white24; for i in x = array('d',range(25524)): ramp data = file('data').extend(readlines(r*i/255, g*i/255, b*i/255)) return ramp]])for line in data: -- make sepia ramp line = line.strip(tweak color as necessary) sepia y = python.evalarray("make_linear_ramp'd',[float(d) for d in line.split(255, 240, 192))"]) im gr = PIL_Image.open TGraph(imageorign,x,y) -- convert to grayscale if not gr.Fit(im.mode == "Lpol6") then im = im.convert(,"Lq") end -- optional: apply contrast enhancement here, e.g. im = PIL_ImageOps mg.autocontrastAdd(imgr)
-- apply sepia palette immg.putpaletteDraw(sepia"ap")
-- convert back #force drawing of canvas to RGB so we can save it as JPEGgenerate the fit TPaveStats -- c1.Update(alternatively, save it in PNG or similar) im = imc1.convertPrint("RGB"filename)
im</pre>Here file 'data' is a 110 lines file with 24 floats values space separated,ie <br/><tt> 20.save6000 19.4000 19.4000 18.3000 17.8000 16.1000 16.7000 21.1000 23.3000 26.1000 26.1000 27.2000 27.8000 28.3000 28.3000 27.2000 25.6000 22.8000 21.7000 21.7000 21.7000 21.7000 21.7000 21.7000 </tt>.<br/>Now a tex file, with a simple layer in lua as interface for python:{||-|<texcode>\startluacodefunction test_ROOT(filename) require("python") test = python.import('test-ROOT1') test.run(imagesepiafilename)end
\stopluacode
 
\def\SepiaImage#1#2{%
\ctxlua{testPIL("#1","#2")}%
\startcombination[2*1]
{\externalfigure[#1]}{\ss Orig.}
{\externalfigure[#2]}{\ss Sepia}
\stopcombination
}
 
\starttext
\startTEXpage
\SepiaImagectxlua{lenatest_ROOT("data.jpgpdf")}\rotate[rotation=90]{lena-sepia\externalfigure[data.jpgpdf]}
\stopTEXpage
\stoptext
</texcode> || [[Image:Test-PILROOT1.pngjpg|330px300px]]
|}
=ConTeXt mkIV examples= ROOT ==This example shot how Here I will collect some tex snippets,just to literally embedoriginal python source code show some ideas.
== Scipy ==Watch how python code <tablett> z = x*np.exp(-x**2-y**2) </tt>is translated in lua code <trtt> z = x.__mul__( np.exp( (x.__pow__(2).__add__(y.__pow__(2))).__neg__() ) )<td/tt>  {| class="wikitable" |-|<texcode>
\startluacode
function test_ROOTtestSCIPY(filenamefigname,dpi)
require("python")
pg = python.globals()
python.apply = python.eval('apply') or {}
np = python.import("numpy")
mlab = python.import("matplotlib.mlab")
griddata = mlab.griddata
plt = python.import("matplotlib.pyplot")
ma = np.ma
random = python.import("numpy.random")
uniform = random.uniform
python.execute([[-- make up some randomly distributed data npts = 200def run x = uniform(filename-2,2,npts): from ROOT import TCanvas y = uniform(-2, TGraph2,npts) from ROOT import gROOT -- z = x*np.exp(-x**2-y**2) from math import sin z = x.__mul__( np.exp( (x.__pow__(2).__add__(y.__pow__(2))).__neg__() ) ) from array import array -- define grid. xi = np.linspace(-2.1,2.1,100)  gROOT yi = np.Resetlinspace(-2.1,2.1,100) -- grid the data. c1 zi = TCanvasgriddata( 'c1'x, 'A Simple Graph Example'y, 200z, 10xi, 700, 500 yi) -- contour the gridded data, plotting dots c1 -- at the randomly spaced data points.SetFillColor( 42 ) c1 -- we put this in python globals space -- CS = plt.SetGridcontour(xi,yi,zi,15,linewidths=0.5,colors='k') pg.xi = xi ; pg.yi = yi ; pg.zi = zi n args = 20python.eval("[xi,yi,zi,15]") x, y kv = arraypython.eval( "{'dlinewidth' ): 0.5 , array( 'dcolors' :'k' }" for i in range CS = python.apply( n plt.contour, args,kv): x -- pg.jet = plt.append( 0cm.1*i )jet y args = python.append( 10*sineval( x"[ixi,yi,zi,15]+0") kv = python.2 ) eval("{'cmap': jet}" gr CS = TGraphpython.apply( nplt.contourf, xargs, y kv) gr -- draw colorbar plt.SetLineColorcolorbar( 2 ) gr -- plot data points.SetLineWidth( 4 ) gr pg.x = x; pg.SetMarkerColor( 4 )y = y gr args = python.SetMarkerStyleeval( 21 "[x,y]") gr kv = python.SetTitleeval( "{'marker': 'o'a simple graph, ' c':'b','s':5}") gr CS = python.GetXaxisapply(plt.scatter, args,kv) plt.SetTitlexlim( 'X title' -2,2) gr plt.GetYaxisylim(-2,2) plt.title(string.SetTitleformat( 'Y titlegriddata test (%i points)' ,npts)) gr --plt.Drawsavefig( figname, dpi, 'ACPwhite' ) c1 -- pg.figname = figname ; pg.Update()dpi = dpi c1 args = python.Printeval(filename)]"[figname]") run kv = pgpython.runeval("{'dpi': dpi ,'facecolor' :'white'}") runCS = python.apply(filenameplt.savefig, args,kv)
end
\stopluacode
 
 
\def\testSCIPY[#1]{%
\getparameters[scipy][#1]%
\ctxlua{testSCIPY("\csname scipyfigname\endcsname",
"\csname scipydpi\endcsname")}%
\externalfigure[\csname scipyfigname\endcsname]%
}
\starttext
\startTEXpage
\ctxluatestSCIPY[figname={test_ROOT("testsintest-scipy-1.pdf")}\rotate[rotation,dpi=90]{\externalfigure[testsin.pdf][width=5cm150}]}
\stopTEXpage
\stoptext
</texcode> </td><td> || [[Image:TestsinTest-scipy.jpgpng|512px600px]] </td> </tr></table>|}
We can do a bit better== Python Imaging Library (PIL) == {| class="wikitable" |-|<texcode>\startluacodefunction testPIL(imageorig,imagesepia) require("python") PIL_Image = python.import("PIL.Image") PIL_ImageOps = python.import("PIL.ImageOps") python.execute([[def make_linear_ramp(white): ramp = [] r, g, b = white for i in range(255): separate python code from lua code ramp.<brextend((r*i/255, g*i/255, b*i/>255)) return ramp]]) Save this in <tt>test --ROOT1make sepia ramp (tweak color as necessary) sepia = python.eval("make_linear_ramp((255, 240, 192))") im = PIL_Image.py</tt> open(so it's also easy imageorig) -- convert to testgrayscale if not(im.mode == "L") then im = im.convert("L") end -- optional:apply contrast enhancement here, e.g. im = PIL_ImageOps.autocontrast(im)  -- apply sepia palette im.putpalette(sepia)<pre>from ROOT import TCanvas -- convert back to RGB so we can save it as JPEG -- (alternatively, TGraph save it in PNG or similar) im = im.convert("RGB")  im.save(imagesepia)end\stopluacode \def\SepiaImage#1#2{%\ctxlua{testPIL("#1",TGraphErrors,TMultiGraph"#2")}%\startcombination[2*1]{\externalfigure[#1]}{\ss Orig.}from ROOT import gROOT{\externalfigure[#2]}{\ss Sepia}from math import sin\stopcombinationfrom array import array}
def run(filename):
c1 = TCanvas("c1","multigraph",200,10,700,500)
c1.SetGrid()
# draw a frame to define the range\starttext mg = TMultiGraph()\startTEXpage # create first graph n = 24; x = array('d',range(24)) data = file('data')\SepiaImage{lena.jpg}{lena-sepia.readlines()jpg} for line in data:\stopTEXpage line = line.strip()\stoptext y = array('d',</texcode> || [float(d) for d in line[Image:Test-PIL.split()png|330px]]) gr = TGraph(n,x,y) gr.Fit("pol6","q") mg.Add(gr)  mg.Draw("ap")  #force drawing of canvas to generate the fit TPaveStats c1.Update() c1.Print(filename)|}
</pre>
Here file 'data' is a 110 lines file with 24 floats values space separated,
ie <br/><tt> 20.6000 19.4000 19.4000 18.3000 17.8000 16.1000 16.7000 21.1000 23.3000 26.1000 26.1000 27.2000 27.8000 28.3000 28.3000 27.2000 25.6000 22.8000 21.7000 21.7000 21.7000 21.7000 21.7000 21.7000 </tt>.<br/>
Now a tex file, with a simple layer in lua as interface for python:
{|
|-
|<texcode>
\startluacode
function test_ROOT(filename)
require("python")
test = python.import('test-ROOT1')
test.run(filename)
end
\stopluacode
\starttext
\startTEXpage
\ctxlua{test_ROOT("data.pdf")}
\rotate[rotation=90]{\externalfigure[data.pdf]}
\stopTEXpage
\stoptext
</texcode>
| [[Image:Test-ROOT1.jpg|300px]]
|}
== ImageMagick ==
For the first case, we consider an implementation of eps2pdf, being ps2pdf virtually the same .<br/>
Actually there is not a python binding of ghostscript, so we build a simple wrapper
using ctypes module<tt>testgs.py</tt> :
<pre>
=== Build the cointainer ===
First we build the container 'Data.dbxml' in the directory "wikienv" (that must exists) :
<pre>
</pre>
=== Make pdf ===We use this modules <tt>wikidbxml_queryTxn.py</tt>to retrive a page, given a title (it can be also used as basis to build more complex queries, but for now it's adeguate ):
<pre>