STM publishing: tools, technologies and change A WordPress site for STM Publishing

14Dec/11Off

LuaTeX: nodes, graphics and PDF coordinate transformation matrices

Posted by Graham Douglas

Powered by MathJax

Note: if you want to zoom in on the matrices, right-click over an equation and set the MathJax parameters to your preferred values:

Zooming MathJax

Introduction

In this post I'll introduce a nice matrix-manipulation library called lua-matrix. It is written in pure Lua and so should be usable with any LuaTeX installation. You can download the code from GitHub. You can use lua-matrix as a convenient method to create PDF transformation matrices.

Note: where to install Lua code modules
The texmf.cnf variable you need to check is LUAINPUTS. See this newsgroup post for more details.

Tip: a Git tool for Windows users
Like many open source projects lua-matrix is hosted on GitHub. If you are a Windows user you may need to install some utilities that let you "check out" a copy of the code on repositories such as GitHub or others based on SVN. For SVN repositories there is the excellent TortoiseSVN but for Git repos I use a free tool called Git for Windows.

Very brief summary of matrices

Quoting from the PDF standard:

"PDF represents coordinates in a two-dimensional space. The point (x, y) in such a space can be expressed in vector form as [x y 1]. The constant third element of this vector (1) is needed so that the vector can be used with 3-by-3 matrices. The transformation between two coordinate systems is represented by a 3-by-3 transformation matrix written as

$$\displaystyle \left( \matrix{ a & b & 0 \cr c & d & 0 \cr e & f & 1 \cr} \right)$$

Because a transformation matrix has only six elements that can be changed, it is usually specified in PDF as the six-element array [a b c d e f].

Note: This is method of representing coordinates is referred to as homogeneous coordinates.

Rotation

The matrix for rotation by an angle \(\theta\) counter clockwise about the origin:
$$\displaystyle \left( \matrix{ \cos (\theta) & \sin (\theta) & 0 \cr -\sin (\theta) & \cos (\theta) & 0 \cr 0 & 0 & 1 \cr} \right)$$

This is expressed in PDF code as \(\cos(\theta)\ \sin(\theta)\ -\hskip-2pt\sin(\theta)\ \cos(\theta)\ 0\ 0\) cm

Translation

The matrix for translation by \((t_x, t_y)\) relative to the origin:

$$\displaystyle \left( \matrix{ 1 & 0 & 0 \cr 0 & 1 & 0 \cr t_x & t_y & 1 \cr} \right)$$

This is expressed in PDF code as \(1\ 0\ 0\ 1\ t_x\ t_y\) cm

Scale

The matrix for scaling by \(s_x\) in the horizonal direction and \(s_y\) in the vertical direction is:

$$\displaystyle \left( \matrix{ s_x & 0 & 0 \cr 0 & s_y & 0 \cr 0 & 0 & 1 \cr} \right)$$

This is expressed in PDF code as \(s_x\ 0\ 0\ s_y\ 0\ 0\) cm

Demonstration graphic

The following simple graphic (shown as inline SVG) will be used to explore transformations. The equivalent PDF graphic (in hand-coded PDF data) is shown below.

Equivalent PDF data

The following PDF code will draw a very similar graphic:

q % save graphics state
1 j % set the line join style
1 J % set the line cap style
10 M % set the miter limit
%Set the stroking color space to DeviceRGB
0 0 0 RG % black
% draw the axes
0 0 m
0.5 w
0 30 l
0 0 m
30 0 l
S % stroke
% draw the red arrow head on x axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
1 0 0 rg % red
% translate to end of line on x-axis
1 0 0 1 30 0 cm
% draw an arrowhead
0 0 m % move to the origin
0 1.5 l
2.5 0 l
0 -1.5 l
h % close the current subpath
B % fill and stroke
Q % restore graphics state
% draw the blue arrow head on y axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
0 0 1 rg % blue
% translate to end of line on y-axis
1 0 0 1 0 30 cm
% draw an arrowhead
0 0 m % move to the origin
-1.5 0 l
 0 2.5 l
1.5 0 l
h % close the current subpath
B % fill and stroke
% restore graphics state
Q
Q

Creating a graphic with LuaTeX nodes

As usual, a simple plain TeX setup.

\pdfoutput=1
\pdfcompresslevel=0
\hoffset-1in
\voffset-1in
\pdfpageheight=50mm
\pdfpagewidth=50mm
\vsize=50mm
\hsize=50mm
\topskip=0pt
\maxdepth=0pt
\nopagenumbers

\directlua{
grafik = node.new("whatsit","pdf_literal")
grafik.mode=0
grafik.data="  q % save graphics state
1 j % set the line join style
1 J % set the line cap style
10 M % set the miter limit
%Set the stroking color space to DeviceRGB
0 0 0 RG % black
% draw the axes
0 0 m
0.5 w
0 30 l
0 0 m
30 0 l
S % stroke
% draw the red arrow head on x axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
1 0 0 rg % red
% translate to end of line on x-axis
1 0 0 1 30 0 cm
% draw an arrowhead
0 0 m % move to the origin
0 1.5 l
2.5 0 l
0 -1.5 l
h % close the current subpath
B % fill and stroke
Q % restore graphics state
% draw the blue arrow head on y axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
0 0 1 rg % blue
% translate to end of line on y-axis
1 0 0 1 0 30 cm
% draw an arrowhead
0 0 m % move to the origin
-1.5 0 l
 0 2.5 l
1.5 0 l
h % close the current subpath
B % fill and stroke
% restore graphics state
Q
Q "

tex.box[1000]=node.hpack(grafik)
}

Here is out new graphic \vskip 35mm
\noindent\hskip 15mm \copy1000
\bye

Notes about the PDF graphic

In the code above we have not assigned any size to the box containing the graphic, hence I needed to add \vskip 35mm \noindent\hskip 15mm to push the graphic into a space where it will be seen. To give the graphic some dimensions, we'll need to add code such as

tex.box[1000].width = width value in sp
tex.box[1000].height = height value in sp
tex.box[1000].depth = depth value in sp

where the values assigned are in sp (special points). You may recall that 65536sp = 1 TeX point, where 72.27 TeX points = 1 inch = 72 PostScript points (same as default in PDF).

As far as the LuaTeX engine is concerned, the box containing the graphic has zero size, we have to tell LuaTeX how big we want it to be. In addition, the line widths, based on the above code, will be affected by any scaling but it is not too difficult to fix that.

The Lua code

The idea is that we create a number of functions based on the lua-matrix library and save those functions into a Lua module called "mymatrix.lua". Within "mymatrix.lua" we import the lua-matrix code via its module called "matrix" which we load with:

local matrix=require("matrix")

Our simple API

Here are the functions defined within our "mymatrix.lua" module:

  • rotate(angle): returns a 3 x 3 rotation matrix (angle positive for counter clockwise)
  • translate(tx,ty): returns a 3 x 3 translation matrix (tx, ty are translations in x, y directions)
  • scale(sx,sy): returns a 3 x 3 scaling matrix (sx, sy are scaling in x,y directions)
  • dump(mtx): simple debugging function (mtx = 3 x 3 matrix)
  • toinlinetex(mtx): returns inline TeX code so we can typeset the matrix (mtx = 3 x 3 matrix)
  • todisplaytex(mtx): returns display TeX code so we can typeset the matrix (mtx = 3 x 3 matrix)
  • topdf(mtx): returns matrix in PDF code format (mtx = 3 x 3 matrix)

Here's the source code for mymodule.lua. One huge advantage of putting Lua code into Lua modules is that it greatly simplifies dealing with \catcode issues. Note that within code saved in Lua files you use the regular Lua comment "--" mechanism and not the TeX comment "%" mechanism. You can use "%" when the code is embedded in a \directlua{...} call.

module("mymatrix",package.seeall)
local matrix=require("matrix")
local rad=math.rad
local sin=math.sin
local cos=math.cos

