Esempio n. 1
0
def setup_model(*, cmdstan_dir, model_dir, name, model, data):
    """Compile Stan model."""
    cmdstanpy.set_cmdstan_path(cmdstan_dir)

    model = model.replace("<-", "=")

    with tempfile.NamedTemporaryFile("w",
                                     prefix=f"{name}_",
                                     suffix=".stan",
                                     dir=model_dir,
                                     delete=False) as f:
        print(model, file=f)
        model_file = f.name

    with tempfile.NamedTemporaryFile("w",
                                     prefix=f"{name}_",
                                     suffix=".json",
                                     dir=model_dir,
                                     delete=False) as f:
        json.dump(data, f, indent=2, sort_keys=True)
        data_file = f.name

    model_object = cmdstanpy.CmdStanModel(stan_file=model_file)
    exe_file = model_object.exe_file
    return model_file, data_file, exe_file
Esempio n. 2
0
def build_cmdstan_model(target_dir):
    """
    Rebuild cmdstan in the build environment, then use this installation to compile the stan model.
    The stan model is copied to {target_dir}/prophet_model.bin
    The cmdstan files required to run cmdstanpy commands are copied to {target_dir}/cmdstan-{version}.

    Parameters
    ----------
    target_dir: Directory to copy the compiled model executable and core cmdstan files to.
    """
    import cmdstanpy

    cmdstan_cache = get_cmdstan_cache()
    download_cmdstan(cmdstan_cache)

    cmdstan_dir = os.path.join(target_dir, f"cmdstan-{CMDSTAN_VERSION}")
    if os.path.isdir(cmdstan_dir):
        rmtree(cmdstan_dir)
    copytree(cmdstan_cache, cmdstan_dir)
    with cmdstanpy.utils.pushd(cmdstan_dir):
        clean_all_cmdstan()
        build_cmdstan()
    cmdstanpy.set_cmdstan_path(cmdstan_dir)

    model_name = "prophet.stan"
    target_name = "prophet_model.bin"
    sm = cmdstanpy.CmdStanModel(stan_file=os.path.join(MODEL_DIR, model_name))
    copy(sm.exe_file, os.path.join(target_dir, target_name))
    # Clean up
    for f in Path(MODEL_DIR).iterdir():
        if f.is_file() and f.name != model_name:
            os.remove(f)
    prune_cmdstan(cmdstan_dir)
Esempio n. 3
0
def init():
    "Initialize CmdStan and CmdStanPy"
    readme = stan_dir / 'README.md'
    if not readme.exists():
        _log.error('CmdStan not found, is it checked out?')
        _log.info('Try running: git submodule update --init --recursive')
        raise RuntimeError('CmdStan not available')

    _log.info('initializing local settings')
    _local_make.write_text(stan_config)

    stanc = stan_dir / 'bin' / 'stanc'
    make = 'make'
    if platform.system() == 'Windows':
        stanc = stanc.with_suffix('.exe')
        make = 'mingw32-make'  # STAN is picky

    _log.info('making sure CmdStan is compiled')
    sp.run([make, '-j4', 'build'], cwd=stan_dir, check=True)

    res = sp.run([os.fspath(stanc), '--version'],
                 capture_output=True,
                 check=True)
    _log.info('built Stan version %s', res.stdout.decode('utf8').strip())
    cmdstanpy.set_cmdstan_path(os.fspath(stan_dir))
Esempio n. 4
0
def install_cmdstan_deps(cmdstan_dir: Path):
    import cmdstanpy

    cmdstan_cache = get_cmdstan_cache()
    download_cmdstan(cmdstan_cache)
    if cmdstan_dir.is_dir():
        rmtree(cmdstan_dir)
    copytree(cmdstan_cache, cmdstan_dir)

    if PLATFORM == "win":
        try:
            cmdstanpy.utils.cxx_toolchain_path()
        except Exception:
            install_cmdstan_toolchain()

    with cmdstanpy.utils.pushd(cmdstan_dir):
        clean_all_cmdstan()
        build_cmdstan()
    cmdstanpy.set_cmdstan_path(str(cmdstan_dir))
Esempio n. 5
0
    subprocess.run(["conda", "list"])
    subprocess.run(["conda", "info"])

else:
    print("pip environment:")
    subprocess.run([sys.executable, "-m", "pip", "list"])

# hacky for RTD - which doesn't actually call conda activate
# see: https://github.com/readthedocs/readthedocs.org/issues/5339
if os.environ.get('READTHEDOCS', False):
    import cmdstanpy

    version = 'v' + cmdstanpy.__version__

    cmdstanpy.set_cmdstan_path(
        '/home/docs/checkouts/readthedocs.org/user_builds/cmdstanpy/'
        'conda/' + version + '/bin/cmdstan')

    os.environ['CXX'] = (
        '/home/docs/checkouts/readthedocs.org/user_builds/cmdstanpy/'
        'conda/' + version + '/bin/x86_64-conda-linux-gnu-c++')

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.dirname(os.path.abspath('.')))

# this sets up logging to print all logging messages
# the ipython directive doesn't show logging, so this is a hack
import logging
from logging import StreamHandler
Esempio n. 6
0
 def __init__(self):
     super().__init__()
     import cmdstanpy
     cmdstanpy.set_cmdstan_path(
         pkg_resources.resource_filename(
             "prophet", f"stan_model/cmdstan-{self.CMDSTAN_VERSION}"))