pycnic / pysimkernel

A Python package to control parameter scans and iterations for computational experiments
ISC License
1 stars 2 forks source link

Minimal testcase for additional layer with multiple inputs #23

Open andsor opened 8 years ago

andsor commented 8 years ago
import numpy as np
from simkernel import Experiment

# define simulation
def sim(x):
    return x

xp = Experiment(sim)
outer_xp = Experiment(xp)

# execute experiment
res = outer_xp(input=[1, 2, 3])

np.testing.assert_array_equal(res, [1, 2, 3])
debsankha commented 8 years ago

This can be taken care of by this barebones backend code:

class Experiment(object):
    def __init__(self, func, inputgen = None):
        """
        Args:
            func: a callable.
            inputgen: a generator
        """
        self.func = func
        if inputgen is None:
            self.inputgen = lambda x:((i,) for i in [x])
        else:
            self.inputgen = inputgen 

    def __call__(self, input):
        res = []
        for inputgen_arg in input:
            res.append(self.run(inputgen_arg))
        return res

    def run(self, inputgen_arg):
        return [self.func(*funcargs) for funcargs in\
                self.inputgen(inputgen_arg)]

if __name__ == '__main__':
    from itertools import repeat

    def sum(x, y):
        return x + y

    x_min = 0
    x_max = 5

    y_min = 10
    y_max = 15

    e_inner = Experiment(sum, inputgen = lambda y:zip(range(x_min, x_max), repeat(y)))
    e_outer = Experiment(e_inner.run, inputgen = None)
    print(e_outer(input = range(y_min, y_max)))