Пример #1
0
	def _process(self, ds, xoffset=0, yoffset=0):###dsxaxis, dsyaxis):
##		assert(dsyaxis is None)		# STUB
##		assert(dsxaxis is None)		# STUB
		
		integrator = Integrate2D()
		dsy, dsx = integrator.value(ds)
		dsyaxis = DatasetFactory.createRange(dsy.shape[0])
		dsxaxis = DatasetFactory.createRange(dsx.shape[0])
		
		gaussian = Gaussian(dsyaxis.min(), dsyaxis.max(), dsyaxis.max()-dsyaxis.min(), (dsyaxis.max()-dsyaxis.min())*(dsy.max()-dsy.min()) )
		gaussian.getParameter(2).setLowerLimit(0)
		if self.maxwidth is not None:
			gaussian.getParameter(1).setUpperLimit(self.maxwidth)
		ansy = Fitter.fit(dsyaxis, dsy, GeneticAlg(0.001), [ gaussian, Offset( dsy.min(),dsy.max() ) ] )
# 		ansy = DataSetFunctionFitter().fit( dsyaxis, dsy, GeneticAlg(.001), [ gaussian, Offset( dsy.min(),dsy.max() ) ] )
# 		ansy = ansy.functionOutput
		
		gaussian = Gaussian(dsxaxis.min(), dsxaxis.max(), dsxaxis.max()-dsxaxis.min(), (dsxaxis.max()-dsxaxis.min())*(dsx.max()-dsx.min()) )
		gaussian.getParameter(2).setLowerLimit(0)
		if self.maxwidth is not None:
			gaussian.getParameter(1).setUpperLimit(self.maxwidth)
		try:
			ansx = fitplot( dsxaxis, dsx, GeneticAlg(.001), [ gaussian, Offset( dsx.min(),dsx.max() ) ] )
		except java.lang.Exception:
			# Probably cannot find Plot_Manager on the finder
			ansx = Fitter.fit(dsxaxis, dsx, GeneticAlg(0.001), [ gaussian, Offset( dsx.min(),dsx.max() ) ] )
		#dsyaxis = dsyaxis.subSampleMean(dsy.dimensions[0]/2)
		#dsy = dsy.subSampleMean(dsy.dimensions[0]/2)
		#dsxaxis = dsxaxis.subSampleMean(dsx.dimensions[0]/2)
		#dsx = dsx.subSampleMean(dsx.dimensions[0]/2)		
		
		peaky = ansy.getParameters()[0].getValue()
		fwhmy = ansy.getParameters()[1].getValue()
		areay = ansy.getParameters()[2].getValue()
		offsety = ansy.getParameters()[3].getValue() / dsx.shape[0]
		
		peakx = ansx.getParameters()[0].getValue()
		fwhmx = ansx.getParameters()[1].getValue()
		areax = ansx.getParameters()[2].getValue()
		offsetx = ansx.getParameters()[3].getValue() / dsy.shape[0]
		
		background = (offsetx+offsety)/2.
		fwhmarea = fwhmy*fwhmx*pi/4
		topy = areay / fwhmy
		topx = areax / fwhmx
		
		if xoffset==None:
			xoffset=0
		
		if yoffset==None:
			yoffset=0
		
		return background, peakx+xoffset, peaky+yoffset, topx, topy, fwhmx, fwhmy, fwhmarea
Пример #2
0
def polyfit(x, y, deg, rcond=None, full=False):
    '''Linear least squares polynomial fit

    Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of order deg to points (x, y).
    Arguments:
    x   -- x-coordinates of sample points
    y   -- y-coordinates of sample points
    deg -- order of fitting polynomial
    
    Returns:
    a vector of coefficients p that minimises the squared error and
    a fitresult object
    '''
    poly = _poly(deg)
    x = _asIterable(x)
    if rcond is None:
        rcond = 2e-16 * y.size
    _fitter.polyFit(x, y, rcond, poly)
    fr = fitresult(poly, x, y)
    if full:
        return fr.parameters, fr
    else:
        return fr.parameters
Пример #3
0
def polyfit(x, y, deg, rcond=None, full=False):
    '''Linear least squares polynomial fit

    Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of order deg to points (x, y).
    Arguments:
    x   -- x-coordinates of sample points
    y   -- y-coordinates of sample points
    deg -- order of fitting polynomial
    
    Returns:
    a vector of coefficients p that minimises the squared error and
    a fitresult object
    '''
    poly = _poly(deg)
    x = _asIterable(x)
    if rcond is None:
        rcond = 2e-16*y.size
    _fitter.polyFit(x, y, rcond, poly)
    fr = fitresult(poly, x, y)
    if full:
        return fr.parameters, fr
    else:
        return fr.parameters
Пример #4
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)
Пример #5
0
	def fitplot(*args):
		fitted_function = Fitter.fit(*args)
		RCPPlotter.plot("Data Vector", args[0],fitted_function.display(args[0])[0]);
		return fitted_function
Пример #6
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)