From 76c6eb0fb393dd22fee8827e3252b80ee6d19730 Mon Sep 17 00:00:00 2001 From: Marius Gerbershagen Date: Thu, 23 Sep 2021 14:28:48 +0200 Subject: [PATCH] symbolics: add derivative operator This allows for also using the syntax which sagemath already uses in the output of symbolic derivatives of functions like `D[0,1](f)(x+y,x-y)` in user input. --- src/sage/symbolic/all.py | 2 ++ src/sage/symbolic/operators.py | 62 ++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/src/sage/symbolic/all.py b/src/sage/symbolic/all.py index bad67459513..63e6b0037a8 100644 --- a/src/sage/symbolic/all.py +++ b/src/sage/symbolic/all.py @@ -18,3 +18,5 @@ from .units import units π = pi + +from .operators import D diff --git a/src/sage/symbolic/operators.py b/src/sage/symbolic/operators.py index a48b0e8e393..e8b79e980f1 100644 --- a/src/sage/symbolic/operators.py +++ b/src/sage/symbolic/operators.py @@ -194,3 +194,65 @@ def parameter_set(self): [0, 1] """ return self._parameter_set + +class DerivativeOperator(): + """ + Derivative operator. + + Acting with this operator onto a function gives a new operator (of + type :class:`FDerivativeOperator`) representing the function + differentiated with respect to one or multiple of its arguments. + + This operator takes a list of indices specifying the position of + the arguments to differentiate. For example, D[0, 0, 1] is an + operator that differentiates a function twice with respect to its + first argument and once with respect to its second argument. + + EXAMPLES:: + + sage: x, y = var('x,y'); f = function('f') + sage: D[0](f)(x) + diff(f(x), x) + sage: D[0](f)(x, y) + diff(f(x, y), x) + sage: D[0, 1](f)(x, y) + diff(f(x, y), x, y) + sage: D[0, 1](f)(x, x^2) + D[0, 1](f)(x, x^2) + + """ + class DerivativeOperatorWithParameters(): + def __init__(self, parameter_set): + self._parameter_set = parameter_set + def __call__(self, function): + return FDerivativeOperator(function, self._parameter_set) + def __repr__(self): + """ + Return the string representation of this derivative operator. + + EXAMPLES:: + + sage: D[0] + D[0] + sage: D[0, 1] + D[0, 1] + """ + return "D[%s]" % (", ".join(map(repr, self._parameter_set))) + + def __getitem__(self, args): + """ + TESTS: + + The order in which the indices are given should not matter:: + + sage: x, y = var('x,y'); f = function('f') + sage: bool(D[0, 1, 0](f)(x, y) == D[0, 0, 1](f)(x, y)) + True + sage: bool(D[1, 0, 0](f)(x, y) == D[0, 0, 1](f)(x, y)) + True + """ + if not isinstance(args, tuple): + args = (args,) + return self.DerivativeOperatorWithParameters(args) + +D = DerivativeOperator()