Exemple #1
0
def das(tup,  x0, from_t=0.4, uniform_fil=None, plot_result=True, fit_kws=None):
    out = namedtuple('das_result', field_names=[
                     'fitter', 'result', 'minimizer'])

    ti = dv.make_fi(tup.t)
    if uniform_fil is not None:
        tupf = filter.uniform_filter(tup, uniform_fil)
    else:
        tupf = tup
    if fit_kws is None:
        fit_kws = {}
    import numpy as np
    #ct = dv.tup(np.hstack((wl, wl)), tup.t[ti(t0):],  np.hstack((pa[ti(t0):, :], se[ti(t0):, :])))
    ct = dv.tup(tup.wl, tup.t[ti(from_t):], tupf.data[ti(from_t):, :])
    f = fitter.Fitter(ct, model_coh=0, model_disp=0)
    f.lsq_method = 'ridge'
    kws = dict(full_model=0, lower_bound=0.2, fixed_names=['w'])
    kws.update(fit_kws)
    lm = f.start_lmfit(x0, **kws)
    res = lm.leastsq()
    import lmfit
    lmfit.report_fit(res)
    if plot_result:
        plt.figure(figsize=(4, 7))
        plt.subplot(211)
        if is_montone(f.wl):
            monotone = False
            # Assume wl is repeated
            N = len(f.wl)
        else:
            monotone = True
            N = len(f.wl) // 2
        print(N)
        l = plt.plot(f.wl[:N], f.c[:N, :], lw=3)
        if monotone:
            l2 = plt.plot(f.wl[:N], f.c[N:, :], lw=1)
            for i, j in zip(l, l2):
                j.set_color(i.get_color())
        plot_helpers.lbl_spec()
        lbls = ['%.1f' % i for i in f.last_para[1:-1]] + ['const']
        plt.legend(lbls)

        plt.subplot(212)

        wi = dv.make_fi(tup.wl)
        for i in range(N)[::6]:
            l, = plt.plot(tup.t, tupf.data[:, i], '-o', lw=0.7,
                          alpha=0.5, label='%.1f cm-1' % f.wl[i], mec='None', ms=3)
            plt.plot(f.t, f.model[:, i], lw=3, c=l.get_color())

            if monotone:
                l, = plt.plot(tup.t, tupf.data[:, i+N], '-o', lw=0.7,
                              alpha=0.5, label='%.1f cm-1' % f.wl[i], mec='None', ms=3)
                plt.plot(f.t, f.model[:, i+N], lw=3, c=l.get_color())
        plt.xlim(-1)
        plt.xscale('symlog', linthreshx=1, linscalex=0.5)
        plot_helpers.lbl_trans()
        plt.legend(loc='best')

    return out(f, res, lm)
Exemple #2
0
 def show_widget(self):
     fname = QFileDialog.getOpenFileName()
     a = np.loadtxt(fname)
     w = a[0, 1:]
     t = a[1:, 0]
     d = a[1:, 1:]
     self.tup = tup(w, t, d)  
Exemple #3
0
def make_report(fitter, info, raw=None, plot_fastest=1, make_ltm=False):

    from skultrafast import zero_finding, dv, plot_funcs

    g = fitter
    name = info.get('name', '')
    solvent = info.get('solvent', '')
    excitation = info.get('excitation', '')
    add_info = info.get('add_info', '')
    title = u"{} in {} excited at {}. {}".format(name, solvent, excitation,
                                                 add_info)
    plot_funcs.a4_overview(g,
                           'pics\\' + title + '.png',
                           title=title,
                           plot_fastest=plot_fastest)

    save_txt_das(name + '_-DAS.txt', g)
    save_txt(name + '_ex' + excitation + '_iso.txt', g.wl, g.t, g.data)
    save_txt(name + '_ex' + excitation + '_iso_fit.txt', g.wl, g.t, g.model)

    dat = zero_finding.interpol(dv.tup(fitter.wl, fitter.t, fitter.data),
                                fitter.tn, 0.0)
    save_txt(name + '_ex' + excitation + '_iso_timecor.txt', *dat)
    if make_ltm:
        plot_funcs.plot_ltm_page(dat, 'pics\\' + title + 'lft_map.png')

    fit = zero_finding.interpol(dv.tup(fitter.wl, fitter.t, fitter.model),
                                fitter.tn, 0.0)
    save_txt(name + '_ex' + excitation + '_iso_fit_timecor.txt', *fit)

    if raw:
        save_txt(name + '_ex' + excitation + '_raw.txt', *raw)

    if hasattr(fitter, 'data_perp'):
        perp = zero_finding.interpol(
            dv.tup(fitter.wl, fitter.t, fitter.data_perp), fitter.tn, 0.0)

        para = zero_finding.interpol(
            dv.tup(fitter.wl, fitter.t, fitter.data_para), fitter.tn, 0.0)

        #plot_funcs.a4_overview_second_page(fitter, para, perp, 'bla.png')
        save_txt(name + '_ex' + excitation + '_para.txt', *para)
        save_txt(name + '_ex' + excitation + '_perp.txt', *perp)
    import matplotlib.pyplot as plt
    plt.close('all')
Exemple #4
0
def interpol(tup, tn, shift=0., new_t=None):
    """
    Uses linear interpolation to shift each channcel by given tn.
    """
    dat = tup.data
    t = tup.t
    if new_t is None:
        new_t = t

    #t_array = np.tile(t.reshape(t.size, 1), (1, dat.shape[1]))
    t_array = t[:, None] - tn[None, :]
    t_array -= shift
    dat_new = np.zeros((new_t.size, dat.shape[1]))
    for i in range(dat.shape[1]):
        dat_new[:, i] = np.interp(new_t, t_array[:, i], dat[:, i], left=0)
    return dv.tup(tup.wl, t, dat_new)
Exemple #5
0
    def interpolate_disp(self, polyfunc) -> 'TimeResSpec':
        """
        Correct for dispersion by linear interpolation .

        Parameters
        ----------
        polyfunc : function
            Function which takes wavenumbers and returns time-zeros.

        Returns
        -------
        TimeResSpec
            New TimeResSpec where the data is interpolated so that all channels
            have the same delay point.
        """
        c = self.copy()
        zeros = polyfunc(self.wavenumbers)
        ntc = zero_finding.interpol(self, zeros)
        tmp_tup = dv.tup(self.wavelengths, self.t, self.data)
        ntc_err = zero_finding.interpol(tmp_tup, zeros)
        c.data = ntc.data
        c.err = ntc_err.data
        return c
Exemple #6
0
    def interpolate_disp(self, polyfunc) -> "TimeResSpec":
        """
        Correct for dispersion by linear interpolation .

        Parameters
        ----------
        polyfunc : function
            Function which takes wavenumbers and returns time-zeros.

        Returns
        -------
        TimeResSpec
            New TimeResSpec where the data is interpolated so that all channels
            have the same delay point.
        """
        c = self.copy()
        zeros = polyfunc(self.wavenumbers)
        ntc = zero_finding.interpol(self, zeros)
        tmp_tup = dv.tup(self.wavelengths, self.t, self.data)
        ntc_err = zero_finding.interpol(tmp_tup, zeros)
        c.data = ntc.data
        c.err = ntc_err.data
        return c
