fish reference 2-1web.mst.edu/~norbert/ge5471/assignments/assign 1... · fish reference 2-1 2 fish...

92
FISH REFERENCE 2-1 2 FISH REFERENCE 2.1 Introduction and Overview This section contains a detailed reference to the FISH language. Following the introduction, Sec- tion 2.2 describes the rules of the language, and how variables and functions are used. Section 2.3 explains FISH statements, and Section 2.4 describes how the FISH language links with FLAC. Pre-defined FISH variables, functions and arrays are described in Section 2.5. FISH is a programming language embedded within FLAC that enables the user to define new variables and functions. These functions may be used to extend FLAC ’s usefulness or add user- defined features. For example, new variables may be plotted or printed, special grid generators may be implemented, servo-control may be applied to a numerical test, unusual distributions of properties may be specified, and parameter studies may be automated. FISH is a “compiler” (rather than an “interpreter”). Programs entered via a FLAC data file are translated into a list of instructions (in “pseudo-code”) stored in FLAC ’s memory space; the original source program is not retained by FLAC. Whenever a FISH function is invoked, its compiled pseudo- code is executed. The use of compiled code (rather than interpreted source code) enables programs to run much faster. However, unlike a compiler, variable names and values are available for printing at any time; values may be modified by the user by using FLAC ’s SET command. FISH programs are simply embedded in a normal FLAC data file: lines following the word DEFINE are processed as a FISH function; the function terminates when the word END is encountered. Functions may invoke other functions, which may invoke others, and so on. The order in which functions are defined does not matter as long as they are all defined before they are used (e.g., invoked by a FLAC command). Since the compiled form of a FISH function is stored in FLAC ’s memory space, the SAVE command saves the function and the current values of associated variables. Section 2.6 discusses extensions to FISH for file manipulation, and Section 2.7 describes the use of socket communication to transfer data between FLAC and another Itasca code. The use of these functions requires a reasonable understanding of programming techniques and constructs; FISH can be used without reference to these extensions. FISH can also be used to implement user-written constitutive models; the procedure is described in Section 2.8. Finally, in Section 2.9, an execution-speed optimizer which can be applied to certain FISH functions is discussed. FLAC Version 6.0

Upload: others

Post on 24-Mar-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

FISH REFERENCE 2 - 1

2 FISH REFERENCE

2.1 Introduction and Overview

This section contains a detailed reference to the FISH language. Following the introduction, Sec-tion 2.2 describes the rules of the language, and how variables and functions are used. Section 2.3explains FISH statements, and Section 2.4 describes how the FISH language links with FLAC.Pre-defined FISH variables, functions and arrays are described in Section 2.5.

FISH is a programming language embedded within FLAC that enables the user to define newvariables and functions. These functions may be used to extend FLAC ’s usefulness or add user-defined features. For example, new variables may be plotted or printed, special grid generatorsmay be implemented, servo-control may be applied to a numerical test, unusual distributions ofproperties may be specified, and parameter studies may be automated.

FISH is a “compiler” (rather than an “interpreter”). Programs entered via a FLAC data file aretranslated into a list of instructions (in “pseudo-code”) stored in FLAC ’s memory space; the originalsource program is not retained by FLAC. Whenever a FISH function is invoked, its compiled pseudo-code is executed. The use of compiled code (rather than interpreted source code) enables programsto run much faster. However, unlike a compiler, variable names and values are available for printingat any time; values may be modified by the user by using FLAC ’s SET command.

FISH programs are simply embedded in a normal FLAC data file: lines following the word DEFINEare processed as a FISH function; the function terminates when the word END is encountered.Functions may invoke other functions, which may invoke others, and so on. The order in whichfunctions are defined does not matter as long as they are all defined before they are used (e.g.,invoked by a FLAC command). Since the compiled form of a FISH function is stored in FLAC ’smemory space, the SAVE command saves the function and the current values of associated variables.

Section 2.6 discusses extensions to FISH for file manipulation, and Section 2.7 describes the useof socket communication to transfer data between FLAC and another Itasca code. The use of thesefunctions requires a reasonable understanding of programming techniques and constructs; FISHcan be used without reference to these extensions.

FISH can also be used to implement user-written constitutive models; the procedure is described inSection 2.8. Finally, in Section 2.9, an execution-speed optimizer which can be applied to certainFISH functions is discussed.

FLAC Version 6.0

2 - 2 FISH in FLAC

2.2 FISH Language Rules, Variables and Functions

2.2.1 Lines

FISH programs can be embedded in a normal FLAC data file or may be entered directly from thekeyboard. Lines following the word DEFINE are taken to be statements of a FISH function; thefunction terminates when the word END is encountered. A valid line of FISH code must take oneof the following forms:

1. The line starts with a statement, such as IF, LOOP, etc. (see Section 2.3).

2. The line contains one or more names of user-defined FISH functions, separatedby spaces – e.g.,

fun 1 fun 2 fun 3

where the names correspond to functions written by the user; these functionsare executed in order. The functions need not be defined prior to their referenceon a line of FISH code (i.e., forward references are allowed).

3. The line consists of an assignment statement (i.e., the expression on the rightof the = sign is evaluated, and the value is given to the variable or functionname on the left of the = sign).

4. The line consists of a FLAC command, provided that the line is embedded in asection of FISH code delimited by the COMMAND – ENDCOMMAND statements(see Section 2.3.3).

5. The line is blank or starts with a semicolon.

FISH variables, function names and statements must be spelled out in full; they cannot be truncated,as in FLAC commands. No continuation lines are allowed; intermediate variables may be used tosplit complex expressions. FISH is “case-insensitive” by default (i.e., it makes no distinctionbetween uppercase and lowercase letters); all names are converted to lowercase letters. Spacesare significant (unlike in FORTRAN) and serve to separate variables, keywords, and so on; noembedded blanks are allowed in variable or function names. Extra spaces may be used to improvereadability (for example, by indenting loops and conditional clauses). Any characters following asemicolon ( ; ) are ignored; comments may be embedded in a FISH program by preceding themwith a semicolon. Blank lines may be embedded in a FISH program.

FLAC Version 6.0

FISH REFERENCE 2 - 3

2.2.2 Names for Functions and Variables; Potential Conflicts

Variable or function names must start with a non-number, and must not contain any of the followingsymbols:

. , * / + - ˆ = < > # ( ) [ ] @ ; ’ "

User-defined names can be any length, but they are truncated in printout and in plot captions, due toline-length limitations. In general, names may be chosen arbitrarily, although they must not be thesame as a FISH statement (see Section 2.3) or a pre-defined variable or function (see Section 2.5).There are also many other words used in FLAC input that should be avoided. The list containedin Table 2.1 shows all words that could give rise to a conflict if used to name a FISH variable orfunction. However, the potential conflict depends on the way in which the chosen name is used.For example, the word gravity could be used as a FISH variable, provided that it is simply referredto inside a FISH function; a conflict would arise only if it is necessary to use the SET command toset its value, since gravity is a valid argument to the SET command. Similarly, it may be impossibleto print the value of a FISH variable if its name is the same as a parameter for the PRINT command.The list of property names for built-in models (see PROPERTY command in Section 1.2 in theCommand Reference) should also be consulted before choosing property names for a user-writtenconstitutive model (see Section 2.8.4). If in doubt, avoid any of the names listed in Table 2.1 or forthe PROPERTY command, or contractions of the names (since FLAC allows truncation of keywordsand commands).

FLAC Version 6.0

2 - 4 FISH in FLAC

Table 2.1 List of words in FLAC and FISH that may conflict with chosen names

a3 clock ega gp copy mat inverse poro2

a4 close elastic gpp mat transpose power

abs cm max else grand max pp

acos columns end grid maxdt preparse

and command end command gwdt mechanical print

angle config end if gwtdel mem prop

anisotropic constitutive model end loop gwtime memory pslow

app pnt cos end section hbm message quit

appgw pnt cparse error hbs min r

apply crdt ev p help mindt r integrate

appth pnt creep ev tot his mode range

area crtdel ex 1, ex 2, etc. hisfile model rayleigh

array crtime exit ieb mohr-coulomb read

asin csc exp ieb pnt monchrome reset

aspect csxx f prop ierr movie restore

asxx csxy f2mod if ncontours return

asxy csyy filcolor iface ncwrite rff pnt

asyy cszz fish igp nerr rsat

aszz cycle fish msg imem nerr fish s 3dd

atan damp fix implicit new s dyn

atan2 damping flags in ngrwater s echo

att pnt datum float information nmechanical s flow

attach define flow initial not s mech

back degrad flprop int nstep s mess

baud density fmem int pnt nthermal s movie

bicoe do update fmod interface null s tens

bsxx dsxx fobl itasca nwgpp s therm

bsxy dsxy fobu izones open sat

bsyy dsyy force jerr or save

bszz dszz fos jgp out sclin

call dt fos f jzones output sclose

case dump free large p stress section

case of dy friend legend pac set

cf axi dy state fsi lff pnt palette sgn

cf creep dydt fsr limits parse sig1

cf dyn dydt gpi fstring list pfast sig2

cf ext dydt gpj ftens lmul pi sin

cf gw dynamic g2flow ln plot sm max

cf ps dytdel gen log pltangle small

cf therm dytime get mem loop pltcohesion solve

cga e p gflow lose mem pltfriction sopen

char echo gmsmul mark plttension sqrt

FLAC Version 6.0

FISH REFERENCE 2 - 5

Table 2.1 List of words in FLAC and FISH that may conflict with chosen names (cont.)

sread v nmech yacc

ss v ntherm ybody

ssi vector ydisp

ssr vga yflow

state vgp0 yforce

step vgpcnw ygrav

stop vgpcw ynwflow

str pnt viscous yreaction

string visrat ytable

structure vol strain yvel

swrite vs z copy

sxx vsi z model

sxy vsr z prop

sys vsxx zart

syy vsxy zde11

szz vsyy zde12

tab pnt vszz zde22

table water zde33

table size wbiot zdpp

tan wbulk zdrot

temperature wdens zmsmul

tenflg while stepping zporos

tension window zsub

tflow wipp zs11

thdt wk11 zs12

thermal wk12 zs22

theta wk22 zs33

thtdel write ztea

thtime x zteb

title xacc ztec

tolerance xbody zted

trac pnt xdisp ztsa

track xflow ztsb

type xforce ztsc

ubiquitous xform ztsd

ucs xgrav zvisc

udm pnt xnwflow zxbar

umul xreaction

unbal xtable

unmark xvel

urand xywrite

v ngw y

FLAC Version 6.0

2 - 6 FISH in FLAC

By default, user-defined variables represent single numbers or strings. Multi-dimensional arraysof numbers or strings may be stored if the ARRAY statement is used. Section 2.3.1 defines the wayin which arrays are created and used. At present, there is no explicit printout or input facility forarrays, but functions may be written in FISH to perform these operations. For example, the contentsof a two dimensional array (or matrix) may be initialized and printed, as shown in Example 2.1:

Example 2.1 Initializing and printing FISH arrays

def afill ; fill matrix with random numbersarray var(4,3)loop m (1,4)

loop n (1,3)var(m,n) = urand

end_loopend_loop

enddef ashow ; display contents of matrix

loop m (1,4)hed = ’ ’msg = ’ ’+string(m)loop n (1,3)

hed = hed + ’ ’+string(n)msg = msg + ’ ’+string(var(m,n))

end_loopif m = 1

dum = out(hed)end_ifdum = out(msg)

end_loopendafillashow

Upon execution, the following output is produced:

1 2 31 5.7713E-001 6.2307E-001 7.6974E-0012 8.3807E-001 3.3640E-001 8.5697E-0013 6.3214E-001 5.4165E-002 1.8227E-0014 8.5974E-001 9.2797E-001 9.6332E-001

FLAC Version 6.0

FISH REFERENCE 2 - 7

2.2.3 Scope of Variables

Variable and function names are recognized globally (as in the BASIC language), except for propertyvariables associated with user-defined constitutive models (see Section 2.8.4). As soon as a nameis mentioned in a valid FISH program line, it is thereafter recognized globally, both in FISH codeand in FLAC commands (for example, in place of a number); it also appears in the list of variablesdisplayed when the PRINT fish command is given. A variable may be given a value in one FISHfunction and used in another function or in a FLAC command. The value is retained until it ischanged. The values of all variables are also saved by the SAVE command and restored by theRESTORE command.

2.2.4 Functions: Structure, Evaluation and Calling Scheme

The only object in the FISH language that can be executed is the “function.” Functions have noarguments; communication of parameters is through the setting of variables prior to invoking thefunction. (Recall that variables have global scope.) The name of a function follows the DEFINEstatement, and its scope terminates with the END statement. The END statement also serves to returncontrol to the caller when the function is executed. (Note that the EXIT statement also returns control– see Section 2.3.2.) Consider Example 2.2, which shows function construction and use.

Example 2.2 Construction of a function

newdef xxx

aa = 2 * 3xxx = aa + bb

end

The value of xxx is changed when the function is executed. The variable aa is computed locally,but the existing value of bb is used in the computation of xxx. If values are not explicitly givento variables, they default to zero (integer). It is not necessary for a function to assign a value tothe variable corresponding to its name. The function xxx may be invoked in one of the followingways:

(1) as a single word xxx on a FISH input line;

(2) as the variable xxx in a FISH formula – e.g.,

new var = (sqrt(xxx)/5.6)ˆ4;

(3) as a single word xxx on a FLAC input line;

(4) as a symbolic replacement for a number on an input line (see Section 2.4.1);and

(5) as a parameter to the SET, PRINT or HISTORY command in FLAC.

FLAC Version 6.0

2 - 8 FISH in FLAC

A function may be referred to in another function before it is defined; the FISH compiler simplycreates a symbol at the time of first mention, and then links all references to the function when it isdefined by a DEFINE command. A function can be deleted or redefined.

Function calls may be nested to any level (i.e., functions may refer to other functions, which mayrefer to others, ad infinitum). However, recursive function calls are not allowed (i.e., execution of afunction must not invoke that same function). Example 2.3 shows a recursive function call, whichis not allowed, because the name of the defining function is used in such a way that the functionwill try to call itself. The example will produce an error on execution.

Example 2.3 A recursive function call

newdef stress_sum

stress_sum = 0.0loop i (1,izones)

stress_sum = stress_sum + sxx(i,1)end_loop

end

The same function should be coded as shown in Example 2.4:

Example 2.4 Removing recursion from the function shown in Example 2.3

newdef stress_sum

sum = 0.0loop i (1,izones)

sum = sum + sxx(i,1)end_loopstress_sum = sum

end

The difference between variables and functions is that a function is always executed wheneverits name is mentioned; a variable simply conveys its current value. However, the execution of afunction may cause other variables (as opposed to functions) to be evaluated. This effect is useful,for example, when several histories of FISH variables are required – only one function is necessaryin order to evaluate several quantities, as in Example 2.5.

FLAC Version 6.0

FISH REFERENCE 2 - 9

Example 2.5 Evaluation of variables

newdef h_var_1

h_var_1 = sxx(3,4) + fach_var_2 = syy(3,4) + fach_var_3 = sxy(3,4) + fac

end

The FLAC commands to request histories might be:

hist h var 1hist h var 2hist h var 3

The function h var 1 would be executed by FLAC ’s history logic every few steps but, as a sideeffect, the values of h var 2 and h var 3would also be computed and used as history variables.

2.2.5 Data Types

There are three data types used for FISH variables or function values:

1. Integer (exact numbers in the range −2,147,483,648 to +2,147,483,647);

2. Floating-Point (approximate numbers with about six decimal digits of precision, witha range of approximately 10−35 to 1035); and

3. String (packed sequence of any printable characters; the sequence may be any length,but it will be truncated on the printout. Strings are denoted in FISH and FLAC by asequence of characters enclosed by single quotes – e.g., ‘Have a nice day’ – notethat the use of strings in FLAC is restricted to titles and file names. See Section 2.4.1.)

A variable in FISH can change its type dynamically, depending on the type of the expression towhich it is set. To make this clear, consider the assignment statement

var1 = var2

Ifvar1 andvar2 are of different types, then two things are done: first, var1’s type is converted tovar2’s type; second, var2’s data is transferred to var1. In other languages, such as FORTRANor C, the type of var1 is not changed, although data conversion is done. By default, all variablesin FISH start their life as integers; however, a statement such as

var1 = 3.4

causes var1 to become a floating-point variable when it is executed. The current type of allvariables may be determined by giving the FLAC command PRINT fish – the types will be denotedin the printout.

FLAC Version 6.0

2 - 10 FISH in FLAC

The dynamic typing mechanism in FISH was devised to make programming easier for non-programmers. In languages such as BASIC, numbers are stored in floating-point format, which cancause difficulties when integers are needed for, say, loop counters. In FISH, the type of the variableadjusts naturally to the context in which it is used. For example, in the code fragment

n = n + 2xx = xx + 3.5

the variable n will be an integer and will be incremented by exactly 2, and the variable xx willbe a floating-point number, subject to the usual truncation error but capable of handling a muchbigger dynamic range. The rules governing type conversion in arithmetic operations are explainedin Section 2.2.6. The type of a variable is determined by the type of the object on the right-handside of an assignment statement; this applies both to FISH statements and to assignments done withthe FLAC SET command. Both types of assignment may be used to change the type of a variableaccording to the value specified, as follows:

1. An integer assignment (digits 0-9 only) will cause the variable to become aninteger (e.g., var1 = 334).

2. If the assigned number has a decimal point or an exponent denoted by “e”or “E,” then the variable will become a floating-point number (e.g., var1 =3e5; var2 = -1.2).

3. If the assignment is delimited by single quotes, the variable becomes a string,with the “value” taken to be the list of characters inside the quotes (e.g., var1= ‘Have a nice day’).

Type conversion is also done in assignments involving pre-defined variables or functions; theserules are presented in Section 2.5.

A variable’s type can be pre-assigned during the compilation phase if required: the FISH statementsINT, FLOAT and STRING cause the associated variable to be initialized to the given type. This isdiscussed in Section 2.3.1. Normally, it is unnecessary to do pre-assignment, except for variablesused in constitutive models that will be optimized (see Sections 2.8 and 2.9).

2.2.6 Arithmetic: Expressions and Type Conversions

Arithmetic follows the conventions used in most languages. The symbols

ˆ / * - +

denote exponentiation, division, multiplication, subtraction and addition, respectively, and are ap-plied in the order of precedence given. Arbitrary numbers of parentheses may be used to renderexplicit the order of evaluation; expressions within parentheses are evaluated before anything else(inner parentheses are evaluated first). As an example, FISH evaluates the following variable xxas 133:

xx = 6/3*4ˆ3+5

FLAC Version 6.0

FISH REFERENCE 2 - 11

The expression is equivalent to

xx = ( (6/3) * (4ˆ3) ) + 5

If there is any doubt about the order in which arithmetic operators are applied, then parenthesesshould be used for clarification.

If either of the two arguments in an arithmetic operation is of floating-point type, then the resultwill be floating-point. If both of the arguments are integers, then the result will be integer. It isimportant to note that the division of one integer by another causes truncation of the result (forexample, 5/2 produces the result 2, and 5/6 produces the result 0).

2.2.7 Strings

There are three main FISH intrinsic functions that are available to manipulate strings:

in(var) prints out variable var if it is a string, or the message “Input?” ifit is not, and then waits for input from the keyboard. (The returnedvalue depends on the characters that are typed. FISH tries to decodethe input first as an integer and then as a floating-point number; thereturned value will be of type int or float if a single number has beentyped in that can be decoded as integer or floating-point, respectively.The number should be the only thing on the line. However, if it isfollowed by a space, comma or parenthesis, then any other characterson the line are ignored. If the characters typed in by the user cannot beinterpreted as a single number, then the returned value will be a stringcontaining the sequence of characters. The user’s FISH function candetermine what has been returned by using the function type( ).)

out(s) prints out the message contained in s to the screen (and to the log file,if it is open). The variable s must be of type string. The returnedvalue of the function is zero if no error is detected, and 1 if there isan error in the argument (e.g., if s is not a string).

string(var) converts var to type string. If var is already of type string, then thefunction simply returns var as its value. If var is int or float, then acharacter string that corresponds to the number as it would be printedout will be returned. However, no blanks are included in the string.

One use of these functions is to control interactive input and output. Example 2.6 demonstratesthis for user-supplied input parameters for Young’s modulus and Poisson’s ratio.

FLAC Version 6.0

2 - 12 FISH in FLAC

Example 2.6 Control of interactive input

def in_defxx = in(msg+’(’+’default:’+string(default)+’):’)if type(xx) = 3

in_def = defaultelse

in_def = xxend_if

enddef moduli_data

default = 1.0e9msg=’Input Young‘s modulus ’y_mod = in_def

;default = 0.25msg=’Input Poisson‘s ratio ’p_ratio = in_defif p_ratio = 0.5 then

ii = out(’ Bulk mod is undefined at Poisson‘s ratio = 0.5’)ii = out(’ Select a different value --’)p_ratio = in_def

end_if;

s_mod = y_mod / (2.0 * (1.0 + p_ratio))b_mod = y_mod / (3.0 * (1.0 - 2.0 * p_ratio))

endmoduli_data;grid 10,10model elasticprop bulk = b_mod shear = s_modprint p_ratio y_mod b_mod s_modpauseprint bulkpauseprint shear

The only arithmetic operation that is valid for string variables is addition; as demonstrated inExample 2.6, this causes two strings to be concatenated.

It is invalid for only one argument in an arithmetic operation to be a string variable. The intrinsicfunction string( ) must be used if a number is to be included as part of a string variable (see variablexx in Example 2.6). Also, note the use of intrinsic function type( ), which identifies the type of

FLAC Version 6.0

FISH REFERENCE 2 - 13

argument (see Section 2.5.5). Further string manipulation may be performed with the intrinsicfunctions parse, pre parse and cparse, as described in Section 2.6.

2.2.8 Deleting and Redefining FISH Functions

A FISH function can be deleted or redefined. If the same name as an existing function is given on aDEFINE line, the code corresponding to the old function is first deleted (and a warning printed), andthe new code substituted. If an END immediately follows the DEFINE line, then no new functionis created (i.e., the old function is just deleted). Such a “null” function is also assumed to benonexistent, even if some declarative statements come between the DEFINE and END (e.g., float,int, etc.). The following are some notes of caution:

1. A constitutive model function cannot be deleted or redefined (since existinggrid variables would be left as orphans).

2. The variables that are used in a function still exist even if the function is deleted;only the code is deleted. Since variables are global, it is likely that they areused elsewhere. The name of a deleted function will still exist as a variable.

3. If a function is replaced by another of the same name, all calls to the old functionwill be replaced automatically by calls to the new one, as demonstrated inExample 2.7:

Example 2.7 Replacing FISH functions with the same name

def joeii = out(’ a function’)

enddef fred

joeendfred ; ... old message will appeardef joe

ii = out(’ a new function’)endfred ; ... new message will appear

If joe is deleted, however, a message will be printed on execution of fred,saying that joe is now only a variable and cannot be executed.

FLAC Version 6.0

2 - 14 FISH in FLAC

2.3 FISH Statements

There are a number of reserved words in the FISH language; they must not be used for user-defined variable or function names. The reserved words, or statements, fall into three categories,as explained below.

2.3.1 Specification Statements

The following words are normally placed at the beginning of a FISH function. They alter thecharacteristics of the function or its variables, but do not affect the flow of control within thefunction. They are only interpreted during compilation.

ARRAY var1(n1, n2 . . . ) <var2(m1, m2 . . . )> <var3(p1, p2 . . . )> . . .

This statement permits arrays of any dimension and size to be included in FISH code.

In the above specification, var1 is any valid variable name, and n1, n2 . . . areeither actual integers, or single user-defined variables (not expressions) that haveinteger values at the time the ARRAY statement is processed. There may be severalarrays specified on the same line (e.g., var2, above); the number of dimensions maybe different for each array. The ARRAY statement is a specification and is actedon during compilation, not execution (it is ignored during execution). Note thefollowing:

1. The given name may be an existing single variable. If so, it is converted to anarray and its value is lost. If the name does not already exist, it is created.

2. The given name may not be that of a function or the name of an existing array(i.e., arrays cannot be redefined).

3. The given dimensions (n1, n2, . . . ) must be positive integers or evaluate topositive integers (i.e., indices start at 1, not 0).

4. There is no limit to the number and size of the array dimensions, except memorycapacity and the maximum line length.

5. Arrays may be declared and used in optimized functions, limited as follows:

a) Only the first element of an array is checked for type; the re-maining elements are assumed to be of the same type. It is theuser’s responsibility to ensure this; otherwise, the results willbe wrong. In particular, mixed-type arrays will fail.

FLAC Version 6.0

FISH REFERENCE 2 - 15

b) An array name may be given the type int or float prior to theARRAY statement, in order to initialize all elements to the giventype: e.g.,

float abcarray abc(3,3)

If not explicitly typed, the array elements will default to inte-gers.

c) It is assumed that array indices are integers; the use of an arraywith non-integer indices will cause the FISH function to fail orgive incorrect answers.

Array variables take any type (integer, float or string), according to the same rulesgoverning single variables. They are used exactly like single variables, except thatthey are always followed by an argument (or index) list enclosed by parentheses. Inuse (as opposed to in specification), array indices may be integer expressions; e.g.,

var1 = (abc(3,nn+3,max(5,6)) + qqq) / 3.4

is a valid statement if abc is the name of a three-dimensional array. Arrays mayappear on both sides of an assignment, and arrays may be used as indices of otherarrays.

Some restrictions apply to the use of array names in FLAC command lines:

(1) the command PRINT fish prints the legend – array – if the corresponding symbolis an array;

(2) PRINTname (wherename is a FISH array name) simply prints out the maximumarray indices; and

(3) the use of a FISH array name as the source or destination for a number in theSET command is not allowed, and prompts an error message (e.g., SET grav =name, where name is a FISH array name).

CONSTITUTIVEMODEL <n>

If this statement appears at the beginning of a user-defined function, then the functionis taken to be a new constitutive model. It will be executed in exactly the same way asa built-in constitutive model (i.e., called four times (once for each subzone) for eachFLAC zone at each calculation step). There are some precise rules that apply to thestructure of a constitutive function and the variables that are available at executiontime. Section 2.8 consists of a user’s guide to the writing of constitutive models.

Synonym: CONSTITUTIVE MODEL

FLAC Version 6.0

2 - 16 FISH in FLAC

INT ivar1 ivar2 ivar3 . . .

FLOAT fvar1 fvar2 fvar3 . . .

STRING svar1 svar2 svar3 . . .

These statements initialize the types of the variable(s) that follow either to integer,floating-point or string, respectively; the variable names must be separated by spaces.Section 2.2.5 explains the three data types supported by FISH. The action of INT,FLOAT and STRING is to change the type of the associated variable immediately(and to create the variable if it does not exist). Since FISH variables are global inscope, the same variable can have its type set in several functions; in this case, thelatest declaration takes precedence. Furthermore, since a variable’s type can changedynamically, the preset type can be overwritten during execution. The main use ofthe type statements is in the optimization of constitutive model functions; otherwise,there is no real need to use the statements.

FRIEND func1 func2 . . .

The FRIEND statement should only appear in a constitutive model function. It indi-cates that all variables and code within the named function(s) are to be treated as ifthey were embedded within the body of the constitutive function. In particular, statevariables are recognized within friend functions. See Section 2.8.7 for more details.

WHILESTEPPING

If this statement appears anywhere within a user-defined function, then the function isalways executed automatically at the start of every FLAC step. The WHILESTEPPINGattribute can later be disabled with the use of the SET fishcall 0 remove command(see Section 2.4.4).

The fishcall (see the command SET fishcall) statement provides more flexibility andcontrol than the WHILESTEPPING command, and its use is preferred.

Synonym: WHILE STEPPING

FLAC Version 6.0

FISH REFERENCE 2 - 17

2.3.2 Control Statements

The following statements serve to direct the flow of control during execution of a FISH function.Their position in the function is of critical importance, unlike the specification statements describedabove.

DEFINE function-name

END The FISH program between the DEFINE and END commands is compiled and stored inFLAC ’s memory space. The compiled version of the function is executed wheneverits name is mentioned, as explained in Section 2.2.4. The function name (whichshould be chosen according to the rules in Section 2.2.2) does not need to be assigneda value in the program section that follows.

CASEOF expr

CASE n

ENDCASE The action of these control statements is similar to the FORTRAN-computed GOTO,or C’s SWITCH statement. It allows control to be passed rapidly to one of severalcode segments, depending on the value of an index. The use of the keywords isillustrated in Example 2.8.

Synonym: CASE OF END CASE

Example 2.8 Usage of the CASE construct

CASEOF expr;............ default code here

CASE i1;............ case i1 code here

CASE i2;............ case i2 code here

CASE i3;............ case i3 code here

ENDCASE

The object expr following CASEOF can be any valid algebraic expression; whenevaluated, it will be converted to an integer. The items i1, i2, i3, . . . must be integers(not symbols) in the range 0 to 255. If the value of expr equals i1, then control jumpsto the statements following the CASE i1 statement; execution then continues untilthe next CASE statement is encountered. Control then jumps to the code followingthe ENDCASE statement; there is no “fall-through” as in the C language. Similarjumps are executed if the value of expr equals i2, i3, and so on. If the value ofexpr does not equal the numbers associated with any of the CASE statements, thenany code immediately following the CASEOF statement is executed, with a jump

FLAC Version 6.0

2 - 18 FISH in FLAC

to ENDCASE when the first CASE is encountered. If the value of expr is less thanzero or greater than the greatest number associated with any of the CASEs, then anexecution error is signaled, and processing stops. The numbers n (e.g., i1, i2, i3)need not be sequential or contiguous, but no duplicate numbers may exist.

CASEOF . . . ENDCASE sections may be nested to any degree; there will be no conflictbetween CASE numbers in the different levels of nesting (e.g., several instances ofCASE 5 may appear, provided that they are all associated with different nestinglevels). The use of CASE statements allows rapid decisions to be made (muchmore quickly than for a series of IF . . . ENDIF statements). However, the penalty isthat some memory is consumed; the amount of memory depends on the maximumnumerical value associated with the CASE statements. The memory consumed isone plus the maximum CASE number in double-words (four-byte units).

IF expr1 test expr2 THEN

ELSE

ENDIF These statements allow conditional execution of FISH code segments; ELSE is op-tional and the word THEN may be omitted if desired. The item test consists of oneof the following symbols, or symbol pairs:

= # > < >= <=

The meanings are standard, except for #, which means “not equal.” The items expr1and expr2 are any valid algebraic expressions (which can involve functions, FLACvariables, etc.). If the test is true, then the statements immediately following IF areexecuted until ELSE or ENDIF is encountered. If the test is false, the statements be-tween ELSE and ENDIF are executed if the ELSE statement exists; otherwise, controljumps to the first line after ENDIF. All the given test symbols may be applied whenexpressions expr1 and expr2 evaluate to integers or floating-point values (or a mix-ture). If both expressions evaluate to strings, then only two tests are valid: = and #;all other operations are invalid for strings. Strings must match exactly for equality.

IF . . . ELSE . . . ENDIF clauses can be nested to any depth.

Synonym: END IF

EXIT This statement causes an unconditional jump to the end of the current function.

EXIT SECTION

This statement causes an unconditional jump to the end of a SECTION; FISH programsections are explained below.

FLAC Version 6.0

FISH REFERENCE 2 - 19

LOOP var (expr1, expr2)

ENDLOOP or

LOOP WHILE expr1 test expr2

ENDLOOP

The FISH program lines between LOOP and ENDLOOP are executed repeatedly untilcertain conditions are met. In the first form, which uses an integer counter, var isgiven the value of expr1 initially, and is incremented by 1 at the end of each loopexecution until it obtains the value of expr2. Note that expr1 and expr2 (which maybe arbitrary algebraic expressions) are evaluated at the start of the loop; redefinitionof their component variables within the loop has no effect on the number of loopexecutions. var is a single integer variable; it may be used in expressions within theloop (even in functions called from within the loop), and may even be redefined.

In the second form of the LOOP structure, the loop body is executed while thetest condition is true; otherwise, control passes to the next line after the ENDLOOPstatement. The form of test is identical to that described for the IF statement. Theexpressions may involve floating-point variables as well as integers; the use of stringsand pointers is also permitted under the same conditions that apply to the IF statement.

The two forms of the LOOP structure may be contrasted. In the first, the test is doneat the end of the loop (so there will be at least one pass through the loop); in thesecond, the test is done at the start of the loop (so the loop will be bypassed if thetest is false initially). Loops may be nested to any depth.

Synonym: END LOOP

SECTION

ENDSECTION

The FISH language does not have a “GO TO” statement. The SECTION constructallows control to jump forward in a controlled manner. The statements SECTION. . . ENDSECTION may enclose any number of lines of FISH code; they do not affectthe operation in any way. However, an EXIT SECTION statement within the scope ofthe section so defined will cause control to jump directly to the end of the section.Any number of these jumps may be embedded within the section. The ENDSECTIONstatement acts as a label, similar to the target of a GO TO statement in C or FOR-TRAN. The logic is cleaner, however, because control may not pass to anywhereoutside the defined section, and flow is always “downward.” Sections may not benested; there may be many sections in a function, but they must not overlap or becontained within each other.

Synonym: END SECTION

FLAC Version 6.0

2 - 20 FISH in FLAC

2.3.3 FLAC Command Execution

COMMAND

ENDCOMMAND

FLAC commands may be inserted between this pair of FISH statements; the com-mands will be interpreted when the FISH function is executed. There are a number ofrestrictions concerning the embedding of FLAC commands within a FISH function.The NEW and RESTORE commands are not permitted to be invoked from within aFISH function. The lines found between a COMMAND – ENDCOMMAND pair aresimply stored by FISH as a list of symbols; they are not checked at all, and thefunction must be executed before any errors can be detected.

A FISH function may appear within a COMMAND – ENDCOMMAND pair, and maynot contain the COMMAND – ENDCOMMAND statements. A function that containsthe WHILESTEPPING statement, or a function that is the subject of a fishcall, may notcontain the COMMAND statement.

Comment lines (starting with ;) are taken as FLAC comments, rather than FISHcomments; it may be useful to embed an explanatory message within a function, tobe printed out when the function is invoked. If the echo mode is off (SET echo = off),then any FLAC commands coming from the function are not displayed to the screenor recorded to the log file.

Synonym: END COMMAND

FLAC Version 6.0

FISH REFERENCE 2 - 21

2.4 Linkages to FLAC

2.4.1 Modified FLAC Commands

The following list contains all of the FLAC commands that refer directly to FISH variables orentities. There are many other ways in which FLAC and FISH may interact; these are described inSection 2.4.2.

CONFIG extra n

The extra keyword, given in the CONFIG command, causes space for extra gridvariables to be allocated; the value n specifies the number of extra variables. Suchvariables may be used as “scratch-pad” space by a FISH function, or may be usedto store some grid-related quantities that are later printed or plotted. The extra gridarrays are referred to in a FISH function as ex 1(i,j) . . . ex n(i,j), wheren is the number given in the CONFIG command. The extra grid variables are alwaysof the floating-point type.

HISTORY var

causes a history of the FISH variable or function to be taken during stepping. If var isa function, then it will be evaluated every time that histories are stored (controlled byHISTORY nstep command); it is not necessary to register the function with a fishcall.If var is a FISH variable, then its current value will be taken. Hence, caution shouldbe exercised when using variables (rather than functions) for histories. var may alsobe a material property name; either of a built-in model or a user-defined model. Inboth cases, the property name must be given in full, followed by the zone indices(i, j). The history may be plotted in the usual way.

HISTORY ex n (i,j)

causes a history of the extra grid variable ex n (i, j) to be taken during stepping. n isthe numerical identifier for the extra grid variable, and i, j correspond to grid indices.

INITIAL ex n value

initializes the values of the extra grid variable, number n. The var keyword may alsobe used, as explained in Section 1.2 in the Command Reference under the INITIALcommand.

MODEL var

sets the model (in a particular range of zones) to the user-defined constitutive modelvar, written as a FISH function. If the model defines new properties, then the namesof these may be given as parameters to the PROPERTY, PRINT and PLOT commands.

FLAC Version 6.0

2 - 22 FISH in FLAC

PLOT ex n <zone>

plots contours of the extra grid variable n, treating it as a scalar quantity. FLAC willassume the variable is associated with gridpoints unless the keyword zone is given,which indicates that the extra grid variable is associated with zone centroids.

PLOT ex n,m <zone>

plots vectors of the extra grid variables n and m, where n corresponds to the x-component of the vector, and m corresponds to the y-component. FLAC will assumethe variables are associated with gridpoints unless the keyword zone is given, whichindicates that the extra grid variables are associated with zone centroids.

PLOT ex n,m,l <zone>

plots tensors constructed from the extra grid variables n, m and l, where n correspondsto the xx-component of the tensor, m corresponds to the yy-component, and l tothe xy-component. (The tensor is assumed to be symmetric.) FLAC assumes thevariables are associated with gridpoints unless the keyword zone is given, whichindicates that the extra grid variables are associated with zone centroids.

PRINT var

prints out the value of the FISH variable var. var (and everything else that it calls)will be executed if it is a FISH function.

PRINT ex n <zone>

prints out the values of the extra grid variable, number n. The usual range limits maybe used, as with any other FLAC grid variable. The keyword zone inhibits printingof the last row and column (which are only used for gridpoints).

PRINT fish

prints out a list of FISH symbols and either their current values or an indication oftheir type. c m indicates a constitutive model function. Variables with names thatstart with a dollar sign ($) are not printed with the above command, but they may beprinted with the command PRINT $fish.

PRINT fishcall

prints the current associations between fishcall ID numbers and FISH functions (seeSection 2.4.4).

SET fishcall n <remove> name

The FISH function name will be called in FLAC from a location determined by thevalue of the fishcall ID number n. The currently assigned ID numbers are listed inTable 2.2. The optional keyword remove causes the FISH function to be removedfrom the list when placed before the FISH function name.

FLAC Version 6.0

FISH REFERENCE 2 - 23

SET var value

sets the value of a FISH variable var to the given value. The given number alsodetermines the type given to var, as explained in Section 2.2.5. Note that valuemay itself be a FISH variable or function name; in this case, its value and type aretransferred to var. Neither var nor value may be a FISH array name.

TITLE @str

changes the stored title (used on plots, for example) to the value of the FISH stringvariable str. Note that the variable name must be preceded by the @ sign.

Similarly, @str may appear anywhere that a file name is expected (for example, inthe commands SAVE, RESTORE, LOG and HISTORY). The FISH string stored in stris used as the file name.

2.4.2 Execution of FISH Functions

In general, FLAC and FISH operate as separate entities; FISH statements cannot be given as FLACcommands, and FLAC commands do not work directly as statements in a FISH program. However,there are many ways in which the two systems may interact; some of the more common ways arelisted:

1. Direct use of function – A FISH function is executed at the user’s request bygiving its name on an input line. Typical uses are to generate geometry, set upa particular profile of material properties, or initialize stresses in some fashion.

2. Use as a history variable – When used as the parameter to a HISTORY com-mand, a FISH function is executed at regular times throughout a run, wheneverhistories are stored.

3. Automatic execution during stepping – If a FISH function makes use of thegeneralized fishcall capability (or contains the WHILESTEPPING statement),then it is executed automatically at every step in FLAC ’s calculation cycle,or whenever a particular event occurs. (See Section 2.4.4 for a discussion onfishcall.)

4. Use of function to control a run – Since a FISH function may issue FLACcommands (via the COMMAND statement), the function can be used to “drive”FLAC in a way that is similar to that of a controlling data file. However, theuse of a FISH function to control operation is much more powerful, sinceparameters to commands may be changed by the function.

5. Use of constitutive model functions – A FISH function that can be used insteadof the built-in constitutive models may be written. This type of user-writtenmodel is integrated into FLAC ’s calculation cycle at the deepest level (seeSection 2.8 for complete details).

FLAC Version 6.0

2 - 24 FISH in FLAC

The primary way of executing a FISH function from FLAC is to give its name as FLAC input. Inthis way, FISH function names act just like regular commands in FLAC. However, no parametersmay follow the function name so given. If parameters are to be passed to the function, then theymust be set beforehand with the SET command (explained later).

There is another important link between FISH and FLAC: a FISH symbol (variable or functionname) may be substituted anywhere in a FLAC command that a number is expected. This is a verypowerful feature, because data files can be set up with symbols rather than with actual numbers.

Example 2.9 shows how a data file that is independent of the mesh density can be constructed; thesame geometry (a hole in the center of a block) can be set up for any number of elements in themesh simply by changing two numbers in the SET command.

Example 2.9 FISH function with generic mesh handling capability

newdef make_hole

right = 20.0 ; physical size of block & holetop = 20.0xcen = 12.0ycen = 10.0rad = 6.0ihole = int(iright * xcen / right)jhole = int(jtop * ycen / top)

end; --- FLAC input ---set iright=10 jtop=15 ; number of zonesmake_hole ; for this examplegrid iright, jtopgen 0,0 0,top right,top right,0model elasgen circ xcen, ycen radmodel null reg=ihole,jhole

Example 2.9 illustrates several of the points made above: the function make hole is invoked bygiving its name on a line; the parameters controlling the function are given beforehand with the SETcommand; there are no numerical values in the FLAC input (they are all replaced by symbols).

String variables may be used in a similar way, but their use is much more restricted than the use ofnumerical variables. A FISH string variable may be substituted (a) wherever a file name is required,or (b) as a parameter to the TITLE command. In these cases, the @ sign must be attached to the FISHname of the variable, so that FLAC can distinguish between a literal name and a variable standingfor a name. Example 2.10 illustrates the syntax.

FLAC Version 6.0

FISH REFERENCE 2 - 25

Example 2.10 Using string variables

newdef xxx

name1 = ’abc.log’name2 = ’This is run number ’ + string(n_run)name3 = ’abc’ + string(n_run) + ’.sav’

endset n_run = 3xxxset log = @name1title @name2save @name3

The intrinsic function string( ) is described in Sections 2.2.7 and 2.5.5; it converts a number to astring.

Another important method of using a FISH function is to control a FLAC run or a series of FLACoperations. FLAC commands are placed within a COMMAND . . . ENDCOMMAND section in thefunction. The whole section may be within a loop, and parameters may be passed to FLAC com-mands.

This approach is illustrated in Example 2.11, in which 14 complete runs are done, each with adifferent value of Poisson’s ratio. The results are summarized by a movie which displays theexaggerated grid distortion for each case in sequence.

Example 2.11 Controlling a series of FLAC runs

def seriesp_rat = -0.9loop nn (1,14)

s_mod = youngs / (2.0 * (1.0 + p_rat))b_mod = youngs / (3.0 * (1.0 - 2.0 * p_rat))t_var = ’ Poisson‘s ratio = ’ + string(p_rat)command

ini sxx = 0.0 syy = 0.0 sxy = 0.0ini xvel = 0.0 yvel 0.0 xdis = 0.0 ydis = 0.0prop shear=s_mod bulk=b_modstep 200title @t_varplot hold grid mag 800

end_commandp_rat = p_rat + 0.1

end_loop

FLAC Version 6.0

2 - 26 FISH in FLAC

endgrid 5 5mod elasprop dens=2000set grav 10fix x y j=1set youngs 1e8movie file s.mov onwindow -2 7 -2 7series

For each run (i.e., execution of the loop), all grid variables are reset and properties redefined.The title is also redefined, so that the current value of Poisson’s ratio is displayed on each plottedscreen. For successful movies, it is usually necessary to specify a fixed window and fixed scales (e.g.,magnification, vector scales or contour intervals) so that comparison between frames is meaningful.

2.4.3 Error Handling

FLAC has a built-in error-handling facility that is invoked when some part of the program detects anerror. There is a scheme for returning control to the user in an orderly fashion, no matter where theerror may have been detected. The same logic may be accessed by a user-written FISH function,by using the pre-defined scalars error, nerr, ierr and jerr (see Section 2.5.1 for a complete list ofscalars).

If a FISH function sets error to a nonzero value (e.g., 1), then the error-handling facility of FLACis invoked immediately, and a message is printed. For example, stepping and FISH processing stopas soon as error is set. The message that is printed depends on the value of nerr that is set:

nerr

0 no message

> 0 FLAC ’s internally defined message is displayed.

< 0 The value of the FISH variable fish msg is displayed if it contains a string;otherwise, nothing is printed. The FISH function that sets nerr should assigna string to fish msg, which should not be a function name. If fish msgdoes not exist as a FISH variable, then a generic message is signaled.

The value of nerr may also be tested. It will contain the last error number to be processed by FLAC.The variables ierr and jerr correspond to the grid (i, j) numbers that are displayed by some messages.If nerr is tested in an optimized function, the value of zero will always be returned.

It is important to note that execution of a FISH function is terminated immediately after the statementerror = 1 is encountered; all required assignments (e.g., setting nerr and fish msg) should bedone before setting error. Note that error can also be tested, but it always returns a value of zero.

FLAC Version 6.0

FISH REFERENCE 2 - 27

The error-handling mechanism may also be used in situations that do not involve “errors.” Forexample, stepping may be halted when a certain condition is detected, as illustrated in Example 2.12.

Example 2.12 Using the Error Handler to control a run

newdef ww

while_steppingif unbal < 1e2 then

if step > 5 thennerr = -1fish_msg=’ Unbalanced force is now: ’+string(unbal)error=1

end_ifend_if

endgrid 5 5m epro d 1000 sh 1e8 bu 2e8fix x y j=1set grav 10step 1000

The run will stop when the unbalanced force is less than the set value. Note that, in this example,the test of step is necessary because the unbalanced force is zero at the start of stepping.

2.4.4 FISHCALL

FISH functions may be called from several places in the FLAC program. The form of the commandis

SET fishcall n <remove> name

Setting a fishcall causes the FISH function name to be called from FLAC from a location determinedby the value of ID number n. Currently, the ID numbers shown in Table 2.2 are assigned (at present,they are all in the calculation cycle). The numbers indicate the position where fishcall is located inthe program. Note that ID numbers (in Table 2.2) are placed between specific components of thecalculation cycle. This indicates the stage at which the corresponding FISH function is called. Forexample, a function associated with ID 1 would be called just before the stress calculation (stressesfrom velocities); ID 4 functions would be called just after.

The ID number 0 also corresponds to functions that contain the WHILE STEPPING statement (i.e.,these functions are automatically mapped to ID 0). Any number of functions may be associatedwith the same ID number (although the order in which they are called is undefined; if the order isimportant, then one master function should be called, which then calls a series of sub-functions).

FLAC Version 6.0

2 - 28 FISH in FLAC

Also, any number of ID numbers may be associated with one FISH function. In this case, the samefunction will be invoked from several places in the host code.

Parameters may be passed to FISH functions called by using the intrinsic function FC ARG(n),where n is an argument number. The meanings of the parameters (if any) are listed in Table 2.2.

In addition to the fishcall ID numbers shown in Table 2.2, there is also a fishcall 20 which can becalled before the calculation cycle. This fishcall provides control over the convergence criterionused in the SOLVE fos command. Arguments available for this fishcall are:

fc arg(1) input: lower FOS bracket

fc arg(2) input: upper FOS bracket

fc arg(3) output: set 0 to continue, or 1 to stop solve process

There is a printout keyword fishcall (the abbreviation is fishc) that lists the current associationsbetween ID numbers and FISH functions (i.e., PRINT fishcall).

The SET fishcall command normally adds the given name to the list already associated with thegiven ID number. However, the keyword remove, placed before the FISH name, causes the FISHfunction to be removed from the list. For example,

set fishcall 2 remove xxx

will remove the association between function xxx and ID number 2. Note that a FISH functionmay be associated twice (or more) with the same ID number. In this case, it will be called twice(or more). The remove keyword will remove only one instance of the function name.

FLAC Version 6.0

FISH REFERENCE 2 - 29

Table 2.2 Assigned fishcall IDs

Location in Calculation Cycle CONFIG Mode

top of main cycle loop

fishcall 0 all modes

begin groundwater sub-loop (SET ngw = n)

fishcall 1 only for flow onflows from pressure gradients

fishcall 2 only for flow onpressure-changes at g.p. due to unbalanced flows

fishcall 3 only for flow onfree field pressure and flow calculations

particle tracking

end of groundwater sub-loop

begin mechanical sub-loop (SET nmech = n)

fishcall 4 only for CONFIG thermalthermal stress calculation

fishcall 5 only for CONFIG thermalfishcall 6 all modes

stress calculation: stresses from velocities and coordinates

fishcall 7 all modes

fishcall 8 only for CONFIG gwpore pressure generation due to mech. volume change

fishcall 9 only for CONFIG gwfishcall 10 all modes

interface calculations

fishcall 11 all modes

fishcall 12 only if structures exist

structural calculations

fishcall 13 only if structures exist

free-field calculations

IEB calculations

fishcall 14 all modes

motion calculations (velocity, coordinates from force-sums)

fishcall 15 all modes

ATTACH calculation, TRACK calculation

end of mechanical sub-loop, begin thermal sub-loop

fishcall 16 only for thermal onall thermal calculations

fishcall 17 only for thermal onend thermal sub-loop

just before large-strain update

fishcall 19 all modes

large-strain update

fishcall 18 all modes

end of main cycle loop

FLAC Version 6.0

2 - 30 FISH in FLAC

The data file in Example 2.13 illustrates the use of a fishcall. The function rotation is called justbefore the motion calculation in FLAC (ID = 14) in order to apply x- and y-velocity componentsto rotate a grid. This example tests the stress calculation in the large-strain mode; the σxx and σyy

stress components return to their initial values following a cyclic rotation of 30 degrees.

Example 2.13 Illustration of fishcall use

;--- test of stress rotation ---config extra 4g 1 1mo eldef ini_coord

loop i (1,igp)loop j(1,jgp)

ex_1(i,j)=x(i,j)ex_2(i,j)=y(i,j)ex_3(i,j)=sqrt((ex_1(i,j)-xc)ˆ2+(ex_2(i,j)-yc)ˆ2)ex_4(i,j)=atan2((x(i,j)-xc),(yc-y(i,j)))

end_loopend_loop

endset xc=0 yc=0ini_coorddef rotation

tt=tt+delta_ttheta=0.5*amplitude*(1.0-cos(2*pi*freq*tt))z_area=area(1,1)-1.0loop i (1,igp)

loop j (1,jgp)xt=xc+ex_3(i,j)*sin(ex_4(i,j)+theta*degrad)yt=yc-ex_3(i,j)*cos(ex_4(i,j)+theta*degrad)xvel(i,j)=xt-x(i,j)yvel(i,j)=yt-y(i,j)

end_loopend_loop

endset fishcall 14 rotation ; ... just before MOTIONfix x yini sxx 1set freq=1 delta_t=1e-3 amplitude=30set largepro den 1 she 300 bu 300hist nstep 2hist tthist theta

FLAC Version 6.0

FISH REFERENCE 2 - 31

hist sxx i 1 j 1hist syy i 1 j 1hist z_areadef series

loop nn (1,10)command

step 100plot grid vel stres

end_commandend_loop

endmovie file rotate.mov onwindow -1 2 -1 2seriesmovie offplot hold his 3 4 vs 1

FLAC Version 6.0

2 - 32 FISH in FLAC

2.5 Pre-defined Functions, Variables and Arrays

There are certain functions, variables and arrays that are built into FISH – the names of these entitiesmust be avoided when naming user-defined variables or functions. This section describes all pre-defined entities, except those pertaining to user-defined constitutive models (which are listed inSection 2.8). The entities are organized in the following categories: scalars (single variables), gridvariables, constitutive model variables, general intrinsic functions, table functions and variablesthat give access to FLAC ’s data structure. In some cases, an entity is listed under more than onecategory, as appropriate.

2.5.1 FLAC-Specific Scalar Variables

The variables listed in this category have a single value, and are specifically related to internal FLACdata structures or the solution process. An asterisk (*) denotes that the variable may be assigned avalue within a user-written function; otherwise, the variable’s value may only be tested, not set.

app pnt pointer to APPLY list structure (integer); see Section 2.5.7

appgw pnt pointer to the data structure representing applied groundwa-ter items (integer); see Section 2.5.7

appth pnt pointer to the data structure representing applied thermalitems (integer); see Section 2.5.7

att pnt pointer to ATTACH list structure (integer); see Section 2.5.7

cf axi axisymmetry option (CONFIG axi) = 1 if configured, else 0

cf creep creep option (CONFIG creep) = 1 if configured, else 0

cf dyn dynamic option (CONFIG dynamic) = 1 if configured, else 0

cf ext extra grid variables (CONFIG extra) returns the number ofgrid variables

cf gw groundwater option (CONFIG gwflow) = 1 if configured, else0

cf ps plane-stress option (CONFIG p stress) = 1 if configured, else0

cf therm thermal option (CONFIG thermal) = 1 if configured, else 0

cm max * only defined within a constitutive model; the model mustreturn cm max as the maximum confined modulus; see Sec-tion 2.8

FLAC Version 6.0

FISH REFERENCE 2 - 33

crtdel timestep for creep calculation (as set by the SET crdt com-mand)

crtime “creep time”

dydt gpi returns critical gridpoint i value resulting from dynamictimestep

dydt gpj returns critical gridpoint j value resulting from dynamictimestep

dytdel timestep for dynamic calculation (as set by the SET dydtcommand)

dytime “dynamic time” – real time used in a fully dynamic simula-tion

error * If error (an integer) is set by a FISH function to a nonzerovalue, then control immediately passes to FLAC ’s error pro-cessor; see Section 2.4.3. error always returns zero if it istested.

fos final value of fos

fos f current value of multiplier, F , used in SOLVE fos; see Sec-tion 2.5.1.1 for more details

gwtdel timestep for groundwater calculation (as set by SET gwdtcommand)

gwtime “groundwater time” (consolidation time)

ieb pnt pointer to IEB list structure (integer); see Section 2.5.7

ierr * zone or gridpoint number printed out in some error mes-sages (integer). It can be set or tested; see Section 2.4.3 fordetails.

igp total number of gridpoints in i-direction (integer)

int pnt pointer to interface list structure (integer); see Section 2.5.7

izones total number of zones in i-direction (integer)

jerr * zone or gridpoint number printed out in some error mes-sages (integer). It can be set or tested; see Section 2.4.3 fordetails.

jgp total number of gridpoints in j -direction (integer)

FLAC Version 6.0

2 - 34 FISH in FLAC

jzones total number of zones in j -direction (integer)

large = zero if small-strain mode is in operation; otherwise, largeis nonzero (integer)

mech ratio maximum unbalanced force ratio in grid

mode (integer) only defined within a constitutive model to denotethe type of calculation that should be done; see Section 2.8

nerr * error number that can be set or tested; see Section 2.4.3for details

nerr fish last FISH error number

s 3dd 3D damping (SET 3dd) = 1 if on, = 0 if off

s dyn dynamic calculation (SET dyn) = 1 if on, = 0 if off

s echo echo flag (SET echo) = 1 if on, = 0 if off

s flow flow calculation (SET flow) = 1 if on, = 0 if off

s imp implicit option (SET implicit) = 1 if on, = 0 if off

s log log flag (SET log) = 1 if on, = 0 if off

s mech mechanical calculation (SET mech) = 1 if on, = 0 if off

s mess message flag (SET message) = 1 if on, = 0 if off

s movie movie active (MOVIE on/off) = 1 if on, = 0 if off

sm max * only defined within a constitutive model. The model mustreturn sm max as the maximum shear modulus; see Sec-tion 2.8

step current step number (integer)

str pnt pointer to a structural element data structure (integer); seeSection 2.5.7

tab pnt pointer to TABLE list structure (integer); see Section 2.5.7

tenflg = zero if tension cutoff is to be inhibited; otherwise, tensioncutoff is allowed (integer)

thtdel timestep for thermal calculation (as set by the SET thdt com-mand)

thtime “thermal time”

FLAC Version 6.0

FISH REFERENCE 2 - 35

trac pnt pointer to TRACK list structure (integer); see Section 2.5.7

udm pnt pointer to a user-defined model list structure (integer); seeSection 2.5.7

unbal maximum unbalanced force in grid

unbflow returns unbalanced flow in fast flow mode

v ngw number of groundwater sub-steps (SET ngw) (positive inte-ger)

v nmech number of mechanical sub-steps (SET nmech) (positive in-teger)

v ntherm number of thermal sub-steps (SET ntherm) (positive integer)

wbiot Biot coefficient of effective stress. Note that this variablecorresponds to the value given in the WATER biot c com-mand.

wbulk * bulk modulus of water. Note that this variable correspondsto the value given in the WATER bulk command; the local bulkmodulus of water may be changed independently by usingthe INI fmod command. In other words, the returned valueof wbulk may have no relation to the bulk modulus used inthe grid; similarly, setting wbulk may have no effect if theINI command is subsequently used to override it.

wdens * density of water

xgrav * x-component of gravity (positive is to the right)

ygrav * y-component of gravity (positive is upward). Note thatthe STEP command must be given for gravity to take effect;body forces are computed from the given gravity componentswhen STEP is given.

There is also a group of scalar variables (not listed above) that are only for use in a user-definedconstitutive model (see Section 2.8).

FLAC Version 6.0

2 - 36 FISH in FLAC

2.5.1.1 Use of Variable fos f

The FISH scalar fos f is the current F used in the SOLVE fos calculation. fos f is only nonzeroduring cycling which is done as part of the fos solution; therefore fos f can be tested against zeroto determine whether fos is active. At the start of a fos solution, an elastic simulation is done todetermine the characteristic time for the system. During cycling in this phase, fos f has the value1 × 1020. The user-written FISH code may test for this value, to set non-failing conditions, forexample.

Note that SOLVE fos executes multiple save/restore cycles, so that a user-written FISH function willnot retain variable values between cycles. Any information to be passed between cycles can bewritten to file. See the following example, which writes successive values of F to an ASCII file.In general, a binary file can be used to speed communication between successive incarnations of auser-written FISH function.

Example 2.14 Example use of fos f

; This performs a SOLVE FOS on a simple system. After the complete; run finishes, the file RESULT.OUT contains a list of F values used; to divide material properties. This is for illustration. In a real; case, the value of F could be used to change the properties of some; user-defined object.grid 15 15model mohrprop dens 1000 she 1e8 bu 2e8 fric 30 coh 3.5e4 tens 1e10fix x y j=1set grav 10def setup ; Initialize results file ...

array arr(1)oo = open(’result.out’,1,1)arr(1) = string(0)oo = write(arr,1)oo = close

endsetupdef qqq

array arrsav(500)while_stepping ; Called on restore, for first cycle episodeif fflag = 0

fflag = 1if fos_f = 0.0 ; Only write record if solve fos active

exitendifoo = open(’result.out’,0,1) ; Read in current resultsoo = read(arr,1)

FLAC Version 6.0

FISH REFERENCE 2 - 37

nlines = parse(arr(1),1)if nlines > 0

loop n (1,nlines)oo = read(arr,1)arrsav(n) = arr(1)

endLoopendifnlines = nlines + 1oo = closeoo = open(’result.out’,1,1) ; Write out old results + new onearr(1) = string(nlines)oo = write(arr,1)if nlines > 1

loop n (1,nlines-1)arr(1) = arrsav(n)oo = write(arr,1)

endLoopendifarr(1) = string(fos_f)oo = write(arr,1)oo = close

endifendset fflag=0solve fos

The contents of RESULT.OUT are

111.0000E+201.0000E+002.0000E+001.5000E+001.2500E+001.3750E+001.4375E+001.4063E+001.3906E+001.3984E+001.3945E+00

FLAC Version 6.0

2 - 38 FISH in FLAC

2.5.2 General Scalar Variables

The variables listed in this category have a single value and are not specifically related to FLAC;they are general-purpose scalars. An asterisk (*) denotes that a variable may be assigned a valuewithin a user-written function; otherwise, the variable’s value may only be tested, not set. Thevariables listed below are of floating-point type unless declared otherwise.

clock number of hundredths-of-a-second from midnight

cycle current cycle (step) number

degrad π/180 (used to convert degrees to radians – for example,a = cos(30*degrad) gives the cosine of 30◦)

do update This “function” returns zero, but its use in an assignmentstatement causes a complete update of all grid-related quan-tities; the same update is done every ten steps in large-strainmode. Note that this operation is slow.

grand random number drawn from normal distribution, with a meanof 0.0 and standard deviation of 1.0. The mean and standarddeviation may be modified by multiplying the returned num-ber by a factor and adding an offset.

pi π

step current step (cycle) number

unbal maximum unbalanced force

urand random number drawn from uniform distribution between0.0 and 1.0

2.5.3 FLAC-Specific Model Variables

The following reserved names refer to gridpoint or zone variables that require the row and columnnumbers to be specified in parentheses immediately following the name. For example, the xx-stressin zone (i,j) would be referred to as sxx(i,j), where i and j evaluate to legal integers thatcorrespond to grid indices; an error will be signaled during execution if the indices are out of therange of the grid. Both i and j may be arbitrarily complex expressions involving functions oreven other FLAC array names. The following variable names must be spelled out in full in FISHstatements; they cannot be truncated, as in FLAC commands. An asterisk (*) denotes that thevariable (or individual bit) can be modified by a FISH function; otherwise, its value may only betested. All grid variables are of floating point type except for flags and model, which are integers,and damp, which depends on its arguments.

Zone variables evaluate to zero if the zone is null, and gridpoint variables evaluate to zero if thegridpoint is surrounded by null zones.

FLAC Version 6.0

FISH REFERENCE 2 - 39

2.5.3.1 Gridpoint Variables

damp * grid-based damping parameters. Note that damp takes athird argument, as follows: damp(i, j, code) = value orvalue = damp(i, j, code). It either sets or retrieves grid-based damping information for gridpoint (i,j), according tothe value of code, as follows:

code Description value

1 static damping local 1type (integer) combined 2

2 static damping constant (float) value

3 dynamic damping local 1type (integer) combined 2

Rayleigh 3

4 dynamic damping local and valueconstant (float) combined

5 dynamic Rayleigh fraction (float) value

6 dynamic Rayleigh frequency (float) value

7 dynamic Rayleigh full 0switch (integer) mass term only 1

stiffness only 2

All damping variables may be changed dynamically duringcycling, but for changes to Rayleigh parameters to take ef-fect, the function do update must be called, preferably afterall the grid has been scanned (the function is very time-consuming, and operates on global data).

ex n * extra (floating-point) variables, where n ranges from 1 tothe number specified on the CONFIG extra = n command

f2mod * non-wetting gridpoint fluid modulus (only for CONFIGtpflow mode)

FLAC Version 6.0

2 - 40 FISH in FLAC

flags condition flags – logical or of several bits, as follows:

* fixed in x 2* fixed in y 4null gridpoint 8structural connection 64* marked gridpoint 128attached gridpoint 256* PP fixed 512null groundwater gridpoint 1024* fixed temperature 2048null thermal gridpoint 4096absorbing boundary in x 8192absorbing boundary in y 16384* fixed saturation 65536* fixed pore pressure of the non-wetting phase 131072* fixed seepage (two-phase flow) 262144

fmod * gridpoint fluid modulus. Care should be taken if this vari-able is changed, since critical fluid timesteps will be altered,and numerical instability may occur. If in doubt, issue aSTEP command, which causes the timestep to be recom-puted.

ftens * fluid tensile strength. This is a gridpoint variable.

g2flow non-wetting gridpoint flow sum (only for CONFIG tpflowmode)

gflow gridpoint flow sum. This is the fluid flow, in volume perunit groundwater time, flowing into a gridpoint. In steady-state conditions, the flow sums will be almost zero at interiorgridpoints, since the inflow will balance the outflow. At fixedpore-pressure gridpoints, gflow will be the flow into or outof the grid (positive flow denotes “into the grid”). Note that,when in CONFIG axi mode, the flow volume is associatedwith a unit angle, which is 1 radian.

gmsmul gridpoint multiplier assigned by multi-stepping option

gpp * gridpoint pore pressure

nwgpp * non-wetting gridpoint pore pressure (only for CONFIGtpflow mode)

rsat * residual saturation (only for CONFIG tpflow mode)

FLAC Version 6.0

FISH REFERENCE 2 - 41

sat * saturation. This is a gridpoint variable which ranges from0 to 1.

temp * temperature (only for CONFIG th mode)

tflow thermal energy sum at a gridpoint. At a fixed temperaturegridpoint, a positive energy sum denotes energy entering thegrid, while a negative sum denotes energy leaving the grid.A nonzero energy sum at a free gridpoint indicates that thetemperature is unsteady at the gridpoint. A zero (or close tozero) energy sum indicates steady conditions.

vga * van Genuchten coefficient a (only for CONFIG tpflowmode)

vgp0 * van Genuchten reference pressure (only for CONFIG tpflowmode)

vgpcnw * van Genuchten non-wetting exponent (only for CONFIGtpflow mode)

vgpcw * van Genuchten wetting exponent (only for CONFIG tpflowmode)

x * x-coordinate

xacc * x-acceleration (only for CONFIG dynamic mode)

xbody x-component of body force (summation of gravity and ap-plied forces)

xdisp * x-displacement

xforce unbalanced gridpoint force in x-direction; if the gridpoint isfixed, then this force is the reaction force on the “support.”

xvel * x-velocity

y * y-coordinate

yacc * y-acceleration (only for CONFIG dynamic mode)

ybody y-component of body force (summation of gravity and ap-plied forces)

ydisp * y-displacement

yforce unbalanced gridpoint force in y-direction; if the gridpoint isfixed, then this force is the reaction force on the “support.”

yvel * y-velocity

FLAC Version 6.0

2 - 42 FISH in FLAC

2.5.3.2 Zone Variables

area zone area

Area is computed every time it is used. If it is requiredfrequently, then it should be stored locally, either as a scalar(inside a loop) or in an ex n array.

density * zone density

dy state * special indicator codes for double-yield model (see Sec-tion 2 in Theory and Background):

(1) currently at yield in shear

(2) currently at yield in volume

(4) shear yield criterion involves out-of-plane stress (doesnot mean at yield)

(8) currently at yield in tension

NOTE: The codes may be added together in the case of mul-tiple yielding; for example, both shear and volumetric yieldwould produce an indicator of (3), obtained by adding (1)for shear yield, and (2) for volumetric yield.

e plastic * accumulated plastic shear strain (only for strain-softening,double-yield and bilinear models)

et plastic * accumulated plastic tensile strain (only for strain-soften-ing, double-yield and bilinear models)

ev plastic * accumulated plastic volumetric strain (only for double-yield and Cam-clay models)

ev tot * accumulated total volumetric strain (only for Cam-claymodel)

ex n * extra (floating-point) variables, where n ranges from 1 tothe number specified on the CONFIG extra = n command

flags condition flags – logical or of several bits, as follows:

* A-B triangle pair absent 16* C-D triangle pair absent 32

inimodel causes initialization of derived model properties to be donefor zone (i, j); changes in properties will cause immediatechanges in the model response.

FLAC Version 6.0

FISH REFERENCE 2 - 43

k11 fluid mobility coefficient (only for CONFIG gw mode)

k12 fluid mobility coefficient (only for CONFIG gw mode)

k22 fluid mobility coefficient (only for CONFIG gw mode)

model constitutive model number:

1 null model

2 elastic, isotropic

3 Mohr-Coulomb

4 elastic, anisotropic

5 ubiquitous-joint

6 strain-hardening/softening

7 elastic/viscous

8 power law creep

9 WIPP creep

10 double-yield

11 modified Cam-clay

12 Drucker-Prager

13 crushed-salt viscoplastic

14 WIPP-creep viscoplastic

15 Burger-creep viscoplastic

16 bilinear strain-hardening/softeningubiquitous-joint

-100 CPP (Finn, Hoek-Brown, Cysoil and CPPUDM)models

DLL models written in C++ are identifiable by their names,accessible via z model. Note that FISH user-written consti-tutive models may also return a number (as given in the CON-STITUTIVE MODEL statement in the corresponding FISHfunction).

FLAC Version 6.0

2 - 44 FISH in FLAC

poro2 * porosity (only for CONFIG tpflow mode)

pp * zone pore pressure

state plastic state, (for all plasticity models, except Finn and Hoek-Brown models) as follows:

0 elastic

1 currently at yield in shear and/or volume

2 currently not at yield but has been in the past, eitherin shear or tension (in matrix) or volume

3 currently at yield in tension

6 ubiquitous-joints at yield in shear

7 ubiquitous-joints currently not at yield but havebeen in the past, either in shear or tension

8 ubiquitous-joints at yield in tension

sxx * xx-stress

sxy * xy-stress

syy * yy-stress

szz * zz-stress

udcoe * coefficient of volume strain in pore pressure formula (onlyfor CONFIG tpflow mode)

visrat * viscosity ratio (wet/non-wet) (only for CONFIG tpflowmode)

vol strain accumulated volumetric strain (only for CONFIG gw mode)

vsxx xx-component of stress, including stiffness-proportionalRayleigh damping term (only for dynamic analysis)

vsxy xy-component of stress, including stiffness-proportionalRayleigh damping term (only for dynamic analysis)

vsyy yy-component of stress, including stiffness-proportionalRayleigh damping term (only for dynamic analysis)

vszz zz-component of stress, including stiffness-proportionalRayleigh damping term (only for dynamic analysis)

FLAC Version 6.0

FISH REFERENCE 2 - 45

wk11 * wetting fluid mobility coefficient for full saturation (onlyfor CONFIG tpflow mode)

wk12 * wetting fluid mobility coefficient for full saturation (onlyfor CONFIG tpflow mode)

wk22 * wetting fluid mobility coefficient for full saturation (onlyfor CONFIG tpflow mode)

xflow x-component of the zone flow vector – actually, “specificdischarge” in units of velocity. This quantity is not stored byFLAC, and must be computed when needed: the calculationis time-consuming.

xnwflow x-component of non-wetting zone flow vector

