Skip to content

[mix_model.md] Update np.random → Generator API#978

Merged
jstac merged 1 commit into
mainfrom
update-rng-mix-model
Jul 18, 2026
Merged

[mix_model.md] Update np.random → Generator API#978
jstac merged 1 commit into
mainfrom
update-rng-mix-model

Conversation

@Chihiro2000GitHub

Copy link
Copy Markdown
Contributor

Summary

This PR migrates legacy NumPy random API usage in mix_model.md as part of QuantEcon/meta#299.

The lecture used the module-level np.random.seed / @jit set_seed() idiom for reproducibility. It is replaced with an explicit seeded generator rng = np.random.default_rng(142857) that is passed into the simulation functions.

Details

  • Replaced the np.random.seed(142857) / @jit def set_seed() mechanism with rng = np.random.default_rng(142857). The lecture reset the seed at two points (setup cell and before the long-horizon paths), so rng is (re)created at both points to preserve that behaviour.
  • Migrated np.random.betarng.beta and np.random.randrng.random, and threaded rng as an explicit argument through simulate, draw_lottery, draw_lottery_MC, simulate_mixed, and plot_π_seq, updating all call sites.
  • Kept the existing fixed seed (142857); the original lecture already seeded for reproducibility, so no new seed was introduced.

Note for reviewers

  • π_lim (used with np.vectorize): π_lim is wrapped by π_lim_v = np.vectorize(π_lim) and calls simulate_mixed. Adding rng as a positional argument would make np.vectorize try to broadcast it, so I left π_lim's signature unchanged and let it reference the shared module-level rng inside. This reuses the same single generator, just via closure rather than an argument. The explicit-argument alternative would be:
    def π_lim(α, rng, T=5000, π_0=0.4):
        ...
        l_arr = simulate_mixed(α, rng, T, N=1)[0]
        ...
    π_lim_v = np.vectorize(π_lim, excluded=['rng'])
    # called as π_lim_v(α_arr_x, rng=rng)
    Happy to switch to that if you prefer keeping rng explicit everywhere.
  • Prose at "method 1": the pseudo-code bullet previously said "use the numpy.random.choice function to flip an unfair coin". I updated it to "use the rng.choice method …" to match the Generator API. Note the actual draw_lottery code implements the coin flip with rng.random() <= p rather than rng.choice, so this is a conceptual description — let me know if you'd rather word it differently.
  • x=0.5 convergence figure: under the new generator the realized 200-step path in the "three different prior beliefs" figure (T_mix = 200) converges less visibly to x=0.5 than before, though the text says the posterior means "eventually converge". The theoretical statement still holds; if you'd like the figure to match more tightly, T_mix could be increased. I left it unchanged to keep this PR focused on the RNG migration.
  • The @jit functions (simulate, draw_lottery) have no parallel=True/prange, so rng is passed in explicitly (Case 2). The numpyro/JAX MCMC uses jax.random.PRNGKey, which is not an np.random.* call and is left unchanged. Verified locally that the notebook compiles and runs under Numba 0.62.1.

Hi @mmcky and @HumphreyYang, I'd be grateful if you could take a look when you have time.

@github-actions

Copy link
Copy Markdown

📖 Netlify Preview Ready!

Preview URL: https://pr-978--sunny-cactus-210e3e.netlify.app

Commit: f37f5aa

📚 Changed Lectures


Build Info

@jstac
jstac merged commit 37daf78 into main Jul 18, 2026
1 check passed
@jstac
jstac deleted the update-rng-mix-model branch July 18, 2026 21:04
@jstac

jstac commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Many thanks @Chihiro2000GitHub , nice work. There is, however, an issue of overlapping PRs. I'll write separately to explain.

jstac pushed a commit that referenced this pull request Jul 19, 2026
Rebased onto main. Fixes #577: converts bare/awkward links to MyST
{doc} and inline-link form, applies sentence-case section headings,
and cleans up prose/whitespace. Preserves the rng changes from #978.
jstac pushed a commit that referenced this pull request Jul 19, 2026
Rebased onto main on top of the style-guide branch (#642). Converts
the Numba/NumPy simulation code to JAX (jax.random keys, jax.lax.scan,
jax.vmap), replacing the interim np.random Generator migration from
#978. Keeps #642's link/heading/prose fixes.

Verified: lecture runs end-to-end (JAX cells + numpyro MCMC) on CPU.
jstac pushed a commit that referenced this pull request Jul 19, 2026
Rebased onto main. Fixes #577: converts bare/awkward links to MyST
{doc} and inline-link form, applies sentence-case section headings,
and cleans up prose/whitespace. Preserves the rng changes from #978.
jstac pushed a commit that referenced this pull request Jul 19, 2026
Rebased onto main (now containing the #642 style pass). Converts the
Numba/NumPy simulation code to JAX (jax.random keys, jax.lax.scan,
jax.vmap), superseding the interim np.random Generator migration (#978).

draw_lottery_MC now uses jax.scipy.stats.beta.cdf and a jax.random key
instead of scipy.stats + np.random, so the lecture no longer touches
NumPy's legacy RNG at all.

Verified: full lecture (JAX cells + numpyro NUTS MCMC) runs end-to-end
on CPU; MC draws match the target mixture density.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
jstac pushed a commit that referenced this pull request Jul 19, 2026
Rebased onto main (post #642 style pass). Converts the Numba/NumPy
simulation code to JAX (jax.random keys, jax.lax.scan, jax.vmap),
superseding the interim np.random Generator migration (#978).

Randomness uses explicit jax.random.key threading (keys passed into
simulate / draw_lottery / draw_lottery_MC / simulate_mixed / plot_π_seq
/ π_lim, split where needed) rather than deriving seeds from parameter
values, matching the JAX conversion style guide. draw_lottery_MC uses
jax.scipy.stats.beta.cdf, so the lecture no longer touches NumPy's
legacy RNG. Single seed 42 throughout.

Verified: full lecture (JAX cells + numpyro NUTS MCMC) runs end-to-end
on CPU; MC draws match the target mixture density.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
jstac added a commit that referenced this pull request Jul 19, 2026
* [mix_model] Convert code to JAX

Rebased onto main (post #642 style pass). Converts the Numba/NumPy
simulation code to JAX (jax.random keys, jax.lax.scan, jax.vmap),
superseding the interim np.random Generator migration (#978).

Randomness uses explicit jax.random.key threading (keys passed into
simulate / draw_lottery / draw_lottery_MC / simulate_mixed / plot_π_seq
/ π_lim, split where needed) rather than deriving seeds from parameter
values, matching the JAX conversion style guide. draw_lottery_MC uses
jax.scipy.stats.beta.cdf, so the lecture no longer touches NumPy's
legacy RNG. Single seed 42 throughout.

Verified: full lecture (JAX cells + numpyro NUTS MCMC) runs end-to-end
on CPU; MC draws match the target mixture density.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* [mix_model] Style-guide compliance pass

Bring the lecture into full style-guide compliance:

- figures: remove matplotlib titles (ax.set_title), drop hard-coded
  figsize, use lw=2 on all line charts, lower-case axis labels
- math: \mathbb{E} / \mathbb{P} for expectation/probability, \mathrm{Beta}
  for the distribution name, \log instead of log
- writing: IID (not i.i.d.), Bayes' law (not Bayes' Law / Bayes law)
- doclinks: same-series links use the [](name) auto-title form and drop
  the generic 'this quantecon lecture' text
- code: don't pip install jax at the top (GPU admonition covers it),
  remove the unused pandas import

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: John Stachurski <john.stachurski@gmail.com>
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.

2 participants