Exemplo n.º 1
0
def fit_signal(signal,l):
    x1=np.linspace(0,1,len(signal))
    
    piecewiseModel=Model(piecewise_prob)
    piecewiseModel.set_param_hint('l',     value=1,vary=False)
    piecewiseModel.set_param_hint('C',   vary=True,  value=.1,min=0,max=1)
    piecewiseModel.make_params()
    
    res=piecewiseModel.fit(signal,x=x1,weights=np.sin(1.5*x1)+1.5)
    return res
Exemplo n.º 2
0
def fitGompertz(x, y, dias):  # fit a logistic function~
    def Gompertz(a, b, c, x):
        return a * np.exp(-1 * np.exp(-b * (x - c)))

    model = Model(Gompertz, independent_vars=["x"])

    params = model.make_params()
    params["a"].value = 10000
    params["b"].value = 0.05
    params["c"].value = 100
    output = model.fit(y, params, x=x)
    amplitude = output.params["a"].value
    amplitude = math.floor(amplitude)
    center = output.params["c"].value
    sigma = output.params["b"].value
    fit = []
    xfit = []
    cumulative = []
    for i in range(61, dias):
        if i == 61:
            xfit.append(i)
            value = amplitude * np.exp(-1 * np.exp(-sigma * (i - center)))
            fit.append(value)
            cumulative.append(0)
        else:
            xfit.append(i)
            value = amplitude * np.exp(-1 * np.exp(-sigma * (i - center)))
            fit.append(value)
            c = value - fit[i - 62]
            cumulative.append(c)
    return amplitude, center, sigma, xfit, fit, cumulative, output.fit_report()
Exemplo n.º 3
0
def make_twoDgaussian_model(self):
    """ This method creates a model of the 2D gaussian function.

    The parameters are: 'amplitude', 'center', 'sigm, 'fwhm' and offset
    'c'. For function see:

    @return lmfit.model.CompositeModel model: Returns an object of the
                                              class CompositeModel
    @return lmfit.parameter.Parameters params: Returns an object of the
                                               class Parameters with all
                                               parameters for the
                                               gaussian model.

    """

    def twoDgaussian_function(x, amplitude, x_zero, y_zero, sigma_x, sigma_y,
                              theta, offset):
        # FIXME: x_data_tuple: dimension of arrays

        """ This method provides a two dimensional gaussian function.

        Function taken from:
        http://stackoverflow.com/questions/21566379/fitting-a-2d-gaussian-function-using-scipy-optimize-curve-fit-valueerror-and-m/21566831

        Question from: http://stackoverflow.com/users/2097737/bland & http://stackoverflow.com/users/3273102/kokomoking
                       & http://stackoverflow.com/users/2767207/jojodmo
        Answer: http://stackoverflow.com/users/1461210/ali-m & http://stackoverflow.com/users/5234/mrjrdnthms

        @param array[k][M] x_data_tuple: array which is (k,M)-shaped, x and y
                                         values
        @param float or int amplitude: Amplitude of gaussian
        @param float or int x_zero: x value of maximum
        @param float or int y_zero: y value of maximum
        @param float or int sigma_x: standard deviation in x direction
        @param float or int sigma_y: standard deviation in y direction
        @param float or int theta: angle for eliptical gaussians
        @param float or int offset: offset

        @return callable function: returns the function
        """

        (u, v) = x
        x_zero = float(x_zero)
        y_zero = float(y_zero)

        a = (np.cos(theta) ** 2) / (2 * sigma_x ** 2) \
            + (np.sin(theta) ** 2) / (2 * sigma_y ** 2)
        b = -(np.sin(2 * theta)) / (4 * sigma_x ** 2) \
            + (np.sin(2 * theta)) / (4 * sigma_y ** 2)
        c = (np.sin(theta) ** 2) / (2 * sigma_x ** 2) \
            + (np.cos(theta) ** 2) / (2 * sigma_y ** 2)
        g = offset + amplitude * np.exp(- (a * ((u - x_zero) ** 2) \
                                           + 2 * b * (u - x_zero) * (v - y_zero) \
                                           + c * ((v - y_zero) ** 2)))
        return g.ravel()

    model = Model(twoDgaussian_function)
    params = model.make_params()

    return model, params
def test_custom_independentvar():
    """Tests using a non-trivial object as an independent variable."""
    npts = 501
    xmin = 1
    xmax = 21
    cen = 8
    obj = Stepper(xmin, xmax, npts)
    y = gaussian(obj.get_x(), amplitude=3.0, center=cen, sigma=2.5)
    y += np.random.normal(scale=0.2, size=npts)

    gmod = Model(gaussian_mod)

    params = gmod.make_params(amplitude=2, center=5, sigma=8)
    out = gmod.fit(y, params, obj=obj)

    assert (out.nvarys == 3)
    assert (out.nfev > 10)
    assert (out.chisqr > 1)
    assert (out.chisqr < 100)
    assert (out.params['sigma'].value < 3)
    assert (out.params['sigma'].value > 2)
    assert (out.params['center'].value > xmin)
    assert (out.params['center'].value < xmax)
    assert (out.params['amplitude'].value > 1)
    assert (out.params['amplitude'].value < 5)
Exemplo n.º 5
0
def make_amplitude_model(self, prefix=None):
    """ Create a constant model.

    @param str prefix: optional string, which serves as a prefix for all
                       parameters used in this model. That will prevent
                       name collisions if this model is used in a composite
                       way.

    @return tuple: (object model, object params), for more description see in
                   the method make_constant_model.
    """
    def amplitude_function(x, amplitude):
        """ Function of a constant value.

        @param numpy.array x: 1D array as the independent variable - e.g. time
        @param float amplitude: constant offset

        @return: constant function, in order to use it as a model
        """

        return amplitude

    if not isinstance(prefix, str) and prefix is not None:
        self.log.error(
            'The passed prefix <{0}> of type {1} is not a string and cannot be used as '
            'a prefix and will be ignored for now. Correct that!'.format(
                prefix, type(prefix)))
        model = Model(amplitude_function, independent_vars='x')
    else:
        model = Model(amplitude_function, independent_vars='x', prefix=prefix)

    params = model.make_params()

    return model, params
Exemplo n.º 6
0
def make_amplitude_model(self, prefix=None):
    """ Create a constant model.

    @param str prefix: optional string, which serves as a prefix for all
                       parameters used in this model. That will prevent
                       name collisions if this model is used in a composite
                       way.

    @return tuple: (object model, object params), for more description see in
                   the method make_constant_model.
    """

    def amplitude_function(x, amplitude):
        """ Function of a constant value.

        @param numpy.array x: 1D array as the independent variable - e.g. time
        @param float amplitude: constant offset

        @return: constant function, in order to use it as a model
        """

        return amplitude

    if not isinstance(prefix, str) and prefix is not None:
        self.log.error('The passed prefix <{0}> of type {1} is not a string and cannot be used as '
                       'a prefix and will be ignored for now. Correct that!'.format(prefix,
                                                                                    type(prefix)))
        model = Model(amplitude_function, independent_vars='x')
    else:
        model = Model(amplitude_function, independent_vars='x', prefix=prefix)

    params = model.make_params()

    return model, params
def make_bareexponentialdecay_model(self):
    """
    This method creates a model of bare exponential decay.

    @return tuple: (object model, object params)

    Explanation of the objects:
        object lmfit.model.CompositeModel model:
            A model the lmfit module will use for that fit. Here a
            gaussian model. Returns an object of the class
            lmfit.model.CompositeModel.

        object lmfit.parameter.Parameters params:
            It is basically an OrderedDict, so a dictionary, with keys
            denoting the parameters as string names and values which are
            lmfit.parameter.Parameter (without s) objects, keeping the
            information about the current value.

    """
    def bareexponentialdecay_function(x, lifetime):
        """
        Function of a bare exponential decay.
        @param x: variable variable - e.g. time
        @param lifetime: lifetime
        @return: bare exponential decay function: in order to use it as a model
        """
        return np.exp(-x / lifetime)

    model = Model(bareexponentialdecay_function)
    params = model.make_params()

    return model, params
