예제 #1
0
파일: ngc1647.py 프로젝트: weingrill/SOCS
    def analysis(self):
        import numpy as np
        import matplotlib.pylab as mpl
        from PyAstronomy.pyTiming import pyPDM

        for star in self.stars:
            #i = self.stars.index(star)
            print star, '\t',
            t, m, e = self.lightcurve_fromdb(star)
            t -= min(t)

            S = pyPDM.Scanner(minVal=0.1,
                              maxVal=10.0,
                              dVal=10. / 86400.,
                              mode="period")
            P = pyPDM.PyPDM(t, m)
            p1, t1 = P.pdmEquiBinCover(100, 3, S)
            # For comparison, carry out PDM analysis using 10 bins equidistant
            # bins (no covers).
            #p2, t2 = P.pdmEquiBin(100, S)

            print '%.3f\t%.2f' % (p1[np.argmin(t1)], min(t1))
            # Show the result
            mpl.figure(facecolor='white')
            mpl.title("Result of PDM analysis")
            mpl.xlabel("Period")
            mpl.ylabel("Theta")
            mpl.plot(p1, t1)
            #mpl.plot(p2, t2, 'gp-')
            #mpl.legend(["pdmEquiBinCover", "pdmEquiBin"])
            #mpl.savefig('/work1/jwe/NGC1647/results/'+star+'.png')
            mpl.show()
예제 #2
0
def computePDMA(npjdmag):
    timedata = npjdmag[:, 0]
    magdata = npjdmag[:, 1]
    S = pyPDM.Scanner(minVal=0.005, maxVal=20, dVal=0.0001, mode="frequency")
    P = pyPDM.PyPDM(timedata, magdata)
    bindata = int(len(magdata) / 4)
    #bindata = 10
    f2, t2 = P.pdmEquiBin(bindata, S)
    delta = np.min(t2)
    pdmp = 1 / f2[np.argmin(t2)]
    return pdmp, delta
예제 #3
0
    def sanity_Scanner(self):
        # Import PDM module
        from PyAstronomy.pyTiming import pyPDM

        # Get Scanner instance
        scanner = pyPDM.Scanner(minVal=0.5,
                                maxVal=1.0,
                                dVal=0.05,
                                mode="period")
        # Print the periods covered by the scanner
        print("Periods: ", end=' ')
        for period in scanner:
            print(period, end=' ')
예제 #4
0
def pdm_period(time, magnitude, error=None, **kwargs):

    # scanner creation
    sparams = {"minVal": 0.01, "maxVal": 1, "dVal": 0.001}
    sparams.update(kwargs)
    sparams["mode"] = "period"
    scanner = pyPDM.Scanner(**sparams)

    pdm = pyPDM.PyPDM(time, magnitude)
    periods, frequencies = pdm.pdmEquiBin(20, scanner)
    period = periods[np.argmin(frequencies)]

    return period
예제 #5
0
파일: case83435.py 프로젝트: weingrill/SOCS
    def scanner(self):
        # Import PDM module
        from PyAstronomy.pyTiming import pyPDM

        # Get Scanner instance
        scanner = pyPDM.Scanner(minVal=0.1,
                                maxVal=1.0,
                                dVal=0.01,
                                mode="period")
        # Print the periods covered by the scanner
        print "Periods: ",
        for period in scanner:
            print period,
예제 #6
0
    def sanity_PDMAna(self):
        import numpy
        import matplotlib.pylab as plt
        from PyAstronomy.pyTiming import pyPDM

        # Create artificial data with frequency = 3,
        # period = 1/3
        x = numpy.arange(100) / 100.0
        y = numpy.sin(x * 2.0 * numpy.pi * 3.0 + 1.7)

        # Get a ``scanner'', which defines the frequency interval to be checked.
        # Alternatively, also periods could be used instead of frequency.
        S = pyPDM.Scanner(minVal=0.5, maxVal=5.0, dVal=0.01, mode="frequency")

        # Carry out PDM analysis. Get frequency array
        # (f, note that it is frequency, because the scanner's
        # mode is ``frequency'') and associated Theta statistic (t).
        # Use 10 phase bins and 3 covers (= phase-shifted set of bins).
        P = pyPDM.PyPDM(x, y)
        f1, t1 = P.pdmEquiBinCover(10, 3, S)
        # For comparison, carry out PDM analysis using 10 bins equidistant
        # bins (no covers).
        f2, t2 = P.pdmEquiBin(10, S)
예제 #7
0
파일: case83435.py 프로젝트: weingrill/SOCS
    def analysis(self):
        import numpy
        import matplotlib.pylab as mpl
        from PyAstronomy.pyTiming import pyPDM

        # Create artificial data with frequency = 3,
        # period = 1/3
        x = self.hjd
        y = self.mag

        # Get a ``scanner'', which defines the frequency interval to be checked.
        # Alternatively, also periods could be used instead of frequency.
        S = pyPDM.Scanner(minVal=0.163,
                          maxVal=0.33,
                          dVal=0.00001,
                          mode="period")

        # Carry out PDM analysis. Get frequency array
        # (f, note that it is frequency, because the scanner's
        # mode is ``frequency'') and associated Theta statistic (t).
        # Use 10 phase bins and 3 covers (= phase-shifted set of bins).
        P = pyPDM.PyPDM(x, y)
        p1, t1 = P.pdmEquiBinCover(100, 3, S)
        # For comparison, carry out PDM analysis using 10 bins equidistant
        # bins (no covers).
        p2, t2 = P.pdmEquiBin(100, S)

        # Show the result
        mpl.figure(facecolor='white')
        mpl.title("Result of PDM analysis")
        mpl.xlabel("Period")
        mpl.ylabel("Theta")
        mpl.plot(p1, t1, 'bp-')
        mpl.plot(p2, t2, 'gp-')
        #mpl.legend(["pdmEquiBinCover", "pdmEquiBin"])
        mpl.show()
예제 #8
0
def PMD(x,
        y,
        dy,
        pVal,
        mode="period",
        label=None,
        figout=None,
        pmd_para=[10, 3]):
    '''
    >x,y,dy 时间,星等,误差
    >pVal:[最小周期,最大周期,周期间隔]
    >label-----figout--------outdir 
     曲线解释---图片保存名称---图片保存目录
    >作图:原始数据,周期theta图,相位图
    '''

    import numpy as np
    import matplotlib.pyplot as plt
    from PyAstronomy.pyTiming import pyPDM

    if not isinstance(x, np.ndarray):
        x = np.array(x)
        y = np.array(y)
        dy = np.array(dy)
    S = pyPDM.Scanner(minVal=pVal[0], maxVal=pVal[1], dVal=pVal[2], mode=mode)
    P = pyPDM.PyPDM(x, y)
    time, theta = P.pdmEquiBinCover(pmd_para[0], pmd_para[1], S)

    fig, ax = plt.subplots(3)
    fig.set_size_inches(30, 20)
    ax[0].invert_yaxis()
    ax[2].invert_yaxis()
    ax[0].grid()
    ax[1].grid()
    ax[2].grid()
    ax[0].errorbar(x, y, dy, fmt='o')
    ax[0].legend([label], loc='upper right', fontsize=20, frameon=False)

    ax[1].set_title("Result of PDM analysis")
    ax[1].set_xlabel(mode)
    ax[1].set_ylabel("Theta")
    ax[1].plot(time, theta, 'bp-')

    best_period = time[np.argmin(theta)]
    peak_theta = np.min(theta)
    ax[1].plot(best_period, peak_theta, 'ro')
    ax[1].legend(
        ['pdmEquiBinCover', 'peak is ' + str(round(best_period, 10)) + 'd'],
        loc='lower right',
        fontsize=15,
        frameon=False)

    if mode == "period":
        ax[2].errorbar((x / best_period) % 1, y, dy, fmt='o')
    else:
        ax[2].errorbar((x * best_period) % 1, y, dy, fmt='o')
    ax[2].legend(
        ['folded data with period=' + str(round(best_period, 10)) + 'd'],
        loc='upper right',
        fontsize=20)
    if figout != None:
        plt.savefig(figout, dpi=600)
    plt.show()
    return time, theta, best_period
예제 #9
0
import sys
import numpy as np
from PyAstronomy.pyTiming import pyPDM

nbins = 10
covers = 3

nd = 1000
P = 10.0
jd = np.linspace(0.0, 100.0, nd, dtype=np.double)
fs = np.sin(jd / P * 2.0 * np.pi) + np.random.randn(nd) * 0.1

S = pyPDM.Scanner(minVal=1.0 / (50.0),
                  maxVal=1.0e0,
                  dVal=1.0e-4,
                  mode="frequency")
P = pyPDM.PyPDM(jd, fs)
f1, t1 = P.pdmEquiBinCover(nbins, covers, S)
f2, t2 = P.pdmEquiBin(nbins, S)
예제 #10
0
#adding the noise
# we use a normal distibution with a std deviation of 1.0, centered at 0
stddevs=1.0
#shape our noise to the signal's dimensions
noise=numpy.random.normal(0,stddevs,x.shape)
#add to the signal
y1=y+noise"""
#============================================================================
#============================================================================
#============================================================================
#============================================================================

# Get a ``scanner'', which defines the frequency interval to be checked.
# Alternatively, also periods could be used instead of frequency.
S = pyPDM.Scanner(minVal=0.5, maxVal=BinUp, dVal=.1, mode="period")

# Carry out PDM analysis. Get frequency array
# (f, note that it is frequency, because the scanner's
# mode is ``period'') and associated Theta statistic (t).

#here is where we feed te data
P = pyPDM.PyPDM(fxps0, fxps1)  #fixed data
#P = pyPDM.PyPDM(mvps0,mvps1)    #moving data

f1, t1 = P.pdmEquiBinCover(10, 3, S)
#PDM analysis using  bins (no covers).
M = 7

f2, t2 = P.pdmEquiBin(M, S)
#local minima empty list to be appended
예제 #11
0
    num_params_psd_per = 3
  else:
    num_params_psd_per = 0
    
  num_params_psd = (num_params_psd_sto+num_params_psd_per) 
  freq_limit = parset["FreqLimit"]
  V = parset['V']
  W = parset['W']
  
  load_lcdata()
  load_sample()
  
  tspan = lc[-1, 0] - lc[0, 0]
  print "Tspan:", tspan/365.0
  ls_freq = np.logspace(np.log10(1.0/tpmin), np.log10(1.0/(tspan/ncycle)), 500)
  pdm_scan = pyPDM.Scanner(minVal=tpmin, maxVal=tspan/ncycle, dVal=(tspan/ncycle-tpmin)/500, mode="period")
  
  if num_params_psd_per == 0:
    nd_sim = sample.shape[1] - num_params_psd
  else:
    nd_sim = ((sample.shape[1] - num_params_psd) * 2)//3
  
  print sample.shape[1], nd_sim, num_params_psd

  #test_genlc()

  pbTR, TR, TR_obs = pb_TR(doplot=True)
  pbTLS, TLS, TLS_obs = pb_TLS(doplot=True)
  pbTPDM, TPDM, TPDM_obs = pb_TPDM(doplot=True)

  np.savetxt("TR.txt", np.stack((TR, TR_obs), axis=-1), fmt="%15.5f  %15.5f")
예제 #12
0
def LS(kic, kernerforca, Pbeg, Pend, PeriodMod, path='TEMP/'):

    path = path + str(kic)
    data = np.loadtxt(path + '\TS_' + str(kic) + '.txt')
    time = data[:, 0]
    flux = data[:, 1]
    time = time / (60 * 60 * 24)

    g = Gaussian1DKernel(kernerforca, mode='oversample', factor=5000)
    z = convolve(flux, g, boundary='wrap', normalize_kernel=True)

    plt.plot(time, z, '-b')
    plt.plot(time, flux, '-k', alpha=0.5)
    plt.show()
    print("Entering the analysis by the method: ", PeriodMod)

    if PeriodMod == 'LS':

        f = np.linspace(1 / Pend, 1 / Pbeg, 50000)
        p = LombScargle(time, z).power(f)
        y = p**2 / f

        fig = plt.figure(figsize=(8, 5), dpi=130)
        plt.plot(1. / f, y, 'k', lw=0.5)
        sig1 = np.percentile(y, [1.0])
        sig5 = np.percentile(y, [1])
        xlim = (1. / f[0], 1. / f[-1])
        plt.plot(xlim, [sig1, sig1],
                 ':',
                 c='r',
                 alpha=1,
                 lw=0.5,
                 label='FAP 1\%')
        plt.xlabel("Period[days]")
        plt.ylabel("Power")
        i = peakutils.indexes(y, thres=0.99)
        prot = 1. / f[i]
        plt.legend(loc='best')
        plt.savefig(path + '/' + str(kic) + '_LS.pdf')
        plt.show()

    if PeriodMod == 'PDM':

        x = time
        y = z

        S = pyPDM.Scanner(minVal=1 / Pend,
                          maxVal=1 / Pbeg,
                          dVal=0.00001,
                          mode="frequency")
        P = pyPDM.PyPDM(x, y)
        f1, t1 = P.pdmEquiBinCover(5, 1, S)
        f2, t2 = P.pdmEquiBin(10, S)
        fig = plt.figure(figsize=(8, 5), dpi=130)
        plt.xlabel("Frequency [days$^{-1}$]")
        plt.ylabel("Theta")
        plt.plot(f1, t1, 'b-', lw=0.5)
        plt.plot(f2, t2, lw=0.5, alpha=0.5)

        j = peakutils.indexes((-t2), thres=0.95)
        aa = f2[j]
        bb = t2[j]

        labels = np.array(np.round(1 / f2[j], 2))
        texts = []
        for x, y, s in zip(aa, bb, labels):
            texts.append(plt.text(x, y, s, fontsize=7))

        plt.legend(["Multiple sequences", "Equidistant bins"])
        plt.grid(alpha=0.5)
        plt.show()
예제 #13
0
def periodogram(lightcurve_in,
                name="",
                retparam="",
                fixperiod="",
                pdm=0,
                double=0,
                talk=0,
                plot=0,
                location="",
                limits=None):
    if name == "": name = 'test'
    if retparam == "": retparam = 'N'
    if talk == "": talk = 0
    minperiod = 0.01  # minimum period to check
    maxperiod = 2.0  # maximum period to check

    f = np.linspace(0.01, 10, 1000000)  # checks 10 to 100 days
    #f = np.linspace(0.26, 0.28, 1000000)  # checks 10 to 100 days
    lightcurve = []
    lightcurve.append(lightcurve_in[0][np.argsort(lightcurve_in[0])])
    lightcurve.append(lightcurve_in[1][np.argsort(lightcurve_in[0])])
    lightcurve.append(lightcurve_in[2][np.argsort(lightcurve_in[0])])
    lightcurve = np.array(lightcurve)

    if pdm == 0:
        pgram = LombScargle(lightcurve[0], lightcurve[1]).power(f)

        maxper = np.argmax(pgram[np.where(1.0 / f > minperiod)])
        period = fixperiod
    else:
        start = time.time()
        s = pyPDM.Scanner(minVal=0.01, maxVal=10, dVal=1e-5, mode="frequency")
        p = pyPDM.PyPDM(lightcurve[0], lightcurve[1])
        #f, theta = p.pdmEquiBinCover(10, 3, s)
        f, theta = p.pdmEquiBin(10, s)
        minTheta = np.argmin(theta)
        period = 1 / (f[minTheta])
        pgram = 1 - theta
        fixperiod = 0
        end = time.time()
        print(end - start)

    if fixperiod == "":
        period = 1.0 * 1. / f[maxper]
    elif (float(fixperiod) < 0.0):
        fixperiod = float(fixperiod)
        check = np.where((1.0 / f > -0.9 * fixperiod)
                         & (1.0 / f < -1.1 * fixperiod))
        f_cut = f[check[0]]
        pgram_cut = pgram[check[0]]
        maxper = np.argmax(pgram_cut)
        period = 1.0 / f_cut[maxper]
    try:
        fixperiod = -float(fixperiod)
    except ValueError:
        pass

    if (talk == 1):
        print("period: ", period)

    if plot == 1:
        # plot the periodogram
        plt.clf()
        # plt.figure(figsize=(6, 4))
        # plt.rcParams.update({'font.size': 8})
        # rectangle = [0.1, 0.55, 0.35, 0.35]
        # ax = plt.axes(rectangle)
        days = 1 / f
        plt.plot(
            days[np.where(days <= (period * 2 if not double else period * 4))],
            pgram[np.where(
                days <= (period * 2 if not double else period * 4))], 'k-')
        #plt.xlim(0, 3.0 * period)
        # plt.xlim(0,6.0)
        plt.xlabel('Time (d)')
        if pdm == 0:
            plt.ylabel('Frequency')
        else:
            plt.ylabel(r'$1-\theta$')
        if limits:
            plt.xlim(limits)
        #plt.legend(loc='upper center', handletextpad=0.01)

        # # plot the lightcurve
        # rectangle = [0.55, 0.55, 0.35, 0.35]
        # ax = plt.axes(rectangle)
        # plt.plot(lightcurve[0] - 2400000.5, lightcurve[1], color='0.7', marker='.',
        #          linestyle='solid', markersize=0.1)
        # plt.plot(lightcurve[0] - 2400000.5, lightcurve[1], color='Red', marker='o',
        #          linestyle='none', markersize=1)
        # plt.ylim(np.median(lightcurve[1]) + 5.0 * np.std(lightcurve[1]),
        #          np.median(lightcurve[1]) - 5.0 * np.std(lightcurve[1]))
        # plt.locator_params(axis='x', nbins=4)
        # plt.locator_params(axis='y', nbins=5)
        # plt.xlabel('Time, MJD (d)')
        # plt.ylabel('Magnitude {} (mag)'.format('R'))

        if not os.path.exists(location + name + '/'):
            os.mkdir(location + name + '/')

        plt.savefig(location + name + '/' + name + '_Periodogram' +
                    ('(LS) ' if pdm == 0 else '(PDM)') + '.pdf',
                    format='pdf',
                    bbox_inches='tight',
                    dpi=600)
        plt.savefig(location + name + '/' + name + '_Periodogram' +
                    ('(LS) ' if pdm == 0 else '(PDM)') + '.png',
                    format='png',
                    bbox_inches='tight',
                    dpi=600)
        plt.show()

    if double:
        return period * 2
    else:
        return period
예제 #14
0
# pull the date and magnitude into lists
afoev = pd.read_excel('ZUMa_recent_AFOEV_noNTS.xlsx', sheetname='Sheet1')
mod_jul = afoev['Modified Julian Date']
mag = afoev['Visual magnitude']

#we need to see the fairweather observers
#use counter to determine the number of times
#observer has taken measurements
#occur=Counter(afoev['Observer'])
#print (occur)
#this allows us to remove inconsistent observers

# Get a ``scanner'', which defines the frequency interval to be checked.
# Alternatively, also periods could be used instead of frequency.
S = pyPDM.Scanner(minVal=0.5, maxVal=250.0, dVal=.1, mode="frequency")

# Carry out PDM analysis. Get frequency array
# (f, note that it is frequency, because the scanner's
# mode is ``frequency'') and associated Theta statistic (t).
# Use 10 phase bins and 3 covers (= phase-shifted set of bins).
P = pyPDM.PyPDM(mod_jul, mag)
#f1, t1 = P.pdmEquiBinCover(3, 6, S)
# For comparison, carry out PDM analysis using  bins (no covers).
f2, t2 = P.pdmEquiBin(10, S)

#plot the cleaned up data
plt.subplot(2, 1, 1)
plt.plot(mod_jul, mag, 'r.')
plt.xlabel('modified julian date')
plt.ylabel('approx vis magnitude')