Set Directory and Filename of the Input File

SetDirectory["C:\Users\ohtsuka\Documents\AutoGen\AutoGenU\agInvPend"]
InpFile="inputInvPendC.m"

Functions for C Code Generation

Differentiation by a Vector:  Dv

Dv[f_,x_]:=Module[{j,ans},ans=Table[(∂_(x[[j]]))f,{j,Length[x]}];If[Length[Dimensions[ans]]≠1,ans=Transpose[ans]];ans]

Constuction of an n by n Symmetric Matrix from a Vector

Sym[v_,n_]:=Module[{i,j,iv,ans},ans=Table[0,{i,n},{j,n}];iv=1;i=0;Do[Do[ans[[j,j+i]]=v[[iv]];ans[[j+i,j]]=v[[iv]];iv++,{j,n-i}],{i,0,n-1}];ans]

Construction of a Vector from an n by n Symmetric Matrix

DeSym[S_,n_]:=Module[{i,j,ans={}},Do[Do[AppendTo[ans,S[[j,j+i]]],{j,n-i}],{i,0,n-1}];ans]

User Settings

Off[General::spell]
(* Default Values *)
SimplifyLevel=0;
Precondition=0;

Get[InpFile] (* Read Input File *)

If[dimx != Length[fxu], "Warning! Dimension Missmatch in dimx and fxu.">>outfile;Abort[ ];]
If[Length[MyVarNames]!= Length[MyVarValues], "Warning! Dimension Missmatch in MyVarNames and MyVarValues">>outfile;Abort[ ];]
If[(Length[MyArrNames]!= Length[MyArrDims])||(Length[MyArrDims]!= Length[MyArrValues]), "Warning! Dimension Missmatch in MyArrNames, MyArrDims and MyArrValues">>outfile;Abort[ ];]

Generate RHC Algorithm

Euler-Lagrange Equations

H=L+lmdv.fxu+muv.Cxu;
uv=Join[uv,muv];
dimuc=dimu+dimc;
Hx=Dv[H,xv];
Hu=Dv[H,uv];
If[SimplifyLevel>0,Hx=Simplify[Hx];Hu=Simplify[Hu];]
dlmddt=-Hx;

If[Precondition==1,
	Huu=Dv[Hu,uv];
	Hu=LinearSolve[Huu,Hu];
	If[SimplifyLevel>0,Hu=Simplify[Hu]];
]

Boudary Conditions

phix=Dv[phi,xv];
If[SimplifyLevel>0,phix=Simplify[phix];]

Generate C Code

<<Format2`

<<Optimize2`

Conversion of Arrays

ArrNames=Join[MyArrNames,{"x","lmd","u","p","dx","dlmd","hu"}];
ArrDims=Join[MyArrDims,{dimx,dimx,dimuc,dimp,dimx,dimx,dimuc}];
ArrCnv={};
Do[ArrCnv=Join[ArrCnv,Table[ArrNames[[j]]<>"["<>ToString[i]<>"]"->ArrNames[[j]]<>"["<>ToString[i-1]<>"]",{i,ArrDims[[j]]}]],{j,Length[ArrNames]}];

SetOptions[Optimize,OptimizeVariable->{o,Array},OptimizeNull->Prepend[ToExpression[ArrNames],List],OptimizeCoefficients->True,OptimizeProcedure->False];

lept=Length[Optimize[pt][[1]]];
leph=Length[Optimize[phix][[1]]];
lexp=Length[Optimize[fxu][[1]]];
lelp=Length[Optimize[dlmddt][[1]]];
lehu=Length[Optimize[Hu][[1]]];
leno=Max[{lept,leph,lexp,lelp,lehu}];

ArrCnv2=ArrCnv;
Do[
	ArrCnv2=Join[ArrCnv2,Table["o["<>ToString[i]<>"]"->"o["<>ToString[i-1]<>"]",{i,leno}]]
]

SetOptions[CAssign,AssignOptimize->True,AssignPrecision->10,AssignReplace->ArrCnv2,AssignToArray->ToExpression[ArrNames],AssignIndent->"    "];

Output to File

outfile=StringJoin[outfn,".c"];
Splice["AutoGenU.mc",outfile,FormatType->OutputForm];