Quiet@Remove["Global`*"];
SetDirectory[NotebookDirectory[]];
$HistoryLength=3;

data=Drop[dat=Import["scope_31.csv"],2];
Take[dat,2]
Δt=data[[2,1]]-data[[1,1]];
tStart=data[[1,1]];

nMax=Length[data];
Print["dat je ",nMax];
nTake=All;
dataU=Take[data/.{t_,i_,u_,_,_}:>{t-tStart,u},nTake];
dataI=Take[data/.{t_,_,u_,i_,_}:>{t-tStart,i},nTake];
nAV=40;
ListPlot[MovingAverage[Take[dataU,300],nAV],PlotRange->All]

ListPlot[dataI]

ListPlot[MovingAverage[Take[dataU,All],nAV],PlotRange->All]

solab=Solve[{a*t1+b==y1,a*t2+b==y2},{a,b}][[1]];
Solve[0==a*t+b/.solab,t]

Tnom=0.02;
dvojiceU=Partition[dataU,2,1];
dvojiceI=Partition[dataI,2,1];
test[{{t1_,y1_},{t2_,y2_}}]:=y1*y2<0;
prusecik[{{t1_,y1_},{t2_,y2_}}]:=((t2 y1-t1 y2)/(y1-y2));
dvojicePruchodu=Select[dvojiceI,test];
casy=prusecik/@dvojicePruchodu;
skupiny=Gather[%,Abs[#1-#2]<0.2Tnom&];
periodaI=2*Mean[Differences[Mean/@skupiny]]

test[{{t1_,y1_},{t2_,y2_}}]:=y1*y2==0;
dvojicePruchodu=Select[dvojiceU,test];
Union@Cases[dvojicePruchodu,{t_,0.}:>t,{0,∞}];
skupiny=Gather[%,Abs[#1-#2]<0.1Tnom&];
casy=Mean/@skupiny
Select[Partition[casy,3,2]/.{t1_,t2_,t3_}:>t3-t1,Abs[#-Tnom]<0.05*Tnom&]
periodaU=Mean[%];

T

T=Mean[{periodaI,periodaU}];
(*Mean[{periodaI,periodaU}];*)
myInt[f_]:=int[T]/.NDSolve[{f[t]==int'[t],int[0]==0},int,{t,0,T},MaxSteps->(10^6)][[1]];

intU=Interpolation[dataU];
intI=Interpolation[dataI];
aU[0]=0*(1/T)myInt[intU];
aI[0]=0*(1/T)myInt[intI];
aU[i_Integer]:=(2/T)*myInt[Cos[i*((2*Pi)/T)#]*intU[#]&];
aI[i_Integer]:=(2/T)*myInt[Cos[i*((2*Pi)/T)#]*intI[#]&];
bU[i_Integer]:=(2/T)*myInt[Sin[i*((2*Pi)/T)#]*intU[#]&];
bI[i_Integer]:=(2/T)*myInt[Sin[i*((2*Pi)/T)#]*intI[#]&];

nHarm=200;
nahrU=Sum[(aU[i]*Cos[i*((2*Pi)/T)t]+bU[i]*Sin[i*((2*Pi)/T)t]),{i,0,nHarm}];
nahrU>>"nahrU"

nahrI=Sum[(aI[i]*Cos[i*((2*Pi)/T)t]+bI[i]*Sin[i*((2*Pi)/T)t]),{i,0,nHarm}];
nahrI>>"nahrI"

nahrU=<<"nahrU";
nahrI=<<"nahrI";
Plot[{intU[t],nahrU},{t,0,T},PlotRange->All]
Plot[{intI[t],nahrI},{t,0,T},PlotRange->All]

tok=Integrate[nahrI,t];

ParametricPlot[{nahrU,tok},{t,0,T},AspectRatio->1,PlotRange->All,PlotStyle->{Thick,Black},AxesLabel->{"I[A]","Φ [Wb]"}]

dataopt=Select[dataI,NumericQ[#[[1]]]&&NumericQ[#[[2]]]&]

obj[a_,f_,fi_]:=Total[(dataopt[[;;,2]]-(a*Sin[2*Pi*f*#+fi]&/@dataopt[[;;,
1]]))^2]

minfrek=NMinimize[{obj[a,f,fi],f>45,a>0},{a,f,fi},Method->"DifferentialEvolution"]

1/f/.minfrek[[2]]

tok=Integrate[Interpolation[dataI][t],t]

inti=Interpolation[dataU]

testfnc[x_]:=x[[2]]<0

Select[{{2,1},{3,2},{1,4},{1,-5}},testfnc]