gext_latlonmask2 = conv2(gext.latlonmask, [1 1 1;1 1 1;1 1 1],'same')>0;
vypad = padarray(vy,[1 1 0],nan);
vypad = nanmean(cat(4, fillmissing(vypad,'nearest',2), fillmissing(vypad,'nearest',1)),4);
vypad = fillmissing(vypad,'nearest');
vypad(repmat(~gext_latlonmask2,1,1,gext.nt)) = nan;
F_vlat=griddedInterpolant({1:gext.nlat,1:gext.nlon,1:gext.nt},vypad,'nearest','nearest');
vxpad = padarray(vx,[1 1 0],nan);
vxpad = nanmean(cat(4, fillmissing(vxpad,'nearest',2), fillmissing(vxpad,'nearest',1)),4);
vxpad = fillmissing(vxpad,'nearest');
vxpad(repmat(~gext_latlonmask2,1,1,gext.nt)) = nan;
F_vlon=griddedInterpolant({1:gext.nlat,1:gext.nlon,1:gext.nt},vxpad,'nearest','nearest');
Flandpad = padarray(-W.landing./ (rho(:,:,1:end-1) .* repmat(area,1,1,gext.nt-1)) ,[1 1 0],nan);
Flandpad = nanmean(cat(4, fillmissing(Flandpad,'nearest',2), fillmissing(Flandpad,'nearest',1)),4);
Flandpad = fillmissing(Flandpad,'nearest');
Flandpad(repmat(~gext_latlonmask2,1,1,gext.nt-1)) = nan;
Flandpad(isnan(Flandpad))=0;
F_land=griddedInterpolant({1:gext.nlat,1:gext.nlon,1:gext.nt-1},Flandpad,'nearest');
F_out = griddedInterpolant({1:gext.nlat,1:gext.nlon},padarray(double(g.latlonmask),[1 1],0),'nearest','none');
tmp_b = sqrt( (vy-wlat).^2 + (vx-wlon).^2 );
tmp_g = sqrt( (vy).^2 + (vx).^2 );
figure('position',[0 0 1000 400]);
[Y,E] = discretize(reshape(tmp_g(:,:,id),[],1),100);
tmp3 = splitapply(@nansum,reshape(rho(:,:,id),[],1),Y);
bar(E(1:end-1)*1000/60/60,tmp3); xlim([0 30])
xlabel('Ground flight speed [m/s]');
[Y,E] = discretize(reshape(tmp_b(:,:,id),[],1),80);
tmp3 = splitapply(@nansum,reshape(rho(:,:,id),[],1),Y);
bar(E(1:end-1)*1000/60/60,tmp3); xlim([0 30])
xlabel('Bird flight speed [m/s]');
[Y,E] = discretize(reshape(tmp_g(:,:,id),[],1),100);
tmp3 = splitapply(@nansum,reshape(rho(:,:,id),[],1),Y);
bar(E(1:end-1)*1000/60/60,tmp3); xlim([0 30])
xlabel('Ground flight speed [m/s]');
[Y,E] = discretize(reshape(tmp_b(:,:,id),[],1),100);
tmp3 = splitapply(@nansum,reshape(rho(:,:,id),[],1),Y);
bar(E(1:end-1)*1000/60/60,tmp3); xlim([0 30])
xlabel('Bird flight speed [m/s]');
tmp = tmp_b(:,:,id) .* rho(:,:,id);
tmp3 = tmp_g(:,:,id) .* rho(:,:,id);
vbday(i_d) = nansum(tmp(:)) / nansum(tmp2(:));
vgday(i_d) = nansum(tmp3(:)) / nansum(tmp2(:));
figure('position',[0 0 1000 400]); hold on;
plot( g.day, vbday*1000/60/60 )
plot( g.day, vgday*1000/60/60 )
ylabel('Flight Speed [m/s]');
k=1.2; % [-] Induced power factor (p. 45).
m = sum((Sp.massmin+Sp.massmax)/2.*Sp.abondance/100)/1000; % [kg] mass of bird. Values found in appendix of (Aurbach et al., 2020)
gcst = 9.81; % [ms-2] gravity constant
% Vt [m/s] true speed (bird speed-wind speed)
B = sum((Sp.wingmin+Sp.wingmax)/2.*Sp.abondance/100)/100;% [m] Wing span. Values found in appendix of (Aurbach et al., 2020)
airdens = 1; % Air density ?
Sb = 0.00813*m^0.666; % [m2] body frontal area
CDb = 0.1; % [-] body drag coefficient (p. 51).
f_eng = @(Vt) (2*k*(m*gcst)^2)./(Vt*pi*B.^2*airdens) + airdens*Vt.^3*Sb*CDb/2 + Cpro/Ra*1.05*k^(3/4)*m^(3/2)*gcst^(3/2)*Sb^(1/4)*CDb^(1/4)/airdens^(1/2)/B^(3/2);
figure('position',[0 0 800 400]); hold on;
vt=1:0.01:20; Pvt = f_eng(vt);
plot(vt, Pvt,'LineWidth',2)
[~, tmp] = min(Pvt); plot(vt(tmp),min(Pvt),'or')
xlabel('Bird airspeed [m/s]'); ylabel('Mechanical power of the Bird [Watt=J/s]');
title(['Power Curve for an average bird: m=' num2str(m) 'kg, B=' num2str(B) 'm']);
% Find the time of the night
idt=find(gext.day_id(1:end-1)==i_day);
% Old version with a W.departure unknown... tmp = W.departure(:,:,idt);
tmp = Fout.entering(:,:,idt);
tmp(2:end-1,2:end-1,:) = tmp(2:end-1,2:end-1,:)+W.takingoff(:,:,idt);
y = randsample(numel(tmp(:)), Ts_day_departure_sim(i_day), true, tmp(:));
y_lat = nan(Ts_day_departure_sim(i_day), numel(idt)); y_lon=y_lat;
[y_lat(:,2), y_lon(:,2), y_t] = ind2sub(size(tmp),y);
En = zeros(Ts_day_departure_sim(i_day), 1);
% Find if bird lands until next step (no need to move them forward)
landing = F_land(y_lat(:, i_t), y_lon(:, i_t), repmat(idt(i_t-1),Ts_day_departure_sim(i_day),1))>rand(Ts_day_departure_sim(i_day),1);
v_lat = F_vlat(y_lat(id, i_t), y_lon(id, i_t), repmat(idt(i_t),sum(id),1)); % km/h
v_lon = F_vlon(y_lat(id, i_t), y_lon(id, i_t), repmat(idt(i_t),sum(id),1)); % km/h
Vt = sqrt( (v_lat-F_wlat(y_lat(id, i_t), y_lon(id, i_t), repmat(idt(i_t),sum(id),1))).^2 + (v_lon - F_wlon(y_lat(id, i_t), y_lon(id, i_t), repmat(idt(i_t),sum(id),1))).^2);
En(id) = En(id) + f_eng(Vt*1000/60/60)*60*15; % Vt is in km/h -> m/s for f_eng. Puis, J/s -> J [15min]
y_lat(id, i_t+1) = y_lat(id, i_t) + v_lat*dt/dy;
y_lon(id, i_t+1) = y_lon(id, i_t) + v_lon.*dt./interp1((1:g.nlat)',dx,y_lat(id, i_t),'linear','extrap');
% keep same position for that have not yet left
y_lat(~id, i_t+1) = y_lat(~id, i_t);
y_lon(~id, i_t+1) = y_lon(~id, i_t);
% assert(~any(isnan(y_lon(:, i_t+1))))
y_lat(isnan(y_lat(:, i_t+1)), i_t+1) = y_lat(isnan(y_lat(:, i_t+1)), i_t);
y_lon(isnan(y_lon(:, i_t+1)), i_t+1) = y_lon(isnan(y_lon(:, i_t+1)), i_t);
out = ~(F_out(y_lat(:, i_t+1), y_lon(:, i_t+1))==1);
% assert(~any(isnan(y_lon(:))))
% take only bird that have not left the system
flight_duration(i_day,:) = histcounts(sum(~(diff(y_lon(id2,:),1,2)==0),2)*dt, flight_duration_bins);
fd=nan(Ts_day_departure_sim(i_day),1);
for i_b=1:Ts_day_departure_sim(i_day)
lon = interp1(1:g.nlon,g.lon,unique(y_lon(i_b,:),'stable'))';
lat = interp1(1:g.nlat,g.lat,unique(y_lat(i_b,:),'stable'))';
fd(i_b) = sum(lldistkm([lat(2:end-1) lon(2:end-1)],[lat(3:end) lon(3:end)]));
flight_distance(i_day,:) = histcounts(fd(id2), flight_distance_bins);
energy(i_day,:) = histcounts(En(id2), energy_bins);
energykm(i_day,:) = histcounts(En(id2)./fd(id2), energykm_bins);
if (Ts_day_departure_sim(i_day)>0)
origin = sub2ind([gext.nlat gext.nlon],round(y_lat(:,2)),round(y_lon(:,2)));
dest = sub2ind([gext.nlat gext.nlon],round(y_lat(:,i_t+1)),round(y_lon(:,i_t+1)));
[C,~,ic] = unique([origin dest],'rows');
res{i_day} = [C splitapply(@sum,ones(numel(ic),1),ic)*r];
% h = worldmap([g.lat(1) g.lat(end)], [g.lon(1) g.lon(end)]);
% setm(h,'frame','on','grid','off'); set(findall(h,'Tag','MLabel'),'visible','off'); set(findall(h,'Tag','PLabel'),'visible','off')
% geoshow('landareas.shp', 'FaceColor', [215 215 215]./255); geoshow('worldrivers.shp','Color', 'blue')
% plotm(interp1(1:g.nlat,g.lat,y_lat(i_b,:)), interp1(1:g.nlon,g.lon,y_lon(i_b,:)),'-k')
% plotm(interp1(1:g.nlat,g.lat,y_lat(:,2)), interp1(1:g.nlon,g.lon,y_lon(:,2)),'^k','MarkerFaceColor',[0 0 0])
% plotm(interp1(1:g.nlat,g.lat,y_lat(~(y_t==999),end)), interp1(1:g.nlon,g.lon,y_lon(~(y_t==999),end)),'vk','MarkerFaceColor',[0 0 0])
% plotm(interp1(1:g.nlat,g.lat,y_lat(y_t==999,end)), interp1(1:g.nlon,g.lon,y_lon(y_t==999,end)),'<k','MarkerFaceColor',[1 0 0])
% filename='data/Density_estimationMap_M';
%filename='data/Density_estimationMap_M';
tmp = datasample(find(abs(y_lat(:,2)-y_lat(:,end))>2),7);
y_latt = interp1(1:gext.nlat,gext.lat,y_lat(tmp,3:ii:end));
y_lont = interp1(1:gext.nlon,gext.lon,y_lon(tmp,3:ii:end));
%col = get(gca,'colororder');
s=ones(numel(tmp),1); % 1: ground, 2: departure, 3: in air, 4: landing 5: landed
s(s==1 & y_latt(:,i_t)~=y_latt(:,i_t+1))=2;
s(s==3 & y_latt(:,i_t)==y_latt(:,i_t+1))=4;
subplot(3,numel(idtt),i_t)
h = worldmap([g.lat(1) g.lat(end)], [g.lon(1) g.lon(end)]);
setm(h,'frame','on','grid','off'); set(findall(h,'Tag','MLabel'),'visible','off'); set(findall(h,'Tag','PLabel'),'visible','off')
geoshow('landareas.shp', 'FaceColor', [77 77 77]./255);
set(gcf,'color','w'); colormap(gca,brewermap([],'Spectral')); caxis([-5000 5000]);
title(datestr(gext.time(idtt(i_t)),'HH:MM'),'FontSize',14);
tmp=W.takingoff(:,:,idtt(i_t)); tmp(tmp<0.001)=nan;
hsurf=surfm(g.lat2D,g.lon2D,tmp);
scatterm(y_latt(s==1,i_t),y_lont(s==1,i_t),[],col(s==1,:),'.')
scatterm(y_latt(s==2,i_t),y_lont(s==2,i_t),[],col(s==2,:),'filled')
subplot(3,numel(idtt),numel(idtt)+i_t)
h = worldmap([g.lat(1) g.lat(end)], [g.lon(1) g.lon(end)]);
setm(h,'frame','on','grid','off'); set(findall(h,'Tag','MLabel'),'visible','off'); set(findall(h,'Tag','PLabel'),'visible','off')
geoshow('landareas.shp', 'FaceColor', [77 77 77]./255);
gd_tmp = nan(g.nlat, g.nlon);
gd_tmp(g.latlonmask)=nanmean(gd.dens_est(:,g.time==gext.time(idtt(i_t))),2);
surfm(g.lat2D,g.lon2D,gd_tmp);
% plotm(data.lat,data.lon,'.k')
gu_tmp = nan(g.nlat, g.nlon); gv_tmp = nan(g.nlat, g.nlon);
gu_tmp(g.latlonmask)=nanmean(guv.u_est(:,g.time==gext.time(idtt(i_t))),2);
gv_tmp(g.latlonmask)=nanmean(guv.v_est(:,g.time==gext.time(idtt(i_t))),2);
quiverm(g.lat2D(1:5:end,1:5:end),g.lon2D(1:5:end,1:5:end),gu_tmp(1:5:end,1:5:end),gv_tmp(1:5:end,1:5:end),'k')
plotm(y_latt(i_s,1:i_t)',y_lont(i_s,1:i_t)','LineWidth',2,'Color',col(i_s,:))
scatterm(y_latt(s==3,i_t),y_lont(s==3,i_t),[],col(s==3,:),'filled')
subplot(3,numel(idtt),2*numel(idtt)+i_t)
h = worldmap([g.lat(1) g.lat(end)], [g.lon(1) g.lon(end)]);
setm(h,'frame','on','grid','off'); set(findall(h,'Tag','MLabel'),'visible','off'); set(findall(h,'Tag','PLabel'),'visible','off')
geoshow('landareas.shp', 'FaceColor', [77 77 77]./255);
set(gcf,'color','w'); colormap(gca,brewermap([],'Spectral')); caxis([-5000 5000]);
tmp=W.landing(:,:,idtt(i_t)); tmp(tmp>-10)=nan;
hsurf=surfm(g.lat2D,g.lon2D,tmp);
scatterm(y_latt(s==4,i_t),y_lont(s==4,i_t),[],col(s==4,:),'filled')
scatterm(y_latt(s==5,i_t),y_lont(s==5,i_t),[],col(s==5,:),'.')
% h = worldmap([g.lat(1) g.lat(end)], [g.lon(1) g.lon(end)]);
% setm(h,'frame','on','grid','off'); set(findall(h,'Tag','MLabel'),'visible','off'); set(findall(h,'Tag','PLabel'),'visible','off')
% geoshow('landareas.shp', 'FaceColor', [77 77 77]./255);
gflow.id = reshape(1:numel(gflow.lat2D),numel(gflow.lat),numel(gflow.lon));
gflow.match = repelem(gflow.id,rll,rll);
gflow.match = [gflow.match nan(size(gflow.match,1),1); nan(1,size(gflow.match,2)+1)];
origin2 = gflow.match(flows.origin);
dest2 = gflow.match(flows.dest);
[~,tmp1,tmp2] = unique([origin2 dest2 datenum(flows.time)],'rows');
flowsMin = flows(tmp1,:);
flowsMin.origin = origin2(tmp1);
flowsMin.dest = dest2(tmp1);
flowsMin.count = accumarray(tmp2,flows.count);
flowsMin(isnan(flowsMin.origin)|isnan(flowsMin.dest),:)=[];
flowsMin(flowsMin.count<5000,:)=[];
flowsMin(flowsMin.origin==flowsMin.dest,:)=[];
locations = table((1:numel(gflow.lat2D))',string([num2str(gflow.lat2D(:),'%2.2f') repmat(', ',numel(gflow.lat2D),1) num2str(gflow.lon2D(:),'%2.2f')]), gflow.lat2D(:), gflow.lon2D(:),'VariableNames',{'id','name','lat','lon'});
tmp = uint64(sort(unique([flowsMin.origin;flowsMin.dest])));
locationsMin = locations(tmp,:);