#################################################################################################################
## Function to calculate time-integrated upstream mean velocity from step up to each sampling spot, 
## as well as water travel time
#################################################################################################################

###########################################################################################
## created by Marcus Klaus, Swedish University of Agricultural Sciences (SLU), Umeå, Sweden
## contact: marcus.klaus@slu.se
## last update: 2026/04/30
###########################################################################################

## INPUTS:
# data frame with several flow velocity observations per step-pool system
# where sampling spots are aligned with increasing distance from step in downstream direction

# data frame variables:
# Site... Sampling site
# d... Distance of sampling spot from step (m)
# velocity... flow velocity (m/s)

## OUTPUTS:
# V_cum... time-integrated upstream (harmonic) mean velocity (m/s)
# tt... travel time (s)

###########################################################################################

averageFlowVelocity <- function(Site, velocity, d){

  dx <- NULL
  dx <- NULL
  cum_dx <- NULL
  cum_dt <- NULL
  cum_dt <- NULL
  mean_velocity_bubble <- NULL
  
  for (i in 1:length(unique(Site))){
    id <- which(Site==unique(Site)[i])
    
    ## sort within site
    ord <- order(d[id])
    id <- id[ord]
    
    dxi = c(d[id][1], diff(d[id]))

    cum_dxi = cumsum(dxi)
    cum_dti = cumsum(dxi / velocity[id])
    mean_velocity_bubblei = cum_dxi / cum_dti
    
    dx = c(dx,dxi)
    cum_dx = c(cum_dx,cum_dxi)
    cum_dt = c(cum_dt,cum_dti)
    mean_velocity_bubble = c(mean_velocity_bubble,mean_velocity_bubblei)
    
  }

## travel time (m / (m/s) = s)
tt <- d/100/mean_velocity_bubble

return(data.frame(V_cum=mean_velocity_bubble,tt=tt))
}

