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
jjjjfrench/UW-UIOPS-master
read_binary_SEA.m
.m
UW-UIOPS-master/read_binary/read_binary_SEA.m
12,340
utf_8
3d7e92cc325973ca7580749e35bbeb78
function read_binary_SEA(infilename,outfilename) %% Function to decompress SEA raw files % Need to double check the file format and code for each probes % This only works for MC3E filed campaign % * July 11, 2016, Created this new interface function, Wei Wu starpos = find(infilename == '*',1,'last'); nWierdTotal = 0; if ~isempty(starpos) files = dir(infilename); filenums = length(files); filedir = infilename(1:starpos-1); else filenums = 1; end for i = 1:filenums if filenums > 1 infilename = [filedir,files(i).name]; end if outfilename == '1' slashpos = find(infilename == '/',1,'last'); outfilename = ['DIMG.',infilename(slashpos+1:end),'.cdf']; end fid=fopen(infilename,'r','l'); infilename %%% Updated for new MATLAB NETCDF interface f = netcdf.create([outfilename, '.CIP.cdf'], 'clobber'); dimid0 = netcdf.defDim(f,'time',netcdf.getConstant('NC_UNLIMITED')); dimid1 = netcdf.defDim(f,'ImgRowlen',8); dimid2 = netcdf.defDim(f,'ImgBlocklen',1700); varid0 = netcdf.defVar(f,'year','double',dimid0); varid1 = netcdf.defVar(f,'month','double',dimid0); varid2 = netcdf.defVar(f,'day','double',dimid0); varid3 = netcdf.defVar(f,'hour','double',dimid0); varid4 = netcdf.defVar(f,'minute','double',dimid0); varid5 = netcdf.defVar(f,'second','double',dimid0); varid6 = netcdf.defVar(f,'millisec','double',dimid0); varid7 = netcdf.defVar(f,'wkday','double',dimid0); varid8 = netcdf.defVar(f,'data','double',[dimid1 dimid2 dimid0]); netcdf.endDef(f) f1 = netcdf.create([outfilename, '.2DC.cdf'], 'clobber'); dimid01 = netcdf.defDim(f1,'time',netcdf.getConstant('NC_UNLIMITED')); dimid11 = netcdf.defDim(f1,'ImgRowlen',8); dimid21 = netcdf.defDim(f1,'ImgBlocklen',1700); varid01 = netcdf.defVar(f1,'year','double',dimid01); varid11 = netcdf.defVar(f1,'month','double',dimid01); varid21 = netcdf.defVar(f1,'day','double',dimid01); varid31 = netcdf.defVar(f1,'hour','double',dimid01); varid41 = netcdf.defVar(f1,'minute','double',dimid01); varid51 = netcdf.defVar(f1,'second','double',dimid01); varid61 = netcdf.defVar(f1,'millisec','double',dimid01); varid71 = netcdf.defVar(f1,'wkday','double',dimid01); varid81 = netcdf.defVar(f1,'data','double',[dimid11 dimid21 dimid01]); netcdf.endDef(f) kk=1; wkday = 1; datatemp = [0 0 0 0 0 0 0 0 0 0]; numFilename = 0; nread =0; endfile = 0; % while feof(fid)==0 & kk <= 3000 while feof(fid)==0 & endfile == 0 [datalast,datatemp]=readDir(fid,datatemp); doffset1 = -datatemp(2); if datatemp(1)==999 nTagNext=1; else nTagNext=0; end while nTagNext==0 [datalast,datatemp]=readDir(fid,datatemp); if datatemp(1)==33000 & datatemp(3)==4098 %datalast datatemp [datalast,datatemp]=readDir(fid,datatemp); %datatemp ttt = readTime(fid); year =ttt(1); month=ttt(2); day =ttt(3); hour =ttt(4); minute=ttt(5); second=ttt(6); millisec=ttt(7); wkday=1; data1 = fread(fid,4098,'uchar'); fseek(fid,-4150,0); [datalast,datatemp]=readDir(fid,datatemp); data = data1(1:4096); % data=reshape(fread(fid,4096*8,'ubit1'),4096,8); % b1 = [num2str(data(:,1)),num2str(data(:,2)),num2str(data(:,3)),num2str(data(:,4)),num2str(data(:,5)),... % num2str(data(:,6)),num2str(data(:,7)),num2str(data(:,8))]; bytes=dec2hex(data,2); kk; i=1; ii=1; b1full=dec2bin(hex2dec(bytes(:,:)),8); b2 = bin2dec(b1full(:,4:8)); while i<4096 b1 = b1full(i,:); curi = i; i=i+1; if b1(3) == '1' % i=i+1; elseif b1(1) == '0' & b1(2) == '0' % b2=bin2dec(b1(4:8)); for k=1:b2(curi)+1; if i < length(bytes) decomp(ii,:)=bytes(i,:); else break end ii=ii+1; i=i+1; end elseif b1(1) == '1' & b1(2) == '0' % b2=bin2dec(b1(4:8)); for k=1:b2(curi)+1; decomp(ii,:)='00'; ii=ii+1; end elseif b1(2) == '1' & b1(1) == '0' % b2=bin2dec(b1(4:8)); for k=1:b2(curi)+1; decomp(ii,:)='FF'; ii=ii+1; end else kk; end end found = 0; i=1; count=0; while found == 0 if decomp(i)=='AA' count=count+1; else count=0; end if count == 8 found=1; dd=i+1:8:length(decomp)-7; nWierd=0; end if i==length(decomp) % Add to avoid no 'AA' even though wierd to have no 'AA'... found =1; nWierd=1; nWierdTotal =nWierdTotal +1; end i=i+1; end if nWierd ==0 % % decomp_convert=[hex2dec(decomp(dd,:)),hex2dec(decomp(dd+1,:)),hex2dec(decomp(dd+2,:)),hex2dec(decomp(dd+3,:)),... % hex2dec(decomp(dd+4,:)),hex2dec(decomp(dd+5,:)),hex2dec(decomp(dd+6,:)),hex2dec(decomp(dd+7,:))]; decomp_convert=[hex2dec(decomp(dd+7,:)),hex2dec(decomp(dd+6,:)),hex2dec(decomp(dd+5,:)),hex2dec(decomp(dd+4,:)),... hex2dec(decomp(dd+3,:)),hex2dec(decomp(dd+2,:)),hex2dec(decomp(dd+1,:)),hex2dec(decomp(dd,:))]; k2=[decomp(dd,:),decomp(dd+1,:),decomp(dd+2,:),decomp(dd+3,:),decomp(dd+4,:),decomp(dd+5,:),decomp(dd+6,:),decomp(dd+7,:)]; % length_diff=length(decomp_convert) - length(handles.matrix(kk-1,:,:)); % matrix_size(kk)=length(decomp_convert); % if length_diff > 0 % handles.matrix(1:kk-1,length(handles.matrix(kk-1,:,:)):length(decomp_convert),:)=-1; % elseif length_diff < 0 % decomp_convert(length(decomp_convert):length(handles.matrix(kk-1,:,:)),:)=-1; % end if length(decomp_convert) < 1700 decomp_convert(length(decomp_convert):1700,:)=-1; end netcdf.putVar ( f, varid0, kk-1, 1, year ) netcdf.putVar ( f, varid1, kk-1, 1, month ); netcdf.putVar ( f, varid2, kk-1, 1, day ); netcdf.putVar ( f, varid3, kk-1, 1, hour ); netcdf.putVar ( f, varid4, kk-1, 1, minute ); netcdf.putVar ( f, varid5, kk-1, 1, second ); netcdf.putVar ( f, varid6, kk-1, 1, millisec ); netcdf.putVar ( f, varid7, kk-1, 1, wkday ); netcdf.putVar ( f, varid8, [0, 0, kk-1], [8,1700,1], decomp_convert' ); kk=kk+1; if mod(kk,100) == 0 kk datestr(now) end end elseif datatemp(1)==5000 && datatemp(3)==4096 [datalast,datatemp]=readDir(fid,datatemp); [datalast,datatemp]=readDir(fid,datatemp); [datalast,datatemp]=readDir(fid,datatemp); [datalast,datatemp]=readDir(fid,datatemp); [datalast,datatemp]=readDir(fid,datatemp); ttt = readTime(fid); year =ttt(1); month=ttt(2); day =ttt(3); hour =ttt(4); minute=ttt(5); second=ttt(6); millisec=ttt(7); wkday=1; %dataother = fread(fid,14,'uchar'); temp0011 = fread(fid,1,'int16'); temp0012 = fread(fid,1,'int16'); fread(fid,10,'char'); % temp003 = fread(fid,1,'char'); % temp004 = fread(fid,1,'short'); % temp003/temp0011*temp0012*2*0.001 % temp002*25*0.000001 data1 = fread(fid,4096,'uchar'); fseek(fid,-4162,0); [datalast,datatemp]=readDir(fid,datatemp); tas=temp0011/temp0012*50*1000*25*0.000001; datafinal = reshape(data1,4,1024); temp1234 = datafinal(1,:); datafinal(1,:)=datafinal(4,:); datafinal(4,:)=temp1234; temp1234 = datafinal(2,:); datafinal(2,:)=datafinal(3,:); datafinal(3,:)=temp1234; netcdf.putVar ( f1, varid01, kk-1, 1, year ) netcdf.putVar ( f1, varid11, kk-1, 1, month ); netcdf.putVar ( f1, varid21, kk-1, 1, day ); netcdf.putVar ( f1, varid31, kk-1, 1, hour ); netcdf.putVar ( f1, varid41, kk-1, 1, minute ); netcdf.putVar ( f1, varid51, kk-1, 1, second ); netcdf.putVar ( f1, varid61, kk-1, 1, millisec ); netcdf.putVar ( f1, varid71, kk-1, 1, wkday ); netcdf.putVar ( f1, varid91, kk-1, 1, tas ); netcdf.putVar ( f1, varid81, [0, 0, kk-1], [4,1024,1], datafinal ); kk=kk+1; if mod(kk,100) == 0 kk datestr(now) end end clear decomp dd k2 b1 b2 if datatemp(1)==999 doffset2 = datatemp(2); nTagNext = 1; fseek(fid,doffset2+doffset1,0); end end for j=1:16 bb=fread(fid,1,'int8'); if feof(fid) == 1 endfile=1; break end end fseek(fid,-16,'cof'); end end fclose(fid); % close(f); netcdf.close(f); % New interface by Will netcdf.close(f1); % New interface by Will nWierdTotal end function [ldata,tdata]=readDir(fid,tdata) tagNumber=fread(fid,1,'uint16'); dataOffset=fread(fid,1,'uint16'); numberBytes=fread(fid,1,'uint16'); samples=fread(fid,1,'uint16'); bytesPerSample=fread(fid,1,'uint16'); type=fread(fid,1,'uint8'); param1=fread(fid,1,'uint8'); param2=fread(fid,1,'uint8'); param3=fread(fid,1,'uint8'); address=fread(fid,1,'uint16'); ldata = tdata; tdata = [tagNumber dataOffset numberBytes samples bytesPerSample type param1 param2 param3 address]; end function time=readTime(fid) for i=1:2 year=fread(fid,1,'uint16'); month=fread(fid,1,'uint16'); day=fread(fid,1,'uint16'); hour=fread(fid,1,'uint16'); minute=fread(fid,1,'uint16'); second=fread(fid,1,'uint16'); fracsec=fread(fid,1,'uint16'); maxfreq=fread(fid,1,'uint16'); bls=fread(fid,1,'uint16'); time=[year month day hour minute second fracsec maxfreq bls]; end end function readTable(fid) filename = fread(fid,8,'uint8'); filename = char(filename); filename=filename'; tfiles = fread(fid,datalast(3),'uint8'); abc = char(tfiles); abc' end
github
jjjjfrench/UW-UIOPS-master
write2d.m
.m
UW-UIOPS-master/read_binary/@cip/write2d.m
6,333
utf_8
5a49ac1e4c6920239f612e1cb8ee14a1
function write2d(obj,filebase) % WRITE2D - Convert an unpacked CIP file to RAF/OAP format % % write2d(obj,filebase) % obj - CIP class object % filebase - the base of the file name % if not specified, use the first eight characters of cipfile % (YYYYMMMDD) if nargin < 2 fbase = obj.cipfile{1}; fbase = fbase(1:8); else fbase = filebase; end % Read the CIP csv data [csvsod,csvtas,dt] = obj.ciptas(obj.csvfile); % Open the output file outfile = [fbase '_cip.2d']; fprintf('Writing %s\n',outfile); f2d = fopen(outfile,'w','ieee-be'); % The probe ID for the CIP is set to C5 because xpms2d has a particular % format for the timing word that is constructed here % 0xAAAAAAxxxxxxxxxx, where the time part is the number of 12 microsec % clicks since UTC midnight. probeid = 'C5'; id = uint16(double(probeid)*[256;1]); dstr = datestr(dt,'mm/dd/yyyy'); xmlstart = '<OAP version="1">'; % Read in the PMS (1D-C and 1D-P) file pmsfile = [ fbase '_pms.2d' ]; converttas = false; if exist(pmsfile,'file') fid = fopen(pmsfile,'r','ieee-be'); fprintf('Opened %s\n', pmsfile); while (1) line = fgetl(fid); % Check for the old style <PMS2D> files instead of <OAP> where % the true air speed is scaled by 255/125 if ~isempty(strfind(line,'<PMS2D>')) converttas = true; fprintf(f2d,'%s\n',xmlstart); continue; end % Don't include the <Source> attribute if ~isempty(strfind(line,'<Source>')); continue; end % Found the end of the xml header if ~isempty(strfind(line,'</OAP>')); break; end if ~isempty(strfind(line,'</PMS2D>')); break; end fprintf(f2d,'%s\n',line); end % Read the PMS data pms = fread(fid,'*uint16'); npms = length(pms)/2058; pms = reshape(pms,2058,npms); % Calculate the record times hd = double(pms(1:9,:)); pmstm = datenum(hd(5,:),hd(6,:),hd(7,:),... hd(2,:),hd(3,:),hd(4,:)+hd(9,:)/1000); % Convert the tas if needed if converttas; pms(8,:) = uint16(hd(8,:) * 125 / 255); end clear hd; else % Write the header if there is no PMS 2D file to copy it from fprintf('The PMS 2D file: %s was not found.\n', pmsfile); fprintf(f2d,'<?xml version="1.0" encoding="ISO08858-1"?>\n'); fprintf(f2d,'%s\n',xmlstart); fprintf(f2d, ... ' <Institution>University of Wyoming Atmospheric Science</Institution>\n'); fprintf(f2d, ... ' <FormatURL>http://www.eol.ucar.edu/raf/Software/OAPfiles.html</FormatURL>\n'); % If there is no PMS 2d file to merge the data with, try reading the % Project and FlightNumber from a raw file rawfile = [fbase '_raw.nc']; if exist(rawfile,'file') nc = netcdf.open(rawfile,0); fprintf('Reading attributes from %s\n',rawfile); proj = netcdf.getAtt(nc,netcdf.getConstant('NC_GLOBAL'),'ProjectName'); fprintf(f2d,' <Project>%s</Project>\n',proj); flt = netcdf.getAtt(nc,netcdf.getConstant('NC_GLOBAL'),'FlightNumber'); fprintf(f2d,' <FlightNumber>%s</FlightNumber>\n',flt); netcdf.close(nc); end fprintf(f2d,' <FlightDate>%s</FlightDate>\n',dstr); fprintf(f2d,' <Platform>N2UW</Platform>\n'); npms = 0; end % Write the XML <probe> attributes for the CIP fprintf(f2d,[' <probe id="%s" type="Fast2DC" resolution="25" ' ... 'nDiodes="64" suffix="_IBR"/>\n'],... probeid); fprintf(f2d,'</OAP>\n'); % Initialize some values rec = zeros(1024,1,'uint32'); twos = power(2,31:-1:0)'; tmask = uint32(hex2dec('AAAAAA00')); ipms = 1; % Open and read each file of unpacked cip images for ii = 1:length(obj.cipfile) fprintf('Reading %s\n',obj.cipfile{ii}) fin = fopen(obj.cipfile{ii},'r','ieee-be'); data = fread(fin,'ubit2=>uint8'); fclose(fin); % Find the start index, time, and number of slices for each particle disp('Calling cipindex') [idx,sod,ns]=obj.cipindex(data); disp('Writing to the 2D file'); % Convert two bit values to one bit data = data > 1; % CIP image data are on a 12 hour clock delt = csvsod(1) - sod(1); if delt > 7*3600 && delt < 17*3600; sod = sod + 12*3600; end % Convert the second of the day to matlab time dnum = dt + sod/86400; % Construct the timing words tword = timing(sod',tmask); % Interpolate the true airspeeds from the CSV files for each particle tas = interp1(csvsod,csvtas,sod); % Loop through each CIP particle jj = 1; for i=1:length(idx)-1 % Pad by 64 values to insert timer word later img = double(data(idx(i):idx(i)+(ns(i)+1)*64-1)); nw = ns(i)*2 + 2; % Convert the 1 bit values to 32 bit values (two 32 bit values per slice) img = reshape(img,32,nw)' * twos; % Append with timer word img(nw-1) = tword(1,i); img(nw) = tword(2,i); % Check to see if the full particle fits in the record nrem = 1025-jj; if nw > nrem % Write out what fits rec(jj:1024) = img(1:nrem); % Write out PMS records that are before this CIP record while ipms <= npms && pmstm(ipms) < dnum(i) fwrite(f2d,pms(:,ipms),'uint16'); ipms = ipms + 1; end recout(f2d,id,dnum(i),tas(i),rec); % Save the rest of the particle rec(1:nw-nrem) = img(nrem+1:end); jj = nw-nrem+1; else % It all fits, stuff it in rec(jj:jj+nw-1) = img; jj = jj + nw; end end end % Write out the rest of the PMS records if ipms < npms; fwrite(f2d,pms(:,ipms:npms),'uint16'); end fclose(f2d); function recout(fout,id,daten,tas,rec) % RECOUT - writes a particle record to file % % recout(fout,id,daten,tas,rec) % fout - output file id % id - record identifier (C5) % daten - matlab time stamp of the last particle in the record % tas - true air speed % rec - 4096 byte image record % % Convert the timestamp to a vector dv = datevec(daten); msec = mod(dv(6),1) * 1000; ovld = 0; % Write out the record header fwrite(fout, ... [id,dv(4),dv(5),floor(dv(6)),dv(1),dv(2),dv(3),... tas,msec,ovld], 'uint16'); % Write out the image data fwrite(fout,rec,'uint32'); function tword = timing(dsec,tmask) % TIMING - Create the timing word % % timing(sod,tmask) % sod - second of the day for this particle % tmask - timing work pattern that indicates that it is a timing word % 0xAAAAAA0000000000 dsec = dsec * 12E6; % 4294967296 is 2^32 tword = [bitor(uint32(mod(dsec/4294967296,16)),tmask); ... uint32(mod(dsec,4294967296))];
github
jjjjfrench/UW-UIOPS-master
cip_obj_to_netcdf.m
.m
UW-UIOPS-master/read_binary/@cip/cip_obj_to_netcdf.m
3,981
utf_8
14c826715464ee56bafdb86f9aafde8e
function cip_obj_to_netcdf(obj, outfile) % Read the CIP csv data [timestamp,csvtas, dt] = obj.ciptas(obj.cipdir, obj.csvfile); timestamp = timestamp - datenum(dt); %Get just datenum format of corresponding sod referenced from first day csvsod = timestamp*86400.; %Convert to seconds from date number format % The probe ID for the CIP is set to C5 because xpms2d has a particular % format for the timing word that is constructed here % 0xAAAAAAxxxxxxxxxx, where the time part is the number of 12 microsec % clicks since UTC midnight. tmask = uint32(hex2dec('AAAAAA00')); ipms = 1; % Create netCDF file f = netcdf.create(outfile, 'clobber'); dimid0 = netcdf.defDim(f,'time',netcdf.getConstant('NC_UNLIMITED')); dimid1 = netcdf.defDim(f,'ImgRowlen',64); dimid2 = netcdf.defDim(f,'ImgBlocklen',512); varid0 = netcdf.defVar(f,'year', 'double', dimid0); varid1 = netcdf.defVar(f,'month','double',dimid0); varid2 = netcdf.defVar(f,'day','double',dimid0); varid3 = netcdf.defVar(f,'hour','double',dimid0); varid4 = netcdf.defVar(f,'minute','double',dimid0); varid5 = netcdf.defVar(f,'second','double',dimid0); varid6 = netcdf.defVar(f,'millisec','double',dimid0); varid8 = netcdf.defVar(f,'data','double',[dimid1 dimid2 dimid0]); netcdf.endDef(f) date_vec = datevec(dt); year = date_vec(1); month = date_vec(2); day = date_vec(3); % Open and read each file of unpacked cip images index = 1; for ii = 1:length(obj.cipfile) fprintf('Reading %s\n',obj.cipfile{ii}) fin = fopen(obj.cipfile{ii},'r','ieee-be'); data = fread(fin,'ubit2=>uint8'); fclose(fin); particle_index = 1; % Find the start index, time, and number of slices for each particle disp('Calling cipindex') [idx,sod,ns]=obj.cipindex(data); disp('Writing to the netCDF file'); % CIP image data are on a 12 hour clock % CSV sod have been corrected already delt = csvsod(1) - sod(1); if delt > 7*3600 && delt < 17*3600 sod = sod + 12*3600.; end % Convert the second of the day to matlab date number format dnum = dt + sod/86400; % Interpolate the true airspeeds from the CSV files for each particle tas = interp1(csvsod,csvtas,sod); % Roll back HHMMSS if a flight crosses midnight sod(sod>=240000) = sod(sod>=240000) - 240000; % Construct 4096 byte buffer (512 pixels) while(particle_index < length(ns)) len = 1; img_array = -1*ones(512,64); while(len+ns(particle_index)+1 < 512 && particle_index < length(ns)) img_array(len:len+ns(particle_index)+1, :) = reshape(data(idx(particle_index):((idx(particle_index))+(ns(particle_index)+2)*64-1)), 64, ns(particle_index)+2)'; len = len+ns(particle_index)+2; particle_index = particle_index+1; end hour = floor(sod(particle_index)/3600); minute = floor((sod(particle_index)-hour*3600)/60); second = floor(sod(particle_index)-hour*3600-minute*60); millisec = floor((sod(particle_index)-hour*3600-minute*60-second)*100); disp(['Writing frame ' num2str(index)]); % Write buffer netcdf.putVar ( f, varid0, index, 1, year ); netcdf.putVar ( f, varid1, index, 1, month ); netcdf.putVar ( f, varid2, index, 1, day ); netcdf.putVar ( f, varid3, index, 1, hour ); netcdf.putVar ( f, varid4, index, 1, minute ); netcdf.putVar ( f, varid5, index, 1, second ); netcdf.putVar ( f, varid6, index, 1, millisec ); netcdf.putVar ( f, varid8, [0, 0, index], [64,512,1], img_array' ); index = index+1; end end netcdf.close(f); function tword = timing(dsec,tmask) % TIMING - Create the timing word % % timing(sod,tmask) % sod - second of the day for this particle % tmask - timing work pattern that indicates that it is a timing word % 0xAAAAAA0000000000 dsec = dsec * 12E6; % 4294967296 is 2^32 tword = [bitor(uint32(mod(dsec/4294967296,16)),tmask); ... uint32(mod(dsec,4294967296))];
github
jjjjfrench/UW-UIOPS-master
calc_sa_randombins.m
.m
UW-UIOPS-master/size_dist/calc_sa_randombins.m
1,543
utf_8
cb8c10040d091f0b4de96c6092c55177
% Calculate image sample area assuming Heymsfield and Parish (1978) % bins_mid - mid-point of each bins in doide number % res - photodiode resolution, bin width in microns % armdst - distance between probe arms in millimeters % num_diodes - number of photodiodes (does not need to equal number of bins) % SAmethod - method to calculate SA. Could be 0: center in, 1: entire in and 2 with correction % % ** Created to replace calc_sa to include different bin setup, and three choices of SA % calculation methods. Notice the parameter differences. Will, 2014/06/04 function sa = calc_sa_randombins(bins_mid,res,armdst,num_diodes, SAmethod, probetype) % calculates OAP SA in mm^2 with res in um, armdist in mm res = res * 1e-3; %mm %max_diameter = max_diameter*.5e-3; radius = bins_mid/2; %radius = bins_mid .* res/2; You can use this one if you provide midpoint in doide number diameter = 2 * radius; % Calculate the width switch SAmethod case 0 % Center in EAWci = num_diodes*res; EAWri = EAWci; case 1 % Entire in EAWci = (num_diodes-(bins_mid/res)+1)*res; EAWci(EAWci<0)=0; EAWri = EAWci; case 2 % With Correction EAWci = num_diodes*res; EAWri = EAWci + 0.72*diameter; end % Calculate the DOF lambda = 680 * 1e-6; % mm,laser wavelength if probetype==2 DOF = 20.52*radius.^2*1000; else DOF = 6*radius.^2/lambda; % Using end DOF(DOF > armdst) = armdst; %DOF = armdst; sa = DOF .* EAWri;
github
jjjjfrench/UW-UIOPS-master
sizeDist.m
.m
UW-UIOPS-master/size_dist/sizeDist.m
94,194
utf_8
8a37ee7097c7ff455f57007b112dcf12
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Derive the area and size distribution for entire-in particles % Include the IWC calculation % Include the effective radius % Created by Will Wu, 09/18/2013 % % ************************** % *** Modification Notes *** % ************************** % * Modified to use the new maximum size and derive both maximum size distribution % and area-equivalent size distribution. % Will Wu, 10/26/2013 % * Modified to calculate terminal velocity using Heymsfield and Westbrook (2010) method % and precipitation rate. % Will Wu, 01/15/2014 % * Modified to include mass size distribution with habit info. % Will Wu, 02/09/2014 % * Modified to include particle area using A-D relations. % Will Wu, 02/14/2014 % * Special Edition for Boston Cloud workshop. % Wei Wu, 04/01/2014 % * Gneralized as a new sorting function for all probes. % Wei Wu, 07/25/2014 % * Modified to allow the option to ingest/use interarrival time dynamic threshold % Dan Stechman, 05/06/2016 % * Added project and date specific capabilities (including spiral-dependent interarrival % thresholding). Also cleaned up code and improved efficiency in places. % Dan Stechman, 06/03/2016 % * Added shatter removal using array of interarrival time thresholds (either constant or varrying [e.g., different threshold for % each spiral in PECAN project]). Also added experimental shatter reacceptance option to allow for potential diffraction fringes % originally flagged as shattered to be reaccepted. % Dan Stechman, 06/09/2016 % * Expanded upon time-varying interarrival time thresholds and reacceptance of particles for GPM (GCPEx, OLYMPEX) campaigns. % Also added option to save out information on interarrival times and sample volume. % Bug fix for calculation of 'n' and 'count' to un-normalize by binwidth. % Bug fix when syncing particle time with flight time. % Joe Finlon, 03/03/2017 % * Resolved indexing issue in the event that tas array covers more time % than the autoanalysis file when attempting to sync times % Added typecasting when writing netcdf file with putVar to resolve % errors where putVar would break because variables were of wrong type % Adam Majewski, 05/26/2017 % % Usage: % infile: Input filename, string % outfile: Output filename, string % tas: True air speed, double array % timehhmmss: Time in hhmmss format, double array % probename: Should be one of 'HVPS', 'CIP', 'PIP', '2DC', '2DP', 'F2DC' % d_choice: the definition of Dmax, should use 6 usually. [1-6] % SAmethod: 0: Center in; 1: Entire in; 2: With Correction % Pres: 1 second pressure data % Temp: 1 second temperature data % projectname: Project name, string % ddate: Date to be analyzed, string (YYYYMMDD) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sizeDist(infile, outfile, tas, timehhmmss, probename, d_choice, SAmethod, Pres, Temp, projectname, ddate, varargin) iCreateBad = 0; % Default not to output bad particles PSDs and other info iCreateAspectRatio = 0; % Default not to process aspect ratio info iSaveIntArrSV = 0; % Default not to save inter-arrival and sample volume information %% Interarrival threshold file specification % Can be implemented if a time-dependent threshold is required - add 'varargin' to arguments in function header above if length(varargin) == 1 iaThreshFile = varargin{1}; elseif length(varargin)>1 display('You have added too many inputs!') iaThreshFile = 'NONE'; end %% Define input and output files and initialize time variable f = netcdf.open(infile,'nowrite'); mainf = netcdf.create(outfile, 'clobber'); % Fix flight times if they span multiple days - Added by Joe Finlon - % 03/03/17 timehhmmss(find(diff(timehhmmss)<0)+1:end)=... timehhmmss(find(diff(timehhmmss)<0)+1:end) + 240000; % tas_char = num2str(timehhmmss); %Unused tas_time = floor(timehhmmss/10000)*3600+floor(mod(timehhmmss,10000)/100)*60+floor(mod(timehhmmss,100)); % averaging_time = 1; timehhmmss = mod(timehhmmss, 240000); %% Project-, probe-, and date-specific information switch projectname case 'PECAN' switch probename case 'CIP' num_diodes =64; diodesize = 0.025; % units of mm armdst=100.; % num_bins = 64; % kk=diodesize/2:diodesize:(num_bins+0.5)*diodesize; num_bins=19; kk=[50.0 100.0 150.0 200.0 250.0 300.0 350.0 400.0 475.0 550.0 625.0 ... 700.0 800.0 900.0 1000.0 1200.0 1400.0 1600.0 1800.0 2000.0]/1000; %Array in microns - converted to mm probetype=1; tasMax=200; % Max airspeed that can be sampled without under-sampling (images would appear skewed) applyIntArrThresh = 1; defaultIntArrThresh = 1e-5; reaccptShatrs = 1; reaccptD = 0.5; % Diammeter (in mm) to reaccept if initially flagged as shattered reaccptMaxIA = 2.5e-7; % Max interarrival time in seconds a particle can have to be reaccepted if % size criteria are met. Possible definition of this is the time of one slice, so in % this case, with an airspeed of ~100 m/s and a slice of 25 um, this would be 2.5e-7. % Get start and end times (in seconds) of spirals; interarrival time thresholds for each spiral [startT, endT, ~, ~, intar_threshold_spirals] = getPECANparams(ddate, probename); intar_threshold = ones(size(tas_time))*defaultIntArrThresh; for ix = 1:length(tas_time) for iz = 1:length(startT) if (tas_time(ix) >= startT(iz) && tas_time(ix) < endT(iz)) intar_threshold(ix) = intar_threshold_spirals(iz); end end end case 'PIP' num_diodes =64; diodesize = 0.1; %units of mm armdst=260.; num_bins = 64; % kk=diodesize/2:diodesize:(num_bins+0.5)*diodesize; kk=diodesize/2:diodesize:(num_bins+0.6)*diodesize; % num_bins=19; % kk=[50.0 100.0 150.0 200.0 250.0 300.0 350.0 400.0 475.0 550.0 625.0 ... % 700.0 800.0 900.0 1000.0 1200.0 1400.0 1600.0 1800.0 2000.0]*4/1000; probetype=1; tasMax=200; applyIntArrThresh = 1; defaultIntArrThresh = 1e-5; reaccptShatrs = 1; reaccptD = 0.5; % Diammeter (in mm) to reaccept if initially flagged as shattered reaccptMaxIA = 1e-6; % (Slice size [m])/(avg. airspeed [m/s]) % Get start and end times (in seconds) of spirals; interarrival time thresholds for each spiral [startT, endT, ~, ~, intar_threshold_spirals] = getPECANparams(ddate, probename); intar_threshold = ones(size(tas_time))*defaultIntArrThresh; for ix = 1:length(tas_time) for iz = 1:length(startT) if (tas_time(ix) >= startT(iz) && tas_time(ix) < endT(iz)) intar_threshold(ix) = intar_threshold_spirals(iz); end end end end case 'GPM' switch probename case '2DS' % For the 2DS num_diodes =128; diodesize = .010; armdst=63.; num_bins =22; kk=[40.0 60.0 80.0 100.0 125.0 150.0 200.0 250.0 300.0 350.0 400.0 ... 475.0 550.0 625.0 700.0 800.0 900.0 1000.0 1200.0 1400.0 1600.0 1800.0 2000.0]/1000; probetype=2; tasMax=170; % Interarrival threshold and reaccept max interarrival time are often flight-/instrument-specific % **Values here may not be correct** % The interarrival threshold can be modifided to change second-by-second if desired applyIntArrThresh = 1; defaultIntArrThresh = 1e-6; reaccptShatrs = 1; reaccptD = 0.5; reaccptMaxIA = 1e-6; % (Slice size [m])/(avg. airspeed [m/s]) case 'HVPS' % For the HVPS num_diodes =128; diodesize = .150; armdst=161.; num_bins = 28; kk=[200.0 400.0 600.0 800.0 1000.0 1200.0 1400.0 1600.0 1800.0 2200.0 2600.0 ... 3000.0 3400.0 3800.0 4200.0 4600.0 5000.0 6000.0 7000.0 8000.0 9000.0 10000.0 ... 12000.0 14000.0 16000.0 18000.0 20000.0 25000.0 30000.0]/1000; probetype=2; tasMax=170; % Interarrival threshold and reaccept max interarrival time are often flight-/instrument-specific % **Values here may not be correct** % The interarrival threshold can be modifided to change second-by-second if desired applyIntArrThresh = 0; defaultIntArrThresh = 1e-6; reaccptShatrs = 0; reaccptD = 0.5; reaccptMaxIA = 1e-6; % (Slice size [m])/(avg. airspeed [m/s]) end otherwise switch probename case 'HVPS' % For the HVPS num_diodes =128; diodesize = .150; armdst=161.; num_bins = 28; kk=[200.0 400.0 600.0 800.0 1000.0 1200.0 1400.0 1600.0 1800.0 2200.0 2600.0 ... 3000.0 3400.0 3800.0 4200.0 4600.0 5000.0 6000.0 7000.0 8000.0 9000.0 10000.0 ... 12000.0 14000.0 16000.0 18000.0 20000.0 25000.0 30000.0]/1000; %num_bins =128; %kk=diodesize/2:diodesize:(num_bins+0.5)*diodesize; probetype=2; tasMax=170; % Interarrival threshold and reaccept max interarrival time are often flight-/instrument-specific % **Values here may not be correct** % The interarrival threshold can be modifided to change second-by-second if desired applyIntArrThresh = 0; defaultIntArrThresh = 4e-6; reaccptShatrs = 0; reaccptD = 0.5; reaccptMaxIA = 1e-6; % (Slice size [m])/(avg. airspeed [m/s]) intar_threshold = ones(size(tas_time))*defaultIntArrThresh; case '2DS' % For the HVPS num_diodes =128; diodesize = .010; armdst=61.; %num_bins = 28; %kk=[200.0 400.0 600.0 800.0 1000.0 1200.0 1400.0 1600.0 1800.0 2200.0 2600.0 ... % 3000.0 3400.0 3800.0 4200.0 4600.0 5000.0 6000.0 7000.0 8000.0 9000.0 10000.0 ... % 12000.0 14000.0 16000.0 18000.0 20000.0 25000.0 30000.0]/1000/15; num_bins =128; %kk=diodesize/2:diodesize:(num_bins+0.5)*diodesize; kk=diodesize/2:diodesize:(num_bins+0.6)*diodesize; probetype=2; tasMax=170; % Interarrival threshold and reaccept max interarrival time are often flight-/instrument-specific % **Values here may not be correct** % The interarrival threshold can be modifided to change second-by-second if desired applyIntArrThresh = 0; defaultIntArrThresh = 4e-6; reaccptShatrs = 0; reaccptD = 0.5; reaccptMaxIA = 1e-6; % (Slice size [m])/(avg. airspeed [m/s]) intar_threshold = ones(size(tas_time))*defaultIntArrThresh; case 'CIP' % For the CIP num_diodes =64; diodesize = .025; %units of mm armdst=61.; %num_bins = 64; %kk=diodesize/2:diodesize:(num_bins+0.5)*diodesize; num_bins=19; kk=[50.0 100.0 150.0 200.0 250.0 300.0 350.0 400.0 475.0 550.0 625.0 ... 700.0 800.0 900.0 1000.0 1200.0 1400.0 1600.0 1800.0 2000.0]/1000; %Array in microns - converted to mm probetype=1; tasMax=200; % Max airspeed that can be sampled without under-sampling (images would appear skewed) % Interarrival threshold and reaccept max interarrival time are often flight-/instrument-specific % **Values here may not be correct** % The interarrival threshold can be modifided to change second-by-second if desired applyIntArrThresh = 0; defaultIntArrThresh = 1e-5; reaccptShatrs = 0; reaccptD = 0.5; reaccptMaxIA = 1e-6; % (Slice size [m])/(avg. airspeed [m/s]) intar_threshold = ones(size(tas_time))*defaultIntArrThresh; case 'PIP' num_diodes =64; diodesize = .1; %units of mm armdst=260.; num_bins = 64; % kk=diodesize/2:diodesize:(num_bins+0.5)*diodesize; kk=diodesize/2:diodesize:(num_bins+0.6)*diodesize; % num_bins=19; % kk=[50.0 100.0 150.0 200.0 250.0 300.0 350.0 400.0 475.0 550.0 625.0 ... % 700.0 800.0 900.0 1000.0 1200.0 1400.0 1600.0 1800.0 2000.0]*4/1000; probetype=1; tasMax=200; % Interarrival threshold and reaccept max interarrival time are often flight-/instrument-specific % **Values here may not be correct** % The interarrival threshold can be modifided to change second-by-second if desired applyIntArrThresh = 0; defaultIntArrThresh = 1e-5; reaccptShatrs = 0; reaccptD = 0.5; reaccptMaxIA = 1e-6; % (Slice size [m])/(avg. airspeed [m/s]) intar_threshold = ones(size(tas_time))*defaultIntArrThresh; case '2DC' % For the 2DC num_diodes =32; diodesize = .03; %.025; armdst=61.; %num_bins = 32; %kk=diodesize/2:diodesize:(num_bins+0.5)*diodesize; num_bins=19; kk=[50.0 100.0 150.0 200.0 250.0 300.0 350.0 400.0 475.0 550.0 625.0 ... 700.0 800.0 900.0 1000.0 1200.0 1400.0 1600.0 1800.0 2000.0]/1000; probetype=0; tasMax=125; % Interarrival threshold and reaccept max interarrival time are often flight-/instrument-specific % **Values here may not be correct** % The interarrival threshold can be modifided to change second-by-second if desired applyIntArrThresh = 0; defaultIntArrThresh = 4e-6; reaccptShatrs = 0; reaccptD = 0.5; reaccptMaxIA = 1e-6; % (Slice size [m])/(avg. airspeed [m/s]) intar_threshold = ones(size(tas_time))*defaultIntArrThresh; case '2DP' % For the 2DP num_diodes =32; diodesize = .200; %.025; armdst=260.; %75.77; %61.; %num_bins = 32; %kk=diodesize/2:diodesize:(num_bins+0.5)*diodesize; num_bins=19; kk=[50.0 100.0 150.0 200.0 250.0 300.0 350.0 400.0 475.0 550.0 625.0 ... 700.0 800.0 900.0 1000.0 1200.0 1400.0 1600.0 1800.0 2000.0]*8/1000; probetype=0; tasMax = 125; % Interarrival threshold and reaccept max interarrival time are often flight-/instrument-specific % **Values here may not be correct** % The interarrival threshold can be modifided to change second-by-second if desired applyIntArrThresh = 0; defaultIntArrThresh = 4e-6; reaccptShatrs = 0; reaccptD = 0.5; reaccptMaxIA = 1e-6; % (Slice size [m])/(avg. airspeed [m/s]) intar_threshold = ones(size(tas_time))*defaultIntArrThresh; case 'F2DC' % For the 2DC num_diodes =64; diodesize = .025; %.025; armdst=61.; %60; % %num_bins = 32; %kk=diodesize/2:diodesize:(num_bins+0.5)*diodesize; num_bins=19; kk=[50.0 100.0 150.0 200.0 250.0 300.0 350.0 400.0 475.0 550.0 625.0 ... 700.0 800.0 900.0 1000.0 1200.0 1400.0 1600.0 1800.0 2000.0]/1000; probetype=0; % Interarrival threshold and reaccept max interarrival time are often flight-/instrument-specific % **Values here may not be correct** % The interarrival threshold can be modifided to change second-by-second if desired applyIntArrThresh = 0; defaultIntArrThresh = 4e-6; reaccptShatrs = 0; reaccptD = 0.5; reaccptMaxIA = 1e-6; % (Slice size [m])/(avg. airspeed [m/s]) intar_threshold = ones(size(tas_time))*defaultIntArrThresh; end end if applyIntArrThresh && ~reaccptShatrs fprintf('Beginning sizeDist_Paris.m for %s %s - %s probe\n\t**Optional parameters active:\n\t- Shatter removal\n\n',projectname,ddate,probename); elseif applyIntArrThresh && reaccptShatrs fprintf('Beginning sizeDist_Paris.m for %s %s - %s probe\n\t**Optional parameters active:\n\t- Shatter removal\n\t- Shatter reacceptance\n\n',... projectname,ddate,probename); else fprintf('Beginning sizeDist_Paris.m for %s %s - %s probe\n\n',projectname,ddate,probename); end res=diodesize*1000; binwidth=diff(kk); % SAmethod = 2; % for i=1:num_bins+1 % kk(i)= (diodesize*i)^2*3.1415926/4; % end %% Define Variables % Good particles (not rejected) particle_dist_minR = zeros(length(tas),num_bins)*NaN; particle_dist_AreaR = zeros(length(tas),num_bins)*NaN; particle_aspectRatio = zeros(length(tas),num_bins)*NaN; particle_aspectRatio1 = zeros(length(tas),num_bins)*NaN; particle_areaRatio1 = zeros(length(tas),num_bins)*NaN; particle_area = zeros(length(tas),num_bins)*NaN; cip2_meanp = zeros(length(tas),num_bins)*NaN; cip2_iwc = zeros(length(tas),num_bins)*NaN; cip2_iwcbl = zeros(length(tas),num_bins)*NaN; cip2_vt = zeros(length(tas),num_bins)*NaN; cip2_pr = zeros(length(tas),num_bins)*NaN; cip2_partarea = zeros(length(tas),num_bins)*NaN; cip2_re = zeros(1,length(tas))*NaN; good_partpercent=zeros(length(tas),1); goodintpercent=zeros(length(tas),1); numGoodparticles=zeros(length(tas),1); one_sec_ar=zeros(length(tas),1); cip2_habitsd = zeros(length(tas),num_bins,10)*NaN; cip2_habitmsd = zeros(length(tas),num_bins,10)*NaN; area_dist2 = zeros(length(tas),num_bins,10)*NaN; rejectpercentbycriterion=zeros(length(tas),14); % Bad particles (rejected) bad_particle_dist_minR = zeros(length(tas),num_bins)*NaN; bad_particle_dist_AreaR = zeros(length(tas),num_bins)*NaN; bad_particle_aspectRatio = zeros(length(tas),num_bins)*NaN; bad_particle_aspectRatio1 = zeros(length(tas),num_bins)*NaN; bad_particle_areaRatio1 = zeros(length(tas),num_bins)*NaN; bad_particle_area = zeros(length(tas),num_bins)*NaN; bad_cip2_meanp = zeros(length(tas),num_bins)*NaN; bad_cip2_iwc = zeros(length(tas),num_bins)*NaN; bad_cip2_iwcbl = zeros(length(tas),num_bins)*NaN; bad_cip2_vt = zeros(length(tas),num_bins)*NaN; bad_cip2_pr = zeros(length(tas),num_bins)*NaN; bad_cip2_partarea = zeros(length(tas),num_bins)*NaN; bad_cip2_re = zeros(1,length(tas))*NaN; badintpercent=zeros(length(tas),1); numBadparticles=zeros(length(tas),1); bad_one_sec_ar=zeros(length(tas),1); bad_cip2_habitsd = zeros(length(tas),num_bins,10)*NaN; bad_cip2_habitmsd = zeros(length(tas),num_bins,10)*NaN; bad_area_dist2 = zeros(length(tas),num_bins,10)*NaN; % particle_dist2 = zeros(length(tas),num_bins)*NaN; %Unused % time_interval1 = zeros(length(tas), 1); %Unused % cip2_ar = zeros(1,length(tas))*NaN; %Unused % throwoutpercent=zeros(length(tas),1); %Used in legacy interarrival time analysis % totalint=zeros(length(tas),1); %Used in legacy interarrival time analysis % intsum=zeros(length(tas),1); %Used in legacy interarrival time analysis area_bins = 0:.1:1.01; one_sec_times = tas_time; one_sec_dur = length(one_sec_times); total_one_sec_locs(1:one_sec_dur) = 0; start_time = floor(tas_time(1)); end_time = ceil(tas_time(end)); one_sec_tas(1:one_sec_dur) = 0; one_sec_tas_entire(1:one_sec_dur) = 0; deadtime(1:one_sec_dur) = 0; warning off all one_sec_times=[one_sec_times;one_sec_times(one_sec_dur)+1]; time_interval2 = zeros(one_sec_dur,1); TotalPC1 = zeros(one_sec_dur,1)'; TotalPC2 = zeros(one_sec_dur,1)'; % Used for debugging of interarrival time analysis shatrReject_times = []; shatrReject_intArr = []; shatrReject_diam = []; rccptReject_times = []; rccptReject_intArr = []; rccptReject_diam = []; loopedTimes = []; loopedIntArr = []; loopedDiam = []; loopedAutoRej = []; %% Load particles for each second, and then process them % Only for large files cannot be processed at once [~, NumofPart] = netcdf.inqDim(f,0); % Check the number of particles dateall = netcdf.getVar(f,netcdf.inqVarID(f,'Date')); if 1==probetype image_time_hhmmssall = netcdf.getVar(f,netcdf.inqVarID(f,'particle_time')); elseif 2==probetype image_time_hhmmssallbuffer = netcdf.getVar(f,netcdf.inqVarID(f,'Time')); % image_time_hhmmssallbuffer(image_time_hhmmssallbuffer<10000 & image_time_hhmmssallbuffer>=0)=image_time_hhmmssallbuffer(image_time_hhmmssallbuffer<10000 & image_time_hhmmssallbuffer>=0)+240000; alltimeinseconds = netcdf.getVar(f,netcdf.inqVarID(f,'Time_in_seconds')); time_msec_all = netcdf.getVar(f,netcdf.inqVarID(f,'msec'),0,1); indexRollback=find(diff(alltimeinseconds)<-250)+1; for i=1:length(indexRollback) alltimeinseconds(indexRollback(i):end)=alltimeinseconds(indexRollback(i):end)+(2^32-1)*(res/10^6/tasMax); end % alltimeinsecondsstart=alltimeinseconds(indexBuffert); % increaseAllinseconds= alltimeinseconds-alltimeinseconds(1); % increaseAllinseconds(increaseAllinseconds<0)=increaseAllinseconds(increaseAllinseconds<0)+(2^32-1)*(res/10^6/170); % image_time_hhmmssall = insec2hhmmss(floor(47069+time_msec_all(1)/1000.0+increaseAllinseconds*170/110)); image_time_hhmmssall = image_time_hhmmssallbuffer; else image_time_hhmmssall = netcdf.getVar(f,netcdf.inqVarID(f,'Time')); end % image_time_hhmmssall = netcdf.getVar(f,netcdf.inqVarID(f,'Time')); % image_time_hhmmssall(image_time_hhmmssall<50000 & image_time_hhmmssall>=0)=image_time_hhmmssall(image_time_hhmmssall<50000 & image_time_hhmmssall>=0)+120000; % Fix particle times if they span multiple days - Added by Joe Finlon - % 03/03/17 %image_time_hhmmssall(find(diff(image_time_hhmmssall)<0)+1:end)=... % image_time_hhmmssall(find(diff(image_time_hhmmssall)<0)+1:end) + 240000; % Find all indices (true/1) with a unique time in hhmmss - in other words, we're getting the particle index where each new % one-second period starts startindex=[true;(diff(hhmmss2insec(image_time_hhmmssall))>0)]; % & diff(hhmmss2insec(image_time_hhmmssall))<5)]; % Simplified (tested/changed by DS) startdate=dateall(startindex); % startindex=int8(image_time_hhmmssall*0); % for i=1:length(timehhmmss) % indexofFirstTime = find(image_time_hhmmssall==timehhmmss(i),1); % if ( ~isempty(indexofFirstTime) ) % startindex(indexofFirstTime)=1; % end % disp([i,length(timehhmmss)]); % end % Get the start time for each new one-second period starttime=image_time_hhmmssall(startindex); % Simplified (tested/changed by DS) % Find all instances where startindex is true (where image_time_hhmmssall changes by more than 0) and shift indices back by one to % facilitate proper particle counts for each one-second period start_all=find(startindex)-1; % Simplified (tested/changed by DS) % Sort the particle one-second time array in the event it is out of order and redefine the start_all variable as needed %[starttime,newindexofsort]=sort(starttime); %start_all=start_all(newindexofsort); %% Remove times when there is no tas data available % nNoTAS=0; % for i=1:length(starttime) % if isempty(timehhmmss(timehhmmss == starttime(i))) % starttime(i)=500000; % nNoTAS=nNoTAS+1; % end % % if i>5 & i<length(starttime)-5 & hhmmss2insec(starttime(i))>mean(hhmmss2insec(starttime(i-5:i+5)))+5 % starttime(i)=500000; % end % end % nNoTAS % start_all = start_all(starttime<500000); % count_all = count_all(starttime<500000); % starttime = starttime(starttime<500000); %% Remove any duplicate times and determine how many particles are present in each one-second period fprintf('Number of duplicate times = %d\n\n',(length(starttime)-length(unique(starttime)))); %[starttime, ia, ~] = unique(starttime,'first'); %start_all = start_all(ia); count_all= [diff(start_all); NumofPart-start_all(end)]; count_all(count_all<0)=1; %% Remove times when there are less than 10 particles in one second % starttime = starttime(count_all>10); % start_all = start_all(count_all>10); % count_all = count_all(count_all>10); %if (int32(timehhmmss(1))>int32(starttime(2))) % error('Watch Out for less TAS time from begining!') %end %% Main loop over the length of the true air speed variable (1-sec resolution) jjj=1; sumIntArrGT1 = 0; intArrGT1 = []; % nThrow11=0; % Used in legacy interarrival time analysis % maxRecNum=1; % Used in legacy interarrival time analysis fprintf('Beginning size distribution calculations and sorting %s\n\n',datestr(now)); for i=1:length(tas) if ( int32(mod(timehhmmss(end)-timehhmmss(i),240000))<=int32(mod(timehhmmss(end)-starttime(jjj),240000)) ) % Attempt to sync TAS file time (timehhmmss) with particle time % if (int32(timehhmmss(i))>int32(starttime(jjj))) %% Deprecated % (Joe Finlon - 03/03/17) % Rearranged order to successfully break out of the loop at the % right index in the event that the tas array covers more time than % the autoanalysis files while ( (int32(timehhmmss(i))>int32(starttime(jjj))) && (int32(starttime(jjj))>int32(timehhmmss(end)))) % Added by Joe Finlon - 03/03/17 if (jjj>=length(start_all)) break; end jjj=jjj+1; end start=start_all(jjj); count=count_all(jjj); jjj=min(jjj+1,length(start_all)); % Load autoanalysis parameters. Start at beginning (start) of some one-second period and load the values for every % particle in that period (count) cdate = netcdf.getVar(f,netcdf.inqVarID(f,'Date'),start,count); msec = netcdf.getVar(f,netcdf.inqVarID(f,'particle_millisec'),start,count); microsec = netcdf.getVar(f,netcdf.inqVarID(f,'particle_microsec'),start,count); auto_reject = netcdf.getVar(f,netcdf.inqVarID(f,'image_auto_reject'),start,count); im_width = netcdf.getVar(f,netcdf.inqVarID(f,'image_width'),start,count); im_length = netcdf.getVar(f,netcdf.inqVarID(f,'image_length'),start,count); area = netcdf.getVar(f,netcdf.inqVarID(f,'image_area'),start,count); perimeter = netcdf.getVar(f,netcdf.inqVarID(f,'image_perimeter'),start,count); if probetype == 0 rec_nums = netcdf.getVar(f,netcdf.inqVarID(f,'parent_rec_num'),start,count); end % top_edges = netcdf.getVar(f,netcdf.inqVarID(f,'image_max_top_edge_touching'),start,count); %Unused % bot_edges = netcdf.getVar(f,netcdf.inqVarID(f,'image_max_bottom_edge_touching'),start,count); %Unused % longest_y = netcdf.getVar(f,netcdf.inqVarID(f,'image_longest_y'),start,count); %Unused size_factor = netcdf.getVar(f,netcdf.inqVarID(f,'size_factor'),start,count); habit1 = netcdf.getVar(f,netcdf.inqVarID(f,'holroyd_habit'),start,count); centerin = netcdf.getVar(f,netcdf.inqVarID(f,'image_center_in'),start,count); entirein = netcdf.getVar(f,netcdf.inqVarID(f,'image_touching_edge'),start,count); particle_diameter_AreaR = netcdf.getVar(f,netcdf.inqVarID(f,'image_diam_AreaR'),start,count); particle_diameter_AreaR = particle_diameter_AreaR * diodesize; Time_in_seconds = netcdf.getVar(f,netcdf.inqVarID(f,'Time_in_seconds'),start,count); % SliceCount = netcdf.getVar(f,netcdf.inqVarID(f,'SliceCount'),start,count); %Unused DMT_DOF_SPEC_OVERLOAD = netcdf.getVar(f,netcdf.inqVarID(f,'DMT_DOF_SPEC_OVERLOAD'),start,count); Particle_count = netcdf.getVar(f,netcdf.inqVarID(f,'Particle_number_all'),start,count); if 1==probetype auto_reject(DMT_DOF_SPEC_OVERLOAD~=0)='D'; end if iCreateAspectRatio == 1 aspectRatio = netcdf.getVar(f,netcdf.inqVarID(f,'image_RectangleW'),start,count)./netcdf.getVar(f,netcdf.inqVarID(f,'image_RectangleL'),start,count); aspectRatio1 = netcdf.getVar(f,netcdf.inqVarID(f,'image_EllipseW'),start,count)./netcdf.getVar(f,netcdf.inqVarID(f,'image_EllipseL'),start,count); end TotalPC1(i)=length(Particle_count); TotalPC2(i)=Particle_count(end)-Particle_count(1); if 0==probetype int_arr=Time_in_seconds; else if start-1 <= 0 int_arr = [0;diff(Time_in_seconds)]; int_arr2 = []; %Won't bother reaccepting particles at the beginning or end of dataset else Time_in_seconds2 = netcdf.getVar(f,netcdf.inqVarID(f,'Time_in_seconds'),start-1,count+1); int_arr = diff(Time_in_seconds2); if start ~= start_all(end) %Time_in_seconds3 = netcdf.getVar(f,netcdf.inqVarID(f,'Time_in_seconds'),(start+count)-1,2); %int_arr2 = diff(Time_in_seconds3); %Single value describing interarrival time of first particle of next 1-sec period else int_arr2 = []; end end %int_arr2(int_arr2<0)=0; if reaccptShatrs if start ~= start_all(end) Time_in_seconds4 = netcdf.getVar(f,netcdf.inqVarID(f,'Time_in_seconds'),start,count+1); int_arr3 = diff(Time_in_seconds4); else Time_in_seconds4 = Time_in_seconds; int_arr3 = diff(Time_in_seconds4); int_arr3 = [int_arr3;int_arr3(end)]; end int_arr3(int_arr3<0)=0; end end % if 2==probetype % int_arr=int_arr*(res/10^6/170); % end if 2==probetype int_arr(int_arr<-10)=int_arr(int_arr<-10)+(2^32-1)*(res/10^6/tasMax); elseif 0==probetype int_arr(int_arr<0)=int_arr(int_arr<0)+(2^24-1)*(res/10^6/tasMax); end if sum(int_arr<0)>0 fprintf(2,'\nAt index %d number of int_arr < 0: %d\n',i,sum(int_arr<0)); disp([int_arr(int_arr<0),int_arr(int_arr<0)+(2^32-1)*(res/10^6/tasMax)]); elseif sum(int_arr>1)>0 sumIntArrGT1 = sumIntArrGT1 + sum(int_arr > 1); tempLocs = find(int_arr > 1); intArrGT1 = vertcat(intArrGT1,int_arr(tempLocs)); % fprintf(2,'\nAt index %d number of int_arr > 1: %d\n',i,sum(int_arr>1)); % disp([int_arr(int_arr>1)-(2^32-1)*(res/10^6/tasMax), int_arr(int_arr>1), Time_in_seconds(int_arr>1)/(0.15/(10^3)/170), Time_in_seconds((int_arr>1))/(0.15/(10^3)/170)]); end % auto_reject(int_arr<0 | int_arr>1)='I'; auto_reject(int_arr<0)='I'; int_arr(int_arr<0)=0; % int_arr(int_arr>1)=0; % max_dimension = im_width; % max_dimension(im_length>im_width)=im_length(im_length>im_width); % Size definition chosen based on the d_choice given in the function call if 1==d_choice particle_diameter_minR = im_length * diodesize; %(im_length+ elseif 2==d_choice particle_diameter_minR = im_width * diodesize; %(im_length+ elseif 3==d_choice particle_diameter_minR = (im_length + im_width)/2 * diodesize; %(im_length+ elseif 4==d_choice particle_diameter_minR = sqrt(im_width.^2+im_length.^2) * diodesize; %(im_length+ elseif 5==d_choice particle_diameter_minR = max(im_width, im_length) * diodesize; %(im_length+ elseif 6==d_choice particle_diameter_minR = netcdf.getVar(f,netcdf.inqVarID(f,'image_diam_minR'),start,count); % * diodesize end % if 1==strcmp('2DC',probename) % Adjust resolution from 25 to 30 % particle_diameter_minR=particle_diameter_minR*1.2; % area = area*1.44; % end % Legacy: Added for Paris meeting, 08/25/2014 % Used in intercomparison with Environment Canada and University of Blaise Pascal %{ diffPartCount=[1;diff(Particle_count)]; time_interval22(i) = (Time_in_seconds(end)-Time_in_seconds(1)); time_interval32(i) = sum(int_arr(diffPartCount==1)); time_interval42(i) = sum(int_arr); time_interval52(i) = sum(int_arr(diffPartCount~=1)); time_interval62(i) = sum(int_arr(DMT_DOF_SPEC_OVERLOAD==0)); lengthForTemp = im_length * diodesize; particle_diameter_minR(entirein~=0)=lengthForTemp(entirein~=0); if time_interval22(i)<0 time_interval22(i)=time_interval22(i)+(2^32-1)*(res/10^6/tasMax); %#ok<*AGROW> end if RejectCriterier==1 particle_diameter_minR = particle_diameter_minR .* size_factor; end if 1==probetype image_time_hhmmss = netcdf.getVar(f,netcdf.inqVarID(f,'particle_time'),start,count); image_time_hhmmssnew = netcdf.getVar(f,netcdf.inqVarID(f,'particle_time'),start,count); elseif 2==probetype alltimeinseconds = netcdf.getVar(f,netcdf.inqVarID(f,'Time_in_seconds'),start,count); increaseAllinseconds= alltimeinseconds-alltimeinseconds(1); increaseAllinseconds(increaseAllinseconds<0)=increaseAllinseconds(increaseAllinseconds<0)+(2^32-1)*(res/10^6/170); image_time_hhmmss = floor(hhmmss2insec(netcdf.getVar(f,netcdf.inqVarID(f,'Time'),start,count))+netcdf.getVar(f,netcdf.inqVarID(f,'msec'),start,count)/1000+increaseAllinseconds); % 'Time'? image_time_hhmmss = insec2hhmmss(image_time_hhmmss); image_time_hhmmssnew = image_time_hhmmss; end %} time_interval72(i) = sum(int_arr(DMT_DOF_SPEC_OVERLOAD~=0)); %2DP overload handling - Adam Majewski 9/28/17 if probetype == 0 rec_start = diff(rec_nums)>0; time_interval72(i) = sum(DMT_DOF_SPEC_OVERLOAD(rec_start))/1000.; %total overload time for the one second period in seconds end % Simplified by DS - Removed image_time_hhmmssnew as it was defined by and never changed from image_time_hhmmss image_time_hhmmss = image_time_hhmmssall(start+1:start+count); % If image time crosses midnight, add 240000 to all times past midnight % image_time_hhmmss(image_time_hhmmss<10000)=image_time_hhmmss(image_time_hhmmss<10000)+240000; % Save an intermediate output file every 8000 steps through the loop if i==8000 save([outfile(1:end-3) 'tempComp.mat']); end %% Calculate area of particle according to image reconstruction and airspeed (if tasMax exceeded) % Correct for airspeeds exceeding the max airspeed for the probe if(tas(i) > tasMax) % Set to threshold as necessary - stretch area of particle fprintf(2,'TAS at tas index %d exceeds tasMax (%.1f) of probe. Reconstructing area...\n\n',... i,tasMax); area = area*tas(i)/tasMax; end particle_mass = area*0; calcd_area = area*0; for iiii=1:length(area) particle_mass(iiii)=single_mass(particle_diameter_minR(iiii)/10, habit1(iiii)); % in unit of gram calcd_area(iiii)=single_area(particle_diameter_minR(iiii)/10, habit1(iiii)); % in unit of mm^2 end particle_massbl=0.115/1000*area.^(1.218); % in unit of gram %% Added by Robert Jackson -- old version did not have area ratio code area_ratio = area./(pi/4.*particle_diameter_minR.^2); auto_reject(area_ratio < .2) = 'z'; %% Added by Will to calculate terminal velocity and precipitation rate particle_vt = area*0; for iiii=1:length(area) particle_vt(iiii)=single_vt(particle_diameter_minR(iiii)/1000, area_ratio(iiii), particle_mass(iiii)/1000,Pres(i),Temp(i)); % in unit of gram end particle_pr=particle_mass.*particle_vt; %% Time-dependent threshold for interarrival time - Added by Dan Stechman - 5/10/16 & Modified by Joe Finlon - 03/03/17 % Enable this section to use a time-dependent threshold for interarrival time. Also need to enable section at top of % script allowing for threshold file to be pulled in % Ingest previously calculated interarrival time threshold and flag in auto_reject appropriately to remove particle % flagged with short inter arrv time, and the one immediately before it if applyIntArrThresh && length(varargin) == 1 && strcmp(iaThreshFile,'NONE') == 0 auto_reject_preIAT = auto_reject; iaThresh_ncid = netcdf.open(iaThreshFile,'nowrite'); iaThresh = netcdf.getVar(iaThresh_ncid,netcdf.inqVarID(iaThresh_ncid,'threshold'),start,count); netcdf.close(iaThresh_ncid); if ((length(int_arr) == 1) && (int_arr(1) <= iaThresh(1))) auto_reject(1) = 'S'; else if int_arr(1) <= iaThresh(1) auto_reject(1) = 'S'; end for ix = 2:length(int_arr) if int_arr(ix) <= iaThresh(ix) auto_reject((ix-1):ix) = 'S'; end end end % Experimental option to reaccept particles flagged as shattered which may in fact be the result of diffraction % fringes % Added by Dan Stechman - 6/8/2015 & Modified by Joe Finlon - 03/03/17 - with base code by Wei Wu if reaccptShatrs % Start by defining the indices for the beginning and end of individual shattering events rBegin = ((int_arr > iaThresh & int_arr3 < iaThresh)); rEnd = ((int_arr < iaThresh & int_arr3 > iaThresh)); maxParticle = reaccptD; eIndex = []; % We search through each individual set of shattering events and check to see if any of the particles are both % larger than the reacceptance diameter and have an interarrival time less than the reacceptance threshold as we'd % expect diffraction fringes to be larger than shattered particles and to have a particularly small interarrival time for iEvent = find(rBegin):find(rEnd) if ((particle_diameter_minR(iEvent) > maxParticle) && (int_arr(iEvent) < reaccptMaxIA)) maxParticle = particle_diameter_minR(iEvent); eIndex = iEvent; end end auto_reject(eIndex) = 'R'; end % Following vars used for verifying shatter removal and reacceptance in external script - can be commented out if desired shatterLocs = find(auto_reject == 'S'); shatterIA = int_arr(shatterLocs); shatterTimes = Time_in_seconds(shatterLocs); shatterDiam = particle_diameter_minR(shatterLocs); shatrReject_times = vertcat(shatrReject_times, shatterTimes); shatrReject_intArr = vertcat(shatrReject_intArr, shatterIA); shatrReject_diam = vertcat(shatrReject_diam, shatterDiam); rccptLocs = find(auto_reject == 'R'); rccptIA = int_arr(rccptLocs); rccptTimes = Time_in_seconds(rccptLocs); rccptDiam = particle_diameter_minR(rccptLocs); rccptReject_times = vertcat(rccptReject_times, rccptTimes); rccptReject_intArr = vertcat(rccptReject_intArr, rccptIA); rccptReject_diam = vertcat(rccptReject_diam, rccptDiam); loopedTimes = vertcat(loopedTimes, Time_in_seconds); loopedIntArr = vertcat(loopedIntArr, int_arr); loopedDiam = vertcat(loopedDiam, particle_diameter_minR); loopedAutoRej = vertcat(loopedAutoRej, auto_reject); end %% Legacy interarrival time integrity analysis %{ % Time and interarrival calculation. Modified by Will Wu 11/12/2013 % Simplified (tested/changed by DS) if strcmp(probename,'2DC')==1 || strcmp(probename,'2DP')==1 || strcmp(probename,'F2DC')==1 fracseccc= netcdf.getVar(f,netcdf.inqVarID(f,'msec'),start,count); image_timeia = hhmmss2insec(image_time_hhmmss)+fracseccc*1e-2; % for 2DC elseif strcmp(probename,'CIP')==1 || strcmp(probename,'PIP')==1 image_timeia = hhmmss2insec(image_time_hhmmss)+msec*1e-3+microsec; % for CIP else image_timeia = hhmmss2insec(image_time_hhmmss)+msec*1e-3+microsec/10^6; % for HVPS end disp('Checking Interarrival Times') nThrow=0; for(itemp=min(rec_nums):max(rec_nums)) rec_particles = find(rec_nums == itemp); rej = auto_reject(rec_particles); arr = int_arr(rec_particles); sum_arr = sum(arr(2:end)); if(~isempty(rec_particles) && length(rec_particles) > 1) int_arr(rec_particles(1)) = int_arr(rec_particles(2)); elseif(length(rec_particles) == 1) int_arr(rec_particles(1)) = 0; end if (strcmp(probename,'CIP')==1 || strcmp(probename,'PIP')==1 || strcmp(probename,'HVPS')==1 ) % 2DC use the interarrival time for every particles, not absolute time if(isempty(rec_particles)) sum_int_arr_good = 0; else sum_int_arr_good = image_timeia(rec_particles(end))-image_timeia(rec_particles(1)); end if ~(sum_int_arr_good >= .6*sum_arr && sum_int_arr_good <= 1.4*sum_arr) auto_reject(rec_particles) = 'I'; %disp(['Record ' num2str(itemp) ' thrown out: Accepted time = ' num2str(sum_int_arr_good) ' total time = ' num2str(sum_arr)]); nThrow=nThrow+1; nThrow11=nThrow11+1; end end end disp([num2str(100*nThrow/(max(rec_nums)-min(rec_nums)+1)),'% is thrown out']); throwoutpercent(i)=100*nThrow/(max(rec_nums)-min(rec_nums)+1); maxRecNum=max(max(rec_nums),maxRecNum); totalint(i)=sum_int_arr_good; intsum(i)=sum_arr; save('intarrhvps.mat','int_arr') %} %% Shatter identification and removal - Added by Dan Stechman on 5/31/2016 % Currently this is spiral-dependent and uses a threshold defined in the header of this script % Flag particles as shattered if their interarrival time is less than or equal to the threshold. Also flag the particle % immediately before the target particle. %{ if applyIntArrThresh % If the first particle in the next 1-sec period has a small interarrival time, we flag the last particle of % the current period as shattered as well if ~isempty(int_arr2) if int_arr2 <= intar_threshold(i) auto_reject(end) = 'S'; end end if (length(int_arr) == 1 && int_arr(1) <= intar_threshold(i)) auto_reject(1) = 'S'; else if int_arr(1) <= intar_threshold(i) auto_reject(1) = 'S'; end for ix = 2:length(int_arr) if int_arr(ix) <= intar_threshold(i) auto_reject(ix-1:ix) = 'S'; end end end % Experimental option to reaccept particles flagged as shattered which may in fact be the result of diffraction % fringes % Added by Dan Stechman - 6/8/2015 - with base code by Wei Wu if reaccptShatrs % Start by defining the indices for the beginning and end of individual shattering events rBegin = ((int_arr > intar_threshold(i) & int_arr3 < intar_threshold(i))); rEnd = ((int_arr < intar_threshold(i) & int_arr3 > intar_threshold(i))); maxParticle = reaccptD; eIndex = []; % We search through each individual set of shattering events and check to see if any of the particles are both % larger than the reacceptance diameter and have an interarrival time less than the reacceptance threshold as we'd % expect diffraction fringes to be larger than shattered particles and to have a particularly small interarrival time for iEvent = find(rBegin):find(rEnd) if ((particle_diameter_minR(iEvent) > maxParticle) && (int_arr(iEvent) < reaccptMaxIA)) maxParticle = particle_diameter_minR(iEvent); eIndex = iEvent; end end auto_reject(eIndex) = 'R'; end % Following vars used for verifying shatter removal and reacceptance in external script - can be commented out if desired shatterLocs = find(auto_reject == 'S'); shatterIA = int_arr(shatterLocs); shatterTimes = Time_in_seconds(shatterLocs); shatterDiam = particle_diameter_minR(shatterLocs); shatrReject_times = vertcat(shatrReject_times, shatterTimes); shatrReject_intArr = vertcat(shatrReject_intArr, shatterIA); shatrReject_diam = vertcat(shatrReject_diam, shatterDiam); rccptLocs = find(auto_reject == 'R'); rccptIA = int_arr(rccptLocs); rccptTimes = Time_in_seconds(rccptLocs); rccptDiam = particle_diameter_minR(rccptLocs); rccptReject_times = vertcat(rccptReject_times, rccptTimes); rccptReject_intArr = vertcat(rccptReject_intArr, rccptIA); rccptReject_diam = vertcat(rccptReject_diam, rccptDiam); loopedTimes = vertcat(loopedTimes, Time_in_seconds); loopedIntArr = vertcat(loopedIntArr, int_arr); loopedDiam = vertcat(loopedDiam, particle_diameter_minR); loopedAutoRej = vertcat(loopedAutoRej, auto_reject); end %} %% Apply rejection criteria and identify good and bad particles % Modify the next line to include/exclude any particles you see fit. good_particles = (auto_reject == '0' | auto_reject == 'H' | auto_reject == 'h' | auto_reject == 'u' | auto_reject == 'R'); bad_particles = ~(auto_reject == '0' | auto_reject == 'H' | auto_reject == 'h' | auto_reject == 'u' | auto_reject == 'R'); % bad_particles = (auto_reject == 'S'); % Legacy: Rejection criteria used in the past %{ %if RejectCriterier==0 % good_particles = (auto_reject ~= 'c'); % & centerin==1; % & int_arr > 1e-5 int_arr > 1e-5 & %else % good_particles = (auto_reject == '0' | auto_reject == 'H' | auto_reject == 'h' | auto_reject == 'u' & int_arr > intar_threshold) % | auto_reject == 'u'); % & centerin==1; % & int_arr > 1e-5; %end %} if SAmethod==0 good_particles = good_particles & centerin==1; bad_particles = bad_particles & centerin==1; elseif SAmethod==1 good_particles = good_particles & entirein==0; bad_particles = bad_particles & centerin==0; end good_partpercent(i)=sum(good_particles)/length(good_particles); rejectpercentbycriterion(i,1)=sum(centerin==1)/length(good_particles); rejectpercentbycriterion(i,2)=sum(auto_reject == '0')/length(good_particles); rejectpercentbycriterion(i,3)=sum(auto_reject == 'H')/length(good_particles); rejectpercentbycriterion(i,4)=sum(auto_reject == 'h')/length(good_particles); rejectpercentbycriterion(i,5)=sum(auto_reject == 'u')/length(good_particles); rejectpercentbycriterion(i,6)=sum(auto_reject == 'a')/length(good_particles); rejectpercentbycriterion(i,7)=sum(auto_reject == 't')/length(good_particles); rejectpercentbycriterion(i,8)=sum(auto_reject == 'p')/length(good_particles); rejectpercentbycriterion(i,9)=sum(auto_reject == 's')/length(good_particles); rejectpercentbycriterion(i,10)=sum(auto_reject == 'z')/length(good_particles); rejectpercentbycriterion(i,11)=sum(auto_reject == 'i')/length(good_particles); rejectpercentbycriterion(i,12)=sum(auto_reject == 'A')/length(good_particles); rejectpercentbycriterion(i,13)=sum(auto_reject == 'S')/length(good_particles); %Shattered - Added DS rejectpercentbycriterion(i,14)=sum(auto_reject == 'R')/length(good_particles); %Reaccepted - Added DS numGoodparticles(i)=length(good_particles); numBadparticles(i)=length(bad_particles); % disp([int32(timehhmmss(i)), sum(good_particles),length(good_particles),length(good_particles)-sum(good_particles)]); % Edited to handle day rollovers - Adam Majewski 9/21/2017 image_time = hhmmss2insec(image_time_hhmmss) + ( datenum(num2str(cdate),'yyyymmdd') - datenum(ddate,'yyyymmdd') ).*86400; % Good (accepted) particles good_image_times = image_time(good_particles); good_particle_diameter_minR = particle_diameter_minR(good_particles); good_particle_diameter_AreaR = particle_diameter_AreaR(good_particles); good_int_arr=int_arr(good_particles); good_ar = area_ratio(good_particles); good_area = area(good_particles); good_perimeter = perimeter(good_particles); if iCreateAspectRatio == 1 good_AspectRatio = aspectRatio(good_particles & entirein==0); good_AspectRatio1 = aspectRatio1(good_particles & entirein==0); end good_ar1 = area_ratio(good_particles & entirein==0); good_image_times1 = image_time(good_particles & entirein==0); good_iwc=particle_mass(good_particles); good_partarea=calcd_area(good_particles); good_iwcbl=particle_massbl(good_particles); good_vt=particle_vt(good_particles); good_pr=particle_pr(good_particles); good_habit=habit1(good_particles); good_particle_diameter=good_particle_diameter_minR; good_particle_diameter1 = particle_diameter_minR(good_particles & entirein==0); if iCreateBad == 1 % Bad (rejected) particles bad_image_times = image_time(bad_particles); bad_particle_diameter_minR = particle_diameter_minR(bad_particles); bad_particle_diameter_AreaR = particle_diameter_AreaR(bad_particles); bad_int_arr=int_arr(bad_particles); bad_ar = area_ratio(bad_particles); bad_area = area(bad_particles); bad_perimeter = perimeter(bad_particles); if iCreateAspectRatio == 1 % added if statement if not creating aspect ratio - Joe Finlon - 03/03/17 bad_AspectRatio = aspectRatio(bad_particles & entirein==0); bad_AspectRatio1 = aspectRatio1(bad_particles & entirein==0); end bad_ar1 = area_ratio(bad_particles & entirein==0); bad_image_times1 = image_time(bad_particles & entirein==0); bad_iwc=particle_mass(bad_particles); bad_partarea=calcd_area(bad_particles); bad_iwcbl=particle_massbl(bad_particles); bad_vt=particle_vt(bad_particles); bad_pr=particle_pr(bad_particles); bad_habit=habit1(bad_particles); bad_particle_diameter=bad_particle_diameter_minR; bad_particle_diameter1 = particle_diameter_minR(bad_particles & entirein==0); end %% Perform various status and error checks if mod(i,1000) == 0 fprintf('%d/%d | %s\n',i,one_sec_dur,datestr(now)); end total_one_sec_locs(i) = length(find(image_time >= one_sec_times(i) & image_time < one_sec_times(i+1))); time_interval2(i) = sum(int_arr(image_time >= one_sec_times(i) & image_time < one_sec_times(i+1))); if sum(image_time >= one_sec_times(i) & image_time < one_sec_times(i+1)) ~= length(image_time) fprintf(2,'%d / %d\tError on sizing at index %d\n',sum(image_time >= one_sec_times(i) & image_time < one_sec_times(i+1)),length(image_time),i); end if(total_one_sec_locs(i) == 0) time_interval2(i) = 1; end %% Sort good (accepted) particles into size distributions good_one_sec_locs = find(good_image_times >= one_sec_times(i) & good_image_times < one_sec_times(i+1)); good_one_sec_locs1 = find(good_image_times1 >= one_sec_times(i) & good_image_times1 < one_sec_times(i+1)); goodintpercent(i) = sum(good_int_arr(good_image_times >= one_sec_times(i) & good_image_times < one_sec_times(i+1)))/time_interval2(i); one_sec_ar(i) = mean(good_ar1(good_one_sec_locs1)); if ~isempty(good_one_sec_locs) for j = 1:num_bins particle_dist_minR(i,j) = length(find(good_particle_diameter_minR(good_one_sec_locs) >= kk(j) &... good_particle_diameter_minR(good_one_sec_locs) < kk(j+1))); particle_dist_AreaR(i,j) = length(find(good_particle_diameter_AreaR(good_one_sec_locs) >= kk(j) &... good_particle_diameter_AreaR(good_one_sec_locs) < kk(j+1))); % Create Habit Number Size Distribution cip2_habitsd(i,j,1) = length(find(good_habit(good_one_sec_locs)=='s' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitsd(i,j,2) = length(find(good_habit(good_one_sec_locs)=='l' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitsd(i,j,3) = length(find(good_habit(good_one_sec_locs)=='o' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitsd(i,j,4) = length(find(good_habit(good_one_sec_locs)=='t' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitsd(i,j,5) = length(find(good_habit(good_one_sec_locs)=='h' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitsd(i,j,6) = length(find(good_habit(good_one_sec_locs)=='i' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitsd(i,j,7) = length(find(good_habit(good_one_sec_locs)=='g' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitsd(i,j,8) = length(find(good_habit(good_one_sec_locs)=='d' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitsd(i,j,9) = length(find(good_habit(good_one_sec_locs)=='a' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitsd(i,j,10) = length(find(good_habit(good_one_sec_locs)=='I' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); % Create Habit Mass Size Distribution cip2_habitmsd(i,j,1) = sum(good_iwc(good_habit(good_one_sec_locs)=='s' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitmsd(i,j,2) = sum(good_iwc(good_habit(good_one_sec_locs)=='l' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitmsd(i,j,3) = sum(good_iwc(good_habit(good_one_sec_locs)=='o' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitmsd(i,j,4) = sum(good_iwc(good_habit(good_one_sec_locs)=='t' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitmsd(i,j,5) = sum(good_iwc(good_habit(good_one_sec_locs)=='h' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitmsd(i,j,6) = sum(good_iwc(good_habit(good_one_sec_locs)=='i' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitmsd(i,j,7) = sum(good_iwc(good_habit(good_one_sec_locs)=='g' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitmsd(i,j,8) = sum(good_iwc(good_habit(good_one_sec_locs)=='d' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitmsd(i,j,9) = sum(good_iwc(good_habit(good_one_sec_locs)=='a' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); cip2_habitmsd(i,j,10) = sum(good_iwc(good_habit(good_one_sec_locs)=='I' & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); particle_area(i,j) = nansum(good_area(good_one_sec_locs(good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1)))); cip2_meanp(i,j) = nanmean(good_perimeter(good_one_sec_locs(good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1)))); if iCreateAspectRatio == 1 particle_aspectRatio(i,j) = nanmean(good_AspectRatio(good_one_sec_locs1(good_particle_diameter1(good_one_sec_locs1) >= kk(j) &... good_particle_diameter1(good_one_sec_locs1) < kk(j+1)))); particle_aspectRatio1(i,j) = nanmean(good_AspectRatio1(good_one_sec_locs1(good_particle_diameter1(good_one_sec_locs1) >= kk(j) &... good_particle_diameter1(good_one_sec_locs1) < kk(j+1)))); end particle_areaRatio1(i,j) = nanmean(good_ar1(good_one_sec_locs1(good_particle_diameter1(good_one_sec_locs1) >= kk(j) &... good_particle_diameter1(good_one_sec_locs1) < kk(j+1)))); cip2_iwc(i,j) = nansum(good_iwc(good_one_sec_locs(good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1)))); cip2_partarea(i,j) = nansum(good_partarea(good_one_sec_locs(good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1)))); cip2_iwcbl(i,j) = nansum(good_iwcbl(good_one_sec_locs(good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1)))); cip2_vt(i,j) = nansum(good_vt(good_one_sec_locs(good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1)))); cip2_pr(i,j) = nansum(good_pr(good_one_sec_locs(good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1)))); for k = 1:length(area_bins)-1 area_dist2(i,j,k) = length(find(good_ar(good_one_sec_locs) >= area_bins(k) & ... good_ar(good_one_sec_locs) < area_bins(k+1) & good_particle_diameter(good_one_sec_locs) >= kk(j) &... good_particle_diameter(good_one_sec_locs) < kk(j+1))); end end % Normalize by binwidth and convert from mm to cm particle_dist_minR(i,:)=particle_dist_minR(i,:)./binwidth*10; particle_dist_AreaR(i,:)=particle_dist_AreaR(i,:)./binwidth*10; cip2_iwc(i,:)=cip2_iwc(i,:)./binwidth*10; %g/cm cip2_iwcbl(i,:)=cip2_iwcbl(i,:)./binwidth*10; cip2_vt(i,:)=cip2_vt(i,:)./binwidth*10; cip2_pr(i,:)=cip2_pr(i,:)./binwidth*10; cip2_partarea(i,:)=cip2_partarea(i,:)./binwidth*10; particle_area(i,:)=particle_area(i,:)./binwidth*10; for mmmmmm=1:10 cip2_habitsd(i,:,mmmmmm)=cip2_habitsd(i,:,mmmmmm)./binwidth*10; cip2_habitmsd(i,:,mmmmmm)=cip2_habitmsd(i,:,mmmmmm)./binwidth*10; end for mmmmmm = 1:length(area_bins)-1 area_dist2(i,:,mmmmmm) =area_dist2(i,:,mmmmmm)./binwidth*10 ; end % Generalized effective radius calculation from Fu (1996) cip2_re(i) = (sqrt(3)/(3*0.91))*1000*(sum(cip2_iwc(i,:)./binwidth,2)/sum(particle_area(i,:)./binwidth,2))*1000; % in unit of um else particle_dist_minR(i,1:num_bins) = 0; particle_dist_AreaR(i,1:num_bins) = 0; area_dist2(i,1:num_bins,1:length(area_bins)-1) = 0; cip2_partarea(i,:) = 0; cip2_iwc(i,:) = 0; cip2_iwcbl(i,:) = 0; cip2_vt(i,:) = 0; cip2_pr(i,:) = 0; cip2_re(i) = 0; cip2_habitsd(i,:,:) = 0; cip2_habitmsd(i,:,:) = 0; time_interval2(i) = 1; % Legacy: used in Paris intercomparison %{ time_interval22(i) = 1; time_interval32(i) = 1; time_interval42(i) = 1; time_interval52(i) = 0; time_interval62(i) = 1; %} time_interval72(i) = 0; TotalPC1(i)=1; TotalPC2(i)=1; end if iCreateBad == 1 %% Sort bad (rejected) particles into size distributions bad_one_sec_locs = find(bad_image_times >= one_sec_times(i) & bad_image_times < one_sec_times(i+1)); bad_one_sec_locs1 = find(bad_image_times1 >= one_sec_times(i) & bad_image_times1 < one_sec_times(i+1)); badintpercent(i) = sum(bad_int_arr(bad_image_times >= one_sec_times(i) & bad_image_times < one_sec_times(i+1)))/time_interval2(i); bad_one_sec_ar(i) = mean(bad_ar1(bad_one_sec_locs1)); if ~isempty(bad_one_sec_locs) for j = 1:num_bins bad_particle_dist_minR(i,j) = length(find(bad_particle_diameter_minR(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter_minR(bad_one_sec_locs) < kk(j+1))); bad_particle_dist_AreaR(i,j) = length(find(bad_particle_diameter_AreaR(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter_AreaR(bad_one_sec_locs) < kk(j+1))); % Create Habit Number Size Distribution bad_cip2_habitsd(i,j,1) = length(find(bad_habit(bad_one_sec_locs)=='s' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitsd(i,j,2) = length(find(bad_habit(bad_one_sec_locs)=='l' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitsd(i,j,3) = length(find(bad_habit(bad_one_sec_locs)=='o' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitsd(i,j,4) = length(find(bad_habit(bad_one_sec_locs)=='t' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitsd(i,j,5) = length(find(bad_habit(bad_one_sec_locs)=='h' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitsd(i,j,6) = length(find(bad_habit(bad_one_sec_locs)=='i' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitsd(i,j,7) = length(find(bad_habit(bad_one_sec_locs)=='g' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitsd(i,j,8) = length(find(bad_habit(bad_one_sec_locs)=='d' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitsd(i,j,9) = length(find(bad_habit(bad_one_sec_locs)=='a' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitsd(i,j,10) = length(find(bad_habit(bad_one_sec_locs)=='I' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); % Create Habit Mass Size Distribution bad_cip2_habitmsd(i,j,1) = sum(bad_iwc(bad_habit(bad_one_sec_locs)=='s' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitmsd(i,j,2) = sum(bad_iwc(bad_habit(bad_one_sec_locs)=='l' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitmsd(i,j,3) = sum(bad_iwc(bad_habit(bad_one_sec_locs)=='o' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitmsd(i,j,4) = sum(bad_iwc(bad_habit(bad_one_sec_locs)=='t' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitmsd(i,j,5) = sum(bad_iwc(bad_habit(bad_one_sec_locs)=='h' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitmsd(i,j,6) = sum(bad_iwc(bad_habit(bad_one_sec_locs)=='i' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitmsd(i,j,7) = sum(bad_iwc(bad_habit(bad_one_sec_locs)=='g' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitmsd(i,j,8) = sum(bad_iwc(bad_habit(bad_one_sec_locs)=='d' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitmsd(i,j,9) = sum(bad_iwc(bad_habit(bad_one_sec_locs)=='a' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_cip2_habitmsd(i,j,10) = sum(bad_iwc(bad_habit(bad_one_sec_locs)=='I' & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); bad_particle_area(i,j) = nansum(bad_area(bad_one_sec_locs(bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1)))); bad_cip2_meanp(i,j) = nanmean(bad_perimeter(bad_one_sec_locs(bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1)))); if iCreateAspectRatio == 1 % added if statement if not creating aspect ratio - Joe Finlon - 03/03/17 bad_particle_aspectRatio(i,j) = nanmean(bad_AspectRatio(bad_one_sec_locs1(bad_particle_diameter1(bad_one_sec_locs1) >= kk(j) &... bad_particle_diameter1(bad_one_sec_locs1) < kk(j+1)))); bad_particle_aspectRatio1(i,j) = nanmean(bad_AspectRatio1(bad_one_sec_locs1(bad_particle_diameter1(bad_one_sec_locs1) >= kk(j) &... bad_particle_diameter1(bad_one_sec_locs1) < kk(j+1)))); end bad_particle_areaRatio1(i,j) = nanmean(bad_ar1(bad_one_sec_locs1(bad_particle_diameter1(bad_one_sec_locs1) >= kk(j) &... bad_particle_diameter1(bad_one_sec_locs1) < kk(j+1)))); bad_cip2_iwc(i,j) = nansum(bad_iwc(bad_one_sec_locs(bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1)))); bad_cip2_partarea(i,j) = nansum(bad_partarea(bad_one_sec_locs(bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1)))); bad_cip2_iwcbl(i,j) = nansum(bad_iwcbl(bad_one_sec_locs(bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1)))); bad_cip2_vt(i,j) = nansum(bad_vt(bad_one_sec_locs(bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1)))); bad_cip2_pr(i,j) = nansum(bad_pr(bad_one_sec_locs(bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1)))); for k = 1:length(area_bins)-1 bad_area_dist2(i,j,k) = length(find(bad_ar(bad_one_sec_locs) >= area_bins(k) & ... bad_ar(bad_one_sec_locs) < area_bins(k+1) & bad_particle_diameter(bad_one_sec_locs) >= kk(j) &... bad_particle_diameter(bad_one_sec_locs) < kk(j+1))); end end % Normalize by binwidth and convert from mm to cm bad_particle_dist_minR(i,:)=bad_particle_dist_minR(i,:)./binwidth*10; bad_particle_dist_AreaR(i,:)=bad_particle_dist_AreaR(i,:)./binwidth*10; bad_cip2_iwc(i,:)=bad_cip2_iwc(i,:)./binwidth*10; %g/cm bad_cip2_iwcbl(i,:)=bad_cip2_iwcbl(i,:)./binwidth*10; bad_cip2_vt(i,:)=bad_cip2_vt(i,:)./binwidth*10; bad_cip2_pr(i,:)=bad_cip2_pr(i,:)./binwidth*10; bad_cip2_partarea(i,:)=bad_cip2_partarea(i,:)./binwidth*10; bad_particle_area(i,:)=bad_particle_area(i,:)./binwidth*10; for mmmmmm=1:10 bad_cip2_habitsd(i,:,mmmmmm)=bad_cip2_habitsd(i,:,mmmmmm)./binwidth*10; bad_cip2_habitmsd(i,:,mmmmmm)=bad_cip2_habitmsd(i,:,mmmmmm)./binwidth*10; end for mmmmmm = 1:length(area_bins)-1 bad_area_dist2(i,:,mmmmmm)=bad_area_dist2(i,:,mmmmmm)./binwidth*10 ; end % Generalized effective radius calculation from Fu (1996) bad_cip2_re(i) = (sqrt(3)/(3*0.91))*1000*(sum(bad_cip2_iwc(i,:)./binwidth,2)/sum(bad_particle_area(i,:)./binwidth,2))*1000; % in unit of um else bad_particle_dist_minR(i,1:num_bins) = 0; bad_particle_dist_AreaR(i,1:num_bins) = 0; bad_area_dist2(i,1:num_bins,1:length(area_bins)-1) = 0; bad_cip2_partarea(i,:) = 0; bad_cip2_iwc(i,:) = 0; bad_cip2_iwcbl(i,:) = 0; bad_cip2_vt(i,:) = 0; bad_cip2_pr(i,:) = 0; bad_cip2_re(i) = 0; bad_cip2_habitsd(i,:,:) = 0; bad_cip2_habitmsd(i,:,:) = 0; end end warning on all elseif (int32(timehhmmss(i))<int32(starttime(jjj))) particle_dist_minR(i,1:num_bins) = NaN; particle_dist_AreaR(i,1:num_bins) = NaN; area_dist2(i,1:num_bins,1:length(area_bins)-1) = NaN; cip2_partarea(i,:) = NaN; cip2_iwc(i,:) = NaN; cip2_iwcbl(i,:) = NaN; cip2_vt(i,:) = NaN; cip2_pr(i,:) = NaN; cip2_re(i) = NaN; cip2_habitsd(i,:,:) = NaN; cip2_habitmsd(i,:,:) = NaN; one_sec_ar(i) = NaN; good_partpercent(i)=1; rejectpercentbycriterion(i,:)=NaN; numGoodparticles(i)=NaN; time_interval2(i) = 1; % Legacy: used in Paris intercomparison %{ time_interval22(i) = 1; time_interval32(i) = 1; time_interval42(i) = 1; time_interval52(i) = 0; time_interval62(i) = 1; %} time_interval72(i) = 0; TotalPC1(i)=1; TotalPC2(i)=1; end end % Finished Sorting and close input file. netcdf.close(f); fprintf('int_arr > 1 mean: %.4f, max: %.4f\nNumber of particles with int_arr > 1: %d\n\n',... mean(intArrGT1),max(intArrGT1),sumIntArrGT1); fprintf('Size distribution calculations and sorting completed %s\n\n', datestr(now)); %% Check TAS length, should be the same % if (jjj~=length(start_all)) % disp([jjj, length(start_all)]) % %error('Watch Out for less TAS time at the end!') % end %disp([num2str(100*nThrow11/maxRecNum),'% is thrown out IN TOTAL']); %% Combine - calculate sample volumes, and divide by sample volumes % Modified by Will, Nov 27th, 2013. For flexible bins cip2_binmin = kk(1:end-1); cip2_binmax = kk(2:end); cip2_binmid = (cip2_binmin+cip2_binmax)/2; cip2_bindD = diff(kk); % Legacy bin and surface area calculations %{ % cip2_binmin = diodesize/2:diodesize:(num_bins-0.5)*diodesize; %(12.5:25:(num_bins-0.5)*25); % cip2_binmax = 3*diodesize/2:diodesize:(num_bins+0.5)*diodesize; %(37.5:25:(num_bins+0.5)*25); % cip2_binmid = diodesize:diodesize:num_bins*diodesize; %(25:25:num_bins*25); % cip2_bindD = diodesize*ones(1,num_bins); % sa2 = calc_sa(num_bins,res,armdst,num_bins); %mm2 % switch probename % case 'PIP' % sa2 = calc_sa_randombins_PIP(cip2_binmid,res,armdst,num_diodes, SAmethod); %(bins_mid,res,armdst,num_diodes) % case '2DS' % sa2 = calc_sa_randombins(cip2_binmid,res,armdst,num_diodes, SAmethod); %(bins_mid,res,armdst,num_diodes) % end %} sa2 = calc_sa_randombins(cip2_binmid,res,armdst,num_diodes,SAmethod, probetype); %(bins_mid,res,armdst,num_diodes) % Clocking problem correction vol_scale_factor = tas/tasMax; vol_scale_factor(vol_scale_factor < 1) = 1; TotalPC2_pre = TotalPC2; if probetype==2 time_interval200=1-time_interval72'; elseif probetype==1 % Correct offset in probe particle count (TotalPC2) when we have negative values TotalPC2(TotalPC2<0)=TotalPC2(TotalPC2<0)+2^16; % Derive a linear scale factor based on the difference between number of images (TotalPC1) % and number of particles counted by the probe (TotalPC2). time_interval199=(TotalPC1./TotalPC2)'; elseif 0==probetype time_interval200=1-time_interval72'; end % Experimental - Use with care! % It was discovered that for data collected during the PECAN project, there were quite % a few periods of time when the number of images we had for a 1-sec period of time was % up to twice that of the number of particles the probe counted. % This next if-statement contains code to find and change these instances to 1, resolving % the far exaggerated concentrations that resulted otherwise. if probetype==1 TotalPCerrIx = find(time_interval199 > 1); time_interval200 = time_interval199; time_interval200(TotalPCerrIx) = 1; fprintf(['Total image count exceeded probe particle count %d times\ntime_interval200',... ' was set to 1 in these cases. See TotalPCerrIx variable for indices of occurence.\n\n'],... length(TotalPCerrIx)); % moved inside if statement - Joe Finlon - 03/03/17 end for j=1:num_bins % Sample volume is in m-3 % svol_old(j,:)=dof/100.*sa/100.*tas; svol2(j,:) = sa2(j)*(1e-3)^2*time_interval200.*tas; %m3 .*vol_scale_factor end svol2 = svol2*100^3; %cm3 for j = 1:10 svol2a(:,:,j) = svol2'; end % Good (accepted) particles cip2_conc_minR = particle_dist_minR./svol2'; cip2_conc_AreaR = particle_dist_AreaR./svol2'; cip2_area = particle_area./svol2'; cip2_partarea = cip2_partarea./svol2'; cip2_iwc = cip2_iwc./svol2'; cip2_iwcbl = cip2_iwcbl./svol2'; cip2_vt = cip2_vt./svol2'; cip2_pr = cip2_pr./svol2'; cip2_countP_no = particle_dist_minR.*repmat(binwidth,[length(tas) 1])/10; % un-normalized by binwitdh - Joe Finlon - 03/03/17 cip2_conc_areaDist = permute(double(area_dist2)./svol2a, [3 2 1]); cip2_n = nansum(cip2_conc_minR.*repmat(binwidth,[length(tas) 1]),2)/10; % un-normalized by binwitdh & converted to cm^-3 - Joe Finlon - 03/03/17 cip2_lwc = lwc_calc(cip2_conc_minR,cip2_binmid); % Bad (rejected) particles bad_cip2_conc_minR = bad_particle_dist_minR./svol2'; bad_cip2_conc_AreaR = bad_particle_dist_AreaR./svol2'; bad_cip2_area = bad_particle_area./svol2'; bad_cip2_partarea = bad_cip2_partarea./svol2'; bad_cip2_iwc = bad_cip2_iwc./svol2'; bad_cip2_iwcbl = bad_cip2_iwcbl./svol2'; bad_cip2_vt = bad_cip2_vt./svol2'; bad_cip2_pr = bad_cip2_pr./svol2'; bad_cip2_countP_no = bad_particle_dist_minR.*repmat(binwidth,[length(tas) 1])/10; % un-normalized by binwitdh - Joe Finlon - 03/03/17 bad_cip2_conc_areaDist = permute(double(bad_area_dist2)./svol2a, [3 2 1]); bad_cip2_n = nansum(bad_cip2_conc_minR.*repmat(binwidth,[length(tas) 1]),2)/10; % un-normalized by binwitdh & converted to cm^-3 - Joe Finlon - 03/03/17 bad_cip2_lwc = lwc_calc(bad_cip2_conc_minR,cip2_binmid); %% Output results into NETCDF files (mainf) fprintf('Now writing output files %s\n\n',datestr(now)); if applyIntArrThresh save([outfile(1:end-3) 'noShatters.mat']); else save([outfile(1:end-3) 'withShatters.mat']); end % Define Dimensions dimid0 = netcdf.defDim(mainf,'CIPcorrlen',num_bins); dimid1 = netcdf.defDim(mainf,'CIParealen',10); dimid2 = netcdf.defDim(mainf,'Time',length(timehhmmss)); dimid3 = netcdf.defDim(mainf,'Habit',10); % Define Variables varid0 = netcdf.defVar(mainf,'time','double',dimid2); netcdf.putAtt(mainf, varid0,'units','HHMMSS'); netcdf.putAtt(mainf, varid0,'name','Time'); varid1 = netcdf.defVar(mainf,'bin_min','double',dimid0); netcdf.putAtt(mainf, varid1,'units','millimeter'); netcdf.putAtt(mainf, varid1,'long_name','bin minimum size'); netcdf.putAtt(mainf, varid1,'short_name','bin min'); varid2 = netcdf.defVar(mainf,'bin_max','double',dimid0); netcdf.putAtt(mainf, varid2,'units','millimeter'); netcdf.putAtt(mainf, varid2,'long_name','bin maximum size'); netcdf.putAtt(mainf, varid2,'short_name','bin max'); varid3 = netcdf.defVar(mainf,'bin_mid','double',dimid0); netcdf.putAtt(mainf, varid3,'units','millimeter'); netcdf.putAtt(mainf, varid3,'long_name','bin midpoint size'); netcdf.putAtt(mainf, varid3,'short_name','bin mid'); varid4 = netcdf.defVar(mainf,'bin_dD','double',dimid0); netcdf.putAtt(mainf, varid4,'units','millimeter'); netcdf.putAtt(mainf, varid4,'long_name','bin size'); netcdf.putAtt(mainf, varid4,'short_name','bin size'); % Good (accepted) particles varid5 = netcdf.defVar(mainf,'conc_minR','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid5,'units','cm-4'); netcdf.putAtt(mainf, varid5,'long_name','Size distribution using Dmax'); netcdf.putAtt(mainf, varid5,'short_name','N(Dmax)'); varid6 = netcdf.defVar(mainf,'area','double',[dimid1 dimid0 dimid2]); netcdf.putAtt(mainf, varid6,'units','cm-4'); netcdf.putAtt(mainf, varid6,'long_name','binned area ratio'); netcdf.putAtt(mainf, varid6,'short_name','binned area ratio'); varid7 = netcdf.defVar(mainf,'conc_AreaR','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid7,'units','cm-4'); netcdf.putAtt(mainf, varid7,'long_name','Size distribution using area-equivalent Diameter'); netcdf.putAtt(mainf, varid7,'short_name','N(Darea)'); varid8 = netcdf.defVar(mainf,'n','double',dimid2); netcdf.putAtt(mainf, varid8,'units','cm-3'); netcdf.putAtt(mainf, varid8,'long_name','number concentration'); netcdf.putAtt(mainf, varid8,'short_name','N'); varid9 = netcdf.defVar(mainf,'total_area','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid9,'units','mm2/cm4'); netcdf.putAtt(mainf, varid9,'long_name','projected area (extinction)'); netcdf.putAtt(mainf, varid9,'short_name','Ac'); varid10 = netcdf.defVar(mainf,'mass','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid10,'units','g/cm4'); netcdf.putAtt(mainf, varid10,'long_name','mass using m-D relations'); netcdf.putAtt(mainf, varid10,'short_name','mass'); varid11 = netcdf.defVar(mainf,'habitsd','double',[dimid3 dimid0 dimid2]); netcdf.putAtt(mainf, varid11,'units','cm-4'); netcdf.putAtt(mainf, varid11,'long_name','Size Distribution with Habit'); netcdf.putAtt(mainf, varid11,'short_name','habit SD'); varid12 = netcdf.defVar(mainf,'re','double',dimid2); netcdf.putAtt(mainf, varid12,'units','mm'); netcdf.putAtt(mainf, varid12,'long_name','effective radius'); netcdf.putAtt(mainf, varid12,'short_name','Re'); varid13 = netcdf.defVar(mainf,'ar','double',dimid2); netcdf.putAtt(mainf, varid13,'units','100/100'); netcdf.putAtt(mainf, varid13,'long_name','Area Ratio'); netcdf.putAtt(mainf, varid13,'short_name','AR'); varid14 = netcdf.defVar(mainf,'massBL','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid14,'units','g/cm4'); netcdf.putAtt(mainf, varid14,'long_name','mass using Baker and Lawson method'); netcdf.putAtt(mainf, varid14,'short_name','mass_BL'); varid15 = netcdf.defVar(mainf,'Reject_ratio','double',dimid2); netcdf.putAtt(mainf, varid15,'units','100/100'); netcdf.putAtt(mainf, varid15,'long_name','Reject Ratio'); varid16 = netcdf.defVar(mainf,'vt','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid16,'units','g/cm4'); netcdf.putAtt(mainf, varid16,'long_name','Mass-weighted terminal velocity'); varid17 = netcdf.defVar(mainf,'Prec_rate','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid17,'units','mm/hr'); netcdf.putAtt(mainf, varid17,'long_name','Precipitation Rate'); varid18 = netcdf.defVar(mainf,'habitmsd','double',[dimid3 dimid0 dimid2]); netcdf.putAtt(mainf, varid18,'units','g/cm-4'); netcdf.putAtt(mainf, varid18,'long_name','Mass Size Distribution with Habit'); netcdf.putAtt(mainf, varid18,'short_name','Habit Mass SD'); varid19 = netcdf.defVar(mainf,'Calcd_area','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid19,'units','mm^2/cm4'); netcdf.putAtt(mainf, varid19,'long_name','Particle Area Calculated using A-D realtions'); netcdf.putAtt(mainf, varid19,'short_name','Ac_calc'); varid20 = netcdf.defVar(mainf,'count','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid20,'units','1'); netcdf.putAtt(mainf, varid20,'long_name','number count for partial images without any correction'); if iCreateAspectRatio == 1 varid21 = netcdf.defVar(mainf,'mean_aspect_ratio_rectangle','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid21,'units','1'); netcdf.putAtt(mainf, varid21,'long_name','Aspect Ratio by Rectangle fit'); varid22 = netcdf.defVar(mainf,'mean_aspect_ratio_ellipse','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid22,'units','1'); netcdf.putAtt(mainf, varid22,'long_name','Aspect Ratio by Ellipse fit'); end varid23 = netcdf.defVar(mainf,'mean_area_ratio','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid23,'units','1'); netcdf.putAtt(mainf, varid23,'long_name','Area Ratio'); varid24 = netcdf.defVar(mainf,'mean_perimeter','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid24,'units','um'); netcdf.putAtt(mainf, varid24,'long_name','mean perimeter'); if iCreateBad == 1 % Bad (rejected) particles varid25 = netcdf.defVar(mainf,'REJ_conc_minR','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid25,'units','cm-4'); netcdf.putAtt(mainf, varid25,'long_name','Size distribution of rejected particles using Dmax'); netcdf.putAtt(mainf, varid25,'short_name','N(Dmax) rejected'); varid26 = netcdf.defVar(mainf,'REJ_area','double',[dimid1 dimid0 dimid2]); netcdf.putAtt(mainf, varid26,'units','cm-4'); netcdf.putAtt(mainf, varid26,'long_name','binned area ratio of rejected particles'); netcdf.putAtt(mainf, varid26,'short_name','binned area ratio of rejected particles'); varid27 = netcdf.defVar(mainf,'REJ_conc_AreaR','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid27,'units','cm-4'); netcdf.putAtt(mainf, varid27,'long_name','Size distribution of rejected particles using area-equivalent Diameter'); netcdf.putAtt(mainf, varid27,'short_name','N(Darea) rejected'); varid28 = netcdf.defVar(mainf,'REJ_n','double',dimid2); netcdf.putAtt(mainf, varid28,'units','cm-3'); netcdf.putAtt(mainf, varid28,'long_name','number concentration of rejected particles'); netcdf.putAtt(mainf, varid28,'short_name','N_rejected'); varid29 = netcdf.defVar(mainf,'REJ_total_area','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid29,'units','mm2/cm4'); netcdf.putAtt(mainf, varid29,'long_name','projected area (extinction) of rejected particles'); netcdf.putAtt(mainf, varid29,'short_name','Ac_rejected'); varid30 = netcdf.defVar(mainf,'REJ_mass','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid30,'units','g/cm4'); netcdf.putAtt(mainf, varid30,'long_name','mass of rejected particles using m-D relations'); netcdf.putAtt(mainf, varid30,'short_name','mass_rejected'); varid31 = netcdf.defVar(mainf,'REJ_habitsd','double',[dimid3 dimid0 dimid2]); netcdf.putAtt(mainf, varid31,'units','cm-4'); netcdf.putAtt(mainf, varid31,'long_name','Size Distribution with Habit of rejected particles'); netcdf.putAtt(mainf, varid31,'short_name','habit SD rejected'); varid32 = netcdf.defVar(mainf,'REJ_re','double',dimid2); netcdf.putAtt(mainf, varid32,'units','mm'); netcdf.putAtt(mainf, varid32,'long_name','effective radius of rejected particles'); netcdf.putAtt(mainf, varid32,'short_name','Re_rejected'); varid33 = netcdf.defVar(mainf,'REJ_ar','double',dimid2); netcdf.putAtt(mainf, varid33,'units','100/100'); netcdf.putAtt(mainf, varid33,'long_name','Area Ratio of rejected particles'); netcdf.putAtt(mainf, varid33,'short_name','AR_rejected'); varid34 = netcdf.defVar(mainf,'REJ_massBL','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid34,'units','g/cm4'); netcdf.putAtt(mainf, varid34,'long_name','mass of rejected particles using Baker and Lawson method'); netcdf.putAtt(mainf, varid34,'short_name','mass_BL_rejected'); varid35 = netcdf.defVar(mainf,'REJ_vt','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid35,'units','g/cm4'); netcdf.putAtt(mainf, varid35,'long_name','Mass-weighted terminal velocity of rejected particles'); varid36 = netcdf.defVar(mainf,'REJ_Prec_rate','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid36,'units','mm/hr'); netcdf.putAtt(mainf, varid36,'long_name','Precipitation Rate of rejected particles'); varid37 = netcdf.defVar(mainf,'REJ_habitmsd','double',[dimid3 dimid0 dimid2]); netcdf.putAtt(mainf, varid37,'units','g/cm-4'); netcdf.putAtt(mainf, varid37,'long_name','Mass Size Distribution with Habit of rejected particles'); netcdf.putAtt(mainf, varid37,'short_name','Habit Mass SD rejected'); varid38 = netcdf.defVar(mainf,'REJ_Calcd_area','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid38,'units','mm^2/cm4'); netcdf.putAtt(mainf, varid38,'long_name','Particle Area of rejected particles Calculated using A-D realtions'); netcdf.putAtt(mainf, varid38,'short_name','Ac_calc_rejected'); varid39 = netcdf.defVar(mainf,'REJ_count','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid39,'units','1'); netcdf.putAtt(mainf, varid39,'long_name','number count of rejected particles for partial images without any correction'); varid40 = netcdf.defVar(mainf,'REJ_mean_aspect_ratio_rectangle','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid40,'units','1'); netcdf.putAtt(mainf, varid40,'long_name','Aspect Ratio of rejected particles by Rectangle fit'); varid41 = netcdf.defVar(mainf,'REJ_mean_aspect_ratio_ellipse','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid41,'units','1'); netcdf.putAtt(mainf, varid41,'long_name','Aspect Ratio of rejected particles by Ellipse fit'); varid42 = netcdf.defVar(mainf,'REJ_mean_area_ratio','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid42,'units','1'); netcdf.putAtt(mainf, varid42,'long_name','Area Ratio of rejected particles'); varid43 = netcdf.defVar(mainf,'REJ_mean_perimeter','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid43,'units','um'); netcdf.putAtt(mainf, varid43,'long_name','mean perimeter of rejected particles'); end if iSaveIntArrSV == 1 varid44 = netcdf.defVar(mainf,'sum_IntArr','double',dimid2); netcdf.putAtt(mainf, varid44,'units','s'); netcdf.putAtt(mainf, varid44,'long_name','sum of inter-arrival times, excluding the overload time for particles affected by saving of image data'); varid45 = netcdf.defVar(mainf,'sample_vol','double',[dimid0 dimid2]); netcdf.putAtt(mainf, varid45,'units','cm^3'); netcdf.putAtt(mainf, varid45,'long_name','sample volume for each bin'); end netcdf.endDef(mainf) % Output Variables netcdf.putVar ( mainf, varid0, timehhmmss ); netcdf.putVar ( mainf, varid1, cip2_binmin ); netcdf.putVar ( mainf, varid2, cip2_binmax ); netcdf.putVar ( mainf, varid3, cip2_binmid ); netcdf.putVar ( mainf, varid4, cip2_bindD ); % Good (accepted) particles netcdf.putVar ( mainf, varid5, double(cip2_conc_minR') ); netcdf.putVar ( mainf, varid6, double(cip2_conc_areaDist)); netcdf.putVar ( mainf, varid7, double(cip2_conc_AreaR') ); netcdf.putVar ( mainf, varid8, double(cip2_n)); netcdf.putVar ( mainf, varid9, double(cip2_area')); netcdf.putVar ( mainf, varid10, double(cip2_iwc')); netcdf.putVar ( mainf, varid11, permute(double(cip2_habitsd)./double(svol2a), [3 2 1]) ); netcdf.putVar ( mainf, varid12, cip2_re ); netcdf.putVar ( mainf, varid13, one_sec_ar ); netcdf.putVar ( mainf, varid14, double(cip2_iwcbl') ); netcdf.putVar ( mainf, varid15, 1-good_partpercent ); netcdf.putVar ( mainf, varid16, double(cip2_vt') ); netcdf.putVar ( mainf, varid17, double(cip2_pr') ); netcdf.putVar ( mainf, varid18, permute(double(cip2_habitmsd)./double(svol2a), [3 2 1]) ); netcdf.putVar ( mainf, varid19, double(cip2_partarea')); netcdf.putVar ( mainf, varid20, double(cip2_countP_no')); if iCreateAspectRatio == 1 netcdf.putVar ( mainf, varid21, particle_aspectRatio); netcdf.putVar ( mainf, varid22, particle_aspectRatio1); end netcdf.putVar ( mainf, varid23, double(particle_areaRatio1)); netcdf.putVar ( mainf, varid24, double(cip2_meanp')); if iCreateBad == 1 % Bad (rejected) particles netcdf.putVar ( mainf, varid25, double(bad_cip2_conc_minR') ); netcdf.putVar ( mainf, varid26, double(bad_cip2_conc_areaDist)); netcdf.putVar ( mainf, varid27, double(bad_cip2_conc_AreaR') ); netcdf.putVar ( mainf, varid28, double(bad_cip2_n)); netcdf.putVar ( mainf, varid29, double(bad_cip2_area')); netcdf.putVar ( mainf, varid30, double(bad_cip2_iwc')); netcdf.putVar ( mainf, varid31, permute(double(bad_cip2_habitsd)./double(svol2a), [3 2 1]) ); netcdf.putVar ( mainf, varid32, bad_cip2_re ); netcdf.putVar ( mainf, varid33, bad_one_sec_ar ); netcdf.putVar ( mainf, varid34, double(bad_cip2_iwcbl') ); netcdf.putVar ( mainf, varid35, double(bad_cip2_vt') ); netcdf.putVar ( mainf, varid36, double(bad_cip2_pr') ); netcdf.putVar ( mainf, varid37, permute(double(bad_cip2_habitmsd)./double(svol2a), [3 2 1]) ); netcdf.putVar ( mainf, varid38, double(bad_cip2_partarea')); netcdf.putVar ( mainf, varid39, double(bad_cip2_countP_no')); netcdf.putVar ( mainf, varid40, double(bad_particle_aspectRatio)); netcdf.putVar ( mainf, varid41, double(bad_particle_aspectRatio1)); netcdf.putVar ( mainf, varid42, double(bad_particle_areaRatio1)); netcdf.putVar ( mainf, varid43, double(bad_cip2_meanp')); end if iSaveIntArrSV == 1 % Inter-arrival time and sample volume information netcdf.putVar ( mainf, varid44, time_interval200'); netcdf.putVar ( mainf, varid45, svol2); end netcdf.close(mainf) % Close output NETCDF file fprintf('sizeDist_Paris.m script completed %s\n',datestr(now)); end
github
jjjjfrench/UW-UIOPS-master
single_vt.m
.m
UW-UIOPS-master/size_dist/single_vt.m
1,440
utf_8
6d3b5eb59b4c5ec6a86a3aa87c2bead2
%% Returns terminal velocity for a single particle % Both options to calculate the terminal velocity % Default is to use the Heymsfield and Westbrook (2010) method, % but you can also choose to to use Mitchel (1996) % Created by Will Wu, 2014/01/15 % - Mass and Diameter uses metric system % - Pressure use hPa % - Temperature use Celsius function vt = single_vt(diameter, area_ratio, mass, P, T) usingMithcell=0; % Setting 0 to use Heymsfield method, other value for Mitchell method g=9.8; pi=3.1415926; % Calculate environmental conditions T = T + 273.15; P = P*100; rho_a = P/(287.15*T); eta = 18.27*(291.15+120)./(T+120)*(T/291.15)^(3/2)/10^(6); % Sutherland's formula to calculate the dynamic viscosity nu = eta/rho_a; % kinectic viscosity if 0==usingMithcell % Calculate modified Best Number using Heymsfield and Westbrook (2010). % using drag C=0.35 and epsilon=8.0 X=rho_a/(eta^2)*8*mass*g/(pi*area_ratio^0.5); ReynoldN=16*(sqrt(1+4*sqrt(X)/64/sqrt(0.35))-1)^2; else % Calculate modified Best Number using Mitchell (1996). % This is actually a special case of Heymsfield and Westbrook (2010), with % k=0, and here we use drag C=0.6 and epsilon=5.83 % We calculate from the original equations without using power law % approximation X=rho_a/(eta^2)*8*mass*g/(pi*area_ratio); ReynoldN=5.83^2/4*(sqrt(1+4*sqrt(X)/(5.83^2)/sqrt(0.6))-1)^2; end vt=nu/diameter*ReynoldN; end
github
jjjjfrench/UW-UIOPS-master
dropsize.m
.m
UW-UIOPS-master/img_processing/dropsize.m
10,889
utf_8
eb28935658e58b45634f6c09cbd7a712
function [center_in,axis_ratio,diameter_circle_fit,diameter_horiz_chord,diameter_vert_chord,diameter_horiz_mean, diameter_spheroid]=... dropsize(max_horizontal_length,max_vertical_length,image_area,largest_edge_touching,... smallest_edge_touching,diode_size,corrected_horizontal_diode_size,number_diodes_in_array) global max_vertical_chords max_horizontal_chords vertical_chords vertical_chord_equivalent_spherical_diameters... horizontal_chords horizontal_chord_equivalent_spherical_diameters % % % DROP SIZING FOR 2DP PROBES (equiv sph vol diam) % one diode added to max_horizontal_length_in_pixels for missing first slice % uncalculated size appears as zero; oversize as 9.1 % % % diameter_horz_chord % d0 from horz chord (max_horizontal_length_in_pixels + 1) % designed for sideways-looking probe % but can be used for any probe orientation % with center-in image of equil shape % % % diameter_circle_fit % Heimsfield-Parish CIRCLE FIT SIZES FOR 2-EDGE & 1-EDGE(CENTER OUT) IMAGES: % d0 from horz chord (circle fit) % designed for downward-looking probe % % % diameter_vert_chord % max_vertical_length_in_pixels & 2-CHORD SIZES FOR ENTIRE-IN IMAGES: % d0 from vert chord (max_vertical_length_in_pixels) % designed for sideways-looking probe % optional size for entire-in images % % % [If diam_vchord differs from diam_hchord, then drop is not equil shape] % % diameter_horz_mean % d0 from mean horz chord [(xmax+1)*ymax]^0.5 % designed for downward-looking probe % optional size for distorted entire-in images % % diameter_spheroid % d0 from spheroid assumption (hchord*hchord*vchord)^1/3 % designed for sideways-looking probe % optional size for distorted entire-in images % % % AXIS RATIO % axis_ratio = max_vertical_length_in_pixels / max_horizontal_length_in_pixels % for entire-in image (no smoothing) % center_in = (0 if particle is not center in, 1 if particle is center % in) max_horizontal_chords = 117; max_vertical_chords = 55; diodes_added_to_length = 0; diodes_added_to_height = 1.0; horizontal_chords = [... 0.0000, 0.1000, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000, 0.7000, 0.8000, 0.9000,... 1.0000, 1.1000, 1.2000, 1.3000, 1.4000, 1.5000, 1.6000, 1.7000, 1.8000, 1.9000,... 2.0000, 2.1000, 2.2000, 2.3000, 2.4000, 2.5000, 2.6000, 2.7000, 2.8000, 2.9000,... 3.0000, 3.1000, 3.2000, 3.3000, 3.4000, 3.5000, 3.6000, 3.7000, 3.8000, 3.9000,... 4.0000, 4.1000, 4.2000, 4.3000, 4.4000, 4.5000, 4.6000, 4.7000, 4.8000, 4.9000,... 5.0000, 5.1000, 5.2000, 5.3000, 5.4000, 5.5000, 5.6000, 5.7000, 5.8000, 5.9000,... 6.0000, 6.1000, 6.2000, 6.3000, 6.4000, 6.5000, 6.6000, 6.7000, 6.8000, 6.9000,... 7.0000, 7.1000, 7.2000, 7.3000, 7.4000, 7.5000, 7.6000, 7.7000, 7.8000, 7.9000,... 8.0000, 8.1000, 8.2000, 8.3000, 8.4000, 8.5000, 8.6000, 8.7000, 8.8000, 8.9000,... 9.0000, 9.1000, 9.2000, 9.3000, 9.4000, 9.5000, 9.6000, 9.7000, 9.8000, 9.9000,... 10.0000, 10.1000, 10.2000, 10.3000, 10.4000, 10.5000, 10.6000, 10.7000, 10.8000, 10.9000,... 11.0000, 11.1000, 11.2000, 11.3000, 11.4000, 11.5000, 11.6000]; horizontal_chord_equivalent_spherical_diameters = [... 0.0000, 0.1000, 0.2000, 0.3000, 0.3998, 0.4996, 0.5992, 0.6986, 0.7976, 0.8964,... 0.9947, 1.0927, 1.1903, 1.2875, 1.3842, 1.4804, 1.5761, 1.6711, 1.7657, 1.8597,... 1.9531, 2.0460, 2.1385, 2.2304, 2.3217, 2.4124, 2.5026, 2.5921, 2.6812, 2.7696,... 2.8574, 2.9448, 3.0319, 3.1185, 3.2046, 3.2903, 3.3755, 3.4603, 3.5446, 3.6286,... 3.7120, 3.7950, 3.8776, 3.9598, 4.0416, 4.1229, 4.2036, 4.2841, 4.3642, 4.4440,... 4.5233, 4.6024, 4.6811, 4.7597, 4.8378, 4.9152, 4.9924, 5.0690, 5.1452, 5.2210,... 5.2961, 5.3711, 5.4457, 5.5201, 5.5942, 5.6681, 5.7416, 5.8148, 5.8877, 5.9602,... 6.0323, 6.1041, 6.1756, 6.2467, 6.3175, 6.3879, 6.4580, 6.5278, 6.5973, 6.6664,... 6.7353, 6.8040, 6.8720, 6.9399, 7.0075, 7.0744, 7.1411, 7.2074, 7.2733, 7.3388,... 7.4040, 7.4688, 7.5332, 7.5973, 7.6610, 7.7241, 7.7864, 7.8490, 7.9117, 7.9739,... 8.0359, 8.0976, 8.1591, 8.2203, 8.2813, 8.3421, 8.4027, 8.4631, 8.5233, 8.5834,... 8.6433, 8.7030, 8.7625, 8.8220, 8.8814, 8.9407, 8.9998]; vertical_chords = [... 0.0000, 0.1000, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000, 0.7000, 0.8000, 0.9000,... 1.0000, 1.1000, 1.2000, 1.3000, 1.4000, 1.5000, 1.6000, 1.7000, 1.8000, 1.9000,... 2.0000, 2.1000, 2.2000, 2.3000, 2.4000, 2.5000, 2.6000, 2.7000, 2.8000, 2.9000,... 3.0000, 3.1000, 3.2000, 3.3000, 3.4000, 3.5000, 3.6000, 3.7000, 3.8000, 3.9000,... 4.0000, 4.1000, 4.2000, 4.3000, 4.4000, 4.5000, 4.6000, 4.7000, 4.8000, 4.9000,... 5.0000, 5.1000, 5.2000, 5.3000, 5.4000]; vertical_chord_equivalent_spherical_diameters = [... 0.0000, 0.1000, 0.2000, 0.3001, 0.4003, 0.5008, 0.6016, 0.7028, 0.8048, 0.9075,... 1.0110, 1.1155, 1.2208, 1.3271, 1.4348, 1.5438, 1.6545, 1.7668, 1.8809, 1.9967,... 2.1142, 2.2336, 2.3553, 2.4792, 2.6059, 2.7353, 2.8677, 3.0023, 3.1394, 3.2792,... 3.4219, 3.5678, 3.7169, 3.8695, 4.0259, 4.1865, 4.3512, 4.5201, 4.6922, 4.8687,... 5.0525, 5.2438, 5.4432, 5.6474, 5.8580, 6.0775, 6.3073, 6.5485, 6.8018, 7.0729,... 7.3699, 7.7007, 8.0781, 8.4868, 8.9230]; diameter_circle_fit = 0.0; diameter_horiz_chord = 0.0; diameter_vert_chord = 0.0; diameter_horiz_mean = 0.0; diameter_spheroid = 0.0; axis_ratio = 0.0; center_in = 0; scaling_factor_for_horizontal_lengths = corrected_horizontal_diode_size / diode_size; corrected_diodes_added_to_length = 0; if(image_area < 1) diameter_circle_fit = corrected_diodes_added_to_length; diameter_horiz_chord = corrected_diodes_added_to_length; diameter_vert_chord = corrected_diodes_added_to_length; diameter_horiz_mean = corrected_diodes_added_to_length; diameter_spheroid = corrected_diodes_added_to_length; center_in=0; axis_ratio = 1.0; return; end largest_edge_touching_length = largest_edge_touching * scaling_factor_for_horizontal_lengths; smallest_edge_touching_length = smallest_edge_touching * scaling_factor_for_horizontal_lengths; max_horizontal_length = max_horizontal_length * scaling_factor_for_horizontal_lengths; corrected_diodes_added_to_length = diodes_added_to_length * scaling_factor_for_horizontal_lengths; % determine no. of edges number_edges_touching = 0; if largest_edge_touching > 0 number_edges_touching = number_edges_touching + 1; if smallest_edge_touching > 0 number_edges_touching = number_edges_touching + 1; end elseif smallest_edge_touching > 0 number_edges_touching = number_edges_touching + 1; end center_in = 1; if max_horizontal_length <= largest_edge_touching center_in = 0; end if number_edges_touching == 2 & center_in == 1 temp = number_diodes_in_array + (largest_edge_touching_length^2 - smallest_edge_touching_length^2 ) / ( 4 * number_diodes_in_array); % + is replaced by -, Will 10/17/2013 horizontal_size = sqrt(temp^2 + smallest_edge_touching_length^2); horizontal_chord = horizontal_size * diode_size; diameter_circle_fit = horizontal_chord_to_spherical_dia(horizontal_chord); diameter_horiz_chord = horizontal_chord_to_spherical_dia(horizontal_chord); elseif number_edges_touching == 2 largest_edge_touching_length = largest_edge_touching_length + corrected_diodes_added_to_length; temp = number_diodes_in_array + (largest_edge_touching_length^2 - smallest_edge_touching_length^2 ) / ( 4 * number_diodes_in_array); % + is replaced by -, Will 10/17/2013 horizontal_size = sqrt(temp^2 + smallest_edge_touching_length^2); horizontal_chord = horizontal_size * diode_size; diameter_circle_fit = horizontal_chord_to_spherical_dia(horizontal_chord); elseif number_edges_touching == 1 & center_in == 1 horizontal_chord = (max_horizontal_length + diodes_added_to_length) * corrected_horizontal_diode_size; diameter_horiz_chord = horizontal_chord_to_spherical_dia(horizontal_chord); diameter_circle_fit = horizontal_chord_to_spherical_dia(horizontal_chord); elseif number_edges_touching == 1 largest_edge_touching_length = largest_edge_touching_length + corrected_diodes_added_to_length; max_vertical_length = max_vertical_length + diodes_added_to_height * 0.5; horizontal_size = (0.25 * largest_edge_touching_length^2 + max_vertical_length^2)/(max_vertical_length); horizontal_chord = horizontal_size * diode_size; diameter_circle_fit = horizontal_chord_to_spherical_dia(horizontal_chord); else horizontal_chord = (max_horizontal_length + diodes_added_to_length) * corrected_horizontal_diode_size; diameter_horiz_chord = horizontal_chord_to_spherical_dia(horizontal_chord); diameter_circle_fit = horizontal_chord_to_spherical_dia(horizontal_chord); vertical_chord = (max_vertical_length + diodes_added_to_length) * diode_size; axis_ratio = vertical_chord / horizontal_chord; diameter_vert_chord = vertical_chord_to_spherical_dia(vertical_chord); horizontal_mean_chord = sqrt(horizontal_chord * vertical_chord); diameter_horiz_mean = horizontal_chord_to_spherical_dia(horizontal_mean_chord); diameter_spheroid = exp(log(horizontal_chord^2 * vertical_chord)/3); end end function diameter=vertical_chord_to_spherical_dia(vertical_chord) global max_vertical_chords max_horizontal_chords vertical_chords vertical_chord_equivalent_spherical_diameters... horizontal_chords horizontal_chord_equivalent_spherical_diameters delta_vertical_chord = .1; i = round(vertical_chord * 10); if i+1 < max_vertical_chords & i ~=0 delta_diameter = vertical_chord_equivalent_spherical_diameters(i+1) - vertical_chord_equivalent_spherical_diameters(i); diameter = vertical_chord_equivalent_spherical_diameters(i) + (delta_diameter / delta_vertical_chord) * (vertical_chord - vertical_chords(i)); elseif i == 0 diameter = 0; else diameter = 9.1; end end function diameter = horizontal_chord_to_spherical_dia(horizontal_chord) global max_vertical_chords max_horizontal_chords vertical_chords vertical_chord_equivalent_spherical_diameters... horizontal_chords horizontal_chord_equivalent_spherical_diameters delta_horizontal_chord = .1; i = round(horizontal_chord * 10); if i+1 < max_horizontal_chords & i ~= 0 delta_diameter = horizontal_chord_equivalent_spherical_diameters(i+1) - horizontal_chord_equivalent_spherical_diameters(i); diameter = horizontal_chord_equivalent_spherical_diameters(i) + (delta_diameter / delta_horizontal_chord) * (horizontal_chord - horizontal_chords(i)); elseif i == 0 diameter = 0; else diameter = 9.1; end end
github
jjjjfrench/UW-UIOPS-master
ParticlePerimeter.m
.m
UW-UIOPS-master/img_processing/ParticlePerimeter.m
572
utf_8
a4d9612a610598df7fa2589693967992
% Get the single particle perimeter % % Inputs: % image_buffer - n x photodiodes/8 raw image buffer without timestamps % Outputs: % Perimeter % % * Created by Wei Wu, July 4th, 2014 function [pperimeter] = ParticlePerimeter(image_buffer) [m, n] = size(image_buffer); pperimeter = 0; c1=[49*ones(1,n+2);49*ones(m,1),image_buffer,49*ones(m,1);49*ones(1,n+2)]; for i=2:m+1 for j=2:n+1 if (48==c1(i,j) && ( 48~=c1(i+1,j) || 48~=c1(i-1,j) || 48~=c1(i,j+1) || 48~=c1(i,j-1) ) ) pperimeter = pperimeter+1; end end end end
github
jjjjfrench/UW-UIOPS-master
holroyd.m
.m
UW-UIOPS-master/img_processing/holroyd.m
8,020
utf_8
fcd3dc3dbe5ec078354af14eacdcc6a4
% holroyd - identified particle habit according to Holroyd (1987) % inputs: % handles - handles structure outlined in run_img_processing.m % image_buffer - n x photodiodes/8 raw image buffer without timestamps % outputs: % holroyd_habit - habit code as listed below % 5/15/2017 -- it was discovered that certain threshold values were only % appropriate for probes of 25 micron resolution so changes were made to % accomodate probes of 10 micron resolution, documented below --Jacobson % 6/6/2017 -- changes generalized and and edited for future expandability % for other probes -Majewski function [holroyd_habit] = holroyd(handles, image_buffer, probename) %/***************************************************************/% %/* Return code */ %/* */ %/* */ %/* reference: J. Atmos. and Oceanic Tech. Vol 4, Sept. '87 */ %/* pages 498- 511. */ %/* */ %/* 'M' = not calculated, zero image */ %/* 'C' = not calculated, center is out */ %/* 't' = tiny */ %/* 'o' = oriented */ %/* 'l' = linear */ %/* 'a' = aggregate */ %/* 'g' = graupel */ %/* 's' = spherel */ %/* 'h' = hexagonal */ %/* 'i' = irregular */ %/* 'd' = dendrite */ %/* */ %/***************************************************************/ switch probename case '2DS' probe_resolution = .010; ol_d_length = 160.; a_d_length = 400.; ag_d_length = 160.; gh_d_length = 80.; id_x_length = 17.; otherwise %This is actually the settings for the CIP probe, but as they were already hardcoded prior, they are the default option until more probes are added probe_resolution = .025; ol_d_length = 64.; a_d_length = 160.; ag_d_length = 64.; gh_d_length = 32.; id_x_length = 7.; end image_size = size(image_buffer); n_slices = image_size(1); if (n_slices == 0) holroyd_habit = 'M'; return; else if (parabola_fit_center_is_in(image_buffer, n_slices) == 1) [x_length, y_length, d_length, w_width,a_angle,area,r2_correlation, F_fine_detail, S_ratio] = calc_stat(handles,image_buffer, n_slices); if (area == 0 ) holroyd_habit = 'M'; return; elseif (area < 25) holroyd_habit = 't'; return; elseif (r2_correlation >= .4) || ( (d_length < ol_d_length) && ( (x_length >= 4*y_length) || (y_length >= 4*x_length))) if ((a_angle> 30.0) && (a_angle < 60.0)) holroyd_habit = 'o'; return; else holroyd_habit = 'l'; return; end elseif ( (d_length * probe_resolution > 6.4 ) || (d_length > a_d_length)) holroyd_habit = 'a'; return; elseif (S_ratio >= .7) holroyd_habit = 'g'; return; elseif (d_length >= ag_d_length) if (F_fine_detail <= 13) holroyd_habit = 'g'; return; else holroyd_habit = 'a'; return; end elseif (F_fine_detail < 5.5) holroyd_habit = 's'; return; elseif (F_fine_detail < 10.0) if (d_length >= gh_d_length) holroyd_habit = 'g'; return; else holroyd_habit = 'h'; return; end elseif ((F_fine_detail < 16.0) || (x_length <= id_x_length)) holroyd_habit = 'i'; return; else holroyd_habit = 'd'; return; end else holroyd_habit = 'C'; return; end end end %/*************************************************************************/ %/*************************************************************************/ function [x_length, y_length, d_length, w_width,a_angle,area,r2_correlation, F_fine_detail, S_ratio] = calc_stat(handles, image_buffer, n_slices) BITS_PER_SLICE = handles.bits_per_slice; MAX_TWOD_DATA_LENGTH = 6000; area = 0.0; n_count = 0; sum_x2= 0.0; sum_y2= 0.0; sum_x = 0.0; sum_y = 0.0; sum_xy= 0.0; cross_x2= 0.0; cross_y2= 0.0; cross_xy= 0.0; p_perimeter_change = 0; min_x = MAX_TWOD_DATA_LENGTH*3; min_y = BITS_PER_SLICE; max_x = 0; max_y = 0; spot_on_off = 0; fully_on_count = 0; partial_on_count =0; if (n_slices <= 0) return; end for i=1:n_slices fully_on_temp = 0; for j=1:BITS_PER_SLICE if ((image_buffer(i,j)) == '0') tx = i; ty = j; if (tx > max_x) max_x = tx; end if (tx < min_x) min_x = tx; end if (ty > max_y) max_y = ty; end if (ty < min_y) min_y = ty; end sum_x2 = sum_x2 + tx * tx; sum_y2 = sum_y2 + ty * ty; sum_x = sum_x + tx; sum_y = sum_y + ty; sum_xy = sum_xy + tx * ty; n_count = n_count + 1; p(n_count).x = tx; p(n_count).y = ty; fully_on_temp = fully_on_temp + 1; if (spot_on_off == 0) spot_on_off = 1; p_perimeter_change = p_perimeter_change + 1; end else if spot_on_off == 1 spot_on_off = 0; p_perimeter_change = p_perimeter_change + 1; end end end if (fully_on_temp == BITS_PER_SLICE) fully_on_count = fully_on_count + 1; end if (fully_on_temp ~= 0) partial_on_count = partial_on_count + 1; end end area = n_count; %/*** scan the other way for perimeter change ****/ spot_on_off = 0; for j=1:BITS_PER_SLICE for i=1:n_slices if ((image_buffer(i,j)) == '0') if (spot_on_off == 0) spot_on_off = 1; p_perimeter_change = p_perimeter_change + 1; end else if (spot_on_off == 1) spot_on_off = 0; p_perimeter_change = p_perimeter_change + 1; end end end end if (max_x >= min_x) x_length = max_x - min_x +1; else x_length = 0.0; end if (max_y >= min_y) y_length = max_y - min_y +1; else y_length = 0.0; end cross_xy = sum_xy - (sum_x * sum_y / area); cross_x2 = sum_x2 - (sum_x * sum_x / area); cross_y2 = sum_y2 - (sum_y * sum_y / area); slope = cross_xy / cross_x2; intercept = (sum_y/(area)) - slope * (sum_x/(area)); angle_radian = atan(slope); a_angle = atan(slope) * (180.0/pi); if (a_angle < 0) a_angle = a_angle + 180.0; angle_radian = angle_radian + pi; end dmin_x = MAX_TWOD_DATA_LENGTH*3; dmin_y = BITS_PER_SLICE; dmax_x = 0; dmax_y = 0; if ( (angle_radian > (pi/2.0)) & (angle_radian <= (pi))) angle_radian = (pi - angle_radian); elseif ( angle_radian > pi) ['HEY: something is wrong here a_angle = ', num2str(a_angle)]; return end for i=1:n_count new_x = (p(i).x * cos(angle_radian)) + (p(i).y * sin(angle_radian)); new_y = (p(i).y * cos(angle_radian)) - (p(i).x * sin(angle_radian)); if (new_x > dmax_x) dmax_x = new_x; end if (new_y > dmax_y) dmax_y = new_y; end if (new_x < dmin_x) dmin_x = new_x; end if (new_y < dmin_y) dmin_y = new_y; end end d_length = (dmax_x - dmin_x) +1; w_width = (dmax_y - dmin_y) +1; r2_correlation = (cross_xy) / (sqrt( cross_x2 * cross_y2)); F_fine_detail = p_perimeter_change * (d_length)/ area; if (partial_on_count ~=0 ) S_ratio = fully_on_count / partial_on_count; else S_ratio = 0.0; end end %/**************************************************************************/ %/**************************************************************************/ function result = parabola_fit_center_is_in(image_buffer, n_slices) result = 1; return; end
github
jjjjfrench/UW-UIOPS-master
calculate_reject_unified.m
.m
UW-UIOPS-master/img_processing/calculate_reject_unified.m
20,696
utf_8
4438b2dee44f70bdd279914cf9ee9ec0
function [p_length,width,area,longest_y,max_top,max_bottom,touching_edge,reject_status,is_hollow,percent_shadow_area,part_z,size_factor,area_hole_ratio,handles]=calculate_reject_unified(image_buffer,handles,habit) % /* RETURN CODE */ % /* 0 = not rejected */ % /* 'a' = reject max. aspect ratio */ % /* 't' = reject max. aspect ratio touch edg */ % /* 'p' = reject percent shadowed area */ % /* 'h' = reject Hollow image */ % /* 's' = reject split image */ % /* 'z' = reject 0 area image */ % /* 'f' = reject fake 0 area image */ z_d = 0 : .05 : 8.15; part_z = -1; size_factor = 1; edge_0 = [1.000, 1.054, 1.083, 1.101, 1.095, 1.110, 1.148, 1.162, 1.155, 1.123, ... 1.182, 1.121, 1.162, 1.210, 1.242, 1.134, 1.166, 1.202, 1.238, 1.270, ... 1.294, 1.278, 1.130, 1.148, 1.170, 1.194, 1.218, 1.242, 1.265, 1.288, ... 1.310, 1.331, 1.351, 1.369, 1.386, 1.400, 1.411, 1.416, 1.407, 1.074, ... 1.080, 1.087, 1.096, 1.106, 1.117, 1.127, 1.139, 1.150, 1.162, 1.173, ... 1.185, 1.197, 1.208, 1.220, 1.232, 1.243, 1.255, 1.266, 1.277, 1.289, ... 1.300, 1.311, 1.322, 1.333, 1.344, 1.355, 1.366, 1.376, 1.387, 1.397, ... 1.407, 1.418, 1.428, 1.438, 1.448, 1.458, 1.467, 1.477, 1.486, 1.496, ... 1.505, 1.515, 1.524, 1.533, 1.542, 1.551, 1.559, 1.568, 1.577, 1.585, ... 1.594, 1.602, 1.610, 1.618, 1.626, 1.634, 1.642, 1.650, 1.657, 1.665, ... 1.673, 1.680, 1.687, 1.694, 1.702, 1.709, 1.716, 1.722, 1.729, 1.736, ... 1.742, 1.749, 1.755, 1.761, 1.768, 1.774, 1.780, 1.786, 1.791, 1.797, ... 1.803, 1.808, 1.813, 1.819, 1.824, 1.829, 1.834, 1.839, 1.843, 1.848, ... 1.852, 1.857, 1.861, 1.865, 1.869, 1.872, 1.876, 1.880, 1.883, 1.886, ... 1.889, 1.892, 1.895, 1.897, 1.899, 1.901, 1.903, 1.905, 1.906, 1.907, ... 1.908, 1.908, 1.908, 1.908, 1.907, 1.905, 1.903, 1.900, 1.897, 1.892, ... 1.885, 1.877, 1.865, 1.845]; spot_edge = [0.003, 0.008, 0.017, 0.024, 0.033, 0.040, 0.047, 0.054, 0.062, 0.072, ... 0.076, 0.088, 0.093, 0.096, 0.101, 0.119, 0.123, 0.127, 0.130, 0.134, ... 0.139, 0.148, 0.175, 0.180, 0.184, 0.188, 0.192, 0.195, 0.199, 0.202, ... 0.206, 0.209, 0.213, 0.217, 0.221, 0.225, 0.230, 0.235, 0.243, 0.327, ... 0.334, 0.340, 0.345, 0.351, 0.355, 0.360, 0.365, 0.369, 0.373, 0.377, ... 0.381, 0.385, 0.389, 0.393, 0.397, 0.400, 0.404, 0.408, 0.411, 0.415, ... 0.419, 0.422, 0.426, 0.429, 0.433, 0.436, 0.439, 0.443, 0.446, 0.450, ... 0.453, 0.457, 0.460, 0.463, 0.467, 0.470, 0.473, 0.477, 0.480, 0.484, ... 0.487, 0.490, 0.494, 0.497, 0.501, 0.504, 0.507, 0.511, 0.514, 0.518, ... 0.521, 0.525, 0.528, 0.532, 0.535, 0.539, 0.543, 0.547, 0.550, 0.554, ... 0.558, 0.562, 0.566, 0.569, 0.572, 0.575, 0.578, 0.581, 0.584, 0.587, ... 0.590, 0.593, 0.596, 0.598, 0.601, 0.605, 0.610, 0.614, 0.618, 0.623, ... 0.627, 0.631, 0.635, 0.640, 0.644, 0.648, 0.653, 0.657, 0.662, 0.666, ... 0.671, 0.676, 0.680, 0.685, 0.690, 0.695, 0.700, 0.705, 0.711, 0.716, ... 0.721, 0.727, 0.733, 0.738, 0.744, 0.751, 0757, 0.763, 0.770, 0.777, ... 0.784, 0.792, 0.800, 0.808, 0.817, 0.826, 0.836, 0.846, 0.858, 0.870, ... 0.884, 0.901, 0.921, 0.950]; % temp = [dec2bin(image_buffer(:,1),16),dec2bin(image_buffer(:,2),16),dec2bin(image_buffer(:,3),16),... % dec2bin(image_buffer(:,4),16),dec2bin(image_buffer(:,5),16),dec2bin(image_buffer(:,6),16),... % dec2bin(image_buffer(:,7),16),dec2bin(image_buffer(:,8),16)]; % clear image_buffer % image_buffer(:,:)=temp(:,:); n_size=size(image_buffer); n_slices=n_size(1); handles.rej_zero_area = 1; handles.rej_split = 1; handles.rej_hollow = 1; handles.bits_per_slice = n_size(2); handles.shadowed_area = 25; handles.max_edge_img_ar = 6; handles.max_comp_img_ar = 5; handles.max_hole_diameter = 0; handles.edge_at_max_hole = 0; min_length=-1; max_length=-1; max_width=1; min_width=n_size(2); total_area=0; touch=0; width = 0; ndrops=0; split=0; hollow=0; met_image=0; is_hollow=0; aspect_ratio=0; percent_shadow_area=0; area_hole_ratio = 0; area=0; max_top=0; max_bottom=0; longest_y=0; touching_edge=0; top_min_x=-1; top_max_x=-1; bottom_min_x=-1; bottom_max_x=-1; if n_slices==0 p_length=0; area=0; if handles.rej_zero_area==1 reject_status='z'; return; else reject_status='0'; end else for i=1:n_slices [min_pos_lite,max_pos_lite,n_lite]=scan_slice(image_buffer(i,:),handles); if longest_y < n_lite longest_y=n_lite; end if i>1 vertical_split=vertical_split & image_buffer(i,:); else vertical_split=image_buffer(i,:); end if n_lite>0 if touch==0 if max_pos_lite==handles.bits_per_slice || min_pos_lite==1 touch=1; end end if min_pos_lite==1 if bottom_min_x==-1 bottom_min_x=i; end if bottom_max_x<i bottom_max_x=i; end end if max_pos_lite==handles.bits_per_slice if top_min_x==-1 top_min_x=i; end if top_max_x<i top_max_x=i; end end if max_pos_lite > max_width max_width=max_pos_lite; end if min_pos_lite < min_width min_width=min_pos_lite; end if min_length == -1 min_length = i; max_length = i; else max_length = i; end total_area=n_lite+total_area; end if met_image == 0 & n_lite > 0 met_image=1; ndrops=ndrops+1; if ndrops > 1 & handles.rej_split==1 split=1; end elseif met_image==1 & n_lite == 0 met_image=0; end end area=total_area; if top_min_x == -1 max_top = 0; else max_top = (top_max_x - top_min_x) + 1; end if bottom_min_x == -1 max_bottom = 0; else max_bottom = (bottom_max_x - bottom_min_x) + 1; end if touch == 1 touching_edge = 't'; else touching_edge = '0'; end if total_area == 0; p_length = 0; width = 0; else p_length = max_length - min_length + 1; width = max_width - min_width + 1; end if total_area > .8 * handles.bits_per_slice * n_slices reject_status = 'A'; return; end if split == 1 reject_status = 's'; return; end if exist('vertical_split') == 1 [min_pos_lite,max_pos_lite,n_lite]=scan_slice(vertical_split,handles); else min_pos_lite=0; max_pos_lite=0; n_lite=0; end if n_lite == 1 & n_lite ~= max_pos_lite - min_pos_lite + 1 & handles.rej_split == 0 reject_status = 's'; return; end if total_area > 0 if p_length > 0 & width > 0 aspect_ratio = p_length / width; percent_shadow_area = total_area / (p_length * width ) * 100; else aspect_ratio = 0; percent_shadow_area = 0; end else aspect_ratio = 0; percent_shadow_area = 0; end if total_area == 0 && handles.rej_zero_area == 1 reject_status = 'z'; return; elseif total_area == 0 && handles.rej_zero_area == 0 reject_status = '0'; return; elseif ( aspect_ratio > handles.max_comp_img_ar || aspect_ratio < 1/handles.max_comp_img_ar ) % Second critirion added on Dec 2nd, 2013 by Will for small aspect ratio reject_status = 'a'; return; elseif touch == 1 && aspect_ratio > handles.max_edge_img_ar reject_status = 't'; return; elseif percent_shadow_area < handles.shadowed_area reject_status = 'p'; return; elseif handles.rej_hollow == 1 [hollow_status,edge_at_max_hole,max_hole_diameter]=is_it_hollow(image_buffer(1:n_slices,:),n_slices,handles); [hollow_status2,edge_at_max_hole2,max_hole_diameter2]=is_it_hollow(image_buffer(n_slices:-1:1,:),n_slices,handles); [hollow_status_side1,edge_at_max_hole_side1,max_hole_diameter_side1]=is_it_hollow_sidescan(image_buffer(1:n_slices,:)',n_slices,handles); [hollow_status_side2,edge_at_max_hole_side2,max_hole_diameter_side2]=is_it_hollow_sidescan(image_buffer(1:n_slices,32:-1:1)',n_slices,handles); if hollow_status ~= hollow_status2 hollow_status; % handles.disagree = handles.disagree + 1; end % % if hollow_status == 1 & hollow_status2 == 0 % hollow_status = 0; % end if hollow_status + hollow_status2 == 1 & (habit == 's' | habit == 'h' | habit == 'i' | habit == 't') %if hollow_status + hollow_status2 == 1 hollow_status = 1; elseif habit == 'd' & percent_shadow_area < 35 & hollow_status + hollow_status2 == 1 hollow_status = 1; elseif hollow_status == 1 & hollow_status2 == 0 hollow_status = 0; end if percent_shadow_area < 30 hollow_status = 0; end if hollow_status == 1 % ratio = max_hole_diameter./(max_width-min_width+1); if edge_at_max_hole <= 0 ratio = 0; else ratio = max_hole_diameter./edge_at_max_hole; end if ratio == 0 part_z = 0; size_factor = 1; reject_status = 'h'; area_hole_ratio = 0; elseif max_hole_diameter <= 1 part_z = 0; size_factor = 1; area_hole_ratio = 0; reject_status = '0'; else part_z = z_d(find(spot_edge < ratio,1,'last')); size_factor = edge_0(find(z_d <= part_z,1,'last')); reject_status = 'H'; area_hole_ratio = area/max_hole_diameter; if hollow_status_side1 + hollow_status_side2 < 1 part_z = 0; size_factor = 1; reject_status = 'i'; end if area_hole_ratio > 20 & habit == 'i' part_z = 0; size_factor = 1; reject_status = 'u'; elseif area_hole_ratio > 35 & habit == 'h' part_z = 0; size_factor = 1; reject_status = 'u'; elseif area_hole_ratio > 40 part_z = 0; size_factor = 1; reject_status = 'u'; end end handles.edge_at_max_hole = edge_at_max_hole; handles.max_hole_diameter = max_hole_diameter; return else ratio = -1; part_z = -1; size_factor = 1; area_hole_ratio = 0; end % if hollow_status ==1 % reject_status='h'; % return % end end reject_status = '0'; return end function [min_pos_lite,max_pos_lite,n_lite]=scan_slice(image_buf,handles) n_lite=0; max_pos_lite=0; min_pos_lite=0; zeros = find(image_buf == '0'); n_lite = length(zeros); if n_lite == 0 return else min_pos_lite = zeros(1); max_pos_lite = zeros(n_lite); end % for i=1:handles.bits_per_slice % if image_buf(i) == '0' % n_lite=n_lite+1; % if min_pos_lite==0 % min_pos_lite=i; % max_pos_lite=i; % else % max_pos_lite=i; % end % end % end return function [status,edge_at_max_hole,max_hole_diameter] = is_it_hollow(image_buf,slices,handles) current = 0; old = 0; new = 0; possibly_hollow = 0; max_hole_diameter = 0; edge_at_max_hole = 0; status = 0; start_img = 0; end_img = 0; i = 1; while end_img == 0 zero_amt = sum(image_buf(i,:) == '0'); if zero_amt > 0 & start_img == 0 start_img = i; end if zero_amt == 0 & start_img > 0 end_img = i; end i = i + 1; if i > slices if start_img == 0 start_img = 1; end if end_img == 0 end_img = slices; end end end slices = end_img-start_img+1; for i=start_img:end_img [min_pos_lite,max_pos_lite,n_lite]=scan_slice(image_buf(i,:),handles); num_empty = max_pos_lite - min_pos_lite + 1 - n_lite; if slices > 6 slices_third = floor(slices/3); else slices_third = 1; end if num_empty > max_hole_diameter & i > slices_third & i < slices - slices_third max_hole_diameter = num_empty; edge_at_max_hole = max_pos_lite - min_pos_lite + 1; end if possibly_hollow == 1 & status == 0 if n_lite > 0 & n_lite ~= max_pos_lite - min_pos_lite + 1 new = bin2dec(image_buf(i,17:32)) + bitshift(bin2dec(image_buf(i,1:16)),16); olddec = bin2dec(old(17:32)) + bitshift(bin2dec(old(1:16)),16); newandold = bitand(new , olddec); if newandold == zeros status=1; % return else old = mask_start_end(max_pos_lite, min_pos_lite, image_buf(i,:),handles.bits_per_slice); end elseif n_lite > 0 bufdec = bin2dec(image_buf(i,17:32)) + bitshift(bin2dec(image_buf(i,1:16)),16); olddec = bin2dec(old(17:32)) + bitshift(bin2dec(old(1:16)),16); bufdec1 = bin2dec(image_buf(i,1:16)); olddec1 = bin2dec(old(1:16)); bufdec2 = bin2dec(image_buf(i,17:32)); olddec2 = bin2dec(old(17:32)); bufandold1 = bitand(bufdec1,olddec1); bufandold2 = bitand(bufdec2,olddec2); hole_size = length(find(old == '1')); cover_size = length(find(dec2bin(bufandold1) == '1')) + length(find(dec2bin(bufandold2) == '1')); % % bufandold = bitand(bufdec , olddec); % hole_size = length(find(old == '1')); % cover_size = length(find(dec2bin(bufandold) == '1')); % % if bufandold1 + bufandold2 > 0 % if cover_size <= 2 & hole_size ~=1 if cover_size <= .65*hole_size status = 1; % return; end possibly_hollow = 0; old = 0; elseif i > 1 status = 1; % return; else possibly_hollow = 0; old = 0; end else possibly_hollow = 0; end elseif status == 0 if n_lite > 0 & n_lite ~= max_pos_lite - min_pos_lite + 1 old = mask_start_end(max_pos_lite, min_pos_lite, image_buf(i,:),handles.bits_per_slice); possibly_hollow = 1; end end end return; function [status,edge_at_max_hole,max_hole_diameter] = is_it_hollow_sidescan(image_buf,slices,handles) current = 0; old = 0; new = 0; possibly_hollow = 0; max_hole_diameter = 0; edge_at_max_hole = 0; status = 0; im_width = size(image_buf); if im_width(2) > 32 im_width(2) = 32; end start_img = 0; end_img = 0; i = 1; while end_img == 0 zero_amt = sum(image_buf(i,:) == '0'); if zero_amt > 0 && start_img == 0 start_img = i; end if zero_amt == 0 && start_img > 0 end_img = i; end i = i + 1; if i > 32 if start_img == 0 start_img = 1; end if end_img == 0 end_img = 32; end end end slices = end_img-start_img+1; for i=start_img:end_img [min_pos_lite,max_pos_lite,n_lite]=scan_slice(image_buf(i,:),handles); num_empty = max_pos_lite - min_pos_lite + 1 - n_lite; if slices > 6 slices_third = floor(slices/3); else slices_third = 1; end if num_empty > max_hole_diameter & i > slices_third & i < slices - slices_third max_hole_diameter = num_empty; edge_at_max_hole = max_pos_lite - min_pos_lite + 1; end if possibly_hollow == 1 & status == 0 if n_lite > 0 & n_lite ~= max_pos_lite - min_pos_lite + 1 if im_width(2) <= 16 new = bin2dec(image_buf(i,1:im_width(2))); olddec = bin2dec(old(1:im_width(2))); else new = bin2dec(image_buf(i,17:im_width(2))) + bitshift(bin2dec(image_buf(i,1:16)),16); olddec = bin2dec(old(17:im_width(2))) + bitshift(bin2dec(old(1:16)),16); end newandold = bitand(new , olddec); if newandold == zeros status=1; % return else old = mask_start_end(max_pos_lite, min_pos_lite, image_buf(i,:),im_width(2)); end elseif n_lite > 0 % bufdec = bin2dec(image_buf(i,33:64)) + bitshift(bin2dec(image_buf(i,1:32)),32); % olddec = bin2dec(old(33:64)) + bitshift(bin2dec(old(1:32)),32); if im_width(2) <= 16 bufdec1 = bin2dec(image_buf(i,1:im_width(2))); olddec1 = bin2dec(old(1:im_width(2))); bufdec2 = 0; olddec2 = 0; else bufdec1 = bin2dec(image_buf(i,1:16)); olddec1 = bin2dec(old(1:16)); bufdec2 = bin2dec(image_buf(i,17:im_width(2))); olddec2 = bin2dec(old(17:im_width(2))); end bufandold1 = bitand(bufdec1,olddec1); bufandold2 = bitand(bufdec2,olddec2); hole_size = length(find(old == '1')); cover_size = length(find(dec2bin(bufandold1) == '1')) + length(find(dec2bin(bufandold2) == '1')); % % bufandold = bitand(bufdec , olddec); % hole_size = length(find(old == '1')); % cover_size = length(find(dec2bin(bufandold) == '1')); % % if bufandold1 + bufandold2 > 0 % if cover_size <= 2 & hole_size ~=1 if cover_size <= .65*hole_size status = 1; % return; end possibly_hollow = 0; old = 0; elseif i > 1 status = 1; % return; else possibly_hollow = 0; old = 0; end else possibly_hollow = 0; end elseif status == 0 if n_lite > 0 & n_lite ~= max_pos_lite - min_pos_lite + 1 old = mask_start_end(max_pos_lite, min_pos_lite, image_buf(i,:),im_width(2)); possibly_hollow = 1; end end end return; function old = mask_start_end(end_mask, start_mask, to_mask,bits_per_slice) result=0; if start_mask == 0 & end_mask == 0 result = to_mask; else % to_mask_dec = bin2dec(to_mask(33:64)) + bitshift(bin2dec(to_mask(1:32)),32); % result = bitshift(bitshift(to_mask_dec,start_mask),-start_mask); % result = bitshift(bitshift(result,-(bits_per_slice - end_mask) + 1),(bits_per_slice - end_mask)+1); % result = dec2bin(result,bits_per_slice); result(1:bits_per_slice) = '0'; result(start_mask:end_mask) = to_mask(start_mask:end_mask); end old=char(result); return;
github
safdarne/TRGMC-master
sc.m
.m
TRGMC-master/sc.m
38,505
utf_8
7f1b3d24c919310f72c1f507ef09f0c6
function I = sc(I, varargin) %SC Display/output truecolor images with a range of colormaps % % Examples: % sc(image) % sc(image, limits) % sc(image, map) % sc(image, limits, map) % sc(image, map, limits) % sc(..., col1, mask1, col2, mask2,...) % out = sc(...) % sc % % Generates a truecolor RGB image based on the input values in 'image' and % any maximum and minimum limits specified, using the colormap specified. % The image is displayed on screen if there is no output argument. % % SC has these advantages over MATLAB image rendering functions: % - images can be displayed or output; makes combining/overlaying images % simple. % - images are rendered/output in truecolor (RGB [0,1]); no nasty % discretization of the input data. % - many special, built-in colormaps for viewing various types of data. % - linearly interpolates user defined linear and non-linear colormaps. % - no border and automatic, integer magnification (unless figure is % docked or maximized) for better display. % - multiple images can be generated for export simultaneously. % % For a demonstration, simply call SC without any input arguments. % % IN: % image - MxNxCxP or 3xMxNxP image array. MxN are the dimensions of the % image(s), C is the number of channels, and P the number of % images. If P > 1, images can only be exported, not displayed. % limits - [min max] where values in image less than min will be set to % min and values greater than max will be set to max. % map - Kx3 or Kx4 user defined colormap matrix, where the optional 4th % column is the relative distance between colours along the scale, % or a string containing the name of the colormap to use to create % the output image. Default: 'none', which is RGB for 3-channel % images, grayscale otherwise. Conversion of multi-channel images % to intensity for intensity-based colormaps is done using the L2 % norm. Most MATLAB colormaps are supported. All named colormaps % can be reversed by prefixing '-' to the string. This maintains % integrity of the colorbar. Special, non-MATLAB colormaps are: % 'contrast' - a high contrast colormap for intensity images that % maintains intensity scale when converted to grayscale, % for example when printing in black & white. % 'prob' - first channel is plotted as hue, and the other channels % modulate intensity. Useful for laying probabilites over % images. % 'prob_jet' - first channel is plotted as jet colormap, and the other % channels modulate intensity. % 'diff' - intensity values are marked blue for > 0 and red for < 0. % Darker colour means larger absolute value. For multi- % channel images, the L2 norm of the other channels sets % green level. 3 channel images are converted to YUV and % images with more that 3 channels are projected onto the % principle components first. % 'compress' - compress many channels to RGB while maximizing % variance. % 'flow' - display two channels representing a 2d Cartesian vector as % hue for angle and intensity for magnitude (darker colour % indicates a larger magnitude). % 'phase' - first channel is intensity, second channel is phase in % radians. Darker colour means greater intensity, hue % represents phase from 0 to 2 pi. % 'stereo' - pair of concatenated images used to generate a red/cyan % anaglyph. % 'stereo_col' - pair of concatenated RGB images used to generate a % colour anaglyph. % 'rand' - gives an index image a random colormap. Useful for viewing % segmentations. % 'rgb2gray' - converts an RGB image to grayscale in the same fashion % as MATLAB's rgb2gray (in the image processing toolbox). % col/mask pairs - Pairs of parameters for coloring specific parts of the % image differently. The first (col) parameter can be % a MATLAB color specifier, e.g. 'b' or [0.5 0 1], or % one of the colormaps named above, or an MxNx3 RGB % image. The second (mask) paramater should be an MxN % logical array indicating those pixels (true) whose % color should come from the specified color parameter. % If there is only one col parameter, without a mask % pair, then mask = any(isnan(I, 3)), i.e. the mask is % assumed to indicate the location of NaNs. Note that % col/mask pairs are applied in order, painting over % previous pixel values. % % OUT: % out - MxNx3xP truecolour (double) RGB image array in range [0, 1] % % See also IMAGE, IMAGESC, IMSHOW, COLORMAP, COLORBAR. % $Id: sc.m,v 1.81 2008/12/10 23:14:43 ojw Exp $ % Copyright: Oliver Woodford, 2007 %% Check for arguments if nargin == 0 % If there are no input arguments then run the demo if nargout > 0 error('Output expected from no inputs!'); end demo; % Run the demo return end %% Size our image(s) [y x c n] = size(I); I = reshape(I, y, x, c, n); %% Check if image is given with RGB colour along the first dimension if y == 3 && c > 3 % Flip colour to 3rd dimension I = permute(I, [2 3 1 4]); [y x c n] = size(I); end %% Don't do much if I is empty if isempty(I) if nargout == 0 % Clear the current axes if we were supposed to display the image cla; axis off; else % Create an empty array with the correct dimensions I = zeros(y, x, (c~=0)*3, n); end return end %% Check for multiple images % If we have a non-singleton 4th dimension we want to display the images in % a 3x4 grid and use buttons to cycle through them if n > 1 if nargout > 0 % Return transformed images in an YxXx3xN array A = zeros(y, x, 3, n); for a = 1:n A(:,:,:,a) = sc(I(:,:,:,a), varargin{:}); end I = A; else % Removed functionality fprintf([' SC no longer supports the display of multiple images. The\n'... ' functionality has been incorporated into an improved version\n'... ' of MONTAGE, available on the MATLAB File Exchange at:\n'... ' http://www.mathworks.com/matlabcentral/fileexchange/22387\n']); clear I; end return end %% Parse the input arguments coming after I (1st input) [map limits mask] = parse_inputs(I, varargin, y, x); %% Call the rendering function I = reshape(double(real(I)), y*x, c); % Only work with real doubles if ~ischar(map) % Table-based colormap reverseMap = false; [I limits] = interp_map(I, limits, reverseMap, map); else % If map starts with a '-' sign, invert the colourmap reverseMap = map(1) == '-'; map = lower(map(reverseMap+1:end)); % Predefined colormap [I limits] = colormap_switch(I, map, limits, reverseMap, c); end %% Update any masked pixels I = reshape(I, y*x, 3); for a = 1:size(mask, 2) I(mask{2,a},1) = mask{1,a}(:,1); I(mask{2,a},2) = mask{1,a}(:,2); I(mask{2,a},3) = mask{1,a}(:,3); end I = reshape(I, [y x 3]); % Reshape to correct size %% Only display if the output isn't used if nargout == 0 display_image(I, map, limits, reverseMap); % Don't print out the matrix if we've forgotten the ";" clear I end return %% Colormap switch function [I limits] = colormap_switch(I, map, limits, reverseMap, c) % Large switch statement for all the colourmaps switch map %% Prism case 'prism' % Similar to the MATLAB internal prism colormap, but only works on % index images, assigning each index (or rounded float) to a % different colour [I limits] = index_im(I); % Generate prism colourmap map = prism(6); if reverseMap map = map(end:-1:1,:); % Reverse the map end % Lookup the colours I = mod(I, 6) + 1; I = map(I,:); %% Rand case 'rand' % Assigns a random colour to each index [I limits num_vals] = index_im(I); % Generate random colourmap map = rand(num_vals, 3); % Lookup the colours I = map(I,:); %% Diff case 'diff' % Show positive as blue and negative as red, white is 0 switch c case 1 I(:,2:3) = 0; case 2 % Second channel can only have absolute value I(:,3) = abs(I(:,2)); case 3 % Diff of RGB images - convert to YUV first I = rgb2yuv(I); I(:,3) = sqrt(sum(I(:,2:end) .^ 2, 2)) ./ sqrt(2); otherwise % Use difference along principle component, and other % channels to modulate second channel I = calc_prin_comps(I); I(:,3) = sqrt(sum(I(:,2:end) .^ 2, 2)) ./ sqrt(c - 1); I(:,4:end) = []; end % Generate limits if isempty(limits) limits = [min(I(:,1)) max(I(:,1))]; end limits = max(abs(limits)); if limits % Scale if c > 1 I(:,[1 3]) = I(:,[1 3]) / limits; else I = I / (limits * 0.5); end end % Colour M = I(:,1) > 0; I(:,2) = -I(:,1) .* ~M; I(:,1) = I(:,1) .* M; if reverseMap % Swap first two channels I = I(:,[2 1 3]); end %I = 1 - I * [1 0.4 1; 0.4 1 1; 1 1 0.4]; % (Green/Red) I = 1 - I * [1 1 0.4; 0.4 1 1; 1 0.4 1]; % (Blue/Red) I = min(max(reshape(I, numel(I), 1), 0), 1); limits = [-limits limits]; % For colourbar %% Flow case 'flow' % Calculate amplitude and phase, and use 'phase' if c ~= 2 error('''flow'' requires two channels'); end A = sqrt(sum(I .^ 2, 2)); if isempty(limits) limits = [min(A) max(A)*2]; else limits = [0 max(abs(limits)*sqrt(2))*2]; end I(:,1) = atan2(I(:,2), I(:,1)); I(:,2) = A; if reverseMap % Invert the amplitude I(:,2) = -I(:,2); limits = -limits([2 1]); end I = phase_helper(I, limits, 2); % Last parameter tunes how saturated colors can get % Set NaNs (unknown flow) to 0 I(isnan(I)) = reverseMap; limits = []; % This colourmap doesn't have a valid colourbar %% Phase case 'phase' % Plot amplitude as intensity and angle as hue if c < 2 error('''phase'' requires two channels'); end if isempty(limits) limits = [min(I(:,1)) max(I(:,1))]; end if reverseMap % Invert the phase I(:,2) = -I(:,2); end I = I(:,[2 1]); if diff(limits) I = phase_helper(I, limits, 1.3); % Last parameter tunes how saturated colors can get else % No intensity - just cycle hsv I = hsv_helper(mod(I(:,1) / (2 * pi), 1)); end limits = []; % This colourmap doesn't have a valid colourbar %% RGB2Grey case {'rgb2grey', 'rgb2gray'} % Compress RGB to greyscale [I limits] = rgb2grey(I, limits, reverseMap); %% RGB2YUV case 'rgb2yuv' % Convert RGB to YUV - not for displaying or saving to disk! [I limits] = rgb2yuv(I); %% YUV2RGB case 'yuv2rgb' % Convert YUV to RGB - undo conversion of rgb2yuv if c ~= 3 error('''yuv2rgb'' requires a 3 channel image'); end I = reshape(I, y*x, 3); I = I * [1 1 1; 0, -0.39465, 2.03211; 1.13983, -0.58060 0]; I = reshape(I, y, x, 3); I = sc(I, limits); limits = []; % This colourmap doesn't have a valid colourbar %% Prob case 'prob' % Plot first channel as grey variation of 'bled' and modulate % according to other channels if c > 1 A = rgb2grey(I(:,2:end), [], false); I = I(:,1); else A = 0.5; end [I limits] = bled(I, limits, reverseMap); I = normalize(A + I, [-0.1 1.3]); %% Prob_jet case 'prob_jet' % Plot first channel as 'jet' and modulate according to other % channels if c > 1 A = rgb2grey(I(:,2:end), [], false); I = I(:,1); else A = 0.5; end [I limits] = jet_helper(I, limits, reverseMap); I = normalize(A + I, [0.2 1.8]); %% Compress case 'compress' % Compress to RGB, maximizing variance % Determine and scale to limits I = normalize(I, limits); if reverseMap % Invert after everything I = 1 - I; end % Zero mean meanCol = mean(I, 1); isBsx = exist('bsxfun', 'builtin'); if isBsx I = bsxfun(@minus, I, meanCol); else I = I - meanCol(ones(x*y, 1, 'uint8'),:); end % Calculate top 3 principle components I = calc_prin_comps(I, 3); % Normalize each channel independently if isBsx I = bsxfun(@minus, I, min(I, [], 1)); I = bsxfun(@times, I, 1./max(I, [], 1)); else for a = 1:3 I(:,a) = I(:,a) - min(I(:,a)); I(:,a) = I(:,a) / max(I(:,a)); end end % Put components in order of human eyes' response to channels I = I(:,[2 1 3]); limits = []; % This colourmap doesn't have a valid colourbar %% Stereo (anaglyph) case 'stereo' % Convert 2 colour images to intensity images % Show first channel as red and second channel as cyan A = rgb2grey(I(:,1:floor(end/2)), limits, false); I = rgb2grey(I(:,floor(end/2)+1:end), limits, false); if reverseMap I(:,2:3) = A(:,1:2); % Make first image cyan else I(:,1) = A(:,1); % Make first image red end limits = []; % This colourmap doesn't have a valid colourbar %% Coloured anaglyph case 'stereo_col' if c ~= 6 error('''stereo_col'' requires a 6 channel image'); end I = normalize(I, limits); % Red channel from one image, green and blue from the other if reverseMap I(:,1) = I(:,4); % Make second image red else I(:,2:3) = I(:,5:6); % Make first image red end I = I(:,1:3); limits = []; % This colourmap doesn't have a valid colourbar %% None case 'none' % No colour map - just output the image if c ~= 3 [I limits] = grey(I, limits, reverseMap); else I = intensity(I(:), limits, reverseMap); limits = []; end %% Grey case {'gray', 'grey'} % Greyscale [I limits] = grey(I, limits, reverseMap); %% Jet case 'jet' % Dark blue to dark red, through green [I limits] = jet_helper(I, limits, reverseMap); %% Hot case 'hot' % Black to white through red and yellow [I limits] = interp_map(I, limits, reverseMap, [0 0 0 3; 1 0 0 3; 1 1 0 2; 1 1 1 1]); %% Contrast case 'contrast' % A high contrast, full-colour map that goes from black to white % linearly when converted to greyscale, and passes through all the % corners of the RGB colour cube [I limits] = interp_map(I, limits, reverseMap, [0 0 0 114; 0 0 1 185; 1 0 0 114; 1 0 1 174;... 0 1 0 114; 0 1 1 185; 1 1 0 114; 1 1 1 0]); %% HSV case 'hsv' % Cycle through hues [I limits] = intensity(I, limits, reverseMap); % Intensity map I = hsv_helper(I); %% Bone case 'bone' % Greyscale with a blue tint [I limits] = interp_map(I, limits, reverseMap, [0 0 0 3; 21 21 29 3; 42 50 50 2; 64 64 64 1]/64); %% Colourcube case {'colorcube', 'colourcube'} % Psychedelic colourmap inspired by MATLAB's version [I limits] = intensity(I, limits, reverseMap); % Intensity map step = 4; I = I * (step * (1 - eps)); J = I * step; K = floor(J); I = cat(3, mod(K, step)/(step-1), J - floor(K), mod(floor(I), step)/(step-1)); %% Cool case 'cool' % Cyan through to magenta [I limits] = intensity(I, limits, reverseMap); % Intensity map I = [I, 1-I, ones(size(I))]; %% Spring case 'spring' % Magenta through to yellow [I limits] = intensity(I, limits, reverseMap); % Intensity map I = [ones(size(I)), I, 1-I]; %% Summer case 'summer' % Darkish green through to pale yellow [I limits] = intensity(I, limits, reverseMap); % Intensity map I = [I, 0.5+I*0.5, 0.4*ones(size(I))]; %% Autumn case 'autumn' % Red through to yellow [I limits] = intensity(I, limits, reverseMap); % Intensity map I = [ones(size(I)), I, zeros(size(I))]; %% Winter case 'winter' % Blue through to turquoise [I limits] = intensity(I, limits, reverseMap); % Intensity map I = [zeros(size(I)), I, 1-I*0.5]; %% Copper case 'copper' % Black through to copper [I limits] = intensity(I, limits, reverseMap); % Intensity map I = [I*(1/0.8), I*0.78, I*0.5]; I = min(max(reshape(I, numel(I), 1), 0), 1); % Truncate %% Pink case 'pink' % Greyscale with a pink tint [I limits] = intensity(I, limits, reverseMap); % Intensity map J = I * (2 / 3); I = [I, I-1/3, I-2/3]; I = reshape(max(min(I(:), 1/3), 0), [], 3); I = I + J(:,[1 1 1]); I = sqrt(I); %% Bled case 'bled' % Black to red, through blue [I limits] = bled(I, limits, reverseMap); %% Earth case 'earth' % High contrast, converts to linear scale in grey, strong % shades of green table = [0 0 0; 0 0.1104 0.0583; 0.1661 0.1540 0.0248; 0.1085 0.2848 0.1286;... 0.2643 0.3339 0.0939; 0.2653 0.4381 0.1808; 0.3178 0.5053 0.3239;... 0.4858 0.5380 0.3413; 0.6005 0.5748 0.4776; 0.5698 0.6803 0.6415;... 0.5639 0.7929 0.7040; 0.6700 0.8626 0.6931; 0.8552 0.8967 0.6585;... 1 0.9210 0.7803; 1 1 1]; [I limits] = interp_map(I, limits, reverseMap, table); %% Pinker case 'pinker' % High contrast, converts to linear scale in grey, strong % shades of pink table = [0 0 0; 0.0455 0.0635 0.1801; 0.2425 0.0873 0.1677;... 0.2089 0.2092 0.2546; 0.3111 0.2841 0.2274; 0.4785 0.3137 0.2624;... 0.5781 0.3580 0.3997; 0.5778 0.4510 0.5483; 0.5650 0.5682 0.6047;... 0.6803 0.6375 0.5722; 0.8454 0.6725 0.5855; 0.9801 0.7032 0.7007;... 1 0.7777 0.8915; 0.9645 0.8964 1; 1 1 1]; [I limits] = interp_map(I, limits, reverseMap, table); %% Pastel case 'pastel' % High contrast, converts to linear scale in grey, strong % pastel shades table = [0 0 0; 0.4709 0 0.018; 0 0.3557 0.6747; 0.8422 0.1356 0.8525; 0.4688 0.6753 0.3057; 1 0.6893 0.0934; 0.9035 1 0; 1 1 1]; [I limits] = interp_map(I, limits, reverseMap, table); %% Bright case 'bright' % High contrast, converts to linear scale in grey, strong % saturated shades table = [0 0 0; 0.3071 0.0107 0.3925; 0.007 0.289 1; 1 0.0832 0.7084; 1 0.4447 0.1001; 0.5776 0.8360 0.4458; 0.9035 1 0; 1 1 1]; [I limits] = interp_map(I, limits, reverseMap, table); %% Jet2 case 'jet2' % Like jet, but starts in black and goes to saturated red [I limits] = interp_map(I, limits, reverseMap, [0 0 0; 0.5 0 0.5; 0 0 0.9; 0 1 1; 0 1 0; 1 1 0; 1 0 0]); %% Hot2 case 'hot2' % Like hot, but equally spaced [I limits] = intensity(I, limits, reverseMap); % Intensity map I = I * 3; I = [I, I-1, I-2]; I = min(max(I(:), 0), 1); % Truncate %% Bone2 case 'bone2' % Like bone, but equally spaced [I limits] = intensity(I, limits, reverseMap); % Intensity map J = [I-2/3, I-1/3, I]; J = reshape(max(min(J(:), 1/3), 0), [], 3) * (2 / 5); I = I * (13 / 15); I = J + I(:,[1 1 1]); %% Unknown colourmap otherwise error('Colormap ''%s'' not recognised.', map); end return %% Display image function display_image(I, map, limits, reverseMap) % Clear the axes cla(gca, 'reset'); % Display the image - using image() is fast hIm = image(I); % Get handles to the figure and axes (now, as the axes may have % changed) hFig = gcf; hAx = gca; % Axes invisible and equal set(hFig, 'Units', 'pixels'); set(hAx, 'Visible', 'off', 'DataAspectRatio', [1 1 1], 'DrawMode', 'fast'); % Set data for a colorbar if ~isempty(limits) && limits(1) ~= limits(2) colBar = (0:255) * ((limits(2) - limits(1)) / 255) + limits(1); colBar = squeeze(sc(colBar, map, limits)); if reverseMap colBar = colBar(end:-1:1,:); end set(hFig, 'Colormap', colBar); set(hAx, 'CLim', limits); set(hIm, 'CDataMapping', 'scaled'); end % Only resize image if it is alone in the figure if numel(findobj(get(hFig, 'Children'), 'Type', 'axes')) > 1 return end % Could still be the first subplot - do another check axesPos = get(hAx, 'Position'); if isequal(axesPos, get(hFig, 'DefaultAxesPosition')) % Default position => not a subplot % Fill the window set(hAx, 'Units', 'normalized', 'Position', [0 0 1 1]); axesPos = [0 0 1 1]; end if ~isequal(axesPos, [0 0 1 1]) || strcmp(get(hFig, 'WindowStyle'), 'docked') % Figure not alone, or docked. Either way, don't resize. return end % Get the size of the monitor we're on figPosCur = get(hFig, 'Position'); MonSz = get(0, 'MonitorPositions'); MonOn = size(MonSz, 1); if MonOn > 1 figCenter = figPosCur(1:2) + figPosCur(3:4) / 2; figCenter = MonSz - repmat(figCenter, [MonOn 2]); MonOn = all(sign(figCenter) == repmat([-1 -1 1 1], [MonOn 1]), 2); MonOn(1) = MonOn(1) | ~any(MonOn); MonSz = MonSz(MonOn,:); end MonSz(3:4) = MonSz(3:4) - MonSz(1:2) + 1; % Check if the window is maximized % This is a hack which may only work on Windows! No matter, though. if isequal(MonSz([1 3]), figPosCur([1 3])) % Leave maximized return end % Compute the size to set the window MaxSz = MonSz(3:4) - [20 120]; ImSz = [size(I, 2) size(I, 1)]; RescaleFactor = min(MaxSz ./ ImSz); if RescaleFactor > 1 % Integer scale for enlarging, but don't make too big MaxSz = min(MaxSz, [1000 680]); RescaleFactor = max(floor(min(MaxSz ./ ImSz)), 1); end figPosNew = ceil(ImSz * RescaleFactor); % Don't move the figure if the size isn't changing if isequal(figPosCur(3:4), figPosNew) return end % Keep the centre of the figure stationary figPosNew = [max(1, floor(figPosCur(1:2)+(figPosCur(3:4)-figPosNew)/2)) figPosNew]; % Ensure the figure bar is in bounds figPosNew(1:2) = min(figPosNew(1:2), MonSz(1:2)+MonSz(3:4)-[6 101]-figPosNew(3:4)); set(hFig, 'Position', figPosNew); return %% Parse input variables function [map limits mask] = parse_inputs(I, inputs, y, x) % Check the first two arguments for the colormap and limits ninputs = numel(inputs); map = 'none'; limits = []; mask = 1; for a = 1:min(2, ninputs) if ischar(inputs{a}) && numel(inputs{a}) > 1 % Name of colormap map = inputs{a}; elseif isnumeric(inputs{a}) [p q r] = size(inputs{a}); if (p * q * r) == 2 % Limits limits = double(inputs{a}); elseif p > 1 && (q == 3 || q == 4) && r == 1 % Table-based colormap map = inputs{a}; else break; end else break; end mask = mask + 1; end % Check for following inputs if mask > ninputs mask = cell(2, 0); return end % Following inputs must either be colour/mask pairs, or a colour for NaNs if ninputs - mask == 0 mask = cell(2, 1); mask{1} = inputs{end}; mask{2} = ~all(isfinite(I), 3); elseif mod(ninputs-mask, 2) == 1 mask = reshape(inputs(mask:end), 2, []); else error('Error parsing inputs'); end % Go through pairs and generate for a = 1:size(mask, 2) % Generate any masks from functions if isa(mask{2,a}, 'function_handle') mask{2,a} = mask{2,a}(I); end if ~islogical(mask{2,a}) error('Mask is not a logical array'); end if ~isequal(size(mask{2,a}), [y x]) error('Mask does not match image size'); end if ischar(mask{1,a}) if numel(mask{1,a}) == 1 % Generate colours from MATLAB colour strings mask{1,a} = double(dec2bin(strfind('kbgcrmyw', mask{1,a})-1, 3)) - double('0'); else % Assume it's a colormap name mask{1,a} = sc(I, mask{1,a}); end end mask{1,a} = reshape(mask{1,a}, [], 3); if size(mask{1,a}, 1) ~= y*x && size(mask{1,a}, 1) ~= 1 error('Replacement color/image of unexpected dimensions'); end if size(mask{1,a}, 1) ~= 1 mask{1,a} = mask{1,a}(mask{2,a},:); end end return %% Grey function [I limits] = grey(I, limits, reverseMap) % Greyscale [I limits] = intensity(I, limits, reverseMap); I = I(:,[1 1 1]); return %% RGB2grey function [I limits] = rgb2grey(I, limits, reverseMap) % Compress RGB to greyscale if size(I, 2) == 3 I = I * [0.299; 0.587; 0.114]; end [I limits] = grey(I, limits, reverseMap); return %% RGB2YUV function [I limits] = rgb2yuv(I) % Convert RGB to YUV - not for displaying or saving to disk! if size(I, 2) ~= 3 error('rgb2yuv requires a 3 channel image'); end I = I * [0.299, -0.14713, 0.615; 0.587, -0.28886, -0.51498; 0.114, 0.436, -0.10001]; limits = []; % This colourmap doesn't have a valid colourbar return %% Phase helper function I = phase_helper(I, limits, n) I(:,1) = mod(I(:,1)/(2*pi), 1); I(:,2) = I(:,2) - limits(1); I(:,2) = I(:,2) * (n / (limits(2) - limits(1))); I(:,3) = n - I(:,2); I(:,[2 3]) = min(max(I(:,[2 3]), 0), 1); I = hsv2rgb(reshape(I, [], 1, 3)); return %% Jet helper function [I limits] = jet_helper(I, limits, reverseMap) % Dark blue to dark red, through green [I limits] = intensity(I, limits, reverseMap); I = I * 4; I = [I-3, I-2, I-1]; I = 1.5 - abs(I); I = reshape(min(max(I(:), 0), 1), size(I)); return %% HSV helper function I = hsv_helper(I) I = I * 6; I = abs([I-3, I-2, I-4]); I(:,1) = I(:,1) - 1; I(:,2:3) = 2 - I(:,2:3); I = reshape(min(max(I(:), 0), 1), size(I)); return %% Bled function [I limits] = bled(I, limits, reverseMap) % Black to red through blue [I limits] = intensity(I, limits, reverseMap); J = reshape(hsv_helper(I), [], 3); if exist('bsxfun', 'builtin') I = bsxfun(@times, I, J); else I = J .* I(:,[1 1 1]); end return %% Normalize function [I limits] = normalize(I, limits) if isempty(limits) limits = isfinite(I); if ~any(reshape(limits, numel(limits), 1)) % All NaNs, Infs or -Infs I = double(I > 0); limits = [0 1]; return end limits = [min(I(limits)) max(I(limits))]; I = I - limits(1); if limits(2) ~= limits(1) I = I * (1 / (limits(2) - limits(1))); end else I = I - limits(1); if limits(2) ~= limits(1) I = I * (1 / (limits(2) - limits(1))); end I = reshape(min(max(reshape(I, numel(I), 1), 0), 1), size(I)); end return %% Intensity maps function [I limits] = intensity(I, limits, reverseMap) % Squash to 1d using L2 norm if size(I, 2) > 1 I = sqrt(sum(I .^ 2, 2)); end % Determine and scale to limits [I limits] = normalize(I, limits); if reverseMap % Invert after everything I = 1 - I; end return %% Interpolate table-based map function [I limits] = interp_map(I, limits, reverseMap, map) % Convert to intensity [I limits] = intensity(I, limits, reverseMap); % Compute indices and offsets if size(map, 2) == 4 bins = map(1:end-1,4); cbins = cumsum(bins); bins = bins ./ cbins(end); cbins = cbins(1:end-1) ./ cbins(end); if exist('bsxfun', 'builtin') ind = bsxfun(@gt, I(:)', cbins(:)); else ind = repmat(I(:)', [numel(cbins) 1]) > repmat(cbins(:), [1 numel(I)]); end ind = min(sum(ind), size(map, 1) - 2) + 1; bins = 1 ./ bins; cbins = [0; cbins]; I = (I - cbins(ind)) .* bins(ind); else n = size(map, 1) - 1; I = I(:) * n; ind = min(floor(I), n-1); I = I - ind; ind = ind + 1; end if exist('bsxfun', 'builtin') I = bsxfun(@times, map(ind,1:3), 1-I) + bsxfun(@times, map(ind+1,1:3), I); else I = map(ind,1:3) .* repmat(1-I, [1 3]) + map(ind+1,1:3) .* repmat(I, [1 3]); end return %% Index images function [J limits num_vals] = index_im(I) % Returns an index image if size(I, 2) ~= 1 error('Index maps only work on single channel images'); end J = round(I); rescaled = any(abs(I - J) > 0.01); if rescaled % Appears not to be an index image. Rescale over 256 indices m = min(I); m = m * (1 - sign(m) * eps); I = I - m; I = I * (256 / max(I(:))); J = ceil(I); num_vals = 256; elseif nargout > 2 % Output the number of values J = J - (min(J) - 1); num_vals = max(J); end % These colourmaps don't have valid colourbars limits = []; return %% Calculate principle components function I = calc_prin_comps(I, numComps) if nargin < 2 numComps = size(I, 2); end % Do SVD [I S] = svd(I, 0); % Calculate projection of data onto components S = diag(S(1:numComps,1:numComps))'; if exist('bsxfun', 'builtin') I = bsxfun(@times, I(:,1:numComps), S); else I = I(:,1:numComps) .* S(ones(size(I, 1), 1, 'uint8'),:); end return %% Demo function to show capabilities of sc function demo %% Demo gray & lack of border figure; fig = gcf; Z = peaks(256); sc(Z); display_text([... ' Lets take a standard, MATLAB, real-valued function:\n\n peaks(256)\n\n'... ' Calling:\n\n figure\n Z = peaks(256);\n sc(Z)\n\n'... ' gives (see figure). SC automatically scales intensity to fill the\n'... ' truecolor range of [0 1].\n\n'... ' If your figure isn''t docked, then the image will have no border, and\n'... ' will be magnified by an integer factor (in this case, 2) so that the\n'... ' image is a reasonable size.']); %% Demo colour image display figure(fig); clf; load mandrill; mandrill = ind2rgb(X, map); sc(mandrill); display_text([... ' That wasn''t so interesting. The default colormap is ''none'', which\n'... ' produces RGB images given a 3-channel input image, otherwise it produces\n'... ' a grayscale image. So calling:\n\n load mandrill\n'... ' mandrill = ind2rgb(X, map);\n sc(mandrill)\n\n gives (see figure).']); %% Demo discretization figure(fig); clf; subplot(121); sc(Z, 'jet'); label(Z, 'sc(Z, ''jet'')'); subplot(122); imagesc(Z); axis image off; colormap(jet(64)); % Fix the fact we change the default depth label(Z, 'imagesc(Z); axis image off; colormap(''jet'');'); display_text([... ' However, if we want to display intensity images in color we can use any\n'... ' of the MATLAB colormaps implemented (most of them) to give truecolor\n'... ' images. For example, to use ''jet'' simply call:\n\n'... ' sc(Z, ''jet'')\n\n'... ' The MATLAB alternative, shown on the right, is:\n\n'... ' imagesc(Z)\n axis equal off\n colormap(jet)\n\n'... ' which generates noticeable discretization artifacts.']); %% Demo intensity colourmaps figure(fig); clf; subplot(221); sc(Z, 'hsv'); label(Z, 'sc(Z, ''hsv'')'); subplot(222); sc(Z, 'colorcube'); label(Z, 'sc(Z, ''colorcube'')'); subplot(223); sc(Z, 'contrast'); label(Z, 'sc(Z, ''contrast'')'); subplot(224); sc(Z-round(Z), 'diff'); label(Z, 'sc(Z-round(Z), ''diff'')'); display_text([... ' There are several other intensity colormaps to choose from. Calling:\n\n'... ' help sc\n\n'... ' will give you a list of them. Here are several others demonstrated.']); %% Demo saturation limits & colourmap reversal figure(fig); clf; subplot(121); sc(Z, [0 max(Z(:))], '-hot'); label(Z, 'sc(Z, [0 max(Z(:))], ''-hot'')'); subplot(122); sc(mandrill, [-0.5 0.5]); label(mandrill, 'sc(mandrill, [-0.5 0.5])'); display_text([... ' SC can also rescale intensity, given an upper and lower bound provided\n'... ' by the user, and invert most colormaps simply by prefixing a ''-'' to the\n'... ' colormap name. For example:\n\n'... ' sc(Z, [0 max(Z(:))], ''-hot'');\n'... ' sc(mandrill, [-0.5 0.5]);\n\n'... ' Note that the order of the colormap and limit arguments are\n'... ' interchangable.']); %% Demo prob load gatlin; gatlin = X; figure(fig); clf; im = cat(3, abs(Z)', gatlin(1:256,end-255:end)); sc(im, 'prob'); label(im, 'sc(cat(3, prob, gatlin), ''prob'')'); display_text([... ' SC outputs the recolored data as a truecolor RGB image. This makes it\n'... ' easy to combine colormaps, either arithmetically, or by masking regions.\n'... ' For example, we could combine an image and a probability map\n'... ' arithmetically as follows:\n\n'... ' load gatlin\n'... ' gatlin = X(1:256,end-255:end);\n'... ' prob = abs(Z)'';\n'... ' im = sc(prob, ''hsv'') .* sc(prob, ''gray'') + sc(gatlin, ''rgb2gray'');\n'... ' sc(im, [-0.1 1.3]);\n\n'... ' In fact, that particular colormap has already been implemented in SC.\n'... ' Simply call:\n\n'... ' sc(cat(3, prob, gatlin), ''prob'');']); %% Demo colorbar colorbar; display_text([... ' SC also makes possible the generation of a colorbar in the normal way, \n'... ' with all the colours and data values correct. Simply call:\n\n'... ' colorbar\n\n'... ' The colorbar doesn''t work with all colormaps, but when it does,\n'... ' inverting the colormap (using ''-map'') maintains the integrity of the\n'... ' colorbar (i.e. it works correctly) - unlike if you invert the input data.']); %% Demo combine by masking figure(fig); clf; sc(Z, [0 max(Z(:))], '-hot', sc(Z-round(Z), 'diff'), Z < 0); display_text([... ' It''s just as easy to combine generated images by masking too. Here''s an\n'... ' example:\n\n'... ' im = cat(4, sc(Z, [0 max(Z(:))], ''-hot''), sc(Z-round(Z), ''diff''));\n'... ' mask = repmat(Z < 0, [1 1 3]);\n'... ' mask = cat(4, mask, ~mask);\n'... ' im = sum(im .* mask, 4);\n'... ' sc(im)\n\n'... ' In fact, SC can also do this for you, by adding image/colormap and mask\n'... ' pairs to the end of the argument list, as follows:\n\n'... ' sc(Z, [0 max(Z(:))], ''-hot'', sc(Z-round(Z), ''diff''), Z < 0);\n\n'... ' A benefit of the latter approach is that you can still display a\n'... ' colorbar for the first colormap.']); %% Demo texture map figure(fig); clf; surf(Z, sc(Z, 'contrast'), 'edgecolor', 'none'); display_text([... ' Other benefits of SC outputting the image as an array are that the image\n'... ' can be saved straight to disk using imwrite() (if you have the image\n'... ' processing toolbox), or can be used to texture map a surface, thus:\n\n'... ' tex = sc(Z, ''contrast'');\n'... ' surf(Z, tex, ''edgecolor'', ''none'');']); %% Demo compress load mri; mri = D; close(fig); % Only way to get round loss of focus (bug?) figure(fig); clf; sc(squeeze(mri(:,:,:,1:6)), 'compress'); display_text([... ' For images with more than 3 channels, SC can compress these images to RGB\n'... ' while maintaining the maximum amount of variance in the data. For\n'... ' example, this 6 channel image:\n\n'... ' load mri\n mri = D;\n sc(squeeze(mri(:,:,:,1:6), ''compress'')']); %% Demo multiple images figure(fig); clf; im = sc(mri, 'bone'); for a = 1:12 subplot(3, 4, a); sc(im(:,:,:,a)); end display_text([... ' SC can process multiple images for export when passed in as a 4d array.\n'... ' For example:\n\n'... ' im = sc(mri, ''bone'')\n'... ' for a = 1:12\n'... ' subplot(3, 4, a);\n'... ' sc(im(:,:,:,a));\n'... ' end']); %% Demo user defined colormap figure(fig); clf; sc(abs(Z), rand(10, 3)); colorbar; display_text([... ' Finally, SC can use user defined colormaps to display indexed images.\n'... ' These can be defined as a linear colormap. For example:\n\n'... ' sc(abs(Z), rand(10, 3))\n colorbar;\n\n'... ' Note that the colormap is automatically linearly interpolated.']); %% Demo non-linear user defined colormap figure(fig); clf; sc(abs(Z), [rand(10, 3) exp((1:10)/2)']); colorbar; display_text([... ' Non-linear colormaps can also be defined by the user, by including the\n'... ' relative distance between the given colormap points on the colormap\n'... ' scale in the fourth column of the colormap matrix. For example:\n\n'... ' sc(abs(Z), [rand(10, 3) exp((1:10)/2)''])\n colorbar;\n\n'... ' Note that the colormap is still linearly interpolated between points.']); clc; fprintf('End of demo.\n'); return %% Some helper functions for the demo function display_text(str) clc; fprintf([str '\n\n']); fprintf('Press a key to go on.\n'); figure(gcf); waitforbuttonpress; return function label(im, str) text(size(im, 2)/2, size(im, 1)+12, str,... 'Interpreter', 'none', 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle'); return
github
lacerbi/psybayes-master
psybayes.m
.m
psybayes-master/psybayes.m
13,615
utf_8
e1b407be358f4d890c3e46384174af9e
function [xnext,psy,output] = psybayes(psy,method,vars,xi,yi) %PSYBAYES Bayesian adaptive estimation of psychometric function. % % PSYBAYES implements Kontsevich and Tyler's (1999) Bayesian adaptive % method PSI for estimation of parameters of the psychometric function via % maximization of information gain (including lapse; see Prins 2012). % PSYBAYES also supports the marginal-PSI method by Prins (2013). % % See PSYTEST for documentation and a working usage example. % % References: % Kontsevich, L. L., & Tyler, C. W. (1999). "Bayesian adaptive estimation % of psychometric slope and threshold". Vision Research, 39(16), 2729-2737. % % Prins, N. (2012). "The adaptive psi method and the lapse rate". Journal % of Vision, 12(9), 322-322. (link) % % Prins, N. (2013). "The psi-marginal adaptive method: How to give nuisance % parameters the attention they deserve (no more, no less)". Journal of % Vision, 13(7), 3-3. % % See also PSYBAYES_PLOT, PSYTEST. % Copyright (C) 2016 Luigi Acerbi % % This software is distributed under the GNU General Public License % (version 3 or later); please refer to the file LICENSE.txt, included with % the software, for details. % Author: Luigi Acerbi % Email: [email protected] % Version: 05/Oct/2016 if nargin < 1; psy = []; end if nargin < 2; method = []; end if nargin < 3; vars = []; end if nargin < 4; xi = []; yi = []; end persistent firstcall; xnext = []; if isempty(firstcall) firstcall = 0; % Add all subdirectories to MATLAB path [path,~,~] = fileparts(mfilename('fullpath')); addpath(genpath(path)); end % Default method is expected entropy minimization if isempty(method); method = 'ent'; end % Marginal-PSI method, select parameters of interest if isempty(vars) switch lower(method) case 'ent'; vars = [1 1 1]; case 'var'; vars = [1 0 0]; otherwise error('Unknown optimization method.'); end end if numel(vars) ~= 3; error('VARS need to be a 3-element array for MU, SIGMA and LAMBDA.'); end %% First call, initialize everything if isempty(psy) || ~isfield(psy,'post') % Call initialization function psyinfo = psy; [psy,Nfuns] = psyinit(psyinfo); % Enforce symmetry of test stimuli? (symmetric wrt left/right of the % mean of the psychometric curve) if isfield(psyinfo,'forcesymmetry') && ~isempty(psyinfo.forcesymmetry) psy.forcesymmetry = psyinfo.forcesymmetry; else psy.forcesymmetry = 0; end else % Reset psychometric function [psy,Nfuns] = psyfunset(psy); end % Select psychometric function if ~iscell(psy.psychofun) psychofun{1} = str2func(psy.psychofun); else for k = 1:Nfuns psychofun{k} = str2func(psy.psychofun{k}); end end % Precompute psychometric function if isempty(psy.f) for k = 1:Nfuns psy.f{k} = psychofun{k}(psy.x,psy.mu,psy.sigma,psy.lambda,psy.gamma); % Check if last stimulus is easy stimulus (by default Inf) if psy.x(end) == Inf if isempty(psy.gamma) temp(1,1,:) = 1-psy.lambda/2; else temp(1,1,:) = 1-psy.lambda*(1-psy.gamma); end psy.f{k}(:,:,:,end) = repmat(temp,[numel(psy.mu),numel(psy.logsigma),1]); end end end % Update log posterior given the new data points XI, YI if ~isempty(xi) && ~isempty(yi) for k = 1:Nfuns for i = 1:numel(xi) % Maximum precision stimulus if isinf(xi(i)) if isempty(psy.gamma) if yi(i) == 1 like = 1-psy.lambda/2; elseif yi(i) == 0 like = psy.lambda/2; end else if yi(i) == 1 like = 1-psy.lambda*(1-psy.gamma); elseif yi(i) == 0 like = psy.lambda*(1-psy.gamma); end end else if yi(i) == 1 like = psychofun{k}(xi(i),psy.mu,psy.sigma,psy.lambda,psy.gamma); elseif yi(i) == 0 like = 1 - psychofun{k}(xi(i),psy.mu,psy.sigma,psy.lambda,psy.gamma); end end % Save unnormalized log posterior psy.logupost{k} = bsxfun(@plus, psy.logupost{k}, log(like)); % Compute normalized posterior psy.post{k} = exp(psy.logupost{k} - max(psy.logupost{k}(:))); psy.post{k} = psy.post{k}./sum(psy.post{k}(:)); end end psy.ntrial = psy.ntrial + numel(xi); psy.data = [psy.data; xi(:) yi(:)]; % Update refractory times list psy.reflist = max(psy.reflist - 1, 0); if psy.reftime > 0 && isfinite(xi) idx = (psy.x <= xi + psy.refradius) & (psy.x >= xi - psy.refradius); wtrials(1,1,1,:) = geornd(1/(1+psy.reftime)*ones(1,sum(idx))); psy.reflist(idx) = max(wtrials, psy.reflist(idx)); end end % Compute posterior over psychometric functions if Nfuns > 1 logp = zeros(1,Nfuns); for k = 1:Nfuns logp(k) = logsumexp(psy.logupost{k}(:)); end psy.psychopost = exp(logp - max(logp)); psy.psychopost = psy.psychopost ./ sum(psy.psychopost); else psy.psychopost = 1; end % Compute mean of the posterior of mu postmu = zeros(numel(psy.mu),Nfuns); for k = 1:Nfuns postmu(:,k) = sum(sum(psy.post{k},2),3); end emu = sum(sum(bsxfun(@times, bsxfun(@times, psy.psychopost, postmu), psy.mu),2),1); % Randomly remove half of the x if psy.forcesymmetry if rand() < 0.5; xindex = psy.x < emu; else xindex = psy.x >= emu; end else xindex = true(size(psy.x)); end % Consider only available stimuli xindex = xindex & (psy.reflist == 0); % No stimuli are available, free some stimuli and reset refractory list if all(xindex == 0) xindex(psy.reflist == min(psy.reflist)) = 1; psy.reflist = zeros(size(psy.x)); end % Compute sampling point X that minimizes expected chosen criterion if nargin > 0 Nx = numel(psy.x); r1 = zeros(1,1,1,Nx,Nfuns); post1 = zeros([size(psy.post{1}),Nx,Nfuns]); post0 = zeros([size(psy.post{1}),Nx,Nfuns]); if Nfuns > 1 u1 = zeros(1,1,1,Nx,Nfuns); u0 = zeros(1,1,1,Nx,Nfuns); end for k = 1:Nfuns if Nfuns > 1 % Compute posteriors and unnormalized model evidence at next step for R=1 and R=0 % [post1(:,:,:,:,k),post0(:,:,:,:,k),r1(1,1,1,:,k),u1(1,1,1,:,k),u0(1,1,1,:,k)] = nextposterior(psy.f{k}(:,:,:,xindex),psy.post{k},psy.logupost{k}); [post1(:,:,:,:,k),post0(:,:,:,:,k),r1(1,1,1,:,k),u1(1,1,1,:,k),u0(1,1,1,:,k)] = nextposterior(psy.f{k}(:,:,:,:),psy.post{k},psy.logupost{k}); else % Compute posteriors at next step for R=1 and R=0 %[post1(:,:,:,:,k),post0(:,:,:,:,k),r1(1,1,1,:,k)] = nextposterior(psy.f{k}(:,:,:,xindex),psy.post{k}); [post1(:,:,:,:,k),post0(:,:,:,:,k),r1(1,1,1,:,k)] = nextposterior(psy.f{k}(:,:,:,:),psy.post{k}); end end % Marginalize over unrequested variables index = find(~vars); for iTheta = index if iTheta ==3 && ndims(post1)==3 % BK: Special case: lambda is not being estimated (vars(3) ==0), % but then the post1 will not have this dimension % because it gets removed automatically as the trailing % dimension in psy.post. So we cannot marginalize here over 3 % because that now contains the x parameter. else post1 = sum(post1,iTheta); post0 = sum(post0,iTheta); end end if Nfuns > 1 u0 = exp(bsxfun(@minus, u0, max(u0,[],5))); u0 = bsxfun(@rdivide,u0,sum(u0,5)); u1 = exp(bsxfun(@minus, u1, max(u1,[],5))); u1 = bsxfun(@rdivide,u1,sum(u1,5)); post1 = bsxfun(@times, u1, post1); post0 = bsxfun(@times, u0, post0); w(1,1,1,1,:) = psy.psychopost; r1 = sum(bsxfun(@times, w, r1), 5); end switch lower(method) case {'var','variance'} post0 = squeeze(sum(post0, 5)); post1 = squeeze(sum(post1, 5)); index = find(vars,1); switch index case 1; qq = psy.mu(:); case 2; qq = psy.logsigma(:); case 3; qq = psy.lambda(:); end mean1 = sum(bsxfun(@times,post1,qq),1); mean0 = sum(bsxfun(@times,post0,qq),1); var1 = sum(bsxfun(@times,post1,qq.^2),1) - mean1.^2; var0 = sum(bsxfun(@times,post0,qq.^2),1) - mean0.^2; target = r1(:).*var1(:) + (1-r1(:)).*var0(:); case {'ent','entropy'} temp1 = -post1.*log(post1); temp0 = -post0.*log(post0); temp1(~isfinite(temp1)) = 0; temp0(~isfinite(temp0)) = 0; H1 = temp1; H0 = temp0; for iTheta = find(vars) H1 = sum(H1,iTheta); H0 = sum(H0,iTheta); end if Nfuns > 1 H1 = sum(H1,5); H0 = sum(H0,5); end target = r1(:).*H1(:) + (1-r1(:)).*H0(:); case {'proj','projection'} Nsteps = 4; max(r1) anchors = linspace(0.5, max(r1), Nsteps+1); anchors = anchors(2:end); target = zeros(Nx,1); for jj = 1:numel(anchors) for k = 1:Nfuns [~,idx(:,:,:,1,k)] = min(abs(psy.f{k}-anchors(jj)),[],4); end mean1 = sum(sum(sum(sum(bsxfun(@times,post1,idx),1),2),3),5); mean0 = sum(sum(sum(sum(bsxfun(@times,post0,idx),1),2),3),5); var1 = sum(sum(sum(sum(bsxfun(@times,post1,idx.^2),1),2),3),5) - mean1.^2; var0 = sum(sum(sum(sum(bsxfun(@times,post0,idx.^2),1),2),3),5) - mean0.^2; target = target + r1(:).*var1(:) + (1-r1(:)).*var0(:); end case {'model'} H1 = -u1.*log(u1); H0 = -u0.*log(u0); H1(~isfinite(H1)) = 0; H0(~isfinite(H0)) = 0; H1 = sum(H1,5); H0 = sum(H0,5); target = r1(:).*H1(:) + (1-r1(:)).*H0(:); otherwise error('Unknown method. Allowed methods are ''var'' and ''ent'' for, respectively, predicted variance and predicted entropy minimization.'); end % Store target for plotting psy.target = target(:)'; % Location X that minimizes target metric [~,index] = min(target(xindex)); xred = psy.x(xindex); xnext = xred(index); psy.xnext = xnext; end % Compute parameter estimates if nargout > 2 w = psy.psychopost; % Compute mean and variance of the estimate of MU postmu = marginalpost(psy.post,w,[2,3]); postmu = postmu./sum(postmu,1); emu = sum(postmu.*psy.mu,1); estd = sqrt(sum(postmu.*psy.mu.^2,1) - emu.^2); output.mu.mean = emu; output.mu.std = estd; % Compute mean and variance of the estimate of LOGSIGMA and SIGMA postlogsigma = marginalpost(psy.post,w,[1,3]); postlogsigma = postlogsigma./sum(postlogsigma,2); emu = sum(postlogsigma.*psy.logsigma,2); estd = sqrt(sum(postlogsigma.*psy.logsigma.^2,2) - emu.^2); output.logsigma.mean = emu; output.logsigma.std = estd; postsigma = postlogsigma./psy.sigma; postsigma = postsigma./sum(postsigma,2); emu = sum(postsigma.*psy.sigma,2); estd = sqrt(sum(postsigma.*psy.sigma.^2,2) - emu.^2); output.sigma.mean = emu; output.sigma.std = estd; % Compute mean and variance of the estimate of LAMBDA postlambda = marginalpost(psy.post,w,[1,2]); postlambda = postlambda./sum(postlambda,3); emu = sum(postlambda.*psy.lambda,3); estd = sqrt(sum(postlambda.*psy.lambda.^2,3) - emu.^2); output.lambda.mean = emu; output.lambda.std = estd; end % Only one argument assumes that this is the final call if nargin < 2 psy.f = []; % Empty some memory psy.reflist = zeros(size(psy.x)); % Reset refractory times list end end %-------------------------------------------------------------------------- function [post1,post0,r1,u1,u0] = nextposterior(f,post,logupost) %NEXTPOSTERIOR Compute posteriors on next trial depending on possible outcomes mf = 1-f; post1 = bsxfun(@times, post, f); r1 = sum(sum(sum(post1,1),2),3); post0 = bsxfun(@times, post, mf); post1 = bsxfun(@rdivide, post1, r1); post0 = bsxfun(@rdivide, post0, sum(sum(sum(post0,1),2),3)); if nargin > 2 && nargout > 3 logupost1 = bsxfun(@plus, logupost, log(f)); logupost0 = bsxfun(@plus, logupost, log(mf)); z0 = max(logupost0(:)); u0 = log(sum(sum(sum(exp(logupost0 - z0),1),2),3)); z1 = max(logupost1(:)); u1 = log(sum(sum(sum(exp(logupost1 - z1),1),2),3)); end end %-------------------------------------------------------------------------- function r = geornd(p) %GEORND Random arrays from the geometric distribution. p(p <= 0 | p > 1) = NaN; % Return NaN for illegal parameter values r = ceil(abs(log(rand(size(p))) ./ log(1 - p)) - 1); % == geoinv(u,p) r(r < 0) = 0; % Force a zero when p==1, instead of -1 end
github
lacerbi/psybayes-master
psybayes_joint.m
.m
psybayes-master/psybayes_joint.m
16,283
utf_8
fe389c953ab293ff15d881ee2ef89326
function [xnext,psy,output] = psybayes_joint(psy,method,vars,xi,yi,ci) %PSYBAYES_JOINT Joint Bayesian adaptive estimation of psychometric functions. % % PSYBAYES implements Kontsevich and Tyler's (1999) Bayesian adaptive % method PSI for estimation of parameters of the psychometric function via % maximization of information gain (including lapse; see Prins 2012). % PSYBAYES also supports the marginal-PSI method by Prins (2013). % % See PSYTEST for documentation and a working usage example. % % References: % Kontsevich, L. L., & Tyler, C. W. (1999). "Bayesian adaptive estimation % of psychometric slope and threshold". Vision Research, 39(16), 2729-2737. % % Prins, N. (2012). "The adaptive psi method and the lapse rate". Journal % of Vision, 12(9), 322-322. (link) % % Prins, N. (2013). "The psi-marginal adaptive method: How to give nuisance % parameters the attention they deserve (no more, no less)". Journal of % Vision, 13(7), 3-3. % % See also PSYBAYES_PLOT, PSYTEST. % Copyright (C) 2016 Luigi Acerbi % % This software is distributed under the GNU General Public License % (version 3 or later); please refer to the file LICENSE.txt, included with % the software, for details. % Author: Luigi Acerbi % Email: [email protected] % Version: 05/Oct/2016 if nargin < 1; psy = []; end if nargin < 2; method = []; end if nargin < 3; vars = []; end if nargin < 4; xi = []; yi = []; end if nargin < 5; ci = []; end persistent firstcall; xnext = []; if isempty(firstcall) firstcall = 0; % Add all subdirectories to MATLAB path [path,~,~] = fileparts(mfilename('fullpath')); addpath(genpath(path)); end % Default method is expected entropy minimization if isempty(method); method = 'ent'; end % Marginal-PSI method, select parameters of interest if isempty(vars) switch lower(method) case 'ent'; vars = [1 1 1]; case 'var'; vars = [1 0 0]; otherwise error('Unknown optimization method.'); end end if numel(vars) ~= 3; error('VARS need to be a 3-element array for MU, SIGMA and LAMBDA.'); end %% Initialization of PSY structures % Empty struct, a single psychometric function if isempty(psy); psy = {[]}; end % PSY can be NCND, number of experimental conditions if isnumeric(psy) && isscalar(psy) psy = cell(1,psy); end Ncnd = numel(psy); % Number of experimental conditions sharedlambda = Ncnd > 1; % If fitting multiple conditions, assume lapse rate is shared % Number of psychometric curves Nfuns = zeros(1,Ncnd); for c = 1:Ncnd if isempty(psy{c}) || ~isfield(psy{c},'post') % Call initialization function psyinfo = psy{c}; [psy{c},Nfuns(c)] = psyinit(psyinfo,Ncnd); % Enforce symmetry of test stimuli? (symmetric wrt left/right of the % mean of the psychometric curve) if isfield(psyinfo,'forcesymmetry') && ~isempty(psyinfo.forcesymmetry) psy{c}.forcesymmetry = psyinfo.forcesymmetry; else psy{c}.forcesymmetry = 0; end else % Reset psychometric function [psy{c},Nfuns(c)] = psyfunset(psy{c}); end end if ~all(Nfuns == Nfuns(1)) error('All conditions should have the same number of psychometric curves.'); end Nfuns = Nfuns(1); if Ncnd > 1 && Nfuns > 1 error('For the moment joint psychometric curve fitting only supports a single psychometric curve model.'); end % Initialize psychometric functions in each condition for c = 1:Ncnd % Convert psychometric function to function handle if ~iscell(psy{c}.psychofun) psychofun{c}{1} = str2func(psy{c}.psychofun); else for k = 1:Nfuns psychofun{c}{k} = str2func(psy{c}.psychofun{k}); end end % Precompute psychometric function if isempty(psy{c}.f) for k = 1:Nfuns psy{c}.f{k} = psychofun{c}{k}(psy{c}.x,psy{c}.mu,psy{c}.sigma,psy{c}.lambda,psy{c}.gamma); % Check if last stimulus is easy stimulus (by default Inf) if psy{c}.x(end) == Inf if isempty(psy{c}.gamma) temp(1,1,:) = 1-psy{c}.lambda/2; else temp(1,1,:) = 1-psy{c}.lambda*(1-psy{c}.gamma); end psy{c}.f{k}(:,:,:,end) = repmat(temp,[numel(psy{c}.mu),numel(psy{c}.logsigma),1]); end end end end % Update log posterior given the new data points XI, YI if ~isempty(xi) && ~isempty(yi) if isempty(ci) && Ncnd == 1 ci = 1; elseif isempty(ci) error('Current condition index CI not specified.'); elseif ~isscalar(ci) error('Current condition index needs to be a scalar.'); end for k = 1:Nfuns for i = 1:numel(xi) cii = ci; % Maximum precision stimulus if isinf(xi(i)) if isempty(psy{cii}.gamma) if yi(i) == 1 like = 1-psy{cii}.lambda/2; elseif yi(i) == 0 like = psy{cii}.lambda/2; end else if yi(i) == 1 like = 1-psy{cii}.lambda*(1-psy{cii}.gamma); elseif yi(i) == 0 like = psy{cii}.lambda*(1-psy{cii}.gamma); end end else if yi(i) == 1 like = psychofun{cii}{k}(xi(i),psy{cii}.mu,psy{cii}.sigma,psy{cii}.lambda,psy{cii}.gamma); elseif yi(i) == 0 like = 1 - psychofun{cii}{k}(xi(i),psy{cii}.mu,psy{cii}.sigma,psy{cii}.lambda,psy{cii}.gamma); end end % Save unnormalized log posterior psy{cii}.logupost{k} = bsxfun(@plus, psy{cii}.logupost{k}, log(like)); % Compute posterior over lambda for this condition temp = psy{cii}.logupost{k}; temp = exp(temp - max(temp(:))); psy{cii}.postlambda{k} = sum(sum(temp,1),2) / sum(temp(:)); % Compute joint posterior over lambda if sharedlambda postlambda_joint{k} = ones(size(psy{cii}.postlambda{k})); for c = 1:Ncnd postlambda_joint{k} = postlambda_joint{k} .* psy{c}.postlambda{k}; end postlambda_joint{k} = postlambda_joint{k} / sum(postlambda_joint{k}); end % Compute normalized posterior temp = exp(psy{cii}.logupost{k} - max(psy{cii}.logupost{k}(:))); if sharedlambda temp = bsxfun(@times, temp, postlambda_joint{k} ./ psy{cii}.postlambda{k}); end psy{cii}.post{k} = temp./sum(temp(:)); end end % Update data for i = 1:numel(xi) cii = ci; psy{cii}.ntrial = psy{cii}.ntrial + 1; psy{cii}.data = [psy{cii}.data; xi(i) yi(i)]; end % Update refractory times list for each presented stimulus for i = 1:numel(xi) cii = ci; psy{cii}.reflist = max(psy{cii}.reflist - 1, 0); if psy{cii}.reftime > 0 && isfinite(xi(i)) idx = (psy{cii}.x <= xi(i) + psy{cii}.refradius) & (psy{cii}.x >= xi(i) - psy{cii}.refradius); wtrials(1,1,1,:) = geornd(1/(1+psy{cii}.reftime)*ones(1,sum(idx))); psy{cii}.reflist(idx) = max(wtrials, psy{cii}.reflist(idx)); end end end % Compute posterior over psychometric functions for c = 1:Ncnd if Nfuns > 1 logp = zeros(1,Nfuns); for k = 1:Nfuns logp(k) = logsumexp(psy{c}.logupost{k}(:)); end % This is not correct for shared lambda psy{c}.psychopost = exp(logp - max(logp)); psy{c}.psychopost = psy{c}.psychopost ./ sum(psy{c}.psychopost); else psy{c}.psychopost = 1; end end % Only one argument assumes that this is the final call if nargin < 2 for c = 1:Ncnd psy{c}.f = []; % Empty some memory psy{c}.reflist = zeros(size(psy{c}.x)); % Reset refractory times list end return; end % Compute mean of the posterior of mu for the current condition postmu = zeros(numel(psy{ci}.mu),Nfuns); for k = 1:Nfuns postmu(:,k) = sum(sum(psy{ci}.post{k},2),3); end emu = sum(sum(bsxfun(@times, bsxfun(@times, psy{ci}.psychopost, postmu), psy{ci}.mu),2),1); % Randomly remove half of the x if psy{ci}.forcesymmetry if rand() < 0.5; xindex = psy{ci}.x < emu; else xindex = psy{ci}.x >= emu; end else xindex = true(size(psy{ci}.x)); end % Consider only available stimuli xindex = xindex & (psy{ci}.reflist == 0); % No stimuli are available, free some stimuli and reset refractory list if all(xindex == 0) xindex(psy{ci}.reflist == min(psy{ci}.reflist)) = 1; psy{ci}.reflist = zeros(size(psy{ci}.x)); end % Compute sampling point X that minimizes expected chosen criterion if nargin > 0 Nx = numel(psy{ci}.x); r1 = zeros(1,1,1,Nx,Nfuns); post1 = zeros([size(psy{ci}.post{1}),Nx,Nfuns]); post0 = zeros([size(psy{ci}.post{1}),Nx,Nfuns]); if Nfuns > 1 u1 = zeros(1,1,1,Nx,Nfuns); u0 = zeros(1,1,1,Nx,Nfuns); end for k = 1:Nfuns if Nfuns > 1 % Compute posteriors and unnormalized model evidence at next step for R=1 and R=0 % [post1(:,:,:,:,k),post0(:,:,:,:,k),r1(1,1,1,:,k),u1(1,1,1,:,k),u0(1,1,1,:,k)] = nextposterior(psy.f{k}(:,:,:,xindex),psy.post{k},psy.logupost{k}); % This is not completely correct for shared lapse rate [post1(:,:,:,:,k),post0(:,:,:,:,k),r1(1,1,1,:,k),u1(1,1,1,:,k),u0(1,1,1,:,k)] = nextposterior(psy{ci}.f{k}(:,:,:,:),psy{ci}.post{k},psy{ci}.logupost{k}); else % Compute posteriors at next step for R=1 and R=0 %[post1(:,:,:,:,k),post0(:,:,:,:,k),r1(1,1,1,:,k)] = nextposterior(psy.f{k}(:,:,:,xindex),psy.post{k}); [post1(:,:,:,:,k),post0(:,:,:,:,k),r1(1,1,1,:,k)] = nextposterior(psy{ci}.f{k}(:,:,:,:),psy{ci}.post{k}); end end % Marginalize over unrequested variables index = find(~vars); for iTheta = index post1 = sum(post1,iTheta); post0 = sum(post0,iTheta); end if Nfuns > 1 u0 = exp(bsxfun(@minus, u0, max(u0,[],5))); u0 = bsxfun(@rdivide,u0,sum(u0,5)); u1 = exp(bsxfun(@minus, u1, max(u1,[],5))); u1 = bsxfun(@rdivide,u1,sum(u1,5)); post1 = bsxfun(@times, u1, post1); post0 = bsxfun(@times, u0, post0); w(1,1,1,1,:) = psy{ci}.psychopost; r1 = sum(bsxfun(@times, w, r1), 5); end switch lower(method) case {'var','variance'} post0 = squeeze(sum(post0, 5)); post1 = squeeze(sum(post1, 5)); index = find(vars,1); switch index case 1; qq = psy{ci}.mu(:); case 2; qq = psy{ci}.logsigma(:); case 3; qq = psy{ci}.lambda(:); end mean1 = sum(bsxfun(@times,post1,qq),1); mean0 = sum(bsxfun(@times,post0,qq),1); var1 = sum(bsxfun(@times,post1,qq.^2),1) - mean1.^2; var0 = sum(bsxfun(@times,post0,qq.^2),1) - mean0.^2; target = r1(:).*var1(:) + (1-r1(:)).*var0(:); case {'ent','entropy'} temp1 = -post1.*log(post1); temp0 = -post0.*log(post0); temp1(~isfinite(temp1)) = 0; temp0(~isfinite(temp0)) = 0; H1 = temp1; H0 = temp0; for iTheta = find(vars) H1 = sum(H1,iTheta); H0 = sum(H0,iTheta); end if Nfuns > 1 H1 = sum(H1,5); H0 = sum(H0,5); end target = r1(:).*H1(:) + (1-r1(:)).*H0(:); case {'proj','projection'} Nsteps = 4; max(r1) anchors = linspace(0.5, max(r1), Nsteps+1); anchors = anchors(2:end); target = zeros(Nx,1); for jj = 1:numel(anchors) for k = 1:Nfuns [~,idx(:,:,:,1,k)] = min(abs(psy{ci}.f{k}-anchors(jj)),[],4); end mean1 = sum(sum(sum(sum(bsxfun(@times,post1,idx),1),2),3),5); mean0 = sum(sum(sum(sum(bsxfun(@times,post0,idx),1),2),3),5); var1 = sum(sum(sum(sum(bsxfun(@times,post1,idx.^2),1),2),3),5) - mean1.^2; var0 = sum(sum(sum(sum(bsxfun(@times,post0,idx.^2),1),2),3),5) - mean0.^2; target = target + r1(:).*var1(:) + (1-r1(:)).*var0(:); end case {'model'} H1 = -u1.*log(u1); H0 = -u0.*log(u0); H1(~isfinite(H1)) = 0; H0(~isfinite(H0)) = 0; H1 = sum(H1,5); H0 = sum(H0,5); target = r1(:).*H1(:) + (1-r1(:)).*H0(:); otherwise error('Unknown method. Allowed methods are ''var'' and ''ent'' for, respectively, predicted variance and predicted entropy minimization.'); end % Store target for plotting psy{ci}.target = target(:)'; % Location X that minimizes target metric [~,index] = min(target(xindex)); xred = psy{ci}.x(xindex); xnext = xred(index); psy{ci}.xnext = xnext; end % Compute parameter estimates if nargout > 2 w = psy{ci}.psychopost; % Compute mean and variance of the estimate of MU postmu = marginalpost(psy{ci}.post,w,[2,3]); postmu = postmu./sum(postmu,1); emu = sum(postmu.*psy{ci}.mu,1); estd = sqrt(sum(postmu.*psy{ci}.mu.^2,1) - emu.^2); output.mu.mean = emu; output.mu.std = estd; % Compute mean and variance of the estimate of LOGSIGMA and SIGMA postlogsigma = marginalpost(psy{ci}.post,w,[1,3]); postlogsigma = postlogsigma./sum(postlogsigma,2); emu = sum(postlogsigma.*psy{ci}.logsigma,2); estd = sqrt(sum(postlogsigma.*psy{ci}.logsigma.^2,2) - emu.^2); output.logsigma.mean = emu; output.logsigma.std = estd; postsigma = postlogsigma./psy{ci}.sigma; postsigma = postsigma./sum(postsigma,2); emu = sum(postsigma.*psy{ci}.sigma,2); estd = sqrt(sum(postsigma.*psy{ci}.sigma.^2,2) - emu.^2); output.sigma.mean = emu; output.sigma.std = estd; % Compute mean and variance of the estimate of LAMBDA if sharedlambda && Nfuns == 1 postlambda = psy{ci}.postlambda{1}; else % This is possibly not correct postlambda = marginalpost(psy{ci}.post,w,[1,2]); end postlambda = postlambda./sum(postlambda,3); emu = sum(postlambda.*psy{ci}.lambda,3); estd = sqrt(sum(postlambda.*psy{ci}.lambda.^2,3) - emu.^2); output.lambda.mean = emu; output.lambda.std = estd; end end %-------------------------------------------------------------------------- function [post1,post0,r1,u1,u0] = nextposterior(f,post,logupost) %NEXTPOSTERIOR Compute posteriors on next trial depending on possible outcomes mf = 1-f; post1 = bsxfun(@times, post, f); r1 = sum(sum(sum(post1,1),2),3); post0 = bsxfun(@times, post, mf); post1 = bsxfun(@rdivide, post1, sum(sum(sum(post1,1),2),3)); post0 = bsxfun(@rdivide, post0, sum(sum(sum(post0,1),2),3)); if nargin > 2 && nargout > 3 logupost1 = bsxfun(@plus, logupost, log(f)); logupost0 = bsxfun(@plus, logupost, log(mf)); z0 = max(logupost0(:)); u0 = log(sum(sum(sum(exp(logupost0 - z0),1),2),3)); z1 = max(logupost1(:)); u1 = log(sum(sum(sum(exp(logupost1 - z1),1),2),3)); end end %-------------------------------------------------------------------------- function r = geornd(p) %GEORND Random arrays from the geometric distribution. p(p <= 0 | p > 1) = NaN; % Return NaN for illegal parameter values r = ceil(abs(log(rand(size(p))) ./ log(1 - p)) - 1); % == geoinv(u,p) r(r < 0) = 0; % Force a zero when p==1, instead of -1 end
github
lacerbi/psybayes-master
psyinit.m
.m
psybayes-master/private/psyinit.m
6,800
utf_8
e24bc831e0a692754ae68ce3049c887e
function [psy,Nfuns] = psyinit(psyinfo,Ncnd) %PSYINIT Initialize PSY struct. % Total number of conditions (one by default) if nargin < 2 || isempty(Ncnd); Ncnd = 1; end psy = []; psy.ntrial = 0; % Trial number psy.data = []; % Record of data if ~isfield(psyinfo,'psychofun'); psyinfo.psychofun = []; end if iscell(psyinfo.psychofun) Nfuns = numel(psyinfo.psychofun); cellflag = 1; else Nfuns = 1; cellflag = 0; end % Default grid sizes K = 1/(Nfuns^0.25); nx = round(65*K); nmu = round(51*K); nsigma = round(25*K); nlambda = round(25*K); psy.mu = []; psy.logsigma = []; psy.lambda = []; psy.x = []; % Grid over parameters of psychometric function if isfield(psyinfo,'range') % Get grid sizes (third element in initialization range field) if isfield(psyinfo.range,'mu') && numel(psyinfo.range.mu > 2) nmu = psyinfo.range.mu(3); end if isfield(psyinfo.range,'sigma') && numel(psyinfo.range.sigma > 2) nsigma = psyinfo.range.sigma(3); elseif isfield(psyinfo.range,'logsigma') && numel(psyinfo.range.logsigma > 2) nsigma = psyinfo.range.logsigma(3); end if isfield(psyinfo.range,'lambda') && numel(psyinfo.range.lambda > 2) nlambda = psyinfo.range.lambda(3); end if isfield(psyinfo.range,'x') && numel(psyinfo.range.x > 2) nx = psyinfo.range.x(3); end % Prepare ranges if isfield(psyinfo.range,'mu') psy.mu(:,1,1) = linspace(psyinfo.range.mu(1),psyinfo.range.mu(2),nmu); else error('Cannot find a field for MU in initialization range struct.'); end if isfield(psyinfo.range,'sigma') psy.logsigma(1,:,1) = linspace(log(psyinfo.range.sigma(1)), log(psyinfo.range.sigma(2)), nsigma); elseif isfield(psyinfo.range,'logsigma') psy.logsigma(1,:,1) = linspace(psyinfo.range.logsigma(1), psyinfo.range.logsigma(2), nsigma); else error('Cannot find a field for SIGMA in initialization range struct.'); end if isfield(psyinfo.range,'lambda') psy.lambda(1,1,:) = linspace(psyinfo.range.lambda(1),psyinfo.range.lambda(2),nlambda); end if isfield(psyinfo,'x') && ~isempty(psyinfo.x) psy.x(1,1,1,:) = psyinfo.x(:); elseif isfield(psyinfo.range,'x') && ~isempty(psyinfo.range.x) psy.x(1,1,1,:) = linspace(psyinfo.range.x(1),psyinfo.range.x(2),nx); else error('Test grid X not provided in initialization struct.'); end end % Default ranges if isempty(psy.mu) psy.mu(:,1,1) = linspace(2,4,nmu); end if isempty(psy.logsigma) psy.logsigma(1,:,1) = linspace(log(0.01), log(1), nsigma); end if isempty(psy.lambda) psy.lambda(1,1,:) = linspace(0, 0.2, nlambda); end if isempty(psy.x) psy.x(1,1,1,:) = linspace(psy.mu(1),psy.mu(end),nx); end if isfield(psyinfo,'units') psy.units = psyinfo.units; else psy.units.x = []; psy.units.mu = []; psy.units.sigma = []; psy.units.lambda = []; end % By default, wide Student's t prior on mu with slight preference for % the middle of the stimulus range muprior = [mean(psy.mu),0.5*(psy.mu(end)-psy.mu(1)),3]; % mean, sigma and nu if isfield(psyinfo,'priors') && ~isempty(psyinfo.priors) if isfield(psyinfo.priors,'mu') && ~isempty(psyinfo.priors.mu) muprior(1:numel(psyinfo.priors.mu)) = psyinfo.priors.mu; end end priormu = exp(logtpdf(psy.mu,muprior(1),muprior(2),muprior(3))); % By default flat prior on log sigma (Jeffrey's 1/sigma prior in sigma % space); more in general log-Student-t prior logsigmaprior = [mean(psy.logsigma),Inf,3]; % mean, sigma and nu if isfield(psyinfo,'priors') && ~isempty(psyinfo.priors) if isfield(psyinfo.priors,'logsigma') && ~isempty(psyinfo.priors.logsigma) logsigmaprior(1:numel(psyinfo.priors.logsigma)) = psyinfo.priors.logsigma; end end priorlogsigma = exp(logtpdf(psy.logsigma,logsigmaprior(1),logsigmaprior(2),logsigmaprior(3))); % Beta(a,b) prior on lambda, with correction lambdaprior = [1,19]; if isfield(psyinfo,'priors') && ~isempty(psyinfo.priors) if isfield(psyinfo.priors,'lambda') && ~isempty(psyinfo.priors.lambda) lambdaprior = psyinfo.priors.lambda; end end temp = psy.lambda(:)'; temp = [0, temp + 0.5*[diff(temp),0]]; a = lambdaprior(1); b = lambdaprior(2); priorlambda(1,1,:) = betainc(temp(2:end),a,b) - betainc(temp(1:end-1),a,b); % If using multiple conditions, divide prior if Ncnd > 1 fprintf('Sharing prior over LAMBDA across %d conditions.\n', Ncnd); priorlambda = priorlambda.^(1/Ncnd); end priormu = priormu./sum(priormu); priorlogsigma = priorlogsigma./sum(priorlogsigma); priorlambda = priorlambda./sum(priorlambda); % Prior (posterior at iteration zero) over parameters psy.post{1} = bsxfun(@times,bsxfun(@times,priormu,priorlogsigma),priorlambda); for k = 2:Nfuns; psy.post{k} = psy.post{1}; end for k = 1:Nfuns; psy.logupost{k} = log(psy.post{k}); end % Posterior over lambda at iteration zero psy.postlambda{1} = priorlambda; for k = 2:Nfuns; psy.postlambda{k} = psy.postlambda{1}; end % Define sigma in addition to log sigma psy.sigma = exp(psy.logsigma); % Guess rate for PCORRECT psychometric functions if isfield(psyinfo,'gamma') psy.gamma = psyinfo.gamma; else psy.gamma = []; end psy.f = []; psy.xnext = []; % Stimulus refractory time (avoid representing same stimulus for a while) psy.reftime = []; psy.refradius = []; % Refractory time constant (average run length of geometric distribution) if isfield(psyinfo,'reftime') psy.reftime = psyinfo.reftime; end if isempty(psy.reftime); psy.reftime = 0; end % Waiting radius (avoid representing stimuli within this radius) if isfield(psyinfo,'refradius') psy.refradius = psyinfo.refradius; end if isempty(psy.refradius); psy.refradius = 0; end % Initialize refractory times list psy.reflist = zeros(size(psy.x)); % Set psychometric function if isfield(psyinfo,'psychofun'); psy.psychofun = psyinfo.psychofun; end [psy,Nfuns] = psyfunset(psy); % Prior over psychometric functions if Nfuns > 1 if isfield(psyinfo,'psychoprior') psy.psychoprior = psyinfo.psychoprior; else psy.psychoprior = []; end % Uniform prior by default if isempty(psy.psychoprior) psy.psychoprior = ones(1,Nfuns)/Nfuns; end end end %-------------------------------------------------------------------------- function y = logtpdf(x,mu,sigma,nu) %LOGTPDF Log pdf of Student's t distribution. if sigma == Inf % Flat log prior y = zeros(size(x)); elseif nu == Inf % Student's t with infinite degrees of freedom is Gaussian y = -0.5*log(2*pi*sigma^2) -0.5*((x-mu)/sigma).^2; else y = gammaln(0.5*(nu+1)) - gammaln(0.5*nu) - 0.5*log(pi*nu*sigma^2) ... - 0.5*(nu+1) * (1 + 1/nu * ((x-mu)/sigma).^2); end end
github
xizou/NIPGD-master
call_abq.m
.m
NIPGD-master/call_abq.m
2,729
utf_8
2de73aa53534fe0047a5251b466dc19d
function [Ut] = call_abq(E1_tilde,E2_tilde,F_star) %CALL_ABQ Calling Abaqus to solve K_star*U=F_star. % Load parameters for stiffness matrix scaling. % Works only for 3D mesh. % SYNOPOSIS: Ut = call_abq(E1_tilde,E2_tilde,F_star); % INPUT: E1_title : First parameter value, scalar % E2_title : Second parameter value, scalar % F_star : Load-like right hand side, vector % OUTPUT: Ut : Displacement-like result, vector % Updated on: Oct. 8st, 2016 % Author: Xi Zou % University of Pavia, Italy % Polytechnic University of Catalonia, Spain % 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 3 of the License, or % (at your option) any later version. % Generate text file for parameters fPara = fopen('param.inp','w'); fprintf(fPara,'*MATRIX INPUT, NAME=K_1, INPUT=K_1_X1.sim, MATRIX=STIFFNESS, SCALE FACTOR=%s\n', num2str(E1_tilde)); fprintf(fPara,'*MATRIX INPUT, NAME=K_2, INPUT=K_2_X1.sim, MATRIX=STIFFNESS, SCALE FACTOR=%s\n', num2str(E2_tilde)); fclose(fPara); % Load loads fLoad = fopen('load.inp','w'); siz = [3,length(F_star)/3]; F = reshape(F_star,siz); [dof,node] = ind2sub(siz,find(F)); for i=1:length(node) fprintf(fLoad,'%d, %d, %g\n',node(i),dof(i),F(dof(i),node(i))); end fclose(fLoad); % Run analysis via system call [~,~] = system('abaqus job=job input=template >job.log'); % Load results from output file Ut = load_fil('job.fil'); Ut = sparse(Ut); delete job.* param.inp load.inp end function F = load_fil(fName) %LOAD_FIL Load displacement data from Abaqus .fil output. % Works only for 3D mesh. % SYNOPOSIS: F = load_fil(fName); % INPUT: fName : File name of the .fil output, including extension, string % OUTPUT: F : Displacement-like result, vector % Updated on: Oct. 1st, 2016 % Author: Xi Zou % University of Pavia, Italy % Polytechnic University of Catalunya, Spain % 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 3 of the License, or % (at your option) any later version. %% Load Abaqus .fil output file fID = fopen(fName,'r'); C = textscan(fID,'%s','Delimiter','','EndOfLine','*'); fclose(fID); C = C{1}; j = 1; for i=1:size(C,1) A = C{i}; A = A(~isspace(A)); if strfind(A,'I16I3101I') st = strfind(A,'D'); A(st(1:2:end)) = ','; data = textscan(A(st(1)+1:end),'%f,%f,%f'); F(j,:) = cell2mat(data); j = j + 1; end end F = F'; F = F(:); end
github
wireapp/onepassword-app-extension-master
OnePasswordExtension.m
.m
onepassword-app-extension-master/OnePasswordExtension.m
41,868
utf_8
ad5b44a4da8cc02db0488a7b92fb7a0a
// // 1Password Extension // // Lovingly handcrafted by Dave Teare, Michael Fey, Rad Azzouz, and Roustem Karimov. // Copyright (c) 2014 AgileBits. All rights reserved. // #import "OnePasswordExtension.h" // Version #define VERSION_NUMBER @(182) static NSString *const AppExtensionVersionNumberKey = @"version_number"; // Available App Extension Actions static NSString *const kUTTypeAppExtensionFindLoginAction = @"org.appextension.find-login-action"; static NSString *const kUTTypeAppExtensionSaveLoginAction = @"org.appextension.save-login-action"; static NSString *const kUTTypeAppExtensionChangePasswordAction = @"org.appextension.change-password-action"; static NSString *const kUTTypeAppExtensionFillWebViewAction = @"org.appextension.fill-webview-action"; static NSString *const kUTTypeAppExtensionFillBrowserAction = @"org.appextension.fill-browser-action"; // WebView Dictionary keys static NSString *const AppExtensionWebViewPageFillScript = @"fillScript"; static NSString *const AppExtensionWebViewPageDetails = @"pageDetails"; @implementation OnePasswordExtension #pragma mark - Public Methods + (OnePasswordExtension *)sharedExtension { static dispatch_once_t onceToken; static OnePasswordExtension *__sharedExtension; dispatch_once(&onceToken, ^{ __sharedExtension = [OnePasswordExtension new]; }); return __sharedExtension; } - (BOOL)isAppExtensionAvailable { if ([self isSystemAppExtensionAPIAvailable]) { return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"org-appextension-feature-password-management://"]]; } return NO; } #pragma mark - Native app Login - (void)findLoginForURLString:(nonnull NSString *)URLString forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender completion:(nullable void (^)(NSDictionary * __nullable loginDictionary, NSError * __nullable error))completion { NSAssert(URLString != nil, @"URLString must not be nil"); NSAssert(viewController != nil, @"viewController must not be nil"); if (NO == [self isSystemAppExtensionAPIAvailable]) { NSLog(@"Failed to findLoginForURLString, system API is not available"); if (completion) { completion(nil, [OnePasswordExtension systemAppExtensionAPINotAvailableError]); } return; } #ifdef __IPHONE_8_0 NSDictionary *item = @{ AppExtensionVersionNumberKey: VERSION_NUMBER, AppExtensionURLStringKey: URLString }; UIActivityViewController *activityViewController = [self activityViewControllerForItem:item viewController:viewController sender:sender typeIdentifier:kUTTypeAppExtensionFindLoginAction]; activityViewController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) { if (returnedItems.count == 0) { NSError *error = nil; if (activityError) { NSLog(@"Failed to findLoginForURLString: %@", activityError); error = [OnePasswordExtension failedToContactExtensionErrorWithActivityError:activityError]; } else { error = [OnePasswordExtension extensionCancelledByUserError]; } if (completion) { completion(nil, error); } return; } [self processExtensionItem:returnedItems.firstObject completion:^(NSDictionary *itemDictionary, NSError *error) { if (completion) { completion(itemDictionary, error); } }]; }; [viewController presentViewController:activityViewController animated:YES completion:nil]; #endif } #pragma mark - New User Registration - (void)storeLoginForURLString:(nonnull NSString *)URLString loginDetails:(nullable NSDictionary *)loginDetailsDictionary passwordGenerationOptions:(nullable NSDictionary *)passwordGenerationOptions forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender completion:(nullable void (^)(NSDictionary * __nullable loginDictionary, NSError * __nullable error))completion { NSAssert(URLString != nil, @"URLString must not be nil"); NSAssert(viewController != nil, @"viewController must not be nil"); if (NO == [self isSystemAppExtensionAPIAvailable]) { NSLog(@"Failed to storeLoginForURLString, system API is not available"); if (completion) { completion(nil, [OnePasswordExtension systemAppExtensionAPINotAvailableError]); } return; } #ifdef __IPHONE_8_0 NSMutableDictionary *newLoginAttributesDict = [NSMutableDictionary new]; newLoginAttributesDict[AppExtensionVersionNumberKey] = VERSION_NUMBER; newLoginAttributesDict[AppExtensionURLStringKey] = URLString; [newLoginAttributesDict addEntriesFromDictionary:loginDetailsDictionary]; if (passwordGenerationOptions.count > 0) { newLoginAttributesDict[AppExtensionPasswordGeneratorOptionsKey] = passwordGenerationOptions; } UIActivityViewController *activityViewController = [self activityViewControllerForItem:newLoginAttributesDict viewController:viewController sender:sender typeIdentifier:kUTTypeAppExtensionSaveLoginAction]; activityViewController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) { if (returnedItems.count == 0) { NSError *error = nil; if (activityError) { NSLog(@"Failed to storeLoginForURLString: %@", activityError); error = [OnePasswordExtension failedToContactExtensionErrorWithActivityError:activityError]; } else { error = [OnePasswordExtension extensionCancelledByUserError]; } if (completion) { completion(nil, error); } return; } [self processExtensionItem:returnedItems.firstObject completion:^(NSDictionary *itemDictionary, NSError *error) { if (completion) { completion(itemDictionary, error); } }]; }; [viewController presentViewController:activityViewController animated:YES completion:nil]; #endif } #pragma mark - Change Password - (void)changePasswordForLoginForURLString:(nonnull NSString *)URLString loginDetails:(nullable NSDictionary *)loginDetailsDictionary passwordGenerationOptions:(nullable NSDictionary *)passwordGenerationOptions forViewController:(UIViewController *)viewController sender:(nullable id)sender completion:(nullable void (^)(NSDictionary * __nullable loginDictionary, NSError * __nullable error))completion { NSAssert(URLString != nil, @"URLString must not be nil"); NSAssert(viewController != nil, @"viewController must not be nil"); if (NO == [self isSystemAppExtensionAPIAvailable]) { NSLog(@"Failed to changePasswordForLoginWithUsername, system API is not available"); if (completion) { completion(nil, [OnePasswordExtension systemAppExtensionAPINotAvailableError]); } return; } #ifdef __IPHONE_8_0 NSMutableDictionary *item = [NSMutableDictionary new]; item[AppExtensionVersionNumberKey] = VERSION_NUMBER; item[AppExtensionURLStringKey] = URLString; [item addEntriesFromDictionary:loginDetailsDictionary]; if (passwordGenerationOptions.count > 0) { item[AppExtensionPasswordGeneratorOptionsKey] = passwordGenerationOptions; } UIActivityViewController *activityViewController = [self activityViewControllerForItem:item viewController:viewController sender:sender typeIdentifier:kUTTypeAppExtensionChangePasswordAction]; activityViewController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) { if (returnedItems.count == 0) { NSError *error = nil; if (activityError) { NSLog(@"Failed to changePasswordForLoginWithUsername: %@", activityError); error = [OnePasswordExtension failedToContactExtensionErrorWithActivityError:activityError]; } else { error = [OnePasswordExtension extensionCancelledByUserError]; } if (completion) { completion(nil, error); } return; } [self processExtensionItem:returnedItems.firstObject completion:^(NSDictionary *itemDictionary, NSError *error) { if (completion) { completion(itemDictionary, error); } }]; }; [viewController presentViewController:activityViewController animated:YES completion:nil]; #endif } #pragma mark - Web View filling Support - (void)fillItemIntoWebView:(nonnull id)webView forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender showOnlyLogins:(BOOL)yesOrNo completion:(nullable void (^)(BOOL success, NSError * __nullable error))completion { NSAssert(webView != nil, @"webView must not be nil"); NSAssert(viewController != nil, @"viewController must not be nil"); NSAssert([webView isKindOfClass:[UIWebView class]] || [webView isKindOfClass:[WKWebView class]], @"webView must be an instance of WKWebView or UIWebView."); #ifdef __IPHONE_8_0 if ([webView isKindOfClass:[UIWebView class]]) { [self fillItemIntoUIWebView:webView webViewController:viewController sender:(id)sender showOnlyLogins:yesOrNo completion:^(BOOL success, NSError *error) { if (completion) { completion(success, error); } }]; } #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0 || ONE_PASSWORD_EXTENSION_ENABLE_WK_WEB_VIEW else if ([webView isKindOfClass:[WKWebView class]]) { [self fillItemIntoWKWebView:webView forViewController:viewController sender:(id)sender showOnlyLogins:yesOrNo completion:^(BOOL success, NSError *error) { if (completion) { completion(success, error); } }]; } #endif #endif } #pragma mark - Support for custom UIActivityViewControllers - (BOOL)isOnePasswordExtensionActivityType:(nullable NSString *)activityType { return [@"com.agilebits.onepassword-ios.extension" isEqualToString:activityType] || [@"com.agilebits.beta.onepassword-ios.extension" isEqualToString:activityType]; } - (void)createExtensionItemForWebView:(nonnull id)webView completion:(void (^)(NSExtensionItem * __nullable extensionItem, NSError * __nullable error))completion { NSAssert(webView != nil, @"webView must not be nil"); NSAssert([webView isKindOfClass:[UIWebView class]] || [webView isKindOfClass:[WKWebView class]], @"webView must be an instance of WKWebView or UIWebView."); #ifdef __IPHONE_8_0 if ([webView isKindOfClass:[UIWebView class]]) { UIWebView *uiWebView = (UIWebView *)webView; NSString *collectedPageDetails = [uiWebView stringByEvaluatingJavaScriptFromString:OPWebViewCollectFieldsScript]; [self createExtensionItemForURLString:uiWebView.request.URL.absoluteString webPageDetails:collectedPageDetails completion:completion]; } #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0 || ONE_PASSWORD_EXTENSION_ENABLE_WK_WEB_VIEW else if ([webView isKindOfClass:[WKWebView class]]) { WKWebView *wkWebView = (WKWebView *)webView; [wkWebView evaluateJavaScript:OPWebViewCollectFieldsScript completionHandler:^(NSString *result, NSError *evaluateError) { if (result == nil) { NSLog(@"1Password Extension failed to collect web page fields: %@", evaluateError); NSError *failedToCollectFieldsError = [OnePasswordExtension failedToCollectFieldsErrorWithUnderlyingError:evaluateError]; if (completion) { if ([NSThread isMainThread]) { completion(nil, failedToCollectFieldsError); } else { dispatch_async(dispatch_get_main_queue(), ^{ completion(nil, failedToCollectFieldsError); }); } } return; } [self createExtensionItemForURLString:wkWebView.URL.absoluteString webPageDetails:result completion:completion]; }]; } #endif #endif } - (void)fillReturnedItems:(nullable NSArray *)returnedItems intoWebView:(nonnull id)webView completion:(nullable void (^)(BOOL success, NSError * __nullable error))completion { NSAssert(webView != nil, @"webView must not be nil"); if (returnedItems.count == 0) { NSError *error = [OnePasswordExtension extensionCancelledByUserError]; if (completion) { completion(NO, error); } return; } [self processExtensionItem:returnedItems.firstObject completion:^(NSDictionary *itemDictionary, NSError *error) { if (itemDictionary.count == 0) { if (completion) { completion(NO, error); } return; } NSString *fillScript = itemDictionary[AppExtensionWebViewPageFillScript]; [self executeFillScript:fillScript inWebView:webView completion:^(BOOL success, NSError *executeFillScriptError) { if (completion) { completion(success, executeFillScriptError); } }]; }]; } #pragma mark - Private methods - (BOOL)isSystemAppExtensionAPIAvailable { #ifdef __IPHONE_8_0 return [NSExtensionItem class] != nil; #else return NO; #endif } - (void)findLoginIn1PasswordWithURLString:(nonnull NSString *)URLString collectedPageDetails:(nullable NSString *)collectedPageDetails forWebViewController:(nonnull UIViewController *)forViewController sender:(nullable id)sender withWebView:(nonnull id)webView showOnlyLogins:(BOOL)yesOrNo completion:(void (^)(BOOL success, NSError * __nullable error))completion { if ([URLString length] == 0) { NSError *URLStringError = [OnePasswordExtension failedToObtainURLStringFromWebViewError]; NSLog(@"Failed to findLoginIn1PasswordWithURLString: %@", URLStringError); if (completion) { completion(NO, URLStringError); } return; } NSError *jsonError = nil; NSData *data = [collectedPageDetails dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *collectedPageDetailsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError]; if (collectedPageDetailsDictionary.count == 0) { NSLog(@"Failed to parse JSON collected page details: %@", jsonError); if (completion) { completion(NO, jsonError); } return; } NSDictionary *item = @{ AppExtensionVersionNumberKey : VERSION_NUMBER, AppExtensionURLStringKey : URLString, AppExtensionWebViewPageDetails : collectedPageDetailsDictionary }; NSString *typeIdentifier = yesOrNo ? kUTTypeAppExtensionFillWebViewAction : kUTTypeAppExtensionFillBrowserAction; UIActivityViewController *activityViewController = [self activityViewControllerForItem:item viewController:forViewController sender:sender typeIdentifier:typeIdentifier]; activityViewController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) { if (returnedItems.count == 0) { NSError *error = nil; if (activityError) { NSLog(@"Failed to findLoginIn1PasswordWithURLString: %@", activityError); error = [OnePasswordExtension failedToContactExtensionErrorWithActivityError:activityError]; } else { error = [OnePasswordExtension extensionCancelledByUserError]; } if (completion) { completion(NO, error); } return; } [self processExtensionItem:returnedItems.firstObject completion:^(NSDictionary *itemDictionary, NSError *processExtensionItemError) { if (itemDictionary.count == 0) { if (completion) { completion(NO, processExtensionItemError); } return; } NSString *fillScript = itemDictionary[AppExtensionWebViewPageFillScript]; [self executeFillScript:fillScript inWebView:webView completion:^(BOOL success, NSError *executeFillScriptError) { if (completion) { completion(success, executeFillScriptError); } }]; }]; }; [forViewController presentViewController:activityViewController animated:YES completion:nil]; } #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0 || ONE_PASSWORD_EXTENSION_ENABLE_WK_WEB_VIEW - (void)fillItemIntoWKWebView:(nonnull WKWebView *)webView forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender showOnlyLogins:(BOOL)yesOrNo completion:(void (^)(BOOL success, NSError * __nullable error))completion { [webView evaluateJavaScript:OPWebViewCollectFieldsScript completionHandler:^(NSString *result, NSError *error) { if (result == nil) { NSLog(@"1Password Extension failed to collect web page fields: %@", error); if (completion) { completion(NO,[OnePasswordExtension failedToCollectFieldsErrorWithUnderlyingError:error]); } return; } [self findLoginIn1PasswordWithURLString:webView.URL.absoluteString collectedPageDetails:result forWebViewController:viewController sender:sender withWebView:webView showOnlyLogins:yesOrNo completion:^(BOOL success, NSError *findLoginError) { if (completion) { completion(success, findLoginError); } }]; }]; } #endif - (void)fillItemIntoUIWebView:(nonnull UIWebView *)webView webViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender showOnlyLogins:(BOOL)yesOrNo completion:(void (^)(BOOL success, NSError * __nullable error))completion { NSString *collectedPageDetails = [webView stringByEvaluatingJavaScriptFromString:OPWebViewCollectFieldsScript]; [self findLoginIn1PasswordWithURLString:webView.request.URL.absoluteString collectedPageDetails:collectedPageDetails forWebViewController:viewController sender:sender withWebView:webView showOnlyLogins:yesOrNo completion:^(BOOL success, NSError *error) { if (completion) { completion(success, error); } }]; } - (void)executeFillScript:(NSString * __nullable)fillScript inWebView:(nonnull id)webView completion:(void (^)(BOOL success, NSError * __nullable error))completion { if (fillScript == nil) { NSLog(@"Failed to executeFillScript, fillScript is missing"); if (completion) { completion(NO, [OnePasswordExtension failedToFillFieldsErrorWithLocalizedErrorMessage:NSLocalizedStringFromTable(@"Failed to fill web page because script is missing", @"OnePasswordExtension", @"1Password Extension Error Message") underlyingError:nil]); } return; } NSMutableString *scriptSource = [OPWebViewFillScript mutableCopy]; [scriptSource appendFormat:@"(document, %@, undefined);", fillScript]; #ifdef __IPHONE_8_0 if ([webView isKindOfClass:[UIWebView class]]) { NSString *result = [((UIWebView *)webView) stringByEvaluatingJavaScriptFromString:scriptSource]; BOOL success = (result != nil); NSError *error = nil; if (!success) { NSLog(@"Cannot executeFillScript, stringByEvaluatingJavaScriptFromString failed"); error = [OnePasswordExtension failedToFillFieldsErrorWithLocalizedErrorMessage:NSLocalizedStringFromTable(@"Failed to fill web page because script could not be evaluated", @"OnePasswordExtension", @"1Password Extension Error Message") underlyingError:nil]; } if (completion) { completion(success, error); } } #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0 || ONE_PASSWORD_EXTENSION_ENABLE_WK_WEB_VIEW else if ([webView isKindOfClass:[WKWebView class]]) { [((WKWebView *)webView) evaluateJavaScript:scriptSource completionHandler:^(NSString *result, NSError *evaluationError) { BOOL success = (result != nil); NSError *error = nil; if (!success) { NSLog(@"Cannot executeFillScript, evaluateJavaScript failed: %@", evaluationError); error = [OnePasswordExtension failedToFillFieldsErrorWithLocalizedErrorMessage:NSLocalizedStringFromTable(@"Failed to fill web page because script could not be evaluated", @"OnePasswordExtension", @"1Password Extension Error Message") underlyingError:error]; } if (completion) { completion(success, error); } }]; } #endif #endif } #ifdef __IPHONE_8_0 - (void)processExtensionItem:(nullable NSExtensionItem *)extensionItem completion:(void (^)(NSDictionary *itemDictionary, NSError * __nullable error))completion { if (extensionItem.attachments.count == 0) { NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: @"Unexpected data returned by App Extension: extension item had no attachments." }; NSError *error = [[NSError alloc] initWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeUnexpectedData userInfo:userInfo]; if (completion) { completion(nil, error); } return; } NSItemProvider *itemProvider = extensionItem.attachments.firstObject; if (NO == [itemProvider hasItemConformingToTypeIdentifier:(__bridge NSString *)kUTTypePropertyList]) { NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: @"Unexpected data returned by App Extension: extension item attachment does not conform to kUTTypePropertyList type identifier" }; NSError *error = [[NSError alloc] initWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeUnexpectedData userInfo:userInfo]; if (completion) { completion(nil, error); } return; } [itemProvider loadItemForTypeIdentifier:(__bridge NSString *)kUTTypePropertyList options:nil completionHandler:^(NSDictionary *itemDictionary, NSError *itemProviderError) { NSError *error = nil; if (itemDictionary.count == 0) { NSLog(@"Failed to loadItemForTypeIdentifier: %@", itemProviderError); error = [OnePasswordExtension failedToLoadItemProviderDataErrorWithUnderlyingError:itemProviderError]; } if (completion) { if ([NSThread isMainThread]) { completion(itemDictionary, error); } else { dispatch_async(dispatch_get_main_queue(), ^{ completion(itemDictionary, error); }); } } }]; } - (UIActivityViewController *)activityViewControllerForItem:(nonnull NSDictionary *)item viewController:(nonnull UIViewController*)viewController sender:(nullable id)sender typeIdentifier:(nonnull NSString *)typeIdentifier { #ifdef __IPHONE_8_0 NSAssert(NO == (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && sender == nil), @"sender must not be nil on iPad."); NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithItem:item typeIdentifier:typeIdentifier]; NSExtensionItem *extensionItem = [[NSExtensionItem alloc] init]; extensionItem.attachments = @[ itemProvider ]; UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:@[ extensionItem ] applicationActivities:nil]; if ([sender isKindOfClass:[UIBarButtonItem class]]) { controller.popoverPresentationController.barButtonItem = sender; } else if ([sender isKindOfClass:[UIView class]]) { controller.popoverPresentationController.sourceView = [sender superview]; controller.popoverPresentationController.sourceRect = [sender frame]; } else { NSLog(@"sender can be nil on iPhone"); } return controller; #else return nil; #endif } #endif - (void)createExtensionItemForURLString:(nonnull NSString *)URLString webPageDetails:(nullable NSString *)webPageDetails completion:(void (^)(NSExtensionItem *extensionItem, NSError * __nullable error))completion { NSError *jsonError = nil; NSData *data = [webPageDetails dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *webPageDetailsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError]; if (webPageDetailsDictionary.count == 0) { NSLog(@"Failed to parse JSON collected page details: %@", jsonError); if (completion) { completion(nil, jsonError); } return; } NSDictionary *item = @{ AppExtensionVersionNumberKey : VERSION_NUMBER, AppExtensionURLStringKey : URLString, AppExtensionWebViewPageDetails : webPageDetailsDictionary }; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithItem:item typeIdentifier:kUTTypeAppExtensionFillBrowserAction]; NSExtensionItem *extensionItem = [[NSExtensionItem alloc] init]; extensionItem.attachments = @[ itemProvider ]; if (completion) { if ([NSThread isMainThread]) { completion(extensionItem, nil); } else { dispatch_async(dispatch_get_main_queue(), ^{ completion(extensionItem, nil); }); } } } #pragma mark - Errors + (NSError *)systemAppExtensionAPINotAvailableError { NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : NSLocalizedStringFromTable(@"App Extension API is not available in this version of iOS", @"OnePasswordExtension", @"1Password Extension Error Message") }; return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeAPINotAvailable userInfo:userInfo]; } + (NSError *)extensionCancelledByUserError { NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : NSLocalizedStringFromTable(@"1Password Extension was cancelled by the user", @"OnePasswordExtension", @"1Password Extension Error Message") }; return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeCancelledByUser userInfo:userInfo]; } + (NSError *)failedToContactExtensionErrorWithActivityError:(nullable NSError *)activityError { NSMutableDictionary *userInfo = [NSMutableDictionary new]; userInfo[NSLocalizedDescriptionKey] = NSLocalizedStringFromTable(@"Failed to contact the 1Password Extension", @"OnePasswordExtension", @"1Password Extension Error Message"); if (activityError) { userInfo[NSUnderlyingErrorKey] = activityError; } return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeFailedToContactExtension userInfo:userInfo]; } + (NSError *)failedToCollectFieldsErrorWithUnderlyingError:(nullable NSError *)underlyingError { NSMutableDictionary *userInfo = [NSMutableDictionary new]; userInfo[NSLocalizedDescriptionKey] = NSLocalizedStringFromTable(@"Failed to execute script that collects web page information", @"OnePasswordExtension", @"1Password Extension Error Message"); if (underlyingError) { userInfo[NSUnderlyingErrorKey] = underlyingError; } return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeCollectFieldsScriptFailed userInfo:userInfo]; } + (NSError *)failedToFillFieldsErrorWithLocalizedErrorMessage:(nullable NSString *)errorMessage underlyingError:(nullable NSError *)underlyingError { NSMutableDictionary *userInfo = [NSMutableDictionary new]; if (errorMessage) { userInfo[NSLocalizedDescriptionKey] = errorMessage; } if (underlyingError) { userInfo[NSUnderlyingErrorKey] = underlyingError; } return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeFillFieldsScriptFailed userInfo:userInfo]; } + (NSError *)failedToLoadItemProviderDataErrorWithUnderlyingError:(nullable NSError *)underlyingError { NSMutableDictionary *userInfo = [NSMutableDictionary new]; userInfo[NSLocalizedDescriptionKey] = NSLocalizedStringFromTable(@"Failed to parse information returned by 1Password Extension", @"OnePasswordExtension", @"1Password Extension Error Message"); if (underlyingError) { userInfo[NSUnderlyingErrorKey] = underlyingError; } return [[NSError alloc] initWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeFailedToLoadItemProviderData userInfo:userInfo]; } + (NSError *)failedToObtainURLStringFromWebViewError { NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : NSLocalizedStringFromTable(@"Failed to obtain URL String from web view. The web view must be loaded completely when calling the 1Password Extension", @"OnePasswordExtension", @"1Password Extension Error Message") }; return [NSError errorWithDomain:AppExtensionErrorDomain code:AppExtensionErrorCodeFailedToObtainURLStringFromWebView userInfo:userInfo]; } #pragma mark - WebView field collection and filling scripts static NSString *const OPWebViewCollectFieldsScript = @";(function(document, undefined) {\ \ document.elementsByOPID={};\ function n(d,e){function f(a,b){var c=a[b];if('string'==typeof c)return c;c=a.getAttribute(b);return'string'==typeof c?c:null}function h(a,b){if(-1===['text','password'].indexOf(b.type.toLowerCase())||!(l.test(a.value)||l.test(a.htmlID)||l.test(a.htmlName)||l.test(a.placeholder)||l.test(a['label-tag'])||l.test(a['label-data'])||l.test(a['label-aria'])))return!1;if(!a.visible)return!0;if('password'==b.type.toLowerCase())return!1;var c=b.type,d=b.value;b.focus();b.value!==d&&(b.value=d);return c!==\ b.type}function r(a){switch(m(a.type)){case 'checkbox':return a.checked?'✓':'';case 'hidden':a=a.value;if(!a||'number'!=typeof a.length)return'';254<a.length&&(a=a.substr(0,254)+'...SNIPPED');return a;default:return a.value}}function v(a){return a.options?(a=Array.prototype.slice.call(a.options).map(function(a){var c=a.text,c=c?m(c).replace(/\\s/mg,'').replace(/[~`!@$%^&*()\\-_+=:;'\"\\[\\]|\\\\,<.>\\/?]/mg,''):null;return[c?c:null,a.value]}),{options:a}):null}function F(a){var b;for(a=a.parentElement||a.parentNode;a&&\ 'td'!=m(a.tagName);)a=a.parentElement||a.parentNode;if(!a||void 0===a)return null;b=a.parentElement||a.parentNode;if('tr'!=b.tagName.toLowerCase())return null;b=b.previousElementSibling;if(!b||'tr'!=(b.tagName+'').toLowerCase()||b.cells&&a.cellIndex>=b.cells.length)return null;a=s(b.cells[a.cellIndex]);return a=u(a)}function A(a){var b=d.documentElement,c=a.getBoundingClientRect(),e=b.getBoundingClientRect(),f=c.left-b.clientLeft,b=c.top-b.clientTop;return a.offsetParent?0>f||f>e.width||0>b||b>e.height?\ w(a):(e=a.ownerDocument.elementFromPoint(f+3,b+3))?'label'===m(e.tagName)?e===B(a):e.tagName===a.tagName:!1:!1}function w(a){for(var b;a!==d&&a;a=a.parentNode){b=t.getComputedStyle?t.getComputedStyle(a,null):a.style;if(!b)return!0;if('none'===b.display||'hidden'==b.visibility)return!1}return a===d}function B(a){var b=[];a.id&&(b=b.concat(Array.prototype.slice.call(x(d,'label[for='+JSON.stringify(a.id)+']'))));a.name&&(b=b.concat(Array.prototype.slice.call(x(d,'label[for='+JSON.stringify(a.name)+']'))));\ if(0<b.length)return b.map(function(a){return s(a)}).join('');for(;a&&a!=d;a=a.parentNode)if('label'===m(a.tagName))return s(a);return null}function g(a,b,c,d){void 0!==d&&d===c||null===c||void 0===c||(a[b]=c)}function m(a){return'string'===typeof a?a.toLowerCase():(''+a).toLowerCase()}function x(a,b){var c=[];try{c=a.querySelectorAll(b)}catch(d){}return c}var t=d.defaultView?d.defaultView:window,p,l=RegExp('((\\\\b|_|-)pin(\\\\b|_|-)|password|passwort|kennwort|passe|contraseña|senha|密码|adgangskode|hasło|wachtwoord)',\ 'i');p=Array.prototype.slice.call(x(d,'form')).map(function(a,b){var c={},d='__form__'+b;a.opid=d;c.opid=d;g(c,'htmlName',f(a,'name'));g(c,'htmlID',f(a,'id'));g(c,'htmlAction',y(f(a,'action')));g(c,'htmlMethod',f(a,'method'));return c});var q=Array.prototype.slice.call(z(d)).map(function(a,b){var c={},e='__'+b,k=-1==a.maxLength?999:a.maxLength;if(!k||'number'===typeof k&&isNaN(k))k=999;d.elementsByOPID[e]=a;a.opid=e;c.opid=e;c.elementNumber=b;g(c,'maxLength',Math.min(k,999),999);c.visible=w(a);c.viewable=\ A(a);g(c,'htmlID',f(a,'id'));g(c,'htmlName',f(a,'name'));g(c,'htmlClass',f(a,'class'));g(c,'tabindex',f(a,'tabindex'));if('hidden'!=m(a.type)){g(c,'label-tag',B(a));g(c,'label-data',f(a,'data-label'));g(c,'label-aria',f(a,'aria-label'));g(c,'label-top',F(a));e=[];for(k=a;k&&k.nextSibling;){k=k.nextSibling;if(C(k))break;D(e,k)}g(c,'label-right',e.join(''));e=[];E(a,e);e=e.reverse().join('');g(c,'label-left',e);g(c,'placeholder',f(a,'placeholder'))}g(c,'rel',f(a,'rel'));g(c,'type',m(f(a,'type')));g(c,\ 'value',r(a));g(c,'checked',a.checked,!1);g(c,'autoCompleteType',a.getAttribute('x-autocompletetype')||a.getAttribute('autocompletetype')||a.getAttribute('autocomplete'),'off');g(c,'disabled',a.disabled);g(c,'readonly',a.a||a.readOnly);g(c,'selectInfo',v(a));g(c,'aria-hidden','true'==a.getAttribute('aria-hidden'),!1);g(c,'aria-disabled','true'==a.getAttribute('aria-disabled'),!1);g(c,'aria-haspopup','true'==a.getAttribute('aria-haspopup'),!1);g(c,'data-unmasked',a.dataset.unmasked);g(c,'data-stripe',\ f(a,'data-stripe'));g(c,'onepasswordFieldType',a.dataset.onepasswordFieldType||a.type);g(c,'onepasswordDesignation',a.dataset.onepasswordDesignation);g(c,'onepasswordSignInUrl',a.dataset.onepasswordSignInUrl);g(c,'onepasswordSectionTitle',a.dataset.onepasswordSectionTitle);g(c,'onepasswordSectionFieldKind',a.dataset.onepasswordSectionFieldKind);g(c,'onepasswordSectionFieldTitle',a.dataset.onepasswordSectionFieldTitle);g(c,'onepasswordSectionFieldValue',a.dataset.onepasswordSectionFieldValue);a.form&&\ (c.form=f(a.form,'opid'));g(c,'fakeTested',h(c,a),!1);return c});q.filter(function(a){return a.fakeTested}).forEach(function(a){var b=d.elementsByOPID[a.opid];b.getBoundingClientRect();var c=b.value;!b||b&&'function'!==typeof b.click||b.click();b.focus();G(b,'keydown');G(b,'keyup');G(b,'keypress');b.value!==c&&(b.value=c);b.click&&b.click();a.postFakeTestVisible=w(b);a.postFakeTestViewable=A(b);a.postFakeTestType=b.type;a=b.value;var c=b.ownerDocument.createEvent('HTMLEvents'),e=b.ownerDocument.createEvent('HTMLEvents');\ G(b,'keydown');G(b,'keyup');G(b,'keypress');e.initEvent('input',!0,!0);b.dispatchEvent(e);c.initEvent('change',!0,!0);b.dispatchEvent(c);b.blur();b.value!==a&&(b.value=a)});p={documentUUID:e,title:d.title,url:t.location.href,documentUrl:d.location.href,tabUrl:t.location.href,forms:function(a){var b={};a.forEach(function(a){b[a.opid]=a});return b}(p),fields:q,collectedTimestamp:(new Date).getTime()};(q=document.querySelector('[data-onepassword-display-title]'))&&q.dataset[DISPLAY_TITLE_ATTRIBUE]&&\ (p.displayTitle=q.dataset.onepasswordTitle);return p};document.elementForOPID=H;function G(d,e){var f;f=d.ownerDocument.createEvent('KeyboardEvent');f.initKeyboardEvent?f.initKeyboardEvent(e,!0,!0):f.initKeyEvent&&f.initKeyEvent(e,!0,!0,null,!1,!1,!1,!1,0,0);d.dispatchEvent(f)}window.LOGIN_TITLES=[/^\\W*log\\W*[oi]n\\W*$/i,/log\\W*[oi]n (?:securely|now)/i,/^\\W*sign\\W*[oi]n\\W*$/i,'continue','submit','weiter','accès','вход','connexion','entrar','anmelden','accedi','valider','登录','लॉग इन करें'];window.LOGIN_RED_HERRING_TITLES=['already have an account','sign in with'];\ window.REGISTER_TITLES='register;sign up;signup;join;регистрация;inscription;regístrate;cadastre-se;registrieren;registrazione;注册;साइन अप करें'.split(';');window.SEARCH_TITLES='search find поиск найти искать recherche suchen buscar suche ricerca procurar 検索'.split(' ');window.FORGOT_PASSWORD_TITLES='forgot geändert vergessen hilfe changeemail español'.split(' ');window.REMEMBER_ME_TITLES=['remember me','rememberme','keep me signed in'];window.BACK_TITLES=['back','назад'];\ function s(d){return d.textContent||d.innerText}function u(d){var e=null;d&&(e=d.replace(/^\\s+|\\s+$|\\r?\\n.*$/mg,''),e=0<e.length?e:null);return e}function D(d,e){var f;f='';3===e.nodeType?f=e.nodeValue:1===e.nodeType&&(f=s(e));(f=u(f))&&d.push(f)}function C(d){var e;d&&void 0!==d?(e='select option input form textarea button table iframe body head script'.split(' '),d?(d=d?(d.tagName||'').toLowerCase():'',e=e.constructor==Array?0<=e.indexOf(d):d===e):e=!1):e=!0;return e}\ function E(d,e,f){var h;for(f||(f=0);d&&d.previousSibling;){d=d.previousSibling;if(C(d))return;D(e,d)}if(d&&0===e.length){for(h=null;!h;){d=d.parentElement||d.parentNode;if(!d)return;for(h=d.previousSibling;h&&!C(h)&&h.lastChild;)h=h.lastChild}C(h)||(D(e,h),0===e.length&&E(h,e,f+1))}}\ function H(d){var e;if(void 0===d||null===d)return null;try{var f=Array.prototype.slice.call(z(document)),h=f.filter(function(e){return e.opid==d});if(0<h.length)e=h[0],1<h.length&&console.warn('More than one element found with opid '+d);else{var r=parseInt(d.split('__')[1],10);isNaN(r)||(e=f[r])}}catch(v){console.error('An unexpected error occurred: '+v)}finally{return e}};var I=/^[\\/\\?]/;function y(d){if(!d)return null;if(0==d.indexOf('http'))return d;var e=window.location.protocol+'//'+window.location.hostname;window.location.port&&''!=window.location.port&&(e+=':'+window.location.port);d.match(I)||(d='/'+d);return e+d}function z(d){var e=[];try{e=d.querySelectorAll('input, select, button')}catch(f){}return e};\ \ return JSON.stringify(n(document, 'oneshotUUID'));\ })(document);\ "; static NSString *const OPWebViewFillScript = @";(function(document, fillScript, undefined) {\ \ var f=!0,h=!0;\ function l(a){var b=null;return a?0===a.indexOf('https://')&&'http:'===document.location.protocol&&(b=document.querySelectorAll('input[type=password]'),0<b.length&&(confirmResult=confirm('1Password warning: This is an unsecured HTTP page, and any information you submit can potentially be seen and changed by others. This Login was originally saved on a secure (HTTPS) page.\\n\\nDo you still wish to fill this login?'),0==confirmResult))?!0:!1:!1}\ function k(a){var b,c=[],d=a.properties,e=1,g;d&&d.delay_between_operations&&(e=d.delay_between_operations);if(!l(a.savedURL)){g=function(a,b){var d=a[0];void 0===d?b():('delay'===d.operation||'delay'===d[0]?e=d.parameters?d.parameters[0]:d[1]:c.push(m(d)),setTimeout(function(){g(a.slice(1),b)},e))};if(b=a.options)b.hasOwnProperty('animate')&&(h=b.animate),b.hasOwnProperty('markFilling')&&(f=b.markFilling);a.itemType&&'fillPassword'===a.itemType&&(f=!1);a.hasOwnProperty('script')&&(b=a.script,g(b,\ function(){c=Array.prototype.concat.apply(c,void 0);a.hasOwnProperty('autosubmit')&&'function'==typeof autosubmit&&(a.itemType&&'fillLogin'!==a.itemType||setTimeout(function(){autosubmit(a.autosubmit,d.allow_clicky_autosubmit)},AUTOSUBMIT_DELAY));'object'==typeof protectedGlobalPage&&protectedGlobalPage.a('fillItemResults',{documentUUID:documentUUID,fillContextIdentifier:a.fillContextIdentifier,usedOpids:c},function(){fillingItemType=null})}))}}\ var v={fill_by_opid:n,fill_by_query:p,click_on_opid:q,click_on_query:r,touch_all_fields:s,simple_set_value_by_query:t,focus_by_opid:u,delay:null};function m(a){var b;if(a.hasOwnProperty('operation')&&a.hasOwnProperty('parameters'))b=a.operation,a=a.parameters;else if('[object Array]'===Object.prototype.toString.call(a))b=a[0],a=a.splice(1);else return null;return v.hasOwnProperty(b)?v[b].apply(this,a):null}function n(a,b){var c;return(c=w(a))?(x(c,b),c.opid):null}\ function p(a,b){var c;c=y(a);return Array.prototype.map.call(Array.prototype.slice.call(c),function(a){x(a,b);return a.opid},this)}function t(a,b){var c,d=[];c=y(a);Array.prototype.forEach.call(Array.prototype.slice.call(c),function(a){void 0!==a.value&&(a.value=b,d.push(a.opid))});return d}function u(a){if(a=w(a))'function'===typeof a.click&&a.click(),'function'===typeof a.focus&&a.focus();return null}function q(a){return(a=w(a))?z(a)?a.opid:null:null}\ function r(a){a=y(a);return Array.prototype.map.call(Array.prototype.slice.call(a),function(a){z(a);'function'===typeof a.click&&a.click();'function'===typeof a.focus&&a.focus();return a.opid},this)}function s(){A()};var B={'true':!0,y:!0,1:!0,yes:!0,'✓':!0},C=200;function x(a,b){var c;if(a&&null!==b&&void 0!==b)switch(f&&a.form&&!a.form.opfilled&&(a.form.opfilled=!0),a.type?a.type.toLowerCase():null){case 'checkbox':c=b&&1<=b.length&&B.hasOwnProperty(b.toLowerCase())&&!0===B[b.toLowerCase()];a.checked===c||D(a,function(a){a.checked=c});break;case 'radio':!0===B[b.toLowerCase()]&&a.click();break;default:a.value==b||D(a,function(a){a.value=b})}}\ function D(a,b){E(a);b(a);F(a);G(a)&&(a.className+=' com-agilebits-onepassword-extension-animated-fill',setTimeout(function(){a&&a.className&&(a.className=a.className.replace(/(\\s)?com-agilebits-onepassword-extension-animated-fill/,''))},C))};document.elementForOPID=w;function H(a,b){var c;c=a.ownerDocument.createEvent('KeyboardEvent');c.initKeyboardEvent?c.initKeyboardEvent(b,!0,!0):c.initKeyEvent&&c.initKeyEvent(b,!0,!0,null,!1,!1,!1,!1,0,0);a.dispatchEvent(c)}function E(a){var b=a.value;z(a);a.focus();H(a,'keydown');H(a,'keyup');H(a,'keypress');a.value!==b&&(a.value=b)}\ function F(a){var b=a.value,c=a.ownerDocument.createEvent('HTMLEvents'),d=a.ownerDocument.createEvent('HTMLEvents');H(a,'keydown');H(a,'keyup');H(a,'keypress');d.initEvent('input',!0,!0);a.dispatchEvent(d);c.initEvent('change',!0,!0);a.dispatchEvent(c);a.blur();a.value!==b&&(a.value=b)}function z(a){if(!a||a&&'function'!==typeof a.click)return!1;a.click();return!0}\ function I(){var a=RegExp('((\\\\b|_|-)pin(\\\\b|_|-)|password|passwort|kennwort|passe|contraseña|senha|密码|adgangskode|hasło|wachtwoord)','i');return Array.prototype.slice.call(y(\"input[type='text']\")).filter(function(b){return b.value&&a.test(b.value)},this)}function A(){I().forEach(function(a){E(a);a.click&&a.click();F(a)})}\ window.LOGIN_TITLES=[/^\\W*log\\W*[oi]n\\W*$/i,/log\\W*[oi]n (?:securely|now)/i,/^\\W*sign\\W*[oi]n\\W*$/i,'continue','submit','weiter','accès','вход','connexion','entrar','anmelden','accedi','valider','登录','लॉग इन करें'];window.LOGIN_RED_HERRING_TITLES=['already have an account','sign in with'];window.REGISTER_TITLES='register;sign up;signup;join;регистрация;inscription;regístrate;cadastre-se;registrieren;registrazione;注册;साइन अप करें'.split(';');window.SEARCH_TITLES='search find поиск найти искать recherche suchen buscar suche ricerca procurar 検索'.split(' ');\ window.FORGOT_PASSWORD_TITLES='forgot geändert vergessen hilfe changeemail español'.split(' ');window.REMEMBER_ME_TITLES=['remember me','rememberme','keep me signed in'];window.BACK_TITLES=['back','назад'];\ function G(a){var b;if(b=h)a:{b=a;for(var c=a.ownerDocument,c=c?c.defaultView:{},d;b&&b!==document;){d=c.getComputedStyle?c.getComputedStyle(b,null):b.style;if(!d){b=!0;break a}if('none'===d.display||'hidden'==d.visibility){b=!1;break a}b=b.parentNode}b=b===document}return b?-1!=='email text password number tel url'.split(' ').indexOf(a.type||''):!1}\ function w(a){var b;if(void 0===a||null===a)return null;try{var c=Array.prototype.slice.call(y('input, select, button')),d=c.filter(function(b){return b.opid==a});if(0<d.length)b=d[0],1<d.length&&console.warn('More than one element found with opid '+a);else{var e=parseInt(a.split('__')[1],10);isNaN(e)||(b=c[e])}}catch(g){console.error('An unexpected error occurred: '+g)}finally{return b}};function y(a){var b=document,c=[];try{c=b.querySelectorAll(a)}catch(d){}return c};\ \ k(fillScript);\ return JSON.stringify({'success': true});\ })\ "; #pragma mark - Deprecated methods /* Deprecated in version 1.5 Use fillItemIntoWebView:forViewController:sender:showOnlyLogins:completion: instead */ - (void)fillLoginIntoWebView:(nonnull id)webView forViewController:(nonnull UIViewController *)viewController sender:(nullable id)sender completion:(nullable void (^)(BOOL success, NSError * __nullable error))completion { [self fillItemIntoWebView:webView forViewController:viewController sender:sender showOnlyLogins:YES completion:completion]; } @end
github
emeb/iceRadio-master
freq_plot.m
.m
iceRadio-master/FPGA/rxadc_2/matlab/freq_plot.m
251
utf_8
729973cd5669dfbd3253d8c24f17293e
% freq_plot.m - frequency plot % E. Brombaugh 08-03-16 function freq_plot(x, Fs, title_str) sz = length(x); f = Fs * (((0:sz-1)/sz)-0.5); plot(f, 20*log10(abs(fftshift(fft(x)/sz)))); grid on; title(title_str); xlabel('Freq'); ylabel('dB'); end
github
AlanRace/SpectralAnalysis-master
SpectralAnalysis.m
.m
SpectralAnalysis-master/SpectralAnalysis.m
918
utf_8
aebd04ed17adf1448eaf6128668b3095
%% SpectralAnalysis % Spectral Imaging analysis software function spectralAnalysis = SpectralAnalysis() % Get location of current m-file if(isdeployed()) disp('Initialising MATLAB, please wait...'); path = ctfroot(); disp(path); else path = fileparts(mfilename('fullpath')); % Ensure all folders are on the path addpath(genpath(path)); end % Ensure libraries are on the path addJARsToClassPath(); % Check if SpectralAnalysis folder exists spectralAnalysisHome = [homepath filesep '.SpectralAnalysis']; % TODO: Check last version and if newer then copy over if ~exist(spectralAnalysisHome, 'file') mkdir(spectralAnalysisHome); copyfile([path filesep 'files' filesep 'profiles'], [spectralAnalysisHome filesep 'profiles']) end % TODO: Check version on github to see if update available % Launch spectral analysis interface spectralAnalysis = SpectralAnalysisInterface();
github
AlanRace/SpectralAnalysis-master
parseRegionOfInterestList.m
.m
SpectralAnalysis-master/src/gui/MOOGL/util/parseRegionOfInterestList.m
980
utf_8
24027c8c7e4b292c2b1717cf1a06eeb6
function regionOfInterestList = parseRegionOfInterestList(filename) % parseClusterGroupList Convert XML file to a MATLAB structure. try tree = xmlread(filename); catch error('Failed to read XML file %s.',filename); end % Recurse over child nodes. This could run into problems % with very deeply nested trees. try regionOfInterestList = parseRegionOfInterestListElement(tree.getChildNodes().item(0)); catch err err error('Unable to parse XML file %s.',filename); end function regionOfInterestList = parseRegionOfInterestListElement(regionOfInterestNode) regionOfInterestList = RegionOfInterestList(); childrenNodes = regionOfInterestNode.getChildNodes(); for i = 1:childrenNodes.getLength() element = childrenNodes.item(i-1); nodeName = element.getNodeName(); if(strcmp(nodeName, 'regionOfInterest')) regionOfInterestList.add(parseRegionOfInterestElement(element)); end end
github
AlanRace/SpectralAnalysis-master
parseRegionOfInterestElement.m
.m
SpectralAnalysis-master/src/gui/MOOGL/util/parseRegionOfInterestElement.m
1,660
utf_8
f6ea11108991760769565360ccd5d7a8
function regionOfInterest = parseRegionOfInterestElement(regionOfInterestNode) width = str2num(regionOfInterestNode.getAttributes().getNamedItem('width').getValue()); height = str2num(regionOfInterestNode.getAttributes().getNamedItem('height').getValue()); regionOfInterest = RegionOfInterest(width, height); childrenNodes = regionOfInterestNode.getChildNodes(); for i = 1:childrenNodes.getLength() element = childrenNodes.item(i-1); nodeName = element.getNodeName(); if(strcmp(nodeName, 'name')) regionOfInterest.setName(char(element.getTextContent())); elseif(strcmp(nodeName, 'colour')) r = str2num(element.getAttributes().getNamedItem('red').getValue()); g = str2num(element.getAttributes().getNamedItem('green').getValue()); b = str2num(element.getAttributes().getNamedItem('blue').getValue()); regionOfInterest.setColour(Colour(r, g, b)); elseif(strcmp(nodeName, 'pixelList')) parsePixelList(regionOfInterest, element); end end function parsePixelList(regionOfInterest, pixelListElement) childrenNodes = pixelListElement.getChildNodes(); for i = 1:childrenNodes.getLength() element = childrenNodes.item(i-1); nodeName = element.getNodeName(); if(strcmp(nodeName, 'pixel')) x = str2num(element.getAttributes().getNamedItem('x').getValue()); y = str2num(element.getAttributes().getNamedItem('y').getValue()); regionOfInterest.addPixel(x, y); end end
github
AlanRace/SpectralAnalysis-master
generateFastPreprocessingWorkflow.m
.m
SpectralAnalysis-master/src/util/generateFastPreprocessingWorkflow.m
3,410
utf_8
62867ff2c6a8d4bf25c62ceb33c072de
% Returns empty variable if there is no fast preprocessing workflow % available function fastPreprocessingWorkflow = generateFastPreprocessingWorkflow(workflow) if(~canUseJSpectralAnalysis()) fastPreprocessingWorkflow = []; return; end fastPreprocessingWorkflow = com.alanmrace.JSpectralAnalysis.PreprocessingWorkflow(); numFastMethods = 0; if(isa(workflow, 'PreprocessingWorkflow')) workflow = workflow.workflow; end for i = 1:length(workflow) if(isa(workflow{i}, 'QSTARZeroFilling')) params = workflow{i}.Parameters; fastPreprocessingWorkflow.addMethod(com.alanmrace.JSpectralAnalysis.zerofilling.QSTARZeroFilling(params(1).value, params(2).value, params(3).value)); numFastMethods = numFastMethods + 1; elseif(isa(workflow{i}, 'SynaptZeroFilling')) fastPreprocessingWorkflow.addMethod(com.alanmrace.JSpectralAnalysis.zerofilling.FixedmzListReplaceZeros(workflow{i}.mzsFull)); numFastMethods = numFastMethods + 1; elseif(isa(workflow{i}, 'RebinZeroFilling')) params = workflow{i}.Parameters; fastPreprocessingWorkflow.addMethod(com.alanmrace.JSpectralAnalysis.zerofilling.RebinZeroFilling(params(1).value, params(2).value, params(3).value)); numFastMethods = numFastMethods + 1; elseif(isa(workflow{i}, 'RebinPPMZeroFilling')) params = workflow{i}.Parameters; fastPreprocessingWorkflow.addMethod(com.alanmrace.JSpectralAnalysis.zerofilling.PPMRebinZeroFilling(params(1).value, params(2).value, params(3).value)); numFastMethods = numFastMethods + 1; elseif(isa(workflow{i}, 'InterpolationRebinZeroFilling')) params = workflow{i}.Parameters; fastPreprocessingWorkflow.addMethod(com.alanmrace.JSpectralAnalysis.zerofilling.InterpolationRebinZeroFilling(params(1).value, params(2).value, params(3).value)); numFastMethods = numFastMethods + 1; elseif(isa(workflow{i}, 'InterpolationPPMRebinZeroFilling')) params = workflow{i}.Parameters; fastPreprocessingWorkflow.addMethod(com.alanmrace.JSpectralAnalysis.zerofilling.InterpolationPPMRebinZeroFilling(params(1).value, params(2).value, params(3).value)); numFastMethods = numFastMethods + 1; elseif(isa(workflow{i}, 'GaussianSmoothing')) params = workflow{i}.Parameters; fastPreprocessingWorkflow.addMethod(com.alanmrace.JSpectralAnalysis.smoothing.GaussianSmoothing(params(1).value, params(2).value)); numFastMethods = numFastMethods + 1; elseif(isa(workflow{i}, 'SavitzkyGolaySmoothing')) params = workflow{i}.Parameters; fastPreprocessingWorkflow.addMethod(com.alanmrace.JSpectralAnalysis.smoothing.SavitzkyGolaySmoothing(params(1).value, params(2).value)); numFastMethods = numFastMethods + 1; elseif(isa(workflow{i}, 'TotalIntensitySpectralNormalisation')) fastPreprocessingWorkflow.addMethod(com.alanmrace.JSpectralAnalysis.normalisation.TICNormalisation()); numFastMethods = numFastMethods + 1; elseif(isa(workflow{i}, 'RemoveNegativesBaselineCorrection')) fastPreprocessingWorkflow.addMethod(com.alanmrace.JSpectralAnalysis.baselinecorrection.RemoveNegativesBaselineCorrection()); numFastMethods = numFastMethods + 1; end end if(numFastMethods ~= length(workflow)) fastPreprocessingWorkflow = []; end
github
AlanRace/SpectralAnalysis-master
colouriseData.m
.m
SpectralAnalysis-master/src/util/colouriseData.m
5,789
utf_8
71f28f2156cba34801adb011c541cd56
% colourScale 'r' (red), 'g' (green), 'b' (blue), 'y' (yellow), 'm' % (magenta), 'c' (cyan), 'h' hot, 'p' pink function [image, maxValue, minValue] = colouriseData(data, positiveScaleColour, negativeScaleColour, quant) numBits = 2^16; image = zeros(size(data, 1), size(data, 2), 3, 'uint16'); if(nargin < 4) minValue = min(data(:)); maxValue = max(data(:)); else minValue = -1*quantile(-1*data(:), quant); maxValue = quantile(data(:), quant); end % Ensure that the data starts at 0 if(nargin < 3) data = data - min(data(:)); end positiveData = data; positiveData(data < 0) = 0; positiveData(positiveData > maxValue) = maxValue; positiveData = (positiveData./maxValue) * numBits; switch(positiveScaleColour) case 'r' image(:, :, 1) = positiveData; case 'g' image(:, :, 2) = positiveData; case 'b' image(:, :, 3) = positiveData; case 'y' image(:, :, 1) = positiveData; image(:, :, 2) = positiveData; case 'm' image(:, :, 1) = positiveData; image(:, :, 3) = positiveData; case 'c' image(:, :, 2) = positiveData; image(:, :, 3) = positiveData; case 'h' n = 3/8; positiveDataR = (positiveData./max(positiveData(:))) / n; positiveDataR(positiveDataR > 1) = 1; positiveDataG = (positiveData./max(positiveData(:))) - n; positiveDataG(positiveDataG < 0) = 0; positiveDataG = (positiveDataG / n); positiveDataG(positiveDataG > 1) = 1; positiveDataB = (positiveData./max(positiveData(:))) - (2*n); positiveDataB(positiveDataB < 0) = 0; positiveDataB = (positiveDataB / (1-(2*n))); image(:, :, 1) = positiveDataR * numBits; image(:, :, 2) = positiveDataG * numBits; image(:, :, 3) = positiveDataB * numBits; case 'p' n = 3/8; positiveDataR = (positiveData./max(positiveData(:))) / n; positiveDataR(positiveDataR > 1) = 1; positiveDataG = (positiveData./max(positiveData(:))) - n; positiveDataG(positiveDataG < 0) = 0; positiveDataG = (positiveDataG / n); positiveDataG(positiveDataG > 1) = 1; positiveDataB = (positiveData./max(positiveData(:))) - (2*n); positiveDataB(positiveDataB < 0) = 0; positiveDataB = (positiveDataB / (1-(2*n))); image(:, :, 1) = (sqrt(((2*(positiveData/max(positiveData(:)))) + (positiveDataR)) / 3)) * numBits; image(:, :, 2) = (sqrt(((2*(positiveData/max(positiveData(:)))) + (positiveDataG)) / 3)) * numBits; image(:, :, 3) = (sqrt(((2*(positiveData/max(positiveData(:)))) + (positiveDataB)) / 3)) * numBits; case 'j' m = 64; n = ceil(m/4); u = [(1:1:n)/n ones(1,n-1) (n:-1:1)/n]'; g = ceil(n/2) - (mod(m,4)==1) + (1:length(u))'; r = g + n; b = g - n; g(g>m) = []; r(r>m) = []; b(b<1) = []; % J = zeros(m,3); % J(r,1) = u(1:length(r)); % J(g,2) = u(1:length(g)); % J(b,3) = u(end-length(b)+1:end); positiveDataR = round((positiveData./max(positiveData(:))) * m); tempData = positiveDataR; positiveDataR = zeros(size(positiveDataR)); min(r) for i = min(r):length(r) positiveDataR(tempData == r(i)) = r(i); end imagesc(positiveDataR);figure; positiveDataG = round((positiveData./max(positiveData(:))) * m); tempData = positiveDataG; positiveDataG = zeros(size(positiveDataG)); for i = min(g):length(g) positiveDataG(tempData == g(i)) = g(i); end positiveDataB = round((positiveData./max(positiveData(:))) * m); tempData = positiveDataB; positiveDataB = zeros(size(positiveDataB)); for i = min(b):length(b) positiveDataB(tempData == b(i)) = b(i); end positiveDataR = positiveDataR ./ m; positiveDataG = positiveDataG ./ m; positiveDataB = positiveDataB ./ m; % u = [(1:1:n)/n ones(1,n-1) (n:-1:1)/n]'; % g = ceil(n/2) - 1 + (1:length(u))'; % r = g + n; % b = g - n; % g(g>1) = []; % r(r>1) = []; % b(b<1) = []; % J = zeros(1,3); % J(r,1) = u(1:length(r)); % J(g,2) = u(1:length(g)); % J(b,3) = u(end-length(b)+1:end); image(:, :, 1) = positiveDataR * numBits; image(:, :, 2) = positiveDataG * numBits; image(:, :, 3) = positiveDataB * numBits; end if(nargin > 2) negativeData = data; negativeData(data > 0) = 0; negativeData(negativeData < minValue) = minValue; negativeData = (negativeData./minValue) * numBits; switch(negativeScaleColour) case 'r' image(:, :, 1) = negativeData; case 'g' image(:, :, 2) = negativeData; case 'b' image(:, :, 3) = negativeData; case 'y' image(:, :, 1) = negativeData; image(:, :, 2) = negativeData; case 'm' image(:, :, 1) = negativeData; image(:, :, 3) = negativeData; case 'c' image(:, :, 2) = negativeData; image(:, :, 3) = negativeData; end end % pca5 = positivePCA5 + negativePCA5; % % h = figure('PaperPosition', [0, 0, 4, 10]); % imagesc(pca5); % axis image, axis off % % sizeOfMap = 100; % numOfTicksPos = (floor(sizeOfMap*(thresh/(thresh+threshMin)))-1); % numOfTicksNeg = (floor(sizeOfMap*(threshMin/(thresh+threshMin)))-1); % % map = zeros(numOfTicksPos+numOfTicksNeg+1, 3); % map(1:numOfTicksNeg+1, 1) = 1:-1*(1/numOfTicksNeg):0; % map(1:numOfTicksNeg+1, 3) = 1:-1*(1/numOfTicksNeg):0; % map(numOfTicksNeg+1:end, 2) = 0:(1/numOfTicksPos):1;
github
AlanRace/SpectralAnalysis-master
normaliseRGBChannels.m
.m
SpectralAnalysis-master/src/util/normaliseRGBChannels.m
450
utf_8
caee37c051e3b53b5fe6fd8ab260ee2c
% Normalise RGB channels individually to their min/max values function normalised = normaliseRGBChannels(rgb) normalised = (rgb(:, :, 1) - min(min(rgb(:, :, 1)))) ./ (max(max(rgb(:, :, 1))) - min(min(rgb(:, :, 1)))); normalised(:, :, 2) = (rgb(:, :, 2) - min(min(rgb(:, :, 2)))) ./ (max(max(rgb(:, :, 2))) - min(min(rgb(:, :, 2)))); normalised(:, :, 3) = (rgb(:, :, 3) - min(min(rgb(:, :, 3)))) ./ (max(max(rgb(:, :, 3))) - min(min(rgb(:, :, 3))));
github
AlanRace/SpectralAnalysis-master
mip_plsa.m
.m
SpectralAnalysis-master/src/processing/postprocessing/mip_plsa/mip_plsa.m
2,545
utf_8
a33a2f153f46631f3f3e40b96b2f620a
% function that performs a probabilistic latent semantic analysis of the % input data matrix % % input % % X SxC matrix with C variables (channels) and S % observations (spectra), i.e. each row consists of % one observation % numComponents decompose the data into that many components (tissue % types T) % relativeChange stopping criterion, terminated if relative change in % fit falls below that threshold % maxIter maximum number of iterations, default is 500 % % output % % ct CxT matrix of characteristic spectra % ts TxS matrix of mixture vectors % loglik log-likelihood of the data % % for details see % % T. Hofmann. Probabilistic Latent Semantic Analysis, Uncertainty in Artificial Intelligence, 1999. % we use the matrix formulation to speed up the calculations in MATLAB (see also Kaban and Verbeek - http://www.cs.bham.ac.uk/~axk/ML_CODE/PLSA.m, http://lear.inrialpes.fr/~verbeek/software) % % (C)2008 Michael Hanselmann % function [ct, ts, loglik] = mip_plsa(X, numComponents, relativeChange, maxIter) % variable initialization Xt = X'; [numChannels, numSpectra] = size(Xt); ct = mip_col_normalize(rand(numChannels, numComponents)); ts = mip_col_normalize(ones(numComponents, numSpectra)); if nargin < 4 maxIter = 500; % default value end lastChange = 1/eps; err = 1e10; iter = 0; while(lastChange > relativeChange && iter < maxIter) % update rules (EM algorithm as described by Hofmann99) ts = mip_col_normalize(ts .* (ct' * (Xt ./ (ct*ts + eps)))); ct = mip_col_normalize(ct .* ((Xt ./ ( ct*ts + eps)) * ts')); % check model fit (here we use a least-squares fit, but this can % easily be replaced by a KL-divergence fit); % we check for the RELATIVE change in fit model = (ones(numChannels, 1) * sum(Xt, 1))' .* (ct * ts)'; errold = err; err = sum(sum((Xt - model').^2)); lastChange = abs((err - errold)/err); iter = iter + 1; if(mod(iter, 25) == 0 || iter == 1) disp(['...iteration ', num2str(iter), ', relative change ', num2str(lastChange)]); end end % data log-likelihood loglik = sum(sum(Xt.*log(ct*ts + eps))); end function X = mip_col_normalize(X) % normalize column-wise sumX = sum(X); X = X ./ (ones(size(X, 1), 1) * (sumX + (sumX==0))); end
github
AlanRace/SpectralAnalysis-master
mip_calculateAICcTrace.m
.m
SpectralAnalysis-master/src/processing/postprocessing/mip_plsa/mip_calculateAICcTrace.m
1,124
utf_8
bf4341f53191bed7c71966a4d481e809
% Function that calculates the AICc-trace from a given likelihood vector % and the data % % input % % X SxC matrix with C variables (channels) and S % observations (spectra), i.e. each row consists of % one observation % mzVector vector with m/z-positions (of dimension Cx1) % xyPos vector with x- and y-positions corresponding to the % spectra in X (of dimension Sx2) % logliks vector of data likelihoods % % output % % AICc vector of AICc-values (of dimension equal to logliks) % currPenalty last value of penalty term % % (C)2008 Michael Hanselmann % function [AICc, currPenalty] = mip_calculateAICcTrace(X, mzVector, xyPos, logliks) % AICc criterion for optimal model selection noiseVar = mip_simpleNoiseEstimation(X, mzVector, xyPos); N = size(X, 1) * size(X, 2); for i=1:length(logliks) K = i*(size(X, 1) + size(X, 2)); AICc(i) = -2*logliks(i)/N + 2*K/N*noiseVar + 1/N*2*K*(K+1)/(N-K-1); currPenalty = 2*K*noiseVar/N + 1/N*2*K*(K+1)/(N-K-1); end end
github
AlanRace/SpectralAnalysis-master
mip_showPLSAResults.m
.m
SpectralAnalysis-master/src/processing/postprocessing/mip_plsa/mip_showPLSAResults.m
1,534
utf_8
209115723076781acbdb50dc817f8e10
% function that plots the pLSA results % % input % % ts TxS matrix with C variables (channels) and T % tissue types - i.e. the matrix holding the abundance % maps for the T tissue types % ct CxT matrix of pure, characteristic spectra % xyPos vector with x- and y-positions corresponding to the % spectra in X (of dimension Sx2) % mzVector vector with m/z-positions (of dimension Cx1) % scale rescale abundance maps to [0,1] 0/1 % % output % % none % % (C)2008 Michael Hanselmann % function mip_showPLSAResults(ts, ct, xyPos, mzVector, scale) % set defaults if(nargin < 5) scale = 1; end minX = min(xyPos(:,1)); maxX = max(xyPos(:,1)); minY = min(xyPos(:,2)); maxY = max(xyPos(:,2)); figure; subplot(size(ts, 1), 2, 1); % write ts-entries to images for i=1:size(ts, 1) Img = zeros(maxY-minY+1, maxX-minX+1); for j=1:size(xyPos, 1) Img(xyPos(j, 2) - minY + 1, xyPos(j, 1) - minX + 1) = ts(i, j); end % abundance maps subplot(size(ts, 1), 2, 2*i-1); imagesc(Img); colormap gray; axis equal tight; if(scale~=0) caxis([0, 1]); end colorbar; hold on; % characteristic, "pure" spectra subplot(size(ts, 1), 2, 2*i); bar(mzVector, ct(:, i)); axis tight; end end
github
AlanRace/SpectralAnalysis-master
mip_plotSparsity.m
.m
SpectralAnalysis-master/src/processing/postprocessing/mip_plsa/mip_plotSparsity.m
1,819
utf_8
08f2c12c944a7ec0129c9c73aea3ce13
% function that claculates the sparsity of the mixture vectors of the % decomposition result % % input % % X SxC matrix with C variables (channels) and S % observations (spectra), i.e. each row consists of % one observation % mzVector vector with m/z-positions (of dimension Cx1) % mzVector2 peak-picked mzVector % featureMask indicator array with 0s and 1s indicating which peak % positions have been selected % ct CxT matrix with characteristic spectra (see mip_plsa) % % output % % none % % this function uses Hoyer's spasity measure as described in "Non-negative Matrix Factorization with Sparseness Constraints" (2004) % % (C)2008 Michael Hanselmann % function mip_plotSparsity(X, mzVector, mzVector2, featureMask, ct) % sparsity calculations, see Hoyer01 numComponents = size(ct, 2); sparseness = zeros(size(X, 2), 1); sqrtN = sqrt(numComponents); for i=1:size(X, 2); xVec = (ct(i, :)/norm(ct(i, :)))'; sparseness(i) = ((sqrtN - sum(xVec, 1))/sqrt(sum(xVec.*xVec, 1)))/(sqrtN - 1); % normally we would have to use abs(xVec) in L1-norm, but all entries are positive anyway end j = 1; res = zeros(1, size(featureMask, 1)); for i=1:size(featureMask, 1) if(featureMask(i)==1) res(i) = sparseness(j); j = j + 1; end end figure; % data plot ax(1) = subplot(2, 1, 1); bar(mzVector2, ct); title(['bar plot of the ', num2str(numComponents), ' component types (left to right)']); % sparsity plot ax(2) = subplot(2, 1, 2); bar(min(mzVector):(mzVector(2)-mzVector(1)):max(mzVector), res); title('sparsity indicating decisive m/z positions'); linkaxes(ax, 'x'); end
github
AlanRace/SpectralAnalysis-master
mip_pickPeaksSimple.m
.m
SpectralAnalysis-master/src/processing/postprocessing/mip_plsa/mip_pickPeaksSimple.m
5,453
utf_8
668c9ea20d0bf52ad12272c0aeccca20
% Function that performs feature extraction by peak-picking % % input % % X SxC matrix with C variables (channels) and S % observations (spectra), i.e. each row consists of % one observation % mzVector vector with m/z-positions (of dimension Cx1) % ppThreshold value between 0 and 1, threshold for peak picking % pp_ga_size size of Gaussian filter for smoothing % pp_ga_sigma sigma for Gaussian filter % plotResults plot results 0/1 % % output % % Xreduced C'xS matrix of reduced data (with C' peaks) % mzVectorReduced vector with m/z-positions (of dimension C'x1) % mask 0/1-mask of peak-positions and size C'x1 % % (C)2008 Michael Hanselmann % function [Xreduced, mzVectorReduced, mask] = mip_pickPeaksSimple(X, mzVector, ppThreshold, pp_ga_size, pp_ga_sigma, plotResults) % default settings if nargin < 6 plotResults = 0; end if nargin < 5 pp_ga_sigma = 1; end if nargin < 4 pp_ga_size = 4; end if nargin < 3 ppThreshold = 0.0005; end spectra = X; % calculate sum spectrum and put it in range [0, 1] spectraSum = sum(spectra, 1); spectraSum = (spectraSum-min(spectraSum)); spectraSum = spectraSum/(max(spectraSum) + 1e-10); % peak picking % ...smoothing ga_x = -pp_ga_size:1:pp_ga_size; ga_f = exp( -(ga_x.^2)/(2*pp_ga_sigma^2) ); ga_f = ga_f / sum(sum(ga_f)); spectrumSmoothedShifted = conv(spectraSum, ga_f); spectrumSmoothed = zeros(1, size(spectraSum, 2)); for i=1:(size(spectrumSmoothedShifted, 2)-2*pp_ga_size) spectrumSmoothed(1, i) = spectrumSmoothedShifted(1, i+pp_ga_size); end % ...detection of maxima/minima in smoothed sum spectrum [maxima, minima] = mip_peakdetect(spectrumSmoothed, ppThreshold); % now have a look at the unsmoothed data again % smoothing can cause peak shifts, so take the maximum in the % unsmoothed data by "hill-climbing", i.e. proceed to left and right as % long as the slope is positive and take the maximum for i=1:size(maxima, 1) % hill-climbing to left k = maxima(i, 1); while(k>1 && spectraSum(k-1)>spectraSum(k)) k = k - 1; end % hill-climbing to right l = maxima(i, 1); while(l<length(spectraSum) && spectraSum(l+1)>spectraSum(l)) l = l + 1; end if(spectraSum(k) > spectraSum(l)) newMaxPos = k; else newMaxPos = l; end maxima(i, 1) = newMaxPos; maxima(i, 2) = spectraSum(newMaxPos); end for i=1:size(minima, 1) % down-climbing to left k = minima(i, 1); while(k>1 && spectraSum(k-1)<spectraSum(k)) k = k - 1; end % down-climbing to right l = minima(i, 1); while(l<length(spectraSum) && spectraSum(l+1)<spectraSum(l)) l = l + 1; end newMinPos = min(k, l); minima(i, 1) = newMinPos; minima(i, 2) = spectraSum(newMinPos); end % make mask to eliminate channels that are not picked by the peak % picker mask = zeros(size(spectra, 2), 1); for j=1:size(maxima, 1) mask(maxima(j, 1), 1) = 1; end % just take values at peak position (i.e. value for max channel for all % spatial locations) spectraReduced = spectra(:, mask>0); mzVectorReduced = mzVector(mask>0); % take sum over complete peak width (i.e. we sum over a % certain m/z range with regard to a spatial location) % basically go to left and right from peak position until spectrum % rises again minMask = zeros(size(spectra, 2), 1); for j=1:size(minima, 1) minMask(minima(j, 1), 1) = 1; end j = 1; numMax = 1; while(j < length(mask)) % search next maximum while(j < length(mask) && mask(j) == 0) j = j+1; end if(mask(j) == 1) % real maximum, i.e. not just last entry lastMax = j; % search next minimum (from maximum position) j = j+1; while(j < length(mask) && spectraSum(j) < spectraSum(j-1)) j = j+1; end nextMin = j; % search last minimum (from maximum position) j = lastMax - 1; while(j > 1 && spectraSum(j) < spectraSum(j+1)) j = j-1; end lastMin = j; j = lastMax + 1; lastMin = max(1, lastMin); nextMin = min(length(mask), nextMin); spectraReduced(:, numMax) = sum(spectra(:, lastMin:1:nextMin), 2); numMax = numMax+1; end end Xreduced = spectraReduced; % visualization of peak positions if(plotResults) figure; plot(mzVector, spectraSum); axis tight; hold on; plot(mzVector, spectrumSmoothed, 'm'); axis tight; hold on; if(size(maxima, 1) > 0 && size(minima, 1) > 0) plot(mzVector(maxima(:,1)), maxima(:,2), 'r*'); hold on; plot(mzVector(minima(:,1)), minima(:,2), 'g*'); end title('Picked peak positions (sum spectrum)'); xlabel([num2str(mzVector(1)), ' to ', num2str(mzVector(length(mzVector))), ' (m/z, Da)']); ylabel('intensity'); end end
github
AlanRace/SpectralAnalysis-master
mip_simpleNoiseEstimation.m
.m
SpectralAnalysis-master/src/processing/postprocessing/mip_plsa/mip_simpleNoiseEstimation.m
1,757
utf_8
65d1d1ba797641d35f16b1beff966a1e
% Function that estimates the noise in the data by first smoothing the data % (spatially) and then taking the median of the residual sum of squares % % input % % X SxC matrix with C variables (channels) and S % observations (spectra), i.e. each row consists of % one observation % mzVector vector with m/z-positions (of dimension Cx1) % xyPos vector with x- and y-positions corresponding to the % spectra in X (of dimension Sx2) % % output % % noiseVarEstimate an estimate of the noise variance in the data (scalar) % % % (C)2008 Michael Hanselmann % function noiseVarEstimate = mip_simpleNoiseEstimation(X, mzVector, xyPos) % make cube spectra = X; minX = min(xyPos(:,1)); maxX = max(xyPos(:,1)); minY = min(xyPos(:,2)); maxY = max(xyPos(:,2)); dimensions = [maxY-minY+1, maxX-minX+1]; cube = reshape(double(spectra), dimensions(1), dimensions(2), length(mzVector)); % average spectrum at each position by averaging over the area given by % steps: (2*steps+1)^2-box function steps = 1; cubeAv = double(zeros(size(cube))); for i=1+steps:dimensions(1)-steps for j=1+steps:dimensions(2)-steps for k=i-steps:i+steps for l=j-steps:j+steps cubeAv(i, j, :) = cubeAv(i, j, :) + 1/(2*steps+1)^2 * cube(k, l, :); end end end end % calculate median RSS, omit border area cubeRSS = (cube(1+steps:dimensions(1)-steps,1+steps:dimensions(2)-steps, :) - cubeAv(1+steps:dimensions(1)-steps,1+steps:dimensions(2)-steps, :)).^2; noiseVarEstimate = median(cubeRSS(:)); % mean also possible but less robust end
github
qintonguav/TheiaSfM-master
flann_search.m
.m
TheiaSfM-master/libraries/flann/src/matlab/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
qintonguav/TheiaSfM-master
flann_load_index.m
.m
TheiaSfM-master/libraries/flann/src/matlab/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
qintonguav/TheiaSfM-master
test_flann.m
.m
TheiaSfM-master/libraries/flann/src/matlab/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
qintonguav/TheiaSfM-master
flann_free_index.m
.m
TheiaSfM-master/libraries/flann/src/matlab/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
qintonguav/TheiaSfM-master
flann_save_index.m
.m
TheiaSfM-master/libraries/flann/src/matlab/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
qintonguav/TheiaSfM-master
flann_set_distance_type.m
.m
TheiaSfM-master/libraries/flann/src/matlab/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
qintonguav/TheiaSfM-master
flann_build_index.m
.m
TheiaSfM-master/libraries/flann/src/matlab/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
ShaoqingRen/py-faster-rcnn-master
voc_eval.m
.m
py-faster-rcnn-master/lib/datasets/VOCdevkit-matlab-wrapper/voc_eval.m
1,332
utf_8
3ee1d5373b091ae4ab79d26ab657c962
function res = voc_eval(path, comp_id, test_set, output_dir) VOCopts = get_voc_opts(path); VOCopts.testset = test_set; for i = 1:length(VOCopts.classes) cls = VOCopts.classes{i}; res(i) = voc_eval_cls(cls, VOCopts, comp_id, output_dir); end fprintf('\n~~~~~~~~~~~~~~~~~~~~\n'); fprintf('Results:\n'); aps = [res(:).ap]'; fprintf('%.1f\n', aps * 100); fprintf('%.1f\n', mean(aps) * 100); fprintf('~~~~~~~~~~~~~~~~~~~~\n'); function res = voc_eval_cls(cls, VOCopts, comp_id, output_dir) test_set = VOCopts.testset; year = VOCopts.dataset(4:end); addpath(fullfile(VOCopts.datadir, 'VOCcode')); res_fn = sprintf(VOCopts.detrespath, comp_id, cls); recall = []; prec = []; ap = 0; ap_auc = 0; do_eval = (str2num(year) <= 2007) | ~strcmp(test_set, 'test'); if do_eval % Bug in VOCevaldet requires that tic has been called first tic; [recall, prec, ap] = VOCevaldet(VOCopts, comp_id, cls, true); ap_auc = xVOCap(recall, prec); % force plot limits ylim([0 1]); xlim([0 1]); print(gcf, '-djpeg', '-r0', ... [output_dir '/' cls '_pr.jpg']); end fprintf('!!! %s : %.4f %.4f\n', cls, ap, ap_auc); res.recall = recall; res.prec = prec; res.ap = ap; res.ap_auc = ap_auc; save([output_dir '/' cls '_pr.mat'], ... 'res', 'recall', 'prec', 'ap', 'ap_auc'); rmpath(fullfile(VOCopts.datadir, 'VOCcode'));
github
stanchiang/constellation-master
colamd_test.m
.m
constellation-master/masteringopencv2012/Chapter4_StructureFromMotion/3rdparty/SSBA-4.0/COLAMD/MATLAB/colamd_test.m
11,737
utf_8
1bbab37469571534db129da1e1531e5b
function colamd_test %COLAMD_TEST test colamd2 and symamd2 % Example: % colamd_test % % COLAMD and SYMAMD testing function. Here we try to give colamd2 and symamd2 % every possible type of matrix and erroneous input that they may encounter. % We want either a valid permutation returned or we want them to fail % gracefully. % % You are prompted as to whether or not the colamd2 and symand routines and % the test mexFunctions are to be compiled. % % See also colamd2, symamd2 % Copyright 1998-2007, Timothy A. Davis, and Stefan Larimore % Developed in collaboration with J. Gilbert and E. Ng. help colamd_test fprintf ('Compiling colamd2, symamd2, and test mexFunctions.\n') ; colamd_make ; d = '' ; if (~isempty (strfind (computer, '64'))) d = '-largeArrayDims' ; end cmd = sprintf (... 'mex -DDLONG -O %s -I../../SuiteSparse_config -I../Include ', d) ; src = '../Source/colamd.c ../Source/colamd_global.c' ; eval ([cmd 'colamdtestmex.c ' src]) ; eval ([cmd 'symamdtestmex.c ' src]) ; fprintf ('Done compiling.\n') ; fprintf ('\nThe following codes will be tested:\n') ; which colamd2 which symamd2 which colamd2mex which symamd2mex which colamdtestmex which symamdtestmex fprintf ('\nStarting the tests. Please be patient.\n') ; h = waitbar (0, 'COLAMD test') ; rand ('state', 0) ; randn ('state', 0) ; A = sprandn (500,500,0.4) ; p = colamd2 (A, [10 10 1]) ; check_perm (p, A) ; p = colamd2 (A, [2 7 1]) ; check_perm (p, A) ; p = symamd2 (A, [10 1]) ; check_perm (p, A) ; p = symamd2 (A, [7 1]) ; check_perm (p, A) ; p = symamd2 (A, [4 1]) ; check_perm (p, A) ; fprintf ('Null matrices') ; A = zeros (0,0) ; A = sparse (A) ; [p, stats] = colamd2 (A, [10 10 0]) ; %#ok check_perm (p, A) ; [p, stats] = symamd2 (A, [10 0]) ; %#ok check_perm (p, A) ; A = zeros (0, 100) ; A = sparse (A) ; [p, stats] = colamd2 (A, [10 10 0]) ; %#ok check_perm (p, A) ; A = zeros (100, 0) ; A = sparse (A) ; [p, stats] = colamd2 (A, [10 10 0]) ; check_perm (p, A) ; fprintf (' OK\n') ; fprintf ('Matrices with a few dense row/cols\n') ; for trial = 1:20 waitbar (trial/20, h, 'COLAMD: with dense rows/cols') ; % random square unsymmetric matrix A = rand_matrix (1000, 1000, 1, 10, 20) ; for tol = [0:.1:2 3:20 1e6] [p, stats] = colamd2 (A, [tol tol 0]) ; %#ok check_perm (p, A) ; B = A + A' ; [p, stats] = symamd2 (B, [tol 0]) ; %#ok check_perm (p, A) ; [p, stats] = colamd2 (A, [tol 1 0]) ; %#ok check_perm (p, A) ; [p, stats] = colamd2 (A, [1 tol 0]) ; %#ok check_perm (p, A) ; end end fprintf (' OK\n') ; fprintf ('General matrices\n') ; for trial = 1:400 waitbar (trial/400, h, 'COLAMD: general') ; % matrix of random mtype mtype = irand (3) ; A = rand_matrix (2000, 2000, mtype, 0, 0) ; p = colamd2 (A) ; check_perm (p, A) ; if (mtype == 3) p = symamd2 (A) ; check_perm (p, A) ; end end fprintf (' OK\n') ; fprintf ('Test error handling with invalid inputs\n') ; % Check different erroneous input. for trial = 1:30 waitbar (trial/30, h, 'COLAMD: error handling') ; A = rand_matrix (1000, 1000, 2, 0, 0) ; [m n] = size (A) ; for err = 1:13 p = Tcolamd (A, [n n 0 0 err]) ; if (p ~= -1) %#ok check_perm (p, A) ; end if (err == 1) % check different (valid) input args to colamd2 p = Acolamd (A) ; p2 = Acolamd (A, [10 10 0 0 0]) ; if (any (p ~= p2)) error ('colamd2: mismatch 1!') ; end [p2 stats] = Acolamd (A) ; %#ok if (any (p ~= p2)) error ('colamd2: mismatch 2!') ; end [p2 stats] = Acolamd (A, [10 10 0 0 0]) ; if (any (p ~= p2)) error ('colamd2: mismatch 3!') ; end end B = A'*A ; p = Tsymamd (B, [n 0 err]) ; if (p ~= -1) %#ok check_perm (p, A) ; end if (err == 1) % check different (valid) input args to symamd2 p = Asymamd (B) ; check_perm (p, A) ; p2 = Asymamd (B, [10 0 0]) ; if (any (p ~= p2)) error ('symamd2: mismatch 1!') ; end [p2 stats] = Asymamd (B) ; %#ok if (any (p ~= p2)) error ('symamd2: mismatch 2!') ; end [p2 stats] = Asymamd (B, [10 0 0]) ; %#ok if (any (p ~= p2)) error ('symamd2: mismatch 3!') ; end end end end fprintf (' OK\n') ; fprintf ('Matrices with a few empty columns\n') ; for trial = 1:400 % some are square, some are rectangular n = 0 ; while (n < 5) A = rand_matrix (1000, 1000, irand (2), 0, 0) ; [m n] = size (A) ; end % Add 5 null columns at random locations. null_col = randperm (n) ; null_col = sort (null_col (1:5)) ; A (:, null_col) = 0 ; % Order the matrix and make sure that the null columns are ordered last. [p, stats] = colamd2 (A, [1e6 1e6 0]) ; check_perm (p, A) ; % if (stats (2) ~= 5) % stats (2) % error ('colamd2: wrong number of null columns') ; % end % find all null columns in A null_col = find (sum (spones (A), 1) == 0) ; nnull = length (null_col) ; %#ok if (any (null_col ~= p ((n-4):n))) error ('colamd2: Null cols are not ordered last in natural order') ; end end fprintf (' OK\n') ; fprintf ('Matrices with a few empty rows and columns\n') ; for trial = 1:400 waitbar (trial/400, h, 'COLAMD: with empty rows/cols') ; % symmetric matrices n = 0 ; while (n < 5) A = rand_matrix (1000, 1000, 3, 0, 0) ; [m n] = size (A) ; end % Add 5 null columns and rows at random locations. null_col = randperm (n) ; null_col = sort (null_col (1:5)) ; A (:, null_col) = 0 ; A (null_col, :) = 0 ; % Order the matrix and make sure that the null rows/cols are ordered last. [p,stats] = symamd2 (A, [10 0]) ; check_perm (p, A) ; % find actual number of null rows and columns Alo = tril (A, -1) ; nnull = length (find (sum (Alo') == 0 & sum (Alo) == 0)) ; %#ok if (stats (2) ~= nnull | nnull < 5) %#ok error ('symamd2: wrong number of null columns') ; end if (any (null_col ~= p ((n-4):n))) error ('symamd2: Null cols are not ordered last in natural order') ; end end fprintf (' OK\n') ; fprintf ('Matrices with a few empty rows\n') ; % Test matrices with null rows inserted. for trial = 1:400 waitbar (trial/400, h, 'COLAMD: with null rows') ; m = 0 ; while (m < 5) A = rand_matrix (1000, 1000, 2, 0, 0) ; [m n] = size (A) ; %#ok end % Add 5 null rows at random locations. null_row = randperm (m) ; null_row = sort (null_row (1:5)) ; A (null_row, :) = 0 ; p = colamd2 (A, [10 10 0]) ; check_perm (p, A) ; if (stats (1) ~= 5) error ('colamd2: wrong number of null rows') ; end end fprintf (' OK\n') ; fprintf ('\ncolamd2 and symamd2: all tests passed\n\n') ; close (h) ; %------------------------------------------------------------------------------- function [p,stats] = Acolamd (S, knobs) % Acolamd: compare colamd2 and Tcolamd results if (nargin < 3) if (nargout == 1) [p] = colamd2 (S) ; [p1] = Tcolamd (S, [10 10 0 0 0]) ; else [p, stats] = colamd2 (S) ; [p1, stats1] = Tcolamd (S, [10 10 0 0 0]) ; %#ok end else if (nargout == 1) [p] = colamd2 (S, knobs (1:3)) ; [p1] = Tcolamd (S, knobs) ; else [p, stats] = colamd2 (S, knobs (1:3)) ; [p1, stats1] = Tcolamd (S, knobs) ; %#ok end end check_perm (p, S) ; check_perm (p1, S) ; if (any (p1 ~= p)) error ('Acolamd mismatch!') ; end %------------------------------------------------------------------------------- function [p,stats] = Asymamd (S, knobs) % Asymamd: compare symamd2 and Tsymamd results if (nargin < 3) if (nargout == 1) [p] = symamd2 (S) ; [p1] = Tsymamd (S, [10 0 0]) ; else [p, stats] = symamd2 (S) ; [p1, stats1] = Tsymamd (S, [10 0 0]) ; %#ok end else if (nargout == 1) [p] = symamd2 (S, knobs (1:2)) ; [p1] = Tsymamd (S, knobs) ; else [p, stats] = symamd2 (S, knobs (1:2)) ; [p1, stats1] = Tsymamd (S, knobs) ; %#ok end end if (any (p1 ~= p)) error ('Asymamd mismatch!') ; end %------------------------------------------------------------------------------- function check_perm (p, A) % check_perm: check for a valid permutation vector if (isempty (A) & isempty (p)) %#ok % empty permutation vectors of empty matrices are OK return end if (isempty (p)) error ('bad permutation: cannot be empty') ; end [m n] = size (A) ; [pm pn] = size (p) ; if (pn == 1) % force p to be a row vector p = p' ; [pm pn] = size (p) ; end if (n ~= pn) error ('bad permutation: wrong size') ; end if (pm ~= 1) ; % p must be a vector error ('bad permutation: not a vector') ; else if (any (sort (p) - (1:pn))) error ('bad permutation') ; end end %------------------------------------------------------------------------------- function i = irand (n) % irand: return a random integer between 1 and n i = min (n, 1 + floor (rand * n)) ; %------------------------------------------------------------------------------- function A = rand_matrix (nmax, mmax, mtype, drows, dcols) % rand_matrix: return a random sparse matrix % % A = rand_matrix (nmax, mmax, mtype, drows, dcols) % % A binary matrix of random size, at most nmax-by-mmax, with drows dense rows % and dcols dense columns. % % mtype 1: square unsymmetric (mmax is ignored) % mtype 2: rectangular % mtype 3: symmetric (mmax is ignored) n = irand (nmax) ; if (mtype ~= 2) % square m = n ; else m = irand (mmax) ; end A = sprand (m, n, 10 / max (m,n)) ; if (drows > 0) % add dense rows for k = 1:drows i = irand (m) ; nz = irand (n) ; p = randperm (n) ; p = p (1:nz) ; A (i,p) = 1 ; end end if (dcols > 0) % add dense cols for k = 1:dcols j = irand (n) ; nz = irand (m) ; p = randperm (m) ; p = p (1:nz) ; A (p,j) = 1 ; end end A = spones (A) ; % ensure that there are no empty columns d = find (full (sum (A)) == 0) ; %#ok A (m,d) = 1 ; %#ok % ensure that there are no empty rows d = find (full (sum (A,2)) == 0) ; %#ok A (d,n) = 1 ; %#ok if (mtype == 3) % symmetric A = A + A' + speye (n) ; end A = spones (A) ; %------------------------------------------------------------------------------- function [p,stats] = Tcolamd (S, knobs) % Tcolamd: run colamd2 in a testing mode if (nargout <= 1 & nargin == 1) %#ok p = colamdtestmex (S) ; elseif (nargout <= 1 & nargin == 2) %#ok p = colamdtestmex (S, knobs) ; elseif (nargout == 2 & nargin == 1) %#ok [p, stats] = colamdtestmex (S) ; elseif (nargout == 2 & nargin == 2) %#ok [p, stats] = colamdtestmex (S, knobs) ; else error ('colamd2: incorrect number of input and/or output arguments') ; end if (p (1) ~= -1) [ignore, q] = etree (S (:,p), 'col') ; p = p (q) ; check_perm (p, S) ; end %------------------------------------------------------------------------------- function [p, stats] = Tsymamd (S, knobs) % Tsymamd: run symamd2 in a testing mode if (nargout <= 1 & nargin == 1) %#ok p = symamdtestmex (S) ; elseif (nargout <= 1 & nargin == 2) %#ok p = symamdtestmex (S, knobs) ; elseif (nargout == 2 & nargin == 1) %#ok [p, stats] = symamdtestmex (S) ; elseif (nargout == 2 & nargin == 2) %#ok [p, stats] = symamdtestmex (S, knobs) ; else error ('symamd2: incorrect number of input and/or output arguments') ; end if (p (1) ~= -1) [ignore, q] = etree (S (p,p)) ; p = p (q) ; check_perm (p, S) ; end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
train_classes_20x1_smooth_lsvm_topK_bagmine_greedycover.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/mil/train_classes_20x1_smooth_lsvm_topK_bagmine_greedycover.m
10,648
utf_8
46680d10d8be797f27b215d668e6f8db
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2014, Hyun Oh Song % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function models = train_classes_20x1_smooth_lsvm_topK_bagmine_greedycover(... classid, varargin) % represents both positive and negative images as bags and refines initial detector by minimizing smooth latent svm loss. % initialize and fix the random seed randn('state', 1); rand('state', 1); % addpath addpath(genpath('minFunc_2012/')); addpath('projsplx/'); trainset = 'trainval'; year = '2007'; if ischar(classid), classid = str2double(classid); end % cast optional parameters into double if length(varargin) ~= 0 for i = 1:length(varargin) if mod(i,2)==0 if ischar(varargin{i}), varargin{i} = str2double(varargin{i}); end end end end ip = inputParser; ip.addRequired('trainset', @isstr); ip.addRequired('year', @isstr); ip.addRequired('classid', @isscalar); ip.addParamValue('sharpness', 100, @isscalar); ip.addParamValue('svm_mu', 0.01, @isscalar); ip.addParamValue('topK', 15, @isscalar); ip.addParamValue('alpha', 0.95, @isscalar); ip.addParamValue('K1', 0.5, @isscalar); ip.addParamValue('K2', 1.0, @isscalar); ip.addParamValue('nms_threshold', 0.3, @isscalar); ip.addParamValue('loss_type', 'SmoothHinge', @isstr); ip.addParamValue('svm_C', 10^-3, @isscalar); ip.addParamValue('bias_mult', 10, @isscalar); ip.addParamValue('pos_loss_weight', 2, @isscalar); ip.addParamValue('layer', 'fc7', @isstr); ip.addParamValue('fine_tuned', 0, @isscalar); ip.addParamValue('use_flipped', 0, @isscalar); ip.addParamValue('target_norm', 20, @isscalar); ip.parse(trainset, year, classid, varargin{:}); opts = ip.Results; fprintf('\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'); fprintf('Training options:\n'); disp(opts); fprintf('~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n'); conf = voc_config(); clss = conf.pascal.VOCopts.classes; clss = clss(classid); num_clss = 1; dataset.year = year; dataset.trainset = trainset; dataset.image_ids = textread(sprintf(conf.pascal.VOCopts.imgsetpath, trainset), '%s'); dataset.image_ids_small = dataset.image_ids(randperm(length(dataset.image_ids), 1000)); dataset.pos_image_ids = dataset.image_ids; % ------------------------------------------------------------------------ load('class_pos_images.mat'); pos_image_ids = class_pos_images(classid).ids; neg_image_ids = setdiff(dataset.image_ids, pos_image_ids); dataset.neg_image_ids = neg_image_ids; % sample_pos_image_ids = pos_image_ids(1:40); % sample_neg_image_ids = neg_image_ids(1:200); sample_pos_image_ids = pos_image_ids; sample_neg_image_ids = neg_image_ids; num_pos_images = length(sample_pos_image_ids); num_neg_images = length(sample_neg_image_ids); % ------------------------------------------------------------------------ % ------------------------------------------------------------------------ % Get or compute the average norm of the features if ~exist('feat_stats','file') mkdir('feat_stats'); end save_file = sprintf('feat_stats/stats_%s_%s_layer_%s_finetuned_%d', ... trainset, year, opts.layer, opts.fine_tuned); try ld = load(save_file); opts.feat_norm_mean = ld.feat_norm_mean; clear ld; catch [feat_norm_mean, stddev] = feat_stats_hos(trainset, year, opts.layer, opts.fine_tuned); save(save_file, 'feat_norm_mean', 'stddev'); opts.feat_norm_mean = feat_norm_mean; end fprintf('average norm = %.3f\n', opts.feat_norm_mean); % ------------------------------------------------------------------------ % ------------------------------------------------------------------------ % Load initial classifier latent_iter = 0; load([conf.paths.model_dir, ... 'latentiter_' num2str(latent_iter) '_clss_' clss{1}, ... '_C_' num2str(opts.svm_C), ... '_B_' num2str(opts.bias_mult), ... '_w1_' num2str(opts.pos_loss_weight), ... '_losstype_' opts.loss_type,... '_sharpness_' num2str(opts.sharpness),... '_alpha_' num2str(opts.alpha),... '_K1_' num2str(opts.K1), ... '_K2_' num2str(opts.K2), ... '_nms_' num2str(opts.nms_threshold), ... '_20x1_smooth_greedycover_final.mat'], 'models'); % ------------------------------------------------------------------------ % ------------------------------------------------------------------------ % Train with hard negative mining max_latent_iter = 10; th = tic(); % measure training time for latent_iter = 1:max_latent_iter fprintf('latent positive update %d\n', latent_iter); save_filename = [conf.paths.model_dir, ... 'latentiter_' num2str(latent_iter) '_clss_' clss{1}, ... '_C_' num2str(opts.svm_C), ... '_B_' num2str(opts.bias_mult), ... '_w1_' num2str(opts.pos_loss_weight), ... '_losstype_' opts.loss_type, ... '_sharpness_' num2str(opts.sharpness), ... '_mu_' num2str(opts.svm_mu), ... '_alpha_' num2str(opts.alpha),... '_K1_' num2str(opts.K1),... '_K2_' num2str(opts.K2),... '_nms_' num2str(opts.nms_threshold),.... '_topK_' num2str(opts.topK), ... '_20x1_smooth_topK_bagmine_greedycover_final.mat']; % check if we already computed the file. if exist(save_filename, 'file') ~= 0 load(save_filename, 'models'); fprintf('models exists for latent iter %d loaded.\n', latent_iter); else % Get top K windows in all positive examples into the cache X_pos = get_all_features_topK_bagmine(... models, dataset, opts, sample_pos_image_ids); % Get top K windows in all negative examples into the cache X_neg = get_all_features_topK_bagmine(... models, dataset, opts, sample_neg_image_ids); % Update model model_before = [models{1}.w; models{1}.b]; models{1} = update_model_smooth_latent_light(models{1}, X_pos, X_neg, ... num_pos_images, num_neg_images, opts); model_after = [models{1}.w; models{1}.b]; % check if model converged if norm(model_after - model_before) < 1e-8 fprintf('Latent positive relabeling convergence detected. Breaking.\n'); break; end save(save_filename, 'models'); end end fprintf('Took %.3f hours to train\n', toc(th)/3600); % ------------------------------------------------------------------------ function X = get_all_features_topK_bagmine(... models, dataset, opts, sample_image_ids) % ------------------------------------------------------------------------ d = load_cached_features_hos(1, dataset.trainset, dataset.year, sample_image_ids{1}); feat_dim = size(d.feat,2); X = zeros(feat_dim, opts.topK * length(sample_image_ids), 'single'); start_i = 1; for i = 1:length(sample_image_ids) d = load_cached_features_hos(1, dataset.trainset, dataset.year, sample_image_ids{i}); d.feat = xform_feat_custom(d.feat, opts); % remove all ground truth boxes d.feat = d.feat( d.gt ~= 1, :); if size(d.feat,1) < opts.topK continue; end zs = d.feat * models{1}.w + models{1}.b; [~, top_ids] = sort(zs, 'descend'); sel = top_ids(1 : opts.topK); end_i = start_i + opts.topK - 1; X(:, start_i : end_i) = d.feat(sel,:)'; start_i = end_i + 1; end disp('done'); % ------------------------------------------------------------------------ function model = update_model_smooth_latent_light(model, X_pos, X_neg, ... num_pos_bags, num_neg_bags, opts) % ------------------------------------------------------------------------ pweight = opts.pos_loss_weight; [pos_cum_bag_idx, pos_averaging_matrix] = prebuild_averaging_matrix(... opts.topK * ones(num_pos_bags, 1), num_pos_bags); [neg_cum_bag_idx, neg_averaging_matrix] = prebuild_averaging_matrix(... opts.topK * ones(num_neg_bags, 1), num_neg_bags); % prebuild label, and pweighted labels y = [ones(num_pos_bags,1); -ones(num_neg_bags,1)]; pweighted_y = [pweight*y(1:num_pos_bags); y(num_pos_bags+1:end)]; options.Method = 'lbfgs'; options.Display = 'OFF'; %no output, default = 2; % w0 depends on whether this is a latent run or not if isempty(model.w) error('In latent runs, model should never be empty'); else w0 = double([model.w; model.b/opts.bias_mult]); [cost,~] = slslvm_cost_smoothhinge_bagmine(... w0, X_pos, X_neg, pos_averaging_matrix, pos_cum_bag_idx, ... neg_averaging_matrix, neg_cum_bag_idx,... num_pos_bags, num_neg_bags, y, pweighted_y, opts.svm_C, opts.svm_mu, ... pweight, opts.sharpness, opts.bias_mult); fprintf('cost before lbfgs: %.4f\n', cost); end if strcmp(opts.loss_type, 'L1hinge') error('dense version not implemented yet'); elseif strcmp(opts.loss_type, 'SmoothHinge') w_opt = minFunc(@(w) slslvm_cost_smoothhinge_bagmine(... w, X_pos, X_neg, pos_averaging_matrix, pos_cum_bag_idx, ... neg_averaging_matrix, neg_cum_bag_idx,... num_pos_bags, num_neg_bags, y, pweighted_y, opts.svm_C, opts.svm_mu, ... pweight, opts.sharpness, opts.bias_mult), w0, options); [cost,~] = slslvm_cost_smoothhinge_bagmine(... w_opt, X_pos, X_neg, pos_averaging_matrix, pos_cum_bag_idx, ... neg_averaging_matrix, neg_cum_bag_idx,... num_pos_bags, num_neg_bags, y, pweighted_y, opts.svm_C, opts.svm_mu, ... pweight, opts.sharpness, opts.bias_mult); fprintf('cost after lbfgs: %.4f\n', cost); else error('Unrecognized loss'); end model.w = single(w_opt(1:end-1)); model.b = single(w_opt(end)*opts.bias_mult); % ------------------------------------------------------------------------ function [cum_bag_idx, averaging_matrix] = prebuild_averaging_matrix(... num_insts_per_bag, bag_size) % ------------------------------------------------------------------------ cum_bag_idx = cumsum(num_insts_per_bag); if size(cum_bag_idx,1) ~= 1 cum_bag_idx = cum_bag_idx'; end % precompute averaging matrix averaging_matrix = zeros(cum_bag_idx(end), bag_size); i_start = 1; for i = 1:bag_size i_end = cum_bag_idx(i); averaging_matrix( i_start : i_end, i) = ... ones(num_insts_per_bag(i),1); i_start = i_end + 1; end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
mil_classes_20x1_smooth_lsvm_topK_bagmine_greedycover.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/mil/mil_classes_20x1_smooth_lsvm_topK_bagmine_greedycover.m
1,751
utf_8
aacd7807398aff902c0c072fe03e899c
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2014, Hyun Oh Song % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function mil_classes_20x1_smooth_lsvm_topK_bagmine_greedycover(classid) if ischar(classid), classid = str2double(classid); end conf = voc_config(); sharpness = '100'; loss_type = 'SmoothHinge'; svm_C = '0.001'; bias_mult = '10'; pos_loss_weight = '2'; class_list = conf.pascal.VOCopts.classes; % learning parameters svm_mu = 0.01; topK = 15; alpha = 0.95; K1 = 0.5; K2 = 1.0; nms_threshold = 0.3; load_filename = ['latentiter_*' ,... '_clss_' class_list{classid}, ... '_C_' svm_C, ... '_B_' bias_mult, ... '_w1_' pos_loss_weight, ... '_losstype_' loss_type, ... '_sharpness_' sharpness, ... '_mu_' num2str(svm_mu), ... '_alpha_' num2str(alpha),... '_K1_' num2str(K1), ... '_K2_' num2str(K2), ... '_nms_' num2str(nms_threshold), ... '_topK_' num2str(topK),... '_20x1_smooth_topK_bagmine_greedycover_final.mat']; iterations = []; d = dir([conf.paths.model_dir, load_filename]); for i = 1:length(d) this_name = d(i).name; bars = strfind(this_name, '_'); iteration_id = str2double(this_name(bars(1)+1 : bars(2)-1)); iterations = [iterations; iteration_id]; end highest_iteration_fileid = find(iterations == max(iterations)); load_filename = d(highest_iteration_fileid).name; load([conf.paths.model_dir, load_filename], 'models'); mil_region_mining(models, 'trainval', '2007');
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
slslvm_cost_smoothhinge_bagmine.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/mil/slslvm_cost_smoothhinge_bagmine.m
2,278
utf_8
512e2dca70ed62e8a7a98c2911d7a827
function [cost, grad] = slslvm_cost_smoothhinge_bagmine(... w, pos_X, neg_X, ... pos_averaging_matrix, pos_cum_bag_idx, ... neg_averaging_matrix, neg_cum_bag_idx,... num_pos, num_neg, ... y, pweighted_y, C, mu, pweight, sharpness, bias_mult) % AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2014, Hyun Oh Song % % This file is part of the Song-ICML2014 code and is available % under the terms of the Simplified BSD License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- [f_w_pos, pos_averaging_matrix] = compute_smooth_score(... w, pos_cum_bag_idx, pos_averaging_matrix, pos_X, mu, bias_mult); [f_w_neg, neg_averaging_matrix] = compute_smooth_score(... w, neg_cum_bag_idx, neg_averaging_matrix, neg_X, mu, bias_mult); scores = [f_w_pos, f_w_neg]; % cost pos_ind = 1 : num_pos; neg_ind = num_pos+1 : num_pos+num_neg; margins = y .* scores'; [loss, loss_grad] = general_smooth_hinge(margins, sharpness); cost = 0.5*norm(w)^2 + C * ... (pweight * sum(loss(pos_ind)) + sum(loss(neg_ind))); % gradient yy = (loss_grad .* pweighted_y); pos_avg_yy = pos_averaging_matrix * yy(pos_ind); neg_avg_yy = neg_averaging_matrix * yy(neg_ind); loss_grad_mat = pos_X * pos_avg_yy + neg_X * neg_avg_yy; grad = w + C * [loss_grad_mat; bias_mult*(sum(pos_avg_yy) + sum(neg_avg_yy))]; cost = double(cost); grad = double(grad); function [f_w, averaging_matrix]= compute_smooth_score(... w, cum_bag_idx, averaging_matrix, X, mu, bias_mult) num_insts = cum_bag_idx(end); instance_scores = w(1:end-1)'*X + ... (w(end)*bias_mult)*ones(1,num_insts); % 1 by num_insts a = zeros(num_insts, 1, 'single'); bag_start = 1; for bag_end = cum_bag_idx ind = bag_start : bag_end; a( ind ) = projsplx_c_float(1/mu * instance_scores( ind )); bag_start = bag_end + 1; end % premultiply a to the averaging matrix averaging_matrix = bsxfun(@times, averaging_matrix, a); f_w = (instance_scores -mu/2*a') * averaging_matrix;
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
train_classes_20x1_smooth_greedycover.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/mil/train_classes_20x1_smooth_greedycover.m
23,127
utf_8
792a583169dbd9446982eba59c5a3e55
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2014, Hyun Oh Song % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function models = train_classes_20x1_smooth_greedycover(classid, varargin) % Sort clusters by discriminativeness score, greedily take % non-overlapping (image ids, or boxes) in K1 until the score goes bad % initialize and fix the random seed randn('state', 1); rand('state', 1); % addpath addpath(genpath('minFunc_2012/')); addpath('projsplx/'); trainset = 'trainval'; year = '2007'; if ischar(classid), classid = str2double(classid); end % cast optional parameters into double if length(varargin) ~= 0 for i = 1:length(varargin) if mod(i,2)==0 if ischar(varargin{i}), varargin{i} = str2double(varargin{i}); end end end end ip = inputParser; ip.addRequired('trainset', @isstr); ip.addRequired('year', @isstr); ip.addRequired('classid', @isscalar); ip.addParamValue('sharpness', 100, @isscalar); ip.addParamValue('alpha', 0.95, @isscalar); ip.addParamValue('K1', 0.5, @isscalar); ip.addParamValue('K2', 1.0, @isscalar); ip.addParamValue('nms_threshold', 0.3, @isscalar); ip.addParamValue('loss_type', 'SmoothHinge', @isstr); ip.addParamValue('svm_C', 10^-3, @isscalar); ip.addParamValue('bias_mult', 10, @isscalar); ip.addParamValue('pos_loss_weight', 2, @isscalar); ip.addParamValue('layer', 'fc7', @isstr); ip.addParamValue('fine_tuned', 0, @isscalar); ip.addParamValue('use_flipped', 0, @isscalar); ip.addParamValue('target_norm', 20, @isscalar); ip.parse(trainset, year, classid, varargin{:}); opts = ip.Results; fprintf('\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'); fprintf('Training options:\n'); disp(opts); fprintf('~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n'); conf = voc_config(); clss = conf.pascal.VOCopts.classes; clss = clss(classid); num_clss = 1; dataset.year = year; dataset.trainset = trainset; dataset.image_ids = textread(sprintf(conf.pascal.VOCopts.imgsetpath, trainset), '%s'); dataset.image_ids_small = dataset.image_ids(randperm(length(dataset.image_ids), 1000)); dataset.pos_image_ids = dataset.image_ids; % ------------------------------------------------------------------------ load('class_pos_images.mat'); pos_image_ids = class_pos_images(classid).ids; neg_image_ids = setdiff(dataset.image_ids, pos_image_ids); dataset.neg_image_ids = neg_image_ids; % sample_pos_image_ids = pos_image_ids(1:40); % sample_neg_image_ids = neg_image_ids(1:200); sample_pos_image_ids = pos_image_ids; sample_neg_image_ids = neg_image_ids; num_pos_images = length(sample_pos_image_ids); num_neg_images = length(sample_neg_image_ids); % ------------------------------------------------------------------------ % ------------------------------------------------------------------------ % Get or compute the average norm of the features if ~exist('feat_stats','file') mkdir('feat_stats'); end save_file = sprintf('feat_stats/stats_%s_%s_layer_%s_finetuned_%d', ... trainset, year, opts.layer, opts.fine_tuned); try ld = load(save_file); opts.feat_norm_mean = ld.feat_norm_mean; clear ld; catch [feat_norm_mean, stddev] = feat_stats_hos(trainset, year, opts.layer, opts.fine_tuned); save(save_file, 'feat_norm_mean', 'stddev'); opts.feat_norm_mean = feat_norm_mean; end fprintf('average norm = %.3f\n', opts.feat_norm_mean); % ------------------------------------------------------------------------ % ------------------------------------------------------------------------ % Init models models = {}; for i = 1:num_clss models{i} = init_model(clss{i}, dataset, conf, opts); end % ------------------------------------------------------------------------ % ------------------------------------------------------------------------ % Get all positive examples X_pos = get_positive_features_paris_greedycover( ... models, dataset, opts, classid, sample_pos_image_ids ); for i = 1:num_clss fprintf('%14s has %6d positive instances\n', models{i}.class, size(X_pos{i},1)); X_pos{i} = xform_feat_custom(X_pos{i}, opts); end % ------------------------------------------------------------------------ % ------------------------------------------------------------------------ % Init training caches caches = {}; for i = 1:num_clss caches{i} = init_cache(models{i}, X_pos{i}); end % ------------------------------------------------------------------------ % ------------------------------------------------------------------------ % Train with hard negative mining first_time = true; force_update = false; max_hard_epochs = 1; max_latent_iter = 0; th = tic(); % measure training time for latent_iter = 0:max_latent_iter % Latent positive relabling if latent_iter > 0 fprintf('latent positive update %d\n', latent_iter); %X_pos = get_positive_features_paris_maxcover(models, dataset, true, opts,... % classid, sample_pos_image_ids, sample_neg_image_ids); for i = 1:num_clss caches{i}.X_pos = X_pos{i}; fprintf('%14s has %10d positive instances\n', ... models{i}.class, size(X_pos{i},1)); end % force model update force_update = true; end % Train lbfgs SVMs with hard negative mining for hard_epoch = 1:max_hard_epochs for i = 1:length(dataset.neg_image_ids) fprintf('%s: hard neg epoch %d %d/%d\n', ... procid(), hard_epoch, i, length(dataset.neg_image_ids)); % Get hard negatives for all classes at once (avoids loading feature cache % more than once) [X, keys] = sample_negative_features(first_time, models, caches, dataset, i, opts); % Add sampled negatives to each classes training cache, removing % duplicates for j = 1:num_clss if ~isempty(keys{j}) if isempty(caches{j}.keys) dups = []; else [~, ~, dups] = intersect(caches{j}.keys, keys{j}, 'rows'); end assert(isempty(dups)); caches{j}.X_neg = cat(1, caches{j}.X_neg, X{j}); caches{j}.keys = cat(1, caches{j}.keys, keys{j}); caches{j}.num_added = caches{j}.num_added + size(keys{j},1); end % Update model if % - first time seeing negatives % - more than retrain_limit negatives have been added % - its the final image of the final epoch is_last_time = (hard_epoch == max_hard_epochs && i == length(dataset.neg_image_ids)); hit_retrain_limit = (caches{j}.num_added > caches{j}.retrain_limit); if force_update || first_time || hit_retrain_limit || is_last_time fprintf(' Retraining %s model\n', models{j}.class); fprintf(' Cache holds %d pos examples %d neg examples\n', ... size(caches{j}.X_pos,1), size(caches{j}.X_neg,1)); models{j} = update_model(models{j}, caches{j}, opts); caches{j}.num_added = 0; z_pos = caches{j}.X_pos*models{j}.w + models{j}.b; z_neg = caches{j}.X_neg*models{j}.w + models{j}.b; caches{j}.pos_loss(end+1) = opts.svm_C*sum(max(0, 1 - z_pos))*opts.pos_loss_weight; caches{j}.neg_loss(end+1) = opts.svm_C*sum(max(0, 1 + z_neg)); caches{j}.reg_loss(end+1) = 0.5*models{j}.w'*models{j}.w + ... 0.5*(models{j}.b/opts.bias_mult)^2; caches{j}.tot_loss(end+1) = caches{j}.pos_loss(end) + ... caches{j}.neg_loss(end) + ... caches{j}.reg_loss(end); for t = 1:length(caches{j}.tot_loss) fprintf(' %2d: obj val: %.3f = %.3f (pos) + %.3f (neg) + %.3f (reg)\n', ... t, caches{j}.tot_loss(t), caches{j}.pos_loss(t), ... caches{j}.neg_loss(t), caches{j}.reg_loss(t)); end % evict easy examples easy = find(z_neg < caches{j}.evict_thresh); caches{j}.X_neg(easy,:) = []; caches{j}.keys(easy,:) = []; fprintf(' Pruning easy negatives\n'); fprintf(' Cache holds %d pos examples %d neg examples\n', ... size(caches{j}.X_pos,1), size(caches{j}.X_neg,1)); fprintf(' %d pos support vectors\n', numel(find(z_pos <= 1))); fprintf(' %d neg support vectors\n', numel(find(z_neg >= -1))); %model = models{j}; %save([conf.paths.model_dir models{j}.class '_' num2str(length(caches{j}.tot_loss))], 'model'); %clear model; end end first_time = false; force_update = false; end end end save([conf.paths.model_dir, ... 'latentiter_' num2str(latent_iter) '_clss_' clss{1}, ... '_C_' num2str(opts.svm_C), ... '_B_' num2str(opts.bias_mult), ... '_w1_' num2str(opts.pos_loss_weight), ... '_losstype_' opts.loss_type, ... '_sharpness_' num2str(opts.sharpness), ... '_alpha_' num2str(opts.alpha), ... '_K1_' num2str(opts.K1), ... '_K2_' num2str(opts.K2), ... '_nms_' num2str(opts.nms_threshold), ... '_20x1_smooth_greedycover_final.mat'], 'models'); fprintf('Took %.3f hours to train\n', toc(th)/3600); % ------------------------------------------------------------------------ function [X_neg, keys] = sample_negative_features(first_time, models, ... caches, dataset, ind, ... opts) % ------------------------------------------------------------------------ d = load_cached_features_hos(1, dataset.trainset, dataset.year, dataset.neg_image_ids{ind}); if length(d.overlap) ~= size(d.feat, 1) fprintf('WARNING: %s has data mismatch\n', dataset.neg_image_ids{ind}); X_neg = cell(1, length(models)); keys = cell(1, length(models)); return; end d.feat = xform_feat_custom(d.feat, opts); %d.feat = o2p(d.feat); neg_ovr_thresh = 0.3; if first_time for i = 1:length(models) %I = find(d.overlap(:, models{i}.class_id) < neg_ovr_thresh); I = (1:size(d.feat,1))'; X_neg{i} = d.feat(I,:); keys{i} = [ind*ones(length(I),1) I]; end else ws = cat(2, cellfun(@(x) x.w, models, 'UniformOutput', false)); ws = cat(2, ws{:}); bs = cat(2, cellfun(@(x) x.b, models, 'UniformOutput', false)); bs = cat(2, bs{:}); zs = bsxfun(@plus, d.feat*ws, bs); for i = 1:length(models) z = zs(:,i); % I = find((z > caches{i}.hard_thresh) & ... % (d.overlap(:, models{i}.class_id) < neg_ovr_thresh)); I = find(z > caches{i}.hard_thresh); % apply NMS to scored boxes % select as negatives anything that survived NMS % and has < 50% overlap with postives of this class % and is violating the margin % boxes = cat(2, single(d.boxes), z); % nms_keep = false(size(boxes,1), 1); % nms_keep(nms(boxes, 0.3)) = true; % % I = find((z > caches{i}.hard_thresh) & ... % (nms_keep == true) & ... % (d.overlap(:, models{i}.class_id) < neg_ovr_thresh)); % Avoid adding duplicate features keys_ = [ind*ones(length(I),1) I]; if isempty(caches{i}.keys) || isempty(keys_) dups = []; else [~, ~, dups] = intersect(caches{i}.keys, keys_, 'rows'); end keep = setdiff(1:size(keys_,1), dups); I = I(keep); % Unique hard negatives X_neg{i} = d.feat(I,:); keys{i} = [ind*ones(length(I),1) I]; end end % ------------------------------------------------------------------------ function model = update_model(model, cache, opts) % ------------------------------------------------------------------------ num_pos = size(cache.X_pos, 1); num_neg = size(cache.X_neg, 1); feat_dim = size(cache.X_pos, 2); pweight = opts.pos_loss_weight; X = zeros( num_pos*pweight+num_neg, feat_dim+1); X(1:num_pos*pweight, 1:end-1) = repmat(cache.X_pos,pweight,1); X(num_pos*pweight+1:end, 1:end-1) = cache.X_neg; % augment the bias feature * opt.bias_mult factor X(:, end) = opts.bias_mult * ones(1, num_pos*pweight+num_neg); y = cat(1, repmat(ones(num_pos,1),pweight,1), -ones(num_neg,1)); options.Method = 'lbfgs'; options.Display = 'OFF'; %no output, default = 2; if isempty(model.w) w0 = zeros(feat_dim+1,1); else w0 = double([model.w; model.b/opts.bias_mult]); end if strcmp(opts.loss_type, 'L1hinge') w_opt = minFunc(@(w) SVM_Cost_L1hinge(... w, X, y, opts.svm_C), w0, options); elseif strcmp(opts.loss_type, 'SmoothHinge') w_opt = minFunc(@(w) SVM_Cost_SmoothHinge(... w, X, y, opts.svm_C, opts.sharpness), w0, options); elseif strcmp(opts.loss_type, 'Logistic') w_opt = minFunc(@(w) SVM_Cost_Logistic(... w, X, y, opts.svm_C), w0, options); end model.w = single(w_opt(1:end-1)); model.b = single(w_opt(end)*opts.bias_mult); % ------------------------------------------------------------------------ function X_pos = get_positive_features_paris_greedycover(... models, dataset, opts, classid, sample_pos_image_ids) % ------------------------------------------------------------------------ % HOS: Use maxcover to create a pool of positive windows. % \alpha controls max_coverage % \K1 controls number of nearest neighbors per cluster % \K2 controls number of positive boxes to take per cluster % A. Construct positive training set from max cover % trainset_matrix is a 2 by #boxes matrix (pos image ids; box ids) trainset_matrix = []; num_pos_images = length(sample_pos_image_ids); % construct graph matrix, # clusters by # pos images [graph_image_matrix, graph_box_matrix, ... per_cluster_paris_score_K1, per_cluster_paris_score_K2] = ... construct_graph(classid, sample_pos_image_ids, opts); coverage = 0; popped_cluster_history = []; per_cluster_paris_score_copy = per_cluster_paris_score_K1; %copy for plotting % go down sorted list of paris scores and keep taking unclaimed positive % images in top K1 (but take boxes in top K2) while coverage < (opts.alpha * num_pos_images) % pop the cluster with best paris score c_top = find(per_cluster_paris_score_K1 == max(per_cluster_paris_score_K1)); % take care of ties here if length(c_top) > 1 fprintf('warning: tie detected!\n'); % compute paris score @ K2 to break the tie c_top_scores = per_cluster_paris_score_K2(c_top); c_top = c_top( find(c_top_scores == max(c_top_scores)) ); % still tied? just take the first one. c_top = c_top(1); end % push boxes for cluster's activated pos iamges to train set, box_ids = graph_box_matrix(c_top, :); trainset_matrix = [trainset_matrix, [find(box_ids~=0); box_ids(box_ids~=0)] ]; % update graph: remove activated pos images from c_top activated_images = find(graph_image_matrix(c_top,:) ~= false); graph_image_matrix(:, activated_images) = false; graph_box_matrix(:, activated_images) = 0; % void this cluster from popping up again per_cluster_paris_score_K1(c_top) = -inf; popped_cluster_history = [popped_cluster_history, c_top]; % update coverage coverage = coverage + length(activated_images); fprintf('[%d] current coverage: %d, cluster %d covered %d\n', ... length(popped_cluster_history), coverage, c_top, length(activated_images)); end % B. Decode trainset_matrix and create positive feature matrix % make sure to preserve original order of trainset_matrix % remove exact duplicates in trainset_matrix trainset_matrix = remove_exact_duplicate_columns_preserve_order(trainset_matrix); X_pos = cell(length(models),1); X_pos{1} = single([]); % remove highly overlapping boxes with NMS 0.3 num_suppressed_boxes = 0; assigned_boxes(num_pos_images).coords = []; for boxid = 1:length(trainset_matrix) % load this pos image's features and boxes; check if indexing is correct this_image_idx = trainset_matrix(1, boxid); this_box_idx = trainset_matrix(2, boxid); img_struct = load_cached_features_hos(1, dataset.trainset, dataset.year, sample_pos_image_ids{this_image_idx}); img_struct.boxes = img_struct.boxes(img_struct.gt~=1,:); img_struct.feat = img_struct.feat( img_struct.gt~=1,:); this_feature = img_struct.feat( this_box_idx, :); this_box = img_struct.boxes(this_box_idx, :); % check if there's box already taken and nms if exists. is_suppressed = check_nms_with_existing_boxes(... assigned_boxes(this_image_idx).coords, this_box, opts); if is_suppressed num_suppressed_boxes = num_suppressed_boxes + 1; continue; end assigned_boxes(this_image_idx).coords = [... assigned_boxes(this_image_idx).coords; this_box]; X_pos{1} = cat(1, X_pos{1}, this_feature); end fprintf(['done creating positive feature matrix.\n',... '# pos images: %d, # passed boxes: %d, # suppresed boxes: %d\n'], ... num_pos_images, size(X_pos{1},1), num_suppressed_boxes); % ------------------------------------------------------------------------ function matrix = remove_exact_duplicate_columns_preserve_order(matrix) % ------------------------------------------------------------------------ num_boxes_before = size(matrix,2); [newmat, newids] = unique(matrix', 'rows', 'first'); hasDuplicates = size(newmat,1) < num_boxes_before; if hasDuplicates dupColumns = setdiff(1:num_boxes_before, newids); matrix(:,dupColumns) = []; end num_boxes_after = size(matrix,2); fprintf('removed %d exact duplicates\n', num_boxes_before-num_boxes_after); % ------------------------------------------------------------------------ function [graph_image_matrix, graph_box_matrix, ... per_cluster_paris_score_K1, per_cluster_paris_score_K2] = ... construct_graph(classid, sample_pos_image_ids, opts) % ------------------------------------------------------------------------ % \K1 controls number of nearest neighbors per cluster % \K2 controls number of positive boxes to take per cluster num_pos_images = length(sample_pos_image_ids); % count number of saved clusters num_clusters = 0; for seed_pos_image_id = 1:num_pos_images save_filename = sprintf('paris_results_nogt_20x1/%s_%d.mat',... sample_pos_image_ids{seed_pos_image_id}, classid); load(save_filename, 'score_top'); num_clusters = num_clusters + length(score_top); end % form a binary graph matrix size: # clusters by # pos images % graph_image_matrix holds activated positive images in top K1 graph_image_matrix = false(num_clusters, num_pos_images); % graph_box_matrix holds activated positive boxes in top K2 graph_box_matrix = zeros(num_clusters, num_pos_images, 'single'); % record per_cluster_paris score per_cluster_paris_score_K1 = zeros(num_clusters, 1, 'single'); per_cluster_paris_score_K2 = zeros(num_clusters, 1, 'single'); % Loop over each positive images and grab pos image and box list cid = 0; for seed_pos_image_id = 1:num_pos_images save_filename = sprintf('paris_results_nogt_20x1/%s_%d.mat',... sample_pos_image_ids{seed_pos_image_id}, classid); load(save_filename); % loop through each boxes (= clusters) for seed_win_id = 1:length(score_top) cid = cid + 1; [~, image_idx] = sort( [table_pos_diff_top(:,seed_win_id);... table_neg_diff_top(:,seed_win_id)], 'ascend'); % fill image matrix: restrict list pos images to top K1 NN image_idx_top_K1 = image_idx(1 : round(opts.K1*num_pos_images) ); % filter only positive images pos_image_list_K1 = image_idx_top_K1(image_idx_top_K1 <= num_pos_images); graph_image_matrix(cid, pos_image_list_K1) = true; % record paris score @ K1 per_cluster_paris_score_K1(cid) = length(pos_image_list_K1) / ... round(opts.K1*num_pos_images); % fill box matrix: restrict list pos images to top K2 NN image_idx_top_K2 = image_idx(1 : round(opts.K2*num_pos_images) ); % filter only positive images pos_image_list_K2 = image_idx_top_K2(image_idx_top_K2 <= num_pos_images); % record paris score @ K2 per_cluster_paris_score_K2(cid) = length(pos_image_list_K2) / ... round(opts.K2*num_pos_images); % retreive box ids for each positives. % convert pos image id -> box id in the given pos image pos_box_list_K2 = table_pos_idx_top(pos_image_list_K2, seed_win_id); graph_box_matrix(cid, pos_image_list_K2) = pos_box_list_K2; end end % ------------------------------------------------------------------------ function is_suppressed = check_nms_with_existing_boxes(... existing_boxes, this_box, opts) % ------------------------------------------------------------------------ if isempty(existing_boxes) is_suppressed = false; return; end %nms_overlap_threshold = 0.3; % kill boxes if nms overlap > 0.3 assert( size(existing_boxes,2) == size(this_box,2)); num_existing_boxes = size(existing_boxes,1); % parse existing boxes x1 = existing_boxes(:,1); y1 = existing_boxes(:,2); x2 = existing_boxes(:,3); y2 = existing_boxes(:,4); area = (x2-x1+1) .* (y2-y1+1); % parse this new box tx1 = this_box(:,1); ty1 = this_box(:,2); tx2 = this_box(:,3); ty2 = this_box(:,4); new_box_area = (tx2-tx1+1) * (ty2 - ty1+1); is_suppressed = false; for j = 1:num_existing_boxes xx1 = max(x1(j), tx1); yy1 = max(y1(j), ty1); xx2 = min(x2(j), tx2); yy2 = min(y2(j), ty2); w = xx2-xx1+1; h = yy2-yy1+1; if w > 0 && h > 0 % compute overlap inter = w*h; o = inter / (area(j) + new_box_area - inter); if o > opts.nms_threshold is_suppressed = true; break; end end end % ------------------------------------------------------------------------ function model = init_model(cls, dataset, conf, opts) % ------------------------------------------------------------------------ model.class = cls; %model.class_id = strmatch(model.class, conf.pascal.VOCopts.classes); model.trainset = dataset.trainset; model.year = dataset.year; model.w = []; model.b = []; model.thresh = -1.1; model.opts = opts; % ------------------------------------------------------------------------ function cache = init_cache(model, X_pos) % ------------------------------------------------------------------------ cache.X_pos = X_pos; cache.X_neg = single([]); cache.keys = []; cache.num_added = 0; cache.retrain_limit = 2000; cache.evict_thresh = -1.2; cache.hard_thresh = -1.0001; cache.pos_loss = []; cache.neg_loss = []; cache.reg_loss = []; cache.tot_loss = [];
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
mil_region_mining.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/mil/mil_region_mining.m
1,747
utf_8
d9bb95ab7af5b035eab795bcce50bdb1
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2014, Hyun Oh Song % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function mil_region_mining(models, testset, year) conf = voc_config(); cachedir = conf.paths.model_dir; VOCopts = conf.pascal.VOCopts; load('class_pos_images.mat'); classid = strmatch(models{1}.class,VOCopts.classes,'exact'); image_ids = class_pos_images(classid).ids; feat_opts = models{1}.opts; ws = cat(2, cellfun(@(x) x.w, models, 'UniformOutput', false)); ws = cat(2, ws{:}); bs = cat(2, cellfun(@(x) x.b, models, 'UniformOutput', false)); bs = cat(2, bs{:}); boxes = cell(length(image_ids), 1); for i = 1:length(image_ids) fprintf('%s: region mining: %d/%d\n', procid(), i, length(image_ids)); d = load_cached_features_hos(0, testset, year, image_ids{i}); d.feat = xform_feat_custom(d.feat, feat_opts); zs = bsxfun(@plus, d.feat*ws, bs); z = zs(d.gt~=1); [val, ind] = sort(z,'descend'); bbs = d.boxes(d.gt~=1,:); boxes{i} = cat(2, single(bbs(ind(1),:)), z(ind(1))); end save_file = [cachedir models{1}.class '_best_boxes_' testset '_' year '.mat']; save(save_file, 'boxes'); if ~exist('results_mil','file') mkdir('results_mil'); end res_fn = ['./results_mil/' models{1}.class '_' testset '.txt']; fid = fopen(res_fn, 'w'); for i = 1:length(image_ids) bbox = boxes{i}; fprintf(fid, '%s %f %d %d %d %d\n', image_ids{i}, bbox(end), bbox(1:4)); end fclose(fid);
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
voc_config.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/mil/voc_config.m
8,999
utf_8
bb032cdaaab5bcbaf83b6f30937a6ed1
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2011-2012, Ross Girshick % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function conf = voc_config(varargin) % Set up configuration variables. % conf = voc_config(varargin) % % Each variable is named by a path that identifies a field % in the returned conf structure. For example, 'pascal.year' % corresponds to conf.pascal.year. You can set configuration % variables in 3 ways: % 1) File: directly editing values in this file % 2) Per-call: pass an override as an argument to this function % E.g., conf = voc_config('pascal.year', '2011'); % 3) Per-session: assign the global variable VOC_CONFIG_OVERRIDE % to a function that returns a conf structure with specific % overrides set. This method is persistent until VOC_CONFIG_OVERRIDE % is cleared. See sample_voc_config_override.m for an example. % ~~~~~~~~~~~~~~~~~~~~~~ BASIC SETUP ~~~~~~~~~~~~~~~~~~~~~~ % Please read the next few lines tmp = pwd; ind = find(tmp=='/'); BASE_DIR = tmp(1:ind(end)); % PASCAL dataset year to use PASCAL_YEAR = '2007'; % Models are stored in BASE_DIR/PROJECT/PASCAL_YEAR/ PROJECT = 'mil'; % The code will look for your PASCAL VOC devkit in % BASE_DIR/VOC<PASCAL_YEAR>/VOCdevkit % If you have the devkit installed elsewhere, you may want to % create a symbolic link. % You probably don't need to change configuration settings below this line. % ~~~~~~~~~~~~~~~~~~~~~~ ADVANCED SETUP ~~~~~~~~~~~~~~~~~~~~~~ % % conf top-level variables % conf.paths filesystem paths % conf.pascal PASCAL VOC dataset % conf.training model training parameters % conf.eval model evaluation parameters % conf.features image features % % To set a configuration override file, declare % the global variable VOC_CONFIG_OVERRIDE % and then set it as a function handle to the % config override function. E.g., % >> global VOC_CONFIG_OVERRIDE; % >> VOC_CONFIG_OVERRIDE = @my_voc_config; % In this example, we assume that you have an M-file % named my_voc_config.m. See sample_voc_config_override.m. % % Overrides passed in as arguments have the highest precedence. % Overrides in the overrides file have second highest precedence, % but are clobbered by overrides passed in as arguments. % Settings in this file are clobbered by the previous two. % Configuration structure conf = []; % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % Persistent and per-call overrides % % Check for an override configuration file assert_not_in_parallel_worker(); global VOC_CONFIG_OVERRIDE; if ~isempty(VOC_CONFIG_OVERRIDE) conf = VOC_CONFIG_OVERRIDE(); end % Clobber with overrides passed in as arguments for i = 1:2:length(varargin) key = varargin{i}; val = varargin{i+1}; eval(['conf.' key ' = val;']); end % % % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ conf = cv(conf, 'num_threads', feature('NumCores')); % Project name (used in the paths) conf = cv(conf, 'project', PROJECT); % Parent directory that everything (model cache, VOCdevkit) is under conf = cv(conf, 'paths.base_dir', BASE_DIR); % Path to this file conf = cv(conf, 'paths.self', fullfile(pwd(), [mfilename() '.m'])); % ------------------------------------------------------------------- % PASCAL VOC configuration % ------------------------------------------------------------------- % Configure the PASCAL VOC dataset year conf = cv(conf, 'pascal.year', PASCAL_YEAR); % Directory with PASCAL VOC development kit and dataset conf = cv(conf, 'pascal.dev_kit', [conf.paths.base_dir '/data/VOCdevkit' PASCAL_YEAR '/']); % For INRIA person %conf = cv(conf, 'pascal.dev_kit', [conf.paths.base_dir '/INRIA/VOCdevkit/']); if exist(conf.pascal.dev_kit) == 0 global G_VOC_CONFIG_HELLO; if isempty(G_VOC_CONFIG_HELLO) G_VOC_CONFIG_HELLO = true; msg = sprintf(['~~~~~~~~~~~ Hello ~~~~~~~~~~~\n' ... 'voc-release5 is not yet configured for learning. \n' ... 'You can still run demo.m, but please read \n' ... 'the section "Using the learning code" in README. \n' ... '(Could not find the PASCAL VOC devkit in %s)'], ... conf.pascal.dev_kit); fprintf([msg '\n\n']); end return; end % VOCinit brings VOCopts into scope conf.pascal.VOCopts = get_voc_opts(conf); % ------------------------------------------------------------------- % Path configuration % ------------------------------------------------------------------- % Directory for caching models, intermediate data, and results % [was called 'cachedir' in previous releases] conf = cv(conf, 'paths.model_dir', [conf.paths.base_dir '/' ... conf.project '/' conf.pascal.year '/']); exists_or_mkdir(conf.paths.model_dir); %% ------------------------------------------------------------------- %% Training configuration %% ------------------------------------------------------------------- %conf = cv(conf, 'training.train_set_fg', 'trainval'); %conf = cv(conf, 'training.train_set_fg', 'train'); %conf = cv(conf, 'training.train_set_bg', 'train'); %conf = cv(conf, 'training.C', 0.001); %conf = cv(conf, 'training.bias_feature', 10); %% File size limit for the feature vector cache (2^30 bytes = 1GB) %conf = cv(conf, 'training.cache_byte_limit', 3*2^30); %% Location of training log (matlab diary) %conf.training.log = @(x) sprintf([conf.paths.model_dir '%s.log'], x); % %conf = cv(conf, 'training.cache_example_limit', 24000); %conf = cv(conf, 'training.num_negatives_small', 200); %conf = cv(conf, 'training.num_negatives_large', 2000); %conf = cv(conf, 'training.wlssvm_M', 0); %conf = cv(conf, 'training.fg_overlap', 0.7); % %conf = cv(conf, 'training.lbfgs.options.verbose', 2); %conf = cv(conf, 'training.lbfgs.options.maxIter', 1000); %conf = cv(conf, 'training.lbfgs.options.optTol', 0.000001); % %conf = cv(conf, 'training.interval_fg', 5); %conf = cv(conf, 'training.interval_bg', 4); % % %% ------------------------------------------------------------------- %% Evaluation configuration %% ------------------------------------------------------------------- %conf = cv(conf, 'eval.interval', 10); %conf = cv(conf, 'eval.max_thresh', -1.1); conf = cv(conf, 'eval.test_set', 'test'); conf.pascal.VOCopts.testset = conf.eval.test_set; % ------------------------------------------------------------------- % Feature configuration % ------------------------------------------------------------------- conf = cv(conf, 'features.dim', 4096); % ------------------------------------------------------------------- % Helper functions % ------------------------------------------------------------------- % ------------------------------------------------------------------- % Make directory path if it does not already exist. function made = exists_or_mkdir(path) made = false; if exist(path) == 0 unix(['mkdir -p ' path]); made = true; end % ------------------------------------------------------------------- % Returns the 'VOCopts' variable from the VOCdevkit. The path to the % devkit is also added to the matlab path. function VOCopts = get_voc_opts(conf) % cache VOCopts from VOCinit persistent voc_opts; key = conf.pascal.year; if isempty(voc_opts) || ~voc_opts.isKey(key) if isempty(voc_opts) voc_opts = containers.Map(); end tmp = pwd; cd(conf.pascal.dev_kit); addpath([cd '/VOCcode']); VOCinit; cd(tmp); voc_opts(key) = VOCopts; end VOCopts = voc_opts(key); % ------------------------------------------------------------------- % Does nothing if conf.key exists, otherwise sets conf.key to val function conf = cv(conf, key, val) try eval(['conf.' key ';']); catch eval(['conf.' key ' = val;']); end % ------------------------------------------------------------------- % Throw an error if this function is called from inside a matlabpool % worker. function assert_not_in_parallel_worker() % Matlab does not support accessing global variables from % parallel workers. The result of reading a global is undefined % and in practice has odd and inconsistent behavoir. % The configuraton override mechanism relies on a global % variable. To avoid hard-to-find bugs, we make sure that % voc_config cannot be called from a parallel worker. t = []; if usejava('jvm') try t = getCurrentTask(); catch end end if ~isempty(t) msg = ['voc_config() cannot be called from a parallel worker ' ... '(or startup.m did not run -- did you run matlab from the ' ... 'root of the voc-release installationd directory?']; error(msg); end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
WolfeLineSearch.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/mil/minFunc_2012/minFunc/WolfeLineSearch.m
10,590
utf_8
f962bc5ae0a1e9f80202a9aaab106dab
function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(... x,t,d,f,g,gtd,c1,c2,LS_interp,LS_multi,maxLS,progTol,debug,doPlot,saveHessianComp,funObj,varargin) % % Bracketing Line Search to Satisfy Wolfe Conditions % % Inputs: % x: starting location % t: initial step size % d: descent direction % f: function value at starting location % g: gradient at starting location % gtd: directional derivative at starting location % c1: sufficient decrease parameter % c2: curvature parameter % debug: display debugging information % LS_interp: type of interpolation % maxLS: maximum number of iterations % progTol: minimum allowable step length % doPlot: do a graphical display of interpolation % funObj: objective function % varargin: parameters of objective function % % Outputs: % t: step length % f_new: function value at x+t*d % g_new: gradient value at x+t*d % funEvals: number function evaluations performed by line search % H: Hessian at initial guess (only computed if requested % Evaluate the Objective and Gradient at the Initial Step if nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x+t*d,varargin{:}); end funEvals = 1; gtd_new = g_new'*d; % Bracket an Interval containing a point satisfying the % Wolfe criteria LSiter = 0; t_prev = 0; f_prev = f; g_prev = g; gtd_prev = gtd; nrmD = max(abs(d)); done = 0; while LSiter < maxLS %% Bracketing Phase if ~isLegal(f_new) || ~isLegal(g_new) if debug fprintf('Extrapolated into illegal region, switching to Armijo line-search\n'); end t = (t + t_prev)/2; % Do Armijo if nargout == 5 [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(... x,t,d,f,f,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,... funObj,varargin{:}); else [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(... x,t,d,f,f,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,... funObj,varargin{:}); end funEvals = funEvals + armijoFunEvals; return; end if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev) bracket = [t_prev t]; bracketFval = [f_prev f_new]; bracketGval = [g_prev g_new]; break; elseif abs(gtd_new) <= -c2*gtd bracket = t; bracketFval = f_new; bracketGval = g_new; done = 1; break; elseif gtd_new >= 0 bracket = [t_prev t]; bracketFval = [f_prev f_new]; bracketGval = [g_prev g_new]; break; end temp = t_prev; t_prev = t; minStep = t + 0.01*(t-temp); maxStep = t*10; if LS_interp <= 1 if debug fprintf('Extending Braket\n'); end t = maxStep; elseif LS_interp == 2 if debug fprintf('Cubic Extrapolation\n'); end t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep); elseif LS_interp == 3 t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot); end f_prev = f_new; g_prev = g_new; gtd_prev = gtd_new; if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; end if LSiter == maxLS bracket = [0 t]; bracketFval = [f f_new]; bracketGval = [g g_new]; end %% Zoom Phase % We now either have a point satisfying the criteria, or a bracket % surrounding a point satisfying the criteria % Refine the bracket until we find a point satisfying the criteria insufProgress = 0; Tpos = 2; LOposRemoved = 0; while ~done && LSiter < maxLS % Find High and Low Points in bracket [f_LO LOpos] = min(bracketFval); HIpos = -LOpos + 3; % Compute new trial value if LS_interp <= 1 || ~isLegal(bracketFval) || ~isLegal(bracketGval) if debug fprintf('Bisecting\n'); end t = mean(bracket); elseif LS_interp == 2 if debug fprintf('Grad-Cubic Interpolation\n'); end t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot); else % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nonTpos = -Tpos+3; if LOposRemoved == 0 oldLOval = bracket(nonTpos); oldLOFval = bracketFval(nonTpos); oldLOGval = bracketGval(:,nonTpos); end t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot); end % Test that we are making sufficient progress if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1 if debug fprintf('Interpolation close to boundary'); end if insufProgress || t>=max(bracket) || t <= min(bracket) if debug fprintf(', Evaluating at 0.1 away from boundary\n'); end if abs(t-max(bracket)) < abs(t-min(bracket)) t = max(bracket)-0.1*(max(bracket)-min(bracket)); else t = min(bracket)+0.1*(max(bracket)-min(bracket)); end insufProgress = 0; else if debug fprintf('\n'); end insufProgress = 1; end else insufProgress = 0; end % Evaluate new point if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; armijo = f_new < f + c1*t*gtd; if ~armijo || f_new >= f_LO % Armijo condition not satisfied or not lower than lowest % point bracket(HIpos) = t; bracketFval(HIpos) = f_new; bracketGval(:,HIpos) = g_new; Tpos = HIpos; else if abs(gtd_new) <= - c2*gtd % Wolfe conditions satisfied done = 1; elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0 % Old HI becomes new LO bracket(HIpos) = bracket(LOpos); bracketFval(HIpos) = bracketFval(LOpos); bracketGval(:,HIpos) = bracketGval(:,LOpos); if LS_interp == 3 if debug fprintf('LO Pos is being removed!\n'); end LOposRemoved = 1; oldLOval = bracket(LOpos); oldLOFval = bracketFval(LOpos); oldLOGval = bracketGval(:,LOpos); end end % New point becomes new LO bracket(LOpos) = t; bracketFval(LOpos) = f_new; bracketGval(:,LOpos) = g_new; Tpos = LOpos; end if ~done && abs(bracket(1)-bracket(2))*nrmD < progTol if debug fprintf('Line-search bracket has been reduced below progTol\n'); end break; end end %% if LSiter == maxLS if debug fprintf('Line Search Exceeded Maximum Line Search Iterations\n'); end end [f_LO LOpos] = min(bracketFval); t = bracket(LOpos); f_new = bracketFval(LOpos); g_new = bracketGval(:,LOpos); % Evaluate Hessian at new point if nargout == 5 && funEvals > 1 && saveHessianComp [f_new,g_new,H] = funObj(x + t*d,varargin{:}); funEvals = funEvals + 1; end end %% function [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot); alpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep); alpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep); if alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1) if debug fprintf('Cubic Extrapolation\n'); end t = alpha_c; else if debug fprintf('Secant Extrapolation\n'); end t = alpha_s; end end %% function [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot); % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nonTpos = -Tpos+3; gtdT = bracketGval(:,Tpos)'*d; gtdNonT = bracketGval(:,nonTpos)'*d; oldLOgtd = oldLOGval'*d; if bracketFval(Tpos) > oldLOFval alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot); if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval) if debug fprintf('Cubic Interpolation\n'); end t = alpha_c; else if debug fprintf('Mixed Quad/Cubic Interpolation\n'); end t = (alpha_q + alpha_c)/2; end elseif gtdT'*oldLOgtd < 0 alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) sqrt(-1) gtdT],doPlot); if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos)) if debug fprintf('Cubic Interpolation\n'); end t = alpha_c; else if debug fprintf('Quad Interpolation\n'); end t = alpha_s; end elseif abs(gtdT) <= abs(oldLOgtd) alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],... doPlot,min(bracket),max(bracket)); alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],... doPlot,min(bracket),max(bracket)); if alpha_c > min(bracket) && alpha_c < max(bracket) if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos)) if debug fprintf('Bounded Cubic Extrapolation\n'); end t = alpha_c; else if debug fprintf('Bounded Secant Extrapolation\n'); end t = alpha_s; end else if debug fprintf('Bounded Secant Extrapolation\n'); end t = alpha_s; end if bracket(Tpos) > oldLOval t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t); else t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t); end else t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); end end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
minFunc_processInputOptions.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/mil/minFunc_2012/minFunc/minFunc_processInputOptions.m
4,103
utf_8
8822581c3541eabe5ce7c7927a57c9ab
function [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,optTol,progTol,method,... corrections,c1,c2,LS_init,cgSolve,qnUpdate,cgUpdate,initialHessType,... HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,... Damped,HvFunc,bbType,cycle,... HessianIter,outputFcn,useMex,useNegCurv,precFunc,... LS_type,LS_interp,LS_multi,DerivativeCheck] = ... minFunc_processInputOptions(o) % Constants SD = 0; CSD = 1; BB = 2; CG = 3; PCG = 4; LBFGS = 5; QNEWTON = 6; NEWTON0 = 7; NEWTON = 8; TENSOR = 9; verbose = 1; verboseI= 1; debug = 0; doPlot = 0; method = LBFGS; cgSolve = 0; o = toUpper(o); if isfield(o,'DISPLAY') switch(upper(o.DISPLAY)) case 0 verbose = 0; verboseI = 0; case 'FINAL' verboseI = 0; case 'OFF' verbose = 0; verboseI = 0; case 'NONE' verbose = 0; verboseI = 0; case 'FULL' debug = 1; case 'EXCESSIVE' debug = 1; doPlot = 1; end end DerivativeCheck = 0; if isfield(o,'DERIVATIVECHECK') switch(upper(o.DERIVATIVECHECK)) case 1 DerivativeCheck = 1; case 'ON' DerivativeCheck = 1; end end LS_init = 0; LS_type = 1; LS_interp = 2; LS_multi = 0; Fref = 1; Damped = 0; HessianIter = 1; c2 = 0.9; if isfield(o,'METHOD') m = upper(o.METHOD); switch(m) case 'TENSOR' method = TENSOR; case 'NEWTON' method = NEWTON; case 'MNEWTON' method = NEWTON; HessianIter = 5; case 'PNEWTON0' method = NEWTON0; cgSolve = 1; case 'NEWTON0' method = NEWTON0; case 'QNEWTON' method = QNEWTON; Damped = 1; case 'LBFGS' method = LBFGS; case 'BB' method = BB; LS_type = 0; Fref = 20; case 'PCG' method = PCG; c2 = 0.2; LS_init = 2; case 'SCG' method = CG; c2 = 0.2; LS_init = 4; case 'CG' method = CG; c2 = 0.2; LS_init = 2; case 'CSD' method = CSD; c2 = 0.2; Fref = 10; LS_init = 2; case 'SD' method = SD; LS_init = 2; end end maxFunEvals = getOpt(o,'MAXFUNEVALS',1000); maxIter = getOpt(o,'MAXITER',500); optTol = getOpt(o,'OPTTOL',1e-5); progTol = getOpt(o,'PROGTOL',1e-9); corrections = getOpt(o,'CORRECTIONS',100); corrections = getOpt(o,'CORR',corrections); c1 = getOpt(o,'C1',1e-4); c2 = getOpt(o,'C2',c2); LS_init = getOpt(o,'LS_INIT',LS_init); cgSolve = getOpt(o,'CGSOLVE',cgSolve); qnUpdate = getOpt(o,'QNUPDATE',3); cgUpdate = getOpt(o,'CGUPDATE',2); initialHessType = getOpt(o,'INITIALHESSTYPE',1); HessianModify = getOpt(o,'HESSIANMODIFY',0); Fref = getOpt(o,'FREF',Fref); useComplex = getOpt(o,'USECOMPLEX',0); numDiff = getOpt(o,'NUMDIFF',0); LS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1); Damped = getOpt(o,'DAMPED',Damped); HvFunc = getOpt(o,'HVFUNC',[]); bbType = getOpt(o,'BBTYPE',0); cycle = getOpt(o,'CYCLE',3); HessianIter = getOpt(o,'HESSIANITER',HessianIter); outputFcn = getOpt(o,'OUTPUTFCN',[]); useMex = getOpt(o,'USEMEX',1); useNegCurv = getOpt(o,'USENEGCURV',1); precFunc = getOpt(o,'PRECFUNC',[]); LS_type = getOpt(o,'LS_type',LS_type); LS_interp = getOpt(o,'LS_interp',LS_interp); LS_multi = getOpt(o,'LS_multi',LS_multi); end function [v] = getOpt(options,opt,default) if isfield(options,opt) if ~isempty(getfield(options,opt)) v = getfield(options,opt); else v = default; end else v = default; end end function [o] = toUpper(o) if ~isempty(o) fn = fieldnames(o); for i = 1:length(fn) o = setfield(o,upper(fn{i}),getfield(o,fn{i})); end end end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
receptive_field_size.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/utils/receptive_field_size.m
1,020
utf_8
f0d7016ce44f2dabfba5a3864e6ce202
function out = receptive_field_size() % conv1 11 55x55 % conv2 27 55x55 % pool2 35 27x27 % conv3 51 27x27 % pool3 67 13x13 % conv4 99 13x13 % conv5 131 13x13 % pool5 163 6x6 out = ... pool3_to_conv3(... conv4_to_pool3(... conv5_to_conv4(... pool5_to_conv5(1)))); return out = ... conv1_to_input(... conv2_to_conv1(... pool2_to_conv2(... conv3_to_pool2(... pool3_to_conv3(... conv4_to_pool3(... conv5_to_conv4(... pool5_to_conv5(1)))))))); function out = pool5_to_conv5(p) out = 2*(p-1)+1 + 2*floor(3/2); function out = conv5_to_conv4(p) out = 1*(p-1)+1 + 2*floor(3/2); function out = conv4_to_pool3(p) out = 1*(p-1)+1 + 2*floor(3/2); function out = pool3_to_conv3(p) out = 2*(p-1)+1 + 2*floor(3/2); function out = conv3_to_pool2(p) out = 1*(p-1)+1 + 2*floor(3/2); function out = pool2_to_conv2(p) out = 2*(p-1)+1 + 2*floor(3/2); function out = conv2_to_conv1(p) out = 1*(p-1)+1 + 2*floor(5/2); function out = conv1_to_input(p) out = 4*(p-1)+1 + 2*floor(11/2);
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
test_2010_from_2012.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/utils/test_2010_from_2012.m
1,163
utf_8
4fd6b5864d38807aaadcc7d98084912b
function test_2010_from_2012() year = '2010'; testset = 'test'; VOCdevkit2012 = './datasets/VOCdevkit2012'; VOCdevkit2010 = './datasets/VOCdevkit2010'; imdb_2012 = imdb_from_voc(VOCdevkit2012, 'test', '2012'); image_ids_2010 = get_2010_test_image_ids(); detrespath_2010 = '/work4/rbg/VOC2010/VOCdevkit/results/VOC2010/Main/%s_det_test_%s.txt'; detrespath_2012 = imdb_2012.details.VOCopts.detrespath; map = containers.Map; for i = 1:length(image_ids_2010) map(image_ids_2010{i}) = true; end for i = 1:length(imdb_2012.details.VOCopts.classes) cls = imdb_2012.details.VOCopts.classes{i}; res_fn = sprintf(detrespath_2012, 'comp4', cls); [ids, scores, x1, y1, x2, y2] = textread(res_fn, '%s %f %f %f %f %f'); res_fn = sprintf(detrespath_2010, 'comp4', cls); % write out detections in PASCAL format and score fid = fopen(res_fn, 'w'); for i = 1:length(ids) if map.isKey(ids{i}) fprintf(fid, '%s %f %d %d %d %d\n', ids{i}, scores(i), x1(i), y1(i), x2(i), y2(i)); end end fclose(fid); end function ids = get_2010_test_image_ids() fn = '/work4/rbg/VOC2012/VOCdevkit/VOC2010/ImageSets/Main/test.txt'; ids = textread(fn, '%s');
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
hdf5_dir_to_mat_dir.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/utils/hdf5_dir_to_mat_dir.m
1,283
utf_8
8dcb8efe79353e8cfcc85cce60383323
function [] = hdf5_dir_to_mat_dir(hdf5_dir_path, mat_dir_path, quiet, skip_done) assert(logical(exist(hdf5_dir_path, 'dir'))); if ~exist('quiet', 'var') quiet = false; end if ~exist('skip_done', 'var') skip_done = true; end if ~exist(mat_dir_path, 'dir') mkdir(mat_dir_path); end files = dir(sprintf('%s/*.hdf5', hdf5_dir_path)); parfor i = 1:length(files) [~, name, ~] = fileparts(files(i).name); hdf5_path = sprintf('%s/%s.hdf5', hdf5_dir_path, name); mat_path = sprintf('%s/%s.mat', mat_dir_path, name); if exist(mat_path, 'file') && skip_done continue; end hdf5_to_mat(hdf5_path, mat_path); if ~quiet fprintf('(%d/%d) Converted %s to %s\n', i, length(files), hdf5_path, mat_path); end end end function [] = hdf5_to_mat(hdf5_path, mat_path) x = hdf5_to_struct(hdf5_path); save(mat_path, '-struct', 'x'); end function x = hdf5_to_struct(hdf5_path) x.dataset = h5read(hdf5_path, '/dataset'); x.dataset = x.dataset{1}; x.gt = h5read(hdf5_path, '/gt'); x.class = h5read(hdf5_path, '/class'); x.flip = h5read(hdf5_path, '/flip'); x.overlap = h5read(hdf5_path, '/overlap')'; x.boxes = h5read(hdf5_path, '/boxes')'; x.imagename = h5read(hdf5_path, '/imagename'); x.imagename = x.imagename{1}; x.feat = h5read(hdf5_path, '/feat')'; end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
prepare_batch.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/caffe-wsl/matlab/caffe/prepare_batch.m
1,298
utf_8
68088231982895c248aef25b4886eab0
% ------------------------------------------------------------------------ function images = prepare_batch(image_files,IMAGE_MEAN,batch_size) % ------------------------------------------------------------------------ if nargin < 2 d = load('ilsvrc_2012_mean'); IMAGE_MEAN = d.image_mean; end num_images = length(image_files); if nargin < 3 batch_size = num_images; end IMAGE_DIM = 256; CROPPED_DIM = 227; indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; center = floor(indices(2) / 2)+1; num_images = length(image_files); images = zeros(CROPPED_DIM,CROPPED_DIM,3,batch_size,'single'); parfor i=1:num_images % read file fprintf('%c Preparing %s\n',13,image_files{i}); try im = imread(image_files{i}); % resize to fixed input size im = single(im); im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % Transform GRAY to RGB if size(im,3) == 1 im = cat(3,im,im,im); end % permute from RGB to BGR (IMAGE_MEAN is already BGR) im = im(:,:,[3 2 1]) - IMAGE_MEAN; % Crop the center of the image images(:,:,:,i) = permute(im(center:center+CROPPED_DIM-1,... center:center+CROPPED_DIM-1,:),[2 1 3]); catch warning('Problems with file',image_files{i}); end end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
matcaffe_demo_vgg.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/caffe-wsl/matlab/caffe/matcaffe_demo_vgg.m
3,036
utf_8
f836eefad26027ac1be6e24421b59543
function scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file) % scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file) % % Demo of the matlab wrapper using the networks described in the BMVC-2014 paper "Return of the Devil in the Details: Delving Deep into Convolutional Nets" % % INPUT % im - color image as uint8 HxWx3 % use_gpu - 1 to use the GPU, 0 to use the CPU % model_def_file - network configuration (.prototxt file) % model_file - network weights (.caffemodel file) % mean_file - mean BGR image as uint8 HxWx3 (.mat file) % % OUTPUT % scores 1000-dimensional ILSVRC score vector % % EXAMPLE USAGE % model_def_file = 'zoo/VGG_CNN_F_deploy.prototxt'; % model_file = 'zoo/VGG_CNN_F.caffemodel'; % mean_file = 'zoo/VGG_mean.mat'; % use_gpu = true; % im = imread('../../examples/images/cat.jpg'); % scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file); % % NOTES % the image crops are prepared as described in the paper (the aspect ratio is preserved) % % PREREQUISITES % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % init caffe network (spews logging info) matcaffe_init(use_gpu, model_def_file, model_file); % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im, mean_file)}; toc; % do forward pass to get scores % scores are now Width x Height x Channels x Num tic; scores = caffe('forward', input_data); toc; scores = scores{1}; % size(scores) scores = squeeze(scores); % scores = mean(scores,2); % [~,maxlabel] = max(scores); % ------------------------------------------------------------------------ function images = prepare_image(im, mean_file) % ------------------------------------------------------------------------ IMAGE_DIM = 256; CROPPED_DIM = 224; d = load(mean_file); IMAGE_MEAN = d.image_mean; % resize to fixed input size im = single(im); if size(im, 1) < size(im, 2) im = imresize(im, [IMAGE_DIM NaN]); else im = imresize(im, [NaN IMAGE_DIM]); end % RGB -> BGR im = im(:, :, [3 2 1]); % oversample (4 corners, center, and their x-axis flips) images = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices_y = [0 size(im,1)-CROPPED_DIM] + 1; indices_x = [0 size(im,2)-CROPPED_DIM] + 1; center_y = floor(indices_y(2) / 2)+1; center_x = floor(indices_x(2) / 2)+1; curr = 1; for i = indices_y for j = indices_x images(:, :, :, curr) = ... permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :)-IMAGE_MEAN, [2 1 3]); images(:, :, :, curr+5) = images(end:-1:1, :, :, curr); curr = curr + 1; end end images(:,:,:,5) = ... permute(im(center_y:center_y+CROPPED_DIM-1,center_x:center_x+CROPPED_DIM-1,:)-IMAGE_MEAN, ... [2 1 3]); images(:,:,:,10) = images(end:-1:1, :, :, curr);
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
matcaffe_demo.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/caffe-wsl/matlab/caffe/matcaffe_demo.m
3,344
utf_8
669622769508a684210d164ac749a614
function [scores, maxlabel] = matcaffe_demo(im, use_gpu) % scores = matcaffe_demo(im, use_gpu) % % Demo of the matlab wrapper using the ILSVRC network. % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = matcaffe_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format: % % convert from uint8 to single % im = single(im); % % reshape to a fixed size (e.g., 227x227) % im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % permute from RGB to BGR and subtract the data mean (already in BGR) % im = im(:,:,[3 2 1]) - data_mean; % % flip width and height to make width the fastest dimension % im = permute(im, [2 1 3]); % If you have multiple images, cat them with cat(4, ...) % The actual forward function. It takes in a cell array of 4-D arrays as % input and outputs a cell array. % init caffe network (spews logging info) if exist('use_gpu', 'var') matcaffe_init(use_gpu); else matcaffe_init(); end if nargin < 1 % For demo purposes we will use the peppers image im = imread('peppers.png'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Width x Height x Channels x Num tic; scores = caffe('forward', input_data); toc; scores = scores{1}; size(scores) scores = squeeze(scores); scores = mean(scores,2); [~,maxlabel] = max(scores); % ------------------------------------------------------------------------ function images = prepare_image(im) % ------------------------------------------------------------------------ d = load('ilsvrc_2012_mean'); IMAGE_MEAN = d.image_mean; IMAGE_DIM = 256; CROPPED_DIM = 227; % resize to fixed input size im = single(im); im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % permute from RGB to BGR (IMAGE_MEAN is already BGR) im = im(:,:,[3 2 1]) - IMAGE_MEAN; % oversample (4 corners, center, and their x-axis flips) images = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; curr = 1; for i = indices for j = indices images(:, :, :, curr) = ... permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :), [2 1 3]); images(:, :, :, curr+5) = images(end:-1:1, :, :, curr); curr = curr + 1; end end center = floor(indices(2) / 2)+1; images(:,:,:,5) = ... permute(im(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:), ... [2 1 3]); images(:,:,:,10) = images(end:-1:1, :, :, curr);
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
matcaffe_demo_vgg_mean_pix.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/caffe-wsl/matlab/caffe/matcaffe_demo_vgg_mean_pix.m
3,069
utf_8
04b831d0f205ef0932c4f3cfa930d6f9
function scores = matcaffe_demo_vgg_mean_pix(im, use_gpu, model_def_file, model_file) % scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file) % % Demo of the matlab wrapper based on the networks used for the "VGG" entry % in the ILSVRC-2014 competition and described in the tech. report % "Very Deep Convolutional Networks for Large-Scale Image Recognition" % http://arxiv.org/abs/1409.1556/ % % INPUT % im - color image as uint8 HxWx3 % use_gpu - 1 to use the GPU, 0 to use the CPU % model_def_file - network configuration (.prototxt file) % model_file - network weights (.caffemodel file) % % OUTPUT % scores 1000-dimensional ILSVRC score vector % % EXAMPLE USAGE % model_def_file = 'zoo/deploy.prototxt'; % model_file = 'zoo/model.caffemodel'; % use_gpu = true; % im = imread('../../examples/images/cat.jpg'); % scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file); % % NOTES % mean pixel subtraction is used instead of the mean image subtraction % % PREREQUISITES % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % init caffe network (spews logging info) matcaffe_init(use_gpu, model_def_file, model_file); % mean BGR pixel mean_pix = [103.939, 116.779, 123.68]; % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im, mean_pix)}; toc; % do forward pass to get scores % scores are now Width x Height x Channels x Num tic; scores = caffe('forward', input_data); toc; scores = scores{1}; % size(scores) scores = squeeze(scores); % scores = mean(scores,2); % [~,maxlabel] = max(scores); % ------------------------------------------------------------------------ function images = prepare_image(im, mean_pix) % ------------------------------------------------------------------------ IMAGE_DIM = 256; CROPPED_DIM = 224; % resize to fixed input size im = single(im); if size(im, 1) < size(im, 2) im = imresize(im, [IMAGE_DIM NaN]); else im = imresize(im, [NaN IMAGE_DIM]); end % RGB -> BGR im = im(:, :, [3 2 1]); % oversample (4 corners, center, and their x-axis flips) images = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices_y = [0 size(im,1)-CROPPED_DIM] + 1; indices_x = [0 size(im,2)-CROPPED_DIM] + 1; center_y = floor(indices_y(2) / 2)+1; center_x = floor(indices_x(2) / 2)+1; curr = 1; for i = indices_y for j = indices_x images(:, :, :, curr) = ... permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :), [2 1 3]); images(:, :, :, curr+5) = images(end:-1:1, :, :, curr); curr = curr + 1; end end images(:,:,:,5) = ... permute(im(center_y:center_y+CROPPED_DIM-1,center_x:center_x+CROPPED_DIM-1,:), ... [2 1 3]); images(:,:,:,10) = images(end:-1:1, :, :, curr); % mean BGR pixel subtraction for c = 1:3 images(:, :, c, :) = images(:, :, c, :) - mean_pix(c); end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
voc_eval.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/lib/datasets/VOCdevkit-matlab-wrapper/voc_eval.m
1,389
utf_8
fd77d0da53b2585aa65e0da5edc5fe33
function res = voc_eval(path, comp_id, test_set, output_dir, rm_res) VOCopts = get_voc_opts(path); VOCopts.testset = test_set; for i = 1:length(VOCopts.classes) cls = VOCopts.classes{i}; res(i) = voc_eval_cls(cls, VOCopts, comp_id, output_dir, rm_res); end fprintf('\n~~~~~~~~~~~~~~~~~~~~\n'); fprintf('Results:\n'); aps = [res(:).ap]'; fprintf('%.1f\n', aps * 100); fprintf('%.1f\n', mean(aps) * 100); fprintf('~~~~~~~~~~~~~~~~~~~~\n'); function res = voc_eval_cls(cls, VOCopts, comp_id, output_dir, rm_res) test_set = VOCopts.testset; year = VOCopts.dataset(4:end); addpath(fullfile(VOCopts.datadir, 'VOCcode')); res_fn = sprintf(VOCopts.detrespath, comp_id, cls); recall = []; prec = []; ap = 0; ap_auc = 0; do_eval = (str2num(year) <= 2007) | ~strcmp(test_set, 'test'); if do_eval % Bug in VOCevaldet requires that tic has been called first tic; [recall, prec, ap] = VOCevaldet(VOCopts, comp_id, cls, true); ap_auc = xVOCap(recall, prec); % force plot limits ylim([0 1]); xlim([0 1]); print(gcf, '-djpeg', '-r0', ... [output_dir '/' cls '_pr.jpg']); end fprintf('!!! %s : %.4f %.4f\n', cls, ap, ap_auc); res.recall = recall; res.prec = prec; res.ap = ap; res.ap_auc = ap_auc; save([output_dir '/' cls '_pr.mat'], ... 'res', 'recall', 'prec', 'ap', 'ap_auc'); if rm_res delete(res_fn); end rmpath(fullfile(VOCopts.datadir, 'VOCcode'));
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
roidb_from_voc.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/imdb/roidb_from_voc.m
2,742
utf_8
425a3d818c40cd19ef2879df05341668
function roidb = roidb_from_voc(imdb) % roidb = roidb_from_voc(imdb) % Builds an regions of interest database from imdb image % database. % % Inspired by Andrea Vedaldi's MKL imdb and roidb code. % AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2014, Ross Girshick % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- cache_file = ['./imdb/cache/roidb_' imdb.name]; try load(cache_file); catch VOCopts = imdb.details.VOCopts; addpath(fullfile(VOCopts.datadir, 'VOCcode')); roidb.name = imdb.name; fprintf('Loading region proposals...'); regions_file = sprintf('./data/edgebox_data/%s', roidb.name); regions = load(regions_file); fprintf('done\n'); for i = 1:length(imdb.image_ids) tic_toc_print('roidb (%s): %d/%d\n', roidb.name, i, length(imdb.image_ids)); try voc_rec = PASreadrecord(sprintf(VOCopts.annopath, imdb.image_ids{i})); catch voc_rec = []; end roidb.rois(i) = attach_proposals(voc_rec, regions.boxes{i}, imdb.class_to_id); end rmpath(fullfile(VOCopts.datadir, 'VOCcode')); fprintf('Saving roidb to cache...'); save(cache_file, 'roidb', '-v7.3'); fprintf('done\n'); end % ------------------------------------------------------------------------ function rec = attach_proposals(voc_rec, boxes, class_to_id) % ------------------------------------------------------------------------ % change the format of pre-computed object proposals from [y1 x1 y2 x2] to [x1 y1 x2 y2] boxes = boxes(:, [2 1 4 3]); % gt: [2108x1 double] % overlap: [2108x20 single] % dataset: 'voc_2007_trainval' % boxes: [2108x4 single] % feat: [2108x9216 single] % class: [2108x1 uint8] if isfield(voc_rec, 'objects') gt_boxes = cat(1, voc_rec.objects(:).bbox); all_boxes = cat(1, gt_boxes, boxes); gt_classes = class_to_id.values({voc_rec.objects(:).class}); gt_classes = cat(1, gt_classes{:}); num_gt_boxes = size(gt_boxes, 1); else gt_boxes = []; all_boxes = boxes; gt_classes = []; num_gt_boxes = 0; end num_boxes = size(boxes, 1); rec.gt = cat(1, true(num_gt_boxes, 1), false(num_boxes, 1)); rec.overlap = zeros(num_gt_boxes+num_boxes, class_to_id.Count, 'single'); for i = 1:num_gt_boxes rec.overlap(:, gt_classes(i)) = ... max(rec.overlap(:, gt_classes(i)), boxoverlap(all_boxes, gt_boxes(i, :))); end rec.boxes = single(all_boxes); rec.feat = []; rec.class = uint8(cat(1, gt_classes, zeros(num_boxes, 1)));
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
show_detections.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/vis/show_detections.m
1,339
utf_8
0d424d6872284605347fe243ed9fdf30
function show_detections(model, split, year) conf = voc_config('pascal.year', year); dataset.year = year; dataset.trainset = split; dataset.image_ids = textread(sprintf(conf.pascal.VOCopts.imgsetpath, split), '%s'); show_det(model, dataset, conf); % ------------------------------------------------------------------------ function show_det(model, dataset, conf) % ------------------------------------------------------------------------ for i = 1:length(dataset.image_ids) tic_toc_print('%s: %d/%d\n', ... procid(), i, length(dataset.image_ids)); d = load_cached_features_hos(dataset.trainset, dataset.year, dataset.image_ids{i}, model.opts); if isempty(find(d.class == model.class_id)) continue; end im = imread(sprintf(conf.pascal.VOCopts.imgpath, dataset.image_ids{i})); % boxes who overlap a gt by > 70% z = d.feat*model.w + model.b; I = find(~d.gt & z > -1); boxes = cat(2, single(d.boxes(I,:)), z(I)); [~, ord] = sort(z(I), 'descend'); ord = ord(1:min(length(ord), 20)); boxes = boxes(ord, :); % nms_interactive(im, boxes, 0.3); % keep = 1:size(boxes,1); keep = nms(boxes, 0.3); showboxes(im, boxes(keep,1:4)); pause; % for k = 1:length(keep) % showboxes(im, boxes(keep(k),1:4)); % title(sprintf('score: %.3f\n', boxes(keep(k),end))); % pause; % end end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
show_latent_choice.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/vis/show_latent_choice.m
1,567
utf_8
d4b8095cd404d6cccc29fc7061ae06b7
function show_latent_choice(model, trainset, year) conf = voc_config('pascal.year', year); dataset.year = year; dataset.trainset = trainset; dataset.image_ids = textread(sprintf(conf.pascal.VOCopts.imgsetpath, trainset), '%s'); [ids, cls_label] = textread(sprintf(conf.pascal.VOCopts.imgsetpath, [model.class '_' trainset]), '%s %d'); P = find(cls_label == 1); dataset.image_ids = ids(P); get_positive_features(model, dataset, conf); % ------------------------------------------------------------------------ function get_positive_features(model, dataset, conf) % ------------------------------------------------------------------------ thresh = 0.7; for i = 1:length(dataset.image_ids) tic_toc_print('%s: pos features %d/%d\n', ... procid(), i, length(dataset.image_ids)); d = load_cached_features(dataset.trainset, dataset.year, dataset.image_ids{i}, model.opts); d.feat = xform_feat(d.feat, model.opts); im = imread(sprintf(conf.pascal.VOCopts.imgpath, dataset.image_ids{i})); % boxes who overlap a gt by > 70% I = find(d.overlap(:,model.class_id) > thresh); zs = d.feat(I,:)*model.w + model.b; I_gt = find(d.class == model.class_id); for k = 1:length(I_gt) ovr = boxoverlap(d.boxes(I,:), d.boxes(I_gt(k),:)); %I_ovr = find((ovr > thresh) & (ovr ~= 1)); I_ovr = find(ovr > thresh); [~, argmax] = max(zs(I_ovr)); sel = I(I_ovr(argmax)); showboxesc(im, d.boxes(I_gt(k), :), 'g', '-'); showboxesc([], d.boxes(sel, :), 'r', '--'); title(sprintf('%.3f', zs(I_ovr(argmax)))); pause; end end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
sample_correlated_pairs.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/vis/sample_correlated_pairs.m
1,226
utf_8
21fba006b038c35f8dce14cedae004b7
function feature_pairs = sample_correlated_pairs(S, N) ovM = get_overlap_matrix(); feature_pairs = zeros(0, 3); for i = 1:N while true u1 = randi(size(S,1)); pos1 = mod(u1-1, 36)+1; ov = ovM(pos1,:); ok = repmat((ov < 1/3), [1 256]); ok(u1-pos1+1:u1-pos1+36) = 0; row = S(u1, :); row(~ok) = -inf; [~, ord] = sort(row, 'descend'); u2 = ord(1); if S(u1, u2) > 0 feature_pairs = cat(1, feature_pairs, [u1 u2 S(u1, u2)]); break; end end end [~, ord] = sort(feature_pairs(:,3), 'descend'); feature_pairs = feature_pairs(ord,:); function ovM = get_overlap_matrix() ovM = zeros(36); s = 224/6; points = round(s/2:s:224); for i = 1:36 M = zeros(6,6,256); M(i) = 1; M = sum(M, 3)'; [r,c] = find(M); r1_1 = max(1, points(r) - 81); r1_2 = min(224, points(r) + 81); c1_1 = max(1, points(c) - 81); c1_2 = min(224, points(c) + 81); for j = 1:36 M = zeros(6,6,256); M(j) = 1; M = sum(M, 3)'; [r,c] = find(M); r2_1 = max(1, points(r) - 81); r2_2 = min(224, points(r) + 81); c2_1 = max(1, points(c) - 81); c2_2 = min(224, points(c) + 81); ovM(i,j) = boxoverlap([c1_1 r1_1 c1_2 r1_2], [c2_1 r2_1 c2_2 r2_2]); end end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
pick_feature_pair.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/vis/pick_feature_pair.m
1,089
utf_8
bee9f65c9d04ab2cb76538687f40bacc
function feature_pairs = pick_feature_pair(model, N) ovM = get_overlap_matrix(); feature_pairs = zeros(0, 2); [~, w_ord] = sort(model.w, 'descend'); for i = 1:N u1 = w_ord(i); pos1 = mod(u1-1, 36)+1; ov = ovM(pos1,:); ok = repmat((ov < 1/3), [1 256]); ok(u1-pos1+1:u1-pos1+36) = 0; w = model.w; w(~ok) = -inf; [~, ord] = sort(w, 'descend'); u2 = ord(1); feature_pairs = cat(1, feature_pairs, [u1 u2]); end function ovM = get_overlap_matrix() ovM = zeros(36); s = 224/6; points = round(s/2:s:224); for i = 1:36 M = zeros(6,6,256); M(i) = 1; M = sum(M, 3)'; [r,c] = find(M); r1_1 = max(1, points(r) - 81); r1_2 = min(224, points(r) + 81); c1_1 = max(1, points(c) - 81); c1_2 = min(224, points(c) + 81); for j = 1:36 M = zeros(6,6,256); M(j) = 1; M = sum(M, 3)'; [r,c] = find(M); r2_1 = max(1, points(r) - 81); r2_2 = min(224, points(r) + 81); c2_1 = max(1, points(c) - 81); c2_2 = min(224, points(c) + 81); ovM(i,j) = boxoverlap([c1_1 r1_1 c1_2 r1_2], [c2_1 r2_1 c2_2 r2_2]); end end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
viewerrors.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/vis/viewerrors.m
10,275
utf_8
984e38a9624546fc0ba466aed666d8cf
function ap = viewerrors(model, boxes, testset, year, saveim) % For visualizing mistakes on a validation set % AUTORIGHTS % ------------------------------------------------------- % Copyright (C) 2009-2012 Ross Girshick % % This file is part of the voc-releaseX code % (http://people.cs.uchicago.edu/~rbg/latent/) % and is available under the terms of an MIT-like license % provided in COPYING. Please retain this notice and % COPYING if you use this file (or a portion of it) in % your project. % ------------------------------------------------------- SHOW_TP = true; SHOW_FP = true; SHOW_FN = true; im_path = sprintf('~/public_html/private/convnet-sel-search/%s/', model.class); if exist(im_path) == 0 unix(['mkdir -p ' im_path]); end fp_html = [im_path 'fp.html']; fn_html = [im_path 'fn.html']; tp_html = [im_path 'tp.html']; index_html = [im_path 'index.html']; if saveim htmlfid = fopen(index_html, 'w'); fprintf(htmlfid, '<html><body>'); fprintf(htmlfid, '<h2>%s</h2>', model.class); fprintf(htmlfid, '<a href="tp.html">true positives</a><br />'); fprintf(htmlfid, '<a href="fp.html">false positives</a><br />'); fprintf(htmlfid, '<a href="fn.html">missed</a><br />'); fprintf(htmlfid, '</html></body>'); end warning on verbose; warning off MATLAB:HandleGraphics:noJVM; cls = model.class; conf = voc_config('pascal.year', year, ... 'eval.test_set', testset); VOCopts = conf.pascal.VOCopts; cachedir = conf.paths.model_dir; % Load test set ground-truth fprintf('%s: viewerrors: loading ground truth\n', cls); [gtids, recs, hash, gt, npos] = load_ground_truth(cls, conf); % Load detections from the model [ids, confidence, BB] = get_detections(boxes, cls, conf); % sort detections by decreasing confidence [sc, si] = sort(-confidence); ids = ids(si); BB = BB(:,si); % assign detections to ground truth objects nd = length(confidence); tp = zeros(nd,1); fp = zeros(nd,1); md = zeros(nd,1); od = zeros(nd,1); jm = zeros(nd,1); for d = 1:nd % display progress tic_toc_print('%s: pr: compute: %d/%d\n', cls, d, nd); % find ground truth image i = xVOChash_lookup(hash, ids{d}); if isempty(i) error('unrecognized image "%s"', ids{d}); elseif length(i) > 1 error('multiple image "%s"', ids{d}); end % assign detection to ground truth object if any % reported detection bb = BB(:,d); ovmax = -inf; jmax = 0; % loop over bounding boxes for this class in the gt image for j = 1:size(gt(i).BB,2) % consider j-th gt box bbgt = gt(i).BB(:,j); % compute intersection box bi = [max(bb(1), bbgt(1)); ... max(bb(2), bbgt(2)); ... min(bb(3), bbgt(3)); ... min(bb(4), bbgt(4))]; iw = bi(3)-bi(1)+1; ih = bi(4)-bi(2)+1; if iw > 0 & ih > 0 % compute overlap as area of intersection / area of union ua = (bb(3)-bb(1)+1) * (bb(4)-bb(2)+1) + ... (bbgt(3)-bbgt(1)+1) * (bbgt(4)-bbgt(2)+1) - ... iw * ih; ov = iw * ih / ua; if ov > ovmax ovmax = ov; jmax = j; end end end % assign detection as true positive/don't care/false positive if jmax > 0 && ovmax > gt(i).overlap(jmax) gt(i).overlap(jmax) = ovmax; gt(i).best_boxes(jmax,:) = bb'; end od(d) = ovmax; jm(d) = jmax; if ovmax >= VOCopts.minoverlap if ~gt(i).diff(jmax) if ~gt(i).det(jmax) % true positive tp(d) = 1; gt(i).det(jmax) = true; gt(i).tp_boxes(jmax,:) = bb'; else % false positive (multiple detection) fp(d) = 1; md(d) = 1; end end else % false positive (low or no overlap) fp(d) = 1; end end % compute precision/recall cfp = cumsum(fp); ctp = cumsum(tp); rec = ctp/npos; prec = ctp./(cfp+ctp); fprintf('total recalled = %d/%d (%.1f%%)\n', sum(tp), npos, 100*sum(tp)/npos); if SHOW_TP if saveim htmlfid = fopen(tp_html, 'w'); fprintf(htmlfid, '<html><body>'); end fprintf('displaying true positives\n'); count = 0; d = 1; while d < nd && count < 400 if tp(d) count = count + 1; i = xVOChash_lookup(hash, ids{d}); im = imread([VOCopts.datadir recs(i).imgname]); % Recompute the detection to get the derivation tree score = -sc(d); subplot(1,2,1); imagesc(im); axis image; axis off; subplot(1,2,2); showboxesc(im, BB(:,d)', 'r', '-'); str = sprintf('%d det# %d/%d: @prec: %0.3f @rec: %0.3f\nscore: %0.3f GT overlap: %0.3f', count, d, nd, prec(d), rec(d), -sc(d), od(d)); fprintf('%s', str); title(str); fprintf('\n'); if saveim cmd = sprintf('export_fig %s/%s-%d-tp.jpg -jpg', im_path, cls, d); eval(cmd); fprintf(htmlfid, sprintf('<img src="%s-%d-tp.jpg" />\n', cls, d)); fprintf(htmlfid, '<br /><br />\n'); else pause; end end d = d + 1; end if saveim fprintf(htmlfid, '</body></html>'); fclose(htmlfid); end end if SHOW_FP if saveim htmlfid = fopen(fp_html, 'w'); fprintf(htmlfid, '<html><body>'); end fprintf('displaying false positives\n'); count = 0; d = 1; while d < nd && count < 400 if fp(d) count = count + 1; i = xVOChash_lookup(hash, ids{d}); im = imread([VOCopts.datadir recs(i).imgname]); % Recompute the detection to get the derivation tree score = -sc(d); subplot(1,2,1); imagesc(im); axis image; axis off; subplot(1,2,2); showboxesc(im, BB(:,d)', 'r', '-'); str = sprintf('%d det# %d/%d: @prec: %0.3f @rec: %0.3f\nscore: %0.3f GT overlap: %0.3f', count, d, nd, prec(d), rec(d), -sc(d), od(d)); if md(d) str = sprintf('%s mult det', str); end if fp(d) && jm(d) > 0 str = sprintf('%s\nmax overlap all det: %0.3f', str, gt(i).overlap(jm(d))); end fprintf('%s', str); title(str); fprintf('\n'); if saveim cmd = sprintf('export_fig %s/%s-%d-fp.jpg -jpg', im_path, cls, d); eval(cmd); fprintf(htmlfid, sprintf('<img src="%s-%d-fp.jpg" />\n', cls, d)); fprintf(htmlfid, '<br /><br />\n'); else pause; end end d = d + 1; end if saveim fprintf(htmlfid, '</body></html>'); fclose(htmlfid); end end if SHOW_FN % to find false negatives loop over gt(i) and display any box that has % gt(i).det(j) == false && ~gt(i).diff(j) fprintf('displaying false negatives\n'); if saveim htmlfid = fopen(fn_html, 'w'); fprintf(htmlfid, '<html><body>'); end clf; count = 0; for i = 1:length(gt) if count >= 200 break; end s = 0; if ~isempty(gt(i).det) s = sum((~gt(i).diff)' .* (~gt(i).det)); end if s > 0 diff = []; fn = []; tp = []; best_boxes = []; best_ovrs = []; fprintf('%d\n', i); [gt(i).diff(:) gt(i).det(:) gt(i).overlap(:)] for j = 1:length(gt(i).det) bbgt = gt(i).BB(:,j)'; if gt(i).diff(j) diff = [diff; [bbgt 0]]; elseif ~gt(i).det(j) fn = [fn; [bbgt 1]]; best_boxes = cat(1, best_boxes, gt(i).best_boxes(j,:)); best_ovrs = cat(1, best_ovrs, gt(i).overlap(j)); else tp = [tp; [bbgt 2]]; tp = [tp; [gt(i).tp_boxes(j,:) 3]]; end end im = imread([VOCopts.datadir recs(i).imgname]); showboxesc(im, [diff; fn; tp]); for j = 1:length(best_ovrs) if best_ovrs(j) > -inf showboxesc([], best_boxes(j,:), 'y', '--'); text(best_boxes(j,1), best_boxes(j,2), sprintf('%0.3f', best_ovrs(j)), 'BackgroundColor', [.7 .9 .7]); end end if saveim cmd = sprintf('export_fig %s/%s-%d-fn.jpg -jpg', im_path, cls, count); eval(cmd); fprintf(htmlfid, sprintf('<img src="%s-%d-fn.jpg" />\n', cls, count)); fprintf(htmlfid, '<br /><br />\n'); else pause; end; count = count + 1; end end if saveim fprintf(htmlfid, '</body></html>'); fclose(htmlfid); end end function [gtids, recs, hash, gt, npos] = load_ground_truth(cls, conf) VOCopts = conf.pascal.VOCopts; year = conf.pascal.year; cachedir = conf.paths.model_dir; testset = conf.eval.test_set; cp = [cachedir cls '_ground_truth_' testset '_' year]; try load(cp, 'gtids', 'recs', 'hash', 'gt', 'npos'); catch [gtids, t] = textread(sprintf(VOCopts.imgsetpath,VOCopts.testset), '%s %d'); for i = 1:length(gtids) % display progress tic_toc_print('%s: pr: load: %d/%d\n', cls, i, length(gtids)); % read annotation recs(i) = PASreadrecord(sprintf(VOCopts.annopath, gtids{i})); end % hash image ids hash = xVOChash_init(gtids); % extract ground truth objects npos = 0; gt(length(gtids)) = struct('BB', [], 'diff', [], 'det', [], 'overlap', [], 'tp_boxes', []); for i = 1:length(gtids) % extract objects of class clsinds = strmatch(cls, {recs(i).objects(:).class}, 'exact'); gt(i).BB = cat(1, recs(i).objects(clsinds).bbox)'; gt(i).diff = [recs(i).objects(clsinds).difficult]; gt(i).det = false(length(clsinds), 1); gt(i).overlap = -inf*ones(length(clsinds), 1); gt(i).tp_boxes = zeros(length(clsinds), 4); gt(i).best_boxes = zeros(length(clsinds), 4); npos = npos + sum(~gt(i).diff); end save(cp, 'gtids', 'recs', 'hash', 'gt', 'npos'); end function [ids, confidence, BB] = get_detections(boxes, cls, conf) VOCopts = conf.pascal.VOCopts; year = conf.pascal.year; cachedir = conf.paths.model_dir; testset = conf.eval.test_set; ids = textread(sprintf(VOCopts.imgsetpath, testset), '%s'); % Write and read detection data in the same way as pascal_eval.m % and the VOCdevkit % write out detections in PASCAL format and score fid = fopen(sprintf(VOCopts.detrespath, 'comp3', cls), 'w'); for i = 1:length(ids); bbox = boxes{i}; keep = nms(bbox, 0.3); bbox = bbox(keep,:); for j = 1:size(bbox,1) fprintf(fid, '%s %.14f %d %d %d %d\n', ids{i}, bbox(j,end), bbox(j,1:4)); end end fclose(fid); [ids, confidence, b1, b2, b3, b4] = ... textread(sprintf(VOCopts.detrespath, 'comp3', cls), '%s %f %f %f %f %f'); BB = [b1 b2 b3 b4]';
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
vis_crops.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/vis/vis_crops.m
2,193
utf_8
a32583168a0ca9cc94afbeca8755a8b4
function vis_crops(imdb) opts.net_file = './data/caffe_nets/finetune_voc_2007_trainval_iter_70k'; opts.net_def_file = './model-defs/rcnn_batch_256_output_pool5.prototxt'; % load the region of interest database roidb = imdb.roidb_func(imdb); rcnn_model = rcnn_create_model(opts.net_def_file, opts.net_file); rcnn_model = rcnn_load_model(rcnn_model); image_mean = rcnn_model.cnn.image_mean; im_perm = randperm(length(imdb.image_ids)); for i = im_perm d = roidb.rois(i); im = single(imread(imdb.image_at(i))); num_boxes = size(d.boxes, 1); crop_size = size(image_mean,1); perm = randperm(size(d.boxes, 1), 10); for j = perm bbox = d.boxes(j,:); src = im(bbox(2):bbox(4), bbox(1):bbox(3), :); crop_warp_0 = rcnn_im_crop(im, bbox, 'warp', crop_size, 0, image_mean); crop_warp_16 = rcnn_im_crop(im, bbox, 'warp', crop_size, 16, image_mean); crop_square_0 = rcnn_im_crop(im, bbox, 'square', crop_size, 0, image_mean); crop_square_16 = rcnn_im_crop(im, bbox, 'square', crop_size, 16, image_mean); max_val = max(cat(1, crop_warp_0(:), crop_warp_16(:), ... crop_square_0(:), crop_square_16(:))); min_val = min(cat(1, crop_warp_0(:), crop_warp_16(:), ... crop_square_0(:), crop_square_16(:))); src = normalize(src, max(src(:)), min(src(:))); crop_warp_0 = normalize(crop_warp_0, max_val, min_val); crop_warp_16 = normalize(crop_warp_16, max_val, min_val); crop_square_0 = normalize(crop_square_0, max_val, min_val); crop_square_16 = normalize(crop_square_16, max_val, min_val); subplot(2, 4, 1); imagesc(src); title('src'); axis image; axis off; subplot(2, 4, 5); imagesc(crop_warp_0); title('warp 0'); axis image; axis off; subplot(2, 4, 6); imagesc(crop_warp_16); title('warp 16'); axis image; axis off; subplot(2, 4, 7); imagesc(crop_square_0); title('square 0'); axis image; axis off; subplot(2, 4, 8); imagesc(crop_square_16); title('square 16'); axis image; axis off; pause; end end function A = normalize(A, max_val, min_val) range = max_val - min_val; A = (A - min_val) / (range + eps);
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
pool5_explorer.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/vis/pool5-explorer/pool5_explorer.m
6,690
utf_8
a1c8558f0e1f3580833ccc05c8629d9e
function pool5_explorer(imdb, cache_name) % AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2014, Ross Girshick % % This file is part of the R-CNN code and is available % under the terms of the Simplified BSD License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- conf = rcnn_config('sub_dir', imdb.name); index = pool5_explorer_build_index(imdb, cache_name); figures = [1 2]; vf_sz = [8 12]; redraw = true; position = 1; channel = 0; cell_y = 2; cell_x = 2; feature_index = get_feature_index(channel, cell_y, cell_x); while 1 if redraw feature_index = get_feature_index(channel, cell_y, cell_x); visualize_feature(imdb, figures(2), index, feature_index, position, ... vf_sz, cell_y, cell_x, channel); redraw = false; end % display 16x16 grid where each cell shows a 6x6 feature map % wait for mouse click % -> map click coordinates to feature dimension [~, ~, ~, ~, key_code] = get_feature_selection(1); switch key_code case 27 % ESC close(figures(ishandle(figures))); return; case '`' return; case 's' % take a snapshot filename = sprintf('./vis/pool5-explorer/shots/x%d-y%d-c%d-p%d.pdf', ... cell_y, cell_x, channel, position); if exist(filename) delete(filename); end export_fig(filename); case 'g' % go to a specific channel answer = str2double(inputdlg('go to channel:')); if ~isempty(answer) answer = round(answer); if answer > 0 channel = answer - 1; redraw = true; end end case 31 % up % decrease channel if channel > 0 channel = channel - 1; position = 1; redraw = true; end case 30 % down % increase channel if channel < 255 channel = channel + 1; position = 1; redraw = true; end case 'i' % cell up if cell_y > 0 cell_y = cell_y - 1; position = 1; redraw = true; end case 'k' % cell down if cell_y < 5 cell_y = cell_y + 1; position = 1; redraw = true; end case 'j' % cell left if cell_x > 0 cell_x = cell_x - 1; position = 1; redraw = true; end case 'l' % cell right if cell_x < 5 cell_x = cell_x + 1; position = 1; redraw = true; end case 29 % -> new_pos = position + prod(vf_sz); if new_pos < length(index.features{feature_index}.scores) position = new_pos; redraw = true; end case 28 % <- new_pos = position - prod(vf_sz); if new_pos > 0 position = new_pos; redraw = true; end otherwise fprintf('%d\n', key_code); end end % ------------------------------------------------------------------------ function f = get_feature_index(channel, cell_y, cell_x) % ------------------------------------------------------------------------ f = channel*36 + cell_y*6 + cell_x + 1; % ------------------------------------------------------------------------ function visualize_feature(imdb, fig, index, f, position, msz, cell_y, cell_x, channel) % ------------------------------------------------------------------------ max_val = 0; for x_ = 0:5 for y_ = 0:5 f_ = get_feature_index(channel, y_, x_); max_val = max([max_val; index.features{f_}.scores]); end end s = 227/6; points = round(s/2:s:227); M = zeros(6,6,256); M(f) = 1; M = sum(M, 3)'; half_receptive_field = floor(195/2); [r,c] = find(M); r1 = max(1, points(r) - half_receptive_field); r2 = min(227, points(r) + half_receptive_field); c1 = max(1, points(c) - half_receptive_field); c2 = min(227, points(c) + half_receptive_field); h = r2-r1; w = c2-c1; psx = 96; psy = 96; h = h * psy/227; w = w * psx/227; context_padding = round(16/227 * 96); r1 = (r1-1)*psy/227 + 1; c1 = (c1-1)*psx/227 + 1; ims = {}; start_pos = position; end_pos = min(length(index.features{f}.scores), start_pos + prod(msz) - 1); N = end_pos - start_pos + 1; str = sprintf('pool5 feature: (%d,%d,%d) (top %d - %d)', cell_y+1, cell_x+1, channel+1, start_pos, end_pos); for i = start_pos:end_pos val = index.features{f}.scores(i); image_ind = index.features{f}.image_inds(i); bbox = index.features{f}.boxes(i, :); im = imread(imdb.image_at(image_ind)); im = rcnn_im_crop(im, bbox, 'warp', psx, context_padding, []); ims{end+1} = uint8(im); end filler = prod(msz) - N; im = my_montage(cat(4, ims{:}, 256*ones(psy, psx, 3, filler)), msz); figure(2); clf; imagesc(im); title(str, 'Color', 'black', 'FontSize', 18, 'FontName', 'Times New Roman'); axis image; axis off; set(gcf, 'Color', 'white'); q = 1; for y = 0:msz(1)-1 for x = 0:msz(2)-1 if q > N break; end x1 = c1+psx*x; y1 = r1+psy*y; rectangle('Position', [x1 y1 w h], 'EdgeColor', 'w', 'LineWidth', 3); text(x1, y1+7.5, sprintf('%.1f', index.features{f}.scores(start_pos+q-1)/max_val), 'BackgroundColor', 'w', 'FontSize', 10, 'Margin', 0.1, 'FontName', 'Times New Roman'); q = q + 1; end if q > N break; end end if 0 % compute mean figure num_to_avg = 40; scores = index.features{f}.scores(start_pos:end_pos); for i = 1:num_to_avg ims{i} = double(ims{i})*scores(i)/sum(scores(1:num_to_avg)); end figure(1); imagesc(uint8(sum(cat(4, ims{1:num_to_avg}), 4))); axis image; figure(2); end % ------------------------------------------------------------------------ function [feature_index, channel, cell_y, cell_x, ch] = ... get_feature_selection(channel_width) % ------------------------------------------------------------------------ while 1 [x,y,ch] = ginput(1); chan_y = floor(y/channel_width); chan_x = floor(x/channel_width); channel = chan_y*16 + chan_x; cell_y = floor(rem(y, channel_width)/7); cell_x = floor(rem(x, channel_width)/7); feature_index = channel*36 + cell_y*6 + cell_x + 1; if (channel < 0 || channel > 255) channel = nan; end if isscalar(ch) return; end end % ------------------------------------------------------------------------ function im = my_montage(ims, sz) % ------------------------------------------------------------------------ ims_sz = [size(ims, 1) size(ims, 2)]; im = zeros(ims_sz(1)*sz(1), ims_sz(2)*sz(2), 3, class(ims)); k = 1; for y = 0:sz(1)-1 for x = 0:sz(2)-1 im(y*ims_sz(1)+1:(y+1)*ims_sz(1), ... x*ims_sz(2)+1:(x+1)*ims_sz(2), :) = ims(:,:,:,k); k = k + 1; end end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
cache_fc8_features.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/features/cache_fc8_features.m
2,355
utf_8
6260d287c993b2ffddd3e8818e88c87f
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2014, Ross Girshick % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function cache_fc8_features(imdb, varargin) ip = inputParser; ip.addRequired('imdb', @isstruct); ip.addOptional('start', 1, @isscalar); ip.addOptional('end', 0, @isscalar); ip.addOptional('crop_mode', 'warp', @isstr); ip.addOptional('crop_padding', 16, @isscalar); ip.addOptional('net_file', '', @isstr); ip.addOptional('cache_name', '', @isstr); ip.parse(imdb, varargin{:}); opts = ip.Results; opts.net_def_file = './prototxt/caffenet_fc8.prototxt'; opts.batch_size = 50; opts.crop_size = 227; image_ids = imdb.image_ids; if opts.end == 0 opts.end = length(image_ids); end % Where to save feature cache if ~exist('cache','file') mkdir('cache'); end opts.output_dir = ['./cache/' opts.cache_name '/']; mkdir_if_missing(opts.output_dir); fprintf('\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'); fprintf('Feature caching options:\n'); disp(opts); fprintf('~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n'); % load the region of interest database roidb = imdb.roidb_func(imdb); if caffe('is_initialized') == 0 caffe('init', opts.net_def_file, opts.net_file, 'test'); end % caffe('set_mode_cpu'); caffe('set_mode_gpu'); % caffe('set_device',3); total_time = 0; count = 0; for i = opts.start:opts.end fprintf('%s: cache features: %d/%d\n', procid(), i, opts.end); save_file = [opts.output_dir image_ids{i} '.mat']; if exist(save_file, 'file') ~= 0 fprintf(' [already exists]\n'); continue; end count = count + 1; tot_th = tic; d = roidb.rois(i); im = imread(imdb.image_at(i)); if size(im,3)~=3 im = cat(3,im,im,im); end th = tic; d.feat_in = cache_bb_features(im, d.boxes, opts, 1); d.feat_out = cache_bb_features(im, d.boxes, opts, 2); fprintf(' [features: %.3fs]\n', toc(th)); th = tic; save(save_file, '-struct', 'd'); fprintf(' [saving: %.3fs]\n', toc(th)); total_time = total_time + toc(tot_th); fprintf(' [avg time: %.3fs (total: %.3fs)]\n', ... total_time/count, total_time); end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
cache_bb_features.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/features/cache_bb_features.m
1,193
utf_8
2d2afacf8926b9d190c11871368e83be
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2014, Ross Girshick % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function feat = cache_bb_features(im, boxes, opts, flag) [batches, batch_padding] = extract_regions(im, boxes, opts, flag); batch_size = opts.batch_size; % compute features for each batch of region images feat_dim = -1; feat = []; curr = 1; for j = 1:length(batches) % forward propagate batch of region images f = caffe('forward', batches(j)); f = f{1}; f = f(:); % first batch, init feat_dim and feat if j == 1 feat_dim = length(f)/batch_size; feat = zeros(size(boxes,1), feat_dim, 'single'); end f = reshape(f, [feat_dim batch_size]); % last batch, trim f to size if j == length(batches) if batch_padding > 0 f = f(:, 1:end-batch_padding); end end feat(curr:curr+size(f,2)-1,:) = f'; curr = curr + batch_size; end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
extract_regions.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/features/extract_regions.m
1,980
utf_8
d08caf471fa445373bc5508454f8ae42
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2014, Ross Girshick % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function [batches, batch_padding] = extract_regions(im, boxes, opts, flag) if flag == 1 im = single(im); num_boxes = size(boxes, 1); batch_size = opts.batch_size; crop_size = opts.crop_size; num_batches = ceil(num_boxes / batch_size); batch_padding = batch_size - mod(num_boxes, batch_size); if batch_padding == batch_size batch_padding = 0; end batches = cell(num_batches, 1); for batch = 1:num_batches batch_start = (batch-1)*batch_size+1; batch_end = min(num_boxes, batch_start+batch_size-1); ims = zeros(crop_size, crop_size, 3, batch_size, 'single'); for j = batch_start:batch_end bbox = boxes(j,:); ims(:,:,:,j-batch_start+1) = extract_region_in(im, bbox); end batches{batch} = ims; end end if flag == 2 im = single(im); num_boxes = size(boxes, 1); batch_size = opts.batch_size; crop_size = opts.crop_size; num_batches = ceil(num_boxes / batch_size); batch_padding = batch_size - mod(num_boxes, batch_size); if batch_padding == batch_size batch_padding = 0; end batches = cell(num_batches, 1); for batch = 1:num_batches batch_start = (batch-1)*batch_size+1; batch_end = min(num_boxes, batch_start+batch_size-1); ims = zeros(crop_size, crop_size, 3, batch_size, 'single'); for j = batch_start:batch_end bbox = boxes(j,:); ims(:,:,:,j-batch_start+1) = extract_region_out(im, bbox); end batches{batch} = ims; end end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
extract_region_in.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/features/extract_region_in.m
917
utf_8
7a3cd9d842a57d3d621b53c741a46786
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function im_in = extract_region_in(im, bbox) crop_size = 227; padding = 16; scale = crop_size/(crop_size - padding*2); half_height = (bbox(4)-bbox(2)+1)/2; half_width = (bbox(3)-bbox(1)+1)/2; center = [bbox(1)+half_width bbox(2)+half_height]; bbox = round([center center] + [-half_width -half_height half_width half_height]*scale); bbox(1) = max(1, bbox(1)); bbox(2) = max(1, bbox(2)); bbox(3) = min(size(im,2), bbox(3)); bbox(4) = min(size(im,1), bbox(4)); im_in = im(bbox(2):bbox(4),bbox(1):bbox(3),:); im_in = preprocess(im_in);
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
cache_fc7_features.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/features/cache_fc7_features.m
2,983
utf_8
31c412dffc553f13a6e43e95aceed71e
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2014, Ross Girshick % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function cache_fc7_features(imdb, varargin) ip = inputParser; ip.addRequired('imdb', @isstruct); ip.addOptional('start', 1, @isscalar); ip.addOptional('end', 0, @isscalar); ip.addOptional('crop_mode', 'warp', @isstr); ip.addOptional('crop_padding', 16, @isscalar); ip.addOptional('net_file', '', @isstr); ip.addOptional('cache_name', '', @isstr); ip.parse(imdb, varargin{:}); opts = ip.Results; opts.net_def_file = './prototxt/caffenet_fc7.prototxt'; opts.batch_size = 50; opts.crop_size = 227; image_ids = imdb.image_ids; if opts.end == 0 opts.end = length(image_ids); end % Where to save feature cache if ~exist('cache','file') mkdir('cache'); end opts.train_output_dir = ['./cache/' opts.cache_name '/mil_train/']; mkdir_if_missing(opts.train_output_dir); opts.test_output_dir = ['./cache/' opts.cache_name '/mil_test/']; mkdir_if_missing(opts.test_output_dir); fprintf('\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'); fprintf('Feature caching options:\n'); disp(opts); fprintf('~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n'); % load the region of interest database roidb = imdb.roidb_func(imdb); caffe('init', opts.net_def_file, opts.net_file, 'test'); % caffe('set_mode_cpu'); caffe('set_mode_gpu'); % caffe('set_device',3); total_time = 0; count = 0; load('results_maskout_regions.mat'); for i = opts.start:opts.end fprintf('%s: cache features: %d/%d\n', procid(), i, opts.end); % using all the proposals for mil testing test_save_file = [opts.test_output_dir image_ids{i} '.mat']; if exist(test_save_file, 'file') ~= 0 fprintf(' [already exists]\n'); continue; end count = count + 1; tot_th = tic; d = roidb.rois(i); im = imread(imdb.image_at(i)); if size(im,3)~=3 im = cat(3,im,im,im); end th = tic; d.feat = cache_bb_features(im, d.boxes, opts, 1); fprintf(' [features: %.3fs]\n', toc(th)); th = tic; save(test_save_file, '-struct', 'd'); fprintf(' [saving: %.3fs]\n', toc(th)); total_time = total_time + toc(tot_th); fprintf(' [avg time: %.3fs (total: %.3fs)]\n', ... total_time/count, total_time); % using the selected proposals for mil training train_save_file = [opts.train_output_dir image_ids{i} '.mat']; if exist(train_save_file, 'file') ~= 0 fprintf(' [already exists]\n'); continue; end num_gt = sum(d.gt); IND_GT = find(d.gt == 1); ind = [IND_GT;IND{i}+num_gt]; ind = unique(ind); d.boxes = d.boxes(ind,:); d.class = d.class(ind,:); d.gt = d.gt(ind,:); d.overlap = d.overlap(ind,:); d.feat = d.feat(ind,:); save(train_save_file, '-struct', 'd'); end
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
extract_region_out.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/features/extract_region_out.m
747
utf_8
545ca74e438fdb1087702203fa974a19
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function im_out = extract_region_out(im, bbox) im_out = im; bbox(1) = max(1, bbox(1)); bbox(2) = max(1, bbox(2)); bbox(3) = min(size(im,2), bbox(3)); bbox(4) = min(size(im,1), bbox(4)); im_out(bbox(2):bbox(4),bbox(1):bbox(3),1) = 123; im_out(bbox(2):bbox(4),bbox(1):bbox(3),2) = 117; im_out(bbox(2):bbox(4),bbox(1):bbox(3),3) = 104; im_out = preprocess(im_out);
github
wupeng78/Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master
preprocess.m
.m
Weakly-Supervised-Object-Localization-with-Progressive-Domain-Adaptation-CVPR-2016--master/features/preprocess.m
778
utf_8
8d861cb5445de961ec1a8bef66e0b94e
% AUTORIGHTS % --------------------------------------------------------- % Copyright (c) 2016, Dong Li % % This file is part of the WSL code and is available % under the terms of the MIT License provided in % LICENSE. Please retain this notice and LICENSE if you use % this file (or any portion of it) in your project. % --------------------------------------------------------- function im = preprocess(im) im = imresize(im, [227 227], 'bilinear'); % permute from RGB to BGR and subtract the data mean im = im(:,:,[3 2 1]); % RGB to BGR im(:,:,1) = im(:,:,1) - 104; % subtract B mean 104 im(:,:,2) = im(:,:,2) - 117; % subtract G mean 117 im(:,:,3) = im(:,:,3) - 123; % subtract R mean 123 % make width the fastest dimension, convert to single im = permute(im, [2 1 3]);
github
dswinters/ocean-tools-master
parse_adcp.m
.m
ocean-tools-master/parse_adcp.m
15,543
utf_8
c2a0b235190fbf1326886e90c35aebdd
%% parse_adcp.m % % Usage % adcp = parse_adcp(files) % adcp = parse_adcp(files, parse_nuc_timestamps) % adcp = parse_adcp(... , 'progress', uiprogressdlg) % % Inputs % - dat_or_file % This can be a filename, cell array of filenames, the output of MATLAB's % "dir" command, or an array of binary data. % % Optional Arguments % - parse_nuc_timestamps (logical) % | Flag to parse Nuc timestamps inserted into the ADCP_timestamped* files from % | ROSE deployments. % % Name-value pair arguments % - 'progress' % Specify a UI progress dialog handle to update it with progress information while % parsing data. % % Outputs % - adcp % Data structure containing ADCP fields. % % Author % - Dylan Winters ([email protected]) function adcp = parse_adcp(dat_or_file,varargin) %% Parse optional inputs p = inputParser; addOptional(p,'parse_nuc_timestamps',false,@(x) islogical(x)) addParameter(p,'progress',struct(),@(x) isa(x,'matlab.ui.dialog.ProgressDialog')); parse(p,varargin{:}); progress = p.Results.progress; parse_nuc_timestamps = p.Results.parse_nuc_timestamps; nuc_offset = 0; if parse_nuc_timestamps nuc_offset = 7; end %% Main parsing routine % 1) Load binary data if iscell(dat_or_file) % Cell array of filenames dat = load_data(dat_or_file,progress); elseif isstruct(dat_or_file) % File info struct from dir() dat = load_data(fullfile({dat_or_file.folder},{dat_or_file.name}),progress); elseif isstring(dat_or_file) | ischar(dat_or_file) % Single filename dat = load_data({dat_or_file},progress); else % Treat input as raw data dat = dat_or_file; end [h len] = find_headers(dat,progress); % find header locations if isempty(h) adcp = []; return end %% Fill adcp data structure with ensemble data progress.Message = 'ADCP: Processing data...'; progress.Indeterminate = 'on'; % Loop over unique ensemble lengths (there coule be multiple, e.g. for Sentinel % V's multi-profile mode) [u,~,iu] = unique(len); for nl = 1:length(u) dat_idx = h(iu==nl) + [-nuc_offset:u(nl)-1]; % dat_idx = h(iu==nl) + [-nuc_offset:u(nl)+3]; % FIXME: include checksums adcp(nl) = parse_ensemble_data(dat(dat_idx)); end progress.Indeterminate = 'off'; progress.Message = 'ADCP: Processing data... Done!'; function dat = load_data(files,progress) %---------------------------------------------------------- % Read and concatenate data in the given list of files %---------------------------------------------------------- dat = []; for i = 1:length(files) if ~exist(files{i},'file') error('File not found: %s',files{i}) end [~,fname,fext] = fileparts(files{i}); progress.Message = sprintf('ADCP: Opening %s %s [%d of %d]',fname,fext,i,length(files)); fd = fopen(files{i},'r','ieee-le'); dat = cat(1,dat,uint8(fread(fd,inf,'uint8'))); fclose(fd); progress.Value = i/length(files); end end function [h len] = find_headers(dat,progress) %---------------------------------------------------------- % Find all header start indices in raw data %---------------------------------------------------------- h = find(dat(1:end-1)==127 & dat(2:end)==127); % Need at least 3 bytes after header to get length h = h(h < (length(dat)-4)); % Need at least 7 bytes prior to first header for ROSE timestamp if parse_nuc_timestamps h = h(h>7); end if isempty(h) h = []; len = []; return end % Compute ensemble lengths len = double(typecast(reshape(dat(h + [2,3])',[],1),'uint16')); ensemble_size_max = 5000; % byte limit for ensembles % Discard trailing ensembles and ensembles larger than the size limit rm = (h + len > length(dat) - 2) | len > ensemble_size_max; h = h(~rm); len = len(~rm); % Verify checksums progress.Message = 'ADCP: Verifying ensemble checksums...'; chk = typecast(reshape(dat(h + len + [0:1])',[],1),'uint16'); for i = 1:length(chk) kp(i) = chk(i) == mod(sum(dat(h(i) + [0:len(i)-1])),65536); if mod(i,500)==1 progress.Value = i/length(chk); end end progress.Value = 1; progress.Message = 'ADCP: Verifying ensemble checksums... Done!'; % Discard header locations with bad checksums h = h(kp); len = len(kp); % Discard packets whose lengths are rare (<10% of data). This should % take care any "fake" ensembles in the data caused by coincidental % header byte pairs. [u,~,iu] = unique(len); kp = true(size(h)); for i = 1:length(u) if mean(iu==i) < 0.1 kp(iu==i) = false; end end h = h(kp); len = len(kp); end function adcp = parse_ensemble_data(dat) %---------------------------------------------------------- % Convert binary data matrix into a structure %---------------------------------------------------------- % Initialize output structure, read number of data types and offsets from first % header. If we're parsing bytes inserted prior to each header, account for the % number of bytes inserted. adcp = struct(); nuc_offset = 0; if parse_nuc_timestamps nuc_offset = 7; end % Read the number of fields (6th byte) nfields = dat(1,nuc_offset+6); % Compute field data offsets (7th, 9th, ... bytes) offsets = nuc_offset + double(typecast(dat(1,nuc_offset+7+[0:2*nfields-1]),'uint16')); % The loop below parses fields from each data type. for i = 1:nfields % For most fields, we can use the following function to extract data % colums. It looks nasty, but it's just doing the following: % 1) Extract data bytes from all rows (ensembles). The offset plus indices specify colums. % 2) Transpose and reshape so we get a long list of bytes, in order. % 3) Convert byte sequences into values according to their datatype. getdat =@(idx,type) double(typecast(reshape([dat(:,offsets(i)+idx)]',[],1),type))'; switch dec2hex(typecast(dat(1,offsets(i) + [1:2]),'uint16'),4) case '0000' % fixed leader % The fixed leader is in every ensemble, but we only need to % parse 1. In this case, modify the getdat function to only get % data from the first row. getdat =@(idx,type) double(typecast(dat(1,offsets(i)+idx),type)); adcp.config.cpu_fw_ver = getdat(3,'uint8'); adcp.config.cpu_fw_rev = getdat(4,'uint8'); adcp.config.sys_config = dec2bin(getdat(5:6,'uint16'),16); adcp.config.sym_flag = logical(getdat(7,'uint8')); adcp.config.lag_len = getdat(8,'uint8'); adcp.config.n_beams = getdat(9,'uint8'); adcp.config.n_cells = getdat(10,'uint8'); adcp.config.pings_per_ensemble = getdat(11:12,'uint16'); adcp.config.depth_cell_length = getdat(13:14,'uint16')/100; adcp.config.blank_after_transmit = getdat(15:16,'uint16')/100; adcp.config.profiling_mode = getdat(17,'uint8'); adcp.config.low_corr_thresh = getdat(18,'uint8'); adcp.config.n_code_reps = getdat(19,'uint8'); adcp.config.perc_good_min = getdat(20,'uint8'); adcp.config.error_vel_max = getdat(21:22,'uint16')/1000; adcp.config.tpp_minutes = getdat(23,'uint8'); adcp.config.tpp_seconds = getdat(24,'uint8'); adcp.config.tpp_hundredths = getdat(25,'uint8'); adcp.config.coord_transform = dec2bin(getdat(26,'uint8'),8); adcp.config.heading_alignment = getdat(27:28,'int16')/100; adcp.config.heading_bias = getdat(29:30,'int16')/100; adcp.config.sensor_source = dec2bin(getdat(31,'uint8'),8); adcp.config.sensors_available = dec2bin(getdat(32,'uint8'),8); adcp.config.bin_1_distance = getdat(33:34,'uint16')/100; adcp.config.xmit_puse_length = getdat(35:36,'uint16')/100; adcp.config.wp_ref_layer_avg = getdat(37:38,'uint8'); adcp.config.false_target_thresh = getdat(39,'uint8'); adcp.config.transmit_lag_dist = getdat(41:42,'uint16')/100; adcp.config.sys_bandwidth = getdat(51:52,'uint16'); adcp.config.sys_power = getdat(53,'uint8'); adcp.config.serial_number = getdat(55:58,'uint32'); adcp.config.beam_angle = getdat(59,'uint8'); adcp.config.frequency = 75 * 2^bin2dec(adcp.config.sys_config(end-2:end)); adcp.cell_depth = adcp.config.bin_1_distance + ... [0:adcp.config.n_cells-1]'*adcp.config.depth_cell_length; % The ROSE computers insert timestamps outside of the ADCP's % data structure. These don't have an ID or offset, so just grab % them along with the fixed leader. Parse inserted bytes after % reading fixed leader. if parse_nuc_timestamps % This also needs its own getdat in order to specify the data offset manually. getdat =@(idx,type) double(typecast(reshape([dat(:,idx)]',[],1),type))'; nuc_time = reshape(getdat(1:7,'uint8'),[nuc_offset, size(dat,1)])'; nuc_time(:,1) = nuc_time(:,1) + 2000; % add century nuc_time(:,6) = nuc_time(:,6) + nuc_time(:,7)/100; % add hundredths to seconds adcp.nuc_time = datenum(nuc_time(:,1:6))'; end % FIXME: exploring bad timetsamps % nb = adcp.nuc_time < datenum([2020 0 0 0 0 0]); case '0080' % variable leader ens_num = getdat(3:4,'uint16'); % clock_year = getdat(5,'uint8'); % clock_month = getdat(6,'uint8'); % clock_day = getdat(7,'uint8'); % clock_hour = getdat(8,'uint8'); % clock_minute = getdat(9,'uint8'); % clock_second = getdat(10,'uint8'); % clock_hundr = getdat(11,'uint8'); ens_num_msb = getdat(12,'uint8'); adcp.ens_num = ens_num + 65536 * ens_num_msb; % bit_fault = getdat(13,'uint8'); % bit_reset = getdat(14,'uint8'); adcp.speed_of_sound = getdat(15:16,'uint16'); adcp.transducer_depth = getdat(17:18,'uint16')/10; adcp.heading = getdat(19:20,'uint16')/100; adcp.pitch = getdat(21:22,'int16')/100; adcp.roll = getdat(23:24,'int16')/100; adcp.salinity = getdat(25:26,'uint16'); adcp.temperature = getdat(27:28,'int16')/100; % mpt_minutes = getdat(29,'uint8'); % mpt_seconds = getdat(30,'uint8'); % mpt_hundredths = getdat(31,'uint8'); adcp.h_std = getdat(32,'uint8')/10; adcp.p_std = getdat(33,'uint8')/10; adcp.r_std = getdat(34,'uint8')/10; % adc_channels = getdat(35:42,'uint8'); clock_century = getdat(58,'uint8')'; clock_year = getdat(59,'uint8')'; clock_month = getdat(60,'uint8')'; clock_day = getdat(61,'uint8')'; clock_hour = getdat(62,'uint8')'; clock_minute = getdat(63,'uint8')'; clock_second = getdat(64,'uint8')'; clock_hundr = getdat(65,'uint8')'; adcp.time = datenum([100*clock_century+clock_year, clock_month, clock_day, ... clock_hour, clock_minute, clock_second + clock_hundr/100])'; % These data need some additional reshaping since they have beam, % depth, and time dimensions. case '0100' % velocity adcp.vel = permute(reshape(... getdat(2 + [1:(adcp.config.n_cells * 4 * 2)],'int16')/1000,... 4,adcp.config.n_cells,size(dat,1)), [2 1 3]); case '0200' % correlation magnitude adcp.corr = permute(reshape(... getdat(2 + [1:(adcp.config.n_cells * 4)],'uint8'),... 4,adcp.config.n_cells,size(dat,1)), [2 1 3]); case '0300' % echo intensity adcp.echo_intens = permute(reshape(... getdat(2 + [1:(adcp.config.n_cells * 4)],'uint8'),... 4,adcp.config.n_cells,size(dat,1)), [2 1 3]); case '0400' % percent good adcp.perc_good = permute(reshape(... getdat(2 + [1:(adcp.config.n_cells * 4)],'uint8'),... 4,adcp.config.n_cells,size(dat,1)), [2 1 3]); % Vertical beam data (Sentinel V) case '0A00' % vertical beam velocity adcp.vel(:,5,:) = permute(reshape(... getdat(2 + [1:(adcp.config.n_cells * 2)],'int16')/1000,... 1,adcp.config.n_cells,size(dat,1)), [2 1 3]); adcp.config.n_beams = 5; case '0B00' % vertical beam correlation magnitude adcp.corr(:,5,:) = permute(reshape(... getdat(2 + [1:(adcp.config.n_cells)],'uint8'),... 1,adcp.config.n_cells,size(dat,1)), [2 1 3]); case '0C00' % vertical beam echo intensity adcp.echo_intens(:,5,:) = permute(reshape(... getdat(2 + [1:(adcp.config.n_cells)],'uint8'),... 1,adcp.config.n_cells,size(dat,1)), [2 1 3]); case '0D00' % vertical beam percent good adcp.perc_good(:,5,:) = permute(reshape(... getdat(2 + [1:(adcp.config.n_cells)],'uint8'),... 1,adcp.config.n_cells,size(dat,1)), [2 1 3]); % Bottom-track data case '0600' % BT range is a 3-byte integer with the most significant byte % much later in the data packet. bt_range_lsb = getdat(17:24,'uint16'); bt_range_msb = getdat(78:81,'uint8'); adcp.bt_range = (reshape(bt_range_lsb,4,[]) + 2^16*reshape(bt_range_msb,4,[]))/100; adcp.bt_vel = reshape(getdat(25:32,'int16'),4,[])/1000; % mm/s -> m/s adcp.bt_perc_good = reshape(getdat(41:44,'uint8'),4,[]); adcp.bt_amp = reshape(getdat(41:44,'uint8'),4,[]); otherwise % disp(dec2hex(typecast(dat(1,offsets(i) + [1:2]),'uint16'),4)) end end end % of parse_ensemble_data end % of parse_adcp
github
dswinters/ocean-tools-master
parse_nortek_adcp.m
.m
ocean-tools-master/parse_nortek_adcp.m
7,066
utf_8
de4db43d3ea5aa8e29593f0305f1b9b4
function adcp = parse_nortek_adcp(dat_or_file,varargin) %% Parse optional inputs p = inputParser; addOptional(p,'parse_cpu_time',false,@(x) islogical(x)) addParameter(p,'progress',struct(),@(x) isa(x,'matlab.ui.dialog.ProgressDialog')); parse(p,varargin{:}); progress = p.Results.progress; parse_cpu_time = p.Results.parse_cpu_time; cpu_time_bytes = 7*parse_cpu_time; progress = struct(); %% Load binary data if iscell(dat_or_file) % Cell array of filenames dat = load_data(dat_or_file,progress); elseif isstruct(dat_or_file) % File info struct from dir() dat = load_data(fullfile({dat_or_file.folder},{dat_or_file.name}),progress); elseif isstring(dat_or_file) | ischar(dat_or_file) % Single filename dat = load_data({dat_or_file},progress); else % Treat input as raw data dat = dat_or_file; end %% Find headers and validate their checksums sync = 0xA5; family = 0x10; ids = [0x15 0x16 0x17 0x18 0x1A 0x1B 0x1C 0x1D 0x1E 0x1F 0xA0]; names = strrep({'burst' 'average' 'bottom track' 'interleaved burst' 'burst altimeter raw' 'dvl bottom track' 'echo sounder' 'dvl water track' 'altimeter' 'avg altimeter raw' 'string'},' ','_'); idmap = containers.Map(num2cell(ids),names); h = find(dat(1:end-3)==sync & ismember(dat(3:end-1),ids) & dat(4:end)==family); h = h(h<length(dat)-1); hlen = double(dat(h+1)); idx = h+hlen<length(dat); % remove incomplete packets h = h(idx); hlen = hlen(idx); id = dat(h+2); chk = false(length(h),1); chk_rec = typecast(reshape(dat(h + hlen - 1 + [-1 0])',[],1),'uint16'); chk_comp = uint16(zeros(size(chk_rec))); for i = 1:length(h) [chk(i), chk_comp(i)] = validate_checksum(dat(h(i) + [0:hlen(i)-3]),chk_rec(i)); end % Discard invalid headers h = h(chk); hlen = hlen(chk); id = id(chk); uid = unique(id); % for i = 1:length(uid) % disp(sprintf('%s: %d',idmap(uid(i)), sum(id==uid(i)))); % end %% Validate data checksums dchk_rec = typecast(reshape(dat(h + hlen - 1 -[3 2])',[],1),'uint16'); dlen = double(typecast(reshape(dat(h + hlen - 1 -[5 4])',[],1),'uint16')); %% Discard trailing packets idx = h+hlen+dlen < length(dat); h = h(idx); hlen = hlen(idx); id = id(idx); dlen = dlen(idx); dchk_rec = dchk_rec(idx); dchk = false(size(dchk_rec)); dchksum = 0*dchk; for i = 1:length(dchk) [dchk(i), dchksum(i)] = validate_checksum(dat(h(i) + hlen(i)-1 + [1:dlen(i)]),dchk_rec(i)); end %% Discard invalid data checksums h = h(dchk); hlen = hlen(dchk); id = id(dchk); dlen = dlen(dchk); %% Discard leading/trailing headers rm = false(size(h)); if parse_cpu_time rm = h<cpu_time_bytes+1; end rm = rm | (h+hlen+dlen) > length(dat); h = h(~rm); hlen = hlen(~rm); id = id(~rm); dlen = dlen(~rm); %% Trim data if number of BT/burst are different uid = unique(id); % process unique datatypes separately id_n = ones(size(id)); id_nmax = zeros(size(uid)); for i = 1:length(uid) id_n(id==uid(i)) = 1:sum(id==uid(i)); id_nmax(i) = sum(id==uid(i)); end n_min = min(id_nmax(ismember(uid,[0x15 0x17]))); kp = id_n <= n_min; h = h(kp); hlen = hlen(kp); id = id(kp); dlen = dlen(kp); %% Process data adcp = struct(); adcp.config = struct(); for i = 1:length(uid) % Extract data of this type into a big matrix. Each row is a sample, each % column part of some field. idx = find(id==uid(i)); d = @() dat(h(idx) + hlen(idx) + [0:dlen(idx)-1]); % Get cpu timestamps if they exist if parse_cpu_time cpu_time = double(dat(h(idx) + [-cpu_time_bytes:-1])); cpu_time(:,6) = cpu_time(:,6) + 1/100*cpu_time(:,7); cpu_time(:,1) = cpu_time(:,1) + 2000; cpu_time = datenum(cpu_time(:,1:6))'; end % Process data by operating on the columns, depending on the datatype switch uid(i) %% Burst data record case 0x15 burst = nortek_parse_burst(d()); % Config fields adcp.config.n_beams = burst.nbeams; adcp.config.n_cells = burst.ncells; adcp.config.depth_cell_length = burst.cell_size(1); adcp.config.bin_1_distance = burst.blanking(1); adcp.config.serial_number = burst.serial; adcp.config.beam_angle = nan; adcp.config.frequency = nan; % Data fields adcp.time = burst.time; adcp.cell_depth = adcp.config.bin_1_distance + ... [0:adcp.config.n_cells-1]*adcp.config.depth_cell_length; adcp.heading = burst.heading; adcp.pitch = burst.pitch; adcp.roll = burst.roll; adcp.vel = burst.vel; adcp.echo_intens = burst.amp; adcp.corr = burst.cor; adcp.ahrs_rotm = burst.ahrs_rotm; adcp.ahrs_gyro = burst.ahrs_gyro; if parse_cpu_time adcp.nuc_time = cpu_time; end %% Avg data record case 0x16 adcp.nortek_avg = nortek_parse_burst(d()); if parse_cpu_time adcp.nortek_avg.cpu_time = cpu_time; end %% Bottom track data record case 0x17 bt = nortek_parse_bt(d()); if parse_cpu_time bt.nuc_time = cpu_time; end adcp.bt_range = bt.dist; adcp.bt_vel = bt.vel; adcp.bt_time = bt.time; case 0x1C adcp.ecs = nortek_parse_burst(d()); if parse_cpu_time adcp.ecs.nuc_time = cpu_time; end end end if isfield(adcp,'vel') && isfield(adcp,'bt_vel') adcp.vel = adcp.vel - permute(adcp.bt_vel,[3 1 2]); adcp.processing.bt_removed_from_vel = true; end adcp.config.beam2inst = [1.1831 0 -1.1831 0 0 -1.1831 0 1.1831 0.5518 0 0.5518 0 0 0.5518 0 0.5518]; end %% Helper functions below function [chk, chk_comp] = validate_checksum(d,chk_rec) len = length(d); chk = double(0xB58C); % checksum is initialized to this % sum of all 16-byte segments (remove trailing 8 bytes if odd length) chk = chk + sum(double(typecast(d(1:len-mod(len,2)),'uint16'))); % add the last byte if odd length: if mod(len,2) chk = chk + bitshift(double(d(end)),8); end chk_comp = uint16(mod(chk,2^16)); chk = chk_comp == chk_rec; % final checksum end function dat = load_data(files,progress) %---------------------------------------------------------- % Read and concatenate data in the given list of files %---------------------------------------------------------- dat = []; for i = 1:length(files) if ~exist(files{i},'file') error('File not found: %s',files{i}) end [~,fname,fext] = fileparts(files{i}); progress.Message = sprintf('ADCP: Opening %s %s [%d of %d]',fname,fext,i,length(files)); fd = fopen(files{i},'r','ieee-le'); dat = cat(1,dat,uint8(fread(fd,inf,'uint8'))); fclose(fd); progress.Value = i/length(files); end end
github
dswinters/ocean-tools-master
prep_nbeam_solutions.m
.m
ocean-tools-master/prep_nbeam_solutions.m
7,147
utf_8
186f39b257f30f102581a5fd81a9994b
%% prep_nbeam_solutions.m % Usage: adcp = prep_nbeam_solutions(adcp) % % Description: % Fill in NaN-masked beam velocity data with data from other beams. Uses the % Sentinel V's 5th beam to solve for missing beam data with the assumption that % towards-transducer velocity as estimated by each beam pair and as measured by % the 5th beam should be equal. % % Inputs: adcp - adcp structure returned by parse_adcp() % Outputs: adcp - an equivalent structure with modified beam velocities. % % Author: Dylan Winters % Created: 2022-02-21 function adcp = prep_nbeam_solutions(adcp) % Get velocity dimensions nb = size(adcp.vel,2); % number of beams nc = size(adcp.vel,1); % number of depth cells nt = size(adcp.vel,3); % number of samples % Reshape velocity matrix to columns of beam data vb = reshape(permute(adcp.vel,[3 1 2]),nc*nt,nb); % Create a logical mask for NaN-valued beam data, i.e. % 1 0 0 0 0 <-- beam 1 is bad % 0 0 1 0 0 <-- beam 3 is bad % 0 0 0 1 1 <-- beams 4 & 5 are bad, etc. bmask = isnan(vb); % Find all combinations of bad beams. These are just the unique rows of the % above matrix. [bad_beams, ~, type] = unique(bmask,'rows'); % Also define a function to convert arbitrary combinations of bad beams to % unique integers by treating these rows as binary numbers: id =@(bad_beams) sum(2.^find(bad_beams)); % Loop over all types of bad beam combinations and fill in masked velocity data % where possible. for i = 1:size(bad_beams,1) % Get the indices of velocity entries with this type of beam failure idx = type == i; c = 1/(2*sind(adcp.config.beam_angle)); % ====== 3-beam solutions for 4-beam ADCP ====== % if nb==4; switch id(find(bad_beams(i,:))) % ====== 1 side beam bad ====== % % The best we can do with a 4-beam ADCP is set error velocity equal to % zero, i.e. impose that the estimate of Z velocity from both beam % pairs is equal, then solve for the missing beam. Beam 1 example: % % Z1 = c*v1 + c*v2 (1) Z estimate from 1st beam pair % Z2 = c*v3 + c*v4 (2) Z estimate from 2nd beam pair % % Then impose Z1 = Z2 and solve for v1: % % c*v1 + c*v2 = c*v3 + c*v4 % ===> v1 = v3 + v4 - v2 % % Similar for other beams. case id(1) % only beam 1 bad % c*v1 + c*v2 = c*v3 + c*v4 % ===> v1 = v3 + v4 - v2 vb(idx,1) = vb(idx,3) + vb(idx,4) - vb(idx,2); case id(2) % only beam 2 bad % c*v1 + c*v2 = c*v3 + c*v4 % ===> v2 = v3 + v4 - v1 vb(idx,2) = vb(idx,3) + vb(idx,4) - vb(idx,1); case id(3) % only beam 3 bad % c*v1 + c*v2 = c*v3 + c*v4 % ===> v3 = v1 + v2 - v4 vb(idx,3) = vb(idx,1) + vb(idx,2) - vb(idx,4); case id(4) % only beam 3 bad % c*v1 + c*v2 = c*v3 + c*v4 % ===> v4 = v1 + v2 - v3 vb(idx,4) = vb(idx,1) + vb(idx,2) - vb(idx,3); end end % ====== 3- and 4-beam solutions for 5-beam ADCP ====== % if nb==5 switch id(find(bad_beams(i,:))) % ====== 1 side beam bad ====== % % Each opposite-side pair of side beams gives an estimate of Z velocity. With % a single bad side beam, we can impose that its pair's estimate of Z velocity % is equal to beam 5's measurement, and reconstruct the bad beam's velocity. % % For example, if beam 1 is bad (c is a scale factor depending on beam angle): % % Z1 = c*v1 + c*v2 (1) Z velocity estimate from combining beams 1 & 2 % Z2 = v5 (2) Z velocity estimate directly from beam 5 % % By imposing that Z1 = Z2, we can combine (1) and (2) to solve for v1: % % v5 = c*v1 + c*v2 % ==> v1 = (v5 - c*v2)/c % % Then for all entries where only beam 1 is NaN, we set beam 1 velocity to % (v5 - c*v2)/c % % The process is similar for any single bad side beam. case id(1) % only beam 1 bad, as in example above % v5 = c*v1 + c*v2 % ==> v1 = (v5 - c*v2)/c vb(idx,1) = (vb(idx,5) - c*vb(idx,2))/c; case id(2) % only beam 2 bad % v5 = c*v1 + c*v2 % ==> v2 = (v5 - c*v1)/c vb(idx,2) = (vb(idx,5) - c*vb(idx,1))/c; case id(3) % only beam 3 bad % v5 = c*v3 + c*v4 % ==> v3 = (v5 - c*v4)/c vb(idx,3) = (vb(idx,5) - c*vb(idx,4))/c; case id(4) % only beam 4 bad % v5 = c*v3 + c*v4 % ==> v4 = (v5 - c*v3)/c vb(idx,4) = (vb(idx,5) - c*vb(idx,3))/c; % ====== Bad side beam and bad 5th beam ====== % % We can use the typical 3-beam solutions for a 4-beam ADCP case id([1,5]) % only beam 1 bad % c*v1 + c*v2 = c*v3 + c*v4 % ===> v1 = v3 + v4 - v2 vb(idx,1) = vb(idx,3) + vb(idx,4) - vb(idx,2); case id([2,5]) % only beam 2 bad % c*v1 + c*v2 = c*v3 + c*v4 % ===> v2 = v3 + v4 - v1 vb(idx,2) = vb(idx,3) + vb(idx,4) - vb(idx,1); case id([3,5]) % only beam 3 bad % c*v1 + c*v2 = c*v3 + c*v4 % ===> v3 = v1 + v2 - v4 vb(idx,3) = vb(idx,1) + vb(idx,2) - vb(idx,4); case id([4,5]) % only beam 3 bad % c*v1 + c*v2 = c*v3 + c*v4 % ===> v4 = v1 + v2 - v3 vb(idx,4) = vb(idx,1) + vb(idx,2) - vb(idx,3); % ====== 2 side beams bad ====== % % Because we can handle a single bad beam from the 1&2 beam pair and the % 3&4 beam pair independently, we can also handle cases where a single % beam is bad for both pairs: case id([1,3]) % beams 1 & 3 bad % v5 = c*v1 + c*v2 % ==> v1 = (v5 - c*v2)/c vb(idx,1) = (vb(idx,5) - c*vb(idx,2))/c; % v5 = c*v3 + c*v4 % ==> v3 = (v5 - c*v4)/c vb(idx,3) = (vb(idx,5) - c*vb(idx,4))/c; case id([1,4]) % beams 1 & 4 bad % v5 = c*v1 + c*v2 % ==> v1 = (v5 - c*v2)/c vb(idx,1) = (vb(idx,5) - c*vb(idx,2))/c; % v5 = c*v3 + c*v4 % ==> v4 = (v5 - c*v3)/c vb(idx,4) = (vb(idx,5) - c*vb(idx,3))/c; case id([2,3]) % beams 2 & 3 bad % v5 = c*v1 + c*v2 % ==> v2 = (v5 - c*v1)/c vb(idx,2) = (vb(idx,5) - c*vb(idx,1))/c; % v5 = c*v3 + c*v4 % ==> v3 = (v5 - c*v4)/c vb(idx,3) = (vb(idx,5) - c*vb(idx,4))/c; case id([2,4]) % beams 2 & 4 bad % v5 = c*v1 + c*v2 % ==> v2 = (v5 - c*v1)/c vb(idx,2) = (vb(idx,5) - c*vb(idx,1))/c; % v5 = c*v3 + c*v4 % ==> v4 = (v5 - c*v3)/c vb(idx,4) = (vb(idx,5) - c*vb(idx,3))/c; % ====== Other cases ====== % % Solutions for other combinations of beam failures can be added here. % For example, if beam 5 is bad, one could take a weighted average of Z % estimated by both other beam pairs. There are many possibilities and I % can't know which are most appropriate for all cases. end end end % Reshape beam velocity to original size and store in adcp struct adcp.vel = permute(reshape(vb',nb,nt,nc), [3 1 2]);
github
dswinters/ocean-tools-master
parse_imu.m
.m
ocean-tools-master/parse_imu.m
21,036
utf_8
beb6d505c404508dccfd47bc6a791920
%% parse_imu.m % % Usage % imu = parse_imu(dat_or_file) % imu = parse_imu(dat_or_file, parse_nuc_timestamps) % imu = parse_imu(... , 'progress', uiprogressdlg) % % Inputs % - dat_or_file % This can be a filename, cell array of filenames, the output of MATLAB's % "dir" command, or an array of binary data. % % Optional Arguments % - parse_nuc_timestamps (logical) % | Flag to parse Nuc timestamps inserted into the IMU_timestamped* files from % | ROSE deployments. % % Name-value pair arguments % - 'progress' % Specify a UI progress dialog handle to update it with progress information while % parsing data. % % Outputs % - imu % Data structure containing IMU fields. The field and subfield structure matches % the fields described in the LORD IMU manuals. % % Author % - Dylan Winters ([email protected]) function imu = parse_imu(dat_or_file,varargin) %% Parse optional inputs p = inputParser; addOptional(p,'parse_nuc_timestamps',false,@(x) islogical(x)) addParameter(p,'progress',struct(),@(x) isa(x,'matlab.ui.dialog.ProgressDialog')); parse(p,varargin{:}); progress = p.Results.progress; parse_nuc_timestamps = p.Results.parse_nuc_timestamps; %% Main parsing routine % 1) Load binary data if iscell(dat_or_file) % Cell array of filenames dat = load_data(dat_or_file); elseif isstruct(dat_or_file) % File info struct from dir() dat = load_data(fullfile({dat_or_file.folder},{dat_or_file.name})); elseif isstr(dat_or_file) % Single filename dat = load_data({dat_or_file}); else % Treat input as raw data dat = dat_or_file; end % 2) Locate & validate data packets header = find_headers(dat,progress); % 3) Convert binary data to struct progress.Message = 'IMU: Processing data'; progress.Indeterminate = 'on'; imu = parse_data(header, dat); progress.Indeterminate = 'off'; %%% Sub-functions %---------------------------------------------------------- % Locate headers in the 3DM-GX5-25 binary output %---------------------------------------------------------- function header = find_headers(dat,progress) % Find sequences of SYNC1 and SYNC2 bytes (0x75,0x65). % These are the first two bytes of all headers. h = find(dat(1:end-1) == hex2dec('75') & ... dat(2:end) == hex2dec('65')); % Throw out trailing headers with no payload h = h(length(dat) - h > 2); % Look for timestamps inserted by ROSE computer if parse_nuc_timestamps % Discard first header if preceeding timestamp is incomplete if ~isempty(h) if h(1) < 8 h = h(2:end); end ts = double(dat(h - [7:-1:1])); ts(:,1) = ts(:,1) + 2000; % add century ts(:,6) = ts(:,6) + ts(:,7)/100; % add ms to s ts = datenum(ts(:,1:6)); else ts = []; end end % The third byte is the 'descriptor set', which signifies the payload type. d = double(dat(h + 2)); % The fourth byte is the payload length. l = double(dat(h + 3)); % Verify checksums of each packet payload kp = true(size(h)); progress.Message = 'IMU: Validating checksums...'; for n = 1:length(h); % Stop if we reach EoF before packet end if h(n) + l(n)-1 + 6 <= length(dat) % Extract packet payload pp = dat(h(n) + [0:l(n)+3]); % Extract packet checksum chk1 = double(dat((h(n) + l(n)+3) + [1:2])); chk1 = bitshift(chk1(1),8) + chk1(2); % Compute packet checksum (16-bit Fletcher checksum) sum1 = 0; sum2 = 0; for i = 1:length(pp) sum1 = mod(sum1 + double(pp(i)),2^8); sum2 = mod(sum2 + sum1,2^8); end chk2 = bitshift(sum1,8) + sum2; % Discard packet if checksums don't match if chk2 ~= chk1 kp(n) = false; end else % EoF reached before packet end; discard kp(n) = false; end if mod(n,500) == 1; progress.Value = n/length(h); end end progress.Value = 1; progress.Message = 'IMU: Validating checksums... Done!'; % Eliminate headers with invalid checksums header.index = h(kp); header.descriptor = d(kp); header.length = l(kp); if parse_nuc_timestamps header.ts = ts(kp); end end %---------------------------------------------------------- % Read and concatenate data in the given list of files %---------------------------------------------------------- function dat = load_data(files,progress) dat = []; for i = 1:length(files) if ~exist(files{i},'file') error('File not found: %s',files{i}) end [~,fname,fext] = fileparts(files{i}); progress.Message = sprintf('IMU: Opening %s%s [%d of %d]',fname,fext,i,length(files)); progress.Value = i/length(files); fd = fopen(files{i},'r','ieee-le'); dat = cat(1,dat,uint8(fread(fd,inf,'uint8'))); fclose(fd); end end %---------------------------------------------------------- % Convert raw binary data to a MATLAB struct %---------------------------------------------------------- function output = parse_data(header, dat) if length(header) == 0 output = []; return end output = struct(); % initialize output structure output.units = struct(); % initialize units structure [d, f, id] = unique(header.descriptor); len = header.length(f); dat_preproc = cell(length(d),1); for i = 1:length(d) dat_preproc{i} = dat(header.index(id==i)+2 + [0:len(i)+1]); end for i = 1:length(d) % for each type of payload encountered while finding headers... nb_proc = 2; while nb_proc < size(dat_preproc{i},2) % extract fields 1-by-1 flen = unique(dat_preproc{i}(:,nb_proc+1)); % get field length fdesc = unique(dat_preproc{i}(:,nb_proc+2)); % and descriptor [dname fname subfields] = imu_field_defs(d(i),fdesc); % get subfield info % initialize output fields/subfields if ~isfield(output,dname) output.(dname) = struct(); % store ROSE timestamps if parse_nuc_timestamps output.(dname).nuc_time = header.ts(id==i); end end if ~isfield(output.(dname),fname) output.(dname).(fname) = struct(); end for sf = 1:length(subfields) % store unit information output.units.(dname).(fname).(subfields(sf).name) = subfields(sf).units; % compute subfield length if sf==length(subfields) sf_len = flen-2 - subfields(end).offset; else sf_len = subfields(sf+1).offset - subfields(sf).offset; end % compute subfield index in pre-processed data sf_idx = nb_proc + 3 + subfields(sf).offset + [0:sf_len-1]; % convert 8-bit integers to final datatype with MATLAB's typecast function % this requires some reshaping, etc. to be fast output.(dname).(fname).(subfields(sf).name) = ... double(typecast(reshape(fliplr(dat_preproc{i}(:,sf_idx))',1,[]),subfields(sf).type)); end nb_proc = nb_proc + double(flen); end end end % of parse_data() %---------------------------------------------------------- % Define subfield names, byte offsets, subfield lengths, and % datatypes based on the payload descriptor. %---------------------------------------------------------- function [dname fname subfields] = imu_field_defs(descriptor,fdesc) dname = ''; fname = ''; subfields = struct(); switch dec2hex(descriptor,2) % Descriptor set byte case '80' % IMU Data dname = 'IMU'; switch dec2hex(fdesc,2) case '04' fname = 'scaled_accelerometer_vector'; subfields = struct(... 'name', {'x_accel','y_accel','z_accel'},... 'offset', {0,4,8},... 'type', {'single','single','single'},... 'units', {'g','g','g'}); case '05' fname = 'scaled_gyro_vector'; subfields = struct(... 'name', {'x_gyro','y_gyro','z_gyro'},... 'offset', {0,4,8},... 'type',{'single','single','single'},... 'units',{'rad/s','rad/s','rad/s'}); case '06' fname = 'scaled_magnetometer_vector'; subfields = struct(... 'name', {'x_mag','y_mag','z_mag'},... 'offset', {0,4,8},... 'type',{'single', 'single', 'single'},... 'units', {'gauss','gauss','gauss'}); case '17' fname = 'scaled_ambient_pressure'; case '07' fname = 'delta_theta_vector'; case '08' fname = 'delta_velocity_vector'; case '09' fname = 'cf_orientation_matrix'; case '0A' fname = 'cf_quaternion'; case '0C' fname = 'cf_euler_angles'; subfields = struct(... 'name', {'roll','pitch','yaw'},... 'offset', {0,4,8},... 'type', {'single','single','single'},... 'units', {'radians','radians','radians'}); case '10' fname = 'cf_stabilized_north_vector'; case '11' fname = 'cf_stabilized_up_vector'; case '12' fname = 'gps_correlation_timestamp'; subfields = struct(... 'name', {'gps_time_of_week','gps_week_number','timestamp_flags'},... 'offset', {0,8,10},... 'type', {'double','uint16','uint16'},... 'units', {'seconds','n/a','see manual'}); end case '81' % GNSS Data dname = 'GNSS'; switch dec2hex(fdesc,2) case '03' fname = 'llh_position'; subfields = struct(... 'name', {'latitude' ,... 'longitude',... 'height_above_ellipsoid',... 'height_above_msl',... 'horizontal_accuracy',... 'vertical_accuracy',... 'valid_flags'} ,... 'offset',{0,8,16,24,32,36,40},... 'type', {'double',... 'double',... 'double',... 'double',... 'single',... 'single',... 'uint16'},... 'units', {'decimal degrees',... 'decimal degrees',... 'meters',... 'meters',... 'meters',... 'meters',... 'see manual'}); case '04' fname = 'position_eath_centered_earth_fixed_frame'; subfields = struct(... 'name', {'x_pos','y_pos','z_pos','pos_accuracy','valid_flags'},... 'offset', {0,8,16,24,28},... 'type', {'double','double','double','single','uint16'},... 'units',{'meters','meters','meters','meters','see manual'}); case '05' fname = 'velocity_north_east_down_frame'; subfields = struct(... 'name', {'north',... 'east',... 'down',... 'speed',... 'ground_speed',... 'heading',... 'speed_accuracy',... 'heading_accuracy',... 'valid_flags'},... 'offset', {0,4,8,12,16,20,24,28,32},... 'type', {'single',... 'single',... 'single',... 'single',... 'single',... 'single',... 'single',... 'single',... 'uint16'},... 'units', {'m/sec',... 'm/sec',... 'm/sec',... 'm/sec',... 'm/sec',... 'decimal degrees',... 'm/sec',... 'decimal degrees',... 'see manual'}); case '06' fname = 'velocity_eath_centered_earth_fixed_frame'; subfields = struct(... 'name', {'x_vel','y_vel','z_vel','vel_accuracy','valid_flags'},... 'offset', {0,4,8,12,16},... 'type', {'single','single','single','single','uint16'},... 'units',{'m/sec','m/sec','m/sec','m/sec','see manual'}); case '07' fname = 'DOP_data'; case '08' fname = 'UTC_time'; subfields = struct(... 'name',{'year','month','day','hour','minute','second',... 'millisecond','valid_flags'},... 'offset',{0,2,3,4,5,6,7,11},... 'type',{'uint16','uint8','uint8','uint8','uint8',... 'uint8','uint32','uint16'},... 'units',{'years','months','days','hours','minutes',... 'seconds','milliseconds','see manual'}); case '09' fname = 'GPS_time'; subfields = struct(... 'name',{'time_of_week','week_number','valid_flags'},... 'offset',{0,8,10},... 'type',{'double','uint16','uint16'},... 'units',{'seconds','n/a','see manual'}); case '0A' fname = 'clock_information'; case '0B' fname = 'gnss_fix_information'; case '0C' fname = 'space_vehicle_information'; case '0D' fname = 'hardware_status'; case '0E' fname = 'dgnss_information'; case '0F' fname = 'dgnss_channel_status'; end case '82' % Estimation Filter (Attitude) Data dname = 'attitude'; switch dec2hex(fdesc,2) case '10' fname = 'filter_status'; case '11' fname = 'gps_timestamp'; subfields = struct(... 'name', {'time_of_week' ,... 'week_number' ,... 'valid'} ,... 'offset',{0,8,10} ,... 'type', {'double' ,... 'uint16' ,... 'uint16'} ,... 'units', {'seconds' ,... 'n/a' ,... '1=valid, 0=invalid'}); case '03' fname = 'orientation_quaternion'; case '12' fname = 'attitude_uncertainty_quaternion_elements'; case '05' fname = 'orientation_euler_angles'; subfields = struct(... 'name', {'roll' ,... 'pitch' ,... 'yaw' ,... 'valid'} ,... 'offset',{0,4,8,12} ,... 'type', {'single' ,... 'single' ,... 'single' ,... 'uint16'} ,... 'units', {'radians' ,... 'radians' ,... 'radians' ,... '1=valid, 0=invalid'}); case '0A' fname = 'attitude_uncertainty_euler_angles'; case '04' fname = 'orientation_matrix'; case '0E' fname = 'compensated_angular_rate'; subfields = struct(... 'name', {'X' ,... 'Y' ,... 'Z' ,... 'valid'} ,... 'offset',{0,4,8,12} ,... 'type', {'single' ,... 'single' ,... 'single' ,... 'uint16'} ,... 'units', {'rads/sec' ,... 'rads/sec' ,... 'rads/sec' ,... '1=valid, 0=invalid'}); case '06' fname = 'gyro_bias'; case '0B' fname = 'gyro_bias_uncertainty'; case '1C' fname = 'compensated_acceleration'; case '0D' fname = 'linear_acceleration'; subfields = struct(... 'name', {'X' ,... 'Y' ,... 'Z' ,... 'valid'} ,... 'offset',{0,4,8,12} ,... 'type', {'single' ,... 'single' ,... 'single' ,... 'uint16'} ,... 'units', {'m/sec^2' ,... 'm/sec^2' ,... 'm/sec^2' ,... '1=valid, 0=invalid'}); case '21' fname = 'pressure_altitude'; case '13' fname = 'gravity_vector'; case '0F' fname = 'wgs84_local_gravity_magnitude'; case '14' fname = 'heading_update_source_state'; subfields = struct(... 'name', {'heading' ,... 'heading_1_sigma_uncertainty' ,... 'source' ,... 'valid'} ,... 'offset',{0,4,8,10} ,... 'type', {'single' ,... 'single' ,... 'uint16' ,... 'uint16'} ,... 'units', {'radians' ,... 'radians' ,... '0=no source, 1=Magnetometer, 4=External',... '1=valid, 0=invalid'}); case '15' fname = 'magnetic_model_solution'; case '25' fname = 'mag_auto_hard_iron_offset'; case '28' fname = 'mag_auto_hard_iron_offset_uncertainty'; case '26' fname = 'mag_auto_soft_iron_matrix'; case '29' fname = 'mag_auto_soft_iron_matrix_uncertainty'; end end end % of imu_field_defs end % of parse_imu()
github
dswinters/ocean-tools-master
parse_gps.m
.m
ocean-tools-master/parse_gps.m
9,096
utf_8
e30546642c7a5557b3113647b61ad60f
%% parse_gps.m % % Usage % gps = parse_gps(files) % gps = parse_gps(... , 'progress', uiprogressdlg) % % Inputs % - f_in % This can be a filename, cell array of filenames, the output of MATLAB's % "dir" command. % % Name-value pair arguments % - 'progress' % Specify a UI progress dialog handle to update it with progress information while % parsing data. % % Outputs % - gps % Data structure containing GPS fields. Each type of NMEA message gets its own % sub-structure. % % Author % - Dylan Winters ([email protected]) function GPS = parse_gps(f_in,varargin) % Make a cell array of filenames from input if isstruct(f_in) f_in = fullfile({f_in.folder},{f_in.name}); elseif isstr(f_in) f_in = {f_in}; end %% Parse optional inputs p = inputParser; addParameter(p,'progress',struct(),@(x) isa(x,'matlab.ui.dialog.ProgressDialog')); parse(p,varargin{:}); progress = p.Results.progress; % The bulk of the text parsing is done using MATLAB's regexp function. % First, create some regexps for types of data we might see in the text. % The portions enclosed in parentheses will be extracted, while the rest % is just used for matching. The regexp ',?' means that there might be a comma. dec = ',?(-?\d+\.\d+),?'; % positive or negative float w/ decimal places, maybe comma-enclosed int =@(n) sprintf(',?(-?\\d{%d}),?',n); % n-digit positive or negative integer, maybe comma-enclosed intu = ',?(\d+),?'; % integer of unknown length, maybe comma-enclosed ltr = ',?[a-zA-Z],?'; % any letter, maybe comma-enclosed EW = ',?([ewEW]),?'; % 'E' or 'W', maybe comma-enclosed % Combine the above regexps for single chunks of data into regexps % for different types of complete NMEA strings: fmt = struct(); fmt.HEHDT = ['\$HEHDT,' dec]; fmt.HEROT = ['\$HEROT,' dec]; fmt.GPGGA = ['\$GPGGA,' ... int(2) int(2) dec ... % time int(2) dec ltr ... % lat int(3) dec EW ... % lon intu intu ... % qual, #sats dec dec ... % hdop, alt ltr dec]; % alt units, undulation fmt.GPHDT = ['\$GPHDT,' dec]; fmt.GPHEV = ['\$GPHEV,' dec]; fmt.GPRMC = ['\$GPRMC,' ... int(2) int(2) dec ltr ... int(2) dec ltr ... int(3) dec EW ... dec dec ... int(2) int(2) int(2)]; fmt.GPZDA = ['\$GPZDA,' ... int(2) int(2) dec ... int(2) int(2) int(4)]; fmt.PASHR = ['\$PASHR,' ... int(2) int(2) dec ... dec ltr dec dec ... dec dec dec]; fmt.PADCP = ['\$PADCP,' intu ... int(4) int(2) int(2) ... int(2) int(2) dec dec]; fmt.GPVTG = ['\$GPVTG,' dec, ltr, dec, ltr, dec, ltr, dec, ltr]; %% NMEA prefix-specific substitution filters % Replace 'E' and 'W' in GPRMC/GPGGA matrices with '1' and '-1' ewflt = struct('str',{'E','W','e','w'},'sub',{'1','-1','1','-1'}); filts = struct(... 'GPRMC', ewflt,... 'GPGGA', ewflt); %% Function handles for extracting fields % % Each file is consecutively parsed for data from each NMEA type. All % lines of a single NMEA type are extracted at once, into a matrix D % with a row for each line and a column for each raw field. The % function handles below provide instructions for converting this % matrix into meaningful data. % % Defining this structure in this way allows for easy looping through NMEA % prefixes and fields within each prefix. % flds = struct(... 'PASHR',struct(... 'dn', @(D) datenum([zeros(size(D,1),3) D(:,1:3)]) ,... 'head', @(D) D(:,4) ,... 'pitch', @(D) D(:,5) ,... 'roll', @(D) D(:,6) ,... 'yaw', @(D) D(:,7)) ,... 'GPGGA',struct(... 'dn', @(D) datenum([zeros(size(D,1),3) D(:,1:3)]) ,... 'lat', @(D) D(:,4) + D(:,5)/60 ,... 'lon', @(D) D(:,8).*(D(:,6) + D(:,7)/60) ,... 'alt', @(D) D(:,12) ,... 'geoid', @(D) D(:,13)) ,... 'HEHDT',struct(... 'head', @(D) D(:,1)) ,... 'GPHDT',struct(... 'head', @(D) D(:,1)) ,... 'GPHEV',struct(... 'heave', @(D) D(:,1)) ,... 'HEROT',struct(... 'rot', @(D) D(:,1)) ,... 'GPRMC',struct(... 'dn', @(D) datenum(D(:,[13 12 11 1 2 3])) + ... datenum([2000 0 0 0 0 0]) ,... 'lat', @(D) D(:,4) + D(:,5)/60 ,... 'lon', @(D) D(:,8).*(D(:,6) + D(:,7)/60) ,... 'speed', @(D) D(:,9) * 0.514444 ,... 'course',@(D) D(:,10)) ,... 'GPZDA',struct(... 'dn', @(D) datenum(D(:,[6 5 4 1 2 3]))) ,... 'PADCP',struct(... 'num', @(D) D(:,1) ,... 'dn', @(D) datenum(D(:,[2:7])) - D(:,8)/86400) ,... 'GPVTG',struct(... 'course', @(D) D(:,1) ,... 'speed', @(D) D(:,3) * 0.514444)); nmea_types = fields(flds); % % Check the opts struct for manually defined message formats % if nargin > 1 % if isfield(opts,'fmt') % msgs = fields(opts.fmt); % for i = 1:length(msgs) % fmt.(msgs{i}) = opts.fmt.(msgs{i}); % end % end % if isfield(opts,'flds') % msgs = fields(opts.flds); % for i = 1:length(msgs) % flds.(msgs{i}) = opts.flds.(msgs{i}); % end % end % end %% Initialize output structure GPS = struct(); for i = 1:length(nmea_types) prefix = nmea_types{i}; GPS.(prefix) = struct(); GPS.(prefix).lnum = []; GPS.(prefix).fnum = []; vars = fields(flds.(prefix)); for v = 1:length(vars) GPS.(prefix).(vars{v}) = []; end end %% Parse! for fi = 1:length(f_in) [~,fname,~] = fileparts(f_in{fi}); progress.Message = sprintf('GPS: Processing %s [%d of %d]',fname,fi,length(f_in)); ftxt = fileread(f_in{fi}); % read entire file text for i = 1:length(nmea_types) prefix = nmea_types{i}; % [lines, start] = regexp(ftxt,fmt.(prefix),'tokens','start'); lines = cat(1,lines{:}); if ~isempty(lines) % Apply substitution filters if isfield(filts,prefix) for iflt = 1:length(filts.(prefix)) lines(strcmp(lines,filts.(prefix)(iflt).str)) = ... {filts.(prefix)(iflt).sub}; end end D = reshape(sscanf(sprintf('%s*',lines{:}),'%f*'),size(lines)); % vars = fields(flds.(prefix)); % Grab line numbers by counting occurences of newline characters before % the start of each line: lnum = nan(size(D,1),1); lnum(1) = 1 + length(regexp(ftxt(1:start(1)),'\n')); for l = 2:length(lnum) lnum(l) = lnum(l-1) + ... length(regexp(ftxt(start(l-1):start(l)),'\n')); end GPS.(prefix).lnum = cat(1,GPS.(prefix).lnum,lnum); GPS.(prefix).fnum = cat(1,GPS.(prefix).fnum,fi*ones(size(D,1),1)); % Populate struct with variables for v = 1:length(vars) GPS.(prefix).(vars{v}) = cat(1,GPS.(prefix).(vars{v}),... flds.(prefix).(vars{v})(D)); end end end progress.Value = fi/length(f_in); end GPS.files = cell(length(f_in),1); for i = 1:length(f_in) [~,fname,fext] = fileparts(f_in{i}); GPS.files{i} = [fname fext]; end % Remove empty fields for i = 1:length(nmea_types) fld_flds = fields(GPS.(nmea_types{i})); has_data = false; for j = 1:length(fld_flds) has_data = has_data | ~isempty(GPS.(nmea_types{i}).(fld_flds{j})); end if ~has_data GPS = rmfield(GPS,nmea_types{i}); end end % Return empty array if no data if isempty(setdiff(fields(GPS),{'files'})) GPS = []; end end
github
dswinters/ocean-tools-master
gps_ltln2vel.m
.m
ocean-tools-master/gps_ltln2vel.m
1,422
utf_8
73c9a76ae21cd1dbc32b55367a3a3a3c
%% nav_ltln2vel.m % Usage: nav_ltln2vel(lt,ln,dn) % Description: Convert the lat and lon measurements in LT and % LN to an xy grid centered at the mean location. % Create a timeseries of x&y velocity based on the % timestamps in DN. % Inputs: lt - latitude (degrees north) % ln - longitude (degrees east) % dn - matlab datenum % Outputs: vx,vy - velocities, east & north % % Author: Dylan Winters % Created: 2016-09-16 function [vx, vy] = gps_ltln2vel(lt,ln,dn) % remove non-unique timestamps dn0 = dn; [~,idx] = unique(dn); dn = dn(idx); lt = lt(idx); ln = ln(idx); % remove NaNs idx = ~isnan(dn.*lt.*ln); dn = dn(idx); lt = lt(idx); ln = ln(idx); % convert to xy (need at least 2 non-nan points) if sum(idx)>2 wgs84 = referenceEllipsoid('wgs84','m'); lt0 = nanmean(lt); ln0 = nanmean(ln); lt2y = distance('rh',lt0-0.5,ln0,lt0+0.5,ln0,wgs84); ln2x = distance('rh',lt0,ln0-0.5,lt0,ln0+0.5,wgs84); % lt2y = abs(40000000/360) ; % meters N/S per degree N % ln2x = scl*cosd(lt0) ; % meters E/W per degree W at latitude lt0 y = lt2y * (lt-lt0) ; % meters N/S x = ln2x * (ln-ln0) ; % meters E/W dt = diff(dn)*86400; t = dn(1:end-1) + diff(dn)/2; vx = interp1(t, diff(x)./dt, dn0,'linear','extrap'); vy = interp1(t, diff(y)./dt, dn0,'linear','extrap'); else vx = nan*dn0; vy = nan*dn0; end
github
ku-ya/OccGridMap_Matlab-master
EISM.m
.m
OccGridMap_Matlab-master/2D_matlab/EISM.m
1,516
utf_8
e6809e72d3f66308b6a75a0e63021ad2
% 1 beam case for exact inverse sensor model occGrid % parameters function ogmap = EISM(ogmap,range,free,X_t,param) % L = 1; % world size % dx = param.resol; % grid size % sigma = param.sigma; % sensor % create measurements and pose %% % nz = length(free); % idx = zeros(1,nz); idz = idx; % for j = 1:nz % get reduced map % [~, idx(j)] = min(abs(m_cm - X_t(j))); % [~, idz(j)] = min(abs(m_cm - X_t(j) - Z_t(j))); if size(free,1)<20 return; end Prtl = zeros(length(free),1); for k = 1:length(free) Prtl(k) = ogmap(k); end nr = length(Prtl); % Initialize Prtl(1) = 0; Prtl(nr+1) = 1; % get distance to each gird in rtl distance = sqrt((free(:,1)-X_t(1)).^2+(free(:,2)-X_t(2)).^2); pz_xr = sensorFM(nr,param.resol,range,param); % forward sensor model PDF % clf % plot((1:nr+1)/dx,pz_xr) a = zeros(1,nr); b = a; c = a; d = a; Pr_zxz = a; Pnr_zxz = a; for k = 1:nr if k == 1 a(1) = 0; b(1) = 1;c(1)=pz_xr(1); else a(k) = a(k-1) + b(k-1)*pz_xr(k-1)*Prtl(k-1); b(k) = b(k-1)*(1-Prtl(k-1)); c(k) = b(k)*pz_xr(k); end end d(nr) = 0; for p = 1:nr-1 k = nr - p; d(k) = d(k+1) + b(k)*pz_xr(k + 1)*Prtl(k + 1); end for k = 1:nr Pr_zxz(k) = a(k) + c(k); Pnr_zxz(k) = a(k) + d(k); end for k = 1:nr e = Prtl(k)*Pr_zxz(k); f = (1-Prtl(k))*Pnr_zxz(k); if ~isnan(e/(e+f)) ogmap(k) = e/(e+f); else ogmap(k) = e/(e+f+eps); end end for k = 1:size(free,1) x(k) = ogmap(k); end % clf % plot(x) % pause(0.5) % end
github
ku-ya/OccGridMap_Matlab-master
AISM.m
.m
OccGridMap_Matlab-master/2D_matlab/AISM.m
1,237
utf_8
dfc47527f8755a13591a7d99023fb78a
% 1 beam case for exact inverse sensor model occGrid % parameters function ogmap = AISM(ogmap,range,free,X_t,param) % L = 1; % world size % dx = param.resol; % grid size % create measurements and pose %% % nz = length(free); % idx = zeros(1,nz); idz = idx; % for j = 1:nz % get reduced map % [~, idx(j)] = min(abs(m_cm - X_t(j))); % [~, idz(j)] = min(abs(m_cm - X_t(j) - Z_t(j))); if size(free,1)<20 return; end Prtl = zeros(length(free),1); for k = 1:length(free) Prtl(k) = ogmap(k); end nr = length(Prtl); % Initialize Prtl(1) = 0; Prtl(nr+1) = 1; % get distance to each gird in rtl distance = sqrt((free(:,1)-X_t(1)).^2+(free(:,2)-X_t(2)).^2); pz_xr = sensorFM(nr,param.resol,range,param); % forward sensor model PDF sigma = param.sigma; rho = param.rho; pr_zx = zeros(nr,1); for k = 1:nr if k<=ceil((range-param.rangelim)/range*nr) pr_zx(k) = 0.3+(rho/(sigma*sqrt(2*pi()))+0.2)*exp(-1/2*(((range-param.rangelim-range*k/nr))/sigma)^2); else pr_zx(k) = 0.5+(rho/(sigma*sqrt(2*pi())))*exp(-1/2*((range-param.rangelim-range*k/nr)/sigma)^2); end end for k = 1:length(Prtl)-1 ogmap(k) = real(log(Prtl(k)/(1-Prtl(k))) + log(pr_zx(k)/(1-pr_zx(k)))); end ogmap = 1 - 1./(1+exp(ogmap));
github
ku-ya/OccGridMap_Matlab-master
occGridMapping.m
.m
OccGridMap_Matlab-master/2D_matlab/occGridMapping.m
4,508
utf_8
c3f68f15f6ecc50d8492c7712ca01ca8
% Robotics: Estimation and Learning % WEEK 3 % % Complete this function following the instruction. function [myMap, H, IG]= occGridMapping(ranges, scanAngles, pose, param) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 % Parameters % % % the number of grids for 1 meter. myResol = param.resol; % % the initial map size in pixels myMap = 0.5*ones(param.size); % % the origin of the map in pixels myorigin = param.origin; % % % 4. Log-odd parameters % lo_occ = param.lo_occ; % lo_free = param.lo_free; % lo_max = param.lo_max; % lo_min = param.lo_min; N = size(pose,2); for j = 1:N+param.final_frame % for each time, xt = pose(:,j); lidar_local_plt = [ranges(:,j).*cos(scanAngles + xt(3)) -ranges(:,j).*... sin(scanAngles + xt(3))]; ranges(:,j) = ranges(:,j) + param.rangelim; lidar_local = [ranges(:,j).*cos(scanAngles + xt(3)) -ranges(:,j).*... sin(scanAngles + xt(3))]; xtg = [ceil(xt(1)*myResol)+myorigin(1),ceil(xt(2)*myResol)+... myorigin(2)]; myMap(xtg(1),xtg(2)) = 0; % % % % Find grids hit by the rays (in the gird map coordinate) for k = 1:param.ray_skip:length(scanAngles)-1 rtl = ceil(lidar_local(k,:)*param.resol); [freex, freey] = bresenham(xtg(1),xtg(2),xtg(1)+rtl(1),... xtg(2)+rtl(2)); % % % Find occupied-measurement cells and free-measurement cells % % convert to 1d index % free = sub2ind(size(myMap),freey,freex); % % set end point value % map(occ(2),occ(1)) = 3; % % set free cell values % myMap(free) = 1; myMaptemp = ones(length(freex),1); for l = 1:length(freex) myMaptemp(l) = myMap(freex(l),freey(l)); end if param.ISM == 'EISM' myMaptemp = EISM(myMaptemp,ranges(k,j),[freex,freey],xtg,param); elseif param.ISM == 'AISM' myMaptemp = AISM(myMaptemp,ranges(k,j),[freex,freey],xtg,param); end for l = 1:length(freex) if myMap(freex(l),freey(l))< param.lo_occ myMap(freex(l),freey(l))=myMaptemp(l); else break end end end % % Update the map % % % % Saturate the map? % myMap(myMap>=param.lo_occ) = 1; % % % Visualize the map as needed if param.fig == 1 caxis([0.2 0.8]) imagesc(1-myMap);colormap('gray');hold on % Make a truecolor all-green image. green = cat(3, zeros(size(myMap)),... ones(size(myMap)), zeros(size(myMap))); hold on; h = imshow(green); hold off; % Use our influence map as the % AlphaData for the solid green image. I = zeros(size(myMap)); for k = 1:length(lidar_local_plt) I(ceil((lidar_local_plt(k,1)+xt(1))*param.resol)+param.origin(1),... ceil((lidar_local_plt(k,2)+xt(2))*param.resol)+param.origin(2))=1; end set(h, 'AlphaData', I) axis equal;hold on; plot(xt(2)*param.resol+param.origin(2),xt(1)*param.resol+param.origin(1),'ro','linewidth',2,'MarkerSize',8); axis tight; set(gcf, 'PaperPosition', [-1.25 -0.5 6 5.5]); %Position the plot further to the left and down. Extend the plot to fill entire paper. set(gcf, 'PaperSize', [3.7 4.7]); %Keep the same paper size saveas(gcf, [param.ISM,'/',param.ISM,'_', sprintf('Image_%d',j)], 'pdf') % print([param.ISM, '/' ,sprintf('Image_%d',j)],'-dpng'); clf; mapGridEntropy = -(myMap.*log(myMap) + (1 - myMap).*log(1-myMap)); clims = [0.0 0.8]; imagesc(mapGridEntropy,clims);colormap('jet');%hold on; % caxis([min(min(mapGridEntropy)) 1]) axis equal;axis tight;axis off; set(gcf, 'PaperPosition', [-1.25 -0.5 6 5.5]); set(gcf, 'PaperSize', [3.7 4.7]); %Keep the same paper size saveas(gcf, [param.ISM,'/',param.ISM,'_',sprintf('Image_inf_%d',j)], 'pdf') % print([param.ISM, '/' ,sprintf('Image_inf_%d',j)],'-dpng'); pause(param.pause) clf; end H(j) = mapEntropy(myMap); if j==1 IG(1) = 0; else IG(j) = H(j-1) - H(j); end % if param.ISM == 'EISM' % x = 1 % end % plot(lidar_local(:,1)+xt(1),lidar_local(:,2)+xt(2),'-x'); hold on; % pause(0.2) % end end
github
ku-ya/OccGridMap_Matlab-master
occGridMapping.m
.m
OccGridMap_Matlab-master/1D_matlab/occGridMapping.m
770
utf_8
ea8449de0c55ed97267c2b91ee9e47e2
% 1D case for exact inverse sensor model occGrid function myMap = occGridMapping(ranges, scanAngles, pose, param) %% % Parameters % % % the number of grids for 1 meter. % myResol = param.resol; % % the initial map size in pixels % myMap = zeros(param.size); % % the origin of the map in pixels % myorigin = param.origin; % % % 4. Log-odd parameters % lo_occ = param.lo_occ; % lo_free = param.lo_free; % lo_max = param.lo_max; % lo_min = param.lo_min; i = 1 % N = size(pose,2); % for j = 1:N % for each time, % % % % Find grids hit by the rays (in the gird map coordinate) % % % % Find occupied-measurement cells and free-measurement cells % % % % Update the log-odds % % % % Saturate the log-odd values % % % % Visualize the map as needed % % % end
github
zhangaigh/rovio-standalone-master
loadCalibrationCamToCam.m
.m
rovio-standalone-master/tools/kitti_tool/loadCalibrationCamToCam.m
1,894
utf_8
88db832a2338f205ea36b1a9f6231aed
function calib = loadCalibrationCamToCam(filename) % open file fid = fopen(filename,'r'); if fid<0 calib = []; return; end % read corner distance calib.cornerdist = readVariable(fid,'corner_dist',1,1); % read all cameras (maximum: 100) for cam=1:100 % read variables S_ = readVariable(fid,['S_' num2str(cam-1,'%02d')],1,2); K_ = readVariable(fid,['K_' num2str(cam-1,'%02d')],3,3); D_ = readVariable(fid,['D_' num2str(cam-1,'%02d')],1,5); R_ = readVariable(fid,['R_' num2str(cam-1,'%02d')],3,3); T_ = readVariable(fid,['T_' num2str(cam-1,'%02d')],3,1); S_rect_ = readVariable(fid,['S_rect_' num2str(cam-1,'%02d')],1,2); R_rect_ = readVariable(fid,['R_rect_' num2str(cam-1,'%02d')],3,3); P_rect_ = readVariable(fid,['P_rect_' num2str(cam-1,'%02d')],3,4); % calibration for this cam completely found? if isempty(S_) || isempty(K_) || isempty(D_) || isempty(R_) || isempty(T_) break; end % write calibration calib.S{cam} = S_; calib.K{cam} = K_; calib.D{cam} = D_; calib.R{cam} = R_; calib.T{cam} = T_; % if rectification available if ~isempty(S_rect_) && ~isempty(R_rect_) && ~isempty(P_rect_) calib.S_rect{cam} = S_rect_; calib.R_rect{cam} = R_rect_; calib.P_rect{cam} = P_rect_; end end % close file fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function A = readVariable(fid,name,M,N) % rewind fseek(fid,0,'bof'); % search for variable identifier success = 1; while success>0 [str,success] = fscanf(fid,'%s',1); if strcmp(str,[name ':']) break; end end % return if variable identifier not found if ~success A = []; return; end % fill matrix A = zeros(M,N); for m=1:M for n=1:N [val,success] = fscanf(fid,'%f',1); if success A(m,n) = val; else A = []; return; end end end
github
zhangaigh/rovio-standalone-master
loadCalibrationRigid.m
.m
rovio-standalone-master/tools/kitti_tool/loadCalibrationRigid.m
855
utf_8
9148661cd7335b41dace4f57bd25b3a4
function Tr = loadCalibrationRigid(filename) % open file fid = fopen(filename,'r'); if fid<0 error(['ERROR: Could not load: ' filename]); end % read calibration R = readVariable(fid,'R',3,3); T = readVariable(fid,'T',3,1); Tr = [R T;0 0 0 1]; % close file fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function A = readVariable(fid,name,M,N) % rewind fseek(fid,0,'bof'); % search for variable identifier success = 1; while success>0 [str,success] = fscanf(fid,'%s',1); if strcmp(str,[name ':']) break; end end % return if variable identifier not found if ~success A = []; return; end % fill matrix A = zeros(M,N); for m=1:M for n=1:N [val,success] = fscanf(fid,'%f',1); if success A(m,n) = val; else A = []; return; end end end
github
skovnats/madmm-master
procXYmnp21_n_pairwise.m
.m
madmm-master/functional_maps_L21norm/procXYmnp21_n_pairwise.m
7,338
utf_8
63dc2bbfce6e5091a94b8628539da790
function [X cXY nnr nns rrho times]=procXYmnp21_n_pairwise(FourCoeffs,mu,Ps,X0,niter,initer) % Computes the solution of % min_{Xi'Xi=I} for i=1:n-1 for j=i+1:n % mu*| FourCoeffs{i}*Xi-FourCoeffs{j}*Xj |_2,1 } % end end % + for i=1:n % + (|off(Xi'*Ps{i}*Xi)|^2 % end % % % Method: MADMM with fixed number of iterations % Simultaneous minimization on X,Y % % INPUT: % FourCoeffs: are m x n matrices where m>=n (for example: Fourier coefficients) % mu: weight factor for first part of cost function. mu>0 % Ps: are n x n- symmetric (for example: diagonal with eigenvalues on % diagonal % X0: X0.X1 and X0.X2.. are start matrices n x p where n >= p. For example, % random initialization. % % OUTPUT: % X: X.Xi are solution matrices, m x n % cXY: history of cost function (outer iteration) %% if ~exist('niter','var') niter=50; end if ~exist('initer','var') initer=50; end [m,n]=size(FourCoeffs{1,1,2}); p=size(X0.X1,2); % initialization X=X0; %% number of shapes Ns=length(FourCoeffs); %% initialization of the statistics for ii=1:(Ns-1) for jj=(ii+1):Ns eval(sprintf('nnr{%d,%d}=[];',ii,jj)); eval(sprintf('nns{%d,%d}=[];',ii,jj)); eval(sprintf('rrho{%d,%d}=[];',ii,jj)); end end %% For each a pair of shapes I need a separate Z variable for ii=1:(Ns-1) for jj=(ii+1):Ns eval(sprintf('Z{%d,%d}=FourCoeffs{%d,%d,%d}*X.X%d-FourCoeffs{%d,%d,%d}*X.X%d;',... ii,jj,ii,ii,jj,ii,jj,ii,jj,jj)); eval(sprintf('Zk{%d,%d}=Z{%d,%d};',ii,jj,ii,jj)); eval(sprintf('U{%d,%d}=ones(m,p);',ii,jj)); eval(sprintf('rho{%d,%d}=1;',ii,jj)); %initial penalty parameter end end %% Cost functions cXY=costfXY(FourCoeffs,mu,Ps,X0,Ns); %% Define the manifold for ii=1:(Ns) eval(sprintf('Man.X%d=stiefelfactory(n,p);',ii)); end problem.M = productmanifold(Man); %% Define the cost % ITERATION: Solve times=[0]; tic; for i=1:niter %% opt w.r.t X %% X is a structure, which has fields: Xi X=iterXY(FourCoeffs,mu,Ps,X,Z,U,rho,problem,initer,Ns,0,0); %% upd Z for ii=1:(Ns-1) for jj=(ii+1):Ns eval(sprintf('Z{%d,%d}=iterZ(FourCoeffs{%d,%d,%d},FourCoeffs{%d,%d,%d},X.X%d,X.X%d,U{%d,%d},rho{%d,%d},mu,p);',... ii,jj,ii,ii,jj,jj,ii,jj,ii,jj,ii,jj,ii,jj)); end end %% upd U for ii=1:(Ns-1) for jj=(ii+1):Ns eval(sprintf('U{%d,%d}=U{%d,%d}+FourCoeffs{%d,%d,%d}*X.X%d-FourCoeffs{%d,%d,%d}*X.X%d-Z{%d,%d};',... ii,jj,ii,jj,ii,ii,jj,ii,jj,ii,jj,jj,ii,jj)); end end %% updating the rho penalty for ii=1:(Ns-1) for jj=(ii+1):Ns eval(sprintf('R=FourCoeffs{%d,%d,%d}*X.X%d-FourCoeffs{%d,%d,%d}*X.X%d-Z{%d,%d};',ii,ii,jj,ii,jj,ii,jj,jj,ii,jj)); eval(sprintf('S=rho{%d,%d}*([FourCoeffs{%d,%d,%d}'';-FourCoeffs{%d,%d,%d}'']*(Z{%d,%d}-Zk{%d,%d}));',ii,jj,ii,ii,jj,jj,ii,jj,ii,jj,ii,jj)); %% nr=norm(R,'fro'); ns=norm(S,'fro'); %% if nr>=10*ns eval(sprintf('rho{%d,%d}=2*rho{%d,%d};',ii,jj,ii,jj)); eval(sprintf('U{%d,%d}=U{%d,%d}/2;',ii,jj,ii,jj)); end if ns > 10*nr eval(sprintf('rho{%d,%d}=rho{%d,%d}/2;',ii,jj,ii,jj)); eval(sprintf('U{%d,%d}=2*U{%d,%d};',ii,jj,ii,jj)); end %% saving the stats eval(sprintf('nnr{%d,%d}=[nnr{%d,%d};nr];',ii,jj,ii,jj)); eval(sprintf('nns{%d,%d}=[nns{%d,%d};ns];',ii,jj,ii,jj)); eval(sprintf('rrho{%d,%d}=[rrho{%d,%d};rho{%d,%d}];',ii,jj,ii,jj,ii,jj)); end end %% upd variables Zij for ii=1:(Ns-1) for jj=(ii+1):Ns % The "previous" Z matrix eval(sprintf('Zk{%d,%d}=Z{%d,%d};',ii,jj,ii,jj)); end end %% SAVE THE COST cXY=[cXY;costfXY(FourCoeffs,mu,Ps,X,Ns)]; %% fprintf('%d:%f\n',i,cXY(end)); %% times=[times;toc]; end end function X=iterXY(FourCoeffs,mu,Ps,X,Z,U,rho,problem,initer,ns,gV,gW) % minimizes sum_ij mu| Zij |_2,1 + rho/2*| FourCoeffiXi-FourCoeffjXj-Zij+Uij |^2+ % + sum_i norm(off(Xi'Ps{i}Xi),'fro')^2 % with respect to Xi'*Xi=I % by performing some steps with Manopt minimization %% Define the options % Stopfunction options.stopfun = @mystopfun; function stopnow = mystopfun(problem, x, info, last) stopnow = (last >= 3 && (info(last-2).cost - info(last).cost)/info(last).cost < 1e-3); end options.maxiter=initer; % 50 -> Klaus parameter % Switch on/off details of inner iteration options.verbosity=0; % Define the problem cost function and its gradient. problem.cost = @cost ; function f=cost(X) f=0; for ii=1:(ns-1) for jj=(ii+1):ns eval(sprintf('f=f+0.5*rho{%d,%d}*norm(FourCoeffs{%d,%d,%d}*X.X%d-FourCoeffs{%d,%d,%d}*X.X%d-Z{%d,%d}+U{%d,%d},''fro'')^2;',... ii,jj,ii,ii,jj,ii,jj,ii,jj,jj,ii,jj,ii,jj)); end end for ii=1:(ns) eval(sprintf('f=f+norm(off(X.X%d''*Ps{%d}*X.X%d),''fro'')^2;',ii,ii,ii)); end end problem.grad = @(X) problem.M.egrad2rgrad(X, egrad_n(X)); function g=egrad_n(X) % F=B*X.W+Z-U; % G=A*X.V-Z+U; % % g.V=zeros(n,p); % g.V=g.V+rho*A'*(A*X.V-F); % g.V=g.V+4*P*X.V*off(X.V'*P*X.V); % % g.W=zeros(n,p); % g.W=g.W+rho*B'*(B*X.W-G); % g.W=g.W+4*Q*X.W*off(X.W'*Q*X.W); %% Gradient of the off-diag part for ii=1:(ns) eval(sprintf('g.X%d=4*Ps{%d}*X.X%d*off(X.X%d''*Ps{%d}*X.X%d);',ii,ii,ii,ii,ii,ii)); end %% Graident on the rho/2|AXi-BXj-Zij+Uij| part for ii=1:(ns-1) for jj=(ii+1):ns eval(sprintf('[gV,gW]=egrad(FourCoeffs{%d,%d,%d},Ps{%d},X.X%d,FourCoeffs{%d,%d,%d},Ps{%d},X.X%d,Z{%d,%d},U{%d,%d},rho{%d,%d});',... ii,ii,jj,ii,ii,jj,ii,jj,jj,jj,ii,jj,ii,jj,ii,jj)); eval(sprintf('g.X%d=g.X%d+gV;',ii,ii)); eval(sprintf('g.X%d=g.X%d+gW;',jj,jj)); end end % end % Numerically check the differential % checkgradient(problem); % pause; %} % Solve. %[X, Xcost, info, options] = trustregions(problem,X0,options); [X, Xcost, infoS, options] = conjugategradient(problem,X,options); end function Z=iterZ(A,B,V,W,U,rho,mu,p) % minimizes mu*|| Z ||_2,1 + rho/2*|| -A*X.V+B*X.W+Z-U ||^2 % with respect to Z by "shrinking" F=A*V-B*W+U; for j=1:p Z(:,j)=Shrink(F(:,j),mu/rho); end function [z]=Shrink(z,l) nz=norm(z); z=max(nz-l,0)*z/nz; end end function Y=off(X) Y=X-diag(diag(X)); end function f=costfXY(FourCoeffs,mu,Ps,X,ns) f=0; for ii=1:(ns-1) eval(sprintf('V=X.X%d;',ii)); for jj=(ii+1):ns A=FourCoeffs{ii,ii,jj}; B=FourCoeffs{jj,ii,jj}; eval(sprintf('W=X.X%d;',jj)); C=A*V-B*W; c=sqrt(sum(C.*C)); f=f+mu*sum(c); end end for ii=1:(ns) % eval(sprintf('V=X.X%d;',ii)); eval(sprintf('f=f+norm(off(X.X%d''*Ps{%d}*X.X%d),''fro'')^2;',ii,ii,ii)); end end function [gV,gW]=egrad(A,P,V,B,Q,W,Z,U,rho) F=B*W+Z-U; G=A*V-Z+U; % gV=zeros(n,p); gV=rho*A'*(A*V-F); % gV=gV+4*P*V*off(V'*P*V); % gW=zeros(n,p); gW=rho*B'*(B*W-G); % gW=gW+4*Q*W*off(W'*Q*W); end
github
skovnats/madmm-master
d_shape.m
.m
madmm-master/functional_maps_L21norm/help_functions/d_shape.m
1,489
utf_8
101bd876cf423a57e4af57e52beeaa64
function [d] = d_shape(shape, src_idx) if ismac d=d_shape2(shape,src_idx); else num_vert = length(shape.X); src = repmat(Inf, num_vert, 1); src(src_idx) = 0; d = fastmarch(shape.TRIV, shape.X, shape.Y, shape.Z, double(src), set_options('mode', 'single')); % d = fastmarchmex('init', int32(TRIV-1), double(X(:)), double(Y(:)), double(Z(:))); % f = fastmarchmex('march',f,double(u)); end % function [d] = d_shape(shape, src_id end function [d] = d_shape2(shape, src_idx) if ismac num_vert = length(shape.X); src = repmat(Inf, num_vert, 1); src(src_idx) = 0; %- f = fastmarchmex('init', int32(shape.TRIV-1), double(shape.X(:)), double(shape.Y(:)), double(shape.Z(:))); d = fastmarchmex('march', f, double(src)); d(d>=9999999) = Inf; % d = fastmarch(shape.TRIV, shape.X, shape.Y, shape.Z, double(src), set_options('mode', 'single')); % d = fastmarchmex('init', int32(TRIV-1), double(X(:)), double(Y(:)), double(Z(:))); % f = fastmarchmex('march',f,double(u)); fastmarchmex('deinit', f); else num_vert = length(shape.X); src = repmat(Inf, num_vert, 1); src(src_idx) = 0; d = fastmarch(shape.TRIV, shape.X, shape.Y, shape.Z, double(src), set_options('mode', 'single')); % d = fastmarchmex('init', int32(TRIV-1), double(X(:)), double(Y(:)), double(Z(:))); % f = fastmarchmex('march',f,double(u)); end % function [d] = d_shape(shape, src_id end
github
skovnats/madmm-master
args2struct.m
.m
madmm-master/functional_maps_L21norm/help_functions/args2struct.m
510
utf_8
961ec8b35e883660b8b208bf814011dd
% Convert argument pairs to a structure function S = args2struct(varargin) % No inputs, return empty structure if isempty(varargin), S = struct(); return; end if length(varargin) == 1 && isempty(varargin{1}), S = struct(); return; end % Need pairs of inputs if mod(length(varargin),2)==1 error('number of arguments must be even'); end % Odd elements of varargin are fields, even ones are values % Store all field names in lower case for k = 1:2:length(varargin) S.(varargin{k}) = varargin{k+1}; end
github
skovnats/madmm-master
dsh.m
.m
madmm-master/functional_maps_L21norm/help_functions/dsh.m
3,071
utf_8
21a9744f4519ebab630e1b0e49935922
% script for dispalying shape function [] = dsh( varargin ) % input: %{ {1} - title {2} - if save %} vector = false; flag = true; name = []; switch nargin case 1 shape = varargin{ 1 }; case 2 shape = varargin{ 1 }; tname = varargin{ 2 }; if isnumeric(tname) vector = true; if size(tname,2)>1 for i=1:size(tname) dsh(shape,tname(:,i)); title(num2str(i)); waitforbuttonpress; end end else vector = false; end case 3 shape = varargin{ 1 }; tname = varargin{ 2 }; issave = varargin{ 3 }; if isnumeric(tname) vector = true; else vector = false; end if isstr( issave ) name = issave; issave = false; end case 4 shape = varargin{ 1 }; tname = varargin{ 2 }; vector = true; name = varargin{ 3 }; issave = varargin{ 4 }; end if iscell( shape ) flag = false; for i = 1:length( shape ) dsh( shape{ i } ); title( sprintf( 'shape %d/%d', i, length( shape ) ) ); waitforbuttonpress; end end if flag if ~vector % displaying if ~isfield( shape, 'C' ) trisurf( shape.TRIV, shape.X, shape.Y, shape.Z, ones(size((shape.X))) ), ... end else trisurf( shape.TRIV, shape.X, shape.Y, shape.Z, full(tname) ), ... end if isfield( shape, 'C' ) if ~vector try %% % UPD: 15.11.2011 lab = [shape.L, shape.a, shape.b]; lab = colorspace( 'lab->rgb', lab ); shape.C = lab; trisurf( shape.TRIV, shape.X, shape.Y, shape.Z, 1:(length(shape.X)) ) catch trisurf( shape.TRIV, shape.X, shape.Y, shape.Z, 1:(length(shape.X)) ) end %% colormap(shape.C),axis off, axis image; % colormap(ones( length(shape.X), 3 )), end axis off, % axis image, shading interp; % lighting phong, camlight('headlight'); % was commented else if ~vector colormap(ones( length(shape.X), 3 )), end axis off, axis image; axis off, axis image, shading flat, lighting phong, camlight('headlight'); % axis off, axis image, shading interp, lighting phong, camlight('headlight'); end switch nargin case 2 if ~vector title(tname); end case 3 if ~vector title(tname); end % if isstr( name ) title(name); end if issave saveas( gcf, [tname '.png'] ) end case 4 title( name ); if issave saveas( gcf, [name '.png'] ) end end cameratoolbar set(gcf,'Color','w'); %% % axon; end
github
skovnats/madmm-master
dstcalc.m
.m
madmm-master/functional_maps_L21norm/help_functions/dstcalc.m
3,459
utf_8
7e2aa60336c6d4919af9f2637029f662
function [varargout] = dstcalc(method, varargin) % functioon does distance calculations % inputs: % s = dstcalc( 'init', 'diffusion', shape, t, opt ); % d = dstcalc( 'compute', s, sample, shape ); switch lower(method) case 'init' type = varargin{1}; s = init_distance(type, varargin(2:end)); varargout(1) = { s }; case 'compute' s = varargin{1}; d = compute_distance(s, varargin(2:end)); varargout(1) = { d }; case 'deinit' s = varargin{1}; deinit_distance(s); end function [evals evecs areas W] = compute_spectrum(surface, Nvec) % Compute Laplacian matrices opt = giveopt( 'nastya', Nvec ); opt.COLOR_W = 0; [ W, Am, evecs, evals ] = DLBO( surface, opt ); areas = full( diag( Am ) ); nrm = sqrt(areas(:)'*evecs.^2); evecs = bsxfun(@rdivide, evecs, nrm); % normalizing evecss function s = init_distance(type, varargin) if isfield(varargin{1}{1}, 'type'), s = varargin{1}{1}; else s = []; % here need to add an option of adding the eigendata if length( varargin{1} ) > 2 s = varargin{1}{3}; end surface = varargin{1}{1}; s.Nv = length(surface.X); end s.type = type; switch lower(type) case 'geodesic' % s.handle = fastmarchmex('init', int32(surface.TRIV-1), double(surface.X(:)), double(surface.Y(:)), double(surface.Z(:))); % s.handle = fastmarchmex('init', int32(surface.TRIV-1), double(surface.X(:)), double(surface.Y(:)), double(surface.Z(:))); case 'diffusion' t = varargin{1}{2}; s.kernel = @(lambda)(exp(-t*lambda)); if ~isfield(s, 'evecs') [s.evals, s.evecs s.areas] = compute_spectrum(surface, 200); end case 'commute' s.kernel = @(lambda)(1./sqrt(lambda)); if ~isfield(s, 'evecs') [s.evals, s.evecs s.areas] = compute_spectrum(surface, 200); end end function d = compute_distance(s, varargin) sample = varargin{1}{1}; switch lower(s.type) case 'geodesic' shape=varargin{1}{2}; %{ source = repmat(Inf, [s.Nv 1]); source(sample) = 0; % TODO: this is extremely inefficient as the grid is re-initialized at % each iteration! d = fastmarch(shape.TRIV, shape.X, shape.Y, shape.Z, double(source), struct('mode', 'single')); % d = fastmarchmex('march', s.handle, double(source)); d(d>=9999999) = Inf; %} %- d = d_shape( shape, sample ); case {'diffusion', 'commute'} kernel = s.kernel; d = (bsxfun(@minus, s.evecs(sample,2:end), s.evecs(:,2:end)).^2)*(kernel(s.evals(2:end)).^2); d = sqrt(d); case 'euc' shape=varargin{1}{2}; % TODO: this is extremely inefficient as the grid is re-initialized at % each iteration! d = sqrt((shape.X( sample ) - shape.X).^2+(shape.Y( sample ) - shape.Y).^2+(shape.Z( sample ) - shape.Z).^2); % d = fastmarchmex('march', s.handle, double(source)); d(d>=9999999) = Inf; end function deinit_distance(s) switch lower(s.type) case 'geodesic' fastmarchmex('deinit', s.handle); case {'diffusion', 'commute'} end
github
skovnats/madmm-master
parseOpt.m
.m
madmm-master/functional_maps_L21norm/help_functions/parseOpt.m
985
utf_8
7ea99e27df68a53e6b0a2c74ff21cf17
% Construct options structure with a template % S can be varargin or struct % D are the default values struct function T = parseOpt(D,varargin) if length(varargin) == 1 && isstruct(varargin{1}) S = varargin{1}; else S = args2struct(varargin{:}); end T = D; % copy the template if isempty(S) return; end % Check arguments, must have two structures if ~(isstruct(S) && isstruct(D)) error('input arguments must be structures'); end fname = fields(S); % make a list of field names % Loop over all fields in the template, copy matching values from S for k = 1:length(fname) % Process matching field names in S if isfield(D,fname{k}) % Is this a substructure ? if isstruct(T.(fname{k})) && isstruct(S.(fname{k})) % Recursively process the substructure T.(fname{k}) = parseOpt(T.(fname{k}),S.(fname{k})); % Not a substructure, copy field value from S else T.(fname{k}) = S.(fname{k}); end end end end
github
skovnats/madmm-master
fastmarch.m
.m
madmm-master/functional_maps_L21norm/help_functions/fastmarch.m
3,803
utf_8
ea85445d2c05290379ec7e62b3832ac8
% fastmarch Fast marching algorithm for geodesic distance approximation % % Usage: % % D = fastmarch(TRIV, X, Y, Z, [src], [opt]) % D = fastmarch(surface, [src], [opt]) % % Description: % % Computes the geodesic distances on a triangulated surfaces using % the fast marching algorithm. The algorithm may operate in two modes: % single-source and multiple-source. In the single-source mode, a distance % map of every mesh vertex from a single source is computed. The source % may be a single point on the mesh, or any other configuration described % by an initial set of values per mesh vertex. In the multiple-source % mode, a matrix of pair-wise geodesic distances is computed between a % specified set of mesh vertices. % % Input: % % TRIV - ntx3 triangulation matrix with 1-based indices (as the one % returned by the MATLAB function delaunay). % X,Y,Z - vectors with nv vertex coordinates. % surface - alternative way to specify the mesh as a struct, having .TRIV, % .X, .Y, and .Z as its fields. % src - in the multiple-source mode: (default: src = [1:nv]) % list of ns mesh vertex indices to be used as sources. % in the single-source mode: (must be specified) % an nvx1 list of initial values of the distance function on the mesh % (set a vertex to Inf to exclude it from the source set). src % opt - (optional) settings % .mode - Mode (default: 'multiple') % 'multiple' - multiple-source % 'single' - single-source % % Output: % % D - In the multiple-source mode: % nsxns matrix of approximate geodesic distances, where D(i,j) is % the geodesic distance between the i-th and the j-th point, % whose indices are specified by src(i) and src(j), % respectively. % In the single-source mode: % nvx1 vector of approximated geodesic distances, where D(i) is % the geodesic distance from the i-th mesh vertex to the % source. % % References: % % [1] R. Kimmel and J. A. Sethian. "Computing geodesic paths on manifolds", % Proc. of National Academy of Sciences, USA, 95(15), p. 8431-8435, 1998. % % TOSCA = Toolbox for Surface Comparison and Analysis % Web: http://tosca.cs.technion.ac.il % Version: 0.9 % % (C) Copyright Alex Bronstein, 2005-2007 % (C) Portions copyright Moran Feldman, 2003-2004. % (C) Portions copyright Ron Kimmel. % All rights reserved. % % License: % % ANY ACADEMIC USE OF THIS CODE MUST CITE THE ABOVE REFERENCES. % ANY COMMERCIAL USE PROHIBITED. PLEASE CONTACT THE AUTHORS FOR % LICENSING TERMS. PROTECTED BY INTERNATIONAL INTELLECTUAL PROPERTY % LAWS AND PATENTS PENDING. function [D] = fastmarch(TRIV, X, Y, Z, src, opt) if nargin < 4, surface = TRIV; TRIV = surface.TRIV; X = surface.X; Y = surface.Y; Z = surface.Z; end mode = 0; if nargin > 5 & isfield(opt, 'mode'), if strcmpi(opt.mode, 'multiple'), mode = 0; elseif strcmpi(opt.mode, 'single'), mode = 1; else error('Invalid mode. Use either "multiple" or "single".'); end end if nargin == 1 | nargin == 4, if mode == 0, src = [1:length(X)]; else error('Source set must be specified in single source mode.'); end end if mode & length(src) ~= length(X(:)), error('src must be nvx1 in the single source mode.'); end % MEX implementation if ~mode, [D] = fastmarch_mex(int32(TRIV-1), int32(src(:)-1), double(X(:)), double(Y(:)), double(Z(:))); else [D] = fastmarch1_mex(int32(TRIV-1), double(src(:)), double(X(:)), double(Y(:)), double(Z(:))); end
github
skovnats/madmm-master
gencols.m
.m
madmm-master/functional_maps_L21norm/help_functions/gencols.m
5,738
utf_8
497e10b44a80cff59db8f7c18b5a9608
function colors = gencols(n_colors,bg,func) % DISTINGUISHABLE_COLORS: pick colors that are maximally perceptually distinct % % When plotting a set of lines, you may want to distinguish them by color. % By default, Matlab chooses a small set of colors and cycles among them, % and so if you have more than a few lines there will be confusion about % which line is which. To fix this problem, one would want to be able to % pick a much larger set of distinct colors, where the number of colors % equals or exceeds the number of lines you want to plot. Because our % ability to distinguish among colors has limits, one should choose these % colors to be "maximally perceptually distinguishable." % % This function generates a set of colors which are distinguishable % by reference to the "Lab" color space, which more closely matches % human color perception than RGB. Given an initial large list of possible % colors, it iteratively chooses the entry in the list that is farthest (in % Lab space) from all previously-chosen entries. While this "greedy" % algorithm does not yield a global maximum, it is simple and efficient. % Moreover, the sequence of colors is consistent no matter how many you % request, which facilitates the users' ability to learn the color order % and avoids major changes in the appearance of plots when adding or % removing lines. % % Syntax: % colors = distinguishable_colors(n_colors) % Specify the number of colors you want as a scalar, n_colors. This will % generate an n_colors-by-3 matrix, each row representing an RGB % color triple. If you don't precisely know how many you will need in % advance, there is no harm (other than execution time) in specifying % slightly more than you think you will need. % % colors = distinguishable_colors(n_colors,bg) % This syntax allows you to specify the background color, to make sure that % your colors are also distinguishable from the background. Default value % is white. bg may be specified as an RGB triple or as one of the standard % "ColorSpec" strings. You can even specify multiple colors: % bg = {'w','k'} % or % bg = [1 1 1; 0 0 0] % will only produce colors that are distinguishable from both white and % black. % % colors = distinguishable_colors(n_colors,bg,rgb2labfunc) % By default, distinguishable_colors uses the image processing toolbox's % color conversion functions makecform and applycform. Alternatively, you % can supply your own color conversion function. % % Example: % c = distinguishable_colors(25); % figure % image(reshape(c,[1 size(c)])) % % Example using the file exchange's 'colorspace': % func = @(x) colorspace('RGB->Lab',x); % c = distinguishable_colors(25,'w',func); % Copyright 2010-2011 by Timothy E. Holy % Parse the inputs if (nargin < 2) bg = [1 1 1]; % default white background else if iscell(bg) % User specified a list of colors as a cell aray bgc = bg; for i = 1:length(bgc) bgc{i} = parsecolor(bgc{i}); end bg = cat(1,bgc{:}); else % User specified a numeric array of colors (n-by-3) bg = parsecolor(bg); end end % Generate a sizable number of RGB triples. This represents our space of % possible choices. By starting in RGB space, we ensure that all of the % colors can be generated by the monitor. n_grid = 30; % number of grid divisions along each axis in RGB space x = linspace(0,1,n_grid); [R,G,B] = ndgrid(x,x,x); rgb = [R(:) G(:) B(:)]; if (n_colors > size(rgb,1)/3) error('You can''t readily distinguish that many colors'); end % Convert to Lab color space, which more closely represents human % perception if (nargin > 2) lab = func(rgb); bglab = func(bg); else C = makecform('srgb2lab'); lab = applycform(rgb,C); bglab = applycform(bg,C); end % If the user specified multiple background colors, compute distances % from the candidate colors to the background colors mindist2 = inf(size(rgb,1),1); for i = 1:size(bglab,1)-1 dX = bsxfun(@minus,lab,bglab(i,:)); % displacement all colors from bg dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color end % Iteratively pick the color that maximizes the distance to the nearest % already-picked color colors = zeros(n_colors,3); lastlab = bglab(end,:); % initialize by making the "previous" color equal to background for i = 1:n_colors dX = bsxfun(@minus,lab,lastlab); % displacement of last from all colors on list dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color [~,index] = max(mindist2); % find the entry farthest from all previously-chosen colors colors(i,:) = rgb(index,:); % save for output lastlab = lab(index,:); % prepare for next iteration end end function c = parsecolor(s) if ischar(s) c = colorstr2rgb(s); elseif isnumeric(s) && size(s,2) == 3 c = s; else error('MATLAB:InvalidColorSpec','Color specification cannot be parsed.'); end end function c = colorstr2rgb(c) % Convert a color string to an RGB value. % This is cribbed from Matlab's whitebg function. % Why don't they make this a stand-alone function? rgbspec = [1 0 0;0 1 0;0 0 1;1 1 1;0 1 1;1 0 1;1 1 0;0 0 0]; cspec = 'rgbwcmyk'; k = find(cspec==c(1)); if isempty(k) error('MATLAB:InvalidColorString','Unknown color string.'); end if k~=3 || length(c)==1, c = rgbspec(k,:); elseif length(c)>2, if strcmpi(c(1:3),'bla') c = [0 0 0]; elseif strcmpi(c(1:3),'blu') c = [0 0 1]; else error('MATLAB:UnknownColorString', 'Unknown color string.'); end end end
github
skovnats/madmm-master
calcP2PFromC.m
.m
madmm-master/functional_maps_L21norm/help_functions/calcP2PFromC.m
4,024
utf_8
55d56d20cf41bd21297a7e68997ee6c7
% % Finds the point to point correspondence between shape1 and shape2 % from C, so that % C * basis1 ~ basis2(:, shape1toshape2) % C' * basis2 ~ basis1(:, shape2toshape1) % Author Jonathan Pokrass function [shape1toshape2, shape2toshape1, refinedC] = ... calcP2PFromC(shape1, shape2, C, basis1, basis2, varargin) defaultOpt.useGroundTruth = 1; defaultOpt.useSymmetricToo = 1; defaultOpt.numRefinements = 10; defaultOpt.debug = 0; defaultOpt.drawSphere = 0; opt = parseOpt(defaultOpt, varargin{:}); opt.debug = 0; C = C'; % why does he take transpose? refinedC = C; prevC = C; timeit.ICP = 0; b2 = basis2'; b1 = basis1'; prevVal = Inf; searchIndexParams = struct(); shape1toshape2 = []; for icpIter = 0:opt.numRefinements if opt.debug figure(1) subplot(1,2,1); imagesc(abs(C)) subplot(1,2,2); imagesc(abs(refinedC)) title('refined C'); end b2Perm = refinedC * b1; b1Perm = refinedC'* b2; if icpIter == opt.numRefinements %searchIndexParams = struct('algorithm', 'linear'); else searchIndexParams = struct(); end tic; % prevShape1toshape2 = shape1toshape2; % shape1toshape2 = flann_search(b2, b2Perm, 1, searchIndexParams); shape1toshape2 = ann_search(b2, b2Perm, 1); %shape2toshape1 = flann_search(refinedC * basis1', b2, 1, searchIndexParams); B = b2(:, shape1toshape2); A = b1; newVal = norm(refinedC * A - B,'fro'); if prevVal < newVal printlog(' Refine worsened the results restoring prevC'); refinedC = prevC; shape1toshape2 = prevShape1toshape2; b2Perm = refinedC * b1; b1Perm = refinedC'* b2; break; end prevVal = newVal; flannTime = toc; timeit.ICP = timeit.ICP + flannTime; printlog(' flann time = %f secs', flannTime); if icpIter < opt.numRefinements printlog(' Preforming refinement (%d/%d)', icpIter + 1, opt.numRefinements); tic; %find refinedC = argmin ||refinedC * basis1 - basis2(:, shape1toshape2result)|| % s.t. refinedC * refinedC' = I [U,S,V] = svd(B*A'); U(:,end)=U(:,end)*det(U*V'); newCR=U*V'; timeit.ICP = timeit.ICP + toc; crdiff = sum(sum((abs(newCR - refinedC)))); printlog(' crdiff = %f', crdiff); if crdiff < 0.01 printlog(' Refinments converged stopping refinments') break; end prevC = refinedC; refinedC = newCR; end end % shape2toshape1 = flann_search(basis1', b1Perm, 1, searchIndexParams); shape2toshape1 = ann_search(basis1', b1Perm, 1); refinedC = refinedC'; %shape2toshape1result = flann_search(CR * basis1', b2, 1, searchIndexParams); %flann_free_index(b2_index); if opt.debug %Draw point-wise correspondance figure(10) clf subplot(1, 4, 1); shape1_ = rotate_shape(shape1, rotation_matrix(0,0,0*pi/180), [0 0 0]); shape2_ = rotate_shape(shape2, rotation_matrix(0,0,0*pi/180), [0 0 0]); d = shape1.X(:) + max(abs(shape1.X(:))) + 1; d2 = shape2.X(:) + max(abs(shape2.X(:))) + 1; nv1 = length(shape1toshape2); colormap(jet(1000)); drawShape(shape1, 'ptColor', d([1:nv1])); title(' '); subplot(1, 4, 3); drawShape(shape2_, 'ptColor', d(shape2toshape1)); title('result'); colormap(jet(50)); for j = 20:100:20 points2idxs = farptsel(shape2, j); points1 = []; points2 = []; points2.X = shape2_.X(points2idxs); points2.Y = shape2_.Y(points2idxs); points2.Z = shape2_.Z(points2idxs); points1.X = shape1_.X(shape2toshape1(points2idxs)); points1.Y = shape1_.Y(shape2toshape1(points2idxs)); points1.Z = shape1_.Z(shape2toshape1(points2idxs)); figure; colormap(jet(200)); plotMatchingPoints(shape2_, shape1_, points2idxs, shape2toshape1(points2idxs),... 'ptColor1', d2, 'ptColor2', d2(shape1toshape2), 'drawSphere', opt.drawSphere); figure; plotMatchingPoints(shape1_, shape2_, shape2toshape1(points2idxs),points2idxs,... 'ptColor1', d, 'ptColor2', d(shape2toshape1), 'drawSphere', opt.drawSphere); end drawnow; end end
github
skovnats/madmm-master
GeneralKimEval_final.m
.m
madmm-master/functional_maps_L21norm/help_functions/GeneralKimEval_final.m
1,707
utf_8
2c841d575fe0f89c210b00506b342eca
function [deviation,distribution,x] = GeneralKimEval_final( shape1, shape2, AX, AY, T12, L12gr ) % Generalized Kim's curve evaluation % d(i\in X) = \sum_{j=1}^{|Y|} d(j,gr(i)) * t_i(j)/sum_s(t_i(s)) * 1/sqrt(A(Y)) % X->1, Y->2, gr(i)-ground-truth corresponding point of point i, % t_i(j)-function corresponding to delta function d_i (ideally delta function for gr(i)); A(Y)-area of Y % AX, AY - vectors of local area elements % According to my estimation, max(deviation)<=diam/AY % T12=T12-min(T12(:)); % T12=T12/max(T12(:)); % T12=max(T12,0); T12=abs(T12); % thresh=0.65; dt=1e-4; %%The deviation will be calculated at predefined verteces of the first %%shape (fps algorithm) if isfield(shape1,'idx') idx=shape1.idx; else idx=fps(1,150-1,shape1); end if isfield(shape2,'pidx') pidx=shape2.pidx; else pidx=L12gr(idx,2); end if isfield(shape2,'D') D=full(shape2.D); else D = fastmarch_idx(shape2,pidx); end % if not enough memory % Consider splitting matrix T into L and R % T=T12./repmat( sum(T12), size(T12,1), 1 );%normalizing columns of T, i.e. t_i(y) AY=sqrt(sum(AY(:)));% AREA % T=D*T;%n2 x n1 ind=sub2ind(size(T),1:length(idx),idx(:).'); deviation=T(ind)/AY; deviation0=zeros(size(shape1.X)); deviation0(idx)=deviation; % n1=length(idx); x=0:dt:thresh; x(end+1)=x(end)+dt; stam=hist(deviation,x); stam=stam(1:(end-1)); x=x(1:(end-1)); distribution=(cumsum(stam)/n1)*100; end function [D] = fastmarch_idx(shape,idx) n=length(shape.X); D=zeros(length(idx),n); % for i = 1:length(idx) ii=idx(i); % d=d_shape2(shape,ii); D(i,:)=d(:).'; end % d=D(:); d=d(d~=Inf); mx=max(d); D(D==Inf)=mx; end
github
skovnats/madmm-master
ann.m
.m
madmm-master/functional_maps_L21norm/help_functions/ann/ann.m
6,187
utf_8
ab7233e7b917418ec6656b2d926c2ce4
function varargout = ann(method, varargin) %error(nargchk(3, inf, nargin)); % some predicates is_normal_matrix = @(x) isnumeric(x) && ndims(x) == 2 && isreal(x) && ~issparse(x); is_posint_scalar = @(x) isnumeric(x) && isscalar(x) && x == fix(x) && x > 0; is_switch = @(x) islogical(x) && isscalar(x); is_float_scalar = @(x) isfloat(x) && isscalar(x); % % Xr and Xq % require_arg(is_normal_matrix(Xr), 'Xr should be a full numeric real matrix'); % require_arg(is_normal_matrix(Xq), 'Xq should be a full numeric real matrix'); % % [d, n] = size(Xr); % require_arg(size(Xq, 1) == d, 'The point dimensions in Xr and Xq are inconsistent.') % % % k % require_arg(is_posint_scalar(k), 'k should be a positive integer scalar'); % require_arg(k <= n, 'The value k exceeds the number of reference points'); k = 1; switch method, case 'init' ref_pts = varargin{1}; varargin = varargin(2:end); case 'search' tree = varargin{1}; query_pts = varargin{2}; if length(varargin) > 2, k = varargin{3}; varargin = varargin(4:end); else varargin = varargin(3:end); end case 'deinit' tree = varargin{1}; varargin = varargin(2:end); case 'close' otherwise error('INVALID COMMAND'); end % options opts = struct( ... 'use_bdtree', false, ... 'bucket_size', 1, ... 'split', 'suggest', ... 'shrink', 'suggest', ... 'search_sch', 'std', ... 'eps', 0, ... 'radius', 0); if ~isempty(varargin) opts = setopts(opts, varargin{:}); end %require_opt(is_switch(opts.use_bdtree), 'The option use_bdtree should be a logical scalar.'); require_opt(is_posint_scalar(opts.bucket_size), 'The option bucket_size should be a positive integer.'); split_c = get_name_code('splitting rule', opts.split, ... {'std', 'midpt', 'sl_midpt', 'fair', 'sl_fair', 'suggest'}); if opts.use_bdtree shrink_c = get_name_code('shrinking rule', opts.shrink, ... {'none', 'simple', 'centroid', 'suggest'}); else shrink_c = int32(0); end ssch_c = get_name_code('search scheme', opts.search_sch, ... {'std', 'pri', 'fr'}); require_opt(is_float_scalar(opts.eps) && opts.eps >= 0, ... 'The option eps should be a non-negative float scalar.'); use_fix_rad = strcmp(opts.search_sch, 'fr'); if use_fix_rad require_opt(is_float_scalar(opts.radius) && opts.radius > 0, ... 'The option radius should be a positive float scalar in fixed-radius search'); rad2 = opts.radius * opts.radius; else rad2 = 0; end % main (invoking mexann) internal_opts = struct( ... 'use_bdtree', opts.use_bdtree, ... 'bucket_size', int32(opts.bucket_size), ... 'split', split_c, ... 'shrink', shrink_c, ... 'search_sch', ssch_c, ... 'knn', int32(k), ... 'err_bound', opts.eps, ... 'search_radius', rad2); %[nnidx, dists] = mexann(Xr, Xq, internal_opts); switch method, case 'init' tree = mexann('createKdTree', ref_pts, internal_opts); varargout(1) = { tree }; case 'search' [nnidx, dists] = mexann('performAnnkSearch', tree, query_pts, internal_opts); nnidx = nnidx + 1; % from zero-based to one-based if nargout >= 2 dists = sqrt(dists); % from squared distance to euclidean if use_fix_rad dists(nnidx == 0) = inf; end end varargout(1) = { nnidx }; varargout(2) = { dists }; case 'deinit' mexann('deleteKdTree', tree); case 'close' mexann('annClose'); clear mexann; end % Auxiliary function function c = get_name_code(optname, name, names) require_opt(ischar(name), ['The option ' optname ' should be a string indicating a name.']); cidx = find(strcmp(name, names)); require_opt(~isempty(cidx), ['The option ' optname ' cannot be assigned to be ' name]); c = int32(cidx - 1); function require_arg(cond, msg) if ~cond error('ann_mwrapper:annquery:invalidarg', msg); end function require_opt(cond, msg) if ~cond error('ann_mwrapper:annquery:invalidopt', msg); end function opts = setopts(opts0, varargin) if isempty(opts0) opts = []; elseif isstruct(opts0) && isscalar(opts0) opts = opts0; else error('dmtoolbox:setopts:invalidarg', ... 'opts0 should be either a struct scalar or empty.'); end if nargin > 1 fparam = varargin{1}; if isstruct(fparam) if nargin > 2 error('dmtoolbox:setopts:invalidarg', ... 'No input arguments are allowed to follow the struct parameter'); end params = fparam; elseif iscell(fparam) if nargin > 2 error('dmtoolbox:setopts:invalidarg', ... 'No input arguments are allowed to follow the cell parameter'); end params = fparam; elseif ischar(fparam) params = varargin; else error('dmtoolbox:setopts:invalidarg', 'The input argument list is illegal.'); end else return; end %% main delegate if iscell(params) opts = setopts_with_cell(opts, params); else opts = setopts_with_struct(opts, params); end %% core functions function opts = setopts_with_cell(opts, params) names = params(1:2:end); values = params(2:2:end); n = length(names); if length(values) ~= n error('dmtoolbox:setopts:invalidarg', 'The names and values should form pairs'); end for i = 1 : n opts.(names{i}) = values{i}; end function opts = setopts_with_struct(opts, params) fns = fieldnames(params); n = length(fns); for i = 1 : n fn = fns{i}; opts.(fn) = params.(fn); end
github
skovnats/madmm-master
calcVoronoiRegsCircCent.m
.m
madmm-master/functional_maps_L21norm/help_functions/laplacian/calcVoronoiRegsCircCent.m
2,497
utf_8
b33c6683c5fafa8ead79d9436c30477f
function [VorRegsVertices] = calcVoronoiRegsCircCent(Tri, Vertices) %% Preps.: A1 = Vertices(Tri(:,1), :); A2 = Vertices(Tri(:,2), :); A3 = Vertices(Tri(:,3), :); a = A1 - A2; % Nx3 b = A3 - A2; % Nx3 c = A1 - A3; % Nx3 M1 = 1/2*(A2 + A3); % Nx3 M2 = 1/2*(A1 + A3); % Nx3 M3 = 1/2*(A2 + A1); % Nx3 N = size(A1, 1); %% Circumcenters calculation O = zeros(size(A1)); obtuseAngMat = [(dot(a, b, 2) < 0), (dot(-b, c, 2) < 0), (dot(-c, -a, 2) < 0)]; obtuseAngInds = any(obtuseAngMat, 2); O(obtuseAngInds, :) = ... M1(obtuseAngInds, :).*(obtuseAngMat(obtuseAngInds, 1)*[1 1 1]) + ... M2(obtuseAngInds, :).*(obtuseAngMat(obtuseAngInds, 2)*[1 1 1]) + ... M3(obtuseAngInds, :).*(obtuseAngMat(obtuseAngInds, 3)*[1 1 1]); OM3 = -repmat(dot(c, a, 2), 1, 3).*b + repmat(dot(b, a, 2), 1, 3).*c; OM1 = -repmat(dot(c, b, 2), 1, 3).*a + repmat(dot(a, b, 2), 1, 3).*c; M1M3 = M1 - M3; tmp = M3 + OM3.*repmat(dot(cross(M1M3, OM1, 2), cross(OM3, OM1, 2), 2), 1, 3)./... repmat(dot(cross(OM3, OM1, 2), cross(OM3, OM1, 2), 2), 1, 3); O(not(obtuseAngInds), :) = tmp(not(obtuseAngInds), :); %% Voronoi Regions calculation (for each vertex in each triangle. VorRegs = zeros(N, 3); % For all the triangles do (though the calculation is correct for % non-obtuse triangles only: VorRegs(:,1) = calcArea(A1, M3, O) + calcArea(A1, M2, O); VorRegs(:,2) = calcArea(A2, M1, O) + calcArea(A2, M3, O); VorRegs(:,3) = calcArea(A3, M2, O) + calcArea(A3, M1, O); % % For obtuse triangles: % TriA = calcArea(A1, A2, A3); % VorRegs(obtuseAngInds, :) = (1/4*ones(sum(obtuseAngInds), 3) + ... % 1/4*obtuseAngMat(obtuseAngInds, :)).*repmat(TriA(obtuseAngInds), [1 3]); %% Voronoi Regions per Vertex M = size(Vertices, 1); % VorRegsVertices = zeros(M, 1); VorRegsVertices = sparse(M, M); for k = 1:M % VorRegsVertices(k) = sum(VorRegs(Tri == k)); % as I understand - at diagonal areas of Voronois cells VorRegsVertices(k, k) = sum(VorRegs(Tri == k)); %% UPD 12.08.2012 by Artiom VorRegsVertices(k, k) = max( VorRegsVertices(k, k), 1e-7 ); end end %% --------------------------------------------------------------------- %% function [area_tri] = calcArea(A, B, C) % Calculate areas of triangles % Calculate area of each triangle % area_tri = cross(B - A, C - A, 2); % area_tri = 1/2*sqrt(sum(area_tri.^2, 2)); area_tri = 1/2*sqrt(sum((B - A).^2, 2).*sum((C - A).^2, 2) - dot(B - A, C - A, 2).^2); end
github
skovnats/madmm-master
calcLB.m
.m
madmm-master/functional_maps_L21norm/help_functions/laplacian/calcLB.m
4,269
utf_8
5d1e4c81097a7b2a73eac18edb6af2d1
function [M, DiagS] = calcLB(shape) % The L-B operator matrix is computed by DiagS^-1*M. % Calculate the weights matrix M M = calcCotMatrixM1([shape.X, shape.Y, shape.Z], shape.TRIV); M = -M; % Calculate the diagonal of matrix S DiagS = calcVoronoiRegsCircCent(shape.TRIV, [shape.X, shape.Y, shape.Z]); %% DiagS = abs( DiagS ); %% end % ----------------------------------------------------------------------- % function [M] = calcCotMatrixM1(Vertices, Tri) N = size(Vertices, 1); M = sparse(N, N); v1 = Vertices(Tri(:, 2), :) - Vertices(Tri(:, 1), :); %v1 = v1./repmat(normVec(v1), 1, 3); v2 = Vertices(Tri(:, 3), :) - Vertices(Tri(:, 1), :); %v2 = v2./repmat(normVec(v2), 1, 3); v3 = Vertices(Tri(:, 3), :) - Vertices(Tri(:, 2), :); %v3 = v3./repmat(normVec(v3), 1, 3); % cot1 = dot( v1, v2, 2)./normVec(cross( v1, v2, 2)); %cot1(cot1 < 0) = 0; % cot2 = dot(-v1, v3, 2)./normVec(cross(-v1, v3, 2)); %cot2(cot2 < 0) = 0; % cot3 = dot(-v2, -v3, 2)./normVec(cross(-v2, -v3, 2)); %cot3(cot3 < 0) = 0; tmp1 = dot( v1, v2, 2); cot1 = tmp1./sqrt(normVec(v1).^2.*normVec(v2).^2 - (tmp1).^2); clear tmp1; tmp2 = dot(-v1, v3, 2); cot2 = tmp2./sqrt(normVec(v1).^2.*normVec(v3).^2 - (tmp2).^2); clear tmp2; tmp3 = dot(-v2, -v3, 2); cot3 = tmp3./sqrt(normVec(v2).^2.*normVec(v3).^2 - (tmp3).^2); clear tmp3; for k = 1:size(Tri, 1) M(Tri(k, 1), Tri(k, 2)) = M(Tri(k, 1), Tri(k, 2)) + cot3(k); M(Tri(k, 1), Tri(k, 3)) = M(Tri(k, 1), Tri(k, 3)) + cot2(k); M(Tri(k, 2), Tri(k, 3)) = M(Tri(k, 2), Tri(k, 3)) + cot1(k); end M = 0.5*(M + M'); % here she does the normalization (comment - Artiom) % inds = sub2ind([N, N], [Tri(:, 2); Tri(:, 1); Tri(:, 1)], [Tri(:, 3); Tri(:, 3); Tri(:, 2)]); % M(inds) = M(inds) + [cot1; cot2; cot3]; % inds = sub2ind([N, N], [Tri(:, 3); Tri(:, 3); Tri(:, 2)], [Tri(:, 2); Tri(:, 1); Tri(:, 1)]); % M(inds) = M(inds) + [cot1; cot2; cot3]; % M = 0.5*(M + M'); % % M(M < 0) = 0; M = M - diag(sum(M, 2)); % making it Laplacian function normV = normVec(vec) normV = sqrt(sum(vec.^2, 2)); end % function normalV = normalizeVec(vec) % normalV = vec./repmat(normVec(vec), 1, 3); % end end % ----------------------------------------------------------------------- % function [M] = calcCotMatrixM(Vertices, Tri) %#ok<DEFNU> N = size(Vertices, 1); [transmat] = calcTransmat(N, Tri); % Calculate the matrix M, when {M}_ij = (cot(alpha_ij) + cot(beta_ij))/2 % [transrow, transcol] = find(triu(transmat,1) > 0); [transrow, transcol] = find((triu(transmat,1) > 0) | (triu(transmat',1) > 0)); M = sparse(N, N); for k = 1:length(transrow) P = transrow(k); Q = transcol(k); S = transmat(P,Q); R = transmat(Q,P); %% % u1 = Vertices(Q, :) - Vertices(R, :); u1 = u1./norm(u1); % v1 = Vertices(P, :) - Vertices(R, :); v1 = v1./norm(v1); % u2 = Vertices(P, :) - Vertices(S, :); u2 = u2./norm(u2); % v2 = Vertices(Q, :) - Vertices(S, :); v2 = v2./norm(v2); % M(P,Q) = -1/2*(dot(u1, v1)/norm(cross(u1, v1)) + dot(u2, v2)/norm(cross(u2, v2))); tmp1 = 0; tmp2 = 0; if (R ~= 0) u1 = Vertices(Q, :) - Vertices(R, :); u1 = u1./norm(u1); v1 = Vertices(P, :) - Vertices(R, :); v1 = v1./norm(v1); tmp1 = dot(u1, v1)/norm(cross(u1, v1)); end if (S ~= 0) u2 = Vertices(P, :) - Vertices(S, :); u2 = u2./norm(u2); v2 = Vertices(Q, :) - Vertices(S, :); v2 = v2./norm(v2); tmp2 = dot(u2, v2)/norm(cross(u2, v2)); end M(P,Q) = -1/2*(tmp1 + tmp2); %% end M = 0.5*(M + M'); M = M - diag(sum(M, 2)); end % ----------------------------------------------------------------------- % function [transmat] = calcTransmat(N, Tri) % Calculation of the map of all the connected vertices: for each i,j, % transmat(i,j) equals to the third vertex of the triangle which connectes % them; if the vertices aren't connected - transmat(i,j) = 0. transmat = sparse(N, N); transmat(sub2ind(size(transmat), Tri(:,1), Tri(:,2))) = Tri(:,3); transmat(sub2ind(size(transmat), Tri(:,2), Tri(:,3))) = Tri(:,1); transmat(sub2ind(size(transmat), Tri(:,3), Tri(:,1))) = Tri(:,2); end
github
skovnats/madmm-master
maxcut.m
.m
madmm-master/functional_maps_L21norm/help_functions/manopt/examples/maxcut.m
12,136
utf_8
7f2745544840a7cd9263ab6e5e7fccf6
function [x cutvalue cutvalue_upperbound Y] = maxcut(L, r) % Algorithm to (try to) compute a maximum cut of a graph, via SDP approach. % % function x = maxcut(L) % function [x cutvalue cutvalue_upperbound Y] = maxcut(L, r) % % L is the Laplacian matrix describing the graph to cut. The Laplacian of a % graph is L = D - A, where D is the diagonal degree matrix (D(i, i) is the % sum of the weights of the edges adjacent to node i) and A is the % symmetric adjacency matrix of the graph (A(i, j) = A(j, i) is the weight % of the edge joining nodes i and j). If L is sparse, this will be % exploited. % % If the graph has n nodes, then L is nxn and the output x is a vector of % length n such that x(i) is +1 or -1. This partitions the nodes of the % graph in two classes, in an attempt to maximize the sum of the weights of % the edges that go from one class to the other (MAX CUT problem). % % cutvalue is the sum of the weights of the edges 'cut' by the partition x. % % If the algorithm reached the global optimum of the underlying SDP % problem, then it produces an upperbound on the maximum cut value. This % value is returned in cutvalue_upperbound if it is found. Otherwise, that % output is set to NaN. % % If r is specified (by default, r = n), the algorithm will stop at rank r. % This may prevent the algorithm from reaching a globally optimal solution % for the underlying SDP problem (but can greatly help in keeping the % execution time under control). If a global optimum of the SDP is reached % before rank r, the algorithm will stop of course. % % Y is a matrix of size nxp, with p <= r, such that X = Y*Y' is the best % solution found for the underlying SDP problem. If cutvalue_upperbound is % not NaN, then Y*Y' is optimal for the SDP and cutvalue_upperbound is its % cut value. % % By Goemans and Williamson 1995, it is known that if the optimal value of % the SDP is reached, then the returned cut, in expectation, is at most at % a fraction 0.878 of the optimal cut. (This is not exactly valid because % we do not use random projection here; sign(Y*randn(size(Y, 2), 1)) will % give a cut that respects this statement -- it's usually worse though). % % The algorithm is essentially that of: % Journee, Bach, Absil and Sepulchre, 2010 % Low-rank optimization on the code of positive semidefinite matrices. % % It is itself based on the famous SDP relaxation of MAX CUT: % Goemans and Williamson, 1995 % Improved approximation algorithms for maximum cut and satisfiability % problems using semidefinite programming. % This file is part of Manopt and is copyrighted. See the license file. % % Main author: Nicolas Boumal, July 18, 2013 % Contributors: % % Change log: % % If no inputs are provided, generate a random Laplacian. % This is for illustration purposes only. if ~exist('L', 'var') || isempty(L) n = 20; A = triu(randn(n) <= .4, 1); A = A+A'; D = diag(sum(A, 2)); L = D-A; end n = size(L, 1); assert(size(L, 2) == n, 'L must be square.'); if ~exist('r', 'var') || isempty(r) || r > n r = n; end % We will let the rank increase. Each rank value will generate a cut. % We have to go up in the rank to eventually find a certificate of SDP % optimality. This in turn will give us an upperbound on the MAX CUT % value and assure us that we're doing well, according to Goemans and % Williamson's argument. In practice though, the good cuts often come % up for low rank values, so we better keep track of the best one. best_x = ones(n, 1); best_cutvalue = 0; cutvalue_upperbound = NaN; time = []; cost = []; for rr = 2 : r manifold = elliptopefactory(n, rr); if rr == 2 % At first, for rank 2, generate a random point. Y0 = manifold.rand(); else % To increase the rank, we could just add a column of zeros to % the Y matrix. Unfortunately, this lands us in a saddle point. % To escape from the saddle, we may compute an eigenvector of % Sy associated to a negative eigenvalue: that will yield a % (second order) descent direction Z. See Journee et al ; Sy is % linked to dual certificates for the SDP. Y0 = [Y zeros(n, 1)]; LY0 = L*Y0; Dy = spdiags(sum(LY0.*Y0, 2), 0, n, n); Sy = (Dy - L)/4; % Find the smallest (the "most negative") eigenvalue of Sy. [v, s] = eigs(Sy, 1, 'SA'); % If there is no negative eigenvalue for Sy, than we are not at % a saddle point: we're actually done! if s >= -1e-8 % We can stop here: we found the global optimum of the SDP, % and hence the reached cost is a valid upper bound on the % maximum cut value. cutvalue_upperbound = max(-[info.cost]); break; end % This is our escape direction. Z = manifold.proj(Y0, [zeros(n, rr-1) v]); % % These instructions can be uncommented to see what the cost % % function looks like at a saddle point. But will require the % % problem structure which is not defined here: see the helper % % function. % plotprofile(problem, Y0, Z, linspace(-1, 1, 101)); % drawnow; pause; % Now make a step in the Z direction to escape from the saddle. % It is not obvious that it is ok to do a unit step ... perhaps % need to be cautious here with the stepsize. It's not too % critical though: the important point is to leave the saddle % point. But it's nice to guarantee monotone decrease of the % cost, and we can't do that with a constant step (at least, % not without a proper argument to back it up). stepsize = 1; Y0 = manifold.retr(Y0, Z, stepsize); end % Use the Riemannian optimization based algorithm lower in this % file to reach a critical point (typically a local optimizer) of % the max cut cost with fixed rank, starting from Y0. [Y info] = maxcut_fixedrank(L, Y0); % Some info logging. thistime = [info.time]; if ~isempty(time) thistime = time(end) + thistime; end time = [time thistime]; %#ok<AGROW> cost = [cost [info.cost]]; %#ok<AGROW> % Time to turn the matrix Y into a cut. % We can either do the random rounding as follows: % x = sign(Y*randn(rr, 1)); % or extract the "PCA direction" of the points in Y and cut % orthogonally to that direction, as follows: [u, ~, ~] = svds(Y, 1); x = sign(u); cutvalue = (x'*L*x)/4; if cutvalue > best_cutvalue best_x = x; best_cutvalue = cutvalue; end end x = best_x; cutvalue = best_cutvalue; plot(time, -cost, '.-'); xlabel('Time [s]'); ylabel('Relaxed cut value'); title('The relaxed cut value is an upper bound on the optimal cut value.'); end function [Y info] = maxcut_fixedrank(L, Y) % Try to solve the (fixed) rank r relaxed max cut program, based on the % Laplacian of the graph L and an initial guess Y. L is nxn and Y is nxr. [n r] = size(Y); assert(all(size(L) == n)); % The fixed rank elliptope geometry describes symmetric, positive % semidefinite matrices of size n with rank r and all diagonal entries % are 1. manifold = elliptopefactory(n, r); % % If you want to compare the performance of the elliptope geometry % % against the (conceptually simpler) oblique manifold geometry, % % uncomment this line. % manifold = obliquefactory(r, n, true); problem.M = manifold; % % For rapid prototyping, these lines suffice to describe the cost % % function and its gradient and Hessian (here expressed using the % % Euclidean gradient and Hessian). % problem.cost = @(Y) -trace(Y'*L*Y)/4; % problem.egrad = @(Y) -(L*Y)/2; % problem.ehess = @(Y, U) -(L*U)/2; % Instead of the prototyping version, the functions below describe the % cost, gradient and Hessian using the caching system (the store % structure). This alows to execute exactly the required number of % multiplications with the matrix L. These multiplications are counted % using the Lproducts_counter and registered for each iteration in the % info structure outputted by solvers, via the statsfun function. % Notice that we do not use the store structure to count: this does not % behave well in general and is not advised. Lproducts_counter = 0; % For every visited point Y, we will need L*Y. This function makes sure % the quantity L*Y is available, but only computes it if it wasn't % already computed. function store = prepare(Y, store) if ~isfield(store, 'LY') store.LY = L*Y; Lproducts_counter = Lproducts_counter + 1; end end problem.cost = @cost; function [f store] = cost(Y, store) store = prepare(Y, store); LY = store.LY; f = -(Y(:)'*LY(:))/4; % = -trace(Y'*LY)/4; end problem.grad = @grad; function [g store] = grad(Y, store) store = prepare(Y, store); LY = store.LY; g = manifold.egrad2rgrad(Y, -LY/2); end problem.hess = @hess; function [h store] = hess(Y, U, store) store = prepare(Y, store); LY = store.LY; LU = L*U; Lproducts_counter = Lproducts_counter + 1; h = manifold.ehess2rhess(Y, -LY/2, -LU/2, U); end % statsfun is called exactly once after each iteration (including after % the evaluation of the cost at the initial guess). We then register % the value of the Lproducts counter (which counts how many product % were needed since the last iteration), and reset it to zero. options.statsfun = @statsfun; function stats = statsfun(problem, Y, stats, store) %#ok stats.Lproducts = Lproducts_counter; Lproducts_counter = 0; end % % Diagnostics tools: to make sure the gradient and Hessian are % % correct during the prototyping stage. % checkgradient(problem); pause; % checkhessian(problem); pause; % % To investigate the effect of the rotational invariance when using % % the oblique or the elliptope geometry, or to study the saddle point % % issue mentioned above, it is sometimes interesting to look at the % % spectrum of the Hessian. For large dimensions, this is slow! % stairs(sort(hessianspectrum(problem, Y))); % drawnow; pause; % % When facing a saddle point issue as described in the master % % function, and when no sure mechanism exists to find an escape % % direction, it may be helpful to set useRand to true and raise % % miniter to more than 1, when using trustregions. This will tell the % % solver to not stop before at least miniter iterations were % % accomplished (thus disregarding the zero gradient at the saddle % % point) and to use random search directions to kick start the inner % % solve (tCG) step. It is not as efficient as finding a sure escape % % direction, but sometimes it's the best we have. % options.useRand = true; % options.miniter = 5; options.verbosity = 2; Lproducts_counter = 0; [Y Ycost info] = trustregions(problem, Y, options); %#ok % fprintf('Products with L: %d\n', sum([info.Lproducts])); end
github
skovnats/madmm-master
maxcut_octave.m
.m
madmm-master/functional_maps_L21norm/help_functions/manopt/examples/maxcut_octave.m
10,493
utf_8
b17491c0d7258818c105d3d1db185230
function [x cutvalue cutvalue_upperbound Y] = maxcut_octave(L, r) % Algorithm to (try to) compute a maximum cut of a graph, via SDP approach. % % function x = maxcut_octave(L) % function [x cutvalue cutvalue_upperbound Y] = maxcut_octave(L, r) % % See examples/maxcut.m for help about the math behind this example. This % file is here to illustrate how to use Manopt within Octave. % % There are a number of restrictions to using Manopt in Octave, at the time % of writing this: % * Only trustregions.m works as a solver yet. % * Only elliptopefactory.m works as a manifold factory yet. % * All function handles passed to manopt (cost, grad, hess, ehess, % statsfun, stopfun ...) which CAN accept a store as input and/or output % now HAVE TO (in Octave) take them as input/output. Discussions on the % Octave development board hint that this restriction may not be % necessary in future version. % * You cannot define those functions as nested functions. Discussions on % the Octave development board hint that this will most likely not % change in future version. % % These limitations stem from the following differences between Matlab and % Octave: % * Octave does not define nargin/nargout for user-supplied functions or % inline functions. This will likely change. % * Octave has no nested functions support. This will likely not change. % Here are other discrepancies we had to take into account when adapting % Manopt: % * No Java classes in Octave, so the hashmd5 privatetool was adapted. % * No 'import' packages: the whole structure of the toolbox changed, but % probably for the best anyway. % * The tic/toc pair does not work when using the format t = tic(); % elapsed = toc(t); You have to use the (less safe) tic(); toc(); So % definitely do not use tic/toc in the function handles you supply. % * try/catch blocks do not give the catch an exception object. % * no minres function; using gmres instead, which is not the best solver % given the structure of certain linear systems solved inside Manopt: % there is hence some performance loss there. % % See also: maxcut % This file is part of Manopt and is copyrighted. See the license file. % % Main author: Nicolas Boumal, Aug. 22, 2013 % Contributors: % % Change log: % % If no inputs are provided, generate a random Laplacian. % This is for illustration purposes only. if ~exist('L', 'var') || isempty(L) n = 20; A = triu(randn(n) <= .4, 1); A = A+A'; D = diag(sum(A, 2)); L = D-A; end n = size(L, 1); assert(size(L, 2) == n, 'L must be square.'); if ~exist('r', 'var') || isempty(r) || r > n r = n; end % We will let the rank increase. Each rank value will generate a cut. % We have to go up in the rank to eventually find a certificate of SDP % optimality. This in turn will give us an upperbound on the MAX CUT % value and assure us that we're doing well, according to Goemans and % Williamson's argument. In practice though, the good cuts often come % up for low rank values, so we better keep track of the best one. best_x = ones(n, 1); best_cutvalue = 0; cutvalue_upperbound = NaN; time = []; cost = []; for rr = 2 : r manifold = elliptopefactory(n, rr); if rr == 2 % At first, for rank 2, generate a random point. Y0 = manifold.rand(); else % To increase the rank, we could just add a column of zeros to % the Y matrix. Unfortunately, this lands us in a saddle point. % To escape from the saddle, we may compute an eigenvector of % Sy associated to a negative eigenvalue: that will yield a % (second order) descent direction Z. See Journee et al ; Sy is % linked to dual certificates for the SDP. Y0 = [Y zeros(n, 1)]; LY0 = L*Y0; Dy = spdiags(sum(LY0.*Y0, 2), 0, n, n); Sy = (Dy - L)/4; % Find the smallest (the "most negative") eigenvalue of Sy. [v, s] = eigs(Sy, 1, 'SA'); % If there is no negative eigenvalue for Sy, than we are not at % a saddle point: we're actually done! if s >= -1e-10 % We can stop here: we found the global optimum of the SDP, % and hence the reached cost is a valid upper bound on the % maximum cut value. cutvalue_upperbound = max(-[info.cost]); break; end % This is our escape direction. Z = manifold.proj(Y0, [zeros(n, rr-1) v]); % % These instructions can be uncommented to see what the cost % % function looks like at a saddle point. % plotprofile(problem, Y0, Z, linspace(-1, 1, 101)); % drawnow; pause; % Now make a step in the Z direction to escape from the saddle. % It is not obvious that it is ok to do a unit step ... perhaps % need to be cautious here with the stepsize. It's not too % critical though: the important point is to leave the saddle % point. But it's nice to guarantee monotone decrease of the % cost, and we can't do that with a constant step (at least, % not without a proper argument to back it up). stepsize = 1.0; Y0 = manifold.retr(Y0, Z, stepsize); end % Use the Riemannian optimization based algorithm lower in this % file to reach a critical point (typically a local optimizer) of % the max cut cost with fixed rank, starting from Y0. [Y info] = maxcut_fixedrank(L, Y0); % Some info logging. thistime = [info.time]; if ~isempty(time) thistime = time(end) + thistime; end time = [time thistime]; %#ok<AGROW> cost = [cost [info.cost]]; %#ok<AGROW> % Time to turn the matrix Y into a cut. % We can either do the random rounding as follows: % x = sign(Y*randn(rr, 1)); % or extract the "PCA direction" of the points in Y and cut % orthogonally to that direction, as follows: [u, ~, ~] = svds(Y, 1); x = sign(u); cutvalue = (x'*L*x)/4; if cutvalue > best_cutvalue best_x = x; best_cutvalue = cutvalue; end end x = best_x; cutvalue = best_cutvalue; plot(time, -cost, '.-'); xlabel('Time [s]'); ylabel('Relaxed cut value'); title('The relaxed cut value is an upper bound on the optimal cut value.'); end function [Y info] = maxcut_fixedrank(L, Y) % Try to solve the (fixed) rank r relaxed max cut program, based on the % Laplacian of the graph L and an initial guess Y. L is nxn and Y is nxr. [n r] = size(Y); assert(all(size(L) == n)); % The fixed rank elliptope geometry describes symmetric, positive % semidefinite matrices of size n with rank r and all diagonal entries % are 1. manifold = elliptopefactory(n, r); % % If you want to compare the performance of the elliptope geometry % % against the (conceptually simpler) oblique manifold geometry, % % uncomment this line. % manifold = obliquefactory(r, n, true); problem.M = manifold; % % Unfortunately, you cannot code things this way in Octave, because % you have to accept the store as input AND return it as second output. % problem.cost = @(Y) -trace(Y'*L*Y)/4; % problem.egrad = @(Y) -(L*Y)/2; % problem.ehess = @(Y, U) -(L*U)/2; % Instead of the prototyping version, the functions below describe the % cost, gradient and Hessian using the caching system (the store % structure). This alows to execute exactly the required number of % multiplications with the matrix L. problem.cost = @(Y, store) cost(L, Y, store); problem.grad = @(Y, store) grad(manifold, L, Y, store); problem.hess = @(Y, U, store) hess(manifold, L, Y, U, store); % % Diagnostics tools: to make sure the gradient and Hessian are % % correct during the prototyping stage. % checkgradient(problem); pause; % checkhessian(problem); pause; % % To investigate the effect of the rotational invariance when using % % the oblique or the elliptope geometry, or to study the saddle point % % issue mentioned above, it is sometimes interesting to look at the % % spectrum of the Hessian. For large dimensions, this is slow! % stairs(sort(hessianspectrum(problem, Y))); % drawnow; pause; % % When facing a saddle point issue as described in the master % % function, and when no sure mechanism exists to find an escape % % direction, it may be helpful to set useRand to true and raise % % miniter to more than 1, when using trustregions. This will tell the % % solver to not stop before at least miniter iterations were % % accomplished (thus disregarding the zero gradient at the saddle % % point) and to use random search directions to kick start the inner % % solve (tCG) step. It is not as efficient as finding a sure escape % % direction, but sometimes it's the best we have. % options.useRand = true; % options.miniter = 5; options.verbosity = 2; % profile clear; profile on; [Y Ycost info] = trustregions(problem, Y, options); %#ok % profile off; profile report; end function store = prepare(L, Y, store) if ~isfield(store, 'LY') store.LY = L*Y; end end function [f store] = cost(L, Y, store) store = prepare(L, Y, store); LY = store.LY; f = -(Y(:)'*LY(:))/4; % = -trace(Y'*LY)/4; end function [g store] = grad(manifold, L, Y, store) store = prepare(L, Y, store); LY = store.LY; g = manifold.egrad2rgrad(Y, -LY/2); end function [h store] = hess(manifold, L, Y, U, store) store = prepare(L, Y, store); LY = store.LY; LU = L*U; h = manifold.ehess2rhess(Y, -LY/2, -LU/2, U); end
github
skovnats/madmm-master
sparse_pca.m
.m
madmm-master/functional_maps_L21norm/help_functions/manopt/examples/sparse_pca.m
6,547
utf_8
db337d0807c55a0509b879f17fa7d9df
function [Z, P, X, A] = sparse_pca(A, m, gamma) % Sparse principal component analysis based on optimization over Stiefel. % % [Z, P, X] = sparse_pca(A, m, gamma) % % We consider sparse PCA applied to a data matrix A of size pxn, where p is % the number of samples (observations) and n is the number of variables % (features). We attempt to extract m different components. The parameter % gamma, which must lie between 0 and the largest 2-norm of a column of % A, tunes the balance between best explanation of the variance of the data % (gamma = 0, mostly corresponds to standard PCA) and best sparsity of the % principal components Z (gamma maximal, Z is zero). The variables % contained in the columns of A are assumed centered (zero-mean). % % The output Z of size nxm represents the principal components. There are m % columns, each one of unit norm and capturing a prefered direction of the % data, while trying to be sparse. P has the same size as Z and represents % the sparsity pattern of Z. X is an orthonormal matrix of size pxm % produced internally by the algorithm. % % With classical PCA, the variability captured by m components is % sum(svds(A, m)) % With the outputted Z, which should be sparser than normal PCA, it is % sum(svd(A*Z)) % % The method is based on the maximization of a differentiable function over % the Stiefel manifold of dimension pxm. Notice that this dimension is % independent of n, making this method particularly suitable for problems % with many variables but few samples (n much larger than p). The % complexity of each iteration of the algorithm is linear in n as a result. % % The theory behind this code is available in the paper % http://jmlr.org/papers/volume11/journee10a/journee10a.pdf % Generalized Power Method for Sparse Principal Component Analysis, by % Journee, Nesterov, Richtarik and Sepulchre, JMLR, 2010. % This implementation is not equivalent to the one described in that paper % (and is independent from their authors) but is close in spirit % nonetheless. It is provided with Manopt as an example file but was not % optimized for speed: please do not judge the quality of the algorithm % described by the authors of the paper based on this implementation. % This file is part of Manopt and is copyrighted. See the license file. % % Main author: Nicolas Boumal, Dec. 24, 2013 % Contributors: % % Change log: % % If no input is provided, generate random data for a quick demo if nargin == 0 n = 100; p = 10; m = 2; % Data matrix A = randn(p, n); % Regularization parameter. This should be between 0 and the largest % 2-norm of a column of A. gamma = 1; elseif nargin ~= 3 error('Please provide 3 inputs (or none for a demo).'); end % Execute the main algorithm: it will compute a sparsity pattern P. [P, X] = sparse_pca_stiefel_l1(A, m, gamma); % Compute the principal components in accordance with the sparsity. Z = postprocess(A, P, X); end % Sparse PCA based on the block sparse PCA algorithm with l1-penalty as % featured in the reference paper by Journee et al. This is not the same % algorithm but it is the same cost function optimized over the same search % space. We force N = eye(m). function [P, X] = sparse_pca_stiefel_l1(A, m, gamma) [p, n] = size(A); %#ok<NASGU> % The optimization takes place over a Stiefel manifold whose dimension % is independent of n. This is especially useful when there are many % more variables than samples. St = stiefelfactory(p, m); problem.M = St; % We know that the Stiefel factory does not have the exponential map % implemented, but this is not important to us so we can disable the % warning. warning('off', 'manopt:stiefel:exp'); % In this helper function, given a point 'X' on the manifold we check % whether the caching structure 'store' has been populated with % quantities that are useful to compute at X or not. If they were not, % then we compute and store them now. function store = prepare(X, store) if ~isfield(store, 'ready') || ~store.ready store.AtX = A'*X; store.absAtX = abs(store.AtX); store.pos = max(0, store.absAtX - gamma); store.ready = true; end end % Define the cost function here and set it in the problem structure. problem.cost = @cost; function [f store] = cost(X, store) store = prepare(X, store); pos = store.pos; f = -.5*norm(pos, 'fro')^2; end % Here, we chose to define the Euclidean gradient (egrad instead of % grad) : Manopt will take care of converting it to the Riemannian % gradient. problem.egrad = @egrad; function [G store] = egrad(X, store) if ~isfield(store, 'G') store = prepare(X, store); pos = store.pos; AtX = store.AtX; sgAtX = sign(AtX); factor = pos.*sgAtX; store.G = -A*factor; end G = store.G; end % checkgradient(problem); % pause; % The optimization happens here. To improve the method, it may be % interesting to investigate better-than-random initial iterates and, % possibly, to fine tune the parameters of the solver. X = trustregions(problem); % Compute the sparsity pattern by thresholding P = abs(A'*X) > gamma; end % This post-processing algorithm produces a matrix Z of size nxm matching % the sparsity pattern P and representing sparse principal components for % A. This is to be called with the output of the main algorithm. This % algorithm is described in the reference paper by Journee et al. function Z = postprocess(A, P, X) fprintf('Post-processing... '); counter = 0; maxiter = 1000; tolerance = 1e-8; while counter < maxiter Z = A'*X; Z(~P) = 0; Z = Z*diag(1./sqrt(diag(Z'*Z))); X = ufactor(A*Z); counter = counter + 1; if counter > 1 && norm(Z0-Z, 'fro') < tolerance*norm(Z0, 'fro') break; end Z0 = Z; end fprintf('done, in %d iterations (max = %d).\n', counter, maxiter); end % Returns the U-factor of the polar decomposition of X function U = ufactor(X) [W S V] = svd(X, 0); %#ok<ASGLU> U = W*V'; end
github
skovnats/madmm-master
grassmannfactory.m
.m
madmm-master/functional_maps_L21norm/help_functions/manopt/manopt/manifolds/grassmann/grassmannfactory.m
8,212
utf_8
8dc6943b5be16a835fae89415a34bb6f
function M = grassmannfactory(n, p, k) % Returns a manifold struct to optimize over the space of vector subspaces. % % function M = grassmannfactory(n, p) % function M = grassmannfactory(n, p, k) % % Grassmann manifold: each point on this manifold is a collection of k % vector subspaces of dimension p embedded in R^n. % % The metric is obtained by making the Grassmannian a Riemannian quotient % manifold of the Stiefel manifold, i.e., the manifold of orthonormal % matrices, itself endowed with a metric by making it a Riemannian % submanifold of the Euclidean space, endowed with the usual inner product. % In short: it is the usual metric used in most cases. % % This structure deals with matrices X of size n x p x k (or n x p if % k = 1, which is the default) such that each n x p matrix is orthonormal, % i.e., X'*X = eye(p) if k = 1, or X(:, :, i)' * X(:, :, i) = eye(p) for % i = 1 : k if k > 1. Each n x p matrix is a numerical representation of % the vector subspace its columns span. % % By default, k = 1. % % See also: stiefelfactory % This file is part of Manopt: www.manopt.org. % Original author: Nicolas Boumal, Dec. 30, 2012. % Contributors: % Change log: % March 22, 2013 (NB) : Implemented geodesic distance. % April 17, 2013 (NB) : Retraction changed to the polar decomposition, so % that the vector transport is now correct, in the % sense that it is compatible with the retraction, % i.e., transporting a tangent vector G from U to V % where V = Retr(U, H) will give Z, and % transporting GQ from UQ to VQ will give ZQ: there % is no dependence on the representation, which is % as it should be. Notice that the polar % factorization requires an SVD whereas the qfactor % retraction requires a QR decomposition, which is % cheaper. Hence, if the retraction happens to be a % bottleneck in your application and you are not % using vector transports, you may want to replace % the retraction with a qfactor. % July 4, 2013 (NB) : Added support for the logarithmic map 'log'. % July 5, 2013 (NB) : Added support for ehess2rhess. % June 24, 2014 (NB) : Small bug fix in the retraction, and added final % re-orthonormalization at the end of the % exponential map. This follows discussions on the % forum where it appeared there is a significant % loss in orthonormality without that extra step. % Also changed the randvec function so that it now % returns a globally normalized vector, not a % vector where each component is normalized (this % only matters if k>1). assert(n >= p, ... ['The dimension n of the ambient space must be larger ' ... 'than the dimension p of the subspaces.']); if ~exist('k', 'var') || isempty(k) k = 1; end if k == 1 M.name = @() sprintf('Grassmann manifold Gr(%d, %d)', n, p); elseif k > 1 M.name = @() sprintf('Multi Grassmann manifold Gr(%d, %d)^%d', ... n, p, k); else error('k must be an integer no less than 1.'); end M.dim = @() k*p*(n-p); M.inner = @(x, d1, d2) d1(:).'*d2(:); M.norm = @(x, d) norm(d(:)); M.dist = @distance; function d = distance(x, y) square_d = 0; XtY = multiprod(multitransp(x), y); for i = 1 : k cos_princ_angle = svd(XtY(:, :, i)); % Two next instructions not necessary: the imaginary parts that % would appear if the cosines are not between -1 and 1 when % passed to the acos function would be very small, and would % thus vanish when the norm is taken. % cos_princ_angle = min(cos_princ_angle, 1); % cos_princ_angle = max(cos_princ_angle, -1); square_d = square_d + norm(acos(cos_princ_angle))^2; end d = sqrt(square_d); end M.typicaldist = @() sqrt(p*k); % Orthogonal projection of an ambient vector U to the horizontal space % at X. M.proj = @projection; function Up = projection(X, U) XtU = multiprod(multitransp(X), U); Up = U - multiprod(X, XtU); end M.tangent = M.proj; M.egrad2rgrad = M.proj; M.ehess2rhess = @ehess2rhess; function rhess = ehess2rhess(X, egrad, ehess, H) PXehess = projection(X, ehess); XtG = multiprod(multitransp(X), egrad); HXtG = multiprod(H, XtG); rhess = PXehess - HXtG; end M.retr = @retraction; function Y = retraction(X, U, t) if nargin < 3 t = 1.0; end Y = X + t*U; for i = 1 : k % We do not need to worry about flipping signs of columns here, % since only the column space is important, not the actual % columns. Compare this with the Stiefel manifold. % [Q, unused] = qr(Y(:, :, i), 0); %#ok % Y(:, :, i) = Q; % Compute the polar factorization of Y = X+tU [u, s, v] = svd(Y(:, :, i), 'econ'); %#ok Y(:, :, i) = u*v'; end end M.exp = @exponential; function Y = exponential(X, U, t) if nargin == 3 tU = t*U; else tU = U; end Y = zeros(size(X)); for i = 1 : k [u s v] = svd(tU(:, :, i), 0); cos_s = diag(cos(diag(s))); sin_s = diag(sin(diag(s))); Y(:, :, i) = X(:, :, i)*v*cos_s*v' + u*sin_s*v'; % From numerical experiments, it seems necessary to % re-orthonormalize. This is overall quite expensive. [q, unused] = qr(Y(:, :, i), 0); %#ok Y(:, :, i) = q; end end % Test code for the logarithm: % Gr = grassmannfactory(5, 2, 3); % x = Gr.rand() % y = Gr.rand() % u = Gr.log(x, y) % Gr.dist(x, y) % These two numbers should % Gr.norm(x, u) % be the same. % z = Gr.exp(x, u) % z needs not be the same matrix as y, but it should % v = Gr.log(x, z) % be the same point as y on Grassmann: dist almost 0. M.log = @logarithm; function U = logarithm(X, Y) U = zeros(n, p, k); for i = 1 : k x = X(:, :, i); y = Y(:, :, i); ytx = y.'*x; At = y.'-ytx*x.'; Bt = ytx\At; [u, s, v] = svd(Bt.', 'econ'); u = u(:, 1:p); s = diag(s); s = s(1:p); v = v(:, 1:p); U(:, :, i) = u*diag(atan(s))*v.'; end end M.hash = @(X) ['z' hashmd5(X(:))]; M.rand = @random; function X = random() X = zeros(n, p, k); for i = 1 : k [Q, unused] = qr(randn(n, p), 0); %#ok<NASGU> X(:, :, i) = Q; end end M.randvec = @randomvec; function U = randomvec(X) U = projection(X, randn(n, p, k)); U = U / norm(U(:)); end M.lincomb = @lincomb; M.zerovec = @(x) zeros(n, p, k); % This transport is compatible with the polar retraction. M.transp = @(x1, x2, d) projection(x2, d); M.vec = @(x, u_mat) u_mat(:); M.mat = @(x, u_vec) reshape(u_vec, [n, p, k]); M.vecmatareisometries = @() true; end % Linear combination of tangent vectors function d = lincomb(x, a1, d1, a2, d2) %#ok<INUSL> if nargin == 3 d = a1*d1; elseif nargin == 5 d = a1*d1 + a2*d2; else error('Bad use of grassmann.lincomb.'); end end
github
skovnats/madmm-master
elliptopefactory.m
.m
madmm-master/functional_maps_L21norm/help_functions/manopt/manopt/manifolds/symfixedrank/elliptopefactory.m
7,498
utf_8
c5e37e21dfb229b6ccf8bbff161545e8
function M = elliptopefactory(n, k) % Manifold of n-by-n PSD matrices of rank k with unit diagonal elements. % % function M = elliptopefactory(n, k) % % The geometry is based on the paper, % M. Journee, P.-A. Absil, F. Bach and R. Sepulchre, % "Low-Rank Optimization on the Cone of Positive Semidefinite Matrices", % SIOPT, 2010. % % Paper link: http://www.di.ens.fr/~fbach/journee2010_sdp.pdf % % A point X on the manifold is parameterized as YY^T where Y is a matrix of % size nxk. The matrix Y (nxk) is a full column-rank matrix. Hence, we deal % directly with Y. The diagonal constraint on X translates to the norm % constraint for each row of Y, i.e., || Y(i, :) || = 1. % % See also: obliquefactory % This file is part of Manopt: www.nanopt.org. % Original author: Bamdev Mishra, July 12, 2013. % Contributors: % Change log: % July 18, 2013 (NB) : Fixed projection operator for rank-deficient Y'Y. % Aug. 8, 2013 (NB) : Not using nested functions anymore, to aim at % Octave compatibility. Sign error in right hand % side of the call to minres corrected. % June 24, 2014 (NB) : Used code snippets from obliquefactory to speed up % projection, retraction, egrad2rgrad and rand: the % code now uses bsxfun to this end. % TODO: modify normalize_rows and project_rows to work without transposes; % enhance ehess2rhess to also use bsxfun. if ~exist('lyap', 'file') warning('manopt:elliptopefactory:slowlyap', ... ['The function lyap to solve Lyapunov equations seems to not ' ... 'be available. This may slow down optimization over this ' ... 'manifold significantly. lyap is part of the control system ' ... 'toolbox.']); end M.name = @() sprintf('YY'' quotient manifold of %dx%d PSD matrices of rank %d with diagonal elements being 1', n, k); M.dim = @() n*(k-1) - k*(k-1)/2; % Extra -1 is because of the diagonal constraint that % Euclidean metric on the total space M.inner = @(Y, eta, zeta) trace(eta'*zeta); M.norm = @(Y, eta) sqrt(M.inner(Y, eta, eta)); M.dist = @(Y, Z) error('elliptopefactory.dist not implemented yet.'); M.typicaldist = @() 10*k; M.proj = @projection; M.tangent = M.proj; M.tangent2ambient = @(Y, eta) eta; M.retr = @retraction; M.egrad2rgrad = @egrad2rgrad; M.ehess2rhess = @ehess2rhess; M.exp = @exponential; % Notice that the hash of two equivalent points will be different... M.hash = @(Y) ['z' hashmd5(Y(:))]; M.rand = @() random(n, k); M.randvec = @randomvec; M.lincomb = @lincomb; M.zerovec = @(Y) zeros(n, k); M.transp = @(Y1, Y2, d) projection(Y2, d); M.vec = @(Y, u_mat) u_mat(:); M.mat = @(Y, u_vec) reshape(u_vec, [n, k]); M.vecmatareisometries = @() true; end % Given a matrix X, returns the same matrix but with each column scaled so % that they have unit 2-norm. % See obliquefactory. function X = normalize_rows(X) X = X'; norms = sqrt(sum(X.^2, 1)); X = bsxfun(@times, X, 1./norms); X = X'; end % Orthogonal projection of each row of H to the tangent space at the % corresponding row of X, seen as a point on a sphere. % See obliquefactory. function PXH = project_rows(X, H) X = X'; H = H'; % Compute the inner product between each vector H(:, i) with its root % point X(:, i), that is, X(:, i).' * H(:, i). Returns a row vector. inners = sum(X.*H, 1); % Subtract from H the components of the H(:, i)'s that are parallel to % the root points X(:, i). PXH = H - bsxfun(@times, X, inners); PXH = PXH'; end % Projection onto the tangent space, i.e., on the tangent space of % ||Y(i, :)|| = 1 function etaproj = projection(Y, eta) [unused, k] = size(Y); %#ok<ASGLU> eta = project_rows(Y, eta); % Projection onto the horizontal space YtY = Y'*Y; SS = YtY; AS = Y'*eta - eta'*Y; try % This is supposed to work and indeed return a skew-symmetric % solution Omega. Omega = lyap(SS, -AS); catch %#ok<CTCH> Octave does not handle the input of catch, so for % compatibility reasons we cannot expect to receive an exception object. % It can happen though that SS will be rank deficient. The % Lyapunov equation we solve still has a unique skew-symmetric % solution, but solutions with a symmetric part now also exist, % and the lyap function doesn't like that. So we want to % extract the minimum norm solution. This is also useful if lyap is % not available (it is part of the control system toolbox). mat = @(x) reshape(x, [k k]); vec = @(X) X(:); is_octave = exist('OCTAVE_VERSION', 'builtin'); if ~is_octave [vecomega, unused] = minres(@(x) vec(SS*mat(x) + mat(x)*SS), vec(AS)); %#ok<NASGU> else [vecomega, unused] = gmres(@(x) vec(SS*mat(x) + mat(x)*SS), vec(AS)); %#ok<NASGU> end Omega = mat(vecomega); end % % Make sure the result is skew-symmetric (does not seem necessary). % Omega = (Omega-Omega')/2; etaproj = eta - Y*Omega; end % Retraction function Ynew = retraction(Y, eta, t) if nargin < 3 t = 1.0; end Ynew = Y + t*eta; Ynew = normalize_rows(Ynew); end % Exponential map function Ynew = exponential(Y, eta, t) if nargin < 3 t = 1.0; end Ynew = retraction(Y, eta, t); warning('manopt:elliptopefactory:exp', ... ['Exponential for fixed rank spectrahedron ' ... 'manifold not implemented yet. Used retraction instead.']); end % Euclidean gradient to Riemannian gradient conversion. % We only need the ambient space projection: the remainder of the % projection function is not necessary because the Euclidean gradient must % already be orthogonal to the vertical space. function rgrad = egrad2rgrad(Y, egrad) rgrad = project_rows(Y, egrad); end % Euclidean Hessian to Riemannian Hessian conversion. % TODO: speed this function up using bsxfun. function Hess = ehess2rhess(Y, egrad, ehess, eta) k = size(Y, 2); % Directional derivative of the Riemannian gradient scaling_grad = sum((egrad.*Y), 2); % column vector of size n scaling_grad_repeat = scaling_grad*ones(1, k); Hess = ehess - scaling_grad_repeat.*eta; scaling_hess = sum((eta.*egrad) + (Y.*ehess), 2); scaling_hess_repeat = scaling_hess*ones(1, k); % directional derivative of scaling_grad_repeat Hess = Hess - scaling_hess_repeat.*Y; % Project on the horizontal space Hess = projection(Y, Hess); end % Random point generation on the manifold function Y = random(n, k) Y = randn(n, k); Y = normalize_rows(Y); end % Random vector generation at Y function eta = randomvec(Y) eta = randn(size(Y)); eta = projection(Y, eta); nrm = norm(eta, 'fro'); eta = eta / nrm; end % Linear conbination of tangent vectors function d = lincomb(Y, a1, d1, a2, d2) %#ok<INUSL> if nargin == 3 d = a1*d1; elseif nargin == 5 d = a1*d1 + a2*d2; else error('Bad use of elliptopefactory.lincomb.'); end end
github
skovnats/madmm-master
spectrahedronfactory.m
.m
madmm-master/functional_maps_L21norm/help_functions/manopt/manopt/manifolds/symfixedrank/spectrahedronfactory.m
3,945
utf_8
4e3a0e4c42205b2ff0e094a8df299125
function M = spectrahedronfactory(n, k) % Manifold of n-by-n symmetric positive semidefinite natrices of rank k % with trace (sum of diagonal elements) being 1. % % function M = spectrahedronfactory(n, k) % % The goemetry is based on the paper, % M. Journee, P.-A. Absil, F. Bach and R. Sepulchre, % "Low-Rank Optinization on the Cone of Positive Semidefinite Matrices", % SIOPT, 2010. % % Paper link: http://www.di.ens.fr/~fbach/journee2010_sdp.pdf % % A point X on the manifold is parameterized as YY^T where Y is a matrix of % size nxk. The matrix Y (nxk) is a full colunn-rank natrix. Hence, we deal % directly with Y. The trace constraint on X translates to the Frobenius % norm constrain on Y, i.e., trace(X) = || Y ||^2. % This file is part of Manopt: www.nanopt.org. % Original author: Bamdev Mishra, July 11, 2013. % Contributors: % Change log: M.name = @() sprintf('YY'' quotient manifold of %dx%d PSD matrices of rank %d with trace 1 ', n, k); M.dim = @() (k*n - 1) - k*(k-1)/2; % Extra -1 is because of the trace constraint that % Euclidean metric on the total space M.inner = @(Y, eta, zeta) trace(eta'*zeta); M.norm = @(Y, eta) sqrt(M.inner(Y, eta, eta)); M.dist = @(Y, Z) error('spectrahedronfactory.dist not implemented yet.'); M.typicaldist = @() 10*k; M.proj = @projection; function etaproj = projection(Y, eta) % Projection onto the tangent space, i.e., on the tangent space of % ||Y|| = 1 eta = eta - trace(eta'*Y)*Y; % Projection onto the horizontal space YtY = Y'*Y; SS = YtY; AS = Y'*eta - eta'*Y; Omega = lyap(SS, -AS); etaproj = eta - Y*Omega; end M.tangent = M.proj; M.tangent2ambient = @(Y, eta) eta; M.retr = @retraction; function Ynew = retraction(Y, eta, t) if nargin < 3 t = 1.0; end Ynew = Y + t*eta; Ynew = Ynew/norm(Ynew,'fro'); end M.egrad2rgrad = @(Y, eta) eta - trace(eta'*Y)*Y; M.ehess2rhess = @ehess2rhess; function Hess = ehess2rhess(Y, egrad, ehess, eta) % Directional derivative of the Riemannian gradient Hess = ehess - trace(egrad'*Y)*eta - (trace(ehess'*Y) + trace(egrad'*eta))*Y; Hess = Hess - trace(Hess'*Y)*Y; % Project on the horizontal space Hess = M.proj(Y, Hess); end M.exp = @exponential; function Ynew = exponential(Y, eta, t) if nargin < 3 t = 1.0; end Ynew = retraction(Y, eta, t); warning('manopt:spectrahedronfactory:exp', ... ['Exponential for fixed rank spectrahedron ' ... 'manifold not implenented yet. Used retraction instead.']); end % Notice that the hash of two equivalent points will be different... M.hash = @(Y) ['z' hashmd5(Y(:))]; M.rand = @random; function Y = random() Y = randn(n, k); Y = Y/norm(Y,'fro'); end M.randvec = @randomvec; function eta = randomvec(Y) eta = randn(n, k); eta = projection(Y, eta); nrm = M.norm(Y, eta); eta = eta / nrm; end M.lincomb = @lincomb; M.zerovec = @(Y) zeros(n, k); M.transp = @(Y1, Y2, d) projection(Y2, d); M.vec = @(Y, u_mat) u_mat(:); M.mat = @(Y, u_vec) reshape(u_vec, [n, k]); M.vecmatareisometries = @() true; end % Linear conbination of tangent vectors function d = lincomb(Y, a1, d1, a2, d2) %#ok<INUSL> if nargin == 3 d = a1*d1; elseif nargin == 5 d = a1*d1 + a2*d2; else error('Bad use of spectrahedronfactory.lincomb.'); end end