Exemplo n.º 8
0
def make_slope_model(self):
    """ This method creates a model of a slope model.

    @return tuple: (object model, object params)

    Explanation of the objects:
        object lmfit.model.CompositeModel model:
            A model the lmfit module will use for that fit. Returns an object of the class
            lmfit.model.CompositeModel.

        object lmfit.parameter.Parameters params:
            It is basically an OrderedDict, so a dictionary, with keys
            denoting the parameters as string names and values which are
            lmfit.parameter.Parameter (without s) objects, keeping the
            information about the current value.

    For further information have a look in:
    http://cars9.uchicago.edu/software/python/lmfit/builtin_models.html#models.GaussianModel
    """
    def slope_function(x, slope):
        """
        Function of a constant value.
        @param x: variable variable
        @param slope: independent variable - slope

        @return: slope function: in order to use it as a model
        """

        return slope + 0.0 * x

    model = Model(slope_function)
    params = model.make_params()

    return model, params
Exemplo n.º 9
0
def test_custom_independentvar():
    """Tests using a non-trivial object as an independent variable."""
    npts = 501
    xmin = 1
    xmax = 21
    cen = 8
    obj = Stepper(xmin, xmax, npts)
    y = gaussian(obj.get_x(), amplitude=3.0, center=cen, sigma=2.5)
    y += np.random.normal(scale=0.2, size=npts)

    gmod = Model(gaussian_mod)

    params = gmod.make_params(amplitude=2, center=5, sigma=8)
    out = gmod.fit(y, params, obj=obj)

    assert(out.nvarys == 3)
    assert(out.nfev > 10)
    assert(out.chisqr > 1)
    assert(out.chisqr < 100)
    assert(out.params['sigma'].value < 3)
    assert(out.params['sigma'].value > 2)
    assert(out.params['center'].value > xmin)
    assert(out.params['center'].value < xmax)
    assert(out.params['amplitude'].value > 1)
    assert(out.params['amplitude'].value < 5)
Exemplo n.º 10
0
def lmfit_gaussian(x_array, y_array, err_array, x_boundarys):

    # Find indeces for six points in spectrum
    idcsW = np.searchsorted(x_array, x_boundarys)

    # Emission region
    idcsEmis = (x_array[idcsW[2]] <= x_array) & (x_array <= x_array[idcsW[3]])

    # Return left and right continua merged in one array
    idcsCont = (((x_array[idcsW[0]] <= x_array) &
                 (x_array <= x_array[idcsW[1]])) |
                ((x_array[idcsW[4]] <= x_array) &
                 (x_array <= x_array[idcsW[5]]))).squeeze()

    emisWave, emisFlux = x_array[idcsEmis], y_array[idcsEmis]
    contWave, contFlux = x_array[idcsCont], y_array[idcsCont]
    idx_peak = np.argmax(emisFlux)

    fit_model = Model(linear_model, prefix=f'{lineLabel}_cont_')
    fit_model.set_param_hint(f'{lineLabel}_cont_slope', **{
        'value': 0,
        'vary': False
    })
    fit_model.set_param_hint(f'{lineLabel}_cont_intercept', **{
        'value': contFlux.mean(),
        'vary': False
    })

    fit_model += Model(gaussian_model, prefix=f'{lineLabel}_')
    fit_model.set_param_hint(f'{lineLabel}_amp',
                             value=emisFlux[idx_peak] - contFlux.mean())
    fit_model.set_param_hint(f'{lineLabel}_center', value=emisWave[idx_peak])
    fit_model.set_param_hint(f'{lineLabel}_sigma', value=1.0)

    x_fit = x_array[idcsEmis + idcsCont]
    y_fit = y_array[idcsEmis + idcsCont]
    w_fit = 1.0 / err_array[idcsEmis + idcsCont]

    fit_params = fit_model.make_params()
    obs_fit_output = fit_model.fit(y_fit, fit_params, x=x_fit, weights=w_fit)

    # amp = obs_fit_output.params[f"{lineLabel}_amp"].value
    mu = obs_fit_output.params[f"{lineLabel}_center"].value
    sigma = obs_fit_output.params[f"{lineLabel}_sigma"].value

    mu_err = obs_fit_output.params[f"{lineLabel}_center"].stderr
    sigma_err = obs_fit_output.params[f"{lineLabel}_sigma"].stderr

    x_obs, y_obs = obs_fit_output.userkws['x'], obs_fit_output.data
    wave_obs = np.linspace(x_obs[0], x_obs[-1], 500)
    flux_comps_obs = obs_fit_output.eval_components(x=wave_obs)
    flux_obs = flux_comps_obs.get(f'{lineLabel}_cont_',
                                  0.0) + flux_comps_obs[f'{lineLabel}_']

    return x_fit, y_fit, wave_obs, flux_obs, mu, sigma, mu_err, sigma_err
