Vectorize annual homogenous flickering process#16
Open
ConnectedSystems wants to merge 1 commit into
Open
Conversation
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.