How to use the elfi.ElfiModel function in elfi

To help you get started, we’ve selected a few elfi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github elfi-dev / elfi / tests / unit / test_utils.py View on Github external
def test_basics(self, ma2, distribution_test):
        # A 1D case
        normal = elfi.Prior('normal', 5, model=elfi.ElfiModel())
        normal_prior = ModelPrior(normal.model)
        distribution_test(normal_prior)

        # A 2D case
        prior = ModelPrior(ma2)
        distribution_test(prior)
github elfi-dev / elfi / tests / functional / test_post_processing.py View on Github external
mu, sigma = (5, 1)

    # Hyperparameters
    mu0, sigma0 = (10, 100)

    y_obs = gauss.gauss(
        mu, sigma, n_obs=n_obs, batch_size=1, random_state=np.random.RandomState(seed))
    sim_fn = partial(gauss.gauss, sigma=sigma, n_obs=n_obs)

    # Posterior
    n = y_obs.shape[1]
    mu1 = (mu0 / sigma0**2 + y_obs.sum() / sigma**2) / (1 / sigma0**2 + n / sigma**2)
    sigma1 = (1 / sigma0**2 + n / sigma**2)**(-0.5)

    # Model
    m = elfi.ElfiModel()
    elfi.Prior('norm', mu0, sigma0, model=m, name='mu')
    elfi.Simulator(sim_fn, m['mu'], observed=y_obs, name='gauss')
    elfi.Summary(lambda x: x.mean(axis=1), m['gauss'], name='ss_mean')
    elfi.Distance('euclidean', m['ss_mean'], name='d')

    res = elfi.Rejection(m['d'], output_names=['ss_mean'], batch_size=batch_size,
                         seed=seed).sample(1000, threshold=1)
    adj = elfi.adjust_posterior(model=m, sample=res, parameter_names=['mu'], summary_names=['ss_mean'])

    assert np.allclose(_statistics(adj.outputs['mu']), (4.9772879640569778, 0.02058680115402544))
github elfi-dev / elfi / tests / functional / test_compilation.py View on Github external
def test_batch_index_value(ma2):
    bi = lambda meta : meta['batch_index']

    # Test the correct batch_index value
    m = elfi.ElfiModel()
    op = elfi.Operation(bi, model=m, name='op')
    op['_uses_meta'] = True
    client = elfi.get_client()
    c = elfi.ComputationContext()
    compiled_net = client.compile(m.source_net, m.nodes)
    loaded_net = client.load_data(compiled_net, c, batch_index=3)
    res = client.compute(loaded_net)

    assert res['op'] == 3
github elfi-dev / elfi / tests / unit / test_utils.py View on Github external
def test_numerical_grad_logpdf(self):
        # Test gradient with a normal distribution
        loc = 2.2
        scale = 1.1
        x = np.random.rand()
        analytical_grad_logpdf = -(x - loc) / scale**2
        prior_node = elfi.Prior('normal', loc, scale, model=elfi.ElfiModel())
        num_grad = ModelPrior(prior_node.model).gradient_logpdf(x)
        assert np.isclose(num_grad, analytical_grad_logpdf, atol=0.01)
github elfi-dev / elfi / elfi / examples / ma2.py View on Github external
true_params : list
        parameters with which the observed data is generated
    seed_obs : None, int
        seed for the observed data generation

    Returns
    -------
    m : elfi.ElfiModel
    """
    if true_params is None:
        true_params = [.6, .2]

    y = MA2(*true_params, n_obs=n_obs, random_state=np.random.RandomState(seed_obs))
    sim_fn = partial(MA2, n_obs=n_obs)

    m = elfi.ElfiModel()
    elfi.Prior(CustomPrior1, 2, model=m, name='t1')
    elfi.Prior(CustomPrior2, m['t1'], 1, name='t2')
    elfi.Simulator(sim_fn, m['t1'], m['t2'], observed=y, name='MA2')
    elfi.Summary(autocov, m['MA2'], name='S1')
    elfi.Summary(autocov, m['MA2'], 2, name='S2')
    elfi.Distance('euclidean', m['S1'], m['S2'], name='d')
    return m
github elfi-dev / elfi / elfi / examples / bdm.py View on Github external
Lintusaari et al. 2016

    Returns
    -------
    m : elfi.ElfiModel
    """

    if seed_obs is None and N == 20:
        y = np.zeros(N, dtype='int16')
        data = np.array([6, 3, 2, 2, 1, 1, 1, 1, 1, 1, 1], dtype='int16')
        y[0:len(data)] = data

    else:
        y = BDM(alpha, delta, tau, N, random_state=np.random.RandomState(seed_obs))

    m = elfi.ElfiModel(name='bdm')
    elfi.Prior('uniform', .005, 2, model=m, name='alpha')
    elfi.Simulator(BDM, m['alpha'], delta, tau, N, observed=y, name='BDM')
    elfi.Summary(T1, m['BDM'], name='T1')
    elfi.Distance('minkowski', m['T1'], p=1, name='d')

    m['BDM'].uses_meta = True

    # Warn the user if the executable is not present
    if not os.path.isfile('bdm') and not os.path.isfile('bdm.exe'):
        cpp_path = get_sources_path()
        warnings.warn("This model uses an external simulator `bdm` implemented in C++ "
                      "that needs to be compiled and copied to your working directory. "
                      "We could not find it from your current working directory. Please"
                      "copy the folder `{}` to your working directory "
                      "and compile the source.".format(cpp_path), RuntimeWarning)
github elfi-dev / elfi / elfi / examples / ricker.py View on Github external
Returns
    -------
    m : elfi.ElfiModel
    """

    if stochastic:
        simulator = partial(stochastic_ricker, n_obs=n_obs)
        if true_params is None:
            true_params = [3.8, 0.3, 10.]

    else:
        simulator = partial(ricker, n_obs=n_obs)
        if true_params is None:
            true_params = [3.8]

    m = elfi.ElfiModel()
    y_obs = simulator(*true_params, n_obs=n_obs, random_state=np.random.RandomState(seed_obs))
    sim_fn = partial(simulator, n_obs=n_obs)
    sumstats = []

    if stochastic:
        elfi.Prior(ss.expon, np.e, 2, model=m, name='t1')
        elfi.Prior(ss.truncnorm, 0, 5, model=m, name='t2')
        elfi.Prior(ss.uniform, 0, 100, model=m, name='t3')
        elfi.Simulator(sim_fn, m['t1'], m['t2'], m['t3'], observed=y_obs, name='Ricker')
        sumstats.append(elfi.Summary(partial(np.mean, axis=1), m['Ricker'], name='Mean'))
        sumstats.append(elfi.Summary(partial(np.var, axis=1), m['Ricker'], name='Var'))
        sumstats.append(elfi.Summary(num_zeros, m['Ricker'], name='#0'))
        elfi.Discrepancy(chi_squared, *sumstats, name='d')

    else:  # very simple deterministic case
        elfi.Prior(ss.expon, np.e, model=m, name='t1')
github elfi-dev / elfi / elfi / examples / lorenz.py View on Github external
to force term and eventually impacts to the result of eta.
        More details in Wilks (2005) et al.
    total_duration : float, optional

    Returns
    -------
    m : elfi.ElfiModel

    """
    simulator = partial(forecast_lorenz, initial_state=initial_state, f=f, n_obs=n_obs, phi=phi,
                        total_duration=total_duration)

    if not true_params:
        true_params = [2.0, 0.1]

    m = elfi.ElfiModel()

    y_obs = simulator(*true_params, random_state=np.random.RandomState(seed_obs))
    sumstats = []

    elfi.Prior('uniform', 0.5, 3., model=m, name='theta1')
    elfi.Prior('uniform', 0, 0.3, model=m, name='theta2')
    elfi.Simulator(simulator, m['theta1'], m['theta2'], observed=y_obs, name='Lorenz')

    sumstats.append(elfi.Summary(mean, m['Lorenz'], name='Mean'))

    sumstats.append(elfi.Summary(var, m['Lorenz'], name='Var'))

    sumstats.append(elfi.Summary(autocov, m['Lorenz'], name='Autocov'))

    sumstats.append(elfi.Summary(cov, m['Lorenz'], name='Cov'))