\section{How to realise a CTL/C++ component from a MATLAB code}
\label{cpp}

The MATLAB language can be used to formulate solutions to mathematical problems
faster and usually shorter than traditional programming languages, using those
from your application is a repetitive and error-prone task, though. By making
MATLAB code accessible as a CTL component, they become much more accessible.
This chapter will first instruct you on how to do this manually and then present
a tool, which can do it automatically.

\subsection{Manual approach}

For this section, MATLAB's \textit{eig()} function is used. It is wrapped into the
function \textit{myeig()} to make it accessible for the MATLAB compiler (MCC).
The resulting executables need either a full MATLAB installation or the MATLAB
Component Runtime (MCR), a ZIP-archive which contains all the libraries necessary
to use the shared libraries or executables generated by MCC.

\lstinputlisting[caption={MATLAB function (myeig.m)}]{sample/cpp/myeig.m}

Firstly, we will look at how to generate a shared library for \textit{myeig()} and
how to use that manually. Generating the library is an easy task, because the
MATLAB compiler does all the work:

\begin{verbatim}
$ /path/to/mcc -W cpplib:libmyeig -T link:lib myeig.m
\end{verbatim}

This will produce several files, most importantly a shared library \textit{libmyeig.so}
and a header file \textit{libmyeig.h}. From now on, the function can be used from
C++ code:

\lstinputlisting[caption={Calling the function (test.cpp)}]{sample/cpp/test.cpp}

Every call to MATLAB specific functionality has to be put into a block starting
with a call of \textit{libmyeigInitialize()} and ending with a call of
\textit{libmyeigTerminate}. Of course, both functions will have the prefix given
to mcc via the \textbf{-W} switch earlier, so using '-W cpplib:foo' will produce
a \textit{fooInitialize()} function.

The generated \textit{myeig()} function has a special calling convention:
it returns void, the first argument is an integer, which specifies how many
returns values the caller expects to get back (MATLAB supports multiple
return values), followed by the variables which MATLAB should assign the
return values to and finally the arguments, all as mxArray.

Normally, you would need to convert the result back to something that is
usable in C++ with the \textit{GetData()} function, but this example just
prints it to the screen.

\subsection{Automatic approach}

The last section showed how much repetitive manual work is required for
calling a MATLAB function from C++ and it did not even cover how to wrap
that into a CTL component. Thankfully, in the process of writing this, a
code generator was developed which automates all of the work and provides
a proper C++-style component interface (CI) to a MATLAB function.

The code generation is done by two scripts \textit{gen\_makefiles.py}
and \textit{dotm2cpp.py}, which does the conversion. In addition to that,
\textit{matlab.h} defines an extended mwArray type, which handles type
conversions of itself to double, int, std::string, $std::vector<double>$
and $std::vector<std::vector<double> >$. After parsing the .m file, the
following files are generated:

\begin{enumerate}
\item A thin C++ wrapper around the code generated by MATLAB's \textit{mcc} compiler
\item A functional CI specifying the function from the Matlab script
\item The necessary CTL\_connect() code, which is needed to compile a working component
\end{enumerate}

After compiling this and linking it to a shared library compiled by \textit{mcc},
you will get a fully-functional CTL/C++ component which calls a function you wrote
in Matlab via MATLAB's C API.

As one function is created for every permutation of types, you should not use
functions with more than 3 arguments and return values as it will take a long time
to compile a component for such a function. If you need a function with more
arguments, you can specify the types manually in your \textit{.m} file, like this:

\lstinputlisting[caption={Example for manually specifying types}]{sample/cpp/mypcg2.m}

\subsubsection{Example 1: Eigenvalues}

\lstinputlisting[caption={Example CTL/C++ client (client.cpp)}]{sample/cpp/client.cpp}
\lstinputlisting[caption={Example CTL/C++ client (client.h)}]{sample/cpp/client.h}

As you can see, your Matlab function is embedded into the namespace \textit{Matlab}
and you need to specify which specialization you want to use (order: type of the
first return value, types of the arguments, types of additional return values).
In this case, $std::vector<std::vector<double> >$ is used for both the return value
and the argument and all the conversion from native C++ types to the Matlab type
system is done transparently inside the generated code. Basically, everything works
like a standard functional CI \textit{Matlab} with one function \textit{myeig()},
which was written in Matlab. The header file just defines a shortcut for the matrix
type and a pretty-printer for it.

\subsubsection{Example 2: PCG}

This section shows a more complex example, which uses two Matlab functions:
\textit{getproblem()} returns a problem of the form $A * x = b$ and 
\textit{mypcg()} solves that using MATLAB's Preconditioned Conjugate Gradient
(PCG) solver.

\lstinputlisting[caption={Example function for generating a problem}]{sample/cpp/getproblem.m}
\lstinputlisting[caption={Example PCG solver}]{sample/cpp/mypcg.m}

As you now would have two \textit{Matlab} namespaces, both code generator scripts support
the command line option \textit{-sFOO} which uses \textbf{FOO} as suffix to the namespace,
so it becomes \textit{MatlabFOO} in this case. 

\lstinputlisting[caption={Example CTL/C++ client (client2.cpp)}]{sample/cpp/client2.cpp}

The client code shows that both the matrices and the vectors do not have to be converted
manually, as said earlier. 

\subsubsection{Example 3: Eval}

\lstinputlisting[caption={Example evaluate function (myeval.m)}]{sample/cpp/myeval.m}

