Пример #1
0
def save_plot(**kwargs):
    """
        save plot
    """
    if 'logy' in kwargs and kwargs['logy']:
        plt.gca().set_yscale('log')
    if 'logx' in kwargs and kwargs['logx']:
        plt.gca().set_xscale('log')
    if 'tight' in kwargs and kwargs['tight']:
        plt.tight_layout()
    if 'lpos' in kwargs and kwargs['lpos'] >= 0:
        if(util.has('bbox_to_anchor', kwargs)):
            if(util.has('ncol', kwargs)):
                plt.legend(loc=kwargs['lpos'], bbox_to_anchor=kwargs['bbox_to_anchor'],
                           ncol=kwargs['ncol'], borderaxespad=0)
            else:
                plt.legend(loc=kwargs['lpos'],
                           bbox_to_anchor=kwargs['bbox_to_anchor'])
        else:
            plt.legend(loc=kwargs['lpos'])
    # plt.gca().set_xlim([kwargs['xmin'],kwargs['xmax']])
    # plt.gca().set_ylim([kwargs['ymin'],kwargs['ymax']])
    if 'save' in kwargs and not kwargs['save'] == None:
        io.mkdirs(kwargs['save'])
        plt.savefig(kwargs['save'] + ".pdf")
    plt.grid(b=kwargs["grid"])
    if 'show' in kwargs and kwargs['show']:
        show(**kwargs)
Пример #2
0
def data_split(datax, datay, **kwargs):
    """
    Split data + errors
    """
    if kwargs['bins'] > 0:
        N, bins = np.histogram(unv(datax), bins=kwargs['bins'])
        y = kwargs['binunc'](N)
        yerr = usd(y)
        yerr = yerr if np.any(np.abs(yerr) > 0) else None
        return bins[0:-1] - (bins[0] - bins[1]) / 2, unv(y), None, yerr
    if util.has("sortbyx", kwargs) and kwargs['sortbyx']:
        ind = np.argsort(unv(datax))
    else:
        ind = np.array(range(len(datax)))
    x = unv(datax)[ind]
    y = unv(datay)[ind]
    xerr = usd(datax)[ind]
    yerr = usd(datay)[ind]
    xerr = xerr if np.any(np.abs(xerr) > 0) else None
    yerr = yerr if np.any(np.abs(yerr) > 0) else None
    if util.has("xerror", kwargs) and not kwargs['xerror']:
        xerr = None
    if util.has("yerror", kwargs) and not kwargs['yerror']:
        yerr = None
    return x, y, xerr, yerr
Пример #3
0
def function(func, *args, **kwargs):
    """
    Plot function ``func`` between ``xmin`` and ``xmax``

    Parameters
    ----------
    func : function
        Function to be plotted between ``xmin`` and ``xmax``, only taking `array_like` ``x`` as parameter
    *args : optional
        arguments for ``func``
    **kwargs : optional
        see :func:`plot_kwargs`.
    """
    if not util.has("xmin", kwargs) or not util.has("xmin", kwargs):
        raise Exception("xmin or xmax missing.")

    # if not util.has('lpos', kwargs) and not util.has('label', kwargs):
    #    kwargs['lpos'] = -1
    if not util.has('fmt', kwargs):
        kwargs['fmt'] = "-"

    kwargs = plot_kwargs(kwargs)
    xlin = np.linspace(kwargs['xmin'], kwargs['xmax'], kwargs['steps'])
    init_plot(**kwargs)

    if not util.has("label", kwargs) or kwargs['label'] is None:
        kwargs['label'] = get_fnc_legend(func, args, **kwargs)
        # kwargs['lpos'] = 0
    #_plot(xfit, func(xfit, *args), **kwargs)
    _function(wrap.get_lambda_argd(
        func, kwargs['xvar'], *args), xlin, **kwargs)
    if kwargs['ss']:
        save_plot(**kwargs)
Пример #4
0
def _function(func, xfit, **kwargs):
    kargs = {}
    if util.has('fmt', kwargs):
        kargs["fmt"] = kwargs["fmt"]
    if util.has('label', kwargs) and kwargs['label'] != "":
        kargs['label'] = kwargs['label']
    if util.has('color', kwargs) and kwargs['color'] != "":
        kargs['color'] = kwargs['color']
    if util.has('sigmas', kwargs) and kwargs['sigmas'] != "":
        kargs['sigmas'] = kwargs['sigmas']
    __function(func, xfit, **kargs)
Пример #5
0
def _data_split(datax, datay, **kwargs):
    if util.has('fselector', kwargs):
        sel = kwargs['fselector']
        if callable(sel):
            return data_split(datax[sel(datax, datay)],
                              datay[sel(datax, datay)], **kwargs)
        else:
            return data_split(datax[sel], datay[sel], **kwargs)
    return data_split(datax, datay, **kwargs)
Пример #6
0
def init_plot(**kwargs):
    fig = None
    if util.has("axes", kwargs) and kwargs["axes"] is not None:
        plt.sca(kwargs["axes"])
        fig = kwargs["axes"].get_figure()
    if kwargs['init'] or util.true("residue", kwargs):
        if kwargs['size'] is None:
            fig = plt.figure()
        else:
            fig = plt.figure(figsize=kwargs['size'])
        if kwargs['residue']:
            fig.add_axes((.1, .3, .8, .6))
    if util.has("xlabel", kwargs) and kwargs['xlabel'] != "":
        plt.xlabel(kwargs['xlabel'])
    if util.has("ylabel", kwargs) and kwargs['ylabel'] != "":
        plt.ylabel(kwargs['ylabel'])
    if util.has("xaxis", kwargs) and kwargs['xaxis'] != "":
        plt.xlabel(kwargs['xaxis'])
    if util.has("yaxis", kwargs) and kwargs['yaxis'] != "":
        plt.ylabel(kwargs['yaxis'])
    return fig
Пример #7
0
    def tmp(*x):
        tmp_x = []
        j = 1
        # print(x)
        for i in range(1, Ntot + 1):
            # print(i," ",j)
            if not util.has(i, fixed):
                tmp_x += [x[j]]
                # print(x[j])
                j = j + 1
            else:
                tmp_x += [fixed[i]]

        # print(Ntot)
        # print(tmp_x)
        return unv(wrap.get_lambda(function, kwargs['xvar'])(x[0], *tmp_x))
Пример #8
0
def fit_split(datax, datay, **kwargs):
    """
    Splits datax and datay into (x,y,xerr,yerr).

    Parameters
    ----------
    **kwargs : optional
        see :func:`fit_kwargs`.
    """
    kwargs = fit_kwargs(kwargs)
    x, y, xerr, yerr = _data_split(datax, datay, **kwargs)
    if util.has('frange', kwargs):
        x = x[kwargs['frange'][0]:kwargs['frange'][1]]
        y = y[kwargs['frange'][0]:kwargs['frange'][1]]
        if not yerr is None:
            yerr = yerr[kwargs['frange'][0]:kwargs['frange'][1]]
        if not xerr is None:
            xerr = xerr[kwargs['frange'][0]:kwargs['frange'][1]]

    return x, y, xerr, yerr
Пример #9
0
def plt_fit(datax, datay, gfunction, **kwargs):
    """
    Plot Fit
    """
    func = wrap.get_lambda(gfunction, kwargs['xvar'])
    fit = _fit(datax, datay, gfunction, **kwargs)
    def fitted(x): return func(x, *fit)
    l = get_fnc_legend(gfunction, fit, **kwargs)
    if kwargs['prange'] is None:
        x, _, _, _ = ffit.fit_split(datax, datay, **kwargs)
        xfit = np.linspace(np.min(unv(x)), np.max(unv(x)), 1000)
    else:
        xfit = np.linspace(kwargs['prange'][0], kwargs['prange'][1], 1000)
    ll = __function(fitted, xfit, "-", label=l,
                    color=kwargs['fit_color'], sigmas=kwargs['sigmas'])

    if (kwargs['frange'] is not None or kwargs['fselector'] is not None) and util.true('interpolate', kwargs) or util.has("interpolate_max", kwargs) or util.has("interpolate_min", kwargs):
        xxfit = np.linspace(util.get("interpolate_min", kwargs, np.min(
            unv(datax))), util.get("interpolate_max", kwargs, np.max(unv(datax))))
        __function(fitted, np.linspace(np.min(xxfit), np.min(xfit)), "--",
                   color=ll.get_color(), hatch=util.get("interpolate_hatch", kwargs, r"||"), sigmas=kwargs['sigmas'])
        __function(fitted, np.linspace(np.max(xfit), np.max(xxfit)), "--",
                   color=ll.get_color(), hatch=util.get("interpolate_hatch", kwargs, r"||"), sigmas=kwargs['sigmas'])
    return fit, ll.get_color()
Пример #10
0
def fit(datax, datay, function, **kwargs):
    """
    Returns a fit of ``function`` to ``datax`` and ``datay``.

    Parameters
    ----------
    datax : array_like
        X data either as ``unp.uarray`` or ``np.array`` or ``list``
    datay : array_like
        Y data either as ``unp.uarray`` or ``np.array`` or ``list``
    function : func
        Fit function with parameters: ``x``, ``params``
    **kwargs : optional
        see :func:`fit_kwargs`.

    """
    kwargs = fit_kwargs(kwargs)
    x, y, xerr, yerr = fit_split(datax, datay, **kwargs)
    params = None
    if util.has('params', kwargs):
        params = kwargs['params']

    fixed = {}
    vnames = wrap.get_varnames(function, kwargs['xvar'])
    Ntot = len(vnames) - 1
    if util.has("fixed_params", kwargs) and kwargs['fixed_params']:
        for i in range(1, len(vnames)):
            if util.has(vnames[i], kwargs):
                fixed[i] = kwargs[vnames[i]]
    # Count parameters for function
    if params is None:
        N = len(vnames)
        params = [1 for i in range(N - 1)]
    tmp_params = []
    for i, pi in enumerate(params):
        if not util.has(i + 1, fixed):
            tmp_params += [pi]
    params = tmp_params
    N = len(params)

    def tmp(*x):
        tmp_x = []
        j = 1
        # print(x)
        for i in range(1, Ntot + 1):
            # print(i," ",j)
            if not util.has(i, fixed):
                tmp_x += [x[j]]
                # print(x[j])
                j = j + 1
            else:
                tmp_x += [fixed[i]]

        # print(Ntot)
        # print(tmp_x)
        return unv(wrap.get_lambda(function, kwargs['xvar'])(x[0], *tmp_x))

    if xerr is not None:
        fit = _fit_odr(x, y, tmp, params=params, xerr=xerr, yerr=yerr)
    else:
        fit = _fit_curvefit(x, y, tmp, params=params, yerr=yerr)

    rfit = []
    j = 0
    for i in range(1, Ntot + 1):
        if not util.has(i, fixed):
            rfit += [fit[j]]
            j = j + 1
        else:
            rfit += [fixed[i]]

    return rfit