示例#1
0
def test_uniform_acceptor():
    """Test the uniform acceptor."""
    def dist(x, x_0):
        return sum(abs(x[key] - x_0[key]) for key in x_0)

    distance = pyabc.SimpleFunctionDistance(dist)
    acceptor = pyabc.UniformAcceptor()
    eps = pyabc.ListEpsilon([1, 4, 2])

    x = {'s0': 1.5}
    x_0 = {'s0': 0}

    ret = acceptor(distance_function=distance,
                   eps=eps,
                   x=x,
                   x_0=x_0,
                   t=2,
                   par=None)

    assert ret.accept

    # now let's test again, including previous time points

    acceptor = pyabc.UniformAcceptor(use_complete_history=True)

    ret = acceptor(distance_function=distance,
                   eps=eps,
                   x=x,
                   x_0=x_0,
                   t=2,
                   par=None)

    assert not ret.accept
               os.path.join(database_dir, "test_pyabc_" + dbid + ".db"))
    # make a file to hold onto these NSEs for our own record
    with open(os.path.join(temp_path, "NSEs_" + dbid + ".txt"),
              "w") as nse_file:
        nse_file.write("NSEs\n")
    # define NSE Distance function: Calculate NSE with hydroeval library and the subtract 1 from it to get NSED
    def nse(x, x_0):
        nse = he.evaluator(he.nse,
                           simulation_s=np.array(list(x.values())),
                           evaluation=np.array(list(x_0.values())))[0]
        print("nse ", nse)
        # make record
        with open(os.path.join(temp_path, "NSEs_" + dbid + ".txt"),
                  "a") as nse_file:
            nse_file.write(str(nse) + "\n")
        return nse

    # NSEs live on [-infinity, 1] and the best NSE is 1
    # Distances live on [0, infinity and the best distance is 0
    # Therefore, let's make a formula that's informed by NSE, but has range and properties of a distance function
    NSED = pyabc.SimpleFunctionDistance(fun=lambda x, x_0: 1 - nse(x, x_0))
    # make the pyabc Seq Monte Carlo object
    abc = pyabc.ABCSMC(model,
                       prior,
                       population_size=pyabc.ConstantPopulationSize(npop),
                       sampler=sampler,
                       distance_function=NSED)
    # initialize a new run
    abc.new(db_path, obs_dict)
    # run it!
    history = abc.run(max_nr_populations=ngen, minimum_epsilon=0.2)