Exemplo n.º 11
0
def make_barestretchedexponentialdecay_model(self, prefix=None):
    """ Create a general bare exponential decay model.

    @param str prefix: optional string, which serves as a prefix for all
                       parameters used in this model. That will prevent
                       name collisions if this model is used in a composite
                       way.

    @return tuple: (object model, object params)

    Explanation of the objects:
        object lmfit.model.CompositeModel model:
            A model the lmfit module will use for that fit. Here a
            gaussian model. Returns an object of the class
            lmfit.model.CompositeModel.

        object lmfit.parameter.Parameters params:
            It is basically an OrderedDict, so a dictionary, with keys
            denoting the parameters as string names and values which are
            lmfit.parameter.Parameter (without s) objects, keeping the
            information about the current value.

    """
    def barestretchedexponentialdecay_function(x, beta, lifetime):
        """ Function of a bare exponential decay.

        @param numpy.array x: 1D array as the independent variable - e.g. time
        @param float lifetime: constant lifetime

        @return: bare exponential decay function: in order to use it as a model
        """
        return np.exp(-np.power(x / lifetime, beta))

    if not isinstance(prefix, str) and prefix is not None:

        self.log.error(
            'The passed prefix <{0}> of type {1} is not a string and'
            'cannot be used as a prefix and will be ignored for now.'
            'Correct that!'.format(prefix, type(prefix)))
        model = Model(barestretchedexponentialdecay_function,
                      independent_vars='x')
    else:
        model = Model(barestretchedexponentialdecay_function,
                      independent_vars='x',
                      prefix=prefix)

    params = model.make_params()

    return model, params
Exemplo n.º 12
0
def make_amplitude_model(self, prefix=None):
    """ This method creates a model of a constant model.
    @param string prefix: variable prefix

    @return tuple: (object model, object params)

    Explanation of the objects:
        object lmfit.model.CompositeModel model:
            A model the lmfit module will use for that fit. Returns an object of the class
            lmfit.model.CompositeModel.

        object lmfit.parameter.Parameters params:
            It is basically an OrderedDict, so a dictionary, with keys
            denoting the parameters as string names and values which are
            lmfit.parameter.Parameter (without s) objects, keeping the
            information about the current value.

    For further information have a look in:
    http://cars9.uchicago.edu/software/python/lmfit/builtin_models.html#models.GaussianModel
    """
    def amplitude_function(x, amplitude):
        """
        Function of a constant value.
        @param x: variable variable
        @param amplitude: independent variable - e.g. amplitude

        @return: constant function: in order to use it as a model
        """

        return amplitude + 0.0 * x

    if prefix is None:
        model = Model(amplitude_function)
    else:
        if not isinstance(prefix, str):
            logger.error('Given prefix in constant model is no string. '
                         'Deleting prefix.')
        try:
            model = Model(amplitude_function, prefix=prefix)
        except:
            logger.error('Creating the constant model failed. '
                         'The prefix might not be a valid string. '
                         'The prefix was deleted.')
            model = Model(amplitude_function)

    params = model.make_params()

    return model, params
Exemplo n.º 13
0
def make_constant_model(self, prefix=None):
    """ Create constant model.

    @param str prefix: optional string, which serves as a prefix for all
                       parameters used in this model. That will prevent
                       name collisions if this model is used in a composite
                       way.

    @return tuple: (object model, object params)

    Explanation of the objects:
        object lmfit.model.CompositeModel model:
            A model the lmfit module will use for that fit. Returns an object of the class
            lmfit.model.CompositeModel.

        object lmfit.parameter.Parameters params:
            It is basically an OrderedDict, so a dictionary, with keys
            denoting the parameters as string names and values which are
            lmfit.parameter.Parameter (without s) objects, keeping the
            information about the current value.

    For further information have a look in:
    http://cars9.uchicago.edu/software/python/lmfit/builtin_models.html#models.GaussianModel
    """
    def constant_function(x, offset):
        """ Function of a constant value.

        @param numpy.array x: 1D array as the independent variable - e.g. time
        @param float offset: constant offset

        @return: constant function, in order to use it as a model
        """

        return offset

    if not isinstance(prefix, str) and prefix is not None:
        self.log.error(
            'The passed prefix <{0}> of type {1} is not a string and cannot be used as '
            'a prefix and will be ignored for now. Correct that!'.format(
                prefix, type(prefix)))
        model = Model(constant_function, independent_vars='x')
    else:
        model = Model(constant_function, independent_vars='x', prefix=prefix)

    params = model.make_params()

    return model, params
Exemplo n.º 14
0
def make_barestretchedexponentialdecay_model(self, prefix=None):
    """ Create a general bare exponential decay model.

    @param str prefix: optional string, which serves as a prefix for all
                       parameters used in this model. That will prevent
                       name collisions if this model is used in a composite
                       way.

    @return tuple: (object model, object params)

    Explanation of the objects:
        object lmfit.model.CompositeModel model:
            A model the lmfit module will use for that fit. Here a
            gaussian model. Returns an object of the class
            lmfit.model.CompositeModel.

        object lmfit.parameter.Parameters params:
            It is basically an OrderedDict, so a dictionary, with keys
            denoting the parameters as string names and values which are
            lmfit.parameter.Parameter (without s) objects, keeping the
            information about the current value.

    """
    def barestretchedexponentialdecay_function(x, beta, lifetime):
        """ Function of a bare exponential decay.

        @param numpy.array x: 1D array as the independent variable - e.g. time
        @param float lifetime: constant lifetime

        @return: bare exponential decay function: in order to use it as a model
        """
        return np.exp(-np.power(x/lifetime, beta))

    if not isinstance(prefix, str) and prefix is not None:

        self.log.error('The passed prefix <{0}> of type {1} is not a string and'
                     'cannot be used as a prefix and will be ignored for now.'
                     'Correct that!'.format(prefix, type(prefix)))
        model = Model(barestretchedexponentialdecay_function,
                      independent_vars='x')
    else:
        model = Model(barestretchedexponentialdecay_function,
                      independent_vars='x', prefix=prefix)

    params = model.make_params()

    return model, params
Exemplo n.º 15
0
def make_constant_model(self, prefix=None):
    """ Create constant model.

    @param str prefix: optional string, which serves as a prefix for all
                       parameters used in this model. That will prevent
                       name collisions if this model is used in a composite
                       way.

    @return tuple: (object model, object params)

    Explanation of the objects:
        object lmfit.model.CompositeModel model:
            A model the lmfit module will use for that fit. Returns an object of the class
            lmfit.model.CompositeModel.

        object lmfit.parameter.Parameters params:
            It is basically an OrderedDict, so a dictionary, with keys
            denoting the parameters as string names and values which are
            lmfit.parameter.Parameter (without s) objects, keeping the
            information about the current value.

    For further information have a look in:
    http://cars9.uchicago.edu/software/python/lmfit/builtin_models.html#models.GaussianModel
    """
    def constant_function(x, offset):
        """ Function of a constant value.

        @param numpy.array x: 1D array as the independent variable - e.g. time
        @param float offset: constant offset

        @return: constant function, in order to use it as a model
        """

        return offset

    if not isinstance(prefix, str) and prefix is not None:
        self.log.error('The passed prefix <{0}> of type {1} is not a string and cannot be used as '
                       'a prefix and will be ignored for now. Correct that!'.format(prefix,
                                                                                    type(prefix)))
        model = Model(constant_function, independent_vars='x')
    else:
        model = Model(constant_function, independent_vars='x', prefix=prefix)

    params = model.make_params()

    return model, params
Exemplo n.º 16
0
def make_baresine_model(self, prefix=None):
    """ This method creates a model of bare sine without amplitude and
    offset.

    @param string prefix: variable prefix

    @return tuple: (object model, object params)

    Explanation of the objects:
        object lmfit.model.CompositeModel model:
            A model the lmfit module will use for that fit. Here a
            gaussian model. Returns an object of the class
            lmfit.model.CompositeModel.

        object lmfit.parameter.Parameters params:
            It is basically an OrderedDict, so a dictionary, with keys
            denoting the parameters as string names and values which are
            lmfit.parameter.Parameter (without s) objects, keeping the
            information about the current value.

    For further information have a look in:
    http://cars9.uchicago.edu/software/python/lmfit/builtin_models.html#models.GaussianModel
    """
    def sine_function(x, frequency, phase):
        """
        Function of a sine.
        @param x: variable variable - e.g. time
        @param frequency: frequency
        @param phase: phase

        @return: sine function: in order to use it as a model
        """

        return np.sin(2 * np.pi * frequency * x + phase)

    if prefix is not None:
        model = Model(sine_function, prefix=prefix)
    else:
        model = Model(sine_function)

    params = model.make_params()

    return model, params
Exemplo n.º 17
0
def make_twoDgaussian_model(self, prefix=None):
    """ Creates a model of the 2D gaussian function.

    @param str prefix: optional, if multiple models should be used in a
                       composite way and the parameters of each model should be
                       distinguished from each other to prevent name collisions.

    @return tuple: (object model, object params), for more description see in
                   the method make_gaussianwithoutoffset_model.

    """
    def twoDgaussian_function(x, amplitude, center_x, center_y, sigma_x,
                              sigma_y, theta, offset):
        """ Provide a two dimensional gaussian function.

        @param float amplitude: Amplitude of gaussian
        @param float center_x: x value of maximum
        @param float center_y: y value of maximum
        @param float sigma_x: standard deviation in x direction
        @param float sigma_y: standard deviation in y direction
        @param float theta: angle for eliptical gaussians
        @param float offset: offset

        @return callable function: returns the reference to the function

        Function taken from:
        http://stackoverflow.com/questions/21566379/fitting-a-2d-gaussian-function-using-scipy-optimize-curve-fit-valueerror-and-m/21566831

        Question from: http://stackoverflow.com/users/2097737/bland
                       http://stackoverflow.com/users/3273102/kokomoking
                       http://stackoverflow.com/users/2767207/jojodmo
        Answer: http://stackoverflow.com/users/1461210/ali-m
                http://stackoverflow.com/users/5234/mrjrdnthms
        """

        # FIXME: x_data_tuple: dimension of arrays
        # @param np.arra[k][M] x_data_tuple: array which is (k,M)-shaped,
        #                                   x and y values

        (u, v) = x
        center_x = float(center_x)
        center_y = float(center_y)

        a = (np.cos(theta) ** 2) / (2 * sigma_x ** 2) \
            + (np.sin(theta) ** 2) / (2 * sigma_y ** 2)
        b = -(np.sin(2 * theta)) / (4 * sigma_x ** 2) \
            + (np.sin(2 * theta)) / (4 * sigma_y ** 2)
        c = (np.sin(theta) ** 2) / (2 * sigma_x ** 2) \
            + (np.cos(theta) ** 2) / (2 * sigma_y ** 2)
        g = offset + amplitude * np.exp(-(a * ((u - center_x)**2) + 2 * b *
                                          (u - center_x) * (v - center_y) + c *
                                          ((v - center_y)**2)))
        return g.ravel()

    if not isinstance(prefix, str) and prefix is not None:
        self.log.error(
            'The passed prefix <{0}> of type {1} is not a string and'
            'cannot be used as a prefix and will be ignored for now.'
            'Correct that!'.format(prefix, type(prefix)))
        gaussian_2d_model = Model(twoDgaussian_function, independent_vars='x')
    else:
        gaussian_2d_model = Model(twoDgaussian_function,
                                  independent_vars='x',
                                  prefix=prefix)

    params = gaussian_2d_model.make_params()

    return gaussian_2d_model, params
Exemplo n.º 18
0
x1=np.linspace(0,genomeLen-1,len(y1))

### Korem fit

# fit piecewise using least squares (LM)

piecewiseModel=Model(piecewiseLinear)
piecewiseModel.set_param_hint('Ol',     value=0.5*genomeLen,vary=True,min=0,max=genomeLen)
#piecewiseModel.set_param_hint('Tl',     value=0.6*genomeLen,vary=True,min=0,max=genomeLen)
piecewiseModel.set_param_hint('Tc',     value = np.median(np.log2(y1)), vary=True)
piecewiseModel.set_param_hint('Oc',     value = np.median(np.log2(y1)), vary=True)
piecewiseModel.set_param_hint('delta',  value = 0.545*genomeLen, min=0.45*genomeLen, max=0.55*genomeLen, vary=True)#,expr='Tl-Ol if Tl-Ol > 0 else Ol-Tl')

#piecewiseModel.set_param_hint('Tl',     value=0.6*genomeLen,vary=True,min=0,max=genomeLen,expr='mod(Ol+delta,genLen)')
piecewiseModel.set_param_hint('genLen',   vary=False,  value=genomeLen)
piecewiseModel.make_params()

result=piecewiseModel.fit(np.log2(y1),x=x1)
resR2=R2(result.best_fit,y1)
# var=np.var(abs(np.log2(y1)-result.best_fit), dtype=np.float64)
#med=np.median(np.log2(y1))

# y1=[value for value in y1 if (np.log2(value) < med+1.45*np.sqrt(var)) & (np.log2(value)>med-1.45*np.sqrt(var))]

# x1=np.linspace(0,genomeLen-1,len(y1))

# piecewiseModel=Model(piecewiseLinear)
# piecewiseModel.set_param_hint('Ol',     value=0.3*genomeLen,vary=True,min=0,max=genomeLen)
# piecewiseModel.set_param_hint('Tl',     value=0.6*genomeLen,vary=True,min=0,max=genomeLen)
# piecewiseModel.set_param_hint('Tc',     value = np.median(np.log2(y1)), vary=True)
# piecewiseModel.set_param_hint('Oc',     value = np.median(np.log2(y1)), vary=True)
Exemplo n.º 19
0
def make_twoDgaussian_model(self, prefix=None):
    """ Creates a model of the 2D gaussian function.

    @param str prefix: optional, if multiple models should be used in a
                       composite way and the parameters of each model should be
                       distinguished from each other to prevent name collisions.

    @return tuple: (object model, object params), for more description see in
                   the method make_gaussianwithoutoffset_model.

    """

    def twoDgaussian_function(x, amplitude, center_x, center_y, sigma_x, sigma_y,
                              theta, offset):
        """ Provide a two dimensional gaussian function.

        @param float amplitude: Amplitude of gaussian
        @param float center_x: x value of maximum
        @param float center_y: y value of maximum
        @param float sigma_x: standard deviation in x direction
        @param float sigma_y: standard deviation in y direction
        @param float theta: angle for eliptical gaussians
        @param float offset: offset

        @return callable function: returns the reference to the function

        Function taken from:
        http://stackoverflow.com/questions/21566379/fitting-a-2d-gaussian-function-using-scipy-optimize-curve-fit-valueerror-and-m/21566831

        Question from: http://stackoverflow.com/users/2097737/bland
                       http://stackoverflow.com/users/3273102/kokomoking
                       http://stackoverflow.com/users/2767207/jojodmo
        Answer: http://stackoverflow.com/users/1461210/ali-m
                http://stackoverflow.com/users/5234/mrjrdnthms
        """

        # FIXME: x_data_tuple: dimension of arrays
        # @param np.arra[k][M] x_data_tuple: array which is (k,M)-shaped,
        #                                   x and y values

        (u, v) = x
        center_x = float(center_x)
        center_y = float(center_y)

        a = (np.cos(theta) ** 2) / (2 * sigma_x ** 2) \
            + (np.sin(theta) ** 2) / (2 * sigma_y ** 2)
        b = -(np.sin(2 * theta)) / (4 * sigma_x ** 2) \
            + (np.sin(2 * theta)) / (4 * sigma_y ** 2)
        c = (np.sin(theta) ** 2) / (2 * sigma_x ** 2) \
            + (np.cos(theta) ** 2) / (2 * sigma_y ** 2)
        g = offset + amplitude * np.exp(- (a * ((u - center_x) ** 2)
                                           + 2 * b * (u - center_x) * (v - center_y)
                                           + c * ((v - center_y) ** 2)))
        return g.ravel()

    if not isinstance(prefix, str) and prefix is not None:
        self.log.error('The passed prefix <{0}> of type {1} is not a string and'
                     'cannot be used as a prefix and will be ignored for now.'
                     'Correct that!'.format(prefix, type(prefix)))
        gaussian_2d_model = Model(twoDgaussian_function, independent_vars='x')
    else:
        gaussian_2d_model = Model(twoDgaussian_function, independent_vars='x',
                               prefix=prefix)

    params = gaussian_2d_model.make_params()

    return gaussian_2d_model, params
Exemplo n.º 20
0
        fit_model.set_param_hint(f'{lineLabel}_cont_intercept', **{
            'value': obsLm.n_cont,
            'vary': False
        })

        fit_model += Model(gaussian_model, prefix=f'{lineLabel}_')
        fit_model.set_param_hint(f'{lineLabel}_amplitude',
                                 value=obsLm.peak_flux - obsLm.cont)
        fit_model.set_param_hint(f'{lineLabel}_center', value=obsLm.peak_wave)
        fit_model.set_param_hint(f'{lineLabel}_sigma', value=1.0)

        x_array = wave[idcsEmis + idcsCont]
        y_array = flux_voxel_norm[idcsEmis + idcsCont]
        w_array = 1.0 / np.sqrt(err_voxel_norm[idcsEmis + idcsCont])

        fit_params = fit_model.make_params()
        obs_fit_output = fit_model.fit(y_array,
                                       fit_params,
                                       x=x_array,
                                       weights=w_array)

        amp = obs_fit_output.params[f"{lineLabel}_amplitude"].value
        mu = obs_fit_output.params[f"{lineLabel}_center"].value
        sigma = obs_fit_output.params[f"{lineLabel}_sigma"].value

        vr = c_KMpS * (mu - obsLm.peak_wave) / obsLm.peak_wave
        sigma_vel = c_KMpS * sigma / obsLm.peak_wave

        # print(f'intg flux ({obsLm.intg_flux:.3e}); intg err ({obsLm.intg_err:.3e})')
        output_message = f'Observed frame: amp ({amp:0.2f}); mu ({mu:0.2f}); sigma ({sigma:0.2f}); vr ({vr:0.2f});  sigma_vel ({sigma_vel:0.2f})'
        print(output_message)
        return (G) * (field + Hintrinsic)

    def Ultrathin110(field, G, K2, K4, Ms):
        return (G * ((field - ((2 * K4) / Ms)) *
                     (field + 4 * math.pi * Ms - ((2 * K2) / Ms) +
                      ((2 * K4) / Ms)))**0.5)

    if Anisotropy == "IP":
        Kit = Model(KittelIP)

        ntira = 0  # numero de pontos a tirar

        newfields = fields[ntira:]
        newpeak1 = peak[ntira:]

        paramK = Kit.make_params()

        paramK.add("Hintrinsic", value=Hintrinsic)
        paramK.add("G", value=G, min=2.8e6, max=3.1e6)

        Kittelfit = Kit.fit(newpeak1, paramK, field=newfields)
        print(Kittelfit.fit_report())

    elif Anisotropy == "OP":
        Kit = Model(KittelOP)

        ntira = 0  # numero de pontos a tirar

        newfields = fields[ntira:]
        newpeak1 = peak[ntira:]
Exemplo n.º 22
0
# In[5]:


def piecewise_linear(x, x0, y0, k1, k2):
    return np.piecewise(
        x, [x < x0],
        [lambda x: k1 * x + y0 - k1 * x0, lambda x: k2 * x + y0 - k2 * x0])


# In[76]:

pw_model = Model(piecewise_linear)

# In[80]:

params = pw_model.make_params(x0=0, y0=0, k1=0, k2=20)
result = pw_model.fit(utilities, params, x=spark_prices)

# In[83]:

result.plot()

# In[ ]:

# In[44]:

spark_prices = [
    36.35220398990176, 89.98482239433874, 146.14866925335906,
    -73.8559862365699, 160.14420624907902, -57.65810297566061,
    69.08052052522773, -4.23425618441687, 98.50112774509203,
    178.35005457778897, -67.19126847923756, 141.95178064460342,