yflow y-component of the zone flow vector – actually, “specificdischarge” in units of velocity. This quantity is not stored byFLAC, and must be computed when needed: the calculationis time-consuming.

ynwflow y-component of non-wetting zone flow vector

FLAC Version 6.0

2 - 46 FISH in FLAC

z group returns a string corresponding to the group name of zone(i,j ).*

z hyst returns a value corresponding to the hysteretic damping vari-ables Mt , γ1 and γ2. z hyst requires three arguments asfollows:

var = z hyst(i,j,vname)

where i,j are the zone indices and vname is a string denotingthe variable:

‘modfac’ Mt

‘e1’ γ1

‘e2’ γ2

* If the zone is not associated with a group name, then var will contain the integer zero. Thus, beforeprinting out a string, var should be tested, using the type () function: e.g.,

loop i (1, izones)loop j (1, jzones)

var = z group(i,j)if type(var) = 3

oo = out(string(i) +’,’+string(j)+’ Group = ’+var)else

oo = out(string(i)+’,’+string(j)+’ No group’)endif

endLoopendLoop

When z group(i,j) is used as the destination in an expression, the source variable is used as the groupname to be associated with the zone (i,j ). If the zone already is associated with a group name, theassociation is replaced with the new one. If the group name does not already exist, it is created. Ifthe source variable is not a valid string, nothing is done, and no error is signalled. For example:

grid 10 10model elasdef qqq

z group(2,2) = ’fred’z group(3,3) = 33

endqqq

In this case, zone (2,2) receives the group name “fred,” but zone (3,3) receives nothing. Thecommand PRINT group lists “fred” as a valid group name. A group name can be associated with azone even if the zone contains the null model.

FLAC Version 6.0

FISH REFERENCE 2 - 47

z model returns a string denoting the name of a DLL model, or theinteger zero if the zone does not contain a DLL model.

z prop * returns or assigns a property value for a DLL model. z proprequires three arguments, as follows:

var = z prop(i,j,pname)z prop(i,j,pname)

when i,j are the zone indices, and pname is a string denotingthe property name. Refer to the model description for a list ofproperty names. Note that the Finn and Hoek-Brown modelsare DLLs; their property names are listed in Section 1 in theCommand Reference.

z prop also returns the plasticity state number for the Finnand Hoek-Brown models:

num = z prop(i,j,‘state’)

num is 0, 1 or 2 as defined for the state zone variable.

zmsmul zone multiplier assigned by multi-stepping option

2.5.3.3 Strain Calculations

There are eight FISH zone “variables” (ssr, ssi, ssr3d, ssi3d, vsr, vsi, fsr, fsi) that give user-writtenfunctions access to zone strains and strain rates. Note that “shear strain rate” in this context meansthe square root of the second invariant of the deviatoric strain rate. The following four (read-only)functions return only single values for the zone identified by index i, j:

ssi(i, j) maximum shear strain increment (in the 2D plane)

ssr(i, j) maximum shear strain rate (in the 2D plane)

ssi3d(i, j) maximum shear strain increment (3D formulation)

ssr3d(i, j) maximum shear strain rate (3D formulation)

vsi(i, j) volumetric strain increment

vsr(i, j) volumetric strain rate

The following two functions provide all the tensor components, rather than invariants, providingfour components in the array arr, which the user must declare beforehand, and which must have atleast four elements (the function itself returns a zero).

fsi(i, j, arr) full strain increment tensor

fsr(i, j, arr) full strain rate tensor

FLAC Version 6.0

2 - 48 FISH in FLAC

The components in arr are ordered in the following way, according to the array index (given as thefirst number in the following table):

index 1 xx

index 2 yy

index 3 zz

index 4 xy

The computation of strain rate is identical to that performed by FLAC when it applies constitutiverelations to a zone (see Section 1.3.3.1 in Theory and Background) – i.e., strain rates are based ongridpoint velocities and the current coordinates. “Strain increments” are computed with the sameequations, but with displacements substituted for velocities. There are two potential problems withthe latter calculation. First, gridpoint displacements may be reset or changed at any time by theuser; they are not used in the calculation process. It is the user’s responsibility to ensure thatdisplacements are accumulated over a meaningful interval. Second, the strain increments are basedon the geometry at the time of measurement. If the geometry changes significantly during a large-strain simulation, the measured strain will depend on the assumption made about the reference statefor geometry; there are many different formulations for strain to be found in the literature whenlarge displacements are involved. The conscientious user may wish to use only the function fsr,and derive strain increments by accumulation, using some formula of choice.

Note that the functions described take a long time to execute. It is rather inefficient to compute thevalues for each zone at each timestep, if strains are only needed for certain zones (e.g., for histories);the recording logic should be done only for the zones of interest. Further, since each function takesabout the same time to execute, it is better to use fsr or fsi if more than one strain component isneeded for a zone.

Example 2.15 illustrates the application of these functions to calculate strain components. Notethat the arrays must be defined first. The strain increment and strain rate tensors are then calculatedand the arrays are filled with the statements

dum = fsr(i,j,ar)dum = fsi(i,j,ai)

Example 2.15 Strain calculations

;--- Test of FISH strain measures ---conf ext 10grid 5 5m epro d 1000 s 1e8 b 2e8set grav 10fix y j=1solve

FLAC Version 6.0

FISH REFERENCE 2 - 49

def qqqarray ar(4) ai(4)loop i (1,izones)

loop j (1,jzones)dum = fsr(i,j,ar)dum = fsi(i,j,ai)ex_1(i,j) = sqrt((ar(1)-ar(2))ˆ 2 + 4.0 * ar(4)ˆ 2) / 2.0ex_2(i,j) = sqrt((ai(1)-ai(2))ˆ 2 + 4.0 * ai(4)ˆ 2) / 2.0ex_3(i,j) = ar(1) + ar(2) + ar(3)ex_4(i,j) = ai(1) + ai(2) + ai(3)ex_5(i,j) = ai(1)ex_6(i,j) = ai(2)

endLoopendLoop

endqqq;--- to test, give the following commands, line by line, & compareprint ssr ex_1 zonprint ssi ex_2 zonprint vsr ex_3 zonprint vsi ex_4 zonpauseplot hold ex_6 zone fil bou

2.5.4 FLAC Constitutive Model Variables

Property values for all constitutive models may be accessed (changed, as well as tested) in anygeneral FISH function (i.e., any function that is not a constitutive model itself). As with the generalgrid variables, indices must immediately follow the name of the property, enclosed in parentheses.Property names must be spelled out in full, followed by zone indices (which may be single numbers,symbols, or complicated expressions); for example, a valid FISH statement would be

cohesion(2,3) = 3.4e5

If you write a function that tries to change a property variable, but the associated model does not existat the specified grid location (i,j), then no error will be given; however, no change will be madeto the grid. Similarly, if you try to obtain the value of a property for which no corresponding modelexists at the specified grid location, the value will be returned as zero; no error will be detected.Consult Section 1.2 in the Command Reference and Section 2 in Theory and Background forfurther information on the meanings and usage of the following variables:

FLAC Version 6.0

2 - 50 FISH in FLAC

a 1∗ cohesion especc heat† g thexp† k22 qvol

a 2∗ conductivity† et plastic gas c∗ kappa rho∗a wipp∗ con1† etj plastic hb e3plas kshear rs1∗act energy∗ con2† ev plastic hb ind lambda rs2∗alpha cptable ev tot hba lconduct† s f∗angle ctable f qx† hbmb lspec heat† s g1∗atable cy p f qy† hbs mm s k1∗b f∗ cy q f t0† hbs3cv mp1 shear current

b wipp∗ d f∗ f thexp† hbsigci mpc shear mod

b0∗ d wipp∗ ff c1‡ jangle mtable spec heat†

b1∗ d2table ff c2‡ jc2 multiplier stableb2∗ density ff c3‡ jcohesion mutable statebijoint di2 ff c4‡ jd2 mv 1 svbimatrix dilation ff count‡ jdilation mv0 temp∗biot c dilation mob ff evd‡ jf2 n 1∗ tension

bulk current dj2table ff latency‡ jfriction n 2∗ thexp†

bulk mod djtable ff switch‡ jtension n cond† tjtablec2table dtable fj2table k exx∗ n wipp∗ ttablecam p dy state fjtable k eyy∗ nuyx viscosity∗cam q e dot star∗ fr2 k ezz∗ nuzx vol strain

cap pressure e plastic frac d∗ k exy∗ per table xconduct†

citable e primary∗ friction k shear mod∗ poiss xmod

cj2table econduct† friction mob k viscosity∗ por table xyconduct†

cjtable ej plastic f2table k11 porosity yconduct†

co2 es plastic ftable k12 qdil ymod

∗available only for creep model option — see Section 1 in Creep MaterialModels†available only for thermal model option — see Section 1 in Thermal Analysis‡available only for dynamic option — see Section 1 in Dynamic Analysis

Note that properties for the Finn model are accessed with the z prop function rather than directlyby name.

In addition to the above set of names corresponding to built-in models, the properties of user-writtenmodels may be addressed in a similar manner. Again, the names must be spelled in full, and zoneindices must follow the name if the property is referred to outside of the function in which it isdefined. See Section 2.8 for a discussion on properties for user-written models. Properties of DLLmodels are set and retrieved with the z prop function (Section 2.5.3.2).

FLAC Version 6.0

FISH REFERENCE 2 - 51

2.5.5 Intrinsic Functions

All functions return floating-point values except for and, or, not, int and type, which return integers,and get mem, which returns a pointer. The functions max, min, abs and sgn return integers if theirargument(s) are all integer; otherwise, they return as floating-point. All functions must be placed onthe right-hand side of an assignment statement, even if the function’s return value is of no interest.For example,

ii = out(’ Hi there!’)

is a valid way to use the out function. In this case, ii is not used.

abs(a) absolute value of a

acos(a) arc cosine of a (result is in radians)

and(a,b) bit-wise logical and of a and b

asin(a) arc sine of a (result is in radians)

atan(a) arc-tangent of a (result is in radians)

atan2(a,b) arc-tangent of a/b (result is in radians) (NOTE: b may bezero.)

cos(a) cosine of a (a is in radians)

cparse(s, nc1, nc2) see Section 2.6

error string

This function causes an error condition. FISH function pro-cessing (and command processing) stops immediately. Themessage reported is string. This function can be used forassignment only. (string = error is not allowed.)

exp(a) exponential of a

fc arg(n) passes arguments to FISH functions where n is any FISHvariable or expression that evaluates to an integer in the range1 to 20.

float(a) converts a to a floating-point number. If it cannot be con-verted (e.g., if a is a string), then 0.0 is returned.

FLAC Version 6.0

2 - 52 FISH in FLAC

fstring(a, isig) This function works like string if isig = 0. Otherwise, thenumber of significant figures (converted to string form) forfloating-point numbers in a are set to isig. “Significant fig-ures” in this context means the number of digits after thedecimal point. The maximum for isig is 7, and the mini-mum is 1. If isig is given values outside of this range, itis truncated. The action of fstring is the same as string forinteger or string variables (i.e., isig is ignored).

get mem(nw) gets nw integers or floating point variables from FLAC ’smemory space, and returns an integer pointer to the start ofthe contiguous array of objects. See Section 2.5.6.3 for moredetails.

grand random number drawn from normal distribution: mean =0.0; standard deviation = 1.0

in(s) prints out the message contained in string variable s, and thenwaits for input from the keyboard. The returned value willbe of type int or float if a single number has been typed in thatcan be decoded as integer or floating-point, respectively. Thenumber should be the only thing on the line; however, if it isfollowed by a space, comma or parenthesis, then any othercharacters on the line are ignored. If the characters typed inby the user cannot be interpreted as a single number, thenthe returned value will be a string containing the sequenceof characters.

int(a) converts a to integer. If it cannot be converted (e.g., if a is astring), then zero is returned.

ln(a) natural logarithm of a

log(a) base-ten logarithm of a

lose mem(nw,ia) returns nw previously allocated variables to FLAC. The pa-rameter ia is the pointer of the start of the array of objects;there is no checking done to ensure that ia is a valid address.The return value is undefined. See Section 2.5.6.3 for moredetails.

max(a,b) returns maximum of a, b

min(a,b) returns minimum of a, b

not(a) bit-wise logical not of a

or(a,b) bit-wise logical inclusive or of a, b

FLAC Version 6.0

FISH REFERENCE 2 - 53

out(s) prints out the message contained in s to the screen (and tothe log file, if it is open). The variable s must be of typestring. The returned value of the function is zero if no erroris detected, and 1 if there is an error in the argument (e.g., ifs is not a string).

parse(s, i) see Section 2.6

pre parse(s, i) see Section 2.6

rez exe(s) The intrinsic function rez exe (which always returns zero)causes the command contained in the given string, s, to beexecuted. Note that COMMAND . . . END COMMAND must notbe used in a FISH function invoked within the rezoning logic(i.e., a function specified by the REZONE set method com-mand). The commands that may be executed byrez exe( ) are limited to INITIAL, GENERATE, MODEL, PROP-ERTY and APPLY. If the string cannot fit on one line of FISHcode, then it must be composed of separate concatenatedsub-strings stored as a symbol (which is then given as theargument to rez exe( ) instead of being given directly as aquoted string).

sgn(a) sign of a (returns -1 if a < 0; else, 1)

sin(a) sine of a (a is in radians)

sqrt(a) square root of a

string(a) converts a to a string. If a is already of type string, thenthe function simply returns a as its value. If a is int or float,then a character string will be returned that corresponds tothe number as it would be printed out. However, no blanksare included in the string.

tan(a) tangent of a (a is in radians)

type(e) the variable type of e is returned as an integer with value 1,2, 3, 4 or 5, according to the type of the argument: int, float,string, pointer or array, respectively.

urand random number drawn from uniform distribution between0.0 and 1.0

FLAC Version 6.0

2 - 54 FISH in FLAC

2.5.6 Special Functions – Tables, Arrays and Memory Access

The functions described in the previous section are “conventional” in the sense that they simplyreturn a value, given some parameter(s), or they are executed for some effect. In other words,they always appear on the right-hand side of any assignment statement. In contrast, the functionsdescribed in this section (except the array functions in Section 2.5.6.2) may appear on either sideof an assignment (= sign). They act partly as functions and partly as arrays.

2.5.6.1 Tables

The functions table, xtable, ytable and table size allow FISH functions to create and manipulateFLAC tables, which are indexed arrays of number pairs used in several of FLAC ’s commands andoperations. However, tables are different from arrays in other programming languages. Tables aredynamic data structures; items may be inserted and appended, and interpolation between values maybe done automatically. Consequently, the manipulation of tables by FISH is time-consuming. Usethem with caution! The action of each function depends on whether it is the source or destinationfor a given data item; hence, each function is described twice.

A table is a list of pairs of floating-point numbers, denoted for convenience as x and y, although thenumbers may stand for any variables, not necessarily coordinates. Each table entry (or (x,y) pair)also has a sequence number in the table. However, the sequence number of a given (x,y) pair maychange if a new item is inserted in the table. Sequence numbers are integers that start from 1 andgo up to the number of items in the table. Each table has a unique identification number, whichmay be any integer except zero.

There are two distinct ways that tables may be used in a FISH function. The table function behavesin the same way as the regular FLAC TABLE command (i.e., insertion and interpolation is doneautomatically). The other functions, xtable and ytable, allow items to be added or updated byreference to the sequence numbers; no interpolation or insertion is done.

y = table(n,x) The existing table n is consulted, and a y-value is foundby interpolation, corresponding to the given value of x. Thevalue of x should lie between two consecutive stored x-valuesfor the results to be meaningful. An error is signaled if tablen does not exist.

table(n,x) = y An (x,y) pair is inserted into the first appropriate place intable n (i.e., the new item is inserted between two existingitems with x-values that bracket the given x-value). The newitem is placed at the beginning of the table, or appended tothe end if the given x is lower than the lowest x or greater thanthe greatest x, respectively. The number of items in the tableis increased by one, following execution of this statement.If table n does not exist, it is created, and the given item istaken as the first entry. The given statement is equivalent tothe FLAC command TABLE n insert x y. If the given x is

FLAC Version 6.0

FISH REFERENCE 2 - 55

identical to the stored x of an (x,y) pair, then the y-value isupdated, rather than inserted.

x = xtable(n,s) The x-value of the pair of numbers that have sequence num-ber s in table n is returned. An error is signaled if table ndoes not exist, or if sequence number s does not exist.

xtable(n,s) = x The given value of x is substituted for the stored value ofx in the (x,y) pair having sequence number s, in table n.If sequence number s does not exist, then sufficient entriesare appended to table n to encompass the given sequencenumber; the given x is then installed. If the given table doesnot exist, it is created. An error is signaled if n is given aszero, or if s is given as zero or negative.

y = ytable(n,s) The action of this statement is identical to the correspondingxtable statement, except that the y-value of the (x,y) pair,rather than x, is retrieved.

ytable(n,s) = y The action of this statement is identical to the correspondingxtable statement, except that the y-value of the (x,y) pair,rather than x, is installed.

i = table size(n) The number of entries in table n is returned in value i.

Since the xtable and ytable functions can create tables of arbitrary length, they should be used withcaution. It is suggested that the table function be used in constitutive models where interpolatedvalues are needed from tables. The xtable and ytable functions are more useful when generatingtables.

The following notes may be of use for the FISH table functions:

1. In large tables, for efficiency, sequence numbers should be scanned in the di-rection of ascending numbers. FLAC keeps track of the last-accessed sequencenumber for each table; this is used to start the search for the next requestednumber. If the requested number is less than the previous one, the whole tablemay need to be searched.

2. The functions xtable and ytable, rather than table, should be used to updatevalues in an existing table. Although table will update an (x,y) pair if the givenx is identical to the stored x, there may be slight numerical errors, which canresult in insertion rather than updating.

3. In a FISH function that replaces old table values with new values, it is necessaryto create the table first, since the action of retrieving old values will producean error. A complete table may be created (and its entries all set to zero) by asingle statement, as illustrated:

FLAC Version 6.0

2 - 56 FISH in FLAC

xtable(4,100) = 0.0

If table 4 does not exist, then it is created. 100 entries are also created, eachcontaining (0.0,0.0). Subsequent statements, such as

xtable(4,32) = xtable(4,32) + 1.0ytable(4,32) = ytable(4,32) + 4.5

will update table values, but will not alter the length of the table. If the latterstatements are executed before table 4 exists, then an error will be detected.

4. Stored values (both x and y) in tables are always floating-point numbers. Givenintegers are converted to floating-point type before storing. Be careful aboutprecision!

As an example in the use of table functions, the input sequence in Example 2.16 produces a smooth-pointed, star-shaped hole in a FLAC grid.

Example 2.16 Use of table functions

g 50 50m edef star

ntab = 1npts = 100d_theta = 2.0 * pi / nptsloop n (1,npts)

z = sin(3.0*theta)ˆ4 + 1.2xtable(ntab,n) = z * cos(theta)ytable(ntab,n) = z * sin(theta)theta = theta + d_theta

end_loopendstargen -3 -3 -3 3 3 3 3 -3plot hold gridgen table 1plot hold gridmod null reg 20 20plot hold grid

FLAC Version 6.0

FISH REFERENCE 2 - 57

2.5.6.2 Special Array Functions

The following intrinsic functions are defined.

mat transpose (A, B)

returns matrix B as the transpose of matrix A. Both A and Bmust be 2D, user-defined arrays with opposite dimensions(e.g., A(5,3) and B(3,5)). The same matrix must not be usedfor both source and destination. The matrices can containany variable types. The function returns 0 or 1, denotingsuccess or failure, respectively.

mat inverse (A, B)

returns matrix B as the inverse of matrix A, where A andB are square matrices of equal size. The operation causesthe (internal) allocation of 8*N*(N+1) bytes of memory, butif called more than once, the same memory is reused. Thearithmetic is double-precision and it is assumed that all el-ements of A are floating-point numbers. (No checking isdone!) The function returns 0 or 1, denoting success or fail-ure, respectively.

Notes and cautions:

a) The functions operate on existing user-declared arrays in FISH. The numberand sizes of the array dimensions must correspond to the desired matrix oper-ation. For example, to invert a matrix, the array must be two-dimensional andsquare.

b) The matrix size is assumed to be identical to the array size. This may not bea limitation, because arrays can be declared at compile time, based on a sizecomputed from a previously executed function. Example 2.17 illustrates this.

Example 2.17 Setting array size

def xxx..nn = ...

endxxxdef set_mat

array aa(nn,nn) bb(nn,nn)end

FLAC Version 6.0

2 - 58 FISH in FLAC

Example 2.18 contains an example and validation of the matrix inversion function, mat inverse().

Example 2.18 Using the matrix inversion function

def sizenn = 20

endsizedef gg

float abc xyz xx bb totint i j nnarray abc(nn,nn) xyz(nn,nn) xx(nn) bb(nn)loop j (1,nn)

loop i (1,nn)abc(i,j) = urand ; random A coefficients

endLoopxx(j) = float(j) ; X values

endLooploop i (1,nn) ; pre-compute b = A.x

bb(i) = 0.0loop j (1,nn)

bb(i) = bb(i) + abc(i,j) * xx(j)endLoop

endLoopif mat_inverse(abc,xyz) = 1

oo = out(’ Inversion failed!’)exit

endifloop i (1,nn) ; now "solve" ... x = inv(A) . b

tot = 0.0loop j (1,nn)

tot = tot + xyz(i,j) * bb(j)endLoopprintout

endLoopenddef printout

if i > 9oo = out(’ i = ’+string(i)+’ x = ’+string(tot))

elseoo = out(’ i = ’+string(i)+’ x = ’+string(tot))

endifendopt gg

FLAC Version 6.0

FISH REFERENCE 2 - 59

gg;--- Note - x value should be (approximately) integers from 1 to nn

2.5.6.3 Special Functions to Access Memory Directly

Warning! This section is intended for experienced programmers who are familiar with the use oflinked lists. The techniques described here are powerful because they provide access to most of theinternal data in FLAC, but they are dangerous if used without full understanding.

Most of FLAC ’s data is stored in a single, one-dimensional array. A FISH program has access tothis array via imem and fmem, which act like array names for integer and floating-point numbers,respectively. Given index iad (which must be an integer), floating-point (f) or integer (i) values canbe found from

f = fmem(iad)

i = imem(iad)

Values can also be inserted in the array, as follows:

fmem(iad) = f

imem(iad) = i

These functions are potentially very dangerous, as any data can be changed in FLAC ’s main array.Only experienced programmers should use them. No checking is done to verify that iad is aninteger, so the user must be very careful. The use of these functions is explained in Section 2.5.7.

2.5.6.4 Special Functions to Communicate Parameters

In some cases (notably, when using structural piles) it is possible to replace FLAC ’s built-in logicwith the same user-defined logic embodied in a FISH function. In order to communicate parametersbetween the FISH function and FLAC ’s internal logic, the special function fc arg is provided. Thefunction may appear as the source or destination (right- or left-hand side of an expression), and isused as follows:

aa = fc arg(n)fc arg(m) = bb

The arguments n and m can be any FISH variable or expression that evaluates to an integer in the range1 to 20, inclusive (i.e., there are 20 separate parameters that can be used to pass information). Theparameters may be integers or floating-point values (but not strings). For an example applicationof fc arg, see the user-defined normal coupling-spring function, cs nfunction, described inSection 1.10.4 in Structural Elements.

FLAC Version 6.0

2 - 60 FISH in FLAC

2.5.7 Access to FLAC’s Data Structures

Warning! This section is intended for experienced programmers who are familiar with the use oflinked lists. The techniques described here are powerful because they provide access to most of theinternal data in FLAC, but they are dangerous if used without full understanding.

Most of FLAC ’s data is stored in a single, one-dimensional array. A FISH program has access to thisarray via imem and fmem (described in Section 2.5.6.3), which act like array names for integers andfloating-point numbers, respectively. Note that imem(n) and fmem(n) map into the same location inmemory; it is the responsibility of the programmer to access the correct type of data. Pointers to themain data structures are listed in Section 2.5.1. Each data structure consists of one or more linkedlists, with offsets to individual data items listed in Section 4. Memory can also be allocated froma FISH program and used to store whatever the programmer wishes. In many cases, FLAC ’s datablocks contain one or more spare words that can be used as pointers to extension arrays that canbe allocated as needed. Although tables can be used to store data, it is much faster to use allocatedmemory directly, via imem and fmem.

To illustrate the use of the concepts outlined above, let us write a FISH program (listed in Exam-ple 2.19) to record the maximum normal force that acts within an interface, and the step numberand gridpoint at which the maximum occurred. After setting up the problem, we allocate a block ofmemory to contain the recorded data, and set up a pointer to it from the interface. The logic shouldwork for any number of interfaces, although Example 2.19 only involves one interface.

Example 2.19 Accessing FLAC’s data structures

g 10 11m eprop dens 2000 sh 1e8 bu 2e8m n j=6ini x add 2.5 y add -0.9 j=7,12int 4 aside from 1,6 to 11,6 bside from 1,7 to 11,7int 4 kn 5e8 ks 2.5e8 fric 10set grav 10,5 largefix x y j=1step 1def make_list

ip = int_pntloop while ip # 0

imem (ip+1) = get_mem(3) ; get storage bufferip = imem(ip)

endloopendmake_listdef save_data

while_stepping

FLAC Version 6.0

FISH REFERENCE 2 - 61

ip = int_pntloop while ip # o ;scan interfaces

ii = imem(ip+1)loop nside (2,3) ;scan 2 sides

ispt = imem(ip+nside)loop while ispt # 0 ; scan nodes on one side

if abs(fmem(ispt+5)) > fmem(ii) thenfmem(ii) = abs(fmem(ispt+5))imem(ii+1) = isptimem(ii+2) = step

end_ifispt = imem(ispt)

end_loopend_loopip = imem(ip)

end_loopenddef sho_data

ip = int_pntloop while ip # 0

ii = imem(ip+1)s1 = ’ max-Fn = ’+string(fmem(ii))+’, ’ig = imem(imem(ii+1)+2)jg = imem(imem(ii+1)+3)s2 = ’ g.p.(’+string(ig)+’,’+string(jg)+’)’s3 = ’ at step ’+string(imem(ii+2))xx = out(s1+s2+s3)ip = imem(ip)

end_loopendstep 500sho_data

The resulting output is

max-Fn = 2.6127E+05, g.p.(7,7) at step 367

FLAC Version 6.0

2 - 62 FISH in FLAC

2.6 FISH I/O Routines

The set of FISH functions described in this section enable data to be written to, and read from, afile. There are two modes, namely an “ASCII” mode that allows a FISH program to exchange datawith other programs, and a “FISH” mode that enables data to be passed between FISH functions.In FISH mode, the data is written in binary, without loss of precision, whereas numbers written outin ASCII form may lose precision when read back into a FISH program. In FISH mode, the valueof the FISH variable is written to the file, not the name of the variable. Only one file may be openat any one time.

close The currently open file is closed; 0 is returned for a successful operation.

open(filename, wr, mode)

This function opens a file, named filename, for writing or reading. Thevariable filename can be a quoted string or a FISH string variable.

Parameter wr must be an integer with one of the following values:0 file opened for reading; file must exist1 file opened for writing; existing file will be overwritten

Parameter mode must be an integer with one of the following values:0 read/write of FISH variables; only the data corresponding to the

FISH variable (integer, float or string) is transferred, not thename of the variable.

1 read/write of ASCII data; on a read operation the data isexpected to be organized in lines, with CR/LF between lines. Amaximum of 80 characters per line is allowed.

The returned value denotes the following conditions:0 file opened successfully1 filename is not a string2 filename is a string, but is empty3 wr or mode (not integers)4 bad mode (not 0 or 1)5 bad wr (not 0 or 1)6 cannot open file for reading (e.g., file does not exist)7 file already open8 not a FISH mode file (for read access in FISH mode)

FLAC Version 6.0

FISH REFERENCE 2 - 63

read(ar, n)

reads n records into the array ar. Each record is either a line of ASCIIdata or a single FISH variable. The array ar must be an array of at least nelements. The returned value is:0 requested number of lines were input without error−1 error on read (except end-of-file)n positive value indicates that end-of-file was encountered after

reading n lines

In FISH mode, the number and type of records must match exactly thenumber and type of records written. It is up to the user to control this. Ifan arbitrary number of variables is to be written, the first record could bemade to contain this number, so that the correct number could subsequentlybe read.

write(ar, n)

writes n records from the first n elements of the array ar. Each record iseither a line of ASCII data, or a single FISH variable. For ASCII mode,each element written must be of type string. The array ar must be an arrayof at least n elements. The returned value is:0 requested number of lines were output without error−1 error on writen positive value (in ASCII mode) indicates that the nth element

was not a string (hence only n−1 lines were written). An errormessage is also displayed on the screen.

The following intrinsic functions do not perform file operations, but can be used to extract itemsfrom ASCII data that is derived from a file.

cparse(s, nc1, nc2)

This function scans the string s and decodes the characters between columnsnc1 and nc2 (inclusive) as integer, float or string.

parse(s, i)

This function scans the string s and decodes the ith item, which it returns.Integers, floats and strings are recognized. Delimiters are the same as forgeneral commands (i.e., spaces, commas, parentheses, tabs and equal signs).If the ith item is missing, zero is returned. An error message is displayed,and zero is returned if the variable s is not a string.

FLAC Version 6.0

2 - 64 FISH in FLAC

pre parse(s, i)

This function scans the string s and returns an integer value according tothe type of the ith item, as follows:0 missing item1 integer2 float3 string missing (unable to interpret as int or float)

Example 2.20 illustrates the use of the FISH I/O functions:

Example 2.20 Using the FISH I/O functions

def setupa_size = 20IO_READ = 0IO_WRITE = 1IO_FISH = 0IO_ASCII = 1filename = ’junk.dat’

endsetup;def io

array aa(a_size) bb(a_size);

; ASCII I/O TEST ------------------status = open(filename, IO_WRITE, IO_ASCII)aa(1) = ’Line 1 ... Fred’aa(2) = ’Line 2 ... Joe’aa(3) = ’Line 3 ... Roger’status = write(aa,3)status = closestatus = open(filename, IO_READ, IO_ASCII)status = read(bb, a_size)if status # 3 then

oo = out(’ Bad number of lines’)endifstatus = close

;; now check results...loop n (1,3)

if parse(bb(n), 2) # n thenoo = out(’ Bad 2nd item in loop ’ + string(n))exit

FLAC Version 6.0

FISH REFERENCE 2 - 65

endifendloop

;if pre_parse(bb(3), 4) # 3 then

oo = out(’ Not a string’)exit

endif;

; FISH I/O TEST -----------------status = open(filename, IO_WRITE, IO_FISH)funny_int = 1234567funny_float = 1.2345e6aa(1) = ’---> All tests passed OK’aa(2) = funny_intaa(3) = funny_float

;status = write(aa,3)status = closestatus = open(filename, IO_READ, IO_FISH)status = read(bb, 3)status = close

;; now check results...if type(bb(1)) # 3 then

oo = out(’ Bad FISH string read/write’)exit

endifif bb(2) # funny_int then

oo = out(’ Bad FISH integer read/write’)exit

endifif bb(3) # funny_float then

oo = out(’ Bad FISH float read/write’)exit

endifoo = out(bb(1)) ; (should be a good message)command

sys del junk.datendcommand

end;io

FLAC Version 6.0

2 - 66 FISH in FLAC

2.7 Socket I/O Routines

FISH contains the option to allow data to be exchanged between two or more Itasca codes runningas separate processes, using socket connections (as used for TCP/IP transmission over the Internet).At present, socket I/O connections can be made between FLAC and PFC2D or PFC3D. FLAC3D alsoallows socket connections at this time. It is possible to pass data between two or more instancesof the same code (e.g., two instances of FLAC), but the main use is anticipated to be couplingof dissimilar codes such as FLAC and PFC2D. An example of such a coupling is provided inSection 2.7.1.

The data contained in FISH arrays may be passed in either direction between two codes. The datais transmitted in binary with no loss of precision. Up to six data channels may be open at anyone time; these may exist between two codes, or may connect several codes simultaneously. Thefollowing FISH intrinsics are provided. The word process denotes the instance of the code that iscurrently running. All functions return a value of 10 if the ID number is invalid.

sclose(ID)

Channel ID is closed.

sopen(mode, ID)

The integer mode takes the value 0 or 1. A value of 1 causes the data channelof number ID to be initiated, with the process acting as a server. Anotherprocess can link to the server, with the same ID, by invoking sopen, withmode = 0, which denotes the process as a client. The ID number mustbe in the range 0 to 5, inclusive, giving a total of six possible channelsof communication. The server sopen function must be issued before theclient sopen function, for a given ID. While waiting for a connection, theserver process is unresponsive. The sopen function returns 0 when a goodconnection has been made, and nonzero if an error has been detected.

sread(arr, num, ID)

num FISH variables are received from channel ID, and placed in array arr,which is overwritten, and which must be at least num elements in size.The returned value is zero if data is received without error, and nonzero ifan error has occurred. Note that the function sread does not return untilthe requested number of items has been received. Therefore, a process willappear to “lock up” if insufficient data has been sent by the sending process.

FLAC Version 6.0

FISH REFERENCE 2 - 67

swrite(arr, num, ID)

num FISH variables are sent on channel ID from array arr. The data in arrmay consist of a mixture of integers, reals or strings. Zero is returned fora good data transmission, and nonzero if an error is detected. In addition,error messages may be issued for various problems, such as incorrect arraysize, etc.

In order to achieve socket communication between two processes, codes must be started separatelyfrom separate directories. To illustrate the procedure, we can send messages between two instancesof FLAC, and record the log files, as follows. The server log file is as follows:

Example 2.21 Server log file

def servearray arr(3)arr(1)=1234arr(2)=57.89arr(3)=’hello from the server’oo=sopen(1,1)oo=swrite(arr,3,1)oo=sread(arr,1,1)oo=sclose(1)oo=arr(arr(1))

endserve

The client log file is as follows:

Example 2.22 Client log file

def clientarray arr(3)oo=sopen(0,1)oo=sread(arr,3,1)oo=out(’ Received values ...’)oo=out(’ ’+string(arr(1)))oo=out(’ ’+string(arr(2)))oo=out(’ ’+string(arr(3)))arr(1)=’greetings from the client’oo=swrite(arr,1,1)oo=sclose(1)

endclient

FLAC Version 6.0

2 - 68 FISH in FLAC

Data has been passed both ways between the two code instances. A more useful example is givenbelow, in Section 2.5.3.1.

2.7.1 Coupled FLAC and PFC2D Simulation

This example demonstrates the use of the socket I/O functions to transfer data between two codesexecuting separately. A deformable punch (modeled with FLAC) is driven into an assembly ofparticles (modeled with PFC2D ). Initially, a series of walls is created in PFC2D, with each wallcorresponding to a single surface segment of a FLAC zone. As the FLAC zones deform in large-strain, gridpoint velocities are transferred to PFC2D, so that the walls move in exactly the same wayas the boundary segments of the FLAC grid. The resulting wall forces, due to particles interactingwith the walls, are transferred to FLAC as applied gridpoint forces. In this way, a fully coupledsimulation is performed.

