I wrote the following code. A user from Stack Overflow recommended me to write my code here in order to be reviewed for optimization.
How could I optimize it?
Could I have this code in a professional, better form with increased performance?
Explanation: This code calculate multiplication of three matrix in c() function. Then, using Omo as old and Omn as new into c() calculate L(). Finally, defining two if statement accept Ls which are bigger than 1 and R3 which is random number. This code is MCMC fitting data. Here I fit omn and Mn.
import numpy as np
import emcee
import matplotlib.pyplot as plt
from math import *
from scipy.integrate import quad
from scipy.integrate import odeint
O_m=chi=None
xx=np.array([0.01,0.012])
yy=np.array([32.95388698,33.87900347])
Cov=[[137,168],[28155,-2217]] # this is a covariance matrix for simplification I chose the 2*2 one
temp=1e5
z0=0
M=2
Omo = 0.3
Odo=0.7
H0=70
def ant(z, Om, Od):
return 1/sqrt(((1+z)**2)*(1+Om*z)-z*(2+z)*Od)
def dl(n, Om, Od, M):
Od=1-Om
q=quad(ant,0,xx[n],args=(Om,Od))[0]
h=5*log10((1+xx[n])*q)
fn=(yy[n]-M-h)
return fn
def c(Om, Od, M):
f_list = []
for i in range(2): # the value '2' reflects matrix size
f_list.append(dl(i,Om,Od,M))
rdag=[f_list]
rmat=[[f] for f in f_list]
a=np.dot(rdag,Cov)
b=np.dot(a,rmat)
Matrix=np.linalg.det(b)*0.000001
return Matrix
N=2000
with open('txtfile.txt', 'w') as f:
for i in range (1,N):
R1=np.random.uniform(0,1)
R2=np.random.uniform(0,1)
R3=np.random.uniform(0,1)
R4=np.random.uniform(0,1)
def delta(r1, r2):
sig=0.04
d=sig*(np.sqrt(-2*np.log(r1))*np.cos(np.radians(r2)))
return d
Omn=Omo+delta(R1, R2)
Odn=1-Omn
Mn=M+delta(R3,R4)
R3=np.random.uniform(0,1)
def L():
l=np.exp(-0.5*(c(Omn,Odn,Mn)-c(Omo,Odo,M)))
return l
if L()>1:
O_m=Omn
chi=c(Omn,Odn,Mn)
elif L()>R3:
O_m=Omn
chi=c(Omn, Odn, Mn)
f.write("{0}\t{1}\n".format(chi, O_m))
print("Minimum of chi squre is")
if chi<temp:
temp=chi
chimin=temp
print(chimin)
print(input("Press any key to exit... "))
I appreciate your help and your attention