I am fitting some data points to models in a bayesian framework (mcmc-like) in python. I am using a C library to predict the models. For some set of parameters, the C library fails to compute the models becuase it predicts some unphysical parameters (to make an unrelated example, it's as if it predicts masses<0). The C code contains an 'exit()' when this happens. Therefore, the sampling of the parameter space stops. I want to ignore the particular combination of parameters where the prediction of the model fails and keep the sampling going. I tried using 'try'-'except', but this does not work because the external C code still fails and the python code stops before moving to the 'expcept'. I can not modify the C library. Is there any way of catching the error from the C code without stopping the parameter sampling in python?
Here is a similar piece of code:
def my_likelihood(params):
try:
model = model_from_c_library(x_data, params)
diff = model - y_data
like = -0.5 * ((diff / err) ** 2).sum()
if (np.isnan(like) | np.isinf(like) | np.isnan(model).any()):
like = -1e30
except:
like = -1e30
return like
In my case, 'model_from_c_library' returns an error and the python code stops, because in model_from_c_library.c there is something similar to this:
double mass(pars):
m = predict_mass(pars);
if m < 0:
exit(101);
I want to make this an exception in Python.