# Statistika a úprava vstupních dat 
# Martin Radvansky
# Diplomová práce 2022
# verze R 4.1.2

# Z jednotlivych krivek vybere pouze okamzik jednotkoveho skoku a 15 sekund,
# probehne prevzorkovani dat - leva a praha zatacka, vystupem je csv soubor, s levyma, pravyma zatackama, 


#Importy knihoven
library(gmodels)
library(Rmisc)
library(car)
library(effsize)
library(pwr)
library(MKpower)

#pomocne utility
source("Utils.R")

docdir <-"documents_long"

#Definice atributu -------------------------------------------------------------
delkaReg<-15000  #pocet ms po ktere bereme dej regulace
ResampleTime<-20 #cas mezi vzorky pro Resampling
atrTime<-"Time_ms" #atribut obsahujici cas
atrSplineDst<-"SplineDistance" #atribut obsahujici vzdalenost od stredu pruhu
atrTimeStep <- "TimeFromStep"
atrPoloha <- "X_pos"
atrPolohaY <- "Y_pos"
time_axis <- seq(from=0,to=delkaReg,by=ResampleTime) #Casova osa po resamplingu


#Vstupni soubor dat mereni
soubor<-"./data/90a_08092021_step.csv"

#nacteni vsech souboru
soubory <- list.files("./data_long/",".csv",all.files = T, full.names = T)
nazvySloupcu<-c(atrTime,atrPoloha,atrPolohaY,atrSplineDst,"Velocity","WheelAngle","HeartBeat_ms","Zero")
#vyjimky<-c("103","110","116","123")#4,11,17,24
vyjimky<-c()

cx<-1
rec<-1
saveImg<-T
showImg<-T
saveData<-T
#data reakci
dfTotalTimes<-data.frame(RID=numeric(), DataName=character(), Zatacka=character(),  
                         Reakce=numeric(), Ustaleni=numeric(), 
                         MinVal=numeric(), MaxVal=numeric(), Rozdil=numeric(),
                         stringsAsFactors = F)
slTimes<-c("RID","DataName","Zatacka","Reakce","Ustaleni","MinVal","MaxVal","Rozdil")

#data prumeru
dfTotalMeans<-data.frame(RID=numeric(), DataName=character(), Zatacka=character(), stringsAsFactors = F);
slMeans<-c("RID","DataName","Zatacka")
rowix<-1
rowTot<-1
ListTotalDataR<-list()
ListTotalDataL<-list()
for (s in soubory)
{
  data_s<-read.csv2(s,header = F, sep = ";", na.strings=c("","NA"), dec=".",skip = 1) #preskocime radek s headerem a udelame svuj
  colnames(data_s)<-nazvySloupcu
  data_s$TimeFromStep<-NA
  if (s = "./data_long/203_21032022_step_02.csv")
  {
    data_s <- data_s[60000:140000,]
  }
  
  #eliminace pokud bude restart
  if (min(diff(data_s$Time_ms))<0){
    next  #pokud je rozil zaporny doslo k restartu v programu a tedy tento soubor vynechame
  }
  
  #eliminace vyjimek - divna data
  if (substring(basename(s),1,3) %in% vyjimky) {
    next
  }
  
  jmenoF_bezExt<-fs::path_ext_remove(basename(s))
  message("Soubor: (",cx,") : ",s)
  #zobrazeni RAW dat
  if(showImg)
  {
    if(saveImg){
      png(file=sprintf("./%s/%s%s.png",docdir,jmenoF_bezExt,"_RAW")) #,width=600, height=350)
    }
    ZobrazRawData(data_s,s,atrVzdalenost = atrSplineDst, atrCas = atrTime, atrPoloha =  atrPoloha, Uhel=T)
    #ZobrazRawData(data_s,s,atrVzdalenost = atrSplineDst, atrCas = atrTime, atrPoloha =  atrPoloha, Uhel=F)
    par(mar = c(4, 4, 0.3, 0.3))  
    ZobrazRawData(data_s,s,atrVzdalenost = atrSplineDst, atrCas = atrTime, atrPoloha =  atrPoloha, Uhel=T,
        p1ml = NULL, p2ml=NULL, p3ml=NULL, p4ml=NULL, p3xl="Vzorek",
        p1yl = "Pozice", p2yl = "Pozice", p4yl= "Ůhel [\u00B0]",p3yl="Vzdálenost spline [m]")
    if(saveImg){
      dev.off()
    }
    par(mar = c(5.1, 4.1, 4.1, 2.1))    # Default space
  }
  
  #index hodnot kde je inflexni box
  startIx<-Get_StepIndex(data_s[,atrSplineDst])  #- cislo je doleva
  #seznam indexu konce regulace def 15s
  indexT<-Get_RawIndexLen(data_s, startIx, atrTime, delkaReg)
  
  #musime mit stejny pocet start a stop indexu
  if (length(startIx)>length(indexT))
  {
    startIx<-startIx[1:length(indexT)]
  }
  
  if(showImg)
  {
    if(saveImg){
      png(file=sprintf("./%s/%s%s.png",docdir,jmenoF_bezExt,"_RAW_peaks")) #,width=600, height=350)
    }
    #Show_RawTimeReg(data_s, startIx, indexT, atrSplineDst)
    Show_RawTimeReg(data_s, startIx, indexT, atrSplineDst,labmain = NULL, labx = "Vzorek", laby = "Vzdálenost spline [m]")
    if(saveImg){
      dev.off()
    }
  }
    
  #Rozhozeni na leve(-) a prave zatacky(+)
  skokyLR<-DivideDataLR(data_s,startIx,atrTime, delkaReg, atrTimeStep)
  
  #Provede resampling dat
  ResampledDataL<-lapply(skokyLR[["L"]],FUN=function(v){DoInterpolace(v,showchart=FALSE,sampleTime=ResampleTime)})
  ResampledDataR<-lapply(skokyLR[["R"]],FUN=function(v){DoInterpolace(v,showchart=FALSE,sampleTime=ResampleTime)})
  
  ResampledWheelL<-lapply(skokyLR[["L"]],FUN=function(v){DoInterpolace(v,atrDst="WheelAngle",showchart=FALSE,sampleTime=ResampleTime)})
  ResampledWheelR<-lapply(skokyLR[["R"]],FUN=function(v){DoInterpolace(v,atrDst="WheelAngle", showchart=FALSE,sampleTime=ResampleTime)})
  
  ResampledPosXL<-lapply(skokyLR[["L"]],FUN=function(v){DoInterpolace(v,atrDst="X_pos",showchart=FALSE,sampleTime=ResampleTime)})
  ResampledPosXR<-lapply(skokyLR[["R"]],FUN=function(v){DoInterpolace(v,atrDst="X_pos", showchart=FALSE,sampleTime=ResampleTime)})
  
  
  #dataFramy po skupinach resampled
  sk_df<-1 #allRL
  list_dfRL<-Get_ResampletDF(ResampledDataL, ResampledDataR, NULL, NULL, NULL, NULL, sk_df)
  sk_df<-2 #allL
  list_dfL<-Get_ResampletDF(ResampledDataL, ResampledDataR, NULL, NULL, NULL, NULL, sk_df)
  sk_df<-3 #allR
  list_dfR<-Get_ResampletDF(ResampledDataL, ResampledDataR, NULL, NULL, NULL, NULL, sk_df)
  
  #Celkove vsechny krivky vlevo a vpravo
  ListTotalDataR[[rowTot]]<-list_dfR[[1]]
  ListTotalDataL[[rowTot]]<-list_dfL[[1]]
  rowTot<-rowTot+1
  
  #Prumerne krivky
  
  df_colmeansRL <- Get_ColMeans(list_dfRL,1:length(time_axis))
  df_colmeansL <- Get_ColMeans(list_dfL,1:length(time_axis))
  df_colmeansR <- Get_ColMeans(list_dfR,1:length(time_axis))
  
  #prumery a konfidencni intervaly
  
  CI_MeanRL<-Get_MeansCI(list_dfRL,1:length(time_axis))
  CI_MeanL<-Get_MeansCI(list_dfL,1:length(time_axis))
  CI_MeanR<-Get_MeansCI(list_dfR,1:length(time_axis))
     
  if(saveData)
  {
    write.csv2(CI_MeanRL[[1]],file = sprintf("./%s/%s%s.csv",docdir,jmenoF_bezExt,"_MeansRL"),
               col.names = T, row.names = F, sep =";", dec = ".", quote = F)
    write.csv2(CI_MeanR[[1]],file = sprintf("./%s/%s%s.csv",docdir,jmenoF_bezExt,"_MeansR"),
               col.names = T, row.names = F, sep =";", dec = ".", quote = F)
    write.csv2(CI_MeanL[[1]],file = sprintf("./%s/%s%s.csv",docdir,jmenoF_bezExt,"_MeansL"),
               col.names = T, row.names = F, sep =";", dec = ".", quote = F)
  }
  
  #Nastaveni dataframe struktury pro prumery
  # if(ncol(dfTotalMeans)<100){
  #   dfTotalMeans<-cbind(dfTotalMeans,as.data.frame(t(data_reakce))[0,])  
  # }
  # 
  # dfTotalMeans[rowix,]<-c(rowix,jmenoF_bezExt,"A",CI_MeanRL[[1]][2,])
  # rowix<-rowix+1
  # dfTotalMeans[rowix,]<-c(rowix,jmenoF_bezExt,"R",CI_MeanR[[1]][2,])
  # rowix<-rowix+1
  # dfTotalMeans[rowix,]<-c(rowix,jmenoF_bezExt,"L",CI_MeanL[[1]][2,])
  # rowix<-rowix+1
  
  
  #vizualizace krivek
  if(showImg)
  {
    if(saveImg){
      png(file=sprintf("./%s/%s%s.png",docdir,jmenoF_bezExt,"_Means")) #,width=600, height=350)
    }
    par(mfrow=c(3,1))
    Show_Means( vstup = df_colmeansRL, xaxis = time_axis,descr = "Vsechny zatacky RL", sloupce = 1:length(time_axis) )
    Show_Means( vstup = df_colmeansR, xaxis = time_axis,descr = "Vsechny zatacky R", sloupce = 1:length(time_axis) )
    Show_Means( vstup = df_colmeansL, xaxis = time_axis,descr = "Vsechny zatacky L", sloupce = 1:length(time_axis) )
    par(mfrow=c(1,1)) 
    if(saveImg){
      dev.off()
    }
  } 
  
  if(showImg)
  {
    if(saveImg){
      png(file=sprintf("./%s/%s%s.png",docdir,jmenoF_bezExt,"_MeansCI")) #,width=600, height=350)
    }
    
    par(mar = c(4, 4, 0.3, 0.3)) 
    par(mfrow=c(3,1))
    Show_MeanCI(vstup=CI_MeanRL,xaxis = time_axis,descr = "",okno=F, barva = "darkgreen", legenda=T,showX = F,
                laby = "Vzdálenost spline [m]", leglab = "Oba směry")
    Show_MeanCI(vstup=CI_MeanL,xaxis = time_axis,descr = "",okno=F, barva = "red", legenda=T,showX = F,laby = "Vzdálenost spline [m]",
                leglab = "Doleva")
    Show_MeanCI(vstup=CI_MeanR,xaxis = time_axis,descr = "",okno=F, barva = "blue", legenda=T,labx = "Čas [ms]", 
                laby = "Vzdálenost spline [m]", leglab = "Doprava")
    par(mfrow=c(1,1)) 
    par(mar = c(5.1, 4.1, 4.1, 2.1))    # Default space
    
    if(saveImg){
      dev.off()
    }
  } 
  
  if(showImg)
  {
    if(saveImg){
      png(file=sprintf("./%s/%s%s.png",docdir,jmenoF_bezExt,"_MeansRLCI")) #,width=600, height=350)
    }  
    #Show_Mean2CI(CI_MeanL, CI_MeanR, xaxis=time_axis, "Zatacky L a R", "Leva", "Prava", okno=F)
    Show_Mean2CI(CI_MeanL, CI_MeanR, xaxis=time_axis, mainlbl = NULL, descrA = "Doleva", descrB = "Doprava", okno=F,xlbl = "Čas [ms]", ylbl = "Vzdálenost spline [m]",showLegend = T)
    if(saveImg){
      dev.off()
    }
  }     
  
  #zobrazeni vstupnich dat
  if(showImg)
  {
    if(saveImg){
      png(file=sprintf("./%s/%s%s.png",docdir,jmenoF_bezExt,"_MeansTurns")) #,width=600, height=350)
    }  
    par(mar = c(4, 4, 0.3, 0.3)) 
    par(mfrow=c(3,1)) 
    Show_TurnAndMean(vstup=list_dfRL,prumer=CI_MeanRL,xaxis = time_axis, sloupce=1:length(time_axis), 
                     descr = "",okno=F, bmean="darkgreen", showX = F, losaX="", losaY="Vzdálenost spline [m]")
    Show_TurnAndMean(vstup=list_dfR,prumer=CI_MeanR,xaxis = time_axis, sloupce=1:length(time_axis), 
                     descr = "",okno=F, bmean="darkblue", showX = F, losaX="", losaY="Vzdálenost spline [m]")
    Show_TurnAndMean(vstup=list_dfL,prumer=CI_MeanL, xaxis = time_axis, sloupce=1:length(time_axis), 
                     descr = "",okno=F, bmean="darkred",losaX="Čas [ms]", losaY="Vzdálenost spline [m]")    
    par(mfrow=c(1,1)) 
    par(mar = c(5.1, 4.1, 4.1, 2.1))    # Default space
    if(saveImg){
      dev.off()
    }
  }   
  
  #Vsechny response a ustaleni pro prumery
  data_reakce<-CI_MeanRL[[1]][2,]
  
  #zjisteni Response time
  df.tr<-Get_Resp_Ustal(vstup = data_reakce, procZM = 0.1, casVzorku = ResampleTime)
  
  #"RID","DataName","Zatacka","Reakce","Ustaleni","MinVal","MaxVal","Rozdil"
  dfTotalTimes[rec,]<-c(rec,jmenoF_bezExt,"A",
                        as.numeric(df.tr[1,"IxReakce"]),
                        as.numeric(df.tr[1,"IxUstaleni"]),
                        as.numeric(df.tr[1,"MinDst"]),
                        as.numeric(df.tr[1,"MaxDst"]),
                        as.numeric(df.tr[1,"Zmena"]))
  rec<-rec+1
  
  if(saveData)
  {
    write.csv2(df.tr,file = sprintf("./%s/%s%s.csv",docdir,jmenoF_bezExt,"_reakceRL"),
               col.names = T, row.names = F, sep =";", dec = ".", quote = F)
  }
  
  #zobrazeni nalezenych casu na krivce
  if(showImg)
  {
    if(saveImg){
      png(file=sprintf("./%s/%s%s.png",docdir,jmenoF_bezExt,"_ReactionRL")) #,width=600, height=350)
    }
    Show_ResponseTime(vstup=data_reakce, timeaxe=time_axis, casR=df.tr[1,1], 
                      casU=df.tr[1,2], zmn=df.tr[1,5], vzdMin=df.tr[1,3], vzdMax=df.tr[1,4], 
                      popis="mean RL", show_val=T, okno=F)
    if(saveImg){
      dev.off()
    }
  }
  
  data_reakce<-CI_MeanR[[1]][2,]
  #zjisteni Response time
  df.tr<-Get_Resp_Ustal(vstup = data_reakce, procZM=0.1, casVzorku = ResampleTime)
  
  #"RID","DataName","Zatacka","Reakce","Ustaleni","MinVal","MaxVal","Rozdil"
  dfTotalTimes[rec,]<-c(rec,jmenoF_bezExt,"R",
                        as.numeric(df.tr[1,"IxReakce"]),
                        as.numeric(df.tr[1,"IxUstaleni"]),
                        as.numeric(df.tr[1,"MinDst"]),
                        as.numeric(df.tr[1,"MaxDst"]),
                        as.numeric(df.tr[1,"Zmena"]))
  rec<-rec+1
  
  if(saveData)
  {
    write.csv2(df.tr,file = sprintf("./%s/%s%s.csv",docdir,jmenoF_bezExt,"_reakceR"),
               col.names = T, row.names = F, sep =";", dec = ".", quote = F)
  }
  
  
  #zobrazeni nalezenych casu na krivce
  if(showImg)
  {
    if(saveImg){
      png(file=sprintf("./%s/%s%s.png",docdir,jmenoF_bezExt,"_ReactionR")) #,width=600, height=350)
    }
    Show_ResponseTime(vstup=data_reakce, timeaxe=time_axis, casR=df.tr[1,1], 
                      casU=df.tr[1,2], zmn=df.tr[1,5], vzdMin=df.tr[1,3], vzdMax=df.tr[1,4], 
                      popis="mean R", show_val=T, okno=F)
    if(saveImg){
      dev.off()
    }
  }
    
  data_reakce<-CI_MeanL[[1]][2,]
  #zjisteni Response time
  df.tr<-Get_Resp_Ustal(vstup = data_reakce, procZM=0.1, casVzorku = ResampleTime)
  
  #"RID","DataName","Zatacka","Reakce","Ustaleni","MinVal","MaxVal","Rozdil"
  dfTotalTimes[rec,]<-c(rec,jmenoF_bezExt,"L",
                        as.numeric(df.tr[1,"IxReakce"]),
                        as.numeric(df.tr[1,"IxUstaleni"]),
                        as.numeric(df.tr[1,"MinDst"]),
                        as.numeric(df.tr[1,"MaxDst"]),
                        as.numeric(df.tr[1,"Zmena"]))
  rec<-rec+1
  
  if(saveData)
  {
    write.csv2(df.tr,file = sprintf("./%s/%s%s.csv",docdir,jmenoF_bezExt,"_reakceL"),
               col.names = T, row.names = F, sep =";", dec = ".", quote = F)
  }
  
  #zobrazeni nalezenych casu na krivce
  if(showImg)
  {
    if(saveImg){
      png(file=sprintf("./%s/%s%s.png",docdir,jmenoF_bezExt,"_ReactionL")) #,width=600, height=350)
    }
    Show_ResponseTime(vstup=data_reakce, timeaxe=time_axis, casR=df.tr[1,1], 
                      casU=df.tr[1,2], zmn=df.tr[1,5], vzdMin=df.tr[1,3], vzdMax=df.tr[1,4], 
                      popis=NULL, show_val=T, okno=F, labx = "Čas [ms]", laby = "Vzdálenost spline [m]",
                      offU = -1250, offR = 1000)
    
    if(saveImg){
      dev.off()
    }
  }  
  par(mfrow=c(1,1)) 
  cx<-cx+1
}#for s soubory***********************

