In [1]:
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


/home/sophie/tensorflow/venv/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88
  return f(*args, **kwds)
/home/sophie/tensorflow/venv/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88
  return f(*args, **kwds)
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-a5d8d68a8212> in <module>()
      4 import scipy.io as sio
      5 import scipy.optimize
----> 6 from Tkinter import Tk
      7 from tkFileDialog import askdirectory
      8 import libtiff

ImportError: No module named 'Tkinter'

Get folder


In [36]:
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/test/100622ss2

In [37]:
path=foldername

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

In [39]:
Dataname


Out[39]:
'100622ss2'

In [40]:
Dataname='100622ss'

Open the images


In [41]:
t = libtiff.TiffFile(path+'/'+Dataname+'-0001.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(4)+'.tif') 
    #t = libtiff.TiffFile(path+fn) 
    tt = t.get_tiff_array()
    data[:,:,:,i]=tt[:][:][:]
    t.close()
    i=i+1


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-41-c77fdc6366f5> in <module>()
      7 for i in range(len(os.listdir(path))):
      8 #for fn in os.listdir(path):
----> 9     t = libtiff.TiffFile(path+'/'+Dataname+'-'+str(i+1).zfill(4)+'.tif')
     10     #t = libtiff.TiffFile(path+fn)
     11     tt = t.get_tiff_array()

/usr/local/lib/python2.7/dist-packages/libtiff/tiff_file.pyc in __init__(self, filename, mode, first_byte, verbose, local_cache, use_memmap)
    103                 raise NotImplementedError(`mode`)
    104             if not os.path.isfile (filename):
--> 105                 raise ValueError ('file does not exists')
    106             if not os.stat(filename).st_size:
    107                 raise ValueError ('file has zero size')

ValueError: file does not exists

In [42]:
i


Out[42]:
6306

In [43]:
S=data.shape
S


Out[43]:
(40, 206, 204, 6307)

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

Calculate average time series


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

In [45]:
plt.plot(M)


Out[45]:
[<matplotlib.lines.Line2D at 0x7faee1d0fdd0>]

Get approxiamte on and off times


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


Out[46]:
532

Model for fitting onset and offset


In [47]:
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 [48]:
Ms=M[range(liston[0]-8,liston[0]+8)]

In [49]:
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 [50]:
liston[0]-8


Out[50]:
524

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

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


532.334019816

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


533

In [54]:
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 [55]:
Ms=M[range(liston[len(liston)-1]-6,liston[len(liston)-1]+6)]

In [56]:
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 [57]:
res = scipy.optimize.minimize(Sq,x0=[4,3,6,-1])

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


6165.89252714
6165

In [59]:
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()


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


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

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


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

In [62]:
print(TimeFile)


/home/sophie/Downloads/Data100622_.csv

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


---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-63-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/Data100622_.csv'

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

In [ ]:
plt.plot(Timespl)

In [ ]:
max(Timespl)

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

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

In [ ]:
TimeOnFinal=TimeOn-Tinit

In [ ]:
D4.shape

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

In [ ]: