import csv
import matplotlib.pyplot as plt
fragments = []
numbers = []
lengths = []
total_length = 0
with open("C:/Users/Vitalii/Desktop/term3/Informatics/Genome_S_arctica.fna", 'r') as fasta:
    scaffolds = fasta.read().split('\n>')
counter = 0
for scaf in scaffolds:
    scaf = scaf.split('\n')
    name = scaf[0].split(' ')[0]
    sequence = ''.join(scaf[1 : ])
    length = len(sequence)
    fragments.append([name, length])
    total_length += length
    counter += 1
    numbers.append(counter)
    lengths.append(length)
with open('C:/Users/Vitalii/Desktop/term3/Informatics/Scaffolds.csv', 'w') as file:
    new_table = csv.writer(file, delimiter = '\t')
    for frag in fragments:
        new_table.writerow(frag)
N50 = 64598
L50 = 516
N75 = 15054
L75 = 1442
N90 = 2355
L90 = 4637
fig, ax = plt.subplots(figsize = (9,6))
ax.plot(numbers, sorted(lengths, reverse = True), color = 'steelblue', linewidth = 2.5)
ax.set_yscale('log')
x_left, x_right = ax.get_xlim()
y_bottom, y_top = ax.get_ylim()
ax.set_xlim(x_left, x_right)
ax.set_ylim(y_bottom, y_top)
ax.scatter([L50], [N50], zorder = 5, color = 'firebrick', s = 50)
ax.scatter([L75], [N75], zorder = 5, color = 'navy', s = 50)
ax.scatter([L90], [N90], zorder = 5, color = 'forestgreen', s = 50)
ax.annotate(text = 'N50, L50', xy = (L50, N50), xytext = (L50 + 200, N50 + 5000))
ax.annotate(text = 'N75, L75', xy = (L75, N75), xytext = (L75 + 200, N75 + 2300))
ax.annotate(text = 'N90, L90', xy = (L90, N90), xytext = (L90 + 200, N90 + 300))
ax.plot([x_left, L50], [N50, N50], zorder = 3, linestyle = ':', color = 'tomato')
ax.plot([L50, L50], [y_bottom, N50], zorder = 3, linestyle = ':', color = 'tomato')
ax.plot([x_left, L75], [N75, N75], zorder = 3, linestyle = ':', color = 'blue')
ax.plot([L75, L75], [y_bottom, N75], zorder = 3, linestyle = ':', color = 'blue')
ax.plot([x_left, L90], [N90, N90], zorder = 3, linestyle = ':', color = 'seagreen')
ax.plot([L90, L90], [y_bottom, N90], zorder = 3, linestyle = ':', color = 'seagreen')
ax.grid(which = 'major', linewidth = 0.8, color = 'grey')
ax.grid(which = 'minor', linewidth = 0.5, alpha = 0.4, color = 'lightgrey')
ax.fill_between(numbers, sorted(lengths, reverse = True), 0, zorder = 1, color = 'skyblue', alpha = 0.2)
ax.set_xlabel('Номер скаффолда')
ax.set_ylabel('Размер скаффолда (п.н.)')
plt.show()
