Skip to content

Instantly share code, notes, and snippets.

@cswiercz
Created November 14, 2014 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cswiercz/9a0ada70fd885da73226 to your computer and use it in GitHub Desktop.
Save cswiercz/9a0ada70fd885da73226 to your computer and use it in GitHub Desktop.
Variational Derivatives in Save
def variational_derivative(expr,u):
"""Returns the variational derivative of `expr` with respect to `u`.
Variational differentiation is a linear operator so we just need to
figure out how to differentiate a product of terms.
Parameters
----------
expr : expression
u : function
Returns
-------
expression
"""
# expand the expression in a sum of terms
expr = expr.expand()
deriv = sum(_deriv_of_product(term,u) for term in expr.operands())
return deriv
def _deriv_of_product(term,u):
# for n = 0 to highest derivative order in term
# compute d/du_n term: foo = ddun(term,u,n)
# accumulate: deriv += (-1)**n * foo.deriv(x,n)
# return deriv
def ddun(f,n):
# apply product rule
if f.nops() == 1:
# return d/dun derivative of f
else:
# for factor in f:
# accumulate product rule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment