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
zhxing001/DIP_exercise-master
upConv.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/upConv.m
2,670
utf_8
bb548d24157a068adee954f36ad04fbb
% RES = upConv(IM, FILT, EDGES, STEP, START, STOP, RES) % % Upsample matrix IM, followed by convolution with matrix FILT. These % arguments should be 1D or 2D matrices, and IM must be larger (in % both dimensions) than FILT. The origin of filt % is assumed to be floor(size(filt)/2)+1. % % EDGES is a string determining boundary handling: % 'circular' - Circular convolution % 'reflect1' - Reflect about the edge pixels % 'reflect2' - Reflect, doubling the edge pixels % 'repeat' - Repeat the edge pixels % 'zero' - Assume values of zero outside image boundary % 'extend' - Reflect and invert % 'dont-compute' - Zero output when filter overhangs OUTPUT boundaries % % Upsampling factors are determined by STEP (optional, default=[1 1]), % a 2-vector [y,x]. % % The window over which the convolution occurs is specfied by START % (optional, default=[1,1], and STOP (optional, default = % step .* (size(IM) + floor((start-1)./step))). % % RES is an optional result matrix. The convolution result will be % destructively added into this matrix. If this argument is passed, the % result matrix will not be returned. DO NOT USE THIS ARGUMENT IF % YOU DO NOT UNDERSTAND WHAT THIS MEANS!! % % NOTE: this operation corresponds to multiplication of a signal % vector by a matrix whose columns contain copies of the time-reversed % (or space-reversed) FILT shifted by multiples of STEP. See corrDn.m % for the operation corresponding to the transpose of this matrix. % Eero Simoncelli, 6/96. revised 2/97. function result = upConv(im,filt,edges,step,start,stop,res) %% THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD) fprintf(1,'Warning: You should compile the MEX code for "upConv", found in the MEX subdirectory. It is much faster.\n'); %------------------------------------------------------------ %% OPTIONAL ARGS: if (exist('edges') == 1) if (strcmp(edges,'reflect1') ~= 1) warning('Using REFLECT1 edge-handling (use MEX code for other options).'); end end if (exist('step') ~= 1) step = [1,1]; end if (exist('start') ~= 1) start = [1,1]; end % A multiple of step if (exist('stop') ~= 1) stop = step .* (floor((start-ones(size(start)))./step)+size(im)) end if ( ceil((stop(1)+1-start(1)) / step(1)) ~= size(im,1) ) error('Bad Y result dimension'); end if ( ceil((stop(2)+1-start(2)) / step(2)) ~= size(im,2) ) error('Bad X result dimension'); end if (exist('res') ~= 1) res = zeros(stop-start+1); end %------------------------------------------------------------ tmp = zeros(size(res)); tmp(start(1):step(1):stop(1),start(2):step(2):stop(2)) = im; result = rconv2(tmp,filt) + res;
github
zhxing001/DIP_exercise-master
range2.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/range2.m
459
utf_8
b5e91506fc6b3e316a8e1671b5af7467
% [MIN, MAX] = range2(MTX) % % Compute minimum and maximum values of MTX, returning them as a 2-vector. % Eero Simoncelli, 3/97. function [mn, mx] = range2(mtx) %% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD) fprintf(1,'WARNING: You should compile the MEX code for "range2", found in the MEX subdirectory. It is MUCH faster.\n'); if (~isreal(mtx)) error('MTX must be real-valued'); end mn = min(min(mtx)); mx = max(max(mtx));
github
zhxing001/DIP_exercise-master
reconFullSFpyr2.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/reconFullSFpyr2.m
3,257
utf_8
447f5204894b159fbb4ea4de2dccf877
% RES = reconFullSFpyr2(PYR, INDICES, LEVS, BANDS, TWIDTH) % % Reconstruct image from its steerable pyramid representation, in the Fourier % domain, as created by buildSFpyr. % Unlike the standard transform, subdivides the highpass band into % orientations. function res = reconFullSFpyr2(pyr, pind, levs, bands, twidth) %%------------------------------------------------------------ %% DEFAULTS: if (exist('levs') ~= 1) levs = 'all'; end if (exist('bands') ~= 1) bands = 'all'; end if (exist('twidth') ~= 1) twidth = 1; elseif (twidth <= 0) fprintf(1,'Warning: TWIDTH must be positive. Setting to 1.\n'); twidth = 1; end %%------------------------------------------------------------ nbands = spyrNumBands(pind)/2; maxLev = 2+spyrHt(pind(nbands+1:size(pind,1),:)); if strcmp(levs,'all') levs = [0:maxLev]'; else if (any(levs > maxLev) | any(levs < 0)) error(sprintf('Level numbers must be in the range [0, %d].', maxLev)); end levs = levs(:); end if strcmp(bands,'all') bands = [1:nbands]'; else if (any(bands < 1) | any(bands > nbands)) error(sprintf('Band numbers must be in the range [1,3].', nbands)); end bands = bands(:); end %---------------------------------------------------------------------- dims = pind(2,:); ctr = ceil((dims+0.5)/2); [xramp,yramp] = meshgrid( ([1:dims(2)]-ctr(2))./(dims(2)/2), ... ([1:dims(1)]-ctr(1))./(dims(1)/2) ); angle = atan2(yramp,xramp); log_rad = sqrt(xramp.^2 + yramp.^2); log_rad(ctr(1),ctr(2)) = log_rad(ctr(1),ctr(2)-1); log_rad = log2(log_rad); %% Radial transition function (a raised cosine in log-frequency): [Xrcos,Yrcos] = rcosFn(twidth,(-twidth/2),[0 1]); Yrcos = sqrt(Yrcos); YIrcos = sqrt(1.0 - Yrcos.^2); if (size(pind,1) == 2) if (any(levs==1)) resdft = fftshift(fft2(pyrBand(pyr,pind,2))); else resdft = zeros(pind(2,:)); end else resdft = reconSFpyrLevs(pyr(1+sum(prod(pind(1:nbands+1,:)')):size(pyr,1)), ... pind(nbands+2:size(pind,1),:), ... log_rad, Xrcos, Yrcos, angle, nbands, levs, bands); end lo0mask = pointOp(log_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); resdft = resdft .* lo0mask; %% Oriented highpass bands: if any(levs == 0) lutsize = 1024; Xcosn = pi*[-(2*lutsize+1):(lutsize+1)]/lutsize; % [-2*pi:pi] order = nbands-1; %% divide by sqrt(sum_(n=0)^(N-1) cos(pi*n/N)^(2(N-1)) ) const = (2^(2*order))*(factorial(order)^2)/(nbands*factorial(2*order)); Ycosn = sqrt(const) * (cos(Xcosn)).^order; hi0mask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); ind = 1; for b = 1:nbands if any(bands == b) anglemask = pointOp(angle,Ycosn,Xcosn(1)+pi*(b-1)/nbands,Xcosn(2)-Xcosn(1)); band = reshape(pyr(ind:ind+prod(dims)-1), dims(1), dims(2)); banddft = fftshift(fft2(band)); % make real the contents in the HF cross (to avoid information loss in these freqs.) % It distributes evenly these contents among the nbands orientations Mask = (sqrt(-1))^(nbands-1) * anglemask.*hi0mask; Mask(1,:) = ones(1,size(Mask,2))/sqrt(nbands); Mask(2:size(Mask,1),1) = ones(size(Mask,1)-1,1)/sqrt(nbands); resdft = resdft + banddft.*Mask; end ind = ind + prod(dims); end end res = real(ifft2(ifftshift(resdft)));
github
zhxing001/DIP_exercise-master
steer2HarmMtx.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/steer2HarmMtx.m
1,803
utf_8
35816be985c308717168260dc97419d8
% MTX = steer2HarmMtx(HARMONICS, ANGLES, REL_PHASES) % % Compute a steering matrix (maps a directional basis set onto the % angular Fourier harmonics). HARMONICS is a vector specifying the % angular harmonics contained in the steerable basis/filters. ANGLES % (optional) is a vector specifying the angular position of each filter. % REL_PHASES (optional, default = 'even') specifies whether the harmonics % are cosine or sine phase aligned about those positions. % The result matrix is suitable for passing to the function STEER. % Eero Simoncelli, 7/96. function mtx = steer2HarmMtx(harmonics, angles, evenorodd) %%================================================================= %%% Optional Parameters: if (exist('evenorodd') ~= 1) evenorodd = 'even'; end % Make HARMONICS a row vector harmonics = harmonics(:)'; numh = 2*size(harmonics,2) - any(harmonics == 0); if (exist('angles') ~= 1) angles = pi * [0:numh-1]'/numh; else angles = angles(:); end %%================================================================= if isstr(evenorodd) if strcmp(evenorodd,'even') evenorodd = 0; elseif strcmp(evenorodd,'odd') evenorodd = 1; else error('EVEN_OR_ODD should be the string EVEN or ODD'); end end %% Compute inverse matrix, which maps Fourier components onto %% steerable basis. imtx = zeros(size(angles,1),numh); col = 1; for h=harmonics args = h*angles; if (h == 0) imtx(:,col) = ones(size(angles)); col = col+1; elseif evenorodd imtx(:,col) = sin(args); imtx(:,col+1) = -cos(args); col = col+2; else imtx(:,col) = cos(args); imtx(:,col+1) = sin(args); col = col+2; end end r = rank(imtx); if (( r ~= numh ) & ( r ~= size(angles,1) )) fprintf(2,'WARNING: matrix is not full rank'); end mtx = pinv(imtx);
github
zhxing001/DIP_exercise-master
subMtx.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/subMtx.m
420
utf_8
c660029ce728dcb8c540c9cf419fa7bc
% MTX = subMtx(VEC, DIMENSIONS, START_INDEX) % % Reshape a portion of VEC starting from START_INDEX (optional, % default=1) to the given dimensions. % Eero Simoncelli, 6/96. function mtx = subMtx(vec, sz, offset) if (exist('offset') ~= 1) offset = 1; end vec = vec(:); sz = sz(:); if (size(sz,1) ~= 2) error('DIMENSIONS must be a 2-vector.'); end mtx = reshape( vec(offset:offset+prod(sz)-1), sz(1), sz(2) );
github
zhxing001/DIP_exercise-master
spyrHt.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/spyrHt.m
305
utf_8
06e83c1f45c1a99e242fa7ea37093a11
% [HEIGHT] = spyrHt(INDICES) % % Compute height of steerable pyramid with given index matrix. % Eero Simoncelli, 6/96. function [ht] = spyrHt(pind) nbands = spyrNumBands(pind); % Don't count lowpass, or highpass residual bands if (size(pind,1) > 2) ht = (size(pind,1)-2)/nbands; else ht = 0; end
github
zhxing001/DIP_exercise-master
spyrBand.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/spyrBand.m
819
utf_8
7d15b24244e521c9e85c68b3037f569b
% [LEV,IND] = spyrBand(PYR,INDICES,LEVEL,BAND) % % Access a band from a steerable pyramid. % % LEVEL indicates the scale (finest = 1, coarsest = spyrHt(INDICES)). % % BAND (optional, default=1) indicates which subband % (1 = vertical, rest proceeding anti-clockwise). % Eero Simoncelli, 6/96. function res = spyrBand(pyr,pind,level,band) if (exist('level') ~= 1) level = 1; end if (exist('band') ~= 1) band = 1; end nbands = spyrNumBands(pind); if ((band > nbands) | (band < 1)) error(sprintf('Bad band number (%d) should be in range [1,%d].', band, nbands)); end maxLev = spyrHt(pind); if ((level > maxLev) | (level < 1)) error(sprintf('Bad level number (%d), should be in range [1,%d].', level, maxLev)); end firstband = 1 + band + nbands*(level-1); res = pyrBand(pyr, pind, firstband);
github
zhxing001/DIP_exercise-master
wpyrBand.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/wpyrBand.m
873
utf_8
12e08d90ccd6261b737e2d3c5ac5b1e7
% RES = wpyrBand(PYR, INDICES, LEVEL, BAND) % % Access a subband from a separable QMF/wavelet pyramid. % % LEVEL (optional, default=1) indicates the scale (finest = 1, % coarsest = wpyrHt(INDICES)). % % BAND (optional, default=1) indicates which subband (1=horizontal, % 2=vertical, 3=diagonal). % Eero Simoncelli, 6/96. function im = wpyrBand(pyr,pind,level,band) if (exist('level') ~= 1) level = 1; end if (exist('band') ~= 1) band = 1; end if ((pind(1,1) == 1) | (pind(1,2) ==1)) nbands = 1; else nbands = 3; end if ((band > nbands) | (band < 1)) error(sprintf('Bad band number (%d) should be in range [1,%d].', band, nbands)); end maxLev = wpyrHt(pind); if ((level > maxLev) | (level < 1)) error(sprintf('Bad level number (%d), should be in range [1,%d].', level, maxLev)); end band = band + nbands*(level-1); im = pyrBand(pyr,pind,band);
github
zhxing001/DIP_exercise-master
innerProd.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/innerProd.m
404
utf_8
29d3b9025830e8641826ce536cdfa63d
% RES = innerProd(MTX) % % Compute (MTX' * MTX) efficiently (i.e., without copying the matrix) function res = innerProd(mtx) %% NOTE: THIS CODE SHOULD NOT BE USED! (MEX FILE IS CALLED INSTEAD) fprintf(1,'WARNING: You should compile the MEX version of "innerProd.c",\n found in the MEX subdirectory of matlabPyrTools, and put it in your matlab path. It is MUCH faster.\n'); res = mtx' * mtx;
github
zhxing001/DIP_exercise-master
reconSFpyr.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/reconSFpyr.m
3,035
utf_8
d2797e74c72af97fc0d72123dc91035c
% RES = reconSFpyr(PYR, INDICES, LEVS, BANDS, TWIDTH) % % Reconstruct image from its steerable pyramid representation, in the Fourier % domain, as created by buildSFpyr. % % PYR is a vector containing the N pyramid subbands, ordered from fine % to coarse. INDICES is an Nx2 matrix containing the sizes of % each subband. This is compatible with the MatLab Wavelet toolbox. % % LEVS (optional) should be a list of levels to include, or the string % 'all' (default). 0 corresonds to the residual highpass subband. % 1 corresponds to the finest oriented scale. The lowpass band % corresponds to number spyrHt(INDICES)+1. % % BANDS (optional) should be a list of bands to include, or the string % 'all' (default). 1 = vertical, rest proceeding anti-clockwise. % % TWIDTH is the width of the transition region of the radial lowpass % function, in octaves (default = 1, which gives a raised cosine for % the bandpass filters). % Eero Simoncelli, 5/97. function res = reconSFpyr(pyr, pind, levs, bands, twidth) %%------------------------------------------------------------ %% DEFAULTS: if (exist('levs') ~= 1) levs = 'all'; end if (exist('bands') ~= 1) bands = 'all'; end if (exist('twidth') ~= 1) twidth = 1; elseif (twidth <= 0) fprintf(1,'Warning: TWIDTH must be positive. Setting to 1.\n'); twidth = 1; end %%------------------------------------------------------------ nbands = spyrNumBands(pind); maxLev = 1+spyrHt(pind); if strcmp(levs,'all') levs = [0:maxLev]'; else if (any(levs > maxLev) | any(levs < 0)) error(sprintf('Level numbers must be in the range [0, %d].', maxLev)); end levs = levs(:); end if strcmp(bands,'all') bands = [1:nbands]'; else if (any(bands < 1) | any(bands > nbands)) error(sprintf('Band numbers must be in the range [1,3].', nbands)); end bands = bands(:); end %---------------------------------------------------------------------- dims = pind(1,:); ctr = ceil((dims+0.5)/2); [xramp,yramp] = meshgrid( ([1:dims(2)]-ctr(2))./(dims(2)/2), ... ([1:dims(1)]-ctr(1))./(dims(1)/2) ); angle = atan2(yramp,xramp); log_rad = sqrt(xramp.^2 + yramp.^2); log_rad(ctr(1),ctr(2)) = log_rad(ctr(1),ctr(2)-1); log_rad = log2(log_rad); %% Radial transition function (a raised cosine in log-frequency): [Xrcos,Yrcos] = rcosFn(twidth,(-twidth/2),[0 1]); Yrcos = sqrt(Yrcos); YIrcos = sqrt(abs(1.0 - Yrcos.^2)); if (size(pind,1) == 2) if (any(levs==1)) resdft = fftshift(fft2(pyrBand(pyr,pind,2))); else resdft = zeros(pind(2,:)); end else resdft = reconSFpyrLevs(pyr(1+prod(pind(1,:)):size(pyr,1)), ... pind(2:size(pind,1),:), ... log_rad, Xrcos, Yrcos, angle, nbands, levs, bands); end lo0mask = pointOp(log_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); resdft = resdft .* lo0mask; %% residual highpass subband if any(levs == 0) hi0mask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); hidft = fftshift(fft2(subMtx(pyr, pind(1,:)))); resdft = resdft + hidft .* hi0mask; end res = real(ifft2(ifftshift(resdft)));
github
zhxing001/DIP_exercise-master
corrDn.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/corrDn.m
2,132
utf_8
a2140ad2c6dfcb5280f6a594537bc487
% RES = corrDn(IM, FILT, EDGES, STEP, START, STOP) % % Compute correlation of matrices IM with FILT, followed by % downsampling. These arguments should be 1D or 2D matrices, and IM % must be larger (in both dimensions) than FILT. The origin of filt % is assumed to be floor(size(filt)/2)+1. % % EDGES is a string determining boundary handling: % 'circular' - Circular convolution % 'reflect1' - Reflect about the edge pixels % 'reflect2' - Reflect, doubling the edge pixels % 'repeat' - Repeat the edge pixels % 'zero' - Assume values of zero outside image boundary % 'extend' - Reflect and invert % 'dont-compute' - Zero output when filter overhangs input boundaries % % Downsampling factors are determined by STEP (optional, default=[1 1]), % which should be a 2-vector [y,x]. % % The window over which the convolution occurs is specfied by START % (optional, default=[1,1], and STOP (optional, default=size(IM)). % % NOTE: this operation corresponds to multiplication of a signal % vector by a matrix whose rows contain copies of the FILT shifted by % multiples of STEP. See upConv.m for the operation corresponding to % the transpose of this matrix. % Eero Simoncelli, 6/96, revised 2/97. function res = corrDn(im, filt, edges, step, start, stop) %% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD) fprintf(1,'Warning: You should compile the MEX code for "corrDn", found in the MEX subdirectory. It is MUCH faster.\n'); %------------------------------------------------------------ %% OPTIONAL ARGS: if (exist('edges') == 1) if (strcmp(edges,'reflect1') ~= 1) warning('Using REFLECT1 edge-handling (use MEX code for other options).'); end end if (exist('step') ~= 1) step = [1,1]; end if (exist('start') ~= 1) start = [1,1]; end if (exist('stop') ~= 1) stop = size(im); end %------------------------------------------------------------ % Reverse order of taps in filt, to do correlation instead of convolution filt = filt(size(filt,1):-1:1,size(filt,2):-1:1); tmp = rconv2(im,filt); res = tmp(start(1):step(1):stop(1),start(2):step(2):stop(2));
github
zhxing001/DIP_exercise-master
maxPyrHt.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/maxPyrHt.m
603
utf_8
019e5ce9d036a893ec979c63f51ff54a
% HEIGHT = maxPyrHt(IMSIZE, FILTSIZE) % % Compute maximum pyramid height for given image and filter sizes. % Specifically: the number of corrDn operations that can be sequentially % performed when subsampling by a factor of 2. % Eero Simoncelli, 6/96. function height = maxPyrHt(imsz, filtsz) imsz = imsz(:); filtsz = filtsz(:); if any(imsz == 1) % 1D image imsz = prod(imsz); filtsz = prod(filtsz); elseif any(filtsz == 1) % 2D image, 1D filter filtsz = [filtsz(1); filtsz(1)]; end if any(imsz < filtsz) height = 0; else height = 1 + maxPyrHt( floor(imsz/2), filtsz ); end
github
zhxing001/DIP_exercise-master
buildSFpyrLevs.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/buildSFpyrLevs.m
1,825
utf_8
f392f9c8ee1b85c2cf1c86edc383e4af
% [PYR, INDICES] = buildSFpyrLevs(LODFT, LOGRAD, XRCOS, YRCOS, ANGLE, HEIGHT, NBANDS) % % Recursive function for constructing levels of a steerable pyramid. This % is called by buildSFpyr, and is not usually called directly. % Eero Simoncelli, 5/97. function [pyr,pind] = buildSFpyrLevs(lodft,log_rad,Xrcos,Yrcos,angle,ht,nbands); if (ht <= 0) lo0 = ifft2(ifftshift(lodft)); pyr = real(lo0(:)); pind = size(lo0); else bands = zeros(prod(size(lodft)), nbands); bind = zeros(nbands,2); log_rad = log_rad + 1; lutsize = 1024; Xcosn = pi*[-(2*lutsize+1):(lutsize+1)]/lutsize; % [-2*pi:pi] order = nbands-1; %% divide by sqrt(sum_(n=0)^(N-1) cos(pi*n/N)^(2(N-1)) ) %% Thanks to Patrick Teo for writing this out :) const = (2^(2*order))*(factorial(order)^2)/(nbands*factorial(2*order)); Ycosn = sqrt(const) * (cos(Xcosn)).^order; himask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); for b = 1:nbands anglemask = pointOp(angle, Ycosn, Xcosn(1)+pi*(b-1)/nbands, Xcosn(2)-Xcosn(1)); banddft = ((-i)^(nbands-1)) .* lodft .* anglemask .* himask; band = ifft2(ifftshift(banddft)); bands(:,b) = real(band(:)); bind(b,:) = size(band); end dims = size(lodft); ctr = ceil((dims+0.5)/2); lodims = ceil((dims-0.5)/2); loctr = ceil((lodims+0.5)/2); lostart = ctr-loctr+1; loend = lostart+lodims-1; log_rad = log_rad(lostart(1):loend(1),lostart(2):loend(2)); angle = angle(lostart(1):loend(1),lostart(2):loend(2)); lodft = lodft(lostart(1):loend(1),lostart(2):loend(2)); YIrcos = abs(sqrt(1.0 - Yrcos.^2)); lomask = pointOp(log_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); lodft = lomask .* lodft; [npyr,nind] = buildSFpyrLevs(lodft, log_rad, Xrcos, Yrcos, angle, ht-1, nbands); pyr = [bands(:); npyr]; pind = [bind; nind]; end
github
zhxing001/DIP_exercise-master
pixelAxes.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/pixelAxes.m
1,983
utf_8
1b2a2bfddd425fee2ccd276f3948cec7
% [ZOOM] = pixelAxes(DIMS, ZOOM) % % Set the axes of the current plot to cover a multiple of DIMS pixels, % thereby eliminating screen aliasing artifacts when displaying an % image of size DIMS. % % ZOOM (optional, default='same') expresses the desired number of % samples displayed per screen pixel. It should be a scalar, which % will be rounded to the nearest integer, or 1 over an integer. It % may also be the string 'same' or 'auto', in which case the value is chosen so % as to produce an image closest in size to the currently displayed % image. It may also be the string 'full', in which case the image is % made as large as possible while still fitting in the window. % Eero Simoncelli, 2/97. function [zoom] = pixelAxes(dims, zoom) %------------------------------------------------------------ %% OPTIONAL ARGS: if (exist('zoom') ~= 1) zoom = 'same'; end %% Reverse dimension order, since Figure Positions reported as (x,y). dims = dims(2:-1:1); %% Use MatLab's axis function to force square pixels, etc: axis('image'); ax = gca; oldunits = get(ax,'Units'); if strcmp(zoom,'full'); set(ax,'Units','normalized'); set(ax,'Position',[0 0 1 1]); zoom = 'same'; end set(ax,'Units','pixels'); pos = get(ax,'Position'); ctr = pos(1:2)+pos(3:4)/2; if (strcmp(zoom,'same') | strcmp(zoom,'auto')) %% HACK: enlarge slightly so that floor doesn't round down zoom = min( pos(3:4) ./ (dims - 1) ); elseif isstr(zoom) error(sprintf('Bad ZOOM argument: %s',zoom)); end %% Force zoom value to be an integer, or inverse integer. if (zoom < 0.75) zoom = 1/ceil(1/zoom); %% Round upward, subtracting 0.5 to avoid floating point errors. newsz = ceil(zoom*(dims-0.5)); else zoom = floor(zoom + 0.001); % Avoid floating pt errors if (zoom < 1.5) % zoom=1 zoom = 1; newsz = dims + 0.5; else newsz = zoom*(dims-1) + mod(zoom,2); end end set(ax,'Position', [floor(ctr-newsz/2)+0.5, newsz] ) % Restore units set(ax,'Units',oldunits);
github
zhxing001/DIP_exercise-master
pyrBandIndices.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/pyrBandIndices.m
589
utf_8
28f90484526c294bdb24bdbf8014012d
% RES = pyrBandIndices(INDICES, BAND_NUM) % % Return indices for accessing a subband from a pyramid % (gaussian, laplacian, QMF/wavelet, steerable). % Eero Simoncelli, 6/96. function indices = pyrBandIndices(pind,band) if ((band > size(pind,1)) | (band < 1)) error(sprintf('BAND_NUM must be between 1 and number of pyramid bands (%d).', ... size(pind,1))); end if (size(pind,2) ~= 2) error('INDICES must be an Nx2 matrix indicating the size of the pyramid subbands'); end ind = 1; for l=1:band-1 ind = ind + prod(pind(l,:)); end indices = ind:ind+prod(pind(band,:))-1;
github
zhxing001/DIP_exercise-master
pointOp.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/pointOp.m
1,132
utf_8
6e1737ee18a474ee23f6cf6fb58b45c6
% RES = pointOp(IM, LUT, ORIGIN, INCREMENT, WARNINGS) % % Apply a point operation, specified by lookup table LUT, to image IM. % LUT must be a row or column vector, and is assumed to contain % (equi-spaced) samples of the function. ORIGIN specifies the % abscissa associated with the first sample, and INCREMENT specifies the % spacing between samples. Between-sample values are estimated via % linear interpolation. If WARNINGS is non-zero, the function prints % a warning whenever the lookup table is extrapolated. % % This function is much faster than MatLab's interp1, and allows % extrapolation beyond the lookup table domain. The drawbacks are % that the lookup table must be equi-spaced, and the interpolation is % linear. % Eero Simoncelli, 8/96. function res = pointOp(im, lut, origin, increment, warnings) %% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD) fprintf(1,'WARNING: You should compile the MEX code for "pointOp", found in the MEX subdirectory. It is MUCH faster.\n'); X = origin + increment*[0:size(lut(:),1)-1]; Y = lut(:); res = reshape(interp1(X, Y, im(:), 'linear'),size(im));
github
zhxing001/DIP_exercise-master
reconWpyr.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/reconWpyr.m
3,992
utf_8
859a606f214bce204ce3c9ea18c0fc87
% RES = reconWpyr(PYR, INDICES, FILT, EDGES, LEVS, BANDS) % % Reconstruct image from its separable orthonormal QMF/wavelet pyramid % representation, as created by buildWpyr. % % PYR is a vector containing the N pyramid subbands, ordered from fine % to coarse. INDICES is an Nx2 matrix containing the sizes of % each subband. This is compatible with the MatLab Wavelet toolbox. % % FILT (optional) can be a string naming a standard filter (see % namedFilter), or a vector which will be used for (separable) % convolution. Default = 'qmf9'. EDGES specifies edge-handling, % and defaults to 'reflect1' (see corrDn). % % LEVS (optional) should be a vector of levels to include, or the string % 'all' (default). 1 corresponds to the finest scale. The lowpass band % corresponds to wpyrHt(INDICES)+1. % % BANDS (optional) should be a vector of bands to include, or the string % 'all' (default). 1=horizontal, 2=vertical, 3=diagonal. This is only used % for pyramids of 2D images. % Eero Simoncelli, 6/96. function res = reconWpyr(pyr, ind, filt, edges, levs, bands) if (nargin < 2) error('First two arguments (PYR INDICES) are required'); end %%------------------------------------------------------------ %% OPTIONAL ARGS: if (exist('filt') ~= 1) filt = 'qmf9'; end if (exist('edges') ~= 1) edges= 'reflect1'; end if (exist('levs') ~= 1) levs = 'all'; end if (exist('bands') ~= 1) bands = 'all'; end %%------------------------------------------------------------ maxLev = 1+wpyrHt(ind); if strcmp(levs,'all') levs = [1:maxLev]'; else if (any(levs > maxLev)) error(sprintf('Level numbers must be in the range [1, %d].', maxLev)); end levs = levs(:); end if strcmp(bands,'all') bands = [1:3]'; else if (any(bands < 1) | any(bands > 3)) error('Band numbers must be in the range [1,3].'); end bands = bands(:); end if isstr(filt) filt = namedFilter(filt); end filt = filt(:); hfilt = modulateFlip(filt); %% For odd-length filters, stagger the sampling lattices: if (mod(size(filt,1),2) == 0) stag = 2; else stag = 1; end %% Compute size of result image: assumes critical sampling (boundaries correct) res_sz = ind(1,:); if (res_sz(1) == 1) loind = 2; res_sz(2) = sum(ind(:,2)); elseif (res_sz(2) == 1) loind = 2; res_sz(1) = sum(ind(:,1)); else loind = 4; res_sz = ind(1,:) + ind(2,:); %%horizontal + vertical bands. hres_sz = [ind(1,1), res_sz(2)]; lres_sz = [ind(2,1), res_sz(2)]; end %% First, recursively collapse coarser scales: if any(levs > 1) if (size(ind,1) > loind) nres = reconWpyr( pyr(1+sum(prod(ind(1:loind-1,:)')):size(pyr,1)), ... ind(loind:size(ind,1),:), filt, edges, levs-1, bands); else nres = pyrBand(pyr, ind, loind); % lowpass subband end if (res_sz(1) == 1) res = upConv(nres, filt', edges, [1 2], [1 stag], res_sz); elseif (res_sz(2) == 1) res = upConv(nres, filt, edges, [2 1], [stag 1], res_sz); else ires = upConv(nres, filt', edges, [1 2], [1 stag], lres_sz); res = upConv(ires, filt, edges, [2 1], [stag 1], res_sz); end else res = zeros(res_sz); end %% Add in reconstructed bands from this level: if any(levs == 1) if (res_sz(1) == 1) upConv(pyrBand(pyr,ind,1), hfilt', edges, [1 2], [1 2], res_sz, res); elseif (res_sz(2) == 1) upConv(pyrBand(pyr,ind,1), hfilt, edges, [2 1], [2 1], res_sz, res); else if any(bands == 1) % horizontal ires = upConv(pyrBand(pyr,ind,1),filt',edges,[1 2],[1 stag],hres_sz); upConv(ires,hfilt,edges,[2 1],[2 1],res_sz,res); %destructively modify res end if any(bands == 2) % vertical ires = upConv(pyrBand(pyr,ind,2),hfilt',edges,[1 2],[1 2],lres_sz); upConv(ires,filt,edges,[2 1],[stag 1],res_sz,res); %destructively modify res end if any(bands == 3) % diagonal ires = upConv(pyrBand(pyr,ind,3),hfilt',edges,[1 2],[1 2],hres_sz); upConv(ires,hfilt,edges,[2 1],[2 1],res_sz,res); %destructively modify res end end end
github
zhxing001/DIP_exercise-master
shift.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/shift.m
438
utf_8
2ac42b171e4ca683ef1d361eaf331870
% [RES] = shift(MTX, OFFSET) % % Circular shift 2D matrix samples by OFFSET (a [Y,X] 2-vector), % such that RES(POS) = MTX(POS-OFFSET). function res = shift(mtx, offset) dims = size(mtx); offset = mod(-offset,dims); res = [ mtx(offset(1)+1:dims(1), offset(2)+1:dims(2)), ... mtx(offset(1)+1:dims(1), 1:offset(2)); ... mtx(1:offset(1), offset(2)+1:dims(2)), ... mtx(1:offset(1), 1:offset(2)) ];
github
zhxing001/DIP_exercise-master
namedFilter.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/namedFilter.m
3,207
utf_8
8f45ef65fca60f53e0f734c4f1ae01bf
% KERNEL = NAMED_FILTER(NAME) % % Some standard 1D filter kernels. These are scaled such that % their L2-norm is 1.0. % % binomN - binomial coefficient filter of order N-1 % haar: - Haar wavelet. % qmf8, qmf12, qmf16 - Symmetric Quadrature Mirror Filters [Johnston80] % daub2,daub3,daub4 - Daubechies wavelet [Daubechies88]. % qmf5, qmf9, qmf13: - Symmetric Quadrature Mirror Filters [Simoncelli88,Simoncelli90] % % See bottom of file for full citations. % Eero Simoncelli, 6/96. function [kernel] = named_filter(name) if strcmp(name(1:min(5,size(name,2))), 'binom') kernel = sqrt(2) * binomialFilter(str2num(name(6:size(name,2)))); elseif strcmp(name,'qmf5') kernel = [-0.076103 0.3535534 0.8593118 0.3535534 -0.076103]'; elseif strcmp(name,'qmf9') kernel = [0.02807382 -0.060944743 -0.073386624 0.41472545 0.7973934 ... 0.41472545 -0.073386624 -0.060944743 0.02807382]'; elseif strcmp(name,'qmf13') kernel = [-0.014556438 0.021651438 0.039045125 -0.09800052 ... -0.057827797 0.42995453 0.7737113 0.42995453 -0.057827797 ... -0.09800052 0.039045125 0.021651438 -0.014556438]'; elseif strcmp(name,'qmf8') kernel = sqrt(2) * [0.00938715 -0.07065183 0.06942827 0.4899808 ... 0.4899808 0.06942827 -0.07065183 0.00938715 ]'; elseif strcmp(name,'qmf12') kernel = sqrt(2) * [-0.003809699 0.01885659 -0.002710326 -0.08469594 ... 0.08846992 0.4843894 0.4843894 0.08846992 -0.08469594 -0.002710326 ... 0.01885659 -0.003809699 ]'; elseif strcmp(name,'qmf16') kernel = sqrt(2) * [0.001050167 -0.005054526 -0.002589756 0.0276414 -0.009666376 ... -0.09039223 0.09779817 0.4810284 0.4810284 0.09779817 -0.09039223 -0.009666376 ... 0.0276414 -0.002589756 -0.005054526 0.001050167 ]'; elseif strcmp(name,'haar') kernel = [1 1]' / sqrt(2); elseif strcmp(name,'daub2') kernel = [0.482962913145 0.836516303738 0.224143868042 -0.129409522551]'; elseif strcmp(name,'daub3') kernel = [0.332670552950 0.806891509311 0.459877502118 -0.135011020010 ... -0.085441273882 0.035226291882]'; elseif strcmp(name,'daub4') kernel = [0.230377813309 0.714846570553 0.630880767930 -0.027983769417 ... -0.187034811719 0.030841381836 0.032883011667 -0.010597401785]'; elseif strcmp(name,'gauss5') % for backward-compatibility kernel = sqrt(2) * [0.0625 0.25 0.375 0.25 0.0625]'; elseif strcmp(name,'gauss3') % for backward-compatibility kernel = sqrt(2) * [0.25 0.5 0.25]'; else error(sprintf('Bad filter name: %s\n',name)); end % [Johnston80] - J D Johnston, "A filter family designed for use in quadrature % mirror filter banks", Proc. ICASSP, pp 291-294, 1980. % % [Daubechies88] - I Daubechies, "Orthonormal bases of compactly supported wavelets", % Commun. Pure Appl. Math, vol. 42, pp 909-996, 1988. % % [Simoncelli88] - E P Simoncelli, "Orthogonal sub-band image transforms", % PhD Thesis, MIT Dept. of Elec. Eng. and Comp. Sci. May 1988. % Also available as: MIT Media Laboratory Vision and Modeling Technical % Report #100. % % [Simoncelli90] - E P Simoncelli and E H Adelson, "Subband image coding", % Subband Transforms, chapter 4, ed. John W Woods, Kluwer Academic % Publishers, Norwell, MA, 1990, pp 143--192.
github
zhxing001/DIP_exercise-master
wpyrHt.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/wpyrHt.m
270
utf_8
18e1a724afee99389db70484333eb05a
% [HEIGHT] = wpyrHt(INDICES) % % Compute height of separable QMF/wavelet pyramid with given index matrix. % Eero Simoncelli, 6/96. function [ht] = wpyrHt(pind) if ((pind(1,1) == 1) | (pind(1,2) ==1)) nbands = 1; else nbands = 3; end ht = (size(pind,1)-1)/nbands;
github
zhxing001/DIP_exercise-master
buildSFpyr.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/buildSFpyr.m
3,260
utf_8
66654d041ea2ff942f5480347bc4c281
% [PYR, INDICES, STEERMTX, HARMONICS] = buildSFpyr(IM, HEIGHT, ORDER, TWIDTH) % % Construct a steerable pyramid on matrix IM, in the Fourier domain. % This is similar to buildSpyr, except that: % % + Reconstruction is exact (within floating point errors) % + It can produce any number of orientation bands. % - Typically slower, especially for non-power-of-two sizes. % - Boundary-handling is circular. % % HEIGHT (optional) specifies the number of pyramid levels to build. Default % is maxPyrHt(size(IM),size(FILT)); % % The squared radial functions tile the Fourier plane, with a raised-cosine % falloff. Angular functions are cos(theta-k\pi/(K+1))^K, where K is % the ORDER (one less than the number of orientation bands, default= 3). % % TWIDTH is the width of the transition region of the radial lowpass % function, in octaves (default = 1, which gives a raised cosine for % the bandpass filters). % % PYR is a vector containing the N pyramid subbands, ordered from fine % to coarse. INDICES is an Nx2 matrix containing the sizes of % each subband. This is compatible with the MatLab Wavelet toolbox. % See the function STEER for a description of STEERMTX and HARMONICS. % Eero Simoncelli, 5/97. % See http://www.cis.upenn.edu/~eero/steerpyr.html for more % information about the Steerable Pyramid image decomposition. function [pyr,pind,steermtx,harmonics] = buildSFpyr(im, ht, order, twidth) %----------------------------------------------------------------- %% DEFAULTS: max_ht = floor(log2(min(size(im)))+2); if (exist('ht') ~= 1) ht = max_ht; else if (ht > max_ht) error(sprintf('Cannot build pyramid higher than %d levels.',max_ht)); end end if (exist('order') ~= 1) order = 3; elseif ((order > 15) | (order < 0)) fprintf(1,'Warning: ORDER must be an integer in the range [0,15]. Truncating.\n'); order = min(max(order,0),15); else order = round(order); end nbands = order+1; if (exist('twidth') ~= 1) twidth = 1; elseif (twidth <= 0) fprintf(1,'Warning: TWIDTH must be positive. Setting to 1.\n'); twidth = 1; end %----------------------------------------------------------------- %% Steering stuff: if (mod((nbands),2) == 0) harmonics = [0:(nbands/2)-1]'*2 + 1; else harmonics = [0:(nbands-1)/2]'*2; end steermtx = steer2HarmMtx(harmonics, pi*[0:nbands-1]/nbands, 'even'); %----------------------------------------------------------------- dims = size(im); ctr = ceil((dims+0.5)/2); [xramp,yramp] = meshgrid( ([1:dims(2)]-ctr(2))./(dims(2)/2), ... ([1:dims(1)]-ctr(1))./(dims(1)/2) ); angle = atan2(yramp,xramp); log_rad = sqrt(xramp.^2 + yramp.^2); log_rad(ctr(1),ctr(2)) = log_rad(ctr(1),ctr(2)-1); log_rad = log2(log_rad); %% Radial transition function (a raised cosine in log-frequency): [Xrcos,Yrcos] = rcosFn(twidth,(-twidth/2),[0 1]); Yrcos = sqrt(Yrcos); YIrcos = sqrt(1.0 - Yrcos.^2); lo0mask = pointOp(log_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); imdft = fftshift(fft2(im)); lo0dft = imdft .* lo0mask; [pyr,pind] = buildSFpyrLevs(lo0dft, log_rad, Xrcos, Yrcos, angle, ht, nbands); hi0mask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); hi0dft = imdft .* hi0mask; hi0 = ifft2(ifftshift(hi0dft)); pyr = [real(hi0(:)) ; pyr]; pind = [size(hi0); pind];
github
zhxing001/DIP_exercise-master
modulateFlip.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/modulateFlip.m
461
utf_8
92f12f8068fcf49b9863851f106a5aa3
% [HFILT] = modulateFlipShift(LFILT) % % QMF/Wavelet highpass filter construction: modulate by (-1)^n, % reverse order (and shift by one, which is handled by the convolution % routines). This is an extension of the original definition of QMF's % (e.g., see Simoncelli90). % Eero Simoncelli, 7/96. function [hfilt] = modulateFlipShift(lfilt) lfilt = lfilt(:); sz = size(lfilt,1); sz2 = ceil(sz/2); ind = [sz:-1:1]'; hfilt = lfilt(ind) .* (-1).^(ind-sz2);
github
zhxing001/DIP_exercise-master
spyrNumBands.m
.m
DIP_exercise-master/matlab/denoiseBLS_GSM/Simoncelli_PyrTools/spyrNumBands.m
480
utf_8
4a10cb68438c7dfc197ec00066f48fd4
% [NBANDS] = spyrNumBands(INDICES) % % Compute number of orientation bands in a steerable pyramid with % given index matrix. If the pyramid contains only the highpass and % lowpass bands (i.e., zero levels), returns 0. % Eero Simoncelli, 2/97. function [nbands] = spyrNumBands(pind) if (size(pind,1) == 2) nbands = 0; else % Count number of orientation bands: b = 3; while ((b <= size(pind,1)) & all( pind(b,:) == pind(2,:)) ) b = b+1; end nbands = b-2; end
github
ngcthuong/Caffe-DCS-master
Cal_PSNRSSIM.m
.m
Caffe-DCS-master/utilities/Cal_PSNRSSIM.m
6,250
utf_8
891b4e57ebcd097592850eecf97f150e
function [psnr_cur, ssim_cur] = Cal_PSNRSSIM(A,B,row,col) [n,m,ch]=size(B); A = A(row+1:n-row,col+1:m-col,:); B = B(row+1:n-row,col+1:m-col,:); A=double(A); % Ground-truth B=double(B); % e=A(:)-B(:); mse=mean(e.^2); psnr_cur=10*log10(255^2/mse); if ch==1 [ssim_cur, ~] = ssim_index(A, B); else ssim_cur = -1; end function [mssim, ssim_map] = ssim_index(img1, img2, K, window, L) %======================================================================== %SSIM Index, Version 1.0 %Copyright(c) 2003 Zhou Wang %All Rights Reserved. % %The author is with Howard Hughes Medical Institute, and Laboratory %for Computational Vision at Center for Neural Science and Courant %Institute of Mathematical Sciences, New York University. % %---------------------------------------------------------------------- %Permission to use, copy, or modify this software and its documentation %for educational and research purposes only and without fee is hereby %granted, provided that this copyright notice and the original authors' %names appear on all copies and supporting documentation. This program %shall not be used, rewritten, or adapted as the basis of a commercial %software or hardware product without first obtaining permission of the %authors. The authors make no representations about the suitability of %this software for any purpose. It is provided "as is" without express %or implied warranty. %---------------------------------------------------------------------- % %This is an implementation of the algorithm for calculating the %Structural SIMilarity (SSIM) index between two images. Please refer %to the following paper: % %Z. Wang, A. C. Bovik, H. R. Sheikh, and E. P. Simoncelli, "Image %quality assessment: From error measurement to structural similarity" %IEEE Transactios on Image Processing, vol. 13, no. 1, Jan. 2004. % %Kindly report any suggestions or corrections to [email protected] % %---------------------------------------------------------------------- % %Input : (1) img1: the first image being compared % (2) img2: the second image being compared % (3) K: constants in the SSIM index formula (see the above % reference). defualt value: K = [0.01 0.03] % (4) window: local window for statistics (see the above % reference). default widnow is Gaussian given by % window = fspecial('gaussian', 11, 1.5); % (5) L: dynamic range of the images. default: L = 255 % %Output: (1) mssim: the mean SSIM index value between 2 images. % If one of the images being compared is regarded as % perfect quality, then mssim can be considered as the % quality measure of the other image. % If img1 = img2, then mssim = 1. % (2) ssim_map: the SSIM index map of the test image. The map % has a smaller size than the input images. The actual size: % size(img1) - size(window) + 1. % %Default Usage: % Given 2 test images img1 and img2, whose dynamic range is 0-255 % % [mssim ssim_map] = ssim_index(img1, img2); % %Advanced Usage: % User defined parameters. For example % % K = [0.05 0.05]; % window = ones(8); % L = 100; % [mssim ssim_map] = ssim_index(img1, img2, K, window, L); % %See the results: % % mssim %Gives the mssim value % imshow(max(0, ssim_map).^4) %Shows the SSIM index map % %======================================================================== if (nargin < 2 || nargin > 5) ssim_index = -Inf; ssim_map = -Inf; return; end if (size(img1) ~= size(img2)) ssim_index = -Inf; ssim_map = -Inf; return; end [M N] = size(img1); if (nargin == 2) if ((M < 11) || (N < 11)) ssim_index = -Inf; ssim_map = -Inf; return end window = fspecial('gaussian', 11, 1.5); % K(1) = 0.01; % default settings K(2) = 0.03; % L = 255; % end if (nargin == 3) if ((M < 11) || (N < 11)) ssim_index = -Inf; ssim_map = -Inf; return end window = fspecial('gaussian', 11, 1.5); L = 255; if (length(K) == 2) if (K(1) < 0 || K(2) < 0) ssim_index = -Inf; ssim_map = -Inf; return; end else ssim_index = -Inf; ssim_map = -Inf; return; end end if (nargin == 4) [H W] = size(window); if ((H*W) < 4 || (H > M) || (W > N)) ssim_index = -Inf; ssim_map = -Inf; return end L = 255; if (length(K) == 2) if (K(1) < 0 || K(2) < 0) ssim_index = -Inf; ssim_map = -Inf; return; end else ssim_index = -Inf; ssim_map = -Inf; return; end end if (nargin == 5) [H W] = size(window); if ((H*W) < 4 || (H > M) || (W > N)) ssim_index = -Inf; ssim_map = -Inf; return end if (length(K) == 2) if (K(1) < 0 || K(2) < 0) ssim_index = -Inf; ssim_map = -Inf; return; end else ssim_index = -Inf; ssim_map = -Inf; return; end end C1 = (K(1)*L)^2; C2 = (K(2)*L)^2; window = window/sum(sum(window)); img1 = double(img1); img2 = double(img2); mu1 = filter2(window, img1, 'valid'); mu2 = filter2(window, img2, 'valid'); mu1_sq = mu1.*mu1; mu2_sq = mu2.*mu2; mu1_mu2 = mu1.*mu2; sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq; sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq; sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2; if (C1 > 0 & C2 > 0) ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2)); else numerator1 = 2*mu1_mu2 + C1; numerator2 = 2*sigma12 + C2; denominator1 = mu1_sq + mu2_sq + C1; denominator2 = sigma1_sq + sigma2_sq + C2; ssim_map = ones(size(mu1)); index = (denominator1.*denominator2 > 0); ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index)); index = (denominator1 ~= 0) & (denominator2 == 0); ssim_map(index) = numerator1(index)./denominator1(index); end mssim = mean2(ssim_map); return
github
scilab/scilab2c-master
tols.m
.m
scilab2c-master/toyApplication/tols.m
4,661
utf_8
b67703ed2f505e1b8dd21ac875ee5562
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [y, fullframes, loops] = tols(x, h, L) % perform time-partitioned overlap save algorithm % x -- signal (vector) % h -- impulse response (vector) % L -- fft size (frame length for impulse response segmentation is L/2) % y -- convolution result % fullframes -- number of full signal frames processed % loops -- number of total loops % % @author gregor heinrich :: arbylon % @date Nov./Dec. 2006 % fft size for signal and stepping % (only for notation) K = L / 2; % (only for notation; is always = K) S = L - K; % segment impulse response [HH, R] = segmentir(h, K); % original length of x (without zero-padding the first frame) lenx = length(x); % zero-padding of first frame ("saved zeroth frame") x = [zeros(K,1); x]; fprintf('padding %i zeros in front of x\n', K); y = []; % window of input signal frame spectra % @real-time: can be implemented as circular buffer XX = zeros(L, R); % number of full frames from the input % @real-time: unknown fullframes = floor((length(x)-L)/S) + 1; fprintf('expect %i full input frames and %i IR frames.\n', fullframes, R); % signal frames available (including partial ones) hassignal = 1; % more tail frames needed to complete convolution hastail = 1; i = 0; % @real-time: we don't know when the signal ends, thus we don't use the % fullframes variable in a for loop while hassignal || hastail icirc = mod(i, R) + 1; % index into x where xx starts and ends (includes zero-padding) xxstart = i * S + 1; xxend = i * S + L; if xxend <= length(x) % complete signal frame xx = x(xxstart : xxend); % fprintf(' - signal over full frame\n'); elseif xxstart <= length(x) % incomplete signal frame -> must be zero-padded % @real-time: signal ending is started xx = x(xxstart : end); zpad = xxend - length(x); xx = [xx; zeros(zpad, 1)]; fprintf(' - loop %i: signal incomplete, padding %i zeroes\n', i+1, zpad); else % @real-time: there are no samples from the input left; signal % ending is finished; convolution ending is started if hassignal hassignal = 0; % xframes should be exactly = fullframes xframes = i - 1; fprintf(' - loop %i: signal finished, processing tail only.\n', i + 1); end end % drop oldest frame and add new one % @real-time: can be implemented using a circular buffer if (i >= R) rend = R; else % before all ir frames are filled rend = i + 1; end if hassignal % more signal samples available X = fft(xx, L); % for debugging with 1:n: X = round(ifft(X)); XX(:, icirc) = X; rstart = 1; else % @real-time: during convolution ending rstart = i - xframes + 1; end % total length of y ylen = lenx + length(h) - 1; % end of output larger than expected result? yyend = S*(i+1); if yyend > ylen hassignal = 0; hastail = 0; loops = i; end % add most recent frame to convolution result if hastail == 1 yylen = S; y = [y; zeros(S,1)]; else yylen = S - (yyend - ylen); y = [y; zeros(yylen,1)]; loops = i; end % @real-time: loops over r can be done in parallel, also between % subsequent loops over i for r=rstart:rend rcirc = mod(i - (r - 1), R) + 1; % calculate partial convolution Y = XX(:,rcirc) .* HH(:,r); yy = ifft(Y, L); % select last L-K points yy = yy(S+1:L); % add contribution of signal and ir with r frames offset y(end-yylen+1:end) = y(end-yylen+1:end) + yy(1:yylen); end i = i+1; end % while fprintf(' - total loops: %i\n', i); % TODO: make this independent of xlen %y = y(1:ylen); endfunction % convolve %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [HH, R] = segmentir(h, K) % segment impulse response into columns, the last % frame/column is zero-padded as needed. % HH -- matrix of impulse response frames % R -- number of IR frames (=columns of HH) L = 2 * K; fullframes = ceil(length(h)/K) - 1; for i=1:fullframes % column-wise IR frames hh(:,i) = h(K*(i-1)+1 : K*i); end if mod(length(h), K) ~= 0 % zero-pad last ir frame hlast = h((fullframes*K+1):length(h)); hlast = [hlast ; zeros(K - length(hlast),1)]; hh(:,fullframes+1) = hlast; end % column ffts HH = fft(hh, L); % for debugging 1:n: HH = round(ifft(HH)); R = size(HH,2); endfunction % segmentir
github
jamessealesmith/nn_trainer_wc-master
prepare_workspace.m
.m
nn_trainer_wc-master/prepare_workspace.m
294
utf_8
3676b95eaf370e19d1784b9496fb2469
%% Prepare Workspace function logS = prepare_workspace() % get name of log file formatOut = 'mm_dd_yy'; logS = strcat('Logs/',datestr(now,formatOut)); % add folders to path addpath('TrainingAlgorithms','BackpropFunctions','SupportFunctions',... 'Data','CustomFunctions'); warning off end
github
BrainardLab/VirtualWorldPsychophysics-master
save2pdf.m
.m
VirtualWorldPsychophysics-master/toolbox/utilities/save2pdf.m
2,141
utf_8
7332049e1c11bf187f8100ce13f1a901
%SAVE2PDF Saves a figure as a properly cropped pdf % % save2pdf(pdfFileName,handle,dpi) % % - pdfFileName: Destination to write the pdf to. % - handle: (optional) Handle of the figure to write to a pdf. If % omitted, the current figure is used. Note that handles % are typically the figure number. % - dpi: (optional) Integer value of dots per inch (DPI). Sets % resolution of output pdf. Note that 150 dpi is the Matlab % default and this function's default, but 600 dpi is typical for % production-quality. % % Saves figure as a pdf with margins cropped to match the figure size. % (c) Gabe Hoffmann, [email protected] % Written 8/30/2007 % Revised 9/22/2007NARGOUTCHK % Revised 1/14/2007 function save2pdf(pdfFileName,handle,dpi) % Verify correct number of arguments error(nargoutchk(0,3,nargin)); % If no handle is provided, use the current figure as default if nargin<1 [fileName,pathName] = uiputfile('*.pdf','Save to PDF file:'); if fileName == 0; return; end pdfFileName = [pathName,fileName]; end if nargin<2 handle = gcf; end if nargin<3 dpi = 150; end % Backup previous settings prePaperType = get(handle,'PaperType'); prePaperUnits = get(handle,'PaperUnits'); preUnits = get(handle,'Units'); prePaperPosition = get(handle,'PaperPosition'); prePaperSize = get(handle,'PaperSize'); % Make changing paper type possible set(handle,'PaperType','<custom>'); % Set units to all be the same set(handle,'PaperUnits','inches'); set(handle,'Units','inches'); % Set the page size and position to match the figure's dimensions paperPosition = get(handle,'PaperPosition'); position = get(handle,'Position'); set(handle,'PaperPosition',[0,0,position(3:4)]); set(handle,'PaperSize',position(3:4)); % Save the pdf (this is the same method used by "saveas") print(handle,'-dpdf',pdfFileName,sprintf('-r%d',dpi)) % Restore the previous settings set(handle,'PaperType',prePaperType); set(handle,'PaperUnits',prePaperUnits); set(handle,'Units',preUnits); set(handle,'PaperPosition',prePaperPosition); set(handle,'PaperSize',prePaperSize);
github
BrainardLab/VirtualWorldPsychophysics-master
drawPsychometricFunction.m
.m
VirtualWorldPsychophysics-master/toolbox/utilities/drawPsychometricFunction.m
7,947
utf_8
8e40e0e5245a3c14afaef29a0eafd0eb
function thresholds = drawPsychometricFunction(varargin) %%drawPsychometricFunction : draw psychometric function for lightness experiment % % Usage: % drawPsychometricFunction(); % % Description: % Draw psychometirc function for the response of subjects for lightness % experiment. The function needs the directory name of case being studied, % the subject name and the file number. It save the plot in the analysis % directory specified in the pref % % Input: % None % % Output: % 'thresholds' : struct with these options thresholds.U thresholds.L % thresholds.PSE thresholds.thresholds thresholds.fractionCorrect % thresholds.stimPerLevel thresholds.cmpY % % % Optional key/value pairs: % 'directoryName' : (string) Directory name of the case which will be studied (default 'ExampleDirectory') % 'subjectName' : (string) Name of subject (default 'testSubject') % 'fileNumber' : (scalar) (default 1) % 'thresholdU' : (scalar) Upper Threshold % 'thresholdL' : (scalar) Lower Threshold %% Get inputs and defaults. parser = inputParser(); parser.addParameter('experimentType', 'Lightness', @ischar); parser.addParameter('directoryName', 'ExampleCase', @ischar); parser.addParameter('subjectName', 'testSubject', @ischar); parser.addParameter('dateString', datestr(now,1), @ischar); parser.addParameter('fileNumber', 1, @isscalar); parser.addParameter('thresholdU', 0.75, @isscalar); parser.addParameter('thresholdL', 0.25, @isscalar); parser.parse(varargin{:}); experimentType = parser.Results.experimentType; directoryName = parser.Results.directoryName; subjectName = parser.Results.subjectName; dateString = parser.Results.dateString; fileNumber = parser.Results.fileNumber; thresholdU = parser.Results.thresholdU; thresholdL = parser.Results.thresholdL; projectName = 'VirtualWorldPsychophysics'; %% Load the data struct dataFolder = fullfile(getpref(projectName,'dataDir'), experimentType, directoryName, subjectName, dateString); dataFile = sprintf('%s/%s-%d.mat', dataFolder,subjectName, fileNumber); fprintf('\nData will be loaded from:\n%s\n', dataFile); tempData = load(dataFile); data = tempData.data; clear tempData; %% for ii = 1:length(data.trialStruct.cmpY) trialsWithThisCmpLvl = find( data.trialStruct.cmpY(ii) == data.trialStruct.cmpYInTrial); numberOfCorrectResponses = (data.response.actualResponse(trialsWithThisCmpLvl) == data.response.correctResponse(trialsWithThisCmpLvl)); if (data.trialStruct.cmpY(ii) < data.trialStruct.stdY) fractionCorrect(ii) = 1 - mean(numberOfCorrectResponses); totalCorrectResponse(ii) = length(numberOfCorrectResponses) - sum(numberOfCorrectResponses); else fractionCorrect(ii) = mean(numberOfCorrectResponses); totalCorrectResponse(ii) = sum(numberOfCorrectResponses); end end thresholds.stimPerLevel = length(numberOfCorrectResponses); hFig = figure(); yLimits = [-0.05 1.05]; xLimits = [(min(data.trialStruct.cmpY) - min(diff(data.trialStruct.cmpY))/2) ... (max(data.trialStruct.cmpY)+ min(diff(data.trialStruct.cmpY))/2)]; set(hFig,'units','pixels', 'Position', [1 1 600 500]); hold on; box on; % plot a vertical line indicating the standard lStdY = plot([data.trialStruct.stdY data.trialStruct.stdY], yLimits,':r','LineWidth', 1); % Psychometric function form PF = @PAL_CumulativeNormal; % Alternatives: PAL_Gumbel, PAL_Weibull, PAL_CumulativeNormal, PAL_HyperbolicSecant % paramsFree is a boolean vector that determins what parameters get % searched over. 1: free parameter, 0: fixed parameter paramsFree = [1 1 1 1]; % Initial guess. Setting the first parameter to the middle of the stimulus % range and the second to 1 puts things into a reasonable ballpark here. paramsValues0 = [mean(data.trialStruct.cmpY) 1/((max(data.trialStruct.cmpY)-min(data.trialStruct.cmpY))) 0 0]; lapseLimits = [0 0.05]; % Set up standard options for Palamedes search options = PAL_minimize('options'); % Fit with Palemedes Toolbox. The parameter constraints match the psignifit parameters above. Some thinking is % required to initialize the parameters sensibly. We know that the mean of the cumulative normal should be % roughly within the range of the comparison stimuli, so we initialize this to the mean. The standard deviation % should be some moderate fraction of the range of the stimuli, so again this is used as the initializer. xx = linspace(xLimits(1), xLimits(2),1000); [paramsValues] = PAL_PFML_Fit(... data.trialStruct.cmpY',totalCorrectResponse',length(numberOfCorrectResponses)*ones(size(data.trialStruct.cmpY')), ... paramsValues0,paramsFree,PF, ... 'lapseLimits',lapseLimits,'guessLimits',[],'searchOptions',options,'gammaEQlambda',true); yy = PF(paramsValues,xx'); psePal = PF(paramsValues,0.5,'inverse'); threshPal = PF(paramsValues,0.7602,'inverse')-psePal; text(min(data.trialStruct.cmpY),0.475,... ['PSE = ', num2str(psePal,3)],... 'FontSize', 15); % Test to indicate the stimulusIntensities of 75% marker text(min(data.trialStruct.cmpY),0.55,... ['Threshold = ', num2str(threshPal,3)],... 'FontSize', 15); % Test to indicate the stimulusIntensities of 75% marker % Plot Fit Line lTh = plot(xx, yy, 'LineWidth', 1); % Plot Raw Data % comparison lData = plot(data.trialStruct.cmpY,fractionCorrect,'*'); % Indicate 75% threshold thresholdIndex = find(yy > thresholdU, 1); % find threshold if ~isempty(thresholdIndex) plot([xx(1)-1 xx(thresholdIndex)],[yy(thresholdIndex) yy(thresholdIndex)],'k'); % Horizontal line plot([xx(thresholdIndex) xx(thresholdIndex)],[yLimits(1) yy(thresholdIndex)],'k'); % Vertical line lThMk = plot(xx(thresholdIndex),yy(thresholdIndex),'.k','MarkerSize',20); % 75% co-ordiante marker text(min(data.trialStruct.cmpY),0.9,... ['(' num2str(xx(thresholdIndex),3) ',' num2str(round(thresholdU*100)) '%)'],... 'FontSize', 15); % Test to indicate the stimulusIntensities of 75% marker end thresholds.U = xx(thresholdIndex); % Indicate 25% threshold thresholdIndex = find(yy > thresholdL, 1); % find threshold if ~isempty(thresholdIndex) plot([xx(1)-1 xx(thresholdIndex)],[yy(thresholdIndex) yy(thresholdIndex)],'k'); % Horizontal line plot([xx(thresholdIndex) xx(thresholdIndex)],[yLimits(1) yy(thresholdIndex)],'k'); % Vertical line lThMk = plot(xx(thresholdIndex),yy(thresholdIndex),'.k','MarkerSize',20); % 25% co-ordiante marker text(min(data.trialStruct.cmpY),0.4,... ['(' num2str(xx(thresholdIndex),3) ',' num2str(round(thresholdL*100)) '%)'],... 'FontSize', 15); % Test to indicate the stimulusIntensities of 75% marker end thresholds.L = xx(thresholdIndex); legend([lData lTh lStdY],... {'Observation', 'Cum Gauss', 'Standard'},... 'Location','Southeast'); xlabel('Comparison Lightness'); ylabel(['Fraction Comparison Chosen (N per level =',num2str(length(trialsWithThisCmpLvl)),')']); title(sprintf('%s-%d', subjectName, fileNumber),'interpreter','none'); xlim(xLimits); ylim(yLimits); xticks(data.trialStruct.cmpY); hAxis = gca; set(hAxis,'FontSize',15); hAxis.XTickLabelRotation = 90; %% Save the plot and the analysis data analysisFolder = fullfile(getpref(projectName,'analysisDir'), experimentType, directoryName, subjectName, dateString); if ~exist(fullfile(analysisFolder,'plots'), 'dir') mkdir(fullfile(analysisFolder,'plots')); end figureFile = sprintf('%s/plots/%s-%d.pdf', analysisFolder,subjectName, fileNumber); fprintf('\nPlot will be saved in folder:\n%s\n', figureFile); save2pdf(figureFile, hFig, 600); close; thresholds.cmpY = data.trialStruct.cmpY; thresholds.PSE = psePal; thresholds.threshold = threshPal; thresholds.fractionCorrect = fractionCorrect; end function SSE = fitcumgauss(guess, x, y) a = guess(1); mu = guess(2); sigma = guess(3); Est = a/(sigma*sqrt(2*pi)) * exp( -( (x-mu).^2 ./ (2.*sigma).^2 ) ); Est = cumsum(Est) ./ sum(Est); SSE = sum( (y - Est).^2 ); end
github
BrainardLab/VirtualWorldPsychophysics-master
runEasyTrials.m
.m
VirtualWorldPsychophysics-master/toolbox/utilities/runEasyTrials.m
6,719
utf_8
43348671a90b08248dd9abea56e35a31
function runEasyTrials(nEasyTrials, trialStruct, cal, scaleFactor, LMSStruct, params, controlSignal, win, gamePad, parser) % This function runs nEasyTrials number of easy trials at the beginning of % the experiment. These trials are not saved. keepLooping = 1; trialToRun = find(trialStruct.cmpYInTrial == max(trialStruct.cmpYInTrial),nEasyTrials); rightSound = sin(2*pi*[1:1000]/10)/10; wrongSound = rand(1,1000).*sin(2*pi*[1:1000]/10)/10; for iterTrials = trialToRun stdIndex = trialStruct.trialStdIndex(iterTrials); cmpIndex = trialStruct.trialCmpIndex(iterTrials); stdRGBImage = CalFormatToImage(SensorToSettings(cal, scaleFactor*LMSStruct.LMSImageInCalFormat(:,:,stdIndex)),LMSStruct.cropImageSizeX,LMSStruct.cropImageSizeY); cmpRGBImage = CalFormatToImage(SensorToSettings(cal, scaleFactor*LMSStruct.LMSImageInCalFormat(:,:,cmpIndex)),LMSStruct.cropImageSizeX,LMSStruct.cropImageSizeY); stdRGBImage(stdRGBImage < 0 ) = 0; cmpRGBImage(cmpRGBImage < 0 ) = 0; standardYLarger = (trialStruct.stdYInTrial(iterTrials) >= trialStruct.cmpYInTrial(iterTrials)); if trialStruct.cmpInterval(iterTrials) % comparison on the second interval firstImage = stdRGBImage(end:-1:1,:,:); secondImage = cmpRGBImage(end:-1:1,:,:); if standardYLarger correctResponse(iterTrials) = 1; else correctResponse(iterTrials) = 2; end else % comparison on the first firstImage = cmpRGBImage(end:-1:1,:,:); secondImage = stdRGBImage(end:-1:1,:,:); if standardYLarger correctResponse(iterTrials) = 2; else correctResponse(iterTrials) = 1; end end % Write the images into the window and disable win.addImage(params.firstImageLoc, params.firstImageSize, firstImage, 'Name', 'firstImage'); win.addImage(params.secondImageLoc, params.secondImageSize, secondImage, 'Name', 'secondImage'); win.disableObject('firstImage'); win.disableObject('secondImage'); % Enable "left" image and draw win.enableObject('firstImage'); win.draw; % Wait for duration mglWaitSecs(params.stimDuration); win.disableObject('firstImage'); win.draw; % Wait for ISI and show "second" image mglWaitSecs(params.ISI); win.enableObject('secondImage'); win.draw; % Wait for duration mglWaitSecs(params.stimDuration); win.disableObject('secondImage'); win.draw; %% Wait for key FlushEvents; key =[]; while (isempty(key)) % Get user response from keyboard if (strcmp(controlSignal, 'keyboard')) key = mglGetKeyEvent; if (~isempty(key)) switch key.charCode case {params.interval1Key,params.interval2Key} keyPress(iterTrials) = getUserResponse(params,key); case {'q'} fprintf('Do you want to quit? Press Y for Yes, otherwise give your response \n'); key2 = []; while (isempty(key2)) key2 = mglGetKeyEvent; if (~isempty(key2)) switch key2.charCode case {params.interval1Key,params.interval2Key} keyPress(iterTrials) = getUserResponse(params,key2); case {'y'} keepLooping = false; otherwise key2 = []; end end end otherwise key = []; end end % Get user response from gamePad else key = gamePad.getKeyEvent(); if (~isempty(key)) switch key.charCode case {params.interval1Key,params.interval2Key} keyPress(iterTrials) = getUserResponse(params,key); otherwise key = []; end end pressedKeyboard = mglGetKeyEvent; if (~isempty(pressedKeyboard)) switch pressedKeyboard.charCode case {'q'} fprintf('Do you want to quit? Press Y for Yes, otherwise give your response using gamepad \n'); key2 = []; keyG = []; FlushEvents; while (isempty(key2) && isempty(keyG)) key2 = mglGetKeyEvent; keyG = gamePad.getKeyEvent(); if (~isempty(key2)) switch key2.charCode case {'y'} keepLooping = false; key = 0; % set key = 0 in order to exit this loop otherwise key2 = []; end elseif (~isempty(keyG)) switch keyG.charCode case {params.interval1Key,params.interval2Key} key = keyG; keyPress(iterTrials) = getUserResponse(params,key); otherwise keyG = []; end end end end end end end % Check if the experiment continues, otherwise quit without saving data if keepLooping actualResponse(iterTrials) = keyPress(iterTrials); fprintf('The character typed was %d\n',keyPress(iterTrials)); % Give feedback if option is on if parser.Results.feedback if (actualResponse(iterTrials) == correctResponse(iterTrials)); sound(rightSound); else sound(wrongSound); end end mglWaitSecs(params.ITI); else fprintf('Quitting without saving any data.\n'); end end end function response = getUserResponse(params,key) response = []; switch key.charCode % Left/Down case params.interval1Key response = 1; % Right/Up case params.interval2Key response = 2; end % switch end
github
BrainardLab/VirtualWorldPsychophysics-master
runLightnessExperiment.m
.m
VirtualWorldPsychophysics-master/experiment/runLightnessExperiment.m
19,604
utf_8
6f4a343b577c46f34c88a3b2454da03d
function acquisitionStatus = runLightnessExperiment(varargin) %%runExperiment : run lightness estimation experiment and record data % % Usage: % runLightnessExperiment(); % % Description: % Run the lightness estimation psychophysics experiment given the % calibration file, trial struct and LMS stimulus struct. Record the % responses and save the responses in the specified directory. % % Input: % None % % Output: % None % % Optional key/value pairs: % 'directoryName' : (string) Directory name of the case which will be studied (default 'ExampleDirectory') % 'nameOfTrialStruct' : (string) Name of trail stuct to be used in experiment (defalult 'exampleTrial') % 'nameOfCalibrationFile : (string) Name of calibration file (default 'VirtualWorldCalibration.mat') % 'whichCalibration' : (scalar) Which calibration in file to use (default Inf -> most recent) % 'controlSignal' : (string) How to collect user response (options: 'gamePad', 'keyboard', default 'keyboard') % 'subjectName' : (string) Name of subject (default 'testSubject') %% Get inputs and defaults. parser = inputParser(); parser.addParameter('directoryName', 'ExampleCase', @ischar); parser.addParameter('nameOfTrialStruct', 'exampleTrial', @ischar); parser.addParameter('nameOfCalibrationFile', 'VirtualWorldCalibration', @ischar); parser.addParameter('scaleFactor', 0, @isscalar); parser.addParameter('whichCalibration', Inf, @isscalar); parser.addParameter('controlSignal', 'keyboard', @ischar); parser.addParameter('interval1Key', '1', @ischar); parser.addParameter('interval2Key', '2', @ischar); parser.addParameter('feedback', 0, @isscalar); parser.addParameter('isDemo', 0, @isscalar); parser.addParameter('subjectName', 'testSubject', @ischar); parser.addParameter('theoreticalPsychophysicsMode', 0, @isscalar); parser.parse(varargin{:}); directoryName = parser.Results.directoryName; nameOfTrialStruct = parser.Results.nameOfTrialStruct; nameOfCalibrationFile = parser.Results.nameOfCalibrationFile; whichCalibration = parser.Results.whichCalibration; scaleFactor = parser.Results.scaleFactor; controlSignal = parser.Results.controlSignal; interval1Key = parser.Results.interval1Key; interval2Key = parser.Results.interval2Key; subjectName = parser.Results.subjectName; theoreticalPsychophysicsMode = parser.Results.theoreticalPsychophysicsMode; projectName = 'VirtualWorldPsychophysics'; ExperimentType = 'Lightness'; % May want to change this to name the experiment cases differently caseName = directoryName; rightSound = sin(2*pi*[1:1000]/10)/10; wrongSound = rand(1,1000).*ceil(sin(2*pi*[1:1000]/10))/10; acquisitionStatus = 0; %% Some experimental parameters. % % May want to read these from a file at % some point. params.screenDimsCm = [59.67 33.57]; params.fpSize = [0.1 0.1]; % fixation point size params.fpColor = [34 70 34]/255; % fixation point color params.fpColorRed = [0.6 0.2 0.2]; % fixation point color red params.bgColor = [0 0 0]; params.textColor = [0.6 0.2 0.2]; params.firstImageLoc = [0 0]; params.secondImageLoc = [0 0]; params.firstImageSize = [2.62 2.62]; params.secondImageSize = [2.62 2.62]; params.ISI = 0.25; params.ITI = 0.25; params.stimDuration = 0.25; params.interval1Key = interval1Key; params.interval2Key = interval2Key; % If the game pad has symbol 1 2 3 4, instead of X A B Y if strcmp(interval1Key,'GP:1') params.interval1Key = 'GP:UpperLeftTrigger'; end if strcmp(interval2Key,'GP:2') params.interval2Key = 'GP:UpperRightTrigger'; end %% Load the trial struct pathToTrialStruct = fullfile(getpref(projectName,'stimulusInputBaseDir'),... directoryName,[nameOfTrialStruct '.mat']); temp = load(pathToTrialStruct); trialStruct = temp.trialStruct; clear temp; %% Load the LMS struct LMSstructName = trialStruct.LMSstructName; pathToLMSStruct = fullfile(getpref(projectName,'stimulusInputBaseDir'),... directoryName,[LMSstructName '.mat']); temp = load(pathToLMSStruct); LMSStruct = temp.LMSStruct; clear temp; %% Load calibration file cal = LoadCalFile(nameOfCalibrationFile,whichCalibration,fullfile(getpref('VirtualWorldPsychophysics','calibrationDir'))); if (isempty(cal)) error('Could not find specified calibration file'); end %% Initialize calibration structure for the cones cal = SetSensorColorSpace(cal, LMSStruct.T_cones, LMSStruct.S); % Fix the last option %% Find the scale factor if (scaleFactor == 0) scaleFactor = findScaleFactor(cal, LMSStruct); end %% Set Gamma Method cal = SetGammaMethod(cal,0); %% Start Time of Experiment startTime = datestr(now); %% Now loop over the images for presentation on screen % Before that figure out how long it takes to convert two LMS to RGB and % present on screen. Shouldn't be very long response = struct('subjectName',subjectName, ... 'correctResponse',[],... 'actualResponse',[]); %% Initiale display [win, params] = initDisplay(params); %% Start key capture and clear keyboard queue before we draw the stimuli. ListenChar(2); mglGetKeyEvent; % Instantiate a gamePad object if (strcmp(controlSignal, 'gamePad')) gamePad = GamePad(); else gamePad = []; end % Clear out any previous keypresses. FlushEvents; %% Enable fixation and start text win.enableObject('fp'); win.enableObject('startText'); win.enableObject('keyOptions'); win.draw; %% Wait for key % keyPress = GetChar; key = []; while (isempty(key)) if (strcmp(controlSignal, 'keyboard')) key = mglGetKeyEvent; else key = gamePad.getKeyEvent(); end end %% Turn off start text, add images and wait for another key win.disableObject('startText'); win.disableObject('keyOptions'); % Run easy trials nEasyTrials = 5; runEasyTrials(nEasyTrials, trialStruct, cal, scaleFactor, LMSStruct, params, controlSignal, win, gamePad, parser); % Reset the keyboard queue. mglGetKeyEvent; saveData = 1; keepLooping = 1; iterTrials = 0; while keepLooping iterTrials = iterTrials + 1; stdIndex = trialStruct.trialStdIndex(iterTrials); cmpIndex = trialStruct.trialCmpIndex(iterTrials); stdRGBImage = CalFormatToImage(SensorToSettings(cal, scaleFactor*LMSStruct.LMSImageInCalFormat(:,:,stdIndex)),LMSStruct.cropImageSizeX,LMSStruct.cropImageSizeY); cmpRGBImage = CalFormatToImage(SensorToSettings(cal, scaleFactor*LMSStruct.LMSImageInCalFormat(:,:,cmpIndex)),LMSStruct.cropImageSizeX,LMSStruct.cropImageSizeY); stdRGBImage(stdRGBImage < 0 ) = 0; cmpRGBImage(cmpRGBImage < 0 ) = 0; standardYLarger = (trialStruct.stdYInTrial(iterTrials) >= trialStruct.cmpYInTrial(iterTrials)); if trialStruct.cmpInterval(iterTrials) % comparison on the second interval firstImage = stdRGBImage(end:-1:1,:,:); secondImage = cmpRGBImage(end:-1:1,:,:); if standardYLarger correctResponse(iterTrials) = 1; else correctResponse(iterTrials) = 2; end else % comparison on the first firstImage = cmpRGBImage(end:-1:1,:,:); secondImage = stdRGBImage(end:-1:1,:,:); if standardYLarger correctResponse(iterTrials) = 2; else correctResponse(iterTrials) = 1; end end if theoreticalPsychophysicsMode meanRGBFirstImage = mean(mean(mean(firstImage(floor(LMSStruct.cropImageSizeX/2)-4:floor(LMSStruct.cropImageSizeX/2)+5, ... floor(LMSStruct.cropImageSizeX/2)-4:floor(LMSStruct.cropImageSizeX/2)+5,:)))); meanRGBSecondImage = mean(mean(mean(secondImage(floor(LMSStruct.cropImageSizeX/2)-4:floor(LMSStruct.cropImageSizeX/2)+5, ... floor(LMSStruct.cropImageSizeX/2)-4:floor(LMSStruct.cropImageSizeX/2)+5,:)))); keyPress(iterTrials) = (meanRGBSecondImage > meanRGBFirstImage) + 1; actualResponse(iterTrials) = keyPress(iterTrials); else % For testing, extract average RGB values from center of first and % second image, and figure out which is bigger % Write the images into the window and disable win.addImage(params.firstImageLoc, params.firstImageSize, firstImage, 'Name', 'firstImage'); win.addImage(params.secondImageLoc, params.secondImageSize, secondImage, 'Name', 'secondImage'); win.disableObject('firstImage'); win.disableObject('secondImage'); % Enable "left" image and draw win.enableObject('firstImage'); win.draw; % Wait for duration mglWaitSecs(params.stimDuration); win.disableObject('firstImage'); win.draw; % Wait for ISI and show "second" image mglWaitSecs(params.ISI); win.enableObject('secondImage'); win.draw; % Wait for duration mglWaitSecs(params.stimDuration); win.disableObject('secondImage'); win.draw; %% Wait for key FlushEvents; key =[]; while (isempty(key)) % Get user response from keyboard if (strcmp(controlSignal, 'keyboard')) key = mglGetKeyEvent; if (~isempty(key)) switch key.charCode case {params.interval1Key,params.interval2Key} keyPress(iterTrials) = getUserResponse(params,key); case {'q'} fprintf('Do you want to quit? Press Y for Yes, otherwise give your response \n'); key2 = []; while (isempty(key2)) key2 = mglGetKeyEvent; if (~isempty(key2)) switch key2.charCode case {params.interval1Key,params.interval2Key} keyPress(iterTrials) = getUserResponse(params,key2); case {'y'} keepLooping = false; otherwise key2 = []; end end end otherwise key = []; end end % Get user response from gamePad else key = gamePad.getKeyEvent(); if (~isempty(key)) switch key.charCode case {params.interval1Key,params.interval2Key} keyPress(iterTrials) = getUserResponse(params,key); otherwise key = []; end end pressedKeyboard = mglGetKeyEvent; if (~isempty(pressedKeyboard)) switch pressedKeyboard.charCode case {'q'} fprintf('Do you want to quit? Press Y for Yes, otherwise give your response using gamepad \n'); key2 = []; keyG = []; FlushEvents; while (isempty(key2) && isempty(keyG)) key2 = mglGetKeyEvent; keyG = gamePad.getKeyEvent(); if (~isempty(key2)) switch key2.charCode case {'y'} keepLooping = false; key = 0; % set key = 0 in order to exit this loop otherwise key2 = []; end elseif (~isempty(keyG)) switch keyG.charCode case {params.interval1Key,params.interval2Key} key = keyG; keyPress(iterTrials) = getUserResponse(params,key); otherwise keyG = []; end end end end end end end % Check if the experiment continues, otherwise quit without saving data if keepLooping actualResponse(iterTrials) = keyPress(iterTrials); fprintf('The character typed was %d\n',keyPress(iterTrials)); % Give feedback if option is on if parser.Results.feedback if (actualResponse(iterTrials) == correctResponse(iterTrials)); sound(rightSound); else sound(wrongSound); end end mglWaitSecs(params.ITI); else fprintf('Quitting without saving any data.\n'); saveData = 0; end %% Check if one third of experiment is reached if (iterTrials == ceil(length(trialStruct.trialStdIndex)/3)) win.enableObject('oneThirdText'); win.disableObject('fp'); win.enableObject('fpRed'); win.draw; pause(60); win.disableObject('oneThirdText'); win.enableObject('restOver'); win.disableObject('fpRed'); win.enableObject('fp'); win.draw; FlushEvents; %% Wait for key if (strcmp(controlSignal, 'keyboard')) key = []; while (isempty(key)) key = mglGetKeyEvent; end else key = []; while (isempty(key)) key = gamePad.getKeyEvent(); end end % Turn off text win.disableObject('restOver'); % Reset the keyboard queue. mglGetKeyEvent; end %% Check if two third of experiment is reached if (iterTrials == ceil(2*length(trialStruct.trialStdIndex)/3)) win.enableObject('twoThirdText'); win.disableObject('fp'); win.enableObject('fpRed'); win.draw; pause(60); win.disableObject('twoThirdText'); win.enableObject('restOver'); win.disableObject('fpRed'); win.enableObject('fp'); win.draw; FlushEvents; %% Wait for key if (strcmp(controlSignal, 'keyboard')) key = []; while (isempty(key)) key = mglGetKeyEvent; end else key = []; while (isempty(key)) key = gamePad.getKeyEvent(); end end %% Turn off start text, add images and wait for another key win.disableObject('restOver'); % Reset the keyboard queue. mglGetKeyEvent; end % Check if end of experiment is reached end if (iterTrials == length(trialStruct.trialStdIndex)) keepLooping = false; end end %% Done with experiment, close up % % Show end of experimetn text win.enableObject('finishText'); win.draw; pause(10); win.disableObject('finishText'); % Close our display. win.close; % Make sure key capture is off. ListenChar(0); if parser.Results.isDemo saveData = 0; end if saveData %% correct response can be found as response.correctResponse = correctResponse; response.actualResponse = actualResponse; response.keyPress = keyPress; %% End Time of Experiment endTime = datestr(now); %% Make data struct data = struct; data.response = response; data.trialStruct = trialStruct; data.startTime = startTime; data.endTime = endTime; data.cal = cal; data.LMSStruct = LMSStruct; data.subjectName = subjectName; %% Save data here % Figure out some data saving parameters. dataFolder = fullfile(getpref(projectName,'dataDir'), ExperimentType, caseName, subjectName, datestr(now,1)); if ~exist(dataFolder, 'dir') mkdir(dataFolder); end dataFile = sprintf('%s/%s-%d.mat', dataFolder,subjectName, GetNextDataFileNumber(dataFolder, '.mat')); fprintf('\nData will be saved in:\n%s\n', dataFile); save(dataFile,'data','-v7.3'); fprintf('Data was saved.\n'); drawPsychometricFunction('ExperimentType', ExperimentType,... 'directoryName', caseName, ... 'subjectName', subjectName, ... 'date', datestr(now,1), ... 'fileNumber', (GetNextDataFileNumber(dataFolder, '.mat')-1),... 'thresholdU', 0.75, ... 'thresholdL', 0.25); acquisitionStatus = 1; end end % % %% Save the response struct % path2RGBOutputDirectory = fullfile(getpref(projectName,'stimulusInputBaseDir'),... % parser.Results.directoryName); % outputfileName = fullfile(path2RGBOutputDirectory,[outputFileName,'.mat']); % save(outputfileName,'S','-v7.3'); function [win, params] = initDisplay(params) % Create the GLWindow object and linearize the clut. win = GLWindow('SceneDimensions', params.screenDimsCm, ... 'BackgroundColor', params.bgColor); try % Open the display. win.open; % Add the fixation point. win.addOval([0 0], params.fpSize, params.fpColor, 'Name', 'fp'); % Add the fixation point in red color. win.addOval([0 0], params.fpSize, params.fpColorRed, 'Name', 'fpRed'); % Add text win.addText('Hit any button to start', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'startText'); % Identifier for the object. % Add text win.addText(['Key :', 'Interval 1 -> ', params.interval1Key,' Interval 2 -> ',params.interval2Key ], ... % Text to display 'Center', [0 -8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'keyOptions'); % Identifier for the object. % Add text win.addText('One third of trials over. Take 1 minute rest.', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'oneThirdText'); % Identifier for the object. % Add text win.addText('Rest over. Hit any button to continue', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'restOver'); % Identifier for the object. % Add text win.addText('Two third of trials over. Take 1 minute rest.', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'twoThirdText'); % Identifier for the object. % Add text win.addText('Experiment finished.', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'finishText'); % Identifier for the object. % Turn all objects off for now. win.disableAllObjects; catch e win.close; rethrow(e); end end function response = getUserResponse(params,key) response = []; switch key.charCode % Left/Down case params.interval1Key response = 1; % Right/Up case params.interval2Key response = 2; end % switch end
github
BrainardLab/VirtualWorldPsychophysics-master
runExperimentArcade.m
.m
VirtualWorldPsychophysics-master/experiment/runExperimentArcade.m
17,687
utf_8
71670cdef8fd940daed6f91429124bb5
function results = runExperimentArcade(varargin) %%runExperiment : run lightness estimation experiment for the arcade game % % Usage: % runExperimentArcade(); % % Description: % Run the lightness estimation psychophysics experiment given the % calibration file, trial struct and LMS stimulus struct. Give the % resutls of how many correct responses in the end. % % Input: % None % % Output: % numberOfCorrectResponse % % Optional key/value pairs: % 'directoryName' : (string) Directory name of the case which will be studied (default 'ExampleDirectory') % 'nameOfTrialStruct' : (string) Name of trail stuct to be used in experiment (defalult 'exampleTrial') % 'nameOfCalibrationFile : (string) Name of calibration file (default 'VirtualWorldCalibration.mat') % 'whichCalibration' : (scalar) Which calibration in file to use (default Inf -> most recent) % 'controlSignal' : (string) How to collect user response (options: 'gamePad', 'keyboard', default 'keyboard') % 'subjectName' : (string) Name of subject (default 'testSubject') %% Get inputs and defaults. parser = inputParser(); parser.addParameter('directoryName', 'ExampleCase', @ischar); parser.addParameter('nameOfTrialStruct', 'exampleTrial', @ischar); parser.addParameter('nameOfCalibrationFile', 'VirtualWorldCalibration', @ischar); parser.addParameter('scaleFactor', 0, @isscalar); parser.addParameter('whichCalibration', Inf, @isscalar); parser.addParameter('controlSignal', 'keyboard', @ischar); parser.addParameter('interval1Key', '1', @ischar); parser.addParameter('interval2Key', '2', @ischar); parser.addParameter('feedback', 0, @isscalar); parser.addParameter('isDemo', 0, @isscalar); parser.addParameter('subjectName', 'testSubject', @ischar); parser.addParameter('theoreticalPsychophysicsMode', 0, @isscalar); parser.parse(varargin{:}); directoryName = parser.Results.directoryName; nameOfTrialStruct = parser.Results.nameOfTrialStruct; nameOfCalibrationFile = parser.Results.nameOfCalibrationFile; whichCalibration = parser.Results.whichCalibration; scaleFactor = parser.Results.scaleFactor; controlSignal = parser.Results.controlSignal; interval1Key = parser.Results.interval1Key; interval2Key = parser.Results.interval2Key; subjectName = parser.Results.subjectName; theoreticalPsychophysicsMode = parser.Results.theoreticalPsychophysicsMode; projectName = 'VirtualWorldPsychophysics'; rightSound = sin(2*pi*[1:1000]/10)/10; wrongSound = rand(1,1000).*sin(2*pi*[1:1000]/10)/10; %% Some experimental parameters. % % May want to read these from a file at % some point. params.screenDimsCm = [59.65 33.55]; params.fpSize = [0.1 0.1]; % fixation point size params.fpColor = [34 70 34]/255; % fixation point color params.bgColor = [0 0 0 0]; params.textColor = [0.6 0.2 0.2]; params.firstImageLoc = [0 0]; params.secondImageLoc = [0 0]; params.firstImageSize = [2.62 2.62]; params.secondImageSize = [2.62 2.62]; params.ISI = 0.25; params.ITI = 0.25; params.stimDuration = 0.25; params.interval1Key = interval1Key; params.interval2Key = interval2Key; results = [0 0]; % If the game pad has symbol 1 2 3 4, instead of X A B Y if strcmp(interval1Key,'GP:1') params.interval1Key = 'GP:UpperLeftTrigger'; end if strcmp(interval2Key,'GP:2') params.interval2Key = 'GP:UpperRightTrigger'; end %% Load the trial struct pathToTrialStruct = fullfile(getpref(projectName,'stimulusInputBaseDir'),... directoryName,[nameOfTrialStruct '.mat']); temp = load(pathToTrialStruct); trialStruct = temp.trialStruct; clear temp; %% Load the LMS struct LMSstructName = trialStruct.LMSstructName; pathToLMSStruct = fullfile(getpref(projectName,'stimulusInputBaseDir'),... directoryName,[LMSstructName '.mat']); temp = load(pathToLMSStruct); LMSStruct = temp.LMSStruct; clear temp; %% Load calibration file cal = LoadCalFile(nameOfCalibrationFile,whichCalibration,fullfile(getpref('VirtualWorldPsychophysics','calibrationDir'))); if (isempty(cal)) error('Could not find specified calibration file'); end %% Initialize calibration structure for the cones cal = SetSensorColorSpace(cal, LMSStruct.T_cones, LMSStruct.S); % Fix the last option %% Find the scale factor if (scaleFactor == 0) scaleFactor = findScaleFactor(cal, LMSStruct); end %% Set Gamma Method cal = SetGammaMethod(cal,0); %% Start Time of Experiment startTime = datestr(now); %% Now loop over the images for presentation on screen % Before that figure out how long it takes to convert two LMS to RGB and % present on screen. Shouldn't be very long response = struct('subjectName',subjectName, ... 'correctResponse',[],... 'actualResponse',[]); %% Initiate display [win, params] = initDisplay(params, results); %% Start key capture and clear keyboard queue before we draw the stimuli. ListenChar(2); mglGetKeyEvent; % Instantiate a gamePad object if (strcmp(controlSignal, 'gamePad')) gamePad = GamePad(); else gamePad = []; end % Clear out any previous keypresses. FlushEvents; %% Enable fixation and start text win.enableObject('fp'); win.enableObject('TrialStartText'); win.enableObject('keyOptions'); win.draw; %% Wait for key % keyPress = GetChar; key = []; while (isempty(key)) if (strcmp(controlSignal, 'keyboard')) key = mglGetKeyEvent; else key = gamePad.getKeyEvent(); end end %% Turn off start text, add images and wait for another key win.disableObject('TrialStartText'); win.disableObject('keyOptions'); % Run easy trials nEasyTrials = 5; runEasyTrials(nEasyTrials, trialStruct, cal, scaleFactor, LMSStruct, params, controlSignal, win, gamePad, parser); runEasyTrials(nEasyTrials, trialStruct, cal, scaleFactor, LMSStruct, params, controlSignal, win, gamePad, parser); win.enableObject('fp'); win.enableObject('PracticeOverText'); win.draw; pause(10); win.disableObject('PracticeOverText'); win.disableObject('keyOptions'); % Clear out any previous keypresses. FlushEvents; %% Enable fixation and start text win.enableObject('fp'); win.enableObject('RealSessionText'); win.enableObject('keyOptions'); win.draw; %% Wait for key % keyPress = GetChar; key = []; while (isempty(key)) if (strcmp(controlSignal, 'keyboard')) key = mglGetKeyEvent; else key = gamePad.getKeyEvent(); end end %% Turn off start text, add images and wait for another key win.disableObject('RealSessionText'); win.disableObject('keyOptions'); % Reset the keyboard queue. mglGetKeyEvent; saveData = 1; keepLooping = 1; iterTrials = 0; while keepLooping iterTrials = iterTrials + 1; stdIndex = trialStruct.trialStdIndex(iterTrials); cmpIndex = trialStruct.trialCmpIndex(iterTrials); stdRGBImage = CalFormatToImage(SensorToSettings(cal, scaleFactor*LMSStruct.LMSImageInCalFormat(:,:,stdIndex)),LMSStruct.cropImageSizeX,LMSStruct.cropImageSizeY); cmpRGBImage = CalFormatToImage(SensorToSettings(cal, scaleFactor*LMSStruct.LMSImageInCalFormat(:,:,cmpIndex)),LMSStruct.cropImageSizeX,LMSStruct.cropImageSizeY); stdRGBImage(stdRGBImage < 0 ) = 0; cmpRGBImage(cmpRGBImage < 0 ) = 0; standardYLarger = (trialStruct.stdYInTrial(iterTrials) >= trialStruct.cmpYInTrial(iterTrials)); if trialStruct.cmpInterval(iterTrials) % comparison on the second interval firstImage = stdRGBImage(end:-1:1,:,:); secondImage = cmpRGBImage(end:-1:1,:,:); if standardYLarger correctResponse(iterTrials) = 1; else correctResponse(iterTrials) = 2; end else % comparison on the first firstImage = cmpRGBImage(end:-1:1,:,:); secondImage = stdRGBImage(end:-1:1,:,:); if standardYLarger correctResponse(iterTrials) = 2; else correctResponse(iterTrials) = 1; end end if theoreticalPsychophysicsMode meanRGBFirstImage = mean(mean(mean(firstImage(floor(LMSStruct.cropImageSizeX/2)-4:floor(LMSStruct.cropImageSizeX/2)+5, ... floor(LMSStruct.cropImageSizeX/2)-4:floor(LMSStruct.cropImageSizeX/2)+5,:)))); meanRGBSecondImage = mean(mean(mean(secondImage(floor(LMSStruct.cropImageSizeX/2)-4:floor(LMSStruct.cropImageSizeX/2)+5, ... floor(LMSStruct.cropImageSizeX/2)-4:floor(LMSStruct.cropImageSizeX/2)+5,:)))); keyPress(iterTrials) = (meanRGBSecondImage > meanRGBFirstImage) + 1; actualResponse(iterTrials) = keyPress(iterTrials); else % For testing, extract average RGB values from center of first and % second image, and figure out which is bigger % Write the images into the window and disable win.addImage(params.firstImageLoc, params.firstImageSize, firstImage, 'Name', 'firstImage'); win.addImage(params.secondImageLoc, params.secondImageSize, secondImage, 'Name', 'secondImage'); win.disableObject('firstImage'); win.disableObject('secondImage'); % Enable "left" image and draw win.enableObject('firstImage'); win.draw; % Wait for duration mglWaitSecs(params.stimDuration); win.disableObject('firstImage'); win.draw; % Wait for ISI and show "second" image mglWaitSecs(params.ISI); win.enableObject('secondImage'); win.draw; % Wait for duration mglWaitSecs(params.stimDuration); win.disableObject('secondImage'); win.draw; %% Wait for key FlushEvents; key =[]; while (isempty(key)) % Get user response from keyboard if (strcmp(controlSignal, 'keyboard')) key = mglGetKeyEvent; if (~isempty(key)) switch key.charCode case {params.interval1Key,params.interval2Key} keyPress(iterTrials) = getUserResponse(params,key); case {'q'} fprintf('Do you want to quit? Press Y for Yes, otherwise give your response \n'); key2 = []; while (isempty(key2)) key2 = mglGetKeyEvent; if (~isempty(key2)) switch key2.charCode case {params.interval1Key,params.interval2Key} keyPress(iterTrials) = getUserResponse(params,key2); case {'y'} keepLooping = false; otherwise key2 = []; end end end otherwise key = []; end end % Get user response from gamePad else key = gamePad.getKeyEvent(); if (~isempty(key)) switch key.charCode case {params.interval1Key,params.interval2Key} keyPress(iterTrials) = getUserResponse(params,key); otherwise key = []; end end pressedKeyboard = mglGetKeyEvent; if (~isempty(pressedKeyboard)) switch pressedKeyboard.charCode case {'q'} fprintf('Do you want to quit? Press Y for Yes, otherwise give your response using gamepad \n'); key2 = []; keyG = []; FlushEvents; while (isempty(key2) && isempty(keyG)) key2 = mglGetKeyEvent; keyG = gamePad.getKeyEvent(); if (~isempty(key2)) switch key2.charCode case {'y'} keepLooping = false; key = 0; % set key = 0 in order to exit this loop otherwise key2 = []; end elseif (~isempty(keyG)) switch keyG.charCode case {params.interval1Key,params.interval2Key} key = keyG; keyPress(iterTrials) = getUserResponse(params,key); otherwise keyG = []; end end end end end end end % Check if the experiment continues, otherwise quit without saving data if keepLooping actualResponse(iterTrials) = keyPress(iterTrials); fprintf('The character typed was %d\n',keyPress(iterTrials)); % Give feedback if option is on if parser.Results.feedback if (actualResponse(iterTrials) == correctResponse(iterTrials)); sound(rightSound); else sound(wrongSound); end end mglWaitSecs(params.ITI); else fprintf('Quitting without saving any data.\n'); saveData = 0; end % Check if end of experiment is reached end if (iterTrials == length(trialStruct.trialStdIndex)) keepLooping = false; end end %% Done with experiment, close up % % Show end of experimetn text results(1) = sum(actualResponse == correctResponse); results(2) = length(actualResponse); win.close; [win, params] = initDisplay(params, results); win.enableObject('Result'); win.draw; pause(10); win.disableObject('Result'); % Close our display. win.close; % Make sure key capture is off. ListenChar(0); end function [win, params] = initDisplay(params, results) % Create the GLWindow object and linearize the clut. win = GLWindow('SceneDimensions', params.screenDimsCm, ... 'BackgroundColor', params.bgColor, 'SpoofFullScreen', false); try % Open the display. win.open; % Add the fixation point. win.addOval([0 0], params.fpSize, params.fpColor, 'Name', 'fp'); % Add text win.addText('Practice Session: Hit any button to start', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'TrialStartText'); % Identifier for the object. win.addText('Practice Session Over.', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'PracticeOverText'); % Identifier for the object. % Add text win.addText('Game begins: Hit any button to start', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'RealSessionText'); % Identifier for the object. % Add text win.addText('Hit any button to start', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'startText'); % Identifier for the object. % Add text win.addText(['Key :', 'Interval 1 -> ', params.interval1Key,' Interval 2 -> ',params.interval2Key ], ... % Text to display 'Center', [0 -8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'keyOptions'); % Identifier for the object. % Add text win.addText('One third of trials over. Take 1 minute rest.', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'oneThirdText'); % Identifier for the object. % Add text win.addText('Rest over. Hit any button to continue', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'restOver'); % Identifier for the object. % Add text win.addText('Two third of trials over. Take 1 minute rest.', ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'twoThirdText'); % Identifier for the object. % Add text win.addText([num2str(results(1)), ' correct out of ', num2str(results(2)), '. :)'], ... % Text to display 'Center', [0 8], ...% Where to center the text. (x,y) 'FontSize', 75, ... % Font size 'Color', params.textColor, ... % RGB color 'Name', 'Result'); % Identifier for the object. % Turn all objects off for now. win.disableAllObjects; catch e win.close; rethrow(e); end end function response = getUserResponse(params,key) response = []; switch key.charCode % Left/Down case params.interval1Key response = 1; % Right/Up case params.interval2Key response = 2; end % switch end
github
BrainardLab/VirtualWorldPsychophysics-master
t_equivNoiseEtc.m
.m
VirtualWorldPsychophysics-master/tutorials/t_equivNoiseEtc.m
20,673
utf_8
f3af826c6c0444ad2c14d8e1869b6e96
%% Work through basic equivalent noise models % % Description: % Simulates data using a TSD based model, or loads in our actual data, % and fits with various models. % % The fits are for the TSD model used to generate the simulated data and % a piecewise linear model. % % Can also generate curves by simulating a simple (two pixel) linear % receptive field model, but this is not fit as it's slow and stochastic. % Parameters adjusted to match up with experimental data. This is a % simplified version of the model Vijay developed to run on the actual % experimental images. Note that the variability in the experimental % images is constrained by physical reflectance constraints (0-1), and % thus the realized variability is not exactly that specified by the % covariance matrix of the underlying Gaussian. % % In simulate mode, every once and a while the piecewise linear function % fit function crashes for reasons I don't understand. Running it again % is usually then fine, which is one reason it's hard to figure out. % % This requires the Palamedes toolbox. % You'll get that with tbUseProject('VirtualWorldPsychophysics') % or just tbUse('Palamedes_1.9.0') % % See also: t_tvnSimpleModel %% History % 12/10/20 dhb Finished writing first version. %% Initialize clear; close all; %% Set parameters for TSD model if it is simulated. %% Threshold d-prime % % These are also value assumed in TSD fit if the corresponding fit booleans % are false, so they are set outside the SIMULATE conditional. % simThresholdDPrime is the criterion d-prime value used to determine threshold % simSignalExponent is the exponent in the TSD model. % Positive values decrease the slope of the rising limb. See % t_tvnSimpleModel for more expansion on the TSD model. simThresholdDPrime = 1; simSignalExponent = 1; % In the TSD model fit, you can hold the thresholdDPrime and signalExponent % fixed at the values above (set to false here), or search on them (set to % true). fitThresholdDPrime = false; fitSignalExponent = false; %% Simulate or set threshold data and smooth curve for plotting SIMULATE = false; %% Use the effective scalars rather than the nominal scalars when analyzing actual data USE_EFFECTIVESCALARS = true; %% Generate data to be used here if (SIMULATE) % Simulated parameters % simSigma2_i is the variance of the internal noise % simSigma2_e is the variance of the external noise at covScalar = 1. % simDataNoiseSd is the standard deviation of iid Gaussian noise added to the simulated data. simSigma2_i = 1.5; simSigma2_e = 10; simDataNoiseSd = 0.05; % Data size nCovScalarsData = 10; nCovScalarsPlot = 100; covScalarsData = logspace(-3,log10(15),nCovScalarsData); covScalarsPlot = logspace(-3,log10(15),nCovScalarsPlot); % Simulate and add noise thresholdDeltaDataRaw = ComputeTSDModel(simThresholdDPrime,simSigma2_i,simSigma2_e,simSignalExponent,covScalarsData); thresholdDeltaData = thresholdDeltaDataRaw + normrnd(0,simDataNoiseSd,size(thresholdDeltaDataRaw)); yPlotLimLow = 0; yPlotLimHigh = 2; % These parameters yield a reasonable fit (determined by hand) to the simulated data % with default script parameters. lrfThresholdDPrime = simThresholdDPrime; lrfSigma2_i = simSigma2_i; lrfSigma2_e = simSigma2_e; else % See estimateModelTresholds in paper repository for how these % effective scale factors were derived. The model generated there is % run for more covariance scale factors than the experiment, so we need % to pull out just the ones that correspond to the experimental values, % when we put these into the data matrix. covarianceScalarsModelNominal = [0.0001 0.0003, 0.001, 0.003, 0.01, 0.03, 0.10, 0.30, 1]; effectiveCovarianceScalars = [0.0015, 0.0018, 0.0041, 0.0082, 0.0236, 0.0544, 0.2345, 0.4628, 1.0000]; effectiveUseIndex = [1 5 6 7 8 9]; thresholdDeltaInput = [ 0.0001 0.0237 0.01 0.0226 0.03 0.0278 0.1 0.029 0.3 0.0338 1 0.0374]'; nCovScalarsPlot = 100; if (USE_EFFECTIVESCALARS) thresholdDeltaInput(1,:) = effectiveCovarianceScalars(effectiveUseIndex); end covScalarsData = thresholdDeltaInput(1,:); covScalarsPlot = logspace(log10(covScalarsData(1)),log10(covScalarsData(end)),nCovScalarsPlot); thresholdDeltaData = thresholdDeltaInput(2,:); nCovScalarsData = length(covScalarsData); yPlotLimLow = -3.5; yPlotLimHigh = -1.5; % Chosen by hand to approximate our data if (USE_EFFECTIVESCALARS) lrfThresholdDPrime = 1; lrfSigma2_i = 0.0006031; lrfSigma2_e = 0.000896; else lrfThresholdDPrime = 1; lrfSigma2_i = (0.034)^2/2; lrfSigma2_e = (0.05)^2/2; end end %% Fit the underlying TSD model % % If we're fitting thresholdDPrime, pass [] in key/value pair. Otherwise pass fixed value % to use. if (fitThresholdDPrime) passThresholdDPrime = []; else passThresholdDPrime = simThresholdDPrime; end % If we're fitting signalExponent, pass [] in key/value pair. Otherwise % pass fixed value to use. if (fitSignalExponent) passSignalExponent = []; else passSignalExponent = simSignalExponent; end % Fit and report [tsdThresholdDPrime,tsdSigma2_i,tsdSigma2_e,tsdSignalExponent] = FitTSDModel(covScalarsData,thresholdDeltaData,... 'thresholdDPrime',passThresholdDPrime,'signalExponent',passSignalExponent); fprintf('\nTSD fit to data: thresholdDPrime = %0.1f, sigma2_i = %0.4g, sigma2_e = %0.4g, signalExponent = %0.3f\n', ... tsdThresholdDPrime,tsdSigma2_i,tsdSigma2_e,tsdSignalExponent); % Generate smooth curve for plotting tsdThreshDeltaPlot = ComputeTSDModel(tsdThresholdDPrime,tsdSigma2_i,tsdSigma2_e,tsdSignalExponent,covScalarsPlot); %% Fit piecewise linear function [plThresh0,plLogEquivScalar,plSlope] = FitPiecewiseLinear(covScalarsData,thresholdDeltaData); plThreshDeltaPlot = ComputePiecewiseLinear(plThresh0,plLogEquivScalar,plSlope,covScalarsPlot); fprintf('Piecewise fit to data: thresh0 = %0.2f (log T^2 = %0.2f), logEquivScalar = %0.2f, slope = %0.2f\n\n',plThresh0,log10(plThresh0^2),plLogEquivScalar,plSlope); %% Compute linear RF model % % Run out predictions with hand chosen parameters lrfThreshDeltaData = ComputeLinearRFModel(lrfThresholdDPrime,lrfSigma2_i,lrfSigma2_e,covScalarsData); % Fit this with the TSD model, which should describe it exactly with % exponent of 1, up to simulation noise [lrfTSDFitThresholdDPrime,lrfTSDFitSigma2_i,lrfTSDFitSigma2_e,lrfTSDFitSignalExponent] = FitTSDModel(covScalarsData,lrfThreshDeltaData,... 'thresholdDPrime',lrfThresholdDPrime,'signalExponent',1); fprintf('\nLRF model parameters: thresholdDPrime = %0.1f, sigma2_i = %0.4g, sigma2_e = %0.4g\n', ... lrfThresholdDPrime,lrfSigma2_i,lrfSigma2_e); fprintf('TSD fit to linear RF model: thresholdDPrime = %0.1f, sigma2_i = %0.4g, sigma2_e = %0.4g, signalExponent = %0.3f\n', ... lrfTSDFitThresholdDPrime,lrfTSDFitSigma2_i,lrfTSDFitSigma2_e,lrfTSDFitSignalExponent); % Compute curve for plotting lrfTSDFitThreshDeltaPlot = ComputeTSDModel(lrfTSDFitThresholdDPrime,lrfTSDFitSigma2_i,lrfTSDFitSigma2_e,lrfTSDFitSignalExponent,covScalarsPlot); % Interpret piecewise linear parameters % % thresh0 = sqrt(sigma2_n)*simThresholdDPrime; plSigma2_i = (plThresh0/simThresholdDPrime)^2; plSigma2_e = plSigma2_i/10^(plLogEquivScalar); % Print out if (SIMULATE) fprintf('Simulated: internal noise SD = %0.3f, external noise SD = %0.3f (at cov scalar 1)\n',sqrt(simSigma2_i),sqrt(simSigma2_e)); end fprintf('\nTSD fit: internal noise SD = %0.4g, external noise SD = %0.4g (at cov scalar 1)\n',sqrt(tsdSigma2_i),sqrt(tsdSigma2_e)); fprintf('Piecewise fit: internal noise SD = %0.4g, external noise SD = %0.4g (at cov scalar 1)\n',sqrt(plSigma2_i),sqrt(plSigma2_e)); %% Plot log threshold^2 versus log covScalar figure; clf; hold on; plot(log10(covScalarsData),log10(thresholdDeltaData.^2),'ro','MarkerFaceColor','r','MarkerSize',10); plot(log10(covScalarsPlot),log10(tsdThreshDeltaPlot.^2),'r','LineWidth',1); plot(log10(covScalarsPlot),log10(plThreshDeltaPlot.^2),'b','LineWidth',1); plot(log10(covScalarsData),log10(lrfThreshDeltaData.^2),'ko','MarkerFaceColor','k','MarkerSize',8); plot(log10(covScalarsPlot),log10(lrfTSDFitThreshDeltaPlot.^2),'k','LineWidth',1); xlabel('Log10 Covariance Scalar'); ylabel('Log10 Threshold^2'); %ylim([yPlotLimLow yPlotLimHigh]); %% ComputePiecewiseLinear % % Compute thresholds from parameters of piecewise linear fit in log10 % threshold^2 versus log10 covariance scalar piecewise linear fit. function thresholdDeltaLRFs = ComputePiecewiseLinear(thresh0,logEquivScalar,slope,covScalars) delta = log10(thresh0^2); temp = covScalars - logEquivScalar; temp1 = log10(temp); temp1(temp <= 0) = -100; thresholdDeltaLRFs = sqrt(10.^max(delta,delta + slope*(log10(covScalars)-logEquivScalar))); end %% FitPiecewiseLinear function [thresh0,logEquivScalar,slope] = FitPiecewiseLinear(covScalars,thresholdDeltaData) % Reasonable bounds minThresh0 = min(thresholdDeltaData); maxThresh0 = max(thresholdDeltaData); minLogScalar = log10(min(covScalars)); maxLogScalar = log10(max(covScalars)); minSlope = 0.1; maxSlope = 10; % Bounds vlb = [minThresh0 minLogScalar minSlope]; vub = [maxThresh0 maxLogScalar maxSlope]; % Set up starting point grid nThresh0s = 5; nLogScalars = 5; nSlopes = 5; tryThresh0s = linspace(minThresh0,maxThresh0,nThresh0s); tryLogScalars = linspace(minLogScalar,maxLogScalar,nLogScalars); trySlopes = linspace(minSlope,maxSlope,nSlopes); % Grid search around fmincon starting point options = optimset(optimset('fmincon'),'Diagnostics','off','Display','off','LargeScale','off','Algorithm','active-set'); bestF = Inf; bestX = []; for tt = 1:nThresh0s for ll = 1:nLogScalars for ss = 1:nSlopes % Set x0 and search x0 = [tryThresh0s(tt) tryLogScalars(ll) trySlopes(ss)]; x = fmincon(@(x)FitPiecewiseLinearFun(x,covScalars,thresholdDeltaData),x0,[],[],[],[],vlb,vub,[],options); f = FitPiecewiseLinearFun(x,covScalars,thresholdDeltaData); if (f < bestF) bestF = f; bestX = x; end end end end % Extract parameters from best fit thresh0 = bestX(1); logEquivScalar = bestX(2); slope = bestX(3); end %% Error function for piecewise linear fitting function f = FitPiecewiseLinearFun(x,covScalars,thresholdDelta) thresh0 = x(1); logEquivScalar = x(2); slope = x(3); predictedDelta = ComputePiecewiseLinear(thresh0,logEquivScalar,slope,covScalars); diff2 = (thresholdDelta - predictedDelta).^2; f = sqrt(mean(diff2)); end %% Compute thresholds under simple underlying TSD model % % For the signalExponent == 1 case, just need to invert the forward relation % thresholdDPrime = (thresholdLRF - standardLRF)/sqrt(sigman2_n + covScalar*sigma2_e); % % This corresponds to adding noise to both comparison and standard % representationsm as per standard definition of d-prime under equal % variance distributions. % % Since the threshold we want is the difference from the standard, we can % just treat the standardLRF as 0 without loss of generality. % % The raising to the signalExponent is provides an ad-hoc parameter that allows us % more flexibility in fiting the data, but its underlying interpretation % isn't clear. Note that when the signalExponent isn't 1, it's hard to % interpret the sigma's of the fit. Or at least, we have not thought that % through yet. function thresholdDelta = ComputeTSDModel(thresholdDPrime,sigma2_i,sigma2_e,signalExponent,covScalars) for jj = 1:length(covScalars) thresholdDelta(jj) = (sqrt(sigma2_i + covScalars(jj)*sigma2_e)*thresholdDPrime).^(1/signalExponent); end end %% FitTSDModel function [thresholdDPrime,sigma2_i,sigma2_e,signalExponent] = FitTSDModel(covScalars,thresholdDelta,varargin) p = inputParser; p.addParameter('thresholdDPrime',1,@(x) (isempty(x) | isnumeric(x))); p.addParameter('signalExponent',1,@(x) (isempty(x) | isnumeric(x))); p.parse(varargin{:}); % Set thresholdDPrime initial value and bounds depending on parameters % Empty means search over it, otherwise lock at passed % value. if (~isempty(p.Results.thresholdDPrime)) thresholdDPrime0 = p.Results.thresholdDPrime; thresholdDPrimeL = p.Results.thresholdDPrime; thresholdDPrimeH = p.Results.thresholdDPrime; else thresholdDPrime0 = 1; thresholdDPrimeL = 1e-10; thresholdDPrimeH = 1e10; end % Set signalExponent initial value and bounds depending on parameters % Empty means search over it, otherwise lock at passed % value. if (~isempty(p.Results.signalExponent)) signalExponent0 = p.Results.signalExponent; signalExponentL = p.Results.signalExponent; signalExponentH = p.Results.signalExponent; nExps = 1; else signalExponent0 = 1; signalExponentL = 1e-2; signalExponentH = 1e2; nExps = 20; end % Bounds vlb = [thresholdDPrimeL 1e-20 1e-20 signalExponentL]; vub = [thresholdDPrimeH 100 100 signalExponentH]; % Grid over starting parameters trySignalExponents = linspace(signalExponentL,signalExponentH,nExps); % Search bestF = Inf; bestX = []; for ee = 1:nExps thresholdDPrime0 = thresholdDPrime0; signalExponent0 = trySignalExponents(ee); sigma2_i0 = ((min(thresholdDelta).^signalExponent0)/thresholdDPrime0).^2; sigma2_e0 = sigma2_i0; x0 = [thresholdDPrime0 sigma2_i0 sigma2_e0 signalExponent0]; options = optimset(optimset('fmincon'),'Diagnostics','off','Display','off','LargeScale','off','Algorithm','active-set'); x = fmincon(@(x)FitTSDModelFun(x,covScalars,thresholdDelta),x0,[],[],[],[],vlb,vub,[],options); f = FitTSDModelFun(x,covScalars,thresholdDelta); if (f < bestF) bestF = f; bestX = x; end end % Extract parameters thresholdDPrime = bestX(1); sigma2_i = bestX(2); sigma2_e = bestX(3); signalExponent = bestX(4); end %% Error function for TSD model fitting function f = FitTSDModelFun(x,covScalars,thresholdDelta) thresholdDPrime = x(1); sigma2_i = x(2); sigma2_e = x(3); signalExponent = x(4); predictedDelta = ComputeTSDModel(thresholdDPrime,sigma2_i,sigma2_e,signalExponent,covScalars); diff2 = (thresholdDelta - predictedDelta).^2; f = sqrt(mean(diff2)); end %% Compute thresholds under linear RF model % % This is a two-pixel version, with one pixel for center and one for % surround. They have weights 1 and -1, which are hard coded here. We add % external noise to the surround, and vary the center of the comparisons % relative to the standard. % % Internal noise is added to the center and external noise to the surround, % for both standard and comparison. This factors the parameters a bit % differently from the way Vijay did in his code, but allows easy match up % to the analytic TSD model. % % It's useful to plot the psychometric functions, because you want to make % sure that the range of comparison variation is in a regime that affects % performance reasonably. This varies with sigma2_i and sigma2_e, and % based on experience the routine attemps to put the comparison variation % in the right range. function thresholdDelta = ComputeLinearRFModel(thresholdDPrime,sigma2_i,sigma2_e,covScalars,varargin) p = inputParser; p.addParameter('plotPsycho',true,@(x) (islogical(x))); p.parse(varargin{:}); % Figure if (p.Results.plotPsycho) lrfPsychoFig = figure; clf; end % Threshold criterion thresholdCrit = dPrimeToTAFCFractionCorrect(thresholdDPrime); % d-prime of 1 -> 0.7602 % This factor scales the stimuli so as put psychometric function in range. % Determined by hand factor = 10*sqrt(sigma2_i/0.03); % Linear RF linearRF = [1 -1]; % Standard/comparison LRF values standardLRF = factor*0; comparisonLRFs = factor*[-0.05 -0.04 -0.03 -0.02 -0.01 0 0.01 0.02 0.03 0.04 0.05]; N = 5000; for ss = 1:length(covScalars) propComparisonChosen = zeros(1,length(comparisonLRFs)); % Add surrond noise to both standard and comparison as in experiment for cc = 1:length(comparisonLRFs) standardRFValues = standardLRF - normrnd(0,sqrt(covScalars(ss)*sigma2_e + sigma2_i),1,N); comparisonRFValues = comparisonLRFs(cc) - normrnd(0,sqrt(covScalars(ss)*sigma2_e + sigma2_i),1,N); propComparisonChosen(cc) = mean(comparisonRFValues > standardRFValues); end % Fit psychometric function using Palamedes. Fairly standard code. PF = @PAL_CumulativeNormal; % Alternatives: PAL_Gumbel, PAL_Weibull, PAL_CumulativeNormal, PAL_HyperbolicSecant % paramsFree is a boolean vector that determins what parameters get % searched over. 1: free parameter, 0: fixed parameter paramsFree = [1 1 1 1]; % Initial guess. Setting the first parameter to the middle of the stimulus % range and the second to 1 puts things into a reasonable ballpark here. paramsValues0 = [0 1 0 0]; lapseLimits = [0 0.05]; % Set up standard options for Palamedes search options = PAL_minimize('options'); % Fit with Palemedes Toolbox. The parameter constraints match the psignifit parameters above. Some thinking is % required to initialize the parameters sensibly. We know that the mean of the cumulative normal should be % roughly within the range of the comparison stimuli, so we initialize this to the mean. The standard deviation % should be some moderate fraction of the range of the stimuli, so again this is used as the initializer. [paramsValues] = PAL_PFML_Fit(... comparisonLRFs,propComparisonChosen,ones(size(propComparisonChosen)), ... paramsValues0,paramsFree,PF, ... 'lapseLimits',lapseLimits,'guessLimits',[],'searchOptions',options,'gammaEQlambda',true); xx = linspace(comparisonLRFs(1),comparisonLRFs(end),1000); yy = PF(paramsValues,xx'); psePal = PF(paramsValues,0.5,'inverse'); thresholdDelta(ss) = PF(paramsValues,thresholdCrit,'inverse')-psePal; if (p.Results.plotPsycho) figure(lrfPsychoFig); hold on %plot(comparisonLRFs,propComparisonChosen,'ro','MarkerFaceColor','r','MarkerSize',12); plot(xx,yy,'r','LineWidth',1); ylim([0 1]); end end end %% The three functions below are TSD utility routines pasted in from ISETBio function fractionCorrect = dPrimeToTAFCFractionCorrect(dPrime) % fractionCorrect = dPrimeToTAFCPercentFraction(dPrime) % % Get area under ROC curve for an equal-variance normal distribution % d-prime and from there compute fraction correct. % % This was originally written as numerical integration of ROC curve. Now % has analytic calculation inserted, and a check that the two are close. % At some point, might want to change over to the analytic version. % % See also: computeROCArea, analyticPHitPpFA, computeDPrimCritNorm % History: % 05/26/2020 dhb Added analytic calculation %% Examples: %{ dPrimeToTAFCFractionCorrect(0.25) dPrimeToTAFCFractionCorrect(0.5) dPrimeToTAFCFractionCorrect(0.1) dPrimeToTAFCFractionCorrect(2) dPrimeToTAFCFractionCorrect(3) %} nCriteria = 1000; lowCriterion = -8; highCriterion = 8; fractionCorrect = computeROCArea(dPrime,0,1,linspace(lowCriterion,highCriterion,nCriteria)); fractionCorrect1 = normcdf(dPrime/sqrt(2)); if (max(abs(fractionCorrect-fractionCorrect1)) > 1e-3) error('Numerical and analytic calculations do not match'); end end %% Also from isetbio, and here for convenience function rocArea = computeROCArea(signalMean,noiseMean,commonSd,criteria) % rocArea = computeROCArea(signalMean,noiseMean,commonSd,criteria) % % Compute area under ROC curve given signal mean, noise mean, the common % standard deviation, and a set of criteria. Uses the equal-variance % normal assumption. % Compute ROC curve for i = 1:length(criteria) [pHitAnalytic(i),pFaAnalytic(i)] = analyticpHitpFa(signalMean,noiseMean,commonSd,criteria(i)); end % Integrate numerically to get area. The negative % sign is because the way the computation goes, the hit rates % decrease with increasing criteria. rocArea = -trapz([1 pFaAnalytic 0],[1 pHitAnalytic 0]); end function [pHit,pFa] = analyticpHitpFa(signalMean,noiseMean,commonSd,rightCrit) % [pHit,pFa] = analyticpHitpFa(signalMean,noiseMean,commonSd,rightCrit) % % This just finds the area under the signal and noise % distributions to the right of the criterion to obtain % hit and false alarm rates. Uses the equal-variance normal assumption. pHit = 1-normcdf(rightCrit,signalMean,commonSd); pFa = 1-normcdf(rightCrit,noiseMean,commonSd); end
github
BrainardLab/VirtualWorldPsychophysics-master
t_tvnSimpleModel.m
.m
VirtualWorldPsychophysics-master/tutorials/t_tvnSimpleModel.m
4,385
utf_8
180aa1d005a577de29ce95491d141fdb
% t_tvnSimpleModel % % Simple model for thresholds versus noise % % See also: t_equivNoiseEtc % History: % 11/13/19 dhb Wrote it. %% Clear clear; close all; %% Parameters sigmasExternal = linspace(0.01,100,1000); criterionDPrime = 1; %% Initialize figure figure; hold on sigmaInternal = 1; externalIntrusionFactor = 0.5; signalExponent = 1; thresholds = ComputeTvNThresholds(sigmasExternal,criterionDPrime,sigmaInternal,externalIntrusionFactor,signalExponent); plot(log10(sigmasExternal.^2),log10(thresholds.^2),'r','LineWidth',4); sigmaInternal = 2; externalIntrusionFactor = 0.5; signalExponent = 1; thresholds = ComputeTvNThresholds(sigmasExternal,criterionDPrime,sigmaInternal,externalIntrusionFactor,signalExponent); plot(log10(sigmasExternal.^2),log10(thresholds.^2),'r:','LineWidth',4); sigmaInternal = 1; externalIntrusionFactor = 1; signalExponent = 1; thresholds = ComputeTvNThresholds(sigmasExternal,criterionDPrime,sigmaInternal,externalIntrusionFactor,signalExponent); plot(log10(sigmasExternal.^2),log10(thresholds.^2),'b','LineWidth',2); sigmaInternal = 2; externalIntrusionFactor = 10; signalExponent = 1; thresholds = ComputeTvNThresholds(sigmasExternal,criterionDPrime,sigmaInternal,externalIntrusionFactor,signalExponent); plot(log10(sigmasExternal.^2),log10(thresholds.^2),'b:','LineWidth',2); sigmaInternal = 1; externalIntrusionFactor = 0.5; signalExponent = 2; thresholds = ComputeTvNThresholds(sigmasExternal,criterionDPrime,sigmaInternal,externalIntrusionFactor,signalExponent); plot(log10(sigmasExternal.^2),log10(thresholds.^2),'g','LineWidth',4); sigmaInternal = 2; externalIntrusionFactor = 0.5; signalExponent = 2; thresholds = ComputeTvNThresholds(sigmasExternal,criterionDPrime,sigmaInternal,externalIntrusionFactor,signalExponent); plot(log10(sigmasExternal.^2),log10(thresholds.^2),'g:','LineWidth',4); xlim([-3 3]); ylim([-1 5]); axis('square'); xlabel('Log10 Noise Sigma^2'); ylabel('log10 Threshold^2'); function thresholds = ComputeTvNThresholds(sigmasExternal,criterionDPrime,sigmaInternal,externalIntrusionFactor,signalExponent) for ii = 1:length(sigmasExternal) thresholds(ii) = ComputeTvNThreshold(sigmasExternal(ii),criterionDPrime,sigmaInternal,externalIntrusionFactor,signalExponent); end end % Compute thresholds for a generalized version of the standard TvN model. % % Syntax: % threshold = ComputeTvNThreshold(sigmaExternal,criterionDPrime,sigmaInternal,externalIntrusionFactor,signalExponent) % % Description: % Compute threshold under simple model where performance is limited by % an early static non-linearity between stimulus and perceptual axis, % with the non-linearity taken as a power function, as well as noise on % the perceptual axis. The noise is the sum of internal noise and the % effect of external noise. % % When the exponent is 1, this reduces to (I think) the standard model % used for TvN functions. The standard model has an asymptotic slope % of 1 when threshold squared is plotted against noise variance. Our % data have slopes smaller than 1, and adding the exponent as a % parameter allows a description of the data. The process % interpretaiton of this model, however, is not immediately obvious. % % Inputs: % sigmaExternal - Variance of experimentally added external noise. % criterionDPrime - Value of d-prime that corresponds to threshold. % sigmaInternal - Variance of internal noise on perceptual axis. % externalIntrusionFactor - External noise times this is the addive % variance of the external noise on the perceptual axis. % signalExponent - Effect of stimulus strength on perceptual % axis is x raised to this exponent. Set to 1 for the standard TvN % model. % % Outputs: % threshold - Threshold signal strength. % % Optional key/value pairs: % None. % History: % 07/17/19 dhb Added header comment. function threshold = ComputeTvNThreshold(sigmaExternal,criterionDPrime,sigmaInternal,externalIntrusionFactor,signalExponent) sigma = sqrt(sigmaInternal^2 + sigmaExternal^2*externalIntrusionFactor); exponentiatedThreshold = criterionDPrime*sigma; threshold = exponentiatedThreshold^(1/signalExponent); end
github
wenbihan/DeepDenoising-master
classification_demo.m
.m
DeepDenoising-master/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % 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 % maxlabel the label of the highest score % % 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 = classification_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 in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); 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 Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
wenbihan/DeepDenoising-master
MyVOCevalseg.m
.m
DeepDenoising-master/matlab/my_script/MyVOCevalseg.m
4,625
utf_8
128c24319d520c2576168d1cf17e068f
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts] = MyVOCevalseg(VOCopts,id) % image test set [gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; num_missing_img = 0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err num_missing_img = num_missing_img + 1; %fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end %pixel locations to include in computation locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end if (num_missing_img > 0) fprintf(1, 'WARNING: There are %d missing results!\n', num_missing_img); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end if ~strcmp(clname, 'void') class_count = class_count + 1; fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); real_class_count = 0; for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: denom = (gtj+resj-gtjresj); if denom == 0 denom = 1; end accuracies(j)=100*gtjresj/denom; clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; if ~strcmp(clname, 'void') real_class_count = real_class_count + 1; else if denom ~= 1 fprintf(1, 'WARNING: this void class has denom = %d\n', denom); end end if ~strcmp(clname, 'void') fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end end %accuracies = accuracies(1:end); %avacc = mean(accuracies); avacc = sum(accuracies) / real_class_count; fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
wenbihan/DeepDenoising-master
MyVOCevalsegBoundary.m
.m
DeepDenoising-master/matlab/my_script/MyVOCevalsegBoundary.m
4,415
utf_8
1b648714e61bafba7c08a8ce5824b105
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts, overall_acc, avg_class_acc] = MyVOCevalsegBoundary(VOCopts, id, w) % get structural element st_w = 2*w + 1; se = strel('square', st_w); % image test set fn = sprintf(VOCopts.seg.imgsetpath,VOCopts.testset); fid = fopen(fn, 'r'); gtids = textscan(fid, '%s'); gtids = gtids{1}; fclose(fid); %[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end % dilate gt binary_gt = gtim == 255; dilate_gt = imdilate(binary_gt, se); target_gt = dilate_gt & (gtim~=255); %pixel locations to include in computation locs = target_gt; %locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; else class_count = class_count + 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: accuracies(j)=100*gtjresj/(gtj+resj-gtjresj); clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end accuracies = accuracies(1:end); avacc = mean(accuracies); fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
tahmidzbr/Human-Activities-Gestures-Recognition-using-Channel-State-Information-CSI-of-IEEE-802.11n-master
extract_time_information.m
.m
Human-Activities-Gestures-Recognition-using-Channel-State-Information-CSI-of-IEEE-802.11n-master/extract_time_information.m
2,094
utf_8
a6828b2a8313bc3c5092ea1ac0e5d2ce
% ####################################################################### % % ####################################################################### % % Extracting Time Information of packet arrival from CSI Data % % Author: Tahmid Z. Chowdhury % % The University of British Columbia, Canada % Copyright: Using Wi-Fi Channel State Information (CSI) for Human % Activity Recognition & Fall Detection % ####################################################################### % % ####################################################################### % function [time_stamp] = extract_time_information(packet) % where packet is your CSI file csi_trace=read_bf_file(packet); for a=1:j %where j is the total number packets in the CSI file structure % extract the low 32 bits of the NIC's 1 MHz clock % The code doesn't account for wrapping about every 4300 seconds, or 72 minutes. time(a)=csi_trace{a,1}.timestamp_low; end time_diff=(diff(time))*10^-6; %--convert difference b/w time_stamps to seconds actualtime=[0,time_diff]; %--row vector consisting of timestamp differences in seconds sum(time_diff,2); time_stamp=cumsum(actualtime); end % ####################################################################### % % ####################################################################### % % NOTE: If you use this code, please consider citing: % @phdthesis{Chowdhury_2018, series={Electronic Theses and Dissertations (ETDs) 2008+}, % title={Using Wi-Fi channel state information (CSI) for human activity recognition and fall detection}, % url={https://open.library.ubc.ca/collections/ubctheses/24/items/1.0365967}, DOI={http://dx.doi.org/10.14288/1.0365967}, % school={University of British Columbia}, author={Chowdhury, Tahmid Z.}, year={2018}, % collection={Electronic Theses and Dissertations (ETDs) 2008+}} % ####################################################################### % % ####################################################################### %
github
mingloo/DeepSupervisedHashing-master
calcMAP.m
.m
DeepSupervisedHashing-master/scripts/calcMAP.m
685
utf_8
8fde5825c8e4d5afde81c356458b3354
% compute mean average precision (MAP) function [MAP, succRate] = calcMAP (orderH, neighbor) [Q, N] = size(neighbor); pos = 1: N; %pos = [1: 10000]; MAP = 0; numSucc = 0; for i = 1: Q ngb = neighbor(i, orderH(i, :)); nRel = sum(ngb); if nRel > 0 prec = cumsum(ngb) ./ pos; ap = mean(prec(ngb==1)); MAP = MAP + ap; numSucc = numSucc + 1; end % ngb = neighbor(i, orderH(i, :)); % nRel = sum(ngb); % ngb= ngb(1:10000); % if nRel > 0 % prec = cumsum(ngb) ./ pos; % ap = mean(prec(ngb)); % MAP = MAP + ap; % numSucc = numSucc + 1; % end end MAP = MAP / numSucc; succRate = numSucc / Q; end
github
mingloo/DeepSupervisedHashing-master
calcHammingDist.m
.m
DeepSupervisedHashing-master/scripts/calcHammingDist.m
242
utf_8
32c41d9f80386fbbddf74076159f9082
% compute the hamming distance between every pair of data points represented in each row of B1 and B2 function D = calcHammingDist (B1, B2) P1 = sign(B1 - 0.5); P2 = sign(B2 - 0.5); R = size(P1, 2); D = round((R - P1 * P2') / 2); end
github
CoraliePicoche/Seasonality-master
compute_temperature_season.m
.m
Seasonality-master/script/compute_temperature_season.m
439
utf_8
dcc6f7e84e56969b13f7cb605de42048
%%% Model first developped by of Scranton & Vasseur 2016 (Theor Ecol.) %%% Script by Picoche & Barraquand 2017 %%% This function computes a random temperature time series with a seasonal %%% signal, whose dominance depends on the value of theta function [tau] = compute_temperature_season(t, theta) global mu_tau sigma_tau %Seasonality tau=mu_tau+theta*sigma_tau*sin(2*pi*t/365)+normrnd(0,sigma_tau*sqrt(1-(theta^2)/2),1,length(t)); end
github
CoraliePicoche/Seasonality-master
growth_response.m
.m
Seasonality-master/script/growth_response.m
296
utf_8
361a2d909c4de4bca7251485efc9c129
%%% Model first developped by of Scranton & Vasseur 2016 (Theor Ecol.) %%% Script by Picoche & Barraquand 2017 %%% This function computes the growth response to temperature function growth = growth_response(tau) global a_r_tau0 tau0 E_r k growth=a_r_tau0*exp(E_r*(tau-tau0)./(k*tau*tau0)); end
github
CoraliePicoche/Seasonality-master
species_mean_value.m
.m
Seasonality-master/script/species_mean_value.m
1,132
utf_8
4f0cf05bff8b4c928f84a4f3e511aef0
%%% Model first developped by of Scranton & Vasseur 2016 (Theor Ecol.) %%% Script by Picoche & Barraquand 2018 %%% This function computes species mean biomass during the last years of %%% the simulation function res=species_mean_value(youtbis, varargin) S=size(youtbis,2); %number of species tt=size(youtbis,1); %length of the simulation optargs={200}; %corresponding to default value for yspan thresh_min=10^(-6); %threshold below which species are considered extunct and set to 0 num_argin=length(varargin); optargs(1:num_argin)=varargin; yspan=optargs{1}; if yspan>tt/365 error('Size of the window is larger than the simulation') end %Only uses the given timespan to compute the mean biomass ymax=tt; ymin=ymax-yspan*365+1; %we want yspan years of simulations new_youtbis=youtbis(ymin:ymax,:); mask=youtbis(end,:)<thresh_min; %Remove species that are extant at the end of the simulation sbis=1:S; sbis=sbis(~mask); %extant species ymean=zeros(1,S); for s1=sbis ymean(s1)=mean(new_youtbis(:,s1)); end res=ymean; end
github
CoraliePicoche/Seasonality-master
SV16_ode_integration.m
.m
Seasonality-master/script/SV16_ode_integration.m
778
utf_8
51d04f73dda0fa88d174539d19010383
%%% Model first developped by of Scranton & Vasseur 2016 (Theor Ecol.) %%% Script by Picoche & Barraquand 2017 %%% Function for ODE integration function dydt = SV16_ode_integration(t,y) global A m S thresh_min tau b tau_opt r morta_vect %A interaction matrix %m mortality %S number of species %thresh_min biomass below which a species is considered extinct %tau temperature %b and tau_opt species-specific parameters defining the thermal niche %r growth rates depending on the temperature %morta_vect with the variable mortality that Barabas asked for dydt=zeros(S,1); comp=zeros(1,S); mask=transpose(find(y>=thresh_min)); %Only integrates for extant species %Competition comp=1-A(:,mask)*y(mask); dydt(mask)=(r(mask,floor(t)).*comp(mask)-morta_vect(mask)).*y(mask); end
github
CoraliePicoche/Seasonality-master
frac_max.m
.m
Seasonality-master/script/frac_max.m
549
utf_8
ef5e371196abe12e6a78ae83b0852bb8
%%% Model first developped by of Scranton & Vasseur 2016 (Theor Ecol.) %%% Script by Picoche & Barraquand 2017 %%% This function computes the fraction of the maximum growth rate achieved %%% for one for the whole temperature time series function f = frac_max(tau,tau_opt,b) for t=1:length(tau) if b<0 f(t)=10^9; %just a small trick to avoid the Infinite when searching for the right b else tmp=-abs(tau(t)-tau_opt)^3/b; if tau(t)>tau_opt tmp=tmp*5; end; f(t)=exp(tmp); end; end; end
github
CoraliePicoche/Seasonality-master
SV16_ode_integration_no_GR_in_competition.m
.m
Seasonality-master/script/SV16_ode_integration_no_GR_in_competition.m
774
utf_8
0db131eb4471b9cb439fd0d5a8b94ddf
%%% Model first developped by of Scranton & Vasseur 2016 (Theor Ecol.) %%% Script by Picoche & Barraquand 2017 %%% Function for ODE integration, removing the storage effect function dydt = SV16_ode_integration_no_GR_in_competition(t,y) global A m S r thresh_min morta_vect %A interaction matrix %m mortality %S number of species %thresh_min biomass below which a species is considered extinct %tau temperature %b and tau_opt species-specific parameters defining the thermal niche %r growth rates depending on the temperature %morta_vect with the variable mortality that Barabas asked for dydt=zeros(S,1); comp=zeros(1,S); mask=transpose(find(y>=thresh_min)); %Competition comp=A(:,mask)*y(mask); dydt(mask)=(r(mask,floor(t))-morta_vect(mask)-comp(mask)).*y(mask); end
github
CoraliePicoche/Seasonality-master
community_wide_indices.m
.m
Seasonality-master/script/exploratory/community_wide_indices.m
1,607
utf_8
8cbf83ff91ac0a54f9876a6517fb956f
%%% Developped by Picoche & Barraquand 2018 %%% Compare different community-wide synchrony index (Loreau and Gross, by %%% year for the last 500 years saved at the end of a simulation) function [tab_indices] = community_wide_indices(filename) thresh_min=10^(-6); %filename='output_simulation/SV_same_temp/iter1_codeversion_20180228_theta0.mat'; load(filename) %youtbis=youtbis(2:end,:); small trick when looking at old files in %SV_different_temp youtbis(youtbis<thresh_min)=0; if(mod(size(youtbis,1),365)~=0) youtbis=youtbis(1+mod(size(youtbis,1),365):end,:); end; nb_year=size(youtbis,1)/365; S=size(youtbis,2); %%Loreau & Mazancourt (2008) biomass_over_year=reshape(youtbis,365,nb_year,S); % x = julian day ; y = year ; z species community_cycle=cumsum(biomass_over_year,3); %total biomass over a cycle community_cycle=reshape(community_cycle(:,:,60),365,nb_year); %x julian day; y year community_sd=std(community_cycle,1); pop_sd=std(biomass_over_year,1); pop_sd=reshape(pop_sd(1,:,:),nb_year,S); loreau_index=zeros(1,nb_year); for y=1:nb_year loreau_index(y)=(community_sd(y))^2/(sum(pop_sd(y,:)))^2; end; %%Gross et al. (2014) %Using Pearson correlation, as in codyn package gross_index=zeros(1,nb_year); for y=1:nb_year for s=1:S sbis=1:S; sbis=sbis(sbis~=s); sum_pop=sum(biomass_over_year(:,y,sbis),3); if(std(sum_pop)~=0&std(biomass_over_year(:,y,s))~=0) gross_index(y)=gross_index(y)+corr(biomass_over_year(:,y,s),sum_pop); end end; gross_index(y)=gross_index(y)/S; end tab_indices=vertcat(loreau_index,gross_index);
github
CoraliePicoche/Seasonality-master
fun.m
.m
Seasonality-master/script/exploratory/fun.m
108
utf_8
1f0b15c48554c3bf553bc47cac7d204d
%%%essai function f = fun(x,b,tau_opt) %%%% f= growth_response(x).*frac_max_vectoriel(x,tau_opt,b); %%%% end
github
CoraliePicoche/Seasonality-master
compute_temperature.m
.m
Seasonality-master/script/exploratory/compute_temperature.m
387
utf_8
3394d20baa7a1ba7f4f2a72615da1f80
%%% Model of Scranton & Vasseur 2016 (Theor Ecol.) %%% Developped by Picoche & Barraquand 2017 %%% Function for temperature function [tau] = compute_temperature(t) global mu_tau sigma_tau %for now, we're just using a random value, that's option 1 tau=normrnd(mu_tau,sigma_tau,1,length(t)); %Seasonality %tau=mu_tau-sigma_tau/2*cos(2*pi*t/365)+normrnd(0,sigma_tau/2,1,length(t)); end
github
CoraliePicoche/Seasonality-master
convergence_function.m
.m
Seasonality-master/script/exploratory/convergence_function.m
1,250
utf_8
e3cea003ba549efc2f4eeade661f21c0
%%% Model of Scranton & Vasseur 2016 (Theor Ecol.) %%% Developped by Picoche & Barraquand 2018 %%% Function to check stability, given youtbis function convergence_function(youtbis) thresh_min=10^(-6); %First assessments nb_species=sum(youtbis'>thresh_min); nb_species_final=nb_species(end) tot_biomass_final=mean(sum(youtbis((end-364):end,:),2)) biomass_over_year=reshape(youtbis,365,size(youtbis,1)/365,size(youtbis,2)); % x = julian day ; y = year ; z species %We can also consider the coefficient of variation for total biomass tt_biomass=cumsum(biomass_over_year,3); %cv_cycle=std(total_biomass_cycle(:,:,60),[],1)./mean(total_biomass_cycle(:,:,60),1); cv_cycle=std(tt_biomass(:,:,60),[],1)./mean(tt_biomass(:,:,60),1); fig=figure; set(fig,'defaultAxesColorOrder',[[65/255 105/255 225/255]; [0 0 0 ]]); yyaxis left; plot(1:length(cv_cycle),cv_cycle,'LineWidth',2) ylabel('CV of total biomass') set(gca,'Fontsize',16) yyaxis right; plot((1:length(nb_species))/365,nb_species,'-k','LineWidth',2) ylabel('Nb extant species') set(gca,'Ylim',[min(nb_species)-0.5 max(nb_species)+0.5],'Fontsize',16) title('Convergence criteria','Fontsize',18) end
github
CoraliePicoche/Seasonality-master
figure_1.m
.m
Seasonality-master/script/exploratory/figure_1.m
789
utf_8
992038085a34ad2e631e1b4f2f9054ca
%%% Model of Scranton & Vasseur 2016 (Theor Ecol.) %%% Developped by Picoche & Barraquand 2017 %%% fraction of the maximum growth rate achieved for one species function f = figure_1(b,tau_opt) global S temp_min=12; temp_max=26; tmp_tot=linspace(temp_min,temp_max,1000)+273; r=growth_response(tmp_tot); figure;hold on; %a for i=1:S densr=365*r.*frac_max(tmp_tot,tau_opt(i),b(i)); plot(tmp_tot-273.15,densr); plot(tmp_tot-273.15,365.25*r,'k'); end; hold off; %b tau=normrnd(20+273,5,1,1000); figure;hold on; plot(tmp_tot-273,ones(1,length(tmp_tot))*15,'Color',[.17 .17 .17]); ylim([0 120]); for i=1:S gg=mean(365*growth_response(tau).*frac_max(tau,tau_opt(i),b(i))); plot(tau_opt(i)-273,gg,'+') plot([tau_opt(i)-273 tau_opt(i)-273],[0 gg],'-') end; hold off; end
github
CoraliePicoche/Seasonality-master
SV16_ode_integration_randomGR_in_competition.m
.m
Seasonality-master/script/exploratory/SV16_ode_integration_randomGR_in_competition.m
475
utf_8
f82af31a4655ccf8e2706469c224ce77
%%% Model of Scranton & Vasseur 2016 (Theor Ecol.) %%% Developped by Picoche & Barraquand 2017 %%% Function for ODE integration function dydt = SV16_ode_integration_randomGR_in_competition(t,y) global A m S r thresh_min tbis %A interaction matrix %m mortality %S number of species dydt=zeros(S,1); comp=zeros(1,S); mask=transpose(find(y>=thresh_min)); %Competition comp=A(:,mask)*y(mask); dydt(mask)=(r(mask,floor(t))-m-r(mask,tbis(floor(t))).*comp(mask)).*y(mask); end
github
CoraliePicoche/Seasonality-master
frac_max_vectoriel.m
.m
Seasonality-master/script/exploratory/frac_max_vectoriel.m
486
utf_8
b78b44f3a6190743120e40f11a3646ad
%%% Model of Scranton & Vasseur 2016 (Theor Ecol.) %%% Developped by Picoche & Barraquand 2017 %%% fraction of the maximum growth rate achieved for one species function f = frac_max_vectoriel(tau,tau_opt,b) for t=1:length(tau) if b<0 f(t,1:length(b))=10^9; %just a small trick to avoid the Infinite when searching for the right b else tmp=-abs(tau(t)-tau_opt).^3./b; tmp(tau(t)>tau_opt)=tmp(tau(t)>tau_opt)*5; f(t,:)=exp(tmp); end; end; end
github
CoraliePicoche/Seasonality-master
myplot.m
.m
Seasonality-master/script/exploratory/myplot_RAC/myplot.m
4,459
utf_8
10e958278187c8b7a943a5df9ef58350
%% Make a nice plot quickly % Syntax: myplot(X,Y,type,color, style) % [X],[Y]: vectors of data x,y % [type]: type of plots % 'S': scaatter plot, the default % 'L': line % 'B': both % [color]: can ba a number or a vector of 3 % IF it is a number, selecter of color from [mycolors] % to see color plate, type mycolor(0), or check document % IF it is not round, round part means the color code, 0.5 decimal part % means the marker be hollow % IF it is a vector, it is the color code % [style] : line or marker style of corresponding [type]. for type = 'B', apply only to marker % Update 2015/09/21 : use function form [mycolor] instead of script_mycolorplate % Update 2015/09/22 : input [color] can be a 3-number code % Update 2015/10/30 : set default scatter plot transparency; set output; % input can be table % Update 2015/11/11 : Add optional input 'style' % Update 2015/11/23 : Add option color n.5 for hollow markers % Update 2015/12/01 : Add numeric and n.5 input option of 'style'; use [] to pass default values %% function h = myplot(X,Y,type,color,style) if (nargin < 4 || isempty(color)), color = 3; end; if (nargin < 3 ||isempty(type)), type = ('S'); end; % compatibility to data type table Xlab = []; Ylab = []; if istable(X) Xlab = tnames(X); X=table2array(X); end if istable(Y) Ylab = tnames(Y); Y=table2array(Y); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% hollow = 0; % flag for whether the symbal is hollow if length(color)==1 colorcode = mycolor(floor(color)); if color-floor(color) == 0.5 hollow = 1; end else if length(color)==3 colorcode = color; else error('input [color] should be an interger (select from [mycolor]) or a 3-number color code') end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if type=='S' if (nargin < 5||isempty(style)), style = 'o'; end stylesheet = {'o', 's','d','^','p','+','*','X','v','>','<','.'}; a=40; if isnumeric(style) if (style-floor(style) == 0.5); hollow = 1;end style = stylesheet{floor(style)}; end if hollow == 0 && ~any(strcmp(style,{'+','*','X'})) % +,*,X cannot be hollow if any( strcmp(version('-release'), {'2015b'}) ) h = scatter(X,Y,a,style,'Markeredgecolor','none','Markerfacecolor',colorcode,'Markerfacealpha',0.7);% 'Markerfacealpha',0.7); else h = scatter(X,Y,a,style,'Markeredgecolor','none','Markerfacecolor',colorcode); end else % hollow ==1 h = plot(X,Y,style,'color',colorcode); end set(gca,'FontSize',14,'linewidth',2); end if type=='L'|| type=='B' if (nargin < 5||isempty(style)||type=='B') Lstyle = '-'; else Lstyle=style; end stylesheet = {'-','--',':','-.' }; if (isnumeric(Lstyle)), Lstyle = stylesheet{floor(Lstyle)}; end h = plot(X,Y,Lstyle,'linewidth',2,'color',colorcode); set(gca,'FontSize',14,'linewidth',2); end if type=='B' if (nargin < 5||isempty(style)), style = 'o'; end stylesheet = {'o', 's','d','^','p','+','*','X','v','>','<','.'}; a=40; if isnumeric(style) if (style-floor(style) == 0.5); hollow = 1;end style = stylesheet{floor(style)}; end hold on if hollow ==0 && ~any(strcmp(style,{'+','*','X'})) if any( strcmp(version('-release'), {'2015b'}) ) h = scatter(X,Y,a,style,'Markeredgecolor','none','Markerfacecolor',colorcode,'Markerfacealpha',0.7);% 'Markerfacealpha',0.7); else h = scatter(X,Y,a,style,'Markeredgecolor','none','Markerfacecolor',colorcode); end else plot(X,Y,style,'color',colorcode); end set(gca,'FontSize',14,'linewidth',2); end xlabel(Xlab);ylabel(Ylab);
github
CoraliePicoche/Seasonality-master
mysubplot.m
.m
Seasonality-master/script/exploratory/myplot_RAC/mysubplot.m
4,995
utf_8
b92e65a273c1e8dfb133be81e1be88e6
%% Create subplots with Major title % Usage: % % to make subplot: % mysubplot(L, W, ID, Title, tightL, tightW) % [L], [W],: the dimension of subplots as in subplot(L,W,ID) % [ID]: The location of subplot as in subplot(L,W,ID); % to make larger subplot, make [ID] a vector with IDs of multiple cells % [tightW], [tightL]: How tight the subplots packed, on the first and secand dimension. % Or the ratio of space between subplots to the size of subplot. % Default : 0.3, 0.3 % % to make major title: % mysubplot(L,W, 0,Title) % _set ID=0_ % [L], [W]: the dimension of subplots as in mysubplot(L,W,ID) % [Title]: string of the major title % % to display cell layout: % mysubplot(L, W) % For examples of usage, see [X_mysubplot.m] % % Wei-Ting Lin 2015/09/21 % edit line 44, 71, left margin add padW/2 function mysubplot(L, W, ID, bigtitle, tightL, tightW, margin) % ID=0 means title if (nargin < 3|| isempty(ID)), ID = -1; end % when ID = -1 the function will print out the subplot layout if (nargin < 4|| isempty(bigtitle)), bigtitle = ''; end if (nargin < 5 || isempty(tightL)), tightL = 0.3; end if (nargin < 6|| isempty(tightW)), tightW = 0.3; end if (nargin < 7), margin = 0.05; end if ID>L*W error('ID > number of subplot'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %margin = 0.05; if L ==1 titleH = 0.2; else titleH = 0.3/L; end plotW =( 1-margin*2) / W; % width of each subplot plotH = (1-titleH-margin*2) /L; % height %padW =0.3/W;% padding on the width %padL =0.3/L; padW = tightW * plotW; padL =tightL * plotH; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Making title if ID==0 subplot('position',[0 1-titleH 1 titleH ])% new Length of the whole figure is (11/10)*LCM axis([-1 1 -1 1]) text(0,0,bigtitle, 'VerticalAlignment','Middle','HorizontalAlignment','Center','FontSize',16) box off axis off %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Making subplot else if length(ID)==1 if ID ==-1 % marker of "display cell layout" figure mysubplot(L,W, 0, 'subplot cells layout') for i = 1: L*W mysubplot(L,W, i) myplot(1,1, 'S', 40); set(gca,'xtick',[]); set(gca,'ytick',[]) text(1,1, ['ID = ' num2str(i)], 'fontsize', 16, 'Horizontalalignment', 'center') end else %This is the part of the function parallele to subplot r = ceil(ID/W);% which row in the plot c = round(mod(ID-0.1,W)); % witch column in the plot positionL = margin+(plotW)*(c-1)+padW/2 ;%left point positionB = 1 - (r*(plotH)+margin+titleH)+padL;% bottom point %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subplot('position', [positionL positionB plotW-padW plotH-padL]) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end else % conbining multiple cells to one subplot combL = length(ID) ; for p = 1:combL r(p) = ceil(ID(p)/W);% which row in the plot c(p) = round(mod(ID(p)-0.1,W)); % witch column in the plot end BottomLeft = find(c==min(c)&r==max(r)); % the cell on the left bottom corner TopRight = find(c==max(c)&r==min(r)); % the cell on the top right corner if length(BottomLeft)~=1 || length(TopRight)~=1 error('input cell IDs will not make a square') end NCellH = c(TopRight)-c(BottomLeft)+1;% number of cell horizontally NCellV = r(BottomLeft)-r(TopRight)+1;% number of cell vertically if length(ID) ~= NCellH*NCellV % expected numver of cell is not equal to input number of cell error('input cell IDs will not make a square') end % calculate subplot location based on the bottom-left cell positionL = margin+(plotW)*(c(BottomLeft)-1)+padW/2 ;%left point positionB = 1 - (r(BottomLeft)*(plotH)+margin+titleH)+padL;% bottom point % calculate subplot size based on number of cells horizontally and vertically %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subplot('position', [positionL positionB plotW*NCellH-padW plotH*NCellV-padL]) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end end
github
CoraliePicoche/Seasonality-master
num2month.m
.m
Seasonality-master/script/exploratory/myplot_RAC/num2month.m
554
utf_8
f6aa671af3fe68e71cebb7b4919ac571
function monthstr = num2month(monthnum) [n, p] = size(monthnum); for i = 1: n for j = 1: p monthstr(i, j) = n2mstr(monthnum(i,j)); end end if isscalar(monthnum) monthstr = monthstr{1}; end end %% a subfunction function mstr =n2mstr(mnum) monthStr1 = {'January', 'February', 'March', 'April', 'May', 'June', ... 'July', 'August' ,'September','October', 'Novenber','December' }; mstr = monthStr1(mnum); end
github
CoraliePicoche/Seasonality-master
myplot_RAC.m
.m
Seasonality-master/script/exploratory/myplot_RAC/myplot_RAC.m
4,588
utf_8
33c81ccad436bc310b0ca9b317467c48
%% myplot_RAC % This function plots Rank-Abundance Curve. (each community well be presented in subplots, so cannot be embeded in subplot) % % depends on: [mycolor.m], [mysubplot.m] %% *Syntax* % myplot_RAC(X) % X : matrix of size [n, p] ; n communities, p species % % myplot_RAC(X, strs, strn, bigtitle, colorsheet, stylesheet) % strs : string or cell array of strings, the name of the "species" % default is {'spp 1', 'spp 2', ...}; will show as legends % if input is str, will replace the 'spp' in the defult. % strn : string or cell array of strings, the name of the "communities" % default is {'Community 1', 'Community 2', ...}; will show % as title; usage is similar to strs % bigtitle :the bigtitle, deafult is 'Rank-Abundance Curve' % colorsheet : the color of each Species, ranked in the first row % if input is only 1 % stylesheet : the style of each Species, ranked in the first row function myplot_RAC(X, strs, strn, bigtitle, colorsheet, stylesheet) [n, p] = size( X ); %% Defult names if nargin <2 || isempty(strs) strs = 'spp'; end if nargin <3 || isempty(strn) strn = 'Community'; end if nargin <4 || isempty(bigtitle) bigtitle = 'Rank-Abundance Curve'; end %% input names as string if iscell(strs) legends =strs; if length( legends) < p warning('The number of species does not match with "strs" '); end else for s = 1:p legends{s} = [strs, ' ', num2str(s)]; end end if iscell(strn) if length(strn) == n titles =strn; else error('The number of communities does not match with "strn" '); end else for c = 1:n titles{c} = [strn, ' ', num2str(c)]; end end %% Default color temp = mycolor(-1) ; if nargin <5 || isempty(colorsheet) colorsheet = temp([3:19, 21:26, 28, 30:39 ],:); if p> 34 error('number of species is too large; the default color only has 34 colors'); end end [a, b] = size(colorsheet); if isvector(colorsheet) && b~=3 && isnumeric(colorsheet) colorsheet = temp(colorsheet, :); end if a == 1 colorsheet = repmat(colorsheet, p, 1); end if p > length(colorsheet) error('number of species is too large; the default color only has 34 colors'); end %% Default style if nargin <6 || isempty(stylesheet) stylesheet = {'o', 's','d','^','p','>','<', 'o', 's','d','^','p','>','<','o', 's','d','^','p','>','<',... 'o', 's','d','^','p','>','<', 'o', 's','d','^','p','>','<','o', 's','d','^','p','>','<'}; end if ischar(stylesheet) sty = stylesheet; stylesheet =[]; for i = 1:p stylesheet{i} = sty; end end if length(stylesheet) < p st = stylesheet; warning('Input style will be recycled because number of species > number of style') while length(stylesheet) < p stylesheet = [stylesheet, st]; end end %% The first row figure [B, I ] = sort( X( 1, : ), 'descend'); if n >1 % mysubplot(1, n+2, 0, bigtitle) mysubplot(1, n, 1, '', 0.25, 0.1) end for s = 1:p ranks = find(I==s); h = scatter(ranks , X(1, s) ,60, stylesheet{ranks},'Markeredgecolor','none','Markerfacecolor',colorsheet(s, :)); hold on %colorsheet(ranks,:) end myplot( 1:p, B , 'L', 1); hold on % legend(legends{:}) % replot so the symbles are on top for s = 1:p ranks = find(I==s); h = scatter(ranks , X(1, s) ,60, stylesheet{ranks},'Markeredgecolor','none','Markerfacecolor',colorsheet(s, :)); hold on %colorsheet(ranks,:) end axis([1 p 0 max(max(X))]) ; title(titles{1}); ylabel('Abundance');xlabel('Rank') set(gca,'yscale','log','Fontsize',16); %CP added this %% 2~n %X1 = X( :, I ); % in the new matrix, row 1 is sorted X1=X; %CP this is modified for i = 2:n mysubplot(1, n, i, '', 0.25, 0.1) [y, id ] = sort(X1(i,:), 'descend'); myplot( 1:p, y , 'L', 1);hold on for s = 1:p h = scatter( s, y(s) ,60, stylesheet{id(s)},'Markeredgecolor','none','Markerfacecolor',colorsheet(id(s), :)); hold on %CP before, was s, y(s), [...] colorsheet(id(s),:) end box off axis([1 p 0 max(max(X))]) ; set(gca, 'ytick', '') title(titles{i}) xlabel('Rank') set(gca,'yscale','log','Fontsize',16); %CP added this end
github
CoraliePicoche/Seasonality-master
mycolor.m
.m
Seasonality-master/script/exploratory/myplot_RAC/mycolor.m
6,462
utf_8
6b64fa12d5597f8423cb337bb409bd06
% Color selecter: generating a 3-number vector code for a color. % Syntax: % code = mycolor(colorcode,selectplate) % Input: % [colorcode]: integer, selecting from the color plate % e.g. colorcode = 3, means a dark blue from the defaultplate 'color' % colorcode = 0 (default): will display the color plate assigned in a new figure % colorcode = -1 ; return the colormap (3 * ?) matrix, specified in [selectplate] % colorcode is a string (passed to selectplate), return colormap (as colorcode = -1); % [selectplate]: a string, assign the plate you want to chose from % 'color': default % 'redblue': a red to blue bipolor scale % 'gray': a gray scale % * For detail of color plates type mycolor(0) % mycolor(0,'redblue') % mycolor(0,'gray') % Output: % [code]: a vector of size 3, the code for the selected color %------------------------------------------------------------------------------- % % Example: use in plot function % % plot([1:10], rand(1,10),'color',mycolor(3)) % % Example: to display color plate % % mycolor(0,'redblue') % display the red-blue color map % mycolor % equals to mycolor(0,'color') or mycolor(0), display the default color map % % Example: return colormap % cmap = mycolor(-1) % cmap = mycolor('color') % cmap = mycolor('redblue') % % update 2015/09/21: mycolor(0) will display the color plate in a new figure % add an optional input to select 'redblue' and 'gray' plate % update 2015/10/14: can take zero argument % update 2015/10/29: Add usage as colormap % update 2016/07/28: Add some colors, and white function code = mycolor(colorcode, selectplate) if (nargin < 1), colorcode = 0; end; if (nargin < 2) if ischar(colorcode) selectplate = colorcode; colorcode = -1; % set it -1 so it won't be passed through other output % output is the whole colormap else selectplate = 'color' ; end end %% Making color map mycolors(1,:) = ([0 0 0]); mycolors(2,:) = ([0.8 0.2 0.2]); mycolors(3,:) = ([0.0 0.2 0.6]); mycolors(4,:) = ([0.1 0.5 0.1]); mycolors(5,:) = ([0.8 0.7 0.1]); mycolors(6,:) = ([0.4 0.1 0.8]); mycolors(7,:) = ([0.4 0.4 0.4]); mycolors(8,:) = ([0.2 0.7 0.8]); mycolors(9,:) = ([0.6 0.2 0.2]); mycolors(10,:) = ([0.8 0.1 0.8]); mycolors(11,:) = ([0.0 0.4 0.6]); mycolors(12,:) = ([0.5 0.8 0.0]); mycolors(13,:) = ([0.9 0.4 0.1]); % mycolors(14,:) =([0.0745 0.2078 0.3686]); mycolors(15,:) =([0.1765 0.6275 0.6431]); mycolors(16,:) =([0.3725 0.0588 0.0784]); mycolors(17,:) =([0.3339 0.3335 0.5202]); mycolors(18,:) =([0.1373 0.4902 0.3255]); mycolors(19,:) =([0.7765 0.4510 0.0196]); mycolors(20,:) =([0.9725 0.9529 0.8431]); % mycolors(21,:) =([0.0588 0.2941 0.6353]); mycolors(22,:) =([0.0784 0.2588 0.0745]); mycolors(23,:) =([0.6588 0.3529 0]); mycolors(24,:) =([0.4196 0.5098 0.4314]); mycolors(25,:) =([0.4980 0.5412 0.0902]); mycolors(26,:) =([0.9216 0.7961 0.2745]); mycolors(27,:) =([0.9408 0.9369 0.8114]); % mycolors(28,:) =([0.5333 0.7216 0.8471]); mycolors(29,:) =([0.9373 0.8706 0.7216]); mycolors(30,:) =([0.9725 0.1804 0.0863]); mycolors(31,:) =([0.2706 0.3020 0.3569]); mycolors(32,:) =([0.0980 0.4039 0.2667]); mycolors(33,:) =([0.9922 0.4392 0.2353]); mycolors(34,:) =([0 0.9 0]); mycolors(35,:) =([0.9 1 0.4]); mycolors(36,:) =([0.2 0.9 1]); mycolors(37,:) =([0.8 0.5 0.8]); mycolors(38,:) =([1 0.3 0.3]); mycolors(39,:) =([0.3 0.3 1 ]); mycolors(40, :) =([1 1 1] ); %% making a gray map mygrays(1,:)= ([0 0 0]); mygrays(2,:)= ([0.3 0.3 0.3]); mygrays(3,:)= ([0.45 0.45 0.45]); mygrays(4,:)= ([0.6 0.6 0.6]); mygrays(5,:)= ([0.8 0.8 0.8]); mygrays(6,:)= ([0.9 0.9 0.9]); %% making my red-blue color map for r = 1:32 myredblues(r,:) = [0.85 0.05 0.05]+[0 0.8 0.8]*(r/33); end for b = 1:32 myredblues(b+32,:) = [0.05 0.05 0.85]+[0.8 0.8 0]*((33-b)/33); end %% if colorcode > 0 if strcmp(selectplate,'color') code = mycolors(colorcode,:) ; else if strcmp(selectplate,'redblue') code = myredblues(colorcode,:) ; else if strcmp(selectplate,'gray') code = mygrays(colorcode,:) ; else error('input [selectcolor] not recognized'); end end end end %% If input colorcode == 0, display the color plate if colorcode==0 disp('Display color plate for you to chose.') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% figure %%% making color plate for red-blues if strcmp(selectplate,'redblue') for c = 0:63 plot([0 cos(0.098*c)],[0 sin(0.098*c)],'Linewidth',3,'color',myredblues(c+1,:));hold on text(cos(0.098*c)*1.05,sin(0.098*c)*1.05,num2str(c+1)); end end %%% making color plate for [mycolor] if strcmp(selectplate,'color') [n,p] = size(mycolors); for c = 0:n-1 plot([0 cos(0.15*c)],[0 sin(0.15*c)],'Linewidth',3,'color',mycolors(c+1,:));hold on text(cos(0.15*c)*1.05,sin(0.15*c)*1.05,num2str(c+1)) end end %%% making color plate for grays if strcmp(selectplate,'gray') [n,p] = size(mygrays); for c = 0:n-1 plot([0 cos(0.2*c)],[0 sin(0.2*c)],'Linewidth',3,'color',mygrays(c+1,:));hold on text(cos(0.2*c)*1.05,sin(0.2*c)*1.05,num2str(c+1)); end end axis([-1.1 1.1 -1.1 1.1]) axis off end %% If input colorcode == -1, output is the whole colormap if colorcode == -1 if strcmp(selectplate,'color') code=mycolors; end if strcmp(selectplate,'redblue') code=myredblues; end if strcmp(selectplate,'gray') code=mygrays; end end
github
xueshengke/libADMM-master
lrr.m
.m
libADMM-master/algorithms/lrr.m
3,529
utf_8
f415a5263180f31dc35bdec719b7bdf4
function [X,E,obj,err,iter] = lrr(A,B,lambda,opts) % Solve the Low-Rank Representation minimization problem by M-ADMM % % min_{X,E} ||X||_*+lambda*loss(E), s.t. A=BX+E % loss(E) = ||E||_1 or 0.5*||E||_F^2 or ||E||_{2,1} % % --------------------------------------------- % Input: % A - d*na matrix % B - d*nb matrix % lambda - >0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1': loss(E) = ||E||_1 % 'l2': loss(E) = 0.5*||E||_F^2 % 'l21' (default): loss(E) = ||E||_{2,1} % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % X - nb*na matrix % E - d*na matrix % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l21'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,na] = size(A); [~,nb] = size(B); X = zeros(nb,na); E = zeros(d,na); J = X; Y1 = E; Y2 = X; BtB = B'*B; BtA = B'*A; I = eye(nb); invBtBI = (BtB+I)\I; iter = 0; for iter = 1 : max_iter Xk = X; Ek = E; Jk = J; % first super block {J,E} [J,nuclearnormJ] = prox_nuclear(X+Y2/mu,1/mu); if strcmp(loss,'l1') E = prox_l1(A-B*X+Y1/mu,lambda/mu); elseif strcmp(loss,'l21') E = prox_l21(A-B*X+Y1/mu,lambda/mu); elseif strcmp(loss,'l2') E = mu*(A-B*X+Y1/mu)/(lambda+mu); else error('not supported loss function'); end % second super block {X} X = invBtBI*(B'*(Y1/mu-E)+BtA-Y2/mu+J); dY1 = A-B*X-E; dY2 = X-J; chgX = max(max(abs(Xk-X))); chgE = max(max(abs(Ek-E))); chgJ = max(max(abs(Jk-J))); chg = max([chgX chgE chgJ max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = nuclearnormJ+lambda*comp_loss(E,loss); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = nuclearnormJ+lambda*comp_loss(E,loss); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function out = comp_loss(E,loss) switch loss case 'l1' out = norm(E(:),1); case 'l21' out = 0; for i = 1 : size(E,2) out = out + norm(E(:,i)); end case 'l2' out = 0.5*norm(E,'fro')^2; end
github
xueshengke/libADMM-master
groupl1.m
.m
libADMM-master/algorithms/groupl1.m
2,730
utf_8
71035c51c2852449c2ddbc3091fe41ed
function [X,obj,err,iter] = groupl1(A,B,G,opts) % Solve the group l1-minimization problem by ADMM % % min_X \sum_{i=1}^n\sum_{g in G} ||(x_i)_g||_2, s.t. AX=B % % x_i is the i-th column of X % --------------------------------------------- % Input: % A - d*na matrix % B - d*nb matrix % G - a cell indicates a partition of 1:na % opts - Structure value in Matlab. The fields are % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % X - na*nb matrix % obj - objective function value % err - residual ||AX-B||_F % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,na] = size(A); [~,nb] = size(B); X = zeros(na,nb); Z = X; Y1 = zeros(d,nb); Y2 = X; AtB = A'*B; I = eye(na); invAtAI = (A'*A+I)\I; iter = 0; for iter = 1 : max_iter Xk = X; Zk = Z; % update X for i = 1 : nb X(:,i) = prox_gl1(Z(:,i)-Y2(:,i)/mu,G,1/mu); end % update Z Z = invAtAI*(-(A'*Y1-Y2)/mu+AtB+X); dY1 = A*Z-B; dY2 = X-Z; chgX = max(max(abs(Xk-X))); chgZ = max(max(abs(Zk-Z))); chg = max([chgX chgZ max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = compute_obj(X,G); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = compute_obj(X,G); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function obj = compute_obj(X,G) obj = 0; for i = 1 : size(X,2) x = X(:,i); for j = 1 : length(G) obj = obj + norm(x(G{j})); end end
github
xueshengke/libADMM-master
rpca.m
.m
libADMM-master/algorithms/rpca.m
2,944
utf_8
1930326cf4bf01c764909897658853ca
function [L,S,obj,err,iter] = rpca(X,lambda,opts) % Solve the Robust Principal Component Analysis minimization problem by M-ADMM % % min_{L,S} ||L||_*+lambda*loss(S), s.t. X=L+S % loss(S) = ||S||_1 or ||S||_{2,1} % % --------------------------------------------- % Input: % X - d*n matrix % lambda - >0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1' (default): loss(S) = ||S||_1 % 'l21': loss(S) = ||S||_{2,1} % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % L - d*n matrix % S - d*n matrix % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 19/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l1'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n] = size(X); L = zeros(d,n); S = L; Y = L; iter = 0; for iter = 1 : max_iter Lk = L; Sk = S; % update L [L,nuclearnormL] = prox_nuclear(-S+X-Y/mu,1/mu); % update S if strcmp(loss,'l1') S = prox_l1(-L+X-Y/mu,lambda/mu); elseif strcmp(loss,'l21') S = prox_l21(-L+X-Y/mu,lambda/mu); else error('not supported loss function'); end dY = L+S-X; chgL = max(max(abs(Lk-L))); chgS = max(max(abs(Sk-S))); chg = max([chgL chgS max(abs(dY(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = nuclearnormL+lambda*comp_loss(S,loss); err = norm(dY,'fro'); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y = Y + mu*dY; mu = min(rho*mu,max_mu); end obj = nuclearnormL+lambda*comp_loss(S,loss); err = norm(dY,'fro'); function out = comp_loss(E,loss) switch loss case 'l1' out = norm(E(:),1); case 'l21' out = 0; for i = 1 : size(E,2) out = out + norm(E(:,i)); end end
github
xueshengke/libADMM-master
tracelasso.m
.m
libADMM-master/algorithms/tracelasso.m
2,583
utf_8
536f5ce74c82d5f183c3c967e14d6cf6
function [x,obj,err,iter] = tracelasso(A,b,opts) % Solve the trace Lasso minimization problem by ADMM % % min_x ||A*Diag(x)||_*, s.t. Ax=b % % --------------------------------------------- % Input: % A - d*n matrix % b - d*1 vector % opts - Structure value in Matlab. The fields are % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % x - n*1 vector % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n] = size(A); x = zeros(n,1); Z = zeros(d,n); Y1 = zeros(d,1); Y2 = Z; Atb = A'*b; AtA = A'*A; invAtA = (AtA+diag(diag(AtA)))\eye(n); iter = 0; for iter = 1 : max_iter xk = x; Zk = Z; % update x x = invAtA*(-A'*Y1/mu+Atb+diagAtB(A,-Y2/mu+Z)); % update Z [Z,nuclearnorm] = prox_nuclear(A*diag(x)+Y2/mu,1/mu); dY1 = A*x-b; dY2 = A*diag(x)-Z; chgx = max(abs(xk-x)); chgZ = max(abs(Zk-Z)); chg = max([chgx chgZ max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = nuclearnorm; err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = nuclearnorm; err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function v = diagAtB(A,B) % A, B - d*n matrices % v = diag(A'*B), n*1 vector n = size(A,2); v = zeros(n,1); for i = 1 : n v(i) = A(:,i)'*B(:,i); end
github
xueshengke/libADMM-master
groupl1R.m
.m
libADMM-master/algorithms/groupl1R.m
3,417
utf_8
daad367680f297bfd5a82197bec8b72d
function [X,E,obj,err,iter] = groupl1R(A,B,G,lambda,opts) % Solve the group l1 norm regularized minimization problem by M-ADMM % % min_{X,E} loss(E)+lambda*\sum_{i=1}^n\sum_{g in G} ||(x_i)_g||_2, s.t. AX+E=B % x_i is the i-th column of X % loss(E) = ||E||_1 or 0.5*||E||_F^2 % --------------------------------------------- % Input: % A - d*na matrix % B - d*nb matrix % G - a cell indicates a partition of 1:na % opts - Structure value in Matlab. The fields are % opts.loss - 'l1' (default): loss(E) = ||E||_1 % 'l2': loss(E) = 0.5*||E||_F^2 % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % X - na*nb matrix % E - d*nb matrix % obj - objective function value % err - residual ||AX+E-B||_F % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l1'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,na] = size(A); [~,nb] = size(B); X = zeros(na,nb); E = zeros(d,nb); Z = X; Y1 = E; Y2 = X; AtB = A'*B; I = eye(na); invAtAI = (A'*A+I)\I; iter = 0; for iter = 1 : max_iter Xk = X; Ek = E; Zk = Z; % first super block {X,E} for i = 1 : nb X(:,i) = prox_gl1(Z(:,i)-Y2(:,i)/mu,G,1/mu); end if strcmp(loss,'l1') E = prox_l1(B-A*Z-Y1/mu,1/mu); elseif strcmp(loss,'l2') E = mu*(B-A*Z-Y1/mu)/(1+mu); else error('not supported loss function'); end % second super block {Z} Z = invAtAI*(-A'*(Y1/mu+E)+AtB+Y2/mu+X); dY1 = A*Z+E-B; dY2 = X-Z; chgX = max(max(abs(Xk-X))); chgE = max(max(abs(Ek-E))); chgZ = max(max(abs(Zk-Z))); chg = max([chgX chgE chgZ max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = comp_loss(E,loss)+lambda*compute_groupl1(X,G); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = comp_loss(E,loss)+lambda*compute_groupl1(X,G); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function obj = compute_groupl1(X,G) obj = 0; for i = 1 : size(X,2) x = X(:,i); for j = 1 : length(G) obj = obj + norm(x(G{j})); end end
github
xueshengke/libADMM-master
mlap.m
.m
libADMM-master/algorithms/mlap.m
4,761
utf_8
ad408cb013b2ffa24973702254b4d4e0
function [Z,E,obj,err,iter] = mlap(X,lambda,alpha,opts) % Solve the Multi-task Low-rank Affinity Pursuit (MLAP) minimization problem by M-ADMM % % Reference: Cheng, Bin, Guangcan Liu, Jingdong Wang, Zhongyang Huang, and Shuicheng Yan. % Multi-task low-rank affinity pursuit for image segmentation. ICCV, 2011. % % min_{Z_i,E_i} \sum_{i=1}^K (||Z_i||_*+lambda*loss(E_i))+alpha*||Z||_{2,1}, % s.t. X_i=X_i*Z_i+E_i, i=1,...,K. % loss(E) = ||E||_1 or 0.5*||E||_F^2 or ||E||_{2,1} % % --------------------------------------------- % Input: % X - d*n*K tensor % lambda - >0, parameter % alpha - >0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1': loss(E) = ||E||_1 % 'l2': loss(E) = 0.5*||E||_F^2 % 'l21' (default): loss(E) = ||E||_{2,1} % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % Z - n*n*K tensor % E - d*n*K tensor % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l21'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n,K] = size(X); Z = zeros(n,n,K); E = zeros(d,n,K); J = Z; S = Z; Y = E; W = Z; V = Z; dY = Y; XmXS = E; XtX = zeros(n,n,K); invXtXI = zeros(n,n,K); I = eye(n); for i = 1 : K XtX(:,:,i) = X(:,:,i)'*X(:,:,i); invXtXI(:,:,i) = (XtX(:,:,i)+I)\I; end nuclearnormJ = zeros(K,1); iter = 0; for iter = 1 : max_iter Zk = Z; Ek = E; Jk = J; Sk = S; % first super block {J,S} for i = 1 : K [J(:,:,i),nuclearnormJ(i)] = prox_nuclear(Z(:,:,i)+W(:,:,i)/mu,1/mu); S(:,:,i) = invXtXI(:,:,i)*(XtX(:,:,i)-X(:,:,i)'*(E(:,:,i)-Y(:,:,i)/mu)+Z(:,:,i)+(V(:,:,i)-W(:,:,i))/mu); end % second super block {Z,E} Z = prox_tensor_l21((J+S-(W+V)/mu)/2,alpha/(2*mu)); for i = 1 : K XmXS(:,:,i) = X(:,:,i)-X(:,:,i)*S(:,:,i); end if strcmp(loss,'l1') for i = 1 : K E(:,:,i) = prox_l1(XmXS(:,:,i)+Y(:,:,i)/mu,lambda/mu); end elseif strcmp(loss,'l21') for i = 1 : K E(:,:,i) = prox_l21(XmXS(:,:,i)+Y(:,:,i)/mu,lambda/mu); end elseif strcmp(loss,'l2') for i = 1 : K E = (XmXS(:,:,i)+Y(:,:,i)/mu) / (lambda/mu+1); end else error('not supported loss function'); end dY = XmXS-E; dW = Z-J; dV = Z-S; chgZ = max(abs(Zk(:)-Z(:))); chgE = max(abs(Ek(:)-E(:))); chgJ = max(abs(Jk(:)-J(:))); chgS = max(abs(Sk(:)-S(:))); chg = max([chgZ chgE chgJ chgS max(abs(dY(:))) max(abs(dW(:))) max(abs(dV(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = sum(nuclearnormJ)+lambda*comp_loss(E,loss)+alpha*comp_loss(Z,'l21'); err = sqrt(norm(dY(:))^2+norm(dW(:))^2+norm(dV(:))^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y = Y + mu*dY; W = W + mu*dW; V = V + mu*dV; mu = min(rho*mu,max_mu); end obj = sum(nuclearnormJ)+lambda*comp_loss(E,loss)+alpha*comp_loss(Z,'l21'); err = sqrt(norm(dY(:))^2+norm(dW(:))^2+norm(dV(:))^2); function X = prox_tensor_l21(B,lambda) % proximal operator of tensor l21-norm, i.e., the sum of the l2 norm of all % tubes of a tensor. % % X - n1*n2*n3 tensor % B - n1*n2*n3 tensor % % min_X lambda*\sum_{i=1}^n1\sum_{j=1}^n2 ||X(i,j,:)||_2 + 0.5*||X-B||_F^2 [n1,n2,n3] = size(B); X = zeros(n1,n2,n3); for i = 1 : n1 for j = 1 : n2 v = B(i,j,:); nxi = norm(v(:)); if nxi > lambda X(i,j,:) = (1-lambda/nxi)*B(i,j,:); end end end
github
xueshengke/libADMM-master
lrsr.m
.m
libADMM-master/algorithms/lrsr.m
3,838
utf_8
8bd2f6bd0800a5a346a5a4bfbb011702
function [X,E,obj,err,iter] = lrsr(A,B,lambda1,lambda2,opts) % Solve the Low-Rank and Sparse Representation (LRSR) minimization problem by M-ADMM % % min_{X,E} ||X||_*+lambda1*||X||_1+lambda2*loss(E), s.t. A=BX+E % loss(E) = ||E||_1 or 0.5*||E||_F^2 or ||E||_{2,1} % --------------------------------------------- % Input: % A - d*na matrix % B - d*nb matrix % lambda1 - >0, parameter % lambda2 - >0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1': loss(E) = ||E||_1 % 'l2': loss(E) = 0.5*||E||_F^2 % 'l21' (default): loss(E) = ||E||_{2,1} % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % X - nb*na matrix % E - d*na matrix % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l21'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,na] = size(A); [~,nb] = size(B); X = zeros(nb,na); E = zeros(d,na); Z = X; J = X; Y1 = E; Y2 = X; Y3 = X; BtB = B'*B; BtA = B'*A; I = eye(nb); invBtBI = (BtB+2*I)\I; iter = 0; for iter = 1 : max_iter Xk = X; Zk = Z; Ek = E; Jk = J; % first super block {Z,J,E} [Z,nuclearnormZ] = prox_nuclear(X+Y2/mu,1/mu); J = prox_l1(X+Y3/mu,lambda1/mu); if strcmp(loss,'l1') E = prox_l1(A-B*X+Y1/mu,lambda2/mu); elseif strcmp(loss,'l21') E = prox_l21(A-B*X+Y1/mu,lambda2/mu); elseif strcmp(loss,'l2') E = mu*(A-B*X+Y1/mu)/(lambda2+mu); else error('not supported loss function'); end % second super block {X} X = invBtBI*(B'*(Y1/mu-E)+BtA-(Y2+Y3)/mu+Z+J); dY1 = A-B*X-E; dY2 = X-Z; dY3 = X-J; chgX = max(max(abs(Xk-X))); chgE = max(max(abs(Ek-E))); chgZ = max(max(abs(Zk-Z))); chgJ = max(max(abs(Jk-J))); chg = max([chgX chgE chgZ chgJ max(abs(dY1(:))) max(abs(dY2(:))) max(abs(dY3(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = nuclearnormZ+lambda1*norm(J(:),1)+lambda2*comp_loss(E,loss); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2+norm(dY3,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = nuclearnormZ+lambda1*norm(J(:),1)+lambda2*comp_loss(E,loss); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2+norm(dY3,'fro')^2); function out = comp_loss(E,normtype) switch normtype case 'l1' out = norm(E(:),1); case 'l21' out = 0; for i = 1 : size(E,2) out = out + norm(E(:,i)); end case 'l2' out = 0.5*norm(E,'fro')^2; end
github
xueshengke/libADMM-master
fusedl1R.m
.m
libADMM-master/algorithms/fusedl1R.m
3,714
utf_8
145be29163c05b2175bd848ba37d18d1
function [x,e,obj,err,iter] = fusedl1R(A,b,lambda1,lambda2,opts) % Solve the fused Lasso regularized minimization problem by ADMM % % min_{x,e} loss(e) + lambda1*||x||_1 + lambda2*\sum_{i=2}^p |x_i-x_{i-1}|, % loss(e) = ||e||_1 or 0.5*||e||_2^2 % % --------------------------------------------- % Input: % A - d*n matrix % b - d*1 vector % lambda1 - >=0, parameter % lambda2 - >=0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1' (default): loss(e) = ||e||_1 % 'l2': loss(E) = 0.5*||e||_2^2 % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % x - n*1 vector % e - d*1 vector % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 20/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l1'; % default if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n] = size(A); x = zeros(n,1); e = zeros(d,1); z = x; Y1 = e; Y2 = x; Atb = A'*b; I = eye(n); invAtAI = (A'*A+I)\I; % parameters for "flsa" (from SLEP package) tol2 = 1e-10; % the duality gap for termination max_step = 50; % the maximal number of iterations x0 = zeros(n-1,1); % the starting point iter = 0; for iter = 1 : max_iter xk = x; ek = e; zk = z; % first super block {x,e} % flsa solves min_x 1/2||x-v||_2^2+lambda1*||x||_1+lambda2*\sum_{i=2}^p |x_i-x_{i-1}|, x = flsa(z-Y2/mu,x0,lambda1/mu,lambda2/mu,n,max_step,tol2,1,6); if strcmp(loss,'l1') e = prox_l1(b-A*z-Y1/mu,1/mu); elseif strcmp(loss,'l2') e = mu*(b-A*z-Y1/mu)/(1+mu); else error('not supported loss function'); end % second super block {Z} z = invAtAI*(-A'*(Y1/mu+e)+Atb+Y2/mu+x); dY1 = A*z+e-b; dY2 = x-z; chgx = max(abs(xk-x)); chge = max(abs(ek-e)); chgz = max(abs(zk-z)); chg = max([chgx chge chgz max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = comp_loss(e,loss)+comp_fusedl1(x,lambda1,lambda2); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = comp_loss(e,loss)+comp_fusedl1(x,lambda1,lambda2); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function f = comp_fusedl1(x,lambda1,lambda2) % compute f = lambda1*||x||_1 + lambda2*\sum_{i=2}^p |x_i-x_{i-1}|. % x - p*1 vector f = 0; p = length(x); for i = 2 : p f = f+abs(x(i)-x(i-1)); end f = lambda1*norm(x,1)+lambda2*f;
github
xueshengke/libADMM-master
fusedl1.m
.m
libADMM-master/algorithms/fusedl1.m
3,027
utf_8
e180c20b97ac834bfde5d505c23bdb1e
function [x,obj,err,iter] = fusedl1(A,b,lambda,opts) % Solve the fused Lasso (Fused L1) minimization problem by ADMM % % min_x ||x||_1 + lambda*\sum_{i=2}^p |x_i-x_{i-1}|, % s.t. Ax=b % % --------------------------------------------- % Input: % A - d*n matrix % b - d*1 vector % lambda - >=0, parameter % opts - Structure value in Matlab. The fields are % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % x - n*1 vector % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 20/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n] = size(A); x = zeros(n,1); z = x; Y1 = zeros(d,1); Y2 = x; Atb = A'*b; I = eye(n); invAtAI = (A'*A+I)\I; % parameters for "flsa" (from SLEP package) tol2 = 1e-10; % the duality gap for termination max_step = 50; % the maximal number of iterations x0 = zeros(n-1,1); % the starting point iter = 0; for iter = 1 : max_iter xk = x; zk = z; % update x. % flsa solves min_x 1/2||x-v||_2^2+lambda1*||x||_1+lambda2*\sum_{i=2}^p |x_i-x_{i-1}| x = flsa(z-Y2/mu,x0,1/mu,lambda/mu,n,max_step,tol2,1,6); % update z z = invAtAI*(-A'*Y1/mu+Atb+Y2/mu+x); dY1 = A*z-b; dY2 = x-z; chgx = max(abs(xk-x)); chgz = max(abs(zk-z)); chg = max([chgx chgz max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = comp_fusedl1(x,1,lambda); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = comp_fusedl1(x,1,lambda); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function f = comp_fusedl1(x,lambda1,lambda2) % compute f = lambda1*||x||_1 + lambda2*\sum_{i=2}^p |x_i-x_{i-1}|. % x - p*1 vector f = 0; p = length(x); for i = 2 : p f = f+abs(x(i)-x(i-1)); end f = lambda1*norm(x,1)+lambda2*f;
github
xueshengke/libADMM-master
tracelassoR.m
.m
libADMM-master/algorithms/tracelassoR.m
3,247
utf_8
8bc2e00ce23aaa6478590829303525b6
function [x,e,obj,err,iter] = tracelassoR(A,b,lambda,opts) % Solve the trace Lasso regularized minimization problem by M-ADMM % % min_{x,e} loss(e)+lambda*||A*Diag(x)||_*, s.t. Ax+e=b % loss(e) = ||e||_1 or 0.5*||e||_2^2 % --------------------------------------------- % Input: % A - d*n matrix % b - d*1 vector % opts - Structure value in Matlab. The fields are % opts.loss - 'l1' (default): loss(e) = ||e||_1 % 'l2': loss(e) = 0.5*||e||_2^2 % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % x - n*1 vector % e - d*1 vector % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l1'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n] = size(A); x = zeros(n,1); Z = zeros(d,n); e = zeros(d,1); Y1 = e; Y2 = Z; Atb = A'*b; AtA = A'*A; invAtA = (AtA+diag(diag(AtA)))\eye(n); iter = 0; for iter = 1 : max_iter xk = x; ek = e; Zk = Z; % first super block {Z,e} [Z,nuclearnorm] = prox_nuclear(A*diag(x)-Y2/mu,lambda/mu); if strcmp(loss,'l1') e = prox_l1(b-A*x-Y1/mu,1/mu); elseif strcmp(loss,'l2') e = mu*(b-A*x-Y1/mu)/(1+mu); else error('not supported loss function'); end % second super block {x} x = invAtA*(-A'*(Y1/mu+e)+Atb+diagAtB(A,Y2/mu+Z)); dY1 = A*x+e-b; dY2 = Z-A*diag(x); chgx = max(abs(xk-x)); chge = max(abs(ek-e)); chgZ = max(max(abs(Zk-Z))); chg = max([chgx chge chgZ max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = comp_loss(e,loss)+lambda*nuclearnorm; err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = comp_loss(e,loss)+lambda*nuclearnorm; err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function v = diagAtB(A,B) % A, B - d*n matrices % v = diag(A'*B), n*1 vector n = size(A,2); v = zeros(n,1); for i = 1 : n v(i) = A(:,i)'*B(:,i); end
github
xueshengke/libADMM-master
latlrr.m
.m
libADMM-master/algorithms/latlrr.m
3,636
utf_8
51a08d8f2880a125c6d1dda689ba9f7f
function [Z,L,obj,err,iter] = latlrr(X,lambda,opts) % Solve the Latent Low-Rank Representation by M-ADMM % % min_{Z,L,E} ||Z||_*+||L||_*+lambda*loss(E), % s.t., XZ+LX-X=E. % loss(E) = ||E||_1 or 0.5*||E||_F^2 or ||E||_{2,1} % --------------------------------------------- % Input: % X - d*n matrix % lambda - >0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1' (default): loss(E) = ||E||_1 % 'l2': loss(E) = 0.5*||E||_F^2 % 'l21': loss(E) = ||E||_{2,1} % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % Z - n*n matrix % L - d*d matrix % E - d*n matrix % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 19/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l1'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end eta1 = 1.02*2*norm(X,2)^2; % for Z eta2 = eta1; % for L eta3 = 1.02*2; % for E [d,n] = size(X); E = zeros(d,n); Z = zeros(n,n); L = zeros(d,d); Y = E; XtX = X'*X; XXt = X*X'; iter = 0; for iter = 1 : max_iter Lk = L; Ek = E; Zk = Z; % first super block {Z} [Z,nuclearnormZ] = prox_nuclear(Zk-(X'*(Y/mu+L*X-X-E)+XtX*Z)/eta1,1/(mu*eta1)); % second super block {L,E} temp = Lk-((Y/mu+X*Z-Ek)*X'+Lk*XXt-XXt)/eta2; [L,nuclearnormL] = prox_nuclear(temp,1/(mu*eta2)); if strcmp(loss,'l1') E = prox_l1(Ek+(Y/mu+X*Z+Lk*X-X-Ek)/eta3,lambda/(mu*eta3)); elseif strcmp(loss,'l21') E = prox_l21(Ek+(Y/mu+X*Z+Lk*X-X-Ek)/eta3,lambda/(mu*eta3)); elseif strcmp(loss,'l2') E = (Y+mu*(X*Z+Lk*X-X+(eta3-1)*Ek))/(lambda+mu*eta3); else error('not supported loss function'); end dY = X*Z+L*X-X-E; chgL = max(max(abs(Lk-L))); chgE = max(max(abs(Ek-E))); chgZ = max(max(abs(Zk-Z))); chg = max([chgL chgE chgZ max(abs(dY(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = nuclearnormZ+nuclearnormL+lambda*comp_loss(E,loss); err = norm(dY,'fro')^2; disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y = Y + mu*dY; mu = min(rho*mu,max_mu); end obj = nuclearnormZ+nuclearnormZ+lambda*comp_loss(E,loss); err = norm(dY,'fro')^2; function out = comp_loss(E,loss) switch loss case 'l1' out = norm(E(:),1); case 'l21' out = 0; for i = 1 : size(E,2) out = out + norm(E(:,i)); end case 'l2' out = 0.5*norm(E,'fro')^2; end
github
xueshengke/libADMM-master
prox_ksupport.m
.m
libADMM-master/proximal_operator/prox_ksupport.m
1,804
utf_8
028824f0d5fbd7a1023a530eb9fc2265
function B = prox_ksupport(v,k,lambda) % The proximal operator of the k support norm of a vector % % min_x 0.5*lambda*||x||_{ksp}^2+0.5*||x-v||_2^2 % % version 1.0 - 27/06/2016 % % Written by Hanjiang Lai % % Reference: % Lai H, Pan Y, Lu C, et al. Efficient k-support matrix pursuit, ECCV, 2014: 617-631. % L = 1/lambda; d = length(v); if k >= d B = L*v/(1+L); return; elseif k <= 1 k = 1; end [z, ind] = sort(abs(v), 'descend'); z = z*L; ar = cumsum(z); z(d+1) = -inf; diff = 0; err = inf; found = false; for r=k-1:-1:0 [l,T] = bsearch(z,ar,k-r,d,diff,k,r,L); if ( ((L+1)*T >= (l-k+(L+1)*r+L+1)*z(k-r)) && ... (((k-r-1 == 0) || (L+1)*T < (l-k+(L+1)*r+L+1)*z(k-r-1)) ) ) found = true; break; end diff = diff + z(k-r); if k-r-1 == 0 err_tmp = max(0,(l-k+(L+1)*r+L+1)*z(k-r) - (L+1)*T); else err_tmp = max(0,(l-k+(L+1)*r+L+1)*z(k-r) -(L+1)*T) + max(0, - (l-k+(L+1)*r+L+1)*z(k-r-1) + (L+1)*T); end if err > err_tmp err_r = r; err_l = l; err_T = T; err = err_tmp; end end if found == false r = err_r; l = err_l; T = err_T; end % fprintf('r = %d, l = %d \n',r,l); p(1:k-r-1) = z(1:k-r-1)/(L+1); p(k-r:l) = T / (l-k+(L+1)*r+L+1); p(l+1:d) = z(l+1:d); p = p'; % [dummy, rev]=sort(ind,'ascend'); rev(ind) = 1:d; p = sign(v) .* p(rev); B = v - 1/L*p; end function [l,T] = bsearch(z,array,low,high,diff,k,r,L) if z(low) == 0 l = low; T = 0; return; end %z(mid) * tmp - (array(mid) - diff) > 0 %z(mid+1) * tmp - (array(mid+1) - diff) <= 0 while( low < high ) mid = floor( (low + high)/2 ) + 1; tmp = (mid - k + r + 1 + L*(r+1)); if z(mid) * tmp - (array(mid) - diff) > 0 low = mid; else high = mid - 1; end end l = low; T = array(low) - diff; end
github
xinario/SAGAN-master
get_ct_window_size.m
.m
SAGAN-master/poisson_noise_simulation/get_ct_window_size.m
469
utf_8
c9540ad023b1cc0ff035bb7f16d3367a
% get_ct_window_size -- get the display window size. % Paras: % @type : window type % Author: Xin Yi ([email protected]) % Date : 03/22/2017 function [center, width] = get_ct_window_size(type) if strcmp(type, 'lung') center = -700; width = 1500; elseif strcmp(type, 'abdomen') center = 40; width = 400; elseif strcmp(type, 'bone') center = 300; width = 2000; elseif strcmp(type, 'narrow') center = 40; width = 80; end
github
xinario/SAGAN-master
add_poisson_noise.m
.m
SAGAN-master/poisson_noise_simulation/add_poisson_noise.m
884
utf_8
c5d7164b81d8057fa588e5b4f4e8fb7a
% add_poisson_noise -- add poisson noise to a ct slice. % Paras: % @im : attenuation coefficients of a single ct slice % @N0 : x-ray source influx % Author: Xin Yi ([email protected]) % Date : 03/22/2017 function im_noise = add_poisson_noise(im_ac, N0) dtheta = 0.3; dsensor = 0.1; D = 500; sinogram_in = fanbeam(im_ac, D, 'FanSensorSpacing', dsensor, 'FanRotationIncrement', dtheta); %small number >0 that reflects the smallest possible detected photon count epsilon = 5; % to detector count coefficients unit is cm-1 sinogramCT = N0 * exp(-sinogram_in*0.0625); % add poison noise sinogramCT_noise = poissrnd(sinogramCT); sinogram_out = -log(sinogramCT_noise/N0)/0.0625; idx = isinf(sinogram_out); sinogram_out(idx) = -log(epsilon/N0)/0.0625; im_noise = ifanbeam(sinogram_out, D, 'FanSensorSpacing', dsensor, 'OutputSize', max(size(im_ac)));
github
xinario/SAGAN-master
ac2window.m
.m
SAGAN-master/poisson_noise_simulation/ac2window.m
568
utf_8
a1a50589657dc539101e2188ebe364e3
% ac2window -- rescale the ct slice to a specific window range % Paras: % @im_ac : image of attenuation coefficients % @window_type : dispaly window type % Author: Xin Yi ([email protected]) % Date : 03/22/2017 function im_dicom = ac2window(im_ac, window_type) im_dicom_raw = (im_ac - 0.17)/0.17*1000; [center, width] = get_ct_window_size(window_type); im_dicom = uint8(((double(im_dicom_raw) - (center-0.5))/(width-1)+0.5)*255); im_dicom(im_dicom_raw<=center-0.5-(width-1)/2) = 0; im_dicom(im_dicom_raw>center-0.5+(width-1)/2) = 255; end
github
xinario/SAGAN-master
dicom_read_ac.m
.m
SAGAN-master/poisson_noise_simulation/dicom_read_ac.m
629
utf_8
41b0e9973a2e7226fea3759367d012a4
% dicom_read_ac -- transfer the hunsfield units to attenuation coefficents. % Paras: % @file_path : path to the dicom image % Author: Xin Yi ([email protected]) % Date : 03/22/2017 function im_ac = dicom_read_ac(file_path) im_dicom_raw = dicomread(file_path); info = dicominfo(file_path); mask = im_dicom_raw == info.PixelPaddingValue; im_dicom_recaled = im_dicom_raw*info.RescaleSlope + info.RescaleIntercept; %0.17 is the attenuation coef (1/cm) of water at 100 keV im_ac = 0.17*double(im_dicom_recaled) /1000 + 0.17; im_ac(mask) = 0; im_ac(im_ac<0) = 0; end
github
BookIndRandSamplingMethods/code-master
randsrc.m
.m
code-master/CHAPTER_4/ARS_PARS_for_Nakagami_Target/randsrc.m
3,317
utf_8
40674a451df280dbf8f5fb1d2ad7f2d9
% %% Copyright (C) 2003 David Bateman % ## % ## This program is free software; you can redistribute it and/or modify % ## it under the terms of the GNU General Public License as published by % ## the Free Software Foundation; either version 2 of the License, or % ## (at your option) any later version. % ## % ## This program is distributed in the hope that it will be useful, % ## but WITHOUT ANY WARRANTY; without even the implied warranty of % ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % ## GNU General Public License for more details. % ## % ## You should have received a copy of the GNU General Public License % ## along with this program; if not, write to the Free Software % ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % ## -*- texinfo -*- % ## @deftypefn {Function File} {@var{b} = } randsrc (@var{n}) % ## @deftypefnx {Function File} {@var{b} = } randsrc (@var{n},@var{m}) % ## @deftypefnx {Function File} {@var{b} = } randsrc (@var{n},@var{m},@var{alphabet}) % ## @deftypefnx {Function File} {@var{b} = } randsrc (@var{n},@var{m},@var{alphabet},@var{seed}) % ## % ## Generate a matrix of random symbols. The size of the matrix is % ## @var{n} rows by @var{m} columns. By default @var{m} is equal to @var{n}. % ## % ## The variable @var{alphabet} can be either a row vector or a matrix with % ## two rows. When @var{alphabet} is a row vector the symbols returned in % ## @var{b} are chosen with equal probability from @var{alphabet}. When % ## @var{alphabet} has two rows, the second row determines the probabilty % ## with which each of the symbols is chosen. The sum of the probabilities % ## must equal 1. By default @var{alphabet} is [-1 1]. % ## % ## The variable @var{seed} allows the random number generator to be seeded % ## with a fixed value. The initial seed will be restored when returning. % ## @end deftypefn % % ## 2003 FEB 13 % ## initial release % function b = randsrc (n, m, alphabet, seed) switch (nargin) case 0, m = 1; n = 1; alphabet = [-1,1]; seed = Inf; case 1, m = n; alphabet = [-1,1]; seed = Inf; case 2, alphabet = [-1,1]; seed = Inf; case 3, seed = Inf; case 4, otherwise % usage ("b = randsrc (n, [m, [alphabet, [seed]]])"); end %switch %%%% Check alphabet [ar,ac] = size (alphabet); if (ac == 1) b = alphabet (1, 1) * ones (n, m); return; end %if if (ar == 1) prob = [1:ac] / ac; elseif (ar == 2) prob = alphabet(2,:); alphabet = alphabet(1,:); if (abs(1-sum(prob)) > eps) % error ("randsrc: probabilities must added up to one"); end%if prob = cumsum(prob); else % error ("randsrc: alphabet must have 1 or 2 rows"); end %if % Check seed; %if (!isinf (seed)) % old_seed = rand ('seed'); % rand ('seed', seed); %end %if %%%% Create indexes with the right probabilities tmp = rand (n, m); b = ones (n, m); for i = 1:ac-1 b = b + (tmp > prob(i)); end %%%% Map the indexes to the symbols b = alphabet(b); %%%%% BUG: the above gives a row vector for some reason. Force what we want b = reshape(b, n, m); %%%%% Get back to the old %if (!isinf (seed)) % rand ("seed", old_seed); %end %if %end%function
github
BookIndRandSamplingMethods/code-master
scatterhist.m
.m
code-master/CHAPTER_2/scatterhist.m
11,895
utf_8
d75e1d150a4a9c7f080708aeaf22aa05
function h = scatterhist(x,y,varargin) %SCATTERHIST 2D scatter plot with marginal histograms. % SCATTERHIST(X,Y) creates a 2D scatterplot of the data in the vectors X % and Y, and puts a univariate histogram on the horizontal and vertical % axes of the plot. X and Y must be the same length. % % SCATTERHIST(...,'PARAM1',VAL1,'PARAM2',VAL2,...) specifies additional % parameters and their values to control how the plot is made. Valid % parameters are the following: % % Parameter Value % 'NBins' A scalar or a two-element vector specifying the number of % bins for the X and Y histograms. The default is to compute % the number of bins using Scott's rule based on the sample % standard deviation. % % 'Location' A string controlling the location of the marginal % histograms within the figure. 'SouthWest' (the default) % plots the histograms below and to the left of the % scatterplot, 'SouthEast' plots them below and to the % right, 'NorthEast' above and to the right, and 'NorthWest' % above and to the left. % % 'Direction' A string controlling the direction of the marginal % histograms in the figure. 'in' (the default) plots the % histograms with bars directed in towards the scatterplot, % 'out' plots the histograms with bars directed out away % from the scatterplot. % % Any NaN values in either X or Y are treated as missing data, and are % removed from both X and Y. Therefore the plots reflect points for % which neither X nor Y has a missing value. % % Use the data cursor to read precise values and observation numbers % from the plot. % % H = SCATTERHIST(...) returns a vector of three axes handles for the % scatterplot, the histogram along the horizontal axis, and the histogram % along the vertical axis, respectively. % % Example: % Independent normal and lognormal random samples % x = randn(1000,1); % y = exp(.5*randn(1000,1)); % scatterhist(x,y) % Marginal uniform samples that are not independent % u = copularnd('Gaussian',.8,1000); % scatterhist(u(:,1),u(:,2)) % Mixed discrete and continuous data % load('carsmall'); % scatterhist(Weight,Cylinders,'NBins',[10 3]) % SCATTERHIST(X,Y,NBINS) is supported for backwards compatibility. % Copyright 2006-2011 The MathWorks, Inc. % $Revision: 1.1.6.8 $ $Date: 2011/10/15 02:06:59 $ narginchk(2, Inf); if ~isvector(x) || ~isnumeric(x) || ~isvector(y) || ~isnumeric(y) error(message('stats:scatterhist:BadXY')); end if numel(x)~=numel(y) error(message('stats:scatterhist:BadXY')); end x = x(:); y = y(:); obsinds = 1:numel(x); t = isnan(x) | isnan(y); if any(t) x(t) = []; y(t) = []; obsinds(t) = []; end location = 'sw'; % default value direction = 'in'; % default value if nargin < 3 || isempty(varargin{1}) % scatterhist(x,y) % By default use the bins given by Scott's rule [xctrs,yctrs] = defaultBins(x,y); else if nargin == 3 && ~ischar(varargin{1}) % scatterhist(x,y,nbins) nbins = varargin{1}; else % scatterhist(x,y,'name','value',...) pnames = {'nbins' 'location' 'direction'}; dflts = { [] location direction }; [nbins,location,direction] ... = internal.stats.parseArgs(pnames, dflts, varargin{:}); end if isempty(nbins) % By default use the bins given by Scott's rule [xctrs,yctrs] = defaultBins(x,y); elseif ~isnumeric(nbins) || ~(isscalar(nbins) || numel(nbins)==2) || ... any(nbins<=0) || any(nbins~=round(nbins)) error(message('stats:scatterhist:BadBins')); elseif isscalar(nbins) xctrs = nbins; % specified number of bins, same for x and y yctrs = nbins; else xctrs = nbins(1); % specified number of bins, x and y different yctrs = nbins(2); end end % Create the histogram information [nx,cx] = hist(x,xctrs); if length(cx)>1 dx = diff(cx(1:2)); else dx = 1; end xlim = [cx(1)-dx cx(end)+dx]; [ny,cy] = hist(y,yctrs); if length(cy)>1 dy = diff(cy(1:2)); else dy = 1; end ylim = [cy(1)-dy cy(end)+dy]; % Set up positions for the plots switch lower(direction) case 'in' inoutSign = 1; case 'out' inoutSign = -1; otherwise error(message('stats:scatterhist:BadDirection')); end switch lower(location) case {'ne' 'northeast'} scatterLoc = 3; scatterPosn = [.1 .1 .55 .55]; scatterXAxisLoc = 'top'; scatterYAxisLoc = 'right'; histXLoc = 1; histYLoc = 4; histXSign = -inoutSign; histYSign = -inoutSign; case {'se' 'southeast'} scatterLoc = 1; scatterPosn = [.1 .35 .55 .55]; scatterXAxisLoc = 'bottom'; scatterYAxisLoc = 'right'; histXLoc = 3; histYLoc = 2; histXSign = inoutSign; histYSign = -inoutSign; case {'sw' 'southwest'} scatterLoc = 2; scatterPosn = [.35 .35 .55 .55]; scatterXAxisLoc = 'bottom'; scatterYAxisLoc = 'left'; histXLoc = 4; histYLoc = 1; histXSign = inoutSign; histYSign = inoutSign; case {'nw' 'northwest'} scatterLoc = 4; scatterPosn = [.35 .1 .55 .55]; scatterXAxisLoc = 'top'; scatterYAxisLoc = 'left'; histXLoc = 2; histYLoc = 3; histXSign = -inoutSign; histYSign = inoutSign; otherwise error(message('stats:scatterhist:BadLocation')); end % Put up the histograms in preliminary positions. clf hHistY = subplot(2,2,histYLoc); barh(cy,histYSign*ny,1); xmax = max(ny); if xmax == 0, xmax = 1; end % prevent xlim from being [0 0] axis([sort(histYSign*[xmax, 0]), ylim]); axis('off'); hHistX = subplot(2,2,histXLoc); bar(cx,histXSign*nx,1); ymax = max(nx); if ymax == 0, ymax = 1; end % prevent ylim from being [0 0] axis([xlim, sort(histXSign*[ymax, 0])]); axis('off'); % Put the scatterplot up last to put it first on the child list hScatter = subplot(2,2,scatterLoc); hScatterline = plot(x,y,'o'); axis([xlim ylim]); xlabel(getString(message('stats:scatterhist:xaxisLabel'))); ylabel(getString(message('stats:scatterhist:yaxisLabel'))); % Create invisible text objects for later use txt1 = text(0,0,'42','Visible','off','HandleVisibility','off'); txt2 = text(1,1,'42','Visible','off','HandleVisibility','off'); % Make scatter plot bigger, histograms smaller set(hScatter,'Position',scatterPosn, 'XAxisLocation',scatterXAxisLoc, ... 'YAxisLocation',scatterYAxisLoc, 'tag','scatter'); set(hHistX,'tag','xhist'); set(hHistY,'tag','yhist'); scatterhistPositionCallback(); colormap([.8 .8 1]); % more pleasing histogram fill color % Attach custom datatips if ~isempty(hScatterline) % datatips only if there are data hB = hggetbehavior(hScatterline,'datacursor'); set(hB,'UpdateFcn',@scatterhistDatatipCallback); setappdata(hScatterline,'obsinds',obsinds); end % Add listeners to resize or relimit histograms when the scatterplot changes addlistener(hScatter,{'Position' 'OuterPosition'}, 'PostSet',@scatterhistPositionCallback); addlistener(hScatter,{'XLim' 'YLim'},'PostSet',@scatterhistXYLimCallback); % Leave scatter plot as current axes set(get(hScatter,'parent'),'CurrentAxes',hScatter); if nargout>0 h = [hScatter hHistX hHistY]; end % ----------------------------- function [xctrs,yctrs] = defaultBins(x,y) % By default use the bins given by Scott's rule xctrs = internal.stats.histbins(x); % returns bin ctrs yctrs = internal.stats.histbins(y); % returns bin ctrs if length(xctrs)<2 xctrs = 1; % for constant data, use one bin end if length(yctrs)<2 yctrs = 1; % for constant data, use one bin end end % ----------------------------- function scatterhistPositionCallback(~,~) posn = getrealposition(hScatter,txt1,txt2); if feature('HGUsingMATLABClasses') % drawnow ensures that OuterPosition is updated drawnow('expose'); end oposn = get(hScatter,'OuterPosition'); switch lower(location) case {'sw' 'southwest'} % vertically: margin, histogram, margin/4, scatterplot, margin vmargin = min(max(1 - oposn(2) - oposn(4), 0), oposn(2)); posnHistX = [posn(1) vmargin posn(3) oposn(2)-1.25*vmargin]; % horizontally: margin, histogram, margin/4, scatterplot, margin hmargin = min(max(1 - oposn(1) - oposn(3), 0), oposn(1)); posnHistY = [hmargin posn(2) oposn(1)-1.25*hmargin posn(4)]; case {'ne' 'northeast'} % vertically: margin, scatterplot, margin/4, histogram, margin vmargin = max(oposn(2), 0); posnHistX = [posn(1) oposn(2)+oposn(4)+.25*vmargin posn(3) 1-oposn(2)-oposn(4)-1.25*vmargin]; % horizontally: margin, scatterplot, margin/4, histogram, margin hmargin = max(oposn(1), 0); posnHistY = [oposn(1)+oposn(3)+.25*hmargin posn(2) 1-oposn(1)-oposn(3)-1.25*hmargin posn(4)]; case {'se' 'southeast'} % vertically: margin, histogram, margin/4, scatterplot, margin vmargin = max(1 - oposn(2) - oposn(4), 0); posnHistX = [posn(1) vmargin posn(3) oposn(2)-1.25*vmargin]; % horizontally: margin, scatterplot, margin/4, histogram, margin hmargin = max(oposn(1), 0); posnHistY = [oposn(1)+oposn(3)+.25*hmargin posn(2) 1-oposn(1)-oposn(3)-1.25*hmargin posn(4)]; case {'nw' 'northwest'} % vertically: margin, scatterplot, margin/4, histogram, margin vmargin = max(oposn(2), 0); posnHistX = [posn(1) oposn(2)+oposn(4)+.25*vmargin posn(3) 1-oposn(2)-oposn(4)-1.25*vmargin]; % horizontally: margin, histogram, margin/4, scatterplot, margin hmargin = max(1 - oposn(1) - oposn(3), 0); posnHistY = [hmargin posn(2) oposn(1)-1.25*hmargin posn(4)]; end posnHistX = max(posnHistX,[0 0 .05 .05]); posnHistY = max(posnHistY,[0 0 .05 .05]); set(hHistX,'Position',posnHistX); set(hHistY,'Position',posnHistY); scatterhistXYLimCallback(); end % ----------------------------- function scatterhistXYLimCallback(~,~) set(hHistX,'Xlim',get(hScatter,'XLim')); set(hHistY,'Ylim',get(hScatter,'YLim')); end % ----------------------------- function datatipTxt = scatterhistDatatipCallback(~,evt) target = get(evt,'Target'); ind = get(evt,'DataIndex'); pos = get(evt,'Position'); obsinds = getappdata(target,'obsinds'); obsind = obsinds(ind); % datatipTxt = {... % sprintf('x: %s',num2str(pos(1)))... % sprintf('y: %s',num2str(pos(2)))... % ''... % sprintf('Observation: %s',num2str(obsind))... % }; datatipTxt = {... getString(message('stats:scatterhist:dataTip_x',num2str(pos(1)))), ... getString(message('stats:scatterhist:dataTip_y',num2str(pos(2)))), ... '', ... getString(message('stats:scatterhist:dataTip_Obs',num2str(obsind))), ... }; end end % scatterhist main function % ----------------------------- function p = getrealposition(a,txt1,txt2) p = get(a,'position'); % For non-warped axes (as in "axis square"), recalculate another way if isequal(get(a,'WarpToFill'),'off') pctr = p([1 2]) + 0.5 * p([3 4]); xl = get(a,'xlim'); yl = get(a,'ylim'); % Use text to get coordinate (in points) of southwest corner set(txt1,'units','data'); set(txt1,'position',[xl(1) yl(1)]); set(txt1,'units','pixels'); pSW = get(txt1,'position'); % Same for northeast corner set(txt2,'units','data'); set(txt2,'position',[xl(2) yl(2)]); set(txt2,'units','pixels'); pNE = get(txt2,'position'); % Re-create position % Use min/max/abs in case one or more directions are reversed p = [min(pSW(1),pNE(1)), ... max(pSW(2),pNE(2)), ... abs(pNE(1)-pSW(1)), ... abs(pNE(2)-pSW(2))]; p = hgconvertunits(ancestor(a,'figure'),p, ... 'pixels','normalized',ancestor(a,'figure')); % Position to center p = [pctr(1)-p(3)/2, pctr(2)-p(4)/2, p(3), p(4)]; end end % getrealposition function
github
mbrbic/Multi-view-LRSSC-master
pairwise_LRSSC_1view.m
.m
Multi-view-LRSSC-master/pairwise_LRSSC_1view.m
1,954
utf_8
b921b76a654d20be613a7eae2eba0d29
% % One step of ADMM for one view of pairwise multi-view LRSSC. % % ------------------------------------------------------- % Input: % X: mxn data matrix for one view; columns are samples % K: nxn kernel matrix current view % num_views: number of views % C1: nxn low-rank coefficient matrix for current view % C2: nxn sparse coefficient matrix for current view % C3: nxn consensus coefficient matrix for current view % C_sum: sum of nxn coefficient matrices for all views except current % Lambda1, Lambda2, Lambda3, Lambda4: Lagrange multipliers % lambda: coefficients for low-rank, sparsity and consensus constraint % mu: penalty parameters in augmented Lagrangian % noisy: if true then use noisy variant % % Output: % C1: updated low-rank coefficient matrix for current view % C2: updated sparse coefficient matrix for current view % C3: updated consensus coefficient matrix for current view % Lambda1, Lambda2, Lambda3, Lambda4: updated Lagrange multipliers % function [C1, C2, C3, Lambda1, Lambda2, Lambda3, Lambda4, A] = pairwise_LRSSC_1view(X, K, num_views, C1, C2, C3, C_sum, ... Lambda1, Lambda2, Lambda3, Lambda4, lambda, mu, noisy) n = size(X,2); % updating A if ~noisy inv_A = inv(mu(1)*K+(mu(2)+mu(3)+mu(4))*eye(n)); A = inv_A*(mu(1)*K+mu(2)*(C2-Lambda2/mu(2))+mu(3)*(C1-Lambda3/mu(3))+mu(4)*(C3-Lambda4/mu(4))+X'*Lambda1); else inv_A = inv(K+(mu(2)+mu(3)+mu(4))*eye(n)); A = inv_A*(K+mu(2)*(C2-Lambda2/mu(2))+mu(3)*(C1-Lambda3/mu(3))+mu(4)*(C3-Lambda4/mu(4))); end % updating C1,C2 and C3 C2 = soft_thresh(A+Lambda2/mu(2),lambda(2)/mu(2)); C2 = C2-diag(diag(C2)); C1 = sigma_soft_thresh(A+Lambda3/mu(3),lambda(1)/mu(3)); C3 = 1/(2*lambda(3)*(num_views-1)+mu(4))*(2*lambda(3)*C_sum+mu(4)*A+Lambda4); % updating Lagrange multipliers if ~noisy Lambda1 = Lambda1 + mu(1)*(X-X*A); end Lambda2 = Lambda2+mu(2)*(A-C2); Lambda3 = Lambda3+mu(3)*(A-C1); Lambda4 = Lambda4+mu(4)*(A-C3); end
github
mbrbic/Multi-view-LRSSC-master
construct_kernel.m
.m
Multi-view-LRSSC-master/construct_kernel.m
1,724
utf_8
e3b4a782ce1e92137069d6861d57f8b6
% Kernel construction. % % ------------------------------------------------------- % Input: % X1: nxm data matrix (rows are samples) % X2: nxm data matrix (rows are samples) % opts: Structure value with the following fields: % opts.KernelType: kernel type, choices are: % 'Linear': (x'*y),'Gaussian': (e^{-(|x-y|^2)/2sigma^2}), % 'Polynomial': ((x'*y)^d) % opts.sigma: variance for Gaussian kernel % opts.d: degree for polynomial kernel % % Output: % K: nxn kernel matrix % function K = construct_kernel(X1,X2,options) if (~exist('options','var')) options = []; else if ~isstruct(options) error('parameter error!'); end end if ~isfield(options,'KernelType') options.KernelType = 'linear'; end switch lower(options.KernelType) case 'gaussian' % e^{-(|x-y|^2)/2t^2} if ~isfield(options,'sigma') options.sigma = 1; end if isempty(X2) D = eucl_dist2(X1,[],0); else D = eucl_dist2(X1,X2,0); end K = exp(-D/(2*options.sigma^2)); case 'polynomial' % (x'*y)^d if ~isfield(options,'d') options.d = 2; end if isempty(X2) D = full(X1 * X1'); else D = full(X1 * X2'); end K = D.^options.d; case 'linear' % x'*y if isempty(X2) K = full(X1 * X1'); else K = full(X1 * X2'); end otherwise error('Parameter error: opts is not a structure.'); end if isempty(X2) K = max(K,K'); end
github
mbrbic/Multi-view-LRSSC-master
centroid_LRSSC_1view.m
.m
Multi-view-LRSSC-master/centroid_LRSSC_1view.m
2,128
utf_8
c4371c1c1e5c39edccd8f4c2ec66265c
% % One step of ADMM for one view of centroid multi-view LRSSC. % % ------------------------------------------------------- % Input: % X: mxn data matrix for one view; columns are samples % K: nxn kernel matrix current view % C1: nxn low-rank coefficient matrix for current view % C2: nxn sparse coefficient matrix for current view % C3: nxn consensus coefficient matrix for current view % C_centroid: nxn centroid coefficient matrix % Lambda1, Lambda2, Lambda3, Lambda4: Lagrange multipliers % lambda: coefficients for low-rank, sparsity and consensus constraint % mu: penalty parameters in augmented Lagrangian % noisy: if true then use noisy variant % opts.soft_thr: true for soft thresholding (minimization of L1 % norm), false for hard threhsold (minimization of L0 norm) % % Output: % C1: updated low-rank coefficient matrix for current view % C2: updated sparse coefficient matrix for current view % C3: updated consensus coefficient matrix for current view % Lambda1, Lambda2, Lambda3, Lambda4: updated Lagrange multipliers % function [C1, C2, C3, Lambda1, Lambda2, Lambda3, Lambda4, A] = centroid_LRSSC_1view(X, K, C1, C2, C3, C_centroid, ... Lambda1, Lambda2, Lambda3, Lambda4, lambda, mu, noisy) n = size(X,2); % updating A if ~noisy inv_A = inv(mu(1)*K+(mu(2)+mu(3)+mu(4))*eye(n)); A = inv_A * (mu(1)*K+mu(2)*(C2-Lambda2/mu(2))+mu(3)*(C1-Lambda3/mu(3))+mu(4)*(C3-Lambda4/mu(4))+X'*Lambda1); else inv_A = inv(K+(mu(2)+mu(3)+mu(4))*eye(n)); A = inv_A * (K+mu(2)*(C2-Lambda2/mu(2))+mu(3)*(C1-Lambda3/mu(3))+mu(4)*(C3-Lambda4/mu(4))); end % updating C1,C2 and C3 C2_new = soft_thresh(A+Lambda2/mu(2),lambda(2)/mu(2)); C2_new = C2_new - diag(diag(C2_new)); C1_new = sigma_soft_thresh(A+Lambda3/mu(3),lambda(1)/mu(3)); C3_new = 1/(2*lambda(3)+mu(4))*(2*lambda(3)*C_centroid+mu(4)*A+Lambda4); %update variables C1 = C1_new; C2 = C2_new; C3 = C3_new; % updating Lagrange multipliers if ~noisy Lambda1 = Lambda1 + mu(1) * (X - X*A); end Lambda2 = Lambda2 + mu(2) * (A - C2); Lambda3 = Lambda3 + mu(3) * (A - C1); Lambda4 = Lambda4 + mu(4) * (A - C3); end
github
mbrbic/Multi-view-LRSSC-master
performance_kmeans.m
.m
Multi-view-LRSSC-master/performance_kmeans.m
1,303
utf_8
7dc3ce464eda1546d136de65d958a96b
% Run k-means n times and report means and standard deviations of the % performance measures. % % ------------------------------------------------------- % Input: % X: data matrix (rows are samples) % k: number of clusters % truth: truth cluster indicators % % % Output: % CA: clustering accuracy (mean +stdev) % F: F1 measure (mean +stdev) % P: precision (mean +stdev) % R: recall (mean +stdev) % nmi: normalized mutual information (mean +stdev) % AR: adjusted rand index (mean +stdev) % function [CA F P R nmi AR] = performance_kmeans(X, k, truth) max_iter = 1000; % Maximum number of iterations for KMeans replic = 20; % Number of replications for KMeans if (min(truth)==0) truth = truth+1; end warning('off'); for i=1:replic idx = kmeans(X, k,'EmptyAction','singleton','maxiter',max_iter); CAi(i) = 1-compute_CE(idx, truth); % clustering accuracy [Fi(i),Pi(i),Ri(i)] = compute_f(truth,idx); % F1, precision, recall nmii(i) = compute_nmi(truth,idx); ARi(i) = rand_index(truth,idx); end CA(1) = mean(CAi); CA(2) = std(CAi); F(1) = mean(Fi); F(2) = std(Fi); P(1) = mean(Pi); P(2) = std(Pi); R(1) = mean(Ri); R(2) = std(Ri); nmi(1) = mean(nmii); nmi(2) = std(nmii); AR(1) = mean(ARi); AR(2) = std(ARi); end
github
mbrbic/Multi-view-LRSSC-master
spectral_clustering.m
.m
Multi-view-LRSSC-master/spectral_clustering.m
1,100
utf_8
2c499a670f700c1d69379a7c50b3c34a
%-------------------------------------------------------------------------- % This function takes an adjacency matrix of a graph and computes the % clustering of the nodes using the spectral clustering algorithm of % Ng, Jordan and Weiss. % CMat: NxN adjacency matrix % n: number of groups for clustering % groups: N-dimensional vector containing the memberships of the N points % to the n groups obtained by spectral clustering %-------------------------------------------------------------------------- % Copyright @ Ehsan Elhamifar, 2012 % Modified @ Chong You, 2015 %-------------------------------------------------------------------------- function [CA F P R nmi AR] = spectral_clustering(A,k,truth) N = size(A,1); % Normalized spectral clustering according to Ng & Jordan & Weiss % using Normalized Symmetric Laplacian L = I - D^{-1/2} W D^{-1/2} DN = diag( 1./sqrt(sum(A)+eps) ); LapN = speye(N) - DN * A * DN; [~,~,vN] = svd(LapN); kerN = vN(:,N-k+1:N); normN = sum(kerN .^2, 2) .^.5; kerNS = bsxfun(@rdivide, kerN, normN + eps); [CA F P R nmi AR] = performance_kmeans(kerNS,k,truth);
github
mbrbic/Multi-view-LRSSC-master
eucl_dist2.m
.m
Multi-view-LRSSC-master/eucl_dist2.m
1,701
utf_8
29b40873678068324b4647fcdf25e283
% Euclidean Distance matrix. % % ------------------------------------------------------- % Input: % X1: nxm data matrix (rows are samples) % X2: nxm data matrix (rows are samples) % opts: Structure value with the following fields: % opts.KernelType: kernel type, choices are: % 'Linear': (x'*y),'Gaussian': (e^{-(|x-y|^2)/2sigma^2}), % 'Polynomial': ((x'*y)^d) % opts.sigma: variance for Gaussian kernel % opts.d: degree for polynomial kernel % % Output: % K: nxn kernel matrix % % D = EuDist(fea_a,fea_b) % fea_a: nSample_a * nFeature % fea_b: nSample_b * nFeature % D: nSample_a * nSample_a % or nSample_a * nSample_b function [D] = eucl_dist2(X1,X2,bSqrt) if ~exist('bSqrt','var') bSqrt = 1; end if (~exist('fea_b','var')) | isempty(X2) [nSmp, nFea] = size(X1); aa = sum(X1.*X1,2); ab = X1*X1'; aa = full(aa); ab = full(ab); if bSqrt D = sqrt(repmat(aa, 1, nSmp) + repmat(aa', nSmp, 1) - 2*ab); D = real(D); else D = repmat(aa, 1, nSmp) + repmat(aa', nSmp, 1) - 2*ab; end D = max(D,D'); D = D - diag(diag(D)); D = abs(D); else [nSmp_a, nFea] = size(X1); [nSmp_b, nFea] = size(X2); aa = sum(X1.*X1,2); bb = sum(X2.*X2,2); ab = X1*X2'; aa = full(aa); bb = full(bb); ab = full(ab); if bSqrt D = sqrt(repmat(aa, 1, nSmp_b) + repmat(bb', nSmp_a, 1) - 2*ab); D = real(D); else D = repmat(aa, 1, nSmp_b) + repmat(bb', nSmp_a, 1) - 2*ab; end D = abs(D); end
github
mbrbic/Multi-view-LRSSC-master
centroid_MLRSSC.m
.m
Multi-view-LRSSC-master/centroid_MLRSSC.m
4,065
utf_8
24d6aff263cde7054cea083ea5715a03
% % Solve the multiview centroid based LRSSC % % ------------------------------------------------------- % Input: % X: cell of nxm matrices (rows are samples) % k: number of clusters % truth: truth cluster indicators % opts: Structure value with following fields: % opts.lambda: coefficients for low-rank, sparsity and % consensus constraint, respectively % opts.num_iter: number number of iterations % opts.mu: penalty parameters for the ADMM % opts.max_mu: maximal penalty parameters for the ADMM % opts.rho: step size for adaptively changing mu, if 1 fixed mu % is used % opts.kernel: kernel type (Linear, Gaussian or Polynomial) % opts.sigma: parameter for Gaussian kernel % opts.degree: parameter for polynomial kernel % opts.noisy: true for noisy version of LRSSC false otherwise % opts.err_thr: convergence threshold % % Output: % Af: joint affinity matrix % % version 1.0 - 20/12/2016 % version 2.0 - 30/08/2017 % % Written by Maria Brbic ([email protected]) % function Af = centroid_MLRSSC(X, opts) % setting default parameters num_iter = 100; mu = 100; max_mu = 1e6; rho = 1.5; kernel = 'Linear'; noisy = true; lambda = [0.3 0.3 0.3]; err_thr = 10^-3; if ~exist('opts', 'var') opts = []; else if ~isstruct(opts) error('Parameter error: opts is not a structure.'); end end if isfield(opts, 'lambda'); lambda = opts.lambda; end if isfield(opts, 'num_iter'); num_iter = opts.num_iter; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'kernel'); kernel = opts.kernel; end if isfield(opts, 'sigma'); sigma = opts.sigma; end if isfield(opts, 'degree'); degree = opts.degree; end if isfield(opts, 'noisy'); noisy = opts.noisy; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'err_thr'); err_thr = opts.err_thr; end if strcmpi(kernel,'Gaussian') noisy = true; % can't kernelize otherwise end num_views = size(X,2); n = size(X{1},1); C1 = repmat({zeros(n,n)}, 1, num_views); C2 = repmat({zeros(n,n)}, 1, num_views); C3 = repmat({zeros(n,n)}, 1, num_views); K = repmat({zeros(n,n)}, 1, num_views); A = repmat({zeros(n,n)}, 1, num_views); A_prev = repmat({zeros(n,n)}, 1, num_views); Lambda1 = cell(num_views,1); for v = 1:num_views Lambda1{v} = (zeros(size(X{v},2),n)); end Lambda2 = repmat({zeros(n,n)}, 1, num_views); Lambda3 = repmat({zeros(n,n)}, 1, num_views); Lambda4 = repmat({zeros(n,n)}, 1, num_views); C_centroid = zeros(n,n); mu1 = mu; mu2 = mu; mu3 = mu; mu4 = mu; mu = [mu1 mu2 mu3 mu4]; for v = 1:num_views options.KernelType = kernel; if strcmpi(kernel,'Gaussian') options.sigma = sigma(v); end if strcmpi(kernel,'Polynomial') options.d = degree; end K{v} = construct_kernel(X{v},X{v},options); end iter = 0; converged = false; while iter < num_iter && ~converged iter = iter + 1; for v = 1:num_views A_prev{v} = A{v}; % save previous value [C1{v}, C2{v}, C3{v}, Lambda1{v}, Lambda2{v}, Lambda3{v}, Lambda4{v}, A{v}] = centroid_LRSSC_1view... (X{v}', K{v}, C1{v}, C2{v}, C3{v}, C_centroid, Lambda1{v}, Lambda2{v}, Lambda3{v}, Lambda4{v}, ... lambda, mu, noisy); end % update centroid for v = 1:num_views C_centroid = C_centroid+lambda(3)*C2{v}; end C_centroid = C_centroid/(num_views*lambda(3)); % check convergence converged = true; for v=1 : num_views err1 = max(max(abs(A{v}-C1{v}))); err2 = max(max(abs(A{v}-C2{v}))); err3 = max(max(abs(A{v}-C3{v}))); err4 = max(max(abs(A_prev{v}-A{v}))); if err1>err_thr || err2>err_thr || err3>err_thr || err4>err_thr converged = false; break end end mu = min(rho*mu,max_mu); end C = C_centroid; Af = abs(C)+abs(C'); end
github
mbrbic/Multi-view-LRSSC-master
pairwise_MLRSSC.m
.m
Multi-view-LRSSC-master/pairwise_MLRSSC.m
4,316
utf_8
d5dc7be4b5c1bd869617ec9043ee03a7
% % Solve the multiview pairwise similarities based LRSSC % % ------------------------------------------------------- % Input: % X: cell of nxm matrices (rows are samples) % k: number of clusters % truth: truth cluster indicators % opts: Structure value with the following fields: % opts.lambda: coefficients for low-rank, sparsity and % consensus constraint, respectively % opts.num_iter: number number of iterations % opts.mu: penalty parameters for the ADMM % opts.max_mu: maximal penalty parameters for the ADMM % opts.rho: step size for adaptively changing mu, if 1 fixed mu % is used % opts.kernel: kernel type (Linear, Gaussian or Polynomial) % opts.sigma: parameter for Gaussian kernel % opts.degree: parameter for polynomial kernel % opts.noisy: true for noisy version of LRSSC false otherwise % opts.err_thr: convergence threshold % % Output: % Af: joint affinity matrix % % version 1.0 - 20/12/2016 % version 2.0 - 30/08/2017 % % Written by Maria Brbic ([email protected]) % function Af = pairwise_MLRSSC(X, opts) % setting default parameters num_iter = 300; mu = 100; max_mu = 1e6; rho = 1.5; kernel = 'Linear'; noisy = true; lambda = [0.3 0.3 0.3]; err_thr = 10^-3; if ~exist('opts', 'var') opts = []; else if ~isstruct(opts) error('Parameter error: opts is not a structure.'); end end if isfield(opts, 'lambda'); lambda = opts.lambda; end if isfield(opts, 'num_iter'); num_iter = opts.num_iter; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'kernel'); kernel = opts.kernel; end if isfield(opts, 'sigma'); sigma = opts.sigma; end if isfield(opts, 'degree'); degree = opts.degree; end if isfield(opts, 'noisy'); noisy = opts.noisy; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'err_thr'); err_thr = opts.err_thr; end if strcmpi(kernel,'Gaussian') noisy = true; % can't kernelize otherwise end mu1 = mu; mu2 = mu; mu3 = mu; mu4 = mu; mu = [mu1 mu2 mu3 mu4]; num_views = size(X,2); n = size(X{1},1); C1 = repmat({zeros(n,n)}, 1, num_views); C2 = repmat({zeros(n,n)}, 1, num_views); C3 = repmat({zeros(n,n)}, 1, num_views); K = repmat({zeros(n,n)}, 1, num_views); A = repmat({zeros(n,n)}, 1, num_views); A_prev = repmat({zeros(n,n)}, 1, num_views); Lambda1 = cell(num_views,1); for v = 1:num_views Lambda1{v} = (zeros(size(X{v},2),n)); end Lambda2 = repmat({zeros(n,n)}, 1, num_views); Lambda3 = repmat({zeros(n,n)}, 1, num_views); Lambda4 = repmat({zeros(n,n)}, 1, num_views); for v = 1:num_views options.KernelType = kernel; if strcmpi(kernel,'Gaussian') options.sigma = sigma(v); end if strcmpi(kernel,'Polynomial') options.d = degree; end K{v} = construct_kernel(X{v},X{v},options); end iter = 0; converged = false; while iter < num_iter && ~converged iter = iter + 1; C_sum = repmat({zeros(n,n)}, 1, num_views); for v = 1:num_views for v_tmp = 1:num_views if v_tmp ~= v C_sum{v} = C_sum{v}+C2{v_tmp}; end end end for v = 1:num_views A_prev{v} = A{v}; % save previous value [C1{v}, C2{v}, C3{v}, Lambda1{v}, Lambda2{v}, Lambda3{v}, Lambda4{v}, A{v}] = pairwise_LRSSC_1view... (X{v}', K{v}, num_views, C1{v}, C2{v}, C3{v}, C_sum{v}, Lambda1{v}, Lambda2{v}, Lambda3{v}, Lambda4{v}, ... lambda, mu, noisy); end % check convergence converged = true; for v=1 : num_views err1 = max(max(abs(A{v}-C1{v}))); err2 = max(max(abs(A{v}-C2{v}))); err3 = max(max(abs(A{v}-C3{v}))); err4 = max(max(abs(A_prev{v}-A{v}))); if err1>err_thr || err2>err_thr || err3>err_thr || err4>err_thr converged = false; break end end mu = min(rho*mu,max_mu); end %if converged % fprintf('Converged in iter %d\n', iter); %end C_avg = zeros(n,n); for v = 1:num_views C_avg = C_avg+C2{v}; end C_avg = C_avg/(num_views); C = C_avg; Af = abs(C)+abs(C'); end
github
mbrbic/Multi-view-LRSSC-master
compute_CE.m
.m
Multi-view-LRSSC-master/performance/compute_CE.m
1,955
utf_8
f82c9a2da3e44077d754286307840c28
% Compute the clustering error. % %------------------------------------------------------- % Input: % A: predicted cluster assignments % A0 : N true cluster assignments % truth: truth cluster indicators % % % Output: % CE: clustering error % function CE = compute_CE(A,A0) if size(A,2) == 1 A = A'; end if size(A0,2) == 1 A0 = A0'; end L = max(A); L0 = max(A0); N = numel(A); Aerror = zeros(L,max(L,L0)); for i=1:L for j=1:L0 Aerror(i,j) = nnz(A0(A == i) ~= j); end Aerror(i,L0+1:end) = nnz(A == i); end if max(L,L0) <= 10 % for <=10 labels, compute error for every permutation perm = perms(1:max(L,L0)); perm = perm(:,1:L); ind_set = repmat((0:L-1)*L,size(perm,1),1) + perm; [CE,~] = min(sum(Aerror(ind_set),2)); % Find the best permutation of label indices that minimize the disagreement CE = CE / N; else % for >10 labels, compute approximate error using hill climbing % assumed L=L0 swap = []; for i=2:L swap = [swap; repmat(i,i-1,1) (1:i-1)']; end CE = N; for i=1:10 perm = randperm(L); for j=1:1e5 [m,ind] = min(Aerror(sub2ind(size(Aerror),swap(:,1),perm(swap(:,2))')) ... + Aerror(sub2ind(size(Aerror),swap(:,2),perm(swap(:,1))')) ... - Aerror(sub2ind(size(Aerror),swap(:,1),perm(swap(:,1))')) ... - Aerror(sub2ind(size(Aerror),swap(:,2),perm(swap(:,2))'))); if m >= 0 break; end temp = perm(swap(ind,1)); perm(swap(ind,1)) = perm(swap(ind,2)); perm(swap(ind,2)) = temp; end %perm %sum(Aerror(sub2ind(size(Aerror),1:L,perm))) if sum(Aerror(sub2ind(size(Aerror),1:L,perm))) < CE CE = sum(Aerror(sub2ind(size(Aerror),1:L,perm))); end end CE = CE / N; end end
github
mbrbic/Multi-view-LRSSC-master
compute_nmi.m
.m
Multi-view-LRSSC-master/performance/compute_nmi.m
1,364
utf_8
60db924b3abc1efdd1fb1731c534eece
% Compute normalized mutual information. % function nmi = compute_nmi (T, H) N = length(T); classes = unique(T); clusters = unique(H); num_class = length(classes); num_clust = length(clusters); %%compute number of points in each class for j=1:num_class index_class = (T(:)==classes(j)); D(j) = sum(index_class); end % mutual information mi = 0; A = zeros(num_clust, num_class); avgent = 0; for i=1:num_clust %number of points in cluster 'i' index_clust = (H(:)==clusters(i)); B(i) = sum(index_clust); for j=1:num_class index_class = (T(:)==classes(j)); %%compute number of points in class 'j' that end up in cluster 'i' A(i,j) = sum(index_class.*index_clust); if (A(i,j) ~= 0) miarr(i,j) = A(i,j)/N * log2 (N*A(i,j)/(B(i)*D(j))); %%average entropy calculation avgent = avgent - (B(i)/N) * (A(i,j)/B(i)) * log2 (A(i,j)/B(i)); else miarr(i,j) = 0; end mi = mi + miarr(i,j); end end % class entropy class_ent = 0; for i=1:num_class class_ent = class_ent + D(i)/N * log2(N/D(i)); end % clustering entropy clust_ent = 0; for i=1:num_clust clust_ent = clust_ent + B(i)/N * log2(N/B(i)); end % normalized mutual information nmi = 2*mi / (clust_ent + class_ent);
github
andreafarina/SOLUS-master
linearity_fit.m
.m
SOLUS-master/example/example_200202_series/linearity_fit.m
6,499
utf_8
753b17477de52ef6051dbf5991910d79
%% analyisis %clear direc = { 'ex_bulk10_0.1_incl10_0.05',... 'ex_bulk10_0.1_incl10_0.4',... 'ex_bulk10_0.2_incl10_0.2',... 'ex_bulk10_0.1_incl10_0.1',... 'ex_bulk10_0.1_incl10_0.6',... 'ex_bulk10_0.2_incl10_0.4',... 'ex_bulk10_0.1_incl05_0.1',... 'ex_bulk10_0.1_incl10_0.2',... 'ex_bulk10_0.1_incl15_0.1' }; direc = { 'ex_bulk10_0.1_incl10_0.05',... 'ex_bulk10_0.1_incl10_0.4',... 'ex_bulk10_0.1_incl10_0.1',... 'ex_bulk10_0.1_incl10_0.6',... 'ex_bulk10_0.1_incl10_0.2' }; % direc = {'ex_bulk10_0.1_incl10_0.2_p0.0001',... % 'ex_bulk10_0.1_incl10_0.2_p0.00025',... % 'ex_bulk10_0.1_incl10_0.2_p0.0005',... % 'ex_bulk10_0.1_incl10_0.2_p0.001',... % 'ex_bulk10_0.1_incl10_0.2_p0.0025',... % 'ex_bulk10_0.1_incl10_0.2_p0.005',... % 'ex_bulk10_0.1_incl10_0.2_p0.01',... % 'ex_bulk10_0.1_incl10_0.2_p0.025',... % 'ex_bulk10_0.1_incl10_0.2_p0.05',... % 'ex_bulk10_0.1_incl10_0.2_p0.1'... % 'ex_bulk10_0.1_incl10_0.2_p0.2'}; % % %load Test_Standard_REC.mat iii = 1; i_fig = 1001; for i = 1:numel(direc) %['dtprior/',direc{i},'/Test_Standard_REC.mat'] load( ['./dtprior/',direc{i},'/Test_Standard_REC.mat']) for lambda = 1:8 [bx, by, bz] = ndgrid(REC.grid.x, REC.grid.y, REC.grid.z); if lambda >0 %== 3 abs_real(iii) = REC.opt.hete1.val(lambda); mua_recon = REC.opt.bmua(:,lambda); if numel(size(REC.solver.prior.refimage)) > 3 REC.solver.prior.refimage = REC.solver.prior.refimage(:,:,:,1); end abs_recon(iii) = mean(REC.opt.bmua(abs(bx(:)) <= 1 & abs(by(:)) <= 1 & abs(bz(:)) >= 9 & abs(bz(:)) <= 11, lambda));%mean(mua_recon(REC.solver.prior.refimage(:) > mean(REC.solver.prior.refimage(:)))); %mean(REC.opt.bmua(abs(bx(:)) <= 1 & abs(by(:)) <= 1 & abs(bz(:)) > 6 & abs(bz(:)) < 10, lambda)); %mean(mua_recon > 0.5*mean(mua_recon)); % abs_bulk(iii) = REC.opt.mua0(lambda); sca_real(iii) = REC.opt.hete1.val(lambda+ 8); mus_recon = REC.opt.bmusp(:,lambda); sca_recon(iii) = mean(REC.opt.bmusp(abs(bx(:)) <= 1 & abs(by(:)) <= 1 & abs(bz(:)) >= 9 & abs(bz(:)) <= 11, lambda));%mean(mus_recon > 0.5*mean(mus_recon));% sca_bulk(iii) = REC.opt.musp0(lambda); tau(iii) = REC.solver.tau; iii = iii +1; if lambda == 0 PlotMua = reshape(REC.opt.bmua,[REC.grid.dim REC.radiometry.nL]); PlotMus = reshape(REC.opt.bmusp,[REC.grid.dim REC.radiometry.nL]); PlotMua = PlotMua(:,:,:,lambda); PlotMus = PlotMus(:,:,:,lambda); figure(i_fig);ShowRecResults(REC.grid,PlotMua,... REC.grid.z1,REC.grid.z2,REC.grid.dz,1,'auto',0.00,0.05); pause(1) suptitle(sprintf('Recon Mua,target incl = %g mm-1, bulk = %g mm-1, lambda = %g nm, tau = %g',... round(abs_real(iii-1),4),... round(abs_bulk(iii-1),4),... 830,... 0*tau(iii-1))) pause(1) % figure(i_fig+1000);ShowRecResults(REC.grid,PlotMus,... % REC.grid.z1,REC.grid.z2,REC.grid.dz,1,'auto',0.00,0.05); % suptitle(sprintf('Recon Mus, ,nominal incl = %g , bulk = %g, lambda= %g',sca_real(iii-1), sca_bulk(iii-1), lambda)) % i_fig = i_fig + 1; end end end end delta_abs_real = (abs_real)./abs_bulk; delta_abs_recon = (abs_recon)./abs_bulk; delta_sca_real = (sca_real)./sca_bulk; delta_sca_recon = (sca_recon)./sca_bulk; err_abs = (abs_recon - abs_real)./abs_real; err_sca = (sca_recon - sca_real)./abs_real; figure(2);scatter((delta_abs_real), delta_abs_recon), xlabel('nominal contrast \mu_{a,in}/ \mu_{a,bulk}'), ylabel('Reconstructed contrast \mu_{a,in}^{recon} / \mu_{a,bulk}'), title('ABS: Recontructed vs nominal contrast with DT prior, \tau = 0.05' ) figure(3);scatter(delta_sca_real, delta_sca_recon), xlabel('nominal contrast \mu_{s,in}/ \mu_{s,bulk}'), ylabel('Reconstructed contrast \mu_{s,in}^{recon} / \mu_{s,bulk}'), title('SCA: Recontructed vs nominal contrast with DT prior, \tau = 0.05' ) figure(4);scatter(delta_abs_real, err_abs), xlabel('nominal contrast \mu_{a,in}/ \mu_{a,bulk}'), ylabel('Reconstruction Error (\mu_{a,in}^{recon} - \mu_{a,in}) / \mu_{a,in}'), title('ABS: ERROR vs nominal contrast with DT prior, \tau = 0.05' ) figure(5);scatter(delta_sca_real, err_sca), xlabel('nominal contrast \mu_{s,in}/ \mu_{s,bulk}'), ylabel('Reconstruction Error (\mu_{s,in}^{recon} - \mu_{s,in}) / \mu_{s,in}'), title('SCA: ERROR vs nominal contrast with DT prior, \tau = 0.05' ) figure(6);scatter(abs_real, abs_recon), xlabel('nominal abs \mu_{a,in}'), ylabel('Reconstruction \mu_{a,in}^{recon} '), title('ABS: abs vs nominal abs with DT prior, \tau = 0.05' ) figure(7);semilogx(tau, err_abs, 'r--+',... 'MarkerEdgeColor','r','MarkerFaceColor','r', 'LineWidth',2, 'MarkerSize', 15), xlabel('Regularisation Parameter'), ylabel('Reconstruction Error (\mu_{a,in}^{recon} -\mu_{a,in})/\mu_{a,in} '), title('Absorption Reconstruction Error vs Regularisation Parameter' ) xx = reshape(delta_abs_real,[8,5]); yy = reshape(delta_abs_recon, [8,5]); for i_s = 1:5 a(i_s,:) = rand(1,3); figure(8);plot(xx(:,i_s), yy(:,i_s), '+', 'MarkerSize', 8, 'color', a(i_s,:)), hold on %plot(xx(:,i_s), yy_old(:,i_s), 'o', 'MarkerSize', 12, 'color', a(i_s,:)), hold on end pause(2); grid on xlabel('nominal contrast \mu_{a,in}/ \mu_{a,bulk}'), ylabel('Reconstructed contrast \mu_{a,in}^{recon} / \mu_{a,bulk}'), legend('\mu_{a} = 0.005 mm^{-1}','\mu_{a} = 0.01 mm^{-1}', '\mu_{a} = 0.02 mm^{-1}', '\mu_{a} = 0.04 mm^{-1}', '\mu_{a} = 0.06 mm^{-1}') title('ABS: Recontructed Contrast vs target contrast with DT prior, \tau = 0.01 (+), \mu_{s,bulk} \sim 1 mm^{-1} \mu_{a,bulk} \sim 0.01 mm^{-1}' ) for i_s = 1:5 % a(i_s,:) = rand(1,3); figure(8);%plot(xx(:,i_s), yy(:,i_s), '+', 'MarkerSize', 12, 'color', a(i_s,:)), hold on plot(xx(:,i_s), yy_old(:,i_s), 'o', 'MarkerSize', 8, 'color', a(i_s,:)), hold on, legend off end legend('\mu_{a} = 0.005 mm^{-1}','\mu_{a} = 0.01 mm^{-1}', '\mu_{a} = 0.02 mm^{-1}', '\mu_{a} = 0.04 mm^{-1}', '\mu_{a} = 0.06 mm^{-1}') disp('END') function [a,b,c] = fit_linearity(vec_real, vec_recon) vec_real = vec_real/ 0.01 a = 1; b = 1; c = 1; f = fit(vec_real, vec_recon, 'poly2'); return end
github
andreafarina/SOLUS-master
mutiple_run_script.m
.m
SOLUS-master/example/example_200202_series/mutiple_run_script.m
1,527
utf_8
adeeec982ba14695f0f8cb8644281cf4
%% run series of experiments direc = { 'ex_bulk10_0.1_incl10_0.05',... 'ex_bulk10_0.1_incl10_0.4',... 'ex_bulk10_0.2_incl10_0.2',... 'ex_bulk10_0.1_incl10_0.1',... 'ex_bulk10_0.1_incl10_0.6',... 'ex_bulk10_0.2_incl10_0.4',... 'ex_bulk10_0.1_incl05_0.1',... 'ex_bulk10_0.1_incl10_0.2',... 'ex_bulk10_0.1_incl15_0.1' }; % % for i = 1:numel(direc) % close all % old_pwd = pwd; % run_([old_pwd,'/free/',direc{i}], pwd); % system('rm ./precomputed_jacobians/J*') % cd ../../ % end % % for i = 1:numel(direc) close all old_pwd = pwd; run_([old_pwd,'/cylprior/',direc{i},], pwd); system('rm ./precomputed_jacobians/J*') cd ../../ end for i = 1:numel(direc) close all old_pwd = pwd; run_([old_pwd,'/dtprior/',direc{i}], pwd); system('rm ./precomputed_jacobians/J*') cd ../../ end % % pp = {'0.0001','0.00025','0.0005','0.001','0.0025', '0.005', '0.01', '0.025', '0.05', '0.1', '0.2'}; % % for i = 1:numel(pp) % % close all % % old_pwd = pwd; % % run_([old_pwd,'/cylprior_priortest/','ex_bulk10_0.1_incl10_0.2_p',pp{i}], pwd); % % system('rm ./precomputed_jacobians/J*') % % cd ../../ % % end % % % % for i = 1:numel(pp) % % close all % % old_pwd = pwd; % % run_([old_pwd,'/dtprior_priortest/','ex_bulk10_0.1_incl10_0.2_p',pp{i}], pwd); % % system('rm ./precomputed_jacobians/J*') % % cd ../../ % % end function run_(cd_direc, varargin) cd(cd_direc); run_DOT; end
github
andreafarina/SOLUS-master
createExp.m
.m
SOLUS-master/data/202002/createExp.m
24,556
utf_8
a4e4fc8456687115a5988c858451ae9d
function EXP = createExp(DAT_STR, type_phantom) % % EXP = CreateMatlabExp(DAT_STR, type_phantom) % Takes as input the path to a *.dat file and return a MAT variable % suitable for operations in the SOLUS software % DATA_STR is the pathname of a *.dat file % type_phantom is a str defining from which phantom the experimental data should be created: % -'veallard' % -'lardtend' % -'silicon' % EXP is a Matlab variable with experimental data from the phantom old_pwd = pwd; TOMOFOLDER = from_dat2mat(DAT_STR, type_phantom); folder_data = DAT_STR; cd([TOMOFOLDER]) %addpath((['./Tomo structs/' folder_data])); lambda = [635, 670, 830, 915, 940, 980, 1030, 1065]; %lambda used %lambda = [620 670 740 800 910 1020 1050 1090]; for iw = 1:numel(lambda) EXP_file = strcat('Tomo_wave_',num2str(lambda(iw))); load(['Tomo_structs/',EXP_file,'.mat']) % ========================================================================= %% Path % ========================================================================= %EXP.path.data_folder = '/media/psf/Home/Documents/Politecnico/Work/Data/Compressive Imaging/'; %EXP.path.data_folder = '/Users/andreafarina/Documents/Politecnico/Work/Data/Compressive Imaging/'; output_folder = './'; output_suffix = '';%'_sum100'; % ========================================================================= %% Measurement info % ========================================================================= % Measurement folder and name EXP.path.day = '202002'; EXP.path.data_folder = [old_pwd,filesep, 'Tomo_structs'];%['../../results/201710/dynamic phantom']; EXP.path.file_name = T.path.file_name; % Time resolved windows EXP.spc.gain = T.gain; EXP.spc.n_chan = T.Nchannel; EXP.spc.factor = 50e3/T.Nchannel/T.gain; %EXP.time.roi = [500,1500]; EXP.time.roi = T.roi; % just for info EXP.bkg.ch_start = T.bkg.ch_start; EXP.bkg.ch_end = T.bkg.ch_stop; % % time windows % a = 1:2001; % b = a + 0; % twin1 = [a', b']; % twin = twin1; % EXP.time.twin = twin; % irf file EXP.path.irf_file = 'IRF.mat'; % irf shift EXP.irf.t0 = T.irf.t0; %40;%-15;%-30; % ps % sum repetitions % ========================================================================= %% Pre-process SPC and CCD % ========================================================================= cd(old_pwd) [homo,hete,t,EXP.irf] = PreProcessing_SPC(EXP); % ========================================================================= %% Determine size of data % ========================================================================= spc_size = size(hete); ref_size = size(homo); % ========================================================================= %% Save forward data % ========================================================================= % EXP.data.spc = int32(reshape(hete,size(hete,1),[])); % EXP.data.ref = int32(reshape(homo,size(homo,1),[])); EXP.data.spc = (reshape(hete,size(hete,1),[])); EXP.data.ref = (reshape(homo,size(homo,1),[])); EXP.time.axis = t; EXP.grid.dmask = T.dmask; EXP.grid.xs = T.xs; EXP.grid.ys = T.ys; EXP.grid.zs = T.zs; EXP.grid.SourcePos = T.sourcepos; EXP.grid.DetPos = T.detpos; EXP.optp.homo.abs = T.opt.homo.abs; EXP.optp.homo.sca = T.opt.homo.sca; EXP.optp.hete.abs = T.opt.hete.abs; EXP.optp.hete.sca = T.opt.hete.sca; EXP.lambda = T.lambda; mkdir(fullfile(pwd,'EXP_structs',folder_data)) str_file = [fullfile(pwd,'EXP_structs',folder_data),filesep,... 'EXP_',EXP_file,output_suffix]; save(str_file,'EXP'); %%assemble full exp struct EXP_full.irf.area(iw) = EXP.irf.area; EXP_full.irf.baric(iw) = EXP.irf.baric; EXP_full.irf.data(:,iw) = EXP.irf.data; EXP_full.irf.peak(iw) = EXP.irf.peak; EXP_full.irf.variance(iw) = EXP.irf.variance; EXP_full.data.ref(:,(1:size(EXP.data.ref,2))+(iw-1)*size(EXP.data.ref,2)) = EXP.data.ref; EXP_full.data.spc(:,(1:size(EXP.data.spc,2))+(iw-1)*size(EXP.data.spc,2)) = EXP.data.spc; EXP_full.path = EXP.path; EXP_full.path.file_name = 'Tomo'; EXP_full.spc = EXP.spc;EXP_full.time = EXP.time; EXP_full.bkg = EXP.bkg;EXP_full.grid = EXP.grid; EXP_full.optp = EXP.optp; EXP_full.lambda = EXP.lambda; end clear EXP EXP = EXP_full; str_file = [fullfile(pwd,'EXP_structs',folder_data),filesep,... 'EXP_Tomo']; save(str_file,'EXP'); return end % str_file = [fullfile(pwd,'EXP structs',folder_data),filesep,... % 'EXP_','Tomo',output_suffix]; % save(str_file,'EXP'); function TomoFolder = from_dat2mat(STR, type_str) % % convert *.dat files into *.mat structures and returns the path to the % folder where the structures are saved %% Create a file.mat with the data used for the tomographic reconstruction % version @ 11-June-2018 %% Content: % heterogeneous => data(n_time,n_sd,n_lambda); % homogeneous => ref(n_time,n_sd,n_lambda); % irf => irf(n_time,n_lambda); % stand. dev. => sd(n_time,n_sd,n_lambda); % Source Position => SOURCE_POS; % Det. Position => DETECTOR_POS; % Logic Mask => dmask(n_detector, n_source); %========================================================================= %% TCSPC board parameters gain = 6; Nchannel = 4096; factor = 50000/gain/Nchannel; phot_goal = 400000; %Total photons per curve (goal) repetitions = 5; %# of repetitions for each lambda roi = [500 3500]; %% Background removal background = 1; %background = 1 => remove the backgorund %background = 0 => no removal %========================================================================= %% Repetitions sum sum_rep = 1; %sum_rep = 1 => the repetitions are summed %sum_rep = 0 => takes just the first repetition %========================================================================= %% Read .DAT files % Measurement file filepath = STR; %addpath(genpath(['./' filepath])); switch lower(type_str) %% LARD+HAM case 'lardham' xs = [19.5 6.5 -6.5 -19.5]; ys = [10 -10]; zs = 0; N_homo = [473:1:500]; % #homog. measurements N_hete = [501:1:528]; % #heterog. measurements irf_file_name = 'SOLs0100'; lambda = [635, 670, 830, 915, 940, 980, 1030, 1065]; %lambda used T.opt.homo.abs = [0.0038079316 0.0013426612 0.0013876201 0.0100602733 0.0075543996 0.0039425139 0.007613757 0.004933052]; T.opt.homo.sca = [1.228420919 1.189904619 0.913511025 0.8030371548 0.7696766762 0.7560782619 0.7022870595 0.6751796929]; T.opt.hete.abs = [0.037321025 0.021343425 0.0104115095 0.01574798 0.023087425 0.05156646 0.02941183 0.019642555]; T.opt.hete.sca = [0.3711594 0.31473145 0.2147255 0.20802585 0.22279435 0.2970374 0.2203812 0.18975735]; %% VEAL+LARD case 'veallard' xs = [19.5 6.5 -6.5 -19.5]; ys = [10 -10]; zs = 0; N_homo = [672:1:699]; % #homog. measurements N_hete = [700:1:727]; % #heterog. measurements irf_file_name = 'SOLs0111'; lambda = [635, 670, 830, 915, 940, 980, 1030, 1065]; %lambda used T.opt.homo.abs = [0.02791161 0.0177973093 0.009091243 0.01586907 0.0260947261 0.053704805 0.0297806604 0.01985166]; T.opt.homo.sca = [0.9385278214 0.8507553357 0.5872533214 0.5547145536 0.5709639036 0.6376319821 0.5172092786 0.4790727179]; T.opt.hete.abs = [0.0036857775 0.001488738 0.001309731 0.010038185 0.0073729725 0.0050007045 0.0080228255 0.0052807725]; T.opt.hete.sca = [1.761344 1.639484 1.4247535 1.349348 1.2949265 1.200157 1.215836 1.2253315]; %% LARD+TEND case 'lardtend' xs = [19.5 6.5 -6.5 -19.5]; ys = [10 -10]; zs = 0; N_homo = [614:1:641]; % #homog. measurements N_hete = [642:1:669]; % #heterog. measurements irf_file_name = 'SOLs0107'; lambda = [635, 670, 830, 915, 940, 980, 1030, 1065]; %lambda used T.opt.homo.abs = [0.0038005485 0.0034049469 0.0015822979 0.0104953881 0.0075209223 0.0052855228 0.0090089653 0.0054133905]; T.opt.homo.sca = [1.7920386071 1.6857158 1.4810270357 1.4032054643 1.3324607857 1.2932485 1.2526574786 1.24276525]; T.opt.hete.abs = [0.005657467 0.00265227 0.003164864 0.008215303 0.01391677 0.02775662 0.01905252 0.01384971]; T.opt.hete.sca = [2.777692 2.854745 2.679655 2.560578 2.494992 2.154414 2.323298 2.578156]; %% SIL_10_01_1cm case 'sil_10_01_1cm' xs = [20.0000 6.6667 -6.6667 -20.0000]; ys = [14 -14]; zs = 0; lambda = [620 670 740 800 910 1020 1050 1090]; N_homo = [786:1:813]; % #homog. measurements N_hete = [842:1:869]; % #heterog. measurements irf_file_name = 'SOLs0116'; T.opt.homo.abs = [0.00436839500000000 0.00399510520000000 0.00530931960000000 0.00449303100000000 0.0124849820000000 0.00865493720000000 0.00426235080000000 0.00704804460000000]; T.opt.homo.sca = [1.12950240000000 0.996046560000000 0.920408340000000 0.858343020000000 0.656752800000000 0.537798400000000 0.524484660000000 0.472743960000000]; T.opt.hete.abs = [0.0084826386 0.0079976316 0.0096794268 0.0086512542 0.016530138 0.012258804 0.0078621298 0.010433566]; T.opt.hete.sca = [1.1072414 0.98465536 0.9394932 0.86275388 0.66062366 0.53074266 0.51240594 0.46274634]; %% SIL_10_01_6cm case 'sil_10_01_6cm' xs = [20.0000 6.6667 -6.6667 -20.0000]; ys = [14 -14]; zs = 0; lambda = [620 670 740 800 910 1020 1050 1090]; N_homo = [786:1:813]; % #homog. measurements N_hete = [898:1:925]; % #heterog. measurements irf_file_name = 'SOLs0116'; T.opt.homo.abs = [0.00436839500000000 0.00399510520000000 0.00530931960000000 0.00449303100000000 0.0124849820000000 0.00865493720000000 0.00426235080000000 0.00704804460000000]; T.opt.homo.sca = [1.12950240000000 0.996046560000000 0.920408340000000 0.858343020000000 0.656752800000000 0.537798400000000 0.524484660000000 0.472743960000000]; T.opt.hete.abs = [0.0084826386 0.0079976316 0.0096794268 0.0086512542 0.016530138 0.012258804 0.0078621298 0.010433566]; T.opt.hete.sca = [1.1072414 0.98465536 0.9394932 0.86275388 0.66062366 0.53074266 0.51240594 0.46274634]; %% SIL_10_02_1cm case 'sil_10_02_1cm' xs = [20.0000 6.6667 -6.6667 -20.0000]; ys = [14 -14]; zs = 0; lambda = [620 670 740 800 910 1020 1050 1090]; N_homo = [786:1:813]; % #homog. measurements N_hete = [814:1:841]; % #heterog. measurements irf_file_name = 'SOLs0116'; T.opt.homo.abs = [0.00436839500000000 0.00399510520000000 0.00530931960000000 0.00449303100000000 0.0124849820000000 0.00865493720000000 0.00426235080000000 0.00704804460000000]; T.opt.homo.sca = [1.12950240000000 0.996046560000000 0.920408340000000 0.858343020000000 0.656752800000000 0.537798400000000 0.524484660000000 0.472743960000000]; T.opt.hete.abs = [0.01683116 0.01719449 0.019627084 0.017524408 0.024481872 0.019767674 0.015424918 0.017779734]; T.opt.hete.sca = [0.98843248 0.9300621 0.91997866 0.7990178 0.5994491 0.47483964 0.4577962 0.4145961]; %% SIL_10_02_6cm case 'sil_10_02_6cm' xs = [20.0000 6.6667 -6.6667 -20.0000]; ys = [14 -14]; zs = 0; lambda = [620 670 740 800 910 1020 1050 1090]; N_homo = [786:1:813]; % #homog. measurements N_hete = [870:1:897]; % #heterog. measurements irf_file_name = 'SOLs0116'; T.opt.homo.abs = [0.00436839500000000 0.00399510520000000 0.00530931960000000 0.00449303100000000 0.0124849820000000 0.00865493720000000 0.00426235080000000 0.00704804460000000]; T.opt.homo.sca = [1.12950240000000 0.996046560000000 0.920408340000000 0.858343020000000 0.656752800000000 0.537798400000000 0.524484660000000 0.472743960000000]; T.opt.hete.abs = [0.01683116 0.01719449 0.019627084 0.017524408 0.024481872 0.019767674 0.015424918 0.017779734]; T.opt.hete.sca = [0.98843248 0.9300621 0.91997866 0.7990178 0.5994491 0.47483964 0.4577962 0.4145961]; %% case silicon 200202 case 'silicon_200202' xs = [20.0000 6.6667 -6.6667 -20.0000]; ys = [14 -14]; zs = 0; lambda = [635, 670, 830, 915, 940, 980, 1030, 1065]; %:1:244]; % #homog. measurements %:1:244]; % #heterog. measurements irf_file_name = 'SOLs0211'; str_phantom_homo = '10_0.2'; str_phantom_hete = '10_0.4'; switch lower(str_phantom_homo) case '10_0.1' T.opt.homo.abs = [0.09118862 0.08252885 0.07457543 0.114975675 0.07321214 0.07269354 0.09152519 0.076381]; T.opt.homo.sca = [14.267035 13.06632 9.491283 7.8722685 7.707295 7.060895 6.352237 5.989931]; N_homo = [246];% #homog. measurements switch lower(str_phantom_hete) case '10_0.05' T.opt.hete.abs = [0.05246881 0.04837734 0.03696393 0.080474885 0.03518626 0.03308078 0.05274401 0.038200645]; T.opt.hete.sca = [11.46904 10.55009 7.656952 6.150009 6.002163 5.590301 4.857868 4.654679]; N_hete = [247];% #heterog. measurements case '10_0.1' T.opt.hete.abs = [0.094249395 0.09108484 0.07822272 0.12349727 0.07722901 0.07274856 0.09558736 0.081897605]; T.opt.hete.sca = [11.27842 10.56916 7.576539 6.138904 5.994108 5.46071 4.877412 4.694373]; N_hete = [248];% #heterog. measurements case '10_0.2' T.opt.hete.abs = [0.18834215 0.1808696 0.1594672 0.2140688 0.1618171 0.1609721 0.1816612 0.1681408]; T.opt.hete.sca = [11.196185 10.30879 7.183976 6.0505265 5.763012 5.358386 4.799074 4.5417635]; N_hete = [249];% #heterog. measurements case '10_0.4' T.opt.hete.abs = [0.3244506 0.3090453 0.2850104 0.3521497 0.2937037 0.2913416 0.3152952 0.30309455]; T.opt.hete.sca = [9.540982 8.508501 5.992858 5.245241 4.992857 4.637014 4.149682 3.973167]; N_hete = [250];% #heterog. measurements case '10_0.6' T.opt.hete.abs = [0.46561525 0.4456669 0.422469 0.5012814 0.4393349 0.4392696 0.4642975 0.4596188]; T.opt.hete.sca = [9.5278705 8.628135 6.08301 5.301621 5.010855 4.710412 4.163082 4.0690635]; N_hete = [251];% #heterog. measurements case '15_0.1' T.opt.hete.abs = [0.080407055 0.07623264 0.06779367 0.110158655 0.06512177 0.06030613 0.07829765 0.066305675]; T.opt.hete.sca = [16.99245 15.68388 11.63303 9.3891785 9.218989 8.425847 7.417703 7.211785]; N_hete = [252];% #heterog. measurements case '05_0.1' T.opt.hete.abs = [0.087325025 0.08533506 0.07396581 0.1459342 0.08532022 0.08495646 0.1181968 0.10573535]; T.opt.hete.sca = [4.766733 4.387157 3.001634 2.639426 2.415703 2.165157 1.945762 1.762059]; N_hete = [253];% #heterog. measurements end case '10_0.2' T.opt.homo.abs = [0.176269 0.1642548 0.1523256 0.1921913 0.148854 0.1484415 0.1653411 0.1511315]; T.opt.homo.sca = [13.239025 12.28287 8.910008 7.3108825 7.121039 6.537811 5.882884 5.576854]; N_homo = [254];% #homog. measurements switch lower(str_phantom_hete) case '10_0.2' T.opt.hete.abs = [0.18834215 0.1808696 0.1594672 0.2140688 0.1618171 0.1609721 0.1816612 0.1681408]; T.opt.hete.sca = [11.196185 10.30879 7.183976 6.0505265 5.763012 5.358386 4.799074 4.5417635]; N_hete = [255];% #heterog. measurements case '10_0.4' T.opt.hete.abs = [0.3244506 0.3090453 0.2850104 0.3521497 0.2937037 0.2913416 0.3152952 0.30309455]; T.opt.hete.sca = [9.540982 8.508501 5.992858 5.245241 4.992857 4.637014 4.149682 3.973167]; N_hete = [256];% #heterog. measurements end end end meas_homo = []; meas_hete = []; B = []; C = []; TomoFolder = [ filepath filesep 'Tomo_structs']; old_pwd = pwd; cd(filepath) % Homog. measurements for i = 1:length(N_homo) B = DatRead3(strcat('SOLm1',num2str(N_homo(i))),4096,5,8); if sum_rep == 0 meas_homo(:,i,:) = B(:,1,:); %takes just the first repetion. elseif sum_rep == 1 meas_homo(:,i,:) = squeeze(B); %sums the 5 repetitions else meas_homo(:,i,:) = squeeze(sum(B,2)); %sums the 5 repetitions end end % Heterog. measurements for i = 1:length(N_hete) C = DatRead3(strcat('SOLm1',num2str(N_hete(i))),4096,5,8); if sum_rep == 0 meas_hete(:,i,:) = C(:,1,:); %takes just the first repetion. elseif sum_rep == 1 meas_hete(:,i,:) = squeeze(C); %sums the 5 repetitions else meas_hete(:,i,:) = squeeze(sum(C,2)); %sums the 5 repetitions end end meas_homo = permute(meas_homo,[3 2 1]); %rearrange of the dimensions meas_hete = permute(meas_hete,[3 2 1]); %Irf file irf = DatRead3(irf_file_name,4096,5,8); if sum_rep == 0 irf = squeeze(permute(irf(:,1,:),[3 2 1])); %rearrange of the dimensions elseif sum_rep == 1 irf = squeeze(permute(irf(:,:,:),[3 2 1])); else irf = squeeze(permute(sum(irf,2),[3 2 1])); end % for i = 1: size(irf,2) % semilogy(irf(:,i)); % hold on, grid on % end %========================================================================= %% Subtraction of the background if background == 0 else back_start = 450; %first channel for the background back_stop = 500; %last channel for the background back_ref = mean(meas_homo(back_start:back_stop,:,:)); back_data = mean(meas_hete(back_start:back_stop,:,:)); back_irf = mean(irf(back_start:back_stop,:)); meas_homo = meas_homo - back_ref; meas_homo(meas_homo < 0) = 0; meas_hete = meas_hete - back_data; meas_hete(meas_hete < 0) = 0; irf = irf - back_irf; irf(irf < 0) = 0; end % for i = 1: size(data,2) % semilogy(ref(:,i,1)); % hold on, grid on % end %========================================================================= %% Calculation of the standard deviation sd = sqrt(meas_hete); %========================================================================= %% Create the S-D pos. % SOURCE_POS = [xs1 ys1 zs1; xs2 ys2 zs2; ... ; xs8 ys8 zs8]; % SOURCE_POS = [xd1 yd1 zd1; xd2 yd2 zd2; ... ; xd8 yd8 zd8]; SOURCE_POS = [1.95 1 0; 0.65 1 0; -0.65 1 0; -1.95 1 0;... 1.95 -1 0; 0.65 -1 0; -0.65 -1 0; -1.95 -1 0].*10; DET_POS = SOURCE_POS; %========================================================================= %% Create the logic mask % dmask = [s1-d1 s2-d1 ... sn-dn; s1-d2 s2-d2 ... sn-d2 ...] dmask = ones(size(SOURCE_POS,1),size(DET_POS,1)); dmask = dmask - diag(diag(ones(size(SOURCE_POS,1),size(DET_POS,1)))); % we didn't perform rho = 0 and 1->2 , 2->1 %% rearrange measurements meas_homo0 = zeros(Nchannel,sum(dmask(:)) ,size(irf,2)); meas_hete0 = zeros(Nchannel,sum(dmask(:)),size(irf,2)); for lam= 1:size(irf,2) meas_homo0(:,:,lam) = squeeze(meas_homo(:, 1, lam:size(irf,2):end )); meas_hete0(:,:,lam) = squeeze(meas_hete(:, 1, lam:size(irf,2):end)); end count = 1; % srdet = cat(2,[0,1:7]',... % [8,0,9:14]',... % [15:16, 0, 17:21]',... % [22:24,0,25:28]',... % [29:32,0,33:35]',... % [36:40,0,41:42]',... % [43:48,0,49]',... % [50:56,0]'); % srdetmeas = cat(2,[21,8:14]',... % [27:28,15:20]',... % [33:35,22:26]',... % [39:42,29:32]',... % [45:49,36:38]',... % [51:56,43:44]',... % [1:7,50]'); srdetmeas = cat(2,[0,1:7]',... [14,0,8:13]',... [20:21,0,15:19]',... [26:28,0,22:25]',... [32:35,0,29:31]',... [38:42,0,36:37]',... [44:49,0,43]',... [50:56,0]'); %srdet = srdetmeas([2,3,4,5,1,8,7,6],[2,3,4,5,1,8,7,6]); srdet = srdetmeas([5, 4, 3, 2, 6, 7, 8, 1],[5, 4, 3, 2, 6, 7, 8, 1])'; %srdet = srdetmeas([5,1,2,3,4,8,7,6],[5,1,2,3,4,8,7,6]); % srdetmeas = cat(2,[8:14]',... % [21,15:20]',... % [27:28,22:26]',... % [33:35,29:32]',... % [39:42,36:38]',... % [45:49,43:44]',... % [51:56,50]',... % [1:7]')'; meas_homo00 = zeros(size(meas_homo0)); meas_hete00 = meas_homo00; for lam= 1:size(irf,2) dc = 0; for d = 1:64 if srdetmeas(d)>0 %& srdetmeas(d)>0 dc = dc +1; disp(srdet(d)) meas_homo00(:,(dc),lam) = meas_homo0(:,srdet(d), lam); meas_hete00(:,(dc),lam) = meas_hete0(:,srdet(d), lam); end end end meas_homo = meas_homo00; meas_hete = meas_hete00; clearvars meas_homo0 meas_hete0 CalcolaContrasto %imagesc(dmask) %========================================================================= T.dmask = dmask; T.sourcepos = SOURCE_POS; T.detpos = DET_POS; T.xs = xs; T.ys = ys; T.zs = zs; T.gain = gain; T.Nchannel = Nchannel; T.factor = factor; T.lambda = lambda; T.roi = roi; T.bkg.ch_start = back_start; T.bkg.ch_stop = back_stop; cd(old_pwd) mkdir(TomoFolder); cd(TomoFolder); T.path.data_folder = TomoFolder; for iw=1:numel(T.lambda) T.irf.data = irf(:,iw); T.irf.t0 = 0; T.meas_hete = zeros(T.Nchannel,numel(T.dmask)); T.meas_homo = zeros(T.Nchannel,numel(T.dmask)); idm = 1; for im = 1:numel(T.dmask(:)) if T.dmask(im)==1 T.meas_hete(:,im)=meas_hete(:,idm,iw); T.meas_homo(:,im)=meas_homo(:,idm,iw); idm = idm +1; end end T.meas_hete = reshape(T.meas_hete,T.Nchannel,8,8); T.meas_homo = reshape(T.meas_homo,T.Nchannel,8,8); T.path.file_name = ['Tomo_wave_' num2str(T.lambda(iw))]; save(['Tomo_wave_' num2str(T.lambda(iw))],'T'); end cd(old_pwd) end %cd(fileparts(mfilename('fullpath')))
github
andreafarina/SOLUS-master
DatRead3.m
.m
SOLUS-master/data/202002/DatRead3.m
22,460
utf_8
7a8e8f566dc60d850973521c257867aa
function [ Data, varargout ] = DatRead3(FileName,varargin) %DatRead3('FileName') %Can be as input a selection of the following parameters %DatRead3(...,'loop4',numloop4,'loop5',numloop5,'datatype','uint32','compilesub',true/false,'forcereading',true/false) %[Data,Header,EasyReadableHead,SubHeaders,EasyReadableSubHead,UnSqueezedHeader]=DatRead3(...) NumArgOut = nargout-1; NumArgin = nargin-1; ForceReading = false; isCompileSubHeader = false; HeadLen=764; datatype = 'ushort'; nBoard = 1; nDet=1; loop5=1;loop4=1; ismandatoryarg = zeros(8,1); m_loop5 = 1;m_loop4 = 2;m_loop3 = 3;m_loop2 = 4;m_loop1 = 5; m_nsource = 6;m_ndet = 7;m_nboard = 8;m_nbin = 9; isdatatypeargin=0; FilePath = [FileName '.DAT']; if isempty(fileparts(FileName)) FilePath = fullfile(pwd,[FileName,'.DAT']); end fid=fopen(FilePath,'rb'); if fid<0, errordlg('File not found'); Data = []; return; end for iN = 1:NumArgin if strcmpi(varargin{iN},'loop5') loop5 = varargin{iN+1}; ismandatoryarg(m_loop5)=1; end if strcmpi(varargin{iN},'loop4') loop4 = varargin{iN+1}; ismandatoryarg(m_loop4)=1; end if strcmpi(varargin{iN},'loop3') CompiledHeader.LoopNum(3) = varargin{iN+1}; ismandatoryarg(m_loop3)=1; end if strcmpi(varargin{iN},'loop2') CompiledHeader.LoopNum(2) = varargin{iN+1}; ismandatoryarg(m_loop2)=1; end if strcmpi(varargin{iN},'loop1') CompiledHeader.LoopNum(1) = varargin{iN+1}; ismandatoryarg(m_loop1)=1; end if strcmpi(varargin{iN},'datatype') datatype = varargin{iN+1}; end if strcmpi(varargin{iN},'compilesub') isCompileSubHeader = varargin{iN+1}; end if strcmpi(varargin{iN},'forcereading') if(ischar(varargin{iN+1})||isstring(varargin{iN+1})) varargin{iN+1}=string2boolean(varargin{iN+1}); end ForceReading = logical(varargin{iN+1}); end if strcmpi(varargin{iN},'nSource') nDet = varargin{iN+1}; ismandatoryarg(m_nsource)=1; end if strcmpi(varargin{iN},'nDet') nDet = varargin{iN+1}; ismandatoryarg(m_ndet)=1; end if strcmpi(varargin{iN},'nBoard') nBoard = varargin{iN+1}; ismandatoryarg(m_nboard)=1; end if strcmpi(varargin{iN},'nBin') nBin = varargin{iN+1}; ismandatoryarg(m_nbin)=1; end end Head=fread(fid,HeadLen,'uint8'); if (numel(categories(categorical(Head)))==1||sum(Head)==0)&&sum(ismandatoryarg)~=numel(ismandatoryarg) errordlg('Please insert all loop values and nDet, nSource, nBoard, nBin'); Data = []; return; end CompiledHeader = FillHeader(Head); SubLen=CompiledHeader.SizeSubHeader; if SubLen == 0 SkipSub = true; if(~all(ismandatory([m_nboard m_ndet m_nsource]))) errordlg('Please insert nSource, nDet, nBoard'); Data = []; end return; else SkipSub = false; end nBin = CompiledHeader.McaChannNum; datasize = CompiledHeader.SizeData; CompiledHeader.LoopNum(4) = loop4; CompiledHeader.LoopNum(5) = loop5; CompiledHeader.LoopFirst(4) = 0; CompiledHeader.LoopFirst(5) = 0; CompiledHeader.LoopLast(4) = 0; CompiledHeader.LoopLast(5) = 0; CompiledHeader.LoopDelta(4) = 1; CompiledHeader.LoopDelta(5) = 1; CompiledHeader.LoopHome(4) = 0; CompiledHeader.LoopHome(5) = 0; CompiledHeader.LoopNum(1:3)=flip(CompiledHeader.LoopNum(1:3)); CompiledHeader.LoopFirst(1:3)=flip(CompiledHeader.LoopFirst(1:3)); CompiledHeader.LoopLast(1:3)=flip(CompiledHeader.LoopLast(1:3)); CompiledHeader.LoopDelta(1:3)=flip(CompiledHeader.LoopDelta(1:3)); CompiledHeader.LoopHome(1:3)=flip(CompiledHeader.LoopHome(1:3)); for iN = 1:NumArgin if strcmpi(varargin{iN},'loop5') loop5 = varargin{iN+1}; ismandatoryarg(m_loop5)=1; end if strcmpi(varargin{iN},'loop4') loop4 = varargin{iN+1}; ismandatoryarg(m_loop4)=1; end if strcmpi(varargin{iN},'loop3') CompiledHeader.LoopNum(3) = varargin{iN+1}; ismandatoryarg(m_loop3)=1; end if strcmpi(varargin{iN},'loop2') CompiledHeader.LoopNum(2) = varargin{iN+1}; ismandatoryarg(m_loop2)=1; end if strcmpi(varargin{iN},'loop1') CompiledHeader.LoopNum(1) = varargin{iN+1}; ismandatoryarg(m_loop1)=1; end if strcmpi(varargin{iN},'datatype') datatype = varargin{iN+1}; switch datatype case 'ushort' datasize = 2; case 'uint32' datasize = 4; case 'double' datasize = 8; end isdatatypeargin=1; end if strcmpi(varargin{iN},'compilesub') isCompileSubHeader = varargin{iN+1}; end if strcmpi(varargin{iN},'forcereading') if(ischar(varargin{iN+1})||isstring(varargin{iN+1})) varargin{iN+1}=string2boolean(varargin{iN+1}); end ForceReading = logical(varargin{iN+1}); end if strcmpi(varargin{iN},'nSource') nDet = varargin{iN+1}; ismandatoryarg(m_nsource)=1; end if strcmpi(varargin{iN},'nDet') nDet = varargin{iN+1}; ismandatoryarg(m_ndet)=1; end if strcmpi(varargin{iN},'nBoard') nBoard = varargin{iN+1}; ismandatoryarg(m_nboard)=1; end if strcmpi(varargin{iN},'nBin') nBin = varargin{iN+1}; ismandatoryarg(m_nbin)=1; end end if(~isdatatypeargin) datatry = {'ushort','uint32','double'}; else datatry={datatype}; end if ~all(ismandatoryarg([m_nboard m_ndet m_nsource])) && SkipSub==0 for itry = 1:numel(datatry) frewind(fid); fread(fid,HeadLen,'uint8'); out = false; BuffParms = []; Parms = []; while(out==false) SubRaw=fread(fid,SubLen,'uint8'); if isempty(SubRaw), break; end CompSub = FillSub(SubRaw); fread(fid,nBin,datatry{itry}); ActParms = [CompSub.Source CompSub.Det CompSub.Board]; if(isequal(BuffParms,ActParms)) out = true; else if isempty(BuffParms) BuffParms = ActParms; end if isempty(Parms) Parms = ActParms; else Parms(end+1,:) = ActParms; end end end nSource = numel(categories(categorical(Parms(:,1)))); nDet = numel(categories(categorical(Parms(:,2)))); nBoard = numel(categories(categorical(Parms(:,3)))); NumLoop=CompiledHeader.LoopNum; info=dir(FilePath); datatype = datatry{itry}; if info.bytes == (HeadLen + prod(NumLoop)*(nBoard*nDet*nSource)*(SubLen+nBin*2)) datasize = 2; break; end if info.bytes == (HeadLen + prod(NumLoop)*(nBoard*nDet*nSource)*(SubLen+nBin*4)) datasize = 4; break; end if info.bytes == (HeadLen + prod(NumLoop)*(nBoard*nDet*nSource)*(SubLen+nBin*8)) datasize = 8; break; end if(ForceReading==true&&isdatatypeargin) break; end if (ForceReading==false)&&itry==numel(datatry) errordlg({'Can''t handle sizemismatch. Insert more argin' 'Or use (...''forcereading'',''true'') argin'}); Data = []; fclose(fid); return; end if (ForceReading==true)&&itry==numel(datatry) fh = figure('NumberTitle','off','Name','Choose type','Toolbar','none','menubar','none','HandleVisibility','off','Units','normalized','Position',[0.5 0.5 0.1 0.3]); movegui(fh,'center'); uph = uipanel(fh,'Title','Choose type','units','normalized','position',[0 0 1 1]); bg = uibuttongroup(uph,'Visible','on','Position',[0 0 1 1]); uicontrol(bg,'style','radiobutton','String','ushort','units','normalized','position',[0 0 1 0.5]); uicontrol(bg,'style','radiobutton','String','uint32','units','normalized','position',[0 1/3 1 0.5]); uicontrol(bg,'style','radiobutton','String','double','units','normalized','position',[0 2/3 1 0.5]); uicontrol(uph,'style','pushbutton','String','Ok','units','normalized','position',[0.5 0 0.5 0.1],'Callback',@AssignDataType); waitfor(fh,'Tag'); close(fh); fclose(fid); fid=fopen(FilePath,'rb'); fread(fid,HeadLen,'uint8'); out = false; BuffParms = []; Parms = []; while(out==false) SubRaw=fread(fid,SubLen,'uint8'); if isempty(SubRaw), break; end CompSub = FillSub(SubRaw); fread(fid,nBin,datatype); ActParms = [CompSub.Source CompSub.Det CompSub.Board]; if(isequal(BuffParms,ActParms)) out = true; else if isempty(BuffParms) BuffParms = ActParms; end if isempty(Parms) Parms = ActParms; else Parms(end+1,:) = ActParms; end end end nSource = numel(categories(categorical(Parms(:,1)))); nDet = numel(categories(categorical(Parms(:,2)))); nBoard = numel(categories(categorical(Parms(:,3)))); break; end end end fclose(fid); NumLoop=CompiledHeader.LoopNum; CompiledHeader.NumBoard = nBoard; CompiledHeader.NumDet = nDet; CompiledHeader.NumSource = nSource; fid=fopen(FilePath,'rb'); Head=fread(fid,HeadLen,'uint8'); A=zeros(NumLoop(5),NumLoop(4),NumLoop(3),NumLoop(2),NumLoop(1),nBoard,nDet,nSource,nBin); Sub=zeros(NumLoop(5),NumLoop(4),NumLoop(3),NumLoop(2),NumLoop(1),nBoard,nDet,nSource,SubLen); %CompiledSub = zeros(NumLoop(5),NumLoop(4),NumLoop(3),NumLoop(2),NumLoop(1)); isbreakcond = false; try for il5= 1:NumLoop(5) for il4= 1:NumLoop(4) for il3= 1:NumLoop(3) for il2=1:NumLoop(2) for il1=1:NumLoop(1) for iB = 1:nBoard for iD = 1: nDet for iS = 1:nSource if SkipSub==0 BuffSub = fread(fid,SubLen,'uint8'); if ~isempty(BuffSub)&&numel(BuffSub)==SubLen Sub(il5,il4,il3,il2,il1,iB,iD,iS,:)=BuffSub; else warning('backtrace','off') warning('Reading interrupted at:'); warning(strcat('Loop5: ',num2str(il5),'/',num2str(NumLoop(5)))); warning(strcat('Loop4: ',num2str(il4),'/',num2str(NumLoop(4)))); warning(strcat('Loop3: ',num2str(il3),'/',num2str(NumLoop(3)))); warning(strcat('Loop2: ',num2str(il2),'/',num2str(NumLoop(2)))); warning(strcat('Loop1: ',num2str(il1),'/',num2str(NumLoop(1)))); warning(strcat('NumBoard: ',num2str(iB),'/',num2str(nBoard))); warning(strcat('NumDet: ',num2str(iD),'/',num2str(nDet))); warning(strcat('NumSource: ',num2str(iS),'/',num2str(nSource))); warning('Output data will have the dimension specified in TRS settings (Header)'); warning('backtrace','on') isbreakcond = true; break; end if (isCompileSubHeader) CompiledSub(il5,il4,il3,il2,il1,iB,iD,iS) = FillSub(squeeze(Sub(il5,il4,il3,il2,il1,iB,iD,iS,:))); end else BuffSub = 0; end TrashData = fread(fid,nBin,datatype); if ~isempty(TrashData)&&numel(TrashData)==nBin Sub(il5,il4,il3,il2,il1,iB,iD,iS,:)=BuffSub; else warning('backtrace','off') warning('Reading interrupted at:'); warning(strcat('Loop5: ',num2str(il5),'/',num2str(NumLoop(5)))); warning(strcat('Loop4: ',num2str(il4),'/',num2str(NumLoop(4)))); warning(strcat('Loop3: ',num2str(il3),'/',num2str(NumLoop(3)))); warning(strcat('Loop2: ',num2str(il2),'/',num2str(NumLoop(2)))); warning(strcat('Loop1: ',num2str(il1),'/',num2str(NumLoop(1)))); warning(strcat('NumBoard: ',num2str(iB),'/',num2str(nBoard))); warning(strcat('NumDet: ',num2str(iD),'/',num2str(nDet))); warning(strcat('NumSource: ',num2str(iS),'/',num2str(nSource))); warning('Output data will have the dimension specified in TRS settings (Header)'); warning('backtrace','on') isbreakcond = true; break; end A(il5,il4,il3,il2,il1,iB,iD,iS,:)=TrashData; end if isbreakcond, break; end end if isbreakcond, break; end end if isbreakcond, break; end end if isbreakcond, break; end end if isbreakcond, break; end end if isbreakcond, break; end end if isbreakcond, break; end end fclose(fid); catch ME fclose(fid); %ME = MException('FileReading:GeneralError',{'Error reading the file:',ME.message, ' Encountered error at Loop1: ', num2str(il1), ' Loop2: ', num2str(il2), ' Loop3: ', num2str(il3), 'Loop4: ', num2str(il4),' Loop5: ', num2str(il5)}); throw(ME); return end Data = squeeze(A); switch NumArgOut case 1 varargout{1}= Head; case 2 varargout{1} = Head; varargout{2} = CompiledHeader; case 3 varargout{1} = Head; varargout{2} = CompiledHeader; varargout{3} = squeeze(Sub); case 4 varargout{1} = Head; varargout{2} = CompiledHeader; varargout{3} = squeeze(Sub); if isCompileSubHeader == false varargout{4} = []; else varargout{4} = squeeze(CompiledSub); end case 5 varargout{1} = Head; varargout{2} = CompiledHeader; varargout{3} = squeeze(Sub); if isCompileSubHeader == false varargout{4} = []; else varargout{4} = squeeze(CompiledSub); end varargout{5} = Sub; case 6 varargout{1} = Head; varargout{2} = CompiledHeader; varargout{3} = squeeze(Sub); if isCompileSubHeader == false varargout{4} = []; else varargout{4} = squeeze(CompiledSub); end varargout{5} = Sub; varargout{6} = datasize; case 7 varargout{1} = Head; varargout{2} = CompiledHeader; varargout{3} = squeeze(Sub); if isCompileSubHeader == false varargout{4} = []; else varargout{4} = squeeze(CompiledSub); end varargout{5} = Sub; varargout{6} = datasize; varargout{7} = datatype; end end function FS = FillSub(Sub) FieldNames = {'Geom','Source','Fiber','Det','Board','Coord','Pad','Xf','Yf','Zf','Rf','Xs','Ys','Zs','Rs','Rho','TimeNom','TimeEff'... 'n','Loop','Acq','Page','RoiNum','RoiFirst','RoiLast','RoiLambda','RoiPower'}; C = 1; CT = 1; L = 4; LT = 2; D = 8; DT = 3; S = 2; ST = 4; Unit = 1; %byte FieldSize = [C,C,C,C,C,C,C,D,D,D,D,D,D,D,D,D,D,D,D,3*L,L,L,C,4*S,4*S,4*D,4*D]./Unit; FieldType = [CT,CT,CT,CT,CT,CT,CT,DT,DT,DT,DT,DT,DT,DT,DT,DT,DT,DT,DT,LT,LT,LT,CT,ST,ST,DT,DT]; iS = 1; iF = 1; while iS<=length(Sub) iStart = iS; iStop = iS + FieldSize(iF); iStop = iStop-1; iS = iStop+1; RawData = Sub(iStart:iStop); switch FieldType(iF) case CT Data = RawData; if strcmp(FieldNames{iF},'Geom') if Data == 0 Data = 'REFL'; else Data = 'TRASM'; end end if strcmp(FieldNames{iF},'Coord') if Data == 0 Data = 'CART'; else Data = 'POLAR'; end end case LT Data = cast(typecast(uint8(RawData),'int32'),'double'); case DT Data = typecast(uint8(RawData),'double'); case ST Data = cast(typecast(uint8(RawData),'int16'),'double'); end FS.(FieldNames{iF}) = Data; iF = iF +1; end end function FH = FillHeader(Head) FieldNames = {'Ver','SubHeader','SubHeaderVer','SizeHeader','SizeSubHeader','SizeData','Kind','Appl'... ,'Oma','Date','Time','LoopHome','LoopFirst','LoopLast','LoopDelta','LoopNum','McaChannNum','PageNum'... 'FrameNum','RamNum','McaTime','McaFactor','MeasNorm','LabelName','LabelContent','Constn','ConstRho'... 'ConstThick','MammHeader','MammIdxFirst','MammIdxLast','MammIdxTop','MammRateMid','MammRateHigh'}; C = 1; CT = 1; L = 4; LT = 2; D = 8; DT = 3; S = 2; ST = 4; Unit = 1; %byte FieldSize = [2*S,L,L,L,L,L,L,L,L,11*C,9*C,3*L,3*L,3*L,3*L,3*L,L,L,L,L,D,D,L,192*C,352*C,D,D,D,L,2*L,2*L,2*L,2*L,2*L]./Unit; FieldType = [ST,LT,LT,LT,LT,LT,LT,LT,LT,CT,CT,LT,LT,LT,LT,LT,LT,LT,LT,LT,DT,DT,LT,CT,CT,DT,DT,DT,LT,LT,LT,LT,LT,LT]; iS = 1; iF = 1; while iS<=length(Head) iStart = iS; iStop = iS + FieldSize(iF); iStop = iStop-1; iS = iStop+1; RawData = Head(iStart:iStop); %isCHAR = false; switch FieldType(iF) case CT if strcmp(FieldNames{iF},'LabelName') Data = reshape(RawData,[12,16])'; Data = char(Data); Data = string(Data); %isCHAR = true; end if strcmp(FieldNames{iF},'LabelContent') Data = reshape(RawData,[22,16])'; Data = char(Data); Data = string(Data); %isCHAR = true; end if strcmp(FieldNames{iF},'Date') Data = char(RawData'); %isCHAR = true; end if strcmp(FieldNames{iF},'Time') Data = char(RawData'); %isCHAR = true; end %isCHAR = false; case LT Data = cast(typecast(uint8(RawData),'int32'),'double'); if strcmp(FieldNames{iF},'Kind') switch Data case 0 Data = 'Measure'; case 1 Data = 'System'; case 2 Data = 'Simul'; end end if strcmp(FieldNames{iF},'Appl') switch Data case 0 Data = 'Diff'; case 1 Data = 'Mamm'; case 2 Data = 'Oxym'; case 3 Data = 'Fluo'; case 4 Data = 'Spec'; end end if strcmp(FieldNames{iF},'SubHeader') switch Data case 0 Data = false; case 1 Data = true; end end if strcmp(FieldNames{iF},'Oma') switch Data case 0 Data = false; case 1 Data = true; end end if strcmp(FieldNames{iF},'MammHeader') switch Data case 0 Data = false; case 1 Data = true; end end case DT Data = typecast(uint8(RawData),'double'); case ST if strcmp(FieldNames{iF},'Ver') Data = cast(typecast(uint8(RawData(1:2)),'int16'),'double'); Data = [Data cast(typecast(uint8(RawData(3:4)),'int16'),'double')]; else Data = cast(typecast(uint8(RawData),'int16'),'double'); end end FH.(FieldNames{iF}) = Data; iF = iF +1; end end function [output]=string2boolean(string) if strcmp(string,'false') output = false; else output = true; end end function AssignDataType(src,~) ph = src.Parent; rbh = findobj(ph,'style','radiobutton'); assignin('caller','datatype',rbh(logical([rbh.Value])).String); fh = ancestor(src,'figure'); fh.Tag = '1'; end
github
andreafarina/SOLUS-master
pdftops.m
.m
SOLUS-master/src/util/export_fig/pdftops.m
3,687
utf_8
43c139e49fce63cb78060895bd13137a
function varargout = pdftops(cmd) %PDFTOPS Calls a local pdftops executable with the input command % % Example: % [status result] = pdftops(cmd) % % Attempts to locate a pdftops executable, finally asking the user to % specify the directory pdftops was installed into. The resulting path is % stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have pdftops (from the Xpdf package) % installed on your system. You can download this from: % http://www.foolabs.com/xpdf % % IN: % cmd - Command string to be passed into pdftops. % % OUT: % status - 0 iff command ran without problem. % result - Output from pdftops. % Copyright: Oliver Woodford, 2009-2010 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on % Mac OS. % Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path % under linux. % 23/01/2014 - Add full path to pdftops.txt in warning. % 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation % Call pdftops [varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd)); end function path_ = xpdf_path % Return a valid path % Start with the currently set path path_ = user_string('pdftops'); % Check the path works if check_xpdf_path(path_) return end % Check whether the binary is on the path if ispc bin = 'pdftops.exe'; else bin = 'pdftops'; end if check_store_xpdf_path(bin) path_ = bin; return end % Search the obvious places if ispc path_ = 'C:\Program Files\xpdf\pdftops.exe'; else path_ = '/usr/local/bin/pdftops'; end if check_store_xpdf_path(path_) return end % Ask the user to enter the path while 1 errMsg = 'Pdftops not found. Please locate the program, or install xpdf-tools from '; url = 'http://foolabs.com/xpdf'; fprintf(2, '%s\n', [errMsg '<a href="matlab:web(''-browser'',''' url ''');">' url '</a>']); errMsg = [errMsg url]; %#ok<AGROW> if strncmp(computer,'MAC',3) % Is a Mac % Give separate warning as the MacOS uigetdir dialogue box doesn't have a title uiwait(warndlg(errMsg)) end base = uigetdir('/', errMsg); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; %#ok<AGROW> bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) path_ = [base bin_dir{a} bin]; if exist(path_, 'file') == 2 break; end end if check_store_xpdf_path(path_) return end end error('pdftops executable not found.'); end function good = check_store_xpdf_path(path_) % Check the path is valid good = check_xpdf_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('pdftops', path_) warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt')); return end end function good = check_xpdf_path(path_) % Check the path is valid [good, message] = system(sprintf('"%s" -h', path_)); %#ok<ASGLU> % system returns good = 1 even when the command runs % Look for something distinct in the help text good = ~isempty(strfind(message, 'PostScript')); end
github
andreafarina/SOLUS-master
crop_borders.m
.m
SOLUS-master/src/util/export_fig/crop_borders.m
3,791
utf_8
2c8fc83f142f1d5b28b99080556c791e
function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding) %CROP_BORDERS Crop the borders of an image or stack of images % % [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding]) % %IN: % A - HxWxCxN stack of images. % bcol - Cx1 background colour vector. % padding - scalar indicating how much padding to have in relation to % the cropped-image-size (0<=padding<=1). Default: 0 % %OUT: % B - JxKxCxN cropped stack of images. % vA - coordinates in A that contain the cropped image % vB - coordinates in B where the cropped version of A is placed % bb_rel - relative bounding box (used for eps-cropping) % 06/03/15: Improved image cropping thanks to Oscar Hartogensis % 08/06/15: Fixed issue #76: case of transparent figure bgcolor if nargin < 3 padding = 0; end [h, w, c, n] = size(A); if isempty(bcol) % case of transparent bgcolor bcol = A(ceil(end/2),1,:,1); end if isscalar(bcol) bcol = bcol(ones(c, 1)); end % Crop margin from left bail = false; for l = 1:w for a = 1:c if ~all(col(A(:,l,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop margin from right bcol = A(ceil(end/2),w,:,1); bail = false; for r = w:-1:l for a = 1:c if ~all(col(A(:,r,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop margin from top bcol = A(1,ceil(end/2),:,1); bail = false; for t = 1:h for a = 1:c if ~all(col(A(t,:,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop margin from bottom bcol = A(h,ceil(end/2),:,1); bail = false; for b = h:-1:t for a = 1:c if ~all(col(A(b,:,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end % Crop the background, leaving one boundary pixel to avoid bleeding on resize %v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)]; %A = A(v(1):v(2),v(3):v(4),:,:); if padding == 0 % no padding padding = 1; elseif abs(padding) < 1 % pad value is a relative fraction of image size padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING else % pad value is in units of 1/72" points padding = round(padding); % fix cases of non-integer pad value end if padding > 0 % extra padding % Create an empty image, containing the background color, that has the % cropped image size plus the padded border B = repmat(bcol,(b-t)+1+padding*2,(r-l)+1+padding*2); % vA - coordinates in A that contain the cropped image vA = [t b l r]; % vB - coordinates in B where the cropped version of A will be placed vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding]; % Place the original image in the empty image B(vB(1):vB(2), vB(3):vB(4), :) = A(vA(1):vA(2), vA(3):vA(4), :); A = B; else % extra cropping vA = [t-padding b+padding l-padding r+padding]; A = A(vA(1):vA(2), vA(3):vA(4), :); vB = [NaN NaN NaN NaN]; end % For EPS cropping, determine the relative BoundingBox - bb_rel bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h]; end function A = col(A) A = A(:); end
github
andreafarina/SOLUS-master
isolate_axes.m
.m
SOLUS-master/src/util/export_fig/isolate_axes.m
4,851
utf_8
611d9727e84ad6ba76dcb3543434d0ce
function fh = isolate_axes(ah, vis) %ISOLATE_AXES Isolate the specified axes in a figure on their own % % Examples: % fh = isolate_axes(ah) % fh = isolate_axes(ah, vis) % % This function will create a new figure containing the axes/uipanels % specified, and also their associated legends and colorbars. The objects % specified must all be in the same figure, but they will generally only be % a subset of the objects in the figure. % % IN: % ah - An array of axes and uipanel handles, which must come from the % same figure. % vis - A boolean indicating whether the new figure should be visible. % Default: false. % % OUT: % fh - The handle of the created figure. % Copyright (C) Oliver Woodford 2011-2013 % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs % 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio % for pointing out that the function is also used in export_fig.m % 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it % 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!) % 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting % 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro % on FEX page as a comment on 24-Apr-2014); standardized indentation & help section % 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2 % Make sure we have an array of handles if ~all(ishandle(ah)) error('ah must be an array of handles'); end % Check that the handles are all for axes or uipanels, and are all in the same figure fh = ancestor(ah(1), 'figure'); nAx = numel(ah); for a = 1:nAx if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'}) error('All handles must be axes or uipanel handles.'); end if ~isequal(ancestor(ah(a), 'figure'), fh) error('Axes must all come from the same figure.'); end end % Tag the objects so we can find them in the copy old_tag = get(ah, 'Tag'); if nAx == 1 old_tag = {old_tag}; end set(ah, 'Tag', 'ObjectToCopy'); % Create a new figure exactly the same as the old one fh = copyfig(fh); %copyobj(fh, 0); if nargin < 2 || ~vis set(fh, 'Visible', 'off'); end % Reset the object tags for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Find the objects to save ah = findall(fh, 'Tag', 'ObjectToCopy'); if numel(ah) ~= nAx close(fh); error('Incorrect number of objects found.'); end % Set the axes tags to what they should be for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Keep any legends and colorbars which overlap the subplots % Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we % don't test for the type, only the tag (hopefully nobody but Matlab uses them!) lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar'); nLeg = numel(lh); if nLeg > 0 set([ah(:); lh(:)], 'Units', 'normalized'); try ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property catch ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition end if nAx > 1 ax_pos = cell2mat(ax_pos(:)); end ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2); try leg_pos = get(lh, 'OuterPosition'); catch leg_pos = get(lh, 'Position'); % No OuterPosition in HG2, only in HG1 end if nLeg > 1; leg_pos = cell2mat(leg_pos); end leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2); ax_pos = shiftdim(ax_pos, -1); % Overlap test M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ... bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ... bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ... bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2)); ah = [ah; lh(any(M, 2))]; end % Get all the objects in the figure axs = findall(fh); % Delete everything except for the input objects and associated items delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)]))); end function ah = allchildren(ah) ah = findall(ah); if iscell(ah) ah = cell2mat(ah); end ah = ah(:); end function ph = allancestors(ah) ph = []; for a = 1:numel(ah) h = get(ah(a), 'parent'); while h ~= 0 ph = [ph; h]; h = get(h, 'parent'); end end end
github
andreafarina/SOLUS-master
im2gif.m
.m
SOLUS-master/src/util/export_fig/im2gif.m
6,234
utf_8
8ee74d7d94e524410788276aa41dd5f1
%IM2GIF Convert a multiframe image to an animated GIF file % % Examples: % im2gif infile % im2gif infile outfile % im2gif(A, outfile) % im2gif(..., '-nocrop') % im2gif(..., '-nodither') % im2gif(..., '-ncolors', n) % im2gif(..., '-loops', n) % im2gif(..., '-delay', n) % % This function converts a multiframe image to an animated GIF. % % To create an animation from a series of figures, export to a multiframe % TIFF file using export_fig, then convert to a GIF, as follows: % % for a = 2 .^ (3:6) % peaks(a); % export_fig test.tif -nocrop -append % end % im2gif('test.tif', '-delay', 0.5); % %IN: % infile - string containing the name of the input image. % outfile - string containing the name of the output image (must have the % .gif extension). Default: infile, with .gif extension. % A - HxWxCxN array of input images, stacked along fourth dimension, to % be converted to gif. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -nodither - option indicating that dithering is not to be used when % converting the image. % -ncolors - option pair, the value of which indicates the maximum number % of colors the GIF can have. This can also be a quantization % tolerance, between 0 and 1. Default/maximum: 256. % -loops - option pair, the value of which gives the number of times the % animation is to be looped. Default: 65535. % -delay - option pair, the value of which gives the time, in seconds, % between frames. Default: 1/15. % Copyright (C) Oliver Woodford 2011 function im2gif(A, varargin) % Parse the input arguments [A, options] = parse_args(A, varargin{:}); if options.crop ~= 0 % Crop A = crop_borders(A, A(ceil(end/2),1,:,1)); end % Convert to indexed image [h, w, c, n] = size(A); A = reshape(permute(A, [1 2 4 3]), h, w*n, c); map = unique(reshape(A, h*w*n, c), 'rows'); if size(map, 1) > 256 dither_str = {'dither', 'nodither'}; dither_str = dither_str{1+(options.dither==0)}; if options.ncolors <= 1 [B, map] = rgb2ind(A, options.ncolors, dither_str); if size(map, 1) > 256 [B, map] = rgb2ind(A, 256, dither_str); end else [B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str); end else if max(map(:)) > 1 map = double(map) / 255; A = double(A) / 255; end B = rgb2ind(im2double(A), map); end B = reshape(B, h, w, 1, n); % Bug fix to rgb2ind map(B(1)+1,:) = im2double(A(1,1,:)); % Save as a gif imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay); end %% Parse the input arguments function [A, options] = parse_args(A, varargin) % Set the defaults options = struct('outfile', '', ... 'dither', true, ... 'crop', true, ... 'ncolors', 256, ... 'loops', 65535, ... 'delay', 1/15); % Go through the arguments a = 0; n = numel(varargin); while a < n a = a + 1; if ischar(varargin{a}) && ~isempty(varargin{a}) if varargin{a}(1) == '-' opt = lower(varargin{a}(2:end)); switch opt case 'nocrop' options.crop = false; case 'nodither' options.dither = false; otherwise if ~isfield(options, opt) error('Option %s not recognized', varargin{a}); end a = a + 1; if ischar(varargin{a}) && ~ischar(options.(opt)) options.(opt) = str2double(varargin{a}); else options.(opt) = varargin{a}; end end else options.outfile = varargin{a}; end end end if isempty(options.outfile) if ~ischar(A) error('No output filename given.'); end % Generate the output filename from the input filename [path, outfile] = fileparts(A); options.outfile = fullfile(path, [outfile '.gif']); end if ischar(A) % Read in the image A = imread_rgb(A); end end %% Read image to uint8 rgb array function [A, alpha] = imread_rgb(name) % Get file info info = imfinfo(name); % Special case formats switch lower(info(1).Format) case 'gif' [A, map] = imread(name, 'frames', 'all'); if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 A = permute(A, [1 2 5 4 3]); end case {'tif', 'tiff'} A = cell(numel(info), 1); for a = 1:numel(A) [A{a}, map] = imread(name, 'Index', a, 'Info', info); if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 end if size(A{a}, 3) == 4 % TIFF in CMYK colourspace - convert to RGB if isfloat(A{a}) A{a} = A{a} * 255; else A{a} = single(A{a}); end A{a} = 255 - A{a}; A{a}(:,:,4) = A{a}(:,:,4) / 255; A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4])); end end A = cat(4, A{:}); otherwise [A, map, alpha] = imread(name); A = A(:,:,:,1); % Keep only first frame of multi-frame files if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 elseif size(A, 3) == 4 % Assume 4th channel is an alpha matte alpha = A(:,:,4); A = A(:,:,1:3); end end end
github
andreafarina/SOLUS-master
read_write_entire_textfile.m
.m
SOLUS-master/src/util/export_fig/read_write_entire_textfile.m
961
utf_8
775aa1f538c76516c7fb406a4f129320
%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory % % Read or write an entire text file to/from memory, without leaving the % file open if an error occurs. % % Reading: % fstrm = read_write_entire_textfile(fname) % Writing: % read_write_entire_textfile(fname, fstrm) % %IN: % fname - Pathname of text file to be read in. % fstrm - String to be written to the file, including carriage returns. % %OUT: % fstrm - String read from the file. If an fstrm input is given the % output is the same as that input. function fstrm = read_write_entire_textfile(fname, fstrm) modes = {'rt', 'wt'}; writing = nargin > 1; fh = fopen(fname, modes{1+writing}); if fh == -1 error('Unable to open file %s.', fname); end try if writing fwrite(fh, fstrm, 'char*1'); else fstrm = fread(fh, '*char')'; end catch ex fclose(fh); rethrow(ex); end fclose(fh); end
github
andreafarina/SOLUS-master
pdf2eps.m
.m
SOLUS-master/src/util/export_fig/pdf2eps.m
1,522
utf_8
4c8f0603619234278ed413670d24bdb6
%PDF2EPS Convert a pdf file to eps format using pdftops % % Examples: % pdf2eps source dest % % This function converts a pdf file to eps format. % % This function requires that you have pdftops, from the Xpdf suite of % functions, installed on your system. This can be downloaded from: % http://www.foolabs.com/xpdf % %IN: % source - filename of the source pdf file to convert. The filename is % assumed to already have the extension ".pdf". % dest - filename of the destination eps file. The filename is assumed to % already have the extension ".eps". % Copyright (C) Oliver Woodford 2009-2010 % Thanks to Aldebaro Klautau for reporting a bug when saving to % non-existant directories. function pdf2eps(source, dest) % Construct the options string for pdftops options = ['-q -paper match -eps -level2 "' source '" "' dest '"']; % Convert to eps using pdftops [status, message] = pdftops(options); % Check for error if status % Report error if isempty(message) error('Unable to generate eps. Check destination directory is writable.'); else error(message); end end % Fix the DSC error created by pdftops fid = fopen(dest, 'r+'); if fid == -1 % Cannot open the file return end fgetl(fid); % Get the first line str = fgetl(fid); % Get the second line if strcmp(str(1:min(13, end)), '% Produced by') fseek(fid, -numel(str)-1, 'cof'); fwrite(fid, '%'); % Turn ' ' into '%' end fclose(fid); end
github
andreafarina/SOLUS-master
print2array.m
.m
SOLUS-master/src/util/export_fig/print2array.m
9,613
utf_8
e398a6296734121e6e1983a45298549a
function [A, bcol] = print2array(fig, res, renderer, gs_options) %PRINT2ARRAY Exports a figure to an image array % % Examples: % A = print2array % A = print2array(figure_handle) % A = print2array(figure_handle, resolution) % A = print2array(figure_handle, resolution, renderer) % A = print2array(figure_handle, resolution, renderer, gs_options) % [A bcol] = print2array(...) % % This function outputs a bitmap image of the given figure, at the desired % resolution. % % If renderer is '-painters' then ghostcript needs to be installed. This % can be downloaded from: http://www.ghostscript.com % % IN: % figure_handle - The handle of the figure to be exported. Default: gcf. % resolution - Resolution of the output, as a factor of screen % resolution. Default: 1. % renderer - string containing the renderer paramater to be passed to % print. Default: '-opengl'. % gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If % multiple options are needed, enclose in call array: {'-a','-b'} % % OUT: % A - MxNx3 uint8 image of the figure. % bcol - 1x3 uint8 vector of the background color % Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015- %{ % 05/09/11: Set EraseModes to normal when using opengl or zbuffer % renderers. Thanks to Pawel Kocieniewski for reporting the issue. % 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it. % 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size % and erasemode settings. Makes it a bit slower, but more reliable. % Thanks to Phil Trinh and Meelis Lootus for reporting the issues. % 09/12/11: Pass font path to ghostscript. % 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to % Ken Campbell for reporting it. % 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it. % 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for % reporting the issue. % 26/02/15: If temp dir is not writable, use the current folder for temp % EPS/TIF files (Javier Paredes) % 27/02/15: Display suggested workarounds to internal print() error (issue #16) % 28/02/15: Enable users to specify optional ghostscript options (issue #36) % 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation % 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func) % 07/07/15: Fixed issue #83: use numeric handles in HG1 %} % Generate default input arguments, if needed if nargin < 2 res = 1; if nargin < 1 fig = gcf; end end % Warn if output is large old_mode = get(fig, 'Units'); set(fig, 'Units', 'pixels'); px = get(fig, 'Position'); set(fig, 'Units', old_mode); npx = prod(px(3:4)*res)/1e6; if npx > 30 % 30M pixels or larger! warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx); end % Retrieve the background colour bcol = get(fig, 'Color'); % Set the resolution parameter res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))]; % Generate temporary file name tmp_nam = [tempname '.tif']; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(tmp_nam,'w'); fwrite(fid,1); fclose(fid); delete(tmp_nam); % cleanup isTempDirOk = true; catch % Temp dir is not writable, so use the current folder [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU> fpath = pwd; tmp_nam = fullfile(fpath,[fname fext]); isTempDirOk = false; end % Enable users to specify optional ghostscript options (issue #36) if nargin > 3 && ~isempty(gs_options) if iscell(gs_options) gs_options = sprintf(' %s',gs_options{:}); elseif ~ischar(gs_options) error('gs_options input argument must be a string or cell-array of strings'); else gs_options = [' ' gs_options]; end else gs_options = ''; end if nargin > 2 && strcmp(renderer, '-painters') % Print to eps file if isTempDirOk tmp_eps = [tempname '.eps']; else tmp_eps = fullfile(fpath,[fname '.eps']); end print2eps(tmp_eps, fig, 0, renderer, '-loose'); try % Initialize the command to export to tiff using ghostscript cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc']; % Set the font path fp = font_path(); if ~isempty(fp) cmd_str = [cmd_str ' -sFONTPATH="' fp '"']; end % Add the filenames cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options]; % Execute the ghostscript command ghostscript(cmd_str); catch me % Delete the intermediate file delete(tmp_eps); rethrow(me); end % Delete the intermediate file delete(tmp_eps); % Read in the generated bitmap A = imread(tmp_nam); % Delete the temporary bitmap file delete(tmp_nam); % Set border pixels to the correct colour if isequal(bcol, 'none') bcol = []; elseif isequal(bcol, [1 1 1]) bcol = uint8([255 255 255]); else for l = 1:size(A, 2) if ~all(reshape(A(:,l,:) == 255, [], 1)) break; end end for r = size(A, 2):-1:l if ~all(reshape(A(:,r,:) == 255, [], 1)) break; end end for t = 1:size(A, 1) if ~all(reshape(A(t,:,:) == 255, [], 1)) break; end end for b = size(A, 1):-1:t if ~all(reshape(A(b,:,:) == 255, [], 1)) break; end end bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1)); for c = 1:size(A, 3) A(:,[1:l-1, r+1:end],c) = bcol(c); A([1:t-1, b+1:end],:,c) = bcol(c); end end else if nargin < 3 renderer = '-opengl'; end err = false; % Set paper size old_pos_mode = get(fig, 'PaperPositionMode'); old_orientation = get(fig, 'PaperOrientation'); set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait'); try % Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function) fp = []; % in case we get an error below fp = findall(fig, 'Type','patch', 'LineWidth',0.75); set(fp, 'LineWidth',0.5); % Fix issue #83: use numeric handles in HG1 if ~using_hg2(fig), fig = double(fig); end % Print to tiff file print(fig, renderer, res_str, '-dtiff', tmp_nam); % Read in the printed file A = imread(tmp_nam); % Delete the temporary file delete(tmp_nam); catch ex err = true; end set(fp, 'LineWidth',0.75); % restore original figure appearance % Reset paper size set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation); % Throw any error that occurred if err % Display suggested workarounds to internal print() error (issue #16) fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n'); rethrow(ex); end % Set the background color if isequal(bcol, 'none') bcol = []; else bcol = bcol * 255; if isequal(bcol, round(bcol)) bcol = uint8(bcol); else bcol = squeeze(A(1,1,:)); end end end % Check the output size is correct if isequal(res, round(res)) px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below if ~isequal(size(A), px) % Correct the output size A = A(1:min(end,px(1)),1:min(end,px(2)),:); end end end % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); end
github
andreafarina/SOLUS-master
append_pdfs.m
.m
SOLUS-master/src/util/export_fig/append_pdfs.m
2,759
utf_8
9b52be41aff48bea6f27992396900640
%APPEND_PDFS Appends/concatenates multiple PDF files % % Example: % append_pdfs(output, input1, input2, ...) % append_pdfs(output, input_list{:}) % append_pdfs test.pdf temp1.pdf temp2.pdf % % This function appends multiple PDF files to an existing PDF file, or % concatenates them into a PDF file if the output file doesn't yet exist. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % % IN: % output - string of output file name (including the extension, .pdf). % If it exists it is appended to; if not, it is created. % input1 - string of an input file name (including the extension, .pdf). % All input files are appended in order. % input_list - cell array list of input file name strings. All input % files are appended in order. % Copyright: Oliver Woodford, 2011 % Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in % one go is much faster than appending them one at a time. % Thanks to Michael Teo for reporting the issue of a too long command line. % Issue resolved on 5/5/2011, by passing gs a command file. % Thanks to Martin Wittmann for pointing out the quality issue when % appending multiple bitmaps. % Issue resolved (to best of my ability) 1/6/2011, using the prepress % setting % 26/02/15: If temp dir is not writable, use the output folder for temp % files when appending (Javier Paredes); sanity check of inputs function append_pdfs(varargin) if nargin < 2, return; end % sanity check % Are we appending or creating a new file append = exist(varargin{1}, 'file') == 2; output = [tempname '.pdf']; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(output,'w'); fwrite(fid,1); fclose(fid); delete(output); isTempDirOk = true; catch % Temp dir is not writable, so use the output folder [dummy,fname,fext] = fileparts(output); %#ok<ASGLU> fpath = fileparts(varargin{1}); output = fullfile(fpath,[fname fext]); isTempDirOk = false; end if ~append output = varargin{1}; varargin = varargin(2:end); end % Create the command file if isTempDirOk cmdfile = [tempname '.txt']; else cmdfile = fullfile(fpath,[fname '.txt']); end fh = fopen(cmdfile, 'w'); fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output); fprintf(fh, ' "%s"', varargin{:}); fclose(fh); % Call ghostscript ghostscript(['@"' cmdfile '"']); % Delete the command file delete(cmdfile); % Rename the file if needed if append movefile(output, varargin{1}); end end
github
andreafarina/SOLUS-master
using_hg2.m
.m
SOLUS-master/src/util/export_fig/using_hg2.m
1,037
utf_8
3303caab5694b040103ccb6b689387bf
%USING_HG2 Determine if the HG2 graphics engine is used % % tf = using_hg2(fig) % %IN: % fig - handle to the figure in question. % %OUT: % tf - boolean indicating whether the HG2 graphics engine is being used % (true) or not (false). % 19/06/2015 - Suppress warning in R2015b; cache result for improved performance function tf = using_hg2(fig) persistent tf_cached if isempty(tf_cached) try if nargin < 1, fig = figure('visible','off'); end oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval'); try % This generates a [supressed] warning in R2015b: tf = ~graphicsversion(fig, 'handlegraphics'); catch tf = verLessThan('matlab','8.4'); % =R2014b end warning(oldWarn); catch tf = false; end if nargin < 1, delete(fig); end tf_cached = tf; else tf = tf_cached; end end
github
andreafarina/SOLUS-master
eps2pdf.m
.m
SOLUS-master/src/util/export_fig/eps2pdf.m
8,543
utf_8
a63a364925b89dac21030d36b0dd29a3
function eps2pdf(source, dest, crop, append, gray, quality, gs_options) %EPS2PDF Convert an eps file to pdf format using ghostscript % % Examples: % eps2pdf source dest % eps2pdf(source, dest, crop) % eps2pdf(source, dest, crop, append) % eps2pdf(source, dest, crop, append, gray) % eps2pdf(source, dest, crop, append, gray, quality) % eps2pdf(source, dest, crop, append, gray, quality, gs_options) % % This function converts an eps file to pdf format. The output can be % optionally cropped and also converted to grayscale. If the output pdf % file already exists then the eps file can optionally be appended as a new % page on the end of the eps file. The level of bitmap compression can also % optionally be set. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % % Inputs: % source - filename of the source eps file to convert. The filename is % assumed to already have the extension ".eps". % dest - filename of the destination pdf file. The filename is assumed % to already have the extension ".pdf". % crop - boolean indicating whether to crop the borders off the pdf. % Default: true. % append - boolean indicating whether the eps should be appended to the % end of the pdf as a new page (if the pdf exists already). % Default: false. % gray - boolean indicating whether the output pdf should be grayscale % or not. Default: false. % quality - scalar indicating the level of image bitmap quality to % output. A larger value gives a higher quality. quality > 100 % gives lossless output. Default: ghostscript prepress default. % gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If % multiple options are needed, enclose in call array: {'-a','-b'} % Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015- % Suggestion of appending pdf files provided by Matt C at: % http://www.mathworks.com/matlabcentral/fileexchange/23629 % Thank you to Fabio Viola for pointing out compression artifacts, leading % to the quality setting. % Thank you to Scott for pointing out the subsampling of very small images, % which was fixed for lossless compression settings. % 9/12/2011 Pass font path to ghostscript. % 26/02/15: If temp dir is not writable, use the dest folder for temp % destination files (Javier Paredes) % 28/02/15: Enable users to specify optional ghostscript options (issue #36) % 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve % some /findfont errors according to James Rankin, FEX Comment 23/01/15) % 23/06/15: Added extra debug info in case of ghostscript error; code indentation % 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova) % Intialise the options string for ghostscript options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"']; % Set crop option if nargin < 3 || crop options = [options ' -dEPSCrop']; end % Set the font path fp = font_path(); if ~isempty(fp) options = [options ' -sFONTPATH="' fp '"']; end % Set the grayscale option if nargin > 4 && gray options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray']; end % Set the bitmap quality if nargin > 5 && ~isempty(quality) options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false']; if quality > 100 options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"']; else options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode']; v = 1 + (quality < 80); quality = 1 - quality / 100; s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v); options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s); end end % Enable users to specify optional ghostscript options (issue #36) if nargin > 6 && ~isempty(gs_options) if iscell(gs_options) gs_options = sprintf(' %s',gs_options{:}); elseif ~ischar(gs_options) error('gs_options input argument must be a string or cell-array of strings'); else gs_options = [' ' gs_options]; end options = [options gs_options]; end % Check if the output file exists if nargin > 3 && append && exist(dest, 'file') == 2 % File exists - append current figure to the end tmp_nam = tempname; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(tmp_nam,'w'); fwrite(fid,1); fclose(fid); delete(tmp_nam); catch % Temp dir is not writable, so use the dest folder [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU> fpath = fileparts(dest); tmp_nam = fullfile(fpath,[fname fext]); end % Copy the file copyfile(dest, tmp_nam); % Add the output file names options = [options ' -f "' tmp_nam '" "' source '"']; try % Convert to pdf using ghostscript [status, message] = ghostscript(options); catch me % Delete the intermediate file delete(tmp_nam); rethrow(me); end % Delete the intermediate file delete(tmp_nam); else % File doesn't exist or should be over-written % Add the output file names options = [options ' -f "' source '"']; % Convert to pdf using ghostscript [status, message] = ghostscript(options); end % Check for error if status % Retry without the -sFONTPATH= option (this might solve some GS % /findfont errors according to James Rankin, FEX Comment 23/01/15) orig_options = options; if ~isempty(fp) options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' '); status = ghostscript(options); if ~status, return; end % hurray! (no error) end % Report error if isempty(message) error('Unable to generate pdf. Check destination directory is writable.'); elseif ~isempty(strfind(message,'/typecheck in /findfont')) % Suggest a workaround for issue #41 (missing font path) font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1')); fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name); fpath = fileparts(mfilename(-fullpath')); gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt'); fprintf(2, ' try to add the font''s folder to your %s file\n\n', gs_fonts_file); error('export_fig error'); else fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest); if ~isempty(gs_options) fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\n', gs_options); end fprintf(2, 'Ghostscript options: %s\n\n', orig_options); error(message); end end end % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); end
github
andreafarina/SOLUS-master
ghostscript.m
.m
SOLUS-master/src/util/export_fig/ghostscript.m
7,683
utf_8
4def5873a1621e793bd59aaa23f3fc25
function varargout = ghostscript(cmd) %GHOSTSCRIPT Calls a local GhostScript executable with the input command % % Example: % [status result] = ghostscript(cmd) % % Attempts to locate a ghostscript executable, finally asking the user to % specify the directory ghostcript was installed into. The resulting path % is stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have Ghostscript installed on your % system. You can download this from: http://www.ghostscript.com % % IN: % cmd - Command string to be passed into ghostscript. % % OUT: % status - 0 iff command ran without problem. % result - Output from ghostscript. % Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015- %{ % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS. % Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems. % 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and % Shaun Kline for pointing out the issue % 04/05/11 - Thanks to David Chorlian for pointing out an alternative % location for gs on linux. % 12/12/12 - Add extra executable name on Windows. Thanks to Ratish % Punnoose for highlighting the issue. % 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick % Steinbring for proposing the fix. % 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes % for the fix. % 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen % Vermeer for raising the issue. % 27/02/15 - If Ghostscript croaks, display suggested workarounds % 30/03/15 - Improved performance by caching status of GS path check, if ok % 14/05/15 - Clarified warning message in case GS path could not be saved % 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74) %} try % Call ghostscript [varargout{1:nargout}] = system([gs_command(gs_path()) cmd]); catch err % Display possible workarounds for Ghostscript croaks url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998'; % issue #12 url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270'; % issue #20 hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\n * <a href="%s">%s</a> ',hg2_str,url1,url1); if using_hg2 fprintf(2, '(GS 9.10)\n * <a href="%s">%s</a> (R2014a)',url2,url2); end fprintf('\n\n'); if ismac || isunix url3 = 'https://github.com/altmany/export_fig/issues/27'; % issue #27 fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\n * <a href="%s">%s</a>\n\n',url3,url3); % issue #20 fpath = which(mfilename); if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export..." to "setenv ..."\nat the bottom of <a href="matlab:opentoline(''%s'',174)">%s</a>\n\n',fpath,fpath); end rethrow(err); end end function path_ = gs_path % Return a valid path % Start with the currently set path path_ = user_string('ghostscript'); % Check the path works if check_gs_path(path_) return end % Check whether the binary is on the path if ispc bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'}; else bin = {'gs'}; end for a = 1:numel(bin) path_ = bin{a}; if check_store_gs_path(path_) return end end % Search the obvious places if ispc default_location = 'C:\Program Files\gs\'; dir_list = dir(default_location); if isempty(dir_list) default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems dir_list = dir(default_location); end executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'}; ver_num = 0; % If there are multiple versions, use the newest for a = 1:numel(dir_list) ver_num2 = sscanf(dir_list(a).name, 'gs%g'); if ~isempty(ver_num2) && ver_num2 > ver_num for b = 1:numel(executable) path2 = [default_location dir_list(a).name executable{b}]; if exist(path2, 'file') == 2 path_ = path2; ver_num = ver_num2; end end end end if check_store_gs_path(path_) return end else executable = {'/usr/bin/gs', '/usr/local/bin/gs'}; for a = 1:numel(executable) path_ = executable{a}; if check_store_gs_path(path_) return end end end % Ask the user to enter the path while true if strncmp(computer, 'MAC', 3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Ghostscript not found. Please locate the program.')) end base = uigetdir('/', 'Ghostcript not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; %#ok<AGROW> bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) for b = 1:numel(bin) path_ = [base bin_dir{a} bin{b}]; if exist(path_, 'file') == 2 if check_store_gs_path(path_) return end end end end end error('Ghostscript not found. Have you installed it from www.ghostscript.com?'); end function good = check_store_gs_path(path_) % Check the path is valid good = check_gs_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('ghostscript', path_) filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt'); warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_); return end end function good = check_gs_path(path_) persistent isOk if isempty(path_) isOk = false; elseif ~isequal(isOk,true) % Check whether the path is valid [status, message] = system([gs_command(path_) '-h']); %#ok<ASGLU> isOk = status == 0; end good = isOk; end function cmd = gs_command(path_) % Initialize any required system calls before calling ghostscript % TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh) shell_cmd = ''; if isunix shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07 end if ismac shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07 end % Construct the command string cmd = sprintf('%s"%s" ', shell_cmd, path_); end