pythonscipynumerical-integrationdata-fitting

Minimizing a function using python for data fitting


I have a function as the following

q = 1 / sqrt( ((1+z)**2 * (1+0.01*o_m*z) - z*(2+z)*(1-o_m)) )
h = 5 * log10( (1+z)*q ) + 43.1601

I have experimental answers of above equation and once I must to put some data into above function and solve equation below

chi=(q_exp-q_theo)**2/err**2  # this function is a sigma, sigma chi from z=0 to z=1.4 (in the data file)

z, err and q_exp are in the data file(2.txt). Now I have to choose a range for o_m (0.2 to 0.4) and find in what o_m, the chi function will be minimized.

my code is:

from math import *
from scipy.integrate import quad

min = None
l = None
a = None
b = None
c = 0


def ant(z,om,od):
    return 1/sqrt( (1+z)**2 * (1+0.01*o_m*z) - z*(2+z)*o_d )


for o_m in range(20,40,1):
    o_d=1-0.01*o_m
    with open('2.txt') as fp:
        for line in fp:
            n = list( map(float, line.split()) )
            q = quad(ant,n[0],n[1],args=(o_m,o_d))[0]
            h = 5.0 * log10( (1+n[1])*q ) + 43.1601
            chi = (n[2]-h)**2 / n[3]**2
            c = c + chi
        if min is None or min>c:
            min = c
            l = o_m                            
        print('chi=',q,'o_m=',0.01*l)

n[1],n[2],n[3],n[4] are z1, z2, q_exp and err, respectively in the data file. and z1 and z2 are the integration range. I need your help and I appreciate your time and your attention. Please do not rate a negative value. I need your answers.


Solution

  • Unconcsiosely, this question overlap my other question. The correct answer is:

     from math import *
     import numpy as np
     from scipy.integrate import quad
     min=l=a=b=chi=None
     c=0
     z,mo,err=np.genfromtxt('Union2.1_z_dm_err.txt',unpack=True)
     def ant(z,o_m):            #0.01*o_m  is steps of o_m
         return 1/sqrt(((1+z)**2*(1+0.01*o_m*z)-z*(2+z)*(1-0.01*o_m)))
     for o_m in range(20,40):
         c=0
         for i in range(len(z)):
             q=quad(ant,0,z[i],args=(o_m,))[0]     #Integration o to z
             h=5*log10((1+z[i])*(299000/70)*q)+25     #function of dL
             chi=(mo[i]-h)**2/err[i]**2               #chi^2 test function
            c=c+chi
            l=o_m
            print('chi^2=',c,'Om=',0.01*l,'OD=',1-0.01*l)