from fretbursts import *

sns = init_notebook()

"""
Explanation: FRETBursts - ns-ALEX example
This notebook is part of a tutorial series for the FRETBursts burst analysis software.

For a step-by-step introduction to FRETBursts usage please refer to 
us-ALEX smFRET burst analysis.
In this notebook we present a typical FRETBursts
workflow for ns-ALEX smFRET burst analysis. 

While FRETBursts does not specifically includes functions for fitting 
TCSPC fluorescence decays, a fitting with exponential decays and 
IRF deconvolution can be easily performed using standard python libraries. 
For an example and a brief discussion see the notebook 
Lifetime decay fit.
Loading FRETBursts
End of explanation
"""


url = 'http://files.figshare.com/2182602/dsdna_d7_d17_50_50_1.hdf5'

download_file(url, save_dir='./data')

filename = './data/dsdna_d7_d17_50_50_1.hdf5'
filename

"""
Explanation: Downloading the sample data file
The full list of smFRET measurements used in the FRETBursts tutorials 
can be found on Figshare.
Here we download the ns-ALEX data-file and put it in a folder 
named data, inside the notebook folder. 
For this purpose we use the download_file function provided 
by FRETBursts:
End of explanation
"""


# filename = OpenFileDialog()
# filename

import os
if os.path.isfile(filename):
    print("Perfect, I found the file!")
else:
    print("Sorry, I can't find the file:\n%s" % filename)

"""
Explanation: Selecting a data file
Alternatively you can use an open-file dialog in order to select a data file:
End of explanation
"""


d = loader.photon_hdf5(filename)
#d = loader.nsalex(fname)

d.time_max

d.det_t

print("Detector    Counts")
print("--------   --------")
for det, count in zip(*np.unique(d.det_t, return_counts=True)):
    print("%8d   %8d" % (det, count))

#d.add(A_ON=(200, 1500), D_ON=(1750, 3200), det_donor_accept=(4, 6))

d.nanotimes_t

bpl.plot_alternation_hist(d)

"""
Explanation: Load the selected file
Here we load the file and we set the alternation parameters:
End of explanation
"""


loader.alex_apply_period(d)

"""
Explanation: Execute the previous 2 cells until you get a satisfying 
selection for the excitation periods. Then run the following 
to apply the parameters:
End of explanation
"""


d.calc_bg(fun=bg.exp_fit, time_s=30, tail_min_us='auto', F_bg=1.7)

dplot(d, timetrace_bg)

dplot(d, timetrace)
xlim(1, 2)
ylim(-50, 50)

d.burst_search()

ds = d.select_bursts(select_bursts.size, th1=30)

alex_jointplot(ds)

ds.leakage = 0.05

alex_jointplot(ds)

dplot(ds, hist_fret, show_kde=True)

"""
Explanation: Burst search and selection
End of explanation
"""


d.nanotimes

nanotimes = d.nanotimes[0]
nanotimes_d = nanotimes[d.get_D_em()]
nanotimes_a = nanotimes[d.get_A_em()]

"""
Explanation: Nanotimes
The nanotimes for the measurement is saved in the .nanotimes 
attribute of the Data() object (here either d or ds).
As an example here we get the array of nanotimes for all photons, 
donor emission and acceptor emission:
End of explanation
"""


hist_params = dict(bins=range(4096), histtype='step', alpha=0.6, lw=1.5)
hist(nanotimes, color='k', label='Total ph.', **hist_params)
hist(nanotimes_d, color='g', label='D. em. ph.', **hist_params)
hist(nanotimes_a, color='r', label='A. em. ph.', **hist_params)
plt.legend()
plt.yscale('log')

"""
Explanation: We can plot the histogram for this 3 nanotimes:
End of explanation
"""


ph_in_bursts_mask = d.ph_in_bursts_mask_ich()

"""
Explanation: We can also select only nanotimes of photons inside bursts. 
Here, as an example, we will use the ds variable that 
contains a selection of bursts.
First we compute a selection mask (a boolean array) for 
photons inside bursts:
End of explanation
"""


bursts_nanotimes_t = nanotimes[ph_in_bursts_mask]
bursts_nanotimes_d = nanotimes[ph_in_bursts_mask * d.get_D_em()]
bursts_nanotimes_a = nanotimes[ph_in_bursts_mask * d.get_A_em()]

"""
Explanation: Then we apply this selection to the nanotimes array. 
To get the donor- and acceptor-emission nanotimes we combine 
the in-bursts selection mask (ph_in_bursts_mask) with 
the donor or acceptor emission mask (that we get with
.get_D_em() and .get_D_em()):
End of explanation
"""


hist_params = dict(bins=range(4096), histtype='step', alpha=0.6, lw=1.5)
hist(bursts_nanotimes_t, color='k', label='Total ph.', **hist_params)
hist(bursts_nanotimes_d, color='g', label='D. em. ph.', **hist_params)
hist(bursts_nanotimes_a, color='r', label='A. em. ph.', **hist_params)
plt.legend()
plt.yscale('log')

"""
Explanation: And, as before, we can histogram the nanotimes:
End of explanation
"""


nanotimes.tofile('nanotimes_t.csv', sep=',\n')  # save in CSV txt format

"""
Explanation: Saving to a file
Saving some of all these arrays to file is straightforward.
Save array to txt comma-separed-values
To save a single array to a file we can use the .tofile method:
End of explanation
"""


from scipy.io import savemat

savemat('bursts_nanotimes.mat', 
        dict(bn_t=bursts_nanotimes_t, 
             bn_d=bursts_nanotimes_d, 
             bn_a=bursts_nanotimes_a,))

"""
Explanation: Save to legacy MATLAB format
To save a set of arrays in MATLAB format  we can use the 
scipy.io.savemat function.
Here we save 3 arrays bursts_nanotimes_t, bursts_nanotimes_d 
and bursts_nanotimes_a to a file called bursts_nanotimes.mat:
End of explanation
"""


