In the white is Skiba’s W’balance that you all know and love. I’ve combined this now with the interval discovery algorithm so that we can now visualize the change in W’bal by interval in green.

## R script will run on selection.

##

## GC.activity()

## GC.metrics(all=FALSE)

##

## Get the current ride or metrics

##

#start here

require(changepoint)

#read power file from csv. file should be one column of power with header Power

act <- GC.activity()

y <- act$power

## Set Your CP W’ K and Pen

## K is a gain term for recovery introduced by Mike Patton

## Pen is the a term that penalizes for finding smaller intervals with the changepoint algorythm

CP <- 250

W <- 20000

k <- 1

Pen <- 7000

## Calculate W’bal with differential model

Wbal <- vector()

Wexp <- 0

u = 0

n = 1

while (n < length(y)){

if (y[n] > CP){

Wexp <- Wexp + y[n]- CP

Wbal[n] <- W – Wexp

n <- n + 1

u <- 0

}

else{

Wexp <- Wexp – (Wexp/W)*k*(CP-y[n])

Wbal[n] <- W – Wexp

n <- n + 1

u <- u + 1

print(Wbal[n])

}

}

## Make a time series with the power data

myts <- ts(y, start=c(1), end=c(length(y)), frequency= 1)

## Run the changepoint PELT algo, adjust pen.value to optimize penalty

mvalue1 = cpt.mean(myts, penalty=’Manual’,pen.value=’Pen*log(n)’, method=’PELT’)

## Calculate the duration for each interval found

time <- cpts(mvalue1)

time <- append(time, length(y))

## Calculate the delta Wbal for each interval

## pWbal is the Wbal at the start of the interval

pWbal <- vector()

dWbal <- vector()

i <- 1

pWbal[1] <- Wbal[1]

dWbal[1] <- Wbal[time[1]] – Wbal[1]

while(i < length(time)){

pWbal[i+1] <- Wbal[time[i]]

dWbal[i+1] <- Wbal[time[i+1]] – Wbal[time[i]]

i <- i + 1

}

## Recreate the full set of data points

i <- 1

ii <- 1

tpWbal <- vector()

tdWbal <- vector()

while (i < length(y)){

if (i < time[ii]){

tpWbal[i] <- pWbal[ii] – W

tdWbal[i] <- dWbal[ii]

i <- i+1

}

else{

ii <- ii + 1

}

}

##Visualize

plot(tdWbal, ylim = c(-W, W), col=’green’ )

lines(tdWbal,col=’green’)

grid()

lines(Wbal, col=’grey’)