From b73d84c23a1e5f0467428b602a577e5ce3702efc Mon Sep 17 00:00:00 2001 From: Dilawar Singh Date: Thu, 21 Mar 2019 12:55:10 +0530 Subject: [PATCH 1/3] track issue #33. --- analysis/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/analysis/Makefile b/analysis/Makefile index 6362ded..613278f 100644 --- a/analysis/Makefile +++ b/analysis/Makefile @@ -1,4 +1,4 @@ -DATADIR := /home/shomu/DATA/919/919_1_So1 +DATADIR := /home/shomu/DATA/G35/G35_1_So1/ all: - python3 ./analyze_trial.py -d $(DATADIR) -o /tmp/results -c ./mouse_eye.xml #--plot + python3 ./analyze_trial.py -d $(DATADIR) -o /tmp/results -c ./mouse_eye.xml --plot From c320eaaeb1100d26188500a465c008293cff3f27 Mon Sep 17 00:00:00 2001 From: Dilawar Singh Date: Thu, 21 Mar 2019 13:58:42 +0530 Subject: [PATCH 2/3] Bit more update #33. --- analysis/Makefile | 2 +- analysis/analyze_trial.py | 62 +++++++++++++++++++++------------------ 2 files changed, 34 insertions(+), 30 deletions(-) diff --git a/analysis/Makefile b/analysis/Makefile index 613278f..7d8462b 100644 --- a/analysis/Makefile +++ b/analysis/Makefile @@ -1,4 +1,4 @@ -DATADIR := /home/shomu/DATA/G35/G35_1_So1/ +DATADIR := /home/shomu/DATA/G35/G35_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..84d7eb3 100755 --- a/analysis/analyze_trial.py +++ b/analysis/analyze_trial.py @@ -19,12 +19,14 @@ 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)) @@ -101,6 +102,13 @@ def process(**kwargs): data = groups[gname] plot_trial_data(data, resdir, outfile) +def normalize(mat): + mat = np.array(mat) + baseline = np.mean(mat[:30]) + mat = mat - baseline + mat = mat / mat.max() + return mat + def plot_trial_data(trial_data_, trialdir, outfile): times, allBlinks, probeTrial = [], [], [] @@ -127,38 +135,36 @@ def plot_trial_data(trial_data_, trialdir, outfile): minT, maxT = np.mean(tmins), np.mean(tmaxs) newTVec = np.linspace(minT, maxT, len(allBlinks[-1])) - img, probeImg = [], [] + csImg, img, probeImg = [], [], [] alignedData = [] + for i, (tvec, yvec) in enumerate(zip(times, allBlinks)): row = np.interp(newTVec, tvec, yvec) + img.append(row) if i in probeTrial: probeImg.append(row) else: - img.append(row) + csImg.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) + # img = normalize(img) + # probeImg = normalize(probeImg) 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) ax1.grid(False) - im = ax1.imshow(img, interpolation='none', aspect='auto', cmap='viridis') + im = ax1.imshow(img, interpolation='none', aspect='auto', cmap=cmap_) plt.colorbar(im, ax=ax1) - plt.title('CS+') + plt.title('CS+ and PROBE') ticks, labels = computeXTicks(newTVec, tstep=200) plt.xticks(ticks, ['%d' % x for x in labels]) plt.xlabel('Time (ms)') # Collect for final summary. summaryData = {} + img = normalize(img) meanOfTrials = np.mean(img, axis=0) stdOfTrials = np.std(img, axis=0) summaryData['CS+'] = (meanOfTrials, stdOfTrials) @@ -174,9 +180,8 @@ def plot_trial_data(trial_data_, trialdir, outfile): if len(probeImg) > 0: print("[INFO ] Plotting PROBE trials.") im = ax2.imshow(probeImg, interpolation='none', - aspect='auto', cmap='viridis' - ) - ax2.set_title('Probe') + aspect='auto', cmap=cmap_) + ax2.set_title('PROBE') plt.colorbar(im, ax=ax2) ax2.set_xlabel('Time (ms)') @@ -186,6 +191,7 @@ def plot_trial_data(trial_data_, trialdir, outfile): ax3 = plt.subplot(223, sharex=ax1) if len(probeImg) > 0: + probeImg = normalize(probeImg) meanOfProbeTrials = np.mean(probeImg, axis=0) stdOfProbeTrials = np.std(probeImg, axis=0) idx = range(len(meanOfProbeTrials)) @@ -201,17 +207,15 @@ def plot_trial_data(trial_data_, trialdir, outfile): ax4 = plt.subplot(224, sharex=ax1) csM, csU = summaryData['CS+'] baseline = np.mean(csM[:20]) - y = baseline - csM + y = csM - baseline normFact = 1.0 / y.max() - for l in summaryData: - ym, yu = summaryData[l] + for l, c in zip(summaryData, ['blue', 'red']): + ym, yerr = summaryData[l] + baseline = np.mean(ym[:20]) ym -= baseline - ym = np.abs(ym) - ym *= normFact - yerr = yu * normFact - ax4.plot(idx, ym, label=l) + ax4.plot(idx, ym, label=l, color=c, alpha=0.8) ax4.legend(framealpha=0.1) - ax4.fill_between(idx, ym - yerr, ym + yerr, alpha=0.2) + ax4.fill_between(idx, ym - yerr, ym + yerr, color=c, alpha=0.1) # Mark CS and PUFF areas x1, x2 = tick_for_label( @@ -219,19 +223,19 @@ def plot_trial_data(trial_data_, trialdir, outfile): 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.text(x1, -0.35, 'CS', fontsize=10) 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.text(x3, -0.35, 'PUFF', fontsize=10) 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) + # plt.suptitle(r'Trial: %s' % trialName, x=0.1) + plt.tight_layout(pad=2) plt.savefig(outfile) plt.close() print('Wrote summary to %s' % outfile) From 47c52e66db602f1ba27bd0ff9dc6789d9326bcdd Mon Sep 17 00:00:00 2001 From: Dilawar Singh Date: Fri, 22 Mar 2019 18:26:07 +0530 Subject: [PATCH 3/3] Modified. --- analysis/Makefile | 4 +- analysis/analyze_trial.py | 182 ++++++++++---------------------------- 2 files changed, 51 insertions(+), 135 deletions(-) diff --git a/analysis/Makefile b/analysis/Makefile index 7d8462b..3323cd0 100644 --- a/analysis/Makefile +++ b/analysis/Makefile @@ -1,4 +1,4 @@ -DATADIR := /home/shomu/DATA/G35/G35_11_So1/ +DATADIR := /home/shomu/DATA/G33/G33_11_So1/ all: - python3 ./analyze_trial.py -d $(DATADIR) -o /tmp/results -c ./mouse_eye.xml --plot + 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 84d7eb3..3c370cb 100755 --- a/analysis/analyze_trial.py +++ b/analysis/analyze_trial.py @@ -15,7 +15,7 @@ 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: @@ -90,33 +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): - mat = np.array(mat) - baseline = np.mean(mat[:30]) - mat = mat - baseline - mat = mat / mat.max() +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: @@ -132,115 +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) csImg, img, probeImg = [], [], [] alignedData = [] - for i, (tvec, yvec) in enumerate(zip(times, allBlinks)): - row = np.interp(newTVec, tvec, yvec) - img.append(row) + row = sci.interp1d(tvec, yvec, kind='cubic')(newTVec) + alignedData.append(row) if i in probeTrial: probeImg.append(row) else: csImg.append(row) - alignedData.append(zip(newTVec, row)) - - # img = normalize(img) - # probeImg = normalize(probeImg) + 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=cmap_) - plt.colorbar(im, ax=ax1) + 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 = {} - img = normalize(img) - 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=cmap_) - 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: - probeImg = normalize(probeImg) - 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 = csM - baseline - normFact = 1.0 / y.max() - for l, c in zip(summaryData, ['blue', 'red']): - ym, yerr = summaryData[l] - baseline = np.mean(ym[:20]) - ym -= baseline - ax4.plot(idx, ym, label=l, color=c, alpha=0.8) - ax4.legend(framealpha=0.1) - ax4.fill_between(idx, ym - yerr, ym + yerr, color=c, alpha=0.1) - - # 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', fontsize=10) - 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', fontsize=10) - ax4.set_xlabel('Time (ms)') - - ax4.plot([x3, x4], [-0.2, -0.2], color='black') - ax4.set_title('FEC') - - 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 @@ -252,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