How to use pystan - 10 common examples

To help you get started, we’ve selected a few pystan examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github IBM / yaps / tests / stan / test_stan2yaps.py View on Github external
def run_test(dir):
    pathlist = Path(dir).glob('*.stan')
    nb_test = 0
    nb_success = 0
    nb_bad = 0
    for p in pathlist:
        path = str(p)
        with open(path, 'r') as fin:
            code = fin.read()
            try:
                pystan.stanc(model_code=code)
                nb_test += 1
                try:
                    source = yaps.from_stan(code_file=path)
                    ast_ = yaps.from_string(source)
                    stan = yaps.to_stan(ast_)
                    pystan.stanc(model_code=stan)
                    nb_success += 1
                except (AttributeError, SyntaxError, TypeError, AssertionError, ValueError) as err:
                    print("FAILED\t", path, err)
                except RuntimeError:
                    nb_success += 1
            except (ValueError, RuntimeError):
                nb_bad += 1

    print("-------------------------")
    print("{}% of success ({}/{} valid Stan examples, {} bad examples ignored)".format(
github IBM / yaps / tests / stan / test_stan2yaps.py View on Github external
pathlist = Path(dir).glob('*.stan')
    nb_test = 0
    nb_success = 0
    nb_bad = 0
    for p in pathlist:
        path = str(p)
        with open(path, 'r') as fin:
            code = fin.read()
            try:
                pystan.stanc(model_code=code)
                nb_test += 1
                try:
                    source = yaps.from_stan(code_file=path)
                    ast_ = yaps.from_string(source)
                    stan = yaps.to_stan(ast_)
                    pystan.stanc(model_code=stan)
                    nb_success += 1
                except (AttributeError, SyntaxError, TypeError, AssertionError, ValueError) as err:
                    print("FAILED\t", path, err)
                except RuntimeError:
                    nb_success += 1
            except (ValueError, RuntimeError):
                nb_bad += 1

    print("-------------------------")
    print("{}% of success ({}/{} valid Stan examples, {} bad examples ignored)".format(
        round(nb_success/nb_test * 100, 2), nb_success, nb_test, nb_bad))
github IBM / yaps / tests / stan / test_stan2yaps.py View on Github external
def roundtrip(path):
    with open(path, 'r') as fin:
        code = fin.read()
        print(code)
        pystan.stanc(model_code=code)
    print('--------------------------------')
    source = yaps.from_stan(code_file=path)
    print(source)
    print('--------------------------------')
    ast_ = yaps.from_string(source)
    code = yaps.to_stan(ast_)
    print(code)
    print('--------------------------------')
    pystan.stanc(model_code=code)
github BayesianFreaks / scikit-stan / skstan / regression / base.py View on Github external
def fit(self, x: np.array, y: np.array):
        return ps.stan(
            model_code=self.model_code,
            data=self.preprocess(
                RegressionStanData(x, y, self.shrinkage)
            ),
            **self.kwargs
        )
github pyro-ppl / numpyro / benchmarks / hmm.py View on Github external
real acc[K];
            real gamma[T_unsup,K];
            for (k in 1:K)
              gamma[1,k] = log(phi[k,u[1]]);
            for (t in 2:T_unsup) {
              for (k in 1:K) {
                for (j in 1:K)
                  acc[j] = gamma[t-1,j] + log(theta[j,k]) + log(phi[k,u[t]]);
                gamma[t,k] = log_sum_exp(acc);
              }
            }
            target += log_sum_exp(gamma[T_unsup]);
          }
        }
    """
    return pystan.StanModel(model_code=model_code)
github zalando / expan / expan / core / early_stopping.py View on Github external
:rtype:  Class representing a compiled Stan model
    """

    logger.info("Started loading and compiling Stan model for {} distribution".format(distribution))

    if distribution is not 'normal' and distribution is not 'poisson':
        raise ValueError("Model " + distribution + " is not implemented.")

    python_version = '{0[0]}.{0[1]}'.format(sys.version_info)
    compiled_model_file = tempfile.gettempdir() + '/expan_early_stop_compiled_stan_model_' \
                                                + distribution + '_' + python_version + '.pkl'

    if os.path.isfile(compiled_model_file):
        sm = pickle.load(open(compiled_model_file, 'rb'))
    else:
        sm = StanModel(file=model_file)
        with open(compiled_model_file, 'wb') as f:
            pickle.dump(sm, f)
    return sm
github facebook / prophet / python / setup.py View on Github external
def build_stan_model(target_dir, model_dir=MODEL_DIR):
    from pystan import StanModel
    model_name = 'prophet.stan'
    target_name = 'prophet_model.pkl'
    with open(os.path.join(model_dir, model_name)) as f:
        model_code = f.read()
    sm = StanModel(model_code=model_code)
    with open(os.path.join(target_dir, target_name), 'wb') as f:
        pickle.dump(sm, f, protocol=pickle.HIGHEST_PROTOCOL)
github pints-team / pints / pints / interfaces / _stan.py View on Github external
def __init__(self, stan_code, stan_data, pickle_filename=None):

        if pickle_filename:
            if os.path.isfile(pickle_filename):
                sm = pickle.load(open(pickle_filename, 'rb'))
            else:
                sm = pystan.StanModel(model_code=stan_code)
                pickle.dump(sm, open(pickle_filename, 'wb'))
        else:
            sm = pystan.StanModel(model_code=stan_code)

        stanfit = sm.sampling(data=stan_data, iter=1, chains=1,
                              verbose=False, refresh=10,
                              control={'adapt_engaged': False})
        print("Stan model compiled and runs ok...ignore various warnings.")
        self._compiled_stan = sm
        self._fit = stanfit
        self._log_prob = stanfit.log_prob
        self._grad_log_prob = stanfit.grad_log_prob
        self._u_to_c = stanfit.unconstrain_pars
        names = stanfit.unconstrained_param_names()
        self._n_parameters = len(names)
        self._names, self._index = self._initialise_dict_index(names)
github dtrckd / pymake / repo / ml / model / mmsb_stan.py View on Github external
def load_stan_model( model_name ):
        """
        Load stan model from disk,
        if not exist, compile the model from source code
        """
        try:
            stan_model = pickle.load( open(model_name + ".model", 'rb') )
        except IOError:
            stan_model = pystan.StanModel( file = model_name + ".stan" )
            with open(model_name + ".model", 'wb') as fout:
                pickle.dump(stan_model, fout)
            pass

        return stan_model
github blei-lab / edward / edward / models / models.py View on Github external
Parameters
        ----------
        model : pystan.StanModel, optional
            An already compiled Stan model. This is useful to avoid
            recompilation of Stan models both within a session (using
            this argument) and across sessions (by loading a pickled
            pystan.StanModel object and passing it in here).
            Alternatively, one can also pickle the ed.StanModel object
            altogether.
        *args
            Passed into pystan.StanModel.
        **kwargs
            Passed into pystan.StanModel.
        """
        if model is None:
            self.model = pystan.StanModel(*args, **kwargs)
        else:
            self.model = model

        self.modelfit = None
        self.is_initialized = False
        self.n_vars = None