\input texinfo   @c -*-texinfo-*-
@c %**start of header
@setfilename giac_us.info
@settitle Giac API
@comment Carleos 20020729 for Debian packaging added:
@dircategory Math
@direntry
* Giac : (giac_us).         Computer Algebra System Library
@end direntry
@documentlanguage en
@documentencoding ISO-8859-1
@c %**end of header

@setchapternewpage odd

@titlepage
@sp 10
@comment The title is printed in a large font.
@center @titlefont{Giac/Xcas}

@c The following two commands start the copyright page.
@page
@vskip 0pt plus 1filll
Copyright @copyright{} 2001 B. Parisse, Institut Fourier
@end titlepage

@node    Top, Installation, , (dir)
@comment node-name, next,previous, up

Giac is a C++ library that has types for symbolic algebraic manipulations.
Xcas is a GUI linked with Giac that provides the functionnalities
of a general purpose computer algebra system.
Giac's name derive from @uref{http://www.ginac.de}, another C++
library for symbolic algebraic computations.

@menu
* Installation::     How to install giac/icas/xcas
* Xcas::             Describes the xcas user-interface to giac
* Giac::             How to program in C++ using giac.
* Examples::         Some examples of xcas script and C++ program using giac
* Concept Index::    Index.
@end menu

@node    Installation, Xcas, Top, Top
@chapter Installing Giac/Xcas
@menu
* Binaries::         Installing xcas binaries only
* Requirements::     Compiling xcas requires libraries and program
* Options::          Optionnal libraries that enhance giac behaviour
* Configure::        Options for the configure shell script
* Compiling::        Compilation of giac
* Troubles::         Some tips if you are in trouble
@end menu

@node    Binaries, Requirements, Installation, Installation
@section Installing binaries
If you want to use @code{xcas/giac} like another CAS and your OS is
Intel x86 GNU/Linux or Intel StrongARM GNU/Linux or Windows 9x or Mac OS
X.4(+), then
you don't need to worry about compilation. Instead you can install
precompiled binaries:
@itemize
@item x86 GNU/Linux as a normal user: 
@uref{ftp://ftp-fourier.ujf-grenoble.fr/xcas/xcas_user.tgz}

Unpack the archive with
@command{tar xvfz xcas_user.tgz}

then
@command{cd xcas}

and
@command{./xcas}
@item x86 GNU/Linux if you have root access:
@uref{ftp://ftp-fourier.ujf-grenoble.fr/xcas/xcas_root.tgz}
Unpack the archive from the @code{/} directory
@item ARM GNU/Linux:
@uref{ftp://ftp-fourier.ujf-grenoble.fr/xcas/xcas_ipaq.tgz}
@item Windows 9x:
@uref{ftp://ftp-fourier.ujf-grenoble.fr/xcas/xcasinst.exe}.
Run @code{xcas} from the Start menu.
@item Mac OS X:
@uref{ftp://ftp-fourier.ujf-grenoble.fr/xcas/xcas_osx4.dmg.gz}.
Run @code{xcas} from the Applications.
@end itemize

@node    Requirements, Options, Binaries, Installation
@section Requirements
Get Giac source at @uref{ftp://ftp-fourier.ujf-grenoble.fr/xcas/giac_stable.tgz}
or @uref{http://perso.wanadoo.fr/bernard.parisse/}.
Check that your C++ compiler understand the C++ ANSI 3 norm. For
example @code{gcc} version 2.95 or later will work. If the GMP GNU Math 
Precision Library is not installed on your system, install it:
@uref{http://www.gnu.org/directory/gnump.html}. If you are using GNU/Linux,
the GMP library is most probably installed but the headers files
might not, check for a package named something like @code{gmp-devel}.

@node    Options, Configure, Requirements, Installation
@section Options
@enumerate
@item If you want numerical functions you should install the Gnu Scientific 
Library available at @uref{http://sources.redhat.com/gsl}
@item If you want to use NTL for some polynomial operations (currently
factorization), get version >= 5.2 at @uref{http://www.shoup.net}. Then
check that you configured with namespace enabled (this is not the
default) and with GMP enabled (not the default, but this is not mandatory)
If you are not sure of your install go in the NTL directory and type
@smallexample
 make clean
 ./configure NTL_GMP_LIP=on NTL_STD_CXX=on
 make
 make install
@end smallexample
@item If you want advanced arithmetic functions, get PARI at
@uref{http://www.parigp-home.de}.
If you plan to use an old version of PARI WITHOUT NTL then you MUST MAKE THE
FOLLOWING PATCHES in the PARI source directory:
@itemize 
@item File @code{src/basemath/polarit2.c}: remove the word 
@code{static} from the declaration:
@smallexample
  static GEN 
  combine_factors(...)
@end smallexample
@item File @code{src/headers/paridecl.h}: Add the line

@code{GEN     combine_factors(GEN a, GEN famod, GEN p, long klim, long hint);}

in the @code{* polarit2.c} section.
@item Recompile (@command{make all}) and reinstall PARI (@code{make install}) 
and check that @code{libpari.a} has been updated or copy it explicitely 
from the @code{O<your_os>} directory.
@item Replace in @code{/usr/local/include/pari/pariinl.h} @code{labs} 
by @code{std::abs} otherwise you might get compiler errors.
@end itemize
Check in the giac src directory, file pari.cc that the memory allocated
to the PARI stack suit your needs (default is 10M of RAM) or modify:
@code{  long pari_mem_size=10000000;}

@item If you want GUI support, check that you have FLTK 1.1 
installed (available at @uref{http://www.fltk.org}).

@item TeXmacs provides an interface for giac. You can get it
at @uref{http://www.texmacs.org}.
After installing giac, run texmacs and use Insert->Session->giac.

@end enumerate

@node    Configure, Compiling, Options, Installation
@section Configure options
The @code{./configure } shell-script recognizes the following options:
@enumerate
@item --enable-debug
  Allow vecteurs printing and add some debugging code
@item --enable-fltk
  GUI support
@item --enable-gsl
  Use the Gnu Scientific Library for floating point (e.g. special functions..)
@item --enable-sscl
  Allow inclusion of code for semi-classical algorithms (Moyal product, ...)
  Not available yet
@item --enable-ntl
  Allow inclusion of NTL code
@item --enable-pari
  Allow inclusion of PARI code
@end enumerate

These options can be turned off using @code{--disable-option-name} instead of 
@code{--enable-option-name}. By default @code{configure} will use these 
options if the libraries are available on your system.

For full speed binaries, before calling @code{configure} do (with bash 
as shell)

@command{$ export CXXFLAGS="-O3 -fexpensive-optimizations -malign-loops=2 -malign-jumps=2 -malign-functions=2"}

or (with tcsh as shell)

@command{$ setenv CXXFLAGS "-O3 -fexpensive-optimizations -malign-loops=2 -malign-jumps=2 -malign-functions=2"}



@node    Compiling, Troubles, Configure, Installation
@section Compiling
Like with any autoconfiguring GNU software, you can type :

@command{ ./configure }

[add options as needed: try @command{./configure -help} for option info]

@command{ make }

@command{ make check }

[become root if necessary]

@command{ make install }

Tips:
@itemize

@item If you don't want optimizations, set the environment variable 
@env{CXXFLAGS} to @code{-g} before calling configure, with tcsh
@command{ setenv CXXFLAGS -g}, with bash @command{export CXXFLAGS=-g}.

@item If you want the commandline icas only run 

 @command{ ./configure --disable-gui}

 @command{ make }

@item If you want to build xcas for the ARM processor with the Linux familiar 
distribution (e.g. for an iPaq @uref{http://www.handhelds.org})
assuming you have the skiff toolchain installed and FLTK installed.
Check that @code{config.h} defines HAVE_LIBFLTK and does not define 
HAVE_LIBGSL and HAVE_LIBGSLCBLAS unless you have these libraries too, then

@command{ make -f Makefile.ipaq}

Note that I never succeded to build with optimization for the iPaq.


@item Windows

You can compile the library version of giac like under Unix.
Or assuming you have the cygwin tools, gmp and FLTK installed (see 
@uref{http://sources.redhat.com/cygwin} for cygwin, run cygwin,
go in the @code{src} directory and run

@command{ make -f Makefile.win}

After that, you may run @code{xcas.exe} standalone, provided 
@code{/usr/bin/cygwin1.dll} has been copied in the path (e.g. in the same 
directory as @code{xcas.exe})
@end itemize


@node    Troubles, , Compiling, Installation
@section Troubles
@itemize
@item If you test giac after compilation with @code{make check},
please note that the answer assume PARI and NTL are enabled.
Otherwise you will get some errors because factoring will not
return the factors in the same order.
@item Optimization requires much memory for compilation. If you are low 
in memory edit @code{src/Makefile} and if necessary replace the line :

@code{CXXFLAGS = -g -O2}
by :

@code{CXXFLAGS = -g}

@item If you get an error like

@command{autoheader: Symbol 'CONSTANT_DEBUG_SUPPORT' is not covered by ...}

run

@command{autoheader --localdir=.}
@item If you get error when compiling @code{modpoly.cc}, it's most certainly 
because you compiled NTL without namespaces. Recompile it (see section)
@item If you get a linker error about combine_factors not found in 
@code{modfactor.o} it's because you did not modify PARI correctly or 
forgot to re-install the PARI libraries (see section)
@item Cygwin compilation of Giac with PARI 2.1.1 requires you to make
some hand work. I could not get the dynamic version of PARI library compiling.
Therefore I had to do the install by hand
@smallexample
cp libpari.a /usr/local/lib
mkdir /usr/local/include/pari
cp src/headers/*.h /usr/local/include/pari 
cp Ocygwin/*.h /usr/local/include/pari 
@end smallexample
Then I got an error compiling @code{pari.cc} that dispeared by commenting
the offending line in the header @code{/usr/local/include/pari/paricom.h}
After that all went OK.
@end itemize

@node    Xcas, Giac, Installation, Top
@chapter Using xcas, an user-interface to giac
@code{xcas} is an user-interface to giac that is similar to a calculator.
A readline interface named @code{cas} is also available.

@menu
* Interface::     
* CAS::
* Geometry::
* Spreadsheet::
* Scripting::
* Environment::
@end menu

@node Interface, CAS, ,Xcas
@section The interface
You can use but you don't need to have a keyboard to use xcas, it
is designed to be used on a PDA as well. Use the green shift button to get the
button-keyboard.

The window is composed from left and up to right and down of:
@enumerate
@item The main menu-bar: at the left: session management, configuration
and help, at the right the commands by theme
@item The session menu: file and edit operations. In the Edit menu,
the Add item lets you add levels of different kinds: commandlines,
comments, 2-d and 3-d geometry and graphs, spreadsheet, program editor
@item The session, with a blank commandline at startup
@item The buttons: help (?), switch for scientific keyboard (kbd), 
status button (in red, click here to change the CAS configuration)
@end enumerate


The on-line help gives a short description of all the CAS commands
with examples that can be pasted to the commandline. A more complete
description is available by clicking on Details. Command completion
is enabled in commandlines with the Tab key.

Printing may be done natively to Postscript or with a working
@code{LaTeX} installation (with @code{pstricks} for 2-d graphs).

@node CAS, Geometry, Interface, Xcas
@section Computer algebra system commands
A list of commands of the CAS system.
@menu
* Math menu::
* Arithmetic::
* Cas menu::
* Linear algebra::
@end menu

@node Math menu, Arithmetic, , CAS
@subsection Basic mathematic commands

@node Arithmetic, Cas menu, Math menu, CAS
@subsection Arithmetic of integers and polynomials
The @code{gcd} and @code{lcm} commands apply to both argument types : they
return the greatest common divisor or the least common multiplicator.
Other arithmetic commands must begin with an @code{i} if you want
to use them with integers, otherwise the arguments will be considered
as constant polynomials.
@menu
* Integer arithmetic::
* Polynomial arithmetic::
@end menu

@node Integer arithmetic, Polynomial arithmetic, , Arithmetic
@subsubsection Integer arithmetic functions
@menu
* Division::      Euclidean division
* Gcd::           Gcd, lcm, extended gcd, chinese remainder
* Primality::     Primality test, factorization, Euler characteristic
* Other integer:: Jacobi, Legendre symbol...
@end menu

@node Division, Gcd, , Integer arithmetic
@subsubsection Euclidean integer division
Given two integers @code{a} and @code{b}, the euclidean integer division
is defined by the equality :
@example
a=b*q+r
@end example
where usually @code{r} is taken between 0 and @code{b-1}, or
in the symmetric representation, between @code{-b/2} and @code{b/2}.
The functions @code{iquo(a,b)} and @code{irem(a,b)} return respectively
@code{q} and @code{r}, or @code{iquorem(a,b)} return both in a vector.
The @code{smod(a,b)} function will return @code{r} using the symmetric
remainder convention.

@node Gcd, Primality, Division, Integer arithmetic
@subsubsection Integer gcd
The @code{gcd(a,b)} function returns the greatest common divisor
@code{d} of two integers @code{a} and @code{b}. If you need two integers
@code{u} and @code{v} such that:
@example
a*u+b*v=d
@end example
you should call @code{egcd(a,b)} instead, it will return @code{[u,v,d]}.

The @code{ichinrem([a,n],[b,m])} call where @code{n} and @code{m}
are prime together will return a vector @code{[c,n*m]} such that
@code{c=a (mod n)} and @code{c=b (mod m)}.

@node Primality, Other integer, Gcd, Integer arithmetic
@subsubsection Primality and factorization
The @code{is_prime(a)} function will return 0 if @code{a} is not prime.
It will return 2 if @code{a} is known to be prime, and 1 if @code{a}
is a (strong) pseudo-prime. If you have compiled @code{xcas} with PARI
support, you will get a prime certificate instead (see PARI documentation for
more information).

The @code{nextprime(a)} and @code{prevprime(a)} will return the next
or previous (pseudo-)prime, given an integer @code{a}.

The @code{ifactor(a)} function returns a factorization of @code{a}.
It is a good idea to compile with PARI support if you plan to factor
relatively large integers (with prime factors having more than 20 digits).

@node Other integer, , Primality, Integer arithmetic
@subsubsection Other integer functions (Legendre, Jacobi, ...)
Additional integer functions provided by @code{xcas} are
@itemize
@item @code{jacobi(a,b)}
and @code{legendre(a,b)}, see the GMP documentation for more details.
@item @code{pa2b2(p)} return @code{[a,b]} so that @code{p=a*a+b*b}
if @code{p=1 (mod 4)} is prime.
@end itemize

@node Polynomial arithmetic, , Integer arithmetic, Arithmetic
@subsubsection Polynomial arithmetic functions
Polynomials have two representations: symbolic representation or
by a vector of coefficients. In the symbolic representation you might
add the variable name as an additionnal parameter to the functions
you call, otherwise the default variable is used. For the vector
representation, it is recommended to use the right delimiter @code{poly1[}
instead of @code{[} so that usual operations (addition, ...) behave
correctly (i.e. not like vectors or matrices).
@enumerate
@item @code{quo(a,b)} @code{rem(a,b)} and @code{quorem(a,b)}
return respectively @code{q}, @code{r} and @code{[q,r]} polynomials
so that @code{a=b*q+r} and @code{degree(r)<degree(b)}
@item @code{gcd(a,b)} return the greatest common divisor of two
polynomials
@item @code{egcd(a,b)} is the extended euclidean GCD algorithm, like for
integers it returns a list of 3 polynomials @code{u,v,d} such
that @code{au+bv=d}.
@item @code{chinrem} return the chinese remainder for polynomials written 
as lists. The 2 arguments are two lists made of a polynomial modulo
another polynomial (where the modulo polynomials must be prime together). 
The answer is the polynomial modulo the product of the modulo polynomials
that reduce to the original polynomials modulo the original modulo
polynomials
@item @code{cyclotomic} takes an integer n as argument and returns the
n-th cyclotomic polynomial.
@end enumerate

@node Cas menu, Linear algebra, Arithmetic, CAS
@subsection Algebra, calculus, ...
@menu
* Rewriting::
* Diff and integrate::
* Limits and series::
* Solving equations::
* Other cas functions::
@end menu

@node Rewriting, Diff and integrate, , Cas menu
@subsubsection Rewriting expressions
The @code{normal} command rewrites a rational fraction as a ratio of two
coprime polynomials. If an expression is not rational, it is first
rationalized by substitution of transcendental expressions (e.g.
@code{sin(x)} by a temporary identifier. Algebraic expressions
(e.g. @code{sqrt(x)}) are normalized too.

The @code{factor} command factorize polynomials. Like above a non
polynomial expression is first rationalized. You can choose the main
variable with respect to which the polynomial will be factorized by
adding it as second argument of @code{factor}.

The @code{texpand} function is called to expand transcendental
expressions like @code{exp(x+y)=exp(x)*exp(y)} or similar rules
for trigonometric functions. The @code{tlin} function does
the reverse operation for trigonometric functions, as the @code{lin}
function does it for exponentials.

The @code{halftan} function rewrites trigonometric expressions
in terms of the tangent of the half angle. The @code{hyp2exp}
function rewrites hyperbolic functions in terms of exponentials.

@node Diff and integrate, Limits and series, Rewriting, Cas menu
@subsubsection Derivation, integration
The differentiation instruction is @code{diff(expression,variable)}.
The undefined antiderivative is obtained using
@code{integrate(expression,variable)}. If you need defined integration
between bounds @code{a} and @code{b}, choose
@code{integrate(expression,variable,a,b)} for exact integration
or @code{romberg(expression,variable,a,b)} for numeric integration.

Example of defined integration are Fourier coefficients of periodic
functions. They are provided using @code{fourier_an} and @code{fourier_bn}
for trigonometric coefficients or using @code{fourier_cn} for
complex exponentials coefficients.

Some discrete antiderivatives may be obtained using the
@code{sum(variable,expression)} call.

@node Limits and series, Solving equations, Diff and integrate, Cas menu
@subsubsection Limits, series expansion.
For a limit the syntax is
@code{limit(expression,variable,limitpoint[,direction])}.
For a series expansion
@code{series(expression,variable,limitpoint,order[,direction])}.
@code{giac} implementation of @code{limit} and @code{series} is based
on the mrv algorithm. 

@node Solving equations, Other cas functions, Limits and series, Cas menu
@subsection Solving equations
The @code{solve(expression,variable)} call is used to find exact
solutions of (polynomial-)like equations. Use @code{newton} instead
for numeric solutions (of a wider range of equations).

@node Other cas functions, , Solving equations, Cas menu

@node Linear algebra, , Cas menu, CAS
@subsection Linear algebra
Arithmetic operations on matrices and vectors are done using the usual
operators. The scalar product of two vectors is obtained using the @code{*}
operator.

Gaussian elimination (Gauss-Bareiss) over a matrix is performed
using @code{rref(m)}. The kernel of a linear application with matrix
m is obtained with @code{ker(m)}. A system of linear equations (written
symbolically in a vector) can be solved via
@code{linsolve([equations],[variables])}.

The determinant of a matrix may be obtained using two algorithms,
either Gauss-Bareiss invoking @code{det(m)}, or by computing minors
@code{det_minor(m)}. Actually, a last method is provided using the
computation of the constant coefficient of the characteristic polynomial
using Fadeev-Leverrier algorithm.

The characteristic polynomial of a matrix may be computed by Fadeev-Leverrier
algorithm calling @code{pcar(m)}. For matrices withe coefficients in
a finite field, @code{pcar_hessenberg(m)} is a better choice (@code{O(n^3)}
complexity where @code{n} is the size of the matrix).

Eigenvalues and eigenvectors are computed using respectively @code{egvl(m)}
and @code{egv(m)}. The Jordan normal form is obtained invoking
@code{jordan(m)}.

Quadratic forms (written symbolically) can be reduced to sum and differences
of squares using @code{gauss(expression,[variables])}.

There is some support for isometries: @code{mkisom} may be used to
make an isometry from its proper elements as @code{isom(m)} return the
proper elements of an isometry.

@node Geometry, Spreadsheet, CAS, Xcas
@section Geometry
Add a figure (Edit menu of the session, Add item, then select geometry
and graph 2-d or 3-d).
As other objects, you can create geometrical objects anatically using the
commandlines at the left. You may also create points,
segments, etc. with the mouse (or the stylus) or move a geometrical
object depending on the mouse mode (Pointer, point, segment, circle, etc.)

To configure or print a graph, use the menu at the right of the graph.

@node Spreadsheet, Scripting, Geometry, Xcas
@section Spreadsheet
Add a spreadsheet (Edit menu of the session, Add item, spreadsheet).
Cells may have a formal value, or eval to a geometric 2-d object
that will be displayed in a dynamically linked 2-d graph.

@node Scripting, Environment, Spreadsheet, Xcas
@section The xcas scripting language
The xcas and icas program provide an interpreted language that is similar to 
popular other CAS programming language. This scripting language is
available in 4 flavours: C-like syntax (default) or compatibility
mode for simple Maple, Mupad or TI programs. We describe only the C-like
syntax. Instructions must end with a semi-column @code{;}. Groups of 
instructions may be combined like in C with brackets.

You can define a program in a commandline, but it is recommended
to use a Program Editor (Edit->Add->Program menuitem of the session
menubar) if it is larger than a few lines.

@menu
* Language mode::
* Data::
* Loops and conditionnals::
* Functions::
@end menu

@node Language mode, Data, , Scripting
@section Selecting the language mode
Click on the status button and select the programming style.
Alternatively, the command @code{maple_mode(0)} or @code{maple_mode(1)} or 
@code{maple_mode(2)} may be used to switch the language flavour
respectively from C-like to Maple-like or Mupad-like mode. Note that this
command takes effect only when the current parser session is finished
which means when the next command is processed in interative mode or at 
the end of the current file in batch mode, hence you should not begin a script 
file with this command. In batch mode you can achieve the mode switch by 
setting the environment variable @code{GIAC_MAPLE_MODE}, for example with
tcsh: @command{setenv GIAC_MAPLE_MODE 1} 
or with bash @command{export GIAC_MAPLE_MODE=1}
will switch to the Maple-like language. Additionnally you can enter
the @code{maple_mode(1)} command in the @code{.xcasrc} of your home directory
to change the default behavior. Or inside @code{xcas} you can run
the @code{Import} command of the @code{File} menu and select the flavour.
The @code{Export} command can be used to translate the current level
of the history inside @code{xcas} to a file, or the @code{View as} command
of the @code{Edit} menu to translate to the Help output window.

@node Data, Loops and conditionnals, Language mode, Scripting
@section Data
The language accept local and global variables, variables are not typed.
Global variables do not need to be declared, local variables must be declared
at the beginning of a function by the keyword @code{local} followed by 
the names of the local variables separated by commas @code{,} with a final 
semi-columns @code{;}

The affectation sign is @code{:=} like popular CAS and unlike C.
For large vectors, lists and matrices, you may also use @code{=<} to make
in-place modifications (in other words by reference), but be aware
that all references of the object will be modified.
Other operations (e.g. @{+ - * /@}) and function calls are done like in C 
or like in an interactive session.
As in C, the equality test is @code{==}. The single equal sign @code{=}
is used to return an equation (note that
an equation will be transformed in a test
in some situations where an equation could not be expected).
The other tests are @code{!=} for non equal, @code{< <= > >=} for
real value comparisons. You can combine tests with @code{&&} or @code{and},
and @code{||} or @code{or}. The boolean negation is @code{!} or @code{not}.

@node Loops and conditionnals, Functions, Data, Scripting
The loop keywoard is like in C 

@command{for (initialization;while_condition;increment)@{ loop_block @}}

You can break a loop inside the loop block with @code{break;}. 
You can skip immediately to the next iteration with @code{continue;}.

The conditionnal keywoard is like in C

@command{if (condition) @{ bloc_if_true @} [ else @{ bloc_if_false @} ]}

Additionnaly, multiple-cases is translated like in C

@command{swith (variable)@{ case (value_1): ... break; default: ... ; @} }

@node Functions, , Loops and conditionnals, Scripting
Functions are declared and implemeted together like this

@command{function_name(parameters):=@{ definition @}}

Parameters are like local variables with an additional initialization 
from the values of the parameters inside the calling instruction.

@code{return return_value;} should be used to return the value
of the function.

It is not possible to pass arguments by reference, only by value.


@node Environment, ,  Scripting, Xcas
@section Environment variables
If one of these variables @code{GIAC_MAPLE}, @code{GIAC_MUPAD},
@code{GIAC_C} or @code{GIAC_TI} is defined, the corresponding
syntax mode will be in effect. If @code{XCAS_RPN} is defined,
then xcas will start in RPN mode.

The variable @code{XCAS_ROOT} may be used for a custom xcas installation,
it should point to the directory where xcas is installed. @code{XCAS_LOCALE}
should point to the directory where the locales are. @code{XCAS_TMP}
may be defined for temporary exchange files between xcas processes,
if not defined it will use the home directory.

The variable @code{PARI_SIZE} may be used to define the memory
available for pari.

The variable @code{BROWSER} may be used for the HTML documentation browser.

The variable @code{LANG} may be used for internationalization.

The variable @code{GIAC_TIME} and @code{GIAC_TEX} may be used
in giac readline interface to ask for timing and tex output.
@code{GIAC_DEBUG} will give some info on the internals used.

@node    Giac, Examples, Xcas, Top
In this chapter we will first describe the generic data type of giac,
the @code{gen} class. Then we describe the most important data
types than @code{gen} dispatches to (polynomials, vectors, symbolic
objects and gen unary functions). At this point, the reader should be
able to code using @code{giac}, hence we describe how to integrate
code to @code{giac} by inclusion in the library or as a separate
runtime loadable library (called module). The last item describes
how you can add new mathematical objects, e.g. quaternions,
inside the @code{gen} type.

@menu
* C++::                       Why we choosed C++
* Gen::                       The generic class used everywhere in giac
* Polynomials::               Polynomials.
* Vectors and matrices::      Vectors and matrices.
* Symbolics::                 Symbolics.
* Unary functions::           Functions taking a gen and returning a gen
* Making a library function:: Add functionnalities to giac
* Making modules::            Add dynamically loadable functions to giac
* User defined data::         Define your own data inside giac
@end menu

@node C++, Gen, , Giac
Giac uses the C++ language because it is easier to write algebraic
operations using usual operators, for example @code{a+b*x} is easier
to understand and modify than @code{add(a,mul(b,x))}, but it does not 
require that you learn object oriented programming. In fact it is more 
a C library using C++ features that makes programming easier (like the 
I/O streams and the Standard Template Library). However you will need
a recent C++ compiler, e.g. @code{gcc} version 2.95 or later.


@node Gen, Polynomials, C++, Giac
@chapter The gen class
@cindex gen

@code{gen} is the class used to represent mathematical objects 
(@code{#include <giac/gen.h>}). It's a C union, made either of ``direct'' 
objects like @code{int} or @code{double}
or of pointers to heap allocated objects that are reference counted.
Memory allocation is handled by the class itself (except for
user-defined object types). You can check
the actual type of a variable of type @code{gen}, e.g. @code{gen e;}, 
using it's @code{type} field (e.g. @code{if (e.type==...)}). This
@code{type} field of a @code{gen} is an @code{int}. 

The @code{gen} might be~:
@enumerate
@item an immediate int (@code{e.type==_INT_})
@item a double (@code{e.type==_DOUBLE_})
@item an arbitrary precision integer (@code{e.type==_ZINT})
@item a complex number (@code{e.type==_CPLX}), a pointer to 
two objects of type @code{gen} the real and imaginary parts
@item a global name (@code{e.type==_IDNT}), with a pointer to an 
@code{identificateur} type 
@item a symbolic object (@code{e.type==_SYMB}), with a pointer to
a @code{symbolic} type
@item a vector object (in fact it is a list) (@code{e.type==_VECT}), 
with a pointer to a @code{vecteur} type
@item a function object (@code{e.type==_FUNC}),
with a pointer to a @code{unary_function_ptr} type
@end enumerate

Some other types are available (e.g. a pointer to @code{gen_user}
an object you can derive to make your own class, or arbitrary precision
floating point numbers @code{_REAL}), for a complete 
description look at @code{giac/gen.h} (if you have installed @code{giac} 
the path to the include files is @code{/usr/local/include/giac} unless you
override the default, if you did not install it, the path is the path
to the @code{src} directory of the source code distribution).

If you want to access the underlying type, after checking that the type
is correct, you can do the following:
@enumerate
@item for immediate int: @code{int i=e.val;}
@item for double: @code{double d=e._DOUBLE_val;}
@item for arbitray precision integers: @code{mpz_t * m=e._ZINTptr;}
@item for complex numbers: @code{gen realpart=*e._CPLXptr,impart=*(e._CPLXptr+1); }
@item for identificateur: @code{identificateur i=*e._IDNTptr; }
@item for symbolics: @code{symbolic s=*e._SYMBptr;}
@item for composites: @code{vecteur v=*e._VECTptr;}
@item for function objects: @code{unary_function_ptr u=*e._FUNCptr}
@end enumerate

In addition to the main @code{type}, each @code{gen} has a @code{subtype}.
This subtype is used sometimes to select different behaviour, e.g.
adding a constant to a vector might add the constant to all terms for
some geometric objects represented using vectors, only to the term of 
the diagonal of a square matrix, or to the last term for dense polynomials.
See @code{giac/dispatch.h} for the description of the subtypes.

@node Polynomials, Vectors and matrices, Gen, Giac
@cindex Polynomials
@section Polynomials
Polynomials are available as: 
@itemize
@item sparse multivariate polynomials @code{polynome}, 
header files are @code{gausspol.h}, @code{poly.h}, @code{monomial.h}
@item dense univariate polynomials: @code{poly1} or alias @code{modpoly} 
used for modular univariate polynomials. The type used is the same
as for vectors and matrices.
Header files are @code{giac/modfactor.h} and @code{giac/modpoly.h}.
@end itemize

A @code{gen} can be a polynomials if it's @code{type} field is
respectively @code{_POLY} (sparse) or @code{_VECT} (dense).
Conversion functions to and from the symbolic representation with
respect to global names are declared in @code{giac/sym2poly.cc/h}.

@node Vectors and matrices, Symbolics, Polynomials, Giac
@cindex Vectors
@cindex Matrices
@section Vectors and matrices
The type used for vectors and matrices is the same, it's a
@code{std::vector<gen>} (unless you have configured with
@code{--enable-debug}). The header file is @code{giac/vecteur.h}.
A @code{gen} can be a vector if it's @code{type} field is
@code{_VECT}.

@node Symbolics, Unary functions, Vectors and matrices, Giac
@cindex Symbolics
@section Symbolics
Symbolic objects are trees. The @code{sommet} is a @code{unary_function_ptr}
(a class pointing to the function). The @code{feuille} is either
an atomic @code{gen} (for a function with one argument) or a composite
(@code{feuille.type==_VECT}) for a function with more than one argument
(these functions appears therefore as a function with one argument which
is the list of all it's arguments).

@node Unary functions, Making a library function, Symbolics, Giac
@cindex Unary functions
@section Unary functions
In the giac library, every function is viewed as a function taking one
argument and returning one argument. Almost every Xcas functions have
a C++ equivalent with the same name preceded by a _.
If a Xcas function has more than one argument, these arguments 
are packed in a vector which is the first argument of the C++ function. 
Most C++ functions require a second argument, which is
a context pointer. This context pointer 
encapsulate all the context (e.g. complex vs real mode, or all the 
variables that are assigned or assumed). You can use
@code{giac::context0} as global context pointer or define a context
@code{giac::context ct;} and use @code{&ct} as last argument to the function. 

The files @code{usual.cc/.h} give examples of declaration e.g. for
exponential and trigonometric functions. Unary functions have the
following members~:
@itemize
@item a fonction taking a @code{gen} and a @code{context *}
and returning an @code{gen} which does the job
@item partial derivatives of this function if they exist
@item a special Taylor expansion if it's needed (see e.g. @code{taylor_asin}).
This is always the case if your function is defined at infinity.
Note that this function
is called at initialization so that you can include code in it for
example to add your function to the symbolic preprocessing step of the
@code{limit/series} algorithm.
@item a string identifier for printing. If you want the parser to
recognize your function you must add a line in @code{input_lexer.ll}
(see for example @code{"sin"}) or you must register it (see below).
@item two special printing function if normal printing (normal printing
means printing the function name followed by the argument(s) in parentheses) 
is not the right way to print. A null pointer means using normal
printing.
@end itemize
Once your @code{unary_function_eval} is defined, you must construct
a @code{unary_function_ptr} to be able to use it inside symbolics.
When declaring the @code{unary_function_ptr},
you may give an optional argument to specify a behavior for the evaluation
of arguments (quoting or special parser rules). 
In this case, you may give a second optionnal argument 
to register your function dynamically in the list of function names 
recognized by the lexer. Be sure to link the object file so that
initialization occurs after the initialization of @code{input_lexer.ll},
it means you must put your object file before @code{input_lexer.o}
when linking (see for example the position of @code{moyal.o} in
the @code{Makefile.am} file, @code{moyal}
is one example where dynamic registering is done).

You have of course the option to declare the function name
statically in the file @code{input_lexer.ll} but this is not recommended.

@node Making a library function, Making modules, Unary functions, Giac
Here is one example of a dynamically linkable function named
@code{example} which takes 2 arguments and returns the sum divided
by the product if the argument are integers and return itself otherwise. 
The C++ header @code{example.h} code looks like
@example
#ifndef __EXAMPLE_H
#define __EXAMPLE_H
#include <giac/config.h>
#include <giac/gen.h>
#include <giac/unary.h>

#ifndef NO_NAMESPACE_GIAC
namespace giac @{
#endif // ndef NO_NAMESPACE_GIAC

  gen example(const gen & a,const gen & b,GIAC_CONTEXT);
  gen _example(const gen & args,GIAC_CONTEXT);
  extern const unary_function_ptr * const at_example ;

#ifndef NO_NAMESPACE_GIAC
@} // namespace giac
#endif // ndef NO_NAMESPACE_GIAC
#endif // __EXAMPLE_H
@end example

The C++ source code looks like:
@example
using namespace std;
#include "example.h"
#include <giac/giac.h>

#ifndef NO_NAMESPACE_GIAC
namespace giac @{
#endif // ndef NO_NAMESPACE_GIAC

  gen example(const gen & a,const gen & b,GIAC_CONTEXT)@{
    if (is_integer(a) && is_integer(b))
      return (a+b)/(a*b);
    return symbolic(at_example,makesequence(a,b));
  @}

  gen _example(const gen & args,GIAC_CONTEXT)@{
    if ( (args.type!=_VECT) || (args._VECTptr->size()!=2) )
      return gensizeerr(contextptr); // type checking : args must be a vector of size 2
    vecteur & v=*args._VECTptr;
    return example(v[0],v[1],contextptr);
  @}
  const string _example_s("example");
  static define_unary_function_eval (__example,&_example,_example_s);
  define_unary_function_ptr5( at_example ,alias_at_example,&__example,0,true);

#ifndef NO_NAMESPACE_GIAC
@}
#endif // ndef NO_NAMESPACE_GIAC
@end example

Compile it with
@example
c++ -g -c example.cc 
@end example

To test your code, you should write the following @code{test.cc} program
@example
#include "example.h"
 
using namespace std;
using namespace giac;
 
int main()@{
  gen args;
  context ct;
  cout << "Enter arguments of example function, for example 2,3 ";
  cin >> args;
  cout << "Result: " << _example(args,&ct) << endl;
@}
@end example
Compile it with the command
@example
c++ -g example.o test.cc -lgiac -lgmp
@end example
You might need to link to other libraries e.g. 
@code{-lreadline -lhistory -lcurses} depedning on your installation.
Then run @code{a.out}. Here you would test e.g. with @code{[1,2]}.

You can debug your program as usual, e.g. with
@code{gdb a.out}, it is recommended to create a @code{.gdbinit} file
in the current directory so that you can use the @code{v} command
to print giac data, the @code{.gdbinit} file should contain :
@example
echo Defining v as print command for giac types\n
define v
print ($arg0).dbgprint()
end
@end example

When your function is tested, you can add it to the library. Edit
the file @code{Makefile.am} of the @code{src} subdirectory 
of @code{giac} : just add @code{example.cc} before @code{input_lexer.cc} 
in the @code{libgiac_la_SOURCES} line and add @code{example.h} in the
@code{giacinclude_HEADERS} line.

To rebuild the library go in the @code{giac} directory and type
@code{automake; make}

If you want to share your function(s) with other people, you must
license it under the GPL (because it will be linked to GPL-ed code).
Add the GPL header to the files, and send them to the @code{giac}
contribution e-mail, currently @code{mailto:parisse@@fourier.ujf-grenoble.fr}
@example
/*
 *  Copyright (C) 2007 Your name
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
@end example

@node  Making modules, User defined data,  Making a library function, Giac
Another way to share your code could be to build a dynamic library
that can be loaded at runtime using facilities of @code{<dlfcns.h>}.
Warning: modules do not work with static binaries. Be sure
to have dynamic binaries (this is the default when you compile giac,
but the packaged @code{xcas} distributed as a binary is build static to
avoid incompatible libraries).

Let us define a function named @code{mydll} in the file @code{mydll.cc} like
this :
@example
#include <giac/config.h>
#include <giac/giac.h>

#ifndef NO_NAMESPACE_GIAC
namespace giac @{
#endif // ndef NO_NAMESPACE_GIAC

  const string _mydll_s("mydll");
  gen _mydll(const gen & args,GIAC_CONTEXT)@{
    return sin(ln(args,contextptr),contextptr);
  @}
  unary_function_eval __mydll(0,&giac::_mydll,_mydll_s);
  unary_function_ptr at_mydll (&__mydll,0,true); // auto-register

#ifndef NO_NAMESPACE_GIAC
@} // namespace giac
#endif // ndef NO_NAMESPACE_GIAC
@end example

Compile it like this
@example
c++ -fPIC -DPIC -g -c mydll.cc -o mydll.lo 
cc -shared  mydll.lo  -lc  -Wl,-soname -Wl,libgiac_mydll.so.0 -o libgiac_mydll.so.0.0.0
rm -f libgiac_mydll.so.0 && ln -s libgiac_mydll.so.0.0.0 libgiac_mydll.so.0
rm -f libgiac_mydll.so && ln -s libgiac_mydll.so.0.0.0 libgiac_mydll.so
@end example

The library is loadable at runtime in a session using the command
@code{insmod("mydll")} 
assuming it is stored in a directory available
from @code{LD_LIBRARY_PATH} or in @code{/etc/ld.so.conf} otherwise
you must put a path to the library file (beginning with @code{./} if
it is in the current directory), something like
@code{insmod("/path_to/libgiac_mydll.so")}

A nice way to test your code is to add the following line in your
@code{~/.xcasrc} file :
@example
insmod("path_to_libmydll/libmydll.so");
@end example
where you replace @code{path_to_libmydll.so} with the actual path to 
@code{libmydll.so} for example @code{/home/joe} if your login name is
@code{joe} and @code{mydll} is in your home directory.
Then if you are using @code{emacs} as editor, put as first line of 
the file @code{mydll.cc}
@example
// -*- mode:C++ ; compile-command: "g++ -I.. -fPIC -DPIC -g -c mydll.cc -o mydll.lo && ln -sf mydll.lo mydll.o && gcc -shared mydll.lo -lc  -Wl,-soname -Wl,libmydll.so.0 -o libmydll.so.0.0.0 && ln -sf libmydll.so.0.0.0 libmydll.so.0 && ln -sf libmydll.so.0.0.0 libmydll.so" -*-
@end example
Now you can compile it with @code{Compile} of the menu @code{Tools}
and the resulting code is automatically loaded when you launch a new
session with @code{xcas} or @code{cas} which makes testing a breath.

@node  User defined data, , Making modules, Giac
@cindex  User defined data
@section  User defined data
The class @code{gen_user} can be derived so that you can include
your own data inside @code{gen}. Look at the declaration of @code{gen_user}
in the file @code{gen.h} and at the example of the quaternions
in the files @code{quater.h} and @code{quater.cc}.

@node    Examples, Concept Index, Giac, Top
@chapter Some examples of C++ program using giac

@menu
* First example::     
@end menu

@node    First example, , , Examples
@chapter A first simple example
Type the following text with your favorite editor

@smallexample
#include <giac/config.h>
#include <giac/giac.h>
using namespace std;
using namespace giac;

int main()@{
  context ct;
  gen e("x^2-1",&ct);
  e=eval(e,1,&ct);
  cout << _factor(e,&ct) << endl;
@}
@end smallexample

save it e.g. as @code{tryit.cc} and compile it with

@command{c++ -g tryit.cc -lgiac -lgmp}

If you get unresolved symbol, then @code{readline} is probably enabled
and you should compile like that

@command{c++ -g tryit.cc -lgiac -lgmp -lreadline -lcurses}

You can now run @code{a.out} which will print the factorisation of 
@code{x^2-1}.
 
You can also run the program step by step using gdb. We
recommended that you copy the file @code{.gdbinit} from the @code{src}
directory of the giac distribution, because it enables using 
@code{v varname} to print the variable @code{varname} of type @code{gen}.

Some explanations of the code: 
@itemize
@item the @code{#include <giac/giac.h>}
directive includes all the headers of giac (which includes some STL
headers like @code{string} or @code{vector}). 
@item The @code{using namespace}
directive are not mandatory, if you don't use them, you need to modify
some of the code, e.g. use @code{std::string} instead of @code{string}
or @code{giac::gen} instead of @code{gen}. 
@item Variables of type @code{gen}
can be constructed from strings (using the parser), from some C types
(like @code{int} or @code{double}), from the STL type 
@code{std::complex<double>} or from streams (using the parser).
@item Operations like @code{+, -, *} are defined on the @code{gen} type
but the division is not redefined to avoid confusion between integers 
(use @code{iquo}) and double C division (use @code{rdiv}). For powers, 
use @code{pow} as usual.
@end itemize

@node    Concept Index,    ,  Examples, Top
@comment node-name,    next,  previous, up
@unnumbered Concept Index

@printindex cp

@contents
@bye
