示例#1
0
 def setUp(self) -> None:
     ngen = 25
     popsize = 4
     self.sres = SRES(
         cost_fun, popsize=popsize, numGenerations=ngen,
         startingValues=[8.324, 7.335],
         lb=[0.1, 0.1],
         ub=[10, 10],
         childrate=7
     )
     self.sres.setSeed(4)
示例#2
0
def do_estimation(ngen: int = 50, popsize: int = 50, starting_set=None):
    sres = SRES(
        cost_function=cost_fun_mean_squared,
        popsize=popsize,
        numGenerations=ngen,
        startingValues=starting_set if starting_set is not None else
        np.random.normal(5, 0.1, len(r.freeParameters())),
        lb=[0.01] * len(r.freeParameters()),
        ub=[10] * len(r.freeParameters()),
        childrate=7,
    )

    return sres.fit()
示例#3
0
    def test_sres(self):

        sres = SRES(dim=2)

        @sres.COST_FUNCTION_CALLBACK
        def cost_fun(x, f, g):
            sim = generateData(x.contents[0], x.contents[1])
            cost = 0
            for i in range(10):
                cost += (EXP_DATA[i] - sim[i])**2
            f.contents.value = cost

        sres.cost_function = cost_fun
示例#4
0
def do_estimation(ngen: int = 50, popsize: int = 50) -> Tuple[
    List[float], np.ndarray, np.ndarray, List[str], Dict[str, float], float]:
    sres = SRES(
        cost_function=cost_fun,
        popsize=popsize,
        numGenerations=ngen,
        startingValues=[8.3434, 6.342, 3.765],
        lb=[0.001] * len(r.freeParameters()),
        ub=[100] * len(r.freeParameters()),
        childrate=7,
    )

    results = sres.fit()
    best = dict(
        zip(r.freeParameters(), results["best_solution"])
    )
    objective_val = results["best_cost"]
    trace = results["trace"]

    x_sim, y_sim, sel = get_data(**best)
    return trace, x_sim, y_sim, sel, best, objective_val
示例#5
0
    # using this https://stackoverflow.com/a/1556482/3059024
    # how to implement *f = cost?
    # and this: https://stackoverflow.com/a/61543646/3059024
    print("sadfasd")
    f = cost

"""
This callback thing isn't working. Relook atht docs. If no, is there a way I 
can wrap the generation of this function in another function? 
"""


if __name__ == "__main__":
    from sres_capi import *

    sres = SRES()
    esparam = sres._makeESParameter()
    stats = sres._makeESStatistics()
    pop = sres._makeESPopulation()
    # costFun = sres.getCostFunPtr()
    trsf = sres._getTransformFun(2)

    # https://stackoverflow.com/questions/51131433/how-to-pass-lists-into-a-ctypes-function-on-python/51132594
    DoubleArrayLen2 = ct.c_double * 2

    pop_size = 30
    seed = 0
    gamma = 0.85
    alpha = 0.2
    varalphi = 1
    retry = 10
示例#6
0
    """
    optimum at (3.0, 0.5) = 0
    :param position:
    :return:
    """
    x, y = position
    return (1.5 - x + x * y)**2 + (2.25 - x + x * y**2)**2 + (2.625 - x +
                                                              x * y**3)**2


def cost_fun(parameters):
    return beale([parameters.contents[0], parameters.contents[1]])


if __name__ == "__main__":
    ngen = 25
    popsize = 4
    seed = 0

    cb = SRES.callback(2)(cost_fun)

    sres = SRES(cb,
                popsize=popsize,
                numGenerations=ngen,
                startingValues=[8.324, 7.335],
                lb=[0.1, 0.1],
                ub=[10, 10],
                childrate=7)

    print(sres.fit())
示例#7
0
 def setUp(self) -> None:
     self.sres = SRES(ngen=100, lb=[0.01] * 2, ub=[10] * 2, seed=1234)
