plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
gridIndx2.m
|
.m
|
BEHR-core-utils-master/AMF_tools/gridIndx2.m
| 949 |
utf_8
|
5829fca79601db18102ad655de285131
|
%%gridIndx2
%%arr 10/22/2008
%..........................................................................
%
% Description:
% Given a defined grid, the procedure finds the grid indices
% corresponding to input values of latitude, and/or longitude, and/or
% date.
%
% Arguments:
%
% x scalar or vector of values at which grid cell indices are to be evaluated
% xSAVE vector of grid cell values
% nGridCells number of grid cells (require nGridCells not equal to zero)
%
%
% Purpose:
% To find indices of grid cells at a given set of values in vector x.
%
%
% This file replaces Eric's gridIndx which I was having trouble translating
% from IDL.
%..........................................................................
function [gridIndex] = gridIndx2(x, xSAVE, nGridCells)
diff=abs(x-xSAVE);
a=find(diff==min(diff));
cells=1:nGridCells;
b=cells(a);
gridIndex=b;
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
omiAmfAK2.m
|
.m
|
BEHR-core-utils-master/AMF_tools/omiAmfAK2.m
| 15,201 |
utf_8
|
0b4ea30e665b2277679e15eed0c303a6
|
%OMIAMFAK2 - Compute OMI AMFs and AKs given scattering weights and NO2 profiles
%
% [ amf, amfVis, amfCld, amfClr, sc_weights, avgKernel, no2ProfileInterp,
% swPlev ] = omiAmfAK2( pTerr, pCld, cldFrac, cldRadFrac, pressure,
% dAmfClr, dAmfCld, temperature, no2Profile )
%
% INPUTS:
% pTerr - the 2D array of pixel surface pressures
% pCld - the 2D array of pixel cloud pressures
% pTropo - the 2D array of tropopause pressures
% cldFrac - the 2D array of pixel geometric cloud fractions (field: CloudFraction)
% cldRadFrac - the 2D array of pixel radiance cloud fractions (field: CloudRadianceFraction)
% pressure - the vector of standard pressures to expect the scattering weights and profiles at
% dAmfClr - the 3D array of scattering weight a.k.a. box-AMFs for clear sky conditions for each pixel.
% The vertical coordinate should be along the first dimension, the second and third dimensions
% should be the same as the two dimensions of 2D arrays
% dAmfCld - the array of scattering weights for cloudy conditions. Same shape as dAmfClr.
% temperature - the 3D array of temperature profiles for each pixel. Same shape as dAmfClr.
% no2Profile - the 3D array of NO2 profiles for each pixel. Same shape as dAmfClr.
%
% For all 3D inputs, the vertical levels must be at the pressures specified by "pressure".
%
% OUTPUTS:
% amf - the 2D array of AMFs for each pixel that will yield estiamted total columns (including
% ghost column below clouds).
% amfVis - the 2D array of AMFs for each pixel that will yield only visible columns (so EXCLUDING
% ghost column below clouds)
% amfCld - the 2D array of cloudy AMFs that are used for the total column AMF.
% amfClr - the 2D array of clear sky AMFs, used for both AMFs.
% sc_weights - the 3D array of combined scattering weights for the total column AMFs. These include
% weights interpolated to the surface and cloud pressures.
% avgKernel - the 3D array of averaging kerneles for the total column AMFs. These include kernels
% interpolated to the surface and cloud pressure.
% no2ProfileInterp - the NO2 profiles used for each pixel, interpolated to the surface and cloud
% pressures as well.
% swPlev - the 3D array of pressures as vertical coordinates for each pixel. Contains the standard
% pressures from the input "pressure" plus surface and cloud pressures, if different from all the
% standard pressures.
%
% Legacy comment block from Eric Bucsela (some inputs have been removed)
%..........................................................................
% Given a set of profiles, cloud and terrain parameters, computes AMF
% and averging kernel profile. Also integrates to get vertical column densities.
% This is a combination of old codes omiAvgK.pro and calcAMF.pro (w/out uncert calcs)
% EJB (2008-05-30)
%
% Inputs:
% pTerr = pressure of terrain (hPa)
% pCld = pressure of cloud top (hPa)
% cldFrac = geometrical cloud fraction (0.0 to 1.0)
% cldRadFrac = cloud radiance fraction (0.0 to 1.0)
% pressure = pressure vector from highest to lowest pressure (hPa)
% dAmfClr = dAMF profile vector for clear skies
% dAmfCld = dAMF profile vector for overcast skies
% no2Profile= NO2 mixing ratio profile vector for AMF calculation (cm-3)
% no2Profile2= NO2 mixing ratio profile vector for integration (cm-3)
% temperature= temperature profile vector (K)
%
% Outputs:
% amf = air mass factor
% amfCld = component of amf over cloudy part of scene (if any)
% amfClr = component of amf over clear part of scene (if any)
%
% Set keyword ak to compute these additional outputs:
% avgKernel = averaging kernel vector
% vcd = directly integrated NO2 profile (cm-2)
% vcdAvgKernel = integrated product of NO2 profile and avg kernel (cm-2)
%
% Set keyword noghost for amf based on visible column only (otherwise, assume column to ground)
%
% omiAmfAK, pTerr, pCld, cldFrac, cldRadFrac, noGhost=noGhost, ak=ak, $ ;;scalar inputs
% pressure, dAMFclr, dAMFcld, temperature, no2Profile, no2Profile2, $ ;;vector inputs
% amf, amfCld, amfClr, avgKernel, vcd, vcdAvgKernel ;;outputs%
%
%..........................................................................
%
% JLL 13 May 2015: added output for scattering weights and averaging
% kernel, both as the weighted average of clear and cloudy conditions.
% The averaging kernel uses the preexisting code (just uncommented), the
% scattering weights I added myself.
%
% Josh Laughner <[email protected]>
function [amf, amfVis, amfCld, amfClr, sc_weights_clr, sc_weights_cld, avgKernel, no2ProfileInterp, swPlev ] = omiAmfAK2(pTerr, pTropo, pCld, cldFrac, cldRadFrac, pressure, dAmfClr, dAmfCld, temperature, no2Profile)
% Each profile is expected to be a column in the no2Profile matrix. Check
% for this by ensuring that the first dimension of both profile matrices
% has the same length as the pressure vector
E = JLLErrors;
if size(no2Profile,1) ~= length(pressure)
error(E.callError('profile_input','Profiles must be column vectors in the input matrices. Ensure size(no2Profile,1) == length(pressure)'));
end
if size(dAmfClr,1) ~= length(pressure) || size(dAmfCld,1) ~= length(pressure);
error(E.callError('dAmf_input','dAMFs must be column vectors in the input matrices. Ensure size(dAmfxxx,1) == length(pressure)'));
end
if size(temperature,1) ~= length(pressure)
error(E.callError('temperature_input','temperature must be a column vector. Ensure size(temperature,1) == length(pressure)'));
end
alpha = 1 - 0.003 * (temperature - 220); % temperature correction factor vector
% Keep NaNs in alpha, that way the scattering weights will be fill values
% for levels where we don't have temperature data.
alpha_i=max(alpha,0.1,'includenan');
alpha = min(alpha_i,10,'includenan');
% Integrate to get clear and cloudy AMFs
vcdGnd=nan(size(pTerr));
vcdCld=nan(size(pTerr));
amfClr=nan(size(pTerr));
amfCld=nan(size(pTerr));
% JLL 18 May 2015:
% Added preinitialization of these matrices, also nP will be needed to pad
% output vectors from integPr2 to allow concatenation of scattering weights
% vectors into a matrix (integPr2 will return a shorter vector if one or
% both of the pressures to interpolate to is already in the pressure
% vector). We add two to the first dimension of these matrices to make room
% for the three interpolated pressures.
padvec = zeros(1,ndims(no2Profile));
padvec(1) = 3;
swPlev=nan(size(no2Profile)+padvec);
swClr=nan(size(no2Profile)+padvec);
swCld=nan(size(no2Profile)+padvec);
no2ProfileInterp=nan(size(no2Profile)+padvec);
nP = size(swPlev,1);
for i=1:numel(pTerr)
no2Profile_i = no2Profile(:,i);
clearSW_i = no2Profile(:,i) .* dAmfClr(:,i) .* alpha(:,i);
cloudySW_i = (no2Profile(:,i) .* dAmfCld(:,i) .* alpha(:,i));
if all(isnan(no2Profile_i)) || all(isnan(clearSW_i)) || all(isnan(cloudySW_i))
% 16 Apr 2018: found that AMFs were still being calculated if all
% of one type of scattering weight was NaNs, but not the other.
% This happens when, e.g., the MODIS albedo is a NaN so the clear
% sky scattering weights are all NaNs but the cloudy ones are not.
% That leads to a weird case where a pixel that is not necessarily
% 100% cloudy is being calculated with a 0 for the clear sky AMF.
% This is undesired behavior, we would rather just not retrieve
% pixels for which we do not have surface data.
continue
end
vcdGnd(i) = integPr2(no2Profile(:,i), pressure, pTerr(i), pTropo(i), 'fatal_if_nans', true);
if cldFrac(i) ~= 0 && cldRadFrac(i) ~= 0 && pCld(i)>pTropo(i)
vcdCld(i) = integPr2(no2Profile(:,i), pressure, pCld(i), pTropo(i), 'fatal_if_nans', true);
else
vcdCld(i)=0;
end
if cldFrac(i) ~= 1 && cldRadFrac(i) ~= 1
amfClr(i) = integPr2(clearSW_i, pressure, pTerr(i), pTropo(i), 'fatal_if_nans', true) ./ vcdGnd(i);
else
amfClr(i)=0;
end
if cldFrac(i) ~= 0 && cldRadFrac(i) ~= 0 && pCld(i)>pTropo(i)
cldSCD=integPr2(cloudySW_i, pressure, pCld(i), pTropo(i), 'fatal_if_nans', true);
amfCld(i) = cldSCD ./ vcdGnd(i);
else
amfCld(i)=0;
end
% JLL 19 May 2015:
% Added these lines to interpolate to the terrain & cloud pressures and
% output a vector - this resulted in better agreement between our AMF and
% the AMF calculated from "published" scattering weights when we
% published unified scattering weights, so this probably still helps
% with the averaging kernels
[~, ~, this_no2ProfileInterp] = integPr2(no2Profile(:,i), pressure, pTerr(i), pTropo(i), 'interp_pres', [pTerr(i), pCld(i),pTropo(i)], 'fatal_if_nans', true);
[~,this_swPlev,this_swClr] = integPr2((dAmfClr(:,i).*alpha(:,i)), pressure, pTerr(i), pTropo(i), 'interp_pres', [pTerr(i), pCld(i),pTropo(i)], 'fatal_if_nans', true);
[~,~,this_swCld] = integPr2((dAmfCld(:,i).*alpha(:,i)), pressure, pCld(i), pTropo(i), 'interp_pres', [pTerr(i), pCld(i),pTropo(i)], 'fatal_if_nans', true);
if ~iscolumn(this_swPlev)
E.badvar('this_swPlev','Must be a column vector');
elseif ~iscolumn(this_swClr)
E.badvar('this_swClr', 'Must be a column vector');
elseif ~iscolumn(this_swCld)
E.badvar('this_swCld', 'Must be a column vector');
elseif ~iscolumn(this_no2ProfileInterp)
E.badvar('this_no2ProfileInterp', 'Must be a column vector');
end
% Pad with NaNs if there are fewer than nP (number of pressures in the
% input pressure vector + 2 for the interpolated pressures) values.
% integPr2 outputs vectors with nP values, unless one of the interpolated
% pressures is already in the input pressure vector.
this_swPlev = padarray(this_swPlev, nP - length(this_swPlev), nan, 'post');
this_swClr = padarray(this_swClr, nP - length(this_swClr), nan, 'post');
this_swCld = padarray(this_swCld, nP - length(this_swCld), nan, 'post');
this_no2ProfileInterp = padarray(this_no2ProfileInterp, nP - length(this_no2ProfileInterp), nan, 'post');
swPlev(:,i) = this_swPlev;
swClr(:,i) = this_swClr;
swCld(:,i) = this_swCld;
no2ProfileInterp(:,i) = this_no2ProfileInterp;
end
% Combine clear and cloudy parts of AMFs to calculate an AMF that corrects
% multiplicatively for the ghost column. It does so by including the ghost
% column in the VCD in the denominator of the AMF, which makes the AMF the
% ratio of the modeled (visible) SCD to the TOTAL VCD.
%
% We also calculate an AMF that will produce a visible-only VCD by
% effectively replacing the denominator with the modeled visible only VCD.
amf = cldRadFrac .* amfCld + (1-cldRadFrac).*amfClr;
amf(~isnan(amf)) = max(amf(~isnan(amf)), behr_min_amf_val()); % clamp at min value (2008-06-20), but don't replace NaNs with the min value (2016-05-12)
amfVis = amf .* vcdGnd ./ (vcdCld .* cldFrac + vcdGnd .* (1 - cldFrac));
amfVis(~isnan(amfVis)) = max(amfVis(~isnan(amfVis)), behr_min_amf_val());
% There is an alternate way of calculating a visible-only AMF: calculate a
% cloudy visible-only AMF by dividing the cloud modeled SCD by an
% above-cloud only modeled VCD instead of the to-ground VCD. Then weight
% these together by the cloud radiance fraction:
%
% A_vis = (1-f) * A_clr + f * A_cld_vis
% = (1-f) * S_clr / V_clr + f * S_cld / V_cld_vis
%
% Talking with Jim Gleason, he saw no reason that either representation
% would be invalid, and BEHR v2.1C used this alternate formulation.
%
% However, later I heard back from Eric Bucsela about this, and he pointed
% out that the physical interpretation of this alternate method is less
% clear. He generally thinks of AMFs as "what you should see divided by
% what you should want", so that when you divide what you actually see by
% the AMF, you get what you want. Since we see the SCD and want the VCD, we
% really want our visible AMF to be:
%
% A_vis = SCD / VCD_vis
% = [(1-f) * S_clr + f * S_cld] / [(1-f) * V_clr + f * V_cld_vis]
%
% which is subtly different because now everything is one fraction.
% Algebraically, this form is equivalent to multiplying the total-column
% AMF by the ratio of the visible and total VCDs. This also seems to
% produce better agreement if you try to reproduce the AMF with the
% scattering weights.
%
% Eric also pointed out that the visible VCD should be a sum of clear and
% cloudy VCDs weighted by the geometric cloud fraction, not the radiance
% cloud fraction, b/c in that part we don't want to give more weight to the
% brighter cloudy part of the pixel.
%
% -- J. Laughner, 19 Jul 2017
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now compute averaging kernel %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargout > 4
% This is only done for the total column, on the assumption that most
% modelers would want to compare total column against their modeled
% column.
% These 2 sets of lines are an approximation of what is done in the OMI
% NO2 algorithm
avgKernel = nan(size(swPlev));
sc_weights = nan(size(swPlev));
sc_weights_clr = swClr;
sc_weights_cld = swCld;
for i=1:numel(pTerr)
% JLL 19 May 2015 - pull out the i'th vector, this will allow us
% to remove nans for AMF calculations where needed, and also
% check that all vectors have NaNs in the same place.
swPlev_i = swPlev(:,i);
swClr_i = swClr(:,i);
swCld_i = swCld(:,i);
not_nans_i = ~isnan(swClr_i) & ~isnan(swCld_i);
if ~all(not_nans_i == (~isnan(swClr_i) | ~isnan(swCld_i)))
% Error called if there are NaNs present in one but not both of
% these vectors. Previously had checked if the NaNs matched
% those in the pressure levels, but once I fixed it so that
% alpha retained NaNs that were in temperature, that was no
% longer useful, since pressure will never have NaNs unless
% they were appended to ensure equal length vectors when
% surface, cloud, or tropopause pressure are one of the
% standard pressures, but the scattering weights will have NaNs
% where the WRF temperature profile doesn't reach.
E.callError('nan_mismatch','NaNs are not the same in the swPlev, swClr, and swCld vectors');
end
ii = swPlev_i > pTerr(i) & ~isnan(swPlev_i);
sc_weights_clr(ii,i) = 1e-30;
swClr_i(ii)=1e-30;
ii = swPlev_i > pCld(i) & ~isnan(swPlev_i);
swCld_i(ii)=1e-30;
sc_weights_cld(ii,i) = 1e-30;
% 17 Nov 2017 - switched to outputting separate clear and cloudy
% scattering weights
sc_weights(:,i) = (cldRadFrac(i).*swCld_i + (1-cldRadFrac(i)).*swClr_i);
avgKernel(:,i) = sc_weights(:,i) ./ amf(i); % JLL 19 May 2015 - changed to use the scattering weights we're already calculating.
end
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
integPr2.m
|
.m
|
BEHR-core-utils-master/AMF_tools/integPr2.m
| 7,989 |
utf_8
|
da0cf11ddd46f634b372d935cfac8ea0
|
% INTEGPR2 Integrate mixing ratios over pressure
%
% VCD = INTEGPR2(MIXINGRATIO, PRESSURE, PRESSURESURFACE) Integrates the
% profile given by MIXINGRATIO (which must be unscaled, i.e. mol/mol or
% volume/volume) defined at the vertical levels given by PRESSURE (which
% must be monotonically decreasing and given in hPa). PRESSURESURFACE is
% the lower level of integration, must be a scalar also given in hPa. The
% upper limit is taken as the minimum value in PRESSURE.
%
% VCD = INTEGPR2( ___, PRESSURETROPOPAUSE) will integrate up to
% PRESSURETROPOPAUSE instead of the minimum value in PRESSURE.
%
% [ VCD, P_OUT, F_OUT ] = INTEGPR2( ___, 'interp_pres', INTERP_PRES )
% Allows you to specify one or more pressures as the vector INTERP_PRES
% that the mixing ratio vector will be interpolated to. P_OUT will be
% PRESSURES with the INTERP_PRES inserted and F_OUT will be the vector of
% mixing ratios with extra entries corresponding to the INTERP_PRES
% pressures. Note that the size of P_OUT and F_OUT are not guaranteed to
% be numel(pressures) + numel(interp_pres); if any of the INTERP_PRES
% pressures are already present in PRESSURES, then no extra level will be
% added for that INTERP_PRES value.
%
% [ ___ ] = INTEGPR2( ___, 'fatal_if_nans', true ) will cause INTEGPR2 to
% throw an error if any of the mixing ratio values between the lower and
% upper integration limits are NaNs. This allows you to ensure that your
% profile is fully defined over all relevant pressures. If this parameter
% is not given, a warning will still be issued if NaNs are detected.
% Legacy comment block from Ashley Russell:
%..........................................................................
% Integrates vector of mixing ratios (cm-3) above pressureSurface as function of pressure (hPa)
% to get vertical column densities (cm-2). Computes piecewise in layers between two pressures.
% Assumes exponential variation between mixing ratios that are positive or zero (zero is treated as 1.e-30).
% If one or both mixing ratios is negative, assumes constant (average=(f1+f2)/2) mixing ratio in the layer.
% The uncertainties are computed assuming constant mixing ratio in each layer (using exponential
% variation can lead to strange (large) results when f1*p1 is approx f2*p2. This sometimes happens
% when using averaging kernels).
%
% Arguments (vector indices are i = 0,1,2,...n-1):
%
% mixingRatio(i) = input volume mixing ratios (no units)
% pressure(i) = vector of input pressures from largest to smallest (hPa)
% pressureSurface = surface pressure (where integration starts) (hPa)
% interpPres = pressures to interpolate the output profile to (hPa) ( added by JLL for BEHR scattering weights )
%
% Restrictions:
% Pressures must be greater than zero and monotonically decreasing
%
% Equation for exponential variation:
% For a segment of the vertical column between ambient pressures p1 and p2,
% at which the trace gas volume mixing ratios are f1 and f2, the vertical
% column density VCD (assuming number density varies exponentially with p) is
%
% VCD = (f1 * p1 - f2 * p2) / [(b + 1) * m * g]
%
% where: b = ALOG( f2/f1 ) / ALOG( p2/p1 )
%
% Also, for interpolation of f between p1 and p2:
%
% f = f1 * (p/p1)^b
%
% Note: Can get large uncertainties when f1*p1 = f2*p2
%
%..........................................................................
function [vcd, p_out, f_out] = integPr2(mixingRatio, pressure, pressureSurface, varargin)
E = JLLErrors;
p = inputParser;
p.addOptional('pressureTropopause', [], @(x) isscalar(x) && isnumeric(x) && (isnan(x) || x > 0));
p.addParameter('interp_pres', []);
p.addParameter('fatal_if_nans', false);
p.parse(varargin{:});
pout = p.Results;
pressureTropopause = pout.pressureTropopause;
interpPres = pout.interp_pres;
fatal_if_nans = pout.fatal_if_nans;
if any(pressure<0)
E.badinput('PRESSURE must be all >= 0')
elseif any(diff(pressure)>0)
E.badinput('PRESSURE must be monotonically decreasing')
end
if ~isscalar(pressureSurface)
E.badinput('PRESSURESURFACE must be a scalar')
end
if isempty(pressureTropopause)
pressureTropopause = min(pressure);
end
if isempty(interpPres)
if nargout > 1
E.callError('nargout','Without any interpPres values, p_out and f_out will not be set');
end
else
% Make sure the interpolation pressure is within the pressure vector
% given.
interpPres = clipmat(interpPres, min(pressure), max(pressure));
end
% mean molecular mass (kg) * g (m/s2) * (Pa/hPa) * (m2/cm2)
mg = (28.97/6.02E23)*1E-3 * 9.8 * 1E-2 * 1E4;
fmin = 1E-30;
vcd = 0;
f = mixingRatio;
p = pressure;
p0 = max(pressureSurface, min(pressure));
n = numel(p);
dvcd = 0;
deltaVcd = zeros(numel(f),1); % Changed to make these vectors on 9/26/2014 JLL
df = zeros(numel(f),1);
numIP = numel(interpPres);
if numIP > 0
if ~iscolumn(p)
p_out = p';
else
p_out = p;
end
f_out = f;
for a=1:numIP
if all(p~=interpPres(a))
f_i = interpolate_surface_pressure(p,f,interpPres(a));
bottom = p_out > interpPres(a);
top = p_out < interpPres(a);
p_out = [p_out(bottom); interpPres(a); p_out(top)];
f_out = [f_out(bottom); f_i; f_out(top)];
end
end
end
% If the surface pressure is above the tropopause pressure, i.e. the lower
% integration limit is above the upper integration limit, return 0 b/c
% unlike abstract integration where reversing the integration limits
% reverses the sign, here, physically, if the surface pressure is above the
% top limit, then there is no column between the surface and the top limit.
% With this added here, we might want to remove the "pCld > pTropo" tests
% in omiAmfAK2.
if pressureSurface <= pressureTropopause
vcd = 0;
return
end
f0 = interpolate_surface_pressure(p,f,p0);
p(i0) = p0;
f(i0) = f0;
i_initial = i0;
if ~isnan(pressureTropopause)
p_end = max(pressureTropopause, min(pressure));
f_end = interpolate_surface_pressure(p,f,p_end);
p(i0+1) = p_end;
f(i0+1) = f_end;
i_end = i0;
else
i_end = n-1;
end
% Integrate................................................................
if isnan(pressureSurface)
vcd = nan;
return
end
for i = 1:n-1
deltaVcd(i) = (f(i) + f(i + 1)) .* (p(i) - p(i + 1)) ./ (2 * mg); %assume const mixing ratio in each layer
b = (log(max(f(i + 1),fmin)) - log(max(f(i),fmin))) ./ (log(p(i + 1)) - log(p(i)));
if f(i) >= 0 && f(i + 1)>=0 && abs(b + 1) >= 0.01;
deltaVcd(i) = (f(i)*p(i) - f(i + 1)*p(i + 1)) ./ (b + 1) ./ mg; %assume exponential variation in each layer
end
end
if any(isnan(deltaVcd(i_initial:i_end)))
if fatal_if_nans
E.callError('nans_in_column', 'NaNs detected in partial columns.')
else
warning('integPr2:nans_in_column', 'NaNs detected in partial columns. They will not be added into the total column density.')
end
end
vcd = nansum2(deltaVcd(i_initial:i_end));
function [f0] = interpolate_surface_pressure(p_in,f_in,p0_in)
pp=find(p_in>=p0_in); if isempty(pp); pp=0; end
i0 = min(max((max(pp)),1),(n - 1));
f0 = interp1(log([p_in(i0),p_in(i0 + 1)]), [f_in(i0),f_in(i0 + 1)], log(p0_in),'linear','extrap'); %assume linear variation in surface layer
b = (log(max(f_in(i0 + 1),fmin)) - log(max(f_in(i0),fmin))) ./ (log(p_in(i0 + 1)) - log(p_in(i0)));
if f_in(i0) >= 0 && f_in(i0 + 1) >= 0 && abs(b + 1) >= 0.01;
f0 = f_in(i0) * ((p0_in./p_in(i0))^b); %assume exponential variation in surface layer
end
end
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
rProfile_US.m
|
.m
|
BEHR-core-utils-master/AMF_tools/rProfile_US.m
| 2,349 |
utf_8
|
fdbb2f144688bf6869789f9a2ff51a10
|
%%rProfile_US
%%arr 04/22/2011
%Reads monthly WRF profiles from Lukas (for new retrieval, trends)
%NO2 is in ppm
function [no2_bins] = rProfile_US(PROFILE, loncorns, latcorns, c)
pressure = PROFILE.Pressure;
lat_prs = PROFILE.Latitude;
lon_prs = PROFILE.Longitude;
sz = size(PROFILE.NO2_profile);
%no2=reshape(PROFILE.NO2_profile,length(pressure),194300);
no2=reshape(PROFILE.NO2_profile,length(pressure),sz(2)*sz(3)); % reshape to a 2D matrix
no2_bins=zeros(length(pressure),c);
for j=1:c;
x = [];
x1 = loncorns(1,j); y1 = latcorns(1,j);
x2 = loncorns(2,j); y2 = latcorns(2,j);
x3 = loncorns(3,j); y3 = latcorns(3,j);
x4 = loncorns(4,j); y4 = latcorns(4,j);
xall=[x1;x2;x3;x4;x1];
yall=[y1;y2;y3;y4;y1];
xx = inpolygon(lat_prs,lon_prs,yall,xall);
no2_bin=no2(:,xx);
no2_bins(:,j)=mean(no2_bin,2);
end
%for pres_i=1:length(pressure)
% no2_bins(:,pres_i)=(interp2(lon_prs, lat_prs, squeeze(PROFILE.NO2new(pres_i,:,:)), lon, lat,'linear'));
%end
%{
old version of this file
function [no2_bins] = rProfile(loncorns, latcorns, c)
if exist('PROFILE','var')==0
load PROFILEalt
end
pressure = [1020 1015 1010 1005 1000 990 980 970 960 945 925 900 875 850 825 800 770 740 700 660 610 560 500 450 400 350 280 200 100 50 20 5];
lat_prs = 30.025:0.05:49.975; lat_prs=lat_prs'; lat_prs=repmat(lat_prs,1,480); nlat=numel(lat_prs);
lon_prs = -123.975:0.05:-100.025; lon_prs=repmat(lon_prs,400,1); nlon=numel(lon_prs);
for j=1:c;
%if mod(j,50)==0
% disp([num2str(j),' lines read so far out of ', num2str(c)])
%end
x = [];
x1 = loncorns(1,j); y1 = latcorns(1,j);
x2 = loncorns(2,j); y2 = latcorns(2,j);
x3 = loncorns(3,j); y3 = latcorns(3,j);
x4 = loncorns(4,j); y4 = latcorns(4,j);
m1 = (y2-y1)/(x2-x1); m2 = (y3-y2)/(x3-x2);
m3 = (y4-y3)/(x4-x3); m4 = (y1-y4)/(x1-x4);
lat1 = (m1*(lon_prs-x1)+y1); lat2 = (m2*(lon_prs-x2)+y2);
lat3 = (m3*(lon_prs-x3)+y3); lat4 = (m4*(lon_prs-x4)+y4);
xx = find(lat_prs>lat1 & lat_prs<lat2 & lat_prs<lat3 & lat_prs>lat4);
no2=PROFILE.NO2new(:,:);
no2_bin=no2(:,xx);
no2_bins(:,j)=mean(no2_bin,2);
end
%}
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
rDamf2.m
|
.m
|
BEHR-core-utils-master/AMF_tools/rDamf2.m
| 3,684 |
utf_8
|
692dc78d4bd9352518525b3eecf3f1b5
|
%%rDamf
%%arr 07/23/2008
% Reads the dAMF file used in the FORTRAN OMI NO2 algorithm
%..........................................................................
% Returns vector of dAMFs on input pressure grid, interpolated
% at input solar zenith angle, viewing zenith angle, relative azimuth angle
% surface albedo (cloud or terrain) and surface pressure (cloud or terrain)
%
% Inputs:
% fileDamf = complete directory/filename of input file
% pressure = vector of pressures (hPa) monotonically decreasing
% sza, vza, phi, (all in deg), albedo, surfPres (hPa) are scalars
%
% Outputs (optional: Return these to avoid having to re-read fileDamf on each call):
% presSave = pressure grid (vector) from fileDamf
% szaSave = solar zenith angle vector from fileDamf
% vzaSave = viewing zenith angle vector from fileDamf
% phiSave = relative azimuth angle vector from fileDamf
% albedoSave = albedo vector from fileDamf
% surfPresSave = surface pressure vector from fileDamf
% dAmfSave = large array of dAMF values from fileDamf
%..........................................................................
%function [presSave, szaSave, vzaSave, phiSave, albedoSave, surfPresSave, dAmfSave, dAmf] = rDamf2(fileDamf, pressure, sza, vza, phi, albedo, surfPres)
function dAmf = rDamf2(fileDamf, pressure, sza, vza, phi, albedo, surfPres)
E=JLLErrors;
if any(diff(pressure) > 0);
E.badinput('pressure must be a monotonically decreasing vector of pressures');
end
mat_test = [ismatrix(sza), ismatrix(vza), ismatrix(phi), ismatrix(albedo), ismatrix(surfPres)];
mat_error = {'SZA', 'VZA', 'PHI', 'ALBEDO', 'SURFPRES'};
if any(~mat_test)
E.badinput('The inputs %s must be 2D (matrices or vectors). The following are not: %s', strjoin(mat_error, ', '), strjoin(mat_error(~mat_test), ', '));
end
sz = size(sza);
size_test = [isequal(sz, size(vza)), isequal(sz, size(phi)), isequal(sz, size(albedo)), isequal(sz, size(albedo))];
if any(~size_test)
E.badinput('The inputs %s must be all the same size. The following are not the same size as SZA: %s', strjoin(mat_error, ', '), strjoin(mat_error(find(~size_test)+1), ', '));
end
if exist('dAmfSave','var')==0;
fid = fopen(fileDamf,'r');
header = fgets(fid);
n = fscanf(fid,'%g',[1 6]);
nPresSave = n(1); nSzaSave = n(2); nVzaSave = n(3); nPhiSave = n(4); nAlbedoSave = n(5); nSurfPresSave = n(6);
presSave = fscanf(fid, '%g', [nPresSave 1]);
szaSave = fscanf(fid, '%g', [nSzaSave 1]);
vzaSave = fscanf(fid, '%g', [nVzaSave 1]);
phiSave = fscanf(fid, '%g', [nPhiSave 1]);
albedoSave = fscanf(fid, '%g', [nAlbedoSave 1]);
surfPresSave = fscanf(fid, '%g', [nSurfPresSave 1]);
temperatureCoef = fscanf(fid, '%g', [1 1]);
[dAmfSave_vec,count] = fscanf(fid, '%g %g', inf);
dAmfSave = reshape(dAmfSave_vec, [nPresSave nSzaSave nVzaSave nPhiSave nAlbedoSave nSurfPresSave]);
end
% Now interpolate onto the input values
nPresSave = numel(presSave); nSzaSave = numel(szaSave); nVzaSave = numel(vzaSave);
nPhiSave = numel(phiSave); nAlbedoSave = numel(albedoSave); nSurfPresSave = numel(surfPresSave);
dAmf1 = zeros(size(phi,1),size(phi,2),nPresSave);
for i=1:nPresSave;
dum = reshape(dAmfSave(i,:,:,:,:,:), [nSzaSave, nVzaSave,nPhiSave, nAlbedoSave, nSurfPresSave]);
dAmf1(:,:,i) = interpn(szaSave, vzaSave, phiSave, albedoSave, surfPresSave, dum, sza, vza, phi, albedo, surfPres,'linear');
end
dAmfx=shiftdim(dAmf1,2);
dAmf = exp(interp1(log(presSave), log(dAmfx), log(pressure),'linear','extrap'));
status = fclose(fid);
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
behr_montecarlo_uncertainty.m
|
.m
|
BEHR-core-utils-master/AMF_tools/behr_montecarlo_uncertainty.m
| 2,630 |
utf_8
|
55e4df50366d705d87c0ef52ed7926e8
|
function [ amf_var, amf_relvar, param_vals ] = behr_montecarlo_uncertainty( AMFS, uncert_param, uncert_range )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
E = JLLErrors;
params = {'SZAs', 'VZAs', 'RAAs', 'ALBs', 'SurfPs'};
n_params = numel(params);
if ~ismember(uncert_param, params)
E.badinput('UNCERT_PARAM must be one of: %s', strjoin(uncert_param, ', '));
end
n_points = 10000;
% Get the range of values for each parameter and set up the random points
% within those ranges to sample. At the same time, extract the relevant
% vectors for the gridded interpolation, flipping them around to be
% strictly increasing if necessary.
param_ranges = nan(n_params, 2);
param_vals = nan(n_params, n_points);
param_vecs = cell(n_params, 1);
amfs = AMFS.AMFs;
for p=1:n_params
if ndims(AMFS.(params{p})) ~= n_params
E.badinput('AMFS.%s does not have the same number of dimensions as there are parameters', params{p});
end
this_range = [min(AMFS.(params{p})(:)), max(AMFS.(params{p})(:))];
param_ranges(p,:) = this_range;
param_vals(p, :) = randrange(this_range(1), this_range(2), 1, n_points);
pvec = perm_vec(p, n_params);
tmp = permute(AMFS.(params{p}), pvec);
tmp_vec = tmp(:,1);
if all(diff(tmp_vec) < 0)
tmp_vec = flipud(tmp_vec);
amfs = flip(amfs, p);
elseif ~all(diff(tmp_vec) > 0)
E.badinput('Dimension %d of AMFS.%s is not strictly increasing or decreasing', p, params{p});
end
param_vecs{p} = tmp_vec;
end
AInterp = griddedInterpolant(param_vecs, amfs);
i_uncert = strcmp(uncert_param, params);
amf_var = nan(1, n_points);
for a=1:n_points
% For each sample point, vary the uncertain parameter by +/- the
% uncertainty range and calculate the AMF value at the original point
% and the +/- values
test_vals = repmat(param_vals(:,p),1,3);
test_vals(i_uncert, 2) = test_vals(i_uncert, 2) - uncert_range;
test_vals(i_uncert, 3) = test_vals(i_uncert, 3) + uncert_range;
test_vals(i_uncert, :) = clipmat(test_vals(i_uncert,:), param_ranges(i_uncert,:));
test_vals = num2cell(test_vals);
test_amfs = nan(1,3);
for b=1:3
test_amfs(b) = AInterp(test_vals(:,b));
end
amf_var(a) = (abs(test_amfs(2) - test_amfs(1)) + abs(test_amfs(3) - test_amfs(1)))/2;
amf_relvar(a) = amf_var(a) / test_amfs(1);
end
end
function pvec = perm_vec(dim, n)
% Create a vector that, when used with PERMUTE() will permute an N
% dimensional array to have DIM along the first dimension.
pvec = 1:n;
pvec(pvec == dim) = [];
pvec = [dim, pvec];
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
merge_hong_kong_output.m
|
.m
|
BEHR-core-utils-master/AMF_tools/Hong Kong Profile Tools/merge_hong_kong_output.m
| 15,885 |
utf_8
|
899d599cd0838abdebe2f6b460b70d23
|
function [ ] = merge_hong_kong_output( root_dir, start_date, end_date, varargin )
%MERGE_HONG_KONG_OUTPUT Merges CMAQ and WRF data into standard wrfout files
% MERGE_HONG_KONG_OUTPUT( ROOT_DIR, START_DATE, END_DATE ) Looks for
% folders dated 'dd mmm yyyy' in ROOT_DIR and merges the hourly pressure,
% temperature, and NO2 files in those folders along with LON.nc and
% LAT.nc in ROOT_DIR into wrfout_cmaq files that follow the normal format
% for wrfout or wrfout_subset files read by rProfile_WRF. Only data
% between START_DATE and END_DATE are operated on.
%
% Parameters:
%
% 'overwrite' - boolean (default false), controls if existing
% wrfout_cmaq files should be overwritten.
%
% 'save_dir' - string that overrides the default save directory,
% which is fullfile(behr_paths.wrf_profiles{1}, 'hk'). Files are
% always organized into year and month subfolders within this
% save_dir, whether it is given or the default is used.
%
% 'DEBUG_LEVEL' - scalar number that controls how much information is
% printed to the terminal. Default is 2, 0 == no output.
E = JLLErrors;
p = advInputParser;
p.addFlag('check_symlinks');
p.addParameter('overwrite', false);
p.addParameter('save_dir', '');
p.addParameter('DEBUG_LEVEL', 2);
p.parse(varargin{:});
pout = p.AdvResults;
check_symlinks_bool = pout.check_symlinks;
overwrite = pout.overwrite;
save_dir = pout.save_dir;
DEBUG_LEVEL = pout.DEBUG_LEVEL;
if ~islogical(overwrite) || ~isscalar(overwrite)
E.badinput('The parameter "overwrite" must be a scalar logical value')
end
if isempty(save_dir)
save_dir = fullfile(behr_paths.wrf_profiles{1}, 'hk');
if ~exist(save_dir, 'dir')
E.dir_dne('The default root save directory (%s) does not exist', save_dir)
end
elseif ~ischar(save_dir)
E.badinput('The parameter "save_dir" must be a string')
elseif ~exist(save_dir, 'dir')
E.badinput('The save directory given (%s) does not exist', save_dir);
end
if ~isnumeric(DEBUG_LEVEL) || ~isscalar(DEBUG_LEVEL)
E.badinput('The parameter "DEBUG_LEVEL" must be a scalar number')
end
% LON.nc and LAT.nc should be present in the root directory. Rename the
% variables in the info structures so that NCWRITESCHEMA names them
% properly. There should only be one variable per file. Also, these have
% the LAY (layer) dimension, which they really don't need, because they
% aren't defined on a 4D grid.
lon_info = ncinfo(fullfile(root_dir, 'LON.nc'));
lon_info.Variables.Name = 'XLONG';
lon_info.Dimensions(3) = [];
lon_info.Variables.Dimensions(3) = [];
lon_array = ncread(lon_info.Filename, 'LON');
lat_info = ncinfo(fullfile(root_dir, 'LAT.nc'));
lat_info.Variables.Name = 'XLAT';
lat_info.Dimensions(3) = [];
lat_info.Variables.Dimensions(3) = [];
lat_array = ncread(lat_info.Filename, 'LAT');
% Map the variable file names to the desired final named in the merged
% files. The field name of the structure should be both the file name
% (before the _hh) and the variable name in the file. LON and LAT will be
% automatically mapped to XLONG and XLAT, since their files are present
% separately.
var_mapping = struct('NO2', 'no2',...
'T', 'T',...
'P', 'P',...
'PB', 'PB');
% These give the size of the CMAQ and WRF grids in the initial week of data
% that Hugo sent. They will be used to check if the input data is from that
% week and so the WRF and CMAQ grids need reconciled
hk_wrf_sz = [222, 162, 38];
hk_cmaq_sz = [98, 74, 26];
% If the grids are the size for the Hong Kong focused run, cut them
% down according to the information I got from Hugo Mak on 1 Nov 2017:
% For your first question, "I'd assume that the CMAQ levels are just the bottom 26 WRF layers, but could you verify that?", the answer is as follows:
%
% "The vertical layers in WRF runs are as follows, those in red
% (starred) are the 26 vertical layers (the 3rd variable, z) used in
% CMAQ runs:
% 1.0000*, 0.9979*, 0.9956*, 0.9931*,
% 0.9904*, 0.9875*, 0.9844*, 0.9807*,
% 0.9763*, 0.9711*, 0.9649*, 0.9575*,
% 0.9488*, 0.9385*, 0.9263*, 0.9120*,
% 0.8951*, 0.8753*, 0.8521*, 0.8251*,
% 0.7937*, 0.7597, 0.7229*, 0.6833,
% 0.6410*, 0.5960, 0.5484, 0.4985*,
% 0.4467, 0.3934, 0.3393, 0.2850*,
% 0.2316, 0.1801, 0.1324, 0.0903*,
% 0.0542, 0.0241
% (Totally 26 labelled layers)
%
% Basically, the 3rd dimension of all WRF files is 38, and only the
% following ones are useful: 1-20, 21, 23, 25, 28, 32, 36, so it
% becomes 26 vertical layers, i.e. the new dimension is 26, in line
% with CMAQ.
%
% Regarding your 2nd question: "how the T, P, and PB arrays match up
% with the NO2, lat, and lon arrays in space?", the answer is as
% follows:
%
% Before feeding into CMAQ, WRF outputs are converted into
% CMAQ-readable format by MCIP. MCIP cuts the domains of WRF outputs
% into corresponding size of CMAQ according to our configuration, so
% basically CMAQ only reads some parts of WRF outputs (in domain
% size). For WRF output files, it is 222 x 162 for (x, y) variables,
% and only the followings are useful:
%
% For x variable, from 20th to 117th entry, so it becomes dimension
% of 98 For y variable, from 35th to 108th entry, so it becomes
% dimension of 74"
hk_x_cut = 20:117;
hk_y_cut = 35:108;
hk_z_cut = [1:20, 21, 23, 25, 28, 32, 36];
datevec = datenum(start_date):datenum(end_date);
for d=1:numel(datevec)
subdir = datestr(datevec(d), 'dd mmm yyyy');
this_save_dir = fullfile(save_dir, datestr(datevec(d), 'yyyy'), datestr(datevec(d), 'mm'));
if ~exist(this_save_dir, 'dir')
mkdir(this_save_dir)
end
for h=1:24
outfile = sprintf('wrfout_cmaq_%s_%02d-00-00', datestr(datevec(d), 'yyyy-mm-dd'), h-1);
full_outfile = fullfile(this_save_dir, outfile);
if exist(full_outfile, 'file')
if ~overwrite
if DEBUG_LEVEL > 0
fprintf('%s already exists\n', full_outfile)
end
continue
else
delete(full_outfile);
end
end
% Copy the variable names and attributes
copy_schema(fullfile(root_dir, subdir), h, full_outfile, check_symlinks_bool, datevec(d));
% Copy the actual data, cutting down the WRF variables if
% necessary.
copy_data(fullfile(root_dir, subdir), h, full_outfile);
end
end
function copy_schema(input_dir, file_hour, output_file, check_links_bool, curr_date)
fns = fieldnames(var_mapping);
input_info = make_empty_struct_from_cell(fns);
for f=1:numel(fns)
input_file = make_input_name(input_dir, fns{f}, file_hour);
if check_links_bool
check_symlink(input_file, curr_date);
end
input_info.(fns{f}) = ncinfo(input_file);
input_info.(fns{f}).Variables.Name = var_mapping.(fns{f});
end
input_info.LON = lon_info;
input_info.LAT = lat_info;
input_info = match_cmaq_wrf_schema_grids(input_info);
ncwriteschema(output_file, input_info.LON);
ncwriteschema(output_file, input_info.LAT);
for f=1:numel(fns)
ncwriteschema(output_file, input_info.(fns{f}));
end
end
function copy_data(input_dir, file_hour, output_file)
% Load the data
fns = fieldnames(var_mapping);
data_struct = make_empty_struct_from_cell(fns);
for f=1:numel(fns)
input_file = make_input_name(input_dir, fns{f}, file_hour);
data_struct.(fns{f}) = ncread(input_file, fns{f});
end
data_struct.LON = lon_array;
data_struct.LAT = lat_array;
% Match up the CMAQ and WRF outputs
data_struct = match_cmaq_wrf_data_grids(data_struct);
% Write each array to the output file
ncwrite(output_file, 'XLONG', data_struct.LON);
ncwrite(output_file, 'XLAT', data_struct.LAT);
for f=1:numel(fns)
ncwrite(output_file, var_mapping.(fns{f}), data_struct.(fns{f}));
end
end
function data = match_cmaq_wrf_data_grids(data)
if all_sizes_equal(data)
% If all the grids are the right size (accounting for 2D grids), we can
% return data unaltered
return
elseif isequal(size(data.NO2), hk_cmaq_sz) && isequal(size(data.LON), hk_cmaq_sz(1:2)) && isequal(size(data.LAT), hk_cmaq_sz(1:2)) && isequal(size(data.P), hk_wrf_sz) && isequal(size(data.PB), hk_wrf_sz) && isequal(size(data.T), hk_wrf_sz)
data.P = data.P(hk_x_cut, hk_y_cut, hk_z_cut);
data.PB = data.PB(hk_x_cut, hk_y_cut, hk_z_cut);
data.T = data.T(hk_x_cut, hk_y_cut, hk_z_cut);
else
E.callError('undef_grid', 'No subsetting defined for CMAQ/WRF grid sizes of %s vs. %s', mat2str(size(data.NO2)), mat2str(size(data.P)));
end
end
function schema = match_cmaq_wrf_schema_grids(schema)
% First, we need to make sure only one dimension is unlimited.
% We'll use the WRF Time dimension
unlimited_ind = [schema.P.Dimensions.Name];
if sum(unlimited_ind) == 1
wrf_unlimited_dim = schema.P.Dimensions(unlimited_ind);
else
wrf_unlimited_dim = [];
warning('No unlimited dimension found!');
end
% The way that "schema" is set up, is that each variable is
% represented by a schema for a single variable file. So, e.g.
% schema.P is as if ncinfo was called on a file that only had one
% variable, P. (That's why below we can reference
% schema.(fns{f}).Variables.Dimensions without a multiple-reference
% error). This whole block is dealing with different "Time"
% dimensions between WRF and CMAQ. Basically, since version 3
% netCDF files can only have one unlimited dimension, any unlimited
% dimension gets overwritten by the WRF "Time" dimension so that
% only one unlimited dimension is defined across all the schema.
%
% In the WRF files cut down to match CMAQ, the "Time" dimension is
% missing. In that case, we'll just remove the unlimited dimension
% entirely, since BEHR assumes that each file only contains one
% time anyway.
fns = fieldnames(schema);
for f=1:numel(fns)
for i=1:numel(schema.(fns{f}).Dimensions)
if schema.(fns{f}).Dimensions(i).Unlimited
% Found an unlimited dimension - overwrite it with the
% WRF "Time" dimension, if that exists.
if ~isempty(wrf_unlimited_dim)
schema.(fns{f}).Dimensions(i) = wrf_unlimited_dim;
if schema.(fns{f}).Variables.Dimensions(i).Unlimited
schema.(fns{f}).Variables.Dimensions(i) = wrf_unlimited_dim;
else
E.callError('time_dim', 'Unlimited dimension is different in the root and variable dimensions for %s', schema.(fns{f}).Filename);
end
else
% If WRF files do not have an unlimited dimension,
% we need to remove the unlimited dimension from
% the CMAQ file and variables.
% Matlab seems to make a distinction between a
% literal empty array and one saved to a variable,
% so we have to explicitly use the empty brackets
% to remove the dimension.
schema.(fns{f}).Dimensions(i) = [];
if schema.(fns{f}).Variables.Dimensions(i).Unlimited
schema.(fns{f}).Variables.Dimensions(i) = [];
else
E.callError('time_dim', 'Unlimited dimension is different in the root and variable dimensions for %s', schema.(fns{f}).Filename);
end
end
end
end
% Also make everything 64 bit
schema.(fns{f}).Format = '64bit';
end
if all_sizes_equal(schema)
return
elseif isequal(size_from_schema(schema.NO2), hk_cmaq_sz) && isequal(size_from_schema(schema.LON), hk_cmaq_sz(1:2)) && isequal(size_from_schema(schema.LAT), hk_cmaq_sz(1:2)) && isequal(size_from_schema(schema.P), hk_wrf_sz) && isequal(size_from_schema(schema.PB), hk_wrf_sz) && isequal(size_from_schema(schema.T), hk_wrf_sz)
schema.P = set_schema_dims(schema.P, hk_cmaq_sz);
schema.PB = set_schema_dims(schema.PB, hk_cmaq_sz);
schema.T = set_schema_dims(schema.T, hk_cmaq_sz);
else
E.callError('undef_grid', 'No subsetting defined for CMAQ/WRF grid sizes of %s vs. %s', mat2str(size_from_schema(schema.NO2)), mat2str(size_from_schema(schema.P)));
end
end
end
function input_file = make_input_name(input_dir, var_name, file_hour)
input_file = fullfile(input_dir, sprintf('%s_%d.nc', var_name, file_hour));
end
function chk = all_sizes_equal(data_in)
% Were we given a structure of the data fields, or of the schema?
if isfield(data_in.NO2,'Variables')
sz_fxn = @(x) size_from_schema(x);
else
sz_fxn = @(x) size(x);
end
% Assume the sizes are unequal until we prove otherwise
chk = false;
sz = sz_fxn(data_in.NO2); % Assume that all the 3D variables are centered in the grid cells, and so have the same size as NO2
fns = fieldnames(data_in);
% Check each field. If the size doesn't match, return false. If we get
% through to the end, all fields' sizes must have matched, so return true.
for f=1:numel(fns)
if ismember(fns{f}, {'LON','LAT'})
if ~isequal(sz_fxn(data_in.(fns{f})), sz(1:2))
return
end
else
if ~isequal(sz_fxn(data_in.(fns{f})), sz)
return
end
end
end
chk = true;
end
function sz = size_from_schema(schema)
E = JLLErrors;
sz = [schema.Dimensions.Length];
if ~isequal(sz, [schema.Variables.Dimensions.Length])
E.callError('dim_mismatch', 'Lenghts of root dimensions is different from the lengths of %s dimensions in %s', schema.Filename, schema.Variables.Name);
end
% Remove trailing singleton dimensions
xx = find(sz > 1, 1, 'last');
sz = sz(1:xx);
end
function schema = set_schema_dims(schema, sz)
E = JLLErrors;
if numel(schema.Dimensions) ~= numel(schema.Variables.Dimensions)
E.callError('dim_mismatch', 'Number of root dimensions is different from the number of %s dimensions in %s', schema.Filename, schema.Variables.Name);
end
for i=1:numel(schema.Dimensions)
if i > numel(sz)
sz_i = 1;
else
sz_i = sz(i);
end
schema.Dimensions(i).Length = sz_i;
schema.Variables.Dimensions(i).Length = sz_i;
end
end
function check_symlink(link_file, path_date)
% Check that a symlink is pointing to a file for the current date. This
% assumes that the file pointed to by the link resides in a folder named as
% the date; i.e. the next to last path component is a folder with that
% date.
E = JLLErrors;
[stat, link_path] = system(sprintf('readlink "%s"', link_file));
if stat ~= 0
return
end
tmp_path = strsplit(link_path, '/');
date_folder = tmp_path{end-1};
if datenum(date_folder, 'dd mmm yyyy') ~= datenum(path_date)
E.callError('check_symlink:wrong_date', 'File (%s) linked to wrong date (%s instead of %s)', link_file, date_folder, datestr(path_date, 'dd mmm yyyy'));
else
fprintf('Link %s correct\n', link_file);
end
end
|
github
|
chamara84/proactiveChannelSelectionCR-master
|
rewardCalcForChannel.m
|
.m
|
proactiveChannelSelectionCR-master/rewardCalcForChannel.m
| 5,042 |
utf_8
|
d8c8c83c480054af02c9a678f036f063
|
function [channelIndex,reward] = rewardCalcForChannel(channelIndex,current_slot,senseResult,senseTime,channelTransitionMat,stationProb,falseAlarm,missedDet, bufferSize, channelAcqProb, pktTrProb)
%vector order [busy;idle]
%transitionMatrix order = [11,10;
% 01,00]
Q = 1000;
%% initial Vector at sensing time Building
if senseResult == 1 %channel sensed busy
tau_chanState = [(1-missedDet)*stationProb(1,1);1-(1-missedDet)*stationProb(1,1)]; % channel state Prob vector if Busy
tau = tau_chanState'*channelTransitionMat^(current_slot-senseTime); % initial vector at current time
elseif senseResult == 0 %sensed idle
tau_chanState = [1-(1-falseAlarm)*stationProb(2,1);(1-falseAlarm)*stationProb(2,1)];% channel state Prob vector if idle
tau = tau_chanState'*channelTransitionMat^(current_slot-senseTime); % initial vector at current time
else
tau = stationProb;% initial vector at current time
end
tau
tau = [tau';zeros(2*bufferSize-2,1)]';
%% Transition Matrix building for my scheme
T = zeros(2*bufferSize);
T_D = zeros(2*bufferSize);
T_U = zeros(2*bufferSize);
A_0 = [0,0; (1-pktTrProb)*channelAcqProb*channelTransitionMat(2,1)*(1-falseAlarm),(1-pktTrProb)*channelAcqProb*channelTransitionMat(2,2)*(1-falseAlarm)];
A_1 = [(1-pktTrProb)*channelTransitionMat(1,1),(1-pktTrProb)*channelTransitionMat(1,2);
pktTrProb*channelAcqProb*(1-falseAlarm)*channelTransitionMat(2,1)+(1-pktTrProb)*(1-channelAcqProb)*channelTransitionMat(2,1)*(1-falseAlarm)+(1-pktTrProb)*channelTransitionMat(2,1)*falseAlarm,pktTrProb*channelAcqProb*(1-falseAlarm)*channelTransitionMat(2,2)+(1-pktTrProb)*(1-channelAcqProb)*channelTransitionMat(2,2)*(1-falseAlarm)+(1-pktTrProb)*channelTransitionMat(2,2)*falseAlarm];
A_2 = [pktTrProb*channelTransitionMat(1,1),pktTrProb*channelTransitionMat(1,2);
pktTrProb*(1-channelAcqProb)*(1-falseAlarm)*channelTransitionMat(2,1)+pktTrProb*falseAlarm*channelTransitionMat(2,1),pktTrProb*(1-channelAcqProb)*(1-falseAlarm)*channelTransitionMat(2,2)+pktTrProb*falseAlarm*channelTransitionMat(2,2)];
%% reward of trnsmission
A_0_D = [0,0; (1-pktTrProb)*channelAcqProb*channelTransitionMat(2,1)*(1-falseAlarm),(1-pktTrProb)*channelAcqProb*channelTransitionMat(2,2)*(1-falseAlarm)];
A_1_D =[0,0;0,0];
A_2_D =[0,0;0,0];
%% cost of failing to transmit
A_0_U =[0,0;0,0];
A_1_U = [(1-pktTrProb)*channelTransitionMat(1,1),(1-pktTrProb)*channelTransitionMat(1,2);
(1-pktTrProb)*(1-channelAcqProb)*channelTransitionMat(2,1)*(1-falseAlarm),(1-pktTrProb)*(1-channelAcqProb)*channelTransitionMat(2,2)*(1-falseAlarm)];
A_2_U = [pktTrProb*channelTransitionMat(1,1),pktTrProb*channelTransitionMat(1,2);
pktTrProb*(1-channelAcqProb)*(1-falseAlarm)*channelTransitionMat(2,1),pktTrProb*(1-channelAcqProb)*(1-falseAlarm)*channelTransitionMat(2,2)];
T(1:2,1:2) = A_1;
T(1:2,3:4) = A_2;
T((2*bufferSize-1):(2*bufferSize),(2*bufferSize-3):(2*bufferSize-2)) = A_0;
T((2*bufferSize-1):(2*bufferSize),(2*bufferSize-1):(2*bufferSize)) = A_1+A_2;
T_D(1:2,1:2) = A_1_D;
T_D(1:2,3:4) = A_2_D;
T_D((2*bufferSize-1):(2*bufferSize),(2*bufferSize-3):(2*bufferSize-2)) = A_0_D;
T_D((2*bufferSize-1):(2*bufferSize),(2*bufferSize-1):(2*bufferSize)) = A_1_D+A_2_D;
T_U(1:2,1:2) = A_1_U;
T_U(1:2,3:4) = A_2_U;
T_U((2*bufferSize-1):(2*bufferSize),(2*bufferSize-3):(2*bufferSize-2)) = A_0_U;
T_U((2*bufferSize-1):(2*bufferSize),(2*bufferSize-1):(2*bufferSize)) = A_1_U+A_2_U;
for row = 3:2:(2*bufferSize-3)
T(row:row+1,(row-2):(row-1)) = A_0;
T(row:row+1,row:row+1) = A_1;
T(row:row+1,(row+2):(row+3)) = A_2;
T_D(row:row+1,(row-2):(row-1)) = A_0_D;
T_D(row:row+1,row:row+1) = A_1_D;
T_D(row:row+1,(row+2):(row+3)) = A_2_D;
T_U(row:row+1,(row-2):(row-1)) = A_0_U;
T_U(row:row+1,row:row+1) = A_1_U;
T_U(row:row+1,(row+2):(row+3)) = A_2_U;
end
sum(T,2)
%% absorption vector
T_0 = [0;(1-pktTrProb)*channelAcqProb*(channelTransitionMat(2,1)+channelTransitionMat(2,2)*(1-falseAlarm));zeros(2*bufferSize-2,1)];
cumProb = 0;
reward = 0;
n = 1;
while n< Q %%cumProb <0.95 &&
%prob = tau*T^n*T_0;
prob = T^n*T_0;
%cumProb = cumProb + prob;
%reward = reward + n*prob;
reward = reward + prob;
n = n+1;
end
reward
tau*reward
Exp_U = 0;
Exp_D = 0;
tempSumOuter_D = 0;
tempSumOuter_U = 0;
for iteration = 1:(Q-1)
tempSumInner_D = 0;
tempSumInner_U = 0;
for innerIteration = 1:(iteration-1)
before = T^(innerIteration-1);
after = T^(iteration-innerIteration-1)*T_0;
tempSumInner_D = tempSumInner_D + before*T_D*after;
tempSumInner_U = tempSumInner_U + before*T_U*after;
end
tempSumOuter_D = tempSumOuter_D +tempSumInner_D;
tempSumOuter_U = tempSumOuter_U +tempSumInner_U;
end
tau*tempSumOuter_D
tau*tempSumOuter_U
end
|
github
|
EnyaHermite/fastDesp-corrProp-master
|
flann_search.m
|
.m
|
fastDesp-corrProp-master/flann/flann_search.m
| 3,564 |
utf_8
|
7dfb2eee171a6fef9aa4adec527e3145
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. 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 AUTHOR ``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 AUTHOR 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.
function [indices, dists] = flann_search(data, testset, n, search_params)
%NN_SEARCH Fast approximate nearest neighbors search
%
% Performs a fast approximate nearest neighbor search using an
% index constructed using flann_build_index or directly a
% dataset.
% Marius Muja, January 2008
algos = struct( 'linear', 0, 'kdtree', 1, 'kmeans', 2, 'composite', 3, 'lsh', 6, 'saved', 254, 'autotuned', 255 );
center_algos = struct('random', 0, 'gonzales', 1, 'kmeanspp', 2 );
log_levels = struct('none', 0, 'fatal', 1, 'error', 2, 'warning', 3, 'info', 4);
default_params = struct('algorithm', 'kdtree' ,'checks', 32, 'eps', 0.0, 'sorted', 1, 'max_neighbors', -1, 'cores', 1, 'trees', 4, 'branching', 32, 'iterations', 5, 'centers_init', 'random', 'cb_index', 0.4, 'target_precision', 0.9,'build_weight', 0.01, 'memory_weight', 0, 'sample_fraction', 0.1, 'table_number', 12, 'key_size', 20, 'multi_probe_level', 2, 'log_level', 'warning', 'random_seed', 0);
if ~isstruct(search_params)
error('The "search_params" argument must be a structure');
end
params = default_params;
fn = fieldnames(search_params);
for i = [1:length(fn)],
name = cell2mat(fn(i));
params.(name) = search_params.(name);
end
if ~isnumeric(params.algorithm),
params.algorithm = value2id(algos,params.algorithm);
end
if ~isnumeric(params.centers_init),
params.centers_init = value2id(center_algos,params.centers_init);
end
if ~isnumeric(params.log_level),
params.log_level = value2id(log_levels,params.log_level);
end
if (size(data,1)==1 && size(data,2)==1)
% we already have an index
[indices,dists] = nearest_neighbors('index_find_nn', data, testset, n, params);
else
% create the index and search
[indices,dists] = nearest_neighbors('find_nn', data, testset, n, params);
end
end
function value = id2value(map, id)
fields = fieldnames(map);
for i = 1:length(fields),
val = cell2mat(fields(i));
if map.(val) == id
value = val;
break;
end
end
end
function id = value2id(map,value)
id = map.(value);
end
|
github
|
EnyaHermite/fastDesp-corrProp-master
|
flann_load_index.m
|
.m
|
fastDesp-corrProp-master/flann/flann_load_index.m
| 1,578 |
utf_8
|
f9bcc41fd5972c5c987d6a4d41bdc796
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. 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 AUTHOR ``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 AUTHOR 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.
function index = flann_load_index(filename, dataset)
%FLANN_LOAD_INDEX Loads an index from disk
%
% Marius Muja, March 2009
index = nearest_neighbors('load_index', filename, dataset);
end
|
github
|
EnyaHermite/fastDesp-corrProp-master
|
test_flann.m
|
.m
|
fastDesp-corrProp-master/flann/test_flann.m
| 10,328 |
utf_8
|
151c22994b0192f8a071649ad26fbc6b
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. 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 AUTHOR ``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 AUTHOR 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.
function test_flann
data_path = './';
outcome = {'FAILED!!!!!!!!!', 'PASSED'};
failed = 0;
passed = 0;
cnt = 0;
ok = 1;
function assert(condition)
if (~condition)
ok = 0;
end
end
function run_test(name, test)
ok = 1;
cnt = cnt + 1;
tic;
fprintf('Test %d: %s...',cnt,name);
test();
time = toc;
if (ok)
passed = passed + 1;
else
failed = failed + 1;
end
fprintf('done (%g sec) : %s\n',time,cell2mat(outcome(ok+1)))
end
function status
fprintf('-----------------\n');
fprintf('Passed: %d/%d\nFailed: %d/%d\n',passed,cnt,failed,cnt);
end
dataset = [];
testset = [];
function test_load_data
% load the datasets and testsets
% use single precision for better memory efficiency
% store the features one per column because MATLAB
% uses column major ordering
% The dataset.dat and testset.dat files can be downloaded from:
% http://people.cs.ubc.ca/~mariusm/uploads/FLANN/datasets/dataset.dat
% http://people.cs.ubc.ca/~mariusm/uploads/FLANN/datasets/testset.dat
dataset = single(load([data_path 'dataset.dat']))';
testset = single(load([data_path 'testset.dat']))';
assert(size(dataset,1) == size(testset,1));
end
run_test('Load data',@test_load_data);
match = [];
dists = [];
function test_linear_search
[match,dists] = flann_search(dataset, testset, 10, struct('algorithm','linear'));
assert(size(match,1) ==10 && size(match,2) == size(testset,2));
end
run_test('Linear search',@test_linear_search);
function test_kdtree_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','kdtree',...
'trees',8,...
'checks',64));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('kd-tree search',@test_kdtree_search);
function test_kmeans_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('k-means search',@test_kmeans_search);
function test_composite_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','composite',...
'branching',32,...
'iterations',3,...
'trees', 1,...
'checks',64));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('composite search',@test_composite_search);
function test_autotune_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','autotuned',...
'target_precision',0.95,...
'build_weight',0.01,...
'memory_weight',0));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('search with autotune',@test_autotune_search);
function test_index_kdtree_search
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kdtree', 'trees',8,...
'checks',64));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kd-tree search',@test_index_kdtree_search);
function test_index_kmeans_search
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kmeans search',@test_index_kmeans_search);
function test_index_kmeans_search_gonzales
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120,...
'centers_init','gonzales'));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kmeans search gonzales',@test_index_kmeans_search_gonzales);
function test_index_kmeans_search_kmeanspp
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120,...
'centers_init','kmeanspp'));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kmeans search kmeanspp',@test_index_kmeans_search_kmeanspp);
function test_index_composite_search
[index, search_params ] = flann_build_index(dataset,struct('algorithm','composite',...
'branching',32,...
'iterations',3,...
'trees', 1,...
'checks',64));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index composite search',@test_index_composite_search);
function test_index_autotune_search
[index, search_params, speedup ] = flann_build_index(dataset,struct('algorithm','autotuned',...
'target_precision',0.95,...
'build_weight',0.01,...
'memory_weight',0));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index autotune search',@test_index_autotune_search);
status();
end
|
github
|
EnyaHermite/fastDesp-corrProp-master
|
flann_free_index.m
|
.m
|
fastDesp-corrProp-master/flann/flann_free_index.m
| 1,614 |
utf_8
|
5d719d8d60539b6c90bee08d01e458b5
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. 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 AUTHOR ``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 AUTHOR 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.
function flann_free_index(index_id)
%FLANN_FREE_INDEX Deletes the nearest-neighbors index
%
% Deletes an index constructed using flann_build_index.
% Marius Muja, January 2008
nearest_neighbors('free_index',index_id);
end
|
github
|
EnyaHermite/fastDesp-corrProp-master
|
flann_save_index.m
|
.m
|
fastDesp-corrProp-master/flann/flann_save_index.m
| 1,563 |
utf_8
|
5a44d911827fba5422041529b3c01cf6
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. 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 AUTHOR ``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 AUTHOR 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.
function flann_save_index(index_id, filename)
%FLANN_SAVE_INDEX Saves an index to disk
%
% Marius Muja, March 2010
nearest_neighbors('save_index',index_id, filename);
end
|
github
|
EnyaHermite/fastDesp-corrProp-master
|
flann_set_distance_type.m
|
.m
|
fastDesp-corrProp-master/flann/flann_set_distance_type.m
| 1,914 |
utf_8
|
a62dd85add564e04c01aefeb65083f5d
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. 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 AUTHOR ``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 AUTHOR 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.
function flann_set_distance_type(type, order)
%FLANN_LOAD_INDEX Loads an index from disk
%
% Marius Muja, March 2009
distances = struct('euclidean', 1, 'manhattan', 2, 'minkowski', 3, 'max_dist', 4, 'hik', 5, 'hellinger', 6, 'chi_square', 7, 'cs', 7, 'kullback_leibler', 8, 'kl', 8);
if ~isnumeric(type),
type = value2id(distances,type);
end
if type~=3
order = 0;
end
nearest_neighbors('set_distance_type', type, order);
end
function id = value2id(map,value)
id = map.(value);
end
|
github
|
EnyaHermite/fastDesp-corrProp-master
|
flann_build_index.m
|
.m
|
fastDesp-corrProp-master/flann/flann_build_index.m
| 2,299 |
utf_8
|
f4cdee51a1c9616f205dcc814c943903
|
function [index, params, speedup] = flann_build_index(dataset, build_params)
%FLANN_BUILD_INDEX Builds an index for fast approximate nearest neighbors search
%
% [index, params, speedup] = flann_build_index(dataset, build_params) - Constructs the
% index from the provided 'dataset' and (optionally) computes the optimal parameters.
% Marius Muja, January 2008
algos = struct( 'linear', 0, 'kdtree', 1, 'kmeans', 2, 'composite', 3, 'kdtree_single', 4, 'hierarchical', 5, 'lsh', 6, 'saved', 254, 'autotuned', 255 );
center_algos = struct('random', 0, 'gonzales', 1, 'kmeanspp', 2 );
log_levels = struct('none', 0, 'fatal', 1, 'error', 2, 'warning', 3, 'info', 4);
default_params = struct('algorithm', 'kdtree' ,'checks', 32, 'eps', 0.0, 'sorted', 1, 'max_neighbors', -1, 'cores', 1, 'trees', 4, 'branching', 32, 'iterations', 5, 'centers_init', 'random', 'cb_index', 0.4, 'target_precision', 0.9,'build_weight', 0.01, 'memory_weight', 0, 'sample_fraction', 0.1, 'table_number', 12, 'key_size', 20, 'multi_probe_level', 2, 'log_level', 'warning', 'random_seed', 0);
if ~isstruct(build_params)
error('The "build_params" argument must be a structure');
end
params = default_params;
fn = fieldnames(build_params);
for i = [1:length(fn)],
name = cell2mat(fn(i));
params.(name) = build_params.(name);
end
if ~isnumeric(params.algorithm),
params.algorithm = value2id(algos,params.algorithm);
end
if ~isnumeric(params.centers_init),
params.centers_init = value2id(center_algos,params.centers_init);
end
if ~isnumeric(params.log_level),
params.log_level = value2id(log_levels,params.log_level);
end
[index, params, speedup] = nearest_neighbors('build_index',dataset, params);
if isnumeric(params.algorithm),
params.algorithm = id2value(algos,params.algorithm);
end
if isnumeric(params.centers_init),
params.centers_init = id2value(center_algos,params.centers_init);
end
end
function value = id2value(map, id)
fields = fieldnames(map);
for i = 1:length(fields),
val = cell2mat(fields(i));
if map.(val) == id
value = val;
break;
end
end
end
function id = value2id(map,value)
id = map.(value);
end
|
github
|
nthallen/keutsch-hcho-master
|
scancorrect.m
|
.m
|
keutsch-hcho-master/eng/workup/scancorrect.m
| 295 |
utf_8
|
67a0828b2a94fb56b7877df5e6b990c4
|
% Fix scan index issue (FPGA switches to online label before the scan is
% actually complete)
function NewIndices = scancorrect(i)
chunks = chunker(i);
NewChunks = [chunks(:,1) chunks(:,2)+25];
%There are 15 points at the end not labeled as scan points
NewIndices = ChunkIndices(NewChunks);
|
github
|
nthallen/keutsch-hcho-master
|
RemoveFirstPoints.m
|
.m
|
keutsch-hcho-master/eng/workup/RemoveFirstPoints.m
| 595 |
utf_8
|
d041c4bc460d842a5ce6281b3474747e
|
%function FirstPointsRemoved = RemoveFirstPoints(i,n)
%input is the online indices and the number of points at the start of each
%cycles you wish to remove, assessed after viewing the raw data for errors
%output is the online indices without erroneous points
%111811 JBK
%05APR2018 JDS
function [NewIndices,RemovedIndices] = RemoveFirstPoints(i, n)
chunks = chunker(i);
OriginalStart = chunks(:,1);
NewStart = OriginalStart+n;
NewChunks = [NewStart chunks(:,2)];
NewIndices = ChunkIndices(NewChunks);
RemovedChunks = [OriginalStart NewStart];
RemovedIndices = ChunkIndices(RemovedChunks);
|
github
|
nthallen/keutsch-hcho-master
|
refcellcorrect.m
|
.m
|
keutsch-hcho-master/eng/workup/refcellcorrect.m
| 4,249 |
utf_8
|
3d23c2f77e8a0db570d5c2bc8315df04
|
%refcellcorrect_return = refcellcorrect(Data10Hz,Data1Hz,maxLaserV,method,plotme)
% PURPOSE: Correct for any drift in difference count signal that resulted
% in shifting of the laser voltage or peak position (that wasn't recorded
% by the instrument)
function refcellcorrect_return = refcellcorrect(Data10Hz,Data1Hz,maxLaserV,method,plotme,mVwindow,SWScode)
% Find indices of ONLINE and SCAN points
refcellcorrect.online = find(Data10Hz.BCtr_LVstat==10);
refcellcorrect.scan = find(Data10Hz.BCtr_LVstat==1);
% Chunk the scan indices
refcellcorrect.scan_chunks = chunker(refcellcorrect.scan);
l=size(refcellcorrect.scan_chunks,1);
refcellcorrect.time_max=nan(l,1);
refcellcorrect.scan_max_value=nan(l,1);
refcellcorrect.scan_max_LasV=nan(l,1);
for i=1:l
j = refcellcorrect.scan_chunks(i,1):refcellcorrect.scan_chunks(i,2);
% We have to add on the value of refcellcorrect.scan_chunks(i,1) since
% scan_max_index is the index for a subset of data in Data10Hz.powernorm_ref
% rather than the entire array
[refcellcorrect.scan_max_value(i), scan_max_index] = max(Data10Hz.powernorm_ref(j));
max_lasV = Data10Hz.BCtr_LaserV(refcellcorrect.scan_chunks(i,1) + scan_max_index);
refcellcorrect.time_max(i) = Data10Hz.Thchoeng_10(refcellcorrect.scan_chunks(i,1) + scan_max_index);
% Sometimes, the start or end of a scan has an extraneously high point
% that throws off this algo. This if statement ensures that this doesn't
% happen
if (max_lasV < (maxLaserV - mVwindow) || max_lasV > (maxLaserV + mVwindow))
refcellcorrect.scan_max_value(i) = NaN;
refcellcorrect.time_max(i) = NaN;
end
end
% Remove any outliers
A = isoutlier(refcellcorrect.scan_max_value,'mean');
for i=1:length(A)
if A(i)==1
refcellcorrect.scan_max_value(i) = NaN;
refcellcorrect.time_max(i) = NaN;
end
end
% Only consider data after we started our five-minute chopping cycle
start_time = Data1Hz.Thchoeng_1(Data1Hz.SWStat == SWScode);
start_time = start_time(1);
for i=1:length(refcellcorrect.time_max)
if (refcellcorrect.time_max(i) - start_time < 0 || isnan(refcellcorrect.time_max(i)))
refcellcorrect.scan_max_value(i) = NaN;
refcellcorrect.time_max(i) = NaN;
end
end
% Makes sure that if there was a NaN in scan_max_value that a NaN also
% appears for the corresponding time so that both are removed in the next
% bit of code
for i=1:length(refcellcorrect.time_max)
if isnan(refcellcorrect.scan_max_value(i))
refcellcorrect.time_max(i) = NaN;
end
end
% Remove NaNs from dataset before fitting
refcellcorrect.time_max(any(isnan(refcellcorrect.time_max),2),:) = [];
refcellcorrect.scan_max_value(any(isnan(refcellcorrect.scan_max_value),2),:) = [];
switch method
case 'interpolate'
% Generate a moving mean to minimize the effect of noise in each
% of the max peak heights
refcellcorrect.scan_max_value_movmean = movmean(refcellcorrect.scan_max_value,8);
% Interpolate the max peak heights
refcellcorrect.scan_max_interp = interp1(refcellcorrect.time_max,refcellcorrect.scan_max_value_movmean,Data10Hz.Thchoeng_10);
refcellcorrect.time_max_datetime = datetime(refcellcorrect.time_max,'ConvertFrom','posixtime');
if plotme
figure,plot(Data10Hz.datetime+hours(4),refcellcorrect.scan_max_interp)
hold on
plot(refcellcorrect.time_max_datetime,refcellcorrect.scan_max_value,'.')
end
% Find correction ratio by dividing the interpolated heights by the power
% and trigger-normalized ref counts
ratio=refcellcorrect.scan_max_interp./Data10Hz.powernorm_ref;
case 'polyfit'
f = fit(refcellcorrect.time_max,refcellcorrect.scan_max_value,'poly1');
if plotme
figure,plot(f,refcellcorrect.time_max,refcellcorrect.scan_max_value)
end
% Find ratio using REFERENCE cell
correctionvalues = f(Data10Hz.Thchoeng_10);
ratio = correctionvalues./Data10Hz.powernorm_ref;
otherwise
error('Specified method not supported')
end
refcellcorrect_return = Data10Hz.diffcounts.*ratio;
|
github
|
nthallen/keutsch-hcho-master
|
ChunkIndices.m
|
.m
|
keutsch-hcho-master/eng/workup/ChunkIndices.m
| 411 |
utf_8
|
1f6bb48cbfa520023cbe4302f4066384
|
% function ChunkIndices = ChunkIndices(chunks)
%input is a vector containing output from chunker, which is [start indices,
%stop indices]
%output is single vector that contains all the indices within each chunk
%111811 JBK
function ChunkIndices = ChunkIndices(chunks)
ChunkIndices=[];
l=length(chunks);
for i=1:length(chunks);
j = chunks(i,1):chunks(i,2);
j=j';
ChunkIndices=[ChunkIndices;j];
end
|
github
|
nthallen/keutsch-hcho-master
|
powercal.m
|
.m
|
keutsch-hcho-master/eng/workup/powercal.m
| 3,594 |
utf_8
|
207f516749a481337a289b0e140ce1f8
|
% function power = UDTcal(udt,caldate,plotme)
% feed this function a udt signal (in V) to get back power (in mW). Note
% that using this function requires that you have done a power calibration
% on the UDT, which can change with orientation and time.
% INPUTS:
% udt: raw udt voltage
% caldate: date of calibration to use for correction (optional but recommended)
% plotme: flag for generating a plot of the calibration curve (optional)
%OUTPUT:
% power: UDT signal corrected to mW of laser power.
%110823 GMW
function power = powercal(udt,caldate,plotme)
%set defaults for optional inputs
if nargin<3
plotme=0;
if nargin<2
caldate = '08MAR2018';
disp('Using default power function. Your power meters may not be calibrated')
end
end
%Choose calibration curve
switch caldate
case '08MAR2018'
power_cal = [12.1 9.3 10.0 8.3 7.0 6.1 5.0 4.0 3.6 3.1 2.5 2.0 1.5 0.75 0.0];
udt_cal = [0.272 0.237 0.2450 0.216 0.1880 0.1660 0.1410 0.1190 0.1065 0.0920 0.0770 0.063 0.048 0.025 0.0002]; %LasPwrIn values
case '24MAR2018'
power_cal = [11.65 11.2 10.55 9.45 8.3 7.05 6.15 5.3 4.45 3.95 3.45 3.0 2.65 2.0 1.7 1.4 1.0 0.0];
udt_cal = [0.281 0.273 0.261 0.244 0.220 0.1940 0.1730 0.1530 0.1340 0.1180 0.1050 0.093 0.082 0.0645 0.056 0.047 0.034 0.0002]; %LasPwrIn values
case '04APR2018'
power_cal = [11.35 9.75 7.95 6.55 5.2 4.25 3.15 2.65];
udt_cal = [0.2670 0.2500 0.2300 0.2100 0.1910 0.1730 0.1500 0.1360]; %LasPwrIn values
case '10APR2018'
power_cal = [12.9 11.7 10.35 9.05 7.8 7.2 6.35 5.5 4.35 3.45];
udt_cal = [0.2797 0.2690 0.2555 0.2410 0.2270 0.2200 0.2080 0.1950 0.1760 0.1580]; %LasPwrIn values
case '14JUN2018'
power_cal = [11.5 10.75 10.5 10.15 9.55 8.8 8.2 7.4 6.7 5.95 5.3 5.1 4.55 4.0 3.5];
udt_cal = [0.2595 0.2520 0.2500 0.2460 0.2390 0.2310 0.2235 0.2140 0.2040 0.1935 0.1835 0.1800 0.1710 0.1605 0.1520]; %LasPwrIn values
case '20JUN2018'
power_cal = [7.63 6.60 6.85 6.35 5.86 5.34 4.55 3.63 2.88 2.41 2.29 2.06 2.12];
udt_cal = [0.2113 0.2010 0.2037 0.1983 0.1925 0.1857 0.1745 0.1589 0.1428 0.1306 0.1267 0.1186 0.1211]; %LasPwrIn values
case '26JUN2018'
power_cal = [5.95 7.54 8.31 8.1 9.1 9.61 7.75 6.41 5.66 5.27 4.17 3.69 3.33 3.10 3.20 2.76 2.26 1.92 1.59 1.31 1.05];
udt_cal = [0.1933 0.2094 0.2161 0.2145 0.2225 0.2261 0.2125 0.1990 0.1900 0.1846 0.1680 0.1600 0.1530 0.1480 0.1502 0.1400 0.1256 0.1130 0.0985 0.0841 0.0690]; %LasPwrIn values
case '12SEPT2018'
power_cal = [9.97 8.93 8.08 7.21 6.3 5.34 4.46 3.67 3.02 2.53 2.12 1.76 1.49 0.85];
udt_cal = [12.29 11.21 10.29 9.24 7.98 6.54 5.15 3.82 2.82 2.21 1.78 1.44 1.21 0.66]; %LasPwrIn values
case '14SEPT2018'
power_cal = [6.80 6.36 5.70 5.02 4.27 3.44 2.77 2.30 2.06 1.86 1.64 1.35 1.06];
udt_cal = [4.40 4.22 3.90 3.58 3.18 2.73 2.30 1.96 1.76 1.60 1.42 1.19 0.94]; %LasPwrIn values
case '13OCT2018'
power_cal = [3.28 2.95 2.65 2.34 2.08 1.84 1.61 1.41 1.21 1.03 0.86];
udt_cal = [3.65 3.19 2.78 2.39 2.07 1.79 1.54 1.34 1.15 0.983 0.821]; %LasPwrIn values
otherwise
error('Calibration date not recognized!')
end
%do fit and correct input udt to power
fitpar = polyfit(udt_cal,power_cal,3); %assume quadratic
power = polyval(fitpar,udt);
if plotme
figure;plot(udt_cal,power_cal,'*');
xlabel('UDT (V)')
ylabel('Laser Power (mW)')
title(caldate)
linefit(udt_cal,power_cal,1,3);
end
|
github
|
nthallen/keutsch-hcho-master
|
chunker.m
|
.m
|
keutsch-hcho-master/eng/workup/chunker.m
| 548 |
utf_8
|
214091d3c261ea5f11605f0a116267bf
|
% function chunks = chunker(index)
%input is a vector containing indices for all data chunks of a certain type (e.g. cals or zeroes)
%output is a 2-column matrix containing start and stop indices for each chunk
%Edited from the MBO2006 function autoindexer.m.
%070707 GMW
function chunks = chunker(index)
if isempty(index)
chunks = [];
else
chunks = [];%this matrix will contain the indices
j=find(diff(index)~=1);
chunkstart = [index(1);index(j+1)];
chunkstop = [index(j);index(end)];
chunks = [chunkstart chunkstop];
end
|
github
|
altMITgcm/MITgcm-master
|
VERT_FSFB2.m
|
.m
|
MITgcm-master/verification/obcs_ctrl/input_ad/VERT_FSFB2.m
| 2,369 |
utf_8
|
19506cceb9851b2b63996c09e7d4c207
|
function [c2, Psi, G, N2, Pmid] = VERT_FSFB2(N2,Pmid)
%function [c2, Psi, G, N2, Pmid] = VERT_FSFB2(N2,Pmid)
%
% VERT_FSFB.m
%
% Gabriel A. Vecchi - May 12, 1998
%%%%%%%%%%%%%%%%
%
% Solves the discretized wave projection problem
% given the vertical profiles of Temperature, Salinity, Pressure
% and the depth inteval length.
%
% Uses the seawater function sw_bfrq to calculate N2.
%%%%%%%%%%%%%%%%
%
% Arguments:
% T = temperature vector at same depths as salinity and pressure.
% S = salinity vector at same depths as temperature and pressure.
% P = pressure vector at same depths as temperature and salinity.
% Dz = length of depth interval in meters.
%%%%%%%%%%%%%%%%
%
% Returns:
% c2 = vector of square of the wavespeed.
% Psi = matrix of eigenvectors (horizontal velocity structure functions).
% G = matrix of integral of eigenvectors (vertical velocity structure functions).
% N2 = Brunt-Vaisla frequency calculated at the midpoint pressures.
% Pmid = midpoint pressures.
%%%%%%%%%%%%%%%%
% Find N2 - get a M-1 sized vector, at the equator.
%[N2,crap,Pmid] = sw_bfrq(S,T,P,0);
for i = 1:length(N2)
if N2(i) < 0
N2(i) = min(abs(N2));
end;
end;
% bdc: needs equally-spaced depths!
Dz= median(diff(Pmid));
% add a point for the surface
M = length(N2)+1;
% Fill in D - the differential operator matrix.
% Surface (repeat N2 from midpoint depth)
D(1,1) = -2/N2(1);
D(1,2) = 2/N2(1);
% Interior
for i = 2 : M-1,
D(i,i-1) = 1/N2(i-1);
D(i,i) = -1/N2(i-1)-1/N2(i);
D(i,i+1) = 1/N2(i);
end
% Bottom
D(M,M-1) = 2/N2(M-1);
D(M,M) = -2/N2(M-1);
D=-D./(Dz*Dz);
%bdc: no need for A?
% A = eye(M);
% Calculate generalized eigenvalue problem
% bdc: eigs gets top M-1
%[Psi,lambda] = eigs(D,[],M-1);
% use eig:
[Psi,lambda] = eig(D);
% Calculate square of the wavespeed.
c2 = sum(lambda);
c2=1./c2;
Psi = fliplr(Psi);
c2 = fliplr(c2);
for i=1:size(Psi,2)
Psi(:,i) = Psi(:,i)/Psi(1,i);
end
% normalize?
G = INTEGRATOR(M,Dz)*Psi;
function [INT] = INTEGRATOR(M,Del)
%function [INT] = INTEGRATOR(M,Del)
%
% INTEGRATOR.m
%
% Gabriel A. Vecchi - June 7, 1998
%%%%%%%%%%%%%%%%
% Generates and integration matrix.
% Integrates from first point to each point.
%%%%%%%%%%%%%%%%
INT = tril(ones(M));
INT = INT - 0.5*(eye(M));
INT(:,1) = INT(:,1) - 0.5;
INT = INT*Del;
|
github
|
altMITgcm/MITgcm-master
|
sq.m
|
.m
|
MITgcm-master/verification/tutorial_global_oce_latlon/diags_matlab/sq.m
| 396 |
utf_8
|
59792ebeb18f9e9415e48efbc7ad5ce8
|
% sq(A) is similar to squeeze(A) except that elements =0 are set to NaN
%
% sq(A) 0 -> NaN
% sq(A,val1) val1 -> NaN
% sq(A,val1,val2) val1 -> val2
function [A] = sq(B,varargin);
A=squeeze(B);
if nargin>=2
nodata=varargin{1};
else
nodata=0;
end
if nargin==3
newval=varargin{2};
else
newval=NaN;
end
%A(find(A==nodata))=A(find(A==nodata))*NaN;
A(find(A==nodata))=newval;
|
github
|
altMITgcm/MITgcm-master
|
rdmds.m
|
.m
|
MITgcm-master/verification/tutorial_global_oce_latlon/diags_matlab/rdmds.m
| 15,573 |
utf_8
|
ac107b0882b69bd8a4721de82e1f1d24
|
function [AA,itrs,MM] = rdmds(fnamearg,varargin)
% RDMDS Read MITgcmUV meta/data files
%
% A = RDMDS(FNAME)
% A = RDMDS(FNAME,ITER)
% A = RDMDS(FNAME,[ITER1 ITER2 ...])
% A = RDMDS(FNAME,NaN)
% A = RDMDS(FNAME,Inf)
% [A,ITS,M] = RDMDS(FNAME,[...])
% A = RDMDS(FNAME,[...],'rec',RECNUM)
%
% A = RDMDS(FNAME) reads data described by meta/data file format.
% FNAME is a string containing the "head" of the file names.
%
% eg. To load the meta-data files
% T.0000002880.000.000.meta, T.0000002880.000.000.data
% T.0000002880.001.000.meta, T.0000002880.001.000.data
% T.0000002880.002.000.meta, T.0000002880.002.000.data
% T.0000002880.003.000.meta, T.0000002880.003.000.data
% use
% >> A=rdmds('T.0000002880');
% >> size(A)
% ans =
% 64 32 5
% eg. To load a multiple record file
% >> A=rdmds('pickup.0000002880');
% >> size(A)
% ans =
% 64 32 5 61
%
%
% A = RDMDS(FNAME,ITER) reads data described by meta/data file format.
% FNAME is a string containing the "head" of the file name excluding the
% 10-digit iterartion number.
% ITER is a vector of positive integers that will expand to the 10-digit
% number in the file name.
% If ITER=NaN, all iterations will be read.
% If ITER=Inf, the last (highest) iteration will be read.
%
% eg. To repeat above operation
% >> A=rdmds('T',2880);
% eg. To read multiple time steps
% >> A=rdmds('T',[0 1440 2880]);
% eg. To read all time steps
% >> [A,ITS]=rdmds('T',NaN);
% eg. To read the last time step
% >> [A,IT]=rdmds('T',Inf);
% Note: this form can not read files with no iteration count in file name.
%
%
% A = RDMDS(FNAME,[...],'rec',RECNUM) reads individual records from
% multiple record files.
%
% eg. To read a single record from a multi-record file
% >> [A,IT]=rdmds('pickup.ckptA',11);
% eg. To read several records from a multi-record file
% >> [A,IT]=rdmds('pickup',Inf,'rec',[1:5 8 12]);
%
%
% A = RDMDS(FNAME,ITER,MACHINEFORMAT) allows the machine format to be
% A = RDMDS(FNAME,MACHINEFORMAT)
% specified which MACHINEFORMAT is on of the following strings:
% 'n' 'l' 'b' 'd' 'g' 'c' 'a' 's' - see FOPEN for more details
%
AA=[];
itrs=[];
MM=[];
% Default options
ieee='b';
fname=fnamearg;
userecords=0;
recnum=[];
% Check optional arguments
for ind=1:size(varargin,2);
arg=varargin{ind};
if ischar(arg)
if strcmp(arg,'n') | strcmp(arg,'native')
ieee='n';
elseif strcmp(arg,'l') | strcmp(arg,'ieee-le')
ieee='l';
elseif strcmp(arg,'b') | strcmp(arg,'ieee-be')
ieee='b';
elseif strcmp(arg,'c') | strcmp(arg,'cray')
ieee='c';
elseif strcmp(arg,'a') | strcmp(arg,'ieee-le.l64')
ieee='a';
elseif strcmp(arg,'s') | strcmp(arg,'ieee-be.l64')
ieee='s';
elseif strcmp(arg,'rec')
userecords=1;
else
error(['Optional argument ' arg ' is unknown'])
end
else
if userecords==1
recnum=arg;
elseif isempty(itrs)
if isnan(arg)
itrs=scanforfiles(fname);
disp([ sprintf('Reading %i time levels:',size(itrs,2)) sprintf(' %i',itrs) ]);
elseif isinf(arg)
itrs=scanforfiles(fname);
if isempty(itrs)
AA=[];itrs=[];return;
end
disp([ sprintf('Found %i time levels, reading %i',size(itrs,2),itrs(end)) ]);
itrs=itrs(end);
% elseif prod(double(arg>=0)) & prod(double(round(arg)==arg))
% elseif prod(arg>=0) & prod(round(arg)==arg)
elseif min(arg)>=0 & isempty(find(round(arg)~=arg))
if arg>=9999999999
error(sprintf('Argument %i > 9999999999',arg))
end
itrs=arg;
else
error(sprintf('Argument %i must be a positive integer',arg))
end
else
error('Multiple iterations should be specified as a vector')
end
end
end
if isempty(itrs)
itrs=-1;
end
% Loop over each iteration
for iter=1:size(itrs,2);
if itrs(iter)>=0
fname=sprintf('%s.%10.10i',fnamearg,itrs(iter));
end
% Figure out if there is a path in the filename
NS=findstr('/',fname);
if size(NS)>0
Dir=fname(1:NS(end));
else
Dir='./';
end
% Match name of all meta-files
allfiles=dir( sprintf('%s*.meta',fname) );
if size(allfiles,1)==0
disp(sprintf('No files match the search: %s*.meta',fname));
%allow partial reads% error('No files found.')
end
% Loop through allfiles
for j=1:size(allfiles,1);
% Read meta- and data-file
[A,N,M,mG] = localrdmds([Dir allfiles(j).name],ieee,recnum);
%- Merge local Meta file content (M) to MM string:
if j > 0, %- to comment out this block: "if j < 0" (since j is always > 0)
ii=findstr(M,' timeStepNumber');
if isempty(ii), ii1=0; ii2=0;
else ii1=ii; ii2=ii+min(findstr(M(1+ii:end),'];')); end
ii=findstr(M,' timeInterval');
if isempty(ii), jj1=0; jj2=0;
else jj1=ii; jj2=ii+min(findstr(M(1+ii:end),'];')); end
if iter==1 & j==1,
MM=M; ind1=0; ind2=0; is1=ii1; js1=jj1; M3='';
if ii1*jj1 > 0,
%ind1=min(ii1,jj1); ind2=max(ii2,jj2);
%if ii1 < jj1, ii3=ii2+1; jj3=jj1-1;
%else ii3=jj2+1; jj3=ii1-1; end
order=sort([ii1 ii2 jj1 jj2]);
ind1=order(1); ii3=order(2)+1; jj3=order(3)-1; ind2=order(4);
M2=M(ii1:ii2); M4=M(jj1:jj2); M3=M(ii3:jj3);
elseif ii1 > 0,
ind1=ii1; ind2=ii2;
M2=M(ii1:ii2); M4='';
elseif jj1 > 0,
ind1=jj1; ind2=jj2;
M4=M(jj1:jj2); M2='';
end
M5=M(1+ind2:end);
%fprintf(' ii1,ii2 = %i %i ; jj1,jj2= %i %i ;', ii1,ii2, jj1,jj2);
%fprintf(' ii3,jj3= %i %i ; ind1,ind2= %i %i\n',ii3,jj3,ind1,ind2);
%fprintf('M(1:ind1)=%s<\n',M(1:ind1));
%fprintf(' M2=%s<\n',M2);
%fprintf(' M3=%s<\n',M3);
%fprintf(' M4=%s<\n',M4);
%fprintf(' M5=%s<\n',M5);
else
if ii1*jj1 > 0,
order=sort([ii1 ii2 jj1 jj2]);
ind=order(1); ii3=order(2)+1; jj3=order(3)-1; ind2=order(4);
else ind=max(ii1,jj1); ind2=ii2+jj2; end
compar=(ind == ind1); ii=0;
if compar & ind1 == 0, ii=1; compar=strcmp (MM,M); end
if compar & ind1 > 0, ii=2; compar=strncmp(MM,M,ind1) ; end
if compar & ind1 > 0, ii=3; compar=strcmp(M5,M(1+ind2:end)); end
if compar & ii1*jj1 > 0, ii=4; compar=strcmp(M3,M(ii3:jj3)); end
if ~compar,
fprintf('WARNING: Meta file (%s) is different (%i) from 1rst one:\n', ...
allfiles(j).name,ii);
fprintf(' it=%i :MM:%s\n',itrs(1),MM);
fprintf(' it=%i :M :%s\n\n',itrs(iter),M);
elseif ind1 > 0,
if ii1 > 0,
Mj=M(ii1:ii2); ii=findstr(Mj,'['); Mj=Mj(1+ii:end);
% add it-number from Mj to M2 (if different):
if isempty(findstr(M2,Mj)), M2=[deblank(M2(1:end-1)),Mj]; end
end
if jj1 > 0,
Mj=M(jj1:jj2); ii=findstr(Mj,'['); Mj=Mj(1+ii:end);
% add time interval from Mj to M4 (if different):
if isempty(findstr(M4,Mj)), M4=[deblank(M4(1:end-1)),' ;',Mj]; end
end
end
end
% save modifications:
if ind1>0 & j==size(allfiles,1) & iter==size(itrs,2),
if ii1 < jj1, MM=[MM(1:ind1-1),M2,M3,M4,M5];
else MM=[MM(1:ind1-1),M4,M3,M2,M5]; end
end
end
%- put local data file content in global array AA:
bdims=N(1,:);
r0=N(2,:);
rN=N(3,:);
ndims=prod(size(bdims));
if j==1 & iter==1, AA=zeros([bdims size(itrs,2)]); end
if mG(1)==0 & mG(2)==1,
if (ndims == 1)
AA(r0(1):rN(1),iter)=A;
elseif (ndims == 2)
AA(r0(1):rN(1),r0(2):rN(2),iter)=A;
elseif (ndims == 3)
AA(r0(1):rN(1),r0(2):rN(2),r0(3):rN(3),iter)=A;
elseif (ndims == 4)
AA(r0(1):rN(1),r0(2):rN(2),r0(3):rN(3),r0(4):rN(4),iter)=A;
elseif (ndims == 5)
AA(r0(1):rN(1),r0(2):rN(2),r0(3):rN(3),r0(4):rN(4),r0(5):rN(5),iter)=A;
else
error('Dimension of data set is larger than currently coded. Sorry!')
end
elseif (ndims == 1)
AA(r0(1):rN(1),iter)=A;
else
%- to debug: do simple stransfert (with a loop on 2nd index);
% will need to change this later, to improve efficiency:
for i=0:rN(2)-r0(2),
if (ndims == 2)
AA(r0(1)+i*mG(1):rN(1)+i*mG(1),r0(2)+i*mG(2),iter)=A(:,1+i);
elseif (ndims == 3)
AA(r0(1)+i*mG(1):rN(1)+i*mG(1),r0(2)+i*mG(2), ...
r0(3):rN(3),iter)=A(:,1+i,:);
elseif (ndims == 4)
AA(r0(1)+i*mG(1):rN(1)+i*mG(1),r0(2)+i*mG(2), ...
r0(3):rN(3),r0(4):rN(4),iter)=A(:,1+i,:,:);
elseif (ndims == 5)
AA(r0(1)+i*mG(1):rN(1)+i*mG(1),r0(2)+i*mG(2), ...
r0(3):rN(3),r0(4):rN(4),r0(5):rN(5),iter)=A(:,1+i,:,:,:);
else
error('Dimension of data set is larger than currently coded. Sorry!')
end
end
end
end % files
end % iterations
%-------------------------------------------------------------------------------
function [A,N,M,map2glob] = localrdmds(fname,ieee,recnum)
mname=strrep(fname,' ','');
dname=strrep(mname,'.meta','.data');
%- set default mapping from tile to global file:
map2glob=[0 1];
% Read and interpret Meta file
fid = fopen(mname,'r');
if (fid == -1)
error(['File' mname ' could not be opened'])
end
% Scan each line of the Meta file
allstr=' ';
keepgoing = 1;
while keepgoing > 0,
line = fgetl(fid);
if (line == -1)
keepgoing=-1;
else
% Strip out "(PID.TID *.*)" by finding first ")"
%old ind=findstr([line ')'],')'); line=line(ind(1)+1:end);
ind=findstr(line,')');
if size(ind) ~= 0
line=line(ind(1)+1:end);
end
% Remove comments of form //
line=[line,' //']; ind=findstr(line,'//'); line=line(1:ind(1)-1);
% Add to total string (without starting & ending blanks)
while line(1:1) == ' ', line=line(2:end); end
if strncmp(line,'map2glob',8), eval(line);
else allstr=[allstr,deblank(line),' '];
end
end
end
% Close meta file
fclose(fid);
% Strip out comments of form /* ... */
ind1=findstr(allstr,'/*'); ind2=findstr(allstr,'*/');
if size(ind1) ~= size(ind2)
error('The /* ... */ comments are not properly paired')
end
while size(ind1,2) > 0
allstr=[deblank(allstr(1:ind1(1)-1)) allstr(ind2(1)+2:end)];
%allstr=[allstr(1:ind1(1)-1) allstr(ind2(1)+3:end)];
ind1=findstr(allstr,'/*'); ind2=findstr(allstr,'*/');
end
% This is a kludge to catch whether the meta-file is of the
% old or new type. nrecords does not exist in the old type.
nrecords = NaN;
%- store the full string for output:
M=strrep(allstr,'format','dataprec');
% Everything in lower case
allstr=lower(allstr);
% Fix the unfortunate choice of 'format'
allstr=strrep(allstr,'format','dataprec');
% Evaluate meta information
eval(allstr);
N=reshape( dimlist , 3 , prod(size(dimlist))/3 );
rep=[' dimList = [ ',sprintf('%i ',N(1,:)),']'];
if ~isnan(nrecords) & nrecords > 1 & isempty(recnum)
N=[N,[nrecords 1 nrecords]'];
elseif ~isempty(recnum) & recnum>nrecords
error('Requested record number is higher than the number of available records')
end
%- make "dimList" shorter (& fit output array size) in output "M":
pat=' dimList = \[(\s*\d+\,?)*\s*\]';
M=regexprep(M,pat,rep);
% and remove double space within sq.brakets:
ind1=findstr(M,'['); ind2=findstr(M,']');
if length(ind1) == length(ind2),
for i=length(ind1):-1:1, if ind1(i) < ind2(i),
M=[M(1:ind1(i)),regexprep(M(ind1(i)+1:ind2(i)-1),'(\s+)',' '),M(ind2(i):end)];
end; end
else error('The [ ... ] brakets are not properly paired')
end
if isempty(recnum)
recnum=1;
end
if isnan(nrecords)
% This is the old 'meta' method that used sequential access
A=allstr;
% Open data file
fid=fopen(dname,'r',ieee);
% Read record size in bytes
recsz=fread(fid,1,'uint32');
ldims=N(3,:)-N(2,:)+1;
numels=prod(ldims);
rat=recsz/numels;
if rat == 4
A=fread(fid,numels,'real*4');
elseif rat == 8
A=fread(fid,numels,'real*8');
else
sprintf(' Implied size in meta-file = %d', numels )
sprintf(' Record size in data-file = %d', recsz )
error('Ratio between record size and size in meta-file inconsistent')
end
erecsz=fread(fid,1,'uint32');
if erecsz ~= recsz
sprintf('WARNING: Record sizes at beginning and end of file are inconsistent')
end
fclose(fid);
A=reshape(A,ldims);
else
% This is the new MDS format that uses direct access
ldims=N(3,:)-N(2,:)+1;
for r=1:size(recnum(:),1);
if dataprec == 'float32'
A(:,r)=myrdda(dname,ldims,recnum(r),'real*4',ieee);
elseif dataprec == 'float64'
A(:,r)=myrdda(dname,ldims,recnum(r),'real*8',ieee);
else
error(['Unrecognized format in meta-file = ' format]);
end
end
A=reshape(A,[ldims size(recnum(:),1)]);
if size(recnum(:),1)>1
N(1,end+1)=size(recnum(:),1);
N(2,end)=1;
N(3,end)=size(recnum(:),1);
end
end
%-------------------------------------------------------------------------------
% result = RDDA( file, dim, irec [options] )
%
% This routine reads the irec'th record of shape 'dim' from the
% direct-access binary file (float or double precision) 'file'.
%
% Required arguments:
%
% file - string - name of file to read from
% dim - vector - dimensions of the file records and the resulting array
% irec - integer - record number in file in which to write data
%
% Optional arguments (must appear after the required arguments):
% prec - string - precision of storage in file. Default = 'real*8'.
% ieee - string - IEEE bit-wise representation in file. Default = 'b'.
%
% 'prec' may take the values:
% 'real*4' - floating point, 32 bits.
% 'real*8' - floating point, 64 bits - the efault.
%
% 'ieee' may take values:
% 'ieee-be' or 'b' - IEEE floating point with big-endian
% byte ordering - the default
% 'ieee-le' or 'l' - IEEE floating point with little-endian
% byte ordering
% 'native' or 'n' - local machine format
% 'cray' or 'c' - Cray floating point with big-endian
% byte ordering
% 'ieee-le.l64' or 'a' - IEEE floating point with little-endian
% byte ordering and 64 bit long data type
% 'ieee-be.l64' or 's' - IEEE floating point with big-endian byte
% ordering and 64 bit long data type.
%
% eg. T=rdda('t.data',[64 64 32],1);
% T=rdda('t.data',[256],4,'real*4');
% T=rdda('t.data',[128 64],2,'real*4','b');
function [arr] = myrdda(file,N,k,varargin)
% Defaults
WORDLENGTH=8;
rtype='real*8';
ieee='b';
% Check optional arguments
args=char(varargin);
while (size(args,1) > 0)
if deblank(args(1,:)) == 'real*4'
WORDLENGTH=4;
rtype='real*4';
elseif deblank(args(1,:)) == 'real*8'
WORDLENGTH=8;
rtype='real*8';
elseif deblank(args(1,:)) == 'n' | deblank(args(1,:)) == 'native'
ieee='n';
elseif deblank(args(1,:)) == 'l' | deblank(args(1,:)) == 'ieee-le'
ieee='l';
elseif deblank(args(1,:)) == 'b' | deblank(args(1,:)) == 'ieee-be'
ieee='b';
elseif deblank(args(1,:)) == 'c' | deblank(args(1,:)) == 'cray'
ieee='c';
elseif deblank(args(1,:)) == 'a' | deblank(args(1,:)) == 'ieee-le.l64'
ieee='a';
elseif deblank(args(1,:)) == 's' | deblank(args(1,:)) == 'ieee-be.l64'
ieee='s';
else
error(['Optional argument ' args(1,:) ' is unknown'])
end
args=args(2:end,:);
end
nnn=prod(N);
[fid mess]=fopen(file,'r',ieee);
if fid == -1
error('Error while opening file:\n%s',mess)
end
st=fseek(fid,nnn*(k-1)*WORDLENGTH,'bof');
if st ~= 0
mess=ferror(fid);
error('There was an error while positioning the file pointer:\n%s',mess)
end
[arr count]=fread(fid,nnn,rtype);
if count ~= nnn
error('Not enough data was available to be read: off EOF?')
end
st=fclose(fid);
%arr=reshape(arr,N);
%
function [itrs] = scanforfiles(fname)
itrs=[];
allfiles=dir([fname '.*.001.001.meta']);
if isempty(allfiles)
allfiles=dir([fname '.*.meta']);
ioff=0;
else
ioff=8;
end
for k=1:size(allfiles,1);
hh=allfiles(k).name;
itrs(k)=str2num( hh(end-14-ioff:end-5-ioff) );
end
itrs=sort(itrs);
|
github
|
altMITgcm/MITgcm-master
|
mit_getparm.m
|
.m
|
MITgcm-master/verification/tutorial_global_oce_latlon/diags_matlab/mit_getparm.m
| 2,288 |
utf_8
|
fc7cff3c2b1d1b5330d556f335f072ef
|
function y = mit_getparm(fname,pname);
%function y = mit_getparm(fname,pname);
y = [];
[fp, msg] = fopen(fname,'r');
if fp > 0
str{1} = [];
notfound = 0;
while isempty(mystrfind(str{1},pname))
str{1} = fgetl(fp);
if ~ischar(str{1}); % this catches the end of file (not very clean)
notfound = 1;
break;
end
% clear again if commented
if ~isempty(mystrfind(str{1},'#'))
str{1} = [];
end
end
if notfound
disp(['Warning: ' pname ' not found in ' fname])
y=[];
% disp([' setting ' pname ' to zero'])
% y = 0;
else
teststr = [];
% find the termination of parameter pname
% (next line with an '=' sign
% or with a namelist termination character '&' or '/')
n = 1;
while ( isempty(mystrfind(teststr,'=')) & ...
isempty(mystrfind(teststr,'&')) & ...
isempty(mystrfind(teststr,'/')) )
n = n + 1;
teststr = fgetl(fp);
str{n} = teststr;
if ~ischar(teststr); break; end
end
eqind = findstr(str{1},'=');
y = str{1}(eqind+1:end-1);
% check whether it is a string in quotes or something else
quotes = findstr(y,'''');
if ~isempty(quotes)
y(quotes(2):end) = [];
y(1:quotes(1)) = [];
else
if ~( strcmpi(y,'.TRUE.') | strcmpi(y,'.FALSE.') )
y = convert_str2num(str{1}(eqind+1:end-1));
for k=2:n-1
y = [y; convert_str2num(str{k}(eqind+1:end-1))];
end
% $$$ y = str2num(str{1}(eqind+1:end-1))';
% $$$ for k=2:n-1
% $$$ y = [y; str2num(str{k}(eqind+1:end-1))'];
% $$$ end
end
end
end
fclose(fp);
else
error([fname ' could not be opened: ' msg])
end
return
function y = convert_str2num(str)
% take care of the n*value format
stars = findstr(str,'*');
if isempty(stars)
y = str2num(str)';
else
if length(stars)==1
y=repmat(str2num(str(stars+1:end)),[str2num(str(1:stars-1)) 1]);
else
warning('The format n*x1,m*x2, ... cannot be handled')
% $$$ for k=1:length(stars)
% $$$ % find the beginnin and termination of the set
% $$$ end
end
end
return
function [ind] = mystrfind(str,pattern)
if length(pattern) > length(str)
ind = [];
return
else
ind = findstr(str,pattern);
end
|
github
|
altMITgcm/MITgcm-master
|
rdmeta.m
|
.m
|
MITgcm-master/verification/tutorial_global_oce_latlon/diags_matlab/rdmeta.m
| 8,213 |
utf_8
|
1474707bccd022cacade050a0d58558b
|
function [AA] = rdmds(fname,varargin)
%
% Read MITgcmUV Meta/Data files
%
% A = RDMDS(FNAME) reads data described by meta/data file format.
% FNAME is a string containing the "head" of the file names.
%
% eg. To load the meta-data files
% T.0000002880.000.000.meta, T.0000002880.000.000.data
% T.0000002880.001.000.meta, T.0000002880.001.000.data
% T.0000002880.002.000.meta, T.0000002880.002.000.data
% T.0000002880.003.000.meta, T.0000002880.003.000.data
% use
% >> A=rdmds('T.0000002880');
%
% A = RDMDS(FNAME,MACHINEFORMAT) allows the machine format to be specified
% which MACHINEFORMAT is on of the following strings:
%
% 'native' or 'n' - local machine format - the default
% 'ieee-le' or 'l' - IEEE floating point with little-endian
% byte ordering
% 'ieee-be' or 'b' - IEEE floating point with big-endian
% byte ordering
% 'vaxd' or 'd' - VAX D floating point and VAX ordering
% 'vaxg' or 'g' - VAX G floating point and VAX ordering
% 'cray' or 'c' - Cray floating point with big-endian
% byte ordering
% 'ieee-le.l64' or 'a' - IEEE floating point with little-endian
% byte ordering and 64 bit long data type
% 'ieee-be.l64' or 's' - IEEE floating point with big-endian byte
% ordering and 64 bit long data type.
% Default options
ieee='b';
% Check optional arguments
args=char(varargin);
while (size(args,1) > 0)
if deblank(args(1,:)) == 'n' | deblank(args(1,:)) == 'native'
ieee='n';
elseif deblank(args(1,:)) == 'l' | deblank(args(1,:)) == 'ieee-le'
ieee='l';
elseif deblank(args(1,:)) == 'b' | deblank(args(1,:)) == 'ieee-be'
ieee='b';
elseif deblank(args(1,:)) == 'c' | deblank(args(1,:)) == 'cray'
ieee='c';
elseif deblank(args(1,:)) == 'a' | deblank(args(1,:)) == 'ieee-le.l64'
ieee='a';
elseif deblank(args(1,:)) == 's' | deblank(args(1,:)) == 'ieee-be.l64'
ieee='s';
else
error(['Optional argument ' args(1,:) ' is unknown'])
end
args=args(2:end,:);
end
% Match name of all meta-files
eval(['ls ' fname '*.meta;']);
allfiles=ans;
% Beginning and end of strings
Iend=findstr(allfiles,'.meta')+4;
Ibeg=[1 Iend(1:end-1)+2];
% Loop through allfiles
for j=1:prod(size(Ibeg)),
% Read meta- and data-file
[A,N] = localrdmds(allfiles(Ibeg(j):Iend(j)),ieee);
bdims=N(1,:);
r0=N(2,:);
rN=N(3,:);
ndims=prod(size(bdims));
if (ndims == 1)
AA(r0(1):rN(1))=A;
elseif (ndims == 2)
AA(r0(1):rN(1),r0(2):rN(2))=A;
elseif (ndims == 3)
AA(r0(1):rN(1),r0(2):rN(2),r0(3):rN(3))=A;
elseif (ndims == 4)
AA(r0(1):rN(1),r0(2):rN(2),r0(3):rN(3),r0(4):rN(4))=A;
else
error('Dimension of data set is larger than currently coded. Sorry!')
end
end
%-------------------------------------------------------------------------------
function [A,N] = localrdmds(fname,ieee)
mname=strrep(fname,' ','');
dname=strrep(mname,'.meta','.data');
% Read and interpret Meta file
fid = fopen(mname,'r');
if (fid == -1)
error(['File' mname ' could not be opened'])
end
% Scan each line of the Meta file
allstr=' ';
keepgoing = 1;
while keepgoing > 0,
line = fgetl(fid);
if (line == -1)
keepgoing=-1;
else
% Strip out "(PID.TID *.*)" by finding first ")"
%old ind=findstr([line ')'],')'); line=line(ind(1)+1:end);
ind=findstr(line,')');
if size(ind) ~= 0
line=line(ind(1)+1:end);
end
% Remove comments of form //
line=[line ' //']; ind=findstr(line,'//'); line=line(1:ind(1)-1);
% Add to total string
allstr=[allstr line];
end
end
% Close meta file
fclose(fid);
% Strip out comments of form /* ... */
ind1=findstr(allstr,'/*'); ind2=findstr(allstr,'*/');
if size(ind1) ~= size(ind2)
error('The /* ... */ comments are not properly paired')
end
while size(ind1,2) > 0
allstr=[allstr(1:ind1(1)-1) allstr(ind2(1)+3:end)];
ind1=findstr(allstr,'/*'); ind2=findstr(allstr,'*/');
end
% This is a kludge to catch whether the meta-file is of the
% old or new type. nrecords does not exist in the old type.
nrecords = -987;
% Everything in lower case
allstr=lower(allstr);
% Fix the unfortunate choice of 'format'
allstr=strrep(allstr,'format','dataprec');
% Evaluate meta information
eval(allstr);
N=reshape( dimlist , 3 , prod(size(dimlist))/3 );
if nrecords == -987
% This is the old 'meta' method that used sequential access
A=allstr;
% Open data file
fid=fopen(dname,'r',ieee);
% Read record size in bytes
recsz=fread(fid,1,'uint32');
ldims=N(3,:)-N(2,:)+1;
numels=prod(ldims);
rat=recsz/numels;
if rat == 4
A=fread(fid,numels,'real*4');
elseif rat == 8
A=fread(fid,numels,'real*8');
else
sprintf(' Implied size in meta-file = %d', numels )
sprintf(' Record size in data-file = %d', recsz )
error('Ratio between record size and size in meta-file inconsistent')
end
erecsz=fread(fid,1,'uint32');
if erecsz ~= recsz
sprintf('WARNING: Record sizes at beginning and end of file are inconsistent')
end
fclose(fid);
A=reshape(A,ldims);
else
% This is the new MDS format that uses direct access
ldims=N(3,:)-N(2,:)+1;
if dataprec == 'float32'
A=myrdda(dname,ldims,1,'real*4',ieee);
elseif dataprec == 'float64'
A=myrdda(dname,ldims,1,'real*8',ieee);
else
error(['Unrecognized dataprec in meta-file = ' dataprec]);
end
end
%-------------------------------------------------------------------------------
% result = RDDA( file, dim, irec [options] )
%
% This routine reads the irec'th record of shape 'dim' from the
% direct-access binary file (float or double precision) 'file'.
%
% Required arguments:
%
% file - string - name of file to read from
% dim - vector - dimensions of the file records and the resulting array
% irec - integer - record number in file in which to write data
%
% Optional arguments (must appear after the required arguments):
% prec - string - precision of storage in file. Default = 'real*8'.
% ieee - string - IEEE bit-wise representation in file. Default = 'b'.
%
% 'prec' may take the values:
% 'real*4' - floating point, 32 bits.
% 'real*8' - floating point, 64 bits - the efault.
%
% 'ieee' may take values:
% 'ieee-be' or 'b' - IEEE floating point with big-endian
% byte ordering - the default
% 'ieee-le' or 'l' - IEEE floating point with little-endian
% byte ordering
% 'native' or 'n' - local machine format
% 'cray' or 'c' - Cray floating point with big-endian
% byte ordering
% 'ieee-le.l64' or 'a' - IEEE floating point with little-endian
% byte ordering and 64 bit long data type
% 'ieee-be.l64' or 's' - IEEE floating point with big-endian byte
% ordering and 64 bit long data type.
%
% eg. T=rdda('t.data',[64 64 32],1);
% T=rdda('t.data',[256],4,'real*4');
% T=rdda('t.data',[128 64],2,'real*4','b');
function [arr] = myrdda(file,N,k,varargin)
% Defaults
WORDLENGTH=8;
rtype='real*8';
ieee='b';
% Check optional arguments
args=char(varargin);
while (size(args,1) > 0)
if deblank(args(1,:)) == 'real*4'
WORDLENGTH=4;
rtype='real*4';
elseif deblank(args(1,:)) == 'real*8'
WORDLENGTH=8;
rtype='real*8';
elseif deblank(args(1,:)) == 'n' | deblank(args(1,:)) == 'native'
ieee='n';
elseif deblank(args(1,:)) == 'l' | deblank(args(1,:)) == 'ieee-le'
ieee='l';
elseif deblank(args(1,:)) == 'b' | deblank(args(1,:)) == 'ieee-be'
ieee='b';
elseif deblank(args(1,:)) == 'c' | deblank(args(1,:)) == 'cray'
ieee='c';
elseif deblank(args(1,:)) == 'a' | deblank(args(1,:)) == 'ieee-le.l64'
ieee='a';
elseif deblank(args(1,:)) == 's' | deblank(args(1,:)) == 'ieee-be.l64'
ieee='s';
else
error(['Optional argument ' args(1,:) ' is unknown'])
end
args=args(2:end,:);
end
nnn=prod(N);
[fid mess]=fopen(file,'r',ieee);
if fid == -1
error('Error while opening file:\n%s',mess)
end
st=fseek(fid,nnn*(k-1)*WORDLENGTH,'bof');
if st ~= 0
mess=ferror(fid);
error('There was an error while positioning the file pointer:\n%s',mess)
end
[arr count]=fread(fid,nnn,rtype);
if count ~= nnn
error('Not enough data was available to be read: off EOF?')
end
st=fclose(fid);
arr=reshape(arr,N);
|
github
|
altMITgcm/MITgcm-master
|
pcol.m
|
.m
|
MITgcm-master/verification/tutorial_global_oce_latlon/diags_matlab/pcol.m
| 1,497 |
utf_8
|
a292554987c9d7d3edd0a8a6622c1754
|
% Similar to pcolor except that pcol() doesn't drop the last column
% or row of data (ie. doesn't interpolated). It uses the shading flat
% method by default.
%
% See also PCOLOR, IMAGESC
function [hh] = pcol(varargin);
%cmap=colormap;
%if cmap(size(cmap,1),:)==[0 0 0]
%else
% if sum(sum(isnan(data)))~=0
% colormap( [colormap' [0 0 0]']')
% end
%end
% Scale data to fit colormap
%clim=[min(min(data)) max(max(data))];
%data=(data-clim(1))/(clim(2)-clim(1))*(size(colormap,1)-1)+1;
%data(find(isnan(data)==1))=size(colormap,1)+1;
if nargin == 1
%hh=imagesc(data);
data=varargin{1};
pcolor(data([1:end 1],[1:end 1]))
% $$$ xtick = get(gca,'XTick')';
% $$$ ytick = get(gca,'YTick')';
% $$$ xt=xtick+.5;
% $$$ yt=ytick+.5;
else
%hh=imagesc(varargin{1:2},data);
x=varargin{1}(:);
y=varargin{2}(:);
data=varargin{3};
pcolor([x' 2*x(end)-x(end-1)],...
[y' 2*y(end)-y(end-1)],...
data([1:end 1],[1:end 1]))
% $$$ dx = diff(x);
% $$$ dy = diff(y);
% $$$ xtick = get(gca,'XTick'); %[x(1:end-1)+.5*dx; x(end)+.5*dx(end)];
% $$$ ytick = get(gca,'YTick'); %[y(1:end-1)+.5*dy; y(end)+.5*dy(end)];
% $$$ xt = interp1(x,[x(1:end-1)+.5*dx; x(end)+.5*dx(end)],xtick);
% $$$ yt = interp1(y,[y(1:end-1)+.5*dy; y(end)+.5*dy(end)],ytick);
end
%set(gca,'YDir','normal')
% fix tickmarks to emulate imagesc behavior
% $$$ dx = diff(x);
% $$$ dy = diff(y);
% $$$ set(gca,'XTick',xt,'XTickLabel',xtick)
% $$$ set(gca,'YTick',yt,'YTickLabel',ytick)
set(gca,'Layer','top')
shading flat;
|
github
|
altMITgcm/MITgcm-master
|
ncep2global_ocean.m
|
.m
|
MITgcm-master/verification/tutorial_global_oce_latlon/diags_matlab/ncep2global_ocean.m
| 6,746 |
utf_8
|
821818da9e42e4b9a02bbb53c9b88afb
|
function ncep2global_ocean
% function ncep2global_ocean
% read various fluxes, adds them up to have net heat flux and net
% freshwater flux (E-P only)
% interpolates the fluxes onto 90x40 grid of global_ocean.90x40x15
%
% constants
ql_evap = 2.5e6; % latent heat due to evaporation
rho_fresh = 1000; % density of fresh water
onemonth = 60*60*24*30;
% grid parameter
grd = mit_loadgrid(DIRECTORY WHERE THE GRID INFORMATION IS HELD ...
(XC*, YC*, HFAC* etc.));
lonc = grd.lonc;
latc = grd.latc;
cmask = grd.cmask; % 1=wet point, NaN = dry point
rac = grd.rac;
bdir = DIRECTORY WHERE THE NCEP DATA FILES ARE STORED;
% taux
ncload(fullfile(bdir,'ncep_taux_monthly.cdf'),'taux','X','Y','T')
% tauy
ncload(fullfile(bdir,'ncep_tauy_monthly.cdf'),'tauy')
% there appears to be a different east west convention in the data
taux = - taux;
tauy = - tauy;
% qnet
ncload(fullfile(bdir,'ncep_netsolar_monthly.cdf'),'solr')
ncload(fullfile(bdir,'ncep_netlw_monthly.cdf'),'lwflx') % long wave radiation
ncload(fullfile(bdir,'ncep_latent_monthly.cdf'),'heat_flux');
lhflx = heat_flux;
ncload(fullfile(bdir,'ncep_sensible_monthly.cdf'),'heat_flux');
shflx = heat_flux;
% emp
ncload(fullfile(bdir,'ncep_precip_monthly.cdf'),'prate')
ncload(fullfile(bdir,'ncep_runoff_monthly.cdf'),'runoff')
evap = lhflx/ql_evap/rho_fresh; % evaporation rate estimated from latent
% heat flux
precip = prate/rho_fresh; % change the units
% add the fields
% net heat flux: sum of solar radiation, long wave flux, latent heat flux,
% and sensible heat flux
qnet = solr + lwflx + lhflx + shflx;
% net fresh water flux: difference between evaporation and precipitation
emp = evap - precip;
% substract the runoff (doesn't lead anywhere, unfortunately)
empmr = emp - change(runoff,'==',NaN,0)/rho_fresh/onemonth;
runoff(find(isnan(runoff)))=0;
empmr = emp - runoff/rho_fresh/onemonth;
% interpolate the three fields onto 90x40 grid
ir = interp2global(X,Y,lonc,latc); % this sets up the
% interpolator ir!
for k = 1:length(T);
tauxg(:,:,k) = interp2global(X,Y,squeeze(taux(k,:,:)),lonc,latc,ir);
tauyg(:,:,k) = interp2global(X,Y,squeeze(tauy(k,:,:)),lonc,latc,ir);
qnetg(:,:,k) = interp2global(X,Y,squeeze(qnet(k,:,:)),lonc,latc,ir);
empg(:,:,k) = interp2global(X,Y,squeeze(emp(k,:,:)),lonc,latc,ir);
empmrg(:,:,k) = interp2global(X,Y,squeeze(empmr(k,:,:)),lonc,latc,ir);
end
% apply landmask
for k = 1:length(T);
tauxg(:,:,k) = tauxg(:,:,k).*cmask(:,:,1);
tauyg(:,:,k) = tauyg(:,:,k).*cmask(:,:,1);
qnetg(:,:,k) = qnetg(:,:,k).*cmask(:,:,1);
empg(:,:,k) = empg(:,:,k).*cmask(:,:,1);
empmrg(:,:,k) = empmrg(:,:,k).*cmask(:,:,1);
end
% balance the fluxes
effrac = rac.*cmask(:,:,1);
mqnet = mit_mean(qnetg,effrac);
qnetb = qnetg-mean(mqnet);
memp = mit_mean(empg,effrac);
empb = empg-mean(memp);
mempmr = mit_mean(empmrg,effrac);
empmrb = empmrg-mean(mempmr);
% apply the landmasks one more time (because we have added something
% to what should have been zero == land)
for k = 1:length(T);
qnetb(:,:,k) = qnetb(:,:,k).*smask;
empb(:,:,k) = empb(:,:,k).*smask;
empmrb(:,:,k) = empmrb(:,:,k).*smask;
end
% save the fields
acc = 'real*4';
mit_writefield('ncep_taux.bin',change(tauxg,'==',NaN,0),acc);
mit_writefield('ncep_tauy.bin',change(tauyg,'==',NaN,0),acc);
mit_writefield('ncep_qnet.bin',change(qnetb,'==',NaN,0),acc);
mit_writefield('ncep_emp.bin',change(empb,'==',NaN,0),acc);
mit_writefield('ncep_empmr.bin',change(empmrb,'==',NaN,0),acc);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Y = mit_mean(X,area);
%function Y = mit_mean(X,area);
na = ndims(area);
n = ndims(X);
full_area = nansum(area(:));
if n == 2 & na == 2
[nx ny] = size(X);
Xa = X.*area;
Y = nansum(Xa(:))/full_area;
elseif n == 3 & na == 2
[nx ny nt] = size(X);
Xa = X.*repmat(area,[1 1 nt]);
for k=1:nt
Y(k) = nansum(nansum(Xa(:,:,k)))/full_area;
end
elseif n == 3 & na == 3
[nx ny nz] = size(X);
Xa = X.*area;
Y = nansum(Xa(:))/full_area;
else
error('X and area have to have consistent dimensions')
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function count = mit_writefield(fname,h,accuracy)
%function count = mit_writefield(fname,h,accuracy)
ieee='ieee-be';
[fid message] = fopen(fname,'w',ieee);
if fid <= 0
error([message ', filename: ', [fname]])
end
clear count
dims = size(h);
if length(dims) == 2
count = fwrite(fid,h,accuracy);
elseif length(dims) == 3
for k=1:dims(3);
count(k) = fwrite(fid,squeeze(h(:,:,k)),accuracy);
end
elseif length(dims) == 4
for kt=1:dims(4)
for k=1:dims(3)
count(k,kt) = fwrite(fid,squeeze(h(:,:,k,kt)),accuracy);
end
end
end
fclose(fid);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [zi] = interp2global(varargin);
%function [zi] = interp2global(x,y,z,xi,yi,ir);
if nargin == 4
[xx yy] = meshgrid(varargin{1},varargin{2});
xx = reshape(xx,prod(size(xx)),1);
yy = reshape(yy,prod(size(yy)),1);
[xxi yyi] = meshgrid(varargin{3},varargin{4});
xxv = reshape(xxi,prod(size(xxi)),1);
yyv = reshape(yyi,prod(size(yyi)),1);
% create map
if ~exist('ir','var');
r = 230e3; %m
for k = 1:length(xxv);
% find all points within radius r
radius = lonlat2dist(xxv(k),yyv(k),xx,yy);
ir{k} = find(radius<=r);
end
end
zi = ir;
else
% zi = interp2_global(x,y,z,ix,iy','spline')';
z = varargin{3};
xi = varargin{4};
yi = varargin{5};
[xxi yyi] = meshgrid(varargin{4},varargin{5});
ir = varargin{6};
zzv = repmat(NaN,length(ir),1);
% interpolate
for k = 1:length(ir);
% find all points within radius r
zzv(k) = mean(z(ir{k}));
end
zi = reshape(zzv,size(xxi))';
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function r = lonlat2dist(lon,lat,lons,lats)
%function r = lonlat2dist(lon,lat,lons,lats)
%
% returns distance (in meters) between postion (lon,lat) and positions
% (lons,lats) on the earth (sphere). length(r) = length(lons)
earth=6371000;
deg2rad=pi/180;
nx=length(lon);
lt = deg2rad*lat;
ln = deg2rad*lon;
lts = deg2rad*lats;
lns = deg2rad*lons;
alpha = ...
acos( ( cos(lt)*cos(lts) ).*cos(ln-lns) ...
+ ( sin(lt)*sin(lts) ) );
r = earth*abs(alpha');
return
|
github
|
altMITgcm/MITgcm-master
|
rdda.m
|
.m
|
MITgcm-master/verification/advect_cs/input/rdda.m
| 2,915 |
utf_8
|
b7991cf916c2f5ec04c925ee65ba6ebd
|
% result = RDDA( file, dim, irec [options] )
%
% This routine reads the irec'th record of shape 'dim' from the
% direct-access binary file (float or double precision) 'file'.
%
% Required arguments:
%
% file - string - name of file to read from
% dim - vector - dimensions of the file records and the resulting array
% irec - integer - record number in file in which to write data
%
% Optional arguments (must appear after the required arguments):
% prec - string - precision of storage in file. Default = 'real*8'.
% ieee - string - IEEE bit-wise representation in file. Default = 'b'.
%
% 'prec' may take the values:
% 'real*4' - floating point, 32 bits.
% 'real*8' - floating point, 64 bits - the efault.
%
% 'ieee' may take values:
% 'ieee-be' or 'b' - IEEE floating point with big-endian
% byte ordering - the default
% 'ieee-le' or 'l' - IEEE floating point with little-endian
% byte ordering
% 'native' or 'n' - local machine format
% 'cray' or 'c' - Cray floating point with big-endian
% byte ordering
% 'ieee-le.l64' or 'a' - IEEE floating point with little-endian
% byte ordering and 64 bit long data type
% 'ieee-be.l64' or 's' - IEEE floating point with big-endian byte
% ordering and 64 bit long data type.
%
% eg. T=rdda('t.data',[64 64 32],1);
% T=rdda('t.data',[256],4,'real*4');
% T=rdda('t.data',[128 64],2,'real*4','b');
function [arr] = rdda(file,N,k,varargin)
% Defaults
WORDLENGTH=8;
rtype='real*8';
ieee='b';
% Check optional arguments
args=char(varargin);
while (size(args,1) > 0)
if deblank(args(1,:)) == 'real*4'
WORDLENGTH=4;
rtype='real*4';
elseif deblank(args(1,:)) == 'real*8'
WORDLENGTH=8;
rtype='real*8';
elseif deblank(args(1,:)) == 'n' | deblank(args(1,:)) == 'native'
ieee='n';
elseif deblank(args(1,:)) == 'l' | deblank(args(1,:)) == 'ieee-le'
ieee='l';
elseif deblank(args(1,:)) == 'b' | deblank(args(1,:)) == 'ieee-be'
ieee='b';
elseif deblank(args(1,:)) == 'c' | deblank(args(1,:)) == 'cray'
ieee='c';
elseif deblank(args(1,:)) == 'a' | deblank(args(1,:)) == 'ieee-le.l64'
ieee='a';
elseif deblank(args(1,:)) == 's' | deblank(args(1,:)) == 'ieee-be.l64'
ieee='s';
else
sprintf(['Optional argument ' args(1,:) ' is unknown'])
return
end
args=args(2:end,:);
end
nnn=prod(N);
[fid mess]=fopen(file,'r',ieee);
if fid == -1
sprintf('Error while opening file:\n%s',mess)
arr=0;
return
end
st=fseek(fid,nnn*(k-1)*WORDLENGTH,'bof');
if st ~= 0
mess=ferror(fid);
sprintf('There was an error while positioning the file pointer:\n%s',mess)
arr=0;
return
end
[arr count]=fread(fid,nnn,rtype);
if count ~= nnn
sprintf('Not enough data was available to be read: off EOF?')
arr=0;
return
end
st=fclose(fid);
arr=reshape(arr,N);
|
github
|
altMITgcm/MITgcm-master
|
inpaint_nans.m
|
.m
|
MITgcm-master/utils/matlab/inpaint_nans.m
| 12,366 |
utf_8
|
b1af604b26fc4537e04313983bb36eca
|
function B=inpaint_nans(A,method)
% inpaint_nans: in-paints over nans in an array
% usage: B=inpaint_nans(A)
%
% solves approximation to one of several pdes to
% interpolate and extrapolate holes
%
% Written by John D'Errico ([email protected])
%
% arguments (input):
% A - nxm array with some NaNs to be filled in
%
% method - (OPTIONAL) scalar numeric flag - specifies
% which approach (or physical metaphor to use
% for the interpolation.) All methods are capable
% of extrapolation, some are better than others.
% There are also speed differences, as well as
% accuracy differences for smooth surfaces.
%
% methods {0,1,2} use a simple plate metaphor
% methods {3} use a better plate equation,
% but will be slower
% methods 4 use a spring metaphor
%
% method == 0 --> (DEFAULT) see method 1, but
% this method does not build as large of a
% linear system in the case of only a few
% NaNs in a large array.
% Extrapolation behavior is linear.
%
% method == 1 --> simple approach, applies del^2
% over the entire array, then drops those parts
% of the array which do not have any contact with
% NaNs. Uses a least squares approach, but it
% does not touch existing points.
% In the case of small arrays, this method is
% quite fast as it does very little extra work.
% Extrapolation behavior is linear.
%
% method == 2 --> uses del^2, but solving a direct
% linear system of equations for nan elements.
% This method will be the fastest possible for
% large systems since it uses the sparsest
% possible system of equations. Not a least
% squares approach, so it may be least robust
% to noise on the boundaries of any holes.
% This method will also be least able to
% interpolate accurately for smooth surfaces.
% Extrapolation behavior is linear.
%
% method == 3 --+ See method 0, but uses del^4 for
% the interpolating operator. This may result
% in more accurate interpolations, at some cost
% in speed.
%
% method == 4 --+ Uses a spring metaphor. Assumes
% springs (with a nominal length of zero)
% connect each node with every neighbor
% (horizontally, vertically and diagonally)
% Since each node tries to be like its neighbors,
% extrapolation is as a constant function where
% this is consistent with the neighboring nodes.
%
%
% arguments (output):
% B - nxm array with NaNs replaced
% I always need to know which elements are NaN,
% and what size the array is for any method
[n,m]=size(A);
nm=n*m;
k=isnan(A(:));
% list the nodes which are known, and which will
% be interpolated
nan_list=find(k);
known_list=find(~k);
% how many nans overall
nan_count=length(nan_list);
% convert NaN indices to (r,c) form
% nan_list==find(k) are the unrolled (linear) indices
% (row,column) form
[nr,nc]=ind2sub([n,m],nan_list);
% both forms of index in one array:
% column 1 == unrolled index
% column 2 == row index
% column 3 == column index
nan_list=[nan_list,nr,nc];
% supply default method
if (nargin<2)|isempty(method)
method = 0;
elseif ~ismember(method,0:4)
error 'If supplied, method must be one of: {0,1,2,3,4}.'
end
% for different methods
switch method
case 0
% The same as method == 1, except only work on those
% elements which are NaN, or at least touch a NaN.
% horizontal and vertical neighbors only
talks_to = [-1 0;0 -1;1 0;0 1];
neighbors_list=identify_neighbors(n,m,nan_list,talks_to);
% list of all nodes we have identified
all_list=[nan_list;neighbors_list];
% generate sparse array with second partials on row
% variable for each element in either list, but only
% for those nodes which have a row index > 1 or < n
L = find((all_list(:,2) > 1) & (all_list(:,2) < n));
nl=length(L);
if nl>0
fda=sparse(repmat(all_list(L,1),1,3), ...
repmat(all_list(L,1),1,3)+repmat([-1 0 1],nl,1), ...
repmat([1 -2 1],nl,1),nm,nm);
else
fda=spalloc(n*m,n*m,size(all_list,1)*5);
end
% 2nd partials on column index
L = find((all_list(:,3) > 1) & (all_list(:,3) < m));
nl=length(L);
if nl>0
fda=fda+sparse(repmat(all_list(L,1),1,3), ...
repmat(all_list(L,1),1,3)+repmat([-n 0 n],nl,1), ...
repmat([1 -2 1],nl,1),nm,nm);
end
% eliminate knowns
rhs=-fda(:,known_list)*A(known_list);
k=find(any(fda(:,nan_list(:,1)),2));
% and solve...
B=A;
B(nan_list(:,1))=fda(k,nan_list(:,1))\rhs(k);
case 1
% least squares approach with del^2. Build system
% for every array element as an unknown, and then
% eliminate those which are knowns.
% Build sparse matrix approximating del^2 for
% every element in A.
% Compute finite difference for second partials
% on row variable first
[i,j]=ndgrid(2:(n-1),1:m);
ind=i(:)+(j(:)-1)*n;
np=(n-2)*m;
fda=sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...
repmat([1 -2 1],np,1),n*m,n*m);
% now second partials on column variable
[i,j]=ndgrid(1:n,2:(m-1));
ind=i(:)+(j(:)-1)*n;
np=n*(m-2);
fda=fda+sparse(repmat(ind,1,3),[ind-n,ind,ind+n], ...
repmat([1 -2 1],np,1),nm,nm);
% eliminate knowns
rhs=-fda(:,known_list)*A(known_list);
k=find(any(fda(:,nan_list),2));
% and solve...
B=A;
B(nan_list(:,1))=fda(k,nan_list(:,1))\rhs(k);
case 2
% Direct solve for del^2 BVP across holes
% generate sparse array with second partials on row
% variable for each nan element, only for those nodes
% which have a row index > 1 or < n
L = find((nan_list(:,2) > 1) & (nan_list(:,2) < n));
nl=length(L);
if nl>0
fda=sparse(repmat(nan_list(L,1),1,3), ...
repmat(nan_list(L,1),1,3)+repmat([-1 0 1],nl,1), ...
repmat([1 -2 1],nl,1),n*m,n*m);
else
fda=spalloc(n*m,n*m,size(nan_list,1)*5);
end
% 2nd partials on column index
L = find((nan_list(:,3) > 1) & (nan_list(:,3) < m));
nl=length(L);
if nl>0
fda=fda+sparse(repmat(nan_list(L,1),1,3), ...
repmat(nan_list(L,1),1,3)+repmat([-n 0 n],nl,1), ...
repmat([1 -2 1],nl,1),n*m,n*m);
end
% fix boundary conditions at extreme corners
% of the array in case there were nans there
if ismember(1,nan_list(:,1))
fda(1,[1 2 n+1])=[-2 1 1];
end
if ismember(n,nan_list(:,1))
fda(n,[n, n-1,n+n])=[-2 1 1];
end
if ismember(nm-n+1,nan_list(:,1))
fda(nm-n+1,[nm-n+1,nm-n+2,nm-n])=[-2 1 1];
end
if ismember(nm,nan_list(:,1))
fda(nm,[nm,nm-1,nm-n])=[-2 1 1];
end
% eliminate knowns
rhs=-fda(:,known_list)*A(known_list);
% and solve...
B=A;
k=nan_list(:,1);
B(k)=fda(k,k)\rhs(k);
case 3
% The same as method == 0, except uses del^4 as the
% interpolating operator.
% del^4 template of neighbors
talks_to = [-2 0;-1 -1;-1 0;-1 1;0 -2;0 -1; ...
0 1;0 2;1 -1;1 0;1 1;2 0];
neighbors_list=identify_neighbors(n,m,nan_list,talks_to);
% list of all nodes we have identified
all_list=[nan_list;neighbors_list];
% generate sparse array with del^4, but only
% for those nodes which have a row & column index
% >= 3 or <= n-2
L = find( (all_list(:,2) >= 3) & ...
(all_list(:,2) <= (n-2)) & ...
(all_list(:,3) >= 3) & ...
(all_list(:,3) <= (m-2)));
nl=length(L);
if nl>0
% do the entire template at once
fda=sparse(repmat(all_list(L,1),1,13), ...
repmat(all_list(L,1),1,13) + ...
repmat([-2*n,-n-1,-n,-n+1,-2,-1,0,1,2,n-1,n,n+1,2*n],nl,1), ...
repmat([1 2 -8 2 1 -8 20 -8 1 2 -8 2 1],nl,1),nm,nm);
else
fda=spalloc(n*m,n*m,size(all_list,1)*5);
end
% on the boundaries, reduce the order around the edges
L = find((((all_list(:,2) == 2) | ...
(all_list(:,2) == (n-1))) & ...
(all_list(:,3) >= 2) & ...
(all_list(:,3) <= (m-1))) | ...
(((all_list(:,3) == 2) | ...
(all_list(:,3) == (m-1))) & ...
(all_list(:,2) >= 2) & ...
(all_list(:,2) <= (n-1))));
nl=length(L);
if nl>0
fda=fda+sparse(repmat(all_list(L,1),1,5), ...
repmat(all_list(L,1),1,5) + ...
repmat([-n,-1,0,+1,n],nl,1), ...
repmat([1 1 -4 1 1],nl,1),nm,nm);
end
L = find( ((all_list(:,2) == 1) | ...
(all_list(:,2) == n)) & ...
(all_list(:,3) >= 2) & ...
(all_list(:,3) <= (m-1)));
nl=length(L);
if nl>0
fda=fda+sparse(repmat(all_list(L,1),1,3), ...
repmat(all_list(L,1),1,3) + ...
repmat([-n,0,n],nl,1), ...
repmat([1 -2 1],nl,1),nm,nm);
end
L = find( ((all_list(:,3) == 1) | ...
(all_list(:,3) == m)) & ...
(all_list(:,2) >= 2) & ...
(all_list(:,2) <= (n-1)));
nl=length(L);
if nl>0
fda=fda+sparse(repmat(all_list(L,1),1,3), ...
repmat(all_list(L,1),1,3) + ...
repmat([-1,0,1],nl,1), ...
repmat([1 -2 1],nl,1),nm,nm);
end
% eliminate knowns
rhs=-fda(:,known_list)*A(known_list);
k=find(any(fda(:,nan_list(:,1)),2));
% and solve...
B=A;
B(nan_list(:,1))=fda(k,nan_list(:,1))\rhs(k);
case 4
% Spring analogy
% interpolating operator.
% list of all springs between a node and a horizontal
% or vertical neighbor
hv_list=[-1 -1 0;1 1 0;-n 0 -1;n 0 1];
hv_springs=[];
for i=1:4
hvs=nan_list+repmat(hv_list(i,:),nan_count,1);
k=(hvs(:,2)>=1) & (hvs(:,2)<=n) & (hvs(:,3)>=1) & (hvs(:,3)<=m);
hv_springs=[hv_springs;[nan_list(k,1),hvs(k,1)]];
end
% delete replicate springs
hv_springs=unique(sort(hv_springs,2),'rows');
% build sparse matrix of connections, springs
% connecting diagonal neighbors are weaker than
% the horizontal and vertical springs
nhv=size(hv_springs,1);
springs=sparse(repmat((1:nhv)',1,2),hv_springs, ...
repmat([1 -1],nhv,1),nhv,nm);
% eliminate knowns
rhs=-springs(:,known_list)*A(known_list);
% and solve...
B=A;
B(nan_list(:,1))=springs(:,nan_list(:,1))\rhs;
end
% ====================================================
% end of main function
% ====================================================
% ====================================================
% begin subfunctions
% ====================================================
function neighbors_list=identify_neighbors(n,m,nan_list,talks_to)
% identify_neighbors: identifies all the neighbors of
% those nodes in nan_list, not including the nans
% themselves
%
% arguments (input):
% n,m - scalar - [n,m]=size(A), where A is the
% array to be interpolated
% nan_list - array - list of every nan element in A
% nan_list(i,1) == linear index of i'th nan element
% nan_list(i,2) == row index of i'th nan element
% nan_list(i,3) == column index of i'th nan element
% talks_to - px2 array - defines which nodes communicate
% with each other, i.e., which nodes are neighbors.
%
% talks_to(i,1) - defines the offset in the row
% dimension of a neighbor
% talks_to(i,2) - defines the offset in the column
% dimension of a neighbor
%
% For example, talks_to = [-1 0;0 -1;1 0;0 1]
% means that each node talks only to its immediate
% neighbors horizontally and vertically.
%
% arguments(output):
% neighbors_list - array - list of all neighbors of
% all the nodes in nan_list
if ~isempty(nan_list)
% use the definition of a neighbor in talks_to
nan_count=size(nan_list,1);
talk_count=size(talks_to,1);
nn=zeros(nan_count*talk_count,2);
j=[1,nan_count];
for i=1:talk_count
nn(j(1):j(2),:)=nan_list(:,2:3) + ...
repmat(talks_to(i,:),nan_count,1);
j=j+nan_count;
end
% drop those nodes which fall outside the bounds of the
% original array
L = (nn(:,1)<1)|(nn(:,1)>n)|(nn(:,2)<1)|(nn(:,2)>m);
nn(L,:)=[];
% form the same format 3 column array as nan_list
neighbors_list=[sub2ind([n,m],nn(:,1),nn(:,2)),nn];
% delete replicates in the neighbors list
neighbors_list=unique(neighbors_list,'rows');
% and delete those which are also in the list of NaNs.
neighbors_list=setdiff(neighbors_list,nan_list,'rows');
else
neighbors_list=[];
end
|
github
|
altMITgcm/MITgcm-master
|
griddata_fast.m
|
.m
|
MITgcm-master/utils/matlab/griddata_fast.m
| 1,322 |
utf_8
|
5714c2fff7314b59ee02a68191fa02c3
|
function zi = griddata_fast(delau,z,method)
%GRIDDATA_FAST Data gridding and surface fitting.
% ZI = GRIDDATA_FAST(DEL,Z)
%
% See also GRIDDATA_PREPROCESS
% Based on
% Clay M. Thompson 8-21-95
% Copyright 1984-2001 The MathWorks, Inc.
error(nargchk(2,3,nargin))
if nargin<3, method = 'linear'; end
if ~isstr(method),
error('METHOD must be one of ''linear'',''cubic'',''nearest'', or ''v4''.');
end
% Sort x and y so duplicate points can be averaged before passing to delaunay
switch lower(method),
case 'linear'
zi = linear(delau,z);
% case 'cubic'
% zi = cubic(x,y,z,xi,yi);
% case 'nearest'
% zi = nearest(x,y,z,xi,yi);
% case {'invdist','v4'}
% zi = gdatav4(x,y,z,xi,yi);
otherwise
error('Unknown method.');
end
if nargout<=1, xi = zi; end
%------------------------------------------------------------
function zi = linear(del,z)
%LINEAR Triangle-based linear interpolation
% Reference: David F. Watson, "Contouring: A guide
% to the analysis and display of spacial data", Pergamon, 1994.
z = z(:).'; % Treat z as a row so that code below involving
% z(tri) works even when tri is 1-by-3.
zi = sum(z(del.tri) .* del.w,2);
zi = reshape(zi,del.siz);
if ~isempty(del.out), zi(del.out) = NaN; end
%------------------------------------------------------------
|
github
|
altMITgcm/MITgcm-master
|
rdmds.m
|
.m
|
MITgcm-master/utils/matlab/rdmds.m
| 15,720 |
utf_8
|
8e75fe4ad76e960b801f21359b052089
|
function [AA,itrs,MM] = rdmds(fnamearg,varargin)
% RDMDS Read MITgcmUV meta/data files
%
% A = RDMDS(FNAME)
% A = RDMDS(FNAME,ITER)
% A = RDMDS(FNAME,[ITER1 ITER2 ...])
% A = RDMDS(FNAME,NaN)
% A = RDMDS(FNAME,Inf)
% [A,ITS,M] = RDMDS(FNAME,[...])
% A = RDMDS(FNAME,[...],'rec',RECNUM)
%
% A = RDMDS(FNAME) reads data described by meta/data file format.
% FNAME is a string containing the "head" of the file names.
%
% eg. To load the meta-data files
% T.0000002880.000.000.meta, T.0000002880.000.000.data
% T.0000002880.001.000.meta, T.0000002880.001.000.data
% T.0000002880.002.000.meta, T.0000002880.002.000.data
% T.0000002880.003.000.meta, T.0000002880.003.000.data
% use
% >> A=rdmds('T.0000002880');
% >> size(A)
% ans =
% 64 32 5
% eg. To load a multiple record file
% >> A=rdmds('pickup.0000002880');
% >> size(A)
% ans =
% 64 32 5 61
%
%
% A = RDMDS(FNAME,ITER) reads data described by meta/data file format.
% FNAME is a string containing the "head" of the file name excluding the
% 10-digit iterartion number.
% ITER is a vector of positive integers that will expand to the 10-digit
% number in the file name.
% If ITER=NaN, all iterations will be read.
% If ITER=Inf, the last (highest) iteration will be read.
%
% eg. To repeat above operation
% >> A=rdmds('T',2880);
% eg. To read multiple time steps
% >> A=rdmds('T',[0 1440 2880]);
% eg. To read all time steps
% >> [A,ITS]=rdmds('T',NaN);
% eg. To read the last time step
% >> [A,IT]=rdmds('T',Inf);
% Note: this form can not read files with no iteration count in file name.
%
%
% A = RDMDS(FNAME,[...],'rec',RECNUM) reads individual records from
% multiple record files.
%
% eg. To read a single record from a multi-record file
% >> [A,IT]=rdmds('pickup.ckptA',11);
% eg. To read several records from a multi-record file
% >> [A,IT]=rdmds('pickup',Inf,'rec',[1:5 8 12]);
%
%
% A = RDMDS(FNAME,ITER,MACHINEFORMAT) allows the machine format to be
% A = RDMDS(FNAME,MACHINEFORMAT)
% specified which MACHINEFORMAT is on of the following strings:
% 'n' 'l' 'b' 'd' 'g' 'c' 'a' 's' - see FOPEN for more details
%
AA=[];
itrs=[];
MM=[];
% Default options
ieee='b';
fname=fnamearg;
userecords=0;
recnum=[];
% Check optional arguments
for ind=1:size(varargin,2);
arg=varargin{ind};
if ischar(arg)
if strcmp(arg,'n') | strcmp(arg,'native')
ieee='n';
elseif strcmp(arg,'l') | strcmp(arg,'ieee-le')
ieee='l';
elseif strcmp(arg,'b') | strcmp(arg,'ieee-be')
ieee='b';
elseif strcmp(arg,'c') | strcmp(arg,'cray')
ieee='c';
elseif strcmp(arg,'a') | strcmp(arg,'ieee-le.l64')
ieee='a';
elseif strcmp(arg,'s') | strcmp(arg,'ieee-be.l64')
ieee='s';
elseif strcmp(arg,'rec')
userecords=1;
else
error(['Optional argument ' arg ' is unknown'])
end
else
if userecords==1
recnum=arg;
elseif isempty(itrs)
if isnan(arg)
itrs=scanforfiles(fname);
disp([ sprintf('Reading %i time levels:',size(itrs,2)) sprintf(' %i',itrs) ]);
elseif isinf(arg)
itrs=scanforfiles(fname);
if isempty(itrs)
AA=[];itrs=[];return;
end
disp([ sprintf('Found %i time levels, reading %i',size(itrs,2),itrs(end)) ]);
itrs=itrs(end);
% elseif prod(double(arg>=0)) & prod(double(round(arg)==arg))
% elseif prod(arg>=0) & prod(round(arg)==arg)
elseif min(arg)>=0 & isempty(find(round(arg)~=arg))
if arg>=9999999999
error(sprintf('Argument %i > 9999999999',arg))
end
itrs=arg;
elseif length(arg) == 1 & arg == -1
itrs=arg;
else
error(sprintf('Argument %i must be a positive integer',arg))
end
else
error('Multiple iterations should be specified as a vector')
end
end
end
if isempty(itrs)
itrs=-1;
end
% Loop over each iteration
for iter=1:size(itrs,2);
if itrs(iter)>=0
fname=sprintf('%s.%10.10i',fnamearg,itrs(iter));
end
% Figure out if there is a path in the filename
NS=findstr('/',fname);
if size(NS)>0
Dir=fname(1:NS(end));
else
Dir='./';
end
% Match name of all meta-files
%fprintf(' search for file "%s".*meta\n',fname);
allfiles=dir( sprintf('%s.*meta',fname) );
if size(allfiles,1)==0
disp(sprintf('No files match the search: %s.*meta',fname));
%allow partial reads% error('No files found.')
end
% Loop through allfiles
for j=1:size(allfiles,1);
%fprintf(' file # %3i : %s\n',j,allfiles(j).name);
% Read meta- and data-file
[A,N,M,mG] = localrdmds([Dir allfiles(j).name],ieee,recnum);
%- Merge local Meta file content (M) to MM string:
if j > 0, %- to comment out this block: "if j < 0" (since j is always > 0)
ii=findstr(M,' timeStepNumber');
if isempty(ii), ii1=0; ii2=0;
else ii1=ii; ii2=ii+min(findstr(M(1+ii:end),'];')); end
ii=findstr(M,' timeInterval');
if isempty(ii), jj1=0; jj2=0;
else jj1=ii; jj2=ii+min(findstr(M(1+ii:end),'];')); end
if iter==1 & j==1,
MM=M; ind1=0; ind2=0; is1=ii1; js1=jj1; M3='';
if ii1*jj1 > 0,
%ind1=min(ii1,jj1); ind2=max(ii2,jj2);
%if ii1 < jj1, ii3=ii2+1; jj3=jj1-1;
%else ii3=jj2+1; jj3=ii1-1; end
order=sort([ii1 ii2 jj1 jj2]);
ind1=order(1); ii3=order(2)+1; jj3=order(3)-1; ind2=order(4);
M2=M(ii1:ii2); M4=M(jj1:jj2); M3=M(ii3:jj3);
elseif ii1 > 0,
ind1=ii1; ind2=ii2;
M2=M(ii1:ii2); M4='';
elseif jj1 > 0,
ind1=jj1; ind2=jj2;
M4=M(jj1:jj2); M2='';
end
M5=M(1+ind2:end);
%fprintf(' ii1,ii2 = %i %i ; jj1,jj2= %i %i ;', ii1,ii2, jj1,jj2);
%fprintf(' ii3,jj3= %i %i ; ind1,ind2= %i %i\n',ii3,jj3,ind1,ind2);
%fprintf('M(1:ind1)=%s<\n',M(1:ind1));
%fprintf(' M2=%s<\n',M2);
%fprintf(' M3=%s<\n',M3);
%fprintf(' M4=%s<\n',M4);
%fprintf(' M5=%s<\n',M5);
else
if ii1*jj1 > 0,
order=sort([ii1 ii2 jj1 jj2]);
ind=order(1); ii3=order(2)+1; jj3=order(3)-1; ind2=order(4);
else ind=max(ii1,jj1); ind2=ii2+jj2; end
compar=(ind == ind1); ii=0;
if compar & ind1 == 0, ii=1; compar=strcmp (MM,M); end
if compar & ind1 > 0, ii=2; compar=strncmp(MM,M,ind1) ; end
if compar & ind1 > 0, ii=3; compar=strcmp(M5,M(1+ind2:end)); end
if compar & ii1*jj1 > 0, ii=4; compar=strcmp(M3,M(ii3:jj3)); end
if ~compar,
fprintf('WARNING: Meta file (%s) is different (%i) from 1rst one:\n', ...
allfiles(j).name,ii);
fprintf(' it=%i :MM:%s\n',itrs(1),MM);
fprintf(' it=%i :M :%s\n\n',itrs(iter),M);
elseif ind1 > 0,
if ii1 > 0,
Mj=M(ii1:ii2); ii=findstr(Mj,'['); Mj=Mj(1+ii:end);
% add it-number from Mj to M2 (if different):
if isempty(findstr(M2,Mj)), M2=[deblank(M2(1:end-1)),Mj]; end
end
if jj1 > 0,
Mj=M(jj1:jj2); ii=findstr(Mj,'['); Mj=Mj(1+ii:end);
% add time interval from Mj to M4 (if different):
if isempty(findstr(M4,Mj)), M4=[deblank(M4(1:end-1)),' ;',Mj]; end
end
end
end
% save modifications:
if ind1>0 & j==size(allfiles,1) & iter==size(itrs,2),
if ii1 < jj1, MM=[MM(1:ind1-1),M2,M3,M4,M5];
else MM=[MM(1:ind1-1),M4,M3,M2,M5]; end
end
end
%- put local data file content in global array AA:
bdims=N(1,:);
r0=N(2,:);
rN=N(3,:);
ndims=prod(size(bdims));
if j==1 & iter==1, AA=zeros([bdims size(itrs,2)]); end
if mG(1)==0 & mG(2)==1,
if (ndims == 1)
AA(r0(1):rN(1),iter)=A;
elseif (ndims == 2)
AA(r0(1):rN(1),r0(2):rN(2),iter)=A;
elseif (ndims == 3)
AA(r0(1):rN(1),r0(2):rN(2),r0(3):rN(3),iter)=A;
elseif (ndims == 4)
AA(r0(1):rN(1),r0(2):rN(2),r0(3):rN(3),r0(4):rN(4),iter)=A;
elseif (ndims == 5)
AA(r0(1):rN(1),r0(2):rN(2),r0(3):rN(3),r0(4):rN(4),r0(5):rN(5),iter)=A;
else
error('Dimension of data set is larger than currently coded. Sorry!')
end
elseif (ndims == 1)
AA(r0(1):rN(1),iter)=A;
else
%- to debug: do simple stransfert (with a loop on 2nd index);
% will need to change this later, to improve efficiency:
for i=0:rN(2)-r0(2),
if (ndims == 2)
AA(r0(1)+i*mG(1):rN(1)+i*mG(1),r0(2)+i*mG(2),iter)=A(:,1+i);
elseif (ndims == 3)
AA(r0(1)+i*mG(1):rN(1)+i*mG(1),r0(2)+i*mG(2), ...
r0(3):rN(3),iter)=A(:,1+i,:);
elseif (ndims == 4)
AA(r0(1)+i*mG(1):rN(1)+i*mG(1),r0(2)+i*mG(2), ...
r0(3):rN(3),r0(4):rN(4),iter)=A(:,1+i,:,:);
elseif (ndims == 5)
AA(r0(1)+i*mG(1):rN(1)+i*mG(1),r0(2)+i*mG(2), ...
r0(3):rN(3),r0(4):rN(4),r0(5):rN(5),iter)=A(:,1+i,:,:,:);
else
error('Dimension of data set is larger than currently coded. Sorry!')
end
end
end
end % files
end % iterations
%-------------------------------------------------------------------------------
function [A,N,M,map2glob] = localrdmds(fname,ieee,recnum)
mname=strrep(fname,' ','');
dname=strrep(mname,'.meta','.data');
%- set default mapping from tile to global file:
map2glob=[0 1];
% Read and interpret Meta file
fid = fopen(mname,'r');
if (fid == -1)
error(['File' mname ' could not be opened'])
end
% Scan each line of the Meta file
allstr=' ';
keepgoing = 1;
while keepgoing > 0,
line = fgetl(fid);
if (line == -1)
keepgoing=-1;
else
% Strip out "(PID.TID *.*)" by finding first ")"
%old ind=findstr([line ')'],')'); line=line(ind(1)+1:end);
ind=findstr(line,')');
if size(ind) ~= 0
line=line(ind(1)+1:end);
end
% Remove comments of form //
line=[line,' //']; ind=findstr(line,'//'); line=line(1:ind(1)-1);
% Add to total string (without starting & ending blanks)
while line(1:1) == ' ', line=line(2:end); end
if strncmp(line,'map2glob',8), eval(line);
else allstr=[allstr,deblank(line),' '];
end
end
end
% Close meta file
fclose(fid);
% Strip out comments of form /* ... */
ind1=findstr(allstr,'/*'); ind2=findstr(allstr,'*/');
if size(ind1) ~= size(ind2)
error('The /* ... */ comments are not properly paired')
end
while size(ind1,2) > 0
allstr=[deblank(allstr(1:ind1(1)-1)) allstr(ind2(1)+2:end)];
%allstr=[allstr(1:ind1(1)-1) allstr(ind2(1)+3:end)];
ind1=findstr(allstr,'/*'); ind2=findstr(allstr,'*/');
end
% This is a kludge to catch whether the meta-file is of the
% old or new type. nrecords does not exist in the old type.
nrecords = NaN;
%- store the full string for output:
M=strrep(allstr,'format','dataprec');
% Everything in lower case
allstr=lower(allstr);
% Fix the unfortunate choice of 'format'
allstr=strrep(allstr,'format','dataprec');
% Evaluate meta information
eval(allstr);
N=reshape( dimlist , 3 , prod(size(dimlist))/3 );
rep=[' dimList = [ ',sprintf('%i ',N(1,:)),']'];
if ~isnan(nrecords) & nrecords > 1 & isempty(recnum)
N=[N,[nrecords 1 nrecords]'];
elseif ~isempty(recnum) & recnum>nrecords
error('Requested record number is higher than the number of available records')
end
%- make "dimList" shorter (& fit output array size) in output "M":
pat=' dimList = \[(\s*\d+\,?)*\s*\]';
M=regexprep(M,pat,rep);
% and remove double space within sq.brakets:
ind1=findstr(M,'['); ind2=findstr(M,']');
if length(ind1) == length(ind2),
for i=length(ind1):-1:1, if ind1(i) < ind2(i),
M=[M(1:ind1(i)),regexprep(M(ind1(i)+1:ind2(i)-1),'(\s+)',' '),M(ind2(i):end)];
end; end
else error('The [ ... ] brakets are not properly paired')
end
if isempty(recnum)
recnum=1;
end
if isnan(nrecords)
% This is the old 'meta' method that used sequential access
A=allstr;
% Open data file
fid=fopen(dname,'r',ieee);
% Read record size in bytes
recsz=fread(fid,1,'uint32');
ldims=N(3,:)-N(2,:)+1;
numels=prod(ldims);
rat=recsz/numels;
if rat == 4
A=fread(fid,numels,'real*4');
elseif rat == 8
A=fread(fid,numels,'real*8');
else
sprintf(' Implied size in meta-file = %d', numels )
sprintf(' Record size in data-file = %d', recsz )
error('Ratio between record size and size in meta-file inconsistent')
end
erecsz=fread(fid,1,'uint32');
if erecsz ~= recsz
sprintf('WARNING: Record sizes at beginning and end of file are inconsistent')
end
fclose(fid);
A=reshape(A,ldims);
else
% This is the new MDS format that uses direct access
ldims=N(3,:)-N(2,:)+1;
for r=1:size(recnum(:),1);
if dataprec == 'float32'
A(:,r)=myrdda(dname,ldims,recnum(r),'real*4',ieee);
elseif dataprec == 'float64'
A(:,r)=myrdda(dname,ldims,recnum(r),'real*8',ieee);
else
error(['Unrecognized format in meta-file = ' format]);
end
end
A=reshape(A,[ldims size(recnum(:),1)]);
if size(recnum(:),1)>1
N(1,end+1)=size(recnum(:),1);
N(2,end)=1;
N(3,end)=size(recnum(:),1);
end
end
%-------------------------------------------------------------------------------
% result = RDDA( file, dim, irec [options] )
%
% This routine reads the irec'th record of shape 'dim' from the
% direct-access binary file (float or double precision) 'file'.
%
% Required arguments:
%
% file - string - name of file to read from
% dim - vector - dimensions of the file records and the resulting array
% irec - integer - record number in file in which to write data
%
% Optional arguments (must appear after the required arguments):
% prec - string - precision of storage in file. Default = 'real*8'.
% ieee - string - IEEE bit-wise representation in file. Default = 'b'.
%
% 'prec' may take the values:
% 'real*4' - floating point, 32 bits.
% 'real*8' - floating point, 64 bits - the efault.
%
% 'ieee' may take values:
% 'ieee-be' or 'b' - IEEE floating point with big-endian
% byte ordering - the default
% 'ieee-le' or 'l' - IEEE floating point with little-endian
% byte ordering
% 'native' or 'n' - local machine format
% 'cray' or 'c' - Cray floating point with big-endian
% byte ordering
% 'ieee-le.l64' or 'a' - IEEE floating point with little-endian
% byte ordering and 64 bit long data type
% 'ieee-be.l64' or 's' - IEEE floating point with big-endian byte
% ordering and 64 bit long data type.
%
% eg. T=rdda('t.data',[64 64 32],1);
% T=rdda('t.data',[256],4,'real*4');
% T=rdda('t.data',[128 64],2,'real*4','b');
function [arr] = myrdda(file,N,k,varargin)
% Defaults
WORDLENGTH=8;
rtype='real*8';
ieee='b';
% Check optional arguments
args=char(varargin);
while (size(args,1) > 0)
if deblank(args(1,:)) == 'real*4'
WORDLENGTH=4;
rtype='real*4';
elseif deblank(args(1,:)) == 'real*8'
WORDLENGTH=8;
rtype='real*8';
elseif deblank(args(1,:)) == 'n' | deblank(args(1,:)) == 'native'
ieee='n';
elseif deblank(args(1,:)) == 'l' | deblank(args(1,:)) == 'ieee-le'
ieee='l';
elseif deblank(args(1,:)) == 'b' | deblank(args(1,:)) == 'ieee-be'
ieee='b';
elseif deblank(args(1,:)) == 'c' | deblank(args(1,:)) == 'cray'
ieee='c';
elseif deblank(args(1,:)) == 'a' | deblank(args(1,:)) == 'ieee-le.l64'
ieee='a';
elseif deblank(args(1,:)) == 's' | deblank(args(1,:)) == 'ieee-be.l64'
ieee='s';
else
error(['Optional argument ' args(1,:) ' is unknown'])
end
args=args(2:end,:);
end
nnn=prod(N);
[fid mess]=fopen(file,'r',ieee);
if fid == -1
error('Error while opening file:\n%s',mess)
end
st=fseek(fid,nnn*(k-1)*WORDLENGTH,'bof');
if st ~= 0
mess=ferror(fid);
error('There was an error while positioning the file pointer:\n%s',mess)
end
[arr count]=fread(fid,nnn,rtype);
if count ~= nnn
error('Not enough data was available to be read: off EOF?')
end
st=fclose(fid);
%arr=reshape(arr,N);
%
function [itrs] = scanforfiles(fname)
itrs=[];
allfiles=dir([fname '.*.001.001.meta']);
if isempty(allfiles)
allfiles=dir([fname '.*.meta']);
ioff=0;
else
ioff=8;
end
for k=1:size(allfiles,1);
hh=allfiles(k).name;
itrs(k)=str2num( hh(end-14-ioff:end-5-ioff) );
end
itrs=sort(itrs);
|
github
|
altMITgcm/MITgcm-master
|
griddata_preprocess.m
|
.m
|
MITgcm-master/utils/matlab/griddata_preprocess.m
| 2,885 |
utf_8
|
2aa1c7df8924cad853c90486c8438f04
|
function [del] = griddata_preprocess(x,y,xi,yi,method)
%GRIDDATA_PREPROCESS Pre-calculate Delaunay triangulation for use
% with GRIDDATA_FAST.
%
% DEL = GRIDDATA_PREPROCESS(X,Y,XI,YI)
% Based on
% Clay M. Thompson 8-21-95
% Copyright 1984-2001 The MathWorks, Inc.
error(nargchk(4,5,nargin))
%- To interpolate to a section (with position vector xi,yi), skip the
% ndgrid call hereafter. However, since this is poorly documented,
% leave the unconditional call to ndgrid to avoid falling into this trap
% when doing 2-D interpolation on to a square grid (xi & yi of equal size)
%if prod(size(xi)) ~= prod(size(yi))
[yi,xi]=ndgrid(yi,xi);
%end
if nargin<6, method = 'linear'; end
if ~isstr(method),
error('METHOD must be one of ''linear'',''cubic'',''nearest'', or ''v4''.');
end
switch lower(method),
case 'linear'
del = linear(x,y,xi,yi);
% case 'cubic'
% zi = cubic(x,y,z,xi,yi);
% case 'nearest'
% zi = nearest(x,y,z,xi,yi);
% case {'invdist','v4'}
% zi = gdatav4(x,y,z,xi,yi);
otherwise
error('Unknown method.');
end
%------------------------------------------------------------
function delau = linear(x,y,xi,yi)
%LINEAR Triangle-based linear interpolation
% Reference: David F. Watson, "Contouring: A guide
% to the analysis and display of spacial data", Pergamon, 1994.
siz = size(xi);
xi = xi(:); yi = yi(:); % Treat these as columns
x = x(:); y = y(:); % Treat these as columns
% older version of matlab do not have DelaunayTri, later versions do not
% have tsearch
msg=which('DelaunayTri');
if length(msg) > 0 % version is 2012 or newer
% Triangularize the data
tri=DelaunayTri(x,y);
if isempty(tri),
warning('Data cannot be triangulated.');
return
end
% Find the nearest triangle (t)
[t, bcs] = pointLocation(tri, xi, yi);
else % use delaunay and tsearch (and hope it is available)
% Triangularize the data
tri = delaunayn([x y]);
if isempty(tri),
warning('Data cannot be triangulated.');
return
end
% Find the nearest triangle (t)
t = tsearch(x,y,tri,xi,yi);
end % end of selecting version
% Only keep the relevant triangles.
out = find(isnan(t));
if ~isempty(out), t(out) = ones(size(out)); end
tri = tri(t,:);
% Compute Barycentric coordinates (w). P. 78 in Watson.
del = (x(tri(:,2))-x(tri(:,1))) .* (y(tri(:,3))-y(tri(:,1))) - ...
(x(tri(:,3))-x(tri(:,1))) .* (y(tri(:,2))-y(tri(:,1)));
w(:,3) = ((x(tri(:,1))-xi).*(y(tri(:,2))-yi) - ...
(x(tri(:,2))-xi).*(y(tri(:,1))-yi)) ./ del;
w(:,2) = ((x(tri(:,3))-xi).*(y(tri(:,1))-yi) - ...
(x(tri(:,1))-xi).*(y(tri(:,3))-yi)) ./ del;
w(:,1) = ((x(tri(:,2))-xi).*(y(tri(:,3))-yi) - ...
(x(tri(:,3))-xi).*(y(tri(:,2))-yi)) ./ del;
w(out,:) = zeros(length(out),3);
delau.tri=tri;
delau.w=w;
delau.siz=siz;
delau.out=out;
%------------------------------------------------------------
|
github
|
altMITgcm/MITgcm-master
|
rdmnc.m
|
.m
|
MITgcm-master/utils/matlab/rdmnc.m
| 18,248 |
utf_8
|
b3cbc9f16462fc93fe28ebc1bc8e6eee
|
function [S] = rdmnc(varargin)
% Usage:
% S=RDMNC(FILE1,FILE2,...)
% S=RDMNC(FILE1,...,ITER)
% S=RDMNC(FILE1,...,'VAR1','VAR2',...)
% S=RDMNC(FILE1,...,'VAR1','VAR2',...,ITER)
%
% Input:
% FILE1 Either a single file name (e.g. 'state.nc') or a wild-card
% strings expanding to a group of file names (e.g. 'state.*.nc').
% There are no assumptions about suffices (e.g. 'state.*' works).
% VAR1 Model variable names as written in the MNC/netcdf file.
% ITER Vector of iterations in the MNC/netcdf files, not model time.
%
% Output:
% S Structure with fields corresponding to 'VAR1', 'VAR2', ...
%
% Description:
% This function is a rudimentary wrapper for joining and reading netcdf
% files produced by MITgcm. It does not give the same flexibility as
% opening the netcdf files directly using netcdf(), but is useful for
% quick loading of entire model fields which are distributed in multiple
% netcdf files.
%
% Example:
% >> S=rdmnd('state.*','XC','YC','T');
% >> imagesc( S.XC, S.YC, S.T(:,:,1)' );
%
% Author: Alistair Adcroft
% Modifications: Daniel Enderton
% Initializations
dBug=0;
file={};
filepaths={};
files={};
varlist={};
iters=[];
% find out if matlab's generic netcdf API is available
% if not assume that Chuck Denham's netcdf toolbox is installed
usemexcdf = isempty(which('netcdf.open'));
% Process function arguments
for iarg=1:nargin;
arg=varargin{iarg};
if ischar(arg)
if isempty(dir(char(arg)))
varlist{end+1}=arg;
else
file{end+1}=arg;
end
else
if isempty(iters)
iters=arg;
else
error(['The only allowed numeric argument is iterations',...
' to read in as a vector for the last argument']);
end
end
end
if isempty(file)
if isempty(varlist),
fprintf( 'No file name in argument list\n');
else
fprintf(['No file in argument list:\n ==> ',char(varlist(1))]);
for i=2:size(varlist,2), fprintf([' , ',char(varlist(i))]); end
fprintf(' <==\n');
end
error(' check argument list !!!');
end
% Create list of filenames
for eachfile=file
filepathtemp=eachfile{:};
indecies = find(filepathtemp==filesep);
if ~isempty(indecies)
filepathtemp = filepathtemp(1:indecies(end));
else
filepathtemp = '';
end
expandedEachFile=dir(char(eachfile{1}));
for i=1:size(expandedEachFile,1);
if expandedEachFile(i).isdir==0
files{end+1}=expandedEachFile(i).name;
filepaths{end+1}=filepathtemp;
end
end
end
% If iterations unspecified, open all the files and make list of all the
% iterations that appear, use this iterations list for data extraction.
if isempty(iters)
iters = [];
for ieachfile=1:length(files)
eachfile = [filepaths{ieachfile},files{ieachfile}];
if usemexcdf
nc=netcdf(char(eachfile),'read');
nciters = nc{'iter'}(:);
if isempty(nciters), nciters = nc{'T'}(:); end
close(nc);
else
% the parser complains about "netcdf.open" when the matlab netcdf
% API is not available, even when it is not used so we have to
% avoid the use of "netcdf.open", etc in this function
nciters = ncgetvar(char(eachfile),'iter');
if isempty(nciters), nciters = ncgetvar(char(eachfile),'T'); end
end
iters = [iters,nciters'];
end
iters = unique(iters');
end
% Cycle through files for data extraction.
S.attributes=[];
for ieachfile=1:length(files)
eachfile = [filepaths{ieachfile},files{ieachfile}];
if dBug > 0, fprintf([' open: ',eachfile]); end
if usemexcdf
nc=netcdf(char(eachfile),'read');
S=rdmnc_local(nc,varlist,iters,S,dBug);
close(nc);
else
% the parser complains about "netcdf.open" when the matlab netcdf
% API is not available, even when it is not used so we have to
% avoid the use of "netcdf.open", etc in this function
S=rdmnc_local_matlabAPI(char(eachfile),varlist,iters,S,dBug);
end
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Local functions %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [A] = read_att(nc);
allatt=ncnames(att(nc));
if ~isempty(allatt)
for attr=allatt;
A.(char(attr))=nc.(char(attr))(:);
end
else
A = 'none';
end
function [i0,j0,fn] = findTileOffset(S);
fn=0;
if isfield(S,'attributes') & isfield(S.attributes,'global')
G=S.attributes.global;
tn=G.tile_number;
snx=G.sNx; sny=G.sNy; nsx=G.nSx; nsy=G.nSy; npx=G.nPx; npy=G.nPy;
ntx=nsx*npx;nty=nsy*npy;
gbi=mod(tn-1,ntx); gbj=(tn-gbi-1)/ntx;
i0=snx*gbi; j0=sny*gbj;
if isfield(S.attributes.global,'exch2_myFace')
fn=G.exch2_myFace;
i0=G.exch2_txGlobalo -1; j0=G.exch2_tyGlobalo -1;
end
else
i0=0;j0=0;
end
%[snx,sny,nsx,nsy,npx,npy,ntx,nty,i0,j0,fn];
function [S] = rdmnc_local(nc,varlist,iters,S,dBug)
fiter = nc{'iter'}(:); % File iterations present
if isempty(fiter), fiter = nc{'T'}(:); end
if isinf(iters); iters = fiter(end); end
if isnan(iters); iters = fiter; end
[fii,dii] = ismember(fiter,iters); fii = find(fii); % File iteration index
dii = dii(find(dii ~= 0)); % Data interation index
if dBug > 0,
fprintf(' ; fii='); fprintf(' %i',fii);
fprintf(' ; dii='); fprintf(' %i',dii); fprintf(' \n');
end
% No variables specified? Default to all
if isempty(varlist), varlist=ncnames(var(nc)); end
% Attributes for structure
if iters>0; S.iters_from_file=iters; end
S.attributes.global=read_att(nc);
[pstr,netcdf_fname,ext] = fileparts(name(nc));
if strcmp(netcdf_fname(end-3:end),'glob')
% assume it is a global file produced by gluemnc and change some
% attributes
S.attributes.global.sNx = S.attributes.global.Nx;
S.attributes.global.sNy = S.attributes.global.Ny;
S.attributes.global.nPx = 1;
S.attributes.global.nSx = 1;
S.attributes.global.nPy = 1;
S.attributes.global.nSy = 1;
S.attributes.global.tile_number = 1;
S.attributes.global.nco_openmp_thread_number = 1;
end
% Read variable data
for ivar=1:size(varlist,2)
cvar=char(varlist{ivar});
if isempty(nc{cvar})
disp(['No such variable ''',cvar,''' in MNC file ',name(nc)]);
continue
end
% code by Bruno Deremble: if you do not want to read all tiles these
% modifications make the output field smaller, let us see, if it is
% robust
if (isfield(S,cvar) == 0); firstiter = 1; else firstiter = 0; end
% end code by Bruno Deremble
dims = ncnames(dim(nc{cvar})); % Dimensions
sizVar = size(nc{cvar}); nDims=length(sizVar);
if dims{1} == 'T'
if isempty(find(fii)), error('Iters not found'); end
it = length(dims);
tmpdata = nc{cvar}(fii,:);
% leading unity dimensions get lost; add them back:
tmpdata=reshape(tmpdata,[length(fii) sizVar(2:end)]);
else
it = 0;
tmpdata = nc{cvar}(:);
% leading unity dimensions get lost; add them back:
tmpdata=reshape(tmpdata,sizVar);
end
if dBug > 1,
fprintf([' var:',cvar,': nDims=%i ('],nDims);fprintf(' %i',size(nc{cvar}));
fprintf('):%i,nD=%i,it=%i ;',length(size(tmpdata)),length(dims),it);
end
if length(dims) > 1,
tmpdata=permute(tmpdata,[nDims:-1:1]);
end
if dBug > 1,
% fprintf('(tmpdata:');fprintf(' %i',size(tmpdata)); fprintf(')');
end
[ni nj nk nm nn no np]=size(tmpdata);
[i0,j0,fn]=findTileOffset(S);
cdim=dims{end}; if cdim(1)~='X'; i0=0; end
cdim=dims{end}; if cdim(1)=='Y'; i0=j0; j0=0; end
if length(dims)>1;
cdim=dims{end-1}; if cdim(1)~='Y'; j0=0; end
else
j0=0;
end
if dBug > 1,
fprintf(' i0,ni= %i %i; j,nj= %i %i; nk=%i :',i0,ni,j0,nj,nk);
end
% code by Bruno Deremble: if you do not want to read all tiles these
% modifications make the output field smaller, let us see, if it is
% robust
if (firstiter)
S.attributes.i_first.(cvar) = i0;
S.attributes.j_first.(cvar) = j0;
end
i0 = i0 - S.attributes.i_first.(cvar);
j0 = j0 - S.attributes.j_first.(cvar);
% end code by Bruno Deremble
Sstr = '';
for istr = 1:max(nDims,length(dims)),
if istr == it, Sstr = [Sstr,'dii,'];
elseif istr == 1, Sstr = [Sstr,'i0+(1:ni),'];
elseif istr == 2, Sstr = [Sstr,'j0+(1:nj),'];
elseif istr == 3, Sstr = [Sstr,'(1:nk),'];
elseif istr == 4, Sstr = [Sstr,'(1:nm),'];
elseif istr == 5, Sstr = [Sstr,'(1:nn),'];
elseif istr == 6, Sstr = [Sstr,'(1:no),'];
elseif istr == 7, Sstr = [Sstr,'(1:np),'];
else, error('Can''t handle this many dimensions!');
end
end
eval(['S.(cvar)(',Sstr(1:end-1),')=tmpdata;'])
%S.(cvar)(i0+(1:ni),j0+(1:nj),(1:nk),(1:nm),(1:nn),(1:no),(1:np))=tmpdata;
if dBug > 1, fprintf(' %i',size(S.(cvar))); fprintf('\n'); end
S.attributes.(cvar)=read_att(nc{cvar});
% replace missing or FillValues with NaN
if isfield(S.attributes.(cvar),'missing_value');
misval = S.attributes.(cvar).missing_value;
S.(cvar)(S.(cvar) == misval) = NaN;
end
if isfield(S.attributes.(cvar),'FillValue_');
misval = S.attributes.(cvar).FillValue_;
S.(cvar)(S.(cvar) == misval) = NaN;
end
end % for ivar
if isempty(S)
error('Something didn''t work!!!');
end
return
function [S] = rdmnc_local_matlabAPI(fname,varlist,iters,S,dBug)
fiter = ncgetvar(fname,'iter'); % File iterations present
if isempty(fiter), fiter = ncgetvar(fname,'T'); end
if isinf(iters); iters = fiter(end); end
if isnan(iters); iters = fiter; end
[fii,dii] = ismember(fiter,iters); fii = find(fii); % File iteration index
dii = dii(find(dii ~= 0)); % Data interation index
if dBug > 0,
fprintf(' ; fii='); fprintf(' %i',fii);
fprintf(' ; dii='); fprintf(' %i',dii); fprintf(' \n');
end
% now open the file for reading
nc = netcdf.open(fname,'NC_NOWRITE');
% get basic information about netcdf file
[ndims nvars natts recdim] = netcdf.inq(nc);
% No variables specified? Default to all
if isempty(varlist),
for k=0:nvars-1
varlist{k+1} = netcdf.inqVar(nc,k);
end
end
% Attributes for structure
if iters>0; S.iters_from_file=iters; end
S.attributes.global=ncgetatt(nc,'global');
[pstr,netcdf_fname,ext] = fileparts(fname);
if strcmp(netcdf_fname(end-3:end),'glob')
% assume it is a global file produced by gluemnc and change some
% attributes
S.attributes.global.sNx = S.attributes.global.Nx;
S.attributes.global.sNy = S.attributes.global.Ny;
S.attributes.global.nPx = 1;
S.attributes.global.nSx = 1;
S.attributes.global.nPy = 1;
S.attributes.global.nSy = 1;
S.attributes.global.tile_number = 1;
S.attributes.global.nco_openmp_thread_number = 1;
end
% Read variable data
for ivar=1:size(varlist,2)
cvar=char(varlist{ivar});
varid=ncfindvarid(nc,cvar);
if isempty(varid)
disp(['No such variable ''',cvar,''' in MNC file ',fname]);
continue
end
% code by Bruno Deremble: if you do not want to read all tiles these
% modifications make the output field smaller, let us see, if it is
% robust
if (isfield(S,cvar) == 0); firstiter = 1; else firstiter = 0; end
% end code by Bruno Deremble
[varname,xtype,dimids,natts] = netcdf.inqVar(nc,varid);
% does this variable contain a record (unlimited) dimension?
[isrecvar,recpos] = ismember(recdim,dimids);
% Dimensions
clear sizVar dims
for k=1:length(dimids)
[dims{k}, sizVar(k)] = netcdf.inqDim(nc,dimids(k));
end
nDims=length(sizVar);
if isrecvar
if isempty(find(fii)), error('Iters not found'); end
it = length(dims);
if length(dimids) == 1
% just a time or iteration variable, this will result in a vector
% and requires special treatment
icount=1;
tmpdata = zeros(length(fii),1);
for k=1:length(fii)
istart = fii(k)-1;
tmpdata(k) = netcdf.getVar(nc,varid,istart,icount,'double');
end
else
% from now on we assume that the record dimension is always the
% last dimension. This may not always be the case
if recpos ~= nDims
error(sprintf('%s\n%s\n%s%s%i%s%i', ...
['The current code assumes that the record ' ...
'dimension is the last dimension,'], ...
'this is not the case for variable', cvar, ...
': nDims = ', nDims, ...
', position of recDim = ', recpos))
end
istart = zeros(1,it); % indexing starts a 0
icount = sizVar;
% we always want to get only on time slice at a time
icount(recpos) = 1;
% make your life simpler by putting the time dimension first
tmpdata = zeros([length(fii) sizVar(1:end-1)]);
for k=1:length(fii)
istart(recpos) = fii(k)-1; % indexing starts at 0
tmp = netcdf.getVar(nc,varid,istart,icount,'double');
tmpdata(k,:) = tmp(:);
end
% move time dimension to the end ...
tmpdata = shiftdim(tmpdata,1);
% ... and restore original shape
tmpdata = reshape(tmpdata,[sizVar(1:end-1) length(fii)]);
end
else
it = 0;
tmpdata = netcdf.getVar(nc,varid,'double');
end
%
if dBug > 1,
fprintf([' var:',cvar,': nDims=%i ('],nDims);fprintf(' %i',sizVar);
fprintf('):%i,nD=%i,it=%i ;',length(size(tmpdata)),length(dims),it);
end
[ni nj nk nm nn no np]=size(tmpdata);
%
[i0,j0,fn]=findTileOffset(S);
cdim=dims{1}; if cdim(1)~='X'; i0=0; end
cdim=dims{1}; if cdim(1)=='Y'; i0=j0; j0=0; end
if length(dims)>1;
cdim=dims{2}; if cdim(1)~='Y'; j0=0; end
else
j0=0;
end
if dBug > 1,
fprintf(' i0,ni= %i %i; j,nj= %i %i; nk=%i :',i0,ni,j0,nj,nk);
end
% code by Bruno Deremble: if you do not want to read all tiles these
% modifications make the output field smaller, let us see, if it is
% robust
if (firstiter)
S.attributes.i_first.(cvar) = i0;
S.attributes.j_first.(cvar) = j0;
end
i0 = i0 - S.attributes.i_first.(cvar);
j0 = j0 - S.attributes.j_first.(cvar);
% end code by Bruno Deremble
Sstr = '';
for istr = 1:max(nDims,length(dims)),
if istr == it, Sstr = [Sstr,'dii,'];
elseif istr == 1, Sstr = [Sstr,'i0+(1:ni),'];
elseif istr == 2, Sstr = [Sstr,'j0+(1:nj),'];
elseif istr == 3, Sstr = [Sstr,'(1:nk),'];
elseif istr == 4, Sstr = [Sstr,'(1:nm),'];
elseif istr == 5, Sstr = [Sstr,'(1:nn),'];
elseif istr == 6, Sstr = [Sstr,'(1:no),'];
elseif istr == 7, Sstr = [Sstr,'(1:np),'];
else, error('Can''t handle this many dimensions!');
end
end
eval(['S.(cvar)(',Sstr(1:end-1),')=tmpdata;'])
%S.(cvar)(i0+(1:ni),j0+(1:nj),(1:nk),(1:nm),(1:nn),(1:no),(1:np))=tmpdata;
if dBug > 1, fprintf(' %i',size(S.(cvar))); fprintf('\n'); end
%
S.attributes.(cvar)=ncgetatt(nc,cvar);
% replace missing or FillValues with NaN
if isfield(S.attributes.(cvar),'missing_value');
misval = S.attributes.(cvar).missing_value;
S.(cvar)(S.(cvar) == misval) = NaN;
end
if isfield(S.attributes.(cvar),'FillValue_');
misval = S.attributes.(cvar).FillValue_;
S.(cvar)(S.(cvar) == misval) = NaN;
end
end % for ivar
% close the file
netcdf.close(nc);
if isempty(S)
error('Something didn''t work!!!');
end
return
function vf = ncgetvar(fname,varname)
% read a netcdf variable
nc=netcdf.open(fname,'NC_NOWRITE');
% find out basics about the files
[ndims nvars natts dimm] = netcdf.inq(nc);
vf = [];
varid = [];
for k=0:nvars-1
if strcmp(netcdf.inqVar(nc,k),varname)
varid = netcdf.inqVarID(nc,varname);
end
end
if ~isempty(varid);
[varn,xtype,dimids,natts] = netcdf.inqVar(nc,varid);
% get data
vf = double(netcdf.getVar(nc,varid));
else
% do nothing
end
netcdf.close(nc);
return
function misval = ncgetmisval(nc,varid)
[varname,xtype,dimids,natts] = netcdf.inqVar(nc,varid);
misval = [];
for k=0:natts-1
attn = netcdf.inqAttName(nc,varid,k);
if strcmp(attn,'missing_value') | strcmp(attn,'_FillValue')
misval = double(netcdf.getAtt(nc,varid,attname));
end
end
function A = ncgetatt(nc,varname)
% get all attributes and put them into a struct
% 1. get global properties of file
[ndims nvars natts dimm] = netcdf.inq(nc);
% get variable ID and properties
if strcmp('global',varname)
% "variable" is global
varid = netcdf.getConstant('NC_GLOBAL');
else
% find variable ID and properties
varid = ncfindvarid(nc,varname);
if ~isempty(varid)
[varn,xtype,dimids,natts] = netcdf.inqVar(nc,varid);
else
warning(sprintf('variable %s not found',varname))
end
end
if natts > 1
for k=0:natts-1
attn = netcdf.inqAttName(nc,varid,k);
[xtype attlen]=netcdf.inqAtt(nc,varid,attn);
attval = netcdf.getAtt(nc,varid,attn);
if ~ischar(attval)
attval = double(attval);
end
if strcmp(attn,'_FillValue')
% matlab does not allow variable names to begin with an
% underscore ("_"), so we have to do change the name of this
% obsolete attribute.
A.FillValue_=attval;
else
A.(char(attn))=attval;
end
end
else
A = 'none';
end
return
function varid = ncfindvarid(nc,varname)
[ndims nvars natts dimm] = netcdf.inq(nc);
varid=[];
for k=0:nvars-1
if strcmp(netcdf.inqVar(nc,k),varname);
varid = netcdf.inqVarID(nc,varname);
break
end
end
return
|
github
|
altMITgcm/MITgcm-master
|
rdmeta.m
|
.m
|
MITgcm-master/utils/matlab/rdmeta.m
| 8,213 |
utf_8
|
1474707bccd022cacade050a0d58558b
|
function [AA] = rdmds(fname,varargin)
%
% Read MITgcmUV Meta/Data files
%
% A = RDMDS(FNAME) reads data described by meta/data file format.
% FNAME is a string containing the "head" of the file names.
%
% eg. To load the meta-data files
% T.0000002880.000.000.meta, T.0000002880.000.000.data
% T.0000002880.001.000.meta, T.0000002880.001.000.data
% T.0000002880.002.000.meta, T.0000002880.002.000.data
% T.0000002880.003.000.meta, T.0000002880.003.000.data
% use
% >> A=rdmds('T.0000002880');
%
% A = RDMDS(FNAME,MACHINEFORMAT) allows the machine format to be specified
% which MACHINEFORMAT is on of the following strings:
%
% 'native' or 'n' - local machine format - the default
% 'ieee-le' or 'l' - IEEE floating point with little-endian
% byte ordering
% 'ieee-be' or 'b' - IEEE floating point with big-endian
% byte ordering
% 'vaxd' or 'd' - VAX D floating point and VAX ordering
% 'vaxg' or 'g' - VAX G floating point and VAX ordering
% 'cray' or 'c' - Cray floating point with big-endian
% byte ordering
% 'ieee-le.l64' or 'a' - IEEE floating point with little-endian
% byte ordering and 64 bit long data type
% 'ieee-be.l64' or 's' - IEEE floating point with big-endian byte
% ordering and 64 bit long data type.
% Default options
ieee='b';
% Check optional arguments
args=char(varargin);
while (size(args,1) > 0)
if deblank(args(1,:)) == 'n' | deblank(args(1,:)) == 'native'
ieee='n';
elseif deblank(args(1,:)) == 'l' | deblank(args(1,:)) == 'ieee-le'
ieee='l';
elseif deblank(args(1,:)) == 'b' | deblank(args(1,:)) == 'ieee-be'
ieee='b';
elseif deblank(args(1,:)) == 'c' | deblank(args(1,:)) == 'cray'
ieee='c';
elseif deblank(args(1,:)) == 'a' | deblank(args(1,:)) == 'ieee-le.l64'
ieee='a';
elseif deblank(args(1,:)) == 's' | deblank(args(1,:)) == 'ieee-be.l64'
ieee='s';
else
error(['Optional argument ' args(1,:) ' is unknown'])
end
args=args(2:end,:);
end
% Match name of all meta-files
eval(['ls ' fname '*.meta;']);
allfiles=ans;
% Beginning and end of strings
Iend=findstr(allfiles,'.meta')+4;
Ibeg=[1 Iend(1:end-1)+2];
% Loop through allfiles
for j=1:prod(size(Ibeg)),
% Read meta- and data-file
[A,N] = localrdmds(allfiles(Ibeg(j):Iend(j)),ieee);
bdims=N(1,:);
r0=N(2,:);
rN=N(3,:);
ndims=prod(size(bdims));
if (ndims == 1)
AA(r0(1):rN(1))=A;
elseif (ndims == 2)
AA(r0(1):rN(1),r0(2):rN(2))=A;
elseif (ndims == 3)
AA(r0(1):rN(1),r0(2):rN(2),r0(3):rN(3))=A;
elseif (ndims == 4)
AA(r0(1):rN(1),r0(2):rN(2),r0(3):rN(3),r0(4):rN(4))=A;
else
error('Dimension of data set is larger than currently coded. Sorry!')
end
end
%-------------------------------------------------------------------------------
function [A,N] = localrdmds(fname,ieee)
mname=strrep(fname,' ','');
dname=strrep(mname,'.meta','.data');
% Read and interpret Meta file
fid = fopen(mname,'r');
if (fid == -1)
error(['File' mname ' could not be opened'])
end
% Scan each line of the Meta file
allstr=' ';
keepgoing = 1;
while keepgoing > 0,
line = fgetl(fid);
if (line == -1)
keepgoing=-1;
else
% Strip out "(PID.TID *.*)" by finding first ")"
%old ind=findstr([line ')'],')'); line=line(ind(1)+1:end);
ind=findstr(line,')');
if size(ind) ~= 0
line=line(ind(1)+1:end);
end
% Remove comments of form //
line=[line ' //']; ind=findstr(line,'//'); line=line(1:ind(1)-1);
% Add to total string
allstr=[allstr line];
end
end
% Close meta file
fclose(fid);
% Strip out comments of form /* ... */
ind1=findstr(allstr,'/*'); ind2=findstr(allstr,'*/');
if size(ind1) ~= size(ind2)
error('The /* ... */ comments are not properly paired')
end
while size(ind1,2) > 0
allstr=[allstr(1:ind1(1)-1) allstr(ind2(1)+3:end)];
ind1=findstr(allstr,'/*'); ind2=findstr(allstr,'*/');
end
% This is a kludge to catch whether the meta-file is of the
% old or new type. nrecords does not exist in the old type.
nrecords = -987;
% Everything in lower case
allstr=lower(allstr);
% Fix the unfortunate choice of 'format'
allstr=strrep(allstr,'format','dataprec');
% Evaluate meta information
eval(allstr);
N=reshape( dimlist , 3 , prod(size(dimlist))/3 );
if nrecords == -987
% This is the old 'meta' method that used sequential access
A=allstr;
% Open data file
fid=fopen(dname,'r',ieee);
% Read record size in bytes
recsz=fread(fid,1,'uint32');
ldims=N(3,:)-N(2,:)+1;
numels=prod(ldims);
rat=recsz/numels;
if rat == 4
A=fread(fid,numels,'real*4');
elseif rat == 8
A=fread(fid,numels,'real*8');
else
sprintf(' Implied size in meta-file = %d', numels )
sprintf(' Record size in data-file = %d', recsz )
error('Ratio between record size and size in meta-file inconsistent')
end
erecsz=fread(fid,1,'uint32');
if erecsz ~= recsz
sprintf('WARNING: Record sizes at beginning and end of file are inconsistent')
end
fclose(fid);
A=reshape(A,ldims);
else
% This is the new MDS format that uses direct access
ldims=N(3,:)-N(2,:)+1;
if dataprec == 'float32'
A=myrdda(dname,ldims,1,'real*4',ieee);
elseif dataprec == 'float64'
A=myrdda(dname,ldims,1,'real*8',ieee);
else
error(['Unrecognized dataprec in meta-file = ' dataprec]);
end
end
%-------------------------------------------------------------------------------
% result = RDDA( file, dim, irec [options] )
%
% This routine reads the irec'th record of shape 'dim' from the
% direct-access binary file (float or double precision) 'file'.
%
% Required arguments:
%
% file - string - name of file to read from
% dim - vector - dimensions of the file records and the resulting array
% irec - integer - record number in file in which to write data
%
% Optional arguments (must appear after the required arguments):
% prec - string - precision of storage in file. Default = 'real*8'.
% ieee - string - IEEE bit-wise representation in file. Default = 'b'.
%
% 'prec' may take the values:
% 'real*4' - floating point, 32 bits.
% 'real*8' - floating point, 64 bits - the efault.
%
% 'ieee' may take values:
% 'ieee-be' or 'b' - IEEE floating point with big-endian
% byte ordering - the default
% 'ieee-le' or 'l' - IEEE floating point with little-endian
% byte ordering
% 'native' or 'n' - local machine format
% 'cray' or 'c' - Cray floating point with big-endian
% byte ordering
% 'ieee-le.l64' or 'a' - IEEE floating point with little-endian
% byte ordering and 64 bit long data type
% 'ieee-be.l64' or 's' - IEEE floating point with big-endian byte
% ordering and 64 bit long data type.
%
% eg. T=rdda('t.data',[64 64 32],1);
% T=rdda('t.data',[256],4,'real*4');
% T=rdda('t.data',[128 64],2,'real*4','b');
function [arr] = myrdda(file,N,k,varargin)
% Defaults
WORDLENGTH=8;
rtype='real*8';
ieee='b';
% Check optional arguments
args=char(varargin);
while (size(args,1) > 0)
if deblank(args(1,:)) == 'real*4'
WORDLENGTH=4;
rtype='real*4';
elseif deblank(args(1,:)) == 'real*8'
WORDLENGTH=8;
rtype='real*8';
elseif deblank(args(1,:)) == 'n' | deblank(args(1,:)) == 'native'
ieee='n';
elseif deblank(args(1,:)) == 'l' | deblank(args(1,:)) == 'ieee-le'
ieee='l';
elseif deblank(args(1,:)) == 'b' | deblank(args(1,:)) == 'ieee-be'
ieee='b';
elseif deblank(args(1,:)) == 'c' | deblank(args(1,:)) == 'cray'
ieee='c';
elseif deblank(args(1,:)) == 'a' | deblank(args(1,:)) == 'ieee-le.l64'
ieee='a';
elseif deblank(args(1,:)) == 's' | deblank(args(1,:)) == 'ieee-be.l64'
ieee='s';
else
error(['Optional argument ' args(1,:) ' is unknown'])
end
args=args(2:end,:);
end
nnn=prod(N);
[fid mess]=fopen(file,'r',ieee);
if fid == -1
error('Error while opening file:\n%s',mess)
end
st=fseek(fid,nnn*(k-1)*WORDLENGTH,'bof');
if st ~= 0
mess=ferror(fid);
error('There was an error while positioning the file pointer:\n%s',mess)
end
[arr count]=fread(fid,nnn,rtype);
if count ~= nnn
error('Not enough data was available to be read: off EOF?')
end
st=fclose(fid);
arr=reshape(arr,N);
|
github
|
altMITgcm/MITgcm-master
|
densjmd95.m
|
.m
|
MITgcm-master/utils/matlab/densjmd95.m
| 6,582 |
utf_8
|
4771d90926365a39ace86ac088351fb4
|
function rho = densjmd95(s,t,p);
%
% DENSJMD95 Density of sea water
%=========================================================================
%
% USAGE: dens = densjmd95(S,Theta,P)
%
% DESCRIPTION:
% Density of Sea Water using Jackett and McDougall 1995 (JAOT 12)
% polynomial (modified UNESCO polynomial).
%
% INPUT: (all must have same dimensions)
% S = salinity [psu (PSS-78)]
% Theta = potential temperature [degree C (IPTS-68)]
% P = pressure [dbar]
% (P may have dims 1x1, mx1, 1xn or mxn for S(mxn) )
%
% OUTPUT:
% dens = density [kg/m^3]
%
% AUTHOR: Martin Losch 2002-08-09 ([email protected])
%
% check value
% S = 35.5 PSU
% Theta = 3 degC
% P = 3000 dbar
% rho = 1041.83267 kg/m^3
% Jackett and McDougall, 1995, JAOT 12(4), pp. 381-388
% created by mlosch on 2002-08-09
%----------------------
% CHECK INPUT ARGUMENTS
%----------------------
if nargin ~=3
error('densjmd95.m: Must pass 3 parameters')
end
if ndims(s) > 2
dims = size(s);
dimt = size(t);
dimp = size(p);
if length(dims) ~= length(dimt) | length(dims) ~= length(dimp) ...
length(dimt) ~= length(dimp)
error(['for more than two dimensions, S, Theta, and P must have the' ...
' same number of dimensions'])
else
for k=length(dims)
if dims(k)~=dimt(k) | dims(k)~=dimp(k) | dimt(k)~=dimp(k)
error(['for more than two dimensions, S, Theta, and P must have' ...
' the same dimensions'])
end
end
end
else
% CHECK S,T,P dimensions and verify consistent
[ms,ns] = size(s);
[mt,nt] = size(t);
[mp,np] = size(p);
% CHECK THAT S & T HAVE SAME SHAPE
if (ms~=mt) | (ns~=nt)
error('check_stp: S & T must have same dimensions')
end %if
% CHECK OPTIONAL SHAPES FOR P
if mp==1 & np==1 % P is a scalar. Fill to size of S
p = p(1)*ones(ms,ns);
elseif np==ns & mp==1 % P is row vector with same cols as S
p = p( ones(1,ms), : ); % Copy down each column.
elseif mp==ms & np==1 % P is column vector
p = p( :, ones(1,ns) ); % Copy across each row
elseif mp==ms & np==ns % P is a matrix size(S)
% shape ok
else
error('check_stp: P has wrong dimensions')
end %if
[mp,np] = size(p);
% IF ALL ROW VECTORS ARE PASSED THEN LET US PRESERVE SHAPE ON RETURN.
Transpose = 0;
if mp == 1 % row vector
p = p(:);
t = t(:);
s = s(:);
Transpose = 1;
end
%***check_stp
end
% convert pressure to bar
p = .1*p;
% coefficients nonlinear equation of state in pressure coordinates for
% 1. density of fresh water at p = 0
eosJMDCFw(1) = 999.842594;
eosJMDCFw(2) = 6.793952e-02;
eosJMDCFw(3) = - 9.095290e-03;
eosJMDCFw(4) = 1.001685e-04;
eosJMDCFw(5) = - 1.120083e-06;
eosJMDCFw(6) = 6.536332e-09;
% 2. density of sea water at p = 0
eosJMDCSw(1) = 8.244930e-01;
eosJMDCSw(2) = - 4.089900e-03;
eosJMDCSw(3) = 7.643800e-05 ;
eosJMDCSw(4) = - 8.246700e-07;
eosJMDCSw(5) = 5.387500e-09;
eosJMDCSw(6) = - 5.724660e-03;
eosJMDCSw(7) = 1.022700e-04;
eosJMDCSw(8) = - 1.654600e-06;
eosJMDCSw(9) = 4.831400e-04;
t2 = t.*t;
t3 = t2.*t;
t4 = t3.*t;
is = find(s(:) < 0 );
if ~isempty(is)
warning('found negative salinity values, reset them to NaN');
s(is) = NaN;
end
s3o2 = s.*sqrt(s);
% density of freshwater at the surface
rho = eosJMDCFw(1) ...
+ eosJMDCFw(2)*t ...
+ eosJMDCFw(3)*t2 ...
+ eosJMDCFw(4)*t3 ...
+ eosJMDCFw(5)*t4 ...
+ eosJMDCFw(6)*t4.*t;
% density of sea water at the surface
rho = rho ...
+ s.*( ...
eosJMDCSw(1) ...
+ eosJMDCSw(2)*t ...
+ eosJMDCSw(3)*t2 ...
+ eosJMDCSw(4)*t3 ...
+ eosJMDCSw(5)*t4 ...
) ...
+ s3o2.*( ...
eosJMDCSw(6) ...
+ eosJMDCSw(7)*t ...
+ eosJMDCSw(8)*t2 ...
) ...
+ eosJMDCSw(9)*s.*s;
rho = rho./(1 - p./bulkmodjmd95(s,t,p));
if ndims(s) < 3 & Transpose
rho = rho';
end %if
return
function bulkmod = bulkmodjmd95(s,t,p)
%function bulkmod = bulkmodjmd95(s,t,p)
dummy = 0;
% coefficients in pressure coordinates for
% 3. secant bulk modulus K of fresh water at p = 0
eosJMDCKFw(1) = 1.965933e+04;
eosJMDCKFw(2) = 1.444304e+02;
eosJMDCKFw(3) = - 1.706103e+00;
eosJMDCKFw(4) = 9.648704e-03;
eosJMDCKFw(5) = - 4.190253e-05;
% 4. secant bulk modulus K of sea water at p = 0
eosJMDCKSw(1) = 5.284855e+01;
eosJMDCKSw(2) = - 3.101089e-01;
eosJMDCKSw(3) = 6.283263e-03;
eosJMDCKSw(4) = - 5.084188e-05;
eosJMDCKSw(5) = 3.886640e-01;
eosJMDCKSw(6) = 9.085835e-03;
eosJMDCKSw(7) = - 4.619924e-04;
% 5. secant bulk modulus K of sea water at p
eosJMDCKP( 1) = 3.186519e+00;
eosJMDCKP( 2) = 2.212276e-02;
eosJMDCKP( 3) = - 2.984642e-04;
eosJMDCKP( 4) = 1.956415e-06;
eosJMDCKP( 5) = 6.704388e-03;
eosJMDCKP( 6) = - 1.847318e-04;
eosJMDCKP( 7) = 2.059331e-07;
eosJMDCKP( 8) = 1.480266e-04;
eosJMDCKP( 9) = 2.102898e-04;
eosJMDCKP(10) = - 1.202016e-05;
eosJMDCKP(11) = 1.394680e-07;
eosJMDCKP(12) = - 2.040237e-06;
eosJMDCKP(13) = 6.128773e-08;
eosJMDCKP(14) = 6.207323e-10;
t2 = t.*t;
t3 = t2.*t;
t4 = t3.*t;
is = find(s(:) < 0 );
if ~isempty(is)
warning('found negative salinity values, reset them to NaN');
s(is) = NaN;
end
s3o2 = s.*sqrt(s);
%p = pressure(i,j,k,bi,bj)*SItoBar
p2 = p.*p;
% secant bulk modulus of fresh water at the surface
bulkmod = eosJMDCKFw(1) ...
+ eosJMDCKFw(2)*t ...
+ eosJMDCKFw(3)*t2 ...
+ eosJMDCKFw(4)*t3 ...
+ eosJMDCKFw(5)*t4;
% secant bulk modulus of sea water at the surface
bulkmod = bulkmod ...
+ s.*( eosJMDCKSw(1) ...
+ eosJMDCKSw(2)*t ...
+ eosJMDCKSw(3)*t2 ...
+ eosJMDCKSw(4)*t3 ...
) ...
+ s3o2.*( eosJMDCKSw(5) ...
+ eosJMDCKSw(6)*t ...
+ eosJMDCKSw(7)*t2 ...
);
% secant bulk modulus of sea water at pressure p
bulkmod = bulkmod ...
+ p.*( eosJMDCKP(1) ...
+ eosJMDCKP(2)*t ...
+ eosJMDCKP(3)*t2 ...
+ eosJMDCKP(4)*t3 ...
) ...
+ p.*s.*( eosJMDCKP(5) ...
+ eosJMDCKP(6)*t ...
+ eosJMDCKP(7)*t2 ...
) ...
+ p.*s3o2*eosJMDCKP(8) ...
+ p2.*( eosJMDCKP(9) ...
+ eosJMDCKP(10)*t ...
+ eosJMDCKP(11)*t2 ...
) ...
+ p2.*s.*( eosJMDCKP(12) ...
+ eosJMDCKP(13)*t ...
+ eosJMDCKP(14)*t2 ...
);
return
|
github
|
altMITgcm/MITgcm-master
|
cm_landwater.m
|
.m
|
MITgcm-master/utils/matlab/cm_landwater.m
| 1,351 |
utf_8
|
6c91417081d672740729bfc946eee0e1
|
function [c] = cm_landwater(n,varargin)
% [c] = cm_landwater(n)
% [c] = cm_landwater(n,f)
%
% n - is size of color map
% f is scalar fraction that should be water (default=0.5)
% or vector [hmin hmax] from which f will be calculated
%
% e.g.
% >> cm_landwater(64,caxis);
%
% Green-yellor land/blue water colormap
if nargin==1
f=0.5;
else
f=varargin{1};
end
if prod(size(f))==2
hmin=f(1);hmax=f(2);
f=-hmin/(hmax-hmin);
f=max(0,f);f=min(1,f);
end
if mod(n,2)==0
nb=round(n*f(1));
ng=n-nb;
nw=0;
else
nb=floor(n*f(1));
nw=1;
ng=n-nb-nw;
end
b=bluewater(nb);
g=greenland(ng);
w=ones(nw,1)*[1 1 0.55];
c=[b' w' g']';
if nargout==0
colormap(c);
end
%subplot(211)
%plot((0:(n-1))/(n-1),c(:,3:-1:1))
%subplot(212)
%pcol([-1:.1/n:1])
%axis off
% ----------------------------------------------------
function [c] = bluewater(n)
% Blue colormap
x=(0:n-1)'/(n-1);
c=((.7-.7*x)*[1 1 0]+max(0,(1-.65*x))*[0 0 1]);
c=c(end:-1:1,:);
%colormap(c);
% ----------------------------------------------------
function [c] = greenland(n)
% Green land colormap
x=(0:n-1)'/(n-1);
r=max(0,(-.25+1.8*x));
g=.4*(1+2.5*x);
b=0.5*max(0,(-.25+2.0*x));
i=find(r>1);
r(i)=max( 1.7-1*x(i), b(i));
i=find(g>1);
g(i)=max( 1.5-1*x(i), b(i));
c=r*[1 0 0]+g*[0 1 0]+b*[0 0 1];
c=min(max(0,c),1);
%colormap(c);
% ----------------------------------------------------
|
github
|
altMITgcm/MITgcm-master
|
set_mask.m
|
.m
|
MITgcm-master/utils/matlab/ocean_basin/set_mask.m
| 5,044 |
utf_8
|
4eb4ec826e20fede5dbee22bd57dd25a
|
function [newmask,iMask,XV,YV]=set_mask(x,y,mask,val)
% [newmask,iMask,XV,YV]=set_mask(x,y,mask,val)
% GUI to create mask by hand. Idea is to set masking area
% by selecting polygon(s) or selecting single points.
% Area enclosed by the polygon or the selected point is
% set to value 'val'.
% Press 'v' or 'o' to begin selecting a polygon.
% If you want to mark a single point, place cursor over that point
% and press 'm'.
% If you pressed 'v' or 'o', click as many times as needed to
% pick the vertices of a polygon.
% When finished picking points, hit 'enter'.
% (It is not necessary to close the polygon. This will be
% done automatically.) Points with a value of '1' (ocean) are set
% to a value of 'val'. Thus land points (NaN) and points
% corresponding to other masks i.e., values ~= 1 (displayed in
% different colors) will not be touched. HOWEVER, if you
% pressed 'o', the latter points will be OVERWRITTEN.
% If you pressed 'm', the selected point is set to value 'val',
% but ONLY IF its original value was '1' (ocean).
% So you can call this
% function multiple times with a different value of 'val', and
% set a different mask each time (without overwriting what was
% set during a previous call).
% Once the polygon has been selected and the values set, the
% plot will update. You can then pick another polygon or select
% another point by hitting 'v'/'o' or 'm'.
% To end, press 'e'.
% To undo the last step, press 'u'.
% Outputs:
% newmask: the modified mask
% iMask: vector of indices of points that were modified
% XV,YV: cell arrays containing the vertices of polygons selected.
% Thus, the action of this script can be reproduced in two ways:
% (1) newmask=mask;
% newmask(iMask)=val;
% (2) newmask=mask; [Xp,Yp]=ndgrid(x,y);
% for iv=1:length(XV)
% in=inpolygon(Xp,Yp,XV{iv},YV{iv});
% ii=find(newmask==1 & in==1);
% newmask(ii)=val;
% end
% (1) is most robust. (2) will not reproduce the action of
% selecting single points, but it will allow you to set masks
% defined on a different grid.
if val==0 | val==1
error('Cannot set mask value to 0 or 1')
end
newmask=mask;
iNaNs=find(isnan(newmask));
newmask(iNaNs)=0;
[Xp,Yp]=ndgrid(x,y);
% pcolor(x,y,newmask');
% set(gcf,'renderer','zbuffer'); % hack to deal with disappearing crosshairs
refresh_plot(x,y,newmask)
iv=1;
iMask=[];
XV=[];
YV=[];
but='v';
while (~strcmp(but,'e'))
[x1,y1,but]=ginput(1);
but=char(but);
if (strcmp(but,'v') | strcmp(but,'o')) % select polygon
xv=[];yv=[]; but1=but;
while (~strcmp(but1,''))
[x1,y1,but1]=ginput(1);
but1=char(but1);
xv=[xv;x1];yv=[yv;y1];
add_point(xv,yv)
end
xv=[xv;xv(1)]; yv=[yv;yv(1)];
XV{iv}=xv; YV{iv}=yv; iv=iv+1;
in=inpolygon(Xp,Yp,xv,yv);
if (strcmp(but,'v'))
% Only select water points and points in polygon. Points belonging to
% other masks (different colors/values~=val) are not touched.
lastBut='v';
ii=find(newmask==1 & in==1);
else
% Only select water points and points in polygon. Points belonging to
% other masks (different colors/values~=val) may be overwritten.
% ii=find(~isnan(newmask) & in==1);
lastBut='o';
ii=find(newmask~=0 & in==1);
end
oldmask=newmask; % in case we want to undo
newmask(ii)=val;
iMask=[iMask;ii];
% pcolor(x,y,newmask');
% set(gcf,'renderer','zbuffer'); % hack to deal with disappearing crosshairs
refresh_plot(x,y,newmask,XV,YV)
elseif (strcmp(but,'m'))
lastBut='m';
[m,im]=min(abs(x1-x));
[m,jm]=min(abs(y1-y));
% only mark water points
if newmask(im,jm)==1
ii=sub2ind(size(newmask),im,jm);
oldmask=newmask; % in case we want to undo
newmask(ii)=val;
iMask=[iMask;ii];
refresh_plot(x,y,newmask)
end
elseif (strcmp(but,'u')) % undo
nadd=length(ii); % number of points added
disp('Undoing last step ...')
newmask=oldmask; % reset previous values
iMask=iMask(1:end-nadd); % delete mask indices
if lastBut~='m'
tmpXV=XV; tmpYV=YV; % delete polygon vertices. is there an easy way to do this?
clear XV YV
for k=1:length(tmpXV)-1
XV{k}=tmpXV{k};
YV{k}=tmpYV{k};
end
iv=iv-1;
% pcolor(x,y,newmask');
% set(gcf,'renderer','zbuffer'); % hack to deal with disappearing crosshairs
end
refresh_plot(x,y,newmask,XV,YV)
end
end
newmask(iNaNs)=NaN;
function refresh_plot(x,y,mask,XV,YV)
% pcolor(x,y,mask');
% shading interp
imagesc(x,y,mask')
axis xy
% set(gcf,'renderer','zbuffer'); % hack to deal with disappearing crosshairs
if nargin>3
hold on
for k=1:length(XV)
plot(XV{k},YV{k},'k-o')
end
hold off
end
function add_point(x,y)
hold on
plot(x,y,'k-o')
hold off
|
github
|
altMITgcm/MITgcm-master
|
GraphixLoad.m
|
.m
|
MITgcm-master/utils/matlab/Graphix/GraphixLoad.m
| 11,982 |
utf_8
|
0895483a27fd13e552cc564235db7460
|
function [data,xax,yax,time,pltslc,XG,YG] = ...
GraphixLoad(fil,fln,trl,dat,dad,grd,itr,tst,flu,ddf,gdf,avg,slc,pst,...
LoadGridData,GraphixDebug,GridSuffix,ZcordFile,Index,...
Dim,Vector,Mate,uFld,vFld,gmfile,KwxFld,KwyFld,Grads,...
Year0Iter,SecPerYear,Months,PlotFld,XL,YL,ThetaToActT,...
ThetaToThetaEc,DataIn,SecMom,TFld,T2Fld,EtaFld,Eta2Fld,...
u2Fld,v2Fld,DevFromMean,WFld,W2Fld);
% Load parameters.
GraphixGenParam;
GraphixFieldParamA;
GraphixFieldParamO;
GraphixFieldParamI;
GraphixFieldParamC;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Prepare for the various data types, set time %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Time stuff (itr = 0 is start of new 360 day year).
if isempty(Months)
months = (itr-Year0Iter)./(30.*24.*3600./tst);
else
months = Months;
end
time = months/12;
if Dim == 0 & ~isequal(dat,'Mon')
if ismember(PlotFld,fields2D) | ismember(fln,fields2D), Dim = 2; end
if ismember(PlotFld,fields3D) | ismember(fln,fields3D), Dim = 3; end
if Dim == 0
error('Unknown field dimension!');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Read in data %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load grid information.
if ~isequal(dat,'Gra')
[nc,dim,XC,XG,YC,YG,ZC,ZF,RAC,drC,drF,HFacC,...
HFacW,HFacS,dxG,dyG,dxC,dyC,AngleCS,AngleSN] = ...
GraphixLoadGridData(LoadGridData,grd,gdf,flu,GridSuffix,ZcordFile);
end
% Load GRADS data
if isequal(dat,'Gra')
if GraphixDebug, disp([' Debug -- Loading GRADS field.']); end
[data,xax,yax,zax,months,time,dim] = ...
GraphixLoadGradsData(fil,dad,fln,GraphixDebug);
GraphixDebug_Local(GraphixDebug,'data','load',data);
data = GraphixAverage(data,fln,avg,months,ddf,dim);
GraphixDebug_Local(GraphixDebug,'data','average',data);
[data,xax,yax,pltslc] = ...
GraphixSliceGradsData(fln,flu,slc,data,xax,yax,zax);
GraphixDebug_Local(GraphixDebug,'data','slice',data);
% Load monitor data -- can be cleaned up.
elseif isequal(dat,'Mon')
[data,time] = ...
GraphixLoadMonitor(fln,fil,dad,itr,tst,SecPerYear,GraphixDebug);
xax = time; yax = NaN; pltslc = 'timfld';
% Load meridional overturning.
elseif ismember(fln,{'Bol','Psi','Res'})
if isequal(flu,'A'), delM = - 1000*drF ./ g;
elseif isequal(flu,'O'), delM = drF; end
if ismember(fln,{'Psi','Res'})
if isequal(ddf,'MDS')
U = LocalLoad([dad,'/',uFld],uFld,itr,ddf,nc,DataIn);
V = LocalLoad([dad,'/',vFld],vFld,itr,ddf,nc,DataIn);
elseif isequal(ddf,'MNC')
U = LocalLoad([dad,'/',fil],uFld,itr,ddf,nc,DataIn);
V = LocalLoad([dad,'/',fil],vFld,itr,ddf,nc,DataIn);
end
U = GraphixAverage(U,fln,avg,months,ddf,Dim);
V = GraphixAverage(V,fln,avg,months,ddf,Dim);
[psiavg,mask,ylat]=calc_PsiCube(delM,U.*HFacW,V.*HFacS,dxG,dyG);
end
if ismember(fln,{'Bol','Res'})
try
kwx = LocalLoad([dad,'/',gmfile],KwxFld,itr,ddf,nc,DataIn);
kwy = LocalLoad([dad,'/',gmfile],KwyFld,itr,ddf,nc,DataIn);
catch
kwx = LocalLoad([dad,'/GM_Kwx-T'],'',itr,'MDS',nc,DataIn);
kwy = LocalLoad([dad,'/GM_Kwy-T'],'',itr,'MDS',nc,DataIn);
end
kwx = GraphixAverage(kwx,fln,avg,months,ddf,Dim);
kwy = GraphixAverage(kwy,fln,avg,months,ddf,Dim);
[ub,vb]=calc_Bolus_CS(RAC,dxC,dyC,dxG,dyG,drC,kwx,kwy,HFacW,HFacS);
[psibol,mask,ylat]=calc_PsiCube(delM,ub.*HFacW,vb.*HFacS,dxG,dyG);
end
if isequal(fln,'Psi')
data = psiavg(2:end-1,:)';
elseif isequal(fln,'Bol')
data = psibol(2:end-1,:)';
elseif isequal(fln,'Res')
data = psibol(2:end-1,:)' + psiavg(2:end-1,:)';
end
if isequal(flu,'A'), data = data./1e6; end
xax = ylat; yax = ZF; pltslc = 'lathgt';
% Second moments -- This can eventually be made more elegant.
elseif ~isequal(SecMom,'')
if ismember(SecMom,{'T','Eta','W'})
if isequal(SecMom,'Eta')
data = LocalLoad([dad,'/',fil],EtaFld ,itr,ddf,nc,DataIn)./100 ;
data2 = LocalLoad([dad,'/',fil],Eta2Fld,itr,ddf,nc,DataIn)./10000;
elseif ismember(SecMom,{'T','ActT'})
data = LocalLoad([dad,'/',fil],TFld ,itr,ddf,nc,DataIn);
data2 = LocalLoad([dad,'/',fil],T2Fld,itr,ddf,nc,DataIn);
elseif isequal(SecMom,'W')
data = LocalLoad([dad,'/',fil],WFld ,itr,ddf,nc,DataIn);
data2 = LocalLoad([dad,'/',fil],W2Fld,itr,ddf,nc,DataIn);
end
data = GraphixAverage(data ,fln,avg,months,ddf,Dim);
data2 = GraphixAverage(data2,fln,avg,months,ddf,Dim);
data = data2-data.^2;
if isequal(ThetaToActT,1)
pres = NaN.*zeros(size(data));
for iz=1:length(ZC), pres(:,:,iz)=ZC(iz); end
Exner = (pres./presrefA).^(RdA/cpA);
data=data.*Exner.^2;
end
elseif isequal(SecMom,'KE')
U = LocalLoad([dad,'/',fil],uFld ,itr,ddf,nc,DataIn);
V = LocalLoad([dad,'/',fil],vFld ,itr,ddf,nc,DataIn);
UU = LocalLoad([dad,'/',fil],u2Fld,itr,ddf,nc,DataIn);
VV = LocalLoad([dad,'/',fil],v2Fld,itr,ddf,nc,DataIn);
U = GraphixAverage(U ,fln,avg,months,ddf,Dim);
V = GraphixAverage(V ,fln,avg,months,ddf,Dim);
UU = GraphixAverage(UU,fln,avg,months,ddf,Dim);
VV = GraphixAverage(VV,fln,avg,months,ddf,Dim);
u_dim = size(U); nz=prod(u_dim(3:end));
U = reshape(U ,[6*nc nc nz]); V = reshape(V ,[6*nc nc nz]);
UU = reshape(UU,[6*nc nc nz]); VV = reshape(VV,[6*nc nc nz]);
[U_spl ,V_spl ] = split_UV_cub(U ,V );
[UU_spl,VV_spl] = split_UV_cub(UU,VV);
U_spl = reshape(U_spl ,[nc+1 nc nz 6]);
V_spl = reshape(V_spl ,[nc nc+1 nz 6]);
UU_spl = reshape(UU_spl,[nc+1 nc nz 6]);
VV_spl = reshape(VV_spl,[nc nc+1 nz 6]);
U_spl = (U_spl(1:nc,:,:,:) + U_spl(2:nc+1,:,:,:))./2;
V_spl = (V_spl(:,1:nc,:,:) + V_spl(:,2:nc+1,:,:))./2;
UU_spl = (UU_spl(1:nc,:,:,:) + UU_spl(2:nc+1,:,:,:))./2;
VV_spl = (VV_spl(:,1:nc,:,:) + VV_spl(:,2:nc+1,:,:))./2;
U = reshape(permute(U_spl ,[1 4 2 3]),[6*nc nc nz]);
V = reshape(permute(V_spl ,[1 4 2 3]),[6*nc nc nz]);
UU = reshape(permute(UU_spl,[1 4 2 3]),[6*nc nc nz]);
VV = reshape(permute(VV_spl,[1 4 2 3]),[6*nc nc nz]);
data = sqrt((UU + VV)-(U.*U + V.*V));
end
[data,xax,yax,pltslc] = ...
GraphixSlice(data,fln,trl,dat,dad,grd,itr,tst,flu,ddf,gdf,avg,...
slc,pst,Dim,LoadGridData,GridSuffix,ZcordFile,...
Vector,PlotFld,XL,YL);
% General reader.
else
if isequal(Vector,0)
if isempty(Index)
if isequal(ddf,'MNC'), Index = {'+',fln};
elseif isequal(ddf,'MDS'), Index = {'+', ''}; end
end
for ii = 1:2:length(Index)
if isequal(ddf,'MNC')
d = LocalLoad([dad,'/',fil],Index{ii+1},itr,ddf,nc,DataIn);
elseif isequal(ddf,'MDS')
d = LocalLoad([dad,'/',fil],fln,itr,ddf,nc,DataIn);
if ~isequal(Index{ii+1},'')
if isequal(Dim,2)
d=squeeze(d(:,:,Index{ii+1},:));
elseif isequal(Dim,3)
d=squeeze(d(:,:,:,Index{ii+1},:));
end
end
end
if ii == 1, eval(['data = ' ,Index{ii},' d;']);
else, eval(['data = data ',Index{ii},' d;']); end
data(data==1e15)=0; % Set no values to zeros.
end
GraphixDebug_Local(GraphixDebug,'data','load',data);
data = GraphixAverage(data,fln,avg,months,ddf,Dim);
GraphixDebug_Local(GraphixDebug,'data','average',data);
if ThetaToActT | ThetaToThetaEc
pres = NaN.*zeros(size(data));
for iz=1:length(ZC), pres(:,:,iz)=ZC(iz); end
temp=data.*(pres./presrefA).^(RdA/cpA);
data=temp;
end
if ThetaToThetaEc
es=A_CC.*exp(Beta_CC.*(temp-K2C));
qstar=(RdA/RvA).*(es./pres);
data=theta.*exp(LHvapA.*qstar./cpA./temp);
end
elseif ~isempty(find([1,2]==Vector))
if isequal(ddf,'MDS')
data = LocalLoad([dad,'/',fil],fln,itr,ddf,nc,DataIn);
if ~isempty(Index)
if isequal(Dim,2), data1 = squeeze(data(:,Index,:));
data2 = squeeze(data(:, Mate,:));
elseif isequal(Dim,3), data1 = squeeze(data(:,:,Index,:));
data2 = squeeze(data(:,:, Mate,:));
end
else
data1 = data;
data2 = LocalLoad([dad,'/',Mate],fln,itr,ddf,nc,DataIn);
end
elseif isequal(ddf,'MNC')
data1 = LocalLoad([dad,'/',fil],fln ,itr,ddf,nc,DataIn);
data2 = LocalLoad([dad,'/',fil],Mate,itr,ddf,nc,DataIn);
end
if isequal(Vector,1), U = data1; V = data2;
elseif isequal(Vector,2), U = data2; V = data1; end
GraphixDebug_Local(GraphixDebug,'U-dir vector','load',U);
GraphixDebug_Local(GraphixDebug,'V-dir vector','load',V);
U = GraphixAverage(U,fln,avg,months,ddf,Dim);
V = GraphixAverage(V,fln,avg,months,ddf,Dim);
GraphixDebug_Local(GraphixDebug,'U-dir vector','average',U);
GraphixDebug_Local(GraphixDebug,'V-dir vector','average',V);
[uE,vN] = rotate_uv2uvEN(U,V,AngleCS,AngleSN,'C');
%[U,V]=uvcube2latlon(XC,YC,U,V,XL,YL);
if isequal(Vector,1), data = uE;
elseif isequal(Vector,2), data = vN; end
GraphixDebug_Local(GraphixDebug,'data','vector manipulation',data);
end
[data,xax,yax,pltslc] = ...
GraphixSlice(data,fln,trl,dat,dad,grd,itr,tst,flu,ddf,gdf,avg,...
slc,pst,Dim,LoadGridData,GridSuffix,ZcordFile,...
Vector,PlotFld,XL,YL);
GraphixDebug_Local(GraphixDebug,'data','slice',data);
GraphixDebug_Local(GraphixDebug,'xax' ,'slice',xax);
GraphixDebug_Local(GraphixDebug,'yax' ,'slice',yax);
end
if DevFromMean
if size(xax,1) == 1
datazon = mean(data,2);
for ii = 1:length(xax)
data(:,ii) = data(:,ii) - datazon;
end
else
error('DevFromMean for cube grid not yet implemented!');
end
end
%-------------------------------------------------------------------------%
% Local functions %
%-------------------------------------------------------------------------%
% Thus is merely a local function that calls the load data functions
% according to the DataFormat for the data specified by dfm. The (some-
% times length) load calls can be avoided by directly passing the desired
% data matrix with the 'DataIn' agruement.
function data = LocalLoad(fil,fln,itr,dfm,nc,DataIn)
if isempty(DataIn)
if isempty(dir([fil,'*'])), ls([fil,'*']); end
if isequal(dfm,'MDS'), data = rdmds(fil,itr);
elseif isequal(dfm,'MNC'), data = rdmnc([fil,'.*'],fln,'iter',itr);
else error(['Unrecognized data type: ',dfm]); end
else
data = DataIn;
end
if isequal(dfm,'MNC')
eval(['data = data.',fln,';']);
data = data(1:6.*nc,1:nc,:,:);
end
function GraphixDebug_Local(GraphixDebug,arrayname,operation,data)
if GraphixDebug
disp([' Debug -- ''',arrayname,''' size after',...
' ',operation,': ',mat2str(size(data))]);
end
|
github
|
altMITgcm/MITgcm-master
|
displaytiles.m
|
.m
|
MITgcm-master/utils/matlab/cs_grid/displaytiles.m
| 714 |
utf_8
|
325f08e4dd87446d887ea548a0751f3f
|
function [] = displaytiles(A)
% Display tiled field.
%
% Dimensions of A must be (n,n,6)
%
% Written by [email protected], 2001.
global cmin cmax
clf
if size(A,3)==1
A=tiles(A,1:6);
end
cmin=min(min(min(A)));
cmax=max(max(max(A)));
if isnan(cmin)
cmin = 0;
end
if isnan(cmax)
cmax = 1;
end
if cmin==cmax
cmax = cmin+1;
end
subplot(3,4,9)
myplot(A(:,:,1)')
subplot(3,4,10)
myplot(A(:,:,2)')
subplot(3,4,6)
myplot(A(:,:,3)')
subplot(3,4,7)
myplot(A(:,:,4)')
subplot(3,4,3)
myplot(A(:,:,5)')
subplot(3,4,4)
myplot(A(:,:,6)')
%Colorbar
subplot(3,10,30)
x=[0 1];
y=(0:63)'/63*(cmax-cmin)+cmin;
pcol(x,y,[y y]);
set(gca,'XTickLabel',[]);
function [] = myplot( Q )
global cmin cmax
pcol( Q );
caxis([cmin cmax])
|
github
|
altMITgcm/MITgcm-master
|
uvLatLon2cube.m
|
.m
|
MITgcm-master/utils/matlab/cs_grid/uvLatLon2cube.m
| 4,280 |
utf_8
|
94ef18e807e841554f45873f687e5912
|
function [uCs,vCs,errFlag]=uvLatLon2cube(xc,yc,uFld,vFld,xcs,ycs,spv,cosalpha,sinalpha);
% [uCs,vCs]=uvLatLon2cube(xc,yc,uFld,vFld,xcs,ycs,spv);
% put a vector field (uFld,vFld) on to the C-grid, Cubed-sphere grid: uCs,vCs
% xc,yc = long,lat position of vector field (uFld,vFld)
% assume: size(xc) == size(uFld,1) == size(vFld,1)
% and : size(yc) == size(uFld,2) == size(vFld,2)
% xcs,ycs = long,lat of the Cell-Center point on CS-grid
% assume: size(xcs)=size(ycs)=[6*nc nc]=size(uCs)[1:2]=size(vCs)[1:2]
%
% Written by [email protected], 2005.
if nargin < 7, mask=0 ; else mask=1 ; end
uCs=0; vCs=0; mCsU=0; mCsV=0; errFlag=0;
%Rac='/home/jmc/grid_cs32/';
Rac='grid_files/';
nc=size(xcs,2); ncx=6*nc; nPg=ncx*nc;
nr=size(uFld,3);
fprintf('Entering uvLatLon2cube:');
msk1=ones(size(uFld));
if mask == 1,
fld=ones(size(vFld));
msk1(find(uFld == spv))=0;
fld(find(vFld == spv))=0;
fld=fld-msk1; dd=sum(sum(sum(abs(fld))));
if dd == 0,
fprintf(' mask from uFld & vFld match\n');
else
fprintf(' different uFld & vFld mask in %i pts\n',dd);
errFlag=1; return;
end
uFld(find(msk1 == 0))=0;
vFld(find(msk1 == 0))=0;
else
fprintf(' no mask applied\n');
end
%-- check longitude:
dd=mean(mean(xcs))-mean(xc);
fprintf('mean longitude (data/CS): %5.3f %5.3f and dx= %5.3f \n', ...
mean(xc),mean(mean(xcs)),xc(2)-xc(1));
fprintf(' min max longitude (data) : %5.3f %5.3f \n',xc(1),xc(end));
fprintf(' min max longitude (CSgrid): %5.3f %5.3f \n',min(min(xcs)),max(max(xcs)));
%- add 1 column at the end :
if xc(end) < max(max(xcs)),
dimFld=size(uFld); nx=dimFld(1); nxp=nx+1; dimFld(1)=nxp;
fld=uFld; uFld=zeros(dimFld);
uFld(1:nx,:,:)=fld(1:nx,:,:); uFld(nxp,:,:)=fld(1,:,:);
fld=vFld; vFld=zeros(dimFld);
vFld(1:nx,:,:)=fld(1:nx,:,:); vFld(nxp,:,:)=fld(1,:,:);
fld=msk1; msk1=zeros(dimFld);
msk1(1:nx,:,:)=fld(1:nx,:,:); msk1(nxp,:,:)=fld(1,:,:);
xExt=zeros(1,nxp); xExt(1:nx)=xc; xExt(nxp)=xc(1)+360;
fprintf('Add one column at the end (i=%i): lon= %5.3f\n',dimFld(1),xExt(end));
else
xExt=xc;
end
% Read cos and sin of rotation angle if not provided on input
if nargin < 9
namfil=['proj_cs',int2str(nc),'_2uEvN.bin'];
cosalpha=zeros(nPg); sinalpha=zeros(nPg);
fid=fopen([Rac,namfil],'r','b');
cosalpha=fread(fid,nPg,'real*8');
sinalpha=fread(fid,nPg,'real*8');
fclose(fid);
end
uvEN=zeros(nPg, 2);
uvEN(:,1)=cosalpha;
uvEN(:,2)=sinalpha;
%- go to CS grid, keeping E-W, N-S direction:
x6s=permute(reshape(xcs,[nc 6 nc]),[1 3 2]);
y6s=permute(reshape(ycs,[nc 6 nc]),[1 3 2]);
[uCsE]=int2CS(uFld,xExt,yc,x6s,y6s);
[vCsN]=int2CS(vFld,xExt,yc,x6s,y6s);
[mskC]=int2CS(msk1,xExt,yc,x6s,y6s);
uCsE=uCsE./mskC;
vCsN=vCsN./mskC;
uCsE(find(mskC==0))=0;
vCsN(find(mskC==0))=0;
%- rotate toward CS-grid directions :
uCsE=reshape(permute(uCsE,[1 3 2 4]),nPg,nr);
vCsN=reshape(permute(vCsN,[1 3 2 4]),nPg,nr);
ucs=zeros(nPg,nr);
vcs=zeros(nPg,nr);
for k=1:nr,
ucs(:,k)= uvEN(:,1).*uCsE(:,k)+uvEN(:,2).*vCsN(:,k);
vcs(:,k)=-uvEN(:,2).*uCsE(:,k)+uvEN(:,1).*vCsN(:,k);
end
ucs=reshape(ucs,[ncx nc nr]);
vcs=reshape(vcs,[ncx nc nr]);
mskC=reshape(permute(mskC,[1 3 2 4]),[ncx nc nr]);
%- from A-grid to C-grid :
[u6t]=split_C_cub(ucs);
[v6t]=split_C_cub(vcs);
[m6t]=split_C_cub(mskC);
for n=1:2:6,
uloc=u6t(1,:,:,n);
u6t(1,:,:,n)=v6t(1,:,:,n);
v6t(1,:,:,n)=uloc;
end
for n=2:2:6,
uloc=u6t(:,1,:,n);
u6t(:,1,:,n)=v6t(:,1,:,n);
v6t(:,1,:,n)=uloc;
end
%size(u6t)
ncp=nc+1;
uCs=zeros(nc,nc,nr,6);
vCs=zeros(nc,nc,nr,6);
mCsU=zeros(nc,nc,nr,6);
mCsV=zeros(nc,nc,nr,6);
uCs(:,:,:,:)=u6t([1:nc],[2:ncp],:,:)+u6t([2:ncp],[2:ncp],:,:);
mCsU(:,:,:,:)=m6t([1:nc],[2:ncp],:,:)+m6t([2:ncp],[2:ncp],:,:);
vCs(:,:,:,:)=v6t([2:ncp],[1:nc],:,:)+v6t([2:ncp],[2:ncp],:,:);
mCsV(:,:,:,:)=m6t([2:ncp],[1:nc],:,:)+m6t([2:ncp],[2:ncp],:,:);
uCs=reshape(permute(uCs,[1 4 2 3]),[ncx nc nr])/2;
vCs=reshape(permute(vCs,[1 4 2 3]),[ncx nc nr])/2;
mCsU=reshape(permute(mCsU,[1 4 2 3]),[ncx nc nr])/2;
mCsV=reshape(permute(mCsV,[1 4 2 3]),[ncx nc nr])/2;
if mask == 1,
uCs(find(mCsU==0.))=spv;
vCs(find(mCsV==0.))=spv;
end
return
function Qcs=int2CS(Qini, x0,y0,xc,yc)
Qcs=zeros([size(xc) size(Qini,3)]);
for m=1:size(Qini,3)
for f=1:size(xc,3);
Qcs(:,:,f,m)=interp2(y0,x0,Qini(:,:,m),yc(:,:,f),xc(:,:,f));
end
end
return
|
github
|
altMITgcm/MITgcm-master
|
grph_CS.m
|
.m
|
MITgcm-master/utils/matlab/cs_grid/bk_line/grph_CS.m
| 6,836 |
utf_8
|
5194ef2b0c209422ae42f586731cf648
|
function [fac]=grph_CS(var,xcs,ycs,xcg,ycg,c1,c2,shift,cbV,AxBx,kEnv)
% [fac]=grph_CS(var,xcs,ycs,xcg,ycg,c1,c2,shift[,cbV,AxBx,kEnv]) :
% produce a flat plot of the cube_sphere field "var",
% keeping the initial grid (no interpolation, use "surf")
% xcs,ycs,xcg,ycg = center + corner grid point coordinates
% c1 < c2 = min & max for the color graph
% c1 > c2 = scale with min,max of the field, + c1/100 and + c2/100
% shift=-1 : No coast-line
% 1 : No shift but draw coast-line calling draw_coast
% else : draw coast-line (using m_proj) shifted by "shift" degree.
% cbV = 0,1 : horizontal,vertical colorbar; >= 2 : no colorbar;
% kEnv = 0 : standard ; =odd : do not draw the mesh ; >1 : no min,Max written.
% AxBx = do axis(AxBx) to zoom in Box "AxBx" ; only if shift=-1,1 ;
%-----------------------
% Written by [email protected], 2005.
%- small number (relative to lon,lat in degree)
epsil=1.e-6;
%- mid-longitude of the grid (truncated @ epsil level):
xMid=mean(xcs(:)); xMid=epsil*round(xMid/epsil);
%fprintf(' mid Longitude of the grid: %22.16e\n',xMid);
if nargin < 9, cbV=0 ; end
if nargin < 10, AxBx=[xMid-180 xMid+180 -90 90] ; end
if nargin < 11, kEnv=0 ; end
%------------------------------
nc=size(var,2) ; ncp=nc+1 ; nPg=nc*nc*6;
MxV=min(min(var));
mnV=max(max(var));
if shift == 1 | shift == -1,
xxt=reshape(xcs,[nPg 1]); yyt=reshape(ycs,[nPg 1]);
tmp=(xxt-AxBx(1)).*(AxBx(2)-xxt); [I]=find(tmp > 0 );
tmp=(yyt(I)-AxBx(3)).*(AxBx(4)-yyt(I)); [J]=find(tmp > 0 );
IJ=I(J); tmp=var(IJ); mnV=min(tmp); MxV=max(tmp);
end
%------------
if c1 >= c2
mb=(MxV-mnV)*0.01;
c1=mnV+mb*c1;
c2=MxV+mb*c2;
if c1*c2 < 0
c2=max(abs([c1 c2]));
c1=-c2;
end
fprintf('min,max %8.3e %8.3e Cmin,max %8.3e %8.3e \n',mnV,MxV,c1,c2)
end
%------------------------------
%figure(1);
if shift ~= 1 & shift ~= -1,
fac=pi/180.;
else
fac=1. ;
end
%---
nbsf = 0 ; ic = 0 ; jc = 0 ;
nPx=prod(size(xcg)); nPy=prod(size(ycg));
if nPx == nPg & nPy == nPg,
xcg=reshape(xcg,[nPg 1]); ycg=reshape(ycg,[nPg 1]);
%- add the 2 missing corners:
%fprintf(' Local version of grph_CS : ---------------------------------- \n');
xcg(nPg+1)=xcg(1); ycg(nPg+1)=ycg(1+2*nc);
xcg(nPg+2)=xcg(1+3*nc); ycg(nPg+2)=ycg(1);
elseif nPx ~= nPg+2 | nPy ~= nPg+2,
error([' wrong xcg,ycg dimensions : ',int2str(nPx),' , ',int2str(nPy)]);
end
[xx2]=split_Z_cub(xcg);
[yy2]=split_Z_cub(ycg);
%---
var=permute(reshape(var,[nc 6 nc]),[1 3 2]);
for n=1:6,
%if n < 5 & n > 2,
if n < 7,
%--------------------------------------------------------
i0=nc*(n-1);
vv1=zeros(ncp,ncp) ; xx1=vv1 ; yy1=vv1 ;
vv1(1:nc,1:nc)=var(:,:,n);
xx1=xx2(:,:,n);
yy1=yy2(:,:,n);
% if xx1(ncp,1) < xMid-300. ; xx1(ncp,1)=xx1(ncp,1)+360. ; end
% if xx1(1,ncp) < xMid-300. ; xx1(1,ncp)=xx1(1,ncp)+360. ; end
%------------
if shift <= -360
%--- Jump ? (only for debug diagnostic) :
for i=1:nc, for j=1:nc,
if abs(xx1(i,j)-xx1(i,j+1)) > 120
fprintf('N: i,J,xx_j,j+1,+C %3i %3i %3i %8.3e %8.3e %8.3e \n', ...
n, i,j,xx1(i,j), xx1(i,j+1), xcs(i0+i,j) ) ; end
if abs(xx1(i,j)-xx1(i+1,j)) > 120
fprintf('N: I,j,xx_i,i+1,+C %3i %3i %3i %8.3e %8.3e %8.3e \n', ...
n, i,j,xx1(i,j), xx1(i+1,j), xcs(i0+i,j) ) ; end
end ; end
%---
end
%--------------------------------------
if n == 4 | n == 3
jc=1+nc/2 ;
%-- case where Xc jump from < 180 to > -180 when j goes from jc to jc+1 :
% cut the face in 2 parts (1: x > 0 ; 2: x < 0 ) and plot separately
[I]=find(xx1(:,jc) < xMid-120); xx1(I,jc)=xx1(I,jc)+360.;
% N pole longitude is arbitrary: set to +90 to get a nicer plot:
xx1(find( abs(yy1-90)<epsil ))=xMid+90;
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xx1,yy1,vv1,1,ncp,1,jc,c1,c2) ;
%-
[I]=find(xx1(:,jc) > xMid+120); xx1(I,jc)=xx1(I,jc)-360.;
% N pole longitude is arbitrary: set to -90 to get a nicer plot:
xx1(find( abs(yy1-90)<epsil ))=xMid-90;
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xx1,yy1,vv1,1,ncp,jc,ncp,c1,c2) ;
%---
elseif n == 6
ic=1+nc/2 ;
%-- case where Xc jump from < -180 to > 180 when i goes from ic to ic+1 :
% cut the face in 2 parts (1: x > 0 ; 2: x < 0 ) and plot separately
[J]=find(xx1(ic,:) < xMid-120); xx1(ic,J)=xx1(ic,J)+360.;
% S pole longitude is arbitrary: set to +90 to get a nicer plot:
xx1(find( abs(yy1+90)<epsil ))=xMid+90;
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xx1,yy1,vv1,ic,ncp,1,ncp,c1,c2) ;
%-
[J]=find(xx1(ic,:) > xMid+120); xx1(ic,J)=xx1(ic,J)-360.;
% S pole longitude is arbitrary: set to -90 to get a nicer plot:
xx1(find( abs(yy1+90)<epsil ))=xMid-90;
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xx1,yy1,vv1,1,ic,1,ncp,c1,c2) ;
%---
else
%-- plot the face in 1 piece :
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xx1,yy1,vv1,1,ncp,1,ncp,c1,c2) ;
end
%--------------------------------------
end ; end
set(S,'LineStyle','-','LineWidth',0.01);
if rem(kEnv,2) > 0, set(S,'EdgeColor','none'); end
hold off
if shift == -1,
axis(AxBx); fprintf(' Axis(Box): %i %i %i %i \n',AxBx);
elseif shift == 1,
[L]=draw_coast(fac);
set(L,'color',[1 0 1]);
% set(L,'Color',[0 0 0],'LineWidth',2); % set(L,'LineStyle','-');
axis(AxBx); fprintf(' Axis(Box): %i %i %i %i \n',AxBx);
else
m_proj('Equidistant Cylindrical','lat',90,'lon',[-180+shift 180+shift])
%m_proj('Equidistant Cylindrical','lat',[-0 60],'lon',[-180+shift 180+shift])
m_coast('color',[0 0 0]);
m_grid('box','on')
end
%--
if cbV < 2, bV=fix(cbV); moveHV_colbar([10+bV*2.2 10 7-5*bV 7+2*bV]/10,cbV); end
if mnV < MxV & kEnv < 2,
ytxt=min(1,fix(cbV));
if shift == 1 | shift == -1,
xtxt=mean(AxBx(1:2)) ; ytxt=AxBx(3)-(AxBx(4)-AxBx(3))*(12+2*ytxt)/100;
else
xtxt=60 ; ytxt=30*ytxt-145 ;
%xtxt= 0 ; ytxt=30*ytxt-120 ;
end
%fprintf('min,Max= %9.5g , %9.5g (xtxt,ytxt= %f %f)\n',mnV,MxV,xtxt,ytxt);
text(xtxt*fac,ytxt*fac,sprintf('min,Max= %9.5g , %9.5g', mnV, MxV))
%set(gca,'position',[-.1 0.2 0.8 0.75]); % xmin,ymin,xmax,ymax in [0,1]
elseif mnV < MxV, fprintf('min,Max= %9.5g , %9.5g \n',mnV,MxV);
else fprintf('Uniform field: min,Max= %g \n',MxV); end
return
%----------------------------------------------------------------------
function [nbsf,S]=part_surf(nbsf,fac,xx,yy,vv,i1,i2,j1,j2,c1,c2)
S=surf(fac*xx(i1:i2,j1:j2),fac*yy(i1:i2,j1:j2), ...
zeros(i2+1-i1,j2+1-j1),vv(i1:i2,j1:j2)) ;
%shading flat ; %- or faceted (=default) or interp
if c1 < c2, caxis([c1 c2]) ; end
%set(S,'LineStyle','-','LineWidth',0.01); set(S,'EdgeColor','none');
%set(S,'Clipping','off');
%get(S) ;
%nbsf = nbsf+1 ; if nbsf == 1 ; hold on ; view(0,90) ; end
nbsf = nbsf+1 ; if nbsf == 1 ; hold on ; view(0,90) ; end
%axis([-180 180 60 90]) ; % work only without coast-line
%axis([-180 180 -90 -60]) ; % work only without coast-line
%axis([30 60 -45 -25]) ; % work only without coast-line
return
%----------------------------------------------------------------------
|
github
|
altMITgcm/MITgcm-master
|
grph_CSz.m
|
.m
|
MITgcm-master/utils/matlab/cs_grid/bk_line/grph_CSz.m
| 7,506 |
utf_8
|
e06faa836aaf90bfa4b2e880979b55a0
|
function grph_CSz(var,xcs,ycs,xcg,ycg,c1,c2,shift,cbV,AxBx,kEnv)
% grph_CSz(var,xcs,ycs,xcg,ycg,c1,c2,shift[,cbV,AxBx,kEnv]) :
% produce a flat plot of the cube_sphere "var" (@ C-grid corner position)
% keeping the initial grid (no interpolation, use "surf").
% xcs,ycs,xcg,ycg = center + corner grid point coordinates
% c1 < c2 = min & max for the color graph
% c1 > c2 = scale with min,max of the field, + c1/100 and + c2/100
% shift=-1 : No coast-line
% shift= 1 : No shift but draw coast-line calling draw_coast
% else : draw coast-line (using m_proj) shifted by "shift" degree.
% cbV = 0,1 : horizontal,vertical colorbar; >= 2 : no colorbar;
% kEnv = 0 : standard ; =odd : do not draw the mesh ; >1 : no min,Max written.
% AxBx = do axis(AxBx) to zoom in Box "AxBx" ; only if shift=-1 ;
%-----------------------
% Written by [email protected], 2005.
%- small number (relative to lon,lat in degree)
epsil=1.e-6;
%- mid-longitude of the grid (truncated @ epsil level):
xMid=mean(xcs(:)); xMid=epsil*round(xMid/epsil);
%fprintf(' mid Longitude of the grid: %22.16e\n',xMid);
if nargin < 9, cbV=0 ; end
if nargin < 10, AxBx=[xMid-180 xMid+180 -90 90] ; end
if nargin < 11, kEnv=0 ; end
%------------------------------
ncx=size(xcs,1); nc=size(xcs,2) ; ncp=nc+1 ; nPt2=size(var,1);
nPts=ncx*nc;
%- check dim
if ncx ~= 6*nc | nPt2 ~= nPts+2,
fprintf('Bad dim (input fields): nc,ncx,nPts,nPt2= %i %i %i %i\n',nc,ncx,nPts,nPt2);
error(' wrong dimensions ');
end
mnV=min(var);
MxV=max(var);
% mx=min(min(var));
% mn=max(max(var));
%if shift == 1,
% for j=1:nc, for i=1:6*nc,
% if var(i,j) ~= NaN & xcs(i,j) > AxBx(1) & xcs(i,j) < AxBx(2) ...
% & ycs(i,j) > AxBx(3) & ycs(i,j) < AxBx(4) ,
% mn=min(var(i,j),mn); mx=max(var(i,j),mx) ; end
% end ; end ;
%else
% for j=1:nc, for i=1:6*nc,
% if var(i,j) ~= NaN ; mn=min(var(i,j),mn); mx=max(var(i,j),mx) ; end
% end ; end ;
%end
%------------
if c1 >= c2
mb=(MxV-mnV)*0.01;
c1=mnV+mb*c1;
c2=MxV+mb*c2;
if c1*c2 < 0
c2=max(abs([c1 c2]));
c1=-c2;
end
fprintf('min,max %8.3e %8.3e Cmin,max %8.3e %8.3e \n',mnV,MxV,c1,c2)
end
%------------------------------
%figure(1);
if shift ~= 1 & shift ~= -1,
%pphh=path; ppaa='/u/u2/jmc/MATLAB';
pphh=path; ppaa='/home/jmc/matlab/MATLAB';
llaa=length(ppaa); if pphh(1:llaa) == ppaa, else path(ppaa,path);end
set_axis
fac=rad ;
else
fac=1. ;
end
%---
nbsf = 0 ; ic = 0 ; jc = 0 ;
vv0=permute(reshape(var(1:nPts,1),[nc 6 nc]),[1 3 2]);
[xx2]=split_C_cub(xcs,1);
[yy2]=split_C_cub(ycs,1);
%---
for n=1:6,
%if n > 2 & n < 4,
if n < 7,
%--------------------------------------------------------
i0=nc*(n-1);
vv1=zeros(ncp,ncp) ; xx1=vv1 ; yy1=vv1 ;
vv1(1:nc,1:nc)=vv0(:,:,n);
%-----
xx1=xx2(:,:,n);
yy1=yy2(:,:,n);
% if xx1(ncp,1) < xMid-300. ; xx1(ncp,1)=xx1(ncp,1)+360. ; end
% if xx1(1,ncp) < xMid-300. ; xx1(1,ncp)=xx1(1,ncp)+360. ; end
%------------
if shift <= -360
%--- Jump ? (only for debug diagnostic) :
for i=1:nc, for j=1:nc,
if abs(xx1(i,j)-xx1(i,j+1)) > 120
fprintf('N: i,J,xx_j,j+1,+C %3i %3i %3i %8.3e %8.3e %8.3e \n', ...
n, i,j,xx1(i,j), xx1(i,j+1), xcs(i0+i,j) ) ; end
if abs(xx1(i,j)-xx1(i+1,j)) > 120
fprintf('N: I,j,xx_i,i+1,+C %3i %3i %3i %8.3e %8.3e %8.3e \n', ...
n, i,j,xx1(i,j), xx1(i+1,j), xcs(i0+i,j) ) ; end
end ; end
%---
end
%--------------------------------------
if n == 4 | n == 3
jc=2+nc/2 ;
%-- case where Xc jump from < 180 to > -180 when j goes from jc to jc+1 :
% cut the face in 2 parts (1: x > 0 ; 2: x < 0 ) and plot separately
xxSav=xx1(:,jc);
[I]=find(xx1(:,jc) < xMid-120); xx1(I,jc)=xMid+180.;
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xx1,yy1,vv1,1,ncp,1,jc,c1,c2) ;
%-
xx1(:,jc)=xxSav; jc=jc-1;
[I]=find(xx1(:,jc) > xMid+120); xx1(I,jc)=xMid-180.;
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xx1,yy1,vv1,1,ncp,jc,ncp,c1,c2) ;
% Note: later on, will plot separately N & S poles with the 2 missing corners.
%---
elseif n == 6
ic=1+nc/2 ;
%-- case where Xc jump from < -180 to > 180 when i goes from ic to ic+1 :
% cut the face in 2 parts (1: x > 0 ; 2: x < 0 ) and plot separately
xxSav=xx1(ic,:);
[J]=find(xx1(ic,:) < xMid-120); xx1(ic,J)=xMid+180.;
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xx1,yy1,vv1,ic,ncp,1,ncp,c1,c2) ;
%-
xx1(ic,:)=xxSav; ic=ic+1;
[J]=find(xx1(ic,:) > xMid+120); xx1(ic,J)=xMid-180.;
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xx1,yy1,vv1,1,ic,1,ncp,c1,c2) ;
%---
else
%-- plot the face in 1 piece :
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xx1,yy1,vv1,1,ncp,1,ncp,c1,c2) ;
end
%--------------------------------------
end ; end
%--------------
%- add isolated point:
vvI=zeros(2,2); xxI=vvI; yyI=vvI;
%- 1rst missing corner (N.W corner of 1rst face): nPts+1
vvI(1,1)=var(nPts+1);
for l=0:2,
xxI(1+rem(l,2),1+fix(l/2))=xx2(2,ncp,1+2*l);
yyI(1+rem(l,2),1+fix(l/2))=yy2(2,ncp,1+2*l);
end
xxI(2,2)=xxI(1,2); yyI(2,2)=yyI(1,2);
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xxI,yyI,vvI,1,2,1,2,c1,c2) ;
%- 2nd missing corner (S.E corner of 2nd face): nPts+2
vvI(1,1)=var(nPts+2);
for l=0:2,
xxI(1+rem(l,2),1+fix(l/2))=xx2(ncp,2,2+2*l);
yyI(1+rem(l,2),1+fix(l/2))=yy2(ncp,2,2+2*l);
end
xxI(2,2)=xxI(1,2); yyI(2,2)=yyI(1,2);
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xxI,yyI,vvI,1,2,1,2,c1,c2) ;
%- N pole:
vvI(1,1)=var(1+nc/2+2*nc+nc/2*ncx);
xxI(1,:)=xMid-180; xxI(2,:)=xMid+180;
yyI(:,1)=max(ycs(:)); yyI(:,2)=+90;
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xxI,yyI,vvI,1,2,1,2,c1,c2) ;
%- S pole:
vvI(1,1)=var(1+nc/2+5*nc+nc/2*ncx);
xxI(1,:)=xMid-180; xxI(2,:)=xMid+180;
yyI(:,2)=min(ycs(:)); yyI(:,1)=-90;
[nbsf,S(nbsf)]=part_surf(nbsf,fac,xxI,yyI,vvI,1,2,1,2,c1,c2) ;
%--------------
set(S,'LineStyle','-','LineWidth',0.01);
if rem(kEnv,2) > 0, set(S,'EdgeColor','none'); end
hold off
if shift == -1,
axis(AxBx); fprintf(' Axis(Box): %i %i %i %i \n',AxBx);
elseif shift == 1
[L]=draw_coast(fac);
set(L,'color',[1 0 1]);
% set(L,'Color',[0 0 0],'LineWidth',2); % set(L,'LineStyle','-');
axis(AxBx); fprintf(' Axis(Box): %i %i %i %i \n',AxBx);
else
m_proj('Equidistant Cylindrical','lat',90,'lon',[-180+shift 180+shift])
%m_proj('Equidistant Cylindrical','lat',[-0 60],'lon',[-180+shift 180+shift])
m_coast('color',[0 0 0]);
m_grid('box','on')
end
%--
if cbV < 2, scalHV_colbar([10-cbV/2 10 7-5*cbV 7+2*cbV]/10,cbV); end
if mnV < MxV & kEnv < 2,
ytxt=min(1,cbV);
if shift == 1 | shift == -1,
xtxt=mean(AxBx(1:2)) ; ytxt=AxBx(3)-(AxBx(4)-AxBx(3))*(10+1*ytxt)/100;
text(xtxt*fac,ytxt*fac,sprintf('min,Max= %9.5g , %9.5g', mnV, MxV))
%set(gca,'position',[-.1 0.2 0.8 0.75]); % xmin,ymin,xmax,ymax in [0,1]
else text(0,(30*cbV-120)*fac,sprintf('min,Max= %9.5g , %9.5g', mnV, MxV))
end
else fprintf('Uniform field: min,Max= %g \n',MxV); end
return
%----------------------------------------------------------------------
function [nbsf,S]=part_surf(nbsf,fac,xx,yy,vv,i1,i2,j1,j2,c1,c2)
S=surf(fac*xx(i1:i2,j1:j2),fac*yy(i1:i2,j1:j2), ...
zeros(i2+1-i1,j2+1-j1),vv(i1:i2,j1:j2)) ;
if c1 < c2, caxis([c1 c2]) ; end
%set(S,'LineStyle','-','LineWidth',0.01); %set(S,'EdgeColor','none');
%set(S,'Clipping','off');
%get(S) ;
%nbsf = nbsf+1 ; if nbsf == 1 ; hold on ; view(0,90) ; end
nbsf = nbsf+1 ; if nbsf == 1 ; hold on ; view(0,90) ; end
%axis([-180 180 60 90]) ; % work only without coast-line
%axis([-180 180 -90 -60]) ; % work only without coast-line
%axis([30 60 -45 -25]) ; % work only without coast-line
return
%----------------------------------------------------------------------
|
github
|
altMITgcm/MITgcm-master
|
llc_pcol.m
|
.m
|
MITgcm-master/utils/matlab/cs_grid/latloncap/llc_pcol.m
| 4,388 |
utf_8
|
2365f63799298f0149ad467287f3baf1
|
%function h=llc_pcol(t,fldname,iter)
%function h=llc_pcol(t,fldname,iter,'sphere')
%function h=llc_pcol(t,fldname,iter,'m_map arguments')
% with default iter = 1
%function h=llc_pcol(t,fldname)
%function h=llc_pcol(t,fldname,[],'m_map arguments')
%
% plots 2D scalar fields v on the MITgcm llc (lat-lon-cap) grid with pcolor.
% The structure of tiles is assumed to be created by rdnctiles, e.g.,
% t = rdnctiles({'grid.*','state.*'},{'XG','YG','Eta'},[],'bytile',[]);
% see help rdnctiles for details
% (addpath ${mitgcm_rootdir}/utils/matlab/gmt)
% t must contain XG,YG and the field to be plotted as specified in fldname
%
% The optional flag sphere results in a 3D visualization on the sphere
% without any specific projection. Good for debugging.
%
% llc_pcol return a vector h of patch handles.
%
% If present 'm_map argurments' are passed directly to m_proj to select
% any projection that m_map allows, then m_grid is called without any
% options (requires m_map, obviously). In order to control the input of
% m_grid, use m_ungrid and the m_grid with proper arguments, e.g.
% h=llc_pcol(x,y,v,'stereo','lon',0,'lat',80,'rad',60)
% plots a stereographic map with center at (0E,80N) and a radius of 60
% degrees as in: m_proj('stereo','lon',0,'lat',80,'rad',60); use
% m_ungrid; m_grid('box','off')
% to turn off the box around the plot.
% If you want coast lines, you can add them with m_coast after calling
% llc_pcol.
% Unfortunatly, cylindrical and conic maps are limited to the [-180 180]
% range.
function h=llc_pcol(varargin)
zlevel = 1;
ph = [];
holdstatus=ishold;
if ~holdstatus; cla; end
t =varargin{1};
if nargin < 2
error('need at least tile-structure and fldname as input')
end
fldname=varargin{2};
if nargin < 3
iter = 1;
else
iter=varargin{3};
if isempty(iter); iter = 1; end
end
% handle map projections
mapit = 0;
noproj= 0;
if nargin > 3
proj=varargin{4};
if strcmp('sphere',proj)
noproj = 1;
else
mapit = 1;
end
end
if mapit
m_proj(varargin{4:end});
end
% number of tiles
ntiles = length(t);
% loop over tiles
if noproj
% no projection at all
for itile = 1:length(t)
xc = getfield(t(itile).var,'XG')*pi/180;
yc = getfield(t(itile).var,'YG')*pi/180;
fld = getfield(t(itile).var,fldname);
if ndims(fld) == 3;
fld = fld(1:size(xc,1)-1,1:size(yc,2)-1,iter);
else
fld = fld(1:size(xc,1)-1,1:size(yc,2)-1,zlevel,iter);
end
[x,y,z] = sph2cart(xc,yc,1);
ph = [ph;surf(x,y,z,sq(fld))];
view(3)
if (itile == 1); hold on; end
end
set(ph,'edgecolor','none')
shading flat
axis(gca,'image')
view(gca,3)
else
overlap = 30;
for itile = 1:length(t)
fld = getfield(t(itile).var,fldname);
xc = getfield(t(itile).var,'XG');
yc = getfield(t(itile).var,'YG');
if ndims(fld) == 3;
fld = fld(1:size(xc,1)-1,1:size(yc,2)-1,iter);
else
fld = fld(1:size(xc,1)-1,1:size(yc,2)-1,zlevel,iter);
end
% divide tile into two to avoid 360 degree jump
ic{1}=find(xc(:)>+overlap);
ic{2}=find(xc(:)<-overlap);
if mapit; [xc yc]=m_ll2xy(xc,yc,'clipping','on'); end
% if itile==9; keyboard; end
for k=1:2
tfld = fld([1:end 1],[1:end 1]); tfld(ic{k}) = NaN;
x = xc; x(ic{k}) = NaN; y = yc; y(ic{k}) = NaN;
if sum(~isnan(x(:))) > 0
ph = [ph;pcolor(x',y',sq(tfld)')];
end
if (k==1 & itile == 1); hold on; end
end
% now do this again with extensions above 180 and below -180 degrees
xc = getfield(t(itile).var,'XG');
yc = getfield(t(itile).var,'YG');
im=find(xc<0); xc(im) = xc(im) + 360;
ic{1}=find(xc(:) >+overlap+180);
ic{2}=find(xc(:)-360<-overlap-180);
if mapit; [xc yc]=m_ll2xy(xc,yc,'clipping','on'); end
for k=1:2
x = xc-(k-1)*360;
if mapit; x = xc-(k-1)*2*pi; end
y = yc;
tfld = fld([1:end 1],[1:end 1]); tfld(ic{k}) = NaN;
x(ic{k}) = NaN;
y(ic{k}) = NaN;
if sum(~isnan(x(:))) > 0
ph = [ph;pcolor(x',y',sq(tfld)')];
end
% axis image; shading flat; pause
end
end
axis(gca,'image')
set(gca,'box','on','layer','top')
set(ph,'edgecolor','none')
if mapit
m_grid
else
axis([-2 2 -1 1]*90)
end
end %if
hold off
if holdstatus; hold on; end
if nargout > 0
h = ph;
end
return
|
github
|
P-Chao/acfdetect-master
|
CropPosSample.m
|
.m
|
acfdetect-master/CropPosSample.m
| 25,366 |
utf_8
|
82fa96eca30453d1405adc4ebd3ea773
|
function varargout = CropPosSample(varargin)
% CROPPOSSAMPLE MATLAB code for CropPosSample.fig
% CROPPOSSAMPLE, by itself, creates a new CROPPOSSAMPLE or raises the existing
% singleton*.
%
% H = CROPPOSSAMPLE returns the handle to a new CROPPOSSAMPLE or the handle to
% the existing singleton*.
%
% CROPPOSSAMPLE('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CROPPOSSAMPLE.M with the given input arguments.
%
% CROPPOSSAMPLE('Property','Value',...) creates a new CROPPOSSAMPLE or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before CropPosSample_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to CropPosSample_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help CropPosSample
% Last Modified by GUIDE v2.5 30-Jun-2015 00:19:49
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @CropPosSample_OpeningFcn, ...
'gui_OutputFcn', @CropPosSample_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before CropPosSample is made visible.
function CropPosSample_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to CropPosSample (see VARARGIN)
global imgs imgsDir dataBaseDir mouseDown regionFid fileList;
mouseDown = 0;
% Choose default command line output for CropPosSample
handles.output = hObject;
% Initialize file list box.
dataBaseDir = ['./database'];
imgsDir = [dataBaseDir '/positive/'];
imgs = dir([imgsDir '*.jpg']);
imgsLen = length(imgs);
fileList = [];
for k = 1:imgsLen
fileList = [fileList; {imgs(k).name}];
end
set(handles.fileListBox, 'String', fileList);
regionFid = -1;
% Initialize show area
axes(handles.showArea);
% Update handles structure
guidata(hObject, handles);
imgFileLoad(handles);
% UIWAIT makes CropPosSample wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = CropPosSample_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function imgFileLoad(handles)
global imgs imgsDir dataBaseDir imgShow gtPath regionList areaEndPoint areaStartPoint;
% Show selected image on show area
imgShow = imread([imgsDir imgs(get(handles.fileListBox, 'Value')).name]);
% Initialize regionListBox
[pathSrc, name, ext] = fileparts(imgs(get(handles.fileListBox, 'Value')).name);
regionList = [];
gtPath = [dataBaseDir '/posGt/' name '.txt'];
if(exist(gtPath, 'file'))
regionFid = fopen(gtPath, 'r');
pat = '^\w+ (?<left>\d+) (?<top>\d+) (?<width>\d+) (?<height>\d+) \d+ \d+ \d+ \d+ \d+ \d+ \d+';
while(~feof(regionFid))
lineStr = fgetl(regionFid);
if(lineStr == -1)
break;
end
result = regexp(lineStr, pat, 'names');
if(~isempty(result))
regionList = [regionList; [str2num(result.left), str2num(result.top), str2num(result.width), str2num(result.height)]];
end
end
fclose(regionFid);
else
regionFid = fopen(gtPath, 'w+');
fclose(regionFid);
end
if(isempty(regionList))
regionList = [0 0 0 0];
end
regionListStr = [];
for k = 1:size(regionList, 1)
regionListStr = [regionListStr; {num2str(k)}];
end
set(handles.regionListBox, 'Value', 1);
set(handles.regionListBox, 'String', regionListStr);
region = regionList(1, :);
areaStartPoint(1) = region(1);
areaStartPoint(2) = region(2);
areaEndPoint(1) = region(1) + region(3);
areaEndPoint(2) = region(2) + region(4);
set(handles.leftEdit, 'String', num2str(region(1)));
set(handles.topEdit, 'String', num2str(region(2)));
set(handles.widthEdit, 'String', num2str(region(3)));
set(handles.heightEdit, 'String', num2str(region(4)));
uicontrol(handles.nextButton);
showRegionList(imgShow, regionList, handles);
% --- Executes on selection change in fileListBox.
function fileListBox_Callback(hObject, eventdata, handles)
% hObject handle to fileListBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns fileListBox contents as cell array
% contents{get(hObject,'Value')} returns selected item from fileListBox
imgFileLoad(handles);
% --- Executes during object creation, after setting all properties.
function fileListBox_CreateFcn(hObject, eventdata, handles)
% hObject handle to fileListBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in loadButton.
function loadButton_Callback(hObject, eventdata, handles)
% hObject handle to loadButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global imgs imgsDir dataBaseDir fileList;
dataBaseDir = uigetdir('./samples/post', 'Select a database directory');
imgsDir = [dataBaseDir '/positive/'];
imgs = dir([imgsDir '*.jpg']);
imgsLen = length(imgs);
fileList = [];
for k = 1:imgsLen
fileList = [fileList; {imgs(k).name}];
end
set(handles.fileListBox, 'String', fileList);
% --- Executes on button press in lastButton.
function lastButton_Callback(hObject, eventdata, handles)
% hObject handle to lastButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in nextButton.
function nextButton_Callback(hObject, eventdata, handles)
% hObject handle to nextButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
curr = get(handles.fileListBox, 'Value');
total = size(get(handles.fileListBox, 'String'), 1);
if(curr < total)
curr = curr + 1;
set(handles.fileListBox, 'Value', curr);
imgFileLoad(handles);
end
% --- Executes on mouse motion over figure - except title and menu.
function figure1_WindowButtonMotionFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global areaStartPoint areaEndPoint areaClickPoint mouseDown mouseRegion regionDrawMode;
point = get(handles.showArea, 'currentpoint');
x = round(point(1, 1)); y = round(point(1, 2));
if(mouseDown == 1)
if(regionDrawMode == 0)
areaEndPoint = [x, y];
elseif(regionDrawMode == 1)
dx = x - areaClickPoint(1);
dy = y - areaClickPoint(2);
areaStartPoint(1) = areaStartPoint(1) + dx;
areaStartPoint(2) = areaStartPoint(2) + dy;
areaEndPoint(1) = areaEndPoint(1) + dx;
areaEndPoint(2) = areaEndPoint(2) + dy;
areaClickPoint = [x, y];
elseif(regionDrawMode == 2)
dx = x - areaClickPoint(1);
areaStartPoint(1) = areaStartPoint(1) + dx;
areaClickPoint(1) = x;
elseif(regionDrawMode == 3)
dx = x - areaClickPoint(1);
areaEndPoint(1) = areaEndPoint(1) + dx;
areaClickPoint(1) = x;
elseif(regionDrawMode == 4)
dy = y - areaClickPoint(2);
areaStartPoint(2) = areaStartPoint(2) + dy;
areaClickPoint(2) = y;
elseif(regionDrawMode == 5)
dy = y - areaClickPoint(2);
areaEndPoint(2) = areaEndPoint(2) + dy;
areaClickPoint(2) = y;
end
w = (areaEndPoint(1) - areaStartPoint(1));
h = (areaEndPoint(2) - areaStartPoint(2));
if(w < 0)
w = 0;
end
if(h < 0)
h = 0;
end
if(~isempty('mouseRegin'))
% if(~isempty(mouseRegin))
delete(mouseRegion); %May be some problem
end
mouseRegion = rectangle('Position', [areaStartPoint(1), areaStartPoint(2), w, h]);
end
% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure1_WindowButtonUpFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global areaStartPoint areaEndPoint imgShow mouseDown regionList regionDrawMode;
mouseDown = 0;
regionListIndex = get(handles.regionListBox, 'Value');
if(regionListIndex > 0)
w = (areaEndPoint(1) - areaStartPoint(1));
h = (areaEndPoint(2) - areaStartPoint(2));
if(w < 0)
w = 0;
end
if(h < 0)
h = 0;
end
regionList(regionListIndex, 1) = areaStartPoint(1);
regionList(regionListIndex, 2) = areaStartPoint(2);
regionList(regionListIndex, 3) = w;
regionList(regionListIndex, 4) = h;
set(handles.leftEdit, 'String', num2str(regionList(regionListIndex, 1)));
set(handles.topEdit, 'String', num2str(regionList(regionListIndex, 2)));
set(handles.widthEdit, 'String', num2str(regionList(regionListIndex, 3)));
set(handles.heightEdit, 'String', num2str(regionList(regionListIndex, 4)));
showRegionList(imgShow, regionList, handles);
saveRegionList(regionList);
end
uicontrol(handles.nextButton)
% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure1_WindowButtonDownFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global imgShow areaStartPoint areaEndPoint areaClickPoint mouseDown regionList regionDrawMode;
mouseDown = 1;
point = get(handles.showArea, 'currentpoint');
x = round(point(1, 1)); y = round(point(1, 2));
% Calculate region draw mode
if(areaEndPoint(1) == areaStartPoint(1) || areaEndPoint(2) == areaStartPoint(2))
areaStartPoint = [x, y];
regionDrawMode = 0;
else
dx = (x - areaStartPoint(1)) / (areaEndPoint(1) - areaStartPoint(1));
dy = (y - areaStartPoint(2)) / (areaEndPoint(2) - areaStartPoint(2));
if((dx < -0.2 || dx > 1.2) && (dy < -0.2 || dy > 1.2))
areaStartPoint = [x, y];
regionDrawMode = 0;
elseif((dx > 0.2 && dx < 0.8) && (dy > 0.2 && dy < 0.8))
areaClickPoint = [x, y];
regionDrawMode = 1;
elseif(abs(dx) < 0.1 && (dy > 0.2 && dy < 0.8))
areaClickPoint = [x, y];
regionDrawMode = 2;
elseif((dx > 0.9 && dx < 1.1) && (dy > 0.2 && dy < 0.8))
areaClickPoint = [x, y];
regionDrawMode = 3;
elseif(abs(dy) < 0.1 && (dx > 0.2 && dx < 0.8))
areaClickPoint = [x, y];
regionDrawMode = 4;
elseif((dy > 0.9 && dy < 1.1) && (dx > 0.2 && dx < 0.8))
areaClickPoint = [x, y];
regionDrawMode = 5;
end
end
showRegionList(imgShow, regionList, handles);
% --- Executes on selection change in regionListBox.
function regionListBox_Callback(hObject, eventdata, handles)
% hObject handle to regionListBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns regionListBox contents as cell array
% contents{get(hObject,'Value')} returns selected item from regionListBox
global imgShow regionList areaStartPoint areaEndPoint;
region = regionList(eventdata.Source.Value, :);
regionListIndex = eventdata.Source.Value;
areaStartPoint(1) = regionList(regionListIndex, 1);
areaStartPoint(2) = regionList(regionListIndex, 2);
areaEndPoint(1) = regionList(regionListIndex, 3) + areaStartPoint(1);
areaEndPoint(2) = regionList(regionListIndex, 4) + areaStartPoint(2);
set(handles.leftEdit, 'String', num2str(region(1)));
set(handles.topEdit, 'String', num2str(region(2)));
set(handles.widthEdit, 'String', num2str(region(3)));
set(handles.heightEdit, 'String', num2str(region(4)));
showRegionList(imgShow, regionList, handles);
uicontrol(handles.nextButton)
% --- Executes during object creation, after setting all properties.
function regionListBox_CreateFcn(hObject, eventdata, handles)
% hObject handle to regionListBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function leftEdit_Callback(hObject, eventdata, handles)
% hObject handle to leftEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of leftEdit as text
% str2double(get(hObject,'String')) returns contents of leftEdit as a double
global imgShow regionList;
val = str2num(get(hObject, 'String'));
if(isempty(val))
val = 0;
end
regionList(get(handles.regionListBox, 'Value'), 1) = val;
showRegionList(imgShow, regionList, handles);
% --- Executes during object creation, after setting all properties.
function leftEdit_CreateFcn(hObject, eventdata, handles)
% hObject handle to leftEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function topEdit_Callback(hObject, eventdata, handles)
% hObject handle to topEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of topEdit as text
% str2double(get(hObject,'String')) returns contents of topEdit as a double
global imgShow regionList;
val = str2num(get(hObject, 'String'));
if(isempty(val))
val = 0;
end
regionList(get(handles.regionListBox, 'Value'), 2) = val;
showRegionList(imgShow, regionList, handles);
% --- Executes during object creation, after setting all properties.
function topEdit_CreateFcn(hObject, eventdata, handles)
% hObject handle to topEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function widthEdit_Callback(hObject, eventdata, handles)
% hObject handle to widthEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of widthEdit as text
% str2double(get(hObject,'String')) returns contents of widthEdit as a double
global imgShow regionList;
val = str2num(get(hObject, 'String'));
if(isempty(val))
val = 0;
end
regionList(get(handles.regionListBox, 'Value'), 3) = val;
showRegionList(imgShow, regionList, handles);
% --- Executes during object creation, after setting all properties.
function widthEdit_CreateFcn(hObject, eventdata, handles)
% hObject handle to widthEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function heightEdit_Callback(hObject, eventdata, handles)
% hObject handle to heightEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of heightEdit as text
% str2double(get(hObject,'String')) returns contents of heightEdit as a double
global imgShow regionList;
val = str2num(get(hObject, 'String'));
if(isempty(val))
val = 0;
end
regionList(get(handles.regionListBox, 'Value'), 4) = val;
showRegionList(imgShow, regionList, handles);
% --- Executes during object creation, after setting all properties.
function heightEdit_CreateFcn(hObject, eventdata, handles)
% hObject handle to heightEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function showRegionList(imgShow, regionList, handles)
global regionFid;
imshow(imgShow);
for k = 1:size(regionList, 1)
if(regionList(k, 3) > 0 && regionList(k, 4) > 0)
if(k == get(handles.regionListBox, 'Value'))
rectangle('Position', [regionList(k, 1), regionList(k, 2), regionList(k, 3), regionList(k, 4)], 'EdgeColor', 'blue');
else
rectangle('Position', [regionList(k, 1), regionList(k, 2), regionList(k, 3), regionList(k, 4)], 'EdgeColor', 'red');
end
end
end
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global regionFid;
if(regionFid > 0)
fclose(regionFid);
end
function saveRegionList(regionList)
global gtPath;
%Save region list as ground truth file
regionFid = fopen(gtPath, 'w');
fprintf(regionFid, '%% bbGt version=3\n');
if(regionFid > 0)
for k = 1:size(regionList, 1)
if(regionList(k, 3) > 0 && regionList(k, 4) > 0)
fprintf(regionFid, 'car %d %d %d %d 0 0 0 0 0 0 0\n', regionList(k, 1), regionList(k, 2), regionList(k, 3), regionList(k, 4));
end
end
end
fclose(regionFid);
% --- Executes on button press in addRegionButton.
function addRegionButton_Callback(hObject, eventdata, handles)
% hObject handle to addRegionButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global regionList areaStartPoint areaEndPoint;
areaStartPoint = [0 0];
areaEndPoint = [0 0];
regionList = [regionList; [0 0 0 0]];
regionListStr = get(handles.regionListBox, 'String');
regionListLen = size(regionList, 1);
regionListStr = [regionListStr; {num2str(regionListLen)}];
set(handles.regionListBox, 'String', regionListStr);
set(handles.regionListBox, 'Value', regionListLen);
saveRegionList(regionList);
uicontrol(handles.nextButton)
% --- Executes on button press in delRegionButton.
function delRegionButton_Callback(hObject, eventdata, handles)
% hObject handle to delRegionButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global imgShow regionList;
regionList(get(handles.regionListBox, 'Value'), :) = [];
regionListStr = [];
for k = 1:size(get(handles.regionListBox, 'String'), 1)-1
regionListStr = [regionListStr, {num2str(k)}];
end
set(handles.regionListBox, 'String', regionListStr);
set(handles.regionListBox, 'Value', 1);
showRegionList(imgShow, regionList, handles);
saveRegionList(regionList);
uicontrol(handles.nextButton);
% --- Executes on key press with focus on figure1 and none of its controls.
function figure1_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.FIGURE)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
uicontrol(handles.nextButton)
nextButton_KeyPressFcn(handles.nextButton, eventdata, handles);
% --- Executes on key press with focus on nextButton and none of its controls.
function nextButton_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to nextButton (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
global areaStartPoint areaEndPoint imgShow regionList;
if(size(regionList, 1) > 0)
region = regionList(get(handles.regionListBox, 'Value'), :);
if(strcmp(eventdata.Key, 'leftarrow'))
left = region(1);
if(left >= 1)
left = left - 1;
end
region(1) = left;
elseif(strcmp(eventdata.Key, 'rightarrow'))
left = region(1);
left = left + 1;
region(1) = left;
elseif(strcmp(eventdata.Key, 'uparrow'))
up = region(2);
if(up >= 1)
up = up - 1;
end
region(2) = up;
elseif(strcmp(eventdata.Key, 'downarrow'))
up = region(2);
up = up + 1;
region(2) = up;
elseif(strcmp(eventdata.Key, 'escape'))
region = [0 0 0 0];
end
areaStartPoint(1) = region(1);
areaStartPoint(2) = region(2);
areaEndPoint(1) = region(1) + region(3);
areaStartPoint(2) = region(2) + region(4);
set(handles.leftEdit, 'String', num2str(region(1)));
set(handles.topEdit, 'String', num2str(region(2)));
set(handles.widthEdit, 'String', num2str(region(3)));
set(handles.heightEdit, 'String', num2str(region(4)));
regionList(get(handles.regionListBox, 'Value'), :) = region;
showRegionList(imgShow, regionList, handles);
saveRegionList(regionList);
end
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over nextButton.
function nextButton_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to nextButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in deleteButton.
function deleteButton_Callback(hObject, eventdata, handles)
% hObject handle to deleteButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global imgs imgsDir fileList;
%Delete the showing image
delete([imgsDir imgs(get(handles.fileListBox, 'Value')).name]);
lastIndex = get(handles.fileListBox, 'Value');
fileList(lastIndex) = [];
set(handles.fileListBox, 'String', fileList);
if(lastIndex > length(fileList))
lastIndex = length(fileList);
end
imgs = dir([imgsDir '*.jpg']);
set(handles.fileListBox, 'Value', lastIndex);
imgFileLoad(handles);
% --- Executes during object deletion, before destroying properties.
function deleteButton_DeleteFcn(hObject, eventdata, handles)
% hObject handle to deleteButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
|
github
|
P-Chao/acfdetect-master
|
chnsCompute.m
|
.m
|
acfdetect-master/toolbox/channels/chnsCompute.m
| 9,241 |
UNKNOWN
|
10cd4fb60e464bb5aeceab01ff4b499e
|
function chns = chnsCompute( I, varargin )
% Compute channel features at a single scale given an input image.
%
% Compute the channel features as described in:
% P. Doll�r, Z. Tu, P. Perona and S. Belongie
% "Integral Channel Features", BMVC 2009.
% Channel features have proven very effective in sliding window object
% detection, both in terms of *accuracy* and *speed*. Numerous feature
% types including histogram of gradients (hog) can be converted into
% channel features, and overall, channels are general and powerful.
%
% Given an input image I, a corresponding channel is a registered map of I,
% where the output pixels are computed from corresponding patches of input
% pixels (thus preserving overall image layout). A trivial channel is
% simply the input grayscale image, likewise for a color image each color
% channel can serve as a channel. Other channels can be computed using
% linear or non-linear transformations of I, various choices implemented
% here are described below. The only constraint is that channels must be
% translationally invariant (i.e. translating the input image or the
% resulting channels gives the same result). This allows for fast object
% detection, as the channels can be computed once on the entire image
% rather than separately for each overlapping detection window.
%
% Currently, three channel types are available by default (to date, these
% have proven the most effective for sliding window object detection):
% (1) color channels (computed using rgbConvert.m)
% (2) gradient magnitude (computed using gradientMag.m)
% (3) quantized gradient channels (computed using gradientHist.m)
% For more information about each channel type, including the exact input
% parameters and their meanings, see the respective m-files which perform
% the actual computatons (chnsCompute is essentially a wrapper function).
% The converted color channels serve as input to gradientMag/gradientHist.
%
% Additionally, custom channels can be specified via an optional struct
% array "pCustom" which may have 0 or more custom channel definitions. Each
% custom channel is generated via a call to "chns=feval(hFunc,I,pFunc{:})".
% The color space of I is determined by pColor.colorSpace, use the setting
% colorSpace='orig' if the input image is not an 'rgb' image and should be
% left unchanged (e.g. if I has multiple channels). The input I will have
% type single and the output of hFunc should also have type single.
%
% "shrink" (which should be an integer) determines the amount to subsample
% the computed channels (in applications such as detection subsamping does
% not affect performance). The params for each channel type are described
% in detail in the respective function. In addition, each channel type has
% a param "enabled" that determines if the channel is computed. If
% chnsCompute() is called with no inputs, the output is the complete
% default params (pChns). Otherwise the outputs are the computed channels
% and additional meta-data (see below). The channels are computed at a
% single scale, for (fast) multi-scale channel computation see chnsPyramid.
%
% An emphasis has been placed on speed, with the code undergoing heavy
% optimization. Computing the full set of channels used in the BMVC09 paper
% referenced above on a 480x640 image runs over *100 fps* on a single core
% of a machine from 2011 (although runtime depends on input parameters).
%
% USAGE
% pChns = chnsCompute()
% chns = chnsCompute( I, pChns )
%
% INPUTS
% I - [hxwx3] input image (uint8 or single/double in [0,1])
% pChns - parameters (struct or name/value pairs)
% .shrink - [4] integer downsampling amount for channels
% .pColor - parameters for color space:
% .enabled - [1] if true enable color channels
% .smooth - [1] radius for image smoothing (using convTri)
% .colorSpace - ['luv'] choices are: 'gray', 'rgb', 'hsv', 'orig'
% .pGradMag - parameters for gradient magnitude:
% .enabled - [1] if true enable gradient magnitude channel
% .colorChn - [0] if>0 color channel to use for grad computation
% .normRad - [5] normalization radius for gradient
% .normConst - [.005] normalization constant for gradient
% .full - [0] if true compute angles in [0,2*pi) else in [0,pi)
% .pGradHist - parameters for gradient histograms:
% .enabled - [1] if true enable gradient histogram channels
% .binSize - [shrink] spatial bin size (defaults to shrink)
% .nOrients - [6] number of orientation channels
% .softBin - [0] if true use "soft" bilinear spatial binning
% .useHog - [0] if true perform 4-way hog normalization/clipping
% .clipHog - [.2] value at which to clip hog histogram bins
% .pCustom - parameters for custom channels (optional struct array):
% .enabled - [1] if true enable custom channel type
% .name - ['REQ'] custom channel type name
% .hFunc - ['REQ'] function handle for computing custom channels
% .pFunc - [{}] additional params for chns=hFunc(I,pFunc{:})
% .padWith - [0] how channel should be padded (e.g. 0,'replicate')
% .complete - [] if true does not check/set default vals in pChns
%
% OUTPUTS
% chns - output struct
% .pChns - exact input parameters used
% .nTypes - number of channel types
% .data - [nTypes x 1] cell [h/shrink x w/shrink x nChns] channels
% .info - [nTypes x 1] struct array
% .name - channel type name
% .pChn - exact input parameters for given channel type
% .nChns - number of channels for given channel type
% .padWith - how channel should be padded (0,'replicate')
%
% EXAMPLE - default channels
% I=imResample(imread('peppers.png'),[480 640]); pChns=chnsCompute();
% tic, for i=1:100, chns=chnsCompute(I,pChns); end; toc
% figure(1); montage2(cat(3,chns.data{:}));
%
% EXAMPLE - default + custom channels
% I=imResample(imread('peppers.png'),[480 640]); pChns=chnsCompute();
% hFunc=@(I) 5*sqrt(max(0,max(convBox(I.^2,2)-convBox(I,2).^2,[],3)));
% pChns.pCustom=struct('name','Std02','hFunc',hFunc); pChns.complete=0;
% tic, chns=chnsCompute(I,pChns); toc
% figure(1); im(chns.data{4});
%
% See also rgbConvert, gradientMag, gradientHist, chnsPyramid
%
% Piotr's Computer Vision Matlab Toolbox Version 3.23
% Copyright 2014 Piotr Dollar & Ron Appel. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get default parameters pChns
if(nargin==2), pChns=varargin{1}; else pChns=[]; end
if( ~isfield(pChns,'complete') || pChns.complete~=1 || isempty(I) )
p=struct('enabled',{},'name',{},'hFunc',{},'pFunc',{},'padWith',{});
pChns = getPrmDflt(varargin,{'shrink',4,'pColor',{},'pGradMag',{},...
'pGradHist',{},'pCustom',p,'complete',1},1);
pChns.pColor = getPrmDflt( pChns.pColor, {'enabled',1,...
'smooth',1, 'colorSpace','luv'}, 1 );
pChns.pGradMag = getPrmDflt( pChns.pGradMag, {'enabled',1,...
'colorChn',0,'normRad',5,'normConst',.005,'full',0}, 1 );
pChns.pGradHist = getPrmDflt( pChns.pGradHist, {'enabled',1,...
'binSize',[],'nOrients',6,'softBin',0,'useHog',0,'clipHog',.2}, 1 );
nc=length(pChns.pCustom); pc=cell(1,nc);
for i=1:nc, pc{i} = getPrmDflt( pChns.pCustom(i), {'enabled',1,...
'name','REQ','hFunc','REQ','pFunc',{},'padWith',0}, 1 ); end
if( nc>0 ), pChns.pCustom=[pc{:}]; end
end
if(nargin==0), chns=pChns; return; end
% create output struct
info=struct('name',{},'pChn',{},'nChns',{},'padWith',{});
chns=struct('pChns',pChns,'nTypes',0,'data',{{}},'info',info);
% crop I so divisible by shrink and get target dimensions
shrink=pChns.shrink; [h,w,~]=size(I); cr=mod([h w],shrink);
if(any(cr)), h=h-cr(1); w=w-cr(2); I=I(1:h,1:w,:); end
h=h/shrink; w=w/shrink;
% compute color channels
p=pChns.pColor; nm='color channels';
I=rgbConvert(I,p.colorSpace);
I=convTri(I,p.smooth);
if(p.enabled), chns=addChn(chns,I,nm,p,'replicate',h,w); end
% compute gradient magnitude channel
p=pChns.pGradMag; nm='gradient magnitude';
full=0; if(isfield(p,'full')), full=p.full; end
if( pChns.pGradHist.enabled )
[M,O]=gradientMag(I,p.colorChn,p.normRad,p.normConst,full);
elseif( p.enabled )
M=gradientMag(I,p.colorChn,p.normRad,p.normConst,full);
end
if(p.enabled), chns=addChn(chns,M,nm,p,0,h,w); end
% compute gradient histgoram channels
p=pChns.pGradHist; nm='gradient histogram';
if( p.enabled )
binSize=p.binSize; if(isempty(binSize)), binSize=shrink; end
H=gradientHist(M,O,binSize,p.nOrients,p.softBin,p.useHog,p.clipHog,full);
chns=addChn(chns,H,nm,pChns.pGradHist,0,h,w);
end
% compute custom channels
p=pChns.pCustom;
for i=find( [p.enabled] )
C=feval(p(i).hFunc,I,p(i).pFunc{:});
chns=addChn(chns,C,p(i).name,p(i),p(i).padWith,h,w);
end
end
function chns = addChn( chns, data, name, pChn, padWith, h, w )
% Helper function to add a channel to chns.
[h1,w1,~]=size(data);
if(h1~=h || w1~=w), data=imResampleMex(data,h,w,1);
assert(all(mod([h1 w1]./[h w],1)==0)); end
chns.data{end+1}=data; chns.nTypes=chns.nTypes+1;
chns.info(end+1)=struct('name',name,'pChn',pChn,...
'nChns',size(data,3),'padWith',padWith);
end
|
github
|
P-Chao/acfdetect-master
|
imagesAlign.m
|
.m
|
acfdetect-master/toolbox/videos/imagesAlign.m
| 8,167 |
utf_8
|
d125eb5beb502d940be5bd145521f34b
|
function [H,Ip] = imagesAlign( I, Iref, varargin )
% Fast and robust estimation of homography relating two images.
%
% The algorithm for image alignment is a simple but effective variant of
% the inverse compositional algorithm. For a thorough overview, see:
% "Lucas-kanade 20 years on A unifying framework,"
% S. Baker and I. Matthews. IJCV 2004.
% The implementation is optimized and can easily run at 20-30 fps.
%
% type may take on the following values:
% 'translation' - translation only
% 'rigid' - translation and rotation
% 'similarity' - translation, rotation and scale
% 'affine' - 6 parameter affine transform
% 'rotation' - pure rotation (about x, y and z)
% 'projective' - full 8 parameter homography
% Alternatively, type may be a vector of ids between 1 and 8, specifying
% exactly the types of transforms allowed. The ids correspond, to: 1:
% translate-x, 2: translate-y, 3: uniform scale, 4: shear, 5: non-uniform
% scale, 6: rotate-z, 7: rotate-x, 8: rotate-y. For example, to specify
% translation use type=[1,2]. If the transforms don't form a group, the
% returned homography may have more degrees of freedom than expected.
%
% Parameters (in rough order of importance): [resample] controls image
% downsampling prior to computing H. Runtime is proportional to area, so
% using resample<1 can dramatically speed up alignment, and in general not
% degrade performance much. [sig] controls image smoothing, sig=2 gives
% good performance, setting sig too low causes loss of information and too
% high will violate the linearity assumption. [epsilon] defines the
% stopping criteria, use to adjust performance versus speed tradeoff.
% [lambda] is a regularization term that causes small transforms to be
% favored, in general any small non-zero setting of lambda works well.
% [outThr] is a threshold beyond which pixels are considered outliers, be
% careful not to set too low. [minArea] determines coarsest scale beyond
% which the image is not downsampled (should not be set too low). [H0] can
% be used to specify an initial alignment. Use [show] to display results.
%
% USAGE
% [H,Ip] = imagesAlign( I, Iref, varargin )
%
% INPUTS
% I - transformed version of I
% Iref - reference grayscale double image
% varargin - additional params (struct or name/value pairs)
% .type - ['projective'] see above for options
% .resample - [1] image resampling prior to homography estimation
% .sig - [2] amount of Gaussian spatial smoothing to apply
% .epsilon - [1e-3] stopping criteria (min change in error)
% .lambda - [1e-6] regularization term favoring small transforms
% .outThr - [inf] outlier threshold
% .minArea - [4096] minimum image area in coarse to fine search
% .H0 - [eye(3)] optional initial homography estimate
% .show - [0] optionally display results in figure show
%
% OUTPUTS
% H - estimated homography to transform I into Iref
% Ip - tranformed version of I (slow to compute)
%
% EXAMPLE
% Iref = double(imread('cameraman.tif'))/255;
% H0 = [eye(2)+randn(2)*.1 randn(2,1)*10; randn(1,2)*1e-3 1];
% I = imtransform2(Iref,H0^-1,'pad','replicate');
% o=50; P=ones(o)*1; I(150:149+o,150:149+o)=P;
% prmAlign={'outThr',.1,'resample',.5,'type',1:8,'show'};
% [H,Ip]=imagesAlign(I,Iref,prmAlign{:},1);
% tic, for i=1:30, H=imagesAlign(I,Iref,prmAlign{:},0); end;
% t=toc; fprintf('average fps: %f\n',30/t)
%
% See also imTransform2
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get parameters
dfs={'type','projective','resample',1,'sig',2,'epsilon',1e-3,...
'lambda',1e-6,'outThr',inf,'minArea',4096,'H0',eye(3),'show',0};
[type,resample,sig,epsilon,lambda,outThr,minArea,H0,show] = ...
getPrmDflt(varargin,dfs,1);
filt = filterGauss(2*ceil(sig*2.5)+1,[],sig^2);
% determine type of transformation to recover
if(isnumeric(type)), assert(length(type)<=8); else
id=find(strcmpi(type,{'translation','rigid','similarity','affine',...
'rotation','projective'})); msgId='piotr:imagesAlign';
if(isempty(id)), error(msgId,'unknown type: %s',type); end
type={1:2,[1:2 6],[1:3 6],1:6,6:8,1:8}; type=type{id};
end; keep=zeros(1,8); keep(type)=1; keep=keep>0;
% compute image alignment (optionally resample first)
prm={keep,filt,epsilon,H0,minArea,outThr,lambda};
if( resample==1 ), H=imagesAlign1(I,Iref,prm); else
S=eye(3); S([1 5])=resample; H0=S*H0*S^-1; prm{4}=H0;
I1=imResample(I,resample); Iref1=imResample(Iref,resample);
H=imagesAlign1(I1,Iref1,prm); H=S^-1*H*S;
end
% optionally rectify I and display results (can be expensive)
if(nargout==1 && show==0), return; end
Ip = imtransform2(I,H,'pad','replicate');
if(show), figure(show); clf; s=@(i) subplot(2,3,i);
Is=[I Iref Ip]; ri=[min(Is(:)) max(Is(:))];
D0=abs(I-Iref); D1=abs(Ip-Iref); Ds=[D0 D1]; di=[min(Ds(:)) max(Ds(:))];
s(1); im(I,ri,0); s(2); im(Iref,ri,0); s(3); im(D0,di,0);
s(4); im(Ip,ri,0); s(5); im(Iref,ri,0); s(6); im(D1,di,0);
s(3); title('|I-Iref|'); s(6); title('|Ip-Iref|');
end
end
function H = imagesAlign1( I, Iref, prm )
% apply recursively if image large
[keep,filt,epsilon,H0,minArea,outThr,lambda]=deal(prm{:});
[h,w]=size(I); hc=mod(h,2); wc=mod(w,2);
if( w*h<minArea ), H=H0; else
I1=imResample(I(1:(h-hc),1:(w-wc)),.5);
Iref1=imResample(Iref(1:(h-hc),1:(w-wc)),.5);
S=eye(3); S([1 5])=2; H0=S^-1*H0*S; prm{4}=H0;
H=imagesAlign1(I1,Iref1,prm); H=S*H*S^-1;
end
% smooth images (pad first so dimensions unchanged)
O=ones(1,(length(filt)-1)/2); hs=[O 1:h h*O]; ws=[O 1:w w*O];
Iref=conv2(conv2(Iref(hs,ws),filt','valid'),filt,'valid');
I=conv2(conv2(I(hs,ws),filt','valid'),filt,'valid');
% pad images with nan so later can determine valid regions
hs=[1 1 1:h h h]; ws=[1 1 1:w w w]; I=I(hs,ws); Iref=Iref(hs,ws);
hs=[1:2 h+3:h+4]; I(hs,:)=nan; Iref(hs,:)=nan;
ws=[1:2 w+3:w+4]; I(:,ws)=nan; Iref(:,ws)=nan;
% convert weights hardcoded for 128x128 image to given image dims
wts=[1 1 1.0204 .03125 1.0313 0.0204 .00055516 .00055516];
s=sqrt(numel(Iref))/128;
wts=[wts(1:2) wts(3)^(1/s) wts(4)/s wts(5)^(1/s) wts(6)/s wts(7:8)/(s*s)];
% prepare subspace around Iref
[~,Hs]=ds2H(-ones(1,8),wts); Hs=Hs(:,:,keep); K=size(Hs,3);
[h,w]=size(Iref); Ts=zeros(h,w,K); k=0;
if(keep(1)), k=k+1; Ts(:,1:end-1,k)=Iref(:,2:end); end
if(keep(2)), k=k+1; Ts(1:end-1,:,k)=Iref(2:end,:); end
pTransf={'method','bilinear','pad','none','useCache'};
for i=k+1:K, Ts(:,:,i)=imtransform2(Iref,Hs(:,:,i),pTransf{:},1); end
Ds=Ts-Iref(:,:,ones(1,K)); Mref = ~any(isnan(Ds),3);
if(0), figure(10); montage2(Ds); end
Ds = reshape(Ds,[],size(Ds,3));
% iteratively project Ip onto subspace, storing transformation
lambda=lambda*w*h*eye(K); ds=zeros(1,8); err=inf;
for i=1:100
s=svd(H); if(s(3)<=1e-4*s(1)), H=eye(3); return; end
Ip=imtransform2(I,H,pTransf{:},0); dI=Ip-Iref; dI0=abs(dI);
M=Mref & ~isnan(Ip); M0=M; if(outThr<inf), M=M & dI0<outThr; end
M1=find(M); D=Ds(M1,:); ds1=(D'*D + lambda)^(-1)*(D'*dI(M1));
if(any(isnan(ds1))), ds1=zeros(K,1); end
ds(keep)=ds1; H1=ds2H(ds,wts); H=H*H1; H=H/H(9);
err0=err; err=dI0; err(~M0)=0; err=mean2(err); del=err0-err;
if(0), fprintf('i=%03i err=%e del=%e\n',i,err,del); end
if( del<epsilon ), break; end
end
end
function [H,Hs] = ds2H( ds, wts )
% compute homography from offsets ds
Hs=eye(3); Hs=Hs(:,:,ones(1,8));
Hs(2,3,1)=wts(1)*ds(1); % 1 x translation
Hs(1,3,2)=wts(2)*ds(2); % 2 y translation
Hs(1:2,1:2,3)=eye(2)*wts(3)^ds(3); % 3 scale
Hs(2,1,4)=wts(4)*ds(4); % 4 shear
Hs(1,1,5)=wts(5)^ds(5); % 5 scale non-uniform
ct=cos(wts(6)*ds(6)); st=sin(wts(6)*ds(6));
Hs(1:2,1:2,6)=[ct -st; st ct]; % 6 rotation about z
ct=cos(wts(7)*ds(7)); st=sin(wts(7)*ds(7));
Hs([1 3],[1 3],7)=[ct -st; st ct]; % 7 rotation about x
ct=cos(wts(8)*ds(8)); st=sin(wts(8)*ds(8));
Hs(2:3,2:3,8)=[ct -st; st ct]; % 8 rotation about y
H=eye(3); for i=1:8, H=Hs(:,:,i)*H; end
end
|
github
|
P-Chao/acfdetect-master
|
opticalFlow.m
|
.m
|
acfdetect-master/toolbox/videos/opticalFlow.m
| 7,361 |
utf_8
|
b97e8c1f623eca07c6f1a0fff26d171e
|
function [Vx,Vy,reliab] = opticalFlow( I1, I2, varargin )
% Coarse-to-fine optical flow using Lucas&Kanade or Horn&Schunck.
%
% Implemented 'type' of optical flow estimation:
% LK: http://en.wikipedia.org/wiki/Lucas-Kanade_method
% HS: http://en.wikipedia.org/wiki/Horn-Schunck_method
% SD: Simple block-based sum of absolute differences flow
% LK is a local, fast method (the implementation is fully vectorized).
% HS is a global, slower method (an SSE implementation is provided).
% SD is a simple but potentially expensive approach.
%
% Common parameters: 'smooth' determines smoothing prior to computing flow
% and can make flow estimation more robust. 'filt' determines amount of
% median filtering of the computed flow field which improves results but is
% costly. 'minScale' and 'maxScale' control image scales in the pyramid.
% Setting 'maxScale'<1 results in faster but lower quality results, e.g.
% maxScale=.5 makes flow computation about 4x faster. Method specific
% parameters: 'radius' controls window size (and smoothness of flow) for LK
% and SD. 'nBlock' determines number of blocks tested in each direction for
% SD, computation time is O(nBlock^2). For HS, 'alpha' controls tradeoff
% between data and smoothness term (and smoothness of flow) and 'nIter'
% determines number of gradient decent steps.
%
% USAGE
% [Vx,Vy,reliab] = opticalFlow( I1, I2, pFlow )
%
% INPUTS
% I1, I2 - input images to calculate flow between
% pFlow - parameters (struct or name/value pairs)
% .type - ['LK'] may be 'LK', 'HS' or 'SD'
% .smooth - [1] smoothing radius for triangle filter (may be 0)
% .filt - [0] median filtering radius for smoothing flow field
% .minScale - [1/64] minimum pyramid scale (must be a power of 2)
% .maxScale - [1] maximum pyramid scale (must be a power of 2)
% .radius - [10] integration radius for weighted window [LK/SD only]
% .nBlock - [5] number of tested blocks [SD only]
% .alpha - [1] smoothness constraint [HS only]
% .nIter - [250] number of iterations [HS only]
%
% OUTPUTS
% Vx, Vy - x,y components of flow [Vx>0->right, Vy>0->down]
% reliab - reliability of flow in given window
%
% EXAMPLE - compute LK flow on test images
% load opticalFlowTest;
% [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK');
% figure(1); im(I1); figure(2); im(I2);
% figure(3); im([Vx Vy]); colormap jet;
%
% EXAMPLE - rectify I1 to I2 using computed flow
% load opticalFlowTest;
% [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK');
% I1=imtransform2(I1,[],'vs',-Vx,'us',-Vy,'pad','replicate');
% figure(1); im(I1); figure(2); im(I2);
%
% EXAMPLE - compare LK/HS/SD flows
% load opticalFlowTest;
% prm={'smooth',1,'radius',10,'alpha',20,'nIter',250,'type'};
% tic, [Vx1,Vy1]=opticalFlow(I1,I2,prm{:},'LK'); toc
% tic, [Vx2,Vy2]=opticalFlow(I1,I2,prm{:},'HS'); toc
% tic, [Vx3,Vy3]=opticalFlow(I1,I2,prm{:},'SD','minScale',1); toc
% figure(1); im([Vx1 Vy1; Vx2 Vy2; Vx3 Vy3]); colormap jet;
%
% See also convTri, imtransform2, medfilt2
%
% Piotr's Computer Vision Matlab Toolbox Version 3.24
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get default parameters and do error checking
dfs={ 'type','LK', 'smooth',1, 'filt',0, 'minScale',1/64, ...
'maxScale',1, 'radius',10, 'nBlock',5, 'alpha',1, 'nIter',250 };
[type,smooth,filt,minScale,maxScale,radius,nBlock,alpha,nIter] = ...
getPrmDflt(varargin,dfs,1);
assert(any(strcmp(type,{'LK','HS','SD'})));
if( ~ismatrix(I1) || ~ismatrix(I2) || any(size(I1)~=size(I2)) )
error('Input images must be 2D and have same dimensions.'); end
% run optical flow in coarse to fine fashion
if(~isa(I1,'single')), I1=single(I1); I2=single(I2); end
[h,w]=size(I1); nScales=max(1,floor(log2(min([h w 1/minScale])))+1);
for s=1:max(1,nScales + round(log2(maxScale)))
% get current scale and I1s and I2s at given scale
scale=2^(nScales-s); h1=round(h/scale); w1=round(w/scale);
if( scale==1 ), I1s=I1; I2s=I2; else
I1s=imResample(I1,[h1 w1]); I2s=imResample(I2,[h1 w1]); end
% initialize Vx,Vy or upsample from previous scale
if(s==1), Vx=zeros(h1,w1,'single'); Vy=Vx; else r=sqrt(h1*w1/numel(Vx));
Vx=imResample(Vx,[h1 w1])*r; Vy=imResample(Vy,[h1 w1])*r; end
% transform I2s according to current estimate of Vx and Vy
if(s>1), I2s=imtransform2(I2s,[],'pad','replciate','vs',Vx,'us',Vy); end
% smooth images
I1s=convTri(I1s,smooth); I2s=convTri(I2s,smooth);
% run optical flow on current scale
switch type
case 'LK', [Vx1,Vy1,reliab]=opticalFlowLk(I1s,I2s,radius);
case 'HS', [Vx1,Vy1,reliab]=opticalFlowHs(I1s,I2s,alpha,nIter);
case 'SD', [Vx1,Vy1,reliab]=opticalFlowSd(I1s,I2s,radius,nBlock,1);
end
Vx=Vx+Vx1; Vy=Vy+Vy1;
% finally median filter the resulting flow field
if(filt), Vx=medfilt2(Vx,[filt filt],'symmetric'); end
if(filt), Vy=medfilt2(Vy,[filt filt],'symmetric'); end
end
r=sqrt(h*w/numel(Vx));
if(r~=1), Vx=imResample(Vx,[h w])*r; Vy=imResample(Vy,[h w])*r; end
if(r~=1 && nargout==3), reliab=imResample(reliab,[h w]); end
end
function [Vx,Vy,reliab] = opticalFlowLk( I1, I2, radius )
% Compute elements of A'A and also of A'b
radius=min(radius,floor(min(size(I1,1),size(I1,2))/2)-1);
[Ix,Iy]=gradient2(I1); It=I2-I1; AAxy=convTri(Ix.*Iy,radius);
AAxx=convTri(Ix.^2,radius)+1e-5; ABxt=convTri(-Ix.*It,radius);
AAyy=convTri(Iy.^2,radius)+1e-5; AByt=convTri(-Iy.*It,radius);
% Find determinant and trace of A'A
AAdet=AAxx.*AAyy-AAxy.^2; AAdeti=1./AAdet; AAtr=AAxx+AAyy;
% Compute components of velocity vectors (A'A)^-1 * A'b
Vx = AAdeti .* ( AAyy.*ABxt - AAxy.*AByt);
Vy = AAdeti .* (-AAxy.*ABxt + AAxx.*AByt);
% Check for ill conditioned second moment matrices
reliab = 0.5*AAtr - 0.5*sqrt(AAtr.^2-4*AAdet);
end
function [Vx,Vy,reliab] = opticalFlowHs( I1, I2, alpha, nIter )
% compute derivatives (averaging over 2x2 neighborhoods)
pad = @(I,p) imPad(I,p,'replicate');
crop = @(I,c) I(1+c:end-c,1+c:end-c);
Ex = I1(:,2:end)-I1(:,1:end-1) + I2(:,2:end)-I2(:,1:end-1);
Ey = I1(2:end,:)-I1(1:end-1,:) + I2(2:end,:)-I2(1:end-1,:);
Ex = Ex/4; Ey = Ey/4; Et = (I2-I1)/4;
Ex = pad(Ex,[1 1 1 2]) + pad(Ex,[0 2 1 2]);
Ey = pad(Ey,[1 2 1 1]) + pad(Ey,[1 2 0 2]);
Et=pad(Et,[0 2 1 1])+pad(Et,[1 1 1 1])+pad(Et,[1 1 0 2])+pad(Et,[0 2 0 2]);
Z=1./(alpha*alpha + Ex.*Ex + Ey.*Ey); reliab=crop(Z,1);
% iterate updating Ux and Vx in each iter
if( 1 )
[Vx,Vy]=opticalFlowHsMex(Ex,Ey,Et,Z,nIter);
Vx=crop(Vx,1); Vy=crop(Vy,1);
else
Ex=crop(Ex,1); Ey=crop(Ey,1); Et=crop(Et,1); Z=crop(Z,1);
Vx=zeros(size(I1),'single'); Vy=Vx;
f=single([0 1 0; 1 0 1; 0 1 0])/4;
for i = 1:nIter
Mx=conv2(Vx,f,'same'); My=conv2(Vy,f,'same');
m=(Ex.*Mx+Ey.*My+Et).*Z; Vx=Mx-Ex.*m; Vy=My-Ey.*m;
end
end
end
function [Vx,Vy,reliab] = opticalFlowSd( I1, I2, radius, nBlock, step )
% simple block-based sum of absolute differences flow
[h,w]=size(I1); k=2*nBlock+1; k=k*k; D=zeros(h,w,k,'single'); k=1;
rng = @(x,w) max(1+x*step,1):min(w+x*step,w);
for x=-nBlock:nBlock, xs0=rng(x,w); xs1=rng(-x,w);
for y=-nBlock:nBlock, ys0=rng(y,h); ys1=rng(-y,h);
D(ys0,xs0,k)=abs(I1(ys0,xs0)-I2(ys1,xs1)); k=k+1;
end
end
D=convTri(D,radius); [reliab,D]=min(D,[],3);
k=2*nBlock+1; Vy=mod(D-1,k)+1; Vx=(D-Vy)/k+1;
Vy=(nBlock+1-Vy)*step; Vx=(nBlock+1-Vx)*step;
end
|
github
|
P-Chao/acfdetect-master
|
seqWriterPlugin.m
|
.m
|
acfdetect-master/toolbox/videos/seqWriterPlugin.m
| 8,280 |
utf_8
|
597792f79fff08b8bb709313267c3860
|
function varargout = seqWriterPlugin( cmd, h, varargin )
% Plugin for seqIo and videoIO to allow writing of seq files.
%
% Do not call directly, use as plugin for seqIo or videoIO instead.
% The following is a list of commands available (swp=seqWriterPlugin):
% h=swp('open',h,fName,info) % Open a seq file for writing (h ignored).
% h=swp('close',h) % Close seq file (output h is -1).
% swp('addframe',h,I,[ts]) % Writes video frame (and timestamp).
% swp('addframeb',h,I,[ts]) % Writes video frame with no encoding.
% info = swp('getinfo',h) % Return struct with info about video.
%
% The following params must be specified in struct 'info' upon opening:
% width - frame width
% height - frame height
% fps - frames per second
% quality - [80] compression quality (0 to 100)
% codec - string representing codec, options include:
% 'monoraw'/'imageFormat100' - black/white uncompressed
% 'raw'/'imageFormat200' - color (BGR) uncompressed
% 'monojpg'/'imageFormat102' - black/white jpg compressed
% 'jpg'/'imageFormat201' - color jpg compressed
% 'monopng'/'imageFormat001' - black/white png compressed
% 'png'/'imageFormat002' - color png compressed
%
% USAGE
% varargout = seqWriterPlugin( cmd, h, varargin )
%
% INPUTS
% cmd - string indicating operation to perform
% h - unique identifier for open seq file
% varargin - additional options (vary according to cmd)
%
% OUTPUTS
% varargout - output (varies according to cmd)
%
% EXAMPLE
%
% See also SEQIO, SEQREADERPLUGIN
%
% Piotr's Computer Vision Matlab Toolbox Version 2.66
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% persistent variables to keep track of all loaded .seq files
persistent h1 hs fids infos tNms;
if(isempty(h1)), h1=int32(now); hs=int32([]); infos={}; tNms={}; end
nIn=nargin-2; in=varargin; o1=[]; cmd=lower(cmd);
% open seq file
if(strcmp(cmd,'open'))
chk(nIn,2); h=length(hs)+1; hs(h)=h1; varargout={h1}; h1=h1+1;
[pth,name]=fileparts(in{1}); if(isempty(pth)), pth='.'; end
fName=[pth filesep name];
[infos{h},fids(h),tNms{h}]=open(fName,in{2}); return;
end
% Get the handle for this instance
[v,h]=ismember(h,hs); if(~v), error('Invalid load plugin handle'); end
fid=fids(h); info=infos{h}; tNm=tNms{h};
% close seq file
if(strcmp(cmd,'close'))
writeHeader(fid,info);
chk(nIn,0); varargout={-1}; fclose(fid); kp=[1:h-1 h+1:length(hs)];
hs=hs(kp); fids=fids(kp); infos=infos(kp);
tNms=tNms(kp); if(exist(tNm,'file')), delete(tNm); end; return;
end
% perform appropriate operation
switch( cmd )
case 'addframe', chk(nIn,1,2); info=addFrame(fid,info,tNm,1,in{:});
case 'addframeb', chk(nIn,1,2); info=addFrame(fid,info,tNm,0,in{:});
case 'getinfo', chk(nIn,0); o1=info;
otherwise, error(['Unrecognized command: "' cmd '"']);
end
infos{h}=info; varargout={o1};
end
function chk(nIn,nMin,nMax)
if(nargin<3), nMax=nMin; end
if(nIn>0 && nMin==0 && nMax==0), error(['"' cmd '" takes no args.']); end
if(nIn<nMin||nIn>nMax), error(['Incorrect num args for "' cmd '".']); end
end
function success = getImgFile( fName )
% create local copy of fName which is in a imagesci/private
fName = [fName '.' mexext]; s = filesep; success = 1;
sName = [fileparts(which('imread.m')) s 'private' s fName];
tName = [fileparts(mfilename('fullpath')) s 'private' s fName];
if(~exist(tName,'file')), success=copyfile(sName,tName); end
end
function [info, fid, tNm] = open( fName, info )
% open video for writing, create space for header
t=[fName '.seq']; if(exist(t,'file')), delete(t); end
t=[fName '-seek.mat']; if(exist(t,'file')), delete(t); end
fid=fopen([fName '.seq'],'w','l'); assert(fid~=-1);
fwrite(fid,zeros(1,1024),'uint8');
% initialize info struct (w all fields necessary for writeHeader)
assert(isfield2(info,{'width','height','fps','codec'},1));
switch(info.codec)
case {'monoraw', 'imageFormat100'}, frmt=100; nCh=1; ext='raw';
case {'raw', 'imageFormat200'}, frmt=200; nCh=3; ext='raw';
case {'monojpg', 'imageFormat102'}, frmt=102; nCh=1; ext='jpg';
case {'jpg', 'imageFormat201'}, frmt=201; nCh=3; ext='jpg';
case {'monopng', 'imageFormat001'}, frmt=001; nCh=1; ext='png';
case {'png', 'imageFormat002'}, frmt=002; nCh=3; ext='png';
otherwise, error('unknown format');
end; s=1;
if(strcmp(ext,'jpg')), s=getImgFile('wjpg8c'); end
if(strcmp(ext,'png')), s=getImgFile('png');
if(s), info.writeImg=@(p) png('write',p{:}); end; end
if(strcmp(ext,'png') && ~s), s=getImgFile('pngwritec');
if(s), info.writeImg=@(p) pngwritec(p{:}); end; end
if(~s), error('Cannot find Matlab''s source image writer'); end
info.imageFormat=frmt; info.ext=ext;
if(any(strcmp(ext,{'jpg','png'}))), info.seek=1024; info.seekNm=t; end
if(~isfield2(info,'quality')), info.quality=80; end
info.imageBitDepth=8*nCh; info.imageBitDepthReal=8;
nByte=info.width*info.height*nCh; info.imageSizeBytes=nByte;
info.numFrames=0; info.trueImageSize=nByte+6+512-mod(nByte+6,512);
% generate unique temporary name
[~,tNm]=fileparts(fName); t=clock; t=mod(t(end),1);
tNm=sprintf('tmp_%s_%15i.%s',tNm,round((t+rand)/2*1e15),ext);
end
function info = addFrame( fid, info, tNm, encode, I, ts )
% write frame
nCh=info.imageBitDepth/8; ext=info.ext; c=info.numFrames+1;
if( encode )
siz = [info.height info.width nCh];
assert(size(I,1)==siz(1) && size(I,2)==siz(2) && size(I,3)==siz(3));
end
switch ext
case 'raw'
% write an uncompressed image (assume imageBitDepthReal==8)
if( ~encode ), assert(numel(I)==info.imageSizeBytes); else
if(nCh==3), t=I(:,:,3); I(:,:,3)=I(:,:,1); I(:,:,1)=t; end
if(nCh==1), I=I'; else I=permute(I,[3,2,1]); end
end
fwrite(fid,I(:),'uint8'); pad=info.trueImageSize-info.imageSizeBytes-6;
case 'jpg'
if( encode )
% write/read to/from temporary .jpg (not that much overhead)
p=struct('quality',info.quality,'comment',{{}},'mode','lossy');
for t=0:99, try wjpg8c(I,tNm,p); fr=fopen(tNm,'r'); assert(fr>0);
break; catch, pause(.01); fr=-1; end; end %#ok<CTCH>
if(fr<0), error(['write fail: ' tNm]); end; I=fread(fr); fclose(fr);
end
assert(I(1)==255 && I(2)==216 && I(end-1)==255 && I(end)==217); % JPG
fwrite(fid,numel(I)+4,'uint32'); fwrite(fid,I); pad=10;
case 'png'
if( encode )
% write/read to/from temporary .png (not that much overhead)
p=cell(1,17); if(nCh==1), p{4}=0; else p{4}=2; end
p{1}=I; p{3}=tNm; p{5}=8; p{8}='none'; p{16}=cell(0,2);
for t=0:99, try info.writeImg(p); fr=fopen(tNm,'r'); assert(fr>0);
break; catch, pause(.01); fr=-1; end; end %#ok<CTCH>
if(fr<0), error(['write fail: ' tNm]); end; I=fread(fr); fclose(fr);
end
fwrite(fid,numel(I)+4,'uint32'); fwrite(fid,I); pad=10;
otherwise, assert(false);
end
% store seek info
if(any(strcmp(ext,{'jpg','png'})))
if(length(info.seek)<c+1), info.seek=[info.seek; zeros(c,1)]; end
info.seek(c+1)=info.seek(c)+numel(I)+10+pad;
end
% write timestamp
if(nargin<6),ts=(c-1)/info.fps; end; s=floor(ts); ms=round(mod(ts,1)*1000);
fwrite(fid,s,'int32'); fwrite(fid,ms,'uint16'); info.numFrames=c;
% pad with zeros
if(pad>0), fwrite(fid,zeros(1,pad),'uint8'); end
end
function writeHeader( fid, info )
fseek(fid,0,'bof');
% first 4 bytes store OxFEED, next 24 store 'Norpix seq '
fwrite(fid,hex2dec('FEED'),'uint32');
fwrite(fid,['Norpix seq' 0 0],'uint16');
% next 8 bytes for version (3) and header size (1024), then 512 for descr
fwrite(fid,[3 1024],'int32');
if(isfield(info,'descr')), d=info.descr(:); else d=('No Description')'; end
d=[d(1:min(256,end)); zeros(256-length(d),1)]; fwrite(fid,d,'uint16');
% write remaining info
vals=[info.width info.height info.imageBitDepth info.imageBitDepthReal ...
info.imageSizeBytes info.imageFormat info.numFrames 0 ...
info.trueImageSize];
fwrite(fid,vals,'uint32');
% store frame rate and pad with 0's
fwrite(fid,info.fps,'float64'); fwrite(fid,zeros(1,432),'uint8');
% write seek info for compressed images to disk
if(any(strcmp(info.ext,{'jpg','png'})))
seek=info.seek(1:info.numFrames); %#ok<NASGU>
try save(info.seekNm,'seek'); catch; end %#ok<CTCH>
end
end
|
github
|
P-Chao/acfdetect-master
|
kernelTracker.m
|
.m
|
acfdetect-master/toolbox/videos/kernelTracker.m
| 9,315 |
utf_8
|
4a7d0235f1e518ab5f1c9f1b5450b3f0
|
function [allRct, allSim, allIc] = kernelTracker( I, prm )
% Kernel Tracker from Comaniciu, Ramesh and Meer PAMI 2003.
%
% Implements the algorithm described in "Kernel-Based Object Tracking" by
% Dorin Comaniciu, Visvanathan Ramesh and Peter Meer, PAMI 25, 564-577,
% 2003. This is a fast tracking algorithm that utilizes a histogram
% representation of an object (in this implementation we use color
% histograms, as in the original work). The idea is given a histogram q in
% frame t, find histogram p in frame t+1 that is most similar to q. It
% turns out that this can be formulated as a mean shift problem. Here, the
% kernel is fixed to the Epanechnikov kernel.
%
% This implementation uses mex files to optimize speed, it is significantly
% faster than real time for a single object on a 2GHz standard laptop (as
% of 2007).
%
% If I==[], toy data is created. If rctS==0, the user is queried to
% specify the first rectangle. rctE, denoting the object location in the
% last frame, can optionally be specified. If rctE is given, the model
% histogram at fraction r of the video is (1-r)*histS+r*histE where histS
% and histE are the model histograms from the first and last frame. If
% rctE==0 rectangle in final frame is queried, if rectE==-1 it is not used.
%
% Let T denote the length of the video. Returned values are of length t,
% where t==T if the object was tracked through the whole sequence (ie sim
% does not fall below simThr), otherwise t<=T is equal to the last frame in
% which obj was found. You can test if the object was tracked using:
% success = (size(allRct,1)==size(I,4));
%
% USAGE
% [allRct, allIc, allSim] = kernelTracker( [I], [prm] )
%
% INPUTS
% I - MxNx3xT input video
% [prm]
% .rctS - [0] rectangle denoting initial object location
% .rctE - [-1] rectangle denoting final object location
% .dispFlag - [1] show interactive display
% .scaleSrch - [1] if true search over scale
% .nBit - [4] n=2^nBit, color histograms are [n x n x n]
% .simThr - [.7] sim thr for when obj is considered lost
% .scaleDel - [.9] multiplicative diff between consecutive scales
%
% OUTPUTS
% allRct - [t x 4] array of t locations [x,y,wd,ht]
% allSim - [1 x t] array of similarity measures during tracking
% allIc - [1 x t] cell array of cropped windows containing obj
%
% EXAMPLE
% disp('Select a rectangular region for tracking');
% [allRct,allSim,allIc] = kernelTracker();
% figure(2); clf; plot(allRct);
% figure(3); clf; montage2(allIc,struct('hasChn',true));
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.22
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%%% get parameters (set defaults)
if( nargin<1 ); I=[]; end;
if( nargin<2 ); prm=struct(); end;
dfs = {'scaleSrch',1, 'nBit',4, 'simThr',.7, ...
'dispFlag',1, 'scaleDel',.9, 'rctS',0, 'rctE',-1 };
prm = getPrmDflt( prm, dfs );
scaleSrch=prm.scaleSrch; nBit=prm.nBit; simThr=prm.simThr;
dispFlag=prm.dispFlag; scaleDel=prm.scaleDel;
rctS=prm.rctS; rctE=prm.rctE;
if(isempty(I)); I=toyData(100,1); end;
%%% get rctS and rectE if necessary
rctProp = {'EdgeColor','g','Curvature',[1 1],'LineWidth',2};
if(rctS==0); figure(1); clf; imshow(I(:,:,:,1)); rctS=getrect; end
if(rctE==0); figure(1); clf; imshow(I(:,:,:,end)); rctE=getrect; end
%%% precompute kernels for all relevant scales
rctS=round(rctS); rctS(3:4)=rctS(3:4)-mod(rctS(3:4),2);
pos1 = rctS(1:2)+rctS(3:4)/2; wd=rctS(3); ht=rctS(4);
[mRows,nCols,~,nFrame] = size(I);
nScaleSm = max(1,floor(log(max(10/wd,10/ht))/log(scaleDel)));
nScaleLr = max(1,floor(-log(min(nCols/wd,mRows/ht)/2)/log(scaleDel)));
nScale = nScaleSm+nScaleLr+1; scale = nScaleSm+1;
kernel = repmat( buildKernel(wd,ht), [1 nScale] );
for s=1:nScale
r = power(scaleDel,s-1-nScaleSm);
kernel(s) = buildKernel( wd/r, ht/r );
end
%%% build model histogram for rctS
[Ic,Qc] = cropWindow( I(:,:,:,1), nBit, pos1, wd, ht );
qS = buildHist( Qc, kernel(scale), nBit );
%%% optionally build model histogram for rctE
if(length(rctE)==4);
rctE=round(rctE); rctE(3:4)=rctE(3:4)-mod(rctE(3:4),2);
posE = rctE(1:2)+rctE(3:4)/2; wdE=rctE(3); htE=rctE(4);
kernelE = buildKernel(wdE,htE);
[Ic,Qc] = cropWindow( I(:,:,:,end), nBit, posE, wdE, htE ); %end
qE = buildHist( Qc, kernelE, nBit );
else
qE = qS;
end
%%% setup display
if( dispFlag )
figure(1); clf; hImg=imshow(I(:,:,:,1));
hR = rectangle('Position', rctS, rctProp{:} );
pause(.1);
end
%%% main loop
pos = pos1;
allRct = zeros(nFrame,4); allRct(1,:)=rctS;
allIc = cell(1,nFrame); allIc{1}=Ic;
allSim = zeros(1,nFrame);
for frm = 1:nFrame
Icur = I(:,:,:,frm);
% current model (linearly interpolate)
r=(frm-1)/nFrame; q = qS*(1-r) + qE*r;
if( scaleSrch )
% search over scale
best={}; bestSim=-1; pos1=pos;
for s=max(1,scale-1):min(nScale,scale+1)
[p,pos,Ic,sim]=kernelTracker1(Icur,q,pos1,kernel(s),nBit);
if( sim>bestSim ); best={p,pos,Ic,s}; bestSim=sim; end;
end
[~,pos,Ic,scale]=deal(best{:});
wd=kernel(scale).wd; ht=kernel(scale).ht;
else
% otherwise just do meanshift once
[~,pos,Ic,bestSim]=kernelTracker1(Icur,q,pos,kernel(scale),nBit);
end
% record results
if( bestSim<simThr ); break; end;
rctC=[pos(1)-wd/2 pos(2)-ht/2 wd, ht ];
allIc{frm}=Ic; allRct(frm,:)=rctC;
allSim(frm)=bestSim;
% display
if( dispFlag )
set(hImg,'CData',Icur); title(['bestSim=' num2str(bestSim)]);
delete(hR); hR=rectangle('Position', rctC, rctProp{:} );
if(0); waitforbuttonpress; else drawnow; end
end
end
%%% finalize & display
if( bestSim<simThr ); frm=frm-1; end;
allIc=allIc(1:frm); allRct=allRct(1:frm,:); allSim=allSim(1:frm);
if( dispFlag )
if( bestSim<simThr ); disp('lost target'); end
disp( ['final sim = ' num2str(bestSim) ] );
end
end
function [p,pos,Ic,sim] = kernelTracker1( I, q, pos, kernel, nBit )
mRows=size(I,1); nCols=size(I,2);
wd=kernel.wd; wd2=wd/2;
ht=kernel.ht; ht2=ht/2;
xs=kernel.xs; ys=kernel.ys;
for iter=1:1000
posPrev = pos;
% check if pos in bounds
rct = [pos(1)-wd/2 pos(2)-ht/2 wd, ht ];
if( rct(1)<1 || rct(2)<1 || (rct(1)+wd)>nCols || (rct(2)+ht)>mRows )
pos=posPrev; p=[]; Ic=[]; sim=eps; return;
end
% crop window / compute histogram
[Ic,Qc] = cropWindow( I, nBit, pos, wd, ht );
p = buildHist( Qc, kernel, nBit );
if( iter==20 ); break; end;
% compute meanshift step
w = ktComputeW_c( Qc, q, p, nBit );
posDel = [sum(xs.*w)*wd2, sum(ys.*w)*ht2] / (sum(w)+eps);
posDel = round(posDel+.1);
if(all(posDel==0)); break; end;
pos = pos + posDel;
end
locs=p>0; sim=sum( sqrt(q(locs).*p(locs)) );
end
function kernel = buildKernel( wd, ht )
wd = round(wd/2)*2; xs = linspace(-1,1,wd);
ht = round(ht/2)*2; ys = linspace(-1,1,ht);
[ys,xs] = ndgrid(ys,xs); xs=xs(:); ys=ys(:);
xMag = ys.*ys + xs.*xs; xMag(xMag>1) = 1;
K = 2/pi * (1-xMag); sumK=sum(K);
kernel = struct( 'K',K, 'sumK',sumK, 'xs',xs, 'ys',ys, 'wd',wd, 'ht',ht );
end
function p = buildHist( Qc, kernel, nBit )
p = ktHistcRgb_c( Qc, kernel.K, nBit ) / kernel.sumK;
if(0); p=gaussSmooth(p,.5,'same',2); p=p*(1/sum(p(:))); end;
end
function [Ic,Qc] = cropWindow( I, nBit, pos, wd, ht )
row = pos(2)-ht/2; col = pos(1)-wd/2;
Ic = I(row:row+ht-1,col:col+wd-1,:);
if(nargout==2); Qc=bitshift(reshape(Ic,[],3),nBit-8); end;
end
function I = toyData( n, sigma )
I1 = imresize(imread('peppers.png'),[256 256],'bilinear');
I=ones(512,512,3,n,'uint8')*100;
pos = round(gaussSmooth(randn(2,n)*80,[0 4]))+128;
for i=1:n
I((1:256)+pos(1,i),(1:256)+pos(2,i),:,i)=I1;
I1 = uint8(double(I1) + randn(size(I1))*sigma);
end;
I=I((1:256)+128,(1:256)+128,:,:);
end
% % debugging code
% if( debug )
% figure(1);
% subplot(2,3,2); image( Ic ); subplot(2,3,1); image(Icur);
% rectangle('Position', posToRct(pos0,wd,ht), rctProp{:} );
% subplot(2,3,3); imagesc( reshape(w,wd,ht), [0 5] ); colormap gray;
% subplot(2,3,4); montage2( q ); subplot(2,3,5); montage2( p1 );
% waitforbuttonpress;
% end
% % search over 9 locations (with fixed scale)
% if( locSrch )
% best={}; bestSim=0.0; pos1=pos;
% for lr=-1:1
% for ud=-1:1
% posSt = pos1 + [wd*lr ht*ud];
% [p,pos,Ic,sim] = kernelTracker1(Icur,q,posSt,kernel(scale),nBit);
% if( sim>bestSim ); best={p,pos,Ic}; bestSim=sim; end;
% end
% end
% [p,pos,Ic]=deal(best{:});
% end
%%% background histogram -- seems kind of useless, removed
% if( 0 )
% bgSiz = 3; bgImp = 2;
% rctBgStr = max([1 1],rctS(1:2)-rctS(3:4)*(bgSiz/2-.5));
% rctBgEnd = min([nCols mRows],rctS(1:2)+rctS(3:4)*(bgSiz/2+.5));
% rctBg = [rctBgStr rctBgEnd-rctBgStr+1];
% posBg = rctBg(1:2)+rctBg(3:4)/2; wdBg=rctBg(3); htBg=rctBg(4);
% [IcBg,QcBg] = cropWindow( I(:,:,:,1), nBit, posBg, wdBg, htBg );
% wtBg = double( reshape(kernel.K,ht,wd)==0 );
% pre=rctS(1:2)-rctBg(1:2); pst=rctBg(3:4)-rctS(3:4)-pre;
% wtBg = padarray( wtBg, fliplr(pre), 1, 'pre' );
% wtBg = padarray( wtBg, fliplr(pst), 1, 'post' );
% pBg = buildHist( QcBg, wtBg, [], nBit );
% pWts = min( 1, max(pBg(:))/bgImp./pBg );
% if(0); montage2(pWts); impixelinfo; return; end
% else
% pWts=[];
% end;
% if(~isempty(pWts)); p = p .* pWts; end; % in buildHistogram
|
github
|
P-Chao/acfdetect-master
|
seqIo.m
|
.m
|
acfdetect-master/toolbox/videos/seqIo.m
| 17,019 |
utf_8
|
9c631b324bb527372ec3eed3416c5dcc
|
function out = seqIo( fName, action, varargin )
% Utilities for reading and writing seq files.
%
% A seq file is a series of concatentated image frames with a fixed size
% header. It is essentially the same as merging a directory of images into
% a single file. seq files are convenient for storing videos because: (1)
% no video codec is required, (2) seek is instant and exact, (3) seq files
% can be read on any operating system. The main drawback is that each frame
% is encoded independently, resulting in increased file size. The advantage
% over storing as a directory of images is that a single large file is
% created. Currently, either uncompressed, jpg or png compressed frames
% are supported. The seq file format is modeled after the Norpix seq format
% (in fact this reader can be used to read some Norpix seq files). The
% actual work of reading/writing seq files is done by seqReaderPlugin and
% seqWriterPlugin (there is no need to call those functions directly).
%
% seqIo contains a number of utility functions for working with seq files.
% The format for accessing the various utility functions is:
% out = seqIo( fName, 'action', inputs );
% The list of functions and help for each is given below. Also, help on
% individual subfunctions can be accessed by: "help seqIo>action".
%
% Create interface sr for reading seq files.
% sr = seqIo( fName, 'reader', [cache] )
% Create interface sw for writing seq files.
% sw = seqIo( fName, 'writer', info )
% Get info about seq file.
% info = seqIo( fName, 'getInfo' )
% Crop sub-sequence from seq file.
% seqIo( fName, 'crop', tName, frames )
% Extract images from seq file to target directory or array.
% Is = seqIo( fName, 'toImgs', [tDir], [skip], [f0], [f1], [ext] )
% Create seq file from an array or directory of images or from an AVI file.
% seqIo( fName, 'frImgs', info, varargin )
% Convert seq file by applying imgFun(I) to each frame I.
% seqIo( fName, 'convert', tName, imgFun, varargin )
% Replace header of seq file with provided info.
% seqIo( fName, 'newHeader', info )
% Create interface sr for reading dual seq files.
% sr = seqIo( fNames, 'readerDual', [cache] )
%
% USAGE
% out = seqIo( fName, action, varargin )
%
% INPUTS
% fName - seq file to open
% action - controls action (see above)
% varargin - additional inputs (see above)
%
% OUTPUTS
% out - depends on action (see above)
%
% EXAMPLE
%
% See also seqIo>reader, seqIo>writer, seqIo>getInfo, seqIo>crop,
% seqIo>toImgs, seqIo>frImgs, seqIo>convert, seqIo>newHeader,
% seqIo>readerDual, seqPlayer, seqReaderPlugin, seqWriterPlugin
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
switch lower(action)
case {'reader','r'}, out = reader( fName, varargin{:} );
case {'writer','w'}, out = writer( fName, varargin{:} );
case 'getinfo', out = getInfo( fName );
case 'crop', crop( fName, varargin{:} ); out=1;
case 'toimgs', out = toImgs( fName, varargin{:} );
case 'frimgs', frImgs( fName, varargin{:} ); out=1;
case 'convert', convert( fName, varargin{:} ); out=1;
case 'newheader', newHeader( fName, varargin{:} ); out=1;
case {'readerdual','rdual'}, out=readerDual(fName,varargin{:});
otherwise, error('seqIo unknown action: ''%s''',action);
end
end
function sr = reader( fName, cache )
% Create interface sr for reading seq files.
%
% Create interface sr to seq file with the following commands:
% sr.close(); % Close seq file (sr is useless after).
% [I,ts]=sr.getframe(); % Get current frame (returns [] if invalid).
% [I,ts]=sr.getframeb(); % Get current frame with no decoding.
% ts = sr.getts(); % Return timestamps for all frames.
% info = sr.getinfo(); % Return struct with info about video.
% [I,ts]=sr.getnext(); % Shortcut for next() followed by getframe().
% out = sr.next(); % Go to next frame (out=0 on fail).
% out = sr.seek(frame); % Go to specified frame (out=0 on fail).
% out = sr.step(delta); % Go to current frame+delta (out=0 on fail).
%
% If cache>0, reader() will cache frames in memory, so that calls to
% getframe() can avoid disk IO for cached frames (note that only frames
% returned by getframe() are cached). This is useful if the same frames are
% accessed repeatedly. When the cache is full, the frame in the cache
% accessed least recently is discarded. Memory requirements are
% proportional to cache size.
%
% USAGE
% sr = seqIo( fName, 'reader', [cache] )
%
% INPUTS
% fName - seq file name
% cache - [0] size of cache
%
% OUTPUTS
% sr - interface for reading seq file
%
% EXAMPLE
%
% See also seqIo, seqReaderPlugin
if(nargin<2 || isempty(cache)), cache=0; end
if( cache>0 ), [as, fs, Is, ts, inds]=deal([]); end
r=@seqReaderPlugin; s=r('open',int32(-1),fName);
sr = struct( 'close',@() r('close',s), 'getframe',@getframe, ...
'getframeb',@() r('getframeb',s), 'getts',@() r('getts',s), ...
'getinfo',@() r('getinfo',s), 'getnext',@() r('getnext',s), ...
'next',@() r('next',s), 'seek',@(f) r('seek',s,f), ...
'step',@(d) r('step',s,d));
function [I,t] = getframe()
% if not using cache simply call 'getframe' and done
if(cache<=0), [I,t]=r('getframe',s); return; end
% if cache initialized and frame in cache perform lookup
f=r('getinfo',s); f=f.curFrame; i=find(f==fs,1);
if(i), as=as+1; as(i)=0; t=ts(i); I=Is(inds{:},i); return; end
% if image not in cache add (and possibly initialize)
[I,t]=r('getframe',s); if(0), fprintf('reading frame %i\n',f); end
if(isempty(Is)), Is=zeros([size(I) cache],class(I));
as=ones(1,cache); fs=-as; ts=as; inds=repmat({':'},1,ndims(I)); end
[~,i]=max(as); as(i)=0; fs(i)=f; ts(i)=t; Is(inds{:},i)=I;
end
end
function sw = writer( fName, info )
% Create interface sw for writing seq files.
%
% Create interface sw to seq file with the following commands:
% sw.close(); % Close seq file (sw is useless after).
% sw.addframe(I,[ts]); % Writes video frame (and timestamp)
% sw.addframeb(bytes); % Writes video frame with no encoding.
% info = sw.getinfo(); % Return struct with info about video.
%
% The following params must be specified in struct 'info' upon opening:
% width - frame width
% height - frame height
% fps - frames per second
% quality - [80] compression quality (0 to 100)
% codec - string representing codec, options include:
% 'monoraw'/'imageFormat100' - black/white uncompressed
% 'raw'/'imageFormat200' - color (BGR) uncompressed
% 'monojpg'/'imageFormat102' - black/white jpg compressed
% 'jpg'/'imageFormat201' - color jpg compressed
% 'monopng'/'imageFormat001' - black/white png compressed
% 'png'/'imageFormat002' - color png compressed
%
% USAGE
% sw = seqIo( fName, 'writer', info )
%
% INPUTS
% fName - seq file name
% info - see above
%
% OUTPUTS
% sw - interface for writing seq file
%
% EXAMPLE
%
% See also seqIo, seqWriterPlugin
w=@seqWriterPlugin; s=w('open',int32(-1),fName,info);
sw = struct( 'close',@() w('close',s), 'getinfo',@() w('getinfo',s), ...
'addframe',@(varargin) w('addframe',s,varargin{:}), ...
'addframeb',@(varargin) w('addframeb',s,varargin{:}) );
end
function info = getInfo( fName )
% Get info about seq file.
%
% USAGE
% info = seqIo( fName, 'getInfo' )
%
% INPUTS
% fName - seq file name
%
% OUTPUTS
% info - information struct
%
% EXAMPLE
%
% See also seqIo
sr=reader(fName); info=sr.getinfo(); sr.close();
end
function crop( fName, tName, frames )
% Crop sub-sequence from seq file.
%
% Frame indices are 0 indexed. frames need not be consecutive and can
% contain duplicates. An index of -1 indicates a blank (all 0) frame. If
% contiguous subset of frames is cropped timestamps are preserved.
%
% USAGE
% seqIo( fName, 'crop', tName, frames )
%
% INPUTS
% fName - seq file name
% tName - cropped seq file name
% frames - frame indices (0 indexed)
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
sr=reader(fName); info=sr.getinfo(); sw=writer(tName,info);
frames=frames(:)'; pad=sr.getnext(); pad(:)=0;
kp=frames>=0 & frames<info.numFrames; if(~all(kp)), frames=frames(kp);
warning('piotr:seqIo:crop','%i out of bounds frames',sum(~kp)); end
ordered=all(frames(2:end)==frames(1:end-1)+1);
n=length(frames); k=0; tid=ticStatus;
for f=frames
if(f<0), sw.addframe(pad); continue; end
sr.seek(f); [I,ts]=sr.getframeb(); k=k+1; tocStatus(tid,k/n);
if(ordered), sw.addframeb(I,ts); else sw.addframeb(I); end
end; sw.close(); sr.close();
end
function Is = toImgs( fName, tDir, skip, f0, f1, ext )
% Extract images from seq file to target directory or array.
%
% USAGE
% Is = seqIo( fName, 'toImgs', [tDir], [skip], [f0], [f1], [ext] )
%
% INPUTS
% fName - seq file name
% tDir - [] target directory (if empty extract images to array)
% skip - [1] skip between written frames
% f0 - [0] first frame to write
% f1 - [numFrames-1] last frame to write
% ext - [] optionally save as given type (slow, reconverts)
%
% OUTPUTS
% Is - if isempty(tDir) outputs image array (else Is=[])
%
% EXAMPLE
%
% See also seqIo
if(nargin<2 || isempty(tDir)), tDir=[]; end
if(nargin<3 || isempty(skip)), skip=1; end
if(nargin<4 || isempty(f0)), f0=0; end
if(nargin<5 || isempty(f1)), f1=inf; end
if(nargin<6 || isempty(ext)), ext=''; end
sr=reader(fName); info=sr.getinfo(); f1=min(f1,info.numFrames-1);
frames=f0:skip:f1; n=length(frames); tid=ticStatus; k=0;
% output images to array
if(isempty(tDir))
I=sr.getnext(); d=ndims(I); assert(d==2 || d==3);
try Is=zeros([size(I) n],class(I)); catch e; sr.close(); throw(e); end
for k=1:n, sr.seek(frames(k)); I=sr.getframe(); tocStatus(tid,k/n);
if(d==2), Is(:,:,k)=I; else Is(:,:,:,k)=I; end; end
sr.close(); return;
end
% output images to directory
if(~exist(tDir,'dir')), mkdir(tDir); end; Is=[];
for frame=frames
f=[tDir '/I' int2str2(frame,5) '.']; sr.seek(frame);
if(~isempty(ext)), I=sr.getframe(); imwrite(I,[f ext]); else
I=sr.getframeb(); f=fopen([f info.ext],'w');
if(f<=0), sr.close(); assert(false); end
fwrite(f,I); fclose(f);
end; k=k+1; tocStatus(tid,k/n);
end; sr.close();
end
function frImgs( fName, info, varargin )
% Create seq file from an array or directory of images or from an AVI file.
%
% For info, if converting from array, only codec (e.g., 'jpg') and fps must
% be specified while width and height and determined automatically. If
% converting from AVI, fps is also determined automatically.
%
% USAGE
% seqIo( fName, 'frImgs', info, varargin )
%
% INPUTS
% fName - seq file name
% info - defines codec, etc, see seqIo>writer
% varargin - additional params (struct or name/value pairs)
% .aviName - [] if specified create seq from avi file
% .Is - [] if specified create seq from image array
% .sDir - [] source directory
% .skip - [1] skip between frames
% .name - ['I'] base name of images
% .nDigits - [5] number of digits for filename index
% .f0 - [0] first frame to read
% .f1 - [10^6] last frame to read
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo, seqIo>writer
dfs={'aviName','','Is',[],'sDir',[],'skip',1,'name','I',...
'nDigits',5,'f0',0,'f1',10^6};
[aviName,Is,sDir,skip,name,nDigits,f0,f1] ...
= getPrmDflt(varargin,dfs,1);
if(~isempty(aviName))
if(exist('mmread.m','file')==2) % use external mmread function
% mmread requires full pathname, which is obtained via 'which'. But,
% 'which' can fail (maltab bug), so best to just pass in full pathname
t=which(aviName); if(~isempty(t)), aviName=t; end
V=mmread(aviName); n=V.nrFramesTotal;
info.height=V.height; info.width=V.width; info.fps=V.rate;
sw=writer(fName,info); tid=ticStatus('creating seq from avi');
for f=1:n, sw.addframe(V.frames(f).cdata); tocStatus(tid,f/n); end
sw.close();
else % use matlab mmreader function
emsg=['mmreader.m failed to load video. In general mmreader.m is ' ...
'known to have many issues, especially on Linux. I suggest ' ...
'installing the similarly named mmread toolbox from Micah ' ...
'Richert, available at Matlab Central. If mmread is installed, ' ...
'seqIo will automatically use mmread instead of mmreader.'];
try V=mmreader(aviName); catch %#ok<DMMR,CTCH>
error('piotr:seqIo:frImgs',emsg); end; n=V.NumberOfFrames;
info.height=V.Height; info.width=V.Width; info.fps=V.FrameRate;
sw=writer(fName,info); tid=ticStatus('creating seq from avi');
for f=1:n, sw.addframe(read(V,f)); tocStatus(tid,f/n); end
sw.close();
end
elseif( isempty(Is) )
assert(exist(sDir,'dir')==7); sw=writer(fName,info); info=sw.getinfo();
frmStr=sprintf('%s/%s%%0%ii.%s',sDir,name,nDigits,info.ext);
for frame = f0:skip:f1
f=sprintf(frmStr,frame); if(~exist(f,'file')), break; end
f=fopen(f,'r'); if(f<=0), sw.close(); assert(false); end
I=fread(f); fclose(f); sw.addframeb(I);
end; sw.close();
if(frame==f0), warning('No images found.'); end %#ok<WNTAG>
else
nd=ndims(Is); if(nd==2), nd=3; end; assert(nd<=4); nFrm=size(Is,nd);
info.height=size(Is,1); info.width=size(Is,2); sw=writer(fName,info);
if(nd==3), for f=1:nFrm, sw.addframe(Is(:,:,f)); end; end
if(nd==4), for f=1:nFrm, sw.addframe(Is(:,:,:,f)); end; end
sw.close();
end
end
function convert( fName, tName, imgFun, varargin )
% Convert seq file by applying imgFun(I) to each frame I.
%
% USAGE
% seqIo( fName, 'convert', tName, imgFun, varargin )
%
% INPUTS
% fName - seq file name
% tName - converted seq file name
% imgFun - function to apply to each image
% varargin - additional params (struct or name/value pairs)
% .info - [] info for target seq file
% .skip - [1] skip between frames
% .f0 - [0] first frame to read
% .f1 - [inf] last frame to read
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
dfs={'info',[],'skip',1,'f0',0,'f1',inf};
[info,skip,f0,f1]=getPrmDflt(varargin,dfs,1);
assert(~strcmp(tName,fName)); sr=reader(fName); infor=sr.getinfo();
if(isempty(info)), info=infor; end; n=infor.numFrames; f1=min(f1,n-1);
I=sr.getnext(); I=imgFun(I); info.width=size(I,2); info.height=size(I,1);
sw=writer(tName,info); tid=ticStatus('converting seq');
frames=f0:skip:f1; n=length(frames); k=0;
for f=frames, sr.seek(f); [I,ts]=sr.getframe(); I=imgFun(I);
if(skip==1), sw.addframe(I,ts); else sw.addframe(I); end
k=k+1; tocStatus(tid,k/n);
end; sw.close(); sr.close();
end
function newHeader( fName, info )
% Replace header of seq file with provided info.
%
% Can be used if the file fName has a corrupt header. Automatically tries
% to compute number of frames in fName. No guarantees that it will work.
%
% USAGE
% seqIo( fName, 'newHeader', info )
%
% INPUTS
% fName - seq file name
% info - info for target seq file
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
[d,n]=fileparts(fName); if(isempty(d)), d='.'; end
fName=[d '/' n]; tName=[fName '-new' datestr(now,30)];
if(exist([fName '-seek.mat'],'file')); delete([fName '-seek.mat']); end
srp=@seqReaderPlugin; hr=srp('open',int32(-1),fName,info); tid=ticStatus;
info=srp('getinfo',hr); sw=writer(tName,info); n=info.numFrames;
for f=1:n, srp('next',hr); [I,ts]=srp('getframeb',hr);
sw.addframeb(I,ts); tocStatus(tid,f/n); end
srp('close',hr); sw.close();
end
function sr = readerDual( fNames, cache )
% Create interface sr for reading dual seq files.
%
% Wrapper for two seq files of the same image dims and roughly the same
% frame counts that are treated as a single reader object. getframe()
% returns the concatentation of the two frames. For videos of different
% frame counts, the first video serves as the "dominant" video and the
% frame count of the second video is adjusted accordingly. Same general
% usage as in reader, but the only supported operations are: close(),
% getframe(), getinfo(), and seek().
%
% USAGE
% sr = seqIo( fNames, 'readerDual', [cache] )
%
% INPUTS
% fNames - two seq file names
% cache - [0] size of cache (see seqIo>reader)
%
% OUTPUTS
% sr - interface for reading seq file
%
% EXAMPLE
%
% See also seqIo, seqIo>reader
if(nargin<2 || isempty(cache)), cache=0; end
s1=reader(fNames{1}, cache); i1=s1.getinfo();
s2=reader(fNames{2}, cache); i2=s2.getinfo();
info=i1; info.width=i1.width+i2.width;
if( i1.width~=i2.width || i1.height~=i2.height )
s1.close(); s2.close(); error('Mismatched videos'); end
if( i1.numFrames~=i2.numFrames )
warning('seq files of different lengths'); end %#ok<WNTAG>
frame2=@(f) round(f/(i1.numFrames-1)*(i2.numFrames-1));
sr=struct('close',@() min(s1.close(),s2.close()), ...
'getframe',@getframe, 'getinfo',@() info, ...
'seek',@(f) s1.seek(f) & s2.seek(frame2(f)) );
function [I,t] = getframe()
[I1,t]=s1.getframe(); I2=s2.getframe(); I=[I1 I2]; end
end
|
github
|
P-Chao/acfdetect-master
|
seqReaderPlugin.m
|
.m
|
acfdetect-master/toolbox/videos/seqReaderPlugin.m
| 9,617 |
utf_8
|
ad8f912634cafe13df6fc7d67aeff05a
|
function varargout = seqReaderPlugin( cmd, h, varargin )
% Plugin for seqIo and videoIO to allow reading of seq files.
%
% Do not call directly, use as plugin for seqIo or videoIO instead.
% The following is a list of commands available (srp=seqReaderPlugin):
% h = srp('open',h,fName) % Open a seq file for reading (h ignored).
% h = srp('close',h); % Close seq file (output h is -1).
% [I,ts] =srp('getframe',h) % Get current frame (returns [] if invalid).
% [I,ts] =srp('getframeb',h) % Get current frame with no decoding.
% ts = srp('getts',h) % Return timestamps for all frames.
% info = srp('getinfo',h) % Return struct with info about video.
% [I,ts] =srp('getnext',h) % Shortcut for 'next' followed by 'getframe'.
% out = srp('next',h) % Go to next frame (out=0 on fail).
% out = srp('seek',h,frame) % Go to specified frame (out=0 on fail).
% out = srp('step',h,delta) % Go to current frame+delta (out=0 on fail).
%
% USAGE
% varargout = seqReaderPlugin( cmd, h, varargin )
%
% INPUTS
% cmd - string indicating operation to perform
% h - unique identifier for open seq file
% varargin - additional options (vary according to cmd)
%
% OUTPUTS
% varargout - output (varies according to cmd)
%
% EXAMPLE
%
% See also SEQIO, SEQWRITERPLUGIN
%
% Piotr's Computer Vision Matlab Toolbox Version 3.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% persistent variables to keep track of all loaded .seq files
persistent h1 hs cs fids infos tNms;
if(isempty(h1)), h1=int32(now); hs=int32([]); infos={}; tNms={}; end
nIn=nargin-2; in=varargin; o2=[]; cmd=lower(cmd);
% open seq file
if(strcmp(cmd,'open'))
chk(nIn,1,2); h=length(hs)+1; hs(h)=h1; varargout={h1}; h1=h1+1;
[pth,name]=fileparts(in{1}); if(isempty(pth)), pth='.'; end
if(nIn==1), info=[]; else info=in{2}; end
fName=[pth filesep name]; cs(h)=-1;
[infos{h},fids(h),tNms{h}]=open(fName,info); return;
end
% Get the handle for this instance
[v,h]=ismember(h,hs); if(~v), error('Invalid load plugin handle'); end
c=cs(h); fid=fids(h); info=infos{h}; tNm=tNms{h};
% close seq file
if(strcmp(cmd,'close'))
chk(nIn,0); varargout={-1}; fclose(fid); kp=[1:h-1 h+1:length(hs)];
hs=hs(kp); cs=cs(kp); fids=fids(kp); infos=infos(kp);
tNms=tNms(kp); if(exist(tNm,'file')), delete(tNm); end; return;
end
% perform appropriate operation
switch( cmd )
case 'getframe', chk(nIn,0); [o1,o2]=getFrame(c,fid,info,tNm,1);
case 'getframeb', chk(nIn,0); [o1,o2]=getFrame(c,fid,info,tNm,0);
case 'getts', chk(nIn,0); o1=getTs(0:info.numFrames-1,fid,info);
case 'getinfo', chk(nIn,0); o1=info; o1.curFrame=c;
case 'getnext', chk(nIn,0); c=c+1; [o1,o2]=getFrame(c,fid,info,tNm,1);
case 'next', chk(nIn,0); [c,o1]=valid(c+1,info);
case 'seek', chk(nIn,1); [c,o1]=valid(in{1},info);
case 'step', chk(nIn,1); [c,o1]=valid(c+in{1},info);
otherwise, error(['Unrecognized command: "' cmd '"']);
end
cs(h)=c; varargout={o1,o2};
end
function chk(nIn,nMin,nMax)
if(nargin<3), nMax=nMin; end
if(nIn>0 && nMin==0 && nMax==0), error(['"' cmd '" takes no args.']); end
if(nIn<nMin||nIn>nMax), error(['Incorrect num args for "' cmd '".']); end
end
function success = getImgFile( fName )
% create local copy of fName which is in a imagesci/private
fName = [fName '.' mexext]; s = filesep; success = 1;
sName = [fileparts(which('imread.m')) s 'private' s fName];
tName = [fileparts(mfilename('fullpath')) s 'private' s fName];
if(~exist(tName,'file')), success=copyfile(sName,tName); end
end
function [info, fid, tNm] = open( fName, info )
% open video for reading, get header
if(exist([fName '.seq'],'file')==0)
error('seq file not found: %s.seq',fName); end
fid=fopen([fName '.seq'],'r','l');
if(isempty(info)), info=readHeader(fid); else
info.numFrames=0; fseek(fid,1024,'bof'); end
switch(info.imageFormat)
case {100,200}, ext='raw';
case {101 }, ext='brgb8';
case {102,201}, ext='jpg';
case {103 }, ext ='jbrgb';
case {001,002}, ext='png';
otherwise, error('unknown format');
end; info.ext=ext; s=1;
if(any(strcmp(ext,{'jpg','jbrgb'}))), s=getImgFile('rjpg8c'); end
if(strcmp(ext,'png')), s=getImgFile('png');
if(s), info.readImg=@(nm) png('read',nm,[]); end; end
if(strcmp(ext,'png') && ~s), s=getImgFile('pngreadc');
if(s), info.readImg=@(nm) pngreadc(nm,[],false); end; end
if(~s), error('Cannot find Matlab''s source image reader'); end
% generate unique temporary name
[~,tNm]=fileparts(fName); t=clock; t=mod(t(end),1);
tNm=sprintf('tmp_%s_%15i.%s',tNm,round((t+rand)/2*1e15),ext);
% compute seek info for compressed images
if(any(strcmp(ext,{'raw','brgb8'}))), assert(info.numFrames>0); else
oName=[fName '-seek.mat']; n=info.numFrames; if(n==0), n=10^7; end
if(exist(oName,'file')==2), load(oName); info.seek=seek; else %#ok<NODEF>
tid=ticStatus('loading seek info',.1,5); seek=zeros(n,1); seek(1)=1024;
extra=8; % extra bytes after image data (8 for ts, then 0 or 8 empty)
for i=2:n
s=seek(i-1)+fread(fid,1,'uint32')+extra; valid=fseek(fid,s,'bof')==0;
if(i==2 && valid), if(fread(fid,1,'uint32')~=0), fseek(fid,-4,'cof');
else extra=extra+8; s=s+8; valid=fseek(fid,s,'bof')==0; end; end
if(valid), seek(i)=s; tocStatus(tid,i/n);
else n=i-1; seek=seek(1:n); tocStatus(tid,1); break; end
end; if(info.numFrames==0), info.numFrames=n; end
try save(oName,'seek'); catch; end; info.seek=seek; %#ok<CTCH>
end
end
% compute frame rate from timestamps as stored fps may be incorrect
n=min(100,info.numFrames); if(n==1), return; end
ts = getTs( 0:(n-1), fid, info );
ds=ts(2:end)-ts(1:end-1); ds=ds(abs(ds-median(ds))<.005);
if(~isempty(ds)), info.fps=1/mean(ds); end
end
function [frame,v] = valid( frame, info )
v=(frame>=0 && frame<info.numFrames);
end
function [I,ts] = getFrame( frame, fid, info, tNm, decode )
% get frame image (I) and timestamp (ts) at which frame was recorded
nCh=info.imageBitDepth/8; ext=info.ext;
if(frame<0 || frame>=info.numFrames), I=[]; ts=[]; return; end
switch ext
case {'raw','brgb8'}
% read in an uncompressed image (assume imageBitDepthReal==8)
fseek(fid,1024+frame*info.trueImageSize,'bof');
I = fread(fid,info.imageSizeBytes,'*uint8');
if( decode )
% reshape appropriately for mxn or mxnx3 RGB image
siz = [info.height info.width nCh];
if(nCh==1), I=reshape(I,siz(2),siz(1))'; else
I = permute(reshape(I,siz(3),siz(2),siz(1)),[3,2,1]);
end
if(nCh==3), t=I(:,:,3); I(:,:,3)=I(:,:,1); I(:,:,1)=t; end
if(strcmp(ext,'brgb8')), I=demosaic(I,'bggr'); end
end
case {'jpg','jbrgb'}
fseek(fid,info.seek(frame+1),'bof'); nBytes=fread(fid,1,'uint32');
I = fread(fid,nBytes-4,'*uint8');
if( decode )
% write/read to/from temporary .jpg (not that much overhead)
assert(I(1)==255 && I(2)==216 && I(end-1)==255 && I(end)==217); % JPG
for t=0:99, fw=fopen(tNm,'w'); if(fw>=0), break; end; pause(.01); end
if(fw==-1), error(['unable to write: ' tNm]); end
fwrite(fw,I); fclose(fw); I=rjpg8c(tNm);
if(strcmp(ext,'jbrgb')), I=demosaic(I,'bggr'); end
end
case 'png'
fseek(fid,info.seek(frame+1),'bof'); nBytes=fread(fid,1,'uint32');
I = fread(fid,nBytes-4,'*uint8');
if( decode )
% write/read to/from temporary .png (not that much overhead)
for t=0:99, fw=fopen(tNm,'w'); if(fw>=0), break; end; pause(.01); end
if(fw==-1), error(['unable to write: ' tNm]); end
fwrite(fw,I); fclose(fw); I=info.readImg(tNm);
I=permute(I,ndims(I):-1:1);
end
otherwise, assert(false);
end
if(nargout==2), ts=fread(fid,1,'uint32')+fread(fid,1,'uint16')/1000; end
end
function ts = getTs( frames, fid, info )
% get timestamps (ts) at which frames were recorded
n=length(frames); ts=nan(1,n);
for i=1:n, frame=frames(i);
if(frame<0 || frame>=info.numFrames), continue; end
switch info.ext
case {'raw','brgb8'} % uncompressed
fseek(fid,1024+frame*info.trueImageSize+info.imageSizeBytes,'bof');
case {'jpg','png','jbrgb'} % compressed
fseek(fid,info.seek(frame+1),'bof');
fseek(fid,fread(fid,1,'uint32')-4,'cof');
otherwise, assert(false);
end
ts(i)=fread(fid,1,'uint32')+fread(fid,1,'uint16')/1000;
end
end
function info = readHeader( fid )
% see streampix manual for info on header
fseek(fid,0,'bof');
% check that header is not all 0's (a common error)
[tmp,n]=fread(fid,1024); if(n<1024), error('no header'); end
if(all(tmp==0)), error('fully empty header'); end; fseek(fid,0,'bof');
% first 4 bytes store OxFEED, next 24 store 'Norpix seq '
if( ~strcmp(sprintf('%X',fread(fid,1,'uint32')),'FEED') || ...
~strcmp(char(fread(fid,10,'uint16'))','Norpix seq') ) %#ok<FREAD>
error('invalid header');
end; fseek(fid,4,'cof');
% next 8 bytes for version and header size (1024), then 512 for descr
version=fread(fid,1,'int32'); assert(fread(fid,1,'uint32')==1024);
descr=char(fread(fid,256,'uint16'))'; %#ok<FREAD>
% read in more info
tmp=fread(fid,9,'uint32'); assert(tmp(8)==0);
fps = fread(fid,1,'float64'); codec=['imageFormat' int2str2(tmp(6),3)];
% store information in info struct
info=struct( 'width',tmp(1), 'height',tmp(2), 'imageBitDepth',tmp(3), ...
'imageBitDepthReal',tmp(4), 'imageSizeBytes',tmp(5), ...
'imageFormat',tmp(6), 'numFrames',tmp(7), 'trueImageSize', tmp(9),...
'fps',fps, 'seqVersion',version, 'codec',codec, 'descr',descr, ...
'nHiddenFinalFrames',0 );
assert(info.imageBitDepthReal==8);
% seek to end of header
fseek(fid,432,'cof');
end
|
github
|
P-Chao/acfdetect-master
|
pcaApply.m
|
.m
|
acfdetect-master/toolbox/classify/pcaApply.m
| 3,320 |
utf_8
|
a06fc0e54d85930cbc0536c874ac63b7
|
function varargout = pcaApply( X, U, mu, k )
% Companion function to pca.
%
% Use pca.m to retrieve the principal components U and the mean mu from a
% set of vectors x, then use pcaApply to get the first k coefficients of
% x in the space spanned by the columns of U. See pca for general usage.
%
% If x is large, pcaApply first splits and processes x in parts. This
% allows pcaApply to work even for very large arrays.
%
% This may prove useful:
% siz=size(X); k=100; Uim=reshape(U(:,1:k),[siz(1:end-1) k ]);
%
% USAGE
% [ Yk, Xhat, avsq ] = pcaApply( X, U, mu, k )
%
% INPUTS
% X - data for which to get PCA coefficients
% U - returned by pca.m
% mu - returned by pca.m
% k - number of principal coordinates to approximate X with
%
% OUTPUTS
% Yk - first k coordinates of X in column space of U
% Xhat - approximation of X corresponding to Yk
% avsq - measure of squared error normalized to fall between [0,1]
%
% EXAMPLE
%
% See also PCA, PCAVISUALIZE
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% sizes / dimensions
siz = size(X); nd = ndims(X); [D,r] = size(U);
if(D==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
n = siz(end);
% some error checking
if(prod(siz(1:end-1))~=D); error('incorrect size for X or U'); end
if(isa(X,'uint8')); X = double(X); end
if(k>r); warning(['k set to ' int2str(r)]); k=r; end; %#ok<WNTAG>
% If X is small simply call pcaApply1 once.
% OW break up X and call pcaApply1 multiple times and recombine.
maxWidth = ceil( (10^7) / D );
if( maxWidth > n )
varargout = cell(1,nargout);
[varargout{:}] = pcaApply1( X, U, mu, k );
else
inds = {':'}; inds = inds(:,ones(1,nd-1));
Yk = zeros( k, n ); Xhat = zeros( siz );
avsq = 0; avsqOrig = 0; last = 0;
if( nargout==3 ); out=cell(1,4); else out=cell(1,nargout); end;
while(last < n)
first=last+1; last=min(first+maxWidth-1,n);
Xi = X(inds{:}, first:last);
[out{:}] = pcaApply1( Xi, U, mu, k );
Yk(:,first:last) = out{1};
if( nargout>=2 ); Xhat(inds{:},first:last)=out{2}; end;
if( nargout>=3 ); avsq=avsq+out{3}; avsqOrig=avsqOrig+out{4}; end;
end;
varargout = {Yk, Xhat, avsq/avsqOrig};
end
function [ Yk, Xhat, avsq, avsqOrig ] = pcaApply1( X, U, mu, k )
% sizes / dimensions
siz = size(X); nd = ndims(X); [D,r] = size(U);
if(D==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
n = siz(end);
% subtract mean, then flatten X
Xorig = X;
muRep = repmat(mu, [ones(1,nd-1), n ] );
X = X - muRep;
X = reshape( X, D, n );
% Find Yk, the first k coefficients of X in the new basis
if( r<=k ); Uk=U; else Uk=U(:,1:k); end;
Yk = Uk' * X;
% calculate Xhat - the approx of X using the first k princ components
if( nargout>1 )
Xhat = Uk * Yk;
Xhat = reshape( Xhat, siz );
Xhat = Xhat + muRep;
end
% caclulate average value of (Xhat-Xorig).^2 compared to average value
% of X.^2, where X is Xorig without the mean. This is equivalent to
% what fraction of the variance is captured by Xhat.
if( nargout>2 )
avsq = Xhat - Xorig;
avsq = dot(avsq(:),avsq(:));
avsqOrig = dot(X(:),X(:));
if( nargout==3 ); avsq=avsq/avsqOrig; end
end
|
github
|
P-Chao/acfdetect-master
|
forestTrain.m
|
.m
|
acfdetect-master/toolbox/classify/forestTrain.m
| 6,138 |
utf_8
|
de534e2a010f452a7b13167dbf9df239
|
function forest = forestTrain( data, hs, varargin )
% Train random forest classifier.
%
% Dimensions:
% M - number trees
% F - number features
% N - number input vectors
% H - number classes
%
% USAGE
% forest = forestTrain( data, hs, [varargin] )
%
% INPUTS
% data - [NxF] N length F feature vectors
% hs - [Nx1] or {Nx1} target output labels in [1,H]
% varargin - additional params (struct or name/value pairs)
% .M - [1] number of trees to train
% .H - [max(hs)] number of classes
% .N1 - [5*N/M] number of data points for training each tree
% .F1 - [sqrt(F)] number features to sample for each node split
% .split - ['gini'] options include 'gini', 'entropy' and 'twoing'
% .minCount - [1] minimum number of data points to allow split
% .minChild - [1] minimum number of data points allowed at child nodes
% .maxDepth - [64] maximum depth of tree
% .dWts - [] weights used for sampling and weighing each data point
% .fWts - [] weights used for sampling features
% .discretize - [] optional function mapping structured to class labels
% format: [hsClass,hBest] = discretize(hsStructured,H);
%
% OUTPUTS
% forest - learned forest model struct array w the following fields
% .fids - [Kx1] feature ids for each node
% .thrs - [Kx1] threshold corresponding to each fid
% .child - [Kx1] index of child for each node
% .distr - [KxH] prob distribution at each node
% .hs - [Kx1] or {Kx1} most likely label at each node
% .count - [Kx1] number of data points at each node
% .depth - [Kx1] depth of each node
%
% EXAMPLE
% N=10000; H=5; d=2; [xs0,hs0,xs1,hs1]=demoGenData(N,N,H,d,1,1);
% xs0=single(xs0); xs1=single(xs1);
% pTrain={'maxDepth',50,'F1',2,'M',150,'minChild',5};
% tic, forest=forestTrain(xs0,hs0,pTrain{:}); toc
% hsPr0 = forestApply(xs0,forest);
% hsPr1 = forestApply(xs1,forest);
% e0=mean(hsPr0~=hs0); e1=mean(hsPr1~=hs1);
% fprintf('errors trn=%f tst=%f\n',e0,e1); figure(1);
% subplot(2,2,1); visualizeData(xs0,2,hs0);
% subplot(2,2,2); visualizeData(xs0,2,hsPr0);
% subplot(2,2,3); visualizeData(xs1,2,hs1);
% subplot(2,2,4); visualizeData(xs1,2,hsPr1);
%
% See also forestApply, fernsClfTrain
%
% Piotr's Computer Vision Matlab Toolbox Version 3.24
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get additional parameters and fill in remaining parameters
dfs={ 'M',1, 'H',[], 'N1',[], 'F1',[], 'split','gini', 'minCount',1, ...
'minChild',1, 'maxDepth',64, 'dWts',[], 'fWts',[], 'discretize','' };
[M,H,N1,F1,splitStr,minCount,minChild,maxDepth,dWts,fWts,discretize] = ...
getPrmDflt(varargin,dfs,1);
[N,F]=size(data); assert(length(hs)==N); discr=~isempty(discretize);
minChild=max(1,minChild); minCount=max([1 minCount minChild]);
if(isempty(H)), H=max(hs); end; assert(discr || all(hs>0 & hs<=H));
if(isempty(N1)), N1=round(5*N/M); end; N1=min(N,N1);
if(isempty(F1)), F1=round(sqrt(F)); end; F1=min(F,F1);
if(isempty(dWts)), dWts=ones(1,N,'single'); end; dWts=dWts/sum(dWts);
if(isempty(fWts)), fWts=ones(1,F,'single'); end; fWts=fWts/sum(fWts);
split=find(strcmpi(splitStr,{'gini','entropy','twoing'}))-1;
if(isempty(split)), error('unknown splitting criteria: %s',splitStr); end
% make sure data has correct types
if(~isa(data,'single')), data=single(data); end
if(~isa(hs,'uint32') && ~discr), hs=uint32(hs); end
if(~isa(fWts,'single')), fWts=single(fWts); end
if(~isa(dWts,'single')), dWts=single(dWts); end
% train M random trees on different subsets of data
prmTree = {H,F1,minCount,minChild,maxDepth,fWts,split,discretize};
for i=1:M
if(N==N1), data1=data; hs1=hs; dWts1=dWts; else
d=wswor(dWts,N1,4); data1=data(d,:); hs1=hs(d);
dWts1=dWts(d); dWts1=dWts1/sum(dWts1);
end
tree = treeTrain(data1,hs1,dWts1,prmTree);
if(i==1), forest=tree(ones(M,1)); else forest(i)=tree; end
end
end
function tree = treeTrain( data, hs, dWts, prmTree )
% Train single random tree.
[H,F1,minCount,minChild,maxDepth,fWts,split,discretize]=deal(prmTree{:});
N=size(data,1); K=2*N-1; discr=~isempty(discretize);
thrs=zeros(K,1,'single'); distr=zeros(K,H,'single');
fids=zeros(K,1,'uint32'); child=fids; count=fids; depth=fids;
hsn=cell(K,1); dids=cell(K,1); dids{1}=uint32(1:N); k=1; K=2;
while( k < K )
% get node data and store distribution
dids1=dids{k}; dids{k}=[]; hs1=hs(dids1); n1=length(hs1); count(k)=n1;
if(discr), [hs1,hsn{k}]=feval(discretize,hs1,H); hs1=uint32(hs1); end
if(discr), assert(all(hs1>0 & hs1<=H)); end; pure=all(hs1(1)==hs1);
if(~discr), if(pure), distr(k,hs1(1))=1; hsn{k}=hs1(1); else
distr(k,:)=histc(hs1,1:H)/n1; [~,hsn{k}]=max(distr(k,:)); end; end
% if pure node or insufficient data don't train split
if( pure || n1<=minCount || depth(k)>maxDepth ), k=k+1; continue; end
% train split and continue
fids1=wswor(fWts,F1,4); data1=data(dids1,fids1);
[~,order1]=sort(data1); order1=uint32(order1-1);
[fid,thr,gain]=forestFindThr(data1,hs1,dWts(dids1),order1,H,split);
fid=fids1(fid); left=data(dids1,fid)<thr; count0=nnz(left);
if( gain>1e-10 && count0>=minChild && (n1-count0)>=minChild )
child(k)=K; fids(k)=fid-1; thrs(k)=thr;
dids{K}=dids1(left); dids{K+1}=dids1(~left);
depth(K:K+1)=depth(k)+1; K=K+2;
end; k=k+1;
end
% create output model struct
K=1:K-1; if(discr), hsn={hsn(K)}; else hsn=[hsn{K}]'; end
tree=struct('fids',fids(K),'thrs',thrs(K),'child',child(K),...
'distr',distr(K,:),'hs',hsn,'count',count(K),'depth',depth(K));
end
function ids = wswor( prob, N, trials )
% Fast weighted sample without replacement. Alternative to:
% ids=datasample(1:length(prob),N,'weights',prob,'replace',false);
M=length(prob); assert(N<=M); if(N==M), ids=1:N; return; end
if(all(prob(1)==prob)), ids=randperm(M,N); return; end
cumprob=min([0 cumsum(prob)],1); assert(abs(cumprob(end)-1)<.01);
cumprob(end)=1; [~,ids]=histc(rand(N*trials,1),cumprob);
[s,ord]=sort(ids); K(ord)=[1; diff(s)]~=0; ids=ids(K);
if(length(ids)<N), ids=wswor(cumprob,N,trials*2); end
ids=ids(1:N)';
end
|
github
|
P-Chao/acfdetect-master
|
fernsRegTrain.m
|
.m
|
acfdetect-master/toolbox/classify/fernsRegTrain.m
| 5,914 |
utf_8
|
b9ed2d87a22cb9cbb1e2632495ddaf1d
|
function [ferns,ysPr] = fernsRegTrain( data, ys, varargin )
% Train boosted fern regressor.
%
% Boosted regression using random ferns as the weak regressor. See "Greedy
% function approximation: A gradient boosting machine", Friedman, Annals of
% Statistics 2001, for more details on boosted regression.
%
% A few notes on the parameters: 'type' should in general be set to 'res'
% (the 'ave' version is an undocumented variant that only performs well
% under limited conditions). 'loss' determines the loss function being
% optimized, in general the 'L2' version is the most robust and effective.
% 'reg' is a regularization term for the ferns, a low value such as .01 can
% improve results. Setting the learning rate 'eta' is crucial in order to
% achieve good performance, especially on noisy data. In general, eta
% should decreased as M is increased.
%
% Dimensions:
% M - number ferns
% R - number repeats
% S - fern depth
% N - number samples
% F - number features
%
% USAGE
% [ferns,ysPr] = fernsRegTrain( data, hs, [varargin] )
%
% INPUTS
% data - [NxF] N length F feature vectors
% ys - [Nx1] target output values
% varargin - additional params (struct or name/value pairs)
% .type - ['res'] options include {'res','ave'}
% .loss - ['L2'] options include {'L1','L2','exp'}
% .S - [2] fern depth (ferns are exponential in S)
% .M - [50] number ferns (same as number phases)
% .R - [10] number repetitions per fern
% .thrr - [0 1] range for randomly generated thresholds
% .reg - [0.01] fern regularization term in [0,1]
% .eta - [1] learning rate in [0,1] (not used if type='ave')
% .verbose - [0] if true output info to display
%
% OUTPUTS
% ferns - learned fern model w the following fields
% .fids - [MxS] feature ids for each fern for each depth
% .thrs - [MxS] threshold corresponding to each fid
% .ysFern - [2^SxM] stored values at fern leaves
% .loss - loss(ys,ysGt) computes loss of ys relateive to ysGt
% ysPr - [Nx1] predicted output values
%
% EXAMPLE
% %% generate toy data
% N=1000; sig=.5; f=@(x) cos(x*pi*4)+(x+1).^2;
% xs0=rand(N,1); ys0=f(xs0)+randn(N,1)*sig;
% xs1=rand(N,1); ys1=f(xs1)+randn(N,1)*sig;
% %% train and apply fern regressor
% prm=struct('type','res','loss','L2','eta',.05,...
% 'thrr',[-1 1],'reg',.01,'S',2,'M',1000,'R',3,'verbose',0);
% tic, [ferns,ysPr0] = fernsRegTrain(xs0,ys0,prm); toc
% tic, ysPr1 = fernsRegApply( xs1, ferns ); toc
% fprintf('errors train=%f test=%f\n',...
% ferns.loss(ysPr0,ys0),ferns.loss(ysPr1,ys1));
% %% visualize results
% figure(1); clf; hold on; plot(xs0,ys0,'.b'); plot(xs0,ysPr0,'.r');
% figure(2); clf; hold on; plot(xs1,ys1,'.b'); plot(xs1,ysPr1,'.r');
%
% See also fernsRegApply, fernsInds
%
% Piotr's Computer Vision Matlab Toolbox Version 2.50
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get/check parameters
dfs={'type','res','loss','L2','S',2,'M',50,'R',10,'thrr',[0 1],...
'reg',0.01,'eta',1,'verbose',0};
[type,loss,S,M,R,thrr,reg,eta,verbose]=getPrmDflt(varargin,dfs,1);
type=type(1:3); assert(any(strcmp(type,{'res','ave'})));
assert(any(strcmp(loss,{'L1','L2','exp'}))); N=length(ys);
if(strcmp(type,'ave')), eta=1; end
% train stagewise regressor (residual or average)
fids=zeros(M,S,'uint32'); thrs=zeros(M,S);
ysSum=zeros(N,1); ysFern=zeros(2^S,M);
for m=1:M
% train R random ferns using different losses, keep best
if(strcmp(type,'ave')), d=m; else d=1; end
ysTar=d*ys-ysSum; best={};
if(strcmp(loss,'L1')), e=sum(abs(ysTar));
for r=1:R
[fids1,thrs1,ysFern1,ys1]=trainFern(data,sign(ysTar),S,thrr,reg);
a=medianw(ysTar./ys1,abs(ys1)); ysFern1=ysFern1*a; ys1=ys1*a;
e1=sum(abs(ysTar-ys1));
if(e1<=e), e=e1; best={fids1,thrs1,ysFern1,ys1}; end
end
elseif(strcmp(loss,'L2')), e=sum(ysTar.^2);
for r=1:R
[fids1,thrs1,ysFern1,ys1]=trainFern(data,ysTar,S,thrr,reg);
e1=sum((ysTar-ys1).^2);
if(e1<=e), e=e1; best={fids1,thrs1,ysFern1,ys1}; end
end
elseif(strcmp(loss,'exp')), e=sum(exp(ysTar/d)+exp(-ysTar/d));
ysDeriv=exp(ysTar/d)-exp(-ysTar/d);
for r=1:R
[fids1,thrs1,ysFern1,ys1]=trainFern(data,ysDeriv,S,thrr,reg);
e1=inf; if(m==1), aBst=1; end; aMin=aBst/5; aMax=aBst*5;
for phase=1:3, aDel=(aMax-aMin)/10;
for a=aMin:aDel:aMax
eTmp=sum(exp((ysTar-a*ys1)/d)+exp((a*ys1-ysTar)/d));
if(eTmp<e1), a1=a; e1=eTmp; end
end; aMin=a1-aDel; aMax=a1+aDel;
end; ysFern1=ysFern1*a1; ys1=ys1*a1;
if(e1<=e), e=e1; aBst=a1; best={fids1,thrs1,ysFern1,ys1}; end
end
end
% store results and update sums
assert(~isempty(best)); [fids1,thrs1,ysFern1,ys1]=deal(best{:});
fids(m,:)=fids1; thrs(m,:)=thrs1;
ysFern(:,m)=ysFern1*eta; ysSum=ysSum+ys1*eta;
if(verbose), fprintf('phase=%i error=%f\n',m,e); end
end
% create output struct
if(strcmp(type,'ave')), d=M; else d=1; end; clear data;
ferns=struct('fids',fids,'thrs',thrs,'ysFern',ysFern/d); ysPr=ysSum/d;
switch loss
case 'L1', ferns.loss=@(ys,ysGt) mean(abs(ys-ysGt));
case 'L2', ferns.loss=@(ys,ysGt) mean((ys-ysGt).^2);
case 'exp', ferns.loss=@(ys,ysGt) mean(exp(ys-ysGt)+exp(ysGt-ys))-2;
end
end
function [fids,thrs,ysFern,ysPr] = trainFern( data, ys, S, thrr, reg )
% Train single random fern regressor.
[N,F]=size(data); mu=sum(ys)/N; ys=ys-mu;
fids = uint32(floor(rand(1,S)*F+1));
thrs = rand(1,S)*(thrr(2)-thrr(1))+thrr(1);
inds = fernsInds(data,fids,thrs);
ysFern=zeros(2^S,1); cnts=zeros(2^S,1);
for n=1:N, ind=inds(n);
ysFern(ind)=ysFern(ind)+ys(n);
cnts(ind)=cnts(ind)+1;
end
ysFern = ysFern ./ max(cnts+reg*N,eps) + mu;
ysPr = ysFern(inds);
end
function m = medianw(x,w)
% Compute weighted median of x.
[x,ord]=sort(x(:)); w=w(ord);
[~,ind]=max(cumsum(w)>=sum(w)/2);
m = x(ind);
end
|
github
|
P-Chao/acfdetect-master
|
rbfDemo.m
|
.m
|
acfdetect-master/toolbox/classify/rbfDemo.m
| 2,929 |
utf_8
|
14cc64fb77bcac3edec51cf6b84ab681
|
function rbfDemo( dataType, noiseSig, scale, k, cluster, show )
% Demonstration of rbf networks for regression.
%
% See rbfComputeBasis for discussion of rbfs.
%
% USAGE
% rbfDemo( dataType, noiseSig, scale, k, cluster, show )
%
% INPUTS
% dataType - 0: 1D sinusoid
% 1: 2D sinusoid
% 2: 2D stretched sinusoid
% noiseSig - std of idd gaussian noise
% scale - see rbfComputeBasis
% k - see rbfComputeBasis
% cluster - see rbfComputeBasis
% show - figure to use for display (no display if == 0)
%
% OUTPUTS
%
% EXAMPLE
% rbfDemo( 0, .2, 2, 5, 0, 1 );
% rbfDemo( 1, .2, 2, 50, 0, 3 );
% rbfDemo( 2, .2, 5, 50, 0, 5 );
%
% See also RBFCOMPUTEBASIS, RBFCOMPUTEFTRS
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%%% generate trn/tst data
if( 1 )
[Xtrn,ytrn] = rbfToyData( 500, noiseSig, dataType );
[Xtst,ytst] = rbfToyData( 100, noiseSig, dataType );
end;
%%% trn/apply rbfs
rbfBasis = rbfComputeBasis( Xtrn, k, cluster, scale, show );
rbfWeight = rbfComputeFtrs(Xtrn,rbfBasis) \ ytrn;
yTrnRes = rbfComputeFtrs(Xtrn,rbfBasis) * rbfWeight;
yTstRes = rbfComputeFtrs(Xtst,rbfBasis) * rbfWeight;
%%% get relative errors
fracErrorTrn = sum((ytrn-yTrnRes).^2) / sum(ytrn.^2);
fracErrorTst = sum((ytst-yTstRes).^2) / sum(ytst.^2);
%%% display output
display(fracErrorTst);
display(fracErrorTrn);
display(rbfBasis);
%%% visualize surface
minX = min([Xtrn; Xtst],[],1); maxX = max([Xtrn; Xtst],[],1);
if( size(Xtrn,2)==1 )
xs = linspace( minX, maxX, 1000 )';
ys = rbfComputeFtrs(xs,rbfBasis) * rbfWeight;
figure(show+1); clf; hold on; plot( xs, ys );
plot( Xtrn, ytrn, '.b' ); plot( Xtst, ytst, '.r' );
elseif( size(Xtrn,2)==2 )
xs1 = linspace(minX(1),maxX(1),25);
xs2 = linspace(minX(2),maxX(2),25);
[xs1,xs2] = ndgrid( xs1, xs2 );
ys = rbfComputeFtrs([xs1(:) xs2(:)],rbfBasis) * rbfWeight;
figure(show+1); clf; surf( xs1, xs2, reshape(ys,size(xs1)) ); hold on;
plot3( Xtrn(:,1), Xtrn(:,2), ytrn, '.b' );
plot3( Xtst(:,1), Xtst(:,2), ytst, '.r' );
end
function [X,y] = rbfToyData( N, noiseSig, dataType )
% Toy data for rbfDemo.
%
% USAGE
% [X,y] = rbfToyData( N, noiseSig, dataType )
%
% INPUTS
% N - number of points
% dataType - 0: 1D sinusoid
% 1: 2D sinusoid
% 2: 2D stretched sinusoid
% noiseSig - std of idd gaussian noise
%
% OUTPUTS
% X - [N x d] N points of d dimensions each
% y - [1 x N] value at example i
%%% generate data
if( dataType==0 )
X = rand( N, 1 ) * 10;
y = sin( X );
elseif( dataType==1 )
X = rand( N, 2 ) * 10;
y = sin( X(:,1)+X(:,2) );
elseif( dataType==2 )
X = rand( N, 2 ) * 10;
y = sin( X(:,1)+X(:,2) );
X(:,2) = X(:,2) * 5;
else
error('unknown dataType');
end
y = y + randn(size(y))*noiseSig;
|
github
|
P-Chao/acfdetect-master
|
pdist2.m
|
.m
|
acfdetect-master/toolbox/classify/pdist2.m
| 5,162 |
utf_8
|
768ff9e8818251f756c8325368ee7d90
|
function D = pdist2( X, Y, metric )
% Calculates the distance between sets of vectors.
%
% Let X be an m-by-p matrix representing m points in p-dimensional space
% and Y be an n-by-p matrix representing another set of points in the same
% space. This function computes the m-by-n distance matrix D where D(i,j)
% is the distance between X(i,:) and Y(j,:). This function has been
% optimized where possible, with most of the distance computations
% requiring few or no loops.
%
% The metric can be one of the following:
%
% 'euclidean' / 'sqeuclidean':
% Euclidean / SQUARED Euclidean distance. Note that 'sqeuclidean'
% is significantly faster.
%
% 'chisq'
% The chi-squared distance between two vectors is defined as:
% d(x,y) = sum( (xi-yi)^2 / (xi+yi) ) / 2;
% The chi-squared distance is useful when comparing histograms.
%
% 'cosine'
% Distance is defined as the cosine of the angle between two vectors.
%
% 'emd'
% Earth Mover's Distance (EMD) between positive vectors (histograms).
% Note for 1D, with all histograms having equal weight, there is a simple
% closed form for the calculation of the EMD. The EMD between histograms
% x and y is given by the sum(abs(cdf(x)-cdf(y))), where cdf is the
% cumulative distribution function (computed simply by cumsum).
%
% 'L1'
% The L1 distance between two vectors is defined as: sum(abs(x-y));
%
%
% USAGE
% D = pdist2( X, Y, [metric] )
%
% INPUTS
% X - [m x p] matrix of m p-dimensional vectors
% Y - [n x p] matrix of n p-dimensional vectors
% metric - ['sqeuclidean'], 'chisq', 'cosine', 'emd', 'euclidean', 'L1'
%
% OUTPUTS
% D - [m x n] distance matrix
%
% EXAMPLE
% % simple example where points cluster well
% [X,IDX] = demoGenData(100,0,5,4,10,2,0);
% D = pdist2( X, X, 'sqeuclidean' );
% distMatrixShow( D, IDX );
% % comparison to pdist
% n=500; d=200; r=100; X=rand(n,d);
% tic, for i=1:r, D1 = pdist( X, 'euclidean' ); end, toc
% tic, for i=1:r, D2 = pdist2( X, X, 'euclidean' ); end, toc
% D1=squareform(D1); del=D1-D2; sum(abs(del(:)))
%
% See also pdist, distMatrixShow
%
% Piotr's Computer Vision Matlab Toolbox Version 2.52
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<3 || isempty(metric) ); metric=0; end;
switch metric
case {0,'sqeuclidean'}
D = distEucSq( X, Y );
case 'euclidean'
D = sqrt(distEucSq( X, Y ));
case 'L1'
D = distL1( X, Y );
case 'cosine'
D = distCosine( X, Y );
case 'emd'
D = distEmd( X, Y );
case 'chisq'
D = distChiSq( X, Y );
otherwise
error(['pdist2 - unknown metric: ' metric]);
end
D = max(0,D);
end
function D = distL1( X, Y )
m = size(X,1); n = size(Y,1);
mOnes = ones(1,m); D = zeros(m,n);
for i=1:n
yi = Y(i,:); yi = yi( mOnes, : );
D(:,i) = sum( abs( X-yi),2 );
end
end
function D = distCosine( X, Y )
p=size(X,2);
XX = sqrt(sum(X.*X,2)); X = X ./ XX(:,ones(1,p));
YY = sqrt(sum(Y.*Y,2)); Y = Y ./ YY(:,ones(1,p));
D = 1 - X*Y';
end
function D = distEmd( X, Y )
Xcdf = cumsum(X,2);
Ycdf = cumsum(Y,2);
m = size(X,1); n = size(Y,1);
mOnes = ones(1,m); D = zeros(m,n);
for i=1:n
ycdf = Ycdf(i,:);
ycdfRep = ycdf( mOnes, : );
D(:,i) = sum(abs(Xcdf - ycdfRep),2);
end
end
function D = distChiSq( X, Y )
% note: supposedly it's possible to implement this without a loop!
m = size(X,1); n = size(Y,1);
mOnes = ones(1,m); D = zeros(m,n);
for i=1:n
yi = Y(i,:); yiRep = yi( mOnes, : );
s = yiRep + X; d = yiRep - X;
D(:,i) = sum( d.^2 ./ (s+eps), 2 );
end
D = D/2;
end
function D = distEucSq( X, Y )
Yt = Y';
XX = sum(X.*X,2);
YY = sum(Yt.*Yt,1);
D = bsxfun(@plus,XX,YY)-2*X*Yt;
end
%%%% code from Charles Elkan with variables renamed
% function D = distEucSq( X, Y )
% m = size(X,1); n = size(Y,1);
% D = sum(X.^2, 2) * ones(1,n) + ones(m,1) * sum(Y.^2, 2)' - 2.*X*Y';
% end
%%% LOOP METHOD - SLOW
% [m p] = size(X);
% [n p] = size(Y);
% D = zeros(m,n);
% onesM = ones(m,1);
% for i=1:n
% y = Y(i,:);
% d = X - y(onesM,:);
% D(:,i) = sum( d.*d, 2 );
% end
%%% PARALLEL METHOD THAT IS SUPER SLOW (slower than loop)!
% % From "MATLAB array manipulation tips and tricks" by Peter J. Acklam
% Xb = permute(X, [1 3 2]);
% Yb = permute(Y, [3 1 2]);
% D = sum( (Xb(:,ones(1,n),:) - Yb(ones(1,m),:,:)).^2, 3);
%%% USELESS FOR EVEN VERY LARGE ARRAYS X=16000x1000!! and Y=100x1000
% call recursively to save memory
% if( (m+n)*p > 10^5 && (m>1 || n>1))
% if( m>n )
% X1 = X(1:floor(end/2),:);
% X2 = X((floor(end/2)+1):end,:);
% D1 = distEucSq( X1, Y );
% D2 = distEucSq( X2, Y );
% D = cat( 1, D1, D2 );
% else
% Y1 = Y(1:floor(end/2),:);
% Y2 = Y((floor(end/2)+1):end,:);
% D1 = distEucSq( X, Y1 );
% D2 = distEucSq( X, Y2 );
% D = cat( 2, D1, D2 );
% end
% return;
% end
%%% L1 COMPUTATION WITH LOOP OVER p, FAST FOR SMALL p.
% function D = distL1( X, Y )
%
% m = size(X,1); n = size(Y,1); p = size(X,2);
% mOnes = ones(1,m); nOnes = ones(1,n); D = zeros(m,n);
% for i=1:p
% yi = Y(:,i); yi = yi( :, mOnes );
% xi = X(:,i); xi = xi( :, nOnes );
% D = D + abs( xi-yi' );
% end
|
github
|
P-Chao/acfdetect-master
|
pca.m
|
.m
|
acfdetect-master/toolbox/classify/pca.m
| 3,244 |
utf_8
|
848f2eb05c18a6e448e9d22af27b9422
|
function [U,mu,vars] = pca( X )
% Principal components analysis (alternative to princomp).
%
% A simple linear dimensionality reduction technique. Use to create an
% orthonormal basis for the points in R^d such that the coordinates of a
% vector x in this basis are of decreasing importance. Instead of using all
% d basis vectors to specify the location of x, using only the first k<d
% still gives a vector xhat that is close to x.
%
% This function operates on arrays of arbitrary dimension, by first
% converting the arrays to vectors. If X is m+1 dimensional, say of size
% [d1 x d2 x...x dm x n], then the first m dimensions of X are combined. X
% is flattened to be 2 dimensional: [dxn], with d=prod(di). Once X is
% converted to 2 dimensions of size dxn, each column represents a single
% observation, and each row is a different variable. Note that this is the
% opposite of many matlab functions such as princomp. If X is MxNxn, then
% X(:,:,i) represents the ith observation (useful for stack of n images),
% likewise for n videos X is MxNxKxn. If X is very large, it is sampled
% before running PCA. Use this function to retrieve the basis U. Use
% pcaApply to retrieve that basis coefficients for a novel vector x. Use
% pcaVisualize(X,...) for visualization of approximated X.
%
% To calculate residuals:
% residuals = cumsum(vars/sum(vars)); plot(residuals,'-.')
%
% USAGE
% [U,mu,vars] = pca( X )
%
% INPUTS
% X - [d1 x ... x dm x n], treated as n [d1 x ... x dm] elements
%
% OUTPUTS
% U - [d x r], d=prod(di), each column is a principal component
% mu - [d1 x ... x dm] mean of X
% vars - sorted eigenvalues corresponding to eigenvectors in U
%
% EXAMPLE
% load pcaData;
% [U,mu,vars] = pca( I3D1(:,:,1:12) );
% [Y,Xhat,avsq] = pcaApply( I3D1(:,:,1), U, mu, 5 );
% pcaVisualize( U, mu, vars, I3D1, 13, [0:12], [], 1 );
% Xr = pcaRandVec( U, mu, vars, 1, 25, 0, 3 );
%
% See also princomp, pcaApply, pcaVisualize, pcaRandVec, visualizeData
%
% Piotr's Computer Vision Matlab Toolbox Version 3.24
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% set X to be zero mean, then flatten
d=size(X); n=d(end); d=prod(d(1:end-1));
if(~isa(X,'double')), X=double(X); end
if(n==1); mu=X; U=zeros(d,1); vars=0; return; end
mu = mean( X, ndims(X) );
X = bsxfun(@minus,X,mu)/sqrt(n-1);
X = reshape( X, d, n );
% make sure X not too large or SVD slow O(min(d,n)^2.5)
m=2500; if( min(d,n)>m ), X=X(:,randperm(n,m)); n=m; end
% get principal components using the SVD of X: X=U*S*V'
if( 0 )
[U,S]=svd(X,'econ'); vars=diag(S).^2;
elseif( d>n )
[~,SS,V]=robustSvd(X'*X); vars=diag(SS);
U = X * V * diag(1./sqrt(vars));
else
[~,SS,U]=robustSvd(X*X'); vars=diag(SS);
end
% discard low variance prinicipal components
K=vars>1e-30; vars=vars(K); U=U(:,K);
end
function [U,S,V] = robustSvd( X, trials )
% Robust version of SVD more likely to always converge.
% [Converge issues only seem to appear on Matlab 2013a in Windows.]
if(nargin<2), trials=100; end
try [U,S,V] = svd(X); catch
if(trials<=0), error('svd did not converge'); end
n=numel(X); j=randi(n); X(j)=X(j)+eps;
[U,S,V]=robustSvd(X,trials-1);
end
end
|
github
|
P-Chao/acfdetect-master
|
kmeans2.m
|
.m
|
acfdetect-master/toolbox/classify/kmeans2.m
| 5,251 |
utf_8
|
f941053f03c3e9eda40389a4cc64ee00
|
function [ IDX, C, d ] = kmeans2( X, k, varargin )
% Fast version of kmeans clustering.
%
% Cluster the N x p matrix X into k clusters using the kmeans algorithm. It
% returns the cluster memberships for each data point in the N x 1 vector
% IDX and the K x p matrix of cluster means in C.
%
% This function is in some ways less general than Matlab's kmeans.m (for
% example it only uses euclidian distance), but it has some options that
% the Matlab version does not (for example, it has a notion of outliers and
% min-cluster size). It is also many times faster than matlab's kmeans.
% General kmeans help can be found in help for the matlab implementation of
% kmeans. Note that the although the names and conventions for this
% algorithm are taken from Matlab's implementation, there are slight
% alterations (for example, IDX==-1 is used to indicate outliers).
%
% IDX is a n-by-1 vector used to indicated cluster membership. Let X be a
% set of n points. Then the ID of X - or IDX is a column vector of length
% n, where each element is an integer indicating the cluster membership of
% the corresponding element in X. IDX(i)=c indicates that the ith point in
% X belongs to cluster c. Cluster labels range from 1 to k, and thus
% k=max(IDX) is typically the number of clusters IDX divides X into. The
% cluster label "-1" is reserved for outliers. IDX(i)==-1 indicates that
% the given point does not belong to any of the discovered clusters. Note
% that matlab's version of kmeans does not have outliers.
%
% USAGE
% [ IDX, C, d ] = kmeans2( X, k, [varargin] )
%
% INPUTS
% X - [n x p] matrix of n p-dim vectors.
% k - maximum nuber of clusters (actual number may be smaller)
% prm - additional params (struct or name/value pairs)
% .k - [] alternate way of specifying k (if not given above)
% .nTrial - [1] number random restarts
% .maxIter - [100] max number of iterations
% .display - [0] Whether or not to display algorithm status
% .rndSeed - [] random seed for kmeans; useful for replicability
% .outFrac - [0] max frac points that can be treated as outliers
% .minCl - [1] min cluster size (smaller clusters get eliminated)
% .metric - [] metric for pdist2
% .C0 - [] initial cluster centers for first trial
%
% OUTPUTS
% IDX - [n x 1] cluster membership (see above)
% C - [k x p] matrix of centroid locations C(j,:) = mean(X(IDX==j,:))
% d - [1 x k] d(j) is sum of distances from X(IDX==j,:) to C(j,:)
% sum(d) is a typical measure of the quality of a clustering
%
% EXAMPLE
%
% See also DEMOCLUSTER
%
% Piotr's Computer Vision Matlab Toolbox Version 3.24
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get input args
dfs = {'nTrial',1, 'maxIter',100, 'display',0, 'rndSeed',[],...
'outFrac',0, 'minCl',1, 'metric',[], 'C0',[],'k',k };
[nTrial,maxt,dsp,rndSeed,outFrac,minCl,metric,C0,k] = ...
getPrmDflt(varargin,dfs); assert(~isempty(k) && k>0);
% error checking
if(k<1); error('k must be greater than 1'); end
if(~ismatrix(X) || any(size(X)==0)); error('Illegal X'); end
if(outFrac<0 || outFrac>=1), error('outFrac must be in [0,1)'); end
nOut = floor( size(X,1)*outFrac );
% initialize random seed if specified
if(~isempty(rndSeed)); rand('state',rndSeed); end; %#ok<RAND>
% run kmeans2main nTrial times
bd=inf; t0=clock;
for i=1:nTrial, t1=clock; if(i>1), C0=[]; end
if(dsp), fprintf('kmeans2 iter %i/%i step: ',i,nTrial); end
[IDX,C,d]=kmeans2main(X,k,nOut,minCl,maxt,dsp,metric,C0);
if(sum(d)<sum(bd)), bIDX=IDX; bC=C; bd=d; end
if(dsp), fprintf(' d=%f t=%fs\n',sum(d),etime(clock,t1)); end
end
IDX=bIDX; C=bC; d=bd; k=max(IDX);
if(dsp), fprintf('k=%i d=%f t=%fs\n',k,sum(d),etime(clock,t0)); end
% sort IDX to have biggest clusters have lower indicies
cnts = zeros(1,k); for i=1:k; cnts(i) = sum( IDX==i ); end
[~,order] = sort( -cnts ); C = C(order,:); d = d(order);
IDX2=IDX; for i=1:k; IDX2(IDX==order(i))=i; end; IDX = IDX2;
end
function [IDX,C,d] = kmeans2main( X, k, nOut, minCl, maxt, dsp, metric, C )
% initialize cluster centers to be k random X points
[N,p] = size(X); k = min(k,N); t=0;
IDX = ones(N,1); oldIDX = zeros(N,1);
if(isempty(C)), C = X(randperm(N,k),:)+randn(k,p)/1e5; end
% MAIN LOOP: loop until the cluster assigments do not change
if(dsp), nDg=ceil(log10(maxt-1)); fprintf(int2str2(0,nDg)); end
while( any(oldIDX~=IDX) && t<maxt )
% assign each point to closest cluster center
oldIDX=IDX; D=pdist2(X,C,metric); [mind,IDX]=min(D,[],2);
% do not use most distant nOut elements in computation of centers
mind1=sort(mind); thr=mind1(end-nOut); IDX(mind>thr)=-1;
% Recalculate means based on new assignment, discard small clusters
k0=0; C=zeros(k,p);
for IDx=1:k
ids=find(IDX==IDx); nCl=size(ids,1);
if( nCl<minCl ), IDX(ids)=-1; continue; end
k0=k0+1; IDX(ids)=k0; C(k0,:)=sum(X(ids,:),1)/nCl;
end
if(k0>0), k=k0; C=C(1:k,:); else k=1; C=X(randint2(1,1,[1 N]),:); end
t=t+1; if(dsp), fprintf([repmat('\b',[1 nDg]) int2str2(t,nDg)]); end
end
% record within-cluster sums of point-to-centroid distances
d=zeros(1,k); for i=1:k, d(i)=sum(mind(IDX==i)); end
end
|
github
|
P-Chao/acfdetect-master
|
acfModify.m
|
.m
|
acfdetect-master/toolbox/detector/acfModify.m
| 4,202 |
utf_8
|
7a49406d51e7a9431b8fd472be0476e8
|
function detector = acfModify( detector, varargin )
% Modify aggregate channel features object detector.
%
% Takes an object detector trained by acfTrain() and modifies it. Only
% certain modifications are allowed to the detector and the detector should
% never be modified directly (this may cause the detector to be invalid and
% cause segmentation faults). Any valid modification to a detector after it
% is trained should be performed using acfModify().
%
% The parameters 'nPerOct', 'nOctUp', 'nApprox', 'lambdas', 'pad', 'minDs'
% modify the channel feature pyramid created (see help of chnsPyramid.m for
% more details) and primarily control the scales used. The parameters
% 'pNms', 'stride', 'cascThr' and 'cascCal' modify the detector behavior
% (see help of acfTrain.m for more details). Finally, 'rescale' can be
% used to rescale the trained detector (this change is irreversible).
%
% USAGE
% detector = acfModify( detector, pModify )
%
% INPUTS
% detector - detector trained via acfTrain
% pModify - parameters (struct or name/value pairs)
% .nPerOct - [] number of scales per octave
% .nOctUp - [] number of upsampled octaves to compute
% .nApprox - [] number of approx. scales to use
% .lambdas - [] coefficients for power law scaling (see BMVC10)
% .pad - [] amount to pad channels (along T/B and L/R)
% .minDs - [] minimum image size for channel computation
% .pNms - [] params for non-maximal suppression (see bbNms.m)
% .stride - [] spatial stride between detection windows
% .cascThr - [] constant cascade threshold (affects speed/accuracy)
% .cascCal - [] cascade calibration (affects speed/accuracy)
% .rescale - [] rescale entire detector by given ratio
%
% OUTPUTS
% detector - modified object detector
%
% EXAMPLE
%
% See also chnsPyramid, bbNms, acfTrain, acfDetect
%
% Piotr's Computer Vision Matlab Toolbox Version 3.20
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get parameters (and copy to detector and pPyramid structs)
opts=detector.opts; p=opts.pPyramid;
dfs={ 'nPerOct',p.nPerOct, 'nOctUp',p.nOctUp, 'nApprox',p.nApprox, ...
'lambdas',p.lambdas, 'pad',p.pad, 'minDs',p.minDs, 'pNms',opts.pNms, ...
'stride',opts.stride,'cascThr',opts.cascThr,'cascCal',0,'rescale',1 };
[p.nPerOct,p.nOctUp,p.nApprox,p.lambdas,p.pad,p.minDs,opts.pNms,...
opts.stride,opts.cascThr,cascCal,rescale] = getPrmDflt(varargin,dfs,1);
% finalize pPyramid and opts
p.complete=0; p.pChns.complete=0; p=chnsPyramid([],p); p=p.pPyramid;
p.complete=1; p.pChns.complete=1; shrink=p.pChns.shrink;
opts.stride=max(1,round(opts.stride/shrink))*shrink;
opts.pPyramid=p; detector.opts=opts;
% calibrate and rescale detector
detector.clf.hs = detector.clf.hs+cascCal;
if(rescale~=1), detector=detectorRescale(detector,rescale); end
end
function detector = detectorRescale( detector, rescale )
% Rescale detector by ratio rescale.
opts=detector.opts; shrink=opts.pPyramid.pChns.shrink;
bh=opts.modelDsPad(1)/shrink; bw=opts.modelDsPad(2)/shrink;
opts.stride=max(1,round(opts.stride*rescale/shrink))*shrink;
modelDsPad=round(opts.modelDsPad*rescale/shrink)*shrink;
rescale=modelDsPad./opts.modelDsPad; opts.modelDsPad=modelDsPad;
opts.modelDs=round(opts.modelDs.*rescale); detector.opts=opts;
bh1=opts.modelDsPad(1)/shrink; bw1=opts.modelDsPad(2)/shrink;
% move 0-indexed (x,y) location of each lookup feature
clf=detector.clf; fids=clf.fids; is=find(clf.child>0);
fids=double(fids(is)); n=length(fids); loc=zeros(n,3);
loc(:,3)=floor(fids/bh/bw); fids=fids-loc(:,3)*bh*bw;
loc(:,2)=floor(fids/bh); fids=fids-loc(:,2)*bh; loc(:,1)=fids;
loc(:,1)=min(bh1-1,round(loc(:,1)*rescale(1)));
loc(:,2)=min(bw1-1,round(loc(:,2)*rescale(2)));
fids = loc(:,3)*bh1*bw1 + loc(:,2)*bh1 + loc(:,1);
clf.fids(is)=int32(fids);
% rescale thrs for all features (fpdw trick)
nChns=[detector.info.nChns]; assert(max(loc(:,3))<sum(nChns));
k=[]; for i=1:length(nChns), k=[k ones(1,nChns(i))*i]; end %#ok<AGROW>
lambdas=opts.pPyramid.lambdas; lambdas=sqrt(prod(rescale)).^-lambdas(k);
clf.thrs(is)=clf.thrs(is).*lambdas(loc(:,3)+1)'; detector.clf=clf;
end
|
github
|
P-Chao/acfdetect-master
|
acfTrain.m
|
.m
|
acfdetect-master/toolbox/detector/acfTrain.m
| 16,517 |
UNKNOWN
|
a3e566f4a2f6911d7de22c43d54811ef
|
function detector = acfTrain( varargin )
% Train aggregate channel features object detector.
%
% Train aggregate channel features (ACF) object detector as described in:
% P. Doll�r, R. Appel, S. Belongie and P. Perona
% "Fast Feature Pyramids for Object Detection", PAMI 2014.
% The ACF detector is fast (30 fps on a single core) and achieves top
% accuracy on rigid object detection. Please see acfReadme.m for details.
%
% Takes a set of parameters opts (described in detail below) and trains a
% detector from start to finish including performing multiple rounds of
% bootstrapping if need be. The return is a struct 'detector' for use with
% acfDetect.m which fully defines a sliding window detector. Training is
% fast (on the INRIA pedestrian dataset training takes ~10 minutes on a
% single core or ~3m using four cores). Taking advantage of parallel
% training requires launching matlabpool (see help for matlabpool). The
% trained detector may be altered in certain ways via acfModify(). Calling
% opts=acfTrain() returns all default options.
%
% (1) Specifying features and model: The channel features are defined by
% 'pPyramid'. See chnsCompute.m and chnsPyramid.m for more details. The
% channels may be convolved by a set 'filters' to remove local correlations
% (see our NIPS14 paper on LDCF), improving accuracy but slowing detection.
% If 'filters'=[wFilter,nFilter] these are automatically computed. The
% model dimensions ('modelDs') define the window height and width. The
% padded dimensions ('modelDsPad') define the extended region around object
% candidates that are used for classification. For example, for 100 pixel
% tall pedestrians, typically a 128 pixel tall region is used to make a
% decision. 'pNms' controls non-maximal suppression (see bbNms.m), 'stride'
% controls the window stride, and 'cascThr' and 'cascCal' are the threshold
% and calibration used for the constant soft cascades. Typically, set
% 'cascThr' to -1 and adjust 'cascCal' until the desired recall is reached
% (setting 'cascCal' shifts the final scores output by the detector by the
% given amount). Training alternates between sampling (bootstrapping) and
% training an AdaBoost classifier (clf). 'nWeak' determines the number of
% training stages and number of trees after each stage, e.g. nWeak=[32 128
% 512 2048] defines four stages with the final clf having 2048 trees.
% 'pBoost' specifies parameters for AdaBoost, and 'pBoost.pTree' are the
% decision tree parameters, see adaBoostTrain.m for details. Finally,
% 'seed' is the random seed used and makes results reproducible and 'name'
% defines the location for storing the detector and log file.
%
% (2) Specifying training data location and amount: The training data can
% take on a number of different forms. The positives can be specified using
% either a dir of pre-cropped windows ('posWinDir') or dirs of full images
% ('posImgDir') and ground truth labels ('posGtDir'). The negatives can by
% specified using a dir of pre-cropped windows ('negWinDir'), a dir of full
% images without any positives and from which negatives can be sampled
% ('negImgDir'), and finally if neither 'negWinDir' or 'negImgDir' are
% given negatives are sampled from the images in 'posImgDir' (avoiding the
% positives). For the pre-cropped windows all images must have size at
% least modelDsPad and have the object (of size exactly modelDs) centered.
% 'imreadf' can be used to specify a custom function for loading an image,
% and 'imreadp' are custom additional parameters to imreadf. When sampling
% from full images, 'pLoad' determines how the ground truth is loaded and
% converted to a set of positive bbs (see bbGt>bbLoad). 'nPos' controls the
% total number of positives to sample for training (if nPos=inf the number
% of positives is limited by the training set). 'nNeg' controls the total
% number of negatives to sample and 'nPerNeg' limits the number of
% negatives to sample per image. 'nAccNeg' controls the maximum number of
% negatives that can accumulate over multiple stages of bootstrapping.
% Define 'pJitter' to jitter the positives (see jitterImage.m) and thus
% artificially increase the number of positive training windows. Finally if
% 'winsSave' is true cropped windows are saved to disk as a mat file.
%
% USAGE
% detector = acfTrain( opts )
% opts = acfTrain()
%
% INPUTS
% opts - parameters (struct or name/value pairs)
% (1) features and model:
% .pPyramid - [{}] params for creating pyramid (see chnsPyramid)
% .filters - [] [wxwxnChnsxnFilter] filters or [wFilter,nFilter]
% .modelDs - [] model height+width without padding (eg [100 41])
% .modelDsPad - [] model height+width with padding (eg [128 64])
% .pNms - [..] params for non-maximal suppression (see bbNms.m)
% .stride - [4] spatial stride between detection windows
% .cascThr - [-1] constant cascade threshold (affects speed/accuracy)
% .cascCal - [.005] cascade calibration (affects speed/accuracy)
% .nWeak - [128] vector defining number weak clfs per stage
% .pBoost - [..] parameters for boosting (see adaBoostTrain.m)
% .seed - [0] seed for random stream (for reproducibility)
% .name - [''] name to prepend to clf and log filenames
% (2) training data location and amount:
% .posGtDir - [''] dir containing ground truth
% .posImgDir - [''] dir containing full positive images
% .negImgDir - [''] dir containing full negative images
% .posWinDir - [''] dir containing cropped positive windows
% .negWinDir - [''] dir containing cropped negative windows
% .imreadf - [@imread] optional custom function for reading images
% .imreadp - [{}] optional custom parameters for imreadf
% .pLoad - [..] params for bbGt>bbLoad (see bbGt)
% .nPos - [inf] max number of pos windows to sample
% .nNeg - [5000] max number of neg windows to sample
% .nPerNeg - [25] max number of neg windows to sample per image
% .nAccNeg - [10000] max number of neg windows to accumulate
% .pJitter - [{}] params for jittering pos windows (see jitterImage)
% .winsSave - [0] if true save cropped windows at each stage to disk
%
% OUTPUTS
% detector - trained object detector (modify only via acfModify)
% .opts - input parameters used for model training
% .clf - learned boosted tree classifier (see adaBoostTrain)
% .info - info about channels (see chnsCompute.m)
%
% EXAMPLE
%
% See also acfReadme, acfDetect, acfDemoInria, acfModify, acfTest,
% chnsCompute, chnsPyramid, adaBoostTrain, bbGt, bbNms, jitterImage
%
% Piotr's Computer Vision Matlab Toolbox Version 3.40
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% initialize opts struct
opts = initializeOpts( varargin{:} );
if(nargin==0), detector=opts; return; end
% load or initialize detector and begin logging
nm=[opts.name 'Detector.mat']; t=exist(nm,'file');
if(t), if(nargout), t=load(nm); detector=t.detector; end; return; end
t=fileparts(nm); if(~isempty(t) && ~exist(t,'dir')), mkdir(t); end
detector = struct( 'opts',opts, 'clf',[], 'info',[] );
startTrain=clock; nm=[opts.name 'Log.txt'];
if(exist(nm,'file')), diary(nm); diary('off'); delete(nm); end; diary(nm);
RandStream.setGlobalStream(RandStream('mrg32k3a','Seed',opts.seed));
% iterate bootstraping and training
for stage = 0:numel(opts.nWeak)-1
diary('on'); fprintf([repmat('-',[1 75]) '\n']);
fprintf('Training stage %i\n',stage); startStage=clock;
% sample positives and compute info about channels
if( stage==0 )
[Is1,IsOrig1] = sampleWins( detector, stage, 1 );
t=ndims(Is1); if(t==3), t=Is1(:,:,1); else t=Is1(:,:,:,1); end
t=chnsCompute(t,opts.pPyramid.pChns); detector.info=t.info;
end
% compute local decorrelation filters
if( stage==0 && length(opts.filters)==2 )
fs = opts.filters; opts.filters = [];
X1 = chnsCompute1( IsOrig1, opts );
fs = chnsCorrelation( X1, fs(1), fs(2) );
opts.filters = fs; detector.opts.filters = fs;
end
% compute lambdas
if( stage==0 && isempty(opts.pPyramid.lambdas) )
fprintf('Computing lambdas... '); start=clock;
ds=size(IsOrig1); ds(1:end-1)=1; IsOrig1=mat2cell2(IsOrig1,ds);
ls=chnsScaling(opts.pPyramid.pChns,IsOrig1,0);
ls=round(ls*10^5)/10^5; detector.opts.pPyramid.lambdas=ls;
fprintf('done (time=%.0fs).\n',etime(clock,start));
end
% compute features for positives
if( stage==0 )
X1 = chnsCompute1( Is1, opts );
X1 = reshape(X1,[],size(X1,4))';
clear Is1 IsOrig1 ls fs ds t;
end
% sample negatives and compute features
Is0 = sampleWins( detector, stage, 0 );
X0 = chnsCompute1( Is0, opts ); clear Is0;
X0 = reshape(X0,[],size(X0,4))';
% accumulate negatives from previous stages
if( stage>0 )
n0=size(X0p,1); n1=max(opts.nNeg,opts.nAccNeg)-size(X0,1);
if(n0>n1 && n1>0), X0p=X0p(randSample(n0,n1),:); end
if(n0>0 && n1>0), X0=[X0p; X0]; end %#ok<AGROW>
end; X0p=X0;
% train boosted clf
detector.opts.pBoost.nWeak = opts.nWeak(stage+1);
detector.clf = adaBoostTrain(X0,X1,detector.opts.pBoost);
detector.clf.hs = detector.clf.hs + opts.cascCal;
% update log
fprintf('Done training stage %i (time=%.0fs).\n',...
stage,etime(clock,startStage)); diary('off');
end
% save detector
save([opts.name 'Detector.mat'],'detector');
% finalize logging
diary('on'); fprintf([repmat('-',[1 75]) '\n']);
fprintf('Done training (time=%.0fs).\n',...
etime(clock,startTrain)); diary('off');
end
function opts = initializeOpts( varargin )
% Initialize opts struct.
dfs= { 'pPyramid',{}, 'filters',[], ...
'modelDs',[100 41], 'modelDsPad',[128 64], ...
'pNms',struct(), 'stride',4, 'cascThr',-1, 'cascCal',.005, ...
'nWeak',128, 'pBoost', {}, 'seed',0, 'name','', 'posGtDir','', ...
'posImgDir','', 'negImgDir','', 'posWinDir','', 'negWinDir','', ...
'imreadf',@imread, 'imreadp',{}, 'pLoad',{}, 'nPos',inf, 'nNeg',5000, ...
'nPerNeg',25, 'nAccNeg',10000, 'pJitter',{}, 'winsSave',0 };
opts = getPrmDflt(varargin,dfs,1);
% fill in remaining parameters
p=chnsPyramid([],opts.pPyramid); p=p.pPyramid;
p.minDs=opts.modelDs; shrink=p.pChns.shrink;
opts.modelDsPad=ceil(opts.modelDsPad/shrink)*shrink;
p.pad=ceil((opts.modelDsPad-opts.modelDs)/shrink/2)*shrink;
p=chnsPyramid([],p); p=p.pPyramid; p.complete=1;
p.pChns.complete=1; opts.pPyramid=p;
% initialize pNms, pBoost, pBoost.pTree, and pLoad
dfs={ 'type','maxg', 'overlap',.65, 'ovrDnm','min' };
opts.pNms=getPrmDflt(opts.pNms,dfs,-1);
dfs={ 'pTree',{}, 'nWeak',0, 'discrete',1, 'verbose',16 };
opts.pBoost=getPrmDflt(opts.pBoost,dfs,1);
dfs={'nBins',256,'maxDepth',2,'minWeight',.01,'fracFtrs',1,'nThreads',16};
opts.pBoost.pTree=getPrmDflt(opts.pBoost.pTree,dfs,1);
opts.pLoad=getPrmDflt(opts.pLoad,{'squarify',{0,1}},-1);
opts.pLoad.squarify{2}=opts.modelDs(2)/opts.modelDs(1);
end
function [Is,IsOrig] = sampleWins( detector, stage, positive )
% Load or sample windows for training detector.
opts=detector.opts; start=clock;
if( positive ), n=opts.nPos; else n=opts.nNeg; end
if( positive ), crDir=opts.posWinDir; else crDir=opts.negWinDir; end
if( exist(crDir,'dir') && stage==0 )
% if window directory is specified simply load windows
fs=bbGt('getFiles',{crDir}); nImg=length(fs); assert(nImg>0);
if(nImg>n), fs=fs(:,randSample(nImg,n)); end; n=nImg;
for i=1:n, fs{i}=[{opts.imreadf},fs(i),opts.imreadp]; end
Is=cell(1,n); parfor i=1:n, Is{i}=feval(fs{i}{:}); end
else
% sample windows from full images using sampleWins1()
hasGt=positive||isempty(opts.negImgDir); fs={opts.negImgDir};
if(hasGt), fs={opts.posImgDir,opts.posGtDir}; end
fs=bbGt('getFiles',fs); nImg=size(fs,2); assert(nImg>0);
if(~isinf(n)), fs=fs(:,randperm(nImg)); end; Is=cell(nImg*1000,1);
diary('off'); tid=ticStatus('Sampling windows',1,30); k=0; i=0; batch=64;
while( i<nImg && k<n )
batch=min(batch,nImg-i); Is1=cell(1,batch);
%parfor
parfor j=1:batch, ij=i+j;
I = feval(opts.imreadf,fs{1,ij},opts.imreadp{:}); %#ok<PFBNS>
gt=[]; if(hasGt), [~,gt]=bbGt('bbLoad',fs{2,ij},opts.pLoad); end
disp(fs{1,ij});
Is1{j} = sampleWins1( I, gt, detector, stage, positive );
end
Is1=[Is1{:}]; k1=length(Is1); Is(k+1:k+k1)=Is1; k=k+k1;
if(k>n), Is=Is(randSample(k,n)); k=n; end
i=i+batch; tocStatus(tid,max(i/nImg,k/n));
end
Is=Is(1:k); diary('on');
fprintf('Sampled %i windows from %i images.\n',k,i);
end
% optionally jitter positive windows
if(length(Is)<2), Is={}; return; end
nd=ndims(Is{1})+1; Is=cat(nd,Is{:}); IsOrig=Is;
if( positive && isstruct(opts.pJitter) )
opts.pJitter.hasChn=(nd==4); Is=jitterImage(Is,opts.pJitter);
ds=size(Is); ds(nd)=ds(nd)*ds(nd+1); Is=reshape(Is,ds(1:nd));
end
% make sure dims are divisible by shrink and not smaller than modelDsPad
ds=size(Is); cr=rem(ds(1:2),opts.pPyramid.pChns.shrink); s=floor(cr/2)+1;
e=ceil(cr/2); Is=Is(s(1):end-e(1),s(2):end-e(2),:,:); ds=size(Is);
if(any(ds(1:2)<opts.modelDsPad)), error('Windows too small.'); end
% optionally save windows to disk and update log
nm=[opts.name 'Is' int2str(positive) 'Stage' int2str(stage)];
if( opts.winsSave ), save(nm,'Is','-v7.3'); end
fprintf('Done sampling windows (time=%.0fs).\n',etime(clock,start));
diary('off'); diary('on');
end
function Is = sampleWins1( I, gt, detector, stage, positive )
% Sample windows from I given its ground truth gt.
opts=detector.opts; shrink=opts.pPyramid.pChns.shrink;
modelDs=opts.modelDs; modelDsPad=opts.modelDsPad;
if( positive ), bbs=gt; bbs=bbs(bbs(:,5)==0,:); else
if( stage==0 )
% generate candidate bounding boxes in a grid
[h,w,~]=size(I); h1=modelDs(1); w1=modelDs(2);
n=opts.nPerNeg; ny=sqrt(n*h/w); nx=n/ny; ny=ceil(ny); nx=ceil(nx);
[xs,ys]=meshgrid(linspace(1,w-w1,nx),linspace(1,h-h1,ny));
bbs=[xs(:) ys(:)]; bbs(:,3)=w1; bbs(:,4)=h1; bbs=bbs(1:n,:);
else
% run detector to generate candidate bounding boxes
[~,bbs]=acfDetect(I,detector); [~,ord]=sort(bbs(:,5),'descend');
bbs=bbs(ord(1:min(end,opts.nPerNeg)),1:4);
end
if( ~isempty(gt) )
% discard any candidate negative bb that matches the gt
n=size(bbs,1); keep=false(1,n);
for i=1:n, keep(i)=all(bbGt('compOas',bbs(i,:),gt,gt(:,5))<.1); end
bbs=bbs(keep,:);
end
end
% grow bbs to a large padded size and finally crop windows
modelDsBig=max(8*shrink,modelDsPad)+max(2,ceil(64/shrink))*shrink;
%disp(bbs);
r=modelDs(2)/modelDs(1); assert(all(abs(bbs(:,3)./bbs(:,4)-r)<1e-5));
r=modelDsBig./modelDs; bbs=bbApply('resize',bbs,r(1),r(2));
Is=bbApply('crop',I,bbs,'replicate',modelDsBig([2 1]));
end
function chns = chnsCompute1( Is, opts )
% Compute single scale channels of dimensions modelDsPad.
if(isempty(Is)), chns=[]; return; end
fprintf('Extracting features... '); start=clock; fs=opts.filters;
pChns=opts.pPyramid.pChns; smooth=opts.pPyramid.smooth;
dsTar=opts.modelDsPad/pChns.shrink; ds=size(Is); ds(1:end-1)=1;
Is=squeeze(mat2cell2(Is,ds)); n=length(Is); chns=cell(1,n);
parfor i=1:n
C=chnsCompute(Is{i},pChns); C=convTri(cat(3,C.data{:}),smooth);
if(~isempty(fs)), C=repmat(C,[1 1 size(fs,4)]);
for j=1:size(C,3), C(:,:,j)=conv2(C(:,:,j),fs(:,:,j),'same'); end; end
if(~isempty(fs)), C=imResample(C,.5); shr=2; else shr=1; end
ds=size(C); cr=ds(1:2)-dsTar/shr; s=floor(cr/2)+1; e=ceil(cr/2);
C=C(s(1):end-e(1),s(2):end-e(2),:); chns{i}=C;
end; chns=cat(4,chns{:});
fprintf('done (time=%.0fs).\n',etime(clock,start));
end
function filters = chnsCorrelation( chns, wFilter, nFilter )
% Compute filters capturing local correlations for each channel.
fprintf('Computing correlations... '); start=clock;
[~,~,m,n]=size(chns); w=wFilter; wp=w*2-1;
filters=zeros(w,w,m,nFilter,'single');
for i=1:m
% compute local auto-scorrelation using Wiener-Khinchin theorem
mus=squeeze(mean(mean(chns(:,:,i,:)))); sig=cell(1,n);
parfor j=1:n
T=fftshift(ifft2(abs(fft2(chns(:,:,i,j)-mean(mus))).^2));
sig{j}=T(floor(end/2)+1-w+(1:wp),floor(end/2)+1-w+(1:wp));
end
sig=double(mean(cat(4,sig{mus>1/50}),4));
sig=reshape(full(convmtx2(sig,w,w)),wp+w-1,wp+w-1,[]);
sig=reshape(sig(w:wp,w:wp,:),w^2,w^2); sig=(sig+sig')/2;
% compute filters for each channel from sig (sorted by eigenvalue)
[fs,D]=eig(sig); fs=reshape(fs,w,w,[]);
[~,ord]=sort(diag(D),'descend');
fs=flipdim(flipdim(fs,1),2); %#ok<DFLIPDIM>
filters(:,:,i,:)=fs(:,:,ord(1:nFilter));
end
fprintf('done (time=%.0fs).\n',etime(clock,start));
end
|
github
|
P-Chao/acfdetect-master
|
acfDetect.m
|
.m
|
acfdetect-master/toolbox/detector/acfDetect.m
| 3,704 |
utf_8
|
fc0b5fb5b9172ffeec4acf6785bac9ca
|
function [data, bbs] = acfDetect( I, detector, fileName )
% Run aggregate channel features object detector on given image(s).
%
% The input 'I' can either be a single image (or filename) or a cell array
% of images (or filenames). In the first case, the return is a set of bbs
% where each row has the format [x y w h score] and score is the confidence
% of detection. If the input is a cell array, the output is a cell array
% where each element is a set of bbs in the form above (in this case a
% parfor loop is used to speed execution). If 'fileName' is specified, the
% bbs are saved to a comma separated text file and the output is set to
% bbs=1. If saving detections for multiple images the output is stored in
% the format [imgId x y w h score] and imgId is a one-indexed image id.
%
% A cell of detectors trained with the same channels can be specified,
% detected bbs from each detector are concatenated. If using multiple
% detectors and opts.pNms.separate=1 then each bb has a sixth element
% bbType=j, where j is the j-th detector, see bbNms.m for details.
%
% USAGE
% bbs = acfDetect( I, detector, [fileName] )
%
% INPUTS
% I - input image(s) of filename(s) of input image(s)
% detector - detector(s) trained via acfTrain
% fileName - [] target filename (if specified return is 1)
%
% OUTPUTS
% bbs - [nx5] array of bounding boxes or cell array of bbs
%
% EXAMPLE
%
% See also acfTrain, acfModify, bbGt>loadAll, bbNms
%
% Piotr's Computer Vision Matlab Toolbox Version 3.40
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% run detector on every image
data=[];
if(nargin<3), fileName=''; end; multiple=iscell(I);
if(~isempty(fileName) && exist(fileName,'file')), bbs=1; return; end
if(~multiple), [data bbs]=acfDetectImg(I,detector); else
n=length(I); bbs=cell(n,1);
parfor i=1:n, bbs{i}=acfDetectImg(I{i},detector); end
end
% write results to disk if fileName specified
if(isempty(fileName)), return; end
d=fileparts(fileName); if(~isempty(d)&&~exist(d,'dir')), mkdir(d); end
if( multiple ) % add image index to each bb and flatten result
for i=1:n, bbs{i}=[ones(size(bbs{i},1),1)*i bbs{i}]; end
bbs=cell2mat(bbs);
end
dlmwrite(fileName,bbs); bbs=1;
end
function [data, bbs] = acfDetectImg( I, detector )
% Run trained sliding-window object detector on given image.
Ds=detector; if(~iscell(Ds)), Ds={Ds}; end; nDs=length(Ds);
opts=Ds{1}.opts; pPyramid=opts.pPyramid; pNms=opts.pNms;
imreadf=opts.imreadf; imreadp=opts.imreadp;
shrink=pPyramid.pChns.shrink; pad=pPyramid.pad;
separate=nDs>1 && isfield(pNms,'separate') && pNms.separate;
% read image and compute features (including optionally applying filters)
if(all(ischar(I))), I=feval(imreadf,I,imreadp{:}); end
P=chnsPyramid(I,pPyramid); bbs=cell(P.nScales,nDs);
if(isfield(opts,'filters') && ~isempty(opts.filters)), shrink=shrink*2;
for i=1:P.nScales, fs=opts.filters; C=repmat(P.data{i},[1 1 size(fs,4)]);
for j=1:size(C,3), C(:,:,j)=conv2(C(:,:,j),fs(:,:,j),'same'); end
P.data{i}=imResample(C,.5);
end
end
data=P.data;
% apply sliding window classifiers
for i=1:P.nScales
for j=1:nDs, opts=Ds{j}.opts;
modelDsPad=opts.modelDsPad; modelDs=opts.modelDs;
bb = acfDetect1(P.data{i},Ds{j}.clf,shrink,...
modelDsPad(1),modelDsPad(2),opts.stride,opts.cascThr);
shift=(modelDsPad-modelDs)/2-pad;
bb(:,1)=(bb(:,1)+shift(2))/P.scaleshw(i,2);
bb(:,2)=(bb(:,2)+shift(1))/P.scaleshw(i,1);
bb(:,3)=modelDs(2)/P.scales(i);
bb(:,4)=modelDs(1)/P.scales(i);
if(separate), bb(:,6)=j; end; bbs{i,j}=bb;
end
end; bbs=cat(1,bbs{:});
if(~isempty(pNms)), bbs=bbNms(bbs,pNms); end
end
|
github
|
P-Chao/acfdetect-master
|
bbGt.m
|
.m
|
acfdetect-master/toolbox/detector/bbGt.m
| 34,249 |
utf_8
|
402dd4f5c62f7879a4da8690cb14e77d
|
function varargout = bbGt( action, varargin )
% Bounding box (bb) annotations struct, evaluation and sampling routines.
%
% bbGt gives access to two types of routines:
% (1) Data structure for storing bb image annotations.
% (2) Routines for evaluating the Pascal criteria for object detection.
%
% The bb annotation stores bb for objects of interest with additional
% information per object, such as occlusion information. The underlying
% data structure is simply a Matlab stuct array, one struct per object.
% This annotation format is an alternative to the annotation format used
% for the PASCAL object challenges (in addition routines for loading PASCAL
% format data are provided, see bbLoad()).
%
% Each object struct has the following fields:
% lbl - a string label describing object type (eg: 'pedestrian')
% bb - [l t w h]: bb indicating predicted object extent
% occ - 0/1 value indicating if bb is occluded
% bbv - [l t w h]: bb indicating visible region (may be [0 0 0 0])
% ign - 0/1 value indicating bb was marked as ignore
% ang - [0-360] orientation of bb in degrees
%
% Note: although orientation (angle) is stored for each bb, for now it is
% not being used during evaluation or sampling.
%
% bbGt contains a number of utility functions, accessed using:
% outputs = bbGt( 'action', inputs );
% The list of functions and help for each is given below. Also, help on
% individual subfunctions can be accessed by: "help bbGt>action".
%
%%% (1) Data structure for storing bb image annotations.
% Create annotation of n empty objects.
% objs = bbGt( 'create', [n] );
% Save bb annotation to text file.
% objs = bbGt( 'bbSave', objs, fName )
% Load bb annotation from text file and filter.
% [objs,bbs] = bbGt( 'bbLoad', fName, [pLoad] )
% Get object property 'name' (in a standard array).
% vals = bbGt( 'get', objs, name )
% Set object property 'name' (with a standard array).
% objs = bbGt( 'set', objs, name, vals )
% Draw an ellipse for each labeled object.
% hs = draw( objs, pDraw )
%
%%% (2) Routines for evaluating the Pascal criteria for object detection.
% Get all corresponding files in given directories.
% [fs,fs0] = bbGt('getFiles', dirs, [f0], [f1] )
% Copy corresponding files into given directories.
% fs = bbGt( 'copyFiles', fs, dirs )
% Load all ground truth and detection bbs in given directories.
% [gt0,dt0] = bbGt( 'loadAll', gtDir, [dtDir], [pLoad] )
% Evaluates detections against ground truth data.
% [gt,dt] = bbGt( 'evalRes', gt0, dt0, [thr], [mul] )
% Display evaluation results for given image.
% [hs,hImg] = bbGt( 'showRes' I, gt, dt, varargin )
% Compute ROC or PR based on outputs of evalRes on multiple images.
% [xs,ys,ref] = bbGt( 'compRoc', gt, dt, roc, ref )
% Extract true or false positives or negatives for visualization.
% [Is,scores,imgIds] = bbGt( 'cropRes', gt, dt, imFs, varargin )
% Computes (modified) overlap area between pairs of bbs.
% oa = bbGt( 'compOas', dt, gt, [ig] )
% Optimized version of compOas for a single pair of bbs.
% oa = bbGt( 'compOa', dt, gt, ig )
%
% USAGE
% varargout = bbGt( action, varargin );
%
% INPUTS
% action - string specifying action
% varargin - depends on action, see above
%
% OUTPUTS
% varargout - depends on action, see above
%
% EXAMPLE
%
% See also bbApply, bbLabeler, bbGt>create, bbGt>bbSave, bbGt>bbLoad,
% bbGt>get, bbGt>set, bbGt>draw, bbGt>getFiles, bbGt>copyFiles,
% bbGt>loadAll, bbGt>evalRes, bbGt>showRes, bbGt>compRoc, bbGt>cropRes,
% bbGt>compOas, bbGt>compOa
%
% Piotr's Computer Vision Matlab Toolbox Version 3.26
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%#ok<*DEFNU>
varargout = cell(1,max(1,nargout));
[varargout{:}] = feval(action,varargin{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function objs = create( n )
% Create annotation of n empty objects.
%
% USAGE
% objs = bbGt( 'create', [n] )
%
% INPUTS
% n - [1] number of objects to create
%
% OUTPUTS
% objs - annotation of n 'empty' objects
%
% EXAMPLE
% objs = bbGt('create')
%
% See also bbGt
o=struct('lbl','','bb',[0 0 0 0],'occ',0,'bbv',[0 0 0 0],'ign',0,'ang',0);
if(nargin<1 || n==1), objs=o; return; end; objs=o(ones(n,1));
end
function objs = bbSave( objs, fName )
% Save bb annotation to text file.
%
% USAGE
% objs = bbGt( 'bbSave', objs, fName )
%
% INPUTS
% objs - objects to save
% fName - name of text file
%
% OUTPUTS
% objs - objects to save
%
% EXAMPLE
%
% See also bbGt, bbGt>bbLoad
vers=3; fid=fopen(fName,'w'); assert(fid>0);
fprintf(fid,'%% bbGt version=%i\n',vers);
objs=set(objs,'bb',round(get(objs,'bb')));
objs=set(objs,'bbv',round(get(objs,'bbv')));
objs=set(objs,'ang',round(get(objs,'ang')));
for i=1:length(objs)
o=objs(i); bb=o.bb; bbv=o.bbv;
fprintf(fid,['%s' repmat(' %i',1,11) '\n'],o.lbl,...
bb,o.occ,bbv,o.ign,o.ang);
end
fclose(fid);
end
function [objs,bbs] = bbLoad( fName, varargin )
% Load bb annotation from text file and filter.
%
% FORMAT: Specify 'format' to indicate the format of the ground truth.
% format=0 is the default format (created by bbSave/bbLabeler). format=1 is
% the PASCAL VOC format. Loading ground truth in this format requires
% 'VOCcode/' to be in directory path. It's part of VOCdevkit available from
% the PASCAL VOC: http://pascallin.ecs.soton.ac.uk/challenges/VOC/. Objects
% labeled as either 'truncated' or 'occluded' using the PASCAL definitions
% have the 'occ' flag set to true. Objects labeled as 'difficult' have the
% 'ign' flag set to true. 'class' is used for 'lbl'. format=2 is the
% ImageNet detection format and requires the ImageNet Dev Kit.
%
% FILTERING: After loading, the objects can be filtered. First, only
% objects with lbl in lbls or ilbls or returned. For each object, obj.ign
% is set to 1 if it was already at 1, if its label was in ilbls, or if any
% object property is outside of the specified range. The ignore flag is
% used during training and testing so that objects with certain properties
% (such as very small or heavily occluded objects) are excluded. The range
% for each property is a two element vector, [0 inf] by default; a property
% value v is inside the range if v>=rng(1) && v<=rng(2). Tested properties
% include height (h), width (w), area (a), aspect ratio (ar), orientation
% (o), extent x-coordinate (x), extent y-coordinate (y), and fraction
% visible (v). The last property is computed as the visible object area
% divided by the total area, except if o.occ==0, in which case v=1, or
% all(o.bbv==o.bb), which indicates the object may be barely visible, in
% which case v=0 (note that v~=1 in this case).
%
% RETURN: In addition to outputting the objs, bbLoad() can return the
% corresponding bounding boxes (bbs) in an [nx5] array where each row is of
% the form [x y w h ignore], [x y w h] is the bb and ignore=obj.ign. For
% oriented bbs, the extent of the bb is returned, where the extent is the
% smallest axis aligned bb containing the oriented bb. If the oriented bb
% was labeled as a rectangle as opposed to an ellipse, the tightest bb will
% usually increase slightly in size due to the corners of the rectangle
% sticking out beyond the ellipse bounds. The 'ellipse' flag controls how
% an oriented bb is converted to a regular bb. Specifically, set ellipse=1
% if an ellipse tightly delineates the object and 0 if a rectangle does.
% Finally, if 'squarify' is not empty the (non-ignore) bbs are converted to
% a fixed aspect ratio using bbs=bbApply('squarify',bbs,squarify{:}).
%
% USAGE
% [objs,bbs] = bbGt( 'bbLoad', fName, [pLoad] )
%
% INPUTS
% fName - name of text file
% pLoad - parameters (struct or name/value pairs)
% .format - [0] gt format 0:default, 1:PASCAL, 2:ImageNet
% .ellipse - [1] controls how oriented bb is converted to regular bb
% .squarify - [] controls optional reshaping of bbs to fixed aspect ratio
% .lbls - [] return objs with these labels (or [] to return all)
% .ilbls - [] return objs with these labels but set to ignore
% .hRng - [] range of acceptable obj heights
% .wRng - [] range of acceptable obj widths
% .aRng - [] range of acceptable obj areas
% .arRng - [] range of acceptable obj aspect ratios
% .oRng - [] range of acceptable obj orientations (angles)
% .xRng - [] range of x coordinates of bb extent
% .yRng - [] range of y coordinates of bb extent
% .vRng - [] range of acceptable obj occlusion levels
%
% OUTPUTS
% objs - loaded objects
% bbs - [nx5] array containg ground truth bbs [x y w h ignore]
%
% EXAMPLE
%
% See also bbGt, bbGt>bbSave
% get parameters
df={'format',0,'ellipse',1,'squarify',[],'lbls',[],'ilbls',[],'hRng',[],...
'wRng',[],'aRng',[],'arRng',[],'oRng',[],'xRng',[],'yRng',[],'vRng',[]};
[format,ellipse,sqr,lbls,ilbls,hRng,wRng,aRng,arRng,oRng,xRng,yRng,vRng]...
= getPrmDflt(varargin,df,1);
% load objs
if( format==0 )
% load objs stored in default format
fId=fopen(fName);
if(fId==-1), error(['unable to open file: ' fName]); end; v=0;
try v=textscan(fId,'%% bbGt version=%d'); v=v{1}; catch, end %#ok<CTCH>
if(isempty(v)), v=0; end
% read in annotation (m is number of fields for given version v)
if(all(v~=[0 1 2 3])), error('Unknown version %i.',v); end
frmt='%s %d %d %d %d %d %d %d %d %d %d %d';
ms=[10 10 11 12]; m=ms(v+1); frmt=frmt(1:2+(m-1)*3);
in=textscan(fId,frmt); for i=2:m, in{i}=double(in{i}); end; fclose(fId);
% create objs struct from read in fields
n=length(in{1}); objs=create(n);
for i=1:n, objs(i).lbl=in{1}{i}; objs(i).occ=in{6}(i); end
bb=[in{2} in{3} in{4} in{5}]; bbv=[in{7} in{8} in{9} in{10}];
for i=1:n, objs(i).bb=bb(i,:); objs(i).bbv=bbv(i,:); end
if(m>=11), for i=1:n, objs(i).ign=in{11}(i); end; end
if(m>=12), for i=1:n, objs(i).ang=in{12}(i); end; end
elseif( format==1 )
% load objs stored in PASCAL VOC format
if(exist('PASreadrecord.m','file')~=2)
error('bbLoad() requires the PASCAL VOC code.'); end
os=PASreadrecord(fName); os=os.objects;
n=length(os); objs=create(n);
if(~isfield(os,'occluded')), for i=1:n, os(i).occluded=0; end; end
for i=1:n
bb=os(i).bbox; bb(3)=bb(3)-bb(1); bb(4)=bb(4)-bb(2); objs(i).bb=bb;
objs(i).lbl=os(i).class; objs(i).ign=os(i).difficult;
objs(i).occ=os(i).occluded || os(i).truncated;
if(objs(i).occ), objs(i).bbv=bb; end
end
elseif( format==2 )
if(exist('VOCreadxml.m','file')~=2)
error('bbLoad() requires the ImageNet dev code.'); end
os=VOCreadxml(fName); os=os.annotation;
if(isfield(os,'object')), os=os.object; else os=[]; end
n=length(os); objs=create(n);
for i=1:n
bb=os(i).bndbox; bb=str2double({bb.xmin bb.ymin bb.xmax bb.ymax});
bb(3)=bb(3)-bb(1); bb(4)=bb(4)-bb(2); objs(i).bb=bb;
objs(i).lbl=os(i).name;
end
else error('bbLoad() unknown format: %i',format);
end
% only keep objects whose lbl is in lbls or ilbls
if(~isempty(lbls) || ~isempty(ilbls)), K=true(n,1);
for i=1:n, K(i)=any(strcmp(objs(i).lbl,[lbls ilbls])); end
objs=objs(K); n=length(objs);
end
% filter objs (set ignore flags)
for i=1:n, objs(i).ang=mod(objs(i).ang,360); end
if(~isempty(ilbls)), for i=1:n, v=objs(i).lbl;
objs(i).ign = objs(i).ign || any(strcmp(v,ilbls)); end; end
if(~isempty(xRng)), for i=1:n, v=objs(i).bb(1);
objs(i).ign = objs(i).ign || v<xRng(1) || v>xRng(2); end; end
if(~isempty(xRng)), for i=1:n, v=objs(i).bb(1)+objs(i).bb(3);
objs(i).ign = objs(i).ign || v<xRng(1) || v>xRng(2); end; end
if(~isempty(yRng)), for i=1:n, v=objs(i).bb(2);
objs(i).ign = objs(i).ign || v<yRng(1) || v>yRng(2); end; end
if(~isempty(yRng)), for i=1:n, v=objs(i).bb(2)+objs(i).bb(4);
objs(i).ign = objs(i).ign || v<yRng(1) || v>yRng(2); end; end
if(~isempty(wRng)), for i=1:n, v=objs(i).bb(3);
objs(i).ign = objs(i).ign || v<wRng(1) || v>wRng(2); end; end
if(~isempty(hRng)), for i=1:n, v=objs(i).bb(4);
objs(i).ign = objs(i).ign || v<hRng(1) || v>hRng(2); end; end
if(~isempty(oRng)), for i=1:n, v=objs(i).ang; if(v>180), v=v-360; end
objs(i).ign = objs(i).ign || v<oRng(1) || v>oRng(2); end; end
if(~isempty(aRng)), for i=1:n, v=objs(i).bb(3)*objs(i).bb(4);
objs(i).ign = objs(i).ign || v<aRng(1) || v>aRng(2); end; end
if(~isempty(arRng)), for i=1:n, v=objs(i).bb(3)/objs(i).bb(4);
objs(i).ign = objs(i).ign || v<arRng(1) || v>arRng(2); end; end
if(~isempty(vRng)), for i=1:n, o=objs(i); bb=o.bb; bbv=o.bbv; %#ok<ALIGN>
if(~o.occ || all(bbv==0)), v=1; elseif(all(bbv==bb)), v=0; else
v=(bbv(3)*bbv(4))/(bb(3)*bb(4)); end
objs(i).ign = objs(i).ign || v<vRng(1) || v>vRng(2); end
end
% finally get extent of each bounding box (not trivial if ang~=0)
if(nargout<=1), return; end; if(n==0), bbs=zeros(0,5); return; end
bbs=double([reshape([objs.bb],4,[]); [objs.ign]]'); ign=bbs(:,5)==1;
for i=1:n, bbs(i,1:4)=bbExtent(bbs(i,1:4),objs(i).ang,ellipse); end
if(~isempty(sqr)), bbs(~ign,:)=bbApply('squarify',bbs(~ign,:),sqr{:}); end
function bb = bbExtent( bb, ang, ellipse )
% get bb that fully contains given oriented bb
if(~ang), return; end
if( ellipse ) % get bb that encompases ellipse (tighter)
x=bbApply('getCenter',bb); a=bb(4)/2; b=bb(3)/2; ang=ang-90;
rx=(a*cosd(ang))^2+(b*sind(ang))^2; rx=abs(rx/sqrt(rx));
ry=(a*sind(ang))^2+(b*cosd(ang))^2; ry=abs(ry/sqrt(ry));
bb=[x(1)-rx x(2)-ry 2*rx 2*ry];
else % get bb that encompases rectangle (looser)
c=cosd(ang); s=sind(ang); R=[c -s; s c]; rs=bb(3:4)/2;
x0=-rs(1); x1=rs(1); y0=-rs(2); y1=rs(2); pc=bb(1:2)+rs;
p=[x0 y0; x1 y0; x1 y1; x0 y1]*R'+pc(ones(4,1),:);
x0=min(p(:,1)); x1=max(p(:,1)); y0=min(p(:,2)); y1=max(p(:,2));
bb=[x0 y0 x1-x0 y1-y0];
end
end
end
function vals = get( objs, name )
% Get object property 'name' (in a standard array).
%
% USAGE
% vals = bbGt( 'get', objs, name )
%
% INPUTS
% objs - [nx1] struct array of objects
% name - property name ('lbl','bb','occ',etc.)
%
% OUTPUTS
% vals - [nxk] array of n values (k=1 or 4)
%
% EXAMPLE
%
% See also bbGt, bbGt>set
nObj=length(objs); if(nObj==0), vals=[]; return; end
switch name
case 'lbl', vals={objs.lbl}';
case 'bb', vals=reshape([objs.bb]',4,[])';
case 'occ', vals=[objs.occ]';
case 'bbv', vals=reshape([objs.bbv]',4,[])';
case 'ign', vals=[objs.ign]';
case 'ang', vals=[objs.ang]';
otherwise, error('unkown type %s',name);
end
end
function objs = set( objs, name, vals )
% Set object property 'name' (with a standard array).
%
% USAGE
% objs = bbGt( 'set', objs, name, vals )
%
% INPUTS
% objs - [nx1] struct array of objects
% name - property name ('lbl','bb','occ',etc.)
% vals - [nxk] array of n values (k=1 or 4)
%
% OUTPUTS
% objs - [nx1] struct array of updated objects
%
% EXAMPLE
%
% See also bbGt, bbGt>get
nObj=length(objs);
switch name
case 'lbl', for i=1:nObj, objs(i).lbl=vals{i}; end
case 'bb', for i=1:nObj, objs(i).bb=vals(i,:); end
case 'occ', for i=1:nObj, objs(i).occ=vals(i); end
case 'bbv', for i=1:nObj, objs(i).bbv=vals(i,:); end
case 'ign', for i=1:nObj, objs(i).ign=vals(i); end
case 'ang', for i=1:nObj, objs(i).ang=vals(i); end
otherwise, error('unkown type %s',name);
end
end
function hs = draw( objs, varargin )
% Draw an ellipse for each labeled object.
%
% USAGE
% hs = bbGt( 'draw', objs, pDraw )
%
% INPUTS
% objs - [nx1] struct array of objects
% pDraw - parameters (struct or name/value pairs)
% .col - ['g'] color or [nx1] array of colors
% .lw - [2] line width
% .ls - ['-'] line style
%
% OUTPUTS
% hs - [nx1] handles to drawn graphic objects
%
% EXAMPLE
%
% See also bbGt
dfs={'col',[],'lw',2,'ls','-'};
[col,lw,ls]=getPrmDflt(varargin,dfs,1);
n=length(objs); hold on; hs=zeros(n,4);
if(isempty(col)), if(n==1), col='g'; else col=hsv(n); end; end
tProp={'FontSize',10,'color','w','FontWeight','bold',...
'VerticalAlignment','bottom'};
for i=1:n
bb=objs(i).bb; ci=col(i,:);
hs(i,1)=text(bb(1),bb(2),objs(i).lbl,tProp{:});
x=bbApply('getCenter',bb); r=bb(3:4)/2; a=objs(i).ang/180*pi-pi/2;
[hs(i,2),hs(i,3),hs(i,4)]=plotEllipse(x(2),x(1),r(2),r(1),a,ci,[],lw,ls);
end; hold off;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [fs,fs0] = getFiles( dirs, f0, f1 )
% Get all corresponding files in given directories.
%
% The first dir in 'dirs' serves as the baseline dir. getFiles() returns
% all files in the baseline dir and all corresponding files in the
% remaining dirs to the files in the baseline dir, in the same order. Two
% files are in correspondence if they have the same base name (regardless
% of extension). For example, given a file named "name.jpg", a
% corresponding file may be named "name.txt" or "name.jpg.txt". Every file
% in the baseline dir must have a matching file in the remaining dirs.
%
% USAGE
% [fs,fs0] = bbGt('getFiles', dirs, [f0], [f1] )
%
% INPUTS
% dirs - {1xm} list of m directories
% f0 - [1] index of first file in baseline dir to use
% f1 - [inf] index of last file in baseline dir to use
%
% OUTPUTS
% fs - {mxn} list of full file names in each dir
% fs0 - {1xn} list of file names without path or extensions
%
% EXAMPLE
%
% See also bbGt
if(nargin<2 || isempty(f0)), f0=1; end
if(nargin<3 || isempty(f1)), f1=inf; end
m=length(dirs); assert(m>0); sep=filesep;
for d=1:m, dir1=dirs{d}; dir1(dir1=='\')=sep; dir1(dir1=='/')=sep;
if(dir1(end)==sep), dir1(end)=[]; end; dirs{d}=dir1; end
[fs0,fs1] = getFiles0(dirs{1},f0,f1,sep);
n1=length(fs0); fs=cell(m,n1); fs(1,:)=fs1;
for d=2:m, fs(d,:)=getFiles1(dirs{d},fs0,sep); end
function [fs0,fs1] = getFiles0( dir1, f0, f1, sep )
% get fs1 in dir1 (and fs0 without path or extension)
fs1=dir([dir1 sep '*']); fs1={fs1.name};
i3=1;
while(i3<=length(fs1))
name=fs1{i3};
if(strcmp(name,'.')==1 || strcmp(name,'..')==1)
fs1(i3)=[];
i3=i3-1;
end
i3=i3+1;
end
%fs1=fs1(3:end);
fs1=fs1(f0:min(f1,end)); fs0=fs1; n=length(fs0);
if(n==0), error('No files found in baseline dir %s.',dir1); end
for i=1:n, fs1{i}=[dir1 sep fs0{i}]; end
n=length(fs0); for i=1:n, f=fs0{i};
f(find(f=='.',1,'first'):end)=[]; fs0{i}=f; end
end
function fs1 = getFiles1( dir1, fs0, sep )
% get fs1 in dir1 corresponding to fs0
n=length(fs0); fs1=cell(1,n); i2=0; i1=0;
fs2=dir(dir1); fs2={fs2.name}; n2=length(fs2);
eMsg='''%s'' has no corresponding file in %s.';
for i0=1:n, r=length(fs0{i0}); match=0;
while(i2<n2), i2=i2+1; if(strcmpi(fs0{i0},fs2{i2}(1:min(end,r))))
i1=i1+1; fs1{i1}=fs2{i2}; match=1; break; end; end
if(~match), error(eMsg,fs0{i0},dir1); end
end
for i1=1:n, fs1{i1}=[dir1 sep fs1{i1}]; end
end
end
function fs = copyFiles( fs, dirs )
% Copy corresponding files into given directories.
%
% Useful for splitting data into training, validation and testing sets.
% See also bbGt>getFiles for obtaining a set of corresponding files.
%
% USAGE
% fs = bbGt( 'copyFiles', fs, dirs )
%
% INPUTS
% fs - {mxn} list of full file names in each dir
% dirs - {1xm} list of m target directories
%
% OUTPUTS
% fs - {mxn} list of full file names of copied files
%
% EXAMPLE
%
% See also bbGt, bbGt>getFiles
[m,n]=size(fs); assert(numel(dirs)==m); if(n==0), return; end
for d=1:m
if(~exist(dirs{d},'dir')), mkdir(dirs{d}); end
for i=1:n, f=fs{d,i}; j=[0 find(f=='/' | f=='\')]; j=j(end);
fs{d,i}=[dirs{d} '/' f(j+1:end)]; copyfile(f,fs{d,i}); end
end
end
function [gt0,dt0] = loadAll( gtDir, dtDir, pLoad )
% Load all ground truth and detection bbs in given directories.
%
% Loads each ground truth (gt) annotation in gtDir and the corresponding
% detection (dt) in dtDir. gt and dt files must correspond according to
% getFiles(). Alternatively, dtDir may be a filename of a single text file
% that contains the detection results across all images.
%
% Each dt should be a text file where each row contains 5 numbers
% representing a bb (left/top/width/height/score). If dtDir is a text file,
% it should contain the detection results across the full set of images. In
% this case each row in the text file should have an extra leading column
% specifying the image id: (imgId/left/top/width/height/score).
%
% The output of this function can be used in bbGt>evalRes().
%
% USAGE
% [gt0,dt0] = bbGt( 'loadAll', gtDir, [dtDir], [pLoad] )
%
% INPUTS
% gtDir - location of ground truth
% dtDir - [] optional location of detections
% pLoad - {} params for bbGt>bbLoad() (determine format/filtering)
%
% OUTPUTS
% gt0 - {1xn} loaded ground truth bbs (each is a mx5 array of bbs)
% dt0 - {1xn} loaded detections (each is a mx5 array of bbs)
%
% EXAMPLE
%
% See also bbGt, bbGt>getFiles, bbGt>evalRes
% get list of files
if(nargin<2), dtDir=[]; end
if(nargin<3), pLoad={}; end
if(isempty(dtDir)), fs=getFiles({gtDir}); gtFs=fs(1,:); else
dtFile=length(dtDir)>4 && strcmp(dtDir(end-3:end),'.txt');
if(dtFile), dirs={gtDir}; else dirs={gtDir,dtDir}; end
fs=getFiles(dirs); gtFs=fs(1,:);
if(dtFile), dtFs=dtDir; else dtFs=fs(2,:); end
end
% load ground truth
persistent keyPrv gtPrv; key={gtDir,pLoad}; n=length(gtFs);
if(isequal(key,keyPrv)), gt0=gtPrv; else gt0=cell(1,n);
for i=1:n, [~,gt0{i}]=bbLoad(gtFs{i},pLoad); end
gtPrv=gt0; keyPrv=key;
end
% load detections
if(isempty(dtDir) || nargout<=1), dt0=cell(0); return; end
if(iscell(dtFs)), dt0=cell(1,n);
for i=1:n, dt1=load(dtFs{i},'-ascii');
if(numel(dt1)==0), dt1=zeros(0,5); end; dt0{i}=dt1(:,1:5); end
else
dt1=load(dtFs,'-ascii'); if(numel(dt1)==0), dt1=zeros(0,6); end
ids=dt1(:,1); assert(max(ids)<=n);
dt0=cell(1,n); for i=1:n, dt0{i}=dt1(ids==i,2:6); end
end
end
function [gt,dt] = evalRes( gt0, dt0, thr, mul )
% Evaluates detections against ground truth data.
%
% Uses modified Pascal criteria that allows for "ignore" regions. The
% Pascal criteria states that a ground truth bounding box (gtBb) and a
% detected bounding box (dtBb) match if their overlap area (oa):
% oa(gtBb,dtBb) = area(intersect(gtBb,dtBb)) / area(union(gtBb,dtBb))
% is over a sufficient threshold (typically .5). In the modified criteria,
% the dtBb can match any subregion of a gtBb set to "ignore". Choosing
% gtBb' in gtBb that most closely matches dtBb can be done by using
% gtBb'=intersect(dtBb,gtBb). Computing oa(gtBb',dtBb) is equivalent to
% oa'(gtBb,dtBb) = area(intersect(gtBb,dtBb)) / area(dtBb)
% For gtBb set to ignore the above formula for oa is used.
%
% Highest scoring detections are matched first. Matches to standard,
% (non-ignore) gtBb are preferred. Each dtBb and gtBb may be matched at
% most once, except for ignore-gtBb which can be matched multiple times.
% Unmatched dtBb are false-positives, unmatched gtBb are false-negatives.
% Each match between a dtBb and gtBb is a true-positive, except matches
% between dtBb and ignore-gtBb which do not affect the evaluation criteria.
%
% In addition to taking gt/dt results on a single image, evalRes() can take
% cell arrays of gt/dt bbs, in which case evaluation proceeds on each
% element. Use bbGt>loadAll() to load gt/dt for multiple images.
%
% Each gt/dt output row has a flag match that is either -1/0/1:
% for gt: -1=ignore, 0=fn [unmatched], 1=tp [matched]
% for dt: -1=ignore, 0=fp [unmatched], 1=tp [matched]
%
% USAGE
% [gt, dt] = bbGt( 'evalRes', gt0, dt0, [thr], [mul] )
%
% INPUTS
% gt0 - [mx5] ground truth array with rows [x y w h ignore]
% dt0 - [nx5] detection results array with rows [x y w h score]
% thr - [.5] the threshold on oa for comparing two bbs
% mul - [0] if true allow multiple matches to each gt
%
% OUTPUTS
% gt - [mx5] ground truth results [x y w h match]
% dt - [nx6] detection results [x y w h score match]
%
% EXAMPLE
%
% See also bbGt, bbGt>compOas, bbGt>loadAll
% get parameters
if(nargin<3 || isempty(thr)), thr=.5; end
if(nargin<4 || isempty(mul)), mul=0; end
% if gt0 and dt0 are cell arrays run on each element in turn
if( iscell(gt0) && iscell(dt0) ), n=length(gt0);
assert(length(dt0)==n); gt=cell(1,n); dt=gt;
for i=1:n, [gt{i},dt{i}] = evalRes(gt0{i},dt0{i},thr,mul); end; return;
end
% check inputs
if(isempty(gt0)), gt0=zeros(0,5); end
if(isempty(dt0)), dt0=zeros(0,5); end
assert( size(dt0,2)==5 ); nd=size(dt0,1);
assert( size(gt0,2)==5 ); ng=size(gt0,1);
% sort dt highest score first, sort gt ignore last
[~,ord]=sort(dt0(:,5),'descend'); dt0=dt0(ord,:);
[~,ord]=sort(gt0(:,5),'ascend'); gt0=gt0(ord,:);
gt=gt0; gt(:,5)=-gt(:,5); dt=dt0; dt=[dt zeros(nd,1)];
% Attempt to match each (sorted) dt to each (sorted) gt
oa = compOas( dt(:,1:4), gt(:,1:4), gt(:,5)==-1 );
for d=1:nd
bstOa=thr; bstg=0; bstm=0; % info about best match so far
for g=1:ng
% if this gt already matched, continue to next gt
m=gt(g,5); if( m==1 && ~mul ), continue; end
% if dt already matched, and on ignore gt, nothing more to do
if( bstm~=0 && m==-1 ), break; end
% compute overlap area, continue to next gt unless better match made
if(oa(d,g)<bstOa), continue; end
% match successful and best so far, store appropriately
bstOa=oa(d,g); bstg=g; if(m==0), bstm=1; else bstm=-1; end
end; g=bstg; m=bstm;
% store type of match for both dt and gt
if(m==-1), dt(d,6)=m; elseif(m==1), gt(g,5)=m; dt(d,6)=m; end
end
end
function [hs,hImg] = showRes( I, gt, dt, varargin )
% Display evaluation results for given image.
%
% USAGE
% [hs,hImg] = bbGt( 'showRes', I, gt, dt, varargin )
%
% INPUTS
% I - image to display, image filename, or []
% gt - first output of evalRes()
% dt - second output of evalRes()
% varargin - additional parameters (struct or name/value pairs)
% .evShow - [1] if true show results of evaluation
% .gtShow - [1] if true show ground truth
% .dtShow - [1] if true show detections
% .cols - ['krg'] colors for ignore/mistake/correct
% .gtLs - ['-'] line style for gt bbs
% .dtLs - ['--'] line style for dt bbs
% .lw - [3] line width
%
% OUTPUTS
% hs - handles to bbs and text labels
% hImg - handle for image graphics object
%
% EXAMPLE
%
% See also bbGt, bbGt>evalRes
dfs={'evShow',1,'gtShow',1,'dtShow',1,'cols','krg',...
'gtLs','-','dtLs','--','lw',3};
[evShow,gtShow,dtShow,cols,gtLs,dtLs,lw]=getPrmDflt(varargin,dfs,1);
% optionally display image
if(ischar(I)), I=imread(I); end
if(~isempty(I)), hImg=im(I,[],0); title(''); end
% display bbs with or w/o color coding based on output of evalRes
hold on; hs=cell(1,1000); k=0;
if( evShow )
if(gtShow), for i=1:size(gt,1), k=k+1;
hs{k}=bbApply('draw',gt(i,1:4),cols(gt(i,5)+2),lw,gtLs); end; end
if(dtShow), for i=1:size(dt,1), k=k+1;
hs{k}=bbApply('draw',dt(i,1:5),cols(dt(i,6)+2),lw,dtLs); end; end
else
if(gtShow), k=k+1; hs{k}=bbApply('draw',gt(:,1:4),cols(3),lw,gtLs); end
if(dtShow), k=k+1; hs{k}=bbApply('draw',dt(:,1:5),cols(3),lw,dtLs); end
end
hs=[hs{:}]; hold off;
end
function [xs,ys,score,ref] = compRoc( gt, dt, roc, ref )
% Compute ROC or PR based on outputs of evalRes on multiple images.
%
% ROC="Receiver operating characteristic"; PR="Precision Recall"
% Also computes result at reference points (ref):
% which for ROC curves is the *detection* rate at reference *FPPI*
% which for PR curves is the *precision* at reference *recall*
% Note, FPPI="false positive per image"
%
% USAGE
% [xs,ys,score,ref] = bbGt( 'compRoc', gt, dt, roc, ref )
%
% INPUTS
% gt - {1xn} first output of evalRes() for each image
% dt - {1xn} second output of evalRes() for each image
% roc - [1] if 1 compue ROC else compute PR
% ref - [] reference points for ROC or PR curve
%
% OUTPUTS
% xs - x coords for curve: ROC->FPPI; PR->recall
% ys - y coords for curve: ROC->TP; PR->precision
% score - detection scores corresponding to each (x,y)
% ref - recall or precision at each reference point
%
% EXAMPLE
%
% See also bbGt, bbGt>evalRes
% get additional parameters
if(nargin<3 || isempty(roc)), roc=1; end
if(nargin<4 || isempty(ref)), ref=[]; end
% convert to single matrix, discard ignore bbs
nImg=length(gt); assert(length(dt)==nImg);
gt=cat(1,gt{:}); gt=gt(gt(:,5)~=-1,:);
dt=cat(1,dt{:}); dt=dt(dt(:,6)~=-1,:);
% compute results
if(size(dt,1)==0), xs=0; ys=0; score=0; ref=ref*0; return; end
m=length(ref); np=size(gt,1); score=dt(:,5); tp=dt(:,6);
[score,order]=sort(score,'descend'); tp=tp(order);
fp=double(tp~=1); fp=cumsum(fp); tp=cumsum(tp);
if( roc )
xs=fp/nImg; ys=tp/np; xs1=[-inf; xs]; ys1=[0; ys];
for i=1:m, j=find(xs1<=ref(i)); ref(i)=ys1(j(end)); end
else
xs=tp/np; ys=tp./(fp+tp); xs1=[xs; inf]; ys1=[ys; 0];
for i=1:m, j=find(xs1>=ref(i)); ref(i)=ys1(j(1)); end
end
end
function [Is,scores,imgIds] = cropRes( gt, dt, imFs, varargin )
% Extract true or false positives or negatives for visualization.
%
% USAGE
% [Is,scores,imgIds] = bbGt( 'cropRes', gt, dt, imFs, varargin )
%
% INPUTS
% gt - {1xN} first output of evalRes() for each image
% dt - {1xN} second output of evalRes() for each image
% imFs - {1xN} name of each image
% varargin - additional parameters (struct or name/value pairs)
% .dims - ['REQ'] target dimensions for extracted windows
% .pad - [0] padding amount for cropping
% .type - ['fp'] one of: 'fp', 'fn', 'tp', 'dt'
% .n - [100] max number of windows to extract
% .show - [1] figure for displaying results (or 0)
% .fStr - ['%0.1f'] label{i}=num2str(score(i),fStr)
% .embed - [0] if true embed dt/gt bbs into cropped windows
%
% OUTPUTS
% Is - [dimsxn] extracted image windows
% scores - [1xn] detection score for each bb unless 'fn'
% imgIds - [1xn] image id for each cropped window
%
% EXAMPLE
%
% See also bbGt, bbGt>evalRes
dfs={'dims','REQ','pad',0,'type','fp','n',100,...
'show',1,'fStr','%0.1f','embed',0};
[dims,pad,type,n,show,fStr,embed]=getPrmDflt(varargin,dfs,1);
N=length(imFs); assert(length(gt)==N && length(dt)==N);
% crop patches either in gt or dt according to type
switch type
case 'fn', bbs=gt; keep=@(bbs) bbs(:,5)==0;
case 'fp', bbs=dt; keep=@(bbs) bbs(:,6)==0;
case 'tp', bbs=dt; keep=@(bbs) bbs(:,6)==1;
case 'dt', bbs=dt; keep=@(bbs) bbs(:,6)>=0;
otherwise, error('unknown type: %s',type);
end
% create ids that will map each bb to correct name
ms=zeros(1,N); for i=1:N, ms(i)=size(bbs{i},1); end; cms=[0 cumsum(ms)];
ids=zeros(1,sum(ms)); for i=1:N, ids(cms(i)+1:cms(i+1))=i; end
% flatten bbs and keep relevent subset
bbs=cat(1,bbs{:}); K=keep(bbs); bbs=bbs(K,:); ids=ids(K); n=min(n,sum(K));
% reorder bbs appropriately
if(~strcmp(type,'fn')), [~,ord]=sort(bbs(:,5),'descend'); else
if(size(bbs,1)<n), ord=randperm(size(bbs,1)); else ord=1:n; end; end
bbs=bbs(ord(1:n),:); ids=ids(ord(1:n));
% extract patches from each image
if(n==0), Is=[]; scores=[]; imgIds=[]; return; end;
Is=cell(1,n); scores=zeros(1,n); imgIds=zeros(1,n);
if(any(pad>0)), dims1=dims.*(1+pad); rs=dims1./dims; dims=dims1; end
if(any(pad>0)), bbs=bbApply('resize',bbs,rs(1),rs(2)); end
for i=1:N
locs=find(ids==i); if(isempty(locs)), continue; end; I=imread(imFs{i});
if( embed )
if(any(strcmp(type,{'fp','dt'}))), bbs1=gt{i};
else bbs1=dt{i}(:,[1:4 6]); end
I=bbApply('embed',I,bbs1(bbs1(:,5)==0,1:4),'col',[255 0 0]);
I=bbApply('embed',I,bbs1(bbs1(:,5)==1,1:4),'col',[0 255 0]);
end
Is1=bbApply('crop',I,bbs(locs,1:4),'replicate',dims);
for j=1:length(locs), Is{locs(j)}=Is1{j}; end;
scores(locs)=bbs(locs,5); imgIds(locs)=i;
end; Is=cell2array(Is);
% optionally display
if(~show), return; end; figure(show); pMnt={'hasChn',size(Is1{1},3)>1};
if(isempty(fStr)), montage2(Is,pMnt); title(type); return; end
ls=cell(1,n); for i=1:n, ls{i}=int2str2(imgIds(i)); end
if(~strcmp(type,'fn'))
for i=1:n, ls{i}=[ls{i} '/' num2str(scores(i),fStr)]; end; end
montage2(Is,[pMnt 'labels' {ls}]); title(type);
end
function oa = compOas( dt, gt, ig )
% Computes (modified) overlap area between pairs of bbs.
%
% Uses modified Pascal criteria with "ignore" regions. The overlap area
% (oa) of a ground truth (gt) and detected (dt) bb is defined as:
% oa(gt,dt) = area(intersect(dt,dt)) / area(union(gt,dt))
% In the modified criteria, a gt bb may be marked as "ignore", in which
% case the dt bb can can match any subregion of the gt bb. Choosing gt' in
% gt that most closely matches dt can be done using gt'=intersect(dt,gt).
% Computing oa(gt',dt) is equivalent to:
% oa'(gt,dt) = area(intersect(gt,dt)) / area(dt)
%
% USAGE
% oa = bbGt( 'compOas', dt, gt, [ig] )
%
% INPUTS
% dt - [mx4] detected bbs
% gt - [nx4] gt bbs
% ig - [nx1] 0/1 ignore flags (0 by default)
%
% OUTPUTS
% oas - [m x n] overlap area between each gt and each dt bb
%
% EXAMPLE
% dt=[0 0 10 10]; gt=[0 0 20 20];
% oa0 = bbGt('compOas',dt,gt,0)
% oa1 = bbGt('compOas',dt,gt,1)
%
% See also bbGt, bbGt>evalRes
m=size(dt,1); n=size(gt,1); oa=zeros(m,n);
if(nargin<3), ig=zeros(n,1); end
de=dt(:,[1 2])+dt(:,[3 4]); da=dt(:,3).*dt(:,4);
ge=gt(:,[1 2])+gt(:,[3 4]); ga=gt(:,3).*gt(:,4);
for i=1:m
for j=1:n
w=min(de(i,1),ge(j,1))-max(dt(i,1),gt(j,1)); if(w<=0), continue; end
h=min(de(i,2),ge(j,2))-max(dt(i,2),gt(j,2)); if(h<=0), continue; end
t=w*h; if(ig(j)), u=da(i); else u=da(i)+ga(j)-t; end; oa(i,j)=t/u;
end
end
end
function oa = compOa( dt, gt, ig )
% Optimized version of compOas for a single pair of bbs.
%
% USAGE
% oa = bbGt( 'compOa', dt, gt, ig )
%
% INPUTS
% dt - [1x4] detected bb
% gt - [1x4] gt bb
% ig - 0/1 ignore flag
%
% OUTPUTS
% oa - overlap area between gt and dt bb
%
% EXAMPLE
% dt=[0 0 10 10]; gt=[0 0 20 20];
% oa0 = bbGt('compOa',dt,gt,0)
% oa1 = bbGt('compOa',dt,gt,1)
%
% See also bbGt, bbGt>compOas
w=min(dt(3)+dt(1),gt(3)+gt(1))-max(dt(1),gt(1)); if(w<=0),oa=0; return; end
h=min(dt(4)+dt(2),gt(4)+gt(2))-max(dt(2),gt(2)); if(h<=0),oa=0; return; end
i=w*h; if(ig),u=dt(3)*dt(4); else u=dt(3)*dt(4)+gt(3)*gt(4)-i; end; oa=i/u;
end
|
github
|
P-Chao/acfdetect-master
|
bbApply.m
|
.m
|
acfdetect-master/toolbox/detector/bbApply.m
| 21,195 |
utf_8
|
cc9744e55c6b8442486ba7f71e3f84ce
|
function varargout = bbApply( action, varargin )
% Functions for manipulating bounding boxes (bb).
%
% A bounding box (bb) is also known as a position vector or a rectangle
% object. It is a four element vector with the fields: [x y w h]. A set of
% n bbs can be stores as an [nx4] array, most funcitons below can handle
% either a single or multiple bbs. In addtion, typically [nxm] inputs with
% m>4 are ok (with the additional columns ignored/copied to the output).
%
% bbApply contains a number of utility functions for working with bbs. The
% format for accessing the various utility functions is:
% outputs = bbApply( 'action', inputs );
% The list of functions and help for each is given below. Also, help on
% individual subfunctions can be accessed by: "help bbApply>action".
%
% Compute area of bbs.
% bb = bbApply( 'area', bb )
% Shift center of bbs.
% bb = bbApply( 'shift', bb, xdel, ydel )
% Get center of bbs.
% cen = bbApply( 'getCenter', bb )
% Get bb at intersection of bb1 and bb2 (may be empty).
% bb = bbApply( 'intersect', bb1, bb2 )
% Get bb that is union of bb1 and bb2 (smallest bb containing both).
% bb = bbApply( 'union', bb1, bb2 )
% Resize the bbs (without moving their centers).
% bb = bbApply( 'resize', bb, hr, wr, [ar] )
% Fix bb aspect ratios (without moving the bb centers).
% bbr = bbApply( 'squarify', bb, flag, [ar] )
% Draw single or multiple bbs to image (calls rectangle()).
% hs = bbApply( 'draw', bb, [col], [lw], [ls], [prop], [ids] )
% Embed single or multiple bbs directly into image.
% I = bbApply( 'embed', I, bb, [varargin] )
% Crop image regions from I encompassed by bbs.
% [patches, bbs] = bbApply('crop',I,bb,[padEl],[dims])
% Convert bb relative to absolute coordinates and vice-versa.
% bb = bbApply( 'convert', bb, bbRef, isAbs )
% Randomly generate bbs that fall in a specified region.
% bbs = bbApply( 'random', pRandom )
% Convert weighted mask to bbs.
% bbs = bbApply('frMask',M,bbw,bbh,[thr])
% Create weighted mask encoding bb centers (or extent).
% M = bbApply('toMask',bbs,w,h,[fill],[bgrd])
%
% USAGE
% varargout = bbApply( action, varargin );
%
% INPUTS
% action - string specifying action
% varargin - depends on action, see above
%
% OUTPUTS
% varargout - depends on action, see above
%
% EXAMPLE
%
% See also bbApply>area bbApply>shift bbApply>getCenter bbApply>intersect
% bbApply>union bbApply>resize bbApply>squarify bbApply>draw bbApply>crop
% bbApply>convert bbApply>random bbApply>frMask bbApply>toMask
%
% Piotr's Computer Vision Matlab Toolbox Version 3.30
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%#ok<*DEFNU>
varargout = cell(1,max(1,nargout));
[varargout{:}] = feval(action,varargin{:});
end
function a = area( bb )
% Compute area of bbs.
%
% USAGE
% bb = bbApply( 'area', bb )
%
% INPUTS
% bb - [nx4] original bbs
%
% OUTPUTS
% a - [nx1] area of each bb
%
% EXAMPLE
% a = bbApply('area', [0 0 10 10])
%
% See also bbApply
a=prod(bb(:,3:4),2);
end
function bb = shift( bb, xdel, ydel )
% Shift center of bbs.
%
% USAGE
% bb = bbApply( 'shift', bb, xdel, ydel )
%
% INPUTS
% bb - [nx4] original bbs
% xdel - amount to shift x coord of each bb left
% ydel - amount to shift y coord of each bb up
%
% OUTPUTS
% bb - [nx4] shifted bbs
%
% EXAMPLE
% bb = bbApply('shift', [0 0 10 10], 1, 2)
%
% See also bbApply
bb(:,1)=bb(:,1)-xdel; bb(:,2)=bb(:,2)-ydel;
end
function cen = getCenter( bb )
% Get center of bbs.
%
% USAGE
% cen = bbApply( 'getCenter', bb )
%
% INPUTS
% bb - [nx4] original bbs
%
% OUTPUTS
% cen - [nx1] centers of bbs
%
% EXAMPLE
% cen = bbApply('getCenter', [0 0 10 10])
%
% See also bbApply
cen=bb(:,1:2)+bb(:,3:4)/2;
end
function bb = intersect( bb1, bb2 )
% Get bb at intersection of bb1 and bb2 (may be empty).
%
% USAGE
% bb = bbApply( 'intersect', bb1, bb2 )
%
% INPUTS
% bb1 - [nx4] first set of bbs
% bb2 - [nx4] second set of bbs
%
% OUTPUTS
% bb - [nx4] intersection of bbs
%
% EXAMPLE
% bb = bbApply('intersect', [0 0 10 10], [5 5 10 10])
%
% See also bbApply bbApply>union
n1=size(bb1,1); n2=size(bb2,1);
if(n1==0 || n2==0), bb=zeros(0,4); return, end
if(n1==1 && n2>1), bb1=repmat(bb1,n2,1); n1=n2; end
if(n2==1 && n1>1), bb2=repmat(bb2,n1,1); n2=n1; end
assert(n1==n2);
lcsE=min(bb1(:,1:2)+bb1(:,3:4),bb2(:,1:2)+bb2(:,3:4));
lcsS=max(bb1(:,1:2),bb2(:,1:2)); empty=any(lcsE<lcsS,2);
bb=[lcsS lcsE-lcsS]; bb(empty,:)=0;
end
function bb = union( bb1, bb2 )
% Get bb that is union of bb1 and bb2 (smallest bb containing both).
%
% USAGE
% bb = bbApply( 'union', bb1, bb2 )
%
% INPUTS
% bb1 - [nx4] first set of bbs
% bb2 - [nx4] second set of bbs
%
% OUTPUTS
% bb - [nx4] intersection of bbs
%
% EXAMPLE
% bb = bbApply('union', [0 0 10 10], [5 5 10 10])
%
% See also bbApply bbApply>intersect
n1=size(bb1,1); n2=size(bb2,1);
if(n1==0 || n2==0), bb=zeros(0,4); return, end
if(n1==1 && n2>1), bb1=repmat(bb1,n2,1); n1=n2; end
if(n2==1 && n1>1), bb2=repmat(bb2,n1,1); n2=n1; end
assert(n1==n2);
lcsE=max(bb1(:,1:2)+bb1(:,3:4),bb2(:,1:2)+bb2(:,3:4));
lcsS=min(bb1(:,1:2),bb2(:,1:2));
bb=[lcsS lcsE-lcsS];
end
function bb = resize( bb, hr, wr, ar )
% Resize the bbs (without moving their centers).
%
% If wr>0 or hr>0, the w/h of each bb is adjusted in the following order:
% if(hr~=0), h=h*hr; end
% if(wr~=0), w=w*wr; end
% if(hr==0), h=w/ar; end
% if(wr==0), w=h*ar; end
% Only one of hr/wr may be set to 0, and then only if ar>0. If, however,
% hr=wr=0 and ar>0 then resizes bbs such that areas and centers are
% preserved but aspect ratio becomes ar.
%
% USAGE
% bb = bbApply( 'resize', bb, hr, wr, [ar] )
%
% INPUTS
% bb - [nx4] original bbs
% hr - ratio by which to multiply height (or 0)
% wr - ratio by which to multiply width (or 0)
% ar - [0] target aspect ratio (used only if hr=0 or wr=0)
%
% OUTPUT
% bb - [nx4] the output resized bbs
%
% EXAMPLE
% bb = bbApply('resize',[0 0 1 1],1.2,0,.5) % h'=1.2*h; w'=h'/2;
%
% See also bbApply, bbApply>squarify
if(nargin<4), ar=0; end; assert(size(bb,2)>=4);
assert((hr>0&&wr>0)||ar>0);
% preserve area and center, set aspect ratio
if(hr==0 && wr==0), a=sqrt(bb(:,3).*bb(:,4)); ar=sqrt(ar);
d=a*ar-bb(:,3); bb(:,1)=bb(:,1)-d/2; bb(:,3)=bb(:,3)+d;
d=a/ar-bb(:,4); bb(:,2)=bb(:,2)-d/2; bb(:,4)=bb(:,4)+d; return;
end
% possibly adjust h/w based on hr/wr
if(hr~=0), d=(hr-1)*bb(:,4); bb(:,2)=bb(:,2)-d/2; bb(:,4)=bb(:,4)+d; end
if(wr~=0), d=(wr-1)*bb(:,3); bb(:,1)=bb(:,1)-d/2; bb(:,3)=bb(:,3)+d; end
% possibly adjust h/w based on ar and NEW h/w
if(~hr), d=bb(:,3)/ar-bb(:,4); bb(:,2)=bb(:,2)-d/2; bb(:,4)=bb(:,4)+d; end
if(~wr), d=bb(:,4)*ar-bb(:,3); bb(:,1)=bb(:,1)-d/2; bb(:,3)=bb(:,3)+d; end
end
function bbr = squarify( bb, flag, ar )
% Fix bb aspect ratios (without moving the bb centers).
%
% The w or h of each bb is adjusted so that w/h=ar.
% The parameter flag controls whether w or h should change:
% flag==0: expand bb to given ar
% flag==1: shrink bb to given ar
% flag==2: use original w, alter h
% flag==3: use original h, alter w
% flag==4: preserve area, alter w and h
% If ar==1 (the default), always converts bb to a square, hence the name.
%
% USAGE
% bbr = bbApply( 'squarify', bb, flag, [ar] )
%
% INPUTS
% bb - [nx4] original bbs
% flag - controls whether w or h should change
% ar - [1] desired aspect ratio
%
% OUTPUT
% bbr - the output 'squarified' bbs
%
% EXAMPLE
% bbr = bbApply('squarify',[0 0 1 2],0)
%
% See also bbApply, bbApply>resize
if(nargin<3 || isempty(ar)), ar=1; end; bbr=bb;
if(flag==4), bbr=resize(bb,0,0,ar); return; end
for i=1:size(bb,1), p=bb(i,1:4);
usew = (flag==0 && p(3)>p(4)*ar) || (flag==1 && p(3)<p(4)*ar) || flag==2;
if(usew), p=resize(p,0,1,ar); else p=resize(p,1,0,ar); end; bbr(i,1:4)=p;
end
end
function hs = draw( bb, col, lw, ls, prop, ids )
% Draw single or multiple bbs to image (calls rectangle()).
%
% To draw bbs aligned with pixel boundaries, subtract .5 from the x and y
% coordinates (since pixel centers are located at integer locations).
%
% USAGE
% hs = bbApply( 'draw', bb, [col], [lw], [ls], [prop], [ids] )
%
% INPUTS
% bb - [nx4] standard bbs or [nx5] weighted bbs
% col - ['g'] color or [kx1] array of colors
% lw - [2] LineWidth for rectangle
% ls - ['-'] LineStyle for rectangle
% prop - [] other properties for rectangle
% ids - [ones(1,n)] id in [1,k] for each bb into colors array
%
% OUTPUT
% hs - [nx1] handles to drawn rectangles (and labels)
%
% EXAMPLE
% im(rand(3)); bbApply('draw',[1.5 1.5 1 1 .5],'g');
%
% See also bbApply, bbApply>embed, rectangle
[n,m]=size(bb); if(n==0), hs=[]; return; end
if(nargin<2 || isempty(col)), col=[]; end
if(nargin<3 || isempty(lw)), lw=2; end
if(nargin<4 || isempty(ls)), ls='-'; end
if(nargin<5 || isempty(prop)), prop={}; end
if(nargin<6 || isempty(ids)), ids=ones(1,n); end
% prepare display properties
prop=['LineWidth' lw 'LineStyle' ls prop 'EdgeColor'];
tProp={'FontSize',10,'color','w','FontWeight','bold',...
'VerticalAlignment','bottom'}; k=max(ids);
if(isempty(col)), if(k==1), col='g'; else col=hsv(k); end; end
if(size(col,1)<k), ids=ones(1,n); end; hs=zeros(1,n);
% draw rectangles and optionally labels
for b=1:n, hs(b)=rectangle('Position',bb(b,1:4),prop{:},col(ids(b),:)); end
if(m==4), return; end; hs=[hs zeros(1,n)]; bb=double(bb);
for b=1:n, hs(b+n)=text(bb(b,1),bb(b,2),num2str(bb(b,5),4),tProp{:}); end
end
function I = embed( I, bb, varargin )
% Embed single or multiple bbs directly into image.
%
% USAGE
% I = bbApply( 'embed', I, bb, varargin )
%
% INPUTS
% I - input image
% bb - [nx4] or [nx5] input bbs
% varargin - additional params (struct or name/value pairs)
% .col - [0 255 0] color for rectangle or nx3 array of colors
% .lw - [3] width for rectangle in pixels
% .fh - [35] font height (if displaying weight), may be 0
% .fcol - [255 0 0] font color or nx3 array of colors
%
% OUTPUT
% I - output image
%
% EXAMPLE
% I=imResample(imread('cameraman.tif'),2); bb=[200 70 70 90 0.25];
% J=bbApply('embed',I,bb,'col',[0 0 255],'lw',8,'fh',30); figure(1); im(J)
% K=bbApply('embed',J,bb,'col',[0 255 0],'lw',2,'fh',30); figure(2); im(K)
%
% See also bbApply, bbApply>draw, char2img
% get additional parameters
dfs={'col',[0 255 0],'lw',3,'fh',35,'fcol',[255 0 0]};
[col,lw,fh,fcol]=getPrmDflt(varargin,dfs,1);
n=size(bb,1); bb(:,1:4)=round(bb(:,1:4));
if(size(col,1)==1), col=col(ones(1,n),:); end
if(size(fcol,1)==1), fcol=fcol(ones(1,n),:); end
if( ismatrix(I) ), I=I(:,:,[1 1 1]); end
% embed each bb
x0=bb(:,1); x1=x0+bb(:,3)-1; y0=bb(:,2); y1=y0+bb(:,4)-1;
j0=floor((lw-1)/2); j1=ceil((lw-1)/2); h=size(I,1); w=size(I,2);
x00=max(1,x0-j0); x01=min(x0+j1,w); x10=max(1,x1-j0); x11=min(x1+j1,w);
y00=max(1,y0-j0); y01=min(y0+j1,h); y10=max(1,y1-j0); y11=min(y1+j1,h);
for b=1:n
for c=1:3, I([y00(b):y01(b) y10(b):y11(b)],x00(b):x11(b),c)=col(b,c); end
for c=1:3, I(y00(b):y11(b),[x00(b):x01(b) x10(b):x11(b)],c)=col(b,c); end
end
% embed text displaying bb score (inside upper-left bb corner)
if(size(bb,2)<5 || fh==0), return; end
bb(:,1:4)=intersect(bb(:,1:4),[1 1 w h]);
for b=1:n
M=char2img(sprintf('%.4g',bb(b,5)),fh); M=M{1}==0; [h,w]=size(M);
y0=bb(b,2); y1=y0+h-1; x0=bb(b,1); x1=x0+w-1;
if( x0>=1 && y0>=1 && x1<=size(I,2) && y1<=size(I,2))
Ir=I(y0:y1,x0:x1,1); Ig=I(y0:y1,x0:x1,2); Ib=I(y0:y1,x0:x1,3);
Ir(M)=fcol(b,1); Ig(M)=fcol(b,2); Ib(M)=fcol(b,3);
I(y0:y1,x0:x1,:)=cat(3,Ir,Ig,Ib);
end
end
end
function [patches, bbs] = crop( I, bbs, padEl, dims )
% Crop image regions from I encompassed by bbs.
%
% The only subtlety is that a pixel centered at location (i,j) would have a
% bb of [j-1/2,i-1/2,1,1]. The -1/2 is because pixels are located at
% integer locations. This is a Matlab convention, to confirm use:
% im(rand(3)); bbApply('draw',[1.5 1.5 1 1],'g')
% If bb contains all integer entries cropping is straightforward. If
% entries are not integers, x=round(x+.499) is used, eg 1.2 actually goes
% to 2 (since it is closer to 1.5 then .5), and likewise for y.
%
% If ~isempty(padEl), image is padded so can extract full bb region (no
% actual padding is done, this is fast). Otherwise bb is intersected with
% the image bb prior to cropping. If padEl is a string ('circular',
% 'replicate', or 'symmetric'), uses padarray to do actual padding (slow).
%
% USAGE
% [patches, bbs] = bbApply('crop',I,bb,[padEl],[dims])
%
% INPUTS
% I - image from which to crop patches
% bbs - bbs that indicate regions to crop
% padEl - [0] value to pad I or [] to indicate no padding (see above)
% dims - [] if specified resize each cropped patch to [w h]
%
% OUTPUTS
% patches - [1xn] cell of cropped image regions
% bbs - actual integer-valued bbs used to crop
%
% EXAMPLE
% I=imread('cameraman.tif'); bb=[-10 -10 100 100];
% p1=bbApply('crop',I,bb); p2=bbApply('crop',I,bb,'replicate');
% figure(1); im(I); figure(2); im(p1{1}); figure(3); im(p2{1});
%
% See also bbApply, ARRAYCROP, PADARRAY, IMRESAMPLE
% get padEl, bound bb to visible region if empty
if( nargin<3 ), padEl=0; end; h=size(I,1); w=size(I,2);
if( nargin<4 ), dims=[]; end;
if(isempty(padEl)), bbs=intersect([.5 .5 w h],bbs); end
% crop each patch in turn
n=size(bbs,1); patches=cell(1,n);
for i=1:n, [patches{i},bbs(i,1:4)]=crop1(bbs(i,1:4)); end
function [patch, bb] = crop1( bb )
% crop single patch (use arrayCrop only if necessary)
lcsS=round(bb([2 1])+.5-.001); lcsE=lcsS+round(bb([4 3]))-1;
if( any(lcsS<1) || lcsE(1)>h || lcsE(2)>w )
if( ischar(padEl) )
pt=max(0,1-lcsS(1)); pb=max(0,lcsE(1)-h);
pl=max(0,1-lcsS(2)); pr=max(0,lcsE(2)-w);
lcsS1=max(1,lcsS); lcsE1=min(lcsE,[h w]);
patch = I(lcsS1(1):lcsE1(1),lcsS1(2):lcsE1(2),:);
patch = padarray(patch,[pt pl],padEl,'pre');
patch = padarray(patch,[pb pr],padEl,'post');
else
if(ndims(I)==3); lcsS=[lcsS 1]; lcsE=[lcsE 3]; end
patch = arrayCrop(I,lcsS,lcsE,padEl);
end
else
patch = I(lcsS(1):lcsE(1),lcsS(2):lcsE(2),:);
end
bb = [lcsS([2 1]) lcsE([2 1])-lcsS([2 1])+1];
if(~isempty(dims)), patch=imResample(patch,[dims(2),dims(1)]); end
end
end
function bb = convert( bb, bbRef, isAbs )
% Convert bb relative to absolute coordinates and vice-versa.
%
% If isAbs==1, bb is assumed to be given in absolute coords, and the output
% is given in coords relative to bbRef. Otherwise, if isAbs==0, bb is
% assumed to be given in coords relative to bbRef and the output is given
% in absolute coords.
%
% USAGE
% bb = bbApply( 'convert', bb, bbRef, isAbs )
%
% INPUTS
% bb - original bb, either in abs or rel coords
% bbRef - reference bb
% isAbs - 1: bb is in abs coords, 0: bb is in rel coords
%
% OUTPUTS
% bb - converted bb
%
% EXAMPLE
% bbRef=[5 5 15 15]; bba=[10 10 5 5];
% bbr = bbApply( 'convert', bba, bbRef, 1 )
% bba2 = bbApply( 'convert', bbr, bbRef, 0 )
%
% See also bbApply
if( isAbs )
bb(1:2)=bb(1:2)-bbRef(1:2);
bb=bb./bbRef([3 4 3 4]);
else
bb=bb.*bbRef([3 4 3 4]);
bb(1:2)=bb(1:2)+bbRef(1:2);
end
end
function bbs = random( varargin )
% Randomly generate bbs that fall in a specified region.
%
% The vector dims defines the region in which bbs are generated. Specify
% dims=[height width] to generate bbs=[x y w h] such that: 1<=x<=width,
% 1<=y<=height, x+w-1<=width, y+h-1<=height. The biggest bb generated can
% be bb=[1 1 width height]. If dims is a three element vector the third
% coordinate is the depth, in this case bbs=[x y w h d] where 1<=d<=depth.
%
% A number of constraints can be specified that control the size and other
% characteristics of the generated bbs. Note that if incompatible
% constraints are specified (e.g. if the maximum width and height are both
% 5 while the minimum area is 100) no bbs will be generated. More
% generally, if fewer than n bbs are generated a warning is displayed.
%
% USAGE
% bbs = bbApply( 'random', pRandom )
%
% INPUTS
% pRandom - parameters (struct or name/value pairs)
% .n - ['REQ'] number of bbs to generate
% .dims - ['REQ'] region in which to generate bbs [height,width]
% .wRng - [1 inf] range for width of bbs (or scalar value)
% .hRng - [1 inf] range for height of bbs (or scalar value)
% .aRng - [1 inf] range for area of bbs
% .arRng - [0 inf] range for aspect ratio (width/height) of bbs
% .unique - [1] if true generate unique bbs
% .maxOverlap - [1] max overlap (intersection/union) between bbs
% .maxIter - [100] max iterations to go w/o changes before giving up
% .show - [0] if true show sample generated bbs
%
% OUTPUTS
% bbs - [nx4] array of randomly generated integer bbs
%
% EXAMPLE
% bbs=bbApply('random','n',50,'dims',[20 20],'arRng',[.5 .5],'show',1);
%
% See also bbApply
% get parameters
rng=[1 inf]; dfs={ 'n','REQ', 'dims','REQ', 'wRng',rng, 'hRng',rng, ...
'aRng',rng, 'arRng',[0 inf], 'unique',1, 'maxOverlap',1, ...
'maxIter',100, 'show',0 };
[n,dims,wRng,hRng,aRng,arRng,uniqueOnly,maxOverlap,maxIter,show] ...
= getPrmDflt(varargin,dfs,1);
if(length(hRng)==1), hRng=[hRng hRng]; end
if(length(wRng)==1), wRng=[wRng wRng]; end
if(length(dims)==3), d=5; else d=4; end
% generate random bbs satisfying constraints
bbs=zeros(0,d); ids=zeros(0,1); n1=min(n*10,1000);
M=max(dims)+1; M=M.^(0:d-1); iter=0; k=0;
tid=ticStatus('generating random bbs',1,2);
while( k<n && iter<maxIter )
ys=1+floor(rand(2,n1)*dims(1)); ys0=min(ys); ys1=max(ys); hs=ys1-ys0+1;
xs=1+floor(rand(2,n1)*dims(2)); xs0=min(xs); xs1=max(xs); ws=xs1-xs0+1;
if(d==5), ds=1+floor(rand(1,n1)*dims(3)); else ds=zeros(0,n1); end
if(arRng(1)==arRng(2)), ws=hs.*arRng(1); end
ars=ws./hs; ws=round(ws); xs1=xs0+ws-1; as=ws.*hs;
kp = ys0>0 & xs0>0 & ys1<=dims(1) & xs1<=dims(2) & ...
hs>=hRng(1) & hs<=hRng(2) & ws>=wRng(1) & ws<=wRng(2) & ...
as>=aRng(1) & as<=aRng(2) & ars>=arRng(1) & ars<=arRng(2);
bbs1=[xs0' ys0' ws' hs' ds']; bbs1=bbs1(kp,:);
k0=k; bbs=[bbs; bbs1]; k=size(bbs,1); %#ok<AGROW>
if( maxOverlap<1 && k ), bbs=bbs(1:k0,:);
for j=1:size(bbs1,1), bbs0=bbs; bb=bbs1(j,:);
if(d==5), bbs=bbs(bbs(:,5)==bb(5),:); end
if(isempty(bbs)), bbs=[bbs0; bb]; continue; end
ws1=min(bbs(:,1)+bbs(:,3),bb(1)+bb(3))-max(bbs(:,1),bb(1));
hs1=min(bbs(:,2)+bbs(:,4),bb(2)+bb(4))-max(bbs(:,2),bb(2));
o=max(0,ws1).*max(0,hs1); o=o./(bbs(:,3).*bbs(:,4)+bb(3).*bb(4)-o);
if(max(o)<=maxOverlap), bbs=[bbs0; bb]; else bbs=bbs0; end
end
elseif( uniqueOnly && k )
ids=[ids; sum(bbs1.*M(ones(1,size(bbs1,1)),:),2)]; %#ok<AGROW>
[ids,o]=sort(ids); bbs=bbs(o,:); kp=[ids(1:end-1)~=ids(2:end); true];
bbs=bbs(kp,:); ids=ids(kp,:);
end
k=size(bbs,1); if(k0==k), iter=iter+1; else iter=0; end
if(k>n), bbs=bbs(randSample(k,n),:); k=n; end;
tocStatus(tid,max(k/n,iter/maxIter));
end
if( k<n ), warning('only generated %i of %i bbs',k,n); n=k; end %#ok<WNTAG>
% optionally display a few bbs
if( show )
k=8; figure(show); im(zeros(dims)); cs=uniqueColors(1,k,0,0);
if(n>k), bbs1=bbs(randsample(n,k),:); else bbs1=bbs; end
bbs1(:,1:2)=bbs1(:,1:2)-.5;
for i=1:min(k,n), rectangle('Position',bbs1(i,:),...
'EdgeColor',cs(i,:),'LineStyle','--'); end
end
end
function bbs = frMask( M, bbw, bbh, thr )
% Convert weighted mask to bbs.
%
% Pixels in mask above given threshold (thr) indicate bb centers.
%
% USAGE
% bbs = bbApply('frMask',M,bbw,bbh,[thr])
%
% INPUTS
% M - mask
% bbw - bb target width
% bbh - bb target height
% thr - [0] mask threshold
%
% OUTPUTS
% bbs - bounding boxes
%
% EXAMPLE
% w=20; h=10; bbw=5; bbh=8; M=double(rand(h,w)); M(M<.95)=0;
% bbs=bbApply('frMask',M,bbw,bbh); M2=bbApply('toMask',bbs,w,h);
% sum(abs(M(:)-M2(:)))
%
% See also bbApply, bbApply>toMask
if(nargin<4), thr=0; end
ids=find(M>thr); ids=ids(:); h=size(M,1);
if(isempty(ids)), bbs=zeros(0,5); return; end
xs=floor((ids-1)/h); ys=ids-xs*h; xs=xs+1;
bbs=[xs-floor(bbw/2) ys-floor(bbh/2)];
bbs(:,3)=bbw; bbs(:,4)=bbh; bbs(:,5)=M(ids);
end
function M = toMask( bbs, w, h, fill, bgrd )
% Create weighted mask encoding bb centers (or extent).
%
% USAGE
% M = bbApply('toMask',bbs,w,h,[fill],[bgrd])
%
% INPUTS
% bbs - bounding boxes
% w - mask target width
% h - mask target height
% fill - [0] if 1 encodes extent of bbs
% bgrd - [0] default value for background pixels
%
% OUTPUTS
% M - hxw mask
%
% EXAMPLE
%
% See also bbApply, bbApply>frMask
if(nargin<4||isempty(fill)), fill=0; end
if(nargin<5||isempty(bgrd)), bgrd=0; end
if(size(bbs,2)==4), bbs(:,5)=1; end
M=zeros(h,w); B=true(h,w); n=size(bbs,1);
if( fill==0 )
p=floor(getCenter(bbs)); p=sub2ind([h w],p(:,2),p(:,1));
for i=1:n, M(p(i))=M(p(i))+bbs(i,5); end
if(bgrd~=0), B(p)=0; end
else
bbs=[intersect(round(bbs),[1 1 w h]) bbs(:,5)]; n=size(bbs,1);
x0=bbs(:,1); x1=x0+bbs(:,3)-1; y0=bbs(:,2); y1=y0+bbs(:,4)-1;
for i=1:n, y=y0(i):y1(i); x=x0(i):x1(i);
M(y,x)=M(y,x)+bbs(i,5); B(y,x)=0; end
end
if(bgrd~=0), M(B)=bgrd; end
end
|
github
|
P-Chao/acfdetect-master
|
imwrite2.m
|
.m
|
acfdetect-master/toolbox/images/imwrite2.m
| 5,086 |
utf_8
|
c98d66c2cddd9ec90beb9b1bbde31fe0
|
function I = imwrite2( I, mulFlag, imagei, path, ...
name, ext, nDigits, nSplits, spliti, varargin )
% Similar to imwrite, except follows a strict naming convention.
%
% Wrapper for imwrite that writes file to the filename:
% fName = [path name int2str2(i,nDigits) '.' ext];
% Using imwrite:
% imwrite( I, fName, writePrms )
% If I represents a stack of images, the ith image is written to:
% fNamei = [path name int2str2(i+imagei-1,nDigits) '.' ext];
% If I=[], then imwrite2 will attempt to read images from disk instead.
% If dir spec. by 'path' does not exist, imwrite2 attempts to create it.
%
% mulFlag controls how I is interpreted. If mulFlag==0, then I is
% intrepreted as a single image, otherwise I is interpreted as a stack of
% images, where I(:,:,...,j) represents the jth image (see fevalArrays for
% more info).
%
% If nSplits>1, writes/reads images into/from multiple directories. This is
% useful since certain OS handle very large directories (of say >20K
% images) rather poorly (I'm talking to you Bill). Thus, can take 100K
% images, and write into 5 separate dirs, then read them back in.
%
% USAGE
% I = imwrite2( I, mulFlag, imagei, path, ...
% [name], [ext], [nDigits], [nSplits], [spliti], [varargin] )
%
% INPUTS
% I - image or array or cell of images (if [] reads else writes)
% mulFlag - set to 1 if I represents a stack of images
% imagei - first image number
% path - directory where images are
% name - ['I'] base name of images
% ext - ['png'] extension of image
% nDigits - [5] number of digits for filename index
% nSplits - [1] number of dirs to break data into
% spliti - [0] first split (dir) number
% writePrms - [varargin] parameters to imwrite
%
% OUTPUTS
% I - image or images (read from disk if input I=[])
%
% EXAMPLE
% load images; I=images(:,:,1:10); clear IDXi IDXv t video videos images;
% imwrite2( I(:,:,1), 0, 0, 'rats/', 'rats', 'png', 5 ); % write 1
% imwrite2( I, 1, 0, 'rats/', 'rats', 'png', 5 ); % write 5
% I2 = imwrite2( [], 1, 0, 'rats/', 'rats', 'png', 5 ); % read 5
% I3 = fevalImages(@(x) x,{},'rats/','rats','png',0,4,5); % read 5
%
% EXAMPLE - multiple splits
% load images; I=images(:,:,1:10); clear IDXi IDXv t video videos images;
% imwrite2( I, 1, 0, 'rats', 'rats', 'png', 5, 2, 0 ); % write 10
% I2=imwrite2( [], 1, 0, 'rats', 'rats', 'png', 5, 2, 0 ); % read 10
%
% See also FEVALIMAGES, FEVALARRAYS
%
% Piotr's Computer Vision Matlab Toolbox Version 2.30
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<5 || isempty(name) ); name='I'; end;
if( nargin<6 || isempty(ext) ); ext='png'; end;
if( nargin<7 || isempty(nDigits) ); nDigits=5; end;
if( nargin<8 || isempty(nSplits) ); nSplits=1; end;
if( nargin<9 || isempty(spliti) ); spliti=0; end;
n = size(I,3); if(isempty(I)); n=0; end
% multiple splits -- call imwrite2 recursively
if( nSplits>1 )
write2inp = [ {name, ext, nDigits, 1, 0} varargin ];
if(n>0); nSplits=min(n,nSplits); end;
for s=1:nSplits
pathS = [path int2str2(s-1+spliti,2)];
if( n>0 ) % write
nPerDir = ceil( n / nSplits );
ISplit = I(:,:,1:min(end,nPerDir));
imwrite2( ISplit, nPerDir>1, 0, pathS, write2inp{:} );
if( s~=nSplits ); I = I(:,:,(nPerDir+1):end); end
else % read
ISplit = imwrite2( [], 1, 0, pathS, write2inp{:} );
I = cat(3,I,ISplit);
end
end
return;
end
% if I is empty read from disk
if( n==0 )
I = fevalImages( @(x) x, {}, path, name, ext, imagei, [], nDigits );
return;
end
% Check if path exists (create if not) and add '/' at end if needed
if( ~isempty(path) )
if(~exist(path,'dir'))
warning( ['creating directory: ' path] ); %#ok<WNTAG>
mkdir( path );
end;
if( path(end)~='\' && path(end)~='/' ); path(end+1) = '/'; end
end
% Write images using one of the two subfunctions
params = varargin;
if( mulFlag )
imwrite2m( [], 'init', imagei, path, name, ext, nDigits, params );
if( ~iscell(I) )
fevalArrays( I, @imwrite2m, 'write' );
else
fevalArrays( I, @(x) imwrite2m(x{1},'write') );
end
else
if( ~iscell(I) )
imwrite2s( I, imagei, path, name, ext, nDigits, params );
else
imwrite2s( I{1}, imagei, path, name, ext, nDigits, params );
end;
end
function varargout = imwrite2m( I, type, varargin )
% helper for writing multiple images (passed to fevalArrays)
persistent imagei path name ext nDigits params
switch type
case 'init'
narginchk(8,8);
[nstart, path, name, ext, nDigits, params] = deal(varargin{:});
if(isempty(nstart)); imagei=0; else imagei=nstart; end
varargout = {[]};
case 'write'
narginchk(2,2);
imwrite2s( I, imagei, path, name, ext, nDigits, params );
imagei = imagei+1;
varargout = {[]};
end
function imwrite2s( I, imagei, path, name, ext, nDigits, params )
% helper for writing a single image
fullname = [path name int2str2(imagei,nDigits) '.' ext];
imwrite( I, fullname, params{:} );
|
github
|
P-Chao/acfdetect-master
|
convnFast.m
|
.m
|
acfdetect-master/toolbox/images/convnFast.m
| 9,102 |
utf_8
|
03d05e74bb7ae2ecb0afd0ac115fda39
|
function C = convnFast( A, B, shape )
% Fast convolution, replacement for both conv2 and convn.
%
% See conv2 or convn for more information on convolution in general.
%
% This works as a replacement for both conv2 and convn. Basically,
% performs convolution in either the frequency or spatial domain, depending
% on which it thinks will be faster (see below). In general, if A is much
% bigger then B then spatial convolution will be faster, but if B is of
% similar size to A and both are fairly big (such as in the case of
% correlation), convolution as multiplication in the frequency domain will
% tend to be faster.
%
% The shape flag can take on 1 additional value which is 'smooth'. This
% flag is intended for use with smoothing kernels. The returned matrix C
% is the same size as A with boundary effects handled in a special manner.
% That is instead of A being zero padded before being convolved with B;
% near the boundaries a cropped version of the matrix B is used, and the
% results is scaled by the fraction of the weight found in the cropped
% version of B. In this case each dimension of B must be odd, and all
% elements of B must be positive. There are other restrictions on when
% this flag can be used, and in general it is only useful for smoothing
% kernels. For 2D filtering it does not have much overhead, for 3D it has
% more and for higher dimensions much much more.
%
% For optimal performance some timing constants must be set to choose
% between doing convolution in the spatial and frequency domains, for more
% info see timeConv below.
%
% USAGE
% C = convnFast( A, B, [shape] )
%
% INPUTS
% A - d dimensional input matrix
% B - d dimensional matrix to convolve with A
% shape - ['full'] 'valid', 'full', 'same', or 'smooth'
%
% OUTPUTS
% C - result of convolution
%
% EXAMPLE
%
% See also CONV2, CONVN
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<3 || isempty(shape)); shape='full'; end
if( ~any(strcmp(shape,{'same', 'valid', 'full', 'smooth'})) )
error( 'convnFast: unknown shape flag' ); end
shapeorig = shape;
smoothFlag = (strcmp(shape,'smooth'));
if( smoothFlag ); shape = 'same'; end;
% get dimensions of A and B
ndA = ndims(A); ndB = ndims(B); nd = max(ndA,ndB);
sizA = size(A); sizB = size(B);
if (ndA>ndB); sizB = [sizB ones(1,ndA-ndB)]; end
if (ndA<ndB); sizA = [sizA ones(1,ndB-ndA)]; end
% ERROR CHECK if smoothflag
if( smoothFlag )
if( ~all( mod(sizB,2)==1 ) )
error('If flag==''smooth'' then must have odd sized mask');
end;
if( ~all( B>0 ) )
error('If flag==''smooth'' then mask must have >0 values.');
end;
if( any( (sizB-1)/2>sizA ) )
error('B is more then twice as big as A, cannot use flag==''smooth''');
end;
end
% OPTIMIZATION for 3D conv when B is actually 2D - calls (spatial) conv2
% repeatedly on 2D slices of A. Note that may need to rearange A and B
% first and use recursion. The benefits carry over to convnBound
% (which is faster for 2D arrays).
if( ndA==3 && ndB==3 && (sizB(1)==1 || sizB(2)==1) )
if (sizB(1)==1)
A = permute( A, [2 3 1]); B = permute( B, [2 3 1]);
C = convnFast( A, B, shapeorig );
C = permute( C, [3 1 2] );
elseif (sizB(2)==1)
A = permute( A, [3 1 2]); B = permute( B, [3 1 2]);
C = convnFast( A, B, shapeorig );
C = permute( C, [2 3 1] );
end
return;
elseif( ndA==3 && ndB==2 )
C1 = conv2( A(:,:,1), B, shape );
C = zeros( [size(C1), sizA(3)] ); C(:,:,1) = C1;
for i=2:sizA(3); C(:,:,i) = conv2( A(:,:,i), B, shape ); end
if (smoothFlag)
for i=1:sizA(3)
C(:,:,i) = convnBound(A(:,:,i),B,C(:,:,i),sizA(1:2),sizB(1:2));
end
end
return;
end
% get predicted time of convolution in frequency and spatial domain
% constants taken from timeConv
sizfft = 2.^ceil(real(log2(sizA+sizB-1))); psizfft=prod(sizfft);
frequenPt = 3 * 1e-7 * psizfft * log(psizfft);
if (nd==2)
spatialPt = 5e-9 * sizA(1) * sizA(2) * sizB(1) * sizB(2);
else
spatialPt = 5e-8 * prod(sizA) * prod(sizB);
end
% perform convolution
if ( spatialPt < frequenPt )
if (nd==2)
C = conv2( A, B, shape );
else
C = convn( A, B, shape );
end
else
C = convnFreq( A, B, sizA, sizB, shape );
end;
% now correct boundary effects (if shape=='smooth')
if( ~smoothFlag ); return; end;
C = convnBound( A, B, C, sizA, sizB );
function C = convnBound( A, B, C, sizA, sizB )
% calculate boundary values for C in spatial domain
nd = length(sizA);
radii = (sizB-1)/2;
% flip B appropriately (conv flips B)
for d=1:nd; B = flipdim(B,d); end
% accelerated case for 1D mask B
if( nd==2 && sizB(1)==1 )
sumB=sum(B(:)); r=radii(2); O=ones(1,sizA(1));
for i=1:r
Ai=A(:,1:r+i); Bi=B(r+2-i:end);
C(:,i)=sum(Ai.*Bi(O,:),2)/sum(Bi)*sumB;
Ai=A(:,end+1-r-i:end); Bi=B(1:(end-r+i-1));
C(:,end-i+1)=sum(Ai.*Bi(O,:),2)/sum(Bi)*sumB;
end; return;
elseif( nd==2 && sizB(2)==1 )
sumB=sum(B(:)); r=radii(1); O=ones(1,sizA(2));
for i=1:r
Ai=A(1:r+i,:); Bi=B(r+2-i:end);
C(i,:)=sum(Ai.*Bi(:,O),1)/sum(Bi)*sumB;
Ai=A(end+1-r-i:end,:); Bi=B(1:(end-r+i-1));
C(end-i+1,:)=sum(Ai.*Bi(:,O),1)/sum(Bi)*sumB;
end; return;
end
% get location that need to be updated
inds = {':'}; inds = inds(:,ones(1,nd));
Dind = zeros( sizA );
for d=1:nd
inds1 = inds; inds1{ d } = 1:radii(d);
inds2 = inds; inds2{ d } = sizA(d)-radii(d)+1:sizA(d);
Dind(inds1{:}) = 1; Dind(inds2{:}) = 1;
end
Dind = find( Dind );
Dndx = ind2sub2( sizA, Dind );
nlocs = length(Dind);
% get cuboid dimensions for all the boundary regions
sizeArep = repmat( sizA, [nlocs,1] );
radiiRep = repmat( radii, [nlocs,1] );
Astarts = max(1,Dndx-radiiRep);
Aends = min( sizeArep, Dndx+radiiRep);
Bstarts = Astarts + (1-Dndx+radiiRep);
Bends = Bstarts + (Aends-Astarts);
% now update these locations
vs = zeros( 1, nlocs );
if( nd==2 )
for i=1:nlocs % accelerated for 2D arrays
Apart = A( Astarts(i,1):Aends(i,1), Astarts(i,2):Aends(i,2) );
Bpart = B( Bstarts(i,1):Bends(i,1), Bstarts(i,2):Bends(i,2) );
v = (Apart.*Bpart); vs(i) = sum(v(:)) ./ sum(Bpart(:));
end
elseif( nd==3 ) % accelerated for 3D arrays
for i=1:nlocs
Apart = A( Astarts(i,1):Aends(i,1), Astarts(i,2):Aends(i,2), ...
Astarts(i,3):Aends(i,3) );
Bpart = B( Bstarts(i,1):Bends(i,1), Bstarts(i,2):Bends(i,2), ...
Bstarts(i,3):Bends(i,3) );
za = sum(sum(sum(Apart.*Bpart))); zb=sum(sum(sum(Bpart)));
vs(1,i) = za./zb;
end
else % general case [slow]
extract=cell(1,nd);
for i=1:nlocs
for d=1:nd; extract{d} = Astarts(i,d):Aends(i,d); end
Apart = A( extract{:} );
for d=1:nd; extract{d} = Bstarts(i,d):Bends(i,d); end
Bpart = B( extract{:} );
v = (Apart.*Bpart); vs(i) = sum(v(:)) ./ sum(Bpart(:));
end
end
C( Dind ) = vs * sum(B(:));
function C = convnFreq( A, B, sizA, sizB, shape )
% Convolution as multiplication in the frequency domain
siz = sizA + sizB - 1;
% calculate correlation in frequency domain
Fa = fftn(A,siz);
Fb = fftn(B,siz);
C = ifftn(Fa .* Fb);
% make sure output is real if inputs were both real
if(isreal(A) && isreal(B)); C = real(C); end
% crop to size
if(strcmp(shape,'valid'))
C = arrayToDims( C, max(0,sizA-sizB+1 ) );
elseif(strcmp(shape,'same'))
C = arrayToDims( C, sizA );
elseif(~strcmp(shape,'full'))
error('unknown shape');
end
function K = timeConv() %#ok<DEFNU>
% Function used to calculate constants for prediction of convolution in the
% frequency and spatial domains. Method taken from normxcorr2.m
% May need to reset K's if placing this on a new machine, however, their
% ratio should be about the same..
mintime = 4;
switch 3
case 1 % conv2 [[empirically K = 5e-9]]
% convolution time = K*prod(size(a))*prod(size(b))
siza = 30; sizb = 200;
a = ones(siza); b = ones(sizb);
t1 = cputime; t2 = t1; k = 0;
while (t2-t1)<mintime;
disc = conv2(a,b); k = k + 1; t2 = cputime; %#ok<NASGU>
end
K = (t2-t1)/k/siza^2/sizb^2;
case 2 % convn [[empirically K = 5e-8]]
% convolution time = K*prod(size(a))*prod(size(b))
siza = [10 10 10]; sizb = [30 30 10];
a = ones(siza); b = ones(sizb);
t1 = cputime; t2 = t1; k = 0;
while (t2-t1)<mintime;
disc = convn(a,b); k = k + 1; t2 = cputime; %#ok<NASGU>
end
K = (t2-t1)/k/prod(siza)/prod(sizb);
case 3 % fft (one dimensional) [[empirically K = 1e-7]]
% fft time = K * n log(n) [if n is power of 2]
% Works fastest for powers of 2. (so always zero pad until have
% size of power of 2?). 2 dimensional fft has to apply single
% dimensional fft to each column, and then signle dimensional fft
% to each resulting row. time = K * (mn)log(mn). Likewise for
% highter dimensions. convnFreq requires 3 such ffts.
n = 2^nextpow2(2^15);
vec = complex(rand(n,1),rand(n,1));
t1 = cputime; t2 = t1; k = 0;
while (t2-t1) < mintime;
disc = fft(vec); k = k + 1; t2 = cputime; %#ok<NASGU>
end
K = (t2-t1) / k / n / log(n);
end
|
github
|
P-Chao/acfdetect-master
|
imMlGauss.m
|
.m
|
acfdetect-master/toolbox/images/imMlGauss.m
| 5,674 |
utf_8
|
56ead1b25fbe356f7912993d46468d02
|
function varargout = imMlGauss( G, symmFlag, show )
% Calculates max likelihood params of Gaussian that gave rise to image G.
%
% Suppose G contains an image of a gaussian distribution. One way to
% recover the parameters of the gaussian is to threshold the image, and
% then estimate the mean/covariance based on the coordinates of the
% thresholded points. A better method is to do no thresholding and instead
% use all the coordinates, weighted by their value. This function does the
% latter, except in a very efficient manner since all computations are done
% in parallel over the entire image.
%
% This function works over 2D or 3D images. It makes most sense when G in
% fact contains an image of a single gaussian, but a result will be
% returned regardless. All operations are performed on abs(G) in case it
% contains negative or complex values.
%
% symmFlag is an optional flag that if set to 1 then imMlGauss recovers
% the maximum likelihood symmetric gaussian. That is the variance in each
% direction is equal, and all covariance terms are 0. If symmFlag is set
% to 2 and G is 3D, imMlGauss recovers the ML guassian with equal
% variance in the 1st 2 dimensions (row and col) and all covariance terms
% equal to 0, but a possibly different variance in the 3rd (z or t)
% dimension.
%
% USAGE
% varargout = imMlGauss( G, [symmFlag], [show] )
%
% INPUTS
% G - image of a gaussian (weighted pixels)
% symmFlag - [0] see above
% show - [0] figure to use for optional display
%
% OUTPUTS
% mu - 2 or 3 element vector specifying the mean [row,col,z]
% C - 2x2 or 3x3 covariance matrix [row,col,z]
% GR - image of the recovered gaussian (faster if omitted)
% logl - log likelihood of G given recov. gaussian (faster if omitted)
%
% EXAMPLE - 2D
% R = rotationMatrix( pi/6 ); C=R'*[10^2 0; 0 20^2]*R;
% G = filterGauss( [200, 300], [150,100], C, 0 );
% [mu,C,GR,logl] = imMlGauss( G, 0, 1 );
% mask = maskEllipse( size(G,1), size(G,2), mu, C );
% figure(2); im(mask)
%
% EXAMPLE - 3D
% R = rotationMatrix( [1,1,0], pi/4 );
% C = R'*[5^2 0 0; 0 2^2 0; 0 0 4^2]*R;
% G = filterGauss( [50,50,50], [25,25,25], C, 0 );
% [mu,C,GR,logl] = imMlGauss( G, 0, 1 );
%
% See also GAUSS2ELLIPSE, PLOTGAUSSELLIPSES, MASKELLIPSE
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<2 || isempty(symmFlag) ); symmFlag=0; end;
if( nargin<3 || isempty(show) ); show=0; end;
varargout = cell(1,max(nargout,2));
nd = ndims(G); G = abs(G);
if( nd==2 )
[varargout{:}] = imMlGauss2D( G, symmFlag, show );
elseif( nd==3 )
[varargout{:}] = imMlGauss3D( G, symmFlag, show );
else
error( 'Unsupported dimension for G. G must be 2D or 3D.' );
end
function [mu,C,GR,logl] = imMlGauss2D( G, symmFlag, show )
% to be used throughout calculations
[ gridCols, gridRows ] = meshgrid( 1:size(G,2), 1:size(G,1) );
sumG = sum(G(:)); if(sumG==0); sumG=1; end;
% recover mean
muCol = (gridCols .* G); muCol = sum( muCol(:) ) / sumG;
muRow = (gridRows .* G); muRow = sum( muRow(:) ) / sumG;
mu = [muRow, muCol];
% recover sigma
distCols = (gridCols - muCol);
distRows = (gridRows - muRow);
if( symmFlag==0 )
Ccc = (distCols .^ 2) .* G; Ccc = sum(Ccc(:)) / sumG;
Crr = (distRows .^ 2) .* G; Crr = sum(Crr(:)) / sumG;
Crc = (distCols .* distRows) .* G; Crc = sum(Crc(:)) / sumG;
C = [Crr Crc; Crc Ccc];
elseif( symmFlag==1 )
sigSq = (distCols.^2 + distRows.^2) .* G;
sigSq = 1/2 * sum(sigSq(:)) / sumG;
C = sigSq*eye(2);
else
error(['Illegal value for symmFlag: ' num2str(symmFlag)]);
end
% get the log likelihood of the data
if (nargout>2)
GR = filterGauss( size(G), mu, C );
probs = GR; probs( probs<realmin ) = realmin;
logl = G .* log( probs );
logl = sum( logl(:) );
end
% plot ellipses
if (show)
figure(show); im(G);
hold('on'); plotGaussEllipses( mu, C, 2 ); hold('off');
end
function [mu,C,GR,logl] = imMlGauss3D( G, symmFlag, show )
% to be used throughout calculations
[gridCols,gridRows,gridZs]=meshgrid(1:size(G,2),1:size(G,1),1:size(G,3));
sumG = sum(G(:));
% recover mean
muCol = (gridCols .* G); muCol = sum( muCol(:) ) / sumG;
muRow = (gridRows .* G); muRow = sum( muRow(:) ) / sumG;
muZ = (gridZs .* G); muZ = sum( muZ(:) ) / sumG;
mu = [muRow, muCol, muZ];
% recover C
distCols = (gridCols - muCol);
distRows = (gridRows - muRow);
distZs = (gridZs - muZ);
if( symmFlag==0 )
distColsG = distCols .* G; distRowsG = distRows .* G;
Ccc = distCols .* distColsG; Ccc = sum(Ccc(:));
Crc = distRows .* distColsG; Crc = sum(Crc(:));
Czc = distZs .* distColsG; Czc = sum(Czc(:));
Crr = distRows .* distRowsG; Crr = sum(Crr(:));
Czr = distZs .* distRowsG; Czr = sum(Czr(:));
Czz = distZs .* distZs .* G; Czz = sum(Czz(:));
C = [Crr Crc Czr; Crc Ccc Czc; Czr Czc Czz] / sumG;
elseif( symmFlag==1 )
sigSq = (distCols.^2 + distRows.^2 + distZs .^ 2) .* G;
sigSq = 1/3 * sum(sigSq(:));
C = [sigSq 0 0; 0 sigSq 0; 0 0 sigSq] / sumG;
elseif( symmFlag==2 )
sigSq = (distCols.^2 + distRows.^2) .* G; sigSq = 1/2 * sum(sigSq(:));
tauSq = (distZs .^ 2) .* G; tauSq = sum(tauSq(:));
C = [sigSq 0 0; 0 sigSq 0; 0 0 tauSq] / sumG;
else
error(['Illegal value for symmFlag: ' num2str(symmFlag)])
end
% get the log likelihood of the data
if( nargout>2 || (show) )
GR = filterGauss( size(G), mu, C );
probs = GR; probs( probs<realmin ) = realmin;
logl = G .* log( probs );
logl = sum( logl(:) );
end
% plot G and GR
if( show )
figure(show); montage2(G);
figure(show+1); montage2(GR);
end
|
github
|
P-Chao/acfdetect-master
|
montage2.m
|
.m
|
acfdetect-master/toolbox/images/montage2.m
| 7,484 |
utf_8
|
828f57d7b1f67d36eeb6056f06568ebf
|
function varargout = montage2( IS, prm )
% Used to display collections of images and videos.
%
% Improved version of montage, with more control over display.
% NOTE: Can convert between MxNxT and MxNx3xT image stack via:
% I = repmat( I, [1,1,1,3] ); I = permute(I, [1,2,4,3] );
%
% USAGE
% varargout = montage2( IS, [prm] )
%
% INPUTS
% IS - MxNxTxR or MxNxCxTxR, where C==1 or C==3, and R may be 1
% or cell vector of MxNxT or MxNxCxT matrices
% prm
% .showLines - [1] whether to show lines separating the various frames
% .extraInfo - [0] if 1 then a colorbar is shown as well as impixelinfo
% .cLim - [] cLim = [clow chigh] optional scaling of data
% .mm - [] #images/col per montage
% .nn - [] #images/row per montage
% .labels - [] cell array of labels (strings) (T if R==1 else R)
% .perRow - [0] only if R>1 and not cell, alternative displays method
% .hasChn - [0] if true assumes IS is MxNxCxTxR else MxNxTxR
% .padAmt - [0] only if perRow, amount to pad when in row mode
% .padEl - [] pad element, defaults to min value in IS
%
% OUTPUTS
% h - image handle
% m - #images/col
% nn - #images/row
%
% EXAMPLE - [3D] show a montage of images
% load( 'images.mat' ); clf; montage2( images );
%
% EXAMPLE - [3D] show a montage of images with labels
% load( 'images.mat' );
% for i=1:50; labels{i}=['I-' int2str2(i,2)]; end
% prm = struct('extraInfo',1,'perRow',0,'labels',{labels});
% clf; montage2( images(:,:,1:50), prm );
%
% EXAMPLE - [3D] show a montage of images with color boundaries
% load( 'images.mat' );
% I3 = repmat(permute(images,[1 2 4 3]),[1,1,3,1]); % add color chnls
% prm = struct('padAmt',4,'padEl',[50 180 50],'hasChn',1,'showLines',0);
% clf; montage2( I3(:,:,:,1:48), prm )
%
% EXAMPLE - [4D] show a montage of several groups of images
% for i=1:25; labels{i}=['V-' int2str2(i,2)]; end
% prm = struct('labels',{labels});
% load( 'images.mat' ); clf; montage2( videos(:,:,:,1:25), prm );
%
% EXAMPLE - [4D] show using 'row' format
% load( 'images.mat' );
% prm = struct('perRow',1, 'padAmt',6, 'padEl',255 );
% figure(1); clf; montage2( videos(:,:,:,1:10), prm );
%
% See also MONTAGE, PLAYMOVIE, FILMSTRIP
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<2 ); prm=struct(); end
varargout = cell(1,nargout);
%%% get parameters (set defaults)
dfs = {'showLines',1, 'extraInfo',0, 'cLim',[], 'mm',[], 'nn',[],...
'labels',[], 'perRow',false, 'padAmt',0, 'padEl',[], 'hasChn',false };
prm = getPrmDflt( prm, dfs );
extraInfo=prm.extraInfo; labels=prm.labels; perRow=prm.perRow;
hasChn=prm.hasChn;
%%% If IS is not a cell convert to MxNxCxTxR array
if( iscell(IS) && numel(IS)==1 ); IS=IS{1}; end;
if( ~iscell(IS) && ~ismatrix(IS) )
siz=size(IS);
if( ~hasChn );
IS=reshape(IS,[siz(1:2),1,siz(3:end)]);
prm.hasChn = true;
end;
if(ndims(IS)>5); error('montage2: input too large'); end;
end
if( ~iscell(IS) && size(IS,5)==1 ) %%% special case call subMontage once
[varargout{:}] = subMontage(IS,prm);
title(inputname(1));
elseif( perRow ) %%% display each montage in row format
if(iscell(IS)); error('montage2: IS cannot be a cell if perRow'); end;
siz = size(IS);
IS=reshape(permute(IS,[1 2 4 3 5]),siz(1),[],siz(3),siz(5));
if( nargout ); varargout{1}=IS; end
prm.perRow = false; prm.hasChn=true;
[varargout{2:end}] = subMontage( IS, prm );
title(inputname(1));
else %%% display each montage using subMontage
% convert to cell array
if( iscell(IS) )
nMontages = numel(IS);
else
nMontages = size(IS,5);
IS = squeeze(mat2cell2( IS, [1 1 1 1 nMontages] ));
end
% draw each montage
clf;
nn = ceil( sqrt(nMontages) ); mm = ceil(nMontages/nn);
for i=1:nMontages
subplot(mm,nn,i);
prmSub=prm; prmSub.extraInfo=0; prmSub.labels=[];
if( ~isempty(IS{i}) )
subMontage( IS{i}, prmSub );
else
set(gca,'XTick',[]); set(gca,'YTick',[]);
end
if(~isempty(labels)); title(labels{i}); end
end
if( extraInfo ); impixelinfo; end;
end
function varargout = subMontage( IS, prm )
% this function is a generalized version of Matlab's montage.m
% get parameters (set defaults)
dfs = {'showLines',1, 'extraInfo',0, 'cLim',[], 'mm',[], 'nn',[], ...
'labels',[], 'perRow',false, 'hasChn',false, 'padAmt',0, 'padEl',[] };
prm = getPrmDflt( prm, dfs );
showLines=prm.showLines; extraInfo=prm.extraInfo; cLim=prm.cLim;
mm=prm.mm; nn=prm.nn; labels=prm.labels; hasChn=prm.hasChn;
padAmt=prm.padAmt; padEl=prm.padEl;
if( prm.perRow ); mm=1; end;
% get/test image format info and parameters
if( hasChn )
if( ndims(IS)>4 || ~any(size(IS,3)==[1 3]) )
error('montage2: unsupported dimension of IS'); end
else
if( ndims(IS)>3 );
error('montage2: unsupported dimension of IS'); end
IS = permute(IS, [1 2 4 3] );
end
siz = size(IS); nCh=size(IS,3); nIm = size(IS,4); sizPad=siz+padAmt;
if( ~isempty(labels) && nIm~=length(labels) )
error('montage2: incorrect number of labels');
end
% set up the padEl correctly (must have same type / nCh as IS)
if(isempty(padEl))
if(isempty(cLim)); padEl=min(IS(:)); else padEl=cLim(1); end; end
if(length(padEl)==1); padEl=repmat(padEl,[1 nCh]); end;
if(length(padEl)~=nCh); error( 'invalid padEl' ); end;
padEl = feval( class(IS), padEl );
padEl = reshape( padEl, 1, 1, [] );
padAmt = floor(padAmt/2 + .5)*2;
% get layout of images (mm=#images/row, nn=#images/col)
if( isempty(mm) || isempty(nn))
if( isempty(mm) && isempty(nn))
nn = min( ceil(sqrt(sizPad(1)*nIm/sizPad(2))), nIm );
mm = ceil( nIm/nn );
elseif( isempty(mm) )
nn = min( nn, nIm );
mm = ceil(nIm/nn);
else
mm = min( mm, nIm );
nn = ceil(nIm/mm);
end
% often can shrink dimension further
while((mm-1)*nn>=nIm); mm=mm-1; end;
while((nn-1)*mm>=nIm); nn=nn-1; end;
end
% Calculate I (M*mm x N*nn size image)
I = repmat(padEl, [mm*sizPad(1), nn*sizPad(2), 1]);
rows = 1:siz(1); cols = 1:siz(2);
for k=1:nIm
rowsK = rows + floor((k-1)/nn)*sizPad(1)+padAmt/2;
colsK = cols + mod(k-1,nn)*sizPad(2)+padAmt/2;
I(rowsK,colsK,:) = IS(:,:,:,k);
end
% display I
if( ~isempty(cLim)); h=imagesc(I,cLim); else h=imagesc(I); end
colormap(gray); axis('image');
if( extraInfo )
colorbar; impixelinfo;
else
set(gca,'Visible','off')
end
% draw lines separating frames
if( showLines )
montageWd = nn * sizPad(2) + .5;
montageHt = mm * sizPad(1) + .5;
for i=1:mm-1
ht = i*sizPad(1) +.5; line([.5,montageWd],[ht,ht]);
end
for i=1:nn-1
wd = i*sizPad(2) +.5; line([wd,wd],[.5,montageHt]);
end
end
% plot text labels
textalign = { 'VerticalAlignment','bottom','HorizontalAlignment','left'};
if( ~isempty(labels) )
count=1;
for i=1:mm;
for j=1:nn
if( count<=nIm )
rStr = i*sizPad(1)-padAmt/2;
cStr =(j-1+.1)*sizPad(2)+padAmt/2;
text(cStr,rStr,labels{count},'color','r',textalign{:});
count = count+1;
end
end
end
end
% cross out unused frames
[nns,mms] = ind2sub( [nn,mm], nIm+1 );
for i=mms-1:mm-1
for j=nns-1:nn-1,
rStr = i*sizPad(1)+.5+padAmt/2; rs = [rStr,rStr+siz(1)];
cStr = j*sizPad(2)+.5+padAmt/2; cs = [cStr,cStr+siz(2)];
line( cs, rs ); line( fliplr(cs), rs );
end
end
% optional output
if( nargout>0 ); varargout={h,mm,nn}; end
|
github
|
P-Chao/acfdetect-master
|
jitterImage.m
|
.m
|
acfdetect-master/toolbox/images/jitterImage.m
| 5,252 |
utf_8
|
3310f8412af00fd504c6f94b8c48992c
|
function IJ = jitterImage( I, varargin )
% Creates multiple, slightly jittered versions of an image.
%
% Takes an image I, and generates a number of images that are copies of the
% original image with slight translation, rotation and scaling applied. If
% the input image is actually an MxNxK stack of images then applies op to
% each image. Rotations and translations are specified by giving a range
% and a max value for each. For example, if mPhi=10 and nPhi=5, then the
% actual rotations applied are linspace(-mPhi,mPhi,nPhi)=[-10 -5 0 5 10].
% Likewise if mTrn=3 and nTrn=3 then the translations are [-3 0 3]. Each
% tran is applied in the x direction as well as the y direction. Each
% combination of rotation, tran in x, tran in y and scale is used (for
% example phi=5, transx=-3, transy=0), so the total number of images
% generated is R=nTrn*nTrn*nPhi*nScl. Finally, jsiz controls the size of
% the cropped images. If jsiz gives a size that's sufficiently smaller than
% I then all data in the the final set will come from I. Otherwise, I must
% be padded first (by calling padarray with the 'replicate' option).
%
% USAGE
% function IJ = jitterImage( I, varargin )
%
% INPUTS
% I - image (MxN) or set of K images (MxNxK)
% varargin - additional params (struct or name/value pairs)
% .maxn - [inf] maximum jitters to generate (prior to flip)
% .nPhi - [0] number of rotations
% .mPhi - [0] max value for rotation
% .nTrn - [0] number of translations
% .mTrn - [0] max value for translation
% .flip - [0] if true then also adds reflection of each image
% .jsiz - [] Final size of each image in IJ
% .scls - [1 1] nScl x 2 array of vert/horiz scalings
% .method - ['linear'] interpolation method for imtransform2
% .hasChn - [0] if true I is MxNxC or MxNxCxK
%
% OUTPUTS
% IJ - MxNxKxR or MxNxCxKxR set of images, R=(nTrn^2*nPhi*nScl)
%
% EXAMPLE
% load trees; I=imresize(ind2gray(X,map),[41 41]); clear X caption map
% % creates 10 (of 7^2*2) images of slight trans
% IJ = jitterImage(I,'nTrn',7,'mTrn',3,'maxn',10); montage2(IJ)
% % creates 5 images of slight rotations w reflection
% IJ = jitterImage(I,'nPhi',5,'mPhi',25,'flip',1); montage2(IJ)
% % creates 45 images of both rot and slight trans
% IJ = jitterImage(I,'nPhi',5,'mPhi',10,'nTrn',3,'mTrn',2); montage2(IJ)
% % additionally create multiple scaled versions
% IJ = jitterImage(I,'scls',[1 1; 2 1; 1 2; 2 2]); montage2(IJ)
% % example on color image (5 images of slight rotations)
% I=imResample(imread('peppers.png'),[100,100]);
% IJ=jitterImage(I,'nPhi',5,'mPhi',25,'hasChn',1);
% montage2(uint8(IJ),{'hasChn',1})
%
% See also imtransform2
%
% Piotr's Computer Vision Matlab Toolbox Version 2.65
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get additional parameters
siz=size(I);
dfs={'maxn',inf, 'nPhi',0, 'mPhi',0, 'nTrn',0, 'mTrn',0, 'flip',0, ...
'jsiz',siz(1:2), 'scls',[1 1], 'method','linear', 'hasChn',0};
[maxn,nPhi,mPhi,nTrn,mTrn,flip,jsiz,scls,method,hasChn] = ...
getPrmDflt(varargin,dfs,1);
if(nPhi<1), mPhi=0; nPhi=1; end; if(nTrn<1), mTrn=0; nTrn=1; end
% I must be big enough to support given ops so grow I if necessary
trn=linspace(-mTrn,mTrn,nTrn); [dX,dY]=meshgrid(trn,trn);
dY=dY(:)'; dX=dX(:)'; phis=linspace(-mPhi,mPhi,nPhi)/180*pi;
siz1=jsiz+2*max(dX); if(nPhi>1), siz1=sqrt(2)*siz1+1; end
siz1=[siz1(1)*max(scls(:,1)) siz1(2)*max(scls(:,2))];
pad=(siz1-siz(1:2))/2; pad=max([ceil(pad) 0],0);
if(any(pad>0)), I=padarray(I,pad,'replicate','both'); end
% jitter each image
nScl=size(scls,1); nTrn=length(dX); nPhi=length(phis);
nOps=min(maxn,nTrn*nPhi*nScl); if(flip), nOps=nOps*2; end
if(hasChn), nd=3; jsiz=[jsiz siz(3)]; else nd=2; end
n=size(I,nd+1); IJ=zeros([jsiz nOps n],class(I));
is=repmat({':'},1,nd); prm={method,maxn,jsiz,phis,dX,dY,scls,flip};
for i=1:n, IJ(is{:},:,i)=jitterImage1(I(is{:},i),prm{:}); end
end
function IJ = jitterImage1( I,method,maxn,jsiz,phis,dX,dY,scls,flip )
% generate list of transformations (HS)
nScl=size(scls,1); nTrn=length(dX); nPhi=length(phis);
nOps=nTrn*nPhi*nScl; HS=zeros(3,3,nOps); k=0;
for s=1:nScl, S=[scls(s,1) 0; 0 scls(s,2)];
for p=1:nPhi, R=rotationMatrix(phis(p));
for t=1:nTrn, k=k+1; HS(:,:,k)=[S*R [dX(t); dY(t)]; 0 0 1]; end
end
end
% apply each transformation HS(:,:,i) to image I
if(nOps>maxn), HS=HS(:,:,randSample(nOps,maxn)); nOps=maxn; end
siz=size(I); nd=ndims(I); nCh=size(I,3);
I1=I; p=(siz-jsiz)/2; IJ=zeros([jsiz nOps],class(I));
for i=1:nOps, H=HS(:,:,i); d=H(1:2,3)';
if( all(all(H(1:2,1:2)==eye(2))) && all(mod(d,1)==0) )
% handle transformation that's just an integer translation
s=max(1-d,1); e=min(siz(1:2)-d,siz(1:2)); s1=2-min(1-d,1); e1=e-s+s1;
I1(s1(1):e1(1),s1(2):e1(2),:) = I(s(1):e(1),s(2):e(2),:);
else % handle general transformations
for j=1:nCh, I1(:,:,j)=imtransform2(I(:,:,j),H,'method',method); end
end
% crop and store result
I2 = I1(p(1)+1:end-p(1),p(2)+1:end-p(2),:);
if(nd==2), IJ(:,:,i)=I2; else IJ(:,:,:,i)=I2; end
end
% finally flip each resulting image
if(flip), IJ=cat(nd+1,IJ,IJ(:,end:-1:1,:,:)); end
end
|
github
|
P-Chao/acfdetect-master
|
movieToImages.m
|
.m
|
acfdetect-master/toolbox/images/movieToImages.m
| 889 |
utf_8
|
28c71798642af276951ee27e2d332540
|
function I = movieToImages( M )
% Creates a stack of images from a matlab movie M.
%
% Repeatedly calls frame2im. Useful for playback with playMovie.
%
% USAGE
% I = movieToImages( M )
%
% INPUTS
% M - a matlab movie
%
% OUTPUTS
% I - MxNxT array (of images)
%
% EXAMPLE
% load( 'images.mat' ); [X,map]=gray2ind(video(:,:,1));
% M = fevalArrays( video, @(x) im2frame(gray2ind(x),map) );
% I = movieToImages(M); playMovie(I);
%
% See also PLAYMOVIE
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
I = fevalArrays( M, @frame2Ii );
function I = frame2Ii( F )
[I,map] = frame2im( F );
if( isempty(map) )
if( size(I,3)==3 )
classname = class( I );
I = sum(I,3)/3;
I = feval( classname, I );
end
else
I = ind2gray( I, map );
end
|
github
|
P-Chao/acfdetect-master
|
toolboxUpdateHeader.m
|
.m
|
acfdetect-master/toolbox/external/toolboxUpdateHeader.m
| 2,255 |
utf_8
|
7a5b75e586be48da97c84d20b59887ff
|
function toolboxUpdateHeader
% Update the headers of all the files.
%
% USAGE
% toolboxUpdateHeader
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.40
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
header={
'Piotr''s Computer Vision Matlab Toolbox Version 3.40'; ...
'Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]'; ...
'Licensed under the Simplified BSD License [see external/bsd.txt]'};
root=fileparts(fileparts(mfilename('fullpath')));
ds=dir(root); ds=ds([ds.isdir]); ds={ds.name};
ds=ds(3:end); ds=setdiff(ds,{'.git','doc'});
subds = { '/', '/private/' };
exts = {'m','c','cpp','h','hpp'};
omit = {'Contents.m','fibheap.h','fibheap.cpp'};
for i=1:length(ds)
for j=1:length(subds)
for k=1:length(exts)
d=[root '/' ds{i} subds{j}];
if(k==1), comment='%'; else comment='*'; end
fs=dir([d '*.' exts{k}]); fs={fs.name}; fs=setdiff(fs,omit);
n=length(fs); for f=1:n, fs{f}=[d fs{f}]; end
for f=1:n, toolboxUpdateHeader1(fs{f},header,comment); end
end
end
end
end
function toolboxUpdateHeader1( fName, header, comment )
% set appropriate comment symbol in header
m=length(header); for i=1:m, header{i}=[comment ' ' header{i}]; end
% read in file and find header
disp(fName); lines=readFile(fName);
loc = find(not(cellfun('isempty',strfind(lines,header{1}(1:40)))));
if(isempty(loc)), error('NO HEADER: %s\n',fName); end; loc=loc(1);
% check that header is properly formed, return if up to date
for i=1:m; assert(isequal(lines{loc+i-1}(1:10),header{i}(1:10))); end
if(~any(strfind(lines{loc},'NEW'))); return; end
% update copyright year and overwrite rest of header
lines{loc+1}(13:16)=header{2}(13:16);
for i=[1 3:m]; lines{loc+i-1}=header{i}; end
writeFile( fName, lines );
end
function lines = readFile( fName )
fid = fopen( fName, 'rt' ); assert(fid~=-1);
lines=cell(10000,1); n=0;
while( 1 )
n=n+1; lines{n}=fgetl(fid);
if( ~ischar(lines{n}) ), break; end
end
fclose(fid); n=n-1; lines=lines(1:n);
end
function writeFile( fName, lines )
fid = fopen( fName, 'w' );
for i=1:length(lines); fprintf( fid, '%s\n', lines{i} ); end
fclose(fid);
end
|
github
|
P-Chao/acfdetect-master
|
toolboxGenDoc.m
|
.m
|
acfdetect-master/toolbox/external/toolboxGenDoc.m
| 3,639 |
utf_8
|
4c21fb34fa9b6002a1a98a28ab40c270
|
function toolboxGenDoc
% Generate documentation, must run from dir toolbox.
%
% 1) Make sure to update and run toolboxUpdateHeader.m
% 2) Update history.txt appropriately, including w current version
% 3) Update overview.html file with the version/date/link to zip:
% edit external/m2html/templates/frame-piotr/overview.html
%
% USAGE
% toolboxGenDoc
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.40
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% Requires external/m2html to be in path.
cd(fileparts(mfilename('fullpath'))); cd('../');
addpath([pwd '/external/m2html']);
% delete temporary files that should not be part of release
fs={'pngreadc','pngwritec','rjpg8c','wjpg8c','png'};
for i=1:length(fs), delete(['videos/private/' fs{i} '.*']); end
delete('detector/models/*Dets.txt');
% delete old doc and run m2html
if(exist('doc/','dir')), rmdir('doc/','s'); end
dirs={'channels','classify','detector',...
'images','filters','matlab','videos'};
m2html('mfiles',dirs,'htmldir','doc','recursive','on','source','off',...
'template','frame-piotr','index','menu','global','on');
% copy custom menu.html and history file
sDir='external/m2html/templates/';
copyfile([sDir 'menu-for-frame-piotr.html'],'doc/menu.html');
copyfile('external/history.txt','doc/history.txt');
% remove links to private/ in the menu.html files and remove private/ dirs
for i=1:length(dirs)
name = ['doc/' dirs{i} '/menu.html'];
fid=fopen(name,'r'); c=fread(fid,'*char')'; fclose(fid);
c=regexprep(c,'<li>([^<]*[<]?[^<]*)private([^<]*[<]?[^<]*)</li>','');
fid=fopen(name,'w'); fwrite(fid,c); fclose(fid);
name = ['doc/' dirs{i} '/private/'];
if(exist(name,'dir')), rmdir(name,'s'); end
end
% postprocess each html file
for d=1:length(dirs)
fs=dir(['doc/' dirs{d} '/*.html']); fs={fs.name};
for j=1:length(fs), postProcess(['doc/' dirs{d} '/' fs{j}]); end
end
end
function postProcess( fName )
lines=readFile(fName);
assert(strcmp(lines{end-1},'</body>') && strcmp(lines{end},'</html>'));
% remove m2html datestamp (if present)
assert(strcmp(lines{end-2}(1:22),'<hr><address>Generated'));
if( strcmp(lines{end-2}(1:25),'<hr><address>Generated on'))
lines{end-2}=regexprep(lines{end-2}, ...
'<hr><address>Generated on .* by','<hr><address>Generated by');
end
% remove crossreference information
is=find(strcmp('<!-- crossreference -->',lines));
if(~isempty(is)), assert(length(is)==2); lines(is(1):is(2))=[]; end
% insert Google Analytics snippet to end of file
ga={ '';
'<!-- Start of Google Analytics Code -->';
'<script type="text/javascript">';
'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");';
'document.write(unescape("%3Cscript src=''" + gaJsHost + "google-analytics.com/ga.js'' type=''text/javascript''%3E%3C/script%3E"));';
'</script>';
'<script type="text/javascript">';
'var pageTracker = _gat._getTracker("UA-4884268-1");';
'pageTracker._initData();';
'pageTracker._trackPageview();';
'</script>';
'<!-- end of Google Analytics Code -->';
'' };
lines = [lines(1:end-3); ga; lines(end-2:end)];
% write file
writeFile( fName, lines );
end
function lines = readFile( fName )
fid = fopen( fName, 'rt' ); assert(fid~=-1);
lines=cell(10000,1); n=0;
while( 1 )
n=n+1; lines{n}=fgetl(fid);
if( ~ischar(lines{n}) ), break; end
end
fclose(fid); n=n-1; lines=lines(1:n);
end
function writeFile( fName, lines )
fid = fopen( fName, 'w' );
for i=1:length(lines); fprintf( fid, '%s\r\n', lines{i} ); end
fclose(fid);
end
|
github
|
P-Chao/acfdetect-master
|
toolboxHeader.m
|
.m
|
acfdetect-master/toolbox/external/toolboxHeader.m
| 2,391 |
utf_8
|
30c24a94fb54ca82622719adcab17903
|
function [y1,y2] = toolboxHeader( x1, x2, x3, prm )
% One line description of function (will appear in file summary).
%
% General commments explaining purpose of function [width is 75
% characters]. There may be multiple paragraphs. In special cases some or
% all of these guidelines may need to be broken.
%
% Next come a series of sections, including USAGE, INPUTS, OUTPUTS,
% EXAMPLE, and "See also". Each of these fields should always appear, even
% if nothing follows (for example no inputs). USAGE should usually be a
% copy of the first line of code (which begins with "function"), minus the
% word "function". Optional parameters are surrounded by brackets.
% Occasionally, there may be more than 1 distinct usage, in this case list
% additional usages. In general try to avoid this. INPUTS/OUTPUTS are
% self explanatory, however if there are multiple usages can be subdivided
% as below. EXAMPLE should list 1 or more useful examples. Main comment
% should all appear as one contiguous block. Next a blank comment line,
% and then a short comment that includes the toolbox version.
%
% USAGE
% xsum = toolboxHeader( x1, x2, [x3], [prm] )
% [xprod, xdiff] = toolboxHeader( x1, x2, [x3], [prm] )
%
% INPUTS
% x1 - descr. of variable 1,
% x2 - descr. of variable 2, keep spacing like this
% if descr. spans multiple lines do this
% x3 - [0] indicates an optional variable, put def val in []
% prm - [] param struct
% .p1 parameter 1 descr
% .p2 parameter 2 descr
%
% OUTPUTS - and whatever after the dash
% xsum - sum of xs
%
% OUTPUTS - usage 2
% xprod - prod of xs
% xdiff - negative sum of xs
%
% EXAMPLE - and whatever after the dash
% y = toolboxHeader( 1, 2 );
%
% EXAMPLE - example 2
% y = toolboxHeader( 2, 3 );
%
% See also GETPRMDFLT
%
% Piotr's Computer Vision Matlab Toolbox Version 2.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% optional arguments x3 and prm
if( nargin<3 || isempty(x3) ), x3=0; end
if( nargin<4 || isempty(prm) ), prm=[]; end %#ok<NASGU>
% indents should be set with Matlab's "smart indent" (with 2 spaces)
if( nargout==1 )
y1 = add(x1,x2) + x3;
else
y1 = x1 * x2 * x3;
y2 = - x1 - x2 - x3;
end
function s=add(x,y)
% optional sub function comment
s=x+y;
|
github
|
P-Chao/acfdetect-master
|
mdot.m
|
.m
|
acfdetect-master/toolbox/external/m2html/mdot.m
| 2,516 |
utf_8
|
34a14428c433e118d1810e23f5a6caf5
|
function mdot(mmat, dotfile,f)
%MDOT - Export a dependency graph into DOT language
% MDOT(MMAT, DOTFILE) loads a .mat file generated by M2HTML using option
% ('save','on') and writes an ascii file using the DOT language that can
% be drawn using <dot> or <neato> .
% MDOT(MMAT, DOTFILE,F) builds the graph containing M-file F and its
% neighbors only.
% See the following page for more details:
% <http://www.graphviz.org/>
%
% Example:
% mdot('m2html.mat','m2html.dot');
% !dot -Tps m2html.dot -o m2html.ps
% !neato -Tps m2html.dot -o m2html.ps
%
% See also M2HTML
% Copyright (C) 2004 Guillaume Flandin <[email protected]>
% $Revision: 1.1 $Date: 2004/05/05 17:14:09 $
error(nargchk(2,3,nargin));
if ischar(mmat)
load(mmat);
elseif iscell(mmat)
hrefs = mmat{1};
names = mmat{2};
options = mmat{3};
if nargin == 3, mfiles = mmat{4}; end
mdirs = cell(size(names));
[mdirs{:}] = deal('');
if nargin == 2 & length(mmat) > 3,
mdirs = mmat{4};
end;
else
error('[mdot] Invalid argument: mmat.');
end
fid = fopen(dotfile,'wt');
if fid == -1, error(sprintf('[mdot] Cannot open %s.',dotfile)); end
fprintf(fid,'/* Created by mdot for Matlab */\n');
fprintf(fid,'digraph m2html {\n');
% if 'names' contains '.' then they should be surrounded by '"'
if nargin == 2
for i=1:size(hrefs,1)
n = find(hrefs(i,:) == 1);
m{i} = n;
for j=1:length(n)
fprintf(fid,[' ' names{i} ' -> ' names{n(j)} ';\n']);
end
end
%m = unique([m{:}]);
fprintf(fid,'\n');
for i=1:size(hrefs,1)
fprintf(fid,[' ' names{i} ' [URL="' ...
fullurl(mdirs{i},[names{i} options.extension]) '"];\n']);
end
else
i = find(strcmp(f,mfiles));
if length(i) ~= 1
error(sprintf('[mdot] Cannot find %s.',f));
end
n = find(hrefs(i,:) == 1);
for j=1:length(n)
fprintf(fid,[' ' names{i} ' -> ' names{n(j)} ';\n']);
end
m = find(hrefs(:,i) == 1);
for j=1:length(m)
if n(j) ~= i
fprintf(fid,[' ' names{m(j)} ' -> ' names{i} ';\n']);
end
end
n = unique([n(:)' m(:)']);
fprintf(fid,'\n');
for i=1:length(n)
fprintf(fid,[' ' names{n(i)} ' [URL="' fullurl(mdirs{i}, ...
[names{n(i)} options.extension]) '"];\n']);
end
end
fprintf(fid,'}');
fid = fclose(fid);
if fid == -1, error(sprintf('[mdot] Cannot close %s.',dotfile)); end
%===========================================================================
function f = fullurl(varargin)
%- Build full url from parts (using '/' and not filesep)
f = strrep(fullfile(varargin{:}),'\','/');
|
github
|
P-Chao/acfdetect-master
|
m2html.m
|
.m
|
acfdetect-master/toolbox/external/m2html/m2html.m
| 49,063 |
utf_8
|
472047b4c36a4f8b162012840e31b59b
|
function m2html(varargin)
%M2HTML - Documentation Generator for Matlab M-files and Toolboxes in HTML
% M2HTML by itself generates an HTML documentation of the Matlab M-files found
% in the direct subdirectories of the current directory. HTML files are
% written in a 'doc' directory (created if necessary). All the others options
% are set to default (in brackets in the following).
% M2HTML('PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2,...)
% sets multiple option values. The list of option names and default values is:
% o mFiles - Cell array of strings or character array containing the
% list of M-files and/or directories of M-files for which an HTML
% documentation will be built (use relative paths without backtracking).
% Launch M2HTML one directory above the directory your wanting to
% generate documentation for [ <all direct subdirectories> ]
% o htmlDir - Top level directory for generated HTML files [ 'doc' ]
% o recursive - Process subdirectories recursively [ on | {off} ]
% o source - Include Matlab source code in the generated documentation
% [ {on} | off ]
% o download - Add a link to download each M-file separately [ on | {off} ]
% o syntaxHighlighting - Source Code Syntax Highlighting [ {on} | off ]
% o tabs - Replace '\t' (horizontal tab) in source code by n white space
% characters [ 0 ... {4} ... n ]
% o globalHypertextLinks - Hypertext links among separate Matlab
% directories [ on | {off} ]
% o todo - Create a TODO list in each directory summarizing all the
% '% TODO %' lines found in Matlab code [ on | {off}]
% o graph - Compute a dependency graph using GraphViz [ on | {off}]
% 'dot' required, see <http://www.graphviz.org/>
% o indexFile - Basename of the HTML index file [ 'index' ]
% o extension - Extension of generated HTML files [ '.html' ]
% o template - HTML template name to use [ {'blue'} | 'frame' | ... ]
% o search - Add a PHP search engine [ on | {off}] - beta version!
% o save - Save current state after M-files parsing in 'm2html.mat'
% in directory htmlDir [ on | {off}]
% o load - Load a previously saved '.mat' M2HTML state to generate HTML
% files once again with possibly other options [ <none> ]
% o verbose - Verbose mode [ {on} | off ]
%
% For more information, please read the M2HTML tutorial and FAQ at:
% <http://www.artefact.tk/software/matlab/m2html/>
%
% Examples:
% >> m2html('mfiles','matlab', 'htmldir','doc');
% >> m2html('mfiles',{'matlab/signal' 'matlab/image'}, 'htmldir','doc');
% >> m2html('mfiles','matlab', 'htmldir','doc', 'recursive','on');
% >> m2html('mfiles','mytoolbox', 'htmldir','doc', 'source','off');
% >> m2html('mfiles','matlab', 'htmldir','doc', 'global','on');
% >> m2html( ... , 'template','frame', 'index','menu');
%
% See also MWIZARD, MDOT, TEMPLATE.
% Copyright (C) 2005 Guillaume Flandin <[email protected]>
% $Revision: 1.5 $Date: 2005/04/29 16:04:17 $
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to [email protected]
% For tips on how to write Matlab code, see:
% * MATLAB Programming Style Guidelines, by R. Johnson:
% <http://www.datatool.com/prod02.htm>
% * For tips on creating help for your m-files 'type help.m'.
% * Matlab documentation on M-file Programming:
% <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/ch_funh8.html>
% This function uses the Template class so that you can fully customize
% the output. You can modify .tpl files in templates/blue/ or create new
% templates in a new directory.
% See the template class documentation for more details.
% <http://www.artefact.tk/software/matlab/template/>
% Latest information on M2HTML is available on the web through:
% <http://www.artefact.tk/software/matlab/m2html/>
% Other Matlab to HTML converters available on the web:
% 1/ mat2html.pl, J.C. Kantor, in Perl, 1995:
% <http://fresh.t-systems-sfr.com/unix/src/www/mat2html>
% 2/ htmltools, B. Alsberg, in Matlab, 1997:
% <http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=175>
% 3/ mtree2html2001, H. Pohlheim, in Perl, 1996, 2001:
% <http://www.pohlheim.com/perl_main.html#matlabdocu>
% 4/ MatlabToHTML, T. Kristjansson, binary, 2001:
% <http://www.psi.utoronto.ca/~trausti/MatlabToHTML/MatlabToHTML.html>
% 5/ Highlight, G. Flandin, in Matlab, 2003:
% <http://www.artefact.tk/software/matlab/highlight/>
% 6/ mdoc, P. Brinkmann, in Matlab, 2003:
% <http://www.math.uiuc.edu/~brinkman/software/mdoc/>
% 7/ Ocamaweb, Miriad Technologies, in Ocaml, 2002:
% <http://ocamaweb.sourceforge.net/>
% 8/ Matdoc, M. Kaminsky, in Perl, 2003:
% <http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=3498>
% 9/ Matlab itself, The Mathworks Inc, with HELPWIN, DOC and PUBLISH (R14)
%-------------------------------------------------------------------------------
%- Set up options and default parameters
%-------------------------------------------------------------------------------
t0 = clock; % for statistics
msgInvalidPair = 'Bad value for argument: ''%s''';
options = struct('verbose', 1,...
'mFiles', {{'.'}},...
'htmlDir', 'doc',...
'recursive', 0,...
'source', 1,...
'download',0,...
'syntaxHighlighting', 1,...
'tabs', 4,...
'globalHypertextLinks', 0,...
'graph', 0,...
'todo', 0,...
'load', 0,...
'save', 0,...
'search', 0,...
'helptocxml', 0,...
'indexFile', 'index',...
'extension', '.html',...
'template', 'blue',...
'rootdir', pwd,...
'language', 'english');
if nargin == 1 & isstruct(varargin{1})
paramlist = [ fieldnames(varargin{1}) ...
struct2cell(varargin{1}) ]';
paramlist = { paramlist{:} };
else
if mod(nargin,2)
error('Invalid parameter/value pair arguments.');
end
paramlist = varargin;
end
optionsnames = lower(fieldnames(options));
for i=1:2:length(paramlist)
pname = paramlist{i};
pvalue = paramlist{i+1};
ind = strmatch(lower(pname),optionsnames);
if isempty(ind)
error(['Invalid parameter: ''' pname '''.']);
elseif length(ind) > 1
error(['Ambiguous parameter: ''' pname '''.']);
end
switch(optionsnames{ind})
case 'verbose'
if strcmpi(pvalue,'on')
options.verbose = 1;
elseif strcmpi(pvalue,'off')
options.verbose = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'mfiles'
if iscellstr(pvalue)
options.mFiles = pvalue;
elseif ischar(pvalue)
options.mFiles = cellstr(pvalue);
else
error(sprintf(msgInvalidPair,pname));
end
options.load = 0;
case 'htmldir'
if ischar(pvalue)
if isempty(pvalue),
options.htmlDir = '.';
else
options.htmlDir = pvalue;
end
else
error(sprintf(msgInvalidPair,pname));
end
case 'recursive'
if strcmpi(pvalue,'on')
options.recursive = 1;
elseif strcmpi(pvalue,'off')
options.recursive = 0;
else
error(sprintf(msgInvalidPair,pname));
end
options.load = 0;
case 'source'
if strcmpi(pvalue,'on')
options.source = 1;
elseif strcmpi(pvalue,'off')
options.source = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'download'
if strcmpi(pvalue,'on')
options.download = 1;
elseif strcmpi(pvalue,'off')
options.download = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'syntaxhighlighting'
if strcmpi(pvalue,'on')
options.syntaxHighlighting = 1;
elseif strcmpi(pvalue,'off')
options.syntaxHighlighting = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'tabs'
if pvalue >= 0
options.tabs = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'globalhypertextlinks'
if strcmpi(pvalue,'on')
options.globalHypertextLinks = 1;
elseif strcmpi(pvalue,'off')
options.globalHypertextLinks = 0;
else
error(sprintf(msgInvalidPair,pname));
end
options.load = 0;
case 'graph'
if strcmpi(pvalue,'on')
options.graph = 1;
elseif strcmpi(pvalue,'off')
options.graph = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'todo'
if strcmpi(pvalue,'on')
options.todo = 1;
elseif strcmpi(pvalue,'off')
options.todo = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'load'
if ischar(pvalue)
if exist(pvalue) == 7 % directory provided
pvalue = fullfile(pvalue,'m2html.mat');
end
try
load(pvalue);
catch
error(sprintf('Unable to load %s.', pvalue));
end
options.load = 1;
[dummy options.template] = fileparts(options.template);
else
error(sprintf(msgInvalidPair,pname));
end
case 'save'
if strcmpi(pvalue,'on')
options.save = 1;
elseif strcmpi(pvalue,'off')
options.save = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'search'
if strcmpi(pvalue,'on')
options.search = 1;
elseif strcmpi(pvalue,'off')
options.search = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'helptocxml'
if strcmpi(pvalue,'on')
options.helptocxml = 1;
elseif strcmpi(pvalue,'off')
options.helptocxml = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'indexfile'
if ischar(pvalue)
options.indexFile = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'extension'
if ischar(pvalue) & pvalue(1) == '.'
options.extension = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'template'
if ischar(pvalue)
options.template = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'language'
if ischar(pvalue)
options.language = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
otherwise
error(['Invalid parameter: ''' pname '''.']);
end
end
%-------------------------------------------------------------------------------
%- Get template files location
%-------------------------------------------------------------------------------
s = fileparts(which(mfilename));
options.template = fullfile(s,'templates',options.template);
if exist(options.template) ~= 7
error('[Template] Unknown template.');
end
%-------------------------------------------------------------------------------
%- Get list of M-files
%-------------------------------------------------------------------------------
if ~options.load
if strcmp(options.mFiles,'.')
d = dir(pwd); d = {d([d.isdir]).name};
options.mFiles = {d{~ismember(d,{'.' '..'})}};
end
mfiles = getmfiles(options.mFiles,{},options.recursive);
if ~length(mfiles), fprintf('Nothing to be done.\n'); return; end
if options.verbose,
fprintf('Found %d M-files.\n',length(mfiles));
end
mfiles = sort(mfiles); % sort list of M-files in dictionary order
end
%-------------------------------------------------------------------------------
%- Get list of (unique) directories and (unique) names
%-------------------------------------------------------------------------------
if ~options.load
mdirs = {};
names = {};
for i=1:length(mfiles)
[mdirs{i}, names{i}] = fileparts(mfiles{i});
if isempty(mdirs{i}), mdirs{i} = '.'; end
end
mdir = unique(mdirs);
if options.verbose,
fprintf('Found %d unique Matlab directories.\n',length(mdir));
end
name = names;
%name = unique(names); % output is sorted
%if options.verbose,
% fprintf('Found %d unique Matlab files.\n',length(name));
%end
end
%-------------------------------------------------------------------------------
%- Create output directory, if necessary
%-------------------------------------------------------------------------------
if isempty(dir(options.htmlDir))
%- Create the top level output directory
if options.verbose
fprintf('Creating directory %s...\n',options.htmlDir);
end
if options.htmlDir(end) == filesep,
options.htmlDir(end) = [];
end
[pathdir, namedir] = fileparts(options.htmlDir);
if isempty(pathdir)
[status, msg] = mkdir(escapeblank(namedir));
else
[status, msg] = mkdir(escapeblank(pathdir), escapeblank(namedir));
end
if ~status, error(msg); end
end
%-------------------------------------------------------------------------------
%- Get synopsis, H1 line, script/function, subroutines, cross-references, todo
%-------------------------------------------------------------------------------
if ~options.load
synopsis = cell(size(mfiles));
h1line = cell(size(mfiles));
subroutine = cell(size(mfiles));
hrefs = sparse(length(mfiles), length(mfiles));
todo = struct('mfile',[], 'line',[], 'comment',{{}});
ismex = zeros(length(mfiles), length(mexexts));
statlist = {};
statinfo = sparse(1,length(mfiles));
kw = cell(size(mfiles));
freq = cell(size(mfiles));
for i=1:length(mfiles)
if options.verbose
fprintf('Processing file %s...',mfiles{i});
end
s = mfileparse(mfiles{i}, mdirs, names, options);
synopsis{i} = s.synopsis;
h1line{i} = s.h1line;
subroutine{i} = s.subroutine;
hrefs(i,:) = s.hrefs;
todo.mfile = [todo.mfile repmat(i,1,length(s.todo.line))];
todo.line = [todo.line s.todo.line];
todo.comment = {todo.comment{:} s.todo.comment{:}};
ismex(i,:) = s.ismex;
if options.search
if options.verbose, fprintf('search...'); end
[kw{i}, freq{i}] = searchindex(mfiles{i});
statlist = union(statlist, kw{i});
end
if options.verbose, fprintf('\n'); end
end
hrefs = hrefs > 0;
if options.search
if options.verbose
fprintf('Creating the search index...');
end
statinfo = sparse(length(statlist),length(mfiles));
for i=1:length(mfiles)
i1 = find(ismember(statlist, kw{i}));
i2 = repmat(i,1,length(i1));
if ~isempty(i1)
statinfo(sub2ind(size(statinfo),i1,i2)) = freq{i};
end
if options.verbose, fprintf('.'); end
end
clear kw freq;
if options.verbose, fprintf('\n'); end
end
end
%-------------------------------------------------------------------------------
%- Save M-filenames and cross-references for further analysis
%-------------------------------------------------------------------------------
matfilesave = 'm2html.mat';
if options.save
if options.verbose
fprintf('Saving MAT file %s...\n',matfilesave);
end
save(fullfile(options.htmlDir,matfilesave), ...
'mfiles', 'names', 'mdirs', 'name', 'mdir', 'options', ...
'hrefs', 'synopsis', 'h1line', 'subroutine', 'todo', 'ismex', ...
'statlist', 'statinfo');
end
%-------------------------------------------------------------------------------
%- Setup the output directories
%-------------------------------------------------------------------------------
for i=1:length(mdir)
if exist(fullfile(options.htmlDir,mdir{i})) ~= 7
ldir = splitpath(mdir{i});
for j=1:length(ldir)
if exist(fullfile(options.htmlDir,ldir{1:j})) ~= 7
%- Create the output directory
if options.verbose
fprintf('Creating directory %s...\n',...
fullfile(options.htmlDir,ldir{1:j}));
end
if j == 1
[status, msg] = mkdir(escapeblank(options.htmlDir), ...
escapeblank(ldir{1}));
else
[status, msg] = mkdir(escapeblank(options.htmlDir), ...
escapeblank(fullfile(ldir{1:j})));
end
error(msg);
end
end
end
end
%-------------------------------------------------------------------------------
%- Write the master index file
%-------------------------------------------------------------------------------
tpl_master = 'master.tpl';
tpl_master_identifier_nbyline = 4;
php_search = 'search.php';
dotbase = 'graph';
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_MASTER',tpl_master);
tpl = set(tpl,'block','TPL_MASTER','rowdir','rowdirs');
tpl = set(tpl,'block','TPL_MASTER','idrow','idrows');
tpl = set(tpl,'block','idrow','idcolumn','idcolumns');
tpl = set(tpl,'block','TPL_MASTER','search','searchs');
tpl = set(tpl,'block','TPL_MASTER','graph','graphs');
%- Open for writing the HTML master index file
curfile = fullfile(options.htmlDir,[options.indexFile options.extension]);
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set some template variables
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
tpl = set(tpl,'var','MASTERPATH', './');
tpl = set(tpl,'var','DIRS', sprintf('%s ',mdir{:}));
%- Print list of unique directories
for i=1:length(mdir)
tpl = set(tpl,'var','L_DIR',...
fullurl(mdir{i},[options.indexFile options.extension]));
tpl = set(tpl,'var','DIR',mdir{i});
tpl = parse(tpl,'rowdirs','rowdir',1);
end
%- Print full list of M-files (sorted by column)
[sortnames, ind] = sort(names);
m_mod = mod(length(sortnames), tpl_master_identifier_nbyline);
ind = [ind zeros(1,tpl_master_identifier_nbyline-m_mod)];
m_floor = floor(length(ind) / tpl_master_identifier_nbyline);
ind = reshape(ind,m_floor,tpl_master_identifier_nbyline)';
for i=1:prod(size(ind))
if ind(i)
tpl = set(tpl,'var','L_IDNAME',...
fullurl(mdirs{ind(i)},[names{ind(i)} options.extension]));
tpl = set(tpl,'var','T_IDNAME',mdirs{ind(i)});
tpl = set(tpl,'var','IDNAME',names{ind(i)});
tpl = parse(tpl,'idcolumns','idcolumn',1);
else
tpl = set(tpl,'var','L_IDNAME','');
tpl = set(tpl,'var','T_IDNAME','');
tpl = set(tpl,'var','IDNAME','');
tpl = parse(tpl,'idcolumns','idcolumn',1);
end
if mod(i,tpl_master_identifier_nbyline) == 0
tpl = parse(tpl,'idrows','idrow',1);
tpl = set(tpl,'var','idcolumns','');
end
end
%- Add a search form if necessary
tpl = set(tpl,'var','searchs','');
if options.search
tpl = set(tpl,'var','PHPFILE',php_search);
tpl = parse(tpl,'searchs','search',1);
end
%- Link to a full dependency graph, if necessary
tpl = set(tpl,'var','graphs','');
if options.graph & options.globalHypertextLinks & length(mdir) > 1
tpl = set(tpl,'var','LGRAPH',[dotbase options.extension]);
tpl = parse(tpl,'graphs','graph',1);
end
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_MASTER');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
%-------------------------------------------------------------------------------
%- Copy template files (CSS, images, ...)
%-------------------------------------------------------------------------------
% Get list of files
d = dir(options.template);
d = {d(~[d.isdir]).name};
% Copy files
for i=1:length(d)
[p, n, ext] = fileparts(d{i});
if ~strcmp(ext,'.tpl') ... % do not copy .tpl files
& ~strcmp([n ext],'Thumbs.db') % do not copy this Windows generated file
if isempty(dir(fullfile(options.htmlDir,d{i})))
if options.verbose
fprintf('Copying template file %s...\n',d{i});
end
%- there is a bug with <copyfile> in Matlab 6.5 :
% http://www.mathworks.com/support/solutions/data/1-1B5JY.html
%- and <copyfile> does not overwrite files even if newer...
[status, errmsg] = copyfile(fullfile(options.template,d{i}),...
options.htmlDir);
%- If you encounter this bug, please uncomment one of the following lines
% eval(['!cp -rf ' fullfile(options.template,d{i}) ' ' options.htmlDir]);
% eval(['!copy ' fullfile(options.template,d{i}) ' ' options.htmlDir]);
% status = 1;
if ~status
if ~isempty(errmsg)
error(errmsg)
else
warning(sprintf(['<copyfile> failed to do its job...\n' ...
'This is a known bug in Matlab 6.5 (R13).\n' ...
'See http://www.mathworks.com/support/solutions/data/1-1B5JY.html']));
end
end
end
end
end
%-------------------------------------------------------------------------------
%- Search engine (index file and PHP script)
%-------------------------------------------------------------------------------
tpl_search = 'search.tpl';
idx_search = 'search.idx';
% TODO % improving the fill in of 'statlist' and 'statinfo'
% TODO % improving the search template file and update the CSS file
if options.search
%- Write the search index file in output directory
if options.verbose
fprintf('Creating Search Index file %s...\n', idx_search);
end
docinfo = cell(length(mfiles),2);
for i=1:length(mfiles)
docinfo{i,1} = h1line{i};
docinfo{i,2} = fullurl(mdirs{i}, [names{i} options.extension]);
end
doxywrite(fullfile(options.htmlDir,idx_search),statlist,statinfo,docinfo);
%- Create the PHP template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_SEARCH',tpl_search);
%- Open for writing the PHP search script
curfile = fullfile(options.htmlDir, php_search);
if options.verbose
fprintf('Creating PHP script %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set template fields
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH','./');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
tpl = set(tpl,'var','IDXFILE',idx_search);
tpl = set(tpl,'var','PHPFILE',php_search);
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_SEARCH');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
end
%-------------------------------------------------------------------------------
%- Create <helptoc.xml> needed to display hierarchical entries in Contents panel
%-------------------------------------------------------------------------------
% See http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/guiref16.html
% and http://www.mathworks.com/support/solutions/data/1-18U6Q.html?solution=1-18U6Q
% TODO % display directories in TOC hierarchically instead of linearly
if options.helptocxml
curfile = fullfile(options.htmlDir, 'helptoc.xml');
if options.verbose
fprintf('Creating XML Table-Of-Content %s...\n',curfile);
end
fid = openfile(curfile,'w');
fprintf(fid,'<?xml version=''1.0'' encoding=''ISO-8859-1'' ?>\n');
fprintf(fid,'<!-- $Date: %s $ -->\n\n', datestr(now,31));
fprintf(fid,'<toc version="1.0">\n\n');
fprintf(fid,['<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/book_mat.gif">%s\n'], ...
[options.indexFile options.extension],'Toolbox');
for i=1:length(mdir)
fprintf(fid,['<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/reficon.gif">%s\n'], ...
fullfile(mdir{i}, ...
[options.indexFile options.extension]),mdir{i});
if options.graph
fprintf(fid,['\t<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/simulinkicon.gif">%s</tocitem>\n'], ...
fullfile(mdir{i},...
[dotbase options.extension]),'Dependency Graph');
end
if options.todo
if ~isempty(intersect(find(strcmp(mdir{i},mdirs)),todo.mfile))
fprintf(fid,['\t<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/demoicon.gif">%s</tocitem>\n'], ...
fullfile(mdir{i},...
['todo' options.extension]),'Todo list');
end
end
for j=1:length(mdirs)
if strcmp(mdirs{j},mdir{i})
curfile = fullfile(mdir{i},...
[names{j} options.extension]);
fprintf(fid,'\t<tocitem target="%s">%s</tocitem>\n', ...
curfile,names{j});
end
end
fprintf(fid,'</tocitem>\n');
end
fprintf(fid,'</tocitem>\n');
fprintf(fid,'\n</toc>\n');
fclose(fid);
end
%-------------------------------------------------------------------------------
%- Write an index for each output directory
%-------------------------------------------------------------------------------
tpl_mdir = 'mdir.tpl';
tpl_mdir_link = '<a href="%s">%s</a>';
%dotbase defined earlier
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_MDIR',tpl_mdir);
tpl = set(tpl,'block','TPL_MDIR','row-m','rows-m');
tpl = set(tpl,'block','row-m','mexfile','mex');
tpl = set(tpl,'block','TPL_MDIR','othermatlab','other');
tpl = set(tpl,'block','othermatlab','row-other','rows-other');
tpl = set(tpl,'block','TPL_MDIR','subfolder','subfold');
tpl = set(tpl,'block','subfolder','subdir','subdirs');
tpl = set(tpl,'block','TPL_MDIR','todolist','todolists');
tpl = set(tpl,'block','TPL_MDIR','graph','graphs');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
for i=1:length(mdir)
%- Open for writing each output directory index file
curfile = fullfile(options.htmlDir,mdir{i},...
[options.indexFile options.extension]);
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set template fields
tpl = set(tpl,'var','INDEX', [options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH',backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdir{i});
%- Display Matlab m-files, their H1 line and their Mex status
tpl = set(tpl,'var','rows-m','');
for j=1:length(mdirs)
if strcmp(mdirs{j},mdir{i})
tpl = set(tpl,'var','L_NAME', [names{j} options.extension]);
tpl = set(tpl,'var','NAME', names{j});
tpl = set(tpl,'var','H1LINE', h1line{j});
if any(ismex(j,:))
tpl = parse(tpl,'mex','mexfile');
else
tpl = set(tpl,'var','mex','');
end
tpl = parse(tpl,'rows-m','row-m',1);
end
end
%- Display other Matlab-specific files (.mat,.mdl,.p)
tpl = set(tpl,'var','other','');
tpl = set(tpl,'var','rows-other','');
w = what(mdir{i}); w = w(1);
w = {w.mat{:} w.mdl{:} w.p{:}};
for j=1:length(w)
tpl = set(tpl,'var','OTHERFILE',w{j});
tpl = parse(tpl,'rows-other','row-other',1);
end
if ~isempty(w)
tpl = parse(tpl,'other','othermatlab');
end
%- Display subsequent directories and classes
tpl = set(tpl,'var','subdirs','');
tpl = set(tpl,'var','subfold','');
d = dir(mdir{i});
d = {d([d.isdir]).name};
d = {d{~ismember(d,{'.' '..'})}};
for j=1:length(d)
if ismember(fullfile(mdir{i},d{j}),mdir)
tpl = set(tpl,'var','SUBDIRECTORY',...
sprintf(tpl_mdir_link,...
fullurl(d{j},[options.indexFile options.extension]),d{j}));
else
tpl = set(tpl,'var','SUBDIRECTORY',d{j});
end
tpl = parse(tpl,'subdirs','subdir',1);
end
if ~isempty(d)
tpl = parse(tpl,'subfold','subfolder');
end
%- Link to the TODO list if necessary
tpl = set(tpl,'var','todolists','');
if options.todo
if ~isempty(intersect(find(strcmp(mdir{i},mdirs)),todo.mfile))
tpl = set(tpl,'var','LTODOLIST',['todo' options.extension]);
tpl = parse(tpl,'todolists','todolist',1);
end
end
%- Link to the dependency graph if necessary
tpl = set(tpl,'var','graphs','');
if options.graph
tpl = set(tpl,'var','LGRAPH',[dotbase options.extension]);
tpl = parse(tpl,'graphs','graph',1);
end
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_MDIR');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
end
%-------------------------------------------------------------------------------
%- Write a TODO list file for each output directory, if necessary
%-------------------------------------------------------------------------------
tpl_todo = 'todo.tpl';
if options.todo
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_TODO',tpl_todo);
tpl = set(tpl,'block','TPL_TODO','filelist','filelists');
tpl = set(tpl,'block','filelist','row','rows');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
for i=1:length(mdir)
mfilestodo = intersect(find(strcmp(mdir{i},mdirs)),todo.mfile);
if ~isempty(mfilestodo)
%- Open for writing each TODO list file
curfile = fullfile(options.htmlDir,mdir{i},...
['todo' options.extension]);
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set template fields
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdir{i});
tpl = set(tpl,'var','filelists', '');
for k=1:length(mfilestodo)
tpl = set(tpl,'var','MFILE',names{mfilestodo(k)});
tpl = set(tpl,'var','rows','');
nbtodo = find(todo.mfile == mfilestodo(k));
for l=1:length(nbtodo)
tpl = set(tpl,'var','L_NBLINE',...
[names{mfilestodo(k)} ...
options.extension ...
'#l' num2str(todo.line(nbtodo(l)))]);
tpl = set(tpl,'var','NBLINE',num2str(todo.line(nbtodo(l))));
tpl = set(tpl,'var','COMMENT',todo.comment{nbtodo(l)});
tpl = parse(tpl,'rows','row',1);
end
tpl = parse(tpl,'filelists','filelist',1);
end
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_TODO');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
end
end
end
%-------------------------------------------------------------------------------
%- Create dependency graphs using GraphViz, if requested
%-------------------------------------------------------------------------------
tpl_graph = 'graph.tpl';
% You may have to modify the following line with Matlab7 (R14) to specify
% the full path to where GraphViz is installed
dot_exec = 'dot';
%dotbase defined earlier
if options.graph
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_GRAPH',tpl_graph);
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
%- Create a full dependency graph for all directories if possible
if options.globalHypertextLinks & length(mdir) > 1
mdotfile = fullfile(options.htmlDir,[dotbase '.dot']);
if options.verbose
fprintf('Creating full dependency graph %s...',mdotfile);
end
mdot({hrefs, names, options, mdirs}, mdotfile); %mfiles
calldot(dot_exec, mdotfile, ...
fullfile(options.htmlDir,[dotbase '.map']), ...
fullfile(options.htmlDir,[dotbase '.png']));
if options.verbose, fprintf('\n'); end
fid = openfile(fullfile(options.htmlDir, [dotbase options.extension]),'w');
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', './');
tpl = set(tpl,'var','MDIR', 'the whole toolbox');
tpl = set(tpl,'var','GRAPH_IMG', [dotbase '.png']);
try % if <dot> failed...
fmap = openfile(fullfile(options.htmlDir,[dotbase '.map']),'r');
tpl = set(tpl,'var','GRAPH_MAP', fscanf(fmap,'%c'));
fclose(fmap);
end
tpl = parse(tpl,'OUT','TPL_GRAPH');
fprintf(fid,'%s', get(tpl,'OUT'));
fclose(fid);
end
%- Create a dependency graph for each output directory
for i=1:length(mdir)
mdotfile = fullfile(options.htmlDir,mdir{i},[dotbase '.dot']);
if options.verbose
fprintf('Creating dependency graph %s...',mdotfile);
end
ind = find(strcmp(mdirs,mdir{i}));
href1 = zeros(length(ind),length(hrefs));
for j=1:length(hrefs), href1(:,j) = hrefs(ind,j); end
href2 = zeros(length(ind));
for j=1:length(ind), href2(j,:) = href1(j,ind); end
mdot({href2, {names{ind}}, options}, mdotfile); %{mfiles{ind}}
calldot(dot_exec, mdotfile, ...
fullfile(options.htmlDir,mdir{i},[dotbase '.map']), ...
fullfile(options.htmlDir,mdir{i},[dotbase '.png']));
if options.verbose, fprintf('\n'); end
fid = openfile(fullfile(options.htmlDir,mdir{i},...
[dotbase options.extension]),'w');
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdir{i});
tpl = set(tpl,'var','GRAPH_IMG', [dotbase '.png']);
try % if <dot> failed, no '.map' file has been created
fmap = openfile(fullfile(options.htmlDir,mdir{i},[dotbase '.map']),'r');
tpl = set(tpl,'var','GRAPH_MAP', fscanf(fmap,'%c'));
fclose(fmap);
end
tpl = parse(tpl,'OUT','TPL_GRAPH');
fprintf(fid,'%s', get(tpl,'OUT'));
fclose(fid);
end
end
%-------------------------------------------------------------------------------
%- Write an HTML file for each M-file
%-------------------------------------------------------------------------------
%- List of Matlab keywords (output from iskeyword)
matlabKeywords = {'break', 'case', 'catch', 'continue', 'elseif', 'else', ...
'end', 'for', 'function', 'global', 'if', 'otherwise', ...
'persistent', 'return', 'switch', 'try', 'while'};
%'keyboard', 'pause', 'eps', 'NaN', 'Inf'
tpl_mfile = 'mfile.tpl';
tpl_mfile_code = '<a href="%s" class="code" title="%s">%s</a>';
tpl_mfile_keyword = '<span class="keyword">%s</span>';
tpl_mfile_comment = '<span class="comment">%s</span>';
tpl_mfile_string = '<span class="string">%s</span>';
tpl_mfile_aname = '<a name="%s" href="#_subfunctions" class="code">%s</a>';
tpl_mfile_line = '%04d %s\n';
%- Delimiters used in strtok: some of them may be useless (% " .), removed '.'
strtok_delim = sprintf(' \t\n\r(){}[]<>+-*~!|\\@&/,:;="''%%');
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_MFILE',tpl_mfile);
tpl = set(tpl,'block','TPL_MFILE','pathline','pl');
tpl = set(tpl,'block','TPL_MFILE','mexfile','mex');
tpl = set(tpl,'block','TPL_MFILE','script','scriptfile');
tpl = set(tpl,'block','TPL_MFILE','crossrefcall','crossrefcalls');
tpl = set(tpl,'block','TPL_MFILE','crossrefcalled','crossrefcalleds');
tpl = set(tpl,'block','TPL_MFILE','subfunction','subf');
tpl = set(tpl,'block','subfunction','onesubfunction','onesubf');
tpl = set(tpl,'block','TPL_MFILE','source','thesource');
tpl = set(tpl,'block','TPL_MFILE','download','downloads');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
nblinetot = 0;
for i=1:length(mdir)
for j=1:length(mdirs)
if strcmp(mdirs{j},mdir{i})
curfile = fullfile(options.htmlDir,mdir{i},...
[names{j} options.extension]);
%- Copy M-file for download, if necessary
if options.download
if options.verbose
fprintf('Copying M-file %s.m to %s...\n',names{j},...
fullfile(options.htmlDir,mdir{i}));
end
[status, errmsg] = copyfile(mfiles{j},...
fullfile(options.htmlDir,mdir{i}));
error(errmsg);
end
%- Open for writing the HTML file
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
if strcmp(names{j},options.indexFile)
fprintf(['Warning: HTML index file %s will be ' ...
'overwritten by Matlab function %s.\n'], ...
[options.indexFile options.extension], mfiles{j});
end
%- Open for reading the M-file
fid2 = openfile(mfiles{j},'r');
%- Set some template fields
tpl = set(tpl,'var','INDEX', [options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdirs{j});
tpl = set(tpl,'var','NAME', names{j});
tpl = set(tpl,'var','H1LINE', entity(h1line{j}));
tpl = set(tpl,'var','scriptfile', '');
if isempty(synopsis{j})
tpl = set(tpl,'var','SYNOPSIS',get(tpl,'var','script'));
else
tpl = set(tpl,'var','SYNOPSIS', synopsis{j});
end
s = splitpath(mdir{i});
tpl = set(tpl,'var','pl','');
for k=1:length(s)
c = cell(1,k); for l=1:k, c{l} = filesep; end
cpath = {s{1:k};c{:}}; cpath = [cpath{:}];
if ~isempty(cpath), cpath = cpath(1:end-1); end
if ismember(cpath,mdir)
tpl = set(tpl,'var','LPATHDIR',[repmat('../',...
1,length(s)-k) options.indexFile options.extension]);
else
tpl = set(tpl,'var','LPATHDIR','#');
end
tpl = set(tpl,'var','PATHDIR',s{k});
tpl = parse(tpl,'pl','pathline',1);
end
%- Handle mex files
tpl = set(tpl,'var','mex', '');
samename = dir(fullfile(mdir{i},[names{j} '.*']));
samename = {samename.name};
tpl = set(tpl,'var','MEXTYPE', 'mex');
for k=1:length(samename)
[dummy, dummy, ext] = fileparts(samename{k});
switch ext
case '.c'
tpl = set(tpl,'var','MEXTYPE', 'c');
case {'.cpp' '.c++' '.cxx' '.C'}
tpl = set(tpl,'var','MEXTYPE', 'c++');
case {'.for' '.f' '.FOR' '.F'}
tpl = set(tpl,'var','MEXTYPE', 'fortran');
otherwise
%- Unknown mex file source
end
end
[exts, platform] = mexexts;
mexplatforms = sprintf('%s, ',platform{find(ismex(j,:))});
if ~isempty(mexplatforms)
tpl = set(tpl,'var','PLATFORMS', mexplatforms(1:end-2));
tpl = parse(tpl,'mex','mexfile');
end
%- Set description template field
descr = '';
flagsynopcont = 0;
flag_seealso = 0;
while 1
tline = fgets(fid2);
if ~ischar(tline), break, end
tline = entity(fliplr(deblank(fliplr(tline))));
%- Synopsis line
if ~isempty(strmatch('function',tline))
if ~isempty(strmatch('...',fliplr(deblank(tline))))
flagsynopcont = 1;
end
%- H1 line and description
elseif ~isempty(strmatch('%',tline))
%- Hypertext links on the "See also" line
ind = findstr(lower(tline),'see also');
if ~isempty(ind) | flag_seealso
%- "See also" only in files in the same directory
indsamedir = find(strcmp(mdirs{j},mdirs));
hrefnames = {names{indsamedir}};
r = deblank(tline);
flag_seealso = 1; %(r(end) == ',');
tline = '';
while 1
[t,r,q] = strtok(r,sprintf(' \t\n\r.,;%%'));
tline = [tline q];
if isempty(t), break, end;
ii = strcmpi(hrefnames,t);
if any(ii)
jj = find(ii);
tline = [tline sprintf(tpl_mfile_code,...
[hrefnames{jj(1)} options.extension],...
synopsis{indsamedir(jj(1))},t)];
else
tline = [tline t];
end
end
tline = sprintf('%s\n',tline);
end
descr = [descr tline(2:end)];
elseif isempty(tline)
if ~isempty(descr), break, end;
else
if flagsynopcont
if isempty(strmatch('...',fliplr(deblank(tline))))
flagsynopcont = 0;
end
else
break;
end
end
end
tpl = set(tpl,'var','DESCRIPTION',...
horztab(descr,options.tabs));
%- Set cross-references template fields:
% Function called
ind = find(hrefs(j,:) == 1);
tpl = set(tpl,'var','crossrefcalls','');
for k=1:length(ind)
if strcmp(mdirs{j},mdirs{ind(k)})
tpl = set(tpl,'var','L_NAME_CALL', ...
[names{ind(k)} options.extension]);
else
tpl = set(tpl,'var','L_NAME_CALL', ...
fullurl(backtomaster(mdirs{j}), ...
mdirs{ind(k)}, ...
[names{ind(k)} options.extension]));
end
tpl = set(tpl,'var','SYNOP_CALL', synopsis{ind(k)});
tpl = set(tpl,'var','NAME_CALL', names{ind(k)});
tpl = set(tpl,'var','H1LINE_CALL', h1line{ind(k)});
tpl = parse(tpl,'crossrefcalls','crossrefcall',1);
end
% Callers
ind = find(hrefs(:,j) == 1);
tpl = set(tpl,'var','crossrefcalleds','');
for k=1:length(ind)
if strcmp(mdirs{j},mdirs{ind(k)})
tpl = set(tpl,'var','L_NAME_CALLED', ...
[names{ind(k)} options.extension]);
else
tpl = set(tpl,'var','L_NAME_CALLED', ...
fullurl(backtomaster(mdirs{j}),...
mdirs{ind(k)}, ...
[names{ind(k)} options.extension]));
end
tpl = set(tpl,'var','SYNOP_CALLED', synopsis{ind(k)});
tpl = set(tpl,'var','NAME_CALLED', names{ind(k)});
tpl = set(tpl,'var','H1LINE_CALLED', h1line{ind(k)});
tpl = parse(tpl,'crossrefcalleds','crossrefcalled',1);
end
%- Set subfunction template field
tpl = set(tpl,'var',{'subf' 'onesubf'},{'' ''});
if ~isempty(subroutine{j}) & options.source
for k=1:length(subroutine{j})
tpl = set(tpl, 'var', 'L_SUB', ['#_sub' num2str(k)]);
tpl = set(tpl, 'var', 'SUB', subroutine{j}{k});
tpl = parse(tpl, 'onesubf', 'onesubfunction',1);
end
tpl = parse(tpl,'subf','subfunction');
end
subname = extractname(subroutine{j});
%- Link to M-file (for download)
tpl = set(tpl,'var','downloads','');
if options.download
tpl = parse(tpl,'downloads','download',1);
end
%- Display source code with cross-references
if options.source & ~strcmpi(names{j},'contents')
fseek(fid2,0,-1);
it = 1;
matlabsource = '';
nbsubroutine = 1;
%- Get href function names of this file
indhrefnames = find(hrefs(j,:) == 1);
hrefnames = {names{indhrefnames}};
%- Loop over lines
while 1
tline = fgetl(fid2);
if ~ischar(tline), break, end
myline = '';
splitc = splitcode(entity(tline));
for k=1:length(splitc)
if isempty(splitc{k})
elseif ~isempty(strmatch('function',splitc{k}))
%- Subfunctions definition
myline = [myline ...
sprintf(tpl_mfile_aname,...
['_sub' num2str(nbsubroutine-1)],splitc{k})];
nbsubroutine = nbsubroutine + 1;
elseif splitc{k}(1) == ''''
myline = [myline ...
sprintf(tpl_mfile_string,splitc{k})];
elseif splitc{k}(1) == '%'
myline = [myline ...
sprintf(tpl_mfile_comment,deblank(splitc{k}))];
elseif ~isempty(strmatch('...',splitc{k}))
myline = [myline sprintf(tpl_mfile_keyword,'...')];
if ~isempty(splitc{k}(4:end))
myline = [myline ...
sprintf(tpl_mfile_comment,splitc{k}(4:end))];
end
else
%- Look for keywords
r = splitc{k};
while 1
[t,r,q] = strtok(r,strtok_delim);
myline = [myline q];
if isempty(t), break, end;
%- Highlight Matlab keywords &
% cross-references on known functions
if options.syntaxHighlighting & ...
any(strcmp(matlabKeywords,t))
if strcmp('end',t)
rr = fliplr(deblank(fliplr(r)));
icomma = strmatch(',',rr);
isemicolon = strmatch(';',rr);
if ~(isempty(rr) | ~isempty([icomma isemicolon]))
myline = [myline t];
else
myline = [myline sprintf(tpl_mfile_keyword,t)];
end
else
myline = [myline sprintf(tpl_mfile_keyword,t)];
end
elseif any(strcmp(hrefnames,t))
indt = indhrefnames(logical(strcmp(hrefnames,t)));
flink = [t options.extension];
ii = ismember({mdirs{indt}},mdirs{j});
if ~any(ii)
% take the first one...
flink = fullurl(backtomaster(mdirs{j}),...
mdirs{indt(1)}, flink);
else
indt = indt(logical(ii));
end
myline = [myline sprintf(tpl_mfile_code,...
flink, synopsis{indt(1)}, t)];
elseif any(strcmp(subname,t))
ii = find(strcmp(subname,t));
myline = [myline sprintf(tpl_mfile_code,...
['#_sub' num2str(ii)],...
['sub' subroutine{j}{ii}],t)];
else
myline = [myline t];
end
end
end
end
matlabsource = [matlabsource sprintf(tpl_mfile_line,it,myline)];
it = it + 1;
end
nblinetot = nblinetot + it - 1;
tpl = set(tpl,'var','SOURCECODE',...
horztab(matlabsource,options.tabs));
tpl = parse(tpl,'thesource','source');
else
tpl = set(tpl,'var','thesource','');
end
tpl = parse(tpl,'OUT','TPL_MFILE');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid2);
fclose(fid);
end
end
end
%-------------------------------------------------------------------------------
%- Display Statistics
%-------------------------------------------------------------------------------
if options.verbose
prnbline = '';
if options.source
prnbline = sprintf('(%d lines) ', nblinetot);
end
fprintf('Stats: %d M-files %sin %d directories documented in %d s.\n', ...
length(mfiles), prnbline, length(mdir), round(etime(clock,t0)));
end
%===============================================================================
function mfiles = getmfiles(mdirs, mfiles, recursive)
%- Extract M-files from a list of directories and/or M-files
for i=1:length(mdirs)
currentdir = fullfile(pwd, mdirs{i});
if exist(currentdir) == 2 % M-file
mfiles{end+1} = mdirs{i};
elseif exist(currentdir) == 7 % Directory
d = dir(fullfile(currentdir, '*.m'));
d = {d(~[d.isdir]).name};
for j=1:length(d)
%- don't take care of files containing ','
% probably a sccs file...
if isempty(findstr(',',d{j}))
mfiles{end+1} = fullfile(mdirs{i}, d{j});
end
end
if recursive
d = dir(currentdir);
d = {d([d.isdir]).name};
d = {d{~ismember(d,{'.' '..'})}};
for j=1:length(d)
mfiles = getmfiles(cellstr(fullfile(mdirs{i},d{j})), ...
mfiles, recursive);
end
end
else
fprintf('Warning: Unprocessed file %s.\n',mdirs{i});
if ~isempty(strmatch('/',mdirs{i})) | findstr(':',mdirs{i})
fprintf(' Use relative paths in ''mfiles'' option\n');
end
end
end
%===============================================================================
function calldot(dotexec, mdotfile, mapfile, pngfile, opt)
%- Draw a dependency graph in a PNG image using <dot> from GraphViz
if nargin == 4, opt = ''; end
try
%- See <http://www.graphviz.org/>
% <dot> must be in your system path, see M2HTML FAQ:
% <http://www.artefact.tk/software/matlab/m2html/faq.php>
eval(['!"' dotexec '" ' opt ' -Tcmap -Tpng "' mdotfile ...
'" -o "' mapfile ...
'" -o "' pngfile '"']);
% use '!' rather than 'system' for backward compability with Matlab 5.3
catch % use of '!' prevents errors to be catched...
fprintf('<dot> failed.');
end
%===============================================================================
function s = backtomaster(mdir)
%- Provide filesystem path to go back to the root folder
ldir = splitpath(mdir);
s = repmat('../',1,length(ldir));
%===============================================================================
function ldir = splitpath(p)
%- Split a filesystem path into parts using filesep as separator
ldir = {};
p = deblank(p);
while 1
[t,p] = strtok(p,filesep);
if isempty(t), break; end
if ~strcmp(t,'.')
ldir{end+1} = t;
end
end
if isempty(ldir)
ldir{1} = '.'; % should be removed
end
%===============================================================================
function name = extractname(synopsis)
%- Extract function name in a synopsis
if ischar(synopsis), synopsis = {synopsis}; end
name = cell(size(synopsis));
for i=1:length(synopsis)
ind = findstr(synopsis{i},'=');
if isempty(ind)
ind = findstr(synopsis{i},'function');
s = synopsis{i}(ind(1)+8:end);
else
s = synopsis{i}(ind(1)+1:end);
end
name{i} = strtok(s,[9:13 32 40]); % white space characters and '('
end
if length(name) == 1, name = name{1}; end
%===============================================================================
function f = fullurl(varargin)
%- Build full url from parts (using '/' and not filesep)
f = strrep(fullfile(varargin{:}),'\','/');
%===============================================================================
function str = escapeblank(str)
%- Escape white spaces using '\'
str = deblank(fliplr(deblank(fliplr(str))));
str = strrep(str,' ','\ ');
%===============================================================================
function str = entity(str)
%- Escape HTML special characters
%- See http://www.w3.org/TR/html4/charset.html#h-5.3.2
str = strrep(str,'&','&');
str = strrep(str,'<','<');
str = strrep(str,'>','>');
str = strrep(str,'"','"');
%===============================================================================
function str = horztab(str,n)
%- For browsers, the horizontal tab character is the smallest non-zero
%- number of spaces necessary to line characters up along tab stops that are
%- every 8 characters: behaviour obtained when n = 0.
if n > 0
str = strrep(str,sprintf('\t'),blanks(n));
end
|
github
|
P-Chao/acfdetect-master
|
doxysearch.m
|
.m
|
acfdetect-master/toolbox/external/m2html/private/doxysearch.m
| 7,724 |
utf_8
|
8331cde8495f34b86aef8c18656b37f2
|
function result = doxysearch(query,filename)
%DOXYSEARCH Search a query in a 'search.idx' file
% RESULT = DOXYSEARCH(QUERY,FILENAME) looks for request QUERY
% in FILENAME (Doxygen search.idx format) and returns a list of
% files responding to the request in RESULT.
%
% See also DOXYREAD, DOXYWRITE
% Copyright (C) 2004 Guillaume Flandin <[email protected]>
% $Revision: 1.1 $Date: 2004/05/05 14:33:55 $
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% See <http://www.doxygen.org/> for more details.
error(nargchk(1,2,nargin));
if nargin == 1,
filename = 'search.idx';
end
%- Open the search index file
[fid, errmsg] = fopen(filename,'r','ieee-be');
if fid == -1, error(errmsg); end
%- 4 byte header (DOXS)
header = char(fread(fid,4,'uchar'))';
if ~all(header == 'DOXS')
error('[doxysearch] Header of index file is invalid!');
end
%- many thanks to <doxyread.m> and <doxysearch.php>
r = query;
requiredWords = {};
forbiddenWords = {};
foundWords = {};
res = {};
while 1
% extract each word of the query
[t,r] = strtok(r);
if isempty(t), break, end;
if t(1) == '+'
t = t(2:end); requiredWords{end+1} = t;
elseif t(1) == '-'
t = t(2:end); forbiddenWords{end+1} = t;
end
if ~ismember(t,foundWords)
foundWords{end+1} = t;
res = searchAgain(fid,t,res);
end
end
%- Filter and sort results
docs = combineResults(res);
filtdocs = filterResults(docs,requiredWords,forbiddenWords);
filtdocs = normalizeResults(filtdocs);
res = sortResults(filtdocs);
%-
if nargout
result = res;
else
for i=1:size(res,1)
fprintf(' %d. %s - %s\n ',i,res{i,1},res{i,2});
for j=1:size(res{i,4},1)
fprintf('%s ',res{i,4}{j,1});
end
fprintf('\n');
end
end
%- Close the search index file
fclose(fid);
%===========================================================================
function res = searchAgain(fid, word,res)
i = computeIndex(word);
if i > 0
fseek(fid,i*4+4,'bof'); % 4 bytes per entry, skip header
start = size(res,1);
idx = readInt(fid);
if idx > 0
fseek(fid,idx,'bof');
statw = readString(fid);
while ~isempty(statw)
statidx = readInt(fid);
if length(statw) >= length(word) & ...
strcmp(statw(1:length(word)),word)
res{end+1,1} = statw; % word
res{end,2} = word; % match
res{end,3} = statidx; % index
res{end,4} = (length(statw) == length(word)); % full
res{end,5} = {}; % doc
end
statw = readString(fid);
end
totalfreq = 0;
for j=start+1:size(res,1)
fseek(fid,res{j,3},'bof');
numdoc = readInt(fid);
docinfo = {};
for m=1:numdoc
docinfo{m,1} = readInt(fid); % idx
docinfo{m,2} = readInt(fid); % freq
docinfo{m,3} = 0; % rank
totalfreq = totalfreq + docinfo{m,2};
if res{j,2},
totalfreq = totalfreq + docinfo{m,2};
end;
end
for m=1:numdoc
fseek(fid, docinfo{m,1}, 'bof');
docinfo{m,4} = readString(fid); % name
docinfo{m,5} = readString(fid); % url
end
res{j,5} = docinfo;
end
for j=start+1:size(res,1)
for m=1:size(res{j,5},1)
res{j,5}{m,3} = res{j,5}{m,2} / totalfreq;
end
end
end % if idx > 0
end % if i > 0
%===========================================================================
function docs = combineResults(result)
docs = {};
for i=1:size(result,1)
for j=1:size(result{i,5},1)
key = result{i,5}{j,5};
rank = result{i,5}{j,3};
if ~isempty(docs) & ismember(key,{docs{:,1}})
l = find(ismember({docs{:,1}},key));
docs{l,3} = docs{l,3} + rank;
docs{l,3} = 2 * docs{l,3};
else
l = size(docs,1)+1;
docs{l,1} = key; % key
docs{l,2} = result{i,5}{j,4}; % name
docs{l,3} = rank; % rank
docs{l,4} = {}; %words
end
n = size(docs{l,4},1);
docs{l,4}{n+1,1} = result{i,1}; % word
docs{l,4}{n+1,2} = result{i,2}; % match
docs{l,4}{n+1,3} = result{i,5}{j,2}; % freq
end
end
%===========================================================================
function filtdocs = filterResults(docs,requiredWords,forbiddenWords)
filtdocs = {};
for i=1:size(docs,1)
words = docs{i,4};
c = 1;
j = size(words,1);
% check required
if ~isempty(requiredWords)
found = 0;
for k=1:j
if ismember(words{k,1},requiredWords)
found = 1;
break;
end
end
if ~found, c = 0; end
end
% check forbidden
if ~isempty(forbiddenWords)
for k=1:j
if ismember(words{k,1},forbiddenWords)
c = 0;
break;
end
end
end
% keep it or not
if c,
l = size(filtdocs,1)+1;
filtdocs{l,1} = docs{i,1};
filtdocs{l,2} = docs{i,2};
filtdocs{l,3} = docs{i,3};
filtdocs{l,4} = docs{i,4};
end;
end
%===========================================================================
function docs = normalizeResults(docs);
m = max([docs{:,3}]);
for i=1:size(docs,1)
docs{i,3} = 100 * docs{i,3} / m;
end
%===========================================================================
function result = sortResults(docs);
[y, ind] = sort([docs{:,3}]);
result = {};
ind = fliplr(ind);
for i=1:size(docs,1)
result{i,1} = docs{ind(i),1};
result{i,2} = docs{ind(i),2};
result{i,3} = docs{ind(i),3};
result{i,4} = docs{ind(i),4};
end
%===========================================================================
function i = computeIndex(word)
if length(word) < 2,
i = -1;
else
i = double(word(1)) * 256 + double(word(2));
end
%===========================================================================
function s = readString(fid)
s = '';
while 1
w = fread(fid,1,'uchar');
if w == 0, break; end
s(end+1) = char(w);
end
%===========================================================================
function i = readInt(fid)
i = fread(fid,1,'uint32');
|
github
|
P-Chao/acfdetect-master
|
doxywrite.m
|
.m
|
acfdetect-master/toolbox/external/m2html/private/doxywrite.m
| 3,584 |
utf_8
|
3255d8f824957ebc173dde374d0f78af
|
function doxywrite(filename, kw, statinfo, docinfo)
%DOXYWRITE Write a 'search.idx' file compatible with DOXYGEN
% DOXYWRITE(FILENAME, KW, STATINFO, DOCINFO) writes file FILENAME
% (Doxygen search.idx. format) using the cell array KW containing the
% word list, the sparse matrix (nbword x nbfile) with non-null values
% in (i,j) indicating the frequency of occurence of word i in file j
% and the cell array (nbfile x 2) containing the list of urls and names
% of each file.
%
% See also DOXYREAD
% Copyright (C) 2003 Guillaume Flandin <[email protected]>
% $Revision: 1.0 $Date: 2003/23/10 15:52:56 $
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% See <http://www.doxygen.org/> for more details.
error(nargchk(4,4,nargin));
%- Open the search index file
[fid, errmsg] = fopen(filename,'w','ieee-be');
if fid == -1, error(errmsg); end
%- Write 4 byte header (DOXS)
fwrite(fid,'DOXS','uchar');
pos = ftell(fid);
%- Write 256 * 256 header
idx = zeros(256);
writeInt(fid, idx);
%- Write word lists
i = 1;
idx2 = zeros(1,length(kw));
while 1
s = kw{i}(1:2);
idx(double(s(2)+1), double(s(1)+1)) = ftell(fid);
while i <= length(kw) & strmatch(s, kw{i})
writeString(fid,kw{i});
idx2(i) = ftell(fid);
writeInt(fid,0);
i = i + 1;
end
fwrite(fid, 0, 'int8');
if i > length(kw), break; end
end
%- Write extra padding bytes
pad = mod(4 - mod(ftell(fid),4), 4);
for i=1:pad, fwrite(fid,0,'int8'); end
pos2 = ftell(fid);
%- Write 256*256 header again
fseek(fid, pos, 'bof');
writeInt(fid, idx);
% Write word statistics
fseek(fid,pos2,'bof');
idx3 = zeros(1,length(kw));
for i=1:length(kw)
idx3(i) = ftell(fid);
[ia, ib, v] = find(statinfo(i,:));
counter = length(ia); % counter
writeInt(fid,counter);
for j=1:counter
writeInt(fid,ib(j)); % index
writeInt(fid,v(j)); % freq
end
end
pos3 = ftell(fid);
%- Set correct handles to keywords
for i=1:length(kw)
fseek(fid,idx2(i),'bof');
writeInt(fid,idx3(i));
end
% Write urls
fseek(fid,pos3,'bof');
idx4 = zeros(1,length(docinfo));
for i=1:length(docinfo)
idx4(i) = ftell(fid);
writeString(fid, docinfo{i,1}); % name
writeString(fid, docinfo{i,2}); % url
end
%- Set corrext handles to word statistics
fseek(fid,pos2,'bof');
for i=1:length(kw)
[ia, ib, v] = find(statinfo(i,:));
counter = length(ia);
fseek(fid,4,'cof'); % counter
for m=1:counter
writeInt(fid,idx4(ib(m)));% index
fseek(fid,4,'cof'); % freq
end
end
%- Close the search index file
fclose(fid);
%===========================================================================
function writeString(fid, s)
fwrite(fid,s,'uchar');
fwrite(fid,0,'int8');
%===========================================================================
function writeInt(fid, i)
fwrite(fid,i,'uint32');
|
github
|
P-Chao/acfdetect-master
|
doxyread.m
|
.m
|
acfdetect-master/toolbox/external/m2html/private/doxyread.m
| 3,093 |
utf_8
|
3152e7d26bf7ac64118be56f72832a20
|
function [statlist, docinfo] = doxyread(filename)
%DOXYREAD Read a 'search.idx' file generated by DOXYGEN
% STATLIST = DOXYREAD(FILENAME) reads FILENAME (Doxygen search.idx
% format) and returns the list of keywords STATLIST as a cell array.
% [STATLIST, DOCINFO] = DOXYREAD(FILENAME) also returns a cell array
% containing details for each keyword (frequency in each file where it
% appears and the URL).
%
% See also DOXYSEARCH, DOXYWRITE
% Copyright (C) 2003 Guillaume Flandin <[email protected]>
% $Revision: 1.0 $Date: 2003/05/10 17:41:21 $
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% See <http://www.doxygen.org/> for more details.
error(nargchk(0,1,nargin));
if nargin == 0,
filename = 'search.idx';
end
%- Open the search index file
[fid, errmsg] = fopen(filename,'r','ieee-be');
if fid == -1, error(errmsg); end
%- 4 byte header (DOXS)
header = char(fread(fid,4,'uchar'))';
%- 256*256*4 byte index
idx = fread(fid,256*256,'uint32');
idx = reshape(idx,256,256);
%- Extract list of words
i = find(idx);
statlist = cell(0,2);
for j=1:length(i)
fseek(fid, idx(i(j)), 'bof');
statw = readString(fid);
while ~isempty(statw)
statidx = readInt(fid);
statlist{end+1,1} = statw; % word
statlist{end,2} = statidx; % index
statw = readString(fid);
end
end
%- Extract occurence frequency of each word and docs info (name and url)
docinfo = cell(size(statlist,1),1);
for k=1:size(statlist,1)
fseek(fid, statlist{k,2}, 'bof');
numdoc = readInt(fid);
docinfo{k} = cell(numdoc,4);
for m=1:numdoc
docinfo{k}{m,1} = readInt(fid); % idx
docinfo{k}{m,2} = readInt(fid); % freq
end
for m=1:numdoc
fseek(fid, docinfo{k}{m,1}, 'bof');
docinfo{k}{m,3} = readString(fid); % name
docinfo{k}{m,4} = readString(fid); % url
end
docinfo{k} = reshape({docinfo{k}{:,2:4}},numdoc,[]);
end
%- Close the search index file
fclose(fid);
%- Remove indexes
statlist = {statlist{:,1}}';
%===========================================================================
function s = readString(fid)
s = '';
while 1
w = fread(fid,1,'uchar');
if w == 0, break; end
s(end+1) = char(w);
end
%===========================================================================
function i = readInt(fid)
i = fread(fid,1,'uint32');
|
github
|
P-Chao/acfdetect-master
|
imwrite2split.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/imwrite2split.m
| 1,617 |
utf_8
|
4222fd45df123e6dec9ef40ae793004f
|
% Writes/reads a large set of images into/from multiple directories.
%
% This is useful since certain OS handle very large directories (of say
% >20K images) rather poorly (I'm talking to you Bill). Thus, can take
% 100K images, and write into 5 separate directories, then read them back
% in.
%
% USAGE
% I = imwrite2split( I, nSplits, spliti, path, [varargin] )
%
% INPUTS
% I - image or images (if [] reads else writes)
% nSplits - number of directories to split data into
% spliti - first split number
% path - directory where images are
% writePrms - [varargin] parameters to imwrite2
%
% OUTPUTS
% I - image or images (read from disk if input I=[])
%
% EXAMPLE
% load images; clear IDXi IDXv t video videos;
% imwrite2split( images(:,:,1:10), 2, 0, 'rats', 'rats', 'png', 5 );
% images2=imwrite2split( [], 2, 0, 'rats', 'rats', 'png', 5 );
%
% See also IMWRITE2
% Piotr's Image&Video Toolbox Version NEW
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function I = imwrite2split( I, nSplits, spliti, path, varargin )
n = size(I,3); if( isempty(I) ); n=0; end
nSplits = min(n,nSplits);
for s=1:nSplits
pathSplit = [path int2str2(s-1+spliti,2)];
if( n>0 ) % write
nPerDir = ceil( n / nSplits );
ISplit = I(:,:,1:min(end,nPerDir));
imwrite2( ISplit, nPerDir>1, 0, pathSplit, varargin{:} );
if( s~=nSplits ); I = I(:,:,(nPerDir+1):end); end
else % read
ISplit = imwrite2( [], 1, 0, pathSplit, varargin{:} );
I = cat(3,I,ISplit);
end
end
|
github
|
P-Chao/acfdetect-master
|
playmovies.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/playmovies.m
| 1,935 |
utf_8
|
ef2eaad8a130936a1a281f1277ca0ea1
|
% [4D] shows R videos simultaneously as a movie.
%
% Plays a movie.
%
% USAGE
% playmovies( I, [fps], [loop] )
%
% INPUTS
% I - MxNxTxR or MxNx1xTxR or MxNx3xTxR array (if MxNxT calls
% playmovie)
% fps - [100] maximum number of frames to display per second use
% fps==0 to introduce no pause and have the movie play as
% fast as possible
% loop - [0] number of time to loop video (may be inf),
% if neg plays video forward then backward then forward etc.
%
% OUTPUTS
%
% EXAMPLE
% load( 'images.mat' );
% playmovies( videos );
%
% See also MONTAGES, PLAYMOVIE, MAKEMOVIES
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function playmovies( I, fps, loop )
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n PLAYMOVIE is its '...
'recommended replacement.'],upper(mfilename));
if( nargin<2 || isempty(fps)); fps = 100; end
if( nargin<3 || isempty(loop)); loop = 1; end
playmovie( I, fps, loop )
%
% nd=ndims(I); siz=size(I); nframes=siz(end-1);
% if( nd==3 ); playmovie( I, fps, loop ); return; end
% if( iscell(I) ); error('cell arrays not supported.'); end
% if( ~(nd==4 || (nd==5 && any(size(I,3)==[1 3]))) )
% error('unsupported dimension of I'); end
% inds={':'}; inds=inds(:,ones(1,nd-2));
% clim = [min(I(:)),max(I(:))];
%
% h=gcf; colormap gray; figure(h); % bring to focus
% for nplayed = 1 : abs(loop)
% if( loop<0 && mod(nplayed,2)==1 )
% order = nframes:-1:1;
% else
% order = 1:nframes;
% end
% for i=order
% tic; try disc=get(h); catch return; end %#ok<NASGU>
% montage2(squeeze(I(inds{:},i,:)),1,[],clim);
% title(sprintf('frame %d of %d',i,nframes));
% if(fps>0); pause(1/fps - toc); else pause(eps); end
% end
% end
|
github
|
P-Chao/acfdetect-master
|
pca_apply_large.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/pca_apply_large.m
| 2,062 |
utf_8
|
af84a2179b9d8042519bc6b378736a88
|
% Wrapper for pca_apply that allows for application to large X.
%
% Wrapper for pca_apply that splits and processes X in parts, this may be
% useful if processing cannot be done fully in parallel because of memory
% constraints. See pca_apply for usage.
%
% USAGE
% same as pca_apply
%
% INPUTS
% same as pca_apply
%
% OUTPUTS
% same as pca_apply
%
% EXAMPLE
%
% See also PCA, PCA_APPLY, PCA_VISUALIZE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function [ Yk, Xhat, avsq ] = pca_apply_large( X, U, mu, vars, k )
siz = size(X); nd = ndims(X); [N,r] = size(U);
if(N==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
inds = {':'}; inds = inds(:,ones(1,nd-1));
d= prod(siz(1:end-1));
% some error checking
if(d~=N); error('incorrect size for X or U'); end
if(isa(X,'uint8')); X = double(X); end
if( k>r )
warning(['Only ' int2str(r) '<k comp. available.']); %#ok<WNTAG>
k=r;
end
% Will run out of memory if X has too many elements. Hence, run
% pca_apply on parts of X and recombine.
maxwidth = ceil( (10^7) / d );
if(maxwidth > siz(end))
if (nargout==1)
Yk = pca_apply( X, U, mu, vars, k );
elseif (nargout==2)
[Yk, Xhat] = pca_apply( X, U, mu, vars, k );
else
[ Yk, Xhat, avsq ] = pca_apply( X, U, mu, vars, k );
end
else
Yk = zeros( k, siz(end) ); Xhat = zeros( siz );
avsq = 0; avsqOrig = 0; last = 0;
while(last < siz(end))
first=last+1; last=min(first+maxwidth-1,siz(end));
Xi = X(inds{:}, first:last);
if( nargout==1 )
Yki = pca_apply( Xi, U, mu, vars, k );
else
if( nargout==2 )
[Yki,Xhati] = pca_apply( Xi, U, mu, vars, k );
else
[Yki,Xhati,avsqi,avsqOrigi] = pca_apply( Xi, U, mu, vars, k );
avsq = avsq + avsqi; avsqOrig = avsqOrig + avsqOrigi;
end;
Xhat(inds{:}, first:last ) = Xhati;
end
Yk( :, first:last ) = Yki;
end;
if( nargout==3); avsq = avsq / avsqOrig; end
end
|
github
|
P-Chao/acfdetect-master
|
montages2.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/montages2.m
| 2,269 |
utf_8
|
505e2be915d65fff8bfef8473875cc98
|
% MONTAGES2 [4D] Used to display R sets of T images each.
%
% Displays one montage (see montage2) per row. Each of the R image sets is
% flattened to a single long image by concatenating the T images in the
% set. Alternative to montages.
%
% USAGE
% varargout = montages2( IS, [montage2prms], [padSiz] )
%
% INPUTS
% IS - MxNxTxR or MxNx1xTxR or MxNx3xTxR array
% montage2prms - [] params for montage2; ex: {showLns,extraInf}
% padSiz - [4] total amount of vertical or horizontal padding
%
% OUTPUTS
% I - 3D or 4D array of flattened images, disp with montage2
% mm - #montages/row
% nn - #montages/col
%
% EXAMPLE
% load( 'images.mat' );
% imageclusters = clustermontage( images, IDXi, 16, 1 );
% montages2( imageclusters );
%
% See also MONTAGES, MAKEMOVIES, MONTAGE2, CLUSTERMONTAGE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function varargout = montages2( IS, montage2prms, padSiz )
if( nargin<2 || isempty(montage2prms) ); montage2prms = {}; end
if( nargin<3 || isempty(padSiz) ); padSiz = 4; end
[padSiz,er] = checknumericargs( padSiz,[1 1], 0, 1 ); error(er);
% get/test image format info
nd = ndims(IS); siz = size(IS);
if( nd==5 ) %MxNx1xTxR or MxNx3xTxR
nch = size(IS,3);
if( nch~=1 && nch~=3 ); error('illegal image stack format'); end
if( nch==1 ); IS = squeeze(IS); nd=4; siz=size(IS); end
end
if ~any(nd==3:5)
error('unsupported dimension of IS');
end
% reshape IS so that each 3D element is concatenated to a 2D image, adding
% padding
padEl = max(IS(:));
IS=arraycrop2dims(IS, [siz(1)+padSiz siz(2:end)], padEl ); %UD pad
siz=size(IS);
if(nd==3) % reshape bw single
IS=squeeze( reshape( IS, siz(1), [] ) );
elseif(nd==4) % reshape bw
IS=squeeze( reshape( IS, siz(1), [], siz(4) ) );
else % reshape color
IS=squeeze( reshape(permute(IS,[1 2 4 3 5]),siz(1),[],siz(3),siz(5)));
end; siz = size(IS);
IS=arraycrop2dims(IS, [siz(1) siz(2)+padSiz siz(3:end)], padEl);
% show using montage2
varargout = cell(1,nargout);
if( nargout); varargout{1}=IS; end;
[varargout{2:end}] = montage2( IS, montage2prms{:} );
title(inputname(1));
|
github
|
P-Chao/acfdetect-master
|
filter_gauss_1D.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/filter_gauss_1D.m
| 1,137 |
utf_8
|
94a453b82dcdeba67bd886e042d552d9
|
% 1D Gaussian filter.
%
% Equivalent to (but faster then):
% f = fspecial('Gaussian',[2*r+1,1],sigma);
% f = filter_gauss_nD( 2*r+1, r+1, sigma^2 );
%
% USAGE
% f = filter_gauss_1D( r, sigma, [show] )
%
% INPUTS
% r - filter size=2r+1, if r=[] -> r=ceil(2.25*sigma)
% sigma - standard deviation of filter
% show - [0] figure to use for optional display
%
% OUTPUTS
% f - 1D Gaussian filter
%
% EXAMPLE
% f1 = filter_gauss_1D( 10, 2, 1 );
% f2 = filter_gauss_nD( 21, [], 2^2, 2);
%
% See also FILTER_BINOMIAL_1D, FILTER_GAUSS_ND, FSPECIAL
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function f = filter_gauss_1D( r, sigma, show )
if( nargin<3 || isempty(show) ); show=0; end
if( isempty(r) ); r = ceil(sigma*2.25); end
if( mod(r,1)~=0 ); error( 'r must be an integer'); end
% compute filter
x = -r:r;
f = exp(-(x.*x)/(2*sigma*sigma))';
f(f<eps*max(f(:))*10) = 0;
sumf = sum(f(:)); if(sumf~=0); f = f/sumf; end
% display
if(show); filter_visualize_1D( f, show ); end
|
github
|
P-Chao/acfdetect-master
|
clfEcoc.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/clfEcoc.m
| 1,493 |
utf_8
|
e77e1b4fd5469ed39f47dd6ed15f130f
|
function clf = clfEcoc(p,clfInit,clfparams,nclasses,use01targets)
% Wrapper for ecoc that makes ecoc compatible with nfoldxval.
%
% Requires the SVM toolbox by Anton Schwaighofer.
%
% USAGE
% clf = clfEcoc(p,clfInit,clfparams,nclasses,use01targets)
%
% INPUTS
% p - data dimension
% clfInit - binary classifier init (see nfoldxval)
% clfparams - binary classifier parameters (see nfoldxval)
% nclasses - num of classes (currently 3<=nclasses<=7 suppored)
% use01targets - see ecoc
%
% OUTPUTS
% clf - see ecoc
%
% EXAMPLE
%
% See also ECOC, NFOLDXVAL, CLFECOCCODE
%
% Piotr's Image&Video Toolbox Version 2.0
% Copyright 2008 Piotr Dollar. [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Lesser GPL [see external/lgpl.txt]
if( nclasses<3 || nclasses>7 )
error( 'currently only works if 3<=nclasses<=7'); end;
if( nargin<5 || isempty(use01targets)); use01targets=0; end;
% create code (limited for now)
[C,nbits] = clfEcocCode( nclasses );
clf = ecoc(nclasses, nbits, C, use01targets ); % didn't use to pass use01?
clf.verbosity = 0; % don't diplay output
% initialize and temporarily store binary learner
clf.templearner = feval( clfInit, p, clfparams{:} );
% ecoctrain2 is custom version of ecoctrain
clf.funTrain = @clfEcocTrain;
clf.funFwd = @ecocfwd;
function clf = clfEcocTrain( clf, varargin )
clf = ecoctrain( clf, clf.templearner, varargin{:} );
|
github
|
P-Chao/acfdetect-master
|
getargs.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/getargs.m
| 3,455 |
utf_8
|
de2bab917fa6b9ba3099f1c6b6d68cf0
|
% Utility to process parameter name/value pairs.
%
% DEPRECATED -- ONLY USED BY KMEANS2? SHOULD BE REMOVED.
% USE GETPARAMDEFAULTS INSTEAD.
%
% Based on code fromt Matlab Statistics Toolobox's "private/statgetargs.m"
%
% [EMSG,A,B,...]=GETARGS(PNAMES,DFLTS,'NAME1',VAL1,'NAME2',VAL2,...)
% accepts a cell array PNAMES of valid parameter names, a cell array DFLTS
% of default values for the parameters named in PNAMES, and additional
% parameter name/value pairs. Returns parameter values A,B,... in the same
% order as the names in PNAMES. Outputs corresponding to entries in PNAMES
% that are not specified in the name/value pairs are set to the
% corresponding value from DFLTS. If nargout is equal to length(PNAMES)+1,
% then unrecognized name/value pairs are an error. If nargout is equal to
% length(PNAMES)+2, then all unrecognized name/value pairs are returned in
% a single cell array following any other outputs.
%
% EMSG is empty if the arguments are valid, or the text of an error message
% if an error occurs. GETARGS does not actually throw any errors, but
% rather returns an error message so that the caller may throw the error.
% Outputs will be partially processed after an error occurs.
%
% USAGE
% [emsg,varargout]=getargs(pnames,dflts,varargin)
%
% INPUTS
% pnames - cell of valid parameter names
% dflts - cell of default parameter values
% varargin - list of proposed name / value pairs
%
% OUTPUTS
% emsg - error msg - '' if no error
% varargout - list of assigned name / value pairs
%
% EXAMPLE
% pnames = {'color' 'linestyle', 'linewidth'}; dflts = { 'r','_','1'};
% v = {'linew' 2 'nonesuch' [1 2 3] 'linestyle' ':'};
% [emsg,color,linestyle,linewidth,unrec] = getargs(pnames,dflts,v{:}) % ok
% [emsg,color,linestyle,linewidth] = getargs(pnames,dflts,v{:}) % err
%
% See also GETPARAMDEFAULTS
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function [emsg,varargout]=getargs(pnames,dflts,varargin)
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n It will be ' ...
'removed in the next version of the toolbox.'],upper(mfilename));
% We always create (nparams+1) outputs:
% one for emsg
% nparams varargs for values corresponding to names in pnames
% If they ask for one more (nargout == nparams+2), it's for unrecognized
% names/values
emsg = '';
nparams = length(pnames);
varargout = dflts;
unrecog = {};
nargs = length(varargin);
% Must have name/value pairs
if mod(nargs,2)~=0
emsg = sprintf('Wrong number of arguments.');
else
% Process name/value pairs
for j=1:2:nargs
pname = varargin{j};
if ~ischar(pname)
emsg = sprintf('Parameter name must be text.');
break;
end
i = strmatch(lower(pname),lower(pnames));
if isempty(i)
% if they've asked to get back unrecognized names/values, add this
% one to the list
if nargout > nparams+1
unrecog((end+1):(end+2)) = {varargin{j} varargin{j+1}};
% otherwise, it's an error
else
emsg = sprintf('Invalid parameter name: %s.',pname);
break;
end
elseif length(i)>1
emsg = sprintf('Ambiguous parameter name: %s.',pname);
break;
else
varargout{i} = varargin{j+1};
end
end
end
varargout{nparams+1} = unrecog;
|
github
|
P-Chao/acfdetect-master
|
normxcorrn_fg.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/normxcorrn_fg.m
| 2,699 |
utf_8
|
e65c38d97efb3a624e0fa94a97f75eb6
|
% Normalized n-dimensional cross-correlation with a mask.
%
% Similar to normxcorrn, except takes an additional argument that specifies
% a figure ground mask for the T. That is T_fg must be of the same
% dimensions as T, with each entry being 0 or 1, where zero specifies
% regions to ignore (the ground) and 1 specifies interesting regions (the
% figure). Essentially T_fg specifies regions in T that are interesting
% and should be taken into account when doing normalized cross correlation.
% This allows for templates of arbitrary shape, and not just squares.
%
% Note: this function is approximately 3 times slower then normxcorr2
% because it cannot use the trick of precomputing sums.
%
% USAGE
% C = normxcorrn_fg( T, T_fg, A, [shape] )
%
% INPUTS
% T - template to correlate to each window in A
% T_fg - figure/ground mask for the template
% A - matrix to correlate T to
% shape - ['full'] 'valid', 'full', or 'same', see convn_fast help
%
% OUTPUTS
% C - correlation matrix
%
% EXAMPLE
% A=rand(50); B=rand(11); Bfg=ones(11);
% C1=normxcorrn_fg(B,Bfg,A); C2=normxcorr2(B,A);
% figure(1); im(C1); figure(2); im(C2);
% figure(3); im(abs(C1-C2));
%
% See also NORMXCORRN
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function C = normxcorrn_fg( T, T_fg, A, shape )
if( nargin <4 || isempty(shape)); shape='full'; end;
if( ndims(T)~=ndims(A) || ndims(T)~=ndims(T_fg) )
error('TEMPALTE, T_fg, and A must have same number of dimensions'); end;
if( any(size(T)~=size(T_fg)))
error('TEMPALTE and T_fg must have same dimensions'); end;
if( ~all(T_fg==0 | T_fg==1))
error('T_fg may have only entries either 0 or 1'); end;
nkeep = sum(T_fg(:));
if( nkeep==0); error('T_fg must have some nonzero values'); end;
% center T on 0 and normalize magnitued to 1, excluding ground
% T= (T-T_av) / ||(T-T_av)||
T(T_fg==0)=0;
T = T - sum(T(:)) / nkeep;
T(T_fg==0)=0;
T = T / norm( T(:) );
% flip for convn_fast purposes
for d=1:ndims(T); T = flipdim(T,d); end;
for d=1:ndims(T_fg); T_fg = flipdim(T_fg,d); end;
% get average over each window over A
A_av = convn_fast( A, T_fg/nkeep, shape );
% get magnitude over each window over A "mag(WA-WAav)"
% We can rewrite the above as "sqrt(SUM(WAi^2)-n*WAav^2)". so:
A_mag = convn_fast( A.*A, T_fg, shape ) - nkeep * A_av .* A_av;
A_mag = sqrt(A_mag); A_mag(A_mag<.000001)=1; %removes divide by 0 error
% finally get C. in each image window, we will now do:
% "dot(T,(WA-WAav)) / mag(WA-WAav)"
C = convn_fast(A,T,shape) - A_av*sum(T(:));
C = C ./ A_mag;
|
github
|
P-Chao/acfdetect-master
|
makemovie.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/makemovie.m
| 1,266 |
utf_8
|
9a03d9a5227c4eaa86520f206ce283e7
|
% [3D] Used to convert a stack of T images into a movie.
%
% To display same data statically use montage.
%
% USAGE
% M = makemovies( IS )
%
% INPUTS
% IS - MxNxT or MxNx1xT or MxNx3xT array of movies.
%
% OUTPUTS
% M - resulting movie
%
% EXAMPLE
% load( 'images.mat' );
% M = makemovie( videos(:,:,:,1) );
% movie( M );
%
% See also MONTAGE2, MAKEMOVIES, PLAYMOVIE, CELL2ARRAY, FEVALARRAYS,
% IMMOVIE, MOVIE2AVI
% Piotr's Image&Video Toolbox Version NEW
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function M = makemovie( IS )
% get images format (if image stack is MxNxT convert to MxNx1xT)
if (ndims(IS)==3); IS = permute(IS, [1,2,4,3] ); end
siz = size(IS); nch = siz(3); nd = ndims(IS);
if ( nd~=4 ); error('unsupported dimension of IS'); end
if( nch~=1 && nch~=3 ); error('illegal image stack format'); end;
% normalize for maximum contrast
if( isa(IS,'double') ); IS = IS - min(IS(:)); IS = IS / max(IS(:)); end
% make movie
for i=1:siz(4)
Ii=IS(:,:,:,i);
if( nch==1 ); [Ii,Mi] = gray2ind( Ii ); else Mi=[]; end
if i==1
M=repmat(im2frame( Ii, Mi ),[1,siz(4)]);
else
M(i) = im2frame( Ii, Mi );
end
end
|
github
|
P-Chao/acfdetect-master
|
localsum_block.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/localsum_block.m
| 815 |
utf_8
|
1216b03a3bd44ff1fc3256de16a2f1c6
|
% Calculates the sum in non-overlapping blocks of I of size dims.
%
% Similar to localsum except gets sum in non-overlapping windows.
% Equivalent to doing localsum, and then subsampling (except more
% efficient).
%
% USAGE
% I = localsum_block( I, dims )
%
% INPUTS
% I - matrix to compute sum over
% dims - size of volume to compute sum over
%
% OUTPUTS
% I - resulting array
%
% EXAMPLE
% load trees; I=ind2gray(X,map);
% I2 = localsum_block( I, 11 );
% figure(1); im(I); figure(2); im(I2);
%
% See also LOCALSUM
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function I = localsum_block( I, dims )
I = nlfiltblock_sep( I, dims, @rnlfiltblock_sum );
|
github
|
P-Chao/acfdetect-master
|
imrotate2.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/imrotate2.m
| 1,326 |
utf_8
|
bb2ff6c3138ce5f53154d58d7ebc4f31
|
% Custom version of imrotate that demonstrates use of apply_homography.
%
% Works exactly the same as imrotate. For usage see imrotate.
%
% USAGE
% IR = imrotate2( I, angle, [method], [bbox] )
%
% INPUTS
% I - 2D image [converted to double]
% angle - angle to rotate in degrees
% method - ['linear'] 'nearest', 'linear', 'spline', 'cubic'
% bbox - ['loose'] 'loose' or 'crop'
%
% OUTPUTS
% IR - rotated image
%
% EXAMPLE
% load trees;
% tic; X1 = imrotate( X, 55, 'bicubic' ); toc,
% tic; X2 = imrotate2( X, 55, 'bicubic' ); toc
% clf; subplot(2,2,1); im(X); subplot(2,2,2); im(X1-X2);
% subplot(2,2,3); im(X1); subplot(2,2,4); im(X2);
%
% See also IMROTATE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = imrotate2( I, angle, method, bbox )
if( ~isa( I, 'double' ) ); I = double(I); end
if( nargin<3 || isempty(method)); method='linear'; end
if( nargin<4 || isempty(bbox) ); bbox='loose'; end
if( strcmp(method,'bilinear') || strcmp(method,'lin')); method='linear';end
% convert arguments for apply_homography
angle_rads = angle /180 * pi;
R = rotationMatrix( angle_rads );
H = [R [0;0]; 0 0 1];
IR = apply_homography( I, H, method, bbox );
|
github
|
P-Chao/acfdetect-master
|
imSubsResize.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/imSubsResize.m
| 1,338 |
utf_8
|
cd7dedf790c015adfb1f2d620e9ed82f
|
% Resizes subs by resizVals.
%
% Resizes subs in subs/vals image representation by resizVals.
%
% This essentially replaces each sub by sub.*resizVals. The only subtlety
% is that in images the leftmost sub value is .5, so for example when
% resizing by a factor of 2, the first pixel is replaced by 2 pixels and so
% location 1 in the original image goes to location 1.5 in the second
% image, NOT 2. It may be necessary to round the values afterward.
%
% USAGE
% subs = imSubsResize( subs, resizVals, [zeroPnt] )
%
% INPUTS
% subs - subscripts of point locations (n x d)
% resizVals - k element vector of shrinking factors
% zeroPnt - [.5] See comment above.
%
% OUTPUTS
% subs - transformed subscripts of point locations (n x d)
%
% EXAMPLE
% subs = imSubsResize( [1 1; 2 2], [2 2] )
%
%
% See also IMSUBSTOARRAY
% Piotr's Image&Video Toolbox Version NEW
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function subs = imSubsResize( subs, resizVals, zeroPnt )
if( nargin<3 || isempty(zeroPnt) ); zeroPnt=.5; end
[n d] = size(subs);
[resizVals,er] = checkNumArgs( resizVals, [1 d], -1, 2 ); error(er);
% transform subs
resizVals = repmat( resizVals, [n, 1] );
subs = (subs - zeroPnt) .* resizVals + zeroPnt;
|
github
|
P-Chao/acfdetect-master
|
imtranslate.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/imtranslate.m
| 1,183 |
utf_8
|
054727fb31c105414b655c0f938b6ced
|
% Translate an image to subpixel accuracy.
%
% Note that for subplixel accuracy cannot use nearest neighbor interp.
%
% USAGE
% IR = imtranslate( I, dx, dy, [method], [bbox] )
%
% INPUTS
% I - 2D image [converted to double]
% dx - x translation (right)
% dy - y translation (up)
% method - ['linear'] 'nearest', 'linear', 'spline', 'cubic'
% bbox - ['loose'] 'loose' or 'crop'
%
% OUTPUTS
% IR - translated image
%
% EXAMPLE
% load trees;
% XT = imtranslate(X,0,1.5,'bicubic','crop');
% figure(1); im(X,[0 255]); figure(2); im(XT,[0 255]);
%
% See also IMROTATE2
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = imtranslate( I, dx, dy, method, bbox )
if( ~isa( I, 'double' ) ); I = double(I); end
if( nargin<4 || isempty(method)); method='linear'; end
if( nargin<5 || isempty(bbox) ); bbox='loose'; end
if( strcmp(method,'bilinear') || strcmp(method,'lin')); method='linear';end
% convert arguments for apply_homography
H = [eye(2) [dy; dx]; 0 0 1];
IR = apply_homography( I, H, method, bbox );
|
github
|
P-Chao/acfdetect-master
|
randperm2.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/randperm2.m
| 1,398 |
utf_8
|
5007722f3d5f5ba7c0f83f32ef8a3a2c
|
% Returns a random permutation of integers.
%
% randperm2(n) is a random permutation of the integers from 1 to n. For
% example, randperm2(6) might be [2 4 5 6 1 3]. randperm2(n,k) is only
% returns the first k elements of the permuation, so for example
% randperm2(6) might be [2 4]. This is a faster version of randperm.m if
% only need first k<<n elements of the random permutation. Also uses less
% random bits (only k). Note that this is an implementation O(k), versus
% the matlab implementation which is O(nlogn), however, in practice it is
% often slower for k=n because it uses a loop.
%
% USAGE
% p = randperm2( n, k )
%
% INPUTS
% n - permute 1:n
% k - keep only first k outputs
%
% OUTPUTS
% p - k length vector of permutations
%
% EXAMPLE
% randperm2(10,5)
%
% See also RANDPERM
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function p = randperm2( n, k )
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n RANDSAMPLE is its '...
'recommended replacement.'],upper(mfilename));
p = randsample( n, k );
%if (nargin<2); k=n; else k = min(k,n); end
% p = 1:n;
% for i=1:k
% r = i + floor( (n-i+1)*rand );
% t = p(r); p(r) = p(i); p(i) = t;
% end
% p = p(1:k);
|
github
|
P-Chao/acfdetect-master
|
apply_homography.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/apply_homography.m
| 3,582 |
utf_8
|
9c3ed72d35b1145f41114e6e6135b44f
|
% Applies the homography defined by H on the image I.
%
% Takes the center of the image as the origin, not the top left corner.
% Also, the coordinate system is row/ column format, so H must be also.
%
% The bounding box of the image is set by the BBOX argument, a string that
% can be 'loose' (default) or 'crop'. When BBOX is 'loose', IR includes the
% whole transformed image, which generally is larger than I. When BBOX is
% 'crop' IR is cropped to include only the central portion of the
% transformed image and is the same size as I. Preserves I's type.
%
% USAGE
% IR = apply_homography( I, H, [method], [bbox], [show] )
%
% INPUTS
% I - input black and white image (2D double or unint8 array)
% H - 3x3 nonsingular homography matrix
% method - ['linear'] for interp2 'nearest','linear','spline','cubic'
% bbox - ['loose'] see above for meaning of bbox 'loose','crop')
% show - [0] figure to use for optional display
%
% OUTPUTS
% IR - result of applying H to I.
%
% EXAMPLE
% load trees; I=X;
% R = rotationMatrix( pi/4 ); T = [1; 3]; H = [R T; 0 0 1];
% IR = apply_homography( I, H, [], 'crop', 1 );
%
% See also TEXTURE_MAP, IMROTATE2
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = apply_homography( I, H, method, bbox, show )
if( ndims(I)~=2 ); error('I must a MxN array'); end;
if(any(size(H)~=[3 3])); error('H must be 3 by 3'); end;
if(rank(H)~=3); error('H must be full rank.'); end;
if( nargin<3 || isempty(method)); method='linear'; end;
if( nargin<4 || isempty(bbox)); bbox='loose'; end;
if( nargin<5 || isempty(show)); show=0; end;
classname = class( I );
if(~strcmp(classname,'double')); I = double(I); end
I = padarray(I,[3,3],eps,'both');
siz = size(I);
% set origin to be center of image
rstart = (-siz(1)+1)/2; rend = (siz(1)-1)/2;
cstart = (-siz(2)+1)/2; cend = (siz(2)-1)/2;
% If 'bbox' then get bounds of resulting image. To do this project the
% original points accoring to the homography and see the bounds. Note
% that since a homography maps a quadrilateral to a quadrilateral only
% need to look at where the bounds of the quadrilateral are mapped to.
% If 'same' then simply use the original image bounds.
if (strcmp(bbox,'loose'))
pr = H * [rstart rend rstart rend; cstart cstart cend cend; 1 1 1 1];
row_dest = pr(1,:) ./ pr(3,:); col_dest = pr(2,:) ./ pr(3,:);
minr = floor(min(row_dest(:))); maxr = ceil(max(row_dest(:)));
minc = floor(min(col_dest(:))); maxc = ceil(max(col_dest(:)));
elseif (strcmp(bbox,'crop'))
minr = rstart; maxr = rend;
minc = cstart; maxc = cend;
else
error('illegal value for bbox');
end;
mrows = maxr-minr+1;
ncols = maxc-minc+1;
% apply inverse homography on meshgrid in destination image
[col_dest_grid,row_dest_grid] = meshgrid( minc:maxc, minr:maxr );
pr = inv(H) * [row_dest_grid(:)'; col_dest_grid(:)'; ones(1,mrows*ncols)];
row_sample_locs = pr(1,:) ./ pr(3,:) + (siz(1)+1)/2;
row_sample_locs = reshape(row_sample_locs,mrows,ncols);
col_sample_locs = pr(2,:) ./ pr(3,:) + (siz(2)+1)/2;
col_sample_locs = reshape(col_sample_locs,mrows,ncols);
% now texture map results
IR = interp2( I, col_sample_locs, row_sample_locs, method );
IR(isnan(IR)) = 0;
IR = arraycrop2dims( IR, size(IR)-6 ); %undo extra padding
if(~strcmp(classname,'double')); IR=feval(classname,IR ); end
% optionally show
if ( show)
I = arraycrop2dims( I, size(IR)-2 );
figure(show); clf; im(I);
figure(show+1); clf; im(IR);
end
|
github
|
P-Chao/acfdetect-master
|
pca_apply.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/pca_apply.m
| 2,427 |
utf_8
|
0831befb6057f8502bc492227455019a
|
% Companion function to pca.
%
% Use pca to retrieve the principal components U and the mean mu from a
% set fo vectors X1 via [U,mu,vars] = pca(X1). Then given a new
% vector x, use y = pca_apply( x, U, mu, vars, k ) to get the first k
% coefficients of x in the space spanned by the columns of U. See pca for
% general information.
%
% This may prove useful:
% siz = size(X); k = 100;
% Uim = reshape( U(:,1:k), [ siz(1:end-1) k ] );
%
% USAGE
% [ Yk, Xhat, avsq, avsqOrig ] = pca_apply( X, U, mu, vars, k )
%
% INPUTS
% X - array for which to get PCA coefficients
% U - [returned by pca] -- see pca
% mu - [returned by pca] -- see pca
% vars - [returned by pca] -- see pca
% k - number of principal coordinates to approximate X with
%
% OUTPUTS
% Yk - first k coordinates of X in column space of U
% Xhat - approximation of X corresponding to Yk
% avsq - measure of squared error normalized to fall between [0,1]
%
% EXAMPLE
%
% See also PCA, PCA_VISUALIZE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function [Yk,Xhat,avsq,avsqOrig] = pca_apply(X,U,mu,vars,k) %#ok<INUSL>
siz = size(X); nd = ndims(X); [N,r] = size(U);
if(N==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
inds = {':'}; inds = inds(:,ones(1,nd-1));
d= prod(siz(1:end-1));
% some error checking
if(d~=N); error('incorrect size for X or U'); end
if(isa(X,'uint8')); X = double(X); end
if( k>r )
warning(['Only ' int2str(r) '<k comp. available.']); %#ok<WNTAG>
k=r;
end
% subtract mean, then flatten X
Xorig = X;
murep = mu( inds{:}, ones(1,siz(end)));
X = X - murep;
X = reshape(X, d, [] );
% Find Yk, the first k coefficients of X in the new basis
k = min( r, k );
Uk = U(:,1:k);
Yk = Uk' * X;
% calculate Xhat - the approx of X using the first k princ components
if( nargout>1 )
Xhat = Uk * Yk;
Xhat = reshape( Xhat, siz );
Xhat = Xhat + murep;
end
% caclulate average value of (Xhat-Xorig).^2 compared to average value
% of X.^2, where X is Xorig without the mean. This is equivalent to
% what fraction of the variance is captured by Xhat.
if( nargout>2 )
avsq = Xhat - Xorig;
avsq = dot(avsq(:),avsq(:));
avsqOrig = dot(X(:),X(:));
if (nargout==3)
avsq = avsq / avsqOrig;
end
end
|
github
|
P-Chao/acfdetect-master
|
mode2.m
|
.m
|
acfdetect-master/toolbox/external/deprecated/mode2.m
| 731 |
utf_8
|
5c9321ef4b610b4f4a2d43902a68838e
|
% Returns the mode of a vector.
%
% Was mode not part of Matlab before?
%
% USAGE
% y = mode2( x )
%
% INPUTS
% x - vector of integers
%
% OUTPUTS
% y - mode
%
% EXAMPLE
% x = randint2( 1, 10, [1 3] )
% mode(x), mode2( x )
%
% See also MODE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function y = mode2( x )
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n MODE is its '...
'recommended replacement.'],upper(mfilename));
y = mode( x );
% [b,i,j] = unique(x);
% [ mval, ind ] = max(hist(j,length(b)));
% y = b(ind);
|
github
|
P-Chao/acfdetect-master
|
savefig.m
|
.m
|
acfdetect-master/toolbox/external/other/savefig.m
| 13,459 |
utf_8
|
2b8463f9b01ceb743e440d8fb5755829
|
function savefig(fname, varargin)
% Usage: savefig(filename, fighdl, options)
%
% Saves a pdf, eps, png, jpeg, and/or tiff of the contents of the fighandle's (or current) figure.
% It saves an eps of the figure and the uses Ghostscript to convert to the other formats.
% The result is a cropped, clean picture. There are options for using rgb or cmyk colours,
% or grayscale. You can also choose the resolution.
%
% The advantage of savefig is that there is very little empty space around the figure in the
% resulting files, you can export to more than one format at once, and Ghostscript generates
% trouble-free files.
%
% If you find any errors, please let me know! (peder at axensten dot se)
%
% filename: File name without suffix.
%
% fighdl: (default: gcf) Integer handle to figure.
%
% options: (default: '-r300', '-lossless', '-rgb') You can define your own
% defaults in a global variable savefig_defaults, if you want to, i.e.
% savefig_defaults= {'-r200','-gray'};.
% 'eps': Output in Encapsulated Post Script (no preview yet).
% 'pdf': Output in (Adobe) Portable Document Format.
% 'png': Output in Portable Network Graphics.
% 'jpeg': Output in Joint Photographic Experts Group format.
% 'tiff': Output in Tagged Image File Format (no compression: huge files!).
% '-rgb': Output in rgb colours.
% '-cmyk': Output in cmyk colours (not yet 'png' or 'jpeg' -- '-rgb' is used).
% '-gray': Output in grayscale (not yet 'eps' -- '-rgb' is used).
% '-fonts': Include fonts in eps or pdf. Includes only the subset needed.
% '-lossless': Use lossless compression, works on most formats. same as '-c0', below.
% '-c<float>': Set compression for non-indexed bitmaps in PDFs -
% 0: lossless; 0.1: high quality; 0.5: medium; 1: high compression.
% '-r<integer>': Set resolution.
% '-crop': Removes points and line segments outside the viewing area -- permanently.
% Only use this on figures where many points and/or line segments are outside
% the area zoomed in to. This option will result in smaller vector files (has no
% effect on pixel files).
% '-dbg': Displays gs command line(s).
%
% EXAMPLE:
% savefig('nicefig', 'pdf', 'jpeg', '-cmyk', '-c0.1', '-r250');
% Saves the current figure to nicefig.pdf and nicefig.png, both in cmyk and at 250 dpi,
% with high quality lossy compression.
%
% REQUIREMENT: Ghostscript. Version 8.57 works, probably older versions too, but '-dEPSCrop'
% must be supported. I think version 7.32 or newer is ok.
%
% HISTORY:
% Version 1.0, 2006-04-20.
% Version 1.1, 2006-04-27:
% - No 'epstopdf' stuff anymore! Using '-dEPSCrop' option in gs instead!
% Version 1.2, 2006-05-02:
% - Added a '-dbg' option (see options, above).
% - Now looks for a global variable 'savefig_defaults' (see options, above).
% - More detailed Ghostscript options (user will not really notice).
% - Warns when there is no device for a file-type/color-model combination.
% Version 1.3, 2006-06-06:
% - Added a check to see if there actually is a figure handle.
% - Now works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).
% - Now compatible with Ghostscript 8.54, released 2006-06-01.
% Version 1.4, 2006-07-20:
% - Added an option '-soft' that enables anti-aliasing on pixel graphics (on by default).
% - Added an option '-hard' that don't do anti-aliasing on pixel graphics.
% Version 1.5, 2006-07-27:
% - Fixed a bug when calling with a figure handle argument.
% Version 1.6, 2006-07-28:
% - Added a crop option, see above.
% Version 1.7, 2007-03-31:
% - Fixed bug: calling print with invalid renderer value '-none'.
% - Removed GhostScript argument '-dUseCIEColor' as it sometimes discoloured things.
% Version 1.8, 2008-01-03:
% - Added MacIntel: 'MACI'.
% - Added 64bit PC (I think, can't test it myself).
% - Added option '-nointerpolate' (use it to prevent blurring of pixelated).
% - Removed '-hard' and '-soft'. Use '-nointerpolate' for '-hard', default for '-soft'.
% - Fixed the gs 8.57 warning on UseCIEColor (it's now set).
% - Added '-gray' for pdf, but gs 8.56 or newer is needed.
% - Added '-gray' and '-cmyk' for eps, but you a fairly recent gs might be needed.
% Version 1.9, 2008-07-27:
% - Added lossless compression, see option '-lossless', above. Works on most formats.
% - Added lossy compression, see options '-c<float>...', above. Works on 'pdf'.
% Thanks to Olly Woodford for idea and implementation!
% - Removed option '-nointerpolate' -- now savefig never interpolates.
% - Fixed a few small bugs and removed some mlint comments.
% Version 2.0, 2008-11-07:
% - Added the possibility to include fonts into eps or pdf.
%
% TO DO: (Need Ghostscript support for these, so don't expect anything soon...)
% - svg output.
% - '-cmyk' for 'jpeg' and 'png'.
% - Preview in 'eps'.
% - Embedded vector fonts, not bitmap, in 'eps'.
%
% Copyright (C) Peder Axensten (peder at axensten dot se), 2006.
% KEYWORDS: eps, pdf, jpg, jpeg, png, tiff, eps2pdf, epstopdf, ghostscript
%
% INSPIRATION: eps2pdf (5782), eps2xxx (6858)
%
% REQUIREMENTS: Works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
op_dbg= false; % Default value.
% Compression
compr= [' -dUseFlateCompression=true -dLZWEncodePages=true -dCompatibilityLevel=1.6' ...
' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false ' ...
' -dColorImageFilter=%s -dGrayImageFilter=%s']; % Compression.
lossless= sprintf (compr, '/FlateEncode', '/FlateEncode');
lossy= sprintf (compr, '/DCTEncode', '/DCTEncode' );
lossy= [lossy ' -c ".setpdfwrite << /ColorImageDict << /QFactor %g ' ...
'/Blend 1 /HSample [%s] /VSample [%s] >> >> setdistillerparams"'];
% Create gs command.
cmdEnd= ' -sDEVICE=%s -sOutputFile="%s"'; % Essential.
epsCmd= '';
epsCmd= [epsCmd ' -dSubsetFonts=true -dNOPLATFONTS']; % Future support?
epsCmd= [epsCmd ' -dUseCIEColor=true -dColorConversionStrategy=/UseDeviceIndependentColor'];
epsCmd= [epsCmd ' -dProcessColorModel=/%s']; % Color conversion.
pdfCmd= [epsCmd ' -dAntiAliasColorImages=false' cmdEnd];
epsCmd= [epsCmd cmdEnd];
% Get file name.
if((nargin < 1) || isempty(fname) || ~ischar(fname)) % Check file name.
error('No file name specified.');
end
[pathstr, namestr] = fileparts(fname);
if(isempty(pathstr)), fname= fullfile(cd, namestr); end
% Get handle.
fighdl= get(0, 'CurrentFigure'); % See gcf. % Get figure handle.
if((nargin >= 2) && (numel(varargin{1}) == 1) && isnumeric(varargin{1}))
fighdl= varargin{1};
varargin= {varargin{2:end}};
end
if(isempty(fighdl)), error('There is no figure to save!?'); end
set(fighdl, 'Units', 'centimeters') % Set paper stuff.
sz= get(fighdl, 'Position');
sz(1:2)= 0;
set(fighdl, 'PaperUnits', 'centimeters', 'PaperSize', sz(3:4), 'PaperPosition', sz);
% Set up the various devices.
% Those commented out are not yet supported by gs (nor by savefig).
% pdf-cmyk works due to the Matlab '-cmyk' export being carried over from eps to pdf.
device.eps.rgb= sprintf(epsCmd, 'DeviceRGB', 'epswrite', [fname '.eps']);
device.jpeg.rgb= sprintf(cmdEnd, 'jpeg', [fname '.jpeg']);
% device.jpeg.cmyk= sprintf(cmdEnd, 'jpegcmyk', [fname '.jpeg']);
device.jpeg.gray= sprintf(cmdEnd, 'jpeggray', [fname '.jpeg']);
device.pdf.rgb= sprintf(pdfCmd, 'DeviceRGB', 'pdfwrite', [fname '.pdf']);
device.pdf.cmyk= sprintf(pdfCmd, 'DeviceCMYK', 'pdfwrite', [fname '.pdf']);
device.pdf.gray= sprintf(pdfCmd, 'DeviceGray', 'pdfwrite', [fname '.pdf']);
device.png.rgb= sprintf(cmdEnd, 'png16m', [fname '.png']);
% device.png.cmyk= sprintf(cmdEnd, 'png???', [fname '.png']);
device.png.gray= sprintf(cmdEnd, 'pnggray', [fname '.png']);
device.tiff.rgb= sprintf(cmdEnd, 'tiff24nc', [fname '.tiff']);
device.tiff.cmyk= sprintf(cmdEnd, 'tiff32nc', [fname '.tiff']);
device.tiff.gray= sprintf(cmdEnd, 'tiffgray', [fname '.tiff']);
% Get options.
global savefig_defaults; % Add global defaults.
if( iscellstr(savefig_defaults)), varargin= {savefig_defaults{:}, varargin{:}};
elseif(ischar(savefig_defaults)), varargin= {savefig_defaults, varargin{:}};
end
varargin= {'-r300', '-lossless', '-rgb', varargin{:}}; % Add defaults.
res= '';
types= {};
fonts= 'false';
crop= false;
for n= 1:length(varargin) % Read options.
if(ischar(varargin{n}))
switch(lower(varargin{n}))
case {'eps','jpeg','pdf','png','tiff'}, types{end+1}= lower(varargin{n});
case '-rgb', color= 'rgb'; deps= {'-depsc2'};
case '-cmyk', color= 'cmyk'; deps= {'-depsc2', '-cmyk'};
case '-gray', color= 'gray'; deps= {'-deps2'};
case '-fonts', fonts= 'true';
case '-lossless', comp= 0;
case '-crop', crop= true;
case '-dbg', op_dbg= true;
otherwise
if(regexp(varargin{n}, '^\-r[0-9]+$')), res= varargin{n};
elseif(regexp(varargin{n}, '^\-c[0-9.]+$')), comp= str2double(varargin{n}(3:end));
else warning('pax:savefig:inputError', 'Unknown option in argument: ''%s''.', varargin{n});
end
end
else
warning('pax:savefig:inputError', 'Wrong type of argument: ''%s''.', class(varargin{n}));
end
end
types= unique(types);
if(isempty(types)), error('No output format given.'); end
if (comp == 0) % Lossless compression
gsCompr= lossless;
elseif (comp <= 0.1) % High quality lossy
gsCompr= sprintf(lossy, comp, '1 1 1 1', '1 1 1 1');
else % Normal lossy
gsCompr= sprintf(lossy, comp, '2 1 1 2', '2 1 1 2');
end
% Generate the gs command.
switch(computer) % Get gs command.
case {'MAC','MACI'}, gs= '/usr/local/bin/gs';
case {'PCWIN'}, gs= 'gswin32c.exe';
case {'PCWIN64'}, gs= 'gswin64c.exe';
otherwise, gs= 'gs';
end
gs= [gs ' -q -dNOPAUSE -dBATCH -dEPSCrop']; % Essential.
gs= [gs ' -dPDFSETTINGS=/prepress -dEmbedAllFonts=' fonts]; % Must be first?
gs= [gs ' -dUseFlateCompression=true']; % Useful stuff.
gs= [gs ' -dAutoRotatePages=/None']; % Probably good.
gs= [gs ' -dHaveTrueTypes']; % Probably good.
gs= [gs ' ' res]; % Add resolution to cmd.
if(crop && ismember(types, {'eps', 'pdf'})) % Crop the figure.
fighdl= do_crop(fighdl);
end
% Output eps from Matlab.
renderer= ['-' lower(get(fighdl, 'Renderer'))]; % Use same as in figure.
if(strcmpi(renderer, '-none')), renderer= '-painters'; end % We need a valid renderer.
deps = [deps '-loose']; % added by PPD seems to help w cropping in matlab 2014b :(
print(fighdl, deps{:}, '-noui', renderer, res, [fname '-temp']); % Output the eps.
% Convert to other formats.
for n= 1:length(types) % Output them.
if(isfield(device.(types{n}), color))
cmd= device.(types{n}).(color); % Colour model exists.
else
cmd= device.(types{n}).rgb; % Use alternative.
if(~strcmp(types{n}, 'eps')) % It works anyways for eps (VERY SHAKY!).
warning('pax:savefig:deviceError', ...
'No device for %s using %s. Using rgb instead.', types{n}, color);
end
end
cmp= lossless;
if (strcmp(types{n}, 'pdf')), cmp= gsCompr; end % Lossy compr only for pdf.
if (strcmp(types{n}, 'eps')), cmp= ''; end % eps can't use lossless.
cmd= sprintf('%s %s %s -f "%s-temp.eps"', gs, cmd, cmp, fname);% Add up.
status= system(cmd); % Run Ghostscript.
if (op_dbg || status), display (cmd), end
end
delete([fname '-temp.eps']); % Clean up.
end
function fig= do_crop(fig)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Remove line segments that are outside the view.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
haxes= findobj(fig, 'Type', 'axes', '-and', 'Tag', '');
for n=1:length(haxes)
xl= get(haxes(n), 'XLim');
yl= get(haxes(n), 'YLim');
lines= findobj(haxes(n), 'Type', 'line');
for m=1:length(lines)
x= get(lines(m), 'XData');
y= get(lines(m), 'YData');
inx= (xl(1) <= x) & (x <= xl(2)); % Within the x borders.
iny= (yl(1) <= y) & (y <= yl(2)); % Within the y borders.
keep= inx & iny; % Within the box.
if(~strcmp(get(lines(m), 'LineStyle'), 'none'))
crossx= ((x(1:end-1) < xl(1)) & (xl(1) < x(2:end))) ... % Crossing border x1.
| ((x(1:end-1) < xl(2)) & (xl(2) < x(2:end))) ... % Crossing border x2.
| ((x(1:end-1) > xl(1)) & (xl(1) > x(2:end))) ... % Crossing border x1.
| ((x(1:end-1) > xl(2)) & (xl(2) > x(2:end))); % Crossing border x2.
crossy= ((y(1:end-1) < yl(1)) & (yl(1) < y(2:end))) ... % Crossing border y1.
| ((y(1:end-1) < yl(2)) & (yl(2) < y(2:end))) ... % Crossing border y2.
| ((y(1:end-1) > yl(1)) & (yl(1) > y(2:end))) ... % Crossing border y1.
| ((y(1:end-1) > yl(2)) & (yl(2) > y(2:end))); % Crossing border y2.
crossp= [( (crossx & iny(1:end-1) & iny(2:end)) ... % Crossing a x border within y limits.
| (crossy & inx(1:end-1) & inx(2:end)) ... % Crossing a y border within x limits.
| crossx & crossy ... % Crossing a x and a y border (corner).
), false ...
];
crossp(2:end)= crossp(2:end) | crossp(1:end-1); % Add line segment's secont end point.
keep= keep | crossp;
end
set(lines(m), 'XData', x(keep))
set(lines(m), 'YData', y(keep))
end
end
end
|
github
|
P-Chao/acfdetect-master
|
dirSynch.m
|
.m
|
acfdetect-master/toolbox/matlab/dirSynch.m
| 4,570 |
utf_8
|
d288299d31d15f1804183206d0aa0227
|
function dirSynch( root1, root2, showOnly, flag, ignDate )
% Synchronize two directory trees (or show differences between them).
%
% If a file or directory 'name' is found in both tree1 and tree2:
% 1) if 'name' is a file in both the pair is considered the same if they
% have identical size and identical datestamp (or if ignDate=1).
% 2) if 'name' is a directory in both the dirs are searched recursively.
% 3) if 'name' is a dir in root1 and a file in root2 (or vice-versa)
% synchronization cannot proceed (an error is thrown).
% If 'name' is found only in root1 or root2 it's a difference between them.
%
% The parameter flag controls how synchronization occurs:
% flag==0: neither tree1 nor tree2 has preference (newer file is kept)
% flag==1: tree2 is altered to reflect tree1 (tree1 is unchanged)
% flag==2: tree1 is altered to reflect tree2 (tree2 is unchanged)
% Run with showOnly=1 and different values of flag to see its effect.
%
% By default showOnly==1. If showOnly, displays a list of actions that need
% to be performed in order to synchronize the two directory trees, but does
% not actually perform the actions. It is highly recommended to run
% dirSynch first with showOnly=1 before running it with showOnly=0.
%
% USAGE
% dirSynch( root1, root2, [showOnly], [flag], [ignDate] )
%
% INPUTS
% root1 - root directory of tree1
% root2 - root directory of tree2
% showOnly - [1] show but do NOT perform actions
% flag - [0] 0: synchronize; 1: set root2=root1; 2: set root1==root2
% ignDate - [0] if true considers two files same even if have diff dates
%
% OUTPUTS
% dirSynch( 'c:\toolbox', 'c:\toolbox-old', 1 )
%
% EXAMPLE
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 2.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if(nargin<3 || isempty(showOnly)), showOnly=1; end;
if(nargin<4 || isempty(flag)), flag=0; end;
if(nargin<5 || isempty(ignDate)), ignDate=0; end;
% get differences between root1/root2 and loop over them
D = dirDiff( root1, root2, ignDate );
roots={root1,root2}; ticId = ticStatus;
for i=1:length(D)
% get action
if( flag==1 )
if( D(i).in1 ), act=1; src1=1; else act=0; src1=2; end
elseif( flag==2 )
if( D(i).in2 ), act=1; src1=2; else act=0; src1=1; end
else
act=1;
if(D(i).in1 && D(i).in2)
if( D(i).new1 ), src1=1; else src1=2; end
else
if( D(i).in1 ), src1=1; else src1=2; end
end
end
src2=mod(src1,2)+1;
% perform action
if( act==1 )
if( showOnly )
disp(['COPY ' int2str(src1) '->' int2str(src2) ': ' D(i).name]);
else
copyfile( [roots{src1} D(i).name], [roots{src2} D(i).name], 'f' );
end;
else
if( showOnly )
disp(['DEL in ' int2str(src1) ': ' D(i).name]);
else
fName = [roots{src1} D(i).name];
if(D(i).isdir), rmdir(fName,'s'); else delete(fName); end
end
end
if(~showOnly), tocStatus( ticId, i/length(D) ); end;
end
end
function D = dirDiff( root1, root2, ignDate )
% get differences from root1 to root2
D1 = dirDiff1( root1, root2, ignDate, '/' );
% get differences from root2 to root1
D2 = dirDiff1( root2, root1, ignDate, '/' );
% remove duplicates (arbitrarily from D2)
D2=D2(~([D2.in1] & [D2.in2]));
% swap 1 and 2 in D2
for i=1:length(D2),
D2(i).in1=0; D2(i).in2=1; D2(i).new1=~D2(i).new1;
end
% merge
D = [D1 D2];
end
function D = dirDiff1( root1, root2, ignDate, subdir )
if(root1(end)~='/'), root1(end+1)='/'; end
if(root2(end)~='/'), root2(end+1)='/'; end
if(subdir(end)~='/'), subdir(end+1)='/'; end
fs1=dir([root1 subdir]); fs2=dir([root2 subdir]);
D=struct('name',0,'isdir',0,'in1',0,'in2',0,'new1',0);
D=repmat(D,[1 length(fs1)]); n=0; names2={fs2.name}; Dsub=[];
for i1=1:length( fs1 )
name=fs1(i1).name; isdir=fs1(i1).isdir;
if( any(strcmp(name,{'.','..'})) ), continue; end;
i2 = find(strcmp(name,names2));
if(~isempty(i2) && isdir)
% cannot handle this condition
if(~fs2(i2).isdir), disp([root1 subdir name]); assert(false); end;
% recurse and record possible differences
Dsub=[Dsub dirDiff1(root1,root2,ignDate,[subdir name])]; %#ok<AGROW>
elseif( ~isempty(i2) && fs1(i1).bytes==fs2(i2).bytes && ...
(ignDate || fs1(i1).datenum==fs2(i2).datenum))
% nothing to do - files are same
continue;
else
% record differences
n=n+1;
D(n).name=[subdir name]; D(n).isdir=isdir;
D(n).in1=1; D(n).in2=~isempty(i2);
D(n).new1 = ~D(n).in2 || (fs1(i1).datenum>fs2(i2).datenum);
end
end
D = [D(1:n) Dsub];
end
|
github
|
P-Chao/acfdetect-master
|
plotRoc.m
|
.m
|
acfdetect-master/toolbox/matlab/plotRoc.m
| 5,212 |
utf_8
|
008f9c63073c6400c4960e9e213c47e5
|
function [h,miss,stds] = plotRoc( D, varargin )
% Function for display of rocs (receiver operator characteristic curves).
%
% Display roc curves. Consistent usage ensures uniform look for rocs. The
% input D should have n rows, each of which is of the form:
% D = [falsePosRate truePosRate]
% D is generated, for example, by scanning a detection threshold over n
% values from 0 (so first entry is [1 1]) to 1 (so last entry is [0 0]).
% Alternatively D can be a cell vector of rocs, in which case an average
% ROC will be shown with error bars. Plots missRate (which is just 1 minus
% the truePosRate) on the y-axis versus the falsePosRate on the x-axis.
%
% USAGE
% [h,miss,stds] = plotRoc( D, prm )
%
% INPUTS
% D - [nx2] n data points along roc [falsePosRate truePosRate]
% typically ranges from [1 1] to [0 0] (or may be reversed)
% prm - [] param struct
% .color - ['g'] color for curve
% .lineSt - ['-'] linestyle (see LineSpec)
% .lineWd - [4] curve width
% .logx - [0] use logarithmic scale for x-axis
% .logy - [0] use logarithmic scale for y-axis
% .marker - [''] marker type (see LineSpec)
% .mrkrSiz - [12] marker size
% .nMarker - [5] number of markers (regularly spaced) to display
% .lims - [0 1 0 1] axes limits
% .smooth - [0] if T compute lower envelop of roc to smooth staircase
% .fpTarget - [] return miss rates at given fp values (and draw lines)
% .xLbl - ['false positive rate'] label for x-axis
% .yLbl - ['miss rate'] label for y-axis
%
% OUTPUTS
% h - plot handle for use in legend only
% miss - average miss rates at fpTarget reference values
% stds - standard deviation of miss rates at fpTarget reference values
%
% EXAMPLE
% k=2; x=0:.0001:1; data1 = [1-x; (1-x.^k).^(1/k)]';
% k=3; x=0:.0001:1; data2 = [1-x; (1-x.^k).^(1/k)]';
% hs(1)=plotRoc(data1,struct('color','g','marker','s'));
% hs(2)=plotRoc(data2,struct('color','b','lineSt','--'));
% legend( hs, {'roc1','roc2'} ); xlabel('fp'); ylabel('fn');
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.02
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get params
[color,lineSt,lineWd,logx,logy,marker,mrkrSiz,nMarker,lims,smooth, ...
fpTarget,xLbl,yLbl] = getPrmDflt( varargin, {'color' 'g' 'lineSt' '-' ...
'lineWd' 4 'logx' 0 'logy' 0 'marker' '' 'mrkrSiz' 12 'nMarker' 5 ...
'lims' [] 'smooth' 0 'fpTarget' [] 'xLbl' 'false positive rate' ...
'yLbl' 'miss rate' } );
if( isempty(lims) ); lims=[logx*1e-5 1 logy*1e-5 1]; end
% ensure descending fp rate, change to miss rate, optionally 'nicefy' roc
if(~iscell(D)), D={D}; end; nD=length(D);
for j=1:nD, assert(size(D{j},2)==2); end
for j=1:nD, if(D{j}(1,2)<D{j}(end,2)), D{j}=flipud(D{j}); end; end
for j=1:nD, D{j}(:,2)=1-D{j}(:,2); assert(all(D{j}(:,2)>=0)); end
if(smooth), for j=1:nD, D{j}=smoothRoc(D{j}); end; end
% plot: (1) h for legend only, (2) markers, (3) error bars, (4) roc curves
hold on; axis(lims); xlabel(xLbl); ylabel(yLbl);
prmMrkr = {'MarkerSize',mrkrSiz,'MarkerFaceColor',color};
prmClr={'Color',color}; prmPlot = [prmClr,{'LineWidth',lineWd}];
h = plot( 2, 0, [lineSt marker], prmMrkr{:}, prmPlot{:} ); %(1)
DQ = quantizeRocs( D, nMarker, logx, lims ); DQm=mean(DQ,3);
if(~isempty(marker))
plot(DQm(:,1),DQm(:,2),marker,prmClr{:},prmMrkr{:} ); end %(2)
if(nD>1), DQs=std(DQ,0,3);
errorbar(DQm(:,1),DQm(:,2),DQs(:,2),'.',prmClr{:}); end %(3)
if(nD==1), DQ=D{1}; else DQ=quantizeRocs(D,100,logx,lims); end
DQm = mean(DQ,3); plot( DQm(:,1), DQm(:,2), lineSt, prmPlot{:} ); %(4)
% plot line at given fp rate
m=length(fpTarget); miss=zeros(1,m); stds=miss;
if( m>0 )
assert( min(DQm(:,1))<=min(fpTarget) ); DQs=std(DQ,0,3);
for i=1:m, j=find(DQm(:,1)<=fpTarget(i)); j=j(1);
miss(i)=DQm(j,2); stds(i)=DQs(j,2); end
fp=min(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]);
fp=max(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]);
end
% set log axes
if( logx==1 )
ticks=10.^(-8:8);
set(gca,'XScale','log','XTick',ticks);
end
if( logy==1 )
ticks=[.001 .002 .005 .01 .02 .05 .1 .2 .5 1];
set(gca,'YScale','log','YTick',ticks);
end
if( logx==1 || logy==1 ), grid on;
set(gca,'XMinorGrid','off','XMinorTic','off');
set(gca,'YMinorGrid','off','YMinorTic','off');
end
end
function DQ = quantizeRocs( Ds, nPnts, logx, lims )
% estimate miss rate at each target fp rate
nD=length(Ds); DQ=zeros(nPnts,2,nD);
if(logx==1), fps=logspace(log10(lims(1)),log10(lims(2)),nPnts);
else fps=linspace(lims(1),lims(2),nPnts); end; fps=flipud(fps');
for j=1:nD, D=[Ds{j}; 0 1]; k=1; fp=D(k,1);
for i=1:nPnts
while( k<size(D,1) && fp>=fps(i) ), k=k+1; fp=D(k,1); end
k0=max(k-1,1); fp0=D(k0,1); assert(fp0>=fp);
if(fp0==fp), r=.5; else r=(fps(i)-fp)/(fp0-fp); end
DQ(i,1,j)=fps(i); DQ(i,2,j)=r*D(k0,2)+(1-r)*D(k,2);
end
end
end
function D1 = smoothRoc( D )
D1 = zeros(size(D));
n = size(D,1); cnt=0;
for i=1:n
isAnkle = (i==1) || (i==n);
if( ~isAnkle )
dP=D1(cnt,:); dC=D(i,:); dN=D(i+1,:);
isAnkle = (dC(1)~=dP(1)) && (dC(2)~=dN(2));
end
if(isAnkle); cnt=cnt+1; D1(cnt,:)=D(i,:); end
end
D1=D1(1:cnt,:);
end
|
github
|
P-Chao/acfdetect-master
|
simpleCache.m
|
.m
|
acfdetect-master/toolbox/matlab/simpleCache.m
| 4,098 |
utf_8
|
92df86b0b7e919c9a26388e598e4d370
|
function varargout = simpleCache( op, cache, varargin )
% A simple cache that can be used to store results of computations.
%
% Can save and retrieve arbitrary values using a vector (includnig char
% vectors) as a key. Especially useful if a function must perform heavy
% computation but is often called with the same inputs (for which it will
% give the same outputs). Note that the current implementation does a
% linear search for the key (a more refined implementation would use a hash
% table), so it is not meant for large scale usage.
%
% To use inside a function, make the cache persistent:
% persistent cache; if( isempty(cache) ) cache=simpleCache('init'); end;
% The following line, when placed inside a function, means the cache will
% stay in memory until the matlab environment changes. For an example
% usage see maskGaussians.
%
% USAGE - 'init': initialize a cache object
% cache = simpleCache('init');
%
% USAGE - 'put': put something in cache. key must be a numeric vector
% cache = simpleCache( 'put', cache, key, val );
%
% USAGE - 'get': retrieve from cache. found==1 if obj was found
% [found,val] = simpleCache( 'get', cache, key );
%
% USAGE - 'remove': free key
% [cache,found] = simpleCache( 'remove', cache, key );
%
% INPUTS
% op - 'init', 'put', 'get', 'remove'
% cache - the cache object being operated on
% varargin - see USAGE above
%
% OUTPUTS
% varargout - see USAGE above
%
% EXAMPLE
% cache = simpleCache('init');
% hellokey=rand(1,3); worldkey=rand(1,11);
% cache = simpleCache( 'put', cache, hellokey, 'hello' );
% cache = simpleCache( 'put', cache, worldkey, 'world' );
% [f,v]=simpleCache( 'get', cache, hellokey ); disp(v);
% [f,v]=simpleCache( 'get', cache, worldkey ); disp(v);
%
% See also PERSISTENT, MASKGAUSSIANS
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
switch op
case 'init' % init a cache
cacheSiz = 8;
cache.freeinds = 1:cacheSiz;
cache.keyns = -ones(1,cacheSiz);
cache.keys = cell(1,cacheSiz);
cache.vals = cell(1,cacheSiz);
varargout = {cache};
case 'put' % a put operation
key=varargin{1}; val=varargin{2};
cache = cacheput( cache, key, val );
varargout = {cache};
case 'get' % a get operation
key=varargin{1};
[ind,val] = cacheget( cache, key );
found = ind>0;
varargout = {found,val};
case 'remove' % a remove operation
key=varargin{1};
[cache,found] = cacheremove( cache, key );
varargout = {cache,found};
otherwise
error('Unknown cache operation: %s',op);
end
end
function cache = cachegrow( cache )
% double cache size
cacheSiz = length( cache.keyns );
if( cacheSiz>64 ) % warn if getting big
warning(['doubling cache size to: ' int2str2(cacheSiz*2)]);%#ok<WNTAG>
end
cache.freeinds = [cache.freeinds (cacheSiz+1):(2*cacheSiz)];
cache.keyns = [cache.keyns -ones(1,cacheSiz)];
cache.keys = [cache.keys cell(1,cacheSiz)];
cache.vals = [cache.vals cell(1,cacheSiz)];
end
function cache = cacheput( cache, key, val )
% put something into the cache
% get location to place
ind = cacheget( cache, key ); % see if already in cache
if( ind==-1 )
if( isempty( cache.freeinds ) )
cache = cachegrow( cache ); %grow cache
end
ind = cache.freeinds(1); % get new cache loc
cache.freeinds = cache.freeinds(2:end);
end
% now simply place in ind
cache.keyns(ind) = length(key);
cache.keys{ind} = key;
cache.vals{ind} = val;
end
function [ind,val] = cacheget( cache, key )
% get cache element, or fail
cacheSiz = length( cache.keyns );
keyn = length( key );
for i=1:cacheSiz
if(keyn==cache.keyns(i) && all(key==cache.keys{i}))
val = cache.vals{i}; ind = i; return; end
end
ind=-1; val=-1;
end
function [cache,found] = cacheremove( cache, key )
% get cache element, or fail
ind = cacheget( cache, key );
found = ind>0;
if( found )
cache.freeinds = [ind cache.freeinds];
cache.keyns(ind) = -1;
cache.keys{ind} = [];
cache.vals{ind} = [];
end
end
|
github
|
P-Chao/acfdetect-master
|
tpsInterpolate.m
|
.m
|
acfdetect-master/toolbox/matlab/tpsInterpolate.m
| 1,646 |
utf_8
|
d3bd3a26d048f32cfdc17884ccae6d8c
|
function [xsR,ysR] = tpsInterpolate( warp, xs, ys, show )
% Apply warp (obtained by tpsGetWarp) to a set of new points.
%
% USAGE
% [xsR,ysR] = tpsInterpolate( warp, xs, ys, [show] )
%
% INPUTS
% warp - [see tpsGetWarp] bookstein warping parameters
% xs, ys - points to apply warp to
% show - [1] will display results in figure(show)
%
% OUTPUTS
% xsR, ysR - result of warp applied to xs, ys
%
% EXAMPLE
%
% See also TPSGETWARP
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<4 || isempty(show)); show = 1; end
wx = warp.wx; affinex = warp.affinex;
wy = warp.wy; affiney = warp.affiney;
xsS = warp.xsS; ysS = warp.ysS;
xsD = warp.xsD; ysD = warp.ysD;
% interpolate points (xs,ys)
xsR = f( wx, affinex, xsS, ysS, xs(:)', ys(:)' );
ysR = f( wy, affiney, xsS, ysS, xs(:)', ys(:)' );
% optionally show points (xsR, ysR)
if( show )
figure(show);
subplot(2,1,1); plot( xs, ys, '.', 'color', [0 0 1] );
hold('on'); plot( xsS, ysS, '+' ); hold('off');
subplot(2,1,2); plot( xsR, ysR, '.' );
hold('on'); plot( xsD, ysD, '+' ); hold('off');
end
function zs = f( w, aff, xsS, ysS, xs, ys )
% find f(x,y) for xs and ys given W and original points
n = size(w,1); ns = size(xs,2);
delXs = xs'*ones(1,n) - ones(ns,1)*xsS;
delYs = ys'*ones(1,n) - ones(ns,1)*ysS;
distSq = (delXs .* delXs + delYs .* delYs);
distSq = distSq + eye(size(distSq)) + eps;
U = distSq .* log( distSq ); U( isnan(U) )=0;
zs = aff(1)*ones(ns,1)+aff(2)*xs'+aff(3)*ys';
zs = zs + sum((U.*(ones(ns,1)*w')),2);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.