import pandas as pd

# Load segmentation data
seg_data = pd.read_csv("data_cna_hg19.seg", sep="\t")

# Define thresholds for amplification and deletion
threshold_amplification = 0.2
threshold_deletion = -0.2

# Calculate segment length
seg_data["segment_length"] = seg_data["loc.end"] - seg_data["loc.start"]

# Filter for significant alterations
significant_seg = seg_data[(seg_data["seg.mean"] >= threshold_amplification) |
                           (seg_data["seg.mean"] <= threshold_deletion)].copy()

# Calculate the total altered segment length per sample
altered_lengths = significant_seg.groupby("ID")["segment_length"].sum()

# Calculate the total genome length per sample
total_lengths = seg_data.groupby("ID")["segment_length"].sum()

# Calculate Fraction Genome Altered
fraction_genome_altered = altered_lengths / total_lengths

# Handle missing values and round to 4 decimal places
fraction_genome_altered = fraction_genome_altered.fillna(0).round(4)

# Prepare the output DataFrame
fraction_genome_altered_df = fraction_genome_altered.reset_index()
fraction_genome_altered_df.columns = ["Sample_ID", "Fraction_Genome_Altered"]

# Save the results to a CSV file
fraction_genome_altered_df.to_csv("fraction_genome_altered_without_num_mark.csv", index=False)

# Display a summary
print(fraction_genome_altered_df.head())

import pandas as pd
import matplotlib.pyplot as plt

# Load the calculated Fraction Genome Altered data
data = pd.read_csv("fraction_genome_altered_without_num_mark.csv")

# Define bins and labels
bins = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5,
        0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 1]
labels = ['<= 0.05'] + [f'{bins[i]:.2f} - {bins[i+1]:.2f}' for i in range(1, len(bins) - 2)] + ['> 0.9']

# Bin the data
data['Range'] = pd.cut(data["Fraction_Genome_Altered"], bins=bins, labels=labels, include_lowest=True, right=False)

# Calculate frequencies
frequency = data['Range'].value_counts(sort=False)

# Plot the bar chart
plt.figure(figsize=(12, 6))
frequency.plot(kind='bar', color='skyblue', edgecolor='black')

# Customize the plot
plt.title('Distribution of Fraction Genome Altered', fontsize=16)
plt.xlabel('Fraction Genome Altered Range', fontsize=14)
plt.ylabel('Frequency', fontsize=14)
plt.xticks(rotation=45, ha='right', fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)

# Show the plot
plt.tight_layout()
plt.show()
