Plot Scipy ODE solution - matplotlib

I've been trying to solve a nonlinear ordinary differential equation numerically by using Scipy, in particular by the scipy.integrate.RK23 command. It returns <scipy.integrate._ivp.rk.RK23 at 0x7f2b1a908390>. How can I plot the solution?
Thank you in advance for your help!
EDIT:
As a simple example for testing:
import numpy
import scipy.integrate
t0=0;
tf=1;
x0=numpy.array([0]);
def F(t,x): return t**2;
x=scipy.integrate.RK23(F,t0,x0,tf)

RK23 is a class that implements a way to solve an ODE, that is, it is an OdeSolver so it should not be used directly but in other functions like solve_ivp:
import numpy
from scipy.integrate import solve_ivp, RK23
import matplotlib.pyplot as plt
t0=0
tf=1
x0=numpy.array([0])
def F(t,x): return t**2
sol = solve_ivp(F, [t0, tf], x0, RK23)
print(sol)
plt.plot(sol.t, sol.y[0])
plt.show()
OdeSolver allows the developer to add custom methods without the need to rewrite scipy, but since RK23 is a classic method already implemented by scipy, you could pass just the name and scipy search for the appropriate class:
...
sol = solve_ivp(F, [t0, tf], x0, "RK23")
...

Related

Edit a figure from external function

I'm trying to edit a figure that was obtained using an external function.
For example, "nolds.lyap_r" function creates a figure. Let's say I want to add a title to it after it was plotted. How can I do it?
import nolds
import numpy as np
import matplotlib.pyplot as plt
nolds.lyap_r(y, debug_plot=True)
I guess I need to use plt.gca() or plt.gcf() but it didn't work for me:
ax=plt.gca()
ax.set_title("ABC")
pyplot.draw() is there to update the existing figure:
plt.title('A good title')
plt.draw()

Nan encountered when using numba

I am using Numba to speed up a function and I bumped into the following problem.
When using the decorator #njit (or #jit) the behaviour of some numpy function is changed.
For example if I use the following function to calculate tanh
from numba import njit
import numpy as np
#njit
def check_tanh(z):
return np.tanh(z)
and I run it for real values of z I get the same as np.tanh(z) as it should be.
If I move instead parallel to the real axis but with an imaginary part, for example z = x+ 1.j, and increase x, the numpy tanh will converge to 1.+0.j, while check_tanh(z) will return a nan (on my computer this is happening when x>360).
Does anyone have an idea of what is going on and how can be fixed?
Thanks in advance!
Using tanh from cmath fixes the issue.
Seems that is still a problem in Numba
https://github.com/numba/numba/issues/2919

Rolling multidimensional function in pandas

Let's say, I have the following code.
import numpy as np
import pandas as pd
x = pd.DataFrame(np.random.randn(100, 3)).rolling(window=10, center=True).cov()
For each index, I have a 3x3 matrix. I would like to calculate eigenvalues and then some function of those eigenvalues. Or, perhaps, I might want to compute some function of eigenvalues and eigenvectors. The point is that if I take x.loc[0] then I have no problem to compute anything from that matrix. How do I do it in a rolling fashion for all matrices?
Thanks!
You can use the analogous eigenvector/eigenvalue methods in spicy.sparse.linalg.
import numpy as np
import pandas as pd
from scipy import linalg as LA
x = pd.DataFrame(np.random.randn(100, 3)).rolling(window=10, center=True).cov()
for i in range(len(x)):
try:
e_vals,e_vec = LA.eig(x.loc[i])
print(e_vals,e_vec)
except:
continue
If there are no NaN values present then you need not use the try and except instead go for only for loop.

Use ipywidgets to interatively find best position matplotlib text

I am interested in using the interact function to use a slider to adjust the position of text in a matplotlib plot (you know, instead of adjusting the position, running the code, and repeating 1000 times).
Here's a simple example of a plot
import matplotlib.pyplot as plt
x=0.2
y=0.9
plt.text(x, y,'To move',size=19)
plt.show()
and some interact code
from __future__ import print_function
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
def f(x):
return x
interact(f, cx=0.2)
I'm wondering how I can combine these to generate a plot with the text along with a slider that will interactively move the text based on the specified value for x. Is this possible? What if I want to do the same for y?
Thanks in advance!
Here you go:
%matplotlib inline
import matplotlib.pyplot as plt
from ipywidgets import interact
def do_plot(x=0.2, y=0.9):
plt.text(x, y,'To move',size=19)
plt.show()
interact(do_plot)

How can I fit my plots from measured data?

How can I fit my plots?
Up to now, I've got the following code, which plots a variety of graphs from an array (data from an experiment) as it is placed in a loop:
import matplotlib as plt
plt.figure(6)
plt.semilogx(Tau_Array, Correlation_Array, '+-')
plt.ylabel('Correlation')
plt.xlabel('Tau')
plt.title("APD" + str(detector) + "_Correlations_log_graph")
plt.savefig(DataFolder + "/APD" + str(detector) + "_Correlations_log_graph.png")
This works so far with a logarithmic plot, but I am wondering how the fitting process could work right here. In the end I would like to have some kind of a formula or/and a graph which best describes the data I measured.
I would be pleased if someone could help me!
You can use curve_fit from scipy.optimize for this. Here is an example
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x,a):
return np.exp(a*x)
x,y,z = np.loadtxt("fit3.dat",unpack=True)
popt,pcov = curve_fit(func,x,y)
y_fit = np.exp(popt[0]*x)
plt.plot(x,y,'o')
plt.errorbar(x,y,yerr=z)
plt.plot(x,y_fit)
plt.savefig("fit3_plot.png")
plt.show()
In yourcase, you can define the func accordingly. popt is an array containing the value of your fitting parameters.