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
sheldona/hessianIK-master
emptySkeleton.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/emptySkeleton.m
2,792
utf_8
269e811e8abce591c94074b36eeba9aa
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function skel = emptySkeleton skel = struct('njoints',0,... % number of joints 'rootRotationalOffsetEuler',[0;0;0],... % global (constant) rotation of root in world system, Euler angles. 'rootRotationalOffsetQuat',[1;0;0;0],... % global (constant) rotation of root in world system, quaternion. 'nodes',struct([]),... % struct array containing nodes of skeleton tree data structure 'paths',cell(1,1),... % contains a set of edge-disjoint paths the union of which represents the whole tree; represented as cell array of joint ID vectors 'jointNames',cell(1,1),... % cell array of joint names: maps joint ID to joint name 'boneNames',cell(1,1),... % cell array of bone names: maps bone ID to node name. ID 1 is the root. 'nameMap',cell(1,1),... % cell array mapping standard joint names to DOF IDs and trajectory IDs 'animated',[],... % vector of IDs for animated joints/bones 'unanimated',[],... % vector of IDs for unanimated joints/bones 'filename','',... % source filename 'version','',... % file format version 'name','',... % name for this skeleton 'massUnit',1,... % unit divisor for mass 'lengthUnit',1,... % unit divisor for lengths 'angleUnit','deg',... % angle unit (deg or rad) 'documentation','',... % documentation from source file 'fileType','',... % file type (BVH / ASF) 'skin',cell(1,1)); % cell array of skin filenames for this skeleton
github
sheldona/hessianIK-master
emptySkeletonNode.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/emptySkeletonNode.m
2,036
utf_8
5f2126b69ec37eb46b000e2c8f162a24
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function node = emptySkeletonNode node = struct('children',[],... % struct array containing this node's child nodes' indices within "nodes" array of skeleton data structure 'jointName','',... % name of this joint (if it is a joint (BVH)) 'boneName','',... % name of this bone (if it is a bone (ASF)) 'ID',0,... % ID number of this joint/bone 'parentID',0,... % parent node ID 'offset',[0;0;0],... % offset vector from the parent of this node to this node 'direction',[0;0;0],... % direction vector for this bone, given in global coordinates 'length',0,... % length of this bone 'axis',[0;0;0],... % axis of rotation for this node 'DOF',cell(1,1),... % degrees of freedom and rotation order for this node, in the form {'tx','ty','tz','rx','ry','rz'} (e.g.) 'rotationOrder','',... % rotation order in string representation (e.g., 'xyz') 'limits',[]); % kx2, kx2 or kx2 matrix of limits for this node's DOFs
github
sheldona/hessianIK-master
amc_to_matrix.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/ASFAMCparser/amc_to_matrix.m
2,554
utf_8
b1cf288c34613efe546bd9409ebb7ae7
% Reads data from an AMC motion file into a Matlab matrix variable. % AMC file has to be in the AMC format used in the online CMU motion capture library. % number of dimensions = number of columns = 62 % function D = amc_to_matrix(fname) % fname = name of disk input file, in AMC format % Example: % D = amc_to_matrix(fname) % % Jernej Barbic % CMU % March 2003 % Databases Course function [D] = amc_to_matrix(fname) fid=fopen(fname, 'rt'); if fid == -1, fprintf('Error, can not open file %s.\n', fname); return; end; % read-in header line=fgetl(fid); while ~strcmp(line,':DEGREES') line=fgetl(fid); end D=[]; dims =[6 3 3 3 3 3 3 2 3 1 1 2 1 2 2 3 1 1 2 1 2 3 1 2 1 3 1 2 1]; locations = [1 7 10 13 16 19 22 25 27 30 31 32 34 35 37 39 42 43 44 46 47 49 52 53 55 56 59 60 62]; % read-in data % labels can be in any order frame=1; while ~feof(fid) if rem(frame,100) == 0 disp('Reading frame: '); disp(frame); end; row = zeros(62,1); % read frame number line = fscanf(fid,'%s\n',1); for i=1:29 % read angle label id = fscanf (fid,'%s',1); switch (id) case 'root', index = 1; case 'lowerback', index = 2; case 'upperback', index = 3; case 'thorax', index = 4; case 'lowerneck', index = 5; case 'upperneck', index = 6; case 'head', index = 7; case 'rclavicle', index = 8; case 'rhumerus', index = 9; case 'rradius', index = 10; case 'rwrist', index = 11; case 'rhand', index = 12; case 'rfingers', index = 13; case 'rthumb', index = 14; case 'lclavicle', index = 15; case 'lhumerus', index = 16; case 'lradius', index = 17; case 'lwrist', index = 18; case 'lhand', index = 19; case 'lfingers', index = 20; case 'lthumb', index = 21; case 'rfemur', index = 22; case 'rtibia', index = 23; case 'rfoot', index = 24; case 'rtoes', index = 25; case 'lfemur', index = 26; case 'ltibia', index = 27; case 'lfoot', index = 28; case 'ltoes', index = 29; otherwise fprintf('Error, labels in the amc are not correct.\n'); return; end % where to put the data location = locations(index); len = dims(index); if len == 6 x = fscanf (fid,'%f %f %f %f %f %f\n',6); else if len == 3 x = fscanf (fid,'%f %f %f\n',3); else if len == 2 x = fscanf (fid,'%f %f\n',2); else if len == 1 x = fscanf (fid,'%f\n',1); end end end end row(location:location+len-1,1) = x; end row = row'; D = [D; row]; frame = frame + 1; end disp('Total number of frames read: '); disp(frame-1); fclose(fid);
github
sheldona/hessianIK-master
matrix_to_amc.m
.m
hessianIK-master/matlab/HDM05-Parser/parser/ASFAMCparser/matrix_to_amc.m
2,157
utf_8
54cc2acc388d5a139ee98e11ff0745c4
% Writes motion data from matrix D to an AMC file on disk. % The ACM format is the format used in the CMU online motion capture database % function [] = matrix_to_amc(fname, D) % fname = output disk file name for AMC file % D = input Matlab data matrix % Example: % matrix_to_amc('running1.amc', D) % % % Jernej Barbic % CMU % March 2003 % Databases Course function [] = matrix_to_amc(fname, D) fid=fopen(fname, 'wt'); if fid == -1, fprintf('Error, can not open file %s.\n', fname); return; end; % print header fprintf(fid,'#!Matlab matrix to amc conversion\n'); fprintf(fid,':FULLY-SPECIFIED\n'); fprintf(fid,':DEGREES\n'); [rows, cols] = size(D); % print data for frame=1:rows fprintf(fid,'%d\n',frame); fprintf(fid,'root %f %f %f %f %f %f\n', D(frame,1:6)); fprintf(fid,'lowerback %f %f %f\n', D(frame,7:9)); fprintf(fid,'upperback %f %f %f\n', D(frame,10:12)); fprintf(fid,'thorax %f %f %f\n', D(frame,13:15)); fprintf(fid,'lowerneck %f %f %f\n', D(frame,16:18)); fprintf(fid,'upperneck %f %f %f\n', D(frame,19:21)); fprintf(fid,'head %f %f %f\n', D(frame,22:24)); fprintf(fid,'rclavicle %f %f\n', D(frame,25:26)); fprintf(fid,'rhumerus %f %f %f\n', D(frame,27:29)); fprintf(fid,'rradius %f\n', D(frame,30)); fprintf(fid,'rwrist %f\n', D(frame,31)); fprintf(fid,'rhand %f %f\n', D(frame,32:33)); fprintf(fid,'rfingers %f\n', D(frame,34)); fprintf(fid,'rthumb %f %f\n', D(frame,35:36)); fprintf(fid,'lclavicle %f %f\n', D(frame,37:38)); fprintf(fid,'lhumerus %f %f %f\n', D(frame,39:41)); fprintf(fid,'lradius %f\n', D(frame,42)); fprintf(fid,'lwrist %f\n', D(frame,43)); fprintf(fid,'lhand %f %f\n', D(frame,44:45)); fprintf(fid,'lfingers %f\n', D(frame,46)); fprintf(fid,'lthumb %f %f\n', D(frame,47:48)); fprintf(fid,'rfemur %f %f %f\n', D(frame,49:51)); fprintf(fid,'rtibia %f\n', D(frame,52)); fprintf(fid,'rfoot %f %f\n', D(frame,53:54)); fprintf(fid,'rtoes %f\n', D(frame,55)); fprintf(fid,'lfemur %f %f %f\n', D(frame,56:58)); fprintf(fid,'ltibia %f\n', D(frame,59)); fprintf(fid,'lfoot %f %f\n', D(frame,60:61)); fprintf(fid,'ltoes %f\n', D(frame,62)); end fclose(fid);
github
sheldona/hessianIK-master
filterR4.m
.m
hessianIK-master/matlab/HDM05-Parser/quaternions/filterR4.m
2,139
utf_8
9c7df4fc6f448e66036bb7397f11e78e
function [Y,t] = filterR4(varargin) % Y = filterR4(w,X,step,padding_method) % Filters curves embedded in the unit quaternion sphere with a sliding window. % Simply views quats as 4D data without additional structure and renormalizes % to S^3 after filtering % % Input: w, weight vector % X, 4xN matrix of input unit quaternions % optional: step, step size for window (window length is length(w)), default is step=1. % ->!! Length of output sequence is ceil(N/step). !! <- % optional: padding method, one of {'symmetric', 'zero'}. default is 'symmetric' % % Output: Y, Filtered version of X % t, running time for filter. % switch (nargin) case 2 w = varargin{1}; X = varargin{2}; step = 1; padding_method = 'symmetric'; case 3 w = varargin{1}; X = varargin{2}; step = varargin{3}; padding_method = 'symmetric'; case 4 w = varargin{1}; X = varargin{2}; step = varargin{3}; padding_method = varargin{4}; otherwise error('Wrong number of arguments!'); end L = size(w,2); N = size(X,2); if (L>N) error('Filter length must not be larger than number of data points!'); end %%%% prepare data set X by means of pre- and postpadding switch mod(L,2) case 0 % even filter length prepad_length = L/2; postpad_length = L/2 - 1; case 1 % odd filter length prepad_length = (L - 1)/2; postpad_length = (L - 1)/2; end tic; if (strncmp(padding_method,'symmetric',1)) pre = fliplr(X(:,1:prepad_length)); post = fliplr(X(:,N-postpad_length+1:N)); elseif (strncmp(padding_method,'zero',1)) pre = [ones(1,prepad_length);zeros(3,prepad_length)]; post = [ones(1,postpad_length);zeros(3,postpad_length)];; else error('Unknown padding option!'); end X = [pre X post]; Y = zeros(4,ceil(N/step)); for (i=1:ceil(N/step)) pos = step*(i-1)+1; Y(:,i) = bruteForceAverageR4(X(:,pos:pos+L-1),w); end t = toc; %%%%%%%%%%% function Y = bruteForceAverageR4(X,w) Y = sum(X.*repmat(w,4,1),2); Y = Y./sqrt(sum(Y.^2,1));
github
sheldona/hessianIK-master
new_animate.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/new_animate.m
4,443
utf_8
7c2a0775e942d33be94bf604b50913e4
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function new_animate(skel,mot,varargin) % new_animate(skel,mot,num_repeats,time_stretch_factor,range,draw_labels,observer_fcn,start_animation) % INPUT: % - skel and mot are assumed to be struct arrays of identical length containing % skeleton/motion pairs to be animated simultaneously. All mots are supposed to have the same samplingRate. % - range is a cell array which is supposed to be of same length as skel/mot. % Empty cell array entries in range indicate that the entire frame range is to be played back. % - draw_labels is a logical vector the same length as skel indicating whether the corresponding skeleton % is to be drawn with a frame counter label. Empty draw_labels means "draw no labels at all". % - observer_fcn function called at each frame animation; used for progress monitoring % - start_animation determines whether the actual animation shall start immediately or pause until resumeAnimation is called. global VARS_GLOBAL_ANIM if (isempty(VARS_GLOBAL_ANIM)) VARS_GLOBAL_ANIM = emptyVarsGlobalAnimStruct; end num_repeats = 1; time_stretch_factor = 1; VARS_GLOBAL_ANIM.range = cell(length(mot),1); VARS_GLOBAL_ANIM.draw_labels = ones(length(mot),1); start_animation = true; timer_fcn = {'new_animate_showFrame'}; if (nargin>7) start_animation = varargin{6}; end if (nargin>6) timer_fcn = {'new_animate_showFrame',varargin{5}}; end if (nargin > 5) VARS_GLOBAL_ANIM.draw_labels = varargin{4}; end if (nargin > 4) VARS_GLOBAL_ANIM.range = varargin{3}; if (~iscell(VARS_GLOBAL_ANIM.range)) VARS_GLOBAL_ANIM.range = {VARS_GLOBAL_ANIM.range}; end end if (nargin > 3) time_stretch_factor = varargin{2}; end if (nargin > 2) num_repeats = varargin{1}; end VARS_GLOBAL_ANIM.skel = skel; VARS_GLOBAL_ANIM.mot = mot; num_frames = -inf; if (isempty(VARS_GLOBAL_ANIM.range)) VARS_GLOBAL_ANIM.range = cell(1,length(mot)); end for k=1:length(VARS_GLOBAL_ANIM.mot) if (isempty(VARS_GLOBAL_ANIM.range{k})) VARS_GLOBAL_ANIM.range{k} = [1:VARS_GLOBAL_ANIM.mot(k).nframes]; end if (length(VARS_GLOBAL_ANIM.range{k})>num_frames) % determine num_frames as maximum of range lengths num_frames = length(VARS_GLOBAL_ANIM.range{k}); end end new_animate_initGraphics; desired_frame_time = VARS_GLOBAL_ANIM.mot(1).frameTime; if (~isempty(VARS_GLOBAL_ANIM.figure_camera_file)) h = str2func(VARS_GLOBAL_ANIM.figure_camera_file); feval(h, gca); end if (~isempty(VARS_GLOBAL_ANIM.figure_position)) set(gcf,'position',VARS_GLOBAL_ANIM.figure_position); end for (i=1:num_repeats) VARS_GLOBAL_ANIM.frame_draw_time = 0; VARS_GLOBAL_ANIM.frames_drawn = 0; VARS_GLOBAL_ANIM.animation_done = false; t=timerfind('Name','AnimationTimer'); if (~isempty(t)) delete(t); end t = timer('Name','AnimationTimer'); try VARS_GLOBAL_ANIM.previous_call = clock; VARS_GLOBAL_ANIM.current_frame = 1; VARS_GLOBAL_ANIM.frames_total = num_frames; set(t,'TimerFcn',timer_fcn); set(t,'ExecutionMode','fixedRate'); set(t,'TasksToExecute',num_frames); period = round(1000*desired_frame_time/time_stretch_factor)/1000; VARS_GLOBAL_ANIM.timer_period = period; if (period == 0) warning(['Requested timer period of ' num2str(desired_frame_time/time_stretch_factor) ' s is too short for Matlab! Setting period to minimum of 1 ms :-(']); period = 0.001; end set(t,'Period',period); set(t,'BusyMode','queue'); if(start_animation) start(t); end catch delete(t); return end end
github
sheldona/hessianIK-master
coordsDiscNormal.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/coordsDiscNormal.m
2,544
utf_8
ef826401167a9e0fcb50a9677d3e8573
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [X,Y,Z] = coordsDiscNormal(n, x0, radius, nsteps, offset) % [X,Y,Z] = coordsDiscNormal(n, x0, radius, nsteps, offset) % % creates the coordinates of a regular nsteps-gon in 3-space within a plane specified by n and x0 % n....... normal vector, must be 3 x 1 % x0...... fixture point, must be 3 x 1 % radius.. scalar % nsteps.. integer, specifies number of vertices % offset.. constant offset to x0, 3 x 1. Will be projected onto plane. % X,Y and Z are vectors of length nsteps d = length(n); i = find(abs(n)>eps); % find first nonzero component of n % a new basis {e_1,...,e_{i-1},n,e_{i+1},...,e_d}, % where e_i was replaced by n, will still span the whole space IR^d, % since e_i appears in the expansion of n with a nonzero coefficient. if (size(i) == 0) % in this case the normal was near zero... useless! return; end; i = i(1); P = eye(d); % construct permutation matrix that swaps rows 1 and i z = P(:,i); P(:,i) = P(:,1); P(:,1) = z; %line([x0(1);x0(1)+n(1)],[x0(2);x0(2)+n(2)],[x0(3);x0(3)+n(3)]); offset_proj = offset - dot(n,offset) * n; n = P * n; % don't forget to change the representation of our normal! R = zeros(d,d); R(:,1) = n; % "basis vector e_1 will map to n"; replace e_1 (the former e_i) by n. R(2:d,2:d) = eye(d-1); R = gramschmidt(R); % R now contains an orthonormal basis where the first basis vector is n. R = R * P; % permute back: R now contains an orthonormal basis where the ith basis vector is n. t = [0:(2*pi)/nsteps:2*pi-(1/nsteps)]; M = [zeros(1,nsteps); radius*cos(t); radius*sin(t)]; midpoint = x0+offset_proj; %M = R * M + repmat(midpoint,1,nsteps); M = R * M + midpoint(:, ones(1, nsteps)); X = [M(1,:)'; midpoint(1)]; Y = [M(2,:)'; midpoint(2)]; Z = [M(3,:)'; midpoint(3)];
github
sheldona/hessianIK-master
coordsCappedCylinder.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/coordsCappedCylinder.m
4,089
utf_8
90bc8049364cd8f5a2b1163f35b9475f
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [X,Y,Z] = coordsCappedCylinder(p1, p2, epsilon, nsteps, varargin) % [X,Y,Z] = coordsCappedCylinder(p1, p2, epsilon, nsteps, use_caps) % % creates the coordinates of half-sphere-capped cylinder around line segment p1p2 in 3-space, of radius epsilon. % p1...... point 2 defining line segment, must be 3 x 1 % p2...... point 2 defining line segment, must be 3 x 1 % epsilon. scalar % nsteps.. integer, specifies number of vertices at circular cylinder circumference and number of longitude lines around caps % use_caps boolean 2-vector indicating whether caps at p1 and p2 are to be included or not % X,Y and Z are vectors. length: cylinder contributes 2*nsteps entries, each cap contributes (ceil(nsteps/2)-1)*nsteps+1 entries use_caps = [true true]; if (nargin>4) use_caps = varargin{1}; end n = (p2-p1)/norm(p2-p1); d = length(n); i = find(abs(n)>eps); % find first nonzero component of n % a new basis {e_1,...,e_{i-1},n,e_{i+1},...,e_d}, % where e_i was replaced by n, will still span the whole space IR^d, % since e_i appears in the expansion of n with a nonzero coefficient. if (size(i) == 0) % in this case the normal was near zero... useless! return; end; i = i(1); P = eye(d); % construct permutation matrix that swaps rows 1 and i z = P(:,i); P(:,i) = P(:,1); P(:,1) = z; %line([x0(1);x0(1)+n(1)],[x0(2);x0(2)+n(2)],[x0(3);x0(3)+n(3)]); n = P * n; % don't forget to change the representation of our normal! R = zeros(d,d); R(:,1) = n; % "basis vector e_1 will map to n"; replace e_1 (the former e_i) by n. R(2:d,2:d) = eye(d-1); R = gramschmidt(R); % R now contains an orthonormal basis where the first basis vector is n. R = R * P; % permute back: R now contains an orthonormal basis where the ith basis vector is n. t = [0:(2*pi)/nsteps:2*pi-(1/nsteps)]; M = [zeros(1,nsteps); epsilon*cos(t); epsilon*sin(t)]; M1 = R * M + repmat(p1,1,nsteps); M2 = R * M + repmat(p2,1,nsteps); X = M1(1,:)'; Y = M1(2,:)'; Z = M1(3,:)'; nlatitude = ceil(nsteps/2); C = zeros(3,(nlatitude-1)*nsteps); % create half sphere with nlatitude latitude and nsteps longitude lines k=1; for alpha=(pi/2)/nlatitude:(pi/2)/nlatitude:pi/2-(pi/2)/nlatitude radius = epsilon * cos(alpha); h = epsilon * sin(alpha); C(:,(k-1)*nsteps+1:k*nsteps) = [h*ones(1,nsteps); radius*cos(t); radius*sin(t)]; k=k+1; end v = (p2-p1)/norm(p2-p1); if (use_caps(1)) Cflip(1,:) = -C(1,:); Cflip(2:3,:) = C(2:3,:); C1 = R * Cflip + repmat(p1,1,(nlatitude-1)*nsteps); X = [X; C1(1,:)'; p1(1)-v(1)*epsilon]; Y = [Y; C1(2,:)'; p1(2)-v(2)*epsilon]; Z = [Z; C1(3,:)'; p1(3)-v(3)*epsilon]; else Cflat = C; Cflat(1,:) = zeros(1,size(C,2)); C1 = R * Cflat + repmat(p1,1,(nlatitude-1)*nsteps); X = [X; C1(1,:)'; p1(1)]; Y = [Y; C1(2,:)'; p1(2)]; Z = [Z; C1(3,:)'; p1(3)]; end X = [X; M2(1,:)']; Y = [Y; M2(2,:)']; Z = [Z; M2(3,:)']; if (use_caps(2)) C2 = R * C + repmat(p2,1,(nlatitude-1)*nsteps); X = [X; C2(1,:)'; p2(1)+v(1)*epsilon]; Y = [Y; C2(2,:)'; p2(2)+v(2)*epsilon]; Z = [Z; C2(3,:)'; p2(3)+v(3)*epsilon]; else Cflat = C; Cflat(1,:) = zeros(1,size(C,2)); C2 = R * Cflat + repmat(p2,1,(nlatitude-1)*nsteps); X = [X; C2(1,:)'; p2(1)]; Y = [Y; C2(2,:)'; p2(2)]; Z = [Z; C2(3,:)'; p2(3)]; end
github
sheldona/hessianIK-master
old_createPlaneNormal.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/old_createPlaneNormal.m
1,183
utf_8
b97f43b934cb7043af84fe9ae222d544
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [X,Y,Z] = createPlaneNormal(n, x0, sides_length) X = [-sides_length(1)/2 -sides_length(1)/2;sides_length(1)/2 sides_length(1)/2]; Y = [sides_length(2)/2 -sides_length(2)/2;sides_length(2)/2 -sides_length(2)/2]; Z = [0 0;0 0]; n0 = [0;0;1]; x = cross(n,n0); cphi = dot(n/norm(n),n0/norm(n0)); rotate(h,x,phi*180/pi); set(h,'facecolor','black'); alpha(h,0.25);
github
sheldona/hessianIK-master
animateGUI.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/animateGUI.m
13,691
utf_8
5739395d8d277eb8131b34cd31154869
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function varargout = animateGUI(varargin) % animateGUI M-file for animateGUI.fig % animateGUI, by itself, creates a new animateGUI or raises the existing % singleton*. % % H = animateGUI returns the handle to a new animateGUI or the handle to % the existing singleton*. % % animateGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in animateGUI.M with the given input arguments. % % animateGUI('Property','Value',...) creates a new animateGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before animateGUI_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to animateGUI_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help animateGUI % Last Modified by GUIDE v2.5 18-Jul-2006 17:52:38 % Begin initialization code - DO NOT EDIT gui_Singleton = 0; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @animateGUI_OpeningFcn, ... 'gui_OutputFcn', @animateGUI_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin & isstr(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Executes just before animateGUI is made visible. function animateGUI_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to animateGUI (see VARARGIN) % Choose default command line output for animateGUI handles.output = hObject; handles.skel = varargin{1}; handles.mot = varargin{2}; mot_num = length(handles.mot); frames_total = max([handles.mot.nframes]); set(handles.slider_animate, 'Min',0.9,'Max', frames_total +.1,'Value', 1,'SliderStep', [1/frames_total 1/frames_total]); % reset animation controls set(handles.slider_animate, 'Enable','off'); set(handles.slider_speed,'Enable','off'); set(handles.pushbutton_pause,'Enable','off'); set(handles.pushbutton_play,'Enable','off'); % Update handles structure guidata(hObject, handles); cameratoolbar; cameratoolbar('SetCoordSys','y'); handles = startAnimation(hObject,handles); % frame counter global VARS_GLOBAL_ANIM; VARS_GLOBAL_ANIM.graphics_data.frameLabel = handles.text_frameCounter; % UIWAIT makes animateGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Outputs from this function are returned to the command line. function varargout = animateGUI_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Start animating function handles = startAnimation(hObject,handles) % hObject handle to UI-control calling this function % handles structure with handles and user data (see GUIDATA) global VARS_GLOBAL_ANIM % pause the animation that might currently be running pauseAnimation; % prepare animation controls frames_total = max([handles.mot.nframes]); set(handles.slider_animate, 'Enable','on','Max', frames_total+.001,'Value', 1,'SliderStep', [1/frames_total 1/frames_total]); set(handles.slider_speed, 'Enable','on'); set(handles.pushbutton_play, 'Enable','on'); set(handles.pushbutton_pause, 'Enable','on'); speed = get(handles.slider_speed,'Value'); % set some properties for the animation VARS_GLOBAL_ANIM = emptyVarsGlobalAnimStruct; VARS_GLOBAL_ANIM.figure_color = get(gcf,'Color'); VARS_GLOBAL_ANIM.animated_skeleton_Color = [0 0 0]/255; VARS_GLOBAL_ANIM.animated_skeleton_Marker = '.'; VARS_GLOBAL_ANIM.animated_skeleton_MarkerEdgeColor = [1 0 0]; VARS_GLOBAL_ANIM.animated_skeleton_MarkerFaceColor = [1 0 0]; VARS_GLOBAL_ANIM.kill_timer = false; VARS_GLOBAL_ANIM.animated_skeleton_MarkerSize = 8; VARS_GLOBAL_ANIM.animated_point_MarkerSize = 12; VARS_GLOBAL_ANIM.animated_skeleton_LineWidth = 4; VARS_GLOBAL_ANIM.ground_tile_size_factor = 1; VARS_GLOBAL_ANIM.bounding_box_border_extension = 0.01; %VARS_GLOBAL_ANIM.figure_position = [5 5 512 384]; %rehash path set(gcf,'CurrentAxes',handles.axes_animate); cla reset; % start animation VARS_GLOBAL_ANIM.animation_paused = false; new_animate(handles.skel,handles.mot,1,speed,{},{},{'updateAnimationSlider',handles.slider_animate},true); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Executes on button press in pushbutton_pause. function pushbutton_pause_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_pause (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) pauseAnimation; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Executes on button press in pushbutton_play. function pushbutton_play_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_play (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global VARS_GLOBAL_ANIM; speed = get(handles.slider_speed,'Value'); frame = round(get(handles.slider_animate,'Value')); max_frame = round(get(handles.slider_animate,'Max')); if (frame == max_frame) resumeAnimation(1,speed); elseif (VARS_GLOBAL_ANIM.animation_paused) resumeAnimation(frame,speed); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Executes on slider movement. function slider_animate_Callback(hObject, eventdata, handles) % hObject handle to slider_animate (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider global VARS_GLOBAL_ANIM was_already_paused = VARS_GLOBAL_ANIM.animation_paused; pauseAnimation; current_frame = round(get(hObject,'Value')); VARS_GLOBAL_ANIM.current_frame = current_frame; new_animate_showFrame([],[],{},current_frame); if (~was_already_paused) resumeAnimation; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Executes during object creation, after setting all properties. function slider_animate_CreateFcn(hObject, eventdata, handles) % hObject handle to slider_animate (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background, change % 'usewhitebg' to 0 to use default. See ISPC and COMPUTER. usewhitebg = 1; if usewhitebg set(hObject,'BackgroundColor',[.9 .9 .9]); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Executes on button press in pushbutton_done. function pushbutton_done_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_done (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) pauseAnimation; t = timerfind('Name','AnimationTimer'); if (~isempty(t)) delete(t); end delete(gcf); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Executes during object creation, after setting all properties. function slider_speed_CreateFcn(hObject, eventdata, handles) % hObject handle to slider_speed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background, change % 'usewhitebg' to 0 to use default. See ISPC and COMPUTER. usewhitebg = 1; if usewhitebg set(hObject,'BackgroundColor',[.9 .9 .9]); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Executes on slider movement. function slider_speed_Callback(hObject, eventdata, handles) % hObject handle to slider_speed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider global VARS_GLOBAL_ANIM % adjust animation speed if(~VARS_GLOBAL_ANIM.animation_paused) pauseAnimation; current_frame = VARS_GLOBAL_ANIM.current_frame; speed = get(hObject,'Value'); resumeAnimation(current_frame,speed); else speed = get(hObject,'Value'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Executes on state change of checkbox_loop. function checkbox_loop_Callback(hObject, eventdata, handles) % hObject handle to checkbox_loop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox_loop global VARS_GLOBAL_ANIM VARS_GLOBAL_ANIM.loop_playback = get(hObject,'Value'); % --- Executes during object creation, after setting all properties. function edit_gotoFrame_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_gotoFrame (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end function edit_gotoFrame_Callback(hObject, eventdata, handles) % hObject handle to edit_gotoFrame (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_gotoFrame as text % str2double(get(hObject,'String')) returns contents of edit_gotoFrame as a double global VARS_GLOBAL_ANIM was_already_paused = VARS_GLOBAL_ANIM.animation_paused; pauseAnimation; current_frame = round(str2num(char(get(hObject,'String')))); VARS_GLOBAL_ANIM.current_frame = current_frame; new_animate_showFrame([],[],{},current_frame); if (~was_already_paused) resumeAnimation; end
github
sheldona/hessianIK-master
saveCamera.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/saveCamera.m
1,684
utf_8
7749a04b6cedd203283a11fafe2214e5
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function saveCamera(varargin) ax = gca; file = 'camera.m'; if (nargin>1) file = varargin{2}; end if (nargin>0) ax = varargin{1}; end [fid,msg]=fopen(file,'w'); if (fid < 0) disp(msg); return; end fprintf(fid,'function camera(axs)\n\n'); fprintf(fid,'set(axs,''CameraPosition'', [%s],...\n',num2str(get(ax,'CameraPosition'))); fprintf(fid,' ''CameraPositionMode'',''manual'',...\n'); fprintf(fid,' ''CameraTarget'', [%s],...\n',num2str(get(ax,'CameraTarget'))); fprintf(fid,' ''CameraTargetMode'',''manual'',...\n'); fprintf(fid,' ''CameraUpVector'', [%s],...\n',num2str(get(ax,'CameraUpVector'))); fprintf(fid,' ''CameraUpVectorMode'',''manual'',...\n'); fprintf(fid,' ''CameraViewAngle'', [%s],...\n',num2str(get(ax,'CameraViewAngle'))); fprintf(fid,' ''CameraViewAngleMode'',''manual'');'); fclose(fid);
github
sheldona/hessianIK-master
gramschmidt.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/gramschmidt.m
1,318
utf_8
3407cb5995f0348fefd4819b84082843
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function B = gramschmidt(A) n = size(A,1); if (size(A,2) ~= n) return; end; B = zeros(n,n); B(:,1) = (1/norm(A(:,1)))*A(:,1); for i=2:n v = A(:,i); U = B(:,1:i-1); % subspace basis which has already been orthonormalized pc = transpose(U)*v; % orthogonal projection coefficients of v onto U p = U * pc; % orthogonal projection vector of v onto U v = v - p; if (norm(v)<eps) % vectors are not linearly independent! return; end; v = v/norm(v); B(:,i) = v; end;
github
sheldona/hessianIK-master
coordsGridDiscNormal.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/coordsGridDiscNormal.m
2,922
utf_8
d2f60be72f8b308194ab808ee1b48fbb
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [X,Y,Z] = coordsGridDiscNormal(n, x0, radius, nlongitude, nlatitude, offset) % [X,Y,Z] = coordsGridDiscNormal(n, x0, radius, nlongitude, offset) % % creates the coordinates of nlongitude equally spaced concentric regular nlongitude-gons in 3-space within a plane specified by n and x0, max radius "radius" % n....... normal vector, must be 3 x 1 % x0...... fixture point, must be 3 x 1 % radius.. scalar % nlongitude.. integer, specifies number of vertices per concentric nstep-gon % offset.. constant offset to x0, 3 x 1. Will be projected onto plane. % X,Y and Z are vectors of length nlongitude d = length(n); i = find(abs(n)>eps); % find first nonzero component of n % a new basis {e_1,...,e_{i-1},n,e_{i+1},...,e_d}, % where e_i was replaced by n, will still span the whole space IR^d, % since e_i appears in the expansion of n with a nonzero coefficient. if (size(i) == 0) % in this case the normal was near zero... useless! return; end; i = i(1); P = eye(d); % construct permutation matrix that swaps rows 1 and i z = P(:,i); P(:,i) = P(:,1); P(:,1) = z; %line([x0(1);x0(1)+n(1)],[x0(2);x0(2)+n(2)],[x0(3);x0(3)+n(3)]); offset_proj = offset - dot(n,offset) * n; n = P * n; % don't forget to change the representation of our normal! R = zeros(d,d); R(:,1) = n; % "basis vector e_1 will map to n"; replace e_1 (the former e_i) by n. R(2:d,2:d) = eye(d-1); R = gramschmidt(R); % R now contains an orthonormal basis where the first basis vector is n. R = R * P; % permute back: R now contains an orthonormal basis where the ith basis vector is n. t = [0:(2*pi)/nlongitude:2*pi-(1/nlongitude)]; C = zeros(3,nlatitude*nlongitude); % create concentric circles with nlatitude latitude and nlongitude longitude lines k=1; for r = radius:-radius/nlatitude:radius/nlatitude C(:,(k-1)*nlongitude+1:k*nlongitude) = [zeros(1,nlongitude); r*cos(t); r*sin(t)]; k=k+1; end midpoint = x0+offset_proj; %C = R * C + repmat(midpoint,1,nlatitude*nlongitude); C = R * C + midpoint(:, ones(1,nlatitude*nlongitude)); X = [C(1,:)'; midpoint(1)]; Y = [C(2,:)'; midpoint(2)]; Z = [C(3,:)'; midpoint(3)];
github
sheldona/hessianIK-master
resumeAnimation.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/resumeAnimation.m
2,150
utf_8
42f8280c765992e5a383c09d67f18409
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function resumeAnimation(varargin) global VARS_GLOBAL_ANIM if (nargin >1) new_time_stretch_factor = varargin{2}; else new_time_stretch_factor = -1; end if (nargin >0) range = varargin{1}; current_frame = range(1); if(length(range) == 2) last_frame = range(2); else last_frame = VARS_GLOBAL_ANIM.frames_total; end else current_frame = VARS_GLOBAL_ANIM.current_frame; last_frame = VARS_GLOBAL_ANIM.frames_total; end t = timerfind('Name','AnimationTimer'); try if(~isempty(t)) t = t(1); num_frames = last_frame - current_frame +1; set(t,'TasksToExecute',num_frames); VARS_GLOBAL_ANIM.current_frame = current_frame; if(new_time_stretch_factor ~= -1) desired_frame_time = VARS_GLOBAL_ANIM.mot(1).frameTime; period = round(1000*desired_frame_time/new_time_stretch_factor)/1000; VARS_GLOBAL_ANIM.timer_period = period; if (period == 0) warning(['Requested timer period of ' num2str(desired_frame_time/time_stretch_factor) ' s is too short for Matlab! Setting period to minimum of 1 ms :-(']); period = 0.001; end set(t,'Period',period); end start(t); end catch delete(t); return end VARS_GLOBAL_ANIM.animation_paused = false;
github
sheldona/hessianIK-master
animate_sound.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/animate_sound.m
4,499
utf_8
01e75d42c480e6a8ca1ba1846c3f6e77
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function animate_sound(skel,mot,y,fs_audio,varargin) % animate(skel,mot,num_repeats,time_stretch_factor,range,draw_labels) % INPUT: % - skel and mot are assumed to be struct arrays of identical length containing % skeleton/motion pairs to be animated simultaneously. All mots are supposed to have the same samplingRate. % - range is a cell array which is supposed to be of same length as skel/mot. % Empty cell array entries in range indicate that the entire frame range is to be played back. % - draw_labels is a logical vector the same length as skel indicating whether the corresponding skeleton % is to be drawn with a frame counter label. Empty draw_labels means "draw no labels at all". global VARS_GLOBAL_ANIM if (isempty(VARS_GLOBAL_ANIM)) VARS_GLOBAL_ANIM = emptyVarsGlobalAnimStruct; end num_repeats = 1; time_stretch_factor = 1; VARS_GLOBAL_ANIM.range = cell(length(mot),1); VARS_GLOBAL_ANIM.draw_labels = ones(length(mot),1); if (nargin > 8) error('Too many arguments!'); end if (nargin > 7) VARS_GLOBAL_ANIM.draw_labels = varargin{4}; end if (nargin > 6) VARS_GLOBAL_ANIM.range = varargin{3}; if (~iscell(VARS_GLOBAL_ANIM.range)) VARS_GLOBAL_ANIM.range = {VARS_GLOBAL_ANIM.range}; end end if (nargin > 5) time_stretch_factor = varargin{2}; end if (nargin > 4) num_repeats = varargin{1}; end VARS_GLOBAL_ANIM.skel = skel; VARS_GLOBAL_ANIM.mot = mot; num_frames = -inf; for k=1:length(VARS_GLOBAL_ANIM.range) if (isempty(VARS_GLOBAL_ANIM.range{k})) VARS_GLOBAL_ANIM.range{k} = [1:VARS_GLOBAL_ANIM.mot(k).nframes]; end if (length(VARS_GLOBAL_ANIM.range{k})>num_frames) % determine num_frames as maximum of range lengths num_frames = length(VARS_GLOBAL_ANIM.range{k}); end end animate_initGraphics; desired_frame_time = VARS_GLOBAL_ANIM.mot(1).frameTime; if (~isempty(VARS_GLOBAL_ANIM.figure_camera_file)) h = str2func(VARS_GLOBAL_ANIM.figure_camera_file); feval(h, gca); end if (~isempty(VARS_GLOBAL_ANIM.figure_position)) set(gcf,'position',VARS_GLOBAL_ANIM.figure_position); end for (i=1:num_repeats) VARS_GLOBAL_ANIM.frame_draw_time = 0; VARS_GLOBAL_ANIM.frames_drawn = 0; VARS_GLOBAL_ANIM.animation_done = false; t=timerfind('Name','AnimationTimer'); if (~isempty(t)) delete(t); end t = timer('Name','AnimationTimer'); try set(t,'TimerFcn','animate_showFrame'); set(t,'ExecutionMode','fixedRate'); set(t,'TasksToExecute',num_frames); period = round(1000*desired_frame_time/time_stretch_factor)/1000; if (period == 0) warning(['Requested timer period of ' num2str(desired_frame_time/time_stretch_factor) ' s is too short for Matlab! Setting period to minimum of 1 ms :-(']); period = 0.001; end set(t,'Period',period); set(t,'BusyMode','queue'); t1=clock; sound(y,fs_audio); start(t); wait(t); t2=clock; elapsed_time = etime(t2,t1); delete(t); catch delete(t); return end clip_duration = desired_frame_time*num_frames/time_stretch_factor; avg_frame_time = elapsed_time / VARS_GLOBAL_ANIM.frames_drawn; actual_frame_rate = 1/avg_frame_time; target_frame_rate = time_stretch_factor/desired_frame_time; disp(['Frame rate: ' num2str(actual_frame_rate) ' fps, target frame rate was ' num2str(target_frame_rate) ' fps.']); disp(['Clip duration: ' num2str(clip_duration) ' sec. Total frame drawing time: ' num2str(VARS_GLOBAL_ANIM.frame_draw_time) ' sec, ' num2str(100*(target_frame_rate/actual_frame_rate)*VARS_GLOBAL_ANIM.frame_draw_time/clip_duration) ' percent load.']); end
github
sheldona/hessianIK-master
emptyVarsGlobalAnimStruct.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/emptyVarsGlobalAnimStruct.m
3,735
utf_8
4f769d2096aef0f6b1b3368c3a991162
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function s = emptyVarsGlobalAnimStruct s = struct('animation_done',true,... 'range',[],... 'skel',[],... 'mot',[],... 'graphics_data',[],... % struct array with handles to graphics data (planes, lines, etc.) 'graphics_data_index',0,... % index into graphics_data struct array, denoting the currently active figure 'frame_draw_time',0,... 'frames_drawn',0,... 'draw_labels',[],... % boolean array the same size as skel and mot, indicating whether frame counter labels are to be drawn 'figure_position',[],... 'figure_color',[192 192 192]/255,... 'figure_camera_file',[],... 'ground_tile_size_factor',1,... % measures size of ground tiles in multiples of humerus lengths 'bounding_box_border_extension',1,... % how many tiles are to be appended around the ground plane? 'animated_skeleton_Color','black',... 'animated_skeleton_LineWidth',6,... 'animated_skeleton_LineStyle','-',... 'animated_skeleton_Marker','.',... 'animated_skeleton_MarkerSize',36,... 'animated_skeleton_MarkerEdgeColor','red',... 'animated_skeleton_MarkerFaceColor','red',... 'trace_pose_Color','black',... 'trace_pose_LineWidth',2,... 'trace_pose_LineStyle','-',... 'trace_pose_Marker','.',... 'trace_pose_MarkerSize',12,... 'trace_pose_MarkerEdgeColor',[200 200 200]/255,... 'trace_pose_MarkerFaceColor',[200 200 200]/255,... 'animated_point_MarkerSize',20,... 'animated_point_Marker','o',... 'animated_point_MarkerEdgeColor',[0 0 0],... % put RGB row vector here. MarkerFaceColor is user-determined... put empty value if MarkerEdgeColor==MarkerFaceColor is desired 'video_compression','HFYU',... 'video_flip_vert',false,... 'video_flip_horz',false); s.animated_skeleton_Color = 'black'; s.animated_skeleton_LineWidth = 5; s.animated_skeleton_LineStyle= '-'; s.animated_skeleton_Marker= '.'; s.animated_skeleton_MarkerSize= 15; s.animated_skeleton_MarkerEdgeColor= [0.4 0.4 0.4]; s.animated_skeleton_MarkerFaceColor= [0.4 0.4 0.4];
github
sheldona/hessianIK-master
animate_showFrame.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/animate_showFrame.m
6,254
utf_8
559c1de0a69ae55a7b39a19bbdbea997
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function animate_showFrame(varargin) global VARS_GLOBAL_ANIM if (VARS_GLOBAL_ANIM.animation_done) return; end if (nargin>=1) % direct frame draw mode! tasks_executed = varargin{1}; tasks_to_execute = inf; else t = timerfind('Name','AnimationTimer'); if (size(t)==0) return end t = t(1); tasks_executed = get(t,'TasksExecuted'); tasks_to_execute = get(t,'TasksToExecute'); end tic %%%%%%%%%%%%% draw "current_frame" for all skeletons for i = 1:length(VARS_GLOBAL_ANIM.skel) if (tasks_executed > length(VARS_GLOBAL_ANIM.range{i})) % if motion number i need not be animated anymore, skip it! continue; end current_frame = VARS_GLOBAL_ANIM.range{i}(tasks_executed); npaths = size(VARS_GLOBAL_ANIM.skel(i).paths,1); for k = 1:npaths path = VARS_GLOBAL_ANIM.skel(i).paths{k}; nlines = length(path)-1; px = zeros(2,1); py = zeros(2,1); pz = zeros(2,1); px(1) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(1)}(1,current_frame); py(1) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(1)}(2,current_frame); pz(1) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(1)}(3,current_frame); for j = 2:nlines % path number px(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(j)}(1,current_frame); py(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(j)}(2,current_frame); pz(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(j)}(3,current_frame); set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).skel_lines{i}{k}(j-1),'XData',px,'YData',py,'ZData',pz); px(1) = px(2); py(1) = py(2); pz(1) = pz(2); end px(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(nlines+1)}(1,current_frame); py(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(nlines+1)}(2,current_frame); pz(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(nlines+1)}(3,current_frame); set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).skel_lines{i}{k}(nlines),'XData',px,'YData',py,'ZData',pz); end if (isfield(VARS_GLOBAL_ANIM.mot(i),'animated_patch_data')) npatches = length(VARS_GLOBAL_ANIM.mot(i).animated_patch_data); for k=1:npatches X = VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).X(:,current_frame); Y = VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).Y(:,current_frame); Z = VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).Z(:,current_frame); if (size(VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).color,1)==1) %C = repmat(VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).color,size(Z,1),1); C = VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).color(ones(size(Z,1),1),:); else %C = repmat(VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).color(current_frame,:),size(Z,1),1); C = VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).color(current_frame,:) C = C(ones(size(Z,1),1),:); end switch (lower(VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).type)) case 'disc' set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).animated_patches{i}(k),... 'Vertices',[X Y Z],... 'FaceVertexCData',C); case 'polygondisc' set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).animated_patches{i}(k),... 'Vertices',[X Y Z],... 'FaceVertexCData',C); case 'griddisc' set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).animated_patches{i}(k),... 'Vertices',[X Y Z],... 'FaceVertexCData',C); case 'point' if isempty(VARS_GLOBAL_ANIM.animated_point_MarkerEdgeColor) markeredgecolor = C; else %markeredgecolor = repmat(VARS_GLOBAL_ANIM.animated_point_MarkerEdgeColor,size(Z,1),1); markeredgecolor = VARS_GLOBAL_ANIM.animated_point_MarkerEdgeColor(ones(size(Z,1),1),1); end set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).animated_patches{i}(k),... 'Vertices',[X Y Z],... 'MarkerEdgeColor',markeredgecolor,... 'MarkerFaceColor',C); case 'cappedcylinder' set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).animated_patches{i}(k),... 'Vertices',[X Y Z],... 'FaceVertexCData',C); end end end if (~isempty(VARS_GLOBAL_ANIM.draw_labels) && VARS_GLOBAL_ANIM.draw_labels(i)) set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).text_handle(i),'string',sprintf(' Frame %d',current_frame),'position',VARS_GLOBAL_ANIM.mot(i).jointTrajectories{1}(:,current_frame)); end end drawnow; t = toc; VARS_GLOBAL_ANIM.frames_drawn = VARS_GLOBAL_ANIM.frames_drawn + 1; VARS_GLOBAL_ANIM.frame_draw_time = VARS_GLOBAL_ANIM.frame_draw_time + t; if (tasks_executed>=tasks_to_execute) VARS_GLOBAL_ANIM.animation_done = true; end
github
sheldona/hessianIK-master
showTracePoses.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/showTracePoses.m
2,166
utf_8
22106722235c86ca330051e8c0791b28
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function showTracePoses(skel,mot,frames) global VARS_GLOBAL_ANIM if (isempty(VARS_GLOBAL_ANIM)||isempty(VARS_GLOBAL_ANIM.graphics_data)) VARS_GLOBAL_ANIM = emptyVarsGlobalAnimStruct; animate_initGraphics; end f = find(cell2mat({VARS_GLOBAL_ANIM.graphics_data.figure}) == gcf); if (isempty(f)) animate_initGraphics; f = gcf; end VARS_GLOBAL_ANIM.graphics_data_index = f; for k=1:length(frames) VARS_GLOBAL_ANIM.graphics_data(f).trace_poses=... [VARS_GLOBAL_ANIM.graphics_data(f).trace_poses; ... createSkeletonLines({skel,mot},frames(k),... VARS_GLOBAL_ANIM.trace_pose_Color,... VARS_GLOBAL_ANIM.trace_pose_LineWidth,... VARS_GLOBAL_ANIM.trace_pose_LineStyle,... VARS_GLOBAL_ANIM.trace_pose_Marker,... VARS_GLOBAL_ANIM.trace_pose_MarkerSize,... VARS_GLOBAL_ANIM.trace_pose_MarkerEdgeColor,... VARS_GLOBAL_ANIM.trace_pose_MarkerFaceColor)]; % {skel, mot}, frames, color, linewidth, linestyle, marker, markersize, markeredgecolor, markerfacecolor end
github
sheldona/hessianIK-master
params_planePointNormal.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/params_planePointNormal.m
2,782
utf_8
ea22c0084f199090b885985a7baf6db8
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [fixture,n,min_radius] = params_planePointNormal(mot,p1_name,p2_name,p3_name,q_name,d,varargin) % p1 and p2 define the normal of an oriented plane. % p3+offset is the fixture point for the plane. % q is the point that is tested against this plane % d is the offset distance for the plane in the direction of n. % optional argument offset is a 3-vector denoting an offset to be added to the fixture point during min_radius calculation % % function returns sequence of fixture points and unit normals along with % minimum radii that make sense to visualize position of q in relation to the plane. offset = [0;0;0]; if (nargin>6) offset = varargin{1}; end if (ischar(p1_name)) p1 = trajectoryID(mot,p1_name); else p1 = mot.nameMap{p1_name,3}; end if (ischar(p2_name)) p2 = trajectoryID(mot,p2_name); else p2 = mot.nameMap{p2_name,3}; end if (ischar(p3_name)) p3 = trajectoryID(mot,p3_name); else p3 = mot.nameMap{p3_name,3}; end if (ischar(q_name)) q = trajectoryID(mot,q_name); else q = mot.nameMap{q_name,3}; end n = mot.jointTrajectories{p2} - mot.jointTrajectories{p1}; n = n./repmat(sqrt(sum(n.^2)),3,1); % points = mot.jointTrajectories{p3}+n*d; % % fixture = mot.jointTrajectories{p3}+repmat(offset,1,mot.nframes); % dist = dot(n,mot.jointTrajectories{q}-fixture); % q_proj = mot.jointTrajectories{q} - repmat(dist,3,1).*n; % % min_radius = sqrt(sum((fixture-q_proj).^2)); offset = repmat(offset,1,mot.nframes) - repmat(dot(n,repmat(offset,1,mot.nframes)),3,1).*n; %points = mot.jointTrajectories{p1} + n*d; fixture = mot.jointTrajectories{p3}+offset + n*d; dist_q = dot(n,mot.jointTrajectories{q}-fixture); dist_p3 = dot(n,mot.jointTrajectories{p3}-fixture); q_proj = mot.jointTrajectories{q} - repmat(dist_q,3,1).*n; p3_proj = mot.jointTrajectories{p3} - repmat(dist_p3,3,1).*n; radius_q = sqrt(sum((fixture-q_proj).^2)); radius_p3 = sqrt(sum((fixture-p3_proj).^2)); min_radius = max([radius_q; radius_p3]);
github
sheldona/hessianIK-master
new_animate_showFrame.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/new_animate_showFrame.m
7,936
utf_8
54cf87ae23a8624ff5da8c91f5b5f896
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function new_animate_showFrame(obj,event,varargin) global VARS_GLOBAL_ANIM tic; if (VARS_GLOBAL_ANIM.animation_done) toc; return; end if (nargin>3) % direct frame draw mode! current_frame = varargin{2}; VARS_GLOBAL_ANIM.current_frame = current_frame; frames_total = inf; else current_frame = VARS_GLOBAL_ANIM.current_frame; frames_total = VARS_GLOBAL_ANIM.frames_total; end if (nargin>2) observer_fcn = varargin{1}; else observer_fcn = {}; end if (current_frame>=frames_total) t = timerfind('Name','AnimationTimer'); if (~isempty(t)) if(VARS_GLOBAL_ANIM.kill_timer) delete(t); VARS_GLOBAL_ANIM.animation_done = true; avg_frame_time = VARS_GLOBAL_ANIM.frame_draw_time / VARS_GLOBAL_ANIM.frames_drawn; actual_frame_rate = 1/avg_frame_time; disp(['Frame rate: ' num2str(actual_frame_rate) ' fps.']); disp(['Total frame drawing time: ' num2str(VARS_GLOBAL_ANIM.frame_draw_time) ' sec.']); else stop(t); VARS_GLOBAL_ANIM.animation_paused = true; end end if(VARS_GLOBAL_ANIM.loop_playback) current_frame = 1; VARS_GLOBAL_ANIM.current_frame = 1; VARS_GLOBAL_ANIM.animation_paused = false; set(t,'TasksToExecute', VARS_GLOBAL_ANIM.frames_total+1); start(t); end end %if (current_frame>frames_total) % disp('Error: Timer sent too many calls to animate_showFrame!'); % return; %end if(~isempty(observer_fcn)) feval(observer_fcn{1},VARS_GLOBAL_ANIM.current_frame,observer_fcn{2:end}); end % drop frames if more than 30 fps elapsed = etime(clock,VARS_GLOBAL_ANIM.previous_call); if (elapsed < 1/30 && current_frame ~= frames_total) VARS_GLOBAL_ANIM.current_frame = current_frame + 1; t2 = toc; VARS_GLOBAL_ANIM.frame_draw_time = VARS_GLOBAL_ANIM.frame_draw_time + t2; return; end %%%%%%%%%%%%% draw "current_frame" for all skeletons for i = 1:length(VARS_GLOBAL_ANIM.skel) if (current_frame > length(VARS_GLOBAL_ANIM.range{i})) % if motion number i need not be animated anymore, skip it! continue; end % delay beginning of motion for a short period of time %current_frame = max(1,current_frame - 19); current_frame_in_mot = VARS_GLOBAL_ANIM.range{i}(current_frame); set(VARS_GLOBAL_ANIM.graphics_data.frameLabel, 'String', ['frame ' int2str(current_frame_in_mot)]); npaths = size(VARS_GLOBAL_ANIM.skel(i).paths,1); for k = 1:npaths path = VARS_GLOBAL_ANIM.skel(i).paths{k}; nlines = length(path)-1; px = zeros(2,1); py = zeros(2,1); pz = zeros(2,1); px(1) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(1)}(1,current_frame_in_mot); py(1) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(1)}(2,current_frame_in_mot); pz(1) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(1)}(3,current_frame_in_mot); for j = 2:nlines % path number px(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(j)}(1,current_frame_in_mot); py(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(j)}(2,current_frame_in_mot); pz(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(j)}(3,current_frame_in_mot); set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).skel_lines{i}{k}(j-1),'XData',px,'YData',py,'ZData',pz); px(1) = px(2); py(1) = py(2); pz(1) = pz(2); end px(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(nlines+1)}(1,current_frame_in_mot); py(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(nlines+1)}(2,current_frame_in_mot); pz(2) = VARS_GLOBAL_ANIM.mot(i).jointTrajectories{path(nlines+1)}(3,current_frame_in_mot); set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).skel_lines{i}{k}(nlines),'XData',px,'YData',py,'ZData',pz); end if (isfield(VARS_GLOBAL_ANIM.mot(i),'animated_patch_data')) npatches = length(VARS_GLOBAL_ANIM.mot(i).animated_patch_data); for k=1:npatches X = VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).X(:,current_frame_in_mot); Y = VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).Y(:,current_frame_in_mot); Z = VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).Z(:,current_frame_in_mot); if (size(VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).color,1)==1) %C = repmat(VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).color,size(Z,1),1); C = VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).color(ones(size(Z,1),1),:); else C = repmat(VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).color(current_frame_in_mot,:),size(Z,1),1); end switch (lower(VARS_GLOBAL_ANIM.mot(i).animated_patch_data(k).type)) case 'disc' set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).animated_patches{i}(k),... 'Vertices',[X Y Z],... 'FaceVertexCData',C); case 'polygondisc' set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).animated_patches{i}(k),... 'Vertices',[X Y Z],... 'FaceVertexCData',C); case 'griddisc' set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).animated_patches{i}(k),... 'Vertices',[X Y Z],... 'FaceVertexCData',C); case 'point' if isempty(VARS_GLOBAL_ANIM.animated_point_MarkerEdgeColor) markeredgecolor = C; else markeredgecolor = repmat(VARS_GLOBAL_ANIM.animated_point_MarkerEdgeColor,size(Z,1),1); end set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).animated_patches{i}(k),... 'Vertices',[X Y Z],... 'MarkerEdgeColor',markeredgecolor,... 'MarkerFaceColor',C); case 'cappedcylinder' set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).animated_patches{i}(k),... 'Vertices',[X Y Z],... 'FaceVertexCData',C); end end end if (~isempty(VARS_GLOBAL_ANIM.draw_labels) && VARS_GLOBAL_ANIM.draw_labels(i)) set(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).text_handle(i),'string',sprintf(' Frame %d',current_frame),'position',VARS_GLOBAL_ANIM.mot(i).jointTrajectories{1}(:,current_frame_in_mot)); end end drawnow; t2 = toc; VARS_GLOBAL_ANIM.frames_drawn = VARS_GLOBAL_ANIM.frames_drawn + 1; VARS_GLOBAL_ANIM.frame_draw_time = VARS_GLOBAL_ANIM.frame_draw_time + t2; VARS_GLOBAL_ANIM.current_frame = current_frame + 1; VARS_GLOBAL_ANIM.previous_call = clock;
github
sheldona/hessianIK-master
new_animate_initGraphics.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/new_animate_initGraphics.m
8,957
utf_8
98c0162f25275bc385e84a3284063b25
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function new_animate_initGraphics global VARS_GLOBAL_ANIM VARS_GLOBAL_ANIM.loop_playback = 1; bb = [inf -inf inf -inf inf -inf]'; ground_tile_size = -inf; for k = 1:length(VARS_GLOBAL_ANIM.mot) bb([2 4 6]) = max(bb([2 4 6]), VARS_GLOBAL_ANIM.mot(k).boundingBox([2 4 6])); bb([1 3 5]) = min(bb([1 3 5]), VARS_GLOBAL_ANIM.mot(k).boundingBox([1 3 5])); lclavicleIdx = strMatch('lshoulder', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}, 'exact'); if(isempty(lclavicleIdx)) lclavicleIdx = strMatch('LSHO', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}, 'exact'); if(isempty(lclavicleIdx)) lclavicleIdx = strMatch('lsho', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}, 'exact'); end end if isempty(lclavicleIdx) warning('Could not find the clavicle in the nameMap. Using default size 10 [?] of the ground plane grid.'); x=10; else lclavicleIdx = VARS_GLOBAL_ANIM.skel(1).nameMap{lclavicleIdx, 3}; lelbowIdx = strMatch('lelbow', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}); if(isempty(lelbowIdx)) lelbowIdx = strMatch('LELB', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}, 'exact'); if(isempty(lelbowIdx)) lelbowIdx = strMatch('lelb', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}, 'exact'); end end lelbowIdx = VARS_GLOBAL_ANIM.skel(1).nameMap{lelbowIdx, 3}; x = VARS_GLOBAL_ANIM.ground_tile_size_factor*sqrt(sum((VARS_GLOBAL_ANIM.mot(1).jointTrajectories{lclavicleIdx}(:,1)-VARS_GLOBAL_ANIM.mot(1).jointTrajectories{lelbowIdx}(:,1)).^2)); end % x = VARS_GLOBAL_ANIM.ground_tile_size_factor*VARS_GLOBAL_ANIM.skel(1).nodes(VARS_GLOBAL_ANIM.skel(1).nameMap{16,2}).length; % ground tile size will be a multiple of the length of longest lhumerus (DOF id 16) if (x>ground_tile_size) ground_tile_size = x; end end if (sum(isinf(bb)>0)) ground_tile_size = 1; bb_extension = zeros(6,1); bb = [-1 1 0 1 -1 1]'; else bb_extension = [-1 1 0 1 -1 1]'*VARS_GLOBAL_ANIM.bounding_box_border_extension*ground_tile_size; bb = bb + bb_extension; end %nground_tiles = 10; %ground_tile_size = min(bb(2) - bb(1), bb(6) - bb(5)) / nground_tiles; create_new = false; if (~isempty(VARS_GLOBAL_ANIM.graphics_data)) % eliminate invalid figure handles valid_figure_handle_indices = find(ishandle(cell2mat({VARS_GLOBAL_ANIM.graphics_data.figure}))); VARS_GLOBAL_ANIM.graphics_data = VARS_GLOBAL_ANIM.graphics_data(valid_figure_handle_indices); view_curr = view(gca); % newplot; current_figure = gcf; % find current figure in graphics_data VARS_GLOBAL_ANIM.graphics_data_index = find(cell2mat({VARS_GLOBAL_ANIM.graphics_data.figure}) == current_figure); if (isempty(VARS_GLOBAL_ANIM.graphics_data_index)) % current figure hasn't been used for our skeleton graphics output previously create_new = true; VARS_GLOBAL_ANIM.graphics_data_index = length(VARS_GLOBAL_ANIM.graphics_data)+1; % create new entry in graphics_data array VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index) = struct('figure',current_figure,... 'skel_lines',cell(1,1),... 'animated_patches',cell(1,1),... 'ground_plane',0,... 'text_handle',0,... 'view',[],... 'trace_poses',[]); end else % graphics_data IS empty! create_new = true; view_curr = view(gca); % newplot; current_figure = gcf; VARS_GLOBAL_ANIM.graphics_data = struct('figure',current_figure,... 'skel_lines',cell(1,1),... 'animated_patches',cell(1,1),... 'ground_plane',0,... 'text_handle',0,... 'view',[],... 'trace_poses',[]); VARS_GLOBAL_ANIM.graphics_data_index = 1; end i = VARS_GLOBAL_ANIM.graphics_data_index; if (~create_new) delete(VARS_GLOBAL_ANIM.graphics_data(i).ground_plane(find(ishandle(VARS_GLOBAL_ANIM.graphics_data(i).ground_plane)))); VARS_GLOBAL_ANIM.graphics_data(i).ground_plane = []; delete(VARS_GLOBAL_ANIM.graphics_data(i).text_handle(find(ishandle(VARS_GLOBAL_ANIM.graphics_data(i).text_handle) & (VARS_GLOBAL_ANIM.graphics_data(i).text_handle > 0)))); VARS_GLOBAL_ANIM.graphics_data(i).text_handle = []; for k=1:length(VARS_GLOBAL_ANIM.graphics_data(i).skel_lines) if (~isempty(VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k})) for j = 1:size(VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k},1) delete(VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k}{j}(find(ishandle(VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k}{j})))); VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k}{j} = []; end end end for k=1:length(VARS_GLOBAL_ANIM.graphics_data(i).animated_patches) if (~isempty(VARS_GLOBAL_ANIM.graphics_data(i).animated_patches{k})) delete(VARS_GLOBAL_ANIM.graphics_data(i).animated_patches{k}(find(ishandle(VARS_GLOBAL_ANIM.graphics_data(i).animated_patches{k})))); VARS_GLOBAL_ANIM.graphics_data(i).animated_patches{k} = []; end end end reset(gca); if (isempty(VARS_GLOBAL_ANIM.graphics_data(i).view)) VARS_GLOBAL_ANIM.graphics_data(i).view = [-0.9129 0.0000 1.7180 -0.4026;... 0.0461 1.6227 0.4335 -1.0511;... 0.4056 -0.1843 3.8170 21.0978;... 0 0 0 1.0000]; else VARS_GLOBAL_ANIM.graphics_data(i).view = view_curr; end hld=ishold; set(gcf,'NextPlot','add'); set(gca,'NextPlot','add'); %%%%%%%%%%% create ground plane %bb([1 2 5 6],:) = bb([1 2 5 6],:)*10; %ground_tile_size=ground_tile_size*10; VARS_GLOBAL_ANIM.graphics_data(i).ground_plane = createGroundPlane(bb,bb_extension,ground_tile_size); for k=1:length(VARS_GLOBAL_ANIM.skel) %%%%%%%%%%% create text fields for frame number if (~isempty(VARS_GLOBAL_ANIM.draw_labels) && VARS_GLOBAL_ANIM.draw_labels(k)) VARS_GLOBAL_ANIM.graphics_data(i).text_handle(k) = text(0,0,0,''); set(VARS_GLOBAL_ANIM.graphics_data(i).text_handle(k),'interpreter','none'); end %%%%%%%%%%% create lines for skeleton visualization range = VARS_GLOBAL_ANIM.range{k}; current_frame = range(1); VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k,1} = createSkeletonLines(k,current_frame); %%%%%%%%%%% create patches for animated plane/cylinder/sphere/etc visualization if (isfield(VARS_GLOBAL_ANIM.mot(k),'animated_patch_data')) VARS_GLOBAL_ANIM.graphics_data(i).animated_patches{k,1} = createAnimatedPatches(k,current_frame); end end if (~hld) %set(gcf,'NextPlot','replace'); set(gca,'NextPlot','replace'); end figure(VARS_GLOBAL_ANIM.graphics_data(i).figure); set(gcf,'renderer','OpenGL','DoubleBuffer','on'); %set(gcf,'Color','w'); set(gcf,'Color',VARS_GLOBAL_ANIM.figure_color); % set(gca,'Color','w',... % 'XColor','w',... % 'YColor','w',... % 'ZColor','w'); set(gca,'visible','off'); axis equal; axis(bb+[-1 1 -1 1 -1 1]'*ground_tile_size); camup([0 1 0]); %view(VARS_GLOBAL_ANIM.graphics_data(i).view); camproj('perspective'); camlight headlight; light; %set(gcf,'position',[5 5 512 284]); %set(gca,'Units','centimeter') %camva('auto'); %camva('manual');
github
sheldona/hessianIK-master
createSkeletonLines.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/createSkeletonLines.m
3,310
utf_8
81475446626b2907be67cac6c5a709b9
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function skel_lines = createSkeletonLines(skel_ind,current_frame,varargin) global VARS_GLOBAL_ANIM if (~iscell(skel_ind)) skel = VARS_GLOBAL_ANIM.skel(skel_ind); mot = VARS_GLOBAL_ANIM.mot(skel_ind); else skel = skel_ind{1}; mot = skel_ind{2}; end color = VARS_GLOBAL_ANIM.animated_skeleton_Color; linewidth = VARS_GLOBAL_ANIM.animated_skeleton_LineWidth; linestyle = VARS_GLOBAL_ANIM.animated_skeleton_LineStyle; marker = VARS_GLOBAL_ANIM.animated_skeleton_Marker; markersize = VARS_GLOBAL_ANIM.animated_skeleton_MarkerSize; markeredgecolor = VARS_GLOBAL_ANIM.animated_skeleton_MarkerEdgeColor; markerfacecolor = VARS_GLOBAL_ANIM.animated_skeleton_MarkerFaceColor; % color, linewidth, linestyle, marker, markersize, markeredgecolor, markerfacecolor if (nargin>8) markerfacecolor = varargin{9-2}; end if (nargin>7) markeredgecolor = varargin{8-2}; end if (nargin>6) markersize = varargin{7-2}; end if (nargin>5) marker = varargin{6-2}; end if (nargin>4) linestyle = varargin{5-2}; end if (nargin>3) linewidth = varargin{4-2}; end if (nargin>2) color = varargin{3-2}; end %%%%%%%%%%% clear skel_lines if necessary npaths = size(skel.paths,1); skel_lines = cell(npaths,1); for k = 1:npaths path = skel.paths{k}; nlines = length(path)-1; px = zeros(2,1); py = zeros(2,1); pz = zeros(2,1); px(1) = mot.jointTrajectories{path(1)}(1,current_frame); py(1) = mot.jointTrajectories{path(1)}(2,current_frame); pz(1) = mot.jointTrajectories{path(1)}(3,current_frame); for j = 2:nlines % path number px(2) = mot.jointTrajectories{path(j)}(1,current_frame); py(2) = mot.jointTrajectories{path(j)}(2,current_frame); pz(2) = mot.jointTrajectories{path(j)}(3,current_frame); skel_lines{k}(j-1) = line(px,py,pz,'Color',color,'LineWidth',linewidth,'linestyle',linestyle,'Parent',gca,'marker',marker,'markersize',markersize,'markeredgecolor',markeredgecolor,'markerfacecolor',markerfacecolor); px(1) = px(2); py(1) = py(2); pz(1) = pz(2); end px(2) = mot.jointTrajectories{path(nlines+1)}(1,current_frame); py(2) = mot.jointTrajectories{path(nlines+1)}(2,current_frame); pz(2) = mot.jointTrajectories{path(nlines+1)}(3,current_frame); skel_lines{k}(nlines) = line(px,py,pz,'Color',color,'LineWidth',linewidth,'linestyle',linestyle,'Parent',gca,'marker',marker,'markersize',markersize,'markeredgecolor',markeredgecolor,'markerfacecolor',markerfacecolor); end
github
sheldona/hessianIK-master
addAnimatedPatches.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/addAnimatedPatches.m
1,890
utf_8
18c8bb64181343ef5a4cab9f8ca774a8
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function mot = addAnimatedPatches(mot,function_name,function_params,varargin) % mot,function_name,function_params,type,color,alpha,overwrite) type = cell(length(function_name),1); color = cell(length(function_name),1); alpha = zeros(length(function_name),1); overwrite = false; for k=1:length(function_name) type{k} = 'disc'; color{k} = 'blue'; alpha(k) = 1; end if (nargin>6) overwrite = varargin{4}; end if (nargin>5) alpha = varargin{3}; end if (nargin>4) color = varargin{2}; end if (nargin>3) type = varargin{1}; end if (overwrite | ~isfield(mot,'animated_patch_data')) mot.animated_patch_data = animatedPatchStruct(length(function_name)); k0 = 0; else k0 = length(mot.animated_patch_data); end for k = k0+1:k0+length(function_name) mot.animated_patch_data(k).function_name = function_name{k-k0}; mot.animated_patch_data(k).function_params = function_params{k-k0}; mot.animated_patch_data(k).type = type{k-k0}; mot.animated_patch_data(k).color = color{k-k0}; mot.animated_patch_data(k).alpha = alpha(k-k0); end
github
sheldona/hessianIK-master
animatedPatchStruct.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/animatedPatchStruct.m
1,159
utf_8
c015eeaf7e0b0c68bfc3831e5392eb8c
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function s = animatedPatchStruct(varargin) n = 1; if (nargin>0) n = varargin{1}; end s = struct('function_name',cell(n,1),... 'function_params',cell(n,1),... 'color','blue',... 'alpha',1,... 'nsteps',64,... 'type','disc',... 'X',[],... 'Y',[],... 'Z',[]);
github
sheldona/hessianIK-master
updateAnimationSlider.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/updateAnimationSlider.m
1,053
utf_8
a26b08cbee39ea5f869d6928c9c46ba4
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function updateAnimationSlider(current_frame,slider_handle); minimum = get(slider_handle, 'Min'); maximum = get(slider_handle, 'Max'); if (current_frame>=minimum & current_frame<=maximum) set(slider_handle, 'Value', current_frame); end
github
sheldona/hessianIK-master
createAnimatedPatches.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/createAnimatedPatches.m
15,395
utf_8
7eeb9dd84191ba1db207f0a95d3b56cf
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function patches = createAnimatedPatches(k,current_frame,varargin) global VARS_GLOBAL_ANIM patches = []; for j=1:length(VARS_GLOBAL_ANIM.mot(k).animated_patch_data) function_handle = str2func(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).function_name); switch (lower(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).type)) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'disc' function_params = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).function_params; [points,normals,min_radius] = feval(function_handle,... VARS_GLOBAL_ANIM.mot(k),... function_params{:}); %% if (length(function_params)>=6) offset = function_params{6}; else offset = [0;0;0]; end npoints = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).nsteps + 1; X = zeros(npoints,VARS_GLOBAL_ANIM.mot(k).nframes); Y = zeros(npoints,VARS_GLOBAL_ANIM.mot(k).nframes); Z = zeros(npoints,VARS_GLOBAL_ANIM.mot(k).nframes); for i=1:VARS_GLOBAL_ANIM.mot(k).nframes [X(1:npoints,i),Y(1:npoints,i),Z(1:npoints,i)] = coordsDiscNormal(normals(:,i), points(:,i), 1.1*min_radius(i), VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).nsteps, offset); end % X(npoints+1,:) = points(1,:)+offset(1); % Y(npoints+1,:) = points(2,:)+offset(2); % Z(npoints+1,:) = points(3,:)+offset(3); VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).X = X; VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).Y = Y; VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).Z = Z; if (isempty(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color)) VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color = [0 0 0]; end if (size(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color,1)==1) C = repmat(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color,size(Z,1),1); else C = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color; end faces = [npoints*ones(npoints-1,1) [1:npoints-1]' mod([1:npoints-1],npoints-1)'+1]; h = patch('Vertices',[X(:,current_frame) Y(:,current_frame) Z(:,current_frame)],... 'Faces',faces,... 'FaceVertexCData',C,... 'FaceColor','flat',... 'EdgeColor','none',... 'FaceLighting','none'); alpha(h,VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).alpha); patches = [patches h]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'polygondisc' function_params = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).function_params; [points,normals,min_radius] = feval(function_handle,... VARS_GLOBAL_ANIM.mot(k),... function_params{:}); %% if (length(function_params)>=6) offset = function_params{6}; else offset = [0;0;0]; end npoints = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).nsteps + 1; X = zeros(npoints,VARS_GLOBAL_ANIM.mot(k).nframes); Y = zeros(npoints,VARS_GLOBAL_ANIM.mot(k).nframes); Z = zeros(npoints,VARS_GLOBAL_ANIM.mot(k).nframes); for i=1:VARS_GLOBAL_ANIM.mot(k).nframes [X(1:npoints,i),Y(1:npoints,i),Z(1:npoints,i)] = coordsDiscNormal(normals(:,i), points(:,i), 1.1*min_radius(i), VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).nsteps, offset); end X = X(1:npoints-1,:); % get rid of midpoint Y = Y(1:npoints-1,:); Z = Z(1:npoints-1,:); VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).X = X; VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).Y = Y; VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).Z = Z; if (isempty(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color)) VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color = [0 0 0]; end if (size(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color,1)==1) C = repmat(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color,size(Z,1),1); else C = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color; end faces = [1:npoints-1]; h = patch('Vertices',[X(:,current_frame) Y(:,current_frame) Z(:,current_frame)],... 'Faces',faces,... 'FaceVertexCData',C,... 'FaceColor','flat',... 'EdgeColor','none',... 'FaceLighting','none'); alpha(h,VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).alpha); patches = [patches h]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'griddisc' function_params = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).function_params; [points,normals,min_radius] = feval(function_handle,... VARS_GLOBAL_ANIM.mot(k),... function_params{:}); %% if (length(function_params)>=6) offset = function_params{6}; else offset = [0;0;0]; end nsteps = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).nsteps; nlatitude = ceil(nsteps/2); npoints = nlatitude*nsteps+1; X = zeros(npoints,VARS_GLOBAL_ANIM.mot(k).nframes); Y = zeros(npoints,VARS_GLOBAL_ANIM.mot(k).nframes); Z = zeros(npoints,VARS_GLOBAL_ANIM.mot(k).nframes); for i=1:VARS_GLOBAL_ANIM.mot(k).nframes [X(1:npoints,i),Y(1:npoints,i),Z(1:npoints,i)] = coordsGridDiscNormal(normals(:,i), points(:,i), 1.1*min_radius(i), nsteps, nlatitude, offset); end VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).X = X; VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).Y = Y; VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).Z = Z; if (isempty(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color)) VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color = [0 0 0]; end if (size(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color,1)==1) C = repmat(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color,size(Z,1),1); else C = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color; end faces = zeros(nsteps*nlatitude,4); W = [[1:nsteps]' circshift([1:nsteps]',-1) circshift([nsteps+1:2*nsteps]',-1) [nsteps+1:2*nsteps]']; o = 1; for i=1:nlatitude-1 faces(o:o+nsteps-1,:) = W + (i-1)*nsteps; o = o + nsteps; end faces(o:o+nsteps-1,:) = [[(nlatitude-1)*nsteps+1:nlatitude*nsteps]' circshift([(nlatitude-1)*nsteps+1:nlatitude*nsteps]',-1) (nsteps*nlatitude+1)*ones(nsteps,1) [(nlatitude-1)*nsteps+1:nlatitude*nsteps]']; h = patch('Vertices',[X(:,current_frame) Y(:,current_frame) Z(:,current_frame)],... 'Faces',faces,... 'FaceVertexCData',C,... 'FaceColor','flat',... 'EdgeColor','none',... 'FaceLighting','none'); alpha(h,VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).alpha); patches = [patches h]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'point' points = feval(function_handle,... VARS_GLOBAL_ANIM.mot(k),... VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).function_params{:}); X = points(1,:); Y = points(2,:); Z = points(3,:); VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).X = X; VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).Y = Y; VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).Z = Z; if (isempty(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color)) VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color = [0 0 0]; end if (size(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color,1)==1) C = repmat(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color,size(Z,1),1); else C = repmat(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color(current_frame,:),size(Z,1),1); end if isempty(VARS_GLOBAL_ANIM.animated_point_MarkerEdgeColor) markeredgecolor = C; else markeredgecolor = repmat(VARS_GLOBAL_ANIM.animated_point_MarkerEdgeColor,size(Z,1),1); end faces = [1]; h = patch('Vertices',[X(:,current_frame) Y(:,current_frame) Z(:,current_frame)],... 'Faces',faces,... 'MarkerEdgeColor',markeredgecolor,... 'MarkerFaceColor',C,... 'Marker',VARS_GLOBAL_ANIM.animated_point_Marker,... 'MarkerSize',VARS_GLOBAL_ANIM.animated_point_MarkerSize); alpha(h,VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).alpha); patches = [patches h]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'cappedcylinder' [points1,points2] = feval(function_handle,... VARS_GLOBAL_ANIM.mot(k),... VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).function_params{:}); if (length(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).function_params)>=4) use_caps = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).function_params{4}; else use_caps = [true true]; end if (length(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).function_params)>=3) epsilon = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).function_params{3}; else error('Expected epsilon parameter.'); end nsteps = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).nsteps; nlatitude = ceil(nsteps/2); npoints = 2*(nsteps + (nlatitude-1)*nsteps+1); for i=1:VARS_GLOBAL_ANIM.mot(k).nframes [X(:,i),Y(:,i),Z(:,i)] = coordsCappedCylinder(points1(:,i), points2(:,i), epsilon, nsteps, use_caps); end VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).X = X; VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).Y = Y; VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).Z = Z; if (isempty(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color)) VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color = [0 0 0]; end if (size(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color,1)==1) C = repmat(VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color,size(Z,1),1); else C = VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).color; end faces = zeros(nsteps*(1+2*nlatitude),4); faces(1:nsteps,:) = [[1:nsteps]' [nsteps*nlatitude+2:nsteps*(1+nlatitude)+1]' circshift([nsteps*nlatitude+2:nsteps*(1+nlatitude)+1]',-1) circshift([1:nsteps]',-1)]; W = [[1:nsteps]' circshift([1:nsteps]',-1) circshift([nsteps+1:2*nsteps]',-1) [nsteps+1:2*nsteps]']; o = nsteps+1; for i=1:nlatitude-1 faces(o:o+nsteps-1,:) = W + (i-1)*nsteps; o = o + nsteps; end faces(o:o+nsteps-1,:) = [[(nlatitude-1)*nsteps+1:nlatitude*nsteps]' circshift([(nlatitude-1)*nsteps+1:nlatitude*nsteps]',-1) (nsteps*nlatitude+1)*ones(nsteps,1) [(nlatitude-1)*nsteps+1:nlatitude*nsteps]']; o = o + nsteps; W = fliplr(W); % to get the normals pointing outwards for i=1:nlatitude-1 faces(o:o+nsteps-1,:) = W + (i-1)*nsteps + nsteps*nlatitude+1; o = o + nsteps; end faces(o:o+nsteps-1,:) = fliplr([[(nlatitude-1)*nsteps+ nsteps*nlatitude+2:nlatitude*nsteps+ nsteps*nlatitude+1]' circshift([(nlatitude-1)*nsteps+ nsteps*nlatitude+2:nlatitude*nsteps+ nsteps*nlatitude+1]',-1) npoints*ones(nsteps,1) [(nlatitude-1)*nsteps+ nsteps*nlatitude+2:nlatitude*nsteps+ nsteps*nlatitude+1]']); o = o + nsteps; h = patch('Vertices',[X(:,current_frame) Y(:,current_frame) Z(:,current_frame)],... 'Faces',faces,... 'FaceVertexCData',C,... 'FaceColor','flat',... 'EdgeColor','none',... 'FaceLighting','Phong'); alpha(h,VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).alpha); patches = [patches h]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% otherwise warning(['Unknown patch type ' VARS_GLOBAL_ANIM.mot(k).animated_patch_data(j).type]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end end
github
sheldona/hessianIK-master
showTrajectory.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/showTrajectory.m
1,785
utf_8
eb709c8dee65d22c7c903f044f51bb29
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function handle = showTrajectory(varargin) % showTrajectory(mot,trajname,linestyle,downsampling_fac) switch (nargin) case 2 mot = varargin{1}; trajname = varargin{2}; linestyle = 'red o'; downsampling_fac = 1; case 3 mot = varargin{1}; trajname = varargin{2}; linestyle = varargin{3}; downsampling_fac = 1; case 4 mot = varargin{1}; trajname = varargin{2}; linestyle = varargin{3}; downsampling_fac = varargin{4}; otherwise error('Wrong number of arguments!'); end if (ischar(trajname)) ID = trajectoryID(mot,trajname); elseif (isnum(trajname)) ID = trajname; else error('Expected trajectory name or numeric trajectory ID!'); end if (~ishold) hold; end handle = plot3(mot.jointTrajectories{ID}(1,1:downsampling_fac:end),mot.jointTrajectories{ID}(2,1:downsampling_fac:end),mot.jointTrajectories{ID}(3,1:downsampling_fac:end),linestyle);
github
sheldona/hessianIK-master
animate_initGraphics.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/animate_initGraphics.m
9,209
utf_8
cd70562b00aa2a26dee089385ac74678
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function animate_initGraphics global VARS_GLOBAL_ANIM bb = [inf -inf inf -inf inf -inf]'; ground_tile_size = -inf; for k = 1:length(VARS_GLOBAL_ANIM.mot) bb([2 4 6]) = max(bb([2 4 6]), VARS_GLOBAL_ANIM.mot(k).boundingBox([2 4 6])); bb([1 3 5]) = min(bb([1 3 5]), VARS_GLOBAL_ANIM.mot(k).boundingBox([1 3 5])); lclavicleIdx = strmatch('lshoulder', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}, 'exact'); if(isempty(lclavicleIdx)) lclavicleIdx = strmatch('LSHO', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}, 'exact'); if(isempty(lclavicleIdx)) lclavicleIdx = strmatch('lsho', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}, 'exact'); end end if isempty(lclavicleIdx) warning('Could not find the clavicle in the nameMap. Using default size 10 [?] of the ground plane grid.'); x=10; else lclavicleIdx = VARS_GLOBAL_ANIM.skel(1).nameMap{lclavicleIdx, 3}; lelbowIdx = strmatch('lelbow', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}); if(isempty(lelbowIdx)) lelbowIdx = strmatch('LELB', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}, 'exact'); if(isempty(lelbowIdx)) lelbowIdx = strmatch('lelb', {VARS_GLOBAL_ANIM.skel(1).nameMap{:,1}}, 'exact'); end end lelbowIdx = VARS_GLOBAL_ANIM.skel(1).nameMap{lelbowIdx, 3}; x = VARS_GLOBAL_ANIM.ground_tile_size_factor*sqrt(sum((VARS_GLOBAL_ANIM.mot(1).jointTrajectories{lclavicleIdx}(:,1)-VARS_GLOBAL_ANIM.mot(1).jointTrajectories{lelbowIdx}(:,1)).^2)); end %x = VARS_GLOBAL_ANIM.ground_tile_size_factor*VARS_GLOBAL_ANIM.skel(1).nodes(VARS_GLOBAL_ANIM.skel(1).nameMap{16,2}).length; % ground tile size will be a multiple of the length of longest lhumerus (DOF id 16) if (x>ground_tile_size) ground_tile_size = x; end end if (sum(isinf(bb)>0)) ground_tile_size = 1; bb_extension = zeros(6,1); bb = [-1 1 0 1 -1 1]'; else bb_extension = [-1 1 0 1 -1 1]'*VARS_GLOBAL_ANIM.bounding_box_border_extension*ground_tile_size; bb = bb + bb_extension; end %nground_tiles = 10; %ground_tile_size = min(bb(2) - bb(1), bb(6) - bb(5)) / nground_tiles; create_new = false; if (~isempty(VARS_GLOBAL_ANIM.graphics_data)) % eliminate invalid figure handles valid_figure_handle_indices = find(ishandle(cell2mat({VARS_GLOBAL_ANIM.graphics_data.figure}))); VARS_GLOBAL_ANIM.graphics_data = VARS_GLOBAL_ANIM.graphics_data(valid_figure_handle_indices); view_curr = view(gca); % newplot; current_figure = gcf; % find current figure in graphics_data VARS_GLOBAL_ANIM.graphics_data_index = find(cell2mat({VARS_GLOBAL_ANIM.graphics_data.figure}) == current_figure); if (isempty(VARS_GLOBAL_ANIM.graphics_data_index)) % current figure hasn't been used for our skeleton graphics output previously create_new = true; VARS_GLOBAL_ANIM.graphics_data_index = length(VARS_GLOBAL_ANIM.graphics_data)+1; % create new entry in graphics_data array VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index) = struct('figure',current_figure,... 'skel_lines',cell(1,1),... 'animated_patches',cell(1,1),... 'ground_plane',0,... 'text_handle',0,... 'view',[],... 'trace_poses',[]); end else % graphics_data IS empty! create_new = true; view_curr = view(gca); % newplot; current_figure = gcf; VARS_GLOBAL_ANIM.graphics_data = struct('figure',current_figure,... 'skel_lines',cell(1,1),... 'animated_patches',cell(1,1),... 'ground_plane',-1,... 'text_handle',-1,... 'view',[],... 'trace_poses',[]); VARS_GLOBAL_ANIM.graphics_data_index = 1; end i = VARS_GLOBAL_ANIM.graphics_data_index; if (~create_new) delete(VARS_GLOBAL_ANIM.graphics_data(i).ground_plane(find(ishandle(VARS_GLOBAL_ANIM.graphics_data(i).ground_plane)))); VARS_GLOBAL_ANIM.graphics_data(i).ground_plane = []; delete(VARS_GLOBAL_ANIM.graphics_data(i).text_handle(find(ishandle(VARS_GLOBAL_ANIM.graphics_data(i).text_handle) & (VARS_GLOBAL_ANIM.graphics_data(i).text_handle > 0)))); VARS_GLOBAL_ANIM.graphics_data(i).text_handle = []; for k=1:length(VARS_GLOBAL_ANIM.graphics_data(i).skel_lines) if (~isempty(VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k})) for j = 1:size(VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k},1) delete(VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k}{j}(find(ishandle(VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k}{j})))); VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k}{j} = []; end end end for k=1:length(VARS_GLOBAL_ANIM.graphics_data(i).animated_patches) if (~isempty(VARS_GLOBAL_ANIM.graphics_data(i).animated_patches{k})) delete(VARS_GLOBAL_ANIM.graphics_data(i).animated_patches{k}(find(ishandle(VARS_GLOBAL_ANIM.graphics_data(i).animated_patches{k})))); VARS_GLOBAL_ANIM.graphics_data(i).animated_patches{k} = []; end end end reset(gca); if (isempty(VARS_GLOBAL_ANIM.graphics_data(i).view)) VARS_GLOBAL_ANIM.graphics_data(i).view = [-0.9129 0.0000 1.7180 -0.4026;... 0.0461 1.6227 0.4335 -1.0511;... 0.4056 -0.1843 3.8170 21.0978;... 0 0 0 1.0000]; % VARS_GLOBAL_ANIM.graphics_data(i).view = [ 3.5244 0.0000 -0.1045 -1.7099; % -0.1267 1.4211 -0.3401 -0.4771; % -0.3481 -0.5172 -0.9345 20.8033; % 0 0 0 1.0000]; else VARS_GLOBAL_ANIM.graphics_data(i).view = view_curr; end hld=ishold; set(gcf,'NextPlot','add'); set(gca,'NextPlot','add'); %%%%%%%%%%% create ground plane %bb([1 2 5 6],:) = bb([1 2 5 6],:)*10; %ground_tile_size=ground_tile_size*10; if (VARS_GLOBAL_ANIM.ground_tile_size_factor > 0) VARS_GLOBAL_ANIM.graphics_data(i).ground_plane = createGroundPlane(bb,bb_extension,ground_tile_size); end for k=1:length(VARS_GLOBAL_ANIM.skel) %%%%%%%%%%% create text fields for frame number if (~isempty(VARS_GLOBAL_ANIM.draw_labels) && VARS_GLOBAL_ANIM.draw_labels(k)) VARS_GLOBAL_ANIM.graphics_data(i).text_handle(k) = text(0,0,0,''); set(VARS_GLOBAL_ANIM.graphics_data(i).text_handle(k),'interpreter','none'); end %%%%%%%%%%% create lines for skeleton visualization VARS_GLOBAL_ANIM.graphics_data(i).skel_lines{k,1} = createSkeletonLines(k,1); %%%%%%%%%%% create patches for animated plane/cylinder/sphere/etc visualization if (isfield(VARS_GLOBAL_ANIM.mot(k),'animated_patch_data')) VARS_GLOBAL_ANIM.graphics_data(i).animated_patches{k,1} = createAnimatedPatches(k,1); end end if (~hld) set(gcf,'NextPlot','replace'); set(gca,'NextPlot','replace'); end figure(VARS_GLOBAL_ANIM.graphics_data(i).figure); set(gcf,'renderer','OpenGL','DoubleBuffer','on'); set(gcf,'Color',VARS_GLOBAL_ANIM.figure_color); set(gca,'visible','off'); cameratoolbar('Show'); cameratoolbar('SetCoordSys','y'); cameratoolbar('SetMode','orbit'); ax = gca; axis equal; axis(bb+[-1 1 -1 1 -1 1]'*ground_tile_size); view(gca, -128, 43) camup(gca, [0 1 0]); %view(VARS_GLOBAL_ANIM.graphics_data(i).view); camproj('perspective'); camlight headlight; light; %set(gcf,'position',[5 5 512 284]); %set(gca,'Units','centimeter') %camva('auto'); %camva('manual');
github
sheldona/hessianIK-master
params_planePointNormal_hipMiddle.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/params_planePointNormal_hipMiddle.m
1,872
utf_8
3f364fb83a64507cc42a47f8213efe4e
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [points,n,min_radius] = params_planePointNormal_hipMiddle(mot,p3_name,q_name,d) % The plane is defined as follows: % The normal n is the direction vector from the point halfway between the hips to the root. % p3 is the fixture point for the plane. % q is the point that is tested against this plane % d is the offset distance for the plane in the direction of n. % % function returns sequence of fixture points and unit normals along with % minimum radii that make sense to visualize position of q in relation to the plane. if (ischar(p3_name)) p3 = trajectoryID(mot,p3_name); else p3 = mot.nameMap{p3_name,3}; end if (ischar(q_name)) q = trajectoryID(mot,q_name); else q = mot.nameMap{q_name,3}; end p1 = 0.5*(mot.jointTrajectories{trajectoryID(mot,'lhip')}+mot.jointTrajectories{trajectoryID(mot,'rhip')}); n = mot.jointTrajectories{trajectoryID(mot,'root')} - p1; n = n./repmat(sqrt(sum(n.^2)),3,1); points = mot.jointTrajectories{p3} + n*d; min_radius = sqrt(sum((mot.jointTrajectories{p3}+n*d-mot.jointTrajectories{q}).^2));
github
sheldona/hessianIK-master
animateD.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/animateD.m
1,263
utf_8
3f8a0b3675cad9797f6e4718f617edeb
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function animateD(doc_id,varargin) global VARS_GLOBAL; repeat_num = 1; speed = 1; frames = 0; if nargin > 3 repeat_num = varargin{3}; end if nargin > 2 speed = varargin{2}; end if nargin > 1 frames = varargin{1}; end [skel,mot] = readMocapD(doc_id); if (frames == 0) frames = 1:mot.nframes; end %animate_initGraphics; figure(100); set(gcf, 'name', [num2str(doc_id), ': ' mot.filename]); animate(skel,mot,repeat_num,speed,frames);
github
sheldona/hessianIK-master
params_planePointNormal_yAxis.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/params_planePointNormal_yAxis.m
1,638
utf_8
0fc5e348ac7026a527e959b2667201e8
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [points,n,min_radius] = params_planePointNormal_yAxis(mot,p3_name,q_name,d) % The plane is defined as follows: % The normal n is the y axis % p3 is the fixture point for the plane. % q is the point that is tested against this plane % d is the offset distance for the plane in the direction of n. % % function returns sequence of fixture points and unit normals along with % minimum radii that make sense to visualize position of q in relation to the plane. if (ischar(p3_name)) p3 = trajectoryID(mot,p3_name); else p3 = mot.nameMap{p3_name,3}; end if (ischar(q_name)) q = trajectoryID(mot,q_name); else q = mot.nameMap{q_name,3}; end n = repmat([0;1;0],1,mot.nframes); points = mot.jointTrajectories{p3} + n*d; min_radius = sqrt(sum((mot.jointTrajectories{p3}+n*d-mot.jointTrajectories{q}).^2));
github
sheldona/hessianIK-master
createGroundPlane.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/createGroundPlane.m
2,338
utf_8
91b0ef6feeb2d3bc384ee3701473cc4f
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function h = createGroundPlane(bb,bb_extension,ground_tile_size) x_min = bb(1); x_max = bb(2); z_min = bb(5); z_max = bb(6); x_width = x_max - x_min; x_rest = mod(x_width,ground_tile_size); x_min = x_min-x_rest/2; x_max = x_max+x_rest/2; z_width = z_max - z_min; z_rest = mod(z_width,ground_tile_size); z_min = z_min-z_rest/2; z_max = z_max+z_rest/2; [floor_x,floor_z] = meshgrid(x_min:ground_tile_size:x_max,z_min:ground_tile_size:z_max); %h = surf(floor_x,repmat(bb(3)-bb_extension(3),size(floor_x)),floor_z); nx = size(floor_x,1); nz = size(floor_z,2); X = zeros(nx*nz,1); Y = zeros(nx*nz,1); Z = zeros(nx*nz,1); for k=1:nz X((k-1)*nx+1:k*nx) = floor_x(:,k); Z((k-1)*nx+1:k*nx) = floor_z(:,k); end ntiles_x = nx - 1; ntiles_z = nz - 1; faces = zeros(ntiles_x*ntiles_z,4); C = zeros(ntiles_x*ntiles_z,1); c = zeros(1,ntiles_x); c(2:2:length(c)) = 1; for z = 1:ntiles_z faces((z-1)*ntiles_x+1:z*ntiles_x,:) = (z-1)*nx + [1:ntiles_x; 2:nx; nx+2:nx+1+ntiles_x; nx+1:nx+ntiles_x]'; C((z-1)*ntiles_x+1:z*ntiles_x) = c; c = 1-c; end % c1 = [0.5 0.5 0.5]; % c2 = [0 0 0]; %c1 = [0.75 0.75 0.75]; %c2 = [0.5 0.5 0.5]; c1 = [9.2/10 9.2/10 9.2/10]; c2 = [8/10 8/10 8/10]; Y = repmat(bb(3)-bb_extension(3),size(X)); h = patch('Vertices',[X Y Z],... 'Faces',faces,... 'FaceVertexCData',C*c1+(1-C)*c2,... 'FaceColor','flat',... 'EdgeColor','none',... 'FaceLighting','none',... 'UserData', 'GroundPlane'); % set(h,'facecolor','black'); %alpha(h,0.5);
github
sheldona/hessianIK-master
clearTracePoses.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/clearTracePoses.m
1,489
utf_8
6c8fe077512099e2b252b07c469a1c78
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function clearTracePoses global VARS_GLOBAL_ANIM if (isempty(VARS_GLOBAL_ANIM)||isempty(VARS_GLOBAL_ANIM.graphics_data)) return; end f = find(cell2mat({VARS_GLOBAL_ANIM.graphics_data.figure}) == gcf); if (isempty(f)) return; end VARS_GLOBAL_ANIM.graphics_data_index = f; num_trace_poses = size(VARS_GLOBAL_ANIM.graphics_data(f).trace_poses,2); num_lines_per_pose = size(VARS_GLOBAL_ANIM.graphics_data(f).trace_poses,1); for k=1:num_trace_poses for j=1:num_lines_per_pose delete(VARS_GLOBAL_ANIM.graphics_data(f).trace_poses{j,k}(ishandle(VARS_GLOBAL_ANIM.graphics_data(f).trace_poses{j,k}))); end end VARS_GLOBAL_ANIM.graphics_data(f).trace_poses = {};
github
sheldona/hessianIK-master
pauseAnimation.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/pauseAnimation.m
1,015
utf_8
6561afbd29136530c0772b4648470d34
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function pauseAnimation global VARS_GLOBAL_ANIM t = timerfind('Name','AnimationTimer'); if(~isempty(t)) t = t(1); stop(t); wait(t); VARS_GLOBAL_ANIM.animation_paused = true; end
github
sheldona/hessianIK-master
params_planePointPoint.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/params_planePointPoint.m
2,899
utf_8
9d0bac1f2b300efaa7b0c654811de25f
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [fixture,n,min_radius] = params_planePointPoint(mot,p1_name,p2_name,p3_name,q_name,d,varargin) % p1, p2 and p3 define an oriented plane. % q is the point that is tested against this plane % p1+offset is the fixture point for the plane. % d is the offset distance for the plane in the direction of n. % optional argument offset is a 3-vector denoting an offset to be added to the fixture point during min_radius calculation % % function returns sequence of fixture points and unit normals along with % minimum radii that make sense to visualize position of q in relation to the plane. offset = [0;0;0]; if (nargin>6) offset = varargin{1}; end if (ischar(p1_name)) p1 = trajectoryID(mot,p1_name); else p1 = mot.nameMap{p1_name,3}; end if (ischar(p2_name)) p2 = trajectoryID(mot,p2_name); else p2 = mot.nameMap{p2_name,3}; end if (ischar(p3_name)) p3 = trajectoryID(mot,p3_name); else p3 = mot.nameMap{p3_name,3}; end if (ischar(q_name)) q = trajectoryID(mot,q_name); else q = mot.nameMap{q_name,3}; end n = cross(mot.jointTrajectories{p1} - mot.jointTrajectories{p3},mot.jointTrajectories{p2} - mot.jointTrajectories{p3}); n = n./repmat(sqrt(sum(n.^2)),3,1); offset = repmat(offset,1,mot.nframes) - repmat(dot(n,repmat(offset,1,mot.nframes)),3,1).*n; %points = mot.jointTrajectories{p1} + n*d; fixture = mot.jointTrajectories{p1}+offset + n*d; dist_q = dot(n,mot.jointTrajectories{q}-fixture); dist_p1 = dot(n,mot.jointTrajectories{p1}-fixture); dist_p2 = dot(n,mot.jointTrajectories{p2}-fixture); dist_p3 = dot(n,mot.jointTrajectories{p3}-fixture); q_proj = mot.jointTrajectories{q} - repmat(dist_q,3,1).*n; p1_proj = mot.jointTrajectories{p1} - repmat(dist_p1,3,1).*n; p2_proj = mot.jointTrajectories{p2} - repmat(dist_p2,3,1).*n; p3_proj = mot.jointTrajectories{p3} - repmat(dist_p3,3,1).*n; radius_q = sqrt(sum((fixture-q_proj).^2)); radius_p1 = sqrt(sum((fixture-p1_proj).^2)); radius_p2 = sqrt(sum((fixture-p2_proj).^2)); radius_p3 = sqrt(sum((fixture-p3_proj).^2)); min_radius = max([radius_q; radius_p1; radius_p2; radius_p3]);
github
sheldona/hessianIK-master
animate.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/animate.m
4,493
utf_8
482def7e4bca1a7f821115e5c91c42a3
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function animate(skel,mot,varargin) % animate(skel,mot,num_repeats,time_stretch_factor,range,draw_labels) % INPUT: % - skel and mot are assumed to be struct arrays of identical length containing % skeleton/motion pairs to be animated simultaneously. All mots are supposed to have the same samplingRate. % - range is a cell array which is supposed to be of same length as skel/mot. % Empty cell array entries in range indicate that the entire frame range is to be played back. % - draw_labels is a logical vector the same length as skel indicating whether the corresponding skeleton % is to be drawn with a frame counter label. Empty draw_labels means "draw no labels at all". global VARS_GLOBAL_ANIM %if (isempty(VARS_GLOBAL_ANIM)) VARS_GLOBAL_ANIM = emptyVarsGlobalAnimStruct; %end num_repeats = 1; time_stretch_factor = 1; VARS_GLOBAL_ANIM.range = cell(length(mot),1); VARS_GLOBAL_ANIM.draw_labels = ones(length(mot),1); if (nargin > 6) error('Too many arguments!'); end if (nargin > 5) VARS_GLOBAL_ANIM.draw_labels = varargin{4}; end if (nargin > 4) VARS_GLOBAL_ANIM.range = varargin{3}; if (~iscell(VARS_GLOBAL_ANIM.range)) VARS_GLOBAL_ANIM.range = {VARS_GLOBAL_ANIM.range}; end end if (nargin > 3) time_stretch_factor = varargin{2}; end if (nargin > 2) num_repeats = varargin{1}; end VARS_GLOBAL_ANIM.skel = skel; VARS_GLOBAL_ANIM.mot = mot; num_frames = -inf; for k=1:length(VARS_GLOBAL_ANIM.range) if (isempty(VARS_GLOBAL_ANIM.range{k})) VARS_GLOBAL_ANIM.range{k} = [1:VARS_GLOBAL_ANIM.mot(k).nframes]; end if (length(VARS_GLOBAL_ANIM.range{k})>num_frames) % determine num_frames as maximum of range lengths num_frames = length(VARS_GLOBAL_ANIM.range{k}); end end animate_initGraphics; desired_frame_time = VARS_GLOBAL_ANIM.mot(1).frameTime; if (~isempty(VARS_GLOBAL_ANIM.figure_camera_file)) h = str2func(VARS_GLOBAL_ANIM.figure_camera_file); feval(h, gca); end if (~isempty(VARS_GLOBAL_ANIM.figure_position)) set(gcf,'position',VARS_GLOBAL_ANIM.figure_position); end for (i=1:num_repeats) VARS_GLOBAL_ANIM.frame_draw_time = 0; VARS_GLOBAL_ANIM.frames_drawn = 0; VARS_GLOBAL_ANIM.animation_done = false; t=timerfind('Name','AnimationTimer'); if (~isempty(t)) delete(t); end t = timer('Name','AnimationTimer'); try set(t,'TimerFcn','animate_showFrame'); set(t,'ExecutionMode','fixedRate'); set(t,'TasksToExecute',num_frames); period = round(1000*desired_frame_time/time_stretch_factor)/1000; if (period == 0) warning(['Requested timer period of ' num2str(desired_frame_time/time_stretch_factor) ' s is too short for Matlab! Setting period to minimum of 1 ms :-(']); period = 0.001; end set(t,'Period',period); set(t,'BusyMode','queue'); t1=clock; start(t); wait(t); t2=clock; elapsed_time = etime(t2,t1); delete(t); catch delete(t); return end clip_duration = desired_frame_time*num_frames/time_stretch_factor; avg_frame_time = elapsed_time / VARS_GLOBAL_ANIM.frames_drawn; VARS_GLOBAL_ANIM.frames_drawn; actual_frame_rate = 1/avg_frame_time; target_frame_rate = time_stretch_factor/desired_frame_time; disp(['Frame rate: ' num2str(actual_frame_rate) ' fps, target frame rate was ' num2str(target_frame_rate) ' fps.']); disp(['Clip duration: ' num2str(clip_duration) ' sec. Total frame drawing time: ' num2str(VARS_GLOBAL_ANIM.frame_draw_time) ' sec, ' num2str(100*(target_frame_rate/actual_frame_rate)*VARS_GLOBAL_ANIM.frame_draw_time/clip_duration) ' percent load.']); end
github
sheldona/hessianIK-master
params_cappedCylinder.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/params_cappedCylinder.m
1,264
utf_8
102ad0b5fdbea7ea428a807018e318f8
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function [points1,points2] = params_cappedCylinder(mot,p1_name,p2_name,varargin) % p1 and p2 define a line segment p1p2. % % function returns the two endpoints of the line segment if (ischar(p1_name)) p1 = trajectoryID(mot,p1_name); else p1 = mot.nameMap{p1_name,3}; end if (ischar(p2_name)) p2 = trajectoryID(mot,p2_name); else p2 = mot.nameMap{p2_name,3}; end points1 = mot.jointTrajectories{p1}; points2 = mot.jointTrajectories{p2};
github
sheldona/hessianIK-master
animateVideo.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/animateVideo.m
6,406
utf_8
f882dde25749bf606e027581e06f1121
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function animateVideo(skel,mot,videofile,varargin) % animateVideo(skel,mot,videofile,num_repeats,time_stretch_factor,downsampling_fac,range,draw_labels,fps) % INPUT: % - skel and mot are assumed to be struct arrays of identical length containing % skeleton/motion pairs to be animated simultaneously. All mots are supposed to have the same samplingRate. % - range is a cell array which is supposed to be of same length as skel/mot. % Empty cell array entries in range indicate that the entire frame range is to be played back. % - downsampling_fac is an integer indicating the desired downsampling factor. % - draw_labels is a logical vector the same length as skel indicating whether the corresponding skeleton % is to be drawn with a frame counter label % - fps, frames per second, overrides the default sampling rate taken from the mot datastructure % - videofile is the filename of the output AVI. global VARS_GLOBAL_ANIM if (isempty(VARS_GLOBAL_ANIM)) VARS_GLOBAL_ANIM = emptyVarsGlobalAnimStruct; end fps = []; num_repeats = 1; time_stretch_factor = 1; downsampling_fac = 1; hold_frames = []; VARS_GLOBAL_ANIM.range = cell(length(mot),1); VARS_GLOBAL_ANIM.draw_labels = ones(length(mot),1); if (nargin > 10) error('Too many arguments!'); end if (nargin > 9) hold_frames = varargin{7}; end if (nargin > 8) fps = varargin{6}; end if (nargin > 7) VARS_GLOBAL_ANIM.draw_labels = varargin{5}; end if (nargin > 6) VARS_GLOBAL_ANIM.range = varargin{4}; if (~iscell(VARS_GLOBAL_ANIM.range)) VARS_GLOBAL_ANIM.range = {VARS_GLOBAL_ANIM.range}; end end if (nargin > 5) downsampling_fac = varargin{3}; end if (nargin > 4) time_stretch_factor = varargin{2}; end if (nargin > 3) num_repeats = varargin{1}; end VARS_GLOBAL_ANIM.skel = skel; VARS_GLOBAL_ANIM.mot = mot; num_frames = -inf; for k=1:length(VARS_GLOBAL_ANIM.range) if (isempty(VARS_GLOBAL_ANIM.range{k})) VARS_GLOBAL_ANIM.range{k} = [1:VARS_GLOBAL_ANIM.mot(k).nframes]; end if (downsampling_fac > 1) VARS_GLOBAL_ANIM.range{k} = intersect(VARS_GLOBAL_ANIM.range{k},[1:downsampling_fac:VARS_GLOBAL_ANIM.mot(k).nframes]); end if (length(VARS_GLOBAL_ANIM.range{k})>num_frames) % determine num_frames as maximum of range lengths num_frames = length(VARS_GLOBAL_ANIM.range{k}); end end if (isempty(hold_frames)) hold_frames = ones(1,num_frames); end animate_initGraphics; figure(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).figure); if (~isempty(VARS_GLOBAL_ANIM.figure_camera_file)) h = str2func(VARS_GLOBAL_ANIM.figure_camera_file); feval(h, gca); else set(gca,'CameraViewAngle',5); end desired_frame_time = VARS_GLOBAL_ANIM.mot(1).frameTime*downsampling_fac; if (isempty(fps)) fps = ceil(VARS_GLOBAL_ANIM.mot(1).samplingRate/downsampling_fac); end aviobj = avifile(videofile,'compression',VARS_GLOBAL_ANIM.video_compression,'quality',75,'fps',fps); %set(gcf,'units','centimeters'); %set(gcf,'paperunits','centimeters'); %set(gcf,'paperposition',get(gcf,'position')); %set(gcf,'units','pixels'); %set(gca,'units','pixels'); if (~isempty(VARS_GLOBAL_ANIM.figure_position)) set(gcf,'position',VARS_GLOBAL_ANIM.figure_position); end %h = get(gca,'children'); %set(h([32:34]),'marker','none'); %axes_rect = round(get(gca,'position')); % frame = hardcopy(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).figure, '-dzbuffer', ['-r' num2str(round(get(0,'screenp')))]); % fy = size(frame,1); % ayl = fy-axes_rect(2)-axes_rect(4)+1; ayh = fy-axes_rect(2); axl = axes_rect(1)+1; axh = axes_rect(1)+axes_rect(3); %set(gca,'units','normalized'); for (i=1:num_repeats) VARS_GLOBAL_ANIM.frame_draw_time = 0; VARS_GLOBAL_ANIM.frames_drawn = 0; VARS_GLOBAL_ANIM.animation_done = false; strlen = 0; count = 0; for k = 1:num_frames for j=1:hold_frames(k) animate_showFrame(k); % frame = getframe(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).figure,[axl ayl axh-axl+1 ayh-ayl+1]); % frame = frame(ayl:ayh,axl:axh,:); frame = getframe(VARS_GLOBAL_ANIM.graphics_data(VARS_GLOBAL_ANIM.graphics_data_index).figure); if (VARS_GLOBAL_ANIM.video_flip_vert) % strcmpi(VARS_GLOBAL_ANIM.video_compression,'PNG1') | frame.cdata = flipdim(frame.cdata,1); end if (VARS_GLOBAL_ANIM.video_flip_horz) frame.cdata = flipdim(frame.cdata,2); end aviobj = addframe(aviobj,frame); count = count+1; s = [num2str(count) '/' num2str(sum(hold_frames))]; disp(char(8*ones(1,strlen+2))); strlen = length(s); disp(s); end end clip_duration = desired_frame_time*num_frames/time_stretch_factor; avg_frame_time = VARS_GLOBAL_ANIM.frame_draw_time / VARS_GLOBAL_ANIM.frames_drawn; actual_frame_rate = 1/avg_frame_time; target_frame_rate = time_stretch_factor/desired_frame_time; disp(['Frame rate: ' num2str(actual_frame_rate) ' fps, target frame rate was ' num2str(target_frame_rate) ' fps.']); disp(['Clip duration: ' num2str(clip_duration) ' sec. Total frame drawing time: ' num2str(VARS_GLOBAL_ANIM.frame_draw_time) ' sec, ' num2str(100*(target_frame_rate/actual_frame_rate)*VARS_GLOBAL_ANIM.frame_draw_time/clip_duration) ' percent load.']); end aviobj = close(aviobj); disp(['Wrote output video file ' videofile '.']);
github
sheldona/hessianIK-master
params_point.m
.m
hessianIK-master/matlab/HDM05-Parser/animate/params_point.m
991
utf_8
7c22edf392e740c65f2843d490b0affa
% This code belongs to the HDM05 mocap database which can be obtained % from the website http://www.mpi-inf.mpg.de/resources/HDM05 . % % If you use and publish results based on this code and data, please % cite the following technical report: % % @techreport{MuellerRCEKW07_HDM05-Docu, % author = {Meinard M{\"u}ller and Tido R{\"o}der and Michael Clausen and Bernd Eberhardt and Bj{\"o}rn Kr{\"u}ger and Andreas Weber}, % title = {Documentation: Mocap Database {HDM05}}, % institution = {Universit{\"a}t Bonn}, % number = {CG-2007-2}, % year = {2007} % } % % % THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY % KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A % PARTICULAR PURPOSE. function points = params_point(mot,p1_name) if (ischar(p1_name)) p1 = trajectoryID(mot,p1_name); else p1 = mot.nameMap{p1_name,3}; end points = mot.jointTrajectories{p1};
github
aman432/Spam-Classifier-master
submit.m
.m
Spam-Classifier-master/Spam/submit.m
1,318
utf_8
bfa0b4ffb8a7854d8e84276e91818107
function submit() addpath('./lib'); conf.assignmentSlug = 'support-vector-machines'; conf.itemName = 'Support Vector Machines'; conf.partArrays = { ... { ... '1', ... { 'gaussianKernel.m' }, ... 'Gaussian Kernel', ... }, ... { ... '2', ... { 'dataset3Params.m' }, ... 'Parameters (C, sigma) for Dataset 3', ... }, ... { ... '3', ... { 'processEmail.m' }, ... 'Email Preprocessing', ... }, ... { ... '4', ... { 'emailFeatures.m' }, ... 'Email Feature Extraction', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases x1 = sin(1:10)'; x2 = cos(1:10)'; ec = 'the quick brown fox jumped over the lazy dog'; wi = 1 + abs(round(x1 * 1863)); wi = [wi ; wi]; if partId == '1' sim = gaussianKernel(x1, x2, 2); out = sprintf('%0.5f ', sim); elseif partId == '2' load('ex6data3.mat'); [C, sigma] = dataset3Params(X, y, Xval, yval); out = sprintf('%0.5f ', C); out = [out sprintf('%0.5f ', sigma)]; elseif partId == '3' word_indices = processEmail(ec); out = sprintf('%d ', word_indices); elseif partId == '4' x = emailFeatures(wi); out = sprintf('%d ', x); end end
github
aman432/Spam-Classifier-master
porterStemmer.m
.m
Spam-Classifier-master/Spam/porterStemmer.m
9,902
utf_8
7ed5acd925808fde342fc72bd62ebc4d
function stem = porterStemmer(inString) % Applies the Porter Stemming algorithm as presented in the following % paper: % Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14, % no. 3, pp 130-137 % Original code modeled after the C version provided at: % http://www.tartarus.org/~martin/PorterStemmer/c.txt % The main part of the stemming algorithm starts here. b is an array of % characters, holding the word to be stemmed. The letters are in b[k0], % b[k0+1] ending at b[k]. In fact k0 = 1 in this demo program (since % matlab begins indexing by 1 instead of 0). k is readjusted downwards as % the stemming progresses. Zero termination is not in fact used in the % algorithm. % To call this function, use the string to be stemmed as the input % argument. This function returns the stemmed word as a string. % Lower-case string inString = lower(inString); global j; b = inString; k = length(b); k0 = 1; j = k; % With this if statement, strings of length 1 or 2 don't go through the % stemming process. Remove this conditional to match the published % algorithm. stem = b; if k > 2 % Output displays per step are commented out. %disp(sprintf('Word to stem: %s', b)); x = step1ab(b, k, k0); %disp(sprintf('Steps 1A and B yield: %s', x{1})); x = step1c(x{1}, x{2}, k0); %disp(sprintf('Step 1C yields: %s', x{1})); x = step2(x{1}, x{2}, k0); %disp(sprintf('Step 2 yields: %s', x{1})); x = step3(x{1}, x{2}, k0); %disp(sprintf('Step 3 yields: %s', x{1})); x = step4(x{1}, x{2}, k0); %disp(sprintf('Step 4 yields: %s', x{1})); x = step5(x{1}, x{2}, k0); %disp(sprintf('Step 5 yields: %s', x{1})); stem = x{1}; end % cons(j) is TRUE <=> b[j] is a consonant. function c = cons(i, b, k0) c = true; switch(b(i)) case {'a', 'e', 'i', 'o', 'u'} c = false; case 'y' if i == k0 c = true; else c = ~cons(i - 1, b, k0); end end % mseq() measures the number of consonant sequences between k0 and j. If % c is a consonant sequence and v a vowel sequence, and <..> indicates % arbitrary presence, % <c><v> gives 0 % <c>vc<v> gives 1 % <c>vcvc<v> gives 2 % <c>vcvcvc<v> gives 3 % .... function n = measure(b, k0) global j; n = 0; i = k0; while true if i > j return end if ~cons(i, b, k0) break; end i = i + 1; end i = i + 1; while true while true if i > j return end if cons(i, b, k0) break; end i = i + 1; end i = i + 1; n = n + 1; while true if i > j return end if ~cons(i, b, k0) break; end i = i + 1; end i = i + 1; end % vowelinstem() is TRUE <=> k0,...j contains a vowel function vis = vowelinstem(b, k0) global j; for i = k0:j, if ~cons(i, b, k0) vis = true; return end end vis = false; %doublec(i) is TRUE <=> i,(i-1) contain a double consonant. function dc = doublec(i, b, k0) if i < k0+1 dc = false; return end if b(i) ~= b(i-1) dc = false; return end dc = cons(i, b, k0); % cvc(j) is TRUE <=> j-2,j-1,j has the form consonant - vowel - consonant % and also if the second c is not w,x or y. this is used when trying to % restore an e at the end of a short word. e.g. % % cav(e), lov(e), hop(e), crim(e), but % snow, box, tray. function c1 = cvc(i, b, k0) if ((i < (k0+2)) || ~cons(i, b, k0) || cons(i-1, b, k0) || ~cons(i-2, b, k0)) c1 = false; else if (b(i) == 'w' || b(i) == 'x' || b(i) == 'y') c1 = false; return end c1 = true; end % ends(s) is TRUE <=> k0,...k ends with the string s. function s = ends(str, b, k) global j; if (str(length(str)) ~= b(k)) s = false; return end % tiny speed-up if (length(str) > k) s = false; return end if strcmp(b(k-length(str)+1:k), str) s = true; j = k - length(str); return else s = false; end % setto(s) sets (j+1),...k to the characters in the string s, readjusting % k accordingly. function so = setto(s, b, k) global j; for i = j+1:(j+length(s)) b(i) = s(i-j); end if k > j+length(s) b((j+length(s)+1):k) = ''; end k = length(b); so = {b, k}; % rs(s) is used further down. % [Note: possible null/value for r if rs is called] function r = rs(str, b, k, k0) r = {b, k}; if measure(b, k0) > 0 r = setto(str, b, k); end % step1ab() gets rid of plurals and -ed or -ing. e.g. % caresses -> caress % ponies -> poni % ties -> ti % caress -> caress % cats -> cat % feed -> feed % agreed -> agree % disabled -> disable % matting -> mat % mating -> mate % meeting -> meet % milling -> mill % messing -> mess % meetings -> meet function s1ab = step1ab(b, k, k0) global j; if b(k) == 's' if ends('sses', b, k) k = k-2; elseif ends('ies', b, k) retVal = setto('i', b, k); b = retVal{1}; k = retVal{2}; elseif (b(k-1) ~= 's') k = k-1; end end if ends('eed', b, k) if measure(b, k0) > 0; k = k-1; end elseif (ends('ed', b, k) || ends('ing', b, k)) && vowelinstem(b, k0) k = j; retVal = {b, k}; if ends('at', b, k) retVal = setto('ate', b(k0:k), k); elseif ends('bl', b, k) retVal = setto('ble', b(k0:k), k); elseif ends('iz', b, k) retVal = setto('ize', b(k0:k), k); elseif doublec(k, b, k0) retVal = {b, k-1}; if b(retVal{2}) == 'l' || b(retVal{2}) == 's' || ... b(retVal{2}) == 'z' retVal = {retVal{1}, retVal{2}+1}; end elseif measure(b, k0) == 1 && cvc(k, b, k0) retVal = setto('e', b(k0:k), k); end k = retVal{2}; b = retVal{1}(k0:k); end j = k; s1ab = {b(k0:k), k}; % step1c() turns terminal y to i when there is another vowel in the stem. function s1c = step1c(b, k, k0) global j; if ends('y', b, k) && vowelinstem(b, k0) b(k) = 'i'; end j = k; s1c = {b, k}; % step2() maps double suffices to single ones. so -ization ( = -ize plus % -ation) maps to -ize etc. note that the string before the suffix must give % m() > 0. function s2 = step2(b, k, k0) global j; s2 = {b, k}; switch b(k-1) case {'a'} if ends('ational', b, k) s2 = rs('ate', b, k, k0); elseif ends('tional', b, k) s2 = rs('tion', b, k, k0); end; case {'c'} if ends('enci', b, k) s2 = rs('ence', b, k, k0); elseif ends('anci', b, k) s2 = rs('ance', b, k, k0); end; case {'e'} if ends('izer', b, k) s2 = rs('ize', b, k, k0); end; case {'l'} if ends('bli', b, k) s2 = rs('ble', b, k, k0); elseif ends('alli', b, k) s2 = rs('al', b, k, k0); elseif ends('entli', b, k) s2 = rs('ent', b, k, k0); elseif ends('eli', b, k) s2 = rs('e', b, k, k0); elseif ends('ousli', b, k) s2 = rs('ous', b, k, k0); end; case {'o'} if ends('ization', b, k) s2 = rs('ize', b, k, k0); elseif ends('ation', b, k) s2 = rs('ate', b, k, k0); elseif ends('ator', b, k) s2 = rs('ate', b, k, k0); end; case {'s'} if ends('alism', b, k) s2 = rs('al', b, k, k0); elseif ends('iveness', b, k) s2 = rs('ive', b, k, k0); elseif ends('fulness', b, k) s2 = rs('ful', b, k, k0); elseif ends('ousness', b, k) s2 = rs('ous', b, k, k0); end; case {'t'} if ends('aliti', b, k) s2 = rs('al', b, k, k0); elseif ends('iviti', b, k) s2 = rs('ive', b, k, k0); elseif ends('biliti', b, k) s2 = rs('ble', b, k, k0); end; case {'g'} if ends('logi', b, k) s2 = rs('log', b, k, k0); end; end j = s2{2}; % step3() deals with -ic-, -full, -ness etc. similar strategy to step2. function s3 = step3(b, k, k0) global j; s3 = {b, k}; switch b(k) case {'e'} if ends('icate', b, k) s3 = rs('ic', b, k, k0); elseif ends('ative', b, k) s3 = rs('', b, k, k0); elseif ends('alize', b, k) s3 = rs('al', b, k, k0); end; case {'i'} if ends('iciti', b, k) s3 = rs('ic', b, k, k0); end; case {'l'} if ends('ical', b, k) s3 = rs('ic', b, k, k0); elseif ends('ful', b, k) s3 = rs('', b, k, k0); end; case {'s'} if ends('ness', b, k) s3 = rs('', b, k, k0); end; end j = s3{2}; % step4() takes off -ant, -ence etc., in context <c>vcvc<v>. function s4 = step4(b, k, k0) global j; switch b(k-1) case {'a'} if ends('al', b, k) end; case {'c'} if ends('ance', b, k) elseif ends('ence', b, k) end; case {'e'} if ends('er', b, k) end; case {'i'} if ends('ic', b, k) end; case {'l'} if ends('able', b, k) elseif ends('ible', b, k) end; case {'n'} if ends('ant', b, k) elseif ends('ement', b, k) elseif ends('ment', b, k) elseif ends('ent', b, k) end; case {'o'} if ends('ion', b, k) if j == 0 elseif ~(strcmp(b(j),'s') || strcmp(b(j),'t')) j = k; end elseif ends('ou', b, k) end; case {'s'} if ends('ism', b, k) end; case {'t'} if ends('ate', b, k) elseif ends('iti', b, k) end; case {'u'} if ends('ous', b, k) end; case {'v'} if ends('ive', b, k) end; case {'z'} if ends('ize', b, k) end; end if measure(b, k0) > 1 s4 = {b(k0:j), j}; else s4 = {b(k0:k), k}; end % step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1. function s5 = step5(b, k, k0) global j; j = k; if b(k) == 'e' a = measure(b, k0); if (a > 1) || ((a == 1) && ~cvc(k-1, b, k0)) k = k-1; end end if (b(k) == 'l') && doublec(k, b, k0) && (measure(b, k0) > 1) k = k-1; end s5 = {b(k0:k), k};
github
aman432/Spam-Classifier-master
submitWithConfiguration.m
.m
Spam-Classifier-master/Spam/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
aman432/Spam-Classifier-master
savejson.m
.m
Spam-Classifier-master/Spam/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
aman432/Spam-Classifier-master
loadjson.m
.m
Spam-Classifier-master/Spam/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
aman432/Spam-Classifier-master
loadubjson.m
.m
Spam-Classifier-master/Spam/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
aman432/Spam-Classifier-master
saveubjson.m
.m
Spam-Classifier-master/Spam/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
sovandas/Modulation-Testing-Tool-master
parameterEdit.m
.m
Modulation-Testing-Tool-master/SISO OFDM/parameterEdit.m
4,564
utf_8
74f2193b03e8af2a1f406a0056e10c89
function varargout = parameterEdit(varargin) % PARAMETEREDIT MATLAB code for parameterEdit.fig % PARAMETEREDIT, by itself, creates a new PARAMETEREDIT or raises the existing % singleton*. % % H = PARAMETEREDIT returns the handle to a new PARAMETEREDIT or the handle to % the existing singleton*. % % PARAMETEREDIT('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in PARAMETEREDIT.M with the given input arguments. % % PARAMETEREDIT('Property','Value',...) creates a new PARAMETEREDIT or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before parameterEdit_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to parameterEdit_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help parameterEdit % Last Modified by GUIDE v2.5 11-Nov-2013 23:20:17 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @parameterEdit_OpeningFcn, ... 'gui_OutputFcn', @parameterEdit_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before parameterEdit is made visible. function parameterEdit_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to parameterEdit (see VARARGIN) % Choose default command line output for parameterEdit handles.output = hObject; % Display Input variableNames = whos('-file',varargin{2}); % get variable names variableValues = load(varargin{2}); % load varaibles tableData = {}; % initialize table for i = 1:length(variableNames), % iterate over variables tableData{i,1} = variableNames(i).name; % get variable name if strcmp(variableNames(i).class, 'double'), if length(size(variableValues.(variableNames(i).name))) > 1, % handle arrays tableData{i,2} = num2str(variableValues.(variableNames(i).name)); % get variable value else tableData{i,2} = variableValues.(variableNames(i).name); end elseif strcmp(variableNames(i).class, 'char'), tableData{i,2} = variableValues.(variableNames(i).name); end end set(handles.uitable1,'Data',tableData); % set table to display parameters % Update handles structure handles.parameterFile = varargin{2}; % save file location handles.variableNames = variableNames; % save variable data guidata(hObject, handles); % UIWAIT makes parameterEdit wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = parameterEdit_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in save. function save_Callback(hObject, eventdata, handles) % hObject handle to save (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) data = guidata(handles.figure1); % parameterData = load(data.parameterFile); tableData = get(handles.uitable1,'Data'); for i = 1:size(tableData,1), if strcmp(data.variableNames(i).class,'double'), parameterData.(tableData{i,1}) = str2num(tableData{i,2}); elseif strcmp(data.variableNames(i).class,'char'), parameterData.(tableData{i,1}) = tableData{i,2}; end end save(data.parameterFile, '-struct', 'parameterData');
github
sovandas/Modulation-Testing-Tool-master
parameterEdit.m
.m
Modulation-Testing-Tool-master/SM OFDM/parameterEdit.m
4,564
utf_8
74f2193b03e8af2a1f406a0056e10c89
function varargout = parameterEdit(varargin) % PARAMETEREDIT MATLAB code for parameterEdit.fig % PARAMETEREDIT, by itself, creates a new PARAMETEREDIT or raises the existing % singleton*. % % H = PARAMETEREDIT returns the handle to a new PARAMETEREDIT or the handle to % the existing singleton*. % % PARAMETEREDIT('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in PARAMETEREDIT.M with the given input arguments. % % PARAMETEREDIT('Property','Value',...) creates a new PARAMETEREDIT or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before parameterEdit_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to parameterEdit_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help parameterEdit % Last Modified by GUIDE v2.5 11-Nov-2013 23:20:17 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @parameterEdit_OpeningFcn, ... 'gui_OutputFcn', @parameterEdit_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before parameterEdit is made visible. function parameterEdit_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to parameterEdit (see VARARGIN) % Choose default command line output for parameterEdit handles.output = hObject; % Display Input variableNames = whos('-file',varargin{2}); % get variable names variableValues = load(varargin{2}); % load varaibles tableData = {}; % initialize table for i = 1:length(variableNames), % iterate over variables tableData{i,1} = variableNames(i).name; % get variable name if strcmp(variableNames(i).class, 'double'), if length(size(variableValues.(variableNames(i).name))) > 1, % handle arrays tableData{i,2} = num2str(variableValues.(variableNames(i).name)); % get variable value else tableData{i,2} = variableValues.(variableNames(i).name); end elseif strcmp(variableNames(i).class, 'char'), tableData{i,2} = variableValues.(variableNames(i).name); end end set(handles.uitable1,'Data',tableData); % set table to display parameters % Update handles structure handles.parameterFile = varargin{2}; % save file location handles.variableNames = variableNames; % save variable data guidata(hObject, handles); % UIWAIT makes parameterEdit wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = parameterEdit_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in save. function save_Callback(hObject, eventdata, handles) % hObject handle to save (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) data = guidata(handles.figure1); % parameterData = load(data.parameterFile); tableData = get(handles.uitable1,'Data'); for i = 1:size(tableData,1), if strcmp(data.variableNames(i).class,'double'), parameterData.(tableData{i,1}) = str2num(tableData{i,2}); elseif strcmp(data.variableNames(i).class,'char'), parameterData.(tableData{i,1}) = tableData{i,2}; end end save(data.parameterFile, '-struct', 'parameterData');
github
sovandas/Modulation-Testing-Tool-master
SM_test_est_with_ch_est_adaptive_modulation.m
.m
Modulation-Testing-Tool-master/SM OFDM/SM_test_est_with_ch_est_adaptive_modulation.m
12,232
utf_8
c59725a94507e3d8a4fac3a01f0ebde3
function [BER, BER_SM, BER_QAM, channel, estimated_channel, estimated_SNR, fitted_SNR] = SM_test_est_with_ch_est_adaptive_modulation(input_from_diode_ch1, input_from_diode_ch2, qam_dco_ch1, qam_dco_ch2, SM_bits, M, P, Frames, Nfft, cp_length, omitted_carriers, preamble_length, offset, frame_eq_mult, samples_per_symbol, filter_type, roll_off_factor, Max_Constellation_Size, number_of_pilot_frames) for k=1:log2(Max_Constellation_Size) demodulator{k} = modem.qamdemod('M',2^k,'SymbolOrder','Gray','OutputType','Bit'); %Creates a QAM modulator object for constellation sizes up to Max_Constellation_Size power_rescale(k) = sqrt(demodulator{k}.Constellation()*demodulator{k}.Constellation()'/(2^k)); end BER=[]; BER_SM=[]; BER_QAM=[]; channel_ch1=[]; estimated_channel_ch1=[]; estimated_SNR_ch1=[]; fitted_SNR_ch1=[]; for counter=1:floor(Frames/frame_eq_mult) [channel_ch11(counter,:), estimated_channel_ch11(counter,:), estimated_SNR_ch11(counter,:), fitted_SNR_ch11(counter,:)] = SM_channel_estimation(input_from_diode_ch1, qam_dco_ch1((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)*(Nfft-2)/2+1:((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft-2)/2), number_of_pilot_frames, Nfft, cp_length, omitted_carriers, preamble_length, offset+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)*(Nfft+cp_length)*samples_per_symbol, samples_per_symbol, filter_type, roll_off_factor); [channel_ch21(counter,:), estimated_channel_ch21(counter,:), estimated_SNR_ch21(counter,:), fitted_SNR_ch21(counter,:)] = SM_channel_estimation(input_from_diode_ch2, qam_dco_ch1((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)*(Nfft-2)/2+1:((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft-2)/2), number_of_pilot_frames, Nfft, cp_length, omitted_carriers, preamble_length, offset+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)*(Nfft+cp_length)*samples_per_symbol, samples_per_symbol, filter_type, roll_off_factor); [channel_ch12(counter,:), estimated_channel_ch12(counter,:), estimated_SNR_ch12(counter,:), fitted_SNR_ch12(counter,:)] = SM_channel_estimation(input_from_diode_ch1, qam_dco_ch2(((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft-2)/2+1:((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2), number_of_pilot_frames, Nfft, cp_length, omitted_carriers, preamble_length, offset+((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft+cp_length)*samples_per_symbol, samples_per_symbol, filter_type, roll_off_factor); [channel_ch22(counter,:), estimated_channel_ch22(counter,:), estimated_SNR_ch22(counter,:), fitted_SNR_ch22(counter,:)] = SM_channel_estimation(input_from_diode_ch2, qam_dco_ch2(((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft-2)/2+1:((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2), number_of_pilot_frames, Nfft, cp_length, omitted_carriers, preamble_length, offset+((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft+cp_length)*samples_per_symbol, samples_per_symbol, filter_type, roll_off_factor); channel = [channel_ch11; channel_ch12; channel_ch21; channel_ch22]; estimated_channel = [estimated_channel_ch11; estimated_channel_ch12; estimated_channel_ch21; estimated_channel_ch22]; estimated_SNR = [estimated_SNR_ch11; estimated_SNR_ch12; estimated_SNR_ch21; estimated_SNR_ch22]; fitted_SNR = [fitted_SNR_ch11; fitted_SNR_ch12; fitted_SNR_ch21; fitted_SNR_ch22]; qam_recovered_diode_ch1 = recover_ofdm_signal(input_from_diode_ch1, preamble_length+offset+((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft+cp_length)*samples_per_symbol, filter_type, roll_off_factor, frame_eq_mult, Nfft, cp_length, samples_per_symbol); qam_recovered_diode_ch2 = recover_ofdm_signal(input_from_diode_ch2, preamble_length+offset+((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft+cp_length)*samples_per_symbol, filter_type, roll_off_factor, frame_eq_mult, Nfft, cp_length, samples_per_symbol); qam_recovered_diode_no_zeros_ch1=[]; for k=1:frame_eq_mult %qam_recovered_diode_no_zeros((k-1)*(Nfft-2*(omitted_carriers+1))/2+1:k*(Nfft-2*(omitted_carriers+1))/2) = qam_recovered_diode((k-1)*(Nfft-2)/2+1+omitted_carriers:k*(Nfft-2)/2)./sqrt(P); work_block = qam_recovered_diode_ch1((k-1)*(Nfft-2)/2+1:k*(Nfft-2)/2); %Takes a frame of symbols qam_recovered_diode_no_zeros_ch1 = [qam_recovered_diode_no_zeros_ch1,work_block([zeros(1,omitted_carriers),M]~=0)./sqrt(P(M~=0))]; %Removes all zeros from that symbol frame and rescales by the assigned power end qam_recovered_diode_no_zeros_ch2=[]; for k=1:frame_eq_mult work_block = qam_recovered_diode_ch2((k-1)*(Nfft-2)/2+1:k*(Nfft-2)/2); %Takes a frame of symbols qam_recovered_diode_no_zeros_ch2 = [qam_recovered_diode_no_zeros_ch2,work_block([zeros(1,omitted_carriers),M]~=0)./sqrt(P(M~=0))]; %Removes all zeros from that symbol frame and rescales by the assigned power end qam_dco_no_zeros_ch1=[]; for k=1:frame_eq_mult work_block = qam_dco_ch1((k-1+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2+1:(k+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2); qam_dco_no_zeros_ch1 = [qam_dco_no_zeros_ch1,work_block([zeros(1,omitted_carriers),M]~=0)./sqrt(P(M~=0))]; end qam_dco_no_zeros_ch2=[]; for k=1:frame_eq_mult work_block = qam_dco_ch2((k-1+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2+1:(k+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2); qam_dco_no_zeros_ch2 = [qam_dco_no_zeros_ch2,work_block([zeros(1,omitted_carriers),M]~=0)./sqrt(P(M~=0))]; end % figure, plot(10*log10(abs(qam_recovered_diode_no_zeros./qam_dco_no_zeros).^2)) % xlabel('Active Carrier Index') % ylabel('|H|^2 [dB]') % temp_str = ['Gain in ',num2str(frame_eq_mult),' consecutive frames']; % legend(temp_str) % % figure, plot(phase(qam_recovered_diode_no_zeros./qam_dco_no_zeros)) % xlabel('Active Carrier Index') % ylabel('Phase(H) [Rad]') % temp_str = ['Phase in ',num2str(frame_eq_mult),' consecutive frames']; % legend(temp_str) %qam_recovered_diode_no_zeros_equalized_ch1=qam_recovered_diode_no_zeros_ch1; qam_recovered_diode_no_zeros_equalized_ch1=[]; current_channel_ch11 = channel_ch11(counter,:); current_channel_ch12 = channel_ch12(counter,:); block_length = length(qam_recovered_diode_no_zeros_ch1)/frame_eq_mult; for k=1:frame_eq_mult qam_recovered_diode_no_zeros_equalized_ch1 = [qam_recovered_diode_no_zeros_equalized_ch1,qam_recovered_diode_no_zeros_ch1((k-1)*block_length+1:k*block_length)./current_channel_ch11(M~=0)]; end %qam_recovered_diode_no_zeros_equalized_ch2=qam_recovered_diode_no_zeros_ch2; qam_recovered_diode_no_zeros_equalized_ch2=[]; current_channel_ch21 = channel_ch21(counter,:); current_channel_ch22 = channel_ch22(counter,:); block_length = length(qam_recovered_diode_no_zeros_ch2)/frame_eq_mult; for k=1:frame_eq_mult qam_recovered_diode_no_zeros_equalized_ch2 = [qam_recovered_diode_no_zeros_equalized_ch2,qam_recovered_diode_no_zeros_ch2((k-1)*block_length+1:k*block_length)./current_channel_ch22(M~=0)]; end for k=1:log2(Max_Constellation_Size) points_of_same_size_received{k}=[]; points_of_same_size_received_equalized{k}=[]; points_of_same_size_original{k}=[]; end original_QAM_bits=[]; received_QAM_bits=[]; received_SM_bits=[]; M_without_zeros = M(M~=0); for k=1:frame_eq_mult for l=1:block_length qam_recovered_diode_no_zeros_rescaled_ch1((k-1)*block_length+l) = qam_recovered_diode_no_zeros_ch1((k-1)*block_length+l)*power_rescale(log2(M_without_zeros(l))); qam_recovered_diode_no_zeros_rescaled_ch2((k-1)*block_length+l) = qam_recovered_diode_no_zeros_ch2((k-1)*block_length+l)*power_rescale(log2(M_without_zeros(l))); if SM_bits((k-1)*block_length+l) == 1 points_of_same_size_received{log2(M_without_zeros(l))} = [points_of_same_size_received{log2(M_without_zeros(l))},qam_recovered_diode_no_zeros_rescaled_ch1((k-1)*block_length+l)]; else points_of_same_size_received{log2(M_without_zeros(l))} = [points_of_same_size_received{log2(M_without_zeros(l))},qam_recovered_diode_no_zeros_rescaled_ch2((k-1)*block_length+l)]; end qam_recovered_diode_no_zeros_equalized_rescaled_ch1((k-1)*block_length+l) = qam_recovered_diode_no_zeros_equalized_ch1((k-1)*block_length+l)*power_rescale(log2(M_without_zeros(l))); qam_recovered_diode_no_zeros_equalized_rescaled_ch2((k-1)*block_length+l) = qam_recovered_diode_no_zeros_equalized_ch2((k-1)*block_length+l)*power_rescale(log2(M_without_zeros(l))); if SM_bits((k-1)*block_length+l) == 1 points_of_same_size_received_equalized{log2(M_without_zeros(l))} = [points_of_same_size_received_equalized{log2(M_without_zeros(l))},qam_recovered_diode_no_zeros_equalized_rescaled_ch1((k-1)*block_length+l)]; else points_of_same_size_received_equalized{log2(M_without_zeros(l))} = [points_of_same_size_received_equalized{log2(M_without_zeros(l))},qam_recovered_diode_no_zeros_equalized_rescaled_ch2((k-1)*block_length+l)]; end qam_dco_no_zeros_rescaled_ch1((k-1)*block_length+l) = qam_dco_no_zeros_ch1((k-1)*block_length+l)*power_rescale(log2(M_without_zeros(l))); qam_dco_no_zeros_rescaled_ch2((k-1)*block_length+l) = qam_dco_no_zeros_ch2((k-1)*block_length+l)*power_rescale(log2(M_without_zeros(l))); if SM_bits((k-1)*block_length+l) == 1 points_of_same_size_original{log2(M_without_zeros(l))} = [points_of_same_size_original{log2(M_without_zeros(l))},qam_dco_no_zeros_rescaled_ch1((k-1)*block_length+l)]; else points_of_same_size_original{log2(M_without_zeros(l))} = [points_of_same_size_original{log2(M_without_zeros(l))},qam_dco_no_zeros_rescaled_ch2((k-1)*block_length+l)]; end [SM_bit, QAM_bits] = SM_demodulate_2channels_with_crosstalk(qam_recovered_diode_no_zeros_rescaled_ch1((k-1)*block_length+l),qam_recovered_diode_no_zeros_rescaled_ch2((k-1)*block_length+l), M_without_zeros(l), demodulator{log2(M_without_zeros(l))}, current_channel_ch11(l), current_channel_ch12(l), current_channel_ch21(l), current_channel_ch22(l)); received_QAM_bits = [received_QAM_bits,QAM_bits]; received_SM_bits = [received_SM_bits,SM_bit]; if SM_bits((k-1)*block_length+l) == 1 original_QAM_bits = [original_QAM_bits,demodulate(demodulator{log2(M_without_zeros(l))},qam_dco_no_zeros_rescaled_ch1((k-1)*block_length+l))']; else original_QAM_bits = [original_QAM_bits,demodulate(demodulator{log2(M_without_zeros(l))},qam_dco_no_zeros_rescaled_ch2((k-1)*block_length+l))']; end end end for k=1:log2(Max_Constellation_Size) if length(points_of_same_size_received{k})>0 && length(points_of_same_size_received_equalized{k})>0 && length(points_of_same_size_original{k})>0 scatterplot(points_of_same_size_received{k}); scatterplot(points_of_same_size_received_equalized{k}); scatterplot(points_of_same_size_original{k}); end end size(original_QAM_bits) + size(SM_bits) BER_QAM(counter) = sum(sum(xor(original_QAM_bits, received_QAM_bits)))/length(original_QAM_bits); BER_SM(counter) = sum(sum(xor(SM_bits, received_SM_bits)))/length(SM_bits); BER(counter) = (BER_SM*length(SM_bits) + BER_QAM*length(original_QAM_bits))/(length(SM_bits) + length(original_QAM_bits)); end
github
sovandas/Modulation-Testing-Tool-master
parameterEdit.m
.m
Modulation-Testing-Tool-master/MIMO OFDM/parameterEdit.m
4,564
utf_8
74f2193b03e8af2a1f406a0056e10c89
function varargout = parameterEdit(varargin) % PARAMETEREDIT MATLAB code for parameterEdit.fig % PARAMETEREDIT, by itself, creates a new PARAMETEREDIT or raises the existing % singleton*. % % H = PARAMETEREDIT returns the handle to a new PARAMETEREDIT or the handle to % the existing singleton*. % % PARAMETEREDIT('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in PARAMETEREDIT.M with the given input arguments. % % PARAMETEREDIT('Property','Value',...) creates a new PARAMETEREDIT or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before parameterEdit_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to parameterEdit_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help parameterEdit % Last Modified by GUIDE v2.5 11-Nov-2013 23:20:17 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @parameterEdit_OpeningFcn, ... 'gui_OutputFcn', @parameterEdit_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before parameterEdit is made visible. function parameterEdit_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to parameterEdit (see VARARGIN) % Choose default command line output for parameterEdit handles.output = hObject; % Display Input variableNames = whos('-file',varargin{2}); % get variable names variableValues = load(varargin{2}); % load varaibles tableData = {}; % initialize table for i = 1:length(variableNames), % iterate over variables tableData{i,1} = variableNames(i).name; % get variable name if strcmp(variableNames(i).class, 'double'), if length(size(variableValues.(variableNames(i).name))) > 1, % handle arrays tableData{i,2} = num2str(variableValues.(variableNames(i).name)); % get variable value else tableData{i,2} = variableValues.(variableNames(i).name); end elseif strcmp(variableNames(i).class, 'char'), tableData{i,2} = variableValues.(variableNames(i).name); end end set(handles.uitable1,'Data',tableData); % set table to display parameters % Update handles structure handles.parameterFile = varargin{2}; % save file location handles.variableNames = variableNames; % save variable data guidata(hObject, handles); % UIWAIT makes parameterEdit wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = parameterEdit_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in save. function save_Callback(hObject, eventdata, handles) % hObject handle to save (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) data = guidata(handles.figure1); % parameterData = load(data.parameterFile); tableData = get(handles.uitable1,'Data'); for i = 1:size(tableData,1), if strcmp(data.variableNames(i).class,'double'), parameterData.(tableData{i,1}) = str2num(tableData{i,2}); elseif strcmp(data.variableNames(i).class,'char'), parameterData.(tableData{i,1}) = tableData{i,2}; end end save(data.parameterFile, '-struct', 'parameterData');
github
sovandas/Modulation-Testing-Tool-master
MIMO_test_est_with_ch_est_adaptive_modulation.m
.m
Modulation-Testing-Tool-master/MIMO OFDM/MIMO_test_est_with_ch_est_adaptive_modulation.m
14,887
utf_8
dc04eabf4637c5a652f42d0a115cb9f9
function [BER, BER_QAM1, BER_QAM2, channel, estimated_channel, SNR1, SNR2] = MIMO_test_est_with_ch_est_adaptive_modulation(input_from_diode_ch1, input_from_diode_ch2, qam_dco_ch1, qam_dco_ch2, M, P, Frames, Nfft, cp_length, omitted_carriers, preamble_length, offset, frame_eq_mult, samples_per_symbol, filter_type, roll_off_factor, Max_Constellation_Size, number_of_pilot_frames) for k=1:log2(Max_Constellation_Size) demodulator{k} = modem.qamdemod('M',2^k,'SymbolOrder','Gray','OutputType','Bit'); %Creates a QAM modulator object for constellation sizes up to Max_Constellation_Size power_rescale(k) = sqrt(demodulator{k}.Constellation()*demodulator{k}.Constellation()'/(2^k)); end BER=[]; BER_QAM1=[]; BER_QAM2=[]; % channel_ch1=[]; % estimated_channel_ch1=[]; % estimated_SNR_ch1=[]; % fitted_SNR_ch1=[]; for counter=1:floor(Frames/frame_eq_mult) [channel_ch11(counter,:), estimated_channel_ch11(counter,:), estimated_SNR_ch11(counter,:), fitted_SNR_ch11(counter,:)] = SM_channel_estimation(input_from_diode_ch1, qam_dco_ch1((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)*(Nfft-2)/2+1:((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft-2)/2), number_of_pilot_frames, Nfft, cp_length, omitted_carriers, preamble_length, offset+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)*(Nfft+cp_length)*samples_per_symbol, samples_per_symbol, filter_type, roll_off_factor); [channel_ch21(counter,:), estimated_channel_ch21(counter,:), estimated_SNR_ch21(counter,:), fitted_SNR_ch21(counter,:)] = SM_channel_estimation(input_from_diode_ch2, qam_dco_ch1((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)*(Nfft-2)/2+1:((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft-2)/2), number_of_pilot_frames, Nfft, cp_length, omitted_carriers, preamble_length, offset+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)*(Nfft+cp_length)*samples_per_symbol, samples_per_symbol, filter_type, roll_off_factor); [channel_ch12(counter,:), estimated_channel_ch12(counter,:), estimated_SNR_ch12(counter,:), fitted_SNR_ch12(counter,:)] = SM_channel_estimation(input_from_diode_ch1, qam_dco_ch2(((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft-2)/2+1:((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2), number_of_pilot_frames, Nfft, cp_length, omitted_carriers, preamble_length, offset+((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft+cp_length)*samples_per_symbol, samples_per_symbol, filter_type, roll_off_factor); [channel_ch22(counter,:), estimated_channel_ch22(counter,:), estimated_SNR_ch22(counter,:), fitted_SNR_ch22(counter,:)] = SM_channel_estimation(input_from_diode_ch2, qam_dco_ch2(((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft-2)/2+1:((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2), number_of_pilot_frames, Nfft, cp_length, omitted_carriers, preamble_length, offset+((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames)*(Nfft+cp_length)*samples_per_symbol, samples_per_symbol, filter_type, roll_off_factor); channel = [channel_ch11; channel_ch12; channel_ch21; channel_ch22]; estimated_channel = [estimated_channel_ch11; estimated_channel_ch12; estimated_channel_ch21; estimated_channel_ch22]; estimated_SNR = [estimated_SNR_ch11; estimated_SNR_ch12; estimated_SNR_ch21; estimated_SNR_ch22]; fitted_SNR = [fitted_SNR_ch11; fitted_SNR_ch12; fitted_SNR_ch21; fitted_SNR_ch22]; qam_recovered_diode_ch1 = recover_ofdm_signal(input_from_diode_ch1, preamble_length+offset+((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft+cp_length)*samples_per_symbol, filter_type, roll_off_factor, frame_eq_mult, Nfft, cp_length, samples_per_symbol); qam_recovered_diode_ch2 = recover_ofdm_signal(input_from_diode_ch2, preamble_length+offset+((counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft+cp_length)*samples_per_symbol, filter_type, roll_off_factor, frame_eq_mult, Nfft, cp_length, samples_per_symbol); %qam_recovered_diode_no_zeros_equalized_ch1=qam_recovered_diode_no_zeros_ch1; qam_recovered_diode_equalized_ch1=[]; qam_recovered_diode_equalized_ch2=[]; current_channel_ch11 = channel_ch11(counter,:); current_channel_ch12 = channel_ch12(counter,:); current_channel_ch21 = channel_ch21(counter,:); current_channel_ch22 = channel_ch22(counter,:); block_length = length(qam_recovered_diode_ch1)/frame_eq_mult; for k=1:frame_eq_mult for l=1:block_length iH = inv([current_channel_ch11(end-block_length+l),current_channel_ch12(end-block_length+l);current_channel_ch21(end-block_length+l),current_channel_ch22(end-block_length+l)]); %Compute the inverse of the channel matrix working_sample_equalized = iH*[qam_recovered_diode_ch1((k-1)*block_length+l);qam_recovered_diode_ch2((k-1)*block_length+l)]; % Equalize a pair of received samples. Since this is OFDM, both the spatial and the temporal channel are equalized qam_recovered_diode_equalized_ch1 = [qam_recovered_diode_equalized_ch1,working_sample_equalized(1)]; qam_recovered_diode_equalized_ch2 = [qam_recovered_diode_equalized_ch2,working_sample_equalized(2)]; end end qam_recovered_diode_no_zeros_ch1=[]; for k=1:frame_eq_mult work_block = qam_recovered_diode_ch1((k-1)*(Nfft-2)/2+1:k*(Nfft-2)/2); %Takes a frame of symbols qam_recovered_diode_no_zeros_ch1 = [qam_recovered_diode_no_zeros_ch1,work_block([zeros(1,omitted_carriers),M(1,:)]~=0)./sqrt(P(1,M(1,:)~=0))]; %Removes all zeros from that symbol frame and rescales by the assigned power end qam_recovered_diode_no_zeros_ch2=[]; for k=1:frame_eq_mult work_block = qam_recovered_diode_ch2((k-1)*(Nfft-2)/2+1:k*(Nfft-2)/2); %Takes a frame of symbols qam_recovered_diode_no_zeros_ch2 = [qam_recovered_diode_no_zeros_ch2,work_block([zeros(1,omitted_carriers),M(2,:)]~=0)./sqrt(P(2,M(2,:)~=0))]; %Removes all zeros from that symbol frame and rescales by the assigned power end qam_recovered_diode_no_zeros_equalized_ch1=[]; for k=1:frame_eq_mult work_block = qam_recovered_diode_equalized_ch1((k-1)*(Nfft-2)/2+1:k*(Nfft-2)/2); %Takes a frame of symbols qam_recovered_diode_no_zeros_equalized_ch1 = [qam_recovered_diode_no_zeros_equalized_ch1,work_block([zeros(1,omitted_carriers),M(1,:)]~=0)./sqrt(P(1,M(1,:)~=0))]; %Removes all zeros from that symbol frame and rescales by the assigned power end qam_recovered_diode_no_zeros_equalized_ch2=[]; for k=1:frame_eq_mult work_block = qam_recovered_diode_equalized_ch2((k-1)*(Nfft-2)/2+1:k*(Nfft-2)/2); %Takes a frame of symbols qam_recovered_diode_no_zeros_equalized_ch2 = [qam_recovered_diode_no_zeros_equalized_ch2,work_block([zeros(1,omitted_carriers),M(2,:)]~=0)./sqrt(P(2,M(2,:)~=0))]; %Removes all zeros from that symbol frame and rescales by the assigned power end qam_dco_no_zeros_ch1=[]; for k=1:frame_eq_mult work_block = qam_dco_ch1((k-1+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2+1:(k+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2); qam_dco_no_zeros_ch1 = [qam_dco_no_zeros_ch1,work_block([zeros(1,omitted_carriers),M(1,:)]~=0)./sqrt(P(1,M(1,:)~=0))]; end qam_dco_no_zeros_ch2=[]; for k=1:frame_eq_mult work_block = qam_dco_ch2((k-1+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2+1:(k+(counter-1)*(frame_eq_mult+number_of_pilot_frames*2)+number_of_pilot_frames*2)*(Nfft-2)/2); qam_dco_no_zeros_ch2 = [qam_dco_no_zeros_ch2,work_block([zeros(1,omitted_carriers),M(2,:)]~=0)./sqrt(P(2,M(2,:)~=0))]; end for k=1:log2(Max_Constellation_Size) points_of_same_size_received{k}=[]; points_of_same_size_received_equalized{k}=[]; points_of_same_size_original{k}=[]; end original_QAM_bits1=[]; original_QAM_bits2=[]; received_QAM_bits1=[]; received_QAM_bits2=[]; M_without_zeros1 = M(1,M(1,:)~=0); M_without_zeros2 = M(2,M(2,:)~=0); block_length = length(qam_recovered_diode_no_zeros_equalized_ch1)/frame_eq_mult; for k=1:frame_eq_mult for l=1:block_length qam_recovered_diode_no_zeros_rescaled_ch1((k-1)*block_length+l) = qam_recovered_diode_no_zeros_ch1((k-1)*block_length+l)*power_rescale(log2(M_without_zeros1(l))); points_of_same_size_received{log2(M_without_zeros1(l))} = [points_of_same_size_received{log2(M_without_zeros1(l))},qam_recovered_diode_no_zeros_rescaled_ch1((k-1)*block_length+l)]; qam_recovered_diode_no_zeros_equalized_rescaled_ch1((k-1)*block_length+l) = qam_recovered_diode_no_zeros_equalized_ch1((k-1)*block_length+l)*power_rescale(log2(M_without_zeros1(l))); points_of_same_size_received_equalized{log2(M_without_zeros1(l))} = [points_of_same_size_received_equalized{log2(M_without_zeros1(l))},qam_recovered_diode_no_zeros_equalized_rescaled_ch1((k-1)*block_length+l)]; qam_dco_no_zeros_rescaled_ch1((k-1)*block_length+l) = qam_dco_no_zeros_ch1((k-1)*block_length+l)*power_rescale(log2(M_without_zeros1(l))); points_of_same_size_original{log2(M_without_zeros1(l))} = [points_of_same_size_original{log2(M_without_zeros1(l))},qam_dco_no_zeros_rescaled_ch1((k-1)*block_length+l)]; received_QAM_bits1 = [received_QAM_bits1,demodulate(demodulator{log2(M_without_zeros1(l))}, qam_recovered_diode_no_zeros_equalized_rescaled_ch1((k-1)*block_length+l)).']; original_QAM_bits1 = [original_QAM_bits1,demodulate(demodulator{log2(M_without_zeros1(l))},qam_dco_no_zeros_rescaled_ch1((k-1)*block_length+l))']; end end % Using the demodulated data to esitmated the SNR since it is dependent on the cross-talk. signal_energy1=zeros(1,block_length); noise_energy1=zeros(1,block_length); for k=1:frame_eq_mult signal_energy1 = signal_energy1 + qam_recovered_diode_no_zeros_equalized_rescaled_ch1((k-1)*block_length+1:k*block_length).*conj(qam_recovered_diode_no_zeros_equalized_rescaled_ch1((k-1)*block_length+1:k*block_length)); noise_energy1 = noise_energy1 + (qam_recovered_diode_no_zeros_equalized_rescaled_ch1((k-1)*block_length+1:k*block_length) - qam_dco_no_zeros_rescaled_ch1((k-1)*block_length+1:k*block_length)).*... conj(qam_recovered_diode_no_zeros_equalized_rescaled_ch1((k-1)*block_length+1:k*block_length) - qam_dco_no_zeros_rescaled_ch1((k-1)*block_length+1:k*block_length)); end polynomial_degree=5; SNR1(counter,:) = polyval(polyfit([1:length(signal_energy1)],signal_energy1./noise_energy1,polynomial_degree),[1:length(signal_energy1)]); figure, plot(10*log10(SNR1(counter,:))), hold on, plot(10*log10(signal_energy1./noise_energy1),'r'); title('Channel 1 Achievable SNR'); block_length = length(qam_recovered_diode_no_zeros_equalized_ch2)/frame_eq_mult; for k=1:frame_eq_mult for l=1:block_length qam_recovered_diode_no_zeros_rescaled_ch2((k-1)*block_length+l) = qam_recovered_diode_no_zeros_ch2((k-1)*block_length+l)*power_rescale(log2(M_without_zeros2(l))); points_of_same_size_received{log2(M_without_zeros2(l))} = [points_of_same_size_received{log2(M_without_zeros2(l))},qam_recovered_diode_no_zeros_rescaled_ch2((k-1)*block_length+l)]; qam_recovered_diode_no_zeros_equalized_rescaled_ch2((k-1)*block_length+l) = qam_recovered_diode_no_zeros_equalized_ch2((k-1)*block_length+l)*power_rescale(log2(M_without_zeros2(l))); points_of_same_size_received_equalized{log2(M_without_zeros2(l))} = [points_of_same_size_received_equalized{log2(M_without_zeros2(l))},qam_recovered_diode_no_zeros_equalized_rescaled_ch2((k-1)*block_length+l)]; qam_dco_no_zeros_rescaled_ch2((k-1)*block_length+l) = qam_dco_no_zeros_ch2((k-1)*block_length+l)*power_rescale(log2(M_without_zeros2(l))); points_of_same_size_original{log2(M_without_zeros2(l))} = [points_of_same_size_original{log2(M_without_zeros2(l))},qam_dco_no_zeros_rescaled_ch2((k-1)*block_length+l)]; received_QAM_bits2 = [received_QAM_bits2,demodulate(demodulator{log2(M_without_zeros2(l))}, qam_recovered_diode_no_zeros_equalized_rescaled_ch2((k-1)*block_length+l)).']; original_QAM_bits2 = [original_QAM_bits2,demodulate(demodulator{log2(M_without_zeros2(l))},qam_dco_no_zeros_rescaled_ch2((k-1)*block_length+l))']; end end % Using the demodulated data to esitmated the SNR since it is dependent on the cross-talk. signal_energy2=zeros(1,block_length); noise_energy2=zeros(1,block_length); for k=1:frame_eq_mult signal_energy2 = signal_energy2 + qam_recovered_diode_no_zeros_equalized_rescaled_ch2((k-1)*block_length+1:k*block_length).*conj(qam_recovered_diode_no_zeros_equalized_rescaled_ch2((k-1)*block_length+1:k*block_length)); noise_energy2 = noise_energy2 + (qam_recovered_diode_no_zeros_equalized_rescaled_ch2((k-1)*block_length+1:k*block_length) - qam_dco_no_zeros_rescaled_ch2((k-1)*block_length+1:k*block_length)).*... conj(qam_recovered_diode_no_zeros_equalized_rescaled_ch2((k-1)*block_length+1:k*block_length) - qam_dco_no_zeros_rescaled_ch2((k-1)*block_length+1:k*block_length)); end polynomial_degree=5; SNR2(counter,:) = polyval(polyfit([1:length(signal_energy2)],signal_energy2./noise_energy2,polynomial_degree),[1:length(signal_energy2)]); figure, plot(10*log10(SNR2(counter,:))), hold on, plot(10*log10(signal_energy2./noise_energy2),'r'); title('Channel 2 Achievable SNR'); for k=1:log2(Max_Constellation_Size) if length(points_of_same_size_received{k})>0 && length(points_of_same_size_received_equalized{k})>0 && length(points_of_same_size_original{k})>0 scatterplot(points_of_same_size_received{k}); scatterplot(points_of_same_size_received_equalized{k}); scatterplot(points_of_same_size_original{k}); end end BER_QAM1(counter) = sum(sum(xor(original_QAM_bits1, received_QAM_bits1)))/length(original_QAM_bits1) BER_QAM2(counter) = sum(sum(xor(original_QAM_bits2, received_QAM_bits2)))/length(original_QAM_bits2) BER(counter) = (BER_QAM1*length(original_QAM_bits1) + BER_QAM2*length(original_QAM_bits2))/(length(original_QAM_bits1) + length(original_QAM_bits2)) end
github
sqjin/scEpath-master
clusteringCells.m
.m
scEpath-master/clusteringCells.m
4,523
utf_8
855d58cac5df9078e81f48eb4516b78c
function [y, S] = clusteringCells(data,networkIfo,C,clusterRange,showFigure) % perform unsupervised clustering of single cell data % Inputs: % data: single cell data (rows are genes and columns are cells) % networkIfo: network information for the constructed gene-gene network % C: number of clusters, by default automatically choosing based on eigengap % clusterRange: a vector,the range of potential clusters when automatically choosing the number of clusters, default=2:10 % showFigure: boolean, to show the similarity matrix or not, default= 1 (true) % Outputs: % y is the cluster label of each cell % S is the similarity matrix if ~exist('showFigure','var') || isempty(showFigure) showFigure = 1; end if ~exist('C','var') C = []; end if ~exist('clusterRange','var') || isempty(clusterRange) clusterRange = 3:10; end data = data(networkIfo.IDselect,:); rng('default'); %%% for reproducibility %% check if SIMLR has been successfully installed (https://github.com/BatzoglouLabSU/SIMLR) try SIMLR(data(1:min(50,size(data,1)),1:20)',2); catch INSTALL_SIMLR % compile external C program for the computations of SIMLR end %% if isempty(C) for c = clusterRange [y, S] = SIMLR(data',c,10); K1 = EstimateNumberClusters(abs(S), clusterRange,0); if isequal(K1,c) K1 = EstimateNumberClusters(abs(S), clusterRange,1); break; end end else [y, S] = SIMLR(data',C,10); end %% visualization of similarity matrix if showFigure [~,labelOrdered] = sort(y); Ssym = (abs(S)+abs(S'))/2; SsymOrdered = Ssym(labelOrdered,labelOrdered); SsymOrdered(logical(eye(size(SsymOrdered)))) = 0; hFig2 = figure; imagesc(SsymOrdered); axis square; colormap hot; c = colorbar; c.Location = 'eastoutside'; % c.Label.String = 'Similarity'; % c.Label.FontSize = 8;%c.Label.FontWeight = 'bold'; c.FontSize = 8; set(gca,'FontSize',8) xlim([0.5 length(y)+0.5]); xlabel('Cells','FontName','Arial','FontSize',10) ylabel('Cells','FontName','Arial','FontSize',10) folderName = fullfile(pwd,'results','figures'); if ~exist(folderName, 'dir') mkdir(folderName); end saveas(hFig2,fullfile(folderName,'cell_similarity_matrix.pdf')) end function [K1, K12,eigengap] = EstimateNumberClusters(W, NUMC,showFigure) %%%This function estimates the number of clusters using eigengap %W is the similarity graph %NUMC is a vector which contains the possible choices of number of clusters. %%K1 is the estimated best number of clusters according to eigen-gaps %%K12 is the estimated SECOND best number of clusters according to eigen-gaps % an example would be [K1, K12,eigengap] = Estimate_Number_of_Clusters_given_graph(W, [2:5]); %%Note that this function can only give an estimate of the number of %%clusters. How to determine the "OPTIMAL" number of clusters, is still an %%open question so far. if nargin < 2 NUMC = 2:10; end if min(NUMC)==1 warning('Note that we always assume there are more than one cluster.'); NUMC(NUMC<=1) = []; end W = (W + W')/2; W = W - diag(diag(W)); if ~isempty(NUMC) degs = sum(W, 2); D = sparse(1:size(W, 1), 1:size(W, 2), degs); % compute unnormalized Laplacian L = D - W; degs(degs == 0) = eps; % calculate D^(-1/2) D = spdiags(1./(degs.^0.5), 0, size(D, 1), size(D, 2)); % calculate normalized Laplacian L = D * L * D; % compute the eigenvectors corresponding to the k smallest % eigenvalues [U, eigenvalue] = eigs(L, max(NUMC)+1, eps); eigenvalue = diag(eigenvalue); [a,b] = sort((eigenvalue),'ascend'); eigenvalue = (eigenvalue(b)); eigengap = abs(diff(eigenvalue)); [tt1, t1] = sort(eigengap(NUMC),'descend');K1 = NUMC(t1(1));K12 = NUMC(t1(2)); end if ~exist('showFigure','var') showFigure = 1; end if showFigure hFig1 = figure; plot(NUMC,eigengap(NUMC),'k-') hold on scatter(K1,tt1(1),20,'r','filled') line([K1,K1],[0 tt1(1)],'Color','red','LineStyle','--') xlabel('Number of clusters','FontName','Arial','FontSize',10) ylabel('Eigengap','FontName','Arial','FontSize',10) set(gca,'Xtick',NUMC) folderName = fullfile(pwd,'results','figures'); if ~exist(folderName, 'dir') mkdir(folderName); end saveas(hFig1,fullfile(folderName,'eigenGap.pdf')) end
github
sqjin/scEpath-master
constructingNetwork.m
.m
scEpath-master/constructingNetwork.m
4,418
utf_8
07b464ae3eba9965f313e9cab6e15ed9
function networkIfo = constructingNetwork(data,quick_construct,thresh,thresh_percent,showFigure,fig_width,fig_height) % construct a gene-gene co-expression network % Inputs: % data: single cell data (rows are cells and columns are genes) % quick_construct: default=0,the network will be constructed by choosing the highest threshold without a significant reduction in the number of genes; % thresh: if quick_construct=1, thresh is the threshold for constructing a network. default = 0.1 % thresh_percent: the percentage threshold for indicating a significant reduction in the number of genes % showFigure: boolean, to show the network metrics or not, default= 1 (true) % fig_width : the figure width, default=800 % fig_height : the figure height, default=250 % Outputs: % networkIfo: network information for the constructed gene-gene network % networkIfo.R: adjacency matrix (upper matrix) of the constructed network % networkIfo.IDselect: the index of selected genes in the constructed network % networkIfo.deg: the connectivity (degree) of each node % networkIfo.reduction_percent; the percentage of reduction in the number of nodes with different threshold tau % networkIfo.tau; the range of threshold tau if ~exist('thresh_percent','var') || isempty(thresh_percent) thresh_percent = 0.2; % 20% reduction in the number of nodes end if ~exist('showFigure','var') || isempty(showFigure) showFigure = 1; end if ~exist('fig_width', 'var') || isempty(fig_width) fig_width = 600; end if ~exist('fig_height', 'var') || isempty(fig_height) fig_height = 180; end R00 = corr(data,'Type','Spearman'); R00 = triu(R00,1); R00 = sparse(R00); R00 = abs(R00); total_nodes = size(R00,1); if quick_construct || total_nodes < 50 if ~exist('thresh','var') || isempty(thresh),thresh = 0.1; end threshSig = thresh; [R,IDselect,deg] = calculatingAdjacencyMatrix(R00,threshSig); num_nodes = length(IDselect);num_edges = nnz(R); reduction_percent = (total_nodes-num_nodes)/total_nodes; else [thresh,num_nodes,num_edges] = calculatingNetworkMetrics(R00); % reduction_percent = [0,-diff(num_nodes)./num_nodes(1:end-1)]; reduction_percent = (total_nodes-num_nodes)/total_nodes; idx = find(reduction_percent > thresh_percent,1); threshSig = thresh(idx-1); [R,IDselect,deg] = calculatingAdjacencyMatrix(R00,threshSig); end networkIfo.R = R; networkIfo.IDselect = IDselect; networkIfo.deg = deg; networkIfo.reduction_percent = reduction_percent;networkIfo.tau = thresh; if showFigure hFig = figure('position', [600, 200, fig_width, fig_height]); subplot(1,3,1) plot(thresh,num_nodes,'k-o') ylim([0 total_nodes*1.05]) xlim([0.05 0.85]) xlabel('\tau','FontName','Arial','FontSize',10); ylabel('Number of nodes','FontName','Arial','FontSize',10); box on grid on subplot(1,3,2) plot(thresh,reduction_percent*100,'k-o') ylim([0 100]) xlim([0.05 0.85]) xlabel('\tau','FontName','Arial','FontSize',10); ylabel({'Percentage of reduction', 'in the number of nodes'},'FontName','Arial','FontSize',10); ytickformat('percentage') grid on box on subplot(1,3,3) plot(thresh,num_edges,'k-o') xlim([0.05 0.85]) xlabel('\tau','FontName','Arial','FontSize',10); ylabel('Number of edges','FontName','Arial','FontSize',10); box on grid on folderName = fullfile(pwd,'results','figures'); if ~exist(folderName, 'dir') mkdir(folderName); end saveas(hFig,fullfile(folderName,'topological_metrics_gene_network.pdf')) end function [thresh,num_nodes,num_edges] = calculatingNetworkMetrics(R00) thresh = 0.1:0.1:0.8; num_nodes = zeros(1,length(thresh)); num_edges = zeros(1,length(thresh)); for i = 1:length(thresh) [R,IDselect] = calculatingAdjacencyMatrix(R00,thresh(i)); num_edges(i) = nnz(R); num_nodes(i) = length(IDselect); sprintf('When tau is %.2f, the number of nodes is %d.',thresh(i),length(IDselect)) end function [R,IDselect,deg] = calculatingAdjacencyMatrix(R,thresh) R = R>thresh; G = graph(R,'upper'); comp = conncomp(G,'OutputForm','cell'); [~,idx] = max(cellfun('length',comp)); IDselect = comp{idx}; R = R(IDselect,IDselect); G = graph(R,'upper'); deg = degree(G);
github
sqjin/scEpath-master
optimal_SVHT_coef.m
.m
scEpath-master/optimal_SVHT_coef.m
4,578
utf_8
601f5430e4282be5998f855bc038b18f
function coef = optimal_SVHT_coef(beta, sigma_known) % function omega = optimal_SVHT_coef(beta, sigma_known) % % Coefficient determining optimal location of Hard Threshold for Matrix % Denoising by Singular Values Hard Thresholding when noise level is known or % unknown. % % See D. L. Donoho and M. Gavish, "The Optimal Hard Threshold for Singular % Values is 4/sqrt(3)", http://arxiv.org/abs/1305.5870 % % IN: % beta: aspect ratio m/n of the matrix to be denoised, 0<beta<=1. % beta may be a vector % sigma_known: 1 if noise level known, 0 if unknown % % OUT: % coef: optimal location of hard threshold, up the median data singular % value (sigma unknown) or up to sigma*sqrt(n) (sigma known); % a vector of the same dimension as beta, where coef(i) is the % coefficient correcponding to beta(i) % % % % Usage in unknown noise level: % % Given an m-by-n matrix Y known to be low rank and observed in white % noise with mean zero and unknown variance % % [U D V] = svd(Y); % y = diag(Y); % y( y < (optimal_SVHT_coef_sigma_unknown(m/n,0) * median(y)) ) = 0; % % ----------------------------------------------------------------------------- % Authors: Matan Gavish and David Donoho <lastname>@stanford.edu, 2013 % % This program is free software: you can redistribute it and/or modify it under % the terms of the GNU General Public License as published by the Free Software % Foundation, either version 3 of the License, or (at your option) any later % version. % % 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, see <http://www.gnu.org/licenses/>. % ----------------------------------------------------------------------------- if sigma_known coef = optimal_SVHT_coef_sigma_known(beta); else coef = optimal_SVHT_coef_sigma_unknown(beta); end end function lambda_star = optimal_SVHT_coef_sigma_known(beta) assert(all(beta>0)); assert(all(beta<=1)); assert(prod(size(beta)) == length(beta)); % beta must be a vector w = (8 * beta) ./ (beta + 1 + sqrt(beta.^2 + 14 * beta +1)); lambda_star = sqrt(2 * (beta + 1) + w); end function omega = optimal_SVHT_coef_sigma_unknown(beta) warning('off','MATLAB:quadl:MinStepSize') assert(all(beta>0)); assert(all(beta<=1)); assert(prod(size(beta)) == length(beta)); % beta must be a vector coef = optimal_SVHT_coef_sigma_known(beta); MPmedian = zeros(size(beta)); for i=1:length(beta) MPmedian(i) = MedianMarcenkoPastur(beta(i)); end omega = coef ./ sqrt(MPmedian); end function I = MarcenkoPasturIntegral(x,beta) if beta <= 0 | beta > 1, error('beta beyond') end lobnd = (1 - sqrt(beta))^2; hibnd = (1 + sqrt(beta))^2; if (x < lobnd) | (x > hibnd), error('x beyond') end dens = @(t) sqrt((hibnd-t).*(t-lobnd))./(2*pi*beta.*t); I = quadl(dens,lobnd,x); fprintf('x=%.3f,beta=%.3f,I=%.3f\n',x,beta,I); end function med = MedianMarcenkoPastur(beta) MarPas = @(x) 1-incMarPas(x,beta,0); lobnd = (1 - sqrt(beta))^2; hibnd = (1 + sqrt(beta))^2; change = 1; while change & (hibnd - lobnd > .001), change = 0; x = linspace(lobnd,hibnd,5); for i=1:length(x), y(i) = MarPas(x(i)); end if any(y < 0.5), lobnd = max(x(y < 0.5)); change = 1; end if any(y > 0.5), hibnd = min(x(y > 0.5)); change = 1; end end med = (hibnd+lobnd)./2; end function I = incMarPas(x0,beta,gamma) if beta > 1, error('betaBeyond'); end topSpec = (1 + sqrt(beta))^2; botSpec = (1 - sqrt(beta))^2; MarPas = @(x) IfElse((topSpec-x).*(x-botSpec) >0, ... sqrt((topSpec-x).*(x-botSpec))./(beta.* x)./(2 .* pi), ... 0); if gamma ~= 0, fun = @(x) (x.^gamma .* MarPas(x)); else fun = @(x) MarPas(x); end I = quadl(fun,x0,topSpec); function y=IfElse(Q,point,counterPoint) y = point; if any(~Q), if length(counterPoint) == 1, counterPoint = ones(size(Q)).*counterPoint; end y(~Q) = counterPoint(~Q); end end end
github
sqjin/scEpath-master
distinguishable_colors.m
.m
scEpath-master/enternal/distinguishable_colors.m
5,753
utf_8
57960cf5d13cead2f1e291d1288bccb2
function colors = distinguishable_colors(n_colors,bg,func) % DISTINGUISHABLE_COLORS: pick colors that are maximally perceptually distinct % % When plotting a set of lines, you may want to distinguish them by color. % By default, Matlab chooses a small set of colors and cycles among them, % and so if you have more than a few lines there will be confusion about % which line is which. To fix this problem, one would want to be able to % pick a much larger set of distinct colors, where the number of colors % equals or exceeds the number of lines you want to plot. Because our % ability to distinguish among colors has limits, one should choose these % colors to be "maximally perceptually distinguishable." % % This function generates a set of colors which are distinguishable % by reference to the "Lab" color space, which more closely matches % human color perception than RGB. Given an initial large list of possible % colors, it iteratively chooses the entry in the list that is farthest (in % Lab space) from all previously-chosen entries. While this "greedy" % algorithm does not yield a global maximum, it is simple and efficient. % Moreover, the sequence of colors is consistent no matter how many you % request, which facilitates the users' ability to learn the color order % and avoids major changes in the appearance of plots when adding or % removing lines. % % Syntax: % colors = distinguishable_colors(n_colors) % Specify the number of colors you want as a scalar, n_colors. This will % generate an n_colors-by-3 matrix, each row representing an RGB % color triple. If you don't precisely know how many you will need in % advance, there is no harm (other than execution time) in specifying % slightly more than you think you will need. % % colors = distinguishable_colors(n_colors,bg) % This syntax allows you to specify the background color, to make sure that % your colors are also distinguishable from the background. Default value % is white. bg may be specified as an RGB triple or as one of the standard % "ColorSpec" strings. You can even specify multiple colors: % bg = {'w','k'} % or % bg = [1 1 1; 0 0 0] % will only produce colors that are distinguishable from both white and % black. % % colors = distinguishable_colors(n_colors,bg,rgb2labfunc) % By default, distinguishable_colors uses the image processing toolbox's % color conversion functions makecform and applycform. Alternatively, you % can supply your own color conversion function. % % Example: % c = distinguishable_colors(25); % figure % image(reshape(c,[1 size(c)])) % % Example using the file exchange's 'colorspace': % func = @(x) colorspace('RGB->Lab',x); % c = distinguishable_colors(25,'w',func); % Copyright 2010-2011 by Timothy E. Holy % Parse the inputs if (nargin < 2) bg = [1 1 1]; % default white background else if iscell(bg) % User specified a list of colors as a cell aray bgc = bg; for i = 1:length(bgc) bgc{i} = parsecolor(bgc{i}); end bg = cat(1,bgc{:}); else % User specified a numeric array of colors (n-by-3) bg = parsecolor(bg); end end % Generate a sizable number of RGB triples. This represents our space of % possible choices. By starting in RGB space, we ensure that all of the % colors can be generated by the monitor. n_grid = 30; % number of grid divisions along each axis in RGB space x = linspace(0,1,n_grid); [R,G,B] = ndgrid(x,x,x); rgb = [R(:) G(:) B(:)]; if (n_colors > size(rgb,1)/3) error('You can''t readily distinguish that many colors'); end % Convert to Lab color space, which more closely represents human % perception if (nargin > 2) lab = func(rgb); bglab = func(bg); else C = makecform('srgb2lab'); lab = applycform(rgb,C); bglab = applycform(bg,C); end % If the user specified multiple background colors, compute distances % from the candidate colors to the background colors mindist2 = inf(size(rgb,1),1); for i = 1:size(bglab,1)-1 dX = bsxfun(@minus,lab,bglab(i,:)); % displacement all colors from bg dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color end % Iteratively pick the color that maximizes the distance to the nearest % already-picked color colors = zeros(n_colors,3); lastlab = bglab(end,:); % initialize by making the "previous" color equal to background for i = 1:n_colors dX = bsxfun(@minus,lab,lastlab); % displacement of last from all colors on list dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color [~,index] = max(mindist2); % find the entry farthest from all previously-chosen colors colors(i,:) = rgb(index,:); % save for output lastlab = lab(index,:); % prepare for next iteration end end function c = parsecolor(s) if ischar(s) c = colorstr2rgb(s); elseif isnumeric(s) && size(s,2) == 3 c = s; else error('MATLAB:InvalidColorSpec','Color specification cannot be parsed.'); end end function c = colorstr2rgb(c) % Convert a color string to an RGB value. % This is cribbed from Matlab's whitebg function. % Why don't they make this a stand-alone function? rgbspec = [1 0 0;0 1 0;0 0 1;1 1 1;0 1 1;1 0 1;1 1 0;0 0 0]; cspec = 'rgbwcmyk'; k = find(cspec==c(1)); if isempty(k) error('MATLAB:InvalidColorString','Unknown color string.'); end if k~=3 || length(c)==1, c = rgbspec(k,:); elseif length(c)>2, if strcmpi(c(1:3),'bla') c = [0 0 0]; elseif strcmpi(c(1:3),'blu') c = [0 0 1]; else error('MATLAB:UnknownColorString', 'Unknown color string.'); end end end
github
sqjin/scEpath-master
SIMLR_LARGE.m
.m
scEpath-master/enternal/SIMLR/src/SIMLR_LARGE.m
3,824
utf_8
d93d9e5fe003f6e721edf44251075283
function [S0, F] = SIMLR_LARGE(X, c, k, ifimpute,normalize) %%% if nargin==2 k=10; ifimpute = 0; normalize = 0; end if nargin==3 ifimpute = 0; normalize = 0; end if nargin==4 normalize = 0; end if ifimpute X = X'; [I,J] = find(X==0); Xmean = mean(X); X(sub2ind(size(X),I,J)) = Xmean(J); X = X'; end if normalize X = X'; X = X - min(X(:)); X = X / max(X(:)); X = bsxfun(@minus, X, mean(X, 1)); X = X'; end NITER = 5; r = -1; beta = 0.8; [ind, val] = mex_KNN_Annoy(X,2*k); ind = ind + 1; val = double((abs(val))); %%%%construct multiple kernels D_Kernels = mex_multipleK(val, ind,k); %D_Kernels are of size Nx(2k)x55 clear val alphaK = 1/(size(D_Kernels,3))*ones(1,size(D_Kernels,3)); distX = mean(D_Kernels,3); di = distX(:,2:(k+2)); rr = 0.5*(k*di(:,k+1)-sum(di(:,1:k),2)); if r <= 0 r = mean(rr); end lambda = max((mean(rr)),0); clear rr di %A(isnan(A))=0; S0 = max(max(distX))-distX; %S0(:,1) = S0(:,1) + sum(S0,2); S0 = NE_dn(S0,'ave'); [F,evalues] = mex_top_eig_svd(S0, ind, c); d = evalues/max(evalues); d = (1-beta)*d./(1-beta*d.^2); F =F.*repmat((d+eps)', length(F),1); F = NE_dn(F,'ave'); F0 = F; for iter = 1:NITER distf = mex_L2_distance_1(F, ind); distf = (distX+lambda*distf)/2/r; distf = projsplx_c(-distf')'; S0 = (1-beta)*S0+(beta)*distf; [F,evalues] = mex_top_eig_svd(S0, ind, c); d = evalues/max(evalues); d = (1-beta)*d./(1-beta*d.^2); F =F.*repmat((d+eps)', length(F),1); F = NE_dn(F,'ave'); F = (1-beta)*F0+(beta)*F; F0 = F; for i = 1:size(D_Kernels,3) temp = (eps+D_Kernels(:,:,i)).*(eps+S0); DD(i) = mean(sum(temp)); end alphaK0 = umkl_bo(DD); alphaK0 = alphaK0/sum(alphaK0); alphaK = (1-beta)*alphaK + beta*alphaK0; alphaK = alphaK/sum(alphaK); lambda = 1.5*lambda; r = r/1.1; distX = Kbeta(D_Kernels,alphaK'); end; val = S0; I = repmat([1:size(S0,1)]',1,size(S0,2)); S0 = sparse(I(:), ind(:), S0(:)/2.0, size(S0,1),size(S0,1)) + sparse(ind(:), I(:), S0(:)/2.0, size(S0,1),size(S0,1)); ydata = []; y = []; end function thisP = umkl_bo(D,beta) if nargin<2 beta = 1/length(D); end tol = 1e-4; u = 20;logU = log(u); [H, thisP] = Hbeta(D, beta); betamin = -Inf; betamax = Inf; % Evaluate whether the perplexity is within tolerance Hdiff = H - logU; tries = 0; while (abs(Hdiff) > tol) && (tries < 30) % If not, increase or decrease precision if Hdiff > 0 betamin = beta; if isinf(betamax) beta = beta * 2; else beta = (beta + betamax) / 2; end else betamax = beta; if isinf(betamin) beta = beta / 2; else beta = (beta + betamin) / 2; end end % Recompute the values [H, thisP] = Hbeta(D, beta); Hdiff = H - logU; tries = tries + 1; end end function [H, P] = Hbeta(D, beta) D = (D-min(D))/(max(D) - min(D)+eps); P = exp(-D * beta); sumP = sum(P); H = log(sumP) + beta * sum(D .* P) / sumP; P = P / sumP; end function D_kernels = mex_multipleK(val,ind,KK) if nargin<3 KK=20; end val = val.*val; sigma = [2:-0.25:1]; allk = [ceil(KK/2):ceil(KK/10):(ceil(KK*1.5))]; t = 1; for i = 1:length(allk) if allk(i)< size(val,2) temp = mean(val(:,1:allk(i)),2); temp0 = .5*(repmat(temp,1,size(val,2)) + temp(ind))+eps; for j = 1:length(sigma) temp = normpdf(val, 0, sigma(j)*temp0); temptemp = temp(:,1); temp = .5*(repmat(temptemp,1,size(val,2)) + temptemp(ind)) - temp; D_kernels(:,:,t) = temp+eps; t = t+1; end end end end function distf = mex_L2_distance_1(F, ind) [m,n] = size(ind); I = repmat([1:m]',1,n); temp = sum((F(I(:),:) - F(ind(:),:)).^2,2); distf = zeros(m,n); distf(:) = temp; end
github
sqjin/scEpath-master
fast_pca.m
.m
scEpath-master/enternal/SIMLR/src/fast_pca.m
997
utf_8
faf27f941117e07978072249dcc5a39d
function X = fast_pca(in_X, K) in_X = in_X - repmat(mean(in_X),size(in_X,1),1); [U, S, ~] = rsvd(in_X, K); K = min(size(S,2),K); X = U(:,1:K)*diag(sqrt(diag(S(1:K,1:K)))); X = X./repmat(sqrt(sum(X.*X,2)),1,K); end function [U,S,V] = rsvd(A,K) %------------------------------------------------------------------------------------- % random SVD % Extremely fast computation of the truncated Singular Value Decomposition, using % randomized algorithms as described in Halko et al. 'finding structure with randomness % % usage : % % input: % * A : matrix whose SVD we want % * K : number of components to keep % % output: % * U,S,V : classical output as the builtin svd matlab function %------------------------------------------------------------------------------------- % Antoine Liutkus (c) Inria 2014 [M,N] = size(A); P = min(2*K,N); X = randn(N,P); Y = A*X; W1 = orth(Y); B = W1'*A; [W2,S,V] = svd(B,'econ'); U = W1*W2; K=min(K,size(U,2)); U = U(:,1:K); S = S(1:K,1:K); V=V(:,1:K); end
github
sqjin/scEpath-master
L2_distance_1.m
.m
scEpath-master/enternal/SIMLR/src/L2_distance_1.m
508
utf_8
163a4a02852578aabe7c4660b447694b
% compute squared Euclidean distance % ||A-B||^2 = ||A||^2 + ||B||^2 - 2*A'*B function d = L2_distance_1(a,b) % a,b: two matrices. each column is a data % d: distance matrix of a and b if (size(a,1) == 1) a = [a; zeros(1,size(a,2))]; b = [b; zeros(1,size(b,2))]; end aa=sum(a.*a); bb=sum(b.*b); ab=a'*b; d = repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab; d = real(d); d = max(d,0); % % force 0 on the diagonal? d = d.*(1-eye(size(d))); %d = d/size(a,1)^2;
github
sqjin/scEpath-master
colorspace.m
.m
scEpath-master/enternal/SIMLR/src/colorspace.m
16,178
utf_8
2ca0aee9ae4d0f5c12a7028c45ef2b8d
function varargout = colorspace(Conversion,varargin) %COLORSPACE Transform a color image between color representations. % B = COLORSPACE(S,A) transforms the color representation of image A % where S is a string specifying the conversion. The input array A % should be a real full double array of size Mx3 or MxNx3. The output B % is the same size as A. % % S tells the source and destination color spaces, S = 'dest<-src', or % alternatively, S = 'src->dest'. Supported color spaces are % % 'RGB' sRGB IEC 61966-2-1 % 'YCbCr' Luma + Chroma ("digitized" version of Y'PbPr) % 'JPEG-YCbCr' Luma + Chroma space used in JFIF JPEG % 'YDbDr' SECAM Y'DbDr Luma + Chroma % 'YPbPr' Luma (ITU-R BT.601) + Chroma % 'YUV' NTSC PAL Y'UV Luma + Chroma % 'YIQ' NTSC Y'IQ Luma + Chroma % 'HSV' or 'HSB' Hue Saturation Value/Brightness % 'HSL' or 'HLS' Hue Saturation Luminance % 'HSI' Hue Saturation Intensity % 'XYZ' CIE 1931 XYZ % 'Lab' CIE 1976 L*a*b* (CIELAB) % 'Luv' CIE L*u*v* (CIELUV) % 'LCH' CIE L*C*H* (CIELCH) % 'CAT02 LMS' CIE CAT02 LMS % % All conversions assume 2 degree observer and D65 illuminant. % % Color space names are case insensitive and spaces are ignored. When % sRGB is the source or destination, it can be omitted. For example % 'yuv<-' is short for 'yuv<-rgb'. % % For sRGB, the values should be scaled between 0 and 1. Beware that % transformations generally do not constrain colors to be "in gamut." % Particularly, transforming from another space to sRGB may obtain % R'G'B' values outside of the [0,1] range. So the result should be % clamped to [0,1] before displaying: % image(min(max(B,0),1)); % Clamp B to [0,1] and display % % sRGB (Red Green Blue) is the (ITU-R BT.709 gamma-corrected) standard % red-green-blue representation of colors used in digital imaging. The % components should be scaled between 0 and 1. The space can be % visualized geometrically as a cube. % % Y'PbPr, Y'CbCr, Y'DbDr, Y'UV, and Y'IQ are related to sRGB by linear % transformations. These spaces separate a color into a grayscale % luminance component Y and two chroma components. The valid ranges of % the components depends on the space. % % HSV (Hue Saturation Value) is related to sRGB by % H = hexagonal hue angle (0 <= H < 360), % S = C/V (0 <= S <= 1), % V = max(R',G',B') (0 <= V <= 1), % where C = max(R',G',B') - min(R',G',B'). The hue angle H is computed on % a hexagon. The space is geometrically a hexagonal cone. % % HSL (Hue Saturation Lightness) is related to sRGB by % H = hexagonal hue angle (0 <= H < 360), % S = C/(1 - |2L-1|) (0 <= S <= 1), % L = (max(R',G',B') + min(R',G',B'))/2 (0 <= L <= 1), % where H and C are the same as in HSV. Geometrically, the space is a % double hexagonal cone. % % HSI (Hue Saturation Intensity) is related to sRGB by % H = polar hue angle (0 <= H < 360), % S = 1 - min(R',G',B')/I (0 <= S <= 1), % I = (R'+G'+B')/3 (0 <= I <= 1). % Unlike HSV and HSL, the hue angle H is computed on a circle rather than % a hexagon. % % CIE XYZ is related to sRGB by inverse gamma correction followed by a % linear transform. Other CIE color spaces are defined relative to XYZ. % % CIE L*a*b*, L*u*v*, and L*C*H* are nonlinear functions of XYZ. The L* % component is designed to match closely with human perception of % lightness. The other two components describe the chroma. % % CIE CAT02 LMS is the linear transformation of XYZ using the MCAT02 % chromatic adaptation matrix. The space is designed to model the % response of the three types of cones in the human eye, where L, M, S, % correspond respectively to red ("long"), green ("medium"), and blue % ("short"). % Pascal Getreuer 2005-2010 %%% Input parsing %%% if nargin < 2, error('Not enough input arguments.'); end [SrcSpace,DestSpace] = parse(Conversion); if nargin == 2 Image = varargin{1}; elseif nargin >= 3 Image = cat(3,varargin{:}); else error('Invalid number of input arguments.'); end FlipDims = (size(Image,3) == 1); if FlipDims, Image = permute(Image,[1,3,2]); end if ~isa(Image,'double'), Image = double(Image)/255; end if size(Image,3) ~= 3, error('Invalid input size.'); end SrcT = gettransform(SrcSpace); DestT = gettransform(DestSpace); if ~ischar(SrcT) && ~ischar(DestT) % Both source and destination transforms are affine, so they % can be composed into one affine operation T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)]; Temp = zeros(size(Image)); Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10); Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11); Temp(:,:,3) = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12); Image = Temp; elseif ~ischar(DestT) Image = rgb(Image,SrcSpace); Temp = zeros(size(Image)); Temp(:,:,1) = DestT(1)*Image(:,:,1) + DestT(4)*Image(:,:,2) + DestT(7)*Image(:,:,3) + DestT(10); Temp(:,:,2) = DestT(2)*Image(:,:,1) + DestT(5)*Image(:,:,2) + DestT(8)*Image(:,:,3) + DestT(11); Temp(:,:,3) = DestT(3)*Image(:,:,1) + DestT(6)*Image(:,:,2) + DestT(9)*Image(:,:,3) + DestT(12); Image = Temp; else Image = feval(DestT,Image,SrcSpace); end %%% Output format %%% if nargout > 1 varargout = {Image(:,:,1),Image(:,:,2),Image(:,:,3)}; else if FlipDims, Image = permute(Image,[1,3,2]); end varargout = {Image}; end return; function [SrcSpace,DestSpace] = parse(Str) % Parse conversion argument if ischar(Str) Str = lower(strrep(strrep(Str,'-',''),'=','')); k = find(Str == '>'); if length(k) == 1 % Interpret the form 'src->dest' SrcSpace = Str(1:k-1); DestSpace = Str(k+1:end); else k = find(Str == '<'); if length(k) == 1 % Interpret the form 'dest<-src' DestSpace = Str(1:k-1); SrcSpace = Str(k+1:end); else error(['Invalid conversion, ''',Str,'''.']); end end SrcSpace = alias(SrcSpace); DestSpace = alias(DestSpace); else SrcSpace = 1; % No source pre-transform DestSpace = Conversion; if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end end return; function Space = alias(Space) Space = strrep(strrep(Space,'cie',''),' ',''); if isempty(Space) Space = 'rgb'; end switch Space case {'ycbcr','ycc'} Space = 'ycbcr'; case {'hsv','hsb'} Space = 'hsv'; case {'hsl','hsi','hls'} Space = 'hsl'; case {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'} return; end return; function T = gettransform(Space) % Get a colorspace transform: either a matrix describing an affine transform, % or a string referring to a conversion subroutine switch Space case 'ypbpr' T = [0.299,0.587,0.114,0;-0.1687367,-0.331264,0.5,0;0.5,-0.418688,-0.081312,0]; case 'yuv' % sRGB to NTSC/PAL YUV % Wikipedia: http://en.wikipedia.org/wiki/YUV T = [0.299,0.587,0.114,0;-0.147,-0.289,0.436,0;0.615,-0.515,-0.100,0]; case 'ydbdr' % sRGB to SECAM YDbDr % Wikipedia: http://en.wikipedia.org/wiki/YDbDr T = [0.299,0.587,0.114,0;-0.450,-0.883,1.333,0;-1.333,1.116,0.217,0]; case 'yiq' % sRGB in [0,1] to NTSC YIQ in [0,1];[-0.595716,0.595716];[-0.522591,0.522591]; % Wikipedia: http://en.wikipedia.org/wiki/YIQ T = [0.299,0.587,0.114,0;0.595716,-0.274453,-0.321263,0;0.211456,-0.522591,0.311135,0]; case 'ycbcr' % sRGB (range [0,1]) to ITU-R BRT.601 (CCIR 601) Y'CbCr % Wikipedia: http://en.wikipedia.org/wiki/YCbCr % Poynton, Equation 3, scaling of R'G'B to Y'PbPr conversion T = [65.481,128.553,24.966,16;-37.797,-74.203,112.0,128;112.0,-93.786,-18.214,128]; case 'jpegycbcr' % Wikipedia: http://en.wikipedia.org/wiki/YCbCr T = [0.299,0.587,0.114,0;-0.168736,-0.331264,0.5,0.5;0.5,-0.418688,-0.081312,0.5]*255; case {'rgb','xyz','hsv','hsl','lab','luv','lch','cat02lms'} T = Space; otherwise error(['Unknown color space, ''',Space,'''.']); end return; function Image = rgb(Image,SrcSpace) % Convert to sRGB from 'SrcSpace' switch SrcSpace case 'rgb' return; case 'hsv' % Convert HSV to sRGB Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1)); case 'hsl' % Convert HSL to sRGB L = Image(:,:,3); Delta = Image(:,:,2).*min(L,1-L); Image = huetorgb(L-Delta,L+Delta,Image(:,:,1)); case {'xyz','lab','luv','lch','cat02lms'} % Convert to CIE XYZ Image = xyz(Image,SrcSpace); % Convert XYZ to RGB T = [3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]; R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3); % R G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3); % G B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3); % B % Desaturate and rescale to constrain resulting RGB values to [0,1] AddWhite = -min(min(min(R,G),B),0); R = R + AddWhite; G = G + AddWhite; B = B + AddWhite; % Apply gamma correction to convert linear RGB to sRGB Image(:,:,1) = gammacorrection(R); % R' Image(:,:,2) = gammacorrection(G); % G' Image(:,:,3) = gammacorrection(B); % B' otherwise % Conversion is through an affine transform T = gettransform(SrcSpace); temp = inv(T(:,1:3)); T = [temp,-temp*T(:,4)]; R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10); G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11); B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12); Image(:,:,1) = R; Image(:,:,2) = G; Image(:,:,3) = B; end % Clip to [0,1] Image = min(max(Image,0),1); return; function Image = xyz(Image,SrcSpace) % Convert to CIE XYZ from 'SrcSpace' WhitePoint = [0.950456,1,1.088754]; switch SrcSpace case 'xyz' return; case 'luv' % Convert CIE L*uv to XYZ WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); L = Image(:,:,1); Y = (L + 16)/116; Y = invf(Y)*WhitePoint(2); U = Image(:,:,2)./(13*L + 1e-6*(L==0)) + WhitePointU; V = Image(:,:,3)./(13*L + 1e-6*(L==0)) + WhitePointV; Image(:,:,1) = -(9*Y.*U)./((U-4).*V - U.*V); % X Image(:,:,2) = Y; % Y Image(:,:,3) = (9*Y - (15*V.*Y) - (V.*Image(:,:,1)))./(3*V); % Z case {'lab','lch'} Image = lab(Image,SrcSpace); % Convert CIE L*ab to XYZ fY = (Image(:,:,1) + 16)/116; fX = fY + Image(:,:,2)/500; fZ = fY - Image(:,:,3)/200; Image(:,:,1) = WhitePoint(1)*invf(fX); % X Image(:,:,2) = WhitePoint(2)*invf(fY); % Y Image(:,:,3) = WhitePoint(3)*invf(fZ); % Z case 'cat02lms' % Convert CAT02 LMS to XYZ T = inv([0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834]); L = Image(:,:,1); M = Image(:,:,2); S = Image(:,:,3); Image(:,:,1) = T(1)*L + T(4)*M + T(7)*S; % X Image(:,:,2) = T(2)*L + T(5)*M + T(8)*S; % Y Image(:,:,3) = T(3)*L + T(6)*M + T(9)*S; % Z otherwise % Convert from some gamma-corrected space % Convert to sRGB Image = rgb(Image,SrcSpace); % Undo gamma correction R = invgammacorrection(Image(:,:,1)); G = invgammacorrection(Image(:,:,2)); B = invgammacorrection(Image(:,:,3)); % Convert RGB to XYZ T = inv([3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]); Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B; % X Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B; % Y Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B; % Z end return; function Image = hsv(Image,SrcSpace) % Convert to HSV Image = rgb(Image,SrcSpace); V = max(Image,[],3); S = (V - min(Image,[],3))./(V + (V == 0)); Image(:,:,1) = rgbtohue(Image); Image(:,:,2) = S; Image(:,:,3) = V; return; function Image = hsl(Image,SrcSpace) % Convert to HSL switch SrcSpace case 'hsv' % Convert HSV to HSL MaxVal = Image(:,:,3); MinVal = (1 - Image(:,:,2)).*MaxVal; L = 0.5*(MaxVal + MinVal); temp = min(L,1-L); Image(:,:,2) = 0.5*(MaxVal - MinVal)./(temp + (temp == 0)); Image(:,:,3) = L; otherwise Image = rgb(Image,SrcSpace); % Convert to sRGB % Convert sRGB to HSL MinVal = min(Image,[],3); MaxVal = max(Image,[],3); L = 0.5*(MaxVal + MinVal); temp = min(L,1-L); S = 0.5*(MaxVal - MinVal)./(temp + (temp == 0)); Image(:,:,1) = rgbtohue(Image); Image(:,:,2) = S; Image(:,:,3) = L; end return; function Image = lab(Image,SrcSpace) % Convert to CIE L*a*b* (CIELAB) WhitePoint = [0.950456,1,1.088754]; switch SrcSpace case 'lab' return; case 'lch' % Convert CIE L*CH to CIE L*ab C = Image(:,:,2); Image(:,:,2) = cos(Image(:,:,3)*pi/180).*C; % a* Image(:,:,3) = sin(Image(:,:,3)*pi/180).*C; % b* otherwise Image = xyz(Image,SrcSpace); % Convert to XYZ % Convert XYZ to CIE L*a*b* X = Image(:,:,1)/WhitePoint(1); Y = Image(:,:,2)/WhitePoint(2); Z = Image(:,:,3)/WhitePoint(3); fX = f(X); fY = f(Y); fZ = f(Z); Image(:,:,1) = 116*fY - 16; % L* Image(:,:,2) = 500*(fX - fY); % a* Image(:,:,3) = 200*(fY - fZ); % b* end return; function Image = luv(Image,SrcSpace) % Convert to CIE L*u*v* (CIELUV) WhitePoint = [0.950456,1,1.088754]; WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); Image = xyz(Image,SrcSpace); % Convert to XYZ Denom = Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3); U = (4*Image(:,:,1))./(Denom + (Denom == 0)); V = (9*Image(:,:,2))./(Denom + (Denom == 0)); Y = Image(:,:,2)/WhitePoint(2); L = 116*f(Y) - 16; Image(:,:,1) = L; % L* Image(:,:,2) = 13*L.*(U - WhitePointU); % u* Image(:,:,3) = 13*L.*(V - WhitePointV); % v* return; function Image = lch(Image,SrcSpace) % Convert to CIE L*ch Image = lab(Image,SrcSpace); % Convert to CIE L*ab H = atan2(Image(:,:,3),Image(:,:,2)); H = H*180/pi + 360*(H < 0); Image(:,:,2) = sqrt(Image(:,:,2).^2 + Image(:,:,3).^2); % C Image(:,:,3) = H; % H return; function Image = cat02lms(Image,SrcSpace) % Convert to CAT02 LMS Image = xyz(Image,SrcSpace); T = [0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834]; X = Image(:,:,1); Y = Image(:,:,2); Z = Image(:,:,3); Image(:,:,1) = T(1)*X + T(4)*Y + T(7)*Z; % L Image(:,:,2) = T(2)*X + T(5)*Y + T(8)*Z; % M Image(:,:,3) = T(3)*X + T(6)*Y + T(9)*Z; % S return; function Image = huetorgb(m0,m2,H) % Convert HSV or HSL hue to RGB N = size(H); H = min(max(H(:),0),360)/60; m0 = m0(:); m2 = m2(:); F = H - round(H/2)*2; M = [m0, m0 + (m2-m0).*abs(F), m2]; Num = length(m0); j = [2 1 0;1 2 0;0 2 1;0 1 2;1 0 2;2 0 1;2 1 0]*Num; k = floor(H) + 1; Image = reshape([M(j(k,1)+(1:Num).'),M(j(k,2)+(1:Num).'),M(j(k,3)+(1:Num).')],[N,3]); return; function H = rgbtohue(Image) % Convert RGB to HSV or HSL hue [M,i] = sort(Image,3); i = i(:,:,3); Delta = M(:,:,3) - M(:,:,1); Delta = Delta + (Delta == 0); R = Image(:,:,1); G = Image(:,:,2); B = Image(:,:,3); H = zeros(size(R)); k = (i == 1); H(k) = (G(k) - B(k))./Delta(k); k = (i == 2); H(k) = 2 + (B(k) - R(k))./Delta(k); k = (i == 3); H(k) = 4 + (R(k) - G(k))./Delta(k); H = 60*H + 360*(H < 0); H(Delta == 0) = nan; return; function Rp = gammacorrection(R) Rp = zeros(size(R)); i = (R <= 0.0031306684425005883); Rp(i) = 12.92*R(i); Rp(~i) = real(1.055*R(~i).^0.416666666666666667 - 0.055); return; function R = invgammacorrection(Rp) R = zeros(size(Rp)); i = (Rp <= 0.0404482362771076); R(i) = Rp(i)/12.92; R(~i) = real(((Rp(~i) + 0.055)/1.055).^2.4); return; function fY = f(Y) fY = real(Y.^(1/3)); i = (Y < 0.008856); fY(i) = Y(i)*(841/108) + (4/29); return; function Y = invf(fY) Y = fY.^3; i = (Y < 0.008856); Y(i) = (fY(i) - 4/29)*(108/841); return;
github
sqjin/scEpath-master
litekmeans.m
.m
scEpath-master/enternal/SIMLR/src/litekmeans.m
16,583
utf_8
b74ab36bf2876c2205b06e5bb554d8d8
function [label, center, bCon, sumD, D] = litekmeans(X, k, varargin) %LITEKMEANS K-means clustering, accelerated by matlab matrix operations. % % label = LITEKMEANS(X, K) partitions the points in the N-by-P data matrix % X into K clusters. This partition minimizes the sum, over all % clusters, of the within-cluster sums of point-to-cluster-centroid % distances. Rows of X correspond to points, columns correspond to % variables. KMEANS returns an N-by-1 vector label containing the % cluster indices of each point. % % [label, center] = LITEKMEANS(X, K) returns the K cluster centroid % locations in the K-by-P matrix center. % % [label, center, bCon] = LITEKMEANS(X, K) returns the bool value bCon to % indicate whether the iteration is converged. % % [label, center, bCon, SUMD] = LITEKMEANS(X, K) returns the % within-cluster sums of point-to-centroid distances in the 1-by-K vector % sumD. % % [label, center, bCon, SUMD, D] = LITEKMEANS(X, K) returns % distances from each point to every centroid in the N-by-K matrix D. % % [ ... ] = LITEKMEANS(..., 'PARAM1',val1, 'PARAM2',val2, ...) specifies % optional parameter name/value pairs to control the iterative algorithm % used by KMEANS. Parameters are: % % 'Distance' - Distance measure, in P-dimensional space, that KMEANS % should minimize with respect to. Choices are: % {'sqEuclidean'} - Squared Euclidean distance (the default) % 'cosine' - One minus the cosine of the included angle % between points (treated as vectors). Each % row of X SHOULD be normalized to unit. If % the intial center matrix is provided, it % SHOULD also be normalized. % % 'Start' - Method used to choose initial cluster centroid positions, % sometimes known as "seeds". Choices are: % {'sample'} - Select K observations from X at random (the default) % 'cluster' - Perform preliminary clustering phase on random 10% % subsample of X. This preliminary phase is itself % initialized using 'sample'. An additional parameter % clusterMaxIter can be used to control the maximum % number of iterations in each preliminary clustering % problem. % matrix - A K-by-P matrix of starting locations; or a K-by-1 % indicate vector indicating which K points in X % should be used as the initial center. In this case, % you can pass in [] for K, and KMEANS infers K from % the first dimension of the matrix. % % 'MaxIter' - Maximum number of iterations allowed. Default is 100. % % 'Replicates' - Number of times to repeat the clustering, each with a % new set of initial centroids. Default is 1. If the % initial centroids are provided, the replicate will be % automatically set to be 1. % % 'clusterMaxIter' - Only useful when 'Start' is 'cluster'. Maximum number % of iterations of the preliminary clustering phase. % Default is 10. % % % Examples: % % fea = rand(500,10); % [label, center] = litekmeans(fea, 5, 'MaxIter', 50); % % fea = rand(500,10); % [label, center] = litekmeans(fea, 5, 'MaxIter', 50, 'Replicates', 10); % % fea = rand(500,10); % [label, center, bCon, sumD, D] = litekmeans(fea, 5, 'MaxIter', 50); % TSD = sum(sumD); % % fea = rand(500,10); % initcenter = rand(5,10); % [label, center] = litekmeans(fea, 5, 'MaxIter', 50, 'Start', initcenter); % % fea = rand(500,10); % idx=randperm(500); % [label, center] = litekmeans(fea, 5, 'MaxIter', 50, 'Start', idx(1:5)); % % % See also KMEANS % % [Cite] Deng Cai, "Litekmeans: the fastest matlab implementation of % kmeans," Available at: % http://www.zjucadcg.cn/dengcai/Data/Clustering.html, 2011. % % version 2.0 --December/2011 % version 1.0 --November/2011 % % Written by Deng Cai (dengcai AT gmail.com) if nargin < 2 error('litekmeans:TooFewInputs','At least two input arguments required.'); end [n, p] = size(X); pnames = { 'distance' 'start' 'maxiter' 'replicates' 'onlinephase' 'clustermaxiter'}; dflts = {'sqeuclidean' 'sample' [] [] 'off' [] }; [eid,errmsg,distance,start,maxit,reps,online,clustermaxit] = getargs(pnames, dflts, varargin{:}); if ~isempty(eid) error(sprintf('litekmeans:%s',eid),errmsg); end if ischar(distance) distNames = {'sqeuclidean','cosine'}; j = strcmpi(distance, distNames); j = find(j); if length(j) > 1 error('litekmeans:AmbiguousDistance', ... 'Ambiguous ''Distance'' parameter value: %s.', distance); elseif isempty(j) error('litekmeans:UnknownDistance', ... 'Unknown ''Distance'' parameter value: %s.', distance); end distance = distNames{j}; else error('litekmeans:InvalidDistance', ... 'The ''Distance'' parameter value must be a string.'); end center = []; if ischar(start) startNames = {'sample','cluster'}; j = find(strncmpi(start,startNames,length(start))); if length(j) > 1 error(message('litekmeans:AmbiguousStart', start)); elseif isempty(j) error(message('litekmeans:UnknownStart', start)); elseif isempty(k) error('litekmeans:MissingK', ... 'You must specify the number of clusters, K.'); end if j == 2 if floor(.1*n) < 5*k j = 1; end end start = startNames{j}; elseif isnumeric(start) if size(start,2) == p center = start; elseif (size(start,2) == 1 || size(start,1) == 1) center = X(start,:); else error('litekmeans:MisshapedStart', ... 'The ''Start'' matrix must have the same number of columns as X.'); end if isempty(k) k = size(center,1); elseif (k ~= size(center,1)) error('litekmeans:MisshapedStart', ... 'The ''Start'' matrix must have K rows.'); end start = 'numeric'; else error('litekmeans:InvalidStart', ... 'The ''Start'' parameter value must be a string or a numeric matrix or array.'); end % The maximum iteration number is default 100 if isempty(maxit) maxit = 100; end % The maximum iteration number for preliminary clustering phase on random % 10% subsamples is default 10 if isempty(clustermaxit) clustermaxit = 10; end % Assume one replicate if isempty(reps) || ~isempty(center) reps = 1; end if ~(isscalar(k) && isnumeric(k) && isreal(k) && k > 0 && (round(k)==k)) error('litekmeans:InvalidK', ... 'X must be a positive integer value.'); elseif n < k error('litekmeans:TooManyClusters', ... 'X must have more rows than the number of clusters.'); end bestlabel = []; sumD = zeros(1,k); bCon = false; for t=1:reps switch start case 'sample' center = X(randsample(n,k),:); case 'cluster' Xsubset = X(randsample(n,floor(.1*n)),:); [dump, center] = litekmeans(Xsubset, k, varargin{:}, 'start','sample', 'replicates',1 ,'MaxIter',clustermaxit); case 'numeric' end last = 0;label=1; it=0; switch distance case 'sqeuclidean' while any(label ~= last) && it<maxit last = label; bb = full(sum(center.*center,2)'); ab = full(X*center'); D = bb(ones(1,n),:) - 2*ab; [val,label] = min(D,[],2); % assign samples to the nearest centers ll = unique(label); if length(ll) < k %disp([num2str(k-length(ll)),' clusters dropped at iter ',num2str(it)]); missCluster = 1:k; missCluster(ll) = []; missNum = length(missCluster); aa = sum(X.*X,2); val = aa + val; [dump,idx] = sort(val,1,'descend'); label(idx(1:missNum)) = missCluster; end E = sparse(1:n,label,1,n,k,n); % transform label into indicator matrix center = full((E*spdiags(1./sum(E,1)',0,k,k))'*X); % compute center of each cluster it=it+1; end if it<maxit bCon = true; end if isempty(bestlabel) bestlabel = label; bestcenter = center; if reps>1 if it>=maxit aa = full(sum(X.*X,2)); bb = full(sum(center.*center,2)); ab = full(X*center'); D = bsxfun(@plus,aa,bb') - 2*ab; D(D<0) = 0; else aa = full(sum(X.*X,2)); D = aa(:,ones(1,k)) + D; D(D<0) = 0; end D = sqrt(D); for j = 1:k sumD(j) = sum(D(label==j,j)); end bestsumD = sumD; bestD = D; end else if it>=maxit aa = full(sum(X.*X,2)); bb = full(sum(center.*center,2)); ab = full(X*center'); D = bsxfun(@plus,aa,bb') - 2*ab; D(D<0) = 0; else aa = full(sum(X.*X,2)); D = aa(:,ones(1,k)) + D; D(D<0) = 0; end D = sqrt(D); for j = 1:k sumD(j) = sum(D(label==j,j)); end if sum(sumD) < sum(bestsumD) bestlabel = label; bestcenter = center; bestsumD = sumD; bestD = D; end end case 'cosine' while any(label ~= last) && it<maxit last = label; W=full(X*center'); [val,label] = max(W,[],2); % assign samples to the nearest centers ll = unique(label); if length(ll) < k missCluster = 1:k; missCluster(ll) = []; missNum = length(missCluster); [dump,idx] = sort(val); label(idx(1:missNum)) = missCluster; end E = sparse(1:n,label,1,n,k,n); % transform label into indicator matrix center = full((E*spdiags(1./sum(E,1)',0,k,k))'*X); % compute center of each cluster centernorm = sqrt(sum(center.^2, 2)); center = center ./ centernorm(:,ones(1,p)); it=it+1; end if it<maxit bCon = true; end if isempty(bestlabel) bestlabel = label; bestcenter = center; if reps>1 if any(label ~= last) W=full(X*center'); end D = 1-W; for j = 1:k sumD(j) = sum(D(label==j,j)); end bestsumD = sumD; bestD = D; end else if any(label ~= last) W=full(X*center'); end D = 1-W; for j = 1:k sumD(j) = sum(D(label==j,j)); end if sum(sumD) < sum(bestsumD) bestlabel = label; bestcenter = center; bestsumD = sumD; bestD = D; end end end end label = bestlabel; center = bestcenter; if reps>1 sumD = bestsumD; D = bestD; elseif nargout > 3 switch distance case 'sqeuclidean' if it>=maxit aa = full(sum(X.*X,2)); bb = full(sum(center.*center,2)); ab = full(X*center'); D = bsxfun(@plus,aa,bb') - 2*ab; D(D<0) = 0; else aa = full(sum(X.*X,2)); D = aa(:,ones(1,k)) + D; D(D<0) = 0; end D = sqrt(D); case 'cosine' if it>=maxit W=full(X*center'); end D = 1-W; end for j = 1:k sumD(j) = sum(D(label==j,j)); end end function [eid,emsg,varargout]=getargs(pnames,dflts,varargin) %GETARGS Process parameter name/value pairs % [EID,EMSG,A,B,...]=GETARGS(PNAMES,DFLTS,'NAME1',VAL1,'NAME2',VAL2,...) % accepts a cell array PNAMES of valid parameter names, a cell array % DFLTS of default values for the parameters named in PNAMES, and % additional parameter name/value pairs. Returns parameter values A,B,... % in the same order as the names in PNAMES. Outputs corresponding to % entries in PNAMES that are not specified in the name/value pairs are % set to the corresponding value from DFLTS. If nargout is equal to % length(PNAMES)+1, then unrecognized name/value pairs are an error. If % nargout is equal to length(PNAMES)+2, then all unrecognized name/value % pairs are returned in a single cell array following any other outputs. % % EID and EMSG are empty if the arguments are valid. If an error occurs, % EMSG is the text of an error message and EID is the final component % of an error message id. GETARGS does not actually throw any errors, % but rather returns EID and EMSG so that the caller may throw the error. % Outputs will be partially processed after an error occurs. % % This utility can be used for processing name/value pair arguments. % % Example: % pnames = {'color' 'linestyle', 'linewidth'} % dflts = { 'r' '_' '1'} % varargin = {{'linew' 2 'nonesuch' [1 2 3] 'linestyle' ':'} % [eid,emsg,c,ls,lw] = statgetargs(pnames,dflts,varargin{:}) % error % [eid,emsg,c,ls,lw,ur] = statgetargs(pnames,dflts,varargin{:}) % ok % We always create (nparams+2) outputs: % one each for emsg and eid % nparams varargs for values corresponding to names in pnames % If they ask for one more (nargout == nparams+3), it's for unrecognized % names/values % Original Copyright 1993-2008 The MathWorks, Inc. % Modified by Deng Cai ([email protected]) 2011.11.27 % Initialize some variables emsg = ''; eid = ''; nparams = length(pnames); varargout = dflts; unrecog = {}; nargs = length(varargin); % Must have name/value pairs if mod(nargs,2)~=0 eid = 'WrongNumberArgs'; emsg = 'Wrong number of arguments.'; else % Process name/value pairs for j=1:2:nargs pname = varargin{j}; if ~ischar(pname) eid = 'BadParamName'; emsg = 'Parameter name must be text.'; break; end i = strcmpi(pname,pnames); i = find(i); if isempty(i) % if they've asked to get back unrecognized names/values, add this % one to the list if nargout > nparams+2 unrecog((end+1):(end+2)) = {varargin{j} varargin{j+1}}; % otherwise, it's an error else eid = 'BadParamName'; emsg = sprintf('Invalid parameter name: %s.',pname); break; end elseif length(i)>1 eid = 'BadParamName'; emsg = sprintf('Ambiguous parameter name: %s.',pname); break; else varargout{i} = varargin{j+1}; end end end varargout{nparams+1} = unrecog;
github
sqjin/scEpath-master
SIMLR.m
.m
scEpath-master/enternal/SIMLR/src/SIMLR.m
9,303
utf_8
7913f20bdbdf908c5366ae37d193da4d
function [y, S, F, ydata,alphaK,timeOurs,converge,LF] = SIMLR(X, c, k, ifimpute,normalize) %%% if nargin==2 k=10; ifimpute = 0; normalize = 0; end if nargin==3 ifimpute = 0; normalize = 0; end if nargin==4 normalize = 0; end if ifimpute X = X'; [I,J] = find(X==0); Xmean = mean(X); X(sub2ind(size(X),I,J)) = Xmean(J); X = X'; end if normalize X = X'; X = X - min(X(:)); X = X / max(X(:)); X = bsxfun(@minus, X, mean(X, 1)); X = X'; end t0 = tic; order = 2; no_dim=c; NITER = 30; num = size(X,1); r = -1; beta = 0.8; D_Kernels = multipleK(X); clear X alphaK = 1/(size(D_Kernels,3))*ones(1,size(D_Kernels,3)); distX = mean(D_Kernels,3); [distX1, idx] = sort(distX,2); A = zeros(num); di = distX1(:,2:(k+2)); rr = 0.5*(k*di(:,k+1)-sum(di(:,1:k),2)); id = idx(:,2:k+2); temp = (repmat(di(:,k+1),1,size(di,2))-di)./repmat((k*di(:,k+1)-sum(di(:,1:k),2)+eps),1,size(di,2)); a = repmat([1:num]',1,size(id,2)); A(sub2ind(size(A),a(:),id(:)))=temp(:); if r <= 0 r = mean(rr); end lambda = max((mean(rr)),0); A(isnan(A))=0; S0 = max(max(distX))-distX; S0 = Network_Diffusion(S0,k); S0 = NE_dn(S0,'ave'); S= (S0 + S0')/2; D0 = diag(sum(S,order)); L0= D0-S; [F, temp, evs]=eig1(L0, c, 0); F = NE_dn(F,'ave'); for iter = 1:NITER distf = L2_distance_1(F',F'); A = zeros(num); %b = idx(:,2:(2*k+2)); b = idx(:,2:end); a = repmat([1:num]',1,size(b,2)); inda = sub2ind(size(A),a(:),b(:)); ad = reshape((distX(inda)+lambda*distf(inda))/2/r,num,size(b,2)); ad = projsplx_c(-ad')'; A(inda) = ad(:); A(isnan(A))=0; S = (1-beta)*A+beta*S; S = Network_Diffusion(S,k); S= (S + S')/2; D = diag(sum(S,order)); L = D - S; F_old = F; [F, temp, ev]=eig1(L, c, 0); F = NE_dn(F,'ave'); F = (1-beta)*F_old+beta*F; evs(:,iter+1) = ev; for i = 1:size(D_Kernels,3) temp = (eps+D_Kernels(:,:,i)).*(eps+S); DD(i) = mean(sum(temp)); end alphaK0 = umkl_bo(DD); alphaK0 = alphaK0/sum(alphaK0); alphaK = (1-beta)*alphaK + beta*alphaK0; alphaK = alphaK/sum(alphaK); fn1 = sum(ev(1:c)); fn2 = sum(ev(1:c+1)); converge(iter) = fn2-fn1; if iter<10 if (ev(end) > 0.000001) lambda = 1.5*lambda; r = r/1.01; end else if (converge(iter)>1.01*converge(iter-1)) S = S_old; if converge(iter-1) > 0.2 % warning('Maybe you should set a larger value of c'); end break; end end S_old = S; distX = Kbeta(D_Kernels,alphaK'); [distX1, idx] = sort(distX,2); end; LF = F; D = diag(sum(S,order)); L = D - S; [U,D] = eig(L); if length(no_dim)==1 F = tsne_p_bo((S),[], U(:,1:no_dim)); else clear F; for i = 1:length(no_dim) F{i} = tsne_p_bo((S),[], U(:,1:no_dim(i))); end end timeOurs = toc(t0); [~,center] = litekmeans(LF, c,'replicates',20); [~,center] = min(dist2(center,LF),[],2); y = litekmeans(F,c,'Start',center); ydata = tsne_p_bo(S); end function thisP = umkl_bo(D,beta) if nargin<2 beta = 1/length(D); end tol = 1e-4; u = 20;logU = log(u); [H, thisP] = Hbeta(D, beta); betamin = -Inf; betamax = Inf; % Evaluate whether the perplexity is within tolerance Hdiff = H - logU; tries = 0; while (abs(Hdiff) > tol) && (tries < 30) % If not, increase or decrease precision if Hdiff > 0 betamin = beta; if isinf(betamax) beta = beta * 2; else beta = (beta + betamax) / 2; end else betamax = beta; if isinf(betamin) beta = beta / 2; else beta = (beta + betamin) / 2; end end % Recompute the values [H, thisP] = Hbeta(D, beta); Hdiff = H - logU; tries = tries + 1; end end function [H, P] = Hbeta(D, beta) D = (D-min(D))/(max(D) - min(D)+eps); P = exp(-D * beta); sumP = sum(P); H = log(sumP) + beta * sum(D .* P) / sumP; P = P / sumP; end function D_Kernels = multipleK(x) N = size(x,1); KK = 0; sigma = [2:-0.25:1]; Diff = (dist2(x)); [T,INDEX]=sort(Diff,2); [m,n]=size(Diff); allk = 10:2:30; t=1; for l = 1:length(allk) if allk(l) < (size(x,1)-1) TT=mean(T(:,2:(allk(l)+1)),2)+eps; Sig=(repmat(TT,1,n)+repmat(TT',n,1))/2; Sig=Sig.*(Sig>eps)+eps; for j = 1:length(sigma) W=normpdf(Diff,0,sigma(j)*Sig); Kernels(:,:,KK+t) = (W + W')/2; t = t+1; end end end for i = 1:size(Kernels,3) K = Kernels(:,:,i); k = 1./sqrt(diag(K)+1); %G = K.*(k*k'); G = K; D_Kernels(:,:,i) = (repmat(diag(G),1,length(G)) +repmat(diag(G)',length(G),1) - 2*G)/2; D_Kernels(:,:,i) = D_Kernels(:,:,i) - diag(diag(D_Kernels(:,:,i))); end end % function W = Network_Diffusion(A, K) %K = min(2*K, round(length(A)/10)); A = A-diag(diag(A)); P = (dominateset(double(abs(A)),min(K,length(A)-1))).*sign(A); DD = sum(abs(P')); P = P + (eye(length(P))+diag(sum(abs(P')))); P = (TransitionFields(P)); [U,D] = eig(P); d = real((diag(D))+eps); alpha = 0.8; beta = 2; d = (1-alpha)*d./(1-alpha*d.^beta); D = diag(real(d)); W = U*D*U'; W = (W.*(1-eye(length(W))))./repmat(1-diag(W),1,length(W)); D=sparse(1:length(DD),1:length(DD),DD); W=D*(W); W = (W+W')/2; end function ydata = tsne_p_bo(P, labels, no_dims) %TSNE_P Performs symmetric t-SNE on affinity matrix P if ~exist('labels', 'var') labels = []; end if ~exist('no_dims', 'var') || isempty(no_dims) no_dims = 2; end % First check whether we already have an initial solution if numel(no_dims) > 1 initial_solution = true; ydata = no_dims; no_dims = size(ydata, 2); else initial_solution = false; end % Initialize some variables n = size(P, 1); % number of instances momentum = .08; % initial momentum final_momentum = .1; % value to which momentum is changed mom_switch_iter = 250; % iteration at which momentum is changed stop_lying_iter = 100; % iteration at which lying about P-values is stopped max_iter = 1000; % maximum number of iterations epsilon = 500; % initial learning rate min_gain = .01; % minimum gain for delta-bar-delta % Make sure P-vals are set properly P(1:n + 1:end) = 0; % set diagonal to zero P = 0.5 * (P + P'); % symmetrize P-values P = max(P ./ sum(P(:)), realmin); % make sure P-values sum to one const = sum(P(:) .* log(P(:))); % constant in KL divergence if ~initial_solution P = P * 4; % lie about the P-vals to find better local minima end % Initialize the solution if ~initial_solution ydata = .0001 * randn(n, no_dims); end y_incs = zeros(size(ydata)); gains = ones(size(ydata)); % Run the iterations for iter=1:max_iter % Compute joint probability that point i and j are neighbors sum_ydata = sum(ydata .^ 2, 2); num = 1 ./ (1 + bsxfun(@plus, sum_ydata, bsxfun(@plus, sum_ydata', -2 * (ydata * ydata')))); % Student-t distribution num(1:n+1:end) = 0; % set diagonal to zero Q = max(num ./ sum(num(:)), realmin); % normalize to get probabilities % Compute the gradients (faster implementation) L = (P - Q) .* num; y_grads = 4 * (diag(sum(L, 1)) - L) * ydata; % Update the solution gains = (gains + .2) .* (sign(y_grads) ~= sign(y_incs)) ... % note that the y_grads are actually -y_grads + (gains * .8) .* (sign(y_grads) == sign(y_incs)); gains(gains < min_gain) = min_gain; y_incs = momentum * y_incs - epsilon * (gains .* y_grads); ydata = ydata + y_incs; ydata = bsxfun(@minus, ydata, mean(ydata, 1)); ydata(ydata<-100)=-100;ydata(ydata>100)=100; % Update the momentum if necessary if iter == mom_switch_iter momentum = final_momentum; end if iter == stop_lying_iter && ~initial_solution P = P ./ 4; end % Print out progress if ~rem(iter, 10) cost = const - sum(P(:) .* log(Q(:))); % disp(['Iteration ' num2str(iter) ': error is ' num2str(cost)]); end % Display scatter plot (maximally first three dimensions) if ~isempty(labels) if no_dims == 1 scatter(ydata, ydata, 9, labels, 'filled'); elseif no_dims == 2 scatter(ydata(:,1), ydata(:,2), 9, labels, 'filled'); else scatter3(ydata(:,1), ydata(:,2), ydata(:,3), 40, labels, 'filled'); end axis equal tight % axis off drawnow end end end
github
sqjin/scEpath-master
SIMLR_embedding_tsne.m
.m
scEpath-master/enternal/SIMLR/src/SIMLR_embedding_tsne.m
2,427
utf_8
3e805cd1014ff2298086d18d9910a372
function Y = SIMLR_embedding_tsne(P, do_init,DD, Y0) %%%compute 2-D coordinates by approximae t-SNE % % Y = SIMLR_embedding_tsne(P, do_init) % % Input: % P: N x N, pairwise (sparse) similarities or network (weighted) adjacency matrix % do_init: boolean, do over-attraction initialization or not, default=false % % Output: % Y: N x 2, 2-D coordinates % % All rights reserved. if ~exist('do_init', 'var') || isempty(do_init) do_init = false; end if nargin<3 DD = 2; end method = 'wtsne'; P = 0.5 * (P+P'); P = P / sum(sum(P)); theta = 2; rng('default'); if nargin<4 Y0 = randn(size(P,1),DD)*1e-4; end check_step = 1; tol = 1e-4; max_time = inf; verbose = false; optimizer = 'fphssne'; recordYs = false; if do_init fprintf('===============================================\n'); fprintf('Starting Learning tSNE embeddings\n'); fprintf('===============================================\n'); attr = 4; max_iter = 30; Y1 = tSNE_embed(P, Y0, attr, theta, max_iter, check_step, tol, max_time, verbose, recordYs); else Y1 = Y0; end attr = 1; max_iter = 300; Y = tSNE_embed(P, Y1, attr, theta, max_iter, check_step, tol, max_time, verbose, recordYs); end function [Y, ts, Ys] = tSNE_embed(P, Y0, attr, theta, max_iter, check_step, tol, max_time, verbose, recordYs) Y = Y0; [I,J] = find(P); Pnz = nonzeros(P); weights = sum(P)'; ts(1) = 0; t = 1; if recordYs Ys = cell(max_iter,1); Ys{1} = Y; else Ys = []; end tic; n = size(P,1); for iter=2:max_iter Y_old = Y; qnz = 1./(1+sum((Y(I,:)-Y(J,:)).^2,2)); Pq = attr * sparse(I,J,Pnz.*qnz,n,n); [~, repu] = compute_wtsne_obj_grad_repulsive_barneshut(Y, weights, theta, 2); Y = bsxfun(@rdivide, Pq * Y - repu/4, sum(Pq,2)+eps); if recordYs && mod(iter, check_step)==0 t = t + 1; Ys{t} = Y; end ts(iter) = toc; if ts(iter)>max_time if verbose fprintf('max_time exceeded\n'); end break; end diffY = norm(Y-Y_old,'fro') / norm(Y_old,'fro'); if verbose && mod(iter, check_step)==0 fprintf('iter=%d/%d, collapsed_time=%.2f, diffY=%.12f, obj=%.12f\n', iter, max_iter, toc, diffY, obj); end if diffY<tol if verbose fprintf('converged after %d iterations.\n', iter); end break; end end ts = ts(1:iter); if recordYs Ys = Ys(1:t); end end
github
Shenc0411/CS445-master
mask2chain.m
.m
CS445-master/mp3/mask2chain.m
15,323
utf_8
816e13d1228586bd4c7115c9c3075203
function [x, y] = mask2chain_tmp(mask) crack_img = seg2cracks(double(mask)); fragments = cracks2fragments(crack_img, mask, 1); x = round(fragments{1}(:, 1)); y = round(fragments{1}(:, 2)); % x = fragments{1}(:, 1); % y = fragments{1}(:, 2); [gy, gx] = gradient(double(mask)); epix = (gy.^2+gx.^2>0) & mask; e = y + (x-1)*size(crack_img, 1); ind = epix(e); mean(ind) x = x(ind); y = y(ind); figure(1), hold off, plot(x, y), axis image %% cracks2fragments function [fragments, junctions, neighbor_lookups] = cracks2fragments(crack_img, seg, isolation_check) % % [fragments, junctions, neighbor_lookups] = cracks2fragments(crack_img, seg, isolation_check) % if(nargin<3) isolation_check = true; end [nrows,ncols] = size(crack_img); JUNCTION_BIT = 5; % Get a lookup table of where the image border is: onborder = false(nrows,ncols); onborder(:,[1 end]) = true; onborder([1 end],:) = true; num_neighbors_lookup = 4*ones(nrows,ncols); num_neighbors_lookup([1 end],:) = 3; num_neighbors_lookup(:,[1 end]) = 3; num_neighbors_lookup([1 nrows end-nrows+1 end]) = 2; % Neighbors: up, down, left, right neighbor_offsets = [-1 1 -nrows nrows]; % for the up neighbor, i want to check its down bit (3); for the right % neighbor, i want to check its left bit (4); etc... check_bit_interior = [3 1 2 4]; % Figure out the valid neighbors on the borders UP = 1; DOWN = 2; LEFT = 3; RIGHT = 4; valid_border_neighbors = cell(nrows,ncols); [valid_border_neighbors{1,:}] = deal([DOWN LEFT RIGHT]); [valid_border_neighbors{end,:}] = deal([UP LEFT RIGHT]); [valid_border_neighbors{:,1}] = deal([UP DOWN RIGHT]); [valid_border_neighbors{:,end}] = deal([UP DOWN LEFT]); valid_border_neighbors{1,1} = [DOWN RIGHT]; valid_border_neighbors{1,end} = [DOWN LEFT]; valid_border_neighbors{end,1} = [UP RIGHT]; valid_border_neighbors{end,end} = [UP LEFT]; % % Find the junctions that aren't on the image border junction_map = bitget(crack_img, JUNCTION_BIT); junction_index = find(junction_map); num_junctions = length(junction_index); junction_map = double(junction_map); junction_map(junction_index) = 1:num_junctions; junction_fragmentlist = cell(1,num_junctions); fragment_junctionlist = {}; fragment_segments = {}; segment_fragments = cell(1,max(seg(:))); [junction_y,junction_x] = ind2sub([nrows ncols], junction_index); junctions = [junction_x(:)+0.5 junction_y(:)+0.5]; %% Fragment Chaining not_in_fragment = true(nrows,ncols); fragment_indices = zeros(1,nrows*ncols); fragment_ctr = 0; fragments = {}; % % Randomize the order we go through the starting junctions (mainly for % % debug/display purposes): % rand_index = randperm(num_junctions); % for(i_rand=1:num_junctions) % i = rand_index(i_rand); for(i = 1:num_junctions) % get the neighbors of the starting junction that have not already been % made part of another fragment and whose orientation/shape match this % junction if(~onborder(junction_index(i))) junction_neighbors = junction_index(i)+neighbor_offsets; check_bit = check_bit_interior; else junction_neighbors = junction_index(i)+neighbor_offsets(valid_border_neighbors{junction_index(i)}); check_bit = check_bit_interior(valid_border_neighbors{junction_index(i)}); end neighbor_bits = bitget(crack_img(junction_neighbors), check_bit); which_junction_neighbors = find(neighbor_bits & not_in_fragment(junction_neighbors)); % ... % & ~onborder(junction_neighbors));% & ~junction_map(junction_neighbors)); % remove any neighbors that are themselves junctions and have a lower % index than the current starting junction. a single-crack-long % fragment has already been chained between these two junctions in this % case, so we don't need to do it again. which_junction_neighbors( junction_map(junction_neighbors(which_junction_neighbors)) & ... junction_neighbors(which_junction_neighbors) < junction_index(i) ) = []; % create a fragment starting from this junction and heading off along % each available neighbor for(j = 1:length(which_junction_neighbors)) % in case we just closed a loop, don't start marching back out % around the same loop in the opposite direction: if(not_in_fragment(junction_neighbors(which_junction_neighbors(j)))) % prevent us from coming right back to the starting junction on % the next step not_in_fragment(junction_index(i)) = false; fragment_ctr = fragment_ctr + 1; junction_fragmentlist{i}(end+1) = fragment_ctr; fragment_junctionlist{fragment_ctr} = i; fragment_length = 1; fragment_indices(1) = junction_index(i); % record the segmentation numbers on either side of this % fragment, store as [leftseg rightseg] if(~onborder(junction_index(i))) step_dir = which_junction_neighbors(j); else step_dir = valid_border_neighbors{junction_index(i)}(which_junction_neighbors(j)); end switch(step_dir) case(1) % about to move UP fragment_segments{fragment_ctr} = [seg(junction_index(i)) seg(junction_index(i)+nrows)]; case(2) % about to move DOWN fragment_segments{fragment_ctr} = [seg(junction_index(i)+1+nrows) seg(junction_index(i)+1)]; case(3) % about to move LEFT fragment_segments{fragment_ctr} = [seg(junction_index(i)+1) seg(junction_index(i))]; case(4) % about to move RIGHT fragment_segments{fragment_ctr} = [seg(junction_index(i)+nrows) seg(junction_index(i)+1+nrows)]; otherwise error('Invalid neighbor chosen???') end neighbors = junction_neighbors; which_neighbors = which_junction_neighbors(j); while(~isempty(which_neighbors)) % add current position to fragment fragment_length = fragment_length + 1; fragment_indices(fragment_length) = neighbors(which_neighbors); % once we've gone more than one step from the start, re-enable % the possibility of ending up there, in case of a closed % fragment around an isolated segment if(fragment_length==3) not_in_fragment(junction_index(i)) = true; end % if we've reached another junction, add that junction to this % fragment and stop if(junction_map(neighbors(which_neighbors))) % Don't add this fragment if this is a closed loop and % we already have it listed as a member of this % junction if(neighbors(which_neighbors) ~= junction_index(i)) junction_fragmentlist{junction_map(neighbors(which_neighbors))}(end+1) = fragment_ctr; end fragment_junctionlist{fragment_ctr}(2) = junction_map(neighbors(which_neighbors)); break; end % Otherwise, mark this position as being part of a fragment and % continue chaining not_in_fragment(fragment_indices(fragment_length)) = false; % get matching neighbors from this point that aren't already % used in another fragment crnt = fragment_indices(fragment_length); if(~onborder(crnt)) neighbors = crnt + neighbor_offsets; check_bit = check_bit_interior; else neighbors = crnt + neighbor_offsets(valid_border_neighbors{crnt}); check_bit = check_bit_interior(valid_border_neighbors{crnt}); end neighbor_bits = bitget(crack_img(neighbors), check_bit); which_neighbors = find(neighbor_bits & not_in_fragment(neighbors)); % & ~onborder(neighbors)); end % Create the fragment from the list of indices. Offset it by 0.5 % pixels in either direction to put it in image coordinates. [y,x] = ind2sub([nrows ncols], fragment_indices(1:fragment_length)); fragments{fragment_ctr} = [x(:)+0.5 y(:)+0.5]; % If this fragment didn't end at a junction (but instead at the % image border), add a "junction" for the end point: if(numel(fragment_junctionlist{fragment_ctr})==1) num_junctions = num_junctions + 1; junctions(num_junctions,:) = fragments{fragment_ctr}(end,:); fragment_junctionlist{fragment_ctr}(2) = num_junctions; junction_fragmentlist{num_junctions} = fragment_ctr; end end end % Allow other fragments to end up at this junction (this _should_ % already have been set back to true in most cases, but just in % case...) not_in_fragment(junction_index(i)) = true; end %% Handle isolated regions if(isolation_check) % Look for any segments that have not had any fragments used yet. They % must be surrounded entirely by one other segment meaning their boundary % has no junctions. We need % to add a fragment for that boundary (and some junctions) to our list. used_segments = vertcat(fragment_segments{:}); used_segments = unique(used_segments(:)); num_segments = max(seg(:)); unused_segments = true(1,num_segments); unused_segments(used_segments) = false; unused_segments = find(unused_segments); if(~isempty(unused_segments)) stats = regionprops(seg, 'PixelIdxList'); segment_indices = {stats.PixelIdxList}; isolated_seg = zeros(size(seg)); for k = 1:numel(unused_segments) isolated_seg(segment_indices{unused_segments(k)}) = k; end num_isolated_seg = numel(unused_segments); %isolated_seg(vertcat(segment_indices{unused_segments})) = true; %[isolated_seg, num_isolated_seg] = bwlabel(isolated_seg, 8); % Put a false junction on the border of each isolated segment: for(i=1:num_isolated_seg) % Get the cracks for this isolated segment isolated_cracks = seg2cracks(isolated_seg==i); % Put a false junction indicator on the border of the isolated % segment crack_index = find(isolated_cracks>0); isolated_cracks(crack_index(1)) = bitset(isolated_cracks(crack_index(1)), JUNCTION_BIT); % Chain the fragments around this isolated segment [temp_fragments, temp_junctions, temp_neighbor] = ... cracks2fragments(isolated_cracks, seg, false); % Concatenate the results with the existing results, adjusting % fragment and junction numbering as necessary fragments = [fragments temp_fragments]; junctions = [junctions; temp_junctions]; for(j=1:numel(temp_neighbor.junction_fragmentlist)) temp_neighbor.junction_fragmentlist{j} = temp_neighbor.junction_fragmentlist{j} + fragment_ctr; end junction_fragmentlist = [junction_fragmentlist temp_neighbor.junction_fragmentlist]; for(j=1:numel(temp_neighbor.fragment_junctionlist)) temp_neighbor.fragment_junctionlist{j} = temp_neighbor.fragment_junctionlist{j} + num_junctions; end fragment_junctionlist = [fragment_junctionlist temp_neighbor.fragment_junctionlist]; fragment_segments = [fragment_segments temp_neighbor.fragment_segments]; update_segments = ~cellfun('isempty', temp_neighbor.segment_fragments); for(j=find(update_segments)) segment_fragments{j} = [segment_fragments{j} temp_neighbor.segment_fragments{j}+fragment_ctr]; end % Don't want to update these too soon! fragment_ctr = fragment_ctr + numel(temp_fragments); junction_ctr = num_junctions + size(temp_junctions,1); end end end %% Output neighbor_lookups.junction_fragmentlist = junction_fragmentlist; neighbor_lookups.fragment_junctionlist = fragment_junctionlist; neighbor_lookups.fragment_segments = fragment_segments; neighbor_lookups.segment_fragments = segment_fragments; % Compute edge adjacency info num_fragments = fragment_ctr; FORWARD = 2; REVERSE = 1; directed_neighbors = cell(2*num_fragments,1); for(i=1:num_fragments) % Get forward neighbors directed_neighbors{i} = get_neighbors(i, neighbor_lookups, FORWARD, num_fragments); % Get reverse neighbors directed_neighbors{i+num_fragments} = get_neighbors(i, neighbor_lookups, REVERSE, num_fragments); end neighbor_lookups.directed_neighbors = directed_neighbors; % DEBUG CODE: % % Check that we're not still having the problem where a fragment has the % % same superpixel listed on both sides. % temp = vertcat(fragment_segments{:}); % if(any(temp(:,1)==temp(:,2))) % warning('At least one fragment has the same superpixel listed for left and right!') % keyboard % end return; %% Helper: Find directed neighbors function neighbors = get_neighbors(fragment, neighbor_data, direction, num_fragments) % direction==2 -> forward % direction==1? -> reverse % Get all the foward neighbors for this fragment: junction = neighbor_data.fragment_junctionlist{fragment}(direction); neighbors = neighbor_data.junction_fragmentlist{junction}; neighbors(neighbors==fragment) = []; if(~isempty(neighbors)) % Any neighbors that connect to this in the wrong direction should be % referenced to the reverse fragment neighbor_junctions = vertcat(neighbor_data.fragment_junctionlist{neighbors}); to_reverse = (neighbor_junctions(:,2)==junction); neighbors(to_reverse) = neighbors(to_reverse) + num_fragments; end %% seg2cracks function [crack_img] = seg2cracks(seg) % % [crack_img] = seg2cracks(seg) % % Converts a segmentation image into a crack-coded image. % % Bits: % | % | 1 % 4 ----+---- 2 % | % | 3 % Values: % tic UP = 1; RIGHT = 2; DOWN = 3; LEFT = 4; JUNCTION = 5; % dx = uint8(seg ~= image_right(seg)); % dy = uint8(seg ~= image_down(seg) ); % crack_img = dx + bitshift(dy,LEFT-1) + ... % bitshift(image_right(dy),RIGHT-1) + bitshift(image_down(dx),DOWN-1); % Removed dependency on image_down and image_right, to make this more % easily packaged: dx = uint8(seg ~= seg(:,[2:end end])); dy = uint8(seg ~= seg([2:end end],:)); crack_img = dx + bitshift(dy,LEFT-1) + ... bitshift(dy(:,[2:end end]),RIGHT-1) + bitshift(dx([2:end end],:),DOWN-1); % Find interior junctions: junction_map = (crack_img==11 | crack_img==7 | crack_img==14 | ... crack_img==13 | crack_img==15); % Find the junctions along the borders: junction_map([1 end],:) = junction_map([1 end],:) | bitget(crack_img([1 end],:),UP); junction_map(:,[1 end]) = junction_map(:,[1 end]) | bitget(crack_img(:,[1 end]),LEFT); % set the junction bit for all these junctions in the crack_img crack_img(junction_map) = bitset(crack_img(junction_map), JUNCTION);
github
Shenc0411/CS445-master
auto_homography.m
.m
CS445-master/mp5/auto_homography.m
1,604
utf_8
43e69b60910b0e8336b4ed782d13dcaa
function H=auto_homography(Ia,Ib) % Computes a homography that maps points from Ia to Ib % % Input: Ia and Ib are images % Output: H is the homography % % Note: to use H in maketform, use maketform('projective', H') % Computes correspondences and matches [fa,da] = vl_sift(im2single(rgb2gray(Ia))) ; [fb,db] = vl_sift(im2single(rgb2gray(Ib))) ; matches = vl_ubcmatch(da,db) ; numMatches = size(matches,2) ; % Xa and Xb are 3xN matrices that contain homogeneous coordinates for the N % matching points for each image Xa = fa(1:2,matches(1,:)) ; Xa(3,:) = 1 ; Xb = fb(1:2,matches(2,:)) ; Xb(3,:) = 1 ; %% RANSAC niter = 1000; best_score = 0; for t = 1:niter % estimate homograpyh subset = vl_colsubset(1:numMatches, 4) ; pts1 = Xa(:, subset); pts2 = Xb(:, subset); H_t = computeHomography(pts1, pts2); % edit helper code below % score homography Xb_ = H_t * Xa ; % project points from first image to second using H du = Xb_(1,:)./Xb_(3,:) - Xb(1,:)./Xb(3,:) ; dv = Xb_(2,:)./Xb_(3,:) - Xb(2,:)./Xb(3,:) ; ok_t = sqrt(du.*du + dv.*dv) < 1; % you may need to play with this threshold score_t = sum(ok_t) ; if score_t > best_score best_score = score_t; H = H_t; end end disp(num2str(best_score)) % Optionally, you may want to re-estimate H based on inliers %% function H = computeHomography(pts1, pts2) % Compute homography that maps from pts1 to pts2 using least squares solver % % Input: pts1 and pts2 are 3xN matrices for N points in homogeneous % coordinates. % % Output: H is a 3x3 matrix, such that pts2~=H*pts1
github
Shenc0411/CS445-master
vl_compile.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/vl_compile.m
5,060
utf_8
978f5189bb9b2a16db3368891f79aaa6
function vl_compile(compiler) % VL_COMPILE Compile VLFeat MEX files % VL_COMPILE() uses MEX() to compile VLFeat MEX files. This command % works only under Windows and is used to re-build problematic % binaries. The preferred method of compiling VLFeat on both UNIX % and Windows is through the provided Makefiles. % % VL_COMPILE() only compiles the MEX files and assumes that the % VLFeat DLL (i.e. the file VLFEATROOT/bin/win{32,64}/vl.dll) has % already been built. This file is built by the Makefiles. % % By default VL_COMPILE() assumes that Visual C++ is the active % MATLAB compiler. VL_COMPILE('lcc') assumes that the active % compiler is LCC instead (see MEX -SETUP). Unfortunately LCC does % not seem to be able to compile the latest versions of VLFeat due % to bugs in the support of 64-bit integers. Therefore it is % recommended to use Visual C++ instead. % % See also: VL_NOPREFIX(), VL_HELP(). % Authors: Andrea Vedadli, Jonghyun Choi % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin < 1, compiler = 'visualc' ; end switch lower(compiler) case 'visualc' fprintf('%s: assuming that Visual C++ is the active compiler\n', mfilename) ; useLcc = false ; case 'lcc' fprintf('%s: assuming that LCC is the active compiler\n', mfilename) ; warning('LCC may fail to compile VLFeat. See help vl_compile.') ; useLcc = true ; otherwise error('Unknown compiler ''%s''.', compiler) end vlDir = vl_root ; toolboxDir = fullfile(vlDir, 'toolbox') ; switch computer case 'PCWIN' fprintf('%s: compiling for PCWIN (32 bit)\n', mfilename); mexwDir = fullfile(toolboxDir, 'mex', 'mexw32') ; binwDir = fullfile(vlDir, 'bin', 'win32') ; case 'PCWIN64' fprintf('%s: compiling for PCWIN64 (64 bit)\n', mfilename); mexwDir = fullfile(toolboxDir, 'mex', 'mexw64') ; binwDir = fullfile(vlDir, 'bin', 'win64') ; otherwise error('The architecture is neither PCWIN nor PCWIN64. See help vl_compile.') ; end impLibPath = fullfile(binwDir, 'vl.lib') ; libDir = fullfile(binwDir, 'vl.dll') ; mkd(mexwDir) ; % find the subdirectories of toolbox that we should process subDirs = dir(toolboxDir) ; subDirs = subDirs([subDirs.isdir]) ; discard = regexp({subDirs.name}, '^(.|..|noprefix|mex.*)$', 'start') ; keep = cellfun('isempty', discard) ; subDirs = subDirs(keep) ; subDirs = {subDirs.name} ; % Copy support files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ~exist(fullfile(binwDir, 'vl.dll')) error('The VLFeat DLL (%s) could not be found. See help vl_compile.', ... fullfile(binwDir, 'vl.dll')) ; end tmp = dir(fullfile(binwDir, '*.dll')) ; supportFileNames = {tmp.name} ; for fi = 1:length(supportFileNames) name = supportFileNames{fi} ; cp(fullfile(binwDir, name), ... fullfile(mexwDir, name) ) ; end % Ensure implib for LCC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if useLcc lccImpLibDir = fullfile(mexwDir, 'lcc') ; lccImpLibPath = fullfile(lccImpLibDir, 'VL.lib') ; lccRoot = fullfile(matlabroot, 'sys', 'lcc', 'bin') ; lccImpExePath = fullfile(lccRoot, 'lcc_implib.exe') ; mkd(lccImpLibDir) ; cp(fullfile(binwDir, 'vl.dll'), fullfile(lccImpLibDir, 'vl.dll')) ; cmd = ['"' lccImpExePath '"', ' -u ', '"' fullfile(lccImpLibDir, 'vl.dll') '"'] ; fprintf('Running:\n> %s\n', cmd) ; curPath = pwd ; try cd(lccImpLibDir) ; [d,w] = system(cmd) ; if d, error(w); end cd(curPath) ; catch cd(curPath) ; error(lasterr) ; end end % Compile each mex file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for i = 1:length(subDirs) thisDir = fullfile(toolboxDir, subDirs{i}) ; fileNames = ls(fullfile(thisDir, '*.c')); for f = 1:size(fileNames,1) fileName = fileNames(f, :) ; sp = strfind(fileName, ' '); if length(sp) > 0, fileName = fileName(1:sp-1); end filePath = fullfile(thisDir, fileName); fprintf('MEX %s\n', filePath); dot = strfind(fileName, '.'); mexFile = fullfile(mexwDir, [fileName(1:dot) 'dll']); if exist(mexFile) delete(mexFile) end cmd = {['-I' toolboxDir], ... ['-I' vlDir], ... '-O', ... '-outdir', mexwDir, ... filePath } ; if useLcc cmd{end+1} = lccImpLibPath ; else cmd{end+1} = impLibPath ; end mex(cmd{:}) ; end end % -------------------------------------------------------------------- function cp(src,dst) % -------------------------------------------------------------------- if ~exist(dst,'file') fprintf('Copying ''%s'' to ''%s''.\n', src,dst) ; copyfile(src,dst) ; end % -------------------------------------------------------------------- function mkd(dst) % -------------------------------------------------------------------- if ~exist(dst, 'dir') fprintf('Creating directory ''%s''.', dst) ; mkdir(dst) ; end
github
Shenc0411/CS445-master
vl_noprefix.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/vl_noprefix.m
1,875
utf_8
97d8755f0ba139ac1304bc423d3d86d3
function vl_noprefix % VL_NOPREFIX Create a prefix-less version of VLFeat commands % VL_NOPREFIX() creats prefix-less stubs for VLFeat functions % (e.g. SIFT for VL_SIFT). This function is seldom used as the stubs % are included in the VLFeat binary distribution anyways. Moreover, % on UNIX platforms, the stubs are generally constructed by the % Makefile. % % See also: VL_COMPILE(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). root = fileparts(which(mfilename)) ; list = listMFilesX(root); outDir = fullfile(root, 'noprefix') ; if ~exist(outDir, 'dir') mkdir(outDir) ; end for li = 1:length(list) name = list(li).name(1:end-2) ; % remove .m nname = name(4:end) ; % remove vl_ stubPath = fullfile(outDir, [nname '.m']) ; fout = fopen(stubPath, 'w') ; fprintf('Creating stub %s for %s\n', stubPath, nname) ; fprintf(fout, 'function varargout = %s(varargin)\n', nname) ; fprintf(fout, '%% %s Stub for %s\n', upper(nname), upper(name)) ; fprintf(fout, '[varargout{1:nargout}] = %s(varargin{:})\n', name) ; fclose(fout) ; end end function list = listMFilesX(root) list = struct('name', {}, 'path', {}) ; files = dir(root) ; for fi = 1:length(files) name = files(fi).name ; if files(fi).isdir if any(regexp(name, '^(\.|\.\.|noprefix)$')) continue ; else tmp = listMFilesX(fullfile(root, name)) ; list = [list, tmp] ; end end if any(regexp(name, '^vl_(demo|test).*m$')) continue ; elseif any(regexp(name, '^vl_(demo|setup|compile|help|root|noprefix)\.m$')) continue ; elseif any(regexp(name, '\.m$')) list(end+1) = struct(... 'name', {name}, ... 'path', {fullfile(root, name)}) ; end end end
github
Shenc0411/CS445-master
vl_pegasos.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/misc/vl_pegasos.m
2,837
utf_8
d5e0915c439ece94eb5597a07090b67d
% VL_PEGASOS [deprecated] % VL_PEGASOS is deprecated. Please use VL_SVMTRAIN() instead. function [w b info] = vl_pegasos(X,Y,LAMBDA, varargin) % Verbose not supported if (sum(strcmpi('Verbose',varargin))) varargin(find(strcmpi('Verbose',varargin),1))=[]; fprintf('Option VERBOSE is no longer supported.\n'); end % DiagnosticCallRef not supported if (sum(strcmpi('DiagnosticCallRef',varargin))) varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[]; varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[]; fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n'); end % different default value for MaxIterations if (sum(strcmpi('MaxIterations',varargin)) == 0) varargin{end+1} = 'MaxIterations'; varargin{end+1} = ceil(10/LAMBDA); end % different default value for BiasMultiplier if (sum(strcmpi('BiasMultiplier',varargin)) == 0) varargin{end+1} = 'BiasMultiplier'; varargin{end+1} = 0; end % parameters for vl_maketrainingset setvarargin = {}; if (sum(strcmpi('HOMKERMAP',varargin))) setvarargin{end+1} = 'HOMKERMAP'; setvarargin{end+1} = varargin{find(strcmpi('HOMKERMAP',varargin),1)+1}; varargin(find(strcmpi('HOMKERMAP',varargin),1)+1)=[]; varargin(find(strcmpi('HOMKERMAP',varargin),1))=[]; end if (sum(strcmpi('KChi2',varargin))) setvarargin{end+1} = 'KChi2'; varargin(find(strcmpi('KChi2',varargin),1))=[]; end if (sum(strcmpi('KINTERS',varargin))) setvarargin{end+1} = 'KINTERS'; varargin(find(strcmpi('KINTERS',varargin),1))=[]; end if (sum(strcmpi('KL1',varargin))) setvarargin{end+1} = 'KL1'; varargin(find(strcmpi('KL1',varargin),1))=[]; end if (sum(strcmpi('KJS',varargin))) setvarargin{end+1} = 'KJS'; varargin(find(strcmpi('KJS',varargin),1))=[]; end if (sum(strcmpi('Period',varargin))) setvarargin{end+1} = 'Period'; setvarargin{end+1} = varargin{find(strcmpi('Period',varargin),1)+1}; varargin(find(strcmpi('Period',varargin),1)+1)=[]; varargin(find(strcmpi('Period',varargin),1))=[]; end if (sum(strcmpi('Window',varargin))) setvarargin{end+1} = 'Window'; setvarargin{end+1} = varargin{find(strcmpi('Window',varargin),1)+1}; varargin(find(strcmpi('Window',varargin),1)+1)=[]; varargin(find(strcmpi('Window',varargin),1))=[]; end if (sum(strcmpi('Gamma',varargin))) setvarargin{end+1} = 'Gamma'; setvarargin{end+1} = varargin{find(strcmpi('Gamma',varargin),1)+1}; varargin(find(strcmpi('Gamma',varargin),1)+1)=[]; varargin(find(strcmpi('Gamma',varargin),1))=[]; end setvarargin{:} DATA = vl_maketrainingset(double(X),int8(Y),setvarargin{:}); DATA [w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:}); fprintf('\n vl_pegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n'); end
github
Shenc0411/CS445-master
vl_svmpegasos.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/misc/vl_svmpegasos.m
1,178
utf_8
009c2a2b87a375d529ed1a4dbe3af59f
% VL_SVMPEGASOS [deprecated] % VL_SVMPEGASOS is deprecated. Please use VL_SVMTRAIN() instead. function [w b info] = vl_svmpegasos(DATA,LAMBDA, varargin) % Verbose not supported if (sum(strcmpi('Verbose',varargin))) varargin(find(strcmpi('Verbose',varargin),1))=[]; fprintf('Option VERBOSE is no longer supported.\n'); end % DiagnosticCallRef not supported if (sum(strcmpi('DiagnosticCallRef',varargin))) varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[]; varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[]; fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n'); end % different default value for MaxIterations if (sum(strcmpi('MaxIterations',varargin)) == 0) varargin{end+1} = 'MaxIterations'; varargin{end+1} = ceil(10/LAMBDA); end % different default value for BiasMultiplier if (sum(strcmpi('BiasMultiplier',varargin)) == 0) varargin{end+1} = 'BiasMultiplier'; varargin{end+1} = 0; end [w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:}); fprintf('\n vl_svmpegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n'); end
github
Shenc0411/CS445-master
vl_override.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/misc/vl_override.m
4,654
utf_8
e233d2ecaeb68f56034a976060c594c5
function config = vl_override(config,update,varargin) % VL_OVERRIDE Override structure subset % CONFIG = VL_OVERRIDE(CONFIG, UPDATE) copies recursively the fileds % of the structure UPDATE to the corresponding fields of the % struture CONFIG. % % Usually CONFIG is interpreted as a list of paramters with their % default values and UPDATE as a list of new paramete values. % % VL_OVERRIDE(..., 'Warn') prints a warning message whenever: (i) % UPDATE has a field not found in CONFIG, or (ii) non-leaf values of % CONFIG are overwritten. % % VL_OVERRIDE(..., 'Skip') skips fields of UPDATE that are not found % in CONFIG instead of copying them. % % VL_OVERRIDE(..., 'CaseI') matches field names in a % case-insensitive manner. % % Remark:: % Fields are copied at the deepest possible level. For instance, % if CONFIG has fields A.B.C1=1 and A.B.C2=2, and if UPDATE is the % structure A.B.C1=3, then VL_OVERRIDE() returns a strucuture with % fields A.B.C1=3, A.B.C2=2. By contrast, if UPDATE is the % structure A.B=4, then the field A.B is copied, and VL_OVERRIDE() % returns the structure A.B=4 (specifying 'Warn' would warn about % the fact that the substructure B.C1, B.C2 is being deleted). % % Remark:: % Two fields are matched if they correspond exactly. Specifically, % two fileds A(IA).(FA) and B(IA).FB of two struct arrays A and B % match if, and only if, (i) A and B have the same dimensions, % (ii) IA == IB, and (iii) FA == FB. % % See also: VL_ARGPARSE(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). warn = false ; skip = false ; err = false ; casei = false ; if length(varargin) == 1 & ~ischar(varargin{1}) % legacy warn = 1 ; end if ~warn & length(varargin) > 0 for i=1:length(varargin) switch lower(varargin{i}) case 'warn' warn = true ; case 'skip' skip = true ; case 'err' err = true ; case 'argparse' argparse = true ; case 'casei' casei = true ; otherwise error(sprintf('Unknown option ''%s''.',varargin{i})) ; end end end % if CONFIG is not a struct array just copy UPDATE verbatim if ~isstruct(config) config = update ; return ; end % if CONFIG is a struct array but UPDATE is not, no match can be % established and we simply copy UPDATE verbatim if ~isstruct(update) config = update ; return ; end % if CONFIG and UPDATE are both struct arrays, but have different % dimensions then nom atch can be established and we simply copy % UPDATE verbatim if numel(update) ~= numel(config) config = update ; return ; end % if CONFIG and UPDATE are both struct arrays of the same % dimension, we override recursively each field for idx=1:numel(update) fields = fieldnames(update) ; for i = 1:length(fields) updateFieldName = fields{i} ; if casei configFieldName = findFieldI(config, updateFieldName) ; else configFieldName = findField(config, updateFieldName) ; end if ~isempty(configFieldName) config(idx).(configFieldName) = ... vl_override(config(idx).(configFieldName), ... update(idx).(updateFieldName)) ; else if warn warning(sprintf('copied field ''%s'' which is in UPDATE but not in CONFIG', ... updateFieldName)) ; end if err error(sprintf('The field ''%s'' is in UPDATE but not in CONFIG', ... updateFieldName)) ; end if skip if warn warning(sprintf('skipping field ''%s'' which is in UPDATE but not in CONFIG', ... updateFieldName)) ; end continue ; end config(idx).(updateFieldName) = update(idx).(updateFieldName) ; end end end % -------------------------------------------------------------------- function field = findFieldI(S, matchField) % -------------------------------------------------------------------- field = '' ; fieldNames = fieldnames(S) ; for fi=1:length(fieldNames) if strcmpi(fieldNames{fi}, matchField) field = fieldNames{fi} ; end end % -------------------------------------------------------------------- function field = findField(S, matchField) % -------------------------------------------------------------------- field = '' ; fieldNames = fieldnames(S) ; for fi=1:length(fieldNames) if strcmp(fieldNames{fi}, matchField) field = fieldNames{fi} ; end end
github
Shenc0411/CS445-master
vl_quickvis.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/quickshift/vl_quickvis.m
3,696
utf_8
27f199dad4c5b9c192a5dd3abc59f9da
function [Iedge dists map gaps] = vl_quickvis(I, ratio, kernelsize, maxdist, maxcuts) % VL_QUICKVIS Create an edge image from a Quickshift segmentation. % IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) creates an edge % stability image from a Quickshift segmentation. RATIO controls the tradeoff % between color consistency and spatial consistency (See VL_QUICKSEG) and % KERNELSIZE controls the bandwidth of the density estimator (See VL_QUICKSEG, % VL_QUICKSHIFT). MAXDIST is the maximum distance between neighbors which % increase the density. % % VL_QUICKVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at % most MAXCUTS segmentations. The edges between regions in each of these % segmentations are labeled in IEDGE, where the label corresponds to the % largest DIST which preserves the edge. % % [IEDGE,DISTS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) also % returns the DIST thresholds that were chosen. % % IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, DISTS) will use the DISTS % specified % % [IEDGE,DISTS,MAP,GAPS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) % also returns the MAP and GAPS from VL_QUICKSHIFT. % % See Also: VL_QUICKSHIFT(), VL_QUICKSEG(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin == 4 dists = maxdist; maxdist = max(dists); [Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist); else [Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist); dists = unique(floor(gaps(:))); dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh if length(dists) > maxcuts ind = round(linspace(1,length(dists), maxcuts)); dists = dists(ind); end end [Iedge dists] = mapvis(map, gaps, dists); function [Iedge dists] = mapvis(map, gaps, maxdist, maxcuts) % MAPVIS Create an edge image from a Quickshift segmentation. % IEDGE = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) creates an edge % stability image from a Quickshift segmentation. MAXDIST is the maximum % distance between neighbors which increase the density. % % MAPVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at most % MAXCUTS segmentations. The edges between regions in each of these % segmentations are labeled in IEDGE, where the label corresponds to the % largest DIST which preserves the edge. % % [IEDGE,DISTS] = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) also returns the DIST % thresholds that were chosen. % % IEDGE = MAPVIS(MAP, GAPS, DISTS) will use the DISTS specified % % See Also: VL_QUICKVIS, VL_QUICKSHIFT, VL_QUICKSEG if nargin == 3 dists = maxdist; maxdist = max(dists); else dists = unique(floor(gaps(:))); dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh % throw away min region size instead of maxdist? ind = find(dists < maxdist); dists = dists(ind); if length(dists) > maxcuts ind = round(linspace(1,length(dists), maxcuts)); dists = dists(ind); end end Iedge = zeros(size(map)); for i = 1:length(dists) s = find(gaps >= dists(i)); mapdist = map; mapdist(s) = s; [mapped labels] = vl_flatmap(mapdist); fprintf('%d/%d %d regions\n', i, length(dists), length(unique(mapped))) borders = getborders(mapped); Iedge(borders) = dists(i); %Iedge(borders) = Iedge(borders) + 1; %Iedge(borders) = i; end %%%%%%%%% GETBORDERS function borders = getborders(map) dx = conv2(map, [-1 1], 'same'); dy = conv2(map, [-1 1]', 'same'); borders = find(dx ~= 0 | dy ~= 0);
github
Shenc0411/CS445-master
vl_demo_aib.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/demo/vl_demo_aib.m
2,928
utf_8
590c6db09451ea608d87bfd094662cac
function vl_demo_aib % VL_DEMO_AIB Test Agglomerative Information Bottleneck (AIB) D = 4 ; K = 20 ; randn('state',0) ; rand('state',0) ; X1 = randn(2,300) ; X1(1,:) = X1(1,:) + 2 ; X2 = randn(2,300) ; X2(1,:) = X2(1,:) - 2 ; X3 = randn(2,300) ; X3(2,:) = X3(2,:) + 2 ; figure(1) ; clf ; hold on ; vl_plotframe(X1,'color','r') ; vl_plotframe(X2,'color','g') ; vl_plotframe(X3,'color','b') ; axis equal ; xlim([-4 4]); ylim([-4 4]); axis off ; rectangle('position',D*[-1 -1 2 2]) vl_demo_print('aib_basic_data', .6) ; C = 1:K*K ; Pcx = zeros(3,K*K) ; f1 = quantize(X1,D,K) ; f2 = quantize(X2,D,K) ; f3 = quantize(X3,D,K) ; Pcx(1,:) = vl_binsum(Pcx(1,:), ones(size(f1)), f1) ; Pcx(2,:) = vl_binsum(Pcx(2,:), ones(size(f2)), f2) ; Pcx(3,:) = vl_binsum(Pcx(3,:), ones(size(f3)), f3) ; Pcx = Pcx / sum(Pcx(:)) ; [parents, cost] = vl_aib(Pcx) ; cutsize = [K*K, 10, 3, 2, 1] ; for i=1:length(cutsize) [cut,map,short] = vl_aibcut(parents, cutsize(i)) ; parents_cut(short > 0) = parents(short(short > 0)) ; C = short(1:K*K+1) ; [drop1,drop2,C] = unique(C) ; figure(i+1) ; clf ; plotquantization(D,K,C) ; hold on ; %plottree(D,K,parents_cut) ; axis equal ; axis off ; title(sprintf('%d clusters', cutsize(i))) ; vl_demo_print(sprintf('aib_basic_clust_%d',i),.6) ; end % -------------------------------------------------------------------- function f = quantize(X,D,K) % -------------------------------------------------------------------- d = 2*D / K ; j = round((X(1,:) + D) / d) ; i = round((X(2,:) + D) / d) ; j = max(min(j,K),1) ; i = max(min(i,K),1) ; f = sub2ind([K K],i,j) ; % -------------------------------------------------------------------- function [i,j] = plotquantization(D,K,C) % -------------------------------------------------------------------- hold on ; cl = [[.3 .3 .3] ; .5*hsv(max(C)-1)+.5] ; d = 2*D / K ; for i=0:K-1 for j=0:K-1 patch(d*(j+[0 1 1 0])-D, ... d*(i+[0 0 1 1])-D, ... cl(C(j*K+i+1),:)) ; end end % -------------------------------------------------------------------- function h = plottree(D,K,parents) % -------------------------------------------------------------------- d = 2*D / K ; C = zeros(2,2*K*K-1)+NaN ; N = zeros(1,2*K*K-1) ; for i=0:K-1 for j=0:K-1 C(:,j*K+i+1) = [d*j-D; d*i-D]+d/2 ; N(:,j*K+i+1) = 1 ; end end for i=1:length(parents) p = parents(i) ; if p==0, continue ; end; if all(isnan(C(:,i))), continue; end if all(isnan(C(:,p))) C(:,p) = C(:,i) / N(i) ; else C(:,p) = C(:,p) + C(:,i) / N(i) ; end N(p) = N(p) + 1 ; end C(1,:) = C(1,:) ./ N ; C(2,:) = C(2,:) ./ N ; xt = zeros(3, 2*length(parents)-1)+NaN ; yt = zeros(3, 2*length(parents)-1)+NaN ; for i=1:length(parents) p = parents(i) ; if p==0, continue ; end; xt(1,i) = C(1,i) ; xt(2,i) = C(1,p) ; yt(1,i) = C(2,i) ; yt(2,i) = C(2,p) ; end h=line(xt(:),yt(:),'linestyle','-','marker','.','linewidth',3) ;
github
Shenc0411/CS445-master
vl_demo_alldist.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/demo/vl_demo_alldist.m
5,460
utf_8
6d008a64d93445b9d7199b55d58db7eb
function vl_demo_alldist % numRepetitions = 3 ; numDimensions = 1000 ; numSamplesRange = [300] ; settingsRange = {{'alldist2', 'double', 'l2', }, ... {'alldist', 'double', 'l2', 'nosimd'}, ... {'alldist', 'double', 'l2' }, ... {'alldist2', 'single', 'l2', }, ... {'alldist', 'single', 'l2', 'nosimd'}, ... {'alldist', 'single', 'l2' }, ... {'alldist2', 'double', 'l1', }, ... {'alldist', 'double', 'l1', 'nosimd'}, ... {'alldist', 'double', 'l1' }, ... {'alldist2', 'single', 'l1', }, ... {'alldist', 'single', 'l1', 'nosimd'}, ... {'alldist', 'single', 'l1' }, ... {'alldist2', 'double', 'chi2', }, ... {'alldist', 'double', 'chi2', 'nosimd'}, ... {'alldist', 'double', 'chi2' }, ... {'alldist2', 'single', 'chi2', }, ... {'alldist', 'single', 'chi2', 'nosimd'}, ... {'alldist', 'single', 'chi2' }, ... {'alldist2', 'double', 'hell', }, ... {'alldist', 'double', 'hell', 'nosimd'}, ... {'alldist', 'double', 'hell' }, ... {'alldist2', 'single', 'hell', }, ... {'alldist', 'single', 'hell', 'nosimd'}, ... {'alldist', 'single', 'hell' }, ... {'alldist2', 'double', 'kl2', }, ... {'alldist', 'double', 'kl2', 'nosimd'}, ... {'alldist', 'double', 'kl2' }, ... {'alldist2', 'single', 'kl2', }, ... {'alldist', 'single', 'kl2', 'nosimd'}, ... {'alldist', 'single', 'kl2' }, ... {'alldist2', 'double', 'kl1', }, ... {'alldist', 'double', 'kl1', 'nosimd'}, ... {'alldist', 'double', 'kl1' }, ... {'alldist2', 'single', 'kl1', }, ... {'alldist', 'single', 'kl1', 'nosimd'}, ... {'alldist', 'single', 'kl1' }, ... {'alldist2', 'double', 'kchi2', }, ... {'alldist', 'double', 'kchi2', 'nosimd'}, ... {'alldist', 'double', 'kchi2' }, ... {'alldist2', 'single', 'kchi2', }, ... {'alldist', 'single', 'kchi2', 'nosimd'}, ... {'alldist', 'single', 'kchi2' }, ... {'alldist2', 'double', 'khell', }, ... {'alldist', 'double', 'khell', 'nosimd'}, ... {'alldist', 'double', 'khell' }, ... {'alldist2', 'single', 'khell', }, ... {'alldist', 'single', 'khell', 'nosimd'}, ... {'alldist', 'single', 'khell' }, ... } ; %settingsRange = settingsRange(end-5:end) ; styles = {} ; for marker={'x','+','.','*','o'} for color={'r','g','b','k','y'} styles{end+1} = {'color', char(color), 'marker', char(marker)} ; end end for ni=1:length(numSamplesRange) for ti=1:length(settingsRange) tocs = [] ; for ri=1:numRepetitions rand('state',ri) ; randn('state',ri) ; numSamples = numSamplesRange(ni) ; settings = settingsRange{ti} ; [tocs(end+1), D] = run_experiment(numDimensions, ... numSamples, ... settings) ; end means(ni,ti) = mean(tocs) ; stds(ni,ti) = std(tocs) ; if mod(ti-1,3) == 0 D0 = D ; else err = max(abs(D(:)-D0(:))) ; fprintf('err %f\n', err) ; if err > 1, keyboard ; end end end end if 0 figure(1) ; clf ; hold on ; numStyles = length(styles) ; for ti=1:length(settingsRange) si = mod(ti - 1, numStyles) + 1 ; h(ti) = plot(numSamplesRange, means(:,ti), styles{si}{:}) ; leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ; errorbar(numSamplesRange, means(:,ti), stds(:,ti), 'linestyle', 'none') ; end end for ti=1:length(settingsRange) leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ; end figure(1) ; clf ; barh(means(end,:)) ; set(gca,'ytick', 1:length(leg), 'yticklabel', leg,'ydir','reverse') ; xlabel('Time [s]') ; function [elaps, D] = run_experiment(numDimensions, numSamples, settings) distType = 'l2' ; algType = 'alldist' ; classType = 'double' ; useSimd = true ; for si=1:length(settings) arg = settings{si} ; switch arg case {'l1', 'l2', 'chi2', 'hell', 'kl2', 'kl1', 'kchi2', 'khell'} distType = arg ; case {'alldist', 'alldist2'} algType = arg ; case {'single', 'double'} classType = arg ; case 'simd' useSimd = true ; case 'nosimd' useSimd = false ; otherwise assert(false) ; end end X = rand(numDimensions, numSamples) ; X(X < .3) = 0 ; switch classType case 'double' case 'single' X = single(X) ; end vl_simdctrl(double(useSimd)) ; switch algType case 'alldist' tic ; D = vl_alldist(X, distType) ; elaps = toc ; case 'alldist2' tic ; D = vl_alldist2(X, distType) ; elaps = toc ; end
github
Shenc0411/CS445-master
vl_demo_ikmeans.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/demo/vl_demo_ikmeans.m
774
utf_8
17ff0bb7259d390fb4f91ea937ba7de0
function vl_demo_ikmeans() % VL_DEMO_IKMEANS numData = 10000 ; dimension = 2 ; data = uint8(255*rand(dimension,numData)) ; numClusters = 3^3 ; [centers, assignments] = vl_ikmeans(data, numClusters); figure(1) ; clf ; axis off ; plotClusters(data, centers, assignments) ; vl_demo_print('ikmeans_2d',0.6); [tree, assignments] = vl_hikmeans(data,3,numClusters) ; figure(2) ; clf ; axis off ; plotClusters(data, [], [4 2 1] * double(assignments)) ; vl_demo_print('hikmeans_2d',0.6); function plotClusters(data, centers, assignments) hold on ; cc=jet(double(max(assignments(:)))); for i=1:max(assignments(:)) plot(data(1,assignments == i),data(2,assignments == i),'.','color',cc(i,:)); end if ~isempty(centers) plot(centers(1,:),centers(2,:),'k.','MarkerSize',20) end
github
Shenc0411/CS445-master
vl_demo_svm.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/demo/vl_demo_svm.m
1,235
utf_8
7cf6b3504e4fc2cbd10ff3fec6e331a7
% VL_DEMO_SVM Demo: SVM: 2D linear learning function vl_demo_svm y=[];X=[]; % Load training data X and their labels y load('vl_demo_svm_data.mat') Xp = X(:,y==1); Xn = X(:,y==-1); figure plot(Xn(1,:),Xn(2,:),'*r') hold on plot(Xp(1,:),Xp(2,:),'*b') axis equal ; vl_demo_print('svm_training') ; % Parameters lambda = 0.01 ; % Regularization parameter maxIter = 1000 ; % Maximum number of iterations energy = [] ; % Diagnostic function function diagnostics(svm) energy = [energy [svm.objective ; svm.dualObjective ; svm.dualityGap ] ] ; end % Training the SVM energy = [] ; [w b info] = vl_svmtrain(X, y, lambda,... 'MaxNumIterations',maxIter,... 'DiagnosticFunction',@diagnostics,... 'DiagnosticFrequency',1) % Visualisation eq = [num2str(w(1)) '*x+' num2str(w(2)) '*y+' num2str(b)]; line = ezplot(eq, [-0.9 0.9 -0.9 0.9]); set(line, 'Color', [0 0.8 0],'linewidth', 2); vl_demo_print('svm_training_result') ; figure hold on plot(energy(1,:),'--b') ; plot(energy(2,:),'-.g') ; plot(energy(3,:),'r') ; legend('Primal objective','Dual objective','Duality gap') xlabel('Diagnostics iteration') ylabel('Energy') vl_demo_print('svm_energy') ; end
github
Shenc0411/CS445-master
vl_demo_kdtree_sift.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/demo/vl_demo_kdtree_sift.m
6,832
utf_8
e676f80ac330a351f0110533c6ebba89
function vl_demo_kdtree_sift % VL_DEMO_KDTREE_SIFT % Demonstrates the use of a kd-tree forest to match SIFT % features. If FLANN is present, this function runs a comparison % against it. % AUTORIGHS rand('state',0) ; randn('state',0); do_median = 0 ; do_mean = 1 ; % try to setup flann if ~exist('flann_search', 'file') if exist(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) addpath(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) ; end end do_flann = exist('nearest_neighbors') == 3 ; if ~do_flann warning('FLANN not found. Comparison disabled.') ; end maxNumComparisonsRange = [1 10 50 100 200 300 400] ; numTreesRange = [1 2 5 10] ; % get data (SIFT features) im1 = imread(fullfile(vl_root, 'data', 'roofs1.jpg')) ; im2 = imread(fullfile(vl_root, 'data', 'roofs2.jpg')) ; im1 = single(rgb2gray(im1)) ; im2 = single(rgb2gray(im2)) ; [f1,d1] = vl_sift(im1,'firstoctave',-1,'floatdescriptors','verbose') ; [f2,d2] = vl_sift(im2,'firstoctave',-1,'floatdescriptors','verbose') ; % add some noise to make matches unique d1 = single(d1) + rand(size(d1)) ; d2 = single(d2) + rand(size(d2)) ; % match exhaustively to get the ground truth elapsedDirect = tic ; D = vl_alldist(d1,d2) ; [drop, best] = min(D, [], 1) ; elapsedDirect = toc(elapsedDirect) ; for ti=1:length(numTreesRange) for vi=1:length(maxNumComparisonsRange) v = maxNumComparisonsRange(vi) ; t = numTreesRange(ti) ; if do_median tic ; kdtree = vl_kdtreebuild(d1, ... 'verbose', ... 'thresholdmethod', 'median', ... 'numtrees', t) ; [i, d] = vl_kdtreequery(kdtree, d1, d2, ... 'verbose', ... 'maxcomparisons',v) ; elapsedKD_median(vi,ti) = toc ; errors_median(vi,ti) = sum(double(i) ~= best) / length(best) ; errorsD_median(vi,ti) = mean(abs(d - drop) ./ drop) ; end if do_mean tic ; kdtree = vl_kdtreebuild(d1, ... 'verbose', ... 'thresholdmethod', 'mean', ... 'numtrees', t) ; %kdtree = readflann(kdtree, '/tmp/flann.txt') ; %checkx(kdtree, d1, 1, 1) ; [i, d] = vl_kdtreequery(kdtree, d1, d2, ... 'verbose', ... 'maxcomparisons', v) ; elapsedKD_mean(vi,ti) = toc ; errors_mean(vi,ti) = sum(double(i) ~= best) / length(best) ; errorsD_mean(vi,ti) = mean(abs(d - drop) ./ drop) ; end if do_flann tic ; [i, d] = flann_search(d1, d2, 1, struct('algorithm','kdtree', ... 'trees', t, ... 'checks', v)); ifla = i ; elapsedKD_flann(vi,ti) = toc; errors_flann(vi,ti) = sum(i ~= best) / length(best) ; errorsD_flann(vi,ti) = mean(abs(d - drop) ./ drop) ; end end end figure(1) ; clf ; leg = {} ; hnd = [] ; sty = {{'color','r'},{'color','g'},... {'color','b'},{'color','c'},... {'color','k'}} ; for ti=1:length(numTreesRange) s = sty{mod(ti,length(sty))+1} ; if do_median h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errors_median(:,ti),'-*',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h1 ; end if do_mean h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errors_mean(:,ti), '-o',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h2 ; end if do_flann h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errors_flann(:,ti), '+--',s{:}) ; hold on ; leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h3 ; end end set([hnd], 'linewidth', 2) ; xlabel('speedup over linear search (log times)') ; ylabel('percentage of incorrect matches (%)') ; h=legend(hnd, leg{:}, 'location', 'southeast') ; set(h,'fontsize',8) ; grid on ; axis square ; vl_demo_print('kdtree_sift_incorrect',.6) ; figure(2) ; clf ; leg = {} ; hnd = [] ; for ti=1:length(numTreesRange) s = sty{mod(ti,length(sty))+1} ; if do_median h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errorsD_median(:,ti),'*-',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h1 ; end if do_mean h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errorsD_mean(:,ti), 'o-',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h2 ; end if do_flann h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errorsD_flann(:,ti), '+--',s{:}) ; hold on ; leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h3 ; end end set([hnd], 'linewidth', 2) ; xlabel('speedup over linear search (log times)') ; ylabel('relative overestimation of minmium distannce (%)') ; h=legend(hnd, leg{:}, 'location', 'southeast') ; set(h,'fontsize',8) ; grid on ; axis square ; vl_demo_print('kdtree_sift_distortion',.6) ; % -------------------------------------------------------------------- function checkx(kdtree, X, t, n, mib, mab) % -------------------------------------------------------------------- if nargin <= 4 mib = -inf * ones(size(X,1),1) ; mab = +inf * ones(size(X,1),1) ; end lc = kdtree.trees(t).nodes.lowerChild(n) ; uc = kdtree.trees(t).nodes.upperChild(n) ; if lc < 0 for i=-lc:-uc-1 di = kdtree.trees(t).dataIndex(i) ; if any(X(:,di) > mab) error('a') ; end if any(X(:,di) < mib) error('b') ; end end return end i = kdtree.trees(t).nodes.splitDimension(n) ; v = kdtree.trees(t).nodes.splitThreshold(n) ; mab_ = mab ; mab_(i) = min(mab(i), v) ; checkx(kdtree, X, t, lc, mib, mab_) ; mib_ = mib ; mib_(i) = max(mib(i), v) ; checkx(kdtree, X, t, uc, mib_, mab) ; % -------------------------------------------------------------------- function kdtree = readflann(kdtree, path) % -------------------------------------------------------------------- data = textread(path)' ; for i=1:size(data,2) nodeIds = data(1,:) ; ni = find(nodeIds == data(1,i)) ; if ~isnan(data(2,i)) % internal node li = find(nodeIds == data(4,i)) ; ri = find(nodeIds == data(5,i)) ; kdtree.trees(1).nodes.lowerChild(ni) = int32(li) ; kdtree.trees(1).nodes.upperChild(ni) = int32(ri) ; kdtree.trees(1).nodes.splitThreshold(ni) = single(data(2,i)) ; kdtree.trees(1).nodes.splitDimension(ni) = single(data(3,i)+1) ; else di = data(3,i) + 1 ; kdtree.trees(1).nodes.lowerChild(ni) = int32(- di) ; kdtree.trees(1).nodes.upperChild(ni) = int32(- di - 1) ; end kdtree.trees(1).dataIndex = uint32(1:kdtree.numData) ; end
github
Shenc0411/CS445-master
vl_impattern.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/imop/vl_impattern.m
6,876
utf_8
1716a4d107f0186be3d11c647bc628ce
function im = vl_impattern(varargin) % VL_IMPATTERN Generate an image from a stock pattern % IM=VLPATTERN(NAME) returns an instance of the specified % pattern. These stock patterns are useful for testing algoirthms. % % All generated patterns are returned as an image of class % DOUBLE. Both gray-scale and colour images have range in [0,1]. % % VL_IMPATTERN() without arguments shows a gallery of the stock % patterns. The following patterns are supported: % % Wedge:: % The image of a wedge. % % Cone:: % The image of a cone. % % SmoothChecker:: % A checkerboard with Gaussian filtering on top. Use the % option-value pair 'sigma', SIGMA to specify the standard % deviation of the smoothing and the pair 'step', STEP to specfity % the checker size in pixels. % % ThreeDotsSquare:: % A pattern with three small dots and two squares. % % UniformNoise:: % Random i.i.d. noise. % % Blobs: % Gaussian blobs of various sizes and anisotropies. % % Blobs1: % Gaussian blobs of various orientations and anisotropies. % % Blob: % One Gaussian blob. Use the option-value pairs 'sigma', % 'orientation', and 'anisotropy' to specify the respective % parameters. 'sigma' is the scalar standard deviation of an % isotropic blob (the image domain is the rectangle % [-1,1]^2). 'orientation' is the clockwise rotation (as the Y % axis points downards). 'anisotropy' (>= 1) is the ratio of the % the largest over the smallest axis of the blob (the smallest % axis length is set by 'sigma'). Set 'cut' to TRUE to cut half % half of the blob. % % A stock image:: % Any of 'box', 'roofs1', 'roofs2', 'river1', 'river2', 'spotted'. % % All pattern accept a SIZE parameter [WIDTH,HEIGHT]. For all but % the stock images, the default size is [128,128]. % Author: Andrea Vedaldi % Copyright (C) 2012 Andrea Vedaldi. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin > 0 pattern=varargin{1} ; varargin=varargin(2:end) ; else pattern = 'gallery' ; end patterns = {'wedge','cone','smoothChecker','threeDotsSquare', ... 'blob', 'blobs', 'blobs1', ... 'box', 'roofs1', 'roofs2', 'river1', 'river2'} ; % spooling switch lower(pattern) case 'wedge', im = wedge(varargin) ; case 'cone', im = cone(varargin) ; case 'smoothchecker', im = smoothChecker(varargin) ; case 'threedotssquare', im = threeDotSquare(varargin) ; case 'uniformnoise', im = uniformNoise(varargin) ; case 'blob', im = blob(varargin) ; case 'blobs', im = blobs(varargin) ; case 'blobs1', im = blobs1(varargin) ; case {'box','roofs1','roofs2','river1','river2','spots'} im = stockImage(pattern, varargin) ; case 'gallery' clf ; num = numel(patterns) ; for p = 1:num vl_tightsubplot(num,p,'box','outer') ; imagesc(vl_impattern(patterns{p}),[0 1]) ; axis image off ; title(patterns{p}) ; end colormap gray ; return ; otherwise error('Unknown patter ''%s''.', pattern) ; end if nargout == 0 clf ; imagesc(im) ; hold on ; colormap gray ; axis image off ; title(pattern) ; clear im ; end function [u,v,opts,args] = commonOpts(args) opts.size = [128 128] ; [opts,args] = vl_argparse(opts, args) ; ur = linspace(-1,1,opts.size(2)) ; vr = linspace(-1,1,opts.size(1)) ; [u,v] = meshgrid(ur,vr); function im = wedge(args) [u,v,opts,args] = commonOpts(args) ; im = abs(u) + abs(v) > (1/4) ; im(v < 0) = 0 ; function im = cone(args) [u,v,opts,args] = commonOpts(args) ; im = sqrt(u.^2+v.^2) ; im = im / max(im(:)) ; function im = smoothChecker(args) opts.size = [128 128] ; opts.step = 16 ; opts.sigma = 2 ; opts = vl_argparse(opts, args) ; [u,v] = meshgrid(0:opts.size(1)-1, 0:opts.size(2)-1) ; im = xor((mod(u,opts.step*2) < opts.step),... (mod(v,opts.step*2) < opts.step)) ; im = double(im) ; im = vl_imsmooth(im, opts.sigma) ; function im = threeDotSquare(args) [u,v,opts,args] = commonOpts(args) ; im = ones(size(u)) ; im(-2/3<u & u<2/3 & -2/3<v & v<2/3) = .75 ; im(-1/3<u & u<1/3 & -1/3<v & v<1/3) = .50 ; [drop,i] = min(abs(v(:,1))) ; [drop,j1] = min(abs(u(1,:)-1/6)) ; [drop,j2] = min(abs(u(1,:))) ; [drop,j3] = min(abs(u(1,:)+1/6)) ; im(i,j1) = 0 ; im(i,j2) = 0 ; im(i,j3) = 0 ; function im = blobs(args) [u,v,opts,args] = commonOpts(args) ; im = zeros(size(u)) ; num = 5 ; square = 2 / num ; sigma = square / 2 / 3 ; scales = logspace(log10(0.5), log10(1), num) ; skews = linspace(1,2,num) ; for i=1:num for j=1:num cy = (i-1) * square + square/2 - 1; cx = (j-1) * square + square/2 - 1; A = sigma * diag([scales(i) scales(i)/skews(j)]) * [1 -1 ; 1 1] / sqrt(2) ; C = inv(A'*A) ; x = u - cx ; y = v - cy ; im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ; end end im = im / max(im(:)) ; function im = blob(args) [u,v,opts,args] = commonOpts(args) ; opts.sigma = 0.15 ; opts.anisotropy = .5 ; opts.orientation = 2/3 * pi ; opts.cut = false ; opts = vl_argparse(opts, args) ; im = zeros(size(u)) ; th = opts.orientation ; R = [cos(th) -sin(th) ; sin(th) cos(th)] ; A = opts.sigma * R * diag([opts.anisotropy 1]) ; T = [0;0] ; [x,y] = vl_waffine(inv(A),-inv(A)*T,u,v) ; im = exp(-0.5 *(x.^2 + y.^2)) ; if opts.cut im = im .* double(x > 0) ; end function im = blobs1(args) [u,v,opts,args] = commonOpts(args) ; opts.number = 5 ; opts.sigma = [] ; opts = vl_argparse(opts, args) ; im = zeros(size(u)) ; square = 2 / opts.number ; num = opts.number ; if isempty(opts.sigma) sigma = 1/6 * square ; else sigma = opts.sigma * square ; end rotations = linspace(0,pi,num+1) ; rotations(end) = [] ; skews = linspace(1,2,num) ; for i=1:num for j=1:num cy = (i-1) * square + square/2 - 1; cx = (j-1) * square + square/2 - 1; th = rotations(i) ; R = [cos(th) -sin(th); sin(th) cos(th)] ; A = sigma * R * diag([1 1/skews(j)]) ; C = inv(A*A') ; x = u - cx ; y = v - cy ; im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ; end end im = im / max(im(:)) ; function im = uniformNoise(args) opts.size = [128 128] ; opts.seed = 1 ; opts = vl_argparse(opts, args) ; state = vl_twister('state') ; vl_twister('state',opts.seed) ; im = vl_twister(opts.size([2 1])) ; vl_twister('state',state) ; function im = stockImage(pattern,args) opts.size = [] ; opts = vl_argparse(opts, args) ; switch pattern case 'river1', path='river1.jpg' ; case 'river2', path='river2.jpg' ; case 'roofs1', path='roofs1.jpg' ; case 'roofs2', path='roofs2.jpg' ; case 'box', path='box.pgm' ; case 'spots', path='spots.jpg' ; end im = imread(fullfile(vl_root,'data',path)) ; im = im2double(im) ; if ~isempty(opts.size) im = imresize(im, opts.size) ; im = max(im,0) ; im = min(im,1) ; end
github
Shenc0411/CS445-master
vl_tpsu.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/imop/vl_tpsu.m
1,755
utf_8
09f36e1a707c069b375eb2817d0e5f13
function [U,dU,delta]=vl_tpsu(X,Y) % VL_TPSU Compute the U matrix of a thin-plate spline transformation % U=VL_TPSU(X,Y) returns the matrix % % [ U(|X(:,1) - Y(:,1)|) ... U(|X(:,1) - Y(:,N)|) ] % [ ] % [ U(|X(:,M) - Y(:,1)|) ... U(|X(:,M) - Y(:,N)|) ] % % where X is a 2xM matrix and Y a 2xN matrix of points and U(r) is % the opposite -r^2 log(r^2) of the radial basis function of the % thin plate spline specified by X and Y. % % [U,dU]=vl_tpsu(x,y) returns the derivatives of the columns of U with % respect to the parameters Y. The derivatives are arranged in a % Mx2xN array, one layer per column of U. % % See also: VL_TPS(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if exist('tpsumx') U = tpsumx(X,Y) ; else M=size(X,2) ; N=size(Y,2) ; % Faster than repmat, but still fairly slow r2 = ... (X( ones(N,1), :)' - Y( ones(1,M), :)).^2 + ... (X( 1+ones(N,1), :)' - Y(1+ones(1,M), :)).^2 ; U = - rb(r2) ; end if nargout > 1 M=size(X,2) ; N=size(Y,2) ; dx = X( ones(N,1), :)' - Y( ones(1,M), :) ; dy = X(1+ones(N,1), :)' - Y(1+ones(1,M), :) ; r2 = (dx.^2 + dy.^2) ; r = sqrt(r2) ; coeff = drb(r)./(r+eps) ; dU = reshape( [coeff .* dx ; coeff .* dy], M, 2, N) ; end % The radial basis function function y = rb(r2) y = zeros(size(r2)) ; sel = find(r2 ~= 0) ; y(sel) = - r2(sel) .* log(r2(sel)) ; % The derivative of the radial basis function function y = drb(r) y = zeros(size(r)) ; sel = find(r ~= 0) ; y(sel) = - 4 * r(sel) .* log(r(sel)) - 2 * r(sel) ;
github
Shenc0411/CS445-master
vl_xyz2lab.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/imop/vl_xyz2lab.m
1,570
utf_8
09f95a6f9ae19c22486ec1157357f0e3
function J=vl_xyz2lab(I,il) % VL_XYZ2LAB Convert XYZ color space to LAB % J = VL_XYZ2LAB(I) converts the image from XYZ format to LAB format. % % VL_XYZ2LAB(I,IL) uses one of the illuminants A, B, C, E, D50, D55, % D65, D75, D93. The default illuminatn is E. % % See also: VL_XYZ2LUV(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin < 2 il='E' ; end switch lower(il) case 'a' xw = 0.4476 ; yw = 0.4074 ; case 'b' xw = 0.3324 ; yw = 0.3474 ; case 'c' xw = 0.3101 ; yw = 0.3162 ; case 'e' xw = 1/3 ; yw = 1/3 ; case 'd50' xw = 0.3457 ; yw = 0.3585 ; case 'd55' xw = 0.3324 ; yw = 0.3474 ; case 'd65' xw = 0.312713 ; yw = 0.329016 ; case 'd75' xw = 0.299 ; yw = 0.3149 ; case 'd93' xw = 0.2848 ; yw = 0.2932 ; end J=zeros(size(I)) ; % Reference white Yw = 1.0 ; Xw = xw/yw ; Zw = (1-xw-yw)/yw * Yw ; % XYZ components X = I(:,:,1) ; Y = I(:,:,2) ; Z = I(:,:,3) ; x = X/Xw ; y = Y/Yw ; z = Z/Zw ; L = 116 * f(y) - 16 ; a = 500*(f(x) - f(y)) ; b = 200*(f(y) - f(z)) ; J = cat(3,L,a,b) ; % -------------------------------------------------------------------- function b=f(a) % -------------------------------------------------------------------- sp = find(a > 0.00856) ; sm = find(a <= 0.00856) ; k = 903.3 ; b=zeros(size(a)) ; b(sp) = a(sp).^(1/3) ; b(sm) = (k*a(sm) + 16)/116 ;
github
Shenc0411/CS445-master
vl_test_gmm.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_gmm.m
1,332
utf_8
76782cae6c98781c6c38d4cbf5549d94
function results = vl_test_gmm(varargin) % VL_TEST_GMM % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). vl_test_init ; end function s = setup() randn('state',0) ; s.X = randn(128, 1000) ; end function test_multithreading(s) dataTypes = {'single','double'} ; for dataType = dataTypes conversion = str2func(char(dataType)) ; X = conversion(s.X) ; vl_twister('state',0) ; vl_threads(0) ; [means, covariances, priors, ll, posteriors] = ... vl_gmm(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Initialization', 'rand') ; vl_twister('state',0) ; vl_threads(1) ; [means_, covariances_, priors_, ll_, posteriors_] = ... vl_gmm(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Initialization', 'rand') ; vl_assert_almost_equal(means, means_, 1e-2) ; vl_assert_almost_equal(covariances, covariances_, 1e-2) ; vl_assert_almost_equal(priors, priors_, 1e-2) ; vl_assert_almost_equal(ll, ll_, 1e-2 * abs(ll)) ; vl_assert_almost_equal(posteriors, posteriors_, 1e-2) ; end end
github
Shenc0411/CS445-master
vl_test_twister.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_twister.m
1,251
utf_8
2bfb5a30cbd6df6ac80c66b73f8646da
function results = vl_test_twister(varargin) % VL_TEST_TWISTER vl_test_init ; function test_illegal_args() vl_assert_exception(@() vl_twister(-1), 'vl:invalidArgument') ; vl_assert_exception(@() vl_twister(1, -1), 'vl:invalidArgument') ; vl_assert_exception(@() vl_twister([1, -1]), 'vl:invalidArgument') ; function test_seed_by_scalar() rand('twister',1) ; a = rand ; vl_twister('state',1) ; b = vl_twister ; vl_assert_equal(a,b,'seed by scalar + VL_TWISTER()') ; function test_get_set_state() rand('twister',1) ; a = rand('twister') ; vl_twister('state',1) ; b = vl_twister('state') ; vl_assert_equal(a,b,'read state') ; a(1) = a(1) + 1 ; vl_twister('state',a) ; b = vl_twister('state') ; vl_assert_equal(a,b,'set state') ; function test_multi_dimensions() b = rand('twister') ; rand('twister',b) ; vl_twister('state',b) ; a=rand([1 2 3 4 5]) ; b=vl_twister([1 2 3 4 5]) ; vl_assert_equal(a,b,'VL_TWISTER([M N P ...])') ; function test_multi_multi_args() rand('twister',1) ; a=rand(1, 2, 3, 4, 5) ; vl_twister('state',1) ; b=vl_twister(1, 2, 3, 4, 5) ; vl_assert_equal(a,b,'VL_TWISTER(M, N, P, ...)') ; function test_square() rand('twister',1) ; a=rand(10) ; vl_twister('state',1) ; b=vl_twister(10) ; vl_assert_equal(a,b,'VL_TWISTER(N)') ;
github
Shenc0411/CS445-master
vl_test_kdtree.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_kdtree.m
2,449
utf_8
9d7ad2b435a88c22084b38e5eb5f9eb9
function results = vl_test_kdtree(varargin) % VL_TEST_KDTREE vl_test_init ; function s = setup() randn('state',0) ; s.X = single(randn(10, 1000)) ; s.Q = single(randn(10, 10)) ; function test_nearest(s) for tmethod = {'median', 'mean'} for type = {@single, @double} conv = type{1} ; tmethod = char(tmethod) ; X = conv(s.X) ; Q = conv(s.Q) ; tree = vl_kdtreebuild(X,'ThresholdMethod', tmethod) ; [nn, d2] = vl_kdtreequery(tree, X, Q) ; D2 = vl_alldist2(X, Q, 'l2') ; [d2_, nn_] = min(D2) ; vl_assert_equal(... nn,uint32(nn_),... 'incorrect nns: type=%s th. method=%s', func2str(conv), tmethod) ; vl_assert_almost_equal(... d2,d2_,... 'incorrect distances: type=%s th. method=%s', func2str(conv), tmethod) ; end end function test_nearests(s) numNeighbors = 7 ; tree = vl_kdtreebuild(s.X) ; [nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ... 'numNeighbors', numNeighbors) ; D2 = vl_alldist2(s.X, s.Q, 'l2') ; [d2_, nn_] = sort(D2) ; d2_ = d2_(1:numNeighbors, :) ; nn_ = nn_(1:numNeighbors, :) ; vl_assert_equal(nn,uint32(nn_)) ; vl_assert_almost_equal(d2,d2_) ; function test_ann(s) vl_twister('state', 1) ; numNeighbors = 7 ; maxComparisons = numNeighbors * 50 ; tree = vl_kdtreebuild(s.X) ; [nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ... 'numNeighbors', numNeighbors, ... 'maxComparisons', maxComparisons) ; D2 = vl_alldist2(s.X, s.Q, 'l2') ; [d2_, nn_] = sort(D2) ; d2_ = d2_(1:numNeighbors, :) ; nn_ = nn_(1:numNeighbors, :) ; for i=1:size(s.Q,2) overlap = numel(intersect(nn(:,i), nn_(:,i))) / ... numel(union(nn(:,i), nn_(:,i))) ; assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ; end function test_ann_forest(s) vl_twister('state', 1) ; numNeighbors = 7 ; maxComparisons = numNeighbors * 25 ; numTrees = 5 ; tree = vl_kdtreebuild(s.X, 'numTrees', 5) ; [nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ... 'numNeighbors', numNeighbors, ... 'maxComparisons', maxComparisons) ; D2 = vl_alldist2(s.X, s.Q, 'l2') ; [d2_, nn_] = sort(D2) ; d2_ = d2_(1:numNeighbors, :) ; nn_ = nn_(1:numNeighbors, :) ; for i=1:size(s.Q,2) overlap = numel(intersect(nn(:,i), nn_(:,i))) / ... numel(union(nn(:,i), nn_(:,i))) ; assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ; end
github
Shenc0411/CS445-master
vl_test_imwbackward.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_imwbackward.m
514
utf_8
33baa0784c8f6f785a2951d7f1b49199
function results = vl_test_imwbackward(varargin) % VL_TEST_IMWBACKWARD vl_test_init ; function s = setup() s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; function test_identity(s) xr = 1:size(s.I,2) ; yr = 1:size(s.I,1) ; [x,y] = meshgrid(xr,yr) ; vl_assert_almost_equal(s.I, vl_imwbackward(xr,yr,s.I,x,y)) ; function test_invalid_args(s) xr = 1:size(s.I,2) ; yr = 1:size(s.I,1) ; [x,y] = meshgrid(xr,yr) ; vl_assert_exception(@() vl_imwbackward(xr,yr,single(s.I),x,y), 'vl:invalidArgument') ;
github
Shenc0411/CS445-master
vl_test_alphanum.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_alphanum.m
1,624
utf_8
2da2b768c2d0f86d699b8f31614aa424
function results = vl_test_alphanum(varargin) % VL_TEST_ALPHANUM vl_test_init ; function s = setup() s.strings = ... {'1000X Radonius Maximus','10X Radonius','200X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','Allegia 50 Clasteron','Allegia 500 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 6R Clasteron','Alpha 100','Alpha 2','Alpha 200','Alpha 2A','Alpha 2A-8000','Alpha 2A-900','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 5000','Callisto Morphamax 600','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 700','Callisto Morphamax 7000','Xiph Xlater 10000','Xiph Xlater 2000','Xiph Xlater 300','Xiph Xlater 40','Xiph Xlater 5','Xiph Xlater 50','Xiph Xlater 500','Xiph Xlater 5000','Xiph Xlater 58'} ; s.sortedStrings = ... {'10X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','200X Radonius','1000X Radonius Maximus','Allegia 6R Clasteron','Allegia 50 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 500 Clasteron','Alpha 2','Alpha 2A','Alpha 2A-900','Alpha 2A-8000','Alpha 100','Alpha 200','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 600','Callisto Morphamax 700','Callisto Morphamax 5000','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 7000','Xiph Xlater 5','Xiph Xlater 40','Xiph Xlater 50','Xiph Xlater 58','Xiph Xlater 300','Xiph Xlater 500','Xiph Xlater 2000','Xiph Xlater 5000','Xiph Xlater 10000'} ; function test_basic(s) sorted = vl_alphanum(s.strings) ; assert(isequal(sorted,s.sortedStrings)) ;
github
Shenc0411/CS445-master
vl_test_printsize.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_printsize.m
1,447
utf_8
0f0b6437c648b7a2e1310900262bd765
function results = vl_test_printsize(varargin) % VL_TEST_PRINTSIZE vl_test_init ; function s = setup() s.fig = figure(1) ; s.usletter = [8.5, 11] ; % inches s.a4 = [8.26772, 11.6929] ; clf(s.fig) ; plot(1:10) ; function teardown(s) close(s.fig) ; function test_basic(s) for sigma = [1 0.5 0.2] vl_printsize(s.fig, sigma) ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(1), sigma*s.usletter(1), 1e-4) ; vl_assert_almost_equal(pos(1), 0, 1e-4) ; vl_assert_almost_equal(pos(3), sigma*s.usletter(1), 1e-4) ; end function test_papertype(s) vl_printsize(s.fig, 1, 'papertype', 'a4') ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(1), s.a4(1), 1e-4) ; function test_margin(s) m = 0.5 ; vl_printsize(s.fig, 1, 'margin', m) ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(1), s.usletter(1) * (1 + 2*m), 1e-4) ; vl_assert_almost_equal(pos(1), s.usletter(1) * m, 1e-4) ; function test_reference(s) sigma = 1 ; vl_printsize(s.fig, 1, 'reference', 'vertical') ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(2), sigma*s.usletter(2), 1e-4) ; vl_assert_almost_equal(pos(2), 0, 1e-4) ; vl_assert_almost_equal(pos(4), sigma*s.usletter(2), 1e-4) ;
github
Shenc0411/CS445-master
vl_test_cummax.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_cummax.m
838
utf_8
5e98ee1681d4823f32ecc4feaa218611
function results = vl_test_cummax(varargin) % VL_TEST_CUMMAX vl_test_init ; function test_basic() vl_assert_almost_equal(... vl_cummax(1), 1) ; vl_assert_almost_equal(... vl_cummax([1 2 3 4], 2), [1 2 3 4]) ; function test_multidim() a = [1 2 3 4 3 2 1] ; b = [1 2 3 4 4 4 4] ; for k=1:6 dims = ones(1,6) ; dims(k) = numel(a) ; a = reshape(a, dims) ; b = reshape(b, dims) ; vl_assert_almost_equal(... vl_cummax(a, k), b) ; end function test_storage_classes() types = {@double, @single, ... @int32, @uint32, ... @int16, @uint16, ... @int8, @uint8} ; if vl_matlabversion() > 71000 types = horzcat(types, {@int64, @uint64}) ; end for a = types a = a{1} ; for b = types b = b{1} ; vl_assert_almost_equal(... vl_cummax(a(eye(3))), a(toeplitz([1 1 1], [1 0 0 ]))) ; end end
github
Shenc0411/CS445-master
vl_test_imintegral.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_imintegral.m
1,429
utf_8
4750f04ab0ac9fc4f55df2c8583e5498
function results = vl_test_imintegral(varargin) % VL_TEST_IMINTEGRAL vl_test_init ; function state = setup() state.I = ones(5,6) ; state.correct = [ 1 2 3 4 5 6 ; 2 4 6 8 10 12 ; 3 6 9 12 15 18 ; 4 8 12 16 20 24 ; 5 10 15 20 25 30 ; ] ; function test_matlab_equivalent(s) vl_assert_equal(slow_imintegral(s.I), s.correct) ; function test_basic(s) vl_assert_equal(vl_imintegral(s.I), s.correct) ; function test_multi_dimensional(s) vl_assert_equal(vl_imintegral(repmat(s.I, [1 1 3])), ... repmat(s.correct, [1 1 3])) ; function test_random(s) numTests = 50 ; for i = 1:numTests I = rand(5) ; vl_assert_almost_equal(vl_imintegral(s.I), ... slow_imintegral(s.I)) ; end function test_datatypes(s) vl_assert_equal(single(vl_imintegral(s.I)), single(s.correct)) ; vl_assert_equal(double(vl_imintegral(s.I)), double(s.correct)) ; vl_assert_equal(uint32(vl_imintegral(s.I)), uint32(s.correct)) ; vl_assert_equal(int32(vl_imintegral(s.I)), int32(s.correct)) ; vl_assert_equal(int32(vl_imintegral(-s.I)), -int32(s.correct)) ; function integral = slow_imintegral(I) integral = zeros(size(I)); for k = 1:size(I,3) for r = 1:size(I,1) for c = 1:size(I,2) integral(r,c,k) = sum(sum(I(1:r,1:c,k))); end end end
github
Shenc0411/CS445-master
vl_test_sift.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_sift.m
1,318
utf_8
806c61f9db9f2ebb1d649c9bfcf3dc0a
function results = vl_test_sift(varargin) % VL_TEST_SIFT vl_test_init ; function s = setup() s.I = im2single(imread(fullfile(vl_root,'data','box.pgm'))) ; [s.ubc.f, s.ubc.d] = ... vl_ubcread(fullfile(vl_root,'data','box.sift')) ; function test_ubc_descriptor(s) err = [] ; [f, d] = vl_sift(s.I,... 'firstoctave', -1, ... 'frames', s.ubc.f) ; D2 = vl_alldist(f, s.ubc.f) ; [drop, perm] = min(D2) ; f = f(:,perm) ; d = d(:,perm) ; error = mean(sqrt(sum((single(s.ubc.d) - single(d)).^2))) ... / mean(sqrt(sum(single(s.ubc.d).^2))) ; assert(error < 0.1, ... 'sift descriptor did not produce desctiptors similar to UBC ones') ; function test_ubc_detector(s) [f, d] = vl_sift(s.I,... 'firstoctave', -1, ... 'peakthresh', .01, ... 'edgethresh', 10) ; s.ubc.f(4,:) = mod(s.ubc.f(4,:), 2*pi) ; f(4,:) = mod(f(4,:), 2*pi) ; % scale the components so that 1 pixel erro in x,y,z is equal to a % 10-th of angle. S = diag([1 1 1 20/pi]); D2 = vl_alldist(S * s.ubc.f, S * f) ; [d2,perm] = sort(min(D2)) ; error = sqrt(d2) ; quant80 = round(.8 * size(f,2)) ; % check for less than one pixel error at 80% quantile assert(error(quant80) < 1, ... 'sift detector did not produce enough keypoints similar to UBC ones') ;
github
Shenc0411/CS445-master
vl_test_binsum.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_binsum.m
1,377
utf_8
f07f0f29ba6afe0111c967ab0b353a9d
function results = vl_test_binsum(varargin) % VL_TEST_BINSUM vl_test_init ; function test_three_args() vl_assert_almost_equal(... vl_binsum([0 0], 1, 2), [0 1]) ; vl_assert_almost_equal(... vl_binsum([1 7], -1, 1), [0 7]) ; vl_assert_almost_equal(... vl_binsum([1 7], -1, [1 2 2 2 2 2 2 2]), [0 0]) ; function test_four_args() vl_assert_almost_equal(... vl_binsum(eye(3), [1 1 1], [1 2 3], 1), 2*eye(3)) ; vl_assert_almost_equal(... vl_binsum(eye(3), [1 1 1]', [1 2 3]', 2), 2*eye(3)) ; vl_assert_almost_equal(... vl_binsum(eye(3), 1, [1 2 3], 1), 2*eye(3)) ; vl_assert_almost_equal(... vl_binsum(eye(3), 1, [1 2 3]', 2), 2*eye(3)) ; function test_3d_one() Z = zeros(3,3,3) ; B = 3*ones(3,1,3) ; R = Z ; R(:,3,:) = 17 ; vl_assert_almost_equal(... vl_binsum(Z, 17, B, 2), R) ; function test_3d_two() Z = zeros(3,3,3) ; B = 3*ones(3,3,1) ; X = zeros(3,3,1) ; X(:,:,1) = 17 ; R = Z ; R(:,:,3) = 17 ; vl_assert_almost_equal(... vl_binsum(Z, X, B, 3), R) ; function test_storage_classes() types = {@double, @single, ... @int32, @uint32, ... @int16, @uint16, ... @int8, @uint8} ; if vl_matlabversion() > 71000 types = horzcat(types, {@int64, @uint64}) ; end for a = types a = a{1} ; for b = types b = b{1} ; vl_assert_almost_equal(... vl_binsum(a(eye(3)), a([1 1 1]), b([1 2 3]), 1), a(2*eye(3))) ; end end
github
Shenc0411/CS445-master
vl_test_lbp.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_lbp.m
892
utf_8
a79c0ce0c85e25c0b1657f3a0b499538
function results = vl_test_lbp(varargin) % VL_TEST_TWISTER vl_test_init ; function test_unfiorm_lbps(s) % enumerate the 56 uniform lbps q = 0 ; for i=0:7 for j=1:7 I = zeros(3) ; p = mod(s.pixels - i + 8, 8) + 1 ; I(p <= j) = 1 ; f = vl_lbp(single(I), 3) ; q = q + 1 ; vl_assert_equal(find(f), q) ; end end % constant lbps I = [1 1 1 ; 1 0 1 ; 1 1 1] ; f = vl_lbp(single(I), 3) ; vl_assert_equal(find(f), 57) ; I = [1 1 1 ; 1 1 1 ; 1 1 1] ; f = vl_lbp(single(I), 3) ; vl_assert_equal(find(f), 57) ; % other lbps I = [1 0 1 ; 0 0 0 ; 1 0 1] ; f = vl_lbp(single(I), 3) ; vl_assert_equal(find(f), 58) ; function test_fliplr(s) randn('state',0) ; I = randn(256,256,1,'single') ; f = vl_lbp(fliplr(I), 8) ; f_ = vl_lbpfliplr(vl_lbp(I, 8)) ; vl_assert_almost_equal(f,f_,1e-3) ; function s = setup() s.pixels = [5 6 7 ; 4 NaN 0 ; 3 2 1] ;
github
Shenc0411/CS445-master
vl_test_colsubset.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_colsubset.m
828
utf_8
be0c080007445b36333b863326fb0f15
function results = vl_test_colsubset(varargin) % VL_TEST_COLSUBSET vl_test_init ; function s = setup() s.x = [5 2 3 6 4 7 1 9 8 0] ; function test_beginning(s) vl_assert_equal(1:5, vl_colsubset(1:10, 5, 'beginning')) ; vl_assert_equal(1:5, vl_colsubset(1:10, .5, 'beginning')) ; function test_ending(s) vl_assert_equal(6:10, vl_colsubset(1:10, 5, 'ending')) ; vl_assert_equal(6:10, vl_colsubset(1:10, .5, 'ending')) ; function test_largest(s) vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, 5, 'largest')) ; vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, .5, 'largest')) ; function test_smallest(s) vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, 5, 'smallest')) ; vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, .5, 'smallest')) ; function test_random(s) assert(numel(intersect(s.x, vl_colsubset(s.x, 5, 'random'))) == 5) ;
github
Shenc0411/CS445-master
vl_test_alldist.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_alldist.m
2,373
utf_8
9ea1a36c97fe715dfa2b8693876808ff
function results = vl_test_alldist(varargin) % VL_TEST_ALLDIST vl_test_init ; function s = setup() vl_twister('state', 0) ; s.X = 3.1 * vl_twister(10,10) ; s.Y = 4.7 * vl_twister(10,7) ; function test_null_args(s) vl_assert_equal(... vl_alldist(zeros(15,12), zeros(15,0), 'kl2'), ... zeros(12,0)) ; vl_assert_equal(... vl_alldist(zeros(15,0), zeros(15,0), 'kl2'), ... zeros(0,0)) ; vl_assert_equal(... vl_alldist(zeros(15,0), zeros(15,12), 'kl2'), ... zeros(0,12)) ; vl_assert_equal(... vl_alldist(zeros(0,15), zeros(0,12), 'kl2'), ... zeros(15,12)) ; function test_self(s) vl_assert_almost_equal(... vl_alldist(s.X, 'kl2'), ... makedist(@(x,y) x*y, s.X, s.X), ... 1e-6) ; function test_distances(s) dists = {'chi2', 'l2', 'l1', 'hell', 'js', ... 'kchi2', 'kl2', 'kl1', 'khell', 'kjs'} ; distsEquiv = { ... @(x,y) (x-y)^2 / (x + y), ... @(x,y) (x-y)^2, ... @(x,y) abs(x-y), ... @(x,y) (sqrt(x) - sqrt(y))^2, ... @(x,y) x - x .* log2(1 + y/x) + y - y .* log2(1 + x/y), ... @(x,y) 2 * (x*y) / (x + y), ... @(x,y) x*y, ... @(x,y) min(x,y), ... @(x,y) sqrt(x.*y), ... @(x,y) .5 * (x .* log2(1 + y/x) + y .* log2(1 + x/y))} ; types = {'single', 'double'} ; for simd = [0 1] for d = 1:length(dists) for t = 1:length(types) vl_simdctrl(simd) ; X = feval(str2func(types{t}), s.X) ; Y = feval(str2func(types{t}), s.Y) ; vl_assert_almost_equal(... vl_alldist(X,Y,dists{d}), ... makedist(distsEquiv{d},X,Y), ... 1e-4, ... 'alldist failed for dist=%s type=%s simd=%d', ... dists{d}, ... types{t}, ... simd) ; end end end function test_distance_kernel_pairs(s) dists = {'chi2', 'l2', 'l1', 'hell', 'js'} ; for d = 1:length(dists) dist = char(dists{d}) ; X = s.X ; Y = s.Y ; ker = ['k' dist] ; kxx = vl_alldist(X,X,ker) ; kyy = vl_alldist(Y,Y,ker) ; kxy = vl_alldist(X,Y,ker) ; kxx = repmat(diag(kxx), 1, size(s.Y,2)) ; kyy = repmat(diag(kyy), 1, size(s.X,1))' ; d2 = vl_alldist(X,Y,dist) ; vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ; end function D = makedist(cmp,X,Y) [d,m] = size(X) ; [d,n] = size(Y) ; D = zeros(m,n) ; for i = 1:m for j = 1:n acc = 0 ; for k = 1:d acc = acc + cmp(X(k,i),Y(k,j)) ; end D(i,j) = acc ; end end conv = str2func(class(X)) ; D = conv(D) ;
github
Shenc0411/CS445-master
vl_test_ihashsum.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_ihashsum.m
581
utf_8
edc283062469af62056b0782b171f5fc
function results = vl_test_ihashsum(varargin) % VL_TEST_IHASHSUM vl_test_init ; function s = setup() rand('state',0) ; s.data = uint8(round(16*rand(2,100))) ; sel = find(all(s.data==0)) ; s.data(1,sel)=1 ; function test_hash(s) D = size(s.data,1) ; K = 5 ; h = zeros(1,K,'uint32') ; id = zeros(D,K,'uint8'); next = zeros(1,K,'uint32') ; [h,id,next] = vl_ihashsum(h,id,next,K,s.data) ; sel = vl_ihashfind(id,next,K,s.data) ; count = double(h(sel)) ; [drop,i,j] = unique(s.data','rows') ; for k=1:size(s.data,2) count_(k) = sum(j == j(k)) ; end vl_assert_equal(count,count_) ;
github
Shenc0411/CS445-master
vl_test_grad.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_grad.m
434
utf_8
4d03eb33a6a4f68659f868da95930ffb
function results = vl_test_grad(varargin) % VL_TEST_GRAD vl_test_init ; function s = setup() s.I = rand(150,253) ; s.I_small = rand(2,2) ; function test_equiv(s) vl_assert_equal(gradient(s.I), vl_grad(s.I)) ; function test_equiv_small(s) vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ; function test_equiv_forward(s) Ix = diff(s.I,2,1) ; Iy = diff(s.I,2,1) ; vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;
github
Shenc0411/CS445-master
vl_test_whistc.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_whistc.m
1,384
utf_8
81c446d35c82957659840ab2a579ec2c
function results = vl_test_whistc(varargin) % VL_TEST_WHISTC vl_test_init ; function test_acc() x = ones(1, 10) ; e = 1 ; o = 1:10 ; vl_assert_equal(vl_whistc(x, o, e), 55) ; function test_basic() x = 1:10 ; e = 1:10 ; o = ones(1, 10) ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; x = linspace(-1,11,100) ; o = ones(size(x)) ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; function test_multidim() x = rand(10, 20, 30) ; e = linspace(0,1,10) ; o = ones(size(x)) ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ; vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ; vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ; function test_nan() x = rand(10, 20, 30) ; e = linspace(0,1,10) ; o = ones(size(x)) ; x(1:7:end) = NaN ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ; vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ; vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ; function test_no_edges() x = rand(10, 20, 30) ; o = ones(size(x)) ; vl_assert_equal(histc(1, []), vl_whistc(1, 1, [])) ; vl_assert_equal(histc(x, []), vl_whistc(x, o, [])) ; vl_assert_equal(histc(x, [], 1), vl_whistc(x, o, [], 1)) ; vl_assert_equal(histc(x, [], 2), vl_whistc(x, o, [], 2)) ; vl_assert_equal(histc(x, [], 3), vl_whistc(x, o, [], 3)) ;
github
Shenc0411/CS445-master
vl_test_roc.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_roc.m
1,019
utf_8
9b2ae71c9dc3eda0fc54c65d55054d0c
function results = vl_test_roc(varargin) % VL_TEST_ROC vl_test_init ; function s = setup() s.scores0 = [5 4 3 2 1] ; s.scores1 = [5 3 4 2 1] ; s.labels = [1 1 -1 -1 -1] ; function test_perfect_tptn(s) [tpr,tnr] = vl_roc(s.labels,s.scores0) ; vl_assert_almost_equal(tpr, [0 1 2 2 2 2] / 2) ; vl_assert_almost_equal(tnr, [3 3 3 2 1 0] / 3) ; function test_perfect_metrics(s) [tpr,tnr,info] = vl_roc(s.labels,s.scores0) ; vl_assert_almost_equal(info.eer, 0) ; vl_assert_almost_equal(info.auc, 1) ; function test_swap1_tptn(s) [tpr,tnr] = vl_roc(s.labels,s.scores1) ; vl_assert_almost_equal(tpr, [0 1 1 2 2 2] / 2) ; vl_assert_almost_equal(tnr, [3 3 2 2 1 0] / 3) ; function test_swap1_tptn_stable(s) [tpr,tnr] = vl_roc(s.labels,s.scores1,'stable',true) ; vl_assert_almost_equal(tpr, [1 2 1 2 2] / 2) ; vl_assert_almost_equal(tnr, [3 2 2 1 0] / 3) ; function test_swap1_metrics(s) [tpr,tnr,info] = vl_roc(s.labels,s.scores1) ; vl_assert_almost_equal(info.eer, 1/3) ; vl_assert_almost_equal(info.auc, 1 - 1/(2*3)) ;
github
Shenc0411/CS445-master
vl_test_dsift.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_dsift.m
2,048
utf_8
fbbfb16d5a21936c1862d9551f657ccc
function results = vl_test_dsift(varargin) % VL_TEST_DSIFT vl_test_init ; function s = setup() I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; s.I = rgb2gray(single(I)) ; function test_fast_slow(s) binSize = 4 ; % bin size in pixels magnif = 3 ; % bin size / keypoint scale scale = binSize / magnif ; windowSize = 5 ; [f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ... 'size', binSize, ... 'step', 10, ... 'bounds', [20,20,210,140], ... 'windowsize', windowSize, ... 'floatdescriptors') ; [f_, d_] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ... 'size', binSize, ... 'step', 10, ... 'bounds', [20,20,210,140], ... 'windowsize', windowSize, ... 'floatdescriptors', ... 'fast') ; error = std(d_(:) - d(:)) / std(d(:)) ; assert(error < 0.1, 'dsift fast approximation not close') ; function test_sift(s) binSize = 4 ; % bin size in pixels magnif = 3 ; % bin size / keypoint scale scale = binSize / magnif ; windowSizeRange = [1 1.2 5] ; for wi = 1:length(windowSizeRange) windowSize = windowSizeRange(wi) ; [f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ... 'size', binSize, ... 'step', 10, ... 'bounds', [20,20,210,140], ... 'windowsize', windowSize, ... 'floatdescriptors') ; numKeys = size(f, 2) ; f_ = [f ; ones(1, numKeys) * scale ; zeros(1, numKeys)] ; [f_, d_] = vl_sift(s.I, ... 'magnif', magnif, ... 'frames', f_, ... 'firstoctave', -1, ... 'levels', 5, ... 'floatdescriptors', ... 'windowsize', windowSize) ; error = std(d_(:) - d(:)) / std(d(:)) ; assert(error < 0.1, 'dsift and sift equivalence') ; end
github
Shenc0411/CS445-master
vl_test_alldist2.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_alldist2.m
2,284
utf_8
89a787e3d83516653ae8d99c808b9d67
function results = vl_test_alldist2(varargin) % VL_TEST_ALLDIST vl_test_init ; % TODO: test integer classes function s = setup() vl_twister('state', 0) ; s.X = 3.1 * vl_twister(10,10) ; s.Y = 4.7 * vl_twister(10,7) ; function test_null_args(s) vl_assert_equal(... vl_alldist2(zeros(15,12), zeros(15,0), 'kl2'), ... zeros(12,0)) ; vl_assert_equal(... vl_alldist2(zeros(15,0), zeros(15,0), 'kl2'), ... zeros(0,0)) ; vl_assert_equal(... vl_alldist2(zeros(15,0), zeros(15,12), 'kl2'), ... zeros(0,12)) ; vl_assert_equal(... vl_alldist2(zeros(0,15), zeros(0,12), 'kl2'), ... zeros(15,12)) ; function test_self(s) vl_assert_almost_equal(... vl_alldist2(s.X, 'kl2'), ... makedist(@(x,y) x*y, s.X, s.X), ... 1e-6) ; function test_distances(s) dists = {'chi2', 'l2', 'l1', 'hell', ... 'kchi2', 'kl2', 'kl1', 'khell'} ; distsEquiv = { ... @(x,y) (x-y)^2 / (x + y), ... @(x,y) (x-y)^2, ... @(x,y) abs(x-y), ... @(x,y) (sqrt(x) - sqrt(y))^2, ... @(x,y) 2 * (x*y) / (x + y), ... @(x,y) x*y, ... @(x,y) min(x,y), ... @(x,y) sqrt(x.*y)}; types = {'single', 'double', 'sparse'} ; for simd = [0 1] for d = 1:length(dists) for t = 1:length(types) vl_simdctrl(simd) ; X = feval(str2func(types{t}), s.X) ; Y = feval(str2func(types{t}), s.Y) ; a = vl_alldist2(X,Y,dists{d}) ; b = makedist(distsEquiv{d},X,Y) ; vl_assert_almost_equal(a,b, ... 1e-4, ... 'alldist failed for dist=%s type=%s simd=%d', ... dists{d}, ... types{t}, ... simd) ; end end end function test_distance_kernel_pairs(s) dists = {'chi2', 'l2', 'l1', 'hell'} ; for d = 1:length(dists) dist = char(dists{d}) ; X = s.X ; Y = s.Y ; ker = ['k' dist] ; kxx = vl_alldist2(X,X,ker) ; kyy = vl_alldist2(Y,Y,ker) ; kxy = vl_alldist2(X,Y,ker) ; kxx = repmat(diag(kxx), 1, size(s.Y,2)) ; kyy = repmat(diag(kyy), 1, size(s.X,1))' ; d2 = vl_alldist2(X,Y,dist) ; vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ; end function D = makedist(cmp,X,Y) [d,m] = size(X) ; [d,n] = size(Y) ; D = zeros(m,n) ; for i = 1:m for j = 1:n acc = 0 ; for k = 1:d acc = acc + cmp(X(k,i),Y(k,j)) ; end D(i,j) = acc ; end end conv = str2func(class(X)) ; D = conv(D) ;
github
Shenc0411/CS445-master
vl_test_fisher.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_fisher.m
2,097
utf_8
c9afd9ab635bd412cbf8be3c2d235f6b
function results = vl_test_fisher(varargin) % VL_TEST_FISHER vl_test_init ; function s = setup() randn('state',0) ; dimension = 5 ; numData = 21 ; numComponents = 3 ; s.x = randn(dimension,numData) ; s.mu = randn(dimension,numComponents) ; s.sigma2 = ones(dimension,numComponents) ; s.prior = ones(1,numComponents) ; s.prior = s.prior / sum(s.prior) ; function test_basic(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior) ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function test_norm(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi_ = phi_ / norm(phi_) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'normalized') ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function test_sqrt(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'squareroot') ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function test_improved(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi_ = phi_ / norm(phi_) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved') ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function test_fast(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior, true) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi_ = phi_ / norm(phi_) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved', 'fast') ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function enc = simple_fisher(x, mu, sigma2, pri, fast) if nargin < 5, fast = false ; end sigma = sqrt(sigma2) ; for k = 1:size(mu,2) delta{k} = bsxfun(@times, bsxfun(@minus, x, mu(:,k)), 1./sigma(:,k)) ; q(k,:) = log(pri(k)) - 0.5 * sum(log(sigma2(:,k))) - 0.5 * sum(delta{k}.^2,1) ; end q = exp(bsxfun(@minus, q, max(q,[],1))) ; q = bsxfun(@times, q, 1 ./ sum(q,1)) ; n = size(x,2) ; if fast [~,i] = max(q) ; q = zeros(size(q)) ; q(sub2ind(size(q),i,1:n)) = 1 ; end for k = 1:size(mu,2) u{k} = delta{k} * q(k,:)' / n / sqrt(pri(k)) ; v{k} = (delta{k}.^2 - 1) * q(k,:)' / n / sqrt(2*pri(k)) ; end enc = cat(1, u{:}, v{:}) ;
github
Shenc0411/CS445-master
vl_test_imsmooth.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_imsmooth.m
1,837
utf_8
718235242cad61c9804ba5e881c22f59
function results = vl_test_imsmooth(varargin) % VL_TEST_IMSMOOTH vl_test_init ; function s = setup() I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; I = max(min(vl_imdown(I),1),0) ; s.I = single(I) ; function test_pad_by_continuity(s) % Convolving a constant signal padded with continuity does not change % the signal. I = ones(3) ; for ker = {'triangular', 'gaussian'} ker = char(ker) ; J = vl_imsmooth(I, 2, ... 'kernel', ker, ... 'padding', 'continuity') ; vl_assert_almost_equal(J, I, 1e-4, ... 'padding by continutiy with kernel = %s', ker) ; end function test_kernels(s) for ker = {'triangular', 'gaussian'} ker = char(ker) ; for type = {@single, @double} for simd = [0 1] for sigma = [1 2 7] for step = [1 2 3] vl_simdctrl(simd) ; conv = type{1} ; g = equivalent_kernel(ker, sigma) ; J = vl_imsmooth(conv(s.I), sigma, ... 'kernel', ker, ... 'padding', 'zero', ... 'subsample', step) ; J_ = conv(convolve(s.I, g, step)) ; vl_assert_almost_equal(J, J_, 1e-4, ... 'kernel=%s sigma=%f step=%d simd=%d', ... ker, sigma, step, simd) ; end end end end end function g = equivalent_kernel(ker, sigma) switch ker case 'gaussian' W = ceil(4*sigma) ; g = exp(-.5*((-W:W)/(sigma+eps)).^2) ; case 'triangular' W = max(round(sigma),1) ; g = W - abs(-W+1:W-1) ; end g = g / sum(g) ; function I = convolve(I, g, step) if strcmp(class(I),'single') g = single(g) ; else g = double(g) ; end for k=1:size(I,3) I(:,:,k) = conv2(g,g,I(:,:,k),'same'); end I = I(1:step:end,1:step:end,:) ;
github
Shenc0411/CS445-master
vl_test_svmtrain.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_svmtrain.m
4,277
utf_8
071b7c66191a22e8236fda16752b27aa
function results = vl_test_svmtrain(varargin) % VL_TEST_SVMTRAIN vl_test_init ; end function s = setup() randn('state',0) ; Np = 10 ; Nn = 10 ; xp = diag([1 3])*randn(2, Np) ; xn = diag([1 3])*randn(2, Nn) ; xp(1,:) = xp(1,:) + 2 + 1 ; xn(1,:) = xn(1,:) - 2 + 1 ; s.x = [xp xn] ; s.y = [ones(1,Np) -ones(1,Nn)] ; s.lambda = 0.01 ; s.biasMultiplier = 10 ; if 0 figure(1) ; clf; vl_plotframe(xp, 'g') ; hold on ; vl_plotframe(xn, 'r') ; axis equal ; grid on ; end % Run LibSVM as an accuate solver to compare results with. Note that % LibSVM optimizes a slightly different cost function due to the way % the bias is handled. % [s.w, s.b] = accurate_solver(s.x, s.y, s.lambda, s.biasMultiplier) ; s.w = [1.180762951236242; 0.098366470721632] ; s.b = -1.540018443946204 ; s.obj = obj(s, s.w, s.b) ; end function test_sgd_basic(s) for conv = {@single, @double} conv = conv{1} ; vl_twister('state',0) ; [w b info] = vl_svmtrain(s.x, s.y, s.lambda, ... 'Solver', 'sgd', ... 'BiasMultiplier', s.biasMultiplier, ... 'BiasLearningRate', 1/s.biasMultiplier, ... 'MaxNumIterations', 1e5, ... 'Epsilon', 1e-3) ; % there are no absolute guarantees on the objective gap, but % the heuristic SGD uses as stopping criterion seems reasonable % within a factor 10 at least. o = obj(s, w, b) ; gap = o - s.obj ; vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ; assert(gap <= 1e-2) ; end end function test_sdca_basic(s) for conv = {@single, @double} conv = conv{1} ; vl_twister('state',0) ; [w b info] = vl_svmtrain(s.x, s.y, s.lambda, ... 'Solver', 'sdca', ... 'BiasMultiplier', s.biasMultiplier, ... 'MaxNumIterations', 1e5, ... 'Epsilon', 1e-3) ; % the gap with the accurate solver cannot be % greater than the duality gap. o = obj(s, w, b) ; gap = o - s.obj ; vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ; assert(gap <= 1e-3) ; end end function test_weights(s) for algo = {'sgd', 'sdca'} for conv = {@single, @double} conv = conv{1} ; vl_twister('state',0) ; numRepeats = 10 ; pos = find(s.y > 0) ; neg = find(s.y < 0) ; weights = ones(1, numel(s.y)) ; weights(pos) = numRepeats ; % simulate weighting by repeating positives [w b info] = vl_svmtrain(... s.x(:, [repmat(pos,1,numRepeats) neg]), ... s.y(:, [repmat(pos,1,numRepeats) neg]), ... s.lambda / (numel(pos) *numRepeats + numel(neg)) / (numel(pos) + numel(neg)), ... 'Solver', 'sdca', ... 'BiasMultiplier', s.biasMultiplier, ... 'MaxNumIterations', 1e6, ... 'Epsilon', 1e-4) ; % apply weigthing [w_ b_ info_] = vl_svmtrain(... s.x, ... s.y, ... s.lambda, ... 'Solver', char(algo), ... 'BiasMultiplier', s.biasMultiplier, ... 'MaxNumIterations', 1e6, ... 'Epsilon', 1e-4, ... 'Weights', weights) ; vl_assert_almost_equal(conv([w; b]), conv([w_; b_]), 0.05) ; end end end function test_homkermap(s) for solver = {'sgd', 'sdca'} for conv = {@single,@double} conv = conv{1} ; dataset = vl_svmdataset(conv(s.x), 'homkermap', struct('order',1)) ; vl_twister('state',0) ; [w_ b_] = vl_svmtrain(dataset, s.y, s.lambda) ; x_hom = vl_homkermap(conv(s.x), 1) ; vl_twister('state',0) ; [w b] = vl_svmtrain(x_hom, s.y, s.lambda) ; vl_assert_almost_equal([w; b],[w_; b_], 1e-7) ; end end end function [w,b] = accurate_solver(X, y, lambda, biasMultiplier) addpath opt/libsvm/matlab/ N = size(X,2) ; model = svmtrain(y', [(1:N)' X'*X], sprintf(' -c %f -t 4 -e 0.00001 ', 1/(lambda*N))) ; w = X(:,model.SVs) * model.sv_coef ; b = - model.rho ; format long ; disp('model w:') disp(w) disp('bias b:') disp(b) end function o = obj(s, w, b) o = (sum(w.*w) + b*b) * s.lambda / 2 + mean(max(0, 1 - s.y .* (w'*s.x + b))) ; end