import numpy as np
import matplotlib.pyplot as plt
import re

# Constants
D = 0.1
mu = 0.1
kx = 6
x0 = 1
Fmax = 8 * kx * x0**3 / np.sqrt(27)
L = D / (mu * Fmax)
tau = L * L / D
plt.rc('text.latex', preamble=r'\usepackage{amsmath} \usepackage{mathptmx}')

# LaTeX-Unterstützung aktivieren und Schriftart setzen
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
# Set global font to Serif
plt.rcParams['font.family'] = 'serif'

# Function to read data from a file
def readfile(file_path):
    return np.loadtxt(file_path)

# Function to normalize and chunk the data
def normalize_and_chunk(data, num_chunks=300):
    # Calculate the sum of all elements in the data array
    data_sum = np.sum(data)
    
    # Normalize the data by dividing each element by the sum
    normalized_data = data / data_sum

    # Chunk the data and calculate average frequency
    chunk_size = len(normalized_data) // num_chunks  # Integer division to get chunk size
    chunked_data = []
    x_values = []

    for j in range(num_chunks):
        start_index = j * chunk_size
        end_index = (j + 1) * chunk_size

        chunk = normalized_data[start_index:end_index]
        chunk_avg = np.mean(chunk)

        chunked_data.append(chunk_avg * chunk_size)
        
        x_values.append((start_index + end_index) / 2 * 0.005 / tau)  # Adjust x-values

    # Normalize the chunked data to maintain the area under the curve
    if len(x_values) > 2:  # Ensure there are enough x-values for normalization
        chunked_data /= (x_values[3] - x_values[2])

    return chunked_data, x_values

# Function to extract tumblerate and runrate from filename
def extract_rates(filename):
    match = re.search(r'tumblerate(\d+)runrate(\d+)', filename)
    if match:
        tumblerate = match.group(1)
        runrate = match.group(2)
        return tumblerate, runrate
    return None, None

# Function to create a subplot for given MD and TPS file paths
def create_subplot(ax, md_files, tps_files, colors, markers):
   # ax.plot([], [], marker='o', color='black', linestyle='None', label=r'MD')
   # ax.plot([], [], color='black', linestyle='-', label=r'TPS')
    
    for idx, (md_file, tps_file) in enumerate(zip(md_files, tps_files)):
        # Read data
        data_md = readfile(md_file)
        data_TPS = readfile(tps_file)
        
        # Normalize and chunk data
        chunked_data_md, x_values_md = normalize_and_chunk(data_md)
        chunked_data_TPS, x_values_tps = normalize_and_chunk(data_TPS)

        # Extract tumblerate and runrate for labels
        tumblerate, runrate = extract_rates(md_file)

        # Directly replace values as per your request
        if tumblerate == '2':
            tumblerate = '0.24'
        elif tumblerate == '10':
            tumblerate = '1.20'
        elif tumblerate == '6':
            tumblerate = '0.70'
        elif tumblerate == '1':
            tumblerate = '0.12'
            
        if runrate == '1':
            runrate = '0.12'
        elif runrate == '10':
            runrate = '1.20'
        elif runrate == '2':
            runrate = '0.24'

        # Plot MD data as dashed lines with unique markers and colors

        if tumblerate == '0':
                ax.plot(x_values_md, chunked_data_md, linestyle='none', color=colors[idx],
                marker=markers[idx], label=fr'ABP', 
                linewidth=2, markersize=5)
                ax.plot(x_values_tps, chunked_data_TPS, color=colors[idx], alpha=0.5, linestyle = '--',
                #label=fr'$\lambda_{{1 \rightarrow 0}}={tumblerate}$, $\lambda_{{0 \rightarrow 1}}={runrate}$'
                )

        elif runrate == '0':
                ax.plot(x_values_md, chunked_data_md, linestyle='none', color=colors[idx],
                marker=markers[idx], label=fr'BP', 
                linewidth=2, markersize=5)
                ax.plot(x_values_tps, chunked_data_TPS, color=colors[idx], alpha=0.5, linestyle = ':',
                #label=fr'$\lambda_{{1 \rightarrow 0}}={tumblerate}$, $\lambda_{{0 \rightarrow 1}}={runrate}$'
                )
        else:         
            ax.plot(x_values_md, chunked_data_md, linestyle='none', color=colors[idx],
            marker=markers[idx], label=fr'$\lambda_{{1 \rightarrow 0}}={tumblerate}/\tau$, $\lambda_{{0 \rightarrow 1}}={runrate}/\tau$', 
                linewidth=2, markersize=5)

            # Plot TPS data in the same color as MD
            ax.plot(x_values_tps, chunked_data_TPS, color=colors[idx], alpha=0.5,
                #label=fr'$\lambda_{{1 \rightarrow 0}}={tumblerate}$, $\lambda_{{0 \rightarrow 1}}={runrate}$'
                )

    ax.set_xlim([0, 50])  # Adjust x-axis limit as necessary
    ax.set_ylim([0, 0.14])  # Adjust y-axis limit as necessary
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif', weight='normal', size=10)
    # Enable ticks on both sides and inside
    ax.tick_params(axis='both', which='both', direction='in', top=True, right=True)

    ax.set_xlabel(fr'$t/\tau$', fontsize=10, fontweight='normal')
    ax.set_ylabel(fr'$P(t_\text{{TPT}})$', fontsize=10, fontweight='normal')
    ax.tick_params(axis='both', labelsize=8)  # Set tick label font size
    ax.legend(fontsize=8, loc='upper center', bbox_to_anchor=(0.5, 1.)) # Set legend font size

# Define specific colors and markers for each dataset in each subplot
subplot_details = [
    {
        "md": [
            "data/length_distributions/length_distribution_histo_md_rtp_step0.005pe10tumblerate2runrate0samplesize1000000.dat",
            "data/length_distributions/length_distribution_histo_md_rtp_step0.005pe10tumblerate0runrate2samplesize1000000.dat",
            "data/length_distributions/length_distribution_histo_md_rtp_step0.005pe10tumblerate6runrate2samplesize1000000.dat",
        ],
        "TPS": [
            "data/length_distributions/length_distribution_histo_TPS_rtp_step0.005pe10tumblerate2runrate0samplesize100000000.dat",
            "data/length_distributions/length_distribution_histo_TPS_rtp_step0.005pe10tumblerate0runrate2samplesize100000000.dat",
            "data/length_distributions/length_distribution_histo_TPS_rtp_step0.005pe10tumblerate6runrate2samplesize100000000.dat",
        ],
        "colors": ['blue', 'red', 'green'],
        "markers": ['o', 's', '^']
    },
    {
        "md": [
            "data/length_distributions/length_distribution_histo_md_rtp_step0.005pe10tumblerate10runrate10samplesize1000000.dat",
            "data/length_distributions/length_distribution_histo_md_rtp_step0.005pe10tumblerate1runrate10samplesize1000000.dat"
        ],
        "TPS": [
            "data/length_distributions/length_distribution_histo_TPS_rtp_step0.005pe10tumblerate10runrate10samplesize100000000.dat",
            "data/length_distributions/length_distribution_histo_TPS_rtp_step0.005pe10tumblerate1runrate10samplesize100000000.dat"
        ],
        "colors": ['cyan', 'red'],
        "markers": ['D', 'x']
    },
    {
        "md": [
            "data/length_distributions/length_distribution_histo_md_rtp_step0.005pe10tumblerate1runrate1samplesize1000000.dat",
            "data/length_distributions/length_distribution_histo_md_rtp_step0.005pe10tumblerate10runrate1samplesize1000000.dat"
        ],
        "TPS": [
            "data/length_distributions/length_distribution_histo_TPS_rtp_step0.005pe10tumblerate1runrate1samplesize100000000.dat",
            "data/length_distributions/length_distribution_histo_TPS_rtp_step0.005pe10tumblerate10runrate1samplesize100000000.dat"
        ],
        "colors": ['black', 'blue'],
        "markers": ['+', 'P']
    }
]

# Create the plot
fig, axs = plt.subplots(1, 3, figsize=(7, 3.3), tight_layout=True)
plt.rc('text', usetex=True)
plt.rc('font', family='serif', weight='normal', size=10)
for ax, data in zip(axs, subplot_details):
    create_subplot(ax, data["md"], data["TPS"], data["colors"], data["markers"])
        
# Hide the x-axis and x-ticks for axs[1] and axs[2]
axs[1].set_ylabel('')
axs[1].set_yticklabels([])
axs[1].tick_params(axis='y', which='both', direction='in', right=True, left=True)  # Keep ticks on both sides

axs[2].set_ylabel('')
axs[2].set_yticklabels([])
axs[2].tick_params(axis='y', which='both', direction='in', right=True, left=True)  # Keep ticks on both sides

plt.rc('text.latex', preamble=r'\usepackage{amsmath} \usepackage{mathptmx}')

# Set global font to Serif
plt.rcParams['font.family'] = 'serif'

plt.tight_layout()  # Adjust layout to minimize whitespace
plt.savefig('/home/tom/Ph.D./TPS_for_RTP/LaTex/paper/Figures/P(t_TPT)_TPS_MD_severalcases.pdf')
plt.show()



