plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
HelmchenLabSoftware/OCIA-master
preprocLickData.m
.m
OCIA-master/caImgAnalysis/utils/preprocLickData.m
3,089
utf_8
3f4c637d9aa39cc0464e87a71cae95d2
function lickRateUS = preprocLickData(lickDataCell, lickThreshHard, sampRate, doPlots) lickRateBinSize = 0.05; % in s (e.g. 0.05 for 50 ms bins) for n = 1 : numel(lickDataCell); lickV = lickDataCell{n}; t = (1 : numel(lickV)) ./ sampRate; try % filter the lick vector lickVfilt = filterLickVector(lickV, doPlots); lickVfilt(lickVfilt < lickThreshHard) = 0; % onsets for each 'lick' lickOn = zeros(1, numel(lickV)); for m = 2 : numel(lickOn) if lickVfilt(m) && ~lickVfilt(m - 1) lickOn(m) = 1; end; end; % 'lick rate' based on onsets lickTimes = t(lickOn > 0); tt = t(1) : lickRateBinSize : t(end); [lickRate, tt] = instantfr(lickTimes, tt); lickRateUS = interp1(tt, lickRate, t); catch err; o(' Error while pre-processing lick data : %s.', err.identifier, 0, 0); % fill with nans lickRateUS = nan(size(lickV)); end; if doPlots; figure('Name', sprintf('Trial %1.0f', n), 'NumberTitle', 'off') plot(t, lickV, 'k', 'linewidth', 2), hold on plot(t, lickVfilt, 'r--', 'linewidth', 1.5) plot(tt, lickRate ./ 1000, 'y--', 'linewidth', 1.5) plot(t, lickRateUS ./ 1000, 'b--', 'linewidth', 1.5) xlabel('Time (s)'), legend({'raw', 'filt', 'rate/1000', 'rateUS/1000'}) end; end; end function out = filterLickVector(in, doPlots) in = abs(in); % lick data histogram [count,xout] = hist(in,sqrt(numel(in))); % optional: plot histogram if doPlots figure('Name','Histogram','NumberTitle','off') plot(xout,count,'k'), hold on end % fit double-peaked gaussian to histogram fObj = fit(xout',count','gauss2'); % optional: plot fit if doPlots; plot(fObj,'r--') end % pull out peaks and widths from fit peaks = [fObj.b1 fObj.b2]; width = [fObj.c1 fObj.c2]; % sort so that first peak is the more negative one [peaks,ix] = sort(peaks); width = width(ix); % width as SD width = width ./ sqrt(2); % probability of each data point based on normal distribution p = 1-normcdf(in,peaks(2),width(2)); % threshold p-value --> this will be adjusted for the number of data points pThresh = 0.001; pThresh = pThresh ./ numel(in); % threshold thresh = in; thresh(p>pThresh) = 0; % binarize thresh_bin = thresh; thresh_bin(thresh_bin>0) = 1; % discard segments smaller minSiz minSiz = 3; cc = bwconncomp(thresh_bin); for n = 1:numel(cc.PixelIdxList) if numel(cc.PixelIdxList{n})<minSiz thresh_bin(cc.PixelIdxList{n}) = 0; end end % join adjacent segments minSeparation = 50; cc = bwconncomp(thresh_bin); if numel(cc.PixelIdxList) > 1 for n = 2:numel(cc.PixelIdxList) currentSegment = cc.PixelIdxList{n}; previousSegment = cc.PixelIdxList{n-1}; if currentSegment(1)-previousSegment(end) <= minSeparation thresh_bin(previousSegment(end):currentSegment(1)) = 1; end end end thresh(~thresh_bin) = 0; out = thresh; end
github
HelmchenLabSoftware/OCIA-master
eventDetector.m
.m
OCIA-master/caImgAnalysis/utils/eventDetection/eventDetector.m
9,591
utf_8
66349ac972c2fcdf425e9e2ba5603434
function eventDetection = eventDetector(ROIStats, stim, eventDetectMethod, frameRate, psConfig, saveName) %[eventMatAllRuns, instFiringRateAllRuns, residuals, models] = testingEventDetector(ROIStats, stim, eventDetectMethod, frameRate, psConfig, saveName) % event detection function - wrapper to different event detection algorithms % input: structure created by GetRoiStats (*_RoiStats) % % % Adapted from eventDetector coded by Balazs Laurency, 2013 % Modified by A. van der Bourg, 2014 dbgLevel = 2; doStimEventRasterPlot = 1; doEventDetection = 1; %% Event detection parameters [config, V, P] = getDefaultParameters(eventDetectMethod, frameRate); %%#ok<NASGU,ASGLU> o(' #eventDetector: loading event detection parameters of default config!', 3, dbgLevel); %% Event detection % event detection on roiStats % % last row is neuropil, remove it % allDFFData(end, :) = []; % init sizes of data set nROIs = size(ROIStats, 1); nRuns = size(ROIStats, 2); nFrames = size(ROIStats{1, 1}, 2); o(' #eventDetector: variables initialized.', 3, dbgLevel); o(' #eventDetector: starting event detection ... ', 2, dbgLevel); eventDetectStartTime = tic; eventData = cell(size(ROIStats)); residuals = cell(size(ROIStats)); models = cell(size(ROIStats)); eventMatAllRuns = zeros(nROIs, nRuns * size(ROIStats{1, 1}, 2)); instFiringRateAllRuns = zeros(nROIs, nRuns* size(ROIStats{1, 1}, 2)); stimVectorAllRuns = zeros(1, nRuns * size(ROIStats{1, 1}, 2)); % outerDffData = ROIStats; nRunsWithError = 0; nTotEvents = 0; for iRun = nRuns; try startIndex = (iRun - 1) * nFrames + 1; endIndex = iRun * nFrames; eventDetect = config.EventDetect; o(' #eventDetector: run %d/%d, %d rois...', iRun, nRuns, nROIs, 4, dbgLevel); if size(stim{iRun}, 2) ~= endIndex - startIndex + 1; o(' #eventDetector: run %d/%d, %d rois: skip for bad size.', iRun, nRuns, nROIs, 1, dbgLevel); continue; end; stimVectorAllRuns(startIndex : endIndex) = stim{iRun}; eventDetect.rate = frameRate; currentEventMat = zeros(nROIs, nFrames); instFiringRate = zeros(nROIs, nFrames); if doEventDetection; %Parallel computing for multiple ROIs parfor iROI = 1 : nROIs; o(' #eventDetector: run %d/%d - roi %d/%d ...', iRun, nRuns, iROI, nROIs, 5, dbgLevel); caTrace = ROIStats{iROI, iRun}; % caTrace = mpi_BandPassFilterTimeSeries(caTrace, 1 / frameRate, bpfilter.low, bpfilter.high); %#ok<PFBNS> if isempty(caTrace); warning('eventDetector:caTraceEmpty', 'caTrace is empty!'); continue; elseif isnan(caTrace); % warning('eventDetector:caTraceNaN', 'caTrace is NaN!'); eventData{iROI, iRun} = nan(1, nFrames); %#ok<PFOUS> continue; end; switch lower(eventDetectMethod) case 'fast_oopsi' oopsiOut = fast_oopsi(caTrace, V, P); oopsiOut(oopsiOut < config.EventDetect.oopsi_thr) = 0; %#ok<PFBNS> currentEventMat(iROI, :) = oopsiOut'; eventData{iROI, iRun} = oopsiOut'; case 'peeling' % eventOut = doPeeling(eventDetect, caTrace); [~, ~, peelRes] = Peeling(caTrace, frameRate); residuals{iROI, iRun} = peelRes.peel; models{iROI, iRun} = peelRes.model; % eventCounts(iROI) = sum(peelRes.spiketrain); %%#ok<PFOUS> % residualVector(iROI) = sum(abs(eventOut.data.peel)) / length(eventOut.data.peel); currentEventMat(iROI, :) = peelRes.spiketrain; eventData{iROI, iRun} = peelRes.spiketrain; %if doExtractInstFiringRate % smoothing kernel for converting spike trains into inst. firing rate (in Hz); % sigma in units of frames (default: 1 frames) % Smoothed gauss kernel instantaneous firing % rate extraction gausskern = normpdf((1:nFrames),round(0.5*nFrames),1); APdens = conv(peelRes.spiketrain', gausskern); %Obtain the instantaneous firing rate from the %smoothed AP-density instFiringRate(iROI,:) = frameRate*APdens(round(0.5*nFrames):round(0.5*nFrames)+nFrames-1); %end; end; nEventsFound = sum(currentEventMat(iROI, :)); nTotEvents = nTotEvents + nEventsFound; o(' #eventDetector: run %d/%d - roi %d/%d done, %d event(s) found.', ... iRun, nRuns, iROI, nROIs, nEventsFound, 4, dbgLevel); end ; end; eventMatAllRuns(:, startIndex : endIndex) = currentEventMat; instFiringRateAllRuns(:, startIndex:endIndex) = instFiringRate; o(' #eventDetector: run %d/%d done.', iRun, nRuns, 3, dbgLevel); catch err; nRunsWithError = nRunsWithError + 1; %#ok<NASGU> o(' #eventDetector: problem in run %d/%d.', iRun, nRuns, 2, dbgLevel); rethrow(err); end; end; eventDetectEndTime = toc(eventDetectStartTime); % PSTraceRoi = PsPlotAnalysisCellArray(ROIStats, stim, psConfig); o(' #eventDetector: event detection done for %d runs (%d error(s), %d total events, %.2f sec).', ... nRuns, nRunsWithError, nTotEvents, eventDetectEndTime, 2, dbgLevel); if ~isempty(eventMatAllRuns) && nTotEvents > 0; o(' #eventDetector: extracting peri-stimulus events...', 3, dbgLevel); PSEventRoi = PsPlotAnalysis(eventMatAllRuns, stimVectorAllRuns, psConfig); config.PsPlotEventRoi = PSEventRoi; o(' #eventDetector: extracting peri-stimulus events done.', 2, dbgLevel); else o(' #eventDetector: no events found (%d).', nTotEvents, 1, dbgLevel); end o(' #eventDetector: moving to plotting section ...', 3, dbgLevel); %% Population stimulus event raster plot if doStimEventRasterPlot; o(' #eventDetector: plotting the peri-stimulus event raster plot ...', 2, dbgLevel); %#ok<*UNRCH> fig = plotStimEventRaster( ... 'PopRasterSinglePlot', ... % title of the plot PSEventRoi, ... % event counts around the stimulus stim{1}, ... % stimuli for extracting their 'name' psConfig.base, ... % number of frames looked before the stimulus psConfig.evoked, ... % number of frames looked after the stimulus frameRate); % frame rate % set(fig, 'WindowStyle', 'docked'); if doStimEventRasterPlot > 1; saveas(fig, sprintf('%s_EventStimRaster_%s', saveName, eventDetectMethod)); saveas(fig, sprintf('%s_EventStimRaster_%s.png', saveName, eventDetectMethod)); close(fig); end; o(' #eventDetector: plotting the peri-stimulus event raster plot done.', 2, dbgLevel); %#ok<*UNRCH> end; %% Output all variables eventDetection.eventMatAllRuns = eventMatAllRuns; eventDetection.instFiringRateAllRuns= instFiringRateAllRuns; eventDetection.residuals = residuals; eventDetection.models = models; %varargout{1} = config; end %Default parameters - optimized for OGB? function [config, V, P] = getDefaultParameters(eventDetectMethod, frameRate) amp = 12; tau = 2; onsettau = 0.01; switch lower(eventDetectMethod); case 'fast_oopsi'; config.EventDetect.amp = amp; config.EventDetect.tau = tau; config.EventDetect.onsettau = onsettau; config.EventDetect.doPlot = 0; % should be switched off config.EventDetect.lam = 0.2; % firing rate(ish) config.EventDetect.base_frames = 10; config.EventDetect.oopsi_thr = 0.3; config.EventDetect.integral_thr = 5; config.EventDetect.filter = [7 2]; config.EventDetect.minGof = 0.5; P.lam = config.EventDetect.lam; % P.gam = (1-(1/freq_ca)) / ca_tau; V.dt = 1/frameRate; V.est_gam = 1; % estimate decay time parameter (does not work) V.est_sig = 1; % estimate baseline noise SD V.est_lam = 1; % estimate firing rate V.est_a = 0; % estimate spatial filter V.est_b = 0; % estimate background fluo. V.fast_thr = 1; V.fast_iter_max = 3; case 'peeling'; V = []; P = []; config.EventDetect.optimizeSpikeTimes = 0; config.EventDetect.schmittHi = [1.75 0 3]; config.EventDetect.schmittLo = [-1 -3 0]; config.EventDetect.schmittMinDur = [0.3 0.05 3]; config.EventDetect.A1 = amp; config.EventDetect.tau1 = tau; config.EventDetect.onsettau = onsettau; config.EventDetect.optimMethod = 'none'; config.EventDetect.minPercentChange = 0.1; config.EventDetect.maxIter = 20; config.EventDetect.plotFinal = 0; case 'none'; config = []; V = []; P = []; warning('Nothing to do here! Exit ...') return; end; end
github
HelmchenLabSoftware/OCIA-master
PeelingOptimizeSpikeTimesSaturation.m
.m
OCIA-master/caImgAnalysis/utils/eventDetection/PeelingOptimizeSpikeTimesSaturation.m
4,465
utf_8
82892eced9f5fb70e0d8ad3f544df164
function [spkTout,output] = PeelingOptimizeSpikeTimesSaturation(dff,spkTin,lowerT,upperT,... ca_amp,ca_gamma,ca_onsettau,ca_rest, ca_kappas, kd, conc, dffmax, frameRate, dur, optimMethod,maxIter,doPlot) % optimization of spike times found by Peeling algorithm % minimize the sum of the residual squared % while several optimization algorithms are implemented (see below), we have only used pattern % search. Other algorithms are only provided for convenience and are not tested sufficiently. % % Henry Luetcke ([email protected]) % Brain Research Institut % University of Zurich % Switzerland spkTout = spkTin; t = (1:numel(dff))./frameRate; ca = spkTimes2FreeCalcium(spkTin,ca_amp,ca_gamma,ca_onsettau,ca_rest, ca_kappas,... kd, conc,frameRate,dur); modeltmp = Calcium2Fluor(ca,ca_rest,kd,dffmax); model = modeltmp(1:length(dff)); if doPlot figure('Name','Before Optimization') plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b') legend('DFF','Model','Residual') end residual = dff - model; resInit = sum(residual.^2); % start optimization x0 = spkTin; lbound = spkTin - lowerT; lbound(lbound<0) = 0; ubound = spkTin + upperT; ubound(ubound>max(t)) = max(t); lbound = zeros(size(spkTin)); ubound = repmat(max(t),size(spkTin)); opt_args.dff = dff; opt_args.ca_rest = ca_rest; opt_args.ca_amp = ca_amp; opt_args.ca_gamma = ca_gamma; opt_args.ca_onsettau = ca_onsettau; opt_args.ca_kappas = ca_kappas; opt_args.kd = kd; opt_args.conc = conc; opt_args.dffmax = dffmax; opt_args.frameRate = frameRate; opt_args.dur = dur; optimClock = tic; switch lower(optimMethod) case 'simulated annealing' options = saoptimset; case 'pattern search' options = psoptimset; case 'genetic' options = gaoptimset; otherwise error('Optimization method %s not supported.',optimMethod) end % options for optimization algorithms % not all options are used for all algorithms options.Display = 'off'; options.MaxIter = maxIter; options.MaxIter = Inf; options.UseParallel = 'always'; options.ObjectiveLimit = 0; options.TimeLimit = 10; % in s / default is Inf % experimental options.MeshAccelerator = 'on'; % off by default options.TolFun = 1e-9; % default is 1e-6 options.TolMesh = 1e-9; % default is 1e-6 options.TolX = 1e-9; % default is 1e-6 % options.MaxFunEvals = numel(spkTin)*100; % default is 2000*numberOfVariables % options.MaxFunEvals = 20000; options.Display = 'none'; % options.Display = 'final'; % options.PlotFcns = {@psplotbestf @psplotbestx}; % options.OutputFcns = @psoutputfcn_peel; switch lower(optimMethod) case 'simulated annealing' [x, fval , exitFlag, output] = simulannealbnd(... @(x) objectiveFunc(x,opt_args),x0,lbound,ubound,options); case 'pattern search' [x, fval , exitFlag, output] = patternsearch(... @(x) objectiveFunc(x,opt_args),x0,[],[],[],[],lbound,... ubound,[],options); case 'genetic' [x, fval , exitFlag, output] = ga(... @(x) objectiveFunc(x,opt_args),numel(x0),[],[],[],[],lbound,... ubound,[],options); end if fval < resInit spkTout = x; else disp('Optimization did not improve residual. Keeping input spike times.') end if doPlot fprintf('Optimization time (%s): %1.2f s\n',optimMethod,toc(optimClock)) fprintf('Final squared residual: %1.2f (Change: %1.2f)\n',fval,resInit-fval); spkVector = zeros(1,numel(t)); for i = 1:numel(spkTout) [~,idx] = min(abs(spkTout(i)-t)); spkVector(idx) = spkVector(idx)+1; end model = conv(spkVector,modelTransient); model = model(1:length(t)); figure('Name','After Optimization') plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b') legend('DFF','Model','Residual') end function residual = objectiveFunc(spkTin,opt_args) dff = opt_args.dff; ca_rest = opt_args.ca_rest; ca_amp = opt_args.ca_amp; ca_gamma = opt_args.ca_gamma; ca_onsettau = opt_args.ca_onsettau; ca_kappas = opt_args.ca_kappas; kd = opt_args.kd; conc = opt_args.conc; dffmax = opt_args.dffmax; frameRate = opt_args.frameRate; dur = opt_args.dur; ca = spkTimes2FreeCalcium(sort(spkTin),ca_amp,ca_gamma,ca_onsettau,ca_rest, ca_kappas,... kd, conc,frameRate,dur); modeltmp = Calcium2Fluor(ca,ca_rest,kd,dffmax); model = modeltmp(1:length(dff)); residual = dff-model; residual = sum(residual.^2);
github
HelmchenLabSoftware/OCIA-master
PeelingOptimizeSpikeTimes.m
.m
OCIA-master/caImgAnalysis/utils/eventDetection/PeelingOptimizeSpikeTimes.m
4,159
utf_8
61e419a2e0808657c62b39f38bc0fb60
function [spkTout,output] = PeelingOptimizeSpikeTimes(dff,spkTin,lowerT,upperT,... rate,tauOn,A1,tau1,optimMethod,maxIter,doPlot) % optimization of spike times found by Peeling algorithm % minimize the sum of the residual squared % while several optimization algorithms are implemented (see below), we have only used pattern % search. Other algorithms are only provided for convenience and are not tested sufficiently. % % Henry Luetcke ([email protected]) % Brain Research Institut % University of Zurich % Switzerland t = (1:numel(dff))./rate; modelTransient = modelCalciumTransient(t,t(1),tauOn,A1,tau1); modelTransient = modelTransient'; spkTout = spkTin; spkVector = zeros(1,numel(t)); for i = 1:numel(spkTin) [~,idx] = min(abs(spkTin(i)-t)); spkVector(idx) = spkVector(idx)+1; end model = conv(spkVector,modelTransient); model = model(1:length(t)); if doPlot figure('Name','Before Optimization') plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b') legend('DFF','Model','Residual') end residual = dff - model; resInit = sum(residual.^2); % start optimization x0 = spkTin; lbound = spkTin - lowerT; lbound(lbound<0) = 0; ubound = spkTin + upperT; ubound(ubound>max(t)) = max(t); lbound = zeros(size(spkTin)); ubound = repmat(max(t),size(spkTin)); opt_args.dff = dff; opt_args.rate = rate; opt_args.tauOn = tauOn; opt_args.A1 = A1; opt_args.tau1 = tau1; optimClock = tic; switch lower(optimMethod) case 'simulated annealing' options = saoptimset; case 'pattern search' options = psoptimset; case 'genetic' options = gaoptimset; otherwise error('Optimization method %s not supported.',optimMethod) end % options for optimization algorithms % not all options are used for all algorithms options.Display = 'off'; options.MaxIter = maxIter; options.MaxIter = Inf; options.UseParallel = 'always'; options.ObjectiveLimit = 0; % options.TimeLimit = 10; % in s / default is Inf % experimental options.MeshAccelerator = 'on'; % off by default options.TolFun = 1e-9; % default is 1e-6 options.TolMesh = 1e-9; % default is 1e-6 options.TolX = 1e-9; % default is 1e-6 % options.MaxFunEvals = numel(spkTin)*100; % default is 2000*numberOfVariables % options.MaxFunEvals = 20000; options.Display = 'none'; % options.Display = 'final'; % options.PlotFcns = {@psplotbestf @psplotbestx}; % options.OutputFcns = @psoutputfcn_peel; switch lower(optimMethod) case 'simulated annealing' [x, fval , exitFlag, output] = simulannealbnd(... @(x) objectiveFunc(x,opt_args),x0,lbound,ubound,options); case 'pattern search' [x, fval , exitFlag, output] = patternsearch(... @(x) objectiveFunc(x,opt_args),x0,[],[],[],[],lbound,... ubound,[],options); case 'genetic' [x, fval , exitFlag, output] = ga(... @(x) objectiveFunc(x,opt_args),numel(x0),[],[],[],[],lbound,... ubound,[],options); end if fval < resInit spkTout = x; else disp('Optimization did not improve residual. Keeping input spike times.') end if doPlot fprintf('Optimization time (%s): %1.2f s\n',optimMethod,toc(optimClock)) fprintf('Final squared residual: %1.2f (Change: %1.2f)\n',fval,resInit-fval); spkVector = zeros(1,numel(t)); for i = 1:numel(spkTout) [~,idx] = min(abs(spkTout(i)-t)); spkVector(idx) = spkVector(idx)+1; end model = conv(spkVector,modelTransient); model = model(1:length(t)); figure('Name','After Optimization') plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b') legend('DFF','Model','Residual') end function residual = objectiveFunc(spkTin,opt_args) dff = opt_args.dff; rate = opt_args.rate; tauOn = opt_args.tauOn; A1 = opt_args.A1; tau1 = opt_args.tau1; t = (1:numel(dff))./rate; modelTransient = spkTimes2Calcium(0,tauOn,A1,tau1,0,0,rate,max(t)); spkVector = zeros(1,numel(t)); for i = 1:numel(spkTin) [~,idx] = min(abs(spkTin(i)-t)); spkVector(idx) = spkVector(idx)+1; end model = conv(spkVector,modelTransient); model = model(1:length(t)); residual = dff-model; residual = sum(residual.^2);
github
HelmchenLabSoftware/OCIA-master
Peeling.m
.m
OCIA-master/caImgAnalysis/utils/eventDetection/Peeling.m
9,395
utf_8
87cff27352caf1bd8056e60c2e4c81cf
function [ca_p, peel_p, data] = Peeling(dff, rate, varargin) % this is the main routine of the peeling algorithm % % Peeling algorithm was developed by Fritjof Helmchen % Brain Research Institute % University of Zurich % Switzerland % % Matlab implementation and spike timing optimization by Henry Luetcke & Fritjof Helmchen % Brain Research Institute % University of Zurich % Switzerland % % Please cite: % Grewe BF, Langer D, Kasper H, Kampa BM, Helmchen F. High-speed in vivo calcium imaging % reveals neuronal network activity with near-millisecond precision. % Nat Methods. 2010 May;7(5):399-405. maxRate_peel = Inf; if rate > maxRate_peel peel_rate = maxRate_peel; fit_rate = rate; x = 1/rate:1/rate:numel(dff)/rate; xi = 1/peel_rate:1/peel_rate:max(x); peel_dff = interp1(x,dff,xi); else peel_rate = rate; fit_rate = rate; peel_dff = dff; end [ca_p,exp_p,peel_p, data] = InitPeeling(peel_dff, peel_rate); if nargin > 2 for n = 1:numel(varargin) S = varargin{n}; if n == 1 ca_p = overrideFieldValues(ca_p,S); elseif n == 2 exp_p = overrideFieldValues(exp_p,S); elseif n == 3 peel_p = overrideFieldValues(peel_p,S); end end end data.model = 0; data.freecamodel = ca_p.ca_rest; data.spikes = zeros(1,1000); data.numspikes = 0; data.peel = data.dff; wsiz = round(peel_p.slidwinsiz*exp_p.acqrate); checkwsiz = round(peel_p.negintwin*exp_p.acqrate); peel_p.smttmindurFrames = ceil(peel_p.smttmindur*exp_p.acqrate); peel_p.smttlowMinEvents = 1; nexttim = 1/exp_p.acqrate; [ca_p, peel_p, data] = FindNextEvent(ca_p, exp_p, peel_p, data, nexttim); if (peel_p.evtfound == 1) data.numspikes = data.numspikes + 1; data.spikes(data.numspikes) = peel_p.nextevt; [ca_p, exp_p, data] = SingleFluorTransient(ca_p, exp_p, data, peel_p.spk_recmode, peel_p.nextevt); data.model = data.model + data.singleTransient; end maxiter = 999999; iter = 0; nexttimMem = Inf; nexttimCounter = 0; timeStepForward = 2./exp_p.acqrate; while (peel_p.evtfound == 1) % check integral after subtracting Ca transient if (peel_p.spk_recmode == 'linDFF') elseif (peel_p.spk_recmode == 'satDFF') ca_p.onsetposition = peel_p.nextevt; ca_p = IntegralofCaTransient(ca_p, peel_p, exp_p, data); end dummy = data.peel - data.singleTransient; [~,startIdx] = min(abs(data.tim-data.spikes(data.numspikes))); [~,stopIdx] = min(abs(data.tim-(data.spikes(data.numspikes)+... peel_p.intcheckwin))); if startIdx < stopIdx currentTim = data.tim(startIdx:stopIdx); currentPeel = dummy(startIdx:stopIdx); currentIntegral = trapz(currentTim,currentPeel); else % if this is true, startIdx is the last data point and we should % not accept it as a spike currentIntegral = ca_p.negintegral*peel_p.negintacc; end if currentIntegral > (ca_p.negintegral*peel_p.negintacc) data.peel = data.peel - data.singleTransient; nexttim = data.spikes(data.numspikes) - peel_p.stepback; if (nexttim < 0) nexttim = 1/exp_p.acqrate; end else data.spikes(data.numspikes) = []; data.numspikes = data.numspikes-1; data.model = data.model - data.singleTransient; nexttim = peel_p.nextevt + timeStepForward; end peel_p.evtaccepted = 0; [ca_p, peel_p, data] = FindNextEvent(ca_p, exp_p, peel_p, data, nexttim); if peel_p.evtfound data.numspikes = data.numspikes + 1; data.spikes(data.numspikes) = peel_p.nextevt; [ca_p, exp_p, data] = SingleFluorTransient(ca_p, exp_p, data, peel_p.spk_recmode, peel_p.nextevt); data.model = data.model + data.singleTransient; else break end iter = iter + 1; if nexttim == nexttimMem nexttimCounter = nexttimCounter + 1; else nexttimMem = nexttim; nexttimCounter = 0; end %% if nexttimCounter > 50 nexttim = nexttim + timeStepForward; end if (iter > maxiter) % warning('Reached maxiter (%1.0f). nexttim=%1.2f. Timeout!',maxiter,nexttim); % save % error('Covergence failed!') break end end if length(data.spikes) > data.numspikes data.spikes(data.numspikes+1:end) = []; end % go back to original frame rate if rate > maxRate_peel spikes = data.spikes; [ca_p,exp_p,peel_p, data] = InitPeeling(dff, fit_rate); if nargin > 2 for n = 1:numel(varargin) S = varargin{n}; if n == 1 ca_p = overrideFieldValues(ca_p,S); elseif n == 2 exp_p = overrideFieldValues(exp_p,S); elseif n == 3 peel_p = overrideFieldValues(peel_p,S); end end end data.spikes = spikes; end % optimization of reconstructed spike times to improve timing optMethod = 'pattern search'; optMaxIter = 100000; %lowerT = 1; % relative to x0 %upperT = 1; % relative to x0 lowerT = 0.1; % relative to x0 upperT = 0.1; % relative to x0 if numel(data.spikes) && peel_p.optimizeSpikeTimes if (peel_p.spk_recmode == 'linDFF') spikes = PeelingOptimizeSpikeTimes(data.dff,data.spikes,lowerT,upperT,... exp_p.acqrate,ca_p.onsettau,ca_p.amp1,ca_p.tau1,optMethod,optMaxIter,0); elseif (peel_p.spk_recmode == 'satDFF') spikes = PeelingOptimizeSpikeTimesSaturation(data.dff,data.spikes,lowerT,upperT,... ca_p.ca_amp,ca_p.ca_gamma,ca_p.ca_onsettau,ca_p.ca_rest,ca_p.ca_kappas, exp_p.kd,... exp_p.conc,exp_p.dffmax, exp_p.acqrate, length(data.dff)./exp_p.acqrate, optMethod,optMaxIter,0); else error('Undefined mode'); end data.spikes = sort(spikes); end % fit onset to improve timing accuracy if peel_p.fitonset onsetfittype = fittype('modelCalciumTransient(t,onsettime,onsettau,amp1,tau1)',... 'independent','t','coefficients',{'onsettime','onsettau','amp1'},... 'problem',{'tau1'}); wleft = round(peel_p.fitwinleft*exp_p.acqrate); % left window for onset fit wright = round(peel_p.fitwinright*exp_p.acqrate); % right window for onset fit for i = 1:numel(data.spikes) [~,idx] = min(abs(data.spikes(i)-data.tim)); if (idx-wleft) < 1 currentwin = data.dff(1:idx+wright); currenttim = data.tim(1:idx+wright); elseif (idx+wright) > numel(data.dff) currentwin = data.dff(idx-wleft:numel(data.dff)); currenttim = data.tim(idx-wleft:numel(data.dff)); currentwin = currentwin - mean(data.dff(idx-wleft:idx)); else currentwin = data.dff(idx-wleft:idx+wright); currenttim = data.tim(idx-wleft:idx+wright); currentwin = currentwin - mean(data.dff(idx-wleft:idx)); end lowerBounds = [currenttim(1) 0.1*ca_p.onsettau 0.5*ca_p.amp1]; upperBounds = [currenttim(end) 5*ca_p.onsettau 10*ca_p.amp1]; startPoint = [data.spikes(i) ca_p.onsettau ca_p.amp1]; problemParams = {ca_p.tau1}; fOptions = fitoptions('Method','NonLinearLeastSquares','Lower',... lowerBounds,... 'Upper',upperBounds,'StartPoint',startPoint); [fitonset,gof] = fit(currenttim',currentwin',onsetfittype,... 'problem',problemParams,fOptions); if gof.rsquare < 0.95 % fprintf('\nBad onset fit (t=%1.3f, r^2=%1.3f)\n',... % data.spikes(i),gof.rsquare); else % fprintf('\nGood onset fit (r^2=%1.3f)\n',gof.rsquare); data.spikes(i) = fitonset.onsettime; end end end % loop to create spike train vector from spike times data.spiketrain = zeros(1,numel(data.tim)); for i = 1:numel(data.spikes) [~,idx] = min(abs(data.spikes(i)-data.tim)); data.spiketrain(idx) = data.spiketrain(idx)+1; end % re-derive model and residuals after optimization if (peel_p.spk_recmode == 'linDFF') modelTransient = spkTimes2Calcium(0,ca_p.onsettau,ca_p.amp1,ca_p.tau1,... ca_p.amp2,ca_p.tau2,exp_p.acqrate,max(data.tim)); data.model = conv(data.spiketrain,modelTransient); data.model = data.model(1:length(data.tim)); elseif (peel_p.spk_recmode == 'satDFF') modeltmp = spkTimes2FreeCalcium(data.spikes,ca_p.ca_amp,ca_p.ca_gamma,ca_p.ca_onsettau,ca_p.ca_rest, ca_p.ca_kappas,... exp_p.kd, exp_p.conc,exp_p.acqrate,max(data.tim)); data.model = Calcium2Fluor(modeltmp,ca_p.ca_rest,exp_p.kd, exp_p.dffmax); end data.peel = data.dff - data.model; % plotting parameter if isfield(peel_p,'doPlot') if peel_p.doPlot doPlot = 1; else doPlot = 0; end else doPlot = 1; end if doPlot % plots at interpolation rate figure; plot(data.tim,data.peel); hold all plot(data.tim,data.dff); hold all plot(data.tim,data.model); hold all plot(data.tim,data.spiketrain,'-k','LineWidth',2) legend({'Residual','Calcium','UPAPs'}) % unverified putative action potential end end function Sout = overrideFieldValues(Sout,Sin) fieldIDs = fieldnames(Sin); for n = 1:numel(fieldIDs) Sout.(fieldIDs{n}) = Sin.(fieldIDs{n}); end end
github
HelmchenLabSoftware/OCIA-master
eventDetector_OLDBalazs.m
.m
OCIA-master/caImgAnalysis/utils/eventDetection/eventDetector_OLDBalazs.m
15,137
utf_8
826457af3667681b47d959443193ceeb
function varargout = eventDetector(ROIStats, stim, ROISet, eventDetectMethod, frameRate, bpfilter, psConfig, saveName) % event detection function - wrapper to different event detection algorithms % input: structure created by GetRoiStats (*_RoiStats) dbgLevel = 2; % required folders %folderList = {'Projects/EventDetect','Projects/TwoPhotonAnalyzer'}; %addFolders2Path(folderList,1); maxRuns = Inf; % for testing % maxRuns = 2; % for testing doCaTracesPlot = 1; doPlotEvents = doCaTracesPlot && 1; %%#ok<NASGU> doRasterPlot = 1; doStimEventRasterPlot = 1; % doPsStimPlot = 1; doEventCountPlot = 0; doEventDetection = 1; o(' #eventDetector: method: "%s", maxRuns = %d ...', eventDetectMethod, maxRuns, 1, dbgLevel); %% Event detection parameters [config, V, P] = getDefaultParameters(eventDetectMethod, frameRate); %%#ok<NASGU,ASGLU> o(' #eventDetector: event detection parameters configured.', 3, dbgLevel); %% Event detection % event detection on roiStats % % last row is neuropil, remove it % allDFFData(end, :) = []; % init sizes of data set nROIs = size(ROIStats, 1); nRuns = size(ROIStats, 2); nFrames = size(ROIStats{1, 1}, 2); % only process requested runs if nRuns > maxRuns; nRuns = maxRuns; ROIStats(:, maxRuns + 1 : end) = []; end o(' #eventDetector: variables initialized.', 3, dbgLevel); o(' #eventDetector: starting event detection ... ', 2, dbgLevel); eventDetectStartTime = tic; eventData = cell(size(ROIStats)); residuals = cell(size(ROIStats)); models = cell(size(ROIStats)); eventMatAllRuns = zeros(nROIs, nRuns * size(ROIStats{1, 1}, 2)); stimVectorAllRuns = zeros(1, nRuns * size(ROIStats{1, 1}, 2)); % outerDffData = ROIStats; nRunsWithError = 0; nTotEvents = 0; % nRuns = 1; o('/!\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0); % for iRun = 1 : nRuns; nRuns = 1; o('/!\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0); for iRun = 7; try % ROIStats = outerDffData; startIndex = (iRun - 1) * nFrames + 1; endIndex = iRun * nFrames; eventDetect = config.EventDetect; o(' #eventDetector: run %d/%d, %d rois...', iRun, nRuns, nROIs, 4, dbgLevel); if size(stim{iRun}, 2) ~= endIndex - startIndex + 1; o(' #eventDetector: run %d/%d, %d rois: skip for bad size.', iRun, nRuns, nROIs, 1, dbgLevel); continue; end; stimVectorAllRuns(startIndex : endIndex) = stim{iRun}; eventDetect.rate = frameRate; % eventCounts = zeros(1, nROIs); % residuals = zeros(1, nROIs); currentEventMat = zeros(nROIs, nFrames); if doEventDetection; % parfor iROI = 1 : nROIs; % for iROI = 1 : nROIs; for iROI = 1 : 3; o(' #eventDetector: run %d/%d - roi %d/%d ...', iRun, nRuns, iROI, nROIs, 5, dbgLevel); caTrace = ROIStats{iROI, iRun}; % caTrace = mpi_BandPassFilterTimeSeries(caTrace, 1 / frameRate, bpfilter.low, bpfilter.high); %#ok<PFBNS> if isempty(caTrace); warning('eventDetector:caTraceEmpty', 'caTrace is empty!'); continue; elseif isnan(caTrace); % warning('eventDetector:caTraceNaN', 'caTrace is NaN!'); eventData{iROI, iRun} = nan(1, nFrames); continue; end; switch lower(eventDetectMethod) case 'fast_oopsi' oopsiOut = fast_oopsi(caTrace, V, P); oopsiOut(oopsiOut < config.EventDetect.oopsi_thr) = 0; %#ok<PFBNS> currentEventMat(iROI, :) = oopsiOut'; eventData{iROI, iRun} = oopsiOut'; case 'peeling' % eventOut = doPeeling(eventDetect, caTrace); [~, ~, peelRes] = Peeling(caTrace, frameRate); residuals{iROI, iRun} = peelRes.peel; models{iROI, iRun} = peelRes.model; % eventCounts(iROI) = sum(peelRes.spiketrain); %%#ok<PFOUS> % residualVector(iROI) = sum(abs(eventOut.data.peel)) / length(eventOut.data.peel); currentEventMat(iROI, :) = peelRes.spiketrain; eventData{iROI, iRun} = peelRes.spiketrain; end; nEventsFound = sum(currentEventMat(iROI, :)); nTotEvents = nTotEvents + nEventsFound; o(' #eventDetector: run %d/%d - roi %d/%d done, %d event(s) found.', ... iRun, nRuns, iROI, nROIs, nEventsFound, 4, dbgLevel); end ; end; eventMatAllRuns(:, startIndex : endIndex) = currentEventMat; o(' #eventDetector: run %d/%d done.', iRun, nRuns, 3, dbgLevel); catch err; nRunsWithError = nRunsWithError + 1; %#ok<NASGU> o(' #eventDetector: problem in run %d/%d.', iRun, nRuns, 2, dbgLevel); rethrow(err); end; end; eventDetectEndTime = toc(eventDetectStartTime); % PSTraceRoi = PsPlotAnalysisCellArray(ROIStats, stim, psConfig); o(' #eventDetector: event detection done for %d runs (%d error(s), %d total events, %.2f sec).', ... nRuns, nRunsWithError, nTotEvents, eventDetectEndTime, 2, dbgLevel); if ~isempty(eventMatAllRuns) && nTotEvents > 0; o(' #eventDetector: extracting peri-stimulus events...', 3, dbgLevel); PSEventRoi = PsPlotAnalysis(eventMatAllRuns, stimVectorAllRuns, psConfig); config.PsPlotEventRoi = PSEventRoi; o(' #eventDetector: extracting peri-stimulus events done.', 2, dbgLevel); else o(' #eventDetector: no events found (%d).', nTotEvents, 1, dbgLevel); end o(' #eventDetector: moving to plotting section ...', 3, dbgLevel); %% Calcium DFF / DRR Plot - with events if doCaTracesPlot; % only plot if required o(' #eventDetector: plotting the calcium DFF (or DRR) Plot with events...', 2, dbgLevel); %#ok<*UNRCH> % go through each run % nRuns = 1; o('/!\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0); % for iRun = 1 : nRuns; nRuns = 1; o('/!\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0); for iRun = 7; o(' #eventDetector: plotting run %d/%d ...', iRun, nRuns, 4, dbgLevel); fig = plotROICaTracesWithEvent(iRun, saveName, ... % run number and figure name cell2mat(ROIStats(:, iRun)), ... % calcium traces as a nROI-by-nFrames matrix cell2mat(eventData(:, iRun)), ... % detected events as a nROI-by-nFrames matrix stim{iRun}, ... % stimulus as a nFrames long vector ROISet, ... % name and coordinates of the rois frameRate, ... % frame rate bpfilter, ... % band-pass filter settings eventDetectMethod, ... % used detection method doPlotEvents); % tells whether to plot the events or not fig = plotROICaTracesWithEvent(iRun, saveName, ... % run number and figure name cell2mat(residuals(:, iRun)), ... % calcium traces as a nROI-by-nFrames matrix cell2mat(eventData(:, iRun)), ... % detected events as a nROI-by-nFrames matrix stim{iRun}, ... % stimulus as a nFrames long vector ROISet, ... % name and coordinates of the rois frameRate, ... % frame rate [], ... % band-pass filter settings eventDetectMethod, ... % used detection method doPlotEvents); % tells whether to plot the events or not fig = plotROICaTracesWithEvent(iRun, saveName, ... % run number and figure name cell2mat(models(:, iRun)), ... % calcium traces as a nROI-by-nFrames matrix cell2mat(eventData(:, iRun)), ... % detected events as a nROI-by-nFrames matrix stim{iRun}, ... % stimulus as a nFrames long vector ROISet, ... % name and coordinates of the rois frameRate, ... % frame rate [], ... % band-pass filter settings eventDetectMethod, ... % used detection method doPlotEvents); % tells whether to plot the events or not o(' #eventDetector: plotting run %d/%d done, saving...', iRun, nRuns, 4, dbgLevel); % set(fig, 'WindowStyle', 'docked'); if doCaTracesPlot > 1; if doPlotEvents; saveName = sprintf('%s_ROICaTracesWithEvents_run%02d_%s', saveName, iRun, ... eventDetectMethod); else saveName = sprintf('%s_ROICaTracesWithoutEvents_run%02d_%s', saveName, iRun, ... eventDetectMethod); end; saveas(fig, saveName); saveas(fig, [saveName '.png']); close(fig); end; o(' #eventDetector: plotting & saving run %d/%d done.', iRun, nRuns, 3, dbgLevel); end o(' #eventDetector: plotting %d run(s) done.', nRuns, 2, dbgLevel); end; %% Event count plot if doEventCountPlot; o(' #eventDetector: plotting the event counts for ROI image...', 2, dbgLevel); %#ok<*UNRCH> fig = plotCountROIMap( ... eventCounts, ... % event counts for each ROI 256, 256, ... % dimensions of the frame ROISet(1 : end - 1, 2)); % the positions of the ROI %% TODO HARD CODED IMAGE DIMS if doEventCountPlot > 1; set(fig, 'WindowStyle', 'docked'); saveas(fig, sprintf('%s_ROIEventCount_%s', saveName, eventDetectMethod)); saveas(fig, sprintf('%s_ROIEventCount_%s.png', saveName, eventDetectMethod)); close(fig); end; o(' #eventDetector: plotting the event counts for ROI image done.', 3, dbgLevel); %#ok<*UNRCH> end; %% Population stimulus event raster plot if doStimEventRasterPlot; o(' #eventDetector: plotting the peri-stimulus event raster plot ...', 2, dbgLevel); %#ok<*UNRCH> fig = plotStimEventRaster( ... 'PopRasterSinglePlot', ... % title of the plot PSEventRoi, ... % event counts around the stimulus stim{1}, ... % stimuli for extracting their 'name' psConfig.base, ... % number of frames looked before the stimulus psConfig.evoked, ... % number of frames looked after the stimulus frameRate); % frame rate % set(fig, 'WindowStyle', 'docked'); if doStimEventRasterPlot > 1; saveas(fig, sprintf('%s_EventStimRaster_%s', saveName, eventDetectMethod)); saveas(fig, sprintf('%s_EventStimRaster_%s.png', saveName, eventDetectMethod)); close(fig); end; o(' #eventDetector: plotting the peri-stimulus event raster plot done.', 2, dbgLevel); %#ok<*UNRCH> end; % %% Population stimulus plot % if doPsStimPlot; % o(' #eventDetector: plotting the peri-stimulus plot ...', 2, dbgLevel); %#ok<*UNRCH> % fig = plotPSStimPlot( ... % 'PopPeriStimPlot', ... % title of the plot % PSTraceRoi, ... % all traces around the stimulus % stim{1}, ... % stimuli for extracting their 'name' % psConfig.base, ... % number of frames looked before the stimulus % psConfig.evoked, ... % number of frames looked after the stimulus % frameRate); % frame rate % if doPsStimPlot > 1; % % set(fig, 'WindowStyle', 'docked'); % saveas(fig, sprintf('%s_PSStimAverage_%s', roiStats.saveName, eventDetectMethod)); % saveas(fig, sprintf('%s_PSStimAverage_%s.png', roiStats.saveName, eventDetectMethod)); % close(fig); % end; % o(' #eventDetector: plotting the peri-stimulus plot done.', 2, dbgLevel); %#ok<*UNRCH> % end; %% Population raster plot if doRasterPlot; o(' #eventDetector: plotting the population raster plot ...', 2, dbgLevel); %#ok<*UNRCH> cellIDaxes = ROISet(:, 1); switch lower(eventDetectMethod) case {'peeling', 'fast_oopsi'}; titleStr = 'PopRaster'; [fig, ~] = PsPlot2Raster(PSEventRoi, frameRate, ... psConfig.base + 1, cellIDaxes(1 : length(cellIDaxes) - 1), 1, 0); set(fig, 'Name', titleStr, 'NumberTitle', 'off'); % set(fig, 'WindowStyle', 'docked'); if doRasterPlot > 1; saveas(fig,sprintf('%s_EventRasterByRoi_%s', saveName, eventDetectMethod)); saveas(fig,sprintf('%s_EventRasterByRoi_%s.png', saveName, eventDetectMethod)); close(fig); end; end o(' #eventDetector: plotting the population raster plot done.', 2, dbgLevel); %#ok<*UNRCH> end; %% end varargout{1} = config; end function [config, V, P] = getDefaultParameters(eventDetectMethod, frameRate) amp = 10; tau = 2; onsettau = 0.01; switch lower(eventDetectMethod); case 'fast_oopsi'; config.EventDetect.amp = amp; config.EventDetect.tau = tau; config.EventDetect.onsettau = onsettau; config.EventDetect.doPlot = 0; % should be switched off config.EventDetect.lam = 0.2; % firing rate(ish) config.EventDetect.base_frames = 10; config.EventDetect.oopsi_thr = 0.3; config.EventDetect.integral_thr = 5; config.EventDetect.filter = [7 2]; config.EventDetect.minGof = 0.5; P.lam = config.EventDetect.lam; % P.gam = (1-(1/freq_ca)) / ca_tau; V.dt = 1/frameRate; V.est_gam = 1; % estimate decay time parameter (does not work) V.est_sig = 1; % estimate baseline noise SD V.est_lam = 1; % estimate firing rate V.est_a = 0; % estimate spatial filter V.est_b = 0; % estimate background fluo. V.fast_thr = 1; V.fast_iter_max = 3; case 'peeling'; V = []; P = []; config.EventDetect.optimizeSpikeTimes = 0; config.EventDetect.schmittHi = [1.75 0 3]; config.EventDetect.schmittLo = [-1 -3 0]; config.EventDetect.schmittMinDur = [0.3 0.05 3]; config.EventDetect.A1 = amp; config.EventDetect.tau1 = tau; config.EventDetect.onsettau = onsettau; config.EventDetect.optimMethod = 'none'; config.EventDetect.minPercentChange = 0.1; config.EventDetect.maxIter = 20; config.EventDetect.plotFinal = 0; case 'none'; config = []; V = []; P = []; warning('Nothing to do here! Exit ...') return; end; end
github
HelmchenLabSoftware/OCIA-master
CalciumDecay.m
.m
OCIA-master/caImgAnalysis/utils/eventDetection/CalciumDecay.m
1,116
utf_8
67138b4224a9d6e8edefa5aa8b387b8e
function [t,X] = CalciumDecay(p_gamma,p_carest,p_cacurrent,p_kappas,p_kd,p_conc,tspan) % Uses ODE45 to solve Single-compartment model differential equation % % Fritjof Helmchen ([email protected]) % Brain Research Institute,University of Zurich, Switzerland % created: 7.10.2013, last update: 25.10.2013 fh options=odeset('RelTol',1e-6); % set an error Xo = p_cacurrent; % initial conditions mypar = [p_gamma,p_carest,p_kappas,p_kd,p_conc]; % parameters [t,X] = ode45(@Relax2CaRest,tspan,Xo,options, mypar); % call the solver, tspan should contain time vector with more than two elements %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dx_dt]= Relax2CaRest(t,x,pp) % differential equation describing the decay of calcium conc level to resting level in the presence % of indicator dye with variable buffering capacity. % paramters pp: 1 - gamma, 2 - ca_rest, 3 - kappaS, 4 - kd, 5 - indicator total concentration (all conc in nM) dx_dt = -pp(1)* (x - pp(2))/(1 + pp(3) + pp(4)*pp(5)/(x + pp(4))^2); return end end
github
HelmchenLabSoftware/OCIA-master
extractPSTrace.m
.m
OCIA-master/caImgAnalysis/utils/periStim/extractPSTrace.m
3,041
utf_8
d3b2e3521d07d12854cf69d00e9ef54d
function PSCaTraces = extractPSTrace(caTraces, stims, PSFrames, varargin) if numel(varargin) > 0 && isnumeric(varargin{1}) && numel(varargin{1}) == 1; nMaxStimPerTrial = varargin{1}; else nMaxStimPerTrial = 10; end; if numel(varargin) > 1 && islogical(varargin{2}) && varargin{2}; useROIParFor = true; else useROIParFor = false; end; % make sure the peri-stimulus frames are specified as a structure if isnumeric(PSFrames) && numel(PSFrames) == 2; PSFrames = struct('base', [PSFrames(1) 0], 'evoked', [0 PSFrames(2)]); % make sure the peri-stimulus frames are specified as a structure elseif isnumeric(PSFrames) && numel(PSFrames) == 4; PSFrames = struct('base', [PSFrames(1) PSFrames(2)], 'evoked', [PSFrames(3) PSFrames(4)]); end; % get all different stims "indexes" stimTypes = unique(stims(stims ~= 0 & ~isnan(stims))); % get the size of the dataset nTrials = size(caTraces, 1); nStims = nTrials * nMaxStimPerTrial; % maximum possible stimulus per trial (to allocate enough space) nROIs = size(caTraces, 2); nFrames = size(caTraces, 3); nStimTypes = numel(stimTypes); % get the peri-stimulus frames' range PSFramesRange = unique([PSFrames.base(1) : PSFrames.base(2) PSFrames.evoked(1) : PSFrames.evoked(2)]); nPeriStimFrames = max(PSFramesRange) - min(PSFramesRange) + 1; % create a nStimTypes x nStims x nROIs x nPeriStimFrames matrix PSCaTraces = nan(nStimTypes, nStims, nROIs, nPeriStimFrames); % go through each ROI and concatenate all repetitions: % using parallel loop if useROIParFor; parfor iROI = 1 : nROIs; % store in the output structure PSCaTraces(:, :, iROI, :) = extractPSTraceForROI(reshape(caTraces(:, iROI, :), nTrials, nFrames), ... stims, nStims, nTrials, nPeriStimFrames, stimTypes, PSFrames); end % without parallel loop else for iROI = 1 : nROIs; % store in the output structure PSCaTraces(:, :, iROI, :) = extractPSTraceForROI(reshape(caTraces(:, iROI, :), nTrials, nFrames), ... stims, nStims, nTrials, nPeriStimFrames, stimTypes, PSFrames); end end; % remove empty trials emptyTrials = arrayfun(@(iTrial) all(all(all(isnan(PSCaTraces(:, iTrial, :, :))))), 1 : size(PSCaTraces, 2)); PSCaTraces(:, emptyTrials, :, :) = []; end function PSCaTrace = extractPSTraceForROI(caTraces, stims, nStims, nTrials, nPeriStimFrames, stimTypes, PSFrames) % collect relevant data, ignoring empty runs concatCaTraces = []; concatStims = []; % go trough each repetition for iPFTrial = 1 : nTrials; if ~isempty(caTraces(iPFTrial, :)); % ignore empty runs concatCaTraces = cat(2, concatCaTraces, caTraces(iPFTrial, :)); concatStims = cat(2, concatStims, stims(iPFTrial, :)); end; end; % extract the peri-stimulus averages PSCaTrace = extractPSTraceSingleTrace(concatCaTraces, concatStims, stimTypes, PSFrames.base, PSFrames.evoked); % pad with nans PSCaTrace = cat(2, PSCaTrace, nan(numel(stimTypes), nStims - size(PSCaTrace, 2), nPeriStimFrames)); end
github
HelmchenLabSoftware/OCIA-master
PsPlotAnalysisCellArray.m
.m
OCIA-master/caImgAnalysis/utils/periStim/PsPlotAnalysisCellArray.m
4,374
utf_8
5d32da67e5de7c730620b9a5b3198cce
function PSData = PsPlotAnalysisCellArray(ROIStatsData, stimCell, psFrames) % dataCell ... cell array with roi time-series (nROIs x nReps), each cell is a matrix of 1 x nFrames % stimCell ... cell array of stim vectors (1 x nReps), each cell is a matrix of 1 x nFrames % config ... peri-stimulus config structure with the number of base and evoked frames % PSData ... cell array of stim-locked ROI time-series (nROIs x nStims) % this file written by Henry Luetcke ([email protected]) % modified by Balazs % get all different stims "indexes" stimTypes = unique(cell2mat(stimCell)); % remove the 0 which is the "no stim" index stimTypes(stimTypes == 0) = []; nROIs = size(ROIStatsData, 1); nReps = size(ROIStatsData, 2); nStims = numel(stimTypes); % nFrames = size(ROIStatsData{1, 1}, 2); % create a cell array (nROIs x nStims), each cell is a matrix of nReps x nPeriStimFrames PSData = cell(nROIs, nStims); % go through each ROI and concatenate all repetitions for iROI = 1 : nROIs; % collect relevant data, ignoring empty runs allTraces = []; allStims = []; % go trough each repetition for iRep = 1 : nReps; if ~isempty(ROIStatsData{iROI, iRep}); % ignore empty runs allTraces = [allTraces, ROIStatsData{iROI, iRep}]; %#ok<AGROW> allStims = [allStims, stimCell{iRep}]; %#ok<AGROW> end; end; % extract the peri-stimulus averages PSData(iROI, :) = doPsPlot(allTraces, allStims, stimTypes, psFrames.base, psFrames.evoked); end end function psData = doPsPlot(data, stimVector, stimTypes, baseFrames, evokedFrames) psData = cell(1,length(stimTypes)); for n = 1:numel(stimTypes) currentStim = stimTypes(n); currentStimNo = numel(find(stimVector==currentStim)); if isempty(currentStimNo) psData{roi,n} = []; continue end for roi = 1:size(data,1) psData{roi,n} = zeros(currentStimNo,... baseFrames+evokedFrames); end currentStimNo = 0; for t = 1:numel(stimVector) if stimVector(t) == currentStim currentStimNo = currentStimNo + 1; nanPad = 0; startFrame = t - baseFrames; if startFrame < 1 nanPad = startFrame-1; startFrame = 1; end stopFrame = t + evokedFrames-1; if stopFrame > numel(stimVector) nanPad = stopFrame - numel(stimVector); stopFrame = numel(stimVector); end for roi = 1:size(data,1) currentRoiTrace = data(roi,startFrame:stopFrame); if nanPad < 0 currentRoiTrace = [nan(1,abs(nanPad)) currentRoiTrace]; elseif nanPad > 0 currentRoiTrace = [currentRoiTrace nan(1,nanPad)]; end psData{roi,n}(currentStimNo,:) = currentRoiTrace; end end end end end % stimTypes = unique(stimVector); % all non-zero elements % stimTypes(stimTypes==0) = []; % PsPlotData = cell(size(data,1),length(stimTypes)); % for n = 1:numel(stimTypes) % currentStim = stimTypes(n); % currentStimNo = numel(find(stimVector==currentStim)); % for roi = 1:size(data,1) % PsPlotData{roi,n} = zeros(currentStimNo,... % baseFrames+evokedFrames); % end % currentStimNo = 0; % for t = 1:numel(stimVector) % if stimVector(t) == currentStim % currentStimNo = currentStimNo + 1; % nanPad = 0; % startFrame = t - baseFrames; % if startFrame < 1 % nanPad = startFrame-1; % startFrame = 1; % end % stopFrame = t + evokedFrames-1; % if stopFrame > numel(stimVector) % nanPad = stopFrame - numel(stimVector); % stopFrame = numel(stimVector); % end % for roi = 1:size(data,1) % currentRoiTrace = data(roi,startFrame:stopFrame); % if nanPad < 0 % currentRoiTrace = [nan(1,abs(nanPad)) currentRoiTrace]; % elseif nanPad > 0 % currentRoiTrace = [currentRoiTrace nan(1,nanPad)]; % end % PsPlotData{roi,n}(currentStimNo,:) = currentRoiTrace; % end % end % end % end
github
HelmchenLabSoftware/OCIA-master
GetRoiStatsRaps.m
.m
OCIA-master/caImgAnalysis/ROIStats/GetRoiStatsRaps.m
14,428
utf_8
c3e91f2c80c771821e60bb7a2d4530ef
function varargout = GetRoiStatsRaps(config) % get ROI timecourses from images, with support for muliple ROIs and runs % returns structure data, info and stimulus fields % data field contains a cell array with ROI timecourses for different cells % in rows and different runs in columns: % [cell1_run1] [cell1_run2] ... [cell1_runN] % [cell2_run1] [cell2_run2] ... [cell2_runN] % ... ... ... % [cellN_run1] [cellN_run2] ... [cellN_runN] % this file written by Henry Luetcke ([email protected]) config = ParseConfig(config); matfiles = config.matfiles; % run in parallel (matlabpool should be available)? if matlabpool('size') doParallel = 1; else doParallel = 0; end % doParallel = 0; for n = 1:numel(matfiles) if isempty(strfind(matfiles{n},'.mat')) matfiles{n} = [matfiles{n} '.mat']; end end S = load(matfiles{1}); data = S.(genvarname(strrep(matfiles{1},'.mat',''))); samplingRate = data.hdr.rate; delFrame = data.proc.DelFrame; % number of points fIdx = strfind(matfiles{1},'pts'); for i = fIdx-1:-1:1 if strcmp(matfiles{1}(i),'_') config.points = str2num(matfiles{1}(i+1:fIdx-1)); break end end % experiment specific info animalID = data.hdr.animalID; spotID = data.hdr.spotID; saveName = sprintf('%s_%s_RoiStats',animalID,spotID); % print out some experiment details fprintf('%s - %s\n',animalID,spotID); fprintf('Total Points: %1.0f Sampling frequency: %1.2f\n',config.points,samplingRate); fprintf('Total cells: %1.0f\n',config.points/config.pointsPerCell); fprintf('Background vector: %s\n',num2str(config.bgVector)); config.totalCells = config.points/config.pointsPerCell; %% low-pass filter parameters switch config.LowPass.method case 'sg' lpFiltCutoff = config.LowPass.params(1); lpFiltCutoff = round(lpFiltCutoff.*data.hdr.rate); if ~rem(lpFiltCutoff,2) lpFiltCutoff = lpFiltCutoff+1; end config.LowPass.lpFiltCutoff = lpFiltCutoff; config.LowPass.sgolayOrder = config.LowPass.params(2); % filter order clear lpFiltCutoff end %% Setup event detection - Peeling config.runsNo = numel(matfiles); switch lower(config.EventDetect.method) case 'peeling' % setup generic input structure for doPeeling % required fields should be defined in calling script (see % doPeeling for documentation) eventS = config.EventDetect; eventS.rate = samplingRate; case 'none' % nothing to do here otherwise error('Unknow event detection method: %s',config.EventDetect.method) end out.roiData = cell(1,config.runsNo); out.eventData = cell(1,config.runsNo); out.modelData = cell(1,config.runsNo); out.residualData = cell(1,config.runsNo); out.stim = cell(1,config.runsNo); out.hdr = cell(1,config.runsNo); out.proc = cell(1,config.runsNo); %% Process runs for currentRun = 1:config.runsNo fprintf('\nNow processing run %1.0f\n',currentRun); % for 'drr', work on both channels, for 'dff' work on ch1 S = load(matfiles{currentRun}); data = S.(genvarname(strrep(matfiles{currentRun},'.mat',''))); out.hdr{currentRun} = data.hdr; out.proc{currentRun} = data.proc; rapsData = cell(1,length(config.channelVector)); for n = 1:length(config.channelVector) A = data.img_data{config.channelVector(n)}; A(:,end+1) = A(:,1); A(:,1) = []; % first column last rapsData{n} = A; end timepoints = size(rapsData{1},1); if isempty(data.stim) if config.ch3Sound [config.stim{currentRun},soundT] = ... img2vector(double(data.img_data{3}),1/config.pixelTime,0); else config.stim{currentRun} = []; end config.stim{currentRun} = removeBlankPixels(config.stim{currentRun}); [stimTable,~,toneClean] = AnalyzePureToneVector(config.stim{currentRun},... 1/config.pixelTime,0); % [stimTable,toneClean] = cleanUpBadSound(config.stim{currentRun},... % 1/config.pixelTime,0); plotSoundVector = 1; else stimTable = data.stim; plotSoundVector = 0; end [stim,stimTime,stimID] = soundTable2StimVector(stimTable,1/config.pixelTime,0); out.stim{currentRun} = stimTable; % average columns for each cell ch1ByCell = zeros(size(rapsData{1},1),... config.points/config.pointsPerCell); ch2ByCell = zeros(size(rapsData{2},1),... config.points/config.pointsPerCell); pos = 1; for n = 1:config.pointsPerCell:size(rapsData{1},2) currentCell = double(rapsData{1}(:,n:n+config.pointsPerCell-1)); currentCell = removeBlankPixels(currentCell,1); % currentCell(:,end) = currentCell(:,end) + ... % (mean(mean(currentCell(:,1:config.pointsPerCell-1)))-mean(currentCell(:,end))); ch1ByCell(:,pos) = mean(currentCell,2); currentCell = double(rapsData{2}(:,n:n+config.pointsPerCell-1)); currentCell = removeBlankPixels(currentCell,1); % currentCell(:,end) = currentCell(:,end) + ... % (mean(mean(currentCell(:,1:config.pointsPerCell-1)))-mean(currentCell(:,end))); ch2ByCell(:,pos) = mean(currentCell,2); pos = pos + 1; end % subtract background ch1_bg = mean(ch1ByCell(:,config.bgVector),2); ch2_bg = mean(ch2ByCell(:,config.bgVector),2); for n = 1:size(ch1ByCell,2) ch1ByCell(:,n) = ch1ByCell(:,n) - ch1_bg; ch2ByCell(:,n) = ch2ByCell(:,n) - ch2_bg; end disp('Subtracted background'); % remove background columns ch1ByCell(:,config.bgVector) = []; ch2ByCell(:,config.bgVector) = []; switch config.statsType case 'drr' ratio = ch1ByCell ./ ch2ByCell; case 'dff' ratio = ch1ByCell; end % DRR DRR = zeros(size(ratio)); for n = 1:size(ch1ByCell,2) % r0 = findF0_prctile(ratio(:,n),samplingRate,5,10); % calculate F0 (use quadratic fit method) r0 = CalculateF0(ratio(:,n),samplingRate); DRR(:,n) = ((ratio(:,n) - r0) ./ r0)*100; end fprintf('Calculated relative fluorescence (%s)\n',... upper(config.statsType)); DRRsmooth = zeros(size(DRR)); for n = 1:size(DRR,2) DRRsmooth(:,n) = doLowPassFilter(DRR(:,n),config.LowPass); end % notch filter if config.notchF fprintf('Fluorescence notch filter %1.2fHz (Q=%1.1f)\n',... config.notchF,config.notchQ); for n = 1:size(DRR,2) DRRsmooth(:,n) = notchFilter(DRRsmooth(:,n),samplingRate,... config.notchF,config.notchQ); end end RoiMatAllRuns = DRRsmooth'; out.roiData{currentRun} = RoiMatAllRuns; %% Event detection switch lower(config.EventDetect.method) case 'peeling' fprintf('Started Peeling for %s %s run %1.0f (%1.0f cells)\n',... animalID,spotID,currentRun,size(RoiMatAllRuns,1)) t = tic; eventData = zeros(size(RoiMatAllRuns)); modelData = zeros(size(RoiMatAllRuns)); residualData = zeros(size(RoiMatAllRuns)); if doParallel spiketrainCell = cell(1,size(RoiMatAllRuns,1)); modelCell = cell(1,size(RoiMatAllRuns,1)); peelCell = cell(1,size(RoiMatAllRuns,1)); parfor roi2 = 1:size(RoiMatAllRuns,1) Sin = eventS; Sin.dff = RoiMatAllRuns(roi2,:); outS = doPeeling(Sin); spiketrainCell{1,roi2} = outS.data.spiketrain; modelCell{1,roi2} = outS.data.model; peelCell{1,roi2} = outS.data.peel; end for roi2 = 1:size(RoiMatAllRuns,1) eventData(roi2,:) = spiketrainCell{roi2}; modelData(roi2,:) = modelCell{roi2}; residualData(roi2,:) = peelCell{roi2}; end clear spiketrainCell modelCell peelCell else for roi2 = 1:size(RoiMatAllRuns,1) fprintf('.') eventS.dff = RoiMatAllRuns(roi2,:); outS = doPeeling(eventS); eventData(roi2,:) = outS.data.spiketrain; modelData(roi2,:) = outS.data.model; residualData(roi2,:) = outS.data.peel; end end t = toc(t); fprintf('\nFinished Peeling (t=%1.2f s)\n',t) end out.eventData{currentRun} = eventData; out.modelData{currentRun} = modelData; out.residualData{currentRun} = residualData; % plot all Rois with stim in stacked plot titleStr = (strrep(matfiles{currentRun},'.mat','')); fig = figure('Name',titleStr,'NumberTitle','off'); hold all currentOffset = 0; time = (1:size(RoiMatAllRuns,2))/samplingRate; cellIDaxes = cell(size(RoiMatAllRuns,1),1); meanYpos = zeros(size(RoiMatAllRuns,1),1); for roi = 1:size(RoiMatAllRuns,1) data = RoiMatAllRuns(roi,:); currentSD = std(data); data = data + (min(data)*-1); dataPlot = data + currentOffset; currentOffset = max(dataPlot); cellIDaxes{roi} = sprintf('%1.0f (%1.2f)',roi,currentSD); meanYpos(roi) = mean(dataPlot); switch lower(config.EventDetect.method) case 'fast_oopsi' events = eventData(roi,:)*30; events = events + currentOffset; currentOffset = max(events); end end if config.ch3Sound && plotSoundVector cellIDaxes{roi+1} = 'sound'; dataPlot = ScaleToMinMax(config.stim{currentRun},0,50); dataPlot = dataPlot + currentOffset; meanYpos(roi+1) = mean(dataPlot); currentOffset = max(dataPlot); end hold all set(gca,'ylim',[0 currentOffset],'xlim',[min(time) ... max(time)+0.1*max(time)]) set(gca,'XTick',[]) ax1 = gca; saveStr = titleStr; try titleStr = sprintf('%s\nStandard: %1.0f kHz Deviant: %1.0f kHz',... titleStr,stimID(1),stimID(2)); end title(titleStr,'Interpreter','none') ylabel(sprintf('%% %s',upper(config.statsType))) ax2 = axes('Position',get(gca,'Position'),'YAxisLocation','right'); set(ax2,'ylim',[0 currentOffset],'xlim',[min(time) max(time)],... 'YTick',meanYpos,'YTickLabel',cellIDaxes) xlabel('Time / s') hold all stimTimes1 = stimTime(stim==1); stimTimes2 = stimTime(stim==2); for n = 1:numel(stimTimes1) plot([stimTimes1(n) stimTimes1(n)],[0 currentOffset],'--','Color',[0.5 0.5 0.5]), hold all end for n = 1:numel(stimTimes2) plot([stimTimes2(n) stimTimes2(n)],[0 currentOffset],'--r'), hold all end hold all currentOffset = 0; for roi = 1:size(RoiMatAllRuns,1) data = RoiMatAllRuns(roi,:); data = data + (min(data)*-1); dataPlot = data + currentOffset; plot(time,dataPlot,'k') currentOffset = max(dataPlot); events = eventData(roi,:); switch lower(config.EventDetect.method) case 'fast_oopsi' events = events * 30; events = events + currentOffset; plot(time,events,'Color',[0.5 0.5 0.5]) currentOffset = max(events); case 'peeling' spikeTimes = time(events>0); scatter(spikeTimes,repmat(min(dataPlot),1,numel(spikeTimes)),'.',... 'MarkerEdgeColor',[0.5 0.5 0.5]) end end if config.ch3Sound && plotSoundVector dataPlot = ScaleToMinMax(config.stim{currentRun},0,50); dataPlot = dataPlot + currentOffset; plot(soundT,dataPlot,'Color',[0.5 0.5 0.5]) end linkaxes([ax1,ax2],'y') saveas(gcf,[saveStr '.fig']) end SaveAndAssignInBase(out,saveName,'SaveOnly') if nargout varargout{1} = out; end %% Function - doLowPassFilter function v = doLowPassFilter(v,S) switch S.method case 'sg' v = sgolayfilt(v,S.sgolayOrder,S.lpFiltCutoff); end function f0_mat = CalculateF0(roi_mat,f) t = (1/f:1/f:length(roi_mat)./f)'; p = polyfit(t,roi_mat,2); f0_mat = p(1).*t.^2 + p(2).*t + p(3); %% Function - ParseConfig function config = ParseConfig(config) % check for missing fields in config structure and add them with % default values if ~isfield(config,'matfiles') matFiles = sort(uigetfile(... '*.mat','Select Mat Files','MultiSelect','on')); config.matfiles = strrep(matFiles,'.mat',''); else matfiles = config.matfiles; end if ~isfield(config,'saveName') config.saveName = [matfiles{1} '__RoiStats']; end if ~isfield(config,'pointsPerCell') config.pointsPerCell = 9; end if ~isfield(config,'bgVector') config.bgVector = [1 2 3]; end if ~isfield(config,'ch3Sound') config.ch3Sound = 1; end if ~isfield(config,'pixelTime') config.pixelTime = 12; end config.pixelTime = config.pixelTime / 1000000; if ~isfield(config,'statsType') config.statsType = 'dff'; end if ~isfield(config,'notchF') config.notchF = 0; end if ~isfield(config,'notchQ') config.notchQ = 1; end % channels for stats calculation % DFF is calculated on the channel specified by config.channelVector(1) % DRR is calculated on the channels specified by config.channelVector(1) % and config.channelVector(2) if ~isfield(config,'channelVector') config.channelVector = [1 2]; end if strcmpi(config.statsType,'drr') && numel(config.channelVector) < 2 error('config.channelVector must specify at least 2 channels for DRR stats!'); end if ~isfield(config,'psConfig') config.psConfig = struct; config.psConfig.baseFrames = 5; config.psConfig.evokedFrames = 15; end % event detection if ~isfield(config,'EventDetect') config.EventDetect.method = 'none'; end % low-pass filter if ~isfield(config,'LowPass') config.LowPass.method = 'none'; config.LowPass.params = []; end % LowPass.method may take the following values: % 'none' ... no low-pass filtering is applied % 'sg' ... savitzky-golay filter, as implemented in ML % LowPass.params is a vector with filter parameters, depending on the % specific filter (all cutoffs should be defined in s) % for SG, params are [lpFilterCutoff filterOrder] % e.o.f.
github
HelmchenLabSoftware/OCIA-master
GetRoiStatsLineScan.m
.m
OCIA-master/caImgAnalysis/ROIStats/GetRoiStatsLineScan.m
10,400
utf_8
14f4dec618b5d5152ce43b50f448cbac
function varargout = GetRoiStatsLineScan(config) % get ROI timecourses from images, with support for muliple ROIs and runs % returns structure data, info and stimulus fields % data field contains a cell array with ROI timecourses for different cells % in rows and different runs in columns: % [cell1_run1] [cell1_run2] ... [cell1_runN] % [cell2_run1] [cell2_run2] ... [cell2_runN] % ... ... ... % [cellN_run1] [cellN_run2] ... [cellN_runN] % this file written by Henry Luetcke ([email protected]) config = ParseConfig(config); matfiles = config.matfiles; for n = 1:numel(matfiles) if isempty(strfind(matfiles{n},'.mat')) matfiles{n} = [matfiles{n} '.mat']; end end S = load(matfiles{1}); data = S.(genvarname(strrep(matfiles{1},'.mat',''))); config.imgDim = data.hdr.size(1:2); roiSet = data.roi; cellNo = size(roiSet,1); config.runsNo = numel(matfiles); config.timepoints = data.hdr.size(1); % config.dataRoi = cell(cellNo,config.runsNo); % config.dataRoiNorm = cell(cellNo,config.runsNo); % config.dataNpil = cell(cellNo,config.runsNo); % cMatFigRoi = figure('Name',sprintf('%s %s',config.statsType,'Roi'),... % 'NumberTitle','off','color','white'); % cMatFigRoiNorm = figure('Name',sprintf('%s %s',config.statsType,'RoiNorm'),... % 'NumberTitle','off','color','white'); % cMatFigRoiNpil = figure('Name',sprintf('%s %s',config.statsType,'RoiNpil'),... % 'NumberTitle','off','color','white'); RoiMatAllRuns = []; RoiMatNormAllRuns = []; RoiMatNpilAllRuns = []; StimVectorAllRuns = []; %% Process runs for currentRun = 1:config.runsNo fprintf('\nNow processing run %1.0f\n',currentRun); % for 'drr', work on both channels, for 'dff' work on ch1 S = load(matfiles{currentRun}); data = S.(genvarname(strrep(matfiles{currentRun},'.mat',''))); currentImgData = cell(1,length(config.channelVector)); currentMeanImgData = cell(1,length(config.channelVector)); for n = 1:length(config.channelVector) currentImgData{n} = double(data.img_data{config.channelVector(n)}); % currentMeanImgData{n} = mean(currentImgData{n},3); end config.stim{currentRun} = data.stim; config.frameRate{currentRun} = data.hdr.rate; roiSet = data.roi; roiLabel = roiSet(:,1); if isfield(data.hdr,'bits') bitDepth = data.hdr.bits; else bitDepth = 16; end if islogical(roiSet{1,2}) roiSet = ij_RoiSetCompression(roiSet,1); end for currentRoi = 1:size(roiSet,1) roi = roiSet{currentRoi,2}; roiId = roiSet{currentRoi,1}; % we only need the columns for each roi roiSet{currentRoi,2} = unique(roi(:,2)); end config.roi = roiSet(:,1:2); stim = config.stim{currentRun}; if isempty(stim) stimVectorFrameRate = zeros(1,config.timepoints); else if isstruct(stim) if stim.rate ~= config.frameRate{currentRun} % compute stimVectorFrameRate stimVectorFrameRate = ResampleStimVector(stim.vector,stim.rate,... config.timepoints,config.frameRate{currentRun}); else stimVectorFrameRate = stim.vector; end elseif isvector(stim) % assume stim vector already converted to frames stimVectorFrameRate = stim; end end if numel(stimVectorFrameRate) > config.timepoints stimVectorFrameRate(config.timepoints+1:end) = []; elseif numel(stimVectorFrameRate) < config.timepoints stimVectorFrameRate(end:config.timepoints) = 0; end StimVectorAllRuns = [StimVectorAllRuns stimVectorFrameRate]; if config.forceIJf0 stimVectorFrameRate = zeros(1,config.timepoints); end %% LowPass filter points = round(config.lowPass*config.frameRate{currentRun}); %% Calculate stats for currentRoi = 1:size(config.roi,1) currentColumns = config.roi{currentRoi,2}; roiData = cell(1,numel(config.channelVector)); for n = 1:numel(config.channelVector) roiData{n} = currentImgData{n}(:,currentColumns); roiData{n} = nanmean(roiData{n},2); roiData{n} = filter(ones(1,points)/points,1,roiData{n}); roiData{n}(1:points,:) = []; end switch lower(config.statsType) case 'dff' roiStats = roiData{1}; case 'drr' roiStats = roiData{1} ./ roiData{2}; end roiStats = roiStats'; % calculate F0 % roiF0 = CalculateF0(roiStats,stimVectorFrameRate,config.baseFrames); roiF0 = findF0(roiStats,config.frameRate{currentRun},1,10); % calculate stats roiStats = ((roiStats-roiF0) ./ roiF0) .* 100; roiStats(isinf(roiStats)) = 0; roiStats(isnan(roiStats)) = 0; % save mean stats timecourse config.dataRoi{currentRoi,currentRun} = roiStats; currentRoiMat(currentRoi,:) = roiStats; end RoiMatAllRuns = [RoiMatAllRuns currentRoiMat]; end % plot all Rois with stim in stacked plot titleStr = sprintf('%s',config.saveName); fig = figure('Name',titleStr,'NumberTitle','off'); hold all currentOffset = 0; time = (1:size(RoiMatAllRuns,2))/config.frameRate{1}; for roi = 1:size(RoiMatAllRuns,1) id = sprintf('%1.0f',roi); data = RoiMatAllRuns(roi,:); data = data + (min(data)*-1); dataPlot = data + currentOffset; plot(time,dataPlot) currentOffset = max(dataPlot); text(max(time),mean(dataPlot),id) end for n = 1:numel(StimVectorAllRuns) if StimVectorAllRuns(n) == 1 plot([time(n) time(n)],[0 currentOffset],'LineStyle','--',... 'Color',[0.8 0.8 0.8]) elseif StimVectorAllRuns(n) == 2 plot([time(n) time(n)],[0 currentOffset],'LineStyle','--',... 'Color',[0.3 0.3 0.3]) end end set(gca,'ylim',[0 currentOffset],'xlim',[min(time) max(time)+0.1*max(time)]) xlabel('Time / s') title(titleStr,'Interpreter','none') ylabel(sprintf('%% %s',upper(config.statsType))) saveas(fig,config.saveName) SaveAndAssignInBase(config,config.saveName) if nargout varargout{1} = config; end %% Function - pcolorPlot function pcolorPlot(fig,runs,currentRun,roiMat,stimVector,roiLabel) figure(fig) subplot(runs,1,currentRun) roiMat = [ScaleToMinMax(stimVector,0,25);roiMat]; colorMat = padarray(roiMat,[1 1]); pFig = pcolor([-0.5:(size(colorMat,2)-1.5)],... [-0.5:(size(colorMat,1)-1.5)],colorMat); set(pFig,'EdgeAlpha',0); xAxis = get(gca,'XLim'); yAxis = get(gca,'YLim'); caxis([-5 25]); set(gca,'XLim',[0.5 xAxis(2)],'YLim',[0.5 yAxis(2)]); roiLabel = ['stim'; roiLabel; 'npil']; set(gca,'YTick',[1:length(roiLabel)],'XTick',[]); set(gca,'YTickLabel',roiLabel,'FontSize',8); colorbar %% Function - ParseConfig function config = ParseConfig(config) % check for missing fields in config structure and add them with % default values if ~isfield(config,'matfiles') matfiles = uigetfile('*.mat','Select Mat Files','MultiSelect','on'); if ~iscell(matfiles) matfiles = {matfiles}; end config.matfiles = strrep(matfiles,'.mat',''); end if ~isfield(config,'saveName') config.saveName = [config.matfiles{1} '__RoiStats']; end % force f0 calculation as in ImageJ if ~isfield(config,'forceIJf0') config.forceIJf0 = 0; end if isempty(config.forceIJf0) config.forceIJf0 = 0; end % number of initial frames for normalization (forceImageJf0) OR the number % of frames before a stimulus used for renormalization if ~isfield(config,'baseFrames') config.baseFrames = 10; end if isempty(config.baseFrames) config.baseFrames = 10; end if ~isfield(config,'statsType') config.statsType = 'dff'; end % channels for stats calculation % DFF is calculated on the channel specified by config.channelVector(1) % DRR is calculated on the channels specified by config.channelVector(1) % and config.channelVector(2) if ~isfield(config,'channelVector') config.channelVector = [1 2]; end if strcmpi(config.statsType,'drr') && numel(config.channelVector) < 2 error('config.channelVector must specify at least 2 channels for DRR stats!'); end if ~isfield(config,'psConfig') config.psConfig = struct; config.psConfig.baseFrames = 5; config.psConfig.evokedFrames = 15; end if ~isfield(config,'lowPass') config.lowPass = 1/30; % in s end %% Function - CalculateF0 function f0_mat = CalculateF0(roi_mat,stim,base) if ~max(stim) f0_mat = roi_mat(:,1:base); f0_mat = nanmean(f0_mat,2); f0_mat = repmat(f0_mat,1,size(roi_mat,2)); return end % binarise stim vector (each stimulus type leads to % renormalization) stim(stim>0)=1; % define frames of stimulus onset stim_onset = zeros(size(stim)); for n = 2:length(stim) if stim(n) == 1 && stim(n-1) == 0 stim_onset(n) = 1; end end % designate the base frames BEFORE stimulus onset as baseline stim_base = zeros(size(stim)); for n = base+1:length(stim) if stim_onset(n) == 1 stim_base(n-base:n-1) = 1; end end f0_mat = zeros(size(roi_mat)); for n = 1:length(stim) if stim_base(n) == 1 stim_base(n:n+base-1) = 0; % find endpoint of current F0 interval (the frame before % next normalization interval start) f0_stop = find(stim_base==1,1,'first')-1; if isempty(f0_stop) f0_stop = length(stim); end for pixel = 1:size(f0_mat,1) current_mean = mean(roi_mat(pixel,n:n+base-1)); f0_mat(pixel,n:f0_stop) = current_mean; end end end % timepoints before first stimulus get F0 value for first % pre-stimulus baseline pre_stim1 = find(f0_mat(1,:)~=0,1,'first'); for pixel = 1:size(f0_mat,1) f0_mat(pixel,1:pre_stim1-1) = f0_mat(pixel,pre_stim1); end %% Function - ResampleStimVector function stimVectorFrameRate = ResampleStimVector(stim,stimRate,timepoints,frameRate) stimVectorFrameRate = zeros(1,timepoints); for n = 1:timepoints startT = (n-1)/frameRate; stopT = n/frameRate; startStim = round(startT*stimRate); if startStim == 0 startStim = 1; end stopStim = round(stopT*stimRate); if startStim > length(stim) || stopStim > length(stim) stimVectorFrameRate(n) = 0; else stimVectorFrameRate(n) = round(mean(stim(startStim:stopStim))); end end % e.o.f.
github
HelmchenLabSoftware/OCIA-master
ConvertRawData_legacy.m
.m
OCIA-master/caImgAnalysis/ROIStats/ConvertRawData_legacy.m
12,315
utf_8
54a3f3e6134c4f0dd99acd8f124d9fc8
function varargout = ConvertRawData(varargin) % inputs: no need to specify any inputs --> GUI-based file selection % optional input arguments, specified as 'property' 'value' pair in % arbitrary order, e.g. 'zoom',1.07 OR as a structure with properties as % field names and values, e.g. config.zoom = 1.07 % for a full list of supported arguments see the end of this file % License: this file may only be used with agreement to the license terms % outlined in the accompanying license.txt % if you do not agree with these terms, you MUST NOT use this file or any % part thereof in any way % this file written by Henry Luetcke ([email protected]) % current version: 2010-04-14 %% Main RawDataDir = getGlobalParameters('RawDataDir'); if ~RawDataDir error('Raw data directory MUST be specified'); end args = parseInputArgs(varargin); if min(size(args.RawFiles)) > 1 runs = size(args.RawFiles,1); else runs = length(args.RawFiles); % make sure runs are in columns args.RawFiles = reshape(args.RawFiles,numel(args.RawFiles),1); end for n = 1:runs % create structure currentS = initStruct(args,n,RawDataDir); % preprocess image data currentS = preprocStruct(args,n,currentS); % save files saveFiles(currentS,args.SaveDir); S{n} = currentS; end if nargout varargout{1} = S; end %% Parse inputs function S = parseInputArgs(inargs) if ~isempty(inargs) && isstruct(inargs{1}) % convert structure to pseudo-input cellarray inargs = struct2cellArray(inargs{1}); end RawDataDir = getGlobalParameters('RawDataDir'); % input files SpInput = find(strcmpi(inargs, 'RawFiles')); if numel(SpInput) RawFiles = inargs{SpInput+1}; if ~iscellstr(RawFiles) error('Modifier for raw files property must be a cell string'); end else [FileName,PathName,FilterIndex] = uigetfile({'*.fcs';'*.tif';'*.tiff'},... 'Select raw file(s) to import','MultiSelect','on'); if ~iscellstr(FileName) FileName = {FileName}; end if ~FileName{1}; return; end if ~iscellstr(FileName); FileName = cellstr(FileName); end if strfind(PathName,RawDataDir) PathName = strrep(PathName,RawDataDir,''); end for n = 1:length(FileName) % interpret GUI-selected multiple files as different channels RawFiles{1,n} = fullfile(PathName,FileName{n}); end end S.RawFiles = RawFiles; % frame rate SpInput = find(strcmpi(inargs, 'frame_rate')); if numel(SpInput) frame_rate = inargs{SpInput+1}; if isscalar(frame_rate) frame_rate = repmat(frame_rate,1,length(RawFiles)); else if length(frame_rate) ~= length(RawFiles) error('Frame rate must be a scalar or vector of length input file number'); end end else frame_rate = []; end S.frame_rate = frame_rate; % zoom SpInput = find(strcmpi(inargs, 'zoom')); if numel(SpInput) zoom_factor = inargs{SpInput+1}; if isscalar(zoom_factor) zoom_factor = repmat(zoom_factor,1,length(RawFiles)); else if length(zoom_factor) ~= length(RawFiles) error('Zoom must be a scalar or vector of length input file number'); end end else zoom_factor = []; end S.zoom_factor = zoom_factor; % image type SpInput = find(strcmpi(inargs, 'type')); if numel(SpInput) img_type = inargs{SpInput+1}; if ~iscellstr(img_type); img_type = cellstr(img_type); end if length(img_type) == 1 img_type = repmat(img_type,1,length(RawFiles)); elseif length(img_type) ~= length(RawFiles) error('Image type must be a cell string of length 1 or input file number'); end else img_type = cell(1,length(RawFiles)); end S.img_type = img_type; % Roi set SpInput = find(strcmpi(inargs, 'RoiSet')); if numel(SpInput) roi_set = inargs{SpInput+1}; if ~iscellstr(roi_set); roi_set = cellstr(roi_set); end if length(roi_set) == 1 roi_set = repmat(roi_set,1,length(RawFiles)); elseif length(roi_set) ~= length(RawFiles) error('RoiSet must be a cell string of length 1 or input file number'); end else roi_set = cell(1,length(RawFiles)); end S.roi_set = roi_set; % Stimulus SpInput = find(strcmpi(inargs, 'Stim')); if numel(SpInput) stim = inargs{SpInput+1}; if ~iscell(stim); stim = {stim}; end if length(stim) == 1 stim = repmat(stim,1,length(RawFiles)); elseif length(stim) ~= length(RawFiles) error('Stimulation must be a cell array of length 1 or input file number'); end else stim = cell(1,length(RawFiles)); end S.stim = stim; % Output directory SpInput = find(strcmpi(inargs, 'SaveDir')); if numel(SpInput) SaveDir = inargs{SpInput+1}; if exist(SaveDir,'dir') ~= 7 try mkdir(SaveDir); catch error('Failed to create directory %s',SaveDir); end end else SaveDir = pwd; end S.SaveDir = SaveDir; % Preprocessing options - delete frame SpInput = find(strcmpi(inargs, 'DelFrame')); if numel(SpInput) del_frame = inargs{SpInput+1}; if isscalar(del_frame) del_frame = repmat(del_frame,1,length(RawFiles)); else if length(del_frame) ~= length(RawFiles) error('DelFrame must be a scalar or vector of length input file number'); end end else del_frame = []; end S.del_frame = del_frame; % bg. correction SpInput = find(strcmpi(inargs, 'BgCorrect')); if numel(SpInput) bgCorrect = inargs{SpInput+1}; else bgCorrect = []; end S.bgCorrect = bgCorrect; %% Structure initialization function S = initStruct(inargs,n,RawDataDir) infile = inargs.RawFiles(n,:); [FilePath,FileName,FileType] = fileparts(infile{1}); % if the file cannot be found with the absolute path, try the relative path % instead if exist(infile{1},'file') ~= 2 infile_full = fullfile(RawDataDir,FilePath,[FileName FileType]); if exist(infile_full,'file') ~= 2 error('Could not find %s on absolute and relative paths',infile_full); end else infile_full = infile; end switch FileType case '.fcs' img = import_raw(infile_full); S.img_data{1} = uint8(img.ch1/255); % always save 8-bit integers S.img_data{2} = uint8(img.ch2/255); % try to decode parts of header % save bit-depth for later usage S.bits = 8; case '.tif' % TODO: new tif-import in separate file, return data cell array and % header info for n = 1:numel(infile) [FilePath,FileName,FileType] = fileparts(infile{n}); if exist(infile{n},'file') ~= 2 infile_full = fullfile(RawDataDir,FilePath,[FileName FileType]); if exist(infile_full,'file') ~= 2 error('Could not find %s on absolute and relative paths',infile{n}); end else infile_full = infile{n}; end img =tiffread2_wrapper(infile_full); S.img_data{n} = img.data; S.hdr.tifHeader{n} = img.header; if exist(strrep(infile_full,'channel00','channel01')) == 2 img =tiffread2_wrapper(strrep(infile_full,'channel00','channel01')); S.img_data{n+1} = img.data; S.hdr.tifHeader{n+1} = img.header; end if exist(strrep(infile_full,'channel00','channel02')) == 2 img =tiffread2_wrapper(strrep(infile_full,'channel00','channel02')); S.img_data{n+2} = img.data; S.hdr.tifHeader{n+2} = img.header; end end otherwise error('Unrecognized file type %s',FileType); end % creation date for infile if ~iscellstr(infile_full) dummy{1} = infile_full; infile_full = dummy; end file_pars = dir(infile_full{1}); S.hdr.createDate = file_pars.date; % other header info S.hdr.size = size(S.img_data{1}); if isempty(inargs.frame_rate) S.hdr.rate = []; else S.hdr.rate = inargs.frame_rate(n); end if isempty(inargs.zoom_factor) S.hdr.zoom = []; else S.hdr.zoom = inargs.zoom_factor(n); end S.hdr.type = inargs.img_type{n}; S.hdr.fileorigin = infile{1}; % channel ID S.hdr.channelID = cell(1,length(S.img_data)); S.hdr = orderfields(S.hdr); % RoiSet decoder if isempty(inargs.roi_set{n}) S.roi = []; else S.roi = ij_roiDecoder(inargs.roi_set{n},[S.hdr.size(1) S.hdr.size(2)]); end % Stimulation if isempty(inargs.stim{n}) S.stim = []; else S.stim = inargs.stim{n}; if length(S.stim) ~= S.hdr.size(3) warning('Stim vector length does not agree with timepoints for run %s',... int2str(n)); end end S = orderfields(S); %% Preprocessing function S = preprocStruct(inargs,n,S) % Delete frame if isempty(inargs.del_frame) if size(S.img_data{1},3) > 3 del_frame = 1; else del_frame = 0; end else del_frame = inargs.del_frame(n); end for channel = 1:length(S.img_data) S.img_data{channel} = S.img_data{channel}(:,:,del_frame+1:end); if ~isempty(S.stim) && channel == 1 S.stim = S.stim(del_frame+1:end); S.hdr.size(3) = S.hdr.size(3) - del_frame; end end S.proc.DelFrame = del_frame; % Bg. correct (on movies only) if ~isempty(inargs.bgCorrect) && strcmp(S.hdr.type,'movie') method = inargs.bgCorrect{1}; switch method case 'roi' % need to have inargs.bgCorrect{2} in roi set roiID = inargs.bgCorrect{2}; if ~isempty(S.roi) && strcmp(S.roi(:,1),roiID) arg2 = bwunpack(S.roi{strcmp(S.roi(:,1),roiID),2}); else error('Could not find Roi for bg. correction'); end otherwise arg2 = inargs.bgCorrect{2}; end for channel = 1:length(S.img_data) S.img_data{channel} = bg_subtract_HL(S.img_data{channel},arg2,... inargs.bgCorrect{3},method); end end S.proc.bgCorrect = inargs.bgCorrect; S = orderfields(S); %% save files function saveFiles(currentS,SaveDir) saveName = currentS.hdr.fileorigin; [PathName,saveName,ext] = fileparts(saveName); saveName_mean = fullfile(SaveDir,['avg_' saveName]); % saveName = fullfile(SaveDir,saveName); % save mat-format currentDir = pwd; cd(SaveDir) SaveAndAssignInBase(currentS,genvarname(saveName),'SaveOnly'); cd(currentDir) % save tiff-format (1 file per channel) if ~strcmp(ext,'.tif') for n = 1:length(currentS.img_data) chID = sprintf('ch%s',int2str(n)); img.(chID) = currentS.img_data{n}; if n == 1 % save average image for first channel only mean_img = img.(chID); mean_img = mean(mean_img,3); avg_img.img = mean_img; write_to_tif(avg_img,saveName_mean,8); end end clear currentS write_to_tif(img,saveName,8); % save as 8-bit tiff end %% Documentation % 'RawFiles' - a cellstring with relative path to any of the supported input % filetypes, supports several files, e.g. batch mode % path should be relative to the RawDataDir path specified in the .config % located in matlabroot\work (platform-independent) % or full path to files (platform-dependent) % for TIF files, mutliple channels are encoded in columns and multiple % files in rows, e.g.: % {'file1_ch1.tif' 'file1_ch2.tif'; 'file2_ch1.tif' 'file2_ch2.tif'} % 'frame_rate' - frame rate of the image acquisition (scalar or vector with % 1 value per file) % 'zoom' - zoom factor (scalar or vector) % 'type' - cellstring with image type descriptions, e.g. 'stack', 'movie', % 'frame' or 'linescan' % 'RoiSet' - cellstring with full path to IJ RoiSet.zip files for all runs % 'SaveDir' - specifies directory for saving converted files (current % directory is used if this is not specified) % 'Stim' - stimulation info as cell array with one entry per run or one % entry for all runs (default: empty) % interpretation of the stimulation protocol depends on later routines, % here we will only add the provided values to the structure % Preprocessing options % 'DelFrame' - number of frames to delete (defaults to 0 for all images % with 3 or less frames, otherwise defaults to 1), also apply to stim % vector, if any and to size vector % 'BgCorrect' - background correction specification as cell array with % {'method', param, plotFlag} --> applied with these parameters to all % movies % see bg_subtract_HL for details %
github
HelmchenLabSoftware/OCIA-master
registerImages_MIRT.m
.m
OCIA-master/caImgAnalysis/ROIStats/registerImages_MIRT.m
3,661
utf_8
a9d34819b9b436f37f06ed9e5e7bdb43
function [tranformMatrix,newImage] = registerImages_MIRT(refim, im, varargin) % wrapper for MIRT registration tools % For the MIRT info visit the project website at % https://sites.google.com/site/myronenko/research/mirt % it is safer to add MIRT dynamicaly to the path because the toolbox % shadows some native ML functions (e.g. nanmean) % in the end, folders should be removed from path again % balazsMIRTPath = 'C:\Users\laurenczy\Documents\MIRT'; % balazsMIRTPath = 'P:\matlab\dynamicPath\MIRT\'; % I changed the code so that you can specify config.balazsMIRTPath (line % 28) if nargin > 2 if isstruct(varargin{1}); config = varargin{1}; else config = getDefaultConfig; config.main.single = varargin{1}; if nargin > 3; config.main.saveName = varargin{2}; end; end; else config = getDefaultConfig; end % validate config config2 = getDefaultConfig; fields = fieldnames(config2); for n = 1:numel(fields) if ~isfield(config,fields{n}) config.(fields{n}) = config2.(fields{n}); end end if isfield(config, 'balazsMIRTPath') addpath(genpath(config.balazsMIRTPath)); else folder2add = addMIRT2path('dynamicPath/MIRT'); end % check if transformation matrix has been provided --> just apply transformation if isstruct(refim); tranformMatrix = refim; newImage = mirt2D_transform(im, tranformMatrix); if ~isfield(config, 'balazsMIRTPath'); rmpath(folder2add); else rmpath(genpath(config.balazsMIRTPath)); end; return end % equilibrate brightness ranges for both images refim = linScale(refim); im = linScale(im); try [tranformMatrix, newImage] = mirt2D_register(refim,im, config.main, config.optim); close(gcf); if ~isfield(config, 'balazsMIRTPath'); rmpath(folder2add); else rmpath(genpath(config.balazsMIRTPath)); end; catch e fprintf('Registration failed. Cleaning up path ...\n') if ~isfield(config, 'balazsMIRTPath'); rmpath(folder2add); else rmpath(genpath(config.balazsMIRTPath)); end; rethrow(e) end %% Function - getDefaultConfig function config = getDefaultConfig % these are default settings of the most important MIRT parameters % they may or may not give good results with a particular image % Main settings main.similarity='SSD'; % similarity measure, e.g. SSD, CC, SAD, RC, CD2, MS, MI main.subdivide=3; % use 3 hierarchical levels main.okno=5; % mesh window size main.lambda = 0.005; % transformation regularization weight, 0 for none main.single=1; % show mesh transformation at every iteration main.saveName = [datestr(now, 'yyyy_mm_dd__HH_MM_SS') '__RegMesh']; % figure save name % Optimization settings optim.maxsteps = 200; % maximum number of iterations at each hierarchical level optim.fundif = 1e-5; % tolerance (stopping criterion) optim.gamma = 1; % initial optimization step size optim.anneal=0.8; % annealing rate on the optimization step config.main = main; config.optim = optim; %% Function - addMIRT2path function folder2add = addMIRT2path(basePath) % check for env MATLABLOCALPATH envVarName = 'MATLABLOCALPATH'; % the name of the env var try localPath = getenv(envVarName); catch e error('Failed to load environement variable %s',envVarName) end folderList = {basePath}; folderList = strrep(folderList,'\',filesep); folderList = strrep(folderList,'/',filesep); folder2add = sprintf('%s%s%s',localPath,filesep,folderList{1}); if ~exist(folder2add,'dir') error('\nFolder %s not found.',folder2add) end folder2add = genpath(folder2add); addpath(folder2add);
github
HelmchenLabSoftware/OCIA-master
ConvertRawData.m
.m
OCIA-master/caImgAnalysis/ROIStats/ConvertRawData.m
23,529
utf_8
09b72a006a2b553e3c3efd8e14720406
function varargout = ConvertRawData(varargin) % inputs: no need to specify any inputs --> GUI-based file selection % optional input arguments, specified as 'property' 'value' pair in % arbitrary order, e.g. 'zoom',1.07 OR as a structure with properties as % field names and values, e.g. config.zoom = 1.07 % for a full list of supported arguments see the end of this file % this file written by Henry Luetcke ([email protected]) % current version: 2011-06-05 % 2011-01: added freeline 2D (focus) support % 2011-06: added AOD (J90) support (Raps and frame scans) % 2013-10: added LSM support %% Main dbgLevel = 0; % RawDataDir = getGlobalParameters('RawDataDir'); % if ~RawDataDir % error('Raw data directory MUST be specified'); % end o(' #ConvertRawData(): parsing inputs...', 2, dbgLevel); args = parseInputArgs(varargin); if min(size(args.RawFiles)) > 1 nRuns = size(args.RawFiles, 1); else nRuns = length(args.RawFiles); % make sure runs are in columns args.RawFiles = reshape(args.RawFiles, numel(args.RawFiles), 1); end o(' #ConvertRawData(): number of runs: %d.', nRuns, 1, dbgLevel); structArray = cell(1, nRuns); for iRun = 1 : nRuns; o(' #ConvertRawData(): run %d of %d...', iRun, nRuns, 2, dbgLevel); % create structure currStruct = initStruct(args, iRun); if ~isstruct(currStruct); % if an error occured continue; end; o(' #ConvertRawData(): run %d/%d: initialized structure.', iRun, nRuns, 3, dbgLevel); % preprocess image data currStruct = preprocStruct(args, iRun, currStruct); o(' #ConvertRawData(): run %d/%d: pre-processed structure.', iRun, nRuns, 3, dbgLevel); % save files saveFiles(currStruct, args.SaveDir, args); % assign in array structArray{iRun} = currStruct; o(' #ConvertRawData(): run %d/%d: saved files and assigned in array.', iRun, nRuns, 3, dbgLevel); end if nargout varargout{1} = structArray; end end %% Parse inputs function outStruct = parseInputArgs(inargs) dbgLevel = 0; o(' #ConvertRawData.parseInputArgs(): ...', 4, dbgLevel); if ~isempty(inargs) && isstruct(inargs{1}) % convert structure to pseudo-input cellarray inargs = struct2cellArray(inargs{1}); end % RawDataDir = getGlobalParameters('RawDataDir'); % input files SpInput = find(strcmpi(inargs, 'RawFiles')); if numel(SpInput) RawFiles = inargs{SpInput+1}; if ~iscellstr(RawFiles); error('Modifier for raw files property must be a cell string'); end else [FileName, PathName, ~] = uigetfile({'*.tif';'*.tiff';'*.fcs';'*.fln';'*.lsm'},... 'Select raw file(s) to import','MultiSelect','on'); if ~iscellstr(FileName) FileName = {FileName}; end if ~FileName{1}; return; end if ~iscellstr(FileName); FileName = cellstr(FileName); end % if strfind(PathName,RawDataDir) % PathName = strrep(PathName,RawDataDir,''); % end RawFiles = cell(1,length(FileName)); for n = 1:length(FileName) % interpret GUI-selected multiple files as different channels RawFiles{1, n} = fullfile(PathName, FileName{n}); end end outStruct.RawFiles = RawFiles; o(' #ConvertRawData.parseInputArgs(): RawFiles created (length: %d)...', numel(RawFiles), 5, dbgLevel); % animal ID SpInput = find(strcmpi(inargs, 'animalID')); if numel(SpInput) animalID = inargs{SpInput+1}; else animalID = ''; end outStruct.animalID = animalID; o(' #ConvertRawData.parseInputArgs(): animalID = %s...', animalID, 5, dbgLevel); % spot ID SpInput = find(strcmpi(inargs, 'spotID')); if numel(SpInput) spotID = inargs{SpInput+1}; else spotID = ''; end outStruct.spotID = spotID; o(' #ConvertRawData.parseInputArgs(): spotID = %s...', spotID, 5, dbgLevel); % frame rate SpInput = find(strcmpi(inargs, 'frame_rate')); if numel(SpInput) frame_rate = inargs{SpInput+1}; if isscalar(frame_rate) frame_rate = repmat(frame_rate,1,length(RawFiles)); else if length(frame_rate) ~= length(RawFiles) error('Frame rate must be a scalar or vector of length input file number'); end end else frame_rate = []; end outStruct.frame_rate = frame_rate; % zoom SpInput = find(strcmpi(inargs, 'zoom')); if numel(SpInput) zoom_factor = inargs{SpInput+1}; if isscalar(zoom_factor) zoom_factor = repmat(zoom_factor,1,length(RawFiles)); else if length(zoom_factor) ~= length(RawFiles) error('Zoom must be a scalar or vector of length input file number'); end end else zoom_factor = []; end outStruct.zoom_factor = zoom_factor; % laser power SpInput = find(strcmpi(inargs, 'laserPower')); if numel(SpInput) laserPower = inargs{SpInput+1}; if isscalar(laserPower) laserPower = repmat(laserPower,1,length(RawFiles)); else if length(laserPower) ~= length(RawFiles) error('Laser power must be a scalar or vector of length input file number'); end end else laserPower = []; end outStruct.laserPower = laserPower; % image type SpInput = find(strcmpi(inargs, 'type')); if numel(SpInput) img_type = inargs{SpInput+1}; if ~iscellstr(img_type); img_type = cellstr(img_type); end if length(img_type) == 1 img_type = repmat(img_type,1,length(RawFiles)); elseif length(img_type) ~= length(RawFiles) error('Image type must be a cell string of length 1 or input file number'); end else img_type = {'movie'}; img_type = repmat(img_type,1,length(RawFiles)); % img_type = cell(1,length(RawFiles)); end outStruct.img_type = img_type; % Roi set SpInput = find(strcmpi(inargs, 'RoiSet')); if numel(SpInput) roi_set = inargs{SpInput+1}; if iscell(roi_set) && size(roi_set, 2) == 2; % all okay, ROISet with 2 columns: names and ROIMasks for each ROI else if ~iscellstr(roi_set); roi_set = cellstr(roi_set); end if length(roi_set) == 1 roi_set = repmat(roi_set,1,length(RawFiles)); elseif length(roi_set) ~= length(RawFiles) error('RoiSet must be a cell string of length 1 or input file number'); end end; else roi_set = cell(1,length(RawFiles)); end outStruct.roi_set = roi_set; % Reference image SpInput = find(strcmpi(inargs, 'RefImg')); if numel(SpInput) refImg = inargs{SpInput + 1}; if ischar(refImg); % okay will be loaded later elseif isnumeric(refImg); % already loaded image else error('refImg must be a file name or a loaded reference image !'); end else refImg = ''; end outStruct.refImg = refImg; % Stimulus SpInput = find(strcmpi(inargs, 'Stim')); if numel(SpInput) stim = inargs{SpInput+1}; if ~iscell(stim); stim = {stim}; end if length(stim) == 1 && length(RawFiles) > 1 stim = repmat(stim,1,length(RawFiles)); elseif length(stim) ~= length(RawFiles) error('Stimulation must be a cell array of length 1 or input file number'); end else stim = cell(1,length(RawFiles)); end outStruct.stim = stim; % Ephys SpInput = find(strcmpi(inargs, 'Ephys')); if numel(SpInput) ephys = inargs{SpInput+1}; if ~iscell(ephys) || length(ephys) ~= length(RawFiles) error('Ephys must be a cell array of length input file number'); end outStruct.ephys = ephys; end % Output directory SpInput = find(strcmpi(inargs, 'SaveDir')); if numel(SpInput) SaveDir = inargs{SpInput+1}; if exist(SaveDir,'dir') ~= 7 try mkdir(SaveDir); catch e error('Failed to create directory %s',SaveDir); end end else SaveDir = pwd; end outStruct.SaveDir = SaveDir; % color vector SpInput = find(strcmpi(inargs, 'ColorVector')); if numel(SpInput) outStruct.ColorVector = inargs{SpInput+1}; else outStruct.ColorVector = [2 1 0]; end % Dimensions - usually not necessary to specify, except for freeline 2d % focus in which case dims should be specified as [columns rows] SpInput = find(strcmpi(inargs, 'Dims')); if numel(SpInput) outStruct.dims = inargs{SpInput+1}; else switch outStruct.img_type{1} case 'free2d_focus' error('Must always specify image dimensions for freeline 2D focus.'); end end % Position - can be created with makePositionStructure SpInput = find(strcmpi(inargs, 'Position')); if numel(SpInput) outStruct.position = inargs{SpInput+1}; else outStruct.position = makePositionStructure; end % Preprocessing options - delete frame SpInput = find(strcmpi(inargs, 'DelFrame')); if numel(SpInput) del_frame = inargs{SpInput+1}; if isscalar(del_frame) del_frame = repmat(del_frame,1,length(RawFiles)); else if length(del_frame) ~= length(RawFiles) error('DelFrame must be a scalar or vector of length input file number'); end end else del_frame = []; end outStruct.del_frame = del_frame; % bg. correction SpInput = find(strcmpi(inargs, 'BgCorrect')); if numel(SpInput) bgCorrect = inargs{SpInput+1}; else bgCorrect = []; end outStruct.bgCorrect = bgCorrect; end %% Structure initialization function S = initStruct(inargs, iRun) dbgLevel = 0; o(' #ConvertRawData#initStruct(): run %d...', iRun, 4, dbgLevel); infile = inargs.RawFiles(iRun, :); [FilePath,FileName,FileType] = fileparts(infile{1}); % if the file cannot be found with the absolute path, try the relative path % instead if exist(infile{1},'file') ~= 2 infile_full = fullfile(FilePath,[FileName FileType]); if exist(infile_full,'file') ~= 2 warning('initStruct:FileNotFound', 'Could not find %s on absolute and relative paths', infile_full); S = []; return; % error('Could not find %s on absolute and relative paths',infile_full); end else infile_full = infile; end S.hdr.animalID = inargs.animalID; S.hdr.spotID = inargs.spotID; S.hdr.laserPower = inargs.laserPower; S.hdr.refImg = inargs.refImg; S.hdr.frame_rate = inargs.frame_rate; S.hdr.position = inargs.position; switch FileType case {'.fcs','.fln'} switch inargs.img_type{iRun} case 'free2d_focus' img = import_raw(infile_full,inargs.dims(1),inargs.dims(2),768); S.img_data{1} = uint8(img.ch1/255); % always save 8-bit integers S.img_data{2} = uint8(img.ch2/255); otherwise img = import_raw(infile_full); S.img_data{1} = uint8(img.ch1/255); % always save 8-bit integers S.img_data{2} = uint8(img.ch2/255); % try to decode parts of header end % save bit-depth for later usage S.hdr.bits = 8; case '.tif' % TODO: new tif-import in separate file, return data cell array and % header info for m = 1:numel(infile) [FilePath,FileName,FileType] = fileparts(infile{m}); if exist(infile{m},'file') ~= 2 infile_full = fullfile(FilePath,[FileName FileType]); if exist(infile_full,'file') ~= 2 error('Could not find %s on absolute and relative paths',infile{iRun}); end else infile_full = infile{iRun}; end img =tiffread2_wrapper(infile_full); S.img_data{m} = img.data; S.hdr.tifHeader{m} = img.header; if ~isempty(strfind(infile_full,'channel00')) if exist(strrep(infile_full,'channel00','channel01'), 'file') == 2 img =tiffread2_wrapper(strrep(infile_full,'channel00','channel01')); S.img_data{m+1} = img.data; S.hdr.tifHeader{m+1} = img.header; end if exist(strrep(infile_full,'channel00','channel02'), 'file') == 2 img =tiffread2_wrapper(strrep(infile_full,'channel00','channel02')); S.img_data{m+2} = img.data; S.hdr.tifHeader{m+2} = img.header; end end clear img % additional files - AOD J90 switch inargs.img_type{m} case {'aod_raps','aod_frame'} dims = size(S.img_data{m}); % split up channels (assume 3 channels are stored) FramesPerChannel = dims(3) / 3; currentChannel = 1; pos = 0; switch inargs.img_type{m} case {'aod_raps'} imgData = {zeros(dims(1)*FramesPerChannel,dims(2))}; otherwise imgData = {zeros(dims(1),dims(2),FramesPerChannel)}; end imgData = repmat(imgData,1,3); for frame = 1:dims(3) if pos == FramesPerChannel currentChannel = currentChannel + 1; pos = 1; else pos = pos + 1; end switch inargs.img_type{m} case {'aod_raps'} imgData{currentChannel}((dims(1)*(pos-1))+1:dims(1)*pos,:) = ... S.img_data{m}(:,:,frame); otherwise imgData{currentChannel}(:,:,pos) = ... S.img_data{m}(:,:,frame); end end S.img_data = imgData; clear imgData if exist(strrep(infile_full,'.tif','_RAData.txt'), 'file') == 2 S.hdr.RAData = importdata(strrep(infile_full,'.tif','_RAData.txt')); end if exist(strrep(infile_full,'.tif','_FOV.png'), 'file') == 2 S.hdr.FOV = importdata(strrep(infile_full,'.tif','_FOV.png')); end end end S.hdr.bits = 16; case '.lsm' % Zeiss LSM file format for m = 1:numel(infile) [FilePath,FileName,FileType] = fileparts(infile{m}); if exist(infile{m},'file') ~= 2 infile_full = fullfile(FilePath,[FileName FileType]); if exist(infile_full,'file') ~= 2 error('Could not find %s on absolute and relative paths',infile{iRun}); end else infile_full = infile{iRun}; end img = readLSMfile(infile_full); S.img_data{m} = img.data; S.hdr.tifHeader{m} = img.hdr; % header info S.hdr.bits = img.hdr.scaninf.BITS_PER_SAMPLE; S.hdr.frame_rate = 1./img.hdr.lsminf.TimeInterval; S.hdr.laserPower = img.hdr.scaninf.LASER_POWER; clear img end otherwise error('Unrecognized file type %s',FileType); end % creation date for infile if ~iscellstr(infile_full) dummy{1} = infile_full; infile_full = dummy; end file_pars = dir(infile_full{1}); S.hdr.createDate = file_pars.date; % other header info S.hdr.size = size(S.img_data{1}); % if isempty(inargs.frame_rate) % S.hdr.rate = []; % if isfield(S.hdr,'tifHeader') && isfield(S.hdr.tifHeader{1,1},'info') % if isempty(strcmp(S.hdr.tifHeader{1,1}.info,'Failed to read XML header')) % S.hdr.rate = 1 / str2double(S.hdr.tifHeader{1,1}.info.TimeIncrement); % end % end % else % S.hdr.rate = inargs.frame_rate(iRun); % end if isempty(inargs.zoom_factor) S.hdr.zoom = []; else S.hdr.zoom = inargs.zoom_factor(iRun); end S.hdr.type = inargs.img_type{iRun}; S.hdr.fileorigin = infile{1}; % channel ID S.hdr.channelID = cell(1,length(S.img_data)); S.hdr = orderfields(S.hdr); % RoiSet decoder if isempty(inargs.roi_set{iRun}) S.roi = []; elseif exist(inargs.roi_set{iRun}, 'file'); S.roi = ij_roiDecoder(inargs.roi_set{iRun},[S.hdr.size(1) S.hdr.size(2)]); S.roi = ij_RoiSetCompression(S.roi,1); elseif iscell(inargs.roi_set) && size(inargs.roi_set, 2) == 2; S.roi = inargs.roi_set; end % Stimulation if isempty(inargs.stim{iRun}) S.stim = []; else S.stim = inargs.stim{iRun}; % only display warning if stim is a vector, not a structure. if ~isstruct(S.stim) && length(S.stim) ~= S.hdr.size(3); warning('Stim vector length does not agree with timepoints for run %s',... int2str(iRun)); end end if isfield(inargs,'ephys') S.ephys = inargs.ephys{iRun}; end S = orderfields(S); end %% Preprocessing function S = preprocStruct(inargs,n,S) % Delete frame if isempty(inargs.del_frame) if size(S.img_data{1},3) > 3 del_frame = 1; else del_frame = 0; end else del_frame = inargs.del_frame(n); end for channel = 1:length(S.img_data) switch inargs.img_type{n} case {'free2d_focus','aod_raps'} S.img_data{channel} = S.img_data{channel}(del_frame+1:end,:); otherwise S.img_data{channel} = S.img_data{channel}(:,:,del_frame+1:end); end end % adjust stimulus protocol % if ~isempty(S.stim) % if isstruct(S.stim) % S.stim.vector(1:round(1/S.hdr.rate*del_frame*S.stim.rate)) = []; % elseif isvector(S.stim) % assume vector already converted to frames % S.stim = S.stim(del_frame+1:end); % end % end switch inargs.img_type{n} case 'free2d_focus' S.hdr.size(1) = S.hdr.size(1) - del_frame; otherwise if length(S.hdr.size) > 2 S.hdr.size(3) = S.hdr.size(3) - del_frame; end end % adjust ephys if isfield(S,'ephys') S.ephys.data(1:round(1/S.hdr.rate*del_frame*S.ephys.rate)) = []; end S.proc.DelFrame = del_frame; % Bg. correct if ~isempty(inargs.bgCorrect) method = inargs.bgCorrect{1}; switch method case 'roi' % need to have inargs.bgCorrect{2} in roi set roiID = inargs.bgCorrect{2}; if ~isempty(S.roi) && strcmp(S.roi(:,1),roiID) arg2 = bwunpack(S.roi{strcmp(S.roi(:,1),roiID),2}); else error('Could not find Roi for bg. correction'); end otherwise arg2 = inargs.bgCorrect{2}; end for channel = 1:length(S.img_data) S.img_data{channel} = bg_subtract_HL(S.img_data{channel},arg2,... inargs.bgCorrect{3},method); end end S.proc.bgCorrect = inargs.bgCorrect; S = orderfields(S); end %% save files function saveFiles(currentS,SaveDir,args) saveName = currentS.hdr.fileorigin; [~, saveName, ext] = fileparts(saveName); saveName_mean = fullfile(SaveDir,[saveName '__avg']); saveName = fullfile(SaveDir,saveName); saveName = strrep(saveName,'__channel00',''); % saveName_mean = strrep(saveName_mean,'__channel00',''); if currentS.hdr.bits == 8 for n = 1:numel(currentS.img_data) currentS.img_data{n} = uint8(currentS.img_data{n}); end else for n = 1:numel(currentS.img_data) currentS.img_data{n} = uint16(currentS.img_data{n}); end end % save mat-format SaveAndAssignInBase(currentS,saveName,'SaveOnly'); % save average images if isempty(strfind(args.img_type{1},'aod_raps')) mean_img = cell(1, numel(currentS.img_data)); for n = 1:numel(currentS.img_data) chID = sprintf('ch%s',int2str(n)); mean_img{n} = currentS.img_data{n}; switch args.img_type{1} case 'free2d_focus' mean_img{n} = mean(mean_img{n}); mean_img{n} = repmat(mean_img{n},numel(mean_img{n}),1); otherwise mean_img{n} = mean(mean_img{n},3); end if strcmp(ext,'.tif') avg_img.img = mean_img{n}; chID = sprintf('channel%02.0f',n-1); currentSaveName_mean = strrep(saveName_mean,'channel00',chID); if isempty(strfind(args.img_type{1},'aod_frame')) write_to_tif(avg_img,currentSaveName_mean); end else avg_img.(chID) = mean_img{n}; % write below end end end % RGB merge (multi-channel only) if ~strcmp(args.img_type{1},'aod_raps') && numel(mean_img) > 1 if args.ColorVector(1) red = linScale(mean_img{args.ColorVector(1)}); else red = zeros(size(mean_img{1})); end if args.ColorVector(2) green = linScale(mean_img{args.ColorVector(2)}); else green = zeros(size(mean_img{1})); end if args.ColorVector(3) blue = linScale(mean_img{args.ColorVector(3)}); else blue = zeros(size(mean_img{1})); end rgb.data = cat(3,red,green,blue); if isempty(strfind(saveName_mean,'channel00__')) currentSaveName_mean = [saveName_mean '_RGB']; else currentSaveName_mean = strrep(saveName_mean,'channel00__','RGB'); end write_to_tif(rgb,currentSaveName_mean) end % save tiff-format (1 file per channel) for fcs files if strcmp(strtrim(ext),'.fcs') for n = 1:length(currentS.img_data) chID = sprintf('ch%s',int2str(n)); img.(chID) = currentS.img_data{n}; end clear currentS write_to_tif(img,saveName,8); % save as 8-bit tiff saveName = [saveName '__avg']; write_to_tif(avg_img,saveName,8); end; end %% Documentation % 'RawFiles' - a cellstring with relative path to any of the supported input % filetypes, supports several files, e.g. batch mode % path should be relative to the RawDataDir path specified in the .config % located in matlabroot\work (platform-independent) % or full path to files (platform-dependent) % for TIF files, mutliple channels are encoded in columns and multiple % files in rows, e.g.: % {'file1_ch1.tif' 'file1_ch2.tif'; 'file2_ch1.tif' 'file2_ch2.tif'} % 'frame_rate' - frame rate of the image acquisition (scalar or vector with % 1 value per file) % 'zoom' - zoom factor (scalar or vector) % 'type' - cellstring with image type descriptions, e.g. 'stack', 'movie', % 'frame' or 'linescan' % 'RoiSet' - cellstring with full path to IJ RoiSet.zip files for all runs % OR ROISet cell array with 2 columns: names and ROIMasks % 'SaveDir' - specifies directory for saving converted files (current % directory is used if this is not specified) % 'Stim' - stimulation info as cell array with one entry per run or one % entry for all runs (default: empty) % interpretation of the stimulation protocol depends on later routines, % here we will only add the provided values to the structure % 'animalID' % 'spotID' % 'zoom' % 'laserPower' % 'Position' - Position structure with fields of 'units' (e.g. % 'pixel','um'), spotCoordinates (1x3 vector), refCoordinates (nx3 matrix), % refID (cellstring with ID for n reference coordinates), specifiy NaN for % coordinates that are not available - use makePositionStructure to create % 'ephys' - ephys as cell array with one entry per run; provide ephys data % structure for each run with (at least) two fields: % ephys.data ... the recorded data as vector % ephys.rate ... the sampling rate for ephys recording % Preprocessing options % 'DelFrame' - number of frames to delete (defaults to 0 for all images % with 3 or less frames, otherwise defaults to 1), also apply to stim % vector, if any, to size vector and to ephys, if any % 'BgCorrect' - background correction specification as cell array with % {'method', param, plotFlag} --> applied with these parameters to all % movies % see bg_subtract_HL for details
github
HelmchenLabSoftware/OCIA-master
GetRoiStats.m
.m
OCIA-master/caImgAnalysis/ROIStats/GetRoiStats.m
30,729
utf_8
40f7e00ec7f7217d038af19be260c737
function varargout = GetRoiStats(config) % get ROI timecourses from images, with support for muliple ROIs and runs % returns structure data, info and stimulus fields % data field contains a cell array with ROI timecourses for different cells % in rows and different runs in columns: % [cell1_run1] [cell1_run2] ... [cell1_runN] % [cell2_run1] [cell2_run2] ... [cell2_runN] % ... ... ... % [cellN_run1] [cellN_run2] ... [cellN_runN] % assume raw data structure specified as mat-files wih fields: % img_data ... cell array for image data (each channel in one cell) % roi ... imageJ roi set % stim ... stimulus vector (at frame rate, i.e. 1 value per frame) % hdr ... header information % proc ... preprocessing information (e.g. how many frames have been deleted) % this file written by Henry Luetcke ([email protected]) dbgLevel = 1; %% GetRoiStats - Inititialization % parse the configuration structure config = ParseConfig(config); o('#GetRoiStats(): %d file(s) to process...', numel(config.matFiles), 1, dbgLevel); % init some parameters [config, matFiles] = initParams(config, dbgLevel); o('#GetRoiStats(): parameters initialized.', 2, dbgLevel); % init some more parameters nRuns = config.nRuns; ROISet = []; imgDims = cell(nRuns, 1); config.runFileIDs = cell(nRuns, 1); matFileStructs = cell(1, nRuns); %% GetRoiStats - Create common ROISet o('#GetRoiStats(): processing %d runs...', config.nRuns, 2, dbgLevel); for iRun = 1 : nRuns; o(' #GetRoiStats(): processing run %d/%d (%s) ...', iRun, nRuns, matFiles{iRun}, 2, dbgLevel); % make sure the mat file exists if ~exist(matFiles{iRun}, 'file'); warning('GetRoiStats:FileNotFound', 'Could not find mat-file "%s", skipping run %d.', ... matFiles{iRun}, iRun); continue; end; %% GetRoiStats --- Initialize run % load the mat-file for this run and store it (avoids reloading it in the next for-loop) % also assign a "fileID" name for that run (date + time withouth '.mat') fileID = strrep(matFiles{iRun}, '.mat', ''); matFileWrapper = load(matFiles{iRun}); matFileStruct = matFileWrapper.(genvarname(fileID)); matFileStruct.hdr.fileID = fileID; config.runFileIDs{iRun} = fileID; matFileStructs{iRun} = matFileStruct; %% GetRoiStats --- Extract ROIs, calculate mean point and merge % load ROIs as a cell-array with ROI IDs and their masks localROISet = matFileStruct.roi; % process each ROI for mean (middle) point calculation for iLocalROI = 1 : size(localROISet, 1); ROIMask = localROISet{iLocalROI, 2}; if isa(ROIMask, 'uint32'); ROIMask = bwunpack(ROIMask); end; % calculate mean (middle) point's coordinate [ROIYCoords, ROIXCoords] = find(ROIMask == 1); localROISet{iLocalROI, 3} = [mean(ROIYCoords), mean(ROIXCoords)]; end; % if no general ROISet is available, use the first one encountered if isempty(ROISet); ROISet = localROISet; % otherwise merge the ROISets else % search through each local ROISet if it exists in the global ROISet for iLocalROI = 1 : size(localROISet, 1); localROIID = localROISet{iLocalROI, 1}; % if local (new) ROI doesn't exist in the global ROISet if ~ismember(localROIID, ROISet(:, 1)); % add it to the global ROISet ROISet(end + 1, 1 : 3) = localROISet(iLocalROI, :); %#ok<AGROW> end; end; end; end; % add the neuropil as an ROI [ROISet, ~] = addNPilROIToROISet(ROISet, 0.15); % store the merged ROIs (with neuropil) config.ROISet = ROISet; %% GetRoiStats - Process runs ROIStatsData = cell(size(ROISet, 1), nRuns); o('#GetRoiStats(): processing %d runs...', config.nRuns, 2, dbgLevel); for iRun = 1 : nRuns; % retrieve the stored matFileStruct matFileStruct = matFileStructs{iRun}; fileID = config.runFileIDs{iRun}; o(' #GetRoiStats(): processing run %d/%d (%s)...', iRun, nRuns, fileID, 2, dbgLevel); % initialize containers for the imaging data (recorded movies) currImgData = cell(1, length(config.channelVector)); currMeanImgData = cell(1, length(config.channelVector)); imgDims{iRun} = config.img_dims; o(' #GetRoiStats(): run %d/%d: ROIs extracted.', iRun, nRuns, 4, dbgLevel); %% GetRoiStats --- Image registration + channel switching % check size of movie and ROISet, must be same if any(size(ROISet{1, 2}) ~= matFileStruct.hdr.size(1:2)); o(' #GetRoiStats(): run %d/%d: image registration required... (size of ROI != movie).', ... iRun, nRuns, 4, dbgLevel); matFileStruct = doImageReg(matFileStruct, config); imgDims{iRun} = [size(matFileStruct.img_data{1}, 1) size(matFileStruct.img_data{1}, 2)]; end; o(' #GetRoiStats(): run %d/%d: image registration done.', iRun, nRuns, 3, dbgLevel); %% GetRoiStats --- Image averaging % image data is already arranged here as specified in channelVector. CH1 and CH2 are always % ordered in the same way from here to the end : % DFF is calculated on channel 1, DRR is ch1 / ch2 for iChan = 1 : numel(matFileStruct.img_data) % make sure we have double data type (might be stored as int16 / int8) currImgData{iChan} = double(matFileStruct.img_data{iChan}); % also store a mean image for display of Rois currMeanImgData{iChan} = mean(currImgData{iChan}, 3); end; %% GetRoiStats --- PseudoFlatField correct image if config.doFlatfield; % correct the image's intensity using the "PseudoFlatfieldCorrect" (gaussian filtering) currSegmImg = PseudoFlatfieldCorrect(currMeanImgData{1}); currSegmImg(currSegmImg < 0) = 0; else currSegmImg = currMeanImgData{1}; end; o(' #GetRoiStats(): run %d/%d: Pseudo-flat field correction done.', ... iRun, nRuns, 3, dbgLevel); %% GetRoiStats --- Check ROI presence in current run % reload the ROIs localROISet = matFileStruct.roi; % check the presence of each global ROI in the local ROISet ROISet(:, 4) = cellfun(@(ROIID){ismember(ROIID, localROISet(:, 1))}, ROISet(:, 1)); %% GetRoiStats --- Plot ROIs on RGB image if config.doSaveROIRGBPlot; o(' #GetRoiStats(): run %d/%d: Plotting ROIs on RGB ...', iRun, nRuns, 3, dbgLevel); ROIRGBHand = doROIRGBPlot(imgDims{iRun}, localROISet, currSegmImg, currMeanImgData, fileID, 0.7); if config.doSaveROIRGBPlot > 1; if exist('ROIRGB', 'dir') ~= 7; mkdir('ROIRGB'); end; saveas(ROIRGBHand, sprintf('ROIRGB/%s__ROIRGB', fileID)); saveas(ROIRGBHand, sprintf('ROIRGB/%s__ROIRGB.png', fileID)); close(ROIRGBHand); end; end; nFrames = size(currImgData{1}, 3); o(' #GetRoiStats(): run %d/%d: %d frame(s).', iRun, nRuns, nFrames, 3, dbgLevel); %% GetRoiStats --- ROI and neuropil analysis o(' #GetRoiStats(): run %d/%d: ROI analysis...', iRun, nRuns, 3, dbgLevel); % go through each ROI (and neuropil) and extract the ROIStats from them for iROI = 1 : size(ROISet, 1); % if ROI was not present in this run and is not the neuropil, don't process it if ~strcmp('NPil', ROISet{iROI, 1}) && ~ROISet{iROI, 4}; continue; end; ROIMask = ROISet{iROI, 2}; % for neuropil, use the ROIMask from the localROISet if strcmp('NPil', ROISet{iROI, 1}); [localROISetWithNPil, ~] = addNPilROIToROISet(localROISet, 0.15); ROIMask = localROISetWithNPil{strcmp('NPil', localROISetWithNPil(:, 1)), 2}; end; doSaveF0ExtractPlot = config.doSaveF0AndExtractPlot; if iROI ~= 1 && rand(1) > 0.05; % draw the plot with 5% chance doSaveF0ExtractPlot = 0; end; % store roi data ROIStatsData{iROI, iRun} = extractROIStats(currImgData, ROIMask, ... config.statsType, config.LowPass, config.HiPass, config.f0, ... sprintf('%s_F0AndExtract_run%d_ROI%d', config.saveName, iRun, iROI), ... doSaveF0ExtractPlot); end; clear ROIYCoords ROIXCoords fileID; end %% GetRoiStats - End of runs processing % copy stuff in the config, assuming things were similar over all runs... config.img_dims = imgDims(1); config.ROISet = ROISet; config.ROIStatsData = ROIStatsData; % config.freqIDs = 1.0e+03 * [5, 9, 13, 17, 21, 25, 29, 33, 37, 41]; % config.freqIDs = 4000 * (2 .^ (((1 : 15) - 1) * 0.25)); % config.plotLimits = [-1 5]; %% GetRoiStats - Config saving saveName = sprintf('%s_ROIStats', config.saveName); o(' #GetRoiStats(): saving ROIStats under "%s"...', saveName, 3, dbgLevel); SaveAndAssignInBase(config, saveName); o(' #GetRoiStats(): ROIStats saving done.', 2, dbgLevel); if nargout; varargout{1} = config; end; end %% Function - doImageReg function matFileStruct = doImageReg(matFileStruct, config) % Perform non-linear registration of movie to hign resolution image % Note that at this stage, the channel order should NOT yet be adjusted % according to config.ChannelVector % Registration performs the following steps: % 1. Identify reference image channel and average multiple frames (if any) % 2. Resize all movie channels to the xy-dims of the reference image --> % this is the minimum processing that needs to be done, so that image % dimensions are consistent for downstream analysis; if the reference image % is for example the average of each movie, then registration could stop % at this point % 3. Average all frames of movie in registration channel % 4. Register movie average to reference image using non-linear image % registration tool MIRT % 5. Check quality of the registration % 6. Apply transformation matrix to all frames of all channels and write % the result back into S.img_data dbgLevel = 3; if config.reg.doRegistration; o(' #GetRoiStats.doImageReg(): doing image up-sampling AND registration ...', 2, dbgLevel); else o(' #GetRoiStats.doImageReg(): doing image up-sampling only (no registration) ...', 2, dbgLevel); end; % get the reference image using the channels specified in the config refImg = getRefOrRegImage(matFileStruct.hdr.fileID, 'Reference', ... matFileStruct.refImg, config, config.reg.doSaveRefImagePlot, dbgLevel); refDims = size(refImg); nChan = numel(matFileStruct.img_data); nFrames = size(matFileStruct.img_data{1}, 3); % if no matlab pool open or in a worker, use standard for loop, other use parfor useParfor = matlabpool('size') && isempty(javachk('desktop')); % upsample movie to refImg upSampleTic = tic; % for performance timing purposes for iChan = 1 : nChan; o(' #Get...ImageReg(): up-sampling channel %d/%d (useParfor = %d) ...', ... iChan, nChan, useParfor, 2, dbgLevel); origCh = matFileStruct.img_data{iChan}; upSampImg = zeros(refDims(1), refDims(2), nFrames); if useParfor; parfor iFrame = 1 : nFrames; upSampImg(:, :, iFrame) = imresize(origCh(:, :, iFrame), refDims); end; else for iFrame = 1 : nFrames; upSampImg(:, :, iFrame) = imresize(origCh(:, :, iFrame), refDims); end; end; matFileStruct.img_data{iChan} = upSampImg; end; o(' #Get...ImageReg(): up-sampling done (%.2f seconds).', toc(upSampleTic), 1, dbgLevel); if ~config.reg.doRegistration; return; end; o(' #Get...ImageReg(): registration required: doRegistration = %d.', ... config.reg.doRegistration, 2, dbgLevel); % get the registration image using the registration channel(s) specified in the config regImg = getRefOrRegImage(matFileStruct.hdr.fileID, 'Registration', ... matFileStruct.img_data, config, config.reg.doSaveRegImagePlot, dbgLevel); if ~isfield(matFileStruct, 'tform') || isempty(matFileStruct.tform); o(' #Get...ImageReg(): transform matrix (tform) not present. ', 2, dbgLevel); o(' #Get...ImageReg(): running registration to create it ... ', 2, dbgLevel); tFormCreateTic = tic; % for performance timing purposes config.reg.main.single = config.reg.doSaveRegProgressPlot; config.reg.main.saveName = sprintf('%s__RegMesh', matFileStruct.hdr.fileID); % run registration [tform, newImg] = registerImages_MIRT(refImg, regImg, config.reg); % display overlay if config.reg.doSaveRegOverlayPlot; hReg = figure('Name', sprintf('Image Registration Overlay for %s', matFileStruct.hdr.fileID), ... 'NumberTitle', 'off'); subplot(1, 2, 1); imshowpair(refImg, edge(regImg,'canny'), 'method', 'blend'); title('Reference - Input overlay'); subplot(1, 2, 2); imshowpair(refImg, edge(newImg,'canny'), 'method', 'blend'); title('Reference - Registered overlay'); % save if required if config.reg.doSaveRegOverlayPlot > 1; if exist('RegOverlay', 'dir') ~= 7; mkdir('RegOverlay'); end; saveas(hReg, sprintf('RegOverLay/%s__ImgRegOvl', matFileStruct.hdr.fileID)); saveas(hReg, sprintf('RegOverLay/%s__ImgRegOvl.png', matFileStruct.hdr.fileID)); close(hReg); end; end; matFileStruct.tform = tform; % save tform into original mat-file (image data already resized) S2 = load(matFileStruct.hdr.fileID); data2 = S2.(genvarname(matFileStruct.hdr.fileID)); data2.tform = tform; SaveAndAssignInBase(data2,matFileStruct.hdr.fileID,'SaveOnly') clear data2 S2; o(' #Get...ImageReg(): transform matrix (tform) created (%.2f seconds).', ... toc(tFormCreateTic), 2, dbgLevel); else o(' #Get...ImageReg(): transform matrix (tform) already present.', 2, dbgLevel); tform = matFileStruct.tform; end; % apply transformation only on channels required by the channelVector tFormApplyTic = tic; % for performance timing purposes oriImg_data = matFileStruct.img_data; nChanForApply = numel(config.channelVector); matFileStruct.img_data = {}; % clear the previous data for iChan = 1 : nChanForApply; tFormApplyChanTic = tic; % for performance timing purposes o(' #Get...ImageReg(): Applying transformation to channel %d (useParfor = %d) ...', ... config.channelVector(iChan), useParfor, 2, dbgLevel); origCh = oriImg_data{config.channelVector(iChan)}; newCh = zeros(size(oriImg_data{config.channelVector(iChan)})); if useParfor; parfor iFrame = 1 : nFrames; [~ ,newCh(:, :, iFrame)] = registerImages_MIRT(tform, origCh(:, :, iFrame), config.reg); %#ok<PFBNS> end; else for iFrame = 1 : nFrames; [~, newCh(:, :, iFrame)] = registerImages_MIRT(tform, origCh(:, :, iFrame), config.reg); end; end; o(' #Get...ImageReg(): Applied transf. to chan. %d on %d frame(s) (%.2f seconds).', ... config.channelVector(iChan), nFrames, toc(tFormApplyChanTic), 2, dbgLevel); matFileStruct.img_data{iChan} = newCh; end; o(' #Get...ImageReg(): Applied transf. to %d channel(s) on %d frame(s) (%.2f seconds).', ... nChanForApply, nFrames, toc(tFormApplyTic), 1, dbgLevel); % plot the applied transformations if config.reg.doSaveRegComparisonPlot; figHand = figure('NumberTitle', 'off', 'Name', ... sprintf('Registration comparison for %s', matFileStruct.hdr.fileID)); subplot(nChanForApply + 1, 2, 1); imshow(linScale(regImg), []); title('Registration image'); subplot(nChanForApply + 1, 2, 2); imshow(linScale(refImg), []); title('Reference image'); for iChan = 1 : nChanForApply; % plot the mean image before subplot(nChanForApply + 1, 2, iChan * 2 + 1); imshow(linScale(mean(oriImg_data{iChan}, 3)), []); title(sprintf('Channel %d before transformation', config.channelVector(iChan))); subplot(nChanForApply + 1, 2, iChan * 2 + 2); imshow(linScale(mean(matFileStruct.img_data{iChan}, 3)), []); title(sprintf('Channel %d after transformation', config.channelVector(iChan))); end; suptitle(sprintf('Registration comparison of %s', strrep(matFileStruct.hdr.fileID, '_', '\_'))); % save if required if config.reg.doSaveRegComparisonPlot > 1; if exist('RegComparison', 'dir') ~= 7; mkdir('RegComparison'); end; saveas(figHand, sprintf('RegComparison/%s__RegComp', matFileStruct.hdr.fileID)); saveas(figHand, sprintf('RegComparison/%s__RegComp.png', matFileStruct.hdr.fileID)); close(figHand); end; end; for iChan = 1 : nChanForApply; o(' #Get...ImageReg(): Channels numbering change : chan %d / %d is now chan %d / %d.', ... config.channelVector(iChan), nChan, iChan, nChanForApply, 1, dbgLevel); end; end %% Function - ParseConfig function config = ParseConfig(config) % check for missing fields in config structure and add them with default values if ~isfield(config, 'matFiles') matFiles = sort(uigetfile('*.mat', 'Select Mat Files', 'MultiSelect', 'on')); config.matFiles = strrep(matFiles, '.mat', ''); else matFiles = config.matFiles; end if ~isfield(config,'saveName') config.saveName = [matFiles{1} '__ROIStats']; end if ~isfield(config,'statsType') config.statsType = 'dff'; end % BL - 2013-06-27 : added this field because it was missing if ~isfield(config,'roi') config.roi = struct; end % channels for stats calculation % DFF is calculated on the channel specified by config.channelVector(1) % DRR is calculated on the channels specified by config.channelVector(1) % and config.channelVector(2) if ~isfield(config,'channelVector') config.channelVector = [1 2]; end if strcmpi(config.statsType,'drr') && numel(config.channelVector) < 2 error('config.channelVector must specify at least 2 channels for DRR stats!'); end % if ~isfield(config,'npilCorrect') % config.npilCorrect = 0.2; % end % if ~isfield(config,'recycleNpilMovie') % config.recycleNpilMovie = 0; % end if ~isfield(config,'doFlatfield') config.doFlatfield = 0; end if ~isfield(config,'doOgbSRsegmentation') config.doOgbSRsegmentation = 0; end if config.doOgbSRsegmentation if ~isfield(config,'OgbChannel') config.OgbChannel = 1; end if ~isfield(config,'SrChannel') config.SrChannel = 2; end end if ~isfield(config,'segOptions') config.segOptions = struct; end if ~isfield(config,'psFrames') config.psFrames = struct; config.psFrames.base = 5; config.psFrames.evoked = 15; end % low-pass filter if ~isfield(config,'LowPass') config.LowPass.method = 'none'; config.LowPass.params = [0.5 1]; end % LowPass.method may take the following values: % 'none' ... no low-pass filtering is applied % 'sg' ... savitzky-golay filter, as implemented in ML % LowPass.params is a vector with filter parameters, depending on the % specific filter (all cutoffs should be defined in s) % for SG, params are [lpFilterCutoff filterOrder] % high-pass filter if ~isfield(config,'HiPass') config.HiPass.method = 'polyFit'; config.HiPass.polyOrder = 2; end % f0 calculation if ~isfield(config,'f0') config.f0.method = 'median'; end % specifies how f0 should be calculated % method can be 'median', 'polyfit', 'percentile' % for polyfit and percentile methods, specify the fit degree or percentile % cutoff as params; e.g. for quadratic fit: % config.f0.method = 'polyfit' % config.f0.params = 2 % registration options if ~isfield(config,'reg') config.reg.regChannel = 1; % which channel to perform registration on config.reg.doRegistration = 1; % if set to 0, channels will only be resized to reference image else if ~isfield(config.reg,'regChannel') config.reg.regChannel = 1; end if ~isfield(config.reg,'doRegistration') config.reg.doRegistration = 1; end end % adding some more missing fields if ~isfield(config,'doSaveROIRGBPlot') config.doSaveROIRGBPlot = 1; end end %% Function - initParams function [config, matFiles] = initParams(config, dbgLevel) % this is a list of mat-files containing the raw data % data will be concatenated so should be from one imaging area and always contain the same number of Rois matFiles = config.matFiles; for iFile = 1 : numel(matFiles); if isempty(strfind(matFiles{iFile}, '.mat')); matFiles{iFile} = [matFiles{iFile} '.mat']; end; end; % load the first mat-file and extract some general parameters matFileWrapper = load(matFiles{1}); matFileStruct = matFileWrapper.(genvarname(strrep(matFiles{1},'.mat',''))); config.img_dims = matFileStruct.hdr.size(1 : 2); % x and y dimensions of the image config.ROISet = matFileStruct.roi; % the ROI set config.nRuns = numel(matFiles); % number of runs % low-pass filter parameters switch config.LowPass.method; case 'sg'; lpFiltCutoff = config.LowPass.params(1); lpFiltCutoff = round(lpFiltCutoff .* matFileStruct.hdr.rate); if ~rem(lpFiltCutoff, 2); lpFiltCutoff = lpFiltCutoff + 1; end; config.LowPass.lpFiltCutoff = lpFiltCutoff; config.LowPass.sgolayOrder = config.LowPass.params(2); % filter order clear lpFiltCutoff o(' #GetRoiStats(): low-pass filtering parameters set with sgolay filter.', 3, dbgLevel); otherwise; o(' #GetRoiStats(): no low-pass filtering.', 4, dbgLevel); end % pre-allocate cell arrays, each cell will contain the imaging data for % that ROI during that run. Also pre-allocate for the neuropil config.ROIStatsData = cell(size(config.ROISet, 1) + 1, config.nRuns); % initialize parameters for each run for iRun = 1 : config.nRuns; % make sure the mat-file for that run exists if ~exist(matFiles{iRun}, 'file'); warning('GetRoiStats:FileNotFound', 'Could not find mat-file "%s", skipping it.', matFiles{iRun}); continue; end; % open the mat-file and extract the structure matFileWrapper = load(matFiles{iRun}); matFileStruct = matFileWrapper.(genvarname(strrep(matFiles{iRun},'.mat',''))); nFrames = matFileStruct.hdr.size(3); % elongate the stim vector if needed, print an error if it's too short if numel(matFileStruct.stim) < nFrames; matFileStruct.stim(end + 1 : nFrames) = 0; elseif numel(matFileStruct.stim) > nFrames; error('GetRoiStats:StimVectorTooLong', 'Stim vector is longer than time-series for "%s".', ... matFiles{iRun}); end; config.stim{iRun} = matFileStruct.stim; % stim vector for each run config.frameRate{iRun} = matFileStruct.hdr.frame_rate; % support different frame rates per run end; end %% Function - CalculateF0 % fit a quadratic function to the timeseries and use it as F0 % works best for long timeseries with sparse activity % function f0_mat = CalculateF0(roi_mat, f) function f0_mat = CalculateF0(roi_mat, S) switch lower(S.method) case 'median' f0_mat = median(roi_mat); case 'polyfit' t = 1:length(roi_mat); p = polyfit(t',roi_mat',S.params(1)); f0_mat = p(1).*t.^2 + p(2).*t + p(3); case 'percentile' f0_mat = prctile(roi_mat,S.params(1)); otherwise error('F0 method %s is not supported',S.method) end end %% Function - doLowPassFilter function v = doLowPassFilter(v, S) switch S.method case 'sg' v = sgolayfilt(v,S.sgolayOrder,S.lpFiltCutoff); end end %% Function - doHiPassFilter function v = doHiPassFilter(v, S) switch S.method case 'polyFit' p = polyfit(1:numel(v),v,S.polyOrder); f = polyval(p,1:numel(v)); v = v - f; end end %% Function - ResampleStimVector function stimVectorFrameRate = ResampleStimVector(stim,stimRate,nFrames,frameRate) %#ok<DEFNU> stimVectorFrameRate = zeros(1,nFrames); for n = 1:nFrames startT = (n-1)/frameRate; stopT = n/frameRate; startStim = round(startT*stimRate); if startStim == 0 startStim = 1; end stopStim = round(stopT*stimRate); if startStim > length(stim) || stopStim > length(stim) stimVectorFrameRate(n) = 0; else stimVectorFrameRate(n) = round(mean(stim(startStim:stopStim))); end end end %% Function - getRefOrRegImage function img = getRefOrRegImage(fileID, imgType, baseImgs, config, doSavePlot, dbgLevel) if doSavePlot; % display the reference image figHand = figure('NumberTitle', 'off', 'Name', sprintf('%s Image for %s', imgType, fileID)); end; % using only 1 registration channel if numel(config.reg.regChannel) == 1; o(' #Get...ImageReg(): Generating "%s" frame based on the channel %d.', ... imgType, config.reg.regChannel, 3, dbgLevel); img = baseImgs{config.reg.regChannel}; % flatten (average) the image; if size(img, 3) > 1; img = mean(img, 3); end; if doSavePlot; % plot the reference image imshow(img, []); title(sprintf('%s image: channel %d of %s', imgType, config.reg.regChannel, ... strrep(fileID, '_', '\_'))); end; % if two channels are specified, do oregistration on the difference between the two (regChan1 - regChan2) elseif numel(config.reg.regChannel) == 2; o(' #Get...ImageReg(): Generating "%s" frame based on the channels %d and %d.', ... imgType, config.reg.regChannel, 3, dbgLevel); regChan1RefImg = linScale(baseImgs{config.reg.regChannel(1)}); regChan2RefImg = linScale(baseImgs{config.reg.regChannel(2)}); % flatten (average) the image; if size(regChan1RefImg, 3) > 1; regChan1RefImg = mean(regChan1RefImg, 3); end; if size(regChan2RefImg, 3) > 1; regChan2RefImg = mean(regChan2RefImg, 3); end; img = regChan1RefImg - regChan2RefImg; if config.reg.multiRegChannelForbidNegatives; img(img < 0) = 0; % make sure there's no negative end; img = linScale(img); if doSavePlot; % plot the reference image subplot(1, 3, 1); imshow(regChan1RefImg, []); title(sprintf('Channel %d', config.reg.regChannel(1))); subplot(1, 3, 2); imshow(regChan2RefImg, []); title(sprintf('Channel %d', config.reg.regChannel(2))); subplot(1, 3, 3); imshow(img, []); title(sprintf('%s image: channel %d - %d', imgType, config.reg.regChannel)); suptitle(sprintf('%s image of %s', imgType, strrep(fileID, '_', '\_'))); end; end; % save if required if doSavePlot > 1; if exist(imgType, 'dir') ~= 7; mkdir(imgType); end; saveas(figHand, sprintf('%s/%s__%sImg', imgType, fileID, imgType(1:3))); saveas(figHand, sprintf('%s/%s__%sImg.png', imgType, fileID, imgType(1:3))); close(figHand); end; end %% Function - doNeuropilInterpolation function currentNpilData = doNeuropilInterpolation(config, currentImgData) %#ok<DEFNU> npilFile = [saveNameBase '__NpilMovies.mat']; currentNpilData = cell(1,length(config.channelVector)); currentNpilDataSave = cell(1,length(config.channelVector)); if config.recycleNpilMovie; try a = load(npilFile); currentNpilData = a.(genvarname(strrep(npilFile,'.mat',''))); catch e; %#ok<NASGU> for n = 1:length(config.channelVector) currentNpilData{n} = NeuropilInterpolation(... currentImgData{n},roiSetActiveModel,4,1); if bitDepth == 8 currentNpilDataSave{n} = uint8(currentNpilData{n}); else currentNpilDataSave{n} = uint16(currentNpilData{n}); end end SaveAndAssignInBase(currentNpilDataSave,npilFile,'SaveOnly') clear currentNpilDataSave end else for n = 1:length(config.channelVector) currentNpilData{n} = NeuropilInterpolation(... currentImgData{n},roiSetActiveModel,4,1); if bitDepth == 8 currentNpilDataSave{n} = uint8(currentNpilData{n}); else currentNpilDataSave{n} = uint16(currentNpilData{n}); end end SaveAndAssignInBase(currentNpilDataSave,npilFile,'SaveOnly') clear currentNpilDataSave end end %% Function - extractROIStats function ROIStatsFiltNorm = extractROIStats(imgData, ROIMask, ... statsType, LowPassFilterConfig, HiPassFilterConfig, f0config, saveName, ... doSavePlot) ROIImgData = cell(1, numel(imgData)); % pull out timeseries from masked pixels and average for each relevant channels for iChan = 1 : numel(imgData); ROIImgData{iChan} = mean(GetRoiTimeseries(imgData{iChan}, ROIMask), 1); end switch lower(statsType) case 'dff' ROIStatsRaw = ROIImgData{1}; case 'drr' ROIStatsRaw = ROIImgData{1} ./ ROIImgData{2}; end meanOfRawTrace = mean(ROIStatsRaw); % high-pass filter calcium traces ROIStatsFilt = doHiPassFilter(ROIStatsRaw, HiPassFilterConfig); % low-pass filter calcium traces ROIStatsFilt = doLowPassFilter(ROIStatsFilt, LowPassFilterConfig); ROIStatsFiltAdj = ROIStatsFilt + meanOfRawTrace; % calculate F0 F0 = CalculateF0(ROIStatsFiltAdj, f0config); % calculate normalized fluorescence change ROIStatsFiltNorm = ((ROIStatsFiltAdj - F0) ./ F0) .* 100; ROIStatsFiltNorm(isinf(ROIStatsFiltNorm)) = 0; ROIStatsFiltNorm(isnan(ROIStatsFiltNorm)) = 0; % plotting for debugging only if doSavePlot; figF0AndExtract = figure('NumberTitle', 'off', 'Name', ... sprintf('%s_extractROIStats', saveName)); nSubPlots = 4; subplot(nSubPlots, 1, 1); plot(ROIStatsRaw, 'r'); line([0, numel(ROIStatsRaw)], [meanOfRawTrace, meanOfRawTrace], 'Color', 'black'); legend({'Raw', 'mean'}); title(sprintf('Raw trace with mean ( = %d)', round(meanOfRawTrace))); subplot(nSubPlots, 1, 2); plot(ROIStatsFilt, 'k'); legend({'Filtered'}); title('Raw trace filtered'); subplot(nSubPlots, 1, 3); plot(ROIStatsFiltAdj, 'g'); if numel(F0) == 1; line([0, numel(ROIStatsFiltAdj)], [F0, F0], 'Color', 'black'); else hold on; plot(F0, 'k'); end; legend({'Adjusted', 'F0'}); title('Raw trace filtered and adjusted (with mean) and F0'); subplot(nSubPlots, 1, 4); plot(ROIStatsFiltNorm, 'b'); legend({'Filtered'}); title('DFF/DRR trace'); if doSavePlot > 1; if exist('F0AndExtractPlots', 'dir') ~= 7; mkdir('F0AndExtractPlots'); end; saveNameF0AndExtract = ['F0AndExtractPlots/' saveName]; saveas(figF0AndExtract, saveNameF0AndExtract); saveas(figF0AndExtract, [saveNameF0AndExtract '.png']); close(figF0AndExtract); end; end; end % e.o.f.
github
HelmchenLabSoftware/OCIA-master
roiStatsSingleDay.m
.m
OCIA-master/caImgAnalysis/ROIStats/roiStatsSingleDay.m
8,667
utf_8
c684320eb5799d0a156ee487373b3ffb
function configCell = roiStatsSingleDay(spotList, doAddRois, config) roiStatsSingleDayTic = tic; % for performance timing purposes % add folders to path folderList = {'Projects/2PIanalyzer','Projects/CalciumSim',... 'Projects/EventDetect'}; addFolders2Path(folderList,1); dbgLevel = 1; o('#roiStatsSingleDay(): %d spot(s) to process, doAddRois = %d ...', ... size(spotList, 1), doAddRois, 1, dbgLevel); % loads expInfo cell array expInfoMat = load('ExperimentInfo.mat'); expInfo = expInfoMat.expInfo; % build saveName from current directory name (usually the date) and spot name [~, baseName, ~] = fileparts(pwd); % baseName = ['ROIStats_' baseName]; startDir = pwd; % second loop to handles movies o('#roiStatsSingleDay(): searching for movies (BF vs Odd10)...', 2, dbgLevel); expList_bfSpotId = cell(size(expInfo,1), 1); % store BF experiment info expList_bfMatFileName = cell(size(expInfo,1), 1); % store BF experiment info expList_odd10SpotId = cell(size(expInfo,1), 1); % store Odd10 experiment info expList_odd10MatFileName = cell(size(expInfo,1), 1); % store Odd10 experiment info for iSpot = 1:numel(spotList); % only target spot(s) if any(config.targetSpots) && ~any(config.targetSpots == iSpot); continue; end; o(' #roiStatsSingleDay(): spot %d/%d ...', iSpot, numel(spotList), 2, dbgLevel); % go through each row (= each recording) for iRun = 1 : size(expInfo, 1); % only target run(s) if any(config.targetRuns) && ~any(config.targetRuns == iRun); continue; end; %%#ok<PFBNS> % process only spots corresponding to the current spot if ~strcmp(spotList{iSpot}, expInfo{iRun, 1}); continue; end; %%#ok<PFBNS> o(' #roiStatsSingleDay(): spot %d/%d - row %d/%d ...', ... iSpot, numel(spotList), iRun, size(expInfo, 1), 3, dbgLevel); % check the image type, must be a movie if strcmp(expInfo{iRun, 4}, 'movie'); % check the image name and classify according to either BF or Odd10 if ~isempty(strfind(expInfo{iRun, 2}, 'BF_')); o(' #roiStatsSingleDay(): found BF movie: "%s".', expInfo{iRun, 3}, 4, dbgLevel); expList_bfSpotId{iRun} = spotList{iSpot}; expList_bfMatFileName{iRun} = expInfo{iRun, 3}; elseif ~isempty(strfind(expInfo{iRun,2},'Odd10_')); o(' #roiStatsSingleDay(): found Odd10 movie: "%s".', expInfo{iRun, 3}, 4, dbgLevel); expList_odd10SpotId{iRun} = spotList{iSpot}; expList_odd10MatFileName{iRun} = expInfo{iRun, 3}; else continue; end; end; end; end; o('#roiStatsSingleDay(): movies classified.', 2, dbgLevel); o('#roiStatsSingleDay(): Getting ROI stats for all spots...', 1, dbgLevel); configCell = cell(2, numel(spotList)); for iSpot = 1 : numel(spotList); spotTic = tic; % for performance timing purposes % only target spot(s) if any(config.targetSpots) && ~any(config.targetSpots == iSpot); continue; end; o(' #roiStatsSingleDay(): processing spot %d/%d ("%s") at %s...', ... iSpot, numel(spotList), spotList{iSpot}, datestr(clock,21), 2, dbgLevel); % BF config.matFiles = cell(1,1); nMatFilesFound = 0; config.saveName = [baseName '_BF_' spotList{iSpot}]; fullPath = sprintf('%s%s%s', startDir, filesep, spotList{iSpot}); % search for get the mat files from the BF runs for iRun = 1 : size(expList_bfSpotId,1) % only target run(s) if any(config.targetRuns) && ~any(config.targetRuns == iRun); continue; end; if isempty(expList_bfSpotId{iRun}); continue; end; if strcmp(expList_bfSpotId{iRun}, spotList{iSpot}); o(' #roiStatsSingleDay(): spot %d/%d - BF row %d/%d ...', ... iSpot, numel(spotList), iRun, size(expInfo, 1), 3, dbgLevel); nMatFilesFound = nMatFilesFound + 1; config.matFiles{nMatFilesFound} = expList_bfMatFileName{iRun}; end; end; ticStimConv = tic; o(' #roiStatsSingleDay(): stim conversion and ref image adding for %d mat files ...', ... nMatFilesFound, 2, dbgLevel); parfor iMatFile = 1 : nMatFilesFound; doStimConversAndAddRefImage(sprintf('%s%s%s.mat', fullPath, filesep, ... config.matFiles{iMatFile}), 'bf', fullPath, dbgLevel); %#ok<PFBNS> end; o(' #roiStatsSingleDay(): stim conversion and ref image adding for %d mat files done (%3.1f sec)', ... nMatFilesFound, toc(ticStimConv), 2, dbgLevel); if nMatFilesFound > 0; o(' #roiStatsSingleDay(): Getting ROI stats for BF stims (%d movies)...', ... nMatFilesFound, 2, dbgLevel); cd(fullPath); configCell{1,iSpot} = GetRoiStats(config); cd(startDir); end; % % Odd10 % config.matFiles = cell(1,1); % nMatFilesFound = 0; % config.saveName = [baseName '_Odd10_' spotList{iSpot}]; % for iRun = 1:size(expList_odd10SpotId,1) % if isempty(expList_odd10SpotId{iRun}); continue; end; % if strcmp(expList_odd10SpotId{iRun},spotList{iSpot}); % o(' #roiStatsSingleDay(): spot %d/%d - Odd10 row %d/%d ...', ... % iSpot, numel(spotList), iRun, size(expInfo, 1), 3, dbgLevel); % nMatFilesFound = nMatFilesFound + 1; % config.matFiles{nMatFilesFound} = expList_odd10MatFileName{iRun}; % doStimConversion(sprintf('%s%s%s.mat',fullPath,filesep,... % config.matFiles{nMatFilesFound}),'odd10'); % end; % end; % if nMatFilesFound > 0; % o(' #roiStatsSingleDay(): Getting ROI stats for Odd10 stims (%d movies)...', ... % nMatFilesFound, 2, dbgLevel); % cd(fullPath); % configCell{2,iSpot} = GetRoiStats(config); % warning: can contain a parfor % cd(startDir); % end; o(' #roiStatsSingleDay(): finished spot %d/%d ("%s") at %s (%.2f seconds).', ... iSpot, numel(spotList), spotList{iSpot}, datestr(clock,21), toc(spotTic), 2, dbgLevel); end; o(' #roiStatsSingleDay(): finished getting ROI stats of %d spot(s) at %s (%.2f seconds).', ... numel(spotList), datestr(clock, 21), toc(roiStatsSingleDayTic), 2, dbgLevel); end function doStimConversAndAddRefImage(matfile, stimType, fullPath, dbgLevel) o(' #doStimConversAndAddRefImage(): stim conversion and ref image adding for %s, stimType: %s ...', ... matfile, stimType, 3, dbgLevel); TDTRate = 97656.25; matSaveName = matfile; if ~exist(matfile, 'file') warning('doStimConversion:FileNotFound', 'Could not find mat-file "%s", skipping it.', matfile); return; end; vars = whos('-file', matfile); matFileStruct = load(matfile, vars(1).name); matFileStruct = matFileStruct.(vars(1).name); % add refImage as image if it's only a string if isfield(matFileStruct.hdr, 'refImg') && ischar(matFileStruct.hdr.refImg); o(' #doStimConversAndAddRefImage(): %s: found ref image: %s ...', ... matfile, matFileStruct.hdr.refImg, 3, dbgLevel); refImgMatFilePath = sprintf('%s%s%s.mat', fullPath, filesep, matFileStruct.hdr.refImg); refImgVars = whos('-file', refImgMatFilePath); refImgStruct = load(refImgMatFilePath, refImgVars(1).name); refImgData = refImgStruct.(refImgVars(1).name).img_data; matFileStruct.refImg = cell(1, numel(refImgData)); for iChan = 1 : numel(refImgData); matFileStruct.refImg{iChan} = mean(refImgData{iChan}, 3); end; o(' #doStimConversAndAddRefImage(): %s: ref image added as image.', matfile, 3, dbgLevel); end; stim = matFileStruct.stim; if isnumeric(stim) % already converted o(' #doStimConversAndAddRefImage(): %s: stim is already a numeric.', matfile, 3, dbgLevel); return ; end frame_rate = matFileStruct.hdr.frame_rate; delFrame = matFileStruct.proc.DelFrame; stimID = stim.freqIdSeries; timepoints = stim.timePoints; timepoints = timepoints ./ TDTRate; % convert to frame and offset by delFrame timepoints = round(timepoints .* frame_rate) - delFrame; stimVector = zeros(1,size(matFileStruct.img_data{1},3)); switch lower(stimType) case 'odd10' stimID(stimID==1) = 2; stimID(stimID==-1) = 1; end stimVector(timepoints) = stimID; matFileStruct.proc.stim = matFileStruct.stim; matFileStruct.stim = stimVector; o(' #doStimConversAndAddRefImage(): %s: created new stim vector (%d frame(s) long).', ... matfile, numel(matFileStruct.stim), 3, dbgLevel); SaveAndAssignInBase(matFileStruct, matSaveName, 'SaveOnly'); end
github
HelmchenLabSoftware/OCIA-master
extractSummaryInfoForSpots.m
.m
OCIA-master/caImgAnalysis/ROIStats/extractSummaryInfoForSpots.m
8,614
utf_8
85d821b91cc6f7df9c0da703f4792edb
function extractSummaryInfoForSpots(animalID) dbgLevel = 4; extractAllTic = tic; % for performance timing purposes %% Get days with spots year = '2013'; % leave this as a string, not a number rawDataRootPath = 'W:\Neurophysiology\RawData\Balazs_Laurenczy\'; analysisRootPath = 'W:\Neurophysiology\Projects\Auditory\Analysis\AuditoryLearning\'; % analysisRootPath = 'D:\Balazs\'; % analysisRootPath = 'C:\Users\laurenczy.HIFO\Documents\LocalData\'; analysisRootPath = [analysisRootPath year '\' animalID '\']; o('#extractSummaryInfoForSpots(): animalID = %s.', animalID, 1, dbgLevel); o('#extract...ForSpots(): rawDataRootPath = "%s".', rawDataRootPath, 3, dbgLevel); o('#extract...ForSpots(): analysisRootPath = "%s".', analysisRootPath, 3, dbgLevel); % get all days with at least 1 "spot**" folder inside for this mouse daysWithSpot = getDaysWithSpot(year, rawDataRootPath, animalID, 0); o('#extract...ForSpots(): Found %d day(s) with spot for animal %s.', ... numel(daysWithSpot), animalID, 2, dbgLevel); % restrict the running to specific day(s), spot(s), run(s). Can be set to 0 to run all or % can be set to single number: targetDays = 2; or to a list: targetSpots = [2 3 5]; targetDays = 0; targetSpots = 0; nChans = 3; colorVector = [1 2 0]; %% Process each day for iDay = 1 : numel(daysWithSpot); dayTic = tic; % for performance timing purposes % only target day(s) if any(targetDays) && ~any(targetDays == iDay); continue; end; %% Experiment info day = daysWithSpot(iDay); notebookFileName = day.notebookFileName; % list of spots with short name in notebook file spotList = day.spotList; currentDate = day.day; o('#extract...ForSpots(): Processing day %s with %d spot(s).', currentDate, size(spotList, 1), 2, dbgLevel); %% Input files fullRawDataPath = [rawDataRootPath year filesep animalID filesep currentDate]; stimFile = [fullRawDataPath filesep 'CaImgExp_' currentDate '.mat']; % perform analysis in different directory than the raw data directory analysisPath = [analysisRootPath currentDate]; % load CaImgExp CaImgExpMat = load(stimFile); allZipFiles = []; % fetch all zip files for iSpot = 1 : size(spotList, 1); % only target spot(s) if any(targetSpots) && ~any(targetSpots == iSpot); continue; end; analysisSpotPath = [analysisPath, filesep, spotList{iSpot, 1}, filesep]; allZipFiles = [allZipFiles dir([analysisSpotPath '*.zip'])]; %#ok<*AGROW> end; refNamesWithRoiSet = cell(numel(allZipFiles), 1); for iStruct = 1 : numel(allZipFiles); refNamesWithRoiSet{iStruct} = regexprep(allZipFiles(iStruct).name, '__RoiSet.zip', ''); end; % read the HelioScan notebook text file and generate and "experiment info" cell array where % each row is a different recording (reference image or movie) expInfo = prepare4dataImport(notebookFileName, spotList, refNamesWithRoiSet, 1, 1, 1); o(' #extract...ForSpots(): %s: Experiment info generated.', currentDate, 3, dbgLevel); % import each spot for iSpot = 1 : size(spotList, 1); spotTic = tic; % for performance timing purposes % only target spot(s) if any(targetSpots) && ~any(targetSpots == iSpot); continue; end; % load stims iSpotInCaImgExp = str2double(strrep(spotList{iSpot, 2}, 'sp', '')); spotInfo = CaImgExpMat.CaImgExp.spots{iSpotInCaImgExp}; % skip if that spot was not created on that day if isempty(spotInfo); o(' #extract...ForSpots(): %s: skipping spot %d as it is empty.', currentDate, iSpot, 2, dbgLevel); continue; end; spotID = spotList{iSpot, 1}; % for example 'spot01' analysisSpotPath = [analysisPath, filesep, spotID]; rawSpotPath = [fullRawDataPath, filesep, spotList{iSpot, 1}, filesep]; allRefs = expInfo(strcmp(expInfo(:, 1), spotID) & ~cellfun(@isempty, strfind(expInfo(:, 2), 'Ref256x')), :); refsWithROIs = expInfo(strcmp(expInfo(:, 1), spotID) & ~cellfun(@isempty, strfind(expInfo(:, 2), 'Ref256x')) & ... cell2mat(expInfo(:, 8)), :); % read the data from all channels for iRef = 1 : size(allRefs, 1); refName = allRefs{iRef, 3}; refFullFileName = sprintf('%s%s%s%s__channel__CHANNUM__.tif', ... rawSpotPath, refName, filesep, refName); RGBImage = getMergedImage(refFullFileName, nChans, colorVector); rawDataMousePath = [rawDataRootPath year filesep animalID filesep]; zoomedOutStr = ''; if allRefs{iRef, 9}; zoomedOutStr = 'zoomOut_'; end; saveName = sprintf('%s%s_%s_%s%dum_%04.1fLI_z%03.1f_RGBRef', rawDataMousePath, spotID, day.day, ... zoomedOutStr, spotInfo.depth, allRefs{iRef, 6}, allRefs{iRef, 7}); saveName = strrep(saveName, '.', 'p'); % size(RGBImage.data); write_to_tif(RGBImage, saveName); end; % % read the data from all channels % for iRef = 1 : size(refsWithROIs, 1); % refName = refsWithROIs{iRef, 3}; % refFullFileName = sprintf('%s%s%s%s__channel__CHANNUM__.tif', ... % rawSpotPath, refName, filesep, refName); % RGBImage = getMergedImage(refFullFileName, nChans, colorVector); % img = RGBImage.data; % % ROISetFileName = ''; % for iStruct = 1 : numel(allZipFiles); % if strfind(allZipFiles(iStruct).name, refName); % ROISetFileName = allZipFiles(iStruct).name; % break; % end; % end; % % imgDims = [size(img, 1) size(img, 2)]; % ROISetFullFileName = sprintf('%s%s%s', analysisSpotPath, filesep, ROISetFileName); % ROISet = ij_roiDecoder(ROISetFullFileName, imgDims); % % figHand = doROIRGBPlot(imgDims, ROISet, img, {img(:, :, 2)}, refsWithROIs{iRef, 3}, 0.8); % title(refsWithROIs{iRef, 3}, 'Interpreter', 'none'); % rawDataMousePath = [rawDataRootPath year filesep animalID filesep]; % saveName = sprintf('%s%s_%s_RGBRef_withROI.png', rawDataMousePath, spotID, day.day); % saveas(figHand, saveName); % close(figHand); % end; % get the surface stack and do the sum of the frames surfStack = expInfo(strcmp(expInfo(:, 1), spotID) & ~cellfun(@isempty, strfind(expInfo(:, 2), 'surface')) & ... ~cellfun(@isempty, strfind(expInfo(:, 4), '3D stack')), :); if ~isempty(surfStack); surfStackName = surfStack{1, 3}; surfStackFullFileName = sprintf('%s%s%s%s__channel__CHANNUM__.tif', ... rawSpotPath, surfStackName, filesep, surfStackName); RGBImage = getMergedImage(surfStackFullFileName, nChans, colorVector); RGBImage.data = sum(RGBImage.data, 3) ./ size(RGBImage.data, 3); RGBImage.data = linScale(PseudoFlatfieldCorrect(RGBImage.data), 0, 2 ^ 16); saveName = sprintf('%s%s_%s_surface', rawDataMousePath, spotID, day.day); write_to_tif(RGBImage, saveName); end; o(' #extract...ForSpots(): %s - %s: written out all references (%.2f seconds).', currentDate, spotID, ... toc(spotTic), 2, dbgLevel); end o(' #extract...ForSpots(): %s: extracted data (%.2f seconds).', currentDate, ... toc(dayTic), 1, dbgLevel); end; o('#extractSummaryInfoForSpots(): extracted all data for "%s" (%.2f seconds).', ... animalID, toc(extractAllTic), 1, dbgLevel); end function RGBImage = getMergedImage(refFullFileName, nChans, colorVector) refImg = cell(nChans, 1); for iChan = 0 : nChans - 1; fileName = strrep(refFullFileName, '__CHANNUM__', sprintf('%02d', iChan)); if ~exist(fileName, 'file'); refImg{iChan + 1} = zeros(256, 256); else tiffStruct = tiffread2_wrapper(fileName); refImg{iChan + 1} = tiffStruct.data; end; end; % merge the channels RGBImage = struct(); red = zeros(size(refImg{1})); green = zeros(size(refImg{1})); blue = zeros(size(refImg{1})); if colorVector(1); red = linScale(refImg{colorVector(1)}); end; if colorVector(2); green = linScale(refImg{colorVector(2)}); end; if colorVector(3); blue = linScale(refImg{colorVector(3)}); end RGBImage.data = cat(3, red, green, blue); end
github
HelmchenLabSoftware/OCIA-master
GetRoiStatsFrameJ90.m
.m
OCIA-master/caImgAnalysis/ROIStats/GetRoiStatsFrameJ90.m
19,099
utf_8
018f54858f295d12e1a279c84d8700c4
function varargout = GetRoiStatsFrameJ90(config) % get ROI timecourses from images, with support for muliple ROIs and runs % returns structure data, info and stimulus fields % data field contains a cell array with ROI timecourses for different cells % in rows and different runs in columns: % [cell1_run1] [cell1_run2] ... [cell1_runN] % [cell2_run1] [cell2_run2] ... [cell2_runN] % ... ... ... % [cellN_run1] [cellN_run2] ... [cellN_runN] % this file written by Henry Luetcke ([email protected]) config = ParseConfig(config); matfiles = config.matfiles; for n = 1:numel(matfiles) if isempty(strfind(matfiles{n},'.mat')) matfiles{n} = [matfiles{n} '.mat']; end end S = load(matfiles{1}); data = S.(genvarname(strrep(matfiles{1},'.mat',''))); delFrame = data.proc.DelFrame; % experiment specific info animalID = data.hdr.animalID; spotID = data.hdr.spotID; config.saveName = sprintf('%s_%s',animalID,spotID); config.img_dims = data.hdr.size(1:2); roiSet = data.roi; cellNo = size(roiSet,1); config.runsNo = numel(matfiles); config.timepoints = data.hdr.size(3); %% low-pass filter parameters switch config.LowPass.method case 'sg' lpFiltCutoff = config.LowPass.params(1); lpFiltCutoff = round(lpFiltCutoff.*data.hdr.rate); if ~rem(lpFiltCutoff,2) lpFiltCutoff = lpFiltCutoff+1; end config.LowPass.lpFiltCutoff = lpFiltCutoff; config.LowPass.sgolayOrder = config.LowPass.params(2); % filter order clear lpFiltCutoff end config.dataRoi = cell(cellNo,config.runsNo); config.dataRoiNorm = cell(cellNo,config.runsNo); config.dataNpil = cell(cellNo,config.runsNo); %% Event detection parameters if ~strcmp(config.EventDetect.method,'none') config.EventDetect.amp = 2.5; config.EventDetect.tau = 0.6; config.EventDetect.onsettau = 0.01; config.EventDetect.doPlot = 0; % should be switched off switch lower(config.EventDetect.method) case 'fast_oopsi' config.EventDetect.lam = 0.1; % firing rate config.EventDetect.base_frames = 10; config.EventDetect.oopsi_thr = 0.3; config.EventDetect.integral_thr = 5; config.EventDetect.filter = [7 2]; config.EventDetect.minGof = 0.5; case 'peeling' config.EventDetect.schmittHi = 1.75; config.EventDetect.schmittLo = -0.75; config.EventDetect.schmittmindur = 0.3; end end % initialize some parameters S = load(matfiles{1}); data = S.(genvarname(strrep(matfiles{1},'.mat',''))); config.frameRate = data.hdr.rate; if isfield(data.hdr,'bits') bitDepth = data.hdr.bits; else bitDepth = 16; end RoiMatAllRuns = []; % eventMatAllRuns = []; %% Process runs for currentRun = 1:config.runsNo fprintf('\nNow processing run %1.0f\n',currentRun); S = load(matfiles{currentRun}); data = S.(genvarname(strrep(matfiles{currentRun},'.mat',''))); currentImgData = cell(1,length(config.channelVector)); % currentMeanImgData = cell(1,length(config.channelVector)); for n = 1:length(config.channelVector) currentImgData{n} = double(data.img_data{config.channelVector(n)}); % currentMeanImgData{n} = mean(currentImgData{n},3); end if config.ch3Sound [config.stim{currentRun},soundT] = ... img2vector(double(data.img_data{3}),1/config.pixelTime,0); else config.stim{currentRun} = []; end config.stim{currentRun} = removeBlankPixels(config.stim{currentRun}); % [stimTable,h,toneClean] = AnalyzePureToneVector(config.stim{currentRun},... % 1/config.pixelTime,0); % config.stim{currentRun} = soundTable2StimVector(stimTable,1/config.pixelTime,0); roiSet = data.roi; % convert to mask Roi format roiSet = ij_RoiSetCompression(roiSet,2); refImg = data.refImg; roiRgb = zeros(size(refImg,1),size(refImg,2),3); cmap = jet(size(roiSet,1)); alpha_mat = ones(size(refImg)); roiCounterImg = zeros(size(alpha_mat)); roiSetActiveModel = roiSet; saveActiveModel = 0; roiLabel = roiSet(:,1); for currentRoi = 1:size(roiSet,1) switch class(roiSet{currentRoi,2}) case 'uint32' roi = bwunpack(roiSet{currentRoi,2}); otherwise roi = roiSet{currentRoi,2}; end roiId = roiSet{currentRoi,1}; if length(find(roi)) == 1 % run Active Model segmentation on point Rois [cog_row, cog_col] = ind2sub(size(alpha_mat),find(roi)); roi = ... doActiveModelSegment(refImg,[cog_row cog_col],config.segOptions); roiSetActiveModel{currentRoi,2} = roi; saveActiveModel = 1; [y,x] = find(roi==1); roiSetActiveModel{currentRoi,3} = [mean(y),mean(x)]; else [y,x] = find(roi==1); roiSet{currentRoi,3} = [mean(y),mean(x)]; roiSetActiveModel{currentRoi,3} = [mean(y),mean(x)]; end alpha_mat(roi==1) = 0.75; if ~isempty(str2num(roiId)) roiCounterImg(roi==1) = str2num(roiId); end [row, col] = ind2sub(size(alpha_mat),find(roi)); for idx = 1:length(row) for color = 1:3 roiRgb(row(idx),col(idx),color) = ... cmap(currentRoi,color); end end end config.roi.roiSet = roiSet; if saveActiveModel config.roi.ActiveModel = roiSetActiveModel; end %% Apply registration tform = data.tform; for n = 1:length(config.channelVector) hiResFunc = zeros(size(refImg,1),size(refImg,2),size(currentImgData{n},3)); for frame = 1:size(currentImgData{n},3) currentFrame = removeBlankPixels(currentImgData{n}(:,:,frame)); if size(currentFrame) ~= size(refImg) currentFrame = imresize(currentFrame,[size(refImg,1) size(refImg,2)]); % imresize performs bicubic interpolation by default end if ~isempty(tform) currentFrame = imtransform(currentFrame,tform,'xdata',... [1 size(currentFrame,2)],'ydata',[1 size(currentFrame,1)]); end hiResFunc(:,:,frame) = currentFrame; end currentImgData{n} = hiResFunc; clear hiResFunc end %% Plot Rois % display created Rois on mean frame in RGB multi-color h2 = figure('Name',sprintf('ROIs %s',matfiles{currentRun}),'NumberTitle','off'); imshow(roiRgb); hold on hRef = imshow(mean(currentImgData{1},3),[],'InitialMagnification','fit'); set(hRef,'AlphaData',alpha_mat); s = regionprops(roiCounterImg,roiCounterImg,'MaxIntensity','Extrema'); hold(gca, 'on'); for k = 1:numel(s) e = s(k).Extrema; val = s(k).MaxIntensity; text(e(1,1), e(1,2)-1, sprintf('%d', val), ... 'Parent', gca, ... 'Clipping', 'on', ... 'Color', 'r', ... 'FontWeight', 'bold', ... 'Tag', 'CellLabel'); end drawnow saveNameBase = strrep(matfiles{currentRun},'.mat',''); saveas(h2,[saveNameBase '__RoiRgb.fig']); hold(gca, 'off'); %% Neuropil interpolation npilFile = [saveNameBase '__NpilMovies.mat']; currentNpilData = cell(1,length(config.channelVector)); currentNpilDataSave = cell(1,length(config.channelVector)); if config.recycleNpilMovie try a = load(npilFile); currentNpilData = a.(genvarname(strrep(npilFile,'.mat',''))); catch for n = 1:length(config.channelVector) currentNpilData{n} = NeuropilInterpolation(... currentImgData{n},roiSetActiveModel,4,1); if bitDepth == 8 currentNpilDataSave{n} = uint8(currentNpilData{n}); else currentNpilDataSave{n} = uint16(currentNpilData{n}); end end SaveAndAssignInBase(currentNpilDataSave,npilFile,'SaveOnly') clear currentNpilDataSave end else for n = 1:length(config.channelVector) currentNpilData{n} = NeuropilInterpolation(... currentImgData{n},roiSetActiveModel,4,1); if bitDepth == 8 currentNpilDataSave{n} = uint8(currentNpilData{n}); else currentNpilDataSave{n} = uint16(currentNpilData{n}); end end SaveAndAssignInBase(currentNpilDataSave,npilFile,'SaveOnly') clear currentNpilDataSave end %% Neuropil analysis switch lower(config.statsType) case 'dff' npilStats = mean(GetRoiTimeseries(currentNpilData{1},[]),1); case 'drr' npilStats = mean(GetRoiTimeseries(currentNpilData{1},[]),1) ./... mean(GetRoiTimeseries(currentNpilData{2},[]),1); end % calculate F0 (use quadratic fit method) npilF0 = CalculateF0(npilStats,config.frameRate); npilStats = ((npilStats-npilF0) ./ npilF0) .* 100; npilStats(isinf(npilStats)) = 0; npilStats(isnan(npilStats)) = 0; config.frameNpil.data{currentRun} = npilStats; %% ROI analysis currentRoiMat = zeros(size(roiSetActiveModel,1),config.timepoints); for currentRoi = 1:size(roiSetActiveModel,1) roi = roiSetActiveModel{currentRoi,2}; roiImgData = cell(1,numel(config.channelVector)); roiNpilData = cell(1,numel(config.channelVector)); for n = 1:numel(config.channelVector) roiImgData{n} = mean(GetRoiTimeseries(currentImgData{n},roi),1); end switch lower(config.statsType) case 'dff' roiStats = roiImgData{1}; case 'drr' roiCh1 = roiImgData{1}; roiCh2 = roiImgData{2}; roiStats = roiCh1 ./ roiCh2; end % calculate F0 (use quadratic fit method) roiF0 = CalculateF0(roiStats,config.frameRate); % calculate stats roiStats = ((roiStats-roiF0) ./ roiF0) .* 100; roiStats(isinf(roiStats)) = 0; roiStats(isnan(roiStats)) = 0; % event detection on roiStats % if ~strcmp(config.EventDetect.method,'none') % %% Event detection % eventDetect = config.EventDetect; % eventDetect.ca = roiStats; % thus, we use the non-neuropil corrected trace % eventDetect.rate = config.frameRate{currentRun}; % eventStruct = CalciumEventDetect(eventDetect); % config.EventDetect.event{currentRoi,currentRun} = eventStruct.data.spike_predict; % oopsi = eventStruct.data.oopsi; % if strcmp(eventDetect.method,'fast_oopsi') % config.EventDetect.oopsi{currentRoi,currentRun} = eventStruct.data.oopsi; % elseif strcmp(eventDetect.method,'peeling') % config.EventDetect.residual{currentRoi,currentRun} = eventStruct.data.oopsi; % config.EventDetect.model{currentRoi,currentRun} = eventStruct.data.model; % end % fprintf('\n%s Roi %1.0f Run %1.0f'); % fprintf('Events: %1.0f\n',sum(eventStruct.data.spike_predict)); % fprintf('Residual per frame: %1.3f\n',... % sum(abs(eventStruct.data.oopsi))/length(eventStruct.data.oopsi)); % currentEventMat(currentRoi,:) = eventStruct.data.spike_predict; % end % low-pass filter calcium traces roiStats = doLowPassFilter(roiStats,config.LowPass); % save config.dataRoi{currentRoi,currentRun} = roiStats; currentRoiMat(currentRoi,:) = roiStats; end % lowPass filter frame neuropil npilStats = doLowPassFilter(npilStats,config.LowPass); % save frame neuropil in last row currentRoiMat(currentRoi+1,:) = npilStats; RoiMatAllRuns = [RoiMatAllRuns currentRoiMat]; % eventMatAllRuns = [eventMatAllRuns currentEventMat]; end stimVectorAllRuns = cell2mat(config.stim); stimTimeAllRuns = (1:length(stimVectorAllRuns)).*config.pixelTime; %% Calcium Event Plot % plot all Rois with stim in stacked plot titleStr = sprintf('%s',config.saveName); fig = figure('Name',titleStr,'NumberTitle','off'); hold all currentOffset = 0; time = (1:size(RoiMatAllRuns,2))/config.frameRate; cellIDaxes = cell(size(RoiMatAllRuns,1),1); meanYpos = zeros(size(RoiMatAllRuns,1),1); for roi = 1:size(RoiMatAllRuns,1) if roi == size(RoiMatAllRuns,1) id = 'npil'; else id = roiLabel{roi}; end data = RoiMatAllRuns(roi,:); data = data + (min(data)*-1); dataPlot = data + currentOffset; currentOffset = max(dataPlot); cellIDaxes{roi} = id; meanYpos(roi) = mean(dataPlot); end stimVectorPlot = ScaleToMinMax(stimVectorAllRuns,0,max(RoiMatAllRuns(end,:))); stimVectorPlot = (stimVectorPlot - min(stimVectorPlot)) + currentOffset; currentOffset = max (stimVectorPlot); roiLabel{end+1} = 'sound'; set(gca,'ylim',[0 currentOffset],'xlim',[min(time) max(time)+0.1*max(time)]) set(gca,'XTick',[]) ax1 = gca; title(titleStr,'Interpreter','none') ylabel(sprintf('%% %s',upper(config.statsType))) ax2 = axes('Position',get(gca,'Position'),'YAxisLocation','right'); set(ax2,'ylim',[0 currentOffset],'xlim',[min(time) max(time)],... 'YTick',meanYpos,'YTickLabel',cellIDaxes) xlabel('Time / s') hold all currentOffset = 0; for roi = 1:size(RoiMatAllRuns,1) data = RoiMatAllRuns(roi,:); data = data + (min(data)*-1); dataPlot = data + currentOffset; plot(time,dataPlot) currentOffset = max(dataPlot); % if roi == size(RoiMatAllRuns,1) % break % end % eventData = eventMatAllRuns(roi,:); % spkTimes = []; % for m = 1:length(eventData) % if eventData(m) % h_err = errorbar(time(m),min(dataPlot),0,... % config.EventDetect.amp,'Color','black'); % removeErrorBarEnds(h_err) % set(h_err,'LineWidth',2) % end % end end plot(stimTimeAllRuns,stimVectorPlot,'k') % for n = 1:numel(StimVectorAllRuns) % if StimVectorAllRuns(n) == 1 % plot([time(n) time(n)],[0 currentOffset],'LineStyle','--',... % 'Color',[0.8 0.8 0.8]) % elseif StimVectorAllRuns(n) == 2 % plot([time(n) time(n)],[0 currentOffset],'LineStyle','--',... % 'Color',[0.3 0.3 0.3]) % end % end linkaxes([ax1,ax2],'y') saveas(fig,sprintf('%s_RoiCalciumEvents',config.saveName)) matfileName = sprintf('%s_RoiStats.mat',config.saveName); save(matfileName,'config') if nargout varargout{1} = config; end %% Function - ParseConfig function config = ParseConfig(config) % check for missing fields in config structure and add them with % default values if ~isfield(config,'matfiles') matFiles = sort(uigetfile(... '*.mat','Select Mat Files','MultiSelect','on')); config.matfiles = strrep(matFiles,'.mat',''); else matfiles = config.matfiles; end if ~isfield(config,'saveName') config.saveName = [matfiles{1} '__RoiStats']; end % force f0 calculation as in ImageJ if ~isfield(config,'forceIJf0') config.forceIJf0 = 0; end if isempty(config.forceIJf0) config.forceIJf0 = 0; end % number of initial frames for normalization (forceImageJf0) OR the number % of frames before a stimulus used for renormalization if ~isfield(config,'baseFrames') config.baseFrames = 10; end if isempty(config.baseFrames) config.baseFrames = 10; end if ~isfield(config,'statsType') config.statsType = 'dff'; end % channels for stats calculation % DFF is calculated on the channel specified by config.channelVector(1) % DRR is calculated on the channels specified by config.channelVector(1) % and config.channelVector(2) if ~isfield(config,'channelVector') config.channelVector = [1 2]; end if strcmpi(config.statsType,'drr') && numel(config.channelVector) < 2 error('config.channelVector must specify at least 2 channels for DRR stats!'); end if ~isfield(config,'npilCorrect') config.npilCorrect = 0.2; end if ~isfield(config,'recycleNpilMovie') config.recycleNpilMovie = 0; end if ~isfield(config,'doOgbSRsegmentation') config.doOgbSRsegmentation = 0; end if config.doOgbSRsegmentation if ~isfield(config,'OgbChannel') config.OgbChannel = 1; end if ~isfield(config,'SrChannel') config.SrChannel = 2; end end if ~isfield(config,'segOptions') config.segOptions = struct; end if ~isfield(config,'psConfig') config.psConfig = struct; config.psConfig.baseFrames = 5; config.psConfig.evokedFrames = 15; end % event detection if ~isfield(config,'EventDetect') config.EventDetect.method = 'none'; end % low-pass filter (applied to the calcium trace AFTER event detection) % also applied to GLM model if ~isfield(config,'LowPass') config.LowPass.method = 'none'; config.LowPass.params = []; end % LowPass.method may take the following values: % 'none' ... no low-pass filtering is applied % 'sg' ... savitzky-golay filter, as implemented in ML % LowPass.params is a vector with filter parameters, depending on the % specific filter (all cutoffs should be defined in s) % for SG, params are [lpFilterCutoff filterOrder] if ~isfield(config,'ch3Sound') config.ch3Sound = 1; end if ~isfield(config,'pixelTime') config.pixelTime = 12; end config.pixelTime = config.pixelTime / 1000000; %% Function - CalculateF0 function f0_mat = CalculateF0(roi_mat,f) t = 1/f:1/f:length(roi_mat)./f; p = polyfit(t',roi_mat',2); f0_mat = p(1).*t.^2 + p(2).*t + p(3); %% Function - doLowPassFilter function v = doLowPassFilter(v,S) switch S.method case 'sg' v = sgolayfilt(v,S.sgolayOrder,S.lpFiltCutoff); end %% Function - doActiveModelSegment function roi = doActiveModelSegment(img,cog,options) options.cog = cog; if ~isfield(options,'cellsize') options.cellsize = 7; end if ~isfield(options,'minMaskSize') options.minMaskSize = 20; end if ~isfield(options,'snake_iter1') options.snake_iter1 = 100; end if ~isfield(options,'snake_iter') options.snake_iter = 10; end if ~isfield(options,'alpha') options.alpha = 1; end if ~isfield(options,'beta') options.beta = 0; end if ~isfield(options,'tau') options.tau = 0.1; end if ~isfield(options,'filt_range') options.filt_range = [3 3]; end if ~isfield(options,'filt_order') options.filt_order = 1; end if ~isfield(options,'canny_lo') options.canny_lo = [0.1 0.05 0.01]; end if ~isfield(options,'canny_hi') options.canny_hi = [0.25 0.15 0.05]; end if ~isfield(options,'alt_radius') options.alt_radius = 2; end if ~isfield(options,'doPlot') options.doPlot = 0; end if ~isfield(options,'enlarge') options.enlarge = 0; end if ~isfield(options,'erode') options.erode = 0; end try roi = ActiveModel_segment(img,options); catch roi = zeros(size(img,1),size(img,2)); rethrow(lasterror); end % e.o.f.
github
HelmchenLabSoftware/OCIA-master
henry_analyzeHDF5_singleDay.m
.m
OCIA-master/caImgAnalysis/analysisHDF5/henry_analyzeHDF5_singleDay.m
8,844
utf_8
594a225ffaaef1c7c4dd24f7b2b9e09b
function S = henry_analyzeHDF5_singleDay(id, doSave, doDecode) % id ... date string for the HDF5 file (e.g. 14011001) or Matlab structure from previous run config.doSave = doSave; config.doDecode = doDecode; if ~isstruct(id) fileName = sprintf('%s.h5',id); animalID = sprintf('mou_bl_%s_%s',id(1:6),id(7:8)); datasetID = ['/' animalID]; o('Loading data for %s ...', animalID, 0, 0); % load HDF5 and convert to data structure S = loadDataFromHDF5(fileName,datasetID); o('Loading data for %s done.', animalID, 0, 0); else S = id; animalID = S.animalID; S = rmfield(S,'animalID'); end clear id fieldsSpots = fieldnames(S); for n = 1:numel(fieldsSpots) % loop over spots spotID = fieldsSpots{n}; currentSpot = S.(fieldsSpots{n}); fieldsDays = fieldnames(currentSpot); for m = 1:numel(fieldsDays) % loop over days dateID = strrep(fieldsDays{m},'x',''); currentS = currentSpot.(fieldsDays{m}); ROISet = S.(spotID).(fieldsDays{m}).ROISets; o('Running analysis for %s %s %s.',animalID,spotID,dateID, 0, 0) %{ [caTracesMean, trialCount, tPs, perfTrue, perfShuf] = doSingleDayAnalysis(currentS,config); % Save results S.(spotID).(fieldsDays{m}).results.caTracesMean = caTracesMean; S.(spotID).(fieldsDays{m}).results.tPs = tPs; if config.doDecode S.(spotID).(fieldsDays{m}).results.perfTrue = perfTrue; S.(spotID).(fieldsDays{m}).results.perfShuf = perfShuf; end % Average Neuropil signal for target and distractor titleStr = sprintf('%s %s %s Avg Traces',animalID,spotID,dateID); h = figure('Name',titleStr,'NumberTitle','off'); splotTiles = subplotTiles(size(caTracesMean{1},1)); splotPos = 1; for roi = 1:size(caTracesMean{1},1) subplot(splotTiles(1),splotTiles(2),splotPos), splotPos = splotPos + 1; plot(tPs,caTracesMean{1}(roi,:),'k'), hold on plot(tPs,caTracesMean{2}(roi,:),'r') if roi == size(caTracesMean{1},1) title('Neuropil') legend({sprintf('Targ (%1.0f trials)',trialCount(1)),... sprintf('Dist (%1.0f trials)',trialCount(2))}) xlabel('Time (s)'), ylabel('DRR (%)') else title( ROISet{1}{roi,1}) end end adjustSubplotAxes(h,'x',[min(tPs) max(tPs)],'y',[]) % Average Roi traces for target and distractor titleStr = sprintf('%s %s %s Avg Image',animalID,spotID,dateID); h = figure('Name',titleStr,'NumberTitle','off'); nRois = size(caTracesMean{1},1)-1; caTracesMeanMat = [caTracesMean{1}(1:nRois,:); caTracesMean{2}(1:nRois,:)]; caTracesMeanMat = ScaleToMinMax(caTracesMeanMat,0,1); subplot(1,2,1) % target imagesc(tPs,1:nRois,caTracesMeanMat(1:nRois,:),[0 1]) xlabel('Time (s)'), ylabel('Roi') title(sprintf('Target (%1.0f trials)',trialCount(1))) subplot(1,2,2) % distractor imagesc(tPs,1:nRois,caTracesMeanMat(nRois+1:end,:),[0 1]) xlabel('Time (s)'), ylabel('Roi') title(sprintf('Distractor (%1.0f trials)',trialCount(2))) colormap('hot'), colorbar %} % NaiveBayes performance if config.doDecode titleStr = sprintf('%s %s %s NaiveBayes',animalID,spotID,dateID); h = figure('Name',titleStr,'NumberTitle','off'); shadedErrorBar(tPs,nanmean(perfShuf,1),nanstd(perfShuf,[],1),'k',1); hold on shadedErrorBar(tPs,nanmean(perfTrue,1),nanstd(perfTrue,[],1),'r',1); set(gca,'xlim',[min(tPs) max(tPs)]) legend({'Shuf','True'}), xlabel('Time (s)'), ylabel('Classification Perf. +- SD (%)') end end end S.animalID = animalID; if config.doSave SaveAndCloseFigures end end %% Function - doSingleDayAnalysis function [caTracesMean, trialCount, tPs, perfTrue, perfShuf] = doSingleDayAnalysis(S,config) imgRate = 76.9; % in Hz psTimes = [-0.5 2]; % in s psTimesIx = round(psTimes.*imgRate); stim = S.behav.stim; trials = numel(stim); % figure out target and non-target targetNontarget = []; for n = 1:numel(S.behav.target) if ~S.behav.target{n} continue end if stim{n} == 1 targetNontarget = [1 2]; else targetNontarget = [2 1]; end break end % fprintf('Target: stim %1.0f\n',targetNontarget(1)) % fprintf('Non-Target: stim %1.0f\n',targetNontarget(2)) caTracesTrials = cell(1,2); for t = 1:trials caTraces = S.caTraces{t}; imgDelay = S.behav.imgDelays{t}; stimStartTime = S.behav.stimStartTime{t}-imgDelay; timeCa = (1:size(caTraces,2))./imgRate; stimStartIx = find(timeCa>=stimStartTime,1,'first'); psStartIx = stimStartIx + psTimesIx(1); if psStartIx < 1 error('psStart too early on trial %1.0f',t) end psStopIx = stimStartIx + psTimesIx(2); if psStopIx > size(caTraces,2) % warning('psStop too late on trial %1.0f. Skipping ...',t) continue; end if t == 1 tPs = ((psStartIx:psStopIx)-stimStartIx)./imgRate; end if isempty(caTracesTrials{stim{t}}) caTracesTrials{stim{t}} = caTraces(:,psStartIx:psStopIx); else caTracesTrials{stim{t}} = cat(3, caTracesTrials{stim{t}}, caTraces(:,psStartIx:psStopIx)); end end stimStartIx = find(tPs>=0,1,'first'); for n = 1:numel(caTracesTrials) data = nanmean(caTracesTrials{n},3); % baseline normalization / filter for m = 1:size(data,1) data(m,:) = data(m,:) - nanmean(data(m,1:stimStartIx)); data(m,:) = sgolayfilt(data(m,:),3,11); end caTracesMean{1,targetNontarget(n)} = data; trialCount(1,targetNontarget(n)) = size(caTracesTrials{n},3); decodeData{1,targetNontarget(n)} = caTracesTrials{n}; end if config.doDecode % time-resolved decoding analysis (target vs. distractor) for neuron population holdOut = 0.2; % fraction of trials to leave out iters = 100; % number of iterations decodeTimepoints = size(data,2); % consider binning to reduce timepoints perfTrue = zeros(iters,decodeTimepoints); perfShuf = zeros(iters,decodeTimepoints); dispPercent = 10; fprintf('NaiveBayes classification: 00%% done') for t = 1:decodeTimepoints popData = []; labels = []; for stim = 1:numel(decodeData) for trial = 1:size(decodeData{stim},3) popData = [popData; decodeData{stim}(1:end-1,t,trial)']; % last row is neuropil labels(end+1,1) = stim; end end perfTrue(1:iters,t) = doClassify(popData,labels,holdOut,iters,0); perfShuf(1:iters,t) = doClassify(popData,labels,holdOut,iters,1); percentDone = round(t/decodeTimepoints*100); if percentDone >= dispPercent fprintf('\b\b\b\b\b\b\b\b%1.0f%% done',percentDone) dispPercent = dispPercent + 10; end end else perfTrue = []; perfShuf = []; end fprintf('\n\n') end %% Function - doClassify function varargout = doClassify(data,labels,holdOut,iters,shuffled) if ~any(data) for n = 1:nargout varargout{n} = NaN; end return end perf = zeros(iters,1); postpCell = cell(iters,1); predictedCell = cell(iters,1); testlabelsCell = cell(iters,1); % compute the max. number of unique hold-outs (should be > iters) holdOutN = ceil(numel(labels)*holdOut); warning('off','MATLAB:nchoosek:LargeCoefficient') maxHoldOuts = nchoosek(numel(labels),holdOutN); warning('on','MATLAB:nchoosek:LargeCoefficient') if maxHoldOuts < iters warning('Max. number of unique hold-outs is %1.0f and iterations are %1.0f.',... maxHoldOuts,iters) end parfor n = 1:iters if shuffled labels2 = labels(randperm(numel(labels))); else labels2 = labels; end c = cvpartition(labels2,'holdout',holdOut); trainData = data(c.training,:); trainLabels = labels2(c.training); if ~any(trainData) perf(n) = NaN; continue end testData = data(c.test,:); testLabels = labels2(c.test); model = NaiveBayes.fit(trainData,trainLabels); [postP,predicted,logp] = posterior(model,testData); perf(n) = (numel(find(predicted==testLabels))./numel(testLabels)).*100; postpCell{n} = postP; predictedCell{n} = predicted; testlabelsCell{n} = testLabels; end varargout{1} = perf; if nargout > 1 varargout{2} = predictedCell; varargout{3} = testlabelsCell; varargout{4} = postpCell; end end %% Function - Save and close figures function SaveAndCloseFigures while numel(findobj) > 1 set(findall(gcf,'Interpreter','Tex'),'Interpreter','None') makePrettyFigure(gcf); saveName = get(gcf,'Name'); saveas(gcf,strrep(saveName,' ','-')) close(gcf) end end
github
HelmchenLabSoftware/OCIA-master
henry_analyzeHDF5_multiDay.m
.m
OCIA-master/caImgAnalysis/analysisHDF5/henry_analyzeHDF5_multiDay.m
11,569
utf_8
74a90237433029f9bab1d1ffc0de5844
function S = henry_analyzeHDF5_multiDay(id, config) % id ... date string for the HDF5 file (e.g. 14011001) or Matlab structure from previous run % ADD ANALYSIS OF DECODING WITH LABELING OF WHICH PHASE IT IS ('NAIVE', 'LEARNING', 'EXPERT') % SEE IF TRAINING DATA SET ON EXPERT CAN ALSO PREDICT IN LEARNING % TRY TO PREDICT DPRIME FROM ACTVITY if ~isstruct(id) fileName = sprintf('%s.h5',id); animalID = sprintf('mou_bl_%s_%s',id(1:6),id(7:8)); datasetID = ['/' animalID]; % load HDF5 and convert to data structure S = loadDataFromHDF5(fileName,datasetID); else S = id; end clear id; fieldsSpots = fieldnames(S); spotFound = 0; for n = 1:numel(fieldsSpots) % loop over spots spotID = fieldsSpots{n}; if ~strcmp(spotID,config.spotID) continue else spotFound = 1; currentSpot = S.(fieldsSpots{n}); break end end if ~spotFound error('Did not find %s', config.spotID) end fieldsDays = fieldnames(currentSpot); if numel(fieldsDays) < 2 warning('Need at least 2 days for multi-day analysis. Skipping ...') S = []; return end if config.doCorr titleStr = sprintf('%s %s MultiDay Correlation',animalID,spotID); hCorr = figure('Name',titleStr,'NumberTitle','off'); end if config.doDecode titleStr = sprintf('%s %s MultiDay Decode',animalID,spotID); hDecode = figure('Name',titleStr,'NumberTitle','off'); end splot_pos = 1; for n = 2:numel(fieldsDays) dateID1 = strrep(fieldsDays{n-1},'x',''); dateID2 = strrep(fieldsDays{n},'x',''); S_day1 = currentSpot.(fieldsDays{n-1}); S_day2 = currentSpot.(fieldsDays{n}); % match RoiSets roiID_day1 = S_day1.ROISets.(cell2mat(fieldnames(S_day1.ROISets))).ROISet(:,1); roiID_day2 = S_day2.ROISets(cell2mat(fieldnames(S_day1.ROISets))).ROISet(:,1); matchIx = zeros(1,2); pos = 1; for m1 = 1:numel(roiID_day1) if strcmpi(roiID_day1{m1},'npil') continue end for m2 = 1:numel(roiID_day2) if strcmpi(roiID_day1{m1},roiID_day2{m2}) matchIx(pos,1:2) = [m1,m2]; pos = pos + 1; end end end roiID = roiID_day1(matchIx(:,1)); fprintf('\n%s - %s: %1.0f matching Rois\n',dateID1,dateID2,pos-1) [caTracesMean_day1, caTracesTrials_day1, tPs] = doSingleDayAnalysis(S_day1,config); [caTracesMean_day2, caTracesTrials_day2] = doSingleDayAnalysis(S_day2,config); % Correlation analysis if config.doCorr [corrMatch, corrNonMatchDiffDay, corrNonMatchSameDay] = ... doMultiDayCorrelationAnalysis(caTracesMean_day1,caTracesMean_day2,matchIx); figure(hCorr) % plot target subplot(numel(fieldsDays)-1,2,splot_pos); splot_pos = splot_pos + 1; [f,x] = ecdf(corrNonMatchDiffDay{1}); stairs(x,f,'k'), hold on [f,x] = ecdf(corrNonMatchSameDay{1}); stairs(x,f,'b'), hold on [f,x] = ecdf(corrMatch{1}); stairs(x,f,'r'), hold on legend({'NMatch Diff Day','NMatch Same Day','Match'},'location','northwest') xlabel('r'), ylabel('cumulative F') title(sprintf('%s - %s Target',dateID1,dateID2),'interpreter','none') % plot distractor subplot(numel(fieldsDays)-1,2,splot_pos); splot_pos = splot_pos + 1; [f,x] = ecdf(corrNonMatchDiffDay{2}); stairs(x,f,'k'), hold on [f,x] = ecdf(corrNonMatchSameDay{2}); stairs(x,f,'b'), hold on [f,x] = ecdf(corrMatch{2}); stairs(x,f,'r'), hold on xlabel('r'), ylabel('cumulative F') title(sprintf('%s - %s Distractor',dateID1,dateID2),'interpreter','none') end % Decoding analysis if config.doDecode [perfTrue, perfShuf] = doMultiDayDecode(caTracesTrials_day1,... caTracesTrials_day2,matchIx,tPs,config); roiID{end+1} = 'Pop'; figure(hDecode) subplot(numel(fieldsDays)-1,1,n-1) hErr = errorbar(1:numel(roiID),mean(perfShuf,1),std(perfShuf,1),'sk'); removeErrorBarEnds(hErr); hold on hErr = errorbar(1:numel(roiID),mean(perfTrue,1),std(perfTrue,1),'or'); removeErrorBarEnds(hErr); set(gca,'xlim',[0 numel(roiID)+1],'xtick',1:numel(roiID),'xticklabel',roiID) title(sprintf('%s - %s',dateID1,dateID2),'interpreter','none') ylabel('Perf. (%)') if n == numel(fieldsDays) xlabel('ROIs'), legend({'Shuf','True'}) end end end if config.doCorr adjustSubplotAxes(hCorr,'x',[-1 1]); end if config.doDecode adjustSubplotAxes(hDecode,'y',[0 100]); end S.animalID = animalID; if config.doSave SaveAndCloseFigures end end %% Function - doMultiDayDecode function [perfTrue, perfShuf] = ... doMultiDayDecode(trials_day1,trials_day2,matchIx,tPs,config) % train classifier on data from day 1 and test on day 2 stimStartIx = find(tPs>=0,1,'first'); tPsStim = tPs(stimStartIx:end); tPsStimI = tPsStim(1):0.1:tPsStim(end); % interpolation iters = config.iters; % single-cell analysis perfTrue = zeros(iters,size(matchIx,1)); perfShuf = zeros(iters,size(matchIx,1)); for n1 = 1:size(matchIx,1) roi_day1_targ = squeeze(trials_day1{1}(matchIx(n1,1),:,:))'; roi_day1_targ = roi_day1_targ(:,stimStartIx:end); roi_day1_dist = squeeze(trials_day1{2}(matchIx(n1,1),:,:))'; roi_day1_dist = roi_day1_dist(:,stimStartIx:end); trainLabels = [ones(size(roi_day1_targ,1),1); repmat(2,size(roi_day1_dist,1),1)]; trainData = [roi_day1_targ; roi_day1_dist]; roi_day2_targ = squeeze(trials_day2{1}(matchIx(n1,2),:,:))'; roi_day2_targ = roi_day2_targ(:,stimStartIx:end); roi_day2_dist = squeeze(trials_day2{2}(matchIx(n1,2),:,:))'; roi_day2_dist = roi_day2_dist(:,stimStartIx:end); testLabels = [ones(size(roi_day2_targ,1),1); repmat(2,size(roi_day2_dist,1),1)]; testData = [roi_day2_targ; roi_day2_dist]; perfTrue(1:iters,n1) = doClassify(trainData,trainLabels,testData,testLabels,0.2,iters,0); perfShuf(1:iters,n1) = doClassify(trainData,trainLabels,testData,testLabels,0.2,iters,1); % interpolation to reduce dimensionality trainDataI = (interp1(tPsStim,trainData',tPsStimI))'; testDataI = (interp1(tPsStim,testData',tPsStimI))'; if n1 == 1 trainDataPop = trainDataI; testDataPop = testDataI; else trainDataPop = [trainDataPop, trainDataI]; testDataPop = [testDataPop, testDataI]; end end % population analysis % without dimensionality reduction perfTruePop = doClassify(trainDataPop,trainLabels,testDataPop,testLabels,0.2,iters,0); perfShufPop = doClassify(trainDataPop,trainLabels,testDataPop,testLabels,0.2,iters,1); % dimensionality reduction (PCA) % [pc,score,latent] = princomp([trainDataPop; testDataPop]); % varExplained = cumsum(latent)./sum(latent); % cutoff = find(varExplained>0.9,1,'first'); % trainData = score(1:numel(trainLabels),1:cutoff); % testData = score(numel(trainLabels)+1:end,1:cutoff); % perfTruePop = doClassify(trainData,trainLabels,testData,testLabels,0.2,iters,0); % perfShufPop = doClassify(trainData,trainLabels,testData,testLabels,0.2,iters,1); perfTrue = [perfTrue, perfTruePop']; perfShuf = [perfShuf, perfShufPop']; end %% Function - doClassify function perf = doClassify(trainData,trainLabels,testData,testLabels,holdOut,iters,shuffled) % compute the max. number of unique hold-outs (should be > iters) holdOutN = ceil(numel(trainLabels)*holdOut); warning('off','MATLAB:nchoosek:LargeCoefficient') maxHoldOuts = nchoosek(numel(trainLabels),holdOutN); warning('on','MATLAB:nchoosek:LargeCoefficient') if maxHoldOuts < iters warning('Max. number of unique hold-outs is %1.0f and iterations are %1.0f.',... maxHoldOuts,iters) end parfor n = 1:iters if shuffled trainLabels2 = trainLabels(randperm(numel(trainLabels))); else trainLabels2 = trainLabels; end c = cvpartition(trainLabels2,'holdout',holdOut); trainData2 = trainData(c.training,:); trainLabels2 = trainLabels2(c.training); model = NaiveBayes.fit(trainData2,trainLabels2); [~,predicted] = posterior(model,testData); perf(n) = (numel(find(predicted==testLabels))./numel(testLabels)).*100; end varargout{1} = perf; end %% Function - doMultiDayCorrelationAnalysis function [corrMatch, corrNonMatchDiffDay, corrNonMatchSameDay] = ... doMultiDayCorrelationAnalysis(ca_day1,ca_day2,matchIx) % approach: first correlate time series of different cells from different days to get 'null' % distribution of correlations; then correlate for the same cells on different days and compare to % 'null' distribution corrMatch = cell(1,numel(ca_day1)); corrNonMatchDiffDay = cell(1,numel(ca_day1)); corrNonMatchSameDay = cell(1,numel(ca_day1)); for n1 = 1:size(matchIx,1) for t = 1:numel(ca_day1) % matching Rois roi_day1 = ca_day1{t}(matchIx(n1,1),:); roi_day2 = ca_day2{t}(matchIx(n1,2),:); corrMatch{t}(end+1) = corr(roi_day1',roi_day2'); % non-matching Rois for n2 = 1:size(matchIx,1) if n1 == n2 continue end roi_day2 = ca_day2{t}(matchIx(n2,2),:); corrNonMatchDiffDay{t}(end+1) = corr(roi_day1',roi_day2'); roi2_day1 = ca_day1{t}(matchIx(n2,1),:); corrNonMatchSameDay{t}(end+1) = corr(roi_day1',roi2_day1'); end end end end %% Function - doSingleDayAnalysis function [caTracesMean, caTracesTrialsOut, tPs] = doSingleDayAnalysis(S,config) psTimesIx = round(config.psTimes.*config.imgRate); stim = S.behav.stim; trials = min(numel(stim), numel(S.caTraces)); % figure out target and non-target targetNontarget = []; for n = 1:numel(S.behav.target) if ~S.behav.target{n} continue end if stim{n} == 1 targetNontarget = [1 2]; else targetNontarget = [2 1]; end break end fprintf('Target: stim %1.0f\n',targetNontarget(1)) fprintf('Non-Target: stim %1.0f\n',targetNontarget(2)) caTracesTrials = cell(1,2); caTracesTrialsOut = cell(1,2); for t = 1:trials caTraces = S.caTraces{t}; imgDelay = S.behav.imgDelays{t}; stimStartTime = S.behav.stimStartTime{t}-imgDelay; timeCa = (1:size(caTraces,2))./config.imgRate; stimStartIx = find(timeCa>=stimStartTime,1,'first'); psStartIx = stimStartIx + psTimesIx(1); if psStartIx < 1 error('psStart too early on trial %1.0f',t) end psStopIx = stimStartIx + psTimesIx(2); if psStopIx > size(caTraces,2) % warning('psStop too late on trial %1.0f. Skipping ...',t) continue end if t == 1 tPs = ((psStartIx:psStopIx)-stimStartIx)./config.imgRate; end if isempty(caTracesTrials{stim{t}}) caTracesTrials{stim{t}} = caTraces(:,psStartIx:psStopIx); else caTracesTrials{stim{t}} = cat(3, caTracesTrials{stim{t}}, caTraces(:,psStartIx:psStopIx)); end end stimStartIx = find(tPs>=0,1,'first'); for n = 1:numel(caTracesTrials) data = nanmean(caTracesTrials{n},3); % baseline normalization / filter for m = 1:size(data,1) data(m,:) = data(m,:) - nanmean(data(m,1:stimStartIx)); data(m,:) = sgolayfilt(data(m,:),3,11); end caTracesMean{1,targetNontarget(n)} = data; caTracesTrialsOut{1,targetNontarget(n)} = caTracesTrials{n}; end end %% Function - Save and close figures function SaveAndCloseFigures while numel(findobj) > 1 set(findall(gcf,'Interpreter','Tex'),'Interpreter','None') makePrettyFigure(gcf); saveName = get(gcf,'Name'); saveas(gcf,strrep(saveName,' ','-')) close(gcf) end end
github
HelmchenLabSoftware/OCIA-master
analyseStimulusTuning.m
.m
OCIA-master/caImgAnalysis/postAnalysis/analyseStimulusTuning.m
9,135
utf_8
9c894bb7f270ae312885d479465bfde5
function multiCompTuningPairs = analyseStimulusTuning(multiComparisonStats, stimIDs, multiCompareThresh, saveName, plotLimits, doSaveTuningPlot, doSavePairedTuningPlot) % By using the results obtained by multiStimComparison this function % plots the significance levels for different comparison metric (every % stimulus compared with all) in a pairwise overview bar plot % % There also exists significance if one stimulus parameter response is significantly % lower than all the others! % % A comparison is significant for the given threshold if the comparsion % intervals do not overlap = variance interval does not contain 0 % % doSaveTuningPlot: Saves all bar plots and plots significances (also % generates plot if there is no significance % % doSavePairedTuningPlot: Only plots significant pairs in subplots % % Usage: analyseStimulusTuning(multiComparisonStats, stimIDs, multiCompareThresh, saveName, plotLimits, doSaveTuningPlot, doSavePairedTuningPlot) % % % Author: A. van der Bourg, 2014 % % TODO: % * Add axe handle for Balazs %% Init variables nROIs = size(multiComparisonStats, 1); % ROI pairwise significance array multiCompTuningPairs = cell(nROIs,1); %% Find exclusively pairs for groups that are significant for iROI = 1: nROIs % Obtain the multiple comparison stats for a given ROI comparisonMatrix = multiComparisonStats{iROI, 1}; significanceIndex = zeros(size(comparisonMatrix, 1), 1); % Find all significant pairs for iPair = 1: size(comparisonMatrix, 1) % Check if variance interval is between zero (if both negative % or if both positive it is significant, otherwise not)! if comparisonMatrix(iPair, 3) < 0 if comparisonMatrix(iPair, 5) < 0 significanceIndex(iPair, 1) = 1; else significanceIndex(iPair, 1) = 0; end; else if comparisonMatrix(iPair, 3) > 0 if comparisonMatrix(iPair, 5) > 0 significanceIndex(iPair, 1) = 1; else significanceIndex(iPair, 1) = 0; end; end; end; % Store the significant pair information %multiCompTuningPairs{iROI, 1} = significanceIndex; end; %% Save significant pairs sigPairs = generateSigPairs(iROI, significanceIndex, multiComparisonStats); multiCompTuningPairs{iROI, 1} = sigPairs; %% Perform plotting for all conditions if doSaveTuningPlot == 1 || doSaveTuningPlot == 2 %Make a bar plot figHandle = figure; meanResps = multiComparisonStats{iROI, 2}'; errorHandles = meanResps(2,:); meanResps = meanResps(1,:); axeH = bar(meanResps, 'hist'); ylabel('Mean Evoked Response'); % Ignore too small plotlimits so star significance is % plotted correctly. if max(meanResps(:)) < plotLimits(2) ylim(plotLimits); end; set(gca, 'XTickLabel', stimIDs); set(axeH,'FaceColor',[1,1,1]*0.5,'LineWidth',1) hold on; errorHandle = errorbar(meanResps, errorHandles, '+'); set(errorHandle,'color',[1,1,1]*0.52); %Add significance starts with sigstar function (sometimes %messy) if (length(significanceIndex(significanceIndex ==1))) >0 hold on; sigPairs = generateSigPairs(iROI, significanceIndex, multiComparisonStats); sigVector = ones(1,size(sigPairs,2)) * multiCompareThresh; sigstar(sigPairs, sigVector); hold off; end; hold off; if doSaveTuningPlot == 2 set(gca, 'FontSize', 8); %figHandle saveFigToDir(gcf, [saveName '_StimulusTuning_ROI' num2str(iROI)], 'ROIStimulusTuning', doSaveTuningPlot, 1, 1); close all; end; end; %% This plot only plots significant pairs as indicated in % significanceIndex and generateSigPairs if doSavePairedTuningPlot == 1 || doSavePairedTuningPlot == 2 if (length(significanceIndex(significanceIndex ==1))) >0 mainHandle = figure; % Pair matrix that is feeded to bar (Mx2 matrix) pairSet = zeros(length(significanceIndex(significanceIndex ==1)), 2); %Get pairs and error handles sigPairs = generateSigPairs(iROI, significanceIndex, multiComparisonStats); sigVector = ones(1,size(sigPairs,2)) * multiCompareThresh; %Obtain mean values meanResps = multiComparisonStats{iROI, 2}'; errorHandles = meanResps(2,:); errorHandles = errorHandles(1, 1:2); %Can this be done in one step? Dunno... meanResps = meanResps(1,:); pairIndex = 1; for iPair = sigPairs pairSet(pairIndex,1) = meanResps(1, iPair{1,1}(1)); pairSet(pairIndex, 2) = meanResps(1, iPair{1,1}(2)); pairIndex = pairIndex + 1; end; %Plot the significant pairs as subplots (only semi-elegant %solution for now to circumvent problems with paired %bar-plots [xIndex, yIndex] = findSubplotConfig(size(sigPairs,2)); %Iterate through all subplots for pairIndex = 1:size(sigPairs, 2) subplot(yIndex, xIndex, pairIndex); %Hack for subplots figHandle = gcf; hold on; barSet = [pairSet(pairIndex, 1), pairSet(pairIndex, 2)]; axeH = bar(barSet); ylabel('Mean Evoked Response'); % Ignore too small plotlimits so star significance is % plotted correctly. if max(meanResps(:)) < plotLimits(2) ylim(plotLimits); end; errorHandle = errorbar(barSet, errorHandles, '+'); set(errorHandle,'color',[1,1,1]*0.52); sigstar([1,2], sigVector(1)); %Get pair and label x-axis stimLabel = [stimIDs(sigPairs{1, pairIndex}(1)), stimIDs(sigPairs{1, pairIndex}(2))]; set(gca, 'XTick', [1,2]); set(gca, 'XTickLabel', stimLabel); set(axeH,'FaceColor',[1,1,1]*0.5,'LineWidth',1) set(gca, 'FontSize', 8); title('Significant Multiple Comparison Pairs'); end; hold off; if doSavePairedTuningPlot == 2 saveFigToDir(mainHandle, [saveName '_PairedStimulusTuning_ROI' num2str(iROI)], 'ROIPairedStimulusTuning', doSavePairedTuningPlot, 1, 1); close all; end; end; end; end; end function pairVectCell = generateSigPairs(roiIndex, significanceIndex, multiComparisonStats) % Function to generate a pair vector cell array that is needed to plot % all significant multi-comparisons using sigstar pairDims = size(significanceIndex, 1); pairVectCell = cell(1, length(significanceIndex(significanceIndex ==1))); %Go through all possibilties and get the significant paired elements pairVectIndex =1; for pairIndex = 1:pairDims if significanceIndex(pairIndex,1) == 1 % We obtain the pairs by getting the paired numbers for the % given significanceIndex entry in multiComparisonStats pairVectCell{1, pairVectIndex} = [multiComparisonStats{roiIndex, 1}(pairIndex,1), multiComparisonStats{roiIndex, 1}(pairIndex,2)]; pairVectIndex = pairVectIndex +1; end; end end function [xIndex, yIndex] = findSubplotConfig(significantPairs) % Function to evaluate which configuration is best to plot subplots % First check odd cases then even cases if mod(significantPairs,2) == 0 % An even number with sqrt can configure sqrt(x)*sqrt(x) if mod(sqrt(significantPairs),2) ==0 xIndex = sqrt(significantPairs); yIndex = sqrt(significantPairs); else xIndex = significantPairs / 2; yIndex = 2; end; % Odd cases else if sqrt(significantPairs)*sqrt(significantPairs) == significantPairs; xIndex = sqrt(significantPairs); yIndex = sqrt(significantPairs); else xIndex = round(significantPairs/2); yIndex = 2; end; end end
github
HelmchenLabSoftware/OCIA-master
doROIRGBPlot.m
.m
OCIA-master/caImgAnalysis/postAnalysis/plotting/doROIRGBPlot.m
2,018
utf_8
ee970a4efdf6e6b9c9d7596a4dd7e72a
%% Function - doROIRGBPlot function figH = doROIRGBPlot(axeH, imgDims, ROISet, leftImg, meanImage, fileID, alphaVal) % created by B. Laurenczy - 2013 % 2D matrix for the alpha transparency of each ROI on the final image alphaMat = ones(imgDims(1), imgDims(2)); % 3D matrix for the RGB values of each ROI ROIRGB = zeros(imgDims(1), imgDims(2), 3); % colormap with a different color for each ROI CMap = jet(size(ROISet, 1)); % 2D matrix containing the indexes of the ROIs for the text plotting ROICounterImg = zeros(size(alphaMat)); % go trough each ROI to fill in the above variables for iROI = 1 : size(ROISet, 1); % extract the ROIMask and the ROI's ID ROIMask = ROISet{iROI, 2}; % set (a bit) transparent the regions where this ROI is alphaMat(ROIMask == 1) = alphaVal; ROICounterImg(ROIMask == 1) = iROI; [row, col] = ind2sub(size(alphaMat), find(ROIMask)); % assign the color for each pixel for i = 1 : length(row); ROIRGB(row(i), col(i), :) = CMap(iROI, :); end end % display the ROIs on mean frame in RGB multi-color if isempty(axeH); figH = figure('Name', sprintf('ROIs for %s', fileID), 'NumberTitle', 'off'); if ~isempty(leftImg); subplot(1, 2, 1, 'Parent', figH); imshow(linScale(leftImg), 'Parent', gca); subplot(1, 2, 2, 'Parent', figH); axeH = gca; else axeH = axes('Parent', figH); end; else figH = getParentFigure(axeH); end; imshow(ROIRGB, 'Parent', axeH); hold(axeH, 'on'); imShowHandle = imshow(meanImage{1}, [], 'InitialMagnification', 'fit', 'Parent', axeH); set(imShowHandle, 'AlphaData', alphaMat); regionGroups = regionprops(ROICounterImg, ROICounterImg, 'MaxIntensity', 'Extrema'); hold(axeH, 'on'); for iGroup = 1 : numel(regionGroups) regionCenter = regionGroups(iGroup).Extrema; text(regionCenter(1,1), regionCenter(1,2)-1, ROISet{iGroup, 1}, 'Parent', axeH, ... 'Clipping', 'on', 'Color', 'r', 'FontWeight', 'bold', 'Tag', 'CellLabel'); end hold(axeH, 'off'); end
github
HelmchenLabSoftware/OCIA-master
PlotRoiTimecourse.m
.m
OCIA-master/caImgAnalysis/postAnalysis/plotting/PlotRoiTimecourse.m
7,108
utf_8
5d58dabaf73fc2b72e2636360675e780
function varargout = PlotRoiTimecourse(varargin) % plot timecourses of Rois in RoiSet % in1 ... fcs-file / cell-array of tiff-files (max. 2) % in2 ... RoiSet % returns structure with fields time (adjusted by Roi location), stats type % and value and roi ID % return time axis in varargout{1} % return timeseries as cell in varargout{2} % return Roi IDs as cell in varargout{3} % this file written by Henry Luetcke ([email protected]) filename = varargin{1}; roifile = varargin{2}; %% Parameters % imaging frequency freq = 7.81; % no. of slices to delete del_slice = 1; % bg. threshold in percentile bg_thresh = 1; % smoothing span (0 for none) % smoothing is performed by local regression using weighted linear least % squares and a 2nd degree polynomial model % span is provided in percentage of total number of data points (<=1) smooth_span = 0; % highpass filter cutoff in Hz (0 for none) % this is an experimental highpass filter that works in the fourier domain % and attemts to remove frequency components slower than the cutoff hp_cutoff = 0; % run single channel analysis on channel 2 SwitchChannels = 0; % type of stats image ('none','dff','drr') stats_type = 'drr'; ts.stats_type = stats_type; switch stats_type case 'none' stats_type = 1; case 'drr' stats_type = 2; case 'dff' stats_type = 3; end % baseline (e.g. no. of baseline frames) base = 10; % stimulus description in vector format (0 0 0 1 1 0 0 ...) % empty to use base frames for stats calculation stim_vector = []; %% Load data and preprocess if ~isnumeric(filename) if ~iscellstr(filename) files{1} = filename; else files = filename; end % figure title fig_title = strrep(files{1},'.fcs',''); fig_title = strrep(fig_title,'.tif',''); if ~isempty(strfind(files{1},'.fcs')) img = import_raw(filename); else img_data = tif2mat(files{1},'nosave'); img.ch1 = img_data.data; if length(files) > 1 img_data = tif2mat(files{2},'nosave'); img.ch2 = img_data.data; clear img_data end end else fig_title = 'workspace variable'; img.ch1 = filename; end pixel_time = (1/freq)/(size(img.ch1,1)*size(img.ch1,2)); % load roi set if ~iscell(roifile) roi_set = ij_roiDecoder(roifile,[size(img.ch1,1) size(img.ch1,2)]); else roi_set = roifile; % format from roi timecourse extractor??? if size(roi_set,2) == 3 for n = 1:size(roi_set,1) a = zeros(roi_set{n,2}); for m = 1:size(roi_set{n,3}) a(roi_set{n,3}(m)) = 1; end roi_set{n,4} = bwpack(a); end roi_set(:,2:3) = []; end end % background Rois are named bg.roi if sum(strcmp(roi_set(:,1),'bg.roi')) bg_mask = bwunpack(roi_set{strcmp(roi_set(:,1),'bg.roi'),2}); roi_set(strcmp(roi_set(:,1),'bg.roi'),:)=[]; else bg_mask = []; end % big bad coding practice disregard here % switch channels % this can be used to do single channel analysis on channel 2 if SwitchChannels img.ch1 = img.ch2; warning('Switched channels 1 and 2. Now evaluating channel 2.'); end if isempty(bg_mask) img.ch1 = double(PreprocImageData(img.ch1,del_slice,bg_thresh)); else img.ch1 = double(PreprocImageData(img.ch1,del_slice,bg_mask)); end if stats_type == 2 if isempty(bg_mask) img.ch2 = double(PreprocImageData(img.ch2,del_slice,bg_thresh)); else img.ch2 = double(PreprocImageData(img.ch2,del_slice,bg_mask)); end else if isfield(img,'ch2') img = rmfield(img,'ch2'); end end [dur,time] = gui_CalculateTimeVector(1:size(img.ch1,3),freq,[]); figure('Name',fig_title,'NumberTitle','off'); hold all for n = 1:size(roi_set,1) fprintf('\nRoi %s\n',roi_set{n,1}); mask = bwunpack(roi_set{n,2}); ts.ch1{n} = mean(GetRoiTimeseries(img.ch1,mask),1); if stats_type == 2 ts.ch2{n} = mean(GetRoiTimeseries(img.ch2,mask),1); % calculate DRR stats = ts.ch1{n} ./ ts.ch2{n}; elseif stats_type == 1 || stats_type == 3 stats = ts.ch1{n}; end if stats_type == 2 || stats_type == 3 % estimate baseline values (according to stimulus protocol) % without stim. protocol, choose first 10 timepoints f0_mat = CalculateF0(stats,stim_vector,base); % calculate stats stats = ((stats-f0_mat) ./ f0_mat).* 100; stats(stats==Inf) = 0; stats(stats==-Inf) = 0; stats(stats==NaN) = 0; end % smoothing if smooth_span stats = smooth(stats,smooth_span,'loess'); end % highpass filter if hp_cutoff stats = mpi_BandPassFilterTimeSeries(stats,1/freq,hp_cutoff,freq*2); end ca_shift = mean(find(mask'==1)) * pixel_time; ca_shift = (1/freq) - ca_shift; ts.time{n} = time - ca_shift; fprintf('\nAdjusted Roi time by %1.2f frames based on mean ROI location\n',... ca_shift/(1/freq)); ts.stats{n} = stats; ts.roi_id{n} = roi_set{n,1}; plot(ts.time{n},stats); clear stats end legend(ts.roi_id); varargout{1} = ts; %% Image preprocessing function img_data = PreprocImageData(img_data,del_slice,bg_thresh) % in1 ... raw image matrix % in2 ... number of initial slices to delete % in3 ... background subtraction threshold (percentile) img_data(:,:,1:del_slice) = []; if max(reshape(img_data,1,numel(img_data))) > 256 img_data = img_data./255; end img_data = uint8(img_data); if ~isempty(bg_thresh) if size(bg_thresh,1) > 1 img_data = bg_subtract_HL(img_data,bg_thresh,1,'roi'); else img_data = bg_subtract_HL(img_data,bg_thresh,1,'percentile'); end end img_data(img_data<0)=0; function f0_mat = CalculateF0(roi_mat,stim,base) if isempty(stim) f0_mat = roi_mat(:,1:base); f0_mat = nanmean(f0_mat,2); f0_mat = repmat(f0_mat,1,size(roi_mat,2)); return end % binarise stim vector (each stimulus type leads to % renormalization) stim(stim>0)=1; % define frames of stimulus onset stim_onset = zeros(size(stim)); for n = 2:length(stim) if stim(n) == 1 && stim(n-1) == 0 stim_onset(n) = 1; end end % designate the base frames BEFORE stimulus onset as baseline stim_base = zeros(size(stim)); for n = base+1:length(stim) if stim_onset(n) == 1 stim_base(n-base:n-1) = 1; end end f0_mat = zeros(size(roi_mat)); for n = 1:length(stim) if stim_base(n) == 1 stim_base(n:n+base-1) = 0; % find endpoint of current F0 interval (the frame before % next normalization interval start) f0_stop = find(stim_base==1,1,'first')-1; if isempty(f0_stop) f0_stop = length(stim); end for pixel = 1:size(f0_mat,1) current_mean = mean(roi_mat(pixel,n:n+base-1)); f0_mat(pixel,n:f0_stop) = current_mean; end end end % timepoints before first stimulus get F0 value for first % pre-stimulus baseline pre_stim1 = find(f0_mat(1,:)~=0,1,'first'); for pixel = 1:size(f0_mat,1) f0_mat(pixel,1:pre_stim1-1) = f0_mat(pixel,pre_stim1); end
github
HelmchenLabSoftware/OCIA-master
doPSAveragePlotForROI.m
.m
OCIA-master/caImgAnalysis/postAnalysis/plotting/doPSAveragePlotForROI.m
1,893
utf_8
2ba38f9d133c145dfca2444bc537918b
%% Function - doPSAveragePlot function [fig, fig2] = doPSAveragePlotForROI(iROI, ROIID, PSROIStatsData, uniqueStims,... stimNames, frameRate, baseFrames) figName = sprintf('PSPlot %s', ROIID); fig = figure('Name', figName, 'NumberTitle', 'off'); hold all; % setup subplot if numel(uniqueStims) > 3; M = ceil(sqrt(numel(uniqueStims))); N = M; else M = numel(uniqueStims); N = M; end; if N * (M - 1) >= numel(uniqueStims); M = M - 1; end; AllStimsPSTrace = []; for iStim = 1 : size(PSROIStatsData, 2); stimPSTrace = PSROIStatsData{iROI, iStim}; AllStimsPSTrace = [AllStimsPSTrace; stimPSTrace]; %#ok<AGROW> subplot(M, N, iStim); PSTime = (1:size(stimPSTrace,2)) ./ frameRate; PSTime = PSTime - (baseFrames ./ frameRate); hErr = errorbar(PSTime, nanmean(stimPSTrace, 1), sem(stimPSTrace, 1), 'k', 'LineWidth', 2); hold on; removeErrorBarEnds(hErr); % if iStim >= (M * N) - N + 1; if iStim >= size(PSROIStatsData, 2) - N + 1; xlabel('Time [s]'); else set(gca, 'XTickLabel', []); end; if mod(iStim, N) == 1; ylabel('DFF [%] \pm SEM'); else set(gca, 'YTickLabel', []); end; title(sprintf('%s\\_%s', ROIID, sprintf('%3.1fkHz', stimNames(iStim) / 1000))); end; adjustSubplotAxes(fig, 'y', [], 'x', [min(PSTime) max(PSTime)]); tightfig; hold off; [psPeak(iROI), i] = max(nanmean(stimPSTrace,1)); %#ok<ASGLU> psPeakSD(iROI) = nanstd(stimPSTrace(:, i)); %#ok<NASGU> figName = strrep(figName, 'PSPlot', 'PSPlotAllStims'); fig2 = figure('Name',figName,'NumberTitle','off'); hold all; plot(PSTime, AllStimsPSTrace, 'Color',[0.5 0.5 0.5]); hErr = errorbar(PSTime, nanmean(AllStimsPSTrace,1), sem(AllStimsPSTrace,1),... 'r','LineWidth',2); removeErrorBarEnds(hErr); xlabel('Time [s]'); ylabel('DFF [%] \pm SEM'); title(sprintf('PSPlot all stims %s', ROIID)); end
github
HelmchenLabSoftware/OCIA-master
glmAnalysis2P.m
.m
OCIA-master/caImgAnalysis/Decoding_2PI/glmAnalysis2P.m
6,600
utf_8
3db4ec3701a3383bb6d15241bffd2e87
function glmAnalysis2P % GLM analysis function for two-photon imaging data % input: structure created by GetRoiStats (*_RoiStats) % make GLM design matrix if config.doGLMstats onsettau = 0.05; tau = 0.5; tAxis_singleRun = (1:numel(config.stim{1}))./config.frameRate{1}; modelTransient = spkTimes2Calcium(0,onsettau,1,tau,0,0,... config.frameRate{1},tAxis_singleRun(end)); modelC = cell(1,numel(config.stim)); for n = 1:numel(config.stim) currentStim = config.stim{n}; uniqueStims = unique(currentStim); uniqueStims(uniqueStims==0) = []; currentModel = []; for m = 1:numel(uniqueStims) stimOn = zeros(size(currentStim)); stimOn(currentStim==uniqueStims(m)) = 1; stimOnConv = conv(stimOn,modelTransient); stimOnConv = stimOnConv(1:numel(stimOn)); currentModel = [currentModel reshape(stimOnConv,numel(stimOnConv),1)]; end % apply low-pass filter to the model modelC{n} = doLowPassFilter(currentModel,config.LowPass); end % concatenate model A = modelC{1}; for n = 2:length(modelC) A = [A; modelC{n}]; end % ensure column vectors for model if size(A,1) < size(A,2) A = A'; end modelC = A; tAxis_runs = (1:size(modelC,1))./config.frameRate{1}; % Orthogonalize the model model = Gram_Schmidt_Process(modelC); end % Significance level, corrected for multiple comparisons % number of comparisons = cell number + 1 (neuropil) % this applies to significance tests of the GLM only switch lower(config.multiCompareProc) case 'none' alphaCorrected = config.alpha; case 'bonf' alphaCorrected = config.alpha ./ (cellNo+1); otherwise error('Multiple comparison procedure %s not implemented',... config.multiCompareProc); end %% GLM analysis if config.doGLMstats for currentRoi = 1:size(RoiMatAllRuns,1) config.glmStatsRoi{currentRoi} = ... doGLMfit(model,RoiMatAllRuns(currentRoi,:),alphaCorrected); end end %% Plot GLM and PS psPlotDir = sprintf('PsPlots_%s',config.saveName); if exist(psPlotDir) ~= 7 mkdir(psPlotDir) end for currentRoi = 1:size(RoiMatAllRuns,1) if config.doGLMstats if currentRoi == size(RoiMatAllRuns,1) figName = sprintf('GLM fit Npil'); else figName = sprintf('GLM fit Roi%s',roiLabel{currentRoi}); end fig = figure('Name',figName,'NumberTitle','off'); hold all glmStats = config.glmStatsRoi{currentRoi}; plot(tAxis_runs,RoiMatAllRuns(currentRoi,:),'k'), hold on plot(tAxis_runs,model,'r'), hold on hErr = errorbar(tAxis_runs,glmStats.yfit,glmStats.ciL,glmStats.ciU,... 'g','LineWidth',1.5); removeErrorBarEnds(hErr) legend({'DRR' 'Stim' 'Model'}) set(gca,'xlim',[0 max(tAxis_runs)]) xlabel('Time / s') ylabel('DRR / %') titleStr = sprintf('b=%1.2f (p=%1.2f)',glmStats.b(2),glmStats.pBeta(2)); title(titleStr) end if currentRoi == size(RoiMatAllRuns,1) figName = sprintf('PsPlot Npil'); else figName = sprintf('PsPlot Roi%s',roiLabel{currentRoi}); end fig = figure('Name',figName,'NumberTitle','off'); hold all % setup subplot if numel(uniqueStims) > 3 subIdx = repmat(ceil(sqrt(numel(uniqueStims))),1,2); elseif numel(uniqueStims) == 3 subIdx = [1 3]; elseif numel(uniqueStims) == 2 subIdx = [1 2]; elseif numel(uniqueStims) == 1 subIdx = [1 1]; end AllStims = []; for currentStim = 1:size(PsPlotDataRoi,2) stimPsPlot = PsPlotDataRoi{currentRoi,currentStim}; AllStims = [AllStims;stimPsPlot]; subplot(subIdx(1),subIdx(2),currentStim) psTime = (1:size(stimPsPlot,2))./config.frameRate{1}; psTime = psTime - (config.psConfig.baseFrames./config.frameRate{1}); hErr = errorbar(psTime,nanmean(stimPsPlot,1),sem(stimPsPlot,1),... 'k','LineWidth',2); hold on removeErrorBarEnds(hErr); xlabel('Time / s') ylabel('DFF / % +- SEM') if currentRoi == size(RoiMatAllRuns,1) title(sprintf('Peri-stim plot Npil Stim %1.0f',currentStim)) else title(sprintf('Peri-stim plot Roi%s Stim %1.0f',... roiLabel{currentRoi},currentStim)) end end adjustSubplotAxes(fig,'y',[],'x',[min(psTime) max(psTime)]) saveStr = sprintf('%s%s%s',psPlotDir,filesep,strrep(figName,' ','')); saveas(fig,saveStr) close(fig) [psPeak(currentRoi),idx] = max(nanmean(stimPsPlot,1)); psPeakSD(currentRoi) = nanstd(stimPsPlot(:,idx)); figName = strrep(figName,'PsPlot','PsPlotAllStims'); fig = figure('Name',figName,'NumberTitle','off'); hold all plot(psTime,AllStims,'Color',[0.5 0.5 0.5]), hold on hErr = errorbar(psTime,nanmean(AllStims,1),sem(AllStims,1),... 'r','LineWidth',2); hold on removeErrorBarEnds(hErr); xlabel('Time / s') ylabel('DFF / % +- SEM') saveStr = sprintf('%s%s%s',psPlotDir,filesep,strrep(figName,' ','')); saveas(fig,saveStr) close(fig) end %% Function - ParseConfig function config = ParseConfig(config) % check for missing fields in config structure and add them with % default values if ~isfield(config,'doGLMstats') config.doGLMstats = 1; end % significance level for GLM stats if ~isfield(config,'alpha') config.alpha = 0.05; end % multiple comparison correction procedure (correct for the number of cells % / neuropil which are statistically tested) if ~isfield(config,'multiCompareProc') config.multiCompareProc = 'bonf'; end % these procedures are currently implemented (beta is the corrected sig. level): % 'none' ... beta = alpha % 'bonf' ... Bonferroni correction, beta = alpha/n % possible future options: % Sidak procedure % FDR procedure %% Function - doGLMfit function glmStats = doGLMfit(model,data,alpha) [b,dev,stats] = glmfit(model,data); [yfit,ciL,ciU] = glmval(b,model,'identity',stats); % important parameters from fit glmStats = struct; glmStats.b = b; glmStats.dfe = stats.dfe; % degrees of freedom glmStats.seBeta = stats.se; % SE for beta glmStats.tBeta = stats.t; % t = beta ./ sqrt((sum(res.^2)/dfe)) glmStats.pBeta = stats.p; glmStats.res = stats.resid; glmStats.yfit = yfit; glmStats.ciL = ciL; glmStats.ciU = ciU; if stats.p(2) <= alpha glmStats.sig = 1; % reject the null hypothesis else glmStats.sig = 0; % accept the null hypothesis end
github
HelmchenLabSoftware/OCIA-master
analyzeHDF5.m
.m
OCIA-master/caImgAnalysis/Decoding_2PI/analyzeHDF5.m
8,349
utf_8
fb7db0df66962b7b174a9a468b6386ab
function S = analyzeHDF5(id) % id ... date string for the HDF5 file (e.g. 14011001) or Matlab structure from previous run doSave = 1; if ~isstruct(id) fileName = sprintf('%s.h5',id); animalID = sprintf('mou_bl_%s_%s',id(1:6),id(7:8)); datasetID = ['/' animalID]; % load HDF5 and convert to data structure S = loadDataFromHDF5(fileName,datasetID); else S = id; animalID = S.animalID; S = rmfield(S,'animalID'); end clear id fieldsSpots = fieldnames(S); for n = 1:numel(fieldsSpots) % loop over spots spotID = fieldsSpots{n}; currentSpot = S.(fieldsSpots{n}); fieldsDays = fieldnames(currentSpot); for m = 1:numel(fieldsDays) % loop over days dateID = strrep(fieldsDays{m},'x',''); currentS = currentSpot.(fieldsDays{m}); fprintf('\n\nRunning analysis for %s %s %s\n',animalID,spotID,dateID) [caTracesMean, trialCount, tPs, perfTrue, perfShuf] = doSingleDayAnalysis(currentS); S.(fieldsSpots{n}).(fieldsDays{m}).caTracesMean = caTracesMean; S.(fieldsSpots{n}).(fieldsDays{m}).trialCount = trialCount; S.(fieldsSpots{n}).(fieldsDays{m}).tPs = tPs; S.(fieldsSpots{n}).(fieldsDays{m}).perfTrue = perfTrue; S.(fieldsSpots{n}).(fieldsDays{m}).perfShuf = perfShuf; %{ % Average Neuropil signal for target and distractor titleStr = sprintf('%s %s %s Avg Npil',animalID,spotID,dateID); h = figure('Name',titleStr,'NumberTitle','off'); plot(tPs,caTracesMean{1}(end,:),'k'), hold on plot(tPs,caTracesMean{2}(end,:),'r') legend({sprintf('Targ (%1.0f trials)',trialCount(1)),... sprintf('Dist (%1.0f trials)',trialCount(2))}) % Average ROI traces for target and distractor titleStr = sprintf('%s %s %s Avg ROI',animalID,spotID,dateID); h = figure('Name',titleStr,'NumberTitle','off'); nROIs = size(caTracesMean{1},1)-1; caTracesMeanMat = [caTracesMean{1}(1:nROIs,:); caTracesMean{2}(1:nROIs,:)]; caTracesMeanMat = ScaleToMinMax(caTracesMeanMat,0,1); subplot(1,2,1) % target imagesc(tPs,1:nROIs,caTracesMeanMat(1:nROIs,:),[0 1]) xlabel('Time (s)'), ylabel('ROI') title(sprintf('Target (%1.0f trials)',trialCount(1))) subplot(1,2,2) % distractor imagesc(tPs,1:nROIs,caTracesMeanMat(nROIs+1:end,:),[0 1]) xlabel('Time (s)'), ylabel('ROI') title(sprintf('Distractor (%1.0f trials)',trialCount(2))) colormap('hot'), colorbar % NaiveBayes performance titleStr = sprintf('%s %s %s NaiveBayes',animalID,spotID,dateID); h = figure('Name',titleStr,'NumberTitle','off'); shadedErrorBar(tPs,nanmean(perfShuf,1),nanstd(perfShuf,[],1),'k',1); hold on shadedErrorBar(tPs,nanmean(perfTrue,1),nanstd(perfTrue,[],1),'r',1); set(gca,'xlim',[min(tPs) max(tPs)]) legend({'Shuf','True'}), xlabel('Time (s)'), ylabel('Classification Perf. +- SD (%)') %} end end S.animalID = animalID; % if doSave % SaveAndCloseFigures % end end %% Function - doSingleDayAnalysis function [caTracesMean, trialCount, tPs, perfTrue, perfShuf] = doSingleDayAnalysis(S) imgRate = 76.9; % in Hz psTimes = [-0.5 2]; % in s psTimesIx = round(psTimes.*imgRate); stim = S.behav.stim; trials = numel(stim); % figure out target and non-target targetNontarget = []; for n = 1:numel(S.behav.target) if ~S.behav.target{n} continue end if stim{n} == 1 targetNontarget = [1 2]; else targetNontarget = [2 1]; end break end fprintf('Target: stim %1.0f\n',targetNontarget(1)) fprintf('Non-Target: stim %1.0f\n',targetNontarget(2)) caTracesTrials = cell(1,2); for t = 1:trials caTraces = S.caTraces{t}; imgDelay = S.behav.imgDelays{t}; stimStartTime = S.behav.stimStartTime{t}-imgDelay; timeCa = (1:size(caTraces,2))./imgRate; stimStartIx = find(timeCa>=stimStartTime,1,'first'); psStartIx = stimStartIx + psTimesIx(1); if psStartIx < 1 error('psStart too early on trial %1.0f',t) end psStopIx = stimStartIx + psTimesIx(2); if psStopIx > size(caTraces,2) % warning('psStop too late on trial %1.0f. Skipping ...',t) continue end if t == 1 tPs = ((psStartIx:psStopIx)-stimStartIx)./imgRate; end if isempty(caTracesTrials{stim{t}}) caTracesTrials{stim{t}} = caTraces(:,psStartIx:psStopIx); else caTracesTrials{stim{t}} = cat(3, caTracesTrials{stim{t}}, caTraces(:,psStartIx:psStopIx)); end end stimStartIx = find(tPs>=0,1,'first'); for n = 1:numel(caTracesTrials) data = nanmean(caTracesTrials{n},3); % baseline normalization / filter for m = 1:size(data,1) data(m,:) = data(m,:) - nanmean(data(m,1:stimStartIx)); data(m,:) = sgolayfilt(data(m,:),3,11); end oriData = caTracesTrials{n}; nPSFramesDS = round(size(oriData, 2) / 4) + 1; DSData = nan(size(oriData, 1), nPSFramesDS, size(oriData, 3)); for iROI = 1 : size(oriData, 1); for iTrial = 1 : size(oriData, 3); [DSData(iROI, :, iTrial), tPs] = interp1DS(imgRate, imgRate / 4, squeeze(oriData(iROI, :, iTrial))); end; end; caTracesMean{1,targetNontarget(n)} = data; trialCount(1,targetNontarget(n)) = size(caTracesTrials{n},3); % decodeData{1,targetNontarget(n)} = oriData; decodeData{1,targetNontarget(n)} = DSData; end % time-resolved decoding analysis (target vs. distractor) for neuron population holdOut = 0.2; % fraction of trials to leave out % iters = 50; % number of iterations iters = 100; % number of iterations decodeTimepoints = size(decodeData{1},2); % consider binning to reduce timepoints perfTrue = zeros(iters,decodeTimepoints); perfShuf = zeros(iters,decodeTimepoints); dispPercent = 10; fprintf('NaiveBayes classification: 00%% done') for t = 1:decodeTimepoints popData = []; labels = []; for stim = 1:numel(decodeData) for trial = 1:size(decodeData{stim},3) popData = [popData; decodeData{stim}(1:end-1,t,trial)']; % last row is neuropil labels(end+1,1) = stim; end end perfTrue(1:iters,t) = doClassify(popData,labels,holdOut,iters,0); perfShuf(1:iters,t) = doClassify(popData,labels,holdOut,iters,1); percentDone = round(t/decodeTimepoints*100); if percentDone >= dispPercent fprintf('\b\b\b\b\b\b\b\b%1.0f%% done',percentDone) dispPercent = dispPercent + 10; end end fprintf('\n\n') end %% Function - doClassify function varargout = doClassify(data,labels,holdOut,iters,shuffled) if ~any(data) for n = 1:nargout varargout{n} = NaN; end return end perf = zeros(iters,1); postpCell = cell(iters,1); predictedCell = cell(iters,1); testlabelsCell = cell(iters,1); % compute the max. number of unique hold-outs (should be > iters) holdOutN = ceil(numel(labels)*holdOut); warning('off','MATLAB:nchoosek:LargeCoefficient') maxHoldOuts = nchoosek(numel(labels),holdOutN); warning('on','MATLAB:nchoosek:LargeCoefficient') if maxHoldOuts < iters warning('Max. number of unique hold-outs is %1.0f and iterations are %1.0f.',... maxHoldOuts,iters) end parfor n = 1:iters if shuffled labels2 = labels(randperm(numel(labels))); else labels2 = labels; end c = cvpartition(labels2,'holdout',holdOut); trainData = data(c.training,:); trainLabels = labels2(c.training); if ~any(trainData) perf(n) = NaN; continue end testData = data(c.test,:); testLabels = labels2(c.test); model = NaiveBayes.fit(trainData,trainLabels); [postP,predicted,logp] = posterior(model,testData); perf(n) = (numel(find(predicted==testLabels))./numel(testLabels)).*100; postpCell{n} = postP; predictedCell{n} = predicted; testlabelsCell{n} = testLabels; end varargout{1} = perf; if nargout > 1 varargout{2} = predictedCell; varargout{3} = testlabelsCell; varargout{4} = postpCell; end end %% Function - Save and close figures function SaveAndCloseFigures while numel(findobj) > 1 set(findall(gcf,'Interpreter','Tex'),'Interpreter','None') makePrettyFigure(gcf); saveName = get(gcf,'Name'); saveas(gcf,strrep(saveName,' ','-')) close(gcf) end end
github
HelmchenLabSoftware/OCIA-master
treeBaggerClassifier.m
.m
OCIA-master/caImgAnalysis/Decoding_2PI/regressionClassifier/treeBaggerClassifier.m
4,908
utf_8
49f4179317c4ba59e28b5720c576ef65
function [rmse_true,rmse_shuf,pVal] = ... treeBaggerClassifier(neuronData,stimData) % neuronData ... trial x neuron cell array of calcium data % each calcium timeseries must be column vector % stimData ... trial x 1 cell array of stimulus data for each trial % stim vector must be at frame rate and column vector ntrees = 32; % number of trees in forest bootSamples = 100; % number of bootstrap samples for comparing true and shuffled rmse doPlot = 1; % plot classifier performance? neurons = size(neuronData,2); trials = size(neuronData,1); % trials = 10; % only a subset to save time % neurons = 5; leaveOutTrials = 2; % how many trials to leave out maxCrossVals = 100; % max. number of cross-validations leaveOut = uniqueCombinations(1:trials,leaveOutTrials); if size(leaveOut,1) > maxCrossVals fprintf('\nRandomly selecting %1.0f out of %1.0f cross-validations!',... maxCrossVals,size(leaveOut,1)) idx = randperm(size(leaveOut,1)); leaveOut = leaveOut(idx(1:maxCrossVals),:); end sgolayOrder = 1; sgolaySpan = 5; % in frames frameShift = [-20:2:20]; frameShift(frameShift==0) = []; % options for treebagger opts = statset('UseParallel','always'); rmse_true = zeros(trials,neurons); rmse_shuf = zeros(trials,neurons); pVal = zeros(1,neurons); for n = 1:neurons fprintf('\nNeuron %1.0f\n',n) % classify by leaving out trials and use them for cross-validation for m = 1:size(leaveOut,1) trainCa = []; trainStim = []; testCa = []; testStim = []; for t = 1:trials currentCa = neuronData{t,n}; currentStim = stimData{t}; currentCa = sgolayfilt(currentCa,sgolayOrder,sgolaySpan); [currentCa,currentStim] = ... shiftFrames(currentCa,currentStim,frameShift); if isempty(find(leaveOut(m,:)==t,1)) % training trial trainCa = [trainCa; currentCa]; trainStim = [trainStim; currentStim]; else % test trial testCa = [testCa; currentCa]; testStim = [testStim; currentStim]; end end % build tree with training data / true labels rtree = TreeBagger(ntrees,trainCa,trainStim,... 'Method','regression','Options',opts); % predict with left out trial stimPredict = predict(rtree,testCa); % compute rmse with stim rmse_true(m,n) = mean(sqrt((stimPredict-testStim).^2)); % build tree with training data / shuffled labels trainStim = trainStim(randperm(numel(trainStim))); rtree = TreeBagger(ntrees,trainCa,trainStim,... 'Method','regression','Options',opts); % predict with left out trial stimPredict = predict(rtree,testCa); % compute rmse with stim rmse_shuf(m,n) = mean(sqrt((stimPredict-testStim).^2)); end % statistical comparison of performance with true and shuffled labels pVal(n) = doStats(rmse_true(:,n),rmse_shuf(:,n),bootSamples); end if doPlot hErr = errorbar([1:neurons],mean(rmse_true),std(rmse_true),'r'); removeErrorBarEnds(hErr); hold on hErr = errorbar([1:neurons],mean(rmse_shuf),std(rmse_shuf),'k'); removeErrorBarEnds(hErr); set(gca,'xtick',[1:neurons],'xticklabel',[1:neurons]) ylabel('RMSE'),xlabel('Neuron') legend({'true labels','shuffled labels'}) end %% Function - shift frames to create additional variables function [Xout,stim] = shiftFrames(X,stim,shift) Xout = X; for n = 1:numel(shift) Xnew = circshift(X,shift(n)); Xout = [Xout Xnew]; end if min(shift) < 0 Xout(end+min(shift)+1,:) = []; stim(end+min(shift)+1,:) = []; end if max(shift) > 0 Xout(1:max(shift),:) = []; stim(1:max(shift),:) = []; end %% Function - Statistical comparison of true and shuffled rmse function p = doStats(a,b,samples) % use a bootstrap approach to test if a-b < 0 % this is a one-tailed test d = a-b; % mean_boot = bootstrp(samples,@mean,d); % sd_boot = bootstrp(samples,@std,d); % p = 1 - normcdf(0,mean(mean_boot),mean(sd_boot)); % or a plain t-test [~,p] = ttest(a,b,0.05,'left'); function out=uniqueCombinations(choicevec,choose) % from mapping toolbox function COMBNTNS choicevec = choicevec(:); % Enforce a column vector choices=length(choicevec); % If the number of choices and the number to choose % are the same, choicevec is the only output. if choices==choose(1) out=choicevec'; % If being chosen one at a time, return each element of % choicevec as its own row elseif choose(1)==1 out=choicevec; % Otherwise, recur down to the level at which one such % condition is met, and pack up the output as you come out of % recursion. else out = []; for i=1:choices-choose(1)+1 tempout=uniqueCombinations(choicevec(i+1:choices),choose(1)-1); out=[out; choicevec(i)*ones(size(tempout,1),1) tempout]; end end
github
HelmchenLabSoftware/OCIA-master
treeBaggerClassifier.m
.m
OCIA-master/caImgAnalysis/Decoding_2PI/AwakeWhisk_Tina/treeBaggerClassifier.m
4,923
utf_8
4869515cb11a96bbbae85e3de0522e59
function [rmse_true,rmse_shuf,pVal] = ... treeBaggerClassifier(neuronData,stimData) % neuronData ... trial x neuron cell array of calcium data % each calcium timeseries must be column vector % stimData ... trial x 1 cell array of stimulus data for each trial % stim vector must be at frame rate and column vector ntrees = 50; % number of trees in forest doPlot = 1; % plot classifier performance? neurons = size(neuronData,2); trials = size(neuronData,1); % trials = 10; % only a subset to save time % neurons = 5; leaveOutTrials = 3; % how many trials to leave out maxCrossVals = 24; % max. number of cross-validations leaveOut = uniqueCombinations(1:trials,leaveOutTrials); leaveOut = leaveOut(randperm(size(leaveOut,1))',:); if size(leaveOut,1) > maxCrossVals fprintf('\nRandomly selecting %1.0f out of %1.0f cross-validations!',... maxCrossVals,size(leaveOut,1)) idx = randperm(size(leaveOut,1)); leaveOut = leaveOut(idx(1:maxCrossVals),:); end sgolayOrder = 1; sgolaySpan = 0; % in frames (0 ... no filter) frameShift = [-10:2:10]; % frameShift(frameShift==0) = []; % options for treebagger opts = statset('UseParallel','always'); rmse_true = zeros(trials,neurons); rmse_shuf = zeros(trials,neurons); pVal = zeros(1,neurons); for n = 1:neurons fprintf('\nNeuron %1.0f\n',n) % classify by leaving out trials and use them for cross-validation for m = 1:size(leaveOut,1) trainCa = []; trainStim = []; testCa = []; testStim = []; for t = 1:trials currentCa = neuronData{t,n}; currentStim = stimData{t}; if sgolaySpan currentCa = sgolayfilt(currentCa,sgolayOrder,sgolaySpan); end [currentCa,currentStim] = ... shiftFrames(currentCa,currentStim,frameShift); if isempty(find(leaveOut(m,:)==t,1)) % training trial trainCa = [trainCa; currentCa]; trainStim = [trainStim; currentStim]; else % test trial testCa = [testCa; currentCa]; testStim = [testStim; currentStim]; end end % build tree with training data / true labels rtree = TreeBagger(ntrees,trainCa,trainStim,... 'Method','regression','Options',opts); % predict with left out trial stimPredict = predict(rtree,testCa); % compute rmse with stim rmse_true(m,n) = mean(sqrt((stimPredict-testStim).^2)); % build tree with training data / shuffled labels trainStim = trainStim(randperm(numel(trainStim))); rtree = TreeBagger(ntrees,trainCa,trainStim,... 'Method','regression','Options',opts); % predict with left out trial stimPredict = predict(rtree,testCa); % compute rmse with stim rmse_shuf(m,n) = mean(sqrt((stimPredict-testStim).^2)); end % statistical comparison of performance with true and shuffled labels pVal(n) = doStats(rmse_true(:,n),rmse_shuf(:,n)); end if doPlot hErr = errorbar([1:neurons],mean(rmse_true),std(rmse_true),'r'); removeErrorBarEnds(hErr); hold on hErr = errorbar([1:neurons],mean(rmse_shuf),std(rmse_shuf),'k'); removeErrorBarEnds(hErr); set(gca,'xtick',[1:neurons],'xticklabel',[1:neurons]) ylabel('RMSE'),xlabel('Neuron') legend({'true labels','shuffled labels'}) end %% Function - shift frames to create additional variables function [Xout,stim] = shiftFrames(X,stim,shift) Xout = X; for n = 1:numel(shift) Xnew = circshift(X,shift(n)); Xout = [Xout Xnew]; end if min(shift) < 0 Xout(end+min(shift)+1,:) = []; stim(end+min(shift)+1,:) = []; end if max(shift) > 0 Xout(1:max(shift),:) = []; stim(1:max(shift),:) = []; end %% Function - Statistical comparison of true and shuffled rmse function p = doStats(a,b) % use a bootstrap approach to test if a-b < 0 % this is a one-tailed test d = a-b; % mean_boot = bootstrp(samples,@mean,d); % sd_boot = bootstrp(samples,@std,d); % p = 1 - normcdf(0,mean(mean_boot),mean(sd_boot)); % or a plain t-test [~,p] = ttest(a,b,0.05,'left'); function out=uniqueCombinations(choicevec,choose) % stolen from mapping toolbox function COMBNTNS choicevec = choicevec(:); % Enforce a column vector choices=length(choicevec); % If the number of choices and the number to choose % are the same, choicevec is the only output. if choices==choose(1) out=choicevec'; % If being chosen one at a time, return each element of % choicevec as its own row elseif choose(1)==1 out=choicevec; % Otherwise, recur down to the level at which one such % condition is met, and pack up the output as you come out of % recursion. else out = []; for i=1:choices-choose(1)+1 tempout=uniqueCombinations(choicevec(i+1:choices),choose(1)-1); out=[out; choicevec(i)*ones(size(tempout,1),1) tempout]; end end
github
HelmchenLabSoftware/OCIA-master
treeBaggerClassifierTrainTest.m
.m
OCIA-master/caImgAnalysis/Decoding_2PI/AwakeWhisk_Tina/treeBaggerClassifierTrainTest.m
7,127
utf_8
02182e3a0bb5570bd5f6b45cac09cf18
function [mseTrue, mseShuf] = treeBaggerClassifierTrainTest(neuronTrain,neuronTest,stimTrain,stimTest) % in this file, train and test data sets are explicitely specified (e.g. for chronic analysis across % sessions) % neuronTrain ... trial x neuron cell array of training calcium data % neuronTest ... trial x neuron cell array of testing calcium data % the number of neurons MUST be identical in train and test data % stimTrain ... trial x 1 cell array of stimulus data for each trial (same number of trials as in % neuronTrain) % stimTest ... trial x 1 cell array of stimulus data for each trial (same number of trials as in % neuronTest) maxNeurons = inf; % save time during debug % hold-out a certain fraction of data on multiple iterations holdOutF = 0.2; iter = 5; % number of iterations with different hold outs --> error bars on predictions % options for treebagger opts = statset('UseParallel','always'); ntrees = 30; regressionMethod = 'bag'; % 'lsboost' or 'bag' neurons = size(neuronTrain,2); if size(neuronTest,2) ~= neurons error('Must have the same number of neurons in train and test data sets!') end trialsTrain = size(neuronTrain,1); trialsTest = size(neuronTest,1); if maxNeurons < neurons neurons = maxNeurons; end % concatenate predictors and response data % predictors X ... activity of different neurons (or same neuron at different lags) % response data Y ... the parameter to be explained by the neural activity (e.g. whisk vector) Xtrain = []; Xtest = []; Ytrain = []; Ytest = []; for n = 1:neurons vTrain = []; vTest = []; for t = 1:trialsTrain % TODO: perhaps high-pass filter of predictors and response data if n == 1 Ytrain = [Ytrain; stimTrain{t}]; end vTrain = [vTrain; neuronTrain{t,n}]; end for t = 1:trialsTest if n == 1 Ytest = [Ytest; stimTest{t}]; end vTest = [vTest; neuronTest{t,n}]; end Xtrain = [Xtrain, vTrain]; Xtest = [Xtest, vTest]; end warning('off','all') %% Population prediction [mseTruePop,mseShufPop] = doClassify(Xtrain,Xtest,Ytrain,Ytest,ntrees,regressionMethod,holdOutF,opts,iter); % figure('Name','Population Prediction'); % hErr = errorbar(nanmean(lossTrue),std(lossTrue),'r'); % removeErrorBarEnds(hErr); hold on % hErr = errorbar(nanmean(lossShuf),std(lossShuf),'k'); removeErrorBarEnds(hErr); % xlabel('Number of trees'); ylabel('Test classification MSE +- SD'); % title(regressionMethod) % legend({'True','Shuffled'}) % mseTrue = lossTrue(:,end); mseShuf = lossShuf(:,end); % % dPrimePop = ((nanmean(mseShuf)-nanmean(mseTrue))) ./ ... % sqrt((nanvar(mseShuf)+nanvar(mseTrue))./2); plotSingleNeuron = 0; %% Single-neuron prediction dPrimeSingleCell = zeros(1,neurons); for n = 1:neurons currentXtrain = Xtrain(:,n); currentXtest = Xtest(:,n); [mseTrue{n},mseShuf{n}] = doClassify(currentXtrain,currentXtest,Ytrain,Ytest,ntrees,... regressionMethod,holdOutF,opts,iter); % mseTrue = lossTrue(:,end); mseShuf = lossShuf(:,end); % dPrimeSingleCell(n) = ((nanmean(mseShuf)-nanmean(mseTrue))) ./ ... % sqrt((nanvar(mseShuf)+nanvar(mseTrue))./2); % if plotSingleNeuron % figure('Name',sprintf('Prediction Neuron %1.0f',n)); % hErr = errorbar(nanmean(lossTrue),std(lossTrue),'r'); % removeErrorBarEnds(hErr); hold on % hErr = errorbar(nanmean(lossShuf),std(lossShuf),'k'); removeErrorBarEnds(hErr); % xlabel('Number of trees'); ylabel('Test classification MSE +- SD'); % title(sprintf('Prediction Neuron %1.0f - %s',n,regressionMethod)) % legend({'True','Shuffled'}) % end end % dprime = [dPrimeSingleCell, dPrimePop]; mseTrue{n+1} = mseTruePop; mseShuf{n+1} = mseShufPop; warning('on','all') end function [lossTrue,lossShuf] = doClassify(Xtrain,Xtest,Ytrain,Ytest,ntrees,method,holdOutF,opts,iter) for i = 1:iter % shuffling YtrainShuff = Ytrain(randperm(numel(Ytrain))); YtestShuff = Ytest(randperm(numel(Ytest))); cvpartTrain = cvpartition(Ytrain,'holdout',holdOutF); cvpartTest = cvpartition(Ytest,'holdout',holdOutF); % select data used for training currentXtrain = Xtrain(training(cvpartTrain),:); currentYtrain = Ytrain(training(cvpartTrain),:); % testing is done on the larger fraction of cvpartTest holdouts, i.e. the training fraction currentXtest = Xtest(training(cvpartTest),:); currentYtest = Ytest(training(cvpartTest),:); % select shuffled data currentYtrainShuf = YtrainShuff(training(cvpartTrain),:); currentYtestShuf = YtestShuff(training(cvpartTest),:); switch method case 'bag' modelTrue = TreeBagger(ntrees,currentXtrain,currentYtrain,... 'Method','regression','Options',opts); modelShuf = TreeBagger(ntrees,currentXtrain,currentYtrainShuf,... 'Method','regression','Options',opts); lossTrue(i,:) = error(modelTrue,currentXtest,currentYtest,'mode','cumulative'); lossShuf(i,:) = error(modelShuf,currentXtest,currentYtestShuf,'mode','cumulative'); case 'lsboost' modelTrue = fitensemble(currentXtrain,currentYtrain,method,ntrees,'Tree',... 'type','regression'); modelShuf = fitensemble(currentXtrain,currentYtrainShuf,method,ntrees,'Tree',... 'type','regression'); lossTrue(i,:) = loss(modelTrue,currentXtest,currentYtest,'mode','cumulative'); lossShuf(i,:) = loss(modelShuf,currentXtest,currentYtestShuf,'mode','cumulative'); end end end %% Function - shift frames to create additional variables function [Xout,stim] = shiftFrames(X,stim,shift) Xout = X; for n = 1:numel(shift) Xnew = circshift(X,shift(n)); Xout = [Xout Xnew]; end if min(shift) < 0 Xout(end+min(shift)+1,:) = []; stim(end+min(shift)+1,:) = []; end if max(shift) > 0 Xout(1:max(shift),:) = []; stim(1:max(shift),:) = []; end end %% Function - Statistical comparison of true and shuffled rmse function p = doStats(a,b) % use a bootstrap approach to test if a-b < 0 % this is a one-tailed test d = a-b; % mean_boot = bootstrp(samples,@mean,d); % sd_boot = bootstrp(samples,@std,d); % p = 1 - normcdf(0,mean(mean_boot),mean(sd_boot)); % or a plain t-test [~,p] = ttest(a,b,0.05,'left'); end function out=uniqueCombinations(choicevec,choose) % stolen from mapping toolbox function COMBNTNS choicevec = choicevec(:); % Enforce a column vector choices=length(choicevec); % If the number of choices and the number to choose % are the same, choicevec is the only output. if choices==choose(1) out=choicevec'; % If being chosen one at a time, return each element of % choicevec as its own row elseif choose(1)==1 out=choicevec; % Otherwise, recur down to the level at which one such % condition is met, and pack up the output as you come out of % recursion. else out = []; for i=1:choices-choose(1)+1 tempout=uniqueCombinations(choicevec(i+1:choices),choose(1)-1); out=[out; choicevec(i)*ones(size(tempout,1),1) tempout]; end end end
github
HelmchenLabSoftware/OCIA-master
treeBaggerClassifier2.m
.m
OCIA-master/caImgAnalysis/Decoding_2PI/AwakeWhisk_Tina/treeBaggerClassifier2.m
7,070
utf_8
718e6cc19869446a49a17adf092dde6e
function varargout = treeBaggerClassifier2(neuronData,stimData) % neuronData ... trial x neuron cell array of calcium data % each calcium timeseries must be column vector % stimData ... trial x 1 cell array of stimulus data for each trial % stim vector must be at frame rate and column vector f = 7.81; maxTrials = Inf; % only a subset to save time maxNeurons = Inf; % hold-out a certain fraction of data for testing holdOutF = 0.2; % e.g. 80% used for training % iter = 10; % number of iterations with different hold outs --> error bars on predictions % options for treebagger opts = statset('UseParallel','always'); ntrees = 30; regressionMethod = 'bag'; % 'lsboost' or 'bag' neurons = size(neuronData,2); trials = size(neuronData,1); if maxNeurons < neurons neurons = maxNeurons; end if maxTrials < trials trials = maxTrials; end % concatenate predictors and response data % predictors X ... activity of different neurons (or same neuron at different lags) % response data Y ... the parameter to be explained by the neural activity (e.g. whisk vector) X = []; Y = []; for n = 1:neurons v = []; for t = 1:trials % TODO: perhaps high-pass filter of predictors and response data if n == 1 Y = [Y; preprocVector(stimData{t})]; end v = [v; preprocVector(neuronData{t,n})]; end X = [X, v]; end warning('off','all') %% Population prediction [lossTrue,lossShuf,modelTrue,modelShuf] = doClassify(X,Y,ntrees,regressionMethod,holdOutF,opts); % predicted responses Ypredict = oobPredict(modelTrue); % plot predictions on trial 1 (really should not be included in training) neuronData_trial1 = cell2mat(neuronData(1,:)); for n = 1:size(neuronData_trial1,2) neuronData_trial1(:,n) = preprocVector(neuronData_trial1(:,n)); end stimData_trial1 = preprocVector(stimData{1}); stimData_predict_true = predict(modelTrue,neuronData_trial1); stimData_predict_shuf = predict(modelShuf,neuronData_trial1); t = (1:numel(stimData_trial1))./f; figure plot(t,stimData_trial1,'k'), hold on plot(t,stimData_predict_true,'r') legend({'Whisk','Predicted'}) xlabel('Time / s') warning('on','all') varargout{1} = lossTrue(end); varargout{2} = lossShuf(end); % figure('Name','Population Prediction'); % hErr = errorbar(nanmean(lossTrue),std(lossTrue),'r'); % removeErrorBarEnds(hErr); hold on % hErr = errorbar(nanmean(lossShuf),std(lossShuf),'k'); removeErrorBarEnds(hErr); % xlabel('Number of trees'); ylabel('Test classification MSE +- SD'); % title(regressionMethod) % legend({'True','Shuffled'}) % mseTrue = lossTrue(:,end); mseShuf = lossShuf(:,end); % % dPrimePop = ((nanmean(mseShuf)-nanmean(mseTrue))) ./ ... % sqrt((nanvar(mseShuf)+nanvar(mseTrue))./2); % % plotSingleNeuron = 0; % %% Single-neuron prediction % dPrimeSingleCell = zeros(1,size(X,2)); % for n = 1:size(X,2) % [lossTrue,lossShuf] = doClassify(X(:,n),Y,ntrees,regressionMethod,holdOutF,opts,iter); % mseTrue = lossTrue(:,end); mseShuf = lossShuf(:,end); % dPrimeSingleCell(n) = ((nanmean(mseShuf)-nanmean(mseTrue))) ./ ... % sqrt((nanvar(mseShuf)+nanvar(mseTrue))./2); % if plotSingleNeuron % figure('Name',sprintf('Prediction Neuron %1.0f',n)); % hErr = errorbar(nanmean(lossTrue),std(lossTrue),'r'); % removeErrorBarEnds(hErr); hold on % hErr = errorbar(nanmean(lossShuf),std(lossShuf),'k'); removeErrorBarEnds(hErr); % xlabel('Number of trees'); ylabel('Test classification MSE +- SD'); % title(sprintf('Prediction Neuron %1.0f - %s',n,regressionMethod)) % legend({'True','Shuffled'}) % end % end % dprime = [dPrimeSingleCell, dPrimePop]; end function v = preprocVector(v) % high-pass filter % p = polyfit([1:numel(v)]',v,2); % v = v - polyval(p,[1:numel(v)]'); % low-pass filter v = sgolayfilt(v,2,5); v = ScaleToMinMax(v,0,1); end function [lossTrue,lossShuf,modelTrue,modelShuf] = doClassify(X,Y,ntrees,regressionMethod,holdOutF,opts) % cvpart = cvpartition(Y,'holdout',holdOutF); % Xtrain = X(training(cvpart),:); % Ytrain = Y(training(cvpart),:); % Xtest = X(test(cvpart),:); % Ytest = Y(test(cvpart),:); % Yshuff = Y(randperm(numel(Y))); % YtrainShuff = Yshuff(training(cvpart),:); % YtestShuff = Yshuff(test(cvpart),:); % treebagger needs no hold-out (get errors from out-of-bag classifications) modelTrue = TreeBagger(ntrees,X,Y,... 'Method','regression','Options',opts,'minleaf',1,'oobpred','on'); modelShuf = TreeBagger(ntrees,X,Yshuff,... 'Method','regression','Options',opts,'minleaf',1,'oobpred','on'); lossTrue = error(modelTrue,X,Y,'mode','cumulative'); lossShuf = error(modelShuf,X,Y,'mode','cumulative'); % switch regressionMethod % case 'bag' % modelTrue = TreeBagger(ntrees,Xtrain,Ytrain,... % 'Method','regression','Options',opts,'minleaf',1,'oobpred','on'); % modelShuf = TreeBagger(ntrees,Xtrain,YtrainShuff,... % 'Method','regression','Options',opts,'minleaf',1,'oobpred','on'); % lossTrue = error(modelTrue,Xtest,Ytest,'mode','cumulative'); % lossShuf = error(modelShuf,Xtest,YtestShuff,'mode','cumulative'); % case 'lsboost' % modelTrue = fitensemble(Xtrain,Ytrain,regressionMethod,ntrees,'Tree',... % 'type','regression'); % modelShuf = fitensemble(Xtrain,YtrainShuff,regressionMethod,ntrees,'Tree',... % 'type','regression'); % lossTrue = loss(modelTrue,Xtest,Ytest,'mode','cumulative'); % lossShuf = loss(modelShuf,Xtest,YtestShuff,'mode','cumulative'); % end end %% Function - shift frames to create additional variables function [Xout,stim] = shiftFrames(X,stim,shift) Xout = X; for n = 1:numel(shift) Xnew = circshift(X,shift(n)); Xout = [Xout Xnew]; end if min(shift) < 0 Xout(end+min(shift)+1,:) = []; stim(end+min(shift)+1,:) = []; end if max(shift) > 0 Xout(1:max(shift),:) = []; stim(1:max(shift),:) = []; end end %% Function - Statistical comparison of true and shuffled rmse function p = doStats(a,b) % use a bootstrap approach to test if a-b < 0 % this is a one-tailed test d = a-b; % mean_boot = bootstrp(samples,@mean,d); % sd_boot = bootstrp(samples,@std,d); % p = 1 - normcdf(0,mean(mean_boot),mean(sd_boot)); % or a plain t-test [~,p] = ttest(a,b,0.05,'left'); end function out=uniqueCombinations(choicevec,choose) % stolen from mapping toolbox function COMBNTNS choicevec = choicevec(:); % Enforce a column vector choices=length(choicevec); % If the number of choices and the number to choose % are the same, choicevec is the only output. if choices==choose(1) out=choicevec'; % If being chosen one at a time, return each element of % choicevec as its own row elseif choose(1)==1 out=choicevec; % Otherwise, recur down to the level at which one such % condition is met, and pack up the output as you come out of % recursion. else out = []; for i=1:choices-choose(1)+1 tempout=uniqueCombinations(choicevec(i+1:choices),choose(1)-1); out=[out; choicevec(i)*ones(size(tempout,1),1) tempout]; end end end
github
HelmchenLabSoftware/OCIA-master
importData_textureDisc.m
.m
OCIA-master/caImgAnalysis/Decoding_2PI/TextureDisc_Jerry/importData_textureDisc.m
1,991
utf_8
9965ffb89b724ddee6083c3d90aa97cf
function Sout = importData_textureDisc(matfile) load(matfile) roiLabel = Ca.roiLabel; % animal / session ID id = roiLabel{1,1}; idx = strfind(id,'-'); Sout.info.animal = id(1:idx(1)-1); Sout.info.session = str2num(id(idx(1)+1:idx(2)-1)); Sout.info.sample_rate = Ca.sample_rate; Sout.info.roiLabel = roiLabel; trialID = Ca.Trial_Name; % the HS filename for each imaging trial % build the texture trial vector by searching through {summary} and finding % trialID --> code textures 1 - 4 (textures 1, 3, 5, 7) Sout.info.trialVectors.texture = findTrialTexture(trialID,summary); % DRR trial x time matrix for each neuron timepoints = size(Ca.dRR{1,1},2); for roi = 1:numel(roiLabel) id = roiLabel{roi,1}; idx = strfind(id,'-'); id = id(idx(2)+1:end); % for field name drr = zeros(numel(trialID),timepoints); for trial = 1:numel(trialID) if isempty(Ca.dRR{roi,trial}) drr(trial,:) = NaN; else drr(trial,:) = Ca.dRR{roi,trial}(1,:); end end Sout.(id).dRR = drr; end %% Function - findTrialTexture function v = findTrialTexture(trialID,summary) trialCol = 6; % the column of summary in which trial IDs are stored textureCol = 4; % the column of summary in which texture is stored v = zeros(numel(trialID),1); for n = 1:numel(trialID) id = trialID{n}; match = 0; for m = 2:size(summary,1) if ~isnan(summary{m,trialCol}) & strcmp(summary{m,trialCol},id) match = 1; texture = summary{m,textureCol}; switch texture(1:9) case 'Texture 1' v(n) = 1; case 'Texture 3' v(n) = 2; case 'Texture 5' v(n) = 3; case 'Texture 7' v(n) = 4; otherwise error('Could not match texture %s (trial %s)',texture,id) end end end if ~match error('Could not match trial %s',id) end end
github
HelmchenLabSoftware/OCIA-master
textureDisc_dimensionReduce.m
.m
OCIA-master/caImgAnalysis/Decoding_2PI/TextureDisc_Jerry/textureDisc_dimensionReduce.m
1,799
utf_8
6db53e071307051e42d0481f251ad5b6
function S = textureDisc_dimensionReduce(S) % S is a data structure returned by importData_textureDisc % this file written by Henry Luetcke ([email protected]) animalID = S.info.animal; sessionID = S.info.session; rate = S.info.sample_rate; roiLabel = S.info.roiLabel; % roi labels without session ID roiLabel = strrep(roiLabel,sprintf('%s-%1.0f-',animalID,sessionID),''); % treat each Roi separately for roi = 1:numel(roiLabel) roiID = roiLabel{roi}; fprintf('Processing %s\n',roiID); data = S.(roiLabel{roi}).dRR; S.(roiLabel{roi}).reducedGauss1 = fitSingleTrialTransient(data,'gauss1'); end function fitCoef = fitSingleTrialTransient(data,fitLib) fitCoef = zeros(size(data,1),4); % 3 coefficients for gaussian + r^2 t = (1:size(data,2))'; fObj = cell(1,size(data,1)); gof = cell(1,size(data,1)); parfor n = 1:size(data,1) y = data(n,:)'; if any(isnan(y)) fObj{n} = NaN; gof{n} = NaN; continue end opts = fitoptions(fitLib); opts.Lower = [0 0 1]; opts.Upper = [max(y) max(t) max(t)]; [fObj{n},gof{n}] = fit(t,y,fitLib,opts); end for n = 1:size(data,1) try c = coeffvalues(fObj{n}); fitCoef(n,1:numel(c)) = c; fitCoef(n,numel(c)+1) = gof{n}.rsquare; catch fitCoef(n,1:size(fitCoef,2)) = NaN; end % if ~doPlot; continue; end % figure('Name',id) % plot(t,y,'k'), hold on % plot(fObj) % switch fitLib % case 'gauss1' % titleStr = sprintf('a=%1.3f b=%1.3f c=%1.3f r^2=%1.3f',c(1),c(2),c(3),gof.rsquare); % case 'fourier1' % titleStr = sprintf('a0=%1.3f a1=%1.3f b1=%1.3f w=%1.3f r^2=%1.3f',... % c(1),c(2),c(3),c(4),gof.rsquare); % end % title(titleStr) end
github
HelmchenLabSoftware/OCIA-master
strucdisp.m
.m
OCIA-master/utils/misc/strucdisp.m
18,695
utf_8
d5a885d0bc1cb649b355669e25a49853
function strucdisp(Structure, depth, printValues, maxArrayLength, fileName) %STRUCDISP display structure outline % % STRUCDISP(STRUC, DEPTH, PRINTVALUES, MAXARRAYLENGTH, FILENAME) displays % the hierarchical outline of a structure and its substructures. % % STRUC is a structure datatype with unknown field content. It can be % either a scalar or a vector, but not a matrix. STRUC is the only % mandatory argument in this function. All other arguments are optional. % % DEPTH is the number of hierarchical levels of the structure that are % printed. If DEPTH is smaller than zero, all levels are printed. Default % value for DEPTH is -1 (print all levels). % % PRINTVALUES is a flag that states if the field values should be printed % as well. The default value is 1 (print values) % % MAXARRAYLENGTH is a positive integer, which determines up to which % length or size the values of a vector or matrix are printed. For a % vector holds that if the length of the vector is smaller or equal to % MAXARRAYLENGTH, the values are printed. If the vector is longer than % MAXARRAYLENGTH, then only the size of the vector is printed. % The values of a 2-dimensional (m,n) array are printed if the number of % elements (m x n) is smaller or equal to MAXARRAYLENGTH. % For vectors and arrays, this constraint overrides the PRINTVALUES flag. % % FILENAME is the name of the file to which the output should be printed. % if this argument is not defined, the output is printed to the command % window. % % Contact author: B. Roossien <[email protected]> % (c) ECN 2007-2008 % % Version 1.3.0 %% Creator and Version information % Created by B. Roossien <[email protected]> 14-12-2006 % % Based on the idea of % M. Jobse - display_structure (Matlab Central FileID 2031) % % Acknowledgements: % S. Wegerich - printmatrix (Matlab Central FileID 971) % % Beta tested by: % K. Visscher % % Feedback provided by: % J. D'Errico % H. Krause % J.K. Kok % J. Kurzmann % K. Visscher % % % (c) ECN 2006-2007 % www.ecn.nl % % Last edited on 08-03-2008 %% Version History % % 1.3.0 : Bug fixes and added logicals % 1.2.3 : Buf fix - Solved multi-line string content bug % 1.2.2 : Bug fix - a field being an empty array gave an error % 1.2.1 : Bug fix % 1.2.0 : Increased readability of code % Makes use of 'structfun' and 'cellfun' to increase speed and % reduce the amount of code % Solved bug with empty fieldname parameter % 1.1.2 : Command 'eval' removed with a more simple and efficient solution % 1.1.1 : Solved a bug with cell array fields % 1.1.0 : Added support for arrayed structures % Added small matrix size printing % 1.0.1 : Bug with empty function parameters fixed % 1.0.0 : Initial release %% Main program %%%%% start program %%%%% % first argument must be structure if ~isstruct(Structure) error('First input argument must be structure'); end % first argument can be a scalar or vector, but not a matrix if ~isvector(Structure) error('First input argument can be a scalar or vector, but not a matrix'); end % default value for second argument is -1 (print all levels) if nargin < 2 || isempty(depth) depth = -1; end % second argument must be an integer if ~isnumeric(depth) error('Second argument must be an integer'); end % second argument only works if it is an integer, therefore floor it depth = floor(depth); % default value for third argument is 1 if nargin < 3 || isempty(printValues) printValues = 1; end % default value for fourth argument is 10 if nargin < 4 || isempty(maxArrayLength) maxArrayLength = 10; end % start recursive function listStr = recFieldPrint(Structure, 0, depth, printValues, ... maxArrayLength); % 'listStr' is a cell array containing the output % Now it's time to actually output the data % Default is to output to the command window % However, if the filename argument is defined, output it into a file if nargin < 5 || isempty(fileName) % write data to screen for i = 1 : length(listStr) disp(cell2mat(listStr(i, 1))); end else % open file and check for errors fid = fopen(fileName, 'wt'); if fid < 0 error('Unable to open output file'); end % write data to file for i = 1 : length(listStr) fprintf(fid, '%s\n', cell2mat(listStr(i, 1))); end % close file fclose(fid); end end %% FUNCTION: recFieldPrint function listStr = recFieldPrint(Structure, indent, depth, printValues, ... maxArrayLength) % Start to initialiase the cell listStr. This cell is used to store all the % output, as this is much faster then directly printing it to screen. listStr = {}; % "Structure" can be a scalar or a vector. % In case of a vector, this recursive function is recalled for each of % the vector elements. But if the values don't have to be printed, only % the size of the structure and its fields are printed. if length(Structure) > 1 if (printValues == 0) varStr = createArraySize(Structure, 'Structure'); listStr = [{' '}; {['Structure', varStr]}]; body = recFieldPrint(Structure(1), indent, depth, ... printValues, maxArrayLength); listStr = [listStr; body; {' O'}]; else for iStruc = 1 : length(Structure) listStr = [listStr; {' '}; {sprintf('Structure(%d)', iStruc)}]; body = recFieldPrint(Structure(iStruc), indent, depth, ... printValues, maxArrayLength); listStr = [listStr; body; {' O'}]; end end return end %% Select structure fields % The fields of the structure are distinguished between structure and % non-structure fields. The structure fields are printed first, by % recalling this function recursively. % First, select all fields. fields = fieldnames(Structure); % Next, structfun is used to return an boolean array with information of % which fields are of type structure. isStruct = structfun(@isstruct, Structure); % Finally, select all the structure fields strucFields = fields(isStruct == 1); %% Recursively print structure fields % The next step is to select each structure field and handle it % accordingly. Each structure can be empty, a scalar, a vector or a matrix. % Matrices and long vectors are only printed with their fields and not with % their values. Long vectors are defined as vectors with a length larger % then the maxArrayLength value. The fields of an empty structure are not % printed at all. % It is not necessary to look at the length of the vector if the values % don't have to be printed, as the fields of a vector or matrix structure % are the same for each element. % First, some indentation calculations are required. strIndent = getIndentation(indent + 1); listStr = [listStr; {strIndent}]; strIndent = getIndentation(indent); % Next, select each field seperately and handle it accordingly for iField = 1 : length(strucFields) fieldName = cell2mat(strucFields(iField)); Field = Structure.(fieldName); % Empty structure if isempty(Field) strSize = createArraySize(Field, 'Structure'); line = sprintf('%s |--- %s :%s', ... strIndent, fieldName, strSize); listStr = [listStr; {line}]; % Scalar structure elseif isscalar(Field) line = sprintf('%s |--- %s', strIndent, fieldName); % Recall this function if the tree depth is not reached yet if (depth < 0) || (indent + 1 < depth) lines = recFieldPrint(Field, indent + 1, depth, ... printValues, maxArrayLength); listStr = [listStr; {line}; lines; ... {[strIndent ' | O']}]; else listStr = [listStr; {line}]; end % Short vector structure of which the values should be printed elseif (isvector(Field)) && ... (printValues > 0) && ... (length(Field) < maxArrayLength) && ... ((depth < 0) || (indent + 1 < depth)) % Use a for-loop to print all structures in the array for iFieldElement = 1 : length(Field) line = sprintf('%s |--- %s(%g)', ... strIndent, fieldName, iFieldElement); lines = recFieldPrint(field(iFieldElement), indent + 1, ... depth, printValues, maxArrayLength); listStr = [listStr; {line}; lines; ... {[strIndent ' | O']}]; if iFieldElement ~= length(Field) listStr = [listStr; {[strIndent ' | ']}]; end end % Structure is a matrix or long vector % No values have to be printed or depth limit is reached else varStr = createArraySize(Field, 'Structure'); line = sprintf('%s |--- %s :%s', ... strIndent, fieldName, varStr); lines = recFieldPrint(Field(1), indent + 1, depth, ... 0, maxArrayLength); listStr = [listStr; {line}; lines; ... {[strIndent ' | O']}]; end % Some extra blank lines to increase readability listStr = [listStr; {[strIndent ' | ']}]; end % End iField for-loop %% Field Filler % To properly align the field names, a filler is required. To know how long % the filler must be, the length of the longest fieldname must be found. % Because 'fields' is a cell array, the function 'cellfun' can be used to % extract the lengths of all fields. maxFieldLength = max(cellfun(@length, fields)); %% Print non-structure fields without values % Print non-structure fields without the values. This can be done very % quick. if printValues == 0 noStrucFields = fields(isStruct == 0); for iField = 1 : length(noStrucFields) Field = cell2mat(noStrucFields(iField)); filler = char(ones(1, maxFieldLength - length(Field) + 2) * 45); listStr = [listStr; {[strIndent ' |' filler ' ' Field]}]; end return end %% Select non-structure fields (to print with values) % Select fields that are not a structure and group them by data type. The % following groups are distinguished: % - characters and strings % - numeric arrays % - logical % - empty arrays % - matrices % - numeric scalars % - cell arrays % - other data types % Character or string (array of characters) isChar = structfun(@ischar, Structure); charFields = fields(isChar == 1); % Numeric fields isNumeric = structfun(@isnumeric, Structure); % Numeric scalars isScalar = structfun(@isscalar, Structure); isScalar = isScalar .* isNumeric; scalarFields = fields(isScalar == 1); % Numeric vectors (arrays) isVector = structfun(@isvector, Structure); isVector = isVector .* isNumeric .* not(isScalar); vectorFields = fields(isVector == 1); % Logical fields isLogical = structfun(@islogical, Structure); logicalFields = fields(isLogical == 1); % Empty arrays isEmpty = structfun(@isempty, Structure); emptyFields = fields(isEmpty == 1); % Numeric matrix with dimension size 2 or higher isMatrix = structfun(@(x) ndims(x) >= 2, Structure); isMatrix = isMatrix .* isNumeric .* not(isVector) ... .* not(isScalar) .* not(isEmpty); matrixFields = fields(isMatrix == 1); % Cell array isCell = structfun(@iscell, Structure); cellFields = fields(isCell == 1); % Datatypes that are not checked for isOther = not(isChar + isNumeric + isCell + isStruct + isLogical + isEmpty); otherFields = fields(isOther == 1); %% Print non-structure fields % Print all the selected non structure fields % - Strings are printed to a certain amount of characters % - Vectors are printed as long as they are shorter than maxArrayLength % - Matrices are printed if they have less elements than maxArrayLength % - The values of cells are not printed % Start with printing strings and characters. To avoid the display screen % becoming a mess, the part of the string that is printed is limited to 31 % characters. In the future this might become an optional parameter in this % function, but for now, it is placed in the code itself. % if the string is longer than 31 characters, only the first 31 characters % are printed, plus three dots to denote that the string is longer than % printed. maxStrLength = 31; for iField = 1 : length(charFields) Field = cell2mat(charFields(iField)); filler = char(ones(1, maxFieldLength - length(Field) + 2) * 45); if (size(Structure.(Field), 1) > 1) && (size(Structure.(Field), 2) > 1) varStr = createArraySize(Structure.(Field), 'char'); elseif length(Field) > maxStrLength varStr = sprintf(' ''%s...''', Structure.(Field(1:maxStrLength))); else varStr = sprintf(' "%s"', Structure.(Field)); end listStr = [listStr; {[strIndent ' |' filler ' ' Field ' :' varStr]}]; end % Print empty fields for iField = 1 : length(emptyFields) Field = cell2mat(emptyFields(iField)); filler = char(ones(1, maxFieldLength - length(Field) + 2) * 45); listStr = [listStr; {[strIndent ' |' filler ' ' Field ' : [ ]' ]}]; end % Print logicals. If it is a scalar, print true/false, else print vector % information for iField = 1 : length(logicalFields) Field = cell2mat(logicalFields(iField)); filler = char(ones(1, maxFieldLength - length(Field) + 2) * 45); if isscalar(Structure.(Field)) logicalValue = {'False', 'True'}; varStr = sprintf(' %s', logicalValue{Structure.(Field) + 1}); else varStr = createArraySize(Structure.(Field), 'Logic array'); end listStr = [listStr; {[strIndent ' |' filler ' ' Field ' :' varStr]}]; end % Print numeric scalar field. The %g format is used, so that integers, % floats and exponential numbers are printed in their own format. for iField = 1 : length(scalarFields) Field = cell2mat(scalarFields(iField)); filler = char(ones(1, maxFieldLength - length(Field) + 2) * 45); varStr = sprintf(' %g', Structure.(Field)); listStr = [listStr; {[strIndent ' |' filler ' ' Field ' :' varStr]}]; end % Print numeric array. If the length of the array is smaller then % maxArrayLength, then the values are printed. Else, print the length of % the array. for iField = 1 : length(vectorFields) Field = cell2mat(vectorFields(iField)); filler = char(ones(1, maxFieldLength - length(Field) + 2) * 45); if length(Structure.(Field)) > maxArrayLength varStr = createArraySize(Structure.(Field), 'Array'); else varStr = sprintf('%g ', Structure.(Field)); varStr = ['[' varStr(1:length(varStr) - 1) ']']; end listStr = [listStr; {[strIndent ' |' filler ' ' Field ' : ' varStr]}]; end % Print numeric matrices. If the matrix is two-dimensional and has more % than maxArrayLength elements, only its size is printed. % If the matrix is 'small', the elements are printed in a matrix structure. % The top and the bottom of the matrix is indicated by a horizontal line of % dashes. The elements are also lined out by using a fixed format % (%#10.2e). Because the name of the matrix is only printed on the first % line, the space is occupied by this name must be filled up on the other % lines. This is done by defining a 'filler2'. % This method was developed by S. Wegerich. for iField = 1 : length(matrixFields) Field = cell2mat(matrixFields(iField)); filler = char(ones(1, maxFieldLength - length(Field) + 2) * 45); if numel(Structure.(Field)) > maxArrayLength varStr = createArraySize(Structure.(Field), 'Array'); varCell = {[strIndent ' |' filler ' ' Field ' :' varStr]}; else matrixSize = size(Structure.(Field)); filler2 = char(ones(1, maxFieldLength + 6) * 32); dashes = char(ones(1, 12 * matrixSize(2) + 1) * 45); varCell = {[strIndent ' |' filler2 dashes]}; % first line with field name varStr = sprintf('%#10.2e |', Structure.(Field)(1, :)); varCell = [varCell; {[strIndent ' |' filler ' ' ... Field ' : |' varStr]}]; % second and higher number rows for j = 2 : matrixSize(1) varStr = sprintf('%#10.2e |', Structure.(Field)(j, :)); varCell = [varCell; {[strIndent ' |' filler2 '|' varStr]}]; end varCell = [varCell; {[strIndent ' |' filler2 dashes]}]; end listStr = [listStr; varCell]; end % Print cell array information, i.e. the size of the cell array. The % content of the cell array is not printed. for iField = 1 : length(cellFields) Field = cell2mat(cellFields(iField)); filler = char(ones(1, maxFieldLength - length(Field) + 2) * 45); varStr = createArraySize(Structure.(Field), 'Cell'); listStr = [listStr; {[strIndent ' |' filler ' ' Field ' :' varStr]}]; end % Print unknown datatypes. These include objects and user-defined classes for iField = 1 : length(otherFields) Field = cell2mat(otherFields(iField)); filler = char(ones(1, maxFieldLength - length(Field) + 2) * 45); varStr = createArraySize(Structure.(Field), 'Unknown'); listStr = [listStr; {[strIndent ' |' filler ' ' Field ' :' varStr]}]; end end %% FUNCTION: getIndentation % This function creates the hierarchical indentations function str = getIndentation(indent) x = ' | '; str = ''; for i = 1 : indent str = cat(2, str, x); end end %% FUNCTION: createArraySize % This function returns a string with the array size of the input variable % like: "[1x5 Array]" or "[2x3x5 Structure]" where 'Structure' and 'Array' % are defined by the type parameter function varStr = createArraySize(varName, type) varSize = size(varName); arraySizeStr = sprintf('%gx', varSize); arraySizeStr(length(arraySizeStr)) = []; varStr = [' [' arraySizeStr ' ' type ']']; end
github
HelmchenLabSoftware/OCIA-master
client.m
.m
OCIA-master/utils/socket_communication/client.m
1,728
utf_8
c1e65f4b0d1315930638729cb9769c5e
% CLIENT connect to a server and read a message % % Usage - message = client(host, port, number_of_retries) function message = client(host, port, number_of_retries) import java.net.Socket import java.io.* if (nargin < 3) number_of_retries = 20; % set to -1 for infinite end retry = 0; input_socket = []; message = []; while true retry = retry + 1; if ((number_of_retries > 0) && (retry > number_of_retries)) fprintf(1, 'Too many retries\n'); break; end try fprintf(1, 'Retry %d connecting to %s:%d\n', ... retry, host, port); % throws if unable to connect input_socket = Socket(host, port); % get a buffered data input stream from the socket input_stream = input_socket.getInputStream; d_input_stream = DataInputStream(input_stream); fprintf(1, 'Connected to server\n'); % read data from the socket - wait a short time first pause(0.5); bytes_available = input_stream.available; fprintf(1, 'Reading %d bytes\n', bytes_available); message = zeros(1, bytes_available, 'uint8'); for i = 1:bytes_available message(i) = d_input_stream.readByte; end message = char(message); % cleanup input_socket.close; break; catch if ~isempty(input_socket) input_socket.close; end % pause before retrying pause(1); end end end
github
HelmchenLabSoftware/OCIA-master
makeMMNexperiment_duration.m
.m
OCIA-master/utils/soundGen/makeMMNexperiment_duration.m
2,993
utf_8
92bdcf7093f7ef7456e1a169108f5e79
function makeMMNexperiment_duration(durVector,f,sf) % in1 ... duration vector % in2 ... pure tone frequency (Hz) % in3 ... sampling frequency % this file written by Henry Luetcke ([email protected]) % some fixed parameters duty = 0.5; % duty cycle in s runs = 2; % no. of runs % (must be even, half the runs f1 is standard and f2 deviant, other half % vv) stims = 100; % no. of stims per run percS1S2 = [90 10]; % percentages for standard (S1) and deviant (S2) % check parameters if rem(runs,2) error('Number of runs must be even'); end if sum(percS1S2) ~= 100 error('Percentages of standard and deviants must sum to 100'); end % --> must be integers wrt. stims/runs for n = 1:length(percS1S2) if rem(stims*(percS1S2(n)/100),1) error('Number of standard and deviants must be integers'); end end % runs vector with 1 (f1 f2) and 2 (f2 f1) runsVector = [1 2]; runsVector = repmat(runsVector,1,runs/2); runsVector = shuffleVector(runsVector); stimVectorAll = cell(1,length(runsVector)); toneArrayAll = cell(1,length(runsVector)); % process each run for currentRun = 1:length(runsVector) % if runsVector(currentRun) == 1 % currentVector = durVector; % elseif runsVector(currentRun) == 2 % currentVector = fliplr(durVector); % end % make stim vector stimsS1 = stims*(percS1S2(1)/100); stimsS2 = stims*(percS1S2(2)/100); stimVector = [repmat(1,1,stimsS1),repmat(2,1,stimsS2)]; while true stimVector = shuffleVector(stimVector); % ensure first couple of stims are not 2 nonDeviants = 6; if sum(unique(stimVector(1:nonDeviants))) > 1 continue end % no adjacent deviants adjacentDeviant = 6; accept = 1; for n = adjacentDeviant+1:length(stimVector) if stimVector(n) == 2 if ~isempty(find(stimVector(n-adjacentDeviant:n-1)==2, 1)) accept = 0; end end end if accept break end end % half of the deviants should be 3 deviantsIdx = find(stimVector==2); if rem(numel(deviantsIdx),2) error('Number of deviants must be even.') end deviantsIdx = shuffleArray(deviantsIdx); deviantsIdx = deviantsIdx(1:(numel(deviantsIdx)/2)); stimVector(deviantsIdx) = 3; currentToneArray = MakePureToneArray_duration(durVector,stimVector,f,sf); SaveAndAssignInBase(stimVector,sprintf('stimVectorRun%02.0f',currentRun),... 'AssignOnly'); SaveAndAssignInBase(currentToneArray,sprintf('toneArrayRun%02.0f',currentRun),... 'AssignOnly'); stimVectorAll{currentRun} = stimVector; toneArrayAll{currentRun} = currentToneArray; end saveName = ['expInfo' datestr(clock,30) '.mat']; % save(saveName,'stimVectorAll','toneArrayAll'); fprintf('\nFinished\n'); function sRand = shuffleVector(s) k = randperm(length(s)); sRand = s; for n = 1:length(k) sRand(n) = s(k(n)); end
github
HelmchenLabSoftware/OCIA-master
makePureTone.m
.m
OCIA-master/utils/soundGen/makePureTone.m
1,803
utf_8
4775e6038bf3aba14c55af3dbc971624
function s = makePureTone(freqs,duration,varargin) % generate a pure tone % in1 ... carrier frequency in Hz % in2 ... duration in s % in3 ... sampling frequency in Hz {44100} % in4 ... rampDur in fraction of total duration {0.05} % in5 ... play tone {0}; 0 or 1 % in6 ... save wav file {[]}; filename of wav file % out1 ... the sound vector s or a cell array if more than one frequency was specified % this file written by Henry Luetcke ([email protected]) if nargin > 2 && ~isempty(varargin{1}); sf = varargin{1}; else sf = 44100; end if nargin > 3 && ~isempty(varargin{2}); rampDur = varargin{2}; else rampDur = 0.05; % ramp duration (fraction of total duration, max. 0.5) end if nargin > 4 && ~isempty(varargin{3}); doPlay = varargin{3}; else doPlay = 0; end if nargin > 5 && ~isempty(varargin{4}); saveWav = varargin{4}; else saveWav = []; end modFreq = 0; % modulation frequency modIndex = 1; % modulation index s = cell(numel(freqs), 1); for i = 1:length(freqs) % make the sound s{i} = MakeSound(sf,duration,freqs(i),modFreq,modIndex,rampDur); if doPlay sound(s{i},sf); end if ~isempty(saveWav) wavwrite(s{i},sf,16,saveWav); end end if numel(freqs) == 1; s = s{1}; end; function s = MakeSound(sf,d,f,mf,mi,rd) % frequency modulated sound n = round(sf * d); % number of samples c = (1:n) / sf; % carrier data preparation c = 2 * pi * f * c; % m = (1:n) / sf; % modulator data preparation % m = mi * cos(2 * pi * mf * m); % sinusoidal modulation m = 0; s = sin(c + m); % frequency modulation % ramp rd = d .* rd; nr = floor(sf * rd); r = sin(linspace(0, pi/2, nr)); r = [r, ones(1, n - nr * 2), fliplr(r)]; % make ramped sound s = s .* r;
github
HelmchenLabSoftware/OCIA-master
makeOmittedStimExperimentNoise.m
.m
OCIA-master/utils/soundGen/makeOmittedStimExperimentNoise.m
3,099
utf_8
f608ebec790c4a07c4e0772436893523
function makeOmittedStimExperimentNoise(fCellArray,sf) % fCellArray ... {[lower1 upper1],[lower2 upper2]} % sf ... sampling frequency % if f2 = 0, this will create an omitted stimulus paradigm % this file written by Henry Luetcke ([email protected]) % some fixed parameters dur = 0.2; % tone duration in s runs = 10; % no. of runs % (must be even, half the runs f1 is standard and f2 deviant, other half % vv) stims = 100; % no. of stims per run percS1S2 = [90 10]; % percentages for standard (S1) and deviant (S2) standardBetweenDeviant = 6; % this is the min. number of standard tones % between deviants (also the number of standards at start and end of % experiment) % check parameters if rem(runs,2) error('Number of runs must be even'); end if sum(percS1S2) ~= 100 error('Percentages of standard and deviants must sum to 100'); end % --> must be integers wrt. stims/runs for n = 1:length(percS1S2) if rem(stims*(percS1S2(n)/100),1) error('Number of standard and deviants must be integers'); end end % runs vector with 1 (f1 f2) and 2 (f2 f1) runsVector = [1 2]; runsVector = repmat(runsVector,1,runs/2); runsVector = shuffleVector(runsVector); if ~fCellArray{2} runsVector = ones(size(runsVector)); end stimVectorAll = cell(1,length(runsVector)); toneArrayAll = cell(1,length(runsVector)); % process each run for currentRun = 1:length(runsVector) if runsVector(currentRun) == 1 currentfCell = fCellArray; elseif runsVector(currentRun) == 2 currentfCell = fliplr(fCellArray); end % make stim vector stimsS1 = stims*(percS1S2(1)/100); stimsS2 = stims*(percS1S2(2)/100); stimVector = [repmat(1,1,stimsS1),repmat(2,1,stimsS2)]; while true stimVector = shuffleVector(stimVector); % min. number of standards at start and end if sum(unique(stimVector(1:standardBetweenDeviant))) > 1 continue end if sum(unique(stimVector(end-standardBetweenDeviant+1:end))) > 1 continue end accept = 1; for n = standardBetweenDeviant+1:length(stimVector) if stimVector(n) == 2 if ~isempty(find(stimVector(n-standardBetweenDeviant:n-1)==2, 1)) accept = 0; end end end if accept break end end currentToneArray = MakeNoiseToneArray(currentfCell,stimVector,dur,sf); % SaveAndAssignInBase(stimVector,sprintf('stimVectorRun%02.0f',currentRun),... % 'AssignOnly'); % SaveAndAssignInBase(currentToneArray,sprintf('toneArrayRun%02.0f',currentRun),... % 'AssignOnly'); stimVectorAll{currentRun} = stimVector; toneArrayAll{currentRun} = currentToneArray; end saveName = ['expInfo' datestr(clock,30) '.mat']; save(saveName,'stimVectorAll','toneArrayAll','fCellArray','sf'); evalStr = sprintf('load %s',saveName); evalin('base',evalStr) fprintf('\nFinished\n'); function sRand = shuffleVector(s) k = randperm(length(s)); sRand = s; for n = 1:length(k) sRand(n) = s(k(n)); end
github
HelmchenLabSoftware/OCIA-master
makeMMNexperiment.m
.m
OCIA-master/utils/soundGen/makeMMNexperiment.m
3,040
utf_8
1c64717c6c6d44304d01eeced947ad07
function makeMMNexperiment(fVector,sf) % fVector ... [freq1 freq2] % sf ... sampling frequency % if freq2 = 0, this will create an omitted stimulus paradigm % this file written by Henry Luetcke ([email protected]) % some fixed parameters dur = 0.2; % tone duration in s runs = 10; % no. of runs % (must be even, half the runs f1 is standard and f2 deviant, other half % vv) stims = 50; % no. of stims per run percS1S2 = [90 10]; % percentages for standard (S1) and deviant (S2) standardBetweenDeviant = 6; % this is the min. number of standard tones % between deviants (also the number of standards at start and end of % experiment) % check parameters if rem(runs,2) error('Number of runs must be even'); end if sum(percS1S2) ~= 100 error('Percentages of standard and deviants must sum to 100'); end % --> must be integers wrt. stims/runs for n = 1:length(percS1S2) if rem(stims*(percS1S2(n)/100),1) error('Number of standard and deviants must be integers'); end end % runs vector with 1 (f1 f2) and 2 (f2 f1) runsVector = [1 2]; runsVector = repmat(runsVector,1,runs/2); runsVector = shuffleVector(runsVector); if ~fVector(2) runsVector = ones(size(runsVector)); end stimVectorAll = cell(1,length(runsVector)); toneArrayAll = cell(1,length(runsVector)); % process each run for currentRun = 1:length(runsVector) if runsVector(currentRun) == 1 currentfVector = fVector; elseif runsVector(currentRun) == 2 currentfVector = fliplr(fVector); end % make stim vector stimsS1 = stims*(percS1S2(1)/100); stimsS2 = stims*(percS1S2(2)/100); stimVector = [repmat(1,1,stimsS1),repmat(2,1,stimsS2)]; while true stimVector = shuffleVector(stimVector); % min. number of standards at start and end if sum(unique(stimVector(1:standardBetweenDeviant))) > 1 continue end if sum(unique(stimVector(end-standardBetweenDeviant+1:end))) > 1 continue end accept = 1; for n = standardBetweenDeviant+1:length(stimVector) if stimVector(n) == 2 if ~isempty(find(stimVector(n-standardBetweenDeviant:n-1)==2, 1)) accept = 0; end end end if accept break end end currentToneArray = MakePureToneArray(currentfVector,stimVector,dur,sf); % SaveAndAssignInBase(stimVector,sprintf('stimVectorRun%02.0f',currentRun),... % 'AssignOnly'); % SaveAndAssignInBase(currentToneArray,sprintf('toneArrayRun%02.0f',currentRun),... % 'AssignOnly'); stimVectorAll{currentRun} = stimVector; toneArrayAll{currentRun} = currentToneArray; end saveName = ['expInfo' datestr(clock,30) '.mat']; save(saveName,'stimVectorAll','toneArrayAll'); evalStr = sprintf('load %s',saveName); evalin('base',evalStr) fprintf('\nFinished\n'); function sRand = shuffleVector(s) k = randperm(length(s)); sRand = s; for n = 1:length(k) sRand(n) = s(k(n)); end
github
HelmchenLabSoftware/OCIA-master
makeNoiseTone.m
.m
OCIA-master/utils/soundGen/makeNoiseTone.m
1,583
utf_8
c793c5a273c13f3af3f81b914137b260
function s = makeNoiseTone(freqs,duration,varargin) % generate a pure tone % in1 ... band-limiting frequencies in Hz [lower upper] % in2 ... duration in s % in3 ... sampling frequency in Hz {44100} % in4 ... play tone {0}; 0 or 1 % in5 ... rd % out1 ... the sound vector s % this file written by Henry Luetcke ([email protected]) if nargin > 2 sf = varargin{1}; if isempty(sf) sf = 44100; end else sf = 44100; end if nargin > 3 doPlay = varargin{2}; else doPlay = 0; end if nargin > 4 doPlay = varargin{2}; rd = varargin{3}; % ramp duration (fraction of total duration, max. 0.5) else rd = 0.05; % ramp duration (fraction of total duration, max. 0.5) end s = randn(1,round(sf*duration)); % Noise signal s = mpi_BandPassFilterTimeSeries(s,1/sf,freqs(1),freqs(2)); s = ScaleToMinMax(s,-1,1); % ramp n = round(sf .* duration); rd = duration .* rd; nr = floor(sf * rd); r = sin(linspace(0, pi/2, nr)); r = [r, ones(1, n - nr * 2), fliplr(r)]; % make ramped sound s = s .* r; if doPlay sound(s,sf); end function s = MakeSound(sf,d,f,mf,mi,rd) % frequency modulated sound n = sf * d; % number of samples c = (1:n) / sf; % carrier data preparation c = 2 * pi * f * c; % m = (1:n) / sf; % modulator data preparation % m = mi * cos(2 * pi * mf * m); % sinusoidal modulation m = 0; s = sin(c + m); % frequency modulation % ramp rd = d .* rd; nr = floor(sf * rd); r = sin(linspace(0, pi/2, nr)); r = [r, ones(1, n - nr * 2), fliplr(r)]; % make ramped sound s = s .* r;
github
HelmchenLabSoftware/OCIA-master
xyerrorbar.m
.m
OCIA-master/utils/plotting/xyerrorbar.m
1,618
utf_8
bbdb1d7c67cfdc53de32740db8e3dbd1
% xyerrorbar.m % (c) Nils Sjoberg 07-09-2004 Sweden % xyerrorbar(x,y,errx,erry,s) plots the data in y vs x with errorbars for % both y and x-data. Variables errx and erry are arrays of length=length(x and y) containing the % error in each and every datapoint. % s contains drawing-options for the plot and the options are the same as in % the ordinary plot-command, however the errorbar is plotted in a very % nice red hue! % % Here is an example % >figure % >xyerrorbar([1:0.5:5],[sin([1:0.5:5])],[ones(10,1).*0.1],[ones(10,1).*0.2],'g+') % the result shold be a plot of sin(x) vs x with errorbars for both x and % sin(x) -data. function h=xyerrorbar(x,y,errx,erry,s) if length(x)~=length(y) disp('x and y must have the same number of elements') return end if nargin<5 s=''; end hold on for k=1:length(x) l1=line([x(k)-errx(k) x(k)+errx(k)],[y(k) y(k)]); set(l1,'color',[0.5 0.5 0.5]) set(get(get(l1,'Annotation'),'LegendInformation'),... 'IconDisplayStyle','off'); % Exclude from legend % l2=line([x(k)-errx(k) x(k)-errx(k)],[y(k)-0.1*errx(k) y(k)+0.1*errx(k)]); % l3=line([x(k)+errx(k) x(k)+errx(k)],[y(k)-0.1*errx(k) y(k)+0.1*errx(k)]); l4=line([x(k) x(k)],[y(k)-erry(k) y(k)+erry(k)]); set(l4,'color',[0.5 0.5 0.5]) set(get(get(l4,'Annotation'),'LegendInformation'),... 'IconDisplayStyle','off'); % Exclude from legend % l5=line([x(k)-0.1*errx(k) x(k)+0.1*errx(k)],[y(k)-erry(k) y(k)-erry(k)]); % l6=line([x(k)-0.1*errx(k) x(k)+0.1*errx(k)],[y(k)+erry(k) y(k)+erry(k)]); end h = plot(x,y,s); hold off
github
HelmchenLabSoftware/OCIA-master
displayData.m
.m
OCIA-master/utils/plotting/displayData.m
9,061
utf_8
8f602663bd107c33523766f80b676ca0
function varargout = displayData(varargin) % this file written by Henry Luetcke if nargin S = varargin{1}; % parameter structure else S = struct; end tic S = parseInputs(S); %% load data [FilePath,FileName,FileType] = fileparts(S.RawFiles{1}); fullInfile = fullfile(FilePath,[FileName FileType]); if exist(fullInfile,'file') ~= 2 error('Could not find %s on absolute and relative paths',fullInfile); end switch FileType case '.fcs' img = import_raw(fullInfile); S.img_data{1} = uint8(img.ch1/255); % always save 8-bit integers S.img_data{2} = uint8(img.ch2/255); % save bit-depth for later usage S.hdr.bits = 8; case '.tif' % TODO: new tif-import in separate file, return data cell array and % header info img =tiffread2_wrapper(fullInfile); S.img_data{1} = img.data; S.hdr.tifHeader{1} = img.header; disp('Loaded channel 1'); if exist(strrep(fullInfile,'channel00','channel01')) == 2 img =tiffread2_wrapper(strrep(fullInfile,'channel00','channel01')); S.img_data{2} = img.data; S.hdr.tifHeader{2} = img.header; disp('Loaded channel 2'); end if exist(strrep(fullInfile,'channel00','channel02')) == 2 img =tiffread2_wrapper(strrep(fullInfile,'channel00','channel02')); S.img_data{3} = img.data; S.hdr.tifHeader{3} = img.header; disp('Loaded channel 3'); end S.hdr.bits = 16; otherwise error('Unrecognized file type %s',FileType); end %% Delete frames if S.del_frame for n = 1:length(S.img_data) S.img_data{n} = S.img_data{n}(:,:,S.del_frame+1:end); end end fprintf('Deleted %1.0f frame(s)\n',S.del_frame); %% Background correction if S.bgCorrect for n = 1:length(S.img_data) S.img_data{n} = bg_subtract_HL(S.img_data{n},S.bgCorrect,0,... 'percentile'); S.img_data{n}(S.img_data{n}<0) = 0; end end %% Calculate stats switch lower(S.statsType) case 'dff' stats = S.img_data{S.channelVector==1}; avgImg = mean(stats,3); intensityCutoff = prctile(avgImg(:),1); maskImg = ones(size(avgImg)); maskImg(avgImg<=intensityCutoff) = 0; case 'drr' stats1 = S.img_data{S.channelVector==1}; stats2 = S.img_data{S.channelVector==2}; avgImg = mean(stats1,3); stats = stats1 ./ stats2; clear stats1 stats2 intensityCutoff = prctile(avgImg(:),1); maskImg = ones(size(avgImg)); maskImg(avgImg<=intensityCutoff) = 0; % could extend this to include second channel end % smooth stats image parfor n = 1:size(stats,3) stats(:,:,n) = imfilter(stats(:,:,n),fspecial('gaussian',[10 10])); end fprintf('Smoothed image\n'); % calculate stats fprintf('Calculating %s image\n',upper(S.statsType)); statsImg = zeros(size(stats)); parfor x1 = 1:size(stats,1) % fprintf('Processing row %1.0f of %1.0f\n',x1,size(stats,1)); currentRow = shiftdim(stats(x1,:,:))'; currentRow = doStats(currentRow,maskImg(x1,:),S.frame_rate,5,25); statsImg(x1,:,:) = reshape(currentRow',size(stats,2),size(stats,3)); % for x2 = 1:size(stats,2) % if maskImg(x1,x2) % fVector = reshape(stats(x1,x2,:),1,size(stats,3)); % % 5 s segements; background at 25th percentile % f0Vector = findF0(fVector,S.frame_rate,5,25); % statsImg(x1,x2,:) = ... % ((fVector-f0Vector) ./ f0Vector) .* 100; % else % statsImg(x1,x2,:) = NaN; % end % end end stats = statsImg; clear statsImg frameNpil = nanmean(GetRoiTimeseries(stats,[])); %% Average image figure('Name','Average image','NumberTitle','off','Color','white'); imagesc(avgImg), colormap(gray), colorbar set(gca,'xtick',[],'ytick',[]) %% Activity image imgActive = FindActiveCells(stats,1); % normalize by neuropil skewness imgActive = imgActive ./ skewness(frameNpil); figure('Name','Activity image','NumberTitle','off','Color','white'); imagesc(imgActive), colorbar set(gca,'xtick',[],'ytick',[]) %% Frame neuropil plot figure('Name','Frame neuropil','NumberTitle','off','Color','white'); time = 1/S.frame_rate:1/S.frame_rate:size(stats,3)/S.frame_rate; plot(time,frameNpil) xlabel('Time / s') ylabel(sprintf('%s / %%',S.statsType)); tilefigs % toc % return windowSize = 5; for x1 = 1:size(stats,1) for x2 = 1:size(stats,2) stats(x1,x2,:) = filtfilt(ones(1,windowSize)/windowSize,1,... stats(x1,x2,:)); end end %% Activity movie % figure('Name','Activity Movie','NumberTitle','off','Color','white'); % true-color grayscale image avgMovie = gray2rgb(avgImg,512,'gray'); avgMovie = repmat(avgMovie,[1 1 1 size(stats,3)]); avgIntensity = zeros(1,3); cmap = hot(256); statsScale = [10 30]; statsLUT = statsScale(1):(statsScale(2)-statsScale(1))/255:statsScale(2); disp('Making movie...') for n = 1:size(stats,3) fprintf('Frame %1.0f / %1.0f\n',n,size(stats,3)); stats(:,:,n) = imfilter(stats(:,:,n),fspecial('gaussian',[10 10])); currentAvgMovie = avgMovie(:,:,1:3,n); currentStats = stats(:,:,n); currentRGB = zeros(size(stats,1),size(stats,2),3); for x1 = 1:size(currentStats,1) for x2 = 1:size(currentStats,2) if currentStats(x1,x2) > statsScale(1) avgIntensity = reshape(currentAvgMovie(x1,x2,:),1,3); [val,idx] = min(abs(statsLUT-currentStats(x1,x2))); if idx > size(cmap,1) idx = size(cmap,1); end currentStatsRGB = cmap(idx,:); currentRGB(x1,x2,:) = nanmean([avgIntensity; currentStatsRGB]); else currentRGB(x1,x2,:) = currentAvgMovie(x1,x2,1:3); end end end avgMovie(:,:,1:3,n) = currentRGB; end avgMovie(avgMovie>1) = 1; avgMovie(avgMovie<0) = 0; implay(avgMovie,25) toc function statsImg = doStats(stats,maskImg,frameRate,segmentDur,f0cutoff) statsImg = zeros(size(stats)); for n = 1:size(stats,2) if ~maskImg(n) statsImg(:,n) = nan(size(stats,1),1); else fVector = stats(:,n)'; % 5 s segements; background at 25th percentile f0Vector = findF0(fVector,frameRate,segmentDur,f0cutoff); fVector = ((fVector-f0Vector) ./ f0Vector) .* 100; statsImg(:,n) = fVector'; end end % statsImg(:,~maskImg) = NaN; %% ParseInputs - function function S = parseInputs(inargs) if ~isempty(inargs) && isstruct(inargs) % convert structure to pseudo-input cellarray inargs = struct2cellArray(inargs); end % input files - usually Gui-select SpInput = find(strcmpi(inargs, 'RawFiles')); if numel(SpInput) RawFiles = inargs{SpInput+1}; if ~iscellstr(RawFiles) error('Modifier for raw files property must be a cell string'); end else [FileName,PathName,FilterIndex] = uigetfile({'*.tif';'*.tiff';'*.fcs'},... 'Select raw file(s) - only 1 channel','MultiSelect','off'); if ~iscellstr(FileName) FileName = {FileName}; end if ~FileName{1}; return; end if ~iscellstr(FileName); FileName = cellstr(FileName); end % if strfind(PathName,RawDataDir) % PathName = strrep(PathName,RawDataDir,''); % end for n = 1:length(FileName) % interpret GUI-selected multiple files as different channels RawFiles{1,n} = fullfile(PathName,FileName{n}); end end S.RawFiles = RawFiles; % frame rate SpInput = find(strcmpi(inargs, 'frame_rate')); if numel(SpInput) frame_rate = inargs{SpInput+1}; if isscalar(frame_rate) frame_rate = repmat(frame_rate,1,length(RawFiles)); else if length(frame_rate) ~= length(RawFiles) error('Frame rate must be a scalar or vector of length input file number'); end end else frame_rate = 9.16; end S.frame_rate = frame_rate; % Preprocessing options - delete frame SpInput = find(strcmpi(inargs, 'DelFrame')); if numel(SpInput) del_frame = inargs{SpInput+1}; if isscalar(del_frame) del_frame = repmat(del_frame,1,length(RawFiles)); else if length(del_frame) ~= length(RawFiles) error('DelFrame must be a scalar or vector of length input file number'); end end else del_frame = 1; end S.del_frame = del_frame; % bg. correction - only specify cutoff for percentile method here (default % 1) SpInput = find(strcmpi(inargs, 'BgCorrect')); if numel(SpInput) bgCorrect = inargs{SpInput+1}; else bgCorrect = 1; end S.bgCorrect = bgCorrect; if ~isfield(S,'statsType') S.statsType = 'dff'; end % channels for stats calculation % DFF is calculated on the channel specified by config.channelVector(1) % DRR is calculated on the channels specified by config.channelVector(1) % and config.channelVector(2) if ~isfield(S,'channelVector') S.channelVector = [1 2]; end if strcmpi(S.statsType,'drr') && numel(S.channelVector) < 2 error('channelVector must specify at least 2 channels for DRR stats!'); end
github
HelmchenLabSoftware/OCIA-master
patchline.m
.m
OCIA-master/utils/plotting/patchline.m
3,694
utf_8
7e03ec713dc3b5ed750f273f9a944d50
function p = patchline(xs,ys,varargin) % Plot lines as patches (efficiently) % % SYNTAX: % patchline(xs,ys) % patchline(xs,ys,zs,...) % patchline(xs,ys,zs,'PropertyName',propertyvalue,...) % p = patchline(...) % % PROPERTIES: % Accepts all parameter-values accepted by PATCH. % % DESCRIPTION: % p = patchline(xs,ys,zs,'PropertyName',propertyvalue,...) % Takes a vector of x-values (xs) and a same-sized % vector of y-values (ys). z-values (zs) are % supported, but optional; if specified, zs must % occupy the third input position. Takes all P-V % pairs supported by PATCH. Returns in p the handle % to the resulting patch object. % % NOTES: % Note that we are drawing 0-thickness patches here, % represented only by their edges. FACE PROPERTIES WILL % NOT NOTICEABLY AFFECT THESE OBJECTS! (Modify the % properties of the edges instead.) % % LINUX (UNIX) USERS: One test-user found that this code % worked well on his Windows machine, but crashed his % Linux box. We traced the problem to an openGL issue; % the problem can be fixed by calling 'opengl software' % in your <http://www.mathworks.com/help/techdoc/ref/startup.html startup.m>. % (That command is valid at startup, but not at runtime, % on a unix machine.) % % EXAMPLES: %%% Example 1: % % n = 10; % xs = rand(n,1); % ys = rand(n,1); % zs = rand(n,1)*3; % plot3(xs,ys,zs,'r.') % xlabel('x');ylabel('y');zlabel('z'); % p = patchline(xs,ys,zs,'linestyle','--','edgecolor','g',... % 'linewidth',3,'edgealpha',0.2); % %%% Example 2: (Note "hold on" not necessary here!) % % t = 0:pi/64:4*pi; % p(1) = patchline(t,sin(t),'edgecolor','b','linewidth',2,'edgealpha',0.5); % p(2) = patchline(t,cos(t),'edgecolor','r','linewidth',2,'edgealpha',0.5); % l = legend('sine(t)','cosine(t)'); % tmp = sort(findobj(l,'type','patch')); % for ii = 1:numel(tmp) % set(tmp(ii),'facecolor',get(p(ii),'edgecolor'),'facealpha',get(p(ii),'edgealpha'),'edgecolor','none') % end % %%% Example 3 (requires Image Processing Toolbox): %%% (NOTE that this is NOT the same as showing a transparent image on %%% of the existing image. (That functionality is %%% available using showMaskAsOverlay or imoverlay). %%% Instead, patchline plots transparent lines over %%% the image.) % % img = imread('rice.png'); % imshow(img) % img = imtophat(img,strel('disk',15)); % grains = im2bw(img,graythresh(img)); % grains = bwareaopen(grains,10); % edges = edge(grains,'canny'); % boundaries = bwboundaries(edges,'noholes'); % cmap = jet(numel(boundaries)); % ind = randperm(numel(boundaries)); % for ii = 1:numel(boundaries) % patchline(boundaries{ii}(:,2),boundaries{ii}(:,1),... % 'edgealpha',0.2,'edgecolor',cmap(ind(ii),:),'linewidth',3); % end % % Written by Brett Shoelson, PhD % [email protected] % 5/31/2012 % % Revisions: % 6/26 Improved rice.png example, modified FEX image. % % Copyright 2012 MathWorks, Inc. % % See also: patch, line, plot [zs,PVs] = parseInputs(varargin{:}); if rem(numel(PVs),2) ~= 0 % Odd number of inputs! error('patchline: Parameter-Values must be entered in valid pairs') end % Facecolor = 'k' is (essentially) ignored here, but syntactically necessary if isempty(zs) p = patch([xs(:);NaN],[ys(:);NaN],'k'); else p = patch([xs(:);NaN],[ys(:);NaN],[zs(:);NaN],'k'); end % Apply PV pairs for ii = 1:2:numel(PVs) set(p,PVs{ii},PVs{ii+1}) end if nargout == 0 clear p end function [zs,PVs] = parseInputs(varargin) if isnumeric(varargin{1}) zs = varargin{1}; PVs = varargin(2:end); else PVs = varargin; zs = []; end
github
HelmchenLabSoftware/OCIA-master
makePrettyFigure.m
.m
OCIA-master/utils/plotting/makePrettyFigure.m
1,030
utf_8
4025d23131e4c264865ded9bcedc5c31
function figOut = makePrettyFigure(varargin) % for a given figure, apply some operations to make it look nicer if nargin == 0; fig = gcf; else fig = varargin{1}; end; figOut = fig; % a cell array of default axis properties (column 1 is the property name, % column 2 is the property value) defaultProps = { ... 'box','off'; ... 'linewidth',1.5; ... 'fontname','arial'; ... 'fontsize',14; ... }; % some basic niceties on the figure set(fig,'color','white') % get children (the axes) figHandles = findall(fig); for n = 1:numel(figHandles) setDefaultAxesProps(figHandles(n),defaultProps); end set(findall(0,'tag','legend'),'box','on') function setDefaultAxesProps(a,defaultProps) for n = 1:size(defaultProps,1) try set(a,defaultProps{n,1},defaultProps{n,2}) end end % children = get(a,'children'); % for n = 1:numel(children) % for m = 1:size(defaultProps,1) % try % set(children(n),defaultProps{m,1},defaultProps{m,2}) % end % end % end
github
HelmchenLabSoftware/OCIA-master
PsPlot2Raster.m
.m
OCIA-master/utils/plotting/PsPlot2Raster.m
7,798
utf_8
50a24bc695620bf37df86f36fba74d0b
function varargout = PsPlot2Raster(varargin) % plot different columns (stims) in ps_plot_cell in different subplots % in1 ... psPlot cell array (roi x stim), each cell contains trial x % timepoints ps-matrix % in2 ... sampling frequency % in3 ... offset (frame of stimulus presentation) % in4 ... optional cellstring with roi names % in5 ... PlotType (1 ... trials-by-Rois, 2 ... Rois-by-trials), default 1 % in6 ... plot PSTH (1 or 0, only takes effect if PlotType is 1 and % Roi count is 1); default 0 % out1 ... figure handle % out2 ... PSTH (roi x stim cell array), always calculated trials x rois % this file written by Henry Luetcke ([email protected]) inargs = varargin; [ps_plot_cell,freq,offset,roiList,plotType,doPSTH] = ParseInputs(inargs{1:length(inargs)}); roiCount = size(ps_plot_cell,1); maxStim = size(ps_plot_cell,2); % roiCount = 2; % maxStim = size(ps_plot_cell,2); cmap = lines(roiCount); % or we plot alternately in 1 of 2 colors % cmap = [0 0 0; 1 0 0]; % cmap = repmat(cmap,roiCount/2,1); % if size(cmap,1) < roiCount % cmap(roiCount,:) = cmap(1,:); % end % ytick_pos = zeros(1,roiCount); h_fig = figure('Name','Raster plot','NumberTitle','off'); hold on if plotType == 1 psth_cell = doPlot(ps_plot_cell,roiCount,maxStim,freq,offset,cmap,... roiList,doPSTH); if nargout == 2 varargout{2} = psth_cell; end elseif plotType == 2 trialNo = size(ps_plot_cell{1,1},1); psByTrial = cell(trialNo,maxStim); pos = 1; for stim = 1:maxStim for trial = 1:trialNo for roi = 1:roiCount if ~isnan(ps_plot_cell{roi,stim}) psByTrial{trial,stim}(roi,:) = ... ps_plot_cell{roi,stim}(trial,:); else psByTrial{trial,stim}(roi,:) = 0; end end end end for n = 1:trialNo trialList{n} = sprintf('%02g',n); end cmap = lines(trialNo); doPlot(psByTrial,trialNo,maxStim,freq,offset,cmap,trialList,doPSTH); end if nargout varargout{1} = h_fig; end %% Plot function function varargout = doPlot(ps_plot_cell,roiCount,maxStim,freq,offset,... cmap,roiList,doPSTH) psth_cell = cell(roiCount,maxStim); % number of ps-timepoints % while true doBreak = 0; for roi = 1:roiCount eventRange = unique(ps_plot_cell{roi,1}); if ~isnan(eventRange(1)) timepoints = size(ps_plot_cell{roi,1},2); doBreak = 1; break end end if ~doBreak error('Could not determine number of timepoints'); end % if doBreak % break % end % end % sum rasters for all rois for stims AllStimSum = zeros(maxStim,timepoints); trials = zeros(1,maxStim); for stim = 1:maxStim currentSum = zeros(1,timepoints); for roi = 1:roiCount currentRoiSum = nansum(ps_plot_cell{roi,stim},1); if isnan(currentRoiSum) continue end if ~currentRoiSum continue end currentSum = nansum([currentSum;currentRoiSum],1); if ~trials(stim) trials(stim) = size(ps_plot_cell{roi,stim},1); end end AllStimSum(stim,:) = currentSum; end absoluteYmax = []; maxTrials = max(trials); % setup subplot if maxStim > 3 subIdx = repmat(ceil(sqrt(maxStim)),1,2); else subIdx = [1 maxStim]; end for stim = 1:maxStim subplot(subIdx(1),subIdx(2),stim); hold on pos = 1; plottedRoiCount = 1; % some Rois are NaN min_time = inf; max_time = -inf; for roi = 1:roiCount posStart = pos; current_raster = ps_plot_cell{roi,stim}; if isnan(current_raster) current_raster = zeros(trials(stim),timepoints); end % roiList2{plottedRoiCount} = roiList{roi}; plottedRoiCount = plottedRoiCount + 1; timepoints = size(current_raster,2); if min_time > ((1-offset) / freq)-1/freq; min_time = ((1-offset) / freq)-1/freq; end if max_time < ((size(current_raster,2)-offset) / freq)+1/freq; max_time = ((size(current_raster,2)-offset) / freq)+1/freq; end lastTrialEmpty = 0; for current_run = 1:maxTrials if current_run > trials(stim) current_sweep = zeros(1,size(current_raster,2)); else current_sweep = current_raster(current_run,:); end spikeTimes = find(current_sweep); if isempty(spikeTimes) lastTrialEmpty = 1; else lastTrialEmpty = 0; end spikeTimes = (spikeTimes-offset) / freq; h_err = errorbar(spikeTimes,repmat(pos,1,length(spikeTimes)),... repmat(1/(freq*2),1,length(spikeTimes)),... repmat(1/(freq*2),1,length(spikeTimes)),'.k'); hold on set(h_err,'Color',cmap(roi,:),'Marker','none'); pos = pos + 1; end % if last trial was empty, plot white point at 0,pos-1 % if lastTrialEmpty % herrorbar(0,pos-1,0,0,'.w'); hold on % end posStop = pos; ytick_pos(plottedRoiCount) = round(mean([posStart posStop])); ylims = get(gca,'ylim'); psth = nansum(current_raster,1); % 0.5 s moving average filter % windowSize = ceil(0.5 * 0.5 * freq); % psth = filtfilt(ones(1,windowSize)/windowSize,1,psth); if doPSTH psth_scaled = linScale(psth,posStart,posStop); psth_time = (min_time+1/freq):1/freq:(max_time-1/freq); plot(psth_time,psth_scaled,':k','LineWidth',1.5) end psth = psth ./ size(current_raster,1); psth_cell{roi,stim} = reshape(psth,1,numel(psth)); end % plot the summed PSTH for all Rois for this stimulus % normalize between 0 and pos/10, then offset by pos if stim == 1 AllStimSum = linScale(AllStimSum,0,pos/10); end currentSum = AllStimSum(stim,:); currentSum = currentSum + pos; % currentSum = filtfilt(ones(1,windowSize)/windowSize,1,currentSum); currentSum_time = (min_time+1/freq):1/freq:(max_time-1/freq); plot(currentSum_time,currentSum,':k','LineWidth',1.5) ytick_pos(length(ytick_pos)+1) = mean(currentSum); ytick_pos(1) = []; if isempty(absoluteYmax) absoluteYmax = max(currentSum); else currentYmax = max(currentSum); if currentYmax > absoluteYmax absoluteYmax = currentYmax; end end set(gca,'xlim',[min_time max_time]) if stim == 1 roiList = reshape(roiList,1,numel(roiList)); set(gca,'ytick',ytick_pos,'yticklabel',[roiList 'sum']) else set(gca,'ytick',[]) end set(gca,'TickLength',[0 0]) title(['Stim ' int2str(stim)]) axisHandle(stim) = gca; end for n = 1:length(axisHandle) set(axisHandle(n),'ylim',[0 absoluteYmax]); end if nargout varargout{1} = psth_cell; end % fprintf('\nPlotted %s total runs from %s Rois\n',... % int2str(pos-1),int2str(size(ps_plot_cell,1))); %% Parse inputs function [ps_plot_cell,freq,offset,roiList,plotType,doPSTH] = ... ParseInputs(varargin) error(nargchk(3,6,nargin)) ps_plot_cell = varargin{1}; if ~iscell(ps_plot_cell) ps_plot_cell = {ps_plot_cell}; end freq = varargin{2}; offset = varargin{3}; roiCount = size(ps_plot_cell,1); if nargin >= 4 && ~isempty(varargin{4}) roiList = varargin{4}; else for n = 1:roiCount roiList{n} = sprintf('%02g',n); end end if nargin >= 5 && ~isempty(varargin{5}) plotType = varargin{5}; else plotType = 1; end doPSTH = 0; if nargin >= 6 && plotType == 1 && ~isempty(varargin{6}) doPSTH = varargin{6}; end
github
HelmchenLabSoftware/OCIA-master
adjustSubplotAxes.m
.m
OCIA-master/utils/plotting/adjustSubplotAxes.m
1,602
utf_8
0fd6cc79ba5adfbf3fc307b09b8e87bd
function adjustSubplotAxes(h,varargin) % adjust axis of all subplots in figure h % specify axis by string / value combination, e.g.: % 'X',[-5 10] sets all x-limits to [-5 10] % 'Y',[] sets y-limits to Min / Max % unlisted axes are left untouched % varargin{1} ... the axis limits to be set (default: Min / Max) inargs = varargin; xLims = NaN; yLims = NaN; zLims = NaN; for n = 1:numel(inargs) if isstr(inargs{n}) switch lower(inargs{n}) case 'x' xLims = inargs{n+1}; case 'y' yLims = inargs{n+1}; case 'z' zLims = inargs{n+1}; end end end % get all axes of the figure h axisHandles = findobj(h,'Type','Axes'); legendHandles = findobj(h,'Tag','legend'); for n = 1:numel(legendHandles) props{n} = get(legendHandles(n)); end % set axes if ~any(isnan(xLims)) setLimits('xlim',xLims,axisHandles); end if ~any(isnan(yLims)) setLimits('ylim',yLims,axisHandles); end if ~any(isnan(zLims)) setLimits('zlim',zLims,axisHandles); end % reset legend props for n = 1:numel(legendHandles) fields = fieldnames(props{n}); for m = 1:numel(fields) try set(legendHandles(n),fields{m},props{n}.(fields{m})) end end end function setLimits(type,lims,axisHandles) if isempty(lims) % find axis limits of all axes lims = [inf -inf]; for n = 1:numel(axisHandles) currentLims = get(axisHandles(n),type); lims(1) = min([lims(1) currentLims(1)]); lims(2) = max([lims(2) currentLims(2)]); end end set(axisHandles,type,lims)
github
HelmchenLabSoftware/OCIA-master
groupedErrBar.m
.m
OCIA-master/utils/plotting/groupedErrBar.m
5,106
utf_8
94caedf9ae477f0d7de99a816ae21638
function h = groupedErrBar(dataCell,varargin) % plot multiple data sets in groups with errorbar and (optionally) individual data points % dataCell ... cell array with 1 vector per cell containing n observations % cells in the same row will be grouped, cells in different rows will be different groups (similar % to bar function) % optional input args ({'parameter',value} pairs): % 'plotAll' ... plot individual observations in addition to mean / error (0 or 1) % 'avg' ... 'mean', 'median' % 'var' ... 'sd', 'sem', 'ci' (ci is 95% CI of the mean and should not be used with median) % 'separation' ... 0.2 (determines the separation of groups) % 'xticklabel' ... {'1','2','3'} (name of each group) % 'legend' ... legend entry for each column % doStats ... 0 or 1 (default: 0) --> print out stats comparison for each group % output: handle vector % Example: % A = {randn(10,1) randn(8,1) randn(12,1); randn(5,1) randn(9,1) randn(7,1)}; % groupedErrBar(A,'var','sem','plotall',1,'xticklabel',{'G1','G2'},'legend',{'t1','t2','t3'}) % this function requires the statistics toolbox % TODO: further measures of central tendency and variability (e.g. CI); assymetric error bars; stats if nargin > 1 config = parseInputArgs(varargin); else config = parseInputArgs; % defaults end dataSize = size(dataCell); % calculate corresponding x-axis xCoarse = 1:dataSize(1); % the different groups x = []; for n = 1:dataSize(1) x = [x, linspace(xCoarse(n)-config.separation,xCoarse(n)+config.separation,dataSize(2))]; end % run ANOVA on entire data set if config.doStats anovaData = []; anovaLabels = cell(1,2); for row = 1:dataSize(1) for col = 1:dataSize(2) anovaData = [anovaData; dataCell{row,col}]; anovaLabels{1,1} = [anovaLabels{1,1}; repmat(row,numel(dataCell{row,col}),1)]; anovaLabels{1,2} = [anovaLabels{1,2}; repmat(col,numel(dataCell{row,col}),1)]; end end [~,table] = anovan(anovaData,anovaLabels,'display','off','model','full',... 'varnames',{'Row','Column'}); fprintf('\nANOVA table:\n') disp(table) end colorMap = lines(dataSize(2)); % different color for each entry per group % now just go sequentially through the data and plot xPos = 0; for row = 1:dataSize(1) for col = 1:dataSize(2) xPos = xPos + 1; data = dataCell{row,col}; config.avgColor = colorMap(col,:); if row == dataSize(1) config.setLegend = 1; else config.setLegend = 0; end doPlot(x(xPos),data,config); end if config.doStats anovaData = []; labels = []; for col = 1:dataSize(2) anovaData = [anovaData; dataCell{row,col}]; labels = [labels; repmat(col,numel(dataCell{row,col}),1)]; end [~,table,stats] = anovan(anovaData,labels,'display','off'); if isempty(config.xticklabel) fprintf('\nStats - %1.0f\n',row) else fprintf('\nStats - %s\n',config.xticklabel{row}) end fprintf('F=%1.3f p=%1.5e df=%1.0f\n',table{2,6},table{2,7},table{3,3}) end end % label axis if isempty(config.xticklabel) set(gca,'xtick',1:dataSize(1)) else set(gca,'xtick',1:dataSize(1),'xticklabel',config.xticklabel) end set(gca,'xlim',[0 x(end)+x(1)]), ylabel(sprintf('%s +- %s',config.avg,config.var)) legend(config.legend) makePrettyFigure(gcf); end function doPlot(x,data,config) switch lower(config.avg) case 'mean' avgData = nanmean(data); case 'median' avgData = nanmedian(data); otherwise error('Avg measure %s not supported',config.avg) end switch lower(config.var) case 'sd' varData = nanstd(data); case 'sem' varData = sem(data); case 'ci' [~,~,varData] = normfit(data); otherwise error('Var measure %s not supported',config.var) end if config.plotAll hScatter = scatter(repmat(x,numel(data),1),data,'Marker','o','MarkerEdgeColor',[0.5 0.5 0.5]); hold on set(get(get(hScatter,'Annotation'),'LegendInformation'),... 'IconDisplayStyle','off'); end xErr = x - config.separation./10; % slightly offset if numel(varData) == 1 hErr = errorbar(xErr,avgData,varData,... 'Marker','s','Color',config.avgColor,'LineStyle','none'); else hErr = errorbar(xErr,avgData,varData(1),varData(2),... 'Marker','s','Color',config.avgColor,'LineStyle','none'); end removeErrorBarEnds(hErr); hold on if ~config.setLegend set(get(get(hErr,'Annotation'),'LegendInformation'),... 'IconDisplayStyle','off'); end end function config = parseInputArgs(varargin) if nargin inArgs = varargin; else inArgs = {[]}; end inArgs = inArgs{1}; config = struct; requiredArgs = {'plotAll','avg','var','separation','xticklabel','legend','doStats'}; defaults = {1,'mean','sem',0.2,[],[],0}; for n = 1:numel(requiredArgs) if isempty(find(strcmpi(inArgs,requiredArgs{n}), 1)) config.(requiredArgs{n}) = defaults{n}; else config.(requiredArgs{n}) = inArgs{find(strcmpi(inArgs,requiredArgs{n}),1)+1}; end end end
github
HelmchenLabSoftware/OCIA-master
nfb_errorbar.m
.m
OCIA-master/utils/plotting/nfb_errorbar.m
7,945
utf_8
90c8e91005ce42d017454ea42ffb2e73
% nfb_errorbar is a generic function which produces a bar chart with error % bars % its main advantage is that it readily plots each bar and errorbar % separately, making it easy to change colours, filling etc for each bar % individually later on % % USAGE: % [out1] = nfb_errorbar(in1, in2) % % Comulsory input arguments % in1 ... bar matrix (2D) % in2 ... errorbar matrix (2D) % of course in1 and in2 could also be a simple vector % each matrix entry corresponds to 1 bar / errorbar and values in the same % row will be grouped (i.e. bars sit closer on the plot than values from % different rows) % bar and errorbar matrices MUST be of equal size % % Optional input arguments (in any order) % 'Figure', add errorbar to an existing figure (provide handle to figure) % 'Spacing' (default: 0.85) % 'Color', string specification of valid Matlab colormap (see doc colormap) % (default is 'jet') % 'Labels', cellstring of row*columns length (one label % per bar) or row length (one label per bar group) % i.e. 'Labels',{'value1' 'value2' 'value3'} % 'Legend', cellstring provides legend tags for bars (must not be longer % than number of bars, i.e. rows*columns of input matrices) % 'RemoveTee', remove horizontal lines at end of error bars (0 or 1, % default 0), requires removeErrorBarEnds function % String args: 'Title', 'XLabel', 'YLabel', 'Name' (Figure Name, if % specified, also switches NumberTitle off) % % out1 ... handle to figure % this file written by Henry Luetcke ([email protected]) function [bar_chart] = nfb_errorbar(varargin) if nargin < 2 disp('You MUST provide at least 2 input arguments'); disp(' '); help nfb_errorbar return end bars = varargin{1}; errs = varargin{2}; if size(bars) ~= size(errs) error('Bar and errorbar matrices must be of equal size'); end if length(size(bars)) > 2 || length(size(errs)) > 2 error('Bar and errorbar matrices must be 2D matrices'); end % hluetck::12.02.2008 % Parameter for specifying spacing between bars explicitely % check if spacing of bars has been specified explicitely spacing = 0.85; % tauer::20.02.2008 % simplified SpInput = find(strcmp(varargin, 'Spacing')); if numel(SpInput) spacing = varargin{SpInput+1}; end % hluetck::03.03.2008 % Option to add errorbar plot to existing figure SpInput = find(strcmp(varargin, 'Figure')); if numel(SpInput) bar_chart = varargin{SpInput+1}; else bar_chart = figure; end hold on % hluetck::12.02.2008 % Parameter for specifying spacing between bars explicitely % first we generate the x values (depending on the number of rows and % columns) % tauer::20.02.2008 % simplified current_x = 1; for n = 1:size(bars,1) for m = 1:size(bars,2) x_vals((n-1)*size(bars,2)+m) = current_x; current_x = current_x + spacing; end current_x = current_x + 0.5; end % rearrange matrices into vectors and plot rows = size(bars,1); cols = size(bars,2); bars = reshape(bars',(size(bars,1)*size(bars,2)),1); errs = reshape(errs',(size(errs,1)*size(errs,2)),1); % hluetck::24.02.2008 % specify bar color according to Matlab color map SpInput = find(strcmp(varargin, 'Color')); if numel(SpInput) cmap = varargin{SpInput+1}; cstring = sprintf('%s(%s)',cmap,int2str(cols)); try evalc(cstring); catch fprintf(... '\n"%s" is not a valid Matlab color map. Using ''jet''.\n',... cmap); cmap = 'jet'; end else cmap = 'jet'; end cstring = sprintf('%s(%s)',cmap,int2str(cols)); group_colors = colormap(cstring); % hluetck::23.02.2008 % changed allocation of bar color % now cycle colors within bar groups and not between groups % (makes more sense if used in combination with legend?) % also adjusted color specification (now RGB vector) % plot current_col = 0; col = 1; for n = 1:length(bars) if current_col == cols col = 1; current_col = 0; end bar(x_vals(n),bars(n),'FaceColor',group_colors(col,:)); current_col = current_col + 1; col = col + 1; end % for n = length(errs):-1:1 % errorbar(x_vals(n),bars(n),errs(n),'k','LineWidth',1.5); % end e_bar = errorbar(x_vals,bars,errs,'k','LineWidth',1.5,'LineStyle','none'); % parse opional input arguments if nargin > 2 opt_args = varargin(3:nargin); for n = 1:length(opt_args) if strcmp(opt_args{n},'RemoveTee') == 1 removeTee = opt_args{n+1}; if removeTee && exist('removeErrorBarEnds','file') == 2 removeErrorBarEnds(e_bar); end end % hluetck::23.02.2008 % included option to attach only one label per bar group % in combination with legend option, this now allows efficient % labeling of bar charts % attach labels if strcmp(opt_args{n},'Labels') == 1 labels = opt_args{n+1}; if length(labels) ~= (rows*cols) if length(labels) ~= rows disp('Incorrect number of labels has been given'); disp(' '); help nfb_errorbar return else % hluetck::23.02.2008 % attach only 1 label per bar group if rem(cols,2) center = ceil(cols/2); x_vals_short = []; x_vals_pos = 1; previous_center = 0; for m = 1:length(x_vals) if m == (ceil((cols*x_vals_pos)/2)+previous_center) previous_center = ceil((cols*x_vals_pos)/2); x_vals_short(x_vals_pos) = x_vals(m); x_vals_pos = x_vals_pos + 1; end end else center = cols/2; center = ceil(cols/2); x_vals_short = []; x_vals_pos = 1; previous_center = 0; for m = 1:length(x_vals) if m == (ceil((cols*x_vals_pos)/2)+previous_center) previous_center = ceil((cols*x_vals_pos)/2); x_vals_short(x_vals_pos) = x_vals(m)+0.5; x_vals_pos = x_vals_pos + 1; end end end set(gca,'XTick',[x_vals_short],'XTickLabel',labels); end else % hluetck::23.02.2008 % attach one label for each bar set(gca,'XTick',[x_vals],'XTickLabel',labels); end end % hluetck::23.02.2008 % modified legend creation (it does actually work now) % create column legend if strcmp(opt_args{n},'Legend') == 1 col_legend = opt_args{n+1}; if length(col_legend) > cols*rows disp('Incorrect number of legend values has been given'); disp(' '); help nfb_errorbar return end legend(col_legend,'Location','Best'); end % add a title if strcmp(opt_args{n},'Title') == 1 plot_title = opt_args{n+1}; h_title = title(plot_title); set(h_title,'Interpreter','none'); end % y-axis label if strcmp(opt_args{n},'YLabel') == 1 plot_ylabel = opt_args{n+1}; ylabel(plot_ylabel); end % x-axis label if strcmp(opt_args{n},'XLabel') == 1 plot_xlabel = opt_args{n+1}; xlabel(plot_xlabel); end % Figure Name if strcmp(opt_args{n},'Name') == 1 fig_name = opt_args{n+1}; set(gcf,'Name',fig_name,'NumberTitle','off'); end end end % e.o.f.
github
HelmchenLabSoftware/OCIA-master
fig2m.m
.m
OCIA-master/utils/plotting/fig2m.m
19,924
utf_8
857a1a6daef974fc98a2e735071bb6e8
function varargout = fig2m(guiName,outputDir,syscolorfig,cb_gen) % FIG2M - Generate programmatic GUI M-File from a FIG-File % % Version : 1.0 % Created : 10/05/2006 % Modified: 14/04/2010 % Author : Thomas Montagnon (The MathWorks France) % % >> outputFile = fig2m(guiName,outputDir,syscolorfig,cb_gen); % % guiName -> Name of the Fig-File (absolute or relative path) % outputDir -> Directory where the generated M-File will be saved % syscolorfig -> Use system default background color (true or false) % cb_gen -> Generate callbacks (true or false) % outputFile -> Name of the generated M-File % % >> fig2m % % If you call the function with no input arguments it will ask you for the % parameters. % INPUT ARGUMENTS if nargin < 4 % Generate callbacks answer = questdlg('Do you want to generate the callbacks?','Callbacks','Yes','No','Yes'); if strcmp(answer,'Yes') cb_gen = true; else cb_gen = false; end end if nargin < 3 % Use system default background color answer = questdlg('Do you want to use the system default background color?','Background color','Yes','No','Yes'); if strcmp(answer,'Yes') syscolorfig = true; else syscolorfig = false; end end if nargin == 1 % Check if guiName is a directory or a file if exist(guiName,'dir') [guiName,guiPath] = uigetfile(fullfile(guiName,'*.fig'),'Choose a FIG-File'); if isequal(guiName,0) return end guiName = fullfile(guiPath,guiName); end % Output directory outputDir = uigetdir(guiPath,'Choose the output directory'); if isequal(outputDir,0) return end end if nargin == 0 % Fig-File [guiName,guiPath] = uigetfile('*.fig','Choose a FIG-File'); if isequal(guiName,0) return end guiName = fullfile(guiPath,guiName); % Output directory outputDir = uigetdir(guiPath,'Choose the output directory'); if isequal(outputDir,0) return end end if ~exist(guiName,'file') error('Bad input argument'); end % Get info about the FIG-File [guiPath,guiName,guiExt] = fileparts(guiName); % Stop the execution of the function if the FIG-File doesn't exist or is invalid if ~strcmpi(guiExt,'.fig') uiwait(errordlg('Invalid GUI file','Error')); varargout{1} = ''; return end if ~exist(fullfile(guiPath,[guiName,guiExt]),'file') uiwait(errordlg('GUI file not exists','Error')); varargout{1} = ''; return end % Output file name outputFile = [guiName '_build.m']; % Name of the output file outFile = fullfile(outputDir,outputFile); % Graphic objects categories Categories = {... 'FIGURE',... 'CONTEXT MENUS',... 'MENU ITEMS',... 'PANELS',... 'AXES',... 'LINES',... 'SURFACES',... 'STATIC TEXTS',... 'PUSHBUTTONS',... 'TOGGLE BUTTONS',... 'RADIO BUTTONS',... 'CHECKBOXES',... 'EDIT TEXTS',... 'LISTBOXES',... 'POPUP MENU',... 'SLIDERS',... 'UITABLE',... 'TOOLBAR', ... 'PUSH TOOLS', ... 'TOGGLE TOOLS'}; % Default Tags DefTags = {... 'figure',... 'menu',... 'menuitem',... 'panel',... 'axes',... 'line',... 'surf',... 'text',... 'pushbutton',... 'togglebutton',... 'radiobutton',... 'checkbox',... 'edit',... 'listbox',... 'popupmenu',... 'slider',... 'uitable',... 'uitoolbar', ... 'uipushtool', ... 'uitoggletool'}; % Callbacks names cb_names = { ... 'Callback', ... 'ButtonDownFcn', ... 'CreateFcn', ... 'DeleteFcn', ... 'KeyPressFcn', ... 'KeyReleaseFcn', ... 'ResizeFcn', ... 'WindowButtonDownFcn', ... 'WindowButtonMotionFcn', ... 'WindowButtonUpFcn', ... 'WindowScrollWheelFcn', ... 'SelectionChangeFcn', ... 'ClickedCallback', ... 'OffCallback', ... 'OnCallback', ... 'CellEditCallback', ... 'CellSelectionCallback'}; % Default properties values dprop = default_prop_values(); % Properties for each style of objects prop = control_properties(); idList = fieldnames(prop); % Ouput file header header = sprintf([... 'function fig_hdl = %s\n' ... '%% %s\n' ... '%%-------------------------------------------------------------------------------\n' ... '%% File name : %-30s\n' ... '%% Generated on: %-30s\n' ... '%% Description :\n' ... '%%-------------------------------------------------------------------------------\n' ... '\n\n'], ... outputFile(1:end-2),... upper(outputFile(1:end-2)),... outputFile,... datestr(now)); try % Open the GUI cdir = pwd; cd(guiPath); figFcn = str2func(guiName); figHdl = figFcn(); cd(cdir); % figHdl = openfig(fullfile(guiPath,[guiName,'.fig'])); pause(.1); % Set Window style & CloseRequestFcn for GUI in order to hide the figure set(figHdl,'WindowStyle','normal','CloseRequestFcn','closereq','visible','off'); pause(.1); % List all the graphic object by category list.Fg = figHdl; list.Cm = sort(findobj(figHdl,'Type', 'uicontextmenu')); list.Mb = sort(findobj(figHdl,'Type', 'uimenu')); list.Pa = sort(findobj(figHdl,'Type', 'uipanel')); list.Ax = sort(findobj(figHdl,'Type', 'axes')); list.Li = sort(findobj(figHdl,'Type', 'line')); list.Sf = sort(findobj(figHdl,'Type', 'surface')); list.Ta = sort(findobj(figHdl,'Type', 'uitable')); list.To = sort(findobj(figHdl,'Type' ,'uitoolbar')); list.Pt = sort(findobj(figHdl,'Type' ,'uipushtool')); list.Tt = sort(findobj(figHdl,'Type' ,'uitoggletool')); list.St = sort(findobj(figHdl,'Style','text')); list.Pb = sort(findobj(figHdl,'Style','pushbutton')); list.Tb = sort(findobj(figHdl,'Style','togglebutton')); list.Rb = sort(findobj(figHdl,'Style','radiobutton')); list.Cb = sort(findobj(figHdl,'Style','checkbox')); list.Ed = sort(findobj(figHdl,'Style','edit')); list.Lb = sort(findobj(figHdl,'Style','listbox')); list.Pu = sort(findobj(figHdl,'Style','popupmenu')); list.Sl = sort(findobj(figHdl,'Style','slider')); % Init callback list if cb_gen cb_list = {}; end % Start writing the output file str = sprintf('%s',header); % Add command to init the handles structure str = sprintf('%s%% Initialize handles structure\nhandles = struct();\n\n',str); % Creat all controls str = sprintf('%s%% Create all UI controls\nbuild_gui();\n\n',str); % Add command line to assign output variable str = sprintf('%s%% Assign function output\nfig_hdl = handles.%s;\n\n',... str,get(list.Fg,'Tag')); % Create a nested function to build all uicontrols str = sprintf('%s%%%% ---------------------------------------------------------------------------\n',str); str = sprintf('%s\tfunction build_gui()\n%% Creation of all uicontrols\n\n',str); % Write the generation code for all the objects, grouped by category for indCat=1:length(idList) % Handles vector and properties list for the current category hdlsTemp = list.(idList{indCat}); propTemp = prop.(idList{indCat}); % Object creation function depending on the category switch idList{indCat} case 'Fg' ctrlFcn = 'figure'; case 'Pa' ctrlFcn = 'uipanel'; case 'Ta' ctrlFcn = 'uitable'; case 'Mb' ctrlFcn = 'uimenu'; case 'Cm' ctrlFcn = 'uicontextmenu'; case 'Ax' ctrlFcn = 'axes'; case 'Li' ctrlFcn = 'line'; case 'Sf' ctrlFcn = 'surf'; case 'To' ctrlFcn = 'uitoolbar'; case 'Pt' ctrlFcn = 'uipushtool'; case 'Tt' ctrlFcn = 'uitoggletool'; otherwise ctrlFcn = 'uicontrol'; end % If there are objects from the current category then write code if ~isempty(hdlsTemp) % Category name str = sprintf('%s\t\t%% --- %s -------------------------------------\n',str,Categories{indCat}); % Init index for empty tags idxTag = 1; % Browse all the object belonging to the current category for indObj=1:length(hdlsTemp) % Get property values for the current object listTemp = get(hdlsTemp(indObj)); % If tag is empty then create one if isempty(listTemp.Tag) listTemp.Tag = sprintf('%s%u',DefTags{indCat},idxTag); set(hdlsTemp(indObj),'Tag',listTemp.Tag); idxTag = idxTag + 1; end % Special treatment for UIButtongroup (UIButtongroup are UIPanel with % the SelectedObject property): Change creation function name if strcmp(idList{indCat},'Pa') if isfield(listTemp,'SelectedObject') ctrlFcn = 'uibuttongroup'; end end % Start object creation code % (store all the objects handles in a handles structure) str = sprintf('%s\t\thandles.%s = %s( ...\n',str,listTemp.Tag,ctrlFcn); % Browse the object properties for indProp=1:length(propTemp) % For Parent & UIContextMenu properties, value is an object handle if strcmp(propTemp{indProp},'Parent') || strcmp(propTemp{indProp},'UIContextMenu') if ~isempty(listTemp.(propTemp{indProp})) propVal = sprintf('handles.%s',get(listTemp.(propTemp{indProp}),'Tag')); else propVal = []; end else propVal = listTemp.(propTemp{indProp}); end if ~isfield(dprop,propTemp{indProp}) || ~isequal(propVal,dprop.(propTemp{indProp})) % Create Property/Value string according to the class of the property % value switch class(listTemp.(propTemp{indProp})) case 'char' s = format_char(); case {'double','single','uint8'} s = format_numeric(); case 'cell' s = format_cell(); case 'logical' s = format_logical(); end % end of switch % Write the code line 'Property','Value',... str = sprintf('%s\t\t\t"%s", %s, ...\n',str,propTemp{indProp},s); end % end isequal end % Next property % Callbacks if cb_gen % Extract all property names l = fieldnames(listTemp); % Find defined callback properties [iprop,icb] = find(strcmp(repmat(l,1,length(cb_names)),repmat(cb_names,length(l),1))); %#ok<ASGLU> for indCb=1:length(icb) if ~isempty(listTemp.(cb_names{icb(indCb)})) cb_list{end+1} = [listTemp.Tag '_' cb_names{icb(indCb)}]; %#ok<AGROW> str = sprintf('%s\t\t\t"%s", %s, ...\n',str,cb_names{icb(indCb)},['@' cb_list{end}]); end end end % Suppress the 5 last characters (, ...) and finish the creation command str(end-5:end) = ''; str = sprintf('%s);\n\n',str); end % Next object end % End if ~isempty(hdlsTemp) end % Next object category % Close the build_gui nested function str = sprintf('%s\n\tend\n\n',str); % Add callback functions if cb_gen for indCb=1:length(cb_list) str = sprintf('%s%%%% ---------------------------------------------------------------------------\n',str); str = sprintf('%s\tfunction %s(hObject,evendata) %%#ok<INUSD>\n\n',str,cb_list{indCb}); str = sprintf('%s\tend\n\n',str); end end % Close main function str = sprintf('%send\n',str); % Close the figure close(figHdl); % Write the output file fid = fopen(outFile,'w'); fprintf(fid,'%s',str); fclose(fid); % Open the generated M-File in the editor edit(outFile); % Return the name of the output file varargout{1} = outFile; catch ME varargout{1} = outFile; try %#ok<TRYNC> close(figHdl); end disp(listTemp.Tag); disp(ME.message); end function s = format_cell() % Cell arrays (Create a single string with each cell separated by % a | character) if strcmpi(propTemp{indProp},'ColumnFormat') && all(cellfun(@isempty,propVal)) s = ['{' repmat('''char'' ',size(propVal)) '}']; elseif strcmpi(propTemp{indProp},'ColumnFormat') s = sprintf('"%s",',propVal{:}); s = ['{' strrep(s(1:end-1),'''''','[]') '}']; % Handles the case of automatic column format elseif strcmpi(propTemp{indProp},'ColumnWidth') s = propVal; s(cellfun(@isstr,s)) = cellfun(@(string) ['''' string ''''],s(cellfun(@isstr,s)),'UniformOutput',false); s(cellfun(@isnumeric,s)) = cellfun(@num2str,s(cellfun(@isnumeric,s)),'UniformOutput',false); s = sprintf('%s,',s{:}); s = ['{' s(1:end-1) '}']; elseif strcmpi(propTemp{indProp},'Data') ft = struct('char','"%s",','logical','logical(%d),','double','%f,'); classes = cellfun(@class,propVal(1,:),'UniformOutput',false); s = cellfun(@(s) ft.(s),classes,'UniformOutput',false); fmt = [s{:}]; fmt = [fmt(1:end-1) ';']; propVal = propVal'; s = sprintf(fmt,propVal{:}); s = strrep(s,'logical(0)','false'); s = strrep(s,'logical(1)','true'); s = ['{' s(1:end-1) '}']; else s = sprintf('"%s",',propVal{:}); s = ['{' s(1:end-1) '}']; end end function s = format_numeric() % Numeric (Convert numerical value into string) if syscolorfig && strcmpi(idList{indCat},'Fg') && strcmpi(propTemp{indProp},'Color') % When using the system default background colors then override the % property value s = 'get(0,''DefaultUicontrolBackgroundColor'')'; elseif any(strcmpi(propTemp{indProp},{'BackgroundColor','ForegroundColor','Color'})) % Limit to 3 digits for all colors vectors/matrices s = mat2str(propVal,3); elseif any(strcmpi(propTemp{indProp},{'Parent','UIContextMenu'})) % Simply output the handles.<tag> characters string when the property is % either Parent or UIContextMenu s = sprintf('%s',propVal); else if length(size(propVal)) > 2 matLin = propVal(:); s = sprintf(',%u',size(propVal)); s = sprintf('reshape(%s%s)',mat2str(matLin),s); else s = mat2str(propVal); end end end function s = format_char() % Characters if size(propVal,1) > 1 % For character arrays that have more than 1 line s = 'sprintf('''; for j=1:size(propVal,1) s = sprintf('%s\t\t%s\\n',s,strrep(propVal(j,:),'''','''''')); end s = [s ''')']; elseif ~isempty(findstr(propVal,char(13))) % For character arrays that contain new line character s = sprintf('sprintf("%s")',strrep(strrep(strrep(propVal,char(13),'\n'),char(10),''),'''','''''')); else % For character arrays that have a single line and no new line s = sprintf('"%s"',strrep(propVal,'''','''''')); end end function s = format_logical() % Format logical property values trueFalse = {'false,','true,'}; s = trueFalse(propVal+1); s = [s{:}]; s = ['[' s(1:end-1) ']']; end end %------------------------------------------------------------------------------- function cprop = control_properties() % Common objects properties prop.Def = {'Parent','Tag','UserData','Visible'}; prop.Font = {'FontAngle','FontName','FontSize','FontUnits','FontWeight'}; prop.Color = {'ForegroundColor','BackgroundColor'}; prop.Pos = {'Units','Position'}; prop.Str = {'String','TooltipString'}; % Properties for each style of objects cprop.Fg = [{'Tag'}, prop.Pos, {'Name','MenuBar','NumberTitle','Color','Resize','UIContextMenu'}]; cprop.Cm = [prop.Def]; cprop.Mb = [prop.Def, {'Label','Checked','Enable','ForegroundColor'}]; cprop.Pa = [prop.Def, prop.Pos, prop.Font, prop.Color, {'Title','TitlePosition','BorderType','BorderWidth','HighlightColor','ShadowColor','UIContextMenu'}]; cprop.Ax = [prop.Def, prop.Pos, {'UIContextMenu'}]; cprop.Li = {'BeingDeleted','BusyAction','ButtonDownFcn','Color','CreateFcn','DeleteFcn','DisplayName','EraseMode','HandleVisibility','HitTest','Interruptible','LineStyle','LineWidth','Marker','MarkerEdgeColor','MarkerFaceColor','MarkerSize','Parent','Selected','SelectionHighlight','Tag','UIContextMenu','UserData','Visible','XData','YData','ZData'}; cprop.Sf = {'AlphaData','AlphaDataMapping','CData','CDataMapping','DisplayName','EdgeAlpha','EdgeColor','EraseMode','FaceAlpha','FaceColor','LineStyle','LineWidth','Marker','MarkerEdgeColor','MarkerFaceColor','MarkerSize','MeshStyle','XData','YData','ZData','FaceLighting','EdgeLighting','BackFaceLighting','AmbientStrength','DiffuseStrength','SpecularStrength','SpecularExponent','SpecularColorReflectance','VertexNormals','NormalMode','ButtonDownFcn','Selected','SelectionHighlight','Tag','UIContextMenu','UserData','Visible','Parent','XDataMode','XDataSource','YDataMode','YDataSource','CDataMode','CDataSource','ZDataSource'}; cprop.St = [prop.Def, {'Style'}, prop.Pos, prop.Font, prop.Color, prop.Str, {'Enable','HorizontalAlignment'}]; cprop.Pb = [prop.Def, {'Style'}, prop.Pos, prop.Font, prop.Color, prop.Str, {'Enable','UIContextMenu','CData'}]; cprop.Tb = [prop.Def, {'Style'}, prop.Pos, prop.Font, prop.Color, prop.Str, {'Enable','UIContextMenu','CData'}]; cprop.Rb = [prop.Def, {'Style'}, prop.Pos, prop.Font, prop.Color, prop.Str, {'Enable','UIContextMenu'}]; cprop.Cb = [prop.Def, {'Style'}, prop.Pos, prop.Font, prop.Color, prop.Str, {'Enable','UIContextMenu'}]; cprop.Ed = [prop.Def, {'Style'}, prop.Pos, prop.Font, prop.Color, prop.Str, {'Enable','UIContextMenu','HorizontalAlignment','Min','Max'}]; cprop.Lb = [prop.Def, {'Style'}, prop.Pos, prop.Font, prop.Color, prop.Str, {'Enable','UIContextMenu','Min','Max'}]; cprop.Pu = [prop.Def, {'Style'}, prop.Pos, prop.Font, prop.Color, prop.Str, {'Enable','UIContextMenu'}]; cprop.Sl = [prop.Def, {'Style'}, prop.Pos, prop.Font, prop.Color, prop.Str, {'Enable','UIContextMenu','Min','Max','SliderStep'}]; cprop.Ta = [prop.Def, prop.Pos, prop.Font, prop.Color, {'ColumnEditable','ColumnFormat','ColumnName','ColumnWidth','Data','Enable','RearrangeableColumns','RowName','RowStriping','TooltipString','UIContextMenu'}]; cprop.To = [prop.Def]; cprop.Pt = [prop.Def, {'TooltipString','CData','Enable','Separator'}]; cprop.Tt = [prop.Def, {'TooltipString','CData','Enable','Separator','State'}]; end %------------------------------------------------------------------------------- function dprop = default_prop_values() dprop = struct( ... 'MenuBar' , 'figure', ... 'NumberTitle' , 'on', ... 'Resize' , 'off', ... 'UIContextMenu' , [], ... 'FontAngle' , 'normal', ... 'FontName' , 'MS Sans Serif', ... 'FontSize' , 8, ... 'FontUnits' , 'points', ... 'FontWeight' , 'normal', ... 'ForegroundColor' , [0 0 0], ... 'BackgroundColor' , get(0,'DefaultUicontrolBackgroundColor'), ... 'TitlePosition' , 'lefttop', ... 'BorderType' , 'etchedin', ... 'BorderWidth' , 1, ... 'HighlightColor' , [1 1 1], ... 'ShadowColor' , [0.5 0.5 0.5], ... 'HorizontalAlignment' , 'center', ... 'TooltipString' , '', ... 'CData' , [], ... 'Enable' , 'on', ... 'SliderStep' , [.01 .1], ... 'Min' , 0, ... 'Max' , 1, ... 'UserData' , [], ... 'BeingDeleted' , 'off', ... 'BusyAction' , 'queue', ... 'ColumnEditable' , [], ... 'ColumnFormat' , [], ... 'ColumnName' , 'numbered', ... 'ColumnWidth' , 'auto', ... 'Data' , {cell(4,2)}, ... 'RearrangeableColumns', 'off', ... 'RowName' , 'numbered', ... 'RowStriping' , 'on', ... 'Visible' , 'on', ... 'String' , '', ... 'Separator' , 'off', ... 'State' , 'off'); end
github
HelmchenLabSoftware/OCIA-master
sigstar.m
.m
OCIA-master/utils/plotting/sigstar.m
9,019
utf_8
9e111a96ba442eee144d7eaac47163c8
function varargout=sigstar(groups,stats,nosort,putStarsUnder) % SIGSTAR Add significance stars to bar charts, boxplots, line charts, etc, % % H = SIGSTAR(GROUPS,STATS,NSORT) % % Purpose % Add stars and lines highlighting significant differences between pairs of groups. % The user specifies the groups and associated p-values. The function handles much of % the placement and drawing of the highlighting. Stars are drawn according to: % * represents p<=0.05 % ** represents p<=1E-2 % *** represents p<=1E-3 % % % Inputs % GROUPS - a cell array defining the pairs of groups to compare. Groups defined % either as pairs of scalars indicating locations along the X axis or as % strings corresponding to X-tick labels. Groups can be a mixture of both % definition types. % STATS - a vector of p-values the same length as GROUPS. If empty or missing it's % assumed to be a vector of 0.05s the same length as GROUPS. Nans are treated % as indicating non-significance. % NSORT - optional, 0 by default. If 1, then significance markers are plotted in % the order found in GROUPS. If 0, then they're sorted by the length of the % bar. % % Outputs % H - optionally return handles for significance highlights. Each row is a different % highlight bar. The first column is the line. The second column is the text (stars). % % % Examples % 1. % bar([5,2,1.5]) % sigstar({[1,2], [1,3]}) % % 2. % bar([5,2,1.5]) % sigstar({[2,3],[1,2], [1,3]},[nan,0.05,0.05]) % % 3. % R=randn(30,2); % R(:,1)=R(:,1)+3; % boxplot(R) % set(gca,'XTick',1:2,'XTickLabel',{'A','B'}) % H=sigstar({{'A','B'}},0.01); % ylim([-3,6.5]) % set(H,'color','r') % % 4. Note the difference in the order with which we define the groups in the % following two cases. % x=[1,2,3,2,1]; % subplot(1,2,1) % bar(x) % sigstar({[1,2], [2,3], [4,5]}) % subplot(1,2,2) % bar(x) % sigstar({[2,3],[1,2], [4,5]}) % % ALSO SEE: demo_sigstar % % KNOWN ISSUES: % 1. Algorithm for identifying whether significance bar will overlap with % existing plot elements may not work in some cases (see line 277) % 2. Bars may not look good on exported graphics with small page sizes. % Simply increasing the width and height of the graph with the % PaperPosition property of the current figure should fix things. % % Rob Campbell - CSHL 2013 %Input argument error checking %If the user entered just one group pair and forgot to wrap it in a cell array %then we'll go easy on them and wrap it here rather then generate an error if ~iscell(groups) & length(groups)==2 groups={groups}; end if nargin<2 stats=repmat(0.05,1,length(groups)); end if isempty(stats) stats=repmat(0.05,1,length(groups)); end if nargin<3 nosort=0; end if nargin<4 putStarsUnder=0; end %Check the inputs are of the right sort if ~iscell(groups) error('GROUPS must be a cell array') end if ~isvector(stats) error('STATS must be a vector') end if length(stats)~=length(groups) error('GROUPS and STATS must be the same length') end %Each member of the cell array GROUPS may be one of three things: %1. A pair of indices. %2. A pair of strings (in cell array) referring to X-Tick labels %3. A cell array containing one index and one string % % For our function to run, we will need to convert all of these into pairs of % indices. Here we loop through GROUPS and do this. xlocs=nan(length(groups),2); %matrix that will store the indices xtl=get(gca,'XTickLabel'); for ii=1:length(groups) grp=groups{ii}; if isnumeric(grp) xlocs(ii,:)=grp; %Just store the indices if they're the right format already elseif iscell(grp) %Handle string pairs or string/index pairs if isstr(grp{1}) a=strmatch(grp{1},xtl); elseif isnumeric(grp{1}) a=grp{1}; end if isstr(grp{2}) b=strmatch(grp{2},xtl); elseif isnumeric(grp{2}) b=grp{2}; end xlocs(ii,:)=[a,b]; end %Ensure that the first column is always smaller number than the second xlocs(ii,:)=sort(xlocs(ii,:)); end %If there are any NaNs we have messed up. if any(isnan(xlocs(:))) error('Some groups were not found') end %Optionally sort sig bars from shortest to longest so we plot the shorter ones first %in the loop below. Usually this will result in the neatest plot. If we waned to %optimise the order the sig bars are plotted to produce the neatest plot, then this %is where we'd do it. Not really worth the effort, though, as few plots are complicated %enough to need this and the user can define the order very easily at the command line. if ~nosort [~,ind]=sort(xlocs(:,2)-xlocs(:,1),'ascend'); xlocs=xlocs(ind,:);groups=groups(ind); stats=stats(ind); end %----------------------------------------------------- %Add the sig bar lines and asterisks holdstate=ishold; hold on H=ones(length(groups),2); %The handles will be stored here y=ylim; yd=myRange(y)*0.05; %separate sig bars vertically by 5% for ii=1:length(groups) thisY=findMinY(xlocs(ii,:), putStarsUnder) + iff(putStarsUnder == 1, -1, 1) * yd; H(ii,:)=makeBar(xlocs(ii,:),thisY,stats(ii), putStarsUnder); end %----------------------------------------------------- %Now we can add the little downward ticks on the ends of each line. We are %being extra cautious and leaving this it to the end just in case the y limits %of the graph have changed as we add the highlights. The ticks are set as a %proportion of the y axis range and we want them all to be the same the same %for all bars. yd=myRange(ylim)*0.01; %Ticks are 1% of the y axis range if putStarsUnder; yd = -yd; end; for ii=1:length(groups) y=get(H(ii,1),'YData'); y(1)=y(1)-yd; y(4)=y(4)-yd; set(H(ii,1),'YData',y) end %Be neat and return hold state to whatever it was before we started if ~holdstate hold off elseif holdstate hold on end %Optionally return the handles to the plotted significance bars (first column of H) %and asterisks (second column of H). if nargout>0 varargout{1}=H; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Internal functions function H=makeBar(x,y,p, putStarsUnder) %makeBar produces the bar and defines how many asterisks we get for a %given p-value if p<=1E-3 stars='***'; elseif p<=1E-2 stars='**'; elseif p<=0.05 stars='*'; elseif isnan(p) stars='n.s.'; else stars=''; end x=repmat(x,2,1); y=repmat(y,4,1); H(1)=plot(x(:),y,'-k','LineWidth',1.5); %Increase offset between line and text if we will print "n.s." %instead of a star. if ~isnan(p) offset=0.005; else offset=0.03; end if putStarsUnder; H(2)=text(mean(x(:)),mean(y)-myRange(ylim)*5*offset,stars,... 'HorizontalAlignment','Center',... 'BackGroundColor','none'); else H(2)=text(mean(x(:)),mean(y)+myRange(ylim)*offset,stars,... 'HorizontalAlignment','Center',... 'BackGroundColor','none'); end; function Y=findMinY(x, putStarsUnder) %Find the minimum y value needed to clear all the plotted data present %over a given range of x values. This allows the significance bar to %be plotted in the best location. % %First look for patch objects (bars in a bar-chart, most likely) p=findobj(gca,'Type','Patch'); xd=get(p,'XData'); if iscell(xd) xd=groupedBarFix(xd,'x'); end xd(xd<x(1))=0; xd(xd>x(2))=0; overlapping=any(xd,1); %These x locations overlap %Find the corresponding y values clear xd yd=get(p,'YData'); if iscell(yd) yd=groupedBarFix(yd,'y'); end yd=yd(:,overlapping); %So we must have a value of at least Y in order to miss all the %plotted bar data: if putStarsUnder; Y=min(yd(:)); else Y=max(yd(:)); end; %Now let's check if any other plot elements (such as significance bars we've %already added) exist over this range of x values. % % NOTE! This code doesn't identify all cases where there is overlap. %For example, if you have a significance bar going from 3 to 7 along the x %axis and you then try to add a new one from 4 to 5, then it won't see the %existing one as overlapping. However, I've yet to find this a problem in %practice so I'll leave things be. Can easily be fixed if leads to bugs. p=findobj(gca,'Type','Line'); tmpY=nan(1,length(p)); for ii=1:length(p) xd=get(p(ii),'XData'); xd(xd<x(1))=0; xd(xd>x(2))=0; overlapping=xd>0; %These x locations overlap if ~any(overlapping) continue end clear xd yd=get(p(ii),'YData'); yd=yd(overlapping); if putStarsUnder; tmpY(ii)=min(yd); else tmpY(ii)=max(yd); end; end if putStarsUnder; Y=min([Y,tmpY]); else Y=max([Y,tmpY]); end; %The patch coords of grouped error bars aren't a matrix but a cell array. This needs to be %converted to a suitable matrix in order for the code to work. This function does that. function out=groupedBarFix(in,xy) out=ones([size(in{1}),length(in)]); for ii=1:length(in) out(:,:,ii)=in{ii}; end switch xy case 'x' out=mean(out,3); case 'y' out=max(out,[],3); end %replacement for stats toolbox range function function rng=myRange(x) rng = max(x) - min(x);
github
HelmchenLabSoftware/OCIA-master
barerrorbar.m
.m
OCIA-master/utils/plotting/barerrorbar.m
6,065
utf_8
d18f6c7caa4b5acbe0a3a5d61dc73f31
function varargout = barerrorbar(varargin) % BARERRORBAR Create a bar plot with error bars. BARERRORBAR() uses the % MATLAB functions BAR() and ERRORBAR() and changes the 'XData' property % of the errorbar plot so that the error bars are plotted at the center % of each bar. This does not support "stack" bar plots. % % Syntax: varargout = barerrorbar(varargin) % % Inputs: % Method 1: Cell array method % varargin{1} - A cell array containing all of the inputs to be fed % to bar(). % varargin{2} - A cell array containing all of the inputs to be fed % to errorbar(). % Method 2: Simple Method % varargin{1} - The data to be plotted by bar(). % varargin{2} - The E input to errorbar(). % % Outputs: % varargout{1} - The handle to the bar plot. % varargout{2} - The handle to the errorbar plot. % % Examples: % x = 0.2*randn(3,4,100) + 1; % xMeans = mean(x,3); % xMeansConf = repmat(2*0.2/10,3,4); % xMeansL = repmat(3*0.2/10,3,4); % xMeansU = repmat(4*0.2/10,3,4); % % figure % barerrorbar(xMeans,xMeansConf); % % figure % barerrorbar({3:5,xMeans,'m'}, {repmat((3:5)',1,4),xMeans, xMeansL,xMeansU,'bx'}); % % figure % barerrorbar({3:5,xMeans,'k'}, {repmat((3:5)',1,4),xMeans, xMeansL,xMeansU,'bx'}); % hold on % barerrorbar({7:9,xMeans}, {repmat((7:9)',1,4),xMeans, 2*xMeansL,4*xMeansU,'d','color',[0.7 0.7 0.7]}); % % Other m-files required: none % Subfunctions: interpretinputs % MAT-files required: none % % See also: bar.m errorbar.m % Author: Kenneth D. Morton Jr. and J. Simeon Stohl % Revised by: Kenneth D. Morton Jr. % Duke University, Department of Electrical and Computer Engineering % Email Address: [email protected] % Created: 07-July-2005 % Last revision: 06-January-2006 % Check if hold is on startedWithHoldOn = ishold; [data, barInputs, errorbarInputs] = interpinputs(varargin); % Create the bar plot and keep the handles for later use. barHandles = bar(barInputs{:}); barHandlesStruct = get(barHandles); if ~startedWithHoldOn hold on else % Hold is already on so we need to check the XTick and save them. oldXTicks = get(gca,'XTick'); oldXTickLabels = get(gca,'XTickLabel'); end % Find out the bar width which is dependent on the number of bar sets and % the number of bars in each set. barWidth = barHandlesStruct(1).BarWidth; errorbarHandles = errorbar(errorbarInputs{:}); % The crazy stuff to find the bar centers. Some of it is how bar.m does it. [nGroups, nBarsPerGroup] = size(data); % fix bug if only 1 bar per group - B.Laurenczy 2014-03-21 if nGroups == 1 && nBarsPerGroup > 1; groupMembership = barHandlesStruct(1).XData; else for iBpg = 1:nBarsPerGroup groupMembership(:,iBpg) = barHandlesStruct(iBpg).XData; end end; groupWidth = min(0.8, nBarsPerGroup/(nBarsPerGroup+1.5)); groupLocs = groupMembership(:,1); distanceToNearestGroup = zeros(1,nGroups); if nGroups > 1; for iGroup = 1:nGroups distanceToNearestGroup(iGroup) = ... min(abs(groupLocs(iGroup)-... groupLocs(groupLocs~=groupLocs(iGroup)))); end groupWidth = groupWidth*min(distanceToNearestGroup); barGap = (nGroups - 1) * groupWidth / (nGroups-1) / nBarsPerGroup; almostCenters = (0:nBarsPerGroup-1)'.*barGap - 0.5*barGap*nBarsPerGroup; relativeCenters = almostCenters + mean([(1-barWidth)/2.*barGap; (1+barWidth)/2.*barGap]); centers = repmat(relativeCenters',nGroups,1) + groupMembership; % Change the XData of the errorbars to be at our bar centers. for iBpg = 1:nBarsPerGroup set(errorbarHandles(iBpg),'XData',centers(:,iBpg)); end end; % Turn hold off if it wasn't on to begin with if ~startedWithHoldOn hold off else % Set the XTick and XTickLabels to inlcude the old and new information. newXTicks = groupMembership(:,1); newXTickLabels = num2str(newXTicks); set(gca,'XTick',sort(unique([oldXTicks newXTicks']))); if ischar(oldXTickLabels) % If this is a string then they are probably default so update with % the new additions. set(gca,'XTickLabel',[oldXTickLabels; newXTickLabels]); end end % Prepare both sets of handles as outputs, if requested. if nargout > 0 varargout{1} = barHandles; end if nargout > 1 varargout{2} = errorbarHandles; end % End of barerrorbar() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data, barInputs, errorbarInputs] = interpinputs(inCell) % Interperate the inputs so that they can be used in barerrorbar(). Make % two different possibilities based on the type of inputs. % Method 1: Cell array method. % varargin{1} - A cell array containing all of the inputs to be fed % to bar(). % varargin{2} - A cell array containing all of the inputs to be fed % to errorbar(). % Method 2: Simple Method % varargin{1} - The data to be plotted by bar(). % varargin{2} - The data to be plotted by errorbar(). if iscell(inCell{1}) % We have entered Method 1 barInputs = inCell{1}; if length(barInputs) > 2 data = barInputs{2}; elseif length(barInputs) < 2 data = barInputs{1}; elseif length(barInputs) == 2 if ischar(barInputs{2}) data = barInputs{1}; else data = barInputs{2}; end end else barInputs = {inCell{1}}; data = inCell{1}; nRows = size(barInputs{1},1); if nRows == 1 barInputs{1} = barInputs{1}'; end end %Plot black dot errorbars for the default. if iscell(inCell{2}) errorbarInputs = inCell{2}; else errorbarInputs = {inCell{1}, inCell{2}, 'k.',}; end if length(inCell) > 2 error(['Too many input arguments.' ... ' Try using the cell array input method.']); end % Search for the 'stack' option in the bar inputs for iBI = 1:length(barInputs) if ischar(barInputs{iBI}) if strcmpi(barInputs{iBI},'stack') error('barerrorbar() does not support "stack" bar plots.') end end end
github
HelmchenLabSoftware/OCIA-master
pdftops.m
.m
OCIA-master/utils/plotting/export_fig/pdftops.m
3,574
utf_8
92ff676904575e16046dfff010b4e145
function varargout = pdftops(cmd) %PDFTOPS Calls a local pdftops executable with the input command % % Example: % [status result] = pdftops(cmd) % % Attempts to locate a pdftops executable, finally asking the user to % specify the directory pdftops was installed into. The resulting path is % stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have pdftops (from the Xpdf package) % installed on your system. You can download this from: % http://www.foolabs.com/xpdf % % IN: % cmd - Command string to be passed into pdftops. % % OUT: % status - 0 iff command ran without problem. % result - Output from pdftops. % Copyright: Oliver Woodford, 2009-2010 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on % Mac OS. % Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path % under linux. % 23/01/2014 - Add full path to pdftops.txt in warning. % 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation % Call pdftops [varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd)); end function path_ = xpdf_path % Return a valid path % Start with the currently set path path_ = user_string('pdftops'); % Check the path works if check_xpdf_path(path_) return end % Check whether the binary is on the path if ispc bin = 'pdftops.exe'; else bin = 'pdftops'; end if check_store_xpdf_path(bin) path_ = bin; return end % Search the obvious places if ispc path_ = 'C:\Program Files\xpdf\pdftops.exe'; else path_ = '/usr/local/bin/pdftops'; end if check_store_xpdf_path(path_) return end % Ask the user to enter the path while 1 errMsg = 'Pdftops not found. Please locate the program, or install xpdf-tools from '; url = 'http://foolabs.com/xpdf'; fprintf(2, '%s\n', [errMsg '<a href="matlab:web(''-browser'',''' url ''');">' url '</a>']); errMsg = [errMsg url]; %#ok<AGROW> if strncmp(computer,'MAC',3) % Is a Mac % Give separate warning as the MacOS uigetdir dialogue box doesn't have a title uiwait(warndlg(errMsg)) end base = uigetdir('/', errMsg); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; %#ok<AGROW> bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) path_ = [base bin_dir{a} bin]; if exist(path_, 'file') == 2 break; end end if check_store_xpdf_path(path_) return end end error('pdftops executable not found.'); end function good = check_store_xpdf_path(path_) % Check the path is valid good = check_xpdf_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('pdftops', path_) warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt')); return end end function good = check_xpdf_path(path_) % Check the path is valid [good, message] = system(sprintf('"%s" -h', path_)); %#ok<ASGLU> % system returns good = 1 even when the command runs % Look for something distinct in the help text good = ~isempty(strfind(message, 'PostScript')); end
github
HelmchenLabSoftware/OCIA-master
crop_borders.m
.m
OCIA-master/utils/plotting/export_fig/crop_borders.m
3,666
utf_8
ebb9c61581b6f0d4a2db2fd1d9e30685
function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding) %CROP_BORDERS Crop the borders of an image or stack of images % % [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding]) % %IN: % A - HxWxCxN stack of images. % bcol - Cx1 background colour vector. % padding - scalar indicating how much padding to have in relation to % the cropped-image-size (0<=padding<=1). Default: 0 % %OUT: % B - JxKxCxN cropped stack of images. % vA - coordinates in A that contain the cropped image % vB - coordinates in B where the cropped version of A is placed % bb_rel - relative bounding box (used for eps-cropping) % 06/03/15: Improved image cropping thanks to Oscar Hartogensis % 08/06/15: Fixed issue #76: case of transparent figure bgcolor if nargin < 3 padding = 0; end [h, w, c, n] = size(A); if isempty(bcol) % case of transparent bgcolor bcol = A(ceil(end/2),1,:,1); end if isscalar(bcol) bcol = bcol(ones(c, 1)); end % Crop margin from left bail = false; for l = 1:w for a = 1:c if ~all(col(A(:,l,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop margin from right bcol = A(ceil(end/2),w,:,1); bail = false; for r = w:-1:l for a = 1:c if ~all(col(A(:,r,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop margin from top bcol = A(1,ceil(end/2),:,1); bail = false; for t = 1:h for a = 1:c if ~all(col(A(t,:,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop margin from bottom bcol = A(h,ceil(end/2),:,1); bail = false; for b = h:-1:t for a = 1:c if ~all(col(A(b,:,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop the background, leaving one boundary pixel to avoid bleeding on resize %v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)]; %A = A(v(1):v(2),v(3):v(4),:,:); if padding == 0 % no padding padding = 1; elseif abs(padding) < 1 % pad value is a relative fraction of image size padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING else % pad value is in units of 1/72" points padding = round(padding); % fix cases of non-integer pad value end if padding > 0 % extra padding % Create an empty image, containing the background color, that has the % cropped image size plus the padded border B = repmat(bcol,(b-t)+1+padding*2,(r-l)+1+padding*2); % vA - coordinates in A that contain the cropped image vA = [t b l r]; % vB - coordinates in B where the cropped version of A will be placed vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding]; % Place the original image in the empty image B(vB(1):vB(2), vB(3):vB(4), :) = A(vA(1):vA(2), vA(3):vA(4), :); A = B; else % extra cropping vA = [t-padding b+padding l-padding r+padding]; A = A(vA(1):vA(2), vA(3):vA(4), :); vB = [NaN NaN NaN NaN]; end % For EPS cropping, determine the relative BoundingBox - bb_rel bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h]; end function A = col(A) A = A(:); end
github
HelmchenLabSoftware/OCIA-master
isolate_axes.m
.m
OCIA-master/utils/plotting/export_fig/isolate_axes.m
4,721
utf_8
253cd7b7d8fc7cb00d0cc55926f32de5
function fh = isolate_axes(ah, vis) %ISOLATE_AXES Isolate the specified axes in a figure on their own % % Examples: % fh = isolate_axes(ah) % fh = isolate_axes(ah, vis) % % This function will create a new figure containing the axes/uipanels % specified, and also their associated legends and colorbars. The objects % specified must all be in the same figure, but they will generally only be % a subset of the objects in the figure. % % IN: % ah - An array of axes and uipanel handles, which must come from the % same figure. % vis - A boolean indicating whether the new figure should be visible. % Default: false. % % OUT: % fh - The handle of the created figure. % Copyright (C) Oliver Woodford 2011-2013 % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs % 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio % for pointing out that the function is also used in export_fig.m % 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it % 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!) % 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting % 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro % on FEX page as a comment on 24-Apr-2014); standardized indentation & help section % 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2 % Make sure we have an array of handles if ~all(ishandle(ah)) error('ah must be an array of handles'); end % Check that the handles are all for axes or uipanels, and are all in the same figure fh = ancestor(ah(1), 'figure'); nAx = numel(ah); for a = 1:nAx if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'}) error('All handles must be axes or uipanel handles.'); end if ~isequal(ancestor(ah(a), 'figure'), fh) error('Axes must all come from the same figure.'); end end % Tag the objects so we can find them in the copy old_tag = get(ah, 'Tag'); if nAx == 1 old_tag = {old_tag}; end set(ah, 'Tag', 'ObjectToCopy'); % Create a new figure exactly the same as the old one fh = copyfig(fh); %copyobj(fh, 0); if nargin < 2 || ~vis set(fh, 'Visible', 'off'); end % Reset the object tags for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Find the objects to save ah = findall(fh, 'Tag', 'ObjectToCopy'); if numel(ah) ~= nAx close(fh); error('Incorrect number of objects found.'); end % Set the axes tags to what they should be for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Keep any legends and colorbars which overlap the subplots % Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we % don't test for the type, only the tag (hopefully nobody but Matlab uses them!) lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar'); nLeg = numel(lh); if nLeg > 0 set([ah(:); lh(:)], 'Units', 'normalized'); try ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property catch ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition end if nAx > 1 ax_pos = cell2mat(ax_pos(:)); end ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2); try leg_pos = get(lh, 'OuterPosition'); catch leg_pos = get(lh, 'Position'); % No OuterPosition in HG2, only in HG1 end if nLeg > 1; leg_pos = cell2mat(leg_pos); end leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2); ax_pos = shiftdim(ax_pos, -1); % Overlap test M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ... bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ... bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ... bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2)); ah = [ah; lh(any(M, 2))]; end % Get all the objects in the figure axs = findall(fh); % Delete everything except for the input objects and associated items delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)]))); end function ah = allchildren(ah) ah = findall(ah); if iscell(ah) ah = cell2mat(ah); end ah = ah(:); end function ph = allancestors(ah) ph = []; for a = 1:numel(ah) h = get(ah(a), 'parent'); while h ~= 0 ph = [ph; h]; h = get(h, 'parent'); end end end
github
HelmchenLabSoftware/OCIA-master
im2gif.m
.m
OCIA-master/utils/plotting/export_fig/im2gif.m
6,048
utf_8
5a7437140f8d013158a195de1e372737
%IM2GIF Convert a multiframe image to an animated GIF file % % Examples: % im2gif infile % im2gif infile outfile % im2gif(A, outfile) % im2gif(..., '-nocrop') % im2gif(..., '-nodither') % im2gif(..., '-ncolors', n) % im2gif(..., '-loops', n) % im2gif(..., '-delay', n) % % This function converts a multiframe image to an animated GIF. % % To create an animation from a series of figures, export to a multiframe % TIFF file using export_fig, then convert to a GIF, as follows: % % for a = 2 .^ (3:6) % peaks(a); % export_fig test.tif -nocrop -append % end % im2gif('test.tif', '-delay', 0.5); % %IN: % infile - string containing the name of the input image. % outfile - string containing the name of the output image (must have the % .gif extension). Default: infile, with .gif extension. % A - HxWxCxN array of input images, stacked along fourth dimension, to % be converted to gif. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -nodither - option indicating that dithering is not to be used when % converting the image. % -ncolors - option pair, the value of which indicates the maximum number % of colors the GIF can have. This can also be a quantization % tolerance, between 0 and 1. Default/maximum: 256. % -loops - option pair, the value of which gives the number of times the % animation is to be looped. Default: 65535. % -delay - option pair, the value of which gives the time, in seconds, % between frames. Default: 1/15. % Copyright (C) Oliver Woodford 2011 function im2gif(A, varargin) % Parse the input arguments [A, options] = parse_args(A, varargin{:}); if options.crop ~= 0 % Crop A = crop_borders(A, A(ceil(end/2),1,:,1)); end % Convert to indexed image [h, w, c, n] = size(A); A = reshape(permute(A, [1 2 4 3]), h, w*n, c); map = unique(reshape(A, h*w*n, c), 'rows'); if size(map, 1) > 256 dither_str = {'dither', 'nodither'}; dither_str = dither_str{1+(options.dither==0)}; if options.ncolors <= 1 [B, map] = rgb2ind(A, options.ncolors, dither_str); if size(map, 1) > 256 [B, map] = rgb2ind(A, 256, dither_str); end else [B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str); end else if max(map(:)) > 1 map = double(map) / 255; A = double(A) / 255; end B = rgb2ind(im2double(A), map); end B = reshape(B, h, w, 1, n); % Bug fix to rgb2ind map(B(1)+1,:) = im2double(A(1,1,:)); % Save as a gif imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay); end %% Parse the input arguments function [A, options] = parse_args(A, varargin) % Set the defaults options = struct('outfile', '', ... 'dither', true, ... 'crop', true, ... 'ncolors', 256, ... 'loops', 65535, ... 'delay', 1/15); % Go through the arguments a = 0; n = numel(varargin); while a < n a = a + 1; if ischar(varargin{a}) && ~isempty(varargin{a}) if varargin{a}(1) == '-' opt = lower(varargin{a}(2:end)); switch opt case 'nocrop' options.crop = false; case 'nodither' options.dither = false; otherwise if ~isfield(options, opt) error('Option %s not recognized', varargin{a}); end a = a + 1; if ischar(varargin{a}) && ~ischar(options.(opt)) options.(opt) = str2double(varargin{a}); else options.(opt) = varargin{a}; end end else options.outfile = varargin{a}; end end end if isempty(options.outfile) if ~ischar(A) error('No output filename given.'); end % Generate the output filename from the input filename [path, outfile] = fileparts(A); options.outfile = fullfile(path, [outfile '.gif']); end if ischar(A) % Read in the image A = imread_rgb(A); end end %% Read image to uint8 rgb array function [A, alpha] = imread_rgb(name) % Get file info info = imfinfo(name); % Special case formats switch lower(info(1).Format) case 'gif' [A, map] = imread(name, 'frames', 'all'); if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 A = permute(A, [1 2 5 4 3]); end case {'tif', 'tiff'} A = cell(numel(info), 1); for a = 1:numel(A) [A{a}, map] = imread(name, 'Index', a, 'Info', info); if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 end if size(A{a}, 3) == 4 % TIFF in CMYK colourspace - convert to RGB if isfloat(A{a}) A{a} = A{a} * 255; else A{a} = single(A{a}); end A{a} = 255 - A{a}; A{a}(:,:,4) = A{a}(:,:,4) / 255; A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4])); end end A = cat(4, A{:}); otherwise [A, map, alpha] = imread(name); A = A(:,:,:,1); % Keep only first frame of multi-frame files if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 elseif size(A, 3) == 4 % Assume 4th channel is an alpha matte alpha = A(:,:,4); A = A(:,:,1:3); end end end
github
HelmchenLabSoftware/OCIA-master
read_write_entire_textfile.m
.m
OCIA-master/utils/plotting/export_fig/read_write_entire_textfile.m
924
utf_8
779e56972f5d9778c40dee98ddbd677e
%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory % % Read or write an entire text file to/from memory, without leaving the % file open if an error occurs. % % Reading: % fstrm = read_write_entire_textfile(fname) % Writing: % read_write_entire_textfile(fname, fstrm) % %IN: % fname - Pathname of text file to be read in. % fstrm - String to be written to the file, including carriage returns. % %OUT: % fstrm - String read from the file. If an fstrm input is given the % output is the same as that input. function fstrm = read_write_entire_textfile(fname, fstrm) modes = {'rt', 'wt'}; writing = nargin > 1; fh = fopen(fname, modes{1+writing}); if fh == -1 error('Unable to open file %s.', fname); end try if writing fwrite(fh, fstrm, 'char*1'); else fstrm = fread(fh, '*char')'; end catch ex fclose(fh); rethrow(ex); end fclose(fh); end
github
HelmchenLabSoftware/OCIA-master
pdf2eps.m
.m
OCIA-master/utils/plotting/export_fig/pdf2eps.m
1,471
utf_8
a1f41f0c7713c73886a2323e53ed982b
%PDF2EPS Convert a pdf file to eps format using pdftops % % Examples: % pdf2eps source dest % % This function converts a pdf file to eps format. % % This function requires that you have pdftops, from the Xpdf suite of % functions, installed on your system. This can be downloaded from: % http://www.foolabs.com/xpdf % %IN: % source - filename of the source pdf file to convert. The filename is % assumed to already have the extension ".pdf". % dest - filename of the destination eps file. The filename is assumed to % already have the extension ".eps". % Copyright (C) Oliver Woodford 2009-2010 % Thanks to Aldebaro Klautau for reporting a bug when saving to % non-existant directories. function pdf2eps(source, dest) % Construct the options string for pdftops options = ['-q -paper match -eps -level2 "' source '" "' dest '"']; % Convert to eps using pdftops [status, message] = pdftops(options); % Check for error if status % Report error if isempty(message) error('Unable to generate eps. Check destination directory is writable.'); else error(message); end end % Fix the DSC error created by pdftops fid = fopen(dest, 'r+'); if fid == -1 % Cannot open the file return end fgetl(fid); % Get the first line str = fgetl(fid); % Get the second line if strcmp(str(1:min(13, end)), '% Produced by') fseek(fid, -numel(str)-1, 'cof'); fwrite(fid, '%'); % Turn ' ' into '%' end fclose(fid); end
github
HelmchenLabSoftware/OCIA-master
print2array.m
.m
OCIA-master/utils/plotting/export_fig/print2array.m
9,369
utf_8
ca18a1e6c5a944b591a0557bd69f1c2c
function [A, bcol] = print2array(fig, res, renderer, gs_options) %PRINT2ARRAY Exports a figure to an image array % % Examples: % A = print2array % A = print2array(figure_handle) % A = print2array(figure_handle, resolution) % A = print2array(figure_handle, resolution, renderer) % A = print2array(figure_handle, resolution, renderer, gs_options) % [A bcol] = print2array(...) % % This function outputs a bitmap image of the given figure, at the desired % resolution. % % If renderer is '-painters' then ghostcript needs to be installed. This % can be downloaded from: http://www.ghostscript.com % % IN: % figure_handle - The handle of the figure to be exported. Default: gcf. % resolution - Resolution of the output, as a factor of screen % resolution. Default: 1. % renderer - string containing the renderer paramater to be passed to % print. Default: '-opengl'. % gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If % multiple options are needed, enclose in call array: {'-a','-b'} % % OUT: % A - MxNx3 uint8 image of the figure. % bcol - 1x3 uint8 vector of the background color % Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015- %{ % 05/09/11: Set EraseModes to normal when using opengl or zbuffer % renderers. Thanks to Pawel Kocieniewski for reporting the issue. % 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it. % 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size % and erasemode settings. Makes it a bit slower, but more reliable. % Thanks to Phil Trinh and Meelis Lootus for reporting the issues. % 09/12/11: Pass font path to ghostscript. % 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to % Ken Campbell for reporting it. % 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it. % 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for % reporting the issue. % 26/02/15: If temp dir is not writable, use the current folder for temp % EPS/TIF files (Javier Paredes) % 27/02/15: Display suggested workarounds to internal print() error (issue #16) % 28/02/15: Enable users to specify optional ghostscript options (issue #36) % 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation % 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func) % 07/07/15: Fixed issue #83: use numeric handles in HG1 %} % Generate default input arguments, if needed if nargin < 2 res = 1; if nargin < 1 fig = gcf; end end % Warn if output is large old_mode = get(fig, 'Units'); set(fig, 'Units', 'pixels'); px = get(fig, 'Position'); set(fig, 'Units', old_mode); npx = prod(px(3:4)*res)/1e6; if npx > 30 % 30M pixels or larger! warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx); end % Retrieve the background colour bcol = get(fig, 'Color'); % Set the resolution parameter res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))]; % Generate temporary file name tmp_nam = [tempname '.tif']; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(tmp_nam,'w'); fwrite(fid,1); fclose(fid); delete(tmp_nam); % cleanup isTempDirOk = true; catch % Temp dir is not writable, so use the current folder [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU> fpath = pwd; tmp_nam = fullfile(fpath,[fname fext]); isTempDirOk = false; end % Enable users to specify optional ghostscript options (issue #36) if nargin > 3 && ~isempty(gs_options) if iscell(gs_options) gs_options = sprintf(' %s',gs_options{:}); elseif ~ischar(gs_options) error('gs_options input argument must be a string or cell-array of strings'); else gs_options = [' ' gs_options]; end else gs_options = ''; end if nargin > 2 && strcmp(renderer, '-painters') % Print to eps file if isTempDirOk tmp_eps = [tempname '.eps']; else tmp_eps = fullfile(fpath,[fname '.eps']); end print2eps(tmp_eps, fig, 0, renderer, '-loose'); try % Initialize the command to export to tiff using ghostscript cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc']; % Set the font path fp = font_path(); if ~isempty(fp) cmd_str = [cmd_str ' -sFONTPATH="' fp '"']; end % Add the filenames cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options]; % Execute the ghostscript command ghostscript(cmd_str); catch me % Delete the intermediate file delete(tmp_eps); rethrow(me); end % Delete the intermediate file delete(tmp_eps); % Read in the generated bitmap A = imread(tmp_nam); % Delete the temporary bitmap file delete(tmp_nam); % Set border pixels to the correct colour if isequal(bcol, 'none') bcol = []; elseif isequal(bcol, [1 1 1]) bcol = uint8([255 255 255]); else for l = 1:size(A, 2) if ~all(reshape(A(:,l,:) == 255, [], 1)) break; end end for r = size(A, 2):-1:l if ~all(reshape(A(:,r,:) == 255, [], 1)) break; end end for t = 1:size(A, 1) if ~all(reshape(A(t,:,:) == 255, [], 1)) break; end end for b = size(A, 1):-1:t if ~all(reshape(A(b,:,:) == 255, [], 1)) break; end end bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1)); for c = 1:size(A, 3) A(:,[1:l-1, r+1:end],c) = bcol(c); A([1:t-1, b+1:end],:,c) = bcol(c); end end else if nargin < 3 renderer = '-opengl'; end err = false; % Set paper size old_pos_mode = get(fig, 'PaperPositionMode'); old_orientation = get(fig, 'PaperOrientation'); set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait'); try % Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function) fp = []; % in case we get an error below fp = findall(fig, 'Type','patch', 'LineWidth',0.75); set(fp, 'LineWidth',0.5); % Fix issue #83: use numeric handles in HG1 if ~using_hg2(fig), fig = double(fig); end % Print to tiff file print(fig, renderer, res_str, '-dtiff', tmp_nam); % Read in the printed file A = imread(tmp_nam); % Delete the temporary file delete(tmp_nam); catch ex err = true; end set(fp, 'LineWidth',0.75); % restore original figure appearance % Reset paper size set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation); % Throw any error that occurred if err % Display suggested workarounds to internal print() error (issue #16) fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n'); rethrow(ex); end % Set the background color if isequal(bcol, 'none') bcol = []; else bcol = bcol * 255; if isequal(bcol, round(bcol)) bcol = uint8(bcol); else bcol = squeeze(A(1,1,:)); end end end % Check the output size is correct if isequal(res, round(res)) px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below if ~isequal(size(A), px) % Correct the output size A = A(1:min(end,px(1)),1:min(end,px(2)),:); end end end % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); end
github
HelmchenLabSoftware/OCIA-master
append_pdfs.m
.m
OCIA-master/utils/plotting/export_fig/append_pdfs.m
2,678
utf_8
949c7c4ec3f5af6ff23099f17b1dfd79
%APPEND_PDFS Appends/concatenates multiple PDF files % % Example: % append_pdfs(output, input1, input2, ...) % append_pdfs(output, input_list{:}) % append_pdfs test.pdf temp1.pdf temp2.pdf % % This function appends multiple PDF files to an existing PDF file, or % concatenates them into a PDF file if the output file doesn't yet exist. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % % IN: % output - string of output file name (including the extension, .pdf). % If it exists it is appended to; if not, it is created. % input1 - string of an input file name (including the extension, .pdf). % All input files are appended in order. % input_list - cell array list of input file name strings. All input % files are appended in order. % Copyright: Oliver Woodford, 2011 % Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in % one go is much faster than appending them one at a time. % Thanks to Michael Teo for reporting the issue of a too long command line. % Issue resolved on 5/5/2011, by passing gs a command file. % Thanks to Martin Wittmann for pointing out the quality issue when % appending multiple bitmaps. % Issue resolved (to best of my ability) 1/6/2011, using the prepress % setting % 26/02/15: If temp dir is not writable, use the output folder for temp % files when appending (Javier Paredes); sanity check of inputs function append_pdfs(varargin) if nargin < 2, return; end % sanity check % Are we appending or creating a new file append = exist(varargin{1}, 'file') == 2; output = [tempname '.pdf']; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(output,'w'); fwrite(fid,1); fclose(fid); delete(output); isTempDirOk = true; catch % Temp dir is not writable, so use the output folder [dummy,fname,fext] = fileparts(output); %#ok<ASGLU> fpath = fileparts(varargin{1}); output = fullfile(fpath,[fname fext]); isTempDirOk = false; end if ~append output = varargin{1}; varargin = varargin(2:end); end % Create the command file if isTempDirOk cmdfile = [tempname '.txt']; else cmdfile = fullfile(fpath,[fname '.txt']); end fh = fopen(cmdfile, 'w'); fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output); fprintf(fh, ' "%s"', varargin{:}); fclose(fh); % Call ghostscript ghostscript(['@"' cmdfile '"']); % Delete the command file delete(cmdfile); % Rename the file if needed if append movefile(output, varargin{1}); end end
github
HelmchenLabSoftware/OCIA-master
using_hg2.m
.m
OCIA-master/utils/plotting/export_fig/using_hg2.m
1,002
utf_8
b1620dd31f4d0b8acea2723e354a3518
%USING_HG2 Determine if the HG2 graphics engine is used % % tf = using_hg2(fig) % %IN: % fig - handle to the figure in question. % %OUT: % tf - boolean indicating whether the HG2 graphics engine is being used % (true) or not (false). % 19/06/2015 - Suppress warning in R2015b; cache result for improved performance function tf = using_hg2(fig) persistent tf_cached if isempty(tf_cached) try if nargin < 1, fig = figure('visible','off'); end oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval'); try % This generates a [supressed] warning in R2015b: tf = ~graphicsversion(fig, 'handlegraphics'); catch tf = verLessThan('matlab','8.4'); % =R2014b end warning(oldWarn); catch tf = false; end if nargin < 1, delete(fig); end tf_cached = tf; else tf = tf_cached; end end
github
HelmchenLabSoftware/OCIA-master
eps2pdf.m
.m
OCIA-master/utils/plotting/export_fig/eps2pdf.m
8,355
utf_8
3b82818a1bc7c7e39c8491ce325b2235
function eps2pdf(source, dest, crop, append, gray, quality, gs_options) %EPS2PDF Convert an eps file to pdf format using ghostscript % % Examples: % eps2pdf source dest % eps2pdf(source, dest, crop) % eps2pdf(source, dest, crop, append) % eps2pdf(source, dest, crop, append, gray) % eps2pdf(source, dest, crop, append, gray, quality) % eps2pdf(source, dest, crop, append, gray, quality, gs_options) % % This function converts an eps file to pdf format. The output can be % optionally cropped and also converted to grayscale. If the output pdf % file already exists then the eps file can optionally be appended as a new % page on the end of the eps file. The level of bitmap compression can also % optionally be set. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % % Inputs: % source - filename of the source eps file to convert. The filename is % assumed to already have the extension ".eps". % dest - filename of the destination pdf file. The filename is assumed % to already have the extension ".pdf". % crop - boolean indicating whether to crop the borders off the pdf. % Default: true. % append - boolean indicating whether the eps should be appended to the % end of the pdf as a new page (if the pdf exists already). % Default: false. % gray - boolean indicating whether the output pdf should be grayscale % or not. Default: false. % quality - scalar indicating the level of image bitmap quality to % output. A larger value gives a higher quality. quality > 100 % gives lossless output. Default: ghostscript prepress default. % gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If % multiple options are needed, enclose in call array: {'-a','-b'} % Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015- % Suggestion of appending pdf files provided by Matt C at: % http://www.mathworks.com/matlabcentral/fileexchange/23629 % Thank you to Fabio Viola for pointing out compression artifacts, leading % to the quality setting. % Thank you to Scott for pointing out the subsampling of very small images, % which was fixed for lossless compression settings. % 9/12/2011 Pass font path to ghostscript. % 26/02/15: If temp dir is not writable, use the dest folder for temp % destination files (Javier Paredes) % 28/02/15: Enable users to specify optional ghostscript options (issue #36) % 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve % some /findfont errors according to James Rankin, FEX Comment 23/01/15) % 23/06/15: Added extra debug info in case of ghostscript error; code indentation % 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova) % Intialise the options string for ghostscript options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"']; % Set crop option if nargin < 3 || crop options = [options ' -dEPSCrop']; end % Set the font path fp = font_path(); if ~isempty(fp) options = [options ' -sFONTPATH="' fp '"']; end % Set the grayscale option if nargin > 4 && gray options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray']; end % Set the bitmap quality if nargin > 5 && ~isempty(quality) options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false']; if quality > 100 options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"']; else options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode']; v = 1 + (quality < 80); quality = 1 - quality / 100; s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v); options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s); end end % Enable users to specify optional ghostscript options (issue #36) if nargin > 6 && ~isempty(gs_options) if iscell(gs_options) gs_options = sprintf(' %s',gs_options{:}); elseif ~ischar(gs_options) error('gs_options input argument must be a string or cell-array of strings'); else gs_options = [' ' gs_options]; end options = [options gs_options]; end % Check if the output file exists if nargin > 3 && append && exist(dest, 'file') == 2 % File exists - append current figure to the end tmp_nam = tempname; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(tmp_nam,'w'); fwrite(fid,1); fclose(fid); delete(tmp_nam); catch % Temp dir is not writable, so use the dest folder [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU> fpath = fileparts(dest); tmp_nam = fullfile(fpath,[fname fext]); end % Copy the file copyfile(dest, tmp_nam); % Add the output file names options = [options ' -f "' tmp_nam '" "' source '"']; try % Convert to pdf using ghostscript [status, message] = ghostscript(options); catch me % Delete the intermediate file delete(tmp_nam); rethrow(me); end % Delete the intermediate file delete(tmp_nam); else % File doesn't exist or should be over-written % Add the output file names options = [options ' -f "' source '"']; % Convert to pdf using ghostscript [status, message] = ghostscript(options); end % Check for error if status % Retry without the -sFONTPATH= option (this might solve some GS % /findfont errors according to James Rankin, FEX Comment 23/01/15) orig_options = options; if ~isempty(fp) options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' '); status = ghostscript(options); if ~status, return; end % hurray! (no error) end % Report error if isempty(message) error('Unable to generate pdf. Check destination directory is writable.'); elseif ~isempty(strfind(message,'/typecheck in /findfont')) % Suggest a workaround for issue #41 (missing font path) font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1')); fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name); fpath = fileparts(mfilename(-fullpath')); gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt'); fprintf(2, ' try to add the font''s folder to your %s file\n\n', gs_fonts_file); error('export_fig error'); else fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest); if ~isempty(gs_options) fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\n', gs_options); end fprintf(2, 'Ghostscript options: %s\n\n', orig_options); error(message); end end end % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); end
github
HelmchenLabSoftware/OCIA-master
ghostscript.m
.m
OCIA-master/utils/plotting/export_fig/ghostscript.m
7,706
utf_8
92dbafb8d4fb243cae8716c6ecb0bbe5
function varargout = ghostscript(cmd) %GHOSTSCRIPT Calls a local GhostScript executable with the input command % % Example: % [status result] = ghostscript(cmd) % % Attempts to locate a ghostscript executable, finally asking the user to % specify the directory ghostcript was installed into. The resulting path % is stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have Ghostscript installed on your % system. You can download this from: http://www.ghostscript.com % % IN: % cmd - Command string to be passed into ghostscript. % % OUT: % status - 0 iff command ran without problem. % result - Output from ghostscript. % Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015- %{ % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS. % Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems. % 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and % Shaun Kline for pointing out the issue % 04/05/11 - Thanks to David Chorlian for pointing out an alternative % location for gs on linux. % 12/12/12 - Add extra executable name on Windows. Thanks to Ratish % Punnoose for highlighting the issue. % 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick % Steinbring for proposing the fix. % 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes % for the fix. % 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen % Vermeer for raising the issue. % 27/02/15 - If Ghostscript croaks, display suggested workarounds % 30/03/15 - Improved performance by caching status of GS path check, if ok % 14/05/15 - Clarified warning message in case GS path could not be saved % 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74) % 10/11/15 - Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX %} try % Call ghostscript [varargout{1:nargout}] = system([gs_command(gs_path()) cmd]); catch err % Display possible workarounds for Ghostscript croaks url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998'; % issue #12 url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270'; % issue #20 hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\n * <a href="%s">%s</a> ',hg2_str,url1,url1); if using_hg2 fprintf(2, '(GS 9.10)\n * <a href="%s">%s</a> (R2014a)',url2,url2); end fprintf('\n\n'); if ismac || isunix url3 = 'https://github.com/altmany/export_fig/issues/27'; % issue #27 fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\n * <a href="%s">%s</a>\n\n',url3,url3); % issue #20 fpath = which(mfilename); if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export..." to "setenv ..."\nat the bottom of <a href="matlab:opentoline(''%s'',174)">%s</a>\n\n',fpath,fpath); end rethrow(err); end end function path_ = gs_path % Return a valid path % Start with the currently set path path_ = user_string('ghostscript'); % Check the path works if check_gs_path(path_) return end % Check whether the binary is on the path if ispc bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'}; else bin = {'gs'}; end for a = 1:numel(bin) path_ = bin{a}; if check_store_gs_path(path_) return end end % Search the obvious places if ispc default_location = 'C:\Program Files\gs\'; dir_list = dir(default_location); if isempty(dir_list) default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems dir_list = dir(default_location); end executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'}; ver_num = 0; % If there are multiple versions, use the newest for a = 1:numel(dir_list) ver_num2 = sscanf(dir_list(a).name, 'gs%g'); if ~isempty(ver_num2) && ver_num2 > ver_num for b = 1:numel(executable) path2 = [default_location dir_list(a).name executable{b}]; if exist(path2, 'file') == 2 path_ = path2; ver_num = ver_num2; end end end end if check_store_gs_path(path_) return end else executable = {'/usr/bin/gs', '/usr/local/bin/gs'}; for a = 1:numel(executable) path_ = executable{a}; if check_store_gs_path(path_) return end end end % Ask the user to enter the path while true if strncmp(computer, 'MAC', 3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Ghostscript not found. Please locate the program.')) end base = uigetdir('/', 'Ghostcript not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; %#ok<AGROW> bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) for b = 1:numel(bin) path_ = [base bin_dir{a} bin{b}]; if exist(path_, 'file') == 2 if check_store_gs_path(path_) return end end end end end if ismac error('Ghostscript not found. Have you installed it (http://pages.uoregon.edu/koch)?'); else error('Ghostscript not found. Have you installed it from www.ghostscript.com?'); end end function good = check_store_gs_path(path_) % Check the path is valid good = check_gs_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('ghostscript', path_) filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt'); warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_); return end end function good = check_gs_path(path_) persistent isOk if isempty(path_) isOk = false; elseif ~isequal(isOk,true) % Check whether the path is valid [status, message] = system([gs_command(path_) '-h']); %#ok<ASGLU> isOk = status == 0; end good = isOk; end function cmd = gs_command(path_) % Initialize any required system calls before calling ghostscript % TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh) shell_cmd = ''; if isunix shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07 end if ismac shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07 end % Construct the command string cmd = sprintf('%s"%s" ', shell_cmd, path_); end
github
HelmchenLabSoftware/OCIA-master
fix_lines.m
.m
OCIA-master/utils/plotting/export_fig/fix_lines.m
6,290
utf_8
8437006b104957762090e3d875688cb6
%FIX_LINES Improves the line style of eps files generated by print % % Examples: % fix_lines fname % fix_lines fname fname2 % fstrm_out = fixlines(fstrm_in) % % This function improves the style of lines in eps files generated by % MATLAB's print function, making them more similar to those seen on % screen. Grid lines are also changed from a dashed style to a dotted % style, for greater differentiation from dashed lines. % % The function also places embedded fonts after the postscript header, in % versions of MATLAB which place the fonts first (R2006b and earlier), in % order to allow programs such as Ghostscript to find the bounding box % information. % %IN: % fname - Name or path of source eps file. % fname2 - Name or path of destination eps file. Default: same as fname. % fstrm_in - File contents of a MATLAB-generated eps file. % %OUT: % fstrm_out - Contents of the eps file with line styles fixed. % Copyright: (C) Oliver Woodford, 2008-2014 % The idea of editing the EPS file to change line styles comes from Jiro % Doke's FIXPSLINESTYLE (fex id: 17928) % The idea of changing dash length with line width came from comments on % fex id: 5743, but the implementation is mine :) % Thank you to Sylvain Favrot for bringing the embedded font/bounding box % interaction in older versions of MATLAB to my attention. % Thank you to D Ko for bringing an error with eps files with tiff previews % to my attention. % Thank you to Laurence K for suggesting the check to see if the file was % opened. % 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+) % 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39 function fstrm = fix_lines(fstrm, fname2) % Issue #20: warn users if using this function in HG2 (R2014b+) if using_hg2 warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.'); end if nargout == 0 || nargin > 1 if nargin < 2 % Overwrite the input file fname2 = fstrm; end % Read in the file fstrm = read_write_entire_textfile(fstrm); end % Move any embedded fonts after the postscript header if strcmp(fstrm(1:15), '%!PS-AdobeFont-') % Find the start and end of the header ind = regexp(fstrm, '[\n\r]%!PS-Adobe-'); [ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+'); % Put the header first if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1) fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]); end end % Make sure all line width commands come before the line style definitions, % so that dash lengths can be based on the correct widths % Find all line style sections ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes! regexp(fstrm, '[\n\r]DO[\n\r]'),... regexp(fstrm, '[\n\r]DA[\n\r]'),... regexp(fstrm, '[\n\r]DD[\n\r]')]; ind = sort(ind); % Find line width commands [ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]'); % Go through each line style section and swap with any line width commands % near by b = 1; m = numel(ind); n = numel(ind2); for a = 1:m % Go forwards width commands until we pass the current line style while b <= n && ind2(b) < ind(a) b = b + 1; end if b > n % No more width commands break; end % Check we haven't gone past another line style (including SO!) if a < m && ind2(b) > ind(a+1) continue; end % Are the commands close enough to be confident we can swap them? if (ind2(b) - ind(a)) > 8 continue; end % Move the line style command below the line width command fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)]; b = b + 1; end % Find any grid line definitions and change to GR format % Find the DO sections again as they may have moved ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]')); if ~isempty(ind) % Find all occurrences of what are believed to be axes and grid lines ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]')); if ~isempty(ind2) % Now see which DO sections come just before axes and grid lines ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]); ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right ind = ind(ind2); % Change any regions we believe to be grid lines to GR fstrm(ind+1) = 'G'; fstrm(ind+2) = 'R'; end end % Define the new styles, including the new GR format % Dot and dash lengths have two parts: a constant amount plus a line width % variable amount. The constant amount comes after dpi2point, and the % variable amount comes after currentlinewidth. If you want to change % dot/dash lengths for a one particular line style only, edit the numbers % in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and % /GR (grid lines) lines for the style you want to change. new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width '/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width '/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines '/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines '/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines '/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines '/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant % Construct the output % This is the original (memory-intensive) code: %first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section %[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/'); %[remaining, remaining] = strtok(remaining, '%'); %fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining]; fstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\r',new_style{:}),'%']); % Write the output file if nargout == 0 || nargin > 1 read_write_entire_textfile(fname2, fstrm); end end
github
HelmchenLabSoftware/OCIA-master
notBoxPlot.m
.m
OCIA-master/utils/plotting/notBoxPlot/notBoxPlot.m
6,618
utf_8
bce98cc92bdab9639cc0a40da6e039e3
function varargout=notBoxPlot(y,x,jitter,style) % notBoxPlot - Doesn't plot box plots! % % function notBoxPlot(y,x,jitter,style) % % % Purpose % An alternative to a box plot, where the focus is on showing raw % data. Plots columns of y as different groups located at points % along the x axis defined by the optional vector x. Points are % layed over a 1.96 SEM (95% confidence interval) in red and a 1 SD % in blue. The user has the option of plotting the SEM and SD as a % line rather than area. Raw data are jittered along x for clarity. This % function is suited to displaying data which are normally distributed. % Since, for instance, the SEM is meaningless if the data are bimodally % distributed. % % % Inputs % y - each column of y is one variable/group. If x is missing or empty % then each column is plotted in a different x position. % % x - optional, x axis points at which y columns should be % plotted. This allows more than one set of y values to appear % at one x location. Such instances are coloured differently. % Note that if x and y are both vectors of the same length this function % behaves like boxplot (see Example 5). % % jitter - how much to jitter the data for visualization % (optional). The width of the boxes are automatically % scaled to the jitter magnitude. % % style - a string defining plot style of the data. % 'patch' [default] - plots SEM and SD as a box using patch % objects. % 'line' - create a plot where the SD and SEM are % constructed from lines. % 'sdline' - a hybrid of the above, in which only the SD is % replaced with a line. % % % Outputs % H - structure of handles for plot objects. % % % Example 1 - simple example % clf % subplot(2,1,1) % notBoxPlot(randn(20,5)); % subplot(2,1,2) % h=notBoxPlot(randn(10,40)); % d=[h.data]; % set(d(1:4:end),'markerfacecolor',[0.4,1,0.4],'color',[0,0.4,0]) % % Example 2 - overlaying with areas % clf % x=[1,2,3,4,5,5]; % y=randn(20,length(x)); % y(:,end)=y(:,end)+3; % y(:,end-1)=y(:,end-1)-1; % notBoxPlot(y,x); % % Example 3 - lines % clf % H=notBoxPlot(randn(20,5),[],[],'line'); % set([H.data],'markersize',10) % % Example 4 - mix lines and areas [note that the way this function % sets the x axis limits can cause problems when combining plots % this way] % % clf % h=notBoxPlot(randn(10,1)+4,5,[],'line'); % set(h.data,'color','m') % h=notBoxPlot(randn(50,10)); % set(h(5).data,'color','m') % % Example 5 - x and y are vectors % clf % x=[1,1,1,3,2,1,3,3,3,2,2,3,3]; % y=[7,8,6,1,5,7,2,1,3,4,5,2,4]; % notBoxPlot(y,x); % % Note: an alternative to the style used in Example 5 is to call % notBoxPlot from a loop in an external function. In this case, the % user will have to take care of the x-ticks and axis limits. % % Example 6 - replacing the SD with bars % clf % y=randn(50,1); % clf % notBoxPlot(y,1,[],'sdline') % notBoxPlot(y,2) % xlim([0,3]) % % % Rob Campbell - January 2010 % % also see: boxplot % Check input arguments error(nargchk(0,4,nargin)) if nargin==0 help(mfilename) return end if isvector(y), y=y(:); end if nargin<2 || isempty(x) x=1:size(y,2); end if nargin<3 || isempty(jitter) jitter=0.3; %larger value means greater amplitude jitter end if nargin<4 style='patch'; %Can also be 'line' or 'sdline' end style=lower(style); if jitter==0 && strcmp(style,'patch') warning('A zero value for jitter means no patch object visible') end if isvector(y) & isvector(x) & length(x)>1 x=x(:); if length(x)~=length(y) error('length(x) should equal length(y)') end u=unique(x); for ii=1:length(u) f=find(x==u(ii)); h(ii)=notBoxPlot(y(f),u(ii),jitter,style); end %Make plot look pretty if length(u)>1 xlim([min(u)-1,max(u)+1]) set(gca,'XTick',u) end if nargout==1 varargout{1}=h; end return end if length(x) ~= size(y,2) error('length of x doesn''t match the number of columns in y') end %We're going to render points with the same x value in different %colors so we loop through all unique x values and do the plotting %with nested functions. No clf in order to give the user more %flexibility in combining plot elements. hold on [uX,a,b]=unique(x); h=[]; for ii=1:length(uX) f=find(b==ii); h=[h,myPlotter(x(f),y(:,f))]; end hold off %Tidy up plot: make it look pretty if length(x)>1 set(gca,'XTick',unique(x)) xlim([min(x)-1,max(x)+1]) end if nargout==1 varargout{1}=h; end %Nested functions follow %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h=myPlotter(X,Y) SEM=SEM_calc(Y); %Supplied external function SD=nanstd(Y); %Requires the stats toolbox mu=nanmean(Y); %Requires the stats toolbox %The plot colors to use for multiple sets of points on the same x %location cols=hsv(length(X)+1)*0.5; cols(1,:)=0; jitScale=jitter*0.55; %To scale the patch by the width of the jitter for k=1:length(X) thisY=Y(:,k); thisY=thisY(~isnan(thisY)); thisX=repmat(X(k),1,length(thisY)); if strcmp(style,'patch') h(k).sdPtch=patchMaker(SD(k),[0.6,0.6,1]); end if strcmp(style,'patch') || strcmp(style,'sdline') h(k).semPtch=patchMaker(SEM(k),[1,0.6,0.6]); h(k).mu=plot([X(k)-jitScale,X(k)+jitScale],[mu(k),mu(k)],'-r',... 'linewidth',2); end %Plot jittered raw data C=cols(k,:); J=(rand(size(thisX))-0.5)*jitter; h(k).data=plot(thisX+J, thisY, 'o', 'color', C,... 'markerfacecolor', C+(1-C)*0.65); end if strcmp(style,'line') | strcmp(style,'sdline') for k=1:length(X) %Plot SD h(k).sd=plot([X(k),X(k)],[mu(k)-SD(k),mu(k)+SD(k)],... '-','color',[0.2,0.2,1],'linewidth',2); set(h(k).sd,'ZData',[1,1]*-1) end end if strcmp(style,'line') for k=1:length(X) %Plot mean and SEM h(k).mu=plot(X(k),mu(k),'o','color','r',... 'markerfacecolor','r',... 'markersize',10); h(k).sem=plot([X(k),X(k)],[mu(k)-SEM(k),mu(k)+SEM(k)],'-r',... 'linewidth',2); h(k).xAxisLocation=x(k); end end function ptch=patchMaker(thisInterval,color) l=mu(k)-thisInterval; u=mu(k)+thisInterval; ptch=patch([X(k)-jitScale, X(k)+jitScale, X(k)+jitScale, X(k)-jitScale],... [l,l,u,u], 0); set(ptch,'edgecolor','none','facecolor',color) end %function patchMaker end %function myPlotter end %function notBoxPlot
github
HelmchenLabSoftware/OCIA-master
importResonanceFolder.m
.m
OCIA-master/utils/importExport/importResonanceFolder.m
2,264
utf_8
17b8b7e3b8ac097566672757e58f4ca8
function imgStruct = importResonanceFolder(dataPath) %#ok<STOUT,INUSD> error('importResonanceFolder:Deprecated', 'DEPRECATED: use loadData instead'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Intrinsic image analyser % % Originally created on 28 / 11 / 2013 % % Written by B. Laurenczy ([email protected]) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% process files of the folder fileNames = ls(dataPath); %#ok<UNRCH> % get all file names imgStruct = struct('img_data', [], 'hdr', []); iChan = 1; keepAvgFramesSeparate = 0; for iFile = 1 : size(fileNames, 1); fileName = fileNames(iFile, :); if ~isempty(regexp(fileName, '\.xml', 'once')); imgStruct.hdr.filePath = [dataPath filesep fileName]; xml = xmlread(imgStruct.hdr.filePath); dimX = getNodeValue(xml, 'ResolutionX'); dimY = getNodeValue(xml, 'ResolutionY'); nFrames = getNodeValue(xml, 'Frames'); imgStruct.hdr.size = [dimX, dimY, nFrames]; imgStruct.hdr.frame_rate = getNodeValue(xml, 'FrameScanRate'); imgStruct.hdr.nAveraging = getNodeValue(xml, 'AveragingRepetitions'); imgStruct.hdr.zStepSize = getNodeValue(xml, 'StepSize'); % fileID = fopen([dataPath filesep fileName]); % data = fread(fileID, 'uint16'); % fclose(fileID); elseif ~isempty(regexp(fileName, '\.bin', 'once')); fileID = fopen([dataPath filesep fileName]); data = fread(fileID, 'uint16'); if imgStruct.hdr.nAveraging == 1; imgStruct.img_data{iChan} = reshape(data, imgStruct.hdr.size); elseif imgStruct.hdr.nAveraging > 1; imgStruct.img_data{iChan} = reshape(data, [imgStruct.hdr.size imgStruct.hdr.nAveraging]); end; if imgStruct.hdr.nAveraging > 1 && ~keepAvgFramesSeparate; imgStruct.img_data{iChan} = reshape(mean(imgStruct.img_data{iChan}, 4), imgStruct.hdr.size); end; fclose(fileID); iChan = iChan + 1; end; end; function value = getNodeValue(xml, tagName) value = str2double(xml.getDocumentElement.getElementsByTagName(tagName).item(0).getChildNodes.item(0).getNodeValue); end end
github
HelmchenLabSoftware/OCIA-master
ReadEphys.m
.m
OCIA-master/utils/importExport/ReadEphys.m
1,245
utf_8
07f7cdadb5d8e096e0e9a910fd033ee4
function [ephys,FrameClock] = ReadEphys(varargin) % read binary data files written by LabView E-phys acquisition program in % H45 % requires file name of file to read and number of timepoints % returns e-phys trace and frame clock % this file written by Henry Luetcke ([email protected]) if nargin == 2 filename = varargin{1}; timepoints = varargin{2}; elseif nargin == 1 filename = varargin{1}; timepoints = getTimePointDialog; else [FileName, PathName] = uigetfile('*.*','Select file for reading'); filename = fullfile(PathName,FileName); timepoints = getTimePointDialog; end fid = fopen(filename); if ~timepoints % read till end of file, FrameClock empty % hdr1 = fread(fid,96,'float32','ieee-be'); ephys = fread(fid,'float32','ieee-be'); FrameClock = []; else hdr1 = fread(fid,96,'float32','ieee-be'); ephys = fread(fid,timepoints,'float32','ieee-be'); hdr2 = fread(fid,96,'float32','ieee-be'); FrameClock = fread(fid,timepoints,'float32','ieee-be'); end fclose(fid); function timepoints = getTimePointDialog prompt = {'Timepoints in file:'}; dlg_title = 'Specify timepoints'; num_lines = 1; answer = inputdlg(prompt,dlg_title,num_lines,{''}); timepoints = str2double(answer{1});
github
HelmchenLabSoftware/OCIA-master
ij_RoiSetSeedPointSegment.m
.m
OCIA-master/utils/importExport/imageJROI/ij_RoiSetSeedPointSegment.m
4,975
utf_8
8d601794c01445d79037f07f2ec57d22
function ij_RoiSetSeedPointSegment(varargin) % segment cell Rois from ImageJ single point RoiSet and save as new ImageJ % RoiSet % in1 ... configuration structure for this program % may be called without input arguments --> GUI file selection and default % parameters (c.f. below) % uses ActiveModel segmentation provided by Parametric Active Model Toolbox % http://www.mathworks.ch/matlabcentral/fileexchange/22871 % (c) Copyright Bing Li 2005 - 2009. % this file written by Henry Luetcke ([email protected]) %% Input and default parameters if nargin config = varargin{1}; else config = struct; end config = ParseConfigStruct(config); %% Do segmentation for n = 1:length(config.roi_files) % support tiff only at this stage img = tif2mat(config.img_files{n},'nosave'); img = img.data; img = mean(img,3); roiSet = ij_roiDecoder(config.roi_files{n},size(img)); roiSet_seg = roiSet; % run segmentation for each point Roi for roi = 1:size(roiSet,1) point_mask = bwunpack(roiSet{roi,2}); [x,y] = ind2sub(size(img),find(point_mask==1)); if length(x) > 1 warning('Found more than 1 point in Roi %s of RoiSet %s',... roiSet{roi,1},config.roi_files{n}); elseif isempty(x) || isempty(y) warning('Found no points in Roi %s of RoiSet %s',... roiSet{roi,1},config.roi_files{n}); roiSet_seg{roi} = []; continue end config.cog = [x y]; roiSet_seg{roi,2} = ActiveModel_segment(img,config); end % save as new ImageJ RoiSet tmpdir = datestr(clock,30); mkdir(tmpdir); zip_filename = strrep(config.roi_files{n},'.zip','_Cells.zip'); start_dir = pwd; cd(tmpdir); for roi = 1:size(roiSet_seg,1) status = ij_roiEncoder(roiSet_seg{roi,2},roiSet{roi,1}); end % create neuropil Rois (either none or 4) if config.npil_rois roi_img = zeros(size(img)); for roi = 1:size(roiSet_seg,1) roi_img(roiSet_seg{roi,2}==1) = 1; end roi1 = repmat(1,round(size(roi_img,1)/2),round(size(roi_img,2)/2)); roi2 = repmat(2,size(roi_img,1)-round(size(roi_img,1)/2),... round(size(roi_img,2)/2)); roi3 = repmat(3,round(size(roi_img,1)/2),size(roi_img,2)-... round(size(roi_img,2)/2)); roi4 = repmat(4,size(roi_img,1)-round(size(roi_img,1)/2),... size(roi_img,2)-round(size(roi_img,2)/2)); npil_rois = [roi1 roi3; roi2 roi4]; npil_rois(roi_img~=0) = 0; for npil_no = 1:4 roi = zeros(size(roi_img)); roi(npil_rois==npil_no&img>20) = 1; status = ij_roiEncoder(roi,sprintf('n%1.0f.roi',npil_no)); roiSet_seg{size(roiSet_seg,1)+1,1} = sprintf('n%1.0f.roi',npil_no); roiSet_seg{size(roiSet_seg,1),2} = roi; end end zip(zip_filename,roiSet_seg(:,1)); [path, zip_filename] = fileparts(zip_filename); cd(start_dir); rmdir(tmpdir,'s'); mat_filename = strrep(zip_filename,'.zip','.mat'); roiSet = roiSet_seg; roiSet(:,1) = strrep(roiSet(:,1),'.roi',''); save(mat_filename,'roiSet'); end %% Parse config structure function config = ParseConfigStruct(config) % input file(s) if ~isfield(config,'roi_files') [config.roi_files,PathName] = uigetfile('*.zip','MultiSelect','on'); if isstr(config.roi_files) config.roi_files = {config.roi_files}; end for n = 1:length(config.roi_files) config.roi_files{n} = fullfile(PathName,config.roi_files{n}); end elseif isstr(config.roi_files) config.roi_files = {config.roi_files}; end if ~isfield(config,'img_files') [config.img_files,PathName] = uigetfile({'*.tif';'*.tiff'},'MultiSelect','on'); if isstr(config.img_files) config.img_files = {config.img_files}; end for n = 1:length(config.img_files) config.img_files{n} = fullfile(PathName,config.img_files{n}); end elseif isstr(config.img_files) config.img_files = {config.img_files}; end if length(config.roi_files) ~= length(config.img_files) error('You MUST specify the same number of image and roi files!'); end % required field names and their values config_fields = {'cellsize' 'snake_iter1' 'snake_iter' ... 'alpha' 'beta' 'tau' 'filt_range' 'filt_order' 'canny_lo' ... 'canny_hi' 'alt_radius' 'npil_rois' 'doPlot' 'verbosity'}; config_vals = {7 100 10 1 0 0.1 [3 3] 1 [0.1 0.05 0.01] ... [0.25 0.15 0.05] 3 0 0 0}; for n = 1:length(config_fields) if ~isfield(config,config_fields{n}) config.(config_fields{n}) = config_vals{n}; end end config_savename = ['AMsegment_config.html']; print2html(config,5,config_savename); config_savename = strrep(config_savename,'.html','.mat'); save(config_savename,'config'); config_savename = strrep(config_savename,'.mat',''); fprintf('\nCurrent configuration saved in %s\n',config_savename); % e.o.f.
github
HelmchenLabSoftware/OCIA-master
loadDataFromHDF5.m
.m
OCIA-master/utils/importExport/HDF5/loadDataFromHDF5.m
7,865
utf_8
4d3a9dea75580223eebd08fa81693430
function data = loadDataFromHDF5(filePath, datasetPath) % data = loadDataFromHDF5(filePath, datasetPath) % Wrapper for the h5readAsStruct function that reads out the content of the HDF5 file as a structure and reshapes it % to a more usable format. % % Written on 2014-04-07 by B. Laurenczy ([email protected]) % read the HDF5 file's content into a structure dataStruct = h5readAsStruct(filePath, datasetPath); % reshape it to our need data = reshapeData(dataStruct, filePath, datasetPath); end % reshape each field to our need function dataStruct = reshapeData(dataStruct, filePath, structPath) % if not a structure, just return the data if ~isstruct(dataStruct); return; end; % get the fields fNames = fieldnames(dataStruct); % go through each field and process it for iFName = 1 : numel(fNames); fName = fNames{iFName}; % get the field name % different processing for different field names switch fName; % reshape the ROISet into the 2-column cell array with col. 1 being the names and col. 2 beign the masks % also add the reference image and the runs validities as columns in the cell array % final output in the ROISet field will be a cell array with one row for each ROISet and % 4 columns : { ROISet, runsValidity, refImage, ROISet's runID } case 'ROISet'; % read as h5read_wrapper would do ROISetStruct = processStruct(filePath, structPath, {}); dataStruct.ROISet = ROISetStruct.ROISet; dataStruct.runsValidity = ROISetStruct.runsValidity; dataStruct.refImage = ROISetStruct.refImage; %{ ROISetStruct = dataStruct.ROISet; ROINamesRuns = fieldnames(ROISetStruct.ROINames); dataStruct.ROISet = cell(numel(ROINamesRuns), 4); for iRun = 1 : numel(ROINamesRuns); runID = ROINamesRuns{iRun}; ROINames = ROISetStruct.ROINames.(runID); nROIs = size(ROINames, 1); masks = ROISetStruct.masks.(runID); runsValidity = ROISetStruct.runsValidity.(runID); nRuns = size(runsValidity, 1); % cast matrix of logical into cell-array of logical masks = arrayfun(@(iROI)masks(:, :, iROI), 1 : nROIs, 'UniformOutput', false)'; % cast matrix of doubles into a cell-array of strings ... in a single line! :D Take that clarity ! runsValidity = arrayfun(@(iRun)char(runsValidity(iRun, :)), 1 : nRuns, 'UniformOutput', false)'; % cast matrix of doubles into a cell-array of strings ... in a single line! :D Take that clarity ! ROINames = arrayfun(@(iROI)strtrim(char(ROINames(iROI, :))), 1 : nROIs, 'UniformOutput', false)'; % create ROISet based on the reshaped data dataStruct.ROISet{iRun, 1} = [ROINames, masks]; dataStruct.ROISet{iRun, 2} = runsValidity; dataStruct.ROISet{iRun, 3} = ROISetStruct.refImage.(runID); dataStruct.ROISet{iRun, 4} = runID; end; %} % reshape the behavior data from one structure with many fields to a structure with cell-arrays as fields, % with one cell-array per field and an additional field for the runIDs case 'behav'; behavStruct = dataStruct.behav; behavStructArray = structfun(@(x)x, behavStruct, 'UniformOutput', false); dataStruct.runIDs = regexprep(fieldnames(behavStruct), '^x', ''); behavFields = fieldnames(behavStructArray); dataStruct.behav = struct(); c = struct2cell(behavStructArray); for iField = 1 : numel(behavFields); dataStruct.behav.(behavFields{iField}) = c(iField, :); end; % reshape the structure as cell-arrays (runIDs should be the same as in the 'behav' field) case {'caTraces', 'stim', 'exclMask'}; s = dataStruct.(fName); sFNames = fieldnames(s); c = cell(numel(sFNames), 1); for iRun = 1 : numel(sFNames); c{iRun} = s.(sFNames{iRun}); end; dataStruct.(fName) = c; % otherwise go recusrive otherwise structPath = sprintf('%s/%s', structPath, regexprep(fName, '^x', '')); dataStruct.(fName) = reshapeData(dataStruct.(fName), filePath, structPath); end; end; end % separate function to process structures. Fields of the structure can be stored either as data % sets or as attributes if they have "simple" values (single numbers, single logicals or string) function data = processStruct(fileName, datasetPath, h5readArgs) % read the data-set field names of the structure from the attribute as a comma-separated string datasetNames = str2cell(h5readatt(fileName, datasetPath, 'FieldNames_DS')); % read the attribute field names of the structure from the attribute as a comma-separated string attNames = str2cell(h5readatt(fileName, datasetPath, 'FieldNames_Att')); % remove the empty cells attNames(cellfun(@isempty, attNames)) = []; datasetNames(cellfun(@isempty, datasetNames)) = []; % initate the structure data = struct(); % go through each data-set stored field name for iName = 1 : numel(datasetNames); % get the field name name = datasetNames{iName}; % create the data set path using that name datasetPathStruct = sprintf('%s/%s', datasetPath, name); % read the data set to extract the value, recursively data.(name) = h5read_wrapper(fileName, datasetPathStruct, h5readArgs); end; % go through each attribute stored field name for iName = 1 : numel(attNames); % get the field name name = attNames{iName}; % load the value from the attribute dataVal = h5readatt(fileName, datasetPath, sprintf('%s_Value', name)); % load the orginial data type from the attribute dataType = h5readatt(fileName, datasetPath, sprintf('%s_DataType', name)); % load the orginial dimension from the attribute (to restore the orientation: 1xN or Nx1) dim = str2dim(h5readatt(fileName, datasetPath, sprintf('%s_Dim', name))); % process the different data types differently switch dataType; % strings (char) case 'char'; % store the value as a converted, reshaped char data.(name) = char(reshape(dataVal, dim)); % logicals case 'logical'; % store the value as a converted, reshaped logical data.(name) = logical(reshape(dataVal, dim)); % numeric case {'single', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'}; % store the value as a reshaped numeric data.(name) = reshape(dataVal, dim); % others: unknown, throw a warning otherwise warning('h5read_wrapper:processStruct:UnknownDataTypeValue', ... 'Data type "%s" of field "%s" at data set path "%s" is not supported.', dataType, name, datasetPath); end; end; end
github
HelmchenLabSoftware/OCIA-master
h5createIntermediateGroup.m
.m
OCIA-master/utils/importExport/HDF5/h5createIntermediateGroup.m
1,120
utf_8
5ba2a52ce40089c79f3c43287ca89493
% creates an intermediate group in the HDF5 file so that group exists whenever an attribute needs to be attached to it function h5createIntermediateGroup(fileName, groupPath) % if file does not exist, create a new file using the default properties if ~exist(fileName, 'file'); fID = H5F.create(fileName, 'H5F_ACC_TRUNC', 'H5P_DEFAULT', 'H5P_DEFAULT'); % if file exists, open it using the default properties else fID = H5F.open(fileName, 'H5F_ACC_RDWR', 'H5P_DEFAULT'); end; % check if the group does not already exist try % try to fetch the info for this group ... H5G.get_objinfo(fID, groupPath, false); % ... if no error, then group exists so abort return; catch err; %#ok<NASGU> % error mean no group, so one can create it end; % create group creation property list and set it to allow creation of intermediate groups gPropList = H5P.create('H5P_LINK_CREATE'); H5P.set_create_intermediate_group(gPropList, 1); % create the group at groupPath gID = H5G.create(fID, groupPath, gPropList, 'H5P_DEFAULT', 'H5P_DEFAULT'); % close all H5P.close(gPropList); H5G.close(gID); H5F.close(fID); end
github
HelmchenLabSoftware/OCIA-master
h5read_wrapper.m
.m
OCIA-master/utils/importExport/HDF5/h5read_wrapper.m
9,682
utf_8
1e980dce42de30109767710808bce2c5
function data = h5read_wrapper(filePath, datasetPath, h5readArgs) % data = h5read_wrapper(fileName, datasetPath, h5readArgs) % Wrapper for the h5read function that also handles cell-array, structures and struct-arrays. % Recursively reads the data from the HDF5 file "fileName" from the dataset path "datasetPath". % Arguments to the h5read function can be provided using the h5readArgs cell-array. % get the data type of the data from the attribute try dataType = h5readatt(filePath, datasetPath, 'DataType'); catch err; error('h5read_wrapper:DataTypeAttributeNotFound', ... 'Could not find the attribute "DataType" at path "%s" in file "%s".', datasetPath, filePath); end; % process the different data types in different ways switch dataType; % numeric case {'single', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'}; % read out the data data = h5read(filePath, datasetPath, h5readArgs{:}); % logical case 'logical'; % read out the data data = h5read(filePath, datasetPath, h5readArgs{:}); % convert to logical data = logical(data); % strings (char) case 'char'; % read out the data data = h5read(filePath, datasetPath, h5readArgs{:}); % convert to char data = char(data); % cell-arrays case 'cellArray'; % cell arrays are processed in a separate function data = processCellArray(filePath, datasetPath, h5readArgs); % cell-arrays saved as matrix case 'cellArrayMat'; % cell arrays are processed in a separate function data = processCellArrayMat(filePath, datasetPath, h5readArgs); % structures case 'struct'; % structures are processed in a separate function data = processStruct(filePath, datasetPath, h5readArgs); % struct-arrays case 'structArray'; % struct-arrays are processed in a separate function data = processStructArray(filePath, datasetPath, h5readArgs); % others: categorical (nominal/ordinal), tables and all kinds of weird stuff are not supported otherwise; warning('h5read_wrapper:DataTypeNotSupported', 'Data type "%s" is not supported.', dataType); % abort return; end; end % separate function to process cell-arrays and load each cell's content separately function data = processCellArray(fileName, datasetPath, h5readArgs) % read the dimension of the data from the attribute as a "3x4x5" string dim = str2dim(h5readatt(fileName, datasetPath, 'cellArray_Dim')); % get the indexes of the non-empty cells datasetPathNonEmptyCell = sprintf('%s/cellNonEmptyIndexes', datasetPath); nonEmptyCells = h5read_wrapper(fileName, datasetPathNonEmptyCell, h5readArgs); % initiate the cell-array data = cell(dim); % go through each non-empty cell and load it separately for iCell = find(nonEmptyCells); % create the path using a simple "cell_[CELL_INDEX]" path datasetPathCell = sprintf('%s/cell_%d', datasetPath, iCell); % if the cell was empty, the data set was not created so skip it and leave it empty if ~h5exists(fileName, datasetPathCell); continue; end; % read the data set for the content of the cell, recursively data{iCell} = h5read_wrapper(fileName, datasetPathCell, h5readArgs); end; end % separate function to process cell-arrays that are saved as matrix function data = processCellArrayMat(fileName, datasetPath, h5readArgs) % read the dimension of the data from the attribute as a "3x4x5" string dim = str2dim(h5readatt(fileName, datasetPath, 'cellArrayMat_Dim')); % extract the cell-array's values as a dataset of doubles datasetPathCell = sprintf('%s/cellArrayMat_Val', datasetPath); linDataMatDouble = h5read_wrapper(fileName, datasetPathCell, h5readArgs); % extract the cell-array's dimensions datasetPathCell = sprintf('%s/cellArrayMat_Dim', datasetPath); matDim = h5read_wrapper(fileName, datasetPathCell, h5readArgs); % extract the cell-array's data types datasetPathCell = sprintf('%s/cellArrayMat_DataTypes', datasetPath); dataTypes = h5read_wrapper(fileName, datasetPathCell, h5readArgs); % calculate the number of values per cell by calculating the product of the dimensions nValuesPerCell = arrayfun(@(x)prod(matDim(x, matDim(x, :) > 0)), 1 : size(matDim, 1)); % empty cells (dim = 0x0x0x...) must have a number of values of 0 nValuesPerCell(arrayfun(@(x)~any(matDim(x, :) > 0), 1 : size(matDim, 1))) = 0; % convert back the matrix to a cell array linDataCellDouble = mat2cell(linDataMatDouble, reshape(nValuesPerCell, numel(nValuesPerCell), 1)); nCells = size(linDataCellDouble, 1); % create a linearized cell array with empty cells linData = cell(nCells, 1); % convert back the doubles into the appropriate data type and reshape the cells to their original dimensions: % go cell by cell for iCell = 1 : nCells; % if all dimensions are empty, the cell must remain empty if ~any(matDim(iCell, :)); continue; end; % cast the double into the right value cellValue = cast(linDataCellDouble{iCell}', strtrim(dataTypes(iCell, :))); % reshape the cell's content to the original dimension linData{iCell} = reshape(cellValue, matDim(iCell, matDim(iCell, :) > 0)); end; % reshape the cell-array to have the original dimension data = reshape(linData, dim); end % separate function to process struct-arrays and load each structure separately function data = processStructArray(fileName, datasetPath, h5readArgs) % read the dimension of the struct-array from the attribute as a "3x4x5" string dim = str2dim(h5readatt(fileName, datasetPath, 'struct_Dim')); % read the field names of the structure from the attribute as a comma-separated string names = str2cell(h5readatt(fileName, datasetPath, 'FieldNames')); % remove the empty cells names(cellfun(@isempty, names)) = []; % initate the struct-array using the cell2struct function. Each structure already contains the right field names data = cell2struct(cell([numel(names), dim]), names, 1); % go trough each structure an load it separately for iStruct = 1 : numel(data); % create the path using a simple "struct_[STRUCT_INDEX]" path datasetPathStruct = sprintf('%s/struct_%d', datasetPath, iStruct); % if the structure was empty, the data set was not created so skip it and leave it empty if ~h5exists(fileName, datasetPathStruct); continue; end; % read the data set for a single structure, recursively data(iStruct) = h5read_wrapper(fileName, datasetPathStruct, h5readArgs); end; end % separate function to process structures. Fields of the structure can be stored either as data % sets or as attributes if they have "simple" values (single numbers, single logicals or string) function data = processStruct(fileName, datasetPath, h5readArgs) % read the data-set field names of the structure from the attribute as a comma-separated string datasetNames = str2cell(h5readatt(fileName, datasetPath, 'FieldNames_DS')); % read the attribute field names of the structure from the attribute as a comma-separated string attNames = str2cell(h5readatt(fileName, datasetPath, 'FieldNames_Att')); % remove the empty cells attNames(cellfun(@isempty, attNames)) = []; datasetNames(cellfun(@isempty, datasetNames)) = []; % initate the structure data = struct(); % go through each data-set stored field name for iName = 1 : numel(datasetNames); % get the field name name = datasetNames{iName}; % create the data set path using that name datasetPathStruct = sprintf('%s/%s', datasetPath, name); % read the data set to extract the value, recursively data.(name) = h5read_wrapper(fileName, datasetPathStruct, h5readArgs); end; % go through each attribute stored field name for iName = 1 : numel(attNames); % get the field name name = attNames{iName}; % load the value from the attribute dataVal = h5readatt(fileName, datasetPath, sprintf('%s_Value', name)); % load the orginial data type from the attribute dataType = h5readatt(fileName, datasetPath, sprintf('%s_DataType', name)); % load the orginial dimension from the attribute (to restore the orientation: 1xN or Nx1) dim = str2dim(h5readatt(fileName, datasetPath, sprintf('%s_Dim', name))); % nan-bug in reading dimension if any(isnan(dim)); warning('h5read_wrapper:unreadableAttribute', ... 'Cannot read attribute "%s" because dimension string is (partly) NaN', name); continue; end; % process the different data types differently switch dataType; % strings (char) case 'char'; % store the value as a converted, reshaped char data.(name) = char(reshape(dataVal, dim)); % logicals case 'logical'; % store the value as a converted, reshaped logical data.(name) = logical(reshape(dataVal, dim)); % numeric case {'single', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'}; % store the value as a reshaped numeric data.(name) = reshape(dataVal, dim); % others: unknown, throw a warning otherwise warning('h5read_wrapper:processStruct:UnknownDataTypeValue', ... 'Data type "%s" of field "%s" at data set path "%s" is not supported.', dataType, name, datasetPath); end; end; end
github
HelmchenLabSoftware/OCIA-master
h5exists.m
.m
OCIA-master/utils/importExport/HDF5/h5exists.m
1,057
utf_8
1db0c46a2621b643d377b487c7574545
% delete a group in the HDF5 file function doesExist = h5exists(fileName, groupPath) % check if the file exists if ~exist(fileName, 'file'); doesExist = false; return; end; doesExist = true; fileID = H5F.open(fileName); pathParts = regexp(groupPath, '/', 'split'); iPart = 2; while iPart < numel(pathParts); partialPartsString = sprintf('/%s', pathParts{2 : iPart}); nextPart = pathParts{iPart + 1}; try groupID = H5G.open(fileID, partialPartsString); catch err; if strcmp(err.identifier, 'MATLAB:imagesci:hdf5lib:libraryError') && iPart == 2; doesExist = false; break; end; rethrow(err); end; if H5L.exists(groupID, nextPart, 'H5P_DEFAULT'); % fprintf('Path "%s/%s": link exists\n', partialPartsString, nextPart); H5G.close(groupID); else % fprintf('Path "%s/%s": link does not exist\n', partialPartsString, nextPart); doesExist = false; break; end; iPart = iPart + 1; end; H5F.close(fileID); end
github
HelmchenLabSoftware/OCIA-master
loadDataFromHDF5_old.m
.m
OCIA-master/utils/importExport/HDF5/loadDataFromHDF5_old.m
4,559
utf_8
b3d2b1533fb9d314c711a71eefa2fff5
function data = loadDataFromHDF5_old(filePath, datasetPath) % data = loadDataFromHDF5(filePath, datasetPath) % Wrapper for the h5readAsStruct function that reads out the content of the HDF5 file as a structure and reshapes it % to a more usable format. % % Written on 2014-04-07 by B. Laurenczy ([email protected]) % read the HDF5 file's content into a structure dataStruct = h5readAsStruct(filePath, datasetPath); % reshape it to our need data = reshapeData(dataStruct); end % reshape each field to our need function dataStruct = reshapeData(dataStruct) % if not a structure, just return the data if ~isstruct(dataStruct); return; end; % get the fields fNames = fieldnames(dataStruct); % go through each field and process it for iFName = 1 : numel(fNames); fName = fNames{iFName}; % get the field name % different processing for different field names switch fName; % reshape the ROISet into the 2-column cell array with col. 1 being the names and col. 2 beign the masks % also add the reference image and the runs validities as columns in the cell array % final output in the ROISet field will be a cell array with one row for each ROISet and % 4 columns : { ROISet, runsValidity, refImage, ROISet's runID } case 'ROISet'; ROISetStruct = dataStruct.ROISet; ROINamesRuns = fieldnames(ROISetStruct.ROINames); dataStruct.ROISet = cell(numel(ROINamesRuns), 4); for iRun = 1 : numel(ROINamesRuns); runID = ROINamesRuns{iRun}; ROINames = ROISetStruct.ROINames.(runID); nROIs = size(ROINames, 1); masks = ROISetStruct.masks.(runID); runsValidity = ROISetStruct.runsValidity.(runID); nRuns = size(runsValidity, 1); % cast matrix of logical into cell-array of logical masks = arrayfun(@(iROI)masks(:, :, iROI), 1 : nROIs, 'UniformOutput', false)'; % cast matrix of doubles into a cell-array of strings ... in a single line! :D Take that clarity ! runsValidity = arrayfun(@(iRun)char(runsValidity(iRun, :)), 1 : nRuns, 'UniformOutput', false)'; % cast matrix of doubles into a cell-array of strings ... in a single line! :D Take that clarity ! ROINames = arrayfun(@(iROI)strtrim(char(ROINames(iROI, :))), 1 : nROIs, 'UniformOutput', false)'; % create ROISet based on the reshaped data dataStruct.ROISet{iRun, 1} = [ROINames, masks]; dataStruct.ROISet{iRun, 2} = runsValidity; dataStruct.ROISet{iRun, 3} = ROISetStruct.refImage.(runID); dataStruct.ROISet{iRun, 4} = runID; end; % reshape the behavior data from one structure with many fields to a structure with cell-arrays as fields, % with one cell-array per field and an additional field for the runIDs case 'behav'; behavStruct = dataStruct.behav; behavStructArray = structfun(@(x)x, behavStruct, 'UniformOutput', false); dataStruct.runIDs = regexprep(fieldnames(behavStruct), '^x', ''); behavFields = fieldnames(behavStructArray); dataStruct.behav = struct(); c = struct2cell(behavStructArray); for iField = 1 : numel(behavFields); dataStruct.behav.(behavFields{iField}) = c(iField, :); end; % reshape the structure as cell-arrays (runIDs should be the same as in the 'behav' field) case {'caTraces', 'stim', 'exclMask'}; s = dataStruct.(fName); sFNames = fieldnames(s); c = cell(numel(sFNames), 1); for iRun = 1 : numel(sFNames); c{iRun} = s.(sFNames{iRun}); end; dataStruct.(fName) = c; % otherwise go recusrive otherwise dataStruct.(fName) = reshapeData(dataStruct.(fName)); end; end; end
github
HelmchenLabSoftware/OCIA-master
h5createwrite_wrapper.m
.m
OCIA-master/utils/importExport/HDF5/h5createwrite_wrapper.m
16,544
utf_8
9489ee1b4d18ac50e7741d3b0080da0f
function h5createwrite_wrapper(fileName, datasetPath, data, h5createArgs, h5writeArgs) % h5createwrite_wrapper(fileName, datasetPath, data, h5createArgs, h5writeArgs) % Wrapper for the h5create and h5write functions that also handles cell-array, structures and struct-arrays. % Recursively creates and/or writes the data as HDF5 into the file "fileName" under the dataset path "datasetPath". % Arguments to the h5create and h5write functions can be provided using the h5createArgs and h5writeArgs cell-array. % maximum limit for having a string structure value written out as an attribute CHAR_ATT_LIMIT = 200; % maximum limit for having a logical structure value written out as an attribute LOGICAL_ATT_LIMIT = 10; % maximum limit for having a numeric structure value written out as an attribute NUMERIC_ATT_LIMIT = 10; % maximum number of dimensions that a cell can have and still be converted as a matrix CELL_MAX_DIM = 32; % minimum number of characters required to know a datatype from the command "class" DATA_TYPE_DESCR_LEN = 7; % get the data type of the data and store it before eventual modifications dataType = class(data); originalDataType = dataType; % process the different data types in different ways switch dataType; % numeric case {'single', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'}; % nothing to do, just store as numeric % logical and strings (char) case {'logical', 'char'}; % logical and chars should be converted to 8-bit data = uint8(data); % get the new data type dataType = class(data); % cell-arrays case 'cell'; % cell arrays are processed in a separate function processCellArray(fileName, datasetPath, data, h5createArgs, h5writeArgs, CELL_MAX_DIM, DATA_TYPE_DESCR_LEN); % stop here since function return; % structures and struct-arrays case 'struct'; % if creation is required, create the group path first, so that attribute saving already have the path ready h5createIntermediateGroup(fileName, datasetPath); % structures and struct-arrays are processed in a separate function processStruct(fileName, datasetPath, data, h5createArgs, h5writeArgs, CHAR_ATT_LIMIT, LOGICAL_ATT_LIMIT, ... NUMERIC_ATT_LIMIT); return; % others: categorical (nominal/ordinal), tables and all kinds of weird stuff are not supported otherwise; warning('h5createwrite_wrapper:DataTypeNotSupported', 'Data type "%s" is not supported.', dataType); % abort return; end; % get the dimension of the data dim = size(data); % is data size is not empty, create the data set with the actual data type if ~any(dim == 0); % if dataset already exists, delete it if h5exists(fileName, datasetPath); h5deleteGroup(fileName, datasetPath); end; h5create(fileName, datasetPath, dim, 'DataType', dataType, h5createArgs{:}); % write the data into the data set with the actual data type h5write(fileName, datasetPath, data, h5writeArgs{:}); % is data size has an empty dimension, chunk size should be specified else % if dataset already exists, delete it if h5exists(fileName, datasetPath); h5deleteGroup(fileName, datasetPath); end; % get the chunk size as the size divided by ten chunkSize = fix(dim / 10); % set the dimensions that are 0 to 1 chunkSize(chunkSize == 0) = 1; % create the data set with an infinite size and data type 'double' since an empty array is a double h5create(fileName, datasetPath, inf(1 : ndims(dim)), 'ChunkSize', chunkSize, 'DataType', 'double', ... h5createArgs{:}); % store the original dimension of the data into an attribute h5writeatt(fileName, datasetPath, 'DataDim', dim2str(dim)); % % write an empty cell the data set with the actual data type % h5write(fileName, datasetPath, [], h5writeArgs{:}); end; % store the orginal data type into an attribute h5writeatt(fileName, datasetPath, 'DataType', originalDataType); end % separate function to process cell-arrays and save each cell's content separately function processCellArray(fileName, datasetPath, data, h5createArgs, h5writeArgs, ... CELL_MAX_DIM, DATA_TYPE_DESCR_LEN) % linearize the cell-array (e.g. turn a 3 x 4 x 5 cell-array into a 1 x (3*4*5) = 1 * 60 cell-array linData = data(:); % get the number of cells nCells = size(linData, 1); % get a logical mask of the non-empty cells nonEmptyCells = ~cellfun(@isempty, linData); % if the cell-array is empty, make sure the group is created anyway if ~any(~cellfun(@isempty, linData)); h5createIntermediateGroup(fileName, datasetPath); end; % check whether the cell array can be converted to a matrix: % check if the array only contains chars, logicals, numerics or empty cells isCharNumLogicOnly = ~any(~cellfun(@(c) isempty(c) || ischar(c) || islogical(c) || isnumeric(c), linData)); % check if the array only contains empty cells isOnlyEmpty = ~any(nonEmptyCells); % check if the dimensions of the cells do not exceed CELL_MAX_DIM maxDimExceeded = any(cellfun(@(c) ndims(c) > CELL_MAX_DIM, linData)); % if it is only data types that can be converted into a matrix and maximum number of dimensions is not exceeded and % the cell-array is not empty and has cells, convert the cell array to a matrix if isCharNumLogicOnly && ~maxDimExceeded && nCells > 0 && ~isOnlyEmpty; % get the dimensions of the data as nCells x CELL_MAX_DIM matrix matDim = cell2mat(cellfun(@(x) [size(x) zeros(1, CELL_MAX_DIM - numel(size(x)))], linData, 'UniformOutput', false)); % get only the relevant matrix of dimension, e.g. take out columns with only 0 zero dimension matDim(:, ~any(matDim)) = []; % get the data types as nCells x DATA_TYPE_DESCR_LEN char matrix dataTypes = cell2mat(cellfun(@(x) [class(x) repmat(' ', 1, DATA_TYPE_DESCR_LEN - numel(class(x)))], linData, ... 'UniformOutput', false)); % convert everything to linearized matrix of doubles with dimensions nTotalValues x 1 linDataDouble = cell2mat(cellfun(@(c) double(reshape(c, numel(c), 1)), linData, 'UniformOutput', false)); % save the cell-array's values as a dataset of doubles datasetPathCell = sprintf('%s/cellArrayMat_Val', datasetPath); h5createwrite_wrapper(fileName, datasetPathCell, linDataDouble, h5createArgs, h5writeArgs); % save the cell-array's dimensions datasetPathCell = sprintf('%s/cellArrayMat_Dim', datasetPath); h5createwrite_wrapper(fileName, datasetPathCell, matDim, h5createArgs, h5writeArgs); % save the cell-array's data types datasetPathCell = sprintf('%s/cellArrayMat_DataTypes', datasetPath); h5createwrite_wrapper(fileName, datasetPathCell, dataTypes, h5createArgs, h5writeArgs); % write some annotation for this data set: get the dimension first dim = size(data); % write in an attribute the data type as being a matrix-cell-array h5writeatt(fileName, datasetPath, 'DataType', 'cellArrayMat'); % write in an attribute the dimension of the data as a "3x4x5" string h5writeatt(fileName, datasetPath, 'cellArrayMat_Dim', dim2str(dim)); % if the cell array contains other data types else % if cell-array has not only empty cells if ~isOnlyEmpty; % go through each non-empty cell save it separately nonEmptyCellIndexes = find(nonEmptyCells); for iCellLoop = 1 : numel(nonEmptyCellIndexes); % get the cell index iCell = nonEmptyCellIndexes(iCellLoop); % create the path using a simple "cell_[CELL_INDEX]" path datasetPathCell = sprintf('%s/cell_%d', datasetPath, iCell); % only save cell if it is not empty if ~isempty(linData{iCell}); % create/write the data set for the content of the cell, recursively h5createwrite_wrapper(fileName, datasetPathCell, linData{iCell}, h5createArgs, h5writeArgs); end; end; end; % write some annotation for this data set: get the dimension first dim = size(data); % write in an attribute the data type as being a cell-array h5writeatt(fileName, datasetPath, 'DataType', 'cellArray'); % write in an attribute the dimension of the data as a "3x4x5" string h5writeatt(fileName, datasetPath, 'cellArray_Dim', dim2str(dim)); % write out in a dataset the indexes of the non empty cells: % create the path using "cellNonEmptyIndexes" datasetPathNonEmptyCell = sprintf('%s/cellNonEmptyIndexes', datasetPath); % create/write the data set for the nonEmptyCellIndexes h5createwrite_wrapper(fileName, datasetPathNonEmptyCell, nonEmptyCells, h5createArgs, h5writeArgs); end end % separate function to process structures and struct-arrays. Fields of the structure can be save either % as data sets or as attributes if they have "simple" values (single number, single logicals or string) function processStruct(fileName, datasetPath, data, h5createArgs, h5writeArgs, ... CHAR_ATT_LIMIT, LOGICAL_ATT_LIMIT, NUMERIC_ATT_LIMIT) % CHAR_ATT_LIMIT: maximum limit for having a string structure value written out as an attribute % LOGICAL_ATT_LIMIT: maximum limit for having a logical structure value written out as an attribute % NUMERIC_ATT_LIMIT: maximum limit for having a numeric structure value written out as an attribute % if we are dealing with a single structure (not struct-array) if numel(data) == 1; % get the field names names = fieldnames(data); % create 2 cell array for the field names: datasetNames = cell(1, numel(names)); % field names with "complex" value saved as data set attNames = cell(1, numel(names)); % field names with "simple" value saved as attributes % go through each field name for iName = 1 : numel(names); % get the field name and the value name = names{iName}; dataVal = data.(name); % get the data type and the dimension of the value dataType = class(dataVal); dim = size(dataVal); % SIMPLE STRING: if it is a char with no 3rd dimension and one of the dimension is 1 and the other % does not exceed CHAR_ATT_LIMIT, save as attribute if ischar(dataVal) && numel(dim) <= 2 && any(dim == 1) && ~any(dim > CHAR_ATT_LIMIT); % store the field name as being saved as attribute attNames{iName} = name; % save the value as attribute h5writeatt(fileName, datasetPath, sprintf('%s_Value', name), dataVal); % save the orginial data type as attribute h5writeatt(fileName, datasetPath, sprintf('%s_DataType', name), dataType); % save the orginial dimension as attribute (needed to restore the orientation: 1xN or Nx1) h5writeatt(fileName, datasetPath, sprintf('%s_Dim', name), dim2str(dim)); % SIMPLE LOGICAL: if it is a logical with no 3rd dimension and one of the dimension is 1 and the other % does not exceed LOGICAL_ATT_LIMIT, convert to unsigned integer 8-bit and save as attribute elseif islogical(dataVal) && numel(dim) <= 2 && any(dim == 1) && ~any(dim > LOGICAL_ATT_LIMIT); % store the field name as being saved as attribute attNames{iName} = name; % save the value as uint8 converted attribute h5writeatt(fileName, datasetPath, sprintf('%s_Value', name), uint8(dataVal)); % save the orginial data type as attribute h5writeatt(fileName, datasetPath, sprintf('%s_DataType', name), dataType); % save the orginial dimension as attribute (needed to restore the orientation: 1xN or Nx1) h5writeatt(fileName, datasetPath, sprintf('%s_Dim', name), dim2str(dim)); % SIMPLE NUMERIC: if it is a numeric with no 3rd dimension and one of the dimension is 1 and the other % does not exceed NUMERIC_ATT_LIMIT, save as attribute elseif isnumeric(dataVal) && numel(dim) <= 2 && any(dim == 1) && ~any(dim > NUMERIC_ATT_LIMIT); % store the field name as being saved as attribute attNames{iName} = name; % save the value as uint8 converted attribute h5writeatt(fileName, datasetPath, sprintf('%s_Value', name), dataVal); % save the orginial data type as attribute h5writeatt(fileName, datasetPath, sprintf('%s_DataType', name), dataType); % save the orginial dimension as attribute (needed to restore the orientation: 1xN or Nx1) h5writeatt(fileName, datasetPath, sprintf('%s_Dim', name), dim2str(dim)); % COMPLEX DATA: if it cannot be saved as attribute, save it as data set using recursion else % create the data set path using that name datasetPathStruct = sprintf('%s/%s', datasetPath, name); % store the field name as being saved as data set datasetNames{iName} = name; % create/write the data set for the value of the field, recursively h5createwrite_wrapper(fileName, datasetPathStruct, dataVal, h5createArgs, h5writeArgs); end; end; % remove the empty cells attNames(cellfun(@isempty, attNames)) = []; datasetNames(cellfun(@isempty, datasetNames)) = []; datasetNamesString = cell2str(datasetNames); attNamesString = cell2str(attNames); % try to get already existing field names try prevFieldsDS = h5readatt(fileName, datasetPath, 'FieldNames_DS'); prevFieldsAtt = h5readatt(fileName, datasetPath, 'FieldNames_Att'); datasetNamesString = regexprep(regexprep([prevFieldsDS, ',', datasetNamesString], ',$', ''), '^,', ''); attNamesString = regexprep(regexprep([prevFieldsAtt, ',', attNamesString], ',$', ''), '^,', ''); catch err; if ~strcmp(err.identifier, 'MATLAB:imagesci:hdf5lib:libraryError'); rethrow(err); end; end; % remove redundant IDs datasetNamesAll = unique(regexp(datasetNamesString, ',', 'split'), 'stable'); datasetNamesString = regexprep(sprintf('%s,', datasetNamesAll{:}), ',$', ''); attNamesAll = unique(regexp(attNamesString, ',', 'split'), 'stable'); attNamesString = regexprep(sprintf('%s,', attNamesAll{:}), ',$', ''); % write the data type as attribute for this structure h5writeatt(fileName, datasetPath, 'DataType', 'struct'); % write both the attribute-saved and the dataset-saved field names as comma-separated string attributes h5writeatt(fileName, datasetPath, 'FieldNames_DS', datasetNamesString); h5writeatt(fileName, datasetPath, 'FieldNames_Att', attNamesString); % if we have 0 or more than an element, process as a struct-array else % linearize the struct-array (e.g. turn a 3 x 4 x 5 cell-array into a 1 x (3*4*5) = 1 * 60 cell-array linData = data(:); % go trough each structure an save it separately for iStruct = 1 : numel(linData); % only save non-empty structures if any(~structfun(@isempty, linData(iStruct))) % create the path using a simple "struct_[STRUCT_INDEX]" path datasetPathStruct = sprintf('%s/struct_%d', datasetPath, iStruct); % create/write the data set for the single structure, recursively h5createwrite_wrapper(fileName, datasetPathStruct, linData(iStruct), h5createArgs, h5writeArgs); end; end; % write some annotation for this data set: get the dimension and the field names dim = size(data); % if the struct-array is empty, make sure the the group is created anyway if isempty(data); h5createIntermediateGroup(fileName, datasetPath); end; % get the field names of the structure(s) names = fieldnames(data); % write in an attribute the data type as being a struct-array h5writeatt(fileName, datasetPath, 'DataType', 'structArray'); % write in an attribute the dimension of the data as a "3x4x5" string h5writeatt(fileName, datasetPath, 'struct_Dim', dim2str(dim)); % write in an attribute the filed names as a comma-separated string h5writeatt(fileName, datasetPath, 'FieldNames', cell2str(names)); end; end
github
HelmchenLabSoftware/OCIA-master
h5deleteGroup.m
.m
OCIA-master/utils/importExport/HDF5/h5deleteGroup.m
762
utf_8
8ef76eb11513fb6fff7cba395bdaa02c
% delete a group in the HDF5 file function h5deleteGroup(fileName, groupPath) % if file does not exist, create a new file using the default properties if ~exist(fileName, 'file'); fID = H5F.create(fileName, 'H5F_ACC_TRUNC', 'H5P_DEFAULT', 'H5P_DEFAULT'); % if file exists, open it using the default properties else fID = H5F.open(fileName, 'H5F_ACC_RDWR', 'H5P_DEFAULT'); end; % check if the group does not already exist try % try to fetch the info for this group ... H5G.get_objinfo(fID, groupPath, false); % ... if no error, then group exists, so go on ... catch err; %#ok<NASGU> % error means no group, so nothing to do return; end; % delete the object H5L.delete(fID, groupPath, 'H5P_DEFAULT'); % close all H5F.close(fID); end
github
HelmchenLabSoftware/OCIA-master
xcorr_mc.m
.m
OCIA-master/utils/stat/xcorr_mc.m
1,122
utf_8
bb01c55ef67edb3bbe21ccc25ae74ecb
function [cc,p,cc_mc] = xcorr_mc(x,y,maxlags,n) % monte-carlo cross-correlation of x and y % Input % x ... input vector 1 (will be shuffled) % y ... input vector 2 (will NOT be shuffled) % lag ... lag for xcorr % n ... number of samples for shuffled data % Output % cc ... the true cross-correlation between x and y % p ... probability of correlation for each time point % cc_mc ... the matrix of shuffled cross-correlation values % this file written by Henry Luetcke ([email protected]) % force columns vectors x = reshape(x,numel(x),1); y = reshape(y,numel(y),1); % true cross-correlation cc = xcorr(x,y,maxlags,'coeff'); % shuffled cross-correlation cc_mc = doShuffledXcorr(x,y,maxlags,n); % estimate the 2-tailed probability of true cc at each timepoint p = doStats(cc_mc,cc); function cc_mc = doShuffledXcorr(x,y,maxlags,n) cc_mc = zeros(maxlags*2+1,n); for i = 1:n xPerm = x(randperm(numel(x))); cc_mc(:,i) = xcorr(xPerm,y,maxlags,'coeff'); end function p = doStats(A,c) p = zeros(size(A,1),1); for n = 1:size(A,1) [mu,sigma] = normfit(A(n,:)); p(n) = 1 - (normcdf(abs(c(n)),mu,sigma)); end
github
HelmchenLabSoftware/OCIA-master
sparseness.m
.m
OCIA-master/utils/stat/sparseness.m
1,021
utf_8
9e7d0a6350274c815488872e8005f081
function k = sparseness(varargin) % calculate sparseness measure k for response vector r (in1) with method % (in2) % methods: % {'kurtosis'} % 'treves_rolls' % 'willmore_tolhurst' % this file written by Henry Luetcke ([email protected]) if nargin == 1 r = varargin{1}; method = 'kurtosis'; elseif nargin == 2 r = varargin{1}; method = varargin{2}; else error('Incorrect number of input arguments.'); end switch lower(method) case 'kurtosis' k = doKurtosis(r); case 'treves_rolls' k = doTrevesRolls(r); case 'willmore_tolhurst' k = doWillmoreTolhurst(r); end function k = doKurtosis(r) mean_r = mean(r); sd_r = std(r); k = zeros(size(r)); for n = 1:length(r) k(n) = ((r(n)-mean_r)/sd_r)^4; end k = sum(k)/length(r); k = k - 3; function k = doTrevesRolls(r) k1 = sum(r/length(r)); k1 = k1^2; k2 = sum((r.^2)/length(r)); k = k1 / k2; function k = doWillmoreTolhurst(r) k1 = sum(abs(r)/length(r)); k1 = k1^2; k2 = sum((r.^2)/length(r)); k = 1 - (k1 / k2);
github
HelmchenLabSoftware/OCIA-master
fit_fminsearch.m
.m
OCIA-master/utils/matlabExtend/fit_fminsearch.m
1,098
utf_8
aba55d992c51d5e7750b6453a19ddde2
function fit_fminsearch % simulate a double-peaked Gaussian a = normrnd(1,0.5,[10000,1]); a = [a; normrnd(3,0.5,[10000,1])]; [count,xout] = hist(a,sqrt(numel(a))); figure('Name','Fit fun figure','NumberTitle','off') stairs(xout,count,'k-'), hold on %% fit with curve fitting toolbox % fit double-peaked gaussian to histogram fObj = fit(xout',count','gauss2'); plot(fObj,'r--') %% fit with fminsearch % (no curve fitting toolbox required) % start points x0 should be chosen as precisely as possible pars0 = [max(count) 1 1 max(count) 1 1]'; [x, fval] = fminsearch(@(x) gauss2(x,count,xout),pars0); % x contains the optimal 6 parameters for the Gaussian % fval is the minimum of the objective function, ie. the smaller the better the fit fitCurve = x(1).*exp(-((xout-x(2))./x(3)).^2) + ... x(4).*exp(-((xout-x(5))./x(6)).^2); plot(xout,fitCurve,'b--') legend({'dota','fit','fminsearch'}) end %% Objective function for minimization function fOut = gauss2(pars,a,x) f = pars(1).*exp(-((x-pars(2))./pars(3)).^2) + ... pars(4).*exp(-((x-pars(5))./pars(6)).^2); fOut = sum(abs(f-a)); end
github
HelmchenLabSoftware/OCIA-master
mydepfun.m
.m
OCIA-master/utils/matlabExtend/mydepfun.m
3,300
utf_8
4b01dad21c371327373768234c3dc9be
function filelist = mydepfun(fn,recursive) %MYDEPFUN - Variation on depfun which skips toolbox files % % filelist = mydepfun(fn) % filelist = mydepfun(fn,recursive) % % Returns a list of files which are required by the specified % function, omitting any which are inside $matlabroot/toolbox. % % "fn" is a string specifying a filename in any form that can be % identified by the built-in function "which". % "recursive" is a logical scalar; if false, only the files called % directly by the specified function are returned. If true, *all* % those files are scanned to, and any required by those, and so on. % % "filelist" is a cell array of fully qualified file name strings, % including the specified file. % % e.g. % filelist = mydepfun('myfunction') % filelist = mydepfun('C:\files\myfunction.m',true) % Copyright 2006-2010 The MathWorks, Inc. if ~ischar(fn) error('First argument must be a string'); end foundfile = which(fn); if isempty(foundfile) error('File not found: %s',fn); end % Scan this file filelist = i_scan(foundfile); % If "recursive" is supplied and true, scan files on which this one depends. if nargin>1 && recursive % Create a list of files which we have still to scan. toscan = filelist; toscan = toscan(2:end); % first entry is always the same file again % Now scan files until we have none left to scan while numel(toscan)>0 % Scan the first file on the list newlist = i_scan(toscan{1}); newlist = newlist(2:end); % first entry is always the same file again toscan(1) = []; % remove the file we've just scanned % Find out which files are not already on the list. Take advantage of % the fact that "which" and "depfun" return the correct capitalisation % of file names, even on Windows, making it safe to use "ismember" % (which is case-sensitive). reallynew = ~ismember(newlist,filelist); newlist = newlist(reallynew); % If they're not already in the file list, we'll need to scan them too. % (Conversely, if they ARE in the file list, we've either scanned them % already, or they're currently on the toscan list) % fprintf('%dx%d - %dx%d\n', size(newlist), size(toscan)); toscan2 = toscan; toscan = unique( [ toscan2 ; newlist ] ); filelist = unique( [ filelist ; newlist ] ); fprintf('filelist size: %d\n', numel(filelist)); end end %%%%%%%%%%%%%%%%%%%%% % Returns the non-toolbox files which the specified one calls. % The specified file is always first in the returned list. function list = i_scan(f) func = i_function_name(f); list = matlab.codetools.requiredFilesAndProducts(func, 'toponly')'; % list = depfun(func,'-toponly','-quiet'); toolboxroot = fullfile(matlabroot,'toolbox'); intoolbox = strncmpi(list,toolboxroot,numel(toolboxroot)); list = list(~intoolbox); %%%%%%%%%%%%%%%%%%%%%%%% function func = i_function_name(f) % Identifies the function name for the specified file, % including the class name where appropriate. Does not % work for UDD classes, e.g. @rtw/@rtw [dirname,funcname] = fileparts(f); [ignore,dirname] = fileparts(dirname); if ~isempty(dirname) && dirname(1)=='@' func = [ dirname '/' funcname ]; else func = funcname; end
github
HelmchenLabSoftware/OCIA-master
smoothn.m
.m
OCIA-master/utils/matlabExtend/smoothn.m
3,357
utf_8
880f4a892aa0f80387fc54388891b162
function Y = smoothn(X,sz,filt,std) %SMOOTHN Smooth N-D data % Y = SMOOTHN(X, SIZE) smooths input data X. The smoothed data is % retuirned in Y. SIZE sets the size of the convolution kernel % such that LENGTH(SIZE) = NDIMS(X) % % Y = SMOOTHN(X, SIZE, FILTER) Filter can be 'gaussian' or 'box' (default) % and determines the convolution kernel. % % Y = SMOOTHN(X, SIZE, FILTER, STD) STD is a vector of standard deviations % one for each dimension, when filter is 'gaussian' (default is 0.65) if nargin == 2, filt = 'b'; elseif nargin == 3, std = 0.65; elseif nargin>4 || nargin<2 error('Wrong number of input arguments.'); end % check the correctness of sz if ndims(sz) > 2 || min(size(sz)) ~= 1 error('SIZE must be a vector'); elseif length(sz) == 1 sz = repmat(sz,ndims(X)); elseif ndims(X) ~= length(sz) error('SIZE must be a vector of length equal to the dimensionality of X'); end % check the correctness of std if filt(1) == 'g' if length(std) == 1 std = std*ones(ndims(X),1); elseif ndims(X) ~= length(std) error('STD must be a vector of length equal to the dimensionality of X'); end std = std(:)'; end sz = sz(:)'; % check for appropriate size padSize = (sz-1)/2; if ~isequal(padSize, floor(padSize)) || any(padSize<0) error('All elements of SIZE must be odd integers >= 1.'); end % generate the convolution kernel based on the choice of the filter filt = lower(filt); if (filt(1) == 'b') smooth = ones(sz)/prod(sz); % box filter in N-D elseif (filt(1) == 'g') smooth = ndgaussian(padSize,std); % a gaussian filter in N-D else error('Unknown filter'); end % pad the data X = padreplicate(X,padSize); % perform the convolution Y = convn(X,smooth,'valid'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = ndgaussian(siz,std) % Calculate a non-symmetric ND gaussian. Note that STD is scaled to the % sizes in SIZ as STD = STD.*SIZ ndim = length(siz); sizd = cell(ndim,1); for i = 1:ndim sizd{i} = -siz(i):siz(i); end grid = gridnd(sizd); std = reshape(std.*siz,[ones(1,ndim) ndim]); std(find(siz==0)) = 1; % no smoothing along these dimensions as siz = 0 std = repmat(std,2*siz+1); h = exp(-sum((grid.*grid)./(2*std.*std),ndim+1)); h = h/sum(h(:)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function argout = gridnd(argin) % exactly the same as ndgrid but it accepts only one input argument of % type cell and a single output array nin = length(argin); nout = nin; for i=nin:-1:1, argin{i} = full(argin{i}); % Make sure everything is full siz(i) = prod(size(argin{i})); end if length(siz)<nout, siz = [siz ones(1,nout-length(siz))]; end argout = []; for i=1:nout, x = argin{i}(:); % Extract and reshape as a vector. s = siz; s(i) = []; % Remove i-th dimension x = reshape(x(:,ones(1,prod(s))),[length(x) s]); % Expand x x = permute(x,[2:i 1 i+1:nout]); % Permute to i'th dimension argout = cat(nin+1,argout,x); % Concatenate to the output end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b=padreplicate(a, padSize) %Pad an array by replicating values. numDims = length(padSize); idx = cell(numDims,1); for k = 1:numDims M = size(a,k); onesVector = ones(1,padSize(k)); idx{k} = [onesVector 1:M M*onesVector]; end b = a(idx{:});
github
HelmchenLabSoftware/OCIA-master
DataHash.m
.m
OCIA-master/utils/matlabExtend/DataHash.m
15,429
utf_8
e725a80cb9180de1eb03e47b850a95dc
function Hash = DataHash(Data, Opt) % DATAHASH - Checksum for Matlab array of any type % This function creates a hash value for an input of any type. The type and % dimensions of the input are considered as default, such that UINT8([0,0]) and % UINT16(0) have different hash values. Nested STRUCTs and CELLs are parsed % recursively. % % Hash = DataHash(Data, Opt) % INPUT: % Data: Array of these built-in types: % (U)INT8/16/32/64, SINGLE, DOUBLE, (real or complex) % CHAR, LOGICAL, CELL (nested), STRUCT (scalar or array, nested), % function_handle. % Opt: Struct to specify the hashing algorithm and the output format. % Opt and all its fields are optional. % Opt.Method: String, known methods for Java 1.6 (Matlab 2009a): % 'SHA-1', 'SHA-256', 'SHA-384', 'SHA-512', 'MD2', 'MD5'. % Known methods for Java 1.3 (Matlab 6.5): % 'MD5', 'SHA-1'. % Default: 'MD5'. % Opt.Format: String specifying the output format: % 'hex', 'HEX': Lower/uppercase hexadecimal string. % 'double', 'uint8': Numerical vector. % 'base64': Base64 encoded string, only printable % ASCII characters, 33% shorter than 'hex'. % Default: 'hex'. % Opt.Input: Type of the input as string, not case-sensitive: % 'array': The contents, type and size of the input [Data] are % considered for the creation of the hash. Nested CELLs % and STRUCT arrays are parsed recursively. Empty arrays of % different type reply different hashs. % 'file': [Data] is treated as file name and the hash is calculated % for the files contents. % 'bin': [Data] is a numerical, LOGICAL or CHAR array. Only the % binary contents of the array is considered, such that % e.g. empty arrays of different type reply the same hash. % Default: 'array'. % % OUTPUT: % Hash: String, DOUBLE or UINT8 vector. The length depends on the hashing % method. % % EXAMPLES: % % Default: MD5, hex: % DataHash([]) % 7de5637fd217d0e44e0082f4d79b3e73 % % MD5, Base64: % Opt.Format = 'base64'; % Opt.Method = 'MD5'; % DataHash(int32(1:10), Opt) % bKdecqzUpOrL4oxzk+cfyg % % SHA-1, Base64: % S.a = uint8([]); % S.b = {{1:10}, struct('q', uint64(415))}; % Opt.Method = 'SHA-1'; % DataHash(S, Opt) % ZMe4eUAp0G9TDrvSW0/Qc0gQ9/A % % SHA-1 of binary values: % Opt.Method = 'SHA-1'; % Opt.Input = 'bin'; % DataHash(1:8, Opt) % 826cf9d3a5d74bbe415e97d4cecf03f445f69225 % % NOTE: % Function handles and user-defined objects cannot be converted uniquely: % - The subfunction ConvertFuncHandle uses the built-in function FUNCTIONS, % but the replied struct can depend on the Matlab version. % - It is tried to convert objects to UINT8 streams in the subfunction % ConvertObject. A conversion by STRUCT() might be more appropriate. % Adjust these subfunctions on demand. % % MATLAB CHARs have 16 bits! In consequence the string 'hello' is treated as % UINT16('hello') for the binary input method. % % DataHash uses James Tursa's smart and fast TYPECASTX, if it is installed: % http://www.mathworks.com/matlabcentral/fileexchange/17476 % As fallback the built-in TYPECAST is used automatically, but for large % inputs this can be more than 100 times slower. % For Matlab 6.5 installing typecastx is obligatory to run DataHash. % % Tested: Matlab 6.5, 7.7, 7.8, 7.13, WinXP/32, Win7/64 % Author: Jan Simon, Heidelberg, (C) 2011-2012 matlab.THISYEAR(a)nMINUSsimon.de % % See also: TYPECAST, CAST. % FEX: % Michael Kleder, "Compute Hash", no structs and cells: % http://www.mathworks.com/matlabcentral/fileexchange/8944 % Tim, "Serialize/Deserialize", converts structs and cells to a byte stream: % http://www.mathworks.com/matlabcentral/fileexchange/29457 % Jan Simon, "CalcMD5", MD5 only, faster C-mex, no structs and cells: % http://www.mathworks.com/matlabcentral/fileexchange/25921 % $JRev: R-k V:011 Sum:kZG25iszfKbg Date:28-May-2012 12:48:06 $ % $License: BSD (use/copy/change/redistribute on own risk, mention the author) $ % $File: Tools\GLFile\DataHash.m $ % History: % 001: 01-May-2011 21:52, First version. % 007: 10-Jun-2011 10:38, [Opt.Input], binary data, complex values considered. % 011: 26-May-2012 15:57, Fails for binary input and empty data. % Main function: =============================================================== % Java is needed: if ~usejava('jvm') error(['JSimon:', mfilename, ':NoJava'], ... '*** %s: Java is required.', mfilename); end % typecastx creates a shared data copy instead of the deep copy as Matlab's % TYPECAST - for a [1000x1000] DOUBLE array this is 100 times faster! persistent usetypecastx if isempty(usetypecastx) usetypecastx = ~isempty(which('typecastx')); % Run the slow WHICH once only end % Default options: ------------------------------------------------------------- Method = 'MD5'; OutFormat = 'hex'; isFile = false; isBin = false; % Check number and type of inputs: --------------------------------------------- nArg = nargin; if nArg == 2 if isa(Opt, 'struct') == 0 % Bad type of 2nd input: error(['JSimon:', mfilename, ':BadInput2'], ... '*** %s: 2nd input [Opt] must be a struct.', mfilename); end % Specify hash algorithm: if isfield(Opt, 'Method') Method = upper(Opt.Method); end % Specify output format: if isfield(Opt, 'Format') OutFormat = Opt.Format; end % Check if the Input type is specified - default: 'array': if isfield(Opt, 'Input') if strcmpi(Opt.Input, 'File') isFile = true; if ischar(Data) == 0 error(['JSimon:', mfilename, ':CannotOpen'], ... '*** %s: 1st input is not a file name', mfilename); end if exist(Data, 'file') ~= 2 error(['JSimon:', mfilename, ':FileNotFound'], ... '*** %s: File not found: %s.', mfilename, Data); end elseif strncmpi(Opt.Input, 'bin', 3) % Accept 'binary' isBin = true; if (isnumeric(Data) || ischar(Data) || islogical(Data)) == 0 error(['JSimon:', mfilename, ':BadDataType'], ... '*** %s: 1st input is not numeric, CHAR or LOGICAL.', mfilename); end end end elseif nArg ~= 1 % Bad number of arguments: error(['JSimon:', mfilename, ':BadNInput'], ... '*** %s: 1 or 2 inputs required.', mfilename); end % Create the engine: ----------------------------------------------------------- try Engine = java.security.MessageDigest.getInstance(Method); catch error(['JSimon:', mfilename, ':BadInput2'], ... '*** %s: Invalid algorithm: [%s].', mfilename, Method); end % Create the hash value: ------------------------------------------------------- if isFile % Read the file and calculate the hash: FID = fopen(Data, 'r'); if FID < 0 error(['JSimon:', mfilename, ':CannotOpen'], ... '*** %s: Cannot open file: %s.', mfilename, Data); end Data = fread(FID, Inf, '*uint8'); fclose(FID); Engine.update(Data); if usetypecastx Hash = typecastx(Engine.digest, 'uint8'); else Hash = typecast(Engine.digest, 'uint8'); end elseif isBin % Contents of an elementary array: if isempty(Data) % Nothing to do, Engine.update fails for empty input! Hash = typecastx(Engine.digest, 'uint8'); elseif usetypecastx % Faster typecastx: if isreal(Data) Engine.update(typecastx(Data(:), 'uint8')); else Engine.update(typecastx(real(Data(:)), 'uint8')); Engine.update(typecastx(imag(Data(:)), 'uint8')); end Hash = typecastx(Engine.digest, 'uint8'); else % Matlab's TYPECAST is less elegant: if isnumeric(Data) if isreal(Data) Engine.update(typecast(Data(:), 'uint8')); else Engine.update(typecast(real(Data(:)), 'uint8')); Engine.update(typecast(imag(Data(:)), 'uint8')); end elseif islogical(Data) % TYPECAST cannot handle LOGICAL Engine.update(typecast(uint8(Data(:)), 'uint8')); elseif ischar(Data) % TYPECAST cannot handle CHAR Engine.update(typecast(uint16(Data(:)), 'uint8')); Engine.update(typecast(Data(:), 'uint8')); end Hash = typecast(Engine.digest, 'uint8'); end elseif usetypecastx % Faster typecastx: Engine = CoreHash_(Data, Engine); Hash = typecastx(Engine.digest, 'uint8'); else % Slower built-in TYPECAST: Engine = CoreHash(Data, Engine); Hash = typecast(Engine.digest, 'uint8'); end % Convert hash specific output format: ----------------------------------------- switch OutFormat case 'hex' Hash = sprintf('%.2x', double(Hash)); case 'HEX' Hash = sprintf('%.2X', double(Hash)); case 'double' Hash = double(reshape(Hash, 1, [])); case 'uint8' Hash = reshape(Hash, 1, []); case 'base64' Hash = fBase64_enc(double(Hash)); otherwise error(['JSimon:', mfilename, ':BadOutFormat'], ... '*** %s: [Opt.Format] must be: HEX, hex, uint8, double, base64.', ... mfilename); end % return; % ****************************************************************************** function Engine = CoreHash_(Data, Engine) % This mothod uses the faster typecastx version. % Consider the type and dimensions of the array to distinguish arrays with the % same data, but different shape: [0 x 0] and [0 x 1], [1,2] and [1;2], % DOUBLE(0) and SINGLE([0,0]): Engine.update([uint8(class(Data)), typecastx(size(Data), 'uint8')]); if isstruct(Data) % Hash for all array elements and fields: F = sort(fieldnames(Data)); % Ignore order of fields Engine = CoreHash_(F, Engine); % Catch the fieldnames for iS = 1:numel(Data) % Loop over elements of struct array for iField = 1:length(F) % Loop over fields Engine = CoreHash_(Data(iS).(F{iField}), Engine); end end elseif iscell(Data) % Get hash for all cell elements: for iS = 1:numel(Data) Engine = CoreHash_(Data{iS}, Engine); end elseif isnumeric(Data) || islogical(Data) || ischar(Data) if isempty(Data) == 0 if isreal(Data) % TRUE for LOGICAL and CHAR also: Engine.update(typecastx(Data(:), 'uint8')); else % typecastx accepts complex input: Engine.update(typecastx(real(Data(:)), 'uint8')); Engine.update(typecastx(imag(Data(:)), 'uint8')); end end elseif isa(Data, 'function_handle') Engine = CoreHash(ConvertFuncHandle(Data), Engine); else % Most likely this is a user-defined object: try Engine = CoreHash(ConvertObject(Data), Engine); catch warning(['JSimon:', mfilename, ':BadDataType'], ... ['Type of variable not considered: ', class(Data)]); end end % return; % ****************************************************************************** function Engine = CoreHash(Data, Engine) % This methods uses the slower TYPECAST of Matlab % See CoreHash_ for comments. Engine.update([uint8(class(Data)), typecast(size(Data), 'uint8')]); if isstruct(Data) % Hash for all array elements and fields: F = sort(fieldnames(Data)); % Ignore order of fields Engine = CoreHash(F, Engine); % Catch the fieldnames for iS = 1:numel(Data) % Loop over elements of struct array for iField = 1:length(F) % Loop over fields Engine = CoreHash(Data(iS).(F{iField}), Engine); end end elseif iscell(Data) % Get hash for all cell elements: for iS = 1:numel(Data) Engine = CoreHash(Data{iS}, Engine); end elseif isempty(Data) elseif isnumeric(Data) if isreal(Data) Engine.update(typecast(Data(:), 'uint8')); else Engine.update(typecast(real(Data(:)), 'uint8')); Engine.update(typecast(imag(Data(:)), 'uint8')); end elseif islogical(Data) % TYPECAST cannot handle LOGICAL Engine.update(typecast(uint8(Data(:)), 'uint8')); elseif ischar(Data) % TYPECAST cannot handle CHAR Engine.update(typecast(uint16(Data(:)), 'uint8')); elseif isa(Data, 'function_handle') Engine = CoreHash(ConvertFuncHandle(Data), Engine); else % Most likely a user-defined object: try Engine = CoreHash(ConvertObject(Data), Engine); catch warning(['JSimon:', mfilename, ':BadDataType'], ... ['Type of variable not considered: ', class(Data)]); end end % return; % ****************************************************************************** function FuncKey = ConvertFuncHandle(FuncH) % The subfunction ConvertFuncHandle converts function_handles to a struct % using the Matlab function FUNCTIONS. The output of this function changes % with the Matlab version, such that DataHash(@sin) replies different hashes % under Matlab 6.5 and 2009a. % An alternative is using the function name and name of the file for % function_handles, but this is not unique for nested or anonymous functions. % If the MATLABROOT is removed from the file's path, at least the hash of % Matlab's toolbox functions is (usually!) not influenced by the version. % Finally I'm in doubt if there is a unique method to hash function handles. % Please adjust the subfunction ConvertFuncHandles to your needs. % The Matlab version influences the conversion by FUNCTIONS: % 1. The format of the struct replied FUNCTIONS is not fixed, % 2. The full paths of toolbox function e.g. for @mean differ. FuncKey = functions(FuncH); % ALTERNATIVE: Use name and path. The <matlabroot> part of the toolbox functions % is replaced such that the hash for @mean does not depend on the Matlab % version. % Drawbacks: Anonymous functions, nested functions... % funcStruct = functions(FuncH); % funcfile = strrep(funcStruct.file, matlabroot, '<MATLAB>'); % FuncKey = uint8([funcStruct.function, ' ', funcfile]); % Finally I'm afraid there is no unique method to get a hash for a function % handle. Please adjust this conversion to your needs. % return; % ****************************************************************************** function DataBin = ConvertObject(DataObj) % Convert a user-defined object to a binary stream. There cannot be a unique % solution, so this part is left for the user... % Perhaps a direct conversion is implemented: DataBin = uint8(DataObj); % Or perhaps this is better: % DataBin = struct(DataObj); % return; % ****************************************************************************** function Out = fBase64_enc(In) % Encode numeric vector of UINT8 values to base64 string. Pool = [65:90, 97:122, 48:57, 43, 47]; % [0:9, a:z, A:Z, +, /] v8 = [128; 64; 32; 16; 8; 4; 2; 1]; v6 = [32, 16, 8, 4, 2, 1]; In = reshape(In, 1, []); X = rem(floor(In(ones(8, 1), :) ./ v8(:, ones(length(In), 1))), 2); Y = reshape([X(:); zeros(6 - rem(numel(X), 6), 1)], 6, []); Out = char(Pool(1 + v6 * Y)); % return;
github
HelmchenLabSoftware/OCIA-master
gencode_rvalue.m
.m
OCIA-master/utils/matlabExtend/gencode/gencode_rvalue.m
4,540
utf_8
461c5aa9248a9962253bec5ce7d36038
function [str, sts] = gencode_rvalue(item) % GENCODE_RVALUE Code for right hand side of MATLAB assignment % Generate the right hand side for a valid MATLAB variable % assignment. This function is a helper to GENCODE, but can be used on % its own to generate code for the following types of variables: % * scalar, 1D or 2D numeric, logical or char arrays % * scalar or 1D cell arrays, where each item can be one of the supported % array types (i.e. nested cells are allowed) % % function [str, sts] = gencode_rvalue(item) % Input argument: % item - value to generate code for % Output arguments: % str - cellstr with generated code, line per line % sts - true, if successful, false if code could not be generated % % See also GENCODE, GENCODE_SUBSTRUCT, GENCODE_SUBSTRUCTCODE. % % This code has been developed as part of a batch job configuration % system for MATLAB. See % http://sourceforge.net/projects/matlabbatch % for details about the original project. %_______________________________________________________________________ % Copyright (C) 2007 Freiburg Brain Imaging % Volkmar Glauche % $Id: gencode_rvalue.m 410 2009-06-23 11:47:26Z glauche $ rev = '$Rev: 410 $'; %#ok str = {}; sts = true; switch class(item) case 'char' if ndims(item) == 2 cstr = {''}; % Create cell string, keep white space padding for k = 1:size(item,1) cstr{k} = item(k,:); end str1 = genstrarray(cstr); if numel(str1) == 1 % One string, do not print brackets str = str1; else % String array, print brackets and concatenate str1 str = [ {'['} str1(:)' {']'} ]; end else % not an rvalue sts = false; end case 'cell' if isempty(item) str = {'{}'}; elseif ndims(item) == 2 && any(size(item) == 1) str1 = {}; for k = 1:numel(item) [str2 sts] = gencode_rvalue(item{k}); if ~sts break; end str1 = [str1(:)' str2(:)']; end if sts if numel(str1) == 1 % One item, print as one line str{1} = sprintf('{%s}', str1{1}); else % Cell vector, print braces and concatenate str1 if size(item,1) == 1 endstr = {'}'''}; else endstr = {'}'}; end str = [{'{'} str1(:)' endstr]; end end else sts = false; end case 'function_handle' if isempty(item) str{1} = 'function_handle.empty;'; else fstr = func2str(item); % sometimes (e.g. for anonymous functions) '@' is already included % in func2str output if fstr(1) == '@' str{1} = fstr; else str{1} = sprintf('@%s', fstr); end end otherwise if isobject(item) || ~(isnumeric(item) || islogical(item)) || issparse(item) || ndims(item) > 2 sts = false; else % treat item as numeric or logical, don't create 'class'(...) % classifier code for double clsitem = class(item); if isempty(item) if strcmp(clsitem, 'double') str{1} = '[]'; else str{1} = sprintf('%s([])', clsitem); end else % Use mat2str with standard precision 15 if any(strcmp(clsitem, {'double', 'logical'})) sitem = mat2str(item); else sitem = mat2str(item,'class'); end bsz = max(numel(sitem)+2,100); % bsz needs to be > 100 and larger than string length str1 = textscan(sitem, '%s', 'delimiter',';', 'bufsize',bsz); if numel(str1{1}) > 1 str = str1{1}; else str{1} = str1{1}{1}; end end end end function str = genstrarray(stritem) % generate a cell string of properly quoted strings suitable for code % generation. str = strrep(stritem, '''', ''''''); for k = 1:numel(str) str{k} = sprintf('"%s"', str{k}); end
github
HelmchenLabSoftware/OCIA-master
gencode.m
.m
OCIA-master/utils/matlabExtend/gencode/gencode.m
8,361
utf_8
7355f9b9b8500373a07c87da2f3deab7
function [str, tag, cind] = gencode(item, tag, tagctx) % GENCODE Generate code to recreate any MATLAB struct/cell variable. % For any MATLAB variable, this function generates a .m file that % can be run to recreate it. Classes can implement their class specific % equivalent of gencode with the same calling syntax. By default, classes % are treated similar to struct variables. % % [str, tag, cind] = gencode(item, tag, tagctx) % Input arguments: % item - MATLAB variable to generate code for (the variable itself, not its % name) % tag - optional: name of the variable, i.e. what will be displayed left % of the '=' sign. This can also be a valid struct/cell array % reference, like 'x(2).y'. If not provided, inputname(1) will be % used. % tagctx - optional: variable names not to be used (e.g. keywords, % reserved variables). A cell array of strings. % Output arguments: % str - cellstr containing code lines to reproduce the input variable % tag - name of the generated variable (equal to input tag) % cind - index into str to the line where the variable assignment is coded % (usually 1st line for non-object variables) % % See also GENCODE_RVALUE, GENCODE_SUBSTRUCT, GENCODE_SUBSTRUCTCODE. % % This code has been developed as part of a batch job configuration % system for MATLAB. See % http://sourceforge.net/projects/matlabbatch % for details about the original project. %_______________________________________________________________________ % Copyright (C) 2007 Freiburg Brain Imaging % Volkmar Glauche % $Id: gencode.m 410 2009-06-23 11:47:26Z glauche $ rev = '$Rev: 410 $'; %#ok if nargin < 2 tag = inputname(1); end; if nargin < 3 tagctx = {}; end if isempty(tag) tag = genvarname('val', tagctx); end; % Item count cind = 1; % try to generate rvalue code [rstr sts] = gencode_rvalue(item); if sts lvaleq = sprintf('%s = ', tag); if numel(rstr) == 1 str{1} = sprintf('%s%s;', lvaleq, rstr{1}); else str = cell(size(rstr)); indent = {repmat(' ', 1, numel(lvaleq)+1)}; str{1} = sprintf('%s%s', lvaleq, rstr{1}); str(2:end-1) = strcat(indent, rstr(2:end-1)); str{end} = sprintf('%s%s;', indent{1}, rstr{end}); if numel(str) > 10 % add cell mode comment to structure longer output str = [{'%%'} str(:)' {'%%'}]; end end else switch class(item) case 'char' str = {}; szitem = size(item); subs = gensubs('()', {':',':'}, szitem(3:end)); for k = 1:numel(subs) substag = gencode_substruct(subs{k}, tag); str1 = gencode(subsref(item, subs{k}), substag{1}, tagctx); str = [str(:)' str1(:)']; end case 'cell' str = {}; szitem = size(item); subs = gensubs('{}', {}, szitem); for k = 1:numel(subs) substag = gencode_substruct(subs{k}, tag); str1 = gencode(subsref(item, subs{k}), substag{1}, tagctx); str = [str(:)' str1(:)']; end case 'struct' str = gencode_structobj(item, tag, tagctx); otherwise if isobject(item) || ~(isnumeric(item) || islogical(item)) % This branch is hit for objects without a gencode method try % try to generate code in a struct-like fashion str = gencode_structobj(item, tag, tagctx); catch % failed - generate a warning in generated code and % warn directly str = {sprintf('warning(''%s: No code generated for object of class %s.'')', tag, class(item))}; if any(exist('cfg_message') == 2:6) cfg_message('matlabbatch:gencode:unknown', ... '%s: Code generation for objects of class "%s" must be implemented as object method.', tag, class(item)); else warning('gencode:unknown', ... '%s: Code generation for objects of class "%s" must be implemented as object method.', tag, class(item)); end end elseif issparse(item) % recreate sparse matrix from indices [tmpi tmpj tmps] = find(item); [stri tagi cindi] = gencode(tmpi); [strj tagj cindj] = gencode(tmpj); [strs tags cinds] = gencode(tmps); str = [stri(:)' strj(:)' strs(:)']; cind = cind + cindi + cindj + cinds; str{end+1} = sprintf('%s = sparse(tmpi, tmpj, tmps);', tag); else str = {}; szitem = size(item); subs = gensubs('()', {':',':'}, szitem(3:end)); for k = 1:numel(subs) substag = gencode_substruct(subs{k}, tag); str1 = gencode(subsref(item, subs{k}), substag{1}, tagctx); str = [str(:)' str1(:)']; end end end end function subs = gensubs(type, initdims, sz) % generate a cell array of subscripts into trailing dimensions of % n-dimensional arrays. Type is the subscript type (either '()' or '{}'), % initdims is a cell array of leading subscripts that will be prepended to % the generated subscripts and sz contains the size of the remaining % dimensions. % deal with special case of row vectors - only add one subscript in this % case if numel(sz) == 2 && sz(1) == 1 && isempty(initdims) ind = 1:sz(2); else % generate index array, rightmost index varying fastest ind = 1:sz(1); for k = 2:numel(sz) ind = [kron(ind, ones(1,sz(k))); kron(ones(1,size(ind,2)), 1:sz(k))]; end; end; subs = cell(1,size(ind,2)); % for each column of ind, generate a separate subscript structure for k = 1:size(ind,2) cellind = num2cell(ind(:,k)); subs{k} = substruct(type, [initdims(:)' cellind(:)']); end; function str = gencode_structobj(item, tag, tagctx) % Create code for a struct array. Also used as fallback for object % arrays, if the object does not provide its own gencode implementation. citem = class(item); % try to figure out fields/properties that can be set if isobject(item) && exist('metaclass','builtin') mobj = metaclass(item); % Only create code for properties which are % * not dependent or dependent and have a SetMethod % * not constant % * not abstract % * have public SetAccess sel = cellfun(@(cProp)(~cProp.Constant && ... ~cProp.Abstract && ... (~cProp.Dependent || ... (cProp.Dependent && ... ~isempty(cProp.SetMethod))) && ... strcmp(cProp.SetAccess,'public')),mobj.Properties); fn = cellfun(@(cProp)subsref(cProp,substruct('.','Name')),mobj.Properties(sel),'uniformoutput',false); else % best guess fn = fieldnames(item); end if isempty(fn) if isstruct(item) str{1} = sprintf('%s = struct([]);', tag); else str{1} = sprintf('%s = %s;', tag, citem); end elseif isempty(item) if isstruct(item) fn = strcat('''', fn, '''', ', {}'); str{1} = sprintf('%s = struct(', tag); for k = 1:numel(fn)-1 str{1} = sprintf('%s%s, ', str{1}, fn{k}); end str{1} = sprintf('%s%s);', str{1}, fn{end}); else str{1} = sprintf('%s = %s.empty;', tag, citem); end elseif numel(item) == 1 if isstruct(item) str = {}; else str{1} = sprintf('%s = %s;', tag, citem); end for l = 1:numel(fn) str1 = gencode(item.(fn{l}), sprintf('%s.%s', tag, fn{l}), tagctx); str = [str(:)' str1(:)']; end else str = {}; szitem = size(item); subs = gensubs('()', {}, szitem); for k = 1:numel(subs) if ~isstruct(item) str{end+1} = sprintf('%s = %s;', gencode_substruct(subs{k}, tag), citem); end for l = 1:numel(fn) csubs = [subs{k} substruct('.', fn{l})]; substag = gencode_substruct(csubs, tag); str1 = gencode(subsref(item, csubs), substag{1}, tagctx); str = [str(:)' str1(:)']; end end end
github
HelmchenLabSoftware/OCIA-master
profile_history.m
.m
OCIA-master/utils/matlabExtend/profile_history/profile_history.m
21,451
utf_8
09cf826e21a726826828395761ce3c13
function profile_history(profData, initialDetail, varargin) % profile_history - display profiling data as a timeline history % % profile_history analyzes the latest profiling session and displays the % function-call timings and durations in a graphical timeline. The function % labels and timeline bars are clickable, linking to their respective % detailed profiling report (of the builtin Matlab profiler). % % profile_history(profData) displays the timeline of a specific profiling % session, that was previously stored via a profData=profile('info') command. % % profile_history(initialDetail) or profile_history(profData,initialDetail) % displays the timeline showing an initial detail level of a specified number % of functions (default initialDetail=15). The detail level can then be % changed interactively, using a slider at the bottom of the figure. % % Sample usage: % profile on; myProgram(); profile_history % profile on; myProgram(); profData=profile('info'); profile_history(profData) % profile_history(20); % profile_history(profData,15); % % Technical description: % http://UndocumentedMatlab.com/blog/function-call-timeline-profiling % % Note: % profile_history uses a wrapper function for the built-in profile.m % that is located in the @char subfolder. If for some reason you see % problems when running the profiler, simply delete the @char folder. % In order to be able to use profile_history after you delete the @char % folder, add the -timestamp parameter whenever you profile: % profile on -timestamp; myProgram(); profile_history % (adding the -timestamp parameter is not needed when the @char exists) % % Bugs and suggestions: % Please send to Yair Altman (altmany at gmail dot com) % % See also: % profile, profview % % Release history: % 1.0 2014-06-16: First version posted on <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/27420">MathWorks File Exchange</a> % 1.1 2014-06-17: Fixes for HG2 (R2014b), fix info-box alignment near figure's right edge % 1.2 2014-06-17: Fix the previous update... % 1.3 2014-06-18: External tick marks; fixed wrapper function edge-case as per user feedback % 1.4 2014-06-26: Added initialDetail input arg and interactive detail-control functionality % 1.5 2014-06-27: Fixed bug in case of few profiled functions (checkbox didn't work) % 1.6 2014-06-29: Fix for R2010a % License to use and modify this code is granted freely to all interested, as long as the original author is % referenced and attributed as such. The original author maintains the right to be solely associated with this work. % Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com % $Revision: 1.6 $ $Date: 2014/06/27 18:50:00 $ % Check inputs if nargin<1 || isempty(profData) profData = profile('info'); end if nargin<2 if isstruct(profData) initialDetail = 15; % =Default value else % i.e., profData was skipped, only initialDetail was specified initialDetail = profData; profData = profile('info'); end end % Ensure that there is valid history data to process if isempty(profData) || ~isstruct(profData) || ~isfield(profData,'FunctionHistory') error('YMA:profile_history:noStruct','Invalid profiling data: call %s following profile. For example:\n profile on -timestamp; surf(peaks); %s', mfilename, mfilename); elseif isempty(profData.FunctionHistory) error('YMA:profile_history:noData','No profiling data: call %s following profile. For example:\n profile on -timestamp; surf(peaks); %s', mfilename, mfilename); elseif size(profData.FunctionHistory,1) < 4 error('YMA:profile_history:noTiming','No timing data: call profile with the -timing parameter. For example:\n profile on -timestamp; surf(peaks); %s', mfilename); end % Parse the profile history data table histData = profData.FunctionHistory; startTime = histData(3,1) + histData(4,1)/1e6; relativeTimes = histData(3,:) + histData(4,:)/1e6 - startTime; % Differentiate between close calls N = numel(relativeTimes); for idx = 2 : N % TODO - vectorize this loop if relativeTimes(idx) <= relativeTimes(idx-1) relativeTimes(idx) = relativeTimes(idx-1) + 0.05*profData.ClockPrecision; end end %plot(relativeTimes); % Start the report figure in invisible mode (for improved performance) handles.hFig = figure('NumberTitle','off', 'Name','Profiling history', 'Visible','off', 'Color','w', 'Toolbar','figure'); handles.funcNames = getFunctionNames(profData); numFuncs = numel(handles.funcNames); handles.hAxes = axes('YDir','reverse', 'OuterPosition',[0,0,1,1], 'LooseInset',[0.05,0.15,0.02,0.01], 'FontSize',8, ... 'NextPlot','add', 'YTick',1:numFuncs, 'TickDir','out', 'YTickLabel',handles.funcNames, 'YLim',[1,numFuncs+0.2], ... 'ButtonDownFcn',{@mouseClickedCallbackFcn,handles.hFig}); try % HG2 set(handles.hAxes,'TickLabelInterpreter','none'); catch % HG1 end setappdata(handles.hFig,'hAxes',handles.hAxes); setappdata(handles.hFig,'numFuncs',numFuncs); xlabel(handles.hAxes, 'Secs from start'); if numFuncs > initialDetail visibility = {'visible','off'}; else visibility = {}; end for funcIdx = 1 : numFuncs % TODO - vectorize this loop % Get this function's entry and exit times entryIdx = (histData(2,:)==funcIdx) & (histData(1,:)==0); exitIdx = (histData(2,:)==funcIdx) & (histData(1,:)==1); profData.FunctionTable(funcIdx).EntryTimes = relativeTimes(entryIdx); profData.FunctionTable(funcIdx).ExitTimes = relativeTimes(exitIdx); if sum(entryIdx) > sum(exitIdx) % Function entry was provided without a corresponding function exit try sumDurations = sum(profData.FunctionTable(funcIdx).ExitTimes - profData.FunctionTable(funcIdx).EntryTimes(1:end-1)); lastDuration = profData.FunctionTable(funcIdx).TotalTime - sumDurations; profData.FunctionTable(funcIdx).ExitTimes(end+1) = profData.FunctionTable(funcIdx).EntryTimes(end) + lastDuration; catch % something is seriously fishy - bail out... end end profData.FunctionTable(funcIdx).SelfTime = zeros(1,sum(entryIdx)); % will be updated below % Plot the function's execution durations xData = [profData.FunctionTable(funcIdx).EntryTimes; ... profData.FunctionTable(funcIdx).ExitTimes]; handles.hPlotLines{funcIdx} = plot(xData, funcIdx(ones(size(xData))), '.-b', 'HitTest','off')'; end % Display the execution paths execPathX = reshape(relativeTimes(sort([1:N,2:N-1])),2,[]); execPathY = []; ancestors = []; cp = profData.ClockPrecision; for execIdx = 1 : N % TODO - vectorize this loop % Update the self-time for the function that just switched funcIdx = histData(2,execIdx); if execIdx > 1 duration = relativeTimes(execIdx) - relativeTimes(execIdx-1); duration = cp * round(duration/cp); if histData(1,execIdx) == 0 if ~isempty(ancestors) prevFuncIdx = ancestors(end); else prevFuncIdx = []; end else %prevFuncIdx = histData(2,execIdx-1); prevFuncIdx = funcIdx; end try funcData = profData.FunctionTable(prevFuncIdx); entryIdx = max(find(funcData.EntryTimes <= relativeTimes(execIdx))); %#ok<MXFND> % I think ,1,'last') is not available in old ML releases, so use max() if isempty(entryIdx), entryIdx = 1; end profData.FunctionTable(prevFuncIdx).SelfTime(entryIdx) = funcData.SelfTime(entryIdx) + duration; catch % ignore - probably prevFuncIdx==[] end end % Update the execPathY values and ancestors if histData(1,execIdx) == 0 % Push the function-call stack downwards execPathY(end+1) = funcIdx; %#ok<*AGROW> ancestors(end+1) = funcIdx; else % histData(1,execIdx) == 1 try % Pop the function-call stack upwards execPathY(end+1) = ancestors(end-1); ancestors(end) = []; catch % no parent function, so hide the exec path here execPathY(end+1) = NaN; ancestors = []; end end end execPathY = reshape(execPathY(sort([1:N-1,1:N-1])),2,[]); handles.hExecPaths = plot(execPathX, execPathY, '-r', 'LineWidth',2, 'HitTest','off', visibility{:}); % Display waterfalls waterfallX = reshape(execPathX(2:end-1),2,[]); waterfallY = reshape(execPathY(2:end-1),2,[]); handles.hWaterfalls = plot(waterfallX, waterfallY, ':r', 'HitTest','off', visibility{:}); direction = sign(diff(waterfallY)); hUpMarks = text(waterfallX(1,direction<0), mean(waterfallY(:,direction<0)), '\^', 'Color','r', 'HitTest','off', visibility{:}, 'FontSize',10, 'HorizontalAlignment','center', 'VerticalAlignment','middle'); hDownMarks = text(waterfallX(1,direction>0), mean(waterfallY(:,direction>0)), 'v', 'Color','r', 'HitTest','off', visibility{:}, 'FontSize',8, 'HorizontalAlignment','center', 'VerticalAlignment','cap'); handles.hTextLabels = zeros(numel(handles.hWaterfalls),1); handles.hTextLabels(direction<0) = hUpMarks; handles.hTextLabels(direction>0) = hDownMarks; % Add functionality checkboxes uicontrol('Style','checkbox', 'String','execution paths', 'value',1, 'Units','Pixels', 'Position',[ 10,5,100,20], 'Background','w', 'Tag','cbExecPath', 'Callback',{@execPathCallbackFcn, handles, profData}); uicontrol('Style','checkbox', 'String','waterfall lines', 'value',1, 'Units','Pixels', 'Position',[110,5,100,20], 'Background','w', 'Tag','cbWaterfall', 'Callback',{@waterfallCallbackFcn, handles, profData}); uicontrol('Style','checkbox', 'String','hover info-box', 'value',1, 'Units','Pixels', 'Position',[200,5,100,20], 'Background','w', 'Tag','cbInfoBox', 'Callback',{@infoBoxCallbackFcn, handles, profData}); if numFuncs > initialDetail try % Add the detail slider (much nicer-looking than Matlab's ugly builtin "slider" =Win95 scrollbar) jSlider = javax.swing.JSlider; try jSlider = javaObjectEDT(jSlider); catch, end % R2008b and newer tooltipStr = sprintf('%d functions',initialDetail); set(jSlider, 'Minimum',1, 'Maximum',numFuncs, 'Value',initialDetail, 'ToolTipText',tooltipStr); %, 'Background',java.awt.Color.white); %'PaintLabels',false, 'PaintTicks',false, 'Orientation',jSlider.HORIZONTAL) jSlider.setBackground(java.awt.Color.white); % Fix for R2010a [hjSlider, hContainer] = javacomponent(jSlider, [400,2,100,20]); set(hContainer, 'Tag','jSlider', 'UserData',hjSlider); set(hjSlider, 'StateChangedCallback',{@detailsCallbackFcn,handles,profData}); % So far so good - add the labels on the left and right of the slider uicontrol('Style','text', 'String','Display detail: 1 ', 'Units','Pixels', 'Position',[300,1,100,20], 'Background','w', 'horizontalAlignment','right'); uicontrol('Style','text', 'String',num2str(numFuncs), 'Units','Pixels', 'Position',[500,1, 50,20], 'Background','w', 'horizontalAlignment','left'); catch % never mind - ignore... end % Finally, update the plot axes updatePlot(handles, profData); end % Set the info-box hover callback set(handles.hFig, 'WindowButtonMotionFcn',{@mouseMovedCallbackFcn,profData}); % Display the figure set(handles.hFig, 'Visible','on'); end % Get valid function names function funcNames = getFunctionNames(profData) % First get all profiled function names funcNames = {profData.FunctionTable.FunctionName}; % Strip away profiling artifacts while ~isempty(strfind(funcNames{end},'profile')) funcNames(end) = []; end if strcmpi(funcNames{end},'ispc'), funcNames(end) = []; end if strcmpi(funcNames{end},'fileparts'), funcNames(end) = []; end end % Execution path checkbox callback function execPathCallbackFcn(cbExecPath, eventData, handles, profData) %#ok<INUSL> updatePlot(handles, profData) end % Waterfall lines checkbox callback function waterfallCallbackFcn(cbWaterfall, eventData, handles, profData) %#ok<INUSL> updatePlot(handles, profData) end % Hover info-box checkbox callback function infoBoxCallbackFcn(cbInfoBox, eventData, handles, profData) %#ok<INUSL> if get(cbInfoBox,'Value') set(handles.hFig, 'WindowButtonMotionFcn',{@mouseMovedCallbackFcn,profData}); else set(handles.hFig, 'WindowButtonMotionFcn',[]); end end % Display details slider callback function detailsCallbackFcn(hSlider, eventData, handles, profData) %#ok<INUSL> newValue = round(hSlider.getValue); prevValue = getappdata(handles.hFig,'detailValue'); if ~isequal(prevValue, newValue) setappdata(handles.hFig,'detailValue', newValue); hSlider.setToolTipText(sprintf('%d functions',newValue)); updatePlot(handles, profData); end end % Update visibility detail function updatePlot(handles, profData) if ~isempty(getappdata(handles.hFig,'inCallback')), return; end setappdata(handles.hFig,'inCallback',true); try hSlider = get(findall(handles.hFig,'Tag','jSlider'), 'UserData'); try numFuncsToDisplay = round(hSlider.getValue); catch numFuncsToDisplay = numel(handles.funcNames); % if no slider is displayed use all funcs end numFuncs = numel(handles.hPlotLines); [sortedTimes, sortedIdx] = sort([profData.FunctionTable(1:numFuncs).TotalTime]); %#ok<ASGLU> idxToDisplay = sortedIdx(end-numFuncsToDisplay+1:end); sortedIdx = sort(idxToDisplay); % Main plot lines (solid blue lines) set([handles.hPlotLines{:}], 'Visible','off'); set([handles.hPlotLines{idxToDisplay}], 'Visible','on'); set(handles.hAxes, 'YTickLabel',handles.funcNames(sortedIdx), 'YTick',sortedIdx); % Execution paths (solid red lines) cbExecPath = findall(handles.hFig, 'Tag','cbExecPath'); processPlotHandles(cbExecPath, handles.hExecPaths, idxToDisplay); % Waterfalls (dotted vertical red lines) cbWaterfall = findall(handles.hFig, 'Tag','cbWaterfall'); processPlotHandles(cbWaterfall, handles.hWaterfalls, idxToDisplay, handles.hTextLabels); catch err disp(err.message); %debugging breakpoint disp(err.stack(1)); end setappdata(handles.hFig,'inCallback',[]); end % Hide/display plot lines having certain Y values function processPlotHandles(hCheckbox, handlesToProcess, yValuesToDisplay, hTextLabels) if get(hCheckbox,'Value') % Only display plot line having certain Y values %set(handlesToProcess,'visible','on'); set(handlesToProcess,'visible','off'); yData = get(handlesToProcess, 'YData'); yData = [yData{:}]; yStart = yData(1:2:end); yEnd = yData(2:2:end); thisIdxToDisplay = ismember(yStart,yValuesToDisplay) & ismember(yEnd,yValuesToDisplay); set(handlesToProcess(thisIdxToDisplay),'visible','on'); % Now the corresponding text handles if nargin > 3 hTextLabelsToProcess = setdiff(hTextLabels(thisIdxToDisplay,:), 0); set(hTextLabels(hTextLabels~=0), 'visible','off'); set(hTextLabelsToProcess, 'visible','on'); end else % Hide *all* plot lines and corresponding text handles set(handlesToProcess, 'visible','off'); try set(hTextLabels(hTextLabels~=0), 'visible','off'); catch, end end end % Convert clicked position into a function index function [funcIdx,currentPoint,axesPos,yLim] = getFuncIdx(hFig, hAxes) % Get the clicked position currentPoint = get(hFig,'CurrentPoint'); x = currentPoint(1); y = currentPoint(2); % Convert clicked position into a function index if nargin<2, hAxes = getappdata(hFig,'hAxes'); end axesPos = getpixelposition(hAxes); axesHeight = axesPos(4); deltaYFromBottom = y - axesPos(2); deltaYFromTop = axesHeight - deltaYFromBottom; relYFromTop = min(max(deltaYFromTop/axesHeight,0),1); yLim = get(hAxes,'YLim'); numFuncs = getappdata(hFig,'numFuncs'); funcIdx = min(max(round(yLim(1) + relYFromTop*diff(yLim)), 1), numFuncs); % The following is currently unused: if x < axesPos(1) % Clicked outside the axes (on a function label) else % Clicked within the axes end end % Axes mouse-click callback function mouseClickedCallbackFcn(hAxes, eventData, hFig) %#ok<INUSL> % First get the clicked function index in the profiling table funcIdx = getFuncIdx(hFig, hAxes); % Open the detailed profiling report for the clicked function profview(funcIdx); end % Figure mouse-click callback function mouseMovedCallbackFcn(hFig, eventData, profData) %#ok<INUSL> % First get the hovered function index in the profiling table [funcIdx,currentPoint,axesPos,yLim] = getFuncIdx(hFig); % Get the info text-box handle hInfoBox = getappdata(hFig,'hInfoBox'); if isempty(hInfoBox) % Prepare the info-box hInfoBox = text(0,0,'', 'EdgeColor',.8*[1,1,1], 'FontSize',7, 'Tag','hInfoBox', 'VerticalAlignment','bottom', 'interpreter','none', 'HitTest','off'); setappdata(hFig,'hInfoBox',hInfoBox); end if currentPoint(2)<axesPos(2) || currentPoint(2)>axesPos(2)+axesPos(4) || currentPoint(1)>axesPos(1)+axesPos(3) % Mouse pointer is outside the axes boundaries - hide the info box set(hInfoBox, 'Visible','off'); else % Get the hovered position in data units % Note: we could also use the builtin hgconvertunits function axesWidth = axesPos(3); deltaXFromLeft = currentPoint(1) - axesPos(1); relXFromLeft = min(max(deltaXFromLeft/axesWidth,0),1); hAxes = getappdata(hFig,'hAxes'); xLim = get(hAxes,'XLim'); dataX = xLim(1) + relXFromLeft*diff(xLim); %disp([x axesWidth deltaXFromLeft relXFromLeft xLim dataX]) % Get the function's timing data functionData = profData.FunctionTable(funcIdx); % Find the nearest function entry point entryIdx = max(find(functionData.EntryTimes <= dataX)); %#ok<MXFND> % I think ,1,'last') is not available in old ML releases, so use max() if isempty(entryIdx), entryIdx = 1; end % Bail out if the entry is not visible if ~ismember(functionData.FunctionName, get(hAxes,'YTickLabel')) set(hInfoBox, 'Visible','off'); return; end % Get the entry's time entryTime = functionData.EntryTimes(entryIdx); exitTime = functionData.ExitTimes(entryIdx); totalTime = exitTime - entryTime; selfTime = functionData.SelfTime(entryIdx); childTime = totalTime - selfTime; selfTotalTime = sum(functionData.SelfTime); totalTotalTime = sum(functionData.TotalTime); childTotalTime = totalTotalTime - selfTotalTime; % Assemble all the info into the info-box string %cp = profData.ClockPrecision; str = functionData.FunctionName; numEntries = numel(functionData.EntryTimes); if numEntries > 1 str = sprintf('%s\n => call #%d of %d', str, entryIdx, numEntries); end %str = sprintf('%s\n Start: %+.3f\n Self: %+.3f\n Child: %+.3f\n Total: %+.3f\n End: %+.3f', ... % str, entryTime, selfTime, childTime, totalTime, exitTime); str = sprintf('%s\n Start: %+.3f\n Self: %+.3f', str, entryTime, selfTime); if numEntries > 1, str = sprintf('%s (of %.3f)', str, selfTotalTime); end str = sprintf('%s\n Child: %+.3f', str, childTime); if numEntries > 1, str = sprintf('%s (of %.3f)', str, childTotalTime); end str = sprintf('%s\n Total: %+.3f', str, totalTime); if numEntries > 1, str = sprintf('%s (of %.3f)', str, totalTotalTime); end str = sprintf('%s\n End: %+.3f', str, exitTime); set(hInfoBox, 'Visible','on', 'Position',[dataX,funcIdx], 'String',str, ... 'VerticalAlignment','top', 'HorizontalAlignment','left'); % Update the info-box location based on cursor position extent = get(hInfoBox,'Extent'); %disp(num2str([extent,yLim,xLim],'%.2f ')) if extent(2) - 2*extent(4) < yLim(1) set(hInfoBox, 'VerticalAlignment','top'); else set(hInfoBox, 'VerticalAlignment','bottom'); end if extent(1) + extent(3) > xLim(2) %set(hInfoBox, 'HorizontalAlignment','right'); set(hInfoBox, 'Position',[dataX-extent(3),funcIdx]); else %set(hInfoBox, 'HorizontalAlignment','left'); end end end
github
HelmchenLabSoftware/OCIA-master
parseXML.m
.m
OCIA-master/utils/file/parseXML.m
2,298
utf_8
2872d6a03a9a0534868ee63adbb29a11
function theStruct = parseXML(filename) % PARSEXML Convert XML file to a MATLAB structure. try tree = xmlread(filename); catch error('Failed to read XML file %s.',filename); end % Recurse over child nodes. This could run into problems % with very deeply nested trees. theStruct = parseChildNodes(tree); return try theStruct = parseChildNodes(tree); catch error('Unable to parse XML file %s.',filename); rethrow(lasterror) end % ----- Subfunction PARSECHILDNODES ----- function children = parseChildNodes(theNode) % Recurse over node children. children = []; if theNode.hasChildNodes childNodes = theNode.getChildNodes; numChildNodes = childNodes.getLength; allocCell = cell(1, numChildNodes); children = struct( ... 'Name', allocCell, 'Attributes', allocCell, ... 'Data', allocCell, 'Children', allocCell); delIdx = []; for count = 1:numChildNodes theChild = childNodes.item(count-1); switch char(theChild.getNodeName) case '#texttt' delIdx(length(delIdx)+1) = count; otherwise children(count) = makeStructFromNode(theChild); end end children(delIdx) = []; end % ----- Subfunction MAKESTRUCTFROMNODE ----- function nodeStruct = makeStructFromNode(theNode) % Create structure of node info. nodeStruct = struct( ... 'Name', char(theNode.getNodeName), ... 'Attributes', parseAttributes(theNode), ... 'Data', '', ... 'Children', parseChildNodes(theNode)); if any(strcmp(methods(theNode), 'getData')) nodeStruct.Data = char(theNode.getData); else nodeStruct.Data = ''; end % ----- Subfunction PARSEATTRIBUTES ----- function attributes = parseAttributes(theNode) % Create attributes structure. attributes = []; if theNode.hasAttributes theAttributes = theNode.getAttributes; numAttributes = theAttributes.getLength; allocCell = cell(1, numAttributes); attributes = struct('Name', allocCell, 'Value', ... allocCell); for count = 1:numAttributes attrib = theAttributes.item(count-1); attributes(count).Name = char(attrib.getName); attributes(count).Value = char(attrib.getValue); end end
github
HelmchenLabSoftware/OCIA-master
depfunFast.m
.m
OCIA-master/utils/file/depfunFast.m
3,341
utf_8
e1a987535066e28a1e99c5fce821bdda
function filelist = depfunFast(fn,recursive) % Variation on the built-in depfun function, which skips toolbox files % % filelist = mydepfun(fn) % filelist = mydepfun(fn,recursive) % % Returns a list of files which are required by the specified % function, omitting any which are inside $matlabroot/toolbox. % % "fn" is a string specifying a filename in any form that can be % identified by the built-in function "which". % "recursive" is a logical scalar; if false, only the files called % directly by the specified function are returned. If true, *all* % those files are scanned to, and any required by those, and so on. % % "filelist" is a cell array of fully qualified file name strings, % including the specified file. % % e.g. % filelist = mydepfun('myfunction') % filelist = mydepfun('C:\files\myfunction.m',true) %PMTKauthor Malcolm Wood %PMTKurl http://www.mathworks.com/matlabcentral/fileexchange/10702 % This file is from matlabtools.googlecode.com if ~ischar(fn) error('First argument must be a string'); end foundfile = which(fn); if isempty(foundfile) error('File not found: %s',fn); end % Scan this file filelist = i_scan(foundfile); % If "recursive" is supplied and true, scan files on which this one depends. if nargin>1 && recursive % Create a list of files which we have still to scan. toscan = filelist; toscan = toscan(2:end); % first entry is always the same file again % Now scan files until we have none left to scan while numel(toscan)>0 % Scan the first file on the list newlist = i_scan(toscan{1}); newlist = newlist(2:end); % first entry is always the same file again toscan(1) = []; % remove the file we've just scanned % Find out which files are not already on the list. Take advantage of % the fact that "which" and "depfun" return the correct capitalisation % of file names, even on Windows, making it safe to use "ismember" % (which is case-sensitive). reallynew = ~ismember(newlist,filelist); newlist = newlist(reallynew); % If they're not already in the file list, we'll need to scan them too. % (Conversely, if they ARE in the file list, we've either scanned them % already, or they're currently on the toscan list) toscan = unique( [ toscan ; newlist ] ); filelist = unique( [ filelist ; newlist ] ); end end end %%%%%%%%%%%%%%%%%%%%% % Returns the non-toolbox files which the specified one calls. % The specified file is always first in the returned list. function list = i_scan(f) func = i_function_name(f); list = matlab.codetools.requiredFilesAndProducts(func, 'toponly')'; ulist = list; toolboxroot = fullfile(matlabroot,'toolbox'); intoolbox = strncmpi(ulist,toolboxroot,numel(toolboxroot)); list = list(~intoolbox); end %%%%%%%%%%%%%%%%%%%%%%%% function func = i_function_name(f) % Identifies the function name for the specified file, % including the class name where appropriate. Does not % work for UDD classes, e.g. @rtw/@rtw [dirname,funcname,ext] = fileparts(f); [ignore,dirname] = fileparts(dirname); if ~isempty(dirname) && dirname(1)=='@' func = [ dirname '/' funcname ]; else func = funcname; end end
github
HelmchenLabSoftware/OCIA-master
showByteSize.m
.m
OCIA-master/utils/file/showByteSize.m
991
utf_8
0a61a86db4a2ae5060ab4797b40d0d11
function showByteSize(in, fid) %#ok<INUSL> % BYTESIZE writes the memory usage of the provide variable to the given file % identifier. Output is written to screen if fid is 1, empty or not provided. if nargin == 1 || isempty(fid) fid = 1; end s = whos('in'); fprintf(fid,[Bytes2str(s.bytes) '\n']); end function str = Bytes2str(NumBytes) % BYTES2STR Private function to take integer bytes and convert it to % scale-appropriate size. scale = floor(log(NumBytes)/log(1024)); switch scale case 0 str = [sprintf('%.0f',NumBytes) ' b']; case 1 str = [sprintf('%.3f',NumBytes/(1024)) ' kb']; case 2 str = [sprintf('%.3f',NumBytes/(1024^2)) ' Mb']; case 3 str = [sprintf('%.3f',NumBytes/(1024^3)) ' Gb']; case 4 str = [sprintf('%.3f',NumBytes/(1024^4)) ' Tb']; case -inf % Size occasionally returned as zero (eg some Java objects). str = 'Not Available'; otherwise str = 'Over a petabyte!!!'; end end
github
HelmchenLabSoftware/OCIA-master
exportMfiles.m
.m
OCIA-master/utils/file/exportMfiles.m
3,841
utf_8
367bfa75d006163523b8208a9c631218
function exportMfiles(funcname,doPcode,doZip,saveDir) % find dependencies for function funcname % copy all dependencies to saveDir % create zip-archive saveDir.zip % optionally, pcode % this file written by Henry Luetcke ([email protected]) if ~iscell(funcname) funcname = {funcname}; end if isempty(funcname) error('No function names specified'); end if ~iscellstr(funcname) error('Function names must be strings'); end if nargin<2 zipfilename = fullfile(pwd,[ funcname{1} '.zip' ]); end req = cell(size(funcname)); for i=1:numel(funcname) req{i} = depfunFast(funcname{i},1); % recursive end req = vertcat(req{:}); % cell arrays of full file names req = unique(req); % filename for the first function file [~, baseFuncName, ext] = fileparts(funcname{1}); % Find the common root directory d = i_root_directory(req); % Calculate relative paths for all required files. n = numel(d); for i=1:numel(req) % This is the bit that can't be vectorised req{i} = req{i}(n+1:end); % step over last character (which is the separator) end if exist(saveDir, 'dir') ~= 7; mkdir(saveDir); end; % req is a cell array with all functions, d is the root directory for n = 1:length(req) currentFile = req{n}; [~, currentBaseName, ext] = fileparts(currentFile); if ~exist(fullfile(pwd,[currentBaseName ext]),'file') copyfile(fullfile(d,currentFile),'.'); doFileMove = 1; else doFileMove = 0; end currentFile = fullfile(pwd,[currentBaseName ext]); if doPcode if exist([saveDir filesep 'protected'],'dir') ~= 7 mkdir([saveDir filesep 'protected']) end if strcmp(saveDir, '.'); saveDir = './.'; end; % never pcode the top-most function if strcmp(currentBaseName,baseFuncName) if doFileMove movefile(currentFile,saveDir) else copyfile(currentFile,saveDir) end else pcode(currentFile) delete(currentFile) currentFile = strrep(currentFile,'.m','.p'); if doFileMove movefile(currentFile,[saveDir filesep 'protected']) else copyfile(currentFile,[saveDir filesep 'protected']) end end else if doFileMove movefile(currentFile,saveDir) else copyfile(currentFile,saveDir) end end end % zip up saveDir if doZip; zip([saveDir '.zip'],saveDir) end; % delete saveDir % rmdir(saveDir) %%%%%%%%%%%%%%%%%%%%% % Identifies the common root directory of all files in cell array "req" function d = i_root_directory(req) d = i_parent(req{1}); for i=1:numel(req) t = i_parent(req{i}); if strncmp(t,d,numel(d)) % req{i} is in directory d. Next file. continue; end % req{i} is not in directory d. Up one directory. count = 1; while true % Remove trailing separator before calling fileparts. Add it % again afterwards. tempd = i_parent(d(1:end-1)); if strcmp(d,tempd) % fileparts didn't find us a higher directory error('Failed to find common root directory for %s and %s',req{1},req{i}); end d = tempd; if strncmp(t,d,numel(d)) % req{i} is in directory d. Next file. break; end % Safety measure for untested platform. count = count+1; if count>1000 error('Bug in i_root_directory.'); end end end %%%%%%%%%%%%%%%%%%% function d = i_parent(d) % Identifies the parent directory, including a trailing separator % Include trailing separator in all comparisons so we don't assume that % file C:\tempX\file.txt is in directory C:\temp d = fileparts(d); if d(end)~=filesep d = [d filesep]; end
github
HelmchenLabSoftware/OCIA-master
tiffread2.m
.m
OCIA-master/utils/file/tiffread2.m
19,177
utf_8
1eab6091d5c0b85e5ab70139f0d580c3
function [stack, img_read] = tiffread2(filename, img_first, img_last, funUpdateWaitBar) % tiffread, version 2.4 % % [stack, nbImages] = tiffread; % [stack, nbImages] = tiffread(filename); % [stack, nbImages] = tiffread(filename, imageIndex); % [stack, nbImages] = tiffread(filename, firstImageIndex, lastImageIndex); % % % 2010-04-30::hluetck % modify to also store file description if field info exists % % % Reads 8,16,32 bits uncompressed grayscale and (some) color tiff files, % as well as stacks or multiple tiff images, for example those produced % by metamorph or NIH-image. However, the entire TIFF standard is not % supported (but you may extend it). % % The function can be called with a file name in the current directory, % or without argument, in which case it pop up a file openning dialog % to allow manual selection of the file. % If the stacks contains multiples images, loading can be restricted by % specifying the first and last images to read, or just one image to read. % % at return, nbimages contains the number of images read, and S is a vector % containing the different images with some additional informations. The % image pixels values are stored in the field .data, for gray level images, % or in the fields .red, .green and .blue % the pixels values are in the native (integer) format, % and must be converted to be used in most matlab functions. % % Example: % im = tiffread('spindle.stk'); % imshow( double(im(5).data), [] ); % % Francois Nedelec, EMBL, Copyright 1999-2006. % rewriten July 7th, 2004 at Woods Hole during the physiology course. % last modified April 12, 2006. % Contributions: % Kendra Burbank suggested the waitbar % Hidenao Iwai for the code to read floating point images, % Stephen Lang made tiffread more compliant with PlanarConfiguration % % Please, help us improve this software: send us feedback/bugs/suggestions % This software is provided at no cost by a public research institution. % However, postcards are always welcome! % % Francois Nedelec % nedelec (at) embl.de % Cell Biology and Biophysics, EMBL; Meyerhofstrasse 1; 69117 Heidelberg; Germany % http://www.embl.org % http://www.cytosim.org %Optimization: join adjacent TIF strips: this results in faster reads consolidateStrips = 1; %if there is no argument, we ask the user to choose a file: if (nargin == 0) [filename, pathname] = uigetfile('*.tif;*.stk;*.lsm', 'select image file'); filename = [ pathname, filename ]; end if (nargin<=1); img_first = 1; img_last = 10000; end if (nargin==2); img_last = img_first; end % not all valid tiff tags have been included, as they are really a lot... % if needed, tags can easily be added to this code % See the official list of tags: % http://partners.adobe.com/asn/developer/pdfs/tn/TIFF6.pdf % % the structure IMG is returned to the user, while TIF is not. % so tags usefull to the user should be stored as fields in IMG, while % those used only internally can be stored in TIF. global TIF; TIF = []; %counters for the number of images read and skipped img_skip = 0; img_read = 0; % set defaults values : TIF.SampleFormat = 1; TIF.SamplesPerPixel = 1; TIF.BOS = 'l'; %byte order string % if isempty(findstr(filename,'.')) % filename = [filename,'.tif']; % end TIF.nFrames = numel(imfinfo(filename)); TIF.file = fopen(filename,'r','l'); if TIF.file == -1 filename = strrep(filename, '.tif', '.stk'); TIF.file = fopen(filename,'r','l'); if TIF.file == -1 error(['file <',filename,'> not found.']); end end % read header % read byte order: II = little endian, MM = big endian byte_order = fread(TIF.file, 2, '*char'); if ( strcmp(byte_order', 'II') ) TIF.BOS = 'l'; %normal PC format elseif ( strcmp(byte_order','MM') ) TIF.BOS = 'b'; else error('This is not a TIFF file (no MM or II).'); end %----- read in a number which identifies file as TIFF format tiff_id = fread(TIF.file,1,'uint16', TIF.BOS); if (tiff_id ~= 42) error('This is not a TIFF file (missing 42).'); end %----- read the byte offset for the first image file directory (IFD) ifd_pos = fread(TIF.file,1,'uint32', TIF.BOS); while (ifd_pos ~= 0) clear IMG; IMG.filename = fullfile( pwd, filename ); % move in the file to the first IFD fseek(TIF.file, ifd_pos, -1); %disp(strcat('reading img at pos :',num2str(ifd_pos))); %read in the number of IFD entries num_entries = fread(TIF.file,1,'uint16', TIF.BOS); %disp(strcat('num_entries =', num2str(num_entries))); %read and process each IFD entry for i = 1:num_entries % save the current position in the file file_pos = ftell(TIF.file); % read entry tag TIF.entry_tag = fread(TIF.file, 1, 'uint16', TIF.BOS); entry = readIFDentry; %disp(strcat('reading entry <',num2str(TIF.entry_tag),'>')); switch TIF.entry_tag case 254 TIF.NewSubfiletype = entry.val; case 256 % image width - number of column IMG.width = entry.val; case 257 % image height - number of row IMG.height = entry.val; TIF.ImageLength = entry.val; case 258 % BitsPerSample per sample TIF.BitsPerSample = entry.val; TIF.BytesPerSample = TIF.BitsPerSample / 8; IMG.bits = TIF.BitsPerSample(1); %fprintf(1,'BitsPerSample %i %i %i\n', entry.val); case 259 % compression if (entry.val ~= 1); error('Compression format not supported.'); end case 262 % photometric interpretation TIF.PhotometricInterpretation = entry.val; if ( TIF.PhotometricInterpretation == 3 ) fprintf(1, 'warning: ignoring the look-up table defined in the TIFF file'); end case 269 IMG.document_name = entry.val; case 270 % comment: TIF.info = entry.val; case 271 IMG.make = entry.val; case 273 % strip offset TIF.StripOffsets = entry.val; TIF.StripNumber = entry.cnt; %fprintf(1,'StripNumber = %i, size(StripOffsets) = %i %i\n', TIF.StripNumber, size(TIF.StripOffsets)); case 274 % orientation is read, but the matrix is not rotated if 1 < entry.val && entry.val < 9; TIF.Orientation = entry.val; keys = { 'TopLeft', 'TopRight', 'BottomRight', 'BottomLeft', 'LeftTop', ... 'RightTop', 'RightBottom', 'LeftBottom' }; TIF.OrientationText = keys{entry.val}; end case 277 % sample_per pixel TIF.SamplesPerPixel = entry.val; %fprintf(1,'Color image: sample_per_pixel=%i\n', TIF.SamplesPerPixel); case 278 % rows per strip TIF.RowsPerStrip = entry.val; case 279 % strip byte counts - number of bytes in each strip after any compressio TIF.StripByteCounts= entry.val; case 282 % X resolution IMG.x_resolution = entry.val; case 283 % Y resolution IMG.y_resolution = entry.val; case 284 %planar configuration describe the order of RGB TIF.PlanarConfiguration = entry.val; case 296 % resolution unit IMG.resolution_unit= entry.val; case 305 % software IMG.software = entry.val; case 306 % datetime IMG.datetime = entry.val; case 315 IMG.artist = entry.val; case 317 %predictor for compression if (entry.val ~= 1); error('unsuported predictor value'); end case 320 % color map IMG.cmap = entry.val; IMG.colors = entry.cnt/3; case 339 TIF.SampleFormat = entry.val; case 33628 %metamorph specific data IMG.MM_private1 = entry.val; case 33629 %this tag identify the image as a Metamorph stack! TIF.MM_stack = entry.val; TIF.MM_stackCnt = entry.cnt; if ( img_last > img_first ) if exist('funUpdateWaitBar', 'var') && isa(funUpdateWaitBar, 'function_handle') funUpdateWaitBar(0); elseif exist('waitbar_handle', 'var') waitbar_handle = waitbar(0,'Please wait...','Name',['Reading ' filename]); end; end case 33630 %metamorph stack data: wavelength TIF.MM_wavelength = entry.val; case 33631 %metamorph stack data: gain/background? TIF.MM_private2 = entry.val; otherwise % fprintf(1,'ignored TIFF entry with tag %i (cnt %i)\n', TIF.entry_tag, entry.cnt); end % move to next IFD entry in the file fseek(TIF.file, file_pos+12,-1); end %Planar configuration is not fully supported %Per tiff spec 6.0 PlanarConfiguration irrelevent if SamplesPerPixel==1 %Contributed by Stephen Lang if ((TIF.SamplesPerPixel ~= 1) && (TIF.PlanarConfiguration == 1)) error('PlanarConfiguration = %i not supported', TIF.PlanarConfiguration); end %total number of bytes per image: PlaneBytesCnt = IMG.width * IMG.height * TIF.BytesPerSample; if consolidateStrips %Try to consolidate the strips into a single one to speed-up reading: BytesCnt = TIF.StripByteCounts(1); if BytesCnt < PlaneBytesCnt ConsolidateCnt = 1; %Count how many Strip are needed to produce a plane while TIF.StripOffsets(1) + BytesCnt == TIF.StripOffsets(ConsolidateCnt+1) ConsolidateCnt = ConsolidateCnt + 1; BytesCnt = BytesCnt + TIF.StripByteCounts(ConsolidateCnt); if ( BytesCnt >= PlaneBytesCnt ); break; end end %Consolidate the Strips if ( BytesCnt <= PlaneBytesCnt(1) ) && ( ConsolidateCnt > 1 ) %fprintf(1,'Consolidating %i stripes out of %i', ConsolidateCnt, TIF.StripNumber); TIF.StripByteCounts = [BytesCnt; TIF.StripByteCounts(ConsolidateCnt+1:TIF.StripNumber ) ]; TIF.StripOffsets = TIF.StripOffsets( [1 , ConsolidateCnt+1:TIF.StripNumber] ); TIF.StripNumber = 1 + TIF.StripNumber - ConsolidateCnt; end end end %read the next IFD address: ifd_pos = fread(TIF.file, 1, 'uint32', TIF.BOS); %if (ifd_pos) disp(['next ifd at', num2str(ifd_pos)]); end if isfield( TIF, 'MM_stack' ) if ( img_last > TIF.MM_stackCnt ) img_last = TIF.MM_stackCnt; end %this loop is to read metamorph stacks: for ii = img_first:img_last TIF.StripCnt = 1; %read the image fileOffset = PlaneBytesCnt * ( ii - 1 ); %fileOffset = 0; %fileOffset = ftell(TIF.file) - TIF.StripOffsets(1); if ( TIF.SamplesPerPixel == 1 ) IMG.data = read_plane(fileOffset, IMG.width, IMG.height, 1); else IMG.red = read_plane(fileOffset, IMG.width, IMG.height, 1); IMG.green = read_plane(fileOffset, IMG.width, IMG.height, 2); IMG.blue = read_plane(fileOffset, IMG.width, IMG.height, 3); end if exist('funUpdateWaitBar', 'var') && isa(funUpdateWaitBar, 'function_handle') funUpdateWaitBar(img_read/TIF.MM_stackCnt); elseif exist('waitbar_handle', 'var') waitbar( img_read/TIF.MM_stackCnt, waitbar_handle); end; [ IMG.info, IMG.MM_stack, IMG.MM_wavelength, IMG.MM_private2 ] = extractMetamorphData(ii); img_read = img_read + 1; stack( img_read ) = IMG; end break; else %this part to read a normal TIFF stack: if ( img_skip + 1 >= img_first ) TIF.StripCnt = 1; %read the image if ( TIF.SamplesPerPixel == 1 ) IMG.data = read_plane(0, IMG.width, IMG.height, 1); else IMG.red = read_plane(0, IMG.width, IMG.height, 1); IMG.green = read_plane(0, IMG.width, IMG.height, 2); IMG.blue = read_plane(0, IMG.width, IMG.height, 3); end % 2010-04-30::hluetck % modify to also store file description if field info exists if isfield(TIF,'info') IMG.descriptor = TIF.info; end img_read = img_read + 1; if exist('funUpdateWaitBar', 'var') && isa(funUpdateWaitBar, 'function_handle') funUpdateWaitBar(img_read/TIF.nFrames); elseif exist('waitbar_handle', 'var') waitbar( img_read/TIF.nFrames, waitbar_handle); end; try stack( img_read ) = IMG; catch %stack %IMG error('The file contains dissimilar images: you can only read them one by one'); end else img_skip = img_skip + 1; end if ( img_skip + img_read >= img_last ) break; end end end %clean-up fclose(TIF.file); if exist('funUpdateWaitBar', 'var') && isa(funUpdateWaitBar, 'function_handle') funUpdateWaitBar(1); elseif exist('waitbar_handle', 'var') delete( waitbar_handle ); clear waitbar_handle; end drawnow; %return empty array if nothing was read if ~ exist( 'stack', 'var') stack = []; end return; %============================================================================ function plane = read_plane(offset, width, height, planeCnt) global TIF; %return an empty array if the sample format has zero bits if ( TIF.BitsPerSample(planeCnt) == 0 ) plane=[]; return; end %fprintf(1,'reading plane %i size %i %i\n', planeCnt, width, height); %determine the type needed to store the pixel values: switch( TIF.SampleFormat ) case 1 classname = sprintf('uint%i', TIF.BitsPerSample(planeCnt)); case 2 classname = sprintf('int%i', TIF.BitsPerSample(planeCnt)); case 3 if ( TIF.BitsPerSample(planeCnt) == 32 ) classname = 'single'; else classname = 'double'; end otherwise error('unsuported TIFF sample format %i', TIF.SampleFormat); end % Preallocate a matrix to hold the sample data: plane = zeros(width, height, classname); % Read the strips and concatenate them: line = 1; while ( TIF.StripCnt <= TIF.StripNumber ) strip = read_strip(offset, width, planeCnt, TIF.StripCnt, classname); TIF.StripCnt = TIF.StripCnt + 1; % copy the strip onto the data plane(:, line:(line+size(strip,2)-1)) = strip; line = line + size(strip,2); if ( line > height ) break; end end % Extract valid part of data if needed if ~all(size(plane) == [width height]), plane = plane(1:width, 1:height); error('Cropping data: more bytes read than needed...'); end % transpose the image (otherwise display is rotated in matlab) plane = plane'; return; %=================== sub-functions to read a strip =================== function strip = read_strip(offset, width, planeCnt, stripCnt, classname) global TIF; %fprintf(1,'reading strip at position %i\n',TIF.StripOffsets(stripCnt) + offset); StripLength = TIF.StripByteCounts(stripCnt) ./ TIF.BytesPerSample(planeCnt); %fprintf(1, 'reading strip %i\n', stripCnt); fseek(TIF.file, TIF.StripOffsets(stripCnt) + offset, 'bof'); bytes = fread( TIF.file, StripLength, classname, TIF.BOS ); if ( length(bytes) ~= StripLength ) error('End of file reached unexpectedly.'); end strip = reshape(bytes, width, StripLength / width); return; %===================sub-functions that reads an IFD entry:=================== function [nbBytes, matlabType] = convertType(tiffType) switch (tiffType) case 1 nbBytes=1; matlabType='uint8'; case 2 nbBytes=1; matlabType='uchar'; case 3 nbBytes=2; matlabType='uint16'; case 4 nbBytes=4; matlabType='uint32'; case 5 nbBytes=8; matlabType='uint32'; case 11 nbBytes=4; matlabType='float32'; case 12 nbBytes=8; matlabType='float64'; otherwise error('tiff type %i not supported', tiffType) end return; %===================sub-functions that reads an IFD entry:=================== function entry = readIFDentry() global TIF; entry.tiffType = fread(TIF.file, 1, 'uint16', TIF.BOS); entry.cnt = fread(TIF.file, 1, 'uint32', TIF.BOS); %disp(['tiffType =', num2str(entry.tiffType),', cnt = ',num2str(entry.cnt)]); [ entry.nbBytes, entry.matlabType ] = convertType(entry.tiffType); if entry.nbBytes * entry.cnt > 4 %next field contains an offset: offset = fread(TIF.file, 1, 'uint32', TIF.BOS); %disp(strcat('offset = ', num2str(offset))); fseek(TIF.file, offset, -1); end if TIF.entry_tag == 33629 %special metamorph 'rationals' entry.val = fread(TIF.file, 6*entry.cnt, entry.matlabType, TIF.BOS); else if entry.tiffType == 5 entry.val = fread(TIF.file, 2*entry.cnt, entry.matlabType, TIF.BOS); else entry.val = fread(TIF.file, entry.cnt, entry.matlabType, TIF.BOS); end end if ( entry.tiffType == 2 ); entry.val = char(entry.val'); end return; %==============distribute the metamorph infos to each frame: function [info, stack, wavelength, private2 ] = extractMetamorphData(imgCnt) global TIF; info = []; stack = []; wavelength = []; private2 = []; if TIF.MM_stackCnt == 1 return; end left = imgCnt - 1; if isfield( TIF, 'info' ) S = length(TIF.info) / TIF.MM_stackCnt; info = TIF.info(S*left+1:S*left+S); end if isfield( TIF, 'MM_stack' ) S = length(TIF.MM_stack) / TIF.MM_stackCnt; stack = TIF.MM_stack(S*left+1:S*left+S); end if isfield( TIF, 'MM_wavelength' ) S = length(TIF.MM_wavelength) / TIF.MM_stackCnt; wavelength = TIF.MM_wavelength(S*left+1:S*left+S); end if isfield( TIF, 'MM_private2' ) S = length(TIF.MM_private2) / TIF.MM_stackCnt; private2 = TIF.MM_private2(S*left+1:S*left+S); end return;
github
HelmchenLabSoftware/OCIA-master
spikeTimeAnalyzer.m
.m
OCIA-master/utils/spike/spikeTimeAnalyzer.m
5,911
utf_8
40a546c18226484564e906b605c8c857
function varargout = spikeTimeAnalyzer( s, psthT, evokedT, method, doPlot ) % inputs (all compulsory): % s ... cell array of spike times per trial % psthTime ... time bins relative to stim onset (=0) % evokedT ... time to count as evoked; used for counting evoked spikes; either n x 2 matrix with % different tStart and tStop windows or a number; in the latter case evokedT is expanded to [0 evokedT] % method ... method for ifr calculation: 'barsP', 'turbotrend', 'turbotrendboot', 'InstantFR', 'none' % outputs (all optional): % count ... n x 2 matrix with base (column 1) and evoked (column 2) spike counts per trial (n), % normalized to the respective time interval % ifr ... 4 x t matrix with mean instantaneous firing rate (row 1), SD of IFR (row 2) and lower (row % 3) / upper CI (row 4); depending on the method, not all statistics are computed (if not computed, % row is NaN) % spike raster ... n x t matrix of spike counts per psth bin % written by Henry Luetcke ([email protected]) %% Parameters lambda = 0.5; % lambda parameter for turbotrend samples = 1000; % samples parameter for bootstrap estimation techniques doShadedEbar = 1; errorStats = 'sd'; % 'sd' or 'ci' ('ci' is 95% CI) rate = 1./(psthT(2)-psthT(1)); if numel(evokedT) == 1 evokedT = [0 evokedT]; end %% Assemble raster and count spikes spikeRaster = zeros(numel(s),length(psthT)); count = zeros(numel(s),size(evokedT,1)+1); if doPlot hFig = figure('Name','Raster Plot Spike Times','NumberTitle','off'); subplot(2,1,1) end for n = 1:length(s) if ~isempty(s{n}) && doPlot plot(s{n},repmat(n,1,numel(s{n})),'o','MarkerEdgeColor','none','MarkerFaceColor','k'), hold on end spikeTimes = s{n}; baseSpikes = numel(find(spikeTimes>=psthT(1)&spikeTimes<0)); count(n,1) = baseSpikes; for m = 1:size(evokedT,1) evokedSpikes = numel(find(spikeTimes>=evokedT(m,1)&spikeTimes<=evokedT(m,2))); count(n,m+1) = evokedSpikes; end for m = 1:numel(spikeTimes) [~,idx] = min(abs(psthT-spikeTimes(m))); spikeRaster(n,idx) = spikeRaster(n,idx) + 1; end end if doPlot, set(gca,'xlim',[psthT(1) psthT(end)]), ylabel('Trials'), end %% Compute IFR ifr = nan(4,numel(psthT)); switch lower(method) case 'barsp' % smooth histogram using bayesian adaptive regression splines bp = defaultParams; bp.use_logspline = 0; f = barsP(sum(spikeRaster,1),[psthT(1) psthT(end)],numel(s),bp); if isfield(f,'mean') ifr = f.mean'; lowerConf = ifr-f.confBands(:,1)'; upperConf = f.confBands(:,2)'-ifr; ifr(2,:) = f.sd'; ifr(3:4,:) = [upperConf; lowerConf]; ifr = ifr ./ length(s).*rate; % not sure if this is legitimate (statistically) else ifr(1,:) = sum(spikeRaster,1)./length(s).*rate; end case 'turbotrend' firingRate = sum(spikeRaster,1)./length(s).*rate; [~, ~, yfit] = turbotrend(psthT, firingRate, lambda, numel(psthT)); ifr(1,:) = yfit'; case 'turbotrendboot' ifr = doTurboTrendBoot(samples,spikeRaster,numel(s),rate,... lambda,psthT); case 'instantfr' ifr = doInstantFR(s,psthT,samples); case 'none' ifr(1,:) = sum(spikeRaster,1)./length(s).*rate; otherwise error('Method %s not implemented (yet)!',method) end %% Plot raster psth = sum(spikeRaster,1)./length(s).*rate; % sparseness of psth psthKurtosis = kurtosis(psth); if doPlot subplot(2,1,2) stairs(psthT,psth,'k'), hold on if doShadedEbar switch lower(errorStats) case 'sd' if ~all(isnan(ifr(2,:))) shadedErrorBar(psthT,ifr(1,:),ifr(2,:),'r',1); ylabel('Firing rate +- SD') else plot(psthT,ifr(1,:),'r'); ylabel('Firing rate') end case 'ci' if ~all(isnan(ifr(3,:))) && ~all(isnan(ifr(4,:))) shadedErrorBar(psthT,ifr(1,:),ifr(3:4,:),'r',1); ylabel('Firing rate +- 95% CI') else plot(psthT,ifr(1,:),'r'); ylabel('Firing rate') end end else plot(psthT,ifr(1,:),'r'); ylabel('Firing rate') end ylims = get(gca,'ylim'); set(gca,'xlim',[psthT(1) psthT(end)]) hLegend = legend({sprintf('Observed (k=%1.3f)',psthKurtosis),sprintf('Fit (%s)',method)}); set(hLegend,'box','off','location','best') end %% Define outputs varargout{1} = count; varargout{2} = ifr; varargout{3} = spikeRaster; varargout{4} = psthKurtosis; end %% Function - doTurboTrendBoot function ifr = doTurboTrendBoot(samples,spikeCount,trials,rate,lambda,psthT) n = numel(psthT); % bootstrap indices for row replacement [~,ix] = bootstrp(samples,[],zeros(1,trials)); yFit = zeros(samples,length(psthT)); for i = 1:samples count = spikeCount(ix(:,i),:); firingRate = sum(count,1)./trials.*rate; [~, ~, yFit(i,:)] = turbotrend(psthT, firingRate, lambda, n); end ifr = zeros(4,size(yFit,2)); ifr(1,:) = nanmean(yFit,1); ifr(2,:) = nanstd(yFit,1); ifr(3:4,:) = bootci(samples,@mean,yFit); end %% Function - doInstantFR function ifr = doInstantFR(s,psthT,samples) % try two different approaches to compute the IFR per trial, but number of spikes usually way to low % to achieve robust results ifrTrials = zeros(numel(s),numel(psthT)); for n = 1:numel(s) % ifrTrials(n,:) = instantfr(s{n},psthT); try spikeTimes = s{n}; spikeTimes = spikeTimes - psthT(1); [tt, rate] = BayesRR(spikeTimes); tt = tt + psthT(1); ifrTrials(n,:) = interp1(tt,rate,psthT); end end ifr = zeros(4,length(psthT)); ifr(1,:) = nanmean(ifrTrials,1); ifr(2,:) = nanstd(ifrTrials,1); ifr(3:4,:) = bootci(samples,@nanmean,ifrTrials); end
github
HelmchenLabSoftware/OCIA-master
concatanateSegments.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/concatanateSegments.m
1,464
utf_8
768b37514426be26a3cc94efe0113aa4
%dirname='F:\data tetrodes\th_8\th_8_2014_10_28_a'; function f= concatanateSegments(dirname) list = dir(dirname); i=3; oldExpName='Experiment'; whiskingAll = []; mkdir(fullfile(dirname,'whiskByTrial')); count = 0; for i=3:length(list) fname = list(i).name; ind=strfind(fname,'_Whisker_Tracking'); if(~isempty(ind)) expname = fname(1:ind); load(fullfile(dirname,fname)); if (strcmp(oldExpName,expname)) whiskingAll = [whiskingAll; MovieInfo.AvgWhiskerAngle']; else if ~isempty(whiskingAll) count = count+1; save(fullfile(dirname,'whiskByTrial',[oldExpName 't' num2str(count) '.mat']),'whiskingAll'); whiskingAll = []; end whiskingAll = [whiskingAll; MovieInfo.AvgWhiskerAngle']; end oldExpName = expname; end end count=count+1; save(fullfile(dirname,'whiskByTrial',[oldExpName 't' num2str(count) '.mat']),'whiskingAll'); %% subdirname=fullfile(dirname,'whiskByTrial'); sublist = dir(subdirname); load(fullfile(subdirname,sublist(3).name)); [nr nc] = size(whiskingAll); whiskAngle = nan(nr+5,numel(sublist)-2); for i=3:numel(sublist) load(fullfile(subdirname,sublist(i).name)); whiskAngle(1:length(whiskingAll),i-2)=whiskingAll; end save(fullfile(dirname, 'whiskAngle.mat'),'whiskAngle'); xlswrite('whiskAngle',whiskAngle); end
github
HelmchenLabSoftware/OCIA-master
wt_keyboard_shortcuts.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/wt_knutsen/wt_keyboard_shortcuts.m
887
utf_8
80026debb0b351752a721eab3a1cdda9
% WT_SHOW_KEYBOARD_SHORTCUTS % Show keyboard shortcuts. function wt_keyboard_shortcuts cShortcuts = { ... 'Ctr+P Open parameters window' ... 'Ctr+D Dump current view to printer, file or clipboard' ... 'Ctr+S Save data' ... 'Ctr+N Load next movie in list' ... 'Ctr+H Hide/unhide image' ... 'Ctr+M Play movie from current frame' ... 'SPACE Stop/start tracking' ... 'Any number Go back N frames' ... '0 (zero) Go forward one frame' ... 'Ctr+G Open Go-to-frame dialog' ... 'Ctr+E Edit notes' ... }; msgbox(cShortcuts, 'WT Keyboard Shortcuts') return;
github
HelmchenLabSoftware/OCIA-master
wt_find_nose.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/wt_knutsen/wt_find_nose.m
932
utf_8
975914d45d66953aedf8d6b290311c4d
% WT_FIND_NOSE Finds the nose in image, given eye positions. % % Whisker Tracker (WT) % % Authors: Per Magne Knutsen, Dori Derdikman % % (c) Copyright 2004 Yeda Research and Development Company Ltd., % Rehovot, Israel % % This software is protected by copyright and patent law. Any unauthorized % use, reproduction or distribution of this software or any part thereof % is strictly forbidden. % % Citation: % Knutsen, Derdikman, Ahissar (2004), Tracking whisker and head movements % of unrestrained, behaving rodents, J. Neurophys, 2004, IN PRESS % function vNose = wt_find_nose(vRightEye, vLeftEye, nAxLen) nMidPnt = [mean([vRightEye(:,1) vLeftEye(:,1)],2) mean([vRightEye(:,2) vLeftEye(:,2)],2)]; % eye midpoint vRrelM = vRightEye - nMidPnt; vAngRrelX = rad2deg(atan(vRrelM(:,2)./vRrelM(:,1))); vAngNrelX = deg2rad(90 + vAngRrelX); vNrelX = [nAxLen*cos(vAngNrelX) nAxLen*sin(vAngNrelX)]; vNose = nMidPnt + vNrelX; return;
github
HelmchenLabSoftware/OCIA-master
wt_change_whisker_width.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/wt_knutsen/wt_change_whisker_width.m
507
utf_8
42e2a89228861c394eea10f3855e1ff8
%%%% WT_CHANGE_WHISKER_WIDTH %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Open dialog window and allow user to select width of displayed whiskers % in pixels. function wt_change_whisker_width global g_tWT sAns = inputdlg('Set whisker width in pixels', 'WT'); % Exceptions if isempty(sAns), return; end if g_tWT.WhiskerWidth < 1, g_tWT.WhiskerWidth = 1; end if g_tWT.WhiskerWidth > 50, g_tWT.WhiskerWidth = 50; end g_tWT.WhiskerWidth = str2num(sAns{1}); % Refresh display wt_display_frame return;
github
HelmchenLabSoftware/OCIA-master
wt_reset_all.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/wt_knutsen/wt_reset_all.m
1,679
utf_8
1226ca71091a23a6f1f8303cb5f55ec0
% WT_RESET_ALL % Reset all movie and tracking parameters % % Whisker Tracker (WT) % % Authors: Per Magne Knutsen, Dori Derdikman % % (c) Copyright 2004 Yeda Research and Development Company Ltd., % Rehovot, Israel % % This software is protected by copyright and patent law. Any unauthorized % use, reproduction or distribution of this software or any part thereof % is strictly forbidden. % % Citation: % Knutsen, Derdikman, Ahissar (2004), Tracking whisker and head movements % of unrestrained, behaving rodents, J. Neurophys, 2004, IN PRESS % function wt_reset_all % Issue warning sAnswer = questdlg('This action will delete all tracked whiskers, head-movements and associated parameters. Continue?', ... 'Title', 'Yes', 'No', 'No'); if strcmp(sAnswer, 'No'), return; end global g_tWT g_tWT.MovieInfo.Roi = [1 1 g_tWT.MovieInfo.Width-1 g_tWT.MovieInfo.Height-1]; g_tWT.MovieInfo.Rot = 0; %g_tWT.MovieInfo.ResizeFactor = 1; g_tWT.MovieInfo.Flip = [0 0]; g_tWT.MovieInfo.SplinePoints = []; g_tWT.MovieInfo.WhiskerSide = []; g_tWT.MovieInfo.Angle = []; g_tWT.MovieInfo.PositionOffset = []; g_tWT.MovieInfo.Intersect = []; g_tWT.MovieInfo.RefLine = [0 1; 0 2]; g_tWT.MovieInfo.RightEye = []; g_tWT.MovieInfo.LeftEye = []; g_tWT.MovieInfo.Nose = []; g_tWT.MovieInfo.StimulusA = []; g_tWT.MovieInfo.StimulusB = []; g_tWT.MovieInfo.EyeNoseAxLen = []; g_tWT.MovieInfo.ImCropSize = [g_tWT.MovieInfo.Width g_tWT.MovieInfo.Height]; g_tWT.MovieInfo.Curvature = []; g_tWT.MovieInfo.ObjectRadPos = []; g_tWT.MovieInfo.WhiskerIdentity = {}; g_tWT.MovieInfo.LastFrame = []; g_tWT.MovieInfo.CalBarLength = []; g_tWT.MovieInfo.CalibCoords = [0 0;0 0]; wt_display_frame return
github
HelmchenLabSoftware/OCIA-master
wt_clean_splines.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/wt_knutsen/wt_clean_splines.m
7,905
utf_8
2e17634243b0ca52ef2135a4c7ca49a8
% WT_CLEAN_SPLINES % % Clean splinepoints by removing movements of certain amplitude and % duration. Also included is an optional low-pass filter (mainly intended % to filter head-movements before tracking whiskers). Note that all % changes made are permanent % % Syntax: wt_clean_splines(W, OPT), where % W is the index of the whisker to be cleaned % OPT is an optional string command only used by the function % internally. % % If you call the function directly, you never need to give the OPT % parameter. This function will only work when the WT GUI is launched, and % then only on the currently loaded movie. function wt_clean_splines(w, varargin) global g_tWT persistent nWd; persistent nAmp; persistent nLp; if nargin == 3, nLp = varargin{2}; % use passed low-filt value when saving changes else, nLp = 0; % default low-pass (0 means no low-pass) end if isempty(nWd) nWd = 2; % default pulse-width nAmp = 2; % default pulse-amplitude end mOrigSplPoints = []; % Check if we should execute one of the sub-routines straight away... if nargin >= 2 switch varargin{1} case 'setwidth' nWd = str2num(char(inputdlg(sprintf('Set maximum jitter-width (in frames). Save changes from the menu after reviewing the changes.\n'), 'Set width'))); case 'setamplitude' nAmp = str2num(char(inputdlg(sprintf('Set maximum jitter-amplitude. Save changes from the menu after reviewing the changes.\n'), 'Set amplitude'))); case 'lowpass' sLowPass = 'Set low-pass frequency. Save changes from menu after reviewing the changes.\n'; nLp = str2num(char(inputdlg(sLowPass, 'Set low-pass frequency'))); case 'savechanges' SaveModifiedSplines(w, nWd, nLp, nAmp); return; end end cTitles = []; if w == 0 % Clean head-movements mOrigSplPoints = [g_tWT.MovieInfo.RightEye g_tWT.MovieInfo.LeftEye]; cTitles = [{'Right-eye X'}, {'Right-eye Y'}, {'Left-eye X'}, {'Left-eye Y'}]; else mOrigSplPoints = []; for s = 1:size(g_tWT.MovieInfo.SplinePoints, 1) for nDim = 1:2 if (s == 1) & (nDim == 1), continue, end vData = reshape(g_tWT.MovieInfo.SplinePoints(s,nDim,:,w), size(g_tWT.MovieInfo.SplinePoints, 3), 1); mOrigSplPoints = [mOrigSplPoints vData]; if nDim == 2, sDim = 'Hor';, else sDim = 'Rad';, end; cTitles{size(cTitles,2)+1} = sprintf('Point# %d - %s', s, sDim); end end end % Plot original splines PlotModifiedSplines(mOrigSplPoints, cTitles, nWd, nLp, nAmp, w); % start with default pulse-width = 2 return; %%%% PLOT_MODIFIED_SPLINES %%%% function PlotModifiedSplines(mSplPoints, cTitles, nWd, nLp, nAmp, w) global g_tWT figure(333); clf; set(gcf, 'DoubleBuffer', 'on', 'Menu', 'None', 'Name', 'WT Clean', 'NumberTitle', 'off') % Plot splineas in different sub-panes for s = 1:size(mSplPoints,2) subplot(size(mSplPoints,2), 1, s); hold on vXlim = [0 size(mSplPoints,1)]; vYlim = [min(mSplPoints(:,s))-5 max(mSplPoints(:,s))+5]; % Figure title if s == 1 title(sprintf('Original trace is red, new trace in blue. Width=%d, Amplitude=%d Low-pass=%d', nWd, nAmp, nLp)) end % Plot original trace vY = mSplPoints(:,s); vY(find(vY == 0)) = NaN; plot(1:size(mSplPoints,1), vY, 'r') % Plot cleaned trace mSlpPointsCleaned = CleanTrace(mSplPoints(:,s), nWd, nLp, nAmp); plot(1:size(mSplPoints,1), mSlpPointsCleaned, 'b') % Set axes properties set(gca, 'xlim', vXlim, 'ylim', vYlim, 'FontSize', 8, ... 'xtick', vXlim(1):250:vXlim(2), ... 'ytick', [] ) ylabel('Pixel') if s == size(mSplPoints,2), xlabel('Frame#'), end title(cTitles{s}) end % Create figure menu uimenu(gcf, 'Label', 'Width', 'Callback', [sprintf('wt_clean_splines(%d, ''setwidth'')', w)]); uimenu(gcf, 'Label', 'Amplitude', 'Callback', [sprintf('wt_clean_splines(%d, ''setamplitude'')', w)]); uimenu(gcf, 'Label', 'Low-pass', 'Callback', [sprintf('wt_clean_splines(%d, ''lowpass'')', w)]); uimenu(gcf, 'Label', 'Save changes', 'Callback', [sprintf('wt_clean_splines(%d, ''savechanges'', %d); close(%d); figure(%d)', w, nLp, gcf, findobj('Tag', 'WTMainWindow') )]); uimenu(gcf, 'Label', 'Exit', 'Callback', [sprintf('close(%d)', gcf)]); return; %%%% SAVE_MODIFIED_SPLINES %%%% function SaveModifiedSplines(w, nWd, nLp, nAmp) global g_tWT % Give warning to user switch questdlg('These changes are irreversible! Are you should you want to save these changes?', 'Warning', 'Yes', 'No', 'No') case 'No' return; case 'Yes' if w == 0 g_tWT.MovieInfo.RightEye(:,1) = CleanTrace(g_tWT.MovieInfo.RightEye(:,1), nWd, nLp, nAmp); g_tWT.MovieInfo.RightEye(:,2) = CleanTrace(g_tWT.MovieInfo.RightEye(:,2), nWd, nLp, nAmp); g_tWT.MovieInfo.LeftEye(:,1) = CleanTrace(g_tWT.MovieInfo.LeftEye(:,1), nWd, nLp, nAmp); g_tWT.MovieInfo.LeftEye(:,2) = CleanTrace(g_tWT.MovieInfo.LeftEye(:,2), nWd, nLp, nAmp); g_tWT.MovieInfo.Nose = wt_find_nose(g_tWT.MovieInfo.RightEye, g_tWT.MovieInfo.LeftEye, g_tWT.MovieInfo.EyeNoseAxLen); else %%% new mOrigSplPoints = []; for s = 1:size(g_tWT.MovieInfo.SplinePoints, 1) for nDim = 1:2 if (s == 1) & (nDim == 1), continue, end vData = squeeze(g_tWT.MovieInfo.SplinePoints(s,nDim,:,w)); g_tWT.MovieInfo.SplinePoints(s,nDim,:,w) = ... CleanTrace(vData, nWd, nLp, nAmp); end end % Replace NaN's with zeros g_tWT.MovieInfo.SplinePoints(find(isnan(g_tWT.MovieInfo.SplinePoints))) = 0; %%% % mOrigSplPoints = [ ... % reshape(g_tWT.MovieInfo.SplinePoints(1,2,:,w), size(g_tWT.MovieInfo.SplinePoints, 3), 1) ... % (reshape(g_tWT.MovieInfo.SplinePoints(2,2,:,w), size(g_tWT.MovieInfo.SplinePoints, 3), 1)) ... % (reshape(g_tWT.MovieInfo.SplinePoints(3,2,:,w), size(g_tWT.MovieInfo.SplinePoints, 3), 1)) ... % (reshape(g_tWT.MovieInfo.SplinePoints(2,1,:,w), size(g_tWT.MovieInfo.SplinePoints, 3), 1)) ]; % % Y coordinates % for s = 1:3 % mSlpPointsCleaned = CleanTrace(mOrigSplPoints(:,s), nWd, nLp, nAmp); % g_tWT.MovieInfo.SplinePoints(s, 2, : ,w) = mSlpPointsCleaned; % end % % X coordinate for mid spline-point % mSlpPointsCleaned = CleanTrace(mOrigSplPoints(:,4), nWd, nLp, nAmp); % g_tWT.MovieInfo.SplinePoints(2, 1, : ,w) = mSlpPointsCleaned; g_tWT.MovieInfo.Angle(:,w) = zeros(size(g_tWT.MovieInfo.Angle(:,w))); % clear angle end end wt_set_status(sprintf('Saved trace %d with width = %d and low-pass = %d', w, nWd, nLp, nAmp)) return; %%%% CLEAN_TRACE %%%% function vNew = CleanTrace(vOld, nMaxWidth, nLowPass, nMaxAmp) global g_tWT vNew = vOld; % Iterate over range of widths and amplitudes, and clean out detected jitter for w = 1:nMaxWidth for a = 1:nMaxAmp vTempl = [0 ones(1,w) 0] * a; for i = 1:length(vNew)-(w+1) vec = vNew(i:i+length(vTempl)-1)'; if sum(abs(vTempl - abs((vec-vec(1))))) == 0 vNew(i:i+length(vTempl)-1) = vNew(i); end end end end % Low-pass filter vNew(find(vNew == 0)) = NaN; if nLowPass > 0 vIn = vNew; [a,b] = butter(3, nLowPass/(g_tWT.MovieInfo.FramesPerSecond/2), 'low'); vFiltSrsIndx = find(~isnan(vIn)); vFiltSeries = vIn(vFiltSrsIndx); vOut = zeros(size(vIn))*NaN; vOut(vFiltSrsIndx) = filtfilt(a, b, vFiltSeries); vNew = vOut; end return;
github
HelmchenLabSoftware/OCIA-master
wt_graphs.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/wt_knutsen/wt_graphs.m
37,590
utf_8
e8c936d149d617165a414402eb0796d8
function wt_graphs( varargin ) % WT_GRAPHS % Organize and create graphs % % Usage: % wt_graphs % wt_graphs(CMD) % wt_graphs(VAR, TGL) % % Inputs: % CMD close % refresh % VAR angle % curvature % TGL Toggle parameter ON/OFF % if length(varargin) == 2 varargin{1} varargin{2} end global g_tWT persistent p_vRefLine; persistent p_vPlotWhichWhiskers; persistent p_cActivePlots; persistent p_nAngleDelta; % Determine which plots to show if nargin ~= 2 % Reset all parameters (e.g. when menu is closed) if nargin == 1 switch lower(varargin{1}) case 'close' p_vPlotWhichWhiskers = []; p_cActivePlots = []; delete(findobj('Name', 'WT Plots')) return; case 'refresh' p_vRefLine = []; wt_graphs; end end % Activate menu, or create new if it does not exist if findobj('Tag', 'plotprefs'), figure(findobj('Tag', 'plotprefs')); else, CreateMenu; end else %%% PLOT GRAPHS % If there are two input arguments, it means either that % 1 - a graph should be turned ON/OFF, or % 2 - if the first argument is a number that a whisker should be turned ON/OFF nFS = g_tWT.MovieInfo.FramesPerSecond; if nargin == 2 | nargin == 0 sPlotWhat = varargin{1}; % type of plot nShow = varargin{2}; % if plot should be turned 1=ON or 0=OFF if ~isempty(str2num(sPlotWhat)) sPlotWhat = str2num(sPlotWhat); if nShow if isempty(p_vPlotWhichWhiskers), p_vPlotWhichWhiskers = sPlotWhat; else p_vPlotWhichWhiskers(end+1) = sPlotWhat; end else if isempty(p_vPlotWhichWhiskers), return; % we shouldn't get here... else % Remove whisker from list p_vPlotWhichWhiskers = p_vPlotWhichWhiskers(find(p_vPlotWhichWhiskers~=sPlotWhat)); end end else % Create list of plots to show if nShow % turn ON if isempty(p_cActivePlots), p_cActivePlots = {sPlotWhat}; else p_cActivePlots{end+1} = sPlotWhat; end else % turn OFF if isempty(p_cActivePlots), return; % we shouldn't get here... else % Remove plot from list vKeep = []; for p = 1:size(p_cActivePlots,2) if ~strcmp(char(p_cActivePlots{p}), sPlotWhat) vKeep = [vKeep p]; end end p_cActivePlots = {p_cActivePlots{[vKeep]}}; end end end else, wt_error('Mistake in input argument list'); return; end % Don't open window if there are no head movements or options selected if islogical(p_vPlotWhichWhiskers~=0) & (isempty(p_vPlotWhichWhiskers) | isempty(p_cActivePlots)) return end % Open figure window if not already opened if isempty(findobj('Name', 'WT Plots')) figure; set(gcf, 'NumberTitle', 'off', ... 'Name', 'WT Plots', ... 'Doublebuffer', 'on', ... 'MenuBar', 'figure', ... 'Renderer', 'painters', ... 'BackingStore', 'on' ); CreatePushButtons; else figure(findobj('Name', 'WT Plots')); CreatePushButtons; end % Determine which figure to plot, calculate their midlines and % respective positions in the current subplot. % - work from bottom of figure and up... % keep structure that contains 1) type of plot, 2) mid-line, 3) height % (2 and 3 is for normalization of the trace and the calibration bars) % We keep track of plot-type by name and number (for sorting) tPlots = struct('order',{{'Triggers', 'Position from object', 'Base Translation', 'Curvature', 'Angle', 'Velocity', 'Acceleration'}}); tPlots.proportion = [ ... .1 ... % triggers .15 ... % positon from object .15 ... % Base Translation .15 ... % curvature .15 ... % angle .15 ... % velocity .15 ... % acceleration ]; tPlots.midline = zeros(1, size(tPlots.order, 2)); tPlots.height = zeros(1, size(tPlots.order, 2)); % Units of plots and calibration bars tPlots.calib = [... NaN, ... % ON/OFF 2, ... % Position from object, mm or pix 1, ... % Base Translation, mm or pix NaN, ... % Curvature, mm or pix 5, ... % Degrees angle 500, ... % Velocity, deg/sec 250 ... % Acceleration, deg/sec^2 ]; nCurrHeightUsed = 0; % Available height of subplot already used for p = 1:size(tPlots.order, 2) % Check if plot should be included if sum(strcmp(p_cActivePlots, char(tPlots.order(p)))) >= 1 tPlots.midline(p) = nCurrHeightUsed + tPlots.proportion(p)/2; tPlots.height(p) = tPlots.proportion(p); nCurrHeightUsed = nCurrHeightUsed + tPlots.proportion(p); end end % Expand all traces to occupy full height of subplot (ie. normalize to height of 1) tPlots.midline = tPlots.midline ./ nCurrHeightUsed; tPlots.height = tPlots.height ./ nCurrHeightUsed; % Number of extra panels (e.g. for triggered averages if sum( [strcmp(p_cActivePlots, 'Avg cycle (trig A)') strcmp(p_cActivePlots, 'Avg cycle (trig B)')]) bExtraPanel = 1; else, bExtraPanel = 0; end % - delete existing traces if reference angle or AngleDelta has % changed (also happens when user clicks Refresh) if ~isequal(p_vRefLine, g_tWT.MovieInfo.RefLine) | ~isequal(p_nAngleDelta, g_tWT.MovieInfo.AngleDelta) g_tWT.MovieInfo.Angle = []; g_tWT.MovieInfo.Intersect = []; g_tWT.MovieInfo.PositionOffset = []; g_tWT.MovieInfo.Curvature = []; p_vRefLine = g_tWT.MovieInfo.RefLine; p_nAngleDelta = g_tWT.MovieInfo.AngleDelta; end % Iterate over whiskers for w = 1:length(p_vPlotWhichWhiskers) % All plots are normalized according to their proportionate height % to the subplot (see above) if bExtraPanel nFrameStart = 1+5*(w-1); nFrameEnd = nFrameStart+3; hLeftPanel = subplot(length(p_vPlotWhichWhiskers), 4+bExtraPanel, [nFrameStart:nFrameEnd]); hold on hRightPanel = subplot(length(p_vPlotWhichWhiskers), 4+bExtraPanel, nFrameEnd+1); hold on nRightPanelLength = 0; else hLeftPanel = subplot(length(p_vPlotWhichWhiskers), 1, w); hold on end % Plot head movements if p_vPlotWhichWhiskers(w) == 0 vN = FilterSeries(g_tWT.MovieInfo.Nose(:,2)); [vN, sUnit] = wt_pix_2_mm(vN ./ max(vN)); PlotTrace(vN, vN, hLeftPanel, 'nose', 0.5, 'Head Y Pos', nFS) hold on nCurrentFrame = get(g_tWT.Handles.hSlider, 'Value'); hFrameMarker = plot([nCurrentFrame nCurrentFrame].*(1000/nFS), [-.5 1.5], 'r:'); set(hFrameMarker, 'Tag', 'framemarker') set(hLeftPanel, 'ylim', [0 1], ... 'ytick', [], ... 'xlim', [1 nMovDur], ... 'box', 'on', ... 'FontSize', 8, ... 'Tag', 'tracesplot', ... 'ButtonDownFcn', [sprintf('v=get(gca,''CurrentPoint'');wt_display_frame(round(v(1,1)/%d))', 1000/nFS)] ); axes(hLeftPanel); title(sprintf('%s, %d frames/sec, LoPass=%dHz', .... g_tWT.MovieInfo.Filename, ... g_tWT.MovieInfo.FramesPerSecond, ... str2num(get(findobj('tag','lowpass'), 'String')) )); xlabel('Time (ms)'); % Create black bar bar to the left of the plot vPosition = get(hLeftPanel, 'Position'); hBlob = uicontrol(gcf, 'Style', 'frame', ... 'Units', 'Normalized', ... 'Position', [vPosition(1)-0.075 vPosition(2) 0.025 vPosition(4)], ... 'ForegroundColor', [0 0 0], 'BackgroundColor', [0 0 0] ); continue; end % Find missing frames vSplFrames = find(sum(sum(g_tWT.MovieInfo.SplinePoints(:,:,:,p_vPlotWhichWhiskers(w)))) > 0); % tracked frames try vAngFrames = find(g_tWT.MovieInfo.Angle(:,p_vPlotWhichWhiskers(w)) ~= 0 ); % frames with computed angle vMissingFrames = setdiff(vSplFrames, vAngFrames); % tracked frames without angle catch, vMissingFrames = vSplFrames; end % - compute if ~isempty(vMissingFrames) mSplinePoints = g_tWT.MovieInfo.SplinePoints(:, :, vMissingFrames, p_vPlotWhichWhiskers(w)); % angle [g_tWT.MovieInfo.Angle(vMissingFrames, p_vPlotWhichWhiskers(w)) g_tWT.MovieInfo.Intersect(vMissingFrames,1:2,p_vPlotWhichWhiskers(w))] = ... wt_get_angle(mSplinePoints, g_tWT.MovieInfo.RefLine, g_tWT.MovieInfo.AngleDelta); end % Plot angle nAngleIndx = find(strcmp(tPlots.order, 'Angle')); vAngle = g_tWT.MovieInfo.Angle(:, p_vPlotWhichWhiskers(w)); vAngleFilt = zeros(size(vAngle))*NaN; vAngle(find(vAngle==0)) = NaN; vAngleFilt = FilterSeries(vAngle, 'angle'); if tPlots.height(nAngleIndx) ~= 0 [vAngle, nNormFact] = NormalizeToHeight(vAngleFilt, tPlots.midline(nAngleIndx), tPlots.height(nAngleIndx)); PlotTrace(vAngle, vAngleFilt, hLeftPanel, 'angle', tPlots.midline(nAngleIndx), 'Angle', nFS); DrawCalibrationBar(nNormFact, tPlots.calib(nAngleIndx), vAngle, sprintf('%.1f deg', tPlots.calib(nAngleIndx)), nFS) PlotMaxDwellTime(vAngleFilt, vAngle, nNormFact, 'deg', nFS); % - plot average angle if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig A)'))) nLen = PlotTraceWithErrorBars(vAngle, vAngleFilt, g_tWT.MovieInfo.StimulusA, hRightPanel, 'angle-average-stimA'); nRightPanelLength = max([nRightPanelLength nLen]); end if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig B)'))) nLen = PlotTraceWithErrorBars(vAngle, vAngleFilt, g_tWT.MovieInfo.StimulusB, hRightPanel, 'angle-average-stimB'); nRightPanelLength = max([nRightPanelLength nLen]); end end % Plot Base Translation (intersect) nIntersectIndx = find(strcmp(tPlots.order, 'Base Translation')); if tPlots.height(nIntersectIndx) ~= 0 [vIntersect, sUnit] = wt_pix_2_mm(g_tWT.MovieInfo.Intersect(:, 2, p_vPlotWhichWhiskers(w))); vIntersectFilt = FilterSeries(vIntersect); [vIntersect, nNormFact] = NormalizeToHeight(vIntersectFilt, tPlots.midline(nIntersectIndx), tPlots.height(nIntersectIndx)); PlotTrace(vIntersect, vIntersectFilt, hLeftPanel, 'intersect', tPlots.midline(nIntersectIndx), 'Inters', nFS) DrawCalibrationBar(nNormFact, tPlots.calib(nIntersectIndx), vIntersect, sprintf('%d %s', tPlots.calib(nIntersectIndx), sUnit), nFS) PlotMaxDwellTime(vIntersectFilt, vIntersect, nNormFact, sprintf('%s', sUnit), nFS); % - plot mean intersect if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig A)'))) nLen = PlotTraceWithErrorBars(vIntersect, vIntersectFilt, g_tWT.MovieInfo.StimulusA, hRightPanel, 'intersect-average-stimA'); nRightPanelLength = max([nRightPanelLength nLen]); end if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig B)'))) nLen = PlotTraceWithErrorBars(vIntersect, vIntersectFilt, g_tWT.MovieInfo.StimulusB, hRightPanel, 'intersect-average-stimB'); nRightPanelLength = max([nRightPanelLength nLen]); end end % Plot whisker's position from object (Y position relative to object) nPosIndx = find(strcmp(tPlots.order, 'Position from object')); bBreak = 0; if tPlots.height(nPosIndx) ~= 0 mWhisker = g_tWT.MovieInfo.SplinePoints(:,:,:, p_vPlotWhichWhiskers(w)); % Head-movements are tracked try, vObj = g_tWT.MovieInfo.ObjectRadPos(p_vPlotWhichWhiskers(w),:,:); catch warndlg('No object has been marked.'); bBreak = 1; end if ~bBreak try mRightEye = g_tWT.MovieInfo.RightEye; mLeftEye = g_tWT.MovieInfo.LeftEye; mNose = g_tWT.MovieInfo.Nose; nWhiskerSide = g_tWT.MovieInfo.WhiskerSide(p_vPlotWhichWhiskers(w)); vPosFromObj = wt_get_position_offset(mWhisker, ... vObj, ... g_tWT.MovieInfo.ImCropSize, ... g_tWT.MovieInfo.RadExt, ... g_tWT.MovieInfo.HorExt, ... mRightEye, ... mLeftEye, ... mNose, ... nWhiskerSide ); catch vPosFromObj = wt_get_position_offset(mWhisker, ... vObj, ... g_tWT.MovieInfo.ImCropSize, ... g_tWT.MovieInfo.RadExt, ... g_tWT.MovieInfo.HorExt ); end g_tWT.MovieInfo.PositionOffset(1:length(vPosFromObj), p_vPlotWhichWhiskers(w)) = vPosFromObj; g_tWT.MovieInfo.PositionOffset(find(g_tWT.MovieInfo.PositionOffset==0)) = NaN; [vPosFromObj, sUnit] = wt_pix_2_mm(g_tWT.MovieInfo.PositionOffset(:, p_vPlotWhichWhiskers(w))); vPosFromObjFilt = FilterSeries(vPosFromObj); [vPosFromObj, nNormFact] = NormalizeToHeight(vPosFromObjFilt, tPlots.midline(nPosIndx), tPlots.height(nPosIndx)); PlotTrace(vPosFromObj, vPosFromObjFilt, hLeftPanel, 'position-offset', tPlots.midline(nPosIndx), 'Pos', nFS) DrawCalibrationBar(nNormFact, tPlots.calib(nPosIndx), vPosFromObj, sprintf('%.f %s', tPlots.calib(nPosIndx), sUnit), nFS) PlotMaxDwellTime(vPosFromObjFilt, vPosFromObj, nNormFact, sprintf('%s', sUnit), nFS, 0); % - plot average position if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig A)'))) nLen = PlotTraceWithErrorBars(vPosFromObj, vPosFromObjFilt, g_tWT.MovieInfo.StimulusA, hRightPanel, 'PositionFromPbject-average-stimA'); nRightPanelLength = max([nRightPanelLength nLen]); end if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig B)'))) nLen = PlotTraceWithErrorBars(vPosFromObj, vPosFromObjFilt, g_tWT.MovieInfo.StimulusB, hRightPanel, 'PositionFromPbject-average-stimB'); nRightPanelLength = max([nRightPanelLength nLen]); end end end % Plot velocity nVelocityIndx = find(strcmp(tPlots.order, 'Velocity')); if tPlots.height(nVelocityIndx) ~= 0 vVelocityFilt = [NaN; diff(vAngleFilt)*g_tWT.MovieInfo.FramesPerSecond]; [vVelocity, nNormFact] = NormalizeToHeight(vVelocityFilt, tPlots.midline(nVelocityIndx), tPlots.height(nVelocityIndx)); PlotTrace(vVelocity, vVelocityFilt, hLeftPanel, 'velocity', tPlots.midline(nVelocityIndx), 'Vel', nFS) DrawCalibrationBar(nNormFact, tPlots.calib(nVelocityIndx), vVelocity, sprintf('%d deg/sec', tPlots.calib(nVelocityIndx)), nFS) PlotMaxDwellTime(vVelocityFilt, vVelocity, nNormFact, '', nFS, 0); % Average velocity across cycles if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig A)'))) nLen = PlotTraceWithErrorBars(vVelocity, vVelocityFilt, g_tWT.MovieInfo.StimulusA, hRightPanel, 'velocity-average-stimB'); nRightPanelLength = max([nRightPanelLength nLen]); end if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig B)'))) nLen = PlotTraceWithErrorBars(vVelocity, vVelocityFilt, g_tWT.MovieInfo.StimulusB, hRightPanel, 'velocity-average-stimB'); nRightPanelLength = max([nRightPanelLength nLen]); end end % Plot acceleration nAccelerationIndx = find(strcmp(tPlots.order, 'Acceleration')); if tPlots.height(nAccelerationIndx) ~= 0 vAccelerationFilt = [NaN; NaN; diff(diff(vAngleFilt))*g_tWT.MovieInfo.FramesPerSecond]; [vAcceleration, nNormFact] = NormalizeToHeight(vAccelerationFilt, tPlots.midline(nAccelerationIndx), tPlots.height(nAccelerationIndx)); PlotTrace(vAcceleration, vAccelerationFilt, hLeftPanel, 'acceleration', tPlots.midline(nAccelerationIndx), 'Acc', nFS) DrawCalibrationBar(nNormFact, tPlots.calib(nAccelerationIndx), vAcceleration, sprintf('%d deg/sec^2', tPlots.calib(nAccelerationIndx)), nFS) PlotMaxDwellTime(vAccelerationFilt, vAcceleration, nNormFact, '', nFS, 0); % Average velocity across cycles if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig A)'))) nLen = PlotTraceWithErrorBars(vAcceleration, vAccelerationFilt, g_tWT.MovieInfo.StimulusA, hRightPanel, 'acceleration-average-stimA'); nRightPanelLength = max([nRightPanelLength nLen]); end if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig B)'))) nLen = PlotTraceWithErrorBars(vAcceleration, vAccelerationFilt, g_tWT.MovieInfo.StimulusB, hRightPanel, 'acceleration-average-stimB'); nRightPanelLength = max([nRightPanelLength nLen]); end end % Plot curvature nCurvatureIndx = find(strcmp(tPlots.order, 'Curvature')); if tPlots.height(nCurvatureIndx) ~= 0 % Find missing frames vSplFrames = find(sum(sum(g_tWT.MovieInfo.SplinePoints(:,:,:,p_vPlotWhichWhiskers(w)))) > 0); % tracked frames try vCurvFrames = find(g_tWT.MovieInfo.Curvature(:,p_vPlotWhichWhiskers(w)) ~= 0 ); % frames with computed curv vMissingFrames = setdiff(vSplFrames, vCurvFrames); % tracked frames without curv catch, vMissingFrames = vSplFrames; end if ~isempty(vMissingFrames) mSplinePoints = g_tWT.MovieInfo.SplinePoints(:, :, vMissingFrames, p_vPlotWhichWhiskers(w)); if g_tWT.MovieInfo.AngleDelta == 0 g_tWT.MovieInfo.Curvature(vMissingFrames, p_vPlotWhichWhiskers(w)) = wt_get_curv_at_base(mSplinePoints); else g_tWT.MovieInfo.Curvature(vMissingFrames, p_vPlotWhichWhiskers(w)) = wt_get_curvature(mSplinePoints); end g_tWT.MovieInfo.Curvature([1:vMissingFrames(1) vMissingFrames(end):end], p_vPlotWhichWhiskers(w)) = NaN; end %[vCurvature, sUnit] = wt_pix_2_mm(g_tWT.MovieInfo.Curvature(:, p_vPlotWhichWhiskers(w))); vCurvature = g_tWT.MovieInfo.Curvature(:, p_vPlotWhichWhiskers(w)); sUnit = 'pix'; if isfield(g_tWT.MovieInfo, 'PixelsPerMM') if ~isempty(g_tWT.MovieInfo.PixelsPerMM) vCurvature = vCurvature .* g_tWT.MovieInfo.PixelsPerMM; sUnit = 'mm'; end end vCurvatureFilt = FilterSeries(vCurvature); [vCurvature, nNormFact] = NormalizeToHeight(vCurvatureFilt, tPlots.midline(nCurvatureIndx), tPlots.height(nCurvatureIndx)); PlotTrace(vCurvature, vCurvatureFilt, hLeftPanel, 'curvature', tPlots.midline(nCurvatureIndx), 'Curv', nFS) DrawCalibrationBar(nNormFact, tPlots.calib(nCurvatureIndx), vCurvature, sprintf('%.2f s', tPlots.calib(nCurvatureIndx), sUnit), nFS) PlotMaxDwellTime(vCurvatureFilt, vCurvature, nNormFact, sprintf('%s', sUnit), nFS); % - plot average curvature if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig A)'))) nLen = PlotTraceWithErrorBars(vCurvature, vCurvatureFilt, g_tWT.MovieInfo.StimulusA, hRightPanel, 'curvature-average-stimA'); nRightPanelLength = max([nRightPanelLength nLen]); end if ~isempty(find(strcmp(p_cActivePlots, 'Avg cycle (trig B)'))) nLen = PlotTraceWithErrorBars(vCurvature, vCurvatureFilt, g_tWT.MovieInfo.StimulusB, hRightPanel, 'curvature-average-stimB'); nRightPanelLength = max([nRightPanelLength nLen]); end end % Plot stimulus nTrigIndx = find(strcmp(tPlots.order, 'Triggers')); if tPlots.height(nTrigIndx) ~= 0 vStimA = g_tWT.MovieInfo.StimulusA; vStimB = g_tWT.MovieInfo.StimulusB; vStimA(find(~vStimA)) = NaN; vStimB(find(~vStimB)) = NaN; % Normalize vStimA = vStimA / max(vStimA) * tPlots.height(nTrigIndx); vStimA = vStimA + tPlots.midline(nTrigIndx)-tPlots.height(nTrigIndx)/2; vStimB = vStimB / max(vStimB) * tPlots.height(nTrigIndx); vStimB = vStimB + tPlots.midline(nTrigIndx)-tPlots.height(nTrigIndx)/2; subplot(hLeftPanel); plot((1:length(vStimA) .*(1000/nFS) ), vStimA/3, 'r', 'LineWidth', 2) subplot(hLeftPanel); plot((1:length(vStimA) .*(1000/nFS) ), vStimB/1.5, 'g', 'LineWidth', 2) end hold on nCurrentFrame = get(g_tWT.Handles.hSlider, 'Value'); hFrameMarker = plot([nCurrentFrame nCurrentFrame].*(1000/nFS), [-.5 1.5], 'r:'); set(hFrameMarker, 'Tag', 'framemarker') % Set plot properties nMovDur = g_tWT.MovieInfo.NumFrames * (1000/g_tWT.MovieInfo.FramesPerSecond); % msec set(hLeftPanel, 'ylim', [0 1], ... 'ytick', [], ... 'xlim', [1 nMovDur], ... 'box', 'on', ... 'FontSize', 8, ... 'Tag', 'tracesplot', ... 'ButtonDownFcn', [sprintf('v=get(gca,''CurrentPoint'');wt_display_frame(round(v(1,1)/%d))', 1000/nFS)] ); axes(hLeftPanel); title(sprintf('%s, %d frames/sec, LoPass=%dHz', .... g_tWT.MovieInfo.Filename, ... g_tWT.MovieInfo.FramesPerSecond, ... str2num(get(findobj('tag','lowpass'), 'String')) ), 'interpreter','none'); xlabel('Time (ms)'); if bExtraPanel if nRightPanelLength <= 0, nRightPanelLength = 100; end set(hRightPanel, 'ylim', [0 1], ... 'ytick', [], ... 'xlim', [1 nRightPanelLength], ... 'box', 'on', ... 'FontSize', 8 ); axes(hRightPanel); title('Cycle average'); xlabel('Time (msec)'); end % Create colored bar left to plots that indicate whisker identity vPosition = get(hLeftPanel, 'Position'); hBlob = uicontrol(gcf, 'Style', 'frame', ... 'Units', 'Normalized', ... 'Position', [vPosition(1)-0.075 vPosition(2) 0.025 vPosition(4)], ... 'ForegroundColor', g_tWT.Colors(p_vPlotWhichWhiskers(w),:), ... 'BackgroundColor', g_tWT.Colors(p_vPlotWhichWhiskers(w),:)); end end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function PrintHeader( sHeader , hWindow , nYpos ) uicontrol(hWindow, 'Style', 'frame', 'Position', [1 nYpos 150 20], ... 'BackgroundColor', [.4 .4 .4] ); uicontrol(hWindow, 'Style', 'text', 'Position', [5 nYpos+2 145 14], ... 'String', sHeader, ... 'HorizontalAlignment', 'center', ... 'foregroundcolor', [.9 .9 .9], ... 'BackgroundColor', [.4 .4 .4], ... 'FontWeight', 'bold' ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Normalize time-series to fit within its dedicated vertical space in % subplot. function [vSeriesOut, nNormFact] = NormalizeToHeight(vSeriesIn, nMidline, nHeight); if length(find(~isnan(vSeriesIn))) == 1 vSeriesOut = vSeriesIn / max(vSeriesIn); nNormFact = max(vSeriesOut) ./ max(vSeriesIn); else vSeriesOut = vSeriesIn - min(vSeriesIn); vSeriesOut = vSeriesOut / max(vSeriesOut) * nHeight; vSeriesOut = vSeriesOut + nMidline - nHeight/2; nHeightOrig = abs(diff([max(vSeriesIn) min(vSeriesIn)])); nHeightNew = abs(diff([max(vSeriesOut) min(vSeriesOut)])); nNormFact = nHeightNew ./ nHeightOrig; end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Low-pass filter timeseries according to GUI settings. function vSeriesOut = FilterSeries(vSeriesIn,varargin) global g_tWT nLowPassFreq = str2num(get(findobj('tag','lowpass'), 'String')); if ~isempty(nLowPassFreq) & ~(nLowPassFreq <= 0) [a,b] = butter(3, nLowPassFreq/(g_tWT.MovieInfo.FramesPerSecond/2), 'low'); vFiltSrsIndx = find(~isnan(vSeriesIn)); vFiltSeries = vSeriesIn(vFiltSrsIndx); vSeriesOut = zeros(size(vSeriesIn))*NaN; vSeriesOut(vFiltSrsIndx) = filtfilt(a, b, vFiltSeries); else, vSeriesOut = vSeriesIn; end vSeriesOut(find(vSeriesOut==0)) = NaN; return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Calculate cycle average of time-series function [vCycleAvg, vCycleError] = GetCycleAverage(vSeriesIn, vStim); vOnsets = find(diff(vStim)==1)+1; % find all onset moments nMinSize = median(diff(vOnsets)) / 2; % remove segments with durations smaller than half of the median duration try vOnsets(find(diff(vOnsets)< nMinSize)) = []; catch wt_error('An error occurred when computing average cycles. Do you have fewer than 2 cycles?') end % Drop cycles that overlap with non-tracked frames vDropIndx = find(vOnsets >= length(vSeriesIn)); if ~isempty(vDropIndx), vOnsets((vDropIndx(1)-1):vDropIndx(end)) = []; end % Drop cycles not in the requested cycle range nFromCycle = str2num(get(findobj('Tag', 'fromcycle'), 'string')); if nFromCycle < 1, nFromCycle = 1; end nToCycle = str2num(get(findobj('Tag', 'tocycle'), 'string')); if nToCycle > length(vOnsets), nToCycle = length(vOnsets); end % Create all segments to use mSegments = []; nIndx = 1; nOnsets = length(vOnsets); for s = 1:nOnsets if s < nFromCycle | s > nToCycle, continue, end if s == nOnsets, vNewSeg = vSeriesIn(vOnsets(s):end); else, vNewSeg = vSeriesIn(vOnsets(s):vOnsets(s+1)-1); end if length(vNewSeg) > size(mSegments,1) % zeropad matrix that holds segments if new segment is longer than % all previous segments padarray(mSegments, length(vNewSeg)-size(mSegments,1), 0, 'post'); end if isempty(mSegments), mSegments = vNewSeg; else, mSegments(1:length(vNewSeg),nIndx) = vNewSeg; end nIndx = nIndx + 1; end % Calculate mean of all segments vCycleAvg = mean(mSegments,2); % Calculate standard-error of all segments vCycleError = std(mSegments, 0, 2) / sqrt(size(mSegments,2)); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Draw calibration bar in subplot function DrawCalibrationBar(nNormFact, nCalibSize, vSeries, sCalibString, nFS) global g_tWT if isempty(vSeries), return; end nCalibLineWidth = 6; nCalibHeight = nCalibSize * nNormFact; nXMax = g_tWT.MovieInfo.NumFrames * (1000/nFS); plot([nXMax-nCalibLineWidth nXMax-nCalibLineWidth] .* (1000/nFS), [min(vSeries) min(vSeries)+nCalibHeight], 'k', 'LineWidth', nCalibLineWidth); hTxt = text(nXMax+25, min(vSeries)+nCalibHeight/2, sCalibString); set(hTxt, 'Rotation', -90, 'HorizontalAlignment', 'center', 'FontSize', 8); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Calculate max dwell-time location in time series % ex. PlotMaxDwellTime(vAngleFilt, vAngle, nNormFact, 'deg') function nMaxDwellTime = PlotMaxDwellTime(vSeriesOrig, vSeriesPlot, nNormFact, sString, nFS, varargin) vBinCenters = min(vSeriesOrig):(max(vSeriesOrig)-min(vSeriesOrig))/100:max(vSeriesOrig); % If data length == 1 if length(find(~isnan(vSeriesOrig))) < 2 | isempty(vBinCenters) nMaxDwellTime = 1; return end if ~isempty(varargin) % Plot line through a given value nMaxDwellTime = varargin{1}; else [vCount, vDwellTime] = hist(vSeriesOrig, vBinCenters); nMaxDwellTime = vDwellTime(find(vCount==max(vCount))); nMaxDwellTime = nMaxDwellTime(1); end nY = (nMaxDwellTime*nNormFact) - diff([min(vSeriesPlot) min(vSeriesOrig*nNormFact)]); hLine = plot([0 length(vSeriesOrig).*(1000/nFS)], [nY nY], 'g:', 'LineWidth', 2); if strcmp(sString, 'deg') sLineString = sprintf('Y = %.5f %s)', nMaxDwellTime, sString); hTxt = text(-2, nY, sprintf('%.1f %s', nMaxDwellTime, sString)); else sLineString = sprintf('Y = %.5f %s', nMaxDwellTime, sString); hTxt = text(-2, nY, sprintf('%.1f %s', nMaxDwellTime, sString)); end set(hLine, 'buttondownfcn', sprintf('msgbox(''%s'')', sLineString)); set(hTxt, 'FontSize', 6, 'HorizontalAlignment', 'right'); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Create the menu window function CreateMenu global g_tWT cOptions = {'Angle', 'Velocity (dA)', 'Acceleration (ddA)', 'Curvature', 'Base Translation', 'Position from object', 'Triggers', 'Avg cycle (trig A)', 'Avg cycle (trig B)'}; % Set text parameters nFontSize = 8; nLinSep = 10; nGuiElements = size(cOptions, 2) + size(g_tWT.MovieInfo.SplinePoints, 4) + 3; % options plus filter dialog if ~isempty(g_tWT.MovieInfo.EyeNoseAxLen) nGuiElements = nGuiElements + 1; end % Open figure window vScrnSize = get(0, 'ScreenSize'); nFigHeight = nGuiElements * (nFontSize*2 + nLinSep) + 60; nFigWidth = 150; vFigPos = [5 vScrnSize(4)-(nFigHeight+21) nFigWidth nFigHeight]; hCurrWin = figure; set(hCurrWin, 'NumberTitle', 'off', ... 'Name', 'WT Menu', ... 'Position', vFigPos, ... 'MenuBar', 'none', ... 'Tag', 'plotprefs', ... 'CloseRequestFcn', 'wt_graphs(''close''); closereq;' ) % Place text string and boxes inside window nCurrLine = nFigHeight; nCurrLine = nCurrLine - (nFontSize*2 + nLinSep); PrintHeader('Select plots', hCurrWin, nCurrLine) for o = 1:size(cOptions, 2) nCurrLine = nCurrLine - (nFontSize*2 + nLinSep); uicontrol(hCurrWin, 'Style', 'checkbox', 'Position', [10 nCurrLine 150 20], ... 'Callback', 'wt_graphs(get(gcbo,''string''), get(gcbo,''value''))', ... 'String', char(cOptions(o)), ... 'HorizontalAlignment', 'left', ... 'BackgroundColor', [.8 .8 .8] ); end % Filter options nCurrLine = nCurrLine - (nFontSize*2 + nLinSep); PrintHeader('Low-pass', hCurrWin, nCurrLine) nCurrLine = nCurrLine - (nFontSize*2 + nLinSep); uicontrol(hCurrWin, 'Style', 'edit', 'Position', [40 nCurrLine 40 20], ... 'HorizontalAlignment', 'center', ... 'Tag', 'lowpass' ); uicontrol(hCurrWin, 'Style', 'text', 'Position', [80 nCurrLine-4 30 20], ... 'String', 'Hz', ... 'BackgroundColor', [.8 .8 .8], ... 'HorizontalAlignment', 'center' ) % Whisker representations nCurrLine = nCurrLine - (nFontSize*2 + nLinSep); PrintHeader('Select whiskers', hCurrWin, nCurrLine) for w = 1:size(g_tWT.MovieInfo.SplinePoints, 4) if isempty(g_tWT.MovieInfo.SplinePoints), continue, end nCurrLine = nCurrLine - (nFontSize*2 + nLinSep); hBox = uicontrol(hCurrWin, 'Style', 'checkbox', 'Position', [10 nCurrLine 125 20], ... 'Callback', 'wt_graphs(get(gcbo, ''Tag''), get(gcbo, ''Value''))', ... % 0=OFF, 1=ON 'HorizontalAlignment', 'right', ... 'String', wt_whisker_id(w), ... 'FontWeight', 'bold', ... 'Tag', num2str(w), ... 'foregroundColor', 'w', ... 'BackgroundColor', g_tWT.Colors(w,:) ); end % Checkbox for plotting head-movements if ~isempty(g_tWT.MovieInfo.EyeNoseAxLen) nCurrLine = nCurrLine - (nFontSize*2 + nLinSep); uicontrol(hCurrWin, 'Style', 'checkbox', 'Position', [10 nCurrLine 125 20], ... 'Callback', 'wt_graphs(get(gcbo, ''Tag''), get(gcbo, ''Value''))', ... % 0=OFF, 1=ON 'String', 'Head', ... 'FontWeight', 'bold', ... 'Tag', '0', ... 'BackgroundColor', [0 0 0], ... 'ForegroundColor', [1 1 1] ); end % Refresh pushbutton nCurrLine = nCurrLine - (nFontSize*2 + nLinSep); uicontrol(hCurrWin, 'Style', 'pushbutton', 'Position', [10 nCurrLine 125 20], ... 'Callback', 'wt_graphs(''refresh''); wt_graphs(get(gcbo, ''Tag''), get(gcbo, ''Value''))', ... % 0=OFF, 1=ON 'String', 'Refresh', ... 'FontWeight', 'bold' ); return; %%%%% PLOTTRACE %%%% function PlotTrace(vTrace, vUserData, hAxes, sIdent, vMidline, sString, nFS) axes(hAxes) vXX = (1:length(vTrace)) .* (1000/nFS); hTrace = plot(vXX, vTrace, 'k'); cUserData = {sIdent, vUserData}; hTraceMenu = uicontextmenu; set(hTrace, 'Tag', 'export-trace', 'UserData', cUserData, 'UIContextMenu', hTraceMenu) uimenu(hTraceMenu, 'Label', 'Copy to new figure', 'Callback', 'x=get(gco,''userdata'');figure;plot(x{2})'); hTxt = text(-10, vMidline, sString); set(hTxt, 'Rotation', 90, 'HorizontalAlignment', 'center', 'FontSize', 8); return; %%%% PLOTTRACEWITHERRORBARS %%%% function nLen = PlotTraceWithErrorBars(vTrace, vUserData, vStim, hAxes, sIdent) % Compute mean and standard-error [vMean, vError] = GetCycleAverage(vTrace, vStim); nLen = length(vMean); [vUserData, vError2] = GetCycleAverage(vUserData, vStim); vColor = [.7 .7 .7]; axes(hAxes) vMean = reshape(vMean, length(vMean), 1); vError = reshape(vError, length(vError), 1); vXt = (0:length(vError)-1)'; vXb = flipud(vXt); vYt = vMean + vError; vYb = flipud(vMean - vError); fill([vXt;vXb], [vYt;vYb], vColor, 'EdgeColor', vColor) hTrace = plot(0:length(vMean)-1,vMean, 'k'); cUserData = {sIdent, vUserData}; hTraceMenu = uicontextmenu; set(hTrace, 'Tag', 'export-trace', 'UserData', cUserData, 'UIContextMenu', hTraceMenu) uimenu(hTraceMenu, 'Label', 'Copy to new figure', 'Callback', 'x=get(gco,''userdata'');figure;plot(x{2})'); return; %%%% CREATEPUSHBUTTONS %%%% function CreatePushButtons hFromField = findobj('Tag', 'fromcycle'); if isempty(hFromField), nFromCycle = 2; else, nFromCycle = str2num(get(hFromField, 'string')); end hToField = findobj('Tag', 'tocycle'); if isempty(hToField), nToCycle = 99; else, nToCycle = str2num(get(hToField, 'string')); end clf uicontrol( 'Position', [5 5 20 20], ... 'Style', 'pushbutton', ... 'String', 'G', ... 'FontSize', 7, 'HorizontalAlignment', 'center', ... 'CallBack', @ToggleGrid ); uicontrol( 'Position', [30 5 20 20], ... 'Style', 'pushbutton', ... 'String', 'M', ... 'FontSize', 7, 'HorizontalAlignment', 'center', ... 'CallBack', @ToggleMarkers ); uicontrol( 'Position', [55 5 20 20], ... 'Style', 'pushbutton', ... 'String', 'E', ... 'FontSize', 7, 'HorizontalAlignment', 'center', ... 'CallBack', @ExportData ); uicontrol( 'Position', [85 5 100 20], ... 'Style', 'text', ... 'String', 'Average cycles', ... 'FontSize', 7, ... 'HorizontalAlignment', 'left' ); uicontrol( 'Position', [185 5 30 20], ... 'Style', 'edit', ... 'String', nFromCycle, ... 'Tag', 'fromcycle', ... 'FontSize', 7, 'HorizontalAlignment', 'center' ); uicontrol( 'Position', [215 5 20 20], ... 'Style', 'text', ... 'String', 'to', ... 'FontSize', 7, 'HorizontalAlignment', 'center' ); uicontrol( 'Position', [235 5 30 20], ... 'Style', 'edit', ... 'String', nToCycle, ... 'Tag', 'tocycle', ... 'FontSize', 7, 'HorizontalAlignment', 'center' ); uicontrol( 'Position', [265 5 20 20], ... 'Style', 'pushbutton', ... 'String', '!', ... 'FontSize', 7, 'HorizontalAlignment', 'center', ... 'Callback', 'wt_graphs(''refresh''); wt_graphs(get(gcbo, ''Tag''), get(gcbo, ''Value''))'); % 0=OFF, 1=ON drawnow; return; %%%% TOGGLEGRID %%%% function ToggleGrid(varargin) vhAxes = findobj(gcf, 'Type', 'axes'); % Get handles to all axes children for i = 1:length(vhAxes) if strcmp(get(vhAxes(i), 'xgrid'), 'off') set(vhAxes(i), 'XGrid', 'on'); else set(vhAxes(i), 'XGrid', 'off'); end end return; %%%% TOGGLEMARKERS **** function ToggleMarkers(varargin) persistent pMarkerStatus; if isempty(pMarkerStatus), pMarkerStatus=0; end pMarkerStatus = ~pMarkerStatus; % toggle marker-status if pMarkerStatus, sMarker='.'; else, sMarker='none'; end vhLines = findobj(gcf, 'Type', 'line'); set(vhLines, 'Marker', sprintf('%s',sMarker)); return; %%%% EXPORTDATA %%%% % Export all traces to either a plain text-file or Excel function ExportData(varargin) % Get object handles for all line-elements that will be exported vhTraces = findobj('Tag', 'export-trace'); % Create container that will hold all the data cData = cell({}); cHeaders = cell({}); for h = 1:length(vhTraces) cUserData = get(vhTraces(h), 'Userdata'); cData{h} = cUserData{2}; cHeaders{h} = cUserData{1}; end % Query whether to export to Excel or text file sAns = questdlg('Export to Excel or text file?', 'Export', 'Excel', 'Text file', 'Excel'); if isempty(sAns), return else if strcmp(sAns, 'Excel') ExportToExcel(cHeaders, cData); else [sFilename, sPathname] = uiputfile('*.txt', 'Save data as'); mData = []; for c = 1:size(cData,2) mData(1:length(cData{c}),size(mData,2)+1) = cData{c}; end mData = [(0:(size(mData,1))-1)' mData]; % insert framenumber in 1st column dlmwrite([sPathname sFilename], mData, '\t'); end end return;
github
HelmchenLabSoftware/OCIA-master
wt_wizard_ctrl.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/wt_knutsen/wt_wizard_ctrl.m
10,146
utf_8
875f79eadaf0ebadb41e2143ca2195c3
function wt_wizard_ctrl(sName, sStateVector, sFuncVector) % % Whisker Tracker (WT) % % Authors: Per Magne Knutsen, Dori Derdikman % The code in this script was contributed by Aharon Sheer. % % (c) Copyright 2004 Yeda Research and Development Company Ltd., % Rehovot, Israel % % This software is protected by copyright and patent law. Any unauthorized % use, reproduction or distribution of this software or any part thereof % is strictly forbidden. % % Citation: % Knutsen, Derdikman, Ahissar (2004), Tracking whisker and head movements % of unrestrained, behaving rodents, J. Neurophys, 2004, IN PRESS % global g_tWT persistent nNextState % The state that will be done if we press Perform nStateVectorSize = size(sStateVector); nStrings = nStateVectorSize(1); nFuncVectorSize = size(sFuncVector); if ( nStrings ~= nFuncVectorSize(1) ) error('Num Functions not same as num States'); end %-------------------------------------------------------------------------- % There are several types of states: % 1) the First State. Here the Wizard can only perform the current % state, or advance to the next state, or exit % % 2) the Last State. Here the Wizard can only perform the current state, % or go back to the previous state, or exit, or Finish % % 3) All intermediate states. Here the Wizard can perform the current state, % or go back to the previous state, or advance to the next state, or exit % % 4) Past the Last State. Here the Wizard can only go back to the previous state, % or exit, or Finish %-------------------------------------------------------------------------- nFirstState = 1; nLastState = nStrings; nExitByX = 0; % When user hits "X" in upper right corner % forever loop while 1 %------------------------------------- % Are we at First State? %------------------------------------- if (isempty(nNextState) | (nNextState <= nFirstState) ) %------------------------------------- % First State %------------------------------------- % at beginning % action buttons - display only Perform and Exit nPerform = 1; % no BACK yet nSkip = 2; nExit = 3; nNextState = nFirstState; % step to first state nSkipState = nNextState + 1; nAction = menu('Wizard', ... ['Perform -- ', sStateVector(nNextState, :)], ... ['Skip to ', sStateVector(nSkipState, :)], ... 'Exit'); if (nAction == nExitByX | nAction == nExit) return; % user exited the menu with no choice, or chose Exit elseif (nAction == nSkip) % DO NOT DO THE ACTION % Skip to next action unless already at end if (nNextState < nLastState) nNextState = nNextState + 1; end else % DO THE ACTION success = wt_do_action(nNextState, sFuncVector); if (success) nNextState = nNextState + 1; % Step to Next State end end % end of processing actions else % no longer at beginning nBackState = nNextState - 1; %------------------------------------- % Are we at Intermediate State? %------------------------------------- if (nNextState < nLastState) %------------------------------------- % Intermediate State %------------------------------------- % display both Back and Perform and Skip nSkipState = nNextState + 1; nBack = 1; % action buttons nPerform = 2; nSkip = 3; nExit = 4; nAction = menu('Wizard', ... 'Back', ... ['Perform -- ', sStateVector(nNextState, :)], ... ['Skip to ', sStateVector(nSkipState, :)], ... 'Exit'); if (nAction == nBack) %return to previous state nNextState = nBackState; % DO NOT DO THE ACTION elseif (nAction == nExitByX | nAction == nExit) return; % user exited the menu with no choice, or chose Exit elseif (nAction == nSkip) % DO NOT DO THE ACTION % Skip to next action unless already at end nNextState = nSkipState; else % Perform % DO THE ACTION success = wt_do_action(nNextState, sFuncVector); if (success & (nNextState < nLastState)) nNextState = nNextState + 1; % Step to Next State end end % end of processing actions %------------------------------------- % Are we at Last State? %------------------------------------- elseif (nNextState == nLastState) %------------------------------------- % Last State %------------------------------------- % display both Back and Perform but not Skip, allow Finish nBack = 1; % action buttons nPerform = 2; nExit = 3; nFinish = 4; nAction = menu('Wizard', ... 'Back', ... ['Perform -- ', sStateVector(nNextState, :)], ... 'Exit', ... 'Finish' ... ); if (nAction == nBack) %return to previous state nNextState = nBackState; % DO NOT DO THE ACTION elseif (nAction == nExitByX | nAction == nExit) return; % user exited the menu with no choice, or chose Exit elseif (nAction == nFinish) nNextState = nFirstState; % return to first state return; % user finished processing else % Perform % DO THE ACTION success = wt_do_action(nNextState, sFuncVector); if (success) nNextState = nNextState + 1; % Step to State After Last State end end % end of processing actions %------------------------------------- % Are we at state After Last State? %------------------------------------- else (nNextState > nLastState) %------------------------------------- % State After Last State %------------------------------------- % display Back but not Skip or Perform, allow Finish nBack = 1; % action buttons nFinish = 2; nAction = menu('Wizard', ... 'Back', ... 'Finish' ... ); if (nAction == nBack) %return to previous state nNextState = nBackState; % DO NOT DO THE ACTION elseif (nAction == nExitByX) return; % user exited the menu with no choice else (nAction == nFinish) nNextState = nFirstState; % return to first state return; % user finished processing end; % end of processing actions end % end of all states except First State end %end of all states end % end of while forever % DO THE ACTION function success = wt_do_action(nNextState, sFuncVector) success = 1; % assume success sActionName = deblank(sFuncVector(nNextState, :)); if (strcmp(sActionName, '')) success = 0; % no function name else success = feval(sActionName); end % go to frame... function success = wt_wizard_go_to_frame sF = inputdlg('Go to frame', 'Go to frame', 1); if isempty(sF) % WARNING -- fail if frame NOT found success = 0; % 'Go to frame' failed else wt_display_frame(str2num(char(sF))); success = 1; % 'Go to Frame' succeeded end % 'Tracking head movements' % To terminate input press RETURN function success = wt_wizard_init_head_tracker success = 1; wt_init_head_tracker; % Tracking head movements % Cleaning head movements function success = wt_wizard_clean_head_movements success = 1; wt_clean_splines(0) % Cleaning head movements % 'Setting Image Region of Interest' function success = wt_wizard_select_roi success = 1; wt_select_roi; % 'Setting Image Region of Interest' % Setting Parameters function success = wt_wizard_tracking_parameters success = 1; wt_set_parameters; % 'Setting Parameters' % Marking Whisker % To terminate input press RETURN function success = wt_wizard_mark_whisker global g_tWT success = 1; wt_mark_whisker; % Marking Whisker % verify that a whisker has been marked % find index of last SplinePoint if isempty(g_tWT.MovieInfo.SplinePoints) % no SplinePoint defined success = 0; % failed to define a whisker end % Set last frame function success = wt_wizard_set_last_frame global g_tWT success = 1; sL = inputdlg('Set last frame to track', 'Set last frame', 1, {num2str(get(g_tWT.Handles.hSlider, 'value'))} ... ); if isempty(sL) % WARNING -- fail if last frame NOT found success = 0; % 'Set Last frame' failed else g_tWT.MovieInfo.LastFrame(1:size(g_tWT.MovieInfo.SplinePoints,4)) = str2num(char(sL)); success = 1; % 'Set last Frame' succeeded end % Rotate image anti-clockwise function success = wt_wizard_rotate_anti success = 1; wt_rotate_frame(-1); % Track stimulus squares function success = wt_wizard_track_stimulus success = 1; wt_track_stimulus; % Calibrate function success = wt_wizard_calibrate success = 1; wt_calibration('calibrate'); % 'Set Full Length' function success = wt_wizard_set_full_length global g_tWT success = 1; % find index of last SplinePoint if isempty(g_tWT.MovieInfo.SplinePoints) % no SplinePoint defined success = 0; % do nothing else % Set full length for LAST SplinePoint nIndx = size(g_tWT.MovieInfo.SplinePoints, 4) + 1; wt_mark_whisker('setfulllength', nIndx); end % Edit notes function success = wt_wizard_edit_notes global g_tWT success = 1; % If notes DO NOT yet exist for this movie, pop up the Notes window if isfield(g_tWT.MovieInfo, 'Notes') if isempty(g_tWT.MovieInfo.Notes), wt_edit_notes, end % No notes yet, force writing of notes end
github
HelmchenLabSoftware/OCIA-master
wt_image_preprocess.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/wt_knutsen/wt_image_preprocess.m
1,643
utf_8
8206eeba9fb64b5ae81978e901201c64
function [mImgOut, mImgOutCroppedOnly] = wt_image_preprocess( mImgIn ) % IM = WT_IMAGE_PREPROCESS(IM) % Pre-processes movie frames during tracking: % (1) Crop % (2) Rotate % (3) Invert contrast % global g_tWT bDebug = g_tWT.VerboseMode; mImgOut = mImgIn; % assign original image %%% DEBUG ONLY if bDebug % original image (cropped) hFig = findobj('Tag', 'IMAGE_PREPROCESS_WINDOW'); if isempty(hFig) hFig = figure; set(hFig, 'Tag', 'IMAGE_PREPROCESS_WINDOW', 'DoubleBuffer', 'on', 'Name', 'WT - IMAGE_PREPROCESS_WINDOW', 'numbertitle', 'off') else, figure(hFig), end subplot(1,3,1); imagesc(mImgIn); colorbar; colormap gray; SetPlotProps title('Original (avg subtr)') end %%% DEBUG END % Crop if ~(g_tWT.MovieInfo.Roi(3:4)+1 == [g_tWT.MovieInfo.Height g_tWT.MovieInfo.Width]) mImgOut = imcrop(mImgOut, g_tWT.MovieInfo.Roi); end % Rotate if g_tWT.MovieInfo.Rot ~= 0, mImgOut = imrotate(mImgOut, g_tWT.MovieInfo.Rot, 'bicubic'); end if g_tWT.MovieInfo.Flip(1) mImgOut = flipud(mImgOut); end % flip up-down if g_tWT.MovieInfo.Flip(2) mImgOut = fliplr(mImgOut); end % flip left-right mImgOutCroppedOnly = mImgOut; % Invert if g_tWT.MovieInfo.Invert, mImgOut = (255 - mImgOut) ; end %%% DEBUG ONLY if bDebug % original image (cropped) subplot(1,3,2); imagesc(mImgOut); colorbar; colormap gray title('Crop/rotate/invert'); SetPlotProps; subplot(1,3,3); imagesc(mImgOut); colorbar; colormap gray title('Normalized'); SetPlotProps; drawnow end %%% DEBUG END return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SetPlotProps set(gca, 'xtick', [], 'ytick', [])
github
HelmchenLabSoftware/OCIA-master
wt_set_parameters.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/wt_knutsen/wt_set_parameters.m
9,886
utf_8
f5dbb32b1dbc879034399099bdb6a129
function wt_set_parameters(varargin) % wt_set_parameters global g_tWT % If no movie is loaded, do not open Parameters dialog bMovieLoaded = 0; if isfield(g_tWT.MovieInfo, 'Filename') if ~isempty(g_tWT.MovieInfo.Filename) bMovieLoaded = 1; end end if ~bMovieLoaded, return, end % Execute sub-function if nargin > 0 switch varargin{1} case 'apply' ApplyParams case 'updatevars' UpdateVars(varargin{2}); case 'loadparams' LoadParams; case 'saveparams' SaveParams; case 'savedefaultparams' SaveDefaultParams; end return; end global g_hOptWin; if ~isempty(g_hOptWin), figure(g_hOptWin), return, end %%%% Start of field data %%%% % FORMAT OF PARAMETERS FIELD STRUCTURE % {DESCRIPTION, DEFAULT_VALUE, OPTION, TARGET_VARIABLE} global g_tOptFields; g_tOptFields = []; global g_cFieldNames; g_cFieldNames = []; g_tOptFields.nDisplayTitle = {'Display', '', 'title', ''}; g_tOptFields.nRotate = {'Rotate image (deg)', num2str(g_tWT.MovieInfo.Rot), '', 'g_tWT.MovieInfo.Rot'}; g_tOptFields.vFlip = {'Flip image (up-down left-right)', num2str(g_tWT.MovieInfo.Flip), '', 'g_tWT.MovieInfo.Flip'}; g_tOptFields.vROI = {'Region of interest [x y width height]', num2str(g_tWT.MovieInfo.Roi), '', 'g_tWT.MovieInfo.Roi'}; g_tOptFields.nRefresh = {'Interval between refresh (frames)', num2str(g_tWT.MovieInfo.ScreenRefresh), '', 'g_tWT.MovieInfo.ScreenRefresh'}; g_tOptFields.nLoadFrames = {'Pre-load (frames)', num2str(g_tWT.MovieInfo.NoFramesToLoad), '', 'g_tWT.MovieInfo.NoFramesToLoad'}; g_tOptFields.nHeadTitle = {'Coordinates of reference line', '', 'title', ''}; g_tOptFields.vHeadA = {'Point A', num2str(g_tWT.MovieInfo.RefLine(1,:)), '', 'g_tWT.MovieInfo.RefLine(1,:)'}; g_tOptFields.vHeadB = {'Point B', num2str(g_tWT.MovieInfo.RefLine(2,:)), '', 'g_tWT.MovieInfo.RefLine(2,:)'}; g_tOptFields.nFindWhiskTitle = {'Whisker tracking parameters', '', 'title', ''}; g_tOptFields.nHorJitterSlow = {'Horizontal jitter [left mid right] SLOW >', num2str(g_tWT.MovieInfo.HorJitterSlow), '', 'g_tWT.MovieInfo.HorJitterSlow'}; g_tOptFields.nHorJitter = {'Horizontal jitter [left mid right] FAST >>', num2str(g_tWT.MovieInfo.HorJitter), '', 'g_tWT.MovieInfo.HorJitter'}; g_tOptFields.nVertJitter = {'Radial jitter of mid-point', num2str(g_tWT.MovieInfo.RadJitter), '', 'g_tWT.MovieInfo.RadJitter'}; g_tOptFields.nWhiskerWidth = {'Whisker filter-width', num2str(g_tWT.MovieInfo.WhiskerWidth), '', 'g_tWT.MovieInfo.WhiskerWidth'}; g_tOptFields.nFilterLength = {'Width of local-angle filters', num2str(g_tWT.MovieInfo.FilterLen), '', 'g_tWT.MovieInfo.FilterLen'}; g_tOptFields.nImageProcTitle = {'Image pre-processing', '', 'title', ''}; % Construct string to display in background frames input field vFr = g_tWT.MovieInfo.AverageFrames; sStr = sprintf('[%s]', sprintf('%d %d; ', vFr')); sStr = sprintf('%s]', sStr(1:findstr('; ]', sStr)-1)); g_tOptFields.vAvgFrames = {'Background frames [from to]', sStr, '', 'g_tWT.MovieInfo.AverageFrames'}; g_tOptFields.nBGFrameLowPass = {'Low-pass background image (pixels)', num2str(g_tWT.MovieInfo.BGFrameLowPass), '', 'g_tWT.MovieInfo.BGFrameLowPass'}; g_tOptFields.nInvert = {'Invert contrast', num2str(g_tWT.MovieInfo.Invert), '', 'g_tWT.MovieInfo.Invert'}; g_tOptFields.nPosIntTitle = {'Position extrapolation', '', 'title', ''}; g_tOptFields.nPosIntOn = {'Enable (0/1)', num2str(g_tWT.MovieInfo.UsePosExtrap), '', 'g_tWT.MovieInfo.UsePosExtrap'}; g_tOptFields.nGaussHw = {'Scale filter by factor of', num2str(g_tWT.MovieInfo.ExtrapFiltHw), '', 'g_tWT.MovieInfo.ExtrapFiltHw'}; g_tOptFields.nAngleCalc = {'Angle calculation', '', 'title', ''}; g_tOptFields.nDelta = {'Pixels from base', num2str(g_tWT.MovieInfo.AngleDelta), '', 'g_tWT.MovieInfo.AngleDelta'}; g_tOptFields.nCalibTitle = {'Calibration', '', 'title', ''}; g_tOptFields.nCalBarLength = {'Length of calibration bar (mm)', num2str(g_tWT.MovieInfo.CalBarLength), '', 'g_tWT.MovieInfo.CalBarLength'}; vFr = g_tWT.MovieInfo.CalibCoords; sStr = sprintf('[%s]', sprintf('%d %d; ', vFr')); sStr = sprintf('%s]', sStr(1:findstr('; ]', sStr)-1)); g_tOptFields.mCalibCoords = {'Calibration marks [Xa Ya; Xb Yb]', sStr, '', 'g_tWT.MovieInfo.CalibCoords'}; %%%% End of field data %%%% % GUI Parameters nGuiElements = size(fieldnames(g_tOptFields), 1); nFontSize = 8; nLinSep = 6; vScrnSize = get(0, 'ScreenSize'); nFigHeight = nGuiElements * (nFontSize*2 + nLinSep) + 50; nFigWidth = 500; nTxtColRatio = 3/5; % portion of figure width occupied by the text column vFigPos = [(vScrnSize(3)/2)-(nFigWidth/2) (vScrnSize(4)/2)-(nFigHeight/2) nFigWidth nFigHeight]; g_hOptWin = figure; set(g_hOptWin, 'NumberTitle', 'off', 'Position', vFigPos, 'MenuBar', 'none', 'DeleteFcn', 'clear global g_hOptWin') nTxtColWidth = nFigWidth*nTxtColRatio; % width of descriptive text column nEdtColWidth = nFigWidth-nTxtColWidth; % width of input field column % Place GUI elements on the figure nCurrLine = nFigHeight; g_cFieldNames = fieldnames(g_tOptFields); hEdt = []; for f = 1:nGuiElements nCurrLine = nCurrLine - (nFontSize*2 + nLinSep); % Separator if applicable if strcmp('title', g_tOptFields.(char(g_cFieldNames(f)))(:,3) ) uicontrol(g_hOptWin, 'Style', 'text', 'Position', [0 nCurrLine nTxtColWidth 20], ... 'String', sprintf(' %s', char(g_tOptFields.(char(g_cFieldNames(f)))(:,1))), ... 'HorizontalAlignment', 'left', ... 'FontWeight', 'bold', ... 'BackgroundColor', [.8 .8 .8] ); continue end % Text uicontrol(g_hOptWin, 'Style', 'text', 'Position', [0 nCurrLine nTxtColWidth 20], ... 'String', sprintf(' %s', char(g_tOptFields.(char(g_cFieldNames(f)))(:,1))), ... 'HorizontalAlignment', 'left', ... 'BackgroundColor', [.8 .8 .8] ); % Input field hEdt = uicontrol(g_hOptWin, 'Style', 'edit', 'Position', [nTxtColWidth nCurrLine nEdtColWidth 20], ... 'String', g_tOptFields.(char(g_cFieldNames(f)))(:,2), ... 'HorizontalAlignment', 'center', 'Tag', char(g_cFieldNames(f))); set(hEdt(end), 'Callback', ... [sprintf('global g_tOptFields; g_tOptFields.(''%s'')(:,2) = get(gco, ''String'');', char(g_cFieldNames(f)))] ) end % Load button uicontrol(g_hOptWin, 'Style', 'pushbutton', ... 'string', 'Load', ... 'position', [nFigWidth/2-185 10 50 20], ... 'Callback', ['wt_set_parameters(''loadparams'')']) % Save button uicontrol(g_hOptWin, 'Style', 'pushbutton', ... 'string', 'Save', ... 'position', [nFigWidth/2-125 10 50 20], ... 'Callback', ['wt_set_parameters(''saveparams'')']) % Save As Default button uicontrol(g_hOptWin, 'Style', 'pushbutton', ... 'string', 'Save as default', ... 'position', [nFigWidth/2-65 10 120 20], ... 'Callback', ['wt_set_parameters(''savedefaultparams'')']) set(g_hOptWin, 'userdata', nGuiElements); % 'Apply' button uicontrol(g_hOptWin, 'Style', 'pushbutton', ... 'string', 'Apply (B)', ... 'position', [nFigWidth/2+65 10 60 20], ... 'Callback', @ApplyParams) % 'Done' button uicontrol(g_hOptWin, 'Style', 'pushbutton', ... 'string', 'Done', ... 'position', [nFigWidth/2+135 10 50 20], ... 'Callback', @DoneParams ) return; %%%% LOAD PARAMETERS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function LoadParams global g_tOptFields g_hOptWin; % Load .mat file [sFilename, sPathname] = uigetfile('*.mat', 'Select parameters file'); if sFilename==0 return end load(sprintf('%s%s', sPathname, sFilename)); pause(0.5); % Update gui cFieldnames = fieldnames(g_tOptFields); for e = 1:size(fieldnames(g_tOptFields),1) h = findobj(g_hOptWin, 'Tag', char(cFieldnames(e))); if ~isempty(h) set(h, 'String', g_tOptFields.(char(cFieldnames(e)))(2)); end end return; %%%% SAVE PARAMETERS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SaveParams global g_tOptFields % Save .mat file [sFilename, sPathname] = uiputfile('wt_default_parameters.mat', 'Save parameters as...'); if sFilename==0 return end pause(0.5); save(sprintf('%s%s', sPathname, sFilename), 'g_tOptFields'); return; %%%% SAVE DEFAULT PARAMETERS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SaveDefaultParams global g_tOptFields % Save .m file sFilename = 'wt_default_parameters.mat'; sPathname = 'C:\'; save(sprintf('%s%s', sPathname, sFilename), 'g_tOptFields'); return; %%%% UPDATE VARS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function UpdateVars(nGuiElements) global g_tWT global g_cFieldNames; global g_tOptFields; g_tWT.FiltVec = []; % Update global variables with the new for f = 1:nGuiElements cTargetVar = char(g_tOptFields.(char(g_cFieldNames(f)))(:,4)); if ~isempty(cTargetVar) eval(sprintf('%s = [%s];', cTargetVar, char(g_tOptFields.(char(g_cFieldNames(f)))(:,2)))); end end return; %%%% APPLY Params %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ApplyParams(varargin) global g_hOptWin; % Enable Redo on this function wt_batch_redo('wt_set_parameters(''apply'')') nGuiElements = get(g_hOptWin, 'userdata'); wt_set_parameters('updatevars', nGuiElements); wt_calibration('recalculate'); wt_update_window_title_status; wt_display_frame; figure(g_hOptWin); return; %%%% DONE Params %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function DoneParams(varargin) global g_hOptWin; nGuiElements = get(g_hOptWin, 'userdata'); wt_set_parameters('updatevars', nGuiElements); wt_calibration('recalculate'); wt_update_window_title_status; close(g_hOptWin); clear global g_cFieldNames; clear global g_tOptFields; wt_display_frame; return;
github
HelmchenLabSoftware/OCIA-master
wt_toggle_imageshow.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/wt_knutsen/wt_toggle_imageshow.m
1,038
utf_8
b9f1e7badee6073df78f3a1350acbcfa
%%%% WT_TOGGLE_IMAGESHOW %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Whisker Tracker (WT) % % Authors: Per Magne Knutsen, Dori Derdikman % % (c) Copyright 2004 Yeda Research and Development Company Ltd., % Rehovot, Israel % % This software is protected by copyright and patent law. Any unauthorized % use, reproduction or distribution of this software or any part thereof % is strictly forbidden. % % Citation: % Knutsen, Derdikman, Ahissar (2004), Tracking whisker and head movements % of unrestrained, behaving rodents, J. Neurophys, 2004, IN PRESS % function wt_toggle_imageshow global g_tWT % Toggle verbose status g_tWT.HideImage = ~g_tWT.HideImage; % Update user-menu switch g_tWT.HideImage case 0 sStatus = 'off'; case 1 sStatus = 'on'; otherwise wt_error('Verbose mode status is undefined. Click continue to set verbose to OFF.') g_tWT.HideImage = 0; sStatus = 'off'; end set(findobj('Label', 'Hide image'), 'checked', sStatus); wt_display_frame return;
github
HelmchenLabSoftware/OCIA-master
wt_select_file.m
.m
OCIA-master/other/functions_widefield/whisker_tracking/wt_knutsen/wt_select_file.m
668
utf_8
09d3aee4c8195babda4f43a86ff08344
% WT_SELECT_FILE function sMovies = wt_select_file global g_tWT [sFilename, sFilepath] = uigetfile({'*.avi', 'AVI-files (*.avi)'; '*.mat', 'MAT-files (*.mat)';'*.*', 'All File (*.*)'}, 'Select file'); % Return immeditaley if user cancelled this action if ~sFilename return; end % Build list of files g_tWT.Movies = struct([]); g_tWT.Movies(1).filename = sprintf('%s%s', sFilepath, sFilename); % Change current directory to that of the loaded file cd(sFilepath); % Reinitialize the gui menus etc. wt_prep_gui; % Clear ROI and rotation parameters g_tWT.MovieInfo.Roi = []; g_tWT.MovieInfo.Rot = 0; % Load movie and display first frame wt_load_movie(1); return;