#!/usr/bin/env python
# coding: utf-8

# In[ ]:


import pandas as pd
import numpy as np
from itertools import groupby
from operator import itemgetter
import random
import json
import pandas as pd
import numpy as np
import os
from pandas import read_csv
from pandas import datetime
from math import sqrt
from math import exp
from statsmodels.tsa.stattools import adfuller
from numpy import log
import re


# In[ ]:


fasta_sequences = SeqIO.parse(open('All_aligned.fasta'), 'fasta')
X = []
Name = []
for fasta in fasta_sequences:
    name= fasta.id
    Name.append(name)
    test_str = str(fasta.seq)
    X.append(test_str)
Count = pd.read_csv('Count.csv')
Filtered = pd.read_csv('Filtered_Sequences.csv')


# In[ ]:


Ref_ID = Aligned['ID']
Sequence = Aligned['Seqeunce']
ref = Sequence[0]
seq = Sequence[1:]
R_ID = Ref_ID[0]
ID = Ref_ID[1:]
match_postion = Filtered["Num_Match"]
mismatch = Filtered["tol_mismatch"]
Consecutive_substring = Filtered["Max_Consecutive"]
gap = Filtered["Num_Gaps"]
Length_of_Sequence = Filtered["Expanded_len_after_align"]
Human_miRNA_Len = Filtered["Human_miRNA_Len"]
List = Filtered['miRNA']


# In[ ]:


Count = Count['Count']


# In[ ]:


X = []
for i in range(len(Count)):
    if(Count[i]==np.max(Count)):
        print(np.max(Count))
        X.append(i+1)


# In[ ]:


def get_consecutive_integer_series(integer_list):
    integer_list = sorted(integer_list)
    start_item = integer_list[0]
    end_item = integer_list[-1]
    a = set(integer_list)
    b = range(start_item, end_item+1)
    c = set(b) - a
    li = []
    start = 0
    for i in sorted(c):
        end = b.index(i)
        li.append(b[start:end])
        start = end + 1
    li.append(b[start:])

    for sliced_list in li:
        if not sliced_list:
            continue
        if len(sliced_list) == 1:
            yield "{0}-{1}".format(sliced_list[0],sliced_list[0]+1)
        else:
            yield "{0}-{1}".format(sliced_list[0], sliced_list[0]+1)


# In[ ]:


Series=[]
for series in get_consecutive_integer_series(X):
    Series.append(series)


# In[ ]:


Var1 = []
for i in range(len(Series)):
    ini = int(S[i].partition("-")[0])
    fin = int(S[i].partition("-")[2])
    change =[]
    print(ini+1)
    print(fin+1)
    Ref = Sequence[0]
    r = Ref[ini-1:fin-1]
    print(r)
    for j in range(len(Sequence)):
        s = Sequence[j]
        s = s[ini-1:fin-1]
        if(r == s):
            if(Ref_ID[j] != 'NC-045512.2/SARS-2/Wuhan-Hu-1/CompleteGenome'):
                print(s)
                print(Ref_ID[j])
                change.append(Ref_ID[j])
    print()
    Var1.append(change)


# In[ ]:


Var2 = []
for i in range(len(Var1)):
    s = Var1[i]
    for j in range(len(s)):
        Var2.append(s[j])
my_final_list = set(Var2)


# In[ ]:


Var3 = []
Var4 = []
Var5 = []
Ref_id.append(Ref_ID[0])
Ref_seq.append(Sequence[0])
for j in range(X.shape[0]):
    for k in range(len(Ref_ID)):
            if(X[j,1] == Ref_ID[k]):
                print(X[j,1])
                Ref_id.append(Ref_ID[k])
                Ref_seq.append(Sequence[k])
                Var6 = [Ref_id, Ref_seq]
                Var6 = np.asarray(Var6)
                Var6 = np.transpose(Var6)
                Var5.append(Var6)
Var3 = Var5[-1]


# In[ ]:


In = []
Fi = []
for i in range(s.shape[0]):
    name= s[i,0]
    if(name == 'NC-045512.2/SARS-2/Wuhan-Hu-1/CompleteGenome'):
        continue
    else:
        for j in range(len(List)):
            if(name == List[j]):
                print(name)
                test_str = str(s[i,1])
                res = None
                temp = re.search(r'[a-z]', test_str, re.I)
                if temp is not None:
                    res = temp.start()
                    In.append(res+1)
                    fin = res + Length_of_Sequence[i]
                    Fi.append(fin)
In = np.asarray(In)
Fi = np.asarray(Fi)
smallest = np.min(In)
largest = np.max(Fi)


# In[ ]:


df = pd.DataFrame(s, columns=["ID", "Sequence"])
df.to_csv("D:\lib\mi_RNA\Sets\Seq_{0}-{1}.csv".format(smallest-1, largest), index=False)
Count[smallest:largest] = 0


# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:


X[0,1]


# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:




