SetDirectory[NotebookDirectory[]]

Union2File=Import["Union2.dat","Table"];

SNnumber=Dimensions[Union2File][[1]]

zmax=Max[Union2File[[All,2]]]

covdeq[Om_,w_]:=NDSolve[{chi'[z]==1/Sqrt[Om*(1+z)^3+(1-Om)*(1+z)^(3*(1+w))],chi[0]==0},chi,{z,0,zmax}]

covd[z_,Om_,w_]:=(chi[z]/.covdeq[Om,w])[[1]]

covd[zmax,0.1,-0.1]

Pointnum=192

Om1=0.001
Om2=0.5
Om3=(Om2-Om1)/(Pointnum-1)

w1=-1.5
w2=-0.4
w3=(w2-w1)/(Pointnum-1)

Cchi2=Sum[1/(Union2File[[i,4]])^2,{i,1,SNnumber}]

Chi2[Om_,w_]:=Total[(5*Log[10,(1+Union2File[[All,2]])*covd[Union2File[[All,2]],Om,w]]-Union2File[[All,3]])^2/(Union2File[[All,4]])^2]-((Total[(5*Log[10,(1+Union2File[[All,2]])*covd[Union2File[[All,2]],Om,w]]-Union2File[[All,3]])/(Union2File[[All,4]])^2])^2/Cchi2);

t1=AbsoluteTime[]

chi2Tab=Monitor[Table[{Om,w,Chi2[Om,w]},{Om,Om1,Om2,Om3},{w,w1,w2,w3}],{Om,w}];

(AbsoluteTime[]-t1)/3600

chi2min=Min[Flatten[chi2Tab,1][[All,3]]]

Omm=Pick[Flatten[chi2Tab,1],Flatten[chi2Tab,1][[All,3]],chi2min][[1,1]]

wm=Pick[Flatten[chi2Tab,1],Flatten[chi2Tab,1][[All,3]],chi2min][[1,2]]

chi2interp=Interpolation[Flatten[chi2Tab,1]]

LH[Om_,w_]:=Exp[-(chi2interp[Om,w]-chi2min)/2];

LH[Omm,wm]

LHTab=Table[{Om,w,If[LH[Om,w]<Exp[-1000],Exp[-1000],LH[Om,w]]},{Om,Om1,Om2,Om3},{w,w1,w2,w3}];

Export["LikelihoodwCDM.m",LHTab]