flav-io / flavio

A Python package for flavour physics phenomenology in the Standard model and beyond
http://flav-io.github.io/
MIT License
71 stars 61 forks source link

Re-using saved FastLikelihood objects #226

Closed bednya closed 1 year ago

bednya commented 1 year ago

Hi,

I wanted to re-use FaslLikelihood object after a make_measurement call. Dumping it as a YAML string or stream seems to abandon the pseudomeasurement data, so I used the pickle module.

The problem is that after unpickling previously saved FastLikelihood object, the pseudomeasurement does not appear in the list of instances of the Measurement class. As a consequence, functions like likelihood.log_likelihood failed to return correct values.

For example, saving FastLikelihood via

import flavio
import pickle
import flavio.statistics.likelihood

obs_list = [
    'BR(Bs->mumu)',
    'BR(B0->mumu)',
    ];

test_lh = flavio.statistics.likelihood.FastLikelihood('test',flavio.default_parameters,
    observables=obs_list
    )
test_lh.make_measurement(N=100)

with open("test.pkl", 'wb') as file:
    pickle.dump(test_lh, file)

print(test_lh.likelihood.log_likelihood(flavio.default_parameters.get_central_all(),flavio.WilsonCoefficients()))

and loading the object (after a kernel restart) via

import flavio
import pickle
with open("test.pkl", 'rb') as file:
    test_lh = pickle.load(file)

produces 0.0 as an output of

print(test_lh.likelihood.log_likelihood(flavio.default_parameters.get_central_all(),flavio.WilsonCoefficients()))

Probably, there is a better solution to the problem, but for the time being I wrote a small workaround 20a30b8 that manually adds the loaded pseudomeasurement to the instance list.

DavidMStraub commented 1 year ago

I would say the way FastLikelihood is implemented, it is very poorly suited for pickling. For users looking for a more convenient way to work with pre-computed and reusable FastLikelihood instances, I would advise them to use a custom smelli.GlobalLikelihood, which has dedicated methods to save and load pickled covariance matrices.

bednya commented 1 year ago

Hi, thanks for the hint!