How to use the pystan.StanModel function in pystan

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 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
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)
        self._long_names = names
        self._counter = Counter(self._index)
        self._dict = {self._names[i]: [] for i in range(len(self._names))}
github probcomp / Venturecxx / python / lib / plugins / venstan.py View on Github external
def cached_stan_model(model_code, cache_dir=None, **kwargs):
  if cache_dir is None:
    print "Not using Stan model cache"
    return pystan.StanModel(model_code=model_code, **kwargs)
  if not os.path.exists(cache_dir):
    os.makedirs(cache_dir)
  code_hash = hashlib.sha256(model_code).hexdigest()
  cache_file = 'compiled-stan-model-%s.pkl' % code_hash
  cache_path = os.path.join(cache_dir, cache_file)
  try:
    model = pickle.load(open(cache_path, 'rb'))
    print "Loaded model from cache %s" % cache_file
  except:
    model = pystan.StanModel(model_code=model_code, **kwargs)
    with open(cache_path, 'wb') as f:
      pickle.dump(model, f)
      print "Saved model to cache %s" % cache_file
  return model