Exemple #7
0
def das(tup, x0, from_t=0.4, uniform_fil=None, plot_result=True, fit_kws=None):
    out = namedtuple('das_result',
                     field_names=['fitter', 'result', 'minimizer'])

    ti = dv.make_fi(tup.t)
    if uniform_fil is not None:
        tupf = filter.uniform_filter(tup, uniform_fil)
    else:
        tupf = tup
    if fit_kws is None:
        fit_kws = {}

    #ct = dv.tup(np.hstack((wl, wl)), tup.t[ti(t0):],  np.hstack((pa[ti(t0):, :], se[ti(t0):, :])))
    ct = dv.tup(tup.wl, tup.t[ti(from_t):], tupf.data[ti(from_t):, :])
    f = fitter.Fitter(ct, model_coh=0, model_disp=0)
    f.lsq_method = 'ridge'
    kws = dict(full_model=0, lower_bound=0.2, fixed_names=['w'])
    kws.update(fit_kws)
    lm = f.start_lmfit(x0, **kws)
    res = lm.leastsq()
    import lmfit
    lmfit.report_fit(res)
    if plot_result:
        plt.figure(figsize=(4, 7))
        plt.subplot(211)
        if is_montone(f.wl):
            monotone = False
            # Assume wl is repeated
            N = len(f.wl)
        else:
            monotone = True
            N = len(f.wl) // 2
        print(N)
        l = plt.plot(f.wl[:N], f.c[:N, :], lw=3)
        if monotone:
            l2 = plt.plot(f.wl[:N], f.c[N:, :], lw=1)
            for i, j in zip(l, l2):
                j.set_color(i.get_color())
        plot_helpers.lbl_spec()
        lbls = ['%.1f' % i for i in f.last_para[1:-1]] + ['const']
        plt.legend(lbls)

        plt.subplot(212)

        wi = dv.make_fi(tup.wl)
        for i in range(N)[::6]:
            l, = plt.plot(tup.t,
                          tupf.data[:, i],
                          '-o',
                          lw=0.7,
                          alpha=0.5,
                          label='%.1f cm-1' % f.wl[i],
                          mec='None',
                          ms=3)
            plt.plot(f.t, f.model[:, i], lw=3, c=l.get_color())

            if monotone:
                l, = plt.plot(tup.t,
                              tupf.data[:, i + N],
                              '-o',
                              lw=0.7,
                              alpha=0.5,
                              label='%.1f cm-1' % f.wl[i],
                              mec='None',
                              ms=3)
                plt.plot(f.t, f.model[:, i + N], lw=3, c=l.get_color())
        plt.xlim(-1)
        plt.xscale('symlog', linthreshx=1, linscalex=0.5)
        plot_helpers.lbl_trans()
        plt.legend(loc='best')

    return out(f, res, lm)
Exemple #8
0
def plot_diff(tup, t0, t_list, **kwargs):
    diff = tup.data - tup.data[dv.fi(tup.t, t0), :]
    plot_spec(dv.tup(tup.wl, tup.t, diff), t_list, **kwargs)
Exemple #9
0
def mean_tup(tup, time):
    wl, t, d = tup.wl, tup.t, tup.data
    new_dat = tup.data / tup.data[dv.fi(t, time), :]
    return dv.tup(wl, t, new_dat)
Exemple #10
0
    def fit_exp(self,
                x0,
                fix_sigma=True,
                fix_t0=False,
                fix_last_decay=True,
                from_t=None,
                model_coh=True,
                lower_bound=0.1):
        """
        Fit a sum of exponentials to the dataset. This function assumes
        the two datasets is already corrected for dispersion.

        Parameters
        ----------
        x0 : list of floats or array
            Starting values of the fit. The first value is the estimate of the
            system response time omega. If `fit_t0` is true, the second float is
            the guess of the time-zero. All other floats are interpreted as the
            guessing values for exponential decays.
        fix_sigma : bool (optional)
            If to fix the IRF duration sigma.
        fix_t0 : bool (optional)
            If to fix the the time-zero.
        fix_last_decay : bool (optional)
            Fixes the value of the last tau of the initial guess. It can be
            used to add a constant by setting the last tau to a large value
            and fix it.
        from_t : float or None
            If not None, data with t<from_t will be ignored for the fit.
        model_coh : bool (optional)
            If coherent contributions should by modeled. If `True` a gaussian
            with a width equal the system response time and its derivatives are
            added to the linear model.
        lower_bound : float (optional)
            Lower bound for decay-constants.
        """
        pa, pe = self.para, self.perp
        if not from_t is None:
            pa = pa.cut_times([(-np.inf, from_t)])
            pe = pe.cut_times([(-np.inf, from_t)])
        all_data = np.hstack((pa.data, pe.data))
        all_wls = np.hstack((pa.wavelengths, pe.wavelengths))
        all_tup = dv.tup(all_wls, pa.t, all_data)

        f = fitter.Fitter(all_tup, model_coh=model_coh, model_disp=1)
        f.res(x0)
        fixed_names = []
        if fix_sigma:
            fixed_names.append('w')

        lm_model = f.start_lmfit(x0,
                                 fix_long=fix_last_decay,
                                 fix_disp=fix_t0,
                                 lower_bound=lower_bound,
                                 full_model=False,
                                 fixed_names=fixed_names)
        ridge_alpha = abs(all_data).max() * 1e-4
        f.lsq_method = 'ridge'
        fitter.alpha = ridge_alpha
        result = lm_model.leastsq()

        self.fit_exp_result_ = FitExpResult(lm_model, result, f)
        return self.fit_exp_result_
Exemple #11
0
    def fit_exp(
        self,
        x0,
        fix_sigma=True,
        fix_t0=False,
        fix_last_decay=True,
        from_t=None,
        model_coh=True,
        lower_bound=0.1,
    ):
        """
        Fit a sum of exponentials to the dataset. This function assumes
        the two datasets is already corrected for dispersion.

        Parameters
        ----------
        x0 : list of floats or array
            Starting values of the fit. The first value is the estimate of the
            system response time omega. If `fit_t0` is true, the second float is
            the guess of the time-zero. All other floats are interpreted as the
            guessing values for exponential decays.
        fix_sigma : bool (optional)
            If to fix the IRF duration sigma.
        fix_t0 : bool (optional)
            If to fix the the time-zero.
        fix_last_decay : bool (optional)
            Fixes the value of the last tau of the initial guess. It can be
            used to add a constant by setting the last tau to a large value
            and fix it.
        from_t : float or None
            If not None, data with t<from_t will be ignored for the fit.
        model_coh : bool (optional)
            If coherent contributions should by modeled. If `True` a gaussian
            with a width equal the system response time and its derivatives are
            added to the linear model.
        lower_bound : float (optional)
            Lower bound for decay-constants.
        """
        pa, pe = self.para, self.perp
        if not from_t is None:
            pa = pa.cut_times([(-np.inf, from_t)])
            pe = pe.cut_times([(-np.inf, from_t)])
        all_data = np.hstack((pa.data, pe.data))
        all_wls = np.hstack((pa.wavelengths, pe.wavelengths))
        all_tup = dv.tup(all_wls, pa.t, all_data)

        f = fitter.Fitter(all_tup, model_coh=model_coh, model_disp=1)
        f.res(x0)
        fixed_names = []
        if fix_sigma:
            fixed_names.append("w")

        lm_model = f.start_lmfit(
            x0,
            fix_long=fix_last_decay,
            fix_disp=fix_t0,
            lower_bound=lower_bound,
            full_model=False,
            fixed_names=fixed_names,
        )
        ridge_alpha = abs(all_data).max() * 1e-4
        f.lsq_method = "ridge"
        fitter.alpha = ridge_alpha
        result = lm_model.leastsq()

        self.fit_exp_result_ = FitExpResult(lm_model, result, f)
        return self.fit_exp_result_
    raw_tn = tup.t[idx]
    no_nan = ~np.any(np.isnan(tup.data), 0)
    fit, p = robust_fit_tz(tup.wl[no_nan], raw_tn[no_nan], deg)
    #dv.subtract_background(tup.data, tup.t, fit, 400)
    fit = np.polyval(p, tup.wl)
    cor = interpol(tup, fit)
    if plot:
        from . import plot_funcs as pl
        pl._plot_zero_finding(tup, raw_tn, fit, cor)
    return cor, fit

if __name__ == '__main__':
    a = np.load('SD5039.npz')
    w, t, d = a['arr_0']
    d -= d[:10,:].mean(0)
    d = d[:,20:]
    w = w[20:]
    t = t
    nt, tn = get_tz_cor(dv.tup(w, t, d), use_max)
    n = 5
    figure(0)
    k, j = use_fit(d[:, ::n], t, tn=tn[::n], n=100)
    figure(1)
    pcolormesh(w, t, d)
    plot(w[::n], k[::])
    plot(w[::n], tn[::n])
    ylim(2, 5)
    xlim(w.min(), w.max())


Exemple #13
0
def plot_diff(tup, t0, t_list, **kwargs):
    diff = tup.data - tup.data[dv.fi(tup.t, t0), :]
    plot_spec(dv.tup(tup.wl, tup.t, diff), t_list, **kwargs)
Exemple #14
0
def mean_tup(tup, time):
    wl, t, d = tup.wl, tup.t, tup.data
    new_dat = tup.data /  tup.data[dv.fi(t, time), :]
    return dv.tup(wl, t, new_dat)