You probably wonder about the weird string concatenation instead of just using
\textit{sprintf()}. The straightforward way would be using:

\begin{verbatim}
str = sprintf('ys = [ys, %s(%i)];', funid, x);
\end{verbatim}

Unfortunately, this code only works when run inside Matlab, but fails when it is used
in a shared library compiled by \textit{mcc}, therefore a workaround was used.

This function is also interesting, because it shows MATLAB's \textit{eval()} in action.
It evaluates a string as if it was typed in on the Matlab console, thus serving as a
kind of dynamic function call here, whatever the user passes as second argument to 
\textit{myeval()} is used as a function which is evaluated at all the values in the
array which is given as first argument. 

\lstinputlisting[caption={Example function being evaluated (foo.m)}]{sample/cpp/foo.m}

This second function makes the whole process a bit tricky, because the client application
needs to know about it and initialize it properly by calling \textit{libfooInitialize()}
and it also needs to copy the resulting pre-compiled \textit{foo.m} to the MCR
directory of libmyeval, so that it can be found at runtime. To hide this from the user,
\textit{dotm2cpp.py} provides the \textit{-u} command line switch, which

\begin{enumerate}
\item Generates the corresponding Makefile for the specified function.
\item Inserts some initialization code into your main function, which initializes the
specified function (to get the pre-compiled \textit{.m} file) and then copies it
to the target directory.
\end{enumerate}

This means that you can safely call the second function from the first one without
writing any C++ support code yourself, but you have to make sure to first call the
Makefile generated for the second function and then the one for the first function.

As you can see, MATLAB's \textit{eval()} serves as a kind of dynamic function call to
a function identified by the user-provided string \textit{funid}. This example also
shows you a way to deal with graphics in your CTL/Matlab application.

\lstinputlisting[caption={Example CTL/C++ client (client3.cpp)}]{sample/cpp/client3.cpp}

\textbf{Note:} If you are using the code generator on a void function, it will still
generate a wrapper function with a return value, so you have to give it some dummy
template argument in your client code. This special case will rarely be used, therefore
it is not handled explicitly.

\subsection{How to use from CTL4j}

In this section, a very simple MATLAB function will be used and called from a
CTL4j application, using an auto-generated CTL/C++ component. The reason for the
simplicity lies in the fact that templated matrix and vector types are not yet
available in the CTL4j and therefore the intersection between Java and MATLAB
lies only in integer and floating point fundamentals.

\lstinputlisting[caption={Simple MATLAB function}]{sample/java/fun2.m}

Using a CTL MATLAB component works just like accessing any other CTL/C++ component
from CTL4j code:

\begin{itemize}
\item Add a new block to the 'genri' target in build.xml:
\begin{verbatim}
<exec executable="${ctlcc}" logError="true"
	output="${src}/_default/MatlabCTLI.java">
	<arg value="ctlcc.py"/>
	<arg value="-F"/>
	<arg value="-q"/>
	<arg value="-DMatlab=MatlabCTLI"/>
	<arg value="matlab/cpp/codegen/mlab_fun2.ci"/>
</exec>
\end{verbatim}

The code generator \textit{ctlcc.py} generates Java code from a CI. If you used
a library name other than 'Matlab', you have to use this of course. The suffix
\textit{CTLI} tells the CTL4j code generator that you just want an RI generated
and none of the other possible wrappers. The '-F' switch tells the generator that
your CI is strictly functional and '-q' keeps it from printing warnings about
undefined types for the template arguments, which it will otherwise print, because
it only understands the CI grammar and not C++. The '-D' directive is always 
needed for classes with the 'CTLI' suffix and the last parameter is the path to
your CI of course.

\item Now you have to add a block to the 'compile-gen' target:
\begin{verbatim}
<java classname="CodeGen.Main" classpath="${classpath}" fork="true">
	<arg value="-DRET=int"/>
	<arg value="-DX1x1=int"/>
	<arg value="-DX2x2=int"/>
	<arg value="_default.MatlabCTLI"/>
</java>
\end{verbatim}

This calls the CTL4j's code generator for the Java class we generated earlier.
For each template parameter in your CI, you have to add a '-D' directive to
specialize the type, as this cannot be done in Java itself. Due to the dynamic
nature of MATLAB types, this means that certain functions might be more
restricted in Java applications than they are in C++ applications.

\item Finally, you can write your client code:

\lstinputlisting[caption={Example Java client}]{sample/java/Client.java}

As in the C++ case, this looks just like any other CTL4j client, 
nothing special. Before running it, do not forget to alter your \textit{locs.txt}
so that it points to the correct service executable.

\item Example output:

\begin{verbatim}
Lenin:~/projects/wire/ctl4j$ ./run.sh 
4
Warning: Unable to open display , MATLAB is starting without a display.
  You will not be able to display graphics on the screen.
Warning: No window system found.  Java option 'MWT' ignored.
Warning: Unable to load Java Runtime Environment: libjvm.so: cannot open shared object file: No such file or directory.
Warning: Disabling Java support.
\end{verbatim}

You can see some warnings from Matlab, as well as the calculation result.

\item Note: Support for template functions and namespace-level functions is a very
new feature in the CTL4j, so it might still contain bugs. In addition to that, the
vector and matrix types used by the C++-code in this paper are not yet supported 
by the CTL4j natively. Please contact the author in case of problems.

\end{itemize}

% vim: ft=tex
