align_cd.m 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. function [offset,inc_t,x,y]=align_cd(ev, ts,val,varargin)
  2. % [offset,inc_t,x,y]=align_cd(ev, ts,val, varargin)
  3. % pairs={'pre' 3;...
  4. % 'post' 3;...
  5. % 'binsz' 0.005;...
  6. % 'meanflg' 0;...
  7. % 'krn' 0.25;...
  8. % 'pre_mask', -inf;...
  9. % 'post_mask',+inf;...
  10. % 'do_plot' false;...
  11. % 'max_iter' 50;...
  12. % 'max_peak' 1e10;...
  13. %
  14. pre = 3;
  15. post = 3;
  16. binsz = 0.005;
  17. % pre_mask = -inf;
  18. % post_mask = +inf;
  19. max_offset = 1;
  20. do_plot = false;
  21. max_iter = 50;
  22. max_peak = [];
  23. var_thres = 0.05;
  24. utils.overridedefaults(who,varargin)
  25. % The masking is not currently implemented because xcorr cannot handle Nan.
  26. % if isscalar(pre_mask)
  27. % pre_mask=zeros(1,numel(ev))+pre_mask;
  28. % elseif numel(pre_mask)~=numel(ev)
  29. % fprintf(1,'numel(pre_mask) must equal num ref events or be scalar');
  30. % return;
  31. % end
  32. % if isscalar(post_mask)
  33. % post_mask=zeros(1,numel(ev))+post_mask;
  34. % elseif numel(post_mask)~=numel(ev)
  35. % fprintf(1,'numel(post_mask) must equal num ref events or be scalar');
  36. % return;
  37. % end
  38. old_var=10e10;
  39. done=0;
  40. offset=zeros(size(ev));
  41. if do_plot
  42. clf;ax=axes;
  43. hold on;
  44. end
  45. cnt=1;
  46. inc_t=ones(size(ev))==1;
  47. %% Calculate the mean and ci of the
  48. while ~done
  49. [y,x]=stats.cdraster(ev+offset,ts(:),val(:),'pre',pre,'post',post,'bin',binsz);
  50. if cnt==1 && ~isempty(max_peak)
  51. thresh=prctile(y(:),max_peak);
  52. else
  53. thresh=+inf;
  54. end
  55. y(abs(y)>thresh)=0;
  56. y(isnan(y))=0;
  57. % [y x]=maskraster(x,y,pre_mask(ref),post_mask(ref));
  58. ymn = nanmean(y(inc_t,:));
  59. yst = stats.nanstderr(y(inc_t,:));
  60. if do_plot
  61. plot(ax,x,ymn-yst,x,ymn+yst,'Color',[1-0.2*cnt, 0 ,0]);
  62. drawnow
  63. end
  64. for tx=1:numel(ev)
  65. if inc_t(tx)
  66. [xcy,xcx]=xcorr(y(tx,:)-nanmean(y(tx,:)),ymn-nanmean(ymn));
  67. [v,peakx]=max(xcy);
  68. offset(tx)=offset(tx)+xcx(peakx)*binsz;
  69. if abs(offset(tx))>max_offset
  70. inc_t(tx)=false;
  71. end
  72. end
  73. end
  74. new_var=sum(nanvar(y));
  75. var_diff=(old_var-new_var)/old_var;
  76. if do_plot
  77. fprintf('Variance improved by %2.3g %% of total variance\n',100*var_diff);
  78. end
  79. old_var=new_var;
  80. cnt=cnt+1;
  81. if abs(var_diff)<var_thres || cnt>max_iter
  82. done=true;
  83. end
  84. end