(expr, fct, x)
return result
If a sympy 'Expr' is of the form:

    expr = expr_0 + expr_1*a_1 + ... + expr_n*a_n

    where all the a_j are noncommuting symbols in basis then

    linear_drivation(expr) = diff(expr_0, x) + diff(expr_1, x)*a_1 + ...
                             + diff(expr_n, x)*a_n + expr_1*fct(a_1, x) + ...
                             + expr_n*fct(a_n, x)
If a sympy 'Expr' is of the form:
If a sympy Expr is of the form :
def linear_derivation(expr, fct, x):
    """
    If a sympy 'Expr' is of the form:

    expr = expr_0 + expr_1*a_1 + ... + expr_n*a_n

    where all the a_j are noncommuting symbols in basis then

    linear_drivation(expr) = diff(expr_0, x) + diff(expr_1, x)*a_1 + ...
                             + diff(expr_n, x)*a_n + expr_1*fct(a_1, x) + ...
                             + expr_n*fct(a_n, x)
    """
    if expr.is_commutative:
        return diff(expr, x)
    expr = expand(expr)
    if isinstance(expr, Mul):
        x = (coefs, bases) = expr.args_cnc()
        coef = Mul(*coefs)
        return diff(coef, x) * bases[0] + coef * fct(bases[0], x)
    elif isinstance(expr, Symbol):
        return fct(expr, x)
    elif isinstance(expr, Add):
        result = S.Zero
        for arg in expr.args:
            term = arg.args_cnc()
            coef = Mul(*term[0])
            if term[1] == []:
                result += diff(coef, x)
            else:
                result += diff(coef, x) * term[1][0] + coef * fct(term[1][0], x)
    return result
def linear_derivation ( expr , fct , x ) : if expr . is_commutative : return diff ( expr , x ) expr = expand ( expr ) if isinstance ( expr , Mul ) : x = ( coefs , bases ) = expr . args_cnc ( ) coef = Mul ( * coefs ) return diff ( coef , x ) * bases [ 0 ] + coef * fct ( bases [ 0 ] , x ) elif isinstance ( expr , Symbol ) : return fct ( expr , x ) elif isinstance ( expr , Add ) : result = S . Zero for arg in expr . args : term = arg . args_cnc ( ) coef = Mul ( * term [ 0 ] ) if term [ 1 ] == [ ] : result += diff ( coef , x ) else : result += diff ( coef , x ) * term [ 1 ] [ 0 ] + coef * fct ( term [ 1 ] [ 0 ] , x ) return result