示例#8
0
class Test(unittest.TestCase):
    def setUp(self) -> None:
        self.sres = SRES(ngen=100, lb=[0.01] * 2, ub=[10] * 2, seed=1234)

    def test_makeESParameter(self):
        cptr = self.sres._makeESParameter()
        self.assertIsNotNone(cptr)
        # free the pointer
        self.sres._freeESParameter(cptr)

    def test_makeESStatistics(self):
        cptr = self.sres._makeESStatistics()
        self.assertIsNotNone(cptr)
        self.sres._freeESStatistics(cptr)

    def test_makeESPopulation(self):
        cptr = self.sres._makeESPopulation()
        self.assertIsNotNone(cptr)
        self.sres._freeESPopulation(cptr)

    def test_makeCostFunPtr(self):
        cptr = self.sres.getCostFunPtr()
        self.assertIsNotNone(cptr)
        self.sres.freeCostFunPtr(cptr)

    def test_how_to_make_array_using_ctypes(self):
        DoubleArrayLen2 = ct.c_double * 2
        print(DoubleArrayLen2)
        arr = DoubleArrayLen2(*[0.1, 0.1])
        print(arr)

    def test_ESInitialWithPtrFitnessFcn(self):
        esparam = self.sres._makeESParameter()
        stats = self.sres._makeESStatistics()
        pop = self.sres._makeESPopulation()
        costFun = self.sres.getCostFunPtr()
        trsf = self.sres._getTransformFun()

        # https://stackoverflow.com/questions/51131433/how-to-pass-lists-into-a-ctypes-function-on-python/51132594
        DoubleArrayLen2 = ct.c_double * 2

        seed = 0
        gamma = 0.85
        alpha = 0.2
        varalphi = 1
        retry = 10
        es = 0
        miu = 30
        lamb = 200
        gen = 1750

        ptr = self.sres.ESInitialWithPtrFitnessFcn(
            seed,  # unsigned int seed,
            esparam,  # ESParameter **param,
            trsf,  # ESfcnTrsfm *trsfm,
            costFun,  # ESfcnFG* fg,
            es,  # int es,
            0,  # int constraint,
            2,  # int dim,
            DoubleArrayLen2(10.0, 10.0),  # double *ub,
            DoubleArrayLen2(0.1, 0.1),  # double *lb,
            miu,  # int miu,
            lamb,  # int lambda,
            gen,  # int gen,
            gamma,  # double gamma,
            alpha,  # double alpha,
            varalphi,  # double varphi,
            retry,  # int retry,
            stats,  # ESPopulation **population
            pop,  # ESStatistics **stats
        )

        self.sres._freeESParameter(esparam)
        self.sres._freeESStatistics(stats)
        self.sres._freeESPopulation(pop)
        self.sres.freeCostFunPtr(costFun)
        self.sres.freeTransformFun(trsf)

    def test(self):
        MODEL = """
        model newModel
            r1: A => B; k1*A;
            r2: B => A; k2*B;
            A = 10;
            B = 0.1;
            k1 = 0.1;
            k2 = 0.1;
        end
        """
        import tellurium as te
        model = te.loada(MODEL)
        print(model.getGlobalParameterIds())
示例#9
0
class SRESTests(unittest.TestCase):

    def setUp(self) -> None:
        ngen = 25
        popsize = 4
        self.sres = SRES(
            cost_fun, popsize=popsize, numGenerations=ngen,
            startingValues=[8.324, 7.335],
            lb=[0.1, 0.1],
            ub=[10, 10],
            childrate=7
        )
        self.sres.setSeed(4)

    def tearDown(self) -> None:
        pass

    def test_best_value(self):
        """TEST_F(CCSRESTests, TestGetBestValue) {
            SRES *sres = SRES_newSRES(cost, 10, 50, s, l, u, 2, 7);
            SRES_setSeed(sres, 4);
            SRES_fit(sres);
            double best;
            SRES_getBestFitnessValue(sres, &best);
            double x = 8.0722599999999995e-11;
            ASSERT_NEAR(x, best, 0.001);
            SRES_deleteSRES(sres);
        }"""
        results = self.sres.fit()
        self.assertAlmostEqual(1.0056368571769424e-07, results["bestFitness"], places=5)

    def testSizeOfHOF(self):
        self.sres.fit()
        self.assertEqual(18, self.sres._getSizeOfHallOfFame(self.sres._obj))

    def test_hof(self):
        self.sres.fit()
        hof = self.sres.getHallOfFame()
        alwaysDecreasing = True
        for i in range(1, len(hof)):
            if hof[i] > hof[i-1]:
                alwaysDecreasing = False
                break
        self.assertTrue(alwaysDecreasing)

    def test_getSol(self):
        self.sres.fit()
        self.assertAlmostEqual(3, self.sres.getSolution()[0], places=2)
        self.assertAlmostEqual(0.5, self.sres.getSolution()[1], places=2)
示例#10
0
    def test_sres_alg_using_version_of_ESStep_that_takes_double_pointers(self):
        """
        We need double pointers as input to ESInit but since pointers in ESStep. In attempt to debug the
        memory related issues in test_sres_alg_using_dereferencing_pointer_functions we rewrote the
        ESStep function in C so that it takes double pointers.
        :return:
        """
        sres = SRES()
        param = sres._makeESParameter()
        stats = sres._makeESStatistics()
        population = sres._makeESPopulation()
        trsfm = sres._getTransformFun(2)

        # https://stackoverflow.com/questions/51131433/how-to-pass-lists-into-a-ctypes-function-on-python/51132594

        seed = ct.c_int32(0)
        gamma = ct.c_double(0.85)
        alpha = ct.c_double(0.2)
        retry = ct.c_int32(10)
        es = ct.c_int32(1)
        constraint = ct.c_int32(0)
        dim = ct.c_int32(2)
        varphi = ct.c_double(1.0)
        ngen = ct.c_int32(50)

        miu = 5
        lambda_ = 5

        # How to verify that this works?
        ub = ct.pointer(sres.DoubleArrayLen2(10.0, 10.0))  # double *ub,
        lb = ct.pointer(sres.DoubleArrayLen2(0.01, 0.01))  # double *lb,

        ESfcnFG_TYPE = ct.CFUNCTYPE(None, ct.POINTER(ct.c_double * 2),
                                    ct.POINTER(ct.c_double),
                                    ct.POINTER(ct.c_double))

        def cost_fun(x, f, g):
            sim = generateData(x.contents[0], x.contents[1])
            cost = 0
            for i in range(10):
                cost += (EXP_DATA[i] - sim[i])**2
            cost_dbl_ptr = ct.pointer(ct.c_double(cost))

            # copy the value from Python to C. If we don't do this, the value gets deleted.
            ct.memmove(
                ct.cast(f, ct.c_void_p).value,
                ct.cast(cost_dbl_ptr, ct.c_void_p).value,
                ct.sizeof(ct.c_double))

        f = ESfcnFG_TYPE(cost_fun)
        sres.ESInitial(seed, param, trsfm, f, es, constraint, dim, ub, lb, miu,
                       lambda_, ngen, gamma, alpha, varphi, retry, population,
                       stats)

        curgen = 0
        while curgen < 1000:
            sres._ESStep(sres.derefESPopulation(population),
                         sres.derefESParameter(param),
                         sres.derefESStatistics(stats), 0.45)
            curgen += 1
示例#11
0
    def test_sres_alg_using_dereferencing_pointer_functions(self):
        """
        We need double pointers as input to ESInit but since pointers in ESStep.
        This version attempts to create double pointers in make* functions and then
        dereference them in using deref* function calls. The actual dereferencing
        happens on the C end
        :return:
        """
        sres = SRES()
        param = sres._makeESParameter()
        stats = sres._makeESStatistics()
        population = sres._makeESPopulation()
        trsfm = sres._getTransformFun(2)

        # https://stackoverflow.com/questions/51131433/how-to-pass-lists-into-a-ctypes-function-on-python/51132594

        seed = ct.c_int32(0)
        gamma = ct.c_double(0.85)
        alpha = ct.c_double(0.2)
        retry = ct.c_int32(10)
        es = ct.c_int32(1)
        constraint = ct.c_int32(0)
        dim = ct.c_int32(2)
        varphi = ct.c_double(1.0)
        ngen = ct.c_int32(50)

        miu = 5
        lambda_ = 5

        # How to verify that this works?
        ub = ct.pointer(sres.DoubleArrayLen2(10.0, 10.0))  # double *ub,
        lb = ct.pointer(sres.DoubleArrayLen2(0.1, 0.1))  # double *lb,

        ESfcnFG_TYPE = ct.CFUNCTYPE(None, ct.POINTER(ct.c_double * 2),
                                    ct.POINTER(ct.c_double),
                                    ct.POINTER(ct.c_double))

        def cost_fun(x, f, g):
            print("From Python : Hello")
            sim = generateData(x.contents[0], x.contents[1])
            cost = 0
            for i in range(10):
                cost += (EXP_DATA[i] - sim[i])**2
            cost_dbl_ptr = ct.pointer(ct.c_double(cost))

            # copy the value from Python to C. If we don't do this, the value gets deleted.
            ct.memmove(
                ct.cast(f, ct.c_void_p).value,
                ct.cast(cost_dbl_ptr, ct.c_void_p).value,
                ct.sizeof(ct.c_double))

        print("From Python: Call to sres.ESInitial")
        sres.ESInitial(seed, param, trsfm, ESfcnFG_TYPE(cost_fun), es,
                       constraint, dim, ub, lb, miu, lambda_, ngen, gamma,
                       alpha, varphi, retry, population, stats)
        print("From Python: Call to sres.ESInitial has finished")

        curgen = 0
        while curgen < 10:
            print("Current gen: ", curgen)
            print("From Python: Call to sres.ESStep")
            sres._ESStep(sres.derefESPopulation(population),
                         sres.derefESParameter(param),
                         sres.derefESStatistics(stats), ct.c_double(0.45))
            print("From Python: Call to sres.ESStep has finished")
            curgen += 1
示例#12
0
import pandas as pd
import numpy as np
from sres import SRES, _lib
import ctypes as ct
import tellurium as te
from math import pi as PI
import unittest

sres = SRES(2)


def generateData(mu, sigma):
    return np.random.normal(mu, sigma, 10)


EXP_DATA = generateData(5, 0.1)


class Test(unittest.TestCase):
    def setUp(self) -> None:
        pass

    @sres.COST_FUNCTION_CALLBACK
    def test_ctypes_callback_fn_example(self):
        from ctypes import cdll

        libc = cdll.msvcrt

        IntArray5 = ct.c_int * 5
        ia = IntArray5(5, 1, 7, 33, 99)
        qsort = libc.qsort
示例#13
0
@SRES.callback(numEstimatedParameters=2)
def beale_cost_fun(parameters):
    """optimum at (x=3.0, y=0.5) = 0"""
    x, y = parameters.contents
    # only when in logspace we need to do this:
    if LOGSPACE:
        x = 10**x
        y = 10**y
    return (1.5 - x + x * y)**2 + (2.25 - x + x * y**2)**2 + (2.625 - x +
                                                              x * y**3)**2


if __name__ == "__main__":
    ngen = 500
    popsize = 8000

    sres = SRES(
        beale_cost_fun,
        popsize=popsize,
        numGenerations=ngen,
        startingValues=[8.324, 7.335],
        lb=[0.1, 0.1],
        ub=[10, 10],
        childrate=7,
        logspace=LOGSPACE,
        verbose=True,
    )

    print(sres.fit())
示例#14
0
from sres import SRES
import numpy as np
import ctypes as ct


def generateData(mu, sigma):
    return np.random.normal(mu, sigma, 10)


EXP_DATA = generateData(5, 0.1)

sres = SRES(100, [0.01] * 2, [10] * 2)

# decorator for wrapping cost function written in Python
# COST_FUNCTION_CALLBACK = ct.CFUNCTYPE(None, ct.POINTER(ct.c_double * 2), ct.POINTER(ct.c_double),
#                                       ct.POINTER(ct.c_double))


@sres.COST_FUNCTION_CALLBACK
def cost_fun(x, f, g):
    sim = generateData(x.contents[0], x.contents[1])
    cost = 0
    for i in range(10):
        cost += (EXP_DATA[i] - sim[i])**2
    f.contents.value = cost


sres.cost_fun = cost_fun

sres.fit(cost_fun)