/* eqns.
Ecological Modelling Front End: Equation Former
Alan Bundy 21.5.81 */


/* Form a recursive equation for each state variable */
go :-
	findall(Var, state_variable(Var), VarList),	% Get list of state variables
	maplist(form_equation, VarList, EqnList),	% Form equation for each
	writef('Equations formed are: %l',[EqnList]).	% Type answer

/* Form recursive equation for state variable */
form_equation(StateVar, d(StateVar)/dt=Value) :-	
	findall(Value,process(StateVar,Value),ValList),	% Make list of contributing processes
	dottoplus(ValList,Value1),			% Make list into sum
	convert(Value1,Value).				% replace system variables by their values

/* Remove unwanted bits from expressions */
convert(Attr,Value) :-		% Replace attribute or process with value
	replace(Attr,Value), !.

convert(Num,Num) :- atom(Num), !.		% Leave real number unchanged

convert(Exp,Ans) :-		% Recursively apply convert
	Exp =.. [Sym|Args], !,
	maplist(convert,Args,NewArgs),
	Ans =.. [Sym|NewArgs].

/* Turn external variable into function of t */
replace(Var,Var_at_t) :- external_variable(Var), !,
	Var_at_t =.. [Var,t].

/* Replace parameter with value */
replace(Para,Ans) :- parameter(Para,Ans), !.

/* Leave state variable unchanged */
replace(Var,Var) :- state_variable(Var,initial,Initval), !.

/* Replace internal variable with value */
replace(Var,Ans) :- internal_variable(Var,Value), !,
	convert(Value,Ans).

/* Replace process with value */
replace(Process,Ans) :- formula(Process,Value), !,
	convert(Value,Ans).

/* Ignore local variables hack for findall */
state_variable(Var) :- state_variable(Var,Time,Val).


/* Replace list by sum */
dottoplus([],0).
dottoplus([Hd|Tl],Hd+Sum) :-
	dottoplus(Tl,Sum).



