#
#
#  Here we store all the Description that will generate the 'description'
#  entry of each function.  Instead, print() will generate the description
#  on the fly, which has several advantages (saves spaces in darwinit and
#  hence loads faster, can be tailored to the width, other formats are
#  possible, e.g. html, etc.)
#
#                                       Gaston H. Gonnet (May 1998)
#
# Extensive modifications and additions:  M. Hallett, (Okt, 1998)

# help/makehelp reads the SwissProt database, fake it for the helps.
FakeReadDb := Fake( 'DB := ReadDb(''/home/darwin/DB/SwissProt.Z''):',
'Peptide file(/home/darwin/DB/SP45.0/SwissProt45.0(169638448), 163235
 entries, 59631787 aminoacids)' );

SeeAlsoDocument := SeeAlso( Paragraph, Block, DocEl, Table, Indent, Document, Code, Color,
	List, HyperLink, LastUpdatedBy, print, HTML, latex, screenwidth,
	Roman, RunDarwinSession, TT, View, Copyright, PostscriptFigure ):
SeeAlsoLinAlg := SeeAlso( Identity, GivensElim, transpose, Cholesky,
  convolve, GaussElim, Eigenvalues, LinearProgramming, matrix_inverse, matrix ):

SeeAlso_Plot := SeeAlso( PlotArguments, DrawHistogram, DrawStackedBar,
    DrawDotplot, DrawDistribution, SmoothData, ViewPlot, StartOverlayPlot,
    DrawPlot, StopOverlayPlot, GetColorMap, Set,  DrawGraph,
    DrawPointDistribution, Plot2Gif, ColorPalette, BrightenColor, DrawTree ):

SeeAlso_symbolic := SeeAlso( has, hastype, indets, subs, coeff, lcoeff,
    mselect, types, noeval ):

SeeAlso_SearchString := SeeAlso( SearchString, CaseSearchString, BestSearchString,
    SearchMultipleString, HammingSearchString, SearchDelim, SearchApproxString,
    MatchRegex):

abs_Description := Description( function(abs),
  Summary( 'absolute value' ),
  CallingSequence( noeval(abs(x)), 'abs(x)' ),
  Parameters( ['x',numeric, 'an expression'] ),
  Returns(numeric),
  Synopsis( 'This function computes the absolute value of a number.
Two syntaxes are available, the functional one, abs(x) or the
mathematical with vertical bars: |x|.
Please note that |x|, when x is an array is not the norm of the vector,
but the vector of the absolute values.' ),
  Examples( '|-0.3|', 'abs(cos(3))', '|[-1,-2,-3]|' )
  ):

NormalizePath_Description := Description( function(NormalizePath),
  Summary('normalize path'),
  CallingSequence( noeval(NormalizePath(path)) ),
  Parameters( ['path', string, 'path expression'] ),
  Returns(string),
  Synopsis('This function normalizes a path, i.e. it eliminates double 
slashes, double points, etc.'),
  Examples( 'NormalizePath(''/path/to/not/../obscure/file/.//'')'),
  SeeAlso(FileStat)
):

Align_Description := Description( function(Align),
  Summary('align sequences using various modes of dynamic programming'),
  CallingSequence( noeval(Align(seq1,seq2,method,DayMat)) ),
  Parameters(
    [seq1,{string,ProbSeq},'pept, nucleot or probabilistic sequence'],
    [seq2,{string,ProbSeq},'pept, nucleot or probabilistic sequence'],
    [method,string,'the mode of dynamic programming to use'],
    [DayMat,{DayMatrix,list(DayMatrix)},'Dayhoff matrices used for alignment']),
  Returns(Alignment),
  Synopsis( 'Align does an alignment of two sequences using the
similarity scores given in the DayMat and the given method.
If a single DayMatrix is given, the alignment is done using it.
If a list of DayMatrix is given, it is understood that the best
PAM matrix be used.  In this case Align will also compute the
PamDistance and PamVariance between the two sequences.
The method is optional, if not given it assumes Local.
The valid methods are:'), '',
Paragraph( -8, 'Local   A local alignment will be performed,
this means that the best subsequences of seq1 and seq2 will be
selected to be aligned.  This type of alignment gives the highest
possible similarity score of any alignment.  This is sometimes
called the Smith & Watermann algorithm.'),
Paragraph( -8, 'Global  A global alignment will be performed,
this means that the entire seq1 is aligned against the entire seq2.
This may result in a negative score if the sequences do not align
very well.  This is sometimes called the Needleman & Wunsch algorithm.'),
Paragraph( -8, 'CFE     A Cost-Free ends alignment is done.
This is like a Global alignment, but deletions of one of the
sequences at each of the end are not penalized.  In some sense
it is between a Local and a Global alignment.'),
Paragraph( -8, 'Shake   A forward-backward alignment is performed.
This alignment iterates forward and backwards until the score cannot
be increased.  In its forward phase will start at the given positions
for seq1 and seq2 and find the ends which give a maximal score.
From this end, it will perform backwards dynamic programming to
find the optimal beginning, and so on until convergence.
This type of alignment is quite similar to a Local alignment, but
can be directed to focus on a particular alignment, even though
it may not be the best of the two sequences.'), '',
Paragraph( -2, 'If the DayMat is omitted, the global variable DM
(if assigned a DayMatrix) is used, else a PAM-250 matrix is
constructed.'),
Paragraph( -2, 'If in addition to the method, the keyword "NoSelf"
is included, when sequences of peptides or nucleotides are
aligned (excluding ProbSeq), self-matches are not allowed.
That is, if a sequence is aligned to itself (being structurally
the same string, this we call self-alignment), the self-match
(which is trivial) will not be allowed.  This is done by giving
the alignment of a position with itself a large penalty.
By doing this it is possible to find repeated patterns.
I.e. an alignment with itself, where the identity is ruled out,
will show any repeated patterns.  In particular if the sequences
align with an offset of k, then there is a k-long motif which is
repeated in the sequence.' ),
Paragraph( -2, 'The method to find the approximate PamDistance
and variance may not find the global maximum of the Score, it may
find a local maximum.
By using the argument "ApproxPAM=ppp", the search for the maximum
will be started at PAM distance ppp.
This may help when we know an approximation of the distance,
or may provide a way of exploring the existence of other local
maxima.' ),
  Keywords('dynamic programming',alignments),
  Examples(
    'Align(AC(P00083),AC(P00091))',
    'Align(Entry(1),Entry(2),Local,DMS)',
    'Align(AC(P13475),AC(P13475),Local,DMS,NoSelf)' ),
  SeeAlso( EstimatePam, CalculateScore, Align, Alignment, MAlign,
DynProgScore, DynProgStrings, CodonAlign )
):

MAlign_Description := Description( function(MAlign),
  Summary('multiple sequence alignment using various methods'),
  CallingSequence( noeval(MAlign(seqs, method, labels, tree, allall)) ),
  Parameters(
    [seqs,list(string),'sequences to align'],
    [method,string,'(optional) method(s) to compute the alignment'],
    [labels,list(string),'(optional) labels for the sequences'],
    [tree,Tree,'(optional) Tree used by the prob method'],
    [allall,matrix({0,Alignment}),'(optional) all-against-all Alignments']),
  Returns(MAlignment),
  Synopsis( 'MAlign does a multiple sequence alignment (MSA) using
the given method(s).
The valid methods are:'), '',
Paragraph( -8, 'prob          Probabilistic method to build MSA'),
Paragraph( -8, 'circ          Circular tour method to build MSA'),
Paragraph( -8, 'best          Chooses the best of 4 methods (expensive)'),
Paragraph( -8, 'Global        Global alignments between sequences'),
Paragraph( -8, 'Local         Local alignments between sequences'),
Paragraph( -8, 'CFE           Cost Free End alignments between sequences'),
Paragraph( -8, 'GapHeuristic  Use gap heuristics to improve the result'),
Paragraph( -2, 'If a method is not specified, the probabilistic
method will be used.
The GapHeuristic can be specified in addition to the other method
specification.' ),
Paragraph( -2, 'If a tree is not provided, it will be
calculated (for the Probabilistic method which needs a tree).'),
Paragraph( -2, 'If an all-against-all Alignment array is not provided,
one will be calculated.
With the method  best, 4 different multiple sequence alignments will
be computed (circular, and probabilistic with Local, CFE and Global)
and the best scoring one will be returned.
GapHeuristics are used for the 4 methods.
This is naturally 4 times more expensive than a single alignment and
should be used with care.'),
  Examples(
    Print('msa := MAlign([''ASDFAA'',''ASDAV'',''ASFDAA'']):'),
    Print('print(msa)'),
    Print('msa := MAlign([''ASDFAA'',''ASDAV'',''ASFDAA''], ''circ''):'),
    Print('print(msa)'),
    Unassign('msa') ),
  SeeAlso( Align, Alignment, DynProgScore, Clusters, MAlignment,
DynProgStrings )
):

Alignment_Description := Description(
  structure( Alignment ),
  Summary( 'a protein or DNA pairwise sequence alignment' ),
  CallingSequence( noeval( Alignment( Seq1, Seq2, Score,
        DayMatrix, PamDistance, PamVariance, modes ))),
  Parameters(
	[ Seq1, string, 'the first protein or DNA sequence'],
	[ Seq2, string, 'the second protein or DNA sequence'],
	[ Score, numeric, 'score of the alignment'],
	[ DayMatrix, DayMatrix, 'Dayhoff matrix used'],
	[ PamDistance, numeric, 'estimate of the PAM distance or 0'],
	[ PamVariance, numeric, 'variance of the PAM distance or 0'],
	[ modes, set(string), 'optional modes of alignment'] ),
  Selectors(
	[ Identity, numeric, 'fraction identical positions (0..1)' ],
	[ Length1, posint, 'length of Seq1'],
	[ Length2, posint, 'length of Seq2'],
	[ Offset1, integer, 'database offset of Seq1'],
	[ Offset2, integer, 'database offset of Seq2'],
	[ PamNumber, numeric, 'synonym of PamDistance' ],
	[ Sim, numeric, 'synonym of Score' ],
    [ Evalue, numeric, 'Evalue of Alignment']),
  Synopsis('An Alignment stores the information of a pairwise
alignment between two sequences (protein or DNA).
It replaces the Match structure, which is now obsolete.
If the mode for the alignment is just Local or unknown, it is
omitted, otherwise it is a set with one of {Local,Global,CFE,Shake}
and optionally NoSelf.' ),
  SeeAlso( EstimatePam, CalculateScore, Align, Alignment, EstimateLogEvalue,
MAlignment, DynProgScore, DynProgStrings )
):

EstimateLogEvalue_Description := Description(
  function(EstimateLogEvalue),
  Summary('estimate Evalue of a local alignment'),
  CallingSequence( noeval(EstimateLogEvalue(al)), 
    noeval(EstimateLogEvalue(al,len2)), 
    noeval(EstimateLogEvalue(al,len1,len2)), 
    noeval(EstimateLogEvalue(score,pam,len1,len2)) ),
  Parameters(
    [al,Alignment,'Pairwise alignment'],
    [score,numeric,'Score of the alignment'],
    [pam,numeric,'used pam distance for alignment'], 
    [len1,positive,'Length of sequence 1'],
    [len2,positive,'Length of sequence 2']),
  Returns(numeric),
  Synopsis('EstimateLogEvalue computes the logarithm of the Evalue 
of a local alignment according to the formula
Evalue = K*m*n*exp(-lambda*score), where m and n are the sequence lengths
and K and lambda parameters which have been fitted for all Dayhoff 
matrices.'),
Paragraph(-2,'Often, one is interested in the Evalue of the two complete 
sequences or even an entire database. To allow for that, the two sequence lengths 
can be overloaded by passing an extra one or two sequence lengths as additional 
arguments.'),
Paragraph(-2,'Instead of passing an Alignment, it is also possible to 
pass an alignment score, the pam distance, and the two sequence lengths
to the function.'),
  References( 'The statistics of sequence similarity scores, 
http://www.ncbi.nlm.nih.gov/blast/tutorial/Altschul-1.html',
'Altschul, S.F. & Gish, W. (1996) "Local alignment statistics." Meth. Enzymol. 266:460-480'),
  Examples(
    's1 := Rand(Protein(200)):',
    's2 := Mutate(s1,60,ZipfGaps):',
    'a := Align(s1,s2,DMS):',
    'exp(EstimateLogEvalue(a))', 
    'exp(EstimateLogEvalue(a,1000000))',
    'EstimateLogEvalue(500,20,300,500)'),
  SeeAlso( EstimatePam, CalculateScore, Align, Alignment, DynProgScore, 
  DynProgStrings )
):


MAlignment_Description := Description(
  structure( MAlignment ),
  Summary( 'a protein or DNA multiple sequence alignment' ),
  CallingSequence( noeval( MAlignment(InputSeqs, AlignedSeqs, labels,
	method, PrintOrder, Score, UpperBound, tree, AllAll) )),
  Parameters(
	[ InputSeqs, list(string), 'input sequences (before alignment)' ],
	[ AlignedSeqs, list(string), 'aligned sequences (in input order)' ],
	[ labels, list(string), 'labels for the sequences (in input order)' ],
	[ method, string, 'method(s) that generated the MSA' ],
	[ PrintOrder, list(integer), 'order used for printing and scoring' ],
	[ Score, numeric, 'score of the MSA (circular tour)' ],
	[ UpperBound, numeric, 'upper bound score (circular tour)' ],
	[ tree, Tree, 'tree used by the probabilistic method' ],
	[ AllAll, matrix, 'all against all Alignment matrix' ] ),
  Synopsis('An MAlignment stores the information of a multiple
sequence alignment.
The sequences may contain proteins or DNA.
The Score and UpperBound (on the score) are calculated using the
circular tour method.
In order to force recalculation of the score, use the selector RecalcScore.
A MAlignment is normally created by calling MAlign.' ),
  SeeAlso( MAlign, Align, Alignment )
):

append_Description := Description( function(append),
  Summary( 'append to a list, set or structure' ),
  CallingSequence( noeval(append(L, e_1..e_k)) ),
  Parameters( ['L', 'a list, set or structure'],
	      ['e_i', 'an arbitrary element'] ),
  Returns( {list,set,structure} ),
  Synopsis( 'This function appends e_1..e_k to the list or structure L.
If the original list or set or structure has length less than 10,
it appends on a new copy of L.
Otherwise it appends it to L and hence (likely) modifies the original object.
So if the first argument of append should not be destroyed, the appending
should be done on a copy of L.
Appending is written in a way that is efficient, even in case of
appending thousands of elements, one at a time, to an empty list.
Appending to sets, although efficient from the data enlargement point
of view, is not efficient as every new set is reordered.
If a large set is to be built by appending one element at a time,
it is much more efficient to use a list and convert the list to a set
once the appending is finished.
This function accepts a variable number of additional arguments.' ),
  Examples( 'append( ABC(1,2,3), 4, 5 )', 'append( CreateArray(1..11,7), 77 )')
  ):

arcsin_Description := Description( function(arcsin),
  Summary( 'the inverse trigonometric function' ),
  CallingSequence( noeval(arcsin(x)) ),
  Parameters( ['x', numeric, 'a numerical value, |x| <= 1'] ),
  Returns(numeric),
  Synopsis( 'This function computes the inverse of the
trigonometric sine function.  For all -1 <= x <= 1, sin(arcsin(x))=x.
For all -Pi/2 <= y <= Pi/2, arcsin(sin(y))=y.  The value returned
by arcsin is a principal value, it is between (-Pi/2 and Pi/2).' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 4.4' ),
  Examples( 'arcsin(0)', 'arcsin(1/2)', 'arcsin(1)', 'arcsin(-1)' ),
  SeeAlso( sin, cos, tan, arctan )
  ):

arctan_Description := Description( function(arctan),
  Summary( 'the inverse trigonometric function' ),
  CallingSequence( noeval(arctan(y)), noeval(arctan(y,x)) ),
  Parameters( ['y', numeric, 'a numerical value'],
	      ['x', numeric, 'an optional numerical value'] ),
  Returns(numeric),
  Synopsis( 'This function, with a single argument,
computes the inverse tangent function
defined by: tan(arctan(y)) = y.  The value returned by arctan is
between -Pi/2 <= arctan(y) <= Pi/2.
With two arguments, it computes the inverse tangent function
defined by: tan(arctan(y,x)) = y/x when x <> 0.  The value returned
by arctan with two arguments is between -Pi < arctan(y,x) <= Pi.
Arctan with two arguments computes the
principal value of the argument of the complex number x+I*y' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 4.4' ),
  Examples( 'arctan(0)', 'arctan(1)', 'arctan(1,0)', 'arctan(-1,0)',
	    'arctan(1,1)', 'arctan(-1,-1)' ),
  SeeAlso( tan, cos, sin, arcsin )
):

AsciiToInt_Description := Description( function(AsciiToInt), 
  Summary( 'convert a single character to its ascii ordinal number'),
  CallingSequence( noeval(AsciiToInt(s)) ), 
  Parameters( ['s', string, 'a string of length 1']),
  Returns(posint),
  Synopsis('Converts a single character into its ascii ordinal number.
This is useful when encoding/decoding symbols for dynamic programming.
It is also useful in general for the analysis of raw input.'),
  Examples( 'AsciiToInt(''a'')', 'AsciiToInt('' '')' ),
  SeeAlso( AsciiToInt, IntToAscii, op(SeeAlso_SearchString),
AToInt, IntToA )
):

IntToAscii_Description := Description( function(IntToAscii), 
  Summary( 'convert an integer to its ascii ordinal character'),
  CallingSequence( noeval(IntToAscii(i)) ), 
  Parameters( ['i', posint, 'an integer between 1 and 255']),
  Returns(string),
  Synopsis('Converts an integer between 1 and 255 to its ascii ordinal
character.
The null character (octal 000) cannot be represented.
This function allows an easy way to generate non-printable characters,
or special (accentuated) characters.
This is useful when encoding/decoding symbols for dynamic programming.
It is also useful in general for the analysis of raw input.'),
  Examples( 'IntToAscii(97)', 'IntToAscii(126)' ),
  SeeAlso( AsciiToInt, IntToAscii, op(SeeAlso_SearchString),
AToInt, IntToA )
):


assemble_Description := Description( function(assemble),
  Summary( 'creates an internal structure' ),
  CallingSequence( noeval(assemble(s)) ),
  Parameters( ['s', structure, 'a structure of valid types']),
  Returns([anything, 'an arbitrary Darwin structure']),
  Synopsis('Assemble and disassemble are a pair of functions
which allow the handling of procedures and expressions in Darwin.
Disassemble transforms an internal structure into a Darwin
data structure, where the names of the classes are the type
names of the components.
Assemble does exactly the reverse.
The existence of this pair of functions is to be able to inspect,
modify and create new bodies of procedures.
Although they both work for any structure, common structures
can be manipulated directly.
It is the body of procedures which cannot be manipulated directly
without dis/assemble.' ),
  Examples( 'assemble(power(a,2))', 'assemble(list(expseq(1,2)))'),
  SeeAlso(length, size, [disassemble, 'the reverse operation'],
	  [type, 'with a single argument'])):


disassemble_Description := Description( function(disassemble),
  Summary( 'produces a data structure from an internal structure' ),
  CallingSequence( noeval(disassemble(s)) ),
  Parameters( ['s', anything, 'any valid Darwin expression']),
  Returns(structure),
  Synopsis('Assemble and disassemble are a pair of functions
which allow the handling of procedures and expressions in Darwin.
Disassemble transforms an internal structure into a Darwin
data structure, where the names of the classes are the type
names of the components.
Assemble does exactly the reverse.
The existence of this pair of functions is to be able to inspect,
modify and create new bodies of procedures.
Although they both work for any structure, common structures
can be manipulated directly.
It is the body of procedures which cannot be manipulated directly
without dis/assemble.' ),
  Examples( 'disassemble(x -> sin(x))', 'disassemble([1,{2,3}])'),
  SeeAlso(length, size, [assemble, 'the reverse operation'],
	  [type, 'with a single argument'])):

assigned_Description := Description( function(assigned), 
  Summary( 'check if a name is assigned' ),
  CallingSequence(noeval(assigned(a)) ),
  Parameters( ['a', 'name'] ),
  Returns( boolean ),
  Synopsis( 'This function tests whether name a has been assigned
a value or symbol.
It should not be used for tables, as the table is not a name and
unassigned entries evaluate to the default value.  For tables,
testing should be done against the default value.' ),
   Examples( 'a:=5',  'assigned(a)', 'b:=c', 'assigned(b)', Unassign('a','b'))
 ):

# added as replacement of BinaryNewick2Darwin by AA. Jan 9, 2009
ParseNewickTree_Description := Description( 
  function(ParseNewickTree),
  Summary('Converts a tree from newick to darwin format'),
  CallingSequence( noeval(ParseNewickTree(t)), 
                   noeval(ParseNewickTree(t,modif)) ),
  Parameters( ['t',string,'tree in newick format'],
              ['modif',symbol=procedure,'(optional) modifier procedures '
                                        .'for label parsing'] ),
  Returns( Tree ),
  Synopsis( 'The function converts a tree from Newick (and also New Hampshire 
eXtended) format to a Darwin tree. Multifurcated nodes will be resolved to
a binary representation with in-between-branches of length 0.'), 
'',
Paragraph( -2, 'Possible modifier for label parsing:' ),
Paragraph( -10, '  ''InternalLabels''=procedure        A function 
string->anything that is called with any label assigned to an internal node. 
The return value is stored in the ''xtra'' field of the node. The default 
handler return NULL for empty labels (such that no ''xtra'' field is created),
the content of the ''NHX''-Tag (see References) or else the label itself.' ),
Paragraph( -10, '  ''LeafLabels''=procedure            A function 
string->anything that is called with ''NHX''-Tags assigned to leaves of 
the tree. The return value is stored in the 3rd field of the Leaf data 
structure. The default handler returns the content of those tags.'),
Paragraph( -10, '  ''defaultBranchLength''=nonnegative If only the topology
of the tree is given, one can set a default length. N-ary inner nodes
will can be preserved that way, as they get all the same height assigned.'),
  References( 'Newick format according to Olson Grammar:
http://evolution.genetics.washington.edu/phylip/newicktree.html',
'Description of New Hampshire extension (vers 2.0):
http://www.phylosoft.org/forester/NHX.html'),
  Examples('t := ''(((A:0.2,B:0.3):0.3,(C:0.5,D:0.3):0.2):0.3,E:0.7):0.0;''',
            'ParseNewickTree(t)', Unassign('t') ),
  SeeAlso( Tree, Leaf, PhylogeneticTree, LeastSquaresTree )
):

ceil_Description := Description( function(ceil),
  CallingSequence( noeval(ceil(x)) ),
  Parameters( ['x', numeric] ),
  Returns(integer),
  Synopsis('ceil returns the smallest integer larger or equal to x.
ceil(x) = -floor(-x) for all values of x.' ),
  Examples( 'ceil(-2)', 'ceil(-1.99999)', 'ceil(2.000001)' ),
  SeeAlso( floor, iquo, mod, round, trunc ) ):

coeff_Description := Description( function(coeff),
  CallingSequence( noeval(coeff(s,v)) ),
  Parameters( ['s', 'an arithmetic expression'],
	['v','a symbol name'] ),
  Returns([algebraic, 'the coefficient multiplying v in s']),
  Synopsis('Coeff computes the linear coefficient in the variable v
contained in the algebraic expression s.  The algebraic expression s
may be any mathematical expression which is not yet evaluated
 (in symbolic form, see noeval).' ),
  Examples( 't1 := noeval(3*a+b*c)',
	'coeff(t1,a)', 'coeff(t1,c)', Unassign('t1') ),
  SeeAlso_symbolic ):

cos_Description := Description( function(cos),
  Summary ('the trigonometric function'),
  CallingSequence( noeval(cos(x)) ),
  Parameters( ['x', numeric, 'a number'] ),
  Returns(numeric),
  Synopsis( 'This function computes the trigonometric cosine function.
cos(x) has simple zeros at at x=Pi/2+n*Pi.' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 4.3' ),
  Examples( 'cos(0)', 'cos(Pi/4)', 'cos(Pi/2)', 'cos(-Pi)' ),
  SeeAlso( sin, tan, arcsin, arctan )
  ):

debug_Description := Description( function(debug),
  CallingSequence( noeval(debug()), noeval(debug(arg)) ),
  Parameters( ['arg', 'an optional symbol or string'] ),
  Returns(NULL),
  Synopsis( 'This function starts or stops the Darwin interactive debugger.
The argument is optional.  Without an argument,
a call to debug() will start the interactive debugger.  A call such as
debug(false) will stop the debugger.  If the argument is a string,
this will be understood as a device which should be used to get the
user''s input (instead of stdin).
E.g. if stdin is used for other purposes, then debug( ''/dev/tty'' )
will force the debugger to use /dev/tty for user input.
At each interaction, the user can enter commands to
inspect, alter variables and continue the debugging process.
'),
'',
Paragraph('The interactive debugger is called whenever:',2),
Paragraph('an assignment statement has been executed',4),
Paragraph('an expression statement has been executed',4),
Paragraph('an if boolean expression has been evaluated',4),
'',

Paragraph('The interactive debugger is activated by:',2),
Paragraph('a Darwin level call by the function debug() or debug(true)',4),
Paragraph('an interrupt (<ctl-c>)',4),
Paragraph('an error (when the option -de is used)',4),
'',

Indent( 2, Paragraph( -2, 'The interactive debugger polls the user
and takes the following actions depending on the input (when the
debugger is expecting input, it will prompt the user with a ">>")')),
'',
Table( center, gutter=5, ColAlign('l','l'), Row('command','action'), Rule,
Row('<cr>, "l", <right-arrow>', 'continue, as currently set'),
Row('"u", "k", <up-arrow>', 'set up to debug only at a higher level'),
Row('"d", "j", <down-arrow>', 'set up to debug everything'),
Row('"?", "h"', 'short help'),
Row('"o"', 'quit the debugger, continue the computation'),
Row('"p"', 'print the current line'),
Row('"q"', 'quit darwin'),
Row('"t"', 'quit the debugger and computation and go to the top'),
Row('"w"', 'print the current stack and lines'),
Row('Set(debug):', 'start kernel debugging'),
Row('xxx;, xxx:', 'execute xxx as a darwin statement')),

Indent( 2, Paragraph( -2, 'Inspecting a variable may be achieved by
executing a statement with just the variable.  Similarly, any
expression can be computed/inspected.  Changing a variable can be
done with an assignment statement.' )),

  SeeAlso( Set, profiling, 'printlevel' )
  ):



Set_Description := Description(
	function( Set ),
	Summary('Set system options and defaults'),
	CallingSequence( noeval( Set( 'opt' )) ),
	Parameters(
		['opt', '{string, string=anything}'] ),
	Returns( [anything,'previous value of the system variable'] ),
	Synopsis('The Set command is used to assign to system variables.' ),
	Table( gutter=3, width=60, ColAlign('l', 'l', 'l'),
Row( 'Name', 'Type', 'Description' ), Rule, 
Row( 'BytesAlloc',   'posint',   'Returns the number of allocated bytes'),
Row( 'echo', 'posint',            'Sets the level of input/output information displayed.'),
Row( '', '',        '0 - no echo under any circumstance'),
Row( '', '',        '1 - (default) echo whenever the input or the output'),
Row( '', '',        '    are not from/to the terminal, but do not echo as a'),
Row( '', '',        '    result of a read statement.'),
Row( '', '',        '2 - echo whenever the input or the output are not'),
Row( '', '',        '    from/to the terminal.'),
Row( '', '',        '3 - echo only as a result of read statements'),
Row( '', '',        '4 - echo everything.'),
Row( '', '',        'n - (n > 4): echo only as a result of read statements'),
Row( '', '',        '    nested less than n-4 '),
Row( '', '',        'The echo option is superseded by quiet, i.e.'),
Row( '', '',        ' if quiet=true, no echo will occur.'),
Row( 'gc', 'integer',             'Sets the frequency (in words allocated) for garbage '),
Row( '', '',                      'collection.'),
Row( 'mapsize',      'integer',   'Sets the minimum size (in chars) required for Darwin '),
Row( '','',                       'to build a  .map file for a database.'),
Row( 'plotdevice',   'string',    'Sets the protocol for subsequent Draw commands.'),
Row( '','',                       '(options: portrait (8.5x11 with 1/2'' margin)'),
Row( '','',                       ' landscape (11x8.5 with 1/2'' margin)'),
Row( '','',                       ' portraitA4 (210x297 with 1/2'' margin)'),
Row( '','',                       ' landscapeA4 (297x210 with 1/2'' margin)'),
Row( 'plotoutput',   'filename',  'Name of the file to store the plotted code.'),
Row( 'printgc',      'boolean',   'Toggles displaying garbage collection information.'),
Row( 'printlevel',   'integer',   'Sets the amount of information which is printed out'),
Row( '', '',                      'during execution.' ),
Row( 'profile',      'boolean',  'Toggles printer/plotter profile mode'),
Row( 'prompt',       'string',   'Sets the Darwin prompt.'),
Row( 'quiet',        'boolean',  'Toggles the suppression of output.'),
Row( 'screenwidth',  'posint',   'Sets the width of a line for all subsequent output.'),
Row( 'server',       'boolean',  'Places Darwin in server mode.'),
Row( 'TotalDPCells', 'posint',   'Return/sets the number of cell computed for DynProgr'),
NULL),
	Keywords(echo,mapsize,plotdevice,plotoutput,printgc,profile,prompt,
	quiet,server,screenwidth,TotalDPCells),
	Examples( 'Set(printgc)', 'Set(plotdevice=landscape)')
):

ServerSocket_Description := Description(
  function(ServerSocket),
  Summary( 'Listen from unix domain socket, fork to process requests'),
  CallingSequence( noeval( ServerSocket(socket_path) )),
  Parameters( 
['socket_path', string, 'path where server socket is created and listen from'],
['gc', posint, '(optional) gc frequency of child process']
  ),
  Returns( string ),
  Synopsis( 'ServerSocket is a function which creates a unix domain
socket and starts listening on it. Each line sent to the socket will
fork the darwin process. The child process will get the received string
as the return value of the function and everything sent to standard out
will be sent back through the socket to the client program. The parent 
process will wait forever and has to be killed externally. Note that 
garbage collection will require a lot of data to be copied. Hence, gc 
frequency will by default be assigned a very high value and childreen
processes should not run too long.'),
  Examples( 
Fake('req := ServerSocket(''/tmp/server_square'')', 'req := 5'),
Fake('print(req ^ 2)',' <all output sent to file> '),
Fake('quit','')),
  SeeAlso( gc, Set, OpenPipe, CallSystem, OpenReading, TimedCallSystem, LockFile )
):

EnterProfile_Description := Description( 
  function(EnterProfile),
  CallingSequence( noeval( EnterProfile( blockname ) )),
  Parameters( ['blockname', string] ),
  Returns( NULL ),
  Synopsis( 'This function is used to identify the beginning of a block
to be profiled.  An EnterProfile should always be matched to an ExitProfile
which should be at the same level (in the same statement sequence) and should
have the same blockname.  The code surrounded by the EnterProfile and
ExitProfile will be profiled under the name given by blockname.
Many pairs of Enter/ExitProfile may be used, with or without the same
blockname.  Run time statistics will be grouped by blockname.
Enter/ExitProfile pairs cannot be nested within the same statement
sequence.'),
  Examples( 'EnterProfile(longloop)',
	's:=0:  for i to 10^5 do s := s+1/i od;',
	'ExitProfile(longloop)', Unassign('i','s') ),
  SeeAlso( ExitProfile, profiling )
):

enum_Description := Description( 
  function(enum),
  Summary( 'list of consecutive integers'),
  CallingSequence( noeval( enum(n) ), noeval( enum(r) ) ),
  Parameters( ['n', integer], ['r', range] ),
  Returns( list ),
  Synopsis( 'This function returns a list of numbers from 1 to n
or from range r=r_1..r_2.' ),
  Examples( 'enum(5)', 'enum(4..10)' ),
  SeeAlso( seq, zip )
):

error_Description := Description(
  function( error ),
  Summary( 'terminate execution and issue an error message'),
  CallingSequence( noeval(error('msg,...')) ),
  Parameters( ['msg', anything, 'usually an error message'],
	['...',anything,'additional arguments to clarify the error'] ),
  Returns( NULL ),
  Synopsis( 'This function returns to the top level of execution
and issues the error message msg.
If an error happens while executing a traperror() function, then
the flow will not return to the top level, instead the
traperror function will return with the value of the argument(s) of
error().
When this happens, the global
variable "lasterror" is set to the value of the error, else it is
unassigned.
Using error/traperror allows for a simple throw-catch mechanism.'),
  Examples(
    'f := proc(x) if x=0 then error(''oops, div by 0'') fi; 5/x end',
    Fake('f(0)','Error, (in f) oops, div by 0'),
    'traperror(f(0))',
    'lasterror', Unassign('f')),
  SeeAlso( traperror, 'lasterror', assert, warning )
):

eval_Description := Description( 
  function( eval ),
  CallingSequence( noeval(eval(exp)) ),
  Parameters( ['exp', 'expression'] ),
  Returns( anything ),
  Synopsis( 
'This function forces the immediate and complete evaluation of exp.' ),
  Examples( 'eval(5+5)', 'eval(parse(''2+3!''))' ),
  SeeAlso( noeval )
):

evalb_Description := Description( 
  function(evalb),
  CallingSequence( noeval(evalb(exp)) ),
  Parameters( ['exp', expression] ),
  Returns( boolean ),
  Synopsis( 'This function forces an immediate evaluation of the boolean
expression exp.' ),
  Examples( 'evalb(5=5)', 'evalb(true = (not(not(not false))))' ),
  SeeAlso( eval )
):

ExitProfile_Description := Description( 
  function(ExitProfile),
  CallingSequence( noeval( ExitProfile( blockname ) )),
  Parameters( ['blockname', string] ),
  Returns( NULL ),
  Synopsis( 'This function is used to identify the ending of a block
to be profiled.  An ExitProfile should always be
matched to a previous EnterProfile which should be
at the same level (in the same statement sequence) and should
have the same blockname.  The code surrounded by the EnterProfile and
ExitProfile will be profiled under the name given by blockname.
Many pairs of Enter/ExitProfile may be used, with or without the same
blockname.  Run time statistics will be grouped by blockname.
Enter/ExitProfile pairs cannot be nested within the same statement
sequence.'),
  Examples( 'EnterProfile(longloop)',
	's:=0:  for i to 10^5 do s := s+1/i od',
	'ExitProfile(longloop)', Unassign('i','s') ),
  SeeAlso( EnterProfile, profiling )
):

exp_Description := Description( function(exp),
  Summary('exponential function'),
  CallingSequence( noeval(exp(x)), noeval(exp(A)) ),
  Parameters( ['x', 'a numerical value'],
	[A,'a square numerical matrix'] ),
  Returns(numeric,matrix(numeric)),
  Synopsis( 'This function computes the exponential e^x
(e = 2.71828...) if the parameter is a single numerical value.
Otherwise, it computes e^A = I + A + A^2/2 + A^3/6 + ...
or the exponential of a square matrix.  For all numerical
values of x, ln(exp(x))=x.' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 4.2' ),
  Examples( 'exp(0)', 'exp(5)', 'exp([[1, 2], [3, 4]])' ),
  SeeAlso( expx1, ln, log, lg, ln1x, log10 )
  ):

expx1_Description := Description( function(expx1),
  Summary( 'compute exp(x)-1 accurately for small x' ),
  CallingSequence( noeval(expx1(x)) ),
  Parameters( ['x', 'a numerical value'] ),
  Returns(numeric),
  Synopsis( 'This function computes the exponential e^x-1 (e = 2.71828...).
This function is intended for very small values of x when exp(x) is
too close to 1, and hence significant precision is lost.
For all numerical values of x, ln1x(expx1(x))=x.' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 4.2' ),
  Examples( 'expx1(0)', 'expx1(5e-20)', 'expx1(ln1x(7e-30))' ),
  SeeAlso( exp, ln, log, lg, ln1x, log10 )
  ):

factorial_Description := Description( function(factorial),
  CallingSequence( noeval(factorial(n)) ),
  Parameters( ['n', 'an integer or numerical value'] ),
  Returns(numeric),
  Synopsis('factorial returns the product of 1*2*3*...*n for integer
values of n.  For non-integer values it returns Gamma(n+1), the
complex-plane extension of factorial.' ),
  Paragraph( 'Gamma(z+1) = z*Gamma(z).', 4 ),
  Paragraph( -2, 'For non-integer values it is also possible to define
factorial for negative arguments.  This function can be invoked with
the standard postfix notation, that is n! or in functional form,
factorial(n).' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 6.1' ),
  Examples( '0!', '6!', 'factorial(-1.5)' ),
  SeeAlso( Gamma, LnGamma ) ):

floor_Description := Description( function(floor),
  CallingSequence( noeval(floor(x)) ),
  Parameters( ['x', 'a numerical value'] ),
  Returns(integer),
  Synopsis('floor returns the largest integer less than or equal to x.
floor(x) = -ceil(-x) for all values of x.' ),
  Examples( 'floor(-2)', 'floor(-1.99999)', 'floor(2.000001)' ),
  SeeAlso( ceil, iquo, mod, round, trunc ) ):

Gamma_Description := Description( function(Gamma),
  Summary( 'the Gamma and Incomplete Gamma functions' ),
  CallingSequence( noeval(Gamma(a)), noeval(Gamma(a,x)) ),
  Parameters( ['a', numeric, 'a numerical value'],
    [x,numeric,'a nonnegative argument for the Incomplete Gamma function'] ),
  Returns(numeric),
  Synopsis( 'For a positive integer a, Gamma(a) returns the
product of 1*2*3*...*(a-1) = (a-1)!.
Gamma satisfies the functional equation:' ),
  Paragraph( 'Gamma(a+1) = a*Gamma(a)', 4 ),
  Paragraph( -2, 'Gamma can be defined as a definite integral:' ),
  Indent(4,MapleFormula( 'Gamma(a) = int( t^(a-1)*exp(-t), t=0..infinity )')),
  Paragraph( -2, 'For non-integer values it is also possible to define
Gamma for negative arguments.  When Gamma is used with two arguments,
it is understood to be the Incomplete Gamma function, defined by
the integral:' ),
  Indent(4,MapleFormula( 'Gamma(a,x) = int( t^(a-1)*exp(-t), t=x..infinity)')),
  Paragraph( -2, '  In this case, a must be positive.' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 6.1, 6.5.3' ),
  Examples( 'Gamma(7)', 'Gamma(100)', 'Gamma(-1.5)', 'Gamma(3,2)' ),
  SeeAlso( factorial, LnGamma, Lngamma ) ):

gcd_Description := Description( function(gcd),
  Summary('greatest common divisor'),
  CallingSequence( noeval(gcd(a1..ak)) ),
  Parameters( ['ai', 'an integer value'] ),
  Returns(integer),
  Synopsis('Gcd computes the greatest common divisor of all the arguments
given.  That is a number that exactly divides each one of the arguments.
Gcd takes a variable number of arguments, but all of them must be integers.' ),
  Examples( 'gcd(91,21)', 'gcd(999999,142857)', 'gcd()', 'gcd(20,25,-30,-40)'),
  SeeAlso( iquo, mod ) ):



matrix_inverse_Description := Description(
  function(matrix_inverse ),
  Summary( 'invert a square matrix' ),
  CallingSequence(noeval(matrix_inverse(A)) ),
  Parameters([A,matrix,'a matrix for which the inverse is wanted'] ),
  Returns(matrix ),
  Synopsis('Compute the inverse of a square matrix.
If A is a square matrix the same effect is obtained by computing A^(-1).
To resolve a system of linear equations, GaussElim(A,b) is more
efficient than A^(-1) * b.' ),
  Examples( 'A := [[3,1,2],[1,2,-1],[2,-1,5]]', 'A^(-1)', Unassign('A') ),
  SeeAlsoLinAlg
):



convolve_Description := Description(
  function( convolve ),
  Summary( 'convolution of two or more vectors' ),
  CallingSequence( noeval(convolve(v1,v2,'...')) ),
  Parameters([v_i,list(numeric),'a numerical vector of arbitrary dimension']),
  Returns( list(numeric) ),
  Synopsis( 'Compute the convolution of two or more numerical
vectors.
The convolution of two vectors v1 and v2 of dimensions d1 and d2 is
the vector r with dimension d1+d2-1 with elements
r[k] = sum( v1[i] * v2[k+i-i], i=1..k-1 ) (references outside v1 or
v2 are considered 0).
The convolution of more than two vectors is computed in an optimal
order.
Convolution is associative and commutative, so order of the operation
does not matter.' ),
  Examples( 'v1:=[1,2,3,4]', 'v2:=[1,1/2,1/3]', 'convolve(v1,v2)',
 	Unassign('v1','v2') ),
  SeeAlsoLinAlg
):



Identity_Description := Description(
  function( Identity ),
  Summary( 'create an identity matrix' ),
  CallingSequence( noeval(Identity(n)) ),
  Parameters([n,posint,'dimension of the matrix']),
  Returns( matrix(integer) ),
  Synopsis( 'Creates a new identity matrix of dimension n x n.' ),
  Examples( 'Identity(3)' ),
  SeeAlsoLinAlg
):

Cholesky_Description := Description(
  function(Cholesky ),
  Summary( 'decomposition of a positive definite matrix A = R * R^t'),
  CallingSequence(noeval(Cholesky(A)) ),
  Parameters([A,matrix(numeric),'a matrix '] ),
  Returns(matrix),
  Synopsis('R := Cholesky(A) computes the Cholesky decomposition of the
matrix A.
A is the input matrix, and must be a square, symmetric, positive
definite matrix.
If A does not satisfy these conditions, an error is returned.
R is a square matrix, lower triangular, such that R*transpose(R) = A.
Cholesky is used to check for positive-definiteness, and at the same time
it allows to solve a system Ax=b (by doing two back-substitutions) if it
is positive-definite.' ),
  Examples( 'A := [[3,1,2],[1,2,-1],[2,-1,5]]',
	'R := Cholesky(A)', 'R * R^t', Unassign('A','R') ),
  SeeAlsoLinAlg
);

GivensElim_Description := Description( function(GivensElim),
  CallingSequence( noeval(GivensElim(A)) ),
  Parameters( [A, 'an  m x n  numerical matrix'] ),
  Returns([ [matrix,matrix], '[Q,R]']),
  Synopsis( 'GivensElim factors an m x n matrix A into two factors,
A = Q*R.  This decomposition is done with individual Givens''
rotations.  The decomposition is commonly called the QR-decomposition.
Q is an m x m square orthonormal matrix, that is Q*Q^t = I.  R is an
m x n upper triangular matrix.  If the matrix is found to be
singular, then R will have zeros in the diagonal and the
decomposition is still correctly done.' ),
  References( 'Computermathematik, Walter Gander, Birkhauser, Ch 5.3' ),
  Examples( 'GivensElim( [[1,2], [-2,3]] )' ),
  SeeAlsoLinAlg
):

GramSchmidt_Description := Description( function(GramSchmidt),
  CallingSequence( noeval(GramSchmidt(A)) ),
  Parameters( [A, 'a list of linearly independent vectors (a matrix)'] ),
  Returns(matrix(numeric)),
  Synopsis( 'The GramSchmidt function computes an orthonormal basis
spanning the same subspace as the vectors in A.  The input matrix A is
interpreted as a list of vectors.  The vectors have to be all of the
same dimension and linearly independent.  The result is a list of
orthonormal vectors, with the same dimension as A.  If the dimension of
A is m x n, then m <= n.  This is often called the Gram-Schmidt
orthonormalization process.' ),
  Examples( 'GramSchmidt( [[1,2],[1,-1]] )',
	    'GramSchmidt( [[0,1,-1],[1,-1,3]] )' ),
  SeeAlsoLinAlg
  ):

If_Description := Description(
  function(If),
  CallingSequence(noeval(If(cond,exptrue, expfalse))),
  Parameters( ['cond', 'boolean expression'], ['exptrue', 'expression'],
    ['expfalse', 'expression'] ),
  Returns( {'type(exptrue)', 'type(expfalse)'} ),
  Synopsis( 'The  If construct provides a short hand version of the
if-then-fi construct.  Every If can be re-written as follows:' ),
  Paragraph( '    > if cond then exptrue else expfalse fi;', -2 ),
  Paragraph( '  Note that the If function returns the result of
exptrue or expfalse.', -2 ),
  Examples( 'x:=5', 'If(mod(x,2)=0, x/2, (x-1)/2)' )
):

ilogb_Description := Description( function(ilogb),
  CallingSequence( noeval(ilogb(x)) ),
  Parameters( ['x', 'a numerical value'] ),
  Returns(integer),
  Synopsis('ilogb returns the exponent of the floating point representation
of x.  This function is defined in the IEEE 754 floating point standard.
It is the floor of the logarithm base 2 of |x|, for |x| >= 1, computed
directly from the representation (very fast).
For non-zero arguments, and for IEEE base 2 floating point numbers,
1 <= |x| / 2^ilogb(x) < 2.' ),
  Examples( 'ilogb(2)', 'ilogb(1.0e-307)', 'ilogb(0)', 'ilogb(Pi)' ),
  SeeAlso( scalb, lg ) ):

SeeAlso_Graph := SeeAlso( Edge,Edges,Graph,InduceGraph,Graph_Rand,
	Nodes,ShortestPath, VertexCover,Clique,EdgeComplement,
	BipartiteGraph, RegularGraph,TetrahedronGraph, MaxCut, MinCut, 
	MaxEdgeWeightClique,FindConnectedComponents,DrawGraph,
	MST, Path, ParseDimacsGraph,Graph_XGMML,Graph_minus ):


TetrahedronGraph_Description := Description(
  function(TetrahedronGraph),
  Summary('generate graphs describing regular polyhedra'),
  CallingSequence( noeval(TetrahedronGraph()),
	noeval(HexahedronGraph()),
	noeval(OctahedronGraph()),
	noeval(IcosahedronGraph()),
	noeval(DodecahedronGraph()) ),
  Returns(Graph),
  Synopsis( 'Generate a graph which corresponds to a regular polyhedra.
That is, a graph whose vertices correspond to the vertices of a
regular polyhedra, and so its edges.' ),
  Examples( 'TetrahedronGraph()', 
        'HexahedronGraph()',
        'OctahedronGraph()',
        'IcosahedronGraph()',
        'DodecahedronGraph()' ),
  SeeAlso_Graph
):


RegularGraph_Description := Description(
  function(RegularGraph),
  Summary('generate a random regular graph'),
  CallingSequence( noeval(RegularGraph(n,e)) ),
  Parameters( [n,integer,'optional number of nodes/vertices'],
	[e,integer,'optional number of edges'] ),
  Returns(Graph),
  Synopsis( 'Generate a random graph where each of the n vertices has the same
degree e.  The product n*e must be even.'),
  Examples( 'RegularGraph(5,2)' ),
  SeeAlso_Graph
):


BipartiteGraph_Description := Description(
  function(BipartiteGraph),
  Summary('generate a random bipartite graph'),
  CallingSequence( noeval(BipartiteGraph(n1,n2,e)) ),
  Parameters( [n1,integer,'optional number of nodes/vertices in first set'],
	[n2,integer,'optional number of nodes/vertices in second set'],
	[e,integer,'optional number of edges'] ),
  Returns(Graph),
  Synopsis( 'Generate a random bipartite graph with n1 nodes in one set and
n2 nodes in another set and e edges connecting between the two.
If e is not specified, it is chosen at random.  If n1 and n2 are not
specified, they are chosen at random between 5 and 20.  A complete
bipartite graph can be generated by requesting it to have n1*n2 edges.
The edges are otherwise randomly chosen and have label 0.'),
  Examples( 'BipartiteGraph(3,4,5)' ),
  SeeAlso_Graph
):

Graph_Rand_Description := Description(
  function(Graph_Rand),
  Summary('generate a random graph'),
  CallingSequence( noeval(Rand(Graph)),
	noeval(Graph_Rand(n,m)) ),
  Parameters( [n,integer,'optional number of nodes/vertices'],
	[m,integer,'optional number of edges'] ),
  Returns(Graph),
  Synopsis( 'Generate a random undirected graph with n nodes and m edges.
If m is not specified, then the number of edges is <= n*ln(n).  If n is
not specified, a random value between 5 and 20 is chosen.
The Edges are all labelled with 0.'),
  Examples( 'Rand(Graph)', 'Graph_Rand(3,4)' ),
  SeeAlso_Graph
):

Graph_XGMML_Description := Description(
  function(Graph_XGMML),
  Summary('exports a graph in xgmml format'),
  CallingSequence( noeval(Graph_XGMML(G)) ),
  Parameters( 
    ['G',Graph,'graph to be exported'],
    ['modif',{string,symbol=anything},'optional modifiers (see below)'] ),
  Returns( string ),
  Synopsis( 'Exports the graph G in xgmml format (an xml format), which 
can be analyzed for example by cytoscape. A description of the format can
be found at "http://www.cs.rpi.edu/~puninj/XGMML/".'),
'',
Paragraph( -2, 'Modifer:' ),
Paragraph( -14, ' directed={boolean}    indicates, whether the graph is 
directed or not' ),
Paragraph( -14, ' title={string}        the title of the graph'),
Paragraph( -14, ' NodeLabel={procedure} a callback procedure to define a 
different label than stored in the Node'),
Paragraph( -14, ' EdgeLabel={procedure} a callback procedure to define a 
different label for the edge than stored in the Graph'),
Paragraph( -14, ' NodeAttribute={procedure} a callback procedure to  add 
attributes to an edge. The function expects a list of tables where at 
least ''name'' and ''value'' elements should be defined for each attribute'),
Paragraph( -14, ' EdgeAttribute={procedure} a callback procedure to add 
attributes to an edge. The function expects a list of tables where at 
least ''name'' and ''value'' elements should be defined for each attribute'),
  Examples('G:=Graph(Edges(Edge(1,A,B),Edge(2,B,C)),Nodes(A,B,C))',
   'print(Graph_XGMML(G))',Unassign('G') ),
  SeeAlso_Graph
):

FindConnectedComponents_Description := Description( 
  function(FindConnectedComponents),
  Summary('set of connected components of a Graph'),
  CallingSequence( noeval(FindConnectedComponents('G'))),
  Parameters( ['G', Graph, 'a given Graph']),
  Returns(set(Graph)),
  Synopsis( 'This function computes the set of connected components
of a Graph, which are returned as a set of Graphs.
The Graph is assumed to be undirected.
The disconnected nodes are returned as singleton Graphs, i.e. a Graph
with a single node.' ),
  Examples( 'G1 := Graph(Edges(Edge(''a'',1,2),Edge(''b'',2,3)), Nodes(1,2,3,4)):',
	'FindConnectedComponents(G1)'),
  SeeAlso_Graph
):

Graph_minus_Description := Description( 
  function(Graph_minus),
  CallingSequence( noeval(Graph_minus('G','V')),
	noeval(Graph_minus('G','E')),
	noeval(Graph_minus('G','G1')) ),
  Parameters( ['G', Graph, 'a given Graph'],
	['V', Nodes, 'Nodes to be removed'],
	['E', Edges, 'Edges to be removed'],
	['G1', Graph, 'Subgraph to be removed'] ),
  Returns(Graph),
  Synopsis( 'This function removes a set of either edges or vertices
from a graph and returns the updated graph.  Note that the deletion of
an edge does not remove the vertex end points of this edge.
The deletion of a vertex removes all incident edges.' ),
  Examples( 'G1 := Graph(Edges(Edge(''a'',1,2), Edge(''b'',2,3), Edge(''c'',3,4)), Nodes(1,2,3,4,5));',
	'Graph_minus(G1, Edges(Edge(''b'',2,3)));',
	'G1 minus Nodes(2,3)',
	'Graph_minus(Graph(Edges(), Nodes(1,2,3,4)), Nodes(1,2,3,4))' ),
  SeeAlso_Graph
):

InduceGraph_Description := Description(
  function(InduceGraph),
  CallingSequence( noeval(InduceGraph('G','V')),
      noeval(InduceGraph('G','E')) ),
  Parameters( ['G', Graph, 'a given Graph'],
      ['V', Nodes, 'Nodes inducing subgraph'],
      ['E', Edges, 'Edges inducing subgraph'] ),
  Returns( Graph ),

  Synopsis( 'This function computes a vertex- or edge-induced subgraph. A
vertex-induced subgraph is one that consists of some of the vertices of the
original graph and all of the edges that connect them in the original. An
edge-induced subgraph consists of some of the edges of the original graph and
the vertices that are at their endpoints.'),
  Examples( 'G := Graph( {{1,2},{2,3},{1,3},{2,4}},{1,2,3,4} )',
  'InduceGraph( G, Nodes(1,2,3) )',
  'InduceGraph( G, Edges( Edge(0,1,2),Edge(0,2,3)) )' ),
  SeeAlso_Graph
):


ParseDimacsGraph_Description := Description(
  function(ParseDimacsGraph),
  CallingSequence( noeval(ParseDimacsGraph(s)) ),
  Parameters(['s',string, 'graph in dimacs format']),
  Returns( Graph ),
  Synopsis( 'This function parses a graph in dimacs format
and returns a Darwin graph structure.'),
  Examples( 'ParseDimacsGraph(''p  edge 5 2\ne 2 4 9\ne 1 5 2\n'')'),
  SeeAlso_Graph
):


Inherit_Description := Description(
  function( Inherit ),
  Summary( 'Inherit all defined methods of the old into the new class'),
  CallingSequence( noeval(Inherit(newclass,oldclass)) ),
  Parameters( [newclass,symbol,'The new class being extended'],
	[oldclass,symbol,'The class donating the methods'] ),
  Returns( 'NULL' ),
  Synopsis( 'All methods defined for the oldclass which are not
defined in the newclass are converted to work with the newclass.
Any method which is not wanted to be inherited must be defined
before calling Inherit.  Alternatively, an unwanted method can
be removed by using noeval.
Multiple inheritance is obtained by invoking Inherit more than once.
Inherit benefits from the availability of newclass_Rand, if the
objects have some special property.  In general, it is a good
idea to define all the methods which are particular to newclass
before invoking Inherit.
Note: Since the newclass is not a subclass of the oldclass (but only
convertible) objects of type newclass are not of type oldclass
and a corresponding test with the function "type" results in
"false".' ),
Examples( Fake('Polar := proc( Rho:numeric, Theta:numeric ) ... end',''),
	'Polar_abs := proc( a:Polar ) a[Rho] end',
	'Inherit(Polar,Complex)'),
  SeeAlso( CompleteClass, objectorientation, Protect, ExtendClass )
):


ExtendClass_Description := Description( function(ExtendClass),
  Summary('Extend a class with additional fields'),
  CallingSequence( noeval( ExtendClass( newclass, oldclass, addarg1, '...' ))),
  Parameters(
	[newclass,symbol,'The new class, oldclass with more fields'],
	[oldclass,symbol,'The base class being extended'],
	[addarg1,[symbol,type,anything],'Description of additional arguments'] ),
  Returns( 'NULL' ),
  Synopsis( 'ExtendClass creates a new class which has all
the fields of the base class plus additionally defined ones.
The result is a new class which automatically inherits all
the methods of the oldclass and has additional fields
described in the 3 and onwards arguments of ExtendClass.
The description of each additional argument is a list of
three values, the name of the new field, its type and,
optionally, its default value.  The default value is used
when creating an object without it or when converting an
object from oldclass to newclass.  More precisely the following
functions are created:'), '',
Table( center, ColAlign( 'l', 'l', 'l'),
Row( 'Old method', 'New Method', 'Comment'), Rule,
Row( oldclass, newclass, 'Constructor based on the oldclass constructor'),
Row( oldclass_xxx, newclass_xxx, 'same rules as Inherit'),
Row( yyy_oldclass, yyy_newclass, 'conversions from other classes to newclass'),
Row( '',oldclass_newclass,'widening conversion'),
Row( '',newclass_oldclass,'narrowing conversion') ), '',
Paragraph(-2,'If some methods are not expected to be inherited
from oldclass, they should either be unevaluated after calling
ExtendClass or defined before calling ExtendClass.'),
Paragraph(-2,'ExtendClass does an implicit Inherit, so there is
no point in doing an Inherit(newclass,oldclass).  Any protection
defined for the oldclass is inherited in the newclass.  The newclass
can Inherit other additional classes as usual.'),
  Examples( 'ExtendClass( DistTree, Tree, [height,numeric,0] )' ),
  SeeAlso( Inherit, CompleteClass, Protect, objectorientation )
):


Protect_Description := Description( function(Protect),
  Summary('Protect fields from a class'),
  CallingSequence( noeval(Protect(classname,field1,'...')) ),
  Parameters( [classname,symbol,'a class name to be protected'],
	[field1,symbol,'a field name of classname'] ),
  Returns( 'NULL' ),
  Synopsis( 'Protect sets up the appropriate mechanism so that the
named fields of the class cannot be changed by any function other
than the methods already defined at the time that Protect is called.
If Protect is called without any field name, then all the fields of
the data structure which have not been protected yet, are protected.
Darwin does not support the concept of hiding at this point.
That is, prevent the user from reading a value from a field.
We do not see any advantages to hiding and we do see disadvantages to it.
The protection operates at two levels.
First, all indexing references are forbidden by
setting the option "NoIndexing" in the class.  Secondly, the
fields mentioned are given a special name, identical in appearance
to the defined one, but different from what a user can type.
All methods referring to the class will have these names fixed
appropriately.  Additional calls to Protect can be used to
Protect names not yet protected and hence create a hierarchy
of protected names and functions that can use them.' ),
  Examples( Fake( 'Protect( Polar, Rho, Theta)', '' ) ),
  SeeAlso( Inherit, CompleteClass, ExtendClass, objectorientation, 'option' )
):


indets_Description := Description( function(indets),
  Summary('return all subexpressions of a given type'),
  CallingSequence( noeval(indets(str,typ)) ),
  Parameters( ['str', anything, 'an arbitrary structure'],
        ['typ',type,'(optional) a type to be searched in str'] ),
  Returns(set(typ)),
  Synopsis('The function indets returns a set with all the
subexpressions in str which are of type typ.
If the type typ is omitted, it is assumed to be "symbol".' ),
  Examples( 'indets([1,-2,3.1,abc],posint)',
	'indets(A(1,[77],[[]]),list)',
	't := Tree(Tree(Leaf(A),5,Leaf(B)),0,Tree(Leaf(C),11,Leaf(D)))',
        'indets(t,Leaf)',
	'indets(t)', Unassign('t')),
  SeeAlso_symbolic ):




intersect_Description := Description( function(intersect),
  CallingSequence( 'a intersect b', noeval(intersect(a,b)) ),
  Parameters( ['a', set], ['b', set] ),
  Returns(set),
  Synopsis( 'Computes the intersection of two sets, that is a set
which has all the elements both in a and b.  The value intersect() is
understood to be the entire universe, and hence intersections including
intersect() will simply return the other argument.  In its functional form,
any arbitrary number of sets can be intersected.  In particular,
intersect(a) = a.' ),
  Examples( '{1,2,3} intersect {2,3,4}', '{1,2,3} intersect {}',
	'{1,2,3} intersect intersect()' ),
  SeeAlso( union, minus, member, subset )
  ):

iquo_Description := Description( function(iquo),
  CallingSequence( noeval(iquo(a,b)) ),
  Parameters( ['a', integer], ['b', integer] ),
  Returns(integer),
  Synopsis('iquo returns the integer quotient between a and b.
If b=0, a division by zero fault is generated.  The result is
truncated towards zero for both positive and negative results.
Formally, iquo(a,b) = trunc(a/b).' ),
  Examples( 'iquo(7,3)', 'iquo(-3,2)', 'iquo(121,11)' ),
  SeeAlso( ceil, floor, iquo, mod, round, trunc ) ):


iterate_Description := Description(
  function(iterate),
  Summary( 'make available one value for an iterator' ),
  CallingSequence( noeval(iterate(v)) ),
  Parameters( [v, anything, 'a value that will be used by a for-in loop'] ),
  Returns('NULL'),
  Synopsis( 'iterate is used inside an iterator function to
feed a value to the calling for-in loop.  The argument(s) of
iterate are evaluated, and the for loop variable is assigned
this value, and another iteration is performed.
The body of the for loop is executed by the call to iterate.' ),
  SeeAlso( objectorientation, Primes, iterator, Infix, Prefix, Postfix, Entries,
Sequences, Leaves, Lines )
):


lcoeff_Description := Description( function(lcoeff),
  Summary('leading coefficient'),
  CallingSequence( noeval(lcoeff(s)) ),
  Parameters( ['s', 'an arithmetic expression'] ),
  Returns([algebraic, 'the leading coefficient in s']),
  Synopsis('lcoeff computes the leading numerical coefficient
contained in the algebraic expression s.  The algebraic expression s
may be any mathematical expression which is not yet evaluated
 (in symbolic form, see noeval).  In case of a sum, the leading
coefficient is extracted from the first (positional) coefficient.' ),
  Examples( 't1 := noeval(3*a+b*c)', 'lcoeff(t1)', Unassign('t1') ),
  SeeAlso_symbolic ):



lg_Description := Description( function(lg),
  CallingSequence( noeval(lg(x)) ),
  Parameters( ['x', 'a positive number or a square matrix']),
  Returns({numeric,matrix(numeric)}),
  Synopsis('lg computes the logarithm base 2 or a number or a
square matrix.  For all arguments it is true that lg(2^x) = x.
For positive arguments or for matrices for which the logarithm
can be computed, it is always true that 2^lg(x) = x.'),
  Examples( 'lg(7.5)', 'lg(16)', 'lg( [[2,1],[0,3]])', '2^lg( [[2,1],[0,3]])' ),
  SeeAlso(ln,log,ln1x, log10,exp,ilogb) ):


ln_Description := Description( function(ln),
  CallingSequence( noeval(ln(x)), noeval(ln(A)) ),
  Parameters( ['x', 'a numerical value > 0'],
	[A,'a square numerical matrix'] ),
  Returns(numeric,matrix(numeric)),
  Synopsis( 'This function computes the logarithm base e
(e = 2.71828...) if the parameter is a single numerical value.
This is usually called the natural logarithm.
If the argument is a square matrix, it computes a square matrix B
with the same dimensions as A
such that e^B=A, or the natural logarithm of a square matrix.
Not all matrices have a logarithm (which is real-valued).
For all numerical values of x, ln(exp(x))=x.' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 4.1' ),
  Examples( 'ln(1)', 'ln(5)', 'ln([[2, 1], [3, 4]])' ),
  SeeAlso( exp, expx1, ilogb, log, lg, ln1x, log10 )
  ):

ln1x_Description := Description( function(ln1x),
  Summary( 'compute ln(1+x) accurately for small x' ),
  CallingSequence( noeval(ln1x(x)) ),
  Parameters( ['x', 'a numerical value > -1'] ),
  Returns(numeric),
  Synopsis( 'This function computes the logarithm base e
(e = 2.71828...) of 1+x.
This is necessary when the value of x is very small, and computing
1+x would produce a significant truncation.
A typical such computation is when 1 - (1-eps)^n has to be computed,
and eps is very small and n is very large.  
This can be done accurately with -expx1(n*ln1x(-eps)).'),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 4.1' ),
  Examples( 'ln1x(0.001)-ln(1.001)', 'ln1x(1e-60)' ),
  SeeAlso( exp, expx1, ilogb, log, lg, ln1x, log10 )
  ):


LnGamma_Description := Description( function(LnGamma),
  Summary( 'logarithm of the Gamma and Incomplete Gamma functions' ),
  CallingSequence( noeval(LnGamma(a)), noeval(LnGamma(a,x)) ),
  Parameters( ['a', numeric, 'a numerical value'],
    [x,nonnegative,'a nonnegative argument for the Incomplete Gamma function'] ),
  Returns(numeric),
  Synopsis( 'For a positive integer a, LnGamma returns the logarithm
of the product of 1*2*3*...*(a-1) = ln( (a-1)! ).
LnGamma satisfies the functional equation:' ),
  Paragraph( 'LnGamma(a+1) = ln(a) + LnGamma(a) = ln(Gamma(a+1))', 4 ),
  Paragraph( -2, 'For non-integer negative values, LnGamma returns the
logarithm of the absolute value of Gamma.  LnGamma is used to compute
factorials or combinatorial numbers when the results are too large
to be represented as floating point numbers.  LnGamma will compute
results for virtually all possible arguments.
When Gamma is used with two arguments,
it is understood to be the Incomplete Gamma function, defined by
the integral:' ),
  Indent(4,MapleFormula(
    'LnGamma(a,x) = ln(int( t^(a-1)*exp(-t), t=x..infinity ))')),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 6.1, 6.5.3' ),
  Examples( 'LnGamma(2)', 'LnGamma(-100.5)',
	'LnGamma(15000)', 'LnGamma(100,100)' ),
  SeeAlso( factorial, Gamma, Lngamma ) ):


Lngamma_Description := Description( function(Lngamma),
  Summary( 'logarithm of the complement of the Gamma function' ),
  CallingSequence( noeval(Lngamma(a,x)) ),
  Parameters( ['a', positive, 'a numerical value'],
    [x,nonnegative,'a nonnegative argument for the Incomplete Gamma function'] ),
  Returns(numeric),
  Synopsis( 'Lngamma is the logarithm of the complement with respect
to Gamma(a) of the Incomplete Gamma function:' ),
  Paragraph( 'Lngamma(a,x) = ln( Gamma(a) - Gamma(a,x) )', 4 ),
  Indent(4,MapleFormula( 'Lngamma(a,x) = ln(int( t^(a-1)*exp(-t), t=0..x ))' )),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 6.5.2' ),
  Examples( 'Lngamma(2,3)', 'ln( Gamma(2) - Gamma(2,3) )' ),
  SeeAlso( factorial, Gamma, LnGamma ) ):

log_Description := Description( function(log),
  CallingSequence( noeval(log(x)), noeval(log(A)) ),
  Parameters( ['x', 'a numerical value > 0'],
	['A','a square numerical matrix'] ),
  Returns(numeric,matrix(numeric)),
  Synopsis( 'This function computes the logarithm base e
(e = 2.71828...) if the parameter is a single numerical value.
This is usually called the natural logarithm.
If the argument is a square matrix, it computes a square matrix B
with the same dimensions as A
such that e^B=A, or the natural logarithm of a square matrix.
Not all matrices have a logarithm (which is real-valued).
For all numerical values of x, log(exp(x))=x.  Log is an alias
for ln.' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 4.1' ),
  Examples( 'log(1)', 'log(5)', 'log([[2, 1], [3, 4]])' ),
  SeeAlso( exp, expx1, ilogb, ln, lg, ln1x, log10 )
  ):

lowercase_Description := Description(
  function(lowercase),
  CallingSequence( noeval(lowercase(t)) ),
  Parameters( ['t', string] ),
  Returns( string ),
  Synopsis( 'The string t is converted to lowercase letters.'  ),
  Examples( 'lowercase(''Not NEARLY SO BoLD'')' ),
  SeeAlso( uppercase )
):


MaxLikelihoodSize_Description := Description( function(MaxLikelihoodSize),
  CallingSequence( noeval(MaxLikelihoodSize(m,k)) ),
  Parameters( ['m', 'posint, the number of balls'],
	['k', 'posint, the number of occupied boxes'] ),
  Returns( posint ),
  Synopsis( 'MaxLikelihoodSize determines the number of boxes
from a "balls in boxes" experiment by maximum likelihood.
When m balls are randomly distributed and they occupy k boxes
this function returns the most likely total number of boxes.
An application of this is the estimation of how many
local minima a function may have, when m random searches find k
different minima.  If m=k, the determination is not possible
(result is infinity) and the function returns DBL_MAX.  The probability
of m balls randomly distributed among n boxes using k of them is:' ),
Paragraph( 'Pr{n,m,k} = stirling2(m,k) * n(n-1)...(n-k+1) / n^m', 6 ),
  Examples( 'MaxLikelihoodSize(10,9)',
	    'MaxLikelihoodSize(10,10)',
	    'MaxLikelihoodSize(120,100)' ),
  SeeAlso( ProbBallsBoxes, ProbCloseMatches ) ):

SeeAlso_Minimize := SeeAlso( MinimizeBrent, MinimizeSD, MaximizeFunc,
    Minimize2DFunc, MinimizeFunc, DisconMinimize, BFGSMinimize, NBody,
    MaxLikelihoodSize ):
Minimize2DFunc_Description := Description( 
  function(Minimize2DFunc),
  CallingSequence( noeval(Minimize2DFunc(f,x,y,prevpoints)) ),

  Parameters( 
	['f', 'a function with two arguments to be minimized'],
	['x', 'an optional initial value for the first argument to f'],
	['y', 'an optional initial value for the second argument to f'],
	['prevpoints', 'an optional list of triplets, [x,y,f(x,y)]'] ),

  Returns([ [numeric,numeric,numeric],
	'[x,y,f(x,y)], a triplet, where x,y is a local minimum of f'] ),
  Synopsis( 'Minimize2DFunc minimizes the function f in two variables.
If x,y are given, the minimization starts at the point x,y.
If additional points are known, they can be included in the list
prevpoints and they will not be recomputed.  To avoid a point (which,
for example, has a singularity) the point should be included in the
prevpoints list with a very high (faked) value.  If no points are
given, Minimize2DFunc starts at random values U(-1,1) of x and
y.  Minimize2DFunc assumes that f(x,y) is very expensive to compute
and tries to do a minimum number of evaluations.' ),
  Examples( 'Minimize2DFunc((x,y) -> sin(x*y)+cos(y))',
	    'Minimize2DFunc((x,y) -> x^4+3*y^2-x*y,1,2)' ),
  SeeAlso_Minimize ):


MinimizeBrent_Description := Description(
  function(MinimizeBrent),
  Summary( 'Univariate minimization using Brent''s algorithm'),
  CallingSequence( noeval(MinimizeBrent(f,iniguess,incr,relateps)) ),

  Parameters( 
	[f, 'a function of one argument to be minimized'],
	[iniguess, 'an initial value for the argument of f'],
	[incr, 'an initial increment to probe around iniguess'],
	[relateps, 'a relative error goal in the argument of f']),

  Returns([ [numeric,numeric],
	'[x,f(x)], a pair, where x is a local minimum of f'] ),
  Synopsis( 'MinimizeBrent minimizes the function f(x) in one variable.
The minimization starts at the point "iniguess" and probes around
with initial increment "incr".  By giving a small increment,
one can have some assurance that a local minimum close to the
initial guess will be found.  Additional arguments to MinimizeBrent
are passed to the function f(x), so that f(x) can be written without
using global variables.  If the function cannot achieve the accuracy
requested in 200 iterations it will stop.  The algorithm uses
a technique based on 3 points spaced by the golden ratio which
was introduced by Richard Brent.' ),
  Examples( 'MinimizeBrent( cos, 3, 0.01, 1e-7 )' ),
  SeeAlso_Minimize ):

minus_Description := Description( function(minus),
  CallingSequence( 'a minus b', noeval(minus(a,b)) ),
  Parameters( ['a', 'a set'], ['b', 'a set'] ),
  Returns(set),
  Synopsis( 'Computes the set difference of two sets; that is a set
consisting of all elements in a but not in b.  The value intersect() is
understood to be the entire universe, and hence subtracting
intersect() will return the empty set and subtracting from
intersect() is not allowed.' ),
  Examples( '{1,2,3} minus {2,3,4}', '{1,2,3} minus {}',
	'{1,2,3} minus intersect()' ),
  SeeAlso( union, intersect, member, subset )
  ):

noeval_Description := Description( 
function(noeval),
CallingSequence( noeval(noeval(exp)) ),
Parameters( ['exp', 'expression'] ),
Returns( expression ),
Synopsis( 'The noeval function delays evaluation of the expression exp.  It 
simply returns exp.'),
Examples( 'unevaluated := noeval(1+1)',
	'unevaluated_function := noeval(factorial(5))',
	'unevaluated', 'unevaluated_function' ),
SeeAlso( eval )
);

NBody_Description := Description( function(NBody),
  CallingSequence( noeval(NBody(dist,var,k1)),
		   noeval(NBody(dist,var,k1,k2,rho1,rho2,inipos)) ),
  Parameters( ['dist', 'distance matrix(numeric > 0)   (1..n x 1..n)'],
	['var', 'distance variance matrix(numeric >= 0)   (1..n x 1..n)'],
	['k1', 'posint, initial dimension, k2 <= k1'],
	['k2', 'posint, final dimension'],
	['rho1', 'numeric >= 0, point separation force'],
	['rho2', 'numeric >= 0, point sequencing force'],
	['inipos', 'matrix(numeric), initial guesses (1..n x 1..k), k=k1 or k=k2']),
  Returns([matrix(numeric),'coordinates of points (1..n x 1..k2)']),
  Synopsis('NBody solves the n-body steady state problem for k1
dimensions, then squeezes the coordinates to k2 dimensions.
The problem is defined as minimizing the sum' ),
Paragraph( '( |x[i]-x[j]| - dist[i,j] ) ^ 2 / var[i,j]', 6 ),
Paragraph( '  In other words, it does a least squares approximation
of the distances.  Var[i,j]=0 is an indication that the distance
between i,j should not be used (fitted).  When the errors in
the fitting are supposed to be relative to the values of the
distances, it is typical to use var = dist.  k2, rho1, rho2 and
inipos are all optional.  If used, they must appear in the
given order.  If k2 is not present it is assumed to be equal
to k1.', -2),
Paragraph( '    Rho1 is used to guarantee some separation of the
points.  The function to minimize is added the value
rho1 / (x[i]-x[j]) ^ 4.  If not present, rho1 defaults to 0.', -2 ),
Paragraph( '    Rho2 is used to impose sequencing over the
points.  The function to minimize is added the value
rho2 * |x[i]-x[i+1]|.  This will guarantee, that if there are
many choices, the selected one will have the original sequence
preserved, like a chain.  If not present, rho2 defaults to
0.01.', -2),
Paragraph( '    Inipos is an initial
guess of the positions of the bodies.  It is a matrix of
dimension 1..n x 1..k1 (or 1..n x 1..k2).  If not present,
the algorithm starts with random locations (it uses the
function Rand()).', -2),
Paragraph( '    The global variable NBodyPotential is set to
the minimum value of the cost potential.', -2 ),
  Examples( 'dist := [ [0,1,1], [1,0,1], [1,1,0] ]',
	 'NBody(dist,dist,2,2,0,0)', 'NBodyPotential' ),
  SeeAlso_Minimize ):


Orthologues_Description := Description(
  function(Orthologues),
  Summary('find orthologous groups between various species'),
  CallingSequence( noeval(Orthologues(SpeciesList,SampleSeq,'...')) ),
  Parameters(
   [SpeciesList,list(string),'a list of strings identifying species'],
   [SampleSeq,string,'a sequence, find all homologous'],
   [MinScore,MinScore=positive,'minimum score for determining homology'],
   [ScoreTol,ScoreTol=positive,'score tolerance for stable pairs'],
   [LenthTol,LenthTol=positive,'length ratio tolerance for homology']
  ),
  Returns( list(OrthologousGroup) ),
  Synopsis( 'Orthologues finds the orthologous groups between
a set/list of species.
All the parameters are optional, but one of SpeciesList or
SampleSeq must be provided.
An orthologous pair of sequences are homologous
sequences which have diverged because of speciation alone.
That is, the most recent ancestor of the two sequences
resided in the most recent common ancestor of both species.
The process follows four steps:' ),
List( '(%d)',
'An all-against-all alignment of all sequences in the species
(or all sequences homologous to the given sample) is done.
The alignments with a score above MinScore (default 300) are refined to
compute their distance.  The alignment length has to be at
least LengthTol (default 70%) of the length of the shorter sequence.',
'The stable pairs are found, that is a pair which scores
highest among all pairs in both directions.  This maximum
score is accepted with a percentage tolerance given by
ScoreTol (default 95%).',
'The stable pairs are compared against all other species to
see if they are paralogous and not orthologous, the ones which
survive the tests are called verified stable pairs.',
'Cliques of the verified stable pairs are extracted, one at
a time to form the orthologous groups.' ),
Paragraph(-2,'The alignments are done using the Dayhoff matrices
stored in DM and DMS (normally build with CreateDayMatrices).
The orthologous groups are returned in a list of OrtholgousGroup
data structures.' ),
  Examples( 'Orthologues([''Picea abies'', ''Pinus contorta'', ''Pinus radiata''])' ),
  SeeAlso( Align, Alignment, SP_Species, Species_Entry,
OrthologousGroup, CreateDayMatrices )
):

OrthologousGroup_Description := Description( 
  structure(OrthologousGroup),
  Summary('information about an orthologous group of sequences'),
  CallingSequence( noeval(OrthologousGroup(Species, Seqs, AllAll)) ),
  Selectors(
   [Species,list(string),'species of each sequence'],
   [Seqs,list(string),'the amino acid sequence'],
   [AllAll,matrix({0,Alignment}),'All-against-all alignments'],
   [Length,posint,'number of sequences in group'],
   [Tree,Tree,'phylogenetic distance tree for the group'] ),
  Synopsis( 'This is the main result of the function Orthologues.
It stores the information about a group (clique) of orthologous
sequences belonging to various species.' ),
  SeeAlso( Orthologues, PhylogeneticTree, SP_Species, Species_Entry )
);


parse_Description := Description( function(parse),
  CallingSequence( noeval(parse(s)) ),
  Parameters( ['s', 'a string with a correct Darwin expression or statement']),
  Returns([anything,'an unevaluated Darwin expression/statement']),
  Synopsis('Parse does the same syntactic analysis that Darwin would
do on a program or interactive command.  It returns the object thus
created without evaluation.  If the string s has a syntax error, then
the command will print an appropriate error and return an error
condition.  If more than one statement is provided in the string,
then these are concatenated and a statement sequence is returned.
A terminating semicolon is not necessary, the parser will add one.
Any NULL statement will be ignored.'),
  Examples( 'parse(''a+b'')', 'eval(parse(''xyz := 1''))', 'xyz' ),
  SeeAlso( eval, noeval ) ):

PartialFraction_Description := Description( function(PartialFraction),
  CallingSequence( noeval(PartialFraction(r)), noeval(PartialFraction(r,eps)) ),
  Parameters( ['r', 'a numerical value'],
	['eps','optional, the desired accuracy of the approximation']),
  Returns( [ [integer,posint],
	'a rational number represented by two integers, p/q'] ),
  Synopsis('PartialFraction computes an approximation of the input
value r as a rational number.  The pair of integers returned, p,q,
should be interpreted as a rational approximation of r, i.e.  p/q=r.
The second argument must be a positive argument.  The computed
approximation will have an error of the same order of magnitude as
eps or smaller.  If eps is omitted the value 1e-5 is used.'),
  Examples( 'PartialFraction(1.234567)',
	'PartialFraction(-Pi,0.01)' ) ):

prints_Description := Description(
  function(prints),
  Summary('print strings in full length'),
  CallingSequence( noeval(prints(string1,'...')) ),
  Parameters( [string1,string,'a string to be printed'] ),
  Returns(NULL),
  Synopsis( 'Print all the arguments as strings (format %s)
ended with a newline.'),
  SeeAlso( print, dprint, lprint, printf, prints )
):


printf_Description := Description( 
  function(printf),
  CallingSequence( noeval(printf(textpattern,' e1, e2,...' ))),
  Parameters( ['textpattern', string], ['ei', expression] ),
  Returns(NULL),
  Synopsis( ' The printf statement behaves in a similar manner as C''s
  	printf statement.'),
  Paragraph('Conversion characters for the printf command' -5),

  Table( gutter=3, width=60, ColAlign(c, l),
  Row('Character', 'Description'),
  Row('a', 'prints any Darwin value including lists, sets and structures'),
  Row('A', 'same as a, but will quote strings (same as dprint)'),
  Row('c', 'prints a single character'),
  Row('d', 'prints an integer'),
  Row('e', 'prints a number in exponential notation'),
  Row('f', 'prints a number (decimal notation)'),
  Row('g', 'prints a number (general format, use f or e, whichever is shorter)'),
  Row('e', 'prints a number (explicit exponent)'),
  Row('o', 'prints the octal conversion of an integer'),
  Row('s', 'prints a string (symbol or string)'),
  Row('u', 'prints an unsigned integer'),
  Row('x', 'prints the hexadecimal conversion of an integer'),
  Row('%', 'prints a percent sign %') ),

  Paragraph('The cursor control sequences for the printf command:',-5),
  Table( gutter=3, width=60, ColAlign(c,l),
  Row('Character', 'Description'),
  Row('b', 'backspace'),
  Row('n', 'carriage return and newline'),
  Row('t', 'tab'),
  Row('v', 'newline'),
  Row(' \\\\ ', 'single backslash'),
  Row(' '''' ', 'single quote') ),

  Examples(
    Print( 'printf(''%a, %a\\n'', [''L'', ''I'', ''S'', ''T''], 
    ''a means any structure'')' ),
    'int := 1234',
    Print( 'printf(''|%d|%10d|%-10d|\\n'', int, int, int, int)' ),
    't := 1234.567',
    Print( 'printf(''|%f|%12f|%12.5f|%-12.5f|\\n'', t, t, t, t)' ),
    Print( 'printf(''|%11s|%12s|%12s|%12s|\\n'', ''normal'',
    ''field of 12'', ''5 decimal'', ''left flush'')' ),
    Unassign('t','int')
	),
  SeeAlso( prints, print, lprint, sprintf, sscanf )
):

Readability_Description := Description(
  function( Readability ),
  Summary( 'statistical index of readability' ),
  CallingSequence( noeval( Readability( s, Counts, Ctype )) ),
  Parameters( [s, string, 'input text to compute readability index'],
	[Counts,array(integer,26,26),'optional statistical frequencies'],
	[Ctype,symbol,'optional name of frequencies'] ),
  Returns( numeric ),
  Synopsis( 'Readability computes an index based on how well
the text follows a given set of probabilities of pairs of characters.
The probabilities are computed from a 26 x 26 matrix of counts of
occurrences of pairs of letters.
Non letters are ignored (including spaces) and case is not sensitive.
The following names of frequencies are implemented:'),
Table( center, ColAlign('l','l'),
  Row('Ctype','Description'), Rule,
  Row('English','di-graphs frequencies for Shakespeare'),
  Row('VowCon','(default) vowel-consonant pairs only'),
  Row('VowConF','vowel-consonant pairs including letter frequencies'),
  Row('Spanish','di-graphs frequencies for Spanish') ),
  Examples( 'Readability(''To be or not to be that is the question'',English)',
    'Readability(''En un lugar de la Mancha de cuyo nombre no me acuerdo'',English)',
    'Readability(ASILITE,VowCon)' ),
  SeeAlso( Rand, Mutate, Sequence )
):

ReadData_Description := Description(
  function( ReadData ),
  Summary( 'read a formatted file' ),
  CallingSequence( noeval( ReadData( filename, fmt )) ),
  Parameters( [filename, string, 'name of file to be read'],
	[fmt,string,'a valid sscanf format'] ),
  Returns( list(list) ),
  Synopsis( 'ReadData opens and reads the file and scans
each line with the format given.  The result of the scan is stored
in a list which is returned.  Normally this will be a matrix
(list of lists).  If there are format errors, a message is
printed and the process continues up to 100 errors.' ),
  SeeAlso( ReadProgram, ReadRawFile, LockFile, FileStat, OpenReading, ReadRawLine, 
  SearchDelim, MySql )
):

ReadLibrary_Description := Description(
  function( ReadLibrary ),
  CallingSequence( noeval( ReadLibrary( filename )),
    noeval( ReadLibrary( filename, funcname )) ),
  Parameters( ['filename', string, 'procedure name or library filename'],
	['funcname', symbol, 'procedure name'] ),
  Returns( procedure ),
  Synopsis( 'If only filename is supplied as a parameter, this function
loads the contents of filename located in the user''s
local Darwin library.
The ReadLibrary returns the function with the supplied name.
If there is a second parameter, the first one is used to load
the file from the library and the second should be a procedure
name which is loaded in that file.
ReadLibrary returns the procedure named in the second argument.
With two arguments, if the filename starts with a slash ("/"),
the it is assumed to be an absolute path name and the library
name (stored in libname) will not be prepended to it.
The location of the Darwin library is set
with the  -l flag when initiating your Darwin session and is
kept in the global variable "libname".' ),
Paragraph( -2, 'One of the main uses of ReadLibrary is to
provide a mechanism for automatic loading of functions from
the library.
By assigning a name with an unevaluated call to ReadLibrary
(with the appropriate parameters), when the function is used
(and its name is evaluated),
it will produce the actual reading of the library.
Since reading the library is likely to assign the function name
with a proc (or something else), the unevaluated ReadLibrary will
be obliterated and the reading of the library happens only once.
This mechanism allows efficient reading of library functions from
many points; the first read will be the only one executed.
The file "darwinit" in the Darwin library provides the definitions
of all system-defined functions and many different examples of its
use.'),
  Examples( Fake('ReadLibrary(MultiAlign)',''),
	Fake('ReadLibrary(MultiAlign, AnchorAlign)','') ),
  SeeAlso( ReadProgram, ReadRawFile, 'libname' )
):

PrintMatrix_Description := Description( function(PrintMatrix),
  CallingSequence( noeval(PrintMatrix(A,format)) ),
  Parameters( ['A', 'a rectangular or square matrix'],
	['format','optional, a formatting string, as in printf']),
  Returns(  NULL ),
  Synopsis('This function pretty-prints a square or rectangular matrix.
It is normally used by the print() command.  If called directly, the user
can specify the format to be used.  Without a printing format, it will
calculate a reasonable format to fit on the screen width.' ),
  Examples(
   Print('PrintMatrix( [[1,2], [3,4]] )' ),
   Print('PrintMatrix( [[1/7,2/7], [3/7,4/7]], ''%13.10f'')' ) ),
  SeeAlso( print, [printf,'for the codes accepted as format']) ):

ReadProgram_Description := Description( function(ReadProgram),
  CallingSequence( noeval(ReadProgram(fname)) ),
  Parameters( ['fname', 'a string which is a file name']),
  Returns( NULL ),
  Synopsis('ReadProgram opens the file indicated by fname.  The file
name should be readable from the directory where Darwin is being
executed.  The file is expected to contain valid Darwin statements.
All statements in the file are read and are only echoed if printlevel
is sufficiently high.  The effect of the statements read is as if
they were executed at the top level, even when ReadProgram is called
inside a function'),
  Examples(Fake('ReadProgram(test)','') ),
  SeeAlso( OpenAppending, OpenPipe, ReadBrk, ReadDb, ReadFasta,
	ReadDssp, ReadLibrary, ReadLine, OpenReading, ReadMap,
	ReadMsa, ReadPhylip, ReadOffsetLine, ReadPima, ReadPir, ReadProgram,
	ReadRawFile, LockFile, FileStat, OpenWriting, MySql) ):

remember_Description := Description(
  function(remember),
  Summary( 'evaluate a function and remember its result' ),
  CallingSequence( noeval(remember(func_call)) ),
  Parameters( [func_call, structure, 'a function call'] ),
  Returns( anything ),
  Synopsis(
'The remember function stores results of function evaluations
in an internal table for the purpose of saving computation time.
When remember is called, the system checks to see if the argument
function has been called previously with the same arguments, and
if so, then the previous result is returned.
If it is not found, the function call is executed and its result
stored in the internal table as well as returned to the user.
The internal table does not keep all the results forever, at
garbage collection time arguments that are no longer available
will cause the corresponding entries to be removed.
Eventually, all unused entries will be removed.
The user of remember should keep in mind that this is a heuristic
saving of evaluations, it should not be counted on happening
every time.' ),
Paragraph( -2, 'Remember is usable when the argument function
does not have side effects (for example printing), as it will
be unpredictable when these side effects will happen.
It should also be used on functions which do a significant
amount of computation, else its effort is not justifiable.
The profiling tools are good to determine which functions will
profit from remembering.' ),
Paragraph( -2, 'Warning: When the returned value is a structure
(e.g. a matrix or a class), changing the structure will also change 
value stored in the remember-table! This will lead to unexpected
behaviour.'),
Paragraph( -2, 'In case that the user wants to erase the remember
table, (for example the function to be remembered has changed its
behavior in some way and old values should not be remembered),
calling remember with the argument "erase" will erase all previously
remembered values'),
Paragraph( -2, 'For the example below we compute the Fibonacci
numbers with their simple recurrence.
Without the remember function, this definition takes exponential time.' ),
 Examples( 'F := proc( n:integer )
if n < 2 then n else
remember(F(n-1)) + remember(F(n-2)) fi end:',
'[ seq( F(i), i=0..10 )]',
'F(25)', Unassign('F') ),
  SeeAlso( hash, table, profiling )
);

return_Description := Description( 	
  function(return),
  CallingSequence( noeval(return(obj)) ),
  Parameters( ['obj', anything] ),
  Returns( anything ),
  Synopsis( 
'The  return function causes Darwin to immediately exit a
procedure and return obj to the point of calling.' ),
  Examples( 'sum_up := proc(x) \n   total := 0:\n    for i from 1 to x do \n        total := total + i\n    od;\n    return(total);\nend', 'sum_up(1772)' ),
  SeeAlso( exit )
);

exit_Description := Description(
  function( exit ),
  CallingSequence( noeval( exit( status ) )),
  Parameters(['status',{0,posint},'exit status code'] ),
  Synopsis( 
'The exit function causes Darwin to immediately be terminated and the value of status is returned to the parent process. A non-zero exit code indicates an 
error whereas 0 indicates a successful termination.'),
  References( 'man 3 exit' ),
  Examples( Fake('exit(2)','') ),
  SeeAlso( return )
);

Roman_Description := Description(
  function(Roman),
  Summary( 'convert an integer to a roman numeral' ),
  CallingSequence( noeval(Roman(n)) ),
  Parameters( [n, posint] ),
  Returns( string ),
  Synopsis( 'Roman converts a positive integer into an
uppercase roman numeral.  The conversion cannot be done for n<=0.
For very large numbers, the output string becomes linear in n/1000.' ),
  Examples( 'Roman(73)', 'Roman(1948)', 'lowercase(Roman(14))' ),
  SeeAlsoDocument
);


ReadFasta_Description := Description(
  function(ReadFasta),
  Summary('load fasta sequence file'),
  CallingSequence( noeval(ReadFasta(fn)) ),
  Parameters( ['fn', string, 'filename']),
  Returns( [list(string), list(string)] ),
  Synopsis( 'ReadFasta loads a file with fasta sequences and returns
a list of sequences and a list of ids.'),
  SeeAlso( OpenAppending, OpenPipe, ReadBrk, ReadDb,
	ReadDssp, ReadLibrary, ReadLine, OpenReading, ReadMap,
	ReadMsa, ReadOffsetLine, ReadPima, ReadPir, ReadProgram,
	ReadRawFile, LockFile, FileStat, OpenWriting, MySql) 
):


RunDarwinSession_Description := Description(
  function(RunDarwinSession),
  Summary( 'run Darwin code inside a Document and insert results' ),
  CallingSequence( noeval(RunDarwinSession(doc)) ),
  Parameters( [doc, structure, 'typically a document or part of one'] ),
  Returns( structure ),
  Synopsis( 'RunDarwinSession scans the input Document structure
(or part of one) and collects all the structures of type DarwinCode(string),
DarwinHideInput(string), DarwinExpression(string), DarwinHidden(string) and
DarwinCodeHTML(string).
These have the following effects:' ),

Paragraph( -15, 'DarwinCode(string) - The string contents of this
structure are interpreted as statements to a darwin session and
are collected and executed by darwin.  The output is separated
into its component, and each original DarwinCode structure is
replaced by a green Code structure containing the input and
a red Code structure containing the output.' ),

Paragraph( -15, 'DarwinHideInput(string) - The string contents of this
structure are interpreted as statements to a darwin session and
are collected and executed by darwin.  The output is separated
into its component, and each original DarwinHideInput structure is
replaced by a red Code structure containing the output.' ),

Paragraph( -15, 'DarwinExpression(string) - The contents of this
structure are considered to be statements also to be merged
in the darwin code and executed.
Their values will replace the structure in the Document.
DarwinExpressions serve as a mechanism to incorporate values
computed in the darwin run, which may not be known, into the
text of the Document.' ),

Paragraph( -15, 'DarwinHidden(string) - The contents of this
structure is executed, but no result is incorporated in the document.
This is useful to set parameters appropriately while it is unwanted
to reflect this in the resulting document.
E.g. Set(gc=xxx).' ),

Paragraph( -15, 'DarwinCodeHTML(string) - The contents of this
structure are assumed to contain characters which are invalid
in normal HTML, (like "<" and ">") and these characters are
converted to their corresponding Entity Names.
Typical uses of this structure are programs which have the
special symbols or programs which will output HTML tags.
E.g. "if a < b then ..." or printf( ''<tag>%s</tag>'' ).' ),

Paragraph( -15, 'InvokeDarwin - This is a global variable
which may be assigned with the name of a command to execute Darwin
if the default ("darwin") is not suitable.  This is needed when
the Darwin command is special or it must be executed with special
arguments.' ), 

Paragraph( -15, 'DarwinOutputUpperLimit - This is a global variable
which if assigned with a positive integer (call it n) will limit the
number of output lines of each single DarwinCode() set of statements.
The value n is the number of lines to be displayed, and if the output
has more lines than n lines, the top n/2 lines will be displayed
followed by a line ". . . . (xxx output lines skipped) . . . ."
followed by the last n/2 lines.
This is very useful when the output is undesirably long, but necessary.' ),

Paragraph( -15, 'DarwinTimeout - This is a global variable
which if assigned a positive value will limit the execution time of
the Darwin session to that value (in seconds).
By default the session is allowed to run for 600 seconds.' ),

Paragraph( -2, 'RunDarwinSession is relatively robust against
errors, help files, etc.
It cannot display objects which are shown with the command View.' ),
  SeeAlsoDocument
);


UTCTime_Description := Description(
  function(UTCTime),
  Summary( 'UTC time in seconds or wall-clock time of evaluation' ),
  CallingSequence( noeval(UTCTime()), noeval(UTCTime(expr)) ),
  Parameters( ['expr', expression] ),
  Returns( numeric ),
  Synopsis( 'This function returns the total wall-clock time taken to
evaluate the expression expr.  When no expression is passed, it
returns the number of seconds since  00:00:00 GMT, January 1, 1970.
This is called UTC time or Coordinated Universal Time.'),
  Examples( 'UTCTime()', 'UTCTime(log10(factorial(100)))',
	'UTCTime( CallSystem(''sleep 2'') )' ),
  SeeAlso( TimedCallSystem, date, time )
):

scalb_Description := Description( function(scalb),
  CallingSequence( noeval(scalb(x,n)) ),
  Parameters( ['x', 'a numerical value'],
		['n', 'an integer'] ),
  Returns(numeric),
  Synopsis('scalb returns the value x multiplied by the base to
the power n.  This function is defined in the IEEE 754 floating
point standard.  For IEEE 754 floating point, the base is 2 and
scalb(x,n) = x * 2^n, is computed by exponent manipulation directly
from the representation.  Hence it is very fast and exact.' ),
  Examples( 'scalb(1,10)', 'scalb(1,-1023)', 'scalb(0,1024)' ),
  SeeAlso( ilogb, lg ) ):

mselect_Description := Description( function(mselect),
  CallingSequence( noeval(mselect(fn,obj,'[arg2,...]')) ),
  Parameters( ['fn', 'the selection function, returns true/false'],
	['obj', 'a composed object (list, set, structure) whose parts
will be selected'],
	['arg2', 'additional arguments that are passed to fn'] ),
  Returns([anything,'the result is of the same type as obj']),
  Synopsis('Mselect selects the parts of the second argument and builds a
new object of the same type, but only with the parts for which the function
fn is true.  More precisely, for each i from 1 to length(obj), op(i,obj)
will be in the result depending on fn(op(i,obj),arg2..) being true or
false.  The extra arguments, arg2, ... are passed as additional arguments
to fn.'),
  Paragraph('Select is normally used on lists sets or structures.',-2),
  Examples( 'mselect( type, [-1,0,1,1.2], posint )',
	    'mselect( x -> (x<1), [-1,0,1,1.2] )' ),
  SeeAlso(op) ):

seq_Description := Description(
  function( seq ),
  CallingSequence( noeval( seq(e,n) ),
	noeval( seq(e, i=lo..hi) ),
	noeval( seq(e, i=SetOrList) )),
  Parameters( ['e', 'an arbitrary expression'], ['n',integer],
	['i',symbol], ['lo', numeric], ['hi', numeric],
	[SetOrList,{set,list},'set or list of values'] ),
  Returns( 'expression sequence of the e objects' ),
  Synopsis( 'In the first format, an expression sequence with e
replicated n times is returned.
This is useful, for example, to create arrays with initial values
and to pad arrays.
Normally, expression sequences will be enclosed in lists, sets or
as arguments of functions or data structures.
In the second format, an expression sequence is produced for all
the values of e with the symbol i assigned consecutive values
from lo to hi (inclusive).  In both cases, a negative integer or
hi < lo will generate an empty expression sequence.
In the third format, the variable i will take all the values
from the set or list.' ),
  Examples( '[seq(7,3)]', '{seq(2^i,i=0..10)}', 'A(seq(i,i=1.5..2.8))',
	'seq(Rand(),4)', '[seq(0,5),seq(i,i=1..5),seq(6,3)]' ),
  SeeAlso( sum, op, zip )
):

sequal_Description := Description(
  function( sequal ),
  CallingSequence( noeval( sequal(a,b) ) ),
  Parameters( ['a', 'an arbitrary expression'], ['b', 'an arbitrary expression'] ),
  Returns( 'true or false' ),
  Synopsis( 'sequal tests for the structural equality of expressions.
This means that if two expressions differ in their structure, but
represent the same value, (e.g. LongInteger(1) and 1), sequal will
just test for the structural equality, and hence sequal(LongInteger(1),1)
will return false, whereas evalb(LongInteger(1)=1) will return true.
Quoted strings and symbols representing the same character sequence,
compare equal under normal equality but will compare different with
sequal.  The primary use of sequal is to take advantage
of the representation of an object, and test for an exact
representation, other than just a value.  Indiscriminate use of sequal
leads to non-polymorphic programs.' ),
  Examples( 'sequal(LongInteger(1),1)',
	'evalb(LongInteger(1)=1)',
	'sequal( {1,2,3}, {1,2} )',
	'sequal(''abc'',abc)' ),
  SeeAlso( evalb, If, objectorientation )
):

Shuffle_Description := Description(
  function( Shuffle ),
  CallingSequence( noeval( Shuffle(t) )),
  Parameters( ['t', '{string, list, structure}'] ),
  Returns( 'type(t)' ),
  Synopsis( 'Randomly permute the characters (when t is a string) or
components (when t is a list or a structure).  A new object is created and
the argument is left unchanged.' ),
  Examples( 'Shuffle(''abcdefghijklmnopqrstuvwxyz'')',
	'Shuffle([1,2,3,4])', 'Shuffle(ABC(a1,a2,a3,a4))' ),
  SeeAlso( CreateRandPermutation, Mutate, CreateRandSeq, Permutation )
):

SignedSynteny_Description := Description( function(SignedSynteny),
  Summary('find the number of inversions of a signed permutation'),
  CallingSequence( noeval(SignedSynteny(perm)) ),
  Parameters( [perm, list(integer), 'a permutation'] ),
  Returns(integer),
  Synopsis('SignedSynteny finds the minimum
number of reversals needed to transform the input permutation
into an ascending straight run of positive integers.
The input permutation is a list of length n of the integers from 1 to n,
where each number is also assigned a sign plus or minus (plus is implicit). 
A reversal operation modifies a signed permutation by swapping the order of
a particular contiguous range and flipping the sign of the elements in the
range. The problem of finding the synteny distance between two genomes,
with known direction of every gene in the genomes, can be reduced to the
problem of finding the number of reversals.
SignedSynteny runs in O(n) and is an implementation of the algorithm
described in "Kaplan et al., Faster and simpler algorithm for sorting signed
permutations by reversals, SODA ''97, ISBN:0-89871-390-0, 344-351, 1997.",
except for a sub-algorithm to find connected components in a special graph. 
A faster algorithm to find the connected components is given in
"Bader et al., A linear-time algorithm for computing inversion distance
between signed permutations with an experimental study, WADS ''01,
ISBN:3-540-42423-7, 365-376, 2001."'),
  Examples( 'SignedSynteny([8, 9, -6, -1, 3, 5, -7, 2, 4])',
	'SignedSynteny([4, 5, 6, -3, -1, -2])' ),
  SeeAlso(PhylogeneticTree, LeastSquaresTree, Synteny, GapTree,
SignedSynteny, DrawTree)):

sin_Description := Description( function(sin),
  CallingSequence( noeval(sin(x)) ),
  Parameters( ['x', 'a numerical value'] ),
  Returns(numeric),
  Synopsis( 'This function computes the trigonometric sine function.
sin(x) has simple zeros at at x=n*Pi.' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 4.3' ),
  Examples( 'sin(0)', 'sin(Pi/4)', 'sin(Pi/2)', 'sin(-Pi)' ),
  SeeAlso( cos, tan, arctan, arcsin )
  ):


SmallAllAll_Description := Description( function(SmallAllAll),
  Summary( 'do an all-against-all matching of a small database' ),
  CallingSequence( noeval(SmallAllAll( MinSim)) ),
  Parameters( [MinSim,numeric,'optional cutoff value for match similarity'] ),
  Returns(NULL),
  Synopsis( 'This function does a complete match of all sequences
in a database against each other.  A database must have been loaded
previously with the ReadDb command.  This function works more like
a program and it prints all sorts of information about the all-all
matching.  A file named DB[Filename].AA is created with the
darwin-readable results of the matrix of matches.  Besides
the matrix of matches, the file contains commands to build
a phylogenetic tree, a probabilistic ancestral sequence and
a multiple alignment of all the sequences.  It is expected
that the user will inspect this file, and choose which commands
to run.  Some of the less used commands are commented out in the
output file.
If the sequences of the database are disconnected in several
groups, that is no significant match can be found between the sequences,
these groups are placed in different files named DB[FileName].i
for consecutive values of i.  If MinSim is omitted it defaults to 100.' ),
  SeeAlso( ReadDb, AlignOneAll, Match )
  ):

subs_Description := Description( function(subs),
  Summary('substitute occurrences of subexpressions'),
  CallingSequence( noeval(subs(val1=repl1,val2=repl2,'...', s)) ),
  Parameters(
        ['val.i',anything,'an object to be replaced in s'],
	['repl.i',anything,'the replacement of val.i'],
	['s', anything, 'an arbitrary object'] ),
  Returns(anything),
  Synopsis('The function subs, creates a new expression,
substituting every occurrence of the
given values by the corresponding replacements.
The substitutions happen left-to-right for the entire s.' ),
  Examples( 'subs(3=abc,[1,2,3])', 'subs(2=77,[77]=abc,A(1,[2],3))',
        'subs(A=B,A(11,22))'),
  SeeAlso_symbolic ):

sum_Description := Description(
  function( sum ),
  CallingSequence( noeval( sum(a) ),
	noeval( sum(p, i=lo..hi) ),
	noeval( sum(p, i=s) ) ),
  Parameters( ['a', 'list','a list of summable elements'],
	['lo', 'numeric', 'lower index of summation'],
	['hi', 'numeric','upper bound of summation'],
	[p,anything,'expression to be summed for all index values'],
	[s,{set,list},'set or list of index valuex'] ),
  Returns( numeric ),
  Synopsis( 'When sum is called with a list, the sum of all the
elements of the list is computed.
The formats with an index variable, i, sum the expression p for
all the values of the variable i.
The expression p is evaluated each time that i is assigned a value.
If a range of values is given, i is first assigned lo which is
incremented by 1 every time.
The expression p is evaluated and summed as long as i <= hi.
In the third format, i is assigned all the values of the set
or list.
If sum is applied on a matrix, the rows are summed, an easy way
of adding the columns.
If it is applied twice on a matrix it will return the sum of all
the elements of a matrix.
The summation variable can be assigned another value, it will
not be changed, nor it will disturb the summation.' ),
  Examples( 'sum([1,3,19])',
	'sum(1/i,i=1..1000)',
	'sum(i^2,i={2,3,5,7})',
	'A := [[1,2,3],[2,2,2]]:',
	'sum(A)', 'sum(sum(A))',
	'i:=nonsense', 'sum(10*i,i=1.53 .. 2)', 'i',
	Unassign('A','i') ),
  SeeAlso( op, seq, zip, product, matrix, list )
):

product_Description := Description(
  function( product ),
  CallingSequence( noeval( product(a) ),
	noeval( product(p, i=lo..hi) ),
	noeval( product(p, i=s) ) ),
  Parameters( ['a', 'list','a list of multipliable elements'],
	['lo', 'numeric', 'lower bound of index'],
	['hi', 'numeric','upper bound of index'],
	[p,anything,'expression to be multiplied for all index values'],
	[s,{set,list},'set or list of index values'] ),
  Returns( numeric ),
  Synopsis( 'When product is called with a list, the product of all the
elements of the list is computed.
The formats with an index variable, i, multiplies the expression p for
all the values of the variable i.
The expression p is evaluated each time that i is assigned a value.
If a range of values is given, i is first assigned lo which is
incremented by 1 every time.
The expression p is evaluated and multiplied as long as i <= hi.
In the third format, i is assigned all the values of the set
or list.
The index variable can be assigned another value, it will
not be changed, nor it will disturb the multiplication. ' ),
  Examples( 'product([1,3,6])',
	'product(i,i=1..10)',
	'product(i^2,i={2,3,5,7})',
	'i:=nonsense', 'product(10*i,i=1..2)', 'i',
	'product([])',
	Unassign('A','i') ),
  SeeAlso( op, seq, zip, product, list, sum )
):


symbol_Description := Description( function(symbol),
  CallingSequence( noeval(symbol(s)) ),
  Parameters( ['s', 'a string']),
  Returns(symbol),
  Synopsis('Symbol transforms a string into a symbol (a Darwin
variable that can hold values).  This is typically needed when a
name is formed by concatenation or as a result of an sprintf() command.
The symbol obtained always refers to a global symbol, never to a local
or to a parameter, when computed inside a procedure.'),
  Examples(
  'symbol(a.b)', 'type(symbol(a.b))', 'type(a.b)' ),
  SeeAlso(string,names) ):

Synteny_Description := Description( function(Synteny),
  Summary('find the number of inversions of a permutation'),
  CallingSequence( noeval(Synteny(perm,k)) ),
  Parameters( [perm, list(posint), 'a permutation'],
	[k,posint,'(optional) effort to be done']),
  Returns(integer),
  Synopsis('Synteny finds an approximation to the minimum
number of inversions needed to transform the input permutation
into a straight run (ascending or descending).
The input permutation is a list of the integers from 1 to n,
where n is the length of the list.
An inversion operation is a modification of a permutation
which selects a particular contiguous range and swaps its
order.
The problem of finding the synteny distance between to genomes
can be easily reduced to the problem of finding the number of
inversions to straighten the permutation.
The parameter k gives the function a hint on how much work
should be done, it is the number of partial solutions that
will be kept during the search.
The problem is NP-complete, so this algorithm searches for a
good approximate solution.
The higher k, the more work it will be done.
For a particular problem, the amount of work is linear in k.
By default k=10.' ),
  Examples( 'Synteny( [1,7,8,9,6,5,4,2,3] )',
	'Synteny( [4,5,6,1,2,3,7,8,9] )' ),
  SeeAlso( PhylogeneticTree, LeastSquaresTree, Synteny, DrawTree,
SignedSynteny, GapTree ) ):

SystemCommand_Description := Description( function(SystemCommand),
  Summary('execute a system command'),
  CallingSequence( noeval(SystemCommand(operation,addit_args)) ),
  Parameters( ['operation', string, 'the name of the system operation'],
	[addit_args, string, '(optional) additional argument needed'] ),
  Returns(numeric),
  Synopsis( 'This command is provided to isolate system dependencies
for performing some operations which require execution of other,
standard, programs in the system.
The optional additional arguments are dependent on the operation
and are typically file names on which the commands should be run.
The value returned is the integer value returned by the CallSystem
command that will run this operation.
This command also allows for simple customization for non-standard
installations.
In this case, the file lib/SystemCommand may have to be extended with
particular commands for your system.
The valid values for operation are:' ),
Paragraph( -20, '  HTML           HTML viewer -- one additional parameter,
the name of the file which contains html source.
The process should be detached to allow stand-alone perusal.' ),
Paragraph( -20, '  postscript     postscript viewer -- one additional
parameter, the name of the postscript file.
(Usually a file ending in ".ps").
The process should detach to allow stand-alone perusal.
This is the command that will show all the darwin plots.' ),
Paragraph( -20, '  darwin         darwin -- two additional parameters,
the name of a file with darwin input commands and the name of the file
where the output will be placed.  The input file should end with
a "quit" command, else the spawned darwin will attempt to read from
the user once that all the commands are executed.'),
Paragraph( -20, '  gimp           picture processing software
(could be gimp, photoshop or something equivalent) -- one additional
parameter, the name of the file (typically a jpg, gif, ps or pdf)' ),
Paragraph( -20, '  rm             remove file(s) -- one additional
argument with the name(s) of the file(s) to be removed.
The removing is forced and without questions asked.'),
Paragraph( -20, '  maple          the maple computer algebra system
-- two additional parameters, the name of a file with maple input
commands and the name of the file where the output will be placed.
Maple is run with option quiet to avoid unnecessary/confusing output.' ),
  SeeAlso( CallSystem, TimedCallSystem, date, hostname )
  ):

tan_Description := Description( function(tan),
  CallingSequence( noeval(tan(x)) ),
  Parameters( ['x', 'a numerical value'] ),
  Returns(numeric),
  Synopsis( 'This function computes the trigonometric tangent function
defined by: tan(x) = sin(x)/cos(x).  tan(x) has a simple poles
at x=Pi/2+n*Pi.' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 4.3' ),
  Examples( 'tan(0)', 'tan(Pi/4)', 'tan(-Pi)' ),
  SeeAlso( sin, cos, arctan, arcsin )
  ):

time_Description := Description(
function(time),
CallingSequence( noeval(time()), noeval(time(expr)) ),
Returns( expression ),
Synopsis( 'This function returns the time needed to evaluate expr.
If no expression is specified, it returns the total CPU
time used by the current session of Darwin.
If time is called with the string "all", then the total CPU time
of the process and all its children is returned.  This is useful to
find the total time used when Darwin calls other programs.' ),
Examples( 'time()', 'time(exp(1.7 * 3.14))', 'time(all)' ),
SeeAlso( TimedCallSystem, date, UTCTime, gigahertz )
);


TimedCallSystem_Description := Description( function(TimedCallSystem),
  CallingSequence( noeval(TimedCallSystem(cmd)),
	noeval(TimedCallSystem(cmd,timeout)) ),
  Parameters( ['cmd', 'a string containing a system command'],
	['timeout', 'an optional integer number of seconds'] ),
  Returns( [[integer,string], 'return code and result of command'] ),
  Synopsis( 'The "cmd" argument is passed to the underlying
operating system.  If the optional "timeout" argument is specified,
Darwin allows for "timeout" seconds of execution.  If the command
does not terminate in the allocated time, it is killed and the
TimedCallSystem returns [-1, ''(Timeout)''], otherwise it returns
a list consisting of the execution return code value returned by
the operating system and the output generated by cmd.  The output
is returned as a string.  It will normally be ended with a newline
character.  Normally, a return code 0 indicates successful execution.' ),
  Examples( 'TimedCallSystem(date,10)', 'TimedCallSystem(''sleep 5'',3)' ),
  SeeAlso( CallSystem, time, UTCTime, SystemCommand )
  ):

traperror_Description := Description( function(traperror), 
  CallingSequence( noeval(traperror( exp ))),
  Parameters( ['exp', 'expression'] ),
  Returns( 'The result of evaluating exp or a string.' ),
  Synopsis( 
'If an error occurs while evaluating exp, the  traperror
function returns a  string consisting of the Darwin error message.
Execution does not halt.  If no error occurs,  traperror simply
returns the result of evaluating exp.' ),
  Examples( 'traperror( undefined_symbol/20 )' ),
  SeeAlso( error, lasterror )
):

trunc_Description := Description (
  function(trunc),
  CallingSequence( noeval( trunc(x) ) ),
  Parameters( ['x', numeric] ),
  Returns( integer ),
  Synopsis( 'Returns the integer portion of the argument x.'),
  Examples( 'trunc(9.9999999)', 'trunc(-9.99999)' ),
  SeeAlso( ceil, floor, round, mod )
):

uppercase_Description := Description( 
  function(uppercase),
  CallingSequence( noeval(uppercase(t)) ),
  Parameters( ['t', string] ),
  Returns( string ),
  Synopsis( 'This function returns the  string t converted to uppercase.' ),
  Examples( 'uppercase(''I have been converted'')' ),
  SeeAlso( lowercase )
):


View_Description := Description(
  function(View),
  Summary( 'show an object on the screen in a visual way' ),
  CallingSequence( noeval(View(t)) ),
  Parameters( ['t', anything,'an object to be displayed'] ),
  Returns( 'NULL' ),
  Synopsis( 'This function attempts to display an object in
a visual way.  If the object is an HTML file, a browser will
be called.  If it is a plot, a postscript viewer will be called,
if it is a Latex file, the xdvi viewer will be called.
This function is very system dependent, it works only in unix/linux,
and assumes that the underlying programs are available.' ),
  Examples( Fake('View(Histogram(data))',''),
	Fake('View(HTML(doc))','') ),
  SeeAlsoDocument
):


Zeta_Description := Description( function(Zeta),
  CallingSequence( noeval(Zeta(s)) ),
  Parameters( ['s', 'numeric'] ),
  Returns(numeric),
  Synopsis( 'This function computes the Riemann Zeta function
defined by' ),
  Indent(4,MapleFormula( 'Zeta(s) = sum( 1 / i^s, i=1..inifinity )')),
  Paragraph( '  Zeta has a simple pole at s=1.  For all other values
it is defined as the complex-plane extension of the above sum.', -2 ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 23.2' ),
  Examples( 'Zeta(2)', 'Zeta(3)', 'Zeta(-0.5)' )
  ):

zip_Description := Description (
  function(zip),
  Summary( 'compute an expression for each component' ),
  CallingSequence( noeval(zip(expr)) ),
  Parameters( ['expr', expression] ),
  Returns( list(expression) ),
  Synopsis( 'Compute an expression over the components of a list
element-wise.
Zip gets its name from an operation like a+b, where a and b are
lists of the same length and the result is the component-wise
sum of each element of a and b.
It is like zipping the two vectors together.
In general, if the expr is an expression which contains vectors
(or list or sets), and all these lists or sets are of the same
length, then zip will compute the expression for each value of
the lists/sets and return a list with the results.
The arguments or components of expr which are not list/sets
will be taken as constants.
Notice that even if the argument contain only sets, zip will
still return a list.' ),
  Examples( 'zip( sin( [1,2,3] ))',
	'f := proc(a,b,c) a*b+c end',
	'zip( f( [1,2,3], 10, {0.1,0.2,0.3} ))',
	'zip( f( 1, [2,3,4,5], Pi-3 ))',
	Unassign( 'f' ) ),
  SeeAlso( op, sum, seq )
):
  
atoi_Description := Description(
  function(atoi),
  Summary('convert characters to integers'),
  CallingSequence( noeval(atoi(t)) ),
  Parameters( ['t', string] ),
  Returns( integer ),
  Synopsis( 'The parameter t should be a string value formed over
the symbols 0..9 and the period symbol (.).  This function
returns an integer value equal to trunc(tt) where tt is the
integer value of t.' ),
  Examples( 'atoi(''3993'')', 'atoi(''-3.9'')', 'type(")' ),
  SeeAlso( trunc, sprintf )
):


assert_Description := Description(
  function( assert ),
  Summary('test that an assertion is true'),
  CallingSequence( noeval(assert(cond)) ),
  Parameters( ['cond', boolean, 'a condition to be tested'] ),
  Returns( NULL ),
  Synopsis( 'This function evaluates its argument, which is
expected to be true or false.
If it evaluates to true, it does nothing.
If it evaluates to false it produces an "assertion failed" error.
The first argument of the error is the unevaluated expression that
evaluated to false.
It is the easy to write assertions which upon failure will
automatically produce meaningful errors.' ),
  Examples( Fake( 'assert(1=2);', 'Error, 1 = 2, assertion failed'),
	'Probab := 1.001',
	'e := [ traperror(assert( Probab >=0 and Probab <= 1))]',
	'length(e)', 'e[1]', Unassign('Probab','e') ),
  SeeAlso( error, traperror, 'lasterror', warning ) 
):

warning_Description := Description(
  function( warning ),
  Summary('outputs warning string on STDERR'),
  CallingSequence( noeval(warning(txt)) ),
  Parameters( ['txt', string, 'the warning message to be printed'] ),
  Returns( NULL ),
  Synopsis( 'This function outputs a warning message on the error stream.'),
  Examples( Fake('warning(''This is a warning'')',
    'WARNING: This is a warning')),
  SeeAlso( error, traperror, 'lasterror' ) 
):




assign_Description := Description(
  function( assign ),
  Summary('assign a variable as a function call'),
  CallingSequence( noeval(assign(a, v)) ),
  Parameters( ['a', name], ['v', anything] ),
  Returns( NULL ),
  Synopsis( 'This function assigns the value v to the name a.  The 
assign function ignores the built-in scoping rules.  Therefore,
an assign call inside of a procedure persists after it is
finished executing.  A variable name can not be assigned a value
from within a procedure if a global variable of the same name has
already been assigned a value.' ),
  Examples( 'z := proc() assign(t, 100); end:',
	   'z()', 't', Unassign('t','z') ),
  SeeAlso( assigned, names, parse, symbol, eval )
):

names_Description := Description(
  function( names ),
  Summary('find all assigned names'),
  CallingSequence( noeval(names(typ)) ),
  Parameters( ['typ', {type,'''assigned'''}] ),
  Returns( 'an expression sequence' ),
  Synopsis( 'When no arguments are specified (or with "anything" as
a typ), the names function returns all names, assigned or unassigned.
When the argument typ is included, all names which are assigned a value
of type typ are returned.  The special typ value "assigned" will
return only the names which are assigned.  Be careful when using
the all the names, that some names like break, next etc. may produce
very unexpected results when evaluated.'),
  Examples( 'names(numeric)' ),
  SeeAlso( assigned, types )
):

type_Description := Description(
  function( type ),
  Summary('type testing'),
  CallingSequence( noeval(type(exp)), noeval(type(exp, typeeval)) ),
  Parameters( 	['exp', anything, 'an expression'], 
		['typeeval', 'any type'] ),
  Returns( {boolean,type} ),
  Synopsis( 'The type function with two arguments returns
true if the type of evaluated exp is typeeval.  Otherwise,
it returns false.  With a single argument, it returns the
type of expression exp.'
 ),
  Examples( 'type(a, anything)', 'type(5, integer)', 'type(''hello'', string)',
	    'type(''abc'')' ),
  SeeAlso( [ types, 'This gives a full description of the valid types and
their compositions'] )
):

copy_Description := Description(
  function( copy ),
  Summary( 'copy a modifiable data structure (at a desired depth)' ),
  CallingSequence( noeval(copy(x)), noeval(copy(x,depth)) ),
  Parameters( ['x', anything, 'the structure/object to copy'],
	[depth,posint,'optional depth of copying'] ),
  Returns( 'type(x)' ),
  Synopsis( 'This function returns an exact copy of any object it is passed.
This makes sense when we copy a modifiable object (strings, data structures,
lists, etc.) which we want to modify and we want to preserve the original
in its unmodified state.
With a second argument, the copying will happen only for the given number
of levels.  Without a second argument is like using copy(x,infinity).' ),
  Examples( 'a := [1,2,[3,4]]', 'a1 := copy(a,1)', 'a2 := copy(a)',
	    'a1[1] := 5', 'a1[3,1] := 77', 'a','a1','a2', Unassign( 'a','a1','a2') )
):

length_Description := Description(
  function( length ),
  Summary('length of an object'),
  CallingSequence( noeval(length( obj )) ),
  Parameters( [ 'obj', { string, list, array, set }, 'any object'] ),
  Returns( {0, posint} ),
  Synopsis( 'Returns the length of the given object obj.' ),
  Examples( 'length('''')', 'length({1,2,{a,b,c}})', 'length([1,2,3,4])', 
	    'length(''length'')' ),
  SeeAlso( length, size, Class, CreateArray, assemble, disassemble )
):

sign_Description := Description(
  function( sign ),
  Summary('sign (-1,0,1) of a number or list of numbers'),
  CallingSequence( noeval(sign( val )) ),
  Parameters( [ 'val', {list,numeric}, 'any value or list of values'] ),
  Returns( {-1,0,1} ),
  Synopsis( 'Returns -1 (if val<0), 0 (if val=0) or 1 (if obj>0).
It also maps itself onto lists (and hence matrices).' ),
  Examples( 'sign(-5)', 'sign( [-1,2,-3,4,0] )' ),
  SeeAlso( If, zip, max, min )
):

size_Description := Description(
  function( size ),
  Summary('number of words used by the entire object'),
  CallingSequence( noeval(size( obj )) ),
  Parameters( [ 'obj', anything, 'any object'] ),
  Returns( {0, posint} ),
  Synopsis( 'Returns the total number of words used by the representation
of the obj in memory.
This is the number of words, which depending on the hardware will be 32 or
64 bits words.  See version() for this information.
This should be used mostly for comparative purposes, when two alternatives
for representing some information have to be evaluated.
Size will not count the name of the Class for data structure objects,
under the assumption that this name is defined only once and used
too many times.
Other objects, even if used repeatedly will be counted entirely.' ),
  Examples( 'size('''')', 'size({1,2,{a,b,c}})', 'size([1,2,3,4])', 
	    'size([1.2,2.2,3.2,4.2])' ),
  SeeAlso( length, size, version, Class, CreateArray, assemble, disassemble )
):

op_Description := Description(
  function( op ),
  Summary('pick up operands of an expression'),
  CallingSequence( noeval(op(obj)), noeval(op(i, obj)), 
		   noeval(op(i..j, obj)) ),
  Parameters( [ 'obj', {set, list, array, structure, range, equal}, 'an object with parts'],
	      	[ 'i' , posint ], 
		['j', posint] ),
  Returns( 'An expression sequence with the components of the object' ),
  Synopsis( 'The op(obj) function strips off the outer-most square
brackets [,] (list, array, matrix) or outer-most braces {,} (set).
It returns an expression sequence with the components.  One use of
op is to change, for example, a list into a set.  E.g. {op(x)}.
 When op is given two arguments, a posint i and an object obj, the
function returns the i^th part of obj.  If a range is given,
it returns all the i^th through j^th parts of obj.' ),
  Examples( 'op([1, [a,b], 4])', 'op({1..2, {4, 5, {7}}})', 
	    'z := var = integer', 'op(1,z)', 'op(2, z)',
	Unassign( 'z' ) ),
  SeeAlso( [selectorfunction, 'select operator a[i]'] )
):

sort_Description := Description(
  function( sort ),
  Summary ('sort a list'),
  CallingSequence( noeval(sort( L )), noeval(sort( L, orderproc)) ),
  Parameters( ['L', list(anything) , 'a list of things to be sorted'], 
		['orderproc', procedure, 'an ordering procedure'] ),
  Returns( list(anything) ),
  Synopsis( 'The sort function can order a list (array) containing
any type of elements as long as these elements are comparable
i.e. the operator <= is applicable and well-defined.
When only supplied a list, sort places the elements in ascending
order and returns a copy of the list.  The ordering it uses is
ascending order and for other data structures it is the same
order that sets use.  In particular, if there are no duplicate
elements in the input list, sorting without an orderproc or
transforming the list into a set have the same effect.
The optional second argument must specify an ordering procedure.
This procedure may have a single argument, in which case it
is understood to return a value on which to order the records,
or may take two arguments, in which case it should return true
or false depending on whether the arguments are in the desired order.
In both cases the arguments will be the entries of the array
to be sorted.  Sort does not destroy/change its argument,
it returns a new array of (sorted) data.  Naturally, sort is
most efficient when called with a single argument.'),
  Examples( 'a := [521, -923, 1293, 521, -3342]', 'sort(a)', 'a',
	'sort(a, x -> -x)', 'neg := proc(a) return(-(abs(a))) end',
	'sort(a, neg)', 'b :=[[z, f], [w, e], [y, d]]', 'sort(b, b->b[2])',
	Unassign( 'a','b','neg') ),
  SeeAlso(set)
):

union_Description := Description( function(union),
  CallingSequence( 'a union b', noeval(union(a,b)) ),
  Parameters( ['a', 'set'], ['b', 'set'] ),
  Returns(set),
  Synopsis( 'Computes the union of two sets, that is a set
which has all the elements of a and b.  Repeated elements
are removed from the resulting set.  The value intersect()
is understood to be the entire universe, and hence unions
including intersect() will simply return this term.
In its functional form, any arbitrary number of sets can be unioned.
In particular, union(a) = a, and union() = {}.' ),
  Examples( '{1,2,3} union {2,3,4}', '{1,2,3} union {}',
	    '{1,2,3} union intersect()' ),
  SeeAlso( intersect, minus, member, subset )
  ):


subset_Description := Description(
  function( subset ),
  CallingSequence( noeval(subset(a, b)) ),
  Parameters( ['a', set], ['b', set] ),
  Returns( boolean ),
  Synopsis( 'The subset function returns true if and only if
every element in set a is in set b.' ),
  Examples( 'subset({1,2,3}, {1,2,3,4})' ),
  SeeAlso( union, intersect, member, minus )
):

member_Description := Description(
  function(member),
  CallingSequence( noeval(member(a, b)) ),
  Parameters(
	['a', anything, 'element to be tested for membership in set or list'], 
	['b', {set, list}, ' a set or list '] ),
  Returns( boolean ),
  Synopsis( 'The member function returns true iff element a is
in the set/list b' ),
  Examples( 'member(5, [1,2,5,7])' ),
  SeeAlso( union, subset, intersect, minus, table,
	SearchArray, SearchOrderedArray )
):

ApproxSearchString_Description := Description(
  function( ApproxSearchString ),
  CallingSequence( noeval(ApproxSearchString(pat, txt, tol)) ),
  Parameters( ['pat', string], ['txt', string], ['tol', '{0, posint}'] ),
  Returns( {posint, -1} ),
  Synopsis( 'The tolerance tol specifies how many mismatches
are allowed between the pattern pat and the body of text txt.
If pat is found in txt (within tol mismatches), the offset in
txt is returned.  Otherwise, -1 is returned.
Note, spaces count as mismatches and case differences do not
count as mismatches.'),
  Examples( 'txt := ''AAAAAAAAAHeLLoBBBBB''',
	'j := ApproxSearchString(''hallo'', txt, 1)',
	'j+txt',
	'ApproxSearchString(''nothing'', ''N.O.T.H.I.N.G.'', 4)',
	Hide( 'txt:=noeval(txt)'), Hide( 'j:=noeval(j)') ),
  SeeAlso_SearchString
):

HammingSearchString_Description := Description(
  function( HammingSearchString ),
  CallingSequence( noeval(HammingSearchString(pat, txt, tol)) ),
  Parameters( ['pat', string], ['txt', string], ['tol', '{0, posint}'] ),
  Returns( {posint, -1} ),
  Synopsis( 'This function is almost identical to ApproxSearchString.
The only difference is that insertions and deletions are not allowed.'),
  Examples( 'txt := ''AAAAAAAAAHeLLoBBBBB''',
	'j := HammingSearchString(''hallo'', txt, 1)',
	'j+txt',
	'HammingSearchString(''aahllo'', txt, 1)',
	Hide( 'txt:=noeval(txt)'), Hide( 'j:=noeval(j)') ),
  SeeAlso_SearchString
):

BestSearchString_Description := Description(
  function( BestSearchString ),
  CallingSequence( noeval(BestSearchString(pat, text)) ),
  Parameters( ['pat', string], ['txt', string] ),
  Returns( {0, posint} ),
  Synopsis( 
'The BestSearchString function returns the best match of pat in the
body of text txt.  If no match is found, it takes the first match
(index 0).' ),
  Examples( 'BestSearchString(''CYIQNCPRG'', ''PPATBCYTQNCPLGFPTTSPS'')',
	    'BestSearchString(''CYIQNCPRG'', ''XXXXXXXXXXXXXXXXX'')' ),
  SeeAlso_SearchString
):

SearchMultipleString_Description := Description(
  function( SearchMultipleString ),
  Summary( 'search several sequential patterns in a string' ),
  CallingSequence( noeval(SearchMultipleString(pat1, pat2 , '...', text)) ),
  Parameters( ['pat_i', string], ['txt', string] ),
  Returns( list(integer) ),
  Synopsis( 
'The SearchMultipleString function returns a list with the offsets of
all the matches of each of the patterns given as arguments.
This is very useful when one wants to search for a portion of
a string enclosed in some particular context.
The individual patterns are matched as case insensitive.
All the patterns have to match, in a non-overlapping way and in
the given order.
If there is no match of all the patterns, the function returns
an empty list.' ),
  Examples(
    'SearchMultipleString( ''('', ''a'', '')'', ''(),(bbb), (...a...)'' )' ),
  SeeAlso_SearchString
):

SearchOrderedArray_Description := Description(
  function( SearchOrderedArray ),
  CallingSequence( noeval(SearchOrderedArray(target, L)) ),
  Parameters( ['target', {string, numeric},'target to be searched for'], 
		['L', {list, array}, 'array or list to be searched in']),
  Returns( {0, posint} ),
  Synopsis( 
'The SearchOrderedArray function returns the first index i such
that L[i] <= target < L[i+1].' ),
  Examples( 'SearchOrderedArray(5, [2, 4, 6, 8, 10])',
	    'SearchOrderedArray(''mike'', [''chantal'', ''gaston'', ''mike'', ''ulrike'', ''xianghong''])',
	    'SearchOrderedArray(5, [10, 8, 6, 4, 2])' ),
  SeeAlso( SearchArray, table, SearchAllArray )
):

SearchArray_Description := Description(
  function( SearchArray ),
  CallingSequence( noeval(SearchArray(t, A)) ),
  Parameters( ['t', {string, numeric}], ['A', array] ),
  Returns( {0, posint} ),
  Synopsis( 
'The function SearchArray returns the index of an element in an
array if it is a member of the array.  Otherwise it returns 0.'
),
  Examples( 
'SearchArray(5, [1, 2, 7, 5, 8])',
'SearchArray(''hi'', [''hello'', ''hallo'', ''hey'', ''hoi''])' ),
  SeeAlso( SearchOrderedArray, table, SearchAllArray )
):

SearchAllArray_Description := Description(
  function( SearchAllArray ),
  CallingSequence( noeval(SearchAllArray(t, A)) ),
  Parameters( ['t', anything], ['A', array] ),
  Returns( array ),
  Synopsis( 
'The function SearchAllArray returns the array of indices of an
element in an array if it is a member of the array.  Otherwise it returns
an empty list.'
),
  Examples( 
'SearchAllArray(5, [1, 2, 7, 5, 8, 5, 7, 5])',
'SearchAllArray(''hi'', [''hello'', ''hallo'', ''hey'', ''hoi''])' ),
  SeeAlso( SearchArray, SearchOrderedArray, table )
):

SearchDb_Description := Description(
  function( SearchDb ),
  CallingSequence( noeval(SearchDb( pat_1..pat_k )) ),
  Parameters( ['pat_i', {string, set(string)}] ),
  Returns( 'an Entry structure' ),
  Synopsis( 
'The SearchDb function searches the sequence
database currently assigned to system variable  DB.  When
pat_i consists of a set of strings, the function
returns the logical OR of the results (all entries containing at
least one of the elements in the set pat_i).  The comma symbol
represents the logical  AND of the arguments.  In this case,
SearchDb returns only those entries that contain all such patterns.'
),
  Examples( FakeReadDb,
	'SearchDb(''platypus'')',
	'SearchDb(''alpha-lactalbumin'')',
	'SearchDb(''platypus'', ''alpha-lactalbumin'')',
	'SearchDb(''alpha-lactalbumin'', {''platypus'', ''panda''})' ),
  SeeAlso( PatEntry, SearchSeqDb, SearchTag, 'DB', SearchID, SearchAC,	
	Species_Entry )
):

SearchID_Description := Description(
  function( SearchID ),
  CallingSequence( noeval(SearchID( pat )) ),
  Parameters( ['pat', string ] ),
  Synopsis( 'The SearchID function searches the sequence database
currently assigned to system variable  DB.  It returns an entry
data structure which contains at most one exact match of the given
argument, pat, with the ID field of the entry.  If no match can
be found it returns an empty data structure.'),
  Examples( FakeReadDb,
	    'SearchID(CY2_RHOVI)', 'SearchID(ZZZZ)' ),
  SeeAlso( SearchSeqDb, SearchTag, 'DB', SearchAC, Species_Entry )
):

SearchAC_Description := Description(
  function( SearchAC ),
  Summary( 'find an entry with a given accession number'),
  CallingSequence( noeval(SearchAC( pat ))),
  Parameters( ['pat', string ] ),
  Returns( Entry ),
  Synopsis( 'The SearchAC function searches the sequence database
currently assigned to system variable  DB.  It returns an entry
data structure which contains at most one exact match of the given
argument, pat, with the AC field of the entry.  If no match can
be found it returns NULL.'),
  Examples( FakeReadDb,
	    'SearchAC(''Q62671;'')', 'SearchAC(ZZZZ)' ),
  SeeAlso( SearchID, SearchSeqDb, SearchTag, 'DB' )
):



SearchTag_Description := Description(
  function( SearchTag ),
  CallingSequence( noeval(SearchTag(tg, txt)) ),
  Parameters( 
    ['tg', string, 'an SGML tag without the surrounding angle brackets'], 
    ['txt', string, 'a string that is searched for in the field defined by tg'] ),
  Returns( string ),
  Synopsis(
'The  SearchTag function extracts the information surrounded
by SGML tag tg in the body of txt text.  If tg is not found in
txt, the empty  string is returned.' ),
Examples('SearchTag(''AC'', ''<ID>ABL1_CAEEL</ID><AC>P03949;</AC>'')' ),
  SeeAlso( SearchDb, SearchID, SearchAC, Species_Entry )
):

CaseSearchString_Description := Description(
  function( CaseSearchString ),
  Summary( 'case sensitive exact string searching' ),
  CallingSequence( noeval(CaseSearchString(pat, txt)) ),
  Parameters( ['pat', string], ['txt', string] ),
  Returns( {-1, 0, posint} ),
  Synopsis( 
'This returns the offset before the character where
pat matches with txt.  If pat does not match txt, -1 is returned.'
),
  Examples( 'CaseSearchString(''here'', ''It is in here'');', 
	    'CaseSearchString(''it'', ''It is in here'');' ),
  SeeAlso_SearchString
):

SearchString_Description := Description(
  function( SearchString ),
  Summary( 'case insensitive exact string searching' ),
  CallingSequence( noeval(SearchString(pat, txt)) ),
  Parameters( ['pat', string, 'a pattern that is sought'], 
		['txt', string, 'a text which is searched'] ),
  Returns( {-1, 0, posint} ),
  Synopsis(
'This returns the offset before the character where
pat matches with txt.  If pat does not match txt, -1 is returned.
This function is case insensitive.'
 ),
  Examples( 'SearchString(''HerE'', ''It is in hERe'')',
	    'SearchString(''where'', ''wear am i'')' ),
  SeeAlso_SearchString
):

MatchRegex_Description := Description(
  function( MatchRegex ),
  Summary( 'matches a regex in a string' ),
  CallingSequence( noeval(MatchRegex( pat, txt)) ),
  Parameters( ['pat', string, 'a regex pattern to be matched'],
              ['txt', string, 'a text which is searched'] ),
  Returns( list(string) ),
  Synopsis('This function matches a regex pattern string in the POSIX Extended 
Regular Expression syntax in a query string. The matching is case sensitive.
If the pattern cannot be matched, the empty list is returned.'),
  Examples( 'MatchRegex(''^a(b|c*)e'', ''accceb'')',
            'MatchRegex(''([a-c]*)de(a.*)'', ''xacccdeabbb'')',
            'MatchRegex(''[A-D]a'', ''acccda'')'),
  SeeAlso_SearchString 
):


SearchDelim_Description := Description(
  function( SearchDelim ),
  Summary( 'break up a string at each occurrence of a delimiter' ),
  CallingSequence( noeval(SearchDelim(delim, txt)) ),
  Parameters(
    ['delim', string, 'a pattern that delimits portions of a string'], 
    ['txt', string, 'the text to be split'] ),
  Returns( list(string) ),
  Synopsis(
'SearchDelim returns a list of strings,
where each string in the list is one of the parts of
the txt delimited by occurrences of delim.
SearchDelim is ideal to break up a string which contains
many lines separated by newlines.
If the string after the last occurrence of delim is empty,
it is not added to the list.
Delimiting with an empty string does not make sense and it
is not allowed.'
 ),
  Examples( 'SearchDelim(''a'', ''abracadabra'')',
	    'SearchDelim(''\\n'', ''file1\\nfile2\\nfile3\\n'')' ),
  SeeAlso( op(SeeAlso_SearchString), SplitLines, Lines )
):

DrawGraph_Description := Description(
  function(DrawGraph),
  Summary('draw a graph in two dimensions'),
  CallingSequence( noeval(DrawGraph(G)), noeval(DrawGraph(G,modif)) ),
  Parameters( 
    [G,Graph,'an input Graph'],
    [modif,{string,symbol=anything}, '(optional) modifiers for the drawing']),
  Returns( NULL ),
  Synopsis( 
'DrawGraph uses the plot facility to display a Graph in two dimensions.
The first argument, G, should be a Graph data structure. The positioning 
of the nodes and other properties of appearance depend on the optional 
arguments:'),
'',
Paragraph(-2, 'Mode of node positioning for NBody problem:'),
Paragraph(-13, '  <default>  equal'),
Paragraph(-13, '  equal      All the edges have an equal initial 
distance and variance'),
Paragraph(-13, '  distance   The Edges'' labels correspond to distances 
between the adjacent nodes. The variance of the distances are assumed 
to be equal to the distance. Edges having a non-positive label are ignored
for the fitting.'),
Paragraph(-13, '  weight     The Edges'' labels correspond to weights or 
scores between the adjacent nodes. They are converted to distances by
taking the inverse of the weights. Variances are assumed to be equal to 
the distance. Edges having a non-positive labels are ignored for the 
fitting.'),
Paragraph(-13, '  procedure  A procedure Edge -> [dist, var] that assigns
a distance and a variance to an edge.'),
'',
Paragraph(-2, 'Edge drawing and labeling:'),
Paragraph(-25, '  <default>              unlabeled'),
Paragraph(-25, '  EdgeDrawing=unlabeled  Edges are drawn without any label'),
Paragraph(-25, '  EdgeDrawing=labeled    The label of each edge is drawn
centered on the line and in the same color than the edge.'),
Paragraph(-25, '  EdgeDrawing=<proc>     A procedure (x1,y1,x2,y2,label,ts,col) 
-> list( drawing commands ). x1,y1,x2,y2 are the starting and end points of 
the edge, label is its label, ts the desired textsize and col the color.'),
'',
Paragraph(-2, 'Node drawing:'),
Paragraph(-22, '  <default>           Nodes are represented with a circle
and the node description'),
Paragraph(-22, '  NodeDrawing=<proc>  A procedure (x,y,label,ts,col) -> 
list( drawing commands ), where the node with label ''label'' is centered 
at (x,y). ts is the desired textsize and col the color.'),
'',
Paragraph(-2, 'Size of Text:'),
Paragraph(-20, '  TextSize=<points>  Set point-size for all text'),
'',
Paragraph(-2, 'Nodes and edges can be colored using the optional argument, 
which takes a list of arguments of the following form:
Color( colorname, obj1, obj2, ... ).  The objects are either Nodes(),
Edges() or Edge() data structures.  This means that those edges or nodes
will be colored with colorname.
The valid names for colorname are defined in lib/Color.
The output is directed according to plotsetup.' ),
  SeeAlso( op(SeeAlso_Plot), string_RGB )
):

DrawDistribution_Description := Description(
  function( DrawDistribution ),
  CallingSequence( noeval(DrawDistribution(sample)) ),
  Parameters( ['sample', array([numeric, numeric]),'[mean,variance] values'],
	['',anything,'(optional) see ?PlotArguments'] ),
  Returns( NULL ),
  Synopsis(
'Draws a distribution curve as a superposition of normal distributions
based on [mu,sigma^2] values.  Each entry in the array sample is
interpreted as one distribution given by the pair [average,variance].
The results are usually stored in a file as with DrawPlot.
They can be seen with ViewPlot().'),
  Examples(
Fake( 'DrawDistribution( [ [0,1], [10,1], [5,10] ] );  ViewPlot()', '' )),
  SeeAlso_Plot
):

DrawDotplot_Description := Description(
  function( DrawDotplot ),
  CallingSequence( noeval(DrawDotplot(data, legend)) ),
  Parameters( ['data', {array([numeric, numeric]),
	list(array([numeric, numeric]))}], ['legend', string] ),
  Returns( NULL ),
  Synopsis( 
'Plots data points as dots (circle, crosses, squares, triangles).' ),
  Examples( ),
  SeeAlso_Plot
):

ViewPlot_Description := Description(
  function(ViewPlot ),
  Summary( 'run a viewer on a plot just created' ),
  CallingSequence( noeval(ViewPlot()) ),
  Returns( NULL ),
  Synopsis( 'Start ghostview showing the current output of DrawPlot() or
most other plotting commands, in the proper orientation.' ),
  SeeAlso_Plot
):

DrawPlot_Description := Description(
  function(DrawPlot ),
  Summary( 'produce a plot/drawing in a file'),
  CallingSequence( noeval(DrawPlot(p,lo..hi)),
	noeval( DrawPlot(numlist)),
	noeval( DrawPlot(pairlist)),
	noeval( DrawPlot(objlist)),
	noeval( DrawPlot(plotset)),
	noeval( DrawPlot(plotset,lo..hi)) ),
  Parameters( [p,procedure,'a numerical procedure'],
	['lo..hi', numeric..numeric, 'numerical range to plot'],
	[numlist,list(numeric),'a list of values joined by lines, the'],
	['','','values are interpreted as coordinates'],
	['','','(i,y[i])'],
	[pairlist,list([numeric,numeric]),'a list of pairs (x[i],y[i]) joined'],
	['','','by straight lines'],
	[objlist,list(object),'a list of objects (described below)'],
	[plotset,set(plots),'a list of any of the above plots']
),
'',
Paragraph(2,'The format of the objects in objlist is:'),
Table( center, ColAlign('l','l'), Rule,
Row('left aligned text', 'LTEXT(x,y,string,points,angle,color)'),
Row('centered text', 'CTEXT(x,y,string,points,angle,color)'),
Row('right aligned text', 'RTEXT(x,y,string,points,angle,color)'),
Row('line', 'LINE(x1,y1,x2,y2,color,width)'),
Row('closed polygon', 'POLYGON(x1,y1,x2,y2,..., fill,color,width)'),
Row('circle', 'CIRCLE(x,y,radius,fill,color,width)'),
Rule,
Row( 'x,x1,x2,y,y1,..', 'numeric values of coordinates'),
Row( 'points', 'points=<posint>, size in points of the text'),
Row( 'angle', 'angle=<numeric>, angle of the text in degrees' ),
Row( 'color', 'color=[r,g,b], values of red/green/blue within 0..1'),
Row( '', '(color is incompatible with fill)' ),
Row( 'fill', 'fill=<numeric>, fill in color (0-black, 1-white)' ),
Row( '', '(fill is incompatible with color)' ),
Row( 'width', 'width=<numeric>, width of lines in points' ) ),
  Returns( NULL ),
  Synopsis('Plot a set of objects creating PostScript output
which is stored in a file.
The name of the file can be set using Set(plotoutput).
By default it is "temp.ps".
It is assumed that all the objects being drawn are on the same
x and y coordinates, that is all the x and y values are on the same units.
Optional arguments are:' ),
Table( center, ColAlign('l','l'),
  Row( 'keyword', 'description' ), Rule,
  Row( 'proportional', 'causes identical scaling for x and y axis'),
  Row( 'axis', 'forces x and y axes to be drawn' ),
  Row( 'grid', 'forces a grid of lines to be drawn' ),
  Row( 'topmargin=xx', 'xx (user) units of space are added at the top' ),
  Row( 'botmargin=xx', 'xx (user) units of space are added at the bottom' ),
  Row( 'leftmargin=xx', 'xx (user) units of space are added as left margin' ),
  Row( 'rightmargin=xx', 'xx (user) units of space are added as right margin' )
  ),
'',
  SeeAlso_Plot
):


#StopOverlayPlot_Description := Description(
#  function(StopOverlayPlot ),
#  CallingSequence( ),
#  Parameters( ),
#  Returns( ),
#  Synopsis( ),
#  Examples( ),
#  SeeAlso_Plot
#):

ExpFit_Description := Description(
  function(ExpFit ),
  Summary('Least squares exponential fit: y[i] ~ a + b * exp(c*x[i])' ),
  CallingSequence(noeval(ExpFit(y,x)) ),
  Parameters(['x',array(numeric),'dependent variable'],
	['y',array(numeric),'independent variable'] ),
  Returns('[a,b,c,sumsq]'),
  Synopsis( 'Compute a least squares fit of the type:' ),
  Paragraph(10, 'y[i] ~ a + b * exp(c*x[i])' ),
  Paragraph( -2, '  where a,b and c are the parameters of the approximation
and sumsq is the sum of the squares of the errors of
the approximation.' ),
  Examples( 'x := [1,2,3,4,5]',
	'y := [0.49, 1.02, 2.1, 4.01, 7.8]',
	'ExpFit(y,x)',
	Hide( 'x := noeval(x); y := noeval(y)' ) ),
  SeeAlso(ExpFit2, LinearRegression, Stat )
):

ExpFit2_Description := Description(
  function(ExpFit2 ),
  Summary('Least squares exponential fit: y[i] ~ a * exp(b*x[i])' ),
  CallingSequence(noeval(ExpFit2(y,x)) ),
  Parameters(	[y,array(numeric),'dependent variable'],
		[x,array(numeric),'independent variable'] ),
  Returns('[a, b, sumsq]' ),
  Synopsis('Compute the least squares fit of the type
y[i] ~ a * exp(b * x[i]).  sumsq is the sum of squares of the
approximation errors.' ),
  Examples( 'x := [1,2,3,4,5]',
	'y := [0.49, 1.02, 2.1, 4.01, 7.8]',
	'ExpFit2(y,x)',
	Hide( 'x := noeval(x); y := noeval(y)' ) ),
  SeeAlso(ExpFit, LinearRegression, Stat )
):

TextHead_Description := Description(
  function(TextHead),
  Summary( 'Find the beginning of a string' ),
  CallingSequence(noeval(TextHead(x))),
  Parameters(['x',string,'an arbitrary string'] ),
  Returns(integer),
  Synopsis('Returns the offset to be added to x (on the left) 
to obtain the first character of the string containing x.' ),
  Examples( 'a := ''CYQQSVWPFMDYQQFQGFSWKMPLGNNH''',
	'a1 := a[10..20]',
	'TextHead(a1)',
	'TextHead(a1)+a1', Unassign('a','a1')
 ),
  SeeAlso( GetOffset, TextHandling )
):

DrawHistogram_Description := Description(
  function(DrawHistogram ),
  Summary( 'single or multiple (side by side) histogram' ),
  CallingSequence( noeval( DrawHistogram(data,labels,legend)) ),
  Parameters( 
	[data,array(numeric),'data values, dim n (single histogram) or'],
	[data,matrix(numeric),'data values dim m x n (multiple histograms)'],
	[labels,array,'(optional) dim n labels of each vertical bar(s)'],
	[legend,array,'(optional) dim m description of each histogram'],
	['',anything,'(optional) see ?PlotArguments'] ),
  Returns( NULL ),
  Synopsis( 'DrawHistogram produces a plot of a histogram of
the numerical values given in data.  That is, when "data" is a single
array (dim n), hence a single histogram, each numerical value of data is
represented by a vertical bar with its height proportional to its
data value.
The data values are printed at the top of each bar.
When "data" is a matrix (dim m x n), this means that m values will be
be plotted together; this will be done with proportional vertical
bars, side by side.
To have the m values stacked on top of each other (instead of side by side),
use ?DrawStackedBar.
The results of DrawHistogram are placed in a file, following
the same conventions as DrawPlot.
The plot can be seen with ViewPlot().' ),
  Examples( Fake(
'DrawHistogram( [1,2,3,4,3,2,1] );  ViewPlot()', '' ),
Fake(
'DrawHistogram( [ [ 38, 180, 42 ], [ 42, 40, 48] ],
                 [ ''politicians'', ''darwin users'', ''boxers''],
                 [ ''IQ'', ''shoe size'' ] )', '' ),
Fake( 'ViewPlot()', '' )),
  SeeAlso_Plot
):

DrawPointDistribution_Description := Description(
  function(DrawPointDistribution ),
  Summary( 'histogram of point distribution' ),
  CallingSequence( noeval( DrawPointDistribution(data,Bars)) ),
  Parameters( 
	[data,array(numeric),'data values, not necessarily ordered'],
	[Bars,posint,'(optional) number of ranges, histogram bars'],
	['',anything,'(optional) see ?PlotArguments'] ),
  Returns( NULL ),
  Synopsis( 'DrawPointDistribution produces a plot of a histogram
of the distribution of the given data points.
The data values are sorted and classified in a number of equally
spaced ranges.  For each range a histogram (vertical bar) with the
number of points in that range is drawn.
This produces a discrete approximation of the density distribution
of the points in data.
The data values do not need to be in order.
The number of vertical bars is automatically computed or it can be
set with an optional second argument.
The results of DrawPointDistribution are placed in a file, following
the same conventions as DrawPlot.
The plot can be seen with ViewPlot().' ),
  Examples( Fake(
'DrawPointDistribution( [seq(Rand(Normal),i=1..500)] );  ViewPlot()', '' )),
  SeeAlso_Plot
):

DrawStackedBar_Description := Description(
  function(DrawStackedBar ),
  Summary( 'histogram with multiple values on each bar' ),
  CallingSequence( noeval( DrawStackedBar(data,labels,legend)) ),
  Parameters( 
	[data,matrix(numeric),'data values dim m x n'],
	[labels,array,'(optional) dim n, labels of each vertical bar'],
	[legend,array,'(optional) dim m, description of each stack'],
	['',anything,'(optional) see ?PlotArguments'] ),
  Returns( NULL ),
  Synopsis( 'DrawStackedBar produces a histogram of
the numerical values given in data.
Each vertical bar is composed of several segments, corresponding to
the m lists of values, stacked on top of each other.
The data values are printed inside each stacked segment of the bars.
To have the m values side by side (instead of stacked), use ?DrawHistogram.
The results of DrawStackedBar are placed in a file, following
the same conventions as DrawPlot.
The plot can be seen with ViewPlot().' ),
  Examples( Fake(
'DrawStackedBar( [ [ 38, 180, 42 ], [ 42, 40, 48] ],
                 [ ''politicians'', ''darwin users'', ''boxers''],
                 [ ''IQ'', ''shoe size'' ] )', '' ),
Fake( 'ViewPlot()', '' )),
  SeeAlso_Plot
):


UpdateStat_Description := Description(
  function(UpdateStat ),
  Summary ('Add sample point to Stat Data Structure'),
  CallingSequence(noeval(UpdateStat( name, number )) ),
  Parameters(['name',Stat,'Stat data structure to be updated'],
	['number',numeric, 'value to be added to Stat data structure']),
  Returns(Stat),
  Synopsis('UpdateStat is used to add a sample point to an existing
Stat data structure.' ),
  Examples('BooHoo := Stat(''Stock Market Losses''):', 
		'UpdateStat( BooHoo, 10000 ):',
		'UpdateStat( BooHoo, 30000 ):',
		'BooHoo[Mean]',
		'BooHoo[Number]',
		Print('print(BooHoo)' ) ),
  SeeAlso(OutsideBounds, Stat, LinearRegression, ExpFit, ExpFit2, Counter, CollectStat )
):


OutsideBounds_Description := Description(
  function( OutsideBounds ),
  Summary ('test whether Stats could be the same'),
  CallingSequence(noeval(OutsideBounds( a, b, Confidence=0.975)) ),
  Parameters(['a',Stat,'Stat data structure to be compared'],
	['b',Stat,'second Stat to be compared or'],
	['b',numeric,'value to be compared'],
	['Confidence',positive, 'confidence level (defaults to 0.975)']),
  Returns(boolean),
  Synopsis('OutsideBounds checks whether two univariate statistics
(Stat objects) or one univariate statistics and a value
represent different values with a certain confidence level.
The confidence level is set to 0.975 by default, which gives the
usual 2.5% error on one side, or the 1.96 standard deviations away
the mean for a normal variable.
If the second argument is a single value the test is equivalent
to determining whether the first distribution could have average b
at the given confidence level.
The Confidence level can be changed to any value between 0.5 <= c < 1.'
),
  Examples('st := Stat(''Near 7''):',
    'to 10 do st+Rand(6.5..7.5) od:',
    Print('print(st)'),
    'OutsideBounds(st,7)',
    'OutsideBounds(st,6.5)',
    'OutsideBounds(st,6.5,Confidence=0.999999)' ),
  SeeAlso(UpdateStat, Stat, LinearRegression, ExpFit, StatTest )
):


CollectStat_Description := Description(
  function(CollectStat ),
  Summary ('collect and summarize Stat structures'),
  CallingSequence(noeval(CollectStat( data )) ),
  Parameters([data,anything,'any structure/list/set containing Stat structures']),
  Returns(list(Stat)),
  Synopsis('CollectStat will inspect any list/structure/set and collect
all the Stat structures together.
The Stat structures will be union-ed whenever they have the same description.
This provides an easy way of adding together several simulation results,
which have been obtained in different runs.' ),
  SeeAlso(OutsideBounds, Stat, UpdateStat, 'union', CollectStat )
):


WeightObservations_Description := Description(
  function( WeightObservations ),
  Summary ('Weight data for least squares analysis'),
  CallingSequence(noeval(WeightObservations( A, b, w )) ),
  Parameters( ['A',matrix(numeric),'n rows of m-dimensional data vectors'],
	['b',array(numeric),'n-dimensional vector of dependent data'],
	['w',array(numeric),'n-dimensional vector of weights'] ),
  Returns( '[ AtA:matrix(numeric), btA:array(numeric), btb:numeric ]' ),
  Synopsis(' Prepare matrices and vectors used for least squares
approximations with given weights.
Given the matrix A (dim n x m) and the vector b (dim n)
a least squares solution searches a vector x, such that
Ax ~ b, or |Ax-b| is minimal in some sense.
A weighted least squares problem is equivalent to the above,
except that every error is weighted by a (non-negative) factor w[i].
This is equivalent to minimizing | W*(Ax-b) |
(where W is a diagonal matrix of weights).
In simpler terms, if a weight w[i] is an integer, then
considering the weight is equivalent to having w[i]
equal observations of the data point i.
Setting a weight to 0 is equivalent to deleting the observation.
WeightObservations prepares the matrix AtA = A^t * A, btA = b^t * A
and btb = b^t * b with the given weights.  Usually, least squares
approximating functions require these as input (SvdAnalysis,
SvdBestBasis, etc.)' ),
  Examples( 'A := [[1,2],[3,3],[4,7],[6,2]]',
	'WeightObservations(A,[1,1,2,2],[10,5,2,0])',
	Hide( 'A := noeval(A)' )
 ),
  SeeAlso( SvdAnalysis, SvdBestBasis )
):



SvdBestBasis_Description := Description(
  function( SvdBestBasis),
  Summary ('Least squares by selecting best basis (subset)'),
  CallingSequence(noeval(SvdBestBasis(AtA, btA, btb,
        NData, names, k, svmin, try, startset)) ),
  Parameters(
   [AtA,matrix(m,m),'the product of A^t * A'],
   [btA,vector(m),'the product b^t * A'],
   [btb,numeric,'the norm squared of b, i.e. b*b'],
   [NData,posint,'number of data points (dim A is n x m)'],
   [names,list(string),'names associated with each column of A'],
   [k,posint,'number of variables in the solution'],
   [svmin,numeric,'optional lower limit for using singular values'],
   [try,posint,'optional, trials after a new local minimum'],
   [startset,list(integer),'optional, k column numbers to start'] ),
  Returns(SvdResult),
  Synopsis('SvdBestBasis finds the best set of k variables to
do a least square fit.  For k<=2 this the result is the global
minimum (and the variable "try" is ignored), for k>2 this is a
heuristic, not an exact algorithm, and its precision depends
on how many trials are performed.  The problem of finding the
best set of variables, when done incrementally, one variable
at a time, is called Stepwise regression.  The results of
SvdBestBasis are generally much better than those obtained by
stepwise regression.' ),
  Paragraph(-2,'The problem is formally defined as follows:
Given a matrix of A (dim n x m) and a vector b (dim n),
we want to find a vector x (dim m)  such that Ax ~ b,
where x has k non-zero components and m-k zero components.
This approximation is in the least squares sense,
i.e. |Ax-b|^2 is minimum.' ),
  Paragraph(-2,'The output is a SvdResult data structure.
The global variable SvdGoodBases is assigned a list of
SvdResult data structures for all the other local minima
that are found.
The global variable SvdGoodPerms is assigned a list of
the permutations of the variables which gave the good bases
in SvdGoodBases.
SvdBestBasis prints information as it computes.
The amount of information printed can be regulated with printlevel.' ),
  Paragraph(-2,'svmin is an optional positive numeric value.
All singular values less than svmin will not be used.
Making svmin=0, all singular values are used, and this is
equivalent to pure least squares.  The selection of singular
values is used for the final computation of the SvdResult,
not for the computation of the best basis.' ),
  Paragraph(-2,'try is an optional integer.
It indicates the number of trials will be done after a new
local minima is found before stopping.
If omitted, 15 trials are done after the lowest norm has been found.' ),
  Paragraph(-2,'startset is an optional list of k integers.
SvdBestBasis will start its search for an optimal from this set.
If try is greater than 1, then other trials, starting at
random sets, will also be tried.' ),
  SeeAlso(Stat, ExpFit, SvdAnalysis, LSBestSum, LSBestDelete, LSBestSumDelete,
        SvdReduceGood, SvdResult )
):


SvdResult_Description := Description(
  structure( SvdResult ),
  Summary( 'results of a least squares approximation, Ax=b' ),
  CallingSequence( noeval( SvdResult(Norm2Err, SensitivityAnalysis,
	SingularValuesUsed, SingularValuesDiscarded, Norm2Indep,
	MinNorm2Err, SolutionVector, NData ) )),
  Selectors(
	[Norm2Err,numeric,'norm of approximation |Ax-b|^2'],
	[SensitivityAnalysis,list(list),'results with sensitivity analysis'],
	[SingularValuesUsed,list(numeric),'singular values used'],
	[SingularValuesDiscarded,list(numeric),'singular values discarded'],
	[Norm2Indep,numeric,'norm of independent variables, |b|^2'],
	[MinNorm2Err,numeric,'|Ax-b|^2 is all sv were used'],
	[SolutionVector,list(numeric),'least squares solution, x'],
	[NData,posint,'number of data points (dim A is n x m)'] ),
  Synopsis('An SvdResult holds the result of a linear least squares
approximation.
Such an approximation is normally generated by SvdAnalysis or SvdBestBasis.
The list with the sensitivity results has 4 entries per variable.
These are the name of the variable, the result value
(the x[i] value), an estimate of the standard deviation and
the amount by which |Ax-b|^2 will increase if this variable
would not be used.
Two compute this difference, all singular values are used.
This list is sorted in decreasing order of the last argument.
The list is only produced if the global variable ComputeSensitivity
is not set to false, otherwise it is empty.' ), 
  SeeAlso( SvdAnalysis, SvdResult, SvdBestBasis )
):


LinearRegression_Description := Description(
  function( LinearRegression),
  Summary ('Compute a linear regression'),
  CallingSequence(noeval(LinearRegerssion(y,x1,'...')) ),
  Parameters(['y',array(numeric),'dependent variable'],
		['y',table,'dependent data are values in table'],
		['x1',array(numeric),'independent variable(s)'] ),
  Returns(array(numeric)),
  Synopsis('Computes a linear regression y = a0 + a1*x1 + a2*x2 + ...
by least squares.  The number of arguments is variable,
it should be at least 2.  LinearRegression returns the vector
[a0,a1,a2,...].  The global variable SumSq is set to the
sum of squares of errors in the regression.'),
Paragraph(-2,'Alternatively, if only one argument is provided,
and it is a table, the regression will be made as if the table
values were the dependent variable and the table arguments were
the independent variable(s).  Hence the arguments of the table must be either
numbers or lists of numbers, consistently.'),
  Examples( 
	'LinearRegression( [2.1,3.01,3.9,4.89], [0,1,2,3] )',
	'SumSq' ),
  SeeAlso(Stat, ExpFit, ExpFit2, SvdAnalysis )
):


LinearClassify_Description := Description(
  function( LinearClassify),
  Summary ('Linear form which does pos/neg classification'),
  CallingSequence(noeval(LinearClassify(A,accept,mode,WeightNeg)) ),
  Parameters( [A,matrix(numeric),'an n x m matrix of independent variables'],
	[accept,{procedure,list},'positive/negative determination'],
	[mode,anything,'optional, algorithm selection, defaults to Svd'],
	[WeightNeg,positive,'optional, weight of negatives'] ),
  Returns(LinearClassification),
  Synopsis('Computes a vector X such that the values A[i]*X >= X0 classify
the positive/negatives.
Such a vector is called a linear discriminant in statistics.
A special way of computing such a vector is called the Fisher
linear discriminant.
LinearClassify normally produces results which are much better
than the Fisher linear discriminant.
LinearClassify returns a data structure called LinearClassification
which contains the vector X and the splitting value, called X0,
the weights of positive and negatives,
the score obtained and the worst misclassifications.
The third argument, if present, directs the function to use
a particular method of computation.  The methods are'),

Table( center, ColAlign('l','l'),
Row('mode','description'), Rule,
Row( BestBasis, 'equivalent to BestBasis(10)'),
Row( 'BestBasis(k)', 'Least Squares to 0-1 using SvdBestBasis of size k'),
Row( 'Svd', '(default mode) equivalent to Svd(1e-5)'),
Row( 'Svd(bound)', 'Least Squares to 0-1 using Svd, with svmin=bound'),
Row( 'Svd(First(k))', 'LS to 0-1 using Svd so that k sing values are used' ),
Row( 'CenterMass', 'Direction between the pos/neg center of masses' ),
Row( 'Variance', 'Variance Discrimination of each variable' ),
Row( 'Fisher', 'Fisher linear discriminant' ),
Row( 'Logistic', 'Steepest descent optimization using the logistic function' ),
Row( 'CrossEntropy', 'Steepest descent optimization using cross entropy' ),
Row( 'Best', 'equivalent to Best(10)' ),
Row( 'Best(n)', 'A combination of methods found most effective by' ),
Row( '','experimentation.  n determines the amount of optimization.'),
Row( '<default>', 'Svd(1e-5)' ) ),

Paragraph(-2, ' In practice the best results are obtained with
Best(n).  Svd(1e-12) and CrossEntropy are also very effective.
Once a LinearClassification has been
computed, it can be improved or refined with the functions:' ),

Table( center, ColAlign('l','l'), Row('function', 'description'), Rule,
Row( 'LinearClassification_refine', 'find the center of the min in each dim'),
Row( 'LinearClassification_refine2', 'Svd applied to a hyperswath'),
Row( 'LinearClassification_refine3', 'Minimize in a random direction'),
Row( 'LinearClassification_refine4', 'Svd on progressively smaller swaths') ),

Paragraph( -2, 'Unless you use the Best option, no matter how good
the initial results are, it always pays to do some refinement steps.
In particular refine2 and refine4 give very good refinements.' ),

  Examples( 'A := [[0,3], [8,5], [10,7], [5,5], [7,4], [7,9]]:',
	'lc := LinearClassify( A, [0,1,1,0,1,0] ):',
	Print( 'print(lc)' ),
	Unassign( 'A', 'lc' )
	),
  SeeAlso( Stat, LinearRegression, LinearClassification, SvdAnalysis,
	SvdBestBasis )
):


LinearClassification_Description := Description(
  structure( LinearClassification ),
  Summary( 'results of a linear classification' ),
  CallingSequence( noeval( LinearClassification(X,X0,WeightPos,WeightNeg,
	NumberPos,NumberNeg,WeightedFalses,HighestNeg,LowestPos)) ),
  Parameters(
	[ X,list(numeric), 'solution vector' ],
	[ X0, numeric, 'threshold value' ],
	[ WeightPos, numeric, 'weight of the positives' ],
	[ WeightNeg, numeric, 'weight of the negatives' ],
	[ NumberPos, posint, 'number of positives' ],
	[ NumberNeg, posint, 'number of negatives' ],
	[ WeightedFalses, numeric, 'weighted misclassifications' ],
	[ HighestNeg, list([posint,numeric]), 'highest scoring negatives' ],
	[ LowestPos, list([posint,numeric]), 'lowest scoring positives' ] ),
  Returns( LinearClassification ),
  Synopsis('Data structure which holds the result of a linear classification.
A linear classification is defined by a vector X, such that the internal
product of every data point A[i] with X can be compared against a
threshold and decide whether the data point is a positive or a negative.
I.e. A[i] X < X0 implies a negative and A[i] X >= X0 a positive.' ),
  SeeAlso( LinearClassify )
):


SetRand_Description := Description(
  function( SetRand ),
  CallingSequence( noeval(SetRand(seed)) ),
  Parameters( ['seed', integer] ),
  Returns( NULL ),
  Synopsis( 'Sets the seed of the random number generator.
The sequence of pseudo-random numbers generated depends uniquely
on the seed, i.e. the same seed will generate the same sequence.' ),
  Examples( 'SetRand(123)' ),
  SeeAlso( Rand, SetRandSeed )
):

Mutate_Description := Description(
  function( Mutate),
  Summary( 'randomly mutate an amino acid sequence' ),
  CallingSequence( noeval(Mutate(seq,PAM,DelType)) ),
  Parameters([seq,string,'original amino acid sequence'],
	[PAM,numeric,'desired PAM distance to mutate'],
	[DelType,{'ExpGaps','ZipfGaps'},'optional, model for making gaps'] ),
  Returns( string ),
  Synopsis( 'This function simulates evolution by performing
random mutations in an amino acid sequence.  These random mutations
respond to the PAM distance given.  The mutations will respond to
a mutation matrix at that distance.  If the third argument is given,
the gaps will be inserted, either with an exponential or zipfian
distribution.  If no third parameter is given, no gaps will be
inserted.
Mutate will use the mutation matrices available in logPAM1, which
are normally set by CreateDayMatrices().
If these matrices are created for DNA (only A,C,G and T), then
the function Mutate will mutate a DNA sequence.' ),
  Examples( 'Mutate(CreateString(40,A),100)' ),
  SeeAlso( CreateDayMatrices,
	CreateRandPermutation,Shuffle,CreateRandSeq,Mutate )
):

CreateArray_Description := Description(
  function( CreateArray),
  Summary ('Creates an array of defined length and initialization'),
  CallingSequence( noeval(CreateArray(1..n1, 1..n2, 1..nk)),
			noeval(CreateArray(1..k, z)) ),
  Parameters( ['ni', integer, 'integer dimensions of the array'],
		['k', integer, 'integer dimension of the array'],
		['z', anything, 'initialization value of the array'] ),
  Returns(list),
  Synopsis( 'This function creates a new array of dimension specified by k.
If the last argument to CreateArray is not of type range, this is the
initial value assigned to each element of the array.' ),
  Examples( 'x := CreateArray(1..5, 4)',
		'y := CreateArray(1..2, 1..2, [3,4])',
		Hide(' x := noeval(x); y := noeval(y)')),
  SeeAlso( CreateString )
):

CreateString_Description := Description(
  function( CreateString),
  Summary ('Creates a string of defined length and initialization'),
  CallingSequence( noeval(CreateString(len)),
			noeval(CreateString(len, z)) ),
  Parameters( ['len', {posint,0}, 'integer length of the string'],
	['z', string, 'initialization value of each character of the string'] ),
  Returns(string),
  Synopsis( 'Create a new string of the given length and initialize it,
setting each character to the initialization value (default: blank).'),
  Examples( ' x := CreateString(6)',
		' y := CreateString(10, d)',
		Hide(' x := noeval(x); y := noeval(y)')),
  SeeAlso( CreateArray )
):


CreateRandPermutation_Description := Description(
  function( CreateRandPermutation),
  CallingSequence( noeval(CreateRandPermutation(n)) ),
  Parameters( ['n', posint] ),
  Returns( list(integer) ),
  Synopsis( 'Returns a random permutation of the integers from 1 to n.' ),
  Examples( 'CreateRandPermutation(5)' ),
  SeeAlso( Rand, SetRand, CreateRandSeq, Shuffle, SetRandSeed, Mutate,
	Permutation )
):

CreateRandSeq_Description := Description(
  function( CreateRandSeq ),
  Summary( 'create a random sequence' ),
  CallingSequence( noeval(CreateRandSeq(len, F)) ),
  Parameters( ['len', posint,'sequence length'], 
	      ['F', array(numeric),'character frequencies'] ),
  Returns( string ),
  Synopsis( 'Given a list of frequencies of length 4, this function
creates a random nucleotide sequence of length len.  When given a list of
20 (amino acid) frequencies, it generates a random amino acid sequence. A list
of length 64 or 65 produces a random codon sequence without stop codons.'),
  Examples( 'CreateRandSeq(20, [0.2, 0.3, 0.4, 0.1])' ),
  SeeAlso( Rand, SetRand, SetRandSeed, CreateRandSeq, 
	   Shuffle, CreateRandPermutation )
):

#SmoothData_Description := Description(
#  function( SmoothData ),
#  CallingSequence( ),
#  Parameters( ),
#  Returns( ),
#  Synopsis( ),
#  Examples( ),
#  SeeAlso( )
#):

SetRandSeed_Description := Description(
  function( SetRandSeed ),
  CallingSequence( noeval(SetRandSeed()) ),
  Returns( NULL ),
  Synopsis( 'Initialize the random number generator to produce a sequence
depending on the date, time and process id.  This is normally a guarantee
that different processes end up with different random seeds.
If printlevel is 3 or higher, SetRandSeed will print the value
that it has used for SetRand() so that the same random sequence
can be regenerated.'),
  Examples( 'SetRandSeed()', 'Rand()' ),
  SeeAlso( Rand, SetRand, CreateRandSeq, Shuffle )
):

SeeAlsoRand := SeeAlso( SetRand, Normal_Rand, CreateRandSeq, Shuffle,
	SetRandSeed, Binomial_Rand, Poisson_Rand, Geometric_Rand, Graph_Rand,
	Exponential_Rand, ChiSquare_Rand, GammaDist_Rand, Beta_Rand,
	FDist_Rand, Student_Rand, StatTest, Cumulative, Zscore, Std_Score,
	Multinomial_Rand ):
Rand_Description := Description(
  function( Rand ),
  CallingSequence( noeval(Rand()) ),
  Returns( numeric ),
  Synopsis( 'This function returns a random number uniformly distributed
between 0 and 1.  The random number generator has the seed set by either
the function SetRand or SetRandSeed.
Any class which is completed with the command CompleteClass will have
an automatically generated Rand function, i.e. random objects of the
class can be generated.
The following table describes the possible arguments of Rand and
the object that will be generated.' ),
'',
Table( ColAlign('l','l'), center,
Row( argument, 'random structure' ),
Rule,
Row( Alignment,'random alignment'),
Row( 'array(t,d1,...)', 'array of dimensions d1,... with entries of type t' ),
Row( 'Beta(a,b)', 'Beta distributed number with average a/(a+b)' ),
Row( 'Binomial(n,p)', 'integer binomially distributed, ave n*p, var n*p*(1-p)' ),
Row( 'Multinomial(n,ps)', 'multinominally distributed integers' ),
Row( 'ChiSquare(nu)', 'chi-square distributed number with ave nu, var 2*nu' ),
Row( 'CodingDNA(n)', 'random DNA coding sequence (no stops) with n bases' ),
Row( 'DNA(n)', 'random DNA sequence with n bases.  Uses the global' ),
Row( '', 'vector AF, if suitable'),
Row( Entry, 'a random entry from the database in DB' ),
Row( 'Exponential(a,b)', 'exponentially distributed number with ave a+b, var b^2' ),
Row( 'FDist(nu1,nu2)', 'random F distributed or Variance-ratio number' ),
Row( 'GammaDist(p)', 'random Gamma distributed number with ave p and var p' ),
Row( 'Geometric(p)', 'geometrically distributed integer with ave (1-p)/p' ),
Row( 'Graph(n,m)', 'random graph with n vertices and m edges' ),
Row( integer, 'random integer' ),
Row( '[t1,t2,...]', 'a list with random components of the given types' ),
Row( LongInteger, 'random extended precision integer' ),
Row( MAlignment,'random multiple sequence alignment'),
Row( 'matrix(t)', 'matrix with random dimensions and random entries of type t' ),
Row( 'Normal(a,b)', 'normally distributed variable with ave a and var b' ),
Row( 'MNormal(a,b)', 'multivariate normal with ave vector a and cov matrix b' ),
Row( 'Poisson(m)', 'Poisson distributed integer with average and variance m' ),
Row( Polar, 'complex number in Polar representation' ),
Row( posint, 'random positive integer' ),
Row( 'Protein(n)', 'a random sequence of amino acids of length n' ),
Row( Sequence, 'the sequence of a random entry from the database in DB' ),
Row( 'a..b', 'integers or numbers (depending on type of a,b) in the range' ),
Row( '{a,b,...}', 'a random value from the set' ),
Row( Stat, 'results of univariate statistics' ),
Row( string, 'random (readable) string' ),
Row( 'Student(nu)', 'Student distributed variable with parameter nu' ),
Row( SvdResult, 'results of an Svd least squares approximation' ),
Row( Tree, 'random distance tree' ),
Row( '<type>', 'a random object of this type' )
),

  Examples( 'SetRand(5)', 'Rand()', 'Rand()',
	'Rand(Normal)', 'Rand(Binomial(20,0.2))', 'Rand(Poisson(55))',
	'Rand(Geometric(0.2))', 'Rand(Exponential(1.2,3))' ),
  SeeAlsoRand
):

Normal_Rand_Description := Description(
  function( Normal_Rand ),
  Summary( 'Generate random normally distributed numbers' ),
  CallingSequence( noeval(Rand(Normal)), noeval(Rand(Normal(m,s2))),
	noeval(Normal_Rand()) ),
  Parameters( [m,numeric,'expected value of the variable'],
	[s2,nonnegative,'variance of the variable'] ),
  Returns( numeric ),
  Synopsis( 'This function returns a random number normally
distributed with average 0 and variance 1.  Normal_Rand
uses Rand() which can be seeded by either the function SetRand
or SetRandSeed.  An normal variable with average m and variance
s2 is obtained with the expression sqrt(s2)*Rand(Normal) + m
or with Rand(Normal(m,s2)).' ),
  References( 'Handbook of Mathematical functions, 
Abramowitz and Stegun, 26.1.26 and 26.2'),
  Examples( 'Normal_Rand()', '[Rand(Normal),Rand(Normal)]',
	'Rand(Normal(10,0.001))' ),
  SeeAlsoRand
):

Binomial_Rand_Description := Description(
  function( Binomial_Rand ),
  Summary( 'Generate random binomially distributed integers' ),
  CallingSequence( noeval(Rand(Binomial(n,p))), noeval(Binomial_Rand(n,p)) ),
  Returns( integer ),
  Synopsis( 'This function returns a random integer binomially
distributed with average n*p and variance n*p*(1-p).
An example of a binomial distribution is the number of heads
resulting from tossing n times a biased coin (that will give "heads"
with probability p).  In mathematical terms, the probability
that the outcome is i is binomial(n,i) * p^i * (1-p)^(n-i)
(for 0 <= i <= n).
Binomial_Rand uses Rand() which can be seeded by either the
function SetRand or SetRandSeed.' ),
  References( 'Handbook of Mathematical functions, 
Abramowitz and Stegun, 26.1.20'),
  Examples( 'Rand(Binomial(20,0.3))', 'Rand(Binomial(1000,0.01))' ),
  SeeAlsoRand
):

Multinomial_Rand_Description := Description(
  function( Multinomial_Rand ),
  Summary( 'Generate random multinomially distributed integers' ),
  CallingSequence( noeval(Rand(Multinomial(n,ps))), noeval(Multinomial_Rand(n,ps)) ),
  Parameters(['n',integer,'number of experiments'],['ps',list(numeric),'probabilities']),
  Returns( list(integer) ),
  Synopsis( 'Given k probabilities ps=[p_1,..., p_k], this function returns a list of k 
   random integers multinomially distributed with averages n*p_i, variances n*p_i*(1-p_i) and
   covariances -n*p_i*p_j. The sum of all integers is n.
Multinomial_Rand uses Rand() which can be seeded by either the
function SetRand or SetRandSeed.' ),
  References( 'MB Brown and J Bromberg (1984), The American Statistician'),
  Examples( 'Rand(Multinomial(100,[0.3,0.2,0.5]))', 'Rand(Multinomial(1000,[0.01,0.9,0.09]))' ),
  SeeAlsoRand
):


Poisson_Rand_Description := Description(
  function( Poisson_Rand ),
  Summary( 'Generate random Poisson-distributed integers' ),
  CallingSequence( noeval(Rand(Poisson(m))) ),
  Returns( integer ),
  Synopsis( 'This function returns a random Poisson-distributed
integer with average m and variance m.
The Poisson distribution is the limiting case of the binomial
distribution when n -> infinity and n*p=m remains bounded.
In mathematical terms, the probability that the outcome is i
is exp(-m) * m^i / i! (for 0 <= i).
Poisson_Rand uses Rand() which can be seeded by either the
function SetRand or SetRandSeed.' ),
  References( 'Handbook of Mathematical functions, 
Abramowitz and Stegun, 26.1.22'),
  Examples( 'Rand(Poisson(20))', 'Rand(Poisson(1000))' ),
  SeeAlsoRand
):

Geometric_Rand_Description := Description(
  function( Geometric_Rand ),
  Summary( 'Generate random geometrically distributed integers' ),
  CallingSequence( noeval(Rand(Geometric(p))) ),
  Returns( integer ),
  Synopsis( 'This function returns a random geometrically distributed
integer with average (1-p)/p and variance (1-p)/p^2.
In mathematical terms, the probability that the outcome is i
is p*(1-p)^i (for 0 <= i).
Notice that the distribution starts at 0.
Geometric_Rand uses Rand() which can be seeded by either the
function SetRand or SetRandSeed.' ),
  References( 'Handbook of Mathematical functions, 
Abramowitz and Stegun, 26.1.24'),
  Examples( 'Rand(Geometric(0.3))', 'Rand(Geometric(0.01))' ),
  SeeAlsoRand
):

Exponential_Rand_Description := Description(
  function( Exponential_Rand ),
  Summary( 'Generate random exponentially distributed reals' ),
  CallingSequence( noeval(Rand(Exponential(a,b))) ),
  Returns( numeric ),
  Synopsis( 'This function returns a random exponentially distributed
number with average a+b and variance b^2.
In mathematical terms, the probability that the outcome is x
is exp( -(x-a)/b ) / b.
The first parameter, a, can take any arbitrary value.
The second parameter, b, has to be positive.
Exponential_Rand uses Rand() which can be seeded by either the
function SetRand or SetRandSeed.' ),
  References( 'Handbook of Mathematical functions, 
Abramowitz and Stegun, 26.1.28'),
  Examples( 'Rand(Exponential(0.3,3))' ),
  SeeAlsoRand
):

ChiSquare_Rand_Description := Description(
  function( ChiSquare_Rand ),
  Summary( 'Generate random Chi-square distributed reals' ),
  CallingSequence( noeval(Rand(ChiSquare(nu))) ),
  Parameters( [nu,nonnegative] ),
  Returns( nonnegative ),
  Synopsis( 'This function returns a random chi-square distributed
number with average nu and variance 2*nu.
When nu is an integer, the sum of the squares of nu Normal(0,1)
variables is distributed as ChiSquare(nu).
ChiSquare_Rand uses Rand() which can be seeded by either the
function SetRand or SetRandSeed.' ),
  References( 'Handbook of Mathematical functions, 
Abramowitz and Stegun, 26.4'),
  Examples( 'Rand(ChiSquare(3))', 'Rand(ChiSquare(100))' ),
  SeeAlsoRand
):

GammaDist_Rand_Description := Description(
  function( GammaDist_Rand ),
  Summary( 'Generate random Gamma distributed reals' ),
  CallingSequence( noeval(Rand(GammaDist(p))) ),
  Parameters( [p,nonnegative] ),
  Returns( nonnegative ),
  Synopsis( 'This function returns a random Gamma distributed
number with average p and variance p.
The sum of two Gamma distributed random variables with parameters
p and q is a Gamma distributed variable with parameter p+q.
We have to call this function GammaDist to prevent the collision
with the Gamma function.
GammaDist_Rand uses Rand() which can be seeded by either the
function SetRand or SetRandSeed.' ),
  References( 'Handbook of Mathematical functions, 
Abramowitz and Stegun, 26.1.32'),
  Examples( 'Rand(GammaDist(3))', 'Rand(GammaDist(100))' ),
  SeeAlsoRand
):

Beta_Rand_Description := Description(
  function( Beta_Rand ),
  Summary( 'Generate random Beta distributed reals' ),
  CallingSequence( noeval(Rand(Beta(a,b))) ),
  Parameters( [a,nonnegative], [b,nonnegative] ),
  Returns( nonnegative ),
  Synopsis( 'This function returns a random Beta distributed
number with average a/(a+b) and variance a*b/((a+b)^2*(a+b+1)).
When a and be are integers, the Beta distribution corresponds to
the distribution of the a-th ordered random number (U(0,1)) out
of a+b-1 numbers.
Also, if X1 and X2 are Chi-square distributed numbers with
parameters nu1 and nu2, X1/(X1+X2) is Beta(nu1,nu2) distributed.
Beta_Rand uses Rand() which can be seeded by either the
function SetRand or SetRandSeed.' ),
  References( 'Handbook of Mathematical functions, 
Abramowitz and Stegun, 26.5'),
  Examples( 'Rand(Beta(3,4))', 'Rand(Beta(2,100))' ),
  SeeAlsoRand
):

FDist_Rand_Description := Description(
  function( FDist_Rand ),
  Summary( 'Generate random F-(variance-ratio) distributed reals' ),
  CallingSequence( noeval(Rand(FDist(nu1,nu2))) ),
  Parameters( [nu1,nonnegative], [nu2,nonnegative] ),
  Returns( nonnegative ),
  Synopsis( 'This function returns a random F distributed
or Variance-ratio distributed number with average nu1/(nu2-2).
If X1 and X2 are Chi-square distributed variables with
parameters nu1 and nu2, then X1/X2 is distributed as FDist(nu1,nu2).
This distribution has a non-finite expected value for nu2<=2 and
non-finite variance for nu2<=4.
FDist_Rand uses Rand() which can be seeded by either the
function SetRand or SetRandSeed.' ),
  References( 'Handbook of Mathematical functions, 
Abramowitz and Stegun, 26.6'),
  Examples( 'Rand(FDist(3,1))', 'Rand(FDist(1,100))' ),
  SeeAlsoRand
):

Student_Rand_Description := Description(
  function( Student_Rand ),
  Summary( 'Generate random Student''s-t distributed reals' ),
  CallingSequence( noeval(Rand(Student(nu))) ),
  Parameters( [nu,nonnegative] ),
  Returns( numeric ),
  Synopsis( 'This function returns a random Student''s t distributed
number with average 0 and variance nu/(nu-2).
If X is a Normal(0,1) random variable and X1 is a Chi-square
random variable with parameter nu, X/sqrt(X1/nu) is Student(nu)
distributed.
Student_Rand uses Rand() which can be seeded by either the
function SetRand or SetRandSeed.' ),
  References( 'Handbook of Mathematical functions, 
Abramowitz and Stegun, 26.7'),
  Examples( 'Rand(Student(3))', 'Rand(Student(100))' ),
  SeeAlsoRand
):

erf_Description := Description(
  function( erf ),
  Summary( 'error function - 2/sqrt(Pi)*int( exp(-t^2), t=0..x )' ),
  CallingSequence( noeval(erf(x)) ),
  Parameters( ['x', numeric] ),
  Returns( numeric ),
  Synopsis('This function returns the result of the following expression:'),
Indent(4,MapleFormula('erf(x)=``(2/Pi^(1/2))*int(exp(-t^2),t=0..x)')),
Paragraph( 0, 'The probability of a normally distributed variable
with mean m and variance s^2 been less than x is
1/2+1/2*erf( (x-m)/sqrt(2*s^2) ).' ), 
  References( 'Erdelyi53, Handbook of Mathematical functions,
Abramowitz and Stegun, 7.1' ),
  Examples( 'erf(0)',  'erf(1.96/sqrt(2))', 'erf(3)', 'erf(-2)' ),
  SeeAlso( erfc, erfcinv, Normal_Rand )
):

erfc_Description := Description(
  function( erfc ),
  Summary( 'the complement of the error function' ),
  CallingSequence( noeval(erfc(x)) ),
  Parameters( ['x', numeric] ),
  Returns( numeric ),
  Synopsis( 'This function returns the result of the following expression:' ),
Paragraph(4,'erfc(x) = 1 - erf(x)'),
Indent(4,MapleFormula('erfc(x)=``(2/Pi^(1/2))*int(exp(-t^2),t=x..infinity)')),
  References( 'Erdelyi53' ),
  Examples( 'erfc(3)', 'erfc(1.96/sqrt(2))' ),
  SeeAlso( erf, erfcinv )
):

erfcinv_Description := Description(
  function( erfcinv ),
  CallingSequence( noeval(erfcinv(x)) ),
  Parameters( ['x', numeric, 'a number'] ),
  Returns( numeric ),
  Synopsis('This function returns the inverse of  erfc(x), that is,
the value of y such that: 2/ sqrt(Pi) integral from y 
to infinity exp(-t^2) dt = x.' ),
  Examples( Fake('erfcinv(3)', 'Error, 3 is an invalid argument for erfcinv'),
		'erfcinv(0.1)', 'sqrt(2)*erfcinv(0.05)' ),
  SeeAlso( erf, erfc )
):


Cumulative:
CumulativeNames := {}:
for z in names(procedure) do
    if length(z) > 14 and z[-14..-1] = '_CumulativeStd' then
	CumulativeNames := CumulativeNames union {z[1..-15]}
    elif length(z) > 11 and z[-11..-1] = '_Cumulative' then
	CumulativeNames := CumulativeNames union {z[1..-12]} fi od:
z := noeval(z):
CumulativeNames := Paragraph( -2, sprintf( 'The system knows how to compute the
Cumulative distributions of: %a.', CumulativeNames )):
Cumulative_Description := Description(
  function( Cumulative ),
  Summary( 'compute the cumulative probability for x' ),
  CallingSequence( noeval(Cumulative(distr,x)) ),
  Parameters( [distr,anything,'description of a probability distribution'],
	['x', numeric, 'a number'] ),
  Returns( numeric ),
  Synopsis('This function computes the probability that a random
distributed variable with distribution "distr" has a value less or equal
to x.
This is normally called the cumulative probability distribution.
The result is between 0 and 1 inclusive.
The format describing the distribution is the same as the one used by Rand.
If x is continuously distributed, with density f(x), then
the cumulative is:' ),
Indent(4,MapleFormula('Cumulative(f,x)=int(f(t),t=-infinity..x)')),
  Paragraph( -2, '  If the distribution is a discrete distribution,
say over the integers, then the cumulative is defined as:' ),
Indent(4,MapleFormula('Cumulative(f,x)=f(x)/2+sum(f(t),t=-infinity..x-1)')),
  CumulativeNames,
  Paragraph( -2, '  If the arguments are such that the value returned
is too close to 1 or too close to 0 for accurate representation,
consider using CumulativeStd which returns its result in
equivalent standard deviations and will not suffer from precision problems.
The relations between the Cumulative(c) and the CumulativeStd(s)
are the following:' ),
Indent(4,MapleFormula('c = 1/2*``(1+erf(s/`2`^(1/2)))')), '',
Indent(4,MapleFormula('c = 1-1/2*erfc(s/`2`^(1/2))')), '',
Indent(4,MapleFormula('c = 1/2*erfc(-s/`2`^(1/2))')),
  References( 'Erdelyi53, Handbook of Mathematical functions,
Abramowitz and Stegun, 7.1' ),
  Examples( 'Cumulative( Binomial(10,0.5), 5 )',
	'Cumulative( U(0,10), 7.5 )' ),
  SeeAlso( Cumulative, CumulativeStd, Rand, StatTest, Std_Score,
	OutsideBounds, ProbBallsBoxes, ProbCloseMatches )
):


CumulativeStd_Description := Description(
  function( CumulativeStd ),
  Summary( 'cumulative probability in standard deviations' ),
  CallingSequence( noeval(CumulativeStd(distr,x)) ),
  Parameters( [distr,anything,'description of a probability distribution'],
	['x', numeric, 'a number'] ),
  Returns( numeric ),
  Synopsis('This function computes the probability that a random
distributed variable with distribution "distr" has a value less or equal
to x.
This is normally called the cumulative probability distribution.
The result is returned in standard deviations of an equivalent Normal(0,1)
distribution.
This is useful when the result is exponentially close to 1 (or to 0)
and returning the probability would cause large truncation errors.
The format describing the distribution is the same as the one used by Rand.
If x is continuously distributed, with density f(x), then
the cumulative is:' ),
Indent(4,MapleFormula('Cumulative(f,x)=int(f(t),t=-infinity..x)')),
  CumulativeNames,
  Paragraph( -2, '  If the distribution is a discrete distribution,
say over the integer, then the cumulative is defined as:' ),
Indent(4,MapleFormula('Cumulative(f,x)=f(x)/2+sum(f(t),t=-infinity..x-1)')),
  Examples( 'CumulativeStd( Binomial(10,0.5), 6 )',
	'CumulativeStd( U(0,10), 9.75 )' ),
  SeeAlso( Cumulative, CumulativeStd, Rand, StatTest, Std_Score,
	OutsideBounds, ProbBallsBoxes, ProbCloseMatches )
):


Std_Score_Description := Description(
  function( Std_Score ),
  Summary( 'conversion from standard deviations to Score' ),
  CallingSequence( noeval(Std_Score(s)) ),
  Parameters( ['s', numeric, 'a number of standard deviations'] ),
  Returns( numeric ),
  Synopsis('This function converts a probability expressed in terms
of standard deviations to a Score (-10*log10(Prob)).
This is done in such a way that very large values can be handled
with precision and without causing overflow/underflow.
Formally, a Score is defined as:' ), '\n',
Indent(4,'Score = -10 * log10( Prob{ Normal(0,1) < s } )'),
  Examples( 'Std_Score( -30 )',
        'Std_Score( +30 )' ),
  SeeAlso( Cumulative, CumulativeStd, Rand, StatTest, Std_Score,
        OutsideBounds, ProbBallsBoxes, ProbCloseMatches )
):



StatTest_Description := Description(
  function( StatTest ),
  Summary( 'Test a statistical hypothesis' ),
  CallingSequence( noeval(StatTest(test,data)) ),
  Parameters( [test,string,'Indicator which test should be done'],
  [data,anything,'data used to test the hypothesis (type depends on test)'] ),
  Returns( TestStatResult ),
  Synopsis('This function tests several statistical hypothesis.
The type of hypothesis to be tested is indicated via the first argument.
Tests implemented so far:'), '',
  Paragraph( -15, 'ChiSquare      One-dimensional Chi-square test of
independence (cells are assumed equally-probably).
"data" is a one-dimensional array of counts (non-negative integers).
The data can also be a table or counts which must be indexed over
the integers.
Every non-zero entry of the table will be assumed an entry in the
data.'),
  Paragraph( -15, 'ChiSquare      Two-dimensional Chi-square test of
independence (rows and columns are assumed independent).
"data" is a two-dimensional array of counts (non-negative integers).
The data can also be a table of counts which must be indexed over
pairs of integers (lists of two integers).
Every non-zero entry of the table will be assumed an entry in the data.'),
  Paragraph( -15, 'Independence   Two arrays of (any type of) data are
grouped to test their independence.  The most significant
Chi-square test is reported.' ),
  Paragraph( -15, 'FriedmanRafsky Tests whether two samples, usually
multivariates, come from the same distribution. Each sample must be 
inputed as a matrix in which each column is a sample.' ),
  Paragraph( -15, 'G              One-dimensional G test of
independence (cells are assumed equally-probably).
This is an instance of the likelihood ratio test applied to a
list of equiprobable events.
"data" is a one-dimensional array of counts (non-negative integers).
The data can also be a table or counts which must be indexed over
the integers.
Every non-zero entry of the table will be assumed an entry in the
data.'),
  Paragraph( -15, 'G              Two-dimensional G test of
independence (rows and columns are assumed independent).
This is an instance of the likelihood ratio test applied to tableaux.
"data" is a two-dimensional array of counts (non-negative integers).
The data can also be a table of counts which must be indexed over
pairs of integers (lists of two integers).
Every non-zero entry of the table will be assumed an entry in the data.'),
'',
  Paragraph( 2, 'For each hypothesis an internal function will be
called that computes the test statistic from the data, the p-value
from Cumulative and the standardized deviation from CumulativeStd.'),
  References( 'Rice JA, Mathematical Statistics and Data Analysis,
2nd ed.  chapter 13.4, p.489', 'Friedman, Rafsky (1979) "Multivariate 
Generalizations of the Wald-Wolfowitz and Smirnov Two-Sample Tests"'),
  Keywords('Chi-Square','G-test','Independence','Friedman-Rafsky'),
  Examples( 'StatTest( ChiSquare,[[1,2,3],[4,5,6],[7,8,9]] )',
	'StatTest( Independence, [A,B,B,B,B,A], [-1,3,4,3,4,-3] )',
	'StatTest( FriedmanRafsky, [[1,5],[2,-1],[1,3]], [[1,-1],[3,4]] )'
 ),
  SeeAlso( TestStatResult, Cumulative, CumulativeStd, Rand, Std_Score,
	OutsideBounds, ProbBallsBoxes, ProbCloseMatches )
):


Zscore_Description := Description(
  function( Zscore ),
  Summary( 'Test a statistical hypothesis' ),
  CallingSequence( noeval(Zscore(data)), noeval(ZscorePercent(data)) ),
  Parameters( [data,list,'Counts of observations, assumed equiprobable'],
  [data,matrix,'Counts by two criteria, assumed independent'] ),
  Returns( {list,matrix} ),
  Synopsis('Zscore transforms a vector or matrix of counts
into a vector/matrix of normalized variables (ones with
expected value 0 and variance 1).
This is subtracting the expected value and dividing
by the standard deviation.
Or Z = (X-E[X])/sqrt(Var(X)).'),
Paragraph( -2, 'In this way the observations can be measured in
"standard deviations away from the mean", which
is a simple and useful measure.
This is sometimes called the Z-transform, but since the
Z-transform has a well established use in power series,
we use the name Zscore.' ),
Paragraph( -2, 'If the input is a vector of integers, it is assumed that
all the values are counts of events which are equally probable.
If the input is a matrix it is assumed that the values are
counts of two independent events (columns/rows).
In both cases, a binomial distribution is assumed for the
counts, i.e. the individual events counted are independent
of each other.
ZscorePercent is very similar, but instead of returning a normalized
variable, it returns a percentage of the expected value, i.e.
Z = 100 * (X-E[X])/E[X]' ),
  Examples( 'Zscore( [8,12,21,7] )',
	Print('print(Zscore( [[3,7,21],[10,15,33]] ))'),
	'ZscorePercent( [8,12,21,7] )'
 ),
  SeeAlso( StatTest, TestStatResult, Cumulative, CumulativeStd, Rand, Std_Score,
	OutsideBounds, ProbBallsBoxes, ProbCloseMatches )
):


TestGradHessian_Description := Description( function(TestGradHessian),
  CallingSequence( noeval(TestGradHessian(f,f1,f2,point)) ),
  Parameters( [f, procedure, 'multivariate numerical function'],
	[f1, procedure, 'gradient of f, returns a vector'],
	[f2, procedure, 'hessian of f, returns a square matrix'],
	[point, list(numeric), '(optional) value at which to test'],
	[n, posint, '(optional) dimension of argument of f'],
	[Tol, Tolerance=positive, '(optional, default=100) error tolerance'] ),
  Returns(boolean),
  Synopsis( 'The TestGradHessian function is used to test whether the
first and second derivatives of a function are computed correctly.
This test is run at the given point (or at a random point instead).
The arguments to f, f1 and f2 are vectors (lists) of dimension n.
The output of f must be a number, the output of f1 must be a list of
numbers of dimension n (the partial derivatives of f) and the output of
f2 must be a matrix (n x n) with the second partial derivatives of f.
' ),
Paragraph(-2,'TestGradHessian computes approximations to the gradient
and the hessian by computing f and f1 at various points.  If the results
are within 100 times the minimal expected error, the function returns
true, else it prints some information about the failure and returns
false.  The error tolerance can be changed from 100 to any desired number
with the corresponding optional argument' ),
  Examples( 'f := proc(x) cos(x[1])*tan(x[2]) end:',
	'f1 := proc(x) [-sin(x[1])*tan(x[2]), cos(x[1])*(1+tan(x[2])^2)] end:',
	'f2 := proc(x) [[-cos(x[1])*tan(x[2]), -sin(x[1])*(1+tan(x[2])^2)],
    [-sin(x[1])*(1+tan(x[2])^2), 2*cos(x[1])*tan(x[2])*(1+tan(x[2])^2)]] end:',
	'TestGradHessian(f,f1,f2,[0.3,0.5])',
	Print('TestGradHessian(f,f1,f2,[0.3,0.5],Tolerance=0.4)'),
	Unassign('f','f1','f2') ),
  SeeAlso_Minimize
  ):


TestStatResult_Description := Description(
  structure( TestStatResult ),
  Summary( 'result of a statistical test' ),
  CallingSequence( noeval( TestStatResult(name, TestStat, pvalue, pstd) ) ),
  Selectors( [name,string,'name of the statistical test'],
  [TestStat,numeric,'test statistic computed from the data'],
  [pvalue,numeric,'p-value (probability value)'],
  [pstd,numeric,'p-value in standard deviations'],
  [plog,numeric,'natural logarithm of the p-value'],
  [CountMatrix,array(integer),'count matrix, (optional, e.g. ChiSquare)'] ),
  Synopsis( 'A TestStatResult holds a result of a statistical test.
It is normally generated by the StatTest function.
The pvalue depends on the test, and in general it is the probability
that such a result is obtained by chance.
Extreme values (very close to 0 or very close to 1) are hence very rare.
The pstd value measures the pvalue too.  It is the number of standard
deviations away that the pvalue would be if it were a normally
distributed variable.  It is useful to measure very extreme probabilities,
where the p-values may be out of precision.
For extremely small values of the p-value, the selector plog may be more
practical, it records the natural logarithm of the p-value.
For the ChiSquare test the count matrix is returned as the fifth field and 
is associated with the selector CountMatrix.' ),
Paragraph( -2, 'Besides the first four fields and the CountMatrix,
the structure can hold any number of additional arguments,
which are test-dependent.
These extra arguments are typically of the form string=anything.
TestStatResult prints nicely via the print method.
Any symbol of type string=anything will be printed using the format (%s = %a).
Any occurrences of _ in the string will be replaced by a space.
An example for this is Degrees_of_freedom=x in the ChiSquare test.' ),
  SeeAlso( StatTest )
):


GaussElim_Description := Description(
  function(GaussElim ),
  CallingSequence( noeval(GaussElim('A', 'b')) ),
  Parameters( ['A', matrix(numeric)], ['b', array(numeric)] ),
  Returns( 'a vector (one dimensional array) of numeric' ),
  Synopsis( 'Given a matrix of numerical values A and vector b, this
function computes x so that A * x = b by Gaussian elimination.
A must be a square numerical matrix.' ),
  Examples( 'GaussElim([[2,4,6], [9,0,27],[17,23,5]], [8, 15, 17])' ),
  SeeAlsoLinAlg
):

log10_Description := Description(
  function(log10),
  CallingSequence( noeval(log10(x)), noeval(log10(A)) ),
  Parameters( ['x', numeric, 'numeric > 0'], 
		[A, matrix, 'a square numeric matrix'] ),
  Returns( numeric, matrix(numeric) ),
  Synopsis( 'This function computes the logarithm (base 10) if the parameter
is a single numerical value.  If the argument is a square matrix, it computes
a square matrix B with the same dimensions of A such that 10^B = A.  Not
all matrices have a logarithm base 10 (which is real valued).' ),
  Examples( 'log10(7.5)', 'log10(10)' ),
  SeeAlso( ln1x, ln, log, lg )
):

max_Description := Description(
  function( max ),
  Summary( 'maximum of numbers or list of numbers' ),
  CallingSequence( noeval(max(L1,L2,'...')) ),
  Parameters( ['Li', {numeric,list(numeric), list(list(numeric))},
	'numbers or list (of lists) of numbers'] ),
  Returns( numeric ),
  Synopsis('Finds the maximum valued element in L if L is simply a
list of numeric elements.  If L is a list of lists of numeric, the
function effectively flattens this list to a simple list and returns
the maximum valued element.' ),
  Examples( 'max(5, 97, 22, [14,15,16] )', 'max(2,3,5,7,11,13,17,19)' ),
  SeeAlso( min, max, avg, var, std )
):

MaximizeFunc_Description := Description(
  function( MaximizeFunc ),
  CallingSequence( noeval(MaximizeFunc(f, r, tol)),
		   noeval(MaximizeFunc(f, r)) ),
  Parameters( ['f', procedure], ['r', numeric..numeric], 
	      ['tol', 'numeric >= 0'] ),
  Returns( '[x, f(x)]' ),
  Synopsis( 'This function finds the maximum [x, f(x)] of a convex
function f over a range r within an absolute accuracy of tol.
If tol is not given as a parameter, the result is of machine accuracy.'),
  Examples( 'MaximizeFunc(x -> sin(x), 0..1)', 
	    'MaximizeFunc(x -> x^2 - 3*x, -2..0)' ),
  SeeAlso_Minimize
):

min_Description := Description(
  function( min ),
  Summary( 'minimum of numbers or list of numbers' ),
  CallingSequence( noeval(min(L1,L2,'...')) ),
  Parameters( ['Li', {numeric,list(numeric), list(list(numeric))},
	'numbers or list (of lists) of numbers'] ),
  Returns( numeric ),
  Synopsis('Finds the minimum valued element in L if L is simply a
list of numeric elements.  If L is a list of lists of numeric,
the function effectively flattens this list to a simple list and
returns the minimum valued element.' ),
  Examples( 'min(5, 97, 22, [14,15,16] )', 'min(2,3,5,7,11,13,17,19)' ),
  SeeAlso( min, max, avg, var, std, median )
):

avg_Description := Description(
  function( avg ),
  Summary( 'average of numbers or list of numbers' ),
  CallingSequence( noeval(avg(L1,L2,'...')) ),
  Parameters( ['Li', {numeric,list(numeric)}, 'a number or list of numbers'] ),
  Returns( numeric ),
  Synopsis('Finds the average of all the values in the arguments.'),
  Examples( 'avg(5, 97, 22, [14,15,16] )', 'avg(2,3,5,7,11,13,17,19)' ),
  SeeAlso( min, max, avg, var, std, median )
):

median_Description := Description(
  function( median ),
  Summary( 'median of numbers or list of numbers' ),
  CallingSequence( noeval(median(L1,L2,'...')) ),
  Parameters( ['Li', {numeric,list(numeric)}, 'a number or list of numbers'] ),
  Returns( numeric ),
  Synopsis('Finds the median of all the values in the arguments.'),
  Examples( 'median(5, 97, 22 )', 'median(2,3,5,7,11,13,17,19)' ),
  SeeAlso( min, max, avg, var, std )
):

var_Description := Description(
  function( var ),
  Summary( 'unbiased estimate of variance of (list of) numbers' ),
  CallingSequence( noeval(var(L1,L2,'...')) ),
  Parameters( ['Li', {numeric,list(numeric)}, 'a number or list of numbers'] ),
  Returns( numeric ),
  Synopsis('Finds the variance of all the values in the arguments.
This is an unbiased estimator of the variance, that is it is computed
with the formula:  (sum(x^2) - sum(x)^2/n) / (n-1), where n is the
number of x values.  This function needs at least two values to
compute successfully'),
  Examples( 'var(5, 97, 22, [14,15,16] )', 'var(2,3,5,7,11,13,17,19)' ),
  SeeAlso( min, max, avg, var, std, median )
):


std_Description := Description(
  function( std ),
  Summary( 'unbiased estimate of standard deviation of (list of) numbers' ),
  CallingSequence( noeval(std(L1,L2,'...')) ),
  Parameters( ['Li', {numeric,list(numeric)}, 'a number or list of numbers'] ),
  Returns( numeric ),
  Synopsis('Finds the variance of all the values in the arguments.
This is an unbiased estimator of the variance, that is it is computed
with the formula:  (sum(x^2) - sum(x)^2/n) / (n-1), where n is the
number of x values.  This function needs at least two values to
compute successfully'),
  Examples( 'std(5, 97, 22, [14,15,16] )', 'std(2,3,5,7,11,13,17,19)' ),
  SeeAlso( min, max, avg, var, std, median )
):

MinimizeFunc_Description := Description(
  function( MinimizeFunc ),
  Summary( 'Minimize a multivariate function using hill descending'),
  CallingSequence( noeval(MinimizeFunc(f, iniguess, epsini, epsfinal ))),
  Parameters( ['f', procedure], ['iniguess', array( numeric )],
	      ['epsini', numeric], ['epsfinal', numeric] ),
  Returns( '[x, f(x)]' ),
  Synopsis( 'Starting at iniguess with error tolerance epsini, this
function minimizes f until the accuracy in each dimension is less than
or equal to epsfinal.  The function f takes an array of arguments.
It returns the argument and the value of the local minimum found.
The dimension of the array is given by the dimension of iniguess.' ),
  Examples( 'MinimizeFunc(x -> 3*tan(x[1])+abs(x[2]), [0.33, 0.44], 0.2, 0.1)' ),
  SeeAlso_Minimize
):

MinimizeSD_Description := Description(
  function( MinimizeSD ),
  Summary( 'Minimize a multivariate function using steepest descent' ),
  CallingSequence( noeval(MinimizeSD(f, iniguess, relateps ))),
  Parameters(
	['f', procedure,'the function to minimize, returns [f(x),f''(x)]' ],
	['iniguess', array( numeric ), 'initial guess'],
	['relateps', numeric, 'stop when |f''(x)| < |x| relateps'] ),
  Returns( '[x, f(x),f''(x)]' ),
  Synopsis( 'Starting at iniguess this function searches a local
minimum in the direction of the steepest descent.
The direction of the steepest descent is used as long as the
actual function decrease agrees (up to 90%) with the predicted
(from the gradient) decrease.
This guarantees that the minimum found is the one in the
direction of the initial steepest descent.
The convergence of this function is fast when it is searching far
from the minimum and then it becomes slow when it is close to the
minimum.' ),

Paragraph(-2,' MinimizeSD returns the list [x,f(x),f''(x)] at a local minimum
(when the convergence criteria is met) or when the number
of iterations exceeds 200.' ),

Paragraph(-2,' The function f(x) should compute the functional and its
gradient and these should be returned as a list of two
values: [fx:numeric,f1x:list(numeric)]
Additional arguments passed on to MinimizeSD (fourth,
fifth, etc.) are passed as additional arguments to f().
In this way f() usually does not need to rely on global information.' ),

  Examples( 'f := x -> [sin(x[1])+x[2]^2,[cos(x[1]),2*x[2]]]',
    'MinimizeSD(f, [0.33, 0.44], 0.001)',
    Hide('f:=noeval(f)') ),
  SeeAlso_Minimize
):

DisconMinimize_Description := Description(
  function( DisconMinimize ),
  CallingSequence( noeval(DisconMinimize(f, iniguess, epsini, epsfinal)) ),
  Parameters( ['f', procedure], ['iniguess', array(numeric)], 
	      ['epsini', numeric], ['epsfinal', numeric] ),
  Returns( 'x, f(x)' ),
  Synopsis( 'Starting at iniguess, this function minimizes f until the
argument accuracy in each dimension is less than or equal to epsfinal
(for discontinuous function f).' ),
  SeeAlso_Minimize
):

BFGSMinimize_Description := Description(
 function( BFGSMinimize ),
 CallingSequence( noeval(BFGSMinimize(f, iniguess, epsini, epsfinal)) ),
 Parameters( ['f', procedure], ['iniguess', array(numeric)],
            ['epsini', numeric], ['epsfinal', numeric] ),
 Returns( 'x, f(x)' ),
 Synopsis( 'The Quasi-Newton approach of the BFGS method is used to
 find the (local) minimum of a function f. BFGSMinimize starts at iniguess
 and stops if either the distance between the two last points is smaller than
 epsfinal or after 1000 iterations without convergence.' ),
 SeeAlso_Minimize
):

mod_Description := Description(
  function( mod ),
  CallingSequence( noeval(mod(x,y)) ),
  Parameters( 	['x', numeric,'a number' ], 
		['y', numeric, 'a number > 0'] ),
  Returns( numeric ),
  Synopsis( 'This function computes the function x (mod y) i.e. it
returns the integer remainder after dividing y into x.  Note:
if x or y are so large that they cannot be represented exactly
as integers in a double precision number, the results may be wrong.' ),
  Examples( 'mod(5,2)', 'mod(99,1)', 'mod(-3,2)' ),
  SeeAlso( ceil, floor, round, trunc )
):

round_Description := Description(
  function(round ),
  CallingSequence( noeval(round(x)) ),
  Parameters( ['x', numeric] ),
  Returns( integer ),
  Synopsis( 'This function rounds the argument x to the nearest integer.
For exact integers + 1/2, the rounding is done according to the next
higher significant bit (IEEE standard).'),
  Examples( 'round(5.5555555)', 'round(1.3)', 'round(-7.8)' ),
  SeeAlso( ceil, floor, mod, trunc )
):

sqrt_Description := Description(
  function( sqrt ),
  Summary ('Square Root'),
  CallingSequence( noeval(sqrt(x)) ),
  Parameters( ['x', 'numeric >= 0'] ),
  Returns( numeric ),
  Synopsis( 'Computes the square root of x.'),
  Examples( 'sqrt(5)' ),
  SeeAlso( Complex, Polar )
):

transpose_Description := Description(
  function( transpose ),
  Summary( 'transpose a matrix' ),
  CallingSequence( noeval(transpose(A)), noeval(A^T), noeval(A^t) ),
  Parameters( ['A', matrix(anything)] ),
  Returns( matrix(anything) ),
  Synopsis( 'Computes the transpose, A^T, of a matrix A.
(The transpose of a matrix is produced by replacing entry A_ij
with entry A_ji for all i, j.)
Transposition can also be achieved through the use of the exponent
T or t.  For this to work properly, T or t must not be assigned.
Transpose will also work for higher order arrays.' ),
  Examples( 'A := transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]])',
	'A^t', Hide('A:=noeval(A)') ),
  SeeAlsoLinAlg
):

GapTree_Description := Description(
  function( GapTree ),
  Summary( 'build a phylogenetic tree based on gaps' ),
  CallingSequence( noeval(GapTree( msa, '...' ))),
  Parameters( [msa, MAlignment, 'one or many MAlignments over the same species'] ),
  Returns( Tree ),
  Synopsis( 'GapTree builds a phylogenetic tree based on the
gaps of one/several multiple sequence alignments.
The assumption is that gap creation is a sufficiently
rare which allows us to build better trees for longer
distances.
The gaps are extracted from MAlignments given as arguments.
Only single gaps which are clearly delimited are used.
Areas in which no sequence is gap-less are not considered.
Areas where sequences have two gaps are also discarded.
The existence/non-existence of gaps is then fed to a
parsimony algorithm to produce a tree.
The input MAlignments should be on the same set of
labels.  More specifically, we expect the MAlignments to
be over different sets of sequences belonging to the same
set of species, identified by the same list of labels.'),
Paragraph( -2, 'The global variable GapTree_Title is set to
a short description of the details of the construction.' ),
  SeeAlso (MAlignment, LeastSquaresTree, Tree, Leaf, DrawTree, Synteny,
BootstrapTree, Entry, Sequence, GapTree, SignedSynteny )
):

PhylogeneticTree_Description := Description( function(PhylogeneticTree),
  Summary( 'Constructs Phylogenetic Trees' ),
  CallingSequence( noeval(PhylogeneticTree(Seqs,Ids,Mode))),
  Parameters( ['Seqs',list, 'Sequences or Entries from which a tree is built'],
   ['Ids',{procedure,list}, 'list of id tags or procedure that produces tags'],
   ['Mode',symbol, 'method - DISTANCE, PARSIMONY or LINEAGE'],
   ['msa',MAlignment, 'optional Multiple sequence alignment'],
   ['allall',matrix, 'optional all vs all matrix of Alignments']),
  Returns(Tree),

  Synopsis( 'PhylogeneticTree is a method for constructing phylogenetic
trees using either minimization of the least squares of the
distances in the real data and computed tree or by minimizing the
number of changes/mutations that would be required' ),

Paragraph(-2,'If the mode passed is DISTANCE, an all-against-all
(each sequence aligned against each other sequence)
is calculated and the distance and variance information is
used to compute a binary tree which approximates via least squares
the distance information.
If an optional array of Alignment data structures is passed as
an argument, this all-against-all will be used instead of recalculating it.
Ten trees are constructed from random starting points and the
best tree is returned.
All trees are optimized using iterations of 4-optim and 5-optim
which optimize all subtrees with 4 and 5 branches respectively.
The quality of the fit is measured by the sum of the squares of
the weighted deviations divided by (n-2)(n-3)/2.
This value is stored in the global variable MST_Qual.
If the global variable MinLen is assigned a positive value, it
will determine the minimum length between internal or external nodes.
If not set, 0.1 PAM is used.
The distance of the branches are the approximate distances
calculated by least squares in PAM units.
Since the tree is made from alignments, the input sequences
must be protein or DNA sequences.' ),
'',

Paragraph(-2,'If the mode passed is PARSIMONY, random trees are
constructed and then optimized with 4-and 5-optim using the
parsimony criterion (the tree with the least amount of mutations
is the best tree).
This is sometimes also called character compatibility.
Each position of the given sequences is treated as a character.
The goal of the parsimony trees is to build a tree such that
we can assign character changes on the branches of the tree
and this total number of changes is minimized.
Amino acids or DNA bases can be used as characters, but also
any other arbitrary symbol (characters are restricted to be
ASCII characters though).
If a MAlignment data structure is passed as an optional argument,
this alignment is used.
If all the sequences are exactly the same length, it is assumed
that they have been already aligned and they are taken as given.
If not, the sequences in Seqs are aligned with the circular tour
method (See ?MAlign).
The global variable MST_Qual is assigned the number of changes
that the returned tree requires.
The distances in the tree are taken from the parsimony construction
and indicate the minimum number of changes that must occur in
that particular branch.
The Parsimony method accepts an additional parameter which
indicates which method to use to build the initial tree.
This tree is later optimized.
The methods to build the initial tree are:'),
Paragraph( -17, '  NJRandom       Neighbour Joining with randomness in the
selection of the best pair to join.'),
Paragraph( -17, '  CircularTour   A circular tour of minimum cost is
built at each step, and the pair of nodes with least cost is selected
to be joined.'),
Paragraph( -17, '  NeighJoin      Neighbour Joining.  At each step the
two subtrees with the least cost to join them are joined.'),
Paragraph( -17, '  DynProgr(k)    Use a dynamic programming approach
among the k best results of Neighbour Joining.'),
Paragraph( -17, '  DynProgr       Identical to DynProgr(10)'),
Paragraph( -17, '  OptInsertion   Insert each leaf/subtree in the best
possible branch of the previously built subtrees.  This is the default
choice, it is a bit slow, but normally gives the best trees.'),
Paragraph( -17, '  Random         Leaves/subtrees are joined randomly.
Quite fast, but produces poor trees.'),
Paragraph( -17, '  LowerBound     Do not build a tree, just compute a
lower bound on the cost of the tree (minimum number of changes).'),
Paragraph( -17, '  SemiOptInsertion(t) Like OptInsertion, but limit
the search of the best insertion to t seconds.'),
Paragraph( -17, '  SemiOptInsertion Synonym of SemiOptInsertion(10).'),
'',
Paragraph(-2,'If the mode passed is StrictCharacterCompatibility,
then it is assumed that the Seqs are strings (all of the same
lengths) of binary characters.
Any symbols can be used for the characters.
If the characters are not compatible, an error is given with
the first pair of characters which are not compatible.
The global variable MST_Qual will contain the minimum number of
character changes, which is equal to the number of informative
characters (and never greater than the length of the sequences
of characters).' ),
'',
Paragraph(-2,'If the mode passed is LINEAGE, then it is assumed
that the Seqs are lists containing lineage descriptions.
The lists are assumed to classify each sequence from the most
general to the most specific class.
The lineage descriptions have to be consistent, that is if
a particular class is used, then it should always be preceded
with the same sequence of classes.
The classes are typically strings, but could be any valid Darwin
object.'),
  Examples('Ids := [''one'',''two'',''three'',''four'']:',
  'Seqs := [''RTHKLPEMNVC'', ''KSHKLPEMNVC'', ''SHKLMNVC'', ''HKLPEMNVC'']:',
  Print('PhylogeneticTree(Seqs,Ids,DISTANCE)'),
  'MST_Qual',
  'PhylogeneticTree(Seqs,Ids,PARSIMONY)',
  'Seqs := [B1xj,B2zj,G2zi,G1xi,G2xi]:',
  'PhylogeneticTree(Seqs,[seq(i,i=1..5)],parsimony)',
  'MST_Qual',
  Unassign('Seqs','Ids')
),
  SeeAlso (MAlignment, LeastSquaresTree, Tree, Leaf, DrawTree, Synteny,
BootstrapTree, Entry, Sequence, GapTree, SignedSynteny,
ComputeDimensionlessFit, RBFS_Tree,Tree_matrix )
  ):

RBFS_Tree_Description := Description( function(RBFS_Tree),
  Summary( 'apply heuristics to improve a distance tree' ),
  CallingSequence( noeval(RBFS_Tree(t,Dist,Var))),
  Parameters( ['t',Tree, 'input distance Tree'],
	['Dist',matrix(numeric),'distance matrix used to build Tree'],
	['Var',matrix(numeric),'variances of the distances'],
	['','''Top'''=posint,'(default=1) number of best trees to return'] ),
  Returns( set([numeric,Tree]) ),
  Synopsis( 'RBFS_Tree is a method for improving distance phylogenetic
trees using heuristics.
The first type of heuristics, called Reduce Best Fitting Subtree (RBFS)
selects a set of subtrees which are highly consistent and their fit is
of good quality, replaces them with a single leaf and attempts to
optimize the reduced tree.
The second heuristic chooses, from different trees, subtrees which are
on the same set of leaves and tries to graft them together hoping that
the resulting tree is better.
RBFS_Tree returns a set of pairs: [DimensionlessFit,Tree].
The number of trees returned can be changed with the optional parameter
Top=n.
The trees returned are the ones which have the highest quality (lowest
DimensionlessFit value).' ),
  SeeAlso( LeastSquaresTree, Tree, Leaf, BootstrapTree, Synteny, GapTree,
SignedSynteny, ComputeDimensionlessFit, PhylogeneticTree )
  ):

LeastSquaresTree_Description := Description(
  function(LeastSquaresTree ),
  Summary( 'compute a distance phylogenetic tree using least squares'),
  CallingSequence( noeval(LeastSquaresTree( Dist, Var )),
		noeval(LeastSquaresTree( Dist, Var, Labels )),
		noeval(LeastSquaresTree( Dist, Var, Labels, IniTree, Keep )) ),
  Parameters( [ 'Dist', matrix(numeric), 'Pairwise distances'], 
	[ 'Var', matrix(numeric), 'Variances' ],
	[ 'Labels', list, 'Optional labels for the leaves' ],
	[IniTree, Tree, 'Initial tree to optimize its branch lengths'],
	[IniTree,'''Random''', 'To start with a completely random tree'],
	[IniTree,'''NJRandom''',
	    'To start with a random Neighbour-joining like tree'],
	[IniTree,'''Trials'''=posint,
	    'Run n trials with NJRandom and return the best tree'],
	[Keep,'''KeepTopology''', '(optional) Optimize branch lengths only']
  ),
  Returns( Tree ),
  Synopsis('This function computes a binary tree which
approximates the given distances Dist by least squares.
The distances are assumed to have a variance given by the matrix Var.
If a list Labels is given, the leaf of the resulting trees are
labelled with these values.
The Leaf nodes produced have 3 fields: (1) the label given
(or their integer index if no Labels are given),
(2) the height of the Leaf and (3) their integer index.
If the global variable MinLen is assigned a positive value,
it will determine the minimum branch length.
If not set, 1/1000th of the average distance between
leaves is used.
The quality of the fit is measured by the sum of the squares of
the weighted deviations divided by (n-2)(n-3)/2.
This value is stored in the global variable MST_Qual.
A dimensionless fitting index is also computed, it is the
MST_Qual / variance(Dist) * harmonic_mean(Var).
This value is printed and stored in the global variable
DimensionlessFit.
Trees built over the same set of species, even with radically
different methods, can be ranked by the quality of their fit with
this index.
If the fourth parameter has a Tree, then this tree is taken and
optimized.'),
Paragraph(-2, 'If the fourth argument is the word "Random",
then the optimization is started over a random tree.
For large trees it makes sense to try several random trees and
choose the one with the best MST_Qual.
When starting with random trees, the global variable MST_Prob
can be set to any numerical value between 0 and 1.
Values close to 1 select trees which are very close to the
one given by Neighbour Joining.
Values close to 0 select completely random trees.
Leaving MST_Prob unassigned is equivalent to using NJRandom.' ),
Paragraph(-2,
'When "NJRandom" is used, a Neighbour-joining like tree is
make with a variable level of randomness at each step
which may produce better random trees.'),
Paragraph(-2,'When the word KeepTopology is used, the
optimization is done only on the branch lengths.
This is useful to optimize the branches of a given tree.'),
Paragraph(-2, 'The function Tree_matrix extracts the distance
matrix from a tree.
It is sort of the inverse of LeastSquaresTree.'),
  Examples( 
'D := [[0, 3, 13, 10], [3, 0, 14, 11], [13, 14, 0, 9], [10, 11, 9, 0]]', 
'V := [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]',
Print('LeastSquaresTree(D, V)'),
Print('t := LeastSquaresTree(D, V, [AA, BB, CC, DD])'),
Print('print(Tree_matrix(t))'),
  Unassign('t','D','V') ),
  SeeAlso( Tree, Leaf, PhylogeneticTree, DrawTree, ViewPlot, RBFS_Tree,
BootstrapTree, Synteny, GapTree, SignedSynteny, ComputeDimensionlessFit,
Tree_matrix )
):
MinSquareTree_Description := LeastSquaresTree_Description:

Tree_matrix_Description := Description(
  function( Tree_matrix ),
  Summary( 'Distence Matrix induced from Tree' ),
  CallingSequence( noeval( Tree_matrix(t) ),
      noeval( Tree_matrix(t, leaves))),
  Parameters(
    [t, Tree, 'the given tree'],
    [leaves,{list,table,procedure}, '(optional) leaf to index mapping']),
  Returns( matrix(nonnegative) ),
  Synopsis( 'This function extracts the pairwise distances between any two
leaves on a tree and returns them in a distance matrix. If the optional ''leaves'' argument is not provided, the ''Label'' or 3rd field of the Leaf datastructures have to contain the indices to the matrix. Otherwise, the leaves argument has to be either a list of leaf labels, a table pointing from labels to indices or a function returning for a leaf datastructure the appropriate index.'),
  Examples(   
't := Tree(Leaf(A,1.2),0,Tree(Leaf(B,1.8),0.9,Leaf(C,1.4)))',
'Tree_matrix(t,[A,B,C])',
Unassign('t') ),
  SeeAlso( Tree, Leaf, PhylogeneticTree, LeastSquaresTree, CreateArray)
):


ComputeDimensionlessFit_Description := Description(
  function( ComputeDimensionlessFit ),
  Summary( 'dimensionless fitting of a distance tree'),
  CallingSequence( noeval( ComputeDimensionlessFit(t,Dist,Var) )),
  Parameters(
	[t,Tree,'the given tree'],
	[t,matrix(numeric),'alternatively, the distances over the tree'],
	[Dist,matrix(numeric),'distance matrix'],
	[Var,matrix(numeric),'variances of the distances'] ),
  Returns( nonnegative ),
  Synopsis( 'This function computes the Dimensionless fitting index
of a set of distances over a tree as in "A Dimensionless Fit Measure for
Phylogenetic Distance Trees", J Bioinform Comput Biol, vol 3, pp 1429-1440.
Trees built over the same set of species, even with radically
different methods, can be ranked by the quality of their fit with
this index.
The input can be a tree (which is converted to an actual distance matrix
with the Tree_matrix) or an actual distance matrix.
The input matrices Dist and Var are the distance measured between the
species and their variance.'),
  SeeAlso( LeastSquaresTree, PhylogeneticTree, BootstrapTree, Synteny,
GapTree, SignedSynteny, Tree_matrix, RBFS_Tree )
):


compress_Description := Description(
  function( compress ),
  Summary( 'compress an arbitrary object' ),
  CallingSequence( noeval(compress(obj)) ),
  Parameters( [obj,anything,'object to compress'] ),
  Returns( compressed ),
  Synopsis( 'Compress takes any structure and compresses it in
a simple way.  The function decompress restores the original
expression.  Normally this is used in cases that lots of
structures are stored in main memory and this would require
too much memory and the structures are not used often enough,
so that it pays to decompress them before using them.
There are several internal structures which are not compressed,
most notably Dayhoff matrices and databases.
Consequently, structures that reference these will (e.g. Alignment)
will not be compressed.
The compression factor is about 3:1 for general structures on
a 32-bit word implementation, higher for 64-bit words.' ),
  Examples( 't := compress([1,2,{3,4}])',
	'decompress(t)', 'size(t)/size([1,2,{3,4}])', Unassign('t') ),
  SeeAlso( size, length, compress, decompress, system )
):


decompress_Description := Description(
  function( decompress ),
  Summary( 'decompresses a compressed object' ),
  CallingSequence( noeval(decompress(compr)) ),
  Parameters( [compr,compressed,'compressed object'] ),
  Returns( anything ),
  Synopsis( 'Compress takes any structure and compresses it in
a simple way.  The function decompress restores the original
expression.  Normally this is used in cases that lots of
structures are stored in main memory and this would require
too much memory and the structures are not used often enough,
so that it pays to decompress them before using them.
The compression factor is about 3:1 for general structures on
a 32-bit word implementation, higher for 64-bit words.' ),
  Examples( 't := compress([1,2,{3,4}])',
	'decompress(t)', 'size(t)/size([1,2,{3,4}])', Unassign('t') ),
  SeeAlso( size, length, compress, decompress, system )
):

print_Description := Description(
  function( print ),
  Summary( 'general pretty-printing'),
  CallingSequence( noeval( print(e1,e2,'...') )),
  Parameters(['ei', anything, expression] ),
  Returns( 'NULL' ),
  Synopsis( 'This function attempts to print out the contents of
each e_{i} in a pretty/readable manner.
Any user-defined data structures/classes
named, for example ClassName, can make use of the print
command by creating a procedure named ClassName_print.
This routine should detail the manner in
which the data structure is to be sent to the standard output.
Any invocation of the print statement on an object of type
ClassName will automatically invoke this routine.
All built-in Darwin data structures have such a routine.
Floating point numbers are printed with 5 significant digits.
The global variable NumberFormat can be assigned a format, as in
the printf function, and all numbers will be printed accordingly.'),
  Paragraph( -2, 'To print procedures there are two options.
Print on a procedure produces a short description based on the
parameters, description field (if any) and return type.
To print the body or the procedure (code) the function
disassemble should be used in conjunction with print.
This produces a nice albeit not perfect formatting.' ),
  Examples( 'x:= [[1,2],[3,4]]', Print('print(x)' ),
	'f := proc(x:positive) description ''test example'';\n    for i to 20 do x+i od; i+sin(x) end:',
	Print('print(f)'),
	Print('print(disassemble(op(PartialFraction)))'),
	Unassign('x','f')),
  SeeAlso( prints, dprint, printf, lprint )
):

dprint_Description := Description( 
  function(dprint),
  Summary('print so that it can be read back by Darwin'),
  CallingSequence( noeval( dprint(e1,e2,'...') ) ),
  Parameters( ['ei', anything, expression] ),
  Returns( 'NULL' ),
  Synopsis( 'This function prints out any Darwin expression.
Expressions are printed so that they could be read back
by Darwin.
In principle a structure dprint-ed should produce, when read
back in, the same structure (except for numerical precision).
If given multiple expressions, these will be separated
by commas, so that they can be read as an expression sequence.
Dprint will use only one newline character at the end of
the printing, so large expressions may be hard to handle
in some systems (will be very long lines).
Floating point numbers are printed with 5 significant digits.
The global variable NumberFormat can be assigned a format, as in
the printf function, and all numbers will be printed accordingly.
Inside a printf statement, the format "%A" achieves the same
effect as dprint.'),
 Examples( Print('dprint(''a b c'',1/3,1e9)'),
	Print('printf( ''%A\\n'', [''a b c'',1/3,1e9] )')
	 ),
  SeeAlso( prints, lprint, print,
  [printf, 'contains conversion patterns'], sprintf, sscanf, PrintMatrix )
):

lprint_Description := Description( 
  function(lprint),
  Summary( 'linear print of expression(s)' ),
  CallingSequence( noeval( lprint(e1,e2,'...') ) ),
  Parameters( ['ei', anything, expression] ),
  Returns( 'NULL' ),
  Synopsis( 'This function prints out any Darwin built-in type
or structured type.
If the expression is too long, newline characters will be
inserted in a semi-intelligent way.
Multiple expressions are separated by a single space.
Floating point numbers are printed with 5 significant digits.
The global variable NumberFormat can be assigned a format, as in
the printf function, and all numbers will be printed accordingly.
lprint is intended to provide a safe and quick way of printing
expressions.
In general, it is not possible to read them back into Darwin,
use dprint for Darwin-readable output.'),
 Examples( 'x:= [[1,2],[3,4]]:',
	Print('lprint(''A linear printing of a square matrix:'', x)' ),
	Unassign('x') ),
  SeeAlso( prints, dprint, print,
  [printf, 'contains conversion patterns'], sprintf, sscanf, PrintMatrix )
):

sscanf_Description := Description(
  function( sscanf ),
  Summary ('String Format Scan'),
  CallingSequence( noeval(sscanf(txt, pat)) ),
  Parameters( ['txt', string, 'a string'], 
		['pat', string, 'a pattern'] ),
  Returns( list ),
  Synopsis( 'This function behaves similar to C''s scanf function.'),
  Examples( 'sscanf(''hello 6 3'', ''%s %d %d'')' ),
  SeeAlso( [printf, 'for a complete list of all conversion codes'], sprintf )
):

sprintf_Description := Description(
  function( sprintf),
  Summary('Storage print -return a string as if printed'),
  CallingSequence( noeval(sprintf( p, a1..ak )) ),
  Parameters( ['p', 'pattern (same format as for printf)'],
	      ['ai', 'arguments to be formatted according to p'] ),
  Returns( string ),
  Synopsis( 'This function behaves similar to C''s sprintf function.' ),
  Examples( 'i:=5', 'j:=6', 'sprintf(''i and j are: %d %d'', i, j)',
	Unassign('i','j') ),
  SeeAlso( [printf, 'for a complete list of all conversion codes'], sprintf,
	sscanf )
):

OpenAppending_Description := Description(
  function( OpenAppending ),
  CallingSequence( noeval(OpenAppending(fname)),
	noeval(OpenAppending(terminal)),
	noeval(OpenAppending(previous)) ),
  Parameters( ['fname', filename],
	['terminal', 'system variable'],
	['previous', 'system variable'] ),
  Returns( NULL ),
  Synopsis('If the parameter is the system name "terminal", all
subsequent output generated by Darwin is sent to the standard output.
This is typically the terminal.  Otherwise, all subsequent output
generated will be appended to the file "fname".
Fname can be a name or an entire path.
If no file named "fname" exists, Darwin creates such a file.
The options "terminal" and "previous" behave the same way
as they do for OpenWriting.' ),
  Examples( Fake('OpenAppending(''~hallett/bankaccount'')',''), 
	Fake('print(''Debit 100000 SFr.'')', 
		 ' <all output sent to file> '),
	Fake('OpenWriting(terminal)','>') ),
  SeeAlso( OpenAppending, OpenReading, OpenWriting, ReadRawLine, ReadLine,
	LockFile, FileStat, inputoutput, ReadOffsetLine, ReadRawFile, ReadData )
):

ReadDb_Description := Description(
  function( ReadDb ),
  CallingSequence( noeval(ReadDb(fname)) ),
  Parameters( ['fname', string, 'sequence database'] ),
  Returns( database ),
  Synopsis( 'The function loads the sequence database located in file.
The contents of file must be in the Darwin ISO-SGML format.
By default, this sequence database is assigned to the system variable
DB unless another variable is specified.  This functions allows
filename to specify a path.
If fname ends in ".gz" or ".Z", then it is assumed to
be a compressed file and it is decompressed before reading.'),
  Examples( FakeReadDb ),
  SeeAlso( 'DB', Entry, GenomeSummary, ConsistentGenome, MySql )
):

OpenReading_Description := Description(
  function(OpenReading ),
  Summary( 'open a file for future reading' ),
  CallingSequence( noeval(OpenReading(filename))),
  Parameters( [filename,string] ),
  Returns( NULL ),
  Synopsis( 'This functions opens the file given as argument for
reading.  Any future ReadRawLine or ReadLine commands will read data
from the opened file.  When the end of the file is reached, the
read commands will return the token EOF.  If the argument is the
name ''terminal'', then the standard input (stdin in Unix) is opened
for input.  A file that is opened this way can contain Darwin commands
or any arbitrary text.  If a ReadRawLine() command is used, then a
textual line of the file will be read.  If a ReadLine() command is
used, then the line is expected to be a valid Darwin command.
If filename ends in ".gz" or ".Z", then it is assumed to
be a compressed file and it is decompressed before reading.' ),
  Examples( Fake( 'OpenReading( ''/home/darwin/test'' )', ''),
	Fake( 't := ReadRawLine()', ''),
	Fake( 'OpenReading(terminal)','') ),
  SeeAlso( OpenAppending, OpenPipe, OpenWriting, ReadRawLine, ReadLine,
	LockFile, FileStat, inputoutput, ReadOffsetLine, ReadRawFile, ReadData, ReadURL,
	MySql, ServerSocket)
):

OpenPipe_Description := Description(
  function(OpenPipe ),
  Summary( 'execute system command and pipe output to Darwin' ),
  CallingSequence( noeval(OpenPipe(cmd)) ),
  Parameters( [cmd,string,'a command for the underlying UNIX system'] ),
  Returns( NULL),
  Synopsis( 'OpenPipe will execute the command described by the
string cmd and directs its output to be the input for Darwin.
This is called opening a pipe in the Unix terminology.
This output is readable with ReadRawLine() commands (simply as text)
or with ReadLine() commands (when the output is/are valid Darwin
commands).  When the output is exhausted, the string EOF will be
returned by the read commands and the pipe will be closed.' ),
  Examples( Fake( 'OpenPipe(date)', ''),
    Fake( 'ReadRawLine()', 'Thu Oct 12 08:01:39 MET DST 2000'),
    Fake( 'ReadRawLine()', EOF) ),
  SeeAlso( OpenAppending, OpenReading, OpenWriting, ReadRawLine, ReadLine,
	inputoutput, ReadOffsetLine, ReadRawFile, CallSystem, SplitLines,
	LockFile, FileStat, TimedCallSystem, SystemCommand )
):

ReadRawLine_Description := Description(
  function( ReadRawLine),
  Summary('read a line as a string' ),
  CallingSequence(noeval(ReadRawLine()),
		noeval(ReadRawLine(t)) ),
  Parameters(['t',string, ' a prompt string'] ),
  Returns(string),
  Synopsis('Reads one line from the current input stream
and returns it as a string.
When the input file is exhausted, the next ReadRawLines will
return the string EOF.
The string t, if provided, is a prompt which is sent to the
standard output directly before reading from the standard input.
This statement should not be used in interactive mode or in
the middle of a program which is being read from the input
stream, as there is bound to be confusion between the program
and the data.
It is recommended to use it inside a function/procedure.' ),
  Examples(Fake( 'OpenPipe(date)', ''),
    Fake( 'ReadRawLine()', 'Thu Oct 12 08:01:39 MET DST 2000'),
    Fake( 'ReadRawLine()', EOF),
    Fake('x := proc() 
t := ReadRawLine(''prompt: ''); 
lprint(''The user entered: '',t); 
end', ''), 
 Fake('x()', 'prompt: 1+3;
The user entered:  1+3;
') 
),
  SeeAlso(OpenReading, OpenPipe, ReadLine, ReadOffsetLine, ReadRawFile,
LockFile, FileStat, inputoutput, SplitLines, ReadData, ReadRawLine, 
SearchDelim, ReadURL, ServerSocket )
):

ReadLine_Description := Description(
  function( ReadLine),
  Summary('reads a darwin command in a single line'),
  CallingSequence(noeval(ReadLine() ),
		noeval(ReadLine(t)) ),
  Parameters(['t',string, ' a prompt string'] ),
  Returns(anything ),
  Synopsis('Reads one statement from the current input stream, evaluates the
statement and return its value.  The string t is a prompt which
is sent to the standard output directly before reading from the
standard input. This statement should only be used from within a
procedure.' ),
  Examples( 
Fake('x := proc() 
t := ReadLine(''prompt: ''); 
lprint(''The user entered: '',t); 
end', ''), 
 Fake('x()', 'prompt: 1+3;
The user entered:  4
') 
),
  SeeAlso(LockFile, FileStat, OpenReading, OpenPipe, ReadLine, ReadOffsetLine,
ReadRawFile, SplitLines, inputoutput, ReadRawLine, ReadData, SearchDelim,
ReadURL,MySql )
):

ReadRawFile_Description := Description(
  function(ReadRawFile ),
  CallingSequence(noeval(ReadRawFile(filename)) ),
  Parameters(['filename', string, 'name of file to be read as a single string'] ),
  Returns(string ),
  Synopsis('Read an entire file (returned as a single string) given by its filename.' ),
  Examples( ),
  SeeAlso( OpenAppending, OpenWriting, OpenReading, ReadRawLine, ReadLine,
	LockFile, FileStat, inputoutput, SplitLines, ReadOffsetLine, ReadData, SearchDelim,
	ReadURL, MySql, NormalizePath)
):

ReadOffsetLine_Description := Description(
  function(ReadOffsetLine ),
  Summary(' Reads one state from a file at a given offset'),
  CallingSequence(noeval(ReadOffsetLine(filename, ofs)) ),
  Parameters(	['filename',filename,'a filename from which to be read'],
		['ofs',posint,'an offset into the file'] ),
  Returns( ),
  Synopsis('Reads one statement starting at ofs in file.' ),
  Examples( ),
  SeeAlso( OpenAppending, OpenWriting, OpenReading, ReadRawLine, ReadLine,
	LockFile, FileStat, inputoutput, ReadRawFile, SplitLines, ReadData, SearchDelim,ReadURL )
):

LockFile_Description := Description(
  function(LockFile ),
  Summary('createas a exclusive lock file'),
  CallingSequence(noeval(LockFile(filename, message)) ),
  Parameters(	['filename',string,'the name of the exclusive lock file'],
		['message',string,'(optional) a comment, added to the lock file'] ),
  Returns( boolean ),
  Synopsis('This command creates a file with the given name which contains some
information about the process and, optionally, the given message.
The creation of this file is done in such a way that only one process will
succeed in creating such a file, even if various are competing for the same
filename.
This implements an exclusive lock mechanism or a semaphore.
The command returns true when it was successful in securing the lock and false
otherwise.
The filename will contain a single line with the hostname, process id number,
date and any given message.
It is guaranteed that only one process will be successful with a given lock file.
This will work on file systems which implement the exclusive locking mechanims
provided by fcntl (see "man 2 fcntl" in unix/linux).' ),
  Examples( ),
  SeeAlso( OpenAppending, OpenWriting, OpenReading, ReadRawLine, ReadLine, ServerSocket,
	LockFile, FileStat, inputoutput, ReadRawFile, SplitLines, ReadData, SearchDelim, 
        ReadURL, NormalizePath )
):

FileStat_Description := Description(
  structure(FileStat ),
  Summary('the unix file status structure'),
  CallingSequence(noeval(FileStat(path)) ),
  Parameters(	['path',string,'a filename or a path'],
	[st_dev,posint, 'device'],
	[st_ino,posint, 'inode'],
	[st_mode,posint, 'protection'],
	[st_nlink,posint, 'number of hard links'],
	[st_uid,integer, 'user ID of owner'],
	[st_gid,integer, 'group ID of owner'],
	[st_rdev,integer, 'device type (if inode device)'],
	[st_size,integer, 'total size, in bytes'],
	[st_blksize,posint, 'blocksize for filesystem I/O'],
	[st_blocks,integer, 'number of blocks allocated'],
	[st_atime,posint, 'time of last access'],
	[st_mtime,posint, 'time of last modification'],
	[st_ctime,posint, 'time of last change']),
  Returns( FileStat ),
  Synopsis('This class stores the unix stat structure, see
"man 2 stat" in any unix system for details.
When called with a single argument, it constructs the entire
structure.
The unix names have been retained for the fields.
This operation is very efficient, it only requires reading the
directory and completes without the execution of any system
command.  Hence it is the recommended way of finding any
information about a file.
When the file does not exist, an empty data structure is
returned.' ),
  Examples( 'FileStat(libname)[st_size]', 'FileStat(''/dev/null'')[st_mtime]',
	'FileStat(non_existing_file)' ),
  SeeAlso( OpenAppending, OpenWriting, OpenReading, ReadRawLine, ReadLine,
	inputoutput, ReadRawFile, SplitLines, ReadData, SearchDelim, LockFile, 
    FileStat, NormalizePath )
):

CurrentOff_Description := Description(
  function(CurrentOff ),
  CallingSequence(noeval(CurrentOff()) ),
  Returns(integer ),
  Synopsis('Returns the current file pointer offset when reading.
This runs the C function ftell() on the current input descriptor.' ),
  SeeAlso( )
):

OpenWriting_Description := Description(
  function( OpenWriting ),
  CallingSequence( noeval(OpenWriting(fname)),
	noeval(OpenWriting(terminal)),
	noeval(OpenWriting(previous)) ),
  Parameters( ['fname', string, 'filename'], 
	['terminal', symbol, 'system variable'],
	['previous', symbol, 'system variable'] ),
  Returns( NULL ),
  Synopsis('If filename is given as the parameter, OpenWriting
will open a file named filename and send all subsequent output
directed towards the standard output into this file.
If filename already exists, it is overwritten.
If "terminal" is specified, all subsequent output is directed back
towards the standard output (typically the monitor).
If filename is "previous", then the current output stream is
closed and subsequent output is reverted to the stream which
was active before the previous OpenWriting or OpenAppending.' ),
  Examples( Fake('OpenWriting(''~hallett/Book/mainfile'')', ''), 
	Fake('print(''A quick way to create a lot of work for myself'')', ''),
	Fake('OpenWriting(terminal)', '') ),
  SeeAlso( OpenAppending, OpenReading, ReadRawLine, ReadLine,
	LockFile, FileStat, inputoutput, ReadOffsetLine, ReadRawFile,
    NormalizePath)
):

Entries_Description := Description(
  iterator( Entries ),
  Summary('iterates over all entries in a database'),
  CallingSequence( 'for z in Entries() do ... od;' ),
  Returns(Entry),
  Synopsis('This is an iterator which returns all the
entries from the default database (stored in DB).
The entries are returned in order, ie. Entry(1), Entry(2), etc.' ),
  SeeAlso( Entry, GetEntryInfo, GetEntryNumber, Sequence, Sequences,
	PatEntry, ID, AC, iterator )
):


Entry_Description := Description(
  function( Entry),
  Summary ('return entries from the database DB'),
  CallingSequence(noeval(Entry(a)) ),
  Parameters(['a',{integer,list(integer),string, structure },
	'Entry number(s) or other description of entries'] ),
  Returns({string,'expseq(string)'}),
  Synopsis('Entry returns the string(s) corresponding to the entries
in the database DB described.  This can be through entry numbers,
PatEntry, Match, ID, AC or partial references to entries.' ),
  Examples( FakeReadDb,
	'e1 := Entry(1)',
	'Entry(PatEntry(10000..10001))',
	'Entry(AC(''P11341''))',
	'Entry(ID(''ID5B_PROJU''))',
	's1 := Sequence(e1)',
	'Entry(e1)',
	'GetEntryNumber(e1)',
	Hide( 'e1:=noeval(e1)'),
	Hide( 's1:=noeval(s1)') ),
  SeeAlso(GetEntryInfo, GetEntryNumber, Sequence, Match, PatEntry, ID, AC, SearchTag )
):


Graph_Description := Description(
  structure(Graph),
  Summary('Data structure for storing a graph'),
  CallingSequence( noeval(Graph(Edges,Nodes))),
  Parameters(
	[Edges,Edges,'description of edges'],
	[Nodes,Nodes,'description of nodes (vertices)'] ),
  Selectors(
[Degrees,list(integer),'a list containing the degree of each node'],
[Adjacencies,list(list),'an array with lists of adjacent nodes,'],
		['','','indexed by node number'],
[Incidences,list(list),'an array with lists of incident edge'],
		['','','numbers, indexed by node number.'],
[Distances,matrix(numeric),'a square matrix containing the distance'],
		['','','between pairs of nodes (assuming that the'],
		['','','edges label is a distance or a list with'],
		['','','first element being a distance).'],
		['','','Disconnected nodes are at dist DBL_MAX.'],
[Labels,matrix,'a square matrix containing the labels of'],
		['','','edges between pairs of nodes.'],
		['','','Disconnected nodes get the label DBL_MAX.'],
[AdjacencyMatrix,matrix,'a square matrix containing 1s for each'],
		['','','edge and zeros otherwise.  The matrix is'],
		['','','symmetric.  The diagonal is zeroed.'] ),
  Synopsis( 'A graph is represented by' ), '',
Code('Graph( Edges( Edge(lab1,n1,n2), ... ), Nodes( lab1, lab2, ... ) )' ), '',
Paragraph( -2, '  Where Edges describes the set of edges and
Nodes describes the set of nodes.  Alternatively, and only as input,
graphs can be represented with the standard notation of set of
vertices and sets of edges.  In this case an edge is represented
as a set of two vertices.  A node (or vertex) can be represented
by any valid object in Darwin.  Usually integers are used.
Notice that the values of Edge must correspond to a node, hence if
you use complicated objects as nodes, these have to be replicated
every time you include them in an Edge.'),
Paragraph(-2,'If Graph is used with only a set of Edges,
it deduces which are the Nodes from the Edges.'),
  Examples( 'Graph({a,b,c},{{a,b},{a,c},{b,c}})',
	'Graph(Edges(Edge(0,10,20),Edge(0,10,35)), Nodes(0,10,20,35))',
	'Graph(Edges(Edge(0,10,20),Edge(0,10,35)))' ),
  SeeAlso_Graph
):




ID_Description := Description(
  structure( ID),
  Summary ('Data structure for storing IDs of the database DB'),
  CallingSequence(noeval(ID(id)) ),
  Parameters(['id',{string,structure,list },
	'ID(s) of Entries in the database DB'],
	['','','PatEntry, Match or Entry data structure'] ),
  Returns(ID ),
  Synopsis('ID is a data structure which holds database identification
tags (IDs) contained in the <ID> and </ID> tags in a Darwin formatted
database.  IDs can be used as arguments to other functions, e.g.
Entry, Sequence, to indicate that the Entry or sequence desired is
the one with the given ID.  ID will attempt to convert its arguments
when they are other entry descriptions to IDs.' ),
  Examples( FakeReadDb,
	'id := ID(''100K_RAT'')',
	'Entry(id)', 'Sequence(id)',
	'ID(Entry(2))',
	'ID(PatEntry(10000..10002))',
	'ID(Sequence(Entry(1)))',
	Hide( 'id:=noeval(id)' )
		),
  SeeAlso(Entry, ID, SearchID, Sequence, Match, PatEntry, AC, SearchAC,
	SP_Species, SPCommonName, Species_Entry )
):

AC_Description := Description(
  structure( AC),
  Summary ('Data structure for storing ACs (Accession numbers) of DB'),
  CallingSequence(noeval(AC(id)) ),
  Parameters(['id',{string,structure,list },
	'ID(s) of Entries in the database DB'],
	['','','PatEntry, Match or Entry data structure'] ),
  Returns(AC ),
  Synopsis('AC is a data structure which holds accession numbers
(ACs) contained in the <AC> and </AC> tags in a Darwin formatted
database.  ACs can be used as arguments to other functions, e.g.
Entry, Sequence, to indicate that the Entry or sequence desired is
the one with the given AC.  AC will attempt to convert its arguments
when they are other entry descriptions to ACs.  An AC can be given
with or without the trailing '';''.  The database contains the
semicolon, so if the AC does not have it, one is added.' ),
  Examples( FakeReadDb,
	'ac := AC(''Q62671'')',
	'Entry(ac)', 'Sequence(ac)',
	'AC(Entry(2))',
	'AC(PatEntry(10000..10002))',
	'AC(Sequence(Entry(1)))',
	Hide( 'ac:=noeval(ac)' )
		),
  SeeAlso(Entry, ID, SearchID, Sequence, Match, PatEntry, AC, SearchAC,
	SP_Species, SPCommonName, Species_Entry )
):


Sequences_Description := Description(
  iterator( Sequences ),
  Summary('iterates over all entries in a database'),
  CallingSequence( 'for z in Sequences() do ... od;' ),
  Returns(Sequence),
  Synopsis('This is an iterator which returns all the
sequences from the default database (stored in DB).
The sequences are returned in order, ie. Sequence(Entry(1)),
Sequence(Entry(2)), etc.' ),
  SeeAlso( Entry, GetEntryInfo, GetEntryNumber, Sequence, Entries,
	PatEntry, ID, AC, iterator )
):


Sequence_Description := Description(
  function( Sequence),
  Summary ('Searching and retrieving sequences in the database DB'),
  CallingSequence(noeval(Sequence(off)) ),
  Parameters(['off',{integer,string,list,structure},
	'entries or list of entries in the database DB'],
	['','','Data structure of type PatEntry, AC or ID'] ),
  Returns(Sequence ),
  Synopsis('Sequence will return the peptide or nucleotide sequence
pointed by the argument(s).  This normally consists of the field
enclosed by the tags <SEQ> and </SEQ>.  Sequence returns a string
or an expression sequence of strings.  When the argument is an ID
or an AC structure, the database is searched for the corresponding
ID or AC.  If the argument is an integer, it is taken to be a
database offset into a sequence.  In this case the maximal sequence
starting at that offset is returned.  Otherwise, the arguments are
treated as the arguments for Entry, and their sequences extracted.' ),
  Examples( FakeReadDb,
	's1 := Sequence(Entry(1))',
	'Sequence(PatEntry(10000..10001))',
	'Sequence(AC(''P11341''))',
	'Sequence(ID(''ID5B_PROJU''))',
	'GetEntryNumber(s1)',
	Hide( 's1:=noeval(s1)') ),
  SeeAlso(Entry, ID, SearchID, Sequence, Match, PatEntry, AC, SearchAC,
	Species_Entry )
):



DbToDarwin_Description := Description(
  function(DbToDarwin ),
  Summary( 'Make a darwin-readable version of SwissProt' ),
  CallingSequence(noeval(DbToDarwin(inp, outfile, descr, TagsToKeep)) ),
  Parameters(['inp',string,'the complete input database as a string' ],
		['outfile',string,'name of the output file (database)'],
		['descr',string,'any commentary'],
		['TagsToKeep',list(string),'tags to keep from SwissProt'] ),
  Returns( 'NULL' ),
  Synopsis('Converts a SwissProt formatted text (inp) into a file
(outfile) usable by Darwin.  This program requires a lot of main
memory, (as much the original input file).  Make sure that you have
enough memory by using (in unix) "unlimit datasize memoryuse".' ),

Paragraph( -2, ' Once the new database is created, the first time
the command  "ReadDb(SwissProt40);"  is executed,
the index of the database will be built.  Building the index
can take quite a bit of CPU time.  This time is spent only once;
future uses of the database will not require any index building.
You will find that Darwin
creates a file named "SwissProt40.tree".  This index file is the Pat
tree for all the peptides and is needed for most of the basic
operations of Darwin.  You must have write permissions
in the directory in which the database is stored to create the
tree (only the first time the database is loaded).
If an index is not needed (no fast searches will be possible),
creating an empty SwissProt40.tree file will indicate to ReadDb
that the user does not want an index.'),
  Examples( 
	Fake('DbToDarwin( ReadRawFile(''sprot40.dat''), ''SwissProt40'',
	ReadRawFile(''relnotes.txt''), [''AC'',''DE'',''OS'',''KW''] )','' ) ),
  SeeAlso( 'DB', ReadDb, GenomeSummary, ConsistentGenome )
):

GetEntryInfo_Description := Description(
  function(GetEntryInfo ),
  Summary('selected tag information from a database entry'),
  CallingSequence(noeval(GetEntryInfo(EntryDescr,tag1,tag2)) ),
  Parameters(	['EntryDescr',{integer,string,list},
	'an entry, entry offset or a list of same'],
		['tag1',string] ,
		['tag2','optional tags'] ),
  Returns(expseq(string)),
  Synopsis('Return the information tags (tag1 and additional
optional tags) for an entry given by offset or several entries
given by an Entry data structure.  The function returns an
expression sequence of string, two elements for each entry
and tag - the first being the tag and the second being the
information for that tag.' ),
  Examples( FakeReadDb,
		'GetEntryInfo(100,''DE'')',
		'GetEntryInfo([Entry(1,2)],''AC'',''ID'' )' ),
  SeeAlso(SearchTag, Entry, GetEntryNumber,SearchID, SearchAC, Species_Entry)
):

GetEntryNumber_Description := Description(
  function( GetEntryNumber),
  CallingSequence(noeval(GetEntryNumber(offset, df)) ),
  Parameters(['offset',{integer,string},'an offset of an entry or an entry'],
		['df',database,'optional - will default to DB if assigned'] ),
  Returns(integer ),
  Synopsis('Return the number of the entry which contains the
given offset in df (default DB).  If the argument is a string, it is
assumed to be part of the database - in which case the entry number
including the beginning of the string is returned.' ),
  Examples( 'a := Entry(1)',
	'GetEntryNumber(a)',
	'GetEntryNumber(34675449)', Unassign('a') ),
  SeeAlso(Entry, GetEntryInfo, TextHead, GetOffset )
):


Species_Entry_Description := Description(
  function( Species_Entry ),
  Summary('find all the entries for a given species'),
  CallingSequence( noeval(Species_Entry(specname)) ),
  Parameters( [specname,string,'species name(s)'] ),
  Returns( list(Entry) ),
  Synopsis( 'Species_Entry returns all the entries in DB (which must
be assigned a sequence database) which match the given specname.
This assumes that the database has a field tagged with <OS>..</OS>
where the species information is available.
This is rather specific of SwissProt.
The first time Species_Entry is called, it builds a table of species
and it may require some time to compute.  Following calls will be
much more efficient.' ),
  Examples( 'Species_Entry(''Abies firma'')' ),
  SeeAlso( Species_Entry, SearchID, GetEntryInfo, Species_Entry, SP_Species,
	SPCommonName, SearchAC, DbToDarwin )
):


SP_Species_Description := Description(
  function( SP_Species ),
  Summary('find all the names of species in the database'),
  CallingSequence( noeval(SP_Species(taxon)) ),
  Parameters( [taxon,string,'optional taxonomic classification'] ),
  Returns( set(string) ),
  Synopsis( 'SP_Species scans the database assigned to DB
and returns the names of all the species (or all the species
of the given taxonomic classification).  This assumes that
the database is a SwissProt database or that at least it has
the OC tags with taxonomic information.
The matching of the taxonomic information is done in a textual
and case insensitive mode.
If this results in an ambiguous selection, it is possible to
include a longer portion of the taxonomic information
(see examples).' ),
  Examples( 'SP_Species(Abies)',
	'SP_Species(Pinus)',
	'SP_Species(''Pinaceae; Pinus'')' ),
  SeeAlso( Species_Entry, SearchID, GetEntryInfo, SP_Species,
	SPCommonName, SearchAC, DbToDarwin )
):


SPCommonName_Description := Description(
  function( SPCommonName ),
  Summary('common name of the species of the entry or scientific name'),
  CallingSequence( noeval(SPCommonName(entry)) ),
  Parameters( [entry,anything,'any description of an entry or entry number'] ),
  Returns( string ),
  Synopsis( 'SPCommonName finds the common name of the species
of the given entry.  If the input is the scientific name of a
species, SPCommonName will try to locate an entry with that
name to use it.  The common name is found within parenthesis
in the OS entry in SwissProt databases.  If the database in DB
does not conform to this rule, the function may not work properly.
If no common name is found, it returns the species name.
If no species name is found, it returns the AC or ID or "no name".
This function is useful to provide simple labels for plots.'),
  Examples( 'SPCommonName(AC(P13475))',
	'SPCommonName(''Raphicerus campestris'')',
	'SPCommonName(AC(P00083))' ),
  SeeAlso( SearchID, GetEntryInfo, Species_Entry, SP_Species,
	SPCommonName, SearchAC, DbToDarwin )
):


SeeAlsoAAA := SeeAlso(BBBToInt, BToInt, BaseToInt, IntToB, IntToBBB,
IntToBase, CIntToA, CIntToAAA, CIntToAmino, IntToCodon, CIntToInt,
CodonToA, CodonToInt, GeneticCode, CodonToCInt, CIntToCodon,
aminoacids, AToInt, AminoToInt, IntToAAA, IntToA, IntToAmino, AAAToInt,
CodonCode, AToCodon, CodonToInt, AToCInt, IntToCInt ):

SeeAlsoDNA := SeeAlso( BBBToInt, BToInt, BaseToInt, IntToB, IntToBBB,
IntToBase, CIntToA, CIntToAAA, CIntToAmino, IntToCodon, CIntToInt,
AToCInt, IntToCInt, CodonToInt, CodonToA, AminoToInt, GeneticCode, 
CodonToCInt, CIntToCodon, Complement, Reverse, antiparallel, 
AltGenCode, AToCodon ):

GetResidentPeakMemory_Description(
  function(GetResidentPeakMemory),
  Summary('Return the peak resident memory used by the process'),
  CallingSequence(noeval(GetResidentPeakMemory())),
  Returns(numeric),
  Synopsis('This function returns the peak resident memory usage
of this darwin process. It can be useful in environments where a
limit on memory usage is enforced'),
  Examples(GetResidentPeakMemory())
):

GetResidentMemory_Description(
  function(GetResidentMemory),
  Summary('Return the current resident memory used by the process'),
  CallingSequence(noeval(GetResidentPeakMemory())),
  Returns(numeric),
  Synopsis('This function returns the current resident memory usage
of this darwin process. It can be useful in environments where a
limit on memory usage is enforced'),
  Examples(GetResidentMemory())
):


AToCInt_Description := Description(
  function(AToCInt ),
  Summary ('One Letter Amino Acid Name to List of Codon Integers '),
  CallingSequence(noeval(AToCInt(AA)) ),
  Parameters(['AA',string,'amino acid 1 letter code']),
  Returns(list),
  Synopsis('This function converts an amino acid 1 letter code into
a list of the corresponding codons. The amino acid 1 letter code
for the stop codons is ''$''. ' ),
  Examples('AToCInt(''$'')','AToCInt(L)' ),
  SeeAlsoAAA
):

IntToCInt_Description := Description(
  function(IntToCInt ),
  Summary ('Amino Acid Integer to List of Codon Integers '),
  CallingSequence(noeval(IntToCInt(AA)) ),
  Parameters(['AA',posint,'amino acid integer']),
  Returns(list),
  Synopsis('This function converts an amino acid integer code into
a list of the corresponding codon integers. It will convert the
symbol for a stop codon ''$'' into a list of stop codons. ' ),
  Examples('IntToCInt(''$'')','IntToCInt(4)' ),
  SeeAlsoAAA
):

AltGenCode_Description := Description( function(AltGenCode),
  Summary( 'Use Alternative Translation Tables' ),
  CallingSequence( noeval(AltGenCode(transl_table,codon))),
  Parameters( ['transl_table',integer,'alternative translation table'],
	['codon',string,'3 DNA bases']),
  Returns(list),
  Synopsis(' AltGenCode takes a 3 letter codon as an input and returns
a list of the amino acid(s) for which the triplet codes. A codon has
more than one translation when, in addition to its normal translation,
it is used as an alternative start codon (M). Absent codons are not
designated as such.  They will return the translation of the standard
genetic code.  The translation tables are the same as those of the reference
website.  Additional initiation codons may be possible. See the website for
more information and a list of the organisms that use each code.'),
'',
Table( center, gutter=5, ColAlign('l','l'), Row('table number','description'), Rule,
Row('1', 'The Standard Code'),
Row('2', 'The Vertebrate Mitochondrial Code'),
Row('3', 'The Yeast Mitochondrial Code'),
Row('4', 'The Mold, Protozoan, and Coelenterate Mitochondrial '),
Row(' ', 'Code and the Mycoplasma/Spiroplasma Code'),
Row('5', 'The Invertebrate Mitochondrial Code'),
Row('6', 'The Ciliate, Dasycladacean and Hexamita Nuclear Code'),
Row('7', 'deleted'),
Row('8', 'deleted'),
Row('9', 'The Echinoderm Mitochondrial Code'),
Row('10', 'The Euplotid Nuclear Code'),
Row('11', 'The Bacterial and Plant Plastid Code'),
Row('12', 'The Alternative Yeast Nuclear Code'),
Row('13', 'The Ascidian Mitochondrial Code '),
Row('14', 'The Flatworm Mitochondrial Code'),
Row('15', 'Blepharisma Nuclear Code'),
Row('16', 'Chlorophycean Mitochondrial Code '),
Row('17', 'not available'),
Row('18', 'not available'),
Row('19', 'not available'),
Row('20', 'not available'),
Row('21', 'Trematode Mitochondrial Code '),
Row('22', 'Scenedesmus obliquus mitochondrial Code'),
Row('23', 'Thraustochytrium Mitochondrial Code') ),
'',
  References( 'www.ncbi.nlm.nih.gov/htbin-post/Taxonomy/wprintgc?mode=c#SG4' ),
  Examples( 'AltGenCode(11,TTG)',
	'AltGenCode(11,TTT)',
	'AltGenCode(12,CTG)'),
  SeeAlsoDNA
  ):


AToCodon_Description := Description(
  function(AToCodon ),
  Summary ('One Letter Amino Acid Name to List of Codons '),
  CallingSequence(noeval(AToCodon(AA)) ),
  Parameters(['AA',string,'amino acid 1 letter code']),
  Returns(list),
  Synopsis('This function converts an amino acid 1 letter code into
 a list of the corresponding codons. The amino acid 1 letter code
for the stop codons is ''$''. ' ),
  Examples('AToCodon(''$'')','AToCodon(L)' ),
  SeeAlsoAAA
):

IntToCodon_Description := Description(
  function(IntToCodon ),
  Summary ('Integer Amino Acid Representation to List of Codons '),
  CallingSequence(noeval(IntToCodon(AA)) ),
  Parameters(['AA',integer,'amino acid integer code']),
  Returns(list),
  Synopsis('This function converts an amino acid integer code
(see ?aminoacids) into a list of the corresponding codons.
The amino acid integer code for the stop codons is 22. ' ),
  Examples('IntToCodon(22)','IntToCodon(5)' ),
  SeeAlsoAAA
):

CIntToInt_Description := Description(
  function(CIntToInt ),
  Summary ('Integer Codon Representation to Amino Acid Number'),
  CallingSequence(noeval(CIntToInt(codon)) ),
  Parameters(['codon',integer, 'integer from 1 to 64'] ),
  Returns(1..22),
  Synopsis('This function converts the integer code for the Codons
from 1 to 64 (see ?CodonCode) to the corresponding amino acid
integers (1..20).  The stop codon returns 22.'),
  Examples('CIntToInt(37)', 'CIntToInt(1)' ),
  SeeAlsoAAA
):

CIntToA_Description := Description(
  function(CIntToA ),
  Summary ('Integer Codon Representation to Amino Acid Letter'),
  CallingSequence(noeval(CIntToA(codon)) ),
  Parameters(['codon',integer, 'integer from 1 to 64'] ),
  Returns( string ),
  Synopsis('This function converts the integer code for the Codons
from 1 to 64 (see ?CodonCode) to the corresponding amino acid
integer one letter code.  The stop codon returns $.' ),
  Examples('CIntToA(37)', 'CIntToA(1)' ),
  SeeAlsoAAA
):

CIntToAAA_Description := Description(
  function(CIntToAAA ),
  Summary ('Integer Codon Representation to Amino Acid 3-Letter Code'),
  CallingSequence(noeval(CIntToAAA(codon)) ),
  Parameters(['codon',integer, 'integer from 1 to 64'] ),
  Returns(string ),
  Synopsis('This function converts the integer code for the Codons
from 1 to 64 (see ?CodonCode) to the corresponding amino acid
three letter code.  The stop codon returns the string ''Stop''.' ),
  Examples('CIntToAAA(37)', 'CIntToAAA(1)' ),
  SeeAlsoAAA
):

CIntToAmino_Description := Description(
  function(CIntToAmino ),
  Summary ('Integer Codon Representation to Amino Acid Name'),
  CallingSequence(noeval(CIntToAmino(codon) )),
  Parameters(['codon',integer, 'integer code for codon between 1 and 64'] ),
  Returns(string ),
  Synopsis('This function converts the integer code for the Codons
from 1 to 64 (see ?CodonCode) to the corresponding amino acid
Name. The stop codon returns the string ''Stop''.' ),
  Examples('CIntToAmino(12)','CIntToAmino(49)' ),
  SeeAlsoAAA
):

BBBToInt_Description := Description(
  function( BBBToInt ),
  Summary ('Nucleic Acid Three Letter Code To Integer'),
  CallingSequence( noeval(BBBToInt(nuc)) ),
  Parameters( ['nuc' , string, 'three letter code for nucleic acid'] ),
  Returns( 1..5 ),
  Synopsis( 'This function converts the following three letter
codes for nucleic acids  Ade, Cyt, Gua, Thy, Ura  to the integers
1..5 respectively.' ),
  Examples( 'BBBToInt(''Ade'')' ),
  SeeAlsoAAA
):

BToInt_Description := Description(
  function( BToInt),
  Summary ('Nucleic Acid One Letter Code To Integer'),
  CallingSequence( noeval(BToInt(nuc)) ),
  Parameters( ['nuc', string, 'one letter code for nucleic acid'] ),
  Returns( 0..6 ),
  Synopsis( 'This function converts the following one letter codes for
nucleic acids A, C, G, T, U, X to the integers 1..6 respectively.  If
nuc is not one of these symbols, then 0 is returned.'),
  Examples( 'BToInt(''A'')', 'BToInt(''R'')' ),
  SeeAlsoAAA
):

BaseToInt_Description := Description(
  function( BaseToInt),
  Summary ('Nucleic Acid Name To Integer'),
  CallingSequence( noeval(BaseToInt(nuc)) ),
  Parameters( ['nuc', 'full name for a nucleic acid'] ),
  Returns( 1..5 ),
  Synopsis( 'This function converts the following full names
for nucleic acids  Adenine, Cytosine, Guanine, Thymine, Uracil
to the integers 1..5 respectively.' ),
  Examples( 'BaseToInt(''Adenine'')' ),
  SeeAlsoAAA
):

IntToBBB_Description := Description(
  function( IntToBBB ),
  Summary ('Integer to Three Letter Nucleic'),
  CallingSequence( noeval(IntToBBB( x )) ),
  Parameters( ['x', {1..5}] ),
  Returns( {'Ade', 'Cyt', 'Gua', 'Thy', 'Ura'} ),
  Synopsis('This function converts an integer between 1..5 into
the three letter code for nucleic acids Ade, Cyt, Gua, Thy, Ura
respectively.'
 ),
  Examples( 'IntToBBB(1)' ),
  SeeAlsoAAA
):

IntToB_Description := Description(
  function( IntToB ),
  Summary ('Integer to One Letter Nucleic'),
  CallingSequence( noeval(IntToB(x)) ),
  Parameters( ['x', {1..6}] ),
  Returns( {'A', 'C', 'G', 'T', 'U', 'X'} ),
  Synopsis('This function converts an integer between 1..6 into the one
letter code for nucleic acids A, C, G, T, U, X.' ),
  Examples( 'IntToB(1)', 'IntToB(6)' ),
  SeeAlsoAAA
):

IntToBase_Description := Description(
  function( IntToBase ),
  Summary ('Integer to Nucleic Acid Name'),
  CallingSequence( noeval(IntToBase(x)) ),
  Parameters(['x', {1..5}] ),
  Returns({'Adenine', 'Cytosine', 'Guanine', 'Thymine', 'Uracil'} ),
  Synopsis( 'This function converts an integer between 1..5 into
the full name for a nucleic acid Adenine, Cytosine,
  Guanine, Thymine, Uracil respectively.'),
  Examples( 'IntToBase(1)' ),
  SeeAlsoAAA
):

GetAaCount_Description := Description(
  function( GetAaCount),
  CallingSequence( noeval(GetAaCount( db )) ),
  Parameters( ['db', database] ),
  Returns( list(numeric, 20) ),
  Synopsis( 'This function counts the number of occurrences of each of the
twenty amino acids.  It returns a list in the standard amino acid
order.  This function requires that a patricia tree has been created
for the database assigned to DB.' ),
  Examples( FakeReadDb,
	'amino_acid_counts := GetAaCount(DB)' ),
  SeeAlso( GetAaFrequency )
):

GetAaFrequency_Description := Description(
  function(GetAaFrequency ),
  CallingSequence( noeval(GetAaFrequency( db )) ),
  Parameters( ['db', database] ),
  Returns( NULL ),
  Synopsis('This procedure computes the percent amino acid frequencies of
the database assigned to db. It prints out the results in a nice
format.  This function requires that a patricia tree has been created
for the database assigned to db.' ),
  Examples( FakeReadDb, Print( 'GetAaFrequency(DB)' ))
):


GetMolWeight_Description := Description(
  function(GetMolWeight ),
  CallingSequence( noeval(GetMolWeight(s)) ),
  Parameters( ['s', {string,list(string)},
	'an (or list of) amino acid sequence'] ),
  Returns( {numeric, list(numeric)} ),
  Synopsis( 'This function computes the molecular weight of an
amino acid sequence or list of amino acid sequences.' ),
  Examples( 'GetMolWeight(''IHGGCA'')', 
	'GetMolWeight([''VTTWD'', ''LIHAAG''])' ),
  SeeAlso( GetMostFrequentGrams )
):

AAAToInt_Description := Description(
  function( AAAToInt ),
  Summary('convert a 3 letter amino acid code to an integer'),
  CallingSequence( noeval(AAAToInt(aa)) ),
  Parameters( ['aa', string, 'three-letter amino acid abbreviations'] ),
  Returns( 1..20 ),
  Synopsis( ' This function converts a three letter abbreviation for an amino
acid to a posint between 1..20 according to the standard ordering of
amino acids. (see ?aminoacids)' ),
  Examples( 'AAAToInt(''Val'')' ),
  SeeAlsoAAA
):

AToInt_Description := Description(
  function( AToInt ),
  Summary('convert a 1 letter amino acid code to an integer'),
  CallingSequence( noeval(AToInt(aa)) ),
  Parameters( ['aa' , string, 'single letter amino acid abbreviations'] ),
  Returns( 0..21 ),
  Synopsis( 'This function converts a one letter abbreviation for an
amino acid to a posint between 1..20 according to the standard ordering
of amino acids (see ?aminoacids).  If aa is not a
amino acid abbreviation, the value 0 is returned.  If aa is the
unknown amino acid X, then the value 21 is returned.' ),
  Examples( 'AToInt(''V'')', 'AToInt(X)' ),
  SeeAlsoAAA
):

AminoToInt_Description := Description(
  function(AminoToInt ),
  Summary('convert an amino-acid name to an integer'),
  CallingSequence( noeval(AminoToInt(aa)) ),
  Parameters( ['aa', string, 'full names for amino acids'] ),
  Returns( 1..20 ),
  Synopsis('This function converts the full name for an amino acid
to a posint between 1..20 according to the standard ordering
of amino acids.' ),
  Examples( 'AminoToInt(''Serine'')' ),
  SeeAlsoAAA
):

IntToAAA_Description := Description(
  function( IntToAAA ),
  Summary('convert an integer into a 3 letter amino-acid name '),
  CallingSequence( noeval(IntToAAA(x)) ),
  Parameters( ['x', integer, 'an integer from 1 to 20'] ),
  Returns( string ),
  Synopsis( 'This function converts a posint into a three
letter abbreviation of an amino acid.  This follows the standard
ordering of amino acids. (See ?aminoacids)' ),
  Examples( 'IntToAAA(1)' ),
  SeeAlsoAAA
):

IntToA_Description := Description(
  function(IntToA ),
  Summary('convert an integer into a 1 letter amino-acid name '),
  CallingSequence( noeval(IntToA(x)) ),
  Parameters( ['x', integer, 'an integer from 1 to 20'] ),
  Returns( string ),
  Synopsis( 'This function converts a posint into a one
letter abbreviation of an amino acid.  This follows the standard
ordering of amino acids. (See ?aminoacids)' ),
  Examples( 'IntToA(20)' ),
  SeeAlsoAAA
):

IntToAmino_Description := Description(
  function( IntToAmino ),
  Summary('convert an integer into an amino-acid name '),
  CallingSequence( noeval(IntToAmino(x)) ),
  Parameters( ['x', integer, 'an integer from 1 to 20'] ),
  Returns( string ),
  Synopsis( 'This function converts a posint into the full
name for an amino acid following the standard
ordering of amino acids. (See ?aminoacids)' ),
  Examples( 'IntToAmino(15)' ),
  SeeAlsoAAA
):

CodonToCInt_Description := Description(
  function( CodonToCInt ),
  Summary('convert a 3-letter codon into a integer'),
  CallingSequence( noeval(CodonToCInt(code)) ),
  Parameters( ['code', string, 'three nucleic (DNA, RNA) bases (one letter each)'] ),
  Returns( 0..64 ),
  Synopsis( 'The 64 different codons over the alphabet {A, C, G,
T=U} are ordered from 1..64.  This function converts a codon to a
number between 1..64.  If it contains an invalid base or an X, it
returns 0.' ),
  Examples( 'CodonToCInt(''TTT'')' ),
  SeeAlsoAAA
):

CIntToCodon_Description := Description(
  function( CIntToCodon ),
  Summary('convert an integer into 3-letter codon'),
  CallingSequence( noeval(CIntToCodon(x)) ),
  Parameters( ['x', integer, 'an integer from 1 to 64'] ),
  Returns( 'three nucleic bases (one letter each'),
  Synopsis( 'The 64 different codons over the alphabet {A, C, G,
T=U} are ordered from 1..64.
This function converts a number between 1..64 to a codon.' ),
  Examples( 'CIntToCodon(15)' ),
  SeeAlsoAAA
):


GetComplement_Description := Description(
  function( GetComplement ),
  CallingSequence( noeval(GetComplement(nuc)) ),
  Parameters( [nuc, string, 'a string of DNA/RNA bases'] ),
  Returns( string ),
  Synopsis( 'Computes the complementary DNA/RNA strand for the given sequence.')
,
  Examples( 'GetComplement(''ACTTACG'')' ),
  SeeAlsoDNA
):

ComplementSequence_Description := Description(
  function(ComplementSequence ),
  CallingSequence( noeval(ComplementSequence( offset )) ),
  Parameters( ['offset', integer] ),
  Returns( [integer,integer] ),
  Synopsis( 'Returns the numeric offset of the sequence ofs is pointing to
and the negative offset of the original sequence passed to GetComplement.' ),
  SeeAlsoDNA
):


Reverse_Description := Description(
  function( Reverse ),
  Summary( 'Reverse a string or a list' ),
  CallingSequence( noeval(Reverse(s)) ),
  Parameters( [s, {string,list}, 'any string or list'] ),
  Returns( {string,list} ),
  Synopsis( 'Reverses a string or a list, i.e. the first character or element
becomes the last, the second the before-last, etc.' ),
  Examples( 'Reverse(''ACTTACG'')' ),
  SeeAlso( antiparallel, Complement, string, CreateString )
):

Complement_Description := Description(
  function( Complement ),
  Summary( 'complement of a DNA sequence' ),
  CallingSequence( noeval(Complement(nuc)) ),
  Parameters( [nuc, string, 'a string of DNA/RNA bases'] ),
  Returns( string ),
  Synopsis( 'Computes the complement DNA/RNA of the given sequence.
For more clarity, the antiparallel of AACC is GGTT.
The reverse of AACC is CCAA and the Complement of AACC is TTGG.
The Complement of a DNA sequence does
not form a double helix with the sequence.' ),
  Examples( 'Complement(''ACTTACG'')' ),
  SeeAlsoDNA
):


Matrices_Description := Description(
  function( Matrices ),
  CallingSequence( noeval(Matrices()) ),
  Returns( NULL ),
  Synopsis( 'This function loads various peptide scoring matrices
including the Gonnet/Benner PAM matrices, Blosum{50,60,62,70},
UNITARY, UNITARY2, RDDH250 (see `Amino Acid Substitutions in
Structurally Related Proteins'', JMB (1988) 204, 1019-1029.
by Risler, Delorme, Delacroix and Henaut.), PIMA.' ),
  SeeAlso( DayMatrix, CreateDayMatrix, CreateDayMatrices )
):

antiparallel_Description := Description(
  function( antiparallel ),
  Summary( 'reverse complement of a DNA sequence' ),
  CallingSequence( noeval(antiparallel( seq )) ),
  Parameters( ['seq', string, 'a DNA/RNA sequence'] ),
  Returns( string ),
  Synopsis( 'Computes the antiparallel sequence of an DNA/RNA sequence.
This is the complement in reverse order.
For more clarity, the antiparallel of AACC is GGTT.
The reverse of AACC is CCAA and the Complement of AACC is TTGG.
The antiparallel of a DNA sequence describes a molecule that would
form a double helix with the sequence.' ),
  Examples( 'antiparallel(''ACCUUC'')' ),
  SeeAlsoDNA
):


DayMatrix_Description := Description(
  structure(DayMatrix),
  Summary('similarity scoring matrix or Dayhoff matrix'),
  CallingSequence( noeval(DayMatrix( PAM )),
	noeval(CreateDayMatrix('logPAM1',PAM)),
	noeval(CreateDayMatrices()),
	noeval(CreateOrigDayMatrix()) ),
  Selectors(
[DelCost,procedure,'proc(k,pam) gives cost of k-long indel'],
[Dimension,posint,'dimension of the similarity matrix'],
[FixedDel,numeric,'fixed cost (opening) for affine indels'],
[IncDel,numeric,'incremental cost for affine indels'],
['logPAM1',matrix,'rate matrix used for this DayMatrix'],
[Mapping,procedure,'proc to map symbols to matrix indices'],
[MaxOffDiag,numeric,'maximum similarity for distinct residues'],
[MaxSim,numeric,'maximum similarity score in the matrix'],
[MinSim,numeric,'minimum similarity score in the matrix'],
[PamDistance,numeric,'PAM distance of this matrix'],
[PamNumber,numeric,'PAM distance of this matrix'],
[Sim,matrix(numeric),'Similarity matrix of scores (see below)'],
[StopSimil,numeric,'cost of matching a stop codon'],
[type,symbol,'type of scoring matrix, Peptide or Nucleotide'],
NULL ),
  Synopsis( 'A DayMatrix is the data structure or class which
holds similarity scores computed from mutation matrices.
The matrices are used for alignment of sequences.
The scores have a precise mathematical meaning: they are 10
times the log10 of the probability that the alignment comes
from homology as opposed to a random coincidence.  Hence
alignment scores give a rough estimate of how rare the
alignment is if it were produced by chance only.
The functions which create DayMatrices (CreateDayMatrices)
normally assign a dense array of DayMatrix to the variable DMS
(to allow estimation of distances between sequences) and a
250-PAM matrix to DM (the most commonly used matrix).
Currently, DayMatrices are internal objects.  The functions
mentioned in the Template part above are used to create DayMatrices.
Some other commonly used scoring matrices can be obtained by
the command Matrices().
When DayMatrix is used as a constructor (first entry above),
it searches the list of DayMatrix DMS for
a matrix of the right PAM and returns it.  If none is found, it
calls CreateDayMatrix to build an appropriate one.'),
Paragraph( -2, 'When selecting the similarity matrix from a
DayMatrix (selector Sim), a new matrix is constructed and
returned.  If the selection on Sim is immediately followed
by two indices, then no matrix is constructed and the corresponding
entry of the Dayhoff matrix is returned.  For this special case,
(e.g. DM[Sim,a,b]), the selectors a and b can be the one letter
codes for the amino acids.  This is more efficient and simpler
than invoking the AToInt conversion.' ),
  Examples( Fake( 'CreateDayMatrices()', '' ),
	'DM[Sim,1,1]',
	'DMS[100,Sim,L,I]',
	'DayMatrix(316)' ),
  SeeAlso( DayMatrix, CreateDayMatrix, CreateDayMatrices, CreateOrigDayMatrix,
	SearchDayMatrix, Matrices )
):


database_Description := Description(
  structure(database),
  Summary('Peptide or Nucleotide database'),
  CallingSequence( noeval(ReadDb( dbname )) ),
  Returns( database ),
  Selectors(
['Entry,i',string, 'the offset into the database of the ith entry.'],
['','', 'For programming convenience, the offset of the beyond'],
['','', 'last entry is defined as DB[TotChars]'],
[FileName, string, 'name of the external file containing the database'],
['Pat,i', integer, 'the ith entry of the Pat index on the data, an'],
['','', 'integer offset'],
[string, string, 'the entire database as a string'],
[TotAA, posint, 'number of amino acids or bases in the database'],
[TotChars, posint, 'number of characters in the database'],
[TotEntries, posint, 'number of entries in the database'],
[type, string, 'dna, rna, mixed or peptide']
 ),
  Synopsis( 'A database (DNA, RNA, mixed or peptide) is loaded with the
command ReadDb.
The database needs to be loaded for most operations involving sequences and
alignments.  The database is always available in the global variable DB.
A database can be assigned to any other name, but certain operations,
like finding an Entry, or using the Pat index, will perform on the
database which is assigned to the global variable DB.
All the selectors are read-only, they cannot be modified.' ),
Paragraph( -2, 'The database consists of an SGML-formatted file which
contains the information about entries and sequences.
For a file to be successfully loaded as a database, there have to be
entries (tagged between <E> and </E>).
Within each entry there should be a sequence (tagged between <SEQ> and
</SEQ>) of peptides, DNA or RNA.
The first time that a database is loaded, two index files are constructed.
One contains the Pat index and it is stored under the name dbname.tree
and the other is a quick reference for entries and is stored under the
name dbname.map.
If the database under dbname is changed, these two files (dbname.tree and
dbname.map) should be removed to force ReadDb to rebuild them.' ),
Paragraph( -2, 'The Pat index maintains a total order among all the
subsequences of the SEQ fields of the entries.
There are as many entries in the Pat index as amino acids (or bases)
in the entire database.
If a Pat index is not desired, creating a null dbname.tree file
will prevent ReadDb of building a Pat index.' ),
  Examples( FakeReadDb ),
  SeeAlso( AC, Entry, GetOffset, ID, Offset, PatEntry, ReadDb, SearchDb,
	SearchFrag, SearchID, SearchSeqDb, SearchTag,
	Sequence, GenomeSummary, ConsistentGenome )
):


GenomeSummary_Description := Description(
  structure( GenomeSummary ),
  Summary('summary information of a database file'),
  CallingSequence( noeval(GenomeSummary( 'DB' )) ),
  Parameters( ['DB', database, 'database structure to create a summary'] ),
  Returns( GenomeSummary ),
  Selectors(
   [FileName, string, 'name of external file containing the database'],
   [string, string, 'the entire header of the database as a string'],
   [TotAA, posint, 'number of amino acids or bases in the database'],
   [TotChars, posint, 'number of characters in the database'],
   [TotEntries, posint, 'number of entries in the database'],
   [type, string, 'dna, rna, mixed or peptide'],
   [EntryLengths,list(posint), 'length of each entry'],
   [Id,string, '5-letter code (SwissProt) for species/genome'],
   [Kingdom,string, 'either Bacteria, Archaea or Eukaryota'],
   [Lineage,list(string), 'Lineage as a list (from OS tags)'],
   [Genus,string,'First part of the scientific name'],
   [Epithet,string,'Second part of the scientific name'],
   [sgml_tag,string, 'The contents of the tag in the database header']
 ),
  Synopsis( 'GenomeSummary provides an alternative to loading a database
when the sequences themselves are not needed.
Typically, the database is loaded, then GenomeSummary is run and its
results are stored in a file for later reading.
In this way, all of the data except for the sequences themselves, is
available and many genomes can be loaded into a darwin session.'),
  Paragraph( -2, 'GenomeSummary has all the selectors which are
available for a database (except for Entry and Pat which are can only
be used if the sequences are present).
Additionally it provides a few additional selectors.
The EntryLengths contains the length of the sequence of each entry.
The string selector, does not select the entire text of the database,
just the text that is before the first entry.
This is normally called the header of the database.
In the header there are several useful tags which describe the entire
database, for example, 5-letter code, kingdom, lineage, etc.
This information is available directly through selectors.
Any other tagged information in the header can be selected with the
name of the tag as a selector.' ),
  Examples( Fake( 'ReadDb(''/home/darwin/DB/genomes/ECOLI/ECOLI.db''):
> gs := GenomeSummary(DB):
> gs[TotAA]','1358990'),
Fake( 'gs[Lineage]','[Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, 
Enterobacteriaceae, Escherichia, Escherichia coli]'),
Fake('print(gs)','  FileName: /home/darwin/DB/genomes/ECOLI/ECOLI.db
    string: <DBNAME>Escherichia coli K-12 MG1655 complete genome.</DBNAME><D...
     TotAA: 1358990
  TotChars: 6806443
TotEntries: 4289
      type: Peptide
        Id: ECOLI
   Kingdom: Bacteria
   Lineage: [Bacteria, Proteobacteria, Gammaproteobacteria, Enterobacteriales, Enterobacteriaceae, Escherichia, Escherichia coli]') ),
  SeeAlso( ReadDb, database, 'DB', Entry, Sequence, ConsistentGenome )
):


ConsistentGenome_Description := Description(
  structure( ConsistentGenome ),
  Summary('check the consistency of a database file'),
  CallingSequence( noeval(ConsistentGenome( name )) ),
  Parameters( [name, string, '5-letter name of a species/genome'] ),
  Returns( 'NULL' ),
  Synopsis( 'This function check various aspects of consistency
of a database file which contains a single genome.
The database should have been loaded with ReadDb before calling
this function.
Various header fields should be present, (SCINAME, KINGDOM,
5LETTERNAME and optionally ALTGENETICCODE).
The entries should contain also a DNA entry, which is checked to
be in accordance with the protein sequence.
This function will print error messages of the inconsistencies found.
For some errors, like identically duplicated sequences, it will
print editor commands (vi) to correct the problems.' ),
  SeeAlso( ReadDb, database, 'DB', Entry, Sequence, GenomeSummary )
):


DayMatrixScale_Description := Description(
  function( DayMatrixScale ),
  CallingSequence( noeval(DayMatrixScale( dm )) ),
  Parameters( ['dm', DayMatrix ] ),
  Returns( numeric ),
  Synopsis( 'Computes the scaling factor lambda of dm such that
sum (f[i]*f[j]*exp(lambda*dm[Sim,i,j])) = 1.
For Dayhoff-like matrices DM, DayMatrixScale (DM) = ln (10) / 10.'
 ),
  Examples( 'DayMatrixScale( DM )' ),
  SeeAlso( CreateOrigDayMatrix, DayMatrix, CreateDayMatrices, SearchDayMatrix )
):

CodonToA_Description := Description(
  function( CodonToA ),
  CallingSequence( noeval(CodonToA( triple )) ),
  Parameters( ['triple', 'a 3 letter DNA/RNA sequence'] ),
  Returns( 'one letter amino acid description' ),
  Synopsis('This function converts a 3 letter DNA/RNA sequence into the
amino acid specified by the genetic code.  It returns $ when the given codon
corresponds to the stop codon.' ),
  Examples( 'CodonToA(''UUU'')' ),
  SeeAlsoAAA
):

CodonToInt_Description := Description(
  function( CodonToInt ),
  CallingSequence( noeval(CodonToInt( UUU )) ),
  Parameters( ['UUU', 'a three RNA base sequence (one letter each)'] ),
  Returns( 1..22 ),
  Synopsis( 'This function converts a three RNA base sequence to the
amino acid number it specifies according to the standard genetic code.
If the triplet is unknown, the value 21 is returned.  If it is a
stop codon, it returns 22.'),
  Examples( 'CodonToInt(''UUU'')' ),
  SeeAlsoAAA
):

CreateDayMatrix_Description := Description(
  function( CreateDayMatrix ),
  CallingSequence( noeval(CreateDayMatrix( LogMutMatrix, PamNumber )) ),
  Parameters(
['LogMutMatrix', array(array(numeric)),'logarithm of a 1-PAM mutation matrix'],
['PamNumber', numeric,'desired PAM distance of the result'],
['',posint..posint,'range of integer PAM distances'] ),
  Returns( {DayMatrix,list(DayMatrix)} ),
  Synopsis( 'Computes a similarity scoring matrix
(usually called Dayhoff matrix) from a the logarithm of a
1-PAM mutation matrix (LogMutMatrix) and a PAM distance PamNumber.
CreateDayMatrices() assigns the global variable logPAM1 a logarithm
of a 1-PAM mutation matrix.
If the second argument is an integer range, a list of PAM matrices
with all the PAM values in the range will be computed.' ),
  Examples( 'CreateDayMatrix( NewLogPAM1 , 250)' ),
  SeeAlso( DayMatrix, CreateDayMatrices, CreateOrigDayMatrix, SearchDayMatrix )
):

CreateOrigDayMatrix_Description := Description(
  function( CreateOrigDayMatrix ),
  CallingSequence( noeval(CreateOrigDayMatrix( Mutations, AaCounts, PamNumber )),
	noeval(CreateOrigDayMatrix(mutations, counts, 1..UpperPam)) ),
  Parameters( 	['Mutations', array(numeric, 20, 20)], 
		['AaCounts', array(numeric, 20)], 
		['PamNumber', numeric] ),
  Returns( {DayMatrix, list(DayMatrix)} ),
  Synopsis( 'This function computes a Dayhoff matrix (structured
type DayMatrix) computed by the method first given by Dayhoff
et. all cite{DayhoffOS78} given an
observed mutation matrix mutations, a frequency vector counts and
a PAM distance PAM (or range of PAM distances beginning at 1).' ),
  Examples( 'OrigTot := [87, 41, 40, 47, 33, 38, 50, 89, 34, 37,85, 81, 15, 40, 51, 70, 58, 10, 30, 65]', 
	'OrigFreq := OrigTot/sum(OrigTot)', 
	'OrigDM := CreateOrigDayMatrix(Mutations1978, OrigFreq, 250)' ),
  SeeAlso( DayMatrix, CreateDayMatrix, CreateDayMatrices, SearchDayMatrix )
):

CreateDayMatrices_Description := Description(
  function( CreateDayMatrices ),
  Summary( 'Create all the Dayhoff matrices needed' ),
  CallingSequence( noeval(CreateDayMatrices()),
        noeval(CreateDayMatrices(Name)),
		noeval(CreateDayMatrices(Counts)),
		noeval(CreateDayMatrices(Q,freqs)) ),
  Parameters(
   [Counts,matrix,
	'(optional) a symmetric aa mutation count matrix'],
   [mapping, procedure,
	'(optional) a mapping between symbols and posints'],
   ['', type=anything,
	'(optional) matrices will be of the given type'],
   ['Q',matrix,'(optional) a rate matrix'],
   ['freqs',array,'(optional) frequencies (if called with Q)'],
   ['name',string,'(optional) name of a substitution model (currently allowed are JTT, LG and WAG)']),
  Returns( NULL ),
  Synopsis( 'This function creates all the Dayhoff matrices
needed for other alignment functions to work.
It performs the following four calculations:' ),

Paragraph( -2, '(1) It assigns a Dayhoff matrix computed at PAM
distance 250 to the global variable DM.' ),

Paragraph( -2, '(2) It computes 1266 Dayhoff matrices for various
PAM distances between 0.049 and 1000 and assigns the list of
such matrices to the global variable DMS.' ),

Paragraph( -2, '(3) It computes the amino acid natural frequencies
and assigns them to the global variable AF.' ),

Paragraph( -2, '(4) It assigns the global variable logPAM1 with
the logarithm of the mutation matrix (at PAM distance 1) being used.' ),

Paragraph( -2, 'By default, with no arguments, it uses the data derived from
the entire SwissProt database in Nov 1991 (Benner, Gonnet
and Cohen).  This can be altered in four ways:' ),

Paragraph( -2, '(a) by assigning the global variable NewLogPAM1 with
the logarithm of a PAM 1 mutation matrix, all the computations
will be based on this mutation matrix.' ),

Paragraph( -2, '(b) by passing a count matrix as argument
all the computations will be based on this count matrix.
A count matrix has the counts of mutations (and non mutation on
the diagonal) for a large sample of alignments.
Normally if two amino acids X and Y are aligned, we will add
1/2 to Counts[X,Y] and 1/2 to Counts[Y,X].'),

Paragraph( -2, '(c) by calling the function with a rate matrix
and a frequency vector, the computations will be based on these
parameters'),

Paragraph( -2, '(d) by calling the function with the name of a specific 
substitution model (currently, JTT, LG and WAG are allowed). The 
computations will then be based on that model.'),

Paragraph( -2, 'If the counts are only on the amino acids A, C, G and T,
(and the rest of the counts are just 1 on the diagonal and 0 elsewhere),
the Dayhoff matrices produced are suitable to align DNA sequences.
Actually this is the standard and simplest way of aligning DNA
sequences.  The system knows about the following count matrices,
which can be used as argument of CreateDayMatrices:' ),

Table(center, gutter=3, ColAlign('l','l'),
Row('name','Description'), Rule,
Row('HumanMtDNA', 'Human mitochondrial DNA count matrix based on very short'),
Row( '', 'PAM evolution, taken from 86 full mtDNA genomes'),
Row( 'ViralRNA', 'Counts matrix derived from 50 RNA viruses' )),

  Examples( 'CreateDayMatrices()' ),
  SeeAlso( DayMatrix, CreateDayMatrix, CreateOrigDayMatrix, SearchDayMatrix ,
	CreateCodonMatrices)
):

SearchDayMatrix_Description := Description(
  function( SearchDayMatrix ),
  Summary( 'search an array of DayMatrix for a given PAM' ),
  CallingSequence( noeval(SearchDayMatrix( PAM, daymat )) ),
  Parameters( ['PAM', numeric, ' PAM distance for which matrix is sought'], 
	['daymat', array(DayMatrix), 'an array of Dayhoff matrices'] ),
  Returns( DayMatrix ),
  Synopsis( 'This function searches the list of
DayMatrix for the Dayhoff matrix calculated with PamNumber closest
to PAM.  This function assumes that daymat is in ascending order.' ),
  Examples( Fake('CreateDayMatrices()',''), 'SearchDayMatrix(250, DMS)' ),
  SeeAlso( DayMatrix, CreateDayMatrices, CreateOrigDayMatrix, CreateDayMatrix )
):

GetPosition_Description := Description(
  function(GetPosition ),
  CallingSequence(noeval(GetPosition(df,ofs)) ),
  Parameters(['df',database],['ofs',integer] ),
  Returns(list),
  Synopsis('Returns [pos, len] such that t is the complete sequence ofs is 
pointing to after execution of ''t := ofs + df[string]; t := t[1..len];''.' ),
  Examples( ),
  SeeAlso( )
):

GetIntrons_Description := Description(
  function(GetIntrons ),
  CallingSequence(noeval(GetIntrons(noeval(m))) ),
  Parameters(['m',NucPepMatch] ),
  Returns(list),
  Synopsis('Returns the introns derived from m. m[Introns] must be defined.' ),
  Examples( ),
  SeeAlso(NucPepMatch )
):


AlignNucPepMatch_Description := Description(
  function(AlignNucPepMatch ),
  CallingSequence( noeval( AlignNucPepMatch(npm,dm))),
  Parameters( [npm,NucPepMatch], [dm,DayMatrix] ),
  Returns( NucPepMatch ),
  Synopsis( 'Returns a new match with additional entries: NucGaps,
PepGaps and Introns defining its alignment.' ),
  Examples( ),
  SeeAlso(NucPepMatch )
):

GetAllNucPepMatches_Description := Description(
  function( GetAllNucPepMatches),
  CallingSequence(noeval(GetAllNucPepMatches(npm,D,goal)) ),
  Parameters(['npm',NucPepMatch],['D',DayMatrix],['goal',numeric] ),
  Returns(list ),
  Synopsis('Return the list of all NucPepMatch between the nucleotide
and the peptide sequences in npm reaching goal.' ),
  Examples( ),
  SeeAlso(NucPepMatch, GetAllMatches )
):

NucPepBackDynProg_Description := Description(
  function(NucPepBackDynProg ),
  Summary ('Backwards dynamic programming alignment for peptide and nucleotide sequences'),
  CallingSequence( noeval(NucPepBackDynProg( nuc, pep,
	noeval(DM), len1, len2, IntronScoring)) ),
  Parameters(   ['nuc',string,'a nucleotide sequence'],
		['pep',string,'a peptide sequence'],
		['DM',DayMatrix,'Dayhoff Matrix'],
		['len1',integer,'optional length of the 1st sequence'],
		['len2',integer,'optional length of the 2nd sequence'],
		['IntronScoring',list,'optional Intron Scoring list']
 ),
  Returns( ),
  Synopsis('Compute the similarity and lengths of the best alignment between nuc and
  pep using the Dayhoff matrix DM, the optional lengths len1 and len2 and
  the optional IntronScoring doing backwards dynamic programming. If the
  lengths are not given or -1, return the maximum similarity.' ),
  Examples( ),
  SeeAlso(AlignNucPepAll, AlignNucPepMatch, DynProgNucPepString, 
GlobalNucPepAlign, LocalNucPepAlign, LocalNucPepAlignBestPam,
NucPepDynProg, FindNucPepPam, NucPepMatch )
):

FindNucPepPam_Description := Description(
  function(FindNucPepPam ),
  Summary('Compute Pam estimate for a NucPepMatch' ),
  CallingSequence(noeval(FindNucPepPam(npm, noeval(DMS)) )),
  Parameters(['npm',NucPepMatch],['DMS',array(DayMatrix)] ),
  Returns( ),
  Synopsis('Computes the best pam estimate and its variance
for the given NucPepMatch.' ),
  Examples( ),
  SeeAlso(AlignNucPepAll, AlignNucPepMatch, DynProgNucPepString, 
GlobalNucPepAlign, LocalNucPepAlign, LocalNucPepAlignBestPam,
NucPepDynProg, NucPepBackDynProg, NucPepMatch )
):

NucPepDynProg_Description := Description(
  function(NucPepDynProg ),
  Summary('Compute a Nucleotide Peptide Alignment' ),
  CallingSequence(noeval(NucPepDynProg(nuc, pep,
	noeval(DM), len1, len2, IntronScoring)) ),
  Parameters(	['nuc',string,'Nucleotide Sequence'],
		['pep',string,'Peptide Sequence'],
		['DM',DayMatrix,'Dayhoff Matrix'],
		['len1',integer,'optional length of 1st sequence'],
		['len2',integer,'optional length of 2st sequence'],
		['IntronScoring',list,' Intron scoring']
 ),
  Returns( ),
  Synopsis('Compute the similarity and lengths of the best alignment between nuc and 
  pep using the Dayhoff matrix DM, the optional lengths len1 and len2 and
  the optional IntronScoring. If the lengths are not given or -1, return 
  the maximum similarity.' ),
  Examples( ),
  SeeAlso(AlignNucPepAll, AlignNucPepMatch, DynProgNucPepString, 
GlobalNucPepAlign, LocalNucPepAlign, LocalNucPepAlignBestPam,
FindNucPepPam, NucPepBackDynProg, NucPepMatch )
):

ParallelAllNucPepMatches_Description := Description(
  function( ParallelAllNucPepMatches),
  CallingSequence( noeval(ParallelAllNucPepMatches (npm, dm, goal) )),
  Parameters(['npm',list(NucPepMatch),'a Nucleotide Peptide Match'],
		['dm',{DayMatrix, list(DayMatrix)},' Dayhoff matrix or matrices'],
		['goal',numeric,'threshold value']),
  Returns( ),
  Synopsis('Does multiple GetAllNucPepMatches simultaneously. More efficient
than single GetAllNucPepMatches calls on some parallel machines only.' ),
  Examples( ),
  SeeAlso(NucPepMatch, GetAllNucPepMatches )
):

AlignNucPepAll_Description := Description(
  function( AlignNucPepAll),
  CallingSequence( noeval( AlignNucPepAll(nuc,dm,division,goal,pEntries))),
  Parameters( ['nuc',NucleotideString], ['dm', DayMatrix],
	[division, string], [goal, numeric], [pEntries, posint..posint] ),
  Returns( list(NucPepMatch) ),
  Synopsis( 'Match nuc against a complete PepDB or the entries in the
range given by pEntries of PepDB and return all matches reaching goal
using dm and intron scoring according to division.'),
  Examples( ),
  SeeAlso(NucPepMatch,LocalNucPepAlign,GetPosition,LocalNucPepAlignBestPam,
    GlobalNucPepAlign,GetPeptides,GetIntrons,Normalize,Denormalize,
    VisualizeGene,VisualizeProtein )
):

LocalNucPepAlignBestPam_Description := Description(
  function( LocalNucPepAlignBestPam),
  CallingSequence(noeval(LocalNucPepAlignBestPam(m)) ),
  Parameters(['m',NucPepMatch] ),
  Returns(NucPepMatch ),
  Synopsis('Apply LocalNucPepAlign and FindNucPepPam until a maximum is found.' ),
  Examples( ),
  SeeAlso(AlignNucPepAll, FindNucPepPam, Gene, GetPeptides, GetIntrons,
GlobalNucPepAlign, LocalNucPepAlign, NucPepMatch,
VisualizeGene, VisualizeProtein )
):

LocalNucPepAlign_Description := Description(
  function( LocalNucPepAlign),
  CallingSequence(noeval(LocalNucPepAlign(npm, D)) ),
  Parameters(['npm',NucPepMatch],['D',DayMatrix] ),
  Returns(NucPepMatch ),
  Synopsis('Return the NucPepMatch between the nucleotide and the peptide of
npm with the highest score.' ),
  Examples( ),
  SeeAlso( AlignNucPepAll, FindNucPepPam, Gene, GetPeptides, GetIntrons, 
GlobalNucPepAlign, LocalNucPepAlignBestPam, NucPepMatch, 
VisualizeGene, VisualizeProtein)
):

GlobalNucPepAlign_Description := Description(
  function( GlobalNucPepAlign),
  CallingSequence(noeval(GlobalNucPepAlign(noeval(m),noeval(DM))) ),
  Parameters(['m',NucPepMatch],['DM',DayMatrix] ),
  Returns(NucPepMatch ),
  Synopsis('Run the dynamic programming algorithm for the given Match with
the given DM matrix.' ),
  Examples( ),
  SeeAlso(AlignNucPepAll, FindNucPepPam, Gene, GetPeptides, GetIntrons,
LocalNucPepAlign, LocalNucPepAlignBestPam, NucPepMatch,
VisualizeGene, VisualizeProtein )
):

GetPeptides_Description := Description(
  function( GetPeptides),
  CallingSequence(noeval(GetPeptides(noeval(m))) ),
  Parameters( ['m',NucPepMatch]),
  Returns( ),
  Synopsis('Returns the peptide derived from m. m[NucGaps] and m[Introns] must be
defined. Note that amino acids derived from indels which are a multiple
of 3 do not always correspond to the reading frame implied by the
alignment.' ),
  Examples( ),
  SeeAlso(NucPepMatch )
):

Normalize_Description := Description(
  function( Normalize),
  CallingSequence(noeval(Normalize(noeval(m))) ),
  Parameters(['m',NucPepMatch] ),
  Returns(NucPepMatch ),
  Synopsis( 'Normalizes a match referencing (the complement of) an NucDB
database entry to refer to a sequence being present in memory.'),
  Examples( ),
  SeeAlso( Denormalize )
):

Denormalize_Description := Description(
  function( Denormalize),
  CallingSequence(noeval(Denormalize(noeval(m))) ),
  Parameters(['m',NucPepMatch] ),
  Returns(NucPepMatch ),
  Synopsis('Denormalizes a match referencing a sequence being present in
memory to refer to (the complement of) an NucDB database entry.' ),
  Examples( ),
  SeeAlso(Normalize )
):


NucPepRegions_Description := Description(
  function(NucPepRegions ),
  CallingSequence(noeval(NucPepRegions(npm )) ),
  Parameters(['npm',NucPepMatch,' a nucleotide peptide Match'] ),
  Returns(list),
  Synopsis('Converts an NucPepMatch into a list of alignment regions. Region formats are: 
  - [ALIGN, Sim, nucLen, pepLen] 
  - [NUCGAP, Sim, nucLen, 0] 
  - [PEPGAP, Sim, 0, pepLen] 
  - [INTRON, Sim, nucLen, 0]. 
  After r := NucPepRegions (m), the following equations hold: 
  sum (zip ((x->x[2])(r))) = m[Sim] 
  sum (zip ((x->x[3])(r))) = m[NucLength] 
  sum (zip ((x->x[4])(r))) = m[PepLength]. 
  If either PepDB or NucDB are not loaded, Sim will be 0 in ALIGN regions. 
  If no suitable Dayhoff matrix can be found, Sim will be 0 in ALIGN, 
  NUCGAP and PEPGAP regions.' ),
  Examples( ),
  SeeAlso(NucPepMatch )
):

DynProgNucPepString_Description := Description(
  function( DynProgNucPepString),
  CallingSequence(noeval(DynProgNucPepString(npm)) ),
  Parameters(['npm',NucPepMatch] ),
  Returns( ),
  Synopsis('Return two texts defining the alignment of NucPepMatch suitable
to print it.  npm[NucGaps], npm[PepGaps] and npm[Introns] must be defined.' ),
  Examples( ),
  SeeAlso(AlignNucPepAll, AlignNucPepMatch, Denormalize, 
DynProgNucPepString, FindNucPepPam, Gene, GetAllNucPepMatches, 
GetPeptides, GetIntrons, GetPosition, GlobalNucPepAlign, Intron, 
LocalNucPepAlign, LocalNucPepAlignBestPam,
Normalize, NucDB, NucPepDynProg, NucPepBackDynProg, NucPepMatch, 
NucPepRegions, ParallelAllNucPepMatches, PepDB, ScoreIntron,
VisualizeGene, VisualizeProtein )
):

NSubGene_Description := Description(
  function(NSubGene ),
  CallingSequence(noeval(NSubGene(g,baseRange)) ),
  Parameters(['g','Gene data structure'],
		['baseRange','posint..posint'] ),
  Returns(Gene ),
  Synopsis('Returns the modified Gene containing only bases in baseRange.' ),
  Examples( ),
  SeeAlso(Gene, PSubGene )
):

LinearIntron_Description := Description(
  structure(LinearIntron ),
  CallingSequence(noeval(LinearIntron(n, pam, minlen, F, I)) ),
  Parameters(['n','nucleotide sequence'],['pam',numeric],['minlen',integer],
	['F',numeric],['I',numeric] ),
  Returns( ),
  Synopsis('Computes and stores the general linear intron scoring
model. Use LinearIntron(minlen, F, I) to score F + (len - 1) * I
for any subsequence of length len >= minlen fulfilling the GT-AG rule.' ),
  SeeAlso( IntronModel)
):



Gene_Description := Description(
  structure( Gene ),
  CallingSequence( noeval(Gene(Division,NucEntry,Exons,PepOffset,AlignErrors))),
  Parameters(['Division','string'],
	       ['NucEntry','integer'],
	       ['Exons','list(posint..posint)'],
	       ['PepOffset','PepLength'],
	       ['AlignErrors','integer'] ),
  Returns(Gene ),
  Selectors (['Division',''],
		['NucEntry',''],
		['Exons','list of exon locations'],
		['Introns',''],
		['mRNA',''],
		['NucSequence',''],
		['PepOffset',''],
		['PepLength',''],
		['PepSequence',''],
		['AlignErrors',''] ),
  Synopsis('Data structure defining gene-peptide references.' ),
  Examples( ),
  SeeAlso(NSubGene, PSubGene, NucPepMatch )
):

IntronModel_Description := Description(
  structure( IntronModel),
  CallingSequence(noeval(IntronModel(Donor, InIntron, Acceptor, MinLen)) ),
  Parameters( ['Donor', 'GramSite'],
		['InIntron','GramRegion'],
		['Acceptor','GramSite'],
		['MinLen','posint'] ),
  Returns(IntronModel ),
  Selectors ( ['Donor', 'GramSite'],
		['InIntron','GramRegion'],
 		['Acceptor','GramSite'],
		['MinLen','posint']),
  Synopsis('Structure to hold intron scoring model data.' ),
  SeeAlso( LinearIntron )
):


Intron_Description := Description(
  structure( Intron),
  CallingSequence(noeval(Intron(n, pam, div)) ),
  Parameters(	[n,string,'nucleotide sequence'],
		[pam,numeric,'PAM distance'],
		[div,string, 'code of the division']),
  Returns(Intron ),
  Synopsis('Computes and stores the Bayesian probabilistic
intron scoring model.
Use Intron(div) to select the scoring model for division div.
Divisions are fun, inv, mam, pln, pri, pro, rod, vrt, any.' ),
  Examples( ),
  SeeAlso( )
):


PSubGene_Description := Description(
  function(PSubGene ),
  CallingSequence(noeval(PSubGene( g,new, newLength)) ),
  Parameters(	['PSubGene','Gene'],
		['new','{posint, posint..posint}'],
		['newLength','posint'] ),
  Returns(Gene ),
  Synopsis('Returns the modified Gene encoding the peptide at offset new
with length newLength or with amino acid range new.' ),
  Examples( ),
  SeeAlso(Gene, NSubGene )
):



DynProgScore_Description := Description(
  function( DynProgScore ),
  Summary('compute the forward phase of sequence alignment'),
  CallingSequence( noeval(DynProgScore(seq1,seq2,dm,modif)) ),
  Parameters(
    [seq1,{string,ProbSeq},'first sequence to be aligned'],
    [seq2,{string,ProbSeq},'second sequence to be aligned'],
    [dm,{DayMatrix,list(DayMatrix)}, 'Dayhoff matrix to use for the alignment'],
    [modif,{string,set(string)},'specification of alignment'] ),
  Returns( {['score:numeric',from1..to1,from2..to2], ['Score:numeric']} ),
  Synopsis( 'Computes the optimal cost of the alignment between
seq1 and seq2 using the Dayhoff matrix dm, a specified alignment mode
and a specified deletion cost model.  It returns a triplet:
[ Score, from1..to1, from2..to2 ] or [ Score ] where Score is
the optimal score of the alignment and seq1[from1..to1] and
seq2[from2..to2] are the selected portions of the sequences to align.
seq1 and seq2 can be either peptide sequences, nucleotide
sequences or probabilistic sequences, ProbSeq().
Modif is a set of strings which have the following meanings:' ),

Paragraph( -2, ' For the alignment type, one of the following
can be specified:' ),
Indent( 5, Paragraph( -10, 'Local - (default) a local alignment,
the subsequences of seq1 and seq2 which give the highest score.')),
Indent( 5, Paragraph( -10, 'Global - a global alignment,
the entire seq1 is matched against the entire seq2.' )),
Indent( 5, Paragraph( -10, 'CFE - cost-free ends, the entire seq1
is matched against seq2, but one deletion at the ends is not penalized.' )),
Indent( 5, Paragraph( -10, 'CFEright - cost-free ends, the entire seq1
is matched against seq2, but one deletion at the right
end is not penalized.' )),
Indent( 5, Paragraph( -10, 'Shake - align seq1 and seq2 up to the
point where the maximum score happens.  Then do the same backwards
and forwards until no improvements of the score happen.')),
Indent( 5, Paragraph( -10, 'MinLength(k) - align seq1 and seq2 as
in a Local alignment (starting anyplace, ending anyplace) but at
least k amino acids of each sequence are aligned.
I.e. the minimum of the aligned lengths is k or larger.')),

Paragraph( -2, ' For the deletion cost model, one of the following
can be specified:' ),
Indent( 5, Paragraph( -10, 'Affine - (default) deletion cost
of a gap of length k is FixedDel + IncDel*(k-1).  The values
for FixedDel and IncDel are taken from the Dayhoff matrix dm.')),
Indent( 5, Paragraph( -10, 'LogDel - logarithmic deletion cost,
the cost of a gap of length k is DelFixedLog + DelLog*log(k).
The values for DelFixedLog and DelLog are taken from the
Dayhoff matrix dm.')),

Paragraph( -2, ' For the type of result, any combination of the
following can be specified:' ),
Indent( 5, Paragraph( -10, 'JustScore - 
only the score is computed, and the locations of the match are not
returned (this makes the algorithm run faster for Local and CFE).')),
Indent( 5, Paragraph( -10, 'NoSelf - compute an alignment where
matches of a position with itself are disallowed.  This is relevant
when aligning a sequence with itself with the purpose of discovering
repeated motifs.')),

  Examples( FakeReadDb,
	'DynProgScore(AC(P00083),AC(P00091),DM,Local)',
	'DynProgScore(AC(P00083),AC(P00091),DM,Global)',
	'DynProgScore(AC(P00083),AC(P00091),DM,{CFE,JustScore})',
	'DynProgScore(''ADEFGHIKSDEFGHLK'',''ADEFGHIKSDEFGHLK'',DM,NoSelf)' ),
  SeeAlso( Align, Alignment, CreateDayMatrices, MAlign )
):

TotalAlign_Description := Description(
  function(TotalAlign ),
  CallingSequence(noeval(TotalAlign(m,noeval(DM), goal)) ),
  Parameters(['m',Match,'a Match'],
		['DM',DayMatrix,'a Dayhoff Matrix'],
		['goal',numeric,'a threshold value'] ),
  Returns(list(Match) ),
  Synopsis('The TotalAlign function implements the Smith-Waterman
algorithm SmithW81 with an extension to find all independent local
alignments of the complete sequences of ''m'' reaching a score of at
least ''goal''. The alignments are computed at PAM distance defined
by the similarity matrix DM.' ),
  Examples( ),
  SeeAlso( CreateDayMatrices, MAlign )
):


GetOffset_Description := Description(
  function( GetOffset ),
  Summary ('Gets an offset in the database for a string'),
  CallingSequence( noeval(GetOffset( seq ))),
  Parameters( ['seq', string, 'a string in or outside the database'] ),
  Returns( integer ),
  Synopsis( 'The GetOffset function finds the offset of a string
whether it is in the database or outside.  It is necessary when
we want to pretend that a string is a sequence in the database to
make it an argument of Match.
The GetOffset requires that the system variable DB must be assigned a
sequence database.'),
  Examples( FakeReadDb,
Fake( 'CreateDayMatrices()',''),
's1 := ''MSRYEKMFARLNERNQGAFVPFVTVCDPNAEQSYKIMETLVESGADALELGIPFSDP'':',
's2 := ''MLLLSVNPPLFIPFIVAGDPSPEVTVDLALALEEAGADLLELGVPYSDP'':',
'm3 := Match( GetOffset(s1), GetOffset(s2) )',
Unassign('s1','s2')
),
  SeeAlso(NucPepMatch, ReadDb, MAlign, TotalAlign )
):



FindEntropy_Description := Description(
  function( FindEntropy ),
  CallingSequence( noeval( FindEntropy( day ))),
  Parameters( ['day', DayMatrix] ),
  Returns( numeric ),
  Synopsis('Computes the relative entropy H of day, i.e.
how many bits of information are available per position of an
alignment. See S.F. Altschul, "Amino Acid Substitution Matrices
from an Information Theoretic Perspective", JMB 219(1991):555-565.' ),
  Examples( Fake('CreateDayMatrices()',''), 'FindEntropy(DMS[1])',
	'FindEntropy(DMS[500])', 'FindEntropy(DMS[1000])' )
):

EstimatePam_Description := Description(
  function( EstimatePam ),
  CallingSequence( noeval(EstimatePam( s1, s2, days )) ),
  Parameters( ['s1', string], ['s2', string], ['days', array(DayMatrix)]),
  Returns( '[Score,PamDistance,PamVariance]' ),
  Synopsis( 'Calculates the similarity score, Pam distance
and Pam variance for the alignment defined by s1 and s2.  Notice
that s1 and s2 are taken as aligned already, that is, they are
not re-aligned.  If s1 and s2 need to be aligned,
use DynProgStrings first.
The estimation of the Pam distance and variance is normally done
by Align when given an array of Dayhoff matrices.
If the the estimated distance is lower than 0.1 pam,
the estimate is also computed by expected values (the computation
of distances by maximum likelihood becomes less accurate).
This second estimate is stored in the global variable
ExpectedPamDistance.
The computation of the PamDistance by maximum likelihood
(exactly, not just for an existing DM in days)
is stored in the global variable MLPamDistance.' ),
  Examples( 'EstimatePam(''CITKLFDGDQVLY'', Mutate(''CITKLFDGDQVLY'', 100), DMS)' ),
  SeeAlso( CalculateScore, DynProgStrings, Align, EstimateCodonPAM, EstimateSynPAM, 
  EstimateLogEvalue )
):

CalculateScore_Description := Description(
  function( CalculateScore ),
  Summary('Score two sequences as is, without aligning them' ),
  CallingSequence(noeval(CalculateScore(seq1,seq2,'DM'))),
  Parameters( [seq1,string,'first sequence'],
	[seq2,string,'second sequence'],
	['DM',DayMatrix,'Dahyhoff matrix to score the sequences'] ),
  Returns(numeric),
  Synopsis( 'Calculate the score between two sequences, as is,
no alignment done.  Sequences may contain ''_'' indicating an indel.
An ''_'' matched against another ''_'' will not be scored any value,
like what happens as a result of a multiple alignment.' ),
  Examples( 'CalculateScore(CITKLWDGDQVLY,CLTKIFDGDQVIV,DM)' ),
  SeeAlso( EstimatePam, Align )
):

FindLongestRep_Description := Description(
  function( FindLongestRep ),
  CallingSequence( noeval(FindLongestRep( db )),
		   noeval(FindLongestRep( db, len)),
		   noeval(FindLongestRep( db, len, eb )) ),
  Parameters( ['db', database], ['len', integer], ['eb', integer] ),
  Returns( string ),
  Synopsis('Find the longest repetition(s) in the database db.  If len is
specified, then return only those repetitions longer than len.  If len and
eb are specified, then return repetitions longer than len - endbonus when
matching to the end of both sequences.  This command requires that a
pat index has been built for the database db' )
#  Examples( FakeReadDb,
#		'FindLongestRep(DB, 3000)', 
#		'FindLongestRep(DB, 3000, 20)' )
):

PerIdentToPam_Description := Description(
  function( PerIdentToPam ),
  Summary ('Compute PAM distance from percentage identity'),
  CallingSequence( noeval(PerIdentToPam( p )) ),
  Parameters( ['p', numeric,'percentage identity'] ),
  Returns( numeric ),
  Synopsis( 'Compute the PAM distance which results in the given
percentage identity.'),
  Examples( 'PerIdentToPam(17)' ),
  SeeAlso( PamToPerIdent )
):

PamToPerIdent_Description := Description(
  function( PamToPerIdent ),
  Summary ('Compute percentage identity from PAM'),
  CallingSequence( noeval(PamToPerIdent(p)) ),
  Parameters( ['p', numeric,'PAM distance'] ),
  Returns( numeric ),
  Synopsis('Compute the percentage identity that a pam distance will leave.' ),
  Examples( 'PamToPerIdent(250)' ),
  SeeAlso( PerIdentToPam )
):

ProbDynProg_Description := Description(
  function( ProbDynProg ),
  Summary ('Probabilistic dynamic programming'),
  CallingSequence( noeval( ProbDynProg( A, B, f, w, FixedDel, IncDel) )),
  Parameters( ['A', array(array(numeric))], 
		['B', array(array(numeric))], 
	      	['f', array(numeric)], 
		['w', posint], 
		['FixedDel', numeric],
	      	['IncDel', numeric] ),
  Returns( ),
  Synopsis('Probabilistic dynamic programming.'),
  Examples( ),
  SeeAlso( )
):

DynProgStrings_Description := Description(
  function( DynProgStrings ),
  Summary('compute score and aligned strings from a Match'),
  CallingSequence( noeval(DynProgStrings(m,dm)),
	noeval(DynProgStrings(m,dm,NoSelf)),
	noeval(DynProgStrings(al))),
  Parameters(['m',Match,'input Match'],['dm',DayMatrix,'scoring matrix'],
	[NoSelf,string,'(optional), no self alignments will be allowed'],
	[al,Alignment,'input Alignment object']),
  Returns( [[numeric,string,string],'[score,seq1,seq2]'] ),
  Synopsis('Returns a list with the similarity score, first sequence and
second sequence suitable for printing the given match with the
given similarity matrix.  The sequences are the original sequences
from the match with inserted ''_'' as needed to produce the desired
alignment.  If a third argument is provided, it must be the keyword
''NoSelf''.  This is an indication that no position will be aligned
with itself, a situation useful for the detection of repetitious patterns.
If an Alignment is provided, all the information is contained in the
object, and no additional arguments are needed.' ),
  Examples( 'al := Align(''ADEFGHIKLMNNW'',''ADEFGKLMNNW'')',
	'DynProgStrings(Match(al),DM)',
	'seq1 := ''ADEFGHIKSDEFGHLK''',
	'al := Align(seq1,seq1,NoSelf)',
	'DynProgStrings(Match(al),DM,NoSelf)',
	'DynProgStrings(al)',
	Hide('al:=noeval(al)'), Hide('seq1:=noeval(seq1)') ),
  SeeAlso(Match,Align,print,CodonDynProgStrings)
):

WriteFasta_Description := Description(
  function( WriteFasta ),
  CallingSequence( noeval(WriteFasta( seq )), noeval(WriteFasta( seq, labs, fname)) ),
  Parameters( ['seq',   array(string)], 
              ['labs',  array(string)], 
              ['fname', filename] ),
  Returns( NULL ),
  Synopsis( 'Writes an array of sequences to a file (default is 
  temp.fasta). If no labes are given, the sequences are numbered according
  to the order.'),
  Examples( Fake('WriteFasta([''ACCGTA'', ''AC_GTA''])',
'>1
ACCGTA
>2
AC_GTA' )),
SeeAlso(WriteData,OpenWriting,WriteSeqXML)
):

json_Description := Description(
  function( json ),
  Summary('serialize darwin structure as json compatible string'),
  CallingSequence( noeval(json( obj ))),
  Parameters( ['obj',anything, 'object to be serialized'] ),
  Returns( string ),
  Synopsis( 'This function serializes any darwin object into a json 
formated string. Darwin objects are encoded as objects with a ''_darwinType'' and a ''data'' field.'),
  References( 'http://www.json.org' ),
  Examples( 'json( [1,2,''blue''])', 'json(Complex(5,2))'),
  SeeAlso(OpenWriting, WriteSeqXML)
):

SearchSeqDb_Description := Description(
  function( SearchSeqDb ),
  CallingSequence( noeval(SearchSeqDb( txt )) ),
  Parameters( ['txt', {string,string..string},'sequence string to be searched'] ),
  Returns( PatEntry ),
  Synopsis( 'Find all the occurrences of t in the amino acid sequences
part of DB.'),
  Examples( FakeReadDb,
'SearchSeqDb(''SGPPRIP'')' ),
  SeeAlso( SearchFrag, AlignOneAll )
):

SearchFrag_Description := Description(
  function( SearchFrag ),
  Summary('Search database for a fragment'),
  CallingSequence( noeval(SearchFrag( seq )) ),
  Parameters( ['seq', string] ),
  Returns( list(Match) ),
  Synopsis( 'Return all matches of seq against the peptide database
located in the system variable DB.'),
  Examples( FakeReadDb,
	Print('SearchFrag(''SGPPRIP'')') ),
  SeeAlso( SearchAC, SearchID, PatEntry, SearchDb, SearchSeqDb, AlignOneAll,
	Species_Entry )
):

AlignOneAll_Description := Description(
  function( AlignOneAll ),
  CallingSequence( noeval(AlignOneAll(seq, db, day, cutoff, entries)) ),
  Parameters( ['seq', {string, posint},'a sequence or an entry number'],
	['db', database, 'a DNA or protein database'],
	['day', DayMatrix,'scoring matrix'],
	['cutoff', numeric, 'only matches with score > cutoff will be reported'],
	['entries', posint..posint, '(optional) compare these entries in db only'] ),
  Returns( list(Match) ),
  Synopsis( 'Align seq against all members of the database db
(or the subset of entries specified by the entries parameter
when present) and return the list of matches which have a
similarity score, using day, which exceeds cutoff.
This function will return only one alignment per database sequence.
If seq is a positive integer, then it is understood to be the
sequence in that entry number.
The alignments reported are Local alignments, that is the best
subsequences are matched.' ),
Paragraph( -2, 'This type of search is similar to what FASTA and
BLAST (Basic Local Alignment Search Tool) do.
The main difference between them and AlignOneAll is that AlignOneAll
does not use approximations, it does rigorous dynamic programming
against all the sequences in the database.
Its speed is comparable to the other programs, so we see no reason
to use shortcuts when the exact results are easy to obtain.' ),
  Examples( FakeReadDb,
Fake( 'AlignOneAll(''NKRSPAASQPPVSRVNPQEESYQKLAMETLEELDWCLD'',DB,DM,110)',
'[Match(168.3,9748355,71916164,38,38,250),
 Match(147.5,9749450,71916164,38,38,250),
 Match(122.2,9752627,71916164,38,38,250),
 Match(122.2,9754188,71916164,38,38,250)]') ),
  SeeAlso( 'DB', SearchFrag, SearchSeqDb )
):


Tree_Description := Description(
  structure( Tree ),
  Summary('Internal node of a binary Tree'),
  CallingSequence( noeval(Tree( Left, Height, Right, xtra )) ),
  Parameters(
	[Left, {Leaf, Tree},'recursive left subtree'],
	[Right, {Leaf, Tree},'recursive right subtree'],
	[Height, anything,'any information, usually height'],
	[xtra, anything,'(optional) additional information'] ),
  Returns( Tree ),
  Synopsis( 'The Tree data structure holds binary trees which
may or may not be labelled and/or weighted.
The Left and Right subtree of the tree are either
(1) a Tree structure or (2) a Leaf structure.
Many built-in Darwin routines for phylogenetic trees, assume
that the Height field refers to the height of the node.
These routines include DrawTree.
The use of the xtra field varies significantly
from algorithm to algorithm.' ),
  Examples(
	't := Tree(Tree(Leaf(A),5,Leaf(B)),0,Tree(Leaf(C),11,Leaf(D)))',
	't[Left]', 't[Right]', Hide('t := noeval(t)') ),
  SeeAlso( DrawTree, Leaf, LeastSquaresTree, Synteny, GapTree, SignedSynteny,
	BootstrapTree, PhylogeneticTree, Leaves, Prefix, Postfix, Infix,
	ComputeDimensionlessFit, RBFS_Tree, RobinsonFoulds, ReconcileTree,
	IntraDistance, BipartiteSquared )
):


Infix_Description := Description(
  iterator( Infix ),
  Summary('walks over all the nodes of a tree in infix order'),
  CallingSequence( 'for n in Infix(tree) do ... od;' ),
  Parameters( [tree,Tree,'a general tree'] ),
  Returns(Tree),
  Synopsis('This is an iterator which returns all the
nodes (internal nodes of type "Tree" or external nodes of
type "Leaf") of a tree in infix order.  Infix order means that
the left subtree is visited first, then the node, then the right
subtree, for every node recursively.' ),
  SeeAlso( iterator, objectorientation, iterate, Prefix, Infix, Postfix, Leaves, Leaf )
):


Prefix_Description := Description(
  iterator( Prefix ),
  Summary('walks over all the nodes of a tree in prefix order'),
  CallingSequence( 'for n in Prefix(tree) do ... od;' ),
  Parameters( [tree,Tree,'a general tree'] ),
  Returns(Tree),
  Synopsis('This is an iterator which returns all the
nodes (internal nodes of type "Tree" or external nodes of
type "Leaf") of a tree in prefix order.  Prefix order means that
the node is visited first, then the left subtree, then the right
subtree, for every node recursively.' ),
  SeeAlso( iterator, objectorientation, iterate, Prefix, Infix, Postfix, Leaves, Leaf )
):


Postfix_Description := Description(
  iterator( Postfix ),
  Summary('walks over all the nodes of a tree in postfix order'),
  CallingSequence( 'for n in Postfix(tree) do ... od;' ),
  Parameters( [tree,Tree,'a general tree'] ),
  Returns(Tree),
  Synopsis('This is an iterator which returns all the
nodes (internal nodes of type "Tree" or external nodes of
type "Leaf") of a tree in postfix order.  Postfix order means that
the left subtree is visited first, then the right subtree, then the
node, for every node recursively.' ),
  SeeAlso( iterator, objectorientation, iterate, Prefix, Infix, Postfix, Leaves, Leaf )
):


Leaf_Description := Description(
  structure( Leaf ),
  Summary( 'external node for binary Tree'),
  CallingSequence(
	noeval( Leaf( Label )),
	noeval( Leaf( Label, Height )) ),
  Parameters(
	[Label, anything, 'optional label'],
	[Height, numeric, 'optional height'] ),
  Returns( Leaf ),
  Synopsis( 'The Leaf structure holds the information associated
with the leaf of a tree (Tree structure).  The format is generally
unspecified allowing Leaf structures containing anything.
However, most phylogenetic tree construction algorithms in Darwin
assume that a leaf label is contained in the first position and
the height information is contained in the second position.
Type testing for Tree will also yield true for a Leaf so that
recursive trees with Leaf() nodes are easy to code.
If additional information needs to be stored in the Leaf, the
Leaf class can be extended with ExtendClass.
Alternatively, extra arguments to Leaf will be left undisturbed.' ),
  Examples(
	't:=Tree(Tree(Leaf(A),5,Leaf(B)),0,Tree(Leaf(C),11,Leaf(D)))',
	't[Left, Left, Label]', Hide('t := noeval(t)') ),
  SeeAlso( Tree, DrawTree, ExtendClass, Leaves, Prefix, Postfix, Infix )
):


Leaves_Description := Description(
  iterator( Leaves ),
  Summary('walks over all the leaves of a tree'),
  CallingSequence( 'for n in Leaves(tree) do ... od;' ),
  Parameters( [tree,Tree,'a general tree'] ),
  Returns(Leaf),
  Synopsis('This is an iterator which returns all the
leaves of a tree in infix order.' ),
  SeeAlso( iterator, objectorientation, iterate, Prefix, Infix, Postfix, Leaves, Leaf )
):

Lines_Description := Description(
  iterator( Lines ),
  Summary('iterates over all lines in a string'),
  CallingSequence( 'for z in Lines(s) do ... od;' ),
  Parameters( [s,string,'any string'] ),
  Returns(string),
  Synopsis('This is an iterator which returns all the
lines of a string (separated by a ''\\n'' character) in 
the original order. The newline character at the end of each line 
is also included in the return value.'), 
  SeeAlso( iterator, objectorientation, iterate, string, SearchDelim, SplitLines )
):


IdenticalTrees_Description := Description(
  function( IdenticalTrees ),
  Summary( 'test whether two trees have the same topology' ),
  CallingSequence( noeval(IdenticalTrees(t1,t2)) ),
  Parameters( ['t1', Tree], [t2,Tree] ),
  Returns( boolean ),
  Synopsis( 'IdenticalTrees tests whether the two given trees
have the same topology (shape, relation between the leaves).
The branch lengths are ignored.
The trees must have leaves based on the same labels
(first argument of Leaf).
If the set of leaf labels differs, IdenticalTrees will return false.' ),
  Examples( 't1 := Tree(Tree(Leaf(a,2),1,Leaf(b,2)),0,Tree(Leaf(c,2),1,Leaf(d,2))):',
   't2 := Tree(Tree(Leaf(a,2),1,Leaf(d,2)),0,Tree(Leaf(c,2),1,Leaf(b,2))):',
   'IdenticalTrees(t1,t2)',
   Unassign('t1','t2')),
  SeeAlso( Leaf, Tree )
):


GetTreeLabels_Description := Description(
  function(GetTreeLabels ),
  CallingSequence( noeval(GetTreeLabels( t )) ),
  Parameters( ['t', Tree] ),
  Returns( list ),
  Synopsis( 'This function returns a list of all the leaf labels present in t.'),
  Examples( 'T := Tree( Leaf(a, 2), 0.5, Leaf(e, 1) )',
	'GetTreeLabels( T )', Hide('T := noeval(T)') ),
  SeeAlso( Leaf, Tree )
):

Edge_Description := Description(
  structure( Edge ),
  Summary( 'edge/arc description' ),
  CallingSequence(
	noeval(Edge( Label, From, To ) ) ),
  Returns( Edge ),
  Selectors(
	[Label, anything, 'the label of the edge'],
	[From, anything, 'the first end point of the edge.'],
	[To, anything, 'the second end point of the edge.'] ),
  Synopsis( 'The Edge data structure stores the information
associated with an edge.  Some algorithms assume that the Label
field stores a numeric value representing a weight.
The Edges are always directed, but if the graph is meant to be
undirected, then the From/To are exchangeable and only one entry
per Edge is needed.' ),
  Examples(
	'G := Graph( Edges( Edge(4,1,2), Edge(7,1,3), Edge(6,2,4),
		Edge(5,3,4) ), Nodes(1, 2, 3, 4) )',
	'G[Edges, 1, Label]' ),
  SeeAlso_Graph
):

Edges_Description := Description(
	structure( Edges ),
	CallingSequence(
		noeval(Edges( L ))),
	Parameters(
		['L', '{ list(Edge), NULL }'] ),
	Returns( Edges ),
	Synopsis( 'The Edges structure is the first field of a Graph data
structure.  It consists of a list of Edge structures.' ),
	Examples(
		'G := Graph( Edges( Edge(4,1,2), Edge(7,1,3), Edge(6,2,4),
			Edge(5,3,4) ), Nodes(1, 2, 3, 4) )' ),
	SeeAlso_Graph
):

Nodes_Description := Description(
	structure( Nodes ),
	CallingSequence(
		noeval(Nodes( N ))),
	Parameters(
		['N', '{list({posint, 0}), NULL}'] ),
	Returns( Nodes ),
	Synopsis( 'The Nodes structure holds the list of labels for nodes in a graph.'),
	Examples(
		'G := Graph( Edges( Edge(4,1,2), Edge(7,1,3), Edge(6,2,4),
			Edge(5,3,4) ), Nodes(1, 2, 3, 4) )' ),
	SeeAlso_Graph
):


ShortestPath_Description := Description(
  function( ShortestPath ),
  Summary( 'shortest path from one node to all others'),
  CallingSequence( noeval(ShortestPath(g,i,excl)) ),
  Parameters( ['g',Graph,'given graph'], ['i',anything,'starting node'],
	[excl,set,'(optional) excluded node set'] ),
  Returns( list([posint,numeric]) ),
  Synopsis( 'Compute the shortest path from node i to every
connected node in g.  It is assumed that a non-negative numeric
label on an Edge is the length of the edge, that is the distance
between the corresponding nodes.  "excl" is the set of nodes not
to be considered and defaults to {}.' ),
  Examples( 'g := Graph( Edges(Edge(1.2,1,2),Edge(2,1,4),Edge(3,1,5),Edge(4,2,3),Edge(5,3,4)),Nodes(1,2,3,4,5))',
	'ShortestPath(g,1)',
	Unassign('g') ),
  SeeAlso_Graph
):


Path_Description := Description(
  function( Path ),
  Summary( 'find a path between two nodes of a graph'),
  CallingSequence( noeval(Path(g,n1,n2)) ),
  Parameters( ['g',Graph,'given graph'],
	['n1',Node,'source node'],
	['n2',Node,'destination node'] ),
  Returns( list(Edge) ),
  Synopsis( 'Find a path between n1 and n2, returning all the
edges that need to be traversed in a list.
If there is no path, it returns an empty list.'),
  Examples( 'g := Graph( Edges(Edge(1.2,1,2),Edge(2,1,4),Edge(3,1,5),Edge(4,2,3),Edge(5,3,4)),Nodes(1,2,3,4,5))',
	'Path(g,3,5)',
	Unassign('g') ),
  SeeAlso_Graph
):

ComputeCubicTSP_Description := Description(
  function( ComputeCubicTSP ),
  Summary ('compute Travelling Salesman Cycle (cubic time)'),
  CallingSequence( noeval(ComputeCubicTSP(Dist, trials, 'p1..pk' )) ),
  Parameters(
['Dist', matrix(nonnegative),'symmetric, square, distance matrix'],
['trials',posint,'number of random starting points (optional)'],
['p1..pk',list(posint),'optional good solutions']),
  Returns(list(posint) ),
  Synopsis('Compute a minimum distance cycle (symmetric travelling
salesman problem) with a heuristic O(n^3) algorithm.
The second argument is optional.  If present it indicates the number
of (random starting points) trials that will be computed; the best
cycle/tour of these will be returned.
The third ... kth arguments are also optional and are
permutations of integers which are good solutions to the TSP
problem.  These will be used as seeds to build new (better) solutions.
This is the default function used by ComputeTSP.  It should be used
only when you can provide initial good solutions or a different
number of trials is desired.'),
  SeeAlso( ComputeTSP )
):

ComputeQuarticTSP_Description := Description(
  function( ComputeQuarticTSP ),
  Summary ('compute Travelling Salesman Cycle (quartic time)'),
  CallingSequence( noeval(ComputeQuarticTSP(Dist, trials, 'p1..pk' )) ),
  Parameters(
['Dist', matrix(nonnegative),'symmetric, square, distance matrix'],
['trials',posint,'number of random starting points (optional)'],
['p1..pk',list(posint),'optional good solutions']),
  Returns(list(posint) ),
  Synopsis('Compute a minimum distance cycle (symmetric travelling
salesman problem) with a heuristic O(n^4) algorithm.
The second argument is optional.  If present it indicates the number
of (random starting points) trials that will be computed; the best
cycle/tour of these will be returned.
The third ... kth arguments are also optional and are
permutations of integers which are good solutions to the TSP
problem.  These will be used as seeds to build new (better) solutions.'),
  SeeAlso( ComputeTSP )
):

ComputeTSP_Description := Description(
  function( ComputeTSP ),
  CallingSequence( noeval(ComputeTSP(D)) ),
  Parameters( ['D', matrix(numeric),'symmetric distance matrix'] ),
  Returns( list(posint) ),
  Synopsis( 'This function computes a minimum distance tour through
the distance matrix D (this is the symmetric travelling salesperson problem).' ),
  Examples( 'D := [[0,1,1,10],[1,0,10,1],[1,10,0,1],[10,1,1,0]]',
	'ComputeTSP(D)', Hide('D:=noeval(D)') ),
  SeeAlso( ComputeQuarticTSP, ComputeCubicTSP )
):

Eigenvalues_Description := Description(
  function(Eigenvalues),
  Summary('Eigenvalue/vector decomposition of a symmetric matrix'),
  CallingSequence(noeval(Eigenvalues(A, eigenvects)) ),
  Parameters([A,matrix,'a symmetric matrix'],
		['eigenvects',name,'an optional matrix name'] ),
  Returns( list(numeric) ),
  Synopsis('Compute an eigenvalue/eigenvector decomposition of A.
A must be a symmetric matrix.
The function returns the vector containing the eigenvalues in
increasing order.
The optional second argument, if present must be a name that will
be assigned with the matrix of the eigenvectors.
The eigenvectors have norm 1 and are stored columnwise and the ith
column corresponds to the ith eigenvalue.' ),
  Examples( 'A := [[3,1,2],[1,2,-1],[2,-1,5]]',
	'alpha := Eigenvalues(A,V)',
	'Vt := V^t',
	'A*Vt[1] = alpha[1]*Vt[1]', 'Vt[2]*Vt[2]',
	Unassign('A','V','Vt','alpha')
	),
  SeeAlso( SvdAnalysis, op(SeeAlsoLinAlg) )
):

VertexCover_Description := Description(
  function(VertexCover),
  Summary ('Vertex Cover exact/approximate algorithm'),
  CallingSequence(noeval(VertexCover(A)) ),
  Parameters([A,Graph,'a Graph'] ),
  Returns(set ),
  Synopsis('The input to this algorithm is an undirected graph.
An undirected graph is represented as a Graph data structure which
should accept two selectors: Nodes and Edges.
The Vertex Cover problem is finding the minimum
set of vertices which "cover" all edges.  That is a minimum size
set of vertices such that each edge is incident to at least one of
the vertices in this set.' ),
'',
Paragraph( -2, 'The output is a set of the Nodes in the vertex cover.
The algorithm computes a lower bound on the size of the
vertex cover which is left in the global variable VertexCoverLowerBound.
If this coincides with the size of the answer, it means that the
answer is optimal.  The global variable VertexCoverIterFactor may
be assigned a non-negative number f.  The algorithm will then run
for f*n^2 iterations.  If f=0 then only the greedy heuristic is run,
and this is quite fast.  The larger f, the more accurate the answers
will be, and the more time the algorithm will consume.'),
Paragraph( -2, 'The Vertex Cover problem is closely related
to the Clique problem.  They can be related by the following
formula:' ),
'',
Indent(5,Code('VertexCover(G) = NodeComplement(Clique(EdgeComplement(G)))')),
'',
  Examples( 'VertexCover(PetersenGraph())', 'VertexCoverLowerBound' ),
  SeeAlso_Graph
):

Clique_Description := Description(
  function(Clique),
  Summary ('Maximum clique exact/approximate algorithm'),
  CallingSequence(noeval(Clique(A)) ),
  Parameters([A,Graph,'a Graph'] ),
  Returns(set ),
  Synopsis('The input to this algorithm is an undirected graph.
An undirected graph is represented as a Graph data structure which
should accept two selectors: Nodes and Edges.
The Maximum Clique problem is finding a set of completely
connected vertices which is of maximum size.' ),
Paragraph( -2, 'The output is a set of the Nodes in the clique.
The algorithm computes an upper bound on the size of the
maximum clique which is left in the global variable CliqueUpperBound.
If this coincides with the size of the answer, it means that the
answer is optimal (maximal).  The global variable CliqueIterFactor may
be assigned a non-negative number f.  The algorithm will then run
for f*n^2 iterations.  If f=0 then only the greedy heuristic is run,
and this is quite fast.  The larger f, the more accurate the answers
will be, and the more time the algorithm will consume.'),
Paragraph( -2, 'The Clique problem is closely related
to the Vertex Cover problem.  They can be related by the following
formula:' ),
'',
Indent(5,Code('Clique(G) = NodeComplement(VertexCover(EdgeComplement(G)))')),
  Examples( 'hex := HexahedronGraph()',
	'Clique(hex)',
	Hide('hex:=noeval(hex)') ),
  SeeAlso_Graph
):


MaxEdgeWeightClique_Description := Description(
  function(MaxEdgeWeightClique),
  Summary ('Maximum edge-weight clique approximate algorithm'),
  CallingSequence(noeval(MaxEdgeWeightClique(A)) ),
  Parameters([A,Graph,'a Graph with positive edge weights'] ),
  Returns(set ),
  Synopsis('The input to this algorithm is an undirected graph.
An undirected graph is represented as a Graph data structure which
should accept three selectors: Nodes, Edges and Weight.
An approximation algorithm is used to find the best Clique.
The global variable CliqueIterFactor may be assigned a
non-negative number f.  The larger f, the more accurate the answers
will be, and the more time the algorithm will consume.
The default behaviour is identical to setting CliqueIterFactor to 1.
The current version does part of the searching for the best solution
in a random way, so for large problems, different runs may give
different results.
This allows the algorithm to be run in parallel if necessary.
For convenience, the global variable TotalEdgeWeight is
assigned the sum of edge-weights of the clique found.'),
  SeeAlso_Graph
):

MinCut_Description := Description(
  function(MinCut),
  Summary( 'Approximate min-cut algorithm' ),
  CallingSequence( noeval(MinCut(G)), noeval(MinCut(G,errbound))),
  Parameters(
    [G,Graph,'a Graph'],
    [errbound,nonnegative,'(optional) error bound for not finding minimum'] ),
  Returns([list,'[integer, Nodes, Nodes]']),
  Synopsis('MinCut is the problem of computing the minimal cut of a 
    undirected graph G(V,E), i.e., that of partitioning the vertex set 
    V into two parts so that the number of edges joining 
    vertices in different parts is minimal.'),
    Paragraph(-2, 'This randomized algorithm solves computes a  
    MinCut in O(n^2*log^3(n)). The optional argument ''errbound'' is used to
    set the number of trial runs and has been empirically found to be very
    conservative.'),
    Paragraph(-2,'The algorithm returns the number of edges which cross the 
    cut and the two disjoint vertex sets.'),
  Examples( 'G := Graph({{1,2},{2,3},{1,3},{1,4}},{1,2,3,4})',
    'MinCut(G);',
    Unassign(G) ),
  SeeAlso_Graph
):


MaxCut_Description := Description(
  function(MaxCut),
  Summary( 'Approximate max-cut algorithm' ),
  CallingSequence( noeval(MaxCut(G)), noeval(MaxCut(G,weighted))),
  Parameters(
    [G,Graph,'a Graph'],
    [weighted,boolean,'(optional) compute weighted maxcut'] ),
  Returns([list,'[set,set,numeric]']),
  Synopsis('MaxCut is the problem of computing the maximum cut of a 
    undirected graph G(V,E), i.e., that of partitioning the vertex set 
    V into two parts so that the number (resp. weights) of edges joining 
    vertices in different parts is as large as possible. It is known to be 
    NP-hard.'),
    Paragraph(-2, 'This greedy approximation algorithm solves the unweighted 
    MaxCut problem in O(e+n) (weighted O(e*log(e)+n)) and is a 1/2+1/(2n)
    approximation. The weighted form of the algorithm expects numeric 
    Label fields in the graph data-structure.'),
    Paragraph(-2,'The algortihm returns the two disjoint vertex sets and 
    the number (resp. weights) of the edges crossing the two sets.'),
  Examples( Hide('SetRand(1)'),
    'G := Rand(Graph):',
    'MaxCut(G);',
    Unassign(G) ),
  SeeAlso_Graph
):

EdgeComplement_Description := Description(
  function(EdgeComplement),
  Summary('construct the graph on the complementary edges'),
  CallingSequence( noeval(EdgeComplement(Graph)) ),
  Parameters( [Graph,Graph,'an input graph'] ),
  Returns(Graph),
  Synopsis('Computes the complement graph of the input.  This is a graph
over the same set of nodes, but with edges where there were no edges and
vice-versa.  The labels of the old edges are lost and the new edges are
assigned a 0 label.'),
  Examples( 'hex := HexahedronGraph()',
	'EdgeComplement(hex)',
	Hide('hex:=noeval(hex)') ),
  SeeAlso_Graph
):


DrawTree_Description := Description(
  function(DrawTree ),
  Summary( 'general front-end for drawing phylogenetic trees' ),
  CallingSequence(
        noeval( DrawTree(tree,method,modif))),
  Parameters(
    [tree,Tree,'input tree to draw'],
    [method,string,'(optional) method to display the tree'],
    [modif,{string,symbol=anything},'optional modifiers for the drawing'] ),
  Returns( 'NULL' ),
  Synopsis('DrawTree draws a phylogenetic tree and produces a
file containing postscripts commands.
This is a single interface for all the methods and variants that
we could imagine for drawing phylogenetic trees.
The tree must contain length information in its nodes, as it
is the common case for the functions which build the trees.
The behaviour is classified according to the following phases: '),
'',
Paragraph( -2, 'Mode of tree display:' ),
Paragraph( -14, ' <default>    Vertical' ),
Paragraph( -14, ' Vertical     horizontally equally spaced leaves,
vertical height preserved' ),
Paragraph( -14, ' Unrooted     planar representation, root is only
identified by a small circle, branch distances are preserved.
Also called Splat trees' ),
Paragraph( -14, ' Radial       leaves are on equally spaced directions
from the root, distances to the root preserved' ),
Paragraph( -14, ' RadialLines  like Radial, with arcs indicating distances' ),
Paragraph( -14, ' Phylogram    left to right horizontal branches,
branch lengths preserved' ),
Paragraph( -14, ' Cladogram    left to right horizontal branches,
branches to leaves stretched to align right' ),
Paragraph( -14, ' Bisect       like Radial, but parent is on bisector line' ),
Paragraph( -14, ' BisectLines  like Bisect, with arcs indicating distances' ),
Paragraph( -14, ' ArcRadial    a Cladogram drawn with polar coordinates'    ),
'',
Paragraph( -2, 'Reordering of leaves:' ),
Paragraph( -24, ' <default>              use the ordering in the Tree' ),
Paragraph( -24, ' OrderLeaves=<sel>      permute the left-right subtrees
to make the clusters as contiguous as possible' ),
Paragraph( -24, ' OrderLeaves=LeftHeavy  permute the left-right subtrees
to make the left subtrees the largest' ),
Paragraph( -24, ' OrderLeaves=Random     randomly permute the left-right
subtrees to (possibly) obtain better looking trees' ),
'',
Paragraph( -2, 'Branch labelling:' ),
Paragraph( -24, ' <default>              Adaptive, 2-digit precision,
branch labelling' ),
Paragraph( -24, ' LengthFormat=<format>  A string which is interpreted
as a format of an sprintf call with the length of the branch.
If set to the empty string, no branch labelling will happen.' ),
Paragraph( -24, ' LengthFormat=<proc>    A procedure: (Length) -> string
which takes the branch length as an argument and
produces the string to be placed on the branch.' ),
Paragraph( -24, ' BranchDrawing=<proc>   A procedure that will do all
the branch drawing.
(x1,y1, x2,y2, l) -> list( drawing commands).
The branch spans from (x1,y1) to (x2,y2) and has a branch length l.
Use ShowBootstrap to display boostrapping values on the branches.' ),
'',
Paragraph( -2, 'Internal Nodes:' ),
Paragraph( -22, ' <default>            no labelling happens for
internal nodes' ),
Paragraph( -22, ' InternalNodes=<proc> A procedure (Tree,x,y) ->
list( drawing commands) which will be invoked every time that an
internal node (identified by Tree), is drawn at position (x,y).
ShowBootstrap would display the bootstrapping values for internal nodes if 
they are present in the fourth field of the Tree data structure.' ),
'',
Paragraph( -2, 'Leaf display information:' ),
Paragraph( -20, ' <default>          circle with leaf[Label] written.
If the Leaf contains additional arguments of the form:
Shape = sss or Color = ccc, then the Leaf is displayed using
the shape sss and color ccc.
Alternatively, if the Label is the structure Color(colorcode,xxx),
then xxx will be taken as the Label and will be colored with the
given colorcode.' ),
Paragraph( -20, ' Legend             leaf[Label] written (no circle)' ),
Paragraph( -20, ' LeafDrawing=<proc> A procedure (Leaf,x,y) ->
list( drawing commands) to display the Leaf centered at (x,y).' ),
Paragraph( -20, ' Clusters=<sel>     color and shape according to cluster' ),
Paragraph( -20, ' RadialLabels       leaf labels radial' ),
'',
Paragraph( -2, 'Cross referencing:' ),
Paragraph( -17, ' <default>       no cross referencing, all labelling
is done with leaf[Label]' ),
Paragraph( -17, ' CrossReference  all labelling is done with an alphanumeric
character and leaf[Label] is cross referenced on the right' ),
'',
Paragraph( -2, 'Title:' ),
Paragraph( -17, ' Title=anything  Title to appear centered at the bottom' ),
'',
Paragraph( -2, 'Size of Text:' ),
Paragraph( -17, ' TextSize=<points>  Set point-size for all text' ),
'',
Paragraph( -2, 'Minimum branch length:' ),
Paragraph( -17, ' MinBranchLength=positive  Force all branches to be of
a minimum length.  The labelling will be done with the original lengths,
but the drawing will use this minimum value.  This is a useful option
when part of the tree is cramped together and difficult to see.
The proportions will not be maintained, but the tree can be understood.
It is recommended to display the edge lengths if this option is used.' ),
'',
Paragraph( -2, 'list of drawing commands:' ),
Paragraph( -17, ' CTEXT(...)      Centered text (as for DrawPlot)' ),
Paragraph( -17, ' LTEXT(...)      Left aligned text (as for DrawPlot)' ),
Paragraph( -17, ' RTEXT(...)      Right aligned text (as for DrawPlot)' ),
Paragraph( -17, ' LINE(...)       Line (as for DrawPlot)' ),
Paragraph( -17, ' POLYGON(...)    Closed polygon (as for DrawPlot)' ),
Paragraph( -17, ' CIRCLE(...)     Circle (as for DrawPlot)' ),
'',
Paragraph( -2, 'In all cases, <sel> provides the definition of the
clusters, or groups of leaves.  This can be done as:' ),
Paragraph( -16, ' list(anything) the numbering in the leaves is used
as an index in this list, and the value is the cluster name.
Clustering will be done on equal values.' ),
Paragraph( -16, ' procedure      as above, but the value is obtained
by running the procedure on the Leaf.' ),
'',
Paragraph( -2, 'Drawing of lateral gene transfer (LGT) arrows: in the
ArcRadial tree display, arrows can be drawn to depict LGTs. Each LGT must is 
characterized by its two endpoints, defined in a list placed in the  4th field 
of the relevant Tree() structure (or the 3rd field of a Leaf() structure), as 
follows: [ ''unique id'', {''start'',''end''}, height, (optionally, an RGB 
color triplet)]. '),
'',
Paragraph( -2, 'A list of drawing commands is composed of the objects
(as defined in ?DrawPlot) LTEXT, CTEXT, RTEXT, LINE, POLYGON and CIRCLE.' ),

  SeeAlso( DrawTree, Leaf, LeastSquaresTree, GapTree, SignedSynteny,
	SystemCommand, DrawPlot,
	Synteny, PhylogeneticTree, BootstrapTree, Tree, ViewPlot )
):



CreateRandMultAlign_Description := Description(
  function(CreateRandMultAlign ),
  Summary( 'Random multiple alignment following a phylogenetic tree'),
  CallingSequence(
		noeval(CreateRandMultAlign(tree, len)),
		noeval(CreateRandMultAlign(tree, len, method)),
		noeval(CreateRandMultAlign(tree, len, DelType))
  ),
  Parameters(
	[tree,Tree,'Phylogenetic tree'],
	[len, posint, 'Length of root sequence'],
	[method, string, '(optional) MSA method, default: Probabilistic'],
	[DelType, {ExpGaps,ZipfGaps}, '(optional) mutation type, default: no gaps']
  ),
  Returns(MAlignment),
  Synopsis('Produces a random multiple alignment that is generated
from a phylogenetic tree. The DelType is directly passed to the Mutate function, while
the method is used for the MAlign function.' ),
  Examples(
	'tree := Tree(Leaf(A,-7.5000,1),0,Tree(Tree(Leaf(D,-8.5000,4),-7.5000,Leaf(C,-8.5000,3)),-4.5000,Leaf(B,-5.5000,2))):',
	Print('msa := CreateRandMultAlign(tree,200,ExpGaps)'),
	Print('print(msa)'), Unassign('tree','msa')),
  SeeAlso(CreateRandSeq,Mutate,MAlign, MAlignment,Tree , BootstrapTree)
):



CollapseNodes_Description := Description(
  function(CollapseNodes ),
  CallingSequence( 
		noeval( CollapseNodes( tree, 'PAM = pam' )),
		noeval( CollapseNodes( tree, 'NodeCount = ncount' )),
		noeval( CollapseNodes( tree, 'Class = class')),
		noeval( CollapseNodes( tree, 'Bootstrapping = boots'))),
  Parameters( [tree,Tree], [pam,positive,'PAM distance'],
	[ncount,posint,'Number of nodes'],[class,{string,list(string)},'Lineage(s)'],
	[boots,posint,'Minimal bootstrapping percentage'] ),
  Returns( Tree ),
  Synopsis( 'Collapses subtrees to a single leaf. With the PAM option, all leaves that
	are at most the desired PAM distance from each other are collapsed. The
	NodeCount option collapses all subtrees with less or equal this number of
	leaves. The Class option is used for species trees to collapse leaves that
	are from the same class of species. Finally, Bootstrapping collapses all
	subtrees where all nodes are at least boots% supported by bootstrapping.' ),
  Examples('tree := Tree(Leaf(Mouse,-2.9000),0,Tree(Leaf(Human,-2.2000),-0.6000,
	Leaf(Dog,-2.7000)));','CollapseNodes(tree,PAM=4)', Unassign( 'tree') ),

  SeeAlso( Tree, PrintTreeSeq , BootstrapTree)
):


FindCircularOrder_Description := Description(
  function(FindCircularOrder ),
  Summary('list of Leaf labels in lexicographical order'),
  CallingSequence(noeval(FindCircularOrder(t)) ),
  Parameters([t,Tree,'input tree'] ),
  Returns(list ),
  Synopsis('Find a circular order of a tree, in particular,
a lexicographical order of a Tree.' ),
  Examples('tree := Tree(Tree(Tree(Leaf(f9,-90.4683,372),-89.6651,
Leaf(e8,-91.6422,371)),-87.7817, Leaf(e7,-89.9699,370)),-63.2655,
Tree(Tree(Leaf(e6,-84.4243,369),-81.6475,Leaf(e5,-83.9666,368)),
-78.2662,Leaf(e4,-84.5572,367))):',
 'FindCircularOrder(tree)',
    Unassign( 'tree') ),
  SeeAlso(Tree,Leaf,Leaves,CircularTour,Clusters )
):


CircularTour_Description := Description(
  function(CircularTour ),
  Summary('find a minimal cost Circular tour'),
  CallingSequence(
	noeval(CircularTour(seqs)),
	noeval(CircularTour(AllAll)),
	noeval(CircularTour(Dist)) ),
  Parameters(
	[seqs,list(string),'a list of Sequences (DNA or proteins)'],
	[AllAll,matrix(Alignment),'all vs all Alignment matrix'],
	[Dist,matrix(numeric),'all vs all distance matrix (symmetric)'] ),
  Returns(list(posint) ),
  Synopsis('This is a front-end to ComputeTSP where we give as
input either a set of sequences or a distance matrix
or an AllAll matrix and the result is a minimal cost
tour broken at the most convenient place (highest cost).
The input can be:' ),

Paragraph( -15, 'List of sequences - n sequences.
The sequences are aligned all against all using Global alignments
with the default DM matrix.  (the rest is as with AllAll matrix).' ),

Paragraph( -15, 'AllAll matrix - an n x n symmetric matrix of 
Alignments.  If the Alignments have a PamDistance, the
minimal cost tour is based on PamDistances.
If not it is based on maximizing the Score
of the neighbouring alignments.' ),

Paragraph( -15, 'Distance matrix - an n x n symmetric distance
matrix.  The tour is computed to minimize the
sum of the distances.' ),

Paragraph( -2, 'The output is the list of indices in the
best tour of length n.' ),
  Examples(
  'seqs := [SSSS, AAAA, AAAS, AASS, ASSS, SSSA, SSAA, SAAA]:',
 'CircularTour(seqs)',
    Unassign( 'seqs') ),
  SeeAlso(FindCircularOrder,CircularTour,ComputeTSP,MAlign,Clusters )
):


Clusters_Description := Description(
  function(Clusters ),
  Summary('find Clusters of seqs or objects'),
  CallingSequence(
	noeval(Clusters(seqs,lim)),
	noeval(Clusters(AllAll,lim)),
	noeval(Clusters(Dist,lim)) ),
  Parameters(
	[seqs,list(string),'a list of Sequences (DNA or proteins)'],
	[AllAll,matrix(Alignment),'all vs all Alignment matrix'],
	[Dist,matrix(numeric),'all vs all distance matrix (symmetric)'],
	[lim,symbol=positive,'mode and value used to define clusters'] ),
  Returns(list(set(posint)) ),
  Synopsis('This function finds clusters in a set of sequences or
any objects from their distance or similarity constraints.
The input is either a set of sequences or a distance matrix
or an AllAll matrix and the result is a list of sets of clusters.
The components of the clusters are identified by the indices
to the seqs or AllAll or Dist arrays.
The parameters can be:' ),

Paragraph( -15, 'List of sequences - n sequences.
The sequences are aligned all against all using Global alignments
with the default DM matrix.  (the rest is as with AllAll matrix).' ),

Paragraph( -15, 'AllAll matrix - an n x n symmetric matrix of 
Alignments.
If the cluster definition is based on MaxDistance=ddd or
AveDistance=dd then the clusters are selected so that the
PamDistance (or average) of the Alignments are less than ddd.
If MinSimil=sss or AveSimil=sss is specified, the the clusters
will be determined by the Score (or average) of the Alignments
being larger than sss.' ),

Paragraph( -15, 'Distance matrix - an n x n symmetric distance matrix.
MaxDistance=ddd or AveDistance=ddd should be specified and
the clusters are determined by this maximum/average distance.' ),

Paragraph( -15, 'MaxDistance = ddd - The clusters are
determined by the distance ddd.
I.e. any two sequences or objects which are separated by less than
ddd will be part of the same cluster' ),

Paragraph( -15, 'AveDistance = ddd - The clusters are
determined by the distance ddd.
The clusters are built one at a time, starting with the first
sequence/object and adding one member at a time.
The member added is the one whose average distance to the rest
of the cluster is less than ddd.
The clusters built this way, may depend on the order of the
input sequences.' ),

Paragraph( -15, 'MinSimil = sss - Like MaxDistance, but the
selection criteria is based on Similarity or Score being
greater than sss.' ),

Paragraph( -15, 'AveSimil = sss - Like AveDistance, but
the selection criteria is based on the average Similarity or Score being
greater than sss.' ),

Paragraph( -2, 'The output is the list of sets of indices.
Each set is a cluster.  All indices are included, hence some
clusters may be singletons.' ),
  Examples(
   'seqs := [SSSSS, AAAAA, AAAAS, SASSS, SSSSA, ASAAA]:',
   'Clusters(seqs,AveSimil=8)',
   Unassign( 'seqs') ),
  SeeAlso(FindCircularOrder,CircularTour,ComputeTSP,MAlign,Clusters )
):




ReadBrk_Description := Description(
  function( ReadBrk ),
  CallingSequence( noeval(ReadBrk( fname )),
	noeval(ReadBrk( fname, tags=taglist )) ),
  Parameters(
	[fname, string, 'file name with the Brookhaven database'],
	[taglist,list(string),'list of tags to be included'] ),
  Returns( NULL ),
  Synopsis( 'Read a Brookhaven database file into a Fold() data structure.
Specify "compressed=true" as an argument if the file should be
read by "zcat".  The default taglist is HEADER, SOURCE, SEQRES, ATOM.' )
):

ReadDssp_Description := Description(
  function( ReadDssp ),
  CallingSequence( noeval(ReadDssp( fname)) ),
  Parameters( ['fname', filename] ),
  Returns( NULL ),
  Synopsis( 'Read a DSSP formatted database file into a Fold() data structure.
Specify "compressed=true" as an argument if the file should be read by "zcat".
Specify "tags=[taglist]" as an argument to read selected tags. The default
taglist is HEADER, SOURCE.' )
):


DigestSeq_Description := Description(
  function( DigestSeq ),
  Summary ('return digestion fragments'),
  CallingSequence( noeval(DigestSeq( seq, enzyme )) ),
  Parameters( ['seq', string], ['enzyme', string] ),
  Returns( list(string) ),
  Synopsis( 'Return the protein fragments that would result from a
digestion with the given enzyme.' ),
  Examples( 'DigestSeq(''WWWWWWPCPLTTTTTTTTT'', Armillaria )' ),
  SeeAlso( DigestTrypsin, SearchMassDb, DigestAspN,
	DigestionWeights, Protein, MassProfileResults,
	DigestWeights, DynProgMassDb, enzymes, DynProgMass, ProbBallsBoxes,
	ProbCloseMatches)
):

DigestWeights_Description := Description(
  function(DigestWeights ),
  Summary ('return weights of digestion fragments'),
  CallingSequence( noeval(DigestWeights(seq, enzyme)) ),
  Parameters( ['seq', string, 'a protein sequence'], 
		['enzyme', matrix(boolean),'' ] ),
  Returns( list(numeric) ),
  Synopsis( 'Return the weights of the protein fragments that would
result from a digestion with the given enzyme.'),
  Examples( 'DigestWeights(''WWWWWWPCPLTTTTTTTTT'', Armillaria )' ),
  SeeAlso( DigestSeq, DigestTrypsin, SearchMassDb, 
	DigestionWeights, Protein, MassProfileResults,
	DynProgMassDb, enzymes, DigestAspN, DynProgMass, ProbBallsBoxes,
	ProbCloseMatches)
):

DigestTrypsin_Description := Description(
  function(DigestTrypsin ),
  Summary ('return digestion fragments from Trypsin'),
  CallingSequence( noeval(DigestTrypsin( seq )) ),
  Parameters( ['seq', string, 'a protein sequence'] ),
  Returns( list(string) ),
  Synopsis( 'This function returns a set of fragment sequences of seq
as though seq were digested by trypsin.' ),
  SeeAlso( DigestAspN, DigestSeq, DigestWeights, SearchMassDb, 
	DigestionWeights, Protein, MassProfileResults,
	DynProgMassDb, enzymes, DynProgMass, ProbBallsBoxes, ProbCloseMatches)
):

DigestAspN_Description := Description(
  function(DigestAspN ),
  Summary ('return digestion fragments from AspN'),
  CallingSequence( noeval(DigestAspN( seq )) ),
  Parameters( ['seq', string , 'a protein sequence']),
  Returns( list(string) ),
  Synopsis( 'This functions returns a set of fragment sequences of seq
as though seq were digested by AspN.'),
  SeeAlso( DigestSeq, DigestWeights, DigestTrypsin, SearchMassDb, 
	DigestionWeights, Protein, MassProfileResults,
	DynProgMassDb, enzymes, DynProgMass, ProbBallsBoxes, ProbCloseMatches )
):

DynProgMass_Description := Description(
  function(DynProgMass ),
  Summary ('matches digestion fragments with a sequence'),
  CallingSequence(noeval(DynProgMass(p,seq,stddev,deb)) ),
  Parameters(	['p',{array,structure},''],
		['seq',string,''],
		['stddev',numeric,''],
		['deb',numeric,''] ),
  Returns( ),
  Synopsis('Matches a Carboxypeptidase A digest (Fragment) with a
sequence using dynamic programming.'),
  Paragraph(5,'Data structure of fragment:'),
  Paragraph(5, '[[-2.0023, P]], [[-1.2703, GV],[-1.2703, VG],[-0.9824, R]], ....'),
  Paragraph(5, '[[-1.8961, T]], [0, 104.0941]]'),
  Examples( ),
  SeeAlso( DigestSeq, DigestWeights, DigestTrypsin, SearchMassDb,
	DigestionWeights, Protein, MassProfileResults,
	DynProgMassDb, enzymes, DigestAspN, ProbBallsBoxes, ProbCloseMatches)
):

DynProgMassDb_Description := Description(
  function(DynProgMassDb ),
  Summary ('matches digestion fragments with a database'),
  CallingSequence(noeval(DynProgMassDb(p,m,term,df,stddev,ddb ))),
  Parameters(['p',array,' '],
		['m',integer,' '],
		['term',string,' '],
		['df',database,' '],
		['stddev',numeric,' '],
		['ddb',numeric,' ']),
  Returns( ),
  Synopsis('Matches a Carboxypeptidase A digest (Fragment) against the whole database' ),
  Examples( ),
  SeeAlso(DigestSeq, DigestWeights, DigestTrypsin, SearchMassDb,
	DigestionWeights, Protein, MassProfileResults,
	DynProgMass, enzymes, DigestAspN, ProbBallsBoxes, ProbCloseMatches)
):


DigestionWeights_Description := Description(
  structure(DigestionWeights ),
  Summary ('data structure to hold digestion information'),
  CallingSequence(noeval(DigestionWeights(digestor,weights)) ),
  Parameters(	['digestor',string,'name of the digestion enzyme'],
	['weights',numeric,'molecular weights of the fragments'],
	['', {equation,symbol},'amino acid weight modification']
	),
  Returns(DigestionWeights ),
  Synopsis('DigestionWeights is a data structure used to hold
the name of the digestion enzyme followed by the weights obtained
from the digestion.
See ?enzymes for a complete description of the enzymes being
recognized and their properties.
Additionally we can specify various conditions that result in
weight modifications of the amino acids.
The weight modifications can be placed anywhere in the list
of weights and are all optional.  Currently these are:' ),

Paragraph(-2,'C=208.29  An equation with a one-letter code on the
lhs and a weight on the right indicates to the program that the
given amino acid (due to some modification pre/post digestion)
has the given weight.'),

Paragraph(-2,'Deuterated  This word will indicate that all the
hydrogen atoms have been exchanged with Deuterium, and hence
the weights of all aa should be adjusted accordingly.'),

Paragraph(-2,'If the digestor is CNBr or TrypsinCysModified or
NTCB, changes to the weights are made automatically.' ),

  Examples('DigestionWeights(''Trypsin'',
    601.9438, 504.0904, 1512.4545, 480, 590)' ),
  SeeAlso(DigestSeq, DigestWeights, DigestTrypsin, SearchMassDb,
	Protein, MassProfileResults, DynProgMass, 
	enzymes, DigestAspN, DynProgMassDb, ProbBallsBoxes, ProbCloseMatches)
):


Protein_Description := Description(
  structure(Protein ),
  Summary ('data structure to hold SearchMassDb data'),
  CallingSequence(noeval(Protein(ApproxMass, DigestionWeights() )),
		  noeval(Protein(ApproxMass, DigestionMono() )) ),
  Parameters(	[ApproxMass,structure,'approximate mass in Daltons'],
	[DigestionWeights,structure,'weights obtained from using the digestor'],
	[DigestionMono,structure,'as above but using monoisoptopic masses']),
  Returns(Protein),
  Synopsis('Protein is a data structure that holds the approximate mass
in an ApproxMass data structure and the digestion weights in either a
DigestionWeights or a DigestionMono data structure.
It is used as input to the SearchMassDb function.'),
  Examples(
	'Protein(ApproxMass(65800),DigestionWeights(''Trypsin'',601.9438, 504.0904, 1512.4545, 480, 590, 700, 998))' ),
  SeeAlso( DigestSeq, DigestWeights, DigestTrypsin, SearchMassDb,
	DigestionWeights, MassProfileResults, DynProgMass, 
	enzymes, DigestAspN, DynProgMassDb, ProbBallsBoxes, ProbCloseMatches)
):


SearchMassDb_Description := Description(
  function(SearchMassDb ),
  Summary ('Searches digestion fragments against a database'),
  CallingSequence(noeval(SearchMassDb(p,n))),
  Parameters(['p',Protein,'description of protein (weights, enzymes, etc.)'],
   ['n',integer,'maximum number of returned matches'] ),
  Returns( MassProfileResults ),
  Synopsis('Searches the n most significant matches of weights of
digested fragments. The search is done against the database which
is currently loaded (with the command ReadDb).  This could be a protein
 or a nucleotide database.  The description of the protein to be searched
is in terms of the (one or many) weights resulting from digesting
the protein with an enzyme.  This description can also hold
other information as deuteration, and modified amino acid weights.
See Protein and DigestionWeights for details.
The result is a data structure which contains the best n matches,
ordered from best to worst.  Each match is described by the similarity
score, number of fragments in the protein, number of matched fragments,
and description of the matching protein.  See MassProfileResults for
full details.'),
  Examples( FakeReadDb,
	Print('print( SearchMassDb( Protein(DigestionWeights(''Trypsin'',
    601.9438, 504.0904, 1512.4545, 480, 590)), 5 ))' )),
  SeeAlso( DigestSeq, DigestWeights, DigestTrypsin, SearchMassDb,
	DigestionWeights, MassProfileResults, DynProgMass,
	enzymes, DigestAspN, DynProgMassDb, ProbBallsBoxes, ProbCloseMatches )
):


ProbBallsBoxes_Description := Description(
  function(ProbBallsBoxes ),
  Summary ('probability of hitting k eps-boxes with n balls'),
  CallingSequence(noeval(ProbBallsBoxes(k,n,eps))),
  Parameters(
   ['k',posint,'number of boxes'],
   ['n',posint,'number of balls randomly thrown in [0,1]'],
   ['eps',positive,'0<eps<1/k, the width of each box'] ),
  Returns( positive ),
  Synopsis('Computes the probability of having each of the
k boxes with at least one ball when n balls are thrown randomly
over the interval [0,1].
Each of the boxes is assumed to be of width eps and are placed
randomly and without overlaps.
This is the main tool for computing scores (-10*log10(Prob()))
of the MassProfile results.'),
  Examples( 'ProbBallsBoxes(3,10,0.0001)' ),
  SeeAlso( DigestSeq, DigestWeights, DigestTrypsin, SearchMassDb,
	DigestionWeights, MassProfileResults, DynProgMass, Std_Score,
	enzymes, DigestAspN, DynProgMassDb, lnProbBallsBoxes, ProbCloseMatches,
	OutsideBounds, Stat, Cumulative, StatTest )
):


lnProbBallsBoxes_Description := Description(
  function(lnProbBallsBoxes ),
  Summary ('probability of hitting k eps-boxes with n balls'),
  CallingSequence(noeval(lnProbBallsBoxes(k,n,eps))),
  Parameters(
   ['k',posint,'number of boxes'],
   ['n',posint,'number of balls randomly thrown in [0,1]'],
   ['eps',positive,'0<eps<1/k, the width of each box'] ),
  Returns( numeric ),
  Synopsis('Computes the natural logarithm of the probability
of having each of the k boxes with at least one ball when
n balls are thrown randomly over the interval [0,1].
Each of the boxes is assumed to be of width eps and are placed
randomly and without overlaps.
This function should be used for extreme cases when the
probabilities are so small that may not be representable as
a floating point number.
This is the main tool for computing scores (-10*log10(Prob()))
of the MassProfile results.'),
  Examples( 'lnProbBallsBoxes(3,10,0.0001)' ),
  SeeAlso( DigestSeq, DigestWeights, DigestTrypsin, SearchMassDb,
	DigestionWeights, MassProfileResults, DynProgMass, Std_Score,
	enzymes, DigestAspN, DynProgMassDb, ProbBallsBoxes, ProbCloseMatches,
	OutsideBounds, Stat, Cumulative, StatTest )
):


ProbCloseMatches_Description := Description(
  function(ProbCloseMatches ),
  Summary ('prob of k eps-close matches among U(0,1) values'),
  CallingSequence(noeval(ProbCloseMatches(k,n1,n2,eps))),
  Parameters(
   ['k',posint,'number of matches'],
   ['n1',posint,'number of points randomly thrown in [0,1]'],
   ['n2',posint,'number of points randomly thrown in [0,1]'],
   ['eps',positive,'0<eps<1, the limit distance to consider a match'] ),
  Returns( positive ),
  Synopsis('Computes the probability of having k matches between
two different sets of points.
A match is considered when one point from the first set matches
(is closer than eps) a point of the second set.
All the points are assumed to be U(0,1).
There are n1 points in the first set and n2 points in the second set.'),
  Examples( 'ProbCloseMatches(4,10,22,0.0001)' ),
  SeeAlso( SearchMassDb, DynProgMassDb, ProbBallsBoxes, ProbCloseMatches, Std_Score,
	OutsideBounds, Stat, Cumulative, StatTest )
):

GetMostFrequentGrams_Description := Description(
  function( GetMostFrequentGrams ),
  CallingSequence( noeval(GetMostFrequentGrams( n, k)) ),
  Parameters( ['n', posint], ['k', posint] ),
  Returns(NULL ),
  Synopsis( 'This function prints out the n most frequent k-grams
(sequences of length k). It requires a database loaded at system
variable DB.' ),
  Examples( Print( 'GetMostFrequentGrams(5, 5)' )),
  SeeAlso( 'DB', GetMolWeight, GramRegion, GetGramRegion, GetGramRegionScore )
):

GramRegion_Description := Description(
  structure( GramRegion ),
  CallingSequence( noeval(GramRegion(ProbI, ProbE, Extend, LogR0)),
  noeval(GramRegion(intCounts, totCounts, Extend, LogR0)) ),
  Parameters( ['ProbI','array(numeric)'],
		['ProbE','array(numeric)'],
		['Extend','integer'],
		['LogR0','numeric'],
		['Mean','numeric'],
		['Min','numeric'],
		['Max','numeric'] ),
  Returns(structure(array,array,integer, numeric) ),
  Synopsis('Structure to hold GramRegion scoring model data. If called with
array(integer) as the first two arguments (holding Counting data), it
returns the GramRegion data structure with ProbI and ProbE.' ),
  Examples( ),
  SeeAlso( GetGramRegion, GetMostFrequentGrams, GetMolWeight )
):


GetGramRegionScore_Description := Description(
  function( GetGramRegionScore ),
  CallingSequence( noeval(GetGramRegionScore( n, S )) ),
  Parameters( ['n', string], ['G', GramRegion] ),
  Returns( numeric ),
  Synopsis('Computes k-gram region scores over nucleotide sequence n
according to S.' ),
  SeeAlso( GetGramRegion, GetMostFrequentGrams, GetMolWeight )
):

ScoreIntron_Description := Description(
  function( ScoreIntron),
  CallingSequence(noeval(ScoreIntron(noeval(m),noeval(intron))) ),
  Parameters(['m',NucPepMatch],['intron',posint] ),
  Returns( ),
  Synopsis('Computes the score [alpha, delta, omega] for a given intron.' ),
  Examples( ),
  SeeAlso(Introns )
):

GramSite_Description := Description(
  structure( GramSite),
  CallingSequence(noeval( GramSite(Scores, LeftLen, LogR0)),
		  noeval( GramSite(counts, totCounts, LeftLen, LogR0)) ),
  Parameters(['Scores','array(array(numeric))'],
		['LeftLen','posint'],
		['LogR0','numeric'],
		['RightLen','posint'],
		['Mean','numeric'],
		['Min','numeric'],
		['Max','numeric'] ),
  Returns( structure (array,posint,numeric)),
  Synopsis('Structure to hold k-gram scoring model data. When called with counts and
totCounts, it returns the Gram Site Scores' ),
  Examples( ),
  SeeAlso(GetGramSite, GetGramSiteScore )
):


GetGramSiteScore_Description := Description(
  function( GetGramSiteScore),
  CallingSequence(noeval(GetGramSiteScore(n,S)) ),
  Parameters(	['n',string],
		['S',GramSite] ),
  Returns( ),
  Synopsis('Computes k-gram site scores over nucleotide sequence n according to S.'),
  Examples( ),
  SeeAlso(GetGramRegionScore, GetGramSite, GramSite )
):

NucDB_Description := Description(
  variable( NucDB ),
  Synopsis( 'This system variable is used to point to a database
containing nucleotide or ribonucleotide sequences.' ),
  SeeAlso( 'DB', PepDB )
):

PepDB_Description := Description(
  variable( PepDB ),
  Synopsis( 'This system variables is used to point to a database
containing amino acid sequences.' ),
  SeeAlso( 'DB', NucDB )
):

Pi_Description := Description(
  variable( noeval(Pi) ),
  Synopsis('Contains the value of Pi.' )
):

DBL_EPSILON_Description := Description(
  variable( noeval(DBL_EPSILON) ),
  Synopsis('The system variable DBL_EPSILON has the property that
it is the smallest number where 1+DBL_EPSILON <> 1.'),
  SeeAlso( noeval(DBL_MAX) )
):

EOF_Description := Description(
  variable( EOF ),
  Synopsis('The system variable EOF is used to mark the end of a file.' ),
  SeeAlso( )
):

date_Description := Description(
  function(date ),
  CallingSequence( noeval(date()) ),
  Returns( string ),
  Synopsis('Returns the current date and time as a string.' ),
  SeeAlso( time, UTCTime )
):

getpid_Description := Description(
  function( getpid),
  CallingSequence( noeval(getpid()) ),
  Returns( posint ),
  Synopsis('This function returns the process identification number
assigned by the operating system to the current invocation of Darwin.' ),
  Examples( 'getpid()' )
):

gc_Description := Description(
  function(gc ),
  Summary( 'garbage collection' ),
  CallingSequence( noeval(gc()) ),
  Returns( NULL ),
  Synopsis( 'This function forces Darwin to immediately coalesce all
allocated but not in use memory.  Unless the system variable
printgc is set to false, this function prints the current number of
bytes allocated and the total CPU time used so far.' ),
  Examples( 'gc()' ),
  SeeAlso([Set, 'the gc option'] )
):

gigahertz_Description := Description(
  function(gigahertz ),
  Summary( 'estimate the processor speed' ),
  CallingSequence( noeval(gigahertz()) ),
  Returns( numeric ),
  Synopsis( 'This function estimates the computing power of the
processor which is running.  The value has been tuned so that a
Pentium III processor rated at 750MHz gives 0.75 as a result.
Hence, this is a measure equivalent to the number of MHz of such
processors.  There are many many factors which affect the efficiency
of Darwin running on a particular processor, e.g. compiler, system
load, cache size, type of processor, memory speed, and many others.
So this number should be taken with extreme care.  The function
executes alignments, some counting, random number generation and
some linear algebra to obtain the estimate of the time.' ),
  Examples( 'gigahertz()' ),
  SeeAlso(time )
):

has_Description := Description( function(has),
  Summary('test if a structure contains a value'), 
  CallingSequence( noeval(has(str,val)) ),
  Parameters( ['str', anything, 'an arbitrary structure'],
	['val',anything,'value to be found in str'] ),
  Returns(boolean),
  Synopsis('The function tests whether the second argument is part of
the first argument.' ),
  Examples( 'has([1,2,3],2)', 'has(A(1,2,3),4)', 'has({[A(77)]},77)'),
  SeeAlso_symbolic ):

hastype_Description := Description( function(hastype),
  Summary('test if a structure contains any object of a given type'),
  CallingSequence( noeval(hastype(str,typ)) ),
  Parameters( ['str', anything, 'an arbitrary structure'],
        ['typ',type,'a type to be found in str'] ),
  Returns(boolean),
  Synopsis('The function hastype tests whether the first argument contains
any value of the given type' ),
  Examples( 'hastype([1,2,3],posint)', 'hastype(A(1,2,3),list)',
	'hastype({[A(77)]},list)'),
  SeeAlso_symbolic ):


hash_Description := Description(
  function( hash),
  Summary( 'hashing value of an arbitrary expression' ),
  CallingSequence( noeval(hash(expr)) ),
  Parameters( [expr, anything, 'any Darwin expression'] ),
  Returns( integer ),
  Synopsis( 'The hash function returns an arbitrary integer
computed from the given expression.
This hashing value is guaranteed to be the same for identical
expressions, but it is not guaranteed to be unique.
That is, there could be two different expressions which yield
the same hash value.
The hash value of a string with a single character is the
numerical value of its ascii representation plus a constant.
Hashing values are used internally for the remember function,
and may be used by the user for similar purposes (detecting
that two expressions are different without actually comparing them).
The hashing values are not guaranteed to be the same across
different systems, in particular they depend on the integer
word size.' ),
  Examples( 'hash([1,2])', 'hash(''abc'')', 'hash(abc)', 'hash(a)-hash(A)',
	'hash(ASHYMY)-hash(YYYWYN)' ),
  SeeAlso( remember, table, sha2 )
):


help_Description := Description(
  function( help),
  CallingSequence( noeval(help(topic)), noeval('? topic') ),
  Parameters( ['topic', string] ),
  Returns( NULL ),
  Synopsis( 'The help and ? functions search (approximately)
for the topic in the Darwin system and print out any description
lines for these routines.  The help function is case insensitive.' ),
  Paragraph( -2, 'Users should take note that print(topic) and
help(topic) have different semantics.  Firstly, no approximate
search is performed with topic in the former and secondly,
the description for topic is calculated dynamically for topic
(any examples are run immediately).'),
  Examples( Fake('help(Match)',' . . . '), Fake('? phylogenetic', ' . . . ') ),
  SeeAlso( print )
):

hostname_Description := Description(
  function( hostname ),
  CallingSequence( noeval(hostname()) ),
  Returns( string ),
  Synopsis('This function returns the name of the current host on
which the current session is running.' ),
  Examples( 'hostname()' ),
  SeeAlso( getpid, CallSystem )
):

sleep_Description := Description(
  function( sleep ),
  CallingSequence( noeval(sleep(t)) ),
  Parameters( ['t', posint] ),
  Returns( NULL ),
  Synopsis( 'This function causes Darwin to sleep (delay
execution) for t seconds.  Only the
<ctrl-c> keystroke will interrupt the sleep command.'
),
  Examples( 'sleep(1)' ),
  SeeAlso( getpid, CallSystem, TimedCallSystem )
):


SplitLines_Description := Description(
  function( SplitLines ),
  Summary( 'make a list of lines from a string' ),
  CallingSequence( noeval(SplitLines(s)) ),
  Parameters( [s, string, 'a string which may contain newlines'] ),
  Returns( list(string) ),
  Synopsis( 'SplitLines takes a string and breaks it after every
newline character (''\\n'').  Each of these lines are placed in
an output list.  If the string does not end in a newline, the
last string of the list will not end in a newline.  In other
words, SplitLines just splits the string, it does not introduce
or remove any characters.'),
  Examples( 'SplitLines(''abc'')', 'SplitLines(''abc\nxyz'')' ),
  SeeAlso( ReadRawFile, TimedCallSystem, LockFile, FileStat, OpenPipe, ReadLine, ReadOffsetLine, Lines, SearchDelim )
):


CallSystem_Description := Description(
  function( CallSystem ),
  CallingSequence( noeval(CallSystem(cmd)) ),
  Parameters( ['cmd', string] ),
  Returns( integer ),
  Synopsis( 'The CallSystem command passes the argument cmd to
the underlying operating system for execution.  It returns the
integer value returned by the operating system.'),
'',
Paragraph(-2,'  If the results of the execution are to be
returned as a string in Darwin, then the command TimedCallSystem
will do this without the need of an intermediate file.  Also
the command OpenPipe allows the direct reading of the output
of a system command' ),
  Examples( Fake( 'CallSystem(''date'')', 
		'Fri Apr 25 12:39:18 MEST 2003\n0') ),
  SeeAlso( LockFile, FileStat, OpenPipe, TimedCallSystem, SystemCommand )
):
 
NULL_Description := Description(
  variable( 'NULL' ),
  Synopsis('The NULL expression sequence.' )
):

libname_Description := Description(
  variable(noeval(libname)),
  Synopsis(
'The libname system variable stores the path of the Darwin library.
It is set by the -l flag when executing Darwin from the command line.')
):

version_Description := Description(
  function( version ),
  CallingSequence( noeval(version()) ),
  Returns( expseq ),
  Synopsis('Returns and expression sequence with 10 components:' ),
List( '%d',
'VersionType: string, Production or Debug',
'Architecture: string, encoded name of architecture',
'Version: number',
'CompiledWith: string, name of the compiler used',
'CompilerVersion: string',
'CompilerOptions: string',
'DateCompiled: string, result of system command date',
'CharactersPerWord: posint, number of characters per word',
'Vectorized: string, vectorized computations enabled by compiler',
'GitCommit: string, git-commit id of source used to compile' ),
  Examples( 'version()' )
):

DBL_MAX_Description := Description(
  variable( noeval(DBL_MAX) ),
  Synopsis('The system variable holds the value of the maximum double
numeric allowed in Darwin.  This variable is set in the library file
darwinit. The LongInteger() routines in Darwin allow for larger integers.' ),
  Examples( 'DBL_MAX' ),
  SeeAlso( LongInteger )
):

DM_Description := Description(
  variable('DM'),
  Synopsis( 'The DM (Dayhoff matrix) system variable has type
DayMatrix and contains a Dayhoff matrix computed at PAM distance
250 after a call to the function CreateDayMatrices().
Some routines perform all operations under the assumption
that the Dayhoff matrix currently contained in DM is the
correct Dayhoff matrix to use.'),
  SeeAlso( 'DMS', DayMatrix, CreateDayMatrices, CreateDayMatrix )
):

DMS_Description := Description(
  variable('DMS'),
  Synopsis( 'The DMS (Dayhoff matrices) system variable has
type list(DayMatrix) and contains 1266 Dayhoff matrices for
various PAM distances between 0.049 and 1000 after a call
to the function CreateDayMatrices().  Some routines perform
all operations under the assumption that the Dayhoff matrices
currently contained in DMS are the correct Dayhoff matrices to use.' ),
  SeeAlso( 'DM', DayMatrix, CreateDayMatrices, CreateDayMatrix )
):

lasterror_Description := Description(
  variable( noeval(lasterror) ),
  Synopsis( 'Contains the last error message generated by
Darwin during the current session' ),
  SeeAlso( 'traperror', error )
):

SeeAlso_IPC := SeeAlso( ConnectTcp, DisconnectTcp, ParExecuteSlave, 
ReceiveTcp, SendTcp, darwinipc, ipcsend, SendDataTcp, ReceiveDataTcp, 
ParExecuteIPC, ParExecuteTest ):

ConnectTcp_Description := Description(
  function(ConnectTcp),
  CallingSequence( noeval( ConnectTcp(path, slave) )),
  Parameters( [path, string, 'path to a UNIX pipe'], 
		[slave, boolean,''] ),
  Returns( 'NULL' ),
  Synopsis( 'Creates connection to IPC daemon at path (a UNIX pipe).
slave must be false for all darwin processes not created by the daemon.' ),
  Examples( Fake('r := traperror(ConnectTcp(''/tmp/.ipc/darwin'', false))',''),
Fake('SendTcp(''PING''); r := ReceiveTcp(3)', 'r := PING OK'),
Fake('SendTcp(''MSTAT linneus1''); r := ReceiveTcp(3)',
'r := DATA linneus1 0:OK ALIVE'),
  Fake('DisconnectTcp();','')),
  SeeAlso_IPC
):

DisconnectTcp_Description := Description(
  function(DisconnectTcp ),
  CallingSequence(noeval(DisconnectTcp() ) ),
  Returns(NULL ),
  Synopsis('Closes the connection to the IPC daemon.' ),
  Examples(
  Fake('r := traperror(ConnectTcp(''/tmp/.ipc/darwin'', false))',''),
  Fake('SendTcp(''PING''); r := ReceiveTcp(3)', 'r := PING OK'),
  Fake('SendTcp(''MSTAT linneus1''); r := ReceiveTcp(3)',
	'r := DATA linneus1 0:OK ALIVE'),
  Fake('DisconnectTcp();','')),
  SeeAlso_IPC
):

ReceiveTcp_Description := Description(
  function(ReceiveTcp ),
  CallingSequence(noeval(ReceiveTcp(timeout)) ),
  Parameters(['timeout',{0, posint},'seconds to wait for timeout'] ),
  Returns({NULL,string} ),
  Synopsis('Waits up to timeout seconds to receive data from the IPC daemon.
This command is usually preceded by a SendTcp.
Returns NULL if no data is received (i.e. timeout occurred).' ),
  Examples( 
Fake('r := traperror(ConnectTcp(''/tmp/.ipc/darwin'', false))',''),
Fake('SendTcp(''PING''); r := ReceiveTcp(3)', 'r := PING OK'),
Fake('SendTcp(''MSTAT linneus1''); r := ReceiveTcp(3)',
'r := DATA linneus1 0:OK ALIVE'),
  Fake('DisconnectTcp();','')),
  SeeAlso_IPC
):

SendTcp_Description := Description(
  function(SendTcp ),
  CallingSequence(noeval(SendTcp(data)) ),
  Parameters(['data',string, 'command to the ipcdeamon'] ),
  Returns(NULL ),
  Synopsis('SendTcp sends data to the IPC daemon. This data is usually
a command understood by darwinipc. See ?darwinipc. A SendTcp is followed
by a ReceiveTcp to read out the response from the daemon.' ),
  Examples( 
Fake('r := traperror(ConnectTcp(''/tmp/.ipc/darwin'', false))',''),
Fake('SendTcp(''PING''); r := ReceiveTcp(3)', 'r := PING OK'),
Fake('SendTcp(''MSTAT linneus1''); r := ReceiveTcp(3)',
'r := DATA linneus1 0:OK ALIVE'),
  Fake('DisconnectTcp();','')),
  SeeAlso_IPC
):

GetMachineUsage_Description := Description(
  function(GetMachineUsage ),
  CallingSequence(noeval(GetMachineUsage(logfile)) ),
  Parameters(['logfile',string] ),
  Returns( ),
  Synopsis('Reads a log file created by ParExecuteIPC and produces a listing
containing all machines and the work they did, sorted by machine usage.' ),
  SeeAlso_IPC
):


ParExecuteIPC_Description := Description(
  function(ParExecuteIPC),
  CallingSequence(noeval(ParExecuteIPC('queue', ProgFileName, machines, handler, 
delay, controls)) ),
  Parameters(['queue',list({string,structure}),'statements parameterizing each job'],
	['ProgFileName',string,'File name containing init and job procedures'],
	['machines',list(string),'list of machines to be used' ],
	['handler',{0,procedure},'result handler '],
	['delay',posint,'delay (secs) between checking machines: default 10'],
	['controls',string,'statements about how a job be can be executed']),
  Returns(NULL),
  Synopsis(' ParExecuteIPC runs the job described in ProgFileName
with the parameters in queue on machines. Before executing a task in 
parallel on several machines, several areas must be prepared.'),

Paragraph(2,'1). Find the machines to be used. The criteria for machines to be
used are that a) they are accessible via the Internet. b) all machines have
an account with the same name. c) All machines must be capable of running darwin
and darwinipc (See ?darwinipc).  It is possible to configure ParExecuteIPC
to use certain machines at specific times of the day, only when they
have a specific load or only when no one is logged in.  Machine names in
this list can have a suffix of the form ":class" where class is an integer
(see example).  If class suffixes are used, a machine with class greater than
zero when becoming idle will start a job already running on a machine of
lower class.  This avoids waiting for termination of the last few jobs
which are running on slow machines.'),
Paragraph(2,'2) Determine what files are needed.  All files that are
needed must be available with the same path name on all machines
(databases, darwin code, etc.).'), 
Paragraph(2,'3) Determine the smallest independent job.'),
Paragraph(2,'4) Determine the variables that parameterize a single job
and create a list (queue) of strings in which each string contains all
Darwin statements required to parameterize a job.' ),
Paragraph(2, '5) Create a file (ProgFileName) containing two parameterless
procedures- init and job.  init does the initialization (loads databases,
computes Dayhoff matrices) - its return value is ignored.  job does the
actual job and must return the results as a string.  Inside job, the global
variable PE_job is the number of the job being executed, and the global variable
tmpfile can be used as the name of a temporary scratch file, for instance to
write the results.
The job procedure should be written in such a way that it can be
executed several times within the same run (with different jobs).
Note: do not forget to declare all variables being used in both
procedures as global.'),
Paragraph(2,'6) Optionally, a result handler procedure can be created.
The result handler
accepts a job number (an integer) and its result (a string) and handles the
result.  Note that handling a job result should only take negligible time, so
this handler typically writes the result to a file.  If you do not provide your own
handler, the default handler (indicated by the number 0 as an argument to
ParExecuteIPC) is used. The default result handler creates one output file
per job: the results of job i are stored in ProgFileName.out.i.'),

Paragraph(2,'When ParExecuteIPC executes, it automatically creates two files-
ProgFileName.log and ProgFileName.done.  In ProgFileName.done, the job numbers
of the completed jobs are listed.  If the completion was not successful, then
the job number is preceded by a minus sign.
ProgFileName.log is a log of the
process execution.  It tells what the status of the machines was when
ParExecuteIPc was started, tells which machine is running each job and the
execution time.  It also contains any error messages generated by the
processes.  When ParExecuteIPC completes, it sends a mail message containing
some statistics unless the NoMail control statement is passed.'), 
Paragraph(2,'When ParExecuteIPC is killed before completion, it creates a
file named ParExecute.redo. If this file is renamed ParExecAction and the
ParExecuteIPC command is restarted, it will automatically complete all
jobs in the ParExecAction file.  When restarted, ParExecuteIPC will also redo
any jobs in the ProgFileName.done file that are preceded by a minus sign.
At anytime during the execution of ParExecuteIPC, control statements can
be executed by placing them in a file called ParExecAction in the directory
from which the command was run.'),

Paragraph(2,'ParExecuteIPC recognizes the following control statements.'),
Paragraph(0,''),
Table(center, gutter=2, ColAlign('l','l'),
Row('StartUsing m','Adds m to the pool of machines being used.'),
Row('StopUsing m','Removes m from the pool of machines to be used.  Any job'),
Row('','running on m is killed and its results discarded.'),
Row('Status','Write the status of all machines to the log file.'),
Row('LoginControl m on/off','Turn the login control on machine m on or off.'),
Row('ForcedRun m on/off','On machine m, force process to run (ignore BUSY flag)'),
Row('NiceValue m n','Run at nice n on machine m'),
Row('OffHours m from..to','Jobs running on machine m are stopped between from and to'),
Row('','hours (both in 24 hour notation).'),
Row('MaxJobs m n','Run n jobs (as if having n processors) on machine m'),
Row('LoadThreshold m low hi','A job in machine m is stopped when the load on its'),
Row('','machine is greater than hi, and is continued when the'),
Row('','load gets less than low.'),
Row('LoadThreshold low hi','Set global thresholds'),
Row('RunAlso job','Adds job command to the job queue.'),
Row('KillAll','Kill all running jobs and end ParExecuteIPC.  Send a'),
Row('','mail message with execution statistics to the user.'),
Row('Interrupt','Kill all running jobs and end ParExecuteIPC.  Write the'),
Row('','jobs to be finished into a file, ParExecAction.redo. '),
Row('NoMail','Turns off the sending of execution statistics by email.')
),

Paragraph(2,'There are four ways to send a control statement to a ParExecuteIPC job:'),
Paragraph(2,'1) As a line of the optional controls parameter when ParExecuteIPC is
invoked.'),
Paragraph(2,'As data being sent to the ParExecuteIPC process via Darwin''s IPC
feature (see ?darwinipc). This is the most efficient way and
response to the command is immediate.
For example, (assuming that the ParExecuteIPC process has pid
8281 and runs on ru3),
typing:'),
Paragraph(0,'ipcsend SEND ru2 8281:Status'),
Paragraph(2,'at the operating system prompt will cause the ParExecuteIPC status to
be reported on the log file.'),
Paragraph(2,'3) As a line of the file ParExecAction in the current directory of the
ParExecuteIPC process.  Whenever this file is found, it is read, processed and deleted.'),
Paragraph(2,'4) As a line of ParExecAction.pid in the current directory of the
ParExecuteAction process, where pid is the process id of the ParExecuteIPC process.
Whenever this file is found, it is read, processed and deleted.'),

Paragraph(2,'If login control is on, jobs are stopped whenever an interactive user
logs in to the machine, and are continued when no user is logged in.  Logins of
certain users can be excluded from this checking with the -u switch of the
darwinipc daemon (see ?darwinipc).'),
Paragraph(0,''),
Paragraph(2,'For the following example, first create a file with the name
"ParExample".  In that file, define procedures with the names init and job.
These procedure names are not optional.  In this example, a result handler
is also defined with procedure name "Handler".  This file name is optional.
Here is the contents of the file "ParExample":'),

Paragraph(0,'init := proc()'),
Paragraph(0,'  ReadDb(''/home/darwin/DB/SwissProt''):'),
Paragraph(0,'end:'),
Paragraph(0,''),
Paragraph(0,'job := proc()'),
Paragraph(0,'  sequ := SearchTag(''SEQ'',Entry(entry)):'),
Paragraph(0,'  sequence := staring(SearchSeqDb(sequ)):'),
Paragraph(0,'  sequence;'),
Paragraph(0,'end:'),
Paragraph(0,''),
Paragraph(0,'Handler := proc(job:integer,t:string)'),
Paragraph(0,'OpenAppending(''Job.results'');'),
Paragraph(0,' printf(''%s\n'',t):'),
Paragraph(0,'end:'),

Paragraph(2,'Before running the command, the queue which parameterizes each job, 
the machines to be used and the control strings must be defined.'),

  Examples(Fake('Machines:=[''linneus1:2'',''linneus2:3'']',''), 
Fake('Controls := ''OffHours linneus1 8..9 \n MaxJobs linneus2 4\n''',''),
Fake('queue := [seq(sprintf(''entry := %d:'',i),i=1..10)]',''),
Fake('ParExecuteIPC(queue,''ParExample'',Machines,Handler,10,Controls)','')
),
  SeeAlso_IPC
):


ParExecuteTest_Description := Description(
  function(ParExecuteTest),
  CallingSequence(noeval(ParExecuteTest(thisjob,ProgFileName,machine))),
  Parameters(['thisjob',{string,structure},'statements parameterizing one job'],
	['ProgFileName',string,'File name containing init and job procedures'],
	['machine',string,'machine to be used'] ),
  Returns(string),
  Synopsis('ParExecuteTest tests thisjob using the prog in ProgFileName
simulating a ParExecuteIPC on machine. It is designed to test the setup
of a ParExecuteIPC before running it on multiple machines.'),
Paragraph(2,'For the following example, first create a file with the name
"ParExample".  In that file, define procedures with the names init and job.
These procedure names are not optional.  
Here is the contents of the file "ParExample":'),

Paragraph(0,'init := proc()'),
Paragraph(0,'  ReadDb(''/home/darwin/DB/SwissProt''):'),
Paragraph(0,'end:'),
Paragraph(0,''),
Paragraph(0,'job := proc()'),
Paragraph(0,'  sequ := SearchTag(''SEQ'',Entry(entry)):'),
Paragraph(0,'  sequence := staring(SearchSeqDb(sequ)):'),
Paragraph(0,'  sequence;'),
Paragraph(0,'end:'),
Paragraph(0,''),
Examples(Fake('queue := [seq(sprintf(''entry := %d:'',i),i=1..10)]:',''),
  Fake('ParExecuteTest(queue[2],''ParExample'',linneus2):',
'Warning: procedure Handler reassigned
May 20 13:16:10 2003: linneus2 creates parallel process
May 20 13:16:10 2003: linneus2(19680) started
May 20 13:16:10 2003: linneus2(19680) initialized (0.0 s CPU)
May 20 13:16:10 2003: linneus2(19680) started job
May 20 13:16:10 2003: linneus2(19680) completed job (0.0 s CPU), result:
MASVKSSSSSSSSSFISLLLLILLVIVLQSQVIECQPQQSCTASLTGLNVCAPFLVPGSPTASTECCNAVQSINHDCMC
May 20 13:16:10 2003: linneus2(19680) ending
May 20 13:16:10 2003: linneus2(19680) ended')),
  SeeAlso_IPC
):

Process_Description := Description(
  structure( Process),
  Summary( 'structure to hold Process information' ),
  CallingSequence( noeval( Process( Pid,Job,Stopped,EventTime,JobTime)) ),
  Parameters(
	[ Pid, integer ],
	[ Job, integer ],
	[ Stopped, boolean ],
	[ EventTime, numeric ],
	[ JobTime, numeric ] ),
  Returns( Process ),
  Selectors(
	[ ElapsedTime, string ] ),
  Synopsis( 'This data structure holds information about a particular
process in a machine.  The main application is for parallel processing
and hence it contains all sorts of status information.' ),
  SeeAlso( Machine, ParExec2, darwinipc )
):

Machine_Description := Description(
  structure( Machine),
  Summary( 'structure to hold Machine references' ),
  CallingSequence( noeval( Machine( Name, User, Class, Processes,
	MaxProcesses, LoginControl, OffHours, LoadRange,
	ForcedRun, NiceValue, StartCycle, DownCount, LastProcess)) ),
  Parameters(
	[Name, string],
	[ User, string],
	[ Class, integer],
	[ Processes, list(Process)],
	[ MaxProcesses, posint],
	[ LoginControl, boolean],
	[ OffHours, integer..integer],
	[ LoadRange, numeric..numeric],
	[ ForcedRun, boolean],
	[ NiceValue, integer],
	[ StartCycle, numeric],
	[ DownCount, integer],
	[ LastProcess, integer] ),
  Returns( Machine ),
  Synopsis( 'This data structure holds information about a particular
machine (computer).  The main application is for parallel processing
and hence it contains all sorts of controlling information.' ),
  SeeAlso( ParExec2, darwinipc, Process )
):

Descriptions := noeval(Descriptions):




######  Structures ######

Match_Description := Description(
  structure( Match ),
  Summary('Structure data type to hold peptide/peptide matches'),
  CallingSequence( noeval(Match( Offset1, Offset2 )),
	noeval(Match( Sim, Offset1, Offset2)),
	noeval(Match( Sim, Offset1, Offset2, Length1, Length2)),
	noeval(Match( Sim, Offset1, Offset2, Length1, Length2, pam)),
	noeval(Match( Sim, Offset1, Offset2, Length1, Length2, PamNumber, PamVariance)) ),
  Parameters( ['Sim', numeric, 'similarity score of the Match'], 
	['Offset1', posint, 'offset of the first sequence in the database'], 
	['Offset2', posint,'offset of the second sequence in the database'],
	['Length1', posint, 'length of the match of the first sequence'], 
	['Length2', posint, 'length of the match of the second sequence'], 
	['PamNumber', numeric, 'Estimate of the PAM distance between the sequences'],
	['PamVariance', numeric, 'Estimate of the PAM variance between the sequences'] ),
  Returns( Match ),
  Synopsis( 'The Match structure holds all the necessary information
for the alignment of two peptide sequences.  The offsets are positions
into a peptide database, hence Match requires that an appropriate
database has been loaded.  The offsets are relative to the system
variable DB.  Typically, Match structures are initialized by giving
only the two offsets.  The remaining fields are completed by one
of several alignment algorithms.' ),
  Examples( FakeReadDb,
	'm:=Match( Sequence(Entry(1)), Sequence(Entry(2)) )',
	'm2 := Match( GetOffset(''UTTUWPC''), Sequence(Entry(20)))' ),
  SeeAlso( GetOffset, NucPepMatch, ReadDb, MAlign, TotalAlign )
):

NucPepMatch_Description := Description(
  structure( NucPepMatch ),
  CallingSequence( noeval(NucPepMatch (NucEntries, PepEntries)),
  	noeval(NucPepMatch (NucOffset,PepOffset)),
  noeval(NucPepMatch (Sim,NucOffset,PepOffset,NucLen,PepLen)),
  noeval(NucPepMatch (Sim,NucOffset,PepOffset,NucLen,PepLen,PamNumber)),
  noeval(NucPepMatch (Sim,NucOffset,PepOffset,NucLen,PepLen,PamNumber,PamVariance)),
  noeval(NucPepMatch (Sim,NucOffset,PepOffset,NucLen,PepLen,PamNumber,PamVariance,
	  IntronScoring)),
  noeval(NucPepMatch (Sim,NucOffset,PepOffset,NucLen,PepLen,PamNumber,PamVariance,
	  IntronScoring,NucGaps,PepGaps,Introns))),
  Parameters(
    ['Sim',numeric,'Similarity score'],
    ['NucOffset',integer,'Offset of the nucleotide sequence in NucDB'], 
    ['PepOffset',integer,'Offset of the peptide sequence in PepDB'], 
    ['NucLength',integer,'Length of the nucleotide sequence'],
    ['PepLength',integer,'Length of the peptide sequence'],
    ['PamNumber',numeric,'Estimated PAM distance for the match'],
    ['PamVariance',numeric,'Estimated PAM variance for the match'], 
    ['IntronScoring',{structure, string, 0},'Function for scoring introns'],
    ['NucGaps',list,'Gaps in the nucleotide sequence from the alignment'],
    ['PepGaps',list,'Gaps in the peptide sequence from the alignment'],
    ['Introns',list,'List of suspected introns'] ),
  Returns( ),
  Synopsis( 'The NucPepMatch structure holds all the necessary
information for the alignment of a peptide and a nucleotide sequence.
The offsets are positions into a peptide and nucleotide database,
hence NucPepMatch requires that appropriate databases have been loaded.' ),
  Examples( ),
  SeeAlso(AlignNucPepAll, AlignNucPepMatch, Denormalize, 
DynProgNucPepString, FindNucPepPam, Gene, GetAllNucPepMatches, 
GetPeptides, GetIntrons, GetPosition, GlobalNucPepAlign, Intron, 
LocalNucPepAlign, LocalNucPepAlignBestPam,
Match, Normalize, NucDB, NucPepDynProg, NucPepBackDynProg, NucPepMatch, 
NucPepRegions, ParallelAllNucPepMatches, PepDB, ScoreIntron,
VisualizeGene, VisualizeProtein ) 
):

Paragraph_Description := Description(
  structure(Paragraph ),
  Summary( 'holds contents of a paragraph of text' ),
  CallingSequence(
	noeval( Paragraph(content1,'...') ),
	noeval( Paragraph(indent,content1,'...')) ),
  Returns( Paragraph ),
  Selectors( [indent,integer,'the integer indentation value'],
	[content_i,{string,structure},'the text content of the Paragraph'] ),
  Synopsis( 'The Paragraph structure holds text that is expected to
be laid out as a paragraph.  The integer value indent specifies the
number of blank positions to be added at the beginning of the first line.
If the indent value is negative, then the first line is not indented,
but the rest of the lines will be indented by -indent.
Paragraphs are typically part of Documents or Descriptions or any
place where text must be formatted.
When a Paragraph is converted to a string, each content_i is converted
to a string, all concatenated together and properly broken into lines
not exceeding the value of the interface variable screenwidth.
A newline character is always added at the end of the last line of
the converted Paragraph.
Any newlines or tab characters in the contents are changed into spaces.' ),
  Examples( 'p := Paragraph( 5, ''This text is indented 5 spaces'' )',
	Print( 'print(p)' ),
	Unassign('p')),
  SeeAlsoDocument
):

Roman:  # the parse statement will not automatically load from the library
List_Description := Description(
  structure(List ),
  Summary( 'holds contents of a List of displayable items' ),
  CallingSequence(
	noeval( List(labelling,item1,item2,'...') )),
  Returns( List ),
  Selectors( [labelling,{procedure,string},'labelling method'],
	[item_i,{string,structure},'text or structure for each entry']),
  Synopsis( 'The List structure holds information which will be
formatted as a simple list.
The first argument is a procedure which should produce a string
for each integer argument.
This will be the label that is used for each entry in the list.
If the first argument is a string with a "%" in it, it is
interpreted as an argument for sprintf.
This is an easy way to provide arbitrary formating of numbers.
If it is a string, that string is used for all items in the list.
A list is normally part of a Document or some other structure
intended for display or human-readable purposes.
The following table shows some common labelling functions
and their results for a few integers:' ),
Table( center, gutter=2, ColAlign('l','r','r','r','r','r'),
  Row( procedure, 1, 2, 10, 20 ,30 ), Rule,
  seq( Row( p, parse(p)(1), parse(p)(2), parse(p)(10), parse(p)(20),
	parse(p)(30) ), p = [ 'Roman', 'Alphabetical',
	'x->lowercase(Roman(x))',
	'x->sprintf(''(%s)'',Alphabetical(x))'] ),
  Row( '''(%d)''', '(1)', '(2)', '(10)', '(20)', '(30)' ),
  Row( '''o''', 'o', 'o', 'o', 'o', 'o' )),
  Examples( 'string( List(''--%d--'',First,Second))' ),
  SeeAlsoDocument
):

Document_Description := Description(
  structure(Document ),
  Summary( 'holds contents of a human-readable document' ),
  CallingSequence(
	noeval( Document(content1,content2,'...') ) ),
  Returns( Document ),
  Selectors(
	[content_i,{string,structure},'the contents of the Document'] ),
  Synopsis( 'The Document structure holds text and other structures
which are expected to be laid out as a Document.
When a Document is converted, each content_i is converted to the
same target.
Normally a Document is converted to a string, HTML or Latex.
Besides text, the following structures are valid inside Documents:' ),
Table( center, gutter=3, ColAlign('l','l'),
  Row( 'Name/Use', 'Description' ), Rule,
  Row( 'Alphabetical(int)', 'Convert a number to alphabetical numerals' ),
  Row( 'Alphanumerical(int)', 'Convert a number to alphanumerical numerals' ),
  Row( 'Bold(txt,...)', 'Bold text' ),
  Row( 'Center(txt,...)', 'Center the contents' ),
  Row( 'Code(txt,...)', 'preformated, equally spaced text' ),
  Row( 'Color(code,txt)', 'Color the contents' ),
  Row( 'Copyright(who)', 'Insert copyright symbol, year and argument.' ),
  Row( 'Font(font,txt,...)', 'Set contents with a given font' ),
  Row( 'HyperLink(txt,URL)', 'URL linked data' ),
  Row( 'Indent(txt,...)', 'Indented data' ),
  Row( 'IT(txt,...)', 'Italic text' ),
  Row( 'LastUpdatedBy(who)', 'Convenient macro to end Document page.' ),
  Row( 'List(format,txt,...)', 'List/Definitions/bullets' ),
  Row( 'MapleFormula(string)', 'mathematical formula in Maple format'),
  Row( 'Ordinal(int)', 'Convert a number to its ordinal ending' ),
  Row( 'Paragraph(int,txt,...)', 'A paragraph of text, lines adjusted' ),
  Row( 'PlusMin(string)', 'Expand +- to proper plus-minus symbols' ),
  Row( 'PostscriptFigure(psfile,...)', 'Figure from postscript source' ),
  Row( 'Roman(int)', 'Convert a number to roman numerals' ),
  Row( 'SectionHeader(lev,txt)', 'Section/subsection header' ),
  Row( 'Size(size,txt,...)', 'Set contents to a given size' ),
  Row( 'Table(...)', 'Tabular data' ),
  Row( 'TT(txt,...)', 'tty format (equally spaced font)' )),
Paragraph( 'where txt means a string or any structure that will
represent text.'),
  Keywords(Alphabetical,Alphanumerical,Bold, Center, Copyright,
Font, HyperLink, Indent, IT, LastUpdatedBy, Ordinal,
PlusMin, Roman, SectionHeader, Size ),
  Examples( 'd := Document( Paragraph(2,Hi), Indent(5,List(Roman,first,second)) )',
	Print( 'print(d)' ), Unassign('d') ),
  SeeAlsoDocument
):



PatEntry_Description := Description(
  structure(PatEntry ),
  Summary ('Data structure for entries to the Pat index for the database DB'),
  CallingSequence(noeval(PatEntry(a)) ),
  Parameters(['a',{integer,range, list(integer), string },
	'PatEntry number(s) in the database DB'], 
	['','','or a string to be searched'] ),
  Returns(PatEntry),
  Synopsis('When a Darwin database is read for the first time,
Darwin will automatically create a Patricia tree data structure
from the contents of the SEQ field for each entry.
This is accessed via a Pat index.
PatEntry is a data structure for entries to the Pat index for
the database DB.  If the argument is an integer, a list of integers
or a range of integers, these are considered to be entries in the
Pat index of the database.  If a string is given, it is assumed
to be a sequence, and the Pat index is searched for all the sequences
which contain the string exactly.  The result is returned as a range,
even in the case that it is not found (an empty range) which is useful
as it points to the two closest neighbouring sequences in the database.
Searching for exact identity of peptides using PatEntry is very fast.' ),
  Examples(
  'PatEntry(1)',
  'PatEntry(1..5)',
  'PatEntry(''HHHHHHHH'')',
  'PatEntry(''B'')',
  'PatEntry(''C'')',
  'Sequence(PatEntry(CCCCCCCC))'
 ),
  SeeAlso(Entry, Sequence, Match, string, ID )
):

Permutation_Description := Description(
  structure( Permutation ),
  Summary( 'a mathematical permutation' ),
  CallingSequence( noeval(Permutation(p)), noeval(Permutation(n)) ),
  Parameters( [p,list(posint),'list of integers from 1 to n'],
	[n,posint,'creates an identity permutation of size n'] ),
  Returns( Permutation ),
  Synopsis( 'A Permutation holds a list of consecutive
positive integers which describe how to permute a set of
size n.
Permutations can be multiplied (the product of two
permutations a * b is a permutation which is identical
to applying b and then a).
Permutations can also be powered, in particular an inverse
permutation is obtained by 1/a.' ),
  Examples( 'a := Rand(Permutation(7))',
	'b := Rand(Permutation(7))',
	'a*b', '1/a' ),
  SeeAlso( Rand, CreateRandPermutation, Mutate, Shuffle )
):

PlotArguments_Description := Description(
  structure( PlotArguments ),
  Summary( 'structure to hold plotting/drawing options' ),
  CallingSequence( noeval(PlotArguments(Title, TitleX, TitleY, TitlePts,
	Lines, Grid, LabelFormat, GridFormat, Colors, Axis)) ),
  Parameters( ['Title', string,'text to be displayed in the plot' ],
	['TitleX', numeric,'x coordinate of the title'],
	['TitleY', numeric,'y coordinate of the title'],
	['TitlePts', numeric,'point size of the title'],
	['Lines', boolean],
	['Grid', boolean],
	['LabelFormat', string],
	['GridFormat', string],
	['Colors', string, 'colour map'],
	['Axis', boolean,'axis will be drawn'] ),
  Returns( PlotArguments ),
  Synopsis( 'Structure to hold plot options.  This structure is used
internally by several drawing functions.  The way of filling the values
is uniform for all the functions, and these accept the values in the
following format:' ),
'',
Table( center, ColAlign('l','l'),gutter=3,
Row( 'Title'=string, 'text to be displayed in the plot' ),
Row( 'TitleX'=numeric, 'x coordinate of the title' ),
Row( 'TitleY'=numeric, 'y coordinate of the title' ),
Row( 'TitlePts'=numeric, 'point size of the title' ),
Row( 'Lines'=boolean, 'draw horizontal lines' ),
Row( 'Grid'=boolean, 'draw a grid (horizontal and vertical lines' ),
Row( 'LabelFormat'=string, 'printf-style format for labels' ),
Row( 'GridFormat'=string, 'printf-style format for Lines or Grid values' ),
Row( 'Colors'=list, 'list of colors suitable for GetColorMap' ),
Row( 'Axis'=boolean, 'draw x and y axes' )
),
  SeeAlso_Plot
):

Table_Description := Description(
  structure(Table ),
  Summary( 'structure to print/display tables' ),
  CallingSequence(
	noeval( Table(arg1,'...',argn) ) ),
  Parameters( ['arg1..n',anything, 'components of table in any order'],
	['', 'center', 'the entire table is centered'],
	['', 'border', 'the entire table is framed with a border'],
	['', 'gutter=posint', 'set gutter between columns'],
	['', 'gutter=list(posint)', 'set gutter for each individual column'],
	['', 'ColAlign({string,p(posint)}...)',
		'set alignment for each individual column'],
	['', 'RowAlign(string)',
		'set vertical alignment for following rows'],
	['', '', '(''l'', ''c'' and ''r'' for left, center, right)'],
	['', 'Row(args)', 'a row of data, each argument in a column'],
	['', 'title=string', 'title/caption to describe the table'],
	['', 'Values(args)', 'args to be distributed columwise'],
	['', 'rowwise', 'uses Values(), but args are distributed rowwise'],
	['', 'width=posint', 'width of the table in characters'],
	['', 'Rule', 'draw a horizontal line'],
	['', 'SpanPrevious ', 'possible argument of Row']
	),
  Returns( Table ),
  Synopsis( 'The Table structure holds information describing a
table (or tabular information).  This is expected to be laid out
as a table either as text, latex, html or something else.
If a Row structure has an element with the name ''SpanPrevious'',
then the previous entry will be expanded to occupy also the space
of this entry (like \\multicolumn in latex or colspan in html).
The alignment inside the cells are set with ColAlign - either l (left), r (right),
c (center) or p(x) (paragraph with a fixed width of x characters).' ),
  Examples( 't := Table( center, border, gutter=4, Row(''abc'',''cde''),Row(1,1e9)):',
	Print('print(t)'), Unassign('t') ),
  SeeAlsoDocument
):


MapleFormula_Description := Description(
  structure(MapleFormula),
  Summary('mathematical formula given in Maple format'),
  CallingSequence( noeval(MapleFormula(string))),
  Parameters( [string,'math formula in maple format'] ),
  Returns(MapleFormula),
  Synopsis( 'A MapleFormula object is constructed with a single argument, the
formula that is to be sent to Maple for "nice" text output formatting.'),
  Examples( 'M := MapleFormula(''sum(i,i=1..10)''):',Print('print(M)')),
  SeeAlsoDocument
):


PostscriptFigure_Description := Description(
  structure(PostscriptFigure),
  Summary('figure given by a postscript file (Darwin or other)'),
  CallingSequence( noeval(PostscriptFigure())),
  Parameters(
	[psfile,string,'(opt) file name containing the postscript'],
	[caption,Caption=string,'(opt) caption to describe the figure'],
	[convmeth,Convert=string,'(opt) conversion method'],
	[linkas,LinkAs=string,'(opt) path of image source in HTML'],
	[newfn,PlaceUnder=string,'(opt) name of converted image file'],
	[modif,string=string,'(opt) pattern substitutions for input file']
 ),
  Returns(PostscriptFigure),
  Synopsis( 'A PostscriptFigure object is constructed from a postscript
file which could be generated by a Darwin Draw command or from some
other source, e.g. xfig.
This structure is normally held in a Document and is displayed as
appropriate (as HTML, latex or a string).
If no psfile is given, it is assumed that it comes from a Draw command
and hence plotoutfile is used.
When this structure is converted to HTML, a .gif or .jpg file has to be made.
The default method is ''auto'' which will use the UNIX tool ''convert''
to automatically create a .jpg file without user interaction. If this
does not lead to satisfying results or some modifications (e.g. rotation) has
to be performed, the method ''gimp'' should be used. This will open the
file in Gimp and gives control to the user.
Hence Gimp has to be available in the system.
The LinkAs option allows linking the file under a different path when
converting to HTML. With PlaceUnder a filename for the converted
file can be given. This filename also determines the image format (.gif
or .jpg).
If it is converted to latex, the postscript is converted to
encapsulated postscript with ps2eps, which should also be available.
Conversion to a string just prints a box with a unix command
suitable to display the contents.'),
Paragraph( -2, 'The modifiers are a simple mechanism to modify
previously created postscript files.
Textual substitution will be performed (length issues are ignored, and
most of the time they work well).
These substitutions should be based on a relatively unique pattern,
short patterns that may coincide with other postscript commands are
bound to be disastrous.'),
  Examples( 'PostscriptFigure( ''PAMgraph.ps'', Caption=''Score vs PAM'')' ),
  SeeAlsoDocument
):


Code_Description := Description(
  structure(Code),
  Summary('placeholder for text that should be displayed "as is"'),
  CallingSequence( noeval(Code(string1,'...'))),
  Parameters( [string1,string,'text to be displayed as is'] ),
  Returns(Code),
  Synopsis( 'The Code data structure holds text that is to be
displayed preserving all spaces, tabs, newlines, etc.  This is
what is expected to happen to a program.  The content of Code
will normally be displayed with constant-width font.
Any newlines appearing in the argument strings will be displayed.
Additionally, a newline is inserted at the end of every argument.
Arguments of Code will be displayed in new lines.  So if the
insertion of code is desired within a sentence, the TT() structure
should be used (constant width font).' ),
  Examples( 'Code( ''for i to 10 do lprint(i^2) od'')' ),
  SeeAlsoDocument
):


TT_Description := Description(
  structure(TT),
  Summary('placeholder for text that should be displayed "as is"'),
  CallingSequence( noeval(TT(string1,'...'))),
  Parameters( [string1,string,'text to be displayed as is'] ),
  Returns(TT),
  Synopsis( 'The TT data structure holds text that is to be
displayed using a constant width font (like in a typewriter)' ),
  Examples( 'TT( ''for i to 10 do lprint(i^2) od'')' ),
  SeeAlsoDocument
):


Color_Description := Description(
  structure(Color),
  Summary('structure to define the color of some document part'),
  CallingSequence( noeval(Color(colcode,doc1,'...'))),
  Parameters( [colcode,string,'a color name or its hex RGB values'] ),
  Returns(Color),
  Synopsis( 'The Color data structure holds document parts that
are to be displayed in that color.  The number of arguments is variable.' ),
  Examples( 'Color( red, ''Your balance is negative'' )' ),
  SeeAlso( op(SeeAlsoDocument), string_RGB, RGB_string )
):


string_RGB_Description := Description( function(string_RGB),
  Summary( 'convert a color name into an RGB vector' ),
  CallingSequence( noeval(string_RGB(s)) ),
  Parameters( ['s',string, 'an color name without spaces'] ),
  Returns([nonnegative,nonnegative,nonnegative]),
  Synopsis( 'This function converts a color name into a
3 value RGB vector.
The vector contains the values for red, green and blue in a scale
of 0 to 1.
Black is [0,0,0] and white is [1,1,1].
The name matching is case independent and it tolerates up to two
errors.
About 650 colours are known to this function.
The full list can be found at lib/Color.' ),
  Examples( 'string_RGB(MidnightBlue)', 'string_RGB(midnightBLAU)',
	'string_RGB(chocolate)' ),
  SeeAlso( Color, string_RGB, RGB_string, DrawTree )
  ):


RGB_string_Description := Description( function(RGB_string),
  Summary( 'convert an RGB vector into a color name' ),
  CallingSequence( noeval(RGB_string(rgb)), noeval(RGB_string(r,g,b)) ),
  Parameters( ['rgb',list(nonnegative), 'an RGB vector of length 3'],
	[r,nonnegative,'intensity for red (0..1)'],
	[g,nonnegative,'intensity for green (0..1)'],
	[b,nonnegative,'intensity for blue (0..1)'] ),
  Returns(string),
  Synopsis( 'This function converts a 3 value RGB vector into
a color name.
The vector contains the values for red, green and blue in a scale
of 0 to 1.
Black is [0,0,0] and white is [1,1,1].
The matching is approximate and the result is the one which is
closest in euclidean distance to one in the table.
About 650 colours are known to this function.
The full list can be found at lib/Color.' ),
  Examples( 'RGB_string([0,0,0])', 'RGB_string(0.5,1,0)',
	'RGB_string(.8,.4,.1)' ),
  SeeAlso( Color, string_RGB, RGB_string, DrawTree )
  ):


ColorPalette_Description := Description( function(ColorPalette),
  Summary( 'creates a set of colors according to a colormap' ),
  CallingSequence( noeval(ColorPalette(n)), noeval(ColorPalette(n, map)) ),
  Parameters(
    ['n',posint,'the number of different colors to be created'],
    ['map',string, '(optional) a colormap'] ),
  Returns( list([nonnegative,nonnegative,nonnegative]) ),
  Synopsis('This function computes n different colors according to
a colormap and returns their RGB values between [0,1]. The possible
colormaps are described below and completely specify the appearance
of the colors:'),
'',
Paragraph(-2,'The map parameter can be one of the following colormaps:'),
Paragraph(-13,'  <default>  jet'),
Paragraph(-13,'  jet        jet ranges from blue to red, and passes
through the colors cyan, yellow, and orange. It is a variation of the
hsv colormap.'),
Paragraph(-13,'  hsv        hsv varies the hue component of the
hue-saturation-value color model. The colors begin with red, pass
through yellow, green, cyan, blue, magenta, and return to red. The
colormap is particularly appropriate for displaying periodic functions.'),
Paragraph(-13,'  heat       heat varies the color from a saturated
blue through white into a saturated red. This map is useful for heatmaps,
where negative and positive values are possible.'),
Paragraph(-13,'  stoplight  stoplight gives colors from red through yellow
to green.'),
Paragraph(-13,'  lines      lines gives a list of distinct colors.'),
Examples( 'colors := ColorPalette(10)' ),
  SeeAlso( op(SeeAlso_Plot) )
):

BrightenColor_Description := Description( function(BrightenColor),
  Summary('Brighten or darken a RGB color'),
  CallingSequence( noeval(BrightenColor(color)), 
                   noeval(BrightenColor(color,beta)) ),
  Parameters(
    ['color',list(nonnegative),'a RGB color'],
	['beta',numeric,'(optional) amount of increase/decrease in brightness']),
  Returns([nonnegative,nonnegative,nonnegative]),
  Synopsis('BrightenColor increases or decreases the color intensity. If 
0 < beta < 1, the color gets brighter and if -1 < beta < 0 the color gets
darker. The operation is not necessarily reversable (see example). 
The default value for beta is 0.3'),
  Examples( 'BrightenColor([1,0,0])',
      'BrightenColor([0.5,0.5,0.5], -.2)',
	  'BrightenColor(BrightenColor([0.3,0.5,0.9],-0.4),0.4)'),
  SeeAlso( op(SeeAlso_Plot) )
):

matrix_Description := Description(
  structure( matrix ),
  Summary( 'a matrix of elements' ),
  CallingSequence( noeval( CreateArray(1..m,1..n)),
	[['...'],['...'],'...'] ),
  Returns( matrix ),
  Synopsis( 'A matrix in darwin is a list of lists where all the
internal lists have the same length.  A matrix can be created
with CreateArray, explicitly as a list of lists, with append
or iteratively.  Algebra between matrix and scalars or
between matrix and vectors follows the normal rules of Linear
Algebra.  A matrix multiplied by a vector on the right assumes
the vector is a column vector.  A matrix multiplied by a vector
on the left assumes the vector is a row vector.' ),
  Examples( '[[1,2],[2,3]]', 'CreateArray(1..3,1..4,777)' ),
  SeeAlso( list, CreateArray, op(SeeAlsoLinAlg),
    SvdBestBasis, CovarianceAnalysis, SvdAnalysis, LinearRegression )
):

list_Description := Description(
  structure(list ),
  Summary( 'list or array of arbitrary elements' ),
  CallingSequence( [], [noeval(a)], ['a,...'] ),
  Parameters( [noeval(a),anything] ),
  Returns( list ),
  Selectors( ['<integer>','the ith element in the list'],
	['<integer>..<integer>', 'a sublist of elements from the list']),
  Synopsis( 'A list holds arbitrary values or structures.
Elements in the list are left in the order the list was created.
A list is also an array. A list of lists (of the same length) is a matrix.
Elements of a list can be replaced with an assignment statement.
Arithmetic operations work on lists (arrays) and lists of lists (matrices)
according to the normal rules of linear algebra. (See examples)
As an array, the list has no interpretation of column or row.
It will act as column or row depending on the operation performed on it.
When selecting with an integer range, negative values are interpreted
as counting from the right.  I.e. -2..-1 select the last two elements
of the list.'),
  Examples( 'a := [b,1,2,2]',
    'a[1]', 'a[1..2]', 'a[-1..-1]', 'a[-2..-1]', 'a[3] := 77', 'a',
    'A := [[1,2],[3,0]]', 'V := [-2,3]', 'A*V', 'V*A', '2*A', 'A/3',
    '7*V', 'V/5', 'V*V', 'B := 1/A', 'A*B', 'V+[0,1]',
    Unassign( 'a','A','V','B' ) ),
  SeeAlso( member, subset, mselect, set, append, CreateArray, matrix )
):

set_Description := Description(
  structure(set ),
  Summary( '(mathematical) set of arbitrary elements' ),
  CallingSequence( {}, {a}, {'a,...'} ),
  Returns( set ),
  Selectors( ['<integer>','the ith element in the set'],
	['<negint>','the ith element from the right'],
	['<integer>..<integer>',
	'an expseq of elements from the set']),
  Synopsis( 'A set holds a set of arbitrary values or structures.
Elements in the set are ordered according to a unique order,
and repeated elements are removed.
Elements of a set (when the user is sure where they are located),
can be replaced with an assignment statement.
When selecting with an integer range, negative values are interpreted
as counting from the right.  I.e. -2..-1 select the last two elements
of the set.  The sorting of sets is very efficient, so if order is
desired, placing the information in sets may be more efficient.'),
  Examples( 'a := {b,1,2,[d,e]}',
    'a[1]', 'a[1..2]', 'a[-1..-1]', 'a[-2..-1]', 'a[3] := 77', 'a',
    Unassign('a') ),
  SeeAlso( 'union', 'minus', member, 'intersect', subset, mselect, list,
	sort, append )
):


table_Description := Description(
  structure(table ),
  Summary( 'structure to store and retrieve elements by name' ),
  CallingSequence( noeval(table()), noeval(table(unassig)) ),
  Parameters(
   [unassig,anything,'value to be returned for an unassigned entry'],
   ['',procedure,'a procedure that will be invoked on unassigned entries'] ),
  Returns( table ),
  Selectors( [key,anything,'key value for accessing or storing in table'] ),
  Synopsis( 'A table stores arbitrary values or structures, which can
be accessed by a key.
The key can be any valid object in Darwin.
The access to the table is done with normal indexing and the assignment
of values is done with assignments.
When an inexistent element is accessed a special value is returned.
By default this value is the symbol "unassigned".
It can be changed to any other value.
If the default value is a procedure, it will be understood that the
value to be returned on an inexistent entry is the result of computing
the procedure over the argument.
For sparse numerical tables, it is convenient to set the unassigned value
to 0 so addition into the table can be done directly.' ),
Paragraph( -2, 'To test if an entry is assigned or not, it is not
possible to use the function assigned, as the table is not a name,
and non-existent entries are automatically considered to have the
default value.
Instead, testing for the default value should be used.'),
Paragraph( -2, 'The iterator Indices() will operate on a table
and iterate over all the existing (assigned) indices of the table.' ),
  Examples( 'Kingdom := table(unknown):',
	'Kingdom[mouse] := Eukaryota:  Kingdom[ecoli] := Bacterium:',
	'[Kingdom[mouse], Kingdom[rat]];',
	Print( 'print(Kingdom)' ),
	'Kingdom[ecoli] := Bacteria',
	Print( 'for z in Indices(Kingdom) do lprint(z,Kingdom[z]) od'),
	Unassign('z','Kingdom') ),
  SeeAlso( member, set, subset, Table, SearchArray, SearchOrderedArray,
	SearchAllArray, assigned )
):


Stat_Description := Description(
  structure(Stat ),
  Summary ('Basic Univariate Statistics Package'),
  CallingSequence(noeval(Stat()),noeval(Stat('Description')) ),
  Returns(Stat),
  Selectors (['Number',integer,'number of observations recorded'],
	['Mean',numeric,'mean of the sample'],
	['Average',numeric,'mean of the sample (same as Mean)'],
	['Variance',numeric, 'variance of the sample'],
	['VarVariance',numeric, 'variance of the observed variance'],
	['Skewness',numeric, 'coefficient of skewness (sidewise leaning)'],
	['Excess',numeric, 'excess (flatness, or kurtosis)'],
	['Min',numeric, 'the minimum of the sample'],
	['Minimum',numeric, 'the minimum of the sample'],
	['Max',numeric, 'the maximum of the sample'],
	['Maximum',numeric, 'the maximum of the sample'],
	['ShortForm',string,'Description: MeanVar'],
	['StdErr',numeric, '95% conf. interval of mean'],
	['CV',numeric, 'coefficient of variance (std. dev/mean)'],
	['Description',string, 'user-defined description'],
	['MeanVar',string, 'form: xxx+-xx (mean and 95% conf. interval)'],
	['VarVar',string, 'form: xxx+-xx (variance and 95% conf. interval)']
 ),
  Synopsis('Stat defines a new data structure to gather univariate
statistical information. Methods exist for printing, adding and creating
a union of two Stat data structures.
The extraction of useful statistical data from the information collected
in a Stat data structure is performed with the provided selectors.' ),
  References( 'Handbook of Mathematical Functions, M. Abramowitz and
I. Stegun, Ch 26.1' ),
  Examples('BooHoo := Stat(''Stock Market Losses'')',
	'BooHoo2 := Stat(''More Losses'')',
	'UpdateStat( BooHoo, 10000 ):',
	'UpdateStat( BooHoo, 30000 ):',
	'UpdateStat( BooHoo2, 50000 ):',
	'UpdateStat( BooHoo2, 60000 ):',
	'BooHoo[Mean]',
	'BooHoo[Number]',
	'Akk := BooHoo union BooHoo2',
	Print('print(BooHoo)')
),
  SeeAlso(OutsideBounds, UpdateStat, LinearRegression, ExpFit, ExpFit2, Counter, CollectStat )
):


Counter_Description := Description(
  structure(Counter ),
  Summary ('accumulates values'),
  CallingSequence(noeval(Counter()),noeval(Counter('title')) ),
  Returns(Counter),
  Selectors (['value',numeric,'accumulated value of the counter'],
        ['title',string, 'user-defined description']),
  Synopsis('A Counter is an object which stores a number.
It is understood that this number
is incremented occasionally, that is the purpose of a counter.
It is possible to have as many counters as we want, each one with its
own description.
The way to increment a Counter is by add a value to the structure.
E.g. c1+1, will increment the Counter c1 by 1.
The counter is incremented as a side effect of the addition (or subtraction).
The result of the expression is the total accumulated so far.'),
Paragraph( -2, 'A Counter can also be multiplied by a numerical factor,
this has little use in practice, except for multiplying by zero which
erases the Counter.  E.g. 0*c1' ),
  Examples('c1 := Counter(iterations):  c2 := Counter(''Normal numbers''):',
	'to 100 do c1+1;  c2+Rand(Normal) od:',
	Print('print(c1,c2)'), Unassign('c1','c2')
),
  SeeAlso(Stat, LinearRegression, Counter, objectorientation )
):



Covariance_Description := Description(
  structure( Covariance ),
  Summary( 'store and compute covariances and correlations' ),
  CallingSequence( noeval( Covariance() ), 
	noeval( Covariance(Description) ),
	noeval( Covariance(Description,VarNames) )),
  Parameters(
	[ Description, string, 'descriptive name of the set'],
	[ VarNames, list, 'names of the variables' ] ),
  Returns( Covariance ),
  Selectors(
	[Mean,list(numeric),'mean values of the variables'],
	[Variance,list(numeric),'variances of the variables'],
	[Minimum,list(numeric),'minimum values of the variables'],
	[Maximum,list(numeric),'maximum values of the variables'],
	[Number,integer,'number of sample points recorded'],
	[MaxVariance,[numeric,list],'largest eigenvalue/eigenvector'],
	[Eigenvalues,[list,matrix],'eigenvalues/vectors of covariance matrix'],
	[CovMatrix,matrix(numeric),'estimated covariance matrix'],
	[CorrMatrix,matrix(numeric),'estimated correlation matrix'] ),
  Synopsis( 'Covariance is a data structure which stores the values
of vectors of variables, and upon demand selects/computes various
results.
A call to Covariance sets the space to record the information.
Calls to Covariance_update or adding a value to a Covariance
variable records additional results.
At any point selections can be made, resulting in computations.
Further data can be added and further selections can be made.
Each data point should be a numerical vector of dimension m.
The CovMatrix selector returns an unbiased estimator of the
covariances of the variables.
The diagonal of this matrix contains the estimates of the
variances of the variables.
The CorrMatrix selector returns an unbiased estimator of the
correlation coefficients of the variables.  Its diagonal is 1.
MaxVariance returns the largest eigenvalue of the covariance
matrix and its corresponding eigenvector.
This vector gives the linear combination of the variables that
will show the largest variance.
The Eigenvalues selector returns a list, [e,v], with the
eigenvalues and the eigenvectors of the covariance matrix.
e is sorted in increasing order ( e[1]<=e[2]<=...<=e[m] )
and v is the array of eigenvectors (each row is an
eigenvector, v is an m x m matrix).
Covariance analysis is useful to find which are the
linear combinations of the data which give the
maximum/minimum variances.
If a is a data point (a vector of dimension m), then a*v[i]
has variance e[i].
If the data has linear dependencies, then some linear
combinations will have 0 variance.
Then the smallest e value will be 0 (or roundoff error from 0).
The number of 0 (or near 0) eigenvalues is the number of
linear dependencies in the data.' ),
  Examples( 'c := Covariance(''test two vars'',[v1,v2]):',
    'c+[0,1]:  c+[0.1,1.1]:  c+[0.2,1.2]:  c+[0,1.3]:',
    Print('print(c)'),
    'c[Eigenvalues]', Unassign('c')
),
  SeeAlso(OutsideBounds, Stat, SvdAnalysis, Eigenvalues, Counter )
):



BaseCount_Description := Description( function(BaseCount),
  Summary( 'Counts the number of DNA bases in a sequence' ),
  CallingSequence( noeval(BaseCount(sequ))),
  Parameters( ['sequ',string,'DNA sequence'] ),
  Returns(list),
  Synopsis('BaseCount counts the number of each base in a DNA
sequence and returns a vector of length 6 with the number of each
kind of base A, C, G, T, U, and X in place numbers 1 through
6 respectively. '),
  Examples('BaseCount(''ACCGGGTTTUUX'')' )
  ):


ProbIndex_Description := Description(
  function( ProbIndex),
  Summary ('Compute the Probability Index'),
  CallingSequence(noeval(ProbIndex(ma)) ),
  Parameters(['ma',array(string),'multiple sequence alignment'],
        ['t',Tree,'a phylogenetic tree']),
  Returns(list(numeric) ),
  Synopsis('Computes a variation index defined as
-log10( Probability{position} ) for all positions of a multiple alignment.'),
  Examples(   'ma := [ ''    -------------------------FPEVVGKTVDQAREYFTLHYPQ           '',
''    -------------------IASAGFVRDAQGNCIK---                    '',
''AKQVVLLIFGSWQLARERLANEMRKAVAY__TFL__NFDMGRQPLSMHYSDKVCSPRMSTET'',
''AEPIVPLLFGMWRLKRKKANNKLLRCVKY__TLLARNTSDGREPVACRYSEKICSPRTGTKT'',
''AEVIVPLLFGVWRLKREERTYTLLQCVKY__VFLARNTVAGNRPLSKKFSEKVCSPRK    '',
''AEPIVPLLFGLWQLAREKASNTLLQCVKY__VFLARNTVAGRRPLKMKYSDKVCSPRKGAKT'',
'' EPIVPLL__MWQLAIEKSSNTLLQCVK__KVFLARKTVAGRRPLSMKFSDKVCNPRKGTKT'',
''  PIVPLLFGMWQLAREKASNTLLQCVKYYYVFLARNTVAGRRPLSMKYSDKVCSPRKGTKT'']',
'tree := Tree(Tree(Leaf(b,-250.0000,2),-2.8422e-14,Leaf(a,-250,1)),0,
Tree(Leaf(h, -250.0000,8),-209.7583,Tree(Leaf(g,-260.8121,7),-227.6537,Tree(Leaf(f,-256.9830,6)
,-233.8701,Tree(Leaf(d,-240.9182,4),-235.7326,Tree(Leaf(e,-252.2867,5),
-237.4908,Leaf(c,-239.0000,3)))))))',
'prxd := ProbIndex (ma, tree)',
 Hide( 'ma := noeval(ma); tree := noeval(tree); prxd := noeval(prxd);' )
),
  SeeAlso( ScaleIndex, KWIndex, PrintIndex, PlotIndex )
):

ScaleIndex_Description := Description(
  function( ScaleIndex ),
  Summary ('Compute the Scale Variation Index'),
  CallingSequence(noeval(ScaleIndex(ma)) ),
  Parameters(['ma',array(string),'multiple sequence alignment'],
        ['t',Tree,'a phylogenetic tree']),
  Returns(list(numeric) ),
  Synopsis('Computes a variation index defined as the scale
factor for pam distances that makes Probability{position} maximal
for all positions of a multiple alignment.' ),
  Examples(   'ma := [ ''    -------------------------FPEVVGKTVDQAREYFTLHYPQ           '',
''    -------------------IASAGFVRDAQGNCIK---                    '',
''AKQVVLLIFGSWQLARERLANEMRKAVAY__TFL__NFDMGRQPLSMHYSDKVCSPRMSTET'',
''AEPIVPLLFGMWRLKRKKANNKLLRCVKY__TLLARNTSDGREPVACRYSEKICSPRTGTKT'',
''AEVIVPLLFGVWRLKREERTYTLLQCVKY__VFLARNTVAGNRPLSKKFSEKVCSPRK    '',
''AEPIVPLLFGLWQLAREKASNTLLQCVKY__VFLARNTVAGRRPLKMKYSDKVCSPRKGAKT'',
'' EPIVPLL__MWQLAIEKSSNTLLQCVK__KVFLARKTVAGRRPLSMKFSDKVCNPRKGTKT'',
''  PIVPLLFGMWQLAREKASNTLLQCVKYYYVFLARNTVAGRRPLSMKYSDKVCSPRKGTKT'']',
'tree := Tree(Tree(Leaf(b,-250.0000,2),-2.8422e-14,Leaf(a,-250,1)),0,Tree(Leaf(h,
-250.0000,8),-209.7583,Tree(Leaf(g,-260.8121,7),-227.6537,Tree(Leaf(f,-256.9830,
6),-233.8701,Tree(Leaf(d,-240.9182,4),-235.7326,Tree(Leaf(e,-252.2867,5),
-237.4908,Leaf(c,-239.0000,3)))))))',
'scxd := ScaleIndex (ma, tree)',
 Hide( 'ma := noeval(ma); tree := noeval(tree); scxd := noeval(prxd);' )
),
  SeeAlso( KWIndex, ProbIndex, PrintIndex, PlotIndex )
):

KWIndex_Description := Description(
  function( KWIndex),
  Summary ('Compute the Kabat-Wu Variation Index'),
  CallingSequence(noeval(KWIndex(ma)) ),
  Parameters(['ma',array(string),'multiple sequence alignment']),
  Returns(list(numeric) ),
  Synopsis( 'Computes the Kabat-Wu variation index for all positions
of a multiple alignment.' ),
  References( 'T.T. Wu, E.A. Kabat: An analysis of the
sequences of the variable regions of Bence Jones proteins and
myeloma light chains and their implications for antibody
complementarity.  J. Exp. Med. 132(1970): 211-250.' ),
  Examples( 'ma := [
''    -------------------------FPE'',
''    -------------------IASAGFVRD'',
''AKQVVLLIFGSWQLARERLANEMRKAVAY__T'',
''AEPIVPLLFGMWRLKRKKANNKLLRCVKY__T'',
''AEVIVPLLFGVWRLKREERTYTLLQCVKY__V'',
''AEPIVPLLFGLWQLAREKASNTLLQCVKY__V'',
'' EPIVPLL__MWQLAIEKSSNTLLQCVK__KV'',
''  PIVPLLFGMWQLAREKASNTLLQCVKYYYV'']',
'kwxd := KWIndex (ma)',
 Hide( 'ma := noeval(ma); kwxd := noeval(prxd);')
),
  SeeAlso( ScaleIndex, ProbIndex, PrintIndex, PlotIndex )
):

Plot2Gif_Description := Description( function( Plot2Gif),
  Summary ('convert a plot output to a gif file'),
  CallingSequence(noeval(Plot2Gif(opt)) ),
  Parameters(
      [opt,'''landscape''','(optional) produce the gif in landscape format'],
      [opt,'''portrait''','(optional) produce the gif in portrait format'],
      [opt,output=string,'(optional) file name to place the result']
),
  Returns(NULL ),
  Synopsis('Uses underlying unix/linux commands to convert
the output of a Draw/Plot command to a xxx.gif file.
The commands used are pstopnm and ppmtogif and may not exist
in all versions of the operating systems.' ),
  Examples( Fake( 'Plot2Gif( landscape, output=''figure1.gif'' )', '') ),
  SeeAlso_Plot
):


PlotIndex_Description := Description(
  function( PlotIndex),
  Summary ('Plot a Variation Index'),
  CallingSequence(noeval(PlotIndex(ma)) ),
  Parameters(['ma',array(string),'multiple sequence alignment'],
        ['index',array(numeric),'a variation index']),
  Returns(NULL ),
  Synopsis('Plots a histogram from the variation index.' ),
  SeeAlso( KWIndex, ScaleIndex, ProbIndex, PrintIndex, PlotIndex )
):


Primes_Description := Description(
  iterator( Primes ),
  Summary('generates the prime numbers'),
  CallingSequence( 'for n in Primes() do ... od;' ),
  Returns(posint),
  Synopsis('This is an iterator which returns all the
prime numbers in increasing order.' ),
  SeeAlso( iterator, objectorientation, iterate )
):


PrintIndex_Description := Description(
  function( PrintIndex),
  Summary ('Prints a Variation Index'),
  CallingSequence(noeval(PrintIndex(ma,index)) ),
  Parameters(['ma',array(string),'multiple sequence alignment'],
        ['index',array(numeric),'a variation index']),
  Returns(NULL ),
  Synopsis('Prints the multiple alignment, followed by the indices,
one position per row.' ),
  Examples( 'ma := [ ''AKQVVLLIFGSW'', ''AEPIVPLLFGMW'', ''AEVIVPLLFGVW'',
  ''AEPIVPLLFGLW'', '' EPIVPLL__MW'', ''  PIVPLLFGMW'']:',
'tree := Tree(Tree(Leaf(3,-50.3881,c),-31.1550,Tree(Tree(
  Leaf(2,-52.2087,b),-50.4844,Tree(Leaf(6,-71.9795,f),-53.3023,
  Leaf(5,-92.0774,e))),-41.0671,Leaf(4,-48.3231,d))),0,Leaf(1,-62.9954,a)):',
'prxd := ProbIndex (ma, tree)',
    Print( 'PrintIndex(ma,prxd)' ),
    Unassign('ma','tree','prxd') ),
  SeeAlso( KWIndex, ScaleIndex, ProbIndex, PrintIndex, PlotIndex )
):

latex_Description := Description(
  function( latex ),
  Summary( 'convert a document or part of it to latex' ),
  CallingSequence( noeval( noeval(latex)(a,titl,auth) ),
	noeval(LaTeX(a,titl,auth)), noeval(LaTeXC(a))),
  Parameters( ['a', {structure, string}, 'object to convert to latex'],
	[titl,string,'(optional) title of the document'],
	[auth,string,'(optional) author(s) of the document']),
  Returns( string ),
  Synopsis( 'The latex function converts an object, typically a
Document or a part thereof, to latex.  LaTeX is a synonym of latex,
much more difficult to type but according to Leslie Lamport.
LaTeXC is used for a component, that is no headers/trailers will
be produced.' ),
  Examples( 't := Table( center, border, Row(''abc'',''cde'')):',
  Print('prints(LaTeXC(t))'),
  'd := Document(''Species evolve, that''''s it.''):',
  Print( 'prints(latex(d,''The origin of species'',''Charles Darwin''))' ),
  Unassign('t','d') ),
  SeeAlsoDocument
):


TPIDistr_Description := Description(
  function( TPIDistr ),
  Summary( 'distribution of number of changes in a sequence' ),
  CallingSequence( noeval( TPIDistr(a1,a2,a3,a4) )),
  Parameters( ['a_i', posint, 'number of symbols of the ith type']),
  Returns( list(numeric) ),
  Synopsis( 'The arguments (any number from 1 to 4) are taken to
be the number of symbols of each type.  a1 is the number of symbols
of type 1, a2 the number of symbols of type 2, etc.
TPIDistr computes the probability distribution of the number of
transitions in a random sequence with a1, a2, ... symbols of each
type.
This has a special application in computing the TPI index (tRNA
Pairing Index) which measures how autocorrelated are the tRNAs
that translate a given amino acid, independently of the
frequencies of the tRNAs and codons.' ),
Paragraph( -2, 'The distribution is returned in a list, and the
first entry corresponds to 0 changes, the second to 1 change, etc.
The number of changes can never exceed a1+a2+...-1, so the list
returned is of length a1+a2+...' ),
Paragraph( -2, 'For example, there are 3 ways of permuting 2 A''s
and one B.  AAB, ABA and BAA.  Two sequences have one transition
and one sequence has two transitions.  so the result in this
case should be [0,2/3,1/3].' ),
  Examples( 'TPIDistr(1,2)', 'TPIDistr(1,2,3,4)' ),
  SeeAlso( ComputeTPI, TPIDistr, SetuptRNA )
):



ComputeTPI_Description := Description(
  function( ComputeTPI ),
  Summary( 'TPI index of a DNA sequence' ),
  CallingSequence( noeval( ComputeTPI(e,mode) )),
  Parameters( [e, string, 'an Entry which contains a DNA sequence'],
	[mode,string,'(optional), the string AllAA']),
  Returns( list({numeric,list}) ),
  Synopsis( 'The TPI index measures how much correlation there
exists among the consecutive tRNAs coding for each amino acid.
This autocorrelation is measured in a way that it is insensitive
to different frequencies of amino acids, different frequencies
of tRNAs and different frequencies of bases.
Two indices are computed, which are two representations of the
same magnitude.
In both cases, the TPI measures the cumulative distribution of the
number of pairs of consecutive tRNAs coding for the same amino
acids.
If the actual number of pairs it too low, this means that the
tRNAs are "rotated" around quite often.
If the number of pairs is high, this means that the tRNAs are
"reused" often.
The first value returned is a normal deviate with the same cumulative
probability of having the observed number of pairs.
A negative value means less correlation than expected, a positive
value higher correlation than expected.
Since it is a normal deviate, N(0,1), it is easy to estimate
how rare the values are.
E.g. 1.96 means that it is higher only 2.5% of the time, etc.
The second value is the cumulative probability of having the
observed number of pairs spread over the interval -1 .. 1.' ),
Paragraph( -2, 'The function cannot compute the TPI unless the
tRNA information is given.
This is normally done with the function SetuptRNA.' ),
Paragraph( -2, 'If a second argument, AllAA, is given, then both
indices are computed for all the individual amino acids as well
as for the ensemble.
In this case, a list of lists is returned, where each component
is a list with the two values and the name of the amino acid.' ),
  SeeAlso( ComputeTPI, TPIDistr, SetuptRNA )
):



tRNA_names := []:
for z in names(list(list)) do if length(z) > 5 and z[-5..-1]='_tRNA' then
    tRNA_names := append( tRNA_names, z[1..-6] ) fi od:
tRNA_names := sort( tRNA_names, lowercase ):
SetuptRNA_Description := Description(
  function( SetuptRNA ),
  Summary( 'set up functions for tRNA translations' ),
  CallingSequence( noeval( SetuptRNA(d) )),
  Parameters(
	[d,list(list),'a list (by aa) of list of codons or'],
	[d,string,'the name of a known table of tRNA'] ),
  Returns( 'NULL' ),
  Synopsis( 'This function sets up all the necessary functions
to translate tRNAs.
These are from tInt to A, AAA, Amino, Int, CInt and Codon
and from Int and CInt to tRNA and tInt.
Its input is either a string (which means a predefined name)
or it is a list of 20 (one per amino acid) lists of tRNAs.
The format is best given by an example, see the file
lib/SetuptRNA.
Execution of SetuptRNA causes the following functions and
values to be defined:' ),
Table( center, ColAlign('l','l'),
  Row( 'Name', 'Description' ), Rule,
  Row( 'ntRNA', 'integer, the number of tRNA molecules used' ),
  Rule,
  Row( 'tIntToInt', 'tInt (1..ntRNA) to Int (aa number, 1..20)' ),
  Row( 'tIntToA', 'tInt (1..ntRNA) to A (aa one-letter code)' ),
  Row( 'tIntToAAA', 'tInt (1..ntRNA) to AAA (aa 3-letter code)' ),
  Row( 'tIntToAmino', 'tInt (1..ntRNA) to Amino (aa full name)' ),
  Rule,
  Row( 'tIntToCInt', 'tInt (1..ntRNA) to set of CInt (codon number, 1..64)' ),
  Row( 'tIntToCodon', 'tInt (1..ntRNA) to set of Codon (3-letter codon)' ),
  Rule,
  Row( 'tIntTotRNA', 'tInt (1..ntRNA) to tRNA (tRNA name)' ),
  Row( 'tRNATotInt', 'tRNA (tRNA name) to tInt (1..ntRNA)' ),
  Rule,
  Row( 'IntTotInt', 'Int (aa number, 1..20) to set of tInt (1..ntRNA)' ),
  Row( 'IntTotRNA', 'Int (aa number, 1..20) to set of tRNA (tRNA name)' ),
  Rule,
  Row( 'CIntTotInt', 'CInt (codon number, 1..64) to tInt (1..ntRNA)' ),
  Row( 'CIntTotRNA', 'CInt (codon number, 1..64) to tRNA (tRNA name)' ) ),
Paragraph( -2, 'Currently the following names are recognized as
arguments for SetuptRNA: ' . string(tRNA_names) ),
  Examples( 'SetuptRNA(yeast)' ),
  SeeAlso( ComputeTPI, TPIDistr, SetuptRNA )
):


#################################################
# Descriptions for all the codon functions.     #
#                        Adrian Schneider, 2004 #
#################################################

# --------------  CodonMatrix  --------------------------------

CodonPamToPam_Description:= Description(
  function(CodonPamToPam),
  Summary('Convert CodonPAM to PAM.'),
  CallingSequence( noeval(CodonPamToPam(lnM1,CF,CodonPam))),
  Parameters(
  	[lnM1,matrix(numeric,64),'Logarithm of a 1-PAM codon mutation matrix.'],
  	['CF',array(numeric,64),'Codon frequencies'],
  	[CodonPam,numeric,'CodonPAM to be converted']),
  Returns(numeric),
  Synopsis('Converts CodonPAM to PAM.
This conversion depends on the amount of synonymous mutations for a
species or set of species, so the logarithm of the 1-CodonPAM matrix
and the codon frequencies are required as arguments.
The conversion is done by summing up the percentage of synonymous
mutations in the codon matrix.
This sum is the expected percentage of identical amino acids at this
CodonPAM distance, which then can be converted to PAM using the
PerIdentToPam function.'),
  Examples(
  	Fake('CodonPamToPam(CodonLogPAM1,CF,50)','23.3413' )),
  SeeAlso( PamToCodonPam, CreateCodonMatrices, PerIdentToPam)
):


PamToCodonPam_Description:= Description(
  function(PamToCodonPam),
  Summary('Convert PAM to CodonPAM.'),
  CallingSequence( noeval(PamToCodonPam(lnM1,CF,Pam))),
  Parameters(
  	[lnM1,matrix(numeric,64),'Logarithm of a 1-PAM codon mutation matrix.'],
  	['CF',array(numeric,64),'Codon frequencies'],
  	[Pam,numeric,'PAM distance to be converted']),
  Returns(numeric),
  Synopsis('Converts PAM to CodonPAM.
This conversion depends on the amount of synonymous mutations for a
species or set of species, so the logarithm of the 1-CodonPAM matrix
and the codon frequencies are required as arguments.
The conversion is done by inverting the CodonPamtoPam function
using a Brent''s search.'),
  Examples(
  	Fake('PamToCodonPam(CodonLogPAM1,CF,50)','109.2499' )),
  SeeAlso( CodonPamToPam, CreateCodonMatrices)
):

CreateSynMatrices_Description:= Description(
  function(CreateSynMatrices),
  Summary('Creates a global list of SynPAM matrices.'),
  CallingSequence( noeval( CreateSynMatrices() ),
  		   noeval( CreateSynMatrices(setname) ) ),
  Parameters(
  	[setname,string,'name of predefined set.']),
  Returns(NULL),
  Synopsis('When called with a set name, the precomputed count
matrices are loaded and used to create the global scoring matrices.
As default, the count matrix form the OMA project is used.
The function then sets all non-synonymous mutation counts to zero
and uses this matrix to create the global list SynMS with 1000
scoring matrices of various SynPAM distances.'),
  Examples(
  	Fake('CreateSynMatrices()','' ),Fake('CreateSynMatrices(mus)','' )),
  SeeAlso(CodonMatrix, CreateCodonMatrices, CreateDayMatrices, EstimateSynPAM, CodonDynProgStrings)
):

CreateCodonMatrices_Description:= Description(
  function(CreateCodonMatrices),
  Summary('creates a global list of codon mutation matrices.'),
  CallingSequence( noeval( CreateCodonMatrices() ),
  		   noeval( CreateCodonMatrices(setname) ),
  		   noeval( CreateCodonMatrices(counts) ),
		   noeval( CreateCodonMatrices(rates,freqs) ) ),
  Parameters(
  	[setname,string,'Name of the desired set of species.'],
  	[count,matrix(numeric),'Matrix with codon mutation counts.'],
	[rates,matrix(numeric),'a rate matrix Q'],
	[freqs,array(nonnegative),'codon frequencies']),
  Returns(NULL),
  Synopsis('When called with a set name, the precomputed logarithm
of the respective mutation matrices are loaded and used to create
the global scoring matrices.
When called with no argument, the matrices are cretaed from
the data form the OMA project. Alternatively, ''mt'' can be used as setname
to construct matrices for mitochondiral coding DNA.
When a count matrix is given, the mutation matrices are derived
from this matrix. When a rate matrix and the natural frequencies are given,
then those are used to create the scoring matrices.
The function creates the following global objects:' ),
Paragraph( -10, '    CF - a vector of length 64 containing the codon frequencies,' ),
Paragraph( -10, '    CodonLogPAM1 - the logarithm of a 1-CodonPAM mutation matrix,' ),
Paragraph( -10, '    CM - the 250-CodonPAM similarity matrix and' ),
Paragraph( -10, '    CMS - a list of 1266 similarity matrices.' ),
  Examples(
  	Fake('CreateCodonMatrices()','' ), Fake('CreateCodonMatrices(hum)','' )),
  SeeAlso(CreateSynMatrices, CreateDayMatrices, CodonAlign, CodonDynProgStrings, EstimateCodonPAM)
):

CodonMatrix_Description := Description(
  structure( CodonMatrix ),
  Summary( 'a codon mutation matrix' ),
  CallingSequence( 'CodonMatrix()',
   		   'CodonMatrix(Sim, Desc, CodonPam)',
		   'CodonMatrix(Sim, Desc, CodonPam, AAPAM)',
		   'CodonMatrix(Sim, Desc, CodonPam, AAPAM, FixedDel, IncDel)'),
  Parameters( [Sim,matrix(numeric,64),'64 x 64 codon similarity matrix'],
             [Desc,string,'a description'],
  	     [CodonPam,numeric,'CodonPam number of the matrix'],
  	     [AAPam,numeric,'the equivalent PAM distance'],
  	     [FixedDel,numeric,'the constant part of the deletion costs'],
	     [IncDel,numeric,'the length-dependent part of the deletion costs'],
	     [PamDistance,numeric,'synonym of CodonPam'],
	     [PamNumber,numeric,'synonym of CodonPam'],
	     [MaxSim,numeric,'the highest similarity score in the matrix'],
	     [MinSim,numeric,'the lowest similarity score in the matrix'],
	     [MaxOffDiag,numeric,'the highest similarity score that is not in the diagonal'],
	     [Type,string,'synonym of Desc'],
	     [Description,string,'synonym of Desc']),
  Synopsis( 'A CodonMatrix contains everything that is needed to score
codon alignments.
This is basically the 64x64 scoring matrix plus the deletion cost function.
These costs are based on the PAM distance equivalent and are
calculated automatically if they are not given as an argument.
A CodonMatrix is now only used for storing SynPAM matrices' ),
  SeeAlso( CreateSynMatrices, EstimateSynPAM )
):

# ------------  CodonAlign ----------------------------------------

CodonAlign_Description := Description( function(CodonAlign),
  Summary('align codon sequences using dynamic programming'),
  CallingSequence( noeval(CodonAlign(seq1,seq2,method,cm)) ),
  Parameters(
    [seq1,string,'codon sequence'],
    [seq2,string,'codon sequence'],
    [method,string,'the mode of dynamic programming to use'],
    [cm,{DayMatrix,list(DayMatrix)},'codon matrices used for alignment']),
  Returns(Alignment),
  Synopsis( 'CodonAlign does an alignment of two codon sequences using the
similarity scores given in the DayMatrix (of type ''Codon'') and the given method.
If a single DayMatrix is given, the alignment is done using it.
If a list of DayMatrix is given, it is understood that the best
CodonPAM matrix be used.  Since the introduction of the generic dynamic programming,
CodonAlign is only a wrapper function. It extracts the DNA sequence from an entry
and converts the codon sequence to a character string for the generic Align
function.'),
Examples(
    Fake('CodonAlign(''AAACCCGGG'',''AAGCCGGGG'', CM)',
    	'Alignment(''AVq'',''CWq'',30.2765,DM,0,0)'),
    Fake('CodonAlign(''AAACCCGGG'',''AAGCCGGGG'',CMS)',
    'Alignment(''AVq'',''CWq'',34.3914,DMS[345],79,30984.0898)')),
  SeeAlso( DayMatrix, Align, CreateCodonMatrices, CodonDynProgStrings)
):

# ------------------  CodonScore ---------------------------------------

ScoreAlignment_Description:= Description(
  function(ScoreAlignment),
  Summary('scores an existing codon or protein alignment'),
  CallingSequence( noeval( ScoreAlignment(dps1,dps2,S) ) ),
  Parameters(
  	[dps1,string,'First of the aligned sequences.'],
	[dps2,string,'Second of the aligned sequences.'],
  	[S,{DayMatrix,CodonMatrix},'a scoring matrix']),
  Returns(numeric),
  Synopsis('This functions scores two aligned sequences with a given scoring matrix S. 
  If S is a CodonPAM or SynPAM matrix, the sequences are interpreted as DNA, and if S is a Dayhoff matrix,
  the sequences are assumed to be proteins. The two input strings must be of same length and can include
gaps (''___'' or ''_'') which will be scored according to the gap cost formula as defined in
in the scoring matrix.'),
  Examples(
  	Fake(' ScoreAlignment(AAACCCGGGTTT,AAACCG___TTT,cm)','13.7069' )),
  SeeAlso(CodonMatrix, CreateCodonMatrices, CreateSynMatrices, CodonAlign, Align, DynProgStrings, 
  	CodonDynProgStrings, CreateDayMatrices)
):

EstimateSynPAM_Description:= Description(
  function(EstimateSynPAM),
  Summary('finds the best-scoring SynPAM matrix for an alignment'),
  CallingSequence( noeval( EstimateSynPAM(dps1,dps2) ) ),
  Parameters(
  	[dps1,string,'First of the aligned sequences.'],
	[dps2,string,'Second of the aligned sequences.']),
  Returns('[Score, SynPAM, SynPAMVariance]'),
  Synopsis('Given two codon-wise aligned DNA sequences, this functions finds the 
          best-scoring SynPAM matrix. Anaologous to EstimatePam, it returns a list
          containing the score, the SynPAM estimate and the SynPAM variance.'),
  Examples(
  	Fake('EstimateSynPAM(AAACCCGGGTTT,AAACCG___TTT)','[2.3328, 51.9870, 942.8518]')),
  SeeAlso(CodonMatrix, CreateSynMatrices, CodonDynProgStrings, EstimateCodonPAM, CodonAlign, EstimatePam, 
  EstimateNG86, EstimatePB93)
):

EstimateCodonPAM_Description:= Description(
  function(EstimateCodonPAM),
  Summary('finds the best-scoring CodonPAM matrix for an alignment'),
  CallingSequence( noeval( EstimateCodonPAM(dps1,dps2,cms) ) ),
  Parameters(
        [dps1,string,'First of the aligned sequences.'],
        [dps2,string,'Second of the aligned sequences.'],
	[cms,list(DayMatrix),'array of codon scoring matrices']),
  Returns('[Score, CodonPAM, CodonPAMVariance]'),
  Synopsis('Given two codon-wise aligned DNA sequences, this functions finds the 
  	best-scoring CodonPAM matrix. Anaologous to EstimatePam, it returns a list 
	containing the score, the CodonPAM estimate and the CodonPAM variance.'),
  Examples(
        Fake('EstimateCodonPAM(AAACCCGGGTTT,AAACCG___TTT,CMS)','[11.0814, 91, 1653.3145]')),
  SeeAlso(CreateCodonMatrices, CodonAlign, CodonDynProgStrings, EstimatePam , EstimateSynPAM )
):

CodonDynProgStrings_Description := Description(
  function( CodonDynProgStrings ),
  Summary('compute score and aligned strings from a codon alignment'),
  CallingSequence( noeval(CodonDynProgStrings(al))),
  Parameters(['al',Alignment,'Codon alignment']),
  Returns( [[numeric,string,string],'[score,seq1,seq2]'] ),
  Synopsis('Returns a list with the similarity score, first sequence and
second sequence suitable for printing the aligned DNA sequences (with ''___''
inserted at gap positions).' ),
  Examples( 
	Fake('al := CodonAlign(AAACCCGGGTTT,AAACCTTTT,CMS,Global)',
	     'al := Alignment(''AVq#'',''AX#'',10.7382,DMS[368],102,47328.8945,{Global})'),
	Fake('CodonDynProgStrings(al)',
	     '[10.7382, AAACCCGGGTTT, AAACCT___TTT]')),
  SeeAlso(CodonAlign, CreateCodonMatrices, EstimateCodonPAM)
):

CodonMutate_Description := Description(
  function( CodonMutate ),
  Summary('randomly evolve a codon sequence'),
  CallingSequence( noeval( CodonMutate('seq1',cpam)),
		   noeval( CodonMutate('seq1',cpam,DelType,lnM1))),
   Parameters(['seq1',string,'codon sequence'],
	      [cpam,positive,'CodonPAM distance to mutate'],
	      [DelType,'ExpGaps','(optional) gap type'],
	      [lnM1,matrix(numeric),'(optional) log. of a 1-PAM matrix']),
  Returns(string),
  Synopsis('Mutates a sequence of codons over a certain CodonPAM distance.
  Stop codons always mutate to stop codons while sense codon always mutate to sense 
  codons. When a gap type is given, the function returns not only the mutated string, 
  but also the two aligned sequences, where the exact position of the gaps can be
  seen. lnM1 is by default assumed to be CodonLogPAM1 which must be created with
  CreateDayMatrices() first.'),
  Examples( Fake('CodonMutate(CCCATCAACACTGAC,50)',
		'CCTATCGCCACCGAC')),
  SeeAlso(CreateRandSeq,CreateCodonMatrices,Mutate)
):



BootstrapTree_Description := Description(
  function( BootstrapTree ),
  Summary('assign confidence values to internal nodes or branches'),
  CallingSequence( noeval(BootstrapTree(Ds,labels,bstype)),
		   noeval(BootstrapTree(Ds,labels,nrounds,bstype)),
		   noeval(BootstrapTree(treeofall,bstrees,bstype))),
  Parameters(['Ds',array(matrix),'Distance matrices'],
             ['labels',array(anything),'Labels'],
             ['nrounds',posint,'(optional) number of rounds'],
             ['treeofall',Tree,'tree of all data'],
             ['bstrees',array(Tree),'trees from bootstrapping'],
	     ['bstype',{'Branches','Nodes'},'(optional) type']),
  Returns(Tree),
 Synopsis('Depending on the value of ''bstype'', this function computes
confidence values for internal nodes (default) or branches. 
The values are integers between 0 and 100, denoting how often (in percent)
a particular node or branch occured during the bootstrapping.
By default, 100 bootstrapping trees from randomly selected distance matrices
(prob 2/3) are constructed and evaluated.
Typically, each of the input matrices corresponds
to one orthologous group. Alternatively, a tree from all data plus a list of
trees from bootstrapping experiments could be given as arguments. 
The confidence values are stored in the fourth field of the Tree data structure
and can be displayed using the option InternalNodes = ShowBootstrap 
or BranchDrawing = ShowBootstrap for the DrawTree function. To make the result
more readable, only bootstrap values below 100 percent are displayed.'),
Examples( 'T1 := Tree(Tree(Tree(Leaf(''A'',-3),-2,Leaf(''B'',-3) ),-1,Leaf(''C'',-3)),0,
            Tree(Tree(Leaf(''E'',-3),-2,Leaf(''F'',-3) ),-1,Leaf(''D'',-3))):',
	'T2 := Tree(Tree(Tree(Leaf(''B'',-3),-2,Leaf(''C'',-3) ),-1,Leaf(''A'',-3)),0,
            Tree(Tree(Leaf(''D'',-3),-2,Leaf(''E'',-3) ),-1,Leaf(''F'',-3))):',
	'BS1 := BootstrapTree(T1, [T1,T2])',
	'DrawTree(BS1, InternalNodes=ShowBootstrap)',
	'BS2 := BootstrapTree(T1, [T1,T2], Branches)',
	'DrawTree(BS2, BranchDrawing=ShowBootstrap)', Unassign('T1','T2','BS1','BS2')),
SeeAlso(Tree, DrawTree, PhylogeneticTree, LeastSquaresTree,
ComputeDimensionlessFit, RBFS_Tree )
):

SeeAlso_Ontology := SeeAlso( GOdownload, GOname, GOnumber, GOdefinition, GOsuperclass,
GOsuperclassR, GOsubclass, GOsubclassR, GOsuperclassR):

Params_Ontology := Parameters([
    'go',{string,posint},'GO number'] ):

Synopsis_Ontology := () -> 'The argument can either be a number or a string of the 
form ''GO:00'.Rand(1000..9999).'''.':

GOdownload_Description  := Description(
  function(GOdownload),
  Summary('downloads the gene ontologies and converts them to a Darwin readable format'),
  CallingSequence( noeval(GOdownload) ),
  Returns(NULL),
 Synopsis('Downloads the gene ontologies from http://www.geneontology.org/ontology/gene_ontology.obo and converts them to Darwin tables that are stored in the file GOdata.drw which is located in Darwin'' data directory.'),
SeeAlso_Ontology
):

GOname_Description  := Description(
  function(GOname),
  Summary('returns the name of a Gene Ontology'),
  CallingSequence( noeval(GOname(go)) ),
  Params_Ontology,
  Returns(string),
  Synopsis('Returns the name for a GO number. '.Synopsis_Ontology()),
  Examples(Fake( 'GOname(23)','maltose metabolic process' )),
  SeeAlso_Ontology
):

GOdefinition_Description  := Description(
  function(GOdefinition),
  Summary('returns the definition of a Gene Ontology'),
  CallingSequence( noeval(GOdefinition(go)) ),
  Params_Ontology,
  Returns(string),
  Synopsis('Returns a longer definition describing a GO number. '.Synopsis_Ontology()),
  Examples(
  Fake( 'GOdefinition(23)','The chemical reactions and pathways involving the disaccharide maltose (4-O-alpha-D-glucopyranosyl-D-glucopyranose), an intermediate in the catabolism of glycogen and starch' )),
  SeeAlso_Ontology
):

GOnumber_Description  := Description(
  function(GOname),
  Summary('returns the GO number of a Gene Ontology term'),
  CallingSequence( noeval(GOnumber(go)) ),
  Parameters([
    'desc',string,'GO name'] ),
  Returns(integer),
  Synopsis('Returns the GO number corresponding to a GO name. This function is
  the inverse of GOname().'),
  Examples(
  Fake( 'GOnumber(''metabolic process'')','8152' )),
  SeeAlso_Ontology
):

GOsuperclass_Description  := Description(
  function(GOsuperclass),
  Summary('returns all superclasses for a Gene Ontology'),
  CallingSequence( noeval(GOsuperclass(go)), noeval(GOsuperclass(go,'links'={'is_a'})) ),
  Parameters(
    ['go',{string,posint},'GO number'],
    ['links',set(string),'types of links to follow (is_a and/or part_of)']),
  Returns(list(integer)),
  Synopsis('Returns all superclasses for a Gene Ontology. This represents in 
  the default case both the ''is_a'' and ''part_of'' relationship. '
  .Synopsis_Ontology().' The optional named argument ''links'' can be used to
  restrict the type of relationships to one of them.'),
  Examples(Fake( 'GOname(1)', 'mitochondrion inheritance'),
  Fake( 'GOsuperclass(1)', '[48308, 48311]' ),
  Fake('for t in GOsuperclass(1) do print(GOname(t)) od','organelle inheritance\nmitochondrion distribution')),
  SeeAlso_Ontology
):

GOsubclass_Description  := Description(
  function(GOsubclass),
  Summary('returns all subclasses for a Gene Ontology'),
  CallingSequence( noeval(GOsubclass(go)), noeval(GOsubclass(go,'links'={'can_be','has_parts'}))),
  Parameters(
    ['go',{string,posint},'GO number'],
    ['links',set(string),'types of links to follow (can_be and/or has_parts)']),
  Returns(list(integer)),
  Synopsis('Returns all subclasses for a Gene Ontology. This is the inverse of
  the ''is_a'' and ''part_of'' relationship. '.Synopsis_Ontology().' The 
  optional named argument ''links'' can be used to restrict the type of 
  relationships using ''can_be'' or ''has_parts''.'),
  Examples(
  Fake('GOname(48311)','mitochondrion distribution'),
  Fake('GOsubclass(48311)','[1, 48312]'),
  Fake('for t in GOsubclass(48311) do print(GOname(t)) od','mitochondrion inheritance\nintracellular distribution of mitochondria' )),
  SeeAlso_Ontology
):

GOsuperclassR_Description  := Description(
  function(GOsuperclassR),
  Summary('recursive calls to GOsuperclass'),
  CallingSequence( noeval(GOsuperclassR(go)), noeval(GOsuperclassR(go,'links'={'is_a'})) ),
  Parameters(
    ['go',{string,posint},'GO number'],
    ['links',set(string),'types of links to follow (is_a and/or part_of']),
  Returns(list(integer)),
  Synopsis('Recursively calls GOsuperclass to find all superclasses for a 
   	Gene Ontology. '.Synopsis_Ontology()),
  Examples(
  Fake( 'GOname(1)','mitochondrion inheritance'),
  Fake( 'GOsuperclassR(1)','[6996, 7005, 8150, 9987, 16043, 48308, 48311, 51179, 51640, 51641, 51646]'),
  Fake( 'for t in GOsuperclassR(1) do print(GOname(t)) od','organelle organization\n
  mitochondrion organization\n
  biological_process\n
  cellular process\n
  cellular component organization\n
  organelle inheritance\n
  mitochondrion distribution\n
  localization\n
  organelle localization\n
  cellular localization\n
  mitochondrion localization')),
  SeeAlso_Ontology
):

GOsubclassR_Description  := Description(
  function(GOsubclassR),
  Summary('recursive calls to GOsubclass'),
  CallingSequence( noeval(GOsubclassR(go)),noeval(GOsubclassR(go,'links'={'can_be'}))),
  Parameters(
    ['go',{string,posint},'GO number'],
    ['links',set(string),'types of links to follow (can_be and/or has_parts)']),
  Returns(list(integer)),
  Synopsis('Recursively calls GOsubclass to find all subclasses for a
        Gene Ontology. '.Synopsis_Ontology()),
  Examples(
  Fake( 'GOname(7005)','mitochondrion organization'),
  Fake( 'GOsubclassR(7005)','[1, 2, 266, 1836, 1844, 6264, 6390, 6391, 6392, 6393, 6626, 6627, 7006, 7007, 7008, 7287, 8053, 8637, 30150, 30382, 32042, 32043, 32543, 32976, 32979, 32981, 33108, 33615, 33617, 33955, 34551, 34553, 42407, 42792, 43504, 43653, 45039, 45040, 45041, 45042, 45043, 45044, 46902, 48311, 48312, 51204, 70096, 70124, 70125, 70126, 70127, 70143, 70144, 70145, 70146, 70147, 70148, 70149, 70150, 70151, 70152, 70153, 70154, 70155, 70156, 70157, 70158, 70159, 70183, 70184, 70185, 70584]')),
  SeeAlso_Ontology
):

RotateTree_Description := Description(
  function(RotateTree),
  Summary('Returns a new, rotated tree'),
  CallingSequence( noeval(RotateTree(tree,side,sub_side))),
  Parameters( ['tree', Tree, 'a tree to be rotated'],
    ['side',{'Left','Right'},'the first indication about side'],
    ['sub_side',{'Left','Right'},'the second indication about side']),
  Returns(Tree),
  Synopsis('Returns a new, rotated tree rooted half-way through the edge
    that is indicated by the side and sub-side arguments. The leaves of
    the tree should have annotated heights, but this is not strictly
    enforced, unless the rotation is happening directly next to a leaf.'),
  Examples(
    't := Tree(Tree(Leaf(A,15),5,Leaf(B,15)),0,Tree(Leaf(C,15),11,Leaf(D,15)))',
    'newt := RotateTree(t,Left,Left)', Hide('t := noeval(t)'), 
    Hide('newt := noeval(t)') ),
  SeeAlso(Tree,AllRootedTrees,AllTernaryRoots)
):

AllRootedTrees_Description := Description(
  function(AllRootedTrees),
  Summary('Returns all root variants from a tree'),
  CallingSequence( noeval(AllRootedTrees(tree))),
  Parameters( ['tree', Tree, 'the tree structure with arbitrary root position']),
  Returns(set(Tree)),
  Synopsis('Returns all root variants from a tree, including the input tree 
    itself.'),
  Examples(
    't := Tree(Tree(Leaf(A,15),5,Leaf(B,15)),0,Tree(Leaf(C,15),11,Leaf(D,15)))',
    'sAllRootVariants := AllRootedTrees(t)', Hide('t := noeval(t)'),
    Hide('sAllRootVariants := noeval(sAllRootVariants)') ),
  SeeAlso(Tree,RotateTree,AllTernaryRoots)
):

AllTernaryRoots_Description := Description(
  function(AllTernaryRoots),
  Summary('returns a set of all trees with ternary roots'),
  CallingSequence( noeval(AllTernaryRoots('tree'))),
  Parameters( ['tree', Tree, 'the tree structure with arbitrary root position']),
  Returns(set(Tree)),
  Synopsis('Returns all posssible trees with ternary roots. For each internal
  node of the tree (except the original root), a tree is returned where the
  root is at distance 0 above the internal node. For all practical purposes
  (e.g. reconstruction of ancestral sequences), this has the same effect as 
  having a ternary root (which is not possible with the Tree data structure).'),
  Examples(
    't := Tree(Tree(Leaf(A,15),5,Leaf(B,15)),0,Tree(Leaf(C,15),11,Leaf(D,15)))',
    'AllTernaryRoots(t)' ),
  SeeAlso(Tree,RotateTree,AllRootedTrees,PASfromTree)
):

SearchAllString_Description := Description(
  function(SearchAllString),
  Summary('Find several instances of phrase in a text'),
  CallingSequence( noeval(SearchAllString(pat,txt))),
  Parameters(['pat', string, 'a pattern that is sought'],
             ['txt', string, 'a text which is searched']),
  Returns(list),
  Synopsis('The function SearchAllArray returns the array of indices of an
  all the occurrences of the pattern in the text. If pattern can not be found 
  it returns an empty list. This function is case insensitive.'),
  Examples(
    'SearchAllString(''hehe'', ''hehehe'')',
    'SearchAllString(''cat'', ''acgcagcatgcatcagtca'')'),
  SeeAlso_SearchString
);

HammingSearchAllString_Description := Description(
  function(HammingSearchAllString),
  Summary('Find several approx instances of phrase in a text'),
  CallingSequence( noeval(HammingSearchAllString(pat,txt))),
  Parameters(['pat', string, 'a pattern that is sought'],
             ['txt', string, 'a text which is searched'],
             ['dist', integer, 'an (opt.) hamming dist']),
  Returns(list),
  Synopsis('The function HammingSearchAllArray returns the array of indices
  of an all the occurrences of the pattern in the text with in a hamming
  distance (default 1). If pattern can not be found it returns an empty
  list. This function is case insensitive.'),
  Examples(
     'HammingSearchAllString(''cat'', ''acgcatcatgcatcagtca'')'),
  SeeAlso_SearchString
);

CodonCount_Description := Description(
  function(CodonCount),
  Summary('Count the number codons'),
  CallingSequence( noeval(CodonCount()), noeval(CodonCount(dna))),
  Parameters(['dna', string, 'a string of coding DNA']),
  Returns(list),
  Synopsis('The function CodonCount count all codons in the loaded database
  (if no arguments) or counts the codons in DNA sequence coding for a protein
  (given as an argument). The function returns a list of codon occurrences.'),
  SeeAlso(CodonUsage)
);

CodonUsage_Description := Description(
  function(CodonUsage),
  Summary('Get Codon Usage for a particular amino acid'),
  CallingSequence( noeval(CodonUsage()), noeval(CodonUsage(dna))),
  Parameters(['dna',string,'coding DNA']),
  Returns(list),
  Synopsis('Get the codon usage for sequence of coding DNA. If no argument is
  give the function gets the codon usage for all entries in the loaded 
  database.'),
  Examples('CodonUsage();'),
  SeeAlso(CodonCount, RSCU)
);

Translate_Description := Description(
  function(Translate),
  Summary('DNA to Protein'),
  CallingSequence( noeval(Translate(dna))),
  Parameters(['dna', string, 'sequence to be translated']),
  Returns(string),
  Synopsis('Translate a DNA sequence into a protein sequence.'),
  Examples(
    'Translate(''ATGAAATTTTAA'')'),
  SeeAlso(BackTranslate, Transcribe)
);

BackTranslate_Description := Description(
  function(BackTranslate),
  Summary('Protein to DNA'),
  CallingSequence( noeval(BackTranslate(prot, method, k, db))),
  Parameters(['prot', string, 'protein sequence'],
             ['method', {string,set(string)}, 'the mode of codon selection'],
             ['k', integer, 'window size'],
             ['db', database, '(opt) database to be used']),
  Returns(string),
  Synopsis('Back Translate a protein into DNA. 
  The following methods can be used:
   
   Random  - Select codons randomly
   Freq    - Select the most frequent codons
   Least   - Select the least frequent codons/motifs
   Reuse   - Choose codons favoring tRNA reuse
   DynProg - Select codons based on favored motifs in in coding DNA (default)

  Combination of methods can be used as a set. Some methods require a database 
  to be loaded. For methods based on codon frequency, DB must contain the DNA 
  tag and for the DynProg the SEQ tag of DB must be DNA.'),
  Examples(
    FakeReadDb,
    Fake('BackTranslate(''MAAAT'')',''),
    Fake('BackTranslate(''MAAAT'',''DynProg'',7)','')),
  SeeAlso(Translate)
);

ReplaceString_Description := Description(
  function(ReplaceString),
  Summary('Replace a phrase in a text'),
  CallingSequence( noeval(ReplaceString(old, new, txt))),
  Parameters(['old', string, 'pattern to be replaced'],
             ['new', string, 'new pattern'],
             ['txt', string, 'text that will changed']),
  Returns(string),
  Synopsis('Replaces all occurrences of a string in a text with a new string.'),
  Examples(
    'ReplaceString(''east'', ''west'', ''one flew east'')'),
  SeeAlso(SearchString, SearchDelim, SearchAllString)
);

Transcribe_Description := Description(
  function(Transcribe),
  Summary('DNA to RNA'),
  CallingSequence( noeval(Transcribe(dna))),
  Parameters(['dna', string, 'string of bases']),
  Returns(string),
  Synopsis('Replaces all T with U.'),
  Examples(
    'Transcribe(''ATG'')'),
  SeeAlso(Translate,BackTranscribe)
);

BackTranscribe_Description := Description(
  function(BackTranscribe),
  Summary('RNA to DNA'),
  CallingSequence( noeval(BackTranscribe(rna))),
  Parameters(['rna', string, 'string of bases']),
  Returns(string),
  Synopsis('Replaces all U with T in the string.'),
  Examples(
    'BackTranscribe(''AUG'')'),
  SeeAlso(Transcribe)
);

RSCU_Description := Description(
  function(RSCU),
  Summary('Relative synonymous codon usage'),
  CallingSequence( noeval(RSCU()), noeval(RSCU(dna))),
  Parameters(['dna', string, 'optional string of coding DNA']),
  Returns(list),
  Synopsis('The function RSCU returns the relative synonymous codon usage of a 
  organism if no argument is given. If a string of coding DNA is given the 
  relative synonymous codon usage for the string is returned.
  
  Relative synonymous codon usage values are estimated as the ratio of the
  observed codon usage to that value expected if there is uniform usage within
  synonymous groups
  
  The RSCU for a codon (i) is

    RSCUi = Xi / Xj

  where Xi is the number of times the ith codon has been used for a given amino acid, 
  and n is the number of synonymous codons for that amino acid'),
  References('Sharp PM, Tuohy TMF, and Mosurski KR. Codon usage in yeast:
  Cluster analysis clearly differentiates highly and lowly expressed genes. 
  Nucleic Acids Research 14:5125-5143')
);

ComputeCAI_Description := Description(
  function(ComputeCAI),
  Summary('Compute Codon Adaptation Index'),
  CallingSequence(noeval(ComputeCAI(e))),
  Parameters(['e', {string,Entry}, 'dna information']),
  Returns(numeric),
  Synopsis('Computes the CAI (codon adaptation index) for a dna string or an entry
  (with DNA tag). The function requires the the Relative Adaptiveness RA has to be 
  calculated prior to calling ComputeCAI. '),
  SeeAlso(SetupRA)
);

ComputeCAIVector_Description := Description(
  function(ComputeCAIVector),
  Summary('Compute CAI for all AA individually'),
  CallingSequence(noeval(ComputeCAI(e))),
  Returns(list),
  Synopsis('Computes the CAI for all codons in an entry.'),
  SeeAlso(ComputeCAI, SetupRA)
);

SetupRA_Description := Description(
  function(SetupRA),
  Summary('setup of the relative adaptivnes for CAI'),
  CallingSequence(noeval(SetupRA(mode))),
  Synopsis('Assigns the global variable RA needed by ComputeCAI.'),
  SeeAlso(ComputeCAI, RelativeAdaptiveness)
);

RelativeAdaptiveness_Description := Description(
  function(RelativeAdaptiveness),
  Summary('Calculate the realative adaptiveness'),
  CallingSequence(noeval(RelativeAdaptiveness([e]))),
  Returns(list),
  Synopsis(''),
  SeeAlso(ComputeCAI, SetupRA)
);

FindHighlyExpressedGenes_Description := Description(
  function(FindHighlyExpressedGenes),
  Summary('Find genes with high expression'),
  CallingSequence(noeval(FindHighlyExpressedGenes([e]))),
  Returns(list),
  Synopsis('experimental expression data must be avalable in the entries'),
  SeeAlso(ComputeCAI, SetupRA)
);


#################################################
# All the Descriptions for the Ancestor package #
#################################################

PASchapter := 'GM Cannarozzi, A Schneider and GH Gonnet (2007): Probabilistic Ancestral Sequences Based on the Markovian Model of Evolution - Algorithms and Applications, in: D Liberless (editor): Ancestral Sequence Reconstruction, Oxford University Press.':

ProbSeq_Description := Description(
  structure( ProbSeq ),
  Summary( 'stores a generic probabilistic sequence' ),
  CallingSequence( noeval( ProbSeq( ProbVec, CharMap) )),
  Parameters(
        ['ProbVec',{array(array),string},'Probability vectors'],
	['CharMap',procedure,'Character mapping function'] ),
  Synopsis('ProbSeq stores a generic (i.e. any type of sequence - amino acid,
nucleotides, codons or others) probabilistic sequence in the form of a probability 
vectors. Hence each position of the sequence is a vector giving the probability 
of each possible character. The sum of the probabilities at each position is 1 except 
vectors containing only zeros denoting a gap at this position. The ProbSeq can 
alternatively be constructed with a sequence as a string and a mapping function 
(typically one of IntToA, IntToB or CIntToCodon). It will then automatically construct 
a probabilistic sequence with a 1 for the known character and 0 otherwise. If only 
the probabilistic vectors are given, the constructor tries to find the appropriate 
mapping function based on the number of characters.'),
  Examples(
	'ps1 := ProbSeq(''ADRIAN'',IntToA);',
	'ps2 := ProbSeq([[.5,0,.5,0],[.3,.7,0,0]]);',
	Print('print(ps2)'),
	Unassign('ps1','ps2')),
  SeeAlso(IntToA,IntToB,CIntToCodon,ProbAncestor,PASfromMSA,PSDynProg,PASfromTree)
):

ProbAncestor_Description := Description(
  function ( ProbAncestor ),
  CallingSequence( noeval( ProbAncestor(ps1,ps2,d1,d2) ),
		   noeval( ProbAncestor(ps1,ps2,d1,d2,lnM,freq) )),
  Parameters( ['ps1, ps2',ProbSeq,'Probabilistic sequences'],
	      ['d1, d2', numeric, 'Distances to the common ancestor'],
	      ['lnM',matrix(numeric),'(optional) log. of a 1-PAM matrix'],
              ['freq',array(numeric),'(optional) character frequencies']),
  Returns(ProbSeq),
  Synopsis('Given two probabilistic sequences and the distances to their
common ancestor, this function computes the probabilistic ancestral sequence (PAS). The
logarithm of a 1-PAM matrix is needed to compute the mutation matrices for the
two distances. The mutation matrix NewlogPAM1 is the default value and can be used 
for amino acid sequences. For codon sequences CodonLogPAM1 is recommended. The ancestral
probabilities depend on the natural frequencies of the characters. By default, the 
amino acid frequencies AF are used. The global variable LogLikelihoods will be assigned
to an array containing the ln of the likelihoods at each position.'),
  References(PASchapter),
  Examples('ps1 := ProbSeq(''AARV'',IntToA):',
	   'ps2 := ProbSeq(''AVVV'',IntToA):',
	   'pas := ProbAncestor(ps1,ps2,10,10):',
	   Print('print(pas);'),
	   Unassign('ps1','ps2','pas')),
  SeeAlso(ProbSeq,PASfromMSA,PSDynProg,PASfromTree,CreateDayMatrices, 
	CreateCodonMatrices)
):

PSDynProg_Description := Description(
  function ( PSDynProg ),
  CallingSequence( noeval( PSDynProg('ps1','ps2','dist','meth') ),
		   noeval( PSDynProg('ps1','ps2','dist','lnM',
                                'freq','gapcosts','meth') )),
  Parameters( 	['ps1, ps2',ProbSeq,'Probabilistic sequences'],
	     	['dist',numeric,'Distance between the two sequences'],
		['lnM',matrix(numeric),'(optional) log. of a 1-PAM matrix'],
		['freq',array(numeric),'(optional) Natural frequencies of the characters'],
		['gapcosts',procedure,'(optional) Gapcosts as a function of gap length'],
		['meth',{'Local','Global'},'(optional) alignment method']),
  Returns([numeric,ProbSeq,ProbSeq]),
  Synopsis('Dynamic programming over two probabilistic sequences. In the standard case
  of proteins, the global varibles NewLogPAM1, AF and gap costs according to the Dayhoff
  matrices are used. For other types of sequences (e.g. DNA or codons),
  the logarithm of a mutation matrix (e.g. CodonLogPAM1) and the natural
  frequencies of the characters (e.g. CF) are required. Also, a gap cost function is needed that returns
  the costs for a gap of a given size. This is usually k->FixedDel+(k-1)*IncDel with the coefficients
  taken from the CMS matrix for the given distance.
  The default alignment method is ''Local''.'),
  References(PASchapter),
  Examples(	'ps1 := ProbSeq(''RAAVTGAAAQQQFT'',IntToA):',
		'ps2 := ProbSeq(''VTGQQQ'',IntToA):',
		'dist := 10:',
		'aps := PSDynProg(ps1,ps2,dist):',
		Print('print(aps);'),
		Unassign('ps1','ps2','dist','aps') ),
  SeeAlso(ProbSeq,PASfromMSA,ProbAncestor,PASfromTree,CreateDayMatrices,
        CreateCodonMatrices)
):

PASfromMSA_Description := Description(
  function ( PASfromMSA ),
  CallingSequence( noeval( PASfromMSA('msa') ),
		   noeval( PASfromMSA('msa','lnM','freq') )),
  Parameters(   ['msa',MAlignment,'multiple sequence alignment'],
		['lnM',matrix(numeric),'(optional) log. of a 1-PAM matrix'],
                ['freq',array(numeric),'(optional) character frequencies']),
  Returns( ProbSeq ),
  Synopsis('Computes the probabilistic ancestral sequence at the root of a
phylogenetic tree over a multiple sequence alignment of probabilistic
sequences. For protein sequences, the global variable
NewLogPAM1 is assumed to describe the amino acid mutation probabilities. 
The global variable LogLikelihoods will be assigned
to an array containing the ln of the likelihoods at each position.'),
  References(PASchapter),
  Examples(	'seqs := [''AAAR'',''AARR'',''VTAARRQQ'']:',
		Print('msa := MAlign(seqs):'),
		Print('print(msa);'),
		'pas := PASfromMSA(msa):',
		Print('print(pas);'),
		Unassign('seqs','msa','ps','pas') ),
  SeeAlso(ProbSeq,PSDynProg,ProbAncestor,PASfromTree,MAlign,MAlignment)
):

PASfromTree_Description := Description(
  function ( PASfromTree),
  CallingSequence( noeval( PASfromTree('seqs','tree')),
		   noeval( PASfromTree('seqs','tree','lnM','freq','gapcosts'))),
  Parameters(   ['seqs',array({ProbSeq,string}),'(probabilistic) sequences'],
                ['tree',Tree,'tree of the sequences'],
                ['lnM',matrix(numeric),'(optional) log. of a 1-PAM matrix'],
		['freq',array(numeric),'(optional) freq. of characters'],
		['gapcosts',procedure,'(optional) gap cost function']),
  Synopsis('Computes the probabilistic ancestral sequence at the root of a
phylogenetic tree over a list of probabilistic sequences. For each internal node,
the prob. sequences at the roots of the two subtrees are aligned and then an
ancestral vector is computed. The global variable LogLikelihoods will be assigned
to an array containing the ln of the likelihoods at each position.
The third field of the leaves must be integer numbers corresponding to the sequences in the 
list (as it is automatically teh case when the tree comes either from an MAlign or a
PhylogeneticTree call). For protein sequences, the global variables
NewLogPAM1, AF and gap costs drevied from DMS are assumed. For other types
of  sequences, the log of a mutation matrix (e.g. CodonLogPAM1), 
a vector of natural character frequencies (e.g. CF) and a function to compute gap costs
for a given gap length at a given PAM distance is needed. (Typically of the form
(pam,len)->-37.64+7.434*log10(pam)-(len-1)*1.3961).'),
 References(PASchapter),
  Examples(     'seqs := [''VAAAR'',''AARR'',''VTAARRQQ'']:',
		'ps := [seq(ProbSeq(s,IntToA),s=seqs)]:',
		Print('tree := PhylogeneticTree(seqs,[seq(i,i=1..length(seqs))],DISTANCE)'),
		'pas := PASfromTree(ps,tree):',
		Print('print(pas);'),
		Unassign('seqs','ps','tree','gapcosts','pas') ),
 SeeAlso(ProbSeq,PSDynProg,ProbAncestor,PASfromMSA,CreateDayMatrices,CreateCodonMatrices)
):

############# End Ancestor Descriptions ################

WriteData_Description := Description(
  function( WriteData ),
  Summary( 'write data to a file' ),
  CallingSequence( noeval( WriteData( data, filename, separator )) ),
  Parameters( [data, anything, 'data to be saved'],
    [filename, string, 'name of file to be written'],
	[separator, string, 'string used as separator'] ),
  Returns( NULL ),
  Synopsis( 'WriteData function writes data to a file in a simple format. 
  Useful for exporting data to other applications. The filename defaults 
  to temp.dat and the separator is by default the tab character.' ),
  SeeAlso( OpenWriting, LockFile, FileStat, WriteFasta, WriteSeqXML )
):

Globals_Description := Description(
  function( Globals ),
  Summary('returns all global variables set inside a function'),
  CallingSequence( noeval(Globals('func'))),
  Parameters( ['func',procedure,'the function']),
  Returns(set(symbol)),
  Synopsis('Globals returns all global variables that are set inside
  a function. For functions inside modules and inside other functions
  Globals returns exactly those global variables that are also visible to
  the user. Variables that are only global inside a module are not
  reported.'),
  Examples( 'Globals(CreateDayMatrices)'),
  SeeAlso('local',UnassignGlobals)
):

UnassignGlobals_Description := Description(
  function( UnassignGlobals ),
  Summary('unassigns all global variables from a given function'),
  CallingSequence( noeval(UnassignGlobals('func')),
                   noeval(UnassignGlobals('func','ex'))),
  Parameters( ['func',procedure,'the function'],
              ['ex',set,'(optional) exceptions']),
  Returns(NULL),
  Synopsis('UnassignGlobals unassigns all global veriables that are set
  by a given function. The optional second argument allows the user
  to define a set of variables that should be excluded from this.'),
  Examples( 'Clique(TetrahedronGraph())','CliqueUpperBound',
  'UnassignGlobals(Clique)','CliqueUpperBound' ),
  SeeAlso('Globals')
):

Description_Description := Description(
  structure( Description ),
  Summary( 'contains structured information on a function'),
Synopsis('This class contains structured information on a function suitable
to build the "description" entry for a function.  This structure establishes
the "official" format for description of functions in Darwin.' ),
  Paragraph(2,'Description allows an arbitrary number of parameters.'),
  Paragraph(2,'The first argument describes the
function/class/variable/iterator being described.  It is a structure, where
the name of the structure is one of function/class/variable/iterator and the
only field is the name of the object being described. E.g.  function(sin),
structure(Stat), variable(''Pi'').'),
  Paragraph(2,'The Paragraph(), Indent() or Table() or any other Document
valid structures can appear at any place and will insert a paragraph/table
etc. of text at that point.'),
  Paragraph(2,'The following arguments are optional, but must be given in
this order.'),'\n',
  Code('Summary( string )'),
Paragraph(2,  'Summary has an English short description of what the function
does. It should fit in one line together with the name of the function.
It is better if does not start with a capital letter.'),'\n',
Code('CallingSequence( noeval( Func(Ver1) ),
      noeval( Func(Ver2) ))'),
Paragraph(2,  'CallingSequence contains examples on how the function may be
called.  These are typically surrounded by noeval() to prevent their execution.
They serve as a pattern for the one or many ways of using the object.
The names of the arguments used will be described later.'),'\n',
Code('Parameters( [param1, type1, description1],
            [param2, type2, description2], ...)'),
Paragraph(2,  'Parameters holds the name of the parameters, their types,
and a short description for each of them.  Make sure that the 3 columns fit
in the width of a normal page (80 columns).  For a data structure/class,
the names represent the fields of the structure.'),'\n',
Code('Selector( [selname1, type1, description1],
[selname1, type1, description1], ... )'),
Paragraph(2,  'For data structures/classes, these provide the type and
description of the explicit and computed selectors.'),'\n',
Code('Returns( type )
Returns( [type,description] )'),
Paragraph(2,  'Returns describes the value returned, when it is obvious what
it is, the type information is enough, otherwise, a description may be
added.'),'\n',
Code('Synopsis( string, string, ... )'),
Paragraph(2,  'Like a Paragraph, Synopsis contains the description of what
the function does/computes.'),'\n',
Code('References( string, string, ... )'),
Paragraph(2,  'Provides a format for citations related to the object.'),'\n',
Code('Keywords( string, string, ... )'),
Paragraph(2,  'Keywords related to this help topic.'),'\n',
Code('Examples(   )'),
  Paragraph(2, 'Examples contains examples of how the function is used.
They will appear sequentially and with their output.'),'\n',
'Examples( ) have five formats:',
  Paragraph(2,'Quoted string:  the statement contained in quotes is executed
and the statement and its output are printed out. If the string is terminated
with a colon (":"), then its output will not be part of the help file
(like in a Darwin session).  No semicolon is needed at the end, one is added
if necessary.'),
  Paragraph(2,'Fake(commands,output):  The first element is the input to
Darwin, the second element is the desired output.
Nothing is evaluated (e.g. an assignment is not executed).
This is convenient when the action being described interacts with the system
(show a Plot, write a file, etc.)'),
  Paragraph(2,'Hide(command):  This executes a statement but does not print
out either the input or the output.  It is useful when we want to prepare
for the execution or undo some action.'),
  Paragraph(2,'Unassign(string, string, ... ): The arguments, which should be
strings, are assumed to be names that were assigned in the example and need
to be unassigned.  Do not leave names assigned, as these are almost certain
to cause trouble when we generate the entire set of help files.'),
  Paragraph(2,'Print(command): The command is expected to print
(which unless precautions are taken, will end up printing in the wrong place.)
This command collects the printing output in a file and inserts it
appropriately.  Must be used for all the commands which print in one way or
another.'),'\n',
Code('SeeAlso( token, [token,description], ... )'),
Paragraph(2,  'SeeAlso contains a series of tokens suitable for additional
references (and an optional description if necessary)')
):

ReadURL_Description := Description(
  function(ReadURL ),
  CallingSequence(noeval(ReadURL(url)) ),
  Parameters(['url', string, 'a URL'] ),
  Returns(string ),
  Synopsis('Reads a URL and returns it as a string. Works the same way
as ReadRawFile, just with URLs instead of filenames.' ),
  SeeAlso( OpenAppending, OpenWriting, OpenReading, ReadRawLine, ReadLine,
        SplitLines, SearchDelim, DownloadURL)
):

DownloadURL_Description := Description(
  function(DownloadURL ),
  CallingSequence(noeval(DownloadURL(url,filename)) ),
  Parameters(['url', string, 'a URL'],
	     ['filename',string,'filename to save URL'] ),
  Returns(string ),
  Synopsis('Downloads a URL and saves its content in a file.' ),
  SeeAlso( OpenAppending, OpenWriting, OpenReading, ReadRawLine, ReadLine,
        SplitLines, SearchDelim, ReadURL)
):

MST_Description := Description(
 function(MST),
  Summary ('Minimum-Spanning Tree algorithm'),
  CallingSequence(noeval(MST(A)) ),
  Parameters([A,Graph,'a Graph'] ),
  Returns(Graph),
  Synopsis('The input to this algorithm is an undirected graph. It computes
   the minimum spanning tree according to Prim''s algorithm. The implementation
   has a time complexity of O(|V|^2*log(|V|)), whereas the theoretical minimum
   is O(|E|). Therefore, this implementation is relatively good  when working with
   dense graphs, in which case |E| is O(|V^2|).'),
  Examples('hex := HexahedronGraph()', 'MST(hex)', Unassign('hex')),
  SeeAlso_Graph
):

CenterTreeRoot_Description := Description(
  function(CenterTreeRoot),
  Summary ('Place root in center of tree'),
  CallingSequence(noeval(CenterTreeRoot(t)) ),
  Parameters([t, Tree, 'a Tree'] ),
  Returns(Tree),
  Synopsis('Place root of tree such that the number of leaves on each side 
    is most equal.  Useful when drawing circular trees when the root has been 
    placed far from the center.'),
  Examples( 't := Tree(Leaf(''1'',3),0,Tree(Tree(Leaf(''2'',3),2,Leaf(''3'',3)),1,Leaf(''4'',3))):', 
            'CenterTreeRoot(t);',
  Unassign('t')),
  SeeAlso(RotateTree, TreeSize)
):

TreeSize_Description := Description(
  function(TreeSize),
  Summary ('Number of leaves in a tree'),
  CallingSequence(noeval(TreeSize(t)) ),
  Parameters([t, Tree, 'a Tree'] ),
  Returns(integer),
  Synopsis('Traverse a tree and returns the number of leaves.'),
  Examples('t := Rand(Tree):', 'TreeSize(t);',
  Unassign('t')),
  SeeAlso(RotateTree, CenterTreeRoot)
):

MafftMSA_Description := Description(
  function(MafftMSA),
  Summary('Multiple sequence alignment using Mafft'),
  CallingSequence( noeval(MafftMSA(seqs, labels, dm)) ),
  Parameters(
    [seqs,list(string),'sequences to align'],
    [labels,list(string),'(optional) labels for the sequences'],
    [dm,DayMatrix,'(optional) Dayhoff matrix used for alignment']),
  Returns(MAlignment),
  Synopsis( 'MafftMSA computes a multiple sequence alignment (MSA).
    If no Dayhoff matix is passed, mafft uses the BLOSUM62 scoring 
    matrix. Since mafft does not return a score of the MSA, the 
    score and upperbound score in the MAlignment data structure is 
    left undefined. The function works only in unix/linux, and assumes 
    that Mafft is available. Information and source of mafft is available 
    from ''http://align.bmr.kyushu-u.ac.jp/mafft/software/''.'),
  Examples(
    Fake('msa := MafftMSA([''ASDFAARA'',''ASDAVRA'',''ASFDAATA''])',''),
    Fake('print(msa)',
'Multiple sequence alignment:
----------------------------
Score of the alignment: 0
Maximum possible score: 1.7976931e+308

1    ASDFAARA
2    AS_DAVRA
3    ASFDAATA')
	),
  SeeAlso( Align, Alignment, MAlign, MAlignment )
):

MaximizeRD_Description := Description(
 function( MaximizeRD ),
 CallingSequence( noeval(MaximizeRD(ini, f, ran, MaxHours)) ),
 Parameters( ['ini', anything, 'Initial solution'],
           ['f', procedure,'Function to be optimized'],
           ['ran', procedure, 'Procedure that returns a new direction'],
           ['MaxHours',positive,'Optional, limit of computation time in hour.']
  ),
 Returns( 'point:type(ini)' ),

 Synopsis( 'This function finds the point (in a potentially high dimensional
 space) that maximizes f using random directions.'),
  
  Paragraph(-5, 'The input "ini" can be of any type that accepts linear operations (type(ini) could be numerical, list(numerical),matrix(numerical) or anything which accepts addition of similar objects and multiplication by numerical constants).'),

  Paragraph(-5, 'The function f takes a single argument of type(ini) and returns a numerical value.  f(ini) is the initial value. The function f does not need to be continuous.  It is common to have f returning -DBL_MAX when the argument is out of the valid range.'),

  Paragraph(-5, 'The procedure ran returns an object of type(ini) and provides a random direction provides a random direction in the space of the arguments.  ran is called with an argument which is the most recent optimal point.  This is useful when the generation of the random direction requires information about the point.  Let '),

  Paragraph(5, 'd := ran( pt );'),

  Paragraph(-5,'Then, '),

  Paragraph(5,'f( pt + h*d ) '),
        
  Paragraph(-5,'are the points that will be explored, that is starting from pt following the direction d.  It is clear that pt + h*d has to be computable or in other words (h is numeric) that type(ini) is an object which accepts linear operations.  (type(ini) could be numerical, list(numerical), matrix(numerical) or anything which accepts addition of similar objects and multiplication by numerical constants).  '),

  Examples( 'MaximizeFunc(x -> sin(x), 0..1)', 
	    'MaximizeFunc(x -> x^2 - 3*x, -2..0)' ),
  SeeAlso_Minimize
):

Romberg_Description := Description(
  function(Romberg),
  Summary('Integrates a function using Romberg''s Schema'),
  CallingSequence( noeval(Romberg(f,a..b,eps,n))),
  Parameters(['f', procedure, 'function to integrate'],
             ['a..b', range, '(optional, default -inf..+inf) range of the integration'],
             ['eps',numeric, '(optional, default 1e-8) epsilon'],
             ['n', posint, '(optional, default 20) maximum dimension of Romberg''s tableau']), 
  Returns(numeric),
  Synopsis('Integrates the function numerically using Romberg''s method. If the range is not given, it integrates between -infinity and +infinity by using the following substitution int(f(x),x=-inf..+inf) = int(f(tan(x))*(1+tan(x)^2),x=-Pi/2..Pi).'),
  Examples(
    'Romberg(x -> sin(x), 0..2*Pi)')
);

UnionFind_Description := Description(
  structure(UnionFind),
  Summary('Implementation of the Union-Find data structure and algorithm'),
  CallingSequence( noeval(UnionFind('Elements')), noeval(UnionFind()) ),
  Parameters(['Elements', {list(set),list}, '(optinal) initial elements']), 
  Returns(UnionFind),
  Selectors(['Clusters', list(set), 'sets resulting from the union operations']),
  Synopsis('The Union-Find data structure allows one to repetetly join two sets. The algorithm''s performance, given m union/find operations of any ordering, on n elements takes O(log(n)*m*a(m,n)) where a(m,n) is the inverse ackermann function, thus close to O(log(n)) per operation.'),
Paragraph(-2,'Sets can be unified by performing a union operation on the UnionFind data structure and a list containing two elements, one from each of the two sets. New sets can be added two the data structure using the plus function.'),

References('Algorithmen und Datenstrukturen, T. Ottmann and P. Widmayer, Spektrum, Akad.Verl,,1996'),
  Examples('uf := UnionFind([{22,14,31},{12,41,23},{4},{99,25}]):', 
      'union(uf,[14,99]):',
      'uf[Clusters];', 
      'uf + {33,2,6}:',
      'union(uf, [2,4]):',
      'uf[Clusters];')
);


EstimateNG86_Description := Description(
  function(EstimateNG86 ),
  CallingSequence(noeval(EstimateNG86(seq1,seq2)) ),
  Parameters(['seq1', string, 'aligned DNA sequence'],
             ['seq2', string, 'aligned DNA sequence'] ),
  Returns(array(numeric)),
  Synopsis('Computes dN and dS following the method by Nei and Gojobori (1986).
The function returns four values, dN and dS as well as the number of nonsynonymous
(N) and synonymous sites (S). If either dN or dS cannot be computed (typically because
of too much divergence), -1 is returned for the respective value.'),
Examples('EstimateNG86(AAAAAATTT,AAAAAGTTA)'),
  SeeAlso( CodonAlign, EstimateSynPAM, EstimatePB93)
):


EstimatePB93_Description := Description(
  function(EstimatePB93 ),
  CallingSequence(noeval(EstimatePB93(seq1,seq2)) ),
  Parameters(['seq1', string, 'aligned DNA sequence'],
             ['seq2', string, 'aligned DNA sequence'] ),
  Returns(array(numeric)),
  Synopsis('Computes Ka and Ks following the method by Pamilo and Bianchi (1993).
The function returns a list [Ka,Ks] with the two estimates. If these values cannot be computed
(typically because of too much divergence), then [-1,-1] is returned.'),
Examples('EstimatePB93(AAAAAATTT,AAAAAGTTA)'),
  SeeAlso( CodonAlign, EstimateSynPAM, EstimateNG86)
):

RobinsonFoulds_Description := Description(
  function( RobinsonFoulds ),
  Summary('Computes the pairwise Robinson-Foulds distance between a set of trees'),
  CallingSequence( noeval(RobinsonFoulds(trees)) ),
  Parameters(['trees', list(Tree), 'list of trees']),
  Returns(matrix(numeric)),
  Synopsis('The Robinson and Foulds (RF) distance between two trees is the number 
of non-trivial bipartitions present in one of the two trees but not the other, 
divided by the number of possible bi-partitions. Thus, the smaller the  RF 
distance between two trees the closer are their topologies. The algorithm runs
in O(m^2*n), where m ist the number of trees an n the number of Leaves.'),
  References('Pattengale, Gottlieb and Moret, "Efficiently Computing the 
Robinson-Foulds Metric", J. Comp. Biol., 2007, 14(6), 724--735'),
  Examples(
    't1 := Tree(Tree(Leaf(a,2),1,Leaf(b,2)),0,Tree(Leaf(c,2),1,Leaf(d,2))):',
    't2 := Tree(Tree(Leaf(a,2),1,Leaf(d,2)),0,Tree(Leaf(c,2),1,Leaf(b,2))):',
	'RobinsonFoulds([t1,t2]);'
  ),
  SeeAlso( IdenticalTrees, Tree, IntraDistance, BipartiteSquared )
):



BipartiteSquared_Description := Description(
  function( BipartiteSquared ),
  Summary('Computes the distance between two trees'),
  CallingSequence( noeval(BipartiteSquared(tree1,tree2,conf,mode)) ),
  Parameters(['tree1', Tree, 'first tree'],
	['tree2', Tree, 'second tree'],
	['conf', posint, '(optional, def=2) size of basic configuration'],
	['mode',string, '(optional, def=RF) mode of counting: RF or SizeDiff']
	),
  Returns(posint),
  Synopsis('BipartiteSquared generalizes the Robinson and Foulds (RF)
distance between two trees.
The first generalization is with respect to the basic configurations
matched.
The RF inspects each internal edge, which separates the leaves in
two (conf=2) sets.
It can also inspect internal nodes, which separate the leaves in
3 groups (conf=3) or in quartets, which separate the leaves in
4 groups (conf=4).
The second generalization is in the way that the differences are
counted.
The RF measure is like a Hamming distance, if the sets of leaves
are different it counts 1 if they are the same it counts 0
(mode=RF).
A second alternative is to count the size of the set differences,
that is for each pair, count the number of leaves in one but not in the
other (mode=SizeDiff).' ),
Paragraph( -2, 'If the global variable MinLen is assigned a
numerical value, any edge whose length is <= MinLen will be
considered non-existent, that is it will not generate a difference.
This is useful when comparing against trees which are not binary,
but multifurcating, like trees derived from taxonomic information.
The name BipartiteSquared comes from the algorithm to compute
the distance which solves two nested weighted bipartite matching
problems: the inner one for finding the minimum cost of a configuration
against another and the outer one for matching the best configurations
of each tree.' ),
  Examples(
    't1 := Tree(Tree(Leaf(a,2),1,Leaf(b,2)),0,Tree(Leaf(c,2),1,Leaf(d,2))):',
    't2 := Tree(Tree(Leaf(a,2),1,Leaf(d,2)),0,Tree(Leaf(c,2),1,Leaf(b,2))):',
	'BipartiteSquared(t1,t2,2,RF);',
	'BipartiteSquared(t1,t2,2,SizeDiff);'
  ),
  SeeAlso( LeastSquaresTree, Synteny, GapTree, SignedSynteny,
	BootstrapTree, PhylogeneticTree, 
	ComputeDimensionlessFit, RBFS_Tree, RobinsonFoulds, ReconcileTree,
	IntraDistance, BipartiteSquared )
):


IntraDistance_Description := Description(
  function( IntraDistance ),
  Summary('Computes the pairwise distances between trees in a list'),
  CallingSequence( noeval(IntraDistance(Trees,DistanceFunction)) ),
  Parameters(['Trees', list(Tree), 'list of trees'],
	[DistanceFunction,procedure,'(optional), distance between two trees'] ),
  Returns(table),
  Synopsis('IntraDistance computes the distances between every pair
of trees in the given list over the set of common leaves.
That is, each pair of trees is first reduced to the subtrees of the common
leaves and then the distance is computed.
If there are less than 4 common leaves, the pair is ignored as the distance
will be always 0.
IntraDistance returns a table which contains the first three moments
(0th, first and second) of the
distance distribution per size of the intersecting leaves.
That is to say, if r is the result, then r[4] will be a list of 3 values,
which are the 0th, 1st and 2nd moment of the distribution of distances
for trees which shared exactly 4 leaves.' ),
Paragraph(-2, 'If no DistanceFunction is provided, the Robinson-Foulds
distance will be used.
If a branch length of a tree is less or equal to MinLen, then it is
assumed that this branch does not exists, i.e. this is a case of
multifurcation rather than bifurcation and the corresponding edge
will not be counted in the distance.
This is a difference from the RobinsonFoulds distance and it allows
to compute distances to trees with partial information, like trees
derived from taxonomic data.' ),
  Examples(
    'st1 := Tree(Leaf(a,2),1,Leaf(b,2)):',
    'st2 := Tree(Leaf(c,2),1,Leaf(d,2)):',
    'st3 := Tree(Leaf(e,2),0.5,st2):',
    'st4 := Tree(Leaf(a,2),0.5,Tree(Leaf(e,2),1,Leaf(b,2))):',
    'r := IntraDistance( [Tree(st1,0,st2),Tree(st3,0,st1),Tree(st4,0,st2)] ):',
    Print('print(r)'),
    Unassign( 'st1', 'st2', 'st3', 'st4', 'r' )
  ),
  SeeAlso( LeastSquaresTree, Synteny, GapTree, SignedSynteny,
	BootstrapTree, PhylogeneticTree, 
	ComputeDimensionlessFit, RBFS_Tree, RobinsonFoulds, ReconcileTree,
	IntraDistance, BipartiteSquared )
):



ConcatStrings_Description := Description(
  function(ConcatStrings ),
  CallingSequence(noeval(ConcatStrings(slist,sep)) ),
  Parameters(['slist', array(string), 'array of strings'],
             ['sep', string, '(optional) separator'] ),
  Returns(string),
  Synopsis('Concatenates a list of strings to one string. The optional second argument
can be a separator character which is inserted between any two substrings. This
method is much more efficient than repeatedly appending to a string.'),
Examples('ConcatStrings([''Hello '',''World'',''!''])',
	  'ConcatStrings([''A'',''B'',''C''],'', '')'),
  SeeAlso(string, trim, RenderTemplate)
):

trim_Description := Description(
  function(trim),
  Summary('Removes leading and trailing whitespace from a string'),
  CallingSequence(noeval(trim(s)), noeval(trim(s,chars))),
  Parameters([s,string,'string to be trimed'],
             [chars,set,'(optional) set of chars to be removed']),
  Returns(string),
  Synopsis('Return a copy of the string s with leading and trailing
whitespace removed. If chars is not specified, the following characters
are considered to be whitespaces: '' '',''\\t'',''\\n'',''\\r'' and ''\\0''.'),
  Examples('trim(''\tHello '')','trim(''a World '',{'' '',''a''})'),
  SeeAlso(string,ConcatStrings,RenderTemplate)
):

SpeciesCode_Description := Description(
  function(SpeciesCode),
  Summary('NCBI TaxonId to SwissProt species code'),
  CallingSequence(noeval(SpeciesCode(posint))),
  Parameters(['tax',posint,'NCBI taxonomic ID']),
  Returns(string),
  Synopsis('Maps a NCBI taxonomic identifier to the SwissProt species code. If the 
ID is not known, the function returns an error.'),
  Examples('SpeciesCode(9606)'),
  SeeAlso(UpdateSpeciesCode, TaxonId)
):


TaxonId_Description := Description(
  function(TaxonId),
  Summary('SwissProt species code to NCBI TaxonId'),
  CallingSequence(noeval(TaxonId(string))),
  Parameters(['org',posint,'SwissProt species code']),
  Returns(integer),
  Synopsis('Maps a SwissProt species code to the NCBI taxonomic identifier. 
If the species code is not known, the function returns an error.'),
  Examples('TaxonId(''HUMAN'')'),
  SeeAlso(SpeciesCode, UpdateSpeciesCode)
):

UpdateSpeciesCode_Description := Description(
  function(UpdateSpeciesCode),
  Summary('downloads the SwissProt-NCBI species mapping'),
  CallingSequence(noeval(UpdateSpeciesCode())),
  Synopsis('Downloads the mapping between the SwissProt species codes
and the NCBI taxonomic identifiers from http://www.expasy.ch/cgi-bin/speclist 
and converts it into a Darwin readable file called speciescode.drw which 
is located in Darwin''s data directory.'),
  SeeAlso(SpeciesCode, TaxonId)
):

PruneTree_Description := Description(
  function( PruneTree ),
  CallingSequence( noeval(PruneTree( t, contains )) ),
  Parameters( ['t', Tree],
              ['contains', {list, set, procedure}, 'labels remaining in the pruned tree'] ),
  Returns( Tree ),
  Synopsis( 'This function returns a pruned version of the input tree 
containing only leaves whose labels are member of the ''contains''-set / -list or
for which ''contains()'' of a Leaf() structure evaluates to true respectively.'),
  Examples( 'T := Tree( Leaf(''a'', 2), 0.5, Tree(Leaf(''b'',1.5),0.7,Leaf(''e'', 1)) )',
        'PruneTree( T, [''a'',''b''] )', Hide('T := noeval(T)') ),
  SeeAlso( Leaf, Tree, RotateTree )
):


ReconcileTree_Description := Description(
  function(ReconcileTree),
  Summary('Reconciles a gene tree with a species tree'),
  CallingSequence( noeval(ReconcileTree(g,s,g2s)), noeval(ReconcileTree(g,s,g2s,reroot))),
  Parameters(['g', Tree, 'Gene Tree'],
             ['s', {Tree,'OVERLAP'}, 'Species Tree or Species Overlap method'], 
             ['g2s',procedure, 'mapping function from gene to species'],
             ['reroot', boolean, '(optional) reroot gene tree'] ),
  Returns(list),
  Synopsis('The function ReconcileTree infers gene duplication and speciation 
events on a gene tree by comparing it to a TRUSTED species tree. Alternatively,
if no trusted species tree exists, one can use the species overlap reconcilation 
method by setting passing ''OVERLAP'' as the species tree.
The function g2s is a mapping function from the gene name to its species.'),
  Paragraph(-2,'If reroot is set to ''true'' (by default it''s false), the function 
reroots the gene tree on every possible branch and reconciles all those trees. 
It returns the rooted gene tree, that minimizes the number of dupliction events.'),
  Paragraph(-2,'The function returns the reconciled gene tree and the number of 
duplication events on it. The events are stored in the ''XTRA'' field of the tree: 
''D=Y'' and ''D=N'' indicate whether the node represents a duplication or speciation
event respectively.'),
  
  References('Zmasek CM and Eddy SR. A simple algorithm to infer gene duplication
and speciation events on a gene tree. Bioinformatics, 2001, 17(9):821-828',
  'van der Heijden RT et al, Orthology prediction at scalable resolution by 
phylogenetic tree analysis. BMC Bioinformatics. 2007, 8:83.'),
  
  Examples( 'GeneTree := Tree(Tree(Tree(Leaf(a_HUMAN, 3), 2, Leaf(a_YEAST,3)),
              1, Leaf(b_BOVIN,3)), 0, Leaf(c_HUMAN,3))',
        'SpeciesTree := Tree(Tree(Leaf(HUMAN,2),1,Leaf(BOVIN,2)),0,Leaf(YEAST,2))',
        'SwissProtID := x -> x[SearchString(''_'',x)+2..-1]', 
        'tree := ReconcileTree(GeneTree, SpeciesTree, SwissProtID)',
        'tree := ReconcileTree(GeneTree, ''OVERLAP'', SwissProtID)',
        Unassign('SpeciesTree, GeneTree, SwissProtID, tree') ),
  SeeAlso( Tree, RotateTree, PhylogeneticTree, LeastSquaresTree, RobinsonFoulds,
	IntraDistance, BipartiteSquared )
);

PhyML_Description := Description(
  function(PhyML),
  Summary('Wrapper for PhyML, a ML tree reconstruction tool'),
  CallingSequence( noeval(PhyML(msa)) ),
  Parameters(['msa',{MAlignment, list(string)},'Multiple Sequence Alignment'],
             ['labels',list(string),'(optional) Sequence Labels'],
             ['subst',string,'(optional) substitution model'],
             ['inv_sites','inv_sites=boolean','(optional) Estimate invariant sites'],
             ['gamma_dist','gamma_dist={''e'',positive','(optional) Use or estimate gamma parameter'],
             ['rate_cats','rate_cats={numeric}','(optional) number of discrete rate categories'],
             ['inv_sites','inv_sites=boolean','(optional) Estimate invariant sites'],
             ['start_tree','start_tree={Tree,string}','(optional) start tree for search'],
             ['nr_bootstrap','nr_bootstrap={numeric}','(optional) number of bootstrap samples'],
             ['opt_topo','opt_topo=boolean','(optional) optimize topoplogy'],
             ['opt_branch','opt_branch=boolean','(optional) optimize branchlengths'],
             ['seqtype','seqtype=string','(optional) type of sequences (default AA)'],
             ['search_heuris','search_heuris=string','(optional) applied search heuristics'],
             ['LnLperSite', 'LnLperSite=boolean', '(optional) Report log-likelihood values per site? (default NO)']),
  Returns( TreeResult ),
  Synopsis('PhyML is a tool to compute maximum likelihood trees from multiple sequence
alignments. For details see manual (Reference section).'),
'',
Paragraph(-2, '  Available substitution models:'),
Paragraph(-22,'    <default>         JTT'),
Paragraph(-22,'    subst=string      HKY85,JC69,K80,F81,F84,TN93,
   GTR,LG,WAG,JTT,MtREV,Dayhoff,DCMut,RtREV,CpREV,VT,
   Blosum62,MtMam,MtArt,HIVw,HIVb'),
Paragraph(-22,'    seqtype={AA,DNA}  specify type of sequence data. By default,
   Amino Acid is assumed'),
Paragraph(-2, '  Available model modifiers:'),
Paragraph(-31,'    inv_sites={''e'', 0..1}      estimate (e) or set proportion 
of invariant sites to a fixed value.'),
Paragraph(-31,'    gamma_dist={''e'',positive}  estimate (e) or set the 
  gamma rate parameter.'),
Paragraph(-31,'    rate_cats=integer          number of discrete rate categories'),
'',
Paragraph(-2, '  Other parameters:'),
Paragraph(-31,'    nr_bootstrap=integer       determines the amount of bootstrap 
samples to be evaluated. Default=0'),
Paragraph(-31,'    start_tree={Tree,''MP'',''BioNJ''} specifies the start 
topology for the ML search. ''MP'' uses a maximum parsimony tree and 
''BioNJ'' starts with a Neighbor-Joining tree. Alternatively,
you can pass a starting topology. Default=''MP'''),
Paragraph(-31,'    search_heuris={NNI,SPR,BEST}   specifies the applied seach heuristics. 
By default, NNI is used.'),
Paragraph(-31,'    opt_topo=boolean           specifies, whether or not the topology is optimized.'),
Paragraph(-31,'    opt_branch=boolean         specifies, whether or not the branchlengths are optimized.'),
'',
  References('Guindon S., Gascuel O. A simple, fast, and accurate algorithm to estimate large 
phylogenies by maximum likelihood, Systematic Biology, 52(5):696-704, 2003.'),
  Examples( Fake('msa := Rand(MAlignment):',''), 
        Fake('PhyML(msa, ''subst''=''LG'',''inv_sites''=''e'')',
'TreeResult(Tree(Tree(Leaf(RandSeq7, 1e-10),0,Leaf(RandSeq9,0.2974)),0,Tree(Leaf(
RandSeq6,0.2229),0.2173,Tree(Tree(Tree(Leaf(RandSeq5,1.0211),1.0162,Leaf(
RandSeq8,1.3645)),0.7386,Tree(Tree(Leaf(RandSeq3,1.0698),1.0698,Leaf(RandSeq10,
1.5540)),0.7504,Leaf(RandSeq1,0.7580))),0.4718,Tree(Leaf(RandSeq2,0.4878),0.4878
,Leaf(RandSeq4,0.6897))))),ML,table([{[Likelihood, [-3094.8008]]}, {}, {}, {[
InvSites, [0.00500000]]}, {}, {[SubstModel, [LG]]}, {[CPUtime, [12.4500]]}, {}, 
{[Method, [Phyml 3.0]]}, {[Alpha, [99.8640]]}, {}, {}, {}],unassigned))')),
  SeeAlso( Tree, PhylogeneticTree, LeastSquaresTree, MAlign, MafftMSA, 
  RobinsonFoulds, TreeResult, RellTree )
):


RAxML_Description := Description(
  function(RAxML),
  Summary('Wrapper for RAxML, a ML tree reconstruction tool'),
  CallingSequence( noeval(RAxML(msa)) ),
  Parameters(['msa',{MAlignment, list(string)},'Multiple Sequence Alignment'],
             ['labels',list(string),'(optional) Sequence Labels'],
             ['subst',string,'(optional) substitution model'],
             ['inv_sites','inv_sites=boolean','(optional) Estimate invariant sites'],
             ['estimate_basefreqs','estimate_basefreqs=boolean','(optional) Estimate base frequencies'],
             ['start_tree','start_tree={Tree,string}','(optional) start tree for search'],
             ['nr_runs','nr_runs=posint','(optional) number of ML tree searches'],
             ['bootstrap','bootstrap={0,posint}','(optional) number of bootstrap samples'],
             ['rates','rates=string','(optional) Rates model'],
             ['threaded','threaded=integer','(optional) number of threads to be used'],
             ['eps','eps=positive','(optional) stop criteria for ML search']),
  Returns( TreeResult ),
  Synopsis('RAxML is a tool to compute maximum likelihood trees from multiple sequence
alignments. For details see manual (Reference section).'),
'',
Paragraph(-2, '  Available substitution models:'),
Paragraph(-18,'    <default>     GONNET matrices'),
Paragraph(-18,'    subst=string  GONNET, JTT, DAYHOFF, WAG, BLOSUM62, 
MTREV, RTREV, CPREV, MTMAM, VT (all Protein) or GTR (DNA)'),
Paragraph(-2, '  Available model modifiers:'),
Paragraph(-26,'    inv_sites=boolean           estimate proportion 
of invariant sites. Default=false'),
Paragraph(-26,'    estimate_basefreqs=boolean  estimate the base 
frequences from the data, otherwise use fixed frequencies from the 
model. Default=false'),
Paragraph(-26,'    rates=string          choice of rates implementation. 
Available are ''CAT'', ''GAMMA'' and ''MIX''. ''CAT'' classifies each 
site into a fixed rate category. Likelihoods between different topologies 
are not comparable and thus, the method is only available in combination 
with ''nr_runs''=1. ''GAMMA'' uses 4 discrete rate categories according to a 
gamma distribution and estimates the alpha parameter. The ''MIX'' searches
for a good topology using the ''CAT'' model and switches afterwards to the 
''GAMMA'' model to compute stable likelihoods. default=''MIX''.'),
Paragraph(-2, '  Parameters determine exhaustiveness of reconstruction:'),
Paragraph(-26,'    nr_runs=posint        determines the number of ML tree 
searches on the original multiple sequence alignment. default=10'),
Paragraph(-26,'    bootstrap={0,posint}  determines the amount of bootstrap 
samples to be evaluated. Default=0'),
Paragraph(-26,'    start_tree={Tree,''MP'',''random''} specifies the start 
topology for the ML search. ''MP'' uses for each run a different maximum 
parsimony tree and ''random'' starts with a random topology. Alternatively,
you can pass a starting topology. Default=''MP'''),
Paragraph(-26,'    eps=positive          ML search will be stopped if the likelihood 
increased by less than ''eps''. Default=0.1'),
Paragraph(-2, '  Other parameters:'),
Paragraph(-23,'    threaded=integer   specifies the number of threads. 
If set to <= 1, the sequential program is used. Default=1.'),

  References('Alexandros Stamatakis. RAxML-VI-HPC: Maximum Likelihood-based Phylogenetic
Analyses with Thousands of Taxa and Mixed Models, Bioinformatics 22(21):2688-2690, 2006',
'Source code and Manual: http://icwww.epfl.ch/~stamatak/index-Dateien/Page443.htm'),
  Examples( Fake('msa := Rand(MAlignment):',''), 
        Fake('RAxML(msa, ''nr_runs''=2,''bootstrap''=100,''inv_sites''=true)',
'TreeResult(Tree(Tree(Leaf(RandSeq9,0.2961),0,Tree(Leaf(RandSeq6,0.2228),0.2127,
Tree(Tree(Leaf(RandSeq2,0.4692),0.4692,Leaf(RandSeq4,0.6664),73),0.4559,Tree(
Tree(Leaf(RandSeq8,1.3377),0.9953,Leaf(RandSeq5,1.0007),100),0.7236,Tree(Leaf(
RandSeq1,0.7442),0.7398,Tree(Leaf(RandSeq10,1.5340),1.0507,Leaf(RandSeq3,1.0612)
,100),95),100),100),100)),0,Leaf(RandSeq7,1.0473e-06)),ML,table([{[Likelihood, [
-3120.6126]]}, {}, {}, {[InvSites, [0.00011700]]}, {}, {[SubstModel, [GONNET]]},
{[CPUtime, [21.6900]]}, {}, {[Method, [RAxML]]}, {[Alpha, [1000.0997]]}, {}, {},
{}],unassigned))')),
  SeeAlso( Tree, PhylogeneticTree, LeastSquaresTree, MAlign, MafftMSA, 
RobinsonFoulds, TreeResult )
):

TreeResult_Description := Description(
  structure( TreeResult ),
  Summary( 'the result of a tree reconstrution call' ),
  CallingSequence( noeval( TreeResult( Tree, Type, Other) )),
  Parameters(
    [Tree,Tree,'the maximum likelihood tree'],
    [Type,string,'type of reconstruction (ML/Distance/Parsimony/Other)'],
    [Name,string,'(opt) arbitrary name to identify the tree'],
    [Likelihood,numeric,'(opt) log(Likelihood) for ML trees'],
    [Alpha, numeric,'(opt) alpha parameter of Gamma correction'],
    [InvSites,numeric,'(opt) invariant sites'],
    [BaseFreqs, list(numeric), '(opt) base frequencies'],
    [SubstModel,string, '(opt) substitution model'],
    [Method, string,'(opt) name of the function used to build the tree'],
    [CPUtime, numeric,'(opt) seconds use to build the tree'],
    [LSError, nonnegative,'(opt) Weighted branch length errors (Distance)'],
    [CharChanges, integer,'(opt) Number of character changes needed 
    (Parsimony)'],
    [LnLperSite, list(numeric), '(opt) List of loglikelihood values per site']),
  Synopsis('A TreeResult stores the result of a maximum likelihood tree 
reconstrution. Parameters, that have not been estimated are unassigned.'),
  SeeAlso( RAxML, PhyML, Tree, RellTree )
):

RellTree_Description := Description(
  function( RellTree ),
  Summary( 'does RELL on a TreeResult' ),
  CallingSequence( noeval( RellTree( TreeResult, nrOfBootstraps) )),
  Parameters(
    [TreeResult,TreeResult,'the TreeResult object in question'],
    [nrOfBootstraps, posint, '(opt) desired number of bootstrap values']),
  Synopsis('Applies RELL (resamplling of estimated log likelihood values) on a 
  TreeResult object that contains log likelihoods per site (e.g. from a phyml 
  run). See Kishino et al., MBE 1990, for more information.'),
  SeeAlso( PhyML, Tree )
):

Rank_Description := Description(
  function( Rank ),
  Summary('Computes sample ranks'),
  CallingSequence( noeval(Rank( l )), noeval(Rank(l,p)) ),
  Parameters( ['l', list, 'a list of values'],
              ['p', {procedure}, '(optianal) ordering procedure'] ),
  Returns( list ),
  Synopsis( 'This function returns the sample ranks of a list of values. 
Ties (i.e. equal values) are replaced by the average rank of them.'),
  Examples( 'Rank( [4,6,1,5,6,9,1,3,3] )',
            'Rank( [4,6,1,5,6,9,1,3,3], x->-x)'),
  SeeAlso( sum, avg, var, std, cor, sort )
):

cor_Description := Description(
  function( cor ),
  Summary('an unbiased correlation estimate'),
  CallingSequence( noeval(cor(x)), noeval(cor(x,y,method)) ),
  Parameters( [x, {list,matrix}, 'a numeric matrix or list'],
              [y, {list,matrix}, '(optional) a numeric matrix or list'],
              [method, string, '(optional) choice of coefficient'] ),
  Returns( {numeric, matrix(numeric)} ),
  Synopsis( 'This function computes the correlation of ''x'' and ''y'' 
if these are lists. If ''x'' and ''y'' are a matrix, the correlations 
between the columns of ''x'' and the columns of ''y'' are computed. 
The default of y, (i.e. ''y=NULL'') is equivalent to ''y=x'', but more
efficient. The optional string argument ''method'' indicates which 
correlation coefficient is computed.'),
'',
Paragraph(-2, '  Available correlation coefficients:'),
Paragraph(-20,'    <default>     pearson correlation coefficient'),
Paragraph(-20,'    pearson       pearson correlation coefficient'),
Paragraph(-20,'    spearman      spearman''s rank correlation coefficient'),
Paragraph(-20,'    kendall       kendall''s tau correlation coefficient'),
Paragraph(-2, '  If method is ''kendall'' or ''spearman'', Kendall''s
  tau or Spearman''s rho statistic is used to estimate a rank-based
  measure of association.  These are more robust and have been
  recommended if the data do not necessarily come from a bivariate
  normal distribution. Note that ''spearman'' basically
  computes ''cor(R(x), R(y))'' where ''R(u) := Rank(u)'''),

  Examples( 'cor([1,5,8,4], [6,2,8,9])',
            'cor([[1,4],[2,4],[2,2],[6,1],[7,-5]], ''spearman'')' ),
  SeeAlso( Covariance, var, avg, Rank, std, sum, StatTest )
):

RedoCompletion_Description := Description(
    function( RedoCompletion ),
    Summary('Rewrite the file listing commands for shell autocompletion'),
    CallingSequence( noeval(RedoCompletion()) ),
    Returns( NULL ),
    Synopsis('This function rewrites the file "cmds" in the library with
    the list of all function defined in the current session (for this
    purpose, it uses the function names())'),
    SeeAlso( names, noeval(libname) )
):

MySql_Description := Description(
  function(MySql),
  Summary('Wrapper for MySQL client'),
  CallingSequence( noeval(MySql(query)) ),
  Parameters(['query',string,'The MySQL query to be executed.'],
             ['setParseColumns',{list(posint),set(posint)},'(optional) columns to parse'],
             ['host','host=string','(optional) URL of the MySQL server'],
             ['user','user=string','(optional) the MySQL username to use when connecting'],
             ['password','password=string','(optional) the password to use when connecting'],
             ['port','port=integer','(optional) the TCP/IP port number to use for the connection'],
             ['database','database=string','(optional) the name of the database to use']),
  Returns( MySqlResult ),
  Synopsis('The MySql function can be used to access any MySQL database. 
The passed query in sql format is executed on the (remote) server and 
the result is returned to the user.'), 
'',
Paragraph(-2, '  Optional arguments and their default values:'),
Paragraph(-21,'    setParseColumns  A list/set of integer to indicate
which columns should be parsed. Unparsed columns appear as strings in
the result. By default, no columns are parsed.'),
Paragraph(-21,'    host=string      The URL where the MySQL server is
running. The default is ''linneus54.inf.ethz.ch''.'), 
Paragraph(-21,'    user=string      The username to be used when 
connecting to the server. The default username is ''darwin''.'), 
Paragraph(-21,'    password=string  The password to be used when 
connecting to the server. By default, no password is used.'), 
Paragraph(-21,'    port=string      The TCP/IP port number of the 
server. If no port number is provided, the default MySQL port is used.'), 
Paragraph(-21,'    database=string  The name of the database to use.  
The default database is ''vpeikert'' if the host is linneus54, otherwise no database is selected.'), 
  
  Examples( Fake('MySql(''Select genome_5letter, entry_nr, entry_seq from 
  genome, entry where entry_id IN (44,45) and entry_genome_id=genome_id''):',
'MySqlResult([genome_5letter, entry_nr, entry_seq],[[BACSU, 44, 
MAKTLSDIKRSLDGNLGKRLTLKANGGRRKTIERSGILAETYPSVFVIQLDQDENSFERVSYSYADILTETVELTFNDDAASSVAF], 
[BACSU,  45, MGRRRGVMSDEFKYELAKDLGFYDTVKNGGWGEIRARDAGNMVKRAIEIAEQQMAQNQNNR]])'),
  Fake('MySql(''Select * from oma where oma_id=9233'', database=''oma_sep08'')',
'MySqlResult([oma_id, oma_entry_id],[[9233, 1039323], [9233, 1107833], [9233,
2057091], [9233, 2201433]])') ), 
  SeeAlso( ReadRawFile, OpenReading, OpenPipe, MySqlResult )
):

MySqlResult_Description := Description(
  structure( MySqlResult ),
  Summary( 'the result of a MySql function call' ),
  CallingSequence( noeval( MySqlResult(ColumnLabels, Data) )),
  Parameters(
    [ColumnLabels,list(string),'the labels of each column'],
    [Data,matrix,'the two dimensional data matrix']) ,
  Synopsis('A MySqlResult structure stores the result of a MySql 
query. The data of a column can be retreived using the column label
as the selector on the MySqlResult structure.'),
Examples( Fake('x := MySql(''Select * from oma where oma_id=9233'', database=''oma_sep08''):', 
'MySqlResult([oma_id, oma_entry_id],[[9233, 1039323], [9233, 1107833], [9233,
2057091], [9233, 2201433]])'),
Hide('x := MySqlResult([oma_id, oma_entry_id],[[9233, 1039323], [9233, 1107833], [9233
, 2057091], [9233, 2201433]])'),
'x[''Data'']', 'x[''oma_entry_id'']', 
Unassign('x') ),
  SeeAlso( MySql )
):

WriteSeqXML_Description := Description(
  function(WriteSeqXML),
  Summary('Writes a genome database into a SeqXML formatted file.'),
  CallingSequence( noeval(WriteSeqXML('f'))),
  Parameters(['f', string, 'path to output file'],
             ['db', {string,database},'(optional) path to database file / database handle']),
  Returns( NULL ),
  Synopsis('The function WriteSeqXML stores a genome database in SeqXML format. If no ''db'' argument is passed the database currently assigned to DB is used.'),
  SeeAlso( WriteFasta )
):

BirthDeathTree_Description := Description(
  function(BirthDeathTree),
  Summary('Generates a tree from a birth-death process'),
  CallingSequence( noeval(BirthDeathTree(lambda, mu, N, h))),
  Parameters(['lambda', nonnegative, 'birth rate'],
             ['mu', nonnegative, 'death rate'], 
             ['N',posint, 'number of leaves'],
             ['h', positive, 'distance from root to leaves'] ),
  Returns(Tree),
  Synopsis('The function BirthDeathTree generates a tree with N leaves. The time points of the 
bifurcations are sampled from a birth-death process with birth rate lambda and death 
rate mu over a time span h.'),
  Paragraph(-2,'Note: - The resulting tree is ultrametric.'),
  Paragraph(6,'- For mu > 0 the root will usually not be at time 0.'),
  
  References('Gernhard T. The conditioned reconstructed process. J Theor Biol, 2008, 253(4):769-768'),
  
  Examples( 'BDTree := BirthDeathTree(0.1, 0.01, 10, 100)', Unassign('BDTree') ),
  SeeAlso( Tree, ScaleTree, AddDeviation )
):

ScaleTree_Description := Description(
  function(ScaleTree),
  Summary('Scales a tree to a specific height.'),
  CallingSequence( noeval(ScaleTree(t, h))),
  Parameters(['t', Tree, 'tree to be scaled'],
             ['h', positive, 'new distance from root to leaves'] ),
  Returns(Tree),
  Synopsis('The function ScaleTree scales a tree to a given height. If the tree is not ultrametric, 
the distance from the root to the deepest leaf is scaled. The root of the returned tree 
is always at height/time 0.'),
    
  Examples( 'BDTree := BirthDeathTree(0.1, 0.01, 10, 50)', 'ScaledTree := ScaleTree(BDTree, 100)', Unassign('BDTree', 'ScaledTree') ),
  SeeAlso( Tree, BirthDeathTree, AddDeviation )
):

AddDeviation_Description := Description(
  function(AddDeviation),
  Summary('Perturbs the length of the outer branches of a tree.'),
  CallingSequence( noeval(AddDeviation(t))),
  Parameters(['t', Tree, 'tree']),
  Returns(Tree),
  Synopsis('The function AddDeviation perturbs the lenghts of the outer branches of a tree by scaling it by a exponentially distributed factor, thus removing ultrametricity.'),
    
  Examples( 'BDTree := BirthDeathTree(0.1, 0.01, 10, 50)', 'newTree := AddDeviation(BDTree)', Unassign('BDTree', 'newTree') ),
  SeeAlso( Tree, BirthDeathTree, ScaleTree )
):

LoadMatrixFile_Description := Description(
  function(LoadMatrixFile),
  Summary('Loads a substitution rate matrix and character frequencies from a file.'),
  CallingSequence( noeval(LoadMatrixFile(f))),
  Parameters(['f', string, 'path to file']),
  Returns([Q,freq]),
  Synopsis('The function LoadMatrixFile reads a matrix file in PAML compatible format. It computes the substitution rate matrix and returns it, together with the character frequency vector.'),
  Paragraph(-2, 'It is assumed that the order of amino acids and codons is always the same and the matrix is re-ordered to correspond to the order used by Darwin.'),
    
  Examples( Fake('LoadMatrixFile(''matrices/wag.dat'')','') ),
  SeeAlso( )
):

CreateCodonModelMatrices_Description := Description(
  function(CreateCodonModelMatrices),
  Summary('Creates a set of CodonPAM1 matrices according to the M-series codon models.'),
  CallingSequence( noeval(CreateCodonModelMatrices(model, freq, kappa, w)), noeval(CreateCodonModelMatrices(model, freq, kappa, w, props)), noeval(CreateCodonModelMatrices(model, freq, kappa, w, props, p, q))),
  Parameters(['model', {'M0','M2','M3','M8'}, 'type of substitution model'],
             ['freq', list(nonnegative), 'frequency vector'],
             ['kappa', nonnegative, 'transition/transversion ratio'],
             ['w', {nonnegative, set(nonnegative)}, 'dN/dS ratio(s)'],
             ['props', {nonnegative, list(nonnegative)}, '(for model <> M0) proportion(s)'],
             ['p', positive, '(for M8) p parameter of Beta distribution'],
             ['q', positive, '(for M8) q parameter of Beta distribution'] ),
  Returns(list(matrix)),
  Synopsis('The function CreateCodonModelMatrices creates a set of codon substitution matrices according to the M-series codon models  M0, M1/2, M3, M7/8 by Yang.'),
  Paragraph(-2, 'To create matrices for M1 using M2, set w to 1; to create matrices for M7 using M8, set props to 0 and only use elements 1..10 of the list returned by the function.'),
    
  Examples( ),
  SeeAlso( CreateParametricQMatrix )
):

CreateParametricQMatrix_Description := Description(
  function(CreateParametricQMatrix),
  Summary('Creates a rate matrix from a frequency vector, Ts/Tv and dN/dS.'),
  CallingSequence( noeval(CreateParametricQMatrix(f, k, w))),
  Parameters(['f', list(nonnegative), 'frequency vector'],
             ['k', nonnegative, 'transition/transversion ratio'],
             ['w', nonnegative, 'dN/dS ratio'] ),
  Returns(matrix),
  Synopsis('The function CreateParametricQMatrix creates a rate matrix Q from the frequencies and given kappa and w (omega) parameters.'),
    
  Examples(  ),
  SeeAlso( CreateCodonModelMatrices )
):

ClustalMSA_Description := Description(
  function(ClustalMSA),
  Summary('Multiple sequence alignment using clustalw2'),
  CallingSequence( noeval(ClustalMSA(seqs, {optional_args})) ),
  Parameters(
    ['GENERAL SETTINGS',NULL, ''],
    ['seqs',list(string),'sequences to align'],
    ['labels',list(string),'(opt) sequence labels'],
    ['bootstrap',numeric,'(opt) nr. of bootstraps'],
    ['quicktree',boolean,'(opt) FAST algo for guide tree?'],
    ['seqtype',string,'(opt) type of sequence'],
    ['tmpdir',string,'(opt) dir for tempfiles'],
    ['',NULL, ''],
    ['FAST PAIRWISE AL.',NULL, ''],
    ['ktuple',numeric,'(opt) word size'],
    ['topdiags',numeric,'(opt) nr. of best diag.'],
    ['window',numeric,'(opt) window around best diag.'],
    ['pairgap',numeric,'(opt) gap penalty'],
    ['',NULL, ''],
    ['SLOW PAIRWISE AL.',NULL, ''],
    ['pwmatrix',{DayMatrix, CodonMatrix, string},'(opt) protein weight matrix'],
   ['pwgapopen',numeric,'(opt) gap open penalty'],
   ['pwgapext',numeric,'(opt) gap ext. penalty'],
   ['',NULL, ''],
   ['MULTIPLE AL.',NULL, ''],
    ['msamatrix',{string, DayMatrix, CodonMatrix},'(opt) protein weight matrix'],
    ['gapopen',numeric,'(opt) gap opening penalty'],
    ['gapext',numeric,'(opt) gap ext. penalty'],
    ['endgaps',boolean,'(opt) no end gap sep. penalty'],
    ['gapdist',numeric,'(opt) gap sep. penalty range'],
    ['nogap',boolean,'(opt) residue-spec. gaps off'],
    ['nohgap',boolean,'(opt) hydrophilic gaps off'],
    ['maxdiv',numeric,'(opt) % ident. for delay'],
    ['transweight',numeric,'(opt) transitions weighting'],
    ['iteration',string,'(opt) NONE, TREE or ALIGNMENT'],
    ['numiter',numeric,'(opt) max nr of iterations'],
    ['',NULL, ''],
    ['STRUCTURE AL.',NULL, ''],
    ['helixgap',numeric,'(opt) gap penalty for helix core residues'],
    ['strandgap',numeric,'(opt) gap penalty for strand core residues'],
    ['loopgap',numeric,'(opt) gap penalty for loop regions'],
    ['terminalgap',numeric,'(opt) gap penalty for structure termini'],
    ['helixendin',numeric,'(opt) nr of res. inside helix to be treated as terminal'],
    ['helixendout',numeric,'(opt) nr of res. outside helix to be treated as terminal'],
    ['strandendin',numeric,'(opt) nr of res. inside strand to be treated as terminal'],
    ['strandendout',numeric,'(opt) nr of res. outside strand to be treated as terminal']),
  Returns(MAlignment),
  Synopsis('ClustalMSA computes a multiple sequence alignment (MSA).
    If no Dayhoff or Codon matrix is passed, clustalw uses the Gonnet scoring 
    matrix. The score and upperbound score in the MAlignment data structure is 
    left undefined. The function works only in unix/linux, and assumes 
    that clustalw is available (set environment variable $Clustalw to point to binary).
    More information and source of clustalw is available at ''http://www.clustal.org/''.'),
  Paragraph(-2, '  Optional arguments and their default values:'),
  Table( gutter=5, ColAlign('l','l', 'l'),
    Row('','seqs:','true'),
    Row('','bootstrap:',1000),
    Row('','quicktree:','false'),
    Row('','seqtype:','guessed from seqs, {PROTEIN, DNA}'),
    Row('','tmpdir:','/tmp'),
    Row('','ktuple:',1),
    Row('','topdiags:',5),
    Row('','window:',5),
    Row('','pairgap:',3),
    Row('','pwmatrix:','GONNET, {DayMatrix, CodonMatrix, ''GONNET'', ''BLOSUM'', ''PAM'', ''ID''}'),
    Row('','pwgapopen:',10.0),
    Row('','pwgapext:',0.1),
    Row('','msamatrix:','GONNET, {DayMatrix, CodonMatrix, ''GONNET'', ''BLOSUM'', ''PAM'', ''ID''}'),
    Row('','gapopen:',10.0),
    Row('','gapext:',0.2),
    Row('','endgaps:',false),
    Row('','gapdist:',4),
    Row('','nogap:','false'),
    Row('','maxdiv:',30),
    Row('','transweight:',0.5),
    Row('','iteration:','NONE, {''NONE'', ''TREE'', ''ALIGNMENT''}'),
    Row('','numiter:',0),
    Row('','helixgap:',4),
    Row('','strandgap:',4),
    Row('','loopgap:',1),
    Row('','terminalgap:',2),
    Row('','helixendin:',3),
    Row('','helixendout:',0),
    Row('','strandendin:',1),
    Row('','strandendout:',1)
  ),
  Examples(
    Fake('msa := ClustalMSA([''ASDFAARA'',''ASDAVRA'',''ASFDAATA'',''ASGDAGTA''])',''),
    Fake('print(msa)',
'Multiple sequence alignment:
----------------------------
Score of the alignment: 0
Maximum possible score: 1.7976931e+308

1    ASDFAARA
2    AS_DAVRA
3    ASFDAATA
4    ASGDAGTA
')
	),
  SeeAlso( Align, Alignment, MAlign, MAlignment, MafftMSA )
):

TextBlock_Description := Description(
    structure(TextBlock),
    Summary( 'builds a named block around content' ),
    CallingSequence(
        noeval( TextBlock(blockname, content1,'...') )
    ),
    Returns( TextBlock ),
    Selectors( [blockname,string,'the name of the block'],
    [content_i,{string,structure},'the text content of the block'] ),
    Synopsis( 'A TextBlock is only meaningful in the context of a structured output format
    such as LaTeX or (X)HTML. If used in a normal print statement, TextBlock will just output
    the content parameters. If used in a LaTeXC statement, TextBlock will create an environment
    called ''blockname'' around the content.' ),
    Examples( 'b := TextBlock( ''abstract'', ''This is my funny abstract.'' )',
        Print( 'print(b)' ),
        Print( 'prints(LaTeXC(b))' ),
        Unassign('b')),
    SeeAlsoDocument
):

DocEl_Description := Description(
    structure(DocEl),
    Summary( 'Adds metainformation to some content' ),
    CallingSequence(
        noeval( DocEl(tag, content1,'...') )
    ),
    Returns( DocEl ),
    Selectors( [tag,string,'the tag added to the content'],
    [content_i,{string,structure},'the content of the element'] ),
    Synopsis( 'DocEl is only meaningful in the context of a structured output format
    such as LaTeX or (X)HTML. If used in a normal print statement, DocEl will just output
    the content parameters. If used in a LaTeXC statement, DocEl will wrap the content in a
    latex tag.' ),
    Examples( 'd := DocEl( ''author'', ''John Doe'' )',
        Print( 'print(d)' ),
        Print( 'prints(LaTeXC(d))' ),
        Unassign('d')),
    SeeAlsoDocument
):

RenderTemplate_Description := Description(
  function(RenderTemplate),
  Summary( 'Substitutes placeholders in template file with user variables' ),
  CallingSequence(noeval(RenderTemplate(file, tab))),
  Parameters([file,string,'filename of template'],
              [tab,table,'substitution table']),
  Returns(string),
  Synopsis('Return the content of the template file with substituted placeholders. Three different placeholders are supported in the template file: 1) ''<DVAR name="XXX">'', where the whole tag gets replaced by the value in the substitution table. 2) ''<DBOOL name="XXX"> ... </DBOOL>'', where ... is ignored if the variable XXX is false and inserted if it is true respectively. 3) ''<DLOOP name="XXX">...</DLOOP>'' indicates a loop section, where ''<DLVAR name="YYY">'' occurrences are replaced with the appropriate values from tab[XXX,i,YYY], for all possible i. In this case, the value of tab[XXX] needs to be a list of tables.'),
  SeeAlso(string,ConcatStrings,trim,op(SeeAlsoDocument))
):

ReadPhylip_Description := Description( function(ReadPhylip),
  CallingSequence( noeval(ReadPhylip(fname)) ),
  Parameters( ['fname', 'a file name']),
  Returns( list ),
  Synopsis('ReadPhylip opens the file indicated by fname, assumes that
  it is an MSA in PHYLIP format and parses its content. The return value
  consists of a list containing a list of sequences plus a list of corresponding
  labels.'),
  Examples(Fake('ReadPhylip(''myphylipfile.phy'')','') ),
  SeeAlso( OpenAppending, OpenPipe, ReadBrk, ReadDb, ReadFasta,
	ReadDssp, ReadLibrary, ReadLine, OpenReading, ReadMap,
	ReadMsa, ReadPhylip, ReadOffsetLine, ReadPima, ReadPir, ReadProgram,
	ReadRawFile, LockFile, FileStat, OpenWriting, MySql)
):

KHTest_Description := Description(
  function( KHTest ),
  Summary('Runs KH test on two tree topologies over a MAlignment.'),
  CallingSequence( noeval(KHTest(msa, t1, t2))),
  Parameters(['msa', MAlignment, 'Multiple sequence alignment'],
             ['t1', Tree, 'First tree'],
	     ['t2', Tree, 'Second tree'],
             ['method', string, '(optional) BS; RELL; CONV (default)'],
             ['subst', string, '(optional) Substitution model for PhyML (LG)'],
             ['nrOfBootraps', posint, '(optional) Number of bootstraps (100)'],
             ['sigLevel', numeric, '(optional) Significance level'] ),
  Returns( boolean ),
  Synopsis('Run KH test on two tree topologies over a MAlignment and return whether the null 
hypothesis is rejected or not. Tree topologies are kept fixed during resampling. KHTest
returns true if null hypothesis is rejected, false otherwise. PhyML is employed to do
likelihood maximization and must be installed in order to use this function. KHTest uses either 
a convolution (default), RELL or bootstrap.'),
  References('Goldman N., Anderson J.P., Rodrigo A.G. Likelihood-Based Tests of Topologies in Phylogenetics, Systematic Biology, 49:652-670, 2000'),
  Examples(Fake('ReadProgram(''datasets/quartet1/trees.drw'');',''),
            Fake('msa := ReadFastaIntoMAlignment(''datasets/quartet1/MSA_1.fa'');',''),
            Fake('lprint(''BootStrap'', KHTest(msa,tree1,tree2,method=''BS''));',''),
            Fake('lprint(''RELL'', KHTest(msa,tree1,tree2,method=''RELL''));','')
  )
):

MLTopoTest_Description := Description(
  function( MLTopoTest ),
  Summary('Run KH test on an prespecified tree and ML tree over a MAlignment and return whether the null hypothesis is rejected or not.'),
  CallingSequence( noeval(MLTopoTest(msa, t1))),
  Parameters(['msa', MAlignment, 'Multiple sequence alignment'],
             ['t1', Tree, 'Input tree'],
             ['subst', string, '(optional) Substitution model for PhyML (LG)'],
             ['nrOfBootraps', posint, '(optional) Number of bootstraps (100)'],
             ['sigLevel', numeric, '(optional) Significance level'] ),
  Returns( boolean ),
  Synopsis('Run KH test on an apriori tree and the ML tree over a MAlignment and return whether the null  
hypothesis is rejected or not. MLTopoTest
returns true if null hypothesis is rejected, false otherwise. PhyML is employed to do 
likelihood maximization and must be installed in order to use this function.'),
  References('Goldman N., Anderson J.P., Rodrigo A.G. Likelihood-Based Tests of Topologies in Phylogenetics, Systematic Biology, 49:652-670, 2000'),
  Examples(Fake('ReadProgram(''datasets/quartet1/trees.drw'');', ''),
           Fake('msa := ReadFastaIntoMAlignment(''datasets/quartet1/MSA_1.fa'');', ''),
           Fake('lprint(''ML KH test'', MLTest(msa,tree1));','')
  )
):

LinearProgramming_Description := Description(
  function( LinearProgramming ),
  Summary('Solves a linear optimization problem'),
  CallingSequence( noeval(LinearProgramming(A, b, c))),
  Parameters(['A', matrix(numeric), 'Matrix of LHS coefficients'],
             ['b',list(numeric),'Vector of RHS coefficients'],
             ['c',{list(numeric),'Feasibility'},'Vector of coefficients for objective function']
  ),
  Returns( [[list(numeric),set(posint)],'where the first element is the solution and the second is the set of indices to rows of A which define the corner x'],
           [SimplexHasNoSolution,'when there is no solution'],
           [SimplexIsSingular,'when it cannot find a subset of rows from A which is non-singular'],
           [UnboundedSolution(x,d),'where x + h*d, is a solution for any h>=0 and c*(x+h*d) grows unboundedly']
  ),
  Synopsis('LinearProgramming( A, b, c ) solves the problem of finding a vector x such that Ax >= b and c*x is maximum.' ),
  Paragraph('This is the unconstrained problem, the variables in x can
             be positive or negative, for the classical problem, x >= 0,
             these conditions have to be stated explicitly.',0),
  Paragraph('If c is ''Feasibility'' LinearProgramming will only attempt
             to find a feasible solution, which is returned and do no
             optimization. This saves computation.',0),
  Examples(Fake('A := [[-1, -1.5000], [-2, -1], [1, 0], [0, 1]]',''),
           Fake('b := [-750, -1000, 0, 0]',''),
           Fake('c := [50, 40]',''),
           Fake('LinearProgramming(A,b,c);','')
  ),
  SeeAlso( SvdAnalysis, op(SeeAlsoLinAlg), EvolutionaryOptimization )
):

sha2_Description := Description(
  function( sha2 ),
  Summary('Computes SHA2 hash of a string'),
  CallingSequence( noeval(sha2(s)) ),
  Parameters([s,string,'string to be hashed']),
  Returns(string),
  Synopsis('This function computes the 512bit SHA2 hash value of a given string. The result is represented as a hex-formatted string'),
  Examples( 'sha2(''abc'')'),
  SeeAlso( hash )
):

TaxonomyDownload_Description  := Description(
  function(TaxonomyDownload),
  Summary('downloads the UniProt species taxonomy and converts them to a Darwin readable format'),
  CallingSequence( noeval(TaxonomyDownload()) ),
  Returns(NULL),
  Synopsis('Downloads the UniProt species taxonomy hierarchy from the UniProt webpage and converts them to Darwin tables that are stored in the file UniProtTaxonomy.drw which is located in Darwin'' data directory.'),
  SeeAlso(TaxonomyEntry, SpeciesCode, TaxonId)
):

TaxonomyEntry_Description := Description(
  structure(TaxonomyEntry),
  Summary('data structure holding TaxonomyEntry information'),
  Parameters(['id',{string,integer},'the id/name of the taxonomic level']),
  Selectors(
['Scientific Name', string, 'scientific name of level'], 
['Common Name', string, 'common name of level (or empty string)'],
['Synonym', string, 'synonym name of level (or empty string)'],
['Other names', list(string), 'list of other names of level'],
['Species code', string, 'the UniProt species identifier (or empty string)'],
['Parent', TaxonomyEntry, 'the direct parent node in the taxonomy'],
['Children',list(TaxonomyEntry),'the direct children node in the taxonomy'],
['Lineage',list(string), 'the lineage tree'],
['Lineagestring', string, 'the lineage tree as one string (''; '' separated)'],
['LineageIDs', list(integer), 'the lineage ids leading to the node as a list']),
  Synopsis('The TaxonomyEntry datastructre allows to easily access the different names, IDs and parent-/children entries. The selectors are all case insensitive. The constructor of this function accepts a taxonomic identifier, a UniProt species identifier or a scientific species name and returns the instance of the TaxonomyEntry datastructre with the desired taxonomic level.'),
  Examples( 't := TaxonomyEntry(9606)','seq(z[''sciname''], z= t[''children''])','t[''comname'']'),
  SeeAlso(TaxonomyDownload, SpeciesCode,TaxonId)
):


