#Funkce pro praci s daty
#08.12.2021 zalozeno
#zmeneno 29.12.2021

library(ggplot2)
library(tidyr)
library(gmodels)
library(Rmisc)
library(ggpubr)
library(pwr)
library(scales)

#Funkce nalezne Pozitivni Peaky v casove rade
#Vraci seznam souradnic
find_peaks <- function (x, m = 3){
  shape <- diff(sign(diff(x, na.pad = FALSE)))
  pks <- sapply(which(shape < 0), FUN = function(i){
    z <- i - m + 1
    z <- ifelse(z > 0, z, 1)
    w <- i + m + 1
    w <- ifelse(w < length(x), w, length(x))
    if(all(x[c(z : i, (i + 2) : w)] <= x[i + 1])) return(i + 1) else return(numeric(0))
  })
  pks <- unlist(pks)
  pks
}

#funkce zobrazi na jedne strance tri obrazky 
ZobrazRawData<- function (vstup, souborName, atrCas="Y_pos",
                          atrPoloha="X_pos", atrVzdalenost="SplineDistance",
                          okno=F, atrUhel = "WheelAngle" ,Uhel=F,
                          p1xl="",p1yl="",p1ml="",p1b="black",
                          p2xl="",p2yl="",p2ml="",p2b="darkblue",
                          p3xl="",p3yl="",p3ml="",p3b="darkgreen",
                          p4xl="",p4yl="",p4ml="",p4b="darkorange"
                          )
{
  #vstup<-data
  #souborName<-soubor
  
  if(is.null(p1xl)){
    p1_xlab<-NULL
  }else{
    if(p1xl=="")
      p1_xlab <- "" # "sample"
    else
      p1_xlab <-p1xl
  }
  
  if(is.null(p1yl)){
    p1_ylab<-NULL
  }else{
    if(p1yl=="")
      p1_ylab <- "time"
    else
      p1_ylab <-p1yl
  }
  
  if(is.null(p1ml)){
    p1_main<-NULL
  }else{
    if(p1ml=="")
      p1_main <- "Time"
    else
      p1_main <-p1ml
  }
  p1_col <- p1b
  p1_cex <- 0.3
  
  if(is.null(p2xl)){
    p2_xlab<-NULL
  }else{
    if(p2xl=="")
      p2_xlab <- "" #  "sample"
    else
      p2_xlab <-p2xl
  }
  
  if(is.null(p2yl)){
    p2_ylab<-NULL
  }else{
    if(p2yl=="")
      p2_ylab <- "position"
    else
      p2_ylab <-p2yl
  }
  
  if(is.null(p2ml)){
    p2_main<-NULL
  }else{
    if(p2ml=="")
      p2_main <- "Poloha auta"
    else
      p2_main <-p2ml
  }
  p2_col <- p2b
  p2_cex <- 0.3
  
  if(is.null(p3xl)){
    p3_xlab<-NULL
  }else{
    if(p3xl=="")
      p3_xlab <- "" #"sample"
    else
      p3_xlab <-p3xl
  }
  
  if(is.null(p3yl)){
    p3_ylab<-NULL
  }else{
    if(p3yl=="")
      p3_ylab <- "distance"
    else
      p3_ylab <-p3yl
  }
  
  if(is.null(p3ml)){
    p3_main<-NULL
  }else{
    if(p3ml=="")
      p3_main <- "Vzdálenost ke středu pruhu"
    else
      p3_main <-p3ml
  }
  p3_col <- p3b
  p3_cex <- 0.3
  
  if(is.null(p4xl)){
    p4_xlab<-NULL
  }else{
    if(p4xl=="")
      p4_xlab <- "" #"sample"
    else
      p4_xlab <-p4xl
  }
  
  if(is.null(p4yl)){
    p4_ylab<-NULL
  }else{
    if(p4yl=="")
      p4_ylab <- "Uhel [\u00B0]"
    else
      p4_ylab <-p4yl
  }
  
  if(is.null(p4ml)){
    p4_main<-NULL
  }else{
    if(p4ml=="")
      p4_main <- "Uhel natoceni"
    else
      p4_main <-p4ml
  }
  p4_col <- p4b
  p4_cex <- 0.3
  
  
  if (okno) {
    dev.new(noRStudioGD = TRUE)
  }
  
  #cex.main=1.25, cex.lab=1.5, cex.axis=0.75
  par(mfrow=c(3,1)) 
  if(!Uhel)
  {
    if(!is.null(p1_main))
      l<-paste(p1_main,souborName,sep =" ")
    else
      l<-NULL
    plot(vstup[,atrCas], cex=p1_cex, xlab = p1_xlab, ylab = p1_ylab, main = l , col=p1_col, xaxt="n") #cas
    title(xlab="", line=0, cex.lab=1.2, family="Calibri Light")
    plot(vstup[,atrPoloha], cex=p2_cex, xlab = p2_xlab, ylab = p2_ylab, main = p2_main , col=p2_col, xaxt="n") #poloha
    title(xlab="", line=0, cex.lab=1.2, family="Calibri Light")
  }
  if(Uhel)
  {
    if(!is.null(p2_main))
      l<-paste(p2_main,souborName,sep =" ")
    else
      l<-NULL
    
    #plot(vstup[,atrPoloha], cex=p2_cex, xlab = p2_xlab, ylab = p2_ylab, main = l , col=p2_col, xaxt="n") #poloha
    #title(xlab="", line=0, cex.lab=1.2, family="Calibri Light")
    #uh<-rescale(vstup[,atrUhel],to=c(-450,450),from=c(-1,1))
    #plot(uh, cex=p4_cex, xlab = p4_xlab, ylab = p4_ylab, main = p4_main, col=p4_col, xaxt="n") #uhel natoceni
    #title(xlab="", line=0, cex.lab=1.2, family="Calibri Light")
    
    plot(vstup[,atrPoloha], cex=p2_cex, xlab=p2_xlab, ylab = p2_ylab, main = NULL , col=p2_col, xaxt="n") #poloha
    #title(xlab=NULL, line=0, cex.lab=1.2)
    uh<-rescale(vstup[,atrUhel],to=c(-450,450),from=c(-1,1))
    plot(uh, cex=p4_cex, ylab = p4_ylab, xlab=p4_xlab, main = NULL , col=p4_col, xaxt="n") #uhel natoceni
    #title(xlab=NULL, line=0, cex.lab=1.2)
    
  }
  plot(vstup[,atrVzdalenost], cex=p3_cex, xlab = p3_xlab, ylab = p3_ylab, main = p3_main , col=p3_col) #vzdalenost od stredu pruhu
  par(mfrow=c(1,1)) 
}

#Zobrazeni peaku na krivce
ShowPeaks<- function (vstup, atrDst, peakX, peakY, okno=F)
{
  
  #vstup<-data
  #atrDst<-atrSplineDst
  #peakX <- pksX
  #peakY <- pksY
  
  r <- 1
  g <- 0
  b <- 0
  a <- 0.4
  
  colr<-"black"
  p_cex<-0.2
  pp_cex<-0.9
  
  p_xlab <- "sample"
  p_ylab <- "Distance spline"
  p_main <- "Peaks on curve"
  
  if (okno) {
    dev.new(noRStudioGD = TRUE)
  }
  plot(vstup[,atrDst],cex=p_cex, col=colr, main=p_main, xlab=p_xlab, ylab= p_ylab)
  points(peakX, peakY, pch=19,
         col = rgb(red = r, green = g, blue = b, alpha = a), 
         cex=pp_cex)
}

#Nalezeni jednotkoveho skoku
#vstup je seznam hodnot spline distance
#vraci index hodnoty kde he inflexni bod, + je jeden smer, - je smer druhy
Get_StepIndex <- function (vstup)
{
  #vstup<-data
  
  hranice <- 1.5
  
  #nalezeni jednotkoveho skoku
  start<- sapply(1:length(vstup),FUN=function(i)
  {
    if(i>2){
      hodnota <- vstup[i] - vstup[i-1]
      if(abs(hodnota)>hranice)
        return(i*sign(hodnota))
    }
  })
  start<-unlist(start)
}

#Nalezeni indexu kde konci regulace pro jednotkovem skoku
Get_RawIndexLen<- function (vstup, lstStartIx, atrCas="Time_ms",delkaReg=15000)
{
  indexT<-c()
  for (t in abs(lstStartIx))
  {
    pocT<-vstup[t,atrCas]
    i<-t
    while(TRUE)
    {
      if (vstup[i,atrCas]-pocT>=delkaReg){
        indexT<-c(indexT,i)
        break
      }else{
        i<-i+1
        if(i>=nrow(vstup))
          break;
      }
    }
  }
  return (indexT)
}

#Zobrazeni RAW prubehu s casem ukonceni regulace
Show_RawTimeReg <- function (vstup, lstStartIx, lstIndexEnd, atrDst,labx="",laby="",labmain="")
{
  #vstup <- data
  #lstStartIx <- startIx
  #lstIndexEnd <- indexT
  #atrDst <- "SplineDistance"

  p_cex <- 0.2
  
  if(is.null(labx))
  {
    p_xlab <- NULL
  }else{
    if(labx=="")
      p_xlab <- "sample"
    else
      p_xlab <- labx
  }
  
  if(is.null(laby))
  {
    p_ylab <- NULL
  }else{
    if(laby=="")
      p_ylab <- "Distance spline"
    else
      p_ylab <- laby
  }
  
  if(is.null(labmain))
  {
    p_main <- NULL
  }else{
    if(labmain=="")
      p_main <- "Peaks on curve and interval of regulation"
    else
      p_main <- labmain
  }
  
  p_palpha<-0.4
  p_pcex<-0.9
  
  pksY<-vstup[abs(lstStartIx),atrDst]
  #timming<-(data$Time_ms-data$Time_ms[1])/1000
  
  plot(vstup[,atrDst], cex=p_cex, main=p_main, xlab=p_xlab, ylab= p_ylab)
  points(abs(lstStartIx),pksY,pch=19, 
         col = rgb(red = 1, green = 0, blue = 0, alpha = p_palpha),cex=p_pcex)
  abline(v=abs(lstStartIx), col=c("blue"), lty=c(1), lwd=c(1))
  abline(h=0, col=c("orange"), lty=c(2), lwd=c(1.5))
  abline(v=lstIndexEnd, col=c("darkgreen"), lty=c(2), lwd=c(1))
}

#Zobrazeni prumeru
Show_Means <- function (vstup, sloupce, xaxis, descr, okno=F)
{
  #vstup = df_colmeansL3
  #xaxis = time_axis
  #descr = "Vsechny zatacky"
  #sloupce = 1:length(time_axis)
  
  p_cex <- 0.2
  p_xlab <- "time [ms]"
  p_ylab <- "Distance spline [m]"
  p_main <- sprintf("Means of spline distance (%s)",descr)
  xminp<-0
  xmaxp<-15000
  
  
  #dimenze vstupu
  if (nrow(vstup)==length(xaxis))
    vstup <- t(vstup)
  
  if (okno) {
    dev.new(noRStudioGD = TRUE)
  }
  
  cl <- rainbow(nrow(vstup))  
  plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), cex=p_cex, main=p_main, xlab=p_xlab, ylab= p_ylab)
  for(i in 1:nrow(vstup)) {
    lines(xaxis,vstup[i,sloupce], lwd=2, col = cl[i])
  }
  
  if(nrow(vstup)==1){
    popis <- c("all")
  }else if(nrow(vstup)==2){
    popis <- c("part 1", "part 2")
  }else if(nrow(vstup)==3){
    popis <- c("part 1", "part 2", "part 3")
  }
  
  legend('topright',inset=0.05,popis,lty=1,col=cl,title="Interval")
}

#Zobrazeni prumeru a pasu CI
#https://stackoverflow.com/questions/14069629/how-can-i-plot-data-with-confidence-intervals
Show_MeanCI <- function (vstup, xaxis, descr, okno=F, barva = "red", legenda=T, showX=T, labx="", laby="", labm="", leglab="", legcap=NULL)
{
  #vstup <- CI_MeanR3
  #xaxis <- time_axis
  #descr <- "Vsechny zatacky"
  
  
  p_cex <- 0.
  
  if (labx=="")
    p_xlab <- "" #"time [ms]"
  else
    p_xlab <- labx
  
  if (laby=="")
    p_ylab <- "" #"Distance spline [m]"
  else
    p_ylab <- laby
  
  if (labm=="")
    p_main <- "" #sprintf("Means of spline distance and CI (%s)",descr)
  else
    p_main <- labm
  
  xminp<-0
  xmaxp<-15000
  
  
  if (okno) {
    dev.new(noRStudioGD = TRUE)
  }
  
  if (is.null(barva))
  {
    cl <- rainbow(length(vstup))  
  } else {
    cl<-barva
  }
  
  if(showX)
    plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), cex=p_cex, main=p_main, xlab=p_xlab, ylab= p_ylab)
  else
    plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), cex=p_cex, main=p_main, xlab=p_xlab, ylab= p_ylab, xaxt="n")
  
  for(i in 1:length(vstup)) {
    df<-vstup[[i]]
    colA<-col2rgb(cl[i])
    coo<-rgb(red = colA[1,], green=colA[2,], blue=colA[3,], max = 255, alpha = 50)
    polygon(c(xaxis,rev(xaxis)),c(df[1,],rev(df[3,])),col = coo, border = FALSE)
    lines(xaxis,df[2,], lwd=2, col = cl[i])   #prumer
  }
  
  if(length(vstup)==1){
    popis <- leglab  #c("all")
  }else if(length(vstup)==2){
    popis <- c("part 1", "part 2")
  }else if(length(vstup)==3){
    popis <- c("part 1", "part 2", "part 3")
  }
  if(legenda)
  {
    legend('topright',inset=0.05,popis,lty=1,col=cl,title=legcap)
  }
}

