probcomp / cgpm

Library of composable generative population models which serve as the modeling and inference backend of BayesDB.
Apache License 2.0
25 stars 11 forks source link

Create decorator for simulate with N #234

Closed fsaad closed 6 years ago

fsaad commented 6 years ago

For CGPMs which cannot generate N independent samples in a particularly special way other than calling simulate N times, a common pattern in the simulate with N not None is to call itself N times.

Example: https://github.com/probcomp/cgpm/blob/9237e19a7d4523a1984f4380f77d55ba7ac4cbdf/src/primitives/normal.py#L84-L86

This code should wrapped in decorator.

fsaad commented 6 years ago

The following decorator will suffice for pure functions, should test it against methods.

def simulate_many(simulate):
    def simulate_wrapper(*args, **kwargs):
        N = kwargs.get('N', None)
        if N is None:
            return simulate(*args, **kwargs)
        return [simulate(*args, **kwargs) for _i in xrange(N)]
    return simulate_wrapper
fsaad commented 6 years ago

Another question worth asking is, if this pattern is indeed the common case, whether simulate requires an N parameter in the first place. My sense is yes, since some CGPMs will be able to meaningfully optimize sampling N iid in a single simulate call.

fsaad commented 6 years ago

This decorator will not work for positional arguments. Should instead check if the length of args is equal to the number of supported parameters from CGPM simulate and retrieving the last one.