From f4c3be541ce35d3b52015efbbd886cf4fff5cbef Mon Sep 17 00:00:00 2001 From: megkirch Date: Tue, 20 Sep 2016 15:21:11 -0700 Subject: [PATCH] adding Megan's matlab code to SNL-C --- Intancode_Megan/IntanLFP_lightCSD.asv | 1328 +++++++++++++++++ Intancode_Megan/IntanLFP_lightCSD.m | 1328 +++++++++++++++++ Intancode_Megan/Plotting/make_psth_plot.m | 45 + Intancode_Megan/Plotting/make_raster_plot.asv | 69 + Intancode_Megan/Plotting/make_raster_plot.m | 70 + Intancode_Megan/README.md | Bin 0 -> 32 bytes Intancode_Megan/Tlx_analysis_master.asv | 376 +++++ Intancode_Megan/Tlx_analysis_master.m | 376 +++++ Intancode_Megan/calc_FFI.m | 39 + Intancode_Megan/calc_crosscorrs.m | 62 + Intancode_Megan/get_exp_params.asv | 102 ++ Intancode_Megan/get_exp_params.m | 102 ++ Intancode_Megan/get_lightstim_v2.asv | 207 +++ Intancode_Megan/get_lightstim_v2.m | 209 +++ Intancode_Megan/intan2matlab.m | 213 +++ Intancode_Megan/intan_analysis_master.asv | 114 ++ Intancode_Megan/intan_analysis_master.m | 114 ++ Intancode_Megan/intan_analysis_master_copy.m | 466 ++++++ Intancode_Megan/intan_unit_analysis.asv | 471 ++++++ Intancode_Megan/intan_unit_analysis.m | 472 ++++++ Intancode_Megan/kilo_cluster_plots_opto.m | 611 ++++++++ Intancode_Megan/kilo_spike_analysis.m | 285 ++++ 22 files changed, 7059 insertions(+) create mode 100644 Intancode_Megan/IntanLFP_lightCSD.asv create mode 100644 Intancode_Megan/IntanLFP_lightCSD.m create mode 100644 Intancode_Megan/Plotting/make_psth_plot.m create mode 100644 Intancode_Megan/Plotting/make_raster_plot.asv create mode 100644 Intancode_Megan/Plotting/make_raster_plot.m create mode 100644 Intancode_Megan/README.md create mode 100644 Intancode_Megan/Tlx_analysis_master.asv create mode 100644 Intancode_Megan/Tlx_analysis_master.m create mode 100644 Intancode_Megan/calc_FFI.m create mode 100644 Intancode_Megan/calc_crosscorrs.m create mode 100644 Intancode_Megan/get_exp_params.asv create mode 100644 Intancode_Megan/get_exp_params.m create mode 100644 Intancode_Megan/get_lightstim_v2.asv create mode 100644 Intancode_Megan/get_lightstim_v2.m create mode 100644 Intancode_Megan/intan2matlab.m create mode 100644 Intancode_Megan/intan_analysis_master.asv create mode 100644 Intancode_Megan/intan_analysis_master.m create mode 100644 Intancode_Megan/intan_analysis_master_copy.m create mode 100644 Intancode_Megan/intan_unit_analysis.asv create mode 100644 Intancode_Megan/intan_unit_analysis.m create mode 100644 Intancode_Megan/kilo_cluster_plots_opto.m create mode 100644 Intancode_Megan/kilo_spike_analysis.m diff --git a/Intancode_Megan/IntanLFP_lightCSD.asv b/Intancode_Megan/IntanLFP_lightCSD.asv new file mode 100644 index 0000000..05cebcb --- /dev/null +++ b/Intancode_Megan/IntanLFP_lightCSD.asv @@ -0,0 +1,1328 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% IntanLFP_CSD_v2.m +% Script for extracting LFP data from Intan +%Created 09222015 by Megan A Kirchgessner +% Adapted from LFPv2_latest from Bryan J. Hansen +% mkirchgessner@ucsd.edu +% 5/30/2016 - FILTER CHANGED by MAK - replaced with newfilter.m +% 6/14/2016 - changed to intanphy2matlab_v2; added new code for determining running trials (MAK) +% 8/31/2016 - changed to intan2matlab +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% + + +function IntanLFP_lightCSD(exp_path,exp_type) + %% + +% get necessary data +cd(exp_path) +if exist(sprintf('%s/data.mat',exp_path),'file') + load(sprintf('%s/data.mat',exp_path)) % data from intanphy2matlab.m +else + intan2matlab(exp_path); % data from intanphy2matlab.m + load(sprintf('%s/data.mat',exp_path)) +end + +if ~exist(sprintf('%s/LFP_all.mat',exp_path),'file') + % read in amplifier.dat one channel at a time + v = read_intan_amp(exp_path,num_channels,amp_sr,1); + + % filter LFPs + fRawo_ln = newfilter(v,1000,0); + save('LFP_all.mat','fRawo_ln') +else + load(sprintf('%s/LFP_all.mat',exp_path)) +end + +num_channels = size(fRawo_ln,1); +% get LFPs +disp('Get the LFPs'); +tic +var_name = cell(1,num_channels); +for ch = 1:num_channels + if ch < 10 + var_name{ch} = sprintf('LFP0%d',ch); + else + var_name{ch} = sprintf('LFP%d',ch); + end +end +cont=struct; + +field_file_name = 'fields'; +field_output_dir = fullfile(exp_path, field_file_name); +[~,message]=mkdir(field_output_dir); %#ok +cd(field_output_dir); +fileID2 = fopen('lfps.txt','w'); +for i=1:size(fRawo_ln,1) % number of channels + if i>1 + fprintf(fileID2,'\r\n'); + end + ch=sprintf('%s%d', 'Processing channel: ', i); + disp(ch); + if i<10 + save_lfp=sprintf('%s%d','lfp0', i); + else + save_lfp=sprintf('%s%d','lfp', i); + end + cont(i).sig = fRawo_ln(i,:); + cd(field_output_dir); + fprintf(fileID2,save_lfp); +end +fclose(fileID2); +toc +% clear aux_data lfp data zx + +probetype = input('Did you use NeuroNexus 2x16 probe (1), 1x32 probe (2), 32 channel polytrode (3), or 32 channel linear probe (4)?: ', 's'); +probetype = str2double(probetype); +if probetype == 1 + pos=[29 + 26 + 24 + 21 + 20 + 23 + 25 + 28 + 30 + 18 + 19 + 22 + 32 + 27 + 17 + 31 + 7 + 2 + 15 + 8 + 11 + 10 + 12 + 9 + 6 + 14 + 13 + 3 + 5 + 16 + 4 + 1 + ]; + spacing = 50; % vertical spacing of contacts (in microns) +elseif probetype == 2; + pos= [4 + 5 + 13 + 6 + 12 + 11 + 15 + 7 + 2 + 8 + 10 + 9 + 14 + 3 + 16 + 1 + 17 + 32 + 19 + 30 + 25 + 20 + 24 + 29 + 26 + 21 + 23 + 28 + 18 + 22 + 27 + 31]; + spacing = 20; % vertical spacing of contacts + +elseif probetype == 3; % polytrode(pretending they're on same xplane) + pos = [ 8 % from highest to lowest + 24 + 2 + 29 + 7 + 26 + 15 + 21 + 11 + 23 + 12 + 28 + 6 + 18 + 13 + 22 + 5 + 27 + 4 + 31 + 10 + 20 + 9 + 25 + 14 + 30 + 3 + 19 + 16 + 32 + 1 + 17]; + spacing = 25; % vertical spacing of contacts + +elseif probetype == 4; % linear 32ch + pos = [1 + 17 + 16 + 32 + 3 + 19 + 14 + 30 + 9 + 25 + 10 + 20 + 8 + 24 + 2 + 29 + 7 + 26 + 15 + 21 + 11 + 23 + 12 + 28 + 6 + 18 + 13 + 22 + 5 + 27 + 4 + 31]; + spacing = 25; +end + + + + + + +for i=1:length(var_name) + sig{i}=sprintf('%s%d%s','=cont(',pos(i),').sig'); + evalc([var_name{i}, sig{i}]); % LFPs are ordered from top to bottom! +end + +%% find light onset times during blank trials (when mouse was stationary) +disp('Find timing using PD pulses to est. the Evoked Response Potential (ERP)') +tic +% get average light onset time +[~,~,~,av_light_start] = get_lightstim_v2(exp_path,exp_type); % just to get duration and time of light onset +% get the details of the experiment (trial types, prestim time, etc.) +[prestim,poststim,stimtime,trial_type,IVs] = get_exp_params(exp_path,exp_type); +% identify blank light trials +lightvar = find(strcmp(IVs,'light_bit')); +runvar = find(strcmp(IVs,'running')); +light_blnk = find((trial_type(:,1)==0) & (trial_type(:,lightvar)>=1) & (trial_type(:,runvar)==0)); + +new_re=zeros(1,length(light_blnk)); +disp('Get timestamps of light onset during blank trials') +for i = 1:length(light_blnk) + trials2 (i,1) = find(time_index>=trials(light_blnk(i),1)&time_index<=trials(light_blnk(i),2),1,'first'); % in samples, starting from 1 + trials2 (i,2) = find(time_index>=(time_index(trials2(i,1)))&time_index<=(time_index(trials2(i,1))+2.000),1,'last'); + trial_time(i,:) = trials(light_blnk(i),1):1:trials(light_blnk(i),1)+2000; +end +timing=(time_index(trial_time(1,:))-time_index(trial_time(1,1))-1); + + +%% +disp('Create ERPs for each LFP trials x time'); +% Import electrdoes are reordered based on the Neuronexus probe +ERP01=mean(LFP01(trial_time),1); +ERP02=mean(LFP02(trial_time),1); +ERP03=mean(LFP03(trial_time),1); +ERP04=mean(LFP04(trial_time),1); +ERP05=mean(LFP05(trial_time),1); +ERP06=mean(LFP06(trial_time),1); +ERP07=mean(LFP07(trial_time),1); +ERP08=mean(LFP08(trial_time),1); +ERP09=mean(LFP09(trial_time),1); +ERP10=mean(LFP10(trial_time),1); +ERP11=mean(LFP11(trial_time),1); +ERP12=mean(LFP12(trial_time),1); +ERP13=mean(LFP13(trial_time),1); +ERP14=mean(LFP14(trial_time),1); +ERP15=mean(LFP15(trial_time),1); +ERP16=mean(LFP16(trial_time),1); +ERP17=mean(LFP17(trial_time),1); +ERP18=mean(LFP18(trial_time),1); +ERP19=mean(LFP19(trial_time),1); +ERP20=mean(LFP20(trial_time),1); +ERP21=mean(LFP21(trial_time),1); +ERP22=mean(LFP22(trial_time),1); +ERP23=mean(LFP23(trial_time),1); +ERP24=mean(LFP24(trial_time),1); +ERP25=mean(LFP25(trial_time),1); +ERP26=mean(LFP26(trial_time),1); +ERP27=mean(LFP27(trial_time),1); +ERP28=mean(LFP28(trial_time),1); +ERP29=mean(LFP29(trial_time),1); +ERP30=mean(LFP30(trial_time),1); +ERP31=mean(LFP31(trial_time),1); +ERP32=mean(LFP32(trial_time),1); +%----------------------------% +if probetype == 1 + aux_shk1=vertcat(ERP01,ERP02,ERP03,ERP04,ERP05,ERP06,ERP07,ERP08,ERP09,ERP10,ERP11,ERP12,ERP13,ERP14,ERP15,ERP16); + aux_shk2=vertcat(ERP17,ERP18,ERP19,ERP20,ERP21,ERP22,ERP23,ERP24,ERP25,ERP26,ERP27,ERP28,ERP29,ERP30,ERP31,ERP32); + % scale factor + ERP_shk1=(aux_shk1/(1*10^8))*(1*10^6);% Scale factor for ERP <<<< MAYBE CHANGE THIS + ERP_shk2=(aux_shk2/(1*10^8))*(1*10^6);% Scale factor for ERP +% //elseif probetype ==2 +else + aux_shk1 = vertcat(ERP01,ERP02,ERP03,ERP04,ERP05,ERP06,ERP07,ERP08,ERP09,ERP10,ERP11,ERP12,ERP13,ERP14,ERP15,ERP16,... + ERP17,ERP18,ERP19,ERP20,ERP21,ERP22,ERP23,ERP24,ERP25,ERP26,ERP27,ERP28,ERP29,ERP30,ERP31,ERP32); + % scale factor + ERP_shk1=(aux_shk1/(1*10^8))*(1*10^6);% Scale factor for ERP <<<< MAYBE CHANGE THIS +% elseif probetype ==3 +% % aux_shk1 = vertcat(ERP02,ERP04,ERP06,ERP08,ERP10,ERP12,ERP14,ERP16,... +% % ERP18,ERP20,ERP22,ERP24,ERP26,ERP28,ERP30,ERP32); +% % aux_shk2 = vertcat(ERP01,ERP03,ERP05,ERP07,ERP09,ERP11,ERP13,ERP15,... +% % ERP17,ERP19,ERP21,ERP23,ERP25,ERP27,ERP29,ERP31); +% aux_shk1 = vertcat(ERP01,ERP02,ERP03,ERP04,ERP05,ERP06,ERP07,ERP08,ERP09,ERP10,ERP11,ERP12,ERP13,ERP14,ERP15,ERP16,... +% ERP17,ERP18,ERP19,ERP20,ERP21,ERP22,ERP23,ERP24,ERP25,ERP26,ERP27,ERP28,ERP29,ERP30,ERP31,ERP32); +% ERP_shk1=(aux_shk1/(1*10^8))*(1*10^6);% Scale factor for ERP <<<< MAYBE CHANGE THIS +% % scale factor +% % ERP_shk1=(aux_shk1/(1*10^8))*(1*10^6);% Scale factor for ERP <<<< MAYBE CHANGE THIS +% ERP_shk2=(aux_shk2/(1*10^8))*(1*10^6);% Scale factor for ERP + +end + +% clear aux_shk1 aux_shk2 + +%% Plot and clean up ERP figures +if probetype ==1 + ERP_shk1=clean_ERP(ERP_shk1,timing); + ERP_shk2=clean_ERP(ERP_shk2,timing); +else + ERP_shk1=clean_ERP(ERP_shk1,timing); +end + +% normalize ERPs by prestim period + +%% The final ERP figure is sent to the screen to view and now the next section deals +% with the CSD plotter and average analysis +pause(5); +file_name = 'CSD_LFPdata'; +save (file_name); +disp ('saving mat') +HC=CSDplotter; +disp ('Use CSD plotter') +clc +pause(20) +disp ('ERP: normal LFP time series w/o moving trials') +reply = input('Ready to continue? Y/N: ','s'); +if reply == 'Y'; +close all; +disp ('Open CSD matrix file for Shank 1') +filename = uigetfile; +load (filename); +CSD_matrix1=CSD_matrix; +fprintf('%s%s','Filename: ',filename); +close all +clc +disp ('Plot final ERP and CSD side by side') +X2=timing.*1000; +clear CSD_matrix +if probetype ==1 + disp ('Open CSD matrix file for Shank 2') + filename = uigetfile; + load (filename); + CSD_matrix2=CSD_matrix; + fprintf('%s%s','Filename: ',filename); + close all + clc +end +disp ('Plot final ERP and CSD side by side') +%% + FontName = 'MyriadPro-Regular'; % or choose any other font + FontSize = 14; + figure_width = 14; + figure_height = 10; + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + ERP_fig1 = figure; + set(ERP_fig1,'Visible', figuresVisible) + set(ERP_fig1, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(ERP_fig1, 'PaperPositionMode', 'auto'); + set(ERP_fig1, 'Color', [1 1 1]); % Sets figure background + set(ERP_fig1, 'Color', [1 1 1]); % Sets axes background + hsp = subplot(1,1,1, 'Parent', ERP_fig1); + set(hsp,'Position',[0.15 0.17 0.75 0.80]); + plot (X2, ERP_shk1'); + axis on; % display axis + axis tight; % no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [.015 .015] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + yaxis=ylim; + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k','linewidth', 1); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Amplitude (uV)'; + % save handles to set up label properties + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + fig_title=sprintf('%s','ERP 1 '); + set(gca,'Layer', 'top'); + drawnow + %export_fig (fig_title, '-pdf') + export_fig (fig_title, '-png','-r600','-zbuffer'); + + %% + if probetype ==1 + + FontName = 'MyriadPro-Regular'; % or choose any other font + FontSize = 14; + figure_width = 14; + figure_height = 10; + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + ERP_fig2 = figure; + set(ERP_fig2,'Visible', figuresVisible) + set(ERP_fig2, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(ERP_fig2, 'PaperPositionMode', 'auto'); + set(ERP_fig2, 'Color', [1 1 1]); % Sets figure background + set(ERP_fig2, 'Color', [1 1 1]); % Sets axes background + hsp = subplot(1,1,1, 'Parent', ERP_fig2); + set(hsp,'Position',[0.19 0.19 0.75 0.80]); + plot (X2, ERP_shk2'); + axis on; % display axis + axis tight; % no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [.015 .015] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + yaxis=ylim; + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k','linewidth', 1); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Amplitude (uV)'; + % save handles to set up label properties + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + fig_title=sprintf('%s','ERP 2 '); + set(gca,'Layer', 'top'); + drawnow + % export_fig (fig_title, '-pdf') + export_fig (fig_title, '-png','-r600','-opengl') + end +%% +if probetype ==1 + left_channels= fliplr([1:1:size(ERP_shk1,1)]); + right_channels= fliplr([17:1:(size(ERP_shk2,1)+16)]); + channels={left_channels';right_channels'}'; +else + left_channels= fliplr([1:1:size(ERP_shk1,1)]); + channels = {left_channels'}; +end +FontName = 'MyriadPro-Regular'; % or choose any other font + FontSize = 14; + figure_width = 28; + figure_height = 14; + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + ERP_stacked=figure;% figure('units', 'normalized', 'outerposition', [0 0 1 1]); + set(ERP_stacked, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(ERP_stacked, 'PaperPositionMode', 'auto'); + set(ERP_stacked, 'Color', [1 1 1]); % Sets figure background + set(ERP_stacked, 'Color', [1 1 1]); % Sets axes background + hsp = subplot(1,1,1, 'Parent', ERP_stacked); + set(hsp,'Position',[0.15 0.17 0.75 0.80]); +for ii = 1:size(channels,2) + subplot(1, 2, ii); + depth = 0; + depth_spacing = 50; + max_y = 0; + hold all; + % for each channel + chan_legends = {}; + for j=1:length(channels{ii}); + for i = channels{ii}(j) + if ii==1 + averaged_ERP= ERP_shk1(i,:); + elseif ii==2; + i=i-16; + averaged_ERP= ERP_shk2(i,:); + end + plot(X2, averaged_ERP*depth_spacing + depth,'LineWidth',2); + max_y= max_y + max(averaged_ERP); + depth= depth + depth_spacing; + chan_legends= [chan_legends, num2str(i)]; + end +end + yaxis=ylim; + set(gca,'Ylim',[-depth_spacing depth_spacing*length(channels{ii})]) + if ii==1 + set(gca, 'ytick', [0:depth_spacing:(depth_spacing*length(channels{ii}))-depth_spacing],'tickdir','out','yticklabel',[left_channels]); + axis on; % display axis + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [0 0] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number (Sup-->Deep)'; + % save handles to set up label properties + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',2); + % poststimulus onset + elseif ii==2; + set(gca, 'ytick', [0:depth_spacing:(depth_spacing*length(channels{ii}))-depth_spacing],'tickdir','out','yticklabel',[right_channels]); + axis on; % display axis + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [0 0] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number (Sup-->Deep)'; + % save handles to set up label properties + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',2); + end +end +fig_title=sprintf('%s','ERP Stacked '); +set(gca,'Layer', 'top'); +drawnow +%export_fig (fig_title, '-pdf') + export_fig (fig_title, '-png','-r600','-zbuffer'); + +%% Plot CSDs + +% CSD_matrix_all = CSD_matrix1; +% CSD_matrix1 = CSD_matrix_all(2:2:end,:); +% CSD_matrix2 = CSD_matrix_all(1:2:end,:); + + figure_width = 12; + figure_height = 10; + FontSize = 12; + FontName = 'MyriadPro-Regular'; % or choose any other font + % --- setup plot windows + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + CSD_fig1 = figure; + set(CSD_fig1,'Visible', figuresVisible) + set(CSD_fig1, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(CSD_fig1, 'PaperPositionMode', 'auto'); + set(CSD_fig1, 'Renderer','Zbuffer'); + set(CSD_fig1, 'Color', [1 1 1]); % Sets figure background + set(CSD_fig1, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', CSD_fig1); + set(hsp,'Position',[0.15 0.15 0.60 0.80]); + colorDepth = 1000; + colormap(flipud(jet(colorDepth))); +% pcolor(X2, 1:1:size(CSD_matrix1,1), CSD_matrix1); +% imagesc(X2,[],CSD_matrix1) + imagesc(X2(976:1226),[],CSD_matrix1(:,976:1226)) + shading interp; % do not interpolate pixels + axis on; % display axis + axis tight;% no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'in' , ... + 'Ydir' , 'reverse', ... + 'TickLength' , [.01 .01] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'yticklabel',1:1:size(CSD_matrix1,1), 'Ytick', 1:1:size(CSD_matrix1,1)); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number'; + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Shank 1 '); + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); +% caxis([min(min(CSD_matrix1)) max(max(CSD_matrix1))]); + zLabelText = 'nA / mm^3'; % greek letters in LaTeX Syntax + hcb = colorbar('eastoutside'); + h_bar = findobj(gcf,'Tag','Colorbar'); + initpos = get(h_bar,'Position'); + set(h_bar, ... + 'Position',[initpos(1)+initpos(3)*2.5 initpos(2)+initpos(4)*0.3 ... + initpos(3)*0.4 initpos(4)*0.4]); + hcLabel = ylabel(hcb,zLabelText); + set(hcb,'YTickLabel',{'Sink','Source'}, 'Ytick', [min(min(CSD_matrix1)) max(max(CSD_matrix1))]) + set(hcb, ... + 'Box' , 'on' , ... + 'TickDir' , 'in' , ... + 'TickLength' , [.010 .010] , ... + 'LineWidth' , 0.6); + set([gca, hcb, hXLabel, hYLabel, hcLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + ylabh=get(hcb,'Ylabel'); + set(ylabh,'Position',get(ylabh,'Position')-[8 0 0]); + set(gca,'Layer', 'top'); + drawnow +% % superimpose ERPs +% ii=1; +% depth = 1; +% depth_spacing = 1; +% max_y = 0; +% hold all; +% % for each channel +% chan_legends = {}; +% for j=1:length(channels{ii}); +% for i = channels{ii}(j) +% if ii==1 +% averaged_ERP= ERP_shk1(i,:); +% elseif ii==2; +% i=i-16; +% averaged_ERP= ERP_shk2(i,:); +% end +% plot(X2, averaged_ERP*depth_spacing*10 + depth,'LineWidth',2,'Color','k'); +% max_y= max_y + max(averaged_ERP); +% depth= depth + depth_spacing; +% chan_legends= [chan_legends, num2str(i)]; +% end +% end + %export_fig (fig_title, '-pdf') + nrm = input('Do you want to normalize the CSD plot? Y/N:','s'); + if nrm == 'Y' + prestim_csd = mean(CSD_matrix1(:,976:1025),2); % prestim = 200ms before flip + for c = 1: size(CSD_matrix1,1) + nrm_CSD_matrix(c,:) = CSD_matrix1(c,976:end)-prestim_csd(c); + end + CSD_fig1 = figure; + set(CSD_fig1,'Visible', figuresVisible) + set(CSD_fig1, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(CSD_fig1, 'PaperPositionMode', 'auto'); + set(CSD_fig1, 'Renderer','Zbuffer'); + set(CSD_fig1, 'Color', [1 1 1]); % Sets figure background + set(CSD_fig1, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', CSD_fig1); + set(hsp,'Position',[0.15 0.15 0.60 0.80]); + colorDepth = 1000; + colormap(flipud(jet(colorDepth))); +% pcolor(X2(1001:end), 1:1:size(CSD_matrix1,1), nrm_CSD_matrix); + imagesc(X2(976:end), [], nrm_CSD_matrix); + shading interp; % do not interpolate pixels + axis on; % display axis + axis tight;% no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'in' , ... + 'Ydir' , 'reverse', ... + 'TickLength' , [.01 .01] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'yticklabel',1:1:size(CSD_matrix1,1), 'Ytick', 1:1:size(CSD_matrix1,1)); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number'; + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Shank 1 - Normalized'); + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); + caxis([min(min(CSD_matrix1)) max(max(CSD_matrix1))]); + zLabelText = 'nA / mm^3'; % greek letters in LaTeX Syntax + hcb = colorbar('eastoutside'); + h_bar = findobj(gcf,'Tag','Colorbar'); + initpos = get(h_bar,'Position'); + set(h_bar, ... + 'Position',[initpos(1)+initpos(3)*2.5 initpos(2)+initpos(4)*0.3 ... + initpos(3)*0.4 initpos(4)*0.4]); + hcLabel = ylabel(hcb,zLabelText); + set(hcb,'YTickLabel',{'Sink','Source'}, 'Ytick', [min(min(CSD_matrix1)) max(max(CSD_matrix1))]) + set(hcb, ... + 'Box' , 'on' , ... + 'TickDir' , 'in' , ... + 'TickLength' , [.010 .010] , ... + 'LineWidth' , 0.6); + set([gca, hcb, hXLabel, hYLabel, hcLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + ylabh=get(hcb,'Ylabel'); + set(ylabh,'Position',get(ylabh,'Position')-[8 0 0]); + set(gca,'Layer', 'top'); + plot([25 25],get(gca,'ylim'),'-k','Linewidth',.5); + drawnow + end + export_fig (fig_title, '-png','-r600','-zbuffer'); + +%% + if probetype ==1 + figure_width = 12; + figure_height = 10; + FontSize = 12; + FontName = 'MyriadPro-Regular'; % or choose any other font + % --- setup plot windows + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + CSD_fig2 = figure; + set(CSD_fig2,'Visible', figuresVisible) + set(CSD_fig2, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(CSD_fig2, 'PaperPositionMode', 'auto'); + set(CSD_fig2, 'Renderer','Zbuffer'); + set(CSD_fig2, 'Color', [1 1 1]); % Sets figure background + set(CSD_fig2, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', CSD_fig2); + set(hsp,'Position',[0.15 0.15 0.60 0.80]); + colorDepth = 1000; + colormap(flipud(jet(colorDepth))); +% pcolor(X2, 1:1:size(CSD_matrix2,1), CSD_matrix2); + imagesc(X2(976:1226),[],CSD_matrix2(:,976:1226)) + shading interp; % do not interpolate pixels + axis on; % display axis + axis tight;% no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'in' , ... + 'Ydir' , 'reverse', ... + 'TickLength' , [.01 .01] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'yticklabel',1:1:size(CSD_matrix2,1), 'Ytick', 1:1:size(CSD_matrix2,1)); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number'; + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Shank 2 '); + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); +% caxis([min(min(CSD_matrix2)) max(max(CSD_matrix2))]); + zLabelText = 'nA / mm^3'; % greek letters in LaTeX Syntax + hcb = colorbar('eastoutside'); + h_bar = findobj(gcf,'Tag','Colorbar'); + initpos = get(h_bar,'Position'); + set(h_bar, ... + 'Position',[initpos(1)+initpos(3)*2.5 initpos(2)+initpos(4)*0.3 ... + initpos(3)*0.4 initpos(4)*0.4]); + hcLabel = ylabel(hcb,zLabelText); + set(hcb,'YTickLabel',{'Sink','Source'}, 'Ytick', [min(min(CSD_matrix2)) max(max(CSD_matrix2))]) + set(hcb, ... + 'Box' , 'on' , ... + 'TickDir' , 'in' , ... + 'TickLength' , [.010 .010] , ... + 'LineWidth' , 0.6); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + set([hcb, hcLabel], ... + 'FontSize' , 10 , ... + 'FontName' , FontName); + ylabh=get(hcb,'Ylabel'); + set(ylabh,'Position',get(ylabh,'Position')-[8 0 0]); + set(gca,'Layer', 'top'); + drawnow + + nrm = input('Do you want to normalize the CSD plot? Y/N:','s'); + if nrm == 'Y' + prestim_csd = mean(CSD_matrix2(:,900:1000),2); % prestim = 200ms before flip + for c = 1: size(CSD_matrix2,1) + nrm_CSD_matrix(c,:) = CSD_matrix2(c,1001:end)-prestim_csd(c); + end + CSD_fig1 = figure; + set(CSD_fig1,'Visible', figuresVisible) + set(CSD_fig1, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(CSD_fig1, 'PaperPositionMode', 'auto'); + set(CSD_fig1, 'Renderer','Zbuffer'); + set(CSD_fig1, 'Color', [1 1 1]); % Sets figure background + set(CSD_fig1, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', CSD_fig1); + set(hsp,'Position',[0.15 0.15 0.60 0.80]); + colorDepth = 1000; + colormap(flipud(jet(colorDepth))); +% pcolor(X2(1001:end), 1:1:size(CSD_matrix1,1), nrm_CSD_matrix); + imagesc(X2(1001:end), [], nrm_CSD_matrix); + shading interp; % do not interpolate pixels + axis on; % display axis + axis tight;% no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'in' , ... + 'Ydir' , 'reverse', ... + 'TickLength' , [.01 .01] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'yticklabel',1:1:size(CSD_matrix1,1), 'Ytick', 1:1:size(CSD_matrix1,1)); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number'; + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Shank 1 - Normalized'); + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); + caxis([min(min(CSD_matrix1)) max(max(CSD_matrix1))]); + zLabelText = 'nA / mm^3'; % greek letters in LaTeX Syntax + hcb = colorbar('eastoutside'); + h_bar = findobj(gcf,'Tag','Colorbar'); + initpos = get(h_bar,'Position'); + set(h_bar, ... + 'Position',[initpos(1)+initpos(3)*2.5 initpos(2)+initpos(4)*0.3 ... + initpos(3)*0.4 initpos(4)*0.4]); + hcLabel = ylabel(hcb,zLabelText); + set(hcb,'YTickLabel',{'Sink','Source'}, 'Ytick', [min(min(CSD_matrix1)) max(max(CSD_matrix1))]) + set(hcb, ... + 'Box' , 'on' , ... + 'TickDir' , 'in' , ... + 'TickLength' , [.010 .010] , ... + 'LineWidth' , 0.6); + set([gca, hcb, hXLabel, hYLabel, hcLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + ylabh=get(hcb,'Ylabel'); + set(ylabh,'Position',get(ylabh,'Position')-[8 0 0]); + set(gca,'Layer', 'top'); + drawnow + end + + % % superimpose ERPs + % ii=2; + % depth = 1; + % depth_spacing = 1; + % max_y = 0; + % hold all; + % % for each channel + % chan_legends = {}; + % for j=1:length(channels{ii}); + % for i = channels{ii}(j) + % if ii==1 + % averaged_ERP= ERP_shk1(i,:); + % elseif ii==2; + % i=i-16; + % averaged_ERP= ERP_shk2(i,:); + % end + % plot(X2, averaged_ERP*depth_spacing*10 + depth,'LineWidth',2,'Color','k'); + % max_y= max_y + max(averaged_ERP); + % depth= depth + depth_spacing; + % chan_legends= [chan_legends, num2str(i)]; + % end + % end + %export_fig (fig_title, '-pdf') + export_fig (fig_title, '-png','-r600','-zbuffer'); + end +%% Plot CSD traces (Megan addition) +% FontName = 'MyriadPro-Regular'; % or choose any other font +% FontSize = 14; +% figure_width = 28; +% figure_height = 14; +% figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) +% CSD_stacked=figure;% figure('units', 'normalized', 'outerposition', [0 0 1 1]); +% set(CSD_stacked, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) +% set(CSD_stacked, 'PaperPositionMode', 'auto'); +% set(CSD_stacked, 'Color', [1 1 1]); % Sets figure background +% set(CSD_stacked, 'Color', [1 1 1]); % Sets axes background +% hsp = subplot(1,1,1, 'Parent', CSD_stacked); +% set(hsp,'Position',[0.15 0.17 0.75 0.80]); +% for ii = 1:size(channels,2) +% subplot(1, 2, ii); +% depth = 0; +% depth_spacing = 500; +% max_y = 0; +% hold all; +% % for each channel +% chan_legends = {}; +% for j=1:length(channels{ii}); +% for i = channels{ii}(j) +% if ii==1 +% CSD_trace = CSD_matrix1(i,:); +% elseif ii==2; +% i=i-16; +% CSD_trace= CSD_matrix2(i,:); +% end +% plot(X2, CSD_trace/15 + depth,'LineWidth',2); +% max_y= max_y + max(CSD_trace); +% depth= depth + depth_spacing; +% chan_legends= [chan_legends, num2str(i)]; +% end +% end +% yaxis=ylim; +% set(gca,'Ylim',[-depth_spacing depth_spacing*length(channels{ii})]) +% if ii==1 +% set(gca, 'ytick', [0:depth_spacing:(depth_spacing*length(channels{ii}))-depth_spacing],'tickdir','out','yticklabel',[left_channels]); +% axis on; % display axis +% set(gca, ... +% 'Box' , 'off' , ... +% 'TickDir' , 'out' , ... +% 'TickLength' , [0 0] , ... +% 'XMinorTick' , 'off' , ... +% 'YMinorTick' , 'off' , ... +% 'XGrid' , 'off' , ... +% 'YGrid' , 'off' , ... +% 'XColor' , [.0 .0 .0], ... +% 'YColor' , [.0 .0 .0], ... +% 'LineWidth' , 0.6 ); +% set(gca,'Xlim',[-25 225]); +% set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) +% xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax +% yLabelText = 'Electrode number (Sup-->Deep)'; +% % save handles to set up label properties +% hXLabel = xlabel(xLabelText); +% hYLabel = ylabel(yLabelText); +% set([gca, hXLabel, hYLabel], ... +% 'FontSize' , FontSize , ... +% 'FontName' , FontName); +% prestim_offset_y = yaxis(1):1:yaxis(2); +% prestim_offset_t = ones(1, length(prestim_offset_y))*0; +% plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',2); +% % poststimulus onset +% elseif ii==2; +% set(gca, 'ytick', [0:depth_spacing:(depth_spacing*length(channels{ii}))-depth_spacing],'tickdir','out','yticklabel',[right_channels]); +% axis on; % display axis +% set(gca, ... +% 'Box' , 'off' , ... +% 'TickDir' , 'out' , ... +% 'TickLength' , [0 0] , ... +% 'XMinorTick' , 'off' , ... +% 'YMinorTick' , 'off' , ... +% 'XGrid' , 'off' , ... +% 'YGrid' , 'off' , ... +% 'XColor' , [.0 .0 .0], ... +% 'YColor' , [.0 .0 .0], ... +% 'LineWidth' , 0.6 ); +% set(gca,'Xlim',[-25 225]); +% set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) +% xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax +% yLabelText = 'Electrode number (Sup-->Deep)'; +% % save handles to set up label properties +% hXLabel = xlabel(xLabelText); +% hYLabel = ylabel(yLabelText); +% set([gca, hXLabel, hYLabel], ... +% 'FontSize' , FontSize , ... +% 'FontName' , FontName); +% prestim_offset_y = yaxis(1):1:yaxis(2); +% prestim_offset_t = ones(1, length(prestim_offset_y))*0; +% plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',2); +% end +% end +% fig_title=sprintf('%s','CSD Stacked '); +% set(gca,'Layer', 'top'); +% drawnow + +%% Determine the center of mass + t1=find(X2>=-200 & X2<=500,1,'first'); + t2=find(X2>=-200 & X2<=500,1,'last'); + [mean_x1 mean_y1]=centroid_me(CSD_matrix1(:,t1:t2)); + mean_x1=X2((t1-1)+mean_x1); + sprintf ('%s%d%s%d','The centroid value is: ',round(mean_x1), ' ms at contact number ',mean_y1) + if probetype ==1 + t1=find(X2>=-200 & X2<=500,1,'first'); + t2=find(X2>=-200 & X2<=500,1,'last'); + [mean_x2 mean_y2]=centroid_me(CSD_matrix2(:,t1:t2)); + mean_x2=X2((t1-1)+mean_x2); + sprintf ('%s%d%s%d','The centroid value is: ',round(mean_x2), ' ms at contact number ',mean_y2) + end +%% +disp ('Look at the CSD and find the layers which contain the sink(red)') +st_sink1 = input('Shank 1 begining of the sink: ','s'); +end_sink1 = input('Shank 1 Ending of the sink: ','s'); +gran1=str2double(st_sink1):str2double(end_sink1); +%-------------------------------------% + +if probetype ==1 + disp ('Look at the CSD and find the layers which contain the sink(red)') + st_sink2 = input('Shank 2 begining of the sink: ','s'); + end_sink2 = input('Shank 2 Ending of the sink: ','s'); + gran2=str2double(st_sink2):str2double(end_sink2); +end +%% +%%% Now this and final section creates the average CSD across contacts +%%% given +%%% the user defined top and bottom of the sink(red) region in the CSD +%%% plots. The mean and the STD are calaucated for each layer. and the +%%% envelope of the std is ploted using the jbfill fx +axis_time=t1:t2; +if gran1(1)==2; + SG_c=(CSD_matrix1(1,axis_time)); + SG_std=std(CSD_matrix1(1,axis_time))./1; + SG_p=SG_c+SG_std; SG_m=SG_c-SG_std; +else + SG_c=mean(CSD_matrix1(1:(gran1(1)-1),axis_time),1); + SG_std=(std(CSD_matrix1((1:gran1(1)-1),axis_time),0,1))./size(CSD_matrix1(1:gran1(1)-1),2); + SG_p=SG_c+SG_std; SG_m=SG_c-SG_std; +end + G_c=mean(CSD_matrix1(gran1,axis_time),1); + G_std=(std(CSD_matrix1(gran1,axis_time),0,1))./size(CSD_matrix1(gran1),2); + G_p=G_c+G_std; G_m=G_c-G_std; + + IG_c=mean(CSD_matrix1((gran1(length(gran1))+1):size(CSD_matrix1,1),axis_time),1); + IG_std=(std(CSD_matrix1((gran1(length(gran1))+1):size(CSD_matrix1,1),axis_time),0,1))... + ./(length((gran1(length(gran1))+1):size(CSD_matrix1))); + IG_p=IG_c+IG_std; IG_m=IG_c-IG_std; +%% + figure_width = 12; + figure_height = 12; + FontSize = 12; + FontName = 'MyriadPro-Regular'; % or choose any other font + % --- setup plot windows + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + Avg_CSD1 = figure; + set(Avg_CSD1,'Visible', figuresVisible) + set(Avg_CSD1, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(Avg_CSD1, 'PaperPositionMode', 'auto'); + set(Avg_CSD1, 'Color', [1 1 1]); % Sets figure background + set(Avg_CSD1, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', Avg_CSD1); + set(hsp,'Position',[0.10 0.15 0.80 0.80]); + x=X2(axis_time)'; + hold on;handle_vector(:,1) = plot(x,SG_c,'r','LineWidth',2); + hold on; handle_vector(:,2) = jbfill(x,SG_p,SG_m,'r','r',1,.4); + hold on; handle_vector(:,3) = plot(x,G_c,'b','LineWidth',2); + hold on; handle_vector(:,4) = jbfill(x,G_p,G_m,'b','b',1,.4); + hold on; handle_vector(:,5) = plot(x,IG_c,'color',[0 .5 0],'LineWidth',2); + hold on; handle_vector(:,6) = jbfill(x,IG_p,IG_m,[0 .5 0],[0 .5 0],1,.4); + % will remove the 3rd legend entry. + hasbehavior(handle_vector(2),'legend',false); + hasbehavior(handle_vector(4),'legend',false); + hasbehavior(handle_vector(6),'legend',false); + % will remove the 3rd legend entry. + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [0 0] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + axis off + %export_fig ('Avg1', '-png','-r600','-opengl') + axis on + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'ytick', [],'tickdir','out'); + set(gca, 'YTickLabel', num2str(get(gca, 'YTick')')) + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'nA / mm^3'; + h=legend({'Supragranular','Granular','Infragranular'}); + set(h, 'Box', 'off','location', 'Best') + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Avg1 '); + set([gca, hXLabel, hYLabel, h], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + set(h, ... + 'FontSize' , 10 , ... + 'FontName' , FontName); + set(gca,'Layer', 'top'); + drawnow + export_fig (fig_title, '-png','-r600','-opengl') +%% +%%% Now this and final section creates the average CSD across contacts given +%%% the user defined top and bottom of the sink(red) region in the CSD +%%% plots. The mean and the STD are calaucated for each layer. and the +%%% envelope of the std is ploted using the jbfill fx +axis_time=t1:t2; +if probetype ==1 + if gran2(1)==2; + SG_c=(CSD_matrix2(1,axis_time)); + SG_std=std(CSD_matrix2(1,axis_time))./1; + SG_p=SG_c+SG_std; SG_m=SG_c-SG_std; + else + SG_c=mean(CSD_matrix2(1:(gran2(1)-1),axis_time),1); + SG_std=(std(CSD_matrix2((1:gran2(1)-1),axis_time),0,1))./sqrt(size(CSD_matrix2(1:gran2(1)-1),2)); % MK added square roots! + SG_p=SG_c+SG_std; SG_m=SG_c-SG_std; + end + G_c=mean(CSD_matrix2(gran2,axis_time),1); + G_std=(std(CSD_matrix2(gran2,axis_time),0,1))./sqrt(size(CSD_matrix2(gran2),2)); + G_p=G_c+G_std; G_m=G_c-G_std; + + IG_c=mean(CSD_matrix2((gran2(length(gran2))+1):size(CSD_matrix2,1),axis_time),1); + IG_std=(std(CSD_matrix2((gran2(length(gran2))+1):size(CSD_matrix2,1),axis_time),0,1))... + ./sqrt(length((gran1(length(gran1))+1):size(CSD_matrix2))); + IG_p=IG_c+IG_std; IG_m=IG_c-IG_std; +%% + + figure_width = 14; + figure_height = 12; + FontSize = 12; + FontName = 'MyriadPro-Regular'; % or choose any other font + % --- setup plot windows + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + Avg_CSD2 = figure; + set(Avg_CSD2,'Visible', figuresVisible) + set(Avg_CSD2, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(Avg_CSD2, 'PaperPositionMode', 'auto'); + set(Avg_CSD2, 'Color', [1 1 1]); % Sets figure background + set(Avg_CSD2, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', Avg_CSD2); + set(hsp,'Position',[0.10 0.15 0.80 0.80]); + x=X2(axis_time)'; + hold on;handle_vector(:,1) = plot(x,SG_c,'r','LineWidth',2); + hold on; handle_vector(:,2) = jbfill(x,SG_p,SG_m,'r','r',1,.4); + hold on; handle_vector(:,3) = plot(x,G_c,'b','LineWidth',2); + hold on; handle_vector(:,4) = jbfill(x,G_p,G_m,'b','b',1,.4); + hold on; handle_vector(:,5) = plot(x,IG_c,'color',[0 .5 0],'LineWidth',2); + hold on; handle_vector(:,6) = jbfill(x,IG_p,IG_m,[0 .5 0],[0 .5 0],1,.4); + % will remove the 3rd legend entry. + hasbehavior(handle_vector(2),'legend',false); + hasbehavior(handle_vector(4),'legend',false); + hasbehavior(handle_vector(6),'legend',false); + % will remove the 3rd legend entry. + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [0 0] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + axis off + %export_fig ('Avg2', '-png','-r600','-opengl') + axis on + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'ytick', [],'tickdir','out'); + set(gca, 'YTickLabel', num2str(get(gca, 'YTick')')) + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on; plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'nA / mm^3'; + h=legend({'Supragranular','Granular','Infragranular'}); + set(h, 'Box', 'off','location', 'Best') + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Avg2 '); + set([gca, hXLabel, hYLabel, h], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + set(h, ... + 'FontSize' , 10 , ... + 'FontName' , FontName); + set(gca,'Layer', 'top'); + drawnow + export_fig (fig_title, '-png','-r600','-opengl') +end +%% + figure_width = 12; + figure_height = 10; + FontSize = 10; + FontName = 'MyriadPro-Regular'; % or choose any other font + % --- setup plot windows + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + CSD_fig2 = figure; + set(CSD_fig2,'Visible', figuresVisible) + set(CSD_fig2, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(CSD_fig2, 'PaperPositionMode', 'auto'); + set(CSD_fig2, 'Renderer','Zbuffer'); + set(CSD_fig2, 'Color', [1 1 1]); % Sets figure background + set(CSD_fig2, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', CSD_fig2); + set(hsp,'Position',[0.25 0.15 0.35 0.80]); + colorDepth = 1000; + colormap(flipud(jet(colorDepth))); +% pcolor(X2, 1:1:size(CSD_matrix1,1), CSD_matrix1); + imagesc(X2,[],CSD_matrix1) + shading interp; % do not interpolate pixels + axis on; % display axis + axis tight;% no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'in' , ... + 'Ydir' , 'reverse', ... + 'TickLength' , [.05 .05] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200],'TickLength',[0.01 0.01]); + set(gca, 'yticklabel',1:1:size(CSD_matrix1,1), 'Ytick', 1:1:size(CSD_matrix1,1)); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Depth from intial sink (mm)'; + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Shank 1'); + y_tick=1:.5:size(CSD_matrix1,1); +% c_y=find(y_tick==median(gran1)); +% contact_spacing = 150/spacing; +% p_y=find(y_tick==median(gran1)+contact_spacing/2); %below +% m_y=find(y_tick==median(gran1)-contact_spacing/2); %above +% infragran = find(y_tick==median(gran1)+contact_spacing*2); % make line for bottom of L5 +% y_label(c_y)=0; +% y_label(p_y)=0.100; +% y_label(m_y)=0-.100; +% % set(gca, 'yticklabel',[y_label(m_y) y_label(c_y) y_label(p_y)], 'Ytick', [y_tick(m_y) y_tick(c_y) y_tick(p_y)]); +% hold on;plot(get(gca,'xlim'),[median(gran1) median(gran1)],'-k','Linewidth',1.5); +% xaxis=xlim; +% hold on;plot(xaxis,[y_tick(p_y) y_tick(p_y)],'-k','Linewidth',.5); +% hold on;plot(xaxis,[y_tick(m_y) y_tick(m_y)],'-k','Linewidth',.5); +% hold on;plot(xaxis,[y_tick(infragran) y_tick(infragran)],'-k','Linewidth',.5); +% % yaxis=ylim; + + bounds = define_layers(spacing,num_channels,exp_path,1); + s_y = find(y_tick==bounds(1)); + p_y = find(y_tick==bounds(2)); + m_y = find(y_tick==bounds(3)); + infragran = find(y_tick==bounds(end)); +% set(gca, 'yticklabel',[y_label(m_y) y_label(c_y) y_label(p_y)], 'Ytick', [y_tick(m_y) y_tick(c_y) y_tick(p_y)]); + hold on;plot(get(gca,'xlim'),[y_tick(s_y) y_tick(s_y)],'-k','Linewidth',.5); + xaxis=xlim; + hold on;plot(xaxis,[y_tick(p_y) y_tick(p_y)],'-k','Linewidth',.5); + hold on;plot(xaxis,[y_tick(m_y) y_tick(m_y)],'-k','Linewidth',.5); + hold on;plot(xaxis,[y_tick(infragran) y_tick(infragran)],'-k','Linewidth',.5); + + +% prestim_offset_y = yaxis(1):1:yaxis(2); +% prestim_offset_t = ones(1, length(prestim_offset_y))*0; +% hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); + caxis([min(min(CSD_matrix1)) max(max(CSD_matrix1))]); + zLabelText = 'nA / mm^3'; % greek letters in LaTeX Syntax + hcb = colorbar('eastoutside'); + h_bar = findobj(gcf,'Tag','Colorbar'); + initpos = get(h_bar,'Position'); + set(h_bar, ... + 'Position',[initpos(1)+initpos(3)*3.5 initpos(2)+initpos(4)*0.3 ... + initpos(3)*0.4 initpos(4)*0.4]); + hcLabel = ylabel(hcb,zLabelText); + set(hcb,'YTickLabel',{'Sink','Source'}, 'Ytick', [min(min(CSD_matrix1)) max(max(CSD_matrix1))]) + set(hcb, ... + 'Box' , 'on' , ... + 'TickDir' , 'in' , ... + 'TickLength' , [.010 .010] , ... + 'LineWidth' , 0.6); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + set([hcb, hcLabel], ... + 'FontSize' , 11 , ... + 'FontName' , FontName); + ylabh=get(hcb,'Ylabel'); + set(ylabh,'Position',get(ylabh,'Position')-[8 0 0]); + set(gca,'Layer', 'top'); + drawnow + export_fig (fig_title, '-png','-r600','-zbuffer'); + print2eps(fig_title) +end +%% +savefile=sprintf('%s%s','FinalCSD','.mat'); +save (savefile); + +% define_layers(spacing,num_channels,exp_path) +% close all +% clear all +% close all +% clear all +% clc +end \ No newline at end of file diff --git a/Intancode_Megan/IntanLFP_lightCSD.m b/Intancode_Megan/IntanLFP_lightCSD.m new file mode 100644 index 0000000..3ba669c --- /dev/null +++ b/Intancode_Megan/IntanLFP_lightCSD.m @@ -0,0 +1,1328 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% IntanLFP_CSD_v2.m +% Script for extracting LFP data from Intan +%Created 09222015 by Megan A Kirchgessner +% Adapted from LFPv2_latest from Bryan J. Hansen +% mkirchgessner@ucsd.edu +% 5/30/2016 - FILTER CHANGED by MAK - replaced with newfilter.m +% 6/14/2016 - changed to intanphy2matlab_v2; added new code for determining running trials (MAK) +% 8/31/2016 - changed to intan2matlab +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% + + +function IntanLFP_lightCSD(exp_path,exp_type) + %% + +% get necessary data +cd(exp_path) +if exist(sprintf('%s/data.mat',exp_path),'file') + load(sprintf('%s/data.mat',exp_path)) % data from intanphy2matlab.m +else + intan2matlab(exp_path); % data from intanphy2matlab.m + load(sprintf('%s/data.mat',exp_path)) +end + +if ~exist(sprintf('%s/LFP_all.mat',exp_path),'file') + % read in amplifier.dat one channel at a time + v = read_intan_amp(exp_path,num_channels,amp_sr,1); + + % filter LFPs + fRawo_ln = newfilter(v,1000,0); + save('LFP_all.mat','fRawo_ln') +else + load(sprintf('%s/LFP_all.mat',exp_path)) +end + +num_channels = size(fRawo_ln,1); +% get LFPs +disp('Get the LFPs'); +tic +var_name = cell(1,num_channels); +for ch = 1:num_channels + if ch < 10 + var_name{ch} = sprintf('LFP0%d',ch); + else + var_name{ch} = sprintf('LFP%d',ch); + end +end +cont=struct; + +field_file_name = 'fields'; +field_output_dir = fullfile(exp_path, field_file_name); +[~,message]=mkdir(field_output_dir); %#ok +cd(field_output_dir); +fileID2 = fopen('lfps.txt','w'); +for i=1:size(fRawo_ln,1) % number of channels + if i>1 + fprintf(fileID2,'\r\n'); + end + ch=sprintf('%s%d', 'Processing channel: ', i); + disp(ch); + if i<10 + save_lfp=sprintf('%s%d','lfp0', i); + else + save_lfp=sprintf('%s%d','lfp', i); + end + cont(i).sig = fRawo_ln(i,:); + cd(field_output_dir); + fprintf(fileID2,save_lfp); +end +fclose(fileID2); +toc +% clear aux_data lfp data zx + +probetype = input('Did you use NeuroNexus 2x16 probe (1), 1x32 probe (2), 32 channel polytrode (3), or 32 channel linear probe (4)?: ', 's'); +probetype = str2double(probetype); +if probetype == 1 + pos=[29 + 26 + 24 + 21 + 20 + 23 + 25 + 28 + 30 + 18 + 19 + 22 + 32 + 27 + 17 + 31 + 7 + 2 + 15 + 8 + 11 + 10 + 12 + 9 + 6 + 14 + 13 + 3 + 5 + 16 + 4 + 1 + ]; + spacing = 50; % vertical spacing of contacts (in microns) +elseif probetype == 2; + pos= [4 + 5 + 13 + 6 + 12 + 11 + 15 + 7 + 2 + 8 + 10 + 9 + 14 + 3 + 16 + 1 + 17 + 32 + 19 + 30 + 25 + 20 + 24 + 29 + 26 + 21 + 23 + 28 + 18 + 22 + 27 + 31]; + spacing = 20; % vertical spacing of contacts + +elseif probetype == 3; % polytrode(pretending they're on same xplane) + pos = [ 8 % from highest to lowest + 24 + 2 + 29 + 7 + 26 + 15 + 21 + 11 + 23 + 12 + 28 + 6 + 18 + 13 + 22 + 5 + 27 + 4 + 31 + 10 + 20 + 9 + 25 + 14 + 30 + 3 + 19 + 16 + 32 + 1 + 17]; + spacing = 25; % vertical spacing of contacts + +elseif probetype == 4; % linear 32ch + pos = [1 + 17 + 16 + 32 + 3 + 19 + 14 + 30 + 9 + 25 + 10 + 20 + 8 + 24 + 2 + 29 + 7 + 26 + 15 + 21 + 11 + 23 + 12 + 28 + 6 + 18 + 13 + 22 + 5 + 27 + 4 + 31]; + spacing = 25; +end + + + + + + +for i=1:length(var_name) + sig{i}=sprintf('%s%d%s','=cont(',pos(i),').sig'); + evalc([var_name{i}, sig{i}]); % LFPs are ordered from top to bottom! +end + +%% find light onset times during blank trials (when mouse was stationary) +disp('Find timing using PD pulses to est. the Evoked Response Potential (ERP)') +tic +% get average light onset time +[~,~,~,av_light_start] = get_lightstim_v2(exp_path,exp_type); % just to get duration and time of light onset +% get the details of the experiment (trial types, prestim time, etc.) +[prestim,poststim,stimtime,trial_type,IVs] = get_exp_params(exp_path,exp_type); +% identify blank light trials +lightvar = find(strcmp(IVs,'light_bit')); +runvar = find(strcmp(IVs,'running')); +light_blnk = find((trial_type(:,1)==0) & (trial_type(:,lightvar)>=1) & (trial_type(:,runvar)==0)); + +new_re=zeros(1,length(light_blnk)); +disp('Get timestamps of light onset during blank trials') +for i = 1:length(light_blnk) + trials2 (i,1) = find(time_index>=trials(light_blnk(i),1)&time_index<=trials(light_blnk(i),2),1,'first'); % in samples, starting from 1 + trials2 (i,2) = find(time_index>=(time_index(trials2(i,1)))&time_index<=(time_index(trials2(i,1))+2.000),1,'last'); + trial_time(i,:) = trials2(i,1):1:trials2(i,1)+2000; +end +timing=(time_index(trial_time(1,:))-time_index(trial_time(1,1))-1); + + +%% +disp('Create ERPs for each LFP trials x time'); +% Import electrdoes are reordered based on the Neuronexus probe +ERP01=mean(LFP01(trial_time),1); +ERP02=mean(LFP02(trial_time),1); +ERP03=mean(LFP03(trial_time),1); +ERP04=mean(LFP04(trial_time),1); +ERP05=mean(LFP05(trial_time),1); +ERP06=mean(LFP06(trial_time),1); +ERP07=mean(LFP07(trial_time),1); +ERP08=mean(LFP08(trial_time),1); +ERP09=mean(LFP09(trial_time),1); +ERP10=mean(LFP10(trial_time),1); +ERP11=mean(LFP11(trial_time),1); +ERP12=mean(LFP12(trial_time),1); +ERP13=mean(LFP13(trial_time),1); +ERP14=mean(LFP14(trial_time),1); +ERP15=mean(LFP15(trial_time),1); +ERP16=mean(LFP16(trial_time),1); +ERP17=mean(LFP17(trial_time),1); +ERP18=mean(LFP18(trial_time),1); +ERP19=mean(LFP19(trial_time),1); +ERP20=mean(LFP20(trial_time),1); +ERP21=mean(LFP21(trial_time),1); +ERP22=mean(LFP22(trial_time),1); +ERP23=mean(LFP23(trial_time),1); +ERP24=mean(LFP24(trial_time),1); +ERP25=mean(LFP25(trial_time),1); +ERP26=mean(LFP26(trial_time),1); +ERP27=mean(LFP27(trial_time),1); +ERP28=mean(LFP28(trial_time),1); +ERP29=mean(LFP29(trial_time),1); +ERP30=mean(LFP30(trial_time),1); +ERP31=mean(LFP31(trial_time),1); +ERP32=mean(LFP32(trial_time),1); +%----------------------------% +if probetype == 1 + aux_shk1=vertcat(ERP01,ERP02,ERP03,ERP04,ERP05,ERP06,ERP07,ERP08,ERP09,ERP10,ERP11,ERP12,ERP13,ERP14,ERP15,ERP16); + aux_shk2=vertcat(ERP17,ERP18,ERP19,ERP20,ERP21,ERP22,ERP23,ERP24,ERP25,ERP26,ERP27,ERP28,ERP29,ERP30,ERP31,ERP32); + % scale factor + ERP_shk1=(aux_shk1/(1*10^8))*(1*10^6);% Scale factor for ERP <<<< MAYBE CHANGE THIS + ERP_shk2=(aux_shk2/(1*10^8))*(1*10^6);% Scale factor for ERP +% //elseif probetype ==2 +else + aux_shk1 = vertcat(ERP01,ERP02,ERP03,ERP04,ERP05,ERP06,ERP07,ERP08,ERP09,ERP10,ERP11,ERP12,ERP13,ERP14,ERP15,ERP16,... + ERP17,ERP18,ERP19,ERP20,ERP21,ERP22,ERP23,ERP24,ERP25,ERP26,ERP27,ERP28,ERP29,ERP30,ERP31,ERP32); + % scale factor + ERP_shk1=(aux_shk1/(1*10^8))*(1*10^6);% Scale factor for ERP <<<< MAYBE CHANGE THIS +% elseif probetype ==3 +% % aux_shk1 = vertcat(ERP02,ERP04,ERP06,ERP08,ERP10,ERP12,ERP14,ERP16,... +% % ERP18,ERP20,ERP22,ERP24,ERP26,ERP28,ERP30,ERP32); +% % aux_shk2 = vertcat(ERP01,ERP03,ERP05,ERP07,ERP09,ERP11,ERP13,ERP15,... +% % ERP17,ERP19,ERP21,ERP23,ERP25,ERP27,ERP29,ERP31); +% aux_shk1 = vertcat(ERP01,ERP02,ERP03,ERP04,ERP05,ERP06,ERP07,ERP08,ERP09,ERP10,ERP11,ERP12,ERP13,ERP14,ERP15,ERP16,... +% ERP17,ERP18,ERP19,ERP20,ERP21,ERP22,ERP23,ERP24,ERP25,ERP26,ERP27,ERP28,ERP29,ERP30,ERP31,ERP32); +% ERP_shk1=(aux_shk1/(1*10^8))*(1*10^6);% Scale factor for ERP <<<< MAYBE CHANGE THIS +% % scale factor +% % ERP_shk1=(aux_shk1/(1*10^8))*(1*10^6);% Scale factor for ERP <<<< MAYBE CHANGE THIS +% ERP_shk2=(aux_shk2/(1*10^8))*(1*10^6);% Scale factor for ERP + +end + +% clear aux_shk1 aux_shk2 + +%% Plot and clean up ERP figures +if probetype ==1 + ERP_shk1=clean_ERP(ERP_shk1,timing); + ERP_shk2=clean_ERP(ERP_shk2,timing); +else + ERP_shk1=clean_ERP(ERP_shk1,timing); +end + +% normalize ERPs by prestim period + +%% The final ERP figure is sent to the screen to view and now the next section deals +% with the CSD plotter and average analysis +pause(5); +file_name = 'CSD_LFPdata'; +save (file_name); +disp ('saving mat') +HC=CSDplotter; +disp ('Use CSD plotter') +clc +pause(20) +disp ('ERP: normal LFP time series w/o moving trials') +reply = input('Ready to continue? Y/N: ','s'); +if reply == 'Y'; +close all; +disp ('Open CSD matrix file for Shank 1') +filename = uigetfile; +load (filename); +CSD_matrix1=CSD_matrix; +fprintf('%s%s','Filename: ',filename); +close all +clc +disp ('Plot final ERP and CSD side by side') +X2=timing.*1000; +clear CSD_matrix +if probetype ==1 + disp ('Open CSD matrix file for Shank 2') + filename = uigetfile; + load (filename); + CSD_matrix2=CSD_matrix; + fprintf('%s%s','Filename: ',filename); + close all + clc +end +disp ('Plot final ERP and CSD side by side') +%% + FontName = 'MyriadPro-Regular'; % or choose any other font + FontSize = 14; + figure_width = 14; + figure_height = 10; + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + ERP_fig1 = figure; + set(ERP_fig1,'Visible', figuresVisible) + set(ERP_fig1, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(ERP_fig1, 'PaperPositionMode', 'auto'); + set(ERP_fig1, 'Color', [1 1 1]); % Sets figure background + set(ERP_fig1, 'Color', [1 1 1]); % Sets axes background + hsp = subplot(1,1,1, 'Parent', ERP_fig1); + set(hsp,'Position',[0.15 0.17 0.75 0.80]); + plot (X2, ERP_shk1'); + axis on; % display axis + axis tight; % no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [.015 .015] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + yaxis=ylim; + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k','linewidth', 1); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Amplitude (uV)'; + % save handles to set up label properties + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + fig_title=sprintf('%s','ERP 1 '); + set(gca,'Layer', 'top'); + drawnow + %export_fig (fig_title, '-pdf') + export_fig (fig_title, '-png','-r600','-zbuffer'); + + %% + if probetype ==1 + + FontName = 'MyriadPro-Regular'; % or choose any other font + FontSize = 14; + figure_width = 14; + figure_height = 10; + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + ERP_fig2 = figure; + set(ERP_fig2,'Visible', figuresVisible) + set(ERP_fig2, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(ERP_fig2, 'PaperPositionMode', 'auto'); + set(ERP_fig2, 'Color', [1 1 1]); % Sets figure background + set(ERP_fig2, 'Color', [1 1 1]); % Sets axes background + hsp = subplot(1,1,1, 'Parent', ERP_fig2); + set(hsp,'Position',[0.19 0.19 0.75 0.80]); + plot (X2, ERP_shk2'); + axis on; % display axis + axis tight; % no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [.015 .015] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + yaxis=ylim; + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k','linewidth', 1); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Amplitude (uV)'; + % save handles to set up label properties + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + fig_title=sprintf('%s','ERP 2 '); + set(gca,'Layer', 'top'); + drawnow + % export_fig (fig_title, '-pdf') + export_fig (fig_title, '-png','-r600','-opengl') + end +%% +if probetype ==1 + left_channels= fliplr([1:1:size(ERP_shk1,1)]); + right_channels= fliplr([17:1:(size(ERP_shk2,1)+16)]); + channels={left_channels';right_channels'}'; +else + left_channels= fliplr([1:1:size(ERP_shk1,1)]); + channels = {left_channels'}; +end +FontName = 'MyriadPro-Regular'; % or choose any other font + FontSize = 14; + figure_width = 28; + figure_height = 14; + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + ERP_stacked=figure;% figure('units', 'normalized', 'outerposition', [0 0 1 1]); + set(ERP_stacked, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(ERP_stacked, 'PaperPositionMode', 'auto'); + set(ERP_stacked, 'Color', [1 1 1]); % Sets figure background + set(ERP_stacked, 'Color', [1 1 1]); % Sets axes background + hsp = subplot(1,1,1, 'Parent', ERP_stacked); + set(hsp,'Position',[0.15 0.17 0.75 0.80]); +for ii = 1:size(channels,2) + subplot(1, 2, ii); + depth = 0; + depth_spacing = 50; + max_y = 0; + hold all; + % for each channel + chan_legends = {}; + for j=1:length(channels{ii}); + for i = channels{ii}(j) + if ii==1 + averaged_ERP= ERP_shk1(i,:); + elseif ii==2; + i=i-16; + averaged_ERP= ERP_shk2(i,:); + end + plot(X2, averaged_ERP*depth_spacing + depth,'LineWidth',2); + max_y= max_y + max(averaged_ERP); + depth= depth + depth_spacing; + chan_legends= [chan_legends, num2str(i)]; + end +end + yaxis=ylim; + set(gca,'Ylim',[-depth_spacing depth_spacing*length(channels{ii})]) + if ii==1 + set(gca, 'ytick', [0:depth_spacing:(depth_spacing*length(channels{ii}))-depth_spacing],'tickdir','out','yticklabel',[left_channels]); + axis on; % display axis + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [0 0] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number (Sup-->Deep)'; + % save handles to set up label properties + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',2); + % poststimulus onset + elseif ii==2; + set(gca, 'ytick', [0:depth_spacing:(depth_spacing*length(channels{ii}))-depth_spacing],'tickdir','out','yticklabel',[right_channels]); + axis on; % display axis + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [0 0] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number (Sup-->Deep)'; + % save handles to set up label properties + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',2); + end +end +fig_title=sprintf('%s','ERP Stacked '); +set(gca,'Layer', 'top'); +drawnow +%export_fig (fig_title, '-pdf') + export_fig (fig_title, '-png','-r600','-zbuffer'); + +%% Plot CSDs + +% CSD_matrix_all = CSD_matrix1; +% CSD_matrix1 = CSD_matrix_all(2:2:end,:); +% CSD_matrix2 = CSD_matrix_all(1:2:end,:); + + figure_width = 12; + figure_height = 10; + FontSize = 12; + FontName = 'MyriadPro-Regular'; % or choose any other font + % --- setup plot windows + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + CSD_fig1 = figure; + set(CSD_fig1,'Visible', figuresVisible) + set(CSD_fig1, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(CSD_fig1, 'PaperPositionMode', 'auto'); + set(CSD_fig1, 'Renderer','Zbuffer'); + set(CSD_fig1, 'Color', [1 1 1]); % Sets figure background + set(CSD_fig1, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', CSD_fig1); + set(hsp,'Position',[0.15 0.15 0.60 0.80]); + colorDepth = 1000; + colormap(flipud(jet(colorDepth))); +% pcolor(X2, 1:1:size(CSD_matrix1,1), CSD_matrix1); +% imagesc(X2,[],CSD_matrix1) + imagesc(X2(976:1226),[],CSD_matrix1(:,976:1226)) + shading interp; % do not interpolate pixels + axis on; % display axis + axis tight;% no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'in' , ... + 'Ydir' , 'reverse', ... + 'TickLength' , [.01 .01] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'yticklabel',1:1:size(CSD_matrix1,1), 'Ytick', 1:1:size(CSD_matrix1,1)); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number'; + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Shank 1 '); + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); +% caxis([min(min(CSD_matrix1)) max(max(CSD_matrix1))]); + zLabelText = 'nA / mm^3'; % greek letters in LaTeX Syntax + hcb = colorbar('eastoutside'); + h_bar = findobj(gcf,'Tag','Colorbar'); + initpos = get(h_bar,'Position'); + set(h_bar, ... + 'Position',[initpos(1)+initpos(3)*2.5 initpos(2)+initpos(4)*0.3 ... + initpos(3)*0.4 initpos(4)*0.4]); + hcLabel = ylabel(hcb,zLabelText); + set(hcb,'YTickLabel',{'Sink','Source'}, 'Ytick', [min(min(CSD_matrix1)) max(max(CSD_matrix1))]) + set(hcb, ... + 'Box' , 'on' , ... + 'TickDir' , 'in' , ... + 'TickLength' , [.010 .010] , ... + 'LineWidth' , 0.6); + set([gca, hcb, hXLabel, hYLabel, hcLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + ylabh=get(hcb,'Ylabel'); + set(ylabh,'Position',get(ylabh,'Position')-[8 0 0]); + set(gca,'Layer', 'top'); + drawnow +% % superimpose ERPs +% ii=1; +% depth = 1; +% depth_spacing = 1; +% max_y = 0; +% hold all; +% % for each channel +% chan_legends = {}; +% for j=1:length(channels{ii}); +% for i = channels{ii}(j) +% if ii==1 +% averaged_ERP= ERP_shk1(i,:); +% elseif ii==2; +% i=i-16; +% averaged_ERP= ERP_shk2(i,:); +% end +% plot(X2, averaged_ERP*depth_spacing*10 + depth,'LineWidth',2,'Color','k'); +% max_y= max_y + max(averaged_ERP); +% depth= depth + depth_spacing; +% chan_legends= [chan_legends, num2str(i)]; +% end +% end + %export_fig (fig_title, '-pdf') + nrm = input('Do you want to normalize the CSD plot? Y/N:','s'); + if nrm == 'Y' + prestim_csd = mean(CSD_matrix1(:,976:1025),2); % prestim = 200ms before flip + for c = 1: size(CSD_matrix1,1) + nrm_CSD_matrix(c,:) = CSD_matrix1(c,976:end)-prestim_csd(c); + end + CSD_fig1 = figure; + set(CSD_fig1,'Visible', figuresVisible) + set(CSD_fig1, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(CSD_fig1, 'PaperPositionMode', 'auto'); + set(CSD_fig1, 'Renderer','Zbuffer'); + set(CSD_fig1, 'Color', [1 1 1]); % Sets figure background + set(CSD_fig1, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', CSD_fig1); + set(hsp,'Position',[0.15 0.15 0.60 0.80]); + colorDepth = 1000; + colormap(flipud(jet(colorDepth))); +% pcolor(X2(1001:end), 1:1:size(CSD_matrix1,1), nrm_CSD_matrix); + imagesc(X2(976:end), [], nrm_CSD_matrix); + shading interp; % do not interpolate pixels + axis on; % display axis + axis tight;% no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'in' , ... + 'Ydir' , 'reverse', ... + 'TickLength' , [.01 .01] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'yticklabel',1:1:size(CSD_matrix1,1), 'Ytick', 1:1:size(CSD_matrix1,1)); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number'; + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Shank 1 - Normalized'); + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); + caxis([min(min(CSD_matrix1)) max(max(CSD_matrix1))]); + zLabelText = 'nA / mm^3'; % greek letters in LaTeX Syntax + hcb = colorbar('eastoutside'); + h_bar = findobj(gcf,'Tag','Colorbar'); + initpos = get(h_bar,'Position'); + set(h_bar, ... + 'Position',[initpos(1)+initpos(3)*2.5 initpos(2)+initpos(4)*0.3 ... + initpos(3)*0.4 initpos(4)*0.4]); + hcLabel = ylabel(hcb,zLabelText); + set(hcb,'YTickLabel',{'Sink','Source'}, 'Ytick', [min(min(CSD_matrix1)) max(max(CSD_matrix1))]) + set(hcb, ... + 'Box' , 'on' , ... + 'TickDir' , 'in' , ... + 'TickLength' , [.010 .010] , ... + 'LineWidth' , 0.6); + set([gca, hcb, hXLabel, hYLabel, hcLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + ylabh=get(hcb,'Ylabel'); + set(ylabh,'Position',get(ylabh,'Position')-[8 0 0]); + set(gca,'Layer', 'top'); + plot([25 25],get(gca,'ylim'),'-k','Linewidth',.5); + drawnow + end + export_fig (fig_title, '-png','-r600','-zbuffer'); + +%% + if probetype ==1 + figure_width = 12; + figure_height = 10; + FontSize = 12; + FontName = 'MyriadPro-Regular'; % or choose any other font + % --- setup plot windows + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + CSD_fig2 = figure; + set(CSD_fig2,'Visible', figuresVisible) + set(CSD_fig2, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(CSD_fig2, 'PaperPositionMode', 'auto'); + set(CSD_fig2, 'Renderer','Zbuffer'); + set(CSD_fig2, 'Color', [1 1 1]); % Sets figure background + set(CSD_fig2, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', CSD_fig2); + set(hsp,'Position',[0.15 0.15 0.60 0.80]); + colorDepth = 1000; + colormap(flipud(jet(colorDepth))); +% pcolor(X2, 1:1:size(CSD_matrix2,1), CSD_matrix2); + imagesc(X2(976:1226),[],CSD_matrix2(:,976:1226)) + shading interp; % do not interpolate pixels + axis on; % display axis + axis tight;% no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'in' , ... + 'Ydir' , 'reverse', ... + 'TickLength' , [.01 .01] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'yticklabel',1:1:size(CSD_matrix2,1), 'Ytick', 1:1:size(CSD_matrix2,1)); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number'; + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Shank 2 '); + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); +% caxis([min(min(CSD_matrix2)) max(max(CSD_matrix2))]); + zLabelText = 'nA / mm^3'; % greek letters in LaTeX Syntax + hcb = colorbar('eastoutside'); + h_bar = findobj(gcf,'Tag','Colorbar'); + initpos = get(h_bar,'Position'); + set(h_bar, ... + 'Position',[initpos(1)+initpos(3)*2.5 initpos(2)+initpos(4)*0.3 ... + initpos(3)*0.4 initpos(4)*0.4]); + hcLabel = ylabel(hcb,zLabelText); + set(hcb,'YTickLabel',{'Sink','Source'}, 'Ytick', [min(min(CSD_matrix2)) max(max(CSD_matrix2))]) + set(hcb, ... + 'Box' , 'on' , ... + 'TickDir' , 'in' , ... + 'TickLength' , [.010 .010] , ... + 'LineWidth' , 0.6); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + set([hcb, hcLabel], ... + 'FontSize' , 10 , ... + 'FontName' , FontName); + ylabh=get(hcb,'Ylabel'); + set(ylabh,'Position',get(ylabh,'Position')-[8 0 0]); + set(gca,'Layer', 'top'); + drawnow + + nrm = input('Do you want to normalize the CSD plot? Y/N:','s'); + if nrm == 'Y' + prestim_csd = mean(CSD_matrix2(:,900:1000),2); % prestim = 200ms before flip + for c = 1: size(CSD_matrix2,1) + nrm_CSD_matrix(c,:) = CSD_matrix2(c,1001:end)-prestim_csd(c); + end + CSD_fig1 = figure; + set(CSD_fig1,'Visible', figuresVisible) + set(CSD_fig1, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(CSD_fig1, 'PaperPositionMode', 'auto'); + set(CSD_fig1, 'Renderer','Zbuffer'); + set(CSD_fig1, 'Color', [1 1 1]); % Sets figure background + set(CSD_fig1, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', CSD_fig1); + set(hsp,'Position',[0.15 0.15 0.60 0.80]); + colorDepth = 1000; + colormap(flipud(jet(colorDepth))); +% pcolor(X2(1001:end), 1:1:size(CSD_matrix1,1), nrm_CSD_matrix); + imagesc(X2(1001:end), [], nrm_CSD_matrix); + shading interp; % do not interpolate pixels + axis on; % display axis + axis tight;% no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'in' , ... + 'Ydir' , 'reverse', ... + 'TickLength' , [.01 .01] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'yticklabel',1:1:size(CSD_matrix1,1), 'Ytick', 1:1:size(CSD_matrix1,1)); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Electrode number'; + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Shank 1 - Normalized'); + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); + caxis([min(min(CSD_matrix1)) max(max(CSD_matrix1))]); + zLabelText = 'nA / mm^3'; % greek letters in LaTeX Syntax + hcb = colorbar('eastoutside'); + h_bar = findobj(gcf,'Tag','Colorbar'); + initpos = get(h_bar,'Position'); + set(h_bar, ... + 'Position',[initpos(1)+initpos(3)*2.5 initpos(2)+initpos(4)*0.3 ... + initpos(3)*0.4 initpos(4)*0.4]); + hcLabel = ylabel(hcb,zLabelText); + set(hcb,'YTickLabel',{'Sink','Source'}, 'Ytick', [min(min(CSD_matrix1)) max(max(CSD_matrix1))]) + set(hcb, ... + 'Box' , 'on' , ... + 'TickDir' , 'in' , ... + 'TickLength' , [.010 .010] , ... + 'LineWidth' , 0.6); + set([gca, hcb, hXLabel, hYLabel, hcLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + ylabh=get(hcb,'Ylabel'); + set(ylabh,'Position',get(ylabh,'Position')-[8 0 0]); + set(gca,'Layer', 'top'); + drawnow + end + + % % superimpose ERPs + % ii=2; + % depth = 1; + % depth_spacing = 1; + % max_y = 0; + % hold all; + % % for each channel + % chan_legends = {}; + % for j=1:length(channels{ii}); + % for i = channels{ii}(j) + % if ii==1 + % averaged_ERP= ERP_shk1(i,:); + % elseif ii==2; + % i=i-16; + % averaged_ERP= ERP_shk2(i,:); + % end + % plot(X2, averaged_ERP*depth_spacing*10 + depth,'LineWidth',2,'Color','k'); + % max_y= max_y + max(averaged_ERP); + % depth= depth + depth_spacing; + % chan_legends= [chan_legends, num2str(i)]; + % end + % end + %export_fig (fig_title, '-pdf') + export_fig (fig_title, '-png','-r600','-zbuffer'); + end +%% Plot CSD traces (Megan addition) +% FontName = 'MyriadPro-Regular'; % or choose any other font +% FontSize = 14; +% figure_width = 28; +% figure_height = 14; +% figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) +% CSD_stacked=figure;% figure('units', 'normalized', 'outerposition', [0 0 1 1]); +% set(CSD_stacked, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) +% set(CSD_stacked, 'PaperPositionMode', 'auto'); +% set(CSD_stacked, 'Color', [1 1 1]); % Sets figure background +% set(CSD_stacked, 'Color', [1 1 1]); % Sets axes background +% hsp = subplot(1,1,1, 'Parent', CSD_stacked); +% set(hsp,'Position',[0.15 0.17 0.75 0.80]); +% for ii = 1:size(channels,2) +% subplot(1, 2, ii); +% depth = 0; +% depth_spacing = 500; +% max_y = 0; +% hold all; +% % for each channel +% chan_legends = {}; +% for j=1:length(channels{ii}); +% for i = channels{ii}(j) +% if ii==1 +% CSD_trace = CSD_matrix1(i,:); +% elseif ii==2; +% i=i-16; +% CSD_trace= CSD_matrix2(i,:); +% end +% plot(X2, CSD_trace/15 + depth,'LineWidth',2); +% max_y= max_y + max(CSD_trace); +% depth= depth + depth_spacing; +% chan_legends= [chan_legends, num2str(i)]; +% end +% end +% yaxis=ylim; +% set(gca,'Ylim',[-depth_spacing depth_spacing*length(channels{ii})]) +% if ii==1 +% set(gca, 'ytick', [0:depth_spacing:(depth_spacing*length(channels{ii}))-depth_spacing],'tickdir','out','yticklabel',[left_channels]); +% axis on; % display axis +% set(gca, ... +% 'Box' , 'off' , ... +% 'TickDir' , 'out' , ... +% 'TickLength' , [0 0] , ... +% 'XMinorTick' , 'off' , ... +% 'YMinorTick' , 'off' , ... +% 'XGrid' , 'off' , ... +% 'YGrid' , 'off' , ... +% 'XColor' , [.0 .0 .0], ... +% 'YColor' , [.0 .0 .0], ... +% 'LineWidth' , 0.6 ); +% set(gca,'Xlim',[-25 225]); +% set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) +% xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax +% yLabelText = 'Electrode number (Sup-->Deep)'; +% % save handles to set up label properties +% hXLabel = xlabel(xLabelText); +% hYLabel = ylabel(yLabelText); +% set([gca, hXLabel, hYLabel], ... +% 'FontSize' , FontSize , ... +% 'FontName' , FontName); +% prestim_offset_y = yaxis(1):1:yaxis(2); +% prestim_offset_t = ones(1, length(prestim_offset_y))*0; +% plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',2); +% % poststimulus onset +% elseif ii==2; +% set(gca, 'ytick', [0:depth_spacing:(depth_spacing*length(channels{ii}))-depth_spacing],'tickdir','out','yticklabel',[right_channels]); +% axis on; % display axis +% set(gca, ... +% 'Box' , 'off' , ... +% 'TickDir' , 'out' , ... +% 'TickLength' , [0 0] , ... +% 'XMinorTick' , 'off' , ... +% 'YMinorTick' , 'off' , ... +% 'XGrid' , 'off' , ... +% 'YGrid' , 'off' , ... +% 'XColor' , [.0 .0 .0], ... +% 'YColor' , [.0 .0 .0], ... +% 'LineWidth' , 0.6 ); +% set(gca,'Xlim',[-25 225]); +% set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) +% xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax +% yLabelText = 'Electrode number (Sup-->Deep)'; +% % save handles to set up label properties +% hXLabel = xlabel(xLabelText); +% hYLabel = ylabel(yLabelText); +% set([gca, hXLabel, hYLabel], ... +% 'FontSize' , FontSize , ... +% 'FontName' , FontName); +% prestim_offset_y = yaxis(1):1:yaxis(2); +% prestim_offset_t = ones(1, length(prestim_offset_y))*0; +% plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',2); +% end +% end +% fig_title=sprintf('%s','CSD Stacked '); +% set(gca,'Layer', 'top'); +% drawnow + +%% Determine the center of mass + t1=find(X2>=-200 & X2<=500,1,'first'); + t2=find(X2>=-200 & X2<=500,1,'last'); + [mean_x1 mean_y1]=centroid_me(CSD_matrix1(:,t1:t2)); + mean_x1=X2((t1-1)+mean_x1); + sprintf ('%s%d%s%d','The centroid value is: ',round(mean_x1), ' ms at contact number ',mean_y1) + if probetype ==1 + t1=find(X2>=-200 & X2<=500,1,'first'); + t2=find(X2>=-200 & X2<=500,1,'last'); + [mean_x2 mean_y2]=centroid_me(CSD_matrix2(:,t1:t2)); + mean_x2=X2((t1-1)+mean_x2); + sprintf ('%s%d%s%d','The centroid value is: ',round(mean_x2), ' ms at contact number ',mean_y2) + end +%% +disp ('Look at the CSD and find the layers which contain the sink(red)') +st_sink1 = input('Shank 1 begining of the sink: ','s'); +end_sink1 = input('Shank 1 Ending of the sink: ','s'); +gran1=str2double(st_sink1):str2double(end_sink1); +%-------------------------------------% + +if probetype ==1 + disp ('Look at the CSD and find the layers which contain the sink(red)') + st_sink2 = input('Shank 2 begining of the sink: ','s'); + end_sink2 = input('Shank 2 Ending of the sink: ','s'); + gran2=str2double(st_sink2):str2double(end_sink2); +end +%% +%%% Now this and final section creates the average CSD across contacts +%%% given +%%% the user defined top and bottom of the sink(red) region in the CSD +%%% plots. The mean and the STD are calaucated for each layer. and the +%%% envelope of the std is ploted using the jbfill fx +axis_time=t1:t2; +if gran1(1)==2; + SG_c=(CSD_matrix1(1,axis_time)); + SG_std=std(CSD_matrix1(1,axis_time))./1; + SG_p=SG_c+SG_std; SG_m=SG_c-SG_std; +else + SG_c=mean(CSD_matrix1(1:(gran1(1)-1),axis_time),1); + SG_std=(std(CSD_matrix1((1:gran1(1)-1),axis_time),0,1))./size(CSD_matrix1(1:gran1(1)-1),2); + SG_p=SG_c+SG_std; SG_m=SG_c-SG_std; +end + G_c=mean(CSD_matrix1(gran1,axis_time),1); + G_std=(std(CSD_matrix1(gran1,axis_time),0,1))./size(CSD_matrix1(gran1),2); + G_p=G_c+G_std; G_m=G_c-G_std; + + IG_c=mean(CSD_matrix1((gran1(length(gran1))+1):size(CSD_matrix1,1),axis_time),1); + IG_std=(std(CSD_matrix1((gran1(length(gran1))+1):size(CSD_matrix1,1),axis_time),0,1))... + ./(length((gran1(length(gran1))+1):size(CSD_matrix1))); + IG_p=IG_c+IG_std; IG_m=IG_c-IG_std; +%% + figure_width = 12; + figure_height = 12; + FontSize = 12; + FontName = 'MyriadPro-Regular'; % or choose any other font + % --- setup plot windows + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + Avg_CSD1 = figure; + set(Avg_CSD1,'Visible', figuresVisible) + set(Avg_CSD1, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(Avg_CSD1, 'PaperPositionMode', 'auto'); + set(Avg_CSD1, 'Color', [1 1 1]); % Sets figure background + set(Avg_CSD1, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', Avg_CSD1); + set(hsp,'Position',[0.10 0.15 0.80 0.80]); + x=X2(axis_time)'; + hold on;handle_vector(:,1) = plot(x,SG_c,'r','LineWidth',2); + hold on; handle_vector(:,2) = jbfill(x,SG_p,SG_m,'r','r',1,.4); + hold on; handle_vector(:,3) = plot(x,G_c,'b','LineWidth',2); + hold on; handle_vector(:,4) = jbfill(x,G_p,G_m,'b','b',1,.4); + hold on; handle_vector(:,5) = plot(x,IG_c,'color',[0 .5 0],'LineWidth',2); + hold on; handle_vector(:,6) = jbfill(x,IG_p,IG_m,[0 .5 0],[0 .5 0],1,.4); + % will remove the 3rd legend entry. + hasbehavior(handle_vector(2),'legend',false); + hasbehavior(handle_vector(4),'legend',false); + hasbehavior(handle_vector(6),'legend',false); + % will remove the 3rd legend entry. + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [0 0] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + axis off + %export_fig ('Avg1', '-png','-r600','-opengl') + axis on + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'ytick', [],'tickdir','out'); + set(gca, 'YTickLabel', num2str(get(gca, 'YTick')')) + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'nA / mm^3'; + h=legend({'Supragranular','Granular','Infragranular'}); + set(h, 'Box', 'off','location', 'Best') + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Avg1 '); + set([gca, hXLabel, hYLabel, h], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + set(h, ... + 'FontSize' , 10 , ... + 'FontName' , FontName); + set(gca,'Layer', 'top'); + drawnow + export_fig (fig_title, '-png','-r600','-opengl') +%% +%%% Now this and final section creates the average CSD across contacts given +%%% the user defined top and bottom of the sink(red) region in the CSD +%%% plots. The mean and the STD are calaucated for each layer. and the +%%% envelope of the std is ploted using the jbfill fx +axis_time=t1:t2; +if probetype ==1 + if gran2(1)==2; + SG_c=(CSD_matrix2(1,axis_time)); + SG_std=std(CSD_matrix2(1,axis_time))./1; + SG_p=SG_c+SG_std; SG_m=SG_c-SG_std; + else + SG_c=mean(CSD_matrix2(1:(gran2(1)-1),axis_time),1); + SG_std=(std(CSD_matrix2((1:gran2(1)-1),axis_time),0,1))./sqrt(size(CSD_matrix2(1:gran2(1)-1),2)); % MK added square roots! + SG_p=SG_c+SG_std; SG_m=SG_c-SG_std; + end + G_c=mean(CSD_matrix2(gran2,axis_time),1); + G_std=(std(CSD_matrix2(gran2,axis_time),0,1))./sqrt(size(CSD_matrix2(gran2),2)); + G_p=G_c+G_std; G_m=G_c-G_std; + + IG_c=mean(CSD_matrix2((gran2(length(gran2))+1):size(CSD_matrix2,1),axis_time),1); + IG_std=(std(CSD_matrix2((gran2(length(gran2))+1):size(CSD_matrix2,1),axis_time),0,1))... + ./sqrt(length((gran1(length(gran1))+1):size(CSD_matrix2))); + IG_p=IG_c+IG_std; IG_m=IG_c-IG_std; +%% + + figure_width = 14; + figure_height = 12; + FontSize = 12; + FontName = 'MyriadPro-Regular'; % or choose any other font + % --- setup plot windows + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + Avg_CSD2 = figure; + set(Avg_CSD2,'Visible', figuresVisible) + set(Avg_CSD2, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(Avg_CSD2, 'PaperPositionMode', 'auto'); + set(Avg_CSD2, 'Color', [1 1 1]); % Sets figure background + set(Avg_CSD2, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', Avg_CSD2); + set(hsp,'Position',[0.10 0.15 0.80 0.80]); + x=X2(axis_time)'; + hold on;handle_vector(:,1) = plot(x,SG_c,'r','LineWidth',2); + hold on; handle_vector(:,2) = jbfill(x,SG_p,SG_m,'r','r',1,.4); + hold on; handle_vector(:,3) = plot(x,G_c,'b','LineWidth',2); + hold on; handle_vector(:,4) = jbfill(x,G_p,G_m,'b','b',1,.4); + hold on; handle_vector(:,5) = plot(x,IG_c,'color',[0 .5 0],'LineWidth',2); + hold on; handle_vector(:,6) = jbfill(x,IG_p,IG_m,[0 .5 0],[0 .5 0],1,.4); + % will remove the 3rd legend entry. + hasbehavior(handle_vector(2),'legend',false); + hasbehavior(handle_vector(4),'legend',false); + hasbehavior(handle_vector(6),'legend',false); + % will remove the 3rd legend entry. + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'out' , ... + 'TickLength' , [0 0] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + axis off + %export_fig ('Avg2', '-png','-r600','-opengl') + axis on + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200]) + set(gca, 'ytick', [],'tickdir','out'); + set(gca, 'YTickLabel', num2str(get(gca, 'YTick')')) + yaxis=ylim; + prestim_offset_y = yaxis(1):1:yaxis(2); + prestim_offset_t = ones(1, length(prestim_offset_y))*0; + hold on; plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'nA / mm^3'; + h=legend({'Supragranular','Granular','Infragranular'}); + set(h, 'Box', 'off','location', 'Best') + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Avg2 '); + set([gca, hXLabel, hYLabel, h], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + set(h, ... + 'FontSize' , 10 , ... + 'FontName' , FontName); + set(gca,'Layer', 'top'); + drawnow + export_fig (fig_title, '-png','-r600','-opengl') +end +%% + figure_width = 12; + figure_height = 10; + FontSize = 10; + FontName = 'MyriadPro-Regular'; % or choose any other font + % --- setup plot windows + figuresVisible = 'on'; % 'off' for non displayed plots (will still be exported) + CSD_fig2 = figure; + set(CSD_fig2,'Visible', figuresVisible) + set(CSD_fig2, 'units', 'centimeters', 'pos', [5 5 figure_width figure_height]) + set(CSD_fig2, 'PaperPositionMode', 'auto'); + set(CSD_fig2, 'Renderer','Zbuffer'); + set(CSD_fig2, 'Color', [1 1 1]); % Sets figure background + set(CSD_fig2, 'Color', [1 1 1]); % Sets axes background + % --- dimensions and position of plot + hsp = subplot(1,1,1, 'Parent', CSD_fig2); + set(hsp,'Position',[0.25 0.15 0.35 0.80]); + colorDepth = 1000; + colormap(flipud(jet(colorDepth))); +% pcolor(X2, 1:1:size(CSD_matrix1,1), CSD_matrix1); + imagesc(X2,[],CSD_matrix1) + shading interp; % do not interpolate pixels + axis on; % display axis + axis tight;% no white borders + set(gca, ... + 'Box' , 'off' , ... + 'TickDir' , 'in' , ... + 'Ydir' , 'reverse', ... + 'TickLength' , [.05 .05] , ... + 'XMinorTick' , 'off' , ... + 'YMinorTick' , 'off' , ... + 'XGrid' , 'off' , ... + 'YGrid' , 'off' , ... + 'XColor' , [.0 .0 .0], ... + 'YColor' , [.0 .0 .0], ... + 'LineWidth' , 0.6 ); + set(gca,'Xlim',[-25 225]); + set(gca,'XTickLabel',[0 200], 'Xtick', [0 200],'TickLength',[0.01 0.01]); + set(gca, 'yticklabel',1:1:size(CSD_matrix1,1), 'Ytick', 1:1:size(CSD_matrix1,1)); + xLabelText = 'Time from stimulus onset (ms)'; % greek letters in LaTeX Syntax + yLabelText = 'Depth from intial sink (mm)'; + hXLabel = xlabel(xLabelText); + hYLabel = ylabel(yLabelText); + fig_title=sprintf('%s','Shank 1'); + y_tick=1:.5:size(CSD_matrix1,1); +% c_y=find(y_tick==median(gran1)); +% contact_spacing = 150/spacing; +% p_y=find(y_tick==median(gran1)+contact_spacing/2); %below +% m_y=find(y_tick==median(gran1)-contact_spacing/2); %above +% infragran = find(y_tick==median(gran1)+contact_spacing*2); % make line for bottom of L5 +% y_label(c_y)=0; +% y_label(p_y)=0.100; +% y_label(m_y)=0-.100; +% % set(gca, 'yticklabel',[y_label(m_y) y_label(c_y) y_label(p_y)], 'Ytick', [y_tick(m_y) y_tick(c_y) y_tick(p_y)]); +% hold on;plot(get(gca,'xlim'),[median(gran1) median(gran1)],'-k','Linewidth',1.5); +% xaxis=xlim; +% hold on;plot(xaxis,[y_tick(p_y) y_tick(p_y)],'-k','Linewidth',.5); +% hold on;plot(xaxis,[y_tick(m_y) y_tick(m_y)],'-k','Linewidth',.5); +% hold on;plot(xaxis,[y_tick(infragran) y_tick(infragran)],'-k','Linewidth',.5); +% % yaxis=ylim; + + bounds = define_layers(spacing,num_channels,exp_path,1); + s_y = find(y_tick==bounds(1)); + p_y = find(y_tick==bounds(2)); + m_y = find(y_tick==bounds(3)); + infragran = find(y_tick==bounds(end)); +% set(gca, 'yticklabel',[y_label(m_y) y_label(c_y) y_label(p_y)], 'Ytick', [y_tick(m_y) y_tick(c_y) y_tick(p_y)]); + hold on;plot(get(gca,'xlim'),[y_tick(s_y) y_tick(s_y)],'-k','Linewidth',.5); + xaxis=xlim; + hold on;plot(xaxis,[y_tick(p_y) y_tick(p_y)],'-k','Linewidth',.5); + hold on;plot(xaxis,[y_tick(m_y) y_tick(m_y)],'-k','Linewidth',.5); + hold on;plot(xaxis,[y_tick(infragran) y_tick(infragran)],'-k','Linewidth',.5); + + +% prestim_offset_y = yaxis(1):1:yaxis(2); +% prestim_offset_t = ones(1, length(prestim_offset_y))*0; +% hold on;plot(prestim_offset_t, prestim_offset_y, 'k', 'linewidth',1); + caxis([min(min(CSD_matrix1)) max(max(CSD_matrix1))]); + zLabelText = 'nA / mm^3'; % greek letters in LaTeX Syntax + hcb = colorbar('eastoutside'); + h_bar = findobj(gcf,'Tag','Colorbar'); + initpos = get(h_bar,'Position'); + set(h_bar, ... + 'Position',[initpos(1)+initpos(3)*3.5 initpos(2)+initpos(4)*0.3 ... + initpos(3)*0.4 initpos(4)*0.4]); + hcLabel = ylabel(hcb,zLabelText); + set(hcb,'YTickLabel',{'Sink','Source'}, 'Ytick', [min(min(CSD_matrix1)) max(max(CSD_matrix1))]) + set(hcb, ... + 'Box' , 'on' , ... + 'TickDir' , 'in' , ... + 'TickLength' , [.010 .010] , ... + 'LineWidth' , 0.6); + set([gca, hXLabel, hYLabel], ... + 'FontSize' , FontSize , ... + 'FontName' , FontName); + set([hcb, hcLabel], ... + 'FontSize' , 11 , ... + 'FontName' , FontName); + ylabh=get(hcb,'Ylabel'); + set(ylabh,'Position',get(ylabh,'Position')-[8 0 0]); + set(gca,'Layer', 'top'); + drawnow + export_fig (fig_title, '-png','-r600','-zbuffer'); + print2eps(fig_title) +end +%% +savefile=sprintf('%s%s','FinalCSD','.mat'); +save (savefile); + +% define_layers(spacing,num_channels,exp_path) +% close all +% clear all +% close all +% clear all +% clc +end \ No newline at end of file diff --git a/Intancode_Megan/Plotting/make_psth_plot.m b/Intancode_Megan/Plotting/make_psth_plot.m new file mode 100644 index 0000000..cd225dd --- /dev/null +++ b/Intancode_Megan/Plotting/make_psth_plot.m @@ -0,0 +1,45 @@ +function make_psth_plot(binsize,spikes,which_trials,prestim,stimtime,totaltime,light_trialtypes,light_start,light_dur) + +% binsize = size of bins in which to count spikes (in sec) +% spikes = cell array of a single unit's spike times with length of number of trials. +% which_trials = 1xnum_trials vector of 1s and 0s, 1s indicating trials to look +% prestim = time before visual stimulus onset (in sec) +% stimtime = duration of visual stimulus (in sec) +% totaltime = total time of trial(in sec) +% light_trialtypes = 1xnumtrials vector defining each trial's light + % condition +% light_start = time when the light started (in sec) (if not an opto + % experiment, should be []) +% light_dur = duration of light pulse (in sec) (if not an opto + % experiment, should be []) + + color_mat = [0 0 0; 0 .8 1; 0 0 1; 0 0.5 .4; 0 .7 .2]; % for graphing purposes (first is black, last is green) + + +edges = [0:binsize:totaltime-binsize]; +psth = make_psth(binsize,edges,which_trials,spikes,light_trialtypes); + +edges_stim = [-prestim:binsize:(totaltime-prestim-binsize)]'; % x signifies the timepoint of the START of the bin +for c = 1:size(psth,2) + plot(edges_stim,psth(:,c),'color',color_mat(c,:),'linewidth',2) + hold on +end + +xlim([-prestim totaltime-prestim-binsize]) % because points mark the START of the bin +set(gca,'XMinorTick','on') +yax = get(gca,'YLim'); +line([0 0], [0 yax(2)]','Color','r','LineStyle','--') +line([stimtime stimtime], [0 yax(2)]','Color','r','LineStyle','--') +xlabel('Time (sec)','fontsize',14) +ylabel('spikes/sec','Fontsize',14) + +% if it's not an opto experiment, draw patch +if ~isempty(light_start) + x1 = light_start - prestim; % when the light starts + xx = [x1 x1 x1+light_dur x1+light_dur x1]; + yy = [0 yax(2) yax(2) 0 0]; + patch(xx, yy, -1 * ones(size(xx)), [0.9 0.9 0.9], 'LineStyle', 'none') +end + +end + \ No newline at end of file diff --git a/Intancode_Megan/Plotting/make_raster_plot.asv b/Intancode_Megan/Plotting/make_raster_plot.asv new file mode 100644 index 0000000..702e6f4 --- /dev/null +++ b/Intancode_Megan/Plotting/make_raster_plot.asv @@ -0,0 +1,69 @@ +function make_raster_plot(spikes,Fs,prestim,totaltime,light_trialtypes,light_start,pulse_dur) + +% spikes = cell array of a single unit's spike times with length of number of trials. +% Fs = sampling rate (in sec) +% prestim = time before visual stimulus onset (in sec) +% totaltime = total time of trial(in sec) +% light_trialtypes = 1xnumtrials vector defining each trial's light + % condition +% light_start = time when the light started (in sec) +% pulse_dur = duration of light pulse (in sec) + % pulse_dur in trains experiments) + +spike_raster = make_raster(spikes,Fs,totaltime); +num_trials = length(spikes); +color_mat = [0 0 0; 0 0 1; 0 .8 1; 0 0.5 .4; 0 .7 .2]; % for graphing purposes (first is black, last is green) + +time_vec = linspace(-prestim,totaltime-prestim,size(spike_raster,2)); % for x-axis +cond_colors = ones(1,num_trials); % just in case you have multiple conditions + +% if light experiment, add blue shading on raster +if length(unique(light_trialtypes)) > 1 % it was an opto experiment if there's more than one "light" condition (one condition would be nolight) + [cond,idx] = sort(light_trialtypes); % sort trials by light conditions + diff_conds = unique(cond); + new_spike_rast = spike_raster(idx,:); % reordered according to light condition + new_spike_rast(find(~new_spike_rast)) = nan; % so that you don't plot absence of spikes as y=0 + for c = 1:length(diff_conds) + cond_colors(find(cond==diff_conds(c)))=c; + end + start_patch = find(cond>0,1,'first'); % first trial with light + end_patch = num_trials; % assumes all trials where cond > 0 had light + x1 = light_start-prestim; % when the light starts + + for c = 1:length(diff_conds) + start_patch = find(cond==diff_conds(c),1,'first')-1; + end_patch = find(cond==diff_conds(c),1,'last')-1; + if sum(diff_conds>10) % if it was a trains experiment + for p = 1:(light_trialtypes(idx(end_patch))) + space = 1/(light_trialtypes(idx(end_patch))); + patch([x1+((p-1)*space) x1+((p-1)*space) x1+pulse_dur+((p-1)*space) x1+pulse_dur+((p-1)*space) x1+((p-1)*space)],[start_patch end_patch end_patch start_patch start_patch], [0.9 0.9 0.9], 'LineStyle', 'none') + end + elseif diff_conds(c) % any other light condition + patch([x1 x1 x1+pulse_dur x1+pulse_dur x1],[start_patch end_patch end_patch start_patch start_patch], [0.9 0.9 0.9], 'LineStyle', 'none') + end + line([prestim totaltime-prestim], [end_patch end_patch]','Color','r','LineStyle','--') + end + + +% patch([x1 x1 border border x1],[start_patch end_patch end_patch start_patch start_patch], [0.9 0.9 0.9], 'LineStyle', 'none') + hold on +end + +if exist('xrange','var') + rasterrange = [find(time_vec==.4):find(time_vec==.8)]; +else + rasterrange = 1:size(new_spike_rast,2); +end + +% draw raster +for t = 1:num_trials % for each trial + new_spike_rast(t,find(new_spike_rast(t,:))) = new_spike_rast(t,find(new_spike_rast(t,:)))+(t-1); % plot 'ones' in vector so that y = trial number + plot(time_vec(rasterrange),new_spike_rast(t,rasterrange),'.','Color',color_mat(cond_colors(t),:),'MarkerSize',6) + hold on +end +ylim([0 num_trials]) + +xlabel('Time from visual stimulus onset (sec)') +ylabel('Trial (by condition)') + +return \ No newline at end of file diff --git a/Intancode_Megan/Plotting/make_raster_plot.m b/Intancode_Megan/Plotting/make_raster_plot.m new file mode 100644 index 0000000..7f26b81 --- /dev/null +++ b/Intancode_Megan/Plotting/make_raster_plot.m @@ -0,0 +1,70 @@ +function make_raster_plot(spikes,Fs,prestim,totaltime,light_trialtypes,light_start,pulse_dur) + +% spikes = cell array of a single unit's spike times with length of number of trials. +% Fs = sampling rate (in sec) +% prestim = time before visual stimulus onset (in sec) +% totaltime = total time of trial(in sec) +% light_trialtypes = 1xnumtrials vector defining each trial's light + % condition +% light_start = time when the light started (in sec) +% pulse_dur = duration of light pulse (in sec) + % pulse_dur in trains experiments) + +spike_raster = make_raster(spikes,Fs,totaltime); +num_trials = length(spikes); + color_mat = [0 0 0; 0 .8 1; 0 0 1; 0 0.5 .4; 0 .7 .2]; % for graphing purposes (first is black, last is green) + +time_vec = linspace(-prestim,totaltime-prestim,size(spike_raster,2)); % for x-axis +cond_colors = ones(1,num_trials); % just in case you have multiple conditions + +% if light experiment, add blue shading on raster +if length(unique(light_trialtypes)) > 1 % it was an opto experiment if there's more than one "light" condition (one condition would be nolight) + [cond,idx] = sort(light_trialtypes); % sort trials by light conditions + diff_conds = unique(cond); + new_spike_rast = spike_raster(idx,:); % reordered according to light condition + new_spike_rast(find(~new_spike_rast)) = nan; % so that you don't plot absence of spikes as y=0 + for c = 1:length(diff_conds) + cond_colors(find(cond==diff_conds(c)))=c; + end + start_patch = find(cond>0,1,'first'); % first trial with light + end_patch = num_trials; % assumes all trials where cond > 0 had light + x1 = light_start-prestim; % when the light starts + + for c = 1:length(diff_conds) + start_patch = find(cond==diff_conds(c),1,'first')-1; + end_patch = find(cond==diff_conds(c),1,'last')-1; + if sum(diff_conds>10) % if it was a trains experiment + for p = 1:(light_trialtypes(idx(end_patch))) + space = 1/(light_trialtypes(idx(end_patch))); + patch([x1+((p-1)*space) x1+((p-1)*space) x1+pulse_dur+((p-1)*space) x1+pulse_dur+((p-1)*space) x1+((p-1)*space)],[start_patch end_patch end_patch start_patch start_patch], [0.9 0.9 0.9], 'LineStyle', 'none') + end + elseif diff_conds(c) % any other light condition + patch([x1 x1 x1+pulse_dur x1+pulse_dur x1],[start_patch end_patch end_patch start_patch start_patch], [0.9 0.9 0.9], 'LineStyle', 'none') + end + line([-prestim totaltime-prestim], [end_patch end_patch]','Color','r','LineStyle','--') + end + + +% patch([x1 x1 border border x1],[start_patch end_patch end_patch start_patch start_patch], [0.9 0.9 0.9], 'LineStyle', 'none') + hold on +end + +if exist('xrange','var') + rasterrange = [find(time_vec==.4):find(time_vec==.8)]; +else + rasterrange = 1:size(new_spike_rast,2); +end + +% draw raster +for t = 1:num_trials % for each trial + new_spike_rast(t,find(new_spike_rast(t,:))) = new_spike_rast(t,find(new_spike_rast(t,:)))+(t-1); % plot 'ones' in vector so that y = trial number + plot(time_vec(rasterrange),new_spike_rast(t,rasterrange),'.','Color',color_mat(cond_colors(t),:),'MarkerSize',6) + hold on +end +ylim([0 num_trials]) +xlim([-prestim totaltime-prestim]) + +xlabel('Time from visual stimulus onset (sec)','fontsize',14) +ylabel('Trial (by condition)','fontsize',14) + +return \ No newline at end of file diff --git a/Intancode_Megan/README.md b/Intancode_Megan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4457106ba74365c7c9f869e3816f7974ee382074 GIT binary patch literal 32 mcmezWPnki1!IvSGA)O(SA&)_q!IQy{A%wvZNb)jpF#rI8vIXY= literal 0 HcmV?d00001 diff --git a/Intancode_Megan/Tlx_analysis_master.asv b/Intancode_Megan/Tlx_analysis_master.asv new file mode 100644 index 0000000..0e52af7 --- /dev/null +++ b/Intancode_Megan/Tlx_analysis_master.asv @@ -0,0 +1,376 @@ +function Tlx_analysis_master(exp_type) + +main_dir = 'H:\Tlx3project\Augustresults'; +cd(main_dir) +fig_dir = sprintf('H:\\Tlx3project\\Augustresults\\%s_figs',exp_type); + +if ~exist(fig_dir,'dir') + mkdir(fig_dir) +end + +if strcmp(exp_type,'intensities') + + exp_paths = {'H:\Tlx3project\T18\5-3-16\T18_diffintensities_160503_171447',... + 'H:\Tlx3project\T18\5-5-16\T18_run2_diffintensities_160505_092232',... + 'H:\Tlx3project\T19\5-2-16\T19_diffintensities_160502_210213',... + 'H:\Tlx3project\T19\5-3-16\T19_run2_diffintensities_160503_221201',... + 'H:\Tlx3project\T22\7-26-16\T22_diffintensities_160726_171349'}; + +elseif strcmp(exp_type,'ramp') + exp_paths = {'H:\Tlx3project\T14\T14_driftgratingwithramp_160329_175645',... + 'H:\Tlx3project\T15\4-1-16\T15_driftgratingramp_160325_205545',... + 'H:\Tlx3project\T18\5-3-16\T18_ramp_160503_182443',... + 'H:\Tlx3project\T18\5-5-16\T18_run2_ramp_160505_103140',... + 'H:\Tlx3project\T19\5-3-16\T19_run2_ramp_160503_211551',... + 'H:\Tlx3project\T22\7-26-16\T22_ramp_160726_161333',... + }; + +elseif strcmp(exp_type,'trains') + +exp_paths = {'H:\Tlx3project\T9\T9_driftgrating_trains_160125_123706',... + 'H:\Tlx3project\T14\T14_driftgratingtrains_160329_211516',... + 'H:\Tlx3project\T15\3-31-16\T15_driftgratingtrains_160324_214136',... + 'H:\Tlx3project\T19\5-2-16\T19_trains_160502_222135',... + 'H:\Tlx3project\T18\5-3-16\T18_trains_160503_192729',... + 'H:\Tlx3project\T22\7-26-16\T22_trains_160726_183114'}; + +elseif strcmp(exp_type,'inhibit') + exp_paths = {'H:\Tlx3project\TiC1\TiC1_step_160901_141812',... + 'H:\Tlx3project\TiC2\8-31-16\TiC2_step_160831_121353'}; + +end + +count = 1; +for i = 1:length(exp_paths) + exp_path = exp_paths{i}; + % get experiment name + out = regexp(exp_path,'\\','split'); + inds = regexp(out{end},'_\d','start'); % looks for what's before an underscore followed immediately by a number; uses that as exp_name + exp_name = out{end}(1:inds(1)-1); + exp_dir = strcat(main_dir,'\',exp_name); + fprintf(sprintf('Processing experiment %s\n',exp_name)) +% if i == 1 +% intan_analysis_master(exp_path,exp_type); +% end + + % load results + cd(exp_dir) + s = dir; + for ii=1:length(s) + if strfind(s(ii).name,'_results') + results_file = s(ii).name; + end + end + S{i} = importdata(results_file,'-mat'); % load results mat + load(sprintf('%s\\light_params.mat',exp_path)) + lightconds = unique(all_light); +end + +count = 0; +for s = 1:length(S) + for n = 1:S{s}.numunits + if length(S{s}.lightconds)>4 % TEMP - HACK - skip 10hz condition + which_ones = [1 3 4]; + else + which_ones = [1:length(S{s}.lightconds)-1]; + end + % which light condition to use for comparisons +% if strcmp(exp_type,'trains') +% which_lightcond = length(S{s}.lightconds); % use highest frequency % change to make best for particular unit!! +% else +% which_lightcond(count) = 2; % use first light condition (e.g. lowest intensity) +% end + +% if S{s}.FRs(n).ev(1) > .25 % pretty liberal cut-off for which cells to include + count = count+1; + name{count} = S{s}.unitinfo(n).name; + layer(count) = S{s}.unitinfo(n).layer; + vissig(count) = S{s}.unitinfo(n).vissig; + vissig2(count) = S{s}.unitinfo(n).vissig2; + lightsig_vis(count,:) = S{s}.unitinfo(n).lightsig_vis(which_ones); + lightsig_blnk(count,:) = S{s}.unitinfo(n).lightsig_blnk(which_ones); + if length(S{s}.lightconds)>4 % TEMP - HACK + FRev(count,:) = S{s}.FRs(n).ev([1 which_ones+1]); % need to fix - currently contains both FRs and SEs + else + FRev(count,:) = S{s}.FRs(n).ev(1:length(S{s}.FRs(n).ev)/2); % need to fix - currently contains both FRs and SEs + end + + for ii = 2:length(FRev(count,:)) + evdiff(ii-1) = diff(FRev(count,[1 ii]),[],2); % get which light condition resulted in largest change in FR for each unit + end + [~,which_lightcond(count)] = max(abs(evdiff),[],2); + which_lightcond(count) = which_lightcond(count)+1; + + baseline(count) = S{s}.FRs(n).baseline; + if ~isempty(S{s}.FRs(n).SALT10ms) + SALT10ms(count,:) = S{s}.FRs(n).SALT10ms(which_ones); + SALT5ms(count,:) = S{s}.FRs(n).SALT5ms(which_ones); + SALT2ms(count,:) = S{s}.FRs(n).SALT2ms(which_ones); + end + OSI(count,:) = S{s}.tuning(n).OSI(([1 which_ones+1])); + OSI_CV(count,:) = S{s}.tuning(n).OSI_CV([1 which_ones+1]); + DSI(count,:) = S{s}.tuning(n).DSI([1 which_ones+1]); + DSI_CV(count,:) = S{s}.tuning(n).DSI_CV([1 which_ones+1]); + sig_Hot(count,:) = S{s}.tuning(n).sig_Hot([1 which_ones+1]); + sig_Hot2(count,:) = S{s}.tuning(n).sig_Hot2([1 which_ones+1]); + tuning_curve_collapse = zeros(length(S{s}.lightconds),size(S{s}.tuning(n).curve,2)/2); % reset + for o = 1:size(S{s}.tuning(n).curve,2)/2 + tuning_curve_collapse(:,o) = mean([S{s}.tuning(n).curve(:,o) S{s}.tuning(n).curve(:,o+size(S{s}.tuning(n).curve,2)/2)],2); % average evoked FR of same orientations but different directions in NO LIGHT condition + end + [~,pref_deg] = max(tuning_curve_collapse(1,:)); + if length(pref_deg) > 1 + [~,prefpref] = max(tuning_curve_collapse(2,pref_deg)); + pref_deg = pref_deg(prefpref); + end + prefFR_delta(count) = abs(diff(tuning_curve_collapse([1 which_lightcond(count)],pref_deg))); % when more than two light conditions, using only first light condition vs no light + if pref_deg <= size(S{s}.tuning(n).curve,2)/4 + orth_deg = pref_deg+size(S{s}.tuning(n).curve,2)/4; + else + orth_deg = pref_deg-size(S{s}.tuning(n).curve,2)/4; + end + % check if cells should be excluded from tuning analysis (no FR + % at any orientation <-.5 or >-.5) + if abs(tuning_curve_collapse(1,pref_deg)) < .5 + include(count) = 0; + else + include(count) = 1; + end + + orthFR_delta(count) = abs(diff(tuning_curve_collapse([1 which_lightcond(count)],orth_deg))); + % sig_Hot_polar(count,:) = S{s}.tuning(n).sig_Hot_polar([1 which_ones+1]); + t2p_t(count) = S{s}.waveforms(n).t2p_t; + t2p_r(count) = S{s}.waveforms(n).t2p_r; + fwhm(count) = S{s}.waveforms(n).fwhm; + + lightmod(count) = diff(FRev(count,[1 which_lightcond(count)]))./sum(FRev(count,[1 which_lightcond(count)])); +% end + end +end + + +% get different cell types +visual_cells = find((vissig < .05)|(vissig2 < .05)); +light_cells= find(min(lightsig_vis,[],2)<.05); % find cells with significant effect in any light condition +tuned_cells = find(sig_Hot(:,1) < .05); +tuned_cells2 = find(sig_Hot2(:,1) < .05); +% tuned_cells(find(FRev(tuned_cells,1)<.5)) = []; % exclude cells with <.5 baseline FR from being considered "tuned" +tuned_cells = tuned_cells(ismember(tuned_cells,find(include))); +if strcmp(exp_type,'trains') + onset_cells = find(mean(SALT10ms,2)<.05); + quikonset_cells = find(mean(SALT5ms,2)<.05); + tlx_cells = find(mean(SALT2ms,2)<.05); +elseif strcmp(exp_type,'intensities') + onset_cells = find(min(SALT10ms,[],2)<.05); + quikonset_cells = find(min(SALT5ms,[],2)<.05); + tlx_cells = find(min(SALT2ms,[],2)<.05); +end +FS_cells = find(t2p_t < .65); +reg_cells = find(t2p_t >= .65); + +chs_23 = find(layer == 2.5); +chs_4 = find(layer == 4); +chs_5 = find(layer == 5); +chs_55 = find(layer == 5.5); +chs_6 = find(layer == 6); +infgran = [chs_5 chs_55 chs_6]; + +% get means and medians for overall (1st row), supra (2nd) gran (3rd) and infragran (4th) layers for +%reg-spiking (first column) and fast-spiking (second column) +median_sum = [nanmedian(OSI_CV(reg_cells,1)) nanmedian(OSI_CV(FS_cells,1)); + nanmedian(OSI_CV(intersect(chs_23,reg_cells),1)) nanmedian(OSI_CV(intersect(chs_23,FS_cells),1)); + nanmedian(OSI_CV(intersect(chs_4,reg_cells),1)) nanmedian(OSI_CV(intersect(chs_4,FS_cells),1)); + nanmedian(OSI_CV(intersect(infgran,reg_cells),1)) nanmedian(OSI_CV(intersect(infgran,FS_cells),1))]; +mean_sum = [nanmean(OSI_CV(reg_cells,1)) nanmean(OSI_CV(FS_cells,1)); + nanmean(OSI_CV(intersect(chs_23,reg_cells),1)) nanmean(OSI_CV(intersect(chs_23,FS_cells),1)); + nanmean(OSI_CV(intersect(chs_4,reg_cells),1)) nanmean(OSI_CV(intersect(chs_4,FS_cells),1)); + nanmean(OSI_CV(intersect(infgran,reg_cells),1)) nanmean(OSI_CV(intersect(infgran,FS_cells),1))]; +groupn = [length(~isnan(OSI_CV(reg_cells,1))) length(~isnan(OSI_CV(FS_cells,1))); + length(isnan(OSI_CV(intersect(chs_23,reg_cells),1))) length(~isnan(OSI_CV(intersect(chs_23,FS_cells),1))); + length(isnan(OSI_CV(intersect(chs_4,reg_cells),1))) length(~isnan(OSI_CV(intersect(chs_4,FS_cells),1))); + length(isnan(OSI_CV(intersect(infgran,reg_cells),1))) length(~isnan(OSI_CV(intersect(infgran,FS_cells),1)))]; + +cd(fig_dir) +barplot_by_layer(lightmod,layer,ones(1,length(layer)),'Light modulation index','Lightmodulation (evoked)') +barplot_by_layer(OSI_CV',layer,ones(1,length(layer)),'Orientation selectivity index (CV)','OSI (CV)') +barplot_by_layer(DSI_CV',layer,ones(1,length(layer)),'Direction selectivity index (CV)','DSI (CV)') +barplot_by_layer(OSI',layer,ones(1,length(layer)),'Orientation selectivity index','OSI') +barplot_by_layer(DSI',layer,ones(1,length(layer)),'Direction selectivity index','DSI') +barplot_by_layer(diff(OSI_CV(tuned_cells,:),[],2)',layer(tuned_cells),ones(1,length(layer(tuned_cells))),'OSI CV change (light-no light)','OSI change') +barplot_by_layer(diff(DSI_CV(tuned_cells,:),[],2)',layer(tuned_cells),ones(1,length(layer(tuned_cells))),'DSI CV change (light-no light)','DSI change') +if ~strcmp(exp_type,'ramp') + barplot_by_layer(lightmod(onset_cells),layer(onset_cells),ones(1,length(onset_cells)),'Light modulation index','Lightmodulation (onset cells)') +end + +% FS cells +FSFR_fig = figure('name','FS firing rate: No Light vs. Light'); +plot(FRev(intersect(chs_23,FS_cells),1),FRev(intersect(chs_23,FS_cells),mode(which_lightcond)),'r.','MarkerSize',24) +hold on +plot(FRev(intersect(chs_4,FS_cells),1),FRev(intersect(chs_4,FS_cells),mode(which_lightcond)),'b.','MarkerSize',24) +plot(FRev(intersect(chs_5,FS_cells),1),FRev(intersect(chs_5,FS_cells),mode(which_lightcond)),'g.','MarkerSize',24) +plot(FRev(intersect(chs_55,FS_cells),1),FRev(intersect(chs_55,FS_cells),mode(which_lightcond)),'k.','MarkerSize',24) +plot(FRev(intersect(chs_6,FS_cells),1),FRev(intersect(chs_6,FS_cells),mode(which_lightcond)),'c.','MarkerSize',24) +xlabel('Firing rate (spks/s) - No Light','Fontsize',24) +ylabel('Firing rate (spks/s) - Light','Fontsize',24) +xax = get(gca,'XLim'); +yax = get(gca,'YLim'); +x = [min(xax(1),yax(1)):1:max(xax(2),yax(2))]; +y=x; +plot(x,y,'k'); +xlim([min(xax(1),yax(1)), max(xax(2),yax(2))]) +ylim([min(xax(1),yax(1)), max(xax(2),yax(2))]) +% xlim([0 25]) +% ylim([0 25]) +set(gca,'fontsize',18) +l=legend('L2/3','L4','L5A','L5B','L6','Location','SouthEast'); +set(l,'fontsize',18) +print(FSFR_fig, '-dpng','FiringRate_FS') + +% RS cells +RSFR_fig = figure('name','RS firing rate: No Light vs. Light'); +plot(FRev(intersect(chs_23,reg_cells),1),FRev(intersect(chs_23,reg_cells),mode(which_lightcond)),'r.','MarkerSize',24) +hold on +plot(FRev(intersect(chs_4,reg_cells),1),FRev(intersect(chs_4,reg_cells),mode(which_lightcond)),'b.','MarkerSize',24) +plot(FRev(intersect(chs_5,reg_cells),1),FRev(intersect(chs_5,reg_cells),mode(which_lightcond)),'g.','MarkerSize',24) +plot(FRev(intersect(chs_55,reg_cells),1),FRev(intersect(chs_55,reg_cells),mode(which_lightcond)),'k.','MarkerSize',24) +plot(FRev(intersect(chs_6,reg_cells),1),FRev(intersect(chs_6,reg_cells),mode(which_lightcond)),'c.','MarkerSize',24) +xlabel('Firing rate (spks/s) - No Light','Fontsize',24) +ylabel('Firing rate (spks/s) - Light','Fontsize',24) +xax = get(gca,'XLim'); +yax = get(gca,'YLim'); +x = [min(xax(1),yax(1)):1:max(xax(2),yax(2))]; +y=x; +plot(x,y,'k'); +xlim([min(xax(1),yax(1)), max(xax(2),yax(2))]) +ylim([min(xax(1),yax(1)), max(xax(2),yax(2))]) +% xlim([0 25]) +% ylim([0 25]) +set(gca,'fontsize',18) +l=legend('L2/3','L4','L5A','L5B','L6','Location','SouthEast'); +set(l,'fontsize',18) +print(RSFR_fig, '-dpng','FiringRate_RS') + +osi_fig = figure('name','OSI Change (light-nolight) vs. Light modulation'); +plot(diff(OSI_CV(intersect(tuned_cells,chs_23),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_23)),'r.','MarkerSize',24) +hold on +plot(diff(OSI_CV(intersect(tuned_cells,chs_4),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_4)),'b.','MarkerSize',24) +plot(diff(OSI_CV(intersect(tuned_cells,chs_5),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_5)),'g.','MarkerSize',24) +plot(diff(OSI_CV(intersect(tuned_cells,chs_55),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_55)),'k.','MarkerSize',24) +plot(diff(OSI_CV(intersect(tuned_cells,chs_6),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_6)),'c.','MarkerSize',24) +xlabel('change in OSI CV (light - no light)','Fontsize',24) +ylabel('Light modulation index','Fontsize',24) +line([0 0],[-1 1],'Color','k') +line([-1 1],[0 0],'Color','k') +set(gca,'fontsize',18) +l=legend('L2/3','L4','L5A','L5B','L6','Location','SouthEast'); +set(l,'fontsize',18) +print(osi_fig, '-dpng','OSIvslight') +% print2eps('OSIvslight', osi_fig) + +osi_cellfig = figure('name','OSI Change (light-nolight) vs. Light modulation'); +plot(diff(OSI_CV(intersect(reg_cells,tuned_cells),[1 mode(which_lightcond)]),[],2),lightmod(intersect(reg_cells,tuned_cells)),'r.','MarkerSize',24) +hold on +plot(diff(OSI_CV(intersect(FS_cells,tuned_cells),[1 mode(which_lightcond)]),[],2),lightmod(intersect(FS_cells,tuned_cells)),'b.','MarkerSize',24) +xlabel('change in OSI CV (light - no light)','Fontsize',24) +ylabel('Light modulation index','Fontsize',24) +line([0 0],[-1 1],'Color','k') +line([-1 1],[0 0],'Color','k') +set(gca,'fontsize',18) +l=legend('Regular spiking','Fast spiking'); +set(l,'fontsize',18) +print(osi_cellfig, '-dpng','OSIvslight_bycelltype') + +dsi_cellfig = figure('name','DSI Change (light-nolight) vs. Light modulation'); +plot(diff(DSI_CV(intersect(reg_cells,tuned_cells),[1 mode(which_lightcond)]),[],2),lightmod(intersect(reg_cells,tuned_cells)),'r.','MarkerSize',24) +hold on +plot(diff(DSI_CV(intersect(FS_cells,tuned_cells),[1 mode(which_lightcond)]),[],2),lightmod(intersect(FS_cells,tuned_cells)),'b.','MarkerSize',24) +xlabel('change in DSI CV (light - no light)','Fontsize',24) +ylabel('Light modulation index','Fontsize',24) +line([0 0],[-1 1],'Color','k') +line([-1 1],[0 0],'Color','k') +set(gca,'fontsize',18) +l=legend('Regular spiking','Fast spiking'); +set(l,'fontsize',18) +print(dsi_cellfig, '-dpng','DSIvslight_bycelltype') + +dsi_fig = figure('name','OSI Change (light-nolight) vs. Light modulation'); +plot(diff(DSI_CV(intersect(tuned_cells,chs_23),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_23)),'r.','MarkerSize',24) +hold on +plot(diff(DSI_CV(intersect(tuned_cells,chs_4),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_4)),'b.','MarkerSize',24) +plot(diff(DSI_CV(intersect(tuned_cells,chs_5),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_5)),'g.','MarkerSize',24) +plot(diff(DSI_CV(intersect(tuned_cells,chs_55),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_55)),'k.','MarkerSize',24) +plot(diff(DSI_CV(intersect(tuned_cells,chs_6),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_6)),'c.','MarkerSize',24) +xlabel('change in DSI CV (light - no light)','Fontsize',24) +ylabel('Light modulation index','Fontsize',24) +line([0 0],[-1 1],'Color','k') +line([-1 1],[0 0],'Color','k') +set(gca,'fontsize',18) +l=legend('L2/3','L4','L5A','L5B','L6','Location','SouthEast'); +set(l,'fontsize',18) +print(dsi_fig, '-dpng','DSIvslight') +% print2eps('OSIvslight', dsi_fig) + +plot_OSI(layer,OSI_CV,'OSI (CV)') +plot_OSI(layer,DSI_CV,'DSI (CV)') + +% additive vs multiplicative changes +change_by_celltype = figure('name','Change in orthogonal vs preferred FR'); +plot(orthFR_delta(reg_cells),prefFR_delta(reg_cells),'r.','MarkerSize',24) +hold on +plot(orthFR_delta(FS_cells),prefFR_delta(FS_cells),'b.','MarkerSize',24) +xax = get(gca,'XLim'); +yax = get(gca,'YLim'); +x = [min(xax(1),yax(1)):1:max(xax(2),yax(2))]; +y=x; +plot(x,y,'k'); +coeffs(1,:) = polyfit(orthFR_delta(reg_cells), prefFR_delta(reg_cells), 1); +coeffs(2,:) = polyfit(orthFR_delta(FS_cells), prefFR_delta(FS_cells), 1); +% Get fitted values +fittedX = linspace(min(orthFR_delta), max(orthFR_delta), 200); +for i = 1:size(coeffs,1) + fittedY(i,:) = polyval(coeffs(i,:), fittedX); +end +plot(fittedX,fittedY(1,:),'r') +plot(fittedX,fittedY(2,:),'b') +xlabel('Change in orthogonal FR','fontsize',24) +ylabel('Change in preferred FR','fontsize',24) +set(gca,'fontsize',18) +l=legend('Regular spiking','Fast spiking'); +set(l,'fontsize',18) +print(change_by_celltype, '-dpng','FRchange_bycelltype') + +% diff layers +change_by_layer = figure('name','Change in orthogonal vs preferred FR'); +plot(orthFR_delta(chs_23),prefFR_delta(chs_23),'r.','MarkerSize',24) +hold on +plot(orthFR_delta(chs_4),prefFR_delta(chs_4),'b.','MarkerSize',24) +plot(orthFR_delta(chs_5),prefFR_delta(chs_5),'g.','MarkerSize',24) +plot(orthFR_delta(chs_55),prefFR_delta(chs_55),'k.','MarkerSize',24) +plot(orthFR_delta(chs_6),prefFR_delta(chs_6),'c.','MarkerSize',24) +xax = get(gca,'XLim'); +yax = get(gca,'YLim'); +x = [min(xax(1),yax(1)):1:max(xax(2),yax(2))]; +y=x; +plot(x,y,'k--'); +coeffs(1,:) = polyfit(orthFR_delta(chs_23), prefFR_delta(chs_23), 1); +coeffs(2,:) = polyfit(orthFR_delta(chs_4), prefFR_delta(chs_4), 1); +coeffs(3,:) = polyfit(orthFR_delta(chs_5), prefFR_delta(chs_5), 1); +coeffs(4,:) = polyfit(orthFR_delta(chs_55), prefFR_delta(chs_55), 1); +coeffs(5,:) = polyfit(orthFR_delta(chs_6), prefFR_delta(chs_6), 1); +% Get fitted values +fittedX = linspace(min(orthFR_delta), max(orthFR_delta), 200); +for i = 1:size(coeffs,1) + fittedY(i,:) = polyval(coeffs(i,:), fittedX); +end +plot(fittedX,fittedY(1,:),'r') +plot(fittedX,fittedY(2,:),'b') +plot(fittedX,fittedY(3,:),'g') +plot(fittedX,fittedY(4,:),'k') +plot(fittedX,fittedY(5,:),'c') +xlabel('Change in orthogonal FR','fontsize',24) +ylabel('Change in preferred FR','fontsize',24) +set(gca,'fontsize',18) +l=legend('L2/3','L4','L5A','L5B','L6','Location','SouthEast'); +set(l,'fontsize',18) +print(change_by_layer, '-dpng','FRchange_bylayer') + +end diff --git a/Intancode_Megan/Tlx_analysis_master.m b/Intancode_Megan/Tlx_analysis_master.m new file mode 100644 index 0000000..104dfae --- /dev/null +++ b/Intancode_Megan/Tlx_analysis_master.m @@ -0,0 +1,376 @@ +function Tlx_analysis_master(exp_type) + +main_dir = 'H:\Tlx3project\Augustresults'; +cd(main_dir) +fig_dir = sprintf('H:\\Tlx3project\\Augustresults\\%s_figs',exp_type); + +if ~exist(fig_dir,'dir') + mkdir(fig_dir) +end + +if strcmp(exp_type,'intensities') + + exp_paths = {'H:\Tlx3project\T18\5-3-16\T18_diffintensities_160503_171447',... + 'H:\Tlx3project\T18\5-5-16\T18_run2_diffintensities_160505_092232',... + 'H:\Tlx3project\T19\5-2-16\T19_diffintensities_160502_210213',... + 'H:\Tlx3project\T19\5-3-16\T19_run2_diffintensities_160503_221201',... + 'H:\Tlx3project\T22\7-26-16\T22_diffintensities_160726_171349'}; + +elseif strcmp(exp_type,'ramp') + exp_paths = {'H:\Tlx3project\T14\T14_driftgratingwithramp_160329_175645',... + 'H:\Tlx3project\T15\4-1-16\T15_driftgratingramp_160325_205545',... + 'H:\Tlx3project\T18\5-3-16\T18_ramp_160503_182443',... + 'H:\Tlx3project\T18\5-5-16\T18_run2_ramp_160505_103140',... + 'H:\Tlx3project\T19\5-3-16\T19_run2_ramp_160503_211551',... + 'H:\Tlx3project\T22\7-26-16\T22_ramp_160726_161333',... + }; + +elseif strcmp(exp_type,'trains') + +exp_paths = {'H:\Tlx3project\T9\T9_driftgrating_trains_160125_123706',... + 'H:\Tlx3project\T14\T14_driftgratingtrains_160329_211516',... + 'H:\Tlx3project\T15\3-31-16\T15_driftgratingtrains_160324_214136',... + 'H:\Tlx3project\T19\5-2-16\T19_trains_160502_222135',... + 'H:\Tlx3project\T18\5-3-16\T18_trains_160503_192729',... + 'H:\Tlx3project\T22\7-26-16\T22_trains_160726_183114'}; + +elseif strcmp(exp_type,'inhibit') + exp_paths = {'H:\Tlx3project\TiC1\TiC1_step_160901_141812',... + 'H:\Tlx3project\TiC2\8-31-16\TiC2_step_160831_121353'}; + +end + +count = 1; +for i = 1:length(exp_paths) + exp_path = exp_paths{i}; + % get experiment name + out = regexp(exp_path,'\\','split'); + inds = regexp(out{end},'_\d','start'); % looks for what's before an underscore followed immediately by a number; uses that as exp_name + exp_name = out{end}(1:inds(1)-1); + exp_dir = strcat(main_dir,'\',exp_name); + fprintf(sprintf('Processing experiment %s\n',exp_name)) +% if i == 1 +% intan_analysis_master(exp_path,exp_type); +% end + + % load results + cd(exp_dir) + s = dir; + for ii=1:length(s) + if strfind(s(ii).name,'_results') + results_file = s(ii).name; + end + end + S{i} = importdata(results_file,'-mat'); % load results mat + load(sprintf('%s\\light_params.mat',exp_path)) + lightconds = unique(all_light); +end + +count = 0; +for s = 1:length(S) + for n = 1:S{s}.numunits + if length(S{s}.lightconds)>4 % TEMP - HACK - skip 10hz condition + which_ones = [1 3 4]; + else + which_ones = [1:length(S{s}.lightconds)-1]; + end + % which light condition to use for comparisons +% if strcmp(exp_type,'trains') +% which_lightcond = length(S{s}.lightconds); % use highest frequency % change to make best for particular unit!! +% else +% which_lightcond(count) = 2; % use first light condition (e.g. lowest intensity) +% end + +% if S{s}.FRs(n).ev(1) > .25 % pretty liberal cut-off for which cells to include + count = count+1; + name{count} = S{s}.unitinfo(n).name; + layer(count) = S{s}.unitinfo(n).layer; + vissig(count) = S{s}.unitinfo(n).vissig; + vissig2(count) = S{s}.unitinfo(n).vissig2; + lightsig_vis(count,:) = S{s}.unitinfo(n).lightsig_vis(which_ones); + lightsig_blnk(count,:) = S{s}.unitinfo(n).lightsig_blnk(which_ones); + if length(S{s}.lightconds)>4 % TEMP - HACK + FRev(count,:) = S{s}.FRs(n).ev([1 which_ones+1]); % need to fix - currently contains both FRs and SEs + else + FRev(count,:) = S{s}.FRs(n).ev(1:length(S{s}.FRs(n).ev)/2); % need to fix - currently contains both FRs and SEs + end + + for ii = 2:length(FRev(count,:)) + evdiff(ii-1) = diff(FRev(count,[1 ii]),[],2); % get which light condition resulted in largest change in FR for each unit + end + [~,which_lightcond(count)] = max(abs(evdiff),[],2); + which_lightcond(count) = which_lightcond(count)+1; + + baseline(count) = S{s}.FRs(n).baseline; + if ~isempty(S{s}.FRs(n).SALT10ms) + SALT10ms(count,:) = S{s}.FRs(n).SALT10ms(which_ones); + SALT5ms(count,:) = S{s}.FRs(n).SALT5ms(which_ones); + SALT2ms(count,:) = S{s}.FRs(n).SALT2ms(which_ones); + end + OSI(count,:) = S{s}.tuning(n).OSI(([1 which_ones+1])); + OSI_CV(count,:) = S{s}.tuning(n).OSI_CV([1 which_ones+1]); + DSI(count,:) = S{s}.tuning(n).DSI([1 which_ones+1]); + DSI_CV(count,:) = S{s}.tuning(n).DSI_CV([1 which_ones+1]); + sig_Hot(count,:) = S{s}.tuning(n).sig_Hot([1 which_ones+1]); + sig_Hot2(count,:) = S{s}.tuning(n).sig_Hot2([1 which_ones+1]); + tuning_curve_collapse = zeros(length(S{s}.lightconds),size(S{s}.tuning(n).curve,2)/2); % reset + for o = 1:size(S{s}.tuning(n).curve,2)/2 + tuning_curve_collapse(:,o) = mean([S{s}.tuning(n).curve(:,o) S{s}.tuning(n).curve(:,o+size(S{s}.tuning(n).curve,2)/2)],2); % average evoked FR of same orientations but different directions in NO LIGHT condition + end + [~,pref_deg] = max(tuning_curve_collapse(1,:)); + if length(pref_deg) > 1 + [~,prefpref] = max(tuning_curve_collapse(2,pref_deg)); + pref_deg = pref_deg(prefpref); + end + prefFR_delta(count) = abs(diff(tuning_curve_collapse([1 which_lightcond(count)],pref_deg))); % when more than two light conditions, using only first light condition vs no light + if pref_deg <= size(S{s}.tuning(n).curve,2)/4 + orth_deg = pref_deg+size(S{s}.tuning(n).curve,2)/4; + else + orth_deg = pref_deg-size(S{s}.tuning(n).curve,2)/4; + end + % check if cells should be excluded from tuning analysis (no FR + % at any orientation <-.5 or >-.5) + if abs(tuning_curve_collapse(1,pref_deg))<.5 || abs(tuning_curve_collapse(2,pref_deg)) < .5 + include(count) = 0; + else + include(count) = 1; + end + + orthFR_delta(count) = abs(diff(tuning_curve_collapse([1 which_lightcond(count)],orth_deg))); + % sig_Hot_polar(count,:) = S{s}.tuning(n).sig_Hot_polar([1 which_ones+1]); + t2p_t(count) = S{s}.waveforms(n).t2p_t; + t2p_r(count) = S{s}.waveforms(n).t2p_r; + fwhm(count) = S{s}.waveforms(n).fwhm; + + lightmod(count) = diff(FRev(count,[1 which_lightcond(count)]))./sum(FRev(count,[1 which_lightcond(count)])); +% end + end +end + + +% get different cell types +visual_cells = find((vissig < .05)|(vissig2 < .05)); +light_cells= find(min(lightsig_vis,[],2)<.05); % find cells with significant effect in any light condition +tuned_cells = find(sig_Hot(:,1) < .05); +tuned_cells2 = find(sig_Hot2(:,1) < .05); +% tuned_cells(find(FRev(tuned_cells,1)<.5)) = []; % exclude cells with <.5 baseline FR from being considered "tuned" +tuned_cells = tuned_cells(ismember(tuned_cells,find(include))); +if strcmp(exp_type,'trains') + onset_cells = find(mean(SALT10ms,2)<.05); + quikonset_cells = find(mean(SALT5ms,2)<.05); + tlx_cells = find(mean(SALT2ms,2)<.05); +elseif strcmp(exp_type,'intensities') + onset_cells = find(min(SALT10ms,[],2)<.05); + quikonset_cells = find(min(SALT5ms,[],2)<.05); + tlx_cells = find(min(SALT2ms,[],2)<.05); +end +FS_cells = find(t2p_t < .65); +reg_cells = find(t2p_t >= .65); + +chs_23 = find(layer == 2.5); +chs_4 = find(layer == 4); +chs_5 = find(layer == 5); +chs_55 = find(layer == 5.5); +chs_6 = find(layer == 6); +infgran = [chs_5 chs_55 chs_6]; + +% get means and medians for overall (1st row), supra (2nd) gran (3rd) and infragran (4th) layers for +%reg-spiking (first column) and fast-spiking (second column) +median_sum = [nanmedian(OSI_CV(reg_cells,1)) nanmedian(OSI_CV(FS_cells,1)); + nanmedian(OSI_CV(intersect(chs_23,reg_cells),1)) nanmedian(OSI_CV(intersect(chs_23,FS_cells),1)); + nanmedian(OSI_CV(intersect(chs_4,reg_cells),1)) nanmedian(OSI_CV(intersect(chs_4,FS_cells),1)); + nanmedian(OSI_CV(intersect(infgran,reg_cells),1)) nanmedian(OSI_CV(intersect(infgran,FS_cells),1))]; +mean_sum = [nanmean(OSI_CV(reg_cells,1)) nanmean(OSI_CV(FS_cells,1)); + nanmean(OSI_CV(intersect(chs_23,reg_cells),1)) nanmean(OSI_CV(intersect(chs_23,FS_cells),1)); + nanmean(OSI_CV(intersect(chs_4,reg_cells),1)) nanmean(OSI_CV(intersect(chs_4,FS_cells),1)); + nanmean(OSI_CV(intersect(infgran,reg_cells),1)) nanmean(OSI_CV(intersect(infgran,FS_cells),1))]; +groupn = [length(~isnan(OSI_CV(reg_cells,1))) length(~isnan(OSI_CV(FS_cells,1))); + length(isnan(OSI_CV(intersect(chs_23,reg_cells),1))) length(~isnan(OSI_CV(intersect(chs_23,FS_cells),1))); + length(isnan(OSI_CV(intersect(chs_4,reg_cells),1))) length(~isnan(OSI_CV(intersect(chs_4,FS_cells),1))); + length(isnan(OSI_CV(intersect(infgran,reg_cells),1))) length(~isnan(OSI_CV(intersect(infgran,FS_cells),1)))]; + +cd(fig_dir) +barplot_by_layer(lightmod,layer,ones(1,length(layer)),'Light modulation index','Lightmodulation (evoked)') +barplot_by_layer(OSI_CV',layer,ones(1,length(layer)),'Orientation selectivity index (CV)','OSI (CV)') +barplot_by_layer(DSI_CV',layer,ones(1,length(layer)),'Direction selectivity index (CV)','DSI (CV)') +barplot_by_layer(OSI',layer,ones(1,length(layer)),'Orientation selectivity index','OSI') +barplot_by_layer(DSI',layer,ones(1,length(layer)),'Direction selectivity index','DSI') +barplot_by_layer(diff(OSI_CV(tuned_cells,:),[],2)',layer(tuned_cells),ones(1,length(layer(tuned_cells))),'OSI CV change (light-no light)','OSI change') +barplot_by_layer(diff(DSI_CV(tuned_cells,:),[],2)',layer(tuned_cells),ones(1,length(layer(tuned_cells))),'DSI CV change (light-no light)','DSI change') +if ~strcmp(exp_type,'ramp') + barplot_by_layer(lightmod(onset_cells),layer(onset_cells),ones(1,length(onset_cells)),'Light modulation index','Lightmodulation (onset cells)') +end + +% FS cells +FSFR_fig = figure('name','FS firing rate: No Light vs. Light'); +plot(FRev(intersect(chs_23,FS_cells),1),FRev(intersect(chs_23,FS_cells),mode(which_lightcond)),'r.','MarkerSize',24) +hold on +plot(FRev(intersect(chs_4,FS_cells),1),FRev(intersect(chs_4,FS_cells),mode(which_lightcond)),'b.','MarkerSize',24) +plot(FRev(intersect(chs_5,FS_cells),1),FRev(intersect(chs_5,FS_cells),mode(which_lightcond)),'g.','MarkerSize',24) +plot(FRev(intersect(chs_55,FS_cells),1),FRev(intersect(chs_55,FS_cells),mode(which_lightcond)),'k.','MarkerSize',24) +plot(FRev(intersect(chs_6,FS_cells),1),FRev(intersect(chs_6,FS_cells),mode(which_lightcond)),'c.','MarkerSize',24) +xlabel('Firing rate (spks/s) - No Light','Fontsize',24) +ylabel('Firing rate (spks/s) - Light','Fontsize',24) +xax = get(gca,'XLim'); +yax = get(gca,'YLim'); +x = [min(xax(1),yax(1)):1:max(xax(2),yax(2))]; +y=x; +plot(x,y,'k'); +xlim([min(xax(1),yax(1)), max(xax(2),yax(2))]) +ylim([min(xax(1),yax(1)), max(xax(2),yax(2))]) +% xlim([0 25]) +% ylim([0 25]) +set(gca,'fontsize',18) +l=legend('L2/3','L4','L5A','L5B','L6','Location','SouthEast'); +set(l,'fontsize',18) +print(FSFR_fig, '-dpng','FiringRate_FS') + +% RS cells +RSFR_fig = figure('name','RS firing rate: No Light vs. Light'); +plot(FRev(intersect(chs_23,reg_cells),1),FRev(intersect(chs_23,reg_cells),mode(which_lightcond)),'r.','MarkerSize',24) +hold on +plot(FRev(intersect(chs_4,reg_cells),1),FRev(intersect(chs_4,reg_cells),mode(which_lightcond)),'b.','MarkerSize',24) +plot(FRev(intersect(chs_5,reg_cells),1),FRev(intersect(chs_5,reg_cells),mode(which_lightcond)),'g.','MarkerSize',24) +plot(FRev(intersect(chs_55,reg_cells),1),FRev(intersect(chs_55,reg_cells),mode(which_lightcond)),'k.','MarkerSize',24) +plot(FRev(intersect(chs_6,reg_cells),1),FRev(intersect(chs_6,reg_cells),mode(which_lightcond)),'c.','MarkerSize',24) +xlabel('Firing rate (spks/s) - No Light','Fontsize',24) +ylabel('Firing rate (spks/s) - Light','Fontsize',24) +xax = get(gca,'XLim'); +yax = get(gca,'YLim'); +x = [min(xax(1),yax(1)):1:max(xax(2),yax(2))]; +y=x; +plot(x,y,'k'); +xlim([min(xax(1),yax(1)), max(xax(2),yax(2))]) +ylim([min(xax(1),yax(1)), max(xax(2),yax(2))]) +% xlim([0 25]) +% ylim([0 25]) +set(gca,'fontsize',18) +l=legend('L2/3','L4','L5A','L5B','L6','Location','SouthEast'); +set(l,'fontsize',18) +print(RSFR_fig, '-dpng','FiringRate_RS') + +osi_fig = figure('name','OSI Change (light-nolight) vs. Light modulation'); +plot(diff(OSI_CV(intersect(tuned_cells,chs_23),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_23)),'r.','MarkerSize',24) +hold on +plot(diff(OSI_CV(intersect(tuned_cells,chs_4),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_4)),'b.','MarkerSize',24) +plot(diff(OSI_CV(intersect(tuned_cells,chs_5),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_5)),'g.','MarkerSize',24) +plot(diff(OSI_CV(intersect(tuned_cells,chs_55),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_55)),'k.','MarkerSize',24) +plot(diff(OSI_CV(intersect(tuned_cells,chs_6),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_6)),'c.','MarkerSize',24) +xlabel('change in OSI CV (light - no light)','Fontsize',24) +ylabel('Light modulation index','Fontsize',24) +line([0 0],[-1 1],'Color','k') +line([-1 1],[0 0],'Color','k') +set(gca,'fontsize',18) +l=legend('L2/3','L4','L5A','L5B','L6','Location','SouthEast'); +set(l,'fontsize',18) +print(osi_fig, '-dpng','OSIvslight') +% print2eps('OSIvslight', osi_fig) + +osi_cellfig = figure('name','OSI Change (light-nolight) vs. Light modulation'); +plot(diff(OSI_CV(intersect(reg_cells,tuned_cells),[1 mode(which_lightcond)]),[],2),lightmod(intersect(reg_cells,tuned_cells)),'r.','MarkerSize',24) +hold on +plot(diff(OSI_CV(intersect(FS_cells,tuned_cells),[1 mode(which_lightcond)]),[],2),lightmod(intersect(FS_cells,tuned_cells)),'b.','MarkerSize',24) +xlabel('change in OSI CV (light - no light)','Fontsize',24) +ylabel('Light modulation index','Fontsize',24) +line([0 0],[-1 1],'Color','k') +line([-1 1],[0 0],'Color','k') +set(gca,'fontsize',18) +l=legend('Regular spiking','Fast spiking'); +set(l,'fontsize',18) +print(osi_cellfig, '-dpng','OSIvslight_bycelltype') + +dsi_cellfig = figure('name','DSI Change (light-nolight) vs. Light modulation'); +plot(diff(DSI_CV(intersect(reg_cells,tuned_cells),[1 mode(which_lightcond)]),[],2),lightmod(intersect(reg_cells,tuned_cells)),'r.','MarkerSize',24) +hold on +plot(diff(DSI_CV(intersect(FS_cells,tuned_cells),[1 mode(which_lightcond)]),[],2),lightmod(intersect(FS_cells,tuned_cells)),'b.','MarkerSize',24) +xlabel('change in DSI CV (light - no light)','Fontsize',24) +ylabel('Light modulation index','Fontsize',24) +line([0 0],[-1 1],'Color','k') +line([-1 1],[0 0],'Color','k') +set(gca,'fontsize',18) +l=legend('Regular spiking','Fast spiking'); +set(l,'fontsize',18) +print(dsi_cellfig, '-dpng','DSIvslight_bycelltype') + +dsi_fig = figure('name','OSI Change (light-nolight) vs. Light modulation'); +plot(diff(DSI_CV(intersect(tuned_cells,chs_23),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_23)),'r.','MarkerSize',24) +hold on +plot(diff(DSI_CV(intersect(tuned_cells,chs_4),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_4)),'b.','MarkerSize',24) +plot(diff(DSI_CV(intersect(tuned_cells,chs_5),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_5)),'g.','MarkerSize',24) +plot(diff(DSI_CV(intersect(tuned_cells,chs_55),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_55)),'k.','MarkerSize',24) +plot(diff(DSI_CV(intersect(tuned_cells,chs_6),[1 mode(which_lightcond)]),[],2),lightmod(intersect(tuned_cells,chs_6)),'c.','MarkerSize',24) +xlabel('change in DSI CV (light - no light)','Fontsize',24) +ylabel('Light modulation index','Fontsize',24) +line([0 0],[-1 1],'Color','k') +line([-1 1],[0 0],'Color','k') +set(gca,'fontsize',18) +l=legend('L2/3','L4','L5A','L5B','L6','Location','SouthEast'); +set(l,'fontsize',18) +print(dsi_fig, '-dpng','DSIvslight') +% print2eps('OSIvslight', dsi_fig) + +plot_OSI(layer,OSI_CV,'OSI (CV)') +plot_OSI(layer,DSI_CV,'DSI (CV)') + +% additive vs multiplicative changes +change_by_celltype = figure('name','Change in orthogonal vs preferred FR'); +plot(orthFR_delta(reg_cells),prefFR_delta(reg_cells),'r.','MarkerSize',24) +hold on +plot(orthFR_delta(FS_cells),prefFR_delta(FS_cells),'b.','MarkerSize',24) +xax = get(gca,'XLim'); +yax = get(gca,'YLim'); +x = [min(xax(1),yax(1)):1:max(xax(2),yax(2))]; +y=x; +plot(x,y,'k'); +coeffs(1,:) = polyfit(orthFR_delta(reg_cells), prefFR_delta(reg_cells), 1); +coeffs(2,:) = polyfit(orthFR_delta(FS_cells), prefFR_delta(FS_cells), 1); +% Get fitted values +fittedX = linspace(min(orthFR_delta), max(orthFR_delta), 200); +for i = 1:size(coeffs,1) + fittedY(i,:) = polyval(coeffs(i,:), fittedX); +end +plot(fittedX,fittedY(1,:),'r') +plot(fittedX,fittedY(2,:),'b') +xlabel('Change in orthogonal FR','fontsize',24) +ylabel('Change in preferred FR','fontsize',24) +set(gca,'fontsize',18) +l=legend('Regular spiking','Fast spiking'); +set(l,'fontsize',18) +print(change_by_celltype, '-dpng','FRchange_bycelltype') + +% diff layers +change_by_layer = figure('name','Change in orthogonal vs preferred FR'); +plot(orthFR_delta(chs_23),prefFR_delta(chs_23),'r.','MarkerSize',24) +hold on +plot(orthFR_delta(chs_4),prefFR_delta(chs_4),'b.','MarkerSize',24) +plot(orthFR_delta(chs_5),prefFR_delta(chs_5),'g.','MarkerSize',24) +plot(orthFR_delta(chs_55),prefFR_delta(chs_55),'k.','MarkerSize',24) +plot(orthFR_delta(chs_6),prefFR_delta(chs_6),'c.','MarkerSize',24) +xax = get(gca,'XLim'); +yax = get(gca,'YLim'); +x = [min(xax(1),yax(1)):1:max(xax(2),yax(2))]; +y=x; +plot(x,y,'k--'); +coeffs(1,:) = polyfit(orthFR_delta(chs_23), prefFR_delta(chs_23), 1); +coeffs(2,:) = polyfit(orthFR_delta(chs_4), prefFR_delta(chs_4), 1); +coeffs(3,:) = polyfit(orthFR_delta(chs_5), prefFR_delta(chs_5), 1); +coeffs(4,:) = polyfit(orthFR_delta(chs_55), prefFR_delta(chs_55), 1); +coeffs(5,:) = polyfit(orthFR_delta(chs_6), prefFR_delta(chs_6), 1); +% Get fitted values +fittedX = linspace(min(orthFR_delta), max(orthFR_delta), 200); +for i = 1:size(coeffs,1) + fittedY(i,:) = polyval(coeffs(i,:), fittedX); +end +plot(fittedX,fittedY(1,:),'r') +plot(fittedX,fittedY(2,:),'b') +plot(fittedX,fittedY(3,:),'g') +plot(fittedX,fittedY(4,:),'k') +plot(fittedX,fittedY(5,:),'c') +xlabel('Change in orthogonal FR','fontsize',24) +ylabel('Change in preferred FR','fontsize',24) +set(gca,'fontsize',18) +l=legend('L2/3','L4','L5A','L5B','L6','Location','SouthEast'); +set(l,'fontsize',18) +print(change_by_layer, '-dpng','FRchange_bylayer') + +end diff --git a/Intancode_Megan/calc_FFI.m b/Intancode_Megan/calc_FFI.m new file mode 100644 index 0000000..4d0f048 --- /dev/null +++ b/Intancode_Megan/calc_FFI.m @@ -0,0 +1,39 @@ +function win_FR = calc_FFI(exp_paths) + +% exp_paths = {'H:\Tlx3project\T9\T9_driftgrating_trains_160125_123706',... +% 'H:\Tlx3project\T14\T14_driftgratingtrains_160329_211516',... +% 'H:\Tlx3project\T15\3-31-16\T15_driftgratingtrains_160324_214136',... +% 'H:\Tlx3project\T19\5-2-16\T19_trains_160502_222135',... +% 'H:\Tlx3project\T18\5-3-16\T18_trains_160503_192729'}; + +% make rasters for multiple experiments +for i = 1:length(exp_paths) + exp_path = exp_paths{i}; + load(sprintf('%s\\su_spikedata.mat',exp_path)) + for n=1:length(spiketimes) % for each unit in that experiment + spikes = spiketimes{n}; + spike_raster{i}(n,:,:) = make_raster(spikes,1000,2.5); + end +end + +% for each experiment, calculate FRs in first and last pulse of long train +count = 1; +for i = 1:length(exp_paths) + load(sprintf('%s\\light_params.mat',exp_paths{i})) + light_conds = unique(all_light); + light_trials = find(all_light ==light_conds(2)); % TEMP + time = 0:1/1000:2.5; + lightstart = find(time==round(av_light_start)); % SAMPLE at which light started + win = 20; % number of samples to use for FR windows + pre_win = [lightstart-(win):lightstart-1]; + onset_win = [lightstart:lightstart+win-1]; + post_win = [lightstart+win:lightstart+2*win-1]; + for n =1:size(spike_raster{i},1) + win_FR(count,1) = sum(sum(spike_raster{i}(n,light_trials,pre_win)))/(length(light_trials)*(win/1000)); + win_FR(count,2) = sum(sum(spike_raster{i}(n,light_trials,onset_win)))/(length(light_trials)*(win/1000)); + win_FR(count,3) = sum(sum(spike_raster{i}(n,light_trials,post_win)))/(length(light_trials)*(win/1000)); + count = count+1; + end +end + +end \ No newline at end of file diff --git a/Intancode_Megan/calc_crosscorrs.m b/Intancode_Megan/calc_crosscorrs.m new file mode 100644 index 0000000..2a11ac2 --- /dev/null +++ b/Intancode_Megan/calc_crosscorrs.m @@ -0,0 +1,62 @@ +function calc_crosscorrs + +exp_paths = {'H:\Tlx3project\T18\5-3-16\T18_diffintensities_160503_171447',... +'H:\Tlx3project\T18\5-5-16\T18_run2_diffintensities_160505_092232',... +'H:\Tlx3project\T19\5-2-16\T19_diffintensities_160502_210213',... +'H:\Tlx3project\T19\5-3-16\T19_run2_diffintensities_160503_221201'}; + +% make rasters for multiple experiments +for i = 1:length(exp_paths) + exp_path = exp_paths{i}; + load(sprintf('%s\\su_spikedata.mat',exp_path)) + + % get experiment name + animal_name = regexp(exp_paths{i},'T\d+','match'); + animal_name = animal_name{1}; + run_name = regexp(exp_paths{i},'run\d','match'); + if isempty(run_name) + exp_name = animal_name; + else + exp_name = strcat(animal_name,run_name{1}); + end + + results = importdata(sprintf('%s\\%s_results.mat',exp_paths{i},exp_name)); + for n=1:length(spiketimes) % for each unit in that experiment + spikes = spiketimes{n}; + spike_raster{i}(n,:,:) = make_raster(spikes,1000,2.5); + unit{i}(n) = results(n).clustnum; + layer{i}(n) = results(n).layer; + end +end + +cd 'H:\Tlx3project\CumulativeData\T18&T19\CrossCorrs' + +% for each experiment, calculate FRs in first and last pulse of long train +count = 1; +for i = 1:length(exp_paths) + load(sprintf('%s\\light_params.mat',exp_paths{i})) + light_conds = unique(all_light); + light_trials = find(all_light ==light_conds(end)); % TEMP + nolight_trials = find(all_light==light_conds(1)); + time = 0:1/1000:2.5; + lightstart = find(time==round(av_light_start)); % SAMPLE at which light started + [layer_out,inds] = sort(layer{i}); + light_raster(:,:) = mean(spike_raster{i}(:,light_trials,lightstart:lightstart+999),2); + new_lightrast = light_raster(inds,:); + [C,lags] = xcorr(new_lightrast','coeff'); + nolight_raster(:,:) = mean(spike_raster{i}(:,nolight_trials,lightstart:lightstart+999),2); + new_nolightrast = nolight_raster(inds,:); + [D,lags] = xcorr(new_nolightrast','coeff'); + test = reshape(C(1000,:),size(spike_raster{i},1),size(spike_raster{i},1)); + test2 = reshape(D(1000,:),size(spike_raster{i},1),size(spike_raster{i},1)); + fig1=figure;imagesc(test);colorbar + fig2=figure;imagesc(test2);colorbar + fig3=figure;imagesc(test-test2);colorbar + print(fig1,'-dpng',sprintf('Exp%d_Lighton',i)) + print(fig2,'-dpng',sprintf('Exp%d_Lightoff',i)) + print(fig3,'-dpng',sprintf('Exp%d_Lighton-Lightoff',i)) + close all + clear light_raster nolight_raster +end + +end \ No newline at end of file diff --git a/Intancode_Megan/get_exp_params.asv b/Intancode_Megan/get_exp_params.asv new file mode 100644 index 0000000..eab386b --- /dev/null +++ b/Intancode_Megan/get_exp_params.asv @@ -0,0 +1,102 @@ +function [prestim,poststim,stimtime,trial_type,IVs] = get_exp_params(exp_path,exp_type) + +% from analyzer file, determine the different independent variables (IVs) +% in the experiment and create a matrix 'trial_type' of num_trials x +% num_IVs in which values reflect the level of each variable +% also output the prestim, poststim, and stim times +% Inputs: +% exp_path - e.g. 'H:\Tlx3project\T19\5-2-16\T19_diffintensities_160502_210213' +% exp_type - 'ramp', 'trains', 'intensities' or 'size' +% created 8/11/16 by MAK + +cd(exp_path) + +% load analyzer +s = dir; +for i=1:length(s) + if strfind(s(i).name,'.analyzer') + analyze_file = s(i).name; + end +end +load(sprintf('%s/%s',exp_path,analyze_file),'-mat') % load analyzer file with stimulus info +prestim = Analyzer.P.param{1}{3}; % in seconds +poststim = Analyzer.P.param{2}{3}; +if poststim == 0 + extra = .25*1000; % add extra samples for pseudo-poststim period +else + extra = 0; +end +stimtime = Analyzer.P.param{3}{3}; +totaltime = prestim+poststim+stimtime; +onset = .2; % onset time (in seconds) - this will be subtracted from the beginning of the stim period to determine evoked firing rate +num_trials = Analyzer.M.NumTrials; % here, num_trials is defined from the analyzer file rather than from the actual experiment + +% convert to ms +prestim_samps = prestim*1000; +poststim_samps = poststim*1000; +stimtime_samps = stimtime*1000; + +% extract trial types +% num_trials = size(trials,1); +IVs = Analyzer.loops.conds{1}.symbol; % independent variables +trial_type = zeros(num_trials,length(IVs)); % matrix of trials by IVs +for v = 1:length(IVs) % for each variable + conds{v} = cellfun(@(x) x.val{v}, Analyzer.loops.conds, 'UniformOutput',false); % all possible conditions + levs{v} = unique(cell2mat(conds{v})); + num_levs(v) = length(levs{v}); % number of levels of IV + if sum(cellfun('isempty',conds{v})); % if '[]' was a condition (e.g. for blank trials) + num_levs(v) = num_levs(v)+1; + levs{v} = [levs{v} 999]; % blank trials indicated by 999 instead of empty cell (tried with NaN but was too annoying) + end + for i = 1:num_levs(v) + if levs{v}(i)==999 + which_conds = find(cellfun('isempty',conds{v})); % indices of which conds were blank conds + else + which_conds = find([conds{v}{:}] == levs{v}(i)); % indices of which non-blank conds have the same level of variable v + end + cond_trials = []; + for ii = 1:length(which_conds) + cond_trials = [cond_trials cellfun(@(x) x.trialno, Analyzer.loops.conds{which_conds(ii)}.repeats)]; % store trials from different conditions in separate columns + end + cond_trials = sort(cond_trials); + trial_type(cond_trials,v) = levs{v}(i); % use when using ALL trials + end +end + +% import data from intan2matlab.m and make sure trial_type reflects the +% number of trials that actually happened (may be less than num_trials +% because analyzer file is created before the experiment actually starts) +load(sprintf('%s/data.mat',exp_path)) +real_num_trials = size(field_trials,1); +trial_type = trial_type(1:real_num_trials,:); + +% check analyzer-determined light trials against the LED input to Intan +if exist('LED','var') % if it was an optogenetics experiment + lightvar = find(strcmp(IVs,'light_bit')); + [all_light,~,~,~] = get_lightstim_v2(exp_path,exp_type); + trial_type(:,lightvar) = all_light'; +end + +% add column to indicate whether trials were visual (1) or blank (0) +orivar = find(strcmp(IVs,'ori')); +blank_trials = trial_type(:,orivar)<=360; +trial_type = [blank_trials trial_type]; % add column to FRONT of matrix +IVs = {'visual' IVs{:}}; % keep track of variable names + +% determine run vs. stationary trials +if exist('encdA','var') + move_trials = Intan_digital_movement(field_trials,encdA,encdB,0)'; +elseif exist('mouse','var') % using optical mouse for old recordings - might want to change to encoder? + move_trials = zeros(1,size(field_trials,1)); + moveVec = move_trials; + for i = 1:size(field_trials,1) + moveVec(i) = sum(mouse(field_trials(i,1)*20:field_trials(i,2)*20)); % *20 because mouse is still in original amp_sr + end + move_trials(find(moveVec)) = 1; +else + move_trials = zeros(1,size(field_trials,1)); +end +trial_type = [trial_type move_trials']; % add column to trial_type indicating stationary (0) or run (1) trials +IVs{length(IVs)+1} = 'running'; + +end \ No newline at end of file diff --git a/Intancode_Megan/get_exp_params.m b/Intancode_Megan/get_exp_params.m new file mode 100644 index 0000000..eab386b --- /dev/null +++ b/Intancode_Megan/get_exp_params.m @@ -0,0 +1,102 @@ +function [prestim,poststim,stimtime,trial_type,IVs] = get_exp_params(exp_path,exp_type) + +% from analyzer file, determine the different independent variables (IVs) +% in the experiment and create a matrix 'trial_type' of num_trials x +% num_IVs in which values reflect the level of each variable +% also output the prestim, poststim, and stim times +% Inputs: +% exp_path - e.g. 'H:\Tlx3project\T19\5-2-16\T19_diffintensities_160502_210213' +% exp_type - 'ramp', 'trains', 'intensities' or 'size' +% created 8/11/16 by MAK + +cd(exp_path) + +% load analyzer +s = dir; +for i=1:length(s) + if strfind(s(i).name,'.analyzer') + analyze_file = s(i).name; + end +end +load(sprintf('%s/%s',exp_path,analyze_file),'-mat') % load analyzer file with stimulus info +prestim = Analyzer.P.param{1}{3}; % in seconds +poststim = Analyzer.P.param{2}{3}; +if poststim == 0 + extra = .25*1000; % add extra samples for pseudo-poststim period +else + extra = 0; +end +stimtime = Analyzer.P.param{3}{3}; +totaltime = prestim+poststim+stimtime; +onset = .2; % onset time (in seconds) - this will be subtracted from the beginning of the stim period to determine evoked firing rate +num_trials = Analyzer.M.NumTrials; % here, num_trials is defined from the analyzer file rather than from the actual experiment + +% convert to ms +prestim_samps = prestim*1000; +poststim_samps = poststim*1000; +stimtime_samps = stimtime*1000; + +% extract trial types +% num_trials = size(trials,1); +IVs = Analyzer.loops.conds{1}.symbol; % independent variables +trial_type = zeros(num_trials,length(IVs)); % matrix of trials by IVs +for v = 1:length(IVs) % for each variable + conds{v} = cellfun(@(x) x.val{v}, Analyzer.loops.conds, 'UniformOutput',false); % all possible conditions + levs{v} = unique(cell2mat(conds{v})); + num_levs(v) = length(levs{v}); % number of levels of IV + if sum(cellfun('isempty',conds{v})); % if '[]' was a condition (e.g. for blank trials) + num_levs(v) = num_levs(v)+1; + levs{v} = [levs{v} 999]; % blank trials indicated by 999 instead of empty cell (tried with NaN but was too annoying) + end + for i = 1:num_levs(v) + if levs{v}(i)==999 + which_conds = find(cellfun('isempty',conds{v})); % indices of which conds were blank conds + else + which_conds = find([conds{v}{:}] == levs{v}(i)); % indices of which non-blank conds have the same level of variable v + end + cond_trials = []; + for ii = 1:length(which_conds) + cond_trials = [cond_trials cellfun(@(x) x.trialno, Analyzer.loops.conds{which_conds(ii)}.repeats)]; % store trials from different conditions in separate columns + end + cond_trials = sort(cond_trials); + trial_type(cond_trials,v) = levs{v}(i); % use when using ALL trials + end +end + +% import data from intan2matlab.m and make sure trial_type reflects the +% number of trials that actually happened (may be less than num_trials +% because analyzer file is created before the experiment actually starts) +load(sprintf('%s/data.mat',exp_path)) +real_num_trials = size(field_trials,1); +trial_type = trial_type(1:real_num_trials,:); + +% check analyzer-determined light trials against the LED input to Intan +if exist('LED','var') % if it was an optogenetics experiment + lightvar = find(strcmp(IVs,'light_bit')); + [all_light,~,~,~] = get_lightstim_v2(exp_path,exp_type); + trial_type(:,lightvar) = all_light'; +end + +% add column to indicate whether trials were visual (1) or blank (0) +orivar = find(strcmp(IVs,'ori')); +blank_trials = trial_type(:,orivar)<=360; +trial_type = [blank_trials trial_type]; % add column to FRONT of matrix +IVs = {'visual' IVs{:}}; % keep track of variable names + +% determine run vs. stationary trials +if exist('encdA','var') + move_trials = Intan_digital_movement(field_trials,encdA,encdB,0)'; +elseif exist('mouse','var') % using optical mouse for old recordings - might want to change to encoder? + move_trials = zeros(1,size(field_trials,1)); + moveVec = move_trials; + for i = 1:size(field_trials,1) + moveVec(i) = sum(mouse(field_trials(i,1)*20:field_trials(i,2)*20)); % *20 because mouse is still in original amp_sr + end + move_trials(find(moveVec)) = 1; +else + move_trials = zeros(1,size(field_trials,1)); +end +trial_type = [trial_type move_trials']; % add column to trial_type indicating stationary (0) or run (1) trials +IVs{length(IVs)+1} = 'running'; + +end \ No newline at end of file diff --git a/Intancode_Megan/get_lightstim_v2.asv b/Intancode_Megan/get_lightstim_v2.asv new file mode 100644 index 0000000..2f1148d --- /dev/null +++ b/Intancode_Megan/get_lightstim_v2.asv @@ -0,0 +1,207 @@ +function [all_light, pulse_dur, light_dur, av_light_start] = get_lightstim_v2(exp_path,exp_type) + +% get_lightstim_v2.m - use LED input (analog or digital) to determine the parameters of the +% optogenetic stimulation +% updated by MAK 7/14/16 +% Inputs: +% exp_path - e.g. 'H:\Tlx3project\T19\5-2-16\T19_diffintensities_160502_210213' +% exp_type - 'ramp', 'trains', 'intensities' or 'size' +% Outputs: +% all_light - 1xnum_trials vector of values 1:num_conds (0 = no light, 1+ = +% light conditions) +% pulse_dur - duration of light pulse in sec (single pulse, not total +% duration of light!) +% light_dur = total duration of light (from beginning of first pulse to end +% of last pulse) +% av_light_start - average time from visual stimulus onset that light +% turned on + +cd(exp_path) +if exist(sprintf('%s/data.mat',exp_path),'file') + load(sprintf('%s/data.mat',exp_path)) % data from intanphy2matlab.m +else + [~,field_trials,time_index,amp_sr,... + epoc,~,~,LED,~,~] = intanphy2matlab_v2(exp_path); % data from intanphy2matlab.m +end + +% field_trials - trial num x 2 matrix of trial start and end samples (in + % 1000 Hz sampling rate) - starts from 1! +% time_index - vector of time stamps of each sample (in seconds), with 1000 + % samples per second - starts from 0! +% amp_sr - original amplifier sampling rate +% encd - vector of analog output from movement encoder. Still in original + % sampling rate (amp_sr) +% LED - is 0 if not an optogenetics + % experiment, but otherwise, vectors of whether LED was on (1) or off (0) + + + +LN = length(epoc); +div = amp_sr/1000; +zx = 1:div:LN; +izx = floor(zx); +light = LED(izx); % put into 1000hz sampling rate + +%% first, find light trials +for t = 1:size(field_trials,1) % for each trial + samps_per_t = max(diff(field_trials,[],2)); % do this in case each trial doens't have exact same number of samples + light_out(t,:) = light(field_trials(t,1):field_trials(t,1)+samps_per_t); % get actual values of LED input to Intan +end + +[~,ex_trial] = min(mean(light_out,2)); % get example of a trial in which there was definitely no light +light_thresh = 5*std(light_out(ex_trial,:))+max(light_out(ex_trial,:)); % considered light trial if max value exceeds 5 standard deviations of ex_trial above the max value of ex_trial +light_trials = find(max(light_out,[],2)>light_thresh)'; % which trials the light turned on in +light_on = zeros(1,size(field_trials,1)); +light_on(light_trials) = 1; % matrix of all trials: 0 if no light, 1 if light + +% check against analyzer file +s = dir; +for i=1:length(s) + if strfind(s(i).name,'.analyzer') + analyze_file = s(i).name; + end +end +load(sprintf('%s/%s',exp_path,analyze_file),'-mat') % load analyzer file with stimulus info + +% get light conds +lightcond = find(strcmp(Analyzer.loops.conds{1}.symbol,'light_bit')); +conds = cellfun(@(x) x.val{lightcond}, Analyzer.loops.conds); +diff_conds = unique(conds); +num_conds = length(diff_conds); +% get trial types +trial_type = zeros(1,size(field_trials,1)); +for c = 1:length(conds) + ori_trials{:,c} = cellfun(@(x) x.trialno, Analyzer.loops.conds{c}.repeats); % store trials from different conditions in separate columns + trial_type(ori_trials{:,c}) = c; +end +trial_type = trial_type(1:length(light_on)); +light_trials_check = find(ismember(trial_type,find(conds))); +min_length = min(length(light_trials),length(light_trials_check)); % in case number of light trials are different between analyzer and LED input to Intan (suggests there's probably a problem...) +if sum(light_trials(1:min_length)~=light_trials_check(1:min_length)) % if numbers of light trials don't agree + err_count = 1; + fprintf('Analyzer file and LED inputs do not match\n') + off_trial = find(light_trials(1:min_length)~=light_trials_check(1:min_length),1,'first'); % check first conflicting trial + h = figure; plot(light_out(off_trial,:)); + check = input('Was this a light trial? Y or N: ','s'); + if strcmp(check,'N') + light_trials(off_trial) = []; + end + close(h) + if length(light_trials) > length(light_trials_check) % if more light trials were detected by light input to Intan than in analyzer file + offsetA = 1; + offsetB = 0; + elseif length(light_trials) < length(light_trials_check) % vice versa + offsetA = 0; + offsetB = 1; + else % correct number of trials, just disagreement about which ones were light trials + offsetA = 0; + offsetB = 0; + end + if sum(offsetA+offsetB) && sum(light_trials(off_trial+offsetA:end)~=light_trials_check(off_trial+offsetB:end)) % check the next conflicting trial +% fprintf('Analyzer file and LED inputs are not same length\n') + off_trial2 = find(light_trials(off_trial+1:end)~=light_trials_check(off_trial:end),1,'first'); + h = figure; plot(light(field_trials(off_trial+off_trial2,1):field_trials(off_trial+off_trial2,2))) + check = input('Was this a light trial? Y or N: ','s'); + if strcmp(check,'N') + light_trials(off_trial+off_trial2) = []; + end + close(h) + else + fprintf('LED input conflicts with analyzer file. Going with LED input\n') + end +else + err_count = 0; % no conlict between LED input and analyzer file +end + + + +%% determine light parameters given the type of light pulse + +if strcmp(exp_type,'ramp') + for t = 1:length(light_trials) + tt = light_trials(t); + light_end(t) = find(light_out(tt,:)>light_thresh,1,'last'); % find last sample when light was on + light_dur = 1; % assumes ramp lasts 1sec + light_start(t) = light_end(t)-light_dur*1000+1; % go backwards to find the start + end + light_hz = 1; + pulse_dur = round(mean(light_dur)); + all_light = zeros(1,size(field_trials,1)); % includes trials w/o light stim (as 0) + all_light(light_trials) = light_hz; + +elseif strcmp(exp_type,'trains') + for t = 1:length(light_trials) + tt = light_trials(t); + light_start(t) = find(light_out(tt,:)>light_thresh,1,'first'); + light_pulsedur(t) = find(light_out(tt,light_start(t):end)<=light_thresh,1,'first')-1; % finds duration of first light pulse in the trial + light_end(t) = find(light_out(tt,:)>light_thresh,1,'last'); + light_dur(t) = length(light_start(t):light_end(t))/1000; + light_sum(t) = sum(light_out(tt,:)>light_thresh); % sum of light pulses - used to figure out frequency + end + pulse_dur = round(mean(light_pulsedur)); % in sec + light_dur = round(max(light_dur)); % in case of trials with only single pulse, still consider light duration of trials with multiple pulses + light_hz = round(floor(light_sum./(pulse_dur))); % get the light frequencies for each trial (use floor in case ex. sum of 40Hz trial is 81 instead of 80) + pulse_dur = pulse_dur/1000; % change from ms to sec + all_light = zeros(1,size(field_trials,1)); % includes trials w/o light stim (as 0) + all_light(light_trials) = light_hz; + +else % simple step function + for t = 1:length(light_trials) + tt = light_trials(t); + light_start(t) = find(light_out(tt,:)>light_thresh,1,'first'); + light_end(t) = find(light_out(tt,:)>light_thresh,1,'last'); + light_dur(t) = length(light_start(t):light_end(t))/1000; +% light_inten(t) = roundn(mean(light_out(tt,light_start(t):light_end(t))),-1); % round intensity to nearest hundreth + light_inten(t) = roundn(mean(light_out(tt,light_start:light_end)),-1); % round intensity to nearest hundreth + end + intensities = unique(light_inten); + light_hz = 1; + pulse_dur = round(mean(light_dur)); + light_dur = pulse_dur; + all_light = zeros(1,size(field_trials,1)); % includes trials w/o light stim (as 0) + % TEMP b/c TiC2 +% all_light(light_trials) = light_hz; + diff_durs = unique(light_inten); + for i=1:length(diff_durs) + which_dur = ismember(light_inten,diff_durs(i)); % find trials that were at a particular light intensity + all_light(light_trials(which_dur)) = intensities(i); + + if length(intensities) > 1 % if this experiment involved light steps at different intensities - use LED input to determine intensities + small_diffs = find(diff(intensities) < .5); % to account for minor variability amongst intensities + if ~isempty(small_diffs) + % find((light_inten == intensities(small_diffs)) | (light_inten == intensities(small_diffs+1))) + orig_intensities = intensities; + intensities(small_diffs) = []; + count = 1; + for i = 1:length(intensities) + diff_intensities{i} = orig_intensities(count); + count = count+1; + if i == small_diffs + diff_intensities{i} = orig_intensities(small_diffs:small_diffs+1); + count = count+1; + end + end + else + for i = 1:length(intensities) + diff_intensities{i} = intensities(i); + end + end + + all_light = zeros(1,size(field_trials,1)); % includes trials w/o light stim (as 0) + for i = 1:length(intensities) + which_inten = ismember(light_inten,diff_intensities{i}); % find trials that were at a particular light intensity + all_light(light_trials(which_inten)) = intensities(i); + end + else % if single intensity experiment + all_light(light_trials) = 1; + end +end + +%% Get final parameters to save +av_light_start = time_index(round(mean(light_start))); % average time at which light started (1 less than sample # b/c starting with 0!) +% pulse_dur and all_light already made + +% save parameters +save('light_params.mat','all_light', 'pulse_dur', 'av_light_start'); + +return diff --git a/Intancode_Megan/get_lightstim_v2.m b/Intancode_Megan/get_lightstim_v2.m new file mode 100644 index 0000000..812b7d6 --- /dev/null +++ b/Intancode_Megan/get_lightstim_v2.m @@ -0,0 +1,209 @@ +function [all_light, pulse_dur, light_dur, av_light_start] = get_lightstim_v2(exp_path,exp_type) + +% get_lightstim_v2.m - use LED input (analog or digital) to determine the parameters of the +% optogenetic stimulation +% updated by MAK 7/14/16 +% Inputs: +% exp_path - e.g. 'H:\Tlx3project\T19\5-2-16\T19_diffintensities_160502_210213' +% exp_type - 'ramp', 'trains', 'intensities' or 'size' +% Outputs: +% all_light - 1xnum_trials vector of values 1:num_conds (0 = no light, 1+ = +% light conditions) +% pulse_dur - duration of light pulse in sec (single pulse, not total +% duration of light!) +% light_dur = total duration of light (from beginning of first pulse to end +% of last pulse) +% av_light_start - average time from visual stimulus onset that light +% turned on + +cd(exp_path) +if exist(sprintf('%s/data.mat',exp_path),'file') + load(sprintf('%s/data.mat',exp_path)) % data from intanphy2matlab.m +else + [~,field_trials,time_index,amp_sr,... + epoc,~,~,LED,~,~] = intanphy2matlab_v2(exp_path); % data from intanphy2matlab.m +end + +% field_trials - trial num x 2 matrix of trial start and end samples (in + % 1000 Hz sampling rate) - starts from 1! +% time_index - vector of time stamps of each sample (in seconds), with 1000 + % samples per second - starts from 0! +% amp_sr - original amplifier sampling rate +% encd - vector of analog output from movement encoder. Still in original + % sampling rate (amp_sr) +% LED - is 0 if not an optogenetics + % experiment, but otherwise, vectors of whether LED was on (1) or off (0) + + + +LN = length(epoc); +div = amp_sr/1000; +zx = 1:div:LN; +izx = floor(zx); +light = LED(izx); % put into 1000hz sampling rate + +%% first, find light trials +for t = 1:size(field_trials,1) % for each trial + samps_per_t = max(diff(field_trials,[],2)); % do this in case each trial doens't have exact same number of samples + light_out(t,:) = light(field_trials(t,1):field_trials(t,1)+samps_per_t); % get actual values of LED input to Intan +end + +[~,ex_trial] = min(mean(light_out,2)); % get example of a trial in which there was definitely no light +light_thresh = 5*std(light_out(ex_trial,:))+max(light_out(ex_trial,:)); % considered light trial if max value exceeds 5 standard deviations of ex_trial above the max value of ex_trial +light_trials = find(max(light_out,[],2)>light_thresh)'; % which trials the light turned on in +light_on = zeros(1,size(field_trials,1)); +light_on(light_trials) = 1; % matrix of all trials: 0 if no light, 1 if light + +% check against analyzer file +s = dir; +for i=1:length(s) + if strfind(s(i).name,'.analyzer') + analyze_file = s(i).name; + end +end +load(sprintf('%s/%s',exp_path,analyze_file),'-mat') % load analyzer file with stimulus info + +% get light conds +lightcond = find(strcmp(Analyzer.loops.conds{1}.symbol,'light_bit')); +conds = cellfun(@(x) x.val{lightcond}, Analyzer.loops.conds); +diff_conds = unique(conds); +num_conds = length(diff_conds); +% get trial types +trial_type = zeros(1,size(field_trials,1)); +for c = 1:length(conds) + ori_trials{:,c} = cellfun(@(x) x.trialno, Analyzer.loops.conds{c}.repeats); % store trials from different conditions in separate columns + trial_type(ori_trials{:,c}) = c; +end +trial_type = trial_type(1:length(light_on)); +light_trials_check = find(ismember(trial_type,find(conds))); +min_length = min(length(light_trials),length(light_trials_check)); % in case number of light trials are different between analyzer and LED input to Intan (suggests there's probably a problem...) +if sum(light_trials(1:min_length)~=light_trials_check(1:min_length)) % if numbers of light trials don't agree + err_count = 1; + fprintf('Analyzer file and LED inputs do not match\n') + off_trial = find(light_trials(1:min_length)~=light_trials_check(1:min_length),1,'first'); % check first conflicting trial + h = figure; plot(light_out(off_trial,:)); + check = input('Was this a light trial? Y or N: ','s'); + if strcmp(check,'N') + light_trials(off_trial) = []; + end + close(h) + if length(light_trials) > length(light_trials_check) % if more light trials were detected by light input to Intan than in analyzer file + offsetA = 1; + offsetB = 0; + elseif length(light_trials) < length(light_trials_check) % vice versa + offsetA = 0; + offsetB = 1; + else % correct number of trials, just disagreement about which ones were light trials + offsetA = 0; + offsetB = 0; + end + if sum(offsetA+offsetB) && sum(light_trials(off_trial+offsetA:end)~=light_trials_check(off_trial+offsetB:end)) % check the next conflicting trial +% fprintf('Analyzer file and LED inputs are not same length\n') + off_trial2 = find(light_trials(off_trial+1:end)~=light_trials_check(off_trial:end),1,'first'); + h = figure; plot(light(field_trials(off_trial+off_trial2,1):field_trials(off_trial+off_trial2,2))) + check = input('Was this a light trial? Y or N: ','s'); + if strcmp(check,'N') + light_trials(off_trial+off_trial2) = []; + end + close(h) + else + fprintf('LED input conflicts with analyzer file. Going with LED input\n') + end +else + err_count = 0; % no conlict between LED input and analyzer file +end + + + +%% determine light parameters given the type of light pulse + +if strcmp(exp_type,'ramp') + for t = 1:length(light_trials) + tt = light_trials(t); + light_end(t) = find(light_out(tt,:)>light_thresh,1,'last'); % find last sample when light was on + light_dur = 1; % assumes ramp lasts 1sec + light_start(t) = light_end(t)-light_dur*1000+1; % go backwards to find the start + end + light_hz = 1; + pulse_dur = round(mean(light_dur)); + all_light = zeros(1,size(field_trials,1)); % includes trials w/o light stim (as 0) + all_light(light_trials) = light_hz; + +elseif strcmp(exp_type,'trains') + for t = 1:length(light_trials) + tt = light_trials(t); + light_start(t) = find(light_out(tt,:)>light_thresh,1,'first'); + light_pulsedur(t) = find(light_out(tt,light_start(t):end)<=light_thresh,1,'first')-1; % finds duration of first light pulse in the trial + light_end(t) = find(light_out(tt,:)>light_thresh,1,'last'); + light_dur(t) = length(light_start(t):light_end(t))/1000; + light_sum(t) = sum(light_out(tt,:)>light_thresh); % sum of light pulses - used to figure out frequency + end + pulse_dur = round(mean(light_pulsedur)); % in sec + light_dur = round(max(light_dur)); % in case of trials with only single pulse, still consider light duration of trials with multiple pulses + light_hz = round(floor(light_sum./(pulse_dur))); % get the light frequencies for each trial (use floor in case ex. sum of 40Hz trial is 81 instead of 80) + pulse_dur = pulse_dur/1000; % change from ms to sec + all_light = zeros(1,size(field_trials,1)); % includes trials w/o light stim (as 0) + all_light(light_trials) = light_hz; + +else % simple step function + for t = 1:length(light_trials) + tt = light_trials(t); + light_start(t) = find(light_out(tt,:)>light_thresh,1,'first'); + light_end(t) = find(light_out(tt,:)>light_thresh,1,'last'); + light_dur(t) = length(light_start(t):light_end(t))/1000; + light_inten(t) = roundn(mean(light_out(tt,light_start(t):light_end(t))),-1); % round intensity to nearest hundreth +% light_inten(t) = roundn(mean(light_out(tt,light_start:light_end)),-1); % round intensity to nearest hundreth + end + intensities = unique(light_inten); + light_hz = 1; + pulse_dur = round(mean(light_dur)); + light_dur = pulse_dur; + all_light = zeros(1,size(field_trials,1)); % includes trials w/o light stim (as 0) + all_light(light_trials) = light_hz; + +% % TEMP b/c TiC2 +% diff_durs = unique(light_inten); +% for i=1:length(diff_durs) +% which_dur = ismember(light_inten,diff_durs(i)); % find trials that were at a particular light intensity +% all_light(light_trials(which_dur)) = diff_durs(i); +% end + + if length(intensities) > 1 % if this experiment involved light steps at different intensities - use LED input to determine intensities + small_diffs = find(diff(intensities) < .5); % to account for minor variability amongst intensities + if ~isempty(small_diffs) + % find((light_inten == intensities(small_diffs)) | (light_inten == intensities(small_diffs+1))) + orig_intensities = intensities; + intensities(small_diffs) = []; + count = 1; + for i = 1:length(intensities) + diff_intensities{i} = orig_intensities(count); + count = count+1; + if i == small_diffs + diff_intensities{i} = orig_intensities(small_diffs:small_diffs+1); + count = count+1; + end + end + else + for i = 1:length(intensities) + diff_intensities{i} = intensities(i); + end + end + + all_light = zeros(1,size(field_trials,1)); % includes trials w/o light stim (as 0) + for i = 1:length(intensities) + which_inten = ismember(light_inten,diff_intensities{i}); % find trials that were at a particular light intensity + all_light(light_trials(which_inten)) = intensities(i); + end + else % if single intensity experiment + all_light(light_trials) = 1; + end +end + +%% Get final parameters to save +av_light_start = time_index(round(mean(light_start))); % average time at which light started (1 less than sample # b/c starting with 0!) +% pulse_dur and all_light already made + +% save parameters +save('light_params.mat','all_light', 'pulse_dur', 'av_light_start'); + +return diff --git a/Intancode_Megan/intan2matlab.m b/Intancode_Megan/intan2matlab.m new file mode 100644 index 0000000..5093e54 --- /dev/null +++ b/Intancode_Megan/intan2matlab.m @@ -0,0 +1,213 @@ +function intan2matlab(exp_path) + +% Takes in .dat files in 'one file per signal type' format from Intan +% (see http://www.intantech.com/files/Intan_RHD2000_data_file_formats.pdf) +% +% MAK - 7/9/16 +% modified from intanphy2matlab_v2 so that it automatically recognizes +% which inputs are LED, epoch, etc. +% +% exp_path - establish directory that contains .kwik file as well as files +% from intan +% ex. 'E:\MK\9-4-15\09042015_189_150904_145916'; + +cd(exp_path) +kwik_file = sprintf('%s\\amplifier.kwik',exp_path); + +% read header file +[amplifier_channels,aux_input_channels,board_adc_channels,... + board_dig_in_channels,spike_triggers,supply_voltage_channels,... + frequency_parameters] = read_Intan_RHD2000_file; % script from Intan +amp_sr = frequency_parameters.amplifier_sample_rate; % amplifier sampling rate + +% read time.dat file from intan +fileinfo = dir('time.dat'); +num_samples = fileinfo.bytes/4; % int32 = 4 bytes +fid = fopen('time.dat', 'r'); +time = fread(fid, num_samples, 'int32'); +fclose(fid); +time = time / amp_sr; % time index of sample (in seconds) + +% % read auxillary.dat from intan +% num_channels = length(aux_input_channels); % aux input channel info from header file +% fileinfo = dir('auxiliary.dat'); +% num_samples = fileinfo.bytes/(num_channels * 2); % uint16 = 2 bytes +% fid = fopen('auxiliary.dat', 'r'); +% aux_v = fread(fid, [num_channels, num_samples], 'uint16'); +% fclose(fid); +% aux_v = aux_v * 0.0000374; % convert to volts + +% % read supply.dat from intan +% fileinfo = dir('supply.dat'); +% num_samples = fileinfo.bytes/(num_channels * 2); % uint16 = 2 bytes +% fid = fopen('supply.dat', 'r'); +% supply_v = fread(fid, [num_channels, num_samples], 'uint16'); +% fclose(fid); +% supply_v = supply_v * 0.0000748; % convert to volts + +% read analogin.dat from intan +num_channels = length(board_adc_channels); % ADC input info from header file +fileinfo = dir('analogin.dat'); +num_samples = fileinfo.bytes/(num_channels * 2); % uint16 = 2 bytes +fid = fopen('analogin.dat', 'r'); +adc = fread(fid, [num_channels, num_samples], 'uint16'); +fclose(fid); +adc = adc * 0.000050354; % convert to volts + +% read digitalin.dat from intan +num_board_dig_in_channels = length(board_dig_in_channels); % ADC input info from header file +fileinfo = dir('digitalin.dat'); +num_samples = fileinfo.bytes/2; % uint16 = 2 bytes +fid = fopen('digitalin.dat', 'r'); +dig_in_raw = fread(fid, num_samples, 'uint16'); +dig_in = zeros(num_board_dig_in_channels, num_samples); +fclose(fid); +% Extract digital input channels to separate variables. +for i=1:num_board_dig_in_channels + mask = 2^(board_dig_in_channels(i).native_order) * ones(size(dig_in_raw)); + dig_in(i, :) = (bitand(dig_in_raw, mask) > 0); +end + +% assign inputs to appropriate vectors +possible_inputs = {'photodiode','led','LED','laser','epoch','opt_mouse',... + 'encoder','encdA','encdB'}; % for string comparison +var_names = {'photo','LED','LED','LED',... + 'epoc','mouse','encdA','encdA','encdB'}; +diff_vars = unique(var_names); +used_vars = zeros(1,length(var_names)); % keep track of which var_names were used and whether they're digital (1) or analog (2) +disp('Assign inputs to appropriate variables') +% analog inputs +for i = 1:size(adc,1) + which_input = strfind(possible_inputs,board_adc_channels(i).custom_channel_name) ; % find which possible input corresponds to current input + ind = find(cellfun(@(x) ~isempty(x),which_input,'UniformOutput',1)); + used_vars(ind) = 2; + if ~isempty(ind) % if this input matches any of the predetermined possible inputs + fprintf(1, 'Analog input %d: %s', i, board_adc_channels(i).custom_channel_name); + fprintf(1, '\n'); + eval([sprintf('%s_input',var_names{ind}),sprintf('=%d',i)]); + else % if names don't match + fprintf(1, 'Analog input %d: %s', i, board_adc_channels(i).custom_channel_name); + fprintf(1, '\n'); + disp('Doesnt match possible variable names. Choose from the following:') + fprintf(1, '\n'); + for ii = 1:length(diff_vars) + fprintf(1, '%s: %d', diff_vars{ii},ii); + fprintf(1, '\n'); + end + chk = input('Which variable should this input be assigned to?: ','s'); + eval([sprintf('%s_input',diff_vars{chk}),sprintf('=%d',i)]); + used_vars(ind) = 2; + end +end +% digital inputs +for i = 1:size(dig_in,1) + which_input = strfind(possible_inputs,board_dig_in_channels(i).custom_channel_name) ; % find which possible input corresponds to current input + ind = find(cellfun(@(x) ~isempty(x),which_input,'UniformOutput',1)); + used_vars(ind) = 1; + if ~isempty(ind) % if this input matches any of the predetermined possible inputs + fprintf(1, 'Digital input %d: %s', i, board_dig_in_channels(i).custom_channel_name); + fprintf(1, '\n'); + eval([sprintf('%s_input',var_names{ind}),sprintf('=%d',i)]); + else % if names don't match + fprintf(1, 'Digital input %d: %s', i, board_dig_in_channels(i).custom_channel_name); + fprintf(1, '\n'); + fprintf(1, 'Doesnt match possible variable names. Choose from the following:'); + fprintf(1, '\n'); + for ii = 1:length(diff_vars) + fprintf(1, '%s: %d', diff_vars{ii},ii); + fprintf(1, '\n'); + end + chk = input('Which variable should this input be assigned to?: ','s'); + eval([sprintf('%s_input',diff_vars{chk}),sprintf('=%d',i)]); + used_vars(ind) = 1; + end +end + + +% extract appropriate inputs +epoc = dig_in(epoc_input,:); +photo = adc(photo_input,:); +if exist('LED_input','var') + if sum(used_vars(2:4)) == 1 % because indices 2-4 are all for LED_input + LED = dig_in(LED_input,:); + else + LED = adc(LED_input,:); + end +end +if exist('encdA_input','var') % assumes that if encdA exists, so does encdB + if sum(used_vars(7:8)) == 1 + encdA = dig_in(encdA_input,:); % indices 7-8 are for encdA_input + else + encdA = adc(encdA_input,:); + end +end +if exist('encdB_input','var') + encdB = dig_in(encdB_input,:); +end +if exist('mouse_input','var') + if used_var(6) == 1 + mouse = dig_in(mouse_input,:); + else + mouse = adc(mouse_input,:); + end +end + +clear dig_in adc dig_in_raw + +% Extract event information (taken from intan2matlab_ver8.m) +disp('find epoc times') +disp('search var and find trans points') +st=find(epoc(1,:),1,'first'); +en=find(epoc(1,:),1,'last'); +counter=0; +for i=st:1:en; + if counter==0 + if epoc(1,i)==1 && epoc(1,i-1)==0 + counter=counter+1; + fprintf('The number of tranisitons = %d\n',counter); + trans_timestamps2(counter,1)=i; + trans_timestamps2(counter,2)=time(i); + x=epoc(i:end); + trans_timestamps2(counter,3)=find(x==0,1,'first')+st; + trans_timestamps2(counter,4)=time(trans_timestamps2(counter,3)); + end + elseif counter>0 + if epoc(1,i)==1 && epoc(1,i-1)==0 + counter=counter+1; + fprintf('The number of tranisitons = %d\n',counter); + trans_timestamps2(counter,1)=i; + trans_timestamps2(counter,2)=time(i); + x=epoc(i:end); + if length(find(x==1))==length(x) + disp('no tranisition') + trans_timestamps2(counter,:)=[]; + else + trans_timestamps2(counter,3)=find(x==0,1,'first')+i; + trans_timestamps2(counter,4)=time(trans_timestamps2(counter,3)); + end + end + end +end +clear en st x i counter trials ans + +trials(:,1)=trans_timestamps2(:,2); +trials(:,2)=trans_timestamps2(:,4); + +LN = length(time); +div = amp_sr/1000; +zx = 1:div:LN; +izx = floor(zx); +time_index = time(izx); % downsample from 20000 hz to 1000 hz + +for i=1:size(trials,1) + field_trials (i,1) = find(time_index>=trials(i,1),1,'first'); % in 1000 hz samples + field_trials (i,2) = find(time_index>=trials(i,2),1,'first'); +end + +[re]= getSyncTimesRevCorr_AC(photo',(1/amp_sr)); %flip vector + + +save('data.mat', 'trials','field_trials','time_index','amp_sr',... + var_names{find(used_vars>0)},'re') + +return diff --git a/Intancode_Megan/intan_analysis_master.asv b/Intancode_Megan/intan_analysis_master.asv new file mode 100644 index 0000000..6f35799 --- /dev/null +++ b/Intancode_Megan/intan_analysis_master.asv @@ -0,0 +1,114 @@ +function intan_analysis_master(exp_path,exp_type) + +cd(exp_path) +if exist(sprintf('%s/data.mat',exp_path),'file') + load(sprintf('%s/data.mat',exp_path)) % data from intan2matlab.m +else + intan2matlab(exp_path); % data from intan2matlab.m + load(sprintf('%s/data.mat',exp_path)) % data from intan2matlab.m +end + + +% trials - num_trials x 2 matrix of trial start and end times (in seconds) +% field_trials - trial num x 2 matrix of trial start and end samples (in + % 1000 Hz sampling rate) - starts from 1! +% time_index - vector of time stamps of each sample (in seconds), with 1000 + % samples per second - starts from 0! +% amp_sr - original amplifier sampling rate +% epoc - vector of 1s and 0s indicating whether each sample was part of a + % trial (1) or not (0). Still in original sampling rate (amp_sr) +% mmvt - vector of 1s and 0s indicating whether mouse was running (1) or + % not (0) at time of sample. Still in original sampling rate (amp_sr) +% encd - vector of analog output from movement encoder. Still in original + % sampling rate (amp_sr) +% light - is 0 if not an optogenetics experiment, but otherwise, vectors of + % whether LED was on (1) or off (0) +% re - vector for the timestamps (rising phase of photodiode signal). you + % need to remove the first 2 and the last 2 timestamps. Timestamps + % signify the end of a four second black to gray period. +% photo - vector of analog output from photodiode. In original sampling rate + + +%% get experiment name and set up where to store results +full_dir = 'H:\Tlx3project\Augustresults'; +out = regexp(exp_path,'\\','split'); +inds = regexp(out{end},'_\d','start'); % looks for what's before an underscore followed immediately by a number; uses that as exp_name +exp_name = out{end}(1:inds(1)-1); +exp_dir = strcat(full_dir,'\',exp_name); +if ~exist(exp_dir) + mkdir(exp_dir); % will save everything in experiment subfolder within Augustresults +end + +%% load clustering info +% if clustering done with kilosort +if exist('spike_times.npy','file'); % output of npy2mat.py + % load kilosort data + spike_times = readNPY('spike_times.npy'); % here, spike times from ALL clusters + spike_times_ds = floor(spike_times/(amp_sr/1000)); % change sample #s to account for downsampling + clusters = readNPY('spike_clusters.npy'); + % get cluster group + fid = fopen('cluster_groups.csv'); + % read column headers + C_text = textscan(fid, '%s', 1, 'delimiter', ','); + % read group info + grp_dat = textscan(fid, '%f %s', 'delimiter', ','); + fclose(fid); + units = grp_dat{1}; % cluster numbers + cluster_group = grp_dat{2}; % 'good', 'noise', etc. + num_units = length(units); + good_units = units(strcmp(cluster_group,'good')); +else % load phy data + kwik_file = sprintf('%s/amplifier.kwik',exp_path); + info = hdf5info(kwik_file); + spike_times = hdf5read(kwik_file, '/channel_groups/0/spikes/time_samples'); + clusters = hdf5read(kwik_file, '/channel_groups/0/spikes/clusters/main'); % currently only from 1st shank! +end + +% downsample +LN = length(epoc); +div = amp_sr/1000; +zx = 1:div:LN; +izx = floor(zx); +if exist('LED','var') +% led = light(izx); + [params.all_light,params.pulse_dur,params.lighttime,params.av_light_start] = get_lightstim_v2(exp_path,exp_type); % just to get duration and time of light onset +end + +%% get the details of the experiment (trial types, prestim time, etc.) +[params.prestim,params.poststim,params.stimtime,params.trial_type,params.IVs] = get_exp_params(exp_path,exp_type); +params.onset = .1; % hardcoded (in sec) +% params.total_time = prestim+poststim+stimtime; +params.exp_name = exp_name; +params.exp_type = exp_type; +params.amp_sr = amp_sr; + +%% run unit analysis for each unit in this experiment +if exist(sprintf('%s/good_units.txt',exp_path),'file') + good_units = load(sprintf('%s/good_units.txt',exp_path)); % if you predetermined which clusters to look at +% else +% good_units = unique(clusters); % otherwise, look at all clusters (in kilo, this will only be the good ones anyway. but in klusta, it will be everything) +end + +num_units = length(good_units); +for i = 1:num_units + fprintf(sprintf('Performing analysis on %s cluster %s \n',exp_name,num2str(good_units(i)))) + [unitinfo(i),FRs(i),tuning(i),waveforms(i)] = intan_unit_analysis(good_units(i),field_trials,time_index,spike_times,clusters,params,'prestim',1); +end + +%% save full experimental results + +% variable information +S.vars = params.IVs; +S.trialinfo = params.trial_type; +S.exptype = exp_type; +S.lightconds = unique(params.all_light); +S.numunits = num_units; +S.unitinfo = unitinfo; +S.FRs = FRs; +S.tuning = tuning; +S.waveforms = waveforms; + +% save to experiment folder within full_dir +save(sprintf('%s\\%s_results.mat',exp_dir,exp_name),'S') + +end \ No newline at end of file diff --git a/Intancode_Megan/intan_analysis_master.m b/Intancode_Megan/intan_analysis_master.m new file mode 100644 index 0000000..2c3ed1f --- /dev/null +++ b/Intancode_Megan/intan_analysis_master.m @@ -0,0 +1,114 @@ +function intan_analysis_master(exp_path,exp_type) + +cd(exp_path) +if exist(sprintf('%s/data.mat',exp_path),'file') + load(sprintf('%s/data.mat',exp_path)) % data from intan2matlab.m +else + intan2matlab(exp_path); % data from intan2matlab.m + load(sprintf('%s/data.mat',exp_path)) % data from intan2matlab.m +end + + +% trials - num_trials x 2 matrix of trial start and end times (in seconds) +% field_trials - trial num x 2 matrix of trial start and end samples (in + % 1000 Hz sampling rate) - starts from 1! +% time_index - vector of time stamps of each sample (in seconds), with 1000 + % samples per second - starts from 0! +% amp_sr - original amplifier sampling rate +% epoc - vector of 1s and 0s indicating whether each sample was part of a + % trial (1) or not (0). Still in original sampling rate (amp_sr) +% mmvt - vector of 1s and 0s indicating whether mouse was running (1) or + % not (0) at time of sample. Still in original sampling rate (amp_sr) +% encd - vector of analog output from movement encoder. Still in original + % sampling rate (amp_sr) +% light - is 0 if not an optogenetics experiment, but otherwise, vectors of + % whether LED was on (1) or off (0) +% re - vector for the timestamps (rising phase of photodiode signal) in + % sec. you need to remove the first 2 and the last 2 timestamps. + % Timestamps signify the end of a four second black to gray period. +% photo - vector of analog output from photodiode. In original sampling rate + + +%% get experiment name and set up where to store results +full_dir = 'H:\Tlx3project\Augustresults'; +out = regexp(exp_path,'\\','split'); +inds = regexp(out{end},'_\d','start'); % looks for what's before an underscore followed immediately by a number; uses that as exp_name +exp_name = out{end}(1:inds(1)-1); +exp_dir = strcat(full_dir,'\',exp_name); +if ~exist(exp_dir) + mkdir(exp_dir); % will save everything in experiment subfolder within Augustresults +end + +%% load clustering info +% if clustering done with kilosort +if exist('spike_times.npy','file'); % one of the outputs of kilosort + % load kilosort data + spike_times = readNPY('spike_times.npy'); % here, spike times from ALL clusters + spike_times_ds = floor(spike_times/(amp_sr/1000)); % change sample #s to account for downsampling + clusters = readNPY('spike_clusters.npy'); + % get cluster group + fid = fopen('cluster_groups.csv'); + % read column headers + C_text = textscan(fid, '%s', 1, 'delimiter', ','); + % read group info + grp_dat = textscan(fid, '%f %s', 'delimiter', ','); + fclose(fid); + units = grp_dat{1}; % cluster numbers + cluster_group = grp_dat{2}; % 'good', 'noise', etc. + num_units = length(units); + good_units = units(strcmp(cluster_group,'good')); +else % load phy data + kwik_file = sprintf('%s/amplifier.kwik',exp_path); + info = hdf5info(kwik_file); + spike_times = hdf5read(kwik_file, '/channel_groups/0/spikes/time_samples'); + clusters = hdf5read(kwik_file, '/channel_groups/0/spikes/clusters/main'); % currently only from 1st shank! +end + +% downsample +LN = length(epoc); +div = amp_sr/1000; +zx = 1:div:LN; +izx = floor(zx); +if exist('LED','var') +% led = light(izx); + [params.all_light,params.pulse_dur,params.lighttime,params.av_light_start] = get_lightstim_v2(exp_path,exp_type); % just to get duration and time of light onset +end + +%% get the details of the experiment (trial types, prestim time, etc.) +[params.prestim,params.poststim,params.stimtime,params.trial_type,params.IVs] = get_exp_params(exp_path,exp_type); +params.onset = .1; % hardcoded (in sec) +% params.total_time = prestim+poststim+stimtime; +params.exp_name = exp_name; +params.exp_type = exp_type; +params.amp_sr = amp_sr; + +%% run unit analysis for each unit in this experiment +if exist(sprintf('%s/good_units.txt',exp_path),'file') + good_units = load(sprintf('%s/good_units.txt',exp_path)); % if you predetermined which clusters to look at +% else +% good_units = unique(clusters); % otherwise, look at all clusters (in kilo, this will only be the good ones anyway. but in klusta, it will be everything) +end + +num_units = length(good_units); +for i = 1:num_units + fprintf(sprintf('Performing analysis on %s cluster %s \n',exp_name,num2str(good_units(i)))) + [unitinfo(i),FRs(i),tuning(i),waveforms(i)] = intan_unit_analysis(good_units(i),field_trials,time_index,spike_times,clusters,params,'prestim',1); +end + +%% save full experimental results + +% variable information +S.vars = params.IVs; +S.trialinfo = params.trial_type; +S.exptype = exp_type; +S.lightconds = unique(params.all_light); +S.numunits = num_units; +S.unitinfo = unitinfo; +S.FRs = FRs; +S.tuning = tuning; +S.waveforms = waveforms; + +% save to experiment folder within full_dir +save(sprintf('%s\\%s_results.mat',exp_dir,exp_name),'S') + +end \ No newline at end of file diff --git a/Intancode_Megan/intan_analysis_master_copy.m b/Intancode_Megan/intan_analysis_master_copy.m new file mode 100644 index 0000000..52c7fe5 --- /dev/null +++ b/Intancode_Megan/intan_analysis_master_copy.m @@ -0,0 +1,466 @@ +function intan_analysis_master(exp_path,exp_type,unit,layer,normalizing,makeplots) + +cd(exp_path) +if exist(sprintf('%s/data.mat',exp_path),'file') + load(sprintf('%s/data.mat',exp_path)) % data from intan2matlab.m +else + intan2matlab(exp_path); % data from intan2matlab.m + load(sprintf('%s/data.mat',exp_path)) % data from intan2matlab.m +end + + +% trials - num_trials x 2 matrix of trial start and end times (in seconds) +% field_trials - trial num x 2 matrix of trial start and end samples (in + % 1000 Hz sampling rate) - starts from 1! +% time_index - vector of time stamps of each sample (in seconds), with 1000 + % samples per second - starts from 0! +% amp_sr - original amplifier sampling rate +% epoc - vector of 1s and 0s indicating whether each sample was part of a + % trial (1) or not (0). Still in original sampling rate (amp_sr) +% mmvt - vector of 1s and 0s indicating whether mouse was running (1) or + % not (0) at time of sample. Still in original sampling rate (amp_sr) +% encd - vector of analog output from movement encoder. Still in original + % sampling rate (amp_sr) +% light - is 0 if not an optogenetics experiment, but otherwise, vectors of + % whether LED was on (1) or off (0) +% re - vector for the timestamps (rising phase of photodiode signal). you + % need to remove the first 2 and the last 2 timestamps. Timestamps + % signify the end of a four second black to gray period. +% photo - vector of analog output from photodiode. In original sampling rate + + +%% get experiment name and set up where to store results +full_dir = 'H:\Tlx3project\Augustresults'; +out = regexp(exp_path,'\\','split'); +inds = regexp(out{end},'_\d','start'); % looks for what's before an underscore followed immediately by a number; uses that as exp_name +exp_name = out{end}(1:inds(1)-1); +exp_dir = strcat(full_dir,'\',exp_name); +if ~exist(exp_dir) + mkdir(all_fig_dir); % will save everything in experiment subfolder within Augustresults +end + +%% load clustering info +% if clustering done with kilosort +if exist('spikeinfo.mat','file'); % output of npy2mat.py + % load kilosort data + spike_times = readNPY('spike_times.npy'); % here, spike times from ALL clusters + spike_times_ds = floor(spike_times/(amp_sr/1000)); % change sample #s to account for downsampling + clusters = readNPY('spike_clusters.npy'); +else % load phy data + kwik_file = sprintf('%s/amplifier.kwik',exp_path); + info = hdf5info(kwik_file); + spike_times = hdf5read(kwik_file, '/channel_groups/0/spikes/time_samples'); + spike_times_ds = floor(spike_times/(amp_sr/1000)); % change sample #s to account for downsampling + spike_times_ds = spike_times_ds + 1; % has to be +1 because spike_times starts at 0, but the min possible field_trials value could be 1 + clusters = hdf5read(kwik_file, '/channel_groups/0/spikes/clusters/main'); % currently only from 1st shank! +end + +% downsample +LN = length(epoc); +div = amp_sr/1000; +zx = 1:div:LN; +izx = floor(zx); +if exist('LED','var') +% led = light(izx); + [all_light,pulse_dur,lighttime,av_light_start] = get_lightstim_v2(exp_path,exp_type); % just to get duration and time of light onset +end + +%% get the details of the experiment (trial types, prestim time, etc.) +[prestim,poststim,stimtime,trial_type,IVs] = get_exp_params(exp_path,exp_type); +onset = .2; % hardcoded (in sec) +total_time = prestim+poststim+stimtime; + +% do all of the following for each unit: +num_units = length(unique(clusters)); + +%% extract spike times +unit_times = spike_times_ds(find(clusters==unit)); % timestamps of unit's spikes +spiketimes = spikes_by_trial(unit_times,field_trials,250,time_index); % cell array of spike times during each trial + +%% make raster from spike times +spike_raster = make_raster(spiketimes,1000,total_time); + +%% count spikes during periods of interest +num_trials = length(spiketimes); + +% count spikes during prestim, stim, and onset periods +for t = 1:num_trials + spikes_all(t) = length(spiketimes{t}); + spikes_prestim(t) = length(find(spiketimes{t}=av_light_start)&(spiketimes{t}<=av_light_start+lighttime))); + spikes_onset(t) = length(find((spiketimes{t}>=prestim)&(spiketimes{t}=prestim-onset)&(spiketimes{t} 1 % if there are unequal numbers of trials at different orientations within a particular light condition + min_trials = min(trials_per_ori(lc,oriinds)); + for o = 1:length(oris) + ori_lc_trials = intersect(ori_trials(:,o),lc_trials{lc}); + trials2use = randperm(trials_per_ori(lc,o),min_trials); % randomly select min_trials number of trials to use for each orientation within particular lightcond + trialsbyori{lc}(:,o) = spikes_ev(ori_lc_trials(trials2use))./lighttime; % creates trials x oris matrix of FRs for Hotellings tsquare test for each lightcond + end + else + for o = 1:length(oris) + ori_trials(:,o) = find(trial_type(:,orivar) == oris(o)); + ori_lc_trials = intersect(ori_trials(:,o),lc_trials{lc}); + trialsbyori{lc}(:,o) = spikes_ev(ori_lc_trials)./lighttime; + end + end + + % get measure of OSI_CV by trial (for two-sample ttest, below) + for t = 1:size(trialsbyori{lc},1) + [~,OSICV_by_trial{lc}(t),~,~] = calcOSIDSI(trialsbyori{lc}(t,:),oris'); % for now, only using OSICV to measure change in tuning + end + + for o = 1:length(oris)/2 + tuning_curve_nodir{lc}(:,o) = mean([trialsbyori{lc}(:,o) trialsbyori{lc}(:,o+length(oris)/2)],2)-baseline; % average evoked FR of same orientations but different directions in NO LIGHT condition + end + tuned_sig(lc) = T2Hot1(tuning_curve_nodir{lc},0.05); % if tuned_sig(lc) < .05, significantly tuned +end + +% try a different way... +for lc = 1:length(lightconds) + oridom_rad = oris'.*pi/180; % convert to radians + oridom_rad = oridom_rad(1:6); + Xs = tuning_curve_nodir{lc}.*repmat(cos(oridom_rad),size(tuning_curve_nodir{lc},1),1); + Ys = tuning_curve_nodir{lc}.*repmat(sin(oridom_rad),size(tuning_curve_nodir{lc},1),1); + Rx = sum(Xs,2); + Ry = sum(Ys,2); + R = sqrt(Rx.^2+ Ry.^2); + ang = atan(Rx./Ry); % in radians + conv_sign = ones(size(tuning_curve_nodir{lc},1),1); + conv_sign(ang<0) = -1; + R = R.*conv_sign; % CHECK!!!! + tuned_sig_2(lc) = T2Hot1([ang R],.05); +end + + +% test for sig tuning change (two-sample ttest, recommended by Mazurek +% et al. 2014 +for lc = 1:length(lightconds)-1 + [~,tuningchange_sig(lc)] = ttest2(OSICV_by_trial{1}, OSICV_by_trial{lc+1}); % returns P value +end + +% %add multivariate T2 hotellings +% % first, need to vertically concatenate tuning curve matrices from each +% % light condition, but to do that, there need to be equal numbers of trials +% % per orientation across light conditions +% if length(unique(cellfun(@(x) size(x,1),tuning_curve_nodir,'UniformOutput',1))) > 1 % if there are unequal numbers of trials per orientation between different light conditions +% min_trials = min(cellfun(@(x) size(x,1),tuning_curve_nodir,'UniformOutput',1)); +% else +% min_trials = unique(cellfun(@(x) size(x,1),tuning_curve_nodir,'UniformOutput',1)); +% end +% +% for lc = 1:length(lightconds)-1 % hotelling's test only works for two samples, so need to separately compare nolight condition with each light condition +% cat_tuningcurve{lc} = [tuning_curve_nodir{lc}; tuning_curve_nodir{lc+1}]; % vertically-concatenated tuning curve matrix +% % use appropriate whether covariance structures in different light conditions are +% % equal +% cat_tuningcurve{lc} = [[ones(min_trials,1);2*ones(min_trials,1)] cat_tuningcurve{lc}]; % first column indicates group +% if MBoxtest(cat_tuningcurve{lc},0.05) < 0.05 % covariance structures are unequal +% tuningchange_sig{lc} = T2Hot2ihe(cat_tuningcurve{lc},0.05); %***sample sizes may be too small for this +% else % covariance structures are equal +% tuningchange_sig{lc} = T2Hot2iho(cat_tuningcurve{lc},0.05); +% end +% end + +% if it was NOT a ramp experiment, use SALT test to whether light changed activity within a given window of time (here, using 5 and 10ms) +if ~strcmp(exp_type,'ramp') + baseline_rast = spike_raster(visnolight_trials,floor(av_light_start*1000+1):floor(av_light_start*1000+1)+999); % using visually-evoked activity in nolight trials as baseline + for lc = 1:length(lightconds)-1 % currently calculating separately for each light condition - may not be necessary + ev_rast = spike_raster(vislight_trials(lc),floor(av_light_start*1000+1):floor(av_light_start*1000+1)+999); + [p_10(lc) I_10(lc)] = salt(baseline_rast,ev_rast,1/1000,.01); % within 10ms window + [p_5(lc) I_5(lc)] = salt(baseline_rast,ev_rast,1/1000,.005); % within 5ms window + end +else + p_10 = []; + I_10 = []; + p_5 = []; + I_5 = []; +end + +%% get waveform information +if exist(sprintf('Cluster_%s_waveforms.mat',num2str(unit)),'file'); + load(sprintf('Cluster_%s_waveforms.mat',num2str(unit))); +else + [waveforms_microV, max_ch] = readWaveformsFromDat(sprintf('%s/amplifier.dat',exp_path),32,spike_times(find(clusters==unit)),[-16 16],[],4); + save(sprintf('Cluster_%s_waveforms.mat',num2str(unit)),'waveforms_microV','max_ch'); +end +% get trough-to-peak time, trough-to-peak ratio, and +% full-width-half-maximum +[t2p_t,t2p_r,fwhm] = get_waveform_props(waveforms_microV,amp_sr); + +%% save results +% variable information +S.vars = IVs; +S.trialinfo = trial_type; +S.exptype = exp_type; +S.oris = oriconds; +S.lightconds = lightconds; + +% firing rate stuff +S.FRs.prestim = [spikerate_prestim spikerateSE_prestim]; +S.FRs.ev = [spikerate_ev spikerateSE_ev]; +S.FRs.onset = [spikerate_onset spikerateSE_onset]; +S.FRs.baseline = baseline; +S.FRs.baselinedef = normalizing; +S.FRs.SALT10ms = [p_10 I_10]; +S.FRs.SALT5ms = [p_5 I_5]; + +% tuning stuff +S.tuning.curve = tuning_curve; +S.tuning.normcurve = tuning_curve_norm; +S.tuning.OSI = OSI; +S.tuning.OSI_CV = OSI_CV; +S.tuning.DSI = DSI; +S.tuning.DSI_CV = DSI_CV; +S.tuning.sig_Hot = tuned_sig; +S.tuning.sig_Hot_polar = tuned_sig_2; + +% other +S.unit = sprintf('%s_%d',exp_name,unit); +S.layer = layer; +S.vissig = vis_sig; +S.lightsig_vis = vislight_sig; +S.lightsig_blnk = blanklight_sig; + +% waveforms +S.waveforms.microV = waveforms_microV; +S.waveforms.t2p_t = t2p_t; +S.waveforms.t2p_r = t2p_r; +S.waveforms.fwhm = fwhm; + +% save to experiment folder within full_dir +save(sprintf('%s\\%s_results.mat',exp_dir,exp_name),'S') + + +%% plot stuff! +if makeplots + + % make 2-by-4 figure array containing raster plot, PSTHs for visual and + % blank trials, zoom-in of PSTH, running v. stationary barplot, prestim + % v evoked v blanks barplot, orientation tuning curve, and waveform + fig_title = ['Cluster: ' num2str(unit)]; + clust_fig = figure('name', fig_title); + [type,idx] = sort(all_light); % sort trials by light conditions + + % 1) Raster plot + subplot(241) + make_raster_plot(spiketimes,1000,prestim,total_time,all_light,av_light_start,pulse_dur) + title('Raster plot') + + % 2) PSTH - visual trials + subplot(242) + binsize = .025; % 25 ms + make_psth_plot(binsize,spiketimes,ismember(1:num_trials,vis_trials),prestim,stimtime,total_time,trial_type(:,lightvar),av_light_start,pulse_dur) + title('PSTH plot - visual trials') + + % 3) PSTH - blank trials + subplot(243) + make_psth_plot(binsize,spiketimes,ismember(1:num_trials,blank_trials),prestim,stimtime,total_time,trial_type(:,lightvar),av_light_start,pulse_dur) + title('PSTH plot - blank trials') + + % 4) PSTH - zoom + subplot(244) + make_raster_plot(spiketimes,1000,prestim,total_time,all_light,av_light_start,pulse_dur) + xlim([.4 .8]) + title('Raster plot (zoom)') + + % 5) running v stationary + subplot(245) + color_mat = [0 0 0; 0 0.2 .7; 0 0.3 .5; 0 0.4 .4; 0 0 1]; % for graphing purposes (first is black, last is blue) + for lc = 1:length(lightconds) + if lightconds(lc) + [spikerate_run(lc) spikerateSE_run(lc)] = calc_firing_rates(spikes_ev,intersect(run_trials,light_trials{lc-1}),lighttime); + [spikerate_stat(lc) spikerateSE_stat(lc)] = calc_firing_rates(spikes_ev,intersect(stat_trials,light_trials{lc-1}),lighttime); + else + [spikerate_run(lc) spikerateSE_run(lc)] = calc_firing_rates(spikes_ev,intersect(run_trials,nolight_trials),lighttime); + [spikerate_stat(lc) spikerateSE_stat(lc)] = calc_firing_rates(spikes_ev,intersect(run_trials,nolight_trials),lighttime); + end + end + runbar = bargraph([spikerate_run; spikerate_stat],... + [spikerateSE_run; spikerateSE_stat]); + set(get(gca,'YLabel'),'String','Mean FR (spikes/s)','Fontsize',12) + set(gca,'XTicklabel','Running| Stationary') + for i = 1:length(lightconds) + if i == length(lightconds) + set(runbar(i),'FaceColor',color_mat(end,:),'EdgeColor',color_mat(end,:)); % make sure last lightcond is bright blue + else + set(runbar(i),'FaceColor',color_mat(i,:),'EdgeColor',color_mat(i,:)); + end + end + title('Firing rate - running vs. stationary') + + % 6) prestim vs evoked vs blank FRs + subplot(246) + FR = [spikerate_prestim{lightvar}; spikerate_onset{lightvar}; spikerate_ev{lightvar}]; + SE = [spikerateSE_prestim{lightvar}; spikerateSE_onset{lightvar}; spikerateSE_ev{lightvar}]; + if length(unique(trial_type(:,1))) > 1 % if blank trials + for lc = 1:length(lightconds) + if lightconds(lc) + [spikerate_blank(lc) spikerateSE_blank(lc)] = calc_firing_rates(spikes_ev,intersect(blank_trials,light_trials{lc-1}),lighttime); + else + [spikerate_blank(lc) spikerateSE_blank(lc)] = calc_firing_rates(spikes_ev,intersect(blank_trials,nolight_trials),lighttime); + end + end + FR = [FR; spikerate_blank]; + SE = [SE; spikerateSE_blank]; + xcondslabel = 'Prestim| Onset| Evoked| Blanks'; + else + xcondslabel = 'Prestim| Onset| Evoked'; + end + evokedbar = bargraph(FR,SE); + set(get(gca,'YLabel'),'String','Mean FR (spikes/sec)','Fontsize',12) + set(gca,'XTicklabel',xcondslabel) + for i = 1:length(lightconds) + if i == length(lightconds) + set(evokedbar(i),'FaceColor',color_mat(end,:),'EdgeColor',color_mat(end,:)); % make sure last lightcond is bright blue + else + set(evokedbar(i),'FaceColor',color_mat(i,:),'EdgeColor',color_mat(i,:)); + end + end + title('Firing rate') + + % 7) Tuning curves (stationary trials, baseline subtracted) + subplot(247) + for lc = 1:length(lightconds) + shadedErrorBar(oris,tuning_curve_norm(lc,:),spikerateSE_bycond(oriinds,lc,find(runconds==0)),{'Color',color_mat(lc,:),'linewidth',2},1); % plot ori tuning in NO RUN trials + hold on + end + ylabel('Firing rate (baseline-subtracted) (Hz)') + xlabel('Orientation (degrees)') + xlim([0 max(oris)]) + title('Orientation tuning during light period') + + % 8) Plot waveforms + + subplot(248) + t = linspace(0,(size(waveforms_microV,1)-1)/20,size(waveforms_microV,1)); % convert to ms + plot(t,waveforms_microV,'LineWidth',2); + xlim([0 max(t)]) + hold on + title(sprintf('Average waveform of spikes (Max ch: %d)',max_ch)) + ylabel('Amplitude (uV)') + xlabel('Time (ms)') + + % save figs + cd(all_fig_dir) + xSize = 24; ySize = 11; + xLeft = (21-xSize)/2; yTop = (30-ySize)/2; + set(gcf,'PaperPosition',[xLeft yTop xSize ySize]) + set(gcf,'Position',[0 0 xSize*50 ySize*50]) + if layer == 5 + layer_name = 'L5A'; + elseif layer == 5.5 + layer_name = 'L5B'; + elseif layer == 2.5 + layer_name = 'L23'; + else + layer_name = sprintf('L%s',num2str(layer)); + end + save_clust_name= sprintf('%s\\%s_Cluster%d_%s',exp_dir,exp_name,unit,layer_name); + print(clust_fig,'-dpng',save_clust_name) + print2eps(save_clust_name,clust_fig) + +end + +return + + + +function [spikerate, spikerate_SE] = calc_firing_rates(spikes,... + which_trials,period) + +% spikes = column vector of number of spikes by trial for unit of interest +% which_trials = vector of which trials you want to include +% period = length of period (in seconds) that number of spikes was counted + % from (e.g. evoked: 1.8s) + +spikerate = mean(spikes(which_trials)/period); +spikerate_SE = std(spikes(which_trials)/period)/sqrt(length(which_trials)); + +return diff --git a/Intancode_Megan/intan_unit_analysis.asv b/Intancode_Megan/intan_unit_analysis.asv new file mode 100644 index 0000000..e25c848 --- /dev/null +++ b/Intancode_Megan/intan_unit_analysis.asv @@ -0,0 +1,471 @@ +function [unitinfo,FRs,tuning,waveforms] = intan_unit_analysis(unit,field_trials,time_index,spike_times,clusters,params,normalizing,makeplots) + +% trial info from params +exp_name = params.exp_name; % e.g. 'T22_ramp' +exp_type = params.exp_type; +amp_sr = params.amp_sr; +trial_type = params.trial_type; % nxm matrix, n=number of trials, m=number of IVs +IVs = params.IVs; % independent variables +prestim = params.prestim; +stimtime = params.stimtime; +poststim = params.poststim; +total_time = prestim+stimtime+poststim; +onset = params.onset; % amount of time from start of visual stimulus considered "onset" +all_light = params.all_light; +pulse_dur = params.pulse_dur; % duration of light (only different from lighttime during trains experiments +lighttime = params.lighttime; % duration of light stimulation (e.g. 1sec) +av_light_start = params.av_light_start; % average time the light turned on across trials + + +%% extract spike times +spike_times_ds = floor(spike_times/(amp_sr/1000)); % change sample #s to account for downsampling +spike_times_ds = spike_times_ds + 1; % has to be +1 because spike_times starts at 0, but the min possible field_trials value could be 1 +unit_times = spike_times_ds(find(clusters==unit)); % timestamps of unit's spikes +spiketimes = spikes_by_trial(unit_times,field_trials,250,time_index); % cell array of spike times during each trial + +%% make raster from spike times +spike_raster = make_raster(spiketimes,1000,total_time); + +%% count spikes during periods of interest +num_trials = length(spiketimes); + +% count spikes during prestim, stim, and onset periods +for t = 1:num_trials + spikes_all(t) = length(spiketimes{t}); + spikes_prestim(t) = length(find(spiketimes{t}=av_light_start)&(spiketimes{t}<=av_light_start+lighttime))); + spikes_ev_half(t) = length(find((spiketimes{t}>=av_light_start)&(spiketimes{t}<=av_light_start+lighttime/2))); % spikes during first half of light stimulus (since light so powerfully turns off TLx cells) + spikes_onset(t) = length(find((spiketimes{t}>=prestim)&(spiketimes{t}=prestim-onset)&(spiketimes{t}= 1)) % if all average firing rates are under 1Hz, don't consider this unit for tuning +% tuningcount = 0; +% OSI(lc) = nan; +% OSI_CV(lc) = nan; +% DSI(lc) = nan; +% DSI_CV(lc) = nan; +% else + tuningcount = 1; + [OSI(lc),OSI_CV(lc),DSI(lc),DSI_CV(lc)] = calcOSIDSI(tuning_curve(lc,:),oris'); % using only STATIONARY trials (NOT baseline-subtracted, but check whether this is correct!!!!) +% end +end + +%% do some stats +% useful trial indicators: +vis_trials = find(trial_type(:,1)==1); +blank_trials = find(trial_type(:,1)==0); +nolight_trials = find(trial_type(:,lightvar)==0); +for lc=2:length(lightconds) + light_trials{lc-1} = find(trial_type(:,lightvar)==lightconds(lc)); + vislight_trials{lc-1} = find((trial_type(:,1)==1)&(trial_type(:,lightvar)==lightconds(lc))); + blanklight_trials{lc-1} = find((trial_type(:,1)==0)&(trial_type(:,lightvar)==lightconds(lc))); +end +visnolight_trials = find((trial_type(:,1)==1)&(trial_type(:,lightvar)==0)); % assumes first column of trial_type indicates visual vs. blank! +blanknolight_trials = find((trial_type(:,1)==0)&(trial_type(:,lightvar)==0)); +run_trials = find(trial_type(:,runvar) == 1); +stat_trials = find(trial_type(:,runvar) == 0); + +% kruskal-wallis test to test for significant and visual- and light-modulation +vis_sig = kruskalwallis([spikes_onset(visnolight_trials)' spikes_prestim_onsettime(visnolight_trials)'],[],'off'); % significance of visual response (testing using ONSET vs PRESTIM) +vis_sig2 = kruskalwallis([spikes_prestim(visnolight_trials)' spikes_ev_half(visnolight_trials)'],[],'off'); + +for lc = 1:length(lightconds)-1 % exclude nolight condition + ev_spikes = [spikes_ev(visnolight_trials) spikes_ev(vislight_trials{lc})]; % test for each light condition separately, first in VISUAL trials + ev_spikes_group = [ones(1,length(visnolight_trials)) 2*ones(1,length(vislight_trials{lc}))]; + vislight_sig(lc) = kruskalwallis(ev_spikes,ev_spikes_group,'off'); + ev_spikes_blanks = [spikes_ev(blanknolight_trials) spikes_ev(blanklight_trials{lc})]; % test for each light condition separately in BLANK trials + blank_spikes_group = [ones(1,length(blanknolight_trials)) 2*ones(1,length(blanklight_trials{lc}))]; + blanklight_sig(lc) = kruskalwallis(ev_spikes_blanks,blank_spikes_group,'off'); +end + +% test for significant orientation tuning +% but first, check on number of trials (T2Hot1 requires equal numbers of +% trials per orientation) +% ** using running AND stationary trials for now...too hard to equate trial +% numbers among running and stationary trials at each orientation... + +for lc = 1:length(lightconds) + if length(unique(trials_per_ori(lc,oriinds)))> 1 % if there are unequal numbers of trials at different orientations within a particular light condition + min_trials = min(trials_per_ori(lc,oriinds)); + for o = 1:length(oris) + ori_trials{o}= find(trial_type(:,orivar) == oris(o)); + ori_lc_trials = intersect(ori_trials{o},lc_trials{lc}); + trials2use = randperm(trials_per_ori(lc,o),min_trials); % randomly select min_trials number of trials to use for each orientation within particular lightcond + trialsbyori{lc}(:,o) = spikes_ev(ori_lc_trials(sort(trials2use)))./lighttime; % creates trials x oris matrix of FRs for Hotellings tsquare test for each lightcond + end + else + for o = 1:length(oris) + ori_trials{o} = find(trial_type(:,orivar) == oris(o)); + ori_lc_trials = intersect(ori_trials{o},lc_trials{lc}); + trialsbyori{lc}(:,o) = spikes_ev(ori_lc_trials)./lighttime; + end + end + + % get measure of OSI_CV by trial (for two-sample ttest, below) + for t = 1:size(trialsbyori{lc},1) + [~,OSICV_by_trial{lc}(t),~,~] = calcOSIDSI(trialsbyori{lc}(t,:),oris'); % for now, only using OSICV to measure change in tuning + end + + for o = 1:length(oris)/2 + tuning_curve_nodir{lc}(:,o) = mean([trialsbyori{lc}(:,o) trialsbyori{lc}(:,o+length(oris)/2)],2)-baseline; % average evoked FR of same orientations but different directions in NO LIGHT condition + end +% if tuningcount % only do for cells with sufficient tuning curves +% tuned_sig(lc) = T2Hot1(tuning_curve_nodir{lc},0.05); % if tuned_sig(lc) < .05, significantly tuned +% else +% tuned_sig(lc) = nan; +% end + tuned_sig(lc) = T2Hot1(tuning_curve_nodir{lc},0.05,zeros(1,length(oris)/2)); % if tuned_sig(lc) < .05, significantly tuned + tuned_sig_2(lc) = T2Hot1(tuning_curve_nodir{lc},0.05,mean(tuning_curve_nodir{lc}(:))*ones(1,length(oris)/2)); +% [warnmsg, msgid] = lastwarn; % if there was a warning with T2Hot1 (covariance matrix close to singular) +% if exist('warnmsg','var') +% tuned_sig(lc) = nan; +% end + +end + +% % try a different way... +% for lc = 1:length(lightconds) +% oridom_rad = oris'.*pi/180; % convert to radians +% oridom_rad = oridom_rad(1:2:end); +% Xs = tuning_curve_nodir{lc}.*repmat(cos(oridom_rad),size(tuning_curve_nodir{lc},1),1); +% Ys = tuning_curve_nodir{lc}.*repmat(sin(oridom_rad),size(tuning_curve_nodir{lc},1),1); +% Rx = sum(Xs,2); +% Ry = sum(Ys,2); +% R = sqrt(Rx.^2+ Ry.^2); +% ang = atan(Ry./Rx); % in radians % CHECK!!!! +% if tuningcount % only do for cells with sufficient tuning curves +% tuned_sig_2(lc) = T2Hot1([ang R],.05); +% else +% tuned_sig_2(lc) = nan; +% end +% end + + +% test for sig tuning change (two-sample ttest, recommended by Mazurek +% et al. 2014 +for lc = 1:length(lightconds)-1 + if tuningcount % only do for cells with sufficient tuning curves + [~,tuningchange_sig(lc)] = ttest2(OSICV_by_trial{1}, OSICV_by_trial{lc+1}); % returns P value + else + tuningchange_sig(lc) = nan; + end +end + +% %add multivariate T2 hotellings +% % first, need to vertically concatenate tuning curve matrices from each +% % light condition, but to do that, there need to be equal numbers of trials +% % per orientation across light conditions +% if length(unique(cellfun(@(x) size(x,1),tuning_curve_nodir,'UniformOutput',1))) > 1 % if there are unequal numbers of trials per orientation between different light conditions +% min_trials = min(cellfun(@(x) size(x,1),tuning_curve_nodir,'UniformOutput',1)); +% else +% min_trials = unique(cellfun(@(x) size(x,1),tuning_curve_nodir,'UniformOutput',1)); +% end +% +% for lc = 1:length(lightconds)-1 % hotelling's test only works for two samples, so need to separately compare nolight condition with each light condition +% cat_tuningcurve{lc} = [tuning_curve_nodir{lc}; tuning_curve_nodir{lc+1}]; % vertically-concatenated tuning curve matrix +% % use appropriate whether covariance structures in different light conditions are +% % equal +% cat_tuningcurve{lc} = [[ones(min_trials,1);2*ones(min_trials,1)] cat_tuningcurve{lc}]; % first column indicates group +% if MBoxtest(cat_tuningcurve{lc},0.05) < 0.05 % covariance structures are unequal +% tuningchange_sig{lc} = T2Hot2ihe(cat_tuningcurve{lc},0.05); %***sample sizes may be too small for this +% else % covariance structures are equal +% tuningchange_sig{lc} = T2Hot2iho(cat_tuningcurve{lc},0.05); +% end +% end + +% if it was NOT a ramp experiment, use SALT test to whether light changed activity within a given window of time (here, using 5 and 10ms) +if ~strcmp(exp_type,'ramp') + baseline_rast = spike_raster(visnolight_trials,floor(av_light_start*1000+1):floor(av_light_start*1000+1)+999); % using visually-evoked activity in nolight trials as baseline + for lc = 1:length(lightconds)-1 % currently calculating separately for each light condition - may not be necessary + ev_rast = spike_raster(vislight_trials{lc},floor(av_light_start*1000+1):floor(av_light_start*1000+1)+999); + [p_10(lc) I_10(lc)] = salt(baseline_rast,ev_rast,1/1000,.01); % within 10ms window + [p_5(lc) I_5(lc)] = salt(baseline_rast,ev_rast,1/1000,.005); % within 5ms window + [p_2(lc) I_2(lc)] = salt(baseline_rast,ev_rast,1/1000,.002); % within 2ms window + end +else + p_10 = []; + I_10 = []; + p_5 = []; + I_5 = []; + p_2 = []; + I_2 = []; +end + +%% get waveform information +exp_path = cd; % assuming CD was set in intan_unit_master +if exist(sprintf('Cluster_%s_waveforms.mat',num2str(unit)),'file'); + load(sprintf('Cluster_%s_waveforms.mat',num2str(unit))); +else + [waveforms_microV, max_ch] = readWaveformsFromDat(sprintf('%s\\amplifier.dat',exp_path),32,spike_times(find(clusters==unit)),[-16 16],[],4); + save(sprintf('Cluster_%s_waveforms.mat',num2str(unit)),'waveforms_microV','max_ch'); +end +% determine layer +if exist('layers.mat','file') % in current path + layers = importdata('layers.mat'); +else + define_layers(25,32,exp_path,1); %** currently hard-coded for 32ch NN probes - need to change!! + layers = importdata('layers.mat'); +end +layer = layers(max_ch); + +% get trough-to-peak time, trough-to-peak ratio, and +% full-width-half-maximum +[t2p_t,t2p_r,fwhm] = get_waveform_props(waveforms_microV,amp_sr); + +%% save results +% firing rate stuff +FRs.prestim = [spikerate_prestim{lightvar} spikerateSE_prestim{lightvar}]; +FRs.ev = [spikerate_ev{lightvar} spikerateSE_ev{lightvar}]; +FRs.evstart = [spikerate_ev_half{lightvar} spikerateSE_ev_half{lightvar}]; +FRs.onset = [spikerate_onset{lightvar} spikerateSE_onset{lightvar}]; +FRs.baseline = baseline; +FRs.baselinedef = normalizing; +FRs.SALT10ms = [p_10 I_10]; +FRs.SALT5ms = [p_5 I_5]; +FRs.SALT2ms = [p_2 I_2]; + +% tuning stuff +tuning.curve = tuning_curve; +tuning.normcurve = tuning_curve_norm; +tuning.OSI = OSI; +tuning.OSI_CV = OSI_CV; +tuning.DSI = DSI; +tuning.DSI_CV = DSI_CV; +tuning.sig_Hot = tuned_sig; +tuning.sig_Hot2 = tuned_sig_2; + +% general unit info +unitinfo.name = sprintf('%s_%d',exp_name,unit); +unitinfo.layer = layer; +unitinfo.vissig = vis_sig; +unitinfo.lightsig_vis = vislight_sig; +unitinfo.lightsig_blnk = blanklight_sig; +unitinfo.numspikes = length(unit_times); + +% waveforms +waveforms.microV = waveforms_microV; +waveforms.t2p_t = t2p_t; +waveforms.t2p_r = t2p_r; +waveforms.fwhm = fwhm; + + +%% plot stuff! +if makeplots + + % make appropriate figure legends + if strcmp(exp_type,'trains') + for i = 2:length(lightconds) % for graphing purposes + legend_labels{i-1} = sprintf('%dHz',lightconds(i)); + end + elseif strcmp(exp_type,'intensities') + legend_labels = {'Low light','Medium light','High light'}; + full_legend_labels = {'Light OFF','Low light','Medium light','High light'}; + else + legend_labels = {'Light ON'}; + end + + % make 2-by-4 figure array containing raster plot, PSTHs for visual and + % blank trials, zoom-in of PSTH, running v. stationary barplot, prestim + % v evoked v blanks barplot, orientation tuning curve, and waveform + fig_title = ['Cluster_' num2str(unit)]; + clust_fig = figure('name', fig_title); + [type,idx] = sort(all_light); % sort trials by light conditions + + % 1) Raster plot + subplot(241) + make_raster_plot(spiketimes,1000,prestim,total_time,all_light,av_light_start,pulse_dur) + set(gca,'FontSize',14); + title('Raster plot') + + % 2) PSTH - visual trials + subplot(242) + binsize = .025; % 25 ms + make_psth_plot(binsize,spiketimes,ismember(1:num_trials,vis_trials),prestim,stimtime,total_time,trial_type(:,lightvar),av_light_start,lighttime) + title('PSTH plot - visual trials','FontSize',14) + set(gca,'FontSize',14); + + % 3) PSTH - blank trials + subplot(243) + make_psth_plot(binsize,spiketimes,ismember(1:num_trials,blank_trials),prestim,stimtime,total_time,trial_type(:,lightvar),av_light_start,lighttime) + title('PSTH plot - blank trials','FontSize',14) + set(gca,'FontSize',14); + + % 4) PSTH - zoom + subplot(244) + make_raster_plot(spiketimes,1000,prestim,total_time,all_light,av_light_start,pulse_dur) + xlim([.4 .8]) + title('Raster plot (zoom)','FontSize',14) + set(gca,'FontSize',14); + + % 5) running v stationary + subplot(245) + color_mat = [0 0 0; 0 0 1; 0 .8 1; 0 0.5 .4; 0 .7 .2]; % for graphing purposes (first is black, last is green) + for lc = 1:length(lightconds) + if lightconds(lc) + [spikerate_run(lc) spikerateSE_run(lc)] = calc_firing_rates(spikes_ev,intersect(run_trials,light_trials{lc-1}),lighttime); + [spikerate_stat(lc) spikerateSE_stat(lc)] = calc_firing_rates(spikes_ev,intersect(stat_trials,light_trials{lc-1}),lighttime); + else + [spikerate_run(lc) spikerateSE_run(lc)] = calc_firing_rates(spikes_ev,intersect(run_trials,nolight_trials),lighttime); + [spikerate_stat(lc) spikerateSE_stat(lc)] = calc_firing_rates(spikes_ev,intersect(run_trials,nolight_trials),lighttime); + end + end + runbar = bargraph([spikerate_run; spikerate_stat],... + [spikerateSE_run; spikerateSE_stat]); + set(get(gca,'YLabel'),'String','Mean FR (spikes/s)','Fontsize',14) + set(gca,'XTicklabel','Running| Stationary') + for i = 1:length(lightconds) +% if i == length(lightconds) +% set(runbar(i),'FaceColor',color_mat(end,:),'EdgeColor',color_mat(end,:)); % make sure last lightcond is bright blue +% else + set(runbar(i),'FaceColor',color_mat(i,:),'EdgeColor',color_mat(i,:)); +% end + end + title('Firing rate - running vs. stationary','FontSize',14) + legend off + set(gca,'FontSize',14); + + % 6) prestim vs evoked vs blank FRs + subplot(246) + FR = [spikerate_prestim{lightvar}; spikerate_onset{lightvar}; spikerate_ev{lightvar}]; + SE = [spikerateSE_prestim{lightvar}; spikerateSE_onset{lightvar}; spikerateSE_ev{lightvar}]; + if length(unique(trial_type(:,1))) > 1 % if blank trials + for lc = 1:length(lightconds) + if lightconds(lc) + [spikerate_blank(lc) spikerateSE_blank(lc)] = calc_firing_rates(spikes_ev,intersect(blank_trials,light_trials{lc-1}),lighttime); + else + [spikerate_blank(lc) spikerateSE_blank(lc)] = calc_firing_rates(spikes_ev,intersect(blank_trials,nolight_trials),lighttime); + end + end + FR = [FR; spikerate_blank]; + SE = [SE; spikerateSE_blank]; + xcondslabel = 'Prestim| Onset| Evoked| Blanks'; + else + xcondslabel = 'Prestim| Onset| Evoked'; + end + evokedbar = bargraph(FR,SE); + set(get(gca,'YLabel'),'String','Mean FR (spikes/sec)','Fontsize',14) + set(gca,'XTicklabel',xcondslabel,'Fontsize',13) + for i = 1:length(lightconds) +% if i == length(lightconds) +% set(evokedbar(i),'FaceColor',color_mat(end,:),'EdgeColor',color_mat(end,:)); % make sure last lightcond is bright blue +% else + set(evokedbar(i),'FaceColor',color_mat(i,:),'EdgeColor',color_mat(i,:)); +% end + end + title('Firing rate','FontSize',14) + legend off + + % 7) Tuning curves (stationary trials, baseline subtracted) + subplot(247) + for lc = 1:length(lightconds) + shadedErrorBar(oris,tuning_curve_norm(lc,:),spikerateSE_bycond(oriinds,lc,find(runconds==0)),{'Color',color_mat(lc,:),'linewidth',2},1); % plot ori tuning in NO RUN trials + hold on + end + ylabel('Firing rate (baseline-subtracted) (Hz)','FontSize',14) + xlabel('Orientation (degrees)','FontSize',14) + xlim([0 max(oris)]) + title('Orientation tuning during light period','FontSize',14) + set(gca,'FontSize',14); + + % 8) Plot waveforms + + subplot(248) + t = linspace(0,(size(waveforms_microV,1)-1)/20,size(waveforms_microV,1)); % convert to ms + plot(t,waveforms_microV,'LineWidth',2); + xlim([0 max(t)]) + hold on + title(sprintf('Average waveform of spikes (Max ch: %d)',max_ch),'FontSize',14) + ylabel('Amplitude (uV)','FontSize',14) + xlabel('Time (ms)','FontSize',14) + set(gca,'FontSize',14); + + % save figs + all_fig_dir = sprintf('H:\\Tlx3project\\Augustresults\\%s\\Figures',exp_name); + if ~exist(all_fig_dir) + mkdir(all_fig_dir); + end + xSize = 24; ySize = 11; + xLeft = (21-xSize)/2; yTop = (30-ySize)/2; + set(gcf,'PaperPosition',[xLeft yTop xSize ySize]) + set(gcf,'Position',[0 0 xSize*50 ySize*50]) + if layer == 5 + layer_name = 'L5A'; + elseif layer == 5.5 + layer_name = 'L5B'; + elseif layer == 2.5 + layer_name = 'L23'; + else + layer_name = sprintf('L%s',num2str(layer)); + end + save_clust_name= sprintf('%s\\%s_Cluster%d_%s',all_fig_dir,exp_name,unit,layer_name); + print(clust_fig,'-dpng',save_clust_name) + print2eps(save_clust_name,clust_fig) + close all +end + +return + + + +function [spikerate, spikerate_SE] = calc_firing_rates(spikes,... + which_trials,period) + +% spikes = column vector of number of spikes by trial for unit of interest +% which_trials = vector of which trials you want to include +% period = length of period (in seconds) that number of spikes was counted + % from (e.g. evoked: 1.8s) + +spikerate = mean(spikes(which_trials)/period); +spikerate_SE = std(spikes(which_trials)/period)/sqrt(length(which_trials)); + +return diff --git a/Intancode_Megan/intan_unit_analysis.m b/Intancode_Megan/intan_unit_analysis.m new file mode 100644 index 0000000..48d2ad7 --- /dev/null +++ b/Intancode_Megan/intan_unit_analysis.m @@ -0,0 +1,472 @@ +function [unitinfo,FRs,tuning,waveforms] = intan_unit_analysis(unit,field_trials,time_index,spike_times,clusters,params,normalizing,makeplots) + +% trial info from params +exp_name = params.exp_name; % e.g. 'T22_ramp' +exp_type = params.exp_type; +amp_sr = params.amp_sr; +trial_type = params.trial_type; % nxm matrix, n=number of trials, m=number of IVs +IVs = params.IVs; % independent variables +prestim = params.prestim; +stimtime = params.stimtime; +poststim = params.poststim; +total_time = prestim+stimtime+poststim; +onset = params.onset; % amount of time from start of visual stimulus considered "onset" +all_light = params.all_light; +pulse_dur = params.pulse_dur; % duration of light (only different from lighttime during trains experiments +lighttime = params.lighttime; % duration of light stimulation (e.g. 1sec) +av_light_start = params.av_light_start; % average time the light turned on across trials + + +%% extract spike times +spike_times_ds = floor(spike_times/(amp_sr/1000)); % change sample #s to account for downsampling +spike_times_ds = spike_times_ds + 1; % has to be +1 because spike_times starts at 0, but the min possible field_trials value could be 1 +unit_times = spike_times_ds(find(clusters==unit)); % timestamps of unit's spikes +spiketimes = spikes_by_trial(unit_times,field_trials,250,time_index); % cell array of spike times during each trial + +%% make raster from spike times +spike_raster = make_raster(spiketimes,1000,total_time); + +%% count spikes during periods of interest +num_trials = length(spiketimes); + +% count spikes during prestim, stim, and onset periods +for t = 1:num_trials + spikes_all(t) = length(spiketimes{t}); + spikes_prestim(t) = length(find(spiketimes{t}=av_light_start)&(spiketimes{t}<=av_light_start+lighttime))); + spikes_ev_half(t) = length(find((spiketimes{t}>=av_light_start)&(spiketimes{t}<=av_light_start+lighttime/2))); % spikes during first half of light stimulus (since light so powerfully turns off TLx cells) + spikes_onset(t) = length(find((spiketimes{t}>=prestim)&(spiketimes{t}=prestim-onset)&(spiketimes{t}= 1)) % if all average firing rates are under 1Hz, don't consider this unit for tuning +% tuningcount = 0; +% OSI(lc) = nan; +% OSI_CV(lc) = nan; +% DSI(lc) = nan; +% DSI_CV(lc) = nan; +% else + tuningcount = 1; + [OSI(lc),OSI_CV(lc),DSI(lc),DSI_CV(lc)] = calcOSIDSI(tuning_curve(lc,:),oris'); % using only STATIONARY trials (NOT baseline-subtracted, but check whether this is correct!!!!) +% end +end + +%% do some stats +% useful trial indicators: +vis_trials = find(trial_type(:,1)==1); +blank_trials = find(trial_type(:,1)==0); +nolight_trials = find(trial_type(:,lightvar)==0); +for lc=2:length(lightconds) + light_trials{lc-1} = find(trial_type(:,lightvar)==lightconds(lc)); + vislight_trials{lc-1} = find((trial_type(:,1)==1)&(trial_type(:,lightvar)==lightconds(lc))); + blanklight_trials{lc-1} = find((trial_type(:,1)==0)&(trial_type(:,lightvar)==lightconds(lc))); +end +visnolight_trials = find((trial_type(:,1)==1)&(trial_type(:,lightvar)==0)); % assumes first column of trial_type indicates visual vs. blank! +blanknolight_trials = find((trial_type(:,1)==0)&(trial_type(:,lightvar)==0)); +run_trials = find(trial_type(:,runvar) == 1); +stat_trials = find(trial_type(:,runvar) == 0); + +% kruskal-wallis test to test for significant and visual- and light-modulation +vis_sig = kruskalwallis([spikes_onset(visnolight_trials)' spikes_prestim_onsettime(visnolight_trials)'],[],'off'); % significance of visual response (testing using ONSET vs PRESTIM) +vis_sig2 = kruskalwallis([spikes_prestim(visnolight_trials)' spikes_ev_half(visnolight_trials)'],[],'off'); % significance of visual response (testing using 500-1000ms after stim onset vs PRESTIM) + +for lc = 1:length(lightconds)-1 % exclude nolight condition + ev_spikes = [spikes_ev(visnolight_trials) spikes_ev(vislight_trials{lc})]; % test for each light condition separately, first in VISUAL trials + ev_spikes_group = [ones(1,length(visnolight_trials)) 2*ones(1,length(vislight_trials{lc}))]; + vislight_sig(lc) = kruskalwallis(ev_spikes,ev_spikes_group,'off'); + ev_spikes_blanks = [spikes_ev(blanknolight_trials) spikes_ev(blanklight_trials{lc})]; % test for each light condition separately in BLANK trials + blank_spikes_group = [ones(1,length(blanknolight_trials)) 2*ones(1,length(blanklight_trials{lc}))]; + blanklight_sig(lc) = kruskalwallis(ev_spikes_blanks,blank_spikes_group,'off'); +end + +% test for significant orientation tuning +% but first, check on number of trials (T2Hot1 requires equal numbers of +% trials per orientation) +% ** using running AND stationary trials for now...too hard to equate trial +% numbers among running and stationary trials at each orientation... + +for lc = 1:length(lightconds) + if length(unique(trials_per_ori(lc,oriinds)))> 1 % if there are unequal numbers of trials at different orientations within a particular light condition + min_trials = min(trials_per_ori(lc,oriinds)); + for o = 1:length(oris) + ori_trials{o}= find(trial_type(:,orivar) == oris(o)); + ori_lc_trials = intersect(ori_trials{o},lc_trials{lc}); + trials2use = randperm(trials_per_ori(lc,o),min_trials); % randomly select min_trials number of trials to use for each orientation within particular lightcond + trialsbyori{lc}(:,o) = spikes_ev(ori_lc_trials(sort(trials2use)))./lighttime; % creates trials x oris matrix of FRs for Hotellings tsquare test for each lightcond + end + else + for o = 1:length(oris) + ori_trials{o} = find(trial_type(:,orivar) == oris(o)); + ori_lc_trials = intersect(ori_trials{o},lc_trials{lc}); + trialsbyori{lc}(:,o) = spikes_ev(ori_lc_trials)./lighttime; + end + end + + % get measure of OSI_CV by trial (for two-sample ttest, below) + for t = 1:size(trialsbyori{lc},1) + [~,OSICV_by_trial{lc}(t),~,~] = calcOSIDSI(trialsbyori{lc}(t,:),oris'); % for now, only using OSICV to measure change in tuning + end + + for o = 1:length(oris)/2 + tuning_curve_nodir{lc}(:,o) = mean([trialsbyori{lc}(:,o) trialsbyori{lc}(:,o+length(oris)/2)],2)-baseline; % average evoked FR of same orientations but different directions in NO LIGHT condition + end +% if tuningcount % only do for cells with sufficient tuning curves +% tuned_sig(lc) = T2Hot1(tuning_curve_nodir{lc},0.05); % if tuned_sig(lc) < .05, significantly tuned +% else +% tuned_sig(lc) = nan; +% end + tuned_sig(lc) = T2Hot1(tuning_curve_nodir{lc},0.05,zeros(1,length(oris)/2)); % if tuned_sig(lc) < .05, significantly tuned + tuned_sig_2(lc) = T2Hot1(tuning_curve_nodir{lc},0.05,mean(tuning_curve_nodir{lc}(:))*ones(1,length(oris)/2)); +% [warnmsg, msgid] = lastwarn; % if there was a warning with T2Hot1 (covariance matrix close to singular) +% if exist('warnmsg','var') +% tuned_sig(lc) = nan; +% end + +end + +% % try a different way... +% for lc = 1:length(lightconds) +% oridom_rad = oris'.*pi/180; % convert to radians +% oridom_rad = oridom_rad(1:2:end); +% Xs = tuning_curve_nodir{lc}.*repmat(cos(oridom_rad),size(tuning_curve_nodir{lc},1),1); +% Ys = tuning_curve_nodir{lc}.*repmat(sin(oridom_rad),size(tuning_curve_nodir{lc},1),1); +% Rx = sum(Xs,2); +% Ry = sum(Ys,2); +% R = sqrt(Rx.^2+ Ry.^2); +% ang = atan(Ry./Rx); % in radians % CHECK!!!! +% if tuningcount % only do for cells with sufficient tuning curves +% tuned_sig_2(lc) = T2Hot1([ang R],.05); +% else +% tuned_sig_2(lc) = nan; +% end +% end + + +% test for sig tuning change (two-sample ttest, recommended by Mazurek +% et al. 2014 +for lc = 1:length(lightconds)-1 + if tuningcount % only do for cells with sufficient tuning curves + [~,tuningchange_sig(lc)] = ttest2(OSICV_by_trial{1}, OSICV_by_trial{lc+1}); % returns P value + else + tuningchange_sig(lc) = nan; + end +end + +% %add multivariate T2 hotellings +% % first, need to vertically concatenate tuning curve matrices from each +% % light condition, but to do that, there need to be equal numbers of trials +% % per orientation across light conditions +% if length(unique(cellfun(@(x) size(x,1),tuning_curve_nodir,'UniformOutput',1))) > 1 % if there are unequal numbers of trials per orientation between different light conditions +% min_trials = min(cellfun(@(x) size(x,1),tuning_curve_nodir,'UniformOutput',1)); +% else +% min_trials = unique(cellfun(@(x) size(x,1),tuning_curve_nodir,'UniformOutput',1)); +% end +% +% for lc = 1:length(lightconds)-1 % hotelling's test only works for two samples, so need to separately compare nolight condition with each light condition +% cat_tuningcurve{lc} = [tuning_curve_nodir{lc}; tuning_curve_nodir{lc+1}]; % vertically-concatenated tuning curve matrix +% % use appropriate whether covariance structures in different light conditions are +% % equal +% cat_tuningcurve{lc} = [[ones(min_trials,1);2*ones(min_trials,1)] cat_tuningcurve{lc}]; % first column indicates group +% if MBoxtest(cat_tuningcurve{lc},0.05) < 0.05 % covariance structures are unequal +% tuningchange_sig{lc} = T2Hot2ihe(cat_tuningcurve{lc},0.05); %***sample sizes may be too small for this +% else % covariance structures are equal +% tuningchange_sig{lc} = T2Hot2iho(cat_tuningcurve{lc},0.05); +% end +% end + +% if it was NOT a ramp experiment, use SALT test to whether light changed activity within a given window of time (here, using 5 and 10ms) +if ~strcmp(exp_type,'ramp') + baseline_rast = spike_raster(visnolight_trials,floor(av_light_start*1000+1):floor(av_light_start*1000+1)+999); % using visually-evoked activity in nolight trials as baseline + for lc = 1:length(lightconds)-1 % currently calculating separately for each light condition - may not be necessary + ev_rast = spike_raster(vislight_trials{lc},floor(av_light_start*1000+1):floor(av_light_start*1000+1)+999); + [p_10(lc) I_10(lc)] = salt(baseline_rast,ev_rast,1/1000,.01); % within 10ms window + [p_5(lc) I_5(lc)] = salt(baseline_rast,ev_rast,1/1000,.005); % within 5ms window + [p_2(lc) I_2(lc)] = salt(baseline_rast,ev_rast,1/1000,.002); % within 2ms window + end +else + p_10 = []; + I_10 = []; + p_5 = []; + I_5 = []; + p_2 = []; + I_2 = []; +end + +%% get waveform information +exp_path = cd; % assuming CD was set in intan_unit_master +if exist(sprintf('Cluster_%s_waveforms.mat',num2str(unit)),'file'); + load(sprintf('Cluster_%s_waveforms.mat',num2str(unit))); +else + [waveforms_microV, max_ch] = readWaveformsFromDat(sprintf('%s\\amplifier.dat',exp_path),32,spike_times(find(clusters==unit)),[-16 16],[],4); + save(sprintf('Cluster_%s_waveforms.mat',num2str(unit)),'waveforms_microV','max_ch'); +end +% determine layer +if exist('layers.mat','file') % in current path + layers = importdata('layers.mat'); +else + define_layers(25,32,exp_path,1); %** currently hard-coded for 32ch NN probes - need to change!! + layers = importdata('layers.mat'); +end +layer = layers(max_ch); + +% get trough-to-peak time, trough-to-peak ratio, and +% full-width-half-maximum +[t2p_t,t2p_r,fwhm] = get_waveform_props(waveforms_microV,amp_sr); + +%% save results +% firing rate stuff +FRs.prestim = [spikerate_prestim{lightvar} spikerateSE_prestim{lightvar}]; +FRs.ev = [spikerate_ev{lightvar} spikerateSE_ev{lightvar}]; +FRs.evstart = [spikerate_ev_half{lightvar} spikerateSE_ev_half{lightvar}]; +FRs.onset = [spikerate_onset{lightvar} spikerateSE_onset{lightvar}]; +FRs.baseline = baseline; +FRs.baselinedef = normalizing; +FRs.SALT10ms = [p_10 I_10]; +FRs.SALT5ms = [p_5 I_5]; +FRs.SALT2ms = [p_2 I_2]; + +% tuning stuff +tuning.curve = tuning_curve; +tuning.normcurve = tuning_curve_norm; +tuning.OSI = OSI; +tuning.OSI_CV = OSI_CV; +tuning.DSI = DSI; +tuning.DSI_CV = DSI_CV; +tuning.sig_Hot = tuned_sig; +tuning.sig_Hot2 = tuned_sig_2; + +% general unit info +unitinfo.name = sprintf('%s_%d',exp_name,unit); +unitinfo.layer = layer; +unitinfo.vissig = vis_sig; +unitinfo.vissig2 = vis_sig2; +unitinfo.lightsig_vis = vislight_sig; +unitinfo.lightsig_blnk = blanklight_sig; +unitinfo.numspikes = length(unit_times); + +% waveforms +waveforms.microV = waveforms_microV; +waveforms.t2p_t = t2p_t; +waveforms.t2p_r = t2p_r; +waveforms.fwhm = fwhm; + + +%% plot stuff! +if makeplots + + % make appropriate figure legends + if strcmp(exp_type,'trains') + for i = 2:length(lightconds) % for graphing purposes + legend_labels{i-1} = sprintf('%dHz',lightconds(i)); + end + elseif strcmp(exp_type,'intensities') + legend_labels = {'Low light','Medium light','High light'}; + full_legend_labels = {'Light OFF','Low light','Medium light','High light'}; + else + legend_labels = {'Light ON'}; + end + + % make 2-by-4 figure array containing raster plot, PSTHs for visual and + % blank trials, zoom-in of PSTH, running v. stationary barplot, prestim + % v evoked v blanks barplot, orientation tuning curve, and waveform + fig_title = ['Cluster_' num2str(unit)]; + clust_fig = figure('name', fig_title); + [type,idx] = sort(all_light); % sort trials by light conditions + + % 1) Raster plot + subplot(241) + make_raster_plot(spiketimes,1000,prestim,total_time,all_light,av_light_start,pulse_dur) + set(gca,'FontSize',14); + title('Raster plot') + + % 2) PSTH - visual trials + subplot(242) + binsize = .025; % 25 ms + make_psth_plot(binsize,spiketimes,ismember(1:num_trials,vis_trials),prestim,stimtime,total_time,trial_type(:,lightvar),av_light_start,lighttime) + title('PSTH plot - visual trials','FontSize',14) + set(gca,'FontSize',14); + + % 3) PSTH - blank trials + subplot(243) + make_psth_plot(binsize,spiketimes,ismember(1:num_trials,blank_trials),prestim,stimtime,total_time,trial_type(:,lightvar),av_light_start,lighttime) + title('PSTH plot - blank trials','FontSize',14) + set(gca,'FontSize',14); + + % 4) PSTH - zoom + subplot(244) + make_raster_plot(spiketimes,1000,prestim,total_time,all_light,av_light_start,pulse_dur) + xlim([.4 .8]) + title('Raster plot (zoom)','FontSize',14) + set(gca,'FontSize',14); + + % 5) running v stationary + subplot(245) + color_mat = [0 0 0; 0 .8 1; 0 0 1; 0 0.5 .4; 0 .7 .2]; % for graphing purposes (first is black, last is green) + for lc = 1:length(lightconds) + if lightconds(lc) + [spikerate_run(lc) spikerateSE_run(lc)] = calc_firing_rates(spikes_ev,intersect(run_trials,light_trials{lc-1}),lighttime); + [spikerate_stat(lc) spikerateSE_stat(lc)] = calc_firing_rates(spikes_ev,intersect(stat_trials,light_trials{lc-1}),lighttime); + else + [spikerate_run(lc) spikerateSE_run(lc)] = calc_firing_rates(spikes_ev,intersect(run_trials,nolight_trials),lighttime); + [spikerate_stat(lc) spikerateSE_stat(lc)] = calc_firing_rates(spikes_ev,intersect(stat_trials,nolight_trials),lighttime); + end + end + runbar = bargraph([spikerate_run; spikerate_stat],... + [spikerateSE_run; spikerateSE_stat]); + set(get(gca,'YLabel'),'String','Mean FR (spikes/s)','Fontsize',14) + set(gca,'XTicklabel','Running| Stationary') + for i = 1:length(lightconds) +% if i == length(lightconds) +% set(runbar(i),'FaceColor',color_mat(end,:),'EdgeColor',color_mat(end,:)); % make sure last lightcond is bright blue +% else + set(runbar(i),'FaceColor',color_mat(i,:),'EdgeColor',color_mat(i,:)); +% end + end + title('Firing rate - running vs. stationary','FontSize',14) + legend off + set(gca,'FontSize',14); + + % 6) prestim vs evoked vs blank FRs + subplot(246) + FR = [spikerate_prestim{lightvar}; spikerate_onset{lightvar}; spikerate_ev{lightvar}]; + SE = [spikerateSE_prestim{lightvar}; spikerateSE_onset{lightvar}; spikerateSE_ev{lightvar}]; + if length(unique(trial_type(:,1))) > 1 % if blank trials + for lc = 1:length(lightconds) + if lightconds(lc) + [spikerate_blank(lc) spikerateSE_blank(lc)] = calc_firing_rates(spikes_ev,intersect(blank_trials,light_trials{lc-1}),lighttime); + else + [spikerate_blank(lc) spikerateSE_blank(lc)] = calc_firing_rates(spikes_ev,intersect(blank_trials,nolight_trials),lighttime); + end + end + FR = [FR; spikerate_blank]; + SE = [SE; spikerateSE_blank]; + xcondslabel = 'Prestim| Onset| Evoked| Blanks'; + else + xcondslabel = 'Prestim| Onset| Evoked'; + end + evokedbar = bargraph(FR,SE); + set(get(gca,'YLabel'),'String','Mean FR (spikes/sec)','Fontsize',14) + set(gca,'XTicklabel',xcondslabel,'Fontsize',13) + for i = 1:length(lightconds) +% if i == length(lightconds) +% set(evokedbar(i),'FaceColor',color_mat(end,:),'EdgeColor',color_mat(end,:)); % make sure last lightcond is bright blue +% else + set(evokedbar(i),'FaceColor',color_mat(i,:),'EdgeColor',color_mat(i,:)); +% end + end + title('Firing rate','FontSize',14) + legend off + + % 7) Tuning curves (stationary trials, baseline subtracted) + subplot(247) + for lc = 1:length(lightconds) + shadedErrorBar(oris,tuning_curve_norm(lc,:),spikerateSE_bycond(oriinds,lc,find(runconds==0)),{'Color',color_mat(lc,:),'linewidth',2},1); % plot ori tuning in NO RUN trials + hold on + end + ylabel('Firing rate (baseline-subtracted) (Hz)','FontSize',14) + xlabel('Orientation (degrees)','FontSize',14) + xlim([0 max(oris)]) + title('Orientation tuning during light period','FontSize',14) + set(gca,'FontSize',14); + + % 8) Plot waveforms + + subplot(248) + t = linspace(0,(size(waveforms_microV,1)-1)/20,size(waveforms_microV,1)); % convert to ms + plot(t,waveforms_microV,'LineWidth',2); + xlim([0 max(t)]) + hold on + title(sprintf('Average waveform of spikes (Max ch: %d)',max_ch),'FontSize',14) + ylabel('Amplitude (uV)','FontSize',14) + xlabel('Time (ms)','FontSize',14) + set(gca,'FontSize',14); + + % save figs + all_fig_dir = sprintf('H:\\Tlx3project\\Augustresults\\%s\\Figures',exp_name); + if ~exist(all_fig_dir) + mkdir(all_fig_dir); + end + xSize = 24; ySize = 11; + xLeft = (21-xSize)/2; yTop = (30-ySize)/2; + set(gcf,'PaperPosition',[xLeft yTop xSize ySize]) + set(gcf,'Position',[0 0 xSize*50 ySize*50]) + if layer == 5 + layer_name = 'L5A'; + elseif layer == 5.5 + layer_name = 'L5B'; + elseif layer == 2.5 + layer_name = 'L23'; + else + layer_name = sprintf('L%s',num2str(layer)); + end + save_clust_name= sprintf('%s\\%s_Cluster%d_%s',all_fig_dir,exp_name,unit,layer_name); + print(clust_fig,'-dpng',save_clust_name) + print2eps(save_clust_name,clust_fig) + close all +end + +return + + + +function [spikerate, spikerate_SE] = calc_firing_rates(spikes,... + which_trials,period) + +% spikes = column vector of number of spikes by trial for unit of interest +% which_trials = vector of which trials you want to include +% period = length of period (in seconds) that number of spikes was counted + % from (e.g. evoked: 1.8s) + +spikerate = mean(spikes(which_trials)/period); +spikerate_SE = std(spikes(which_trials)/period)/sqrt(length(which_trials)); + +return diff --git a/Intancode_Megan/kilo_cluster_plots_opto.m b/Intancode_Megan/kilo_cluster_plots_opto.m new file mode 100644 index 0000000..f0cf95d --- /dev/null +++ b/Intancode_Megan/kilo_cluster_plots_opto.m @@ -0,0 +1,611 @@ +function kilo_cluster_plots_opto(exp_path,unittype,normalizing,exp_type) + +% modified from phy_spike_analysis_v2.m - takes in data from +% phy_spike_analysis_v3.m +% MAK - 3/14/16 +% assumes this is an optogenetics experiment +% unittype = 'su' or 'mu' (single or multi unit) +% normalizing = 'blank' or 'prestim' to designate how to correct firing + % rates +% exp_type = none, or 'ramp', 'trains', 'intensities' or 'size'. default is none. + +% 6/7/16 - removed prelight and postlight parameters, replaced with +% av_light_start from get_lightstim.m +% 6/13/16 - added exp_type input and plots for running +% 7/17/16 - changed get_lightstim to get_lightstim_v2 + +color_mat = [0 0 0; 0 0.2 .7; 0 0.3 .5; 0 0.4 .4; 0 0 1]; % for graphing purposes (first is black, last is blue) + +% set up experiment directory +exp_dir = 'H:\Tlx3project\ChR2'; +% animal_name = regexp(exp_path,'T\d+','match'); +% animal_name = animal_name{1}; +% run_name = regexp(exp_path,'run\d','match'); +% if isempty(run_name) +% exp_name = animal_name; +% else +% exp_name = strcat(animal_name,run_name{1}); +% end +exp_name = 'LP'; % TEMP + +% load data from phy_spike_analysis_v3 +cd(exp_path) +% if exist(sprintf('%s/%s_spikedata.mat',exp_path,unittype),'file') +% load(sprintf('%s/%s_spikedata.mat',exp_path,unittype)) +% else + kilo_spike_analysis(exp_path,unittype,exp_type); + load(sprintf('%s/%s_spikedata.mat',exp_path,unittype)) +% end + +% get amplifier sampling rate (from intanphy2matlab.m) +load(sprintf('%s/data.mat',exp_path),'amp_sr') % data from intanphy2matlab.m +div = amp_sr/1000; % samples per millisecond + +% make directory to store figures (if one doesn't already exist) +fig_dir = sprintf('%s/Figures',exp_path); +if ~exist(fig_dir) + mkdir(fig_dir); +end +all_fig_dir = sprintf('%s/All_clusters',fig_dir); +if ~exist(all_fig_dir) + mkdir(all_fig_dir); +% else +% rmdir(all_fig_dir,'s') % clear figures folder if it already exists +% mkdir(all_fig_dir); +% delete(sprintf('%s/Figures/*.png',all_fig_dir)) + +end + +% load analyzer +s = dir; +for i=1:length(s) + if strfind(s(i).name,'.analyzer') + analyze_file = s(i).name; + end +end +load(sprintf('%s/%s',exp_path,analyze_file),'-mat') % load analyzer file with stimulus info +prestim = Analyzer.P.param{1}{3}; +poststim = Analyzer.P.param{2}{3}; +if poststim == 0 + poststim = .25; +end +stimtime = Analyzer.P.param{3}{3}; +totaltime = prestim+poststim+stimtime; +onset = .2; % onset time (in seconds) - this will be subtracted from the beginning of the stim period to determine evoked firing rate + +% Determine which probe was used +tmp = dir(exp_path); +possible_probes = {'A2x16_2.prb','A1x32.prb','NeuroNexus_8FCS.prb','A1x32_A48.prb'}; +for i = 1:length(tmp) + isprobename = strcmp(tmp(i).name,possible_probes); + if sum(isprobename) + probetype = find(isprobename); + end +end + +% get necessary trial types +for v = 1:length(Analyzer.loops.conds{1}.val) % for each variable + conds{v} = cellfun(@(x) x.val{v}, Analyzer.loops.conds, 'UniformOutput',false); % all possible conditions + if strcmp(Analyzer.loops.conds{1}.symbol{v},'ori') + blanks = cellfun(@(x) find(isempty(x)), conds{v}, 'UniformOutput', false); + orivar = v; + end +end +num_conds = length(conds{1}); % number of different conditions +oris = unique(cell2mat(conds{orivar})); % actual orientations (e.g. 0, 30, 60, etc.) +num_oris = length(oris); +for c = 1:num_conds + ori_trials{c} = cellfun(@(x) x.trialno, Analyzer.loops.conds{c}.repeats); % store trials from different conditions in separate columns + trial_type(ori_trials{c}) = c; % use when using ALL trials +% trials2use = ori_trials(find(ori_trials(:,c)>num_trials),c); % uncomment if you want to use only second half of experiment +% trial_type(trials2use-300) = c; +end +blank_conds = []; +for bl = 1:length(blanks) + if blanks{bl} + blank_conds = [blank_conds bl]; + end +end + +% in event that analyzer files had to be manually combined (i.e. something +% went weird in experiment) +if exist(sprintf('%s\\trial_type.mat',exp_path),'file') + clear trial_type + load(sprintf('%s\\trial_type.mat',exp_path)) +end + +if ~isempty(blank_conds) % if there were blank trials + blank_trials = ismember(trial_type,blank_conds); + visual_trials = ~ismember(trial_type,blank_conds); +else + visual_trials = ones(1,length(trial_type)); +end +save('blank_trials.mat','blank_trials') + +% get info about light parameters +% if exist(sprintf('%s\\light_params.mat',exp_path),'file') +% load(sprintf('%s\\light_params.mat',exp_path)) +% else + [all_light_hz, pulse_dur, lighttime, av_light_start] = get_lightstim_v2(exp_path,exp_type); +% end +lightconds = unique(all_light_hz); +[type,idx] = sort(all_light_hz); % sort trials by light conditions +for n = 1:length(lightconds) + trials_per_cond(n) = length(find(all_light_hz==lightconds(n))); +end +% make appropriate figure legends +if strcmp(exp_type,'trains') + for i = 2:length(lightconds) % for graphing purposes + legend_labels{i-1} = sprintf('%dHz',lightconds(i)); + end +elseif strcmp(exp_type,'intensities') + legend_labels = {'Low light','Medium light','High light'}; + full_legend_labels = {'Light OFF','Low light','Medium light','High light'}; +else + legend_labels = {'Light ON'}; +end + +%% Run CSD (if you haven't already) +% if exist(sprintf('%s\\layers2.mat',exp_path),'file') +% layers = importdata(sprintf('%s\\layers.mat',exp_path)); +% else +% IntanLFP_CSD(exp_path) +% end + +%% find running trials +load(sprintf('%s/data.mat',exp_path),'field_trials','encdA','encdB','mouse'); +if exist('encdA','var') + move_trials = Intan_digital_movement(field_trials,encdA,encdB,0); +elseif exist('mouse','var') % using optical mouse for old recordings - might want to change to encoder? + move_trials = zeros(1,size(field_trials,1)); + moveVec = move_trials; + for i = 1:size(field_trials,1) + moveVec(i) = sum(mouse(field_trials(i,1)*20:field_trials(i,2)*20)); % *20 because mouse is still in original amp_sr + end + move_trials(find(moveVec)) = 1; +end + +%% First, make array of important plots for all units +% load kilosort data +spike_times = readNPY('spike_times.npy'); +spike_times_ds = floor(spike_times/(amp_sr/1000)); % change sample #s to account for downsampling +clusters = readNPY('spike_clusters.npy'); + +% first, extract waveforms (do it only once because it's time consuming) +for n = 1:length(good_units) + load_waveforms(n) = exist(sprintf('Cluster_%s_waveforms.mat',num2str(good_units(n))),'file'); +end + +if length(find(load_waveforms)) < length(good_units) % if any waveforms are missing, reload them all + for n = 1:length(good_units) + fprintf(sprintf('Extracting waveforms for cluster %s \n',num2str(good_units(n)))) + [waveforms_microV, max_ch] = readWaveformsFromDat(sprintf('%s/amplifier.dat',exp_path),32,spike_times(find(clusters==good_units(n))),[-16 16],[],4); + save(sprintf('Cluster_%s_waveforms.mat',num2str(good_units(n))),'waveforms_microV','max_ch'); + end +end + +for n = 1:length(good_units) + + fig_title = ['Cluster: ' num2str(good_units(n))]; + clust_fig = figure('name', fig_title); %title(sprintf('Cluster %s',clusters2analyze(n))); hold on + unit = good_units(n); + unit_times = spiketimes{n}; % timestamps of unit's spikes + num_trials = length(unit_times); + + % 1) Raster plot + subplot(241) + ylim([0 num_trials]) + xlim([-prestim stimtime+poststim]) + % first, draw light pulses (Raster will go on top) + x1 = av_light_start-prestim; % when the light starts + for c = 1:length(lightconds) + start_patch = find(type==lightconds(c),1,'first')-1; + end_patch = find(type==lightconds(c),1,'last')-1; + for p = 1:(all_light_hz(idx(end_patch))) + space = 1/(all_light_hz(idx(end_patch))); + patch([x1+((p-1)*space) x1+((p-1)*space) x1+pulse_dur/1000+((p-1)*space) x1+pulse_dur/1000+((p-1)*space) x1+((p-1)*space)],[start_patch end_patch end_patch start_patch start_patch], [0.9 0.9 0.9], 'LineStyle', 'none') + end + end + for t = 1:num_trials % for each trial + tt = idx(t); + for i=1:length(unit_times{tt}) + if type(t) % if it's a light condition, make it blue + line([unit_times{tt}(i)-prestim unit_times{tt}(i)-prestim], [t-1 t]','Color','b') + else + line([unit_times{tt}(i)-prestim unit_times{tt}(i)-prestim], [t-1 t]','Color','k') + end + end + end + xlabel('Time (sec)') + ylabel('Trial #') + line([0 0], [0 num_trials]','Color','r','LineStyle','--') +% line([onset onset], [0 num_trials]','Color','r','LineStyle','--') + line([stimtime stimtime], [0 num_trials]','Color','r','LineStyle','--') + for ii = 1:length(unique(type)) + line([-prestim stimtime+poststim], [trials_per_cond(ii)*(ii-1) trials_per_cond(ii)*(ii-1)], 'Color','b','LineStyle','--') + end + title('Raster plot') + + % 2) PSTH + binsize = .025; % in seconds + edges = [0:binsize:totaltime-binsize]; + psth = make_psth(binsize,edges,visual_trials(1:num_trials),spiketimes{n},all_light_hz); + if ~isempty(blank_conds) + psth_blanks = make_psth(binsize,edges,blank_trials(1:num_trials),spiketimes{n},all_light_hz); + else + psth_blanks = []; + end + + subplot(242) +% edges_stim = [-prestim:step:(stimtime+poststim-step)]'; % x signifies the timepoint of the START of the bin + edges_stim = [-prestim:binsize:(stimtime+poststim-binsize)]'; % x signifies the timepoint of the START of the bin + for c = 1:size(psth,2) + plot(edges_stim,psth(:,c),'color',color_mat(c,:),'linewidth',2) + hold on + end +% plot(edges_stim,psth(:,1),'k','linewidth',2) +% hold on +% plot(edges_stim,psth(:,2),'b','linewidth',2) + +% xlim([-prestim stimtime+poststim-binsize]) % because points mark the START of the bin + xlim([-prestim stimtime+poststim-binsize]) % because points mark the START of the bin + set(gca,'XMinorTick','on') + yax = get(gca,'YLim'); + line([0 0], [0 yax(2)]','Color','r','LineStyle','--') + line([stimtime stimtime], [0 yax(2)]','Color','r','LineStyle','--') + xlabel('Time (sec)') + ylabel('spikes/sec','Fontsize',12) +% leg = legend(full_legend_labels); + title('PSTH') + xx = [x1 x1 x1+pulse_dur x1+pulse_dur x1]; + yy = [0 yax(2) yax(2) 0 0]; + patch(xx, yy, -1 * ones(size(xx)), [0.9 0.9 0.9], 'LineStyle', 'none') + + % 3) PSTH - Blanks + subplot(243) + + if ~isempty(blank_conds) + plot(edges_stim,psth_blanks(:,1),'k','linewidth',2) + hold on + plot(edges_stim,psth_blanks(:,2),'b','linewidth',2) + xlim([-prestim stimtime+poststim-binsize]) % because points mark the START of the bin + set(gca,'XMinorTick','on') + yax = get(gca,'YLim'); + line([0 0], [0 yax(2)]','Color','r','LineStyle','--') + line([stimtime stimtime], [0 yax(2)]','Color','r','LineStyle','--') + xlabel('Time (sec)') + ylabel('spikes/sec','Fontsize',12) +% leg = legend('Light OFF', sprintf('Light (%s)',legend_labels{1})); + title('PSTH - Blanks') + xx = [x1 x1 x1+pulse_dur x1+pulse_dur x1]; + yy = [0 yax(2) yax(2) 0 0]; + patch(xx, yy, -1 * ones(size(xx)), [0.9 0.9 0.9], 'LineStyle', 'none') + end + + % either zoomed PSTH, or size tuning plot + subplot(244) + + if strcmp(exp_type,'size') + elseif find(strcmp(Analyzer.loops.conds{1}.symbol,'mask_radius')) % TEMP - if no blank trials, plot size tuning instead + sizevar = find(strcmp(Analyzer.loops.conds{1}.symbol,'mask_radius')); + sizes = unique(cell2mat(conds{sizevar})); % actual orientations (e.g. 0, 30, 60, etc.) + num_sizes = length(sizes); + for i = 1:length(lightconds) + for o = 1:length(sizes) + which_sizetrials = find(ismember(trial_type,find(cell2mat(conds{sizevar})==sizes(o)))); % indices of trials at a particular orientation + which_light_sizetrials = intersect(which_sizetrials,find(all_light_hz == lightconds(i))); % and in diff light conditions + [spikerate_ev_bysize(i,o), spikerateSE_ev_bysize(i,o)] = calc_firing_rates(spikes_ev(:,n),which_light_sizetrials,lighttime); + end + end + + % normalize firing rates +% if strcmp(normalizing,'blank') +% norm_spikerate_size = spikerate_ev_bysize - repmat(spikerate_blank(n,:)',1,length(sizes)); +% elseif strcmp(normalizing,'prestim') +% norm_spikerate_size = spikerate_ev_bysize - repmat(spikerate_prestim(n,:)',1,length(sizes)); +% else +% norm_spikerate_size = spikerate_ev_bysize; +% end + norm_spikerate_size = spikerate_ev_bysize./repmat(max(spikerate_ev_bysize,[],2),1,length(sizes)); % normalize to the peak response in each condition + SE_transform_size = spikerate_ev_bysize./spikerateSE_ev_bysize; % get relationship b/w FR and SE to adjust SEs for normalized FRs + norm_spikerateSE_size = spikerateSE_ev_bysize./SE_transform_size; + + shadedErrorBar(sizes,norm_spikerate_size(1,:),norm_spikerateSE_size(1,:),{'Color',color_mat(1,:),'linewidth',2},1); + hold on + shadedErrorBar(sizes,norm_spikerate_size(end,:),norm_spikerateSE_size(end,:),{'Color',color_mat(end,:),'linewidth',2},1); + ylabel('Normalized Firing rate (Hz)') + xlabel('size (degrees)') + xlim([0 max(sizes)]) + ylim([0 1]) + set(gca,'XTick',sizes(1:2:end)); + yax = get(gca,'YLim'); + title('Size tuning during sustained stimulus') +% legend('Light OFF', sprintf('Light (%s)',legend_labels{end}),'Location','SouthEast'); + + else + + % first, draw light pulses (Raster will go on top) + for c = 1:length(lightconds) + start_patch = find(type==lightconds(c),1,'first')-1; + end_patch = find(type==lightconds(c),1,'last')-1; + for p = 1:(all_light_hz(idx(end_patch))) + space = 1/(all_light_hz(idx(end_patch))); + patch([x1+((p-1)*space) x1+((p-1)*space) x1+pulse_dur/1000+((p-1)*space) x1+pulse_dur/1000+((p-1)*space) x1+((p-1)*space)],[start_patch end_patch end_patch start_patch start_patch], [0.9 0.9 0.9], 'LineStyle', 'none') + end + end + for t = 1:num_trials % for each trial + tt = idx(t); + for i=1:length(unit_times{tt}) + if type(t) % if it's a light condition, make it blue + line([unit_times{tt}(i)-prestim unit_times{tt}(i)-prestim], [t-1 t]','Color','b') + else + line([unit_times{tt}(i)-prestim unit_times{tt}(i)-prestim], [t-1 t]','Color','k') + end + end + end + ylim([0 num_trials]) + xlim([.4 .8]) + set(gca,'XMinorTick','on') + xlabel('Time (sec)') + ylabel('Trial #') + for ii = 1:length(unique(type)) + line([.4 1], [trials_per_cond(ii)*(ii-1) trials_per_cond(ii)*(ii-1)], 'Color','b','LineStyle','--') + end + title('Raster plot (zoomed in)') + + + + end + + % 5) Running vs. stationary plot + subplot(245) + runbar = bargraph([spikerate_run(n,:); spikerate_stat(n,:)],... + [spikerateSE_run(n,:); spikerateSE_stat(n,:)]); + set(get(gca,'YLabel'),'String','Mean FR (spikes/s)','Fontsize',12) + set(gca,'XTicklabel','Running| Stationary') + for i = 1:length(lightconds) + if i == length(lightconds) + set(runbar(i),'FaceColor',color_mat(end,:),'EdgeColor',color_mat(end,:)); % make sure last lightcond is bright blue + else + set(runbar(i),'FaceColor',color_mat(i,:),'EdgeColor',color_mat(i,:)); + end + end + legend('Light OFF',legend_labels) + title('Firing rate - running vs. stationary') + legend('off') + + % 4) Firing rates - Bar plot + subplot(246) + FR = [spikerate_prestim(n,:); spikerate_onset(n,:); spikerate_ev(n,:)]; + SE = [spikerateSE_prestim(n,:); spikerateSE_onset(n,:); spikerateSE_ev(n,:)]; + if ~isempty(blank_conds) + FR = [FR; spikerate_blank(n,:)]; + SE = [SE; spikerateSE_blank(n,:)]; + xcondslabel = 'Prestim| Onset| Evoked| Blanks'; + else + xcondslabel = 'Prestim| Onset| Evoked'; + end + evokedbar = bargraph(FR,SE); + set(get(gca,'YLabel'),'String','Mean FR (spikes/sec)','Fontsize',12) + set(gca,'XTicklabel',xcondslabel) + for i = 1:length(lightconds) + if i == length(lightconds) + set(evokedbar(i),'FaceColor',color_mat(end,:),'EdgeColor',color_mat(end,:)); % make sure last lightcond is bright blue + else + set(evokedbar(i),'FaceColor',color_mat(i,:),'EdgeColor',color_mat(i,:)); + end + end + legend('Light OFF',legend_labels) + title('Firing rate') + legend('off') + + % 5) Tuning Curve (evoked FR) + % calculate firing rates by light and orientation conditions + trialsperori = sum(visual_trials)/length(oris); + trialsperoricond = trialsperori/length(lightconds); + trialsbyori = nan(length(lightconds),trialsperoricond,length(oris)); + + for i = 1:length(lightconds) + for o = 1:length(oris) + which_oritrials = find(ismember(trial_type,find(cell2mat(conds{orivar})==oris(o)))); % indices of trials at a particular orientation + which_light_oritrials = intersect(which_oritrials,find(all_light_hz == lightconds(i))); + which_oritrials_run = intersect(which_oritrials,find(move_trials)); + which_oritrials_norun = intersect(which_oritrials,find(~move_trials)); + which_light_oritrials_run = intersect(which_oritrials_run,find(all_light_hz == lightconds(i))); % and in diff light conditions + which_light_oritrials_norun = intersect(which_oritrials_norun,find(all_light_hz == lightconds(i))); % and in diff light conditions + if length(which_light_oritrials) < trialsperoricond % if there are unequal numbers of trials per condition + missing_trials = trialsperoricond - length(which_light_oritrials); % add the mean FR of the trials that there are as pseudo-trials + add_trials = repmat(mean(spikes_ev(which_light_oritrials,n)./lighttime),missing_trials,1); + fprintf(sprintf('Lightcond%d ori%d missing %d trial(s) - adding fake trials for Hotellings test\n',i,o,missing_trials)) + elseif length(which_light_oritrials) > trialsperoricond + toomany_trials = length(which_light_oritrials) - trialsperoricond; + which_light_oritrials = which_light_oritrials(1:trialsperoricond); % if too many trials, drop the last one(s) + add_trials = []; + fprintf(sprintf('Lightcond%d ori%d has %d too many trial(s) - dropping the last one(s) for Hotellings test\n',i,o,toomany_trials)) + else + add_trials = []; + end + trialsbyori(i,:,o) = [spikes_ev(which_light_oritrials,n)./lighttime; add_trials]; % for T2Hot1 - using all trials regardless of running + [spikerate_ev_bycond_run(i,o), spikerateSE_ev_bycond_run(i,o)] = calc_firing_rates(spikes_ev(:,n),which_light_oritrials_run,lighttime); + [spikerate_ev_bycond_norun(i,o), spikerateSE_ev_bycond_norun(i,o)] = calc_firing_rates(spikes_ev(:,n),which_light_oritrials_norun,lighttime); +% spikes = count_spikes(spiketimes{n},prestim+prelight,prestim+prelight+.25); +% [spikerate_ev_bycond(i,o), spikerateSE_ev_bycond(i,o)] = calc_firing_rates(spikes,which_light_oritrials,.25); + end + end + + for i = 1:length(lightconds) + for o = 1:length(oris)/2 + tuning_curve_nodir(:,o) = mean([trialsbyori(i,:,o)' trialsbyori(i,:,o+length(oris)/2)'],2); % average FRs of same orientations but different directions in NO LIGHT condition + end + if T2Hot1(tuning_curve_nodir,0.05) < .05 + tuned_cell(n,i) = 1; + else + tuned_cell(n,i) = 0; + end + end + + + % normalize firing rates + if strcmp(normalizing,'blank') + norm_spikerate_ev = spikerate_ev_bycond_norun - repmat(spikerate_blank(n,:)',1,length(oris)); % stationary trials + norm_spikerateSE_ev = spikerateSE_ev_bycond_norun; + elseif strcmp(normalizing,'prestim') + norm_spikerate_ev = spikerate_ev_bycond_norun - repmat(spikerate_prestim(n,:)',1,length(oris)); + norm_spikerateSE_ev = spikerateSE_ev_bycond_norun; + else + norm_spikerate_ev = spikerate_ev_bycond_norun; + norm_spikerateSE_ev = spikerateSE_ev_bycond_norun; + end +% norm_spikerate_ev = spikerate_ev_bycond_norun./repmat(max(spikerate_ev_bycond_norun,[],2),1,length(oris)); % normalize to the peak response in each condition +% norm_spikerate_ev(isnan(norm_spikerate_ev)) = 0; +% SE_transform = spikerate_ev_bycond_norun./spikerateSE_ev_bycond_norun; % get relationship b/w FR and SE to adjust SEs for normalized FRs +% norm_spikerateSE_ev = norm_spikerate_ev./SE_transform; +% norm_spikerateSE_ev(isnan(norm_spikerateSE_ev)) = 0; +% +% norm_spikerate_ev_run = spikerate_ev_bycond_run./repmat(max(spikerate_ev_bycond_run,[],2),1,length(oris)); % normalize to the peak response in each condition +% norm_spikerate_ev_run(isnan(norm_spikerate_ev_run)) = 0; +% SE_transform_run = spikerate_ev_bycond_run./spikerateSE_ev_bycond_run; % get relationship b/w FR and SE to adjust SEs for normalized FRs +% norm_spikerateSE_ev_run = norm_spikerate_ev_run./SE_transform_run; + + + + subplot(247) + shadedErrorBar(oris,norm_spikerate_ev(1,:),norm_spikerateSE_ev(1,:),{'Color',color_mat(1,:),'linewidth',2},1); % plot ori tuning in NO RUN trials + hold on + shadedErrorBar(oris,norm_spikerate_ev(2,:),norm_spikerateSE_ev(2,:),{'Color',color_mat(2,:),'linewidth',2},1); + + ylabel('Normalized Firing rate (Hz)') + xlabel('Orientation (degrees)') + xlim([0 max(oris)]) +% ylim([0 1.1]) + set(gca,'XTick',oris(1:2:end)); + yax = get(gca,'YLim'); + title('Orientation tuning during sustained stimulus') +% legend('Light OFF', sprintf('Light (%s)',legend_labels{end}),'Location','SouthEast'); + + + % 6) Plot waveforms + unitname = good_units(n); + subplot(248) +% [waveforms_microV{n},t2p(n),max_ch(n)] = phy_waveforms(unitname,probetype,amp_sr); +% plot([0:size(waveforms_microV{n},2)-1]/div,waveforms_microV{n}','LineWidth',2); + load(sprintf('Cluster_%s_waveforms.mat',num2str(good_units(n)))); + t = linspace(0,(size(waveforms_microV,1)-1)/20,size(waveforms_microV,1)); + plot(t,waveforms_microV,'LineWidth',2); + xlim([0 max(t)]) + hold on + title(sprintf('Average waveform of spikes (Max ch: %d)',max_ch)) + ylabel('Amplitude (uV)') + xlabel('Time (ms)') +% layers = importdata(sprintf('%s\\layers.mat',exp_path)); +% unit_layer(n) = layers(max_ch(n)); + + % get unit layer +% layers(26:30) = 5.5; +% unit_layer(n) = layers(max_ch); + + % save figs + cd(all_fig_dir) + xSize = 24; ySize = 11; + xLeft = (21-xSize)/2; yTop = (30-ySize)/2; + set(gcf,'PaperPosition',[xLeft yTop xSize ySize]) + set(gcf,'Position',[0 0 xSize*50 ySize*50]) +% if unit_layer(n) == 5 +% layer_name = 'L5A'; +% elseif unit_layer(n) == 5.5 +% layer_name = 'L5B'; +% elseif unit_layer(n) == 2.5 +% layer_name = 'L23'; +% else +% layer_name = sprintf('L%s',num2str(unit_layer(n))); +% end + layer_name = 'LP'; + save_clust_name= sprintf('%s_Cluster_%d_%s',upper(unittype),good_units(n),layer_name); + print(clust_fig,'-dpng',save_clust_name) + print2eps(save_clust_name,clust_fig) +% export_fig (save_clust_name, '-png','-r600','-opengl') + +% % test for significant visual modulation +% onset_spikes_lightoff = spikes_onset(intersect(find(all_light_hz == lightconds(1)),find(visual_trials)),n); +% onset_spikes_lighton = spikes_onset(intersect(find(all_light_hz == lightconds(2)),find(visual_trials)),n); +% ev_spikes_lightoff = spikes_ev(intersect(find(all_light_hz == lightconds(1)),find(visual_trials)),n); +% ev_spikes_lighton = spikes_onset(intersect(find(all_light_hz == lightconds(2)),find(visual_trials)),n); + +% kruskal-wallis test to test for significant light- and visual-modulation + if kruskalwallis([spikes_onset(find(visual_trials(1:num_trials)),n) spikes_prestim_onsettime(find(visual_trials(1:num_trials)),n)],[],'off') < .05 + vis_cell(n) = 1; + else + vis_cell(n) = 0; + end + ev_spikes_lightoff = spikes_ev(find(~all_light_hz),n); + ev_spikes_lighton = spikes_ev(find(all_light_hz==lightconds(2)),n); % currently using second light condition! + ev_spikes = [ev_spikes_lightoff' ev_spikes_lighton']; + ev_spikes_group = [ones(1,length(ev_spikes_lightoff)) 2*ones(1,length(ev_spikes_lighton))]; +% if length(ev_spikes_lightoff) ~= length(ev_spikes_lighton) +% min_len = min(length(ev_spikes_lightoff),length(ev_spikes_lighton)); +% ev_spikes_lightoff = ev_spikes_lightoff(1:min_len); +% ev_spikes_lighton = ev_spikes_lighton(1:min_len); +% end +% if kruskalwallis([ev_spikes_lightoff ev_spikes_lighton],[],'off') < .05 % currently testing against 2nd light condition + if kruskalwallis(ev_spikes,ev_spikes_group,'off') < .05 + light_cell(n) = 1; + else + light_cell(n) = 0; + end + + % COME BACK TO THIS +% %determine statistical significance of orientation tuning +% if length(deg) == 8 +% raw_new = ([ mean([raw_lightoff_sep{1}(1:length(c)); raw_lightoff_sep{5}]); mean([raw_lightoff_sep{2}; raw_lightoff_sep{6}]); mean([raw_lightoff_sep{3}; raw_lightoff_sep{7}]); mean([raw_lightoff_sep{4}; raw_lightoff_sep{8}]) ]) - spontfr_mean; +% else +% raw_new = ([ mean([raw_lightoff_sep{1}(1:length(c)); raw_lightoff_sep{7}]); mean([raw_lightoff_sep{2}; raw_lightoff_sep{8}]); mean([raw_lightoff_sep{3}; raw_lightoff_sep{9}]); mean([raw_lightoff_sep{4}; raw_lightoff_sep{10}]); mean([raw_lightoff_sep{5}; raw_lightoff_sep{11}]); mean([raw_lightoff_sep{6}; raw_lightoff_sep{12}]) ]) - spontfr_mean; +% end +% +% P = T2Hot1(raw_new', 0.05); + + % save data + good_units_results(n).clustnum = unit; +% good_units_results(n).layer = unit_layer(n); + good_units_results(n).peakchannel = max_ch; + good_units_results(n).visuallymodulated = vis_cell(n); + good_units_results(n).lightmodulated = light_cell(n); + good_units_results(n).tuned = tuned_cell(n,:); + good_units_results(n).PSTH_visual = psth; + if ~isempty(blank_conds) + good_units_results(n).PSTH_blank = psth_blanks; + end + good_units_results(n).FR.label = {'Light OFF','Light ON'}; + good_units_results(n).FR.prestim = FR(1,:); % NO LIGHT ALWAYS BEFORE LIGHT! + good_units_results(n).FR.onset = FR(2,:); + good_units_results(n).FR.evoked = FR(3,:); + if ~isempty(blank_conds) + good_units_results(n).FR.blanks = FR(4,:); + end + good_units_results(n).orituning.oris = oris; + good_units_results(n).orituning.FR = spikerate_ev_bycond_norun; + good_units_results(n).orituning.SE = spikerateSE_ev_bycond_norun; + good_units_results(n).orituning.FRcorrected = norm_spikerate_ev; + good_units_results(n).orituning.SEcorrected = norm_spikerateSE_ev; + if find(strcmp(Analyzer.loops.conds{1}.symbol,'mask_radius')) + good_units_results(n).sizetuning.sizes = sizes; + good_units_results(n).sizetuning.FR = spikerate_ev_bysize; + good_units_results(n).sizetuning.SE = spikerateSE_ev_bysize; + good_units_results(n).sizetuning.FRcorrected = norm_spikerate_size; + good_units_results(n).sizetuning.SEcorrected = norm_spikerateSE_size; + end +% good_units_results(n).trough2peak = t2p(n); + +% good_units_results(n).slope = poly(n); + good_units_results(n).waveforms = waveforms_microV; + + close all + + cd(exp_path) +end + +save(strcat(exp_name,'_results.mat'),'good_units_results') +cd(exp_dir) % also save to cumulative experiment folder +save(strcat(exp_name,'_results.mat'),'good_units_results') + + + diff --git a/Intancode_Megan/kilo_spike_analysis.m b/Intancode_Megan/kilo_spike_analysis.m new file mode 100644 index 0000000..d38bf9d --- /dev/null +++ b/Intancode_Megan/kilo_spike_analysis.m @@ -0,0 +1,285 @@ +function kilo_spike_analysis(exp_path,unittype,exp_type) + +% modified from phy_spike_analysis_v2 to make more efficient and to + % separate out graphing - MAK 3/14/16 + +% Takes in data from Intan, analyzer file, and phy .kwik file to look at +% spike times and spike frequency from isolated single and multi unit +% clusters +% unittype = 'su' or 'mu' (single or multi units) +% pulse_dur = duration of light (in sec) + +% 6/7/16 - removed prelight and postlight parameters, replaced with +% av_light_start from get_lightstim.m +% 7/17 - changed to get_lightstim_v2.m + +cd(exp_path) +if exist(sprintf('%s/data.mat',exp_path),'file') + load(sprintf('%s/data.mat',exp_path)) % data from intanphy2matlab.m +else + intanphy2matlab_v2(exp_path); % data from intanphy2matlab.m + load(sprintf('%s/data.mat',exp_path)) % data from intanphy2matlab.m +end + + +% trials - num_trials x 2 matrix of trial start and end times (in seconds) +% field_trials - trial num x 2 matrix of trial start and end samples (in + % 1000 Hz sampling rate) - starts from 1! +% time_index - vector of time stamps of each sample (in seconds), with 1000 + % samples per second - starts from 0! +% amp_sr - original amplifier sampling rate +% epoc - vector of 1s and 0s indicating whether each sample was part of a + % trial (1) or not (0). Still in original sampling rate (amp_sr) +% mmvt - vector of 1s and 0s indicating whether mouse was running (1) or + % not (0) at time of sample. Still in original sampling rate (amp_sr) +% encd - vector of analog output from movement encoder. Still in original + % sampling rate (amp_sr) +% LED - is 0 if not an optogenetics experiment, but otherwise, vectors of + % whether LED was on (1) or off (0) +% re - vector for the timestamps (rising phase of photodiode signal). you + % need to remove the first 2 and the last 2 timestamps. Timestamps + % signify the end of a four second black to gray period. +% Photo - vector of analog output from photodiode. In 1000Hz sampling rate + + +% load kilosort data +spike_times = readNPY('spike_times.npy'); +spike_times = floor(spike_times/(amp_sr/1000)); % change sample #s to account for downsampling +clusters = readNPY('spike_clusters.npy'); + +% load analyzer +s = dir; +for i=1:length(s) + if strfind(s(i).name,'.analyzer') + analyze_file = s(i).name; + end +end +load(sprintf('%s/%s',exp_path,analyze_file),'-mat') % load analyzer file with stimulus info +prestim = Analyzer.P.param{1}{3}; +poststim = Analyzer.P.param{2}{3}; +if poststim == 0 + extra = .25*1000; % add extra samples for pseudo-poststim period +else + extra = 0; +end +stimtime = Analyzer.P.param{3}{3}; +totaltime = prestim+poststim+stimtime; +onset = .2; % onset time (in seconds) - this will be subtracted from the beginning of the stim period to determine evoked firing rate + + +% optogenetics? +if sum(LED) > 0 + light_exp = 1; % if using optogenetics +else + light_exp = 0; +end + +% downsample +LN = length(epoc); +div = amp_sr/1000; +zx = 1:div:LN; +izx = floor(zx); +epoch = epoc(izx); +% move = mmvt(izx); +% encode = encd(izx); +if light_exp + light = LED(izx); +end + +% extract trial types +num_trials = size(trials,1); +for v = 1:length(Analyzer.loops.conds{1}.val) % for each variable + conds{v} = cellfun(@(x) x.val{v}, Analyzer.loops.conds, 'UniformOutput',false); % all possible conditions + if strcmp(Analyzer.loops.conds{1}.symbol{v},'ori') + blanks = cellfun(@(x) find(isempty(x)), conds{v}, 'UniformOutput', false); + orivar = v; + end +end +num_conds = length(conds{1}); % number of different conditions +oris = unique(cell2mat(conds{orivar})); % actual orientations (e.g. 0, 30, 60, etc.) +num_oris = length(oris); +trial_type = zeros(1,num_trials); +for c = 1:num_conds + ori_trials{c} = cellfun(@(x) x.trialno, Analyzer.loops.conds{c}.repeats); % store trials from different conditions in separate columns + trial_type(ori_trials{c}) = c; % use when using ALL trials +% trials2use = ori_trials(find(ori_trials(:,c)>num_trials),c); % uncomment if you want to use only second half of experiment +% trial_type(trials2use-300) = c; +end + +% in event that analyzer files had to be manually combined (i.e. something +% went weird in experiment) +if exist(sprintf('%s/trial_type.mat',exp_path),'file') + clear trial_type + load(sprintf('%s/trial_type.mat',exp_path)) +end + +blank_conds = []; +for bl = 1:length(blanks) + if blanks{bl} + blank_conds = [blank_conds bl]; + end +end +% isolate blank trials +if ~isempty(blank_conds) % if there were blank trials + blank_trials = find(ismember(trial_type,blank_conds)); + visual_trials = find(~ismember(trial_type,blank_conds)); +else + visual_trials = 1:length(trial_type); +end +% find light trials +if light_exp + lightvar = find(strcmp(Analyzer.loops.conds{1}.symbol,'light_bit')); + diff_lightconds = unique(cellfun(@(x) x.val{lightvar}, Analyzer.loops.conds)); + num_lightconds = length(find(diff_lightconds)); + all_light_trials = zeros(1,num_trials); + for cc = 1:num_lightconds % for each condition WITH light stimulation + all_light_conds(cc,:) = find(cellfun(@(x) x.val{lightvar}, Analyzer.loops.conds)==diff_lightconds(cc+1)); + all_light_trials(find(ismember(trial_type,all_light_conds(cc,:))))=cc; + end + nolight_conds = find(cellfun(@(x) x.val{lightvar}, Analyzer.loops.conds)==0); + light_conds = sort(all_light_conds(:)); + light_trials = find(ismember(trial_type,light_conds)); + nolight_trials = find(~ismember(trial_type,light_conds)); + + % The following also works for identifying light trials IF the LED + % signal was digital +% for t = 1:num_trials % for each trial +% if sum(light(field_trials(t,1):field_trials(t,2))) % if LED turned on during trial +% light_on(t) = 1; +% else +% light_on(t) = 0; +% end +% end +% light_trials = find(light_on); + + % get info about light parameters + [all_light_hz, pulse_dur, lighttime, av_light_start] = get_lightstim_v2(exp_path,exp_type); + lightconds = unique(all_light_hz); + [type,idx] = sort(all_light_hz); % sort trials by light conditions +end + +% find trials when mouse was running +if exist('encdA','var') + move_trials = Intan_digital_movement(field_trials,encdA,encdB,0); +elseif exist('mouse','var') % using optical mouse for old recordings - might want to change to encoder? + move_trials = zeros(1,size(field_trials,1)); + moveVec = move_trials; + for i = 1:size(field_trials,1) + moveVec(i) = sum(mouse(field_trials(i,1)*20:field_trials(i,2)*20)); % *20 because mouse is still in original amp_sr + end + move_trials(find(moveVec)) = 1; +end + +prestim_samps = prestim*1000; +poststim_samps = poststim*1000; +stimtime_samps = stimtime*1000; +lighttime_samps = lighttime*1000; +spike_times = spike_times + 1; % has to be +1 because spike_times starts at 0, but the min possible field_trials value could be 1 + +fid = fopen('cluster_groups.csv'); +% read column headers +C_text = textscan(fid, '%s', 1, 'delimiter', ','); +% read group info +grp_dat = textscan(fid, '%f %s', 'delimiter', ','); +fclose(fid); +units = grp_dat{1}; % cluster numbers +cluster_group = grp_dat{2}; % 'good', 'noise', etc. +num_units = length(units); + +% determine which group each cluster belongs to (good, MUA, etc.) +single_units = units(find(strcmp(cluster_group,'good'))); +multi_units = units(find(strcmp(cluster_group,'mu'))); % CHECK + +%% extract spike times for units of interest (su or mu) +if strcmp(unittype,'su') + good_units = single_units; +elseif strcmp(unittype,'mu') + good_units = multi_units; +else + error('Didnt specify singleunits (su) or multiunits (mu)') +end + +% if units to analyze are indicated in text file +if exist(sprintf('%s/good_units.txt',exp_path),'file') + good_units = load(sprintf('%s/good_units.txt',exp_path)); +end + +% get each cluster's spikes by trial, and count +spiketimes = cell(1,length(good_units)); +spikes_prestim = nan(num_trials,length(good_units)); +spikes_ev = spikes_prestim; +spikes_onset = spikes_prestim; +spikes_all = spikes_prestim; +for n = 1:length(good_units) + unit = find(units == good_units(n)); + unit_times = spike_times(find(clusters==good_units(n))); % timestamps of unit's spikes + spiketimes{n} = spikes_by_trial(unit_times,field_trials,extra,time_index); + + % count spikes during prestim, stim, poststim, and onset periods + for t = 1:length(spiketimes{n}) + spikes_all(t,n) = length(spiketimes{n}{t}); + spikes_prestim(t,n) = length(find(spiketimes{n}{t}=av_light_start)&(spiketimes{n}{t}<=av_light_start+lighttime))); + spikes_onset(t,n) = length(find((spiketimes{n}{t}>=prestim)&(spiketimes{n}{t}=prestim-onset)&(spiketimes{n}{t}>prestim-onset)