#Ulozeni casu pro reakce souhrnne
if(saveData)
{
  write.csv2(dfTotalTimes,file = sprintf("./%s/%s.csv",docdir,"VsechnyReakce"),
             col.names = T, row.names = F, sep =";", dec = ",", quote = F)
}

if(saveData)
{
  write.csv2(dfTotalMeans,file = sprintf("./%s/%s.csv",docdir,"VsechnyPrumery"),
             col.names = T, row.names = F, sep =";", dec = ",", quote = F)
}
#----------------------- Konec vizualizae a Exportu dat ------------------------

#Statistika---------------------------------------------------------------------

#Vypocet CI a prumeru pro vsechny L a R zatacky
#ListTotalDataR
dfTotalDataR<-ListTotalDataR[[1]][0,]
for (r in ListTotalDataR)
{
  dfTotalDataR<-rbind(dfTotalDataR,r)
}

#ListTotalDataL
dfTotalDataL<-ListTotalDataL[[1]][0,]
for (r in ListTotalDataL)
{
  dfTotalDataL<-rbind(dfTotalDataL,r)
}

#porovnani meanu CI
dfCelkemMeansCIL <- as.data.frame(Get_MeansCIDF(dfTotalDataL,1:length(time_axis)))
dfCelkemMeansCIR <- as.data.frame(Get_MeansCIDF(dfTotalDataR,1:length(time_axis)))

#zobrazeni dvou DF a jejich means a CI
Show_Mean2CI(dfCelkemMeansCIL, dfCelkemMeansCIR, xaxis=time_axis, "Zatacky L a R", "Doleva", "Doprava", okno=F,
             xlbl = "Čas [ms]", ylbl="Vzdálenost spline [m]",mainlbl = NULL)

df.A<-dfTotalMeans[dfTotalMeans$Zatacka=="A",]
cl <- rainbow(nrow(df.A))

dev.new()
#plot(1, type = 'n', xlim = c(0, 15000), ylim = c(-1, 5.5), xlab = "Čas [ms]", ylab = "Vzdálenost spline [m]", main="Vsechny zatacky 20ms")
plot(1, type = 'n', xlim = c(0, 15000), ylim = c(-1, 5.5), xlab = "Čas [ms]", ylab = "Vzdálenost spline [m]", main="")
for(i in 1:nrow(df.A)) {
  lines(time_axis,df.A[i,4:754], lwd=2, col = cl[i])
}

df.L<-dfTotalMeans[dfTotalMeans$Zatacka=="L",]
cl <- rainbow(nrow(df.L))

dev.new()
#plot(1, type = 'n', xlim = c(0, 15000), ylim = c(-1, 5.5), xlab = "Čas [ms]", ylab = "Vzdálenost spline [m]", main="Vsechny zatacky L 20ms")
plot(1, type = 'n', xlim = c(0, 15000), ylim = c(-1, 5.5), xlab = "Čas [ms]", ylab = "Vzdálenost spline [m]", main="")
for(i in 1:nrow(df.L)) {
  lines(time_axis,df.L[i,4:754], lwd=2, col = cl[i])
}


df.R<-dfTotalMeans[dfTotalMeans$Zatacka=="R",]
cl <- rainbow(nrow(df.R))

dev.new()
#plot(1, type = 'n', xlim = c(0, 15000), ylim = c(-1, 5.5), xlab = "cas [ms]", ylab = "vzdalenost", main="Vsechny zatacky R 20ms")
plot(1, type = 'n', xlim = c(0, 15000), ylim = c(-1, 5.5), xlab = "Čas [ms]", ylab = "Vzdálenost spline [m]", main="")
for(i in 1:nrow(df.R)) {
  lines(time_axis,df.R[i,4:754], lwd=2, col = cl[i])
}


#casy --------------------------------------------------------------------------
#prevod na cisla
dfTotalTimes$Reakce<-as.numeric(dfTotalTimes$Reakce)
dfTotalTimes$Ustaleni<-as.numeric(dfTotalTimes$Ustaleni)


df.T<-dfTotalTimes[dfTotalTimes$Zatacka=="A",]
hist(as.numeric(df.T$Reakce))

df.T<-dfTotalTimes[dfTotalTimes$Zatacka=="R",]
hist(as.numeric(df.T$Reakce))

df.T<-dfTotalTimes[dfTotalTimes$Zatacka=="L",]
hist(as.numeric(df.T$Reakce))

t.test(as.numeric(df.T$Reakce))
with(dfTotalTimes,leveneTest(Reakce,as.factor(Zatacka),center="mean"))
t.test(Reakce~Zatacka,data=dfTotalTimes[dfTotalTimes$Zatacka=="R" | dfTotalTimes$Zatacka=="L",],var.equal=T,paired=F )
boxplot(as.numeric(df.T$Reakce))
wilcox.test(Reakce~Zatacka,data=dfTotalTimes[dfTotalTimes$Zatacka=="R" | dfTotalTimes$Zatacka=="L",],mu=0, conf.int=T, alt="two.sided", exact=F,paired=F )
shapiro.test(dfTotalTimes[dfTotalTimes$Zatacka=="R" | dfTotalTimes$Zatacka=="L","Reakce"])
shapiro.test(dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"])
shapiro.test(dfTotalTimes[dfTotalTimes$Zatacka=="L","Reakce"])
nortest::ad.test(dfTotalTimes[dfTotalTimes$Zatacka=="R" | dfTotalTimes$Zatacka=="L","Reakce"])
nortest::ad.test(dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"])
nortest::ad.test(dfTotalTimes[dfTotalTimes$Zatacka=="L","Reakce"])

#-- Reakcni doba ---------------------------------------------------------------
shapiro.test(dfTotalTimes[dfTotalTimes$Zatacka=="A","Reakce"])
shapiro.test(dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"])
shapiro.test(dfTotalTimes[dfTotalTimes$Zatacka=="L","Reakce"])
ggdensity(dfTotalTimes[dfTotalTimes$Zatacka=="A","Reakce"], fill = "lightgray")
ggdensity(dfTotalTimes[dfTotalTimes$Zatacka=="L","Reakce"], fill = "lightgray")
ggdensity(dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"], fill = "lightgray")

ggqqplot(dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"], ylab = "Cas reakce R", ggtheme = theme_minimal())
ggqqplot(dfTotalTimes[dfTotalTimes$Zatacka=="L","Reakce"], ylab = "Cas reakce L", ggtheme = theme_minimal())
ggqqplot(dfTotalTimes[dfTotalTimes$Zatacka=="A","Reakce"], ylab = "Cas reakce A", ggtheme = theme_minimal())
wilcox.test(Reakce~Zatacka,data=dfTotalTimes[dfTotalTimes$Zatacka=="R" | dfTotalTimes$Zatacka=="L",],mu=0,alt="two.sided",conf.int=T, paired=F, exact=F, correct=T, conf.level=.95)

#H0 skupiny jsou stejne v (variance - rozptylu)
leveneTest(Reakce~Zatacka,data=dfTotalTimes[dfTotalTimes$Zatacka=="R" | dfTotalTimes$Zatacka=="L",]) 

#Srovnani casu reakce
lablist<-list(atrb=c("All","Right","Left"))
porovnani <- list( c("A", "R"), c("A", "L"), c("R", "L") )
osaX<-"Zatacka"
osaY<-"Cas reakce"
title<-"Cas reakce vs Zatacka"
grupa<-"Zatacka"
atribut<-"Reakce"
ShowBoxPltCI(dfTotalTimes,porovnani, atribut, grupa, lablist, title, osaX, osaY)

lablist<-list(atrb=c("Vpravo","Vlevo"))
porovnani <- list( c("L", "R"))
osaX<-"Odbočení do pruhu"
osaY<-"Reakční doba [ms]"
title<-NULL
grupa<-"Zatacka"
atribut<-"Reakce"
ShowBoxPltCI(dfTotalTimes[dfTotalTimes$Zatacka!="A",],porovnani, atribut, grupa, lablist, title, osaX, osaY,barvy = c("blue","red","black"))


wilcox.test(dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"],dfTotalTimes[dfTotalTimes$Zatacka=="L","Reakce"],exact = F, conf.int = T)

#median R je mensi nez median L
wilcox.test(x=dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"],y=dfTotalTimes[dfTotalTimes$Zatacka=="L","Reakce"],
            exact = F, conf.int = T, alternative="less") #nemuzeme zamitnout ze je median Reakce  R mensi nez median L

#median R je vetsi nez median L
wilcox.test(x=dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"],y=dfTotalTimes[dfTotalTimes$Zatacka=="L","Reakce"],
            exact = F, conf.int = T, alternative="greater") #nemuzeme zamitnout ze je median Reakce R vetsi nez median L

t.test(dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"],dfTotalTimes[dfTotalTimes$Zatacka=="L","Reakce"], 
       alternative = "two.sided", var.equal = FALSE, conf.int = T)

#Korelace mezi zatackou vlevo a vpravo
c<-cor(dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"],dfTotalTimes[dfTotalTimes$Zatacka=="L","Reakce"])
cor(dfTotalTimes[dfTotalTimes$Zatacka=="A","Reakce"],dfTotalTimes[dfTotalTimes$Zatacka=="L","Reakce"])
cor(dfTotalTimes[dfTotalTimes$Zatacka=="A","Reakce"],dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"])

pwr.t.test(length(dfTotalTimes[dfTotalTimes$Zatacka=="R","Reakce"]),d=c,sig.level = 0.05,type = "two.sample")

#Ukonceni regulace -------------------------------------------------------------
shapiro.test(dfTotalTimes[dfTotalTimes$Zatacka=="A","Ustaleni"])
shapiro.test(dfTotalTimes[dfTotalTimes$Zatacka=="R","Ustaleni"])
shapiro.test(dfTotalTimes[dfTotalTimes$Zatacka=="L","Ustaleni"])
ggqqplot(dfTotalTimes[dfTotalTimes$Zatacka=="R","Ustaleni"], ylab = "Doba ustaleni R", ggtheme = theme_minimal())
ggqqplot(dfTotalTimes[dfTotalTimes$Zatacka=="L","Ustaleni"], ylab = "Doba ustaleni L", ggtheme = theme_minimal())
ggqqplot(dfTotalTimes[dfTotalTimes$Zatacka=="A","Ustaleni"], ylab = "Doba ustaleni A", ggtheme = theme_minimal())
ggdensity(dfTotalTimes[dfTotalTimes$Zatacka=="A","Ustaleni"], fill = "lightgray")
ggdensity(dfTotalTimes[dfTotalTimes$Zatacka=="L","Ustaleni"], fill = "lightgray")
ggdensity(dfTotalTimes[dfTotalTimes$Zatacka=="R","Ustaleni"], fill = "lightgray")

nortest::ad.test(dfTotalTimes[dfTotalTimes$Zatacka=="R" | dfTotalTimes$Zatacka=="L","Ustaleni"])
nortest::ad.test(dfTotalTimes[dfTotalTimes$Zatacka=="R","Ustaleni"])
nortest::ad.test(dfTotalTimes[dfTotalTimes$Zatacka=="L","Ustaleni"])


wilcox.test(Ustaleni~Zatacka,data=dfTotalTimes[dfTotalTimes$Zatacka=="R" | dfTotalTimes$Zatacka=="L",],mu=0,alt="two.sided",conf.int=T, paired=F, exact=F, correct=T, conf.level=.95)

#H0 skupiny jsou stejne v (variance - rozptylu)
leveneTest(Ustaleni~Zatacka,data=dfTotalTimes[dfTotalTimes$Zatacka=="R" | dfTotalTimes$Zatacka=="L",]) 

#Srovnani casu ukonceni regulace
lablist<-list(atrb=c("All","Right","Left"))
porovnani <- list( c("A", "R"), c("A", "L"), c("R", "L") )
osaX<-"Zatacka"
osaY<-"Doba regulace"
title<-"Doba regulace vs Zatacka"
grupa<-"Zatacka"
atribut<-"Ustaleni"

ShowBoxPltCI(dfTotalTimes,porovnani, atribut, grupa, lablist, title, osaX, osaY)

lablist<-list(atrb=c("Pravá","Levá"))
porovnani <- list( c("R", "L"))
osaX<-"Zatacka"
osaY<-"Doba regulace"
title<-"Doba regulace vs Zatacka"
grupa<-"Zatacka"
atribut<-"Ustaleni"

lablist<-list(atrb=c("Vpravo","Vlevo"))
porovnani <- list( c("L", "R"))
osaX<-"Odbočení do pruhu"
osaY<-"Doba ustálení [ms]"
title<-NULL
grupa<-"Zatacka"
atribut<-"Ustaleni"

ShowBoxPltCI(dfTotalTimes[dfTotalTimes$Zatacka!="A",],porovnani, atribut, grupa, lablist, title, osaX, osaY, barvy = c("blue","red","black"))



wilcox.test(dfTotalTimes[dfTotalTimes$Zatacka=="R","Ustaleni"],dfTotalTimes[dfTotalTimes$Zatacka=="L","Ustaleni"],exact = F, conf.int = T)

#median R je mensi nez median L
wilcox.test(dfTotalTimes[dfTotalTimes$Zatacka=="R","Ustaleni"],dfTotalTimes[dfTotalTimes$Zatacka=="L","Ustaleni"],
            exact = F, conf.int = T, alternative="less") #nemuzeme zamitnout ze je median ustaleni  R mensi nez median L

#median R je vetsi nez median L
wilcox.test(dfTotalTimes[dfTotalTimes$Zatacka=="R","Ustaleni"],dfTotalTimes[dfTotalTimes$Zatacka=="L","Ustaleni"],
            exact = F, conf.int = T, alternative="greater") #nemuzeme zamitnout ze je median ustaleni R vetsi nez median L


#Korelace mezi zatackou vlevo a vpravo
cor(dfTotalTimes[dfTotalTimes$Zatacka=="R","Ustaleni"],dfTotalTimes[dfTotalTimes$Zatacka=="L","Ustaleni"])
cor(dfTotalTimes[dfTotalTimes$Zatacka=="A","Ustaleni"],dfTotalTimes[dfTotalTimes$Zatacka=="L","Ustaleni"])
cor(dfTotalTimes[dfTotalTimes$Zatacka=="A","Ustaleni"],dfTotalTimes[dfTotalTimes$Zatacka=="R","Ustaleni"])


#velice slaba pozitivni korelace mezi Ustaleni a reakci
cr<-cor(dfTotalTimes[dfTotalTimes$Zatacka=="A","Ustaleni"],dfTotalTimes[dfTotalTimes$Zatacka=="A","Reakce"])

#power analysis
pwr.t.test(length(dfTotalTimes[dfTotalTimes$Zatacka=="R","Ustaleni"]),d=0.1360791,sig.level = 0.05,type = "two.sample")

pwr.r.test(n = length(dfTotalTimes[dfTotalTimes$Zatacka=="R","Ustaleni"]), r= cr, sig.level = 0.05) #je to slaby test

#rozdily v casech vzorkovani
#soubory obsahuje seznam souboru

rozdilyT<-c()
delkaSim<-c()
pozice_X_A<-c()
pozice_Y_A<-c()
splineDist_A<-c()
velocity_A<-c()
wheelAngle_A<-c()
ix<-1
for (s in soubory)
{
  
  data_s<-read.csv2(s,header = F, sep = ";", na.strings=c("","NA"), dec=".",skip = 1) #preskocime radek s headerem a udelame svuj
  colnames(data_s)<-nazvySloupcu
    
  if (min(diff(data_s$Time_ms))>=0)  #pokud je rozil zaporny doslo k restartu v programu a tedy tento soubor vynechame
  {
    if (!(substring(basename(s),1,3) %in% vyjimky)) #eliminace vyjimek - divna data
    {
      message(sprintf("Soubor (%s) : %s",ix,s))
      rozdilyT<-c(rozdilyT,diff(data_s$Time_ms))
      delkaSim<-c(delkaSim,max(data_s$Time_ms)-min(data_s$Time_ms))
      pozice_X_A<-c(pozice_X_A,data_s$X_pos)
      pozice_Y_A<-c(pozice_Y_A,data_s$Y_pos)
      splineDist_A<-c(splineDist_A,data_s$SplineDistance)
      velocity_A<-c(velocity_A,data_s$Velocity)
      wheelAngle_A<-c(wheelAngle_A,data_s$WheelAngle)
      ix<-ix+1
    }  
  }
}

#------------ Vzorkovani ----------------
Q <- quantile(rozdilyT, probs=c(.25, .75), na.rm = FALSE)
iqr <- IQR(rozdilyT)
up <-  Q[2]+1.5*iqr # Upper Range  
low<- Q[1]-1.5*iqr # Lower Range
eliminated<- rozdilyT[rozdilyT > low & rozdilyT < up]

outliers <- boxplot(rozdilyT, plot=FALSE)$out
xR<-rozdilyT
xR<- xR[-which(xR %in% outliers)]
hist(xR)
histogram(xR)
mean(xR)
table(xR)
boxplot(xR,ylab="Čas vzorkování [ms]",notch = TRUE, add = TRUE, col = "bisque")

hist(rozdilyT,breaks = 100)
mean(rozdilyT)
table(rozdilyT)
boxplot(rozdilyT)
histogram(rozdilyT)
#-----------------------------------

#------- Delka simulace ------------
#simulace v ms
hist(delkaSim)
round(mean(delkaSim)/1000,1)
table(delkaSim)
dev.new()
boxplot(delkaSim/1000,ylab='Délka simulace [s]', col = "bisque")

#simulace v Min
delkaSimMin<-round((delkaSim/1000)/60,2)
hist(delkaSimMin)
mean(delkaSimMin)
table(delkaSimMin)
boxplot(delkaSimMin)

#----------------------------------
#-- Otoceni volantem -------------
#-- interval -1,1 -450 - 450 stupnu

wAngleDeg<-rescale(data_s$WheelAngle,to=c(-450,450),from=c(-1,1))  #library scales

#Zakladni statistika pro vsechny hodnoty
summary(pozice_X_A)
summary(pozice_Y_A)
summary(splineDist_A)
summary(velocity_A)
summary(wheelAngle_A)
summary(rescale(wheelAngle_A,to=c(-450,450),from=c(-1,1)))  #library scales

summary(data_s)
stop()

#-------------------------------------------------------------------------------

#Nacteni dat do promenne -------------------------------------------------------
data<-read.csv2(soubor,header = TRUE, sep = ";", na.strings=c("","NA"), dec=".")
data$TimeFromStep<-NA


#===============================================================================
#zobrazi jak vypadaji RAW data
ZobrazRawData(data,soubor,atrVzdalenost = atrSplineDst )

#zobrazime peaky

#ziskame x a y pro peak na krivce
pksX<-find_peaks(data[,atrSplineDst])
pksY<-data[pksX,atrSplineDst]
ShowPeaks(data,atrSplineDst,pksX,pksY)

#zobrazeni celeho prubehu ------------------------------------------------------
#index hodnot kde je inflexni box
startIx<-Get_StepIndex(data[,atrSplineDst])
#seznam indexu konce regulace def 15s
indexT<-Get_RawIndexLen(data, startIx, atrTime, delkaReg)
#zobrazime odpoved na jednotkovy skok
Show_RawTimeReg(data, startIx, indexT, atrSplineDst)
#-------------------------------------------------------------------------------


#Rozhozeni na leve a prave zatacky
skokyLR<-DivideDataLR(data,startIx,atrTime, delkaReg, atrTimeStep)

#Zjisteni rozdilu casu mezi vzorky stejne poradove cislo vzorku, ale jiny cas od zacatku
rozdilL<-Get_TimeDiff(skokyLR[["L"]],atrTimeStep)
rozdilR<-Get_TimeDiff(skokyLR[["R"]],atrTimeStep)

#rozdil mezi vzorky jednotky ms
rozdil_vzL<-Get_RozdilVzorku(skokyLR[["L"]],atrTime)
rozdil_vzR<-Get_RozdilVzorku(skokyLR[["R"]],atrTime)

#Provede resampling dat
ResampledDataL<-lapply(skokyLR[["L"]],FUN=function(v){DoInterpolace(v,showchart=FALSE,sampleTime=ResampleTime)})
ResampledDataR<-lapply(skokyLR[["R"]],FUN=function(v){DoInterpolace(v,showchart=FALSE,sampleTime=ResampleTime)})


#Resamplovane data rozdelime na poloviny a tretiny

pocetDeleni<-2
deleniL2<-Get_IndexSkupiny(length(ResampledDataL),pocetDeleni)
deleniR2<-Get_IndexSkupiny(length(ResampledDataR),pocetDeleni)

pocetDeleni<-3
deleniL3<-Get_IndexSkupiny(length(ResampledDataL),pocetDeleni)
deleniR3<-Get_IndexSkupiny(length(ResampledDataR),pocetDeleni)

#Datove resamplovane soubory Cele, CeleL, CeleR, 1/2L, 1/2R, 1/3L, 1/3R
sk_df<-1 #allRL
list_dfRL<-Get_ResampletDF(ResampledDataL, ResampledDataR, deleniL2, deleniL3, deleniR2, deleniR3, sk_df)

sk_df<-2 #allL
list_dfL<-Get_ResampletDF(ResampledDataL, ResampledDataR, deleniL2, deleniL3, deleniR2, deleniR3, sk_df)

sk_df<-3 #allR
list_dfR<-Get_ResampletDF(ResampledDataL, ResampledDataR, deleniL2, deleniL3, deleniR2, deleniR3, sk_df)

sk_df<-4 #allL2
list_dfL2<-Get_ResampletDF(ResampledDataL, ResampledDataR, deleniL2, deleniL3, deleniR2, deleniR3, sk_df)

sk_df<-5 #allR2
list_dfR2<-Get_ResampletDF(ResampledDataL, ResampledDataR, deleniL2, deleniL3, deleniR2, deleniR3, sk_df)

sk_df<-6 #allL3
list_dfL3<-Get_ResampletDF(ResampledDataL, ResampledDataR, deleniL2, deleniL3, deleniR2, deleniR3, sk_df)

sk_df<-7 #allR3
list_dfR3<-Get_ResampletDF(ResampledDataL, ResampledDataR, deleniL2, deleniL3, deleniR2, deleniR3, sk_df)

#Prumerne krivky

df_colmeansRL <- Get_ColMeans(list_dfRL,1:length(time_axis))
df_colmeansL <- Get_ColMeans(list_dfL,1:length(time_axis))
df_colmeansL2 <- Get_ColMeans(list_dfL2,1:length(time_axis))
df_colmeansL3 <- Get_ColMeans(list_dfL3,1:length(time_axis))
df_colmeansR <- Get_ColMeans(list_dfR,1:length(time_axis))
df_colmeansR2 <- Get_ColMeans(list_dfR2,1:length(time_axis))
df_colmeansR3 <- Get_ColMeans(list_dfR3,1:length(time_axis))


plot(time_axis,t(df_colmeansR2)[1,])

hist(list_dfRL[[1]][,200])
colMeans(list_dfRL[[1]][,1:700])
data.frame(sapply(ResampledData, colMeans))
plot(list_dfRL[[1]][1,1:length(time_axis)])

#Vizualizace krivek

Show_Means( vstup = df_colmeansRL, xaxis = time_axis,descr = "Vsechny zatacky RL", sloupce = 1:length(time_axis) )
Show_Means( vstup = df_colmeansR, xaxis = time_axis,descr = "Vsechny zatacky R", sloupce = 1:length(time_axis) )
Show_Means( vstup = df_colmeansL, xaxis = time_axis,descr = "Vsechny zatacky L", sloupce = 1:length(time_axis) )
Show_Means( vstup = df_colmeansR2, xaxis = time_axis,descr = "Vsechny zatacky R2", sloupce = 1:length(time_axis) )
Show_Means( vstup = df_colmeansL2, xaxis = time_axis,descr = "Vsechny zatacky L2", sloupce = 1:length(time_axis) )
Show_Means( vstup = df_colmeansR3, xaxis = time_axis,descr = "Vsechny zatacky R3", sloupce = 1:length(time_axis) )
Show_Means( vstup = df_colmeansL3, xaxis = time_axis,descr = "Vsechny zatacky L3", sloupce = 1:length(time_axis) )

#Statisticke analyzy

#prumery a konfidencni intervaly
CI_MeanRL<-Get_MeansCI(list_dfRL,1:length(time_axis))
CI_MeanL<-Get_MeansCI(list_dfL,1:length(time_axis))
CI_MeanL2<-Get_MeansCI(list_dfL2,1:length(time_axis))
CI_MeanL3<-Get_MeansCI(list_dfL3,1:length(time_axis))
CI_MeanR<-Get_MeansCI(list_dfR,1:length(time_axis))
CI_MeanR2<-Get_MeansCI(list_dfR2,1:length(time_axis))
CI_MeanR3<-Get_MeansCI(list_dfR3,1:length(time_axis))

Show_MeanCI(vstup=CI_MeanRL,xaxis = time_axis,descr = "Vsechny zatacky RL",okno=F)
Show_MeanCI(vstup=CI_MeanL,xaxis = time_axis,descr = "Vsechny zatacky L",okno=F)
Show_MeanCI(vstup=CI_MeanR,xaxis = time_axis,descr = "Vsechny zatacky R",okno=F)
Show_MeanCI(vstup=CI_MeanL2,xaxis = time_axis,descr = "Vsechny zatacky L2",okno=F)
Show_MeanCI(vstup=CI_MeanR2,xaxis = time_axis,descr = "Vsechny zatacky R2",okno=F)
Show_MeanCI(vstup=CI_MeanL3,xaxis = time_axis,descr = "Vsechny zatacky L3",okno=F)
Show_MeanCI(vstup=CI_MeanR3,xaxis = time_axis,descr = "Vsechny zatacky R3",okno=F)

Show_Mean2CI(CI_MeanL, CI_MeanR, xaxis, "Zatacky L a R", "Leva", "Prava", okno=F)

#zobrazime jednotlive zatacky a prumer
dev.new()
par(mfrow=c(3,1)) 
Show_TurnAndMean(vstup=list_dfRL,prumer=CI_MeanRL,xaxis = time_axis, sloupce=1:length(time_axis), descr = "Vsechny zatacky",okno=F)
Show_TurnAndMean(vstup=list_dfR,prumer=CI_MeanR,xaxis = time_axis, sloupce=1:length(time_axis), descr = "Vsechny zatacky R",okno=F)
Show_TurnAndMean(vstup=list_dfL,prumer=CI_MeanL,xaxis = time_axis, sloupce=1:length(time_axis), descr = "Vsechny zatacky L",okno=F)
par(mfrow=c(1,1)) 

#pokud mame prvni derivaci tak uhel v RAD je ATAN teto derivace
#prvni derivace diff(y)/diff(time)
#derivMean<- rad2deg(atan(diff(CI_MeanRL[[1]][2,])/20))

#Vsechny response a ustaleni pro prumery
dev.new()
par(mfrow=c(3,1)) 
data_reakce<-CI_MeanRL[[1]][2,]
#zjisteni Response time
df.tr<-Get_Resp_Ustal(vstup = data_reakce, procZM = 0.1, casVzorku = ResampleTime)
#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce, timeaxe=time_axis, casR=df.tr[1,1], 
                  casU=df.tr[1,2], zmn=df.tr[1,5], vzdMin=df.tr[1,3], vzdMax=df.tr[1,4], 
                  popis="mean RL", show_val=T, okno=F)

data_reakce<-CI_MeanR[[1]][2,]
#zjisteni Response time
df.tr<-Get_Resp_Ustal(vstup = data_reakce, procZM=0.1, casVzorku = ResampleTime)
#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce, timeaxe=time_axis, casR=df.tr[1,1], 
                  casU=df.tr[1,2], zmn=df.tr[1,5], vzdMin=df.tr[1,3], vzdMax=df.tr[1,4], 
                  popis="mean R", show_val=T, okno=F)

data_reakce<-CI_MeanL[[1]][2,]
#zjisteni Response time
df.tr<-Get_Resp_Ustal(vstup = data_reakce, procZM=0.1, casVzorku = ResampleTime)
#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce, timeaxe=time_axis, casR=df.tr[1,1], 
                  casU=df.tr[1,2], zmn=df.tr[1,5], vzdMin=df.tr[1,3], vzdMax=df.tr[1,4], 
                  popis="mean L", show_val=T, okno=F)

par(mfrow=c(1,1)) 

 #Leve prumery
dev.new()
par(mfrow=c(2,1)) 
data_reakce<-CI_MeanL2
#zjisteni Response time
df.tr<-Get_Resp_Ustal(vstup = data_reakce, procZm=0.1, casVzorku = ResampleTime)
#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce[[1]][2,], timeaxe=time_axis, casR=df.tr[1,1], 
                  casU=df.tr[1,2], zmn=df.tr[1,5], vzdMin=df.tr[1,3], vzdMax=df.tr[1,4], 
                  popis="mean L prvni polovina", show_val=T, okno=F)


#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce[[2]][2,], timeaxe=time_axis, casR=df.tr[2,1], 
                  casU=df.tr[2,2], zmn=df.tr[2,5], vzdMin=df.tr[2,3], vzdMax=df.tr[2,4], 
                  popis="mean L druha polovina", show_val=T, okno=F)
par(mfrow=c(1,1))  


par(mfrow=c(1,1)) 
#Prave prumery
dev.new()
par(mfrow=c(2,1)) 
data_reakce<-CI_MeanR2
#zjisteni Response time
df.tr<-Get_Resp_Ustal(vstup = data_reakce, procZm=0.1, casVzorku = ResampleTime)
#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce[[1]][2,], timeaxe=time_axis, casR=df.tr[1,1], 
                  casU=df.tr[1,2], zmn=df.tr[1,5], vzdMin=df.tr[1,3], vzdMax=df.tr[1,4], 
                  popis="mean R prvni polovina", show_val=T, okno=F)


#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce[[2]][2,], timeaxe=time_axis, casR=df.tr[2,1], 
                  casU=df.tr[2,2], zmn=df.tr[2,5], vzdMin=df.tr[2,3], vzdMax=df.tr[2,4], 
                  popis="mean R druha polovina", show_val=T, okno=F)
par(mfrow=c(1,1))  

#----------------------------------------
par(mfrow=c(1,1)) 
#Leve prumery
dev.new()
par(mfrow=c(3,1)) 
data_reakce<-CI_MeanL3
#zjisteni Response time
df.tr<-Get_Resp_Ustal(vstup = data_reakce, procZm=0.1, casVzorku = ResampleTime)
#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce[[1]][2,], timeaxe=time_axis, casR=df.tr[1,1], 
                  casU=df.tr[1,2], zmn=df.tr[1,5], vzdMin=df.tr[1,3], vzdMax=df.tr[1,4], 
                  popis="mean L prvni tretina", show_val=T, okno=F)