-- Function to generate PDF transformation (rotation) matrices.
function rotate(angle)
local rot = matrix {{cos(rad(angle)),sin(rad(angle)),0},{-sin(rad(angle)),cos(rad(angle)),0},{0,0,1}}
return rot
end

-- Function to generate PDF transformation (translation) matrices.
function translate(tx,ty)
local tran = matrix {{1,0,0},{0,1,0},{tx,ty,1}}
return tran
end

-- Function to generate PDF transformation (scale) matrices.
function scale(sx,sy)
local scale = matrix {{sx,0,0},{0,sy,0},{0,0,1}}
return scale
end

function dump(mtx)
for i=1,3 do
	for j=1,3 do
		print("(i,j)=("..i..","..j..")="..mtx[i][j])
end
end
end

function todisplaytex(mtx)
texcode=string.format([[$$\left(\matrix {%3.3f & %3.3f & %3.3f \cr %3.3f & %3.3f & %3.3f \cr %3.3f & %3.3f & %3.3f \cr } \right)$$]],
	mtx[1][1], mtx[1][2], mtx[1][3],mtx[2][1], mtx[2][2], mtx[2][3],
	mtx[3][1], mtx[3][2], mtx[3][3])
	return texcode
end

function toinlinetex(mtx)
texcode=string.format([[$\left(\matrix {%3.3f & %3.3f & %3.3f \cr %3.3f & %3.3f & %3.3f \cr %3.3f & %3.3f & %3.3f \cr } \right)$]],
	mtx[1][1], mtx[1][2], mtx[1][3],mtx[2][1], mtx[2][2], mtx[2][3],
	mtx[3][1], mtx[3][2], mtx[3][3])
	return texcode
end

function topdf(mtx)
pdftext = string.format("%3.3f %3.3f %3.3f %3.3f %3.3f %3.3f  cm",
	mtx[1][1], mtx[1][2],mtx[2][1], mtx[2][2], mtx[3][1], mtx[3][2])
	return pdftext
end

Full example

\pdfoutput=1
\pdfcompresslevel=0
\hoffset-1in
\voffset-1in
\pdfpageheight=350mm
\pdfpagewidth=150mm
\vsize=350mm
\hsize=150mm
\topskip=0pt
\maxdepth=0pt
\nopagenumbers
\directlua{require("mymatrix")}

\directlua{
% We'll create an non-transformed graphic and store it in box 1000
grafik = node.new("whatsit","pdf_literal")
grafik.mode=0
grafik.data="
q % save graphics state
1 j % set the line join style
1 J % set the line cap style
10 M % set the miter limit
%Set the stroking color space to DeviceRGB
0 0 0 RG % black
% draw the axes
0 0 m
0.5 w
0 30 l
0 0 m
30 0 l
S % stroke
% draw the red arrow head on x axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
1 0 0 rg % red
% translate to end of line on x-axis
1 0 0 1 30 0 cm
% draw an arrowhead
0 0 m % move to the origin
0 1.5 l
2.5 0 l
0 -1.5 l
h % close the current subpath
B % fill and stroke
Q % restore graphics state
% draw the blue arrow head on y axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
0 0 1 rg % blue
% translate to end of line on y-axis
1 0 0 1 0 30 cm
% draw an arrowhead
0 0 m % move to the origin
-1.5 0 l
 0 2.5 l
1.5 0 l
h % close the current subpath
B % fill and stroke
% restore graphics state
Q
Q "
% store graphic in box 1000
tex.box[1000]=node.hpack(grafik)

% create some transformation matrices
mtx1 = mymatrix.rotate(45)
mtx2 = mymatrix.scale(1.5,2)
mtx3 = mymatrix.translate(15,15)

% Now we copy our untransformed node
% and add the PDF transformation matrices to
% rotate, scale etc.

% We'll do a rotation and store in box 1001
grafik2 = node.copy(grafik)
grafik2.mode=0
cm = mymatrix.topdf(mtx1)
% copy the PDF data from the untransformed
% graphic and add the PDF rotation matrix
grafik2.data="q ".. cm ..grafik.data.." Q "
% store graphic in box 1001
tex.box[1001]=node.hpack(grafik2)

% We'll do a scale and store in box 1002
grafik3 = node.copy(grafik)
grafik3.mode=0
cm = mymatrix.topdf(mtx2)
% copy the PDF data from the untransformed
% graphic and add the PDF rotation matrix
grafik3.data="q ".. cm ..grafik.data.." Q "
% store graphic in box 1002
tex.box[1002]=node.hpack(grafik3)

% Now multiply the scale and rotation matrices
% --- experiment with different combinations
combo=mtx1*mtx2

grafik4 = node.copy(grafik)
grafik4.mode=0
cm = mymatrix.topdf(combo)
% copy the PDF data from the untransformed
% graphic and add the result of multiplication
grafik4.data="q ".. cm ..grafik.data.." Q "

% store graphic in box 1002
tex.box[1003]=node.hpack(grafik4)

% Now multiply the scale, rotation and translation
% matrices --- experiment with different combinations
combo2=mtx1*(mtx2*mtx3)

grafik5 = node.copy(grafik)
grafik5.mode=0
cm = mymatrix.topdf(combo2)
% copy the PDF data from the untransformed
% graphic and add the result of multiplication
grafik5.data="q ".. cm ..grafik.data.." Q "

% store graphic in box 1002
tex.box[1004]=node.hpack(grafik5)

}

Here are our graphics \vskip 35mm
\noindent\hskip 15mm \copy1000 Default graphic
\vskip 35mm
\noindent\hskip 15mm \copy1001 Rotated graphic =  \directlua{tex.sprint(mymatrix.toinlinetex(mtx1))}
\vskip 35mm
\noindent\hskip 15mm \copy1002 Non-uniformly scaled graphic = \directlua{tex.sprint(mymatrix.toinlinetex(mtx2))}
\vskip 35mm
\noindent\hskip 15mm \copy1003 Rotation $\times$ scale = \directlua{tex.sprint(mymatrix.toinlinetex(combo))}
\vskip 35mm
\noindent\hskip 15mm \copy1004 Rotation $\times$ scale $\times$ translate =\directlua{tex.sprint(mymatrix.toinlinetex(combo2))}
\bye

Resulting PDF

As usual, through the Google Docs viewer or download PDF here.

Downloads

Download all code.

1Jan/11Off

Why I admire MathJax

Posted by Graham Douglas

It is, in some ways, a deep irony that the community which spawned the web (i.e., physicists and mathematicians) should, until recently, have had such a hard time using the web to fluently and easily communicate in the natural language of their disciplines: mathematics. Certainly, domain-specific solutions have evolved through the use and combination of tools and techniques such as jsMath, MathML, SVG, bitmaps, LaTeX text and so forth. The author of this post wrote a COM-based (i.e., Windows!) DVI-to-SVG conversion tool 6 years ago but, at the time, the ultra-specific environment in which it worked precluded its mainstream use. Anyone recall Adobe's SVG plug-in for Internet Explorer...? It has taken nearly 20 years for the cluster of associated technologies to catch up and coalesce into providing a viable and mainstream solution: MathJax, which delivers into the browser the exquisite beauty of the typesetting algorithms developed by Donald Knuth in the late 1970s. Anybody who has read the infamous Appendix G of the TeXBook or the article Appendix G illuminated will, or should, have profound respect and admiration for the work of jsMath and MathJax. Replication of the TeX math-typesetting algorithms in JavaScript (or any language!) is an incredible achievement for which the authors and financial sponsors of MathJaX should be applauded, for they have made a major contribution to the future of scientific communication via the web ecosystem. Three cheers to them!

Just in passing, from deciding to set-up this WordPress blog, to downloading + installing WordPress and MathJax installation was about 1.5 hours in total, which just goes to show how easy it is, even for a non-expert like me! Here's a simple formula typeset in TeX/MathJax. Assuming you're using a modern browser, right-click over the formula to see the options presented by MathJax.

\(\vec{F}_g=-F\frac{m_1 m_2}{r^2} \vec{e}_r\)

MathJax, you totally rock!

Filed under: MathJaX Comments Off