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 !! '''
* R-2.8.1 with rpy2-2.0.3 (For Maurizio "Mau" Himmelman , GUIT) ✔ [[#R|here]] (someone says also [http://micahelliott.com/2009/03/considering-r-as-python-supplement considering-r-as-python-supplement ]) .
* quantlib 0.9.7 ✔ (need an example with output in pdf)
* dbxml-2.4.16 (and sqlite) ✔ [[#dbxml|here]]
= Dedicated systems =
$HOME_LUN/sage/local/bin/python setup.py build
cd $HOME_LUN
mkdir tests-SAGEMATH && cd tests-SAGEMATH
##
## I have already installed prev. python.so, I don't want mess things
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,TMultiGraphfrom ROOT import gROOTfrom math import sinfrom array import array
{| classdef run(filename): c1 = TCanvas("c1","multigraph",200,10,700,500) c1.SetGrid()  # draw a frame to define the range mg = TMultiGraph() # create first graph n = 24; x = array('d',range(24)) data = file('data').readlines() for line in data: line = line.strip() y = array('d',[float(d) for d in line.split()]) gr = TGraph(n,x,y) gr.Fit("wikitablepol6" ,"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 testPILtest_ROOT(imageorig,imagesepiafilename)
require("python")
PIL_Image test = python.import("PIL.Image") PIL_ImageOps = python.import("PIL.ImageOps"'test-ROOT1') python.execute([[def make_linear_ramp(white): ramp = [] r, g, b = white for i in range(255): ramp.extend((r*i/255, g*i/255, b*i/255)) return ramp]]) -- make sepia ramp (tweak color as necessary) sepia = python.eval("make_linear_ramp((255, 240, 192))") im = PIL_Image.open(imageorig) -- convert to grayscale 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)  -- convert back to RGB so we can save it as JPEG -- (alternatively, save it in PNG or similar) im = im.convert("RGB")  imtest.saverun(imagesepiafilename)end
\stopluacode
\defstarttext\SepiaImage#1#2{%startTEXpage\ctxlua{testPILtest_ROOT("#1","#2data.pdf")}%\startcombinationrotate[2*1rotation=90]{\externalfigure[#1]}{\ss Origdata.}{\externalfigure[#2pdf]}{\ss Sepia}\stopcombination}  \starttext\startTEXpage\SepiaImage{lena.jpg}{lena-sepia.jpg}
\stopTEXpage
\stoptext
</texcode> || [[Image:Test-PILROOT1.pngjpg|330px300px]]
|}
=ConTeXt mkIV examples= ROOT Here I will collect some tex snippets,just to show some ideas. == Scipy ==This example shot Watch how to literally embedpython code <tt> z = x*np.exp(-x**2-y**2) </tt>original python source is translated in lua code <tt> z = x.__mul__( np.exp( (x.__pow__(2).__add__(y.__pow__(2))).__neg__() ) )</tt> 
<table>{| class="wikitable" <tr>|-<td>|<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
-- make up some randomly distributed data npts = 200 x = uniform(-2,2,npts) y = uniform(-2,2,npts) -- z = x*np.exp(-x**2-y**2) z = x.__mul__( np.exp( (x.__pow__(2).__add__(y.__pow__(2))).__neg__() ) ) -- define grid. xi = np.linspace(-2.1,2.1,100) yi = np.linspace(-2.1,2.1,100) -- grid the data. zi = griddata(x,y,z,xi,yi) -- contour the gridded data, plotting dots -- at the randomly spaced data points. -- we put this in python globals space -- CS = plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k') pg.xi = xi ; pg.yi = yi ; pg.zi = zi args = python.executeeval("[[xi,yi,zi,15]")def run kv = python.eval(filename"{'linewidth': 0.5 ,'colors' :'k'}"): from ROOT import TCanvas CS = python.apply(plt.contour, args, TGraphkv) from ROOT import gROOT -- from math import sin pg.jet = plt.cm.jet from array import array args = python.eval("[xi,yi,zi,15]") kv = python.eval("{'cmap': jet}") CS = python.apply(plt.contourf, args,kv) gROOT -- draw colorbar plt.Resetcolorbar() -- plot data points. pg.x = x; pg.y = y c1 args = TCanvaspython.eval( "[x,y]") kv = python.eval("{'marker': 'c1o', 'A Simple Graph Examplec':'b', 200's':5}") CS = python.apply(plt.scatter, args,kv) plt.xlim(-2,2) plt.ylim(-2,2) plt.title(string.format('griddata test (%i points)', 10npts)) --plt.savefig(figname, 700dpi, 500 'white') -- pg.figname = figname ; pg.dpi = dpi c1 args = python.SetFillColoreval( 42 "[figname]") c1 kv = python.SetGrideval("{'dpi': dpi ,'facecolor' :'white'}") CS = python.apply(plt.savefig, args,kv)end\stopluacode
n = 20
x, y = array( 'd' ), array( 'd' )
for i in range( n ): x.append( 0.\def\testSCIPY[#1*i )]{% y.append( 10*sin( x\getparameters[iscipy]+0.2 ) )[#1]%  gr = TGraph\ctxlua{testSCIPY( n"\csname scipyfigname\endcsname", x, y ) gr.SetLineColor( 2 ) gr.SetLineWidth( 4 ) gr.SetMarkerColor( 4 ) gr.SetMarkerStyle( 21 ) gr.SetTitle( 'a simple graph' ) gr.GetXaxis().SetTitle( 'X title' ) gr.GetYaxis().SetTitle( 'Y title' ) gr.Draw( 'ACP' ) c1.Update() c1.Print(filename "\csname scipydpi\endcsname")}%\externalfigure[\csname scipyfigname\endcsname]]) run = pg.run run(filename)end%\stopluacode}
\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: separate python code from lua code .<br/>Save this in <tt>test-ROOT1.py</tt> == Python Imaging Library (so it's also easy to testPIL) :<pre>from ROOT import TCanvas, TGraph ,TGraphErrors,TMultiGraphfrom ROOT import gROOTfrom math import sinfrom array import array==
def run{| class="wikitable" |-|<texcode>\startluacodefunction testPIL(imageorig,imagesepia) require(filename"python"): c1 PIL_Image = TCanvaspython.import("c1PIL.Image",) PIL_ImageOps = python.import("multigraphPIL.ImageOps",200,10,700,500) c1 python.SetGridexecute([[def make_linear_ramp(white): ramp = [] r, g, b = white # draw a frame to define the for i in range(255): mg = TMultiGraph ramp.extend((r*i/255, g*i/255, b*i/255)) # create first graphreturn ramp]]) n = 24;-- make sepia ramp (tweak color as necessary) x sepia = arraypython.eval('d'"make_linear_ramp((255, 240,range(24192))") data im = file('data')PIL_Image.readlinesopen(imageorig) for line in data: line -- convert to grayscale if not(im.mode == line.strip("L") then y im = array('d',[float(d) for d in lineim.splitconvert("L")]) gr = end -- TGraph(noptional: apply contrast enhancement here,x,y)e.g. gr im = PIL_ImageOps.Fitautocontrast("pol6","q"im) mg -- apply sepia palette im.Addputpalette(grsepia)
mg-- convert back to RGB so we can save it as JPEG -- (alternatively, save it in PNG or similar) im = im.Drawconvert("apRGB")
im.save(imagesepia)end\stopluacode \def\SepiaImage#force drawing of canvas to generate the fit TPaveStats1#2{% c1.Update\ctxlua{testPIL("#1","#2")}% c1\startcombination[2*1]{\externalfigure[#1]}{\ss Orig.Print(filename)}{\externalfigure[#2]}{\ss Sepia}\stopcombination}
</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
\ctxluaSepiaImage{test_ROOT("datalena.pdf")jpg}\rotate[rotation=90]{\externalfigure[datalena-sepia.pdf]jpg}
\stopTEXpage
\stoptext
</texcode> || [[Image:Test-ROOT1PIL.jpgpng|300px330px]]
|}
 
 
== 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>
r = wikiversity.querycategory(title)
local j = 0
local res = r[j] or {} while res do local d = string.format("\%s\\par",string.gsub(tostring(res),'_',' ')) tex.sprint(tex.ctxcatcodes,d) j = j+1 res = r[j] endend\stopluacode  \startluacodefunction simplereports(title) require("python") pg = python.globals() wikiversity = python.import("wikidbxml_queryTxn") r = wikiversity.simplereports(title) local j = tonumber(r) for v = 0,j-1 do local d = string.format("\\input reps\%04d ",v) tex.sprint(tex.ctxcatcodes,d) end print( j )end\stopluacode</texcode> and test it with  <texcode>\starttext{\bfb Query for 'geometr':}\ctxlua{listtitles("geometr")}%\ctxlua{simplereports("geometr")}%\stoptext
</texcode>
(query results are stored in reps0001.tex ,reps0002.tex ,..and test it with  <texcode>\starttext{\bfb Query for 'geometr':}\ctxlua{listtitles("geometr")}%\ctxlua{simplereports("geometr"so on.)}%\stoptext</texcode>