#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce[[2]][2,], timeaxe=time_axis, casR=df.tr[2,1], 
                  casU=df.tr[2,2], zmn=df.tr[2,5], vzdMin=df.tr[2,3], vzdMax=df.tr[2,4], 
                  popis="mean L druha tretina", show_val=T, okno=F)

#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce[[3]][2,], timeaxe=time_axis, casR=df.tr[3,1], 
                  casU=df.tr[3,2], zmn=df.tr[3,5], vzdMin=df.tr[3,3], vzdMax=df.tr[3,4], 
                  popis="mean L treti tretina", show_val=T, okno=F)

par(mfrow=c(1,1))  

par(mfrow=c(1,1)) 

#Prave prumery
dev.new()
par(mfrow=c(3,1)) 
data_reakce<-CI_MeanR3
#zjisteni Response time
df.tr<-Get_Resp_Ustal(vstup = data_reakce, procZm=0.1, casVzorku = ResampleTime)
#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce[[1]][2,], timeaxe=time_axis, casR=df.tr[1,1], 
                  casU=df.tr[1,2], zmn=df.tr[1,5], vzdMin=df.tr[1,3], vzdMax=df.tr[1,4], 
                  popis="mean R prvni tretina", show_val=T, okno=F)


#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce[[2]][2,], timeaxe=time_axis, casR=df.tr[2,1], 
                  casU=df.tr[2,2], zmn=df.tr[2,5], vzdMin=df.tr[2,3], vzdMax=df.tr[2,4], 
                  popis="mean R druha tretina", show_val=T, okno=F)

#zobrazeni nalezenych casu na krivce
Show_ResponseTime(vstup=data_reakce[[3]][2,], timeaxe=time_axis, casR=df.tr[3,1], 
                  casU=df.tr[3,2], zmn=df.tr[3,5], vzdMin=df.tr[3,3], vzdMax=df.tr[3,4], 
                  popis="mean R treti tretina", show_val=T, okno=F)

par(mfrow=c(1,1)) 

#Hodnoty start stop ve vsech krivkach
zatacky<-as.character(list_dfRL[[1]]$Smer)
df.tr<-Get_Resp_Ustal(vstup = list_dfRL[[1]][,1:length(time_axis)], procZm=0.1, casVzorku = ResampleTime)
df.bp<-data.frame(ReakcniDoba=df.tr[,"IxReakce"],Skupina=rep("RL",length(zatacky)))
df.bpT<-data.frame(ReakcniDoba=df.tr[,"IxReakce"],Skupina=zatacky)
df.bp<-rbind(df.bp,df.bpT)

boxplot(ReakcniDoba~Skupina,
        data=df.bp,
        main="Doba reakce na jednotkový skok (změna vzdálenosti o > 10% maxima )",
        xlab="Skupina",
        ylab="Reakční doba [ms]",
        col="orange",
        border="brown"
)

#Ustaleni regulace
zatacky<-as.character(list_dfRL[[1]]$Smer)
df.tr<-Get_Resp_Ustal(vstup = list_dfRL[[1]][,1:length(time_axis)], procZm=0.1, casVzorku = ResampleTime)
df.bp<-data.frame(DobaUstaleni=df.tr[,"IxUstaleni"],Skupina=rep("RL",length(zatacky)))
df.bpT<-data.frame(DobaUstaleni=df.tr[,"IxUstaleni"],Skupina=zatacky)
df.bp<-rbind(df.bp,df.bpT)

boxplot(DobaUstaleni~Skupina,
        data=df.bp,
        main="Doba ustálení po jednotkovém skoku (změna vzdálenosti o < 10% k 0 )",
        xlab="Skupina",
        ylab="Doba ustaleni [ms]",
        col="orange",
        border="brown"
)

#porovnani casovych rad
#TTR package, tseries

library(TTR)
x <- ts(CI_MeanR[[1]][2,],start=c(0,1),end=c(15000,1),frequency=1)
a<-decompose(x)

a<-ccf(CI_MeanR[[1]][2,],CI_MeanL[[1]][2,])

library(timetk)
plot_stl_diagnostics(
  .date_var = time_axis,
  .data=data.frame(CI_MeanR[[1]][2,]),
  .value = CI_MeanR[[1]][2,],
  .frequency = "auto", .trend = "auto",
  .feature_set = c("observed", "season", "trend", "remainder"),
  .interactive = F)

cor.test(CI_MeanR[[1]][2,],CI_MeanL[[1]][2,], method=c("spearman"))

t.test(CI_MeanR[[1]][2,],CI_MeanL[[1]][2,])
boxplot(CI_MeanR[[1]][2,],CI_MeanL[[1]][2,])

#LEFT zatacky ------------------------------------------------------------------
#
ResampledDataL<-lapply(lstL,FUN=function(v){DoInterpolace(v)})

#Vizualizace resampled data
xminp<-0
xmaxp<-15000
dev.new()
par(mfrow=c(1,1)) 
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny leve resampled 20ms")
# Vytvori seznam barev
cl <- rainbow(length(ResampledData))
# Vytvoreni grafu 
for(i in 1:length(ResampledData)) {
  lines(ResampledData[[i]]$Time_ms,ResampledData[[i]]$SplineDistance, lwd=2, col = cl[i])
}

#rozdeleni na skupiny
chunklength<-round(length(ResampledData)/3)
skupiny<-split(1:length(ResampledData),ceiling(seq_along(1:length(ResampledData)) / chunklength))
sk1<-skupiny[[1]]
sk2<-skupiny[[2]]
sk3<-skupiny[[3]]
if (length(skupiny)>3)
  sk3<-c(sk3,skupiny[[4]])
  

#Vizualizace resampled data 1/3
xminp<-0
xmaxp<-15000
dev.new()
par(mfrow=c(3,1)) 
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny leve resampled 20ms 1/3")
cl <- rainbow(length(ResampledData))
for(i in sk1) {
  lines(ResampledData[[i]]$Time_ms,ResampledData[[i]]$SplineDistance, lwd=2, col = cl[i])
}

#Vizualizace resampled data 2/3
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny leve resampled 20ms 2/3")
cl <- rainbow(length(ResampledData))
for(i in sk2) {
  lines(ResampledData[[i]]$Time_ms,ResampledData[[i]]$SplineDistance, lwd=2, col = cl[i])
}

#Vizualizace resampled data 3/3
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny leve resampled 20ms 3/3")
cl <- rainbow(length(ResampledData))
for(i in sk3) {
  lines(ResampledData[[i]]$Time_ms,ResampledData[[i]]$SplineDistance, lwd=2, col = cl[i])
}

df<-data.frame(t(ResampledData[[1]]))
df<-df[0,]

for (i in 1:length(ResampledData))
{
  df<-rbind(df,ResampledData[[i]]$SplineDistance)  
}

plot(df)
df.means<-colMeans(df)

colnames(df)<-paste0("Step", 1:ncol(df), "")
plot(df.means,ylim = c(-1, 5.5), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny leve resampled 20ms prumer",cex=0.5)
cl <- rainbow(length(ResampledData))
# Now fill plot with the data
for(i in 1:length(ResampledData)) {
  lines(1:length(ResampledData[[i]]$SplineDistance),ResampledData[[i]]$SplineDistance, lwd=1, col = cl[i])
}
#LEFT---------------------------------------------------------------------------


#RIGHT zatacky ------------------------------------------------------------------

ResampledDataR<-lapply(lstR,FUN=function(v){DoInterpolace(v)})

#Vizualizace resampled data
xminp<-0
xmaxp<-15000
dev.new()
par(mfrow=c(1,1)) 
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-5.5, 1), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny prave resampled 20ms")
cl <- rainbow(length(ResampledDataR))
for(i in 1:length(ResampledDataR)) {
  lines(ResampledDataR[[i]]$Time_ms,ResampledDataR[[i]]$SplineDistance, lwd=2, col = cl[i])
}

#rozdeleni na skupiny
chunklengthR<-round(length(ResampledDataR)/3)
skupinyR<-split(1:length(ResampledDataR),ceiling(seq_along(1:length(ResampledDataR)) / chunklengthR))
sk1R<-skupinyR[[1]]
sk2R<-skupinyR[[2]]
sk3R<-skupinyR[[3]]
if (length(skupinyR)>3)
  sk3R<-c(sk3R,skupinyR[[4]])


#Vizualizace resampled data 1/3
xminp<-0
xmaxp<-15000
dev.new()
par(mfrow=c(3,1)) 
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-5.5, 1), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny prave resampled 20ms 1/3")
cl <- rainbow(length(ResampledDataR))
for(i in sk1R) {
  lines(ResampledDataR[[i]]$Time_ms,ResampledDataR[[i]]$SplineDistance, lwd=2, col = cl[i])
}

#Vizualizace resampled data 2/3
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-5.5, 1), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny prave resampled 20ms 2/3")
cl <- rainbow(length(ResampledDataR))
for(i in sk2R) {
  lines(ResampledDataR[[i]]$Time_ms,ResampledDataR[[i]]$SplineDistance, lwd=2, col = cl[i])
}

#Vizualizace resampled data 3/3
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-5.5, 1), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny prave resampled 20ms 3/3")
cl <- rainbow(length(ResampledDataR))
for(i in sk3R) {
  lines(ResampledDataR[[i]]$Time_ms,ResampledDataR[[i]]$SplineDistance, lwd=2, col = cl[i])
}

par(mfrow=c(1,1)) 
dfR<-data.frame(t(ResampledDataR[[1]]))
dfR<-dfR[0,]

for (i in 1:length(ResampledDataR))
{
  dfR<-rbind(dfR,ResampledDataR[[i]]$SplineDistance)  
}

plot(dfR)
dfR.means<-colMeans(dfR)

colnames(dfR)<-paste0("Step", 1:ncol(dfR), "")
plot(dfR.means,ylim = c(-5.5, 1), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny prave resampled 20ms prumer",cex=0.5)
cl <- rainbow(length(ResampledDataR))
for(i in 1:length(ResampledDataR)) {
  lines(1:length(ResampledDataR[[i]]$SplineDistance),ResampledDataR[[i]]$SplineDistance, lwd=1, col = cl[i])
}
#RIGHT zatacky -----------------------------------------------------------------

lapply(ResampledData,FUN=function(v){df<-rbind(df,v$SplineDistance)})

data.frame(sapply(ResampledData, colSums))
data.frame(sapply(ResampledData, colMeans))


#Vizualizace dat

xminp<-0
xmaxp<-1200
#All
#Vsechny leve
dev.new()
par(mfrow=c(1,1)) 
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny leve")
cl <- rainbow(length(lstL))
for(i in 1:length(lstL)) {
  lines(lstL[[i]]$SplineDistance, lwd=2, col = cl[i])
}

#vsechny prave
dev.new()
par(mfrow=c(1,1)) 
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), xlab = "vzorek", ylab = "vzdalenost", main="Vsechny prave")
cl <- rainbow(length(lstL))
for(i in 1:length(lstR)) {
  lines(lstR[[i]]$SplineDistance*-1, lwd=2, col = cl[i])
}

#Zobrazeni 

dev.new()
par(mfrow=c(2,1)) 
#1/2
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), xlab = "vzorek", ylab = "vzdalenost",main="prvni polovina L")
cl <- rainbow(round(length(lstL)/2,0))
for(i in 1:round((length(lstL)/2),0)) {
  lines(lstL[[i]]$SplineDistance, lwd=2, col = cl[i])
}

#2/2
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), xlab = "vzorek", ylab = "vzdalenost",main="druha polovina L")
cl <- rainbow(round(length(lstL)/2,0)+1)
for(i in ((round(length(lstL)/2,0)+1):length(lstL))) {
  lines(lstL[[i]]$SplineDistance, lwd=2, col = cl[i-(round(length(lstL)/2,0)+1)])
}

dev.new()
par(mfrow=c(2,1)) 
#1/2
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), xlab = "vzorek", ylab = "vzdalenost",main="prvni polovina R")
cl <- rainbow(round(length(lstR)/2,0))
for(i in 1:round((length(lstR)/2),0)) {
  lines(lstR[[i]]$SplineDistance*-1, lwd=2, col = cl[i])
}

#2/2
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), xlab = "vzorek", ylab = "vzdalenost",main="druha polovina R")
cl <- rainbow(round(length(lstR)/2,0)+1)
for(i in ((round(length(lstR)/2,0)+1):length(lstR))) {
  lines(lstR[[i]]$SplineDistance*-1, lwd=2, col = cl[i-(round(length(lstR)/2,0)+1)])
}

#zobrazeni peaku na krivce
pksX<-find_peaks(lstL[[1]]$SplineDistance)
pksY<-lstL[[1]][pksX,"SplineDistance"]
points(pksX,pksY,pch=19,col = rgb(red = 1, green = 0, blue = 0, alpha = 1),cex=0.9)

# export prumernych hodnot zatacky
write.csv2(df.A[,4:ncol(df.A)],file = sprintf("./%s/%s%s.csv",docdir,"data","_PrumeryRL"),
           col.names = T, row.names = F, sep =";", dec = ".", quote = F)

#*******************************************************************************************
dev.new()
plot(1, type = 'n', xlim = c(0, 15000), ylim = c(-1, 5.5), xlab = "Čas [ms]", ylab = "Vzdálenost spline [m]", main="")
for(i in 1:nrow(df.A)) {
  lines(time_axis,df.A[i,4:754], lwd=2, col = cl[i])
}

as.numeric(df.A[1,4:754])
kk <- ccf(as.numeric(df.A[1,4:754]), as.numeric(df.A[2,4:754]))

kombinace = combn(1:42, 2)
cross_kor = list()

for (i in 1:ncol(kombinace)) 
{
  kk <- ccf(as.numeric(df.A[kombinace[1,i],4:754]), as.numeric(df.A[kombinace[2,i],4:754]))
  cross_kor[[i]] = kk
  message(i)
}

ix_kc = 1
vysledky <- c()
for (i in 1:length(cross_kor))
{
  ix_kc = i
  poradove_cislo <- which.max(cross_kor[[ix_kc]]$acf)
  vysledky = c(vysledky,cross_kor[[ix_kc]]$lag[poradove_cislo])
}
hist(vysledky)
table(vysledky)

stred = mean(as.numeric(df.A[,"X1"]))
df.B = df.A
for (i in 1:nrow(df.B))
{
  h = as.numeric(df.B[i,"X1"])
  rozdil = abs(h-stred)
  if (stred > h)
  {
    df.B[i,4:754] = as.numeric(df.B[i,4:754]) + rozdil  
  }else
  {
    df.B[i,4:754] = as.numeric(df.B[i,4:754]) - rozdil  
  }
}
dev.new()
plot(1, type = 'n', xlim = c(0, 15000), ylim = c(-1, 5.5), xlab = "Čas [ms]", ylab = "Vzdálenost spline [m]", main="")
for(i in 1:nrow(df.B)) {
  lines(time_axis,df.B[i,4:754], lwd=2, col = cl[i])
}