\documentclass[10pt,a4paper]{scrartcl}

\usepackage{lmodern}

\title{\texttt{php-eps-macros}}
\subtitle{A Set of Helper Macros in PHP to Write EPS Files}
\author{Romaric Pujol\\\footnotesize{\texttt{romaric.pujol@insa-lyon.fr}}}
\date{September 28, 2013}

\usepackage{graphicx}
\usepackage{listings}
\usepackage{caption}

\usepackage{amsmath}

\newcommand\code[1]{\lstinline{#1}}

\lstset{showspaces=false,showstringspaces=false}
\lstset{basicstyle=\footnotesize\ttfamily}

\newcommand\PS{PostScript}

\newenvironment{note}{\par\leavevmode\medskip\textbf{Note.} }{\par\leavevmode\medskip}

\usepackage{hyperref}

\begin{document}
\maketitle
\section{Introduction}
This document describes a set of PHP helper files and scripts to generate EPS
   (Encapsulated \PS) files.
When writing documents in \LaTeX, the author might want to include figures in
   it.
Figures can be generated in many ways by many existing softwares, but the
   author might want to make its own from scratch.
If she likes programming, the PostScript language is a wonderful option to
   consider seriously.

In this document, we assume that the reader is already familiar with EPS files
and the \PS{} language.

\section{Directory Content}
\begin{itemize}
\item \texttt{arrow-head.php}, see Section~\ref{ssec:arrow-head.php},
\item \texttt{coords.php}, see Section~\ref{ssec:coords.php},
\item \texttt{eps-header.php}, see Section~\ref{ssec:eps-header.php},
\item \texttt{fatal.php}, see Section~\ref{ssec:fatal.php},
\item \texttt{hyperbolic.php}, see Section~\ref{ssec:hyperbolic.php},
\item \texttt{newton-solver.php}, see Section~\ref{ssec:newton-solver.php},
\item \texttt{plotfunction-bezier-stupid-hom.php}, see Section~\ref{ssec:plotfunction-bezier-stupid-hom.php},
\item \texttt{plotimplicit-bezier-stupid-hom.php}, see Section~\ref{ssec:plotimplicit-bezier-stupid-hom.php},
\item \texttt{plotparametric-bezier-stupid-hom.php}, see Section~\ref{ssec:plotparametric-bezier-stupid-hom.php},
\item \texttt{SmartInsertFont.php}, see Section~\ref{ssec:SmartInsertFont.php},
\item \texttt{trigonometry.php}, see Section~\ref{ssec:trigonometry.php},
\item \texttt{utils.php}, see Section~\ref{ssec:utils.php},
\item \texttt{vector.php}, see Section~\ref{ssec:vector.php}.
\end{itemize}

\section{Structure of your PHP file}
Your PHP file should start as follows:
\lstset{language=PHP}
\begin{lstlisting}
<?php
   $lx=0;
   $ly=0;
   $ux=200;
   $uy=300;
   $author="Romaric Pujol";
   $title="An EPS example file";
   $date="2013/09/28";
   require_once("eps-header.php");
?>
\end{lstlisting}

Then, running \code{php file.php} will output the following EPS header:
\begin{lstlisting}
%!PS-Adobe-2.0 EPSF-3.0
%%BoundingBox: 0 0 200 300
%%Creator: Romaric Pujol
%%CreationDate: 2013/09/28
%%Title: An EPS example file
%%Pages: 1
%%EndComments
\end{lstlisting}

Afterwards, you're free to mix PHP and \PS.

\section{Description of the PHP Files}
\subsection{\texttt{arrow-head.php} --- Making Arrow heads}
\label{ssec:arrow-head.php}
This file implements one \PS{} function to draw an arrow head.
A typical arrow head is represented on Figure~\ref{fig:arrow-head-explained}.
\begin{figure}[ht!]%
\centering
\includegraphics{figs/arrow-head/arrow-head-measures}%
\caption{Arrow head}%
\label{fig:arrow-head-explained}
\end{figure}

The \code{require_once "arrow-head.php"} command will include the \PS{} function
\texttt{ArrowHead} that draws arrow heads, used with the following syntax:
\begin{center}
\textit{angle}\quad$X$\quad$Y$\quad\texttt{ArrowHead}
\end{center}
where \textit{angle} is the angle (in degrees) from the horizontal,
counterclockwise (Figure~\ref{fig:arrow-head-explained} shows an angle of $180$
degrees) and $(X,Y)$ is the coordinate of the vertex of the arrow.
The \PS{} function uses the following variables for the dimensions:
\begin{itemize}
\item \texttt{/ArrowHeadAngle}: the angle $\theta$. It is set to $15$ by default,
\item \texttt{/ArrowHeadProportion}: the ratio $OB/OA$. It is set to $1.67$ by default,
\item \texttt{/ArrowHeadHorizontalSize}: the length $OB$. It is set to $3$ by default,
\end{itemize}
and these values can be modified.

\subsection{\texttt{coords.php} --- Dealing with Coordinates}
\label{ssec:coords.php}
Even though the \PS{} language has these wonderful transformation matrices, it
is not always recommended to use them for change of coordinates, since the
transformation also changes the strokes (the lines that are drawn). This file
will include the \texttt{Coords} \PS{} function, to be used with the following
syntax:
\begin{center}
$x$\quad$y$\quad\texttt{Coords}\quad$X$\quad$Y$
\end{center}
where the input is $(x,y)$, the coordinates in the relative frame, and the output $(X,Y)$
is the coordinates in the absolute frame. For this function to work, the information about
the relative frame must have been given. It uses eight variables:
\texttt{xmin}, \texttt{ymin}, \texttt{xmax}, \texttt{ymax},
\texttt{Xmin}, \texttt{Ymin}, \texttt{Xmax} and \texttt{Ymax}.
Include this file (or files that use it) after having defined
these eight variables!

\subsection{\texttt{eps-header.php} --- Let's Start!}
\label{ssec:eps-header.php}
You will very likely include this before anything else. Make sure you have the variables
\code{$lx}, \code{$ly}, \code{$ux}, \code{$uy} defined. Optionally you can define the variables
\code{$author}, \code{$title} and \code{$date}.

\subsection{\texttt{fatal.php} --- Die Hard!}
\label{ssec:fatal.php}
This file only contains the PHP function \texttt{fatal} that takes $1+1$ arguments.
The first argument is the error string to be output on \textit{stderr} and the other
optional argument is:
\begin{itemize}
\item either a numerical value that corresponds to the exit code,
\item or another string that will be output to \textit{stderr} on a second line,
in which case the exit code is $1$.
\end{itemize}
If this optional argument is not give, the exit code is $1$.

\subsection{\texttt{hyperbolic.php} --- Exponential and hyperbolic functions }
\label{ssec:hyperbolic.php}
This \PS{} set of functions include:
\begin{itemize}
\item \code{EXP}: the exponential in base $\mathrm{e}$,
\item \code{cosh}, \code{sinh}, \code{tanh},
\item \code{arccosh}, \code{arcsinh}, \code{arctanh}.
\end{itemize}

\subsection{\texttt{newton-solver.php} --- Equation solver}
\label{ssec:newton-solver.php}
This \PS{} function is to find approximations of roots of an equation
of the form $f(x)=0$ using the Newton--Raphson method. The syntax is:
\begin{center}
\texttt{\{}$f$\texttt{\}}\quad\texttt{\{}$f'$\texttt{\}}\quad$x_0$\quad$\varepsilon$\quad\texttt{NewtonSolver}\quad$x^*$
\end{center}
where $f$ is the function to find the root of, $f'$ is its derivative, $x_0$ is an approximation of a root
and $\varepsilon$ is the wanted accuracy. The method will stop when either $\lvert x_{\text{next}}-x\rvert\leq\varepsilon$
or after \verb=@NewtonSolverMaxIterations= number of iterations. The \PS{} variable \verb=@NewtonSolverMaxIterations=
is set to $20$ by default. The approximation of the root, $x^*$ is pushed onto the stack.

\subsection{\texttt{plotfunction-bezier-stupid-hom.php} --- Plot Graphs of Functions}
\label{ssec:plotfunction-bezier-stupid-hom.php}
This \PS{} function is to plot graphs of functions using B\'ezier curves (and not
line segments). The result is usually a beautiful smooth curve that scales very
well. But there are a few limitations. Read on.

Let me first explain the nomenclature: the part \emph{hom} in the name stands
for homogeneous, that is the interval is divided into $N$ homogeneous
subintervals ($N$ is given by the user). The part \emph{stupid} is because each subinterval
of the subdivision is itself divided into three subintervals of equal lengths to determine
the control points for the B\'ezier curve. This has some flaws if the function has, e.g.,
very steep slopes.

To be able to use this \PS{} function to plot graphs, you need to know the derivative of your function.
The syntax is as follows:
\begin{center}
\texttt{\{}$f$\texttt{\}}\quad\texttt{\{}$f'$\texttt{\}}\quad$x_{\text{min}}$\quad$x_{\text{max}}$\quad$N$\quad\texttt{PlotFunctionBezierStupidHom}
\end{center}

Figure~\ref{fig:plotfunction-bezier-stupid-hom-demo} shows the result of:
\lstinputlisting[caption=plotfunction-bezier-stupid-hom-demo.php]{figs/plotfunction-bezier-stupid-hom/plotfunction-bezier-stupid-hom-demo.php}
Notice the use of curly brackets to enclose $f$ and $f'$! Also notice that I
defined functions \texttt{cosrad} and \texttt{sinrad} being the (regular)
$\cos$ and $\sin$ functions with the angle given in radians. That's because the
\PS{} \texttt{cos} and \texttt{sin} functions take an angle in degrees.

\begin{figure}[ht!]%
\centering
\includegraphics{figs/plotfunction-bezier-stupid-hom/plotfunction-bezier-stupid-hom-demo}%
\caption{Graph of $\cos$ using the \texttt{plotfunction-bezier-stupid-hom.php} file}%
\label{fig:plotfunction-bezier-stupid-hom-demo}%
\end{figure}

Even though \texttt{PlotFunctionBezierStupidHom} is a stupid function with a
naive algorithm, it still outputs beautiful curves in many cases!

In fact, this PHP file include the file \texttt{plotparametric-bezier-stupid-hom.php},
and uses its PlotParametricBezierStupidHom function. The implementation is just:
\begin{lstlisting}
/PlotFunctionBezierStupidHom {
   { } { pop 1 } 7 2 roll PlotParametricBezierStupidHom
\end{lstlisting}

\subsection{\texttt{plotimplicit-bezier-stupid-hom.php} --- Plot Implicit Curve}
\label{ssec:plotimplicit-bezier-stupid-hom.php}
These \PS{} functions are to plot implicit curves using B\'ezier curves (and not
line segments). The result is usually a beautiful smooth curve that scales very
well. But there are a few limitations. Read on.

Let me first explain the nomenclature: the part \emph{hom} in the name stands
for homogeneous, that is the interval of parametrization is divided into $N$
homogeneous subintervals ($N$ is given by the user). The part \emph{stupid} is
because each subinterval of the subdivision of the parametrization is itself
divided into three subintervals of equal lengths to determine the control
points for the B\'ezier curve.

There are two functions here. Depending on how you want to determine the portion
you want to plot, you'll use one or the other.
%%TODO: Explain!

\subsection{\texttt{plotparametric-bezier-stupid-hom.php} --- Plot Parametric Curves}
\label{ssec:plotparametric-bezier-stupid-hom.php}
This \PS{} function is to plot parametric curves using B\'ezier curves (and not
line segments). The result is usually a beautiful smooth curve that scales very
well. But there are a few limitations. Read on.

Let me first explain the nomenclature: the part \emph{hom} in the name stands
for homogeneous, that is the interval of parametrization is divided into $N$
homogeneous subintervals ($N$ is given by the user). The part \emph{stupid} is
because each subinterval of the subdivision of the parametrization is itself
divided into three subintervals of equal lengths to determine the control
points for the B\'ezier curve. This has some flaws if the function has, e.g.,
very high velocities.

To be able to use this \PS{} function to plot parametric curves, you need to
know the derivative of your coordinate functions. The syntax is as follows:
\begin{center}
\texttt{\{}$x$\texttt{\}}\quad\texttt{\{}$x'$\texttt{\}}\quad\texttt{\{}$y$\texttt{\}}\quad\texttt{\{}$y'$\texttt{\}}\quad$t_{\text{min}}$\quad$t_{\text{max}}$\quad$N$\quad\texttt{PlotParametricBezierStupidHom}
\end{center}

Figure~\ref{fig:plotparametric-bezier-stupid-hom-demo} shows the result of:
\lstinputlisting[caption=plotparametric-bezier-stupid-hom-demo.php]{figs/plotparametric-bezier-stupid-hom/plotparametric-bezier-stupid-hom-demo.php}
It plots the parametric curve given by:
\[\begin{cases}
x'(t)=\dfrac t{2\pi}\cos t\\
y'(t)=\dfrac t{2\pi}\sin t,
\end{cases}\qquad t\in[0,4\pi].\]
Notice the use of curly brackets to enclose $x$, $x'$, $y$ and $y'$! Also notice that I
defined functions \texttt{cosrad} and \texttt{sinrad} being the (regular)
$\cos$ and $\sin$ functions with the angle given in radians. That's because the
\PS{} \texttt{cos} and \texttt{sin} functions take an angle in degrees.

\begin{figure}[ht!]%
\centering
\includegraphics{figs/plotparametric-bezier-stupid-hom/plotparametric-bezier-stupid-hom-demo}%
\caption{Parametric curve using the \texttt{plotparametric-bezier-stupid-hom.php} file}%
\label{fig:plotparametric-bezier-stupid-hom-demo}%
\end{figure}

Even though \texttt{PlotFunctionBezierStupidHom} is a stupid function with a
naive algorithm, it still outputs beautiful curves in many cases!

\subsection{\texttt{trigonometry.php} --- Elementary Trigonometry in Radians}
\label{ssec:trigonometry.php}
This just defines the \PS{} macro \verb=pi= for $\pi$ and the $\sin$, $\cos$
$\tan$ and $\operatorname{atan}$ functions in radians as the \PS{} macros \verb=sinr=,
\verb=cosr=, \verb=tanr= and \verb=atanr= respectively.

\subsection{\texttt{SmartInsertFont.php} --- Inserting Fonts}
\label{ssec:SmartInsertFont.php}
Text is one of the most difficult aspect of making an EPS file by hand. Putting
just one letter here and there is (almost) fine, though. I'm planning to do
some nice (and simple!) helpers to place them and maybe to compose simple text
and maybe to drive a \TeX engine to typeset some for me\ldots but for now you
only have the function PHP \texttt{SmartInsertFont} that will \texttt{locate}
the fontname given. The syntax is:
\begin{center}
\texttt{SmartInsertFont\quad(}\quad\textit{fontname\quad[\quad,\quad path regex\quad]}\quad{)}
\end{center}
This will just dump the font in the document.
\begin{figure}[ht!]%
\centering
\includegraphics{figs/SmartInsertFont/SmartInsertFont-demo}%
\caption{\texttt{SmartInsertFont} helps inserting fonts in EPS document}%
\label{fig:SmartInsertFont-demo.php}%
\end{figure}

Figure~\ref{fig:SmartInsertFont-demo.php} was obtained thus:
\lstinputlisting[caption=SmartInsertFont-demo.php]{figs/SmartInsertFont/SmartInsertFont-demo.php}

\begin{note}
You need to have \texttt{t1ascii} installed to use this function.
\end{note}

\subsection{\texttt{utils.php} --- Miscellaneous Utilies}
\label{ssec:utils.php}
This file contains miscellaneous PostScript macros:
\begin{center}
$a$ $b$ \texttt{min}\\
$a$ $b$ \texttt{max}
\end{center}
($\min$ and $\max$ operators).

\subsection{\texttt{vector.php} --- Drawing Arrows}
\label{ssec:vector.php}
This file defines the \PS{} function \texttt{Vector} that draws a line segment
with an arrow head. If the length of the line segment is less than the size
of the arrow head, nothing is drawn (so as to not have an ugly arrow head on its own).
The syntax is as follows:
\begin{center}
$X_a$\quad$Y_a$\quad$X_b$\quad$Y_b$\quad\texttt{Vector}
\end{center}
This will draw a vector from $(X_a,Y_a)$ to $(X_b,Y_b)$. This file implicitly calls
\texttt{arrow-head.php} and uses the \PS{} function \texttt{ArrowHead} for the arrow head.
Figure~\ref{fig:vector-demo} represents such a vector.
\begin{figure}[ht!]%
\centering
\includegraphics{figs/vector/vector-demo}%
\caption{Vectors drawn by the \PS{} function \texttt{Vector} from file \texttt{vector.php}}%
\label{fig:vector-demo}%
\end{figure}
There's also the \texttt{DoubleVector} macro that draws an arrow head
at both sides of the segment:
\begin{center}
$X_a$\quad$Y_a$\quad$X_b$\quad$Y_b$\quad\texttt{DoubleVector}
\end{center}

\section{Tips}
In this section I briefly describe my workflow tools for creating \LaTeX{}
documents with \PS{} illustrations. It works perfectly well for me. I hope it can
be useful to some other people.
\subsection{The Main Directory}
Each document I created is fully contained in one directory. I use the
\texttt{git} version control system and a private server for backups, but
that's not mandatory. Let's say the directory corresponding to my document
is named \texttt{mydoc}. If the document contains several chapters or parts,
I put each chapter or part in a different file.

The tree structure of \texttt{mydoc} is as follows:
\begin{lstlisting}
$ tree -a
.
|__ bin
    |__ some binarys (optional)...
|__ document.tex
|__ chapter1.tex
|__ chapter2.tex
...
|__ figs
    |__ figs_chapter1
        |__ figure1.php
        |__ figure2.php
        |__ ...
        |__ Makefile -> ../Makefile-figs
    |__ figs_chapter2
        |__ figure1.php
        |__ figure2.php
        |__ ...
        |__ Makefile -> ../Makefile-figs
    |__ ...
    |__ Makefile
    |__ Makefile-figs
|__ .git
    |__ the git stuff ...
|__ .gitignore
|__ Makefile
|__ php
    |__ the php files of this package
\end{lstlisting}

\subsection{The \texttt{Makefile}s}
Im \texttt{mydoc/} I have a main \texttt{Makefile} with several rules. I use
\texttt{latexmk} to generate the document. It typically looks like:
\lstinputlisting[caption=\texttt{Makefile},language=make]{Makefile}

Then, in the \texttt{figs/} directory, I have two \texttt{Makefile}s:
\lstinputlisting[caption=\texttt{figs/Makefile},language=make]{figs/Makefile}
and
\lstinputlisting[caption=\texttt{figs/Makefile-figs},language=make]{figs/Makefile-figs}
Then, in each \texttt{figs/chapter$x$} directory I soft link the \texttt{Makefile-figs}
to a \texttt{Makefile} file using the command:
\begin{center}
\texttt{ln -s ../Makefile-figs ./Makefile}
\end{center}
Then I can add any directories in \texttt{figs/}, perform the previous command, and each PHP
file in there will be converted to EPS and PDF automatically.

\subsection{The Workflow}
Generating my document is as easy as typing \lstinline{make} and adding new figures is just a matter
of writing the PHP file in the corresponding \texttt{figs/chapter$x$} directory.
The rule \texttt{make clean} or \texttt{make C} will clean up everything.
\end{document}


\subsection{Type I and type II errors}