MV-7006: Python UserSub for MotionSolve
In this tutorial, you will learn how to use Python to make a user subroutine for MotionSolve and convert a model with six SFOSUBs, written in C, into a Python usersub.
Using scripting language such as Python gives you power with reduced complexity. These scripts are interpreted and do not require compiling. Therefore, you do not need a building tool to build subroutines. Furthermore, scripts are easier to read and understand, and can be used for faster prototyping.
If you do not have much programming experience, writing scripts for user-subroutines is simpler than writing C code. For a C user, the usage is even simpler. Besides following the language syntax of Python, you only need to follow the rules to convert the C code into Python scripts.
For your reference, a sample set of Python user subroutines is available in the hwsolvers\motionsolve\usersub\py_src folder.
Rules for Written Python User Subroutines
- The output arguments should be moved to the
left-hand-side.
c_datout(&istat);
becomes
istat = py_datout()
In C utility functions, the input and output arguments are combined in an argument list. In Python, the arguments of the py_* utility functions are strictly the input arguments. All output arguments should be moved to the left-side as return values of the function call.
- In C utility functions, any input or output array argument is generally followed by an
integer argument for the array size. In Python utility functions, the integer argument
for the array size is removed because it is not
necessary.
ipar[0] = (int)par[0]; ipar[1] = (int)par[1]; c_sysfnc("DM", ipar, 2, &dm, &errflg);
simply becomes[dm, errflg] = py_sysfnc("DM", [par[0],par[1]])
andipar[0] = (int)par[1]; ipar[1] = (int)par[0]; c_sysary("TDISP", ipar, 2, u1, &nstates, &errflg);
becomes[u1, errflg] = py_sysary("TDISP", [par[1],par[0]])
- Change the function name from c_* to
py_*.
c_rcnvrt(sys1, coord1, sys2, coord2, &istate);
becomes[coord2, istate] = py_rcnvrt(sys1, coord1, sys2)