diff --git a/ANALYSIS CODE/ANALYSIS.m b/ANALYSIS CODE/ANALYSIS.m deleted file mode 100644 index c1c3108..0000000 --- a/ANALYSIS CODE/ANALYSIS.m +++ /dev/null @@ -1,159 +0,0 @@ -function [maleBoutInfo,femaleBoutInfo,run_data,maxfreq_femalepulse,maxfreq_malepulse,male_pulse_IPI] = ANALYZE_VIRILIS_SONG(xsong,xempty) - - -[maleBoutInfo,femaleBoutInfo,run_data] = segmentVirilisSong(xsong,xempty); - -%analyze male and female virilis song: - -%pulse frequency and IPI analysis: - % take male bouts, find regions that DO NOT overlap with female, take - % those regions and find pulseInfoM within those regions - these are - % the individual male pulses. Analyze these for pulse frequency and IPI - % show that male pulse freq and IPI is highly stereotyped - - %for female bouts (each "bout" is actually a female pulse), find all - %female bouts that do not overlap with male bouts, take these, and run - %pulse frequency analysis (IPI analysis done below) - %show that female pulse frequency is more variable - -%times of male/female pulses - %we have starts/stops of male bouts in maleBoutInfo (w0 and w1) - %we have starts/stops of female pulses in femaleBoutInfo (w0 and w1) - %for even those pulses that overlap with male bouts - - %from these two, we can get the IBIs of male song and IPIs of female - %song - - %now we need a coordination score. how coordinated are male/female - %song? - %1)examine the difference in IBI or IPI for when male/female sings - %alone (some definition - for example, for male song, look for several seconds that contain only male song) or with a partner - - %2)look at the variance in male IBI or female IPI when they sing - %alone or with a partner - - %3)look at intervals between a male bout and the start of the - %closest female song (and vice versa) - call this response time (want to calculate this reponse time both to the begining of the male or female song or to the end). - %compare this to male IBI or female IPI. - -%SOME PARAMETERS: -Fs=10000; -T = 1/Fs; -%% -%collect all male bouts and find those female bouts that overlap with male: -r=1; -femalepulse_in_male=[]; -malebout_overlap_female =[]; -for n=1:length(maleBoutInfo.x); -w0 = maleBoutInfo.w0(n); -w1 = maleBoutInfo.w1(n); -I = find(femaleBoutInfo.wc > w0 & femaleBoutInfo.wc < w1); -a = isempty(I); -if a == 1; - continue -else -femalepulse_in_male(r) = I; %these are the indices of femaleBoutInfo that have female pulses that overlap with male song -malebout_overlap_female(r) = n; %these are the indices of maleBoutInfo that also contain female song -r=r+1; -end -end - -%collect male pulses: -r=1; -malepulses_times=[]; -for n=1:length(maleBoutInfo.x); - a = malebout_overlap_female; - M = find(a==n); - MM = isempty(M); - if MM == 0; %if a==n - continue - else - w0 = maleBoutInfo.w0(n); - w1 = maleBoutInfo.w1(n); - I = find(run_data.pulseInfoM.wc > w0 & run_data.pulseInfoM.wc < w1); - malepulses_times(r:r+length(I)-1) = run_data.pulseInfoM.wc(I); %these are the wc's of pulseInfoM that contain true male pulses, without overlaps with female pulses - r = r + length(I); - end -end - -%analyze these male pulses (for pulse frequency and IPI): -r=1; -maxfreq_malepulse=[]; -for n=1:length(malepulses_times); - a = malepulses_times(n); - I = find(run_data.pulseInfoM.wc == a); %index of pulseInfoM - P = run_data.pulseInfoM.x{I}; %one male pulse at a time - %first frequency: - L = length(P); - t = (0:L-1)*T; - NFFT = 2^nextpow2(L); - y = fft(P,NFFT); - f = Fs/2*linspace(0,1,NFFT/2+1); - %figure(2); hold on - %plot(f,2*abs(y(1:NFFT/2+1))); - [~,maxidx] = max(2*abs(y(1:NFFT/2+1))); - maxfreq_malepulse(r) = f(maxidx); - r=r+1; -end - -%Now IPI: -male_pulse_IPI = diff(malepulses_times)./10; %in points -- want in ms, so divide by 10 - -%% -%analyze these female pulses (that do not overlap with male song) for frequency: -maxfreq_femalepulse=[]; -r=1; -for n=1:length(femaleBoutInfo.wc); - a = femalepulse_in_male; - M = find(a==n); - MM = isempty(M); - if MM == 0; %if a==n - continue - else - A = femaleBoutInfo.x{n}; - L = length(A); - t = (0:L-1)*T; - NFFT = 2^nextpow2(L); - y = fft(A,NFFT)/L; - f = Fs/2*linspace(0,1,NFFT/2+1); - %hold on - %plot(f,2*abs(y(1:NFFT/2+1)),'m'); - [~,maxidx] = max(2*abs(y(1:NFFT/2+1))); - maxfreq_femalepulse(r) = f(maxidx); - r=r+1; - end -end -%% - -% %% -% figure(2); title('malebout frequency'); -% maxfreq_malebout=[]; -% for n=1:length(maleBoutInfo.x); -% A = maleBoutInfo.x{n}; -% figure(4); hold on; plot(A); -% L = length(A); -% t = (0:L-1)*T; -% NFFT = Fs/10;%2^nextpow2(L); -% y = fft(A,NFFT); -% f = Fs/2*linspace(0,1,NFFT/2+1); -% figure(2); hold on -% plot(f,2*abs(y(1:NFFT/2+1))); -% [~,maxidx] = max(2*abs(y(1:NFFT/2+1))); -% maxfreq_malebout(n) = f(maxidx); -% end -% %% -% %figure(3); title('femalebout frequency'); -% maxfreq_femalebout=[]; -% for n=1:length(femaleBoutInfo.x); -% A = femaleBoutInfo.x{n}; -% L = length(A); -% t = (0:L-1)*T; -% NFFT = 2^nextpow2(L); -% y = fft(A,NFFT)/L; -% f = Fs/2*linspace(0,1,NFFT/2+1); -% hold on -% plot(f,2*abs(y(1:NFFT/2+1)),'m'); -% [~,maxidx] = max(2*abs(y(1:NFFT/2+1))); -% maxfreq_femalebout(n) = f(maxidx); -% end -% %% \ No newline at end of file diff --git a/ANALYSIS CODE/BTA.m b/ANALYSIS CODE/BTA.m deleted file mode 100644 index 080c1c5..0000000 --- a/ANALYSIS CODE/BTA.m +++ /dev/null @@ -1,31 +0,0 @@ -function [ femaletimes ] = BTA( file ) -%UNTITLED Summary of this function goes here -% Detailed explanation goes here -load(file, 'femaleBoutInfo', 'femaleBoutInfo_no_overlap','maleBoutInfo', 'run_data'); - femaletimes=NaN(length(maleBoutInfo.wc),100); - - for i=1:length(maleBoutInfo.wc); -zz=find(run_data.pulseInfo.wc>maleBoutInfo.w0(i) & run_data.pulseInfo.wcaa); - xx= find(femaleBoutInfo_no_overlap>(a-20000)& femaleBoutInfo_no_overlap(z-10000)); - if isempty(xx) - continue - else - c=femaleBoutInfo_no_overlap(x)-aa; - cc=femaleBoutInfo_no_overlap(xx)-a; - final=horzcat(c,cc); - %x=femaleBoutInfo.wMax(xx)-z; - femaletimes(i,1:length(final))=final; - - end -end - end -end - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectBoutMaxFFT.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectBoutMaxFFT.m deleted file mode 100755 index 8ef1973..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectBoutMaxFFT.m +++ /dev/null @@ -1,47 +0,0 @@ -function BoutsMaxFFT = CollectBoutMaxFFT(folder) - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -allTime = []; -allFreq = []; - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - - load(path_file,'bout_maxFFT'); - % file_names{i} = file; - for j = 1:numel(bout_maxFFT.time) - allTime = catpad(1,allTime,bout_maxFFT.time{j}); - allFreq = catpad(1,allFreq,bout_maxFFT.freq{j}); - end - end -end - -BoutsMaxFFT.allTime = allTime; -BoutsMaxFFT.allFreq = allFreq; - -% BoutsMaxFFT(cellfun('isempty',BoutsMaxFFT))=[]; -% file_names(cellfun('isempty',file_names))=[]; -% -% BoutsMaxFFT=cat(1,BoutsMaxFFT{:}); - - - - - - - - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectBouts.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectBouts.m deleted file mode 100755 index 2cda377..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectBouts.m +++ /dev/null @@ -1,43 +0,0 @@ -function [file_names Bouts] = CollectBouts(folder) -%USAGE [file_names Bouts] = CollectBouts(folder) - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -Bouts = cell(1,file_num); - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; - %get plot data and limits - load(path_file,'bouts'); - file_names{i} = file; - Bouts{i} = bouts.x; - - end -end - -Bouts(cellfun('isempty',Bouts))=[]; -file_names(cellfun('isempty',file_names))=[]; - -Bouts=cat(1,Bouts{:}); - - - - - - - - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectIpiStats.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectIpiStats.m deleted file mode 100755 index 26b5389..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectIpiStats.m +++ /dev/null @@ -1,56 +0,0 @@ -function [ipiStatsAll,file_names,ipiTrainsData,ipiStatsAll.TrainsD,ipiTrainsTime,ipiStatsAll.TrainsT] = CollectIpiStats(folder) - - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -sineTrainDuration = zeros(file_num,1); -pulseTrainDuration = zeros(file_num,1); -sineFreq = zeros(file_num,1); -pulseFreq = zeros(file_num,1); -ipi = zeros(file_num,1); - - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; -% if strfind(root,'_ipi_ipiStatsLomb') ~= 0 - %get plot data and limits - load(path_file,'ipiStatsLomb','ipiTrains'); - file_names{i} = file; - - ipiStats = ipiStatsLomb.ipiStats; - culled_ipi = ipiStatsLomb.culled_ipi; - - mu1(i) = ipiStats.mu1; - mu2(i) = ipiStats.mu2; - Sigma1(i) = ipiStats.S1; - Sigma2(i) = ipiStats.S2; - N(i) = numel(culled_ipi.d); - ipiTrainsData{i} = ipiTrains.d; - ipiTrainsTime{i} = ipiTrains.t; -% end - end -end - -ipiStatsAll.mu1 = mu1(mu1~=0); -ipiStatsAll.mu2 = mu2(mu2~=0); -ipiStatsAll.Sigma1 = Sigma1(Sigma1~=0); -ipiStatsAll.Sigma2 = Sigma2(Sigma2~=0); -ipiStatsAll.N = N(Sigma2~=0); -file_names(cellfun('isempty',file_names))=[]; -ipiTrainsData(cellfun('isempty',ipiTrainsData))=[]; -ipiStatsAll.TrainsD = ipiTrainsData; -ipiTrainsTime(cellfun('isempty',ipiTrainsTime))=[]; -ipiStatsAll.TrainsT = ipiTrainsTime; \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectLombStats.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectLombStats.m deleted file mode 100755 index d4dd44e..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectLombStats.m +++ /dev/null @@ -1,53 +0,0 @@ -function [file_names LombStats LombStatsMat] = CollectLombStats(folder) -%USAGE [file_names LombStats LombStatsMat] = CollectLombStats(folder) - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end - -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -F = cell(1,file_num); -Alpha = cell(1,file_num); -Peaks = cell(1,file_num); -file_names = cell(1,file_num); - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; -% if strfind(root,'_ipi_ipiStatsLomb') ~= 0 - %get plot data and limits - load(path_file,'ipiStatsLomb'); - lomb = ipiStatsLomb.lomb; - file_names{i} = file; - F{i} = lomb.F; - Alpha{i} = lomb.Alpha; - Peaks{i} = lomb.Peaks; -% end - end -end - -F(cellfun('isempty',F))=[]; -Alpha(cellfun('isempty',Alpha))=[]; -Peaks(cellfun('isempty',Peaks))=[]; -file_names(cellfun('isempty',file_names))=[]; - -FMat=cat(1,F{:}); -AlphaMat = cat(1,Alpha{:}); -PeaksMat = cat(1,Peaks{:}); - -LombStats.F = F; -LombStats.Alpha = Alpha; -LombStats.Peaks = Peaks; -LombStatsMat.F = FMat; -LombStatsMat.Alpha = AlphaMat; -LombStatsMat.Peaks = PeaksMat; \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectLongTermStats.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectLongTermStats.m deleted file mode 100755 index 5fcc826..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectLongTermStats.m +++ /dev/null @@ -1,50 +0,0 @@ -function [LongTermStats] = CollectLongTermStats(folder) - - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -sineTrainDuration = zeros(file_num,1); -pulseTrainDuration = zeros(file_num,1); -sineFreq = zeros(file_num,1); -pulseFreq = zeros(file_num,1); -ipi = zeros(file_num,1); - - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; -% if strfind(root,'_ipi_ipiStatsLomb') ~= 0 - %get plot data and limits - load(path_file,'maxFFT','pMFFT','ipiStatsLomb','ipiStatsLomb','ipiTrains','winnowed_sine'); - file_names{i} = file; - - sineTrainDuration(i) = corr(winnowed_sine.start,winnowed_sine.stop-winnowed_sine.start); - pT.d = cell2mat(ipiTrains.d)'; - pT.t = cell2mat(ipiTrains.t)'; - pulseTrainDuration(i) = corr(pT.t,pT.d); - sineFreq(i) = corr(maxFFT.timeAll',maxFFT.freqAll); - pulseFreq(i) = corr(pMFFT.timeAll,pMFFT.freqAll); - ipi(i) = corr(ipiStatsLomb.culled_ipi.t',ipiStatsLomb.culled_ipi.d'); - - -% end - end -end - -LongTermStats.sineTrainDuration = sineTrainDuration(sineTrainDuration~=0); -LongTermStats.pulseTrainDuration = pulseTrainDuration(pulseTrainDuration~=0); -LongTermStats.sineFreq = sineFreq(sineFreq~=0); -LongTermStats.pulseFreq = pulseFreq(pulseFreq~=0); -LongTermStats.ipi = ipi(ipi~=0); diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectPauses.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectPauses.m deleted file mode 100755 index fb9df89..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectPauses.m +++ /dev/null @@ -1,69 +0,0 @@ -function [file_names Pauses PausesMat] = CollectPauses(folder) -%USAGE [file_names Pauses PausesMat] = CollectPauses(folder) -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end - -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -BoutPauses = cell(1,file_num); -PauseDelta = cell(1,file_num); -sinesine = cell(1,file_num); -sinepulse = cell(1,file_num); -pulsesine = cell(1,file_num); -pulsepulse = cell(1,file_num); -file_names = cell(1,file_num); - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; - %get plot data and limits - load(path_file,'pauses'); - file_names{i} = file; - BoutPauses{i} = pauses.BoutPauses; - PauseDelta{i} = pauses.PauseDelta; - sinesine{i} = pauses.sinesine; - sinepulse{i} = pauses.sinepulse; - pulsesine{i} = pauses.pulsesine; - pulsepulse{i} = pauses.pulsepulse; - - end -end - -BoutPauses(cellfun('isempty',BoutPauses)) = []; -PauseDelta(cellfun('isempty',PauseDelta))=[]; -sinesine(cellfun('isempty',sinesine))=[]; -sinepulse(cellfun('isempty',sinepulse))=[]; -pulsesine(cellfun('isempty',pulsesine))=[]; -pulsepulse(cellfun('isempty',pulsepulse))=[]; -file_names(cellfun('isempty',file_names))=[]; - -BoutPausesMat = cat(1,BoutPauses{:}); -PauseDeltaMat = cat(1,PauseDelta{:}); -sinesineMat = cat(1,sinesine{:}); -sinepulseMat = cat(1,sinepulse{:}); -pulsesineMat = cat(1,pulsesine{:}); -pulsepulseMat = cat(1,pulsepulse{:}); - -Pauses.BoutPauses = BoutPauses; -Pauses.PauseDelta = PauseDelta; -Pauses.sinesine = sinesine; -Pauses.sinepulse = sinepulse; -Pauses.pulsesine = pulsesine; -Pauses.pulsepulse = pulsepulse; - -PausesMat.BoutPauses = BoutPausesMat; -PausesMat.PauseDelta = PauseDeltaMat; -PausesMat.sinesine = sinesineMat; -PausesMat.sinepulse = sinepulseMat; -PausesMat.pulsesine = pulsesineMat; -PausesMat.pulsepulse = pulsepulseMat; diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectSineLombStats.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectSineLombStats.m deleted file mode 100755 index ae23742..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectSineLombStats.m +++ /dev/null @@ -1,51 +0,0 @@ -function [file_names LombStats LombStatsMat] = CollectSineLombStats(folder) -%USAGE [file_names LombStats LombStatsMat] = CollectLombStats(folder) -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -F = cell(1,file_num); -Alpha = cell(1,file_num); -Peaks = cell(1,file_num); -file_names = cell(1,file_num); - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; -% if strfind(root,'_ipi_ipiStatsLomb') ~= 0 - %get plot data and limits - load(path_file,'sineLomb'); -% lomb = ipiStatsLomb.lomb; - file_names{i} = file; - F{i} = sineLomb.F; - Alpha{i} = sineLomb.Alpha; - Peaks{i} = sineLomb.Peaks; -% end - end -end - -F(cellfun('isempty',F))=[]; -Alpha(cellfun('isempty',Alpha))=[]; -Peaks(cellfun('isempty',Peaks))=[]; -file_names(cellfun('isempty',file_names))=[]; - -FMat=cat(1,F{:}); -AlphaMat = cat(1,Alpha{:}); -PeaksMat = cat(1,Peaks{:}); - -LombStats.F = F; -LombStats.Alpha = Alpha; -LombStats.Peaks = Peaks; -LombStatsMat.F = FMat; -LombStatsMat.Alpha = AlphaMat; -LombStatsMat.Peaks = PeaksMat; \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectSineStats.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectSineStats.m deleted file mode 100755 index bcaab11..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/CollectSineStats.m +++ /dev/null @@ -1,43 +0,0 @@ -function [file_names sineStats] = CollectSineStats(folder) -%USAGE [file_names sineStats] = CollectSineStats(folder) - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end - -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -%sinePower = zeros(1,file_num); -freq = zeros(1,file_num); -sine2pulse = zeros(1,file_num); -file_names = cell(1,file_num); - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; - load(path_file,'maxFFT','winnowed_sine','culled_pulseInfo'); - %power = winnowed_sine.powerMat; - FFT = maxFFT.freqAll; - numSine = numel(winnowed_sine.start); - numPulse = numel(culled_pulseInfo.w0); - file_names{i} = file; - %sinePower(i) = mean(abs(power)); - freq(i) = mean(FFT); - sine2pulse(i) = numSine / numPulse; - end -end - -file_names(cellfun('isempty',file_names))=[]; - -%sineStats.sinePower = sinePower(sinePower ~=0); -sineStats.freq = freq(freq~=0); -sineStats.sine2pulse = sine2pulse(sine2pulse~=0); \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_allIPI.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_allIPI.m deleted file mode 100755 index c031e79..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_allIPI.m +++ /dev/null @@ -1,108 +0,0 @@ -folder = '/Users/sternd/Documents/Projects/mel-all-14Sept12/'; -dir_list = dir(folder); -file_num = length(dir_list); -allipi = cell(1,file_num); - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 %if it is a .mat file - i = i+1; - %get plot data and limits - load(path_file,'ipi'); - allipi{i} = ipi.d; - end -end - -allipi = cell2mat(allipi); -ipi = allipi(allipi<.2e4); -[obj,residuals,Z] = gmixPlot(ipi',4,[],1000,[],1); - -den = sum(obj.PComponents([3 4])); -mixprops = obj.PComponents([3 4]) / den; -mu = obj.mu([3 4]); -std= obj.Sigma([3 4]); -objnew = gmdistribution(mu,std,mixprops); -prob = cdf(objnew,ipi'); -culled_ipi = (ipi(prob > .025 & prob < .975)); -min(culled_ipi) - -ans = - - 293 - -max(culled_ipi) - -ans = - - 495 - -%%% -%clear old ipiStats -%%% -folder = '/Users/sternd/Documents/Projects/mel-all-14Sept12/'; -dir_list = dir(folder); -file_num = length(dir_list); - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 %if it is a .mat file - i = i+1; - %get plot data and limits - %load(path_file,'ipiStats'); - ipiStats = []; - save(path_file,'ipiStats','-append')%save all variables in original file - end -end - - - - - - -%%% -%cull ipis -%%% -folder = '/Users/sternd/Documents/Projects/mel-all-14Sept12/'; -dir_list = dir(folder); -file_num = length(dir_list); - - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 %if it is a .mat file - i = i+1; - %get plot data and limits - load(path_file); - culled_ipi.d = ipi.d(ipi.d > 293 & ipi.d < 495); - culled_ipi.t = ipi.t(ipi.d > 293 & ipi.d < 495); - - W = who('-file',path_file); - varstruc =struct; - for ii = 1:numel(W) - varstruc.(W{ii}) = eval(W{ii}); - end - - varstruc.ipiStats.culled_ipi.d= culled_ipi.d; - varstruc.ipiStats.culled_ipi.t= culled_ipi.t; - - varstruc.ipiStats.variables.date = date; - varstruc.ipiStats.variables.time = clock; - save(path_file,'-struct','varstruc','-mat')%save all variables in original file - - end -end - - - \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_pulseMaxFFTFreq.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_pulseMaxFFTFreq.m deleted file mode 100755 index c282c4f..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_pulseMaxFFTFreq.m +++ /dev/null @@ -1,58 +0,0 @@ -function [file_names, PulseTrainStart, PulseTrainStop,pulseFFTfreq, pulseFFTtimes,BoutsStart,BoutsStop] = Collect_pulseMaxFFTFreq(folder) -%USAGE [file_names, PulseTrainStart, PulseTrainStop,pulseFFTfreq, pulseFFTtimes,BoutsStart,BoutsStop] = Collect_pulseMaxFFTFreq(folder) - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); -i=0; - -PulseTrainStart = cell(1,file_num); -PulseTrainStop = cell(1,file_num); -pulseFFTfreq = cell(1,file_num); -pulseFFTtimes = cell(1,file_num); -file_names = cell(1,file_num); -BoutsStart = cell(1,file_num); -BoutsStop = cell(1,file_num); - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 %if it is a .mat file - i = i+1; - %get plot data and limits - load(path_file,'pMFFT','bouts','culled_pulseInfo','ipiBouts'); - file_names{i} = file; - PulseTrainStart{i} = cellfun(@(c) c(1),ipiBouts.t); - PulseTrainStop{i} = cellfun(@(c) c(end),ipiBouts.t) + cellfun(@(c) c(end),ipiBouts.d); - pulseFFTfreq{i} = pMFFT.freqAll; - pulseFFTtimes{i} = pMFFT.timeAll; - BoutsStart{i} = bouts.Start; - BoutsStop{i} = bouts.Stop; - end -end - -PulseTrainStart(cellfun('isempty',PulseTrainStart))=[]; -PulseTrainStop(cellfun('isempty',PulseTrainStop))=[]; -pulseFFTfreq(cellfun('isempty',pulseFFTfreq))=[]; -pulseFFTtimes(cellfun('isempty',pulseFFTtimes))=[]; -file_names(cellfun('isempty',file_names))=[]; -BoutsStart(cellfun('isempty',BoutsStart))=[]; -BoutsStop(cellfun('isempty',BoutsStop))=[]; - -%Bouts=cat(1,Bouts{:}); - - - - - - - - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_pulseTrainLength.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_pulseTrainLength.m deleted file mode 100755 index 23ca593..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_pulseTrainLength.m +++ /dev/null @@ -1,12 +0,0 @@ -%for hist of pulse trains - - -%cycle though every file, collect j from each file - -j = zeros(numel(d.t),1); -for i = 1:numel(d.t) - j(i) = d.t{i}(end) + d.d{i}(end) - d.t{i}(1); -end - - -hist(j,100) \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_sineMaxFFTFreq.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_sineMaxFFTFreq.m deleted file mode 100755 index 45665e6..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_sineMaxFFTFreq.m +++ /dev/null @@ -1,72 +0,0 @@ -function [file_names, SineStart,SineStop,sinemaxFFTfreq,sinemaxFFTtime,SINEFFTfreqall, SINEFFTtimesall,BoutsStart,BoutsStop] = Collect_sineMaxFFTFreq(folder,strain) -%USAGE [file_names, SineStart,SineStop,sinemaxFFTfreq,sinemaxFFTtime,SINEFFTfreqall, SINEFFTtimesall,BoutsStart,BoutsStop] = Collect_sineMaxFFTFreq(folder,strain) - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); -i=0; - -SineStart = cell(1,file_num); -SineStop = cell(1,file_num); -sinemaxFFTfreq = cell(1,file_num); -sinemaxFFTtime = cell(1,file_num); -SINEFFTfreqall = cell(1,file_num); -SINEFFTtimesall = cell(1,file_num); -file_names = cell(1,file_num); -BoutsStart = cell(1,file_num); -BoutsStop = cell(1,file_num); - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - if nargin == 2 - strainMatch = strfind(root,strain); - else - strainMatch = 'all'; - end - - if TG == 1 %if it is a .mat file - if ~isempty(strainMatch) - fprintf([file '\n']); - i = i+1; - %get plot data and limits - load(path_file,'maxFFT','bouts','winnowed_sine'); - file_names{i} = file; - SineStart{i} = winnowed_sine.start; - SineStop{i} = winnowed_sine.stop; - sinemaxFFTfreq{i} = maxFFT.freq; - sinemaxFFTtime{i} = maxFFT.time; - SINEFFTfreqall{i} = maxFFT.freqAll; - SINEFFTtimesall{i} = maxFFT.timeAll; - BoutsStart{i} = bouts.Start; - BoutsStop{i} = bouts.Stop; - end - end -end - -SineStart(cellfun('isempty',SineStart))=[]; -SineStop(cellfun('isempty',SineStop))=[]; -sinemaxFFTfreq(cellfun('isempty',sinemaxFFTfreq))=[]; -sinemaxFFTtime(cellfun('isempty',sinemaxFFTtime))=[]; -SINEFFTfreqall(cellfun('isempty',SINEFFTfreqall))=[]; -SINEFFTtimesall(cellfun('isempty',SINEFFTtimesall))=[]; -file_names(cellfun('isempty',file_names))=[]; -BoutsStart(cellfun('isempty',BoutsStart))=[]; -BoutsStop(cellfun('isempty',BoutsStop))=[]; - -%Bouts=cat(1,Bouts{:}); - - - - - - - - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_sineTrainLength.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_sineTrainLength.m deleted file mode 100755 index 3326c64..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/Collect_sineTrainLength.m +++ /dev/null @@ -1,3 +0,0 @@ -%for every file - -j = winnowed_sine.stop - winnowed_sine.start; \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/FFTvarVStime.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/FFTvarVStime.m deleted file mode 100755 index d011c7c..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/FFTvarVStime.m +++ /dev/null @@ -1,9 +0,0 @@ -run = 50; -% for i = 1:75 - length_song = numel(SINEFFTtimesall{i}); - last = length_song - run; - runvar = zeros(last,1); - for j = 1:last - runvar(j) = var(SINEFFTfreqall{i}(j:j+run)); - end -% end \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/KHcycles?.pdf b/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/KHcycles?.pdf deleted file mode 100755 index 0cb5e31..0000000 Binary files a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/KHcycles?.pdf and /dev/null differ diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/KHcycles?.zoom.pdf b/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/KHcycles?.zoom.pdf deleted file mode 100755 index 808c028..0000000 Binary files a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/KHcycles?.zoom.pdf and /dev/null differ diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/check_close_pool.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/check_close_pool.m deleted file mode 100755 index 730d62b..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/check_close_pool.m +++ /dev/null @@ -1,7 +0,0 @@ -function check_close_pool(poolavail,isOpen) - -if isOpen == -1%if pool opened in this script, then close - if poolavail~=0 - matlabpool close force local - end -end diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/check_open_pool.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/check_open_pool.m deleted file mode 100755 index 5bb96b6..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/check_open_pool.m +++ /dev/null @@ -1,12 +0,0 @@ -function [poolavail,isOpen] = check_open_pool - -%[poolavail,isOpen] = check_open_pool - -poolavail = exist('matlabpool','file'); -if poolavail~=0 - isOpen = matlabpool('size') > 0;%check if pools open (as might occur, for eg if called from Process_multi_daq_Song - if isOpen == 0%if not open, then open - matlabpool(getenv('NUMBER_OF_PROCESSORS')) - isOpen = -1;%now know pool was opened in this script (no negative pools from matlabpool('size')) - end -end diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/fastlomb.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/fastlomb.m deleted file mode 100755 index 03c5918..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/fastlomb.m +++ /dev/null @@ -1,244 +0,0 @@ -function [P,f,alpha] = fastlomb(x,t,varargin) -% FASTLOMB caculates the Lomb normalized periodogram (aka Lomb-Scargle, Gauss-Vanicek or Least-Squares spectrum) of a vector x with coordinates in t. -% The coordinates need not be equally spaced. In fact if they are, it is -% probably preferable to use PWELCH or SPECTRUM. For more details on the -% Lomb normalized periodogram, see the excellent section 13.8 in [1], pp. -% 569-577. -% -% This code is a transcription of the Fortran subroutine fasper in [1] -% (pp.575-577), so it is a really fast (albeit not really exact) -% implementation of the Lomb periodogram. Also Matlab's characteristics -% have been taken into account in order to make it even faster for -% Matlab. For an exact calculation of the Lomb periodogram use LOMB, -% which is however about 100 times slower. -% -% If the 'fig' flag is on, the periodogram is created, along with some -% default statistical significance levels: .001, .005, .01, .05, .1, .5. -% If the user wants more significance levels, they can give them as input -% to the function. Those will be red. -% -% SYNTAX -% [P,f,alpha] = fastlomb(x,t,fig,hifac,ofac,a); -% [P,f,alpha] = fastlomb(x,t,fig,hifac,ofac); -% [P,f,alpha] = fastlomb(x,t,fig,hifac); -% [P,f,alpha] = fastlomb(x,t,fig); -% [P,f,alpha] = fastlomb(x,t); -% -% INPUTS -% x: the vector whose spectrum is wanted. -% t: coordinates of x (should have the same length). -% fig: if 0 (default), no figure is created. -% hifac: the maximum frequency returned is -% (hifac) x (average Nyquist frequency) -% See "THE hifac PARAMETER" in the NOTES section below for more -% details on the hifac parameter. Default is 1 (i.e. max frequency -% is the Nyquist frequency). -% ofac: oversampling factor. Typically it should be 4 or larger. Default -% is 4. See "INTERPRETATION AND SELECTION OF THE ofac PARAMETER" -% in the NOTES section below for more details on the choice of -% ofac parameter. -% a: additional significance levels to be drawn on the figure. -% -% OUTPUTS -% P: the Lomb normalized periodogram -% f: respective frequencies -% alpha: statistical significance for each value of P -% -% NOTES -% A. INTERPRETATION AND SELECTION OF THE ofac PARAMETER [1] -% The lowest independent frequency f to be examined is the inverse of -% the span of the input data, -% 1/(tmax-tmin)=1/T. -% This is the frequency such that the data can include one complete -% cycle. In an FFT method, higher independent frequencies would be -% integer multiples of 1/T . Because we are interested in the -% statistical significance of ANY peak that may occur, however, we -% should over-sample more finely than at interval 1/T, so that sample -% points lie close to the top of ANY peak. This oversampling parameter -% is the ofac. A value ofac >~4 might be typical in use. -% -% B. THE hifac PARAMETER [1] -% Let fhi be the highest frequency of interest. One way to choose fhi is -% to compare it with the Nyquist frequency, fc, which we would obtain, if -% the N data points were evenly spaced over the same span T, that is -% fc = N/(2T). -% The input parameter hifac, is defined as fhi/fc. In other words, hifac -% shows how higher (or lower) that the fc we want to go. -% -% REFERENCES -% [1] W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, -% "Numerical recipes in Fortran 77: the art of scientific computing", -% 2nd ed., vol. 1, Cambridge University Press, NY, USA, 2001. -% -% C. Saragiotis, Nov 2008 - - -%% Inputs check and initialization -if nargin < 2, error('%s: there must be at least 2 inputs.',mfilename); end -MACC = 10; % Number of interpolation points per 1/4 cycle of the highest frequency - -[x,t,hifac,ofac,a_usr,f,fig] = init(x,t,varargin{:}); -nt = length(t); - -mx = mean(x); -x = x-mx; -vx = var(x); -if vx==0, error('x has zero variance'); end - -nf = length(f); -nfreq = 2^nextpow2(ofac*hifac*nt*MACC); -% ndim = 2*nfreq; - -tmin = t(1); -tmax = t(end); -T = tmax-tmin; - -%% Extirpolation -fac = 2*nfreq/(T*ofac); -[wk1,wk2] = extirpolate(t-tmin,x,fac,nfreq,MACC); - -%% Take the FFT's -W = fft(wk1); -reft1 = real(W(2:nf+1)); % only positive frequencies, without f=0 -imft1 = imag(W(2:nf+1)); - -W = fft(wk2); -reft2 = real(W(2:nf+1)); -imft2 = imag(W(2:nf+1)); - -%% Main -hypo = sqrt(reft2.^2+imft2.^2); -hc2wt = 0.5*reft2./hypo; -hs2wt = 0.5*imft2./hypo; -cwt = sqrt(0.5+hc2wt); -swt = (sign(hs2wt)+(hs2wt==0)).*(sqrt(0.5-hc2wt)); -den = 0.5*nt + hc2wt.*reft2 + hs2wt.*imft2; -cterm = (cwt.*reft1 + swt.*imft1).^2./den; -sterm = (cwt.*imft1 - swt.*reft1).^2./(nt-den); -P = (cterm+sterm)/(2*vx); -P = P(:); - -%% Significance -M = 2*nf/ofac; -alpha = 1 - (1-exp(-P)).^M; % statistical significance -alpha(alpha<0.1) = M*exp(-P(alpha<0.1)); % (to avoid round-off errors) - -%% Figure -if fig - figure - styles = {':','-.','--'}; - - a = [0.001 0.005 0.01 0.05 0.1 0.5]; - La = length(a); - z = -log(1-(1-a).^(1/M)); -% widths = [.5*ones(1,floor(La/3)) 1*ones(1,La-2*floor(La/3)) 2*ones(1,floor(La/3))]; - hold on; - for i=1:La - line([f(1),0.87*f(end)],[z(i),z(i)],'Color','k','LineStyle',styles{ceil(i*3/La)});%,'LineWidth',widths(i)); - text(0.9*f(end),z(i),strcat('\alpha = ',num2str(a(i))),'fontsize',8); %,'fontname','symbol'); -% lgd{i}=strcat('\alpha=',num2str(a(i))); - end - if ~isempty(a_usr) - [tmp,ind] = intersect(a_usr,a); - a_usr(ind)=[]; - La_usr = length(a_usr); - z_usr = -log(1-(1-a_usr).^(1/M)); - for i = 1:La_usr - line([f(1),0.87*f(end)],[z_usr(i),z_usr(i)],'Color','r','LineStyle',styles{ceil(i*3/La_usr)});%,'LineWidth',widths(i)); - text(0.9*f(end),z_usr(i),strcat('\alpha = ',num2str(a_usr(i))),'fontsize',8); %,'fontname','symbol'); - % lgd{La+i}=strcat('\alpha=',num2str(a_usr(i))); - end - z = [z z_usr]; - end -% legend(lgd); - plot(f,P,'k'); - title('Lomb-Scargle normalized periodogram') - xlabel('f (Hz)'); ylabel('P(f)') - xlim([0 f(end)]); ylim([0,1.2*max([z'; P])]); - hold off; -end - -end - - -%% #### Local functions - -%% init (initialize) -function [x,t,hifac,ofac,a,f,fig] = init(x,t,varargin) - if nargin < 6, a = []; % set default value for a - else a = sort(varargin{4}); - a = a(:)'; - end - if nargin < 5, ofac = 4; % set default value for ofac - else ofac = varargin{3}; - end - if nargin < 4, hifac = 1; % set default value for hifac - else hifac = varargin{2}; - end - if nargin < 3, fig = 0; % set default value for hifac - else fig = varargin{1}; - end - - if isempty(ofac), ofac = 4; end - if isempty(hifac), hifac = 1; end - if isempty(fig), fig = 0; end - - if ~isvector(x) ||~isvector(t), - error('%s: inputs x and t must be vectors',mfilename); - else - x = x(:); t = t(:); - nt = length(t); - if length(x)~=nt - error('%s: Inputs x and t must have the same length',mfilename); - end - end - - [t,ind] = unique(t); % discard double entries and sort t - x = x(ind); - if length(x)~=nt, disp(sprintf('WARNING %s: Double entries have been eliminated',mfilename)); end - - T = t(end) - t(1); - nf = round(0.5*ofac*hifac*nt); - f = (1:nf)'/(T*ofac); -end - -%% extirpolation -function [wk1,wk2] = extirpolate(t,x,fac,nfreq,MACC) - nt = length(x); - wk1 = zeros(2*nfreq,1); - wk2 = zeros(2*nfreq,1); - - for j = 1:nt - ck = 1 + mod(fix(t(j)*fac),2*nfreq); - ckk = 1 + mod(2*(ck-1), 2*nfreq); - wk1 = spread(x(j),wk1,ck, MACC); - wk2 = spread(1 ,wk2,ckk,MACC); - end -end - -%% spread -function yy = spread(y,yy,x,m) - - nfac = [1 1 2 6 24 120 720 5040 40320 362880]; - n = length(yy); - - if x == round(x) % Original Fortran 77 code: ix=x - % if(x.eq.float(ix)) then... - yy(x) = yy(x) + y; - else - % Original Fortran 77 code: i1 = min( max( int(x-0.5*m+1.0),1 ), n-m+1 ) - i1 = min([ max([ floor(x-0.5*m+1),1 ]), n-m+1 ]); - i2 = i1+m-1; - nden = nfac(m); - fac = x-i1; - - fac = fac*prod(x - (i1+1:i2)); - yy(i2) = yy(i2) + y*fac/(nden*(x-i2)); - - for j = i2-1:-1:i1 - nden = (nden/(j+1-i1))*(j-i2); - yy(j) = yy(j) + y*fac/(nden*(x-j)); - end - - end -end diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/license.txt b/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/license.txt deleted file mode 100755 index b96af13..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/license.txt +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2008, Christos Saragiotis -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/parlomb.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/parlomb.m deleted file mode 100755 index b3e9ca7..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/Lomb-Scargle/parlomb.m +++ /dev/null @@ -1,197 +0,0 @@ -function [P,f,alpha] = parlomb(x,t,varargin) -% LOMB caculates the Lomb normalized periodogram (aka Lomb-Scargle, Gauss-Vanicek or Least-Squares spectrum) of a vector x with coordinates in t. -% The coordinates need not be equally spaced. In fact if they are, it is -% probably preferable to use PWELCH or SPECTRUM. For more details on the -% Lomb normalized periodogram, see the excellent section 13.8 in [1], pp. -% 569-577. -% -% This code is a transcription of the Fortran subroutine period in [1] -% (pp.572-573). The calculation of the Lomb normalized periodogram is in -% general a slow procedure. Matlab's characteristics have been taken into -% account in order to make it fast for Matlab but still it is quite slow. -% For a faster (but not exact) version see FASTLOMB. -% -% If the 'fig' flag is on, the periodogram is created, along with some -% default statistical significance levels: .001, .005, .01, .05, .1, .5. -% If the user wants more significance levels, they can give them as input -% to the function. Those will be red. -% -% SYNTAX -% [P,f,alpha] = lomb(x,t,fig,hifac,ofac,a); -% [P,f,alpha] = lomb(x,t,fig,hifac,ofac); -% [P,f,alpha] = lomb(x,t,fig,hifac); -% [P,f,alpha] = lomb(x,t,fig); -% [P,f,alpha] = lomb(x,t); -% -% INPUTS -% x: the vector whose spectrum is wanted. -% t: coordinates of x (should have the same length). -% fig: if 0 (default), no figure is created. -% hifac: the maximum frequency returned is -% (hifac) x (average Nyquist frequency) -% See "THE hifac PARAMETER" in the NOTES section below for more -% details on the hifac parameter. Default is 1 (i.e. max frequency -% is the Nyquist frequency) -% ofac: oversampling factor. Typically it should be 4 or larger. Default -% is 4. See "INTERPRETATION AND SELECTION OF THE ofac PARAMETER" -% in the NOTES section below for more details on the choice of -% ofac parameter. -% a: additional significance levels to be drawn on the figure. -% -% OUTPUTS -% P: the Lomb normalized periodogram -% f: respective frequencies -% alpha: statistical significance for each value of P -% -% NOTES -% A. INTERPRETATION AND SELECTION OF THE ofac PARAMETER [1] -% The lowest independent frequency f to be examined is the inverse of -% the span of the input data, -% 1/(tmax-tmin)=1/T. -% This is the frequency such that the data can include one complete -% cycle. In an FFT method, higher independent frequencies would be -% integer multiples of 1/T . Because we are interested in the -% statistical significance of ANY peak that may occur, however, we -% should over-sample more finely than at interval 1/T, so that sample -% points lie close to the top of ANY peak. This oversampling parameter -% is the ofac. A value ofac >~4 might be typical in use. -% -% B. THE hifac PARAMETER [1] -% Let fhi be the highest frequency of interest. One way to choose fhi is -% to compare it with the Nyquist frequency, fc, which we would obtain, if -% the N data points were evenly spaced over the same span T, that is -% fc = N/(2T). -% The input parameter hifac, is defined as fhi/fc. In other words, hifac -% shows how higher (or lower) that the fc we want to go. -% -% REFERENCES -% [1] W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, -% "Numerical recipes in Fortran 77: the art of scientific computing", -% 2nd ed., vol. 1, Cambridge University Press, NY, USA, 2001. -% -% C. Saragiotis, Nov 2008 - - -%% Inputs check and initialization -[poolavail,isOpen] = check_open_pool; - -if nargin < 2, error('%s: there must be at least 2 inputs.',mfilename); end - -[x,t,hifac,ofac,a_usr,f,fig] = init(x,t,varargin{:}); -nf = length(f); - -mx = mean(x); -x = x-mx; -vx = var(x); -if vx==0, error('%s: x has zero variance',upper(mfilename)); end - - -%% Main - -P = zeros(nf,1); -parfor i=1:nf - wt = 2*pi*f(i)*t; % \omega t - swt = sin(wt); - cwt = cos(wt); - - %% Calculate \omega\tau and related quantities - % I use some trigonometric identities to reduce the computations - Ss2wt = 2*cwt.'*swt; % \sum_t \sin(2\omega\t) - Sc2wt = (cwt-swt).'*(cwt+swt); % \sum_t \cos(2\omega\t) - wtau = 0.5*atan2(Ss2wt,Sc2wt); %\omega\tau - - swtau = sin(wtau); - cwtau = cos(wtau); - - % I use some trigonometric identities to reduce the computations - swttau = swt*cwtau - cwt*swtau; % \sin\omega(t-\tau)) - cwttau = cwt*cwtau + swt*swtau; % \cos\omega(t-\tau)) - - P(i) = ((x.'*cwttau)^2)/(cwttau.'*cwttau) + ((x.'*swttau)^2)/(swttau.'*swttau); -end -P = P/(2*vx); - -%% Significance -M = 2*nf/ofac; -alpha = 1 - (1-exp(-P)).^M; % statistical significance -alpha(alpha<0.1) = M*exp(-P(alpha<0.1)); % (to avoid round-off errors) - -%% Figure -if fig - figure - styles = {':','-.','--'}; - - a = [0.001 0.005 0.01 0.05 0.1 0.5]; - La = length(a); - z = -log(1-(1-a).^(1/M)); - hold on; - for i=1:La - line([f(1),0.87*f(end)],[z(i),z(i)],'Color','k','LineStyle',styles{ceil(i*3/La)}); - text(0.9*f(end),z(i),strcat('\alpha = ',num2str(a(i))),'fontsize',8); - % lgd{i}=strcat('\alpha=',num2str(a(i))); - end - if ~isempty(a_usr) - [tmp,ind] = intersect(a_usr,a); - a_usr(ind)=[]; - La_usr = length(a_usr); - z_usr = -log(1-(1-a_usr).^(1/M)); - for i = 1:La_usr - line([f(1),0.87*f(end)],[z_usr(i),z_usr(i)],'Color','r','LineStyle',styles{ceil(i*3/La_usr)}); - text(0.9*f(end),z_usr(i),strcat('\alpha = ',num2str(a_usr(i))),'fontsize',8); - % lgd{La+i}=strcat('\alpha=',num2str(a_usr(i))); - end - z = [z z_usr]; - end - % legend(lgd); - plot(f,P,'k'); - title('Lomb-Scargle normalized periodogram') - xlabel('f (Hz)'); ylabel('P(f)') - xlim([0 f(end)]); ylim([0,1.2*max([z'; P])]); - hold off; -end -check_close_pool(poolavail,isOpen); -end - - - -%% #### Local functions - -%% init (initialize) -function [x,t,hifac,ofac,a,f,fig] = init(x,t,varargin) -if nargin < 6, a = []; % set default value for a -else a = sort(varargin{4}); - a = a(:)'; -end -if nargin < 5, ofac = 4; % set default value for ofac -else ofac = varargin{3}; -end -if nargin < 4, hifac = 1; % set default value for hifac -else hifac = varargin{2}; -end -if nargin < 3, fig = 0; % set default value for hifac -else fig = varargin{1}; -end - -if isempty(ofac), ofac = 4; end -if isempty(hifac), hifac = 1; end -if isempty(fig), fig = 0; end - -if ~isvector(x) ||~isvector(t), - error('%s: inputs x and t must be vectors',mfilename); -else - x = x(:); t = t(:); - nt = length(t); - if length(x)~=nt - error('%s: Inputs x and t must have the same length',mfilename); - end -end - -[t,ind] = unique(t); % discard double entries and sort t -x = x(ind); -if length(x)~=nt, disp(sprintf('WARNING %s: Double entries have been eliminated',mfilename)); end - -T = t(end) - t(1); -nf = round(0.5*ofac*hifac*nt); -f = (1:nf)'/(T*ofac); -end - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/Plot_Bouts.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/Plot_Bouts.m deleted file mode 100755 index 39ab4bd..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/Plot_Bouts.m +++ /dev/null @@ -1,29 +0,0 @@ -function Plot_Bouts(data,bouts) - -d = data.d; -boutstart=bouts.Start; -boutstop = bouts.Stop; - -figure; clf; -%plot the signal -plot(d,'Color',[.742 .742 .742]); -hold on; - - -% plot bouts in color -for n = 1:length(boutstart) - vec =boutstart(n):boutstop(n); - plot(vec,d(vec),'b') -end - - - - -%title('Sine & Pulses','FontSize',14); -%legend('Signal','Sine','Pulses','Pulse Peaks'); - -grid on -hold off - - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/PulseBoutAnalysis.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/PulseBoutAnalysis.m deleted file mode 100755 index a4fa7c1..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/PulseBoutAnalysis.m +++ /dev/null @@ -1,61 +0,0 @@ -%for plotting, get length of longest sine bout -x = zeros(numel(PulseTrainStart,1)); -for i = 1:numel(PulseTrainStop) - for j = 1:numel(PulseTrainStart{i}) - z = sum(ismember(pulseFFTtimes{i},PulseTrainStart{i}(j):PulseTrainStop{i}(j))); - x(i) = z; - end -end -MaxPulseTrainLength= max(x); - -%for plotting, get max # of sine bouts per song bout and also total num -%bouts - -a = zeros(numel(PulseTrainStart),1); -BoutNum = zeros(numel(BoutsStart),1); -NumPulseBoutsPerSongBout = cell(numel(BoutsStart),1); -for i = 1:numel(PulseTrainStart); - numBouts = numel(BoutsStart{i}); - BoutNum(i) = numBouts; - x = zeros(numBouts,1); - for j = 1:numBouts - z = sum(ismember(PulseTrainStart{i},BoutsStart{i}(j):BoutsStop{i}(j))); - x(j) = z; %Num sine bouts per bout - end - NumPulseBoutsPerSongBout{i} = x; - a(i) = max(x); -end -MaxNumPulseBouts=max(a); -TotalNumBouts = sum(BoutNum); - -%Make 3D array to hold results for plotting -dFreq = NaN(TotalNumBouts,MaxPulseTrainLength,MaxNumPulseBouts); -dTime = NaN(TotalNumBouts,MaxPulseTrainLength,MaxNumPulseBouts); - -%Dump data from SINEFFTfreq into d - -boutNum = 0; -for i = 1:numel(PulseTrainStart);%for each individual - numBouts = numel(BoutsStart{i}); - numPulseBouts = NumPulseBoutsPerSongBout{i}; - pulseBout = 0; - for j = 1:numBouts%for each bout - boutNum = boutNum + 1; - for k = 1:numPulseBouts(j)%for each bout of sine in a song bout - pulseBout = pulseBout+1; - - tf = ismember(pulseFFTtimes{i},PulseTrainStart{i}(pulseBout):PulseTrainStop{i}(pulseBout)); - - pulseLength = sum(tf); - dTime(boutNum,1:pulseLength,k) = pulseFFTtimes{i}(tf); - dFreq(boutNum,1:pulseLength,k) = pulseFFTfreq{i}(tf); - - end - end -end - -dFreq(dFreq == 0) = NaN; -dTime(dTime == 0) = NaN; - - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/PulseModelAnalysisPipeline.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/PulseModelAnalysisPipeline.m deleted file mode 100755 index 47d4315..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/PulseModelAnalysisPipeline.m +++ /dev/null @@ -1,29 +0,0 @@ -%make great pulse model from each individual - -%1 - Starting with pulseInfo2 models, put bad songs in separate folder -%2 - build culled model from each of remaining - -culled_pulseInfo = cull_pulses(pulseInfo2,Lik_pulse.LLR_best,[0 200]); -[culled_pulse_model,culled_Lik_pulse] = fit_pulse_model(culled_pulseInfo.x); - -%compare culled_pulse_model among individuals and strains -%Options -%PCA -%Cluster method - pdist, then UPGMA - - -%??? Is this necessary -%build new community pulse model with sample of data from each individual that forms -%a cluster - - -%Or just do following on good individuals -%algorithm to make pulse model calculate ipis from each individual - -culled_pulseInfo = cull_pulses(pulseInfo2,Lik_pulse.LLR_best,[0 200]); -[culled_pulse_model,culled_Lik_pulse] = fit_pulse_model(culled_pulseInfo.x); -[~,Lik_pulse_all] = Z_2_pulse_model(culled_pulse_model,pulseInfo.x); -final_pulseInfo = cull_pulses(pulseInfo,Lik_pulse_all.LLR_best,[0 200]); -ipi = fit_ipi_model(final_pulseInfo,1e4); -culled_ipi = cullByCDF(ipi, [ ],.005); -gmixPlot(culled_ipi.d',5,100,1e5,[],1);%gives nice plot of mixture model diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/SineBout.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/SineBout.m deleted file mode 100755 index e79344d..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/SineBout.m +++ /dev/null @@ -1,30 +0,0 @@ -BoutTime = cell(numel(BoutsStart),1); -BoutDur = BoutTime; -SineDur = BoutTime; - -BoutDurVSTime = zeros(numel(BoutsStart),1); -SineFracVSTime = BoutDurVSTime; - -for i = 1:numel(BoutsStart) - - numBouts = numel(BoutsStart{i}); - sinedur = zeros(numBouts,1); - boutdur = sinedur; - bouttime = boutdur; - for j = 1:numBouts - sinestarts = SineStart{i}(SineStart{i} >= BoutsStart{i}(j) & SineStart{i} <= BoutsStop{i}(j)); - sinestops = SineStop{i}(SineStop{i} >= BoutsStart{i}(j) & SineStop{i} <= BoutsStop{i}(j)); - sinedur(j) = sum(sinestops -sinestarts); - boutdur(j) = BoutsStop{i}(j) - BoutsStart{i}(j); - bouttime(j) = BoutsStart{i}(j); - - end - BoutTime{i} = bouttime; - BoutDur{i} = boutdur; - SineDur{i} = sinedur; - BoutDurVSTime(i) = corr(boutdur,bouttime); - SineFracVSTime(i) = corr(sinedur./boutdur,bouttime); - -end - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/SineBout.m~ b/ANALYSIS CODE/FlySongAnalysisSuite-master/SineBout.m~ deleted file mode 100755 index 64c69a5..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/SineBout.m~ +++ /dev/null @@ -1,32 +0,0 @@ -BoutTime = cell(numel(BoutsStart),1); -BoutDur = BoutTime; -SineDur = BoutTime; - -BoutDurVSTime = zeros(numel(BoutsStart),1); -SineDurVSTime = BoutDurVSTime; -SineFracVSTime = BoutDurVSTime; - -for i = 1:numel(BoutsStart) - - numBouts = numel(BoutsStart{i}); - sinedur = zeros(numBouts,1); - boutdur = sinedur; - bouttime = boutdur; - for j = 1:numBouts - sinestarts = SineStart{i}(SineStart{i} >= BoutsStart{i}(j) & SineStart{i} <= BoutsStop{i}(j)); - sinestops = SineStop{i}(SineStop{i} >= BoutsStart{i}(j) & SineStop{i} <= BoutsStop{i}(j)); - sinedur(j) = sum(sinestops -sinestarts); - boutdur(j) = BoutsStop{i}(j) - BoutsStart{i}(j); - bouttime(j) = BoutsStart{i}(j); - - end - BoutTime{i} = bouttime; - BoutDur{i} = boutdur; - SineDur{i} = sinedur; - BoutDurVSTime(i) = corr(boutdur,bouttime); - SineDurVSTime(i) = corr(sinedur,bouttime); - SineFracVSTime(i) = corr(sinedur./boutdur,bouttime); - -end - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/SineBoutAnalysis.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/SineBoutAnalysis.m deleted file mode 100755 index 1602506..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/SineBoutAnalysis.m +++ /dev/null @@ -1,61 +0,0 @@ -%for plotting, get length of longest sine bout -x = zeros(numel(SineStart,1)); -for i = 1:numel(SineStop) - for j = 1:numel(SineStart{i}) - z = sum(ismember(SINEFFTtimesall{i},SineStart{i}(j):SineStop{i}(j))); - x(i) = z; - end -end -MaxSineLength= max(x); - -%for plotting, get max # of sine bouts per song bout and also total num -%bouts - -a = zeros(numel(SineStart),1); -BoutNum = zeros(numel(BoutsStart),1); -NumSineBoutsPerSongBout = cell(numel(BoutsStart),1); -for i = 1:numel(SineStart); - numBouts = numel(BoutsStart{i}); - BoutNum(i) = numBouts; - x = zeros(numBouts,1); - for j = 1:numBouts - z = sum(ismember(SineStart{i},BoutsStart{i}(j):BoutsStop{i}(j))); - x(j) = z; %Num sine bouts per bout - end - NumSineBoutsPerSongBout{i} = x; - a(i) = max(x); -end -MaxNumSineBouts=max(a); -TotalNumBouts = sum(BoutNum); - -%Make 3D array to hold results for plotting -dFreq = NaN(TotalNumBouts,MaxSineLength,MaxNumSineBouts); -dTime = NaN(TotalNumBouts,MaxSineLength,MaxNumSineBouts); - -%Dump data from SINEFFTfreq into d - -boutNum = 0; -for i = 1:numel(SineStart);%for each individual - numBouts = numel(BoutsStart{i}); - numSineBouts = NumSineBoutsPerSongBout{i}; - sineBout = 0; - for j = 1:numBouts%for each bout - boutNum = boutNum + 1; - for k = 1:numSineBouts(j)%for each bout of sine in a song bout - sineBout = sineBout+1; - - tf = ismember(SINEFFTtimesall{i},SineStart{i}(sineBout):SineStop{i}(sineBout)); - - sineLength = sum(tf); - dTime(boutNum,1:sineLength,k) = SINEFFTtimesall{i}(tf); - dFreq(boutNum,1:sineLength,k) = SINEFFTfreqall{i}(tf); - - end - end -end - -dFreq(dFreq == 0) = NaN; -dTime(dTime == 0) = NaN; - - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/analyze2.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/analyze2.m deleted file mode 100755 index 5339276..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/analyze2.m +++ /dev/null @@ -1,34 +0,0 @@ - -for i = 1:size(ipis,2); - train_length(i) = sum(ipis{i}); - pulses_per_train(i) = length(ipis{i})+1; - meanIPI_train(i) = mean(ipis{i}); - stdIPI_train(i) = std(ipis{i}); -end - -%plot the IPI trends: -yf=[]; -rsquare=[]; -n=1; -for i=1:size(ipis,2); -aa=length(ipis{i}); -if aa>5; %if there are at least 6 pulses in the train -vect = (1:aa); -[cfun,cfit,output] = fit(vect', ipis{i}', 'exp1'); %exp1: Y = a*exp(b*x) -rsquare(i) = cfit.adjrsquare; -const = cfun.b; -mult = cfun.a; -xf = linspace(1,60,60); - if cfit.adjrsquare>0.5; %if rsquare value is > 0.5 - train(n) = i; - yf(n,:) = exp(const*xf); - n=n+1; - end -end -end - -h=figure(1); for i=1:size(yf,1); -hold on; plot(yf(i,:)); -end -ylim([0 5]); title('exponential fits of IPIs within a train'); - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/analyze_sine_song_trends.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/analyze_sine_song_trends.m deleted file mode 100755 index 5e51d03..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/analyze_sine_song_trends.m +++ /dev/null @@ -1,75 +0,0 @@ -Sine_Freq_Bout = NaN(75,1000,200); -Sine_Freq_Times = NaN(75,1000,200); - -for i=1:length(file_names); %75 experiments - maxFFTfreq = SINEFFTfreq{i}; %take the data from the first experiment - maxFFTtimes = SINEFFTtimes{i}; - bout_Start = BoutsStart{i}; - bout_Stop = BoutsStop{i}; - - for n = length(bout_Start); % - start = bout_Start(n); - stop = bout_Stop(n); - A = find(maxFFTtimes>start & maxFFTtimes0; - C = C - (C(1)-1); - B = B./min(B); - Sine_Freq_Bout(i,1:length(A),n) = B; %each column is a different bout and frequencies are down the rows - Sine_Freq_Times(i,1:length(A),n) = C; - figure(1); hold on; plot(C./10000,B,'.'); - %figure(2); hold on; plot(B,'.r'); - end - end -end - -n=1; -for i = 1:75; -SFB(1,n:n+200000-1) = reshape(Sine_Freq_Bout(i,:,:),1,200000); %reshape works column-wise, so goes down each column -SFT(1,n:n+200000-1) = reshape(Sine_Freq_Times(i,:,:),1,200000); -n=n+200000; -end - -r=1; -for n=1:15000000; - a = SFB(1,n); - TF = isnan(a); - if TF == 1; - continue - end - SFB_A(1,r) = SFB(1,n); - SFT_A(1,r) = SFT(1,n); - r = r + 1; -end - -x=[]; -y=[]; -x = SFT_A'; -y = SFB_A'; -[cfun,cfit,output] = fit(x, y,'exp1'); - -rsquare = cfit.adjrsquare; -const = cfun.b; -mult = cfun.a; -xf = linspace(1,5e4,5e4); - %if cfit.adjrsquare>0.8; %if rsquare value is > 0.5 -yf = exp(const*xf); - -%figure(1); hold on; plot(xf,yf,'k'); -%% -mean_sfb = NaN(75,1000); -for i=1:75; - sfb = Sine_Freq_Bout(i,:,:); %the matrix for each experiment (columns are each bout and rows contain the frequencies) - sfb = squeeze(sfb); - mean_sfb(i,1:1000) = nanmean(sfb,2); %mean down the columns -end - -mm_sfb = nanmean(mean_sfb,1); -mm_sfb_std = nanstd(mean_sfb,1); - -figure; errorbar (mm_sfb, mm_sfb_std); - - - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/build_matrix.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/build_matrix.m deleted file mode 100755 index 5699fb1..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/build_matrix.m +++ /dev/null @@ -1,30 +0,0 @@ -function [data] = build_matrix(varargin) -%USAGE -%%build_matrix(vec1, vec2, vec3...) out of different length vectors -%%replacing empty spaces with NaN. - -%%Creates a matrix with vectors of different dimensions - -data = []; - -for i = 1:nargin - lngths(i) = length(varargin{i}); -end - -ncells = max(lngths) - -for i = 1:nargin - res = varargin{i}; - - if length(res) < ncells - res(length(res)+1:ncells) = NaN; - end - - data = cat(2, data, res'); - -end - - - - - \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/calcAllPulseTrainDurations.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/calcAllPulseTrainDurations.m deleted file mode 100755 index c205a84..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/calcAllPulseTrainDurations.m +++ /dev/null @@ -1,11 +0,0 @@ -trainTimes = []; - -for i = 1:75 - numtrains = numel(ipiTrainsTime{i}); - for j = 1:numtrains - trainDuration = ipiTrainsTime{i}{j}(end) - ipiTrainsTime{i}{j}(1); - if trainDuration > 0 - trainTimes = [trainTimes trainDuration]; - end - end -end diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/calcIpiLombMulti.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/calcIpiLombMulti.m deleted file mode 100755 index 826f7ea..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/calcIpiLombMulti.m +++ /dev/null @@ -1,39 +0,0 @@ -function calcIpiLombMulti(folder) -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end - -dir_list = dir(folder); -file_num = length(dir_list); - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - if TG == 1 -% if strfind(root,'ipi') ~= 0 - - load(path_file); - - fprintf([root '\n']); - %cull pulses using pulse_model - [ipiStats lomb culled_ipi] = cullIPILomb(ipi); - - W = who('-file',path_file); - varstruc =struct; -% load(path_file); - for ii = 1:numel(W) - varstruc.(W{ii}) = eval(W{ii}); - end - varstruc.ipiStatsLomb.ipiStats= ipiStats; - varstruc.ipiStatsLomb.lomb= lomb; - varstruc.ipiStatsLomb.culled_ipi= culled_ipi; - - varstruc.ipiStatsLomb.variables.date = date; - varstruc.ipiStatsLomb.variables.time = clock; - save(path_file,'-struct','varstruc','-mat')%save all variables in original file - -% end - end -end diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/calcIpiMulti.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/calcIpiMulti.m deleted file mode 100755 index 2509f59..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/calcIpiMulti.m +++ /dev/null @@ -1,38 +0,0 @@ -function cullIpiMulti(folder) -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end - -dir_list = dir(folder); -file_num = length(dir_list); - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - if TG == 1 -% if strfind(root,'ipi') ~= 0 - - load(path_file); - - fprintf([root '\n']); - %cull pulses using pulse_model - [ipiStats culled_ipi] = cullIPI(ipi); - - W = who('-file',path_file); - varstruc =struct; -% load(path_file); - for ii = 1:numel(W) - varstruc.(W{ii}) = eval(W{ii}); - end - varstruc.ipiStats.ipiStats= ipiStats; - varstruc.ipiStats.culled_ipi= culled_ipi; - - varstruc.ipiStats.variables.date = date; - varstruc.ipiStats.variables.time = clock; - save(path_file,'-struct','varstruc','-mat')%save all variables in original file - -% end - end -end diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/calcLomb.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/calcLomb.m deleted file mode 100755 index 19dc2fb..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/calcLomb.m +++ /dev/null @@ -1,23 +0,0 @@ -function [lombStats] = calcLomb(culled_ipi,fs,alphaThresh) - -% -%calc Lomb periodgram sign -%peaks at certain alpha (use 0.01 to start) -% - - -%calculate lomb-scargle periodgram -[P,f,alpha]=lomb(culled_ipi.d,culled_ipi.t./fs); -%get peaks -peaks = regionalmax(P); -%get f,alpha,Peaks for peaks < desired alpha -fPeaks = f(peaks); -alphaPeaks = alpha(peaks); - -signF = fPeaks(alphaPeaks < alphaThresh); -signAlpha = alphaPeaks(alphaPeaks .016 & freq < .022); - if numel(freq_range_of_interest) > 1 - best_alpha(i) = min(freq_range_of_interest); - best_P(i) = max(Pow(freq > .016 & freq < .022)); - end -end - -lomb_sim_results.d = d; -lomb_sim_results.P = P; -lomb_sim_results.f = f; -lomb_sim_results.alpha = alpha; -lomb_sim_results.best_alpha = best_alpha; -lomb_sim_results.best_P = best_P; - - - -function [simData,P,f,alpha] = sine_sim(d,ipi,fs,SNR) -t = 1:size(d); %10 minutes -f = 1/(55*fs);%freq = 1/period -% fs = 1e4; -A = 0.002; %amplitude ~2msec -% A = 1; -x = A *sin(2*pi*f*t); - -% plot(t,x) - -% culled_ipi = ipi; -cx = x(ipi.t); -ct = ipi.t; -% plot(ct,cx,'.-') -% -% lomb(cx,ct./fs,1); - -%Now try adding variance to cx -% SNR = .4; -% rmsrnd = sqrt(mean(randn(size(x,2),1).^2)); -% rmsx = sqrt(mean(x.^2)); - -stdx = std(ipi.d./fs); - -% noise = (1/.7088)*(rmsx/SNR) .* randn(size(cx,2),1); -noised = (1/.7088)*(stdx/SNR) .* randn(size(cx,2),1); - -% cy = cx+noise'; -cyd = cx+noised'; - -% plot(ct,cy,'.-') -% lomb(cy,ct./fs,1); - -% plot(ct,cyd,'.-') -[P,f,alpha] = lomb(cyd,ct./fs);%,1); -%don't plot -% [P,f,alpha] = lomb(cyd,ct./fs,1); -simData.t = ct; -simData.x = cyd; - -%%%%%%%%%%%%%%%%%%% -%check rmsq vs rmsrnd -% t = 1:size(data.d); %10 minutes -% f = 1/55e4;%freq = 1/period -% A = 1; -% x = A *sin(2*pi*f*t); -% rmsx = sqrt(mean(x.^2)) -% rmsrnd = sqrt(mean(randn(size(x,2),1).^2)) diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/collectLombSineSimStats.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/collectLombSineSimStats.m deleted file mode 100755 index 076dc97..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/collectLombSineSimStats.m +++ /dev/null @@ -1,128 +0,0 @@ -% culled_ipi = ipiStatsLomb.culled_ipi; - -%%%Now loop through all mat files in folder and collect lomb_sim_results in - -% lsr.filename{ } = filename -% lsr.results{ } = lomb_sim_results; - -function lsr = collectLombSineSimStats(folder) - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end - -%USAGE lsr = collectLombSimStats(folder) -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -file_names = cell(1,file_num); -lomb_sim_results = cell(1,file_num); - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; - fprintf([root '\n']); - load(path_file,'data','maxFFT'); - time_sampled_items.d = maxFFT.freqAll; - time_sampled_items.t = maxFFT.timeAll; - lomb_sim_results{i} = lomb_sim(data,time_sampled_items); - file_names{i} = file; - end -end - -lsr.filename = file_names; -lsr.results = lomb_sim_results; - - - -function lomb_sim_results = lomb_sim(data,ipi) -%ippi = ipiStatsLomb.culled_ipi - - -fs = 1e4; -SNR = .1:.1:2; -d = cell(numel(SNR),1); -P = d; -f = d; -alpha = d; -best_alpha = zeros(numel(SNR),1); -best_P = best_alpha; -for i=1:numel(SNR) - [simData,Pow,freq,sign] = sine_sim(data.d,ipi,fs,SNR(i)); - d{i} = simData; - P{i} = Pow; - f{i} = freq; - alpha{i} = sign; - freq_range_of_interest = sign(freq > .017 & freq < .019); - if numel(freq_range_of_interest) > 1 - best_alpha(i) = min(freq_range_of_interest); - best_P(i) = max(Pow(freq > .017 & freq < .019)); - end -end - -lomb_sim_results.d = d; -lomb_sim_results.P = P; -lomb_sim_results.f = f; -lomb_sim_results.alpha = alpha; -lomb_sim_results.best_alpha = best_alpha; -lomb_sim_results.best_P = best_P; - - - -function [simData,P,f,alpha] = sine_sim(d,ipi,fs,SNR) -t = 1:size(d); %10 minutes -f = 1/(5*fs);%freq = 1/period -% fs = 1e4; -A = 0.002; %amplitude ~2msec -% A = 1; -x = A *sin(2*pi*f*t); - -% plot(t,x) - -% culled_ipi = ipi; -cx = x(ipi.t); -ct = ipi.t; -% plot(ct,cx,'.-') -% -% lomb(cx,ct./fs,1); - -%Now try adding variance to cx -% SNR = .4; -% rmsrnd = sqrt(mean(randn(size(x,2),1).^2)); -% rmsx = sqrt(mean(x.^2)); - -stdx = std(ipi.d./fs); - -% noise = (1/.7088)*(rmsx/SNR) .* randn(size(cx,2),1); -noised = (1/.7088)*(stdx/SNR) .* randn(size(cx,2),1); - -% cy = cx+noise'; -cyd = cx+noised'; - -% plot(ct,cy,'.-') -% lomb(cy,ct./fs,1); - -% plot(ct,cyd,'.-') -[P,f,alpha] = lomb(cyd,ct./fs);%,1); -%don't plot -% [P,f,alpha] = lomb(cyd,ct./fs,1); -simData.t = ct; -simData.x = cyd; - -%%%%%%%%%%%%%%%%%%% -%check rmsq vs rmsrnd -% t = 1:size(data.d); %10 minutes -% f = 1/55e4;%freq = 1/period -% A = 1; -% x = A *sin(2*pi*f*t); -% rmsx = sqrt(mean(x.^2)) -% rmsrnd = sqrt(mean(randn(size(x,2),1).^2)) diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/collectSineSongLombSineSimStats.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/collectSineSongLombSineSimStats.m deleted file mode 100755 index 6d97d05..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/collectSineSongLombSineSimStats.m +++ /dev/null @@ -1,161 +0,0 @@ -% culled_ipi = ipiStatsLomb.culled_ipi; - -%%%Now loop through all mat files in folder and collect lomb_sim_results in - -% lsr.filename{ } = filename -% lsr.results{ } = lomb_sim_results; - -function lsr = collectSineSongLombSineSimStats(folder) - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end - -%USAGE lsr = collectLombSimStats(folder) -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -file_names = cell(1,file_num); -lomb_sim_results = cell(1,file_num); - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; - fprintf([root '\n']); - load(path_file,'data','maxFFT','winnowed_sine'); - time_sampled_items.d = maxFFT.freqAll; - time_sampled_items.t = maxFFT.timeAll; - lomb_sim_results{i} = sine_song_lomb_sim(data,winnowed_sine); - file_names{i} = file; - end -end - -lsr.filename = file_names; -lsr.results = lomb_sim_results; - - -% culled_ipi = ipiStatsLomb.culled_ipi; - -%%%Now loop through all mat files in folder and collect lomb_sim_results in -%%%for individuals - -% lsr.filename{ } = filename -% lsr.results{ } = lomb_sim_results; - - - -function lomb_sim_results = sine_song_lomb_sim(data,winnowed_sine) -%ippi = ipiStatsLomb.culled_ipi - - -fs = data.fs; -SNR = .1:.1:2; -d = cell(numel(SNR),1); -P = d; -f = d; -alpha = d; -best_alpha = zeros(numel(SNR),1); -best_P = best_alpha; -for i=1:numel(SNR) - [simData,Pow,freq,sign] = sine_song_sine_sim(data.d,winnowed_sine,fs,SNR(i)); - d{i} = simData; - P{i} = Pow; - f{i} = freq; - alpha{i} = sign; - if isempty(sign(freq > 0.18 & freq < 0.22)); - best_alpha(i) = NaN; - best_P(i) = NaN; - else - best_alpha(i) = min(sign(freq > 0.18 & freq < 0.22)); - best_P(i) = max(Pow(freq > 0.18 & freq < 0.22)); - end -end - -lomb_sim_results.d = d; -lomb_sim_results.P = P; -lomb_sim_results.f = f; -lomb_sim_results.alpha = alpha; -lomb_sim_results.best_alpha = best_alpha; -lomb_sim_results.best_P = best_P; - - - -function [simData,P,f,alpha] = sine_song_sine_sim(d,winnowed_sine,fs,SNR) -t = 1:size(d); %10 minutes -f = 1/(5*fs);%freq = 1/period -% fs = 1e4; -A = 0.002; %amplitude ~2mV -% A = 1; -x = A *sin(2*pi*f*t); - -holding_cell = cell(1,length(winnowed_sine.start)); -for i = 1:length(winnowed_sine.start) - holding_cell{i} = winnowed_sine.start(i):100:winnowed_sine.stop(i); -end - -winnowed_sine_times =cell2mat(holding_cell); -% plot(t,x) - -% culled_ipi = ipi; -cx = x(winnowed_sine_times); -ct = winnowed_sine_times; -% plot(ct,cx,'.-') -% -% lomb(cx,ct./fs,1); - -%Now try adding variance to cx -% SNR = .4; -% rmsrnd = sqrt(mean(randn(size(x,2),1).^2)); -% rmsx = sqrt(mean(x.^2)); - -stdx = std(cell2mat(winnowed_sine.events)./fs); - -% noise = (1/.7088)*(rmsx/SNR) .* randn(size(cx,2),1); -noised = (1/.7088)*(stdx/SNR) .* randn(size(cx,2),1); - -% cy = cx+noise'; -cyd = cx+noised'; - -% plot(ct,cy,'.-') -% lomb(cy,ct./fs,1); - -% plot(ct,cyd,'.-') -[P,f,alpha] = lomb(cyd,ct./fs); -%don't plot -% [P,f,alpha] = lomb(cyd,ct./fs,1); -%get peaks -peaks = regionalmax(P); -%get f,alpha,Peaks for peaks < desired alpha -fPeaks = f(peaks); -alphaPeaks = alpha(peaks); - -alphaThresh = 0.05; - -signF = fPeaks(alphaPeaks < alphaThresh); -signAlpha = alphaPeaks(alphaPeaks alpha & prob < 1-alpha); -culled_t = ipi.t(prob >alpha & prob < 1-alpha); - -culled_ipi.u = mu; -culled_ipi.S = std; -culled_ipi.d = culled_d; -culled_ipi.t = culled_t; -culled_ipi.fit = obj; \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/cullIPI.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/cullIPI.m deleted file mode 100755 index a51defa..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/cullIPI.m +++ /dev/null @@ -1,70 +0,0 @@ -function [ipiStats culled_ipi] = cullIPI(ipi) - -% -%collect relevant ipi data, return u, S for each, calc Lomb periodgram sign -%peaks at certain alpha (use 0.01 to start) -% - -alphaThresh = 0.025; -fs = 1e4; - -%get two dominant mixture components - -a = ipi.fit.PComponents; -b = sort(a,'descend'); -MP1 = b(1);%mixing proportions -C1 = find(a == MP1);%components -if numel(b) > 1 - MP2 = b(2); - C2 = find(a == MP2); - culled_ipi = cullByCdf(ipi,[C1 C2],alphaThresh); - %re-estimate mixing proportions - options = statset('MaxIter',500); - obj=gmdistribution.fit(culled_ipi.d',2,'options',options); - - a = obj.mu; - b = sort(a,'ascend'); %sort means - mu1 = b(1); - mu2 = b(2); - MP1 = obj.PComponents(a == mu1); %get mixing proportions that correspond to the relevant means - sig1 = obj.Sigma(a == mu1); - sig2 = obj.Sigma(a == mu2); - - - %reduce to one fit if one fit explains most of the data - if MP1 > 0.9%if the top fit explains most of the data, then take just these data - culled_ipi = cullByCdf(ipi,C1,alphaThresh); - obj=gmdistribution.fit(culled_ipi.d',1,'options',options); - mu = obj.mu; - sig = obj.Sigma; - mu1 = mu; - mu2 = NaN; - sig1 = sig; - sig2 = NaN; - end -else - culled_ipi = cullByCdf(ipi,C1,alphaThresh); - if numel(culled_ipi.d) > 0 - options = statset('MaxIter',500); - obj=gmdistribution.fit(culled_ipi.d',1,'options',options); - mu = obj.mu; - sig = obj.Sigma; - mu1 = mu; - mu2 = NaN; - sig1 = sig; - sig2 = NaN; - else - mu1 = culled_ipi.u; - mu2 = NaN; - sig1 = culled_ipi.S; - sig2 = NaN; - end - - -end - - -ipiStats.mu1 = mu1; -ipiStats.mu2 = mu2; -ipiStats.S1 = sig1; -ipiStats.S2 = sig2; diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/cullIPILomb.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/cullIPILomb.m deleted file mode 100755 index 130b800..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/cullIPILomb.m +++ /dev/null @@ -1,67 +0,0 @@ -function [ipiStats lombStats culled_ipi] = cullIPILomb(ipi) - -% -%collect relevant ipi data, return u, S for each, calc Lomb periodgram sign -%peaks at certain alpha (use 0.01 to start) -% - -alphaThresh = 0.05; -fs = 1e4; - -%get two dominant mixture components - -a = ipi.fit.PComponents; -b = sort(a,'descend'); -MP1 = b(1);%mixing proportions -MP2 = b(2); -C1 = find(a == MP1);%components -C2 = find(a == MP2); - -culled_ipi = cullByCdf(ipi,[C1 C2],alphaThresh); - -%re-estimate mixing proportions -options = statset('MaxIter',500); -obj=gmdistribution.fit(culled_ipi.d',2,'options',options); - -a = obj.mu; -b = sort(a,'ascend'); %sort means -mu1 = b(1); -mu2 = b(2); -MP1 = obj.PComponents(a == mu1); %get mixing proportions that correspond to the relevant means -sig1 = obj.Sigma(a == mu1); -sig2 = obj.Sigma(a == mu2); - - -%reduce to one fit if one fit explains most of the data -if MP1 > 0.9%if the top fit explains most of the data, then take just these data - culled_ipi = cullByCdf(ipi,C1,.01); - obj=gmdistribution.fit(culled_ipi.d',1,'options',options); - mu = obj.mu; - sig = obj.Sigma; - mu1 = mu; - mu2 = NaN; - sig1 = sig; - sig2 = NaN; -end - - - -%calculate lomb-scargle periodgram -[P,f,alpha]=lomb(culled_ipi.d,culled_ipi.t./fs); -%get peaks -peaks = regionalmax(P); -%get f,alpha,Peaks for peaks < desired alpha -fPeaks = f(peaks); -alphaPeaks = alpha(peaks); - -signF = fPeaks(alphaPeaks < alphaThresh); -signAlpha = alphaPeaks(alphaPeaks 1 - x = repmat(x,n_data,1); - x = jitter(x,factor); -else %if have one column, need to add false second column to allow jitter to work properly, and then delete - x=repmat(x,n_data,1); - x(:,2) = 2; - x = jitter(x,factor); - x(:,2) = []; -end -x(isnan(d)) = NaN; - -%make new matrix of X positions -%Y = jitter(vector of indices - offset) -for i = 1:n_categories - scatter(x(:,i)-offset,d(:,i),'MarkerEdgeColor',colors{i}) -end - -if ~isempty(std) - for i = 1:n_categories - for j = 1:n_data - line([x(j,i)-offset x(j,i)-offset],[d(j,i)-std(j,i) d(j,i)+std(j,i)],'Color',colors{i},'LineWidth',.5) - end - end -end - -if skip_colheaders == 0 - %add x axis labels - set(gca,'XTick',[1:1:n_categories]) - set(gca,'XTickLabel',colheaders) -end -hold off - -function y = jitter(x, factor, uniformOrGaussianFlag, smallOrRangeFlag, realOrImaginaryFlag) -% Adds a small amount of noise to an input vector, matrix or N-D array. The -% noise can be uniformly or normally distributed, and can have a magnitude -% based upon the range of values of X, or based upon the smallest -% difference between values of X (excluding 'fuzz'). -% -% NOTE: This function accepts complex values for the first input, X. If -% any values of X have imaginary components (even zero-valued imaginary -% components), then by default the noise will be imaginary. Otherwise, the -% default is for real noise. You can choose between real and imaginary -% noise by setting the fifth input parameter (see below). -% -% Y = JITTER(X) adds an amount of uniform noise to the input X, with a -% magnitude of one fifth of the smallest difference between X values -% (excluding 'fuzz'), i.e. the noise, n~U(-d/5, d/5), where d is the -% smallest difference between X values. -% -% Y = JITTER(X, FACTOR) adds noise as above, but scaled by a factor -% of FACTOR, i.e. n~U(-FACTOR*d/5, FACTOR*d/5). -% -% Y = JITTER(X, FACTOR, 1) adds noise as above, but normally distributed -% (white noise), i.e. n~N(0, FACTOR*d/5). JITTER(X, FACTOR, 0) works the -% same as JITTER(X, FACTOR). If the second parameter is left empty (for -% example JITTER(X, [], 1)), then a default scale factor of 1 is used. -% -% Y = JITTER(X, FACTOR, [], 1) adds an amount of noise to X with a -% magnitude of one fiftieth of the range of X. JITTER(X, FACTOR, [], 0) -% works the same as JITTER(X, FACTOR, []). A value of 0 or 1 can be given as -% the third input to choose between uniform and normal noise (see above), -% i.e. n~U(-FACTOR*r/50, FACTOR*r/50) OR n~N(0, FACTOR*r/50), where r is -% the range of the values of X. If the second parameter is left empty then -% a default scale factor of 1 is used. -% -% Y = JITTER(X, FACTOR, [], [], 1) adds an amount of noise as above, but -% with imaginary noise. The magnitude of the noise is the same as in the -% real case, but the phase angle is a uniform random variable, theta~U(0, -% 2*pi). JITTER(X, FACTOR, [], [], 0) works the same as JITTER(X, FACTOR, -% [], []). A value of 0 or 1 can be given as the third input to choose -% between uniform and normal noise, and a value of 0 or 1 can be given as -% the fourth input to choose between using the smallest distance between -% values or the range for determining the magnitude of the noise. If the -% second parameter is left empty then a default scale factor of 1 is used. -% -% -% EXAMPLE: x = [1 -2 7; Inf 3.5 NaN; -Inf 0.001 3]; -% jitter(x) -% -% ans = -% -% 0.9273 -2.0602 6.9569 -% Inf 3.4597 NaN -% -Inf 0.0333 2.9130 -% -% %Plot a noisy sine curve. -% x2 = sin(0:0.1:6); -% plot(jitter(x2, [], 1, 1)); -% -% -% ACKNOWLEGEMENT: This function is based upon the R function of the same -% name, written by Werner Stahel and Martin Maechler, ETH Zurich. -% See http://stat.ethz.ch/R-manual/R-patched/library/base/html/jitter.html -% for details of the original. -% -% -% Class support for input X: -% float: double, single -% -% -% See also RAND, RANDN. -% -% -% $ Author: Richie Cotton $ $ Date: 2006/03/21 $ - - -% Check number of inputs -if nargin < 1 - error('jitter:notEnoughInputs', 'This function requires at least one input.'); -end - -% Set defaults where required -if nargin < 2 || isempty(factor) - factor = 1; -end - -if nargin < 3 || isempty(uniformOrGaussianFlag) - uniformOrGaussianFlag = 0; -end - -if nargin < 4 || isempty(smallOrRangeFlag) - smallOrRangeFlag = 0; -end - -if nargin < 5 || isempty(realOrImaginaryFlag) - realOrImaginaryFlag = ~isreal(x); -end - - -% Find the range of X, ignoring infinite value and NaNs -xFinite = x(isfinite(x(:))); -xRange = max(xFinite) - min(xFinite); - -if ~smallOrRangeFlag - % Remove 'fuzz' - dp = 3 - floor(log10(xRange)); - xFuzzRemoved = round(x * 10^dp) * 10^-dp; - % Find smallest distance between values of X - xUnique = unique(sort(xFuzzRemoved)); - xDifferences = diff(xUnique); - if length(xDifferences) - smallestDistance = min(xDifferences); - elseif xUnique ~= 0 - % In this case, all values are the same, so xUnique has length 1 - smallestDistance = 0.1 * xUnique; - else - % In this case, all values are 0 - smallestDistance = 0.1 * xRange; - end - scaleFactor = 0.2 * factor * smallestDistance; -else - % Calc scale factor based upon range - scaleFactor = 0.02 * factor * xRange; -end - -% Add the noise -s = size(x); -if uniformOrGaussianFlag - % Normal noise - if realOrImaginaryFlag - randomPhaseAngles = 2 * pi * rand(s); - y = x + scaleFactor * randn(s) * exp(randomPhaseAngles * i); - else - y = x + scaleFactor * randn(s); - end -else - % Uniform noise - if realOrImaginaryFlag - randomPhaseAngles = 2 * pi * rand(s); - y = x + scaleFactor * (2*rand(s)-1) * exp(randomPhaseAngles * i); - else - y = x + scaleFactor * (2*rand(s)-1); - end -end \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/extractStrainName.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/extractStrainName.m deleted file mode 100755 index 2eb3318..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/extractStrainName.m +++ /dev/null @@ -1,11 +0,0 @@ -f = file_names; -numf = numel(f); -strainNames = cell(numf,1); -strainInitials = cell(numf,1); -for i = 1:numf - r=regexp(f(i),'_','split'); - name = r{1}(1); - strainNames{i} = char(name); - strainInitials{i} = strainNames{i}(1); -end -strainInitials= cell2mat(strainInitials); diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/extractStrainNames.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/extractStrainNames.m deleted file mode 100755 index 693e874..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/extractStrainNames.m +++ /dev/null @@ -1,13 +0,0 @@ -function [strainNames strainInitials] = extractStrainNames(file_names) -%USAGE [strainNames strainInitials] = extractStrainNames(file_names) -f = file_names; -numf = numel(f); -strainNames = cell(numf,1); -strainInitials = cell(numf,1); -for i = 1:numf - r=regexp(f(i),'_','split'); - name = r{1}(1); - strainNames{i} = char(name); - strainInitials{i} = strainNames{i}(1); -end -strainInitials= cell2mat(strainInitials); diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/extract_annotated_pulses_sines.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/extract_annotated_pulses_sines.m deleted file mode 100755 index 7d1cc89..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/extract_annotated_pulses_sines.m +++ /dev/null @@ -1,14 +0,0 @@ -function [pulses,sines] = extract_annotated_pulses_sines(annotated_pulse_sine,fs) - -pulse_peaks = annotated_pulse_sine.PULSE; -sine_start_stop = annotated_pulse_sine.SINE; - -%For pulse -%Take ~200ms window (100ms) around hand annontated pulse peak -window = .01 * fs; - -%For sine -%Take ~200ms windows stepped through sample - - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/fastlomb.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/fastlomb.m deleted file mode 100755 index 03c5918..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/fastlomb.m +++ /dev/null @@ -1,244 +0,0 @@ -function [P,f,alpha] = fastlomb(x,t,varargin) -% FASTLOMB caculates the Lomb normalized periodogram (aka Lomb-Scargle, Gauss-Vanicek or Least-Squares spectrum) of a vector x with coordinates in t. -% The coordinates need not be equally spaced. In fact if they are, it is -% probably preferable to use PWELCH or SPECTRUM. For more details on the -% Lomb normalized periodogram, see the excellent section 13.8 in [1], pp. -% 569-577. -% -% This code is a transcription of the Fortran subroutine fasper in [1] -% (pp.575-577), so it is a really fast (albeit not really exact) -% implementation of the Lomb periodogram. Also Matlab's characteristics -% have been taken into account in order to make it even faster for -% Matlab. For an exact calculation of the Lomb periodogram use LOMB, -% which is however about 100 times slower. -% -% If the 'fig' flag is on, the periodogram is created, along with some -% default statistical significance levels: .001, .005, .01, .05, .1, .5. -% If the user wants more significance levels, they can give them as input -% to the function. Those will be red. -% -% SYNTAX -% [P,f,alpha] = fastlomb(x,t,fig,hifac,ofac,a); -% [P,f,alpha] = fastlomb(x,t,fig,hifac,ofac); -% [P,f,alpha] = fastlomb(x,t,fig,hifac); -% [P,f,alpha] = fastlomb(x,t,fig); -% [P,f,alpha] = fastlomb(x,t); -% -% INPUTS -% x: the vector whose spectrum is wanted. -% t: coordinates of x (should have the same length). -% fig: if 0 (default), no figure is created. -% hifac: the maximum frequency returned is -% (hifac) x (average Nyquist frequency) -% See "THE hifac PARAMETER" in the NOTES section below for more -% details on the hifac parameter. Default is 1 (i.e. max frequency -% is the Nyquist frequency). -% ofac: oversampling factor. Typically it should be 4 or larger. Default -% is 4. See "INTERPRETATION AND SELECTION OF THE ofac PARAMETER" -% in the NOTES section below for more details on the choice of -% ofac parameter. -% a: additional significance levels to be drawn on the figure. -% -% OUTPUTS -% P: the Lomb normalized periodogram -% f: respective frequencies -% alpha: statistical significance for each value of P -% -% NOTES -% A. INTERPRETATION AND SELECTION OF THE ofac PARAMETER [1] -% The lowest independent frequency f to be examined is the inverse of -% the span of the input data, -% 1/(tmax-tmin)=1/T. -% This is the frequency such that the data can include one complete -% cycle. In an FFT method, higher independent frequencies would be -% integer multiples of 1/T . Because we are interested in the -% statistical significance of ANY peak that may occur, however, we -% should over-sample more finely than at interval 1/T, so that sample -% points lie close to the top of ANY peak. This oversampling parameter -% is the ofac. A value ofac >~4 might be typical in use. -% -% B. THE hifac PARAMETER [1] -% Let fhi be the highest frequency of interest. One way to choose fhi is -% to compare it with the Nyquist frequency, fc, which we would obtain, if -% the N data points were evenly spaced over the same span T, that is -% fc = N/(2T). -% The input parameter hifac, is defined as fhi/fc. In other words, hifac -% shows how higher (or lower) that the fc we want to go. -% -% REFERENCES -% [1] W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, -% "Numerical recipes in Fortran 77: the art of scientific computing", -% 2nd ed., vol. 1, Cambridge University Press, NY, USA, 2001. -% -% C. Saragiotis, Nov 2008 - - -%% Inputs check and initialization -if nargin < 2, error('%s: there must be at least 2 inputs.',mfilename); end -MACC = 10; % Number of interpolation points per 1/4 cycle of the highest frequency - -[x,t,hifac,ofac,a_usr,f,fig] = init(x,t,varargin{:}); -nt = length(t); - -mx = mean(x); -x = x-mx; -vx = var(x); -if vx==0, error('x has zero variance'); end - -nf = length(f); -nfreq = 2^nextpow2(ofac*hifac*nt*MACC); -% ndim = 2*nfreq; - -tmin = t(1); -tmax = t(end); -T = tmax-tmin; - -%% Extirpolation -fac = 2*nfreq/(T*ofac); -[wk1,wk2] = extirpolate(t-tmin,x,fac,nfreq,MACC); - -%% Take the FFT's -W = fft(wk1); -reft1 = real(W(2:nf+1)); % only positive frequencies, without f=0 -imft1 = imag(W(2:nf+1)); - -W = fft(wk2); -reft2 = real(W(2:nf+1)); -imft2 = imag(W(2:nf+1)); - -%% Main -hypo = sqrt(reft2.^2+imft2.^2); -hc2wt = 0.5*reft2./hypo; -hs2wt = 0.5*imft2./hypo; -cwt = sqrt(0.5+hc2wt); -swt = (sign(hs2wt)+(hs2wt==0)).*(sqrt(0.5-hc2wt)); -den = 0.5*nt + hc2wt.*reft2 + hs2wt.*imft2; -cterm = (cwt.*reft1 + swt.*imft1).^2./den; -sterm = (cwt.*imft1 - swt.*reft1).^2./(nt-den); -P = (cterm+sterm)/(2*vx); -P = P(:); - -%% Significance -M = 2*nf/ofac; -alpha = 1 - (1-exp(-P)).^M; % statistical significance -alpha(alpha<0.1) = M*exp(-P(alpha<0.1)); % (to avoid round-off errors) - -%% Figure -if fig - figure - styles = {':','-.','--'}; - - a = [0.001 0.005 0.01 0.05 0.1 0.5]; - La = length(a); - z = -log(1-(1-a).^(1/M)); -% widths = [.5*ones(1,floor(La/3)) 1*ones(1,La-2*floor(La/3)) 2*ones(1,floor(La/3))]; - hold on; - for i=1:La - line([f(1),0.87*f(end)],[z(i),z(i)],'Color','k','LineStyle',styles{ceil(i*3/La)});%,'LineWidth',widths(i)); - text(0.9*f(end),z(i),strcat('\alpha = ',num2str(a(i))),'fontsize',8); %,'fontname','symbol'); -% lgd{i}=strcat('\alpha=',num2str(a(i))); - end - if ~isempty(a_usr) - [tmp,ind] = intersect(a_usr,a); - a_usr(ind)=[]; - La_usr = length(a_usr); - z_usr = -log(1-(1-a_usr).^(1/M)); - for i = 1:La_usr - line([f(1),0.87*f(end)],[z_usr(i),z_usr(i)],'Color','r','LineStyle',styles{ceil(i*3/La_usr)});%,'LineWidth',widths(i)); - text(0.9*f(end),z_usr(i),strcat('\alpha = ',num2str(a_usr(i))),'fontsize',8); %,'fontname','symbol'); - % lgd{La+i}=strcat('\alpha=',num2str(a_usr(i))); - end - z = [z z_usr]; - end -% legend(lgd); - plot(f,P,'k'); - title('Lomb-Scargle normalized periodogram') - xlabel('f (Hz)'); ylabel('P(f)') - xlim([0 f(end)]); ylim([0,1.2*max([z'; P])]); - hold off; -end - -end - - -%% #### Local functions - -%% init (initialize) -function [x,t,hifac,ofac,a,f,fig] = init(x,t,varargin) - if nargin < 6, a = []; % set default value for a - else a = sort(varargin{4}); - a = a(:)'; - end - if nargin < 5, ofac = 4; % set default value for ofac - else ofac = varargin{3}; - end - if nargin < 4, hifac = 1; % set default value for hifac - else hifac = varargin{2}; - end - if nargin < 3, fig = 0; % set default value for hifac - else fig = varargin{1}; - end - - if isempty(ofac), ofac = 4; end - if isempty(hifac), hifac = 1; end - if isempty(fig), fig = 0; end - - if ~isvector(x) ||~isvector(t), - error('%s: inputs x and t must be vectors',mfilename); - else - x = x(:); t = t(:); - nt = length(t); - if length(x)~=nt - error('%s: Inputs x and t must have the same length',mfilename); - end - end - - [t,ind] = unique(t); % discard double entries and sort t - x = x(ind); - if length(x)~=nt, disp(sprintf('WARNING %s: Double entries have been eliminated',mfilename)); end - - T = t(end) - t(1); - nf = round(0.5*ofac*hifac*nt); - f = (1:nf)'/(T*ofac); -end - -%% extirpolation -function [wk1,wk2] = extirpolate(t,x,fac,nfreq,MACC) - nt = length(x); - wk1 = zeros(2*nfreq,1); - wk2 = zeros(2*nfreq,1); - - for j = 1:nt - ck = 1 + mod(fix(t(j)*fac),2*nfreq); - ckk = 1 + mod(2*(ck-1), 2*nfreq); - wk1 = spread(x(j),wk1,ck, MACC); - wk2 = spread(1 ,wk2,ckk,MACC); - end -end - -%% spread -function yy = spread(y,yy,x,m) - - nfac = [1 1 2 6 24 120 720 5040 40320 362880]; - n = length(yy); - - if x == round(x) % Original Fortran 77 code: ix=x - % if(x.eq.float(ix)) then... - yy(x) = yy(x) + y; - else - % Original Fortran 77 code: i1 = min( max( int(x-0.5*m+1.0),1 ), n-m+1 ) - i1 = min([ max([ floor(x-0.5*m+1),1 ]), n-m+1 ]); - i2 = i1+m-1; - nden = nfac(m); - fac = x-i1; - - fac = fac*prod(x - (i1+1:i2)); - yy(i2) = yy(i2) + y*fac/(nden*(x-i2)); - - for j = i2-1:-1:i1 - nden = (nden/(j+1-i1))*(j-i2); - yy(j) = yy(j) + y*fac/(nden*(x-j)); - end - - end -end diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/fftpm.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/fftpm.m deleted file mode 100755 index 72c1a79..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/fftpm.m +++ /dev/null @@ -1,15 +0,0 @@ -function maxfreq = fftpm(pm,color) -%USAGE maxfreq = fftpm(pm,color) -%if specify color, then plots fft -%always spits out maxfreq - -fs = 1e4; -L = length(pm); -NFFT = fs/2;%2^nextpow2(L); -Y = fft(pm,NFFT)/L; -f = fs/2*linspace(0,1,NFFT/2+1); -if nargin ==2 - plot(f,2*abs(Y(1:NFFT/2+1)),color) -end -[~,maxidx] = max(2*abs(Y(1:NFFT/2+1))); -maxfreq = f(maxidx); \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/fftpmMulti.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/fftpmMulti.m deleted file mode 100755 index a6c6a88..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/fftpmMulti.m +++ /dev/null @@ -1,42 +0,0 @@ -function [fileNames, maxfreqMulti] = fftpmMulti(folder,pulseModel_name) -%USAGE maxfreqMulti = fftpmMulti(folder) -%calculate dominant frequency in each pulse model in a folder - -pM_name = char(pulseModel_name); - - -%grab models in a folder and put in cell array - -sep = filesep; -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -fileNames = cell(1,file_num); -maxfreqMulti = zeros(file_num,1); - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and calculating ffts\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; -% if strfind(root,'pm') ~= 0 - %get plot data and limits - pMData = load(path_file,pM_name); - pulse_model = pMData.(pM_name); - - -% load(path_file,'pulse_model'); - fileNames{i} = file; - maxfreqMulti(i) = fftpm(pulse_model.fhM); -% end - end -end - -fileNames(cellfun('isempty',fileNames))=[]; -maxfreqMulti = maxfreqMulti(maxfreqMulti~=0); diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findBoutPauses.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findBoutPauses.m deleted file mode 100755 index e692cf8..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findBoutPauses.m +++ /dev/null @@ -1,9 +0,0 @@ -function BoutPauses = findBoutPauses(bouts) - -%get pauses between bouts - -shifted_bout_starts = circshift(bouts.Start,-1); -bouts_pauses = shifted_bout_starts - bouts.Stop; -bouts_pauses = bouts_pauses(1:end-1); - -BoutPauses = bouts_pauses; diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findBoutPauses_multi.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findBoutPauses_multi.m deleted file mode 100755 index 0318419..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findBoutPauses_multi.m +++ /dev/null @@ -1,36 +0,0 @@ -function findBoutPauses_multi(folder) - - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); - - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - if TG == 1 - - fprintf([root '\n']); - W = who('-file',path_file); - varstruc =struct; - load(path_file); - for ii = 1:numel(W) - varstruc.(W{ii}) = eval(W{ii}); - end - - pauses = varstruc.pauses; - - BoutPauses = findBoutPauses(bouts); - - varstruc.pauses.BoutPauses = BoutPauses; - - varstruc.pauses.variables.date = date; - varstruc.pauses.variables.time = clock; - save(path_file,'-struct','varstruc','-mat')%save all variables in original file - end -end diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findIpiTrains.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findIpiTrains.m deleted file mode 100755 index d513cf8..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findIpiTrains.m +++ /dev/null @@ -1,79 +0,0 @@ -function findIpiTrains(folder) -%collect all data in folder - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and data sizes\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; - % if strfind(root,'_ipi_ipiStatsLomb') ~= 0 - %get culled_ipi data and times - load(path_file,'ipiStats'); - culled_ipi = ipiStats.culled_ipi; - - %grab indexes for start and stop of bouts (cols 1 and 2 of - %boutIdx) - d = culled_ipi.d; - t = culled_ipi.t; - numIpis = numel(culled_ipi.d); - %set up arrays - startIdx = zeros(numIpis,1); - stopIdx = zeros(numIpis,1); - j = 1; - startIdx(j) = 1; - - x = []; - for i = 2:numel(t); - if t(i) - t(i-1) ~= d(i-1)%collect ipis where the ipi matches the distance between pulses - stopIdx(j) = i-1; - j=j+1; - startIdx(j) = i; - - x(j) = t(i); - end - end - stopIdx(j) = i; - - startIdx(startIdx == 0) = []; - stopIdx(stopIdx == 0) = []; - - numBouts = numel(startIdx); - ipis = cell(1,numBouts); - times = cell(1,numBouts); - - for i = 1:numBouts - ipis{i} = d(startIdx(i):stopIdx(i)); - times{i} = t(startIdx(i):stopIdx(i)); - end - - - - W = who('-file',path_file); - varstruc =struct; - load(path_file); - for ii = 1:numel(W) - varstruc.(W{ii}) = eval(W{ii}); - end - varstruc.ipiTrains.d= ipis; - varstruc.ipiTrains.t= times; - - varstruc.ipiTrains.variables.date = date; - varstruc.ipiTrains.variables.time = clock; - save(path_file,'-struct','varstruc','-mat')%save all variables in original file - - % end - end -end - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findMaxFFTinBouts.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findMaxFFTinBouts.m deleted file mode 100755 index a0d444c..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findMaxFFTinBouts.m +++ /dev/null @@ -1,13 +0,0 @@ -function bout_maxFFT = findMaxFFTinBouts(bouts,maxFFT) - -time = cell(numel(bouts.Start),1); -freq = cell(numel(bouts.Start),1); -for i = 1:numel(bouts.Start) - boutTimes = bouts.Start(i):bouts.Stop(i); - tf = ismember(maxFFT.timeAll,boutTimes); - time{i} = maxFFT.timeAll(tf); - freq{i} = maxFFT.freqAll(tf); -end - -bout_maxFFT.time =time; -bout_maxFFT.freq =freq; \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findMaxFFTinBouts_multi.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findMaxFFTinBouts_multi.m deleted file mode 100755 index c2f9604..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findMaxFFTinBouts_multi.m +++ /dev/null @@ -1,51 +0,0 @@ -function findMaxFFTinBouts_multi(folder,sineORpulse) -%USAGE findMaxFFTinBouts_multi('/Users/sternd/Documents/Projects/courtship_song_analysis.w.t.-forpaper/WT_species/mel-all-6Mar/','pulse') - - - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - if TG == 1 - fprintf([root '\n']); - - W = who('-file',path_file); - varstruc =struct; - load(path_file); - for ii = 1:numel(W) - varstruc.(W{ii}) = eval(W{ii}); - end - - data = varstruc.data; - bouts = varstruc.bouts; - - if isempty(sineORpulse) || strcmp(sineORpulse,'sine') == 1 - maxFFT = 'maxFFT'; - elseif strcmp(sineORpulse,'pulse')==1 - maxFFT = 'pMFFT'; - end - - bout_maxFFT = findMaxFFTinBouts(bouts,eval(maxFFT)); - - if strcmp(maxFFT,'maxFFT') == 1 - varstruc.bout_maxFFT = bout_maxFFT; - varstruc.bout_maxFFT.variables.date = date; - varstruc.bout_maxFFT.variables.time = clock; - elseif strcmp(maxFFT,'pMFFT') == 1 - varstruc.bout_pmaxFFT = bout_maxFFT; - varstruc.bout_pmaxFFT.variables.date = date; - varstruc.bout_pmaxFFT.variables.time = clock; - end - - save(path_file,'-struct','varstruc','-mat')%save all variables in original file - end -end - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPauses.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findPauses.m deleted file mode 100755 index 0174d03..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPauses.m +++ /dev/null @@ -1,101 +0,0 @@ -function Pauses = findPauses(data,winnowed_sine,ipiTrains) - - -%ipi best if ipiStatsLomb.culled_ipi - -pulsesong = zeros(size(data.d,1),1); - - -sineStart = round(winnowed_sine.start); -sineStop = round(winnowed_sine.stop); - - -%grab times of pulse song, set to 1 - -ipiStart = cell2mat(ipiTrains.t); -ipiDur = cell2mat(ipiTrains.d); - -for i = 1:numel(ipiStart) - pulsesong(ipiStart(i):(ipiStart(i)+ipiDur(i))) = 1; -end - -%sineBout start and stop times are from above (sineStart, sineStop) -%add second column with type of event identifier (1== sineStart, 2 == -%sineStop) -sineBoutStart = sineStart;%sine start and stop times -sineBoutStop = sineStop; -sineBoutStart(:,2) = 1;%sine start and stop indicators -sineBoutStop(:,2) = 2; - - -%get pulseBout start and stop times -%add column with type of event identifier (3 == pulseStart, 4 == pulseStop) -pulseBoutDiff = diff(pulsesong); -pulseBoutStart = find(pulseBoutDiff == 1) + 1;%pulse start and stop times -pulseBoutStop = find(pulseBoutDiff == -1); -pulseBoutStart(:,2) = 3;%pulse start and stop indicators -pulseBoutStop(:,2) = 4; - -AllEvents = [sineBoutStart;sineBoutStop;pulseBoutStart;pulseBoutStop];%pool them all together -AllEventsSorted = sortrows(AllEvents,1);%sort by time - -%make arrays to hold event info -numDiffEvents = size(sineStart,1) + size(pulseBoutStart,1) - 1; -PauseType = cell(numDiffEvents,1);%type of pause (sine-sine, pulse-sine, sine-pulse, pulse-pulse) -PauseDelta = zeros(numDiffEvents,1);%duration of pause -PauseTime = zeros(numDiffEvents-1,1);%start time of pause - -for i = 1:size(AllEventsSorted,1) - 1 - %get type of transition - type_first = AllEventsSorted(i,2); - type_next = AllEventsSorted(i+1,2); - if (type_first == 2 && type_next == 1) - type = 'sine-sine'; - PauseType{i} = type; - PauseDelta(i) = abs(AllEventsSorted(i+1,1) - AllEventsSorted(i,1));%get duration of pause - PauseTime(i) = AllEventsSorted(i); - elseif (type_first == 2 && type_next == 3) - type = 'sine-pulse'; - PauseType{i} = type; - PauseDelta(i) = abs(AllEventsSorted(i+1,1) - AllEventsSorted(i,1));%get duration of pause - PauseTime(i) = AllEventsSorted(i); - elseif (type_first == 4 && type_next == 1) - type = 'pulse-sine'; - PauseType{i} = type; - PauseDelta(i) = abs(AllEventsSorted(i+1,1) - AllEventsSorted(i,1));%get duration of pause - PauseTime(i) = AllEventsSorted(i); - elseif (type_first == 4 && type_next == 3) - type = 'pulse-pulse'; - PauseType{i} = type; - PauseDelta(i) = abs(AllEventsSorted(i+1,1) - AllEventsSorted(i,1));%get duration of pause - PauseTime(i) = AllEventsSorted(i); - end -end - -%clear out empty cell elements and zeros in arrays -PauseType(cellfun('isempty',PauseType))=[]; -PauseDelta(PauseDelta ==0) = []; -PauseTime(PauseTime ==0) = []; - -%get start time of pause -sineSineDelta = PauseDelta(strcmp('sine-sine',PauseType)); -sinePulseDelta = PauseDelta(strcmp('sine-pulse',PauseType)); -pulsePulseDelta = PauseDelta(strcmp('pulse-pulse',PauseType)); -pulseSineDelta = PauseDelta(strcmp('pulse-sine',PauseType)); - - -% %get pauses between bouts -% -% shifted_bout_starts = circshift(bouts.Start,-1); -% bouts_pauses = shifted_bout_starts - bouts.Stop; -% bouts_pauses = bouts_pauses(1:end-1); -% -% Pauses.Bouts = bouts_pauses; -Pauses.PauseDelta = PauseDelta; -Pauses.Type = PauseType; -Pauses.Time = PauseTime; -Pauses.sinesine = sineSineDelta; -Pauses.sinepulse = sinePulseDelta; -Pauses.pulsesine = pulseSineDelta; -Pauses.pulsepulse = pulsePulseDelta; - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPauses_multi.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findPauses_multi.m deleted file mode 100755 index 86bd72c..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPauses_multi.m +++ /dev/null @@ -1,38 +0,0 @@ -function findPauses_multi(folder) - - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); - - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - if TG == 1 - - fprintf([root '\n']); - W = who('-file',path_file); - varstruc =struct; - load(path_file); - for ii = 1:numel(W) - varstruc.(W{ii}) = eval(W{ii}); - end - - data = varstruc.data; - winnowed_sine = varstruc.winnowed_sine; - ipiTrains = varstruc.ipiTrains; - - pauses = findPauses(data,winnowed_sine,ipiTrains); - - varstruc.pauses = pauses; - - varstruc.pauses.variables.date = date; - varstruc.pauses.variables.time = clock; - save(path_file,'-struct','varstruc','-mat')%save all variables in original file - end -end diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPeriod.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findPeriod.m deleted file mode 100755 index bea876f..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPeriod.m +++ /dev/null @@ -1,42 +0,0 @@ -function period = findPeriod(pulse_model) -%USAGE period = findPeriod(pulse_model) - -pm = pulse_model; -pm = smooth(pulse_model);%perform gentle smoothing to eliminate ridges at peaks and troughs -%get max and min values -pmmax = regionalmax(pm); -pmmin = regionalmax(-pm); -max = pm(pmmax); -maxidx = find(pmmax==1); -min = pm(pmmin); -minidx = find(pmmin==1); -%get abs vales and indexes -a(:,1) = abs(max); -a(:,2) = maxidx; -i(:,1) = abs(min); -i(:,2) = minidx; -%collect all max and min values -all = cat(1,a,i); -all = sortrows(all,-1); - -%find top three hits, these are the peak and two troughs of pulse model -peaks = zeros(3,2); -for i = 1:3 - peaks(i,1) = pm(all(i,2)); - peaks(i,2) = all(i,2); -end -%determine which are pos (1) and which are neg (0) -pos = zeros(3,1); -for i =1:3 - pos(i) = isreal(sqrt(peaks(i,1))); -end - -if sum(pos) == 1; %if one positive, take two negs - troughs = peaks(pos ==0,:); -else %or else take two poss - troughs = peaks(pos ==1,:); -end -troughIdx = troughs(:,2); -period = abs(diff(troughIdx)); - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPeriodMulti.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findPeriodMulti.m deleted file mode 100755 index e500b6b..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPeriodMulti.m +++ /dev/null @@ -1,45 +0,0 @@ -function [fileNames, periodsMulti] = findPeriodMulti(folder,pulseModel_name) -%USAGE [fileNames, periodsMulti] = findPeriodMulti(folder,pulseModel_name) -%calculate dominant frequency in each pulse model in a folder -%pulseModel_name = e.g. 'pulse_model' - - -%grab models in a folder and put in cell array - -pM_name = char(pulseModel_name); - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); -i= 0; - -fileNames = cell(1,file_num); -periodsMulti = zeros(file_num,1); - -%get file names and sample sizes for fhZ and shZ -fprintf('Grabbing file names and calculating trough-to-trough periods\n'); -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - - if TG == 1 - i = i+1; -% if strfind(root,'pm') ~= 0 - %get plot data and limits - - pMData = load(path_file,pM_name); - pulse_model = pMData.(pM_name); - -% load(path_file,'pulse_model'); - fileNames{i} = file; - periodsMulti(i) = findPeriod(pulse_model.fhM); -% end - end -end - -fileNames(cellfun('isempty',fileNames))=[]; -periodsMulti = periodsMulti(periodsMulti~=0); diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPulseMaxFFT.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findPulseMaxFFT.m deleted file mode 100755 index 32eefda..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPulseMaxFFT.m +++ /dev/null @@ -1,23 +0,0 @@ -function pMFFT = findPulseMaxFFT(pulseInfo) - -Fs = 22050; -nfft = 100000; - -numPulse = numel(pulseInfo.x); - -freq = zeros(numPulse,1); -time = zeros(numPulse,1); -%do for each pulse -for i = 1:numPulse - - ym = pulseInfo.x{i}; - r = length(ym); - sec = r/10000; - wnd = round(22050*sec); - z = resample(ym,22050,10000); - [Sn,F] = spectrogram(z,wnd,[],nfft,Fs); - freq(i)= F(abs(Sn) == max(abs(Sn))); - time(i) = pulseInfo.wc(i); -end -pMFFT.timeAll =time; -pMFFT.freqAll =freq; diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPulseMaxFFT_multi.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findPulseMaxFFT_multi.m deleted file mode 100755 index 4c0c637..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findPulseMaxFFT_multi.m +++ /dev/null @@ -1,37 +0,0 @@ -function findPulseMaxFFT_multi(pI,folder) -%USAGE findPulseMaxFFT_multi('culled_pulseInfo','/Users/sternd/Documents/Projects/courtship_song_analysis.w.t.-forpaper/WT_species/mel-all-6Mar/') -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); - -file_num = length(dir_list); -% pI = eval(pI); - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - if TG == 1 - W = who('-file',path_file); - varstruc =struct; - load(path_file); - for ii = 1:numel(W) - varstruc.(W{ii}) = eval(W{ii}); - end - - fprintf([root '\n']); - %calc sine fund freq - pMFFT = findPulseMaxFFT(eval(pI)); - - varstruc.pMFFT = pMFFT; - - varstruc.pMFFT.variables.date = date; - varstruc.pMFFT.variables.time = clock; - save(path_file,'-struct','varstruc','-mat')%save all variables in original file - - end -end - -% check_close_pool(poolavail,isOpen); diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findSongBouts.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findSongBouts.m deleted file mode 100755 index 8549710..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findSongBouts.m +++ /dev/null @@ -1,82 +0,0 @@ -function [bouts] = findSongBouts(data,winnowed_sine,ipiTrains,Pauses,threshold) - -% threshold = 1e4;%this should be set depending on distribution of pauses - -%ipi best if ipiStatsLomb.culled_ipi - -%make array length of recording -%make this a 0/1 index for absence/presence of songennd -song = zeros(size(data.d,1),1); -% sinesong = zeros(size(data.d,1),1); -% pulsesong = zeros(size(data.d,1),1); -%grab times of sine song, set to 1 - - -sineStart = round(winnowed_sine.start); -sineStop = round(winnowed_sine.stop); - -for i = 1:numel(sineStart) -% sinesong(sineStart(i):sineStop(i)) = 1; - song(sineStart(i):sineStop(i)) = 1; -end - -%grab times of pulse song, set to 1 - -ipiStart = cell2mat(ipiTrains.t); -ipiDur = cell2mat(ipiTrains.d); - -for i = 1:numel(ipiStart) - song(ipiStart(i):(ipiStart(i)+ipiDur(i))) = 1; -% pulsesong(ipiStart(i):(ipiStart(i)+ipiDur(i))) = 1; -end - - -%Remove pauses if < threshold -PauseDelta = Pauses.PauseDelta; -PauseTime = Pauses.Time; -shortPausesIdx = find(PauseDelta < threshold); -maskStart = PauseTime(shortPausesIdx)+1; -maskStop = maskStart+PauseDelta(shortPausesIdx); -for i = 1:numel(maskStart) - song(maskStart(i):maskStop(i)) =1; -end - -%call bout start and stop times - -x = diff(song); -% y = find(x); -Starts = find(x==1); -Stops = find(x==-1); - -Start = Starts + 1; -Stop = Stops; - -if song(1) == 1 %then have song from the very beginning - Start = [1;Start]; -end -if song(end) == 1 %then have song at very end - Stop = [Stop;numel(song)]; -end - - -%pad bouts by IPI on either side -max_IPI = max(ipiDur); -Start = Start - max_IPI; -Stop = Stop + max_IPI; - - -%if indixes run off beginning or end, then trim back -Start(Start < 1) = 1; -Stop(Stop > numel(song)) = numel(song); - -%make cell array of bouts -bout_events = cell(numel(Start),1); -for i = 1:numel(bout_events) - bout_events{i} = data.d(Start(i):Stop(i)); -end - - -bouts.Start = Start; -bouts.Stop = Stop; -bouts.x = bout_events; - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/findSongBouts_multi.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/findSongBouts_multi.m deleted file mode 100755 index cafd900..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/findSongBouts_multi.m +++ /dev/null @@ -1,38 +0,0 @@ -function findSongBouts_multi(folder,threshold) - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - if TG == 1 - fprintf([root '\n']); - - W = who('-file',path_file); - varstruc =struct; - load(path_file); - for ii = 1:numel(W) - varstruc.(W{ii}) = eval(W{ii}); - end - - data = varstruc.data; - winnowed_sine = varstruc.winnowed_sine; - ipiTrains = varstruc.ipiTrains; - pauses = varstruc.pauses; - - bouts = findSongBouts(data,winnowed_sine,ipiTrains,pauses,threshold); - - varstruc.bouts = bouts; - - varstruc.bouts.variables.date = date; - varstruc.bouts.variables.time = clock; - save(path_file,'-struct','varstruc','-mat')%save all variables in original file - end -end - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/fit_ipi_model.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/fit_ipi_model.m deleted file mode 100755 index 8a6e402..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/fit_ipi_model.m +++ /dev/null @@ -1,50 +0,0 @@ -function ipi = fit_ipi_model(pulseTimes,numComponents) -%ipi = fit_ipi_model(pulseInfo) -%provide pulses -%return info about ipis, time in second (not samples) - -%p are pulses (=pulseInfo2.wc) -fprintf('fitting ipi model\n') -p = pulseTimes; - -if nargin <2 - numComponents = 6; -end - -p_shift_one = circshift(p,[0 -1]); -ipi_d=p_shift_one(1:end-1)-p(1:end-1); -%Test range of gmdistribution.fit parameters -AIC=zeros(1,numComponents); -obj=cell(1,numComponents); -options = statset('MaxIter',500); -for k=1:numComponents - try - obj{k}=gmdistribution.fit(ipi_d',k,'options',options); - - catch - fprintf('problem\n') - AIC(k) = NaN; - end -% if obj{k}.Converged == 1%keep AIC only for those that converged -% AIC(k)=obj{k}.AIC; -% else -% -% end - -end -[~,numComponents]=min(AIC);%best fit model - -% find(obj{1}.PComponents == max(obj{1}.PComponents)); -ipi_index = find(obj{numComponents}.PComponents == max(obj{numComponents}.PComponents));%find the model in the mixture model with the highest mixture proportion -ipi_mean = obj{numComponents}.mu(ipi_index); -ipi_var = obj{numComponents}.Sigma(ipi_index); -ipi_SD = sqrt(ipi_var); - -ipi_time = p(1:end-1); -ipi = struct('u',ipi_mean,'S',ipi_SD,'d',ipi_d,'t',ipi_time,'fit',obj{numComponents});%results in units of samples - -% fprintf('Could not fit mixture model with winnowed ipis.\n') -% -% ipi =struct('u',[],'S',[],'d',[],'t',[],'fit',{}); -end - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/fit_ipi_model_multi.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/fit_ipi_model_multi.m deleted file mode 100755 index 97892f2..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/fit_ipi_model_multi.m +++ /dev/null @@ -1,41 +0,0 @@ -function fit_ipi_model_multi(folder,pulseInfo_name) -%USAGE fit_ipi_model_multi(folder,pulseInfo_name) -%pulseInfo_name can take 'pulseInfo', 'pulseInfo2', etc. - -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end - -dir_list = dir(folder); -file_num = length(dir_list); - -pI_name = char(pulseInfo_name); - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - if TG == 1 - W = who('-file',path_file); - varstruc =struct; - load(path_file); - for ii = 1:numel(W) - varstruc.(W{ii}) = eval(W{ii}); - end - - pI_data = varstruc.(pI_name); - - fprintf([root '\n']); - ipi = fit_ipi_model(pI_data.wc); - - varstruc.ipi = ipi; - varstruc.ipi.variables.pulseInfo_ver = pI_name; - varstruc.ipi.variables.date = date; - varstruc.ipi.variables.time = clock; - save(path_file,'-struct','varstruc','-mat')%save all variables in original file - - - end -end - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/gmixPlot.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/gmixPlot.m deleted file mode 100755 index 451bde8..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/gmixPlot.m +++ /dev/null @@ -1,87 +0,0 @@ -function [obj,residuals,Z] = gmixPlot(X,N,MaxIter,bins,plotOFF,plotSubGaussians,obj,xlimits,replicates) - -%USAGE [obj,residuals,Z] = gmixPlot(X,N,MaxIter,bins,plotOFF,plotSubGaussians,obj,xlimits,replicates) - - %Inputs: - %X = column vector of data - %N = number of clusters - %MaxIter = max iterations of GMM fit - %bins = number of bins to display - %plotsOFF = turns plotting off and on - %plotSubGaussians = turn subgaussian plots on and off - %obj = inputted GMM - %xlimits = x limits for plot - %replicates = # of replicates for GMM - - %Outputs: - %obj = GMM object - %residuals = GMM errors - %Z = histogram bins (Z = {Xvalues, Yvalues}) - - - - if nargin < 3 || isempty(MaxIter) - MaxIter = 10000; - end - - if nargin < 4 || isempty(bins) - bins = 50; - end - - if nargin < 5 || isempty(plotOFF) - plotOFF = false; - end - - if nargin < 6 || isempty(plotSubGaussians) - plotSubGaussians = false; - end - - if nargin < 9 || isempty(replicates) - replicates = 1; - end - - if nargin < 7 || isempty(obj) - options = statset('MaxIter',MaxIter,'Robust','on'); - obj = gmdistribution.fit(X,N,'Options',options,'Replicates',replicates,'Regularize',1e-30); - else - N = length(obj.mu); - end - - - - - - [YY,XX] = hist(X,bins); - YY = YY ./ (sum(YY)*(XX(2) - XX(1))); - g = @(x) pdf(obj,x); - residuals = YY' - g(XX'); - - - if ~plotOFF - - %figure - bar(XX,YY) - if nargin < 8 || isempty(xlimits) - xlimits = [XX(1) XX(end)]; - end - xx = linspace(xlimits(1),xlimits(2),1000); - - hold on - - xlimits = [xlimits 0 max(YY)*1.1]; - axis(xlimits); - - - if plotSubGaussians - g = @(x,mu,sigma,p) p*exp(-.5*(x-mu).^2./sigma^2)./sqrt(2*pi*sigma^2); - for i=1:N - plot(xx,g(xx,obj.mu(i),sqrt(obj.Sigma(i)),obj.PComponents(i)),'g-','linewidth',2) - end - end - h = plot(xx,pdf(obj,xx')); - set(h,'linewidth',2) - set(h,'Color','r') - - end - - Z = {XX,YY}; \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/jitter/jitter.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/jitter/jitter.m deleted file mode 100755 index 89f3b21..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/jitter/jitter.m +++ /dev/null @@ -1,142 +0,0 @@ -function y = jitter(x, factor, uniformOrGaussianFlag, smallOrRangeFlag, realOrImaginaryFlag) -% Adds a small amount of noise to an input vector, matrix or N-D array. The -% noise can be uniformly or normally distributed, and can have a magnitude -% based upon the range of values of X, or based upon the smallest -% difference between values of X (excluding 'fuzz'). -% -% NOTE: This function accepts complex values for the first input, X. If -% any values of X have imaginary components (even zero-valued imaginary -% components), then by default the noise will be imaginary. Otherwise, the -% default is for real noise. You can choose between real and imaginary -% noise by setting the fifth input parameter (see below). -% -% Y = JITTER(X) adds an amount of uniform noise to the input X, with a -% magnitude of one fifth of the smallest difference between X values -% (excluding 'fuzz'), i.e. the noise, n~U(-d/5, d/5), where d is the -% smallest difference between X values. -% -% Y = JITTER(X, FACTOR) adds noise as above, but scaled by a factor -% of FACTOR, i.e. n~U(-FACTOR*d/5, FACTOR*d/5). -% -% Y = JITTER(X, FACTOR, 1) adds noise as above, but normally distributed -% (white noise), i.e. n~N(0, FACTOR*d/5). JITTER(X, FACTOR, 0) works the -% same as JITTER(X, FACTOR). If the second parameter is left empty (for -% example JITTER(X, [], 1)), then a default scale factor of 1 is used. -% -% Y = JITTER(X, FACTOR, [], 1) adds an amount of noise to X with a -% magnitude of one fiftieth of the range of X. JITTER(X, FACTOR, [], 0) -% works the same as JITTER(X, FACTOR, []). A value of 0 or 1 can be given as -% the third input to choose between uniform and normal noise (see above), -% i.e. n~U(-FACTOR*r/50, FACTOR*r/50) OR n~N(0, FACTOR*r/50), where r is -% the range of the values of X. If the second parameter is left empty then -% a default scale factor of 1 is used. -% -% Y = JITTER(X, FACTOR, [], [], 1) adds an amount of noise as above, but -% with imaginary noise. The magnitude of the noise is the same as in the -% real case, but the phase angle is a uniform random variable, theta~U(0, -% 2*pi). JITTER(X, FACTOR, [], [], 0) works the same as JITTER(X, FACTOR, -% [], []). A value of 0 or 1 can be given as the third input to choose -% between uniform and normal noise, and a value of 0 or 1 can be given as -% the fourth input to choose between using the smallest distance between -% values or the range for determining the magnitude of the noise. If the -% second parameter is left empty then a default scale factor of 1 is used. -% -% -% EXAMPLE: x = [1 -2 7; Inf 3.5 NaN; -Inf 0.001 3]; -% jitter(x) -% -% ans = -% -% 0.9273 -2.0602 6.9569 -% Inf 3.4597 NaN -% -Inf 0.0333 2.9130 -% -% %Plot a noisy sine curve. -% x2 = sin(0:0.1:6); -% plot(jitter(x2, [], 1, 1)); -% -% -% ACKNOWLEGEMENT: This function is based upon the R function of the same -% name, written by Werner Stahel and Martin Maechler, ETH Zurich. -% See http://stat.ethz.ch/R-manual/R-patched/library/base/html/jitter.html -% for details of the original. -% -% -% Class support for input X: -% float: double, single -% -% -% See also RAND, RANDN. -% -% -% $ Author: Richie Cotton $ $ Date: 2006/03/21 $ - - -% Check number of inputs -if nargin < 1 - error('jitter:notEnoughInputs', 'This function requires at least one input.'); -end - -% Set defaults where required -if nargin < 2 || isempty(factor) - factor = 1; -end - -if nargin < 3 || isempty(uniformOrGaussianFlag) - uniformOrGaussianFlag = 0; -end - -if nargin < 4 || isempty(smallOrRangeFlag) - smallOrRangeFlag = 0; -end - -if nargin < 5 || isempty(realOrImaginaryFlag) - realOrImaginaryFlag = ~isreal(x); -end - - -% Find the range of X, ignoring infinite value and NaNs -xFinite = x(isfinite(x(:))); -xRange = max(xFinite) - min(xFinite); - -if ~smallOrRangeFlag - % Remove 'fuzz' - dp = 3 - floor(log10(xRange)); - xFuzzRemoved = round(x * 10^dp) * 10^-dp; - % Find smallest distance between values of X - xUnique = unique(sort(xFuzzRemoved)); - xDifferences = diff(xUnique); - if length(xDifferences) - smallestDistance = min(xDifferences); - elseif xUnique ~= 0 - % In this case, all values are the same, so xUnique has length 1 - smallestDistance = 0.1 * xUnique; - else - % In this case, all values are 0 - smallestDistance = 0.1 * xRange; - end - scaleFactor = 0.2 * factor * smallestDistance; -else - % Calc scale factor based upon range - scaleFactor = 0.02 * factor * xRange; -end - -% Add the noise -s = size(x); -if uniformOrGaussianFlag - % Normal noise - if realOrImaginaryFlag - randomPhaseAngles = 2 * pi * rand(s); - y = x + scaleFactor * randn(s) * exp(randomPhaseAngles * i); - else - y = x + scaleFactor * randn(s); - end -else - % Uniform noise - if realOrImaginaryFlag - randomPhaseAngles = 2 * pi * rand(s); - y = x + scaleFactor * (2*rand(s)-1) * exp(randomPhaseAngles * i); - else - y = x + scaleFactor * (2*rand(s)-1); - end -end \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/jitter/license.txt b/ANALYSIS CODE/FlySongAnalysisSuite-master/jitter/license.txt deleted file mode 100755 index 3424213..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/jitter/license.txt +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2009, Richard Cotton -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/kernel_mode.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/kernel_mode.m deleted file mode 100755 index aca7669..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/kernel_mode.m +++ /dev/null @@ -1,16 +0,0 @@ -function [kmode] = kernel_mode(vector, bins) -%%Function to get the mode from a kernel distribution. -%kernel_mode(vector, 21:1:199) - vector is any vector whose mode is going -%to be obtained. -%bins - a sequence to indicate which is the size of the intervals used to -%get the mode. - - -x=bins; -f=ksdensity(vector,x); -max_f=max(f); -max_f_col=find(f==max_f); -max_x=x(max_f_col); -kmode = max_x; %./11; - - \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/lomb.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/lomb.m deleted file mode 100755 index f87e486..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/lomb.m +++ /dev/null @@ -1,193 +0,0 @@ -function [P,f,alpha] = lomb(x,t,varargin) -% LOMB caculates the Lomb normalized periodogram (aka Lomb-Scargle, Gauss-Vanicek or Least-Squares spectrum) of a vector x with coordinates in t. -% The coordinates need not be equally spaced. In fact if they are, it is -% probably preferable to use PWELCH or SPECTRUM. For more details on the -% Lomb normalized periodogram, see the excellent section 13.8 in [1], pp. -% 569-577. -% -% This code is a transcription of the Fortran subroutine period in [1] -% (pp.572-573). The calculation of the Lomb normalized periodogram is in -% general a slow procedure. Matlab's characteristics have been taken into -% account in order to make it fast for Matlab but still it is quite slow. -% For a faster (but not exact) version see FASTLOMB. -% -% If the 'fig' flag is on, the periodogram is created, along with some -% default statistical significance levels: .001, .005, .01, .05, .1, .5. -% If the user wants more significance levels, they can give them as input -% to the function. Those will be red. -% -% SYNTAX -% [P,f,alpha] = lomb(x,t,fig,hifac,ofac,a); -% [P,f,alpha] = lomb(x,t,fig,hifac,ofac); -% [P,f,alpha] = lomb(x,t,fig,hifac); -% [P,f,alpha] = lomb(x,t,fig); -% [P,f,alpha] = lomb(x,t); -% -% INPUTS -% x: the vector whose spectrum is wanted. -% t: coordinates of x (should have the same length). -% fig: if 0 (default), no figure is created. -% hifac: the maximum frequency returned is -% (hifac) x (average Nyquist frequency) -% See "THE hifac PARAMETER" in the NOTES section below for more -% details on the hifac parameter. Default is 1 (i.e. max frequency -% is the Nyquist frequency) -% ofac: oversampling factor. Typically it should be 4 or larger. Default -% is 4. See "INTERPRETATION AND SELECTION OF THE ofac PARAMETER" -% in the NOTES section below for more details on the choice of -% ofac parameter. -% a: additional significance levels to be drawn on the figure. -% -% OUTPUTS -% P: the Lomb normalized periodogram -% f: respective frequencies -% alpha: statistical significance for each value of P -% -% NOTES -% A. INTERPRETATION AND SELECTION OF THE ofac PARAMETER [1] -% The lowest independent frequency f to be examined is the inverse of -% the span of the input data, -% 1/(tmax-tmin)=1/T. -% This is the frequency such that the data can include one complete -% cycle. In an FFT method, higher independent frequencies would be -% integer multiples of 1/T . Because we are interested in the -% statistical significance of ANY peak that may occur, however, we -% should over-sample more finely than at interval 1/T, so that sample -% points lie close to the top of ANY peak. This oversampling parameter -% is the ofac. A value ofac >~4 might be typical in use. -% -% B. THE hifac PARAMETER [1] -% Let fhi be the highest frequency of interest. One way to choose fhi is -% to compare it with the Nyquist frequency, fc, which we would obtain, if -% the N data points were evenly spaced over the same span T, that is -% fc = N/(2T). -% The input parameter hifac, is defined as fhi/fc. In other words, hifac -% shows how higher (or lower) that the fc we want to go. -% -% REFERENCES -% [1] W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, -% "Numerical recipes in Fortran 77: the art of scientific computing", -% 2nd ed., vol. 1, Cambridge University Press, NY, USA, 2001. -% -% C. Saragiotis, Nov 2008 - - -%% Inputs check and initialization -if nargin < 2, error('%s: there must be at least 2 inputs.',mfilename); end - -[x,t,hifac,ofac,a_usr,f,fig] = init(x,t,varargin{:}); -nf = length(f); - -mx = mean(x); -x = x-mx; -vx = var(x); -if vx==0, error('%s: x has zero variance',upper(mfilename)); end - - -%% Main - -P = zeros(nf,1); -for i=1:nf - wt = 2*pi*f(i)*t; % \omega t - swt = sin(wt); - cwt = cos(wt); - - %% Calculate \omega\tau and related quantities - % I use some trigonometric identities to reduce the computations - Ss2wt = 2*cwt.'*swt; % \sum_t \sin(2\omega\t) - Sc2wt = (cwt-swt).'*(cwt+swt); % \sum_t \cos(2\omega\t) - wtau = 0.5*atan2(Ss2wt,Sc2wt); %\omega\tau - - swtau = sin(wtau); - cwtau = cos(wtau); - - % I use some trigonometric identities to reduce the computations - swttau = swt*cwtau - cwt*swtau; % \sin\omega(t-\tau)) - cwttau = cwt*cwtau + swt*swtau; % \cos\omega(t-\tau)) - - P(i) = ((x.'*cwttau)^2)/(cwttau.'*cwttau) + ((x.'*swttau)^2)/(swttau.'*swttau); -end -P = P/(2*vx); - -%% Significance -M = 2*nf/ofac; -alpha = 1 - (1-exp(-P)).^M; % statistical significance -alpha(alpha<0.1) = M*exp(-P(alpha<0.1)); % (to avoid round-off errors) - -%% Figure -if fig - figure - styles = {':','-.','--'}; - - a = [0.001 0.005 0.01 0.05 0.1 0.5]; - La = length(a); - z = -log(1-(1-a).^(1/M)); - hold on; - for i=1:La - line([f(1),0.87*f(end)],[z(i),z(i)],'Color','k','LineStyle',styles{ceil(i*3/La)}); - text(0.9*f(end),z(i),strcat('\alpha = ',num2str(a(i))),'fontsize',8); -% lgd{i}=strcat('\alpha=',num2str(a(i))); - end - if ~isempty(a_usr) - [tmp,ind] = intersect(a_usr,a); - a_usr(ind)=[]; - La_usr = length(a_usr); - z_usr = -log(1-(1-a_usr).^(1/M)); - for i = 1:La_usr - line([f(1),0.87*f(end)],[z_usr(i),z_usr(i)],'Color','r','LineStyle',styles{ceil(i*3/La_usr)}); - text(0.9*f(end),z_usr(i),strcat('\alpha = ',num2str(a_usr(i))),'fontsize',8); - % lgd{La+i}=strcat('\alpha=',num2str(a_usr(i))); - end - z = [z z_usr]; - end -% legend(lgd); - plot(f,P,'k'); - title('Lomb-Scargle normalized periodogram') - xlabel('f (Hz)'); ylabel('P(f)') - xlim([0 f(end)]); ylim([0,1.2*max([z'; P])]); - hold off; -end - -end - - -%% #### Local functions - -%% init (initialize) -function [x,t,hifac,ofac,a,f,fig] = init(x,t,varargin) - if nargin < 6, a = []; % set default value for a - else a = sort(varargin{4}); - a = a(:)'; - end - if nargin < 5, ofac = 4; % set default value for ofac - else ofac = varargin{3}; - end - if nargin < 4, hifac = 1; % set default value for hifac - else hifac = varargin{2}; - end - if nargin < 3, fig = 0; % set default value for hifac - else fig = varargin{1}; - end - - if isempty(ofac), ofac = 4; end - if isempty(hifac), hifac = 1; end - if isempty(fig), fig = 0; end - - if ~isvector(x) ||~isvector(t), - error('%s: inputs x and t must be vectors',mfilename); - else - x = x(:); t = t(:); - nt = length(t); - if length(x)~=nt - error('%s: Inputs x and t must have the same length',mfilename); - end - end - - [t,ind] = unique(t); % discard double entries and sort t - x = x(ind); - if length(x)~=nt, disp(sprintf('WARNING %s: Double entries have been eliminated',mfilename)); end - - T = t(end) - t(1); - nf = round(0.5*ofac*hifac*nt); - f = (1:nf)'/(T*ofac); -end diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/lomb_sim.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/lomb_sim.m deleted file mode 100755 index 6625a54..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/lomb_sim.m +++ /dev/null @@ -1,50 +0,0 @@ -t = 1:size(data.d); %10 minutes -% t = 1:8471552; %10 minutes -f = 1/55e4;%freq = 1/period -fs = 1e4; -A = 0.002; %amplitude ~2msec -% A = 1; -x = A *sin(2*pi*f*t); - -% plot(t,x) - -%USE CULLED IPI -%culled_ipi = ipiStatsLomb.culled_ipi; - -%USE RAW IPI -culled_ipi = ipi; -cx = x(culled_ipi.t); -ct = culled_ipi.t; - - -% plot(ct,cx,'.-') -% -% lomb(cx,ct./fs,1); - -%Now try adding variance to cx -SNR = .5; -% rmsrnd = sqrt(mean(randn(size(x,2),1).^2)); -% rmsx = sqrt(mean(x.^2)); - -stdx = std(culled_ipi.d./1e4); - -% noise = (1/.7088)*(rmsx/SNR) .* randn(size(cx,2),1); -noised = (1/.7088)*(stdx/SNR) .* randn(size(cx,2),1); - -% cy = cx+noise'; -cyd = cx+noised'; - -% plot(ct,cy,'.-') -% lomb(cy,ct./fs,1); - -plot(ct,cyd,'.-') -lomb(cyd,ct./fs,1); - -%%%%%%%%%%%%%%%%%%% -%check rmsq vs rmsrnd -% t = 1:size(data.d); %10 minutes -% f = 1/55e4;%freq = 1/period -% A = 1; -% x = A *sin(2*pi*f*t); -% rmsx = sqrt(mean(x.^2)) -% rmsrnd = sqrt(mean(randn(size(x,2),1).^2)) diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/phenotable_pulse.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/phenotable_pulse.m deleted file mode 100755 index 5c6852d..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/phenotable_pulse.m +++ /dev/null @@ -1,59 +0,0 @@ -function [phenotable] = phenotable_pulse(folder, names_file, output_file) - -%Read all the PS files produced by Process_wav_Song which are contained -%within a folder and builds an array with all the IPIs combined. - - -dir_list = dir(folder); -file_num = length(dir_list); -sep = filesep; - -fly_names = names_file; - - -%%%Add variables here -%k = 1; -phenotable = zeros(2,length(fly_names)); -%ind = []; - -for y = 1:file_num - file = dir_list(y).name; - [path,name,ext] = fileparts(file); - path_file = [folder sep file]; - TG = strcmp(ext,'.mat'); - if TG == 1 - fprintf(['Reading workspace from file %s.\n'], file) - load(path_file, 'ipiStatsLomb', 'ipi', 'pMFFT'); %Variables to be loaded - - %%%%%Add here whatever you want the code to do - - for i = 1:length(fly_names) - - parsed_filename = textscan(char(fly_names{i}(6:length(fly_names{i}))),'%s','Delimiter','_'); - ind_name = textscan(char(name), '%s', 'Delimiter', '_'); - - if (isequal(char(parsed_filename{1}(1)),char(ind_name{1}(2)))) == 1 - - %mean culled ipi - phenotable(1,i) = ipiStatsLomb.ipiStats.mu1./11; - - %kernel mode ipi.d - phenotable(2,i) = kernel_mode(ipi.d./11, 20:1:180); - - %kernel mode pMFFT - phenotable(3,i) = kernel_mode(pMFFT.freqAll, 1:0.01:1000); - - continue - end - end - - - - - - end - -end - - -tblwrite(phenotable', genvarname({'mu1', 'kernel_modes_ipi_d', 'kernel_modes_pMFFT'}), char(fly_names'), output_file, ','); diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/phenotable_sine.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/phenotable_sine.m deleted file mode 100755 index 85d195a..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/phenotable_sine.m +++ /dev/null @@ -1,58 +0,0 @@ -function [phenotable] = phenotable_sine(folder, names_file, output_file) - -%Read all the PS files produced by Process_wav_Song which are contained -%within a folder and builds an array with all the IPIs combined. - - -dir_list = dir(folder); -file_num = length(dir_list); -sep = filesep; - -fly_names = names_file; - - -%%%Add variables here -%k = 1; -phenotable = zeros(2,length(fly_names)); -%ind = []; - -for y = 1:file_num - file = dir_list(y).name; - [path,name,ext] = fileparts(file); - path_file = [folder sep file]; - TG = strcmp(ext,'.mat'); - if TG == 1 - fprintf(['Reading workspace from file %s.\n'], file) - load(path_file, 'maxFFT', 'winnowed_sine'); %Variables to be loaded - - %%%%%Add here whatever you want the code to do - - - for i = 1:length(fly_names) - - parsed_filename = textscan(char(fly_names{i}(6:length(fly_names{i}))),'%s','Delimiter','_'); - ind_name = textscan(char(name), '%s', 'Delimiter', '_'); - - if (isequal(char(parsed_filename{1}(1)),char(ind_name{1}(2)))) == 1 - - %maxFFT kernel mode - phenotable(1,i) = kernel_mode(maxFFT.freqAll, 140:0.01:250); - - %sine_traons_length - phenotable(2,i) = kernel_mode(winnowed_sine.stop./11 - winnowed_sine.start./11, 1:1:5000); - - continue - end - end - - - - - - end - -end - - -tblwrite(phenotable', genvarname({'sine_max_FFT_mode', 'sine_train_lengths'}), char(fly_names'), output_file, ','); - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/plotSineBoutAnalysis.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/plotSineBoutAnalysis.m deleted file mode 100755 index 6cb52b8..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/plotSineBoutAnalysis.m +++ /dev/null @@ -1,74 +0,0 @@ - -%toggle to use raw (1) or relative -raw = 0; - - -bins = 50; - -if raw == 1 - %for raw data - %for sine data -% xx = linspace(100,200,50); - %for pulse data - xx = linspace(100,350,50); - -else - %for relative to start - xx = linspace(-100,100,bins); -end - -size_bout = 8;%size(dTime,3); -% time = size(dTime,2); -time = 30; %Look at only first 20 time points in each sine -hold on -colormap cool - - -for i = 1:size_bout - - Z = zeros(time,bins); - M = zeros(time,1); - S = zeros(time,1); - for j = 1:time - if raw == 1 -% to plot raw - Z(j,:) = hist(dFreq(:,j,i),xx); - M(j) = nanmean(dFreq(:,j,i)); - S(j) = nanstd(dFreq(:,j,i)); - else -% to plot relative to starting freq - Z(j,:) = hist(dFreq(:,j,i)-dFreq(:,1,1),xx); - M(j) = nanmean(dFreq(:,j,i)-dFreq(:,1,1)); - S(j) = nanstd(dFreq(:,j,i)-dFreq(:,1,1)); - end - if i == 1 && j == 1 - line([1 time*size_bout],[M(1) M(1)],'Color',[.5 .5 .5]) - end - end - Z(Z == 0) = NaN; - - time_ax = (1:time) + (time * (i -1)); - - pcolor(time_ax,xx,log(Z')); - shading interp; - plot(time_ax,M,'k','LineWidth',2); - plot(time_ax,M+S,'k','LineWidth',1); - plot(time_ax,M-S,'k','LineWidth',1); - plot(time_ax(1),M(1),'or','MarkerFaceColor','r'); -end - - -set(gca,'XTick',time/2:time:time*size_bout-time/2) -set(gca,'XTickLabel',num2cell(1:size_bout)) -% xlabel('Sine train number in a single song bout','fontsize',14) -xlabel('Sine train number in a single song bout','fontsize',14); -if raw == 1 -% ylabel('Sine frequency (Hz)','fontsize',14) - ylabel('Sine frequency (Hz)','fontsize',14); -else -% ylabel('Sine frequency relative to initial frequency (Hz)','fontsize',14) - ylabel('Sine frequency relative to initial frequency (Hz)','fontsize',14); - -end -t = colorbar('peer',gca); -set(get(t,'ylabel'),'String','Log(N)'); diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/plotSineFreqvsTime.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/plotSineFreqvsTime.m deleted file mode 100755 index 2c9223e..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/plotSineFreqvsTime.m +++ /dev/null @@ -1,75 +0,0 @@ - -%toggle to use raw (1) or relative -raw = 1; - - -%get 2D arrays of time and Freq -numels = size(dTime,2) * size(dTime,3); -numbouts = size(dTime,1); -t = zeros(numbouts,numels); -f = t; - -for i = 1:numbouts - time = dTime(i,:,:); - time = reshape(time,numels,1); - t(i,:) = time'; - - freq = dFreq(i,:,:); - freq = reshape(freq,numels,1); - f(i,:) = freq'; -end - -startTimes = t(:,1); -rmst = repmat(startTimes,1,size(t,2)); -normT = t - rmst; - -%range of times -start = 0; -% stop = max(max(normT)); -%Too comp intensive to use all data, Use first 5 sec -stop = 5e4; - -steps = 1 + floor(stop / 500); - -bins = 50; - -xx = linspace(100,200,bins); - -Z = zeros(steps,bins); -M = zeros(steps,1); -S = M; -j = 0; - -for i = start:500:stop - j =j +1; - D = f(normT==i); - Z(j,:) = hist(D,xx); - M(j) = mean(D); - S(j) = std(D); -end - - - -time_ax = start:500:stop; -pcolor(time_ax,xx,log(Z')); - -colormap cool -shading flat -hold on -%plot mean -plot(time_ax,M,'k','LineWidth',2) -plot(time_ax,M+S,'k','LineWidth',1) -plot(time_ax,M-S,'k','LineWidth',1) - -% xlim([1 200]) -% ylim([60 200]) - -% plot(time_ax(1),M(1),'oc','MarkerFaceColor','c') -t = colorbar('peer',gca); -set(get(t,'ylabel'),'String','Log(N)'); - - -set(gca,'XTick',0:1e4:stop); -set(gca,'XTickLabel',num2cell(0:5)); -xlabel('Time from start of bout (sec)','fontsize',14); -ylabel('Sine frequency (Hz)','fontsize',14); diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/plot_distributions.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/plot_distributions.m deleted file mode 100755 index 07d8d0e..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/plot_distributions.m +++ /dev/null @@ -1,32 +0,0 @@ -function [plot_legends] = plot_distributions(Collect_file, file_names) - -%%Plot multiple overlaping distributions. - -plot_legends = cell(1,length(file_names)); -%colors -cc=lines(length(file_names)); -figure; -grid on; - -for i = 1:length(file_names) - [f, xi] = ksdensity(Collect_file.ipis{i}); - - parsed_filename = textscan(file_names{i},'%s','Delimiter','_'); - ch = strcat(parsed_filename{1}(2)); - ch2 = Collect_file.kmodes(i); - plot_legends(i) = strcat(ch, ' modes=', num2str(ch2)); - -hold on - -plot(xi,f,'color',cc(i,:)); - -end -legend(plot_legends); - - - - - - - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/plot_power_results.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/plot_power_results.m deleted file mode 100755 index 46f7a2d..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/plot_power_results.m +++ /dev/null @@ -1,12 +0,0 @@ -%plot power results - -all_alpha = zeros(20,75); -for i = 1:75 - all_alpha(:,i) = lsr.results{i}.best_alpha; -end - -power = zeros(20,1); -for i = 1:20 - power(i) = numel(find(all_alpha(i,:) < 0.05)) / 75; -end -plot(.1:.1:2,power) \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/regionalmax.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/regionalmax.m deleted file mode 100755 index cd7e936..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/regionalmax.m +++ /dev/null @@ -1,14 +0,0 @@ -function vals = regionalmax(x) - - idx = (x(2:end-1) > x(3:end)) & (x(2:end-1) > x(1:end-2)); - - firstValue = x(1) > x(2); - lastValue = x(end) > x(end-1); - - s = size(idx); - if s(2) > s(1) - vals = [firstValue idx lastValue]; - else - vals = [firstValue; idx; lastValue]; - end - \ No newline at end of file diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/sine2pulseAnalysis.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/sine2pulseAnalysis.m deleted file mode 100755 index d4f8ba9..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/sine2pulseAnalysis.m +++ /dev/null @@ -1,26 +0,0 @@ -%compare sine and pulse train lengths - -[file_names, SineStart,SineStop,sinemaxFFTfreq,sinemaxFFTtime,SINEFFTfreqall, SINEFFTtimesall,BoutsStart,BoutsStop] = Collect_sineMaxFFTFreq('/Users/sternd/Documents/Projects/courtship_song_analysis.w.t.-forpaper/WT_species/mel-all-6Mar/') -load('/Users/sternd/Documents/Projects/courtship_song_analysis.w.t.-forpaper/WT_species/mel-all-6Mar/_summary info/ipiStatsAll.mat') - -%calculate total sine duration for each individual - -for i = 1:75 - durations{i} = sum(SineStop{i} - SineStart{i}); -end -SineDuration = cell2mat(durations); - - -%calculate total pulse duration for each individual - -PulseDuration = zeros(1,75); -for i = 1:75 - numbouts = length(ipiStatsAll.TrainsT{i}); - temp = zeros(numbouts,1); - for ii = 1:numbouts - bout = cell2mat(ipiStatsAll.TrainsT{i}(ii)); - durationbout = bout(end) - bout(1); - temp(ii) = durationbout; - end - PulseDuration(i) = sum(temp); -end diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/sineSongAnalyze_multi.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/sineSongAnalyze_multi.m deleted file mode 100755 index 384940a..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/sineSongAnalyze_multi.m +++ /dev/null @@ -1,35 +0,0 @@ -function sineSongAnalyze_multi(folder) -% [poolavail,isOpen] = check_open_pool; -if strcmp(folder(end),'/') == 0 - folder = [folder '/']; -end -dir_list = dir(folder); -file_num = length(dir_list); - -for y = 1:file_num - file = dir_list(y).name; %pull out the file name - [~,root,ext] = fileparts(file); - path_file = [folder file]; - TG = strcmp(ext,'.mat'); - if TG == 1 - W = who('-file',path_file); - varstruc =struct; - load(path_file); - for ii = 1:numel(W) - varstruc.(W{ii}) = eval(W{ii}); - end - - fprintf([root '\n']); - %calc sine fund freq - maxFFT = sine_song_analyze2(winnowed_sine); - - varstruc.maxFFT = maxFFT; - - varstruc.sineLomb.variables.date = date; - varstruc.sineLomb.variables.time = clock; - save(path_file,'-struct','varstruc','-mat')%save all variables in original file - - end -end - -% check_close_pool(poolavail,isOpen); diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/sine_song_analyze2.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/sine_song_analyze2.m deleted file mode 100755 index 44309c8..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/sine_song_analyze2.m +++ /dev/null @@ -1,51 +0,0 @@ -function maxFFT = sine_song_analyze2(winnowed_sine) - -Fs = 10000; -nfft = 100000; -NumSine = size(winnowed_sine.clips,1); -maxFFTFreq = cell(NumSine,1); -maxFFTFreqTime = cell(NumSine,1); -% [poolavail,isOpen] = check_open_pool; -for i = 1:NumSine - ym = winnowed_sine.clips{i}; - boutStart = winnowed_sine.start(i); - r = length(ym); - sec = r/10000; - if r>1 - if sec < 0.1 - wnd = round(Fs*sec); - z = resample(ym,Fs,10000); - voltage=[]; - [Sn,F] = spectrogram(z,wnd,[],nfft,Fs); - a = find(F>80 & F<250); - freq2 = F(a); - voltage = abs(Sn(a,:)); - - [~,I] = max(voltage); %I = index of max of the signal between 80-250Hz - maxFFTFreq{i} = freq2(I); %the frequency with this index - maxFFTFreqTime{i} = boutStart; - - elseif sec > 0.1 - wnd = round(0.1*Fs); - z = resample(ym,Fs,10000); - voltage=[]; - [Sn,F] = spectrogram(z,wnd,[],nfft,Fs); - a = find(F>80 & F<250); - freq2 = F(a); - voltage = abs(Sn(a,:)); - - [~,I] = max(voltage); %I = index of max of the signal between 80-250Hz - maxFFTFreq{i} = freq2(I); %the frequency with this index - maxFFTFreqTime{i} = boutStart:500:boutStart+(500*length(I))-1; - end - end -end -maxFFTFreq = maxFFTFreq - - -maxFFT.freq = maxFFTFreq; -maxFFT.time = maxFFTFreqTime; -maxFFT.freqAll = cell2mat(maxFFTFreq); -maxFFT.timeAll = cell2mat(maxFFTFreqTime'); - - diff --git a/ANALYSIS CODE/FlySongAnalysisSuite-master/sine_song_lomb_sim.m b/ANALYSIS CODE/FlySongAnalysisSuite-master/sine_song_lomb_sim.m deleted file mode 100755 index a18eff5..0000000 --- a/ANALYSIS CODE/FlySongAnalysisSuite-master/sine_song_lomb_sim.m +++ /dev/null @@ -1,111 +0,0 @@ -% culled_ipi = ipiStatsLomb.culled_ipi; - -%%%Now loop through all mat files in folder and collect lomb_sim_results in -%%%for individuals - -% lsr.filename{ } = filename -% lsr.results{ } = lomb_sim_results; - - - -function lomb_sim_results = sine_song_lomb_sim(data,winnowed_sine) -%ippi = ipiStatsLomb.culled_ipi - - -fs = data.fs; -SNR = .1:.1:2; -d = cell(numel(SNR),1); -P = d; -f = d; -alpha = d; -best_alpha = zeros(numel(SNR),1); -best_P = best_alpha; -for i=1:numel(SNR) - [simData,Pow,freq,sign] = sine_song_sine_sim(data.d,winnowed_sine,fs,SNR(i)); - d{i} = simData; - P{i} = Pow; - f{i} = freq; - alpha{i} = sign; - best_alpha(i) = min(sign(freq > 0.18 & freq < 0.22)); - best_P(i) = max(Pow(freq > 0.18 & freq < 0.22)); -end - -lomb_sim_results.d = d; -lomb_sim_results.P = P; -lomb_sim_results.f = f; -lomb_sim_results.alpha = alpha; -lomb_sim_results.best_alpha = best_alpha; -lomb_sim_results.best_P = best_P; - - - -function [simData,P,f,alpha] = sine_song_sine_sim(d,winnowed_sine,fs,SNR) -t = 1:size(d); %10 minutes -f = 1/(5*fs);%freq = 1/period -% fs = 1e4; -A = 0.002; %amplitude ~2mV -% A = 1; -x = A *sin(2*pi*f*t); - -holding_cell = cell(1,length(winnowed_sine.start)); -for i = 1:length(winnowed_sine.start) - holding_cell{i} = winnowed_sine.start(i):100:winnowed_sine.stop(i); -end - -winnowed_sine_times =cell2mat(holding_cell); -% plot(t,x) - -% culled_ipi = ipi; -cx = x(winnowed_sine_times); -ct = winnowed_sine_times; -% plot(ct,cx,'.-') -% -% lomb(cx,ct./fs,1); - -%Now try adding variance to cx -% SNR = .4; -% rmsrnd = sqrt(mean(randn(size(x,2),1).^2)); -% rmsx = sqrt(mean(x.^2)); - -stdx = std(cell2mat(winnowed_sine.events)./fs); - -% noise = (1/.7088)*(rmsx/SNR) .* randn(size(cx,2),1); -noised = (1/.7088)*(stdx/SNR) .* randn(size(cx,2),1); - -% cy = cx+noise'; -cyd = cx+noised'; - -% plot(ct,cy,'.-') -% lomb(cy,ct./fs,1); - -% plot(ct,cyd,'.-') -[P,f,alpha] = lomb(cyd,ct./fs); -%don't plot -% [P,f,alpha] = lomb(cyd,ct./fs,1); -%get peaks -peaks = regionalmax(P); -%get f,alpha,Peaks for peaks < desired alpha -fPeaks = f(peaks); -alphaPeaks = alpha(peaks); - -alphaThresh = 0.05; - -signF = fPeaks(alphaPeaks < alphaThresh); -signAlpha = alphaPeaks(alphaPeaks 5000); - if isempty(splittrain); - maletrain{i}=[]; - femalewithmale{i}=[]; - all_pulses{i}=[]; - all_pulsebin{i}=[]; - else - maletrain{i}=NaN(length(splittrain)+1,50); - femalewithmale{i}=NaN(length(splittrain)+1,250); - all_pulses{i}=NaN(length(splittrain)+1,300); - all_pulsesbin{i}=NaN(length(splittrain)+1,300); - - tr1=malebouts_start(1:splittrain(1)); - trend=malebouts_start(splittrain(end)+1:end); - maletrain{i}(1,1:length(tr1))=tr1; - g=2; - for p=1:length(splittrain)-1; -tr=malebouts_start(splittrain(p)+1:splittrain(p+1)); -if length(tr)~=1; -maletrain{i}(g,1:length(tr))=tr; -g=g+1; -end - end - end - - if ~isempty(maletrain{i}) -maletrain{i}(g,1:length(trend))=trend; - -%find duetting sections -for n=1:sum(~isnan(maletrain{i}(:,1))); - maletrainregion=maletrain{i}(n,find(~isnan(maletrain{i}(n,:)))); - femalewith=femaletimes{i}(find(femaletimes{i}>(maletrainregion(1,1)-1000) & femaletimes{i}<(maletrainregion(1,end)+1000))); - if ~isempty(femalewith) - femalewithmale{i}(n, 1:length(femalewith))=femalewith; - end -end - - %categorize exhanges - for n=1:sum(~isnan(maletrain{i}(:,1))); - if sum(~isnan(maletrain{i}(n,:)))>1 & sum(~isnan(femalewithmale{i}(n,:)))>1 - tmppulse=horzcat(maletrain{i}(n,find(~isnan(maletrain{i}(n,:)))), femalewithmale{i}(n,find(~isnan(femalewithmale{i}(n,:))))); -all_pulses{i}(n,1:length(tmppulse))=sort(tmppulse, 'ascend'); -for h=1:length(tmppulse); -if ~isempty(find(maletimes{i}==all_pulses{i}(n,h))) - all_pulsesbin{i}(n,h)=0; -else - all_pulsesbin{i}(n,h)=1; -end -end -if sum(diff(all_pulsesbin{i}(n,:)))<=3 - all_pulsesbin{i}(n,:)=NaN; -end - end - end - - - if sum(~isnan(all_pulsesbin{i}(:,1)))>=3 -duet_start_malepercent(1,i)= nansum(all_pulsesbin{i}(:,1))/sum(~isnan(all_pulsesbin{i}(:,1))); -duet_start_malepercent(2,i)= sum(~isnan(all_pulsesbin{i}(:,1))); - end - end -end -end - diff --git a/ANALYSIS CODE/malemaleRT.m b/ANALYSIS CODE/malemaleRT.m deleted file mode 100644 index bfef686..0000000 --- a/ANALYSIS CODE/malemaleRT.m +++ /dev/null @@ -1,105 +0,0 @@ -function [ MMRT, MMRTM1perm, MMRTM2perm ] = malemaleRT( male1times, male2times , channels) -%UNTITLED Summary of this function goes here -% Detailed explanation goes here - -% load(file, 'MIPI1', 'MIPI2'); - - -for i=1:channels; - male1pulses=male1times{i}; - male2pulses=male2times{i}; - -% male1pulses= MIPI1(:,1)==channels(i); -% -% male2pulses= MIPI2(:,1)==channels(i); -% male2times{i}=male2pulses; -% male1pulses=sort(MIPI1(male1pulses,2),'ascend'); -% male2pulses=sort(MIPI2(male2pulses,2),'ascend'); -% male1times{i}=male1pulses; -% male2times{i}=male2pulses; - - %%for full bout annotations -% maleIBI=diff(male1pulses)'; -% if ~isempty(male1pulses) && ~isempty(male2pulses) -% %split male starts into trains -% splittrain=find(maleIBI>100); -% if ~isempty(splittrain); -% malebout=NaN(length(splittrain)+1,50); -% tr1=male1pulses(1:splittrain(1)); -% trend=male1pulses(splittrain(end)+1:end); -% malebout(1,1:length(tr1))=tr1; -% g=2; -% for p=1:length(splittrain)-1; -% tr=male1pulses(splittrain(p)+1:splittrain(p+1)); -% if length(tr)~=1; -% malebout(g,1:length(tr))=tr; -% g=g+1; -% end -% end -% malebout(g,1:length(trend))=trend; -% -% end - -% k=1; -% for n=1:(size(malebout(:,1))-1); -% malebout_start=round(malebout(n,1)); -% malebout_nextstart=round(malebout(n+1,1)); -% next_male2=find(male2pulses>malebout_start & male2pulsesmalebout_start,1,'first'); -if isempty(next_male2) || isempty(find((round(male2pulses(next_male2))-malebout_start)<1500)) - continue - else - MMRT{i}(1,k)=round(male2pulses(next_male2))-malebout_start; - k=k+1; - end - end - - %% randomize - diff1=diff(male1pulses); - diff2=diff(male2pulses); - diff1len = randperm(length(diff1)); - diff2len = randperm(length(diff2));%shuffling IPIs - male1_perm = cumsum(diff1(diff1len)); - male2_perm = cumsum(diff2(diff2len)); - -k=1; % male2 perm - for n=1:(length(male1pulses)-1); - malebout_start=round(male1pulses(n,1)); - - next_male2=find(male2_perm>malebout_start,1,'first'); -if isempty(next_male2) || isempty(find((round(male2_perm(next_male2))-malebout_start)<1500)) - continue - else - MMRTM1perm{i}(1,k)=round(male2_perm(next_male2))-malebout_start; - k=k+1; - end - end - - k=1; % male1 perm - for n=1:(length(male1_perm)-1); - malebout_start=round(male1_perm(n,1)); - - next_male2=find(male2pulses>malebout_start,1,'first'); -if isempty(next_male2) || isempty(find((round(male2pulses(next_male2))-malebout_start)<1500)) - continue - else - MMRTM2perm{i}(1,k)=round(male2pulses(next_male2))-malebout_start; - k=k+1; - end - end -end - - diff --git a/ANALYSIS CODE/overlaps_fPPM.m b/ANALYSIS CODE/overlaps_fPPM.m deleted file mode 100644 index 91dee54..0000000 --- a/ANALYSIS CODE/overlaps_fPPM.m +++ /dev/null @@ -1,30 +0,0 @@ -function [ norm_overlaps,norm_fPPM ] = overlaps_fPPM( file , channels) -%UNTITLED Summary of this function goes here -% Detailed explanation goes here -load(file, 'FPULSE', 'MPULSE','OVERLAP'); -channel_num=length(channels); - norm_overlaps=cell(channel_num,1); - norm_fPPM=cell(channel_num,1); - - - for i=1:channel_num; - - femalepulses= FPULSE(:,1)==channels(i); - femalepulses=sort(FPULSE(femalepulses,2),'ascend'); - - malebouts=MPULSE(:,1)==channels(i); - malebouts_start=sort(MPULSE(malebouts,2),'ascend'); - malebouts_stop=sort(MPULSE(malebouts,3),'ascend'); - malebouts=horzcat(malebouts_start,malebouts_stop); - - overlaps=OVERLAP(:,1)==channels(i); - overlaps=sort(OVERLAP(overlaps,2),'ascend'); - - norm_overlaps{i}=length(overlaps)/length(malebouts(:,1)); - norm_fPPM{i}=length(femalepulses)/(round(max(femalepulses))-round(min(femalepulses))); - - - - -end - diff --git a/ANALYSIS CODE/permutresponse.m b/ANALYSIS CODE/permutresponse.m deleted file mode 100644 index 61fa884..0000000 --- a/ANALYSIS CODE/permutresponse.m +++ /dev/null @@ -1,44 +0,0 @@ -function [ female_response_time_final] = permutresponse( file, numperms ) -%UNTITLED Summary of this function goes here -% Detailed explanation goes here - - load(file, 'femaleBoutInfo', 'femaleBoutInfo_no_overlap','maleBoutInfo', 'run_data'); - femalepulses=femaleBoutInfo.wMax; - %femalepulses= femaleBoutInfo_no_overlap; - femaleIPI=diff(femalepulses); -%female_response_time_final= NaN(numperms,length(femalepulses)); -female_response_time = []; - for i=1;%:numperms; -% %femalepulses_perm = max(femalepulses)*rand(length(femalepulses),1); -% femaleIPI_perm = randperm(length(femaleIPI)); %shuffling IPIs -% femalepulses_perm = cumsum(femaleIPI(femaleIPI_perm)); - r=1; - for n=1:length(femalepulses); - if n==1; - continue - end - A=femalepulses(n); %female bout center - AA=femalepulses(n-1); %previous female bout center - - B = find(maleBoutInfo.wc < A & maleBoutInfo.wc > AA); %find the male bout between these two female pulses (if there is one) - C = isempty(B); - if C == 0; %if B is not empty - m = length(B); - mm = B(m); %take the last male bout from the ones found - this would be the one closest to the female pulse, A - zz=find(run_data.pulseInfo.wc>maleBoutInfo.w0(mm) & run_data.pulseInfo.wcround(malebouts(u-1,2)),trigger, 'last'); - if malebouts(u,1)-malebouts(u-1,1)<5000; - if ~isempty(find(femalepulsesround(malebouts(u-1,2)))); - FPPB(i,u)= length(find(femalepulsesround(malebouts(u-1,2)))); - else FPPB(i,u)=NaN; - end - else FPPB(i,u)=NaN; - end - - if isempty(dd) - continue - else - if length(dd)>=trigger - w=d-femalepulses(dd(trigger,1)); - if w<1500; - mrt{i}(h,1)=w; - h=h+1; - end - end - end - end - - j=1; - for n=1:length(malebouts(:,1))-1; %female response time - male_start=round(malebouts(n,1)+210); - male_nextstart=round(malebouts(n+1,1)); - next_female=find(femalepulses>male_start & femalepulsesmale_start & femalepulses_permround(malebouts(u-1,2)),trigger, 'last'); - if isempty(dd) - continue - else - if length(dd)>=trigger; - w=d-femalepulses_perm(dd(trigger,1)); - if w<1500; - mrt_Fperm{i}(h,1)=w; - h=h+1; - end - end - - end - end - -% k=1; -% for t=1:length(malebouts); -% a=round(malebouts(t,1)); -% aa=round(malebouts(t,2)); -% x=find(femalepulses_perm<(aa+2000)& femalepulses_perm>aa); -% xx= find(femalepulses_perm>(a-2000)& femalepulses_permmale_start & femalepulsesround(malebouts_perm(u-1)) & femalepulses=trigger; - w=d-femalepulses(dd(trigger,1)); - if w<1500; - mrt_Mperm{i}(h,1)=w; - h=h+1; - end - end - end - end - -end - end - end - end -frt_Fperm_total=cell2mat(frt_Fperm); -frt_Fperm_total=frt_Fperm_total(:); -a=~isnan(frt_Fperm_total); -frt_Fperm_total=frt_Fperm_total(a); -frt_Mperm_total=cell2mat(frt_Mperm); -frt_Mperm_total=frt_Mperm_total(:); -b=~isnan(frt_Mperm_total); -frt_Mperm_total=frt_Mperm_total(b); -mrt_Fperm_total=cell2mat(mrt_Fperm); -mrt_Fperm_total=mrt_Fperm_total(:); -c=~isnan(mrt_Fperm_total); -mrt_Fperm_total=mrt_Fperm_total(c); -mrt_Mperm_total=cell2mat(mrt_Mperm); -mrt_Mperm_total=mrt_Mperm_total(:); -d=~isnan(mrt_Mperm_total); -mrt_Mperm_total=mrt_Mperm_total(d); -mrt=cell2mat(mrt); -frt=cell2mat(frt'); - -% femaletimes_perm_total=cell2mat(femaletimes_perm); -% femaletimes_perm_total=femaletimes_perm_total(:); - - - diff --git a/Ground Truthing Code/GROUND_TRUTHINGv2.m b/Ground Truthing Code/GROUND_TRUTHINGv2.m deleted file mode 100644 index aa6f095..0000000 --- a/Ground Truthing Code/GROUND_TRUTHINGv2.m +++ /dev/null @@ -1,382 +0,0 @@ -function GROUND_TRUTHINGv2(RR,PULSE) - -%take hand segmented data (from 5-6min of songs: 9 different songs; -%PULSE times and SINE starts and stops are in ms (relative to the start of the full song)) -%compare to pulseInfo2 (following heuristic winnow), pulseInfo, -%culled_pulseInfo_1 (pulse model winnow on pulseInfo) and culled_pulseInfo (pulse model winnow on -%pulseInfo2) - -%the comparison should transform the pulse times or sine times into a -%smoothed vector of ones and zeros - then use various metrics to look at relationships. Some sort of smoothing is critical -%because the exact pulse and sine times won't be the same for hand -%segmentation versus automated.... - -%% - -for RR=RR - - if RR==1; %each hand annotated workspace contains both the hand segmeneted data and the automated data (including following culling with the pulse model) - load('PS_ch1.mat'); - elseif RR==2; - load('PS_ch2.mat'); - elseif RR==3; - load('PS_ch3.mat'); - elseif RR==4; - load('PS_ch4.mat'); - elseif RR==5; - load('PS_ch5.mat'); - elseif RR==6; - load('PS_ch6.mat'); - elseif RR==7; - load('PS_ch7.mat'); - elseif RR==8; - load('PS_ch8.mat'); - elseif RR==9; - load('PS_ch9.mat'); - elseif RR==10; - load('PS_ch10.mat'); - end -%% - -RR - -% addpath('/Users/malamurthy/Desktop/OLD_FlySongSegmenter/FlySongAnalysisSuite'); - -%Guassian filter: -Fs=10000; -effwidth = 20; -efftk = -3*effwidth:3*effwidth ; -effkernel = (exp(-(efftk/effwidth).^2/2)/(effwidth*sqrt(2*pi))); -halfWidth=(numel(efftk)/2); - -%first make a spike train out of the SINE and PULSE information: -leng = length(run_data.likelihoods); - - -vector_manual = zeros(1,leng); -vector_manual = vector_manual + 0.1; -%vector_manual_sine = vector_manual_pulse; -ch=PULSE(:,1)==RR; -ch=PULSE(ch,2); -ch= round(ch.*Fs/1000); %to get data back into points from ms (there is only data between 5-6min) -B = ch'; -IPI = (diff(B)); %in points -index = find(IPI < 1000 & IPI > 0); -meanIPI = mean(IPI(index)); %mean IPI -modeIPI = mode(IPI(index)); %mode IPI -varIPI = var(IPI(index)); %variance IPI -stdIPI = std(IPI(index)); %standard deviation IPI -h=figure(11); hist(IPI(index),100); title('IPI histogram'); -name = ['female_IPI_hist_manual_' int2str(RR) '.fig']; -saveas(h,name); - -ipi_byhand = fit_ipi_model(B,2); %guassian mixture model - fit to IPI distribution -%[ipiStats_byhand lombStats_byhand culled_ipi_byhand] = cullIPILomb(ipi_byhand); - -% SINE(:,2) = round(SINE(:,2).*Fs/1000); -% SINE(:,3) = round(SINE(:,3).*Fs/1000); - -for i=1:length(B); %for each pulse - a = round(B(i)); - vector_manual(1,a) = 1; %put a 1 where each pulse peak is -end - -% sine_song_lengths = []; -% -% n=1; -% for i=1:length(SINE(:,2)); %for each sine -% a = SINE(i,2); -% b = SINE(i,3); -% vector_manual_sine(a:b) = ones; %put a 1 where each sine song is -% sine_song_lengths(n) = length(vector_manual_sine(a:b)); %collect sine song lengths -% n=n+1; -% end - -x=vector_manual; %get rid of the zeros outside 5-6min of data -%y=vector_manual_sine(3000001:3600000); - -vector_manual_pulse_guass = conv(x,effkernel); %convolve with the guassian kernel -VMPG=vector_manual_pulse_guass(halfWidth:end-halfWidth); -% vector_manual_sine_guass = conv(y,effkernel); -% VMSG = vector_manual_sine_guass(halfWidth:end-halfWidth); - -%% -%Now create a vector of 0.1s and ones for pulseInfo: - - -vector_comp1_pulse = zeros(1,leng); -vector_comp1_pulse = vector_comp1_pulse + 0.1; - -for n=1:numel(femaleBoutInfo.wMax); %n=1:numel(maleBoutInfo.wc); %for each pulse -% A=maleBoutInfo.w0(n); %male bout center -% AA=maleBoutInfo.w1(n); %previous male bout center -% zz=find(run_data.pulseInfo.wc>A & run_data.pulseInfo.wc 3000000 && winnowed_sine.stop(i) < 3600001; -% sine_song_lengths_comp(n) = length(vector_comp_sine(a:b)); -% n=n+1; -% end -% end -% -% %find IPIs: -% B=[]; -% B = pulseInfo2.wc; %times for pulse peaks -% A=[]; -% A = find(B>3000000 & B<3600001); -% C=[]; -% C = B(A); -% IPI=[]; -% IPI = (diff(C)); %in points -% index = find(IPI < 1000); -% meanIPI_pulseInfo2 = mean(IPI(index)); %mean IPI -% modeIPI_pulseInfo2 = mode(IPI(index)); -% varIPI_pulseInfo2 = var(IPI(index)); -% stdIPI_pulseInfo2 = std(IPI(index)); %standard deviation -% %f=figure(13); hist(IPI(index),100); title('IPI histogram pulseInfo2'); -% %saveas(g,'IPI_hist_pulseInfo2.fig'); -% -% ipi_pulseInfo2 = fit_ipi_model(C,2); -% %[ipiStats_pulseInfo2 lombStats_pulseInfo2 culled_ipi_pulseInfo2] = cullIPILomb(ipi_pulseInfo2); -% -% x=vector_comp_pulse(3000001:3600000); -% y=vector_comp_sine(3000001:3600000); -% -% vector_comp_pulse_guass = conv(x,effkernel); -% VCPG=vector_comp_pulse_guass(halfWidth:end-halfWidth); -% vector_comp_sine_guass = conv(y,effkernel); -% VCSG = vector_comp_sine_guass(halfWidth:end-halfWidth); -% -% %% -% %run culled pulses - then take out the pulses from there: -% -% folder = '/Users/malamurthy/Desktop/FLY SONG SEGMENTATION/CS-Tully hand segmeneted/keep 2'; -% pulse_model = '/Users/malamurthy/Desktop/FlySongWMTSegment' -% -% addpath('/Users/malamurthy/Desktop/FlySongWMTSegment'); -% -% Z_2_pulse_model_multi(folder,'pulseInfo2','/Users/malamurthy/Desktop/FlySongWMTSegment/mel_pm_24ii12.mat'); -% cull_pulses_multi(folder,'pulseInfo2','Lik_pulse','LLR_fh',0); - -%% -% %Now create a vector of 0.1s and ones for culled_pulseInfo2: -% leng = length(xsongsegment); -% -% vector_culled_pulse2 = zeros(1,leng); -% vector_culled_pulse2 = vector_culled_pulse2 + 0.1; -% -% for i=1:numel(culled_pulseInfo2.wc); %for each pulse -% a = culled_pulseInfo2.wc(i); -% vector_culled_pulse2(a) = 1; -% end -% -% %find IPIs: -% B=[]; -% B = culled_pulseInfo2.wc; %times for pulse peaks -% A=[]; -% C=[]; -% A = find(B>3000000 & B<3600001); -% C = B(A); -% IPI=[]; -% IPI = (diff(C)); %in points -% index = find(IPI < 1000); -% meanIPI_culled_pulseInfo2 = mean(IPI(index)); %mean IPI -% modeIPI_culled_pulseInfo2 = mode(IPI(index)); -% varIPI_culled_pulseInfo2 = var(IPI(index)); -% stdIPI_culled_pulseInfo2 = std(IPI(index)); %standard deviation -% g=figure(12); hist(IPI(index),100); title('IPI histogram culled_pulseInfo2'); -% name = ['IPI_hist_culled_pulseInfo2_' int2str(RR) '.fig']; -% saveas(g,name); -% -% ipi_culled_pulseInfo2 = fit_ipi_model(C,2); -% %[ipiStats_culled_pulseInfo2 lombStats__culled_pulseInfo2 culled_ipi_culled_pulseInfo2] = cullIPILomb(ipi_culled_pulseInfo2); -% -% x=[]; -% x=vector_culled_pulse2(3000001:3600000); -% -% vector_culled_pulse2_guass = conv(x,effkernel); -% VCuP2G=vector_culled_pulse2_guass(halfWidth:end-halfWidth); -% -% %% -% %Now create a vector of 0.1s and ones for culled_pulseInfo: -% leng = length(xsongsegment); -% -% vector_culled_pulse = zeros(1,leng); -% vector_culled_pulse = vector_culled_pulse + 0.1; -% -% for i=1:numel(culled_pulseInfo.wc); %for each pulse -% a = culled_pulseInfo.wc(i); -% vector_culled_pulse(a) = 1; -% end -% -% %find IPIs: -% B=[]; -% B = culled_pulseInfo.wc; %times for pulse peaks -% A=[]; -% C=[]; -% A = find(B>3000000 & B<3600001); -% C = B(A); -% IPI=[]; -% IPI = (diff(C)); %in points -% index = find(IPI < 1000); -% meanIPI_culled_pulseInfo = mean(IPI(index)); %mean IPI -% modeIPI_culled_pulseInfo = mode(IPI(index)); -% varIPI_culled_pulseInfo = var(IPI(index)); -% stdIPI_culled_pulseInfo = std(IPI(index)); %standard deviation -% -% ipi_culled_pulseInfo = fit_ipi_model(C,2); -% %[ipiStats_culled_pulseInfo lombStats__culled_pulseInfo culled_ipi_culled_pulseInfo] = cullIPILomb(ipi_culled_pulseInfo); -% -% x=[]; -% x=vector_culled_pulse(3000001:3600000); -% -% vector_culled_pulse_guass = conv(x,effkernel); -% VCuPG=vector_culled_pulse_guass(halfWidth:end-halfWidth); -%% -% pulse_cu2 = xcorr(VMPG,VCuP2G,100,'coeff'); %with maxlags of 100 points %culled_pulseInfo2 -% pulse_cu = xcorr(VMPG,VCuPG,100,'coeff'); %with maxlags of 100 points %culled_pulseInfo -% pulse_c = xcorr(VMPG,VCPG,100,'coeff'); %with maxlags of 100 points %pulseInfo2 -% pulse_c1 = xcorr(VMPG,VC1PG,100,'coeff'); %pulseInfo -% sine_c = xcorr(VMSG,VCSG,100,'coeff'); - -%% -%Need to find the points that VMPG and other vectors (VCuP2G, VCPG, VCuPG, -%and VC1PG) have in common: - -%The peaks in VMPG are the "trues" - the true pulses found by hand segmentation - -%for each vector, get rid of the first 80 and last 80 points, and jitter VMPG (by 45pts) relative to the other vectors -%(the jitter is done because we don't want any peaks in VMPG to PERFECTLY overlap with the peaks in the other vectors) - the code here is looking for interesections between the two vectors: -VMPG = VMPG(81:end-80); -% VCPG = VCPG(81:end-80); -VC1PG = VC1PG(81:end-80); -% VCuP2G = VCuP2G(81:599920); -% VCuPG = VCuPG(81:599920); - -%vector for the timepoints -t=1:leng-160; - -%now use curveintersect.m to find the points where the vectors intersect: -% [VCPGi,VCPGv] = curveintersect(t,VMPG,t,VCPG); %i=indices, v=values -[VC1PGi,VC1PGv] = curveintersect(t,VMPG,t,VC1PG); -% [VCuP2Gi,VCuP2Gv] = curveintersect(t,VMPG,t,VCuP2G); -% [VCuPGi,VCuPGv] = curveintersect(t,VMPG,t,VCuPG); - -%the intersections should be greater than 0.1 (see above, all of the vectors have 0.1 as their min value) - the length of this vector provides the value of -%"trues_found" - that is the pulses that were found by each algorithm that -%are ALSO in "trues" -% Ca=find(VCPGv>0.1); -C1a=find(VC1PGv>0.1); -aa=find(diff(C1a)~=1); -C1a=C1a(aa); -% Cu2a=find(VCuP2Gv>0.1); -% Cua=find(VCuPGv>0.1); - -%for deugging: verify that the correct peaks were found: -g=figure(1); plot(VMPG(1:length(VC1PGi)), 'k'); hold on; plot(VC1PG(1:length(VC1PGi)),'r'); -hold on; plot(VC1PGi(C1a),0.11,'.b'); -title('female_intersection'); -name = ['female_intersection' int2str(RR) '.fig']; -saveas(g,name); -close(g) -%figure; plot(t(1:length(VC1PGv)),VMPG(1:length(VC1PGv)),'k',t(1:length(VC1PGv)),VC1PGv','r') -% hold on -% plot(VCuP2Gi(Cu2a),0.12,'.m'); - -%to get the number of pulses from each original vector, use findpeaks: -VMPG_peaks = findpeaks(VMPG,'minpeakheight',0.1); -% VCPG_peaks = findpeaks(VCPG,'minpeakheight',0.1); -VC1PG_peaks = findpeaks(VC1PG,'minpeakheight',0.1); -% VCuP2G_peaks = findpeaks(VCuP2G,'minpeakheight',0.1); -% VCuPG_peaks = findpeaks(VCuPG,'minpeakheight',0.1); - -%Now I can calculate false positive and negative rates: -%sensitivity(sen) = trues_found/trues -%positive predictive value(ppv) = trues_found/found -%F=2*sen*ppv/(sen+ppv) - -% VCPG_sen = length(Ca)/length(VMPG_peaks); -VC1PG_sen = length(C1a)/length(VMPG_peaks); -% VCuP2G_sen = length(Cu2a)/length(VMPG_peaks); -% VCuPG_sen = length(Cua)/length(VMPG_peaks); - -% VCPG_ppv = length(Ca)/length(VCPG_peaks); -VC1PG_ppv = length(C1a)/length(VC1PG_peaks); -% VCuP2G_ppv = length(Cu2a)/length(VCuP2G_peaks); -% VCuPG_ppv = length(Cua)/length(VCuPG_peaks); - -% FC = (2*VCPG_sen*VCPG_ppv)/(VCPG_sen+VCPG_ppv); -FC1 = (2*VC1PG_sen*VC1PG_ppv)/(VC1PG_sen+VC1PG_ppv); -% FCu2 = (2*VCuP2G_sen*VCuP2G_ppv)/(VCuP2G_sen+VCuP2G_ppv); -% FCu = (2*VCuPG_sen*VCuPG_ppv)/(VCuPG_sen+VCuPG_ppv); - -%% - -t=1:1:leng; - -%compute times of pulses: -tSpike1 = t(find(vector_manual>0.1)); %will find just pulses -% tSpike2 = t(find(vector_comp_pulse(3000001:3600000)>0.1)); %pulseInfo2 -tSpike3 = t(find(vector_comp1_pulse>0.1)); %pulseInfo -% tSpike4 = t(find(vector_culled_pulse2(3000001:3600000)>0.1)); %culled pulseInfo2 -% tSpike5 = t(find(vector_culled_pulse(3000001:3600000)>0.1)); %culled pulseInfo -% DIFF = (length(tSpike1)-length(tSpike2))./length(tSpike1); %fraction not found (or false negative or positive rate) -DIFF2 = (length(tSpike1)-length(tSpike3))./length(tSpike1); -% DIFF3 = (length(tSpike1)-length(tSpike4))./length(tSpike1); -% DIFF4 = (length(tSpike1)-length(tSpike5))./length(tSpike1); - -name = ['female_workspace_' int2str(RR) '.mat']; -save(name); - - -end - - diff --git a/Ground Truthing Code/GROUND_TRUTHINGv3.m b/Ground Truthing Code/GROUND_TRUTHINGv3.m deleted file mode 100644 index 3310a59..0000000 --- a/Ground Truthing Code/GROUND_TRUTHINGv3.m +++ /dev/null @@ -1,224 +0,0 @@ -function [FALSENEGF, FALSENEGM, FALSEPOSF, FALSEPOSM]=GROUND_TRUTHINGv3(RR,FPULSE, MPULSE); - -%take hand segmented data (from 5-6min of songs: 9 different songs; -%PULSE times and SINE starts and stops are in ms (relative to the start of the full song)) -%compare to pulseInfo2 (following heuristic winnow), pulseInfo, -%culled_pulseInfo_1 (pulse model winnow on pulseInfo) and culled_pulseInfo (pulse model winnow on -%pulseInfo2) - -%the comparison should transform the pulse times or sine times into a -%smoothed vector of ones and zeros - then use various metrics to look at relationships. Some sort of smoothing is critical -%because the exact pulse and sine times won't be the same for hand -%segmentation versus automated.... - -%% - -for RR=RR - - if RR==1; %each hand annotated workspace contains both the hand segmeneted data and the automated data (including following culling with the pulse model) - load('PS_ch1.mat', 'femaleBoutInfo'); - load('PS_ch1.mat', 'run_data'); - load('PS_ch1.mat', 'maleBoutInfo'); - elseif RR==2; - load('PS_ch2.mat', 'femaleBoutInfo'); - load('PS_ch2.mat', 'run_data'); - load('PS_ch2.mat', 'maleBoutInfo'); - elseif RR==3; - load('PS_ch3.mat', 'femaleBoutInfo'); - load('PS_ch3.mat', 'run_data'); - load('PS_ch3.mat', 'maleBoutInfo'); - elseif RR==4; - load('PS_ch4.mat', 'femaleBoutInfo'); - load('PS_ch4.mat', 'run_data'); - load('PS_ch4.mat', 'maleBoutInfo'); - elseif RR==5; - load('PS_ch5.mat', 'femaleBoutInfo'); - load('PS_ch5.mat', 'run_data'); - load('PS_ch5.mat', 'maleBoutInfo'); - elseif RR==6; - load('PS_ch6.mat', 'femaleBoutInfo'); - load('PS_ch6.mat', 'run_data'); - load('PS_ch6.mat', 'maleBoutInfo'); - elseif RR==7; - load('PS_ch7.mat', 'femaleBoutInfo'); - load('PS_ch7.mat', 'run_data'); - load('PS_ch7.mat', 'maleBoutInfo'); - elseif RR==8; - load('PS_ch8.mat', 'femaleBoutInfo'); - load('PS_ch8.mat', 'run_data'); - load('PS_ch8.mat', 'maleBoutInfo'); - elseif RR==9; - load('PS_ch9.mat', 'femaleBoutInfo'); - load('PS_ch9.mat', 'run_data'); - load('PS_ch9.mat', 'maleBoutInfo'); - elseif RR==10; - load('PS_ch10.mat', 'femaleBoutInfo'); - load('PS_ch10.mat', 'run_data'); - load('PS_ch10.mat', 'maleBoutInfo'); - elseif RR==13; - load('PS_ch13.mat', 'femaleBoutInfo'); - load('PS_ch13.mat', 'run_data'); - load('PS_ch13.mat', 'maleBoutInfo'); - end -%% manual female pulses - -RR - -Fs=10000; - -Fch=FPULSE(:,1)==RR; -Fch=FPULSE(Fch,2); -Fch= round(Fch.*Fs/1000)'; %to get data back into points from ms -FEMALE = sort(Fch, 'ascend'); -if ~isempty(run_data.stoptime); -FEMALE=FEMALE(find(FEMALE 0); -meanIPIf = mean(IPI_f(index)); %mean IPI -medianIPIf = median(IPI_f(index)); %mode IPI -varIPIf = var(IPI_f(index)); %variance IPI -stdIPIf = std(IPI_f(index)); %standard deviation IPI -IPI_female=struct('IPI_f', IPI_f,'meanIPIf',meanIPIf,'medianIPIf',medianIPIf,'varIPIf',varIPIf,'stdIPIf',stdIPIf); -h=figure(1); hist(IPI_f(index),100); title('female IPI histogram manual'); -name = ['female_IPI_hist_manual_' int2str(RR) '.fig']; -saveas(h,name); - - -%% manual male pulses - -Mch=MPULSE(:,1)==RR; -Mch=MPULSE(Mch,2); -Mch= round(Mch.*Fs/1000)'; %to get data back into points from ms -MALE = sort(Mch, 'ascend'); -if ~isempty(run_data.stoptime); -MALE=MALE(find(MALE 0); -meanIPIm = mean(IPI_m(index)); %mean IPI -medianIPIm = median(IPI_m(index)); %mode IPI -varIPIm = var(IPI_m(index)); %variance IPI -stdIPIm = std(IPI_m(index)); %standard deviation IPI -IPI_male=struct('IPI_m', IPI_m,'meanIPIm',meanIPIm,'medianIPIm',medianIPIm,'varIPIm',varIPIm,'stdIPIm',stdIPIm); -h=figure(2); hist(IPI_m(index),100); title('male IPI histogram manual'); -name = ['male_IPI_hist_manual_' int2str(RR) '.fig']; -saveas(h,name); - -%% automated female pulses - -AUTOFEMALE = femaleBoutInfo.wMax; -if ~isempty(run_data.stoptime); -AUTOFEMALE=AUTOFEMALE(find(AUTOFEMALEA & run_data.pulseInfo.wc a - interval; - c = find(b); - if isempty(c); - falsenegf(z) = 1; - end -end -falsenegf=find(falsenegf); -FALSENEGF = length(falsenegf)/length(FEMALE); - - -%false positive - for z=1:length(AUTOFEMALE); - a=AUTOFEMALE(z); - b = FEMALE < a + interval & FEMALE > a - interval; - c = find(b); - if isempty(c); - falseposf(z) = 1; - end - end - falseposf=find(falseposf); -FALSEPOSF = length(falseposf)/length(AUTOFEMALE); - -%% male ground truthing - -%false negative -for z=1:length(MALE); - a=MALE(z); - b = AUTOMALE < a + interval & AUTOMALE > a - interval; - c = find(b); - if isempty(c); - falsenegm(z) = 1; - - end -end -falsenegm=find(falsenegm); -FALSENEGM = length(falsenegm)/length(MALE); - - -%false positive - for z=1:length(AUTOMALE); - a=AUTOMALE(z); - b = MALE < a + interval & MALE > a - interval; - c = find(b); - if isempty(c); - falseposm(z) = 1; - - end - end - falseposm=find(falseposm); -FALSEPOSM = length(falseposm)/length(AUTOMALE); - - - - -name = ['gt_workspace_' int2str(RR) '.mat']; -save(name, 'FALSENEGF', 'FALSENEGM', 'FALSEPOSF', 'FALSEPOSM', 'IPI_automale', 'IPI_autofemale', 'IPI_male', 'IPI_female'); -clearvars -except FPULSE MPULSE - -end - - diff --git a/Ground Truthing Code/Plot_Ground_Truthing_Data.m b/Ground Truthing Code/Plot_Ground_Truthing_Data.m deleted file mode 100644 index 3043013..0000000 --- a/Ground Truthing Code/Plot_Ground_Truthing_Data.m +++ /dev/null @@ -1,364 +0,0 @@ -%Plot GROUND TRUTHING data: - -a=figure(1); -b=figure(2); -c=figure(3); -d=figure(4); -e=figure(5); -f=figure(6); -%% -%=======sine song lengths: -SINE_LENGTHS=[]; -for QQ=1:9; - name = ['workspace_' int2str(QQ) '.mat']; - load(name); - - SINE_LENGTHS(1,QQ) = mean(sine_song_lengths); - SINE_LENGTHS(2,QQ) = mean(sine_song_lengths_comp); - SINE_LENGTHS(3,QQ) = length(sine_song_lengths); %gives you the number of sine trains found - SINE_LENGTHS(4,QQ) = length(sine_song_lengths_comp); - SINE_LENGTHS(5,QQ) = sum(sine_song_lengths); %gives you the total amount of sine song - SINE_LENGTHS(6,QQ) = sum(sine_song_lengths_comp); -end - -save('SINE_LENGTHS.mat','SINE_LENGTHS'); - -%% -%=======number pulses found (relative to manual): -DIFFS = []; -for QQ=1:9; - name = ['workspace_' int2str(QQ) '.mat']; - load(name); - - DIFFS(1,QQ) = -DIFF2; %pulseInfo - DIFFS(2,QQ) = -DIFF; %pulseInfo2 - DIFFS(3,QQ) = -DIFF4; %culled pulseInfo - DIFFS(4,QQ) = -DIFF3; %culled pulseInfo2 -end - -save('DIFFS.mat','DIFFS'); -%% -%======meanIPI -MEAN_IPI_ALL = []; -for QQ=1:9; - name = ['workspace_' int2str(QQ) '.mat']; - load(name); - - MEAN_IPI_ALL(1,QQ) = meanIPI; - MEAN_IPI_ALL(2,QQ) = meanIPI_pulseInfo2; - MEAN_IPI_ALL(3,QQ) = meanIPI_pulseInfo; - MEAN_IPI_ALL(4,QQ) = meanIPI_culled_pulseInfo; - MEAN_IPI_ALL(5,QQ) = meanIPI_culled1_pulseInfo; -end - -save('MEAN_IPI_ALL.mat','MEAN_IPI_ALL'); - -%% -%==========IPI -MEAN_IPI_lomb = []; -for QQ=1:9; - name = ['workspace_' int2str(QQ) '.mat']; - load(name); - - MEAN_IPI_lomb(1,QQ) = culled_ipi_byhand.u(1,1); - MEAN_IPI_lomb(2,QQ) = culled_ipi_pulseInfo2.u(1,1); - MEAN_IPI_lomb(3,QQ) = culled_ipi_pulseInfo.u(1,1); - MEAN_IPI_lomb(4,QQ) = culled_ipi_culled_pulseInfo2.u(1,1); - MEAN_IPI_lomb(5,QQ) = culled_ipi_culled_pulseInfo.u(1,1); -end - -save('MEAN_IPI_lomb.mat','MEAN_IPI_lomb'); -%% -%=======modeIPI -MODE_IPI_ALL = []; -for QQ=1:9; - name = ['workspace_' int2str(QQ) '.mat']; - load(name); - - MODE_IPI_ALL(1,QQ) = modeIPI; - MODE_IPI_ALL(2,QQ) = modeIPI_pulseInfo2; - MODE_IPI_ALL(3,QQ) = modeIPI_pulseInfo; - MODE_IPI_ALL(4,QQ) = modeIPI_culled_pulseInfo; - MODE_IPI_ALL(5,QQ) = modeIPI_culled1_pulseInfo; -end - -save('MODE_IPI_ALL.mat','MODE_IPI_ALL'); - -%% -%=======correlations -XCORR = []; -XCORR_score =[]; - -for QQ=1:9; - name = ['workspace_' int2str(QQ) '.mat']; - load(name); - - XCORR(QQ,:,1) = pulse_c; - XCORR(QQ,:,2) = pulse_c1; - XCORR(QQ,:,3) = pulse_cu; - XCORR(QQ,:,4) = pulse_cu1; - XCORR(QQ,:,5) = sine_c; - - XCORR_score(1,QQ) = max(pulse_c); - XCORR_score(2,QQ) = max(pulse_c1); - XCORR_score(3,QQ) = max(pulse_cu); - XCORR_score(4,QQ) = max(pulse_cu1); - XCORR_score(5,QQ) = max(sine_c); -end - -save('XCORR.mat','XCORR'); - -figure; hold on; -for i=1:9; -plot((XCORR(i,:,1)),'r'); -plot((XCORR(i,:,2)),'g'); -plot((XCORR(i,:,3)),'b'); -plot((XCORR(i,:,4)),'c'); -end - - -figure; hold on; -for i=1:9; -plot(XCORR(i,:,5),'k'); -end -%% -%get and plot F scores: -F_ALL = []; -for QQ=1:9; - name = ['workspace_' int2str(QQ) '.mat']; - load(name); - - F_ALL(1,QQ) = FC1; %pulseInfo - F_ALL(2,QQ) = FC; %pulseInfo2 - F_ALL(3,QQ) = FCu; %culled pulseInfo - F_ALL(4,QQ) = FCu2; %culled pulseInfo2 -end - -save('Fscores_ALL.mat','F_ALL'); - -%% -%get sensitivity scores: -SEN_ALL = []; -for QQ=1:9; - name = ['workspace_' int2str(QQ) '.mat']; - load(name); - - SEN_ALL(1,QQ) = VC1PG_sen; %pulseInfo - SEN_ALL(2,QQ) = VCPG_sen; %pulseInfo2 - SEN_ALL(3,QQ) = VCu1PG_sen; %culled pulseInfo - SEN_ALL(4,QQ) = VCuPG_sen; %culled pulseInfo2 -end - -save('SEN_ALL.mat','SEN_ALL'); - -%% -%get sensitivity scores: -PPV_ALL = []; -for QQ=1:9; - name = ['workspace_' int2str(QQ) '.mat']; - load(name); - - PPV_ALL(1,QQ) = VC1PG_ppv; %pulseInfo - PPV_ALL(2,QQ) = VCPG_ppv; %pulseInfo2 - PPV_ALL(3,QQ) = VCu1PG_ppv; %culled pulseInfo - PPV_ALL(4,QQ) = VCuPG_ppv; %culled pulseInfo2 -end - -save('PPV_ALL.mat','PPV_ALL'); - -%% - -%plot is from workspace_5 - -h=figure; plot((data.d(3250001:3310000)./2),'k'); %plot in gray -a=[]; -a=find(VMPG(2.5e5:3.1e5)>0.1176); -b=length(a); -c=ones(1,b); -c=c-0.8; -hold on -plot(a,c,'.k'); - -% a=[]; -% a=find(VC1PG(2.5e5:3.1e5)>0.1176); %pulseInfo -% b=length(a); -% c=ones(1,b); -% c=c-0.78; -% hold on -% plot(a,c,'.c'); - -a=[]; -a=find(VCPG(2.5e5:3.1e5)>0.1176); %pulseInfo2 -b=length(a); -c=ones(1,b); -c=c-0.78; -hold on -plot(a,c,'.b'); - -% a=[]; -% a=find(VCuPG(2.5e5:3.1e5)>0.1176); %culled_pulseInfo -% b=length(a); -% c=ones(1,b); -% c=c-0.74; -% hold on -% plot(a,c,'.m'); - -a=[]; -a=find(VCuP2G(2.5e5:3.1e5)>0.1176); %culled_pulseInfo2 -b=length(a); -c=ones(1,b); -c=c-0.76; -hold on -plot(a,c,'.r'); - -a=[]; -a=find(VMSG(2.5e5:3.1e5)>0.997); -b=length(a); -c=ones(1,b); -c=c-0.87; -hold on -plot(a,c,'.k'); - -a=[]; -a=find(VCSG(2.5e5:3.1e5)>0.997); -b=length(a); -c=ones(1,b); -c=c-0.85; -hold on -plot(a,c,'.r'); - -ylim([-0.1 0.3]); -%% -%======= -%IPI distribution -%collect all IPIs for each method and pool: - -clear all - -IPI_ALL = NaN(5,6000); - -m=1; -mm=1; -mmm=1; -mmmm=1; -mmmmm=1; - -for QQ=1:9; - name = ['workspace_' int2str(QQ) '.mat']; - load(name); - -B=[]; -B = PULSE(:,2)'; %times for pulse peaks -n=length(B); -IPI_ALL(1,m:m+n-1) = B; -m=m+n; - - -B=[]; -B = pulseInfo.wc; %times for pulse peaks -A=[]; -C=[]; -A = find(B>3000000 & B<3600001); -C = B(A); -n=length(C); -IPI_ALL(2,mm:mm+n-1) = C; -mm=mm+n; - - -B=[]; -B = pulseInfo2.wc; %times for pulse peaks -A=[]; -C=[]; -A = find(B>3000000 & B<3600001); -C = B(A); -n=length(C); -IPI_ALL(3,mmm:mmm+n-1) = C; -mmm=mmm+n; - -B=[]; -B = culled_pulseInfo_1.wc; %times for pulse peaks -A=[]; -C=[]; -A = find(B>3000000 & B<3600001); -C = B(A); -n=length(C); -IPI_ALL(4,mmmm:mmmm+n-1) = C; -mmmm=mmmm+n; - -B=[]; -B = culled_pulseInfo.wc; %times for pulse peaks -A=[]; -C=[]; -A = find(B>3000000 & B<3600001); -C = B(A); -n=length(C); -IPI_ALL(5,mmmmm:mmmmm+n-1) = C; -mmmmm=mmmmm+n; -end - -IPI_ALL_2=NaN(5,6000); - -for i=1:5; - a=[]; - a=diff(IPI_ALL(i,:)); - b=[]; - b=find(a<600 & a>200); - %b = b-1; - c=[]; - aa=IPI_ALL(i,:); - c=aa(b); - IPI_ALL_2(i,1:length(c)) = c; -end - -save('IPI_ALL.mat','IPI_ALL','IPI_ALL_2'); - -%% -clear all - -load IPI_ALL.mat - -addpath('/Users/malamurthy/Desktop/FlySongAnalysisSuite'); - -MEAN = []; - -ipi_byhand = fit_ipi_model(IPI_ALL(1,:),2); -%[ipiStats_byhand lombStats_byhand culled_ipi_byhand] = cullIPILomb(ipi_byhand); -figure; gmixPlot(ipi_byhand.d',2,100,100,0,1) -figure(11); hold on; errorbar(1,ipi_byhand.u,ipi_byhand.S, ipi_byhand.S); -MEAN(1,1) = ipi_byhand.u; -MEAN(1,2) = ipi_byhand.S; - -ipi_pulseInfo = fit_ipi_model(IPI_ALL(2,:),2); -%[ipiStats_culled_pulseInfo2 lombStats_culled_pulseInfo2 culled_ipi_culled_pulseInfo2] = cullIPILomb(ipi_culled_pulseInfo2); -figure; gmixPlot(ipi_pulseInfo.d',2,100,100,0,1) -figure(11); hold on; errorbar(2,ipi_pulseInfo.u,ipi_pulseInfo.S, ipi_pulseInfo.S); -MEAN(2,1) = ipi_pulseInfo.u; -MEAN(2,2) = ipi_pulseInfo.S; - -ipi_pulseInfo2 = fit_ipi_model(IPI_ALL(3,:),2); -%[ipiStats_culled_pulseInfo2 lombStats_culled_pulseInfo2 culled_ipi_culled_pulseInfo2] = cullIPILomb(ipi_culled_pulseInfo2); -figure; gmixPlot(ipi_pulseInfo2.d',2,100,100,0,1) -figure(11); hold on; errorbar(3,ipi_pulseInfo2.u,ipi_pulseInfo2.S, ipi_pulseInfo2.S); -MEAN(3,1) = ipi_pulseInfo2.u; -MEAN(3,2) = ipi_pulseInfo2.S; - -ipi_culled_pulseInfo = fit_ipi_model(IPI_ALL(4,:),2); -%[ipiStats_culled_pulseInfo2 lombStats_culled_pulseInfo2 culled_ipi_culled_pulseInfo2] = cullIPILomb(ipi_culled_pulseInfo2); -figure; gmixPlot(ipi_culled_pulseInfo.d',2,100,100,0,1) -figure(11); hold on; errorbar(4,ipi_culled_pulseInfo.u,ipi_culled_pulseInfo.S, ipi_culled_pulseInfo.S); -MEAN(4,1) = ipi_culled_pulseInfo.u; -MEAN(4,2) = ipi_culled_pulseInfo.S; - -ipi_culled_pulseInfo2 = fit_ipi_model(IPI_ALL(5,:),2); -%[ipiStats_culled_pulseInfo2 lombStats_culled_pulseInfo2 culled_ipi_culled_pulseInfo2] = cullIPILomb(ipi_culled_pulseInfo2); -figure; gmixPlot(ipi_culled_pulseInfo2.d',2,100,100,0,1) -figure(11); hold on; errorbar(5,ipi_culled_pulseInfo2.u,ipi_culled_pulseInfo2.S, ipi_culled_pulseInfo2.S); -MEAN(5,1) = ipi_culled_pulseInfo2.u; -MEAN(5,2) = ipi_culled_pulseInfo2.S; - - - - - - - diff --git a/Ground Truthing Code/curveintersect.m b/Ground Truthing Code/curveintersect.m deleted file mode 100644 index acee6c9..0000000 --- a/Ground Truthing Code/curveintersect.m +++ /dev/null @@ -1,190 +0,0 @@ -function [x,y]=curveintersect(varargin) -% See attribution below -% Curve Intersections. -% [X,Y]=CURVEINTERSECT(H1,H2) or [X,Y]=CURVEINTERSECT([H1 H2]) finds the -% intersection points of the two curves on the X-Y plane identified -% by the line or lineseries object handles H1 and H2. -% -% [X,Y]=CURVEINTERSECT(X1,Y1,X2,Y2) finds the intersection points of the -% two curves described by the vector data pairs (X1,Y1) and (X2,Y2). -% -% X and Y are empty if no intersection exists. -% -% Example -% ------- -% x1=rand(10,1); y1=rand(10,1); x2=rand(10,1); y2=rand(10,1); -% [x,y]=curveintersect(x1,y1,x2,y2); -% plot(x1,y1,'k',x2,y2,'b',x,y,'ro') -% -% Original Version (-> curveintersect_local) -% --------------------------------------- -% D.C. Hanselman, University of Maine, Orono, ME 04469 -% Mastering MATLAB 7 -% 2005-01-06 -% -% Improved Version (-> this function) -% ----------------------------------- -% S. Hlz, TU Berlin, Germany -% v 1.0: October 2005 -% v 1.1: April 2006 Fixed some minor bugs in function 'mminvinterp' - -x=[]; y=[]; -[x1,y1,x2,y2]=local_parseinputs(varargin{:}); -ind_x1=sign(diff(x1)); ind_x2=sign(diff(x2)); - -ind1=1; -while ind1=min(y1(ind1)) && y_loc<=max(y1(ind1))); y_loc=[]; x_loc=[]; end - - elseif ind_x2(ind2(1))==0 & ind_x1(ind1(1))~=0 - x_loc=x2(ind2(1)); - y_loc=interp1(x1(ind1),y1(ind1),x_loc); - if ~(y_loc>=min(y2(ind2)) && y_loc<=max(y2(ind2))); y_loc=[]; x_loc=[]; end - - elseif ind_x2(ind2(1))~=0 & ind_x1(ind1(1))~=0 - [x_loc,y_loc]=curveintersect_local(x1(ind1),y1(ind1),x2(ind2),y2(ind2)); - - elseif ind_x2(ind2(1))==0 & ind_x1(ind1(1))==0 - [x_loc,y_loc]=deal([]); - - end - x=[x; x_loc(:)]; - y=[y; y_loc(:)]; - ind2=ind2(end); - end - ind1=ind1(end); -end - - - -% ---------------------------------------------- -function [x,y]=curveintersect_local(x1,y1,x2,y2) - -if ~isequal(x1,x2) - xx=unique([x1 x2]); % get unique data points - xx=xx(xx>=max(min(x1),min(x2)) & xx<=min(max(x1),max(x2))); - if numel(xx)<2 - x=[]; - y=[]; - return - end - yy=interp1(x1,y1,xx)-interp1(x2,y2,xx); -else - xx=x1; - yy=y1-y2; -end -x=mminvinterp(xx,yy,0); % find zero crossings of difference -if ~isempty(x) - y=interp1(x1,y1,x); -else - x=[]; - y=[]; -end - -%-------------------------------------------------------------------------- -%-------------------------------------------------------------------------- -function [xo,yo]=mminvinterp(x,y,yo) -%MMINVINTERP 1-D Inverse Interpolation. From the text "Mastering MATLAB 7" -% [Xo, Yo]=MMINVINTERP(X,Y,Yo) linearly interpolates the vector Y to find -% the scalar value Yo and returns all corresponding values Xo interpolated -% from the X vector. Xo is empty if no crossings are found. For -% convenience, the output Yo is simply the scalar input Yo replicated so -% that size(Xo)=size(Yo). -% If Y maps uniquely into X, use INTERP1(Y,X,Yo) instead. -% -% See also INTERP1. - -if nargin~=3 - error('Three Input Arguments Required.') -end -n = numel(y); -if ~isequal(n,numel(x)) - error('X and Y Must have the Same Number of Elements.') -end -if ~isscalar(yo) - error('Yo Must be a Scalar.') -end - -x=x(:); % stretch input vectors into column vectors -y=y(:); - -if yomax(y) % quick exit if no values exist - xo = []; - yo = []; -else % find the desired points - - below = yyo; % True where above yo - on = y==yo; % True where on yo - - kth = (below(1:n-1)&above(2:n)) | (above(1:n-1)&below(2:n)); % point k - kp1 = [false; kth]; % point k+1 - - xo = []; % distance between x(k+1) and x(k) - if any(kth); - alpha = (yo - y(kth))./(y(kp1)-y(kth)); - xo = alpha.*(x(kp1)-x(kth)) + x(kth); - end - xo = sort([xo; x(on)]); % add points, which are directly on line - - yo = repmat(yo,size(xo)); % duplicate yo to match xo points found -end -%-------------------------------------------------------------------------- -function [x1,y1,x2,y2]=local_parseinputs(varargin) - -if nargin==1 % [X,Y]=CURVEINTERSECT([H1 H2]) - arg=varargin{1}; - if numel(arg)==2 && ... - all(ishandle(arg)) && all(strcmp(get(arg,'type'),'line')) - data=get(arg,{'XData','YData'}); - [x1,x2,y1,y2]=deal(data{:}); - else - error('Input Must Contain Two Handles to Line Objects.') - end -elseif nargin==2 % [X,Y]=CURVEINTERSECT(H1,H2) - arg1=varargin{1}; - arg2=varargin{2}; - if numel(arg1)==1 && ishandle(arg1) && strcmp(get(arg1,'type'),'line')... - && numel(arg2)==1 && ishandle(arg2) && strcmp(get(arg2,'type'),'line') - - data=get([arg1;arg2],{'XData','YData'}); - [x1,x2,y1,y2]=deal(data{:}); - else - error('Input Must Contain Two Handles to Line Objects.') - end -elseif nargin==4 - [x1,y1,x2,y2]=deal(varargin{:}); - if ~isequal(numel(x1),numel(y1)) - error('X1 and Y1 Must Contain the Same Number of Elements.') - elseif ~isequal(numel(x2),numel(y2)) - error('X2 and Y2 Must Contain the Same Number of Elements.') - end - x1=reshape(x1,1,[]); % make data into rows - x2=reshape(x2,1,[]); - y1=reshape(y1,1,[]); - y2=reshape(y2,1,[]); - -else - error('Incorrect Number of Input Arguments.') -end -if min(x1)>max(x2) | min(x2)>max(x1) | min(y2)>max(y1) | min(y1)>max(y2) % Polygons can not have intersections - x1=[]; y1=[]; x2=[]; y2=[]; return -end -if numel(x1)<2 || numel(x2)<2 || numel(y1)<2 || numel(y2)<2 - error('At Least Two Data Points are Required for Each Curve.') -end - diff --git a/Process_Song_virilis.m b/Process_Song_virilis.m index ea1fd00..0489d13 100644 --- a/Process_Song_virilis.m +++ b/Process_Song_virilis.m @@ -1,6 +1,20 @@ -function [pulseInfo,pulseInfoF,pulseInfoM,male_song_times_final,segParams] = ... +function [pulseInfo,pulseInfoF,pulseInfoM,male_song_times_final] = ... Process_Song_virilis(song,P,xempty,segParams) - +%Runs heuristic male bout calling analysis +%Inputs: +% song -> 1d time series containing song data +% P -> wavelet amplitudes +% xempty -> noise data +% segParams -> struct containing run parameters +% +%Output: +% pulseInfo -> struct containing information about all pulse calls +% pulseInfoF -> struct containing information about female pulse calls +% pulseInfoM -> struct containing information about male pulse calls +% male_song_times_final -> start and end times of called male bouts +% +% (C) Gordon J. Berman, Jan Clemens, Kelly M. LaRue, and Mala Murthy, 2015 +% Princeton University addpath(genpath('./chronux')) fprintf('Running wavelet transformation.\n') diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..dd8daa1 --- /dev/null +++ b/README.txt @@ -0,0 +1,54 @@ +This code represents a sample implementation of the automated song analysis methods initially described in the paper “Mapping the stereotyped behaviour of freely-moving fruit flies” by LaRue, KM, Clemens, J, Berman GJ, and Murthy, M (eLife, 2015). + +This MATLAB code is presented in order to provide a more explicit representation of the algorithms described in the article text. + +As this code is presented for the sake of methodological repeatability (and not as “Black Box” software), the use of this software is at your own risk. The authors are not responsible for any damage that may result from errors in the software. + +Downloaders of this software are free to use, modify, or redistribute this software how they see fit, but only for non-commercial purposes and all modified versions may only be shared under the same conditions as this (see license below). For any further questions about this code, please email Gordon Berman at gordon.berman@gmail.com. + +All that being said, if any questions/concerns/bugs arise, please feel free to email me (Gordon), and I will do my absolute best to answer/resolve them. + +******* + +1) An example song file is included as the ‘song’ variable saved within exampleSong.mat. +2) The set of likelihood models used in the paper is included within exampleLikelihoodModels.mat + +3) To run a sample implementation, load ‘song’ into the MATLAB workspace and run + + [maleBoutInfo,femaleBoutInfo,run_data] = segmentVirilisSong(song); + +4) Details as to the nature of the output variables listed above can be found in the comments within segmentVirilisSong.m. + +5) To create a set of likelihood models, run + + likelihoodModels = … + find_songs_from_hand_annotations(male_songs,female_songs,overlap_songs); + + Here, male_songs, female_songs, and overlap_songs are each arrays of wavelet amplitudes, with each row being an example wavelet amplitudes at one point in time and each column being a different frequency channel. + +6) Future implementations will allow for a GUI-based creation of these likelihood models. + +******* + +The MIT License (MIT) + +Copyright (c) 2015 Murthy lab + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/WaveletFunctions/centfrq.m b/WaveletFunctions/centfrq.m deleted file mode 100644 index 9d793ff..0000000 --- a/WaveletFunctions/centfrq.m +++ /dev/null @@ -1,76 +0,0 @@ -function [freq,xval,recfreq] = centfrq(wname,iter,in3) -%CENTFRQ center frequency. -% FREQ = CENTFRQ('wname') returns the center frequency in hertz -% of the wavelet function 'wname' (see WAVEFUN). -% -% For FREQ = CENTFRQ('wname',ITER), ITER is the number -% of iterations used by the WAVEFUN function to compute -% the wavelet. -% -% [FREQ,XVAL,RECFREQ] = CENTFRQ('wname',ITER, 'plot') -% returns in addition the associated center frequency based -% approximation RECFREQ on the 2^ITER points grid XVAL -% and plots the wavelet function and RECFREQ. -% -% See also SCAL2FRQ, WAVEFUN, WFILTERS. - -% M. Misiti, Y. Misiti, G. Oppenheim, J.M. Poggi 04-Mar-98. -% Last Revision: 25-May-2003. -% Copyright 1995-2004 The MathWorks, Inc. -% $Revision: 1.6.4.2 $ $Date: 2004/03/15 22:39:48 $ - -% Check arguments. -if nargin==1, iter = 8; end - -% Retrieve wavelet. -wname = deblankl(wname); -wtype = wavemngr('type',wname); -switch wtype - case 1 , [nul,psi,xval] = wavefun(wname,iter); - case 2 , [nul,psi,nul,nul,xval] = wavefun(wname,iter); - case 3 , [nul,psi,xval] = wavefun(wname,iter); - case 4 , [psi,xval] = wavefun(wname,iter); - case 5 , [psi,xval] = wavefun(wname,iter); -end - -T = max(xval)-min(xval); % T is the size of the domain of psi. -n = length(psi); -psi = psi-mean(psi); % psi is numerically centered. -psiFT = fft(psi); % computation of the modulus -sp = (abs(psiFT)); % of the FT. - -% Compute arg max of the modulus of the FT (center frequency). -[vmax,indmax] = max(sp); -if indmax > n/2 - indmax = n-indmax+2; % indmax is always >= 2. -end -per = T/(indmax-1); % period corresponding to the maximum. -freq = 1/per; % associated frequency. - -if nargin > 2 - % plots and computation of the associated reconstructed signal. - psiFT(sp1 , err = 1; -elseif min(scales) - err = 1; - end - if err~=1 - lenSIG = length(ySIG); - try - xSIG = SIG.x; stepSIG = xSIG(2)-xSIG(1); - catch ME %#ok - try - stepSIG = SIG.step; - xSIG = (0:stepSIG:(lenSIG-1)*stepSIG); - catch ME %#ok - try - xlim = SIG.xlim; - xSIG = linspace(xlim(1),xlim(2),lenSIG); - stepSIG = xSIG(2)-xSIG(1); - catch ME %#ok - xSIG = (1:lenSIG); stepSIG = 1; - end - end - end - end - -elseif iscell(SIG) - ySIG = SIG{1}; - xATTRB = SIG{2}; - lenSIG = length(ySIG); - len_xATTRB = length(xATTRB); - if len_xATTRB==lenSIG - xSIG = xATTRB; - stepSIG = xSIG(2)-xSIG(1); - - elseif len_xATTRB==2 - xlim = xATTRB; - xSIG = linspace(xlim(1),xlim(2),lenSIG); - stepSIG = xSIG(2)-xSIG(1); - - elseif len_xATTRB==1 - stepSIG = xATTRB; - xSIG = (0:stepSIG:(lenSIG-1)*stepSIG); - else - xSIG = (1:lenSIG); stepSIG = 1; - end -else - err = 1; -end -if err - errargt(mfilename,'Invalid Value for Signal !','msg'); - error('Wavelet:FunctionArgVal:Invalid_ArgVal', ... - 'Invalid Value for Signal !') -end - -% Check wavelet. -%--------------- -getINTEG = 1; -getWTYPE = 1; -if ischar(WAV) - precis = 10; % precis = 15; - [val_WAV,xWAV] = intwave(WAV,precis); - stepWAV = xWAV(2)-xWAV(1); - wtype = wavemngr('type',WAV); - if wtype==5 , val_WAV = conj(val_WAV); end - getINTEG = 0; - getWTYPE = 0; - -elseif isnumeric(WAV) - val_WAV = WAV; - lenWAV = length(val_WAV); - xWAV = linspace(0,1,lenWAV); - stepWAV = 1/(lenWAV-1); - -elseif isstruct(WAV) - try - val_WAV = WAV.y; - catch ME %#ok - err = 1; - end - if err~=1 - lenWAV = length(val_WAV); - try - xWAV = WAV.x; stepWAV = xWAV(2)-xWAV(1); - catch ME %#ok - try - stepWAV = WAV.step; - xWAV = (0:stepWAV:(lenWAV-1)*stepWAV); - catch ME %#ok - try - xlim = WAV.xlim; - xWAV = linspace(xlim(1),xlim(2),lenWAV); - stepWAV = xWAV(2)-xWAV(1); - catch ME %#ok - xWAV = (1:lenWAV); stepWAV = 1; - end - end - end - end - -elseif iscell(WAV) - if isnumeric(WAV{1}) - val_WAV = WAV{1}; - elseif ischar(WAV{1}) - precis = 10; - val_WAV = intwave(WAV{1},precis); - wtype = wavemngr('type',WAV{1}); - getINTEG = 0; - getWTYPE = 0; - end - xATTRB = WAV{2}; - lenWAV = length(val_WAV); - len_xATTRB = length(xATTRB); - if len_xATTRB==lenWAV - xWAV = xATTRB; stepWAV = xWAV(2)-xWAV(1); - - elseif len_xATTRB==2 - xlim = xATTRB; - xWAV = linspace(xlim(1),xlim(2),lenWAV); - stepWAV = xWAV(2)-xWAV(1); - - elseif len_xATTRB==1 - stepWAV = xATTRB; - xWAV = (0:stepWAV:(lenWAV-1)*stepWAV); - else - xWAV = linspace(0,1,lenWAV); - stepWAV = 1/(lenWAV-1); - end -end -if err - errargt(mfilename,'Invalid Value for Wavelet !','msg'); - error('Wavelet:FunctionArgVal:Invalid_ArgVal', ... - 'Invalid Value for Wavelet !') -end -xWAV = xWAV-xWAV(1); -xMaxWAV = xWAV(end); -if getWTYPE , wtype = 4; end -if getINTEG , val_WAV = stepWAV*cumsum(val_WAV); end - -ySIG = ySIG(:)'; -nb_SCALES = length(scales); -coefs = zeros(nb_SCALES,lenSIG); -ind = 1; -for k = 1:nb_SCALES - a = scales(k); - a_SIG = a/stepSIG; - j = 1+floor((0:a_SIG*xMaxWAV)/(a_SIG*stepWAV)); - if length(j)==1 , j = [1 1]; end - f = fliplr(val_WAV(j)); - coefs(ind,:) = -sqrt(a)*wkeep1(diff(wconv1(ySIG,f)),lenSIG); - ind = ind+1; -end - -% Test for plots. -%---------------- -if nargin<4 , return; end - -% Display Continuous Analysis. -%----------------------------- -dummyCoefs = coefs; -NBC = 240; -if strmatch('3D',plotmode) - dim_plot = '3D'; -elseif strmatch('scal',plotmode) - dim_plot = 'SC'; -else - dim_plot = '2D'; -end - -if isequal(wtype,5) - if ~isempty(findstr(plotmode,'lvl')) - plotmode = 'lvl'; - else - plotmode = 'glb'; - end -end -switch plotmode - case {'lvl','3Dlvl'} - lev_mode = 'row'; abs_mode = 0; beg_title = 'By scale'; - - case {'glb','3Dglb'} - lev_mode = 'mat'; abs_mode = 0; beg_title = ''; - - case {'abslvl','lvlabs','3Dabslvl','3Dlvlabs'} - lev_mode = 'row'; abs_mode = 1; beg_title = 'Abs. and by scale'; - - case {'absglb','glbabs','plot','2D','3Dabsglb','3Dglbabs','3Dplot','3D'} - lev_mode = 'mat'; abs_mode = 1; beg_title = 'Absolute'; - - case {'scal','scalCNT'} - lev_mode = 'mat'; abs_mode = 1; beg_title = 'Absolute'; - - otherwise - plotmode = 'absglb'; - lev_mode = 'mat'; abs_mode = 1; beg_title = 'Absolute'; - dim_plot = '2D'; -end - -if abs_mode , dummyCoefs = abs(dummyCoefs); end -if nargin==5 && ~isequal(plotmode,'scal') && ~isequal(plotmode,'scalCNT') - xlim = varargin{1}; - if xlim(2)lenSIG , xlim(2) = lenSIG; end - indices = xlim(1):xlim(2); - switch plotmode - case {'glb','absglb'} - cmin = min(min(dummyCoefs(:,indices))); - cmax = max(max(dummyCoefs(:,indices))); - dummyCoefs(dummyCoefscmax) = cmax; - - case {'lvl','abslvl'} - cmin = min(dummyCoefs(:,indices),[],2); - cmax = max(dummyCoefs(:,indices),[],2); - for k=1:nb_SCALES - ind = dummyCoefs(k,:)cmax(k); - dummyCoefs(k,ind) = cmax(k); - end - end -elseif isequal(plotmode,'scalCNT') - if ~isempty(varargin) , nbcl = varargin{1}; end -end - -nb = min(5,nb_SCALES); -level = ''; -for k=1:nb , level = [level ' ' num2str(scales(k))]; end %#ok -if nb1 , varargout{1} = SC; end - - case '2D' - if wtype<5 - titleSTR = [beg_title ' Values of Ca,b Coefficients for a = ' level]; - plotPARAMS{6} = titleSTR; - axeAct = gca; - plotCOEFS(axeAct,dummyCoefs,plotPARAMS); - else - axeAct = subplot(2,2,1); - titleSTR = ['Real part of Ca,b for a = ' level]; - plotPARAMS{6} = titleSTR; - plotCOEFS(axeAct,real(dummyCoefs),plotPARAMS); - axeAct = subplot(2,2,2); - titleSTR = ['Imaginary part of Ca,b for a = ' level]; - plotPARAMS{6} = titleSTR; - plotCOEFS(axeAct,imag(dummyCoefs),plotPARAMS); - axeAct = subplot(2,2,3); - titleSTR = ['Modulus of Ca,b for a = ' level]; - plotPARAMS{6} = titleSTR; - plotCOEFS(axeAct,abs(dummyCoefs),plotPARAMS); - axeAct = subplot(2,2,4); - titleSTR = ['Angle of Ca,b for a = ' level]; - plotPARAMS{6} = titleSTR; - plotCOEFS(axeAct,angle(dummyCoefs),plotPARAMS); - end - colormap(pink(NBC)); - - case '3D' - if wtype<5 - titleSTR = [beg_title ' Values of Ca,b Coefficients for a = ' level]; - plotPARAMS{6} = titleSTR; - axeAct = gca; - surfCOEFS(axeAct,dummyCoefs,plotPARAMS); - else - axeAct = subplot(2,2,1); - titleSTR = ['Real part of Ca,b for a = ' level]; - plotPARAMS{6} = titleSTR; - surfCOEFS(axeAct,real(dummyCoefs),plotPARAMS); - axeAct = subplot(2,2,2); - titleSTR = ['Imaginary part of Ca,b for a = ' level]; - plotPARAMS{6} = titleSTR; - surfCOEFS(axeAct,imag(dummyCoefs),plotPARAMS); - axeAct = subplot(2,2,3); - titleSTR = ['Modulus of Ca,b for a = ' level]; - plotPARAMS{6} = titleSTR; - surfCOEFS(axeAct,abs(dummyCoefs),plotPARAMS); - axeAct = subplot(2,2,4); - titleSTR = ['Angle of Ca,b for a = ' level]; - plotPARAMS{6} = titleSTR; - surfCOEFS(axeAct,angle(dummyCoefs),plotPARAMS); - end -end - -%---------------------------------------------------------------------- -function plotCOEFS(axeAct,coefs,plotPARAMS) - -[NBC,lev_mode,abs_mode,ytics,ylabs,titleSTR] = deal(plotPARAMS{1:6}); - -coefs = wcodemat(coefs,NBC,lev_mode,abs_mode); -image(coefs); -set(axeAct, ... - 'YTick',ytics, ... - 'YTickLabel',ylabs, ... - 'YDir','normal', ... - 'Box','On' ... - ); -title(titleSTR,'Parent',axeAct); -xlabel('time (or space) b','Parent',axeAct); -ylabel('scales a','Parent',axeAct); -%---------------------------------------------------------------------- -function surfCOEFS(axeAct,coefs,plotPARAMS) - -[NBC,~,~,ytics,ylabs,titleSTR] = deal(plotPARAMS{1:6}); - -surf(coefs); -set(axeAct, ... - 'YTick',ytics, ... - 'YTickLabel',ylabs, ... - 'YDir','normal', ... - 'Box','On' ... - ); -title(titleSTR,'Parent',axeAct); -xlabel('time (or space) b','Parent',axeAct); -ylabel('scales a','Parent',axeAct); -zlabel('COEFS','Parent',axeAct); - -xl = [1 size(coefs,2)]; -yl = [1 size(coefs,1)]; -zl = [min(min(coefs)) max(max(coefs))]; -set(axeAct,'XLim',xl,'YLim',yl,'ZLim',zl,'view',[-30 40]); - -colormap(pink(NBC)); -shading('interp') -%---------------------------------------------------------------------- diff --git a/WaveletFunctions/deblankl.m b/WaveletFunctions/deblankl.m deleted file mode 100644 index 681b347..0000000 --- a/WaveletFunctions/deblankl.m +++ /dev/null @@ -1,10 +0,0 @@ -function s = deblankl(x) -%DEBLANKL Convert string to lowercase without blanks. -% S = DEBLANKL(X) is the string X converted to lowercase - -if ~isempty(x) - s = lower(x); - s = s(s~=' '); -else - s = []; -end diff --git a/WaveletFunctions/errargt.m b/WaveletFunctions/errargt.m deleted file mode 100644 index 77bdb9a..0000000 --- a/WaveletFunctions/errargt.m +++ /dev/null @@ -1,154 +0,0 @@ -function [err,fig] = errargt(ndfct,var,type,flagWin) -%ERRARGT Check function arguments type. -% ERR = ERRARGT(NDFCT,VAR,TYPE) -% is equal to 1 if any element of input vector or -% matrix VAR (depending on TYPE choice listed below) -% is not of type prescribed by input string TYPE. -% Otherwise ERR = 0. -% -% If ERR = 1, an error message is displayed in the command -% -% -% 'vec' : vector -% 'row' : row vector -% 'col' : column vector -% -% 'dat' : dates AAAAMMJJHHMNSS -% with 0 <= AAAA <=9999 -% 1 <= MM <= 12 -% 1 <= JJ <= 31 -% 0 <= HH <= 23 -% 0 <= MN <= 59 -% 0 <= SS <= 59 -% -% 'mon' : months MM -% with 1 <= MM <= 12 -% -% A special use of ERRARGT is ERR = ERRARGT(NDFCT,VAR,'msg') -% for which ERR = 1 and the string VAR is the error message. -% -% See also ERRARGN. - -% M. Misiti, Y. Misiti, G. Oppenheim, J.M. Poggi 01-May-96. -% Last Revision: 23-Aug-2007. -% Copyright 1995-2007 The MathWorks, Inc. -% $Revision: 1.15.4.4 $ $Date: 2007/10/23 18:59:40 $ - -[r,c] = size(var); -err = 0; - -switch type - case 'int' - if (ischar(var) || any(any(var < 1)) || any(any(var ~= fix(var)))) - err = 1; txt = 'integer(s) > 0 , expected'; - end - - case 'in0' - if (ischar(var) || any(any(var < 0)) || any(any(var ~= fix(var)))) - err = 1; txt = 'integer(s) => 0 , expected'; - end - - case 'rel' - if (ischar(var) || any(any(var ~= fix(var)))) - err = 1; txt = 'integer(s) expected'; - end - - case 'rep' - if (ischar(var) || any(any(var <= 0))) - err = 1; txt = 'real(s) > 0 , expected'; - end - - case 're0' - if (ischar(var) || any(any(var < 0))) - err = 1; txt = 'real(s) => 0 , expected'; - end - - case 'str' - if any(~ischar(var)) - err = 1; txt = 'string expected'; - end - - case 'vec' - if r ~= 1 && c ~= 1 - err = 1; txt = 'vector expected'; - end - - case 'row' - if r ~= 1 - err = 1; txt = 'row vector expected'; - end - - case 'col' - if c ~= 1 - err = 1; txt = 'column vector expected'; - end - - case 'dat' - if isempty(var) - err = 1; txt = 'date expected'; - else - ss = rem(var,100); - mn = rem(fix(var/100),100); - hh = rem(fix(var/10000),100); - jj = rem(fix(var/1000000),100); - mm = rem(fix(var/100000000),100); - aa = fix(var/10000000000); - if any(... - ss < 0 | ss > 59 |... - mn < 0 | mn > 59 |... - hh < 0 | hh > 24 | (hh == 24 & (ss ~= 0 | mn ~= 0)) |... - jj < 1 | jj > 31 | ... - mm < 1 | mm > 12 | ... - aa < 0 | aa > 9999 ... - ) - err = 1; txt = 'date expected'; - end - end - - case 'mon' - if (any(var < 1 | var > 12 | var ~= fix(var))) - err = 1; txt = 'month expected'; - end - - case 'msg' - err = 1; txt = var; - - otherwise - err = 1; txt = 'undefined type of variable'; -end -fig = []; -if err == 1 - if size(txt,1) == 1 - msg = [' ' ndfct ' ---> ' xlate(txt)]; - else - msg = {[' ' ndfct ' ---> '] ; txt}; - end - if strcmp(type,'msg') - txttitle = 'ERROR ... '; - else - txttitle = 'ARGUMENTS ERROR'; - end - - % if GUI is used messages are displayed in a window - % else the Matlab command window is used. - %-------------------------------------------------- - if nargin<4 , flagWin = 1; end - if ~mextglob('is_on') || ~flagWin - lenmsg = length(msg); len = lenmsg+2; - star = '*'; star = star(:,ones(1,len)); - minus = '-'; minus = minus(:,ones(1,len)); - disp(' ') - disp(star); - disp(txttitle); - disp(minus); - if iscell(msg) - for k =1:length(msg) , disp(msg{k}); end - else - disp(msg); - end - disp(star); - disp(' ') - else - fig = errordlg(msg,txttitle,'modal'); - end -end diff --git a/WaveletFunctions/fbspwavf.m b/WaveletFunctions/fbspwavf.m deleted file mode 100644 index 8fc6443..0000000 --- a/WaveletFunctions/fbspwavf.m +++ /dev/null @@ -1,94 +0,0 @@ -function [psi,X] = fbspwavf(LB,UB,N,IN4,IN5,IN6) -%FBSPWAVF Complex Frequency B-Spline wavelet. -% [PSI,X] = FBSPWAVF(LB,UB,N,M,FB,FC) returns values of -% the complex Frequency B-Spline wavelet defined by -% the order parameter M (M is an integer >=1), -% a bandwidth parameter FB, and a wavelet center frequency FC. -% -% The function PSI is computed using the explicit expression: -% PSI(X) = (FB^0.5)*((sinc(FB*X/M).^M).*exp(2*i*pi*FC*X)) -% on an N point regular grid for the interval [LB,UB]. -% -% Output arguments are the wavelet function PSI -% computed on the grid X. -% -% See also WAVEINFO. - -% M. Misiti, Y. Misiti, G. Oppenheim, J.M. Poggi 09-Jun-99. -% Last Revision: 23-Jul-2007. -% Copyright 1995-2007 The MathWorks, Inc. -% $Revision: 1.6.4.3 $ $Date: 2007/10/23 18:59:42 $ - -% Check arguments. -%----------------- -m = 1; -Fb = 1; -Fc = 1; -nbIn = nargin; -switch nbIn - case {0,1,2,3} - error('Wavelet:FunctionInput:NotEnough_ArgNum',... - 'Not enough input arguments.'); - case 5 - error('Wavelet:FunctionInput:Invalid_ArgNum',... - 'Invalid number of input arguments.'); - case 6 , m = IN4; Fb = IN5; Fc = IN6; - case 4 - if ischar(IN4) - label = deblank(IN4); - ind = strncmpi('fbsp',label,4); - if isequal(ind,1) - label(1:4) = []; - len = length(label); - if len>0 - ind = findstr('-',label); - if isempty(ind) - m = []; % error - else - ind = ind(1); - m = wstr2num(label(1:ind-1)); - label(1:ind) = []; - ind = findstr('-',label); - if isempty(ind) - Fb = []; % error - else - Fb = wstr2num(label(1:ind-1)); - label(1:ind) = []; - Fc = wstr2num(label); - end - end - else - Fc = []; % error - end - else - Fc = []; % error - end - else - Fc = []; % error - end -end -err = isempty(m) || isempty(Fc) || isempty(Fb); -if ~err - err = ~isnumeric(Fc) || ~isnumeric(Fb) || (Fc<=0) || (Fb<=0); -end -if err - error('Wavelet:FunctionArgVal:Invalid_WaveNum', ... - 'Invalid Wavelet Number!') -end - -% Compute values of the Complex Frequency B-Spline wavelet. -X = linspace(LB,UB,N); % wavelet support. -psi = (Fb^0.5)*((sinc(Fb*X/m).^m).*exp(2*i*pi*Fc*X)); - - -%----------------------------------------------- -function y = sinc(x) -% -% | sin(pi*x)/(pi*x) if x ~= 0 -% y = sinc(x) = | -% | 1 if x == 0 - -y = ones(size(x)); -k = find(x); -y(k) = sin(pi*x(k))./(pi*x(k)); -%----------------------------------------------- diff --git a/WaveletFunctions/gauswavf.m b/WaveletFunctions/gauswavf.m deleted file mode 100644 index 0eb5b10..0000000 --- a/WaveletFunctions/gauswavf.m +++ /dev/null @@ -1,97 +0,0 @@ -function [psi,X] = gauswavf(LB,UB,N,NumWAW) -%GAUSWAVF Gaussian wavelet. -% [PSI,X] = GAUSWAVF(LB,UB,N,P) returns values of the Pth -% derivative of the Gaussian function F = Cp*exp(-x^2) on -% an N point regular grid for the interval [LB,UB]. Cp is -% such that the 2-norm of the Pth derivative of F is equal -% to 1. P can be integer values from 1 to 8. - -% See also CGAUSWAVF, WAVEINFO. - -% M. Misiti, Y. Misiti, G. Oppenheim, J.M. Poggi 12-Mar-96. -% Last Revision: 11-Apr-2008. -% Copyright 1995-2008 The MathWorks, Inc. -% $Revision: 1.12.4.4 $ $Date: 2008/05/31 23:31:58 $ - -% Check arguments. -%----------------- -nbIn = nargin; -switch nbIn - case 0 - if ~exist('maple') , nmax = 8; else nmax = 45; end %#ok - psi = nmax; - % psi contains the number max for Gaussian wavelets. - % This number depends of Symbolic Toolbox - - case 2 - error('Wavelet:FunctionInput:NotEnough_ArgNum',... - 'Not enough input arguments.'); - - case 3 , NumWAW = 1; - - case 4 - if ischar(NumWAW) - [fam,NumWAW] = wavemngr('fam_num',NumWAW); - NumWAW = wstr2num(NumWAW); - end - - otherwise - error('Wavelet:FunctionInput:TooMany_ArgNum', ... - 'Too many input arguments.'); -end -if errargt(mfilename,NumWAW,'int') - error('Wavelet:Invalid_ArgVal_Or_ArgType', ... - 'Invalid Input Argument.'); -end - -% Compute values of the Gauss wavelet. -X = linspace(LB,UB,N); % wavelet support. -if find(NumWAW==1:8,1) - X2 = X.^2; - F0 = (2/pi)^(1/4)*exp(-X2); -end - -switch NumWAW - case 1 - psi = -2*X.*F0; - - case 2 - psi = 2/(3^(1/2)) * (-1+2*X2).*F0; - - case 3 - psi = 4/(15^(1/2)) * X.* (3-2*X2).*F0; - - case 4 - psi = 4/(105^(1/2)) * (3-12*X2+4*X2.^2).*F0; - - case 5 - psi = 8/(3*(105^(1/2))) * X.* (-15+20*X2-4*X2.^2).*F0; - - case 6 - psi = 8/(3*(1155^(1/2))) * (-15+90*X2-60*X2.^2+8*X2.^3).*F0; - - case 7 - psi = 16/(3*(15015^(1/2))) *X.*(105-210*X2+84*X2.^2-8*X2.^3).*F0; - - case 8 - psi = 16/(45*(1001^(1/2))) * (105-840*X2+840*X2.^2-224*X2.^3+16*X2.^4).*F0; - - otherwise - if ~exist('maple') %#ok - msg = 'Symbolic Math Toolbox(TM) is required!'; - errargt(mfilename,msg,'msg') - error('Wavelet:SymbolicTBX',msg); - end - y = sym('t'); - f = exp(-y.*y); - d = diff(f,NumWAW); - n = sqrt(int(d*d,-Inf,Inf)); - d = d/n; - for j = 1:length(X) - t = X(j); %#ok - psi(j) = eval(d); - end -end -switch rem(NumWAW,4) - case {2,3} , psi = -psi; -end diff --git a/WaveletFunctions/intwave.m b/WaveletFunctions/intwave.m deleted file mode 100644 index 14cb584..0000000 --- a/WaveletFunctions/intwave.m +++ /dev/null @@ -1,114 +0,0 @@ -function [out1,xval,out3] = intwave(wname,in2,in3) -%INTWAVE Integrate wavelet function psi. -% [INTEG,XVAL] = INTWAVE('wname',PREC) computes the integral INTEG, -% of the wavelet function psi (from -inf to XVAL values). -% The function psi is approximated on the 2^PREC -% points grid XVAL where PREC is a positive integer. -% 'wname' is a string containing the name of the wavelet - -% [INTDEC,XVAL,INTREC] = INTWAVE('wname',PREC) -% computes the integrals INTDEC and INTREC of the wavelet -% decomposition function psi_dec and the wavelet -% reconstruction function psi_rec. -% -% INTWAVE('wname',PREC) is equivalent to -% INTWAVE('wname',PREC,0). -% INTWAVE('wname') is equivalent to INTWAVE('wname',8). -% -% When used with three arguments INTWAVE('wname',IN2,IN3), -% PREC = MAX(IN2,IN3) and plots are displayed. -% When IN2 is equal to the special value 0 -% INTWAVE('wname',0) is equivalent to -% INTWAVE('wname',8,IN3). -% INTWAVE('wname') is equivalent to INTWAVE('wname',8). -% -% See also WAVEFUN. - -% M. Misiti, Y. Misiti, G. Oppenheim, J.M. Poggi 12-Mar-96. -% Last Revision: 20-Jul-2010. -% Copyright 1995-2010 The MathWorks, Inc. -% $Revision: 1.11.4.4 $ - -% Check arguments. -iterDEF = 8; -switch nargin - case 1 , - iter = iterDEF; pflag = 0; - case 2 - if in2 == 0, - pflag = 1; - iter = iterDEF; - else - pflag = 0; - if isnumeric(in2) - iter = in2; - else - iter = iterDEF; - end - - end - otherwise - pflag = 1; - in2NUM = isnumeric(in2); - in3NUM = isnumeric(in3); - if in2NUM - if in3NUM - iter = max(in2,in3); - else - iter = in2; - end - - elseif in3NUM - iter = in3; - else - iter = iterDEF; - end -end -if iter~=fix(iter) || iter<1 || iter>20 - iter = iterDEF; -end - -wtype = wavemngr('type',wname); -switch wtype - case {1,3} , [phi,psi,xval] = wavefun(wname,iter); - case 2 , [phi1,psi1,phi2,psi2,xval] = wavefun(wname,iter); - case {4,5} , [psi,xval] = wavefun(wname,iter); -end - -step = xval(2)-xval(1); -switch wtype - case {1,3,4,5} , out1 = cumsum(psi)*step; - case 2 , out1 = cumsum(psi1)*step; out3 = cumsum(psi2)*step; -end - -if pflag - switch wtype - case {1,3,4} - ax(1) = subplot(211); plot(xval,psi,'r'); title('psi function');grid - ax(2) = subplot(212); plot(xval,out1,'g'); - title('psi function integral value from 0 to x-value');grid - set(ax,'XLim',[xval(1),xval(end)]) - - case 2 - ax(1) = subplot(221); - plot(xval,psi1,'r');title('psi dec. funct.');grid - ax(2) = subplot(222); plot(xval,out1,'g'); - title('psi dec. funct. integ. value from 0 to x-value');grid - ax(3) = subplot(223); - plot(xval,psi2,'r');title('psi rec. funct');grid - ax(4) = subplot(224);plot(xval,out3,'g'); - title('psi rec. funct. integ. value from 0 to x-value');grid - set(ax,'XLim',[xval(1),xval(end)]) - - case {5} - ax(1) = subplot(221); - plot(xval,real(psi),'r');title('real part of psi funct.');grid - ax(2) = subplot(222);plot(xval,real(out1),'g'); - title('real part of psi funct. integ. value from 0 to x-value');grid - ax(3) = subplot(223); - plot(xval,imag(psi),'r');title('imag. part of psi funct');grid - ax(4) = subplot(224);plot(xval,imag(out1),'g'); - title('imag. part of psi funct. integ. value from 0 to x-value');grid - set(ax,'XLim',[xval(1),xval(end)]) - end -end diff --git a/WaveletFunctions/mextglob.m b/WaveletFunctions/mextglob.m deleted file mode 100644 index 42f945f..0000000 --- a/WaveletFunctions/mextglob.m +++ /dev/null @@ -1,521 +0,0 @@ -function varargout = mextglob(option,varargin) -%MEXTGLOB Module of extended objects globals. -% VARARGOUT = MEXTGLOB(OPTION,VARARGIN) -% -% OPTION : 'ini' , 'pref' , 'clear' -% 'get' , 'set' , 'is_on' - -% M. Mi - -Def_WGlob_Struct = getappdata(0,'Def_WGlob_Struct'); -initFLAG = isempty(Def_WGlob_Struct); - -switch option - case 'is_on' , varargout{1} = ~initFLAG; return - case 'clear' , - if isappdata(0,'Def_WGlob_Struct') - rmappdata(0,'Def_WGlob_Struct'); - end - return - case {'ini','pref'} - if ~initFLAG - if nargin==1 , return; end - old_prefMode = Def_WGlob_Struct.initMode; - if isequal(old_prefMode,varargin{1}); return; end - else - if nargin==1 , varargin{1} = 'default'; end - end - allPrefMode = cat(2,{'d','y','r','g','b','k','w'},... - {'oldDefaut','default','black','white'},... - num2cell(-1:17) , {'s','std','test'}); - - prefMode = 'default'; - if nargin>1 - modeToTest = varargin{1}; - if ~isempty(modeToTest) - for k = 1:length(allPrefMode) - if isequal(modeToTest,allPrefMode{k}) - prefMode = modeToTest; - break - end - end - end - end - varargin{1} = prefMode; - Def_WGlob_Struct = Get_Def_WGlob_Struct(varargin{:}); - setappdata(0,'Def_WGlob_Struct',Def_WGlob_Struct); - if nargout>0 , varargout{1} = Def_WGlob_Struct; end - - case 'get' - if initFLAG , Def_WGlob_Struct = mextglob('ini'); end - sizes = Def_WGlob_Struct.sizes; - colors = Def_WGlob_Struct.colors; - nbout = nargout; - nbin = nargin-1; - for k=1:min([nbin,nbout]) - switch varargin{k} - case 'InitMode' , ... - varargout{k} = Def_WGlob_Struct.initMode; - case 'Terminal_Prop' , varargout{k} = sizes.termProp; - case 'ShiftTop_Fig' , varargout{k} = sizes.figShiftTop; - case 'Def_Btn_Height' , varargout{k} = sizes.btnHeight; - case 'Def_Btn_Width' , varargout{k} = sizes.btnWidth; - case 'Def_Txt_Height' , varargout{k} = sizes.txtHeight; - case 'Pop_Min_Width' , varargout{k} = sizes.popWidth; - case 'Sli_YProp' , varargout{k} = sizes.sliYProp; - case 'X_Spacing' , varargout{k} = sizes.xSpacing; - case 'Y_Spacing' , varargout{k} = sizes.ySpacing; - case 'bdXLSpacing' , varargout{k} = sizes.bdXLSpacing; - case 'bdXRSpacing' , varargout{k} = sizes.bdXRSpacing; - case 'bdYSpacing' , varargout{k} = sizes.bdYSpacing; - case 'posLX_Txtinaxe' , varargout{k} = sizes.posLX_Txtinaxe; - case 'posRX_Txtinaxe' , varargout{k} = sizes.posRX_Txtinaxe; - case 'X_Graph_Ratio' , varargout{k} = sizes.X_Graph_Ratio; - case 'Win_WH_Ratio' , varargout{k} = sizes.Win_WH_Ratio; - case 'Win_Height' , varargout{k} = sizes.Win_Height; - case 'Win_Width' , varargout{k} = sizes.Win_Width; - case 'Win_Position' , varargout{k} = sizes.Win_Position; - case 'Cmd_Width' , varargout{k} = sizes.Cmd_Width; - case 'Fra_Width' , varargout{k} = sizes.Fra_Width; - case 'Def_AxeFontSize' , varargout{k} = sizes.axeFontSize; - case 'Def_TxtFontSize' , varargout{k} = sizes.txtFontSize; - case 'Def_UicFontSize' , varargout{k} = sizes.uicFontSize; - case 'Def_UicFtWeight' , varargout{k} = sizes.uicFontWeight; - case 'Def_AxeFtWeight' , varargout{k} = sizes.axeFontWeight; - case 'Def_TxtFtWeight' , varargout{k} = sizes.txtFontWeight; - case 'Lst_ColorMap' , varargout{k} = colors.lstColorMap; - case 'Def_UICBkColor' , varargout{k} = colors.uicBkColor; - case 'Def_TxtBkColor' , varargout{k} = colors.txtBkColor; - case 'Def_EdiBkColor' , varargout{k} = colors.ediBkColor; - case 'Def_Edi_ActBkColor' , varargout{k} = colors.ediActBkColor; - case 'Def_Edi_InActBkColor' , varargout{k} = colors.ediInActBkColor; - case 'Def_FraBkColor' , varargout{k} = colors.fraBkColor; - case 'Def_FigColor' , varargout{k} = colors.figColor; - case 'Def_DefColor' , varargout{k} = colors.defColor; - case 'Def_AxeColor' , varargout{k} = colors.axeColor; - case 'Def_AxeXColor' , varargout{k} = colors.axeXColor; - case 'Def_AxeYColor' , varargout{k} = colors.axeYColor; - case 'Def_AxeZColor' , varargout{k} = colors.axeZColor; - case 'Def_TxtColor' , varargout{k} = colors.txtColor; - case 'WTBX_Preferences' , ... - varargout{k} = Def_WGlob_Struct.preferences; - end - end - - case 'set' - if initFLAG , Def_WGlob_Struct = mextglob('ini'); end - nbin = nargin-1; - for k=1:2:nbin - switch varargin{k} - case 'ShiftTop_Fig' - Def_WGlob_Struct.sizes.figShiftTop = varargin{k+1}; - end - end - setappdata(0,'Def_WGlob_Struct',Def_WGlob_Struct); - if nargout>0 , varargout{1} = Def_WGlob_Struct; end - - otherwise , errargt(mfilename,'Unknown Option','msg'); -end -%-------------------------------------------------------------------------- -function Def_WGlob_Struct = Get_Def_WGlob_Struct(varargin) - -% Main Preference Mode. -%---------------------- -prefMode = varargin{1}; -switch prefMode - case {'default','d'} , prefMode = -1; - case {'k'} , prefMode = 1; - case {'w'} , prefMode = 2; - case {'r'} , prefMode = 4; - case {'b'} , prefMode = 5; - case {'g'} , prefMode = 6; - case {'y'} , prefMode = 7; - case {'s','std'} , prefMode = 'std'; -end - -% Defaults for colors. -%--------------------- -defColor = 'black'; -figColor = get(0,'DefaultFigureColor'); -fraBkColor = get(0,'DefaultUiPanelBackgroundColor'); -uicBkColor = get(0,'DefaultUicontrolBackgroundColor'); -uicFontSize = get(0,'DefaultUicontrolFontSize'); -ediBkColor = [1 1 1]; -ediActBkColor = [1 1 1]; -ediInActBkColor = [1 1 1]; -panTitleForColor = 'b'; -txtBkColor = 0.6*[1 1 1]; - -% Defaults for Main preferences. -%------------------------------- -preferences = struct(... - 'oldPrefDef',false, ... - 'figColor',figColor, ... - 'fraBkColor',fraBkColor, ... - 'ediBkColor',ediBkColor, ... - 'ediActBkColor',ediBkColor, ... - 'ediInActBkColor',ediBkColor, ... - 'panTitleForColor',panTitleForColor, ... - 'panFontName','Arial' , ... - 'panFontWeight','bold', ... - 'uicFontWeight','normal', ... - 'uicFontSize',uicFontSize ... - ); - -% Defaults for Fonts. -%-------------------- -noBold = true; % See noBold effect Below - -%------------------------------------------------------------- -% No checking of for inputs. -%---------------------------- -if nargin>1 , preferences.uicFontWeight = varargin{2}; end -if nargin>2 , preferences.panFontWeight = varargin{3}; end -%------------------------------------------------------------- - -% Set sizes preferences. -%----------------------- -scrSize = get(0,'ScreenSize'); -termProp = scrSize(3:4); -scrSize_STR =[int2str(termProp(1)) '_' int2str(termProp(2))]; - -% Default values. -figShiftTop = 50; -axeFontSize = 8; -txtFontSize = 8; -uicFontWeight = 'normal'; -axeFontWeight = 'normal'; -txtFontWeight = 'normal'; -txtHeight = 16; -sliYProp = 2/3; -Win_WH_Ratio = 4/3; -heightFACTOR = 1; -Scr_RATIO = (scrSize(3)./scrSize(4))/Win_WH_Ratio; -Win_WH_Ratio = Win_WH_Ratio*Scr_RATIO; - -switch scrSize_STR - case {'800_600','1024_600'} - btnHeight = 20; - btnWidth = 60; popWidth = 55; - xSpacing = 3; ySpacing = 2; - bdXLSpacing = 60; bdXRSpacing = 40; bdYSpacing = 20; - posLX_Txtinaxe = 42; posRX_Txtinaxe = 25; - fra_border = 2; - axeFontSize = 7; txtFontSize = 8; uicFontSize = 8; - - case '1182_864' - btnHeight = 20; btnWidth = 80; popWidth = 50; - xSpacing = 8; ySpacing = 5; - bdXLSpacing = 80; bdXRSpacing = 50; bdYSpacing = 80; - posLX_Txtinaxe = 48; posRX_Txtinaxe = 28; - fra_border = 6; - heightFACTOR = 1.05; - if isunix - axeFontSize = 10; txtFontSize = 10;uicFontSize = 10; - else - axeFontSize = 9; txtFontSize = 9; uicFontSize = 9; - end - - case {'1024_768','1280_720','1280_768','1280_800'} - btnHeight = 20; btnWidth = 80; popWidth = 50; - xSpacing = 8; ySpacing = 5; - bdXLSpacing = 80; bdXRSpacing = 50; bdYSpacing = 80; - posLX_Txtinaxe = 48; posRX_Txtinaxe = 28; - fra_border = 6; - uicFontSize = 8; - switch scrSize_STR - case '1280_720' - btnHeight = 20; ySpacing = 4; - heightFACTOR = 1.05; - Win_WH_Ratio = 5/3; - - case {'1280_768','1280_800'} - btnHeight = 20; ySpacing = 4; - heightFACTOR = 1.05; - Win_WH_Ratio = 5/3; - end - if isunix - axeFontSize = 10; txtFontSize = 10; uicFontSize = 10; - end - - case {'1280_1024','1280_960'} - btnHeight = 20; btnWidth = 80; popWidth = 50; - xSpacing = 8; ySpacing = 5; - bdXLSpacing = 80; bdXRSpacing = 50; bdYSpacing = 80; - posLX_Txtinaxe = 48; posRX_Txtinaxe = 28; - fra_border = 6; - axeFontSize = 9; txtFontSize = 9; uicFontSize = 9; - heightFACTOR = 1.175; - switch scrSize_STR - case '1280_1024' , Win_WH_Ratio = 1.35; - case '1280_960' , Win_WH_Ratio = 1.35; - end - - % case '1440_900' - - case '1600_1200' - btnHeight = 24; btnWidth = 85; popWidth = 60; - xSpacing = 9; ySpacing = 6; - bdXLSpacing = 80; bdXRSpacing = 80; bdYSpacing = 80; - posLX_Txtinaxe = 48; posRX_Txtinaxe = 28; - fra_border = 6; - if isunix - axeFontSize = 10; txtFontSize = 10;uicFontSize = 10; - else - axeFontSize = 9; txtFontSize = 9; uicFontSize = 9; - end - heightFACTOR = 1.2; - - otherwise - if scrSize(4)<=900 - btnHeight = 20; btnWidth = 80; popWidth = 50; - xSpacing = 8; ySpacing = 5; - bdXLSpacing = 80; bdXRSpacing = 50; bdYSpacing = 80; - posLX_Txtinaxe = 48; posRX_Txtinaxe = 28; - fra_border = 6; - heightFACTOR = 1.05; - if isunix - axeFontSize = 10; txtFontSize = 10;uicFontSize = 10; - else - axeFontSize = 9; txtFontSize = 9; uicFontSize = 9; - end - - elseif scrSize(4)<=1024 % DIM : [1280 x 1024] - btnHeight = 20; btnWidth = 80; popWidth = 50; - xSpacing = 8; ySpacing = 5; - bdXLSpacing = 80; bdXRSpacing = 50; bdYSpacing = 80; - posLX_Txtinaxe = 48; posRX_Txtinaxe = 28; - fra_border = 6; - if isunix - axeFontSize = 9; txtFontSize = 9; uicFontSize = 9; - else % DIM : [1280 x 1024] % DIM : [1280 x 960] - axeFontSize = 9; txtFontSize = 9; uicFontSize = 9; - end - heightFACTOR = 1.175; - - elseif scrSize(4)<=1200 % DIM : [1600 x 1200] - btnHeight = 24; btnWidth = 85; popWidth = 60; - xSpacing = 9; ySpacing = 6; - bdXLSpacing = 80; bdXRSpacing = 80; bdYSpacing = 80; - posLX_Txtinaxe = 48; posRX_Txtinaxe = 28; - fra_border = 6; - if isunix - axeFontSize = 10; txtFontSize = 10;uicFontSize = 10; - else - axeFontSize = 9; txtFontSize = 9; uicFontSize = 9; - end - heightFACTOR = 1.2; - - else - btnHeight = 24; btnWidth = 85; popWidth = 60; - xSpacing = 9; ySpacing = 6; - bdXLSpacing = 80; bdXRSpacing = 80; bdYSpacing = 80; - posLX_Txtinaxe = 48; posRX_Txtinaxe = 28; - fra_border = 6; - if isunix - axeFontSize = 10; txtFontSize = 10;uicFontSize = 10; - else - axeFontSize = 9; txtFontSize = 9; uicFontSize = 9; - end - heightFACTOR = 1.2; - end -end - -win_height = heightFACTOR*(21*btnHeight + 45*ySpacing); -win_width = Win_WH_Ratio*win_height; -win_left = scrSize(3)-5-win_width; -win_down = scrSize(4)-win_height-figShiftTop; -win_pos = [win_left , win_down , win_width , win_height]; -cmd_width = win_width*0.25; - -fra_width = cmd_width - 2*fra_border; -xGra_ratio = (win_width-cmd_width)/win_width; -bdXLSpacing = bdXLSpacing/scrSize(3); -bdXRSpacing = bdXRSpacing/scrSize(3); -bdYSpacing = bdYSpacing/scrSize(4); - -% NEW POSITION (WTBX 4.1); -win_pos(1:2) = win_pos(1:2)/2; -sizes = struct(... - 'figShiftTop', figShiftTop, ... - 'btnHeight', btnHeight, ... - 'btnWidth', btnWidth, ... - 'popWidth', popWidth, ... - 'xSpacing', xSpacing, ... - 'ySpacing', ySpacing, ... - 'bdXLSpacing', bdXLSpacing, ... - 'bdXRSpacing', bdXRSpacing, ... - 'bdYSpacing', bdYSpacing, ... - 'posLX_Txtinaxe',posLX_Txtinaxe, ... - 'posRX_Txtinaxe',posRX_Txtinaxe, ... - 'axeFontSize', axeFontSize, ... - 'txtFontSize', txtFontSize, ... - 'uicFontSize', uicFontSize, ... - 'uicFontWeight', uicFontWeight, ... - 'axeFontWeight', axeFontWeight, ... - 'txtFontWeight', txtFontWeight, ... - 'txtHeight', txtHeight, ... - 'sliYProp', sliYProp, ... - 'termProp', termProp, ... - 'Win_WH_Ratio', Win_WH_Ratio, ... - 'Win_Height', win_height, ... - 'Win_Width', win_width, ... - 'Win_Position', win_pos, ... - 'Cmd_Width', cmd_width, ... - 'Fra_Width', fra_width, ... - 'X_Graph_Ratio', xGra_ratio ... - ); - -% Set colors preferences. -%------------------------ -iP = 4; -switch prefMode - case -1 %'default' - defColor = 'white'; - ediInActBkColor = (figColor + fraBkColor)/2; - panTitleForColor = 'b'; - txtBkColor = 0.7*[1 1 1]; - - case 0 - - case {1,'black'} - defColor = 'black'; - figColor = [0 0 0]; - ediInActBkColor = (figColor + fraBkColor)/1.2; - panTitleForColor = 'y'; - - case {2,'white'} - defColor = 'white'; - figColor = [1 1 1]; - ediInActBkColor = (figColor + fraBkColor)/2.5; - panTitleForColor = 'b'; - txtBkColor = [247/255 247/255 247/255]; - - case {3,'oldDefaut'} % Old default - figColor = [0.5 0.5 0.5]; - panTitleForColor = [0 0 1]; - preferences.oldPrefDef = true; - - case num2cell(iP:iP+3) % IP = 4 (mode 4,5,6,7) - defColor = 'white'; - switch prefMode - case iP - figColor = [0.99 0.91 0.79]; - panTitleForColor = 'r'; - case iP+1 - figColor = [0.70 0.78 1.00]; - panTitleForColor = 'b'; - case {iP+2} - figColor = [0.86 1 0.86]; - panTitleForColor = [0 0.8 0]; - case {iP+3} - figColor = [1 1 0.75]; - panTitleForColor = [0 0 1]; - end - fraBkColor = figColor/1.25; - ediInActBkColor = (figColor + fraBkColor)/2; - txtBkColor = [247/255 247/255 247/255]; - - case num2cell(iP+4:iP+7) % IP = 4 (mode 8,9,10,11) - defColor = 'black'; - switch prefMode - case {iP+4} - figColor = [0.4 0.27 0.27]; panTitleForColor = [1 0.5 0.5]; - case {iP+5} - figColor = [0.27 0.4 0.27]; panTitleForColor = [0.5 1 0.5]; - case {iP+6} - figColor = [0.20 0.30 0.50]; panTitleForColor = [0.7 0.7 1]; - case {iP+7} - figColor = [0.7 0.3 0.2]; panTitleForColor = [1 1 0.5]; - end - fraBkColor = max(min(figColor*2.5,1),panTitleForColor); - ediInActBkColor = (figColor + fraBkColor)/2; - txtBkColor = [247/255 247/255 247/255]; - - case {12,13,14} - switch prefMode - case 12 , figColor = [0.3 0.4 0.5]; panTitleForColor = figColor*1.75; - case 13 , figColor = [0.5 0.3 0.2]; panTitleForColor = [1 0.5 0.5]; - case 14 , figColor = [0.3 0.5 0.2]; panTitleForColor = [0 0.2 0]; - end - fraBkColor = figColor*1.75; - ediInActBkColor = (figColor + fraBkColor)/1.75; - - case {15,16} - defColor = 'white'; - switch prefMode - case 15 , figColor = [0.9 0.9 0.9]; panTitleForColor = 'r'; - case 16 , figColor = [0.7 0.7 0.7]; panTitleForColor = 'b'; - end - fraBkColor = figColor/1.25; - ediInActBkColor = (figColor + fraBkColor)/2; - txtBkColor = [247/255 247/255 247/255]; - - case 17 - defColor = 'black'; - figColor = [0.35 0.35 0.35]; panTitleForColor = 'y'; - fraBkColor = figColor*2.5; - ediInActBkColor = (figColor + fraBkColor)/2; - txtBkColor = [247/255 247/255 247/255]; - - case 'test' - defColor = 'black'; - figColor = [0.4 0.27 0.27]; - fraBkColor = figColor*2.5; - ediInActBkColor = (figColor + fraBkColor)/2; - panTitleForColor = [1 0.5 0.5]; - txtBkColor = [247/255 247/255 247/255]; - - case {'std'} - txtBkColor = [0.90 0.90 0.90]; - fraBkColor = [0.77 0.77 0.77]; -end - -if isequal(defColor,'black') , - axeColor = [0 0 0]; txyz_Color = 'w'; -else - axeColor = [1 1 1]; txyz_Color = 'k'; -end -colors.defColor = defColor; -colors.figColor = figColor; -colors.fraBkColor = fraBkColor; -colors.ediBkColor = ediBkColor; -colors.ediActBkColor = ediActBkColor; -colors.ediInActBkColor = ediInActBkColor; -colors.uicBkColor = uicBkColor; -colors.txtBkColor = txtBkColor; -colors.lstColorMap = ... - {... - 'pink','cool','gray','hot','jet','bone', ... - 'copper','hsv','prism','1 - pink','1 - cool', ... - '1 - gray','1 - hot','1 - jet','1 - bone', ... - 'autumn ','spring','winter','summer' ... - }; -colors.axeColor = axeColor; -colors.axeXColor = txyz_Color; -colors.axeYColor = txyz_Color; -colors.axeZColor = txyz_Color; -colors.txtColor = txyz_Color; - -% Set bold preferences. -%---------------------- -if nargin>1 && ~isequal(varargin{2},'normal') , noBold = false; end -if noBold , fontWeight = 'normal'; else fontWeight ='bold'; end -sizes.uicFontWeight = fontWeight; -sizes.axeFontWeight = fontWeight; -sizes.txtFontWeight = fontWeight; - -% Set main preferences. -%---------------------- -preferences.figColor = figColor; -preferences.fraBkColor = fraBkColor; -preferences.ediBkColor = ediBkColor; -preferences.ediActBkColor = ediActBkColor; -preferences.ediInActBkColor = ediInActBkColor; -preferences.panTitleForColor = panTitleForColor; -preferences.uicFontSize = sizes.uicFontSize; -preferences.uicFontWeight = sizes.uicFontWeight; - -Def_WGlob_Struct = struct('initMode',prefMode, ... - 'preferences',preferences,'sizes',sizes,'colors',colors); -%-------------------------------------------------------------------------- diff --git a/WaveletFunctions/scal2frq.m b/WaveletFunctions/scal2frq.m deleted file mode 100644 index 1f069fe..0000000 --- a/WaveletFunctions/scal2frq.m +++ /dev/null @@ -1,16 +0,0 @@ -function f = scal2frq(a,wname,delta) -%SCAL2FRQ Scale to frequency. -if isempty(a) , f = a; return; end -if nargin == 2, delta = 1; end -err = (min(size(a))>1) | (min(a)0 , varargout{1} = Wavelets_Info; end - - case 'clear' - if isappdata(0,'WTBX_Glob_Info') - rmappdata(0,'WTBX_Glob_Info'); - end - if isappdata(0,'Def_WGlob_Struct') - rmappdata(0,'Def_WGlob_Struct'); - end - if isappdata(0,'Wavelets_Info') , rmappdata(0,'Wavelets_Info'); end - if isappdata(0,'DWT_Attribute') , rmappdata(0,'DWT_Attribute'); end - - case 'wavelets' - tfsn = wavemngr('tfsn'); - varargout{1} = deblank(num2cell(tfsn,2)); - - case 'indw' - % in2 : wavelet name - %------------------- - % out1 = i_fam - % out2 = i_num - % out3 = fam - % out4 = num_str - % out5 = tabNums - % out6 = flag '**' (for GUI) - %--------------------------- - nb_fam = size(Wavelets_Info,1); - wname = deblankl(varargin{1}); - lwna = length(wname); - for i_fam=1:nb_fam - fam = Wavelets_Info(i_fam).familyShortName; - len = length(fam); - ok_wave = 0; - if lwna>=len - if fam==wname(1:len) - tabNums = Wavelets_Info(i_fam).tabNums; - for i_num = 1:size(tabNums,1) - num_str = noblank(tabNums(i_num,:)); - if strcmp(num_str,'no') , num_str = '' ; end - if strcmp([fam num_str],wname) - ok_wave = 1; add_num = 0; break; - end - end - - % test for ** number - %------------------ - if ok_wave==0 && strcmp(num_str,'**') && (lwna>len) - typNums = Wavelets_Info(i_fam).typNums; - num_str = wname(len+1:lwna); - switch typNums - case 'integer' - num = wstr2num(num_str); - if ~isempty(num) && (num==fix(num)) && (0 - if nargin==2 - wtype = lower(varargin{1}); - if isequal(wtype,'all') , return; end - tab_type = {Wavelets_Info(:).type}'; - tab_type = cat(1,tab_type{:}); - switch wtype - case {'dwt'} , ind = find(tab_type==1 | tab_type==2); - case {'cwt'} , ind = find(tab_type>0 & tab_type<5); - case {'owt'} , ind = find(tab_type==1); - case {'ccwt'} , ind = find(tab_type==5); - case {'666'} - ind = [find(tab_type==5) ; find(tab_type>0 & tab_type<5)]; - end - varargout{1} = varargout{1}(ind,:); - end - - case 'tfn' - fnCell = {Wavelets_Info(:).familyName}'; - varargout{1} = strvcat(fnCell{:}); %#ok - if nargin==2 - wtype = lower(varargin{1}); - if isequal(wtype,'all') , return; end - tab_type = {Wavelets_Info(:).type}'; - tab_type = cat(1,tab_type{:}); - switch wtype - case {'dwt'} , ind = find(tab_type==1 | tab_type==2); - case {'cwt'} , ind = find(tab_type>0 & tab_type<5); - case {'owt'} , ind = find(tab_type==1); - case {'ccwt'} , ind = find(tab_type==5); - end - varargout{1} = varargout{1}(ind,:); - end - - case 'fields' - % in2 = {'ind', wavelet index} or - % in2 = {'fsn', family shortname} or - % in2 = {'wn' , wavelet name} - % or - % in2 = wavelet name - %---------------------------- - % in3 ... = field(s) name(s) - %---------------------------- - % out1 ... = field(s) value(s) - %----------------------------- - if iscell(varargin{1}) - in_type = varargin{1}{1}; - arg = varargin{1}{2}; - else - in_type = 'wn'; - arg = varargin{1}; - end - switch in_type - case 'ind' - if isempty(Wavelets_Info) - Wavelets_Info = wavemngr('load'); - end - i_fam = arg; - - case 'fsn' , i_fam = wavemngr('indf',arg); - case 'wn' , i_fam = wavemngr('indw',arg); - end - nb = nargin-2; - if nb==0 - varargout{1} = Wavelets_Info(i_fam); - return; - end - for k=1:nb - switch varargin{k+1} - case 'ind' , field = 'index'; - case 'fn' , field = 'familyName'; - case 'fsn' , field = 'familyShortName'; - case 'type' , field = 'type'; - case 'tabNums' , field = 'tabNums'; - case 'typNums' , field = 'typNums'; - case 'file' , field = 'file'; - case 'bounds' , field = 'bounds'; - otherwise , field = ''; - end - if ~isempty(field) - varargout{k} = Wavelets_Info(i_fam).(field); - else - varargout{k} = Wavelets_Info(i_fam); - end - end - - case 'type' - i_fam = wavemngr('indw',varargin{1}); - varargout{1} = Wavelets_Info(i_fam).('type'); - - case 'file' - i_fam = wavemngr('indw',varargin{1}); - varargout{1} = Wavelets_Info(i_fam).('file'); - - case 'fn' - i_fam = wavemngr('indw',varargin{1}); - varargout{1} = Wavelets_Info(i_fam).('familyName'); - - case 'fsn' - i_fam = wavemngr('indw',varargin{1}); - varargout{1} = Wavelets_Info(i_fam).('familyShortName'); - - case {'tabnums','tabNums'} - i_fam = wavemngr('indf',varargin{1}); - varargout{1} = Wavelets_Info(i_fam).('tabNums'); - - case {'typNums'} - i_fam = wavemngr('indf',varargin{1}); - varargout{1} = Wavelets_Info(i_fam).('typNums'); - - case 'bounds' - i_fam = wavemngr('indw',varargin{1}); - varargout{1} = Wavelets_Info(i_fam).('bounds'); - - case 'isbior' - wname = varargin{1}; - if length(wname)>3, - wname = wname(1:4); - varargout{1} = isequal(wname,'bior') | isequal(wname,'rbio'); - else - varargout{1} = 0; - end - - case 'fam_num' - [~,~,varargout{1},varargout{2}] = wavemngr('indw',varargin{1}); - - case 'length' - wname = varargin{1}; - [wtype,bounds] = wavemngr('fields',{'wn',wname},'type','bounds'); - switch wtype - case {1,2} - Lo_D = wfilters(wname); - varargout{1} = length(Lo_D); - case {3,4} - varargout{1} = bounds(2)-bounds(1)+1; - otherwise - errargt(mfilename,'invalid argument','msg'); - error('Wavelet:Invalid_ArgVal_Or_ArgType', ... - 'Invalid argument value.'); - end - - case 'create' - wavemngr('clear') - beg_fam = 'Family Name : '; - fid = fopen(asc_file); - if fid==-1 - fid = fopen(asc_ini_file); - winfo = fread(fid); - fclose(fid); - fid = fopen(asc_file,'w'); - fwrite(fid,winfo); - fclose(fid); - else - winfo = fread(fid); - fclose(fid); - end - winfo = char(winfo'); - str_NL = findNL('string',winfo); - lennewl = length(str_NL); - ind_NL = findstr(str_NL,winfo); - first = findstr(beg_fam,winfo)+length(beg_fam); - nb_fam = length(first); - - %------------------------------% - % Building Wavelets Structure. % - %------------------------------% - nul = cell(nb_fam,1); - Wavelets_Info = struct(... - 'index',nul, ... - 'familyName',nul, ... - 'familyShortName',nul, ... - 'type',nul, ... - 'tabNums',nul, ... - 'typNums',nul, ... - 'file',nul, ... - 'bounds',nul ... - ); - - for j = 1:nb_fam - i_fam = first(j); - indexs = find(ind_NL>i_fam); - indexs = ind_NL(indexs(1:nb_InfoByWave)); - fam = winfo(i_fam:indexs(1)-1); - sname = winfo(indexs(1)+lennewl:indexs(2)-1); - wtype = winfo(indexs(2)+lennewl:indexs(3)-1); - nums = winfo(indexs(3)+lennewl:indexs(4)-1); - typNums = winfo(indexs(4)+lennewl:indexs(5)-1); - fname = winfo(indexs(5)+lennewl:indexs(6)-1); - bounds = winfo(indexs(6)+lennewl:indexs(7)-1); - - notspace = ~isspace(nums); - lnot = length(notspace); - index1 = find(notspace==1); - k0 = index1(1); - k1 = index1(length(index1)); - indnum = diff(notspace); - fnum = find(indnum==1)+1; - lnum = find(indnum==-1); - if k0==1 , fnum = [1 fnum]; end %#ok - if k1==lnot , lnum = [lnum k1]; end %#ok - nb_num = length(fnum); - tabNums = ''; - for p = 1:nb_num - tabNums = strvcat(tabNums,nums(fnum(p):lnum(p))); %#ok - end - - Wavelets_Info(j).index = j; - Wavelets_Info(j).familyName = fam; - Wavelets_Info(j).familyShortName = sname; - Wavelets_Info(j).type = wstr2num(wtype); - Wavelets_Info(j).tabNums = tabNums; - Wavelets_Info(j).typNums = typNums; - Wavelets_Info(j).file = fname; - Wavelets_Info(j).bounds = wstr2num(bounds); - end - try - save(bin_file,'Wavelets_Info') - catch %#ok<*CTCH> - errargt(mfilename,'Changing Wavelets : Save FAILED !','msg'); - end - - case 'read' - nb_fam = size(Wavelets_Info,1); - sep_fam = '='; - sep_fam = sep_fam(:,ones(1,35)); - sep_num = '-'; - sep_num = sep_num(:,ones(1,30)); - varargout{1} = sep_fam; - tab = char(9); - - families = strvcat(Wavelets_Info(:).familyName); %#ok - tabtab = tab(ones(1,nb_fam),ones(1,2)); - - if nargin==1 - famSName = strvcat(Wavelets_Info(:).familyShortName); %#ok - famTAB = [families tabtab famSName]; - varargout{1}= strvcat(varargout{1},famTAB,sep_fam); %#ok - else - famTAB = [families tabtab]; - for k =1:nb_fam - sfname = Wavelets_Info(k).familyShortName; - varargout{1} = strvcat(varargout{1},[famTAB(k,:) sfname]); %#ok - nb = 0; - wnames = []; - tabNums = Wavelets_Info(k).tabNums; - if size(tabNums,1)>1 - varargout{1} = strvcat(varargout{1},sep_num); %#ok - end - for j = 1:size(tabNums,1) - num_str = noblank(tabNums(j,:)); - if ~strcmp(num_str,'no') - wnames = [wnames sfname noblank(tabNums(j,:)) tab]; %#ok - end - if nb<3 - nb = nb+1; - else - if ~isempty(wnames) - varargout{1} = strvcat(varargout{1},wnames); %#ok - end - nb = 0; - wnames = []; - end - end - if nb>0 && ~isempty(wnames) - varargout{1} = strvcat(varargout{1},wnames); %#ok - end - varargout{1} = strvcat(varargout{1},sep_fam); %#ok - end - end - - case 'read_asc' - fid = fopen(asc_file); - if fid==-1 , fid = fopen(asc_ini_file); end - winfo = fread(fid); - fclose(fid); - idxNL = find(winfo==10,2,'first'); - if isempty(idxNL) - idxNL = find(winfo==13,2,'first'); - end - winfo = winfo(idxNL(2)+1:end); - varargout{1} = char(winfo'); - - case 'read_struct' - if nargin==2 - indfam = varargin{1}; - else - nb_fam = size(Wavelets_Info,1); - indfam = 1:nb_fam; - end - if nargout==0 - sep_fam = '*'; - sep_fam = sep_fam(:,ones(1,35)); - disp(' '); disp(' '); disp(' '); - disp(sep_fam); - end - for k =1:length(indfam) - tmp{k} = Wavelets_Info(indfam(k)); %#ok - if nargout==0 - disp(tmp{k}); disp(sep_fam); - end - end - if nargout>0 , varargout = tmp; end - - case 'add' - wavemngr('clear') - Wavelets_Info = wavemngr('load'); - family_Name = varargin{1}; - if isempty(family_Name) - err = 1; - msg = 'Wavelet Family Name is empty !'; - else - fnIn = noblank(family_Name); - tmpCell = {Wavelets_Info(:).familyName}'; - ind = find(strcmp(fnIn,tmpCell)==1,1); - err = ~isempty(ind); - if err , msg = 'The Wavelet Family Name is already used !'; end - end - - if err==0 - family_Short_Name = varargin{2}; - if isempty(family_Short_Name) - err = 1; - msg = 'Wavelet Family Short Name is empty !'; - else - fsnIn = deblankl(family_Short_Name); - tmpCell = {Wavelets_Info(:).familyShortName}'; - ind = find(strcmp(fsnIn,tmpCell)==1,1); - err = ~isempty(ind); - if err - msg = 'The Wavelet Family Short Name is already used !'; - end - end - end - - if err==0 - wavelet_Type = varargin{3}; - if isempty(find(wavelet_Type==WaveTypePOS,1)) - err = 1; - msg = 'Invalid Wavelet Type !'; - end - end - - if err==0 - if isempty(varargin{4}) - wavelet_tabNums = 'no'; - wavelet_typNums = 'no'; - elseif ischar(varargin{4}) - wavelet_tabNums = deblank(varargin{4}); - wavelet_typNums = 'integer'; - elseif iscell(varargin{4}) - wavelet_tabNums = deblank(varargin{4}{1}); - wavelet_typNums = deblank(varargin{4}{2}); - if ischar(wavelet_typNums) - switch wavelet_typNums - case {'integer','real','string'} - otherwise - err = 1; - msg = 'Invalid Wavelet type of numbers !'; - end - else - err = 1; - msg = 'Invalid Wavelet type of numbers !'; - end - - else - err = 1; - msg = 'Invalid Wavelet numbers !'; - end - end - - if err==0 - wavelet_File = varargin{5}; - if isempty(wavelet_File) - err = 1; - elseif findstr('.mat',wavelet_File) - - else - wavelet_File = deblankl(wavelet_File); - ind = findstr('.m',wavelet_File); - if ind>0 , wavelet_File = wavelet_File(1:ind-1); end - if isempty(wavelet_File) , err = 1; end - end - if err==1 - msg = 'Invalid Wavelet File Name !'; - end - end - if err==0 - nbArgIN = length(varargin); - switch wavelet_Type - case {1,2} - if nbArgIN<6 , wavelet_Bounds = ''; - else - wavelet_Bounds = varargin{6}; - end - - otherwise - if nbArgIN<6 - err = 1; - msg = 'Invalid number of arguments !'; - else - wavelet_Bounds = varargin{6}; - if length(wavelet_Bounds)~=2, err = 1; - elseif wavelet_Bounds(1)>wavelet_Bounds(2), err = 1; - end - if err==1 - msg = 'Invalid value for wavelet bounds !'; - end - end - end - end - if err - msg = strvcat('Add New Wavelet FAILED !!',msg); %#ok - errargt(mfilename,msg,'msg'); - return - end - - fid = fopen(asc_file); - if fid==-1 , fid = fopen(asc_ini_file); end - winfo = fread(fid); - fclose(fid); - fid = fopen(sav_file,'w'); - fwrite(fid,winfo); - fclose(fid); - - Chrline = findNL('char',winfo); - beg_fam = 'Family Name : '; - sep_fam = '------------------------'; - - wavelet_Type = sprintf('%.0f',wavelet_Type); - if ~isempty(wavelet_Bounds) - wavelet_Bounds = [num2str(wavelet_Bounds(1)) ' ' ... - num2str(wavelet_Bounds(2))]; - end - - winfo = [winfo(1:end-1); Chrline; ... - abs(beg_fam'); ... - abs(family_Name(:)); Chrline; ... - abs(family_Short_Name(:)); Chrline; ... - abs(wavelet_Type(:)); Chrline; ... - abs(wavelet_tabNums(:)); Chrline; ... - abs(wavelet_typNums(:)); Chrline; ... - abs(wavelet_File(:)); Chrline; ... - abs(wavelet_Bounds(:)); Chrline; ... - abs(sep_fam'); Chrline ... - ]; - - fid = fopen(asc_file,'w'); - fwrite(fid,winfo); - fclose(fid); - wavemngr('create'); - - case 'del' - wavemngr('clear') - Wavelets_Info = wavemngr('load'); - err = 0; - i_fam = []; - if isempty(varargin{1}) - err = 1; - msg = 'Wavelet Family (Short) Name is empty !'; - else - name = noblank(varargin{1}); - tmpCell = {Wavelets_Info(:).familyName}'; - i_fam = find(strcmp(name,tmpCell)==1); - if isempty(i_fam) - tmpCell = {Wavelets_Info(:).familyShortName}'; - i_fam = find(strcmp(name,tmpCell)==1); - end - end - - if err==0 - if isempty(i_fam) - err = 1; - msg = 'Invalid Wavelet Family (Short) Name !'; - elseif i_fam<=NB_FamInWTB - err = 1; - fn = Wavelets_Info(i_fam).familyName; - msg = sprintf('You can''t delete %s Wavelet Family !',fn); - end - end - if err - errargt(mfilename,msg,'msg'); - return - end - - fid = fopen(asc_file); - if fid==-1 , fid = fopen(asc_ini_file); end - winfo = fread(fid); - fclose(fid); - fid = fopen(sav_file,'w'); - fwrite(fid,winfo); - fclose(fid); - - str_winfo = char(winfo'); - str_NL = findNL('string',winfo); - beg_fam = 'Family Name : '; - first = findstr(beg_fam,str_winfo); - first = first(i_fam); - ind_NL = findstr(str_NL',str_winfo); - indexs = find(ind_NL>first); - indexs = ind_NL(indexs(1:nb_InfoByWave+1)); - last = indexs(nb_InfoByWave+1)+length(str_NL)-1; - - winfo(first:last) = []; - fid = fopen(asc_file,'w'); - fwrite(fid,winfo); - fclose(fid); - wavemngr('create'); - - case 'restore' - wavemngr('clear') - if nargin==1 - fid = fopen(sav_file); - if fid==-1 , fid = fopen(asc_ini_file); end - else - fid = fopen(asc_ini_file); - end - winfo = fread(fid); - fclose(fid); - fid = fopen(asc_file,'w'); - fwrite(fid,winfo); - fclose(fid); - wavemngr('create'); - - case 'rescue' - famtype = ... - {... - 1, 'Haar', 'haar', 1; - 2, 'Daubechies', 'db', 1; - 3, 'Symlets', 'sym', 1; - 4, 'Coiflets', 'coif', 1; - 5, 'BiorSplines', 'bior', 2; - 6, 'ReverseBior', 'rbio', 2; - 7, 'Meyer', 'meyr', 3; - 8, 'DMeyer', 'dmey', 1; - 9, 'Gaussian', 'gaus', 4; - 10, 'Mexican_hat', 'mexh', 4; - 11, 'Morlet', 'morl', 4; - 10, 'Complex Gaussian', 'cgau', 5; - 11, 'Shannon', 'shan', 5; - 10, 'Frequency B-Spline', 'fbsp', 5; - 11, 'Complex Morlet', 'cmor', 5 - - }; - - nums = ... - {... - ''; - '1 2 3 4 5 6 7 8 9 10 **'; - '2 3 4 5 6 7 8 **'; - '1 2 3 4 5'; - '1.1 1.3 1.5 2.2 2.4 2.6 2.8 3.1 3.3 3.5 3.7 3.9 4.4 5.5 6.8'; - '1.1 1.3 1.5 2.2 2.4 2.6 2.8 3.1 3.3 3.5 3.7 3.9 4.4 5.5 6.8'; - ''; - ''; - '1 2 3 4 5 6 7 8 **'; - ''; - ''; - '1 2 3 4 5 **'; - '1-1.5 1-1 1-0.5 1-0.1 2-3 **'; - '1-1-1.5 1-1-1 1-1-0.5 2-1-1 2-1-0.5 2-1-0.1 **'; - '1-1.5 1-1 1-0.5 1-1 1-0.5 1-0.1 **' - }; - - typNums = ... - {... - 'no'; - 'integer'; - 'integer'; - 'integer'; - 'real'; - 'real'; - 'no'; - 'no'; - 'integer'; - 'no'; - 'no'; - 'integer'; - 'string'; - 'string'; - 'string' - }; - - files = ... - {... - 'dbwavf'; - 'dbwavf'; - 'symwavf'; - 'coifwavf'; - 'biorwavf'; - 'rbiowavf'; - 'meyer'; - 'dmey.mat'; - 'gauswavf'; - 'mexihat'; - 'morlet' - 'cgauwavf'; - 'shanwavf'; - 'fbspwavf'; - 'cmorwavf' - }; - - bounds = ... - {... - []; - []; - []; - []; - []; - []; - [-8 8]; - []; - [-5 5]; - [-8 8]; - [-8 8]; - [-5 5]; - [-20 20]; - [-20 20]; - [-8 8] - }; - - nbfam = size(famtype,1); - tabNums = cell(nbfam,1); - for k = 1:nbfam - tabNums{k} = ''; - s = deblank(nums{k}); - if ~isempty(s) - I = find(isspace(s)); - i_beg = 1; - for j = 1:length(I) - i_end = I(j)-1; - ss = deblank(s(i_beg:i_end)); - if ~isempty(ss) - tabNums{k} = strvcat(tabNums{k},ss); %#ok - end - i_beg = i_end+2; - end - ss = deblank(s(i_beg:end)); - tabNums{k} = strvcat(tabNums{k},ss); %#ok - end - if isempty(tabNums{k}) , tabNums{k} = 'no'; end - end - - varargout{1} = ... - struct(... - 'index', famtype(:,1), ... - 'familyName', famtype(:,2), ... - 'familyShortName', famtype(:,3), ... - 'type', famtype(:,4), ... - 'tabNums', tabNums, ... - 'typNums', typNums, ... - 'file', files, ... - 'bounds', bounds ... - ); - - otherwise - errargt(mfilename,'Unknown Option','msg'); - error('Wavelet:Invalid_ArgVal_Or_ArgType', ... - 'Invalid argument value.'); -end - -%----------------------------------% -% Internal Function(s) % -%----------------------------------% -function nl = findNL(opt,txt) -%FINDNL Find New Line char or string. - -ind10 = find(txt==10,1); -ind13 = find(txt==13,1); -if isempty(ind13) , - nl = 10; -elseif isempty(ind10) - nl = 13; -else - nl = [13;10]; -end -if isequal(opt,'string') - nl = char(nl); -end -if size(txt,2)>1 , nl = nl'; end -%----------------------------------% -function s = noblank(x) -%NOBLANK Removes blanks in a string. - -if ~isempty(x) - s = x(x~=' ' & x~=0); -else - s = ''; -end -%----------------------------------% \ No newline at end of file diff --git a/WaveletFunctions/wconv1.m b/WaveletFunctions/wconv1.m deleted file mode 100644 index 2c11956..0000000 --- a/WaveletFunctions/wconv1.m +++ /dev/null @@ -1,15 +0,0 @@ -function y = wconv1(x,f,shape) -%WCONV1 1-D Convolution. -% Y = WCONV1(X,F) performs the 1-D convolution of the -% vectors X and F. -% Y = WCONV1(...,SHAPE) returns a subsection of the -% convolution with size specified by SHAPE (See CONV2). - - -if nargin<3 - shape = 'full'; -end -y = conv2(x(:)',f(:)',shape); -if size(x,1)>1 - y = y'; -end diff --git a/WaveletFunctions/wkeep1.m b/WaveletFunctions/wkeep1.m deleted file mode 100644 index 3e47029..0000000 --- a/WaveletFunctions/wkeep1.m +++ /dev/null @@ -1,50 +0,0 @@ -function y = wkeep1(x,len,varargin) -%WKEEP1 Keep part of a vector. -% -% Y = WKEEP1(X,L,OPT) extracts the vector Y -% from the vector X. The length of Y is L. -% If OPT = 'c' ('l' , 'r', respectively), Y is the central -% (left, right, respectively) part of X. -% Y = WKEEP1(X,L,FIRST) returns the vector X(FIRST:FIRST+L-1). -% -% Y = WKEEP1(X,L) is equivalent to Y = WKEEP1(X,L,'c'). - -nbIn = nargin; -msg = nargchk(2,4,nbIn); -if ~isempty(msg) - error('Wavelet:FunctionInput:NbArg',msg) -end -if (len ~= fix(len)) - error('Wavelet:FunctionArgVal:Invalid_ArgVal',... - 'Invalid argument value %s.','Arg2'); -end - -y = x; -sx = length(x); -ok = (len >= 0) && (len < sx); -if ~ok , return; end - -if nbIn<3 , OPT = 'c'; else OPT = lower(varargin{1}); end -if ischar(OPT) - switch OPT - case 'c' - if nbIn<4 , side = 0; else side = varargin{2}; end - d = (sx-len)/2; - switch side - case {'u','l','0',0} , - first = 1+floor(d); last = sx-ceil(d); - case {'d','r','1',1} , - first = 1+ceil(d); last = sx-floor(d); - end - - case {'l','u'} , first = 1; last = len; - case {'r','d'} , first = sx-len+1; last = sx; - end -else - first = OPT; last = first+len-1; - if (first ~= fix(first)) || (first<1) || (last>sx) - error('Wavelet:FunctionArgVal:Invalid_ArgVal', ... - 'Invalid argument value.'); - end -end -y = y(first:last); diff --git a/WaveletFunctions/wstr2num.m b/WaveletFunctions/wstr2num.m deleted file mode 100644 index 5f1eebe..0000000 --- a/WaveletFunctions/wstr2num.m +++ /dev/null @@ -1,25 +0,0 @@ -function x = wstr2num(s) -%WSTR2NUM Convert string to number. -% X = WSTR2NUM(S) converts the string S, which should be an -% ASCII character representation of a numeric value, to MATLAB's -% numeric representation. The string may contain digits, a decimal -% point, a leading + or - sign, an 'e' preceding a power of 10 scale -% factor, and an 'i' for a complex unit. -% -% WSTR2NUM converts a character array representation of a matrix of -% numbers to a numeric matrix. For example, -% -% A = ['1 2' wstr2num(A) => [1 2;3 4] -% '3 4'] - -% produces x = [1 2i]. -% -% See also NUM2STR, HEX2NUM, CHAR. - -% M. Misiti, Y. Misiti, G. Oppenheim, J.M. Poggi 16-Apr-98. -% Last Revision: 01-May-1998. -% Copyright 1995-2002 The MathWorks, Inc. -% $Revision: 1.8 $ $Date: 2002/04/14 19:38:16 $ - -% Mask for str2num (later we use str2double). -x = str2num(s); diff --git a/byHand/BTA_by_hand.m b/byHand/BTA_by_hand.m deleted file mode 100644 index fd3a23c..0000000 --- a/byHand/BTA_by_hand.m +++ /dev/null @@ -1,150 +0,0 @@ -function [ femaletimes_BTA, BTAtimes_Mperm, BTAtimes_Fperm ] = BTA_by_hand( maletimes, femaletimes , channels, numperms); -%UNTITLED Summary of this function goes here -% Detailed explanation goes here - - channel_num=length(channels); - BTAtimes=cell(1,channel_num); - BTAtimes_Mperm=cell(1,channel_num); - BTAtimes_Fperm=cell(1,channel_num); - - for i=1:channel_num; - - - femalepulses= femaletimes{i}; - - malebouts= maletimes{i}; - if ~isempty(malebouts) && ~isempty(femalepulses); - - BTAtimes{i}=NaN(100,length(malebouts(:,1))); - BTAtimes_Mperm{i}=NaN(100,length(malebouts(:,1))*numperms); - BTAtimes_Fperm{i}=NaN(100,length(malebouts(:,1))*numperms); - - j=1; - for n=2:(size(malebouts,1)-1); - a=round(malebouts(n,1)); - aa=round(malebouts(n,2)); - center=(aa+a)/2; - x=find(femalepulses<(center+2000)& femalepulses>center & femalepulses<(round(malebouts(n+1,1)))); - xx= find(femalepulses>(center-2000)& femalepulses
(round(malebouts(n-1,2)))); - if isempty(xx) && isempty(x) - continue - else - - if isempty(xx) && ~isempty(x) - c=round(femalepulses(x))-center; - BTAtimes{i}(1:length(c),j)=c; - j=j+1; - end - if ~isempty(xx) && isempty(x); - c=round(femalepulses(xx))-center; - BTAtimes{i}(1:length(c),j)=c; - j=j+1; - end - if ~isempty(xx) && ~isempty(x); - c=round(femalepulses(x))-center; - cc=round(femalepulses(xx))-center; - final=vertcat(c,cc); - BTAtimes{i}(1:length(final),j)=final; - j=j+1; - - end - end - end - -%randomize both or true randomization? - for z=1:numperms; %randomize female -% num_pulses=length(femalepulses); -% femalepulses_perm=rand(num_pulses,1)*max(femalepulses); - femaleIPI=diff(femalepulses); - femaleIPI_perm = randperm(length(femaleIPI)); %shuffling IPIs - femalepulses_perm = cumsum(femaleIPI(femaleIPI_perm)); -% - j=1; - for n=2:(size(malebouts,1)-1); - a=round(malebouts(n,1)); - aa=round(malebouts(n,2)); - center=(aa+a)/2; - x=find(femalepulses_perm<(center+2000)& femalepulses_perm>center & femalepulses_perm<(round(malebouts(n+1,1)))); - xx= find(femalepulses_perm>(center-2000)& femalepulses_perm
(round(malebouts(n-1,2)))); - if isempty(xx) && isempty(x) - continue - else - - if isempty(xx) && ~isempty(x) - c=round(femalepulses(x))-center; - BTAtimes_Fperm{i}(1:length(c),j)=c; - j=j+1; - end - if ~isempty(xx) && isempty(x); - c=round(femalepulses(xx))-center; - BTAtimes_Fperm{i}(1:length(c),j)=c; - j=j+1; - end - if ~isempty(xx) && ~isempty(x); - c=round(femalepulses(x))-center; - cc=round(femalepulses(xx))-center; - final=vertcat(c,cc); - BTAtimes_Fperm{i}(1:length(final),j)=final; - j=j+1; - - end - end - end - end -j=1; - for z=1:numperms; %randomize male -% num_bouts=length(malebouts(:,1)); -% malebouts_perm=rand(num_bouts,1)*max(malebouts(:,1)); - MBL=round(diff(maletimes{i},1,2)); - maleIBI1=diff(malebouts(:,1)); - - maleIBI_perm = randperm(length(maleIBI1)); %shuffling IPIs - malebouts_perm1 = cumsum(maleIBI1(maleIBI_perm)); - MBL2= MBL(maleIBI_perm); - malebouts_perm2=malebouts_perm1+MBL2(1:length(malebouts_perm1)); - malebouts_perm=horzcat(malebouts_perm1, malebouts_perm2); - - for n=2:(size(malebouts_perm,1)-1); - a=round(malebouts_perm(n,1)); - aa=round(malebouts_perm(n,2)); - center=(aa+a)/2; -%center=malebouts_perm(n); - x=find(femalepulses<(center+2000)& femalepulses>center & femalepulses<(round(malebouts_perm(n+1,1)))); - xx= find(femalepulses>(center-2000)& femalepulses
(round(malebouts_perm(n-1,1)))); - if isempty(xx) && isempty(x) - continue - else - - if isempty(xx) && ~isempty(x) - c=round(femalepulses(x))-center; - BTAtimes_Mperm{i}(1:length(c),j)=c; - j=j+1; - end - if ~isempty(xx) && isempty(x); - c=round(femalepulses(xx))-center; - BTAtimes_Mperm{i}(1:length(c),j)=c; - j=j+1; - end - if ~isempty(xx) && ~isempty(x); - c=round(femalepulses(x))-center; - cc=round(femalepulses(xx))-center; - final=vertcat(c,cc); - BTAtimes_Mperm{i}(1:length(final),j)=final; - j=j+1; - - end - end - end - end - - - - - - end - end - - femaletimes_BTA=group_hist(BTAtimes); - BTAtimes_Mperm=group_hist(BTAtimes_Mperm); - BTAtimes_Fperm=group_hist(BTAtimes_Fperm); -end diff --git a/byHand/IPIA_W_byhand.m b/byHand/IPIA_W_byhand.m deleted file mode 100644 index a6a06d2..0000000 --- a/byHand/IPIA_W_byhand.m +++ /dev/null @@ -1,16 +0,0 @@ -for i=1:94; -if ~isempty(FIPIW{i}); -if length(FIPIW{i})>10; -FIPIWmedian(i)=median(FIPIW{i}); else FIPIWmedian(i)=NaN; -end; else FIPIWmedian(i)=NaN; -end -end -for i=1:94; -if ~isempty(MIBIW{i}) -bouts=MIBIW{i}(find(~isnan(MIBIW{i}))); -if length(bouts)>10; -MIBIWmedian(i)=median(bouts); else MIBIWmedian(i)=NaN; -end -else MIBIWmedian(i)=NaN; -end -end \ No newline at end of file diff --git a/byHand/MIBI_by_hand.m b/byHand/MIBI_by_hand.m deleted file mode 100644 index 3da50a7..0000000 --- a/byHand/MIBI_by_hand.m +++ /dev/null @@ -1,55 +0,0 @@ -function [ MIBIW, MIBIWvar, MIBIA, MIBIAvar]... - = MIBI_by_hand( maletimes, femaletimes,channels ); -%UNTITLED Summary of this function goes here -% Detailed explanation goes here - - channel_num=length(channels); - -MIBIW=NaN(1000,channel_num); -MIBIA=NaN(1000,channel_num); - - - for i=1:channel_num; - - femalepulses= femaletimes{i}; - - malebouts= maletimes{i}; - - if ~isempty(malebouts) && ~isempty(femalepulses); - maleIBI=diff(malebouts(:,1)); - - %male response time - h=1; j=1; - for u=1:(size(malebouts,1)-1); - d=round(malebouts(u,1)); - dd=round(malebouts(u+1,1)); - if dd-d<4000; - Fbetween= find( femalepulses>d & femalepulses10 -MIBIAvar(i)=nanvar(MIBIA(:,i)); - else MIBIAvar(i)=NaN; - end - if sum(~isnan(MIBIW(:,i)))>10 -MIBIWvar(i)=nanvar(MIBIW(:,i)); - else MIBIWvar(i)=NaN; - end - - end - - - - - \ No newline at end of file diff --git a/byHand/analysis_byhand.m b/byHand/analysis_byhand.m deleted file mode 100644 index 6dae289..0000000 --- a/byHand/analysis_byhand.m +++ /dev/null @@ -1,295 +0,0 @@ -function [femaletimes, overlaps, femaleIPI, femaleIPIalone, femaleIPIwith,... - femalePPS, maletimes, maletimesalone,maletimeswith, femaletimesalone,... - femaletimeswith, maleIBI, maletimesaloneIBI, maletimeswithIBI,maleboutlength, ... - femaleBTA, femaleRT,maleRT, femalePN, maleBN] = analysis_byhand(file,... - channels, samples, Fs, split); -%UNTITLED Summary of this function goes here -% Detailed explanation goes here - - - -load(file,'FPULSE', 'MPULSE','OVERLAP'); -channel_num=length(channels); -femaletimes=[]; -overlap=[]; -overlaps=NaN(1,max(channel_num)); -femaleIPI=[]; -femalePPS=[]; -maletimes=cell(1,channel_num); -femaletimes=cell(1,channel_num); -maleIBI=[]; -maletrain=[]; -maleboutlength=[]; -femaleBTA=[]; -femaleRT=[]; -femalepulses=[]; -malebouts=[]; -maletimesalone=[]; -maletimeswith=[]; -maletimesaloneIBI=[]; -maletimeswithIBI=[]; - femaleIPIalone=[]; - femaleIPIwith=[]; - femaletimesalone=[]; - femaletimeswith=[]; - femalePN=NaN(1,max(channel_num)); - maleRT=[]; - maleBN=NaN(1,max(channel_num)); - - time=samples/Fs; - - for i=1:channel_num; - - % female parameters - if ~isempty(FPULSE); - femalepulses= FPULSE(:,1)==channels(i); - femalepulses=sort(FPULSE(femalepulses,2),'ascend'); - if ~isempty(OVERLAP); - overlap=OVERLAP(:,1)==channels(i); - overlap=sort(OVERLAP(overlap,2),'ascend'); - femalepulses=sort(vertcat(femalepulses,overlap),'ascend'); - end - if nargin==5 - femalepulses=femalepulses(femalepulses>split(1) & femalepulsessplit(1) & malebouts_startsplit(1) & malebouts_stop5000); - if ~isempty(splittrain); - maletrain=NaN(length(splittrain)+1,50); - tr1=malebouts_start(1:splittrain(1)); - trend=malebouts_start(splittrain(end)+1:end); - maletrain(1,1:length(tr1))=tr1; - g=2; - for p=1:length(splittrain)-1; -tr=malebouts_start(splittrain(p)+1:splittrain(p+1)); -if length(tr)~=1; -maletrain(g,1:length(tr))=tr; -g=g+1; -end - end -maletrain(g,1:length(trend))=trend; - maleboutlength{i}=(malebouts(:,2)-malebouts(:,1))'; - - - else - maletrain=malebouts_start; - - end - end - end - - - %separate male song alone versus together - if ~isempty(maletrain); - maletimesalone{i}= NaN(length(maletrain(:,1)),50); - maletimeswith{i}= NaN(length(maletrain(:,1)),50); - maletimesaloneIBI{i}= NaN(length(maletrain(:,1)),50); - maletimeswithIBI{i}= NaN(length(maletrain(:,1)),50); - - if isempty(femalepulses); - maletimesalone{i}= maletrain; - for e=1:size(maletrain); - maletimesaloneIBI{i}(e,1:length(maletrain(e,:))-1)= diff(maletrain(e,:)); - end - else - for m=1:size(maletrain,1); - if isnan(maletrain(m,:)); - maletimesalone{i}(m)=maletrain(m); - else - malestop=find(~isnan(maletrain(m,:)),1,'last'); - b=find(femalepulses>(maletrain(m,1)-1000) & femalepulses<(maletrain(m,malestop)+1000)); - if isempty(b); - trainalone=maletrain(m,1:end); - maletimesalone{i}(m,1:length(trainalone))=trainalone; - maletimesaloneIBI{i}(m,1:length(trainalone)-1)=diff(trainalone); - - else - trainwith=maletrain(m,1:end); - maletimeswith{i}(m,1:length(trainwith))=trainwith; - maletimeswithIBI{i}(m,1:length(trainwith)-1)=diff(trainwith); - end - end - end - end - end - - - - %separate female song alone versus together - femaletimesalone{i}=NaN(length(femalepulses),1); - femaletimeswith{i}=NaN(length(femalepulses),1); - if ~isempty(malebouts); - for c=1:size(femalepulses,1); - if isempty(femalepulses); - femaletimeswith=[]; - femaletimesalone=[]; - else - b=find(malebouts(:,2)>(femalepulses(c)-2000) & malebouts(:,1)<(femalepulses(c)+2000)); - if isempty(b); - femaletimesalone{i}(c,1)=femalepulses(c,1); - - else - femaletimeswith{i}(c,1)=femalepulses(c,1); - end - end - end - -femaleIPIalone_all=diff(femaletimesalone{i})'; -femaleIPIalone{i}=femaleIPIalone_all(femaleIPIalone_all<500); -femaleIPIwith_all=diff(femaletimeswith{i})'; -femaleIPIwith{i}=femaleIPIwith_all(femaleIPIwith_all<500); - - - - - - - %coordination parameters - if ~isempty(femalepulses) || ~isempty(malebouts); - - - - - - femaleBTA{i}= NaN(100,length(malebouts(:,1))); - %female BTA on bout center - j=1; - for n=2:(size(malebouts,1)-1); - a=round(malebouts(n,1)); - aa=round(malebouts(n,2)); - center=(aa+a)/2; - x=find(femalepulses<(center+2000)& femalepulses>center & femalepulses<(round(malebouts(n+1,1)))); - xx= find(femalepulses>(center-2000)& femalepulses
(round(malebouts(n-1,2)))); - if isempty(xx) || isempty(x); - continue - else - c=round(femalepulses(x))-center; - cc=round(femalepulses(xx))-center; - final=vertcat(c,cc); - femaleBTA{i}(1:length(final),j)=final; - j=j+1; - - end - end - - - %female response time on bout start - femaleRT{i}= NaN(1,length(malebouts(:,1))); - k=1; - for z=1:(length(malebouts(:,1))-1); - male_start=round(malebouts(z,1)); - male_nextstart=round(malebouts(z+1,1)); - next_female=find(femalepulses>male_start & femalepulsesround(malebouts(u-1,2)),1, 'last'); - if isempty(dd) - continue - else - w=d-femalepulses(dd); - if w<1500; - maleRT{i}(1,h)=w; - h=h+1; - end - end - end - end - - end - - %pulse numbers - for y=1:length(femaletimes); -if isempty(femaletimes{y}) && ~isempty(maletimes{y}); - courtship_time= max(maletimes{y}(:,2))-min(maletimes{y}(:,1)); - if courtship_time>=20000; - maleBN(y)=((length(maletimes{y}(:,2))/((courtship_time/1000)))); - femalePN(y)=0; - overlaps(y)=0; - else - maleBN(y)=0; - femalePN(y)=0; - overlaps(y)=0; - end - end - if isempty(maletimes{y}) && ~isempty(femaletimes{y}); - courtship_time=max(femaletimes{y})-min(femaletimes{y}); - if courtship_time>=20000; - femalePN(y)=((length(femaletimes{y})/((courtship_time/1000)))); - maleBN(y)=0; - overlaps(y)=0; - else - maleBN(y)=0; - femalePN(y)=0; - overlaps(y)=0; - end - end - if ~isempty(femaletimes{y}) && ~isempty(maletimes{y}); - courtship_start = min(maletimes{y}(1,1),femaletimes{y}(1,1)); - courtship_end = max (maletimes{y}(end,2), femaletimes{y}(end,1)); - courtship_time=courtship_end-courtship_start; - if courtship_time>=20000; - maleBN(y)=((length(maletimes{y}(:,2))/((courtship_time/1000)))); - femalePN(y)=((length(femaletimes{y})/((courtship_time/1000)))); - if ~isempty(overlap); - overlaps(y)=length(overlap)/length(maletimes{y}(:,2)); - end - - if length(maletimes{y}(:,2))>=5 || length(femaletimes{y}(:,1))>=15; - maleBN(y)=maleBN(y); - femalePN(y)=femalePN(y); - overlaps(y)=overlaps(y); - else - maleBN(y)=0; - femalePN(y)=0; - overlaps(y)=0; - end - else - maleBN(y)=0; - femalePN(y)=0; - overlaps(y)=0; - end - end - - end - end - diff --git a/byHand/auto_hand_convert.m b/byHand/auto_hand_convert.m deleted file mode 100644 index 078b3a9..0000000 --- a/byHand/auto_hand_convert.m +++ /dev/null @@ -1,40 +0,0 @@ -function [ FPULSE, MPULSE, OVERLAP] = auto_hand_convert( file) -%UNTITLED Summary of this function goes here -% Detailed explanation goes here - -load(file,'femaleBoutInfo','maleBoutInfo', 'run_data'); -ch = str2double(file(strfind(file, 'ch')+2:strfind(file, '.mat')-1)); -Fs=7812.5; -factor=Fs/1000; - -FPULSE=[]; -MPULSE=[]; -OVERLAP=[]; -% pulses=NaN(length(maleBoutInfo.wc),20); - -FPULSE(:,2)=femaleBoutInfo.wMax/factor; -FPULSE(1:length(femaleBoutInfo.wMax),1)=ch; - -% j=1; -for i=1:length(maleBoutInfo.wc); -% zz=find(run_data.pulseInfo.wc>maleBoutInfo.w0(i) & run_data.pulseInfo.wc, zoom with + and - -%add multiple pulses by clicking on each and then pressing the return key (PULSE_MODE=1) -%add a pulse by clicking on the peak and trough (PULSE_MODE=2) -%add a sine song by clicking on the beginning and end -%delete removes just those currently displayed -%save creates a .mat file with _byhand appended to filename -% if workspace data passed in, file is workspace_byhand.mat -% -%ver 0.2: -% now loads in old byhand.mat files if they exist for further editing -% supports passing in workspace variables -% pulses delineated by either peak and trough, or just peak -% can now listen to data too -% -%ver 0.3: -% now resizes gracefully -% added PULSE_MODE -% added keyboard shortcuts (p = add pulse song, s = add sine song, etc) -% added confirmation dialog for delete of N>10 items -% toggle y-axis scale option -% added sonogram -% -%to convert PULSE_MODE=1 _byhand.mat files to PULSE_MODE=2, rename them to -% _old.mat, load them, and then PULSE=[PULSE PULSE(:,2)+0.001]; and then -% save() without _old; - -function flysong_segmenter_byhand3(varargin) - -global RAW IDXP IDXS PAN ZOOM -global CHANNEL FILE DATA PULSE SINE PULSE_MODE YSCALE NFFT -global FS NARGIN H - -PULSE_MODE=1; - -IDXP=[]; -IDXS=[]; -M=[]; -TOGGLE=[]; -PAN=0; % ms -ZOOM=100; % ms -SHIFT=max(RAW)-min(RAW); -EDIT=0; -STEP_SIZE=1; -DELETE_BUTTON=[]; -CHANNEL=2; -NARGIN=nargin; -NFFT=2^9; - -if(NARGIN==1) - VARARGOUT=[]; - if(strcmp(varargin{1}(end-3:end),'.daq')) - FILE=varargin{1}(1:end-4); - else - FILE=varargin{1}; - end - - if(exist([FILE '_byhand.mat'],'file')) - load([FILE '_byhand.mat']); - else - PULSE=[]; - SINE=[]; - end - - dinfo=daqread(FILE,'info'); - NCHAN=length(dinfo.ObjInfo.Channel); - FS=dinfo.ObjInfo.SampleRate; - RAW=daqread(FILE,'Channel',CHANNEL); -else - PULSE=[]; - SINE=[]; - DATA=varargin{1}; - NCHAN=size(DATA,2); - FS=varargin{2}; - RAW=DATA(:,CHANNEL); -end - -YSCALE=max(max(RAW)); -if(PAN>length(RAW)/FS*1000) PAN=0; end -if((PAN+ZOOM)>(length(RAW)/FS*1000)) ZOOM=(length(RAW)/FS*1000)-PAN; end - -figure; -tmp=get(gcf,'position'); -set(gcf,'position',[0 0 1.5*tmp(3) 1.5*tmp(4)]); -set(gcf,'menubar','none','ResizeFcn',@resizeFcn,'WindowKeyPressFcn',@windowkeypressFcn); - -H=uipanel(); -uicontrol('parent',H,'style','popupmenu','value',CHANNEL,... - 'string',1:NCHAN, ... - 'callback', @changechannel_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','<','tooltipstring','pan left', ... - 'callback', @panleft_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','^','tooltipstring','zoom in', ... - 'callback', @zoomin_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','v','tooltipstring','zoom out', ... - 'callback', @zoomout_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','>','tooltipstring','pan right', ... - 'callback', @panright_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(y)scale','tooltipstring','toggle y-scale', ... - 'callback', @yscale_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(f)req','tooltipstring','increase frequency resolution', ... - 'callback', @nfftup_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(t)ime','tooltipstring','increase temporal resolution', ... - 'callback', @nfftdown_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(p)ulse','tooltipstring','add pulse song', ... - 'callback', @addpulse_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(s)ine','tooltipstring','add sine song', ... - 'callback', @addsine_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(d)elete','tooltipstring','delete displayed pulse and sine song', ... - 'callback', @delete_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(l)isten','tooltipstring','listen to displayed recording', ... - 'callback', @listen_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','save','tooltipstring','save segmentation to disk', ... - 'callback', @save_callback); - -update; - - -function resizeFcn(src,evt) - -global H - -tmp=get(gcf,'position'); -foo=get(H,'children'); - -for(i=1:length(foo)) - switch(get(foo(i),'string')) - case('<') - set(foo(i),'position',[80,tmp(4)-30,20,20]); - case('^') - set(foo(i),'position',[100,tmp(4)-30,20,20]); - case('v') - set(foo(i),'position',[120,tmp(4)-30,20,20]); - case('>') - set(foo(i),'position',[140,tmp(4)-30,20,20]); - case('(y)scale') - set(foo(i),'position',[160,tmp(4)-30,50,20]); - case('(f)req') - set(foo(i),'position',[210,tmp(4)-30,40,20]); - case('(t)ime') - set(foo(i),'position',[250,tmp(4)-30,40,20]); - case('(p)ulse') - set(foo(i),'position',[290,tmp(4)-30,50,20]); - case('(s)ine') - set(foo(i),'position',[340,tmp(4)-30,50,20]); - case('(d)elete') - set(foo(i),'position',[390,tmp(4)-30,50,20]); - case('(l)isten') - set(foo(i),'position',[440,tmp(4)-30,50,20]); - case('save') - set(foo(i),'position',[490,tmp(4)-30,40,20]); - otherwise - set(foo(i),'position',[20,tmp(4)-30,50,20]); - end -end - - -function windowkeypressFcn(src,evt) - -switch(evt.Key) - case('leftarrow') - panleft_callback; - case('uparrow') - zoomin_callback; - case('downarrow') - zoomout_callback; - case('rightarrow') - panright_callback; - case('y') - yscale_callback; - case('f') - nfftup_callback; - case('t') - nfftdown_callback; - case('p') - addpulse_callback; - case('s') - addsine_callback; - case('d') - delete_callback; - case('l') - listen_callback; -end - - - -function changechannel_callback(hObject,eventdata) - -global FILE DATA RAW CHANNEL PAN ZOOM NARGIN - -CHANNEL=get(hObject,'value'); -if(NARGIN==1) - RAW=daqread(FILE,'Channel',CHANNEL); -else - RAW=DATA(:,CHANNEL); -end -update; - - - -function panleft_callback(hObject,eventdata) - -global PAN ZOOM; -PAN=max(0,PAN-ZOOM/2); -update; - - - -function zoomin_callback(hObject,eventdata) - -global PAN ZOOM; - -if(ZOOM<10) return; end; -ZOOM=ZOOM/2; -PAN=PAN+ZOOM/2; -update; - - - -function zoomout_callback(hObject,eventdata) - -global PAN ZOOM RAW FS; - -PAN=max(0,PAN-ZOOM/2); -ZOOM=ZOOM*2; -if((PAN+ZOOM)>(length(RAW)/FS*1000)) - ZOOM=(length(RAW)/FS*1000)-PAN; -end -update; - - - -function panright_callback(hObject,eventdata) - -global PAN ZOOM RAW FS; - -PAN=min(length(RAW)/FS*1000-ZOOM,PAN+ZOOM/2); -update; - - - -function addpulse_callback(hObject,eventdata) - -global CHANNEL PULSE PULSE_MODE; - -if(PULSE_MODE==1) - tmp=ginput; - tmp2=size(tmp,1); - PULSE(end+1:end+tmp2,:)=[repmat(CHANNEL,tmp2,1) tmp(:,1)]; -else - tmp=ginput(2); - PULSE(end+1,:)=[CHANNEL tmp(:,1)']; -end -update; - - - -function addsine_callback(hObject,eventdata) - -global CHANNEL SINE; - -tmp=ginput(2); -SINE(end+1,:)=[CHANNEL tmp(:,1)']; -update; - - - -function delete_callback(hObject,eventdata) - -global PULSE SINE IDXP IDXS; - -tmpp=setdiff(1:size(PULSE,1),IDXP); -tmps=setdiff(1:size(SINE,1),IDXS); -foo='yes'; -bar=length(IDXP)+length(IDXS); -if(bar>10) - foo=questdlg(['are you sure you want to delete these ' num2str(bar) ' items?'],... - '','yes','no','no'); -end -if(strcmp(foo,'yes')) - PULSE=PULSE(tmpp,:); - SINE=SINE(tmps,:); -end -update; - - - -function listen_callback(hObject,eventdata) - -global RAW PAN ZOOM FS; - -sound(RAW((1+ceil(PAN/1000*FS)):floor((PAN+ZOOM)/1000*FS)),FS); - - - -function save_callback(hObject,eventdata) - -global FILE PULSE SINE NARGIN VARARGOUT; - -if(NARGIN==1) - save([FILE '_byhand.mat'],'PULSE','SINE'); -else - save(['workspace_byhand.mat'],'PULSE','SINE'); -end - - -function yscale_callback(hObject,eventdata) - -global YSCALE - -YSCALE=-YSCALE; -update; - - -function nfftup_callback(hObject,eventdata) - -global NFFT - -NFFT=NFFT*2; -update; - - -function nfftdown_callback(hObject,eventdata) - -global NFFT - -NFFT=NFFT/2; -update; - - -function update - -global RAW IDXP IDXS PAN ZOOM -global CHANNEL FILE PULSE SINE PULSE_MODE YSCALE NFFT -global FS - -foo2=(1+ceil(PAN/1000*FS)):floor((PAN+ZOOM)/1000*FS); -foo=RAW(foo2); - -subplot(2,1,1); cla; hold on; -if(length(foo)>NFFT) - [s,f,t,p]=spectrogram(foo',NFFT,[],[],FS,'yaxis'); - fidx=find(f>=25 & f<=2500); - surf((t+foo2(1)./FS).*1000,f(fidx),log10(abs(p(fidx,:))),'EdgeColor','none'); - colormap(flipud(gray)); - axis tight; - ylabel('frequency (Hz)'); -end - -subplot(2,1,2); cla; hold on; - -IDXP=[]; -if(~isempty(PULSE)) - if(PULSE_MODE==1) - IDXP=find((PULSE(:,1)==CHANNEL) & ... - (((PULSE(:,2)>=PAN) & (PULSE(:,2)<=(PAN+ZOOM))))); - else - IDXP=find((PULSE(:,1)==CHANNEL) & ... - (((PULSE(:,2)>=PAN) & (PULSE(:,2)<=(PAN+ZOOM))) | ... - ((PULSE(:,3)>=PAN) & (PULSE(:,3)<=(PAN+ZOOM))))); - end -end - -IDXS=[]; -if(~isempty(SINE)) - IDXS=find((SINE(:,1)==CHANNEL) & ... - (((SINE(:,2)>=PAN) & (SINE(:,2)<=(PAN+ZOOM))) | ... - ((SINE(:,3)>=PAN) & (SINE(:,3)<=(PAN+ZOOM))))); -end - -for(i=1:length(IDXP)) - if(PULSE_MODE==1) - plot([PULSE(IDXP(i),2) PULSE(IDXP(i),2)],[min(foo) max(foo)],... - 'b-','linewidth',3); - else - patch([PULSE(IDXP(i),2) PULSE(IDXP(i),2) PULSE(IDXP(i),3) PULSE(IDXP(i),3)],... - [min(foo) max(foo) max(foo) min(foo)],... - 'b','EdgeColor','b'); - end -end -for(i=1:length(IDXS)) - patch([SINE(IDXS(i),2) SINE(IDXS(i),2) SINE(IDXS(i),3) SINE(IDXS(i),3)],... - [min(foo) max(foo) max(foo) min(foo)],... - 'r','EdgeColor','r'); -end -plot(foo2./FS.*1000,foo,'k'); - -axis tight; -if(YSCALE<0) - v=axis; - axis([foo2(1)./FS.*1000 foo2(end)./FS.*1000 v(3) v(4)]); -else - axis([foo2(1)./FS.*1000 foo2(end)./FS.*1000 -YSCALE YSCALE]); -end -xlabel('time (ms)'); - -v=axis; -subplot(2,1,1); -vv=axis; -axis([v(1) v(2) vv(3) vv(4)]); diff --git a/byHand/flysong_segmenter_byhand3_virilis.m b/byHand/flysong_segmenter_byhand3_virilis.m deleted file mode 100644 index 5c858c6..0000000 --- a/byHand/flysong_segmenter_byhand3_virilis.m +++ /dev/null @@ -1,489 +0,0 @@ -%function flysong_segmenter_byhand3(file) -%function flysong_segmenter_byhand3(data,Fs) -% -%file is the .daq output filename of array_take -%data is a matrix containing the data from daqread() -%Fs is the sampling rate -% -%popupmenu on the left selects the channel number -%pan with < and >, zoom with + and - -%add multiple pulses by clicking on each and then pressing the return key (PULSE_MODE=1) -%add a pulse by clicking on the peak and trough (PULSE_MODE=2) -%add a sine song by clicking on the beginning and end -%delete removes just those currently displayed -%save creates a .mat file with _byhand appended to filename -% if workspace data passed in, file is workspace_byhand.mat -% -%ver 0.2: -% now loads in old byhand.mat files if they exist for further editing -% supports passing in workspace variables -% pulses delineated by either peak and trough, or just peak -% can now listen to data too -% -%ver 0.3: -% now resizes gracefully -% added PULSE_MODE -% added keyboard shortcuts (p = add pulse song, s = add sine song, etc) -% added confirmation dialog for delete of N>10 items -% toggle y-axis scale option -% added sonogram -% -%to convert PULSE_MODE=1 _byhand.mat files to PULSE_MODE=2, rename them to -% _old.mat, load them, and then PULSE=[PULSE PULSE(:,2)+0.001]; and then -% save() without _old; - -function flysong_segmenter_byhand3_virilis(varargin) - -global RAW IDXMP IDXFP PAN ZOOM -global CHANNEL FILE DATA MPULSE FPULSE OVERLAP PULSE_MODE YSCALE NFFT -global FS NARGIN H - -PULSE_MODE=1; - -IDXMP=[]; -IDXFP=[]; -IDXO=[]; -M=[]; -TOGGLE=[]; -PAN=0; % ms -ZOOM=100; % ms -SHIFT=max(RAW)-min(RAW); -EDIT=0; -STEP_SIZE=1; -DELETE_BUTTON=[]; -CHANNEL=2; -NARGIN=nargin; -NFFT=2^9; - -if(NARGIN==1) - VARARGOUT=[]; - if(strcmp(varargin{1}(end-3:end),'.daq')) - FILE=varargin{1}(1:end-4); - else - FILE=varargin{1}; - end - - if(exist([FILE '_byhand.mat'],'file')) - load([FILE '_byhand.mat']); - else - MPULSE=[]; - FPULSE=[]; - OVERLAP=[]; - end - - dinfo=daqread(FILE,'info'); - NCHAN=length(dinfo.ObjInfo.Channel); - FS=dinfo.ObjInfo.SampleRate; - RAW=daqread(FILE,'Channel',CHANNEL); -else - MPULSE=[]; - FPULSE=[]; - OVERLAP=[]; - - DATA=varargin{1}; - NCHAN=size(DATA,2); - FS=varargin{2}; - RAW=DATA(:,CHANNEL); -end - -YSCALE=max(max(RAW)); -if(PAN>length(RAW)/FS*1000) PAN=0; end -if((PAN+ZOOM)>(length(RAW)/FS*1000)) ZOOM=(length(RAW)/FS*1000)-PAN; end - -figure; -tmp=get(gcf,'position'); -set(gcf,'position',[0 0 1.5*tmp(3) 1.5*tmp(4)]); -set(gcf,'menubar','none','ResizeFcn',@resizeFcn,'WindowKeyPressFcn',@windowkeypressFcn); - -H=uipanel(); -uicontrol('parent',H,'style','popupmenu','value',CHANNEL,... - 'string',1:NCHAN, ... - 'callback', @changechannel_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','<','tooltipstring','pan left', ... - 'callback', @panleft_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','^','tooltipstring','zoom in', ... - 'callback', @zoomin_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','v','tooltipstring','zoom out', ... - 'callback', @zoomout_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','>','tooltipstring','pan right', ... - 'callback', @panright_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(y)scale','tooltipstring','toggle y-scale', ... - 'callback', @yscale_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(f)req','tooltipstring','increase frequency resolution', ... - 'callback', @nfftup_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(t)ime','tooltipstring','increase temporal resolution', ... - 'callback', @nfftdown_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(m)male','tooltipstring','add male pulse song', ... - 'callback', @addmalepulse_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(n)female','tooltipstring','add female pulse song', ... - 'callback', @addfemalepulse_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(b)overlap','tooltipstring','add overlap', ... - 'callback', @addoverlap_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(d)elete','tooltipstring','delete displayed song', ... - 'callback', @delete_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','(l)isten','tooltipstring','listen to displayed recording', ... - 'callback', @listen_callback); -uicontrol('parent',H,'style','pushbutton',... - 'string','save','tooltipstring','save segmentation to disk', ... - 'callback', @save_callback); - -update; - - -function resizeFcn(src,evt) - -global H - -tmp=get(gcf,'position'); -foo=get(H,'children'); - -for(i=1:length(foo)) - switch(get(foo(i),'string')) - case('<') - set(foo(i),'position',[80,tmp(4)-30,20,20]); - case('^') - set(foo(i),'position',[100,tmp(4)-30,20,20]); - case('v') - set(foo(i),'position',[120,tmp(4)-30,20,20]); - case('>') - set(foo(i),'position',[140,tmp(4)-30,20,20]); - case('(y)scale') - set(foo(i),'position',[160,tmp(4)-30,50,20]); - case('(f)req') - set(foo(i),'position',[210,tmp(4)-30,40,20]); - case('(t)ime') - set(foo(i),'position',[250,tmp(4)-30,40,20]); - case('(m)male') - set(foo(i),'position',[290,tmp(4)-30,50,20]); - case('(n)female') - set(foo(i),'position',[340,tmp(4)-30,50,20]); - case('(b)overlap') - set(foo(i),'position',[390,tmp(4)-30,50,20]); - case('(d)elete') - set(foo(i),'position',[440,tmp(4)-30,50,20]); - case('(l)isten') - set(foo(i),'position',[490,tmp(4)-30,50,20]); - case('save') - set(foo(i),'position',[540,tmp(4)-30,40,20]); - otherwise - set(foo(i),'position',[20,tmp(4)-30,50,20]); - end -end - - -function windowkeypressFcn(src,evt) - -switch(evt.Key) - case('leftarrow') - panleft_callback; - case('uparrow') - zoomin_callback; - case('downarrow') - zoomout_callback; - case('rightarrow') - panright_callback; - case('y') - yscale_callback; - case('f') - nfftup_callback; - case('t') - nfftdown_callback; - case('m') - addmalepulse_callback; - case('n') - addfemalepulse_callback; - case('b') - addoverlap_callback; - case('d') - delete_callback; - case('l') - listen_callback; -end - - - -function changechannel_callback(hObject,eventdata) - -global FILE DATA RAW CHANNEL PAN ZOOM NARGIN - -CHANNEL=get(hObject,'value'); -if(NARGIN==1) - RAW=daqread(FILE,'Channel',CHANNEL); -else - RAW=DATA(:,CHANNEL); -end -update; - - - -function panleft_callback(hObject,eventdata) - -global PAN ZOOM; -PAN=max(0,PAN-ZOOM/2); -update; - - - -function zoomin_callback(hObject,eventdata) - -global PAN ZOOM; - -if(ZOOM<10) return; end; -ZOOM=ZOOM/2; -PAN=PAN+ZOOM/2; -update; - - - -function zoomout_callback(hObject,eventdata) - -global PAN ZOOM RAW FS; - -PAN=max(0,PAN-ZOOM/2); -ZOOM=ZOOM*2; -if((PAN+ZOOM)>(length(RAW)/FS*1000)) - ZOOM=(length(RAW)/FS*1000)-PAN; -end -update; - - - -function panright_callback(hObject,eventdata) - -global PAN ZOOM RAW FS; - -PAN=min(length(RAW)/FS*1000-ZOOM,PAN+ZOOM/2); -update; - - - -function addmalepulse_callback(hObject,eventdata) - -global CHANNEL MPULSE PULSE_MODE; - -% if(PULSE_MODE==1) -% tmpM=ginput; -% tmpM2=size(tmpM,1); -% MPULSE(end+1:end+tmpM2,:)=[repmat(CHANNEL,tmpM2,1) tmpM(:,1)]; -% else - tmpM=ginput(2); - MPULSE(end+1,:)=[CHANNEL tmpM(:,1)']; -% end -update; - -function addfemalepulse_callback(hObject,eventdata) - -global CHANNEL FPULSE PULSE_MODE; - -if(PULSE_MODE==1) - tmpF=ginput; - tmpF2=size(tmpF,1); - FPULSE(end+1:end+tmpF2,:)=[repmat(CHANNEL,tmpF2,1) tmpF(:,1)]; -else - tmpF=ginput(2); - FPULSE(end+1,:)=[CHANNEL tmpF(:,1)']; -end -update; - -function addoverlap_callback(hObject,eventdata) - -global CHANNEL OVERLAP PULSE_MODE; - -if(PULSE_MODE==1) - tmpF=ginput; - tmpF2=size(tmpF,1); - OVERLAP(end+1:end+tmpF2,:)=[repmat(CHANNEL,tmpF2,1) tmpF(:,1)]; -else - tmpF=ginput(2); - OVERLAP(end+1,:)=[CHANNEL tmpF(:,1)']; -end -update; - - - -function delete_callback(hObject,eventdata) - -global MPULSE FPULSE OVERLAP IDXMP IDXFP IDXO; - -tmpp=setdiff(1:size(MPULSE,1),IDXMP); -tmps=setdiff(1:size(FPULSE,1),IDXFP); -tmpo=setdiff(1:size(OVERLAP,1),IDXO); -foo='yes'; -bar=length(IDXMP)+length(IDXFP)+length(IDXO); -if(bar>10) - foo=questdlg(['are you sure you want to delete these ' num2str(bar) ' items?'],... - '','yes','no','no'); -end -if(strcmp(foo,'yes')) - MPULSE=MPULSE(tmpp,:); - FPULSE=FPULSE(tmps,:); - OVERLAP=OVERLAP(tmpo,:); -end -update; - - - -function listen_callback(hObject,eventdata) - -global RAW PAN ZOOM FS; - -sound(RAW((1+ceil(PAN/1000*FS)):floor((PAN+ZOOM)/1000*FS)),FS); - - - -function save_callback(hObject,eventdata) - -global FILE MPULSE FPULSE OVERLAP NARGIN VARARGOUT; - -if(NARGIN==1) - save([FILE '_byhand.mat'],'MPULSE','FPULSE','OVERLAP'); -else - save(['workspace_byhand.mat'],'MPULSE','FPULSE','OVERLAP'); -end - - -function yscale_callback(hObject,eventdata) - -global YSCALE - -YSCALE=-YSCALE; -update; - - -function nfftup_callback(hObject,eventdata) - -global NFFT - -NFFT=NFFT*2; -update; - - -function nfftdown_callback(hObject,eventdata) - -global NFFT - -NFFT=NFFT/2; -update; - - -function update - -global RAW IDXMP IDXFP IDXO PAN ZOOM -global CHANNEL FILE MPULSE FPULSE OVERLAP PULSE_MODE YSCALE NFFT -global FS - -foo2=(1+ceil(PAN/1000*FS)):floor((PAN+ZOOM)/1000*FS); -foo=RAW(foo2); - -subplot(2,1,1); cla; hold on; -if(length(foo)>NFFT) - [s,f,t,p]=spectrogram(foo',NFFT,[],[],FS,'yaxis'); - fidx=find(f>=25 & f<=2500); - surf((t+foo2(1)./FS).*1000,f(fidx),log10(abs(p(fidx,:))),'EdgeColor','none'); - colormap(flipud(gray)); - axis tight; - ylabel('frequency (Hz)'); -end - -subplot(2,1,2); cla; hold on; - -IDXMP=[]; -if(~isempty(MPULSE)) -% if(PULSE_MODE==1) -% IDXMP=find((MPULSE(:,1)==CHANNEL) & ... -% (((MPULSE(:,2)>=PAN) & (MPULSE(:,2)<=(PAN+ZOOM))))); -% else - IDXMP=find((MPULSE(:,1)==CHANNEL) & ... - (((MPULSE(:,2)>=PAN) & (MPULSE(:,2)<=(PAN+ZOOM))) | ... - ((MPULSE(:,3)>=PAN) & (MPULSE(:,3)<=(PAN+ZOOM))))); -% end -end - -IDXFP=[]; -if(~isempty(FPULSE)) - if(PULSE_MODE==1) - IDXFP=find((FPULSE(:,1)==CHANNEL) & ... - (((FPULSE(:,2)>=PAN) & (FPULSE(:,2)<=(PAN+ZOOM))))); - else - IDXFP=find((FPULSE(:,1)==CHANNEL) & ... - (((FPULSE(:,2)>=PAN) & (FPULSE(:,2)<=(PAN+ZOOM))) | ... - ((FPULSE(:,3)>=PAN) & (FPULSE(:,3)<=(PAN+ZOOM))))); - end -end - -IDXO=[]; -if(~isempty(OVERLAP)) - if(PULSE_MODE==1) - IDXO=find((OVERLAP(:,1)==CHANNEL) & ... - (((OVERLAP(:,2)>=PAN) & (OVERLAP(:,2)<=(PAN+ZOOM))))); - else - IDXO=find((OVERLAP(:,1)==CHANNEL) & ... - (((OVERLAP(:,2)>=PAN) & (OVERLAP(:,2)<=(PAN+ZOOM))) | ... - ((OVERLAP(:,3)>=PAN) & (OVERLAP(:,3)<=(PAN+ZOOM))))); - end -end - -for(i=1:length(IDXMP)) - if isempty(IDXMP)==1; - MPULSE=[]; - else -% if(PULSE_MODE==1) -% plot([MPULSE(IDXMP(i),2) MPULSE(IDXMP(i),2)],[min(foo) max(foo)],... -% 'b-','linewidth',3); -% else - patch([MPULSE(IDXMP(i),2) MPULSE(IDXMP(i),2) MPULSE(IDXMP(i),3) MPULSE(IDXMP(i),3)],... - [min(foo) max(foo) max(foo) min(foo)],... - 'b','EdgeColor','b'); -% end - end -end - -for(i=1:length(IDXFP)) - if(PULSE_MODE==1) - plot([FPULSE(IDXFP(i),2) FPULSE(IDXFP(i),2)],[min(foo) max(foo)],... - 'r-','linewidth',3); - else - patch([FPULSE(IDXFP(i),2) FPULSE(IDXFP(i),2) FPULSE(IDXFP(i),3) FPULSE(IDXFP(i),3)],... - [min(foo) max(foo) max(foo) min(foo)],... - 'r','EdgeColor','r'); - end -end - -for(i=1:length(IDXO)) - if(PULSE_MODE==1) - plot([OVERLAP(IDXO(i),2) OVERLAP(IDXO(i),2)],[min(foo) max(foo)],... - 'g-','linewidth',3); - else - patch([OVERLAP(IDXO(i),2) OVERLAP(IDXO(i),2) OVERLAP(IDXO(i),3) OVERLAP(IDXO(i),3)],... - [min(foo) max(foo) max(foo) min(foo)],... - 'g-','EdgeColor','g'); - end -end - -plot(foo2./FS.*1000,foo,'k'); - -axis tight; -if(YSCALE<0) - v=axis; - axis([foo2(1)./FS.*1000 foo2(end)./FS.*1000 v(3) v(4)]); -else - axis([foo2(1)./FS.*1000 foo2(end)./FS.*1000 -YSCALE YSCALE]); -end -xlabel('time (ms)'); - -v=axis; -subplot(2,1,1); -vv=axis; -axis([v(1) v(2) vv(3) vv(4)]); diff --git a/byHand/frt_by_hand.m b/byHand/frt_by_hand.m deleted file mode 100644 index 792d431..0000000 --- a/byHand/frt_by_hand.m +++ /dev/null @@ -1,38 +0,0 @@ -function [ female_response_times] = frt_by_hand( file, channels ) -%UNTITLED Summary of this function goes here -% Detailed explanation goes here - - load(file, 'FPULSE', 'MPULSE','OVERLAP'); -channel_num=length(channels); - -female_response_times= NaN(length(MPULSE(:,1)),(max(channels))); - for i=1:channel_num; - - femalepulses= FPULSE(:,1)==channels(i); - femalepulses=sort(FPULSE(femalepulses,2),'ascend'); - - malebouts=MPULSE(:,1)==channels(i); - malebouts_start=sort(MPULSE(malebouts,2),'ascend'); - malebouts_stop=sort(MPULSE(malebouts,3),'ascend'); - malebouts=horzcat(malebouts_start,malebouts_stop); - - overlaps=OVERLAP(:,1)==channels(i); - overlaps=sort(OVERLAP(overlaps,2),'ascend'); - - - j=1; - for n=1:length(malebouts(:,1)); - male_end=round(malebouts(n,2)); - next_female=find(femalepulses>male_end,1,'first'); - next_female=round(femalepulses(next_female)); - if isempty(next_female) || isempty(find((next_female-male_end)<1500)) - continue - else - female_response_times(j,channels(i))=next_female-male_end; - j=j+1; - end - end - end - - - diff --git a/byHand/makeMaleFemalePlot_byhand.m b/byHand/makeMaleFemalePlot_byhand.m deleted file mode 100644 index 884317b..0000000 --- a/byHand/makeMaleFemalePlot_byhand.m +++ /dev/null @@ -1,82 +0,0 @@ -function makeMaleFemalePlot_byhand(data,maletimes,femaletimes) - - - - -% -% hold on -% if ~isempty(malepulseInfo.w0) -% cc = [0 0 1]; -% x = malepulseInfo.w0; -% y = malepulseInfo.w1; -% for i=1:length(x) -% rectangle('Position',[x(i) -1 y(i)-x(i)+1 2],'facecolor',cc,'edgecolor',cc); -% end -% end -% -% if ~isempty(femalepulseInfo.w0) -% cc = [1 0 0]; -% x = femalepulseInfo.w0; -% y = femalepulseInfo.w1; -% for i=1:length(x) -% rectangle('Position',[x(i) -1 y(i)-x(i)+1 2],'facecolor',cc,'edgecolor',cc); -% end -% end -% -% plot(data,'k-') -% -% ylim([-.3 .3]) - - - - Fs=10000; - - N = length(data); - male_regions = false(N,1); - female_regions = false(N,1); - - - for i=1:length(maletimes); - male_regions(maletimes(i,1)*10:maletimes(i,2)*10) = true; - end - for i=1:length(femaletimes); - female_regions(femaletimes(i)*10:(femaletimes(i)*10)+10) = true; - end - - male_pulses = bwconncomp(male_regions & ~female_regions); - female_pulses = bwconncomp(female_regions & ~male_regions); - both_pulses = bwconncomp(male_regions & female_regions); - plot(data,'k-') - - hold on - if male_pulses.NumObjects > 0 - - for i=1:male_pulses.NumObjects - x = (male_pulses.PixelIdxList{i}(1))*10; - y = (male_pulses.PixelIdxList{i}(end))*10; - plot(data(x:y), 'b')%rectangle('Position',[x -1 y-x+1 2],'facecolor',cc,'edgecolor',cc); - end - end - - if female_pulses.NumObjects > 0 - - for i=1:female_pulses.NumObjects - x = female_pulses.PixelIdxList{i}(1); - y = female_pulses.PixelIdxList{i}(end); - plot(data(x:y), 'r')%rectangle('Position',[x -1 y-x+1 2],'facecolor',cc,'edgecolor',cc); - end - end - - if both_pulses.NumObjects > 0 - cc = [0 1 0]; - for i=1:both_pulses.NumObjects - x = both_pulses.PixelIdxList{i}(1); - y = both_pulses.PixelIdxList{i}(end); - plot(data(x:y), 'g'); %rectangle('Position',[x -1 y-x+1 2],'facecolor',cc,'edgecolor',cc); - end - end - - - - - ylim([-.3 .3]) \ No newline at end of file diff --git a/exampleSong.mat b/exampleSong.mat new file mode 100644 index 0000000..0b2e579 Binary files /dev/null and b/exampleSong.mat differ diff --git a/find_songs_from_hand_annotations.m b/find_songs_from_hand_annotations.m index 89f1c92..ae8fa7a 100644 --- a/find_songs_from_hand_annotations.m +++ b/find_songs_from_hand_annotations.m @@ -23,6 +23,7 @@ frequencies = segParams.fc; gmm_replicates = segParams.gmm_replicates; maxNumGMM = segParams.maxNumGMM; + wav = 'fbsp2-1-2'; fprintf(1,'Finding Male Principal Components\n'); male_mean = mean(male_songs); diff --git a/find_songs_from_hand_annotations.m~ b/find_songs_from_hand_annotations.m~ deleted file mode 100644 index a876b33..0000000 --- a/find_songs_from_hand_annotations.m~ +++ /dev/null @@ -1,84 +0,0 @@ -function likelihoodModels = find_songs_from_hand_annotations(male_songs,female_songs,overlap_songs) -%Inputs arrays of selected male, female, and overlap song, - - %load parameters - segParams = params_virilis(); - - probModes = segParams.probModes; - maxNumPeaks = segParams.maxNumPeaks; - maxNumPeaks_firstMode = segParams.maxNumPeaks_firstMode; - frequencies = segParams.fc; - gmm_replicates = segParams.gmm_replicates; - maxNumGMM = segParams.maxNumGMM; - - fprintf(1,'Finding Male Principal Components\n'); - male_mean = mean(male_songs); - [coeffs_male,scores_male,latent_male] = princomp(male_songs); - - - fprintf(1,'Finding Female Principal Components\n'); - female_mean = mean(female_songs); - [coeffs_female,scores_female,latent_female] = princomp(female_songs); - - - if nargin >= 3 && isempty(overlap_songs) - fprintf(1,'Finding Overlap Principal Components\n'); - both_mean = mean(overlap_songs); - [coeffs_both,scores_both,latent_both] = princomp(overlap_songs); - end - - - - fprintf(1,'Finding PDFs\n'); - - malePDFs = cell(probModes,1); - femalePDFs = cell(probModes,1); - if nargin >= 3 && isempty(overlap_songs) - bothPDFs = cell(probModes,1); - end - for i=1:probModes - - fprintf(1,'\t #%2i of %2i\n',i,probModes); - if i == 1 - q = maxNumPeaks_firstMode; - else - q = maxNumPeaks; - end - - malePDFs{i} = findBestGMM_AIC(scores_male(:,i),q,gmm_replicates,maxNumGMM); - femalePDFs{i} = findBestGMM_AIC(scores_female(:,i),q,gmm_replicates,maxNumGMM); - if nargin >= 3 && isempty(overlap_songs) - bothPDFs{i} = findBestGMM_AIC(scores_both(:,i),q,gmm_replicates,maxNumGMM); - end - end - - - likelihoodModels.malePDFs = malePDFs; - likelihoodModels.femalePDFs = femalePDFs; - likelihoodModels.noisePDFs = noisePDFs; - - likelihoodModels.male_mean = male_mean; - likelihoodModels.female_mean = female_mean; - likelihoodModels.noise_mean = noise_mean; - - likelihoodModels.coeffs_male = coeffs_male; - likelihoodModels.coeffs_female = coeffs_female; - likelihoodModels.coeffs_noise = coeffs_noise; - - likelihoodModels.latent_male = latent_male; - likelihoodModels.latent_female = latent_female; - likelihoodModels.latent_noise = latent_noise; - - likelihoodModels.probModes = probModes; - likelihoodModels.frequencies = frequencies; - likelihoodModels.scales = scales; - - - if nargin >= 3 && isempty(overlap_songs) - likelihoodModels.bothPDFs = bothPDFs; - likelihoodModels.both_mean = both_mean; - likelihoodModels.coeffs_both = coeffs_both; - likelihoodModels.latent_both = latent_both; - end - - diff --git a/logrank/kmplot/kmplot.m b/logrank/kmplot/kmplot.m deleted file mode 100644 index 75f300a..0000000 --- a/logrank/kmplot/kmplot.m +++ /dev/null @@ -1,291 +0,0 @@ -function varargout=kmplot(varargin) -% KMPLOT Plot the Kaplan-Meier estimation of the survival function -% Survival times are data that measure follow-up time from a defined -% starting point to the occurrence of a given event, for example the time -% from the beginning to the end of a remission period or the time from the -% diagnosis of a disease to death. Standard statistical techniques cannot -% usually be applied because the underlying distribution is rarely Normal -% and the data are often "censored". A survival time is described as -% censored when there is a follow-up time but the event has not yet -% occurred or is not known to have occurred. For example, if remission time -% is being studied and the patient is still in remission at the end of the -% study, then that patient�s remission time would be censored. If a patient -% for some reason drops out of a study before the end of the study period, -% then that patient�s follow-up time would also be considered to be -% censored. The survival function S(t) is defined as the probability of -% surviving at least to time t. The graph of S(t) against t is called the -% survival curve. The Kaplan�Meier method can be used to estimate this -% curve from the observed survival times without the assumption of an -% underlying probability distribution. -% -% Syntax: kmplot(x,alpha,censflag) -% -% Inputs: -% X (mandatory)- Nx2 data matrix: -% (X:,1) = survival time of the i-th subject -% (X:,2) = censored flag -% (0 if not censored; 1 if censored) -% note that if X is a vector, all the flags of the second column -% will be set to 0 (all data are not censored). -% ALPHA (optional) - significance level (default 0.05) -% CENSFLAG (optional) - Censored Plot flag (default 0). If 0 -% censored data will be plotted spreaded on the horizontal -% segment; if 1 they will be plotted at the given time of censoring. -% Outputs: -% Kaplan-Meier plot -% -% Example: (+ indicate that patient is censored) -% -% --------------------- -% Patient Survival -% time -% --------------------- -% 1 7 -% 2 12 -% 3 7+ -% 4 12+ -% 5 11+ -% 6 8 -% 7 9 -% 8 6 -% 9 7+ -% 10 2 -% ---------------------- -% X=[7 0; 12 0; 7 1; 12 1; 11 1; 8 0; 9 0; 6 0; 7 1; 2 0]; -% -% Calling on Matlab the function: kmplot(X) the function will plot the -% Kaplan-Meier estimation of the survival function -% -% Created by Giuseppe Cardillo -% giuseppe.cardillo-edta@poste.it -% -% To cite this file, this would be an appropriate format:Curve -% Cardillo G. (2008). KMPLOT: Kaplan-Meier estimation of the survival -% function. -% http://www.mathworks.com/matlabcentral/fileexchange/22293 - -%Input Error handling -args=cell(varargin); -nu=numel(args); -if isempty(nu) - error('Warning: Data vectors are required') -elseif nu>3 - if nu>4 - error('Warning: Max two input data are required') - end -end -default.values = {[7 0; 12 0; 7 1; 12 1; 11 1; 8 0; 9 0; 6 0; 7 1; 2 0],0.05,0,1}; -default.values(1:nu) = args; -[x alpha cflag flag] = deal(default.values{:}); -if ~all(isfinite(x(:))) || ~all(isnumeric(x(:))) - error('Warning: all X values must be numeric and finite') -end -if isvector(x) - x(:,2)=0; -else - if ~isequal(size(x,2),2) - error('KMPLOT requires Nx2 matrix data.'); - end - if ~all(x(:,2)==0 | x(:,2)==1) - error('Warning: all X(:,2) values must be 0 or 1') - end -end -if nu>1 - if isempty(alpha) - alpha=0.05; - else - if ~isscalar(alpha) || ~isnumeric(alpha) || ~isfinite(alpha) - error('Warning: it is required a numeric, finite and scalar ALPHA value.'); - end - if alpha <= 0 || alpha >= 1 %check if alpha is between 0 and 1 - error('Warning: ALPHA must be comprised between 0 and 1.') - end - end -end -if nu==3 - if isempty(cflag) - cflag=0; - else - if ~isscalar(cflag) || ~isnumeric(cflag) || ~isfinite(cflag) - error('Warning: it is required a numeric, finite and scalar CENSFLAG value.'); - end - if cflag~=0 && cflag~=1 - error('Warning: CENSFLAG value must be 0 or 1') - end - end -end -clear args default nu -%string for LEGEND function -str1=[num2str((1-alpha)*100) '% confidence interval']; - -%sort data by survival time -x=sortrows(x,1); -%table of patients observed for each survival time -%the TABULATE function sets up this matrix: -%table1=[time count percent(on total)] -table1=[0 size(x,1) 1; tabulate(x(:,1))]; -%if all observed time are integers remove not observed time added by -%TABULATE function -table1(table1(:,3)==0,:)=[]; - -%Table of censored data -table12=tabulate(x(x(:,2)==1)); -if ~isempty(table12) - % remove not observed time added by TABULATE function - table12(table12(:,3)==0,:)=[]; - % setup the vector of the censored data - [cens,loc]=ismember(table1(:,1),table12(:,1)); %find censored data -end - -%the percents stored in the the third column are unuseful; -%so, place in the third column how many subjects are still alive at the -%beginning of the i-th interval. -a1=[table1(1,2); -1.*table1(2:end,2)]; -table1(:,3)=cumsum(a1); table1(2:end,3)=table1(1:end-1,3); -%number of deaths in the intervals (don't take in account the censored -%data) -if ~isempty(table12) - table1(cens,2)=table1(cens,2)-table12(loc(cens),2); -end -%finally, delete the first row that is now useless -table1(1,:)=[]; - -t1=[0;table1(:,1)]; %this is the x variable (time); -%this is the y variable (survival function) -T1=[1;cumprod(1-(table1(:,2)./table1(:,3)))]; -if flag %if this function was not called by LOGRANK function - %compute the standard error of the survival function - SE=[0;T1(2:end).*sqrt(cumsum(table1(:,2)./(table1(:,3).* ... - (table1(:,3)-table1(:,2)))))]; -end - -%censored data plotting -if ~isempty(table12) - %if there are censored data after max(t1), add a new cell into the t1, - %T1 and SE arrays - if table12(end,1)>=t1(end,1) - t1(end+1,1)=table12(end,1)+1; - T1(end+1,1)=T1(end,1); - if flag %if this function was not called by LOGRANK function - SE(end+1,1)=SE(end,1); - end - end - if ~cflag - %vectors preallocation - xcg=zeros(1,sum(table12(:,2))); ycg=xcg; J=1; - %for each censored data into the i-th time interval... - for I=1:size(table12,1) - %compute how many position into the array they must occupy - JJ=J+table12(I,2)-1; - %find the correct time interval in which censored data must be - %placed - A=find(t1<=table12(I,1),1,'last'); - B=find(t1>table12(I,1),1,'first'); - %equally divide this interval - int=linspace(table12(I,1),t1(B,1),table12(I,2)+2); - %put all in the vectors of the plotting variables - xcg(J:JJ)=int(2:end-1); - ycg(J:JJ)=T1(A); - %update the counter - J=JJ+1; - end - else - xcg=table1(table1(:,2)==0,1); - ycg=T1(table1(:,2)==0); - end -else - if ~flag %if this function was called by LOGRANK function - xcg=[]; ycg=[]; - end -end -%compute the hazard rate -c1=T1.*numel(x); -c2=-(diff(log(c1(1:end-1)))./diff(t1(1:end-1))); -lambda=mean(c2(c2~=0)); - -if flag %if this function was not called by LOGRANK function - %compute the (1-alpha)*100% confidence interval curves - cv=realsqrt(2)*erfcinv(alpha); %critical value - %lower curve (remember that: the lower curve values can't be negative) - lowc=max(0,T1-SE.*cv); - %if the lower curve reaches the 0 earlier than survival function, trim the - %data. - if isequal(lowc(end-1:end),[0; 0]) - lowcend=find(lowc==0,1,'first'); - else - lowcend=length(lowc); - end - %upper curve (remember that the upper curve values can't be >1) - upc=min(1,T1+SE.*cv); - %eventually, correct the data. - if isequal(upc(end),1) - cupend=find(upc<1,1,'last'); - upc(cupend:end)=upc(cupend); - end - - %compute the median survival time (if exist...) - if isempty(T1(T1==0.5)) %if there is not a point where T=0.5... - I=find(T1>0.5,1,'last'); %find the first point where T>0.5 - J=find(T1<0.5,1,'first'); %find the first point where T<0.5 - if isempty(J) %if all points are >0.5... - mt=0; %...there is no median time - else - %compute the median time by linear interpolation. - p=polyfit([t1(I) t1(J)],[T1(I) T1(J)],1); - mt=(0.5-p(2))/p(1); - str2=['Median time ' num2str(mt)]; %string for LEGEND function - end - else - mt=t1(T1==0.5); - str2=['Median time ' num2str(mt)]; %string for LEGEND function - end - - %plot all the data - clf - hold on - S2=stairs(t1(1:lowcend),lowc(1:lowcend),'g--'); %lower confidence interval curve - stairs(t1,upc,'g--'); %upper confidence interval curve - S1=stairs(t1,T1,'b'); %Kaplan-Meier survival function - if mt>0 %if exist a median time... - S3=plot([0 mt mt],[0.5 0.5 0],'k:'); - end - if ~isempty(table12) %if there are censored data... - S4=plot(xcg,ycg,'r+'); - else - S4=[]; - end - hold off - - %set the axis properly - xmax=max(t1)+1; - axis([0 xmax 0 1.2]); - axis square - %add labels and legend - txt=sprintf('Kaplan-Meier estimate of survival function (hazard rate: %0.4f)\n',lambda); - title(txt,'FontName','Arial','FontSize',14,'FontWeight','Bold'); - ylabel('Estimated survival function','FontName','Arial','FontSize',14,'FontWeight','Bold'); - xlabel('Time','FontName','Arial','FontSize',14,'FontWeight','Bold'); - if mt - if isempty(S4) - legend([S1 S2 S3],'Data',str1,str2) - else - legend([S1 S2 S3 S4],'Data',str1,str2,'Censored') - end - else - if isempty(S4) - legend([S1 S2],'Data',str1) - else - legend([S1 S2 S4],'Data',str1,'Censored') - end - end - disp('HAZARD RATE IS AN EXPERIMENTAL FUNCTION!!!!') -end -if nargout - varargout(1)={table1}; - varargout(2)={table12}; - varargout(3)={t1}; - varargout(4)={T1}; - varargout(5)={xcg}; - varargout(6)={ycg}; - varargout(7)={lambda}; -end \ No newline at end of file diff --git a/logrank/kmplot/license.txt b/logrank/kmplot/license.txt deleted file mode 100644 index a12eb70..0000000 --- a/logrank/kmplot/license.txt +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2008, Giuseppe Cardillo -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/logrank/license.txt b/logrank/license.txt deleted file mode 100644 index a12eb70..0000000 --- a/logrank/license.txt +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2008, Giuseppe Cardillo -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/logrank/logrank.m b/logrank/logrank.m deleted file mode 100644 index 58714bb..0000000 --- a/logrank/logrank.m +++ /dev/null @@ -1,249 +0,0 @@ -function logrank(varargin) -% LOGRANK Comparing survival curves of two groups using the log rank test -% Comparison of two survival curves can be done using a statistical -% hypothesis test called the log rank test. It is used to test the null -% hypothesis that there is no difference between the population survival -% curves (i.e. the probability of an event occurring at any time point is -% the same for each population). This function use the Kaplan-Meier -% procedure to estimate the survival function, so it is mandatory to download -% KMPLOT (http://www.mathworks.com/matlabcentral/fileexchange/22293). -% -% Syntax: logrank(x1,x2,alpha,censflag) -% -% Inputs: -% X1 and X2 (mandatory)- Nx2 data matrix: -% (X:,1) = survival time of the i-th subject -% (X:,2) = censored flag -% (0 if not censored; 1 if censored) -% note that if X is a vector, all the flags of the second column -% will be set to 0 (all data are not censored). -% ALPHA (optional) - significance level (default 0.05) -% CENSFLAG (optional) - Censored Plot flag (default 0). If 0 -% censored data will be plotted spreaded on the horizontal -% segment; if 1 they will be plotted at the given time of -% censoring. -% Outputs: -% Kaplan-Meier plot -% Log-rank statistics -% -% Example: -% load logrankdata x1 x2 -% logrank(x1,x2) -% -%LOG-RANK TEST FOR KAPLAN-MEIER SURVIVAL FUNCTIONS -% -%-------------------------------------------------------------------------------- -%UL S.E. z p-value (2-tailed test) alpha -%-------------------------------------------------------------------------------- -%6.57226 2.80788 2.16258 0.03057 0.050 -%-------------------------------------------------------------------------------- -% The survival functions are statistically different -% -% Created by Giuseppe Cardillo -% giuseppe.cardillo-edta@poste.it -% -% To cite this file, this would be an appropriate format: -% Cardillo G. (2008). LogRank: Comparing survival curves of two groups -% using the log rank test -% http://www.mathworks.com/matlabcentral/fileexchange/22317 - -%Input Error handling -args=cell(varargin); -nu=numel(args); -if isempty(nu) || nu<2 - error('Warning: Data vectors are required') -elseif nu>3 - error('Warning: Max three input data are required') -end -default.values = {[],[],0.05,0}; -default.values(1:nu) = args; -[x1 x2 alpha,cflag] = deal(default.values{:}); -if ~all(isfinite(x1(:))) || ~all(isnumeric(x1(:))) ... - || ~all(isfinite(x2(:))) || ~all(isnumeric(x2(:))) - error('Warning: all X1 and X2 values must be numeric and finite') -end -if isvector(x1) - x1(:,2)=0; -else - if ~isequal(size(x1,2),2) - error('LOGRANK requires Nx2 matrix data.'); - end - if ~all(x1(:,2)==0 | x1(:,2)==1) - error('Warning: all X1(:,2) values must be 0 or 1') - end -end -if isvector(x2) - x2(:,2)=0; -else - if ~isequal(size(x2,2),2) - error('LOGRANK requires Nx2 matrix data.'); - end - if ~all(x2(:,2)==0 | x2(:,2)==1) - error('Warning: all X2(:,2) values must be 0 or 1') - end -end -if nu>=3 - if isempty(alpha) - alpha=0.05; - else - if ~isscalar(alpha) || ~isnumeric(alpha) || ~isfinite(alpha) - error('Warning: it is required a numeric, finite and scalar ALPHA value.'); - end - if alpha <= 0 || alpha >= 1 %check if alpha is between 0 and 1 - error('Warning: ALPHA must be comprised between 0 and 1.') - end - end -end -if nu==4 - if isempty(cflag) - cflag=0; - else - if ~isscalar(cflag) || ~isnumeric(cflag) || ~isfinite(cflag) - error('Warning: it is required a numeric, finite and scalar CENSFLAG value.'); - end - if cflag~=0 && cflag~=1 - error('Warning: CENSFLAG value must be 0 or 1') - end - end -end -clear args default nu - -%recall KMPLOT function to construct tables of data (table1 and table2), -%tables of censored data (table12 and table 22), Kaplan-Meier variables -%(t1, t2, T1 and T2) and Kaplan-Meier graphical data for censored data -%(xcg and ycg). -try - [table1 table12 t1 T1 xcg1 ycg1 lambda1]=kmplot(x1,0.05,cflag,0); - [table2 table22 t2 T2 xcg2 ycg2 lambda2]=kmplot(x2,0.05,cflag,0); -catch ME - disp('Download KMPLOT: http://www.mathworks.com/matlabcentral/fileexchange/22293') - rethrow(ME);0.01529 -end - -%plot both Kaplan-Meier curves -clf -hold on -S1=stairs(t1,T1,'b'); %Kaplan-Meier curve for treatment 1 -if ~isempty(table12) - S3=plot(xcg1,ycg1,'k+'); %Censored data for treatment 1 (if there are) -else - S3=[]; -end - -S2=stairs(t2,T2,'r'); %Kaplan-Meier curve for treatment 2 -if ~isempty(table22) - S3=plot(xcg2,ycg2,'k+'); %Censored data for treatment 2 (if there are) -end -hold off -%set the axis properly -xmax=max([t1;t2])+1; -axis([0 xmax 0 1.2]); -axis square -%add labels and legend -title('Kaplan-Meier estimate of survival functions') -ylabel('Estimated survival functions') -xlabel('Time') -if isempty(S3) - legend([S1 S2],'Treatment 1','Treatment 2') -else - legend([S1 S2 S3],'Treatment 1','Treatment 2','Censored') -end - -clear S1 S2 S3 xmax xcg1 ycg1 xcg2 ycg2 t1 t2 T1 T2 - -%Full-blown LOGRANK procedure -%Merge the first columns of Table1 and Table2 (time intervals) -%and pick-up unique values -A=unique([table1(:,1);table2(:,1)]); -table=zeros(length(A),9); %matrix preallocation -%Out in the first column the time intervals -table(:,1)=A; -%Put in the columns 2 and 3 and in the proper rows the deaths and alive -%taken from table1 columns 2 and 3 -[~, ia ib]=intersect(table1(:,1),A); -table(ib,2:3)=table1(ia,2:3); -%Put in the columns 4 and 5 and in the proper rows the deaths and alive -%taken from table2 columns 2 and 3 -[~, ia ib]=intersect(table2(:,1),A); -table(ib,4:5)=table2(ia,2:3); -%remove the rows where there arent't deaths in both treatments -table((table(:,2)==0 & table(:,4)==0),:)=[]; -clear A c ia ib table1 table2 -%fill the "pigeon-holes" -c=find(table(:,3)==0); %find the "pigeon-holes" of treatment 1 -for I=1:length(c) - if c(I)~=1 - %find the first interval time before the hole where there is almost 1 - %death - J=find(table(1:c(I)-1,3)>0,1,'last'); - table(c(I),3)=table(J,3)-table(J,2); - if ~isempty(table12) - %find eventually censored data - K=find((table12(:,1)=table(J,1)),1,'last'); - %Put in the hole how many subject were alive before the interval time - %of the hole - if ~isempty(K) - table(c(I),3)=table(c(I),3)-sum(table12(K,2)); - end - end - else - table(1,3)=length(x1); - end -end -%Do the same for tratment 2 -c=find(table(:,5)==0); -for I=1:length(c) - if c(I)~=1 - J=find(table(1:c(I)-1,5)>0,1,'last'); - table(c(I),5)=table(J,5)-table(J,4); - if ~isempty(table22) - K=find((table22(:,1)=table(J,1)),1,'last'); - if ~isempty(K) - table(c(I),5)=table(c(I),5)-sum(table22(K,2)); - end - end - else - table(1,5)=length(x2); - end -end -clear c I J K table12 table22 - -%Fill the table and compute the statistic variable -%Compute the total deaths and alive before the i-th time interval -table(:,6:7)=[sum(table(:,[2 4]),2) sum(table(:,[3 5]),2)]; -%Compute the difference between observed deaths for treatment 1 and -%expected deaths in the hyphthesis that the treatments are similar -table(:,8)=table(:,2)-table(:,3).*table(:,6)./table(:,7); -%Log-rank statistic is the sum of column 8 values -UL=abs(sum(table(:,8))); -%Compute the contribute to the standard error -table(:,9)=prod(table(:,[3 5 6]),2).*(table(:,7)-table(:,6)) ... - ./(table(:,7).^2.*(table(:,7)-ones(size(table,1),1))); -%find if there is some NaN (i.e. 0/0) -loc=isnan(table(:,9)); -if any(loc) - table(loc,9)=0; -end -SUL=sqrt(sum(table(:,9))); %Compute the totale standard error -z=abs((UL-0.5)/SUL); %normalized UL with Yates'es correction -p=2*(1-0.5*erfc(-z/realsqrt(2))); %p-value - -%display results -disp('LOG-RANK TEST FOR KAPLAN-MEIER SURVIVAL FUNCTIONS') -disp(' ') -tr=repmat('-',1,110); -disp(tr) -disp('HAZARD RATE IS AN EXPERIMENTAL FUNCTION!!!!') -fprintf('Treatment 1: Hazard rate: %0.4f\n',lambda1) -fprintf('Treatment 2: Hazard rate: %0.4f\n',lambda2) -fprintf('Hazard ratio: %0.4f\n',lambda1/lambda2) -disp(tr) -fprintf('UL\t\t\tS.E.\t\tz\t\tp-value (2-tailed test)\t\talpha\n') -disp(tr) -fprintf('%0.5f\t\t\t%0.5f\t\t%0.5f\t\t%0.5f\t\t\t\t%0.3f\n',UL,SUL,z,p,alpha) -disp(tr) -if p 41) - probModes = 20; %(DONT CHANGE THIS!!!!!!!!!!!!!!) + probModes = 20; %Pnoise < noiseThreshold to count as signal noiseThreshold = .5; diff --git a/params_virilis.m~ b/params_virilis.m~ deleted file mode 100644 index dfc5398..0000000 --- a/params_virilis.m~ +++ /dev/null @@ -1,181 +0,0 @@ -function segParams = params_virilis(fs) -%Fits song data to previously-defined likelihood models -%Inputs: -% data -> 1d array containing a time series of song -% likelihoodModels -> fitted likelihood models from -% find_songs_from_hand_annotation.m (default:exampleLikelihoodModels) -% samplingFrequency -> data sampling frequency in Hz (default = 1e4) -% -%Outputs: -% maleBoutInfo -> struct containing statistis from found male bouts -% femaleBoutInfo -> struct containing statistis from found female bouts -% run_data -> struct containing statistis from analysis -% -% (C) Gordon J. Berman, Jan Clemens, Kelly M. LaRue, and Mala Murthy, 2015 -% Princeton University - - - if nargin < 1 || isempty(fs) - fs = 10000; - end - - %%%%%%%%%%%%%%ALL USER DEFINED PARAMETERS ARE SET HERE%%%%%%%%%%%%%%%%%%%%% - - - %frequencies to use (don't change unless you want to re-run the likelihood - %models) - fc = 100:20:900; - - %factor for computing window around pulse peak - %(this determines how much of the signal before and after the peak - %is included in the pulse, and sets the parameters w0 and w1.) - pulseWindow = round(fs/25); - - %factor times the mean of xempty - only pulses larger than - %this amplitude are counted as true pulses - noiseFactor = 1; - - %male pulse carrier frequency - mpf = 350; - - %100Hz lowpass filter for male pulse detection - male = 100; - - %40Hz lowpass filter for female pulse detection - female = 40; - - %20Hz lowpass filter for male song bout detection - bout = 20; - - %male bout detection based on IPI, in samples - male_IPI = 250; - - %Smoothing parameter for data - filterWindow = 5; - - - %%%%%%%%%%%%%%%%%%%%%%% - - %Threshold for P(both singing | data) - probThreshold = 1; - - %Male probability threshold - maleThreshold = .2; - - %minimum size of a female pulse in the midst of a male pulse (in data - %points) - minFemalePulseSize = 150; - - %number of PCA modes to use in analysis (3 -> 41) - probModes = 20; %(DONT CHANGE THIS!!!!!!!!!!!!!!) - - %Pnoise < noiseThreshold to count as signal - noiseThreshold = .5; - - %minimum percentage of time where p(male) > p(female) in order for the bout - %to be counted as male (***) - minMaleBoutFraction = 1/5; - - %Number of time points over which to test male activity (i is called male if - %the number of initially called male frames is greater than - %minMaleBoutFraction*maleTestDuration points over - %(i-maleTestDuration):(i+maleTestDuration) - maleTestDuration = 500; - - %minimum duration for a bout to be called a male bout (in time points) (***) - minMaleDuration = 1000; - - %Smoothing parameter for male and combination song likelihoods (***) - smoothParameter_male = 25; - - %Smoothing parameter for female and nosie song likelihoods (***) - smoothParameter_female = 50; - - %Smoothing parameter for female and nosie song likelihoods - smoothParameter_amplitudes = 25; - - %Threshold for amplitude - amplitudeThreshold = .1; - - %Threshold for for noise likelihood (***) - %(smaller = more stringent, do not make lower than -5490, must be changed if probModes is changed) - noiseLikelihoodThreshold = 0; - - %Threshold for calling the posterior value noise (between 0 and 1). - %Closer to 1 implies a more stringent cut-off - ampPostThreshold = .95; - - %Maximum noise data set from which to create noise models - maxNumNoise = 500000; - - %Maximum number of peaks to create GMM noise distribution PDF - maxNumPeaks = 4; - - %Maximum number of peaks to create GMM noise distribution PDF for the first - %mode - maxNumPeaks_firstMode = 6; - - %Number of PDF modes used to find female bouts within male bouts - num_male_both_modes = 5; - - %Definition of closeness for female peak elimination (in ms) - female_IPI_limit = 26; - - %Num of consecutive close female peaks needed for elimination (should be - %odd) - num_female_IPI_limit = 3; - - %Length of time (in seconds) - stop_recording_time = 140; - - %Whether or not to refine probabilities using the PDF projection theorem - usePDFProjections = false; - - %Maximum number of data to use in GMM fitting of projection distributions - maxNumGMM = 10000; - - %Number of replicates to use in GMM fits - gmm_replicates = 3; - - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - - - - segParams.maxN - segParams.fc = fc; - segParams.fs = fs; - segParams.pulsewindow = pulseWindow; - segParams.noiseFactor = noiseFactor; - segParams.mpf = mpf; - segParams.male = male; - segParams.female = female; - segParams.bout = bout; - segParams.male_IPI = male_IPI; - segParams.probThreshold = probThreshold; - segParams.minFemalePulseSize = minFemalePulseSize; - segParams.filterWindow = filterWindow; - segParams.probModes = probModes; - segParams.noiseThreshold = noiseThreshold; - segParams.minMaleBoutFraction = minMaleBoutFraction; - segParams.minMaleDuration = minMaleDuration; - segParams.smoothParameter_male = smoothParameter_male; - segParams.smoothParameter_female = smoothParameter_female; - segParams.smoothParameter_amplitudes = smoothParameter_amplitudes; - segParams.amplitudeThreshold = amplitudeThreshold; - segParams.noiseLikelihoodThreshold = noiseLikelihoodThreshold; - segParams.maleThreshold = maleThreshold; - segParams.ampPostThreshold = ampPostThreshold; - segParams.maxNumNoise = maxNumNoise; - segParams.maxNumPeaks = maxNumPeaks; - segParams.maxNumPeaks_firstMode = maxNumPeaks_firstMode; - segParams.num_male_both_modes = num_male_both_modes; - segParams.female_IPI_limit = female_IPI_limit; - segParams.num_female_IPI_limit = num_female_IPI_limit; - segParams.stop_recording_time = stop_recording_time; - segParams.usePDFProjections = usePDFProjections; - segParams.maleTestDuration = maleTestDuration; - - diff --git a/PulseSegmentation_virilis.m b/subroutines/PulseSegmentation_virilis.m similarity index 92% rename from PulseSegmentation_virilis.m rename to subroutines/PulseSegmentation_virilis.m index 77d4eb5..8ef2b63 100644 --- a/PulseSegmentation_virilis.m +++ b/subroutines/PulseSegmentation_virilis.m @@ -1,31 +1,27 @@ function [pulseInfoF, pulseInfoM, pulseInfo,male_song_times_final] = ... PulseSegmentation_virilis(xs,Ps, xempty, segParams) - -%========PARAMETERS================= -% segParams.fc = a; % frequencies examined. These will be -% % converted to CWT scales later on. -% -% segParams.fs = b; % sample rate (in Hz) -% -% segParams.pulsewindow = c; %factor for computing window around pulse peak (this determines how much of the signal before and after the peak is included in the pulse.) -% -% xn = xempty; -% noise = d*mean(abs(xn)); %d is set in params file -% segParams.wnwMinAbsVoltage = noise; %Minimum Absolute Value of the Voltage = g times the mean -% -% segParams.mpf = e; %male pulse carrier frequency -% -% segParams.male = f; -% segParams.female = g; -% segParams.bout = h; +%Subroutine for heuristic male bout calling analysis +%Inputs: +% xs -> 1d time series containing song data +% Ps -> wavelet amplitudes +% xempty -> noise data +% segParams -> struct containing run parameters +% +%Outputs: +% pulseInfoF -> struct containing information about female pulse calls +% pulseInfoM -> struct containing information about male pulse calls +% male_song_times_final -> start and end times of called male bouts +% +% (C) Gordon J. Berman, Jan Clemens, Kelly M. LaRue, and Mala Murthy, 2015 +% Princeton University Fs = segParams.fs; LL = length(xs); xn = xempty; - noise = segParams.noiseFactor*mean(abs(xn)); %d is set in params file - segParams.wnwMinAbsVoltage = noise; %Minimum Absolute Value of the Voltage = g times the mean + noise = segParams.noiseFactor*mean(abs(xn)); + segParams.wnwMinAbsVoltage = noise; sp = segParams; diff --git a/subroutines/break_up_female_pulses.m b/subroutines/break_up_female_pulses.m index aa78687..e1e49de 100644 --- a/subroutines/break_up_female_pulses.m +++ b/subroutines/break_up_female_pulses.m @@ -1,4 +1,15 @@ function female_pulses = break_up_female_pulses(female_pulses,amps,segmentParameters) +%Finds individual female pulses within female regions +%Inputs: +% female_pulses -> cell array containing many collections of female pulse regions +% amps -> wavelet amplitudes +% segmentParameters -> struct containing run parameters +% +%Outputs: +% female_pulses -> broken-up version of the input +% +% (C) Gordon J. Berman, Jan Clemens, Kelly M. LaRue, and Mala Murthy, 2015 +% Princeton University amps2 = gaussianfilterdata(amps,segmentParameters.smoothParameter_amplitudes); amps2(amps == 0) = 0; diff --git a/subroutines/findLikelihoodModelsFromSongs.m b/subroutines/findLikelihoodModelsFromSongs.m deleted file mode 100644 index a40d524..0000000 --- a/subroutines/findLikelihoodModelsFromSongs.m +++ /dev/null @@ -1,214 +0,0 @@ -function likelihoodModels = findLikelihoodModelsFromSongs(male_songs,female_songs,overlap_songs,P_noise,dt) - - - maxNumPeaks = 4; - maxNumPeaks_firstMode = 6; - gmm_replicates = 3; - probModes = 41; - wav = 'fbsp2-1-2'; - maxNumGMM = 10000; - frequencies = 100:20:900; - K = scal2frq(1,wav,dt); - scales = K ./ frequencies; - - L = length(frequencies); - - - - numFiles = length(male_songs(:,1)); - - - - num_male = 0; - num_female = 0; - num_overlap = 0; - for i=1:numFiles - for j=1:32 - if ~isempty(male_songs{i,j}) - num_male = num_male + length(male_songs{i,j}(:,1)); - end - if ~isempty(female_songs{i,j}) - num_female = num_female + length(female_songs{i,j}(:,1)); - end - if ~isempty(overlap_songs{i,j}) - num_overlap = num_overlap + length(overlap_songs{i,j}(:,1)); - end - end - end - - - % Run PCAs - - fprintf(1,'Finding Male Principal Components\n'); - - - all_male = zeros(num_male,L); - keepMale = true; - - count = 1; - for i=1:numFiles - for j=1:32 - if ~isempty(male_songs{i,j}) - all_male(count:count+length(male_songs{i,j}(:,1))-1,:) = male_songs{i,j}; - count = count + length(male_songs{i,j}(:,1)); - end - end - end - - if count > 1 - male_mean = mean(all_male); - [coeffs_male,scores_male,latent_male] = princomp(all_male); - else - keepMale = false; - coeffs_male = []; - scores_male = 0; - latent_male = []; - end - - - % - - fprintf(1,'Finding Female Principal Components\n'); - - - all_female = zeros(num_female,L); - keepFemale = true; - - count = 1; - for i=1:numFiles - for j=1:32 - if ~isempty(female_songs{i,j}) - all_female(count:count+length(female_songs{i,j}(:,1))-1,:) = female_songs{i,j}; - count = count + length(female_songs{i,j}(:,1)); - end - end - end - - if count > 1 - female_mean = mean(all_female); - [coeffs_female,scores_female,latent_female] = princomp(all_female); - else - keepFemale = false; - coeffs_female = []; - scores_female = 0; - latent_female = []; - end - - - % - - fprintf(1,'Finding Overlap Principal Components\n'); - - - all_both = zeros(num_overlap,L); - keepBoth = true; - - count = 1; - for i=1:numFiles - for j=1:32 - if ~isempty(overlap_songs{i,j}) - all_both(count:count+length(overlap_songs{i,j}(:,1))-1,:) = overlap_songs{i,j}; - count = count + length(overlap_songs{i,j}(:,1)); - end - end - end - - if count > 1 - both_mean = mean(all_both); - [coeffs_both,scores_both,latent_both] = princomp(all_both); - else - keepBoth = false; - coeffs_both = []; - scores_both = 0; - latent_both = []; - end - - % Noise PCA - - - fprintf(1,'Finding Noise Principal Components\n'); - - %Pnoise_norm = Pnoise' ./ repmat(sum(Pnoise)',1,Nfft/2+1); - P_noise = P_noise'; - noise_mean = mean(P_noise); - [coeffs_noise,scores_noise,latent_noise] = princomp(P_noise); - - - % Find PDFs - - fprintf(1,'Finding PDFs\n'); - - - malePDFs = cell(probModes,1); - femalePDFs = cell(probModes,1); - noisePDFs = cell(probModes,1); - bothPDFs = cell(probModes,1); - keepBoths = repmat(keepBoth,probModes,1); - keepMales = repmat(keepMale,probModes,1); - keepFemales = repmat(keepFemale,probModes,1); - for i=1:probModes - - fprintf(1,'\t #%2i of %2i\n',i,probModes); - if i == 1 - q = maxNumPeaks_firstMode; - else - q = maxNumPeaks; - end - - if keepMales(i) - malePDFs{i} = findBestGMM_AIC(scores_male(:,i),q,gmm_replicates,maxNumGMM); - else - malePDFs{i} = []; - end - - if keepFemales(i) - femalePDFs{i} = findBestGMM_AIC(scores_female(:,i),q,gmm_replicates,maxNumGMM); - else - femalePDFs{i} = []; - end - - noisePDFs{i} = findBestGMM_AIC(scores_noise(:,i),q,gmm_replicates,maxNumGMM); - - if keepBoths(i) - bothPDFs{i} = findBestGMM_AIC(scores_both(:,i),q,gmm_replicates,maxNumGMM); - else - bothPDFs{i} = []; - end - - end - - - if keepMale - likelihoodModels.malePDFs = malePDFs; - likelihoodModels.male_mean = male_mean; - likelihoodModels.coeffs_male = coeffs_male; - likelihoodModels.latent_male = latent_male; - end - - if keepFemale - likelihoodModels.femalePDFs = femalePDFs; - likelihoodModels.female_mean = female_mean; - likelihoodModels.coeffs_female = coeffs_female; - likelihoodModels.latent_female = latent_female; - end - - likelihoodModels.noisePDFs = noisePDFs; - likelihoodModels.noise_mean = noise_mean; - likelihoodModels.coeffs_noise = coeffs_noise; - likelihoodModels.latent_noise = latent_noise; - - if keepBoth - likelihoodModels.bothPDFs = bothPDFs; - likelihoodModels.both_mean = both_mean; - likelihoodModels.coeffs_both = coeffs_both; - likelihoodModels.latent_both = latent_both; - end - - likelihoodModels.probModes = probModes; - likelihoodModels.frequencies = frequencies; - likelihoodModels.scales = scales; - likelihoodModels.dt = dt; - likelihoodModels.wav = wav; - - - \ No newline at end of file diff --git a/subroutines/findNoiseModel.m b/subroutines/findNoiseModel.m index e06ef94..b2521ae 100644 --- a/subroutines/findNoiseModel.m +++ b/subroutines/findNoiseModel.m @@ -1,5 +1,19 @@ function [noiseModel,obj,posts,threshold,idx] = findNoiseModel(P,amps,segmentParameters) - +%Generates noise likelihood model from data +%Inputs: +% P -> wavelet transform of data +% amps -> wavelet amplitudes +% segmentParameters -> struct containing run parameters +% +%Output: +% noiseModel -> struct containing noise likelihood model information +% obj -> amplitude gaussian mixture model output +% posts -> posterior probabilities for noise model based on GMM +% threshold -> amplitude threshold for noise calls +% idx -> regions chosen to model noise behavior +% +% (C) Gordon J. Berman, Jan Clemens, Kelly M. LaRue, and Mala Murthy, 2015 +% Princeton University fprintf(1,'Creating Noise Model...\n'); diff --git a/subroutines/findPeaks.m b/subroutines/findPeaks.m deleted file mode 100644 index 0329dac..0000000 --- a/subroutines/findPeaks.m +++ /dev/null @@ -1,28 +0,0 @@ -function [peaks,maxIdx,amps,obj,posts] = findPeaks(P,noiseProbs,segmentParameters) - - numToSample = 10000; - numPeaks = 2; - replicates = 3; - - %amps = gaussianfilterdata(sum(P,2),segmentParameters.smoothParameter_amplitudes); - amps = sum(P,2); - obj = gmixPlot(sampleFromMatrix(log(amps)./log(10),numToSample),numPeaks,[],[],true,[],[],[],replicates); - posts = posterior(obj,log(amps)./log(10)); - [~,minIdx] = min(obj.mu); - posts = posts(:,minIdx); - - %amps(posts > segmentParameters.amplitudeThreshold) = 0; - amps(noiseProbs >= segmentParameters.noiseThreshold) = 0; - %amps(noiseLikelihoods > segmentParameters.noiseLikelihoodThreshold) = 0; - - maxIdx = find(imregionalmax(amps) & amps > 0); - minIdx = find(imregionalmin(amps)); - - L = length(maxIdx); - peaks = cell(L,1); - parfor i=1:L - a = find(minIdx>maxIdx(i),1,'first'); - b = find(minIdx num_time_points x length(frequencies) array of wavelet data -% likelihoodModels -> fitted likelihood models from -% find_songs_from_hand_annotation.m (default:exampleLikelihoodModels) -% noiseModel -> fitted noise likelihood model -% segmentParameters -> struct containing parameters -% plotsOn -> true if plot are desired (default = true) -% plotData -> 1d song data to plot (only used if plotsOn = true) -% -%Outputs: -% probs -> Nx4 array of posterior probabilities -% likelihoods -> Nx4 array of log likelihood scores -% noiseP -> probabilities that a particular point belongs to the noise -% model -% P -> wavelet amplitudes -% CCs -> struct containing statistis from analysis -% -% (C) Gordon J. Berman, Jan Clemens, Kelly M. LaRue, and Mala Murthy, 2015 -% Princeton University - - if nargin < 4 || isempty(plotsOn) - plotsOn = true; - end - - - probModes = segmentParameters.probModes; - - smoothParameter_male = segmentParameters.smoothParameter_male; - smoothParameter_female = segmentParameters.smoothParameter_female; - - min_male_length = 1; - min_female_length = 1; - - malePDFs = likelihoodModels.malePDFs; - femalePDFs = likelihoodModels.femalePDFs; - noisePDFs = noiseModel.noisePDFs; - bothPDFs = likelihoodModels.bothPDFs; - - male_mean = likelihoodModels.male_mean; - female_mean = likelihoodModels.female_mean; - noise_mean = noiseModel.noise_mean; - both_mean = likelihoodModels.both_mean; - - coeffs_male = likelihoodModels.coeffs_male; - coeffs_female = likelihoodModels.coeffs_female; - coeffs_noise = noiseModel.coeffs_noise; - coeffs_both = likelihoodModels.coeffs_both; - - - - s = size(data); - if min(s) == 1 - fprintf(1,'Performing Wavelet Transform\n'); - scales = likelihoodModels.scales; - wav = 'fbsp2-1-2'; - C = cwt(data,scales,wav); - P = C'.*conj(C'); - clear C; - else - P = data; - if plotsOn && nargin == 5 - data = plotData; - end - end - - N = length(P(:,1)); - - - fprintf(1,'Calculating Projections\n'); - dataScores_male = bsxfun(@minus,P,male_mean) * coeffs_male(:,1:probModes); - dataScores_female = bsxfun(@minus,P,female_mean) * coeffs_female(:,1:probModes); - dataScores_noise = bsxfun(@minus,P,noise_mean) * coeffs_noise(:,1:probModes); - dataScores_both = bsxfun(@minus,P,both_mean) * coeffs_both(:,1:probModes); - - - fprintf(1,'Finding Likelihoods\n'); - likelihoods = zeros(N,4); - - for i=1:probModes - - likelihoods(:,1) = likelihoods(:,1) + log(pdf(malePDFs{i},dataScores_male(:,i))); - likelihoods(:,2) = likelihoods(:,2) + log(pdf(femalePDFs{i},dataScores_female(:,i))); - likelihoods(:,3) = likelihoods(:,3) + log(pdf(noisePDFs{i},dataScores_noise(:,i))); - likelihoods(:,4) = likelihoods(:,4) + log(pdf(bothPDFs{i},dataScores_both(:,i))); - - end - - - fprintf(1,'Computing Probabilities\n'); - maxVal = max(likelihoods(~isnan(likelihoods) & ~isinf(likelihoods))); - minVal = min(likelihoods(~isnan(likelihoods) & ~isinf(likelihoods))); - likelihoods(isnan(likelihoods) | isinf(likelihoods)) = minVal; - - if smoothParameter_male > 1 - likelihoods(:,1) = gaussianfilterdata(likelihoods(:,1),smoothParameter_male); - likelihoods(:,4) = gaussianfilterdata(likelihoods(:,4),smoothParameter_male); - end - - if smoothParameter_female > 1 - likelihoods(:,2) = gaussianfilterdata(likelihoods(:,2),smoothParameter_female); - likelihoods(:,3) = gaussianfilterdata(likelihoods(:,3),smoothParameter_female); - end - - probs = exp(likelihoods-maxVal); - partition = sum(probs,2); - probs = bsxfun(@rdivide,probs,partition); - - sumProbs = sum(probs)./N; - - maxVals = max(likelihoods,[],2); - subLikes = exp(bsxfun(@minus,likelihoods,maxVals)); - partition = zeros(N,1); - for i=1:4 - partition = partition + subLikes(:,i)*sumProbs(i); - end - - probs = bsxfun(@rdivide,bsxfun(@times,subLikes,sumProbs),partition); - noiseP = probs(:,3); - - - probs = bsxfun(@rdivide,probs,sum(probs,2)); - - - if plotsOn || nargout == 5 - - probs2 = probs(:,1:3); - probs2(:,1) = probs2(:,1) + probs(:,4); - - [~,maxIdx] = max(probs2,[],2); - - - CC_male = largeBWConnComp(maxIdx == 1 | maxIdx == 4,min_male_length); - CC_female = largeBWConnComp(maxIdx == 2,min_female_length); - - CCs = {CC_male,CC_female}; - - figure - - subplot(2,1,1) - hold on - for i=1:length(CC_male.PixelIdxList) - rectangle('Position',... - [CC_male.PixelIdxList{i}(1) -1 length(CC_male.PixelIdxList{i}) 2],... - 'facecolor','b','edgecolor','b'); - end - - for i=1:length(CC_female.PixelIdxList) - rectangle('Position',... - [CC_female.PixelIdxList{i}(1) -1 length(CC_female.PixelIdxList{i}) 2],... - 'facecolor','r','edgecolor','r'); - end - - plot(data,'k-') - - ylim([-.3 .3]) - - - - subplot(2,1,2) - plot(probs(:,1)+probs(:,4),'bo-'); - hold on - plot(probs(:,2),'rs-'); - plot(probs(:,3),'k^-'); - ylim([-.02 1.02]) - end diff --git a/subroutines/find_female_pulses_during_male.m b/subroutines/find_female_pulses_during_male.m index 8177da4..e83a81f 100644 --- a/subroutines/find_female_pulses_during_male.m +++ b/subroutines/find_female_pulses_during_male.m @@ -1,7 +1,20 @@ function [female_pulses,run_data] = ... find_female_pulses_during_male(male_song_times_final,P,... likelihoodModels,female_song_times,amps,segmentParameters) - +%Finds female pulses within male regions +%Inputs: +% male_song_times_final -> cell array containing many collections of female pulse regions +% P -> wavelet values +% likelihoodModels -> struct containing likelihood model information +% female_song_times -> start and end times of female song +% amps -> wavelet amplitudes +% segmentParameters -> struct containing run parameters +% +%Outputs: +% female_pulses -> times of all female pulses +% +% (C) Gordon J. Berman, Jan Clemens, Kelly M. LaRue, and Mala Murthy, 2015 +% Princeton University if nargin < 5 || isempty(segmentParameters) segmentParameters = params_virilis; diff --git a/subroutines/makeLikelihoodModelPlot.m b/subroutines/makeLikelihoodModelPlot.m deleted file mode 100644 index 96c008b..0000000 --- a/subroutines/makeLikelihoodModelPlot.m +++ /dev/null @@ -1,67 +0,0 @@ -function outputStats = makeLikelihoodModelPlot(likelihoodModels,confidenceInterval,numSamples) - - maleColors = 'bc'; %blue and cyan - femaleColors = 'rm'; %red and magenta - bothColors = 'gg'; %dark and light green - noiseColors = 'kg'; %black and gray - - probModes = likelihoodModels.probModes; - numFreqs = length(likelihoodModels.frequencies); - freqs = likelihoodModels.frequencies; - - - if ~isempty(likelihoodModels.coeffs_male) - - fprintf(1,'Processing Male PDF Models\n'); - - randNums = rand(numSamples,probModes); - malePDFs = likelihoodModels.malePDFs; - for i=1:probModes - - - q = zeros(numSamples,1); - a = malePDFs{i}; - parfor j=1:numSamples - f = @(x) cdf(a,x) - randNums(j,i); - q(j) = fzero(f,0); - end - - randNums(:,i) = q; - - end - - - currentSamples = repmat(likelihoodModels.male_mean,numSamples,1); - maleCoeffs = likelihoodModels.coeffs_male; - parfor i=1:numSamples - - x = currentSamples(i,:); - y = randNums(i,:); - - - for j=1:probModes - x = x + y(j)*maleCoeffs(:,j)'; - end - - currentSamples(i,:) = x; - - end - - outputStats.currentSamples = currentSamples; - outputStats.medianMale = median(currentSamples); - dx = (1-confidenceInterval)/2; - outputStats.maleBounds = quantile(currentSamples,[dx,1 - dx]); - - - -% area([freqs fliplr(freqs) freqs(1)],[outputStats.maleBounds(1,:) flipud(outputStats.maleBounds(2,:)) outputStats.maleBounds(1,1)],'color','c') -% hold on -% plot(freqs,outputStats.medianMale,'b-','linewidth',2) -% -% drawnow; -% keyboard - - clear randNums maleCoeffs currentSamples - - - end \ No newline at end of file diff --git a/subroutines/makeMaleFemalePlot.m b/subroutines/makeMaleFemalePlot.m index 3e42817..c1023dc 100644 --- a/subroutines/makeMaleFemalePlot.m +++ b/subroutines/makeMaleFemalePlot.m @@ -1,35 +1,14 @@ function makeMaleFemalePlot(data,malepulseInfo,femalepulseInfo) - - +%Makes plot of called male/female regions +%Inputs: +% data -> 1d time series +% malepulseInfo -> male pulse information returned by segmentVirilisSong +% femalepulseInfo -> female pulse information returned by segmentVirilisSong +% +% (C) Gordon J. Berman, Jan Clemens, Kelly M. LaRue, and Mala Murthy, 2015 +% Princeton University -% -% hold on -% if ~isempty(malepulseInfo.w0) -% cc = [0 0 1]; -% x = malepulseInfo.w0; -% y = malepulseInfo.w1; -% for i=1:length(x) -% rectangle('Position',[x(i) -1 y(i)-x(i)+1 2],'facecolor',cc,'edgecolor',cc); -% end -% end -% -% if ~isempty(femalepulseInfo.w0) -% cc = [1 0 0]; -% x = femalepulseInfo.w0; -% y = femalepulseInfo.w1; -% for i=1:length(x) -% rectangle('Position',[x(i) -1 y(i)-x(i)+1 2],'facecolor',cc,'edgecolor',cc); -% end -% end -% -% plot(data,'k-') -% -% ylim([-.3 .3]) - - - - N = length(data); male_regions = false(N,1); diff --git a/subroutines/segnspp.m b/subroutines/segnspp.m deleted file mode 100644 index b4b80f3..0000000 --- a/subroutines/segnspp.m +++ /dev/null @@ -1,66 +0,0 @@ -function xempty = segnspp(ssf) -%%%%%%%%%%%%%%%%%%%%%%%%%%% -%%Function runs sinesongfinder (multitaper spectral analysis) on recording -%%Finds putative noise by fitting a mixture model to the distribution of -%%power values (A) and taking the lowest mean (var) as noise -%%%%%%%%%%%%%%%%%%%%%%%%%%% -low_freq_cutoff=100; -high_freq_cutoff=1000; -maxNumPoints = 20000; -maxIter = 500; -cutoff_sd=3; -%find freq range of ssf.A to analyze -low_freq_index = find(ssf.f>low_freq_cutoff,1,'first'); -high_freq_index = find(ssf.flow_freq_cutoff,1,'first'); -high_freq_index = find(ssf.f maxNumPoints -% A_sums = sampleFromMatrix(A_sums,maxNumPoints); -% end - -for k=1:4 - obj{k}=gmdistribution.fit(sampleFromMatrix(A_sums',maxNumPoints),k); - if obj{k}.Converged == 1%keep AIC only for those that converged - AIC(k)=obj{k}.AIC; - end -end -[minAIC,numComponents]=min(AIC);%best fit model -noise_index = find(obj{numComponents}.mu == min(obj{numComponents}.mu));%find the dist in the mixture model with the lowest mean -presumptive_noise_mean = obj{numComponents}.mu(noise_index); -presumptive_noise_var = obj{numComponents}.Sigma(noise_index); -presumptive_noise_SD = sqrt(presumptive_noise_var); - -%Collect samples of noise (all segments with A ? mean + SD * cutoff_sd) and -%concatenate -noise_cutoff = presumptive_noise_mean + (presumptive_noise_SD * cutoff_sd); - - -%get indices of ssf.A ? noise_cutoff - -A_noise_indices = find(A_sums maxNumNoise - q = find(xx == maxNumNoise); - xx = xx(1:q); - end - noise(xx) = sample_noise(1:length(xx)); - count = count + length(xx); - - %noise = cat(1,noise,sample_noise); - end - - end -end - - -xempty = noise(1:(count-1)); -keyboard - - - diff --git a/subroutines/sinesongfinder.m b/subroutines/sinesongfinder.m deleted file mode 100644 index 919c982..0000000 --- a/subroutines/sinesongfinder.m +++ /dev/null @@ -1,92 +0,0 @@ -%function SSF=sinesongfinder(d,fs,NW,K,dT,dS,pval) -% -%d=decimate(d,4); fs=fs/4; % if fs>10e3 -%ssf=sinesongfinder(d,fs,11,21,0.02,0.01,0.01) % mosquito -%ssf=sinesongfinder(d,fs,12,20,0.1,0.01,0.05) % fruit fly -%SINEsongfinder_plot(ssf); -% -%NW = time-bandwidth product for tapers -%K = num independent tapers to average over, must be < 2*NW -%dT = window length -%dS = window step size -%pval = criterion for F-test -% -%might need to: -%addpath chronux\spectral_analysis\helper\ -%addpath chronux\spectral_analysis\continuous\ - -function SSF=sinesongfinder(d,fs,NW,K,dT,dS,pval) - -dT2=round(dT*fs); -dS2=round(dS*fs); -plotit=0; % plot it, or don't plot it, there is no try - -% [d t]=daqread(filename); % do it this way when pipelined -% d=d(:,chan); -d=d-repmat(mean(d),size(d,1),1); -% fs=1/max(diff(t)); - -[tapers,eigs]=dpsschk([NW K],dT2,fs); - -params=[]; -params.tapers=tapers; -params.Fs=fs; -params.pad=0; -params.fpass=[0 fs/2]; -i=1; -kk=ceil((length(d)-dT2+1)/dS2); -[f,findx]=getfgrid(params.Fs,max(2^(nextpow2(dT2)+params.pad),dT2),params.fpass); -Fval=zeros(length(f),kk); A=zeros(length(f),kk); -[Fval(:,1),A(:,1),f,sig,sd] = ftestc(d(i:(i+dT2-1)),params,pval/dT2,'n'); -parfor k=2:kk - ii = 1 + (k-1)*dS2; - %[Fval(:,k),A(:,k),f,sig,sd] = ftestc(d(i:(i+dT2-1)),params,pval/dT2,'n'); - [Fval(:,k),A(:,k),~,~,~] = ftestc(d(ii:(ii+dT2-1)),params,pval/dT2,'n'); - %i=i+dS2; -end -t=(0:(size(Fval,2)-1))*dS2/fs; -events=[]; -for(i=1:size(Fval,2)) - fmax=crx_findpeaks(Fval(:,i),sig); %this function name is a hack. chronux 'findpeaks' conflicts with Matlab 'findpeaks'. - %I have renamed the chronux function as crx_findpeaks and changed this line too. - %This means this code is incompatible with the public version of chronux. - %Users must use our version. Future versions of chronux are expected to - %fix this namespace conflict, which will require rewrite of this line. - events=[events; ... - repmat(t(i)+dT/2,length(fmax(1).loc),1) f(fmax(1).loc)']; - if(plotit && length(fmax(1).loc)>0) % show the individual time slices separately - clf; - subplot(3,1,1); - plot(f,abs(A(:,i)),'k'); - ylabel('amplitude'); - title(['# tapers = ' num2str(K) ', win len = ' num2str(dT) ', win step = ' num2str(dS)]); - subplot(3,1,2); hold on; - plot(f,Fval(:,i),'k'); - plot([min(f) max(f)],[sig sig],'k:'); - for(j=1:length(fmax(1).loc)) - plot(f(fmax(1).loc(j)),interp1(f,Fval(:,i),f(fmax(1).loc(j))),'ko'); - end - %axis([0 1000 0 1]); - ylabel('F-stat'); - subplot(3,1,3); - idx=round(t(i)*fs):round((t(i)+dT)*fs); - plot(idx,d(idx),'k'); - axis tight - xlabel('frequency (Hz)'); - ylabel('time series'); - keyboard; % 'return' to continue - end -end - -SSF.d=d; -SSF.fs=fs; -SSF.NW=NW; -SSF.K=K; -SSF.dT=dT; -SSF.dS=dS; -SSF.pval=pval; -SSF.t=t; -SSF.f=f; -SSF.A=A; -SSF.Fval=Fval; -SSF.events=events; diff --git a/subroutines/sinesongfinder_gjb.m b/subroutines/sinesongfinder_gjb.m deleted file mode 100644 index ea14937..0000000 --- a/subroutines/sinesongfinder_gjb.m +++ /dev/null @@ -1,98 +0,0 @@ -%function SSF=sinesongfinder(d,fs,NW,K,dT,dS,pval) -% -%d=decimate(d,4); fs=fs/4; % if fs>10e3 -%ssf=sinesongfinder(d,fs,11,21,0.02,0.01,0.01) % mosquito -%ssf=sinesongfinder(d,fs,12,20,0.1,0.01,0.05) % fruit fly -%SINEsongfinder_plot(ssf); -% -%NW = time-bandwidth product for tapers -%K = num independent tapers to average over, must be < 2*NW -%dT = window length -%dS = window step size -%pval = criterion for F-test -% -%might need to: -%addpath chronux\spectral_analysis\helper\ -%addpath chronux\spectral_analysis\continuous\ - -function SSF=sinesongfinder(d,fs,NW,K,dT,dS,pval) - -dT2=round(dT*fs); -dS2=round(dS*fs); -plotit=0; % plot it, or don't plot it, there is no try - -% [d t]=daqread(filename); % do it this way when pipelined -% d=d(:,chan); -%d=d-repmat(mean(d),size(d,1),1); -d = bsxfun(@minus,d,mean(d)); -% fs=1/max(diff(t)); - -[tapers,~]=dpsschk([NW K],dT2,fs); - -params=[]; -params.tapers=tapers; -params.Fs=fs; -params.pad=0; -params.fpass=[0 fs/2]; -i=1; -kk=ceil((length(d)-dT2+1)/dS2); - -[f,~]=getfgrid(params.Fs,max(2^(nextpow2(dT2)+params.pad),dT2),params.fpass); - - -Fval=zeros(length(f),kk); -A=zeros(length(f),kk); -parfor k=1:kk - ii = 1 + dS2*(k-1); - d2 = d(ii:(ii+dT2-1)); - %[Fval(:,k),A(:,k),f,sig,~] = ftestc(d(i:(i+dT2-1)),params,pval/dT2,'n'); - [Fval(:,k),A(:,k),~,~,~] = ftestc(d2,params,pval/dT2,'n'); - %i=i+dS2; -end -t=(0:(size(Fval,2)-1))*dS2/fs; -events=[]; - -% for i=1:size(Fval,2) -% fmax=crx_findpeaks(Fval(:,i),sig); %this function name is a hack. chronux 'findpeaks' conflicts with Matlab 'findpeaks'. -% %I have renamed the chronux function as crx_findpeaks and changed this line too. -% %This means this code is incompatible with the public version of chronux. -% %Users must use our version. Future versions of chronux are expected to -% %fix this namespace conflict, which will require rewrite of this line. -% events=[events; ... -% repmat(t(i)+dT/2,length(fmax(1).loc),1) f(fmax(1).loc)']; -% if(plotit && ~isempty(fmax(1).loc)) % show the individual time slices separately -% clf; -% subplot(3,1,1); -% plot(f,abs(A(:,i)),'k'); -% ylabel('amplitude'); -% title(['# tapers = ' num2str(K) ', win len = ' num2str(dT) ', win step = ' num2str(dS)]); -% subplot(3,1,2); hold on; -% plot(f,Fval(:,i),'k'); -% plot([min(f) max(f)],[sig sig],'k:'); -% for j=1:length(fmax(1).loc)) -% plot(f(fmax(1).loc(j)),interp1(f,Fval(:,i),f(fmax(1).loc(j))),'ko'); -% end -% %axis([0 1000 0 1]); -% ylabel('F-stat'); -% subplot(3,1,3); -% idx=round(t(i)*fs):round((t(i)+dT)*fs); -% plot(idx,d(idx),'k'); -% axis tight -% xlabel('frequency (Hz)'); -% ylabel('time series'); -% keyboard; % 'return' to continue -% end -% end - -SSF.d=d; -SSF.fs=fs; -SSF.NW=NW; -SSF.K=K; -SSF.dT=dT; -SSF.dS=dS; -SSF.pval=pval; -SSF.t=t; -SSF.f=f; -SSF.A=A; -SSF.Fval=Fval; -SSF.events=events; diff --git a/returnCellLengths.m b/utilities/returnCellLengths.m similarity index 100% rename from returnCellLengths.m rename to utilities/returnCellLengths.m