Skip to content

Instantly share code, notes, and snippets.

@chrisranderson
Created April 7, 2016 02:43
Show Gist options
  • Select an option

  • Save chrisranderson/98d429ab603f4e5742cd42c57a9cbf4b to your computer and use it in GitHub Desktop.

Select an option

Save chrisranderson/98d429ab603f4e5742cd42c57a9cbf4b to your computer and use it in GitHub Desktop.
Caches your Stan model, and recompiles if it has changed since the cache was created.
import pystan
import pickle
import os.path, time
def compile_model():
with open('model.stan', 'r') as my_file:
model_code = my_file.read()
stan_model = pystan.StanModel(model_code=model_code)
print('Compilation finished, writing to pickle.')
with open('model.pkl', 'wb') as f:
pickle.dump(stan_model, f)
return stan_model
def get_model():
try:
model_edited = os.path.getmtime('model.stan')
pickle_edited = os.path.getmtime('model.pkl')
if model_edited > pickle_edited:
print('Model has been changed, recompiling.')
return compile_model()
print('Trying pre-compiled model.')
return pickle.load(open('model.pkl', 'rb'))
except FileNotFoundError as exception:
print('Pre-compiled model not found. Compiling model.')
return compile_model()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment