Exemplo n.º 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)
Exemplo n.º 2
0
def plot_freqs(tup, wl, from_t, to_t, taus=[1]):
    ti = dv.make_fi(tup.t)
    wi = dv.make_fi(tup.wl)
    tl = tup.t[ti(from_t):ti(to_t)]
    trans = tup.data[ti(from_t):ti(to_t), wi(wl)]

    #ax1 = plt.subplot(311)
    #ax1.plot(tl, trans)
    dt = dv.exp_detrend(trans, tl, taus)

    #ax1.plot(tl, -dt+trans)
    #ax2 = plt.subplot(312)
    ax3 = plt.subplot(111)

    f = abs(np.fft.fft(np.kaiser(2 * dt.size, 2) * dt, dt.size * 2))**2
    freqs = np.fft.fftfreq(dt.size * 2, tup.t[ti(from_t) + 1] - tup.t[ti(from_t)])
    n = freqs.size // 2
    ax3.plot(dv.fs2cm(1000 / freqs[1:n]), f[1:n])
    ax3.set_xlabel('freq / cm$^{-1}$')
    return dv.fs2cm(1000 / freqs[1:n]), f[1:n]
Exemplo n.º 3
0
def plot_freqs(tup, wl, from_t, to_t, taus=[1]):
    ti = dv.make_fi(tup.t)
    wi = dv.make_fi(tup.wl)
    tl = tup.t[ti(from_t):ti(to_t)]
    trans = tup.data[ti(from_t):ti(to_t), wi(wl)]

    #ax1 = plt.subplot(311)
    #ax1.plot(tl, trans)
    dt = dv.exp_detrend(trans, tl, taus)

    #ax1.plot(tl, -dt+trans)
    #ax2 = plt.subplot(312)
    ax3 = plt.subplot(111)

    f = abs(np.fft.fft(np.kaiser(2*dt.size, 2)*dt, dt.size*2))**2
    freqs = np.fft.fftfreq(dt.size*2, tup.t[ti(from_t)+1]-tup.t[ti(from_t)])
    n = freqs.size//2
    ax3.plot(dv.fs2cm(1000/freqs[1:n]), f[1:n])
    ax3.set_xlabel('freq / cm$^{-1}$')
    return dv.fs2cm(1000/freqs[1:n]), f[1:n]
Exemplo n.º 4
0
    def __init__(
            self,
            fname,
            invert_data=False,
            is_pol_resolved=False,
            pol_first_scan="unknown",
            valid_channel=None,
    ):
        """Class for working with data files from MessPy v1.

        Parameters
        ----------
        fname : str
            Filename to open.
        invert_data : bool (optional)
            If True, invert the sign of the data. `False` by default.
        is_pol_resolved : bool (optional)
            If the dataset was recorded polarization resolved.
        pol_first_scan : {'magic', 'para', 'perp', 'unknown'}
            Polarization between the pump and the probe in the first scan. If
            `valid_channel` is 'both', this corresponds to the zeroth channel.
        valid_channel : `0`, `1`, 'both'
            Indicates which channels contains a real signal. For recently
            recorded data, it is 0 for the visible setup and 1 for the IR
            setup. Older IR data uses both. If `None` it guesses the valid
            channel from the data, assuming recent data.
        """

        with np.load(fname) as f:
            self.wl = f["wl"]
            self.initial_wl = self.wl.copy()
            self.t = f["t"] / 1000.0
            self.data = f["data"]
            if invert_data:
                self.data *= -1

        self.wavenumbers = 1e7 / self.wl
        self.pol_first_scan = pol_first_scan
        self.is_pol_resolved = is_pol_resolved
        if valid_channel is not None:
            self.valid_channel = valid_channel
        else:
            self.valid_channel = 1 if self.wl.shape[0] > 32 else 0

        self.num_cwl = self.data.shape[0]
        self.plot = MessPyPlotter(self)
        self.t_idx = make_fi(self.t)
Exemplo n.º 5
0
def plot_coef_spec(taus, wl, coefs, div):
    tau_coefs = coefs[:, :len(taus)]
    div.append(taus.max() + 1)
    ti = dv.make_fi(taus)
    last_idx = 0
    non_zeros = ~(coefs.sum(0) == 0)
    for i in div:
        idx = ti(i)
        cur_taus = taus[last_idx:idx]
        cur_nonzeros = non_zeros[last_idx:idx]
        lbl = "%.1f - %.1f ps" % (taus[last_idx], taus[idx])
        plt.plot(wl, tau_coefs[:, last_idx:idx].sum(-1), label=lbl)
        last_idx = ti(i)

    plt.plot(wl, coefs[:, -1])
    plt.legend(title='Decay regions', loc='best')
    lbl_spec()
    plt.title("Spectrum of lft-parts")
Exemplo n.º 6
0
def plot_coef_spec(taus, wl, coefs, div):
    tau_coefs = coefs[:, :len(taus)]
    div.append(taus.max()+1)
    ti = dv.make_fi(taus)
    last_idx = 0
    non_zeros = ~(coefs.sum(0) == 0)
    for i in div:
        idx = ti(i)
        cur_taus = taus[last_idx:idx]
        cur_nonzeros = non_zeros[last_idx:idx]
        lbl = "%.1f - %.1f ps"%(taus[last_idx], taus[idx])
        plt.plot(wl, tau_coefs[:, last_idx:idx].sum(-1), label=lbl)
        last_idx = ti(i)

    plt.plot(wl, coefs[:, -1])
    plt.legend(title='Decay regions', loc='best')
    lbl_spec()
    plt.title("Spectrum of lft-parts")
Exemplo n.º 7
0
    def __init__(self, frequency, signal, unit_freq='nm', unit_signal='OD'):
        """
        Class for working with steady state spectra.

        Parameters
        ----------
        frequency : ndarray
            The frequencies of the spectrum
        signal : ndarray
            Array containing the signal.
        unit_freq : str
            Unit type of the frequencies.
        unit_signal : str
            Unit type of the signal.
        """

        assert (frequency.shape[0] == signal.shape[0])
        idx = np.argsort(frequency)
        self.x = frequency[idx]
        self.y = signal[idx, ...]
        self.unit_freq = unit_freq
        self.unit_signal = unit_signal
        self.back = np.zeros_like(self.x)
        self.fi = dv.make_fi(self.x)
Exemplo n.º 8
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)
Exemplo n.º 9
0
    def __init__(self,
                 wl,
                 t,
                 data,
                 err=None,
                 name=None,
                 freq_unit='nm',
                 disp_freq_unit=None,
                 auto_plot=True):
        """
        Class for working with time-resolved spectra. If offers methods for
        analyzing and pre-processing the data. To visualize the data,
        each `TimeResSpec` object has an instance of an `DataSetPlotter` object
        accessible under `plot`.

        Parameters
        ----------
        wl : array of shape(n)
            Array of the spectral dimension
        t : array of shape(m)
            Array with the delay times.
        data : array of shape(n, m)
            Array with the data for each point.
        err : array of shape(n, m) or None (optional)
            Contains the std err of the data, can be `None`.
        name : str (optional)
            Identifier for data set.
        freq_unit : 'nm' or 'cm' (optional)
            Unit of the wavelength array, default is 'nm'.
        disp_freq_unit : 'nm','cm' or None (optional)
            Unit which is used by default for plotting, masking and cutting
            the dataset. If `None`, it defaults to `freq_unit`.

        Attributes
        ----------
        wavelengths, wavenumbers, t, data : ndarray
            Arrays with the data itself.
        plot : TimeResSpecPlotter
            Helper class which can plot the dataset using `matplotlib`.
        t_idx : function
            Helper function to find the nearest index in t for a given time.
        wl_idx : function
            Helper function to search for the nearest wavelength index for a
            given wavelength.
        wn_idx : function
            Helper function to search for the nearest wavelength index for a
            given wavelength.
        auto_plot : bool
            When True, some function will display their result automatically.
        """

        assert ((t.shape[0], wl.shape[0]) == data.shape)
        t = t.copy()
        wl = wl.copy()
        data = data.copy()

        if freq_unit == 'nm':
            self.wavelengths = wl
            self.wavenumbers = 1e7 / wl
            self.wl = self.wavelengths
        else:
            self.wavelengths = 1e7 / wl
            self.wavenumbers = wl
            self.wl = self.wavenumbers

        self.t = t
        self.data = data
        self.err = err

        if name is not None:
            self.name = name

        # Sort wavelenths and data.
        idx = np.argsort(self.wavelengths)
        self.wavelengths = self.wavelengths[idx]
        self.wavenumbers = self.wavenumbers[idx]
        self.data = self.data[:, idx]
        self.auto_plot = auto_plot
        self.plot = TimeResSpecPlotter(self)
        self.t_idx = dv.make_fi(self.t)
        self.wl_idx = dv.make_fi(self.wavelengths)
        self.wn_idx = dv.make_fi(self.wavenumbers)

        if disp_freq_unit is None:
            self.disp_freq_unit = freq_unit
        else:
            self.disp_freq_unit = disp_freq_unit
        self.plot.freq_unit = self.disp_freq_unit
Exemplo n.º 10
0
    def __init__(
        self,
        wl,
        t,
        data,
        err=None,
        name=None,
        freq_unit="nm",
        disp_freq_unit=None,
        auto_plot=True,
    ):
        """
        Class for working with time-resolved spectra. If offers methods for
        analyzing and pre-processing the data. To visualize the data,
        each `TimeResSpec` object has an instance of an `DataSetPlotter` object
        accessible under `plot`.

        Parameters
        ----------
        wl : array of shape(n)
            Array of the spectral dimension
        t : array of shape(m)
            Array with the delay times.
        data : array of shape(n, m)
            Array with the data for each point.
        err : array of shape(n, m) or None (optional)
            Contains the std err of the data, can be `None`.
        name : str (optional)
            Identifier for data set.
        freq_unit : 'nm' or 'cm' (optional)
            Unit of the wavelength array, default is 'nm'.
        disp_freq_unit : 'nm','cm' or None (optional)
            Unit which is used by default for plotting, masking and cutting
            the dataset. If `None`, it defaults to `freq_unit`.

        Attributes
        ----------
        wavelengths, wavenumbers, t, data : ndarray
            Arrays with the data itself.
        plot : TimeResSpecPlotter
            Helper class which can plot the dataset using `matplotlib`.
        t_idx : function
            Helper function to find the nearest index in t for a given time.
        wl_idx : function
            Helper function to search for the nearest wavelength index for a
            given wavelength.
        wn_idx : function
            Helper function to search for the nearest wavelength index for a
            given wavelength.
        auto_plot : bool
            When True, some function will display their result automatically.
        """

        assert (t.shape[0], wl.shape[0]) == data.shape
        t = t.copy()
        wl = wl.copy()
        data = data.copy()

        if freq_unit == "nm":
            self.wavelengths = wl
            self.wavenumbers = 1e7 / wl
            self.wl = self.wavelengths
        else:
            self.wavelengths = 1e7 / wl
            self.wavenumbers = wl
            self.wl = self.wavenumbers

        self.t = t
        self.data = data
        self.err = err

        if name is not None:
            self.name = name

        # Sort wavelenths and data.
        idx = np.argsort(self.wavelengths)
        self.wavelengths = self.wavelengths[idx]
        self.wavenumbers = self.wavenumbers[idx]
        self.data = self.data[:, idx]
        self.auto_plot = auto_plot
        self.plot = TimeResSpecPlotter(self)
        self.t_idx = dv.make_fi(self.t)
        self.wl_idx = dv.make_fi(self.wavelengths)
        self.wn_idx = dv.make_fi(self.wavenumbers)

        if disp_freq_unit is None:
            self.disp_freq_unit = freq_unit
        else:
            self.disp_freq_unit = disp_freq_unit
        self.plot.freq_unit = self.disp_freq_unit