diff --git a/analysis/Makefile b/analysis/Makefile index 6362ded..3323cd0 100644 --- a/analysis/Makefile +++ b/analysis/Makefile @@ -1,4 +1,4 @@ -DATADIR := /home/shomu/DATA/919/919_1_So1 +DATADIR := /home/shomu/DATA/G33/G33_11_So1/ all: python3 ./analyze_trial.py -d $(DATADIR) -o /tmp/results -c ./mouse_eye.xml #--plot diff --git a/analysis/analyze_trial.py b/analysis/analyze_trial.py index ae2cb69..3c370cb 100755 --- a/analysis/analyze_trial.py +++ b/analysis/analyze_trial.py @@ -15,16 +15,18 @@ import numpy as np import config import multiprocessing -from collections import defaultdict +import scipy.interpolate as sci import matplotlib as mpl import matplotlib.pyplot as plt try: - mpl.style.use(['bmh', 'fivethirtyeight']) + # mpl.style.use(['bmh', 'fivethirtyeight']) + mpl.style.use(['bmh']) except Exception as e: pass trial_data_ = [] kwargs_ = {} +cmap_ = 'jet' def tick_for_label(label, labels, ticks): @@ -64,11 +66,9 @@ def process(**kwargs): global trial_data_ datadir = kwargs['datadir'] print('[INFO] Processing %s' % datadir) - resdir = kwargs.get('outdir', os.path.join(datadir, config.tempdir)) if not os.path.exists(resdir): os.makedirs(resdir) - tiffs = [] for d, sd, fs in os.walk(datadir): for f in fs: @@ -76,6 +76,7 @@ def process(**kwargs): if ext in ['tiff', 'tif']: tiffs.append(os.path.join(d, f)) + assert len(tiffs)>0, "No tiff file found" generate_pickels(tiffs, resdir) for f in sorted(tiffs): pickleFile = os.path.join(resdir, os.path.basename('%s.pickle' % f)) @@ -89,26 +90,18 @@ def process(**kwargs): outfile = os.path.join(resdir, 'summary.png') plot_trial_data(trial_data_, datadir, outfile) - # Ploting using trial type. - groups = defaultdict(list) - for f, res in trial_data_: - groups[res.get('trial_type', 'UNKNOWN')].append((f, res)) - - for gname in groups.keys(): - print('[INFO] Plotting for %s' % gname) - ext = gname.replace(' ', '_') - outfile = os.path.join(resdir, 'summary_%s.png' % ext) - data = groups[gname] - plot_trial_data(data, resdir, outfile) - +def normalize(mat, offset, scale): + # Normalize the data. + mat = mat - offset + mat /= scale + return mat + def plot_trial_data(trial_data_, trialdir, outfile): times, allBlinks, probeTrial = [], [], [] for i, (f, d) in enumerate(trial_data_): tvec = d['time'] cs = d['cs'] - trialType = d.get('trial_type', 'UNKNOWN') - print('[INFO] Trial type is %s' % trialType) tvec = list(map(lambda x: (x - cs[0]).total_seconds(), tvec)) duration = 1000 * (tvec[-1] - tvec[0]) if duration < 900: @@ -124,119 +117,67 @@ def plot_trial_data(trial_data_, trialdir, outfile): tmins.append(t[0]) tmaxs.append(t[-1]) - minT, maxT = np.mean(tmins), np.mean(tmaxs) - newTVec = np.linspace(minT, maxT, len(allBlinks[-1])) + minT, maxT = np.max(tmins), np.min(tmaxs) + newTVec = np.linspace(minT, maxT, 300) - img, probeImg = [], [] + csImg, img, probeImg = [], [], [] alignedData = [] for i, (tvec, yvec) in enumerate(zip(times, allBlinks)): - row = np.interp(newTVec, tvec, yvec) + row = sci.interp1d(tvec, yvec, kind='cubic')(newTVec) + alignedData.append(row) if i in probeTrial: probeImg.append(row) else: - img.append(row) - alignedData.append(zip(newTVec, row)) - - # Separate probe trials. - probeData, otherData = [], [] - for i, row in enumerate(alignedData): - if i in probeTrial: - probeData.append(row) - else: - otherData.append(row) - + csImg.append(row) + + alignedData = np.array(alignedData) + baseLineIndex = np.where((newTVec>0.05) & (newTVec<0.2))[0] + blData = alignedData[:,baseLineIndex] + blMean, blStd = np.mean(blData), np.std(blData) + # Similarly between 500 to 800 is our lage signal. + blinkIndex = np.where((newTVec>0.5)&(newTVec<0.7)) + blinkData = alignedData[:,blinkIndex] + blinkMean, blinkStd = np.mean(np.max(blinkData, axis=2)), np.std(blinkData) + print("[INFO ] Baseline: Mean %.3f +/- %.3f" % (blMean, blStd)) + print("[INFO ] Blink: Mean %.3f +/- %.3f" % (blinkMean, blinkStd)) + + # Normalize the data. + normOffset = blMean - blStd + normScale = blinkMean - normOffset + alignedData = normalize(alignedData, normOffset, normScale) + print('No of probe trials : %d' % len(probeImg)) print('No of other trials: %s' % len(img)) - plt.figure(figsize=(12,8)) - ax1 = plt.subplot(221) + plt.figure(figsize=(12,5)) + ax1 = plt.subplot(121) + ax1.set_ylabel('# Trial') ax1.grid(False) - im = ax1.imshow(img, interpolation='none', aspect='auto', cmap='viridis') - plt.colorbar(im, ax=ax1) - plt.title('CS+') + im = ax1.imshow(alignedData, interpolation='none', aspect='auto', cmap=cmap_) + cbar = plt.colorbar(im, ax=ax1) + cbar.set_ticks([0, 1]) + cbar.set_ticklabels(['Open', 'Close']) + cbar.update_ticks() + plt.title('CS+ and PROBE') ticks, labels = computeXTicks(newTVec, tstep=200) - plt.xticks(ticks, ['%d' % x for x in labels]) + plt.xticks(ticks, ['%d'%x for x in labels]) plt.xlabel('Time (ms)') - # Collect for final summary. - summaryData = {} - meanOfTrials = np.mean(img, axis=0) - stdOfTrials = np.std(img, axis=0) - summaryData['CS+'] = (meanOfTrials, stdOfTrials) - ax3 = plt.subplot(223, sharex=ax1) - idx = range(len(meanOfTrials)) - plt.plot(idx, meanOfTrials, color='blue', label='CS+') - plt.fill_between( - idx, meanOfTrials - stdOfTrials, meanOfTrials + stdOfTrials, color='blue', alpha=0.2 - ) - - ax2 = plt.subplot(222, sharex=ax1) - ax2.grid(False) - if len(probeImg) > 0: - print("[INFO ] Plotting PROBE trials.") - im = ax2.imshow(probeImg, interpolation='none', - aspect='auto', cmap='viridis' - ) - ax2.set_title('Probe') - plt.colorbar(im, ax=ax2) - ax2.set_xlabel('Time (ms)') - - # Compute performance index. - perfs = compute_performance(alignedData) - pI, piList = compute_performance_index(perfs) - - ax3 = plt.subplot(223, sharex=ax1) - if len(probeImg) > 0: - meanOfProbeTrials = np.mean(probeImg, axis=0) - stdOfProbeTrials = np.std(probeImg, axis=0) - idx = range(len(meanOfProbeTrials)) - ax3.plot(idx, meanOfProbeTrials, color='red', label='Probe') - ax3.fill_between(idx, meanOfProbeTrials - stdOfProbeTrials - , meanOfProbeTrials + stdOfProbeTrials, color='red', alpha=0.2 - ) - ax3.legend(framealpha=0.1) - summaryData['Probe'] = (meanOfProbeTrials, stdOfProbeTrials) - plt.xlabel('Time (ms)') - - # Plot the normalized curves - ax4 = plt.subplot(224, sharex=ax1) - csM, csU = summaryData['CS+'] - baseline = np.mean(csM[:20]) - y = baseline - csM - normFact = 1.0 / y.max() - for l in summaryData: - ym, yu = summaryData[l] - ym -= baseline - ym = np.abs(ym) - ym *= normFact - yerr = yu * normFact - ax4.plot(idx, ym, label=l) - ax4.legend(framealpha=0.1) - ax4.fill_between(idx, ym - yerr, ym + yerr, alpha=0.2) - - # Mark CS and PUFF areas - x1, x2 = tick_for_label( - 0, labels, ticks), tick_for_label(50, labels, ticks) - x3, x4 = tick_for_label( - 300, labels, ticks), tick_for_label(350, labels, ticks) - ax4.plot([x1, x2], [-0.2, -0.2], color='black') - ax4.text(x1, -0.35, 'CS') - ax4.set_xlim(xmin = tick_for_label( -200, labels, ticks ) ) - ax4.set_yticks([0, 0.5, 1.0], [0, 0.5, 1.0]) - ax4.text(x3, -0.35, 'PUFF') - ax4.set_xlabel('Time (ms)') - - ax4.plot([x3, x4], [-0.2, -0.2], color='black') - ax4.set_title('FEC') - - plt.tight_layout(pad=4) - trialName = list(filter(None, trialdir.split('/')))[-1] - ax4.set_xlabel('Time (ms)') - plt.suptitle(r'Trial: %s' % trialName, x=0.1) + ## Collect for final summary. + ax2 = plt.subplot(122) + csMat, probeMat = np.array(csImg), np.array(probeImg) + csMat = normalize(csMat, normOffset, normScale) + probeMat = normalize(probeMat, normOffset, normScale) + for mat, c, label in zip((csMat,probeMat), ('blue','red'), ('CS+','PROBE')): + Y = np.mean(mat, axis=0) + Yerr = np.std(mat, axis=0) + ax2.plot(1000*newTVec, Y, color=c, label=label) + ax2.fill_between(1000*newTVec, Y-Yerr, Y+Yerr, color=c, alpha=0.2) + plt.legend(loc='best', framealpha=0.4) + plt.tight_layout(pad=2) plt.savefig(outfile) plt.close() print('Wrote summary to %s' % outfile) - def compute_performance_index(perfs): yesOrNoList = [] yesTrial = 0.0 @@ -248,32 +189,11 @@ def compute_performance_index(perfs): yesOrNoList.append(False) return yesTrial / len(yesOrNoList), yesOrNoList - -def compute_baseline(d): - baseline = filter(lambda x: x[0] < 0 and x[0] > -0.200, d) - signal = list(map(lambda x: x[1], baseline)) +def compute_baseline(T, Y): + # x[0] is time. Upto 200ms + signal = [ y for (t, y) in zip(T, Y) if (t> 0.050 and t < 0.200)] return np.mean(signal), np.std(signal) - -def compute_learning(d, baseline): - tsignal = filter(lambda x: x[0] > 0.0 and x[0] < 0.300, d) - # Subtract mean of baseline i.e. baseline. - signal = list(map(lambda x: abs(x[1] - baseline[0]), tsignal)) - # Return mean and std of signal and variance of baseline. - if len(signal) == 0: - return 0, 0, baseline - return max(signal), np.std(signal), baseline[1] - - -def compute_performance(data): - learnings = [] - for d in data: - baseline = compute_baseline(d) - learning = compute_learning(d, baseline) - learnings.append(learning) - return learnings - - def main(**kwargs): global kwargs_ kwargs_ = kwargs