def test_args_sig_figs(self):
     sampler_args = SamplerArgs()
     cmdstan_path()  # sets os.environ['CMDSTAN']
     if cmdstan_version_before(2, 25):
         with LogCapture() as log:
             logging.getLogger()
             CmdStanArgs(
                 model_name='bernoulli',
                 model_exe='bernoulli.exe',
                 chain_ids=[1, 2, 3, 4],
                 sig_figs=12,
                 method_args=sampler_args,
             )
         expect = (
             'Argument "sig_figs" invalid for CmdStan versions < 2.25, '
             'using version {} in directory {}').format(
                 os.path.basename(cmdstan_path()),
                 os.path.dirname(cmdstan_path()),
             )
         log.check_present(('cmdstanpy', 'WARNING', expect))
     else:
         cmdstan_args = CmdStanArgs(
             model_name='bernoulli',
             model_exe='bernoulli.exe',
             chain_ids=[1, 2, 3, 4],
             sig_figs=12,
             method_args=sampler_args,
         )
         cmd = cmdstan_args.compose_command(idx=0,
                                            csv_file='bern-output-1.csv')
         self.assertIn('sig_figs=', ' '.join(cmd))
         with self.assertRaises(ValueError):
             CmdStanArgs(
                 model_name='bernoulli',
                 model_exe='bernoulli.exe',
                 chain_ids=[1, 2, 3, 4],
                 sig_figs=-1,
                 method_args=sampler_args,
             )
         with self.assertRaises(ValueError):
             CmdStanArgs(
                 model_name='bernoulli',
                 model_exe='bernoulli.exe',
                 chain_ids=[1, 2, 3, 4],
                 sig_figs=20,
                 method_args=sampler_args,
             )
Beispiel #2
0
def clean_examples():
    cmdstan_examples = os.path.join(cmdstan_path(), "examples")
    for root, _, files in os.walk(cmdstan_examples):
        for filename in files:
            _, ext = os.path.splitext(filename)
            if ext.lower() in (".o", ".hpp", ".exe",
                               "") and (filename != ".gitignore"):
                filepath = os.path.join(root, filename)
                os.remove(filepath)
                print("Deleted {}".format(filepath))
Beispiel #3
0
def run_bernoulli_fit():
    # specify Stan file, create, compile CmdStanModel object
    bernoulli_path = os.path.join(cmdstan_path(), 'examples', 'bernoulli',
                                  'bernoulli.stan')
    bernoulli_model = CmdStanModel(stan_file=bernoulli_path)
    bernoulli_model.compile()

    # specify data, fit the model
    bernoulli_data = {'N': 10, 'y': [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]}
    # Show progress
    bernoulli_fit = bernoulli_model.sample(chains=4,
                                           cores=2,
                                           data=bernoulli_data,
                                           show_progress=True)

    # summarize the results (wraps CmdStan `bin/stansummary`):
    print(bernoulli_fit.summary())
Beispiel #4
0
#%%
import os
from cmdstanpy import cmdstan_path, CmdStanModel

bernoulli_stan = os.path.join(cmdstan_path(), 'examples', 'bernoulli',
                              'bernoulli.stan')
bernoulli_model = CmdStanModel(stan_file=bernoulli_stan)
bernoulli_model.name
bernoulli_model.stan_file
bernoulli_model.exe_file
print(bernoulli_model.code())

bernoulli_data = os.path.join(cmdstan_path(), 'examples', 'bernoulli',
                              'bernoulli.data.json')
bern_fit = bernoulli_model.sample(data=bernoulli_data,
                                  output_dir='./model_output')

print(bern_fit)

print(bern_fit.sample.shape)

print(bern_fit.summary())

print(bern_fit.diagnose())
Beispiel #5
0
#!/usr/bin/env python
# Python code from Jupyter notebook `cmdstanpy_tutorial.ipynb`

# ### Import CmdStanPy classes and methods

import os.path
import sys

from cmdstanpy import CmdStanModel, cmdstan_path

# ### Instantiate & compile the model

bernoulli_dir = os.path.join(cmdstan_path(), 'examples', 'bernoulli')
stan_file = os.path.join(bernoulli_dir, 'bernoulli.stan')
with open(stan_file, 'r') as f:
    print(f.read())

model = CmdStanModel(stan_file=stan_file)
print(model)

# ### Assemble the data

data = {"N": 10, "y": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]}

# In the CmdStan `examples/bernoulli` directory, there are data files in both `JSON` and `rdump` formats.
# bern_json = os.path.join(bernoulli_dir, 'bernoulli.data.json')

# ### Do Inference

fit = model.sample(data=data)
print(fit)
Beispiel #6
0
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from typing import Dict
import arviz as az

model_dir = Path("stan_code")
data_dir = Path("data")

# ---- data ---- #
bernoulli_data: Dict = {"N": 10, "y": [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]}
data = pd.DataFrame({"y": bernoulli_data["y"]},
                    index=np.arange(bernoulli_data["N"]))

# ---- model ---- #
bernoulli_stan = Path(cmdstan_path()) / "examples/bernoulli/bernoulli.stan"
bernoulli_model = CmdStanModel(stan_file=bernoulli_stan)
bernoulli_model.compile()

# ---- fitting ---- #
bern_fit: CmdStanMCMC = bernoulli_model.sample(
    data=bernoulli_data,
    chains=4,
    cores=1,
    seed=1111,
    show_progress=True,
)

# ---- results ---- #
"""samples = multi-dimensional array
    all draws from all chains arranged as dimensions:
from pathlib import Path
import cmdstanpy
from cmdstanpy import cmdstan_path, CmdStanModel, CmdStanMCMC
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from typing import Dict
import arviz as az
import os

cmdstanpy.CMDSTAN_PATH = "/Users/tommylees/.cmdstanpy/cmdstan-2.21.0"
print(cmdstan_path())

def clear_pre_existing_files():
    os.system(
        """
        pchs=`find . -name "*.gch"`;
        for f in $pchs; do rm $f; done;
        """
    )
    os.system(
        """
        hpps=`find . -name "*.hpp"`;
        for f in $hpps; do rm $f; done;
        """
    )
    print("Deleted *.hpp and *.gch files")


if __name__ == "__main__":
    clear_pre_existing_files()