I cannot run simple examples in pystan

I am following this tutorial, but the examples do not run.

I have compiled successfully models with pystan recently, but these examples without model or data block seem problematic.

The first example is:

data {
  int<lower=0> N;
  real<lower=0, upper=1> theta;
}
generated quantities {
  int<lower=0, upper=N> y = binomial_rng(N, theta);
}

The python code is:

import stan

N = 100
θ = 0.3

with open('model.stan', 'r') as f:
    model = f.read()

data = {'N': N, 'theta': θ}

posterior = stan.build(model, data, random_seed=123)
res = posterior.sample(num_chains=1, num_samples=10, num_warmup=0)
df = res.to_frame()

print(df.head())

The program stops at the line res = posterior.sample, and I get an AssertionError. Stan warns me that Posterior is improper. Please check your model.

Similarly, if I try the stan code:

generated quantities {
  real<lower=-1, upper=1> x = uniform_rng(-1, 1);
  real<lower=-1, upper=1> y = uniform_rng(-1, 1);
  int<lower=0, upper=1> inside = x^2 + y^2 < 1;
  real<lower=0, upper=4> pi = 4 * inside;
}

I have the same problems.

  • Ubuntu 20.04
  • Python 3.9
  • PyStan 3.7

Can you try fixed_param

res = posterior.fixed_param(num_chains=1, num_samples=10)

Thank you, it runs! But is the method ‘fixed_param’ mentioned in the documentation?

Not sure, We should have API somewhere, but need to check is this the case