%\documentclass[12pt]{amsart}
\documentclass[12pt]{article}

\newcommand{\beq}{\begin{equation}}
\newcommand{\eeq}{\end{equation}}
\newcommand{\ba}{\begin{array}}
\newcommand{\ea}{\end{array}}
\newcommand{\bea}{\begin{eqnarray}}
\newcommand{\eea}{\end{eqnarray}}
\newcommand{\bc}{\begin{center}}
\newcommand{\ec}{\end{center}}
\newcommand{\bt}{\begin{table}}
\newcommand{\et}{\end{table}}
\newcommand{\la}[1]{\label{#1}}
\newcommand{\p}{\partial}
\newcommand{\pp}[2]{{\partial #1 \over \partial #2}}
\newcommand{\ds}{\displaystyle}
\newcommand{\rp}{{\tt reynolds> }}
\newcommand{\mmp}{{\tt matlab>> }}
\newcommand{\FEM}{Femlab }

%\usepackage{amsmath}
\usepackage{epsfig}
\usepackage{float}
\usepackage{fullpage}

\title{A Quick Intro to Femlab}
\author{Roger Thelwell \\ {\tt \small{thelwell@math.colostate.edu}} }
%\email{thelwell@math.colostate.edu}
\date{Sept 16, 2003}

\begin{document}

\maketitle

\section{Introduction}

Femlab is a front-end for Matlab, and allow multi-physics PDEs to be
solved using finite element methods.  \FEM can be controlled
through a GUI and/or a script.m file.

\begin{verbatim}
version = 
     name: 'FEMLAB 2.3'
     major: 0
     build: 145
     rcs: '$Name:  $'
     date: '$Date: 2002/06/10 19:39:20 $'
\end{verbatim}

\noindent
There are newer versions available for down-load.

\section{Getting started}

The best way to start learning \FEM is through the manuals (User's Guide
, Reference,  and the Model Library) - available in both
print and electronic format.  \FEM's help has been installed on Reynolds and
can reached by through the help button in the \FEM control window.
You'll have access to htm and pdf files.
\noindent
There's also online help:\\ 

{\tt http://www.femlab.com/ } \\

\noindent	
In addition, the demos are a great resource. 
You can load and run these, view all setting and modify them.

You'll need to spend some time playing with Femlab - I've been at 
it for several weeks now.  It's powerful, but sometimes hard to control.
There are many options to set.  These notes are just a few comments
that I would have found helpful.  I'll focus
on the GUI application, which makes it pretty easy to build models.  I
haven't yet learned much about scripting, but I think that scripts are
really the best way to manage experiments.

\subsection{GUI}
The GUI is a good place to start with \FEM.  You might want to step
through some of the examples in the User's Guide.  You'll
pick up quite a bit by doing so.   You can call the GUI 
from the Matlab prompt 

\noindent
{\tt \mmp femlab} 


\noindent
Two windows should appear -
the {\tt \FEM} window and the {\tt Model Navigator} window.  New models can
be started by clicking the {\tt New} tab inside the {\tt Model
Navigator} window, selecting the dimension of the problem
and a general format to use.  These formats are:
\begin{itemize}
\item {\tt Geometry only}
\item {\tt Physics modes}
\item {\tt Weak modes}
\item {\tt Classical PDEs}
\item {\tt Applications}
\end{itemize}

\noindent
Double clicking allows you to enter each and make more specific choices.
The {\tt Geometry only} can be used to draw the domain. This domain can then be
saved as a geometry file, to be reloaded at any time.  This is useful when
a complex geometry might be used again. 

The {\tt Physics modes} section includes a wide range of common PDEs.
The coefficients are identified by their usual physical terminology.
This makes it easy to apply these models to engineering applications.
It's more difficult to incorporate additional features to these prebuilt
forms.

The {\tt PDE mode} section lets you build in either a coefficient form
$$d_a \pp{u}{t} + \nabla \cdot (-c \nabla u - \alpha u + \gamma) +
\beta \cdot \nabla u + a u = f $$
or the general form, 
$$ d_a \pp{u}{t} + \nabla \cdot \Gamma = F.$$
The general form is more flexible than the coefficient form, but the
boundary terms are usually more difficult to set properly. Also be
aware that sometimes you'll need to enter scalars, and other times
matrices. The display format isn't the best.  The {\tt View as
Coefficients} can be helpful to see the structure. 

The {\tt Model Library} tab allow access to a variety of pre-coded models.
The wide range can be used as a foundation for modifications.
Multi-physics demos can be found in this section as well. 

The {\tt Multiphysics} tab is used to create multi-physics models.
Once the model and its variables are chosen, the are moved to the
application side by double clicking or by clicking on the $>>$ arrow button.  The default
variable names will be independent, but be careful if you choose your
own.  Each model has reserved local variable names (which you can check
at a later stage, or in the documentation) so be careful with any changes. 
Don't worry too much, though, as it's also possible to change these names at a later stage.

\vspace*{0.2in}

\parbox{4.5in}{
Suggestion: Build your new model using a existing \FEM demo model.
It's easy to add and modify \FEM models.  This includes changing the
geometry, equation coefficients, multi-physics modes, boundary and initial
conditions, mesh and solvers. The default options are in general a
good place to start. }

\subsection{Starting a New Model}

We'll step though to following process to build a model:
\begin{enumerate}
\item Choose a demo or model
\item Draw or load geometry
\item Define the boundary setting
\item Define the Subdomain
\item Verify that the mesh is OK
\item Solve
\item Post mode to visualize the solution
\item Modify?
\end{enumerate}

{\bf
Be careful when changing geometry, and modifying multi-physics.
Defaults are reset in mesh setting and solver tolerances when these
changes are made.}


\subsubsection{Choosing the Model}

From the {\tt Model Navigator} window, click the {\tt New} tab, and select the model
and variables, then click OK.  The default elements work well for the
physics mode problems, but might need to be modified for the
general/weak modes.  You can open the {\tt Model Navigator} window 
any time from the \FEM window by Ctrl-n or by clicking {\tt \underline{F}ile} 
and then {\underline{N}ew}.  

The geometry of the model needs to be established first, but once this
is done the order of the others (boundary and sub-domain) really doesn't matter.
I'll just step through them in the the order that they're found on the menu.   

\subsubsection{Geometry}
The first step is to enter the geometry. Geometry can be either
constructed or imported (
File $\to$ Import from File $\to$ Geometry file).

To draw a new geometry, a grid needs to be established.  Under Options
$\to$ Axis/Grid Setting, set both the axis and grid options.  Press the
Auto radio button to get control of the grid.  If you think you'd like
to use the snap-to-grid 
feature, you'll generally need to enter grid values everywhere you'd to place a vertex in the drawing.   

A sidebar menu should pop up, from which you can chose shapes 
or choose them from the pull-down menu.  The right mouse button can be used to draw squares and circles, and only requires a grid mark in one dimension.

Union(+), intersection (*), difference(-) can be used to create
composite objects.  For example,  R1-C1 removes circle C1 from Rectangle R1.

A single click on a vertex lets you move it. 
Double clicking on an object will open a window that lets you modify
the objects properties (vertex, name, etc).  
Left clicking and holding lets you move the object.

I had some problems with the draw mode, particularly in 3d.  The 
drawing would go well, but the mesh generation would fail, producing 
degenerate elements.  The reference manual has a list of errors that 
can occur (pg 3-71), and some cures.  The cures for my problems were vague. 
 
Once you're finished with the geometry, you can set up boundary and
subdomain. At this point, you can also save the geometry (File $\to$
Export to File $\to$ Geometry file).

\subsubsection{Boundary Mode}

Once you enter boundary mode (either from the menu of by pressing
Ctrl-b), you can select {\tt boundary setting} from the pull-down
menu, or double clicking on the separate boundaries in the line drawing.
Several boundaries can be selected by using the shift key and clicking
each, or by drawing a rectangle with the left mouse button and
enclosing the boundary elements and then double right clicking.
Once the {\tt Boundary Setting} window appears, the boundary values
can be set.  Once entered, press OK.

You won't be able set boundary values unless your in some type of
model mode.  The {\tt Geometry only} selection in the {\tt Model
Navigator} is exactly what it says, and no more.  If you find you
can't set boundary values, this might be the reason.

\subsubsection{Subdomain}

Now set the subdomain values.  If you'd  like to use
parameters here, you can go back to Options on the menu bar and select
{\tt Add/Edit constants}. Enter any parameters that you'd like to use
in the subdomain section.  Also under Options, you can find {\tt
Assigned variable names}, and a list of preassigned variable names.
Make sure you don't have duplicates.

Click on Subdomain from the menu bar and either double click on
drawing or setting in the pull-down menu. Then use constants (or
parameters) and set either coefficient values (coefficient form) or
functions (in general form).
\subsubsection{Mesh}
Enter mesh mode, and either use the refine mesh button or the mesh
parameters to create a  mesh that looks good.  You also have the
option to turn on a adaptive mesh in the solver section, so you don't
have to worry too much here.  The parameter section (at the bottom of
the menu) allow you to set general edge size, growth factor 
 and  curvature (effectively the degree
of the polygonal approximation on curves). You should reinitialize
mesh when you're done here.  You also need to be careful when you
change the geometry - the mesh reverts to the default parameters.
The mesh statistics button is useful to verify that things are right.

\subsubsection{Solve}

The solve stage has the most parameters to set, and is difficult to
optimize. 
A general process to solve a time dependent problem might be:
\begin{itemize}
\item Solve time independent problem (General tab). Fix any problems with
geometry, grid, and initial/boundary conditions.
\item Restart the dependent for a short period of time. (General and
Timestepping tabs). Explore solver tolerances, and test a few different
 time-dependent solvers. Also look at time dependent boundary and
initial conditions.
\item Restart with full length time dependent problem. (Timestepping
tab)
\end{itemize}
Relative tolerence needs to be scalar, and is used
to control all unknown variables.  Absolute tolerence allows you to single out individual variables.  For flow problems, it seems important to use both.  

The initialization in nonlinear problems can be important for convergence.
One way to do this is by prescribing a good initial solution, which is controlled on the {\tt Subdomain} setting window, under the {\tt Initial} tab.
Another way is to use the restart button, and do some 
coarse parameter continuation to find a suitable initialization.

When solving multiphysics problems, you don't need to solve all modes
simultaneously.  Chose the mode(s) to solve by clicking on
{\tt Solve for variables} on the pull-down menu and then selecting.  
This can be useful in multiphysics initialization.

Be careful if you've changed the basic model - (ie removed
mulitphysics, changed geometry, added boundary elements etc), since some 
changes might reset parameters.  It took me several days to notice changes 
in the time dependent solver tolerances and in mesh parameters. 
These only became apparent in the long time runs.
 
\subsubsection{Post Mode}

Used for graphics. Animations can be saved as mpeg, gif or jpg. All
plots are controlled from the plot parameter selection.  The Mpeg format
movies seem to be limited to 16  frames, and the resolution is quite
poor.. The support at femlab
recommended that I make a sequence of tiff format plots, and then use a
free app to make mpg movies.  {\tt Resol} sets resolution of tiff
format.

\subsubsection{\FEM Hot-Keys}

\begin{tabular}{|r|l|}
\hline
Ctrl-n & Open New model \\
Ctrl-s & Save model (.mat file) \\
Ctrl-f & Export fem to Matlab \\
Ctrl-b & Boundary mode \\
Ctrl-i & Initialize mesh \\
Ctrl-e & Solve \\
Ctrl-t & Restart \\
Ctrl-p & Plots (post mode)\\
Ctrl-w & Exit \\
\hline
\end{tabular}

\subsection{Scripts}
\FEM can also be run from {\tt Matlab6} using a script.
If you don't mind keeping \FEM running and doing
everything with the GUI, you don't need to use the command language.
If you'd like to run series of experiments that require you to test
various aspects of the model, you might want to learn some of the basics of the
command language.  This language lets you call all of Femlab's commands
from Matlab's command line.  It also lets you run experiments from
scripts and   
in the backround.  You can actually use \FEM to create scripts 
automatically (which you can them modify), or they can be hand coded.

Saving your work in a .m file is a compact way to keep track of what
you've done, as a list of \FEM's command language commands. It's like a log file
of your keystrokes.
The commands in .m files that you capture is just serial list, so you 
might need to save a sequence of these files to see changes.

\noindent
I used the following, a combination of GUI and the commmand language, 
to build experiments:

\begin{enumerate}

\item With \FEM's GUI, set up the problem and make some short experiments.

\item In \FEM, use CTRL-F to export the fem struc to Matlab.
(it will show up in Matlab as a structure called {\it fem})

\item In Matlab, save the fem structure by using Matlab's save command
      
       (ie \mmp save template {\it fem}). 

\item Use \FEM's GUI to simulate the motions of experiments, and then save these
key commands in a .m file. Use the save as choice under File on the
main menu bar to save a .m  file. 

 (ie save {\it sample} writes sample.m).

\item Using a text editor, write a .m script (ie {\it exper.m}) that loads the template file and performs the experiment.  You can get the commands by looking at the saved
{\it sample.m} files, and lift (and modify) the commands as needed.
You can also look through the reference manual and pre-coded models.  You
might want to include a Matlab save command in {\it exper.m} to save to results of the script.
You can also use Matlab tic/toc to compare the run times of solvers and other options.

\item Run your script.
    I  use {\it screen} to run the experiments in the backround like this:
\begin{verbatim} 
           reynolds> screen 
           reynolds> unsetenv DISPLAY 
           reynolds> matlab6 
              matlab>> exper
              matlab>> save results
\end{verbatim}
    {\it screen} makes it easy to check on progress, but breaking the script
    run prevents you from seeing current progress.

\item In {\tt Matlab}, load your results and use the post commands to view.\\
      (ie \mmp load results \\ 
      \phantom{ie}    \mmp postplot(fem) )
\end{enumerate}

\subsubsection{Examples}
A few examples of \FEM commands that might be useful in scripts:

\begin{verbatim}
% Save current fem structure for restart purposes
fem0=fem;
\end{verbatim}
Set up the mesh again:
\begin{verbatim}
% Extend the mesh
fem.xmesh=meshextend(fem);
\end{verbatim}
Map current solution to to the new mesh (Navier Stokes):
\begin{verbatim}
% Map initial solution to current xmesh
fem0.sol.u(:,1:end-1)=[];
umap={'p',1,1,1,1;'u',1,1,1,1;'v',1,1,1,1};
init=asseminit(fem,'init', {fem0,umap});
\end{verbatim}
I'll use {\tt init} from above to initialize the time dependent
solve. See the reference manual pg 5-134 for all of {\tt femtime} options -
there are many.
\begin{verbatim}
% Solve dynamic problem
fem.sol = femtime(fem,'tlist',[0:.1:1],...
       'ode','fldaspk',...
       'atol',{'u' 1e-3 'v' 1e-3 'p' inf},...
       'stop' , 'on',...
       'init',init,...
       'timeind','D',...
       'report','on');
% stop on returns partial solution if timestepping fails
% timeind D, mass matrix is constant (for speed)
\end{verbatim}
An example of post plotting.  Here I plot the velocity as a colormap,
pressure as a contour plot with colobar and then add flowlines. {\tt Postplot} is worth reading about in the reference manual.
\begin{verbatim}
% Plot solution
postplot(fem,'tridata','sqrt(u^2+v^2)',...
             'contdata','p',...
             'contbar','on',...
             'flowdata',{ 'u' 'v'},...
             'title', 'Surface: Velocity (U) Contour: pressure (p)
Flow: [x velocity (u),y velocity (v)]  ',...
             'axisequal','on');
\end{verbatim}
The stiffness matrix can be assembled and explored.    
\begin{verbatim}
% View stiffness matrix
[K,L,M,N]=assemble(fem); 
spy(K);
% K = Stiffness matrix , L = residual vector
% M = constraint vector , N = constraint matrix
\end{verbatim}
\end{document}


