-
Notifications
You must be signed in to change notification settings - Fork 4
Fix ess imse update #16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
c35c44a
update min corr pair; fixes #13
bob-carpenter 3167571
doc for autocorr, includes in init
bob-carpenter 6827f39
boundary cond for ess, autocorr, fixes #13, fixes #15
bob-carpenter c7c9221
fix merge conflict
c282e8a
ess tests for anticorr
cfae7c8
test coverage: end_pos_pairs return
bob-carpenter 3acce34
clarify doc and format
bob-carpenter 7018496
checkpoint iat impls w/o tests
bob-carpenter e094605
add IAT functions with tests
bob-carpenter ea6ca6e
fix typos and doc correctness for iat
bob-carpenter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import numpy as np | ||
| import numpy.typing as npt | ||
|
|
||
| FloatType = np.float64 | ||
| VectorType = npt.NDArray[FloatType] | ||
|
|
||
| def autocorr(chain: VectorType) -> VectorType: | ||
| """Return sample autocorrelations at all lags from 0 to the length | ||
| of the sequence minus 1 for the specified sequence. The returned | ||
| vector will thus be the same size as the input vector. | ||
|
|
||
| Algorithmically, this function calls NumPy's fast Fourier transform | ||
| and inverse fast Fourier transforms. | ||
|
|
||
| Parameters: | ||
| chain: sequence whose autocorrelation is returned | ||
|
|
||
| Returns: | ||
| autocorrelation estimates at all lags for the specified sequence | ||
|
|
||
| Raises: | ||
| ValueError: if the size of the chain is less than 2 | ||
| """ | ||
| if len(chain) < 2: | ||
| raise ValueError(f"autocorr requires len(chain) >= 2, but {len(chain)=}") | ||
| size = 2 ** np.ceil(np.log2(2 * len(chain) - 1)).astype("int") | ||
| var = np.var(chain) | ||
| ndata = chain - np.mean(chain) | ||
| fft = np.fft.fft(ndata, size) | ||
| sq_mag = np.abs(fft) ** 2 | ||
| N = len(ndata) | ||
| acorr = np.fft.ifft(sq_mag).real / var / N | ||
| return acorr[0:N] |
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| import numpy as np | ||
| import numpy.typing as npt | ||
| import bayes_kit.autocorr as autocorr | ||
|
|
||
| FloatType = np.float64 | ||
| IntType = np.int64 | ||
| VectorType = npt.NDArray[FloatType] | ||
|
|
||
|
|
||
| def _end_pos_pairs(acor: VectorType) -> IntType: | ||
| """ | ||
| Return the index 1 past the last positive pair of autocorrelations | ||
| starting on an even index. The sequence `acor` should contain | ||
| autocorrelations from a Markov chain with values at the lag given by | ||
| the index (i.e., `acor[0]` is autocorrelation at lag 0 and `acor[5]` | ||
| is autocorrelation at lag 5). | ||
|
|
||
| The even index pairs are (0, 1), (2, 3), (4, 5), ... This function | ||
| scans the pairs in order, and returns 1 plus the second index of the | ||
| last such pair that has a positive sum. | ||
|
|
||
| Examples: | ||
| ```python | ||
| _end_pos_pairs([]) = 0 | ||
| _end_pos_pairs([1]) = 0 | ||
| _end_pos_pairs([1, 0.4]) = 2 | ||
| _end_pos_pairs([1, -0.4]) = 2 | ||
| _end_pos_pairs([1, -0.5, 0.25, -0.3]) == 2 | ||
| _end_pos_pairs([1, -0.5, 0.25, -0.1]) == 4 | ||
| _end_pos_pairs([1, -0.5, 0.25, -0.3, 0.05]) == 2 | ||
| _end_pos_pairs([1, -0.5, 0.25, -0.1, 0.05]) == 4 | ||
| ``` | ||
|
|
||
| Parameters: | ||
| acor (VectorType): Input sequence of autocorrelations at lag given by index. | ||
|
|
||
| Returns: | ||
| The index 1 past the last positive pair of values starting on an even index. | ||
| """ | ||
| N = len(acor) | ||
| n = 0 | ||
| while n + 1 < N: | ||
| if acor[n] + acor[n + 1] < 0: | ||
| return n | ||
| n += 2 | ||
| return n | ||
|
|
||
|
|
||
| def iat_ipse(chain: VectorType) -> FloatType: | ||
| """ | ||
| Return an estimate of the integrated autocorrelation time (IAT) | ||
| of the specified Markov chain using the initial positive sequence | ||
| estimator (IPSE). | ||
|
|
||
| The integrated autocorrelation time of a chain is defined to be | ||
| the sum of the autocorrelations at every lag (positive and negative). | ||
| If `autocorr[n]` is the autocorrelation at lag `n`, then | ||
|
|
||
| ``` | ||
| IAT = SUM_{n in Z} autocorr[n], | ||
| ``` | ||
|
|
||
| where `Z = {..., -2, -1, 0, 1, 2, ...}` is the set of integers. | ||
|
|
||
| Because the autocorrelations are symmetric, `autocorr[n] == autocorr[-n]` and | ||
| `autocorr[0] = 1`, if we double count the non-negative entries, we will have | ||
| counted `autocorr[0]`, which is 1, twice, so we subtract 1, to get | ||
|
|
||
| ``` | ||
| IAT = -1 + 2 * SUM_{n in Nat} autocorr[n], | ||
| ``` | ||
|
|
||
| where `Nat = {0, 1, 2, ...}` is the set of natural numbers. | ||
|
|
||
| References: | ||
| Geyer, Charles J. 2011. “Introduction to Markov Chain Monte Carlo.” | ||
| In Handbook of Markov Chain Monte Carlo, edited by Steve Brooks, | ||
| Andrew Gelman, Galin L. Jones, and Xiao-Li Meng, 3–48. Chapman; | ||
| Hall/CRC. | ||
|
|
||
| Parameters: | ||
| chain: A Markov chain. | ||
|
|
||
| Return: | ||
| An estimate of the integrated autocorrelation time (IAT) for the specified chain. | ||
|
|
||
| Raises: | ||
| ValueError: if there are fewer than 4 elements in the chain | ||
| """ | ||
| if len(chain) < 4: | ||
| raise ValueError(f"ess requires len(chains) >= 4, but {len(chain)=}") | ||
| acor = autocorr(chain) | ||
| n = _end_pos_pairs(acor) | ||
| return 2 * acor[0:n].sum() - 1 | ||
|
|
||
|
|
||
| def iat_imse(chain: VectorType) -> FloatType: | ||
| """ | ||
| Return an estimate of the integrated autocorrelation time (IAT) | ||
| of the specified Markov chain using the initial monotone sequence | ||
| estimator (IMSE). | ||
|
|
||
| The IMSE imposes a monotonic downward condition on the sum of pairs, | ||
| replacing each sum with the minimum of the sum and the minimum of | ||
| the previous sums. | ||
|
|
||
| References: | ||
| Geyer, C.J., 1992. Practical Markov chain Monte Carlo. Statistical Science | ||
| 7(4):473--483. | ||
|
|
||
| Geyer, Charles J. 2011. “Introduction to Markov Chain Monte Carlo.” | ||
| In Handbook of Markov Chain Monte Carlo, edited by Steve Brooks, | ||
| Andrew Gelman, Galin L. Jones, and Xiao-Li Meng, 3–48. Chapman; | ||
| Hall/CRC. | ||
|
|
||
| Parameters: | ||
| chain: A Markov chain. | ||
|
|
||
| Return: | ||
| An estimate of integrated autocorrelation time (IAT) for the specified chain. | ||
|
|
||
| Throws: | ||
| ValueError: If there are fewer than 4 elements in the chain. | ||
| """ | ||
| if len(chain) < 4: | ||
| raise ValueError(f"iat requires len(chains) >=4, but {len(chain) = }") | ||
| acor = autocorr(chain) | ||
| n = _end_pos_pairs(acor) | ||
| prev_min = acor[0] + acor[1] | ||
| acor_sum = prev_min | ||
| i = 2 | ||
| while i + 1 < n: | ||
| # enforce monotone downward condition (slow loop) | ||
| prev_min = min(prev_min, acor[i] + acor[i + 1]) | ||
| acor_sum += prev_min | ||
| i += 2 | ||
| return 2 * acor_sum - 1 | ||
|
|
||
|
|
||
| def iat(chain: VectorType) -> FloatType: | ||
| """ | ||
| Return an estimate of the integrated autocorrelation time (IAT) | ||
| of the specified Markov chain. Evaluated by delegating to the | ||
| initial monotone sequence estimator, `iat_imse(chain)`. | ||
|
|
||
| The IAT can be less than one in cases where the Markov chain is | ||
| anti-correlated. | ||
|
|
||
| Parameters: | ||
| chain: A Markov chain. | ||
|
|
||
| Return: | ||
| The integrated autocorrelation time (IAT) for the specified chain. | ||
|
|
||
| Throws: | ||
| ValueError: If there are fewer than 4 elements in the chain. | ||
| """ | ||
| return iat_imse(chain) | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would there be any reason (performance?) someone might want the
ipseinstead? Is it worth exposing the ability to choose that? (I'm guessing not really)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm OK getting rid of IPSE; even though it's a bit faster than IMSE, it has an overestimation bias. Do you think I should get rid of it?
I still think we should keep the
ess_imseandiat_imsedefinitions and delegateessandiat. I know at least for ess we will have further estimators that work cross chain. The other option is to not provide a default implementation. I'm always on the fence about choosing default implementations for users, but in the end, I think they're going to want o seeess()oriat()in most applied code.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't have a strong feeling about IPSE--it's there, it's implemented, it works; no reason to discard that work, especially if we might want to expose it later. The counterargument is that it's more surface area, and unreachable unused code gets out of date (not that any code in Python is ever truly unreachable).
Unfortunately, I'm kind of clueless whether anybody would in practice actually want to have a choice here.
And if we expose that choice, however we did so, I could imagine a tricky situation where we wind up having some deeply nested calls such that there's an inconsistency between the implementations used in different places--whether because it's hard to make sure the "use-this-implementation" flag gets passed around everywhere
essis called, or because users calless_ipsein their own direct code but our version doesn't. Of course, again, dunno if such a scenario is actually likely in practice.I guess it would come down to three questions:
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I talked to @WardBrian and concluded we should leave it in for pedagogical purposes.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sounds good to me. All of this points to the same conclusion--leave it in for pedagogy (and so people could technically call it if they really wanted to), but have a standard pathway that delegates to a specific implementation.