Skip to content

Vectorize annual homogenous flickering process#16

Open
ConnectedSystems wants to merge 1 commit into
peterson-tim-j:masterfrom
ConnectedSystems:vectorize-ann-homogenous-flickering
Open

Vectorize annual homogenous flickering process#16
ConnectedSystems wants to merge 1 commit into
peterson-tim-j:masterfrom
ConnectedSystems:vectorize-ann-homogenous-flickering

Conversation

@ConnectedSystems

Copy link
Copy Markdown

Simple modification to vectorize implementation.

I expect a small performance improvement that increases with the number of state spaces.

Apologies for causing extra work but I have no test data and am unfamiliar with R testing practices.
I think it is correct but have not checked that results are identical.

@ConnectedSystems

ConnectedSystems commented Mar 12, 2026

Copy link
Copy Markdown
Author

I realised it would be simple to test the implementation directly (must still be jet lagged).

Example data for two and three states. I've assumed the rows should sum to 1?

T2 <- matrix(c(0.8, 0.2,
               0.3, 0.7), nrow = 2, byrow = TRUE)

T3 <- matrix(c(0.7, 0.2, 0.1,
               0.1, 0.6, 0.3,
               0.2, 0.3, 0.5), nrow = 3, byrow = TRUE)

And run these with the original and modified implementation

getStateFlicker_original <- function(Tprob) {
  nStates <- nrow(Tprob)
  if (nStates == 1) return(0)
  
  flickerValue <- rep(0, nStates)
  for (i in 1:nStates) {
    ind      <- (1:nStates)[-i]
    prob.out <- sum(Tprob[i, ind])
    prob.in  <- sum(Tprob[ind, i])
    flickerValue[i] <- (prob.in + prob.out) - 1
  }
  return(flickerValue)
}

getStateFlicker_refactored <- function(Tprob) {
  nStates <- nrow(Tprob)
  if (nStates == 1) return(0)
  return(colSums(Tprob) - 2 * diag(Tprob))
}

Comparing the outputs from the above shows the two are equivalent.

Rough timings I've taken show runtime is about 60% of the original (3ms vs 5ms) so while a negligible overall, it could add up when doing long (and repeated) simulations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant