import matplotlib.pyplot as plt
import numpy as np

def plot_period_and_period_differences(julian_dates, periods, period_diffs):
    """
    Plots the period and period differences on the same plot with dual y-axes.
    """
    # Julian midpoints for period differences
    julian_midpoints = (np.array(julian_dates[:-1]) + np.array(julian_dates[1:])) / 2

    fig, ax1 = plt.subplots()

    # Plot periods on the primary y-axis
    color = 'tab:blue'
    ax1.set_xlabel('Julian Date')
    ax1.set_ylabel('Period (s)', color=color)
    ax1.plot(julian_dates, periods, color=color)
    ax1.tick_params(axis='y', labelcolor=color)

    # Create a second y-axis for period differences
    ax2 = ax1.twinx()
    color = 'tab:red'
    ax2.set_ylabel('Period Difference ( x 10 ^8 s)', color=color)
    ax2.plot(julian_midpoints, period_diffs, color=color)
    ax2.tick_params(axis='y', labelcolor=color)

    fig.tight_layout()  # Adjust layout to prevent overlap
    plt.title('Periods and Period Differences')
    plt.show()

# Example usage: Assuming your data file contains julian_dates, periods, and period_diffs
def read_data(filename):
    """
    Reads Julian Dates, Periods, and Period Differences from a file.
    Expected format:
    Julian Date, Period (s), Period Difference (s)
    """
    julian_dates = []
    periods = []
    period_diffs = []

    with open(filename, 'r') as file:
        for line in file:
            jd, period, period_diff = map(float, line.split())
            julian_dates.append(jd)
            periods.append(period)
            period_diffs.append(period_diff * 10**8)

    return julian_dates, periods, period_diffs

# Example usage:
filename = 'angular_acc_20643.dat'  # Replace with your actual file path
julian_dates, periods, period_diffs = read_data(filename)

# Plot the data
plot_period_and_period_differences(julian_dates, periods, period_diffs)
