import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
import seaborn as sns


PLASMID_SIZE = 4777 ## Plasmid size used for editing reaction  
TOTAL_TA_SITES = 211 ## Number of TA sites 

#AMPLICON SEQUENCE
AMPLICON ='cagtgaggcacctatctcagcgatctgtctatttcgttcatccatagttgcctgactccccgtcgtgtagataactacgatacgggagggctta'

DCT = 5.9 #Deta CT between Crosslinked and Unscrosslinked plasmid - This was obtained by Qpcr

#CODE
DECIMAL = 4
    
           
prob = round(2**-DCT, DECIMAL)


SITES_per100bp = str(round(TOTAL_TA_SITES/ (PLASMID_SIZE/100),2))

print('HBB_GFP has ' + SITES_per100bp + 'TA sites per 100bp')

TA_SITES = AMPLICON.count('ta')

SITES_per100bp_amplicon =  str(round( TA_SITES * 100/len(AMPLICON),2))


print('Amplicon size :'+ str(len(AMPLICON)))
print('There is ' +str(TA_SITES) + ' TA sites')

print('This amplicon has ' + SITES_per100bp_amplicon + 'TA sites per 100bp')


if float(SITES_per100bp_amplicon) /float(SITES_per100bp ) > 1.5 :
    print ('This amplicon might overestimate the number of crosslink')
elif float(SITES_per100bp_amplicon) /float(SITES_per100bp ) < 0.7 :
    print ('This amplicon might underestimate the number of crosslink')
else : 
    print('This amplicon is appropriate')



print('probability to find (2-Δct) = ' + str(prob))


sequence = [x for x in range(10**(DECIMAL))] 
lo, hi = 0, len(sequence) - 1

while lo <= hi:
    np.random.seed(123)
    mid = (lo + hi) // 2
    P0 = mid/10**(DECIMAL)
    #print(P0)
    P1=1-P0
    L=[]
    for i in range(10000) :
      L.append(np.random.choice(2, size=7, replace=True, p=[P0, P1]))
    SUM =[]
    for i in L :
        SUM.append(sum(i))
    NEWPROB = round(SUM.count(0)/len(SUM),DECIMAL)
    print(NEWPROB)
    if NEWPROB < prob:
        lo = mid + 1
    elif NEWPROB >prob :
        hi = mid - 1
    else:
        print('probability found =' + str(NEWPROB))
        #print('P0 = ' + str(P0))
        break


BINS = [x for x in range(TA_SITES)]
fig, ax = plt.subplots(figsize =(10, 7))
plt.axvline(0, color='red')
plt.text(0,1000, str(round(SUM.count(0)/len(SUM) *100,2))+ '%')
plt.xlabel('Number of Crosslink')
ax.hist(SUM, bins=BINS);
XLINK =round(sum(SUM)/len(SUM),2) 
TOTAL_XLINK = XLINK*TOTAL_TA_SITES/TA_SITES
plt.text(4,ax.get_ylim()[1] -100, 'AVERAGE XLINK per amplicon:' + str(XLINK))


print('##########')

print('The plasmid has around ' + str(round(TOTAL_XLINK,0)) + ' crosslinks')
