Minuit gives invalid log curve? - python

Trying to fit some data with to a log curve however my output is not valid and I don't understand what is causing the error. It's weird since this is what minuit is supose to do and it's a simple example so I don't get what the issue is.
from iminuit import Minuit
from math import pi
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def logis(x,a,b): #function to fit
return (1+x*np.log(x/b))*a
xlat=np.array([81.96100485, 64.96427609, 38.15520137, 45.75992993,
27.38344029, 23.41742996, 18.73586921, 18.07486749,
9.20589292, 4.83878931, 72.17070899, 71.08083681,
39.57647386, 31.63373626]) #xdata
lo=logis(xlat,92,30) #ydata
p=np.concatenate((np.array([92,30]),xlat,lo),axis=0) #all parameters
def chi(pa): #chisquare
chis=sum((92-pa[0:1])**2)+sum((30-pa[1:2])**2)+sum((xlat-pa[2:16])**2)+sum((lo-logis(pa[2:16],92,30))**2)
return chis
#minuit part
m = Minuit.from_array_func(chi,p,errordef=1)
fmin,para=m.migrad()
print(m.values)
print(fmin)
xn=[]
xtra=np.sort(xlat)
for i in range(2,16):
xn.append(m.values[i])
xr=np.array(xn)
#plot part
xp=np.linspace(min(xr),max(xr),14)
plt.figure(figsize=(14,8.5))
plt.plot(xp,logis(xp,m.values[0],m.values[1]))
plt.show

Related

Create 3D graph from 2 variable function that uses linear algebra to solve system of equations

So, i'm doing this project for my electromagnetism class and I need to plot a 3D graph in python. I normally plot 3d graphs using meshgrids, but the function used to calculate the value uses linear algebra, and since meshgrids are matrices, it seems to be causing some problems. Does anyone know how to work around this problem?
This is the code I made:
#Vamos importar os módulos que precisamos
from math import *
from cmath import *
from numpy import linalg
import numpy as np
import matplotlib.pyplot as plt
import math
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
from numpy import exp,arange
k=0.1
R1=0.4*3.5
R2=R1
L1=83e-6
L2=L1
C1=0.47e-6
C2=C1
Rc=10
M=k*sqrt(L1*L2)
V1=5
# the function that I'm going to plot
def CalcularTransformador(K,w):
Vp=2/pi*5
Rc=10
XL1=1j*w*L1
XL2=1j*w*L2
XC1=(-1j)/(w*C1)
XC2=(-1j)/(w*C2)
M=K*sqrt(L1*L2)
XM=1j*w*M
Z=np.array([[R1+XL1+XC1, -XM],[-XM, XL2+R2+(Rc*XC2)/(Rc+XC2)]])
V=np.array([Vp,0])
i=np.dot(linalg.inv(Z),V)
V2=i[1]*(XL2+R2+(Rc*XC2)/(Rc+XC2))
return i[0], i[1],V2
CalcularTransformador(0.1,150000)
w_angular=np.linspace(150000,260000,1000)
k=np.linspace(0,1,1000)
K,W = meshgrid(k, w_angular)
#print(K,W)
Valores = CalcularTransformador(K, W)
im = imshow(Valores,cmap=cm.RdBu)
show()

coding corelated random variables in Python

I am trying to code two random variables with a correlation. I have been given $Z_1\tilde N(0,1)$ and $Z_2\tilde N(0,1)$. I is also given $cor(Z_1,Z_2)=\rho$. So I need the formula to get $Z_2$ from $Z_1$. Initially, I was trying this code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
rho=0.5
N=100
Z1=np.random(N)
Z2=np.random(N)
return Z2
However, then I realized that $Z_2$ is now no longer correlated to $Z_1$. So I want to ask how I can get the correct $Z_2$.
Let $\alpha$ such that $\alpha^2+\rho^2 = 1$. Let $X, Y$ be independent $N(0,1)$ distributed variables. Set $Z_1 := \rho * X + \alpha * Y$ and $Z_2:=X$. Now $Z1, Z_2$ should fulfill your requirements.

how to use solve_ivp solve Partial Differential Equations with spectral method?

I want to use the spectral method to solve partial differential equations. The equations like that, formula,the initial condition is u(t=0,x)=(a^2)*sech(x),u'_t (t=0)=0.
To solve it, I use the python with the spectral method. Following is the code,
import numpy as np
from scipy.integrate import solve_ivp
from scipy.fftpack import diff as psdiff
#RHS of equations
def f(t,u):
uxx= psdiff(u[N:],period=L,order=2)
du1dt=u[:N]
du2dt =a**2*uxx
dudt=np.append(du1dt,du2dt)
return dudt
a=1
amin=-40;bmax=40
L=bmax-amin;N=256
deltax=L/N
x=np.arange(amin,bmax,deltax)
u01 = 2*np.cosh(x)**(-1)
u02=np.zeros(N)
# y0
inital=np.append(u01,u02)
sola1 = solve_ivp(f, t_span=[0,40],y0=inital,args=(a,))
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(x,sola1.y[:N,5])
plt.show()
Following is my expected result,
expected result.
My python code can run,but I can't get the expected result,and can't find the problem.Following is the result from my python code,
my result
-----------------------------Update----------------------------------------------
I also try a new code,but still can't solve
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from scipy.fftpack import diff as psdiff
from itertools import chain
def lambdifide_odes(y,t,a):
# uxx =- (1j)**2*k**2*u[:N]
u1=y[::2]
u2=y[1::2]
dudt=np.empty_like(y)
du1dt=dudt[::2]
du2dt=dudt[1::2]
du1dt=u2
uxx=psdiff(u1,order=2,period=L)
du2dt=a**2*uxx
return dudt
a=1
amin=-40;bmax=40
L=bmax-amin;N=256
deltax=L/N
x=np.arange(amin,bmax,deltax)
u01 = 2*np.cosh(x)**(-1)
u02=np.zeros(N)
initial=np.array(list(chain.from_iterable(zip(u01,u02))))
t0=np.linspace(0,40,100)
sola1 = odeint(lambdifide_odes,y0=initial,t=t0,args=(a,))
fig, ax = plt.subplots()
ax.plot(x,sola1[20,::2])
plt.show()
You have some slight problem with the design of your state vector and using this in the ODE function. The overall intent is that u[:N] is the wave function and u[N:] its time derivative. Now you want the second space derivative of the wave function, thus you need to use
uxx= psdiff(u[:N],period=L,order=2)
at the moment you use the time derivative, making this a mixed third derivative that does not occur in the equation.

python - What produces the same plot as autocorrelation_plot()?

I need the values of the autocorrelation coefficients coming from the autocorrelation_plot(). The problem is that the output coming from this function is not accessible, so I need another function to get such values. That's why I used acf() from statsmodels but it didn't get the same plot as autocorrelation_plot() does. Here is my code:
from statsmodels.tsa.stattools import acf
from pandas.plotting import autocorrelation_plot
import matplotlib.pyplot as plt
import numpy as np
y = np.sin(np.arange(1,6*np.pi,0.1))
plt.plot(acf(y))
plt.show()
So the result is not the same as this:
autocorrelation_plot(y)
plt.show()
This seems to be related to the nlags parameter of acf:
nlags: int, optional
Number of lags to return autocorrelation for.
I don't know what exactly this does but in the source of acf there is a slicing
that shortens the array:
avf = acovf(x, unbiased=unbiased, demean=True, fft=fft, missing=missing)
acf = avf[:nlags + 1] / avf[0]
If you use statsmodels.tsa.stattools.acovf directly the result is the same as with autocorrelation_plot:
avf = acovf(x, unbiased=unbiased, demean=True, fft=fft, missing=missing)
So you can call it like
plt.plot(acf(y, nlags=len(y)))
to make it work.
An explanation of lag: https://math.stackexchange.com/questions/2548314/what-is-lag-in-a-time-series/2548350

Defining a function to call within axScatter.plt

I'm currently working on defining a mathematical function, i.e.,
from numpy import tanh
def stravinska(Z, eps=0.5):
return ((-0.86928)+(0.052481*Z))*(tanh(((2.66503)-(4.44255*Z))))-1.251617
SII = np.linspace(-3.0, 0.20)
To call within
axScatter_middle.plot(SII, stravinska(Z=0.5), '-k')
However, the following error is return upon compilation:
ValueError: x and y must have same first dimension
I'm scratching my head as to where I have gone wrong as I have used this method successfully many times before. What does this error mean and how can I rectify this problem?
I'm essentially trying to plot the equation 10 from this paper: Semi-empirical analysis of Sloan Digital Sky Survey galaxies – III. How to distinguish AGN hosts
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from numpy import tanh
def stravinska(log_SII_Ha, eps=0):
strav = ((-30.787)+(1.1358*(log_SII_Ha))+(0.27297*((log_SII_Ha)**2)))*(tanh(5.7409* (log_SII_Ha)))-31.093
return strav
SII = np.linspace(-3.0, 0.20)
axScatter_middle.plot(SII, stravinska(SII), '-k')

Categories

Resources