Ejemplo n.º 1
0
 def precession_freq(self):
     tf, vf = aps.LombScargle(self.t(), self.vdw()).autopower()
     peaks, _ = scs.find_peaks(vf, height=np.max(vf) * 0.9)
     if len(peaks) > 0:
         return tf[peaks[0]]
     else:
         return np.nan
Ejemplo n.º 2
0
def get_ls_periodogram(t,y,min_freq=1./1.,max_freq=1./0.1):
    
    """Compute Lomb-Scargle periodogram.
    
    Parameters
    ----------
    t : array
        Observation time array (e.g. MJD), ordered in ascending order.
    
    y : array
        Magnitude measurements at times ``t``.
        
    min_freq, max_freq : float or None
        The period finder can be guided by providing the min and max frequency
        in the ``y`` signal, in units 1/t. 
          min_freq = 1/longest expected period (in days)
          max_freq = 1/shortest expected perdiod (in days)
        The defaults are typical for RR Lyrae variability (RR Lyrae usually
        have a period of a fraction of one day).
        
    Returns
    -------
    period : array
        Phased period of the time-variable signal (fraction of the phase).
        
    power : array
        The periodogramm power as function if ``period``.
        
    """
    
    # Use astropy's LombScargle class
    ls = stats.LombScargle(t, y)

    # Compute the periodogram
    #   We guide the algorithm a bit:
    #     min_freq = 1/longest expected period (in days)
    #     max_freq = 1/shortest expected perdiod (in days)
    #   RR Lyrae usually have a period of a fraction of one day
    frequency, power = ls.autopower(minimum_frequency=min_freq,maximum_frequency=max_freq)
    period = 1./frequency # period is the inverse of frequency
    
    return period, power
Ejemplo n.º 3
0
    def periodogram_sb(self, nterms=1):
        """Single-band periodogram."""

        if (hasattr(self, '_periodogramfreqs_sb') and
                hasattr(self, '_periodogram_sb') and
                hasattr(self, '_periodogramerr_sb')):
            return self._periodogramfreqs_sb, self._periodogram_sb, self._periodogramerr_sb
        else:
            # if self.numCadences > 50:
            #     model = gatspy.periodic.LombScargleFast()
            # else:
            #     model = gatspy.periodic.LombScargle()

            ls = stats.LombScargle(self.t, self.y, self.yerr, nterms=nterms)
            f, psd = ls.autopower(method='fast', normalization='psd', maximum_frequency=1/self.mindt)
            self._periodogramfreqs_sb = np.require(np.array(f), requirements=['F', 'A', 'W', 'O', 'E'])
            self._periodogram_sb = np.require(np.array(psd), requirements=['F', 'A', 'W', 'O', 'E'])
            self._periodogramerr_sb = np.require(np.array(self._periodogram_sb.shape[0]*[0.0]), requirements=['F', 'A', 'W', 'O', 'E'])
        for i in range(self._periodogram_sb.shape[0]):
            if self._periodogram_sb[i] <= 0.0:
                self._periodogram_sb[i] = np.nan
        return self._periodogramfreqs_sb, self._periodogram_sb, self._periodogramerr_sb    
def work_horse(path_list, expected_mut_dict, outfile):
    periodicity_list = []
    for path in path_list:
        x_list = []
        y_list = []
        reader = csv.reader(open(path, "r"), delimiter='\t')
        header = next(reader)
        for line in reader:
            bp = int(line[0]) - 75
            o_count = int(line[1])
            e_count = expected_mut_dict[bp]
            try:
                enrichment = o_count / e_count
            except ZeroDivisionError:
                enrichment = 0
            x_list.append(bp)
            y_list.append(enrichment)

        del x_list[0]
        del x_list[-1]
        del y_list[0]
        del y_list[-1]

        ###############LOMB SCARGLE###############################
        f, Pxx_den = astro.LombScargle(x_list,
                                       y_list,
                                       fit_mean=False,
                                       center_data=True,
                                       nterms=1).autopower()
        new_Pxx_den = [y for x, y in zip(f, Pxx_den)
                       if x < 0.5]  #0.01 < x < 0.5
        Pxx_den_max = max(new_Pxx_den)
        len_f_array = len(f)
        i = 0
        while i < len_f_array:
            if Pxx_den[i] != Pxx_den_max:
                i += 1
                continue
            f_of_Pxx_den_max = f[i]
            i += 1
        periodicity_from_Pxx_den_max = 1 / f_of_Pxx_den_max
        #########################################################
        periodicity_list.append(periodicity_from_Pxx_den_max)

    periodicity_list.sort()
    periodicity_dict = {}
    for periodicity in periodicity_list:
        try:
            periodicity_dict[periodicity] += 1
        except KeyError:
            periodicity_dict[periodicity] = 1

    median_index = round(len(periodicity_list) / 2)
    median = periodicity_list[median_index]
    header = '\t'.join([str(s) for s in ["Median:", median]])
    outfile.write(header + '\n')

    for key in periodicity_dict:
        count = periodicity_dict[key]
        new_line = '\t'.join([str(s) for s in [key, count]])
        outfile.write(new_line + '\n')
Ejemplo n.º 5
0
    while line != '':
        arecibo1_dat = np.append(arecibo1_dat, float(line[:-1]))
        line = arecibo1.readline()

# gaussian parameters
A = 5.
B = 10.
L = 1.
N = 100

# gaussian
x = np.linspace(-L, L, N)
gaussian = A * np.exp(-B * (x)**2)

f_gauss, p_gauss = ast.LombScargle(x, gaussian).autopower(minimum_frequency=0.,
                                                          maximum_frequency=3.)

# arecibo 1 parameters
n = 32768
dt = 0.001

# arecibo 1
t = np.linspace(0., n * dt, n)
f_a1, p_a1 = ast.LombScargle(t, arecibo1_dat).autopower(minimum_frequency=0.,
                                                        maximum_frequency=200.)

# her x-1
time, mag = np.loadtxt('data/her-x-1.txt',
                       delimiter=' ',
                       unpack=True,
                       skiprows=1)
def work_horse(file, num_of_files, figure, subplot_index, ylim_dict):
    x_list = []
    y_list = []
    observed_count_list = []
    expected_count_list = []

    reader = csv.reader(open(file, "r"), delimiter='\t')
    header = next(reader)
    nuc_count = header[-1]
    for line in reader:
        bp = int(line[0]) - 75
        o_count = int(line[1])
        e_count = float(line[2])
        try:
            enrichment = o_count / e_count
        except ZeroDivisionError:
            enrichment = 0
        x_list.append(bp)
        observed_count_list.append(o_count)
        expected_count_list.append(e_count)
        y_list.append(enrichment)

    del x_list[0]
    del x_list[-1]
    del y_list[0]
    del y_list[-1]
    del observed_count_list[0]
    del observed_count_list[-1]
    del expected_count_list[0]
    del expected_count_list[-1]

    #    enrichment_normalization = sum(expected_count_list)/sum(observed_count_list)
    #   y_list = [y*enrichment_normalization for y in y_list]
    y_list_mean = round(statistics.mean(y_list))

    best_fit_coefficients = np.polyfit(x_list, y_list, 2)
    best_fit_polynomial = np.poly1d(best_fit_coefficients)
    best_fit_y_list = []
    for x_value in x_list:
        best_fit_y_list.append(best_fit_polynomial(x_value))
    first_deriv = np.polyder(best_fit_polynomial)
    second_deriv = np.polyder(first_deriv)

    SSR = sum([
        squared_num(y - best_fit_polynomial(x))
        for x, y in zip(x_list, y_list)
    ])
    SST = sum([squared_num(y - y_list_mean) for y in y_list])
    R_2 = 1 - (SSR / SST)

    ###############LOMB SCARGLE###############################
    f, Pxx_den = astro.LombScargle(x_list,
                                   y_list,
                                   fit_mean=False,
                                   center_data=True,
                                   nterms=1).autopower()
    new_Pxx_den = [y for x, y in zip(f, Pxx_den) if x < 0.5]
    Pxx_den_max = max(new_Pxx_den)
    len_f_array = len(f)
    i = 0
    while i < len_f_array:
        if Pxx_den[i] != Pxx_den_max:
            i += 1
            continue
        f_of_Pxx_den_max = f[i]
        i += 1
    periodicity_from_Pxx_den_max = 1 / f_of_Pxx_den_max
    #########################################################

    columns = 3
    rows = round((num_of_files / columns) + .5)
    plt.subplot(rows, columns, subplot_index)
    plt.plot(x_list, y_list, 'royalblue', x_list, best_fit_y_list, 'c--')

    axv_line_list = [
        -72.1, -61.8, -51.5, -41.2, -30.9, -20.6, -10.3, 0, 10.3, 20.6, 30.9,
        41.2, 51.5, 61.8, 72.1
    ]
    for x_pos in axv_line_list:
        plt.axvline(x=x_pos, color='gray', linestyle='--', lw=1)
    every_other_axv_line_list = []
    i = 0
    while i < len(axv_line_list):
        every_other_axv_line_list.append(axv_line_list[i])
        i += 2
    plt.xticks(visible=False)
    if subplot_index > num_of_files - columns:
        plt.xlabel("bp Position")
        plt.xticks(every_other_axv_line_list, visible=True)
    if (subplot_index - 1) % 3 == 0:
        plt.ylabel("Enrichment (Local/Global)")

    mut_count_mean = round(statistics.mean(observed_count_list))
    x_list_min = min(x_list)
    x_list_max = max(x_list)
    y_min = ylim_dict["Min"] * .6
    y_max = ylim_dict["Max"] * 1.1
    plt.ylim(y_min * 1.1, y_max * 1)
    bbox_color = 'red' if mut_count_mean < 200 else 'green'
    bbox_specs = {'facecolor': bbox_color, 'alpha': 0.5, 'pad': 2}
    y_min_shift = 1.1
    y_text_coordinate = y_min * y_min_shift
    plt.text(x_list_min,
             y_text_coordinate,
             "Nuc Count: " + '\n' + str(nuc_count),
             horizontalalignment='left',
             color='black',
             fontsize=12,
             bbox=bbox_specs)

    plt.text(x_list_max,
             y_text_coordinate,
             "Second Der: " + str(second_deriv),
             horizontalalignment='right',
             color='black',
             weight='bold',
             fontsize=10)

    plt.text(0,
             y_text_coordinate,
             "Period: " + '\n' + str(round(periodicity_from_Pxx_den_max, 4)),
             horizontalalignment='center',
             color='black',
             weight='bold',
             fontsize=10)

    ninth_underscore_index = find_nth_occurrence_rindex(file, "_", 9)
    eighth_underscore_index = find_nth_occurrence_rindex(file, "_", 8)
    subplot_title = file[ninth_underscore_index + 1:eighth_underscore_index]
    plt.title(subplot_title, size="medium")
Ejemplo n.º 7
0
                    '_lc.txt'
            lc = np.genfromtxt(fname, names=True)
            time = lc['time']
            mag = lc['mag']
            mag_err = lc['mag_err']

        # what do the phase-wrapped lightcurves look like?
        # 1007116003636; 0.5485033
        period = taus[i]
        phase = np.mod(time - css_peak[ind], period) / period
        if False:
            fig, axes = mp.subplots(1, 2, figsize=(16, 5))
            #nu = np.linspace(1.0, 3.0, 1000)
            #power = aps.LombScargle(time, mag, mag_err).power(nu)
            #nu, power = aps.LombScargle(time, mag, mag_err).autopower()
            nu, power = aps.LombScargle(time, mag, mag_err).autopower(
                minimum_frequency=1.0, maximum_frequency=3.0)
            print nu[np.argmax(power)]
            axes[0].plot(phase, mag, '.', color=cm(feh_cols[i]), alpha=0.4)
            axes[1].plot(nu, power, 'k-')
            axes[1].axvline(1.0 / period, color='r', alpha=0.7, zorder=0)
            mp.suptitle(css_id[ind] + ' / ' + css_id_num[ind])
            #mp.show()

        # calculate some binned statistics
        bins = np.linspace(0, 1, n_bins + 1)
        meds, edges, i_bins = ss.binned_statistic(phase, mag - np.median(mag), \
                                                  statistic='median', \
                                                  bins=bins)
        centers = (edges[0:-1] + edges[1:]) / 2.0
        means = np.zeros(n_bins)
        stds = np.ones(n_bins) * 1e9