#Zobrazeni prumeru a pasu CI pro dve krivky
#https://stackoverflow.com/questions/14069629/how-can-i-plot-data-with-confidence-intervals
Show_Mean2CI <- function (vstupA, vstupB, xaxis, descr, descrA, descrB, okno=F, barvy=c("red","blue"),showLegend=T,xlbl="",ylbl="",mainlbl="")
{
  #vstupA<-dfCelkemMeansCIL
  #vstupB<-dfCelkemMeansCIR
  #xaxis<-time_axis
  #descr<-"Zatacky L a R"
  #descrA<-"Leva"
  #descrB<-"Prava"
  #okno<-F
  #barvy<-c("red","blue")
  #showLegend<-T
  
  #vstup <- CI_MeanR3
  #xaxis <- time_axis
  #descr <- "Vsechny zatacky"
  
  
  p_cex <- 0.2
  if(xlbl=="")
    p_xlab <- "time [ms]"
  else
    p_xlab <- xlbl
  if(ylbl=="")
    p_ylab <- "Distance spline [m]"
  else
    p_ylab = ylbl
  
  if(is.null(mainlbl))
  {
    p_main<-NULL
  }else {
  if(mainlbl=="")
    p_main <- sprintf("Means of spline distance and CI (%s)",descr)
  else
    p_main<-mainlbl
  }
  xminp<-0
  xmaxp<-15000
  
  
  if (okno) {
    dev.new(noRStudioGD = TRUE)
  }
  
  if (is.null(barvy))
  {
    cl <- rainbow(2)  
  } else{
    cl<-barvy
  }
  
  brv<-cl  #barvy pro plne cary
  
  plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), cex=p_cex, main=p_main, xlab=p_xlab, ylab= p_ylab)
  
  
  b1<-col2rgb(cl[1], alpha = T)
  b2<-col2rgb(cl[2], alpha = T)
  
  cooA<-rgb(red = b1[1], green=b1[2], blue=b1[3], max = 255, alpha = 50)
  cooB<-rgb(red = b2[1], green=b2[2], blue=b2[3], max = 255, alpha = 50)
  
  cl<-c(cooA,cooB)
  
  #prvni krivka
  if (is.list(vstupA) & inherits(vstupA, "list"))
  {
    dfA<-vstupA[[1]]
  }else if (inherits(vstupA, "data.frame"))
  {
    dfA<-vstupA
  }
  
  polygon(c(xaxis,rev(xaxis)),c(dfA[1,],rev(dfA[3,])),col = cl[1], border = FALSE)
  lines(xaxis,dfA[2,], lwd=2, col = brv[1])   #prumer
  
  #druha krivka
  if (is.list(vstupB) & inherits(vstupB, "list"))
  {
    dfB<-vstupB[[1]]
  }else if (inherits(vstupB, "data.frame"))
  {
    dfB<-vstupB
  }
  
  polygon(c(xaxis,rev(xaxis)),c(dfB[1,],rev(dfB[3,])),col = cl[2], border = FALSE)
  lines(xaxis,dfB[2,], lwd=2, col = brv[2])   #prumer
  
  popis <- c(descrA, descrB)
  if (showLegend)
  {
    legend('topright',inset=0.05,popis,lty=1,col=brv,title=NULL)
  }
}

#Zobrazime data prubehy zatacek ve vstupu a pridame prumer
Show_TurnAndMean<- function(vstup,prumer,xaxis,descr="",sloupce,okno=F,losaX="time [ms]",losaY="Distance spline [m]",bmean="black",showX=T)
{
  #vstup=list_dfRL
  #prumer=CI_MeanRL
  #xaxis = time_axis
  #descr = "Vsechny zatacky"
  #okno=F
  #sloupce <- 1:length(time_axis)
  
  
  p_xlab <- losaX
  p_ylab <- losaY
  p_main <- descr
  
  l_lwd = 1.2  #tloustka cary zatacky
  m_lwd = 4 #tlouska cary prumeru
  p_cex <- 0.3
  xminp<-0
  xmaxp<-15000
  
  if (okno) {
    dev.new(noRStudioGD = TRUE)
  }
  
  cl <- rainbow(nrow(vstup[[1]]))  
  
  if(showX)
    plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), cex=p_cex, main=p_main, xlab=p_xlab, ylab= p_ylab)
  else
    plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(-1, 5.5), cex=p_cex, main=p_main, xlab=p_xlab, ylab= p_ylab, xaxt="n")
  
  #zobrazime cary zatacek
  for(i in 1:nrow(vstup[[1]])) {
    lines(xaxis,vstup[[1]][i,sloupce], lwd=l_lwd, col = cl[i])
  }
  
  lines(xaxis,prumer[[1]][2,], lwd=m_lwd, col = bmean, lty=2)
  
}


#Radiany na stupne
rad2deg <- function(rad) {
  (rad * 180) / (pi)
}

Show_ResponseTime <-function(vstup, timeaxe, casR, casU, zmn, vzdMin, vzdMax, popis="", show_val=T, okno=F,labx="",laby="", offR=2.5, offU=3.5, lposY=5)
{
  #vstup<-data_Resp
  #timeaxe<-time_axis
  #casR <- indexReakce*20
  #casU <- indexUstaleni*20
  #zmn <- zmena
  #vzdMin <- mi 
  #vzdMax <- ma
  #show_val <- T
  #popis<-"mean RL"
  
  if(is.null(labx))
  {
    p_xlab <- NULL
  } else{
    if(labx=="")
      p_xlab <- "time [ms]"
    else
      p_xlab <- labx
  }
  
  if(is.null(laby))
  {
    p_ylab <- NULL
  } else{
    if(laby=="")
      p_ylab <- "Vzdalenost od spline [m]"
    else
      p_ylab <- laby
  }
  
  if (is.null(popis))
  {
    p_main <- NULL
  }else
  {
    if(popis=="")
      p_main <- sprintf("Reakce na jednotkovy skok (zmena %sm)",round(zmn,2))
    else
      p_main <- sprintf("Reakce na jednotkovy skok (zmena %sm), %s",round(zmn,2),popis)
  }
  p_col <- "black"
  p_cex <- 0.7
  minT<-0
  maxT<-15000
  
  if (okno) {
    dev.new(noRStudioGD = TRUE)
  }
  
  plot(1, type = 'n', xlim = c(minT, maxT), ylim = c(-1, 5.5), cex=p_cex, main=p_main, xlab=p_xlab, ylab= p_ylab)
  lines(timeaxe,vstup, lwd=1.2, col = p_col)
  abline(v=casR, col=c("red"), lty=c(2), lwd=c(1))
  abline(v=casU, col=c("red"), lty=c(2), lwd=c(1))
  abline(h=vzdMin, col=c("blue"), lty=c(2), lwd=c(1))
  abline(h=zmn, col=c("gray"), lty=c(2), lwd=c(1))
  abline(h=-zmn, col=c("gray"), lty=c(2), lwd=c(1))
  abline(h=vzdMax, col=c("blue"), lty=c(2), lwd=c(1))
  abline(h=vzdMax-zmn, col=c("gray"), lty=c(2), lwd=c(1))
  coo<-rgb(red = 127, green=127, blue=127, max = 255, alpha = 50)
  polygon(c(timeaxe,rev(timeaxe)),c(rep(zmn,length(timeaxe)),rep(-zmn,length(timeaxe))),col = coo, border = FALSE)
  polygon(c(timeaxe,rev(timeaxe)),c(rep(vzdMax,length(timeaxe)),rep(vzdMax-zmn,length(timeaxe))),col = coo, border = FALSE)
  if (show_val)
  {
    #text(x=casR, y = lposY, labels = sprintf("%ss",casR/1000), offset = offR, cex = 1, col = "black")
    #text(x=casU+offU, y = lposY, labels = sprintf("%ss",casU/1000), offset = offU, cex = 1, col = "black")
    text(x=casR+offR, y = lposY, labels = sprintf("%ss",casR/1000), cex = 1, col = "black")
    text(x=casU+offU, y = lposY, labels = sprintf("%ss",casU/1000), cex = 1, col = "black")
  }
}

Get_Resp_Ustal <-function(vstup, procZM=0.1, casVzorku=20)
{
  #vstup <- CI_MeanRL  #2 record obsahuje prumer
  #procZM<-0.1 #zmena 10% maximalni hodnoty je brana jako reakce
  #casVzorku<-20
  
  df<-data.frame(IxReakce=numeric(0), IxUstaleni=numeric(0), 
                 MinDst=numeric(0), MaxDst=numeric(0), Zmena=numeric(0))
  
  if (is.list(vstup) & inherits(vstup, "list"))
  {
    krok<-1
    for(l in vstup)
    {
      #najdeme cas kdy od start klesla hodnota o 10% a taky ukonceni regulace odzadu kdy stoupla o 10%
      data_Resp<-l[2,] #prumery
      mi<-min(data_Resp)
      ma<-max(data_Resp)
      zmena<-ma*procZM
      indexReakce<-1
      #nalezeni indexu casu reakce
      for (i in 1:length(data_Resp))
      {
        if(data_Resp[i]<(ma-zmena)){
          indexReakce<-i
          break
        }
      }
      indexUstaleni<-1
      #nalezeni indexu ustaleni
      for (i in rev(1:length(data_Resp)))
      {
        if(abs(data_Resp[i])>(zmena))  #hodnota je mimo rozsah kolem 0
        {
          indexUstaleni<-i
          break
        }
      }
      df[krok,]<-c(indexReakce*casVzorku,indexUstaleni*casVzorku,mi,ma,zmena)
      krok<-krok+1    
    }
    return(df)
    
  } else if (inherits(vstup, "data.frame"))
  {
    #na vstupu je dataframe hodnot
    krok<-1
    for(ri in 1:nrow(vstup))
    {
      data_Resp<-vstup[ri,] #hodnoty
      mi<-min(data_Resp)
      ma<-max(data_Resp)
      zmena<-ma*procZM
      indexReakce<-1
      #nalezeni indexu casu reakce
      for (i in 1:length(data_Resp))
      {
        if(data_Resp[i]<(ma-zmena)){
          indexReakce<-i
          break
        }
      }
      indexUstaleni<-1
      #nalezeni indexu ustaleni
      for (i in rev(1:length(data_Resp)))
      {
        if(abs(data_Resp[i])>(zmena))  #hodnota je mimo rozsah kolem 0
        {
          indexUstaleni<-i
          break
        }
      }
      
      df[krok,]<-c(indexReakce*casVzorku,indexUstaleni*casVzorku,mi,ma,zmena)
      krok<-krok+1
    }
    return(df)
  } else
  {
    krok<-1
    #na vstupu je jen vektor prumernych hodnot 
    data_Resp<-vstup #prumery
    mi<-min(data_Resp)
    ma<-max(data_Resp)
    zmena<-ma*procZM
    indexReakce<-1
    #nalezeni indexu casu reakce
    for (i in 1:length(data_Resp))
    {
      if(data_Resp[i]<(ma-zmena)){
        indexReakce<-i
        break
      }
    }
    indexUstaleni<-1
    #nalezeni indexu ustaleni
    for (i in rev(1:length(data_Resp)))
    {
      if(abs(data_Resp[i])>(zmena))  #hodnota je mimo rozsah kolem 0
      {
        indexUstaleni<-i
        break
      }
    }
    
    df[krok,]<-c(indexReakce*casVzorku,indexUstaleni*casVzorku,mi,ma,zmena)
    return(df)
  }
  return(NULL)
}


#Rozdeleni na leve a prave zatacky
#vracime dva seznamy s daty 15s kazde zatacky
DivideDataLR<- function(vstup, lstStartIx, atrCas="Time_ms",delkaReg=15000,atrTimeStep="TimeFromStep")
{

  lstL<-list()
  lstR<-list()
  lz<-1
  rz<-1
  for (i in lstStartIx)
  {
    seznam<-vstup[FALSE,]
    
    st<-vstup[abs(i),atrCas]
    ix<-abs(i)
    while (TRUE)
    {
      radek<-vstup[ix,]
      radek$TimeFromStep<-vstup[ix,atrCas]-st
      if ((vstup[ix,atrCas]-st)<=delkaReg)
      {
        seznam<-rbind(seznam,radek)
        ix<-ix+1
        if (ix>nrow(vstup))
          break;
      }else{
        #prekrocen cas tak zapiseme do globalnich seznamu
        #kdyz je index zaporny je to zatacka doleva
        if (i>0){
          lstR[[rz]]<-seznam
          rz<-rz+1
        } else{
          lstL[[lz]]<-seznam
          lz<-lz+1
        }
        break;
      }
    }
  }
  
  ret<-list()
  ret[["L"]]<-lstL
  ret[["R"]]<-lstR
  return (ret)
}

#Zjisteni rozdilu mezi casy vzorkovani
Get_TimeDiff<-function(seznam,atrTimeStep="TimeFromStep")
{
  intervaly<-lapply(seznam,FUN=function(x){x[,atrTimeStep]})
  rw<-max(unlist(lapply(intervaly, FUN=function(v){length(v)})))
  
  dfCasy<-data.frame(matrix(0, nrow = rw, ncol = length(intervaly)))
  for (i in 1:length(intervaly)){
    dfCasy[1:length(intervaly[[i]]),i]<-intervaly[[i]]
  }
  
  pmx<-apply(dfCasy[, 1:ncol(dfCasy)], 1, max)
  pmn<-apply(dfCasy[, 1:ncol(dfCasy)], 1, min)
  
  return(pmx-pmn)
}

#Vraci seznam rozdilu casu mezi vzorky jako table
Get_RozdilVzorku <- function(seznam,atrCas)
{
  return (lapply(seznam,FUN=function(v){table(diff(v[,atrCas]))}))
}

#Provede linearni resampling dat
DoInterpolace <-function(origData, atrCas="Time_ms",atrDst = "SplineDistance", delkaT = 15000, showchart=FALSE, sampleTime=20,yLab="Distance spline")
{
  rozdil<-diff(origData[,atrCas])
  manVzorekT<-mean(rozdil)
  cas<-c(0,cumsum(rozdil))
  f<-approxfun(cas,origData[,atrDst])
  
  interpolace<-f(seq(from=0,to=delkaT,by=sampleTime))  
  #musime vlozit posledni vzorek stejny jako predposledni
  interpolace[length(interpolace)]<-interpolace[length(interpolace)-1]  #end(interpolace)[1]
  
  if(showchart){
    p_cex <- 0.2
    p_xlab <- "time [ms]"
    p_ylab <- yLab
    p_main <- sprintf("Resampled data (%sms)",sampleTime)
    
    dev.new()
    par(mfrow=c(2,1)) 
    plot(seq(from=0,to=delkaT,by=sampleTime),interpolace,
         cex=p_cex,main=p_main,xlab=p_xlab, ylab= p_ylab)
    abline(h=0, col=c("orange"), lty=c(2), lwd=c(1.5))
    
    p1_main<-'Original sampling'
    plot(cas,origData[,atrDst], cex=p_cex, main=p1_main, xlab=p_xlab, ylab= p_ylab)
    abline(h=0, col=c("orange"), lty=c(2), lwd=c(1.5))
    par(mfrow=c(1,1)) 
  }
  df<-data.frame(Time_ms=seq(from=0,to=delkaT,by=sampleTime),SplineDistance=interpolace)
  colnames(df)<-c(atrCas,atrDst)
  return(df)
}

#Rozdeleni dat na skupiny v poradi
Get_IndexSkupiny <- function(pocZaznamu,pocetDeleni)
{
  #pocZaznamu<-13
  #pocetDeleni<-3
  
  chunklength<-round(pocZaznamu/pocetDeleni)
  skupiny<-split(1:pocZaznamu, ceiling(seq_along(1:pocZaznamu)/chunklength))
  if (length(skupiny)>pocetDeleni)
  {
    skupiny[[pocetDeleni]]<-c(skupiny[[pocetDeleni]],skupiny[[pocetDeleni+1]])  
    skupiny[[pocetDeleni+1]]<- NULL
  }
  return(skupiny)
}

#Prevede dataframe faktory na cislo
DF_Factors2Num <- function (vstup,seznam)
{
  vstup[ , seznam] <- apply(vstup[ , seznam], 2, function(x) as.numeric(as.character(x)))
  return(vstup)
}


#Vratime dataframe podle seznamu indexu a parametru
# skupina: 1: All data, 2: all L, 3: all R, 4: all 2L, 5: all 2R, 6: all 3L, 7:all 3R
# ResampledDataL, ResampledDataR, deleniL2, deleniL3, deleniR2, deleniR3
Get_ResampletDF <- function (seznamRL, seznamRR, ixL2, ixL3, ixR2, ixR3, skupina)
{
  #seznamRL <- ResampledDataL
  #seznamRR <- ResampledDataR
  #ixL2 <- deleniL2
  #ixL3 <- deleniL3
  #ixR2 <- deleniR2
  #ixR3 <- deleniR3
  #skupina <- 1
  
  out <- list()
  
  dfL <- data.frame(t(seznamRL[[1]]))
  dfL$Smer<-NA
  dfL[ , 1:(ncol(dfL)-1)] <- apply(dfL[ , 1:(ncol(dfL)-1)], 2, function(x) as.numeric(as.character(x)))
  dfL <- dfL[0,]  #prazdny dataframe
  dfR <- dfL
  dfE <- dfL  #sablona prazdneho seznamu
  cnames<-colnames(dfL)
  #lapply(seznamRL,FUN=function(v){df<-rbind(df,v$SplineDistance)})
  
  invertL<-T  #leve zatacky invertujeme hodnotu
  if(skupina==1)
  {
    #jeden df vsechny data L i R
    for(d in seznamRR)
    {
      dfR<-rbind(dfR,setNames(t(data.frame(c(d[,2],"R"))),names(dfR)))  
    }
    colnames(dfR)<-cnames
    row.names(dfR)<-1:nrow(dfR)
    
    for(d in seznamRL)
    {
      if (invertL==T)
      { #invertovat
        dfL<-rbind(dfL,setNames(t(data.frame(c(d[,2]*-1.0,"L"))),names(dfL)))  
      }else{
        dfL<-rbind(dfL,setNames(t(data.frame(c(d[,2],"L"))),names(dfL)))  
      }
    }
    colnames(dfL)<-cnames
    row.names(dfL)<-1:nrow(dfL)
    dfO<-rbind(dfL,dfR)
    dfO<-DF_Factors2Num(dfO,1:(ncol(dfO)-1))
    out[["A"]]<-dfO
    return(out)
  }
  else if(skupina==2)
  {
    #jeden df vsechny data L
    for(d in seznamRL)
    {
      if (invertL==T)
      { #invertovat
        dfL<-rbind(dfL,setNames(t(data.frame(c(d[,2]*-1.0,"L"))),names(dfL)))  
      }else{
        dfL<-rbind(dfL,setNames(t(data.frame(c(d[,2],"L"))),names(dfL)))  
      }
    }
    colnames(dfL)<-cnames
    row.names(dfL)<-1:nrow(dfL)
    
    dfL<-DF_Factors2Num(dfL,1:(ncol(dfL)-1))
    out[["L"]]<-dfL
    return(out)
  }
  else if(skupina==3)
  {
    #jeden df vsechny data R
    for(d in seznamRR)
    {
      dfR<-rbind(dfR,setNames(t(data.frame(c(d[,2],"R"))),names(dfR)))  
    }
    colnames(dfR)<-cnames
    row.names(dfR)<-1:nrow(dfR)
    
    dfR<-DF_Factors2Num(dfR,1:(ncol(dfR)-1))
    out[["R"]]<-dfR
    return(out)
  }
  else if(skupina==4 || skupina==6)  #deleni na 2 nebo tri sady L
  {
    
    message("Prehodit L a R")
    stop()
    
    dfL <- dfE
    ixd<-1
    if(skupina==4)
      ixL<-ixL2
    else 
      ixL<-ixL3
    
    for (p in ixL)  #pocet deleni vsech zatacek vlevo
    {
      dfL <- dfE
      for(di in p) #indexy z dat
      {
        d<-seznamRL[[di]]
        dfL<-rbind(dfL,setNames(t(data.frame(c(d[,2],"L"))),names(dfL)))  
      }
      colnames(dfL)<-cnames
      row.names(dfL)<-1:nrow(dfL)
      
      dfL<-DF_Factors2Num(dfL,1:(ncol(dfL)-1))
      out[[ixd]]<-dfL
      ixd<-ixd+1
    }
    return(out) #dataframy obsahujici data zatacek L
  }
  else if(skupina==5 || skupina==7)  #deleni na 2 nebo tri sady R
  {
    message("Prehodit L a R")
    stop()
    
    dfR <- dfE
    ixd<-1
    if(skupina==5)
      ixR<-ixR2
    else 
      ixR<-ixR3
    
    for (p in ixR)  #pocet deleni vsech zatacek vlevo
    {
      dfR <- dfE
      for(di in p) #indexy z dat
      {
        d<-seznamRR[[di]]
        
        if (invertR==T)
        { #invertovat
          dfR<-rbind(dfR,setNames(t(data.frame(c(d[,2]*-1.0,"R"))),names(dfR)))  
        }else{
          dfR<-rbind(dfR,setNames(t(data.frame(c(d[,2],"R"))),names(dfR)))  
        }
      }
      colnames(dfR)<-cnames
      row.names(dfR)<-1:nrow(dfR)
      
      dfR<-DF_Factors2Num(dfR,1:(ncol(dfR)-1))
      out[[ixd]]<-dfR
      ixd<-ixd+1
    }
    return(out) #dataframy obsahujici data zatacek L
  }
}

#Vraci dataframe s prumerem po sloupcich
Get_ColMeans <- function (vstup, sloupce)
{
  return(data.frame(sapply(vstup, FUN=function(x){ colMeans(x[,sloupce]) })))
}

#Vraci prumernou hodnotu dat a CI ve forme dataFrame v listu
Get_MeansCI <-function (vstup,sloupce)
{
  #vstup<-list_dfL3
  #sloupce <- 1:751
  
  vystup<-list()
  ix<-1
  for (d in vstup)
  {
    vystup[[ix]]<-apply(d[,sloupce],2,FUN=function(x){CI(x)})  #1 rows, 2 colums vrati matici 3x751
    ix<-ix+1
  }
  return(vystup)
}

#Vraci prumernou hodnotu dat a CI ve forme dataFrame v listu
Get_MeansCIDF <-function (vstupdf,sloupce)
{
  #vstupdf<-dfTotalDataL
  #sloupce <- 1:751
  
  vystup<-list()
  vystup<-apply(vstupdf[,sloupce],2,FUN=function(x){CI(x)})  #1 rows, 2 colums vrati matici 3x751
  return(vystup)
}

#Boxploty s p-value ------------------------------------------------------------
#https://coderedirect.com/questions/455701/how-to-change-x-axis-labels-in-ggboxplot
ShowBoxPltCI <- function (vstup, porovnani, atribut, grupa, labelList, ltitle="", losaX="", losaY="",barvy=c("red","blue","black"))
{
  #vstup<-dfTotalTimes
  
  #lablist<-list(atrb=c("All","Right","Left"))
  #my_comparisons <- list( c("A", "R"), c("A", "L"), c("R", "L") )
  #osaX<-"Zatacka"
  #osaY<-"Cas reakce"
  #title<-"Cas reakce vs Zatacka"
  #grupa<-"Zatacka"
  #atribut<-"Reakce"
  
  #get_palette("Dark2", 3)
  #get_palette("npg", 3)
  #palette = c("#00AFBB", "#E7B800", "#FC4E07"))
  #get_palette(c("#00AFBB", "#FC4E07"), 3)
  #set_palette(p, "jco")

  if(is.null(ltitle))
  {
    title=NULL
  }else{
    if (ltitle=="")
      title=""
    else
      title = ltitle
  }
  
  if(is.null(losaX))
  {
    osaX=NULL
  }else{
    if (losaX=="")
      osaX=""
    else
      osaX = losaX
  }
  
  if(is.null(losaY))
  {
    osaY=NULL
  }else{
    if (losaY=="")
      osaY=""
    else
      osaY = losaY
  }
  
  pltA<-c()
  plt<-barvy
  for (c in barvy)
  {
    b<-col2rgb(c,alpha = T)
    pltA<-c(pltA,rgb(b[1],b[2],b[3],128,maxColorValue = 255))
  }
  
  lablist<-labelList
  xlabtic<-lablist[[1]]
  my_comparisons <- porovnani
  fx<-as.formula(sprintf("%s ~ %s",atribut,grupa))
  compare_means(formula = fx, vstup, method = "wilcox.test")
  p <- ggboxplot(vstup, x = grupa, y = atribut,
                 color = grupa, palette = plt, fill = grupa, alpha=0.2,
                 #palette = "jco",
                 #facet.by = facetAtr,
                 panel.labs = lablist,
                 add = "jitter",
                 xlab = osaX,
                 ylab = osaY,
                 title = title)+ 
                 scale_x_discrete(labels=xlabtic)+
                 theme(legend.position="none")+
                 stat_compare_means(comparisons = my_comparisons)
                 #   #stat_compare_means(label.x = 1.5)
                 #   #stat_compare_means(method = "t.test")
                 #   #stat_compare_means( aes(label = ..p.signif..),label.x = 1.5, label.y = 40)
                 #   #stat_compare_means( aes(label = "p.signif"),label.x = 1.5, label.y = 80)
  print(p)
}

#sila testu pro ruzne parametry Correlace
PowerCorrelationPlot <- function ()
{
  # range of correlations
  r <- seq(0.1,0.7,.01)
  nr <- length(r)
  
  # power values
  p <- seq(.3,.9,.1)
  np <- length(p)
  
  # obtain sample sizes
  samsize <- array(numeric(nr*np), dim=c(nr,np))
  for (i in 1:np){
    for (j in 1:nr){
      result <- pwr.r.test(n = NULL, r = r[j],
                           sig.level = .05, power = p[i],
                           alternative = "two.sided")
      samsize[j,i] <- ceiling(result$n)
    }
  }
  
  # set up graph
  xrange <- range(r)
  yrange <- round(range(samsize))
  colors <- rainbow(length(p))
  plot(xrange, yrange, type="n",
       xlab="Correlation Coefficient (r)",
       ylab="Sample Size (n)" )
  
  # add power curves
  for (i in 1:np){
    lines(r, samsize[,i], type="l", lwd=2, col=colors[i])
  }
  
  # add annotation (grid lines, title, legend)
  abline(v=0, h=seq(0,yrange[2],50), lty=2, col="grey89")
  abline(h=0, v=seq(xrange[1],xrange[2],.02), lty=2,
         col="grey89")
  title("Sample Size Estimation for Correlation Studies\n
  Sig=0.05 (Two-tailed)")
  legend("topright", title="Power", as.character(p), fill=colors)
}