How to use the elfi.Distance 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 / functional / test_post_processing.py View on Github external
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)

    # Add some invalid values
    res.outputs['mu'] = np.append(res.outputs['mu'], np.array([np.inf]))
    res.outputs['ss_mean'] = np.append(res.outputs['ss_mean'], np.array([np.inf]))

    with pytest.warns(UserWarning):
        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_post_processing.py View on Github external
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_custom_outputs.py View on Github external
def test_dict_output():
    vsim = elfi.tools.vectorize(simulator)
    vsum = elfi.tools.vectorize(summary)

    obs = simulator([.2, .8])

    elfi.new_model()
    p = elfi.Prior('dirichlet', [2, 2])
    sim = elfi.Simulator(vsim, p, observed=obs)
    S = elfi.Summary(vsum, sim)
    d = elfi.Distance('euclidean', S)

    pool = elfi.OutputPool(['sim'])
    rej = elfi.Rejection(d, batch_size=100, pool=pool, output_names=['sim'])
    sample = rej.sample(100, n_sim=1000)
    mean = np.mean(sample.samples['p'], axis=0)

    # Crude test
    assert mean[1] > mean[0]
github elfi-dev / elfi / tests / functional / test_custom_outputs.py View on Github external
assert is_array(v)
    assert not isinstance(v[0], list)

    vsim = elfi.tools.vectorize(lsimulator, dtype=False)

    v = vsim(np.array([[.2, .8], [.3, .7]]))
    assert is_array(v)
    assert isinstance(v[0], list)

    obs = lsimulator([.2, .8])

    elfi.new_model()
    p = elfi.Prior('dirichlet', [2, 2])
    sim = elfi.Simulator(vsim, p, observed=obs)
    S = elfi.Summary(vsum, sim)
    d = elfi.Distance('euclidean', S)

    pool = elfi.OutputPool(['sim'])
    rej = elfi.Rejection(d, batch_size=100, pool=pool, output_names=['sim'])
    sample = rej.sample(100, n_sim=1000)
    mean = np.mean(sample.samples['p'], axis=0)

    # Crude test
    assert mean[1] > mean[0]
github elfi-dev / elfi / elfi / examples / bdm.py View on Github external
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)

    return m
github elfi-dev / elfi / elfi / examples / ma2.py View on Github external
-------
    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 / lorenz.py View on Github external
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'))

    sumstats.append(elfi.Summary(xcov, m['Lorenz'], True, name='CrosscovPrev'))

    sumstats.append(elfi.Summary(xcov, m['Lorenz'], False, name='CrosscovNext'))

    elfi.Distance('euclidean', *sumstats, name='d')

    return m
github elfi-dev / elfi / elfi / examples / lotka_volterra.py View on Github external
m = elfi.ElfiModel()
    sim_fn = partial(lotka_volterra, **kwargs)
    priors = []
    sumstats = []

    priors.append(elfi.Prior(ExpUniform, -2, 0, model=m, name='r1'))
    priors.append(elfi.Prior(ExpUniform, -5, -2.5, model=m, name='r2'))  # easily kills populations
    priors.append(elfi.Prior(ExpUniform, -2, 0, model=m, name='r3'))
    priors.append(elfi.Prior('poisson', 50, model=m, name='prey0'))
    priors.append(elfi.Prior('poisson', 100, model=m, name='predator0'))
    priors.append(elfi.Prior(ExpUniform, np.log(0.5), np.log(50), model=m, name='sigma'))

    elfi.Simulator(sim_fn, *priors, observed=y_obs, name='LV')
    sumstats.append(elfi.Summary(partial(pick_stock, species=0), m['LV'], name='prey'))
    sumstats.append(elfi.Summary(partial(pick_stock, species=1), m['LV'], name='predator'))
    elfi.Distance('sqeuclidean', *sumstats, name='d')

    logger.info("Generated %i observations with true parameters r1: %.1f, r2: %.3f, r3: %.1f, "
                "prey0: %i, predator0: %i, sigma: %.1f.", n_obs, *true_params)

    return m