Skip to content

Generate code for MATLAB, and DE All BUGS #46

@WangY18

Description

@WangY18
  • Modify sympybotics/symcode/subexprs.py, Line 142
if sympy.utilities.iterables.iterable(expr):
    return expr
  • Add gen_matlab_func to sympybotics/symcode/generation.py
def _mcode(expr):
    code = sympy.printing.octave.OctaveCodePrinter().doprint(expr)
    if options.get('unroll_square', False):
        code = re.sub(r'(\w+)\s*\.\^\s*2', r'(\1).*(\1)', code)
    return code


def gen_matlab_func(code, out_parms, func_parms, func_name='func'):
    indent = 4 * ' '

    out_str = ', '.join(out_parms) if len(out_parms) > 1 else out_parms[0]
    in_str = ', '.join(func_parms)

    mcode = f'function [{out_str}] = {func_name}({in_str})\n\n'

    mcode += code_to_string(code, out_parms, _mcode, indent, '', '')

    mcode += '\nend\n'

    mcode = mcode.replace('\n\n', '\n% \n')

    return mcode

We get

function [tau_out] = tau(parms, q, dq, ddq)
% 
    x0 = -ddq[0]
    x1 = sin(q[1])
    x2 = dq[0]
    x3 = x1.*x2
    x4 = -x3
    x5 = cos(q[1])
    x6 = -x0
    x7 = dq[1].*x4 + x5.*x6
    x8 = x2.*x5
    x9 = dq[1].*x8 + x1.*x6
    x10 = dq[1].*parms[16] + parms[14].*x8 + parms[17].*x3
    x11 = 9.81*x1
    x12 = dq[1].*parms[15] + parms[13].*x8 + parms[16].*x3
    x13 = dq[1].*parms[13] + parms[12].*x8 + parms[14].*x3
    x14 = 9.81*x5
% 
    tau_out[0] = parms[10].*sign(dq[0]) + parms[11] - parms[3].*x0 + x1.*(ddq[1].*parms[16] - dq[1].*x13 + parms[14].*x7 + parms[17].*x9 - parms[19].*x14 + x12.*x8) + x5.*(ddq[1].*parms[13] + dq[1].*x10 + parms[12].*x7 + parms[14].*x9 + parms[19].*x11 + x12.*x4)
    tau_out[1] = ddq[1].*parms[15] + parms[13].*x7 + parms[16].*x9 - parms[18].*x11 + parms[20].*x14 + parms[22].*sign(dq[1]) + parms[23] - x10.*x8 + x13.*x3
% 
end
  • Line 57-59, dynamics.py
self.Pb = sympy.Matrix(numpy.array(Pb).tolist()).applyfunc(lambda x: x.nsimplify())
self.Pd = sympy.Matrix(numpy.array(Pd).tolist()).applyfunc(lambda x: x.nsimplify())
self.Kd = sympy.Matrix(numpy.array(Kd).tolist()).applyfunc(lambda x: x.nsimplify())
  • robotmodel.py, def calc_base_parms, modify:
global sin, cos, sign
sin = numpy.sin
cos = numpy.cos
sign = numpy.sign

l = locals()
exec_(func_def_regressor, globals(), l)

as

import math
global sin, cos, sign
sin = math.sin
cos = math.cos
sign = numpy.sign

l = locals()
# exec_(func_def_regressor, globals(), l)
exec_(func_def_regressor, {'math': math, 'sin': sin, 'cos': cos, 'sign': sign}, l)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions