Search code examples
sympysymbolic-math

Sympy diffgeom: Metric dependent on function


I'm having problems defining a metric using sympy's diffgeom package, where the metric depends on a function f(x,y).

I get the error ValueError: Can't calculate 1st derivative wrt x.

import sympy as sym
from sympy.diffgeom import Manifold, Patch, CoordSystem

m = Manifold("M",2)
patch = Patch("P",m)
cartesian = CoordSystem("cartesian", patch, ["x", "y"])
x, y = cartesian.coord_functions()
f = sym.Function('f')
xi = sym.Symbol('xi')

g = sym.Matrix([
    [ xi + sym.diff(f,x)**2         , sym.diff(f,x) * sym.diff(f,y) ],
    [ sym.diff(f,x) * sym.diff(f,y) , xi + sym.diff(f,y)**2 ]   
])

I have a feeling it's because of how x and y are defined, but I haven't been able to figure it out.


Solution

  • Indeed, differentiation with respect to these x and y (objects of class sympy.diffgeom.diffgeom.BaseScalarField) is not supported. You can see this by accessing the internal property _diff_wrt which indicates if something can be a thing with respect to which to differentiate.

    >>> x._diff_wrt
    False
    

    Do those derivative (with respect to a scalar field) make mathematical sense here? I'm not sure.

    An additional issue is that SymPy does not differentiate functions, so

    f = Function('f')
    diff(f, x) 
    

    is always an error. SymPy can differentiate expressions, e.g., diff(f(x, y), x).

    Aside: diff can be used as a method of an expression, which in your case would result in shorter code, like f(x, y).diff(x).