Calculating partial derivatives python - python

I am little bit confused how to calculate the partial derivatives of sigmoid function in python. Since in general we can calculate that by using the given code:
Example: f(x,y) = x4 + x * y4
w.r.t x. would be then :
import sympy as sym
#Derivatives of multivariable function
x , y = sym.symbols('x y')
f = x4+x*y4
#Differentiating partially w.r.t x
derivative_f = f.diff(x)
derivative_f
how would the code work for partial derivatives of this then:
I tried to sub to the same function but I think I am doing something incorrectly

Related

how to take derivative with respect to two variables?

Imagine we have a function like f(xy), how can one can take derivatives with respect to xy in python?
I tried to rename u=x*y and take derivative with respect to u, but it apparently doesn't work.
from sympy import symbols, diff
x, y, z = symbols('x y z', real=True)
f = 4*x*y + x*sin(z) + x**3 + z**8*y
u=x*y
diff(f, x)
and for one step further how can we do that if we don't have the exact definition of f(x*y)?
thank you.

Having trouble with using sympy subs command when trying to solve a function at an x value of 0

I have a function [ -4*x/sqrt(1 - (1 - 2*x^2)^2) + 2/sqrt(1 - x^2) ] that I need to evaluate at x=0. However, whenever you graph this function, for some interval of y there are many y-values at x=0. This leads me to think that the (subs) command can only return one y-value. Any help or elaboration on this? Thank you!
Here's my code if it might help:
x = symbols('x')
f = 2*asin(x) # f(x) function
g = acos(1-2*x**2) # g(x) function
eq = diff(f-g) # evaluating the derivative of f(x) - g(x)
eq.subs(x, 0) # substituting 0 for x in the derivative of f(x) - g(x)
After I run the code, it returns NaN, which I assume is because substituting in 0 for x returns not a single number, but a range of numbers.
Here is the graph of the function to be evaluated at x=0:
You should always give SymPy as many assumptions as possible. For example, it can't pull an x**2 out of a sqrt because it thinks x is complex.
A factorization an then a simplification solves the problem. SymPy can't do L'Hopital on eq = A + B since it does not know that both A and B converge. So you have to guide it a little by bringing the fractions together and then simplifying:
from sympy import *
x = symbols('x', real=True)
f = 2*asin(x) # f(x) function
g = acos(1-2*x**2) # g(x) function
eq = diff(f-g) # evaluating the derivative of f(x) - g(x)
eq = simplify(factor(eq))
print(eq)
print(limit(eq, x, 0, "+"))
print(limit(eq, x, 0, "-"))
Outputs:
(-2*x + 2*Abs(x))/(sqrt(1 - x**2)*Abs(x))
0
4
simplify, factor and expand do wonders.

Define a function that calculates the partial derivative of another function

I have learned how to automatically find the partial derivative of a function with sympy. My problem is, I need to define a new function that returns the partial derivative of the other function.
from sympy import Symbol, Derivative
y= Symbol('y')
function = y ** 2
deriv = Derivative(function, y).doit()
def func(y):
return deriv
Something like that. Hope you all understood. Thanks!
So y is another function as in predefined like y = Symbol('x') ** 2? I believe your function need another input.
x = Symbol('x')
y = x ** 2
def func(function, symbol):
deriv = Derivative(function, symbol).doit()
return deriv
derivative = func(y, x)
You can't do it without specifying symbol - especially since this is partial derivative you need to tell which symbol it's trying to derive against.

Finding equilibria of ODE as a function of initial conditions

Let us assume I have an ODE with x'(t) = f(x) with the respective solution x(t) = ϕ(x(0),t) of a initial condition x(0). Now I intend to calculate numerically the equilibria as a function of their initial condition: eq(x0) := ϕ(x0, ∞). The ODEs are such that these equilibria exist unambiguously for all initial conditions (including eq = ∞).
My poor man's approach would be to integrate the ODE up to a late time and fetch that value (for brevity I do not show the plotting):
import numpy as np
from scipy.integrate import odeint
# ODE
def func(X,t):
return [ X[2]**2 * (X[0] - X[1]),
X[2]**3 * (X[0] + 3 * X[1]),
-X[2]**2]
# Forming a grid
n = 15
x0 = x1 = np.linspace(0,1,n)
x0_,x1_ = np.meshgrid(x0,x1)
eq = np.zeros([n,n,3])
t = np.linspace(0,100,1000)
x2 = 1
for i in range(n):
for j in range(n):
X = odeint(func,[x0_[j,i],x1_[j,i],x2], t)
eq[j,i,:] = X[-1,:]
Naive example above:
The problem with that approach is that you can never be sure if it converged. I know that you can just find the roots of f(x), but this would not yield the equilibria as a function of their initial conditions (You could trace them back, but since this function is not injective, you will not find values for all initial values). I somehow need a ODE solver which integrates until an equilibria is reached (or stops integrating if it goes beyond a limit). Do you have any ideas?

How to create a random variable whose parameters are themselves random variables in SymPy?

I have a random variable Y whose distribution is Poisson with parameter that is itself a random variable X, which is Poisson with parameter 10.
How can I use SymPy to automatically calculate the covariance between X and Y?
The code
from sympy.stats import *
x1 = Poisson("x1", 3)
x2 = Poisson("x2", x1)
print(covariance(x2,x1))
raises an error
ValueError: Lambda must be positive
The documentation is not clear to me on this matter, and playing around with the function given did not seem to work.
This kind of manipulation is not implemented in SymPy. But you can pass a symbol (z1 below) for the parameter of a distribution. Then after the first step of computation, replace z1 by x1 and take expected value.
from sympy import Symbol
from sympy.stats import Poisson, E
z1 = Symbol("z1")
x1 = Poisson("x1", 3)
x2 = Poisson("x2", z1)
Ex2 = E(E(x2).subs(z1, x1))
Vx2 = E(E((x2-Ex2)**2).subs(z1, x1))
cov = E(E((z1-E(x1))*(x2-Ex2)).subs(z1, x1))
print("E(x2) = {}, var(x2) = {}, cov(x1, x2) = {}".format(Ex2, Vx2, cov))
Output:
E(x2) = 3, var(x2) = 6, cov(x1, x2) = 3
Notice the appearance of Ex2 instead of E(x2) in the formulas for variance and covariance. Using E(x2) here would give incorrect results because E(x2) is an expression involving z1. For the same reason I'm not using variance or covariance functions (as they'd involve the variable E(x2) instead of the correct value 3), expressing everything explicitly as an expected value.

Categories