stan-dev / pystan

PyStan, a Python interface to Stan, a platform for statistical modeling. Documentation: https://pystan.readthedocs.io
ISC License
342 stars 59 forks source link

Test script failed #382

Closed beew closed 1 year ago

beew commented 1 year ago

Describe the bug

Test script failed

Describe your system

pystan installed via pip, version 3.6.0

Steps/Code to Reproduce

Just the standard script to test the installation

import stan

schools_code = """
data {
  int<lower=0> J;         // number of schools
  real y[J];              // estimated treatment effects
  real<lower=0> sigma[J]; // standard error of effect estimates
}
parameters {
  real mu;                // population treatment effect
  real<lower=0> tau;      // standard deviation in treatment effects
  vector[J] eta;          // unscaled deviation from mu by school
}
transformed parameters {
  vector[J] theta = mu + tau * eta;        // school treatment effects
}
model {
  target += normal_lpdf(eta | 0, 1);       // prior log-density
  target += normal_lpdf(y | theta, sigma); // log-likelihood
}
"""

schools_data = {"J": 8,
                "y": [28,  8, -3,  7, -1,  1, 18, 12],
                "sigma": [15, 10, 16, 11,  9, 11, 10, 18]}

posterior = stan.build(schools_code, data=schools_data, random_seed=1)

fit = posterior.sample(num_chains=4, num_samples=1000)

df = fit.to_frame()

These are the outputs

runfile('/home/beew/opt/python310/python-dev/stan_test.py', wdir='/home/beew/opt/python310/python-dev')
Traceback (most recent call last):

  File ~/lib/python3.10/site-packages/spyder_kernels/py3compat.py:356 in compat_exec
    exec(code, globals, locals)

  File ~/python-dev/stan_test.py:35
    posterior = stan.build(schools_code, data=schools_data, random_seed=1)

  File ~/lib/python3.10/site-packages/stan/model.py:519 in build
    return asyncio.run(go())

  File ~/lib/python3.10/asyncio/runners.py:33 in run
    raise RuntimeError(

RuntimeError: asyncio.run() cannot be called from a running event loop
ahartikainen commented 1 year ago

What is runfile function doing? I think this is the same error we see with jupyter so same solution should work

https://pystan.readthedocs.io/en/latest/faq.html

beew commented 1 year ago

What is runfile function doing? I think this is the same error we see with jupyter so same solution should work

https://pystan.readthedocs.io/en/latest/faq.html

Thanks! It works now by adding

import nest_asyncio
nest_asyncio.apply()

to the script.