In [1]:
clear all




In [2]:
import nibabel as nib
import os
import numpy as np
import scipy.io as sio
import scipy.optimize
from Tkinter import Tk
from tkFileDialog import askdirectory
import libtiff 
import matplotlib.pyplot as plt
%matplotlib inline

Get folder


In [3]:
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
foldername = askdirectory() # show an "Open" dialog box and return the path to the selected file
print(foldername)


/media/sophie/100250/100250ss2

In [4]:
path=foldername

In [5]:
A=foldername.split('/')
Dataname=A[-1]

In [6]:
Dataname


Out[6]:
'100250ss2'

Open the images


In [7]:
t = libtiff.TiffFile(path+'/'+Dataname+'-00001.tif') 
tt = t.get_tiff_array() 
t.close()
S=tt.shape
data=np.zeros([S[0],S[1],S[2],len(os.listdir(path))])
#for i in range(1,15000):
for i in range(len(os.listdir(path))):       
#for fn in os.listdir(path):
    t = libtiff.TiffFile(path+'/'+Dataname+'-'+str(i+1).zfill(5)+'.tif') 
    #t = libtiff.TiffFile(path+fn) 
    tt = t.get_tiff_array()
    data[:,:,:,i]=tt[:][:][:]
    t.close()
    i=i+1

In [8]:
S=data.shape
S


Out[8]:
(40, 208, 210, 341)

Find end of onset of light and begining of offset (to align to behavior)

Calculate average time series


In [9]:
M=np.mean(np.mean(np.mean(data,0),0),0)
Mav=M.mean()

In [10]:
plt.plot(M,'+')
#plt.axis([-1,50,0,1.5])


Out[10]:
[<matplotlib.lines.Line2D at 0x7f80f60bc850>]

Get approxiamte on and off times


In [11]:
liston=[i for i in range(len(M)) if M[i]>Mav*0.7]
liston[0]


Out[11]:
21

Model for fitting onset and offset


In [12]:
def model(x,a,b,c,d):
    if x<a:
        return b
    elif x<c:
        return b+(x-a)*d
    else:
        return (c-a)*d+b

Model onset and find precise onset time


In [13]:
Ms=M[range(liston[0]-8,liston[0]+8)]

In [14]:
def Sq(X):
    return sum([(model(i,X[0],X[1],X[2],X[3])-Ms[i])**2 for i in range(len(Ms))])

In [15]:
liston[0]-8


Out[15]:
13

In [16]:
res = scipy.optimize.minimize(Sq,x0=[7,0.3,9,0.7])

In [17]:
ON=liston[0]-8+res.x[2]
print(ON)


20.9996308822

In [18]:
ONint=np.int(np.ceil(ON))
#ONint=1
print(ONint)


21

In [19]:
plt.plot(np.squeeze(M[range(liston[0]-8,liston[0]+8)]),'+')
plt.plot(np.arange(0,len(Ms),0.1),[model(i,res.x[0],res.x[1],res.x[2],res.x[3]) for i in np.arange(0,len(Ms),0.1)])
plt.show()


Model offset and find precise offset time


In [20]:
Ms=M[range(liston[len(liston)-1]-6,liston[len(liston)-1]+6)]

In [21]:
def Sq(X):
    return sum([(model(i,X[0],X[1],X[2],X[3])-Ms[i])**2 for i in range(len(Ms))])

In [22]:
res = scipy.optimize.minimize(Sq,x0=[7,3,9,-1])

In [23]:
OFF=liston[len(liston)-1]-6+res.x[0]
#OFF=liston[len(liston)-1]
print(OFF)
OFFint=np.int(np.floor(OFF))
print(OFFint)


296.997721894
296

In [24]:
plt.plot(np.squeeze(Ms),'+')
plt.plot(np.arange(0,len(Ms),0.1),[model(i,res.x[0],res.x[1],res.x[2],res.x[3]) for i in np.arange(0,len(Ms),0.1)])
plt.show()


Open images times


In [25]:
TimeFile='/home/sophie/Downloads/Data'+''.join([Dataname[i] for i in range(6)])+'_.csv'

In [26]:
print(TimeFile)


/home/sophie/Downloads/Data100250_.csv

In [27]:
Listfile = open(TimeFile, 'r')
ListTime = [line.split('\n')[0] for line in Listfile.readlines()]


---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-27-842fa942eb02> in <module>()
----> 1 Listfile = open(TimeFile, 'r')
      2 ListTime = [line.split('\n')[0] for line in Listfile.readlines()]

IOError: [Errno 2] No such file or directory: '/home/sophie/Downloads/Data100250_.csv'

In [67]:
Timespl=[float(ListTime[i].split(',')[2]) for i in range(1,len(ListTime))]

In [68]:
Timespl[12]


Out[68]:
0.480018

Get times corresponding to images during light on (excitation light completely on : t=0)


In [69]:
print(ONint)
print(OFFint)
print(ON)


24
1999
23.9944316521

In [70]:
TimeOn=[Timespl[i] for i in range(ONint,(OFFint+1))]

In [71]:
Tinit=(ON-(ONint-1))*(Timespl[ONint]-Timespl[ONint-1])+Timespl[ONint-1]

In [72]:
Toff=(OFFint+1-OFF)*(Timespl[OFFint+1]-Timespl[OFFint])+Timespl[OFFint]

In [73]:
Toff-Tinit


Out[73]:
79.006954844511824

In [74]:
Timespl[ONint]-Timespl[ONint-1]


Out[74]:
0.03999200000000003

In [75]:
TimeOn[0]-Tinit


Out[75]:
0.00022268937078862017

In [76]:
import numpy as np

In [77]:
TimeOnFinal=np.array(TimeOn)-Tinit

In [78]:
sio.savemat('/home/sophie/Desktop/'+Dataname+'TimeFluoOn.mat', {'TimeFluoOn':TimeOnFinal})

Keep only the frames for which the excitation is on and save


In [28]:
D4=np.transpose(data[:,:,:,range(ONint,(OFFint+1))],(2,1,0,3))
nim=nib.Nifti1Image(D4,np.eye(4))
nib.save(nim,'/home/sophie/Desktop/'+Dataname+'on.nii.gz')

In [ ]: