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

`KeyError: 'message'` occurs when trying to build a model with wrong datatype #379

Open nigimitama opened 1 year ago

nigimitama commented 1 year ago

Describe the bug

When the data has wrong datatype (e.g. values of dataset are str type), pystan raises KeyError: 'message'.

The full Traceback is:

Traceback (most recent call last):
  File "/workdir/main.py", line 25, in <module>
    posterior = stan.build(model, data=data)
  File "/usr/local/lib/python3.9/site-packages/stan/model.py", line 519, in build
    return asyncio.run(go())
  File "/usr/local/lib/python3.9/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
    return future.result()
  File "/usr/local/lib/python3.9/site-packages/stan/model.py", line 511, in go
    raise RuntimeError(resp.json()["message"])
KeyError: 'message'

This is possibly a problem of the httpstan. But I think this pystan's behavior isn't intended. So I'm reporting here.

Describe your system

Steps/Code to Reproduce

My code sample consists of two files. To run them, please place them at the same directory.

├── Dockerfile
└── main.py
# Dockerfile
FROM python:3.9
COPY main.py .
RUN pip3 install httpstan==4.9.1 pystan==3.6.0
CMD ["python3", "main.py"]
# main.py
import stan

model = """
data {
  int<lower=0> N;
  vector[N] x;
  vector[N] y;
}
parameters {
  real alpha;
  real beta;
  real<lower=0> sigma;
}
model {
  y ~ normal(alpha + beta * x, sigma);
}
"""

# data has str values
data = {
    'y': ['58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72'],
    'x': ['115', '117', '120', '123', '126', '129', '132', '135', '139', '142', '146', '150', '154', '159', '164'],
    'N': 15
}
posterior = stan.build(model, data=data)
riddell-stan commented 1 year ago

Good catch. This does look like a bug.