Created
April 7, 2016 02:43
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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