[Python] How to use sympy codegen with expressions that contain implemented functions

Discussão em 'Python' iniciado por Stack, Junho 10, 2025.

  1. Stack

    Stack Membro Participativo

    Im trying to compile an expression that contains an UndefinedFunction which has an implementation provided. (Alternatively: an expression which contains a Symbol which represents a call to an external numerical function)

    Is there a way to do this? Either with autowrap or codegen or perhaps with some manual editing of the generated files?

    The following naive example does not work:

    import sympy as sp
    import numpy as np
    from sympy.abc import *
    from sympy.utilities.lambdify import implemented_function
    from sympy.utilities.autowrap import autowrap, ufuncify

    def g_implementation(a):
    """represents some numerical function"""
    return a*5

    # sympy wrapper around the above function
    g = implemented_function('g', g_implementation)

    # some random expression using the above function
    e = (x+g(a))**2+100

    # try to compile said expression
    f = autowrap(e, backend='cython')
    # fails with "undefined reference to `g'"


    EDIT:

    I have several large Sympy expressions

    The expressions are generated automatically (via differentiation and such)

    The expressions contain some "implemented UndefinedFunctions" that call some numerical functions (i.e. NOT Sympy expressions)

    The final script/program that has to evaluate the expressions for some input will be called quite often. That means that evaluating the expression in Sympy (via evalf) is definitely not feasible. Even compiling just in time (lambdify, autowrap, ufuncify, numba.jit) produces too much of an overhead.

    Basically I want to create a binary python extension for those expressions without having to implement them by hand in C, which I consider too error prone.

    OS is Windows 7 64bit

    Continue reading...

Compartilhe esta Página