-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinmethod_v1.m
416 lines (388 loc) · 23.2 KB
/
Binmethod_v1.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
% Montecarlo - 3D beam, kogia detectability model.
% Kait Frasier
% 7/23/2013
% JAH 9/2017 to make grid search for best fit to percent RL plot
%{
% Modeling individual click detectability = "group counting method"
% This means that every point generated by the model just represents a
% group of animals. The parameters of each are drawn from a series of
% probability distributions, which ultimately combine to dictate a recieved
% level (RL), at which point a threshold is used to decide whether or not
% the group is "heard".
%}
clearvars
% Parameters
n = 500; % the number of model runs that will feature in the probability distribution
N = 100000; % simulate this many points per model run
maxRange = 1000; % in meters
thresh = 132;% click detection threshold (amplitude in dB pp)
fignum = 1; % if fignum = 0 make no figures
spVec = {'kogia'}; itSp = 1; species = spVec{itSp};
% Parameters that can have multiple values have %***
% assume that some parameters have been determined
% using the click data = diveDepth, descAngle, direct, botAngle
% *** in loop
diveDepth = [435,100]; % ***
sdiveDepth = size(diveDepth);
diveDepths = [25,25];
SLm = [210,10]; SLs = [2,3];
descAnglem = [62,5];
sdescAngle = size(descAnglem);
descAngles = [5,5];
clickStartm = [50,50]; clickStarts = [10,10];
directm = [21,2];
sdirect = size(directm);
minBeamAmpm = [33,3];
minBeamAmps = [2,3];
descentPm = [.10 , .05];
% Parameters Unique to the Bin Method
rotHoriz = [180,20]; %***
srotHoriz = size(rotHoriz);
rotHorizs = [10,10];
rotVertForage = [65,10]; %***
srotVertForage = size(rotVertForage);
rotVertForages = [5,5];
rotVertDive = [50,20]; %***
srotVertDive = size(rotVertDive);
rotVertDives = [5,10];
%
TLprofile_directory = 'E:\Data\ESME\';
saveDir = 'E:\Data\John Reports\KogiaBin\';
% Check if output directory exits
if ~exist(saveDir,'dir')
mkdir(saveDir)
end
% file with grid search results
fnParms = fullfile(saveDir,sprintf('BinModel_ParmsFinal_%s.txt',...
species));
fid = fopen(fnParms,'a');
best = [1000]; %arbitrary large number
%
siteVec = {'DT','GC','MC'};
nsim = sdiveDepth(1) * srotHoriz(1) * srotVertForage(1) * srotVertDive(1);
diff = zeros(nsim,length(siteVec));
for itSite = 1:length(siteVec)
site = siteVec{itSite};
% TL model
polarFile = fullfile(TLprofile_directory,...
sprintf('%skogia_Jan\\118kHz\\%szoom1_118_3DTL_2.mat',site,site));
disp(polarFile);
outdir = fileparts(polarFile);
load(polarFile)
numAngle = length(thisAngle);
if ~exist('botDepthSort','var')
botDepthSort = botDepth_interp(IX,:);
end
% sort the bottom vectors by increasing angle
for preIt = 1:length(sortedTLVec)
sortedTLVec{preIt}(:,1) = sortedTLVec{preIt}(:,2);
end
rr_int = round(rr(2)-rr(1)); % figure out what the range step size is
nrr_new = rr_int*nrr;
rr_new = 0:rr_int:nrr_new; % What are the real values of the range vector? (in m)
pDetTotal = nan(n,1);
binVec = 0:100:maxRange;
binnedPercDet = nan(n,length(binVec)-1);
binnedCounts = nan(n,length(binVec)-1);
% Load measured Percent PP by site
if (strcmp(siteVec{1,itSite}, 'MC'));
load('E:\JAH\Kogia\Detections\MC_Kogia\MC_Kogia_binlog.mat');
elseif (strcmp(siteVec{1,itSite}, 'GC'));
load('E:\JAH\Kogia\Detections\GC_Kogia\GC_Kogia_binlog.mat');
elseif (strcmp(siteVec{1,itSite}, 'DT'));
load('E:\JAH\Kogia\Detections\DT_Kogia\DT_Kogia_binlog.mat');
end
% center of bins and nper number of percent for measurements
botbin = 116; topbin = 140; %used for both model and measurements
icen = find(center > botbin & center < topbin);
lnbper = log10(nbper(icen)); %used for goodness of fit
inot = find(~isinf(lnbper));
isim = 0; %counter for num of simulations per site
%
for itParms1 = 1: sdiveDepth(1)
diveDepthm = diveDepth(itParms1,:);
for itParms2 = 1: srotHoriz(1)
rotHorizm = rotHoriz(itParms2,:);
for itParms3 = 1: srotVertForage(1)
rotVertForagem = rotVertForage(itParms3,:);
for itParms4 = 1: srotVertDive(1)
rotVertDivem = rotVertDive(itParms4,:);
% variables to pick from a distribution for CV estimation
diveDepth_mean = diveDepthm(1) + diveDepthm(2)*rand(n,1); % mean dive altitude is somewhere between 175 and 225m
diveDepth_std = diveDepths(1) + diveDepths(2)*rand(n,1);% dive depth std. dev. is 10 to 20m
SL_mean = SLm(1) + SLm(2)*rand(n,1); % mean source level is between 210 and 220 dB pp - gervais
SL_std = SLs(1) + SLs(2)*rand(n,1); % add 2 to 5 db std dev to source level.
descAngle_mean = descAnglem(1) + descAnglem(2)*rand(n,1); % mean descent angle in deg, from tyack 2006 for blainvilles;
descAngle_std = descAngles(1) + descAngles(2)*rand(n,1); % std deviation of descent angle in deg, from tyack 2006 for blainvilles;
clickStart_mean = clickStartm(1) + clickStartm(2)*rand(n,1); % depth in meters at which clicking starts, from tyack 2006 for blainvilles;
clickStart_std = clickStarts(1) + clickStarts(2)*rand(n,1); % depth in meters at which clicking starts, from tyack 2006 for Cuvier's - blainvilles was unbelievably large;
directivity = directm(1) + directm(2)*rand(n,1); % directivity is between 25 and 27 dB PP (Zimmer et al 2005: Echolocation clicks of free-ranging Cuvier's beaked whales)
descentPerc = descentPm(1) + descentPm(2)*rand(n,1);
%
minBeamAmp_mean = minBeamAmpm(1) + minBeamAmpm(2)*rand(n,1); % minimum off-axis dBs down from peak
minBeamAmp_std = minBeamAmps(1) + minBeamAmps(2)*rand(n,1);
rotHorizDeg = rotHorizm(1) + rotHorizm(2)*rand(n,1);
rotHorizDeg_std = rotHorizs(1) + rotHorizs(2)*rand(n,1);
rotVertDegForage = rotVertForagem(1) + rotVertForagem(2)*rand(n,1);
rotVertDegForageStd = rotVertForages(1) + rotVertForages(2)*rand(n,1);
rotVertDegDive = rotVertDivem(1) + rotVertDivem(2)*rand(n,1);
rotVertDegDiveStd = rotVertDives(1) + rotVertDives(2)*rand(n,1);
for itr_n = 1:n % number of simulations loop
if rem(itr_n,100) == 0
fprintf('TL computation %d of %d\n', itr_n, n)
end
%%%%% Location Computation %%%%%
% rand location
randVec = ceil(rand(2,N)'.*repmat([2*maxRange, 2*maxRange], [N, 1]))...
- repmat([maxRange, maxRange], [N, 1]);
[theta, rho] = cart2pol(randVec(:,1),randVec(:,2)); % convert to polar coord.
clear randVec % trying to save on memory
% trim out the locations that are beyond the max range (corners of the
% 2*maxRange X 2*maxRange square, since now we are using a pi*maxRange^2
% circle)
jjj = 1;
rho2 = [];
theta2 = [];
for iii = 1:length(rho)
if rho(iii) < maxRange
rho2(jjj,1) = rho(iii);
theta2(jjj,1) = theta(iii);
jjj = jjj+1;
end
end
thetaDeg = make360(theta2*180/pi);
clear theta
% go from angle to ref indices
[angleRef,radRef] = angle_ref_comp(thetaDeg,rho2,thisAngle);
%%%%% Depth Computation %%%%%
% Compute bottom depth at each randomly selected point
count0 = 1;
tempDepth = zeros(size(angleRef));
keepPoint = ones(size(angleRef));
diveDepthRef = diveDepth_mean(itr_n) + diveDepth_std(itr_n)...
*randn(size(angleRef));
% Find points that are above surface or below bottom and correct them
flyingWhaleIdx = find(diveDepthRef>=sd | diveDepthRef<1);
while ~isempty(flyingWhaleIdx)
diveDepthRef(flyingWhaleIdx) = diveDepth_mean(itr_n)...
+ diveDepth_std(itr_n)*randn(size(flyingWhaleIdx)); % add variation to dive depth,
flyingWhaleIdx = find(diveDepthRef>=sd | diveDepthRef<1);
end
% Assign last n% to a descent phase
% Choose a depth between start of clicking and destination depth
% determine off-axis angle
descentIdx = (floor((1-descentPerc(itr_n,1))*length(rho2))+1:length(rho2))';
dFactor = rand(size(descentIdx));
clickStartVec = clickStart_mean(itr_n,1) + clickStart_std(itr_n,1).*randn(size(descentIdx));
% Find points that are above surface or below bottom and correct them
flyingWhaleIdx2 = find(clickStartVec>=sd | clickStartVec<1);
while ~isempty(flyingWhaleIdx2)
clickStartVec(flyingWhaleIdx2) = clickStart_mean(itr_n,1)...
+ clickStart_std(itr_n,1).*randn(size(flyingWhaleIdx2)); % add variation to dive depth,
flyingWhaleIdx2 = find(clickStartVec>=sd | clickStartVec<1);
end
descentDelta = dFactor.* (diveDepthRef(descentIdx,:) - clickStartVec);
diveDepthRef(descentIdx,1) = clickStartVec + descentDelta;
%%%%% Beam Angle Computation %%%%%
% Assign random beam orientation in horizontal (all orientations equally likely)
randAngleVec = rand(size(rho2)).*359;
theta2deg = theta2.*180./pi;
partAngle = 180 + make180(thetaDeg);
totalOffAxisHoriz = make180(randAngleVec - partAngle');
onAxisHorz = abs(totalOffAxisHoriz) <= rotHorizDeg(itr_n,1) + ...
rotHorizDeg_std(itr_n,1).*randn(1,size(totalOffAxisHoriz,2));
% Compute vertical component of shift between animal and sensor (sd =
% sensor depth)
dZ = abs(sd - diveDepthRef);
zAngle_180 = ceil(abs(atand(dZ./rho2)));
zAngle_180(descentIdx,1) = ceil(abs(atand(dZ(descentIdx,:)./radRef(descentIdx,:))) - ...
descAngle_mean(itr_n,1) + (descAngle_std(itr_n,1).*randn(size(descentIdx,1),1)));
% If they're foraging, allow one amount of vertical rotation
% if diving, different amount
onAxisVert = abs(zAngle_180) <= rotVertDegForage(itr_n,1) + ...
rotVertDegForageStd(itr_n,1)*randn(size(zAngle_180,1),1);
onAxisVert(descentIdx,1) = abs(zAngle_180(descentIdx,1) ) <= ...
(rotVertDegDive(itr_n,1) + rotVertDegDiveStd(itr_n,1)*randn(size(descentIdx,1),1));
% Compute variation to add to source level
SL_adj = SL_mean(itr_n,1) + (SL_std(itr_n,1)*randn(N,1));
% directVec = directivity_mean(itr_n,1)+(directivity_std(itr_n,1)*randn(N,1));
minAmp = minBeamAmp_mean(itr_n,1)+(minBeamAmp_std(itr_n,1)*randn(N,1));
%%%%% Transmission Loss Loop %%%%%
% initialize some variables
RL = nan(size(thetaDeg));
isheard = zeros(size(thetaDeg));
distTL = nan(size(thetaDeg));
%%%%% Transmission Loss Loop %%%%%
for itr2 = 1:length(thetaDeg)
% Compute location of this animal in the transmission loss matrix:
% Find which row you want to look at:
thisRd = rd_all{angleRef(itr2)};
[~,thisDepthIdx] = min(abs(thisRd - round(diveDepthRef(itr2))));
% Record the distance related portion of this transmission loss
thisSortedTL = real(sortedTLVec{angleRef(itr2)});
distTL(itr2) = thisSortedTL(thisDepthIdx,ceil(radRef(itr2)./rr_int));
% Add up all the sources of TL
if (onAxisVert(itr2)+onAxisHorz(itr2))==2
RL(itr2,1) = SL_adj(itr2) - distTL(itr2);
else
RL(itr2,1) = SL_adj(itr2) - distTL(itr2) - minAmp(itr2);
end
% Is the total TL less than the maximum allowed?
if thresh <= RL(itr2,1)
isheard(itr2,1) = 1; % detected it
end
end
pDetTotal(itr_n,1) = sum(isheard)./length(isheard)';
detVsLoc = [thetaDeg, rho2, isheard];
totalSim = rho2';
detSim = rho2(isheard==1)';
RL_keep = RL(isheard==1);
RLforHist(itr_n,:) = histc(RL_keep,120.5:1:190.5);
% Compute detections in range bins, so you can make a histogram if desired
% Makes more sense for click-based model
% preallocate
binTot = zeros(length(binVec)-1,1);
binDet = zeros(length(binVec)-1,1);
for itr2 = 1:length(binVec)-1
binTot(itr2) = length(find(totalSim>binVec(itr2) & totalSim<binVec(itr2 +1)));
binDet(itr2) = length(find(detSim>binVec(itr2) & detSim<binVec(itr2 +1)));
end
thisPercent = binDet./binTot;
% save the bin counts to the overall set, so you can get means and variances per bin.
binnedPercDet(itr_n,:) = thisPercent';
binnedCountsDet(itr_n,:) = binDet';
binnedCountsTot(itr_n,:) = binTot';
end
save(fullfile(saveDir,sprintf('%s_grpModOut_%dItrs_%s.mat',...
site,itr_n,species)),'-mat')
RLbins = 120.5:1:190.5;
RLnorm = RLforHist./(repmat(nansum(RLforHist,2),1,size(RLforHist,2)));
if (strcmp(species,'kogia'))
%JAH *** remove 16 for other than Kogia!
RLshift = RLbins+1-16; %16 is due to 320 versus 200
else
RLshift = RLbins+1;
end
mRL = nanmean(RLnorm)*100; %percentage
iRL = find(RLshift > botbin & RLshift < topbin);
lRL = log10(mRL(iRL));
isim = isim + 1;
diff(isim,itSite) = sum((lnbper(inot) - lRL(inot)).^2);
fprintf(fid,'\r\n %4s %4d %4d %4d %4d %4d %4d %4d %4d',...
site,diveDepthm,diveDepths,SLm,SLs);
fprintf(fid,'%4d %4d %4d %4d %4d %4d %4d %4d',...
descAnglem,descAngles,clickStartm,clickStarts);
fprintf(fid,'%4d %4d %4d %4d %4d %4d',...
directm,minBeamAmpm,minBeamAmps);
fprintf(fid,'%4d %4d %4d %4d %4d %4d %4d %4d',...
rotHorizm,rotHorizs,rotVertForagem,rotVertForages);
fprintf(fid,'%4d %4d %4d %4d %7.3f %7.3f diff = %8.4f',...
rotVertDivem,rotVertDives,descentPm,diff(isim,itSite));
fprintf(fid,' P(det) %1.3f std %1.3f', ...
nanmean(pDetTotal)*100, nanstd(pDetTotal)*100);
if (itSite == length(siteVec))
diff3 = sum(diff(isim,:),2);
fprintf(fid,' Sum = %8.4f',diff3);
if best > diff3
best = diff3;
fprintf(fid,' Best = %8.4f',best);
end
end
%
if fignum > 0
% Histogram of detectability as a function of range
spots = binVec(1:end-1)+(50);
areas = ((binVec(2:end).^2)*pi)-((binVec(1:end-1).^2)*pi);
means = nanmean(binnedPercDet)*100;
means_keep = (means>0);
spotsprune = spots(means_keep);
means = means(means_keep);
areas = areas(means_keep);
errsTop = nanstd(binnedPercDet(:,means_keep)*100);
errsBot = errsTop;
toobig = (errsTop + means)>100;
toosmall = (means - errsBot)<0;
errsTop(toobig) = 100-means(toobig);
errsBot(toosmall) = -(0-means(toosmall));
% plot Prob Detection
figure(fignum); fignum = fignum +1; %clf
hb1 = bar(spotsprune,means,1);
set(hb1,'EdgeColor','k','FaceColor','w')
hold on
ha = errorbar(spotsprune,means,errsBot,errsTop,'k');
Xdata = get(ha,'Xdata');
temp = 4:3:length(Xdata);
temp(3:3:end) = [];
% xleft and xright contain the indices of the left and right endpoints of the horizontal lines
xleft = temp; xright = temp+1;
Xdata(xleft) = Xdata(xleft) + 20;
Xdata(xright) = Xdata(xright) - 20;
set(ha,'Xdata',Xdata)
plot(spotsprune,means,'-k','LineWidth',3)
set(gca,'XTick',binVec,'FontSize',12)
set(gca,'XTickLabel',binVec)
xlabel(gca,'Horizontal Range (m)','FontSize',14)
ylabel(gca, 'Probability of Detection (%)','FontSize',14)
title({sprintf('Max Horiz. Range = %dm; mean P(det) = %1.2f%%; std = %1.2f%%', ...
maxRange, nanmean(pDetTotal)*100, nanstd(pDetTotal)*100)},'FontSize',14)
print(gcf,'-dpng','-r600',fullfile(saveDir,[site,'_',species,'_grpMod_pDet.png']))
saveas(gca,fullfile(saveDir,[site,'_',species,'_grpMod_pDet.fig']))
% plot percent det versus range
figure(fignum); fignum = fignum +1; clf;
binCountDetMean = nanmean(binnedCountsDet./...
repmat(sum(binnedCountsDet,2),1,size(binnedCountsDet,2)));
binCountDetStd = nanstd(binnedCountsDet./...
repmat(sum(binnedCountsDet,2),1,size(binnedCountsDet,2)));
binId = find(binCountDetMean-binCountDetStd<0);
binCountStdBot = binCountDetStd;
binCountStdBot(binId) = binCountDetMean(binId) ;
hb2 = bar(spots/1000,binCountDetMean,1);
hold on
errorbar(spots/1000,binCountDetMean,binCountStdBot,binCountDetStd,'.k');
set(hb2,'FaceColor',[1,1,1])
set(gca,'XTick',binVec,'FontSize',12)
set(gca,'XTickLabel',binVec)
xlabel(gca,'Horizontal Range (km)','FontSize',14)
ylabel(gca, '% of detections','FontSize',14)
title('Kogia Group: Modeled Detection Ranges','FontSize',14)
saveas(gca,fullfile(saveDir,[site,'_',species,'_grpMod_nDets.fig']))
saveas(gca,fullfile(saveDir,[site,'_',species,'_grpMod_nDets.png']))
%plot Percent det versus RL dBpp
figure(fignum); fignum = fignum +1; clf;
%errorbar(RLbins+1,nanmean(RLnorm)*100,nanstd(RLnorm)*100,'.k');
hold on;
hb3 = bar(RLbins+1,nanmean(RLnorm)*100,1);
set(hb3,'EdgeColor','k','FaceColor','w')
xlim([thresh,160])
ylim([0,30])
xlabel(gca,'RL (dB_p_p re 1\muPa)','FontSize',16)
ylabel(gca, 'Percent of detections','FontSize',16)
set(gca,'FontSize',12)
%plot(RLbins(6:end)+1,mean(RLnorm(:,6:end))*100,'-k','LineWidth',3)
title(siteVec{1,itSite});
print(gcf,'-dpng','-r300',fullfile(saveDir,[site,'_',species,'_grpkMod_RLdist.png']))
saveas(gca,fullfile(saveDir,[site,'_',species,'_grpMod_RLdist.fig']))
% Percent det versus RL as Log plot
%note -16 is to correct for 100kHz data versus fullband
figure(fignum); fignum = fignum +1; clf;
hb4 = bar(RLbins+1-16,mRL,1,...
'barwidth', 1, 'basevalue', 1);
set(hb4,'EdgeColor','k','FaceColor','w')
xlim([thresh-1-16,172-16])
ylim([.001,50])
set(gca,'YScale','log')
xlabel(gca,'RL (dB_p_p re 1\muPa)','FontSize',16)
ylabel(gca, 'Percent of detections','FontSize',16)
set(gca,'FontSize',12)
hold on;
plot(center,nbper,'b--o'); % measured data
title([siteVec{1,itSite},' Error= ',num2str(diff(itSite))]);
print(gcf,'-dpng','-r300',fullfile(saveDir,[site,'_',species,'_grpMod_RLlog.png']))
saveas(gca,fullfile(saveDir,[site,'_',species,'_grpMod_RLlog.fig']))
end
end
end
end
end
end
fclose(fid);