Remove["Global`*"]
SetDirectory[NotebookDirectory[]]

data={#,#^2}&/@Range[0,2,0.001];

ListPlot[data]

model[t_]:=a*t^2+b*t+c

ynamerene=data[[;;,2]];
ymodel = model/@data[[;;,1]];

objective=Total[(ynamerene-ymodel)^2];

(*pro tento pripad muzeme naleznout koeficienty analyticky*)

objsimp=objective//FullSimplify;

Solve[D[objsimp,#]==0&/@{a,b,c},{a,b,c}]

(*obvykle to pocitame ale numericky*)

FindMinimum[objective,{{a,0.8},{b,0.1},{c,0.1}}]

NMinimize[objective,{a,b,c}]

(*vetsina CAE ma funkce ktera hleda aproximace v WM jsou Fit a FindFit*)

Fit[data,{1,x,x^2},x]

data2={#,#^2+#^3+RandomReal[{-0.1,0.1}]}&/@Range[-2,2,0.001];

ListPlot[data]

model2[t_]:=a*t^3+b*t^2+c*t+d

ynamerene2=data2[[;;,2]];
ymodel2= model2/@data2[[;;,1]];

obj2=Total[(ynamerene2-ymodel2)^2];

res=FindMinimum[obj2,{{a,1},{b,1},{c,0.1},{d,0.}}]

model2[x]/.res[[2]]

resfit=Fit[data2,{1,x,x^2,x^3},x]

pltfit2=Plot[resfit,{x,-2,2},PlotStyle->{Blue,Thick}];Show[ListPlot[data2,PlotStyle->Red],pltfit2]

datacap=Import["data.csv"];

logdata=datacap/.{t_,u_}:>{t,Log[u]};
logfit=Fit[logdata,{1,t},t]
proklad=Exp[logfit]
U0=proklad/.t->0;
Show[Plot[proklad,{t,0,(10^(-5))},PlotStyle->Blue,PlotRange->All],ListPlot[datacap,PlotStyle->Red]]

modelcap[t_]:=u0*Exp[-t/tau]

ynamerenecap=datacap[[;;,2]];
ymodelcap=modelcap/@datacap[[;;,1]];

err=Total[(ynamerenecap-ymodelcap)^2];

(*v tomto pripade hledat minimum analyticky nevyhodne - nelinearni rovnice*)

rescap=NMinimize[err,{u0,tau}]

(*rozhodne nenasel globalni minimum*)

(*kdyz pouzivam NMinemize nebo FindMinimum mam podkontrolou metodu a pocatecny odhad*)

(*tim ze zmenim metodu najdu skutecny globalni minimum*)

rescap=NMinimize[err,{u0,tau},Method->"DifferentialEvolution"]

Show[Plot[modelcap[x]/.rescap[[2]],{x,0,10^-5},PlotRange->All],ListPlot[datacap,PlotStyle->Red]]

(*pokud prevedema tento problem na linearni pak muzeme spocitat analyticky*)
modellincap[t_]:=a*t+b

ynamerenecaplin=logdata[[;;,2]];
ymodelcaplin=modellincap/@datacap[[;;,1]];

errlin=Total[(ynamerenecaplin-ymodelcaplin)^2];

errlinsimp=FullSimplify[errlin]

lincap=modellincap[t]/.NSolve[D[errlinsimp,#]==0&/@{a,b},{a,b}][[1]]

Show[Plot[Exp[lincap],{t,0,10^-5},PlotRange->Full,PlotStyle->{Thick,Blue}],ListPlot[datacap,PlotStyle->Red]]