简体   繁体   中英

Plotting phase portraits in Python using polar coordinates

I need a phase portrait of the following nonlinear system given in polar form...

\dot{r} = 0.5*(r - r^3)
\dot{\theta} = 1

I know how to do it in Mathematica...

field1 = {0.5*(r - r^3), 1};
p1 = StreamPlot[Evaluate@TransformedField["Polar" -> "Cartesian", field1, {r, \[Theta]} -> {x, y}], {x, -3, 3}, {y, -3, 3}, Axes -> True, StreamStyle -> Gray, ImageSize -> Large];
Show[p1, AxesLabel->{x,y}, ImageSize -> Large]

在此处输入图像描述

How can I do the same using pyplot.quiver in Python?

Just very naive implementation, but could be helpful...

import numpy as np
import matplotlib.pyplot as plt

def dF(r, theta):
    return 0.5*(r - r**3), 1

X, Y = np.meshgrid(np.linspace(-3.0, 3.0, 30), np.linspace(-3.0, 3.0, 30))
u, v = np.zeros_like(X), np.zeros_like(X)
NI, NJ = X.shape

for i in range(NI):
    for j in range(NJ):
        x, y = X[i, j], Y[i, j]
        r, theta = (x**2 + y**2)**0.5, np.arctan2(y, x)
        fp = dF(r, theta)
        u[i,j] = (r + fp[0]) * np.cos(theta + fp[1]) - x
        v[i,j] = (r + fp[0]) * np.sin(theta + fp[1]) - y

plt.streamplot(X, Y, u, v)
plt.axis('square')
plt.axis([-3, 3, -3, 3])
plt.show()

在此处输入图像描述

Correction of the previous answer:

  • From x=r*cos(theta) one gets dx = dr*cos(theta)-r*sin(theta)*dtheta = x*dr/ry*dtheta ,
  • From y=r*sin(theta) one gets dy = dr*sin(theta)+r*cos(theta)*dtheta = y*dr/r+x*dtheta ,
  • one can use the vectorized operations of numpy to avoid all loops
def dF(r, theta):
    return 0.5*r*(1 - r*r), 1+0*theta

X, Y = np.meshgrid(np.linspace(-3.0, 3.0, 30), np.linspace(-3.0, 3.0, 30))
R, Theta = (X**2 + Y**2)**0.5, np.arctan2(Y, X)
dR, dTheta = dF(R, Theta)
C, S = np.cos(Theta), np.sin(Theta)
U, V = dR*C - R*S*dTheta, dR*S+R*C*dTheta

plt.streamplot(X, Y, U, V, color='r', linewidth=0.5, density=1.6)
plt.axis('square')
plt.axis([-3, 3, -3, 3])
plt.show()

This gives the plot below. Use the density option of streamplot to increase the density of plot lines.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM