Exemplo n.º 1
0
def fit(func,
        coords,
        data,
        p0,
        bounds=[],
        args=None,
        ptol=1e-4,
        seed=None,
        optimizer="apache_nm"):
    '''
    Arguments:
    func      -- function (or list of functions)
    coords    -- coordinate dataset(s)
    data      -- data to fit
    p0        -- list of initial parameters
    bounds    -- list of parameter bounds, bounds are tuples of lower and upper values (any can be None)
    args      -- extra arguments
    ptol      -- parameter fit tolerance
    seed      -- seed value for genetic algorithm-based optimiser
    optimizer -- description of the optimizer to use, e.g. ['local','global','simplex','genetic',
                 'gradient','apache_nm','apache_md','apache_cg']
                 local and global are general settings, which point the one of the specific methods
                 If any global methods are picked, the bounds argument must also be filled in.
    Returns:
    fitresult object
    '''
    fnlist = []
    func = _toList(func)
    p0 = _toList(p0)
    if not isinstance(bounds, list):
        bounds = [bounds]
    else:
        bounds = list(bounds)  # make a copy
    n_bounds = len(bounds)
    mixed = False
    for f in func:
        if isinstance(f, tuple):
            print "parameter count is no longer required"
            f = f[0]
        if function.isjclass(f):
            # create bound function object
            np = function.nparams(f)
            pl = _createparams(np, p0, bounds)
            fnlist.append(f(pl))
        elif not _inspect.isfunction(f):
            # instantiated Java function
            # np = f.getNoOfParameters()
            fnlist.append(f)
        else:
            np = len(_inspect.getargspec(f)[0]) - 1
            if np < 1:
                raise ValueError, "Function needs more than one argument (i.e. at least one parameter)"
            pl = _createparams(np, p0, bounds)
            fnlist.append(fitfunc(f, f.__name__, pl, args))
            mixed = True

    if not mixed:  # no jython functions
        cfunc = _compfn()
    else:
        cfunc = cfitfunc()
    for f in fnlist:
        if function.isjmethod(f):  # unwrap
            f = f._jfunc()
        cfunc.addFunction(f)

    coords = list(_asIterable(coords))
    for i in range(len(coords)):  # check and slice coordinates to match data
        c = coords[i]
        if c.shape != data.shape:
            ns = [slice(d) for d in data.shape]
            coords[i] = c[ns]

    if seed:
        _fitter.seed = int(seed)

    import time
    start = -time.time()
    jcoords = [__cvt_jobj(c, copy=False, force=True) for c in coords]
    jdata = data._jdataset()

    # use the appropriate fitter for the task
    if optimizer == 'local':
        _fitter.simplexFit(ptol, jcoords, jdata, cfunc)
    elif optimizer == 'global':
        if n_bounds == 0:
            print "Using a global optimizer with no bounds is unlikely to work, please use the bounds argument to narrow the search space"
        _fitter.geneticFit(ptol, jcoords, jdata, cfunc)
    elif optimizer == 'simplex':
        _fitter.simplexFit(ptol, jcoords, jdata, cfunc)
    elif optimizer == 'gradient':
        _fitter.GDFit(ptol, jcoords, jdata, cfunc)
    elif optimizer == 'apache_nm':
        _fitter.ApacheNelderMeadFit(jcoords, jdata, cfunc)
    elif optimizer == 'apache_md':
        _fitter.ApacheMultiDirectionFit(jcoords, jdata, cfunc)
    elif optimizer == 'apache_cg':
        _fitter.ApacheConjugateGradientFit(jcoords, jdata, cfunc)
    elif optimizer == 'genetic':
        if n_bounds == 0:
            print "Using a global optimizer with no bounds is unlikely to work, please use the bounds argument to narrow the search space"
        _fitter.geneticFit(ptol, jcoords, jdata, cfunc)

    start += time.time()
    print "Fit took %fs" % start

    return fitresult(cfunc, coords, data)
Exemplo n.º 2
0
def fit(func, coords, data, p0, bounds=[], args=None, ptol=1e-4, seed=None, optimizer="apache_nm"):
    '''
    Arguments:
    func      -- function (or list of functions)
    coords    -- coordinate dataset(s)
    data      -- data to fit
    p0        -- list of initial parameters
    bounds    -- list of parameter bounds, bounds are tuples of lower and upper values (any can be None)
    args      -- extra arguments
    ptol      -- parameter fit tolerance
    seed      -- seed value for genetic algorithm-based optimiser
    optimizer -- description of the optimizer to use, e.g. ['local','global','simplex','genetic',
                 'gradient','apache_nm','apache_md','apache_cg']
                 local and global are general settings, which point the one of the specific methods
                 If any global methods are picked, the bounds argument must also be filled in.
    Returns:
    fitresult object
    '''
    fnlist = []
    func = _toList(func)
    p0 = _toList(p0)
    if not isinstance(bounds, list):
        bounds = [bounds]
    else:
        bounds = list(bounds) # make a copy
    n_bounds = len(bounds)
    mixed = False
    for f in func:
        if isinstance(f, tuple):
            print("parameter count is no longer required")
            f = f[0]
        if function.isjclass(f):
            # create bound function object
            np = function.nparams(f)
            pl = _createparams(np, p0, bounds)
            fnlist.append(f(pl))
        elif not _inspect.isfunction(f):
            # instantiated Java function
            # np = f.getNoOfParameters()
            fnlist.append(f)
        else:
            np = len(_inspect.getargspec(f)[0]) - 1
            if np < 1:
                raise ValueError("Function needs more than one argument (i.e. at least one parameter)")
            pl = _createparams(np, p0, bounds)
            fnlist.append(fitfunc(f, f.__name__, pl, args))
            mixed = True

    if not mixed: # no jython functions
        cfunc = _compfn()
    else:
        cfunc = cfitfunc()
    for f in fnlist:
        if function.isjmethod(f): # unwrap
            f = f._jfunc()
        cfunc.addFunction(f)

    coords = list(_asIterable(coords))
    for i in range(len(coords)): # check and slice coordinates to match data
        c = coords[i]
        if c.shape != data.shape:
            ns = [slice(d) for d in data.shape]
            coords[i] = c[ns]

    if seed:
        _fitter.seed = int(seed)

    jcoords = [ __cvt_jobj(c, copy=False, force=True) for c in coords ]
    jdata = data._jdataset()

    # use the appropriate fitter for the task
    if optimizer == 'local':
        _fitter.ApacheNelderMeadFit(jcoords, jdata, cfunc)
    elif optimizer == 'global':
        if n_bounds == 0:
            print("Using a global optimizer with no bounds is unlikely to work, please use the bounds argument to narrow the search space")
        _fitter.geneticFit(ptol, jcoords, jdata, cfunc)
    elif optimizer == 'simplex':
        _fitter.simplexFit(ptol, jcoords, jdata, cfunc)
    elif optimizer == 'gradient':
        _fitter.GDFit(ptol, jcoords, jdata, cfunc)
    elif optimizer == 'apache_nm':
        _fitter.ApacheNelderMeadFit(jcoords, jdata, cfunc)
    elif optimizer == 'apache_md':
        _fitter.ApacheMultiDirectionFit(jcoords, jdata, cfunc)
    elif optimizer == 'apache_cg':
        _fitter.ApacheConjugateGradientFit(jcoords, jdata, cfunc)
    elif optimizer == 'genetic':
        if n_bounds == 0:
            print("Using a global optimizer with no bounds is unlikely to work, please use the bounds argument to narrow the search space")
        _fitter.geneticFit(ptol, jcoords, jdata, cfunc)

    return fitresult(cfunc, coords, data)