Changes

Jump to navigation Jump to search
=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 !! '''
* ghostscript 8.64 ✔ [[#Ghostscript|here]]
* graphviz 2.24.0 ✔ [[#Graphviz|here]]
* ImageMagick-6.4.9 with pythonmagickwand ✔[[#ImageMagick|here]]
* fontforge 20090224 ✔ [[#Fontforge|here]] Useful to check symbols collision, and if one want to play with the last fontforge, eg to draw the outline of a glyph .
* R-2.8.1 with rpy2-2.0.3 (For Maurizio "Mau" Himmelman , GUIT) ✔ [[#R|here]] (see someone says also [http://micahelliott.com/2009/03/considering-r-as-python-supplement hereconsidering-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> 
{|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
 
-- 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.eval("[xi,yi,zi,15]")
kv = python.eval("{'linewidth': 0.5 ,'colors' :'k'}")
CS = python.apply(plt.contour, args,kv)
--
pg.jet = plt.cm.jet
args = python.eval("[xi,yi,zi,15]")
kv = python.eval("{'cmap': jet}")
CS = python.apply(plt.contourf, args,kv)
-- draw colorbar
plt.colorbar()
-- plot data points.
pg.x = x; pg.y = y
args = python.eval("[x,y]")
kv = python.eval("{'marker': 'o', 'c':'b','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)',npts))
--plt.savefig(figname, dpi, 'white')
--
pg.figname = figname ; pg.dpi = dpi
args = python.eval("[figname]")
kv = python.eval("{'dpi': dpi ,'facecolor' :'white'}")
CS = python.apply(plt.savefig, args,kv)
end
\stopluacode
python.execute([[
def run(filename):
from ROOT import TCanvas, TGraph
from ROOT import gROOT
from math import sin
from array import array
 
 
gROOT.Reset()
 
c1 = TCanvas( 'c1', 'A Simple Graph Example', 200, 10, 700, 500 )
 
c1.SetFillColor( 42 )
c1.SetGrid()
 
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> || [[Image:TestsinTest-scipy.jpgpng|512px600px]]
|}
We can do a bit better: separate python code from lua code .<br/>== Python Imaging Library (PIL) == {| class="wikitable" Save this in <tt>test|-ROOT1.py|</tttexcode> (so it's also easy to test) :<pre>\startluacodefrom ROOT import TCanvasfunction testPIL(imageorig, TGraph ,TGraphErrors,TMultiGraphimagesepia)from ROOT import gROOT require("python")from math PIL_Image = python.import sin("PIL.Image") from array PIL_ImageOps = python.import array("PIL.ImageOps") python.execute([[def runmake_linear_ramp(filenamewhite): c1 ramp = TCanvas("c1"[] r,"multigraph"g,200,10,700,500b = white for i in range(255): c1 ramp.SetGridextend((r*i/255, g*i/255, b*i/255)# draw a frame to define the rangereturn ramp mg = TMultiGraph(]]) # create first graph 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) gre.g.Fit("pol6","q") mg im = PIL_ImageOps.Addautocontrast(grim)
mg-- apply sepia palette im.Drawputpalette("ap"sepia)
#force drawing of canvas -- convert back to generate the fit TPaveStatsRGB so we can save it as JPEG c1-- (alternatively, save it in PNG or similar) im = im.Updateconvert("RGB"c1im.Printsave(filenameimagesepia)end\stopluacode \def\SepiaImage#1#2{%\ctxlua{testPIL("#1","#2")}%\startcombination[2*1]{\externalfigure[#1]}{\ss Orig.}{\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 ==
''ImageMagick® '' ([http://www.imagemagick.org/script/index.php here] ) ''is a software suite to create, edit, and compose bitmap images. It can read, convert and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF. Use ImageMagick to translate, flip, mirror, rotate, scale, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves.
''
There are at least two python bindings, and this time I consider
[http://www.procoders.net/?p=39 PythonMagickWand] which is a binding "ala" ctypes way .
Code is simple<texcode>\usetypescriptfile[type-gentium]\usetypescript[gentium]\setupbodyfont[gentium,10pt]\setuppapersize[A5][A5]\setuplayout[height=middle,topspace=1cm,header={2\lineheight},footer=0pt,backspace=1cm,margin=1cm, width=middle]  \startluacodefunction testimagemagick(box,t) local w local h local d local f local res = 118.11023622047244094488 -- 300 dpi local opacity = 25 local sigma = 15 local x = 10 local y = 10   require("python") pg = python.globals() PythonMagickWand = python.import("PythonMagickWand") w = math.floor((tex.wd[box] / 65536 ) / 72.27 * 2.54 * res ) h = math.floor(((tex.ht[box] / 65536) + (tex.dp[box] / 65536)) / 72.27 *2.54 *res ) f = string.format("%s.png",t)  wand = PythonMagickWand.NewMagickWand() background = PythonMagickWand.NewPixelWand(0) -- PythonMagickWand.MagickNewImage(wand,w,h,background) PythonMagickWand.MagickNewImage(wand,w,h,background)  PythonMagickWand.MagickSetImageResolution(wand,res,res) PythonMagickWand.MagickSetImageUnits(wand,PythonMagickWand.PixelsPerCentimeterResolution) PythonMagickWand.MagickShadowImage(wand,opacity,sigma,x,y) PythonMagickWand.MagickWriteImage(wand ,f)   print(w,h,f)end\stopluacode    \def\testimagemagick[#1]{%\getparameters[imagemagick][#1]%\ctxlua{testimagemagick(\csname imagemagickbox\endcsname,"\csname imagemagickfilename\endcsname")}%} \newcount\shdw\long\def\startShadowtext#1\stopShadowtext{%\bgroup%\setbox0=\vbox{#1}%\testimagemagick[box=0,filename={shd-\the\shdw}]%%%\defineoverlay[backg][{\externalfigure[shd-\the\shdw.png]}]%\framed[background=backg,frame=off,offset=4pt]{\box0}%%%\framed{\box0}\global\advance\shdw by 1%\egroup%} \starttext\startTEXpage%\startShadowtext%\input tufte\stopShadowtext%\stopTEXpage\stoptext</texcode>And here is the result: [[Image:Test-imagemagick.png]] == Fontforge ==
In this example, we will use Metapost to draw a bezier curve of a glyph (''Note: starting from Metapost 1.200 it is now possible to get the actual path drawing routines from a font glyph, so this example is only to show how to translate a path in metapost'').<br/>
We will use 3-layer approach:
def getcurve(self,letter):
self.glname = letter
res_Array = []
res = dict()
try :
#glyph_letter = [ g for g in self.font.glyphs() if g.glyphname == self.glname][0] g = self.font[letter]
except Exception ,e :
res['err'] = str(e)
res_Array.append(res) return resres_Array cntlayer_idx = glyph_letter0; for layer_name in g.layers: layer = g.layers[1layer_name] for contour_idx in range(len(layer)): res = dict() contour = layer[0contour_idx] contour_name = contour.name res['name']= contour.name res['is_quadratic'] = cntcontour.is_quadratic res['closed'] = cntcontour.closed res['points'] = [(p.x,p.y,"%i" %p.on_curve) for p in cnt contour ] res['design_size'] = self.font.design_size res['em'] = self.font.em res_Array.append(res) return resres_Array 
def drawmpostpath(self,letter):
res_Array = self.getcurve(letter)
state = 0
paths = ''
for res in res_Array:
temp = ''
for p in res['points'] :
if p[2]=='1' :
if state == 1 :
temp = temp + '-- (%s,%s)' %(p[0] ,p[1]) ; state = 1; continue
else:
temp = temp + '.. (%s,%s)' %(p[0] ,p[1]) ; state = 1; continue
if state == 1 : temp = temp + ' .. controls (%s,%s)' %(p[0],p[1]) ; state =2; continue
if state == 2 : temp = temp + ' and (%s,%s) ' %(p[0],p[1]) ; state =0; continue
if res['closed'] :
if state == 1 :
temp = 'draw ' + temp[2:] + " -- cycle;\n"
else:
temp = 'draw ' + temp[2:] + " .. cycle;\n"
else:
temp = 'draw ' + temp[2:] + ";\n"
paths = paths + temp
return paths
def getmpostoutline(self,letter):
res = self.getcurve(letter)
path = '..'.join( [str((p[0],p[1])) for p in res['points'] if p[2] == '1'] )
return path
def getmpostpoints(self,letter):
res = self.getcurve(letter)
path = [str((p[0],p[1])) for p in res['points'] if p[2] == '1']
return path
def getmpostpointsSugardrawmpostpoints(self,letter): res res_Array = self.getcurve(letter) path dots = '' for res in res_Array: temp = 'drawdot \n'.join( ["drawdot %s;" %str((p[0],p[1])) for p in res['points'] if p[2] == '1'] )+ "\n" dots = dots + temp return 'drawdot ' +pathdots
if __name__ == '__main__':
s = simpledraw("koeieletterslmmono10-regular.pfbotf") #res = s.getmpostpointsSugar('C') #print res #print s.getmpostoutline('C') print s.getcurve('e') print s.drawmpostpath('e') print s.drawmpostpoints('e') 
</pre>
Next lua layer, which in this case is embed in a tex file:
<texcode>
 
\setupcolors[state=start]
 
 
\startluacode
function testFontforge(fontfile,letter)
testoutlines = python.import("test-fontforge")
s = testoutlines.simpledraw(fontfile)
g = s.getmpostoutlinedrawmpostpath(letter) p = s.getmpostpointsSugardrawmpostpoints(letter) --print( string.format("\%s = \%s ==", letter,g )) tex.sprint(tex.ctxcatcodes,"\\startMPcode") tex.sprint(tex.ctxcatcodes,"pickup pencircle scaled 1pt;") tex.sprint(tex.ctxcatcodes,string.format("draw \%s .. cycle;",g) ) tex.sprint(tex.ctxcatcodes,"pickup pencircle scaled 8pt;") tex.sprint(tex.ctxcatcodes,string.format("\%s",p) ) tex.sprint(tex.ctxcatcodes,"\\stopMPcode")
end
\stopluacode
And this is the result: <br/>
[[Image:Test-fontforge.png|900px]]
 
...ok,it's not correct (why?), but it looks funny :)
== Ghostscript ==
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>
def managepara(c,res):
if c.tag == 'para' and (len(c.text.strip()) > 0is not None):
res.append(c.text.strip()+r"\par")
if c.tag == 'para' and (len(c.getchildren())>0):
#open('res.dbk','w').write( " ".join(res.split()) )
res = getConTeXt(title,res)
return res except Exception,e: print "error on read:" ,e fcntl.flock(lockfile, fcntl.LOCK_UN) lockfile.close() def writeres(title,preamble,postamble,filename):  res = getArtitleByTitle(title=title) if res is not None : res = res.replace('&',r'\&') res = res.replace('#',r'\#') else: res = '' open(filename,'wb').write( '\n'.join((preamble,res,postamble)) )  pass if __name__ == '__main__':  preamble = r"""\usetypescriptfile[type-gentium]\usetypescript[gentium]\setupbodyfont[gentium,10pt]\setuppapersize[A5][A5]\setuplayout[height=middle,topspace=1cm,header={2\lineheight},footer=0pt,backspace=1cm,margin=1cm, width=middle]\starttext"""  postamble = r"""\stoptext"""   title="Primary mathematics/Numbers" filename = 'res.tex' writeres(title,preamble,postamble,filename)</pre> And in the end mkiv wrapper:<texcode>\usetypescriptfile[type-gentium]\usetypescript[gentium]\setupbodyfont[gentium,10pt]\setuppapersize[A5][A5]\setuplayout[height=middle,topspace=1cm,header={2\lineheight},footer=0pt,backspace=1cm,margin=1cm, width=middle]  \startluacodefunction testdbxml(title,preamble,postamble,filename) require("python") pg = python.globals() wikiversity = python.import("wikidbxml_queryTxn") wikiversity.writeres(title,preamble,postamble,filename) end\stopluacode \def\testdbxml[#1]{%\getparameters[dbxml][#1]%\ctxlua{testdbxml("\csname dbxmltitle\endcsname","\csname dbxmlpreamble\endcsname", "\csname dbxmlpostamble\endcsname","\csname dbxmlfilename\endcsname")}%\input \csname dbxmlfilename\endcsname %}   \starttext\testdbxml[title={Primary mathematics/Numbers}, preamble={}, postamble={}, filename={testres.tex}]\stoptext</texcode> Here here the result: <table class="wikitable"> <tr><td></td> <td>[[Image:Dbxml-1.png]]</td></tr><tr><td>[[Image:Dbxml-2.png]]</td> <td>[[Image:Dbxml-3.png]]</td></tr></table> One can also use sqlite that comes with python to query for titles <tt>category.db</tt>made from (for example) <tt>enwikiversity-20090627-category.sql</tt>,so reports are more simpler:just put this in python code above, right before 'if __name__' ...:<pre>import sqlite3def querycategory(title): conn = sqlite3.connect('category.db') c = conn.cursor() t = (title,) c.execute('select cat_title from category where cat_title like "%%%s%%" ;' % t) res = [row[0] for row in c] conn.commit() c.close() return res  def simplereports(title): res = querycategory(title) j = 0 for r in res: g = r.replace('_',' ') print g title= g.encode('utf8') filename = 'reps%04d.tex' % j writeres(title,'','',filename) j = j+1 return j </pre> Similary, add this to tex code<texcode>\startluacodefunction listtitles(title) require("python") pg = python.globals() wikiversity = python.import("wikidbxml_queryTxn") 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>
def writeres(title,preamble,postamble,filename):  res = getArtitleByTitle(title=title) res = res.replace('&',r'\&')and test it with
open(filename,'wb').write( '\n'.join((preamble,res,postamble)) )
 
pass
 
if __name__ == '__main__':
 
preamble = r"""\usetypescriptfile[type-gentium]
\usetypescript[gentium]
\setupbodyfont[gentium,10pt]
\setuppapersize[A5][A5]
\setuplayout[height=middle,topspace=1cm,header={2\lineheight},footer=0pt,backspace=1cm,margin=1cm, width=middle]
\starttext"""
 
postamble = r"""\stoptext"""
 
 
title="Primary mathematics/Numbers"
filename = 'res.tex'
writeres(title,preamble,postamble,filename)
</pre>
 
And in the end mkiv wrapper:
<texcode>
\usetypescriptfile[type-gentium]
\usetypescript[gentium]
\setupbodyfont[gentium,10pt]
\setuppapersize[A5][A5]
\setuplayout[height=middle,topspace=1cm,header={2\lineheight},footer=0pt,backspace=1cm,margin=1cm, width=middle]
 
 
\startluacode
function testdbxml(title,preamble,postamble,filename)
require("python")
pg = python.globals()
wikiversity = python.import("wikidbxml_queryTxn")
wikiversity.writeres(title,preamble,postamble,filename)
end
\stopluacode
 
\def\testdbxml[#1]{%
\getparameters[dbxml][#1]%
\ctxlua{testdbxml("\csname dbxmltitle\endcsname","\csname dbxmlpreamble\endcsname",
"\csname dbxmlpostamble\endcsname","\csname dbxmlfilename\endcsname")}%
\input \csname dbxmlfilename\endcsname %
}
 
 
 
\starttext
{\testdbxml[title={Primary mathematics/Numbersbfb Query for 'geometr':}, preamble=\ctxlua{listtitles("geometr")},% postamble={}, filename=\ctxlua{testres.texsimplereports("geometr")}]%
\stoptext
</texcode>
Here here the result: <table class="wikitable"> <tr><td></td> <td>[[Image:Dbxml-1(query results are stored in reps0001.png]]</td></tr><tr><td>[[Image:Dbxml-2tex ,reps0002.png]]</td> <td>[[Image:Dbxml-3tex ,.png]]</td></tr></table>.and so on.)

Navigation menu