Three data files are used in the simulation. The file in Example 2.23 must first be executed by PFC2D

to create an assembly of particles within a container, and bring the assembly to equilibrium undergravity. The files in Examples 2.24 and 2.25 may then be used by FLAC and PFC2D, respectively,to execute the simulation. In order for the system to operate correctly, both codes should be startedas separate processes from separate directories. Then, Example 2.24 should be called first fromFLAC as the server, which waits (indefinitely) for a connection from another process. The fileExample 2.25 may then be called from PFC2D (operating as a client process) to establish contact.Initially, FLAC sends a series of wall coordinates to PFC2D, and both codes set up arrays of pointersto eliminate searching during cycling. Once the setup process is complete, cycling begins in bothcodes, with forces being sent by PFC2D to FLAC, and velocities being sent by FLAC to PFC2D.Cycling in both codes is synchronized, using a timestep of unity, so that the same displacementsare calculated in each step in each code.

FLAC Version 6.0

FISH REFERENCE 2 - 69

Example 2.23 PFC2D initialization file for coupled FLAC/PFC2D example

;fname: sio3.datset randomwall id 1 kn 1e8 nodes -2,2 -2,0wall id 2 kn 1e8 nodes -2,0 2,0wall id 3 kn 1e8 nodes 2,0 2,2gen id=1,200 rad=.05 .09 x -2 2 y 0 2pro dens 2000 kn 1e8 ks 1e8set grav 0 -10plot create pviewplot add wall blueplot add ball redplot add cforce yellowset dt=dscalecyc 15000prop fric 1.0cyc 15000save pex0.sav

Example 2.24 FLAC initialization and run file for coupled FLAC/PFC2D example

;fname: sio4.datgrid 20 10gen -0.5 1.5 -0.5 2.0 0.5 2.0 0.5 1.5model elasprop dens 1000 shear 2.5e7 bulk 5e7fix x y j=11def setLimits ; Array limits ... must be changed for bigger problem

nbuff = 1000 ; general buffer sizenList = 200 ; max number of walls generatedigpf = igpjgpf = jgp

endsetLimitsdef iniComms ; initialize communications, & send wall data

array buff(nbuff) numrec(1)array i1List(nList) j1List(nList) i2List(nList) j2List(nList)array appnt(igpf,jgpf)oo = sopen(1,1) ; channel 1 ... servernumWalls = 0loop j (1,jzones) ; left side

numWalls = numWalls + 1i1List(numWalls) = 1

FLAC Version 6.0

2 - 70 FISH in FLAC

j1List(numWalls) = ji2List(numWalls) = 1j2List(numWalls) = j+1

endLooploop i (1,izones) ; bottom

numWalls = numWalls + 1i1List(numWalls) = i+1j1List(numWalls) = 1i2List(numWalls) = ij2List(numWalls) = 1

endLooploop j (1,jzones) ; right side

numWalls = numWalls + 1i1List(numWalls) = igpj1List(numWalls) = j+1i2List(numWalls) = igpj2List(numWalls) = j

endLoopibuf = 0loop nn (1,numWalls)

setIJibuf = ibuf + 1buff(ibuf) = x(i1,j1)ibuf = ibuf + 1buff(ibuf) = y(i1,j1)ibuf = ibuf + 1buff(ibuf) = x(i2,j2)ibuf = ibuf + 1buff(ibuf) = y(i2,j2)command

apply xforce=1e-10 yforce=1e-10 i=i1 j=j1endCommand

endLoopnumrec(1) = numWallsoo = out(’ Sending ’+string(numWalls)+’ wall segments to PFC ...’)oo = swrite(numrec,1,1)oo = swrite(buff,ibuf,1)ap = app_pnt ; set up easy access to apply-list pointersloop while ap # 0

ii = imem(ap+$kapi1)jj = imem(ap+$kapj1)appnt(ii,jj) = apap = imem(ap)

endLoopend

FLAC Version 6.0

FISH REFERENCE 2 - 71

def setIJ ; set i,j values, given index nni1 = i1List(nn)j1 = j1List(nn)i2 = i2List(nn)j2 = j2List(nn)

enddef endComms ; Close communications

oo = sclose(1)enddef sendVelocities

ibuf = 0loop nn (1,numWalls)

setIJbuff(ibuf+1) = xvel(i1,j1)buff(ibuf+2) = yvel(i1,j1)buff(ibuf+3) = xvel(i2,j2)buff(ibuf+4) = yvel(i2,j2)ibuf = ibuf + 4

endLoopibuf = numWalls * 4oo = swrite(buff,ibuf,1)getForces

enddef getForces

loop nn (1,numWalls) ; reset applied forcessetIJap1 = appnt(i1,j1)ap2 = appnt(i2,j2)fmem(ap1+$kapv3) = 0.0fmem(ap1+$kapv4) = 0.0fmem(ap2+$kapv3) = 0.0fmem(ap2+$kapv4) = 0.0

endLoopibuf = numWalls * 3oo = sread(buff,ibuf,1)ibuf = 0loop nn (1,numWalls)

setIJFxW = buff(ibuf+1)FyW = buff(ibuf+2)MomW = buff(ibuf+3)denom = FyW * (x(i1,j1)-x(i2,j2)) - FxW * (y(i1,j1)-y(i2,j2))if denom # 0.0

rat = (MomW - FyW * x(i2,j2) + FxW * y(i2,j2)) / denomrat = max(0.0,min(1.0,rat))

FLAC Version 6.0

2 - 72 FISH in FLAC

ap1 = appnt(i1,j1)ap2 = appnt(i2,j2)fmem(ap1+$kapv3) = fmem(ap1+$kapv3) + rat * FxWfmem(ap2+$kapv3) = fmem(ap2+$kapv3) + (1.0-rat) * FxWfmem(ap1+$kapv4) = fmem(ap1+$kapv4) + rat * FyWfmem(ap2+$kapv4) = fmem(ap2+$kapv4) + (1.0-rat) * FyW

endifibuf = ibuf + 3

endLoopendcall app.finset echo offiniCommsset echo onini yvel=-0.5e-3set fishcall 15 sendVelocitieswin -2 2 -1 3set largecycle 1300endComms

Example 2.25 PFC2D run file for coupled FLAC/PFC2D example

;fname: sio5.datres pex0.savdef setLimits ; Array limits ... must be changed for bigger problems

nbuff = 1000 ; general buffer sizenList = 200 ; max number of walls generated

endsetLimitsdef iniComms

array buff(nbuff) numrec(1)array Wpoint(nList)oo = sopen(0,1)oo = sread(numrec,1,1)numWalls = numrec(1)ibuf = numWalls * 4 ; (4 values per wall)oo = sread(buff,ibuf,1)ibuf = 0IDmake = 100 ; starting created wall numberloop nn (1,numWalls)

getSegcommand

wall id=IDmake kn=1e8 ks=1e8 nodes x1,y1 x2,y2

FLAC Version 6.0

FISH REFERENCE 2 - 73

endCommandSection

wp = wall_headloop while wp # null

if w_id(wp) = IDmakeexit section

endifwp = w_next(wp)

endLoopoo = out(’ ** error in finding wall pointer’)Exit

EndSectionWpoint(nn) = wp ; save wall pointerw_fix(wp) = 1 ; inhibit PFC wall velocity updateIDmake = IDmake + 1

endLoopenddef getSeg

ibuf = ibuf + 1x1 = buff(ibuf)ibuf = ibuf + 1y1 = buff(ibuf)ibuf = ibuf + 1x2 = buff(ibuf)ibuf = ibuf + 1y2 = buff(ibuf)

enddef endComms

oo = close(1)enddef getVelocities

ibuf = numWalls * 4oo = sread(buff,ibuf,1)ibuf = 0loop nn (1,numWalls)

ibuf = ibuf + 1xv1 = buff(ibuf)ibuf = ibuf + 1yv1 = buff(ibuf)ibuf = ibuf + 1xv2 = buff(ibuf)ibuf = ibuf + 1yv2 = buff(ibuf)wp = Wpoint(nn)ws = w_wlist(wp)

FLAC Version 6.0

2 - 74 FISH in FLAC

ws_xvel(ws) = xv1ws_yvel(ws) = yv1ws = ws_next(ws)ws_xvel(ws) = xv2ws_yvel(ws) = yv2

endLoopenddef sendForces

ibuf = 0loop nn (1,numWalls)

wp = Wpoint(nn)ibuf = ibuf + 1buff(ibuf) = w_xfob(wp)ibuf = ibuf + 1buff(ibuf) = w_yfob(wp)ibuf = ibuf + 1buff(ibuf) = w_mom(wp)

endLoopibuf = numWalls * 3oo = swrite(buff,ibuf,1)

endset fishcall 0 getVelocitiesset fishcall 3 sendForcesiniCommsplot shosave pex1.savcycle 1300endComms

Figure 2.1 shows the initial particle assembly and the 40 walls that form the deformable punch,corresponding to three sides of a 200-zone FLAC grid. Figure 2.2 shows the final state from PFC2D,in which the active surfaces of the punch exhibit large deformation in response to the forces exertedby the particles. Figure 2.3 shows the corresponding state from FLAC, in which the same surfacedeformation is evident, as well as contours of major principal stresses. Note that FLAC will haltwith a “bad geometry” error if the simulation is continued much further.

FLAC Version 6.0

FISH REFERENCE 2 - 75

PFC2D 3.10Step 30000 10:54:09 Mon Dec 08 2008

View Size: X: -2.200e+000 <=> 2.200e+000 Y: -1.449e+000 <=> 3.449e+000

WallBallCForce Chains

CompressionTension

Maximum = 3.882e+002

Figure 2.1 Initial particle assembly and walls that form deformable punch

PFC2D 3.10Step 31300 10:50:03 Mon Dec 08 2008

View Size: X: -2.200e+000 <=> 2.200e+000 Y: -1.449e+000 <=> 3.449e+000

WallBallCForce Chains

CompressionTension

Maximum = 6.112e+005

Figure 2.2 Final state from PFC2D

FLAC Version 6.0

2 - 76 FISH in FLAC

FLAC (Version 6.00)

LEGEND

8-Dec-08 15:05 step 1300 -1.000E+00 <x< 1.000E+00 -2.500E-01 <y< 2.250E+00

Minimum principal stress -7.50E+06 -5.00E+06 -2.50E+06 0.00E+00 2.50E+06 5.00E+06

Contour interval= 2.50E+06Extrap. by averaging

0.000

0.400

0.800

1.200

1.600

2.000

-0.900 -0.700 -0.500 -0.300 -0.100 0.100 0.300 0.500 0.700 0.900

JOB TITLE : .

Figure 2.3 Final state from FLAC

The physical process is quite straightforward, but there are some points that are important to note:

1. Large-strain mode should be used in FLAC, because PFC2D cannot operatein any other way, and it is necessary for wall movement to keep track withzone-boundary movement.

2. In a simulation that is closely coupled, data should be exchanged at everycycle, at the appropriate points in the calculation cycles for both codes.

3. The timestep in both codes should be identical. This is achieved here byrunning FLAC in static mode and PFC2D with density scaling. Thus, thetimestep is unity for both processes. Alternatively, both codes could be run indynamic mode with the same timestep.

4. In order to “slave” the movement of PFC2D’s walls to FLAC ’s zone-segments,the walls are declared “fixed,” using the FISH intrinsic w fix. This allows auser-written FISH function to override the calculation of wall segment motion.

Some manipulation of forces sent from PFC2D must be done, because each wall produces forcesand moments relative to its center of rotation. FLAC gridpoint forces are derived from this data byusing equations of moment equilibrium, to determine the line of action of the resultant force. Toavoid giving many APPLY commands at each step, the data in an APPLY list is modified directly bya FISH function, using a single APPLY list that is set up at the beginning of the run.

The example is contrived and simplified, but it illustrates that closely coupled interaction may beachieved between a continuum region and a region that contains discrete bodies.

FLAC Version 6.0

FISH REFERENCE 2 - 77

2.8 User-Defined Constitutive Models

2.8.1 Introduction and Overview

New constitutive models may be written in the FISH language. Once compiled successfully, a newmodel behaves just like a built-in model as far as the user is concerned (i.e., it can be installed andremoved by using the MODEL command). A user-defined model can also use properties that aredefined and given names by the model’s author; these names act just like built-in properties (i.e.,they can be set with the PROPERTY command, printed with the PRINT command and plotted withthe PLOT command).

User-written models execute more slowly than built-in models. After optimization (described inSection 2.9), a FISH model will typically run somewhere between one-quarter and one-third thespeed of a built-in model. However, quite often, a user-written model needs only to be installed ina small part of the FLAC grid, since the particular behavior that it is designed to reproduce mayonly occur locally (e.g., cracking around a tunnel); the material elsewhere can be represented by astandard model. In any case, the increased runtimes of the special model may be compensated bydecreased human time and effort, since less work may be done trying to force-fit an inappropriatemodel.

A user-written constitutive model is simply a FISH function containing some special statementsand references to special variables that correspond to local entities within a single zone. The user-defined model (referred to as “UDM”) is called by FLAC four times per zone (once per triangularsubzone) for every solution step. It is the task of the UDM to supply a new set of stress components,given strain increments and the old set of stress components. However, certain other tasks must beperformed, and certain conventions observed. These are described in the following sections.

When a new model has been developed, it should be exercised thoroughly on a one-zone grid withall gridpoints fixed. Given strain paths should be applied to the zone, and histories made of thestress response. The proposed model may be “debugged” very effectively in this way.

The Following Sections Should Only BeRead By Experienced Programmers.

FLAC Version 6.0

2 - 78 FISH in FLAC

2.8.2 Model Definition and Use

The following statement must appear at the beginning of a FISH function for it to be recognized asa user-defined model (UDM).

CONSTITUTIVE MODEL <n>

where n is an optional identification number. The above statement is incompatible with the state-ments WHILE STEPPING and COMMAND, which must not appear in the same function. Once a func-tion containing the statement CONSTITUTIVE MODEL has been successfully compiled, the FLACcommand MODEL can be used to install the UDM in the grid, just like a built-in model (see Exam-ple 2.26).

Example 2.26 Installing a user-defined constitutive model

def test_modelconstitutive_modelzs11 = 0.0zs22 = 0.0

end..

model test_model i=2,3 j=4,5

The optional ID number that follows the word CONSTITUTIVE MODEL must be a positive integer,and must not conflict with the ID numbers of any of FLAC ’s internal models (see Section 2.5.3for a list of built-in model numbers, under variable name model). If the ID number is omitted oris inappropriate, then an ID number of zero is taken. The given number is not necessary, but itis useful when using a FISH function to perform some operation that requires a knowledge of themodel installed in a particular zone (the grid variable model will return the given ID number). Notethat the ID number can only be set by means of the CONSTITUTIVE MODEL statement; it cannot beassigned anywhere else. The code fragment in Example 2.27 illustrates the use of an ID number.

FLAC Version 6.0

FISH REFERENCE 2 - 79

Example 2.27 Assigning model numbers to user-defined constitutive models

def test_modelconstitutive_model 88

.

.enddef put_stresses

loop i (1,izones)loop j (1,jzones)

if model(i,j) = 88 thensxx(i,j) = syy(i,j) * fac_1

else.

The name for a UDM should not conflict with that of any of the built-in models (see Section 1.2 inthe Command Reference, under the MODEL command). Section 2.2.2 should also be consultedto avoid conflicts with other pre-defined names.

2.8.3 User-Defined Local Property Variables

Named variables may be used by the UDM, as with any other FISH function, but since regularFISH variables are of global scope, they cannot be used to store things that are different for eachzone. However, variables that are local to each zone may be defined by declaring them in advancewith the f prop statement,

f prop var1 var2 var3 . . .

This statement is followed by a list of names separated by space(s). Several such statements maybe given, but they should precede any executable code. The names must be unique and must notconflict with FISH statements or any built-in property name (see Section 2.5.4). Any length ofname is allowed, but only the first 12 characters are displayed on plots or print headings.

During compilation of the FISH function, the number of user-defined local variables is counted andused by FLAC to allocate that number of extra words of memory per zone. The names mentionedin the f prop statement(s) are completely equivalent to FLAC properties; they may be set with thePROPERTY command, printed with the PRINT command, and plotted with the PLOT command (ascontours). The variables are of type float; they are normally used to store material properties, butthey can be used to store any state variables at the individual zone level. The names of the localvariables are used just like any other scalar variable within the function that defines them (i.e., theyare referred to without zone indices).

Local “property” variables are also available in other FISH functions (apart from the definingfunction), but there they act like other property variables – i.e., zone subscripts are needed.

FLAC Version 6.0

2 - 80 FISH in FLAC

Some program fragments in Example 2.28 illustrate the use of local property variables:

Example 2.28 Using local property variables

def my_modelconstitutive_model 102f_prop apples plums prunes bananasf_prop grapes pearscase_of mode

case 1;--- do initialization & checking here

case 2zs11 = grapes * zde11 + 2.0 * zde22 / prunes

.

.end;def ini_prop

loop i (1,izones)loop j (1,jzones)

if model(i,j) = 102 thengrapes(i,j) = 34.5prunes(i,j) = 66.6

else.

end;grid 10 10model my_modelini_prop

.

.

In this example, the newly defined properties are used (as scalars) in the calculation of zone stresses(discussed later). The same names are used in another function as indexed grid variables.

In general, note that indexed zone or gridpoint variables must not be used in a UDM function; thefunction is already being called for a particular zone, so indices are irrelevant (and forbidden).

FLAC Version 6.0

FISH REFERENCE 2 - 81

2.8.4 State Variables

During stepping, the UDM function is called four times per zone per timestep (once for eachtriangular subzone). When the function is called, the following local variables (all of type float)are available within the function as scalars. The variables are undefined in functions that are notconstitutive model functions.

zart area or triangular subzone (input)

zde11 �e11 strain increment (input)

zde12 �e12 strain increment (input)

zde22 �e22 strain increment (input)

zde33 �e33 strain increment (input)

zdpp increment in pore pressure (output)

zdrot incremental zone rotation in CONFIG large mode only (input)

zporos porosity of zone (in CONFIG gw mode only) (input)

zs11 σ11 effective stress (input and output)

zs12 σ12 effective stress (input and output)

zs22 σ22 effective stress (input and output)

zs33 σ33 effective stress (input and output)

zsub indicator for subzone averaging (input)

ztea thermal a-zone strain increment (input)

zteb thermal b-zone strain increment (input)

ztec thermal c-zone strain increment (input)

zted thermal d-zone strain increment (input)

ztsa thermal a-zone stress increment (output)

ztsb thermal b-zone stress increment (output)

ztsc thermal c-zone stress increment (output)

ztsd thermal d-zone stress increment (output)

zvisc dynamic viscosity inhibit flag (output)

FLAC Version 6.0

2 - 82 FISH in FLAC

zxbar mean distance of triangular subzone from axis of symmetry(in CONFIG ax mode), such that the volume of the subzoneis given by zart * zxbar (input)

The notations (input) or (output) indicate, respectively, that the variable should be used (and notmodified) by the UDM, or that it may be modified by the UDM.

It is the main task of the UDM function to update the four stress components, given the currentstresses and the four strain increments. Note that the strain components are given; they cannotbe changed by the function. The process of mixed discretization (see Section 1.3.2 in Theoryand Background) has already been applied to the strains before the UDM is called; after thefour subzones are processed by the UDM, the stresses are adjusted externally, as described inSection 1.3.3 in Theory and Background.

If a state variable that applies to the whole quadrilateral zone (e.g., accumulated plastic strain) isrequired, then appropriate averaging must be done within the UDM. The variable zsub indicates tothe function when averaging of quantities in the 4 subzones may be performed (see Section 2.8.6for details).

The variable zdpp is an increment of pore pressure that may be generated by the constitutive model.It is important to note that the increment in pore pressure due to the change in the volume of the zoneis already calculated before the UDM is called. The variable zdpp is only to be used by modelsthat produce pore pressure changes in addition to those associated with zone volume changes (e.g.,if the grains are compressible). Note that zdpp is ignored in axisymmetric mode (i.e., pore pressuregeneration cannot be done by a UDM in an axisymmetric model).

In dynamic simulations, zvisc should be set to 0.0 if it is required that stiffness-proportional dampingbe inhibited; for example, this type of damping may be “switched off” if plastic flow is occurring.If zvisc is set to 1.0, then stiffness-proportional damping will be done normally (if it has beenrequested by a FLAC command).

For thermal/mechanical calculations, the bulk modulus of the model should be used to provideincrements in stresses from increments of strains. This allows the thermal expansion/contractionto be modeled properly.

2.8.5 Operations to Be Performed by the UDM: Use of mode Variable

In addition to the action during stepping (mentioned above), the UDM function must perform othertasks. The scalar variable mode is defined whenever the function is called by FLAC. The UDMshould test the value of mode (an integer) and perform the appropriate tasks according to its value,as follows:

mode

1 This mode is set when the function is called prior to stepping; the UDMmay perform any initialization or checking of material properties, or it may

FLAC Version 6.0

FISH REFERENCE 2 - 83

do nothing. In mode 1, the function is called only once per zone per STEPcommand.

2 Mode 2 corresponds to the main task of the function, as described in Sec-tion 2.8.4 (i.e., new stresses should be computed from old stresses and strainincrements). In this mode, the function is called up to 4 times per zone (oncefor each subzone).

3 The UDM must return values for the scalars cm max and sm max: these shouldbe set to the maximum confined modulus and the shear modulus, respectively,as estimated for this zone. The value of cm max is used by FLAC to computea stable timestep; it is essential that a value is returned for this variable. Foran elastic model, this variable is given by K + (4G/3). Both variables areused by the absorbing boundary logic in dynamic mode (estimates of tangentmoduli should be provided). The UDM is called once per zone for mode 3; itis called at the beginning of stepping and every ten steps in large-strain mode.It may also be called more often if FLAC determines that it needs to recomputethe internal timestep.

4 A set of 4 thermally induced stresses must be computed from a given set of 4fictitious strains. This calculation is only required if thermal calculations arebeing done. Normally, the action consists of multiplying each strain by thecurrent tangent bulk modulus, to give stresses. The UDM is called once perzone for mode 4.

Note that mode 3 is called before mode 1 for constitutive models; also, zone stresses are undefinedin mode 1, mode 3 and mode 4.

As an example of a simple constitutive model written in FISH, the function in Example 2.29 performsan identical operation to the built-in isotropic elastic model of FLAC.

Example 2.29 FISH constitutive model for isotropic elastic behavior

def m_elasconstitutive_modelf_prop m_shear m_bulkf_prop m_e1 m_e2 m_g2case_of mode

; --- initialization ---case 1

m_e1 = m_bulk + 4.0 * m_shear / 3.0m_e2 = m_bulk - 2.0 * m_shear / 3.0m_g2 = 2.0 * m_shear

; --- running section ---case 2

zs11 = zs11 + zde11 * m_e1 + (zde22+zde33) * m_e2

FLAC Version 6.0

2 - 84 FISH in FLAC

zs22 = zs22 + (zde11+zde33) * m_e2 + zde22 * m_e1zs33 = zs33 + (zde11+zde22) * m_e2 + zde33 * m_e1zs12 = zs12 + zde12 * m_g2

; --- max modulus ---case 3

cm_max = m_bulk + 4.0 * m_shear / 3.0sm_max = m_shear

; --- thermal stresses ---case 4

ztsa = ztea * m_bulkztsb = zteb * m_bulkztsc = ztec * m_bulkztsd = zted * m_bulk

end_caseend

The “properties” m e1, m e2 and m g2 are evaluated in the initialization section, to save timeduring stepping. We may store the above FISH code in a file (e.g., “ELAS.FIS”) and call it from aFLAC data file, as shown in Example 2.30:

Example 2.30 Applying the FISH elastic model

g 5 5set grav 10fix x y j=1call elas.fismod m_elasprop m_bulk=2e8 m_shear=1e8 dens=1000step 100print ydisp m_bulk m_shear m_e1ret

The results should be identical to those using FLAC ’s built-in elastic law. However, the executiontime will be slower, as explained in Section 2.8.1. The speed may be increased considerably byusing the command OPT m elas (see Section 2.9).

FLAC Version 6.0

FISH REFERENCE 2 - 85

2.8.6 Averaging of Sub-Zone Variables: Use of zsub Variable

Some “property” variables (declared with the f prop statement) may be used to record or accumulatestate variables for the constitutive model. For example, plastic strain may be accumulated for use ina strain-hardening law. However, properties are stored for the whole quadrilateral zone, whereas theuser-written function is called for each triangular subzone (either 2 or 4, depending on geometry).The computed “property” (e.g., plastic strain) should be the average for the 2 or 4 subzones.Parameter zsub (which is of type float) allows the function to know when to accumulate values andwhen to store them, according to the following prescription:

zsub = 0 The function should accumulate the desired quantity in some uniqueglobal variable. Since the function is called sequentially for allsubzones in the quadrilateral, there is no danger that the globalvariable will conflict with its use by other zones and other models.However, the global variable must not be overwritten by other (non-constitutive) functions.

zsub > 0 The function should now divide the accumulated quantity by zsuband store it in the appropriate property location. Since zsub willhave the value 2.0 or 4.0, the stored property will be the averagequantity. The variable used for accumulation must now be set tozero. This is very important; otherwise, the next zone calculationwill be in error, since its accumulator will not start from zero.

The elastic model given as an example in Section 2.8.5 may be modified to illustrate the useof parameter zsub to save average state variables. For example, suppose we want to save theaccumulated volume strain for each zone. We introduce a new property name m dvol, and a newglobal variable m vol, which should not be used elsewhere. The following modified part of theFISH code in Example 2.31 will store the average volumetric strain in the property variable m dvol.

Example 2.31 Storing average volumetric strain

.

.f_prop m_dvolcase_of mode

.

.;--- running section ---

case 2zs11 = zs11 + zde11 * m_e1 + (zde22+zde33) * m_e2zs22 = zs22 + (zde11+zde33) * m_e2 + zde22 * m_e1zs33 = zs33 + (zde11+zde22) * m_e2 + zde33 * m_e1zs12 = zs12 + zde12 * m_g2m_vol = m_vol + zde11 + zde22 + zde33if zsub > 0.0 then

FLAC Version 6.0

2 - 86 FISH in FLAC

m_dvol = m_dvol + m_vol / zsubm_vol = 0.0

end_if..

After running FLAC, the correctness may be verified by printing out both the newly defined volumestrain and FLAC ’s built-in volume strain measure:

print m dvol vsi

The two results should be identical.

2.8.7 FRIEND Functions for Constitutive Models

The FRIEND statement may be used in a user-defined model (UDM) to allow other functions (withoutthe CONSTITUTIVE MODEL declaration) to have access to the local zone variables of the callingfunction. The format is

friend func1 func2 ...

where func1 and func2 are names of FISH functions. Within such functions (when called from theUDM), the intrinsic zone variables (e.g., zde11, mode, etc.) and property names are treated exactlyas they are in the calling UDM. The FRIEND declaration is only necessary if zone properties andvariables are to be accessed by the associated function. The following restrictions apply:

a) Each function may only be declared as the friend of one UDM; otherwise,there would be a conflict in zone variable names. However, each UDM maydeclare any number of friends.

b) The function referred to by the FRIEND statement must be defined after the orig-inating UDM; otherwise, the compiler cannot know that the property names(used in the FRIEND function) are not just global variables.

c) If a FRIEND function is optimized, the associated UDM function must also beoptimized.

Example 2.32 demonstrates and validates the FRIEND logic:

FLAC Version 6.0

FISH REFERENCE 2 - 87

Example 2.32 Demonstration of FRIEND logic

;--- Test of friend logic ... all computation is done in other; functionsdef m_elas

constitutive_modelfriend aaa bbb ccc bbb_subf_prop m_shear m_bulk m_e1 m_e2 m_g2case_of mode

case 1aaa

case 2bbb

case 3ccc

case 4end_case

enddef aaa

m_e1 = m_bulk + 4.0 * m_shear / 3.0m_e2 = m_bulk - 2.0 * m_shear / 3.0m_g2 = 2.0 * m_shear

enddef bbb

zs11 = zs11 + (zde22 + zde33) * m_e2 + zde11 * m_e1zs22 = zs22 + (zde11 + zde33) * m_e2 + zde22 * m_e1bbb_sub

enddef bbb_sub

zs12 = zs12 + zde12 * m_g2zs33 = zs33 + (zde11 + zde22) * m_e2 + zde33 * m_e1

enddef ccc

cm_max = m_bulk + 4.0 * m_shear / 3.0sm_max = m_shear

endgrid 6 6mod m_elas i=1,3 ; left-hand side in UDMprop m_shear 1e8 m_bulk 2e8 dens 1000 i=1,3mod elas i=4,6 ; right-hand side is built-in modelprop shear 1e8 bulk 2e8 dens 1000 i=4,6set grav 10fix x y j=1optcyc 100

FLAC Version 6.0

2 - 88 FISH in FLAC

pr xdisp; ---> Note that results should be symmetric, but of opposite sign.

2.8.8 Hints and Suggestions

Section 3 contains FISH versions of a number of FLAC ’s built-in models; the FISH programs arealso available on file to FLAC users. It is useful to consult these programs to get some ideas beforewriting a new constitutive model. The following suggestions may also be useful:

1. After defining a constitutive function, type PRINT fish to make sure that:

(a) local properties do not appear in the list; and

(b) misspelled state variables (e.g., zed22) do not appear.

2. If a constitutive program uses many global variables, it may be worthwhile toinclude a $ sign as the first character in their names, since the command PRINTfish will not print these variables (and will cause confusion by listing manynames that may be irrelevant to the user). The “$” variables may be listedseparately with the command PRINT $fish.

3. If a user-defined property is given a value for mode 2 operation of a constitutivefunction, then the conditions will correspond to the last-computed subzone(usually D) unless steps are taken to store the average value (see Section 2.8.6).

4. If you have some user-written models that you use frequently, they can bepre-compiled and stored in a save file; this will eliminate the time delay forcompilation of complicated models. The following file fragments illustratethe technique:

call elas.fis ;compile required modelscall mohr.fiscall my model.fissave defmod.sav ;now save compiled versions

The compiled models can now be retrieved rapidly (from some other data file):

res defmod.savgrid 20 20model my model..

Alternatively, the command res defmod.sav could be placed in the file“FLAC.INI” if the user-written models are always required to be available onstart-up.

FLAC Version 6.0

FISH REFERENCE 2 - 89

5. The names of the new properties defined in a user-written constitutive modelmust be spelled out in full in the PRINT, PLOT and PROPERTY commands(unlike the names of built-in properties, which may be truncated).

6. Some checking of input properties should be done in the mode 1 section of auser-written model; error messages may be printed out by using the variableserror and nerr (see Section 2.4.3).

FLAC Version 6.0

2 - 90 FISH in FLAC

2.9 The Optimizer

The execution speed of user-written FISH functions can be increased in certain cases by using theOPT command; a speed increase of four to eight times is typical. However, there are a numberof restrictions that limit the usefulness of the command, and may actually lead to errors if theoptimized code is used incorrectly. The optimizer was designed primarily to improve the speed ofuser-written constitutive models; there is less advantage in using it for general functions.

2.9.1 Principles of Operation

In a normal FISH function, every reference to a variable necessitates a call to a “librarian” thatdetermines where the information is to be found. Since there are many types and variations ofvariables (e.g., grid variables, intrinsic functions, local properties, etc.), the process of retrieval iscomplicated and time-consuming. The optimizer attempts to go through this process beforehandand store a machine address for each variable (or an index that gives rapid access to a machineaddress). It also determines the types (integer, float or string) of variables and propagates themthrough the arithmetic expressions in order to determine the types of the results in advance; thiseliminates another step at runtime.

The result of invoking the optimizer on a function is to create a new list of instructions (the “o-code”), which consists of basic operations (arithmetic and jumps) using machine addresses. Anyreferences or operations that cannot be translated into simple instructions cause a temporary jumpfrom the o-code to the regular FISH code (the “p-code”) when the function is executed. The printout“% optimized” indicates the proportion of instructions that were translated into o-code. Someoperations cannot be translated, in which case, the optimization of the whole function fails, and anerror message is displayed.

The use of optimized and non-optimized functions during execution is automatic and transparent tothe user; if an optimized version of a function exists, then it is used rather than the non-optimizedversion.

2.9.2 Use of the OPT Command

The optimizer is applied to FISH functions that are already defined, as follows:

OPT <fun1 fun2 fun3. . . >

where fun1, fun2 and fun3 are existing FISH functions. Alternatively, the OPTcommand may be given with no parameters, in which case, all functions are opti-mized. An informative message is provided for each function, indicating whetheroptimization was successful. The OPT command may be given several times (theold optimized version is erased, and a new one is created).

FLAC Version 6.0

FISH REFERENCE 2 - 91

2.9.3 Restrictions

The following rules must be observed when writing a function that can be successfully optimized:

1. The function may call other functions, but such functions must have alreadybeen defined prior to optimization. The called functions may or may not havebeen optimized themselves.

2. COMMAND sections may not be executed while an optimized function is active.For example, an error will occur if an optimized function calls a non-optimizedfunction that contains a COMMAND section. An optimized function may notcontain the COMMAND statement.

3. No mixed-mode arithmetic is allowed (i.e., all variables (and functions) inan arithmetic expression must be of the same type (all integer or all floating-point)). Furthermore, the destination type must be the same as the source typein an assignment statement. If type conversion is required, then the functionsint( ), float( ) and string( ) should be used. The specification statements INT,FLOAT and STRING should be used at the beginning of the function to pre-definethe types of all variables that will be used. The exponentiation operation isexempted from the mixed-mode restriction. For example, 3.4ˆ2 is allowed.

4. The following scalar variables (see Section 2.5.2) will not work in optimizedcode: clock, imem, fmem, urand and grand. All other variables and functionswork correctly.

2.9.4 Suggestions

The following suggestions are designed to improve the speed of an optimized function, but it is notnecessary to follow them in order to achieve a working program.

1. The use of property variables within a constitutive model function should beminimized; if possible, work with regular FISH variables, which are accessedmore rapidly.

2. The following variables or functions involve extra computational overheads:tables, all grid-indexed variables (e.g., sxx(i,j), ex 3(i,j),shear mod(i,j), etc.) and intrinsic functions (e.g., sin(x), sqrt(x)).Also included in the list are user-defined constitutive properties used outsideof the constitutive model in which they are defined.

3. If possible, replace exponentiation (ˆ) with repeated multiplications (e.g.,xdifˆ2 should be replaced with xdif*xdif).

FLAC Version 6.0

2 - 92 FISH in FLAC

2.9.5 Warning

Variable types (integer, float or string) are built into the optimized code at the time of optimization.If the variable types subsequently change, then the results of arithmetic operations will be wrong.For example, integer arithmetic might be used to multiply two floating-point numbers. It is theresponsibility of the user to ensure that variable types do not change.

FLAC Version 6.0