コード例 #1
0
ファイル: p_lomb_scargle.py プロジェクト: richwu/pandashells
def main():
    msg = textwrap.dedent(
        """
        Computes a spectrogram using the lomb-scargle algorithm provided by
        the gatspy module.  The input time series need not have evenly spaced
        time-stamps.  The FFT-based algorithm has complexity O[N*log(N)].

        -----------------------------------------------------------------------
        Examples:

            * Plot the spectrum of a simple sine wave
                  p.linspace 0 10 100 \\
                  | p.df 'df["value"] = 7 * np.sin(2*np.pi*df.time / 1.5)'\\
                        --names time\\
                  | p.lomb_scargle -t time -y value --interp_exp 3\\
                  | p.plot -x period -y amp --xlim 0 3

            * Show the annual and 59-day peaks in the sealevel spectrum
                p.example_data -d sealevel\\
                | p.df 'df["day"] = 365.25 * df.year'\\
                        'df["day"] = df.day - df.day.iloc[0]'\\
                | p.lomb_scargle -t day -y sealevel_mm --interp_exp 3\\
                | p.df 'df[df.period < 720]'\\
                | p.plot -x period -y amp --xlim 1 400\\
                         --title 'Sea-surface height spectrum'\\
                         --xlabel 'period (days)'

        -----------------------------------------------------------------------
        """
    )

    # read command line arguments
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter, description=msg)

    arg_lib.add_args(parser, 'io_in', 'io_out')

    parser.add_argument('-t', '--time_col', help='Time Column',
                        nargs=1, required=True, type=str)

    parser.add_argument('-y', '--observation_col', help='Observation column',
                        nargs=1, dest='val_col', required=True, type=str)

    parser.add_argument('--interp_exp', help='Interpolate by this power of 2',
                        nargs=1, type=int, default=[1])
    parser.add_argument(
        '--freq_order', action='store_true', dest='freq_order', default=False,
        help='Order output by freqency instead of period')

    # parse arguments
    args = parser.parse_args()

    # get the input dataframe
    df = io_lib.df_from_input(args)
    df = lomb_scargle_lib.lomb_scargle(
        df, args.time_col[0], args.val_col[0], args.interp_exp[0],
        args.freq_order)

    # write dataframe to output
    io_lib.df_to_output(args, df)
コード例 #2
0
 def test_freq_order(self):
     t = np.linspace(0, 10, 256)
     y = 7 * np.sin(2 * np.pi * t)
     df_in = pd.DataFrame({'t': t, 'y': y})
     df = lomb_scargle(df_in, 't', 'y', freq_order=True)
     max_rec = df[df.amp == df.amp.max()].iloc[0]
     self.assertTrue(all([x > 0 for x in df.freq.diff().dropna()]))
     self.assertAlmostEqual(max_rec['amp'], 7, places=0)
     self.assertAlmostEqual(max_rec['power'], 49, places=0)
     self.assertAlmostEqual(max_rec['period'], 1, places=0)
     self.assertAlmostEqual(max_rec['freq'], 1, places=0)
     self.assertEqual(len(df), 256)
コード例 #3
0
    def refine_frequency(self, time, amplitude, simple=False, verbose=False):
        # use lomb-scargle to get initial guess
        dfd = pd.DataFrame(dict(t=time, amp=amplitude))
        dfs = lomb_scargle(dfd, 't', 'amp', interp_exponent=1)
        freq = dfs[dfs.power == dfs.power.max()].freq

        # set up to do do a mininzer fit to best freq
        p = ParamState(
            't',
            'y_true',
            a=1,
            b=1,
            f=self.f0,
        )
        p.given(
            t=time,
            y_true=amplitude
        )

        def model(p):
            return (
                p.a * np.sin(2 * np.pi * p.f * p.t) +
                p.b * np.cos(2 * np.pi * p.f * p.t)
            )

        def cost(args, p):
            p.ingest(args)
            err = model(p) - p.y_true
            energy = np.sum(err ** 2)
            return energy

        x0 = p.array
        xf = fmin_powell(cost, x0, args=(p,), disp=verbose)
        p.ingest(xf)
        if (p.f - self.f0) > 3 ** 2:
            raise ValueError(f'Guess freq: {self.f0}, Fit Freq: {p.f}  too far apart')
        self.f0 = p.f

        return self
コード例 #4
0
def main():
    msg = textwrap.dedent("""
        Computes a spectrogram using the lomb-scargle algorithm provided by
        the gatspy module.  The input time series need not have evenly spaced
        time-stamps.  The FFT-based algorithm has complexity O[N*log(N)].

        -----------------------------------------------------------------------
        Examples:

            * Plot the spectrum of a simple sine wave
                  p.linspace 0 10 100 \\
                  | p.df 'df["value"] = 7 * np.sin(2*np.pi*df.time / 1.5)'\\
                        --names time\\
                  | p.lomb_scargle -t time -y value --interp_exp 3\\
                  | p.plot -x period -y amp --xlim 0 3

            * Show the annual and 59-day peaks in the sealevel spectrum
                p.example_data -d sealevel\\
                | p.df 'df["day"] = 365.25 * df.year'\\
                        'df["day"] = df.day - df.day.iloc[0]'\\
                | p.lomb_scargle -t day -y sealevel_mm --interp_exp 3\\
                | p.df 'df[df.period < 720]'\\
                | p.plot -x period -y amp --xlim 1 400\\
                         --title 'Sea-surface height spectrum'\\
                         --xlabel 'period (days)'

        -----------------------------------------------------------------------
        """)

    # read command line arguments
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter, description=msg)

    arg_lib.add_args(parser, 'io_in', 'io_out')

    parser.add_argument('-t',
                        '--time_col',
                        help='Time Column',
                        nargs=1,
                        required=True,
                        type=str)

    parser.add_argument('-y',
                        '--observation_col',
                        help='Observation column',
                        nargs=1,
                        dest='val_col',
                        required=True,
                        type=str)

    parser.add_argument('--interp_exp',
                        help='Interpolate by this power of 2',
                        nargs=1,
                        type=int,
                        default=[1])
    parser.add_argument('--freq_order',
                        action='store_true',
                        dest='freq_order',
                        default=False,
                        help='Order output by freqency instead of period')

    # parse arguments
    args = parser.parse_args()

    # get the input dataframe
    df = io_lib.df_from_input(args)
    df = lomb_scargle_lib.lomb_scargle(df, args.time_col[0], args.val_col[0],
                                       args.interp_exp[0], args.freq_order)

    # write dataframe to output
    io_lib.df_to_output(args, df)