# How to include AceFEM analysis in a package

I would like to wrap my AceFEM analysis in one function and include it in a Mathematica package (.wl). I have followed the instructions on how to create packages from documentation and saved the following code as "MyPackage.wl".

(* AceFEM context needs to be declared before defining my functions. *)

BeginPackage["MyPackage",{"AceFEM"}];

tensionTest::usage="tensionTest[number of elements] does simple tension test and returns force vs. displacement curve.";

Begin["Private"];

tensionTest[n_Integer]:=Module[{nstep,result}
, SMTInputData[]
"test","OL:SEPEQ1DFHYQ1NeoHooke",{"E *"->1000.,"ν *"->0.3}
]
; SMTMesh["test","Q1",{n,n},{{{0,0},{1,0}},{{0,1},{1,1}}}]
; SMTAnalysis[]
; result={{0.,0.}}
; nstep=10
; Do[
SMTNextStep["Δλ"->(1./nstep)]
; While[
SMTConvergence[10^-8,15]
, SMTNewtonIteration[];
]
; AppendTo[result
, { SMTPostData["u",{1,1}]
, Total[ SMTResidual["X"==1&] ][[1]]
}
]
, {i,1,nstep}
]
; result
]

End[];

EndPackage[];


Then I call this package from the notebook saved in the same directory. The package loads, AceFEM side window opens, but when I want to use the function tensionTest I get this strange error. I don't know why the function from the package doesn't work, because I am quite sure its syntax is correct?

Get["MyPackage.wl", Path -> NotebookDirectory[]]

tensionTest[10]


The solution is to add another (undocumented) context "AceCommon" to the list as the second argument of BeginPackage.

BeginPackage["MyPackage", {"AceFEM", "AceCommon"}];


It seems that from all AceFEM symbols used in your function only SMTInputData is not defined in "AceFEM" context. Therefore when the package is called without all other necessary contexts, the symbol SMTInputData doesn't have the correct definition, analysis doesn't get initialized properly and fails in an unexpected way.

Get["MyPackage.wl", Path -> NotebookDirectory[]]

(* {"AceCommon", "AceFEM"} *)

ListPlot[