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
martinarielhartmann/mirtooloct-master
evaleach.m
.m
mirtooloct-master/MIRToolbox/@mirdesign/evaleach.m
33,230
utf_8
a6791354f1633edd3bc91578a489bed5
function [y d2] = evaleach(d,single,name) % Top-down traversal of the design flowchart, at the beginning of the % evaluation phase. % Called by mirfunction, mireval, mirframe and mirsegment. % This is during that traversal that we check whether a chunk decomposition % needs to be performed or not, and carry out that chunk decomposition. if nargin<3 || isempty(name) if not(ischar(d.method)) name = func2str(d.method); end end if nargin<2 single = 0; end CHUNKLIM = mirchunklim; f = d.file; fr = d.frame; if ~isempty(fr) && length(fr.length.val)>1 fr.length.val = fr.length.val(d.scale); if length(fr.hop.val)>1 fr.hop.val = fr.hop.val(d.scale); end end frnochunk = isfield(d.frame,'dontchunk'); frchunkbefore = isfield(d.frame,'chunkbefore'); sg = d.segment; sr = d.sampling; sr2 = d.resampling; w = d.size; lsz = w(2)-w(1)+1; len = lsz/sr; if ischar(sg) error('ERROR in MIREVAL: mirsegment of design object accepts only array of numbers as second argument.'); end if not(isempty(sg)) if ~isnumeric(sg) sg = sort(mirgetdata(sg)); sg = [0 sg';sg' len]; end over = find(sg > len); if not(isempty(over)) sg = sg(1:over-1); end end a = d.argin; ch = d.chunk; chan = d.channel; specif = d.specif; if iscombinemethod(specif,'Average') || iscombinemethod(specif,'Sum') specif.eachchunk = 'Normal'; end if ischar(a) % The top-down traversal of the design flowchart now reaches the lowest % layer, i.e., audio file loading. % Now the actual evaluation will be carried out bottom-up. if isempty(ch) % No chunk decomposition y = miraudio(f,'Now',[w(:)' chan]); else % Chunk decomposition y = miraudio(f,'Now',[ch(1),ch(2) chan]); end if not(isempty(d.postoption)) && d.postoption.mono y = miraudio(y,'Mono',1); end y = set(y,'AcrossChunks',get(d,'AcrossChunks')); y = set(y,'Extracted',1); d2 = d; elseif d.chunkdecomposed && isempty(d.tmpfile) % Already in a chunk decomposition process [y d2] = evalnow(d); elseif isempty(fr) || frnochunk || not(isempty(sg)) %% WHAT ABOUT CHANNELS? % Absence of frame decomposition or presence of segment decomposition in the design to evaluate % (Or particular frame decomposition, where chunks are not distributed to children (frnochunk).) if not(isempty(sg)) meth = 'Segment '; if size(sg,1) == 1 chunks = floor(sg(1:end-1)*sr)+1; chunks(2,:) = min( floor(sg(2:end)*sr)-1,lsz-1)+1; else % The following is used only for miremotion chunks = floor(sg*sr); chunks(1,:) = chunks(1,:)+1; % Code below by Ming-Hsu Chang chunks = chunks'; %%% chunks(2, 1:size(chunks,2)-1) = chunks(1, 2:size(chunks,2)) + (sg(2,1)/fr.hop.val - sg(2,1))*sr; %%% if chunks(2, size(chunks,2)-1) > len %%% chunks = chunks(:, 1:size(chunks,2)-2); else chunks = chunks(:, 1:size(chunks,2)-1); end end elseif not(isfield(specif,'eachchunk')) ... || d.nochunk ... || (not(isempty(single)) && isnumeric(single) && single > 1 ... && isfield(specif,'combinechunk') ... && iscell(specif.combinechunk)) chunks = []; else meth = 'Chunk '; if isempty(fr) if lsz > CHUNKLIM % The required memory exceed the max memory threshold. nch = ceil(lsz/CHUNKLIM); %%% TAKE INTO CONSIDERATION NUMBER OF CHANNELS; ETC... chunks = max(0,lsz-CHUNKLIM*(nch:-1:1))+w(1); chunks(2,:) = lsz-CHUNKLIM*(nch-1:-1:0)+w(1)-1; else chunks = []; end else chunks = compute_frames(fr,sr,sr2,w,lsz,... CHUNKLIM/d.chunksizefactor,d.overlap); end end if not(isempty(chunks)) % The chunk decomposition is performed. nch = size(chunks,2); d = callbeforechunk(d,d,w,lsz); % Some optional initialisation tmp = []; if mirwaitbar h = waitbar(0,['Computing ' name]); else h = 0; end if not(isempty(d.tmpfile)) && d.tmpfile.fid == 0 % When applicable, a new temporary file is created. tmpname = [f '.mirtmp']; d.tmpfile.fid = fopen(tmpname,'w'); end if not(d.ascending) chunks = fliplr(chunks); end afterpostoption = d.postoption; % Used only when: % - eachchunk is set to 'Normal', % - combinechunk is not set to 'Average', and % - no afterchunk field has been specified. % afterpostoption will be used for the final call % to the method after the chunk decomposition. method = d.method; if ~isfield(specif,'eachchunk') specif.eachchunk = 'Normal'; end if ischar(specif.eachchunk) && strcmpi(specif.eachchunk,'Normal') if not(isempty(d.postoption)) pof = fieldnames(d.postoption); for o = 1:length(pof) if isfield(specif.option.(pof{o}),'chunkcombine') afterpostoption = rmfield(afterpostoption,pof{o}); else d.postoption = rmfield(d.postoption,pof{o}); end end end else method = specif.eachchunk; end d2 = d; d2.method = method; y = {}; for i = 1:size(chunks,2) if mirverbose disp([meth,num2str(i),'/',num2str(nch),'...']) end d2 = set(d2,'Chunk',[chunks(1,i) chunks(2,i) (i == size(chunks,2))]); if not(ischar(specif.eachchunk) && ... strcmpi(specif.eachchunk,'Normal')) if frnochunk d2.postoption = 0; else diffchunks = diff(chunks); % Usual chunk size d2.postoption = max(diffchunks) - diffchunks(i); % Reduction of the current chunk size to be taken into % consideration in mirspectrum, for instance, using % zeropadding end end d2 = set(d2,'InterChunk',tmp); d2.chunkdecomposed = 1; [ss d3] = evalnow(d2); if iscell(ss) && not(isempty(ss)) tmp = get(ss{1},'InterChunk'); elseif isstruct(ss) tmp = []; else tmp = get(ss,'InterChunk'); end % d2 is like d3 except that its argument is now evaluated. d3.postoption = d.postoption; % Pas joli joli d3.method = method; d2 = d3; % This new argument is transfered to d y = combinechunk_noframe(y,ss,sg,i,d2,chunks,single); clear ss if isa(h,'matlab.ui.Figure') if not(d.ascending) close(h) h = waitbar((chunks(1,i)-chunks(1,end))/chunks(2,1),... ['Computing ' func2str(d.method) ' (backward)']); else waitbar((chunks(2,i)-chunks(1))/chunks(end),h) end end end if ~isstruct(y) % Final operations to be executed after the chunk decomposition if iscombinemethod(d2.specif,'Average') y{1} = divideweightchunk(y{1},lsz); elseif not(isempty(afterpostoption)) && isempty(d2.tmpfile) y{1} = d.method(y{1},[],afterpostoption); end if not(isempty(d2.tmpfile)) adr = ftell(d2.tmpfile.fid); fclose(d2.tmpfile.fid); ytmpfile.fid = fopen(tmpname); fseek(ytmpfile.fid,adr,'bof'); ytmpfile.data = y{1}; ytmpfile.layer = 0; y{1} = set(y{1},'TmpFile',ytmpfile); end end if isa(d,'mirstruct') && ... (isempty(d.frame) || isfield(d.frame,'dontchunk')) y = evalbranches(d,y); end if isa(h,'matlab.ui.Figure') close(h) end drawnow else % No chunk decomposition [y d2] = evalnow(d); if isa(d,'mirstruct') && isfield(d.frame,'dontchunk') y = evalbranches(d,y); end end elseif d.nochunk [y d2] = evalnow(d); else % Frame decomposition in the design to be evaluated. chunks = compute_frames(fr,sr,sr2,w,lsz,CHUNKLIM,d.overlap); if size(chunks,2)>1 % The chunk decomposition is performed. if mirwaitbar h = waitbar(0,['Computing ' name]); else h = 0; end inter = []; d = set(d,'FrameDecomposition',1); d2 = d; nch = size(chunks,2); y = {}; if frchunkbefore d2after = d2; d2.method = d2.argin.method; d2.option = d2.argin.option; d2.postoption = d2.argin.postoption; d2.argin = d2.argin.argin; end for fri = 1:nch % For each chunk... if mirverbose disp(['Chunk ',num2str(fri),'/',num2str(nch),'...']) end d2 = set(d2,'Chunk',chunks(:,fri)'); d2 = set(d2,'InterChunk',inter); %d2.postoption = []; [res d2] = evalnow(d2); if not(isempty(res)) if iscell(res) inter = get(res{1},'InterChunk'); elseif not(isstruct(res)) inter = get(res,'InterChunk'); res = {res}; end end y = combinechunk_frame(y,res,d2,fri); if ~isempty(h) waitbar(chunks(2,fri)/chunks(end),h); end end if frchunkbefore y = d2after.method(y,d2after.option,d2after.postoption); end if isa(d,'mirstruct') && get(d,'Stat') y = mirstat(y); end if ~isempty(h) close(h) end else % No chunk decomposition [y d2] = evalnow(d); end end if iscell(y) for i = 1:length(y) if not(isempty(y{i}) || isstruct(y{i})) if iscell(y{i}) for j = 1:length(y{i}) y{i}{j} = set(y{i}{j},'InterChunk',[]); end else y{i} = set(y{i},'InterChunk',[]); end end end end function chunks = compute_frames(fr,sr,sr2,w,lsz,CHUNKLIM,frov) if strcmpi(fr.length.unit,'s') fl = fr.length.val*sr; fl2 = fr.length.val*sr2; elseif strcmpi(fr.length.unit,'sp') fl = fr.length.val; fl2 = fl; end if strcmpi(fr.hop.unit,'/1') h = fr.hop.val*fl; h2 = fr.hop.val*fl2; elseif strcmpi(fr.hop.unit,'%') h = fr.hop.val*fl*.01; h2 = fr.hop.val*fl2*.01; elseif strcmpi(fr.hop.unit,'s') h = fr.hop.val*sr; h2 = fr.hop.val*sr2; elseif strcmpi(fr.hop.unit,'sp') h = fr.hop.val; h2 = fr.hop.val; elseif strcmpi(fr.hop.unit,'Hz') h = sr/fr.hop.val; h2 = sr2/fr.hop.val; end if strcmpi(fr.phase.unit,'s') ph = fr.phase.val*sr; elseif strcmpi(fr.phase.unit,'sp') ph = fr.phase.val; elseif strcmpi(fr.phase.unit,'/1') ph = fr.phase.val*h; elseif strcmpi(fr.phase.unit,'%') ph = fr.phase.val*h*.01; end n = floor((lsz-fl-ph)/h)+1; % Number of frames if n < 1 %warning('WARNING IN MIRFRAME: Frame length longer than total sequence size. No frame decomposition.'); fp = w; fp2 = (w-1)/sr*sr2+1; else st = floor(((1:n)-1)*h+ph)+w(1); st2 = floor(((1:n)-1)*h2)+w(1)+ph; fp = [st; floor(st+fl-1)]; fp(:,fp(2,:)>w(2)) = []; fp2 = [st2; floor(st2+fl2-1)]; fp2(:,fp2(2,:)>(w(2)-w(1))/sr*sr2+w(2)) = []; end fpsz = (fp(2,1)-fp(1,1)) * n; % Total number of samples fpsz2 = (fp2(2,1)-fp2(1,1)) * n; % Total number of samples if max(fpsz,fpsz2) > CHUNKLIM % The required memory exceed the max memory threshold. nfr = size(fp,2); % Total number of frames frch = max(ceil(CHUNKLIM/(fp(2,1)-fp(1,1))),2); % Number of frames per chunk frch = max(frch,frov*2); nch = ceil((nfr-frch)/(frch-frov))+1; % Number of chunks chbeg = (frch-frov)*(0:nch-1)+1; % First frame in the chunk chend = (frch-frov)*(0:nch-1)+frch; % Last frame in the chunk chend = min(chend,nfr); if chend(end) == chbeg(end) lszend = fp(2,end)-fp(1,end)+1; % Size of last chunk nend = floor((lszend-fl)/h)+1; % Number of frames in the last chunk if nend < 2 % Last chunk is too short (only one frame), chend(end-1) = chend(end); % concatenated to previous one. chbeg(end) = []; chend(end) = []; end end if frov > 1 % If case of overlap <<<< Check if OK or not? (Was commented out before) chbeg = chend-frch+1; end chunks = [fp(1,chbeg) ; fp(2,chend)+1]; % After resampling, one sample may be missing, leading to a complete frame drop. chunks(end) = min(chunks(end),fp(end)); % Last chunk should not extend beyond audio size. else chunks = []; end function res = combinechunk_frame(old,new,d2,fri) if isa(new,'miraudio') && isempty(mirgetdata(new)) res = old; return end if isstruct(old) f = fields(old); for i = 1:length(f) res.(f{i}) = combinechunk_frame(old.(f{i}),new.(f{i}),d2,fri); end return end if fri == 1 res = new; else res = combineframes(old,new); end function res = combinechunk_noframe(old,new,sg,i,d2,chunks,single) if isempty(new) res = {}; return end if isempty(mirgetdata(new)) res = old; return end if not(iscell(new)) new = {new}; end if not(iscell(old)) old = {old}; end if not(isempty(old)) && isstruct(old{1}) f = fields(old{1}); for j = 1:length(f) index.type = '.'; index.subs = f{j}; res.(f{j}) = combinechunk_noframe(old{1}.(f{j}),new{1}.(f{j}),... sg,i,subsref(d2,index),chunks,single); end return end if ischar(single) && not(isempty(old)) old = {old{1}}; end if isempty(sg) if iscombinemethod(d2.specif,'Average') || ... iscombinemethod(d2.specif,'Sum') % Measure total size for later averaging if iscell(new) new1 = new{1}; else new1 = new; end dnew = get(new1,'Data'); if iscombinemethod(d2.specif,'Average') dnew = mircompute(@multweight,dnew,chunks(2,i)-chunks(1,i)+1); end if iscell(new) new{1} = set(new1,'Data',dnew); else new = set(new1,'Data',dnew); end end %tmp = get(new{1},'InterChunk'); if not(isempty(d2.tmpfile)) && d2.tmpfile.fid > 0 % If temporary file is used, chunk results are written % in the file if i < size(chunks,2) ds = get(new{1},'Data'); ps = get(new{1},'Pos'); %ftell(d2.tmpfile.fid) count = fwrite(d2.tmpfile.fid,ds{1}{1},'double'); count = fwrite(d2.tmpfile.fid,ps{1}{1},'double'); %ftell(d2.tmpfile.fid) clear ds ps end res = new; else % Else, chunk results are directly combined in active % memory if i == 1 res = new; else res = cell(1,length(old)); if isfield(d2.specif,'combinechunk') if not(iscell(d2.specif.combinechunk)) method = {d2.specif.combinechunk}; else method = d2.specif.combinechunk; end for z = 1:length(old) if isframed(old{z}) res(z) = combineframes(old{z},new{z}); else if ischar(method{z}) if strcmpi(method{z},'Concat') doo = get(old{z},'Data'); dn = get(new{z},'Data'); fpo = get(old{z},'FramePos'); fpn = get(new{z},'FramePos'); if size(fpo{1}{1},2)>1 error('Fatal error. Please contact Olivier.'); end if isa(old,'mirscalar') res{z} = set(old{z},... 'Data',{{[doo{1}{1},dn{1}{1}]}},... 'FramePos',{{[fpo{1}{1}(1);fpn{1}{1}(2)]}}); else to = get(old{z},'Pos'); tn = get(new{z},'Pos'); if d2.ascending res{z} = set(old{z},... 'Data',{{[doo{1}{1};dn{1}{1}]}},... 'Pos',{{[to{1}{1};tn{1}{1}]}},... 'FramePos',{{[fpo{1}{1}(1);fpn{1}{1}(2)]}}); else res{z} = set(old{z},... 'Data',{{[dn{1}{1};doo{1}{1}]}},... 'Pos',{{[tn{1}{1};to{1}{1}]}},... 'FramePos',{{[fpo{1}{1}(1);fpn{1}{1}(2)]}}); end end elseif strcmpi(method{z},'Average') || ... strcmpi(method{z},'Sum') doo = get(old{z},'Data'); dn = get(new{z},'Data'); res{z} = set(old{z},... 'ChunkData',doo{1}{1}+dn{1}{1}); else error(['SYNTAX ERROR: ',method{z},... ' is not a known keyword for combinechunk.']); end else res{z} = method{z}(old{z},new{z}); end lo = get(old{z},'Length'); ln = get(new{z},'Length'); res{z} = set(res{z},'Length',{{lo{1}{1}+ln{1}{1}}}); end end else for z = 1:length(old) if isframed(old{z}) res(z) = combineframes(old{z},new{z}); else mirerror('MIREVAL',... 'Chunk recombination in non-framed mode is not available for all features yet. Please turn off the chunk decomposition.'); end end end end end else if i == 1 res = new; else for z = 1:length(old) res{z} = combinesegment(old{z},new{z}); end end end function old = combineframes(old,new) if not(iscell(old)) old = {old}; end if not(iscell(new)) new = {new}; end for var = 1:length(new) ov = old{var}; nv = new{var}; if isa(ov,'mirscalar') ov = combinedata(ov,nv,'Data'); ov = combinedata(ov,nv,'Mode'); if isa(ov,'mirpitch') ov = combinedata(ov,nv,'Amplitude'); end else if isa(ov,'mirtemporal') [ov omatch nmatch] = combinedata(ov,nv,'Time',[],[],@modiftime); else [ov omatch nmatch] = combinedata(ov,nv,'Pos',[],[]); if isa(ov,'mirspectrum') [ov omatch nmatch] = combinedata(ov,nv,'Phase',[],[]); end end ov = combinedata(ov,nv,'Data',omatch,nmatch); end ov = combinedata(ov,nv,'FramePos'); ov = combinedata(ov,nv,'PeakPos'); ov = combinedata(ov,nv,'PeakVal'); ov = combinedata(ov,nv,'PeakMode'); old{var} = ov; end function [ov omatch nmatch] = combinedata(ov,nv,key,omatch,nmatch,modifdata) if isstruct(ov) omatch = []; nmatch = []; f = fields(ov); for i = 1:length(f) ov.(f{i}) = combinedata(ov.(f{i}),nv.(f{i}),key); end return end odata = get(ov,key); if isempty(odata) || isempty(odata{1}) return end odata = odata{1}; if iscell(odata) if ischar(odata{1}) return else odata = odata{1}; end end ndata = get(nv,key); ndata = ndata{1}; if iscell(ndata) ndata = ndata{1}; end if nargin>3 if isempty(omatch) ol = size(odata,1); nl = size(ndata,1); unmatch = ol-nl; if unmatch>0 [unused idx] = min(odata(1:1+unmatch,1,1)-ndata(1)); omatch = idx:idx+nl-1; nmatch = 1:nl; elseif unmatch<0 [unused idx] = min(ndata(1:1-unmatch,1,1)-odata(1)); nmatch = idx:idx+ol-1; omatch = 1:ol; else nmatch = 1:nl; omatch = 1:ol; end end odata(omatch,end+1:end+size(ndata,2),:,:) = ndata(nmatch,:,:,:); %4.D for keysom else odata(:,end+1:end+size(ndata,2),:,:) = ndata; end ov = set(ov,key,{{odata}}); %{odata} for warped chromagram for instance.... function d = modiftime(d,p) d = d + p; function [y d] = evalnow(d) % Go one step further in the top-down evaluation initialisation argin = d.argin; if not(iscell(argin)) argin = {argin}; end for i = 1:length(argin) a = argin{i}; if not(d.ascending) a.ascending = 0; end if isa(a,'mirdata') % Input already computed tmpfile = get(a,'TmpFile'); if not(isempty(tmpfile)) && tmpfile.fid > 0 % The input can be read from the temporary file ch = get(d,'Chunk'); a = tmpfile.data; a = set(a,'InterChunk',get(d,'InterChunk'),'TmpFile',tmpfile); channels = get(a,'Channels'); channels = length(channels{1}); if not(channels) da = get(a,'Data'); channels = size(da{1}{1},3); end sz = (ch(2)-ch(1)+1); current = ftell(tmpfile.fid); origin = current-sz*(channels+1)*8; if origin < 0 sz = sz + origin/(channels+1)/8; origin = 0; end fseek(tmpfile.fid,origin,'bof'); %ftell(tmpfile.fid) [data count] = fread(tmpfile.fid,[sz,channels],'double'); %count data = reshape(data,[sz,1,channels]); [pos count] = fread(tmpfile.fid,sz,'double'); %count %ftell(tmpfile.fid) fseek(tmpfile.fid,current-sz*(channels+1)*8,'bof'); a = set(a,'Data',{{data}},'Pos',{{pos}}); if ch(3) fclose(tmpfile.fid); delete([d.file '.mirtmp']); end argin{i} = a; end elseif isa(a,'mirdesign') if isempty(a.stored) % The design parameters are transfered to the previous component % in the design process a.size = d.size; a.chunk = d.chunk; a.file = d.file; a.channel = d.channel; a.scale = d.scale; a.eval = 1; a.interchunk = d.interchunk; a.sampling = d.sampling; if isstruct(d.frame) && isfield(d.frame,'decomposition') ... && not(isempty(d.frame.decomposition)) a.chunkdecomposed = 1; else a.chunkdecomposed = d.chunkdecomposed; end if not(isempty(d.frame)) && ... not(strcmp(func2str(d.method),'mirframe')) a.frame = d.frame; end a.ready = 1; a.acrosschunks = d.acrosschunks; a.index = d.index; argin{i} = a; else % Variable already calculated tmp = get(d,'Struct'); if not(isempty(tmp)) for j = 1:length(a.stored) % (if modified, modify also mirframe) stored = a.stored{j}; if iscell(stored) if length(stored)>1 tmp = tmp{stored{1},stored{2}}; else tmp = tmp{stored{1}}; end else tmp = getfield(tmp,stored); end end if iscell(tmp) tmp = tmp{1}; end else mirerror('evaleach','THERE is a problem..'); end argin{i} = tmp; end end end if not(iscell(d.argin)) argin = argin{1}; end d.option.struct = get(d,'Struct'); if iscell(d.postoption) [y argin] = d.method(argin,d.option,d.postoption{:}); else [y argin] = d.method(argin,d.option,d.postoption); end d = set(d,'Argin',argin); if isa(d,'mirstruct') && not(isfield(d.frame,'dontchunk')) && isempty(get(d,'Chunk')) y = evalbranches(d,y); end function z = evalbranches(d,y) % For complex flowcharts, now that the first temporary variable (y) has been % computed, the dependent features (d) should be evaluated as well. branch = get(d,'Data'); for i = 1:length(branch) if isa(branch{i},'mirdesign') && get(branch{i},'NoChunk') == 1 % if the value is 2, it is OK. %mirerror('mireval','Flowchart badly designed: mirstruct should not be used if one or several final variables do not accept chunk decomposition.'); end end fields = get(d,'Fields'); z = struct; tmp = get(d,'Tmp'); for i = 1:length(branch) z.(fields{i}) = evalbranch(branch{i},tmp,y); end if get(d,'Stat') && isempty(get(d,'Chunk')) z = mirstat(z,'FileNames',0); end function b = evalbranch(b,d,y) % We need to evaluate the branch reaching the current node (b) from the parent % corresponding to the temporary variable (d), if iscell(b) mirerror('MIREVAL','Sorry, forked branching of temporary variable cannnot be evaluated in current version of MIRtoolbox.'); end if isstruct(b) % Subtrees are evaluated branch after branch. f = fields(b); for i = 1:length(f) b.(f{i}) = evalbranch(b.(f{i}),d,y); end return end if isequal(b,d) %% Does it happen ever?? b = y; return end if not(isa(b,'mirdesign')) mirerror('MIRSTRUCT','In the mirstruct object you defined, the final output should only depend on ''tmp'' variables, and should not therefore reuse the ''Design'' keyword.'); end v = get(b,'Stored'); if length(v)>1 && ischar(v{2}) % f = fields(d); for i = 1:length(f) if strcmpi(v{2},f) b = y; % OK, now the temporary variable has been found. % End of recursion. return end end end argin = evalbranch(get(b,'Argin'),d,y); % Recursion one parent up % The operation corresponding to the branch from the parent to the node % is finally evaluated. if iscell(b.postoption) b = b.method(argin,b.option,b.postoption{:}); else b = b.method(argin,b.option,b.postoption); end function res = iscombinemethod(specif,method) res = isfield(specif,'combinechunk') && ... ((ischar(specif.combinechunk) && ... strcmpi(specif.combinechunk,method)) || ... (iscell(specif.combinechunk) && ... ischar(specif.combinechunk{1}) && ... strcmpi(specif.combinechunk{1},method))); function d0 = callbeforechunk(d0,d,w,lsz) % If necessary, the chunk decomposition is performed a first time for % initialisation purposes. % Currently used only for miraudio(...,'Normal') if not(ischar(d)) && not(iscell(d)) specif = d.specif; CHUNKLIM = mirchunklim; nch = ceil(lsz/CHUNKLIM); if isfield(specif,'beforechunk') ... && ((isfield(d.option,specif.beforechunk{2}) ... && d.option.(specif.beforechunk{2})) ... || (isfield(d.postoption,specif.beforechunk{2}) ... && d.postoption.(specif.beforechunk{2})) ) if mirwaitbar h = waitbar(0,['Preparing ' func2str(d.method)]); else h = 0; end for i = 1:nch disp(['Chunk ',num2str(i),'/',num2str(nch),'...']) chbeg = CHUNKLIM*(i-1); chend = CHUNKLIM*i-1; d2 = set(d,'Size',d0.size,'File',d0.file,... 'Chunk',[chbeg+w(1) min(chend,lsz-1)+w(1)]); d2.method = specif.beforechunk{1}; d2.postoption = {chend-lsz}; d2.chunkdecomposed = 1; [tmp d] = evalnow(d2); d0 = set(d0,'AcrossChunks',tmp); if isa(h,'matlab.ui.Figure') waitbar(chend/lsz,h) end end if isa(h,'matlab.ui.Figure') close(h); end drawnow else d0 = callbeforechunk(d0,d.argin,w,lsz); end end function y = combinesegment(old,new) doo = get(old,'Data'); to = get(old,'Pos'); fpo = get(old,'FramePos'); ppo = get(old,'PeakPos'); pppo = get(old,'PeakPrecisePos'); pvo = get(old,'PeakVal'); ppvo = get(old,'PeakPreciseVal'); pmo = get(old,'PeakMode'); apo = get(old,'AttackPos'); rpo = get(old,'ReleasePos'); tpo = get(old,'TrackPos'); tvo = get(old,'TrackVal'); dn = get(new,'Data'); tn = get(new,'Pos'); fpn = get(new,'FramePos'); ppn = get(new,'PeakPos'); pppn = get(new,'PeakPrecisePos'); pvn = get(new,'PeakVal'); ppvn = get(new,'PeakPreciseVal'); pmn = get(new,'PeakMode'); apn = get(new,'AttackPos'); rpn = get(new,'ReleasePos'); tpn = get(new,'TrackPos'); tvn = get(new,'TrackVal'); y = old; if not(isempty(doo)) y = set(y,'Data',{{doo{1}{:},dn{1}{:}}}); end y = set(y,'FramePos',{{fpo{1}{:},fpn{1}{:}}}); if not(isempty(to)) && size(doo{1},2) == size(to{1},2) y = set(y,'Pos',{{to{1}{:},tn{1}{:}}}); end if not(isempty(ppo)) y = set(y,'PeakPos',{{ppo{1}{:},ppn{1}{:}}},... 'PeakVal',{{pvo{1}{:},pvn{1}{:}}},... 'PeakMode',{{pmo{1}{:},pmn{1}{:}}}); end if not(isempty(pppn)) y = set(y,'PeakPrecisePos',{[pppo{1},pppn{1}{1}]},... 'PeakPreciseVal',{[ppvo{1},ppvn{1}{1}]}); end if not(isempty(apn)) y = set(y,'AttackPos',{[apo{1},apn{1}{1}]}); end if not(isempty(rpn)) y = set(y,'ReleasePos',{[rpo{1},rpn{1}{1}]}); end if not(isempty(tpn)) y = set(y,'TrackPos',{[tpo{1},tpn{1}{1}]}); end if not(isempty(tvn)) y = set(y,'TrackVal',{[tvo{1},tvn{1}{1}]}); end if isa(old,'mirchromagram') clo = get(old,'ChromaClass'); cln = get(new,'ChromaClass'); y = set(y,'ChromaClass',{[clo{1},cln{1}{1}]}); end if isa(old,'miremotion') deo = get(old,'DimData'); ceo = get(old,'ClassData'); den = get(new,'DimData'); cen = get(new,'ClassData'); afo = get(old,'ActivityFactors'); vfo = get(old,'ValenceFactors'); tfo = get(old,'TensionFactors'); hfo = get(old,'HappyFactors'); sfo = get(old,'SadFactors'); tdo = get(old,'TenderFactors'); ago = get(old,'AngerFactors'); ffo = get(old,'FearFactors'); afn = get(new,'ActivityFactors'); vfn = get(new,'ValenceFactors'); tfn = get(new,'TensionFactors'); hfn = get(new,'HappyFactors'); sfn = get(new,'SadFactors'); tdn = get(new,'TenderFactors'); agn = get(new,'AngerFactors'); ffn = get(new,'FearFactors'); y = set(y,'DimData',{[deo{1},den{1}{1}]},'ClassData',{[ceo{1},cen{1}{1}]}); % Code improved by Ming-Hsu Chang if iscell(afo) y = set(y, 'ActivityFactors',{[afo{1},afn{1}{1}]}); end if iscell(vfo) y = set(y, 'ValenceFactors',{[vfo{1},vfn{1}{1}]}); end if iscell(tfo) y = set(y, 'TensionFactors',{[tfo{1},tfn{1}{1}]}); end if iscell(hfo) y = set(y, 'HappyFactors',{[hfo{1},hfn{1}{1}]}); end if iscell(sfo) y = set(y, 'SadFactors',{[sfo{1},sfn{1}{1}]}); end if iscell(tdo) y = set(y, 'TenderFactors',{[tdo{1},tdn{1}{1}]}); end if iscell(ago) y = set(y, 'AngerFactors',{[ago{1},agn{1}{1}]}); end if iscell(ffo) y = set(y, 'FearFactors',{[ffo{1},ffn{1}{1}]}); end end function y = divideweightchunk(orig,length) d = get(orig,'Data'); if isempty(d) y = orig; else v = mircompute(@divideweight,d,length); y = set(orig,'Data',v); end function e = multweight(d,length) e = d*length; function e = divideweight(d,length) e = d/length;
github
martinarielhartmann/mirtooloct-master
plus.m
.m
mirtooloct-master/MIRToolbox/@mirdesign/plus.m
159
utf_8
4c83543fc53f3b9d77b3dea756c818b3
function varargout = plus(a,b) varargout = mirfunction(@pluscell,{a,b},{},1,struct,@init,@plus); function [x type] = init(x,option) type = get(x{1},'Type');
github
martinarielhartmann/mirtooloct-master
max.m
.m
mirtooloct-master/MIRToolbox/@mirdesign/max.m
156
utf_8
152a5a361e15225fc399aaf072410341
function varargout = max(a,b) varargout = mirfunction(@maxcell,{a,b},{},1,struct,@init,@max); function [x type] = init(x,option) type = get(x{1},'Type');
github
martinarielhartmann/mirtooloct-master
mtimes.m
.m
mirtooloct-master/MIRToolbox/@mirdesign/mtimes.m
169
utf_8
91a0abb2d0c449aeac1669a109b4cc06
function varargout = mtimes(a,b) varargout = mirfunction(@mtimescell,{a,b},{},1,struct,@init,@mtimescell); function [x type] = init(x,option) type = get(x{1},'Type');
github
martinarielhartmann/mirtooloct-master
mirspectrum.m
.m
mirtooloct-master/MIRToolbox/@mirspectrum/mirspectrum.m
35,371
utf_8
fcf94ab6871881278d4ed96df6962384
function varargout = mirspectrum(orig,varargin) % s = mirspectrum(x) computes the spectrum of the audio signal x, showing % the distribution of the energy along the frequencies. % (x can be the name of an audio file as well.) % Optional argument: % mirspectrum(...,'Frame',l,h) computes spectrogram, using frames of % length l seconds and a hop rate h. % Default values: l = .05 s, h = .5. % mirspectrum(...,'Min',mi) indicates the lowest frequency taken into % consideration, expressed in Hz. % Default value: 0 Hz. % mirspectrum(...,'Max',ma) indicates the highest frequency taken into % consideration, expressed in Hz. % Default value: the maximal possible frequency, corresponding to % the sampling rate of x divided by 2. % mirspectrum(...,'Window',w): windowing method: % either w = 0 (no windowing) or any windowing function proposed % in the Signal Processing Toolbox (help window). % default value: w = 'hamming' % % mirspectrum(...,'Cents'): decomposes the energy in cents. % mirspectrum(...,'Collapsed'): collapses the spectrum into one % octave divided into 1200 cents. % Redistribution of the frequencies into bands: % mirspectrum(...,'Mel'): Mel bands. % (Requires the Auditory Toolbox.) % mirspectrum(...,'Bark'): Bark bands. % (Code based on Pampalk's MA toolbox). % If the audio signal was frame decomposed, the output s is a % band-decomposed spectrogram. It is then possible to compute % the spectrum of the temporal signal in each band, % using the following syntax: % mirspectrum(s,'AlongBands') % This corresponds to fluctuation (cf. mirfluctuation). % mirspectrum(...,'Mask'): Models masking phenomena in each band. % (Code based on Pampalk's MA toolbox). % mirspectrum(...,'Normal'): normalizes with respect to energy. % mirspectrum(...,'NormalLength'): normalizes with respect to input length. % mirspectrum(...,'NormalInput'): input signal is normalized from 0 to 1. % mirspectrum(...,'Power'): squares the energy. % mirspectrum(...,'dB'): represents the spectrum energy in decibel scale. % mirspectrum(...,'dB',th): keeps only the highest energy over a % range of th dB. % mirspectrum(...,'Terhardt'): modulates the energy following % (Terhardt, 1979) outer ear model. (Code based on Pampalk's MA % toolbox). % mirspectrum(...,'Resonance',r): multiplies the spectrum with a % resonance curve. Possible value for r: % 'ToiviainenSnyder': highlights best perceived meter % (Toiviainen & Snyder 2003) % (default value for spectrum of envelopes) % 'Fluctuation': fluctuation strength (Fastl 1982) % (default value for spectrum of band channels) % mirspectrum(...,'Prod',m): Enhances components that have harmonics % located at multiples of range(s) m of the signal's fundamental % frequency. Computed by compressing the signal by the list of % factors m, and by multiplying all the results with the original % signa (Alonso et al, 2003). % mirspectrum(...,'Sum',s): Similar option using summation instead of % product. % % mirspectrum(...,'MinRes',mr): Indicates a minimal accepted % frequency resolution, in Hz. The audio signal is zero-padded in % order to reach the desired resolution. % If the 'Mel' option is toggled on, 'MinRes' is set by default % to 66 Hz. % mirspectrum(...,'MinRes',mr,'OctaveRatio',tol): Indicates the % minimal accepted resolution in terms of number of divisions of % the octave. Low frequencies are ignored in order to reach the % desired resolution. % The corresponding required frequency resolution is equal to % the difference between the first frequency bins, multiplied % by the constraining multiplicative factor tol (set by % default to .75). % mirspectrum(...,'Res',r): Indicates the required precise frequency % resolution, in Hz. The audio signal is zero-padded in order to % reach the desired resolution. % mirspectrum(...,'Length',l): Specifies the length of the FFT, % overriding the FFT length initially planned. % mirspectrum(...,'ZeroPad',s): Zero-padding of s samples. % mirspectrum(...,'WarningRes',s): Indicates a required frequency % resolution, in Hz, for the input signal. If the resolution does % not reach that prerequisite, a warning is displayed. % mirspectrum(...,'ConstantQ',nb): Carries out a Constant Q Transform % instead of a FFT, with a number of bins per octave fixed to nb. % Default value for nb: 12 bins per octave. % % mirspectrum(...,'Smooth',o): smooths the envelope using a moving % average of order o. % Default value when the option is toggled on: o=10 % mirspectrum(...,'Gauss',o): smooths the envelope using a gaussian % of standard deviation o samples. % Default value when the option is toggled on: o=10 % mirspectrum(...,'TimeSmooth',o): smooths each frequency channel of % a spectrogram using a moving average of order o. % Default value when the option is toggled on: o=10 % mirspectrum(...,'Phase',0): do not compute the FFT phase. win.key = 'Window'; win.type = 'String'; win.default = 'hamming'; option.win = win; min.key = 'Min'; min.type = 'Integer'; min.default = 0; option.min = min; max.key = 'Max'; max.type = 'Integer'; max.default = Inf; option.max = max; mr.key = 'MinRes'; mr.type = 'Integer'; mr.default = 0; option.mr = mr; res.key = 'Res'; res.type = 'Integer'; res.default = NaN; option.res = res; length.key = 'Length'; length.type = 'Integer'; length.default = NaN; option.length = length; zp.key = 'ZeroPad'; zp.type = 'Integer'; zp.default = 0; zp.keydefault = Inf; option.zp = zp; wr.key = 'WarningRes'; wr.type = 'Integer'; wr.default = 0; option.wr = wr; octave.key = 'OctaveRatio'; octave.type = 'Boolean'; octave.default = 0; option.octave = octave; constq.key = 'ConstantQ'; constq.type = 'Integer'; constq.default = 0; constq.keydefault = 12; option.constq = constq; alongbands.key = 'AlongBands'; alongbands.type = 'Boolean'; alongbands.default = 0; option.alongbands = alongbands; ni.key = 'NormalInput'; ni.type = 'Boolean'; ni.default = 0; option.ni = ni; nl.key = 'NormalLength'; nl.type = 'Boolean'; nl.default = 0; nl.when = 'After'; option.nl = nl; norm.key = 'Normal'; norm.type = 'Integer'; norm.default = 0; norm.keydefault = 1; norm.when = 'After'; option.norm = norm; band.type = 'String'; band.choice = {'Freq','Mel','Bark','Cents'}; band.default = 'Freq'; band.when = 'Both'; option.band = band; nbbands.key = 'Bands'; nbbands.type = 'Integer'; nbbands.default = 0; nbbands.when = 'After'; option.nbbands = nbbands; mprod.key = 'Prod'; mprod.type = 'Integers'; mprod.default = []; mprod.keydefault = 2:6; mprod.when = 'After'; option.mprod = mprod; msum.key = 'Sum'; msum.type = 'Integers'; msum.default = []; msum.keydefault = 2:6; msum.when = 'After'; option.msum = msum; reso.key = 'Resonance'; reso.type = 'String'; reso.choice = {'ToiviainenSnyder','Fluctuation','Meter',0,'no','off'}; reso.default = 0; reso.when = 'After'; option.reso = reso; log.key = 'log'; log.type = 'Boolean'; log.default = 0; log.when = 'After'; option.log = log; db.key = 'dB'; db.type = 'Integer'; db.default = 0; db.keydefault = Inf; db.when = 'After'; option.db = db; pow.key = 'Power'; pow.type = 'Boolean'; pow.default = 0; pow.when = 'After'; option.pow = pow; terhardt.key = 'Terhardt'; terhardt.type = 'Boolean'; terhardt.default = 0; terhardt.when = 'After'; option.terhardt = terhardt; mask.key = 'Mask'; mask.type = 'Boolean'; mask.default = 0; mask.when = 'After'; option.mask = mask; % e.key = 'Enhanced'; % e.type = 'Integer'; % e.default = []; % e.keydefault = 2:10; % e.when = 'After'; %option.e = e; collapsed.key = 'Collapsed'; collapsed.type = 'Boolean'; collapsed.default = 0; collapsed.when = 'Both'; option.collapsed = collapsed; aver.key = 'Smooth'; aver.type = 'Integer'; aver.default = 0; aver.keydefault = 10; aver.when = 'After'; option.aver = aver; gauss.key = 'Gauss'; gauss.type = 'Integer'; gauss.default = 0; gauss.keydefault = 10; gauss.when = 'After'; option.gauss = gauss; timesmooth.key = 'TimeSmooth'; timesmooth.type = 'Integer'; timesmooth.default = 0; timesmooth.keydefault = 10; timesmooth.when = 'After'; option.timesmooth = timesmooth; rapid.key = 'Rapid'; rapid.type = 'Boolean'; rapid.default = 0; option.rapid = rapid; phase.key = 'Phase'; phase.type = 'Boolean'; phase.default = 1; option.phase = phase; specif.option = option; specif.defaultframelength = 0.05; specif.defaultframehop = 0.5; specif.eachchunk = @eachchunk; specif.combinechunk = @combinechunk; if isamir(orig,'mirscalar') || isamir(orig,'mirenvelope') specif.nochunk = 1; end varargout = mirfunction(@mirspectrum,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = 'mirspectrum'; function s = main(orig,option,postoption) if isstruct(option) if option.collapsed option.band = 'Cents'; end if isnan(option.res) && strcmpi(option.band,'Cents') && option.min option.res = option.min *(2^(1/1200)-1)*.9; end end if not(isempty(postoption)) if not(strcmpi(postoption.band,'Freq') && isempty(postoption.msum) ... && isempty(postoption.mprod)) ... || postoption.log || postoption.db ... || postoption.pow || postoption.mask || postoption.collapsed ... || postoption.aver || postoption.gauss option.phase = 0; end end if iscell(orig) orig = orig{1}; end if isa(orig,'mirspectrum') && ... not(isfield(option,'alongbands') && option.alongbands) s = orig; if isfield(option,'min') && ... (option.min || iscell(option.max) || option.max < Inf) magn = get(s,'Magnitude'); freq = get(s,'Frequency'); for k = 1:length(magn) m = magn{k}; f = freq{k}; if iscell(option.max) mi = option.min{k}; ma = option.max{k}; else mi = option.min; ma = option.max; end if not(iscell(m)) m = {m}; f = {f}; end for l = 1:length(m) range = find(and(f{l}(:,1) >= mi,f{l}(:,1) <= ma)); m{l} = m{l}(range,:,:); f{l} = f{l}(range,:,:); end magn{k} = m; freq{k} = f; end s = set(s,'Magnitude',magn,'Frequency',freq); end if not(isempty(postoption)) && not(isequal(postoption,0)) s = post(s,postoption); end elseif ischar(orig) s = mirspectrum(miraudio(orig),option,postoption); else if nargin == 0 orig = []; end s.phase = []; s.log = 0; s.xscale = 'Freq'; s.pow = 1; s = class(s,'mirspectrum',mirdata(orig)); s = purgedata(s); s = set(s,'Title','Spectrum','Abs','frequency (Hz)','Ord','magnitude'); %disp('Computing spectrum...') sig = get(orig,'Data'); t = get(orig,'Pos'); if isempty(t) t = get(orig,'FramePos'); for k = 1:length(sig) for l = 1:length(sig{k}) sig{k}{l} = sig{k}{l}'; t{k}{l} = t{k}{l}(1,:,:)'; end end end fs = get(orig,'Sampling'); fp = get(orig,'FramePos'); fr = get(orig,'FrameRate'); lg = get(orig,'Length'); m = cell(1,length(sig)); p = cell(1,length(sig)); f = cell(1,length(sig)); for i = 1:length(sig) d = sig{i}; fpi = fp{i}; if not(iscell(d)) d = {d}; end if option.alongbands fsi = fr{i}; else fsi = fs{i}; end mi = cell(1,length(d)); phi = cell(1,length(d)); fi = cell(1,length(d)); for J = 1:length(d) dj = d{J}; if option.ni mxdj = repmat(max(dj),[size(dj,1),1,1]); mndj = repmat(min(dj),[size(dj,1),1,1]); dj = (dj-mndj)./(mxdj-mndj); end if option.alongbands if size(dj,1)>1 error('ERROR IN MIRSPECTRUM: ''AlongBands'' is restricted to spectrum decomposed into bands, such as ''Mel'' and ''Bark''.') end dj = reshape(dj,[size(dj,2),1,size(dj,3)]); fp{i}{J} = fp{i}{J}([1;end]); lg{i}{J} = diff(fp{i}{J}) * fs{i}; end if option.constq % Constant Q Transform r = 2^(1/option.constq); Q = 1 / (r - 1); f_max = min(fsi/2,option.max); f_min = option.min; if not(f_min) f_min = 16.3516; end B = floor(log(f_max/f_min) / log(r)); % number of bins N0 = round(Q*fsi/f_min); % maximum Nkcq j2piQn = -1i*2*pi*Q*(0:N0-1)'; fj = f_min * r.^(0:B-1)'; transf = NaN(B,size(dj,2),size(dj,3)); for kcq = 1:B Nkcq = round(Q*fsi/fj(kcq)); win = mirwindow(dj,option.win,Nkcq); exq = repmat(exp(j2piQn(1:Nkcq)/Nkcq),... [1,size(win,2),size(win,3)]); transf(kcq,:) = sum(win.* exq) / Nkcq; end else % FFT dj = mirwindow(dj,option.win); if option.zp if option.zp < Inf dj = [dj;zeros(option.zp,size(dj,2),size(dj,3))]; else dj = [dj;zeros(size(dj))]; end end if isstruct(postoption) if strcmpi(postoption.band,'Mel') && ... (not(option.mr) || option.mr > 66) option.mr = 66; end else %warning('WARNING in MIRSPECTRUM (for debugging purposes): By default, minimum resolution specified.') if not(option.mr) option.mr = 66; end end if option.octave N = size(dj,1); res = (2.^(1/option.mr)-1)*option.octave; % Minimal freq ratio between 2 first bins. % freq resolution should be > option.min * res Nrec = fsi/(option.min*res); % Recommended minimal sample length. if Nrec > N % If actual sample length is too small. option.min = fsi/N / res; warning('WARNING IN MIRSPECTRUM: The input signal is too short to obtain the desired octave resolution. Lowest frequencies will be ignored.'); display(['(The recommended minimal input signal length would be ' num2str(Nrec/fsi) ' s.)']); display(['New low frequency range: ' num2str(option.min) ' Hz.']); end N = 2^nextpow2(N); elseif isnan(option.length) if isnan(option.res) N = size(dj,1); if option.mr && N < fsi/option.mr if option.wr && N < fsi/option.wr warning('WARNING IN MIRSPECTRUM: The input signal is too short to obtain the desired frequency resolution. Performed zero-padding will not guarantee the quality of the results.'); end N = max(N,fsi/option.mr); end N = 2^nextpow2(N); else N = ceil(fsi/option.res); end else N = option.length; end % Here is the spectrum computation itself transf = fft(dj,N); %/(length(dj)); len = floor(N/2+1); fj = fsi/2 * linspace(0,1,len)'; if option.max maxf = find(fj>=option.max,1); if isempty(maxf) maxf = len; end else maxf = len; end if option.min minf = find(fj>=option.min,1); if isempty(minf) maxf = len; end else minf = 1; end transf = transf(minf:maxf,:,:); fj = fj(minf:maxf); end mi{J} = abs(transf); if option.phase phi{J} = angle(transf); end fi{J} = repmat(fj,[1,size(transf,2),size(transf,3)]); end if iscell(sig{i}) m{i} = mi; p{i} = phi; f{i} = fi; else m{i} = mi{1}; p{i} = phi{1}; f{i} = fi{1}; end end s = set(s,'Frequency',f,'Magnitude',m,'Phase',p,... 'FramePos',fp,'Length',lg); if not(isempty(postoption)) && isstruct(postoption) s = post(s,postoption,orig); end end function s = post(s,option,orig) if option.collapsed option.band = 'Cents'; end m = get(s,'Magnitude'); f = get(s,'Frequency'); sr = get(s,'Sampling'); for k = 1:length(m) if not(iscell(m{k})) m{k} = {m{k}}; f{k} = {f{k}}; end end if option.timesmooth [state s] = gettmp(s); B = ones(1,option.timesmooth)/option.timesmooth; for h = 1:length(m) for l = 1:length(m{k}) [m{h}{l} state] = filter(B,1,m{h}{l},state,2); %mhl = m{h}{l}; %for i = 1:size(m{h}{l},2) % m{h}{l}(:,i) = min(mhl(:,max(1,i-option.timesmooth+1):i),... % [],2); %end end end s = settmp(s,state); end if get(s,'Power') == 1 && ... (option.pow || any(option.mprod) || any(option.msum)) % mprod could be tried without power? for h = 1:length(m) for l = 1:length(m{k}) m{h}{l} = m{h}{l}.^2; end end s = set(s,'Power',2,'Title',['Power ',get(s,'Title')],'Phase',[]); end if any(option.mprod) for h = 1:length(m) for l = 1:length(m{k}) z0 = m{h}{l}; z1 = z0; for k = 1:length(option.mprod) mpr = option.mprod(k); if mpr zi = ones(size(z0)); zi(1:floor(end/mpr),:,:) = z0(mpr:mpr:end,:,:); z1 = z1.*zi; end end m{h}{l} = z1; end end s = set(s,'Title','Spectral product'); end if any(option.msum) for h = 1:length(m) for l = 1:length(m{k}) z0 = m{h}{l}; z1 = z0; for k = 1:length(option.msum) mpr = option.msum(k); if mpr zi = ones(size(z0)); zi(1:floor(end/mpr),:,:) = z0(mpr:mpr:end,:,:); z1 = z1+zi; end end m{h}{l} = z1; end end s = set(s,'Title','Spectral sum'); end if option.norm for k = 1:length(m) for l = 1:length(m{k}) mkl = m{k}{l}; nkl = zeros(1,size(mkl,2),size(mkl,3)); for kk = 1:size(mkl,2) for ll = 1:size(mkl,3) nkl(1,kk,l) = norm(mkl(:,kk,ll)); end end m{k}{l} = mkl./repmat(nkl,[size(m{k}{k},1),1,1]); end end end if option.nl lg = get(s,'Length'); for k = 1:length(m) for l = 1:length(m{k}) m{k}{l} = m{k}{l}/(lg{k}{l}/sr{k}); end end end if option.terhardt && not(isempty(find(f{1}{1}))) % This excludes the case where spectrum already along bands % Code taken from Pampalk's MA Toolbox for k = 1:length(m) for l = 1:length(m{k}) W_Adb = zeros(size(f{k}{l})); W_Adb(2:size(f{k}{l},1),:,:) = ... + 10.^((-3.64*(f{k}{l}(2:end,:,:)/1000).^-0.8 ... + 6.5 * exp(-0.6 * (f{k}{l}(2:end,:,:)/1000 - 3.3).^2) ... - 0.001*(f{k}{l}(2:end,:,:)/1000).^4)/20); W_Adb = W_Adb.^2; m{k}{l} = m{k}{l}.*W_Adb; end end end if option.reso if not(ischar(option.reso)) if strcmp(get(orig,'XScale'),'Mel') option.reso = 'Fluctuation'; else option.reso = 'ToiviainenSnyder'; end end for k = 1:length(m) for l = 1:length(m{k}) if strcmpi(option.reso,'ToiviainenSnyder') || strcmpi(option.reso,'Meter') w = max(0,... 1 - 0.25*(log2(max(1./max(f{k}{l},1e-12),1e-12)/0.5)).^2); elseif strcmpi(option.reso,'Fluctuation') w1 = f{k}{l} / 4; % ascending part of the fluctuation curve; w2 = 1 - 0.3 * (f{k}{l} - 4)/6; % descending part; %%% Negative! w = min(w1,w2); w = max(0,w); end if max(w) == 0 warning('The resonance curve, not defined for this range of delays, will not be applied.') else m{k}{l} = m{k}{l}.* w; end end end end if strcmp(s.xscale,'Freq') if strcmpi(option.band,'Mel') % The following is largely based on the source code from Auditory Toolbox % (A part that I could not call directly from MIRtoolbox) % (Malcolm Slaney, August 1993, (c) 1998 Interval Research Corporation) try MakeERBFilters(1,1,1); % Just to be sure that the Auditory Toolbox is installed catch error('ERROR IN MIRFILTERBANK: Auditory Toolbox needs to be installed.'); end %disp('Computing Mel-frequency spectral representation...') lowestFrequency = 133.3333; if not(option.nbbands) option.nbbands = 40; end linearFilters = min(13,option.nbbands); linearSpacing = 66.66666666; logFilters = option.nbbands - linearFilters; logSpacing = 1.0711703; totalFilters = option.nbbands; % Figure the band edges. Interesting frequencies are spaced % by linearSpacing for a while, then go logarithmic. First figure % all the interesting frequencies. Lower, center, and upper band % edges are all consequtive interesting frequencies. freqs = lowestFrequency + (0:linearFilters-1)*linearSpacing; freqs(linearFilters+1:totalFilters+2) = ... freqs(linearFilters) * logSpacing.^(1:logFilters+2); lower = freqs(1:totalFilters); center = freqs(2:totalFilters+1); upper = freqs(3:totalFilters+2); % Figure out the height of the triangle so that each filter has % unit weight, assuming a triangular weighting function. triangleHeight = 2./(upper-lower); e = cell(1,length(m)); nch = cell(1,length(m)); for h = 1:length(m) e{h} = cell(1,length(m{h})); for i = 1:length(m{h}) mi = m{h}{i}; fi = f{h}{i}(:,1,1); fftSize = size(fi,1); % We now want to combine FFT bins and figure out % each frequencies contribution mfccFilterWeights = zeros(totalFilters,fftSize); for chan=1:totalFilters mfccFilterWeights(chan,:) = triangleHeight(chan).*... ((fi > lower(chan) & fi <= center(chan)).* ... (fi-lower(chan))/(center(chan)-lower(chan)) + ... (fi > center(chan) & fi < upper(chan)).* ... (upper(chan)-fi)/(upper(chan)-center(chan))); end if find(diff(not(sum(mfccFilterWeights,2)))==-1) % If one channel has no weight whereas the higher one % has a positive weight. warning('WARNING in MIRSPECTRUM: The frequency resolution of the spectrum is too low for the Mel transformation. Some Mel components are undefined.') display('Recommended frequency resolution: at least 66 Hz.') end e{h}{i} = zeros(1,size(mi,2),totalFilters); for J = 1:size(mi,2) if max(mi(:,J)) > 0 fftData = zeros(fftSize,1); % Zero-padding ? fftData(1:size(mi,1)) = mi(:,J); p = mfccFilterWeights * fftData + 1e-16; e{h}{i}(1,J,:) = reshape(p,[1,1,length(p)]); end end f{h}{i} = zeros(1,size(mi,2),totalFilters); end nch{h} = (1:totalFilters)'; end m = e; s = set(s,'XScale','Mel','Title','Mel-Spectrum',... 'Abs','Mel bands','Channels',nch,'Phase',[]); elseif strcmpi(option.band,'Bark') sr = get(s,'Sampling'); % Code taken from Pampalk's MA Toolbox. %% zwicker & fastl: psychoacoustics 1999, page 159 bark_upper = [10 20 30 40 51 63 77 92 108 127 148 172 200 232 270 315 370 440 530 640 770 950 1200 1550]*10; %% Hz e = cell(1,length(m)); nch = cell(1,length(m)); for h = 1:length(m) %% ignore critical bands outside of sampling rate range cb = min(min([find(bark_upper>sr{h}/2),length(bark_upper)]),length(bark_upper)); e{h} = cell(1,length(m{h})); for i = 1:length(m{h}) mi = sum(m{h}{i},3); e{h}{i} = zeros(1,size(mi,2),cb); k = 1; for J=1:cb, %% group into bark bands idx = find(f{h}{i}(k:end,1,1)<=bark_upper(J)); idx = idx + k-1; e{h}{i}(1,:,J) = sum(mi(idx,:,:),1); k = max(idx)+1; end f{h}{i} = zeros(1,size(mi,2),cb); end nch{h} = (1:cb)'; end m = e; s = set(s,'XScale','Bark','Title','Bark-Spectrum',... 'Abs','Bark bands','Channels',nch,'Phase',[]); elseif strcmpi(option.band,'Cents') || option.collapsed for h = 1:length(m) for i = 1:length(m{h}) mi = m{h}{i}; fi = f{h}{i}; isgood = fi(:,1,1)*(2^(1/1200)-1) >= fi(2,1,1)-fi(1,1,1); good = find(isgood); if isempty(good) mirerror('mirspectrum',... 'The frequency resolution of the spectrum is too low to be decomposed into cents.'); display('Hint: if you specify a minimum value for the frequency range (''Min'' option)'); display(' and if you do not specify any frequency resolution (''Res'' option), '); display(' the correct frequency resolution will be automatically chosen.'); end if good>1 warning(['MIRSPECTRUM: Frequency resolution in cent is achieved for frequencies over ',... num2str(floor(fi(good(1)))),' Hz. Lower frequencies are ignored.']) display('Hint: if you specify a minimum value for the frequency range (''Min'' option)'); display(' and if you do not specify any frequency resolution (''Res'' option), '); display(' the correct frequency resolution will be automatically chosen.'); end fi = fi(good,:,:); mi = mi(good,:,:); f2cents = 440*2.^(1/1200*(-1200*10:1200*10-1)'); % The frequencies corresponding to the cent range cents = repmat((0:1199)',[20,size(fi,2),size(fi,3)]); % The cent range is for the moment centered to A440 octaves = ones(1200,1)*(-10:10); octaves = repmat(octaves(:),[1,size(fi,2),size(fi,3)]); select = find(f2cents>fi(1) & f2cents<fi(end)); % Cent range actually used in the current spectrum f2cents = repmat(f2cents(select),[1,size(fi,2),size(fi,3)]); cents = repmat(cents(select),[1,size(fi,2),size(fi,3)]); octaves = repmat(octaves(select),[1,size(fi,2),size(fi,3)]); m{h}{i} = interp1(fi(:,1,1),mi,f2cents(:,1,1)); f{h}{i} = octaves*1200+cents + 6900; % Now the cent range is expressed in midicent end end s = set(s,'Abs','pitch (in midicents)','XScale','Cents','Phase',[]); end end if option.mask if strcmp(s.xscale,'Freq') warning('WARNING IN MIRSPECTRUM: ''Mask'' option available only for Mel-spectrum and Bark-spectrum.'); disp('''Mask'' option ignored'); else nch = get(s,'Channels'); for h = 1:length(m) % Code taken from Pampalk's MA Toolbox. %% spreading function: schroeder et al., 1979, JASA, optimizing %% digital speech coders by exploiting masking properties of the human ear cb = length(nch{h}); % Number of bands. for i = 1:cb, spread(i,:) = 10.^((15.81+7.5*((i-(1:cb))+0.474)-17.5*(1+((i-(1:cb))+0.474).^2).^0.5)/10); end for i = 1:length(m{h}) for J = 1:size(m{h}{i},2) mj = m{h}{i}(1,J,:); mj = spread(1:length(mj),1:length(mj))*mj(:); m{h}{i}(1,J,:) = reshape(mj,1,1,length(mj)); end end end end end if option.collapsed for h = 1:length(m) for i = 1:length(m{h}) mi = m{h}{i}; fi = f{h}{i}; centclass = rem(fi(:,1,1),1200); %neg = find(centclass<0); %centclass(neg) = 1200 + centclass(neg); m{h}{i} = NaN(1200,size(mi,2),size(mi,3)); for k = 0:1199 m{h}{i}(k+1,:,:) = sum(mi(find(centclass==k),:,:),1); end f{h}{i} = repmat((0:1199)',[1,size(fi,2),size(fi,3)]); end end s = set(s,'Abs','Cents','XScale','Cents(Collapsed)'); end if option.log || option.db if not(isa(s,'mirspectrum') && s.log) for k = 1:length(m) if not(iscell(m{k})) m{k} = {m{k}}; f{k} = {f{k}}; end for l = 1:length(m{k}) m{k}{l} = log10(m{k}{l}+1e-16); if option.db m{k}{l} = 10*m{k}{l}; if get(s,'Power') == 1 m{k}{l} = m{k}{l}*2; end end end end elseif isa(s,'mirspectrum') && option.db && s.log<10 for k = 1:length(m) for l = 1:length(m{k}) m{k}{l} = 10*m{k}{l}; if get(s,'Power') == 1 m{k}{l} = m{k}{l}*2; end end end end if option.db s = set(s,'log',10); s = set(s,'Power',2); else s = set(s,'log',1); end if option.db>0 && option.db < Inf for k = 1:length(m) for l = 1:length(m{k}) m{k}{l} = m{k}{l}-repmat(max(m{k}{l}),[size(m{k}{l},1) 1 1]); m{k}{l} = option.db + max(-option.db,m{k}{l}); end end end s = set(s,'Phase',[]); end if option.aver for k = 1:length(m) for i = 1:length(m{k}) m{k}{i} = filter(ones(1,option.aver)/option.aver,1,m{k}{i}); end end s = set(s,'Phase',[]); end if option.gauss for k = 1:length(m) for i = 1:length(m{k}) sigma = option.gauss; gauss = 1/sigma/2/pi... *exp(- (-4*sigma:4*sigma).^2 /2/sigma^2); y = filter(gauss,1,[m{k}{i};zeros(4*sigma,size(m{k}{1},2))]); y = y(4*sigma:end,:,:); m{k}{i} = y(1:size(m{k}{i},1),:,:); end end s = set(s,'Phase',[]); end s = set(s,'Magnitude',m,'Frequency',f); function dj = mirwindow(dj,win,N) if nargin<3 N = size(dj,1); elseif size(dj,1)<N dj(N,1,1) = 0; end if not(win == 0) winf = str2func(win); try w = window(winf,N); catch if strcmpi(win,'hamming') disp('Signal Processing Toolbox does not seem to be installed. Recompute the hamming window manually.'); w = 0.54 - 0.46 * cos(2*pi*(0:N-1)'/(N-1)); else error(['ERROR in MIRSPECTRUM: Unknown windowing function ',win,' (maybe Signal Processing Toolbox is not installed).']); end end kw = repmat(w,[1,size(dj,2),size(dj,3)]); dj = dj(1:N,:,:).* kw; end function [y orig] = eachchunk(orig,option,missing,postchunk) option.zp = option.zp+missing; y = mirspectrum(orig,option); function y = combinechunk(old,new) doo = get(old,'Data'); doo = doo{1}{1}; dn = get(new,'Data'); dn = dn{1}{1}; y = set(old,'ChunkData',doo+dn);
github
martinarielhartmann/mirtooloct-master
mirhisto.m
.m
mirtooloct-master/MIRToolbox/@mirhisto/mirhisto.m
3,357
utf_8
6f716ac28bcb19a4355603f708ace933
function varargout = mirhisto(x,varargin) % h = mirhisto(x) constructs the histogram from x. The elements of x are % binned into equally spaced containers. % Optional argument: % mirhisto(...,'Number',n): specifies the number of containers. % Default value : n = 10. % mirhisto(...,'Ampli'): adds the amplitude of the elements,instead of % simply counting then. n.key = 'Number'; n.type = 'Integer'; n.default = 10; option.n = n; a.key = 'Ampli'; a.type = 'Boolean'; a.default = 0; option.a = a; specif.option = option; varargout = mirfunction(@mirhisto,x,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = 'mirhisto'; function h = main(x,option,postoption) if iscell(x) x = x{1}; end d = get(x,'Data'); fp = get(x,'FramePos'); %disp('Computing histogram...') ddd = cell(1,length(d)); bbb = cell(1,length(d)); for i = 1:length(d) di = d{i}{1}; % To be generalized for segmented data if iscell(di) mx = -Inf; mn = Inf; nc = size(di,2); for k = 1:nc dk = di{k}; if size(dk,4) == 2 dk(end+1:end*2,:,:,1) = dk(:,:,:,2); dk(:,:,:,2) = []; end mxk = max(dk); mnk = min(dk); if mxk > mx mx = mxk; end if mnk < mn mn = mnk; end end if isinf(mx) || isinf(mx) b = []; dd = []; else dd = zeros(1,option.n); if mn == mx b(1,:) = mn-ceil(option.n/2) : mn+floor(option.n/2); else b(1,:) = mn : (mx-mn)/option.n : mx; end for k = 1:nc dk = di{k}; for j = 1:option.n found = find(and(dk>=b(1,j),dk<=b(1,j+1))); if option.a dd(1,j) = dd(1,j) + sum(dk(found)); else dd(1,j) = dd(1,j) + length(found); end end end end else if isa(x,'mirscalar') di = permute(di,[3 2 1]); end if size(di,4) == 2 di(end+1:end*2,:,:,1) = di(:,:,:,2); di(:,:,:,2) = []; end nl = size(di,1); nc = size(di,2); np = size(di,3); dd = zeros(1,option.n,np); for l = 1:np mx = max(max(di(:,:,l),[],1),[],2); mn = min(min(di(:,:,l),[],1),[],2); b(l,:) = mn:(mx-mn)/option.n:mx; for k = 1:nc dk = di(:,k,l); for j = 1:option.n found = (find(and(dk>=b(l,j),dk<=b(l,j+1)))); if option.a dd(1,j,l) = dd(1,j,l) + sum(dk(found)); else dd(1,j,l) = dd(1,j,l) + length(found); end end end end end ddd{i} = ipermute(dd,[3 2 1]); bbb{i}(:,:,1) = b(:,1:end-1); bbb{i}(:,:,2) = b(:,2:end); fp{i} = {fp{i}{1}([1 end])'}; end x = set(x,'FramePos',fp); h = class(struct,'mirhisto',mirdata(x)); h = purgedata(h); h = set(h,'Bins',bbb,'Weight',ddd);
github
martinarielhartmann/mirtooloct-master
mirclassify.m
.m
mirtooloct-master/MIRToolbox/@mirclassify/mirclassify.m
8,794
utf_8
2defa2037b7f54ef59ab70750bf85223
function c = mirclassify(x,varargin) % Optional argument: % mirclassify(...,'Nearest') uses the minimum distance strategy. % (by default) % mirclassify(...,'Nearest',k) uses the k-nearest-neighbour strategy. % Default value: k = 1, corresponding to the minimum distance % strategy. % mirclassify(...,'GMM',ng) uses a gaussian mixture model. Each class is % modeled by at most ng gaussians. % Default value: ng = 1. % Additionnally, the type of mixture model can be specified, % using the set of value proposed in the gmm function: i.e., % 'spherical','diag','full' (default value) and 'ppca'. % (cf. help gmm) % Requires the Netlab toolbox. if not(iscell(x)) x = {x}; end n = get(x{1},'Name'); l = length(n); % Number of training samples lab = cell(1,l); allabs = struct; for i = 1:l sl = strfind(n{i},'/'); if isempty(sl) mirerror('mirclassify','There should not be audio files in the main folder. They should be all in subfolders corresponding to the different classes.'); end lab{i} = n{i}(1:sl(end)-1); if i == 1 allabs.name = lab{1}; allabs.idx = 1; continue end [test li] = ismember(lab{i},{allabs.name}); if test allabs(li).idx(end+1) = i; else allabs(end+1).name = lab{i}; allabs(end).idx = i; end end [k,ncentres,covartype,kmiter,emiter,d,mahl] = scanargin(varargin); nfolds = length(allabs(1).idx); v = []; % Preprocessed training vectors mn = cell(1,length(x)); sd = cell(1,length(x)); for i = 1:length(x) if isnumeric(x{i}) d = cell(1,size(x{i},2)); for j = 1:size(x{i},2) d{j} = x{i}(:,j); end else d = get(x{i},'Data'); end [v mn{i} sd{i}] = integrate(v,d,l); if 0 %isa(t{i},'scalar') m = mode(x{i}); if not(isempty(m)) v = integrate(v,m,l); end end end mahl = cov(v'); for i = 1:length(allabs) s = RandStream('mt19937ar','Seed','shuffle'); p = randperm(s,length(allabs(i).idx)); allabs(i).idx = allabs(i).idx(p); end for h = 1:nfolds va = []; vt = []; idxh = zeros(1,length(allabs)); rlab = cell(1,length(allabs)); rlabt = cell(1,length(allabs)*(nfolds-1)); for i = 1:length(allabs) idxi = allabs(i).idx; va = [va v(:,allabs(i).idx(h))]; for j = (nfolds-1)*(i-1)+(1:nfolds-1) rlabt{j} = allabs(i).name; end idxi(h) = []; vt = [vt v(:,idxi)]; rlab{i} = allabs(i).name; end if k % k-Nearest Neighbour c.nbparam = size(vt,2); for l = 1:size(va,2) [sv,idx] = sort(distance(va(:,l),vt,mahl)); labs = cell(0); % Class labels founds = []; % Number of found elements in each class for i = idx(1:k) labi = rlabt{i}; found = 0; for j = 1:length(labs) if isequal(labi,labs{j}) found = j; end end if found founds(found) = founds(found)+1; else labs{end+1} = labi; founds(end+1) = 1; end end [b ib] = max(founds); c.classes{h,l} = labs{ib}; end elseif ncentres % Gaussian Mixture Model labs = cell(0); % Class labels founds = cell(0); % Elements associated to each label. for i = 1:size(vt,2) labi = rlabt{i}; found = 0; for j = 1:length(labs) if isequal(labi,labs{j}) founds{j}(end+1) = i; found = 1; end end if not(found) labs{end+1} = labi; founds{end+1} = i; end end options = zeros(1, 18); options(2:3) = 1e-4; options(4) = 1e-6; options(16) = 1e-8; options(17) = 0.1; options(1) = 0; %Prints out error values, -1 else c.nbparam = 0; OK = 0; while not(OK) OK = 1; for i = 1:length(labs) options(14) = kmiter; try mix{i} = gmm(size(vt,1),ncentres,covartype); catch error('ERROR IN CLASSIFY: Netlab toolbox not installed.'); end mix{i} = netlabgmminit(mix{i},vt(:,founds{i})',options); options(5) = 1; options(14) = emiter; try mix{i} = gmmem(mix{i},vt(:,founds{i})',options); c.nbparam = c.nbparam + ... length(mix{i}.centres(:)) + length(mix{i}.covars(:)); catch %err = lasterr; %warning('WARNING IN CLASSIFY: Problem when calling GMMEM:'); %disp(err); %disp('Let us try again...'); OK = 0; end end end pr = zeros(size(va,2),length(labs)); for i = 1:length(labs) prior = length(founds{i})/size(vt,2); pr(:,i) = prior * gmmprob(mix{i},va'); %c.post{i} = gmmpost(mix{i},va'); end [mm ib] = max(pr'); for i = 1:size(va,2) c.classes{h,i} = labs{ib(i)}; end end if isempty(rlab) c.correct = NaN; else correct = 0; for i = 1:length(rlab) if isequal(c.classes{h,i},rlab{i}) correct = correct + 1; end end c.correct(h) = correct / length(rlab); end end c = class(c,'mirclassify'); disp('Expected classes:') rlab disp('Classification results:') c.classes if isnan(c.correct) disp('No label has been associated to the test set. Correct classification rate cannot be computed.'); else disp(['Correct classification rate: ',num2str(mean(c.correct),2)]); end figure if k v0 = zeros(size(v,1),0); for i = 1:length(allabs) v0 = [v0 v(:,allabs(i).idx)]; end ltick = nfolds; elseif ncentres v0 = zeros(size(v,1),length(mix)*ncentres); for i = 1:length(mix) for j = 1:ncentres v0(:,ncentres*(i-1)+j) = mix{i}.centres(j,:)'; end end ltick = ncentres; end imagesc(v0) set(gca,'XTick',ltick+.5:ltick:size(v,2)+.5) set(gca,'XTickLabel','') set(gca,'YTick',[]) grid on for i = 1:length(allabs) text(ltick*(i-1)+1,1,allabs(i).name); end function [vt m s] = integrate(vt,v,lvt,m,s) % lvt is the number of samples vtl = []; for l = 1:lvt vl = v{l}; if iscell(vl) vl = vl{1}; end if iscell(vl) vl = vl{1}; end if size(vl,2) > 1 mirerror('MIRCLASSIFY','The analytic features guiding the classification should not be frame-decomposed.'); end vtl(:,l) = vl; end if nargin<4 m = mean(vtl,2); s = std(vtl,0,2); end dnom = repmat(s,[1 size(vtl,2)]); dnom = dnom + (dnom == 0); % In order to avoid division by 0 vtl = (vtl - repmat(m,[1 size(vtl,2)])) ./ dnom; vt(end+1:end+size(vtl,1),:) = vtl; function [k,ncentres,covartype,kmiter,emiter,d,mahl] = scanargin(v) k = 1; d = 0; i = 1; ncentres = 0; covartype = 'full'; kmiter = 10; emiter = 100; mahl = 1; while i <= length(v) arg = v{i}; if ischar(arg) && strcmpi(arg,'Nearest') k = 1; if length(v)>i && isnumeric(v{i+1}) i = i+1; k = v{i}; end elseif ischar(arg) && strcmpi(arg,'GMM') k = 0; ncentres = 1; if length(v)>i if isnumeric(v{i+1}) i = i+1; ncentres = v{i}; if length(v)>i && ischar(v{i+1}) i = i+1; covartype = v{i}; end elseif ischar(v{i+1}) i = i+1; covartype = v{i}; if length(v)>i && isnumeric(v{i+1}) i = i+1; ncentres = v{i}; end end end elseif isnumeric(arg) k = v{i}; else error('ERROR IN MIRCLASSIFY: Syntax error. See help mirclassify.'); end i = i+1; end function y = distance(a,t,mahl) for i = 1:size(t,2) if det(mahl) > 0 % more generally, uses cond lham = inv(mahl); else lham = pinv(mahl); end y(i) = sqrt((a - t(:,i))'*lham*(a - t(:,i))); end %y = sqrt(sum(repmat(a,[1,size(t,2)])-t,1).^2);
github
martinarielhartmann/mirtooloct-master
mirkeystrength.m
.m
mirtooloct-master/MIRToolbox/@mirkeystrength/mirkeystrength.m
3,445
utf_8
25ad1c532626e1a1e817061b825a234b
function varargout = mirkeystrength(orig,varargin) % ks = mirkeystrength(x) computes the key strength, i.e., the probability % associated with each possible key candidate. % Optional parameters: % mirkeystrength(...,'Frame',l,h) orders a frame decomposition of window % length l (in seconds) and hop factor h, expressed relatively to % the window length. For instance h = 1 indicates no overlap. % Default values: l = 1 seconds and h = .5 % The mirchromagram options 'Weight' and 'Triangle' can be specified. % [ks,c] = mirkeystrength(...) also displays the chromagram used for the key % strength estimation. % % Krumhansl, Cognitive foundations of musical pitch. Oxford UP, 1990. % Gomez, Tonal description of polyphonic audio for music content processing, % INFORMS Journal on Computing, 18-3, pp. 294-304, 2006. wth.key = 'Weight'; wth.type = 'Integer'; wth.default = .5; option.wth = wth; tri.key = 'Triangle'; tri.type = 'Boolean'; tri.default = 0; option.tri = tri; transp.key = 'Transpose'; transp.type = 'Integer'; transp.default = 0; transp.when = 'After'; option.transp = transp; specif.option = option; specif.defaultframelength = .1; specif.defaultframehop = .125; varargout = mirfunction(@mirkeystrength,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirkeystrength')) if not(isamir(x,'mirchromagram')) x = mirchromagram(x,'Weight',option.wth,'Triangle',option.tri,'Normal'); else x = mirchromagram(x,'Wrap','Normal'); end end type = 'mirkeystrength'; function k = main(orig,option,postoption) if iscell(orig) orig = orig{1}; end if isa(orig,'mirkeystrength') c = []; k = orig; else c = orig; load gomezprofs; m = get(c,'Magnitude'); st = cell(1,length(m)); kk = cell(1,length(m)); %disp('Computing key strengths...') for i = 1:length(m) mi = m{i}; if not(iscell(mi)) mi = {mi}; end si = cell(1,length(mi)); ki = cell(1,length(mi)); for j = 1:length(mi) mj = mi{j}; sj = zeros(12,size(mj,2),size(mj,3),2); kj = cell(12,size(mj,2),size(mj,3)); for k = 1:size(mj,2) for l = 1:size(mj,3) if ~max(abs(mj(:,k,l))) sj(:,k,l,:) = 0; else tmp = corrcoef([mj(:,k,l) gomezprofs']); sj(:,k,l,1) = tmp(1,2:13); sj(:,k,l,2) = tmp(1,14:25); end kj(:,k,l) = {'C','C#','D','D#','E','F','F#','G','G#','A','A#','B'}; end end si{j} = sj; ki{j} = kj; end st{i} = si; kk{i} = ki; end k = class(struct,'mirkeystrength',mirdata(c)); k = purgedata(k); k = set(k,'Title','Key strength','Abs','tonal center','Ord','strength',... 'Tonic',kk,'Strength',st,'MultiData',{'maj','min'},'Interpolable',0); end k = after(k,postoption); k = {k c}; function k = after(k,postoption) if postoption.transp transp = mod(postoption.transp,12); k = purgedata(k); d = mirgetdata(k); d = [d(13-transp:end,:,:,:);d(1:12-transp,:,:,:)]; k = set(k,'Data',{{d}}); end
github
martinarielhartmann/mirtooloct-master
mircepstrum.m
.m
mirtooloct-master/MIRToolbox/@mircepstrum/mircepstrum.m
4,674
utf_8
ce23ede2483821abfd1017cf8cdf0265
function varargout = mircepstrum(orig,varargin) % s = mircepstrum(x) computes the cepstrum, which indicates % periodicities, and is used for instance for pitch detection. % x can be either a spectrum, an audio signal, or the name of an audio file. % Optional parameter: % mircepstrum(...,'Min',min) specifies the lowest delay taken into % consideration, in seconds. % Default value: 0.0002 s (corresponding to a maximum frequency of % 5 kHz). % mircepstrum(...,'Max',max) specifies the highest delay taken into % consideration, in seconds. % Default value: 0.05 s (corresponding to a minimum frequency of % 20 Hz). % mircepstrum(...,'Freq') represents the cepstrum in the frequency % domain. mi.key = 'Min'; mi.type = 'Integer'; mi.default = 0.0002; mi.unit = {'s','Hz'}; mi.defaultunit = 's'; mi.opposite = 'ma'; option.mi = mi; ma.key = 'Max'; ma.type = 'Integer'; ma.default = .05; ma.unit = {'s','Hz'}; ma.defaultunit = 's'; ma.opposite = 'mi'; option.ma = ma; fr.key = 'Freq'; fr.type = 'Boolean'; fr.default = 0; option.fr = fr; complex.key = 'Complex'; complex.type = 'Boolean'; complex.default = 0; option.complex = complex; specif.option = option; specif.defaultframelength = 0.05; specif.defaultframehop = 0.5; varargout = mirfunction(@mircepstrum,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mircepstrum')) x = mirspectrum(x); end type = 'mircepstrum'; function c = main(orig,option,postoption) if iscell(orig) orig = orig{1}; end c.phase = []; if isa(orig,'mircepstrum') c.freq = orig.freq; else c.freq = 0; end c = class(c,'mircepstrum',mirdata(orig)); c = purgedata(c); c = set(c,'Title','Cepstrum','Abs','quefrency (s)','Ord','magnitude'); if isa(orig,'mircepstrum') if option.ma < Inf || option.mi > 0 || get(orig,'FreqDomain') mag = get(orig,'Magnitude'); pha = get(orig,'Phase'); que = get(orig,'Quefrency'); for h = 1:length(mag) for k = 1:length(mag{h}) if get(orig,'FreqDomain') mag{h}{k} = flipud(mag{h}{k}); que{h}{k} = flipud(1./que{h}{k}); pha{h}{k} = flipud(pha{h}{k}); end range = find(que{h}{k}(:,1,1) <= option.ma & ... que{h}{k}(:,1,1) >= option.mi); mag{h}{k} = mag{h}{k}(range,:,:); pha{h}{k} = pha{h}{k}(range,:,:); que{h}{k} = que{h}{k}(range,:,:); end end c = set(c,'Magnitude',mag,'Phase',pha,'Quefrency',que,'FreqDomain',0); end c = modif(c,option); elseif isa(orig,'mirspectrum') mag = get(orig,'Magnitude'); pha = get(orig,'Phase'); f = get(orig,'Sampling'); q = cell(1,length(mag)); for h = 1:length(mag) len = ceil(option.ma*f{h}); start = ceil(option.mi*f{h})+1; q{h} = cell(1,length(mag{h})); for k = 1:length(mag{h}) m = mag{h}{k}.*exp(1i*pha{h}{k}); m = [m(1:end-1,:) ; conj(flipud(m))]; % Reconstitution of the complete abs(FFT) if not(option.complex) m = abs(m); end m = log(m + 1e-12); c0=fft(m); q0=repmat((0:(size(c0,1)-1))'/f{k},[1,size(m,2),size(m,3)]); len = min(len,floor(size(c0,1)/2)); mag{h}{k} = abs(c0(start:len,:,:)); if option.complex pha{h}{k} = unwrap(angle(c0(start:len,:,:))); else pha{h}{k} = nan(size(c0(start:len,:,:))); end q{h}{k} = q0(start:len,:,:); end end c = set(c,'Magnitude',mag,'Phase',pha,'Quefrency',q); c = modif(c,option); end function c = modif(c,option) mag = get(c,'Magnitude'); que = get(c,'Quefrency'); if option.fr && not(get(c,'FreqDomain')) for k = 1:length(mag) for l = 1:length(mag{k}) m = mag{k}{l}; q = que{k}{l}; if not(isempty(m)) if q(1,1) == 0 m = m(2:end,:,:); q = q(2:end,:,:); end m = flipud(m); q = flipud(1./q); end mag{k}{l} = m; que{k}{l} = q; end end c = set(c,'FreqDomain',1,'Abs','frequency (Hz)'); end c = set(c,'Magnitude',mag,'Quefrency',que,'Freq');
github
martinarielhartmann/mirtooloct-master
mirpartial.m
.m
mirtooloct-master/MIRToolbox/@mirpartial/mirpartial.m
1,009
utf_8
2a4f8c2bb5ed2f391f6fe7eab0719176
function varargout = mirpartial(orig,varargin) max.key = 'Max'; max.type = 'Integer'; max.default = Inf; option.max = max; specif.option = option; varargout = mirfunction(@mirpartial,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = 'mirpartial'; function p = main(orig,option,postoption) a = get(orig,'Amplitude'); p = class(struct,'mirpartial',mirdata(orig)); p = purgedata(p); %fp = get(orig,'FramePos'); pos = cell(1,length(a)); dat = cell(1,length(a)); tp = cell(1,length(a)); for i = 1:length(a) pos{i} = cell(1,length(a{i})); dat{i} = cell(1,length(a{i})); for j = 1:length(a{i}) sizj = min(size(a{i}{j}{1},1),option.max); dat{i}{j} = a{i}{j}{1}(1:sizj,:); pos{i}{j} = repmat((1:sizj)',[1 size(dat{i}{j},2)]); end end p = set(p,'Title','Energy along partials',... 'Abs','partials','Ord','energy','Data',dat,'Pos',pos,... 'TrackPos',tp,'TrackVal',tp);
github
martinarielhartmann/mirtooloct-master
mirplay.m
.m
mirtooloct-master/MIRToolbox/@mirmidi/mirplay.m
523
utf_8
278bd0f7f6429d6298d1a5e2583f7110
function varargout = mirplay(a,varargin) % mirplay method for mirmidi objects. specif.option = struct; specif.eachchunk = 'Normal'; varargout = mirfunction(@mirplay,a,varargin,nargout,specif,@init,@main); if nargout == 0 varargout = {}; end function [x type] = init(x,option) type = ''; function noargout = main(a,option,postoption) if iscell(a) a = a{1}; end d = get(a,'Data'); n = get(a,'Name'); for k = 1:length(d) display(['Playing analysis of file: ' n{k}]) playmidi(d{k}); end noargout = {};
github
martinarielhartmann/mirtooloct-master
mirmidi.m
.m
mirtooloct-master/MIRToolbox/@mirmidi/mirmidi.m
3,166
utf_8
0a67555741f7166d9cdf9af228766d2d
function varargout = mirmidi(orig,varargin) % m = mirmidi(x) converts into a MIDI sequence. % Option associated to mirpitch function can be specified: % 'Contrast' with default value c = .3 thr.key = 'Contrast'; thr.type = 'Integer'; thr.default = .3; option.thr = thr; mono.key = 'Mono'; mono.type = 'Boolean'; mono.default = 1; option.mono = mono; release.key = {'Release','Releases'}; release.type = 'String'; release.choice = {'Olivier','Valeri',0,'no','off'}; release.default = 'Valeri'; option.release = release; specif.option = option; varargout = mirfunction(@mirmidi,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) try hz2midi(440); catch mirerror('MIRMIDI','MIDItoolbox does not seem to be installed.'); end if not(isamir(x,'mirmidi')) && not(isamir(x,'mirpitch')) if isa(x,'mirdesign') && not(option.mono) x = set(x,'SeparateChannels',1); end o = mironsets(x,'Attacks','Releases',option.release); x = {o x}; end type = 'mirmidi'; function m = main(x,option,postoption) transcript = 0; if iscell(x) o = x{1}; doo = get(o,'PeakVal'); da = get(o,'AttackPosUnit'); dr = get(o,'ReleasePosUnit'); a = x{2}; s = mirsegment(a,o); x = mirpitch(s,'Contrast',option.thr,'Sum',0); % x = mircentroid(s); dp = get(x,'Data'); else doo = []; if isa(x,'mirpitch') da = get(x,'Start'); dr = get(x,'End'); dp = get(x,'Degrees'); if isempty(da) dp = get(x,'Data'); else transcript = 1; end else da = get(x,'AttackPosUnit'); dr = get(x,'ReleasePosUnit'); end end df = get(x,'FramePos'); nmat = cell(1,length(dp)); if transcript for i = 1:length(dp) nmat{i} = zeros(length(dp{i}{1}{1}),7); for j = 1:length(dp{i}{1}{1}) t = df{i}{1}(1,da{i}{1}{1}(j)); d = df{i}{1}(2,dr{i}{1}{1}(j) )- t; v = 120; p = dp{i}{1}{1}(j) + 62; nmat{i}(j,:) = [t d 1 p v t d]; end end else for i = 1:length(dp) nmat{i} = []; if isempty(doo) first = 1; else first = 2; end for j = first:length(dp{i}) if isempty(doo) tij = df{i}{j}(1); dij = df{i}{j}(2)- tij; vij = 120; else tij = da{i}{1}{1}(j-1); if isempty(dr{i}) dij = 0; else dij = dr{i}{1}{1}(j-1) - tij; end vij = round(doo{i}{1}{1}(j-1)/max(doo{i}{1}{1})*120); end for k = 1:size(dp{i}{j},3) for l = 1:size(dp{i}{j},2) for n = 1:length(dp{i}{j}{1,l,k}) f = dp{i}{j}{1,l,k}(n); p = round(hz2midi(f)); nmat{i} = [nmat{i}; tij dij 1 p vij tij dij]; end end end end end end m = class(struct,'mirmidi',mirdata(x)); m = set(m,'Data',nmat);
github
martinarielhartmann/mirtooloct-master
mirsave.m
.m
mirtooloct-master/MIRToolbox/@mirmidi/mirsave.m
2,242
utf_8
058b8881d0014a70aa350bbd21fcb9fe
function mirsave(m,f) ext = 0; % Specified new extension if nargin == 1 f = '.mir'; elseif length(f)>3 && strcmpi(f(end-3:end),'.mid') ext = '.mid'; if length(f)==4 f = '.mir'; end elseif length(f)>2 && strcmpi(f(end-2:end),'.ly') ext = '.ly'; if length(f)==3 f = '.mir'; end end nmat = get(m,'Data'); n = get(m,'Name'); nf = length(nmat); for k = 1:nf nk = n{k}; if nf>1 || strcmp(f(1),'.') nk = [nk f]; else nk = f; end if not(ischar(ext)) || strcmp(ext,'.mid') if length(n)<4 || not(strcmpi(n(end-3:end),'.mid')) n = [n '.mid']; end %writemidi(nmat{k},nk,120,60); nmat2midi(nmat{k},nk); elseif strcmp(ext,'.ly') if length(n)<3 || not(strcmpi(n(end-2:end),'.ly ')) n = [n '.ly']; end lywrite(nmat{k},nk); end disp([nk,' saved.']); end function lywrite(nmat,filename) fid = fopen(filename,'wt'); v = ver('MIRtoolbox'); fprintf(fid,['% LilyPond score automatically generated using MIRtoolbox version ' v.Version]); fprintf(fid,'\\new Score \\with {\\override TimeSignature #''transparent = ##t} \n'); fprintf(fid,'\\relative c'' { \n'); fprintf(fid,'\\cadenzaOn \n'); for i = 1:size(nmat,1) switch mod(nmat(i,4)+2,12) case 0 p = 'c'; case 1 p = 'cis'; case 2 p = 'd'; case 3 p = 'dis'; case 4 p = 'e'; case 5 p = 'f'; case 6 p = 'fis'; case 7 p = 'g'; case 8 p = 'gis'; case 9 p = 'a'; case 10 p = 'ais'; case 11 p = 'b'; end if ~mod(i,15) fprintf(fid,'\\bar ""\n'); end if i>1 doo = round((nmat(i,4)-nmat(i-1,4))/12); if doo>0 for j = 1:doo p = [p '''']; end elseif doo<0 for j = 1:-doo p = [p ',']; end end end du = nmat(i,2); if du < .2 fprintf(fid,[p '16 ']); else fprintf(fid,[p '8 ']); end end fprintf(fid,'\n } \n \n \\version "2.14.2"');
github
martinarielhartmann/mirtooloct-master
mirtonalcentroid.m
.m
mirtooloct-master/MIRToolbox/@mirtonalcentroid/mirtonalcentroid.m
2,827
utf_8
ea99af0926744591d9cf85297a10c9d2
function varargout = mirtonalcentroid(orig,varargin) % c = mirtonalcentroid(x) calculates the 6-dimensional tonal centroid % vector from the chromagram. % It corresponds to a projection of the chords along circles of fifths, % of minor thirds, and of major thirds. % [c ch] = mirtonalcentroid(x) also returns the intermediate chromagram. % % C. A. Harte and M. B. Sandler, Detecting harmonic change in musical % audio, in Proceedings of Audio and Music Computing for Multimedia % Workshop, Santa Barbara, CA, 2006. frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [0 0]; frame.keydefault = [.743 .1]; option.frame = frame; specif.option = option; varargout = mirfunction(@mirtonalcentroid,orig,varargin,nargout,specif,@init,@main); function [c type] = init(orig,option) if option.frame.length.val c = mirchromagram(orig,'Frame',option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit,... option.frame.phase.val,... option.frame.phase.unit,... option.frame.phase.atend); else c = mirchromagram(orig); end type = 'mirtonalcentroid'; function tc = main(ch,option,postoption) if iscell(ch) ch = ch{1}; end if isa(ch,'mirtonalcentroid') tc = orig; ch = []; else x1 = sin(pi*7*(0:11)/6)'; y1 = cos(pi*7*(0:11)/6)'; % minor thirds circle x2 = sin(pi*3*(0:11)/2)'; y2 = cos(pi*3*(0:11)/2)'; % major thirds circle x3 = 0.5 * sin(pi*2*(0:11)/3)'; y3 = 0.5 * cos(pi*2*(0:11)/3)'; c = [x1 y1 x2 y2 x3 y3]; c = c'; tc = class(struct,'mirtonalcentroid',mirdata(ch)); tc = purgedata(tc); tc = set(tc,'Title','Tonal centroid','Abs','dimensions','Ord','position'); m = get(ch,'Magnitude'); %disp('Computing tonal centroid...') n = cell(1,length(m)); % The final structured list of magnitudes. d = cell(1,length(m)); % The final structured list of centroid dimensions. for i = 1:length(m) mi = m{i}; if not(iscell(mi)) mi = {mi}; end ni = cell(1,length(mi)); % The list of magnitudes. di = cell(1,length(mi)); % The list of centroid dimensions. for j = 1:length(mi) mj = mi{j}; ni{j} = zeros(6,size(mj,2),size(mi,3)); for k = 1:size(mj,3) ni{j}(:,:,k) = c * mj(:,:,k); end di{j} = repmat((1:6)',[1,size(mj,2),size(mi,3)]); end n{i} = ni; d{i} = di; end tc = set(tc,'Positions',n,'Dimensions',d); end tc = {tc,ch};
github
martinarielhartmann/mirtooloct-master
mirplay.m
.m
mirtooloct-master/MIRToolbox/@mirsimatrix/mirplay.m
2,286
utf_8
50e71f123737e04a5b795409d5de3af3
function mirplay(e,varargin) % mirplay method for mirsimatrix objects. specif.option = struct; specif.eachchunk = 'Normal'; varargout = mirfunction(@mirplay,e,varargin,nargout,specif,@init,@main); if nargout == 0 varargout = {}; end function [x type] = init(x,option) type = ''; function noargout = main(m,option,postoption) d = get(m,'Data'); n = get(m,'Name'); fp = get(m,'FramePos'); w = get(m,'Warp'); figure fp1 = cell2mat(fp{1}); fp2 = cell2mat(fp{2}); fp1m = (fp1(1,:,:,:)+fp1(2,:,:,:))/2; fp2m = (fp2(1,:,:,:)+fp2(2,:,:,:))/2; imagesc(fp2m,fp1m,d{1}{1}); hold on paths = w{1}; bests = w{2}; bestsindex = w{3}; [i j] = find(bests); mirverbose(0) for k = 1:length(i) best = bests(i(k),j(k)); bestindex = bestsindex(i(k),j(k)); path = paths{real(best)+1,imag(best)+1}{bestindex}; if path(2,end) - path(2,1) > 10 && path(1,end) - path(1,1) > 10 if 1 for h = 1:size(path,2) plot(fp2m(path(2,h)),fp1m(path(1,h)),'k+') end drawnow pause for h = 1:size(path,2) plot(fp2m(path(2,h)),fp1m(path(1,h)),'w+') end %a = miraudio(n{1},'Extract',fp1(1,path(1,1)),... % fp1(2,path(1,end))); %b = miraudio(n{1},'Extract',fp2(1,path(2,1)),... % fp2(2,path(2,end))); %mirplay(a); %mirplay(b); else d = 1; h = 1; while h < size(path,2) chge = find(path(d,h+1:end) > path(d,h),1); if isempty(chge) hh = h:size(path,2); else hh = h:h+chge-1; end plot(fp2m(path(2,hh)),fp1m(path(1,hh)),'k+'); drawnow a = miraudio(n{1},'Extract',fp1(1,path(1,hh(1))),... fp1(2,path(1,hh(end)))); b = miraudio(n{1},'Extract',fp2(1,path(2,hh(1))),... fp2(2,path(2,hh(end)))); mirplay(a); mirplay(b); h = hh(end)+1; d = 3-d; end end end end noargout = {};
github
martinarielhartmann/mirtooloct-master
mirsimatrix.m
.m
mirtooloct-master/MIRToolbox/@mirsimatrix/mirsimatrix.m
25,398
utf_8
ed638b58e2097bd95838bdda1b1b83c5
function varargout = mirsimatrix(orig,varargin) % m = mirsimatrix(x) computes the similarity matrix resulting from the % mutual comparison between each possible frame analysis in x. % By default, x is the spectrum of the frame decomposition. % But it can be any other frame analysis. % Optional argument: % mirsimatrix(...,'Distance',f) specifies the name of a distance % function, from those proposed in the Statistics Toolbox % (help pdist). % default value: f = 'cosine' % mirsimatrix(...,'Dissimilarity') return the dissimilarity matrix, % which is the intermediary result before the computation of the % actual similarity matrix. It shows the distance between each % possible frame analysis in x. % mirsimatrix(...,'Similarity',f) indicates the function f specifying % the way the distance values in the dissimilarity matrix are % transformed into similarity values. % Possible values: % f = 'oneminus' (default value) % corresponding to f(x) = 1-x % f = 'exponential' % corresponding to f(x)= exp(-x) % mirsimatrix(...,'Width',w) or more simply dissimatrix(...,w) % specifies the size of the diagonal bandwidth, in samples, % outside which the dissimilarity will not be computed. % if w = inf (default value), all the matrix will be computed. % mirsimatrix(...,'Horizontal') rotates the matrix 45 degrees in order to % make the first diagonal horizontal, and to restrict on the % diagonal bandwidth only. % mirsimatrix(...,'TimeLag') transforms the (non-rotated) matrix into % a time-lag matrix, making the first diagonal horizontal as well % (corresponding to the zero-lag line). % % Foote, J. & Cooper, M. (2003). Media Segmentation using Self-Similarity % Decomposition,. In Proc. SPIE Storage and Retrieval for Multimedia % Databases, Vol. 5021, pp. 167-75. % mirsimatrix(...,'Filter',10) filter along the diagonal of the matrix, % using a uniform moving average filter of size f. The result is % represented in a time-lag matrix. distance.key = 'Distance'; distance.type = 'String'; distance.default = 'cosine'; option.distance = distance; simf.key = 'Similarity'; simf.type = 'String'; simf.default = 'oneminus'; simf.keydefault = 'Similarity'; simf.when = 'After'; option.simf = simf; dissim.key = 'Dissimilarity'; dissim.type = 'Boolean'; dissim.default = 0; option.dissim = dissim; K.key = 'Width'; K.type = 'Integer'; K.default = Inf; option.K = K; filt.key = 'Filter'; filt.type = 'Integer'; filt.default = 0; filt.when = 'After'; option.filt = filt; view.type = 'String'; view.default = 'Standard'; view.choice = {'Standard','Horizontal','TimeLag'}; view.when = 'After'; option.view = view; half.key = 'Half'; half.type = 'Boolean'; half.default = 0; half.when = 'Both'; option.half = half; warp.key = 'Warp'; warp.type = 'Integer'; warp.default = 0; warp.keydefault = .5; warp.when = 'After'; option.warp = warp; cluster.key = 'Cluster'; cluster.type = 'Boolean'; cluster.default = 0; cluster.when = 'After'; option.cluster = cluster; arg2.position = 2; arg2.default = []; option.arg2 = arg2; frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [.05 1]; option.frame = frame; rate.type = 'Integer'; rate.position = 2; rate.default = 20; option.rate = rate; specif.option = option; specif.nochunk = 1; varargout = mirfunction(@mirsimatrix,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if isnumeric(x) m.diagwidth = Inf; m.view = 's'; m.half = 0; m.similarity = NaN; m.graph = {}; m.branch = {}; m.warp = []; m.clusters = []; m = class(m,'mirsimatrix',mirdata); m = set(m,'Title','Dissimilarity matrix'); fp = repmat(((1:size(x,1))-.5)/option.rate,[2,1]); x = set(m,'Data',{{x}},'Pos',[],... 'FramePos',{{fp}},'Name',{inputname(1)}); else if not(isamir(x,'mirsimatrix')) if isamir(x,'miraudio') if isframed(x) x = mirspectrum(x); else x = mirspectrum(x,'Frame',option.frame.length.val,option.frame.length.unit,... option.frame.hop.val,option.frame.hop.unit,... option.frame.phase.val,option.frame.phase.unit); end end end end type = 'mirsimatrix'; function m = main(orig,option,postoption) if postoption.filt postoption.view = 'TimeLag'; end if iscell(orig) orig = orig{1}; end if ~isframed(orig) mirerror('mirsimatrix','The input should be frame decomposed.'); end if isa(orig,'mirsimatrix') d = get(orig,'Data'); for k = 1:length(d) if iscell(option) && isfield(option,'K') && option.K < orig.diagwidth nl = size(d{k},1); if strcmp(orig.view,'h') dl = floor((nl - option.K)/2); dk = d{k}(dl:nl-dl,:); else [spA,spd] = spdiags(d{k},-floor(option.K/2):floor(option.K/2)); dk = full(spdiags(spA,spd,nl,size(d{k},2))); end d{k} = dk; orig.diagwidth = 2*floor(option.K/2)+1; end end m = set(orig,'Data',d); elseif isempty(option.arg2) v = get(orig,'Data'); d = cell(1,length(v)); lK = 2*floor(option.K/2)+1; for k = 1:length(v) vk = v{k}; if mirwaitbar handle = waitbar(0,'Computing dissimilarity matrix...'); else handle = []; end if not(iscell(vk)) vk = {vk}; end for z = 1:length(vk) vz = vk{z}; ll = size(vz,1); l = size(vz,2); nc = size(vz,3); if ll==1 && nc>1 vz = squeeze(vz)'; ll = nc; nc = 1; end nd = size(vz,4); if not(isempty(postoption)) && ... strcmpi(postoption.view,'TimeLag') if isinf(lK) if option.half lK = l; else lK = l*2-1; end end dk{z} = NaN(lK,l,nc); else dk{z} = zeros(l,l,nc); end for g = 1:nc if nd == 1 vv = vz; else vv = zeros(ll*nd,l); for h = 1:nd if iscell(vz) for i = 1:ll for j = 1:l vj = vz{i,j,g,h}; if isempty(vj) vv((h-1)*ll+i,j) = NaN; else vv((h-1)*ll+i,j) = vj; end end end else vv((h-1)*ll+1:h*ll,:) = vz(:,:,g,h); end end end if isinf(option.K) && not(strcmpi(postoption.view,'TimeLag')) try manually = 0; dk{z}(:,:,g) = squareform(pdist(vv',option.distance)); catch manually = 1; end else manually = 1; end if manually if strcmpi(option.distance,'cosine') for i = 1:l nm = norm(vv(:,i)); if ~isnan(nm) && nm vv(:,i) = vv(:,i)/nm; end end end hK = ceil(lK/2); if not(isempty(postoption)) && ... strcmpi(postoption.view,'TimeLag') for i = 1:l if mirwaitbar && (mod(i,100) == 1 || i == l) waitbar(i/l,handle); end ij = min(i+lK-1,l); % Frame region i:ij if ij==i continue end if strcmpi(option.distance,'cosine') dkij = cosine(vv(:,i),vv(:,i:ij)); else mm = squareform(pdist(vv(:,i:ij)',... option.distance)); dkij = mm(:,1); end if option.half for j = 1:length(dkij) dk{z}(j,i+j-1,g) = dkij(j); end else for j = 0:ij-i if hK-j>0 dk{z}(hK-j,i,g) = dkij(j+1); end if hK+j<=lK dk{z}(hK+j,i+j,g) = dkij(j+1); end end end end else win = window(@hanning,lK); win = win(ceil(length(win)/2):end); for i = 1:l if mirwaitbar && (mod(i,100) == 1 || i == l) waitbar(i/l,handle); end j = min(i+hK-1,l); if j==i continue end if strcmpi(option.distance,'cosine') dkij = cosine(vv(:,i),vv(:,i:j))'; else mm = squareform(pdist(vv(:,i:j)',... option.distance)); dkij = mm(:,1); end dkij = dkij.*win(1:length(dkij)); dk{z}(i,i:j,g) = dkij'; if ~option.half dk{z}(i:j,i,g) = dkij; end end end elseif option.half for i = 1:l dk{z}(i+1:end,i,g) = 0; end end end end d{k} = dk; if ~isempty(handle) delete(handle) end end m.diagwidth = lK; if not(isempty(postoption)) && strcmpi(postoption.view,'TimeLag') m.view = 'l'; else m.view = 's'; end m.half = option.half; m.similarity = 0; m.graph = {}; m.branch = {}; m.warp = []; m.clusters = []; m = class(m,'mirsimatrix',mirdata(orig)); m = purgedata(m); m = set(m,'Title','Dissimilarity matrix'); m = set(m,'Data',d,'Pos',[]); else v1 = get(orig,'Data'); v2 = get(option.arg2,'Data'); n1 = get(orig,'Name'); n2 = get(option.arg2,'Name'); fp1 = get(orig,'FramePos'); fp2 = get(option.arg2,'FramePos'); v1 = v1{1}{1}; v2 = v2{1}{1}; nf1 = size(v1,2); nf2 = size(v2,2); nd = size(v1,4); if nd>1 l1 = size(v1,1); vv = zeros(l1*nd,nf1); for h = 1:nd vv((h-1)*l1+1:h*l1,:) = v1(:,:,1,h); end v1 = vv; l2 = size(v2,1); vv = zeros(l2*nd,nf2); for h = 1:nd vv((h-1)*l2+1:h*l2,:) = v2(:,:,1,h); end v2 = vv; clear vv end d = zeros(nf1,nf2); disf = str2func(option.distance); if strcmpi(option.distance,'cosine') for i = 1:nf1 v1(:,i) = v1(:,i)/norm(v1(:,i)); end for i = 1:nf2 v2(:,i) = v2(:,i)/norm(v2(:,i)); end end for i = 1:nf1 %if mirwaitbar && (mod(i,100) == 1 || i == nf1) % waitbar(i/nf1,handle); %end d(i,:) = disf(v1(:,i),v2); end d = {{d}}; m.diagwidth = NaN; m.view = 's'; m.half = 0; m.similarity = 0; m.graph = {}; m.branch = {}; m.warp = []; m.clusters = []; m = class(m,'mirsimatrix',mirdata(orig)); m = purgedata(m); m = set(m,'Title','Dissimilarity matrix','Data',d,'Pos',[],... 'Name',{n1{1},n2{1}},'FramePos',{fp1{1},fp2{1}}); end lK = option.K; if not(isempty(postoption)) if strcmpi(m.view,'s') && isempty(option.arg2) if strcmpi(postoption.view,'Horizontal') for k = 1:length(d) for z = 1:length(d{k}) d{k}{z} = rotatesim(d{k}{z},m.diagwidth); if lK < m.diagwidth W = size(d{k}{z},1); hW = ceil(W/2); hK = floor(lK/2); d{k}{z} = d{k}{z}(hW-hK:hW+hK,:); m.diagwidth = lK; end end end m = set(m,'Data',d); m.view = 'h'; elseif strcmpi(postoption.view,'TimeLag') for k = 1:length(d) for z = 1:length(d{k}) if isinf(m.diagwidth) if option.half nlines = size(d{k}{z},1); half = floor(size(d{k}{z},1)/2); else nlines = 2*size(d{k}{z},1)-1; half = size(d{k}{z},1); end else nlines = m.diagwidth; half = (m.diagwidth+1)/2; end dz = NaN(nlines,size(d{k}{z},2)); if option.half for l = 1:nlines dz(l,l:end) = diag(d{k}{z},l-1)'; end else for l = 1:nlines dia = abs(half-l); if l<half dz(l,1:end-dia) = diag(d{k}{z},dia)'; else dz(l,dia+1:end) = diag(d{k}{z},dia)'; end end if lK < m.diagwidth nlines2 = floor(lK/2); if size(dz,1)>lK dz = dz(half-nlines2:half+nlines2,:); end m.diagwidth = lK; end end d{k}{z}= dz; end end m = set(m,'Data',d); m.view = 'l'; end end if strcmpi(m.view,'l') && ~m.half && option.half for k = 1:length(d) for z = 1:length(d{k}) for l = 1:size(d{k}{z},1) dz(l,1:l-1) = NaN; end d{k}{z}= dz; end end end if ischar(postoption.simf) if strcmpi(postoption.simf,'Similarity') if not(isequal(m.similarity,NaN)) option.dissim = 0; end postoption.simf = 'oneminus'; end if isequal(m.similarity,0) && isstruct(option) ... && isfield(option,'dissim') && not(option.dissim) simf = str2func(postoption.simf); for k = 1:length(d) for z = 1:length(d{k}) d{k}{z} = simf(d{k}{z}); end end m.similarity = postoption.simf; m = set(m,'Title','Similarity matrix','Data',d); elseif length(m.similarity) == 1 && isnan(m.similarity) ... && option.dissim m.similarity = 0; end end if postoption.filt fp = get(m,'FramePos'); for k = 1:length(d) for z = 1:length(d{k}) dz = filter(ones(postoption.filt,1),1,d{k}{z}')'; if option.half d{k}{z} = dz(1:end-postoption.filt,... postoption.filt+1:end); fp{k}{z} = [fp{k}{z}(1,1:end-postoption.filt);... fp{k}{z}(2,postoption.filt+1:end)]; else d{k}{z} = dz(1+ceil(postoption.filt/2):... end-floor(postoption.filt/2),... postoption.filt+1:end); fp{k}{z} = [fp{k}{z}(1,1:end-postoption.filt);... fp{k}{z}(2,postoption.filt+1:end)]; end end end m = set(m,'Data',d,'FramePos',fp); end if postoption.warp dz = 1 - (d{1}{1} - min(min(d{1}{1}))) ... / (max(max(d{1}{1})) - min(min(d{1}{1}))); paths = cell(size(dz)+1); bests = sparse(size(dz,1),size(dz,2)); bestsindex = sparse(size(dz,1),size(dz,2)); for i = 1:size(dz,1) if ~mod(i,100) i/size(dz,1) end for j = 1:size(dz,2) if dz(i,j) > postoption.warp continue end ending = [i; j]; [newpaths bests bestsindex] = ... addpaths({},paths{i,j},ending,dz(i,j),... bests,bestsindex,paths,1); [newpaths bests bestsindex] = ... addpaths(newpaths,paths{i+1,j},ending,dz(i,j),... bests,bestsindex,paths,0); [newpaths bests bestsindex] = ... addpaths(newpaths,paths{i,j+1},ending,dz(i,j),... bests,bestsindex,paths,0); if isempty(newpaths) && (i == 1 || j == 1 || ... (dz(i-1,j-1)> postoption.warp && ... dz(i-1,j)> postoption.warp && ... dz(i,j-1)> postoption.warp)) newpaths = {[ending; 0]}; end paths{i+1,j+1} = newpaths; end end m = set(m,'Warp',{paths,bests,bestsindex}); end if postoption.cluster % && isempty(get(orig,'Clusters')) clus = cell(1,length(d)); for k = 1:length(d) clus{k} = cell(1,length(d{k})); for z = 1:length(d{k}) dz = d{k}{z}; l = size(dz,1); sim = NaN(l); for i = 2:l-1 for j = 1:l-i-1 in = dz(i:i+j,i:i+j); homg = mean(in(:))-std(in(:)); out = [dz(i:i+j,i-1),dz(i:i+j,i+j+1)]; halo = mean(out(:)) - std(out(:)); if homg > .7 && homg-halo>.01 sim(i,j) = homg; if j>1 && ~isnan(sim(i,j-1)) && ... sim(i,j-1)-sim(i,j) < .01 sim(i,j-1) = NaN; end if i>1 && j<l-i-1 && ... ~isnan(sim(i-1,j+1)) && ... sim(i,j)-sim(i-1,j+1) < .01 sim(i-1,j+1) = NaN; end if i>1 && ~isnan(sim(i-1,j)) if abs(sim(i-1,j)-sim(i,j)) < .01 sim(i-1,j) = NaN; sim(i,j) = NaN; elseif sim(i-1,j) > sim(i,j) sim(i,j) = NaN; else sim(i-1,j) = NaN; end end end end end clus{k}{z} = sim; end end m = set(m,'Clusters',clus); end end function [newpaths bests bestsindex] = addpaths(newpaths,oldpaths,ending,d,... bests,bestsindex,paths,diag) for k = 1:length(oldpaths) % For each path if oldpaths{k}(3,end)<10 && d>.33 continue end found_redundant = 0; for l = 1:length(newpaths) if (newpaths{l}(1,1) - oldpaths{k}(1,1)) * ... (newpaths{l}(2,1) - oldpaths{k}(2,1)) >= 0 % Redundant paths. One is removed. found_redundant = 1; if oldpaths{k}(1,1) < newpaths{l}(1,1) % The new candidate is actually better. % The path stored in newpaths is modified. newpaths{l} = [oldpaths{k} ... [ending; oldpaths{k}(3,end)+diag]]; if bests(newpaths{l}(1,1),newpaths{l}(2,1)) ... == ending(1)+1i*ending(2) bests(newpaths{l}(1,1),newpaths{l}(2,1)) = 0; end [bests bestsindex] = update(bests,bestsindex,... oldpaths{k}(1:2,1),... ending(1:2),l,... paths,newpaths); end else % Each of the 2 paths explores more one particular dimension % upfront. No path should be removed. % + % --+ % - | % | % | if oldpaths{k}(1,1) < newpaths{l}(1,1) if bests(oldpaths{k}(1,1),oldpaths{k}(2,1))... == ending(1)+1i*ending(2) bests(oldpaths{k}(1,1),oldpaths{k}(2,1)) = 0; end else if bests(newpaths{l}(1,1),newpaths{l}(2,1))... == ending(1)+1i*ending(2) bests(newpaths{l}(1,1),newpaths{l}(2,1)) = 0; end end end end if ~found_redundant newpaths{end+1} = [oldpaths{k} ... [ending; oldpaths{k}(3,end)+diag]]; [bests bestsindex] = update(bests,bestsindex,... oldpaths{k}(1:2,1),... ending(1:2),length(newpaths),... paths,newpaths); end end function [bests bestsindex] = update(bests,bestsindex,starts,ends,... pathindex,paths,newpaths) key = ends(1)+1i*ends(2); [i,j,v] = find(bests); k = find(v == key); if ~isempty(k) bests(i(k),j(k)) = 0; end previous = bests(starts(1),starts(2)); previndex = bestsindex(starts(1),starts(2)); replace = 0; if previous == 0 replace = 1; else newscore = newpaths{pathindex}(3,end-1); oldscore = paths{real(previous)+1,imag(previous)+1}{previndex}(3,end); if newscore > oldscore replace = 1; elseif newscore == oldscore paths{real(previous)+1,imag(previous)+1}{previndex}; newpaths{pathindex}; end end if replace bests(starts(1),starts(2)) = key; bestsindex(starts(1),starts(2)) = pathindex; end function S = rotatesim(d,K) if length(d) == 1; S = d; else K = min(K,size(d,1)*2+1); lK = floor(K/2); S = NaN(K,size(d,2),size(d,3)); for k = 1:size(d,3) for j = -lK:lK S(lK+j+1,:,k) = [NaN(1,floor(abs(j)/2)) diag(d(:,:,k),j)' ... NaN(1,ceil(abs(j)/2))]; end end end function d = cosine(r,s) d = 1-r'*s; function d = KL(x,y) % Kullback-Leibler distance if size(x,4)>1 x(end+1:2*end,:,:,1) = x(:,:,:,2); x(:,:,:,2) = []; end if size(y,4)>1 y(end+1:2*end,:,:,1) = y(:,:,:,2); y(:,:,:,2) = []; end m1 = mean(x); m2 = mean(y); S1 = cov(x); S2 = cov(y); d = (trace(S1/S2)+trace(S2/S1)+(m1-m2)'*inv(S1+S2)*(m1-m2))/2 - size(S1,1); function s = exponential(d) s = (exp(-d) - exp(-1)) / (1-exp(-1)); function s = oneminus(d) s = 1-d;
github
martinarielhartmann/mirtooloct-master
mirautocor.m
.m
mirtooloct-master/MIRToolbox/@mirautocor/mirautocor.m
25,732
utf_8
738d1a46a0baaa7a8a3825ebbe1bda84
function varargout = mirautocor(orig,varargin) % a = mirautocor(x) computes the autocorrelation function related to x. % Optional parameters: % mirautocor(...,'Min',mi) indicates the lowest delay taken into % consideration. The unit can be precised: % mirautocor(...,'Min',mi,'s') (default unit) % mirautocor(...,'Min',mi,'Hz') % Default value: 0 s. % mirautocor(...,'Max',ma) indicates the highest delay taken into % consideration. The unit can be specified as for 'Min'. % Default value: % if x is a signal, the highest delay is 0.05 s % (corresponding to a minimum frequency of 20 Hz). % if x is an envelope, the highest delay is 2 s. % mirautocor(...,'Resonance',r) multiplies the autocorrelation function % with a resonance curve: % Possible values: % 'Toiviainen' from (Toiviainen & Snyder, 2003) % 'vanNoorden' from (van Noorden & Moelants, 2001) % mirautocor(...,'Center',c) assigns the center value of the % resonance curve, in seconds. % Works mainly with 'Toiviainen' option. % Default value: c = 0.5 % mirautocor(...,'Enhanced',a) reduces the effect of subharmonics. % The original autocorrelation function is half-wave rectified, % time-scaled by the factor a (which can be a factor list as % well), and substracted from the original clipped function. % (Tolonen & Karjalainen) % If the 'Enhanced' option is not followed by any value, % default value is a = 2:10 % mirautocor(...,'Halfwave') performs a half-wave rectification on the % result. % mirautocor(...,'Freq') represents the autocorrelation function in the % frequency domain. % mirautocor(...,'NormalWindow',w): applies a window to the input % signal and divides the autocorrelation by the autocorrelation of % that window (Boersma 1993). % Possible values: any windowing function proposed in the Signal % Processing Toolbox (help window) plus 'rectangle' (no % windowing) % Default value: w = 'hanning' % mirautocor(...,'NormalWindow',0): toggles off this normalization % (which is on by default). % All the parameters described previously can be applied to an % autocorrelation function itself, in order to arrange the results % after the actual computation of the autocorrelation computations. % For instance: a = mirautocor(a,'Resonance','Enhanced') % Other optional parameter: % mirautocor(...,'Compres',k) computes the autocorrelation in the % frequency domain and includes a magnitude compression of the % spectral representation. A normal autocorrelation corresponds % to the value k=2, but values lower than 2 are suggested by % (Tolonen & Karjalainen, 2000). % Default value: k = 0.67 % mirautocor(...,'Normal',n) or simply mirautocor(...,n) specifies % the normalization strategy. Accepted values are 'biased', % 'unbiased', 'coeff' (default value) and 'none'. % See help xcorr for an explanation. min.key = 'Min'; min.type = 'Integer'; min.unit = {'s','Hz'}; if isamir(orig,'mirspectrum') min.defaultunit = 'Hz'; else min.defaultunit = 's'; end min.default = 0; min.opposite = 'max'; option.min = min; max.key = 'Max'; max.type = 'Integer'; max.unit = {'s','Hz'}; if isamir(orig,'mirspectrum') max.defaultunit = 'Hz'; else max.defaultunit = 's'; end if isamir(orig,'mirenvelope') || isamir(orig,'mirdiffenvelope') max.default = 2; % for envelopes, longest period: 2 seconds. elseif isamir(orig,'miraudio') || ischar(orig) % for audio signal,lowest frequency: 20 Hz. max.default = 1/20; else max.default = Inf; end max.opposite = 'min'; option.max = max; xtend.key = {'Extend','Extended'}; xtend.type = 'Boolean'; xtend.default = 0; option.xtend = xtend; scaleoptbw.key = 'Normal'; %'Normal' keyword optional scaleoptbw.key = 'Boolean'; option.scaleoptbw = scaleoptbw; scaleopt.type = 'String'; scaleopt.choice = {'biased','unbiased','coeff','none'}; scaleopt.default = 'coeff'; option.scaleopt = scaleopt; gener.key = {'Generalized','Compres'}; gener.type = 'Integer'; gener.default = 2; gener.keydefault = .67; option.gener = gener; ni.key = 'NormalInput'; %% Normalize before frame or chunk?? ni.type = 'Boolean'; ni.default = 0; option.ni = ni; reso.key = 'Resonance'; reso.type = 'String'; reso.choice = {'ToiviainenSnyder','Toiviainen','vanNoorden','no','off',0}; reso.keydefault = 'Toiviainen'; reso.when = 'After'; reso.default = 0; option.reso = reso; resocenter.key = {'Center','Centre'}; resocenter.type = 'Integer'; resocenter.when = 'After'; option.resocenter = resocenter; h.key = 'Halfwave'; h.type = 'Boolean'; h.when = 'After'; h.default = 0; option.h = h; e.key = 'Enhanced'; e.type = 'Integers'; e.default = []; e.keydefault = 2:10; e.when = 'After'; option.e = e; fr.key = 'Freq'; fr.type = 'Boolean'; fr.default = 0; fr.when = 'After'; option.fr = fr; nw.key = 'NormalWindow'; nw.when = 'Both'; if isamir(orig,'mirspectrum') nw.default = 0; elseif isamir(orig,'mirenvelope') nw.default = 'rectangular'; else nw.default = 'hanning'; end option.nw = nw; win.key = 'Window'; win.type = 'String'; win.default = NaN; option.win = win; phase.key = 'Phase'; phase.type = 'Boolean'; phase.when = 'Both'; phase.default = 0; option.phase = phase; specif.option = option; specif.defaultframelength = 0.05; specif.defaultframehop = 0.5; specif.eachchunk = @eachchunk; specif.combinechunk = @combinechunk; if isamir(orig,'mirscalar') || isamir(orig,'mirenvelope') specif.nochunk = 1; end varargout = mirfunction(@mirautocor,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = 'mirautocor'; function a = main(orig,option,postoption) if iscell(orig) orig = orig{1}; end if isa(orig,'mirautocor') a = orig; if not(isempty(option)) && ... (option.min || iscell(option.max) || option.max < Inf) coeff = get(a,'Coeff'); delay = get(a,'Delay'); for h = 1:length(coeff) if a.freq mi = 1/option.max; ma = 1/option.min; else mi = option.min; ma = option.max; end for k = 1:length(coeff{h}) range = find(and(delay{h}{k}(:,1,1) >= mi,... delay{h}{k}(:,1,1) <= ma)); coeff{h}{k} = coeff{h}{k}(range,:,:); delay{h}{k} = delay{h}{k}(range,:,:); end end a = set(a,'Coeff',coeff,'Delay',delay); end if not(isempty(postoption)) && not(isequal(postoption,0)) a = post(a,postoption); end elseif ischar(orig) a = mirautocor(miraudio(orig),option,postoption); else if nargin == 0 orig = []; end a.freq = 0; a.ofspectrum = 0; a.window = {}; a.normalwindow = 0; a.resonance = ''; a.input = []; a.phase = {}; a = class(a,'mirautocor',mirdata(orig)); a = purgedata(a); a = set(a,'Ord','coefficients'); sig = get(orig,'Data'); if isa(orig,'mirspectrum') a = set(a,'Title','Spectrum autocorrelation','OfSpectrum',1,... 'Abs','frequency (Hz)'); pos = get(orig,'Pos'); else if isa(orig,'mirscalar') a = set(a,'Title',[get(orig,'Title') ' autocorrelation']); pos = get(orig,'FramePos'); for k = 1:length(sig) for l = 1:length(sig{k}) sig{k}{l} = sig{k}{l}'; pos{k}{l} = pos{k}{l}(1,:,:)'; end end else if isa(orig,'mirenvelope') a = set(a,'Title','Envelope autocorrelation'); elseif not(isa(orig,'mirautocor')) a = set(a,'Title','Waveform autocorrelation'); end pos = get(orig,'Pos'); end a = set(a,'Abs','lag (s)'); end f = get(orig,'Sampling'); if isnan(option.win) if isequal(option.nw,0) || ... strcmpi(option.nw,'Off') || strcmpi(option.nw,'No') option.win = 0; elseif isequal(option.nw,1) || strcmpi(option.nw,'On') || ... strcmpi(option.nw,'Yes') option.win = 'hanning'; else option.win = option.nw; end end coeff = cell(1,length(sig)); lags = cell(1,length(sig)); wind = cell(1,length(sig)); for k = 1:length(sig) s = sig{k}; p = pos{k}; fk = f{k}; if iscell(option.max) mi = option.min{k}; ma = option.max{k}; else mi = option.min; ma = option.max; end coeffk = cell(1,length(s)); lagsk = cell(1,length(s)); windk = cell(1,length(s)); for l = 1:length(s) sl = s{l}; sl(isnan(sl)) = 0; if option.ni mxsl = repmat(max(sl),[size(sl,1),1,1]); mnsl = repmat(min(sl),[size(sl,1),1,1]); sl = (sl-mnsl)./(mxsl-mnsl); end pl = p{l}; pl = pl-repmat(pl(1,:,:),[size(pl,1),1,1]); ls = size(sl,1); if mi misp = find(pl(:,1,1)>=mi,1); if isempty(misp) warning('WARNING IN MIRAUTOCOR: The specified range of delays exceeds the temporal length of the signal.'); disp('Minimum delay set to zero.') misp = 1; % misp is the lowest index of the lag range mi = 0; end else misp = 1; end if ma masp = find(pl(:,1,1)>=ma,1); if isempty(masp) masp = Inf; end else masp = Inf; end if option.xtend masp = min(masp,ls); else masp = min(masp,ceil(ls/2)); end if masp <= misp if size(sl,2) > 1 warning('WARNING IN MIRAUTOCOR: Frame length is too small.'); else warning('WARNING IN MIRAUTOCOR: The audio sequence is too small.'); end display('The autocorrelation is not defined for this range of delays.'); end sl = center(sl); if not(ischar(option.win)) || strcmpi(option.win,'Rectangular') kw = ones(size(sl)); else N = size(sl,1); winf = str2func(option.win); try w = window(winf,N); catch if strcmpi(option.win,'hamming') disp('Signal Processing Toolbox does not seem to be installed. Recompute the hamming window manually.'); w = 0.54 - 0.46 * cos(2*pi*(0:N-1)'/(N-1)); else warning(['WARNING in MIRAUTOCOR: Unknown windowing function ',option.win,' (maybe Signal Processing Toolbox is not installed).']); disp('No windowing performed.') w = ones(size(sl,1),1); end end kw = repmat(w,[1,size(sl,2),size(sl,3)]); sl = sl.* kw; end if strcmpi(option.scaleopt,'coeff') scaleopt = 'none'; else scaleopt = option.scaleopt; end c = zeros(masp,size(sl,2),size(sl,3)); for i = 1:size(sl,2) for j = 1:size(sl,3) if option.gener == 2 cc = xcorr(sl(:,i,j),masp-1,scaleopt); c(:,i,j) = cc(masp:end); else ss = abs(fft(sl(:,i,j))); ss = ss.^option.gener; cc = ifft(ss); ll = (0:masp-1); c(:,i,j) = cc(ll+1); end end if strcmpi(option.scaleopt,'coeff') && option.gener == 2 % to be adapted to generalized autocor xc = xcorr(sum(sl(:,i,:),3),0); if xc c(:,i,:) = c(:,i,:)/xc; % This is a kind of generalization of the 'coeff' % normalization for multi-channels signals. In the % original 'coeff' option, the autocorrelation at zero % lag is identically 1.0. In this multi-channels % version, the autocorrelation at zero lag is such that % the sum over channels becomes identically 1.0. end end end coeffk{l} = c(misp:end,:,:); pl = pl(misp:end,:,:); lagsk{l} = pl(1:min(size(coeffk{l},1),size(pl,1)),:,:); windk{l} = kw; end coeff{k} = coeffk; lags{k} = lagsk; wind{k} = windk; end a = set(a,'Coeff',coeff,'Delay',lags,'Window',wind); if option.phase a = set(a,'Input',orig); end if not(isempty(postoption)) a = post(a,postoption); end end function a = post(a,option) debug = 0; coeff = get(a,'Coeff'); lags = get(a,'Delay'); wind = get(a,'Window'); freq = option.fr && not(get(a,'FreqDomain')); if isequal(option.e,1) option.e = 2:10; end if max(option.e) > 1 pa = mirpeaks(a,'NoBegin','NoEnd','Contrast',.01,'Normalize','Local'); va = mirpeaks(a,'Valleys','Contrast',.01,'Normalize','Local'); pv = get(pa,'PeakVal'); vv = get(va,'PeakVal'); end if option.phase x = get(a,'Input'); d = get(x,'Data'); pk = get(a,'PeakPos'); sr = get(a,'Sampling'); phas = cell(1,length(coeff)); end for k = 1:length(coeff) if option.phase phask = cell(1,length(coeff{k})); end for l = 1:length(coeff{k}) c = coeff{k}{l}; % Coefficients of autocorrelation t = lags{k}{l}; % Delays of autocorrelation if not(isempty(c)) if not(isequal(option.nw,0) || strcmpi(option.nw,'No') || ... strcmpi(option.nw,'Off') || a.normalwindow) % 'NormalWindow' option xw = zeros(size(c)); lc = size(c,1); for j = 1:size(c,3) for i = 1:size(c,2) xwij = xcorr(wind{k}{l}(:,i,j),lc,'coeff'); xw(:,i,j) = xwij(lc+2:end); end end c = c./ xw; a.normalwindow = 1; end if ischar(option.reso) && isempty(a.resonance) && ... (strcmpi(option.reso,'ToiviainenSnyder') || ... strcmpi(option.reso,'Toiviainen') || ... strcmpi(option.reso,'vanNoorden')) if isa(a,'mirautocor') && get(a,'FreqDomain') ll = 1./t; else ll = t; end if not(option.resocenter) option.resocenter = .5; end if strcmpi(option.reso,'ToiviainenSnyder') || ... strcmpi(option.reso,'Toiviainen') w = max(1 - 0.25*(log2(max(ll,1e-12)/option.resocenter)).^2, 0); elseif strcmpi(option.reso,'vanNoorden') f0=2.193; b=option.resocenter; f=1./ll; a1=(f0*f0-f.*f).^2+b*f.^2; a2=f0^4+f.^4; w=(1./sqrt(a1))-(1./sqrt(a2)); end if max(w) == 0 warning('The resonance curve, not defined for this range of delays, will not be applied.') else w = w/max(w); c = c.* repmat(w,[1,size(c,2),size(c,3)]); end a.resonance = option.reso; end if option.h c = hwr(c); end if max(option.e) > 1 if a.freq freq = 1; for i = 1:size(c,3) c(:,:,i) = flipud(c(:,:,i)); end t = flipud(1./t); end for g = 1:size(c,2) for h = 1:size(c,3) cgh = c(:,g,h); if length(cgh)>1 pvk = pv{k}{l}{1,g,h}; mv = []; if not(isempty(pvk)) mp = min(pvk); %Lowest peak vvv = vv{k}{l}{1,g,h}; %Valleys mv = vvv(find(vvv<mp,1,'last')); %Highest valley below the lowest peak if not(isempty(mv)) cgh = cgh-mv; end end cgh2 = cgh; tgh2 = t(:,g,1); coef = cgh(2)-cgh(1); % initial slope of the autocor curve tcoef = tgh2(2)-tgh2(1); deter = 0; inter = 0; repet = find(not(diff(tgh2))); % Avoid bug if repeated x-values if repet warning('WARNING in MIRAUTOCOR: Two successive samples have exactly same temporal position.'); tgh2(repet+1) = tgh2(repet)+1e-12; end if coef < 0 % initial descending slope removed deter = find(diff(cgh2)>0,1)-1; % number of removed points if isempty(deter) deter = 0; end cgh2(1:deter) = []; tgh2(1:deter) = []; coef = cgh2(2)-cgh2(1); end if coef > 0 % initial ascending slope prolonged to the left % until it reaches the x-axis while cgh2(1) > 0 coef = coef*1.1; % the further to the left, ... % the more ascending is the slope % (not sure it always works, though...) inter = inter+1; % number of added points cgh2 = [cgh2(1)-coef; cgh2]; tgh2 = [tgh2(1)-tcoef; tgh2]; end cgh2(1) = 0; end for i = option.e % Enhancing procedure % option.e is the list of scaling factors % i is the scaling factor if i be = find(tgh2 & tgh2/i >= tgh2(1),1); % starting point of the substraction % on the X-axis if not(isempty(be)) ic = interp1(tgh2,cgh2,tgh2/i); % The scaled autocorrelation ic(1:be-1) = 0; ic(find(isnan(ic))) = Inf; % All the NaN values are changed % into 0 in the resulting curve ic = max(ic,0); if debug hold off,plot(tgh2,cgh2) end cgh2 = cgh2 - ic; % The scaled autocorrelation % is substracted to the initial one cgh2 = max(cgh2,0); % Half-wave rectification if debug hold on,plot(tgh2,ic,'r') hold on,plot(tgh2,cgh2,'g') drawnow figure end end end end if 0 %~isempty(mv) cgh2 = max(cgh2 + mv,0); end % The temporary modifications are % removed from the final curve if inter>=deter c(:,g,h) = cgh2(inter-deter+1:end); if not(isempty(mv)) c(:,g,h) = c(:,g,h) + mv; end else c(:,g,h) = [zeros(deter-inter,1);cgh2]; end end end end end if option.phase ph = cell(1,size(d{k}{l},2),size(d{k}{l},3)); for i = 1:size(ph,2) for j = 1:size(ph,3) if ~isempty(pk{k}{l}) option.phase = 2; pkj = pk{k}{l}{1,i,j}; phj = zeros(1,length(pkj)); for h = 1:length(pkj) lag = round(t(pkj(h))*sr{k}); if ~lag continue end pha = zeros(1,lag); for g = 1:lag pha(g) = sum(d{k}{l}(g:lag:end,i,j)); end [unused phj(h)] = max(pha); end ph{1,i,j} = phj; end end end phask{l} = ph; end if freq if t(1,1) == 0 c = c(2:end,:,:); t = t(2:end,:,:); end for i = 1:size(c,3) c(:,:,i) = flipud(c(:,:,i)); end t = flipud(1./t); end coeff{k}{l} = c; lags{k}{l} = t; if 0 %option.ph for g = 1:size(p{k}{l},2) for i = 1:length(p{k}{l}{1,g}) if t(1) error('check here'); end indx = p{k}{l}{1,g}(i); end end end end end if option.phase phas{k} = phask; end end a = set(a,'Coeff',coeff,'Delay',lags,'Freq'); if freq a = set(a,'FreqDomain',1,'Abs','frequency (Hz)'); end if option.phase == 2 a = set(a,'Phase',phas); end function [y orig] = eachchunk(orig,option,missing,postchunk) option.scaleopt = 'none'; y = mirautocor(orig,option); function y = combinechunk(old,new) doo = get(old,'Data'); doo = doo{1}{1}; dn = get(new,'Data'); dn = dn{1}{1}; if abs(size(dn,1)-size(doo,1)) <= 2 % Probleme of border fluctuation mi = min(size(dn,1),size(doo,1)); dn = dn(1:mi,:,:); doo = doo(1:mi,:,:); po = get(old,'Pos'); po{1}{1} = po{1}{1}(1:mi,:,:); old = set(old,'Pos',po); elseif length(dn) < length(doo) dn(length(doo),:,:) = 0; % Zero-padding end y = set(old,'ChunkData',doo+dn);
github
martinarielhartmann/mirtooloct-master
combine.m
.m
mirtooloct-master/MIRToolbox/@mirdata/combine.m
3,357
utf_8
501ac7884a5a69e4c2961e5522b546a1
function c = combine(varargin) c = varargin{1}; l = length(varargin); p = cell(1,l); ch = cell(1,l); d = cell(1,l); fp = cell(1,l); fr = cell(1,l); sr = cell(1,l); n = cell(1,l); la = cell(1,l); le = cell(1,l); cl = cell(1,l); pp = cell(1,l); pm = cell(1,l); pv = cell(1,l); ppp = cell(1,l); ppv = cell(1,l); tp = cell(1,l); tv = cell(1,l); tpp = cell(1,l); tpv = cell(1,l); ap = cell(1,l); rp = cell(1,l); if isa(c,'temporal') nb = cell(1,l); end if isa(c,'mirscalar') m = cell(1,l); if isa(c,'mirpitch') pa = cell(1,l); ps = cell(1,l); pe = cell(1,l); pi = cell(1,l); pd = cell(1,l); end end if isa(c,'miremotion') dd = cell(1,l); cd = cell(1,l); end if isa(c,'mirmetre') ac = cell(1,l); g = cell(1,l); end for i = 1:l argin = varargin{i}; p{i} = getargin(argin,'Pos'); ch{i} = getargin(argin,'Channels'); d{i} = getargin(argin,'Data'); fp{i} = getargin(argin,'FramePos'); fr{i} = getargin(argin,'FrameRate'); sr{i} = getargin(argin,'Sampling'); nb{i} = getargin(argin,'NBits'); n{i} = getargin(argin,'Name'); la{i} = getargin(argin,'Label'); le{i} = getargin(argin,'Length'); cl{i} = getargin(argin,'Clusters'); pp{i} = getargin(argin,'PeakPos'); pm{i} = getargin(argin,'PeakMode'); pv{i} = getargin(argin,'PeakVal'); ppp{i} = getargin(argin,'PeakPrecisePos'); ppv{i} = getargin(argin,'PeakPreciseVal'); tp{i} = getargin(argin,'TrackPos'); tv{i} = getargin(argin,'TrackVal'); tpp{i} = getargin(argin,'TrackPrecisePos'); tpv{i} = getargin(argin,'TrackPreciseVal'); ap{i} = getargin(argin,'AttackPos'); rp{i} = getargin(argin,'ReleasePos'); if isa(c,'temporal') ct = getargin(argin,'Centered'); nb{i} = getargin(argin,'NBits'); end if isa(c,'mirscalar') m{i} = getargin(argin,'Mode'); if isa(c,'mirpitch') pa{i} = getargin(argin,'Amplitude'); ps{i} = getargin(argin,'Start'); pe{i} = getargin(argin,'End'); pi{i} = getargin(argin,'Mean'); pd{i} = getargin(argin,'Degrees'); end end if isa(c,'miremotion') dd{i} = getargin(argin,'DimData'); cd{i} = getargin(argin,'ClassData'); end if isa(c,'mirmetre') ac{i} = getargin(argin,'Autocor'); g{i} = getargin(argin,'Globpm'); end end c = set(c,'Pos',p,'Data',d,'FramePos',fp,'FrameRate',fr,'Channels',ch,... 'Sampling',sr,'NBits',nb,'Name',n,'Label',la,'Length',le,... 'Clusters',cl,'PeakPos',pp,'PeakMode',pm,'PeakVal',pv,... 'PeakPrecisePos',ppp,'PeakPreciseVal',ppv,... 'TrackPos',tp,'TrackVal',tv,... 'TrackPrecisePos',tpp,'TrackPreciseVal',tpv,... 'AttackPos',ap,'ReleasePos',rp); if isa(c,'temporal') c = set(c,'Centered',ct,'NBits',nb); end if isa(c,'mirscalar') c = set(c,'Mode',m); if isa(c,'mirpitch') c = set(c,'Amplitude',pa,'Start',ps,'End',pe,'Mean',pi,... 'Degrees',pd); end end if isa(c,'miremotion') c = set(c,'DimData',dd,'ClassData',cd); end if isa(c,'mirmetre') c = set(c,'Autocor',ac,'Globpm',g); end function y = getargin(argin,field) yi = get(argin,field); if isempty(yi) || ischar(yi) || ~iscell(yi) y = yi; else y = yi{1}; end
github
martinarielhartmann/mirtooloct-master
miraudio.m
.m
mirtooloct-master/MIRToolbox/@miraudio/miraudio.m
13,358
utf_8
6e9885c23f30543534bc72a8250a76cb
function varargout = miraudio(orig,varargin) % a = miraudio('filename') loads the sound file 'filename' (in WAV or AU % format) into a miraudio object. % a = miraudio('Folder') loads all the sound files in the CURRENT folder % into a miraudio object. % a = miraudio(v,sr), where v is a column vector, translates the vector v % into a miraudio object. The sampling frequency is set to sr Hertz. % Default value for sr: 44100 Hz. % a = miraudio(b, ...), where b is already a miraudio object, performs % operations on b specified by the optional arguments (see below). % % Transformation options: % miraudio(...,'Mono',0) does not perform the default summing of % channels into one single mono track, but instead stores each % channel of the initial soundfile separately. % miraudio(...,'Center') centers the signals. % miraudio(...,'Sampling',r) resamples at sampling rate r (in Hz). % (Requires the Signal Processing Toolbox.) % miraudio(...,'Normal') normalizes with respect to RMS energy. % Extraction options: % miraudio(...,'Extract',t1,t2,u,f) extracts the signal between dates % t1 and t2, expressed in the unit u. % Possible values for u: % 's' (seconds, by default), % 'sp' (sample index, starting from 1). % The additional optional argument f indicates the referential % origin of the temporal positions. Possible values for f: % 'Start' (by default) % 'Middle' (of the sequence) % 'End' of the sequence % When using 'Middle' or 'End', negative values for t1 or t2 % indicate values before the middle or the end of the audio % sequence. % miraudio(...,'Trim') trims the pseudo-silence beginning and end off % the audio file. Silent frames are frames with RMS below t times % the medium RMS of the whole audio file. % Default value: t = 0.06 % instead of 'Trim': % 'TrimStart' only trims the beginning of the audio file, % 'TrimEnd' only trims the end. % miraudio(...,'TrimThreshold',t) specifies the trimming threshold t. % miraudio(...,'Channel',c) or miraudio(...,'Channels',c) selects the % channels indicated by the (array of) integer(s) c. % Labeling option: % miraudio(...,'Label',l) labels the audio signal(s) following the % label(s) l. % If l is a (series of) number(s), the audio signal(s) are % labelled using the substring of their respective file name of % index l. If l=0, the audio signal(s) are labelled using the % whole file name. % MP3 behave badly! if isempty(orig) varargout = {{}}; return end if isnumeric(orig) if size(orig,2) > 1 || size(orig,3) > 1 mirerror('MIRAUDIO','Only column vectors can be imported into mirtoolbox.'); end if nargin == 1 f = 44100; else f = varargin{1}; end b = 32; if size(orig,1) == 1 orig = orig'; end tp = (0:size(orig,1)-1)'/f; l = (size(orig,1)-1); %/f; t = mirtemporal([],'Time',{{tp}},'Data',{{orig}},'Length',{{l}},... 'FramePos',{{tp([1 end])}},'Sampling',{f},... 'Name',{inputname(1)},'Label',{{}},'Clusters',{{}},... 'Channels',[],'Centered',0,'NBits',{b},... 'Title','Audio signal',... 'PeakPos',{{{}}},'PeakVal',{{{}}},'PeakMode',{{{}}}); aa.fresh = 1; aa.extracted = 0; varargout = {class(aa,'miraudio',t)}; return end center.key = 'Center'; center.type = 'Boolean'; center.default = 0; center.when = 'After'; option.center = center; normal.key = 'Normal'; normal.type = 'Boolean'; normal.default = 0; normal.when = 'After'; option.normal = normal; extract.key = {'Extract','Excerpt'}; extract.type = 'Integer'; extract.number = 2; extract.default = []; extract.unit = {'s','sp'}; extract.defaultunit = 's'; extract.from = {'Start','Middle','End'}; extract.defaultfrom = 'Start'; option.extract = extract; trim.type = 'String'; trim.choice = {'NoTrim','Trim','TrimBegin','TrimStart','TrimEnd'}; trim.default = 'NoTrim'; trim.when = 'After'; option.trim = trim; trimthreshold.key = 'TrimThreshold'; trimthreshold.type = 'Integer'; trimthreshold.default = .06; trimthreshold.when = 'After'; option.trimthreshold = trimthreshold; label.key = 'Label'; label.default = ''; label.when = 'After'; option.label = label; sampling.key = 'Sampling'; sampling.type = 'Integer'; sampling.default = 0; sampling.when = 'Both'; option.sampling = sampling; % segment.key = 'Segment'; % segment.type = 'Integer'; % segment.default = []; % segment.when = 'After'; % option.segment = segment; reverse.key = 'Reverse'; reverse.type = 'Boolean'; reverse.default = 0; reverse.when = 'After'; option.reverse = reverse; mono.key = 'Mono'; mono.type = 'Boolean'; mono.default = NaN; mono.when = 'After'; option.mono = mono; separate.key = 'SeparateChannels'; separate.type = 'Boolean'; separate.default = 0; option.separate = separate; Ch.key = {'Channel','Channels'}; Ch.type = 'Integer'; Ch.default = []; Ch.when = 'After'; option.Ch = Ch; specif.option = option; specif.beforechunk = {@beforechunk,'normal'}; specif.eachchunk = @eachchunk; specif.combinechunk = @combinechunk; if nargin > 1 && ischar(varargin{1}) && strcmp(varargin{1},'Now') if nargin > 2 extract = varargin{2}; else extract = []; end para = []; varargout = {main(orig,[],para,[],extract)}; else varargout = mirfunction(@miraudio,orig,varargin,nargout,specif,@init,@main); end if isempty(varargout) varargout = {{}}; end function [x type] = init(x,option) if isa(x,'mirdesign') if option.sampling x = setresampling(x,option.sampling); end end type = 'miraudio'; function a = main(orig,option,after,index,extract) if iscell(orig) orig = orig{1}; end if ischar(orig) if nargin < 5 extract = []; end [d{1},tp{1},fp{1},f{1},l{1},b{1},n{1},ch{1}] = mirread(extract,orig,1,0); l{1}{1} = l{1}{1}*f{1}; t = mirtemporal([],'Time',tp,'Data',d,'FramePos',fp,'Sampling',f,... 'Name',n,'Label',cell(1,length(d)),... 'Clusters',cell(1,length(d)),'Length',l,... 'Channels',ch,'Centered',0,'NBits',b); t = set(t,'Title','Audio waveform'); a.fresh = 1; a.extracted = 1; a = class(a,'miraudio',t); else if not(isempty(option)) && not(isempty(option.extract)) if not(isstruct(after)) after = struct; end after.extract = option.extract; end if isa(orig,'miraudio') a = orig; else a.fresh = 1; a.extracted = 0; a = class(a,'miraudio',orig); end end if not(isempty(after)) a = post(a,after); end function a = post(a,para) if a.fresh && isfield(para,'mono') a.fresh = 0; if isnan(para.mono) para.mono = 1; end end if isfield(para,'mono') && para.mono == 1 a = mirsum(a,'Mean'); end d = get(a,'Data'); t = get(a,'Time'); ac = get(a,'AcrossChunks'); f = get(a,'Sampling'); cl = get(a,'Clusters'); for h = 1:length(d) for k = 1:length(d{h}) tk = t{h}{k}; dk = d{h}{k}; if isfield(para,'extract') && not(isempty(para.extract)) ... && ~a.extracted t1 = para.extract(1); t2 = para.extract(2); if para.extract(4) if para.extract(4) == 1 shift = round(size(tk,1)/2); elseif para.extract(4) == 2 shift = size(tk,1); end if para.extract(3) shift = tk(shift,1,1); end t1 = t1+shift; t2 = t2+shift; end if para.extract(3) % in seconds ft = find(tk>=t1 & tk<=t2); else % in samples if not(t1) warning('WARNING IN MIRAUDIO: Extract sample positions should be real positive integers.') display('Positions incremented by one.'); t1 = t1+1; t2 = t2+1; end ft = t1:t2; end tk = tk(ft,:,:); dk = dk(ft,:,:); end if isfield(para,'Ch') && not(isempty(para.Ch)) dk = dk(:,:,para.Ch); end if isfield(para,'center') && para.center dk = center_(dk); a = set(a,'Centered',1); end if isfield(para,'normal') && para.normal nl = size(dk,1); nc = size(dk,3); if isempty(ac) ee = 0; for j = 1:nc ee = ee+sum(dk(:,:,j).^2); end ee = sqrt(ee/nl/nc); else ee = sqrt(sum(ac.sqrsum.^2)/ac.samples); end if ee dk = dk./repmat(ee,[nl,1,nc]); end end if isfield(para,'trim') && not(isequal(para.trim,0)) ... %%%% NOT A POST OPERATION!! && not(strcmpi(para.trim,'NoTrim')) if not(para.trimthreshold) para.trimthreshold = 0.06; end trimframe = 100; trimhop = 10; nframes = floor((length(tk)-trimframe)/trimhop)+1; rms = zeros(1,nframes); ss = sum(dk,3); for j = 1:nframes st = floor((j-1)*trimhop)+1; rms(j) = norm(ss(st:st+trimframe-1))/sqrt(trimframe); end rms = (rms-min(rms))./(max(rms)-min(rms)); nosil = find(rms>para.trimthreshold); if strcmpi(para.trim,'Trim') || strcmpi(para.trim,'TrimStart') ... || strcmpi(para.trim,'TrimBegin') nosil1 = min(nosil); if nosil1 > 1 nosil1 = nosil1-1; end n1 = floor((nosil1-1)*trimhop)+1; else n1 = 1; end if strcmpi(para.trim,'Trim') || strcmpi(para.trim,'TrimEnd') nosil2 = max(nosil); if nosil2 < length(rms) nosil2 = nosil2+1; end n2 = floor((nosil2-1)*trimhop)+1; else n2 = length(tk); end tk = tk(n1:n2); dk = dk(n1:n2,1,:); end if isfield(para,'sampling') && para.sampling if and(f{k}, not(f{k} == para.sampling)) for j = 1:size(dk,3) rk(:,:,j) = resample(dk(:,:,j),para.sampling,f{k}); end dk = rk; tk = repmat((0:size(dk,1)-1)',[1 1 size(tk,3)])... /para.sampling + tk(1,:,:); end f{k} = para.sampling; end d{h}{k} = dk; t{h}{k} = tk; %if isfield(para,'reverse') && para.reverse % d{h}{k} = flipdim(d{h}{k},1); %end end end a = set(a,'Data',d,'Time',t,'Sampling',f,'Clusters',cl); a = set(a,'Extracted',0); if isfield(para,'label') if isnumeric(para.label) n = get(a,'Name'); l = cell(1,length(d)); for k = 1:length(d) if para.label l{k} = n{k}(para.label); else l{k} = n{k}; end end a = set(a,'Label',l); elseif iscell(para.label) idx = mod(get(a,'Index'),length(para.label)); if not(idx) idx = length(para.label); end a = set(a,'Label',para.label{idx}); elseif ischar(para.label) && ~isempty(para.label) l = cell(1,length(d)); for k = 1:length(d) l{k} = para.label; end a = set(a,'Label',l); end end function [new orig] = beforechunk(orig,option,missing) option.normal = 0; a = miraudio(orig,option); d = get(a,'Data'); old = get(orig,'AcrossChunks'); if isempty(old) old.sqrsum = 0; old.samples = 0; end new = mircompute(@crossum,d); new = new{1}{1}; new.sqrsum = old.sqrsum + new.sqrsum; new.samples = old.samples + new.samples; function s = crossum(d) s.sqrsum = sum(d.^2); s.samples = length(d); function [y orig] = eachchunk(orig,option,missing) y = miraudio(orig,option); function y = combinechunk(old,new) doo = get(old,'Data'); to = get(old,'Time'); dn = get(new,'Data'); tn = get(new,'Time'); y = set(old,'Data',{{[doo{1}{1};dn{1}{1}]}},... 'Time',{{[to{1}{1};tn{1}{1}]}});
github
martinarielhartmann/mirtooloct-master
miremotion.m
.m
mirtooloct-master/MIRToolbox/@miremotion/miremotion.m
14,268
utf_8
e1e8b3cb2dcd7d9172b5b27dcc2240b7
function varargout = miremotion(orig,varargin) % Predicts emotion along three dimensions and five basic concepts. % Optional parameters: % miremotion(...,'Dimensions',0) excludes all three dimensions. % miremotion(...,'Dimensions',3) includes all three dimensions (default). % miremotion(...,'Activity') includes the 'Activity' dimension. % miremotion(...,'Valence') includes the 'Valence' dimension. % miremotion(...,'Tension') includes the 'Tension' dimension. % miremotion(...,'Dimensions',2) includes 'Activity' and 'Valence'. % miremotion(...,'Arousal') includes 'Activity' and 'Tension'. % miremotion(...,'Concepts',0) excludes all five concepts. % miremotion(...,'Concepts') includes all five concepts (default). % miremotion(...,'Happy') includes the 'Happy' concept. % miremotion(...,'Sad') includes the 'Sad' concept. % miremotion(...,'Tender') includes the 'Tender' concept. % miremotion(...,'Anger') includes the 'Anger' concept. % miremotion(...,'Fear') includes the 'Fear' concept. % miremotion(...,'Frame',...) predict emotion frame by frame. % % Selection of features and coefficients are taken from a study: % Eerola, T., Lartillot, O., and Toiviainen, P. % (2009). Prediction of multidimensional emotional ratings in % music from audio using multivariate regression models. % In Proceedings of 10th International Conference on Music Information Retrieval % (ISMIR 2009), pages 621-626. % % The implemented models are based on multiple linear regression with 5 best % predictors (MLR option in the paper). The box-cox transformations have now been % removed until the normalization values have been established with a large sample of music. % % TODO: Revision of coefficients to (a) force the output range between 0 - 1 and % (b) to be based on alternative models and materials (training sets). % % Updated 03.05.2010 TE % frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [0 0]; frame.keydefault = [2 .5]; option.frame = frame; dim.key = 'Dimensions'; dim.type = 'Integer'; dim.default = NaN; dim.keydefault = 3; option.dim = dim; activity.key = 'Activity'; activity.type = 'Boolean'; activity.default = NaN; option.activity = activity; valence.key = 'Valence'; valence.type = 'Boolean'; valence.default = NaN; option.valence = valence; tension.key = 'Tension'; tension.type = 'Boolean'; tension.default = NaN; option.tension = tension; arousal.key = 'Arousal'; arousal.type = 'Boolean'; arousal.default = NaN; option.arousal = arousal; concepts.key = 'Concepts'; concepts.type = 'Boolean'; concepts.default = NaN; option.concepts = concepts; happy.key = 'Happy'; happy.type = 'Boolean'; happy.default = NaN; option.happy = happy; sad.key = 'Sad'; sad.type = 'Boolean'; sad.default = NaN; option.sad = sad; tender.key = 'Tender'; tender.type = 'Boolean'; tender.default = NaN; option.tender = tender; anger.key = 'Anger'; anger.type = 'Boolean'; anger.default = NaN; option.anger = anger; fear.key = 'Fear'; fear.type = 'Boolean'; fear.default = NaN; option.fear = fear; specif.option = option; specif.defaultframelength = 2; %specif.defaultframehop = .5; specif.combinechunk = {'Average',@nothing}; specif.extensive = 1; varargout = mirfunction(@miremotion,orig,varargin,nargout,specif,@init,@main); %% function [x type] = init(x,option) option = process(option); if option.frame.length.val hop = option.frame.hop.val; if strcmpi(option.frame.hop.unit,'Hz') hop = 1/hop; option.frame.hop.unit = 's'; end if strcmpi(option.frame.hop.unit,'s') hop = hop*get(x,'Sampling'); end if strcmpi(option.frame.hop.unit,'%') hop = hop/100; option.frame.hop.unit = '/1'; end if strcmpi(option.frame.hop.unit,'/1') hop = hop*option.frame.length.val; end frames = 0:hop:1000000; x = mirsegment(x,frames'); elseif isa(x,'mirdesign') x = set(x,'NoChunk',1); end rm = mirrms(x,'Frame',.046,.5); le = 0; %mirlowenergy(rm,'ASR'); o = mironsets(x,'Filterbank',15,'Contrast',0.1); at = mirattacktime(o); as = 0; %mirattackslope(o); ed = 0; %mireventdensity(o,'Option1'); fl = mirfluctuation(x,'Summary'); fp = mirpeaks(fl,'Total',1); fc = 0; %mircentroid(fl); tp = 0; %mirtempo(x,'Frame',2,.5,'Autocor','Spectrum'); pc = mirpulseclarity(x,'Frame',2,.5); %%%%%%%%%%% Why 'Frame'?? s = mirspectrum(x,'Frame',.046,.5); sc = mircentroid(s); ss = mirspread(s); sr = mirroughness(s); %ps = mirpitch(x,'Frame',.046,.5,'Tolonen'); c = mirchromagram(x,'Frame','Wrap',0,'Pitch',0); %%%%%%%%%%%%%%%%%%%% Previous frame size was too small. cp = mirpeaks(c,'Total',1); ps = 0;%cp; ks = mirkeystrength(c); [k kc] = mirkey(ks); mo = mirmode(ks); hc = mirhcdf(c); se = mirentropy(mirspectrum(x,'Collapsed','Min',40,'Smooth',70,'Frame',1.5,.5)); %%%%%%%%% Why 'Frame'?? ns = mirnovelty(mirspectrum(x,'Frame',.1,.5,'Max',5000),'Normal',0); nt = mirnovelty(mirchromagram(x,'Frame',.2,.25),'Normal',0); %%%%%%%%%%%%%%%%%%%% Previous frame size was too small. nr = mirnovelty(mirchromagram(x,'Frame',.2,.25,'Wrap',0),'Normal',0); %%%%%%%%%%%%%%%%%%%% Previous frame size was too small. x = {rm,le, at,as,ed, fp,fc, tp,pc, sc,ss,sr, ps, cp,kc,mo,hc, se, ns,nt,nr}; type = {'miremotion','mirscalar','mirscalar',... 'mirscalar','mirscalar','mirscalar',... 'mirspectrum','mirscalar',... 'mirscalar','mirscalar',... 'mirscalar','mirscalar','mirscalar',... 'mirscalar',... 'mirchromagram','mirscalar','mirscalar','mirscalar',... 'mirscalar',... 'mirscalar','mirscalar','mirscalar'}; %% function e = main(x,option,postoption) warning('WARNING IN MIREMOTION: The current model of miremotion is not correctly calibrated with this version of MIRtoolbox (but with version 1.3 only).'); option = process(option); rm = get(x{1},'Data'); %le = get(x{2},'Data'); at = get(x{3},'Data'); %as = get(x{4},'Data'); %ed = get(x{5},'Data'); %fpp = get(x{6},'PeakPosUnit'); fpv = get(x{6},'PeakVal'); %fc = get(x{7},'Data'); %tp = get(x{8},'Data'); pc = get(x{9},'Data'); sc = get(x{10},'Data'); ss = get(x{11},'Data'); rg = get(x{12},'Data'); %ps = get(x{13},'PeakPosUnit'); cp = get(x{14},'PeakPosUnit'); kc = get(x{15},'Data'); mo = get(x{16},'Data'); hc = get(x{17},'Data'); se = get(x{18},'Data'); ns = get(x{19},'Data'); nt = get(x{20},'Data'); nr = get(x{21},'Data'); e.dim = {}; e.dimdata = mircompute(@initialise,rm); if option.activity == 1 [e.dimdata e.activity_fact] = mircompute(@activity,e.dimdata,rm,fpv,sc,ss,se); e.dim = [e.dim,'Activity']; else e.activity_fact = NaN; end if option.valence == 1 [e.dimdata e.valence_fact] = mircompute(@valence,e.dimdata,rm,fpv,kc,mo,ns); e.dim = [e.dim,'Valence']; else e.valence_fact = NaN; end if option.tension == 1 [e.dimdata e.tension_fact] = mircompute(@tension,e.dimdata,rm,fpv,kc,hc,nr); e.dim = [e.dim,'Tension']; else e.tension_fact = NaN; end e.class = {}; e.classdata = mircompute(@initialise,rm); if option.happy == 1 [e.classdata e.happy_fact] = mircompute(@happy,e.classdata,fpv,ss,cp,kc,mo); e.class = [e.class,'Happy']; else e.happy_fact = NaN; end if option.sad == 1 [e.classdata e.sad_fact] = mircompute(@sad,e.classdata,ss,cp,mo,hc,nt); e.class = [e.class,'Sad']; else e.sad_fact = NaN; end if option.tender == 1 [e.classdata e.tender_fact] = mircompute(@tender,e.classdata,sc,rg,kc,hc,ns); e.class = [e.class,'Tender']; else e.tender_fact = NaN; end if option.anger == 1 [e.classdata e.anger_fact] = mircompute(@anger,e.classdata,rg,kc,se,nr); e.class = [e.class,'Anger']; else e.anger_fact = NaN; end if option.fear == 1 [e.classdata e.fear_fact] = mircompute(@fear,e.classdata,rm,at,fpv,kc,mo); e.class = [e.class,'Fear']; else e.fear_fact = NaN; end e = class(e,'miremotion',mirdata(x{1})); e = purgedata(e); fp = mircompute(@noframe,get(x{1},'FramePos')); e = set(e,'Title','Emotion','Abs','emotions','Ord','magnitude','FramePos',fp); %% function option = process(option) if option.arousal==1 option.activity = 1; option.tension = 1; if isnan(option.dim) option.dim = 0; end end if option.activity==1 || option.valence==1 || option.tension==1 if isnan(option.activity) option.activity = 0; end if isnan(option.valence) option.valence = 0; end if isnan(option.tension) option.tension = 0; end if isnan(option.concepts) option.concepts = 0; end end if not(isnan(option.dim)) && option.dim if isnan(option.concepts) option.concepts = 0; end end if not(isnan(option.concepts)) && option.concepts if isnan(option.dim) option.dim = 0; end end if not(isnan(option.dim)) switch option.dim case 0 if isnan(option.activity) option.activity = 0; end if isnan(option.valence) option.valence = 0; end if isnan(option.tension) option.tension = 0; end case 2 option.activity = 1; option.valence = 1; if isnan(option.tension) option.tension = 0; end case 3 option.activity = 1; option.valence = 1; option.tension = 1; end end if isnan(option.activity) option.activity = 1; end if isnan(option.valence) option.valence = 1; end if isnan(option.tension) option.tension = 1; end if isnan(option.concepts) option.concepts = 1; end if option.concepts option.happy = 1; option.sad = 1; option.tender = 1; option.anger = 1; option.fear = 1; end if option.happy==1 || option.sad==1 || option.tender==1 ... || option.anger==1 || option.fear==1 if isnan(option.happy) option.happy = 0; end if isnan(option.sad) option.sad = 0; end if isnan(option.tender) option.tender = 0; end if isnan(option.anger) option.anger = 0; end if isnan(option.fear) option.fear = 0; end end %% function e = initialise(rm) e = []; function [e af] = activity(e,rm,fpv,sc,ss,se) % without the box-cox transformation, revised coefficients af = zeros(5,1); % In the code below, removal of nan values added by Ming-Hsu Chang af(1) = 0.6664* ((mean(rm(~isnan(rm))) - 0.0559)/0.0337); tmp = fpv{1}; af(2) = 0.6099 * ((mean(tmp(~isnan(tmp))) - 13270.1836)/10790.655); tmp = cell2mat(sc); af(3) = 0.4486*((mean(tmp(~isnan(tmp))) - 1677.7)./570.34); tmp = cell2mat(ss); af(4) = -0.4639*((mean(tmp(~isnan(tmp))) - (250.5574*22.88))./(205.3147*22.88)); % New normalisation proposed by Ming-Hsu Chang af(5) = 0.7056*((mean(se(~isnan(se))) - 0.954)./0.0258); af(isnan(af)) = []; e(end+1,:) = sum(af)+5.4861; function [e vf] = valence(e,rm,fpv,kc,mo,ns) % without the box-cox transformation, revised coefficients vf = zeros(5,1); vf(1) = -0.3161 * ((std(rm) - 0.024254)./0.015667); vf(2) = 0.6099 * ((mean(fpv{1}) - 13270.1836)/10790.655); vf(3) = 0.8802 * ((mean(kc) - 0.5123)./0.091953); vf(4) = 0.4565 * ((mean(mo) - -0.0019958)./0.048664); ns(isnan(ns)) = []; vf(5) = 0.4015 * ((mean(ns) - 131.9503)./47.6463); vf(isnan(vf)) = []; e(end+1,:) = sum(vf)+5.2749; function [e tf] = tension(e,rm,fpv,kc,hc,nr) tf = zeros(5,1); tf(1) = 0.5382 * ((std(rm) - 0.024254)./0.015667); tf(2) = -0.5406 * ((mean(fpv{1}) - 13270.1836)/10790.655); tf(3) = -0.6808 * ((mean(kc) - 0.5124)./0.092); tf(4) = 0.8629 * ((mean(hc) - 0.2962)./0.0459); tf(5) = -0.5958 * ((mean(nr) - 71.8426)./46.9246); tf(isnan(tf)) = []; e(end+1,:) = sum(tf)+5.4679; % BASIC EMOTION PREDICTORS function [e ha_f] = happy(e,fpv,ss,cp,kc,mo) ha_f = zeros(5,1); ha_f(1) = 0.7438*((mean(cell2mat(fpv)) - 13270.1836)./10790.655); ha_f(2) = -0.3965*((mean(cell2mat(ss)) - 250.5574)./205.3147); ha_f(3) = 0.4047*((std(cell2mat(cp)) - 8.5321)./2.5899); ha_f(4) = 0.7780*((mean(kc) - 0.5124)./0.092); ha_f(5) = 0.6220*((mean(mo) - -0.002)./0.0487); ha_f(isnan(ha_f)) = []; e(end+1,:) = sum(ha_f)+2.6166; function [e sa_f] = sad(e,ss,cp,mo,hc,nt) sa_f = zeros(5,1); sa_f(1) = 0.4324*((mean(cell2mat(ss)) - 250.5574)./205.3147); sa_f(2) = -0.3137*((std(cell2mat(cp)) - 8.5321)./2.5899); sa_f(3) = -0.5201*((mean(mo) - -0.0020)./0.0487); sa_f(4) = -0.6017*((mean(hc) - 0.2962)./0.0459); sa_f(5) = 0.4493*((mean(nt) - 42.2022)./36.7782); sa_f(isnan(sa_f)) = []; e(end+1,:) = sum(sa_f)+2.9756; function [e te_f] = tender(e,sc,rg,kc,hc,ns) te_f = zeros(5,1); te_f(1) = -0.2709*((mean(cell2mat(sc)) - 1677.7106)./570.3432); te_f(2) = -0.4904*((std(rg) - 85.9387)./106.0767); te_f(3) = 0.5192*((mean(kc) - 0.5124)./0.0920); te_f(4) = -0.3995*((mean(hc) - 0.2962)./0.0459); te_f(5) = 0.3391*((mean(ns) - 131.9503)./47.6463); te_f(isnan(te_f)) = []; e(end+1,:) = sum(te_f)+2.9756; function [e an_f] = anger(e,rg,kc,se,nr) % an_f = zeros(5,1); %an_f(1) = -0.2353*((mean(pc) - 0.1462)./.1113); an_f(2) = 0.5517*((mean(rg) - 85.9387)./106.0767); an_f(3) = -.5802*((mean(kc) - 0.5124)./0.092); an_f(4) = .2821*((mean(se) - 0.954)./0.0258); an_f(5) = -.2971*((mean(nr) - 71.8426)./46.9246); an_f(isnan(an_f)) = []; e(end+1,:) = sum(an_f)+1.9767; function [e fe_f] = fear(e,rm,at,fpv,kc,mo) fe_f = zeros(5,1); fe_f(1) = 0.4069*((std(rm) - 0.0243)./0.0157); fe_f(2) = -0.6388*((mean(at) - 0.0707)./0.015689218536423); fe_f(3) = -0.2538*((mean(cell2mat(fpv)) - 13270.1836)./10790.655); fe_f(4) = -0.9860*((mean(kc) - 0.5124)./0.0920); fe_f(5) = -0.3144*((mean(mo) - -0.0019958)./0.048663550639094); fe_f(isnan(fe_f)) = []; e(end+1,:) = sum(fe_f)+2.7847; function fp = noframe(fp) fp = [fp(1);fp(end)];
github
martinarielhartmann/mirtooloct-master
mirplay.m
.m
mirtooloct-master/MIRToolbox/@mirpattern/mirplay.m
899
utf_8
ea782c3f96091cb9b147f96756704a55
function varargout = mirplay(p,varargin) pat.key = 'Pattern'; pat.type = 'Integer'; pat.default = 0; option.pat = pat; specif.option = option; specif.eachchunk = 'Normal'; varargout = mirfunction(@mirplay,p,varargin,nargout,specif,@init,@main); if nargout == 0 varargout = {}; end function [x type] = init(x,option) type = ''; function noargout = main(p,option,postoption) if not(option.pat) option.pat = 1:length(p.pattern); end n = get(p,'Name'); for h = 1:length(n) for i = option.pat display(['Pattern # ',num2str(i)]) for j = 1:length(p.pattern{i}.occurrence) display(['Occurrence # ',num2str(j)]) a = miraudio(n{h},'Extract',p.pattern{i}.occurrence{j}.start,... p.pattern{i}.occurrence{j}.end); mirplay(a) end end end noargout = {};
github
martinarielhartmann/mirtooloct-master
mirpattern.m
.m
mirtooloct-master/MIRToolbox/@mirpattern/mirpattern.m
1,867
utf_8
1def40f8b242e54a318195d5ecc0c60f
function varargout = mirpattern(orig,varargin) % p = mirpattern(a) period.key = 'Period'; period.type = 'Boolean'; period.when = 'After'; period.default = 0; option.period = period; specif.option = option; varargout = mirfunction(@mirpattern,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) if not(isamir(x,'mirpattern')) x = mirsimatrix(x); end type = 'mirpattern'; function p = main(orig,option,postoption) if not(isamir(orig,'mirpattern')) b = get(orig,'Branch'); fp = get(orig,'FramePos'); pp = get(orig,'PeakPos'); for i = 1:length(b) for j = 1:length(b{i}{1}) bi = b{i}{1}{j}; pi1 = sort(pp{i}{1}{bi(1,1)}); pi2 = sort(pp{i}{1}{bi(end,1)}); p.pattern{j}.occurrence{1}.start = ... fp{i}{1}(1,bi(1,1)) - mean(fp{i}{1}(1:2,pi1(bi(1,2)))); p.pattern{j}.occurrence{2}.start = ... fp{i}{1}(1,bi(1,1)); p.pattern{j}.occurrence{1}.end = ... fp{i}{1}(1,bi(end,1)) - mean(fp{i}{1}(1:2,pi2(bi(end,2)))); p.pattern{j}.occurrence{2}.end = ... fp{i}{1}(1,bi(end,1)); end end p = class(p,'mirpattern',mirdata(orig)); end if postoption.period for i = 1:length(p.pattern) poi = p.pattern{i}.occurrence; if poi{1}.end > poi{2}.start poi{1}.end = poi{2}.start; cycle = poi{1}.end - poi{1}.start; ncycles = floor((poi{2}.end-poi{2}.start)/cycle)+2; poi{ncycles}.end = poi{2}.end; poi{2}.end = poi{2}.start + cycle; for j = 2:ncycles-1 poi{j}.end = poi{j}.start + cycle; poi{j+1}.start = poi{j}.end; end end p.pattern{i}.occurrence = poi; end end
github
martinarielhartmann/mirtooloct-master
mirpitch.m
.m
mirtooloct-master/MIRToolbox/@mirpitch/mirpitch.m
34,447
utf_8
60e5f74d92ec86e6551b87495a9a6792
function varargout = mirpitch(orig,varargin) % p = mirpitch(x) evaluates the pitch frequencies (in Hz). % Specification of the method(s) for pitch estimation (these methods can % be combined): % mirpitch(...,'Autocor') computes an autocorrelation function % (Default method) % mirpitch(...'Enhanced',a) computes enhanced autocorrelation % (see help mirautocor) % toggled on by default % mirpitch(...,'Compress',k) performs magnitude compression % (see help mirautocor) % mirpitch(...,fb) specifies a type of filterbank. % Possible values: % fb = 'NoFilterBank': no filterbank decomposition % fb = '2Channels' (default value) % fb = 'Gammatone' % mirpitch(...,'Spectrum') computes the FFT spectrum % mirpitch(...,'AutocorSpectrum') computes the autocorrelation of % the FFT spectrum % mirpitch(...,'Cepstrum') computes the cepstrum % Alternatively, an autocorrelation or a cepstrum can be directly % given as first argument of the mirpitch function. % Peak picking options: % mirpitch(...,'Total',m) selects the m best pitches. % Default value: m = Inf, no limit is set concerning the number % of pitches to be detected. % mirpitch(...,'Mono') corresponds to mirpitch(...,'Total',1) % mirpitch(...,'Min',mi) indicates the lowest frequency taken into % consideration. % Default value: 75 Hz. (Praat) % mirpitch(...,'Max',ma) indicates the highest frequency taken into % consideration. % Default value: 2400 Hz. Because there seems to be some problems % with higher frequency, due probably to the absence of % pre-whitening in our implementation of Tolonen and Karjalainen % approach (used by default, cf. below). % mirpitch(...,'Contrast',thr) specifies a threshold value. % (see help peaks) % Default value: thr = .1 % mirpitch(...,'Order',o) specifies the ordering for the peak picking. % Default value: o = 'Amplitude'. % Alternatively, the result of a mirpeaks computation can be directly % given as first argument of the mirpitch function. % Post-processing options: % mirpitch(..., 'Cent') convert the pitch axis from Hz to cent scale. % One octave corresponds to 1200 cents, so that 100 cents % correspond to a semitone in equal temperament. % mirpitch(..., 'Segment') segments the obtained monodic pitch curve % in cents as a succession of notes with stable frequencies. % Additional parameters available: 'SegMinLength', 'SegPitchGap', % 'SegTimeGap'. % mirpitch(...,'Sum','no') does not sum back the channels at the end % of the computation. The resulting pitch information remains % therefore decomposed into several channels. % mirpitch(...,'Median') performs a median filtering of the pitch % curve. When several pitches are extracted in each frame, the % pitch curve contains the best peak of each successive frame. % mirpitch(...,'Stable',th,n) remove pitch values when the difference % (or more precisely absolute logarithmic quotient) with the % n precedent frames exceeds the threshold th. % if th is not specified, the default value .1 is used % if n is not specified, the default value 3 is used % mirpitch(...'Reso',r) removes peaks whose distance to one or % several higher peaks is lower than a given threshold. % Possible value for the threshold r: % 'SemiTone': ratio between the two peak positions equal to % 2^(1/12) % mirpitch(...,'Frame',l,h) orders a frame decomposition of window % length l (in seconds) and hop factor h, expressed relatively to % the window length. For instance h = 1 indicates no overlap. % Default values: l = 46.4 ms and h = 10 ms (Tolonen and % Karjalainen, 2000) % Preset model: % mirpitch(...,'Tolonen') implements (part of) the model proposed in % (Tolonen & Karjalainen, 2000). It is equivalent to % mirpitch(...,'Enhanced',2:10,'Generalized',.67,'2Channels') % [p,a] = mirpitch(...) also displays the result of the method chosen for % pitch estimation, and shows in particular the peaks corresponding % to the pitch values. % p = mirpitch(f,a,<r>) creates a mirpitch object based on the frequencies % specified in f and the related amplitudes specified in a, using a % frame sampling rate of r Hz (set by default to 100 Hz). % % T. Tolonen, M. Karjalainen, "A Computationally Efficient Multipitch % Analysis Model", IEEE TRANSACTIONS ON SPEECH AND AUDIO PROCESSING, % VOL. 8, NO. 6, NOVEMBER 2000 ac.key = 'Autocor'; ac.type = 'Boolean'; ac.default = 0; option.ac = ac; enh.key = 'Enhanced'; enh.type = 'Integer'; enh.default = 2:10; option.enh = enh; filtertype.type = 'String'; filtertype.choice = {'NoFilterBank','2Channels','Gammatone'}; filtertype.default = '2Channels'; option.filtertype = filtertype; sum.key = 'Sum'; sum.type = 'Boolean'; sum.default = 1; option.sum = sum; gener.key = {'Generalized','Compress'}; gener.type = 'Integer'; gener.default = .5; option.gener = gener; as.key = 'AutocorSpectrum'; as.type = 'Boolean'; as.default = 0; option.as = as; s.key = 'Spectrum'; s.type = 'Boolean'; s.default = 0; option.s = s; res.key = 'Res'; res.type = 'Integer'; res.default = NaN; option.res = res; db.key = 'dB'; db.type = 'Integer'; db.default = 0; db.keydefault = Inf; option.db = db; ce.key = 'Cepstrum'; ce.type = 'Boolean'; ce.default = 0; option.ce = ce; comb.key = 'Comb'; comb.type = 'Boolean'; comb.default = 0; option.comb = comb; %% peak picking options m.key = 'Total'; m.type = 'Integer'; m.default = Inf; option.m = m; multi.key = 'Multi'; multi.type = 'Boolean'; multi.default = 0; option.multi = multi; mono.key = 'Mono'; mono.type = 'Boolean'; mono.default = 0; option.mono = mono; mi.key = 'Min'; mi.type = 'Integer'; mi.default = 75; option.mi = mi; ma.key = 'Max'; ma.type = 'Integer'; ma.default = 2400; option.ma = ma; cthr.key = 'Contrast'; cthr.type = 'Integer'; cthr.default = .1; option.cthr = cthr; thr.key = 'Threshold'; thr.type = 'Integer'; thr.default = .4; option.thr = thr; order.key = 'Order'; order.type = 'String'; order.choice = {'Amplitude','Abscissa'}; order.default = 'Amplitude'; option.order = order; reso.key = 'Reso'; reso.type = 'String'; reso.choice = {0,'SemiTone'}; reso.default = 0; option.reso = reso; track.key = 'Track'; % Not used yet track.type = 'Boolean'; track.default = 0; option.track = track; %% post-processing options cent.key = 'Cent'; cent.type = 'Boolean'; cent.default = 0; option.cent = cent; segm.key = 'Segment'; segm.type = 'Boolean'; segm.when = 'Both'; segm.default = 0; option.segm = segm; segmin.key = 'SegMinLength'; segmin.type = 'Integer'; segmin.when = 'Both'; segmin.default = 2; option.segmin = segmin; segpitch.key = 'SegPitchGap'; segpitch.type = 'Integer'; segpitch.when = 'Both'; segpitch.default = 45; option.segpitch = segpitch; segtime.key = 'SegTimeGap'; segtime.type = 'Integer'; segtime.when = 'Both'; segtime.default = 20; option.segtime = segtime; octgap.key = 'OctaveGap'; octgap.type = 'Boolean'; octgap.when = 'Both'; octgap.default = 0; option.octgap = octgap; ref.key = 'Ref'; ref.type = 'Integer'; ref.default = 0; option.ref = ref; stable.key = 'Stable'; stable.type = 'Integer'; stable.number = 2; stable.default = [Inf 0]; stable.keydefault = [.1 3]; option.stable = stable; median.key = 'Median'; median.type = 'Integer'; median.default = 0; median.keydefault = .1; option.median = median; frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [0 0]; frame.keydefault = [NaN NaN]; option.frame = frame; %% preset model tolo.key = 'Tolonen'; tolo.type = 'Boolean'; tolo.default = 0; option.tolo = tolo; harmonic.key = 'Harmonic'; harmonic.type = 'Boolean'; harmonic.default = 0; option.harmonic = harmonic; specif.option = option; specif.chunkframebefore = 1; if isnumeric(orig) if nargin<3 f = 100; else f = varargin{2}; end fp = (0:size(orig,1)-1)/f; fp = [fp;fp+1/f]; p.amplitude = {{varargin{1}'}}; s = mirscalar([],'Data',{{orig'}},'Title','Pitch','Unit','Hz',... 'FramePos',{{fp}},'Sampling',f,'Name',{inputname(1)}); p = class(p,'mirpitch',s); varargout = {p}; else varargout = mirfunction(@mirpitch,orig,varargin,nargout,specif,@init,@main); end function [y type] = init(orig,option) if option.tolo option.enh = 2:10; option.gener = .67; option.filtertype = '2Channels'; elseif option.harmonic option.s = 1; option.frame.hop.val = .1; option.res = 1; option.db = Inf; end if not(option.ac) && not(option.as) && not(option.ce) && not(option.s) option.ac = 1; end if option.segm && option.frame.length.val==0 option.frame.length.val = NaN; option.frame.hop.val = NaN; end if isnan(option.frame.length.val) option.frame.length.val = .0464; end if isnan(option.frame.hop.val) option.frame.hop.val = .01; option.frame.hop.unit = 's'; end if isamir(orig,'mirmidi') || isamir(orig,'mirscalar') || haspeaks(orig) y = orig; else if isamir(orig,'mirautocor') y = mirautocor(orig,'Min',option.mi,'Hz','Max',option.ma,'Hz','Freq'); elseif isamir(orig,'mircepstrum') y = orig; elseif isamir(orig,'mirspectrum') if not(option.as) && not(option.ce) && not(option.s) option.ce = 1; end if option.as y = mirautocor(orig,... 'Min',option.mi,'Hz','Max',option.ma,'Hz'); end if option.ce ce = mircepstrum(orig,'freq',... 'Min',option.mi,'Hz','Max',option.ma,'Hz'); if option.as y = y*ce; else y = ce; end end if option.s y = orig; end else if option.ac x = orig; if not(strcmpi(option.filtertype,'NoFilterBank')) x = mirfilterbank(x,option.filtertype); end x = mirframenow(x,option); y = mirautocor(x,'Generalized',option.gener);%,... % 'Min',option.mi,'Hz','Max',option.ma,'Hz'); if option.sum y = mirsummary(y); end y = mirautocor(y,'Enhanced',option.enh,'Freq'); y = mirautocor(y,'Min',option.mi,'Hz','Max',option.ma,'Hz'); end if option.as || option.ce || option.s x = mirframenow(orig,option); if option.comb y = mirspectrum(x,'Min',option.mi,'Max',2000,'Res',1);%,'Sum'); elseif option.s s = mirspectrum(x,'Min',option.mi,'Max',option.ma,... 'Res',option.res,'dB',option.db); if option.ac y = y*s; else y = s; end end if option.as || option.ce s = mirspectrum(x); if option.as as = mirautocor(s,'Min',option.mi,'Hz',... 'Max',option.ma,'Hz'); if option.ac || option.s y = y*as; else y = as; end end if option.ce ce = mircepstrum(s,'freq','Min',option.mi,'Hz',... 'Max',option.ma,'Hz'); if option.ac || option.s || option.as y = y*ce; else y = ce; end end end end end end type = {'mirpitch',mirtype(y)}; function o = main(x,option,postoption) if option.comb == 2 option.m = Inf; option.order = 'Abscissa'; elseif option.multi && option.m == 1 option.m = Inf; elseif (option.mono && option.m == Inf) %|| option.segm option.m = 1; elseif option.harmonic option.cthr = .01; option.thr = .5; end if iscell(x) if length(x)>1 x2 = get(x{2},'Data'); f2 = get(x{2},'Pos'); end x = x{1}; else x2 = []; end if option.comb == 1 d = get(x,'Data'); pos = get(x,'Pos'); cb = cell(1,length(d)); for i = 1:length(d) cb{i} = cell(1,length(d{i})); for j = 1:length(d{i}) cb{i}{j} = zeros(size(d{i}{j},1),... size(d{i}{j},2),... size(d{i}{j},3)); dij = d{i}{j}/max(max(max(d{i}{j}))); for h = 1:size(d{i}{j},1) ph = pos{i}{j}(h,1,1); ip = h; for k = 2:size(d{i}{j},1) [unused mp] = min(abs(pos{i}{j}(ip(end)+1:end,1,1) ... - ph * k)); if isempty(mp) break end ip(end+1) = ip(end) + mp; end if length(ip) == 1 break end cbh = sum(dij(ip,:,:)); for k = 1:length(ip) cbh = cbh .* ... (.5 * (2 - ... exp(-(max(dij(ip(1:k),:,:),[],1).^2 * 5000)))); end cb{i}{j}(h,:,:) = cbh; end cb{i}{j}(h+1:end,:,:) = []; pos{i}{j}(h+1:end,:,:) = []; end end x = set(x,'Data',cb,'Pos',pos,'Title','Spectral Comb'); end if isa(x,'mirpitch') pf = get(x,'Data'); pa = get(x,'Amplitude'); if option.m < Inf for i = 1:length(pf) for j = 1:length(pf{i}) for h = 1:length(pf{i}{j}) pf{i}{j}{h} = pf{i}{j}{h}(1:option.m,:); pa{i}{j}{h} = pa{i}{j}{h}(1:option.m,:); end end end end else if not(isa(x,'mirpitch') || isa(x,'mirmidi')) x = mirpeaks(x,'Total',option.m,'Track',option.track,... 'Contrast',option.cthr,'Threshold',option.thr,... 'Reso',option.reso,'NoBegin','NoEnd',... 'Order',option.order,'Harmonic',option.harmonic); end if isa(x,'mirscalar') pf = get(x,'Data'); elseif option.harmonic pf = get(x,'TrackPos'); pa = get(x,'TrackVal'); else pf = get(x,'PeakPrecisePos'); pa = get(x,'PeakPreciseVal'); end end fp = get(x,'FramePos'); punit = 'Hz'; if option.comb == 2 pp = get(x,'PeakPos'); pv = get(x,'PeakVal'); pm = get(x,'PeakMode'); f = get(x,'Pos'); for i = 1:length(pf) for j = 1:length(pf{i}) maxf = f{i}{j}(end,1); for h = 1:length(pf{i}{j}) sco = zeros(length(pf{i}{j}{h}),1); for k = 1:length(pf{i}{j}{h}) fk = pf{i}{j}{h}(k); if fk > option.ma break end ws = zeros(round(maxf / fk) ,1); %err = mod(pf{i}{j}{h}/fk,1); %err = min(err,1-err); ws(1) = pa{i}{j}{h}(k); for l = k+1:length(pf{i}{j}{h}) r = round(pf{i}{j}{h}(l) / fk); if r == 1 continue end err = mod(pf{i}{j}{h}(l) / fk ,1); err = min(err,1-err); ws(r) = max(ws(r),pa{i}{j}{h}(l).*exp(-err^2*50)); end sco(k) = sum(ws); if length(ws)>3 && ws(3)<.5 sco(k) = sco(k)/2; end %if length(ws)>5 && ws(5)<.5 % sco(k) = sco(k)/2; %end %/(1+length(find(ws(2:end-1)<.01))); %sco(k) = sum(pa{i}{j}{h}.*exp(-err)); end %pa{i}{j}{h} = sco; [unused b] = max(sco); pf{i}{j}{h} = pf{i}{j}{h}(b); pa{i}{j}{h} = pa{i}{j}{h}(b); pp{i}{j}{h} = pp{i}{j}{h}(b); pv{i}{j}{h} = pv{i}{j}{h}(b); pm{i}{j}{h} = pm{i}{j}{h}(b); end end end x = set(x,'PeakPrecisePos',pf,'PeakPreciseVal',pa,... 'PeakPos',pp,'PeakVal',pv,'PeakMode',pm); end if (option.cent || option.segm) && ... (~isa(x,'mirpitch') || strcmp(get(x,'Unit'),'Hz')) punit = 'cents'; for i = 1:length(pf) for j = 1:length(pf{i}) for k = 1:size(pf{i}{j},3) for l = 1:size(pf{i}{j},2) pf{i}{j}{1,l,k} = 1200*log2(pf{i}{j}{1,l,k}); end end end end end if option.segm scale = []; for i = 1:length(pf) for j = 1:length(pf{i}) if size(pf{i}{j},2) == 1 && size(pf{i}{j}{1},2) > 1 pfj = cell(1,size(pf{i}{j}{1},2)); paj = cell(1,size(pa{i}{j}{1},2)); for l = 1:size(pf{i}{j}{1},2) if isnan(pf{i}{j}{1}(l)) pfj{l} = []; paj{l} = 0; else pfj{l} = pf{i}{j}{1}(l); paj{l} = pa{i}{j}{1}(l); end end pf{i}{j} = pfj; pa{i}{j} = paj; end for k = 1:size(pf{i}{j},3) startp = []; meanp = []; endp = []; deg = []; stabl = []; buffer = []; breaks = []; currentp = []; maxp = 0; reson = []; attack = []; if ~isempty(pf{i}{j}{1,1,k}) pf{i}{j}{1,1,k} = pf{i}{j}{1,1,k}(1); pa{i}{j}{1,1,k} = pa{i}{j}{1,1,k}(1); end if ~isempty(pf{i}{j}{1,end,k}) pf{i}{j}{1,end,k} = pf{i}{j}{1,end,k}(1); pa{i}{j}{1,end,k} = pa{i}{j}{1,end,k}(1); end for l = 2:size(pf{i}{j},2)-1 if ~isempty(pa{i}{j}{1,l,k}) && ... pa{i}{j}{1,l,k}(1) > maxp maxp = pa{i}{j}{1,l,k}(1); end if ~isempty(reson) && l-reson(1).end>50 reson(1) = []; end if ~isempty(pf{i}{j}{1,l,k}) if 1 %isempty(pf{i}{j}{1,l-1,k}) pf{i}{j}{1,l,k} = pf{i}{j}{1,l,k}(1); pa{i}{j}{1,l,k} = pa{i}{j}{1,l,k}(1); else [dpf idx] = min(abs(pf{i}{j}{1,l,k} - ... pf{i}{j}{1,l-1,k})); if idx > 1 && ... pa{i}{j}{1,l,k}(1) - pa{i}{j}{1,l,k}(idx) > .02 pf{i}{j}{1,l,k} = pf{i}{j}{1,l,k}(1); pa{i}{j}{1,l,k} = pa{i}{j}{1,l,k}(1); else pf{i}{j}{1,l,k} = pf{i}{j}{1,l,k}(idx); pa{i}{j}{1,l,k} = pa{i}{j}{1,l,k}(idx); end end end interrupt = 0; if l == size(pf{i}{j},2)-1 || ... isempty(pf{i}{j}{1,l,k}) || ... (~isempty(buffer) && ... abs(pf{i}{j}{1,l,k} - pf{i}{j}{1,l-1,k})... > option.segpitch) || ... (~isempty(currentp) && ... abs(pf{i}{j}{1,l,k} - currentp) > ... option.segpitch) interrupt = 1; elseif (~isempty(pa{i}{j}{1,l-1,k}) && ... pa{i}{j}{1,l,k} - pa{i}{j}{1,l-1,k} > .01) interrupt = 2; end if ~interrupt for h = 1:length(reson) if abs(pf{i}{j}{1,l,k}-reson(h).pitch) < 50 && ... pa{i}{j}{1,l,k} < reson(h).amp/5 pa{i}{j}{1,l,k} = []; pf{i}{j}{1,l,k} = []; interrupt = 1; break end end end if interrupt % Segment interrupted if isempty(buffer) || ... ...%length(buffer.pitch) < option.segmin || ... 0 %std(buffer.pitch) > 25 if length(startp) > length(endp) startp(end) = []; end else if isempty(currentp) strong = find(buffer.amp > max(buffer.amp)*.75); meanp(end+1) = mean(buffer.pitch(strong)); else meanp(end+1) = currentp; end endp(end+1) = l-1; hp = hist(buffer.pitch,5); hp = hp/sum(hp); entrp = -sum(hp.*log(hp+1e-12))./log(length(hp)); stabl(end+1) = entrp>.7; deg(end+1) = cent2deg(meanp(end),scale); reson(end+1).pitch = meanp(end); reson(end).amp = mean(buffer.amp); reson(end).end = l-1; attack(end+1) = max(buffer.amp) > .05; end if isempty(pf{i}{j}{1,l,k}) buffer = []; else buffer.pitch = pf{i}{j}{1,l,k}; buffer.amp = pa{i}{j}{1,l,k}; startp(end+1) = l; end currentp = []; breaks(end+1) = l; elseif isempty(buffer) % New segment starting startp(end+1) = l; buffer.pitch = pf{i}{j}{1,l,k}; buffer.amp = pa{i}{j}{1,l,k}; else if length(pf{i}{j}{1,l,k})>1 mirerror('mirpitch','''Segment'' option only for monodies (use also ''Mono'')'); end buffer.pitch(end+1) = pf{i}{j}{1,l,k}; buffer.amp(end+1) = pa{i}{j}{1,l,k}; if length(buffer.pitch) > 4 && ... std(buffer.pitch(1:end)) < 5 && ... buffer.amp(end) > max(buffer.amp)*.5 currentp = mean(buffer.pitch(1:end)); %else % l end end end if length(startp) > length(meanp) startp(end) = []; end l = 1; while l <= length(endp) if 1 %~isempty(intersect(startp(l)-(1:5),breaks)) && ... % ~isempty(intersect(endp(l)+(1:5),breaks)) if 1 %attack(l) minlength = option.segmin; else minlength = 6; end else minlength = 2; end if endp(l)-startp(l) > minlength % Segment sufficiently long if l>1 && ~attack(l) && ... startp(l) <= endp(l-1)+option.segtime && ... abs(meanp(l)-meanp(l-1)) < 50 % Segment fused with previous one startp(l) = []; %meanp(l-1) = mean(meanp(l-1:l)); meanp(l) = []; deg(l-1) = cent2deg(meanp(l-1),scale); deg(l) = []; attack(l-1) = max(attack(l),attack(l-1)); attack(l) = []; endp(l-1) = []; found = 1; else l = l+1; end % Other cases: Segment too short elseif l>1 && ... startp(l) <= endp(l-1)+option.segtime && ... abs(meanp(l)-meanp(l-1)) < 50 % Segment fused with previous one startp(l) = []; %meanp(l-1) = mean(meanp(l-1:l)); meanp(l) = []; deg(l) = []; attack(l-1) = max(attack(l),attack(l-1)); attack(l) = []; endp(l-1) = []; elseif 0 && l < length(meanp) && ... startp(l+1) <= endp(l)+option.segtime && ... abs(meanp(l+1)-meanp(l)) < 50 % Segment fused with next one startp(l+1) = []; meanp(l) = meanp(l+1); %mean(meanp(l:l+1)); meanp(l+1) = []; deg(l) = deg(l+1); deg(l+1) = []; attack(l) = max(attack(l),attack(l+1)); attack(l+1) = []; endp(l) = []; else % Segment removed startp(l) = []; meanp(l) = []; deg(l) = []; attack(l) = []; endp(l) = []; end end l = 1; while l <= length(endp) if (max([pa{i}{j}{1,startp(l):endp(l),k}]) < maxp/20 ... && isempty(pa{i}{j}{1,startp(l)-1,k}) ... && isempty(pa{i}{j}{1,endp(l)+1,k})) ... || endp(l) - startp(l) < option.segmin % Segment removed fusetest = endp(l) - startp(l) < option.segmin; startp(l) = []; meanp(l) = []; deg(l) = []; endp(l) = []; stabl(l) = []; attack(l) = []; if fusetest && ... l > 1 && l <= length(meanp) && ... abs(meanp(l-1)-meanp(l)) < 50 % Preceding segment fused with next one startp(l) = []; meanp(l-1) = meanp(l); %mean(meanp(l:l+1)); meanp(l) = []; deg(l-1) = deg(l); deg(l) = []; attack(l-1) = max(attack(l),attack(l-1)); attack(l) = []; endp(l-1) = []; end else l = l+1; end end if option.octgap l = 2; while l <= length(endp) if abs(meanp(l-1) - meanp(l) - 1200) < 50 % Segment removed startp(l) = []; meanp(l-1) = meanp(l); meanp(l) = []; deg(l-1) = deg(l); deg(l) = []; attack(l) = []; endp(l-1) = []; stabl(l) = []; elseif abs(meanp(l) - meanp(l-1) - 1200) < 50 % Segment removed startp(l) = []; meanp(l) = meanp(l-1); meanp(l) = []; deg(l) = deg(l-1); deg(l) = []; attack(l) = []; endp(l-1) = []; stabl(l) = []; else l = l+1; end end end ps{i}{j}{k} = startp; pe{i}{j}{k} = endp; pm{i}{j}{k} = meanp; stb{i}{j}{k} = stabl; dg = {}; %{i}{j}{k} = deg; end end end elseif isa(x,'mirpitch') ps = get(x,'Start'); pe = get(x,'End'); pm = get(x,'Mean'); dg = get(x,'Degrees'); stb = get(x,'Stable'); elseif isa(x,'mirmidi') nm = get(x,'Data'); for i = 1:length(nm) startp = nm{i}(:,1); endp = startp + nm{i}(:,2); fp{i} = [startp endp]'; ps{i} = {{1:length(startp)}}; pe{i} = {{1:length(endp)}}; pm{i} = {{nm{i}(:,4)'-68}}; dg{i} = pm{i}; stb{i} = []; pf{i} = {NaN(size(startp'))}; end x = set(x,'FramePos',{fp}); else ps = {}; pe = {}; pm = {}; dg = {}; stb = {}; end if option.stable(1) < Inf for i = 1:length(pf) for j = 1:length(pf{i}) for k = 1:size(pf{i}{j},3) for l = size(pf{i}{j},2):-1:option.stable(2)+1 for m = length(pf{i}{j}{1,l,k}):-1:1 found = 0; for h = 1:option.stable(2) for n = 1:length(pf{i}{j}{1,l-h,k}) if abs(log10(pf{i}{j}{1,l,k}(m) ... /pf{i}{j}{1,l-h,k}(n))) ... < option.stable(1) found = 1; end end end if not(found) pf{i}{j}{1,l,k}(m) = []; end end pf{i}{j}{1,1,k} = zeros(1,0); end end end end end if option.median for i = 1:length(pf) for j = 1:length(pf{i}) if size(fp{i}{j},2) > 1 npf = zeros(size(pf{i}{j})); for k = 1:size(pf{i}{j},3) for l = 1:size(pf{i}{j},2) if isempty(pf{i}{j}{1,l,k}) npf(1,l,k) = NaN; else npf(1,l,k) = pf{i}{j}{1,l,k}(1); end end end pf{i}{j} = medfilt1(npf,... round(option.median/(fp{i}{j}(1,2)-fp{i}{j}(1,1)))); end end end end if 0 %isa(x,'mirscalar') p.amplitude = 0; else p.amplitude = pa; end p.start = ps; p.end = pe; p.mean = pm; p.degrees = dg; p.stable = stb; s = mirscalar(x,'Data',pf,'Title','Pitch','Unit',punit); p = class(p,'mirpitch',s); o = {p,x}; function [deg ref] = cent2deg(cent,ref) deg = round((cent-ref)/100); if isempty(deg) deg = 0; end %ref = cent - deg*100
github
martinarielhartmann/mirtooloct-master
mirplay.m
.m
mirtooloct-master/MIRToolbox/@mirenvelope/mirplay.m
3,662
utf_8
2e8e380750d648bcb991781e813423fd
function mirplay(e,varargin) % mirplay method for mirenvelope objects. Help displayed in ../mirplay.m ch.key = 'Channel'; ch.type = 'Integer'; ch.default = 0; option.ch = ch; sg.key = 'Segment'; sg.type = 'Integer'; sg.default = 0; option.sg = sg; se.key = 'Sequence'; se.type = 'Integer'; se.default = 0; option.se = se; inc.key = 'Increasing'; inc.type = 'MIRtb'; option.inc = inc; dec.key = 'Decreasing'; dec.type = 'MIRtb'; option.dec = dec; every.key = 'Every'; every.type = 'Integer'; option.every = every; burst.key = 'Burst'; burst.type = 'Boolean'; burst.default = 1; option.burst = burst; specif.option = option; specif.eachchunk = 'Normal'; varargout = mirfunction(@mirplay,e,varargin,nargout,specif,@init,@main); if nargout == 0 varargout = {}; end function [x type] = init(x,option) type = ''; function noargout = main(a,option,postoption) if iscell(a) a = a{1}; end d = get(a,'Data'); f = get(a,'Sampling'); n = get(a,'Name'); c = get(a,'Channels'); pp = get(a,'PeakPosUnit'); if not(option.se) if length(d)>1 if isfield(option,'inc') [unused order] = sort(mirgetdata(option.inc)); elseif isfield(option,'dec') [unused order] = sort(mirgetdata(option.dec),'descend'); else order = 1:length(d); end if isfield(option,'every') order = order(1:option.every:end); end else order = 1; end else order = option.se; end if not(isempty(order)) for k = order(:)' display(['Playing envelope of file: ' n{k}]) dk = d{k}; if not(iscell(dk)) dk = {dk}; end if option.ch if isempty(c{k}) chk = option.ch; else [unused unused chk] = intersect(option.ch,c{k}); end else chk = 1:size(dk{1},3); end if isempty(chk) display('No channel to play.'); end for l = chk if chk(end)>1 display([' Playing channel #' num2str(l)]); end if option.sg sgk = option.sg(find(option.sg<=length(dk))); else sgk = 1:length(dk); end for i = sgk if sgk(end)>1 display([' Playing segment #' num2str(i)]) end di = dk{i}; for j = 1:size(di,2) djl = resample(di(:,j,l),11025,round(f{k})); djl = djl/max(djl); djl = rand(length(djl),1).*djl; %djl(:)?; if ~isempty(pp) && ~isempty(pp{k}{i}) pjl = pp{k}{i}{j,l}; d2jl = zeros(length(djl),1); for h = 1:length(pjl) d2jl(round(pjl(h)*11025)) = 1; end djl = djl/10 + d2jl; end sound(djl,11025); idealtime = length(djl)/11025; practime = toc; if practime < idealtime pause(idealtime-practime) end end if option.burst && sgk(end)>1 sound(rand(1,10)) end end end end end noargout = {};
github
martinarielhartmann/mirtooloct-master
mirenvelope.m
.m
mirtooloct-master/MIRToolbox/@mirenvelope/mirenvelope.m
26,047
utf_8
b2e8c24762ea7e5c9b41c1db89666a70
function varargout = mirenvelope(orig,varargin) % e = mirenvelope(x) extracts the envelope of x, showing the global shape % of the waveform. % mirenvelope(...,m) specifies envelope extraction method. % Possible values: % m = 'Filter' uses a low-pass filtering. (Default strategy) % m = 'Spectro' uses a spectrogram. % % Options related to the 'Filter' method: % mirenvelope(...,'Hilbert'): performs a preliminary Hilbert % transform. % mirenvelope(...,'PreDecim',N) downsamples by a factor N>1, where % N is an integer, before the low-pass filtering (Klapuri, 1999). % Default value: N = 1. % mirenvelope(...,'Filtertype',f) specifies the filter type. % Possible values are: % f = 'IIR': filter with one autoregressive coefficient % (default) % f = 'HalfHann': half-Hanning (raised cosine) filter % (Scheirer, 1998) % Option related to the 'IIR' option: % mirenvelope(...,'Tau',t): time constant of low-pass filter in % seconds. % Default value: t = 0.02 s. % mirenvelope(...,'PostDecim',N) downsamples by a factor N>1, where % N is an integer, after the low-pass filtering. % Default value: N = 16 if 'PreDecim' is not used, else N = 1. % mirenvelope(...,'Trim'): trims the initial ascending phase of the % curves related to the transitory state. % % Options related to the 'Spectro' method: % mirenvelope(...,b) specifies whether the frequency range is further % decomposed into bands. Possible values: % b = 'Freq': no band decomposition (default value) % b = 'Mel': Mel-band decomposition % b = 'Bark': Bark-band decomposition % b = 'Cents': decompositions into cents % mirenvelope(...,'Frame',...) specifies the frame configuration. % Default value: length: .1 s, hop factor: 10 %. % mirenvelope(...,'UpSample',N) upsamples by a factor N>1, where % N is an integer. % Default value if 'UpSample' called: N = 2 % mirenvelope(...,'Complex') toggles on the 'Complex' method for the % spectral flux computation. % % Other available for all methods: % mirenvelope(...,'Sampling',r): resamples to rate r (in Hz). % 'Down' and 'Sampling' options cannot therefore be combined. % mirenvelope(...,'Halfwave'): performs a half-wave rectification. % mirenvelope(...,'Center'): centers the extracted envelope. % mirenvelope(...,'HalfwaveCenter'): performs a half-wave % rectification on the centered envelope. % mirenvelope(...,'Log'): computes the common logarithm (base 10) of % the envelope. % mirenvelope(...,'Mu',mu): computes the logarithm of the % envelope, before the eventual differentiation, using a mu-law % compression (Klapuri, 2006). % Default value for mu: 100 % mirenvelope(...,'Log'): computes the logarithm of the envelope. % mirenvelope(...,'Power'): computes the power (square) of the % envelope. % mirenvelope(...,'Diff'): computes the differentation of the % envelope, i.e., the differences between successive samples. % mirenvelope(...,'HalfwaveDiff'): performs a half-wave % rectification on the differentiated envelope. % mirenvelope(...,'Normal'): normalizes the values of the envelope by % fixing the maximum value to 1. % mirenvelope(...,'Lambda',l): sums the half-wave rectified envelope % with the non-differentiated envelope, using the respective % weight 0<l<1 and (1-l). (Klapuri et al., 2006) % mirenvelope(...,'Smooth',o): smooths the envelope using a moving % average of order o. % Default value when the option is toggled on: o=30 % mirenvelope(...,'Gauss',o): smooths the envelope using a gaussian % of standard deviation o samples. % Default value when the option is toggled on: o=30 % mirenvelope(...,'Klapuri06'): follows the model proposed in % (Klapuri et al., 2006). method.type = 'String'; method.choice = {'Filter','Spectro'}; method.default = 'Filter'; option.method = method; %% options related to 'Filter': hilb.key = 'Hilbert'; hilb.type = 'Boolean'; hilb.default = 0; option.hilb = hilb; decim.key = {'Decim','PreDecim'}; decim.type = 'Integer'; decim.default = 0; option.decim = decim; filter.key = 'FilterType'; filter.type = 'String'; filter.choice = {'IIR','HalfHann','Butter',0}; if isamir(orig,'mirenvelope') filter.default = 0; % no more envelope extraction, already done else filter.default = 'IIR'; end option.filter = filter; %% options related to 'IIR': tau.key = 'Tau'; tau.type = 'Integer'; tau.default = .02; option.tau = tau; zp.key = 'ZeroPhase'; % internal use: for manual filtfilt zp.type = 'Boolean'; if isamir(orig,'mirenvelope') zp.default = 0; else zp.default = NaN; end option.zp = zp; ds.key = {'Down','PostDecim'}; ds.type = 'Integer'; if isamir(orig,'mirenvelope') ds.default = 1; else ds.default = NaN; % 0 if 'PreDecim' is used, else 16 end ds.when = 'After'; ds.chunkcombine = 'During'; option.ds = ds; trim.key = 'Trim'; trim.type = 'Boolean'; trim.default = 0; trim.when = 'After'; option.trim = trim; %% Options related to 'Spectro': band.type = 'String'; band.choice = {'Freq','Mel','Bark','Cents'}; band.default = 'Freq'; option.band = band; up.key = {'UpSample'}; up.type = 'Integer'; up.default = 0; up.keydefault = 2; up.when = 'After'; option.up = up; complex.key = 'Complex'; complex.type = 'Boolean'; complex.default = 0; complex.when = 'After'; option.complex = complex; powerspectrum.key = 'PowerSpectrum'; powerspectrum.type = 'Boolean'; powerspectrum.default = 1; option.powerspectrum = powerspectrum; timesmooth.key = 'TimeSmooth'; timesmooth.type = 'Boolean'; timesmooth.default = 0; timesmooth.keydefault = 10; option.timesmooth = timesmooth; terhardt.key = 'Terhardt'; terhardt.type = 'Boolean'; terhardt.default = 0; option.terhardt = terhardt; frame.key = 'Frame'; frame.type = 'Integer'; frame.number = 2; frame.default = [.1 .1]; option.frame = frame; %% Options related to all methods: sampling.key = 'Sampling'; sampling.type = 'Integer'; sampling.default = 0; sampling.when = 'After'; option.sampling = sampling; hwr.key = 'Halfwave'; hwr.type = 'Boolean'; hwr.default = 0; hwr.when = 'After'; option.hwr = hwr; c.key = 'Center'; c.type = 'Boolean'; c.default = 0; c.when = 'After'; option.c = c; chwr.key = 'HalfwaveCenter'; chwr.type = 'Boolean'; chwr.default = 0; chwr.when = 'After'; option.chwr = chwr; mu.key = 'Mu'; mu.type = 'Integer'; mu.default = 0; mu.keydefault = 100; mu.when = 'After'; option.mu = mu; oplog.key = 'Log'; oplog.type = 'Boolean'; oplog.default = 0; oplog.when = 'After'; option.log = oplog; minlog.key = 'MinLog'; minlog.type = 'Integer'; minlog.default = 0; minlog.when = 'After'; option.minlog = minlog; oppow.key = 'Power'; oppow.type = 'Boolean'; oppow.default = 0; oppow.when = 'After'; option.power = oppow; diff.key = 'Diff'; diff.type = 'Integer'; diff.default = 0; diff.keydefault = 1; diff.when = 'After'; option.diff = diff; diffhwr.key = 'HalfwaveDiff'; diffhwr.type = 'Integer'; diffhwr.default = 0; diffhwr.keydefault = 1; diffhwr.when = 'After'; option.diffhwr = diffhwr; lambda.key = 'Lambda'; lambda.type = 'Integer'; lambda.default = 1; lambda.when = 'After'; option.lambda = lambda; aver.key = 'Smooth'; aver.type = 'Integer'; aver.default = 0; aver.keydefault = 30; aver.when = 'After'; option.aver = aver; gauss.key = 'Gauss'; gauss.type = 'Integer'; gauss.default = 0; gauss.keydefault = 30; gauss.when = 'After'; option.gauss = gauss; % iir.key = 'IIR'; % iir.type = 'Boolean'; % iir.default = 0; % iir.when = 'After'; % option.iir = iir; norm.key = 'Normal'; norm.type = 'String'; norm.choice = {0,1,'AcrossSegments'}; norm.default = 0; norm.keydefault = 1; norm.when = 'After'; option.norm = norm; presel.type = 'String'; presel.choice = {'Klapuri06'}; presel.default = 0; option.presel = presel; specif.option = option; specif.eachchunk = 'Normal'; specif.combinechunk = 'Concat'; specif.extensive = 1; varargout = mirfunction(@mirenvelope,orig,varargin,nargout,specif,@init,@main); function [x type] = init(x,option) type = 'mirenvelope'; if isamir(x,'mirscalar') %% Should return in other cases as well? return end if ischar(option.presel) && strcmpi(option.presel,'Klapuri06') option.method = 'Spectro'; end if not(isamir(x,'mirenvelope')) if strcmpi(option.method,'Filter') if isnan(option.zp) if strcmpi(option.filter,'IIR') option.zp = 1; else option.zp = 0; end end if option.zp == 1 x = mirenvelope(x,'ZeroPhase',2,'Down',1,... 'Tau',option.tau,'PreDecim',option.decim); end elseif strcmpi(option.method,'Spectro') x = mirspectrum(x,'Frame',option.frame.length.val,... option.frame.length.unit,... option.frame.hop.val,... option.frame.hop.unit,... option.frame.phase.val,... option.frame.phase.unit,... option.frame.phase.atend,... 'Window','hanning',option.band,... ...'dB', 'Power',option.powerspectrum,... 'TimeSmooth',option.timesmooth,... 'Terhardt',option.terhardt);%,'Mel'); end end function e = main(orig,option,postoption) if iscell(orig) orig = orig{1}; end if isamir(orig,'mirscalar') d = get(orig,'Data'); fp = get(orig,'FramePos'); for i = 1:length(d) for j = 1:length(d{i}) d{i}{j} = reshape(d{i}{j},size(d{i}{j},2),1,size(d{i}{j},3)); p{i}{j} = mean(fp{i}{j})'; end end e.downsampl = 0; e.hwr = 0; e.diff = 0; e.log = 0; e.method = 'Scalar'; e.phase = {{}}; e = class(e,'mirenvelope',mirtemporal(orig)); e = set(e,'Title','Envelope','Data',d,'Pos',p,... 'FramePos',{{p{1}{1}([1 end])}},... 'Sampling',{1/diff(p{1}{1}([1 2]))}); postoption.trim = 0; postoption.ds = 0; e = post(e,postoption); return end if isfield(option,'presel') && ischar(option.presel) && ... strcmpi(option.presel,'Klapuri06') option.method = 'Spectro'; postoption.up = 2; postoption.mu = 100; postoption.diffhwr = 1; postoption.lambda = .8; end if isfield(postoption,'ds') && isnan(postoption.ds) if option.decim postoption.ds = 0; else postoption.ds = 16; end end if not(isfield(option,'filter')) || not(ischar(option.filter)) e = post(orig,postoption); elseif strcmpi(option.method,'Spectro') d = get(orig,'Data'); fp = get(orig,'FramePos'); sr = get(orig,'Sampling'); ch = get(orig,'Channels'); ph = get(orig,'Phase'); for h = 1:length(d) sr{h} = 0; for i = 1:length(d{h}) if size(d{h}{i},3)>1 % Already in bands (channels in 3d dim) d{h}{i} = permute(sum(d{h}{i}),[2 1 3]); if ~isempty(ph) ph{h}{i} = permute(ph{h}{i},[2 1 3]); end else % Simple spectrogram, frequency range sent to 3d dim d{h}{i} = permute(d{h}{i},[2 3 1]); if ~isempty(ph) ph{h}{i} = permute(ph{h}{i},[2 3 1]); end end p{h}{i} = mean(fp{h}{i})'; if not(sr{h}) && size(fp{h}{i},2)>1 sr{h} = 1/(fp{h}{i}(1,2)-fp{h}{i}(1,1)); end end if not(sr{h}) warning('WARNING IN MIRENVELOPE: The frame decomposition did not succeed. Either the input is of too short duration, or the chunk size is too low.'); end ch{h} = (1:size(d{h}{1},3))'; end e.downsampl = 0; e.hwr = 0; e.diff = 0; e.log = 0; e.method = 'Spectro'; e.phase = ph; e = class(e,'mirenvelope',mirtemporal(orig)); e = set(e,'Title','Envelope','Data',d,'Pos',p,... 'Sampling',sr,'Channels',ch,'FramePos',{{fp{1}{1}([1 end])'}}); postoption.trim = 0; postoption.ds = 0; e = post(e,postoption); else if isnan(option.zp) if strcmpi(option.filter,'IIR') option.zp = 1; else option.zp = 0; end end if option.zp == 1 option.decim = 0; end e.downsampl = 1; e.hwr = 0; e.diff = 0; e.log = 0; e.method = option.filter; e.phase = {}; e = class(e,'mirenvelope',mirtemporal(orig)); e = purgedata(e); e = set(e,'Title','Envelope'); sig = get(e,'Data'); x = get(e,'Pos'); sr = get(e,'Sampling'); %disp('Extracting envelope...') d = cell(1,length(sig)); for k = 1:length(sig) if length(sig)==1 [state e] = gettmp(orig,e); else state = []; end if option.decim sr{k} = sr{k}/option.decim; end if strcmpi(option.filter,'IIR') a2 = exp(-1/(option.tau*sr{k})); % filter coefficient a = [1 -a2]; b = 1-a2; elseif strcmpi(option.filter,'HalfHann') a = 1; b = hann(sr{k}*.4); b = b(ceil(length(b)/2):end); elseif strcmpi(option.filter,'Butter') % From Timbre Toolbox w = 5 / ( sr{k}/2 ); [b,a] = butter(3, w); end d{k} = cell(1,length(sig{k})); for i = 1:length(sig{k}) sigi = sig{k}{i}; if option.zp == 2 sigi = flipdim(sigi,1); end if option.hilb try for h = 1:size(sigi,2) for j = 1:size(sigi,3) sigi(:,h,j) = hilbert(sigi(:,h,j)); end end catch disp('Signal Processing Toolbox does not seem to be installed. No Hilbert transform.'); end end sigi = abs(sigi); if option.decim dsigi = zeros(ceil(size(sigi,1)/option.decim),... size(sigi,2),size(sigi,3)); for f = 1:size(sigi,2) for c = 1:size(sigi,3) dsigi(:,f,c) = decimate(sigi(:,f,c),option.decim); end end sigi = dsigi; clear dsigi x{k}{i} = x{k}{i}(1:option.decim:end,:,:); end % tmp = filtfilt(1-a,[1 -a],sigi); % zero-phase IIR filter for smoothing the envelope % Manual filtfilt emptystate = isempty(state); tmp = zeros(size(sigi)); for c = 1:size(sigi,3) if emptystate [tmp(:,:,c) state(:,c,1)] = filter(b,a,sigi(:,:,c)); else [tmp(:,:,c) state(:,c,1)] = filter(b,a,sigi(:,:,c),... state(:,c,1)); end end tmp = max(tmp,0); % For security reason... if option.zp == 2 tmp = flipdim(tmp,1); end d{k}{i} = tmp; %td{k} = round(option.tau*sr{k}*1.5); end end e = set(e,'Data',d,'Pos',x,'Sampling',sr); if length(sig)==1 e = settmp(e,state); end if not(option.zp == 2) e = post(e,postoption); end end if isfield(option,'presel') && ischar(option.presel) && ... strcmpi(option.presel,'Klapuri06') e = mirsum(e,'Adjacent',10); end function e = post(e,postoption) if isempty(postoption) return end if isfield(postoption,'lambda') && not(postoption.lambda) postoption.lambda = 1; end d = get(e,'Data'); tp = get(e,'Time'); sr = get(e,'Sampling'); ds = get(e,'DownSampling'); ph = get(e,'Phase'); for k = 1:length(d) if isfield(postoption,'sampling') if postoption.sampling newsr = postoption.sampling; elseif isfield(postoption,'ds') && postoption.ds>1 newsr = sr{k}/postoption.ds; else newsr = sr{k}; end end if isfield(postoption,'up') && postoption.up [z,p,gain] = butter(6,10/newsr/postoption.up*2,'low'); [sos,g] = zp2sos(z,p,gain); Hd = dfilt.df2tsos(sos,g); end if isfield(postoption,'norm') && ... ischar(postoption.norm) && ... strcmpi(postoption.norm,'AcrossSegments') mdk = 0; for i = 1:length(d{k}) mdk = max(mdk,max(abs(d{k}{i}))); end end for i = 1:length(d{k}) if isfield(postoption,'sampling') && postoption.sampling if and(sr{k}, not(sr{k} == postoption.sampling)) dk = d{k}{i}; for j = 1:size(dk,3) if not(sr{k} == round(sr{k})) mirerror('mirenvelope','The ''Sampling'' postoption cannot be used after using the ''Down'' postoption.'); end rk(:,:,j) = resample(dk(:,:,j),postoption.sampling,sr{k}); end d{k}{i} = rk; tp{k}{i} = repmat((0:size(d{k}{i},1)-1)',... [1 1 size(tp{k}{i},3)])... /postoption.sampling + tp{k}{i}(1,:,:); if not(iscell(ds)) ds = cell(length(d)); end ds{k} = round(sr{k}/postoption.sampling); end elseif isfield(postoption,'ds') && postoption.ds>1 if not(postoption.ds == round(postoption.ds)) mirerror('mirenvelope','The ''Down'' sampling rate should be an integer.'); end ds = postoption.ds; tp{k}{i} = tp{k}{i}(1:ds:end,:,:); % Downsampling... d{k}{i} = d{k}{i}(1:ds:end,:,:); end if isfield(postoption,'sampling') if not(strcmpi(e.method,'Spectro')) && postoption.trim tdk = round(newsr*.1); d{k}{i}(1:tdk,:,:) = repmat(d{k}{i}(tdk,:,:),[tdk,1,1]); d{k}{i}(end-tdk+1:end,:,:) = repmat(d{k}{i}(end-tdk,:,:),[tdk,1,1]); end if postoption.log && ~get(e,'Log') d{k}{i} = log10(d{k}{i}); end if postoption.mu dki = max(0,d{k}{i}); mu = postoption.mu; dki = log(1+mu*dki)/log(1+mu); dki(~isfinite(d{k}{i})) = NaN; d{k}{i} = dki; end if postoption.power d{k}{i} = d{k}{i}.^2; end if postoption.up dki = zeros(size(d{k}{i},1).*postoption.up,... size(d{k}{i},2),size(d{k}{i},3)); dki(1:postoption.up:end,:,:) = d{k}{i}; dki = filter(Hd,[dki;... zeros(6,size(d{k}{i},2),size(d{k}{i},3))]); d{k}{i} = dki(1+ceil(6/2):end-floor(6/2),:,:); tki = zeros(size(tp{k}{i},1).*postoption.up,... size(tp{k}{i},2),... size(tp{k}{i},3)); dt = repmat((tp{k}{i}(2)-tp{k}{i}(1))... /postoption.up,... [size(tp{k}{i},1),1,1]); for j = 1:postoption.up tki(j:postoption.up:end,:,:) = tp{k}{i}+dt*(j-1); end tp{k}{i} = tki; newsr = sr{k}*postoption.up; end if (postoption.diffhwr || postoption.diff) && ... not(get(e,'Diff')) tp{k}{i} = tp{k}{i}(1:end-1,:,:); order = max(postoption.diffhwr,postoption.diff); if postoption.complex dph = diff(ph{k}{i},2); dph = dph/(2*pi);% - round(dph/(2*pi)); ddki = sqrt(d{k}{i}(3:end,:,:).^2 + d{k}{i}(2:end-1,:,:).^2 ... - 2.*d{k}{i}(3:end,:,:)... .*d{k}{i}(2:end-1,:,:)... .*cos(dph)); d{k}{i} = d{k}{i}(2:end,:,:); tp{k}{i} = tp{k}{i}(2:end,:,:); elseif order == 1 ddki = diff(d{k}{i},1,1); else b = firls(order,[0 0.9],[0 0.9*pi],'differentiator'); ddki = filter(b,1,... [repmat(d{k}{i}(1,:,:),[order,1,1]);... d{k}{i};... repmat(d{k}{i}(end,:,:),[order,1,1])]); ddki = ddki(order+1:end-order-1,:,:); end if postoption.diffhwr ddki = hwr(ddki); end d{k}{i} = (1-postoption.lambda)*d{k}{i}(1:end-1,:,:)... + postoption.lambda*sr{k}/10*ddki; end if postoption.aver y = filter(ones(1,postoption.aver),1,... [d{k}{i};zeros(postoption.aver,... size(d{k}{i},2),... size(d{k}{i},3))]); d{k}{i} = y(1+ceil(postoption.aver/2):... end-floor(postoption.aver/2),:,:); end if postoption.gauss sigma = postoption.gauss; gauss = 1/sigma/2/pi... *exp(- (-4*sigma:4*sigma).^2 /2/sigma^2); y = filter(gauss,1,[d{k}{i};zeros(4*sigma,1,size(d{k}{i},3))]); y = y(4*sigma:end,:,:); d{k}{i} = y(1:size(d{k}{i},1),:,:); end %if postoption.iir % a2 = exp(-1/(.4*sr{k})); % d{k}{i} = filter(1-a2,[1 -a2],d{k}{i}); % % [d{k}{i};zeros(postoption.filter,... % % size(d{k}{i},2),... % % size(d{k}{i},3))]); % %d{k}{i} = y(1+ceil(postoption.filter/2):... % % end-floor(postoption.filter/2),:,:); %end if postoption.chwr d{k}{i} = center(d{k}{i}); d{k}{i} = hwr(d{k}{i}); end if postoption.hwr d{k}{i} = hwr(d{k}{i}); end if postoption.c d{k}{i} = center(d{k}{i}); end if get(e,'Log') if postoption.minlog d{k}{i}(d{k}{i} < -postoption.minlog) = NaN; end else if postoption.norm == 1 d{k}{i} = d{k}{i}./repmat(max(abs(d{k}{i})),... [size(d{k}{i},1),1,1]); elseif ischar(postoption.norm) && ... strcmpi(postoption.norm,'AcrossSegments') d{k}{i} = d{k}{i}./repmat(mdk,[size(d{k}{i},1),1,1]); end end end end if isfield(postoption,'sampling') sr{k} = newsr; end end if isfield(postoption,'ds') && postoption.ds>1 e = set(e,'DownSampling',postoption.ds,'Sampling',sr); elseif isfield(postoption,'sampling') && postoption.sampling e = set(e,'DownSampling',ds,'Sampling',sr); elseif isfield(postoption,'up') && postoption.up e = set(e,'Sampling',sr); end if isfield(postoption,'sampling') if postoption.hwr e = set(e,'Halfwave',1); end if postoption.diff e = set(e,'Diff',1,'Halfwave',0,'Title','Differentiated envelope'); end if postoption.diffhwr e = set(e,'Diff',1,'Halfwave',1,'Centered',0); end if postoption.c e = set(e,'Centered',1); end if postoption.chwr e = set(e,'Halfwave',1,'Centered',1); end if postoption.log e = set(e,'Log',1); end end e = set(e,'Data',d,'Time',tp);
github
martinarielhartmann/mirtooloct-master
mirquery.m
.m
mirtooloct-master/MIRToolbox/@mirquery/mirquery.m
2,122
utf_8
69ba1787084c74f96a14a9faf74ff367
function res = mirquery(varargin) % r = mirquery(q,b), where % q is the analysis of one audio file and % b is the analysis of a folder of audio files, % according to the same mirtoolbox feature, % returns the name of the audio files in the database b in an % increasing distance to q with respect to the chosen feature. % r = mirquery(d), where % d is the distance between one audio file and a folder of audio % file, according to a mirtoolbox feature, % returns the name of the audio files in an increasing distance d. % % Optional argument: % mirquery(...,'Best',n) returns the name of the n closest audio % files. % mirquery(..,'Distance',d) specifies the distance to use. % Default value: d = 'Cosine' (cf. mirdist) [distfunc,nbout] = scanargin(varargin); if nargin<2 || not(isa(varargin{2},'mirdata')) returnval=0; dist = varargin{1}; name = get(dist,'Name2'); res.query.val = []; res.query.name = get(dist,'Name'); else returnval=1; query = varargin{1}; base = varargin{2}; name = get(base,'Name'); res.query.val = mirgetdata(query); res.query.name = get(query,'Name'); database = mirgetdata(base); dist = mirdist(query,base,distfunc); end datadist = mirgetdata(dist); [ordist order] = sort(datadist); order(isnan(ordist)) = []; nbout = min(nbout,length(order)); res.dist = ordist(1:nbout); if returnval res.val = database(order); else res.val = []; end res.name = name(order); res = class(res,'mirquery'); function [distfunc,nbout] = scanargin(v) distfunc = 'Cosine'; nbout=Inf; i = 1; while i <= length(v) arg = v{i}; if ischar(arg) && strcmpi(arg,'Distance') if length(v)>i && ischar(v{i+1}) i = i+1; distfunc = v{i}; end elseif ischar(arg) && strcmpi(arg,'Best') if length(v)>i && isnumeric(v{i+1}) i = i+1; nbout = v{i}; end %else % error('ERROR IN MIRQUERY: Syntax error. See help mirquery.'); end i = i+1; end
github
martinarielhartmann/mirtooloct-master
som_probability_gmm.m
.m
mirtooloct-master/somtoolbox/som_probability_gmm.m
2,782
utf_8
1d0b944d5fda0f9051e055d366e40be7
function [pd,Pdm,pmd] = som_probability_gmm(D, sM, K, P) %SOM_PROBABILITY_GMM Probabilities based on a gaussian mixture model. % % [pd,Pdm,pmd] = som_probability_gmm(D, sM, K, P) % % [K,P] = som_estimate_gmm(sM,D); % [pd,Pdm,pmd] = som_probability_gmm(D,sM,K,P); % som_show(sM,'color',pmd(:,1),'color',Pdm(:,1)) % % Input and output arguments: % D (matrix) size dlen x dim, the data for which the % (struct) data struct, probabilities are calculated % sM (struct) map struct % (matrix) size munits x dim, the kernel centers % K (matrix) size munits x dim, kernel width parameters % computed by SOM_ESTIMATE_GMM % P (matrix) size 1 x munits, a priori probabilities for each % kernel computed by SOM_ESTIMATE_GMM % % pd (vector) size dlen x 1, probability of each data vector in % terms of the whole gaussian mixture model % Pdm (matrix) size munits x dlen, probability of each vector in % terms of each kernel % pmd (matrix) size munits x dlen, probability of each vector to % have been generated by each kernel % % See also SOM_ESTIMATE_GMM. % Contributed to SOM Toolbox vs2, February 2nd, 2000 by Esa Alhoniemi % Copyright (c) by Esa Alhoniemi % http://www.cis.hut.fi/projects/somtoolbox/ % ecco 180298 juuso 050100 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % input arguments if isstruct(sM), M = sM.codebook; else M = sM; end [c dim] = size(M); if isstruct(D), D = D.data; end dlen = size(D,1); % reserve space for output variables pd = zeros(dlen,1); if nargout>=2, Pdm = zeros(c,dlen); end if nargout==3, pmd = zeros(c,dlen); end % the parameters of each kernel cCoeff = cell(c,1); cCoinv = cell(c,1); for m=1:c, co = diag(K(m,:)); cCoinv{m} = inv(co); cCoeff{m} = 1 / ((2*pi)^(dim/2)*det(co)^.5); end % go through the vectors one by one for i=1:dlen, x = D(i,:); % compute p(x|m) pxm = zeros(c,1); for m = 1:c, dx = M(m,:) - x; pxm(m) = cCoeff{m} * exp(-.5 * dx * cCoinv{m} * dx'); %pxm(m) = normal(dx, zeros(1,dim), diag(K(m,:))); end pxm(isnan(pxm(:))) = 0; % p(x|m) if nargin>=2, Pdm(:,i) = pxm; end % P(x) = P(x|M) = sum( P(m) * p(x|m) ) pd(i) = P*pxm; % p(m|x) = p(x|m) * P(m) / P(x) if nargout==3, pmd(:,i) = (P' .* pxm) / pd(i); end end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % subfunction normal % % computes probability of x when mean and covariance matrix % of a distribution are known function result = normal(x, mu, co) [l dim] = size(x); coinv = inv(co); coeff = 1 / ((2*pi)^(dim/2)*det(co)^.5); diff = x - mu; result = coeff * exp(-.5 * diff * coinv * diff');
github
martinarielhartmann/mirtooloct-master
som_clget.m
.m
mirtooloct-master/somtoolbox/som_clget.m
3,420
utf_8
34bca7118530f042e1b9d90718cf688a
function a = som_clget(sC, mode, ind) %SOM_CLGET Get properties of specified clusters. % % a = som_clget(sC, mode, ind) % % inds = som_clget(sC,'dinds',20); % col = som_clget(sC,'depth',[1 2 3 20 54]); % % Input and output arguments: % sC (struct) clustering struct % mode (string) what kind of property is requested % 'binds' (a union over) indeces of base clusters % belonging to the specified cluster(s) % 'dinds' (a union over) indeces of the data vectors % belonging to the specified cluster(s) % 'dlen' number of data vectors belonging % to each of the specified cluster(s) % 'depth' depths of the specified clusters % (depth of the root cluster is 0, % depth of its children are 1, etc.) % 'child' (a union over) children clusters % of specified cluster(s), including % the clusters themselves % 'base' base partitioning based on given % clusters % ind (vector) indeces of the clusters % % a (vector) the answer % % See also SOM_CLSTRUCT, SOM_CLPLOT. % Copyright (c) 2000 by the SOM toolbox programming team. % Contributed to SOM Toolbox on XXX by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 180800 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clen = size(sC.tree,1)+1; switch mode, case 'binds', a = []; for i=1:length(ind), a = [a, getbaseinds(sC.tree,ind(i))]; end a = unique(a); case 'dinds', b = []; for i=1:length(ind), b = [b, getbaseinds(sC.tree,ind(i))]; end b = unique(b); a = zeros(length(sC.base),1); for i=1:length(b), a(find(sC.base==b(i)))=1; end a = find(a); case 'dlen', a = zeros(length(ind),1); for i=1:length(ind), b = getbaseinds(sC.tree,ind(i)); for j=1:length(b), a(i) = a(i) + sum(sC.base==b(j)); end end case 'depth', a = getdepth(sC.tree); a = a(ind); case 'child', a = getchildren(sC.tree,ind); case 'base', a = sC.base*0; ind = -sort(-ind); for i=1:length(ind), a(som_clget(sC,'dinds',ind(i))) = ind(i); end end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ch = getchildren(Z,ind) clen = size(Z,1)+1; ch = ind; cho = ind; while any(cho), i = cho(1); cho = cho(2:end); j = Z(i-clen,1); k = Z(i-clen,2); if j>clen, cho(end+1) = j; end if k>clen, cho(end+1) = k; end ch(end+1) = j; ch(end+1) = k; end return; function binds = getbaseinds(Z,ind) clen = size(Z,1)+1; binds = ind; while binds(1)>clen, i = binds(1); binds = binds(2:end); j = Z(i-clen,1); k = Z(i-clen,2); if j>clen, binds = [j binds]; else binds(end+1) = j; end if k>clen, binds = [k binds]; else binds(end+1) = k; end end return; function depth = getdepth(Z) clen = size(Z,1)+1; depth = zeros(2*clen-1,1); ch = 2*clen-1; % active nodes while any(ch), c = ch(1); ch = ch(2:end); if c>clen & isfinite(Z(c-clen,3)), chc = Z(c-clen,1:2); % children of c depth(chc) = depth(c) + 1; % or +(ind==chc(1)) ch = [ch, chc]; end end return;
github
martinarielhartmann/mirtooloct-master
lvq3.m
.m
mirtooloct-master/somtoolbox/lvq3.m
5,951
utf_8
3d1d8a994701991b148ab22ae8bceb1a
function codebook = lvq3(codebook,data,rlen,alpha,win,epsilon) %LVQ3 trains codebook with LVQ3 -algorithm % % sM = lvq3(sM,D,rlen,alpha,win,epsilon) % % sM = lvq3(sM,sD,50*length(sM.codebook),0.05,0.2,0.3); % % Input and output arguments: % sM (struct) map struct, the class information must be % present on the first column of .labels field % D (struct) data struct, the class information must % be present on the first column of .labels field % rlen (scalar) running length % alpha (scalar) learning parameter, e.g. 0.05 % win (scalar) window width parameter, e.g. 0.25 % epsilon (scalar) relative learning parameter, e.g. 0.3 % % sM (struct) map struct, the trained codebook % % NOTE: does not take mask into account. % % For more help, try 'type lvq3', or check out online documentation. % See also LVQ1, SOM_SUPERVISED, SOM_SEQTRAIN. %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % lvq3 % % PURPOSE % % Trains codebook with the LVQ3 -algorithm (described below). % % SYNTAX % % sM = lvq3(sM, data, rlen, alpha, win, epsilon) % % DESCRIPTION % % Trains codebook with the LVQ3 -algorithm. Codebook contains a number % of vectors (mi, i=1,2,...,n) and so does data (vectors xj, j=1,2,...k). % Both vector sets are classified: vectors may have a class (classes are % set to data- or map -structure's 'labels' -field. For each xj the two % closest codebookvectors mc1 and mc2 are searched (euclidean distances % d1 and d2). xj must fall into the zone of window. That happens if: % % min(d1/d2, d2/d1) > s, where s = (1-win) / (1+win). % % If xj belongs to the same class of one of the mc1 and mc1, codebook % is updated as follows (let mc1 belong to the same class as xj): % mc1(t+1) = mc1(t) + alpha * (xj(t) - mc1(t)) % mc2(t+1) = mc2(t) - alpha * (xj(t) - mc2(t)) % If both mc1 and mc2 belong to the same class as xj, codebook is % updated as follows: % mc1(t+1) = mc1(t) + epsilon * alpha * (xj(t) - mc1(t)) % mc2(t+1) = mc2(t) + epsilon * alpha * (xj(t) - mc2(t)) % Otherwise updating is not performed. % % Argument 'rlen' tells how many times training -sequence is performed. % % Argument 'alpha' is recommended to be smaller than 0.1 and argument % 'epsilon' should be between 0.1 and 0.5. % % NOTE: does not take mask into account. % % REFERENCES % % Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, % Berlin, 1995, pp. 181-182. % % See also LVQ_PAK from http://www.cis.hut.fi/research/som_lvq_pak.shtml % % REQUIRED INPUT ARGUMENTS % % sM The data to be trained. % (struct) A map struct. % % data The data to use in training. % (struct) A data struct. % % rlen (integer) Running length of LVQ3 -algorithm. % % alpha (float) Learning rate used in training, e.g. 0.05 % % win (float) Window length, e.g. 0.25 % % epsilon (float) Relative learning parameter, e.g. 0.3 % % OUTPUT ARGUMENTS % % sM Trained data. % (struct) A map struct. % % EXAMPLE % % lab = unique(sD.labels(:,1)); % different classes % mu = length(lab)*5; % 5 prototypes for each % sM = som_randinit(sD,'msize',[mu 1]); % initial prototypes % sM.labels = [lab;lab;lab;lab;lab]; % their classes % sM = lvq1(sM,sD,50*mu,0.05); % use LVQ1 to adjust % % the prototypes % sM = lvq3(sM,sD,50*mu,0.05,0.2,0.3); % then use LVQ3 % % SEE ALSO % % lvq1 Use LVQ1 algorithm for training. % som_supervised Train SOM using supervised training. % som_seqtrain Train SOM with sequential algorithm. % Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas % Copyright (c) by Juha Parhankangas % http://www.cis.hut.fi/projects/somtoolbox/ % Juha Parhankangas 310100 juuso 020200 NOTFOUND = 1; cod = codebook.codebook; dat = data.data; c_class = codebook.labels(:,1); d_class = data.labels(:,1); s = (1-win)/(1+win); x = size(dat,1); y = size(cod,2); c_class=class2num(c_class); d_class=class2num(d_class); ONES=ones(size(cod,1),1); for t=1:rlen fprintf('\rTraining round: %d/%d',t,rlen); tmp = NaN*ones(x,y); for j=1:x flag = 0; mj = 0; mi = 0; no_NaN=find(~isnan(dat(j,:))); di=sqrt(sum([cod(:,no_NaN) - ONES*dat(j,no_NaN)].^2,2)); [foo, ind1] = min(di); di(ind1)=Inf; [foo,ind2] = min(di); %ind2=ind2+1; if d_class(j) & d_class(j)==c_class(ind1) mj = ind1; mi = ind2; if d_class(j)==c_class(ind2) flag = 1; end elseif d_class(j) & d_class(j)==c_class(ind2) mj = ind2; mi = ind1; if d_class(j)==c_class(ind1) flag = 1; end end if mj & mi if flag tmp([mj mi],:) = cod([mj mi],:) + epsilon*alpha*... (dat([j j],:) - cod([mj mi],:)); else tmp(mj,:) = cod(mj,:) + alpha * (dat(j,:)-cod(mj,:)); tmp(mi,:) = cod(mi,:) - alpha * (dat(j,:)-cod(mj,:)); end end end inds = find(~isnan(sum(tmp,2))); cod(inds,:) = tmp(inds,:); end fprintf(1,'\n'); sTrain = som_set('som_train','algorithm','lvq3',... 'data_name',data.name,... 'neigh','',... 'mask',ones(y,1),... 'radius_ini',NaN,... 'radius_fin',NaN,... 'alpha_ini',alpha,... 'alpha_type','constant',... 'trainlen',rlen,... 'time',datestr(now,0)); codebook.trainhist(end+1) = sTrain; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function nos = class2num(class) names = {}; nos = zeros(length(class),1); for i=1:length(class) if ~isempty(class{i}) & ~any(strcmp(class{i},names)) names=cat(1,names,class(i)); end end tmp_nos = (1:length(names))'; for i=1:length(class) if ~isempty(class{i}) nos(i,1) = find(strcmp(class{i},names)); end end
github
martinarielhartmann/mirtooloct-master
som_select.m
.m
mirtooloct-master/somtoolbox/som_select.m
20,295
utf_8
8d0b3f1b93252ad6250273831b30b5ad
function varargout=som_select(c_vect,plane_h,arg) %SOM_SELECT Manual selection of map units from a visualization. % % som_select(c_vect,[plane_h]) % % som_select(3) % som_select(sM.labels(:,1)) % % Input arguments ([]'s are optional): % c_vect (scalar) number of classes % (vector) initial class identifiers % (cell array) of strings, class names % (matrix) size * x 3, the color of each class % [plane_h] (scalar) handle of the plane (axes) to be marked. % By default, the current axes is used (GCA). % For the function to work, the plot in the % axes must have been created with the % SOM_CPLANE function (or SOM_SHOW). % % Launches a GUI which allows user to select nodes from plane by % clicking them or by choosing a region (a polygon). % % Middle mouse button: selects (or clears selection of) a single node % Left mouse button: lets user draw a polygon % Right mouse button: selects (or clears selection of) the units % inside the polygon % % From the GUI, the color (class) is selected as well as whether % but buttons select or clear the selection from the units. The % buttons on the bottom have the following actions: % % 'OK' Assigns the class identifiers to the 'ans' variable in % workspace. The value is an array of class identifiers: % strings (cellstr) if the c_vect was an array of % strings, a vector otherwise. % 'Clear' Removes marks from the plane. % 'Close' Closes the application. % % See also SOM_SHOW, SOM_CPLANE. % Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas % Copyright (c) by Juha Parhankangas % http://www.cis.hut.fi/projects/somtoolbox/ % Juha Parhankangas 050100, juuso 010200 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% input arguments if nargin < 2, plane_h = gca; end if(isempty(gcbo)), arg='start'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% action switch arg case 'start' patch_h=find_patch(plane_h); lattice=getfield(size(get(patch_h,'XData')),{1}); msize(1)=floor(getfield(get(plane_h,'YLim'),{2})); msize(2)=floor(getfield(get(plane_h,'XLim'),{2})-0.5); if lattice==6 lattice='hexa'; else lattice='rect'; end if any(strcmp(get(patch_h,'Tag'),{'planeBar','planePie'})) tmp_dim=size(get(patch_h,'XData'),2)/prod(msize); tmp_xdata=get(patch_h,'XData'); tmp_x=tmp_xdata(:,(msize(1)*(msize(2)-1)+2)*tmp_dim); if floor(tmp_x(1)) ~= round(tmp_x(1)) lattice = 'hexa'; else lattice = 'rect'; end elseif strcmp(get(patch_h,'Tag'),'planePlot') tmp_lines_h=get(gca,'Children'); test_x=mean(get(tmp_lines_h(2),'XData')); if round(test_x) ~= floor(test_x) lattice = 'hexa'; else lattice = 'rect'; end form=0.5*vis_patch('hexa'); l = size(form,1); nx = repmat(form(:,1),1,prod(msize)); ny = repmat(form(:,2),1,prod(msize)); x=reshape(repmat(1:msize(2),l*msize(1),1),l,prod(msize)); y=repmat(repmat(1:msize(1),l,1),1,msize(2)); if strcmp(lattice,'hexa') t = find(~rem(y(1,:),2)); x(:,t)=x(:,t)+.5; end x=x+nx; y=y+ny; colors=reshape(ones(prod(msize),1)*[NaN NaN NaN],... [1 prod(msize) 3]); v=caxis; patch_h=patch(x,y,colors,... 'EdgeColor','none',... 'ButtonDownFcn',... 'som_select([],[],''click'')',... 'Tag','planePlot'); set([gca gcf],'ButtonDownFcn','som_select([],[],''click'')'); caxis(v) end c_colors = []; if iscell(c_vect) [c_vect,c_names,c_classes]=class2num(c_vect); if length(c_classes)<prod(msize), c_classes = zeros(prod(msize),1); end else if all(size(c_vect)>1), c_colors = c_vect; c_names = 1:size(c_vect,1); c_vect = size(c_vect,1); c_classes = zeros(prod(msize),1); elseif length(c_vect)==prod(msize), c_classes = c_vect; u = unique(c_classes(isfinite(c_classes) & c_classes>0)); c_names = u; c_vect = length(u); elseif length(c_vect)>1, c_names = c_vect; c_vect = length(c_vect); c_classes = zeros(prod(msize),1); elseif length(c_vect)==1, c_names = 1:c_vect; c_classes = zeros(prod(msize),1); end end udata.lattice=lattice; udata.patch_h=patch_h; udata.plane_h=plane_h; udata.type=get(udata.patch_h,'Tag'); udata.msize=msize; set(patch_h,'UserData',udata); if strcmp(udata.type,'planePlot') set([gca gcf],'UserData',udata); end str=cat(2,'som_select([],[],''click'')'); set(patch_h,'ButtonDownFcn',str); draw_colorselection(c_names,c_colors); tmp_data=findobj(get(0,'Children'),'Tag','SELECT_GUI'); tmp_data=get(tmp_data,'UserData'); tmp_data.c_names=c_names; tmp_data.mat=reshape(c_classes,msize); tmp_data.patch_h=patch_h; tmp_data.plane_h=plane_h; tmp_data.type=get(udata.patch_h,'Tag'); tmp_data.lattice=lattice; tmp_data.coords=[]; tmp_data.poly_h=[]; tmp_data.msize=msize; tmp_data.mode='select'; set(tmp_data.fig_h,'UserData',tmp_data); draw_classes; case 'click' switch get(gcf,'SelectionType') case 'open' return; case {'normal','alt'} draw_poly; case 'extend' click; end case 'choose' draw_colorselection(0,0,'choose'); case 'close' close_gui; case 'clear' clear_plane; case 'rb' rb_control; case 'ret_mat' gui=findobj(get(0,'Children'),'Tag','SELECT_GUI'); gui=get(gui,'UserData'); mat=reshape(gui.mat,prod(size(gui.mat)),1); if ~isempty(gui.c_names) if isnumeric(gui.c_names), tmp=zeros(length(mat),1); else tmp=cell(length(mat),1); end for i=1:length(gui.c_names) inds=find(mat==i); tmp(inds)=gui.c_names(i); end mat=tmp; end varargout{1}=mat; %gui.mat=zeros(size(gui.mat)); %set(gui.fig_h,'UserData',gui); %h=findobj(get(gui.plane_h,'Children'),'Tag','SEL_PATCH'); %delete(h); end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function rb_control; h=findobj(get(gcf,'Children'),'Style','radiobutton'); set(h,'Value',0); set(gcbo,'Value',1); udata=get(gcf,'UserData'); if strcmp(get(gcbo,'Tag'),'Radiobutton1') udata.mode='select'; else udata.mode='clear'; end set(gcf,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function clear_plane h=findobj(get(0,'Children'),'Tag','SELECT_GUI'); gui=get(h,'UserData'); if strcmp(get(gui.patch_h,'Tag'),'planePlot') colors=reshape(get(gui.patch_h,'FaceVertexCData'),[prod(gui.msize) 3]); colors(:,:)=NaN; set(gui.patch_h,'FaceVertexCData',colors); end h=findobj(get(gui.plane_h,'Children'),'Tag','SEL_PATCH'); gui.mat=zeros(gui.msize); set(gui.fig_h,'UserData',gui); delete(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function click udata=get(gcbo,'UserData'); udata=get(udata.patch_h,'UserData'); coords=get(gca,'CurrentPoint'); row=round(coords(1,2)); if row > udata.msize(1), row = udata.msize(1); end if row < 1, row = 1; end if any(strcmp(udata.lattice,{'hexa','hexaU'})) & ~mod(row,2), col=floor(coords(1,1))+0.5; if col > udata.msize(2)+0.5, col=udata.msize(2)+0.5; end else col=round(coords(1,1)); if col > udata.msize(2), col=udata.msize(2); end end if col < 1, col = 1; end if strcmp(udata.type,'planePlot') if ~mod(row,2) & strcmp(udata.lattice,'hexa'), col=round(col-0.5); end ind=sub2ind(udata.msize,row,col); colors=reshape(get(udata.patch_h,'FaceVertexCData'),[prod(udata.msize) 3]); gui=findobj(get(0,'Children'),'Tag','SELECT_GUI'); gui=get(gui,'UserData'); if ~isempty(gui.curr_col) & all(~isnan(colors(ind,1,:))), if ~strcmp(gui.mode,'clear') & ~all(gui.curr_col == colors(ind,:)) colors(ind,:)=gui.curr_col; gui.mat(row,col)=gui.class; else colors(ind,:)=[NaN NaN NaN]; gui.mat(row,col)=0; end elseif strcmp(gui.mode,'clear') colors(ind,:)=[NaN NaN NaN]; gui.mat(row,col)=0; elseif isempty(gui.curr_col) return; else gui.mat(row,col)=gui.class; colors(ind,:)=gui.curr_col; end set(udata.patch_h,'FaceVertexCData',colors); set(gui.fig_h,'UserData',gui); return; end if any(strcmp(udata.type,{'planePie','planeBar'})) [x,y]=pol2cart(0:0.1:2*pi,0.5); coords=[x';0.5]*0.7; coords(:,2)=[y';0]*0.7; elseif strcmp(udata.lattice,'hexa'); coords=0.7*vis_patch('hexa'); else coords=0.7*vis_patch('rect'); end coords(:,1)=coords(:,1)+col; coords(:,2)=coords(:,2)+row; if ~mod(row,2) & strcmp(udata.lattice,'hexa'), col=round(col-0.5); end hold on; if gco == udata.patch_h gui=findobj(get(0,'Children'),'Tag','SELECT_GUI'); gui=get(gui,'UserData'); if isnan(gui.curr_col) | strcmp(gui.mode,'clear'), return; end h=fill(coords(:,1),coords(:,2),gui.curr_col); str=cat(2,'som_select([],[],''click'')'); set(h,'ButtonDownFcn',str,'Tag','SEL_PATCH'); tmp.patch_h=udata.patch_h; set(h,'UserData',tmp); gui.mat(row,col)=gui.class; set(gui.fig_h,'UserData',gui); else gui=findobj(get(0,'Children'),'Tag','SELECT_GUI'); gui=get(gui,'UserData'); if ~all(get(gcbo,'FaceColor') == gui.curr_col) & ~strcmp(gui.mode,'clear'), if ~isnan(gui.curr_col), set(gcbo,'FaceColor',gui.curr_col); gui.mat(row,col) = gui.class; end else gui.mat(row,col)=0; delete(gco); end set(gui.fig_h,'UserData',gui); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function draw_colorselection(varargin) if length(varargin)==2, if length(varargin{1})==1, n = varargin{1}; names = 1:n; else n = length(varargin{1}); names = varargin{1}; end colors = varargin{2}; shape=[0.5 -0.5;0.5 0.5;1.5 0.5;1.5 -0.5]; rep_x=repmat(shape(:,1),1,n); rep_y=repmat(shape(:,2),1,n); for i=0:getfield(size(rep_y,2))-1, rep_x(:,i+1)=rep_x(:,i+1)+i; end if isempty(colors), colors=jet(n); end data=som_select_gui; data.colors=colors; data.curr_col=NaN; data.class=0; set(0,'CurrentFigure',data.fig_h); hold on; tmp=fill(rep_x,rep_y,0.8); for i=1:n set(tmp(i),... 'EdgeColor',[0 0 0],... 'FaceColor',colors(i,:),... 'ButtonDownFcn','som_select([],0,''choose'');'); end axis('equal'); axis('on'); set(gca,'XTick',1:n,'XTickLabel',names,'XAxisLocation','top'); set(data.a_h,'YLim',[-0.5,0.5],... 'XLim',[0.5 n+0.5],... 'YTickLabel',''); set(data.fig_h,'UserData',data); elseif strcmp(varargin{3},'choose') udata=get(gcf,'UserData'); if strcmp(get(gcbo,'Selected'),'off') old=findobj(get(gca,'Children'),'Type','patch'); set(old,'Selected','off'); set(gcbo,'Selected','on'); udata.curr_col=udata.colors(round(mean(get(gcbo,'XData'))),:); udata.class=mean(get(gcbo,'XData')); else set(gcbo,'Selected','off'); udata.curr_col=NaN; udata.class=0; end set(gcf,'UserData',udata); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data=som_select_gui() a = figure('Color',[0.8 0.8 0.8], ... 'PaperType','a4letter', ... 'Position',[586 584 560 210], ... 'Tag','SELECT_GUI'); data.fig_h=a; b = axes('Parent',a, ... 'Box','on', ... 'CameraUpVector',[0 1 0], ... 'Color',[1 1 1], ... 'DataAspectRatioMode','manual', ... 'PlotBoxAspectRatio',[20 1 2], ... 'PlotBoxAspectRatioMode','manual', ... 'Position',[0.13 0.11 0.775 0.815], ... 'Tag','Axes1', ... 'WarpToFill','off', ... 'XColor',[0 0 0], ... 'XLimMode','manual', ... 'YColor',[0 0 0], ... 'YLimMode','manual', ... 'YTickLabelMode','manual', ... 'ZColor',[0 0 0]); data.a_h=b; b = uicontrol('Parent',a, ... 'Units','points', ... 'BackgroundColor',[0.701961 0.701961 0.701961], ... 'Callback','som_select([],[],''close'')', ... 'FontWeight','demi', ... 'Position',[150 12 50 20], ... 'String','CLOSE', ... 'Tag','Pushbutton1'); b = uicontrol('Parent',a, ... 'Units','points', ... 'BackgroundColor',[0.701961 0.701961 0.701961], ... 'Callback','som_select([],0,''ret_mat'')',... 'FontWeight','demi', ... 'Position',[365 12 50 20], ... 'String','OK', ... 'Tag','Pushbutton2'); b = uicontrol('Parent',a, ... 'Units','points', ... 'BackgroundColor',[0.701961 0.701961 0.701961], ... 'Callback','som_select([],0,''clear'')',... 'FontWeight','demi', ... 'Position',[257.5 12 50 20], ... 'String','CLEAR', ... 'Tag','Pushbutton3'); b = uicontrol('Parent',a, ... 'Units','points', ... 'Position',[50 27 17 16], ... 'Callback','som_select([],[],''rb'')',... 'Style','radiobutton', ... 'Tag','Radiobutton1', ... 'Value',1); b = uicontrol('Parent',a, ... 'Units','points', ... 'BackgroundColor',[0.701961 0.701961 0.701961], ... 'Callback','som_select([],[],''rb'')',... 'Position',[50 7 17 16], ... 'Style','radiobutton', ... 'Tag','Radiobutton2'); b = uicontrol('Parent',a, ... 'Units','points', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',9, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[72 25 28 15], ... 'String','Select', ... 'Style','text', ... 'Tag','StaticText1'); b = uicontrol('Parent',a, ... 'Units','points', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',9, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[72 7 25 13.6], ... 'String','Clear', ... 'Style','text', ... 'Tag','StaticText2'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function close_gui udata=get(get(gcbo,'Parent'),'UserData'); if strcmp(udata.type,'planePlot'); set(udata.plane_h,'ButtonDownFcn','','UserData',[]); set(get(udata.plane_h,'Parent'),'ButtonDownFcn',''); delete(udata.patch_h); return; end h=findobj(get(udata.plane_h,'Children'),'Tag','SEL_PATCH'); set(udata.patch_h,'ButtonDownFcn','','UserData',[]); delete(h); close(udata.fig_h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function draw_poly udata=get(findobj(get(0,'Children'),'Tag','SELECT_GUI'),'UserData'); if isempty(udata.coords) & strcmp(get(gcf,'SelectionType'),'alt') return; end coords(1,1) = getfield(get(gca,'CurrentPoint'),{3}); coords(1,2) = getfield(get(gca,'CurrentPoint'),{1}); udata.coords = cat(1,udata.coords,coords); delete(udata.poly_h); subplot(udata.plane_h); hold on; switch get(gcf,'SelectionType'); case 'normal' udata.poly_h=plot(udata.coords(:,2),udata.coords(:,1),'black',... 'ButtonDownFcn','som_select([],[],''click'')',... 'LineWidth',2); set(udata.fig_h,'UserData',udata); case 'alt' udata.coords=cat(1,udata.coords,udata.coords(1,:)); udata.poly_h=plot(udata.coords(:,2),udata.coords(:,1),'black',... 'LineWidth',2); delete(udata.poly_h); if ~isnan(udata.curr_col) tmp=sort(repmat((1:udata.msize(1))',udata.msize(2),1)); tmp(:,2)=repmat((1:udata.msize(2))',udata.msize(1),1); tmp2=tmp; if strcmp(udata.type,'planePlot') in=find(inpolygon(tmp(:,2),tmp(:,1),... udata.coords(:,2),udata.coords(:,1))); row=tmp2(in,1); col=tmp2(in,2); in=sub2ind(udata.msize,row,col); colors=reshape(get(udata.patch_h,'FaceVertexCData'),... [prod(udata.msize) 3]); if ~isnan(udata.curr_col) & ~strcmp(udata.mode,'clear') colors(in,:)=ones(length(in),1)*udata.curr_col; udata.mat(row,col)=udata.class; elseif strcmp(udata.mode,'clear') colors(in,:)=[NaN NaN NaN]; udata.mat(row,col)=0; end udata.poly_h=[]; udata.coords=[]; set(udata.patch_h,'FaceVertexCData',colors); set(udata.fig_h,'UserData',udata); return; end if strcmp(udata.lattice,'hexa'); t=find(~rem(tmp(:,1),2)); tmp(t,2)=tmp(t,2)+0.5; if any(strcmp(get(udata.patch_h,'Tag'),{'planeC','planeU'})) p=0.7*vis_patch('hexa'); else [x,y]=pol2cart(0:0.1:2*pi,0.5); p=[x';0.5]*0.7; p(:,2)=[y';0]*0.7; end else if any(strcmp(get(udata.patch_h,'Tag'),{'planeC','planeU'})) p=0.7*vis_patch('rect'); else [x,y]=pol2cart(0:0.1:2*pi,0.5); p=[x';0.5]*0.7; p(:,2)=[y';0]*0.7; end end in=find(inpolygon(tmp(:,2),tmp(:,1),udata.coords(:,2),udata.coords(:,1))); set(udata.fig_h,'UserData',udata); if strcmp(udata.mode,'select') remove_selpatches; udata=get(udata.fig_h,'UserData'); for i=1:length(in) udat.patch_h=udata.patch_h; h=patch(p(:,1)+tmp(in(i),2),p(:,2)+tmp(in(i),1),... udata.curr_col,... 'EdgeColor','black',... 'ButtonDownFcn','som_select([],[],''click'')', ... 'Tag','SEL_PATCH',... 'UserData',udat); udata.mat(tmp2(in(i),1),tmp2(in(i),2))=udata.class; end else remove_selpatches; udata=get(udata.fig_h,'UserData'); %h=findobj(get(udata.plane_h,'Children'),'Tag','SEL_PATCH'); %for i=1:length(h) % if all(get(h(i),'FaceColor')==udata.curr_col) & ... % inpolygon(mean(get(h(i),'XData')),mean(get(h(i),'YData')),... % udata.coords(:,2),udata.coords(:,1)) % coords=[floor(mean(get(h(i),'YData')))... % floor(mean(get(h(i),'XData')))]; % udata.mat(coords(1),coords(2))=0; % delete(h(i)); % end %end end end udata.poly_h=[]; udata.coords=[]; set(udata.fig_h,'UserData',udata); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function remove_selpatches udata=get(findobj(get(0,'Children'),'Tag','SELECT_GUI'),'UserData'); h=findobj(get(udata.plane_h,'Children'),'Tag','SEL_PATCH'); for i=1:length(h) if inpolygon(mean(get(h(i),'XData')),mean(get(h(i),'YData')),... udata.coords(:,2),udata.coords(:,1)); coords=[floor(mean(get(h(i),'YData')))... floor(mean(get(h(i),'XData')))]; udata.mat(coords(1),coords(2))=0; delete(h(i)); end end set(udata.fig_h,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [n,names,classes]=class2num(class) names = {}; classes = zeros(length(class),1); for i=1:length(class) if ~isempty(class{i}), a = find(strcmp(class{i},names)); if isempty(a), names=cat(1,names,class(i)); classes(i) = length(names); else classes(i) = a; end end end n=length(names); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h=find_patch(a_h) h=[]; tags={'planeC','planeU','planePie','planeBar','planePlot'}; for i=1:5 if ~isempty(findobj(get(a_h,'Children'),'Tag',tags{i})) h=findobj(get(gca,'Children'),'Tag',tags{i}); if length(h) > 1 h=h(1); end return; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function draw_classes udata=get(findobj(get(0,'Children'),'Tag','SELECT_GUI'), ... 'UserData'); figure(get(udata.plane_h,'Parent')) subplot(udata.plane_h); colors=zeros(prod(udata.msize),3)+NaN; c_map=jet(length(udata.c_names)); inds = find(udata.mat); for i=1:length(inds), colors(inds(i),:) = c_map(udata.mat(inds(i)),:); end if strcmp(udata.type,'planePlot'), set(udata.patch_h,'FaceVertexCData',colors); set(udata.fig_h,'UserData',udata); else hold on co = som_vis_coords(udata.lattice,udata.msize); if any(strcmp(get(udata.patch_h,'Tag'),{'planeC','planeU'})) p=0.7*vis_patch(udata.lattice); else [x,y]=pol2cart(0:0.1:2*pi,0.5); p=[x';0.5]*0.7; p(:,2)=[y';0]*0.7; end for i=1:length(inds), udat.patch_h=udata.patch_h; h=patch(p(:,1)+co(inds(i),1),p(:,2)+co(inds(i),2),... colors(inds(i),:),... 'EdgeColor','black',... 'ButtonDownFcn','som_select([],[],''click'')', ... 'Tag','SEL_PATCH',... 'UserData',udat); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
martinarielhartmann/mirtooloct-master
som_unit_coords.m
.m
mirtooloct-master/somtoolbox/som_unit_coords.m
8,082
utf_8
1656dc53e5cdea92d6870107451337dd
function Coords = som_unit_coords(topol,lattice,shape) %SOM_UNIT_COORDS Locations of units on the SOM grid. % % Co = som_unit_coords(topol, [lattice], [shape]) % % Co = som_unit_coords(sMap); % Co = som_unit_coords(sMap.topol); % Co = som_unit_coords(msize, 'hexa', 'cyl'); % Co = som_unit_coords([10 4 4], 'rect', 'toroid'); % % Input and output arguments ([]'s are optional): % topol topology of the SOM grid % (struct) topology or map struct % (vector) the 'msize' field of topology struct % [lattice] (string) map lattice, 'rect' by default % [shape] (string) map shape, 'sheet' by default % % Co (matrix, size [munits k]) coordinates for each map unit % % For more help, try 'type som_unit_coords' or check out online documentation. % See also SOM_UNIT_DISTS, SOM_UNIT_NEIGHS. %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_unit_coords % % PURPOSE % % Returns map grid coordinates for the units of a Self-Organizing Map. % % SYNTAX % % Co = som_unit_coords(sTopol); % Co = som_unit_coords(sM.topol); % Co = som_unit_coords(msize); % Co = som_unit_coords(msize,'hexa'); % Co = som_unit_coords(msize,'rect','toroid'); % % DESCRIPTION % % Calculates the map grid coordinates of the units of a SOM based on % the given topology. The coordinates are such that they can be used to % position map units in space. In case of 'sheet' shape they can be % (and are) used to measure interunit distances. % % NOTE: for 'hexa' lattice, the x-coordinates of every other row are shifted % by +0.5, and the y-coordinates are multiplied by sqrt(0.75). This is done % to make distances of a unit to all its six neighbors equal. It is not % possible to use 'hexa' lattice with higher than 2-dimensional map grids. % % 'cyl' and 'toroid' shapes: the coordinates are initially determined as % in case of 'sheet' shape, but are then bended around the x- or the % x- and then y-axes to get the desired shape. % % POSSIBLE BUGS % % I don't know if the bending operation works ok for high-dimensional % map grids. Anyway, if anyone wants to make a 4-dimensional % toroid map, (s)he deserves it. % % REQUIRED INPUT ARGUMENTS % % topol Map grid dimensions. % (struct) topology struct or map struct, the topology % (msize, lattice, shape) of the map is taken from % the appropriate fields (see e.g. SOM_SET) % (vector) the vector which gives the size of the map grid % (msize-field of the topology struct). % % OPTIONAL INPUT ARGUMENTS % % lattice (string) The map lattice, either 'rect' or 'hexa'. Default % is 'rect'. 'hexa' can only be used with 1- or % 2-dimensional map grids. % shape (string) The map shape, either 'sheet', 'cyl' or 'toroid'. % Default is 'sheet'. % % OUTPUT ARGUMENTS % % Co (matrix) coordinates for each map units, size is [munits k] % where k is 2, or more if the map grid is higher % dimensional or the shape is 'cyl' or 'toroid' % % EXAMPLES % % Simplest case: % Co = som_unit_coords(sTopol); % Co = som_unit_coords(sMap.topol); % Co = som_unit_coords(msize); % Co = som_unit_coords([10 10]); % % If topology is given as vector, lattice is 'rect' and shape is 'sheet' % by default. To change these, you can use the optional arguments: % Co = som_unit_coords(msize, 'hexa', 'toroid'); % % The coordinates can also be calculated for high-dimensional grids: % Co = som_unit_coords([4 4 4 4 4 4]); % % SEE ALSO % % som_unit_dists Calculate interunit distance along the map grid. % som_unit_neighs Calculate neighborhoods of map units. % Copyright (c) 1997-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 1.0beta juuso 110997 % Version 2.0beta juuso 101199 070600 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Check arguments error(nargchk(1, 3, nargin)); % default values sTopol = som_set('som_topol','lattice','rect'); % topol if isstruct(topol), switch topol.type, case 'som_map', sTopol = topol.topol; case 'som_topol', sTopol = topol; end elseif iscell(topol), for i=1:length(topol), if isnumeric(topol{i}), sTopol.msize = topol{i}; elseif ischar(topol{i}), switch topol{i}, case {'rect','hexa'}, sTopol.lattice = topol{i}; case {'sheet','cyl','toroid'}, sTopol.shape = topol{i}; end end end else sTopol.msize = topol; end if prod(sTopol.msize)==0, error('Map size is 0.'); end % lattice if nargin>1 & ~isempty(lattice) & ~isnan(lattice), sTopol.lattice = lattice; end % shape if nargin>2 & ~isempty(shape) & ~isnan(shape), sTopol.shape = shape; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Action msize = sTopol.msize; lattice = sTopol.lattice; shape = sTopol.shape; % init variables if length(msize)==1, msize = [msize 1]; end munits = prod(msize); mdim = length(msize); Coords = zeros(munits,mdim); % initial coordinates for each map unit ('rect' lattice, 'sheet' shape) k = [1 cumprod(msize(1:end-1))]; inds = [0:(munits-1)]'; for i = mdim:-1:1, Coords(:,i) = floor(inds/k(i)); % these are subscripts in matrix-notation inds = rem(inds,k(i)); end % change subscripts to coordinates (move from (ij)-notation to (xy)-notation) Coords(:,[1 2]) = fliplr(Coords(:,[1 2])); % 'hexa' lattice if strcmp(lattice,'hexa'), % check if mdim > 2, error('You can only use hexa lattice with 1- or 2-dimensional maps.'); end % offset x-coordinates of every other row inds_for_row = (cumsum(ones(msize(2),1))-1)*msize(1); for i=2:2:msize(1), Coords(i+inds_for_row,1) = Coords(i+inds_for_row,1) + 0.5; end end % shapes switch shape, case 'sheet', if strcmp(lattice,'hexa'), % this correction is made to make distances to all % neighboring units equal Coords(:,2) = Coords(:,2)*sqrt(0.75); end case 'cyl', % to make cylinder the coordinates must lie in 3D space, at least if mdim<3, Coords = [Coords ones(munits,1)]; mdim = 3; end % Bend the coordinates to a circle in the plane formed by x- and % and z-axis. Notice that the angle to which the last coordinates % are bended is _not_ 360 degrees, because that would be equal to % the angle of the first coordinates (0 degrees). Coords(:,1) = Coords(:,1)/max(Coords(:,1)); Coords(:,1) = 2*pi * Coords(:,1) * msize(2)/(msize(2)+1); Coords(:,[1 3]) = [cos(Coords(:,1)) sin(Coords(:,1))]; case 'toroid', % NOTE: if lattice is 'hexa', the msize(1) should be even, otherwise % the bending the upper and lower edges of the map do not match % to each other if strcmp(lattice,'hexa') & rem(msize(1),2)==1, warning('Map size along y-coordinate is not even.'); end % to make toroid the coordinates must lie in 3D space, at least if mdim<3, Coords = [Coords ones(munits,1)]; mdim = 3; end % First bend the coordinates to a circle in the plane formed % by x- and z-axis. Then bend in the plane formed by y- and % z-axis. (See also the notes in 'cyl'). Coords(:,1) = Coords(:,1)/max(Coords(:,1)); Coords(:,1) = 2*pi * Coords(:,1) * msize(2)/(msize(2)+1); Coords(:,[1 3]) = [cos(Coords(:,1)) sin(Coords(:,1))]; Coords(:,2) = Coords(:,2)/max(Coords(:,2)); Coords(:,2) = 2*pi * Coords(:,2) * msize(1)/(msize(1)+1); Coords(:,3) = Coords(:,3) - min(Coords(:,3)) + 1; Coords(:,[2 3]) = Coords(:,[3 3]) .* [cos(Coords(:,2)) sin(Coords(:,2))]; end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function C = bend(cx,cy,angle,xishexa) dx = max(cx) - min(cx); if dx ~= 0, % in case of hexagonal lattice it must be taken into account that % coordinates of every second row are +0.5 off to the right if xishexa, dx = dx-0.5; end cx = angle*(cx - min(cx))/dx; end C(:,1) = (cy - min(cy)+1) .* cos(cx); C(:,2) = (cy - min(cy)+1) .* sin(cx); % end of bend %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
martinarielhartmann/mirtooloct-master
vis_footnote.m
.m
mirtooloct-master/somtoolbox/vis_footnote.m
3,091
utf_8
bdff65a1392daa41414831644ccc8235
function h=vis_footnote(txt) % VIS_FOOTNOTE Adds a movable text to the current figure % % h = vis_footnote(T) % % Input and output arguments ([]'s are optional) % [T] (string) text to be written % (scalar) font size to use in all strings % % h (vector) handles to axis objects created by this function % % This function sets a text to the current figure. If T is a string, % it's written as it is to the same place. If T is a scalar, the font % size of all text objects created by this function are changed to the % pointsize T. If no input argument is given the function only returns % the handles to all objects created by this function. The texts may % be dragged to a new location at any time using mouse. Note that the % current axis will be the parent of the text object after dragging. % % String 'Info' is set to the Tag property field of the objects. % % EXAMPLES % % % add movable texts to the current figure and change their % % fontsize to 20 points % vis_footnote('Faa'); vis_footnote('Foo'); vis_footnote(20); % % % delete all objects created by this function from the current figure % delete(vis_footnote); % % See also SOM_SHOW. % Copyright (c) 1997-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta Johan 080698 %% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% error(nargchk(0, 1, nargin)) % check no. of input args %% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Get the handles to the existing Info-axes objects h_infotxt=findobj(gcf,'tag','Info','type','text'); h_infoax=findobj(gcf,'tag','Info','type','axes'); %% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % If no arguments are given, return the old axes handles if nargin == 0 | isempty(txt), ; elseif ischar(txt) % text: set new text [t,h_]=movetext(txt); h_infoax=[h_; h_infoax]; elseif vis_valuetype(txt,{'1x1'}) % scalar: change font size set(h_infotxt,'fontunits','points'); set(h_infotxt,'fontsize',txt); else error('Input argument should be a string or a scalar.'); end %% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargout>0 % output only if necessary h=h_infoax; end %%% SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [t,h]=movetext(txt) % Moves the text. See also VIS_FOOTNOTEBUTTONDOWNFCN % % initpos=[0.05 0.05 0.01 0.01]; memaxes = gca; % Memorize the gca %% Create new axis on the lower left corner. %% This will be the parent for the text object h = axes('position',initpos,'units','normalized'); set(h,'visible','off'); % hide axis t = text(0,0,txt); % write text set(t,'tag','Info'); % set tag set(h,'tag','Info'); % set tag set(t,'verticalalignment','bottom'); % set text alignment set(t,'horizontalalignment','left'); %% Set ButtonDownFcn set(t,'buttondownfcn','vis_footnoteButtonDownFcn') axes(memaxes); % Reset original gca
github
martinarielhartmann/mirtooloct-master
vis_trajgui.m
.m
mirtooloct-master/somtoolbox/vis_trajgui.m
41,530
utf_8
7afe711e9155c89b97c444b1d7e39710
function vis_trajgui(trajStruct,arg) % VIS_TRAJGUI subfuntion for SOM_TRAJECTORY % % This function is the actual GUI called by SOM_TRAJECTORY % function. % % See also SOM_TRAJECTORY. % Contributed code to SOM Toolbox 2.0, February 11th, 2000 by Juha Parhankangas % Copyright (c) by Juha Parhankangas. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juha 180699 if nargin == 1 sM_h=trajStruct.figure; if size(trajStruct.bmus,1) ~= 1 & size(trajStruct.bmus,2) ~= 1 fuzzy_traj(trajStruct,[]); return; end if size(trajStruct.bmus,1) == 1 | size(trajStruct.bmus,2) == 1 udata.bmus = trajStruct.bmus; udata.a_h=[findobj(get(sM_h,'Children'),'Tag','Uplane');... findobj(get(sM_h,'Children'),'Tag','Cplane')]; udata.sM_h=trajStruct.figure; udata.traj=[]; data1 = trajStruct.primary_data; if ~isempty(trajStruct.primary_names) names=trajStruct.primary_names; else for i=1:size(data1,2) names{i,1}=sprintf('Var%d',i); end end udata.lattice=trajStruct.lattice; form = 0.7*vis_patch(udata.lattice); udata.msize = trajStruct.msize; %%%%%%%%%%%%%%%%%%%%%%%% % % forming a patch object, which is placed above every component plane % l = size(form,1); nx = repmat(form(:,1),1,prod(udata.msize)); ny = repmat(form(:,2),1,prod(udata.msize)); x=reshape(repmat(1:udata.msize(2),l*udata.msize(1),1),l,prod(udata.msize)); y=repmat(repmat(1:udata.msize(1),l,1),1,udata.msize(2)); if strcmp(udata.lattice,'hexa') t = find(~rem(y(1,:),2)); x(:,t)=x(:,t)+.5; end x=x+nx; y=y+ny; colors=reshape(ones(prod(udata.msize),1)*[NaN NaN NaN],... [1 prod(udata.msize) 3]); set(0,'CurrentFigure',udata.sM_h); %%%%%%%%%%%%%%%%%%%%%% % % drawing patch % % caxis -commands keep the colormap of the original patch unchanged. % for i=1:length(udata.a_h) udata.real_patch(i)=get(udata.a_h(i),'Children'); set(udata.real_patch(i),'ButtonDownFcn',... 'vis_trajgui([],''click'')'); subplot(udata.a_h(i)); v=caxis; udata.tmp_patch(i)=patch(x,y,colors,'EdgeColor','none',... 'ButtonDownFcn',... 'vis_trajgui([],''click'')',... 'Tag','TmpPatch'); caxis(v); end %%%%%%%%%%%%%%%%%%%% udata.length_of_traj=length(trajStruct.size); udata.size=trajStruct.size; udata.color=trajStruct.color; udata.poly.x=[]; udata.poly.y=[]; udata.poly.h=[]; udata.new_marks=[]; udata.all_marks=[]; udata.d_mark2=[]; udata.fig1 = figure; set(udata.fig1,'KeyPressFcn','vis_trajgui([],''key'')',... 'Name','Primary Data'); %%%%%%%%%%%%%%%%%%%% % % making the 'Tools' -menu % udata.m_i=uimenu(udata.fig1,'Label','Trajectoy T&ools'); udata.m_i(2)=uimenu(udata.m_i,'Label','&Remove Trajectory',... 'Callback',... 'vis_trajgui([],''remove_traj'')'); udata.m_i(3)=uimenu(udata.m_i(1),'Label','&Dye Nodes',... 'Callback',... 'vis_trajgui([],''dye_gui'')'); udata.m_i(4)=uimenu(udata.m_i(1),'Label','&Clear Markers',... 'Callback',... 'vis_trajgui([],''clear'')'); udata.m_i(5)=uimenu(udata.m_i(1),'Label','&Save',... 'Callback',... 'vis_trajgui([],''save'')'); udata.m_i(6)=uimenu(udata.m_i(1),'Label','&Load',... 'Callback',... 'vis_trajgui([],''load'')'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % drawing data components to the figure .... % % if nargin < 5 | isempty(comps) | (isstr(comps) & strcmp(comps,'all')) comps = 1:size(data1,2); end x=1:size(data1,1); for i=1:length(comps) subplot(length(comps),1,i); udata.h(i)=gca; udata.d_mark(i).h=[]; udata.d(i)=plot(x,data1(:,comps(i)),... 'ButtonDownFcn',... 'vis_trajgui([],''line_down'')'); set(gca,'XLim',[1 size(data1,1)],... 'XTick',[],... 'ButtonDownFcn','vis_trajgui([],''line_down'')'); %,... %'YLim',[min(data1(:,comps(i))) max(data1(:,comps(i)))]); ylabel(names{comps(i)}); hold on; ymin=get(udata.h(i),'YLim'); pos=mean(get(udata.h(i),'XLim')); udata.l(i) = line([pos pos],[ymin(1) ymin(2)],... 'Color','red',... 'ButtonDownFcn',... 'vis_trajgui([],''down'')'); end udata.text1=[]; udata.fig2=[]; udata.h2=[]; udata.l2=[]; udata.text2=[]; %%%%%%%%%%%%%%%%%%%%%%%%%%% % % ... and to the figure 2. % if ~isempty(trajStruct.secondary_data) data2=trajStruct.secondary_data; if isempty(trajStruct.secondary_names) for i=1:size(data1,2) names2{i,1}=sprintf('Var%d',i); end else names2=trajStruct.secondary_names; end udata.fig2 = figure; set(udata.fig2,'Name','Secondary Data'); set(udata.fig2,'KeyPressFcn',... 'vis_trajgui([],''key'')'); for i=1:size(data2,2) subplot(size(data2,2),1,i); udata.h2(i) = gca; udata.d_mark2(i).h=[]; udata.d2(i) = plot(x,data2(:,i),... 'ButtonDownFcn',... 'vis_trajgui([],''line_down'')'); set(gca,'XLim',[1 size(data1,1)],'XTick',[],'ButtonDownFcn',... 'vis_trajgui([],[],[],[],[],[],''line_down'')'); ylabel(names2{i}); hold on; ymin = get(udata.h2(i),'YLim'); pos = mean(get(udata.h2(i),'XLim')); udata.l2(i) = line([pos pos],ymin,'Color','red',... 'ButtonDownFcn','vis_trajgui([],''down'')'); end end %%%%%%%%%%%%%%%%%%%%%%%%%% set(udata.fig1,'UserData',udata); if ~isempty(udata.fig2); tmp.fig1=udata.fig1; set(udata.fig2,'UserData',tmp); end tmp=get(udata.sM_h,'UserData'); tmp.fig1=udata.fig1; set(udata.sM_h,'UserData',tmp); set_numbers(round(pos)); return; end end %%%%%%%%%%%%%%%%% % % if figures have been drawn, the only function calls that may exist % are the ones that change the state of the application. % udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); switch arg case 'fuzzy' fuzzy_traj(tS,[]); return; case 'move_fuzzy' fuzzy_traj([],'move'); return; case 'remove_traj' remove_traj; return; case 'line_down' line_bdf('down'); return; case 'line_drag' line_bdf('drag'); return; case 'line_up' line_bdf('up'); return; case 'dye_gui'; color_gui(udata.fig1); return; case {'dye','cyan','magenta','yellow','red','green','blue','white','grey'} dye_nodes(arg); return; case 'clear' clear_markers; return; case 'key' key_bdf; return; case 'click' click; return; case 'save' save_data; return; case 'load' load_data; return; end %%%%%%%%%% % % lines in the data figure(s) are dragged ... % udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); lims=get(gca,'XLim'); x = getfield(get(gca,'CurrentPoint'),{1}); % the location of the line if x < lims(1) x=lims(1); elseif x > lims(2) x=lims(2); end old = gcf; switch arg case 'down',... % mouse button is pressed down above the line set(gcf,'WindowButtonMotionFcn','vis_trajgui([],''drag'')'); set(gcf,'WindowButtonUpFcn','vis_trajgui([],''up'')'); set(udata.l,'EraseMode','xor'); delete(udata.text1); if ~isempty(udata.l2); set(udata.l2,'EraseMode','xor'); delete(udata.text2); end set(gcf,'Pointer','crosshair'); case 'drag' % change the location of the lines set(0,'CurrentFigure',udata.fig1); set(udata.l,'XData',[x x]); if ~isempty(udata.fig2) set(0,'CurrentFigure',udata.fig2); set(udata.l2,'XData',[x x]); end draw_traj(round(x)); set(0,'CurrentFigure',old); case 'up' % draw trajectory and set figure to the normal state. set(udata.l,'EraseMode','normal'); set(gcf,'Pointer','arrow','WindowButtonMotionFcn','',... 'WindowButtonUpFcn',''); draw_traj(round(x)); set_numbers(round(x)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function draw_traj(point) udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); color=udata.color; eMode='normal'; if isstr(udata.color) & strcmp(udata.color,'xor') eMode='xor'; color='black'; end ind=udata.bmus(point); [i j] = ind2sub(udata.msize,ind); if ~mod(i,2) j=j+0.5; end old = gcf; set(0,'CurrentFigure',udata.sM_h); hold on; if isempty(udata.traj) | length(udata.traj.h) ~= length(udata.a_h) % trajectory does not exist for i=1:length(udata.a_h) subplot(udata.a_h(i)); hold on; new.h = plot(j,i,'Color',color,'EraseMode',eMode,'LineStyle','none'); udata.traj.h(i)=new; udata.traj.j=j; udata.traj.i=i; end else if length(udata.traj.j) == udata.length_of_traj % if the length of trajectory == ..., udata.traj.j(1) = []; % the first (the oldest) coordinate pair udata.traj.i(1) = []; % is removed. end udata.traj.j=[udata.traj.j;j]; % the new point is added to the udata.traj.i=[udata.traj.i;i]; % end of coordinate vectors (i and j) for i=1:length(udata.a_h) subplot(udata.a_h(i)); % remove the existing trajectory delete(udata.traj.h(i).h); % and plot the new one. for j=1:length(udata.traj.j) udata.traj.h(i).h(j)=plot(udata.traj.j(j),udata.traj.i(j),... 'Color',color,... 'EraseMode',eMode,'Marker','o','LineWidth',2,... 'MarkerSize',udata.size(udata.length_of_traj-j+1),... 'LineStyle','none'); end end end set(0,'CurrentFigure',udata.fig1); set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function set_numbers(x); % This function writes the numbers beside of the pointer lines udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); xlim = get(gca,'XLim'); ylim = get(gca,'YLim'); p = ylim(1) + 0.9*(ylim(2)-ylim(1)); old = gcf; set(0,'CurrentFigure',udata.fig1); for i=1:length(udata.h) subplot(udata.h(i)); % check if the text is placed to the left side of the line... if abs(x-xlim(1)) > (abs(x-xlim(2))) udata.text1(i)=text(x-1,p,sprintf('%d ->',x),... 'VerticalAlignment','top',... 'HorizontalAlignment','right',... 'FontWeight','demi'); else % or to the right side. udata.text1(i)=text(x+1,p,sprintf('<- %d',x),... 'VerticalAlignment','top',... 'FontWeight','demi'); end end if ~isempty(udata.fig2) set(0,'CurrentFigure',udata.fig2); for i=1:length(udata.h2) subplot(udata.h2(i)); if abs(x-xlim(1)) > (abs(x-xlim(2))) udata.text2(i)=text(x-1,p,sprintf('%d ->',x),... 'VerticalAlignment','top',... 'HorizontalAlignment','right',... 'FontWeight','demi'); else udata.text2(i)=text(x+1,p,sprintf('<- %d',x),... 'VerticalAlignment','top',... 'FontWeight','demi'); end end end set(0,'CurrentFigure',old); set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function remove_traj() % delete trajectory -object from every component plane. udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); if isempty(udata.traj) return; end for i=1:length(udata.traj.h) delete(udata.traj.h(i).h); end udata.traj=[]; set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function line_bdf(arg) % this function takes care of action when region is selected in the % data figure. udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); xlim=get(gca,'XLim'); if ~(any(strcmp('THIS',fieldnames(udata)))) p = getfield(get(gca,'CurrentPoint'),{1}); else p = getfield(get(udata.THIS,'CurrentPoint'),{1}); end if p < xlim(1) p = xlim(1); elseif p > xlim(2) p = xlim(2); end switch arg case 'down' % the mouse button is pressed down, the pointer lines are drawn. % and the state of the figure is changed. udata.THIS=gca; set(gcf,'WindowButtonMotionFcn',... 'vis_trajgui([],''line_drag'')',... 'WindowButtonUpFcn','vis_trajgui([],''line_up'')'); udata.start_p=p; old = gcf; set(0,'CurrentFigure',udata.fig1); for i=1:length(udata.h) subplot(udata.h(i)); udata.t_line.h(i)=line([p p],get(gca,'YLim'),'Color','red'); udata.t_line.h2(i)=line([p p],get(gca,'YLim'),'Color','red',... 'EraseMode','xor'); end if ~isempty(udata.h2) set(0,'CurrentFigure',udata.fig2); for i=1:length(udata.h2) subplot(udata.h2(i)); udata.t_line2.h(i)=line([p p],get(gca,'YLim'),'Color','red'); udata.t_line2.h2(i)=line([p p],get(gca,'YLim'),'Color','red',... 'EraseMode','xor'); end end case 'drag' % change the position of the pointer lines old = gcf; set(0,'CurrentFigure',udata.fig1); set(udata.t_line.h2,'XData',[p p]); if ~isempty(udata.fig2) set(0,'CurrentFigure',udata.fig2); set(udata.t_line2.h2,'XData',[p p]); end set(0,'CurrentFigure',old); case 'up' % sort the 'points' -vector and draw the markers to the data and nodes points=sort([round(udata.start_p) round(p)]); draw_markers(points(1):points(2)); udata=get(udata.fig1,'UserData'); udata.new_marks=unique([udata.new_marks ;(points(1):points(2))']); delete([udata.t_line.h2 udata.t_line.h]); if ~isempty(udata.fig2) delete([udata.t_line2.h2 udata.t_line2.h]); end set(get(udata.THIS,'Parent'),'WindowButtonMotionFcn','',... 'WindowButtonUpFcn',''); udata=rmfield(udata,'THIS'); end set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function draw_markers(x); plot2data(x); plot2plane(x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot2data(x); % plot black markers to the data figure(s) udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); old = gcf; set(0,'CurrentFigure',udata.fig1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if there already exist points in the positions that are members % of the set x, then the old points are removed from data figures... for i=1:length(udata.d_mark(1).h) tmp1 = get(udata.d_mark(1).h(i),'XData'); tmp2 = setdiff(tmp1,x); if length(tmp1) ~= length(tmp2) inds=[]; for j=1:length(tmp2); inds=[inds find(tmp2(j)==tmp1)]; end for j=1:length(udata.d_mark) ydata=getfield(get(udata.d_mark(j).h(i),'YData'),{inds}); set(udata.d_mark(j).h(i),'XData',tmp2,'YData',ydata); end if ~isempty(udata.fig2) for j=1:length(udata.d_mark2) ydata=getfield(get(udata.d_mark2(j).h(i),'YData'),{inds}); set(udata.d_mark2(j).h(i),'XData',tmp2,'YData',ydata); end end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ... and the new ones are plotted. for i=1:length(udata.h) subplot(udata.h(i)); h=plot(x,getfield(get(udata.d(i),'YData'),{x}),'oblack',... 'ButtonDownFcn',... 'vis_trajgui([],''line_down'')'); udata.d_mark(i).h=[udata.d_mark(i).h;h]; end if ~isempty(udata.h2) set(0,'CurrentFigure',udata.fig2); for i=1:length(udata.h2) subplot(udata.h2(i)); h=plot(x,getfield(get(udata.d2(i),'YData'),{x}),'oblack',... 'ButtonDownFcn',... 'vis_trajgui([],''line_down'')'); udata.d_mark2(i).h=[udata.d_mark2(i).h;h]; end end set(0,'CurrentFigure',old); set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot2plane(x); % sets markers to the component planes. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % actually new markers are never plotted, but the color of the patch % lying above the original component plane patch is changed black in % the right positions. udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); udata.new_marks=unique([udata.new_marks ;x']); for i=1:length(udata.a_h) col=get(udata.tmp_patch(i),'FaceVertexCData'); if length(size(col)) == 3 col = reshape(col,[size(col,1) 3]); end for j=1:length(udata.new_marks) col(udata.bmus(udata.new_marks(j)),:)=[0 0 0]; end set(udata.tmp_patch(i),'FaceVertexCData',col); end set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function color_gui(fig1) % construct the graphical user interface for changing the color of the % black (marked) nodes. udata=get(fig1,'UserData'); a = figure('Color',[0.8 0.8 0.8], ... 'Name','Colors', ... 'PaperType','a4letter', ... 'Position',[518 456 120 311], ... 'Tag','Fig1'); udata.c_struct.fig=a; b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.701961 0.701961 0.701961], ... 'Position',[0.0700415 0.28956 0.830492 0.594566], ... 'Style','frame', ... 'Tag','Frame1'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Position',[0.100059 0.301143 0.770456 0.571399], ... 'Style','frame', ... 'Tag','Frame2'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'Callback','vis_trajgui([],''cyan'')', ... 'Position',[0.130077 0.795326 0.170101 0.0617729], ... 'Style','radiobutton', ... 'Tag','cyan', ... 'Value',1); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'Callback','vis_trajgui([],''magenta'')', ... 'Position',[0.130077 0.733553 0.170101 0.057912], ... 'Style','radiobutton', ... 'Tag','magenta'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'Callback','vis_trajgui([],''yellow'')', ... 'Position',[0.130077 0.664059 0.170101 0.0617729], ... 'Style','radiobutton', ... 'Tag','yellow'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'Callback','vis_trajgui([],''red'')', ... 'Position',[0.130077 0.590703 0.170101 0.0617729], ... 'Style','radiobutton', ... 'Tag','red'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'Callback','vis_trajgui([],''green'')', ... 'Position',[0.130077 0.525068 0.170101 0.057912], ... 'Style','radiobutton', ... 'Tag','green'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'Callback','vis_trajgui([],''blue'')', ... 'Position',[0.130077 0.455575 0.170101 0.0617729], ... 'Style','radiobutton', ... 'Tag','blue'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'Callback','vis_trajgui([],''white'')', ... 'Position',[0.130077 0.38608 0.170101 0.0617729], ... 'Style','radiobutton', ... 'Tag','white'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'Callback','vis_trajgui([],''grey'')', ... 'Position',[0.130077 0.320447 0.170101 0.057912], ... 'Style','radiobutton', ... 'Tag','grey'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[0.32019 0.795326 0.470278 0.0501905], ... 'String','Cyan', ... 'Style','text', ... 'Tag','StaticText1'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[0.32019 0.733553 0.520308 0.0463296], ... 'String','Magenta', ... 'Style','text', ... 'Tag','StaticText2'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[0.32019 0.664059 0.470278 0.0501905], ... 'String','Yellow', ... 'Style','text', ... 'Tag','StaticText3'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[0.32019 0.590703 0.470278 0.0501905], ... 'String','Red', ... 'Style','text', ... 'Tag','StaticText4'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[0.32019 0.525068 0.470278 0.0463296], ... 'String','Green', ... 'Style','text', ... 'Tag','StaticText5'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[0.32019 0.455575 0.470278 0.0463296], ... 'String','Blue', ... 'Style','text', ... 'Tag','StaticText6'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[0.32019 0.38608 0.470278 0.0501905], ... 'String','White', ... 'Style','text', ... 'Tag','StaticText7'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[0.32019 0.320447 0.470278 0.0463296], ... 'String','Grey', ... 'Style','text', ... 'Tag','StaticText8'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'Position',[0.0700415 0.146711 0.830492 0.135128], ... 'Style','frame', ... 'Tag','Frame3'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Position',[0.100059 0.158293 0.770456 0.111963], ... 'Style','frame', ... 'Tag','Frame4'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[0.130077 0.177597 0.270833 0.0617729], ... 'String','RGB', ... 'Style','text', ... 'Tag','StaticText9'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Position',[0.410243 0.173736 0.420249 0.0810768], ... 'Style','edit', ... 'Tag','EditText1'); udata.c_struct.RGB=b; b = uicontrol('Parent',a, ... 'Units','normalized', ... 'Callback','vis_trajgui([],''dye'')', ... 'FontWeight','demi', ... 'Position',[0.0700415 0.0270256 0.360214 0.0772162], ... 'String','OK', ... 'Tag','Pushbutton1'); b = uicontrol('Parent',a, ... 'Units','normalized', ... 'Callback','close gcf', ... 'FontWeight','demi', ... 'Position',[0.54032 0.0270256 0.360214 0.0772162], ... 'String','Close', ... 'Tag','Pushbutton2'); udata.c_struct.color=[0 1 1]; tmp.fig1=fig1; set(a,'UserData',tmp); set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function dye_nodes(arg) % takes care of the action, when radiobuttons are pressed % (or the RGB value is set) in the color_gui -figure. % It also handles the starting of dying nodes and plots. udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); switch arg case {'cyan','magenta','yellow','red','green','blue','white','grey'} h=findobj(get(gcf,'Children'),'Style','radiobutton'); set(h,'Value',0); set(gcbo,'Value',1); end switch arg case 'cyan' RGB = [0 1 1]; case 'magenta' RGB = [1 0 1]; case 'yellow' RGB = [1 1 0]; case 'red' RGB = [1 0 0]; case 'green' RGB = [0 1 0]; case 'blue' RGB = [0 0 1]; case 'white' RGB = [1 1 1]; case 'grey' RGB = [0.4 0.4 0.4]; case 'dye' RGB = get(udata.c_struct.RGB,'String'); if isempty(RGB) dye; return; else str1='The value of RGB must be vector containing three scalars'; str2='between 0 and 1.'; color = str2num(RGB); set(udata.c_struct.RGB,'String',''); if isempty(color) close gcf; udata=rmfield(udata,'c_struct'); set(udata.fig1,'UserData',udata); errordlg([{str1};{str2}]); return; end if ~all([1 3] == size(color)) & ~all([3 1] == size(color)) close gcf; errordlg([{str1};{str2}]); udata=rmfield(udata,'c_struct',udata); set(udata.fig1,'UserData',udata); return; end if ~isempty(cat(2,find(color>1),find(color<0))) close gcf errordlg([{str1};{str2}]); udata=rmfield(udata,'c_struct',udata); set(udata.fig1,'UserData',udata); return; end udata.c_struct.color=color; set(udata.fig1,'UserData',udata); dye; return; end end udata.c_struct.color=RGB; set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function dye() % dyes black markers in the component planes and in the data figures udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); inds=unique([udata.all_marks ; udata.new_marks]); for i=1:length(udata.d_mark); for j=1:length(udata.d_mark(i).h) if all(get(udata.d_mark(i).h(j),'Color') == [0 0 0]) set(udata.d_mark(i).h(j),'Color',udata.c_struct.color); end end end if ~isempty(udata.fig2); for i=1:length(udata.d_mark2) for j=1:length(udata.d_mark2(i).h) if all(get(udata.d_mark2(i).h(j),'Color') == [0 0 0]) set(udata.d_mark2(i).h(j),'Color',udata.c_struct.color); end end end end for i=1:length(udata.a_h) col=get(udata.tmp_patch(i),'FaceVertexCData'); for j=1:length(udata.new_marks) col(udata.bmus(udata.new_marks(j)),:)=udata.c_struct.color; end set(udata.tmp_patch(i),'FaceVertexCData',col); end udata.all_marks=unique([udata.all_marks;udata.new_marks]); udata.new_marks=[]; close gcf; udata=rmfield(udata,'c_struct'); set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function clear_markers() % removes markers from the componentplanes and the data figure(s). udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); for i=1:length(udata.d_mark) delete(udata.d_mark(i).h); udata.d_mark(i).h=[]; end for i=1:length(udata.d_mark2) delete(udata.d_mark2(i).h); udata.d_mark2(i).h=[]; end col=NaN*get(udata.tmp_patch(1),'FaceVertexCData'); col=reshape(col,[size(col,1) 3]); for i=1:length(udata.tmp_patch) set(udata.tmp_patch(i),'FaceVertexCData',col); end udata.new_marks=[]; udata.all_marks=[]; if any(strcmp('c_struct',fieldnames(udata))) udata=rmfield(udata,'c_struct'); end set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key_bdf % moves trajectory and pointer lines, when either of % the keys '>' or '<' is pressed. udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); key=get(gcbo,'CurrentCharacter'); % The easiest way to get a new coordinates is to get them from the texts... % The texts are either '<- x' or 'x ->' x=get(udata.text1(1),'String'); x=str2num(x(4:length(x))); if isempty(x) x=get(udata.text1(1),'String'); x=str2num(x(1:length(x)-3)); end switch(key) case '<' if x ~= 1 x= x-1; end case '>' if x ~= getfield(get(get(udata.text1(1),'Parent'),'XLim'),{2}) x = x+1; end otherwise return; end set(udata.l,'XData',[x x]); if ~isempty(udata.fig2) set(udata.l2,'XData',[x x]); end delete(udata.text1); delete(udata.text2); set_numbers(x); draw_traj(x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function click() switch get(gcf,'SelectionType') case 'open' return; case {'normal','alt'} draw_poly; case 'extend' click_node; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function click_node() % takes care of the action, when the middle mouse button is % pressed (mouse pointer is above some component plane). udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); new_marks=[]; old=gcf; NEW=0; AGAIN = 0; coords=get(gca,'CurrentPoint'); row=round(coords(1,2)); if strcmp(udata.lattice,'hexa') & ~mod(row,2) col = round(coords(1,1) - 0.5); else col = round(coords(1,1)); end ind = sub2ind(udata.msize,row,col); new_marks=find(udata.bmus==ind); if strcmp(get(gcbo,'Tag'),'TmpPatch'); % if the callback is made via temporary patch object, node is marked % (node is black) => the mark is to be removed node_color = getfield(get(gcbo,'FaceVertexCData'),{ind,[1:3]}); AGAIN = 1; end for i=1:length(udata.tmp_patch) color = get(udata.tmp_patch(i),'FaceVertexCData'); if length(size(color)) ~= 2 color = reshape(color,[size(color,1) 3]); end if all(isnan(color(ind,:))) NEW=1; color(ind,:)=[0 0 0]; else color(ind,:)=[NaN NaN NaN]; end set(udata.tmp_patch(i),'FaceVertexCData',color); end set(0,'CurrentFigure',udata.fig1); for j=1:length(udata.h) subplot(udata.h(j)); if NEW y=getfield(get(udata.d(j),'YData'),{new_marks}); udata.d_mark(j).h=[udata.d_mark(j).h;plot(new_marks,y,'Color',[0 0 0],... 'LineStyle','none',... 'Marker','o')]; end end if ~isempty(udata.fig2) set(0,'CurrentFigure',udata.fig2); for j=1:length(udata.h2); subplot(udata.h2(j)); if NEW y=getfield(get(udata.d2(j),'YData'),{new_marks}); udata.d_mark2(j).h=[udata.d_mark2(j).h;plot(new_marks,y,... 'LineStyle','none',... 'Color','black',... 'Marker','o')]; end end end if NEW udata.new_marks=[udata.new_marks; new_marks]; end if AGAIN % find marks from the data that map to the clicked node. if the color % of the mark(s) is the same as the node's color, remove mark(s), else % let mark be unchanged. for i=1:length(udata.d_mark(1).h) if all(node_color==get(udata.d_mark(1).h(i),'Color')) tmp1 = get(udata.d_mark(1).h(i),'XData'); tmp2 = setdiff(tmp1,new_marks); if length(tmp1) ~= length(tmp2) inds=[]; for j=1:length(tmp2); inds=[inds find(tmp2(j)==tmp1)]; end for j=1:length(udata.d_mark) ydata=getfield(get(udata.d_mark(j).h(i),'YData'),{inds}); set(udata.d_mark(j).h(i),'XData',tmp2,'YData',ydata); end if ~isempty(udata.fig2) for j=1:length(udata.d_mark2) ydata=getfield(get(udata.d_mark2(j).h(i),'YData'),{inds}); set(udata.d_mark2(j).h(i),'XData',tmp2,'YData',ydata); end end end end end udata.new_marks=setdiff(udata.new_marks, new_marks); udata.all_marks=setdiff(udata.all_marks,new_marks); end set(udata.fig1,'UserData',udata); set(0,'CurrentFigure',old); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function draw_poly() udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); if isempty(udata.poly.x) if strcmp(get(gcf,'SelectionType'),'alt') return; end udata.poly.THIS = gca; end % 'THIS' indicates what was the axes where the polygon was meant to % drawn. It is not possible to add points, that lie in another axes, to the % polygon. if gca ~= udata.poly.THIS return; end coords(1,1) = getfield(get(gca,'CurrentPoint'),{3}); coords(1,2) = getfield(get(gca,'CurrentPoint'),{1}); udata.poly.x=cat(1,udata.poly.x,coords(2)); udata.poly.y=cat(1,udata.poly.y,coords(1)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % remove old 'polygon' from axis delete(udata.poly.h); switch get(gcf,'SelectionType') case 'normal' % add point to the 'polygon' and draw it for i=1:length(udata.a_h) subplot(udata.a_h(i)); hold on; udata.poly.h(i) = plot(udata.poly.x,udata.poly.y,'black',... 'EraseMode','xor',... 'ButtonDownFcn',... 'vis_trajgui([],''click'')',... 'LineWidth',2); end case 'alt' % The polygon is ready. udata.poly.x=cat(1,udata.poly.x,udata.poly.x(1)); udata.poly.y=cat(1,udata.poly.y,udata.poly.y(1)); for i=1:length(udata.a_h) subplot(udata.a_h(i)); udata.poly.h(i) = plot(udata.poly.x,udata.poly.y,'black',... 'EraseMode','xor',... 'ButtonDownFcn',... 'vis_trajgui([],''click'')',... 'LineWidth',2); end tmp=sort(repmat((1:udata.msize(1))',udata.msize(2),1)); tmp(:,2)=repmat((1:udata.msize(2))',udata.msize(1),1); tmp2=tmp; if strcmp(udata.lattice,'hexa'); t=find(~rem(tmp(:,1),2)); tmp(t,2)=tmp(t,2)+0.5; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % find the nodes that lie inside polygon and change coordinates to % linear indices. in = find(inpolygon(tmp(:,2),tmp(:,1),udata.poly.x,udata.poly.y)); in = sub2ind(udata.msize,tmp2(in,1),tmp2(in,2)); colors=get(udata.tmp_patch(1),'FaceVertexCData'); colors=reshape(colors,[size(colors,1) 3]); tmp=ones(length(in),1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % set the color of the nodes just selected, black. colors(in,:)=tmp*[0 0 0]; set(udata.tmp_patch,'FaceVertexCData',colors); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % find the points mapping to the nodes from data inds = []; for i=1:length(in) inds=[inds;find(in(i) == udata.bmus)]; end %%%%%%%%%%%%%%%%%%% % plot marks to data set(udata.fig1,'UserData',udata); plot2data(inds); udata=get(udata.fig1,'UserData'); udata.new_marks=union(udata.new_marks,inds); delete(udata.poly.h); udata.poly.h=[]; udata.poly.x=[]; udata.poly.y=[]; udata.poly.THIS=[]; end set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function save_data() udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); data.points=[]; data.nodes=[]; k=1; for i=1:length(udata.d_mark(1).h) data.points(i).inds=get(udata.d_mark(1).h(i),'XData'); data.points(i).color=get(udata.d_mark(1).h(i),'Color'); end color=get(udata.tmp_patch(1),'FaceVertexCData'); color=reshape(color,[size(color,1) 3]); for i=1:size(color,1) if all(~isnan(color(i,:))) tmp.ind=i; tmp.color=color(i,:); data.nodes(k)=tmp; k=k+1; end end answer=inputdlg('Enter the name of the output variable:','',1); if isempty(answer) | isempty(answer{1}) msgbox('Output is not set to workspace.'); return; else assignin('base',answer{1},data); disp(sprintf('Struct is set to the workspace as ''%s''.',answer{1})); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function load_data() answer = inputdlg('Enter the name of the struct to be loaded:','',1); if isempty(answer) | isempty(answer{1}) msgbox('Data is not loaded.'); return; end data=evalin('base',answer{1}); if ~isstruct(data) errordlg('Input variable must be a struct.'); return; end tmp1 = fieldnames(data); tmp2 = {'nodes','points'}; for i=1:length(tmp1) for j=1:length(tmp2); if ~any(strcmp(tmp2{j},tmp1)) errordlg('Wrong type of struct.'); return; end end end if ~isempty(data.points) tmp1=fieldnames(data.points(1)); end if ~isempty(data.nodes) tmp2=fieldnames(data.nodes(1)); end for i=1:length(tmp1) if ~any(strcmp(tmp1{i},{'inds','color'})) errordlg('Wrong type of struct.'); return; end end for i=1:length(tmp2) if ~any(strcmp(tmp2{i},{'ind','color'})) errordlg('Wrong type of struct.'); return; end end udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); clear_markers; remove_traj; old = gcf; for i=1:length(data.points) for j=1:length(udata.h); set(0,'CurrentFigure',udata.fig1); subplot(udata.h(j)); ydata=getfield(get(udata.d(j),'YData'),{data.points(i).inds}); udata.d_mark(j).h=[udata.d_mark(j).h;... plot(data.points(i).inds,ydata,... 'Color',data.points(i).color,... 'LineStyle','none',... 'Marker','o',... 'ButtonDownFcn',... 'vis_trajgui([],''line_down'')')]; if all(data.points(i).color == [0 0 0]) udata.new_marks=unique([udata.new_marks; (data.points(i).inds)']); else udata.all_marks=unique([udata.all_marks; (data.points(i).inds)']); end end if ~isempty(udata.fig2) set(0,'CurrentFigure',udata.fig2); for j=1:length(udata.h2) subplot(udata.h2(j)); ydata=getfield(get(udata.d2(j),'YData'),{data.points(i).inds}); udata.d_mark2(j).h=[udata.d_mark2(j).h;... plot(data.points(i).inds,ydata,... 'Color',data.points(i).color,... 'LineStyle','none',... 'Marker','o',... 'ButtonDownFcn',... 'vis_trajgui([],''line_down'')')]; end end end set(0,'CurrentFigure',udata.sM_h); color=get(udata.tmp_patch(1),'FaceVertexCData'); color=reshape(color,[size(color,1) 3]); for i=1:length(data.nodes) color(data.nodes(i).ind,:)=data.nodes(i).color; end for i=1:length(udata.tmp_patch); set(udata.tmp_patch(i),'FaceVertexCData',color); end set(0,'CurrentFigure',old); set(udata.fig1,'UserData',udata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fuzzy_traj(trajStruct,arg); %function fuzzy_traj(sM_h,sM,sD,interval,arg) if isempty(arg) if strcmp(trajStruct.lattice,'hexa') udata.lattice='hexa'; udata.form=vis_patch('hexa'); else data.lattice='rect'; udata.form=vis_patch('rect'); end % interval=[1 size(trajStruct.primary_data,1)]; l=size(udata.form,1); dim = size(trajStruct.primary_data,2); udata.a_h=[findobj(get(trajStruct.figure,'Children'),'Tag','Uplane');... findobj(get(trajStruct.figure,'Children'),'Tag','Cplane')]; udata.sM_h=trajStruct.figure; udata.msize=trajStruct.msize; %%%%%%%%%%%%%%% % % constructing patch that is drawn above every plane in map % nx = repmat(udata.form(:,1),1,prod(udata.msize)); ny = repmat(udata.form(:,2),1,prod(udata.msize)); x_c=reshape(repmat(1:udata.msize(2),l*udata.msize(1),1),l,prod(udata.msize)); y_c=repmat(repmat(1:udata.msize(1),l,1),1,udata.msize(2)); if strcmp(udata.lattice,'hexa') t = find(~rem(y_c(1,:),2)); x_c(:,t)=x_c(:,t)+.5; end x_c=x_c+nx; y_c=y_c+ny; udata.orig_c=ones(prod(udata.msize),1)*[NaN NaN NaN]; colors=reshape(udata.orig_c,[1 size(udata.orig_c,1) 3]); set(0,'CurrentFigure',trajStruct.figure); %%%%%%%%% % drawing for i=1:length(udata.a_h); subplot(udata.a_h(i)); v=caxis; udata.patch_h(i) =patch(x_c,y_c,colors,'EdgeColor','none'); caxis(v); end udata.orig_x=get(udata.patch_h(1),'XData'); udata.orig_y=get(udata.patch_h(1),'YData'); % if interval(1) < 1 | interval(2) > size(trajStruct.primary_data,1) % error('Invalid argument ''interval''.'); % end x=1:size(trajStruct.primary_data,1); udata.fig1=figure; set(udata.fig1,'KeyPressFcn',... 'vis_trajgui([],''move_fuzzy'')'); for i=1:size(trajStruct.primary_data,2) subplot(size(trajStruct.primary_data,2),1,i); udata.h(i)=gca; set(udata.h(1),'XTick',[]); udata.d(i)=plot(x,trajStruct.primary_data(:,i)); l_x=1; lims(1) = round(min(trajStruct.primary_data(:,i))); lims(2) = round(max(trajStruct.primary_data(:,i))); udata.l(i) = line([l_x l_x],lims,'Color','red','EraseMode','xor'); end udata.l_x = l_x; udata.interval=[1 size(trajStruct.bmus,2)]; tmp.fig1=udata.fig1; % [K,P] = estimate_kernels(sM,sD); % udata.K=K; % udata.P=P; % udata.codebook=sM.codebook; % udata.data=sD.data; udata.bmus=trajStruct.bmus; set(udata.fig1,'UserData',udata); set(trajStruct.figure,'UserData',tmp); draw_fuzzy(l_x); return; end move_fuzzy; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function draw_fuzzy(x) udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); inds = find(udata.bmus(:,x)); [row col] = ind2sub(udata.msize,inds); if strcmp(udata.lattice,'hexa') t=find(~mod(row,2)); col(t)=col(t)+0.5; end color=udata.orig_c; color=reshape(color,[size(color,1) 3]); xdata=udata.orig_x; ydata=udata.orig_y; tmp= ones(size(xdata(:,1),1),1)*udata.bmus(inds,x)'; color(inds,:) = ones(length(inds),1)*[0 0 0]; xdata(:,inds) = udata.form(:,1)*ones(1,length(inds)).*tmp+ones(6,1)*col'; ydata(:,inds) = udata.form(:,2)*ones(1,length(inds)).*tmp+ones(6,1)*row'; set(udata.patch_h,'FaceVertexCData',color,'XData',xdata,'YData',ydata); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function move_fuzzy % moves pointer lines and draws fuzzy response. udata=get(gcf,'UserData'); udata=get(udata.fig1,'UserData'); switch get(gcf,'CurrentCharacter'); case {'<','>'} key = get(gcf,'CurrentCharacter'); if key == '>' if udata.l_x + 1 > udata.interval(2) return; end l_x = udata.l_x + 1; else if udata.l_x - 1 < udata.interval(1) return; end l_x = udata.l_x - 1; end draw_fuzzy(l_x); set(udata.l,'XData',[l_x l_x]); udata.l_x=l_x; set(udata.fig1,'UserData',udata); otherwise return; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
martinarielhartmann/mirtooloct-master
som_order_cplanes.m
.m
mirtooloct-master/somtoolbox/som_order_cplanes.m
8,524
utf_8
3b6f8da3cb8f17ae375f464280e0f4df
function P = som_order_cplanes(sM, varargin) %SOM_ORDER_CPLANES Orders and shows the SOM component planes. % % P = som_order_cplanes(sM, [[argID,] value, ...]) % % som_order_cplanes(sM); % som_order_cplanes(sM,'comp',1:30,'simil',C,'pca'); % P = som_order_cplanes(sM); % % Input and output arguments ([]'s are optional): % sM (struct) map or data struct % (matrix) a data matrix, size * x dim % [argID, (string) See below. The values which are unambiguous can % value] (varies) be given without the preceeding argID. % % P (matrix) size n x * (typically n x 2), the projection coordinates % % Here are the valid argument IDs and corresponding values. The values % which are unambiguous (marked with '*') can be given without the % preceeding argID. % 'comp' (vector) size 1 x n, which components to project, 1:dim by default % 'simil' *(string) similarity measure to use % 'corr' linear correlation between component planes % 'abs(corr)' absolute value of correlation (default) % 'umat' as 'abs(corr)' but calculated from U-matrices % 'mutu' mutual information (not implemented yet) % (matrix) size n x n, a similarity matrix to be used % 'proj' *(string) projection method to use: 'SOM' (default), % 'pca', 'sammon', 'cca', 'order', 'ring' % 'msize' (vector) size of the SOM that is used for projection % 'show' *(string) how visualization is done: 'planes' (default), % 'names', or 'none' % 'mask' (vector) dim x 1, the mask to use, ones(dim,1) by default % 'comp_names' (cell array) of strings, size dim x 1, the component names % % The visualized objects have a callback associated with them: by % clicking on the object, the index and name of the component are printed % to the standard output. % % See also SOM_SHOW. % Copyright (c) 2000 by the SOM toolbox programming team. % Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 120600 070601 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% check arguments % sM if isstruct(sM), switch sM.type case 'som_map', D = sM.codebook; dim = size(D,2); cnames = sM.comp_names; mask = sM.mask; ismap = 1; case 'som_data', D = sM.data; dim = size(D,2); cnames = sM.comp_names; mask = ones(dim,1); ismap = 0; otherwise, error('Invalid first argument.'); end else D = sM; dim = size(D,2); mask = ones(dim,1); cnames = cell(dim,1); for i = 1:dim, cnames{i} = sprintf('Variable%d',i); end ismap = 0; end % defaults comps = 1:dim; simil = 'abs(corr)'; proj = 'SOM'; show = 'planes'; mapsize = NaN; % varargin i=1; while i<=length(varargin), argok = 1; if ischar(varargin{i}), switch varargin{i}, % argument IDs case 'mask', i=i+1; mask = varargin{i}; case 'comp_names', i=i+1; cnames = varargin{i}; case 'comp', i=i+1; comps = varargin{i}; case 'proj', i=i+1; proj = varargin{i}; case 'show', i=i+1; show = varargin{i}; case 'simil', i=i+1; simil = varargin{i}; case 'msize', i=i+1; mapsize = varargin{i}; % unambiguous values case {'corr','abs(corr)','umat','mutu'}, simil = varargin{i}; case {'SOM','pca','sammon','cca','order','ring'}, proj = varargin{i}; case {'planes','names','none'}, show = varargin{i}; otherwise argok=0; end else argok = 0; end if ~argok, disp(['(som_order_cplanes) Ignoring invalid argument #' num2str(i+1)]); end i = i+1; end if strcmp(show,'planes') & ~ismap, warning('Given data is not a map: using ''names'' visualization.'); show = 'names'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% similarity matrix fprintf(1,'Calculating similarity matrix\n'); % use U-matrix if strcmp(simil,'umat'), if ~ismap, error('Given data is not a map: cannot use U-matrix similarity.'); end U = som_umat(sM); D = zeros(prod(size(U)),dim); m = zeros(dim,1); for i=1:dim, m=m*0; m(i)=1; U = som_umat(sM,'mask',m); D(:,i) = U(:); end end % components D = D(:,comps); cnames = cnames(comps); mask = mask(comps); dim = length(comps); % similarity matrix if ischar(simil), switch simil, case {'corr','abs(corr)','umat'}, A = zeros(dim); me = zeros(1,dim); for i=1:dim, me(i) = mean(D(isfinite(D(:,i)),i)); D(:,i) = D(:,i) - me(i); end for i=1:dim, for j=i:dim, c = D(:,i).*D(:,j); c = c(isfinite(c)); A(i,j) = sum(c)/length(c); A(j,i) = A(i,j); end end s = diag(A); A = A./sqrt(s*s'); switch simil, case {'abs(corr)','umat'}, A = abs(A); case 'corr', A = A + 1; end case 'mutu', error('Mutual information not implemented yet.'); end else A = simil; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% projection fprintf(1,'Projection\n'); mu = 2*dim; switch proj, case 'SOM', if isnan(mapsize), sMtmp = som_randinit(A,'munits',mu); msize = sMtmp.topol.msize; else msize = mapsize; end sM2 = som_make(A,'msize',msize,'rect','tracking',0); bm = assign_unique_bm(sM2,A); Co = som_unit_coords(sM2); P = Co(bm,:); case 'ring', if isnan(mapsize), msize = [1 mu]; else msize = mapsize; end sM2 = som_make(A,'msize',msize,'cyl','rect','tracking',0); bm = assign_unique_bm(sM2,A); Co = som_unit_coords(sM2); P = Co(bm,[1 3]); case 'order', if isnan(mapsize), msize = [1 mu]; else msize = mapsize; end sM2 = som_make(A,'msize',msize,'tracking',0); bm = assign_unique_bm(sM2,A); [dummy,i] = sort(bm); [dummy,P] = sort(i); if size(P,2)>1, P = P'; end if size(P,2)==1, P(:,2) = zeros(length(P),1); end case {'pca','sammon','cca'}, P = pcaproj(A,2); if strcmp(proj,'sammon'), P = sammon(A,P,50,'steps'); elseif strcmp(proj,'cca'), P = cca(A,P,50); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% visualization if ~strcmp(show,'none'), fprintf(1,'Visualization\n'); cla hold on if strcmp(show,'planes') s = findscaling(sM.topol.msize,P); for i=1:dim, C = som_normcolor(D(:,i)); if strcmp(simil,'umat'), h=som_cplane([sM.topol.lattice 'U'],sM.topol.msize,C,1,s*P(i,:)); else h=som_cplane(sM,C,1,s*P(i,:)); end set(h,'edgecolor','none','Userdata',sprintf('[%d] %s',i,cnames{i})); set(h,'ButtonDownFcn','fprintf(1,''%s\n'',get(gco,''UserData''))'); end else s=1; a=[min(P(:,1))-1 max(P(:,1))+1 min(P(:,2))-1-3 max(P(:,2))+1-3]; axis(s*a); end h=text(s*P(:,1),s*P(:,2)-3,cnames); for i=1:length(h), set(h(i),'Userdata',sprintf('[%d] %s',i,cnames{i})); end set(h,'ButtonDownFcn','fprintf(1,''%s\n'',get(gco,''UserData''))'); hold off axis on; axis equal; axis tight; set(gca,'XTick',[],'YTick',[],'Box','on'); end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 %% subfunctions function bm = assign_unique_bm(sM,D) munits = size(sM.codebook,1); [dlen dim] = size(D); margin = max(0,dlen-munits); [bm,qers] = som_bmus(sM,D); bmi=ones(dim,1); hits = som_hits(sM,D); mult = find(hits>1); while any(mult) & sum(hits(mult))-length(mult)>margin, choices = find(bm==mult(1)); while length(choices)>1, [dummy,mv] = max(qers(choices)); mv = choices(mv); [mv_to,q] = som_bmus(sM,D(mv,:),bmi(mv)); bmi(mv)=bmi(mv)+1; qers(mv) = q; bm(mv) = mv_to; choices = find(bm==mv_to); end for i=1:length(hits), hits(i)=sum(bm==i); end mult = find(hits>1); end return; function s = findscaling(msize,P) d1 = median(abs(diff(unique(sort(P(:,1)))))); d2 = median(abs(diff(unique(sort(P(:,2)))))); if d1>0, s1 = 1.5*msize(2)/d1; else s1 = 0; end if d2>0, s2 = 1.5*msize(1)/d2; else s2 = 0; end s = max(s1,s2); if s==0, s=1; end return; function alternative_SOM_plane_vis(sT,bm,simil,D,cnames) clf for i=1:size(D,2), subplot(sT.msize(2),sT.msize(1),bm(i)); if strcmp(simil,'umat'), h=som_cplane([sT.lattice 'U'],sT.msize,D(:,i)); else h=som_cplane(sT,D(:,i)); end set(h,'edgecolor','none'); title(cnames{i}); axis off end return;
github
martinarielhartmann/mirtooloct-master
som_batchtrain.m
.m
mirtooloct-master/somtoolbox/som_batchtrain.m
20,584
utf_8
55d753f2fe72fda2647ec34374600a86
function [sMap,sTrain] = som_batchtrain(sMap, D, varargin) %SOM_BATCHTRAIN Use batch algorithm to train the Self-Organizing Map. % % [sM,sT] = som_batchtrain(sM, D, [argID, value, ...]) % % sM = som_batchtrain(sM,D); % sM = som_batchtrain(sM,sD,'radius',[10 3 2 1 0.1],'tracking',3); % [M,sT] = som_batchtrain(M,D,'ep','msize',[10 3],'hexa'); % % Input and output arguments ([]'s are optional): % sM (struct) map struct, the trained and updated map is returned % (matrix) codebook matrix of a self-organizing map % size munits x dim or msize(1) x ... x msize(k) x dim % The trained map codebook is returned. % D (struct) training data; data struct % (matrix) training data, size dlen x dim % [argID, (string) See below. The values which are unambiguous can % value] (varies) be given without the preceeding argID. % % sT (struct) learning parameters used during the training % % Here are the valid argument IDs and corresponding values. The values which % are unambiguous (marked with '*') can be given without the preceeding argID. % 'mask' (vector) BMU search mask, size dim x 1 % 'msize' (vector) map size % 'radius' (vector) neighborhood radiuses, length 1, 2 or trainlen % 'radius_ini' (scalar) initial training radius % 'radius_fin' (scalar) final training radius % 'tracking' (scalar) tracking level, 0-3 % 'trainlen' (scalar) training length in epochs % 'train' *(struct) train struct, parameters for training % 'sTrain','som_train' = 'train' % 'neigh' *(string) neighborhood function, 'gaussian', 'cutgauss', % 'ep' or 'bubble' % 'topol' *(struct) topology struct % 'som_topol','sTopol' = 'topol' % 'lattice' *(string) map lattice, 'hexa' or 'rect' % 'shape' *(string) map shape, 'sheet', 'cyl' or 'toroid' % 'weights' (vector) sample weights: each sample is weighted % % For more help, try 'type som_batchtrain' or check out online documentation. % See also SOM_MAKE, SOM_SEQTRAIN, SOM_TRAIN_STRUCT. %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_batchtrain % % PURPOSE % % Trains a Self-Organizing Map using the batch algorithm. % % SYNTAX % % sM = som_batchtrain(sM,D); % sM = som_batchtrain(sM,sD); % sM = som_batchtrain(...,'argID',value,...); % sM = som_batchtrain(...,value,...); % [sM,sT] = som_batchtrain(M,D,...); % % DESCRIPTION % % Trains the given SOM (sM or M above) with the given training data % (sD or D) using batch training algorithm. If no optional arguments % (argID, value) are given, a default training is done. Using optional % arguments the training parameters can be specified. Returns the % trained and updated SOM and a train struct which contains % information on the training. % % REFERENCES % % Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, % Berlin, 1995, pp. 127-128. % Kohonen, T., "Things you haven't heard about the Self-Organizing % Map", In proceedings of International Conference % on Neural Networks (ICNN), San Francisco, 1993, pp. 1147-1156. % % KNOWN BUGS % % Batchtrain does not work correctly for a map with a single unit. % This is because of the way 'min'-function works. % % REQUIRED INPUT ARGUMENTS % % sM The map to be trained. % (struct) map struct % (matrix) codebook matrix (field .data of map struct) % Size is either [munits dim], in which case the map grid % dimensions (msize) should be specified with optional arguments, % or [msize(1) ... msize(k) dim] in which case the map % grid dimensions are taken from the size of the matrix. % Lattice, by default, is 'rect' and shape 'sheet'. % D Training data. % (struct) data struct % (matrix) data matrix, size [dlen dim] % % OPTIONAL INPUT ARGUMENTS % % argID (string) Argument identifier string (see below). % value (varies) Value for the argument (see below). % % The optional arguments can be given as 'argID',value -pairs. If an % argument is given value multiple times, the last one is % used. The valid IDs and corresponding values are listed below. The values % which are unambiguous (marked with '*') can be given without the % preceeding argID. % % Below is the list of valid arguments: % 'mask' (vector) BMU search mask, size dim x 1. Default is % the one in sM (field '.mask') or a vector of % ones if only a codebook matrix was given. % 'msize' (vector) map grid dimensions. Default is the one % in sM (field sM.topol.msize) or % 'si = size(sM); msize = si(1:end-1);' % if only a codebook matrix was given. % 'radius' (vector) neighborhood radius % length = 1: radius_ini = radius % length = 2: [radius_ini radius_fin] = radius % length > 2: the vector given neighborhood % radius for each step separately % trainlen = length(radius) % 'radius_ini' (scalar) initial training radius % 'radius_fin' (scalar) final training radius % 'tracking' (scalar) tracking level: 0, 1 (default), 2 or 3 % 0 - estimate time % 1 - track time and quantization error % 2 - plot quantization error % 3 - plot quantization error and two first % components % 'trainlen' (scalar) training length in epochs % 'train' *(struct) train struct, parameters for training. % Default parameters, unless specified, % are acquired using SOM_TRAIN_STRUCT (this % also applies for 'trainlen', 'radius_ini' % and 'radius_fin'). % 'sTrain', 'som_topol' (struct) = 'train' % 'neigh' *(string) The used neighborhood function. Default is % the one in sM (field '.neigh') or 'gaussian' % if only a codebook matrix was given. Other % possible values is 'cutgauss', 'ep' and 'bubble'. % 'topol' *(struct) topology of the map. Default is the one % in sM (field '.topol'). % 'sTopol', 'som_topol' (struct) = 'topol' % 'lattice' *(string) map lattice. Default is the one in sM % (field sM.topol.lattice) or 'rect' % if only a codebook matrix was given. % 'shape' *(string) map shape. Default is the one in sM % (field sM.topol.shape) or 'sheet' % if only a codebook matrix was given. % 'weights' (vector) weight for each data vector: during training, % each data sample is weighted with the corresponding % value, for example giving weights = [1 1 2 1] % would have the same result as having third sample % appear 2 times in the data % % OUTPUT ARGUMENTS % % sM the trained map % (struct) if a map struct was given as input argument, a % map struct is also returned. The current training % is added to the training history (sM.trainhist). % The 'neigh' and 'mask' fields of the map struct % are updated to match those of the training. % (matrix) if a matrix was given as input argument, a matrix % is also returned with the same size as the input % argument. % sT (struct) train struct; information of the accomplished training % % EXAMPLES % % Simplest case: % sM = som_batchtrain(sM,D); % sM = som_batchtrain(sM,sD); % % To change the tracking level, 'tracking' argument is specified: % sM = som_batchtrain(sM,D,'tracking',3); % % The change training parameters, the optional arguments 'train','neigh', % 'mask','trainlen','radius','radius_ini' and 'radius_fin' are used. % sM = som_batchtrain(sM,D,'neigh','cutgauss','trainlen',10,'radius_fin',0); % % Another way to specify training parameters is to create a train struct: % sTrain = som_train_struct(sM,'dlen',size(D,1)); % sTrain = som_set(sTrain,'neigh','cutgauss'); % sM = som_batchtrain(sM,D,sTrain); % % By default the neighborhood radius goes linearly from radius_ini to % radius_fin. If you want to change this, you can use the 'radius' argument % to specify the neighborhood radius for each step separately: % sM = som_batchtrain(sM,D,'radius',[5 3 1 1 1 1 0.5 0.5 0.5]); % % You don't necessarily have to use the map struct, but you can operate % directly with codebook matrices. However, in this case you have to % specify the topology of the map in the optional arguments. The % following commads are identical (M is originally a 200 x dim sized matrix): % M = som_batchtrain(M,D,'msize',[20 10],'lattice','hexa','shape','cyl'); % or % M = som_batchtrain(M,D,'msize',[20 10],'hexa','cyl'); % or % sT= som_set('som_topol','msize',[20 10],'lattice','hexa','shape','cyl'); % M = som_batchtrain(M,D,sT); % or % M = reshape(M,[20 10 dim]); % M = som_batchtrain(M,D,'hexa','cyl'); % % The som_batchtrain also returns a train struct with information on the % accomplished training. This struct is also added to the end of the % trainhist field of map struct, in case a map struct was given. % [M,sTrain] = som_batchtrain(M,D,'msize',[20 10]); % [sM,sTrain] = som_batchtrain(sM,D); % sM.trainhist{end}==sTrain % % SEE ALSO % % som_make Initialize and train a SOM using default parameters. % som_seqtrain Train SOM with sequential algorithm. % som_train_struct Determine default training parameters. % Copyright (c) 1997-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 1.0beta juuso 071197 041297 % Version 2.0beta juuso 101199 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Check arguments error(nargchk(2, Inf, nargin)); % check the number of input arguments % map struct_mode = isstruct(sMap); if struct_mode, sTopol = sMap.topol; else orig_size = size(sMap); if ndims(sMap) > 2, si = size(sMap); dim = si(end); msize = si(1:end-1); M = reshape(sMap,[prod(msize) dim]); else msize = [orig_size(1) 1]; dim = orig_size(2); end sMap = som_map_struct(dim,'msize',msize); sTopol = sMap.topol; end [munits dim] = size(sMap.codebook); % data if isstruct(D), data_name = D.name; D = D.data; else data_name = inputname(2); end nonempty = find(sum(isnan(D),2) < dim); D = D(nonempty,:); % remove empty vectors from the data [dlen ddim] = size(D); % check input dimension if dim ~= ddim, error('Map and data input space dimensions disagree.'); end % varargin sTrain = som_set('som_train','algorithm','batch','neigh', ... sMap.neigh,'mask',sMap.mask,'data_name',data_name); radius = []; tracking = 1; weights = 1; i=1; while i<=length(varargin), argok = 1; if ischar(varargin{i}), switch varargin{i}, % argument IDs case 'msize', i=i+1; sTopol.msize = varargin{i}; case 'lattice', i=i+1; sTopol.lattice = varargin{i}; case 'shape', i=i+1; sTopol.shape = varargin{i}; case 'mask', i=i+1; sTrain.mask = varargin{i}; case 'neigh', i=i+1; sTrain.neigh = varargin{i}; case 'trainlen', i=i+1; sTrain.trainlen = varargin{i}; case 'tracking', i=i+1; tracking = varargin{i}; case 'weights', i=i+1; weights = varargin{i}; case 'radius_ini', i=i+1; sTrain.radius_ini = varargin{i}; case 'radius_fin', i=i+1; sTrain.radius_fin = varargin{i}; case 'radius', i=i+1; l = length(varargin{i}); if l==1, sTrain.radius_ini = varargin{i}; else sTrain.radius_ini = varargin{i}(1); sTrain.radius_fin = varargin{i}(end); if l>2, radius = varargin{i}; end end case {'sTrain','train','som_train'}, i=i+1; sTrain = varargin{i}; case {'topol','sTopol','som_topol'}, i=i+1; sTopol = varargin{i}; if prod(sTopol.msize) ~= munits, error('Given map grid size does not match the codebook size.'); end % unambiguous values case {'hexa','rect'}, sTopol.lattice = varargin{i}; case {'sheet','cyl','toroid'}, sTopol.shape = varargin{i}; case {'gaussian','cutgauss','ep','bubble'}, sTrain.neigh = varargin{i}; otherwise argok=0; end elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), switch varargin{i}(1).type, case 'som_topol', sTopol = varargin{i}; if prod(sTopol.msize) ~= munits, error('Given map grid size does not match the codebook size.'); end case 'som_train', sTrain = varargin{i}; otherwise argok=0; end else argok = 0; end if ~argok, disp(['(som_batchtrain) Ignoring invalid argument #' num2str(i+2)]); end i = i+1; end % take only weights of non-empty vectors if length(weights)>dlen, weights = weights(nonempty); end % trainlen if ~isempty(radius), sTrain.trainlen = length(radius); end % check topology if struct_mode, if ~strcmp(sTopol.lattice,sMap.topol.lattice) | ... ~strcmp(sTopol.shape,sMap.topol.shape) | ... any(sTopol.msize ~= sMap.topol.msize), warning('Changing the original map topology.'); end end sMap.topol = sTopol; % complement the training struct sTrain = som_train_struct(sTrain,sMap,'dlen',dlen); if isempty(sTrain.mask), sTrain.mask = ones(dim,1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% initialize M = sMap.codebook; mask = sTrain.mask; trainlen = sTrain.trainlen; % neighborhood radius if trainlen==1, radius = sTrain.radius_ini; elseif length(radius)<=2, r0 = sTrain.radius_ini; r1 = sTrain.radius_fin; radius = r1 + fliplr((0:(trainlen-1))/(trainlen-1)) * (r0 - r1); else % nil end % distance between map units in the output space % Since in the case of gaussian and ep neighborhood functions, the % equations utilize squares of the unit distances and in bubble case % it doesn't matter which is used, the unitdistances and neighborhood % radiuses are squared. Ud = som_unit_dists(sTopol); Ud = Ud.^2; radius = radius.^2; % zero neighborhood radius may cause div-by-zero error radius(find(radius==0)) = eps; % The training algorithm involves calculating weighted Euclidian distances % to all map units for each data vector. Basically this is done as % for i=1:dlen, % for j=1:munits, % for k=1:dim % Dist(j,i) = Dist(j,i) + mask(k) * (D(i,k) - M(j,k))^2; % end % end % end % where mask is the weighting vector for distance calculation. However, taking % into account that distance between vectors m and v can be expressed as % |m - v|^2 = sum_i ((m_i - v_i)^2) = sum_i (m_i^2 + v_i^2 - 2*m_i*v_i) % this can be made much faster by transforming it to a matrix operation: % Dist = (M.^2)*mask*ones(1,d) + ones(m,1)*mask'*(D'.^2) - 2*M*diag(mask)*D' % Of the involved matrices, several are constant, as the mask and data do % not change during training. Therefore they are calculated beforehand. % For the case where there are unknown components in the data, each data % vector will have an individual mask vector so that for that unit, the % unknown components are not taken into account in distance calculation. % In addition all NaN's are changed to zeros so that they don't screw up % the matrix multiplications and behave correctly in updating step. Known = ~isnan(D); W1 = (mask*ones(1,dlen)) .* Known'; D(find(~Known)) = 0; % constant matrices WD = 2*diag(mask)*D'; % constant matrix dconst = ((D.^2)*mask)'; % constant in distance calculation for each data sample % W2 = ones(munits,1)*mask'; D2 = (D'.^2); % initialize tracking start = clock; qe = zeros(trainlen,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Action % With the 'blen' parameter you can control the memory consumption % of the algorithm, which is in practive directly proportional % to munits*blen. If you're having problems with memory, try to % set the value of blen lower. blen = min(munits,dlen); % reserve some space bmus = zeros(1,dlen); ddists = zeros(1,dlen); for t = 1:trainlen, % batchy train - this is done a block of data (inds) at a time % rather than in a single sweep to save memory consumption. % The 'Dist' and 'Hw' matrices have size munits*blen % which - if you have a lot of data - would be HUGE if you % calculated it all at once. A single-sweep version would % look like this: % Dist = (M.^2)*W1 - M*WD; %+ W2*D2 % [ddists, bmus] = min(Dist); % (notice that the W2*D2 term can be ignored since it is constant) % This "batchy" version is the same as single-sweep if blen=dlen. i0 = 0; while i0+1<=dlen, inds = [(i0+1):min(dlen,i0+blen)]; i0 = i0+blen; Dist = (M.^2)*W1(:,inds) - M*WD(:,inds); [ddists(inds), bmus(inds)] = min(Dist); end % tracking if tracking > 0, ddists = ddists+dconst; % add the constant term ddists(ddists<0) = 0; % rounding errors... qe(t) = mean(sqrt(ddists)); trackplot(M,D,tracking,start,t,qe); end % neighborhood % notice that the elements Ud and radius have been squared! % note: 'bubble' matches the original "Batch Map" algorithm switch sTrain.neigh, case 'bubble', H = (Ud<=radius(t)); case 'gaussian', H = exp(-Ud/(2*radius(t))); case 'cutgauss', H = exp(-Ud/(2*radius(t))) .* (Ud<=radius(t)); case 'ep', H = (1-Ud/radius(t)) .* (Ud<=radius(t)); end % update % In principle the updating step goes like this: replace each map unit % by the average of the data vectors that were in its neighborhood. % The contribution, or activation, of data vectors in the mean can % be varied with the neighborhood function. This activation is given % by matrix H. So, for each map unit the new weight vector is % % m = sum_i (h_i * d_i) / sum_i (h_i), % % where i denotes the index of data vector. Since the values of % neighborhood function h_i are the same for all data vectors belonging to % the Voronoi set of the same map unit, the calculation is actually done % by first calculating a partition matrix P with elements p_ij=1 if the % BMU of data vector j is i. P = sparse(bmus,[1:dlen],weights,munits,dlen); % Then the sum of vectors in each Voronoi set are calculated (P*D) and the % neighborhood is taken into account by calculating a weighted sum of the % Voronoi sum (H*). The "activation" matrix A is the denominator of the % equation above. S = H*(P*D); A = H*(P*Known); % If you'd rather make this without using the Voronoi sets try the following: % Hi = H(:,bmus); % S = Hi * D; % "sum_i (h_i * d_i)" % A = Hi * Known; % "sum_i (h_i)" % The bad news is that the matrix Hi has size [munits x dlen]... % only update units for which the "activation" is nonzero nonzero = find(A > 0); M(nonzero) = S(nonzero) ./ A(nonzero); end; % for t = 1:trainlen %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Build / clean up the return arguments % tracking if tracking > 0, fprintf(1,'\n'); end % update structures sTrain = som_set(sTrain,'time',datestr(now,0)); if struct_mode, sMap = som_set(sMap,'codebook',M,'mask',sTrain.mask,'neigh',sTrain.neigh); tl = length(sMap.trainhist); sMap.trainhist(tl+1) = sTrain; else sMap = reshape(M,orig_size); end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions %%%%%%%% function [] = trackplot(M,D,tracking,start,n,qe) l = length(qe); elap_t = etime(clock,start); tot_t = elap_t*l/n; fprintf(1,'\rTraining: %3.0f/ %3.0f s',elap_t,tot_t) switch tracking case 1, case 2, plot(1:n,qe(1:n),(n+1):l,qe((n+1):l)) title('Quantization error after each epoch'); drawnow otherwise, subplot(2,1,1), plot(1:n,qe(1:n),(n+1):l,qe((n+1):l)) title('Quantization error after each epoch'); subplot(2,1,2), plot(M(:,1),M(:,2),'ro',D(:,1),D(:,2),'b+'); title('First two components of map units (o) and data vectors (+)'); drawnow end % end of trackplot
github
martinarielhartmann/mirtooloct-master
som_stats_report.m
.m
mirtooloct-master/somtoolbox/som_stats_report.m
3,633
utf_8
eca74b20e5ec9e82e9aeee118cd81303
function som_stats_report(csS,fname,fmt,texonly) % SOM_STATS_REPORT Make report of the statistics. % % som_stats_report(csS, fname, fmt, [standalone]) % % som_stats_report(csS, 'data_stats', 'ps') % % Input and output arguments ([]'s are optional): % csS (cell array) of statistics structs % (struct) a statistics struct % fname (string) output file name (without extension) % (cellstr) {direc, fname} % fmt (string) report format: 'ps', 'pdf', 'html' or 'txt' % [texonly] (any) for 'ps' and 'pdf' formats: if 4th argument % is given, only the tex file is written % (w/o document start/end), and it is not compiled % % See also SOM_STATS, SOM_STATS_PLOT, SOM_STATS_TABLE, SOM_TABLE_PRINT, REP_UTILS. % Contributed to SOM Toolbox 2.0, December 31st, 2001 by Juha Vesanto % Copyright (c) by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 311201 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% input arguments if isstruct(csS), csS = {csS}; end dim = length(csS); if iscell(fname), direc = fname{1}; fname = fname{2}; else direc = '.'; end if nargin<4, texonly = 0; else texonly = 1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% action % additional analysis continuity = zeros(dim,1); for i=1:dim, continuity(i) = csS{i}.nunique / csS{i}.nvalid; end entropy_rel = zeros(dim,1); for i=1:dim, c = csS{i}.hist.counts; if length(c) < 2 | all(c==0), entropy(i) = 0; else maxent = log(length(c)); c = c(c>0)/sum(c); entropy_rel(i) = -sum(c.*log(c)) / maxent; end end % meta-statistics values = {'Number of variables',dim; ... 'Number of samples',csS{1}.ntotal; ... 'Valid values',c_and_p_str(count_total(csS,'nvalid'),dim*csS{1}.ntotal); ... 'Mean(#unique / #valid)',mean(continuity); ... 'Mean relative entropy',mean(entropy_rel)}; %'Dataset name',sD.name; 'Report generated',datestr(now); sTdset = som_table_struct(values); % statistics tables [sTstats,csThist] = som_stats_table(csS); sTstats = som_table_modify(sTstats,'addcol',entropy_rel,{'entropy'}); % write report if isempty(fname), fid = 1; else switch fmt, case {'ps','pdf'}, ending = '.tex'; case 'html', ending = '.html'; case 'txt', ending = '.txt'; end fid = fopen([direc '/' fname ending],'w'); end if ~texonly, rep_utils('header',fmt,fid); end rep_utils({'inserttable',sTdset,1,0},fmt,fid); rep_utils({'insertbreak'},fmt,fid); rep_utils({'inserttable',sTstats,1,0},fmt,fid); rep_utils({'insertbreak'},fmt,fid); som_stats_plot(csS,'stats'); rep_utils({'printfigure',[direc '/histograms']},fmt); rep_utils({'insertfigure','histograms'},fmt,fid); for i=1:dim, rep_utils({'insertbreak'},fmt,fid); rep_utils({'inserttable',csThist{i},1,0},fmt,fid); end if ~texonly, rep_utils('footer',fmt,fid); end if fid~=1, fclose(fid); end if ~texonly & any(strcmp(fmt,{'ps','pdf'})), rep_utils('compile',fmt); end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function a = count_total(csS,field) % count total of the field values a = 0; for i=1:length(csS), a = a + getfield(csS{i},field); end return; function str = c_and_p_str(n,m) % return a string of form # (%), e.g. '23 (12%)' if n==m, p = '100'; elseif n==0, p = '0'; else p = sprintf('%.2g',100*n/m); end str = sprintf('%d (%s%%)',round(n),p); return;
github
martinarielhartmann/mirtooloct-master
som_eucdist2.m
.m
mirtooloct-master/somtoolbox/som_eucdist2.m
2,270
utf_8
6f74c5daaf9a1667b8937a1ceb29ffa2
function d=som_eucdist2(Data, Proto) %SOM_EUCDIST2 Calculates matrix of squared euclidean distances between set of vectors or map, data struct % % d=som_eucdist2(D, P) % % d=som_eucdist(sMap, sData); % d=som_eucdist(sData, sMap); % d=som_eucdist(sMap1, sMap2); % d=som_eucdist(datamatrix1, datamatrix2); % % Input and output arguments ([]'s are optional): % D (matrix) size Nxd % (struct) map or data struct % P (matrix) size Pxd % (struct) map or data struct % d (matrix) distance matrix of size NxP % % IMPORTANT % % * Calculates _squared_ euclidean distances % * Observe that the mask in the map struct is not taken into account while % calculating the euclidean distance % % See also KNN, PDIST. % Contributed to SOM Toolbox 2.0, October 29th, 2000 by Johan Himberg % Copyright (c) by Johan Himberg % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta Johan 291000 %% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isstruct(Data); if isfield(Data,'type') & ischar(Data.type), ; else error('Invalid map/data struct?'); end switch Data.type case 'som_map' data=Data.codebook; case 'som_data' data=Data.data; end else % is already a matrix data=Data; end % Take prototype vectors from prototype struct if isstruct(Proto), if isfield(Proto,'type') & ischar(Proto.type), ; else error('Invalid map/data struct?'); end switch Proto.type case 'som_map' proto=Proto.codebook; case 'som_data' proto=Proto.data; end else % is already a matrix proto=Proto; end % Check that inputs are matrices if ~vis_valuetype(proto,{'nxm'}) | ~vis_valuetype(data,{'nxm'}), error('Prototype or data input not valid.') end % Record data&proto sizes and check their dims [N_data dim_data]=size(data); [N_proto dim_proto]=size(proto); if dim_proto ~= dim_data, error('Data and prototype vector dimension does not match.'); end % Calculate euclidean distances between classifiees and prototypes d=distance(data,proto); %%%% Classification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function d=distance(X,Y); % Euclidean distance matrix between row vectors in X and Y U=~isnan(Y); Y(~U)=0; V=~isnan(X); X(~V)=0; d=abs(X.^2*U'+V*Y'.^2-2*X*Y');
github
martinarielhartmann/mirtooloct-master
som_norm_variable.m
.m
mirtooloct-master/somtoolbox/som_norm_variable.m
19,542
utf_8
9323ed0f31d148b4f88cacf4454fdb22
function [x,sNorm] = som_norm_variable(x, method, operation) %SOM_NORM_VARIABLE Normalize or denormalize a scalar variable. % % [x,sNorm] = som_norm_variable(x, method, operation) % % xnew = som_norm_variable(x,'var','do'); % [dummy,sN] = som_norm_variable(x,'log','init'); % [xnew,sN] = som_norm_variable(x,sN,'do'); % xorig = som_norm_variable(xnew,sN,'undo'); % % Input and output arguments: % x (vector) a set of values of a scalar variable for % which the (de)normalization is performed. % The processed values are returned. % method (string) identifier for a normalization method: 'var', % 'range', 'log', 'logistic', 'histD', or 'histC'. % A normalization struct with default values is created. % (struct) normalization struct, or an array of such % (cellstr) first string gives normalization operation, and the % second gives denormalization operation, with x % representing the variable, for example: % {'x+2','x-2}, or {'exp(-x)','-log(x)'} or {'round(x)'}. % Note that in the last case, no denorm operation is % defined. % operation (string) the operation to be performed: 'init', 'do' or 'undo' % % sNorm (struct) updated normalization struct/struct array % % For more help, try 'type som_norm_variable' or check out online documentation. % See also SOM_NORMALIZE, SOM_DENORMALIZE. %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_norm_variable % % PURPOSE % % Initialize, apply and undo normalizations on a given vector of % scalar values. % % SYNTAX % % xnew = som_norm_variable(x,method,operation) % xnew = som_norm_variable(x,sNorm,operation) % [xnew,sNorm] = som_norm_variable(...) % % DESCRIPTION % % This function is used to initialize, apply and undo normalizations % on scalar variables. It is the low-level function that upper-level % functions SOM_NORMALIZE and SOM_DENORMALIZE utilize to actually (un)do % the normalizations. % % Normalizations are typically performed to control the variance of % vector components. If some vector components have variance which is % significantly higher than the variance of other components, those % components will dominate the map organization. Normalization of % the variance of vector components (method 'var') is used to prevent % that. In addition to variance normalization, other methods have % been implemented as well (see list below). % % Usually normalizations convert the variable values so that they no % longer make any sense: the values are still ordered, but their range % may have changed so radically that interpreting the numbers in the % original context is very hard. For this reason all implemented methods % are (more or less) revertible. The normalizations are monotonic % and information is saved so that they can be undone. Also, the saved % information makes it possible to apply the EXACTLY SAME normalization % to another set of values. The normalization information is determined % with 'init' operation, while 'do' and 'undo' operations are used to % apply or revert the normalization. % % The normalization information is saved in a normalization struct, % which is returned as the second argument of this function. Note that % normalization operations may be stacked. In this case, normalization % structs are positioned in a struct array. When applied, the array is % gone through from start to end, and when undone, in reverse order. % % method description % % 'var' Variance normalization. A linear transformation which % scales the values such that their variance=1. This is % convenient way to use Mahalanobis distance measure without % actually changing the distance calculation procedure. % % 'range' Normalization of range of values. A linear transformation % which scales the values between [0,1]. % % 'log' Logarithmic normalization. In many cases the values of % a vector component are exponentially distributed. This % normalization is a good way to get more resolution to % (the low end of) that vector component. What this % actually does is a non-linear transformation: % x_new = log(x_old - m + 1) % where m=min(x_old) and log is the natural logarithm. % Applying the transformation to a value which is lower % than m-1 will give problems, as the result is then complex. % If the minimum for values is known a priori, % it might be a good idea to initialize the normalization with % [dummy,sN] = som_norm_variable(minimum,'log','init'); % and normalize only after this: % x_new = som_norm_variable(x,sN,'do'); % % 'logistic' or softmax normalization. This normalization ensures % that all values in the future, too, are within the range % [0,1]. The transformation is more-or-less linear in the % middle range (around mean value), and has a smooth % nonlinearity at both ends which ensures that all values % are within the range. The data is first scaled as in % variance normalization: % x_scaled = (x_old - mean(x_old))/std(x_old) % and then transformed with the logistic function % x_new = 1/(1+exp(-x_scaled)) % % 'histD' Discrete histogram equalization. Non-linear. Orders the % values and replaces each value by its ordinal number. % Finally, scales the values such that they are between [0,1]. % Useful for both discrete and continuous variables, but as % the saved normalization information consists of all % unique values of the initialization data set, it may use % considerable amounts of memory. If the variable can get % more than a few values (say, 20), it might be better to % use 'histC' method below. Another important note is that % this method is not exactly revertible if it is applied % to values which are not part of the original value set. % % 'histC' Continuous histogram equalization. Actually, a partially % linear transformation which tries to do something like % histogram equalization. The value range is divided to % a number of bins such that the number of values in each % bin is (almost) the same. The values are transformed % linearly in each bin. For example, values in bin number 3 % are scaled between [3,4[. Finally, all values are scaled % between [0,1]. The number of bins is the square root % of the number of unique values in the initialization set, % rounded up. The resulting histogram equalization is not % as good as the one that 'histD' makes, but the benefit % is that it is exactly revertible - even outside the % original value range (although the results may be funny). % % 'eval' With this method, freeform normalization operations can be % specified. The parameter field contains strings to be % evaluated with 'eval' function, with variable name 'x' % representing the variable itself. The first string is % the normalization operation, and the second is a % denormalization operation. If the denormalization operation % is empty, it is ignored. % % INPUT ARGUMENTS % % x (vector) The scalar values to which the normalization % operation is applied. % % method The normalization specification. % (string) Identifier for a normalization method: 'var', % 'range', 'log', 'logistic', 'histD' or 'histC'. % Corresponding default normalization struct is created. % (struct) normalization struct % (struct array) of normalization structs, applied to % x one after the other % (cellstr) of length % (cellstr array) first string gives normalization operation, and % the second gives denormalization operation, with x % representing the variable, for example: % {'x+2','x-2}, or {'exp(-x)','-log(x)'} or {'round(x)'}. % Note that in the last case, no denorm operation is % defined. % % note: if the method is given as struct(s), it is % applied (done or undone, as specified by operation) % regardless of what the value of '.status' field % is in the struct(s). Only if the status is % 'uninit', the undoing operation is halted. % Anyhow, the '.status' fields in the returned % normalization struct(s) is set to approriate value. % % operation (string) The operation to perform: 'init' to initialize % the normalization struct, 'do' to perform the % normalization, 'undo' to undo the normalization, % if possible. If operation 'do' is given, but the % normalization struct has not yet been initialized, % it is initialized using the given data (x). % % OUTPUT ARGUMENTS % % x (vector) Appropriately processed values. % % sNorm (struct) Updated normalization struct/struct array. If any, % the '.status' and '.params' fields are updated. % % EXAMPLES % % To initialize and apply a normalization on a set of scalar values: % % [x_new,sN] = som_norm_variable(x_old,'var','do'); % % To just initialize, use: % % [dummy,sN] = som_norm_variable(x_old,'var','init'); % % To undo the normalization(s): % % x_orig = som_norm_variable(x_new,sN,'undo'); % % Typically, normalizations of data structs/sets are handled using % functions SOM_NORMALIZE and SOM_DENORMALIZE. However, when only the % values of a single variable are of interest, SOM_NORM_VARIABLE may % be useful. For example, assume one wants to apply the normalization % done on a component (i) of a data struct (sD) to a new set of values % (x) of that component. With SOM_NORM_VARIABLE this can be done with: % % x_new = som_norm_variable(x,sD.comp_norm{i},'do'); % % Now, as the normalizations in sD.comp_norm{i} have already been % initialized with the original data set (presumably sD.data), % the EXACTLY SAME normalization(s) can be applied to the new values. % The same thing can be done with SOM_NORMALIZE function, too: % % x_new = som_normalize(x,sD.comp_norm{i}); % % Or, if the new data set were in variable D - a matrix of same % dimension as the original data set: % % D_new = som_normalize(D,sD,i); % % SEE ALSO % % som_normalize Add/apply/redo normalizations for a data struct/set. % som_denormalize Undo normalizations of a data struct/set. % Copyright (c) 1998-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 151199 170400 150500 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% check arguments error(nargchk(3, 3, nargin)); % check no. of input arguments is correct % method sNorm = []; if ischar(method) if any(strcmp(method,{'var','range','log','logistic','histD','histC'})), sNorm = som_set('som_norm','method',method); else method = cellstr(method); end end if iscell(method), if length(method)==1 & isstruct(method{1}), sNorm = method{1}; else if length(method)==1 | isempty(method{2}), method{2} = 'x'; end sNorm = som_set('som_norm','method','eval','params',method); end else sNorm = method; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% action order = [1:length(sNorm)]; if length(order)>1 & strcmp(operation,'undo'), order = order(end:-1:1); end for i=order, % initialize if strcmp(operation,'init') | ... (strcmp(operation,'do') & strcmp(sNorm(i).status,'uninit')), % case method = 'hist' if strcmp(sNorm(i).method,'hist'), inds = find(~isnan(x) & ~isinf(x)); if length(unique(x(inds)))>20, sNorm(i).method = 'histC'; else sNorm{i}.method = 'histD'; end end switch(sNorm(i).method), case 'var', params = norm_variance_init(x); case 'range', params = norm_scale01_init(x); case 'log', params = norm_log_init(x); case 'logistic', params = norm_logistic_init(x); case 'histD', params = norm_histeqD_init(x); case 'histC', params = norm_histeqC_init(x); case 'eval', params = sNorm(i).params; otherwise, error(['Unrecognized method: ' sNorm(i).method]); end sNorm(i).params = params; sNorm(i).status = 'undone'; end % do / undo if strcmp(operation,'do'), switch(sNorm(i).method), case 'var', x = norm_scale_do(x,sNorm(i).params); case 'range', x = norm_scale_do(x,sNorm(i).params); case 'log', x = norm_log_do(x,sNorm(i).params); case 'logistic', x = norm_logistic_do(x,sNorm(i).params); case 'histD', x = norm_histeqD_do(x,sNorm(i).params); case 'histC', x = norm_histeqC_do(x,sNorm(i).params); case 'eval', x = norm_eval_do(x,sNorm(i).params); otherwise, error(['Unrecognized method: ' sNorm(i).method]); end sNorm(i).status = 'done'; elseif strcmp(operation,'undo'), if strcmp(sNorm(i).status,'uninit'), warning('Could not undo: uninitialized normalization struct.') break; end switch(sNorm(i).method), case 'var', x = norm_scale_undo(x,sNorm(i).params); case 'range', x = norm_scale_undo(x,sNorm(i).params); case 'log', x = norm_log_undo(x,sNorm(i).params); case 'logistic', x = norm_logistic_undo(x,sNorm(i).params); case 'histD', x = norm_histeqD_undo(x,sNorm(i).params); case 'histC', x = norm_histeqC_undo(x,sNorm(i).params); case 'eval', x = norm_eval_undo(x,sNorm(i).params); otherwise, error(['Unrecognized method: ' sNorm(i).method]); end sNorm(i).status = 'undone'; elseif ~strcmp(operation,'init'), error(['Unrecognized operation: ' operation]) end end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions % linear scaling function p = norm_variance_init(x) inds = find(~isnan(x) & isfinite(x)); p = [mean(x(inds)), std(x(inds))]; if p(2) == 0, p(2) = 1; end %end of norm_variance_init function p = norm_scale01_init(x) inds = find(~isnan(x) & isfinite(x)); mi = min(x(inds)); ma = max(x(inds)); if mi == ma, p = [mi, 1]; else p = [mi, ma-mi]; end %end of norm_scale01_init function x = norm_scale_do(x,p) x = (x - p(1)) / p(2); % end of norm_scale_do function x = norm_scale_undo(x,p) x = x * p(2) + p(1); % end of norm_scale_undo % logarithm function p = norm_log_init(x) inds = find(~isnan(x) & isfinite(x)); p = min(x(inds)); % end of norm_log_init function x = norm_log_do(x,p) x = log(x - p +1); % if any(~isreal(x)), ok = 0; end % end of norm_log_do function x = norm_log_undo(x,p) x = exp(x) -1 + p; % end of norm_log_undo % logistic function p = norm_logistic_init(x) inds = find(~isnan(x) & isfinite(x)); p = [mean(x(inds)), std(x(inds))]; if p(2)==0, p(2) = 1; end % end of norm_logistic_init function x = norm_logistic_do(x,p) x = (x-p(1))/p(2); x = 1./(1+exp(-x)); % end of norm_logistic_do function x = norm_logistic_undo(x,p) x = log(x./(1-x)); x = x*p(2)+p(1); % end of norm_logistic_undo % histogram equalization for discrete values function p = norm_histeqD_init(x) inds = find(~isnan(x) & ~isinf(x)); p = unique(x(inds)); % end of norm_histeqD_init function x = norm_histeqD_do(x,p) bins = length(p); inds = find(~isnan(x) & ~isinf(x))'; for i = inds, [dummy ind] = min(abs(x(i) - p)); % data item closer to the left-hand bin wall is indexed after RH wall if x(i) > p(ind) & ind < bins, x(i) = ind + 1; else x(i) = ind; end end x = (x-1)/(bins-1); % normalization between [0,1] % end of norm_histeqD_do function x = norm_histeqD_undo(x,p) bins = length(p); x = round(x*(bins-1)+1); inds = find(~isnan(x) & ~isinf(x)); x(inds) = p(x(inds)); % end of norm_histeqD_undo % histogram equalization with partially linear functions function p = norm_histeqC_init(x) % investigate x inds = find(~isnan(x) & ~isinf(x)); samples = length(inds); xs = unique(x(inds)); mi = xs(1); ma = xs(end); % decide number of limits lims = ceil(sqrt(length(xs))); % 2->2,100->10,1000->32,10000->100 % decide limits if lims==1, p = [mi, mi+1]; lims = 2; elseif lims==2, p = [mi, ma]; else p = zeros(lims,1); p(1) = mi; p(end) = ma; binsize = zeros(lims-1,1); b = 1; avebinsize = samples/(lims-1); for i=1:(length(xs)-1), binsize(b) = binsize(b) + sum(x==xs(i)); if binsize(b) >= avebinsize, b = b + 1; p(b) = (xs(i)+xs(i+1))/2; end if b==(lims-1), binsize(b) = samples-sum(binsize); break; else avebinsize = (samples-sum(binsize))/(lims-1-b); end end end % end of norm_histeqC_init function x = norm_histeqC_do(x,p) xnew = x; lims = length(p); % handle values below minimum r = p(2)-p(1); inds = find(x<=p(1) & isfinite(x)); if any(inds), xnew(inds) = 0-(p(1)-x(inds))/r; end % handle values above maximum r = p(end)-p(end-1); inds = find(x>p(end) & isfinite(x)); if any(inds), xnew(inds) = lims-1+(x(inds)-p(end))/r; end % handle all other values for i=1:(lims-1), r0 = p(i); r1 = p(i+1); r = r1-r0; inds = find(x>r0 & x<=r1); if any(inds), xnew(inds) = i-1+(x(inds)-r0)/r; end end % scale so that minimum and maximum correspond to 0 and 1 x = xnew/(lims-1); % end of norm_histeqC_do function x = norm_histeqC_undo(x,p) xnew = x; lims = length(p); % scale so that 0 and 1 correspond to minimum and maximum x = x*(lims-1); % handle values below minimum r = p(2)-p(1); inds = find(x<=0 & isfinite(x)); if any(inds), xnew(inds) = x(inds)*r + p(1); end % handle values above maximum r = p(end)-p(end-1); inds = find(x>lims-1 & isfinite(x)); if any(inds), xnew(inds) = (x(inds)-(lims-1))*r+p(end); end % handle all other values for i=1:(lims-1), r0 = p(i); r1 = p(i+1); r = r1-r0; inds = find(x>i-1 & x<=i); if any(inds), xnew(inds) = (x(inds)-(i-1))*r + r0; end end x = xnew; % end of norm_histeqC_undo % eval function p = norm_eval_init(method) p = method; %end of norm_eval_init function x = norm_eval_do(x,p) x_tmp = eval(p{1}); if size(x_tmp,1)>=1 & size(x,1)>=1 & ... size(x_tmp,2)==1 & size(x,2)==1, x = x_tmp; end %end of norm_eval_do function x = norm_eval_undo(x,p) x_tmp = eval(p{2}); if size(x_tmp,1)>=1 & size(x,1)>=1 & ... size(x_tmp,2)==1 & size(x,2)==1, x = x_tmp; end %end of norm_eval_undo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
martinarielhartmann/mirtooloct-master
cca.m
.m
mirtooloct-master/somtoolbox/cca.m
7,987
utf_8
f9446f8801dde781d7e8f400842fb0c2
function [P] = cca(D, P, epochs, Mdist, alpha0, lambda0) %CCA Projects data vectors using Curvilinear Component Analysis. % % P = cca(D, P, epochs, [Dist], [alpha0], [lambda0]) % % P = cca(D,2,10); % projects the given data to a plane % P = cca(D,pcaproj(D,2),5); % same, but with PCA initialization % P = cca(D, 2, 10, Dist); % same, but the given distance matrix is used % % Input and output arguments ([]'s are optional): % D (matrix) the data matrix, size dlen x dim % (struct) data or map struct % P (scalar) output dimension % (matrix) size dlen x odim, the initial projection % epochs (scalar) training length % [Dist] (matrix) pairwise distance matrix, size dlen x dlen. % If the distances in the input space should % be calculated otherwise than as euclidian % distances, the distance from each vector % to each other vector can be given here, % size dlen x dlen. For example PDIST % function can be used to calculate the % distances: Dist = squareform(pdist(D,'mahal')); % [alpha0] (scalar) initial step size, 0.5 by default % [lambda0] (scalar) initial radius of influence, 3*max(std(D)) by default % % P (matrix) size dlen x odim, the projections % % Unknown values (NaN's) in the data: projections of vectors with % unknown components tend to drift towards the center of the % projection distribution. Projections of totally unknown vectors are % set to unknown (NaN). % % See also SAMMON, PCAPROJ. % Reference: Demartines, P., Herault, J., "Curvilinear Component % Analysis: a Self-Organizing Neural Network for Nonlinear % Mapping of Data Sets", IEEE Transactions on Neural Networks, % vol 8, no 1, 1997, pp. 148-154. % Contributed to SOM Toolbox 2.0, February 2nd, 2000 by Juha Vesanto % Copyright (c) by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % juuso 171297 040100 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Check arguments error(nargchk(3, 6, nargin)); % check the number of input arguments % input data if isstruct(D), if strcmp(D.type,'som_map'), D = D.codebook; else D = D.data; end end [noc dim] = size(D); noc_x_1 = ones(noc, 1); % used frequently me = zeros(1,dim); st = zeros(1,dim); for i=1:dim, me(i) = mean(D(find(isfinite(D(:,i))),i)); st(i) = std(D(find(isfinite(D(:,i))),i)); end % initial projection if prod(size(P))==1, P = (2*rand(noc,P)-1).*st(noc_x_1,1:P) + me(noc_x_1,1:P); else % replace unknown projections with known values inds = find(isnan(P)); P(inds) = rand(size(inds)); end [dummy odim] = size(P); odim_x_1 = ones(odim, 1); % this is used frequently % training length train_len = epochs*noc; % random sample order rand('state',sum(100*clock)); sample_inds = ceil(noc*rand(train_len,1)); % mutual distances if nargin<4 | isempty(Mdist) | all(isnan(Mdist(:))), fprintf(2, 'computing mutual distances\r'); dim_x_1 = ones(dim,1); for i = 1:noc, x = D(i,:); Diff = D - x(noc_x_1,:); N = isnan(Diff); Diff(find(N)) = 0; Mdist(:,i) = sqrt((Diff.^2)*dim_x_1); N = find(sum(N')==dim); %mutual distance unknown if ~isempty(N), Mdist(N,i) = NaN; end end else % if the distance matrix is output from PDIST function if size(Mdist,1)==1, Mdist = squareform(Mdist); end if size(Mdist,1)~=noc, error('Mutual distance matrix size and data set size do not match'); end end % alpha and lambda if nargin<5 | isempty(alpha0) | isnan(alpha0), alpha0 = 0.5; end alpha = potency_curve(alpha0,alpha0/100,train_len); if nargin<6 | isempty(lambda0) | isnan(lambda0), lambda0 = max(st)*3; end lambda = potency_curve(lambda0,0.01,train_len); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Action k=0; fprintf(2, 'iterating: %d / %d epochs\r',k,epochs); for i=1:train_len, ind = sample_inds(i); % sample index dx = Mdist(:,ind); % mutual distances in input space known = find(~isnan(dx)); % known distances if ~isempty(known), % sample vector's projection y = P(ind,:); % distances in output space Dy = P(known,:) - y(noc_x_1(known),:); dy = sqrt((Dy.^2)*odim_x_1); % relative effect dy(find(dy==0)) = 1; % to get rid of div-by-zero's fy = exp(-dy/lambda(i)) .* (dx(known) ./ dy - 1); % Note that the function F here is e^(-dy/lambda)) % instead of the bubble function 1(lambda-dy) used in the % paper. % Note that here a simplification has been made: the derivatives of the % F function have been ignored in calculating the gradient of error % function w.r.t. to changes in dy. % update P(known,:) = P(known,:) + alpha(i)*fy(:,odim_x_1).*Dy; end % track if rem(i,noc)==0, k=k+1; fprintf(2, 'iterating: %d / %d epochs\r',k,epochs); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% clear up % calculate error error = cca_error(P,Mdist,lambda(train_len)); fprintf(2,'%d iterations, error %f \n', epochs, error); % set projections of totally unknown vectors as unknown unknown = find(sum(isnan(D)')==dim); P(unknown,:) = NaN; return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% tips % to plot the results, use the code below %subplot(2,1,1), %switch(odim), % case 1, plot(P(:,1),ones(dlen,1),'x') % case 2, plot(P(:,1),P(:,2),'x'); % otherwise, plot3(P(:,1),P(:,2),P(:,3),'x'); rotate3d on %end %subplot(2,1,2), dydxplot(P,Mdist); % to a project a new point x in the input space to the output space % do the following: % Diff = D - x(noc_x_1,:); Diff(find(isnan(Diff))) = 0; % dx = sqrt((Diff.^2)*dim_x_1); % p = project_point(P,x,dx); % this function can be found from below % tlen = size(p,1); % plot(P(:,1),P(:,2),'bx',p(tlen,1),p(tlen,2),'ro',p(:,1),p(:,2),'r-') % similar trick can be made to the other direction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function vals = potency_curve(v0,vn,l) % curve that decreases from v0 to vn with a rate that is % somewhere between linear and 1/t vals = v0 * (vn/v0).^([0:(l-1)]/(l-1)); function error = cca_error(P,Mdist,lambda) [noc odim] = size(P); noc_x_1 = ones(noc,1); odim_x_1 = ones(odim,1); error = 0; for i=1:noc, known = find(~isnan(Mdist(:,i))); if ~isempty(known), y = P(i,:); Dy = P(known,:) - y(noc_x_1(known),:); dy = sqrt((Dy.^2)*odim_x_1); fy = exp(-dy/lambda); error = error + sum(((Mdist(known,i) - dy).^2).*fy); end end error = error/2; function [] = dydxplot(P,Mdist) [noc odim] = size(P); noc_x_1 = ones(noc,1); odim_x_1 = ones(odim,1); Pdist = zeros(noc,noc); for i=1:noc, y = P(i,:); Dy = P - y(noc_x_1,:); Pdist(:,i) = sqrt((Dy.^2)*odim_x_1); end Pdist = tril(Pdist,-1); inds = find(Pdist > 0); n = length(inds); plot(Pdist(inds),Mdist(inds),'.'); xlabel('dy'), ylabel('dx') function p = project_point(P,x,dx) [noc odim] = size(P); noc_x_1 = ones(noc,1); odim_x_1 = ones(odim,1); % initial projection [dummy,i] = min(dx); y = P(i,:)+rand(1,odim)*norm(P(i,:))/20; % lambda lambda = norm(std(P)); % termination eps = 1e-3; i_max = noc*10; i=1; p(i,:) = y; ready = 0; while ~ready, % mutual distances Dy = P - y(noc_x_1,:); % differences in output space dy = sqrt((Dy.^2)*odim_x_1); % distances in output space f = exp(-dy/lambda); fprintf(2,'iteration %d, error %g \r',i,sum(((dx - dy).^2).*f)); % all the other vectors push the projected one fy = f .* (dx ./ dy - 1) / sum(f); % update step = - sum(fy(:,odim_x_1).*Dy); y = y + step; i=i+1; p(i,:) = y; ready = (norm(step)/norm(y) < eps | i > i_max); end fprintf(2,'\n');
github
martinarielhartmann/mirtooloct-master
sompak_sammon.m
.m
mirtooloct-master/somtoolbox/sompak_sammon.m
4,311
utf_8
e86c45a58b8ef54fa7ae35f5aa42efc7
function sMap=sompak_sammon(sMap,ft,cout,ct,rlen) %SOMPAK_SAMMON Call SOM_PAK Sammon's mapping program from Matlab. % % P = sompak_sammon(sMap,ft,cout,ct,rlen) % % ARGUMENTS ([]'s are optional and can be given as empty: [] or '') % sMap (struct) map struct % (string) filename % [ft] (string) 'pak' or 'box'. Argument must be defined, if % input file is used. % [cout] (string) output file name. If argument is not defined % (i.e argument is '[]') temporary file '__abcdef' is % used in operations and *it_is_removed* after % operations!!! % [ct] (string) 'pak' or 'box'. Argument must be defined, if % output file is used. % rlen (scalar) running length % % RETURNS: % P (matrix) the mapping coordinates % % Calls SOM_PAK Sammon's mapping program (sammon) from Matlab. Notice % that to use this function, the SOM_PAK programs must be in your % search path, or the variable 'SOM_PAKDIR' which is a string % containing the program path, must be defined in the workspace. % SOM_PAK programs can be found from: % http://www.cis.hut.fi/research/som_lvq_pak.shtml % % See also SOMPAK_INIT, SOMPAK_SAMMON, SOMPAK_SAMMON_GUI, % SOMPAK_GUI, SAMMON. % Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas % Copyright (c) by Juha Parhankangas % http://www.cis.hut.fi/projects/somtoolbox/ % Juha Parhankangas 050100 NO_FILE = 0; nargchk(5,5,nargin); if ~(isstruct(sMap) | isstr(sMap)) error('Argument ''sMap'' must be a struct or filename.'); end if isstr(sMap) if isempty(ft) | ~isstr(ft) | ~(strcmp(ft,'pak') | strcmp(ft,'box')) error('Argument ''ft'' must be string ''pak'' or ''box''.'); end if strcmp(ft,'pak') sMap=som_read_cod(sMap); else new_var=diff_varname; varnames=evalin('base','who'); loadname=eval(cat(2,'who(''-file'',''',sMap,''')')); if any(strcmp(loadname{1},evalin('base','who'))) assignin('base',new_var,evalin('base',loadname{1})); evalin('base',cat(2,'load(''',sMap,''');')); new_var2=diff_varname; assignin('base',new_var2,evalin('base',loadname{1})); assignin('base',loadname{1},evalin('base',new_var)); evalin('base',cat(2,'clear ',new_var)); sMap=evalin('base',new_var2); evalin('base',cat(2,'clear ',new_var2)); else evalin('base',cat(2,'load(''',sMap,''');')); sMap=evalin('base',loadname{1}); evalin('base',cat(2,'clear ',loadname{1})); end end end if ~isstr(cout) & isempty(cout) NO_FILE = 1; cout = '__abcdef'; elseif ~isstr(cout) | isempty(cout) error('Argument ''cout'' must be a string or ''[]''.'); end if ~NO_FILE & (isempty(ct) | ~(strcmp(ct,'pak') | strcmp(ct,'box'))) error('Argument ''ct'' must be string ''pak'' or ''box''.'); end som_write_cod(sMap,cout); if ~is_positive_integer(rlen) error('Argument ''rlen'' must be a positive integer.'); end if any(strcmp('SOM_PAKDIR',evalin('base','who'))) command=cat(2,evalin('base','SOM_PAKDIR'),'sammon '); else command='sammon '; end str = sprintf('%s -cin %s -cout %s -rlen %d',command,cout,cout,rlen); if isunix unix(str); else dos(str); end sMap=som_read_cod(cout); if ~NO_FILE if isunix unix(cat(2,'/bin/rm ',cout)); else dos(cat(2,'del ',cout)); end if strcmp(ct,'box'); sMap=sMap.codebook; eval(cat(2,'save ',cout,' sMap')); disp(cat(2,'Output is saved to the file ',sprintf('''%s.mat''.',cout))); else som_write_cod(sMap,cout); sMap=sMap.codebook; disp(cat(2,'Output is saved to the file ',cout,'.')); end else if isunix unix('/bin/rm __abcdef'); else dos('del __abcdef'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bool = is_positive_integer(x) bool = ~isempty(x) & isreal(x) & all(size(x) == 1) & x > 0; if ~isempty(bool) if bool & x~=round(x) bool = 0; end else bool = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = diff_varname(); array=evalin('base','who'); if isempty(array) str='a'; return; end for i=1:length(array) lens(i)=length(array{i}); end ind=max(lens); str(1:ind+1)='a'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
martinarielhartmann/mirtooloct-master
som_show_add.m
.m
mirtooloct-master/somtoolbox/som_show_add.m
48,954
utf_8
2f99faff178e5d12162026e4b926a00c
function h=som_show_add(mode,D,varargin) %SOM_SHOW_ADD Shows hits, labels and trajectories on SOM_SHOW visualization % % h = som_show_add(mode, D, ['argID',value,...]) % % som_show_add('label',sMap) % som_show_add('hit',som_hits(sMap,sD)) % som_show_add('traj',som_bmus(sMap,sD)) % som_show_add('comet',som_bmus(sMap,sD)) % som_show_add('comet',inds, 'markersize', [1 0.2]) % % Input and output arguments ([]'s are optional): % mode (string) operation mode 'label', 'hit', 'traj', 'comet' % D (varies) depending on operation mode % In 'label' mode gives the labels % (struct) map struct, the .labels field of which is used % (cell array of strings) size munits x number_of_labels % In 'hit' mode gives the hit histogram(s) % (matrix) size munits x k, if k>1, D gives hit histograms % for k different sets of data (e.g. k classes). % In 'traj' and 'comet' modes gives the trace of the trajectory % (vector) size N x 1, D(1) is the current and D(end) % is oldest item of the trajectory % [argID, (string) Additional arguments are given as argID, value % value] (varies) pairs. Depend on the operation mode (see below). % % h (vector) handles to the created objects % % Here are the valid argument IDs and corresponding values. Most of % them depend on the operation mode: % % all modes % 'SubPlot' (vector) which subplots are affected (default: current) % (string) 'all': all subplots are affected % mode = 'label' % 'TextSize' (scalar) text size in points % 'TextColor' (string) ColorSpec, 'xor' or 'none': label color % % mode = 'hit' % 'EdgeColor' (string) ColorSpec, 'none' % 'MarkerSize' (scalar) maximum marker size % if k == 1, % 'Marker' (string) 'lattice', Matlab's built-in markerstyles, 'none' % 'MarkerColor'(string) Colorspec, 'none': fill color for markers % 'Text' (string) 'on', 'off': whether to write the number of hits % 'TextColor' (string) ColorSpec, 'xor': text color if Text is 'on' % 'TextSize' (scalar) text font size in points if Text is 'on' % if k > 1, % 'SizeFactor' (string) 'common', 'separate': size scaling % 'Marker' (string) 'lattice', Matlab's built-in markerstyles, 'pie', 'none' % (cell array) size k x 1, marker style for each histogram % 'MarkerColor'(string) Colorspec, 'none': fill color for markers % (matrix) size k x 3, color for each histogram % % mode = 'traj' % 'TrajWidth' (scalar) basic trajectory line width in points % 'WidthFactor'(string) 'hit' or 'equal': effect of hits on line width % 'TrajColor' (string) ColorSpec, 'xor': color for trajectory line % 'Marker' (string) 'lattice', Matlab's built-in markerstyles, 'none' % 'MarkerSize' (scalar) basic marker size (in points) % 'SizeFactor' (string) 'equal', 'hit' (equal size/size depends on freq.) % 'MarkerColor'(string) Colorspec, 'none': color of markers % 'EdgeColor' (string) ColorSpec, 'none': edgecolor of markers % % mode = 'comet' % 'Marker' (string) 'lattice', Matlab's built-in markerstyles % 'MarkerColor'(string) ColorSpec, 'none': color for the markers % (matrix) size N x 3, RGB color for each step % 'EdgeColor' (string) ColorSpec, 'none': edgecolor for markers % 'MarkerSize' (vector) size 1 x 2, size of comet core and tail % % For more help, try 'type som_show_add' or check out online documentation. % See also SOM_SHOW. %%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_show_add % % PURPOSE % % Shows hits, labels and trajectories on SOM_SHOW visualization % % SYNTAX % % h = som_show_add(mode, D); % h = som_show_add(..., 'argID', value); % % DESCRIPTION % % The SOM_SHOW function makes the basic visualization of the SOM. % With SOM_SHOW_ADD one can set labels, hit histogarms or different % trajectories on this visualization. % % labels (mode = 'label') % % Labels are strings describing the units. They may be, e.g., a result % of SOM_AUTOLABEL function. Labels are centered on the unit so that % multiple labels are in a column. % % hit histograms (mode = 'hit') % % Hit histograms indicate how the best matching units of a data % set/some data sets are distribited on a SOM. The hit histogram can % be calculated using function SOM_HITS. % % trajectories (mode = 'traj' or mode = 'comet') % % Trajectories show the best matching units for a data set that is % time (or any ordered) series. It may be either a line connecting the % consecutive best matching units ('traj' mode) or a "comet" % trajectory where the current (first sample in D) best matching unit % has biggest marker and the oldest (last sample) has smallest % marker ('comet' mode). % % NOTE: that the SOM_SHOW_ADD function can only be applied to % figures that have been drawn by SOM_SHOW. % % KNOWN BUGS % % for 'hit' mode, if the given hit matrix is all zeros, a series of % error messages is generated % % REQUIRED INPUT ARGUMENTS % % mode (string) Visuzalization mode % 'label' map labeling % 'hit' hit histograms % 'traj' line style trajectory % 'comet' comet style trajectory % % D (vector, map struct, cell array of strings) Data % % The valid value of D depends on the visualization mode: % % Mode Valid D % 'label' map struct or Mxl cell array of strings, where % M is number of map units and l maximum numer of % labels in unit. % % 'hit' Mx1 vector or MxK matrix, where M is number of map % units and K is number of hit histograms (of K % different classes of data) to be shown % % 'comet' Lx1 vector of best matchig unit indices that have to % 'traj' be in range of the map that is in the figure. L is % the length of trajectory % % OPTIONAL INPUT ARGUMENTS % % Optional arguments must be given as 'argument identifier', value % -pairs. This section is divided in four parts because each mode % functions in a different way, though they may have same identifier % names. % % If user specifies an identifier that is not operational in the % specified mode, the functions gives a warning message. If the % identifier does not exist in any mode the execution is terminated % and an error message is returned. % % GENERAL OPTIONAL INPUT ARGUMENTS (in all modes) % % 'SubPlot' Target subplots in the figure % (vector) Subplots' ordinal numbers in a vector. By default % the target is the current subplot (see GCA). % (string) String 'all' means all subplots. % % 'Marker' Data marker (not in use in 'label' mode) % (string) 'none': sets the markers off % 'lattice': sets the marker shape according to the % lattice of the underlying map, i.e. it gives % rectangles if underlying map lattice is 'rect' and % hexagons for 'hexa', respectively % any of the Matlab's built-in marker styles: 'o', 's', % 'd', 'v', '^', '<' ,'> ', 'p', 'h', 'x', '.', '*', '+' % % NOTE that '.','x','+' or '*' are not recommended since % they have only edgecolor and many visualizations are % based on _face_ color. % % NOTE there is an important difference between built-in % markers. If figure size is changed the 'lattice' % markers are rescaled but the built-in markers stay at % fixed size, and consequently, the size unit for % 'lattice' markers is normalized but for built-in % markers the size is given in points. For 'lattice' % markers size 1 means the size of the map unit. % % NOTE that in 'hit' mode there are some additional features. % % 'EdgeColor' Sets edgecolor for the markers (not in use in 'label' mode) % (string) ColorSpec, e.g. 'r', gives each edge the specified color % 'none': sets markers edges invisible % Default is 'none' - except if MarkerColor is set to 'none' the % defaults is 'black'. % % OPTIONAL INPUT ARGUMENTS mode 'label' % % Labels are centered on the unit so that multiple labels are in % a single column. % % 'SubPlot' see General Optional Input Arguments % % 'TextSize' Text size for labels % (scalar) Text size in points. Default is 10. % % 'TextColor' Text color % (string) ColorSpec specifies the text color for all labels % 'xor': gives Matlab's "xor" text color mode where the % label color depends on background color % 'none': sets labels invisble (but creates the objects) % % OPTIONAL INPUT ARGUMENTS mode 'hit' % % The function in mode 'hit' depends on the input argument size. If % only one hit histogram is drawn (K==1), it is possible to show the % hits using numbers. This is not possible for multiple hit % histograms (K>1). % % 'SubPlot' see General Optional Input Arguments % % 'Marker' Marker style(s) % (string) As in General Optional Input Arguments. In addition % 'pie': sets pie charts for markers. The size of the % pie in each unit describes the number of total hits in the % unit and the share of each sector is the relative amount of % hits in each class (requires multiple histograms). Color for % each class is set by MarkerColor. Default coloring % is hsv(K), where K is the number of hit histograms (classes). % (cell array) size K x 1, of built-in marker style characters. K is % number of histograms (classes), i.e., same as size(D,2) % where D is the second input argument. Cell value is % valid only if multiple histograms are specified (K>1). % % NOTE if multiple histograms (classes) are specified % and Marker is one of the built-in marker styles or % 'lattice', the markers are drawn in size order from % largest to smallest. This insures that all markers are % visible (or at least their edges are). But if two % markers for different classes in the same node were of % same size, the other would be totally hidden. In order % to prevent this, the markers for different classes are % shifted different amounts from the exact centre of the % unit. (Evidently, if Marker is 'pie' this problem does % not exist.) % % Default marker is 'lattice' for one histogram and % 'pie' for multiple histograms. % % 'MarkerColor' Marker color(s) % (string) ColorSpec gives all markers the same color % 'none': leaves the markes transparent (only edges are visible) % (matrix) size K x 3, RGB triples for each histogram class % giving each hit histogram an own color % % NOTE that markers '*','+','x', or '.' cannot use % MarkerColor since these objects have no face (fill) % color. For them only EdgeColor matters. % % 'MarkerSize' Maximum size for marker % (scalar) set the _maximum_ marker size that corresponds to % maximum hit count. If Marker is 'pie' or 'lattice' the % MarkerSize is in normalized scale: 1 correspons to unit size. % If Marker is one of the built-in styles, MarkerSize is given % in points. % % Marker Default MarkerSize % 'lattice' 1 (normalized units) % 'pie' 1 (normalized units) % 'o','s', etc. 6 (points) % % 'SizeFactor' Defines the scaling of the marker sizes in multiple % histogram case (when Marker is one of the built-in marker % styles or 'lattice'). % (string) 'separate' (the default) means that marker size shows % the share of the data which hits the unit compared to % amount of data in that class. That is, the size of % markers show the relative distribution of data on the map % in each class separately. The maximum size is SizeFactor. % 'common' means that marker size shows the distribution of % the data in the different classes compared to % _the total amount of data_. % % 'EdgeColor' Sets edgecolor for the markers, see General % Optional Input Arguments. Default is 'none' - % except if MarkerColor is 'none' or Marker is % 'x','*,'x', or '.'. In these cases default EdgeColor is 'black'. % % 'Text' Write/don't write the number of hits on the % units. This option is not in use for multiple histograms. % (string) 'on' or 'off' (the default) % % 'TextColor' Text color % (string) ColorSpec gives each letter the same color % 'xor' gives a "xor" coloring for the text % % 'TextSize' Text size (in points) % (scalar) text size in points, default is 10 % % OPTIONAL INPUT ARGUMENTS mode 'traj' % % Input D is a Nx1 vector of N BMU indices that describe the trace of the % comet. First element D(1) is "newest" and D(end) "oldest". Note % that at least two indeces are expected: size of D must be at % least 2x1. % % 'SubPlot' see General Optional Input Arguments % % 'TrajColor' Color for trajectory line % (string) ColorSpec gives each marker the same color, 'w' by default % 'none' sets the marker fill invisible: only edges are shown % % 'TrajWidth' Maximum width of trajectory line % (scalar) width in points. Default is 3. % % 'WidthFactor' Shows how often edge between two units has been traversed. % (string) 'hit': the size of the marker shows how frequent the % trajectory visits the unit (TrajWidth sets the % maximum size). This is the default. % 'equal': all lines have the same width (=TrajWidth) % % 'Marker' Marker style, see General Optional Input % Arguments. Default is 'o'. % % NOTE Marker style 'lattice' is not valid in mode 'traj'. % NOTE Markers can be turned off by setting MarkerSize to zero. % % 'MarkerSize' Maximum size of markers % (scalar) Default is 12 (points). % % 'SizeFactor' Sets the frequency based marker size or constant marker size. % (string) 'hit': the size of the marker shows how frequent the % trajectory visits the unit (MarkerSize sets the % maximum size). This is the default. % 'equal': all markers have th esame size (=MarkerSize) % % 'MarkerColor' The fill color(s) for hit markers % (string) ColorSpec gives each marker the same color, default is 'w' % 'none' sets the marker fill invisible: only edges are shown % % NOTE markers '*','+','x', or '.' can't use MarkerColor since % these objects have no face (fill) color: only EdgeColor % matters for these markers. % % 'EdgeColor' see General Optional Input Arguments. Default is % 'none' - except if MarkerColor is 'none' or Marker % is 'x','*','x', or '.'. In these cases default % EdgeColor is 'white'. % % OPTIONAL INPUT ARGUMENTS mode 'comet' % % Input D is a Nx1 vector of N BMU indices that describe the trace of % the comet. First element D(1) is "newest" and D(end) "oldest". Note % that at least two indeces are expected: size of D must be at least % 2x1. % % 'SubPlot' see General Optional Input Arguments % % 'Marker' Marker style, see General Optional Input % Arguments. Default is 'lattice'. % % 'MarkerColor' The fill color(s) for comet markers % (string) ColorSpec gives each marker the same color, default is 'w' % 'none' sets the marker fill invisible: only edges are shown % (matrix) size N x 3, consisting of RGB triples as rows % sets different color for each marker. This may be % used to code the time series using color/grayscale. % % NOTE Markers '*','+','x', or '.' can't use MarkerColor % since these objects have no face (fill) color: only % EdgeColor matters for these markers. % % 'EdgeColor' see General Optional Input Arguments. Default is % 'none' - except if MarkerColor is 'none' or Marker % is 'x','*,'x', or '.'. In these cases default % EdgeColor is 'white'. % % 'MarkerSize' The size of "comet core" and tail % (vector) size 1 x 2: first element sets the size for the marker % representing D(1) and the second set size for D(end) % the size (area) of the markes between these changes linearly. % Note that size units for 'lattice' marker style are % normalized so that 1 means map unit size but for built-in % marker styles the size is given points. % % Marker default value % 'lattice' [0.8 0.1] % 'o','v', etc. [20 4] % % OUTPUT ARGUMENTS % % h (vector) handles to all objects created by the function % % OBJECT TAGS % % Field Tag in every object is set to % % 'Lab' for objects created in mode 'label' % 'Hit' -"- 'hit' % 'Traj' -"- 'traj' % 'Comet' -"- 'comet' % % EXAMPLES % % Not yet ready % % SEE ALSO % % som_show Basic map visualization % som_show_clear Clear hit marks, labels or trajectories from current figure. % Copyright (c) 1999-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta Johan 131199 %% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% error(nargchk(2,Inf,nargin)) % check no. of input args % Get data from the SOM_SHOW figure, exit if error [handles,msg,lattice,msize,dim]=vis_som_show_data('all',gcf); error(msg); munits=prod(msize); % Initialize some variables: these must exist later; % the default values are set by subfunctions Property=init_properties; Property.handles=handles; %%% Check mode and that D is of right type & size for that mode % mode has to be string if ~vis_valuetype(mode,{'string'}), error('String value expected for first input argument (mode).'); else mode=lower(mode); % case insensitive mode_=mode; % 'mode' is internal variable; % for program constructs 'mode_' is shown to % user in some error messags end switch mode % check mode case 'hit' %%% Hit histogram visualization: vector [msize k] if ~vis_valuetype(D,{'nxm'}), error('Hit visualization: a matrix expected for data input.'); elseif size(D,1) ~= prod(msize) error('Hit visualization: data and map size do not match.'); end % Multiple hit histograms if size(D,2)>1 mode='mhit'; % Hit count musn't be negative if any(D(:)<0), error('Hit visualization: negative hit count in data not allowed!'); end end case {'traj','comet'} %%% Trajectory like visualizations if ~vis_valuetype(D,{'nx1'}), error('Trajectory/Comet: a Nx1 vector expected for data input.'); elseif any(D>prod(msize))| any(D<1), error('Trajectory/Comet: BMU indices out of range in data input.'); elseif any(fix(D)~=D), warning('Trajectory/Comet: BMU indices not integer. Rounding...'); elseif size(D,1)<2 error('At least two BMU indexes expected.'); end case 'label' %%% Label visualizations if isstruct(D), % check if D is a map [tmp,ok,tmp]=som_set(D); if all(ok) & strcmp(D.type,'som_map') ; else error('Map struct is invalid!'); end % Size check if length(msize) ~= length(D.topol.msize) | ... munits ~= prod(D.topol.msize), error(['The size of the input map and the map in the figure' ... ' do not match.']); end D=D.labels; % Cell input elseif vis_valuetype(D,{'2Dcellarray_of_char'}) ; % Char input elseif vis_valuetype(D,{'char_array'}), D=cellstr(D); else error(['Labels has to be in a map struct or in a cell array' ... ' of strings']); end if size(D,1) ~= munits error(['The number of labels does not match the size of the map' ... ' in the figure.']); end otherwise error('Invalid visualization mode.'); end if rem(length(varargin),2) error('Mismatch in identifier-value pairs or wrong input argument order.'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read in optional arguments for i=1:2:length(varargin), %% Check that all argument types are strings if ~ischar(varargin{i}) error('Invalid identifier name or input argument order.'); end %% Lower/uppercase in identifier types doesn't matter: identifier=lower(varargin{i}); % identifier (lowercase) value=varargin{i+1}; % Check property identifiers and values and store the values. % Struct used_in is set to initiate warning messages: % if a don't care propersty is set, the user is warned. switch identifier case 'marker' %%% Marker for hits or trajectories switch mode case 'mhit' if vis_valuetype(value,{'markerstyle'}) | ... (vis_valuetype(value,{'string'}) & ... any(strcmp(value,{'lattice','pie'}))), ; % ok elseif vis_valuetype(value,{'cellcolumn_of_char'}), if size(value,1) ~= size(D,2) error([' If a cell of Markers is specified its size must be' ... ' number_of_hit_histograms x 1.']); else for i=1:size(D,2), if ~vis_valuetype(value{i},{'markerstyle'}) error('Cell input for ''Marker'' contains invalid styles.') end end end else error([' Invalid ''Marker'' in case of multiple hit histograms.' ... char(10) ' See detailed documentation.']) end case {'comet','hit'} if vis_valuetype(value,{'markerstyle'}) | isempty(value), % ok; elseif ischar(value) & strcmp(value,'lattice'), % ok; else error(['Marker must be Matlab''s marker style, or string' ... ' ''lattice''.']); end case 'traj' if ~vis_valuetype(value,{'markerstyle'}) & ~isempty(value), error('In mode ''traj'' Marker must be one of Matlab''s built-in marker styles'); end end used_in.comet=1; % Set relevance flags used_in.traj=1; used_in.label=0; used_in.hit=1; used_in.mhit=1; case 'markersize' %%% Marker for hits or trajectories switch mode case 'comet' if ~vis_valuetype(value,{'1x2'}) & ~isempty(value), error('In mode ''comet'' MarkerSize'' must be a 1x2 vector.'); end case {'hit','traj'} if ~vis_valuetype(value,{'1x1'}) & ~isempty(value), error(['In mode ''' mode_ ... ''' ''MarkerSize'' must be a scalar.']); end end used_in.comet=1; % Set relevance flags used_in.traj=1; used_in.label=0; used_in.hit=1; used_in.mhit=1; case 'sizefactor' %%% Hit dependent size factor switch mode case 'traj' if ~vis_valuetype(value,{'string'}) | ... ~any(strcmp(value,{'hit', 'equal'})), error(['In mode ''traj'' ''SizeFactor'' must be ' ... 'string ''equal'' or ''hit''.']); end case 'mhit' if ~vis_valuetype(value,{'string'}) | ... ~any(strcmp(value,{'common', 'separate'})), error(['In mode ''hit'' ''SizeFactor'' must be ' ... 'string ''common'' or ''separate''.']); end end used_in.comet=0; % Set relevance flags used_in.traj=1; used_in.label=0; used_in.hit=0; used_in.mhit=1; case 'markercolor' %%% Markercolor switch mode case 'comet' if ~vis_valuetype(value,{'colorstyle','1x3rgb'}) & ... ~vis_valuetype(value,{'nx3rgb',[size(D,1) 3]},'all') & ... ~isempty(value), error(['MarkerColor in mode ''comet'' must be a ColorSpec,' ... ' string ''none'' or Mx3 matrix of RGB triples.']); end case 'mhit' if ~vis_valuetype(value,{[size(D,2) 3],'nx3rgb'},'all') & ... ~vis_valuetype(value,{'colorstyle','1x3rgb'}), error([' If multiple hit histograms in mode ''hit'' are' ... char(10) ... ' given MarkerColor must be ColorSpec or a Kx3 matrix' ... char(10)... ' of RGB triples where K is the number of histograms.']); end case 'hit' if ~vis_valuetype(value,{'colorstyle','1x3rgb'}) & ... ~isempty(value), error(['MarkerColor in mode ''hit'' ' ... 'must be a ColorSpec or string ''none''.']); end case 'traj' if ~vis_valuetype(value,{'colorstyle','1x3rgb'}) & ... ~isempty(value), error(['MarkerColor in mode ''traj'' ' ... 'must be a ColorSpec or string ''none''.']); end end used_in.comet=1; % Set relevance flags used_in.traj=1; used_in.label=0; used_in.hit=1; used_in.mhit=1; case 'edgecolor' %%% Color for marker edges if ~vis_valuetype(value,{'colorstyle','1x3rgb'}) & ~isempty(value), error('''EdgeColor'' must be a ColorSpec or string ''none''.') end used_in.comet=1; % Set relevance flags used_in.traj=1; used_in.label=0; used_in.hit=1; used_in.mhit=1; case 'text' %%% Labeling for trajectories/hits switch mode case 'hit' %%% Hit count using numbers? if isempty(value), value='off'; elseif vis_valuetype(value,{'string'}) & ... ~any(strcmp(value,{'on','off'})), error('Value for Text in mode ''hit'' should be ''on'' or ''off''.'); else ; % ok end %case 'traj','comet' % if ~vis_valuetype(value,{'char_array','cellcolumn_of_char'}) & ... % ~isempty(value) % error('Value for Text is of wrong type or size.') % elseif ischar(value) % value=strcell(value) % ok, convert to cell % end % if size(traj_label,1)~=size(D,1) % error(['The number of labels in Text and the length of the' ... % ' trajectory do not match.']); % end case 'label' ; % not used end used_in.comet=0; % Set relevance flags used_in.traj=0; used_in.label=0; used_in.hit=1; used_in.mhit=0; case 'textsize' %%% Text size for labels if ~vis_valuetype(value,{'1x1'}) & ~isempty(value), error('TextSize must be scalar.'); end used_in.comet=0; % Set relevance flags used_in.traj=0; used_in.label=1; used_in.hit=1; used_in.mhit=0; case 'textcolor' %%% Color for labels if ~vis_valuetype(value,{'colorstyle','1x3rgb','xor'}) & ~isempty(value), error('''TextColor'' must be ColorSpec, ''xor'' or ''none''.') end used_in.comet=0; % Set relevance flags used_in.traj=0; used_in.label=1; used_in.hit=1; used_in.mhit=0; case 'trajwidth' %%% Basic line width for a line trajectory if ~vis_valuetype(value,{'1x1'}) & ~isempty(value), error('TrajWidth must be a scalar.'); end used_in.comet=0; % Set relevance flags used_in.traj=1; used_in.label=0; used_in.hit=0; used_in.mhit=0; case 'widthfactor' %%% Hit factor for a line trajectory if ~vis_valuetype(value,{'string'}) | ... ~any(strcmp(value,{'hit', 'equal'})), error(['In mode ''traj'' ''WidthFactor'' must be ' ... 'string ''equal'' or ''hit''.']); end used_in.comet=0; % Set relevance flags used_in.traj=1; used_in.label=0; used_in.hit=0; used_in.mhit=0; case 'trajcolor' %%% Color for trajectory line if ~vis_valuetype(value,{'colorstyle','1x3rgb','xor'}) & ~isempty(value), error('''TrajColor'' must be a ColorSpec or string ''xor''.') end used_in.comet=0; % Set relevance flags used_in.traj=1; used_in.label=0; used_in.hit=0; used_in.mhit=0; case 'uselabel' %%% Which labels to show error('Not yet implemented.'); case 'shift' if ~vis_valuetype(value,{'1x1'}) | ((value < 0) | (value > 1)), error('''Shift'' must be a scalar in range [0,1].') end used_in.comet=0; % Set relevance flags used_in.traj=0; used_in.label=0; used_in.hit=0; used_in.mhit=1; case 'subplot' %%% The subplots which are affected if vis_valuetype(value,{'1xn','nx1','string'}), if ischar(value), if ~strcmp(value,'all'), error('Only valid string value for subplot indices is ''all''.'); else value=1:length(handles); end elseif any(value<1) | any(value>length(handles)), error('Subplot indices must be in range 1...number_of_subplots!'); end elseif ~isempty(value) error('Invalid subplot indices!'); end used_in.comet=1; % Set relevance flags used_in.traj=1; used_in.label=1; used_in.hit=1; used_in.mhit=1; otherwise error([ 'Unknown identifier ''' identifier '''.']); end % Warn user if the property that was set has no effect in the % selected visuzlization mode if ~getfield(used_in, mode), warning(['Property ''' identifier ''' has no effect in mode ''' ... mode_ '''.']); else Property=setfield(Property,identifier,value); end end % set default subplot if isempty(Property.subplot) % search the subplot number for current axis value=find(gca==handles); if isempty(value) | value>length(handles) error('SubPlot default value setting: current axis is not in the figure!'); else Property.subplot=value; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%% Main switch: select the right subfunction %%%%%%%%%%%%%%%%%%% switch mode case 'hit' h_=hit(D, lattice, msize, Property); case 'mhit' h_=mhit(D, lattice, msize, Property); case 'label' h_=label(D, lattice, msize, Property); case 'traj' h_=traj(D, lattice, msize, Property); case 'comet' %error('Not yet implemented.'); h_=comet(D, lattice, msize, Property); otherwise error('Whoops! Internal error: unknown mode!'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Build output if necessary %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargout>0 h=h_; end %%%% SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h_=hit(Hits, lattice, msize, Property); % number of map units munits=prod(msize); % subplots p=Property.subplot; handles=Property.handles; % Set default marker if isempty(Property.marker), if strcmp(Property.text,'on') Property.marker='none'; else Property.marker='lattice'; end end % Set default markersize if isempty(Property.markersize) if strcmp(Property.marker,'none'), warning('MarkerSize is not meaningful since Marker is set to ''none''.'); elseif strcmp(Property.marker,'lattice'), Property.markersize=1; % normalized size else Property.markersize=12; % points end end % Set default colors if ~isempty(Property.markercolor), if strcmp(Property.marker,'none') warning('MarkerColor is not used since Marker is set to ''none''.'); Property.markercolor=[]; % not used else ; % ok end elseif any(strcmp(Property.marker,{'+','*','.','x'})), % these don't use fill color: 'none' will cause default % edgecolor to be 'k'. Property.markercolor='none'; else Property.markercolor='k'; end if ~isempty(Property.edgecolor), if strcmp(Property.marker,'none') warning(['EdgeColor is not used since Marker is set to' ... ' ''none''.']); else ; %ok end elseif ~strcmp(Property.markercolor,'none'), Property.edgecolor='none'; else Property.edgecolor='k'; end % Set default text if isempty(Property.text), Property.text='off'; end % Set default textsize if isempty(Property.textsize) Property.textsize=10; elseif strcmp(Property.text,'off') warning('TextSize not used as hits are not set to be shown as numbers.'); end % Set default textcolor if isempty(Property.textcolor) Property.textcolor='w'; elseif strcmp(Property.text,'off') warning('TextColor not used as hits are not set to be shown as numbers.'); end %% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% h_=[]; % this variable is for collecting the object handles % Select the drawing mode if ~strcmp(Property.marker,'none') %%%%% Draw spots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % unit coordinates coord=som_vis_coords(lattice,msize); % Calculate the size of the spots mx=max(Hits); if mx==0, % nothing to draw! h_=[]; return else Size=sqrt(Hits./mx); end % coordinates for non-zero hits (only those are drawn) coord=coord(Size~=0,:); Size=Size(Size~=0); N=size(Size,1); % som_cplane can't draw one unit with arbitrary % coordinates as it its mixed with msize: if size(coord,1)==1 & strcmp(Property.marker,'lattice'), Size=[Size;Size]; coord=[coord;coord]; end for i=1:length(p), % Set axes axes(handles(p(i))); % Get hold state and caxis memhold=ishold; cax=caxis; hold on; switch Property.marker case 'lattice' h_(i,1)=som_cplane(lattice, coord, Property.markercolor, ... Property.markersize*Size); otherwise [S,m]=som_grid(lattice, [N 1],... 'Coord',coord, ... 'Line','none',... 'Marker',Property.marker,... 'MarkerColor',Property.markercolor,... 'MarkerSize', Size*Property.markersize); h_=[h_;m(:)]; end % Restore hold state if ~memhold hold off; end end % Set edgecolor if strcmp(Property.marker,'lattice') set(h_,'edgecolor',Property.edgecolor); else set(h_,'markeredgecolor',Property.edgecolor); end end if strcmp(Property.text,'on'), %%%%% Draw numbers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Do numbers Hits=reshape(Hits,[munits 1]); labels=cell([munits 1]); for i=1:length(Hits) if Hits(i) % zero hit won't be shown labels(i)={num2str(Hits(i))}; end end for i=1:length(p), axes(handles(p(i))); % Set axes memhold=ishold; % Get hold state hold on; [S,m,l,t]=som_grid(lattice, msize, ... 'Line','none',... 'Marker','none', ... 'Label',labels, ... 'LabelColor', Property.textcolor, ... 'LabelSize', Property.textsize); % Get handles h_=[h_;t(:)]; % Restore hold state and caxis if ~memhold hold off; end caxis(cax); end % Remove zero object handles (missing objects) h_=setdiff(h_,0); end %% Set object tags (for som_show_clear) %%%%%%%%%%%%%%%%%%%%%%%%%%%%% set(h_,'Tag','Hit') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h_=mhit(Hits, lattice, msize, Property); % number of map units munits=prod(msize); % subplots p=Property.subplot; handles=Property.handles; % Set default marker if isempty(Property.marker), Property.marker=lattice; end % variable 'mode' indicates which kind of markers are used: if iscell(Property.marker), mode='marker'; elseif vis_valuetype(Property.marker,{'markerstyle'}), mode='marker'; elseif strcmp(Property.marker,'pie'), mode='pie'; else mode='lattice'; end % Set default size scaling if isempty(Property.sizefactor) Property.sizefactor='separate'; end % Set default markersize if isempty(Property.markersize) if any(strcmp(mode,{'lattice','pie'})), Property.markersize=1; % normalized else Property.markersize=12; % points end end % Set default colors if isempty(Property.markercolor), Property.markercolor=hsv(size(Hits,2)); end if isempty(Property.edgecolor), if vis_valuetype(Property.markercolor,{'none'}), Property.edgecolor='k'; else Property.edgecolor='none'; end end % Set default shift if isempty(Property.shift) Property.shift=0; end %% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% h_=[]; % this variable is for collecting the object handles switch mode case {'marker','lattice'} % Number of hits histograms n_Hits=size(Hits,2); % Calculate the size of the spots if strcmp(Property.sizefactor,'common') mx=max(max(Hits)); if mx==0 % nothing to draw! h_=[]; return end spotSize=sqrt(Hits./mx); else mx=repmat(max(Hits),munits,1); mx(mx==0)=1; % Prevent division by zero spotSize=sqrt(Hits./mx); end %%% Make spotSize %reshape Size to a vector [spotSizeforHist(:,1); spotSizeforHist(:,2);...] spotSize=spotSize(:); % indices for non-zero hits (only those are drawn) notZero=find(spotSize ~= 0); % Drop zeros away from spotSize spotSize=spotSize(notZero); % Order spots so that bigger will be drawn first, so that they % won't hide smaller ones [dummy, sizeOrder]=sort(spotSize); sizeOrder=sizeOrder(end:-1:1); spotSize=spotSize(sizeOrder); %%% Make unit coordinates coord=som_vis_coords(lattice,msize); move=repmat(linspace(-.1,.1,n_Hits),size(coord,1),1)*Property.shift; move=repmat(move(:),1,2); % do n_Hits copies of unit coordinates so that they match spotSize coord=repmat(coord,n_Hits,1)+move; % Drop zeros away from coords and order coord=coord(notZero,:); coord=coord(sizeOrder,:); %%% Make unit colors if vis_valuetype(Property.markercolor,{'nx3'}), % If multiple colors Copy unit colors so that they match spotSize color=Property.markercolor(reshape(repmat([1:n_Hits]',1,munits)',... munits*n_Hits,1),:); % drop zeros away & order color=color(notZero,:); color=color(sizeOrder,:); else % only on color color=Property.markercolor; end %%% Make unit markers if iscell(Property.marker), %marker shows class: marker=char(Property.marker); marker=marker(reshape(repmat([1:n_Hits]',1,munits)',... munits*n_Hits,1),:); % Drop zeros, order & make to cell array (for som_grid) marker=marker(notZero,:); marker=cellstr(marker(sizeOrder,:)); else marker=Property.marker; end % som_cplane can't draw one unit with arbitrary % coordinates as it its mixed with msize: if size(coord,1)==1 & strcmp(mode,'lattice'), spotSize = [spotSize; spotSize]; coord = [coord; coord]; end N=length(notZero); % for som_grid visuzalization routine case 'pie' % marker 'pie' requires size parameter totHits if strcmp(mode,'pie') coord=som_vis_coords(lattice, msize); notZero=sum(Hits,2)>0; Hits=Hits(notZero,:); coord=coord(notZero,:); N=size(notZero,1); totHits=sqrt(sum(Hits,2)./max(sum(Hits,2))); end % som_pieplane can't draw one unit with arbitrary % coordinates as it its mixed with msize: if size(coord,1)==1, Hits= [Hits; Hits]; coord = [coord; coord]; end otherwise error('Whoops: internal error. Bad mode in subfunction mhit'); end for i=1:length(p), %%% Main loop begins % Set axis axes(handles(p(i))); % Get hold state and caxis memhold=ishold; cax=caxis; hold on; switch mode case 'lattice' h_(i,1)=som_cplane(lattice, coord, color, spotSize*Property.markersize); case 'marker' [S,m]=som_grid(lattice, [N 1],... 'Coord',coord, ... 'Line','none',... 'Marker',marker,... 'MarkerColor',color,... 'MarkerSize', spotSize*Property.markersize); h_=[h_;m(:)]; case 'pie' h_(i)=som_pieplane(lattice, coord, ... Hits, Property.markercolor, ... totHits*Property.markersize); end % Restore hold state and caxis if ~memhold hold off; end caxis(cax); end % Set edgecolor if any(strcmp(mode,{'lattice','pie'})), set(h_,'edgecolor',Property.edgecolor); else set(h_,'markeredgecolor',Property.edgecolor); end %% Set object tags (for som_show_clear) %%%%%%%%%%%%%%%%%%%%%%%%%%%%% set(h_,'Tag','Hit') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h_=label(Labels, lattice, msize, Property) % number of map units munits=prod(msize); % subplots and handles p=Property.subplot; handles= Property.handles; % Set default text size if isempty(Property.textsize) % default point size Property.textsize=10; end % Check color/set default if isempty(Property.textcolor), Property.textcolor='k'; end % handles will be collected in h_ for output h_=[]; %%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for i=1:length(p); % set axes axes(handles(p(i))); % store hold state and caxis (for some reason matlab may % change caxis(!?) memhold=ishold; hold on; cax=caxis; % Write labels [S,m,l,t]=som_grid(lattice, msize, ... 'Line','none', ... 'Marker', 'none', ... 'Label', Labels, ... 'LabelColor', Property.textcolor, ... 'LabelSize', Property.textsize); % Get handles h_=[h_;m(:);l(:);t(:)]; % reset hold state and caxis if ~memhold hold off; end caxis(cax); end %%% Set object tags %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% set(h_,'Tag','Lab'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h_=traj(bmu, lattice, msize, Property) % number of map units munits=prod(msize); % subplots and handles p=Property.subplot; handles=Property.handles; % Set default text color %if isempty(Property.textcolor), % Property.textcolor='k'; %end % Set default text size %if isempty(Property.textsize) % Property.textsize=10; %end % Set default marker if isempty(Property.marker) Property.marker='o'; end % Set default markersize if isempty(Property.markersize) Property.markersize=10; end % Set default markercolor if isempty(Property.markercolor) Property.markercolor='w'; end % Set default sizefactor if isempty(Property.sizefactor) %Property.sizefactor=0; Property.sizefactor='hit'; end % Set default trajwidth if isempty(Property.trajwidth) Property.trajwidth=3; end % Set default widthfactor if isempty(Property.widthfactor) Property.widthfactor='hit'; end % Set default trajcolor if isempty(Property.trajcolor) Property.trajcolor='w'; end % if no labels, do a empty cell array for syntax reasons %if isempty(Property.text), % Property.text=cell(munits,1); %end h_=[]; % handles will be collected in h_ for output l=length(bmu); % length of trajectory C=sparse(munits, munits); % init a connection matrix %%%%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Calculate the connection matrix that describes the trajectory for i=1:l-1, % The following if structure removes the possible redundancy due % to travels in both directions between two nodes of trajectory % (i.e. reflexivity) I=bmu(i+1);J=bmu(i); %if bmu(i)>bmu(i+1) %else % I=bmu(i);J=bmu(i+1); %end C(I,J)=C(I,J)+1; end % transitive connections are equal C=C+C'; % drop reflexive conncetions away C=spdiags(zeros(munits,1),0,C); % Do labels of trajectory nodes %traj_lab=cell(munits,1); hits=zeros(munits,1); for i=1:l, % traj_lab{bmu(i)}=strvcat(traj_lab{bmu(i)},Property.text{i}); hits(bmu(i))=(hits(bmu(i))+1); end % Calculate unit coordinates unit_coord=som_vis_coords(lattice, msize); % Calculate line width if strcmp(Property.widthfactor,'equal') TrajWidth=(C>0)*Property.trajwidth; else TrajWidth=Property.trajwidth.*sqrt(C./max(max(C))); end % Calculate marker sizes if strcmp(Property.sizefactor,'hit') MarkerSize=Property.markersize*sqrt(hits/max(hits)); else MarkerSize=Property.markersize*(hits>0); end for i=1:length(p), axes(handles(p(i))); % Get hold state and caxis memhold=ishold; cax=caxis; hold on; %'Label', traj_lab, ... %'LabelColor', Property.textcolor, ... %'LabelSize', Property.textsize, ... % Draw [S,m,l,t,s]=som_grid(C,msize,'coord',unit_coord,... 'Line','-', ... 'LineColor', Property.trajcolor, ... 'LineWidth', TrajWidth, ... 'Marker', Property.marker, ... 'MarkerColor', Property.markercolor, ... 'MarkerSize', MarkerSize); % Restore hold state and caxis if ~memhold hold off; end caxis(cax); % Get handles h_=[h_;m(:);l(:);t(:);s(:)]; end %% Set object tags %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% set(h_,'Tag','Traj'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h_=comet(bmu, lattice, msize, Property) % number of map units munits=prod(msize); % subplots and handles p=Property.subplot; handles=Property.handles; % Set default text color %if isempty(Property.textcolor), % Property.textcolor='k'; %end %% Set default text size %if isempty(Property.textsize) % Property.textsize=10; %end % Set default marker if isempty(Property.marker) Property.marker='o'; end % Set default markersize if isempty(Property.markersize), if strcmp(Property.marker,'lattice'), Property.markersize=linspace(0.8,0.1,length(bmu))'; else Property.markersize=sqrt(linspace(400,16,length(bmu)))'; end else if strcmp(Property.marker,'lattice'), Property.markersize=linspace(Property.markersize(1),... Property.markersize(2), ... length(bmu))'; else Property.markersize=sqrt(linspace(Property.markersize(1).^2,... Property.markersize(2).^2, ... length(bmu)))'; end end % Set default markercolor if isempty(Property.markercolor) Property.markercolor='w'; end % Set default edgecolor if isempty(Property.edgecolor), if vis_valuetype(Property.markercolor,{'nx3rgb'}), Property.edgecolor='none'; else Property.edgecolor=Property.markercolor; end end h_=[];l_=[]; % handles will be collected in h_ for output N_bmus=length(bmu); % length of trajectory % if no labels, do a empty cell array for syntax reasons %if isempty(Property.text), % Property.text=cell(N_bmus,1); %end %%%%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Calculate unit coordinates for trajectory points unit_coord=som_vis_coords(lattice, msize); coord=unit_coord(bmu,:); % Make labels for the _unique_ units that the comet hits unique_bmu=unique(bmu); % count units %N_labels=length(unique_bmu); %traj_lab=cell(N_labels,1); % cell for labels %label_coord=unit_coord(unique_bmu,:); % label coordinates % Make labels %for i=1:N_bmus, % index=find(unique_bmu==bmu(i)); % traj_lab{index}=strvcat(traj_lab{index},Property.text{i}); %end %Main loop for drawing comets for i=1:length(p), % set axis axes(handles(p(i))); % Get hold state and caxis memhold=ishold; cax=caxis; hold on; if strcmp(Property.marker,'lattice'), % Draw: marker is a patch ('hexa','rect') l_=som_cplane(lattice, coord, Property.markercolor, ... Property.markersize); % Set edgecolor set(l_,'edgecolor',Property.edgecolor); else % Draw: other markers than 'hexa' or 'rect' [S,m,l,t,s]=som_grid(lattice, [N_bmus 1], 'coord', coord,... 'Line','none', ... 'Marker', Property.marker, ... 'MarkerColor', Property.markercolor, ... 'MarkerSize',Property.markersize); % Set edgecolor set(m, 'markeredgecolor', Property.edgecolor); % Get handles from markers h_=[h_;l_(:);m(:);l(:);t(:);s(:)]; end % Set labels %[S,m,l,t,s]=som_grid(lattice, [N_labels 1], 'coord', label_coord,... % 'Marker','none','Line','none',... % 'Label', traj_lab, ... % 'LabelColor', Property.textcolor, ... % 'LabelSize', Property.textsize); % Get handles from labels %h_=[h_;m(:);l(:);t(:);s(:)]; % Restore hold state and caxis if ~memhold hold off; end caxis(cax); end %% Set object tags %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% set(h_,'Tag','Comet'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function P=init_properties; % Initialize an empty property struct P.marker=[]; P.markersize=[]; P.sizefactor=[]; P.markercolor=[]; P.edgecolor=[]; P.trajwidth=[]; P.widthfactor=[]; P.trajcolor=[]; P.text=[]; P.textsize=[]; P.textcolor=[]; P.subplot=[]; P.shift=[];
github
martinarielhartmann/mirtooloct-master
som_fuzzycolor.m
.m
mirtooloct-master/somtoolbox/som_fuzzycolor.m
6,305
utf_8
ba6ea6d7d1079610c8988bcb30365eb4
function [color,X]=som_fuzzycolor(sM,T,R,mode,initRGB,S) % SOM_FUZZYCOLOR Heuristic contraction projection/soft cluster color coding for SOM % % function [color,X]=som_fuzzycolor(map,[T],[R],[mode],[initRGB],[S]) % % sM (map struct) % [T] (scalar) parameter that defines the speed of contraction % T<1: slow contraction, T>1: fast contraction. Default: 1 % [R] (scalar) number of rounds, default: 30 % [mode] (string) 'lin' or 'exp', default: 'lin' % [initRGB] (string) Strings accepted by SOM_COLORCODE, default: 'rgb2' % [S] (matrix) MxM matrix a precalculated similarity matrix % color (matrix) of size MxRx3 resulting color codes at each step % X (matrix) of size MxRx2 coordiantes for projected unit weight vectors % at each step of iteration. (Color code C is calculated using this % projection.) % % The idea of the projection is to use a naive contraction model which % pulls the units together. Units that are close to each other in the % output space (clusters) contract faster into the same point in the % projection. The original position for each unit is its location in % the topological grid. % % This is an explorative tool to color code the map units so that % similar units (in the sense of euclidean norm) have similar coloring % (See also SOM_KMEANSCOLOR) The tool gives a series of color codings % which start from an initial color coding (see SOM_COLORCODE) and % show the how the fuzzy clustering process evolves. % % The speed of contraction is controlled by the input parameter T. If % it is high the projection contracts more slowly and reveals more % intermediate stages (hierarchy). A good value for T must be % searched manually. It is probable that the default values do not % yield good results. % % The conatrction process may be slow. In this case the mode can be % set to 'exp' instead of 'lin', however, then the computing becomes % heavier. % % EXAMPLE % % load iris; % or any other map struct sM % [color]=som_fuzzycolor(sM,'lin',10); % som_show(sM,'color',color); % % See also SOM_KMEANSCOLOR, SOM_COLORCODE, SOM_CLUSTERCOLOR % % REFERENCES % % Johan Himberg, "A SOM Based Cluster Visualization and Its % Application for False Coloring", in Proceedings of International % Joint Conference on Neural Networks (IJCNN2000)}, % pp. 587--592,Vol. 3, 2000 % % Esa Alhoniemi, Johan Himberg, and Juha Vesanto, Probabilistic % Measures for Responses of Self-Organizing Map Units, pp. 286--290, % in Proceedings of the International ICSC Congress on Computational % Intelligence Methods and Applications (CIMA '99)}, ICSC Academic % Press}, 1999 % % Outline of the heuristic % % First a matrix D of squared pairwise euclidean distances % D(i,j)=d(i,j)^2 between map weight vectors is calculated. This % matrix is transformed into a similarity matrix S, % s(i,j)=exp(-(D(i,j)/(T.^2*v)), where T is a free input parameter and % v the variance of all elements of D v=var(D(:)). The matrix is % further normalized so that all rows sum to one. The original % topological coordinates X=som_unit_coords(sM) are successively % averaged using this matrix. X(:,:,i)=S^i*X(:,:,1); As the process is % actually a series of successive weighted averagings of the initial % coordinates, all projected points eventually contract into one % point. T is a user defined parameter that defines how fast the % projection contracts into this center point. If T is too small, the % process will end into the center point at once. % % In practise, we don't calculate powers of S, but compute % % X(:,:,i)=S.*X(:,:,i-1); % mode: 'lin' % % The contraction process may be slow if T is selected to be large, % then for each step the similarity matrix is squared % % X(:,:,i)=S*X(:,:,1); S=S*S % mode: 'exp' % % The coloring is done using the function SOM_COLORCODE according to % the projections in X, The coordinates are rescaled in order to % achieve maximum color resolution. % Contributed to SOM Toolbox vs2, 2000 by Johan Himberg % Copyright (c) by Johan Himberg % http://www.cis.hut.fi/projects/somtoolbox/ % Previously rownorm function normalized the rows of S erroneously % into unit length, this major bug was corrected 14042003. Now the % rownorm normalizes the rows to have unit sum as it should johan 14042003 %% Check input arguments if isstruct(sM), if ~isfield(sM,'topol') error('Topology field missing.'); end M=size(sM.codebook,1); else error('Requires a map struct.'); end if nargin<2 | isempty(T), T=1; end if ~vis_valuetype(T,{'1x1'}) error('Input for T must be a scalar.'); end if nargin<3 | isempty(R), R=30; end if ~vis_valuetype(R,{'1x1'}) error('Input for R must be a scalar.'); end if nargin < 4 | isempty(mode), mode='lin'; end if ~ischar(mode), error('String input expected for mode.'); else mode=lower(mode); switch mode case {'lin','exp'} ; otherwise error('Input for mode must be ''lin'' or ''exp''.'); end end if nargin < 5 | isempty(initRGB) initRGB='rgb2'; end if ischar(initRGB), try dummy=som_colorcode(sM,initRGB); catch error(['Color code ''' initRGB ''' not known, see SOM_COLORCODE.']); end else error('Invalid color code string'); end if nargin<6 | isempty(S), S=fuzzysimilarity(sM,1./T); end if ~vis_valuetype(S,{[M M]}), error('Similarity matrix must be a MunitsxMunits matrix.') end x = maxnorm(som_unit_coords(sM.topol.msize,sM.topol.lattice,'sheet')); x = x-repmat(mean(x),size(x,1),1); X(:,:,1)=x; color(:,:,1)=som_colorcode(x,'rgb2',1); %%% Actions for i=1:R, switch mode case 'exp' S=rownorm(S*S); tmpX=S*X(:,:,1); case 'lin' tmpX=S*X(:,:,i); end X(:,:,i+1)=tmpX; color(:,:,i+1)=som_colorcode(X(:,:,i+1),initRGB); end color(isnan(color))=0; function r=fuzzysimilarity(sM,p) % Calculate a "fuzzy response" similarity matrix % sM: map % p: sharpness factor d=som_eucdist2(sM,sM); v=std(sqrt(d(:))).^2; r=rownorm(exp(-p^2*(d./v))); r(~isfinite(r))=0; return; function X = rownorm(X) r = sum(X,2); X = X ./ r(:,ones(size(X,2),1)); return; function X = maxnorm(X) for i=1:size(X,2), r = (max(X(:,i))-min(X(:,i))); if r, X(:,i) = X(:,i) / r; end, end return;
github
martinarielhartmann/mirtooloct-master
som_stats.m
.m
mirtooloct-master/somtoolbox/som_stats.m
9,256
utf_8
913c885c15a80104f02cd88b0bcbd0c8
function csS = som_stats(D,varargin) %SOM_STATS Calculate descriptive statistics for the data. % % csS = som_stats(D,[sort]); % % csS = som_stats(D); % csS = som_stats(D,'nosort'); % som_table_print(som_stats_table(csS)) % % Input and output arguments ([]'s are optional): % D (matrix) a matrix, size dlen x dim % (struct) data or map struct % [sort] (string) 'sort' (default) or 'nosort' % If 'nosort' is specified, the data is not % sorted, and therefore the values of % nunique, uvalues, ucount, fvalues, fcount, and tiles fields % are not calculated. This may be useful if % there is a very large amount of data, and % one wants to reduce calculation time. % % csS (cell array) size dim x 1, of statistics structs with % the following fields % .type (string) 'som_stat' % .name (string) name of the variable % .normalization (struct array) variable normalization (see SOM_NORMALIZE) % .ntotal (scalar) total number of values % .nvalid (scalar) number of valid values (not Inf or NaN) % .min (scalar) minimum value % .max (scalar) maximum value % .mean (scalar) mean value (not Inf or NaN) % .std (scalar) standard deviation (not Inf or NaN) % .nunique (scalar) number of unique values % .mfvalue (vector) most frequent value % .mfcount (vector) number of occurances of most frequent value % .values (vector) at most MAXDISCRETE (see below) sample values % .counts (vector) number of occurances for each sampled value % .tiles (vector) NT-tile values, for example % NT=4 for quartiles: 25%, 50% and 75% % NT=100 for percentiles: 1%, 2%, ... and 99% % .hist (struct) histogram struct with the following fields % .type (string) 'som_hist' % .bins (vector) histogram bin centers % .counts (vector) count of values in each bin % .binlabels (cellstr) labels for the bins (denormalized bin % center values) % .binlabels2 (cellstr) labels for the bins (denormalized bin % edge values, e.g. '[1.4,2.5[' % % Constants: % MAXDISCRETE = 10 % NT = 10 % % See also SOM_STATS_PLOT, SOM_STATS_TABLE, SOM_TABLE_PRINT, SOM_STATS_REPORT. % Contributed to SOM Toolbox 2.0, December 31st, 2001 by Juha Vesanto % Copyright (c) by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 311201 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 %% arguments % default values nosort = 0; nbins = 10; maxdiscrete = 20; ntiles = 10; % first argument if isstruct(D), switch D.type, case 'som_map', cn = D.comp_names; sN = D.comp_norm; D = D.codebook; case 'som_data', cn = D.comp_names; sN = D.comp_norm; D = D.data; otherwise, error('Invalid first argument') end else cn = cell(size(D,2),1); cn(:) = {'Variable'}; for i=1:length(cn), cn{i} = sprintf('%s%d',cn{i},i); end sN = cell(size(D,2),1); end [dlen dim] = size(D); % other arguments if length(varargin)>0, if strcmp(varargin{1},'nosort'), nosort = 1; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 %% action sStat = struct('type','som_stat','name','','normalization',[],... 'min',NaN,'max',NaN,'mean',NaN,'std',NaN,... 'nunique',NaN,'values',[],'counts',[],'mfvalue',NaN,'mfcount',NaN,'tiles',[],... 'ntotal',dlen,'nvalid',NaN,'hist',[]); csS = cell(0); for i=1:dim, sS = sStat; sS.name = cn{i}; sS.normalization = sN{i}; x = D(:,i); x(find(~isfinite(x))) = []; % basic descriptive statistics sS.nvalid = length(x); if length(x), sS.min = min(x); sS.max = max(x); sS.mean = mean(x); sS.std = std(x); bins = []; if ~nosort, xsorted = sort(x); % number of unique values repeated = (xsorted(1:end-1)==xsorted(2:end)); j = [1; find(~repeated)+1]; xunique = xsorted(j); sS.nunique = length(xunique); ucount = diff([j; length(xsorted)+1]); % most frequent value [fcount,j] = max(ucount); sS.mfvalue = xunique(j); sS.mfcount = fcount; % -tiles (k*100/ntiles % of values, k=1..) pickind = round(linspace(1,sS.nvalid,ntiles+1)); pickind = pickind(2:end-1); sS.tiles = xsorted(pickind); if sS.nunique <= sS.nvalid/2, % unique values sS.values = xunique; sS.counts = ucount; bins = sS.values; else % just maxdiscrete values, evenly picked pickind = round(linspace(1,sS.nunique,maxdiscrete)); sS.values = xunique(pickind); sS.counts = ucount(pickind); %% OPTION 2: maxdiscrete most frequent values %[v,j] = sort(ucount); %pickind = j(1:maxdiscrete); %sS.values = xunique(pickind); %sS.counts = ucount(pickind); % OPTION 3: representative values - calculated using k-means %[y,bm,qe] = kmeans(x,maxdiscrete); %sS.values = y; %sS.counts = full(sum(sparse(bm,1:length(bm),1,maxdiscrete,length(bm)),2)); end end if isempty(bins), bins = linspace(sS.min,sS.max,nbins+1); bins = (bins(1:end-1)+bins(2:end))/2; end sS.hist = som_hist(x,bins,sS.normalization); else sS.hist = som_hist(x,0); end csS{end+1} = sS; end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 %% subfunctions function sH = som_hist(x,bins,sN) binlabels = []; binlabels2 = []; if nargin<2 | isempty(bins) | isnan(bins), bins = linspace(min(x),max(x),10); end if isstruct(bins), bins = sH.bins; binlabels = sH.binlabels; binlabels2 = sH.binlabels2; end if nargin<3, sN = []; end sH = struct('type','som_hist','bins',bins,'counts',[],... 'binlabels',binlabels,'binlabels2',binlabels2); if length(bins)==1, sH.counts = [length(x)]; edges = bins; elseif length(x), edges = (bins(1:end-1)+bins(2:end))/2; counts = histc(x,[-Inf; edges(:); Inf]); sH.counts = counts(1:end-1); end if isempty(sH.binlabels), b = som_denormalize(bins(:),sN); sH.binlabels = numtostring(b,4); end if isempty(sH.binlabels2), if length(edges)==1, sH.binlabels2 = numtostring(som_denormalize(edges,sN),2); if length(bins)>1, sH.binlabels2 = sH.binlabels2([1 1]); sH.binlabels2{1} = [']' sH.binlabels2{1} '[']; sH.binlabels2{2} = ['[' sH.binlabels2{2} '[']; end else if size(edges,1)==1, edges = edges'; end bstr = numtostring(som_denormalize(edges,sN),4); sH.binlabels2 = bstr([1:end end]); sH.binlabels2{1} = [bstr{1} '[']; for i=2:length(sH.binlabels2)-1, sH.binlabels2{i} = ['[' bstr{i-1} ',' bstr{i} '[']; end sH.binlabels2{end} = ['[' bstr{end}]; end end if 0, if length(bins)==1, sH.binlabels2 = {'constant'}; else ntiles = 10; plim = [1:ntiles-1] / ntiles; cp = cumsum(sH.counts)/sum(sH.counts); [dummy,i] = histc(cp,[-Inf plim Inf]); l2 = cell(length(bins),1); for j=1:length(bins), l2{j} = sprintf('Q%d',i(j)); end if i(1) > 1, l2{1} = ['...' l2{1}]; end k = 0; for j=2:length(bins), if i(j)==i(j-1), if k==0, l2{j-1} = [l2{j-1} '.1']; k = 1; end k = k + 1; l2{j} = [l2{j} '.' num2str(k)]; else k = 0; end end if i(end) < ntiles, l2{end} = [l2{end} '...']; end sH.binlabels2 = l2; end end return; function vstr = numtostring(v,d) r = max(v)-min(v); if r==0, r=1; end nearzero = (abs(v)/r < 10.^-d); i1 = find(v > 0 & nearzero); i2 = find(v < 0 & nearzero); vstr = strrep(cellstr(num2str(v,d)),' ',''); vstr(i1) = {'0.0'}; vstr(i2) = {'-0.0'}; return;
github
martinarielhartmann/mirtooloct-master
knn_old.m
.m
mirtooloct-master/somtoolbox/knn_old.m
7,196
utf_8
91ff9ef390bf0c8610ff647a8a3e29bd
function [Class,P]=knn_old(Data, Proto, proto_class, K) %KNN_OLD A K-nearest neighbor classifier using Euclidean distance % % [Class,P]=knn_old(Data, Proto, proto_class, K) % % [sM_class,P]=knn_old(sM, sData, [], 3); % [sD_class,P]=knn_old(sD, sM, class); % [class,P]=knn_old(data, proto, class); % [class,P]=knn_old(sData, sM, class,5); % % Input and output arguments ([]'s are optional): % Data (matrix) size Nxd, vectors to be classified (=classifiees) % (struct) map or data struct: map codebook vectors or % data vectors are considered as classifiees. % Proto (matrix) size Mxd, prototype vector matrix (=prototypes) % (struct) map or data struct: map codebook vectors or % data vectors are considered as prototypes. % [proto_class] (vector) size Nx1, integers 1,2,...,k indicating the % classes of corresponding protoptypes, default: see the % explanation below. % [K] (scalar) the K in KNN classifier, default is 1 % % Class (matrix) size Nx1, vector of 1,2, ..., k indicating the class % desicion according to the KNN rule % P (matrix) size Nxk, the relative amount of prototypes of % each class among the K closest prototypes for % each classifiee. % % If 'proto_class' is _not_ given, 'Proto' _must_ be a labeled SOM % Toolbox struct. The label of the data vector or the first label of % the map model vector is considered as class label for th prototype % vector. In this case the output 'Class' is a copy of 'Data' (map or % data struct) relabeled according to the classification. If input % argument 'proto_class' _is_ given, the output argument 'Class' is % _always_ a vector of integers 1,2,...,k indiacating the class. % % If there is a tie between representatives of two or more classes % among the K closest neighbors to the classifiee, the class is % selected randomly among these candidates. % % IMPORTANT % % ** Even if prototype vectors are given in a map struct the mask _is not % taken into account_ when calculating Euclidean distance % ** The function calculates the total distance matrix between all % classifiees and prototype vectors. This results to an MxN matrix; % if N is high it is recommended to divide the matrix 'Data' % (the classifiees) into smaller sets in order to avoid memory % overflow or swapping. Also, if K>1 this function uses 'sort' which is % considerably slower than 'max' which is used for K==1. % % See also KNN, SOM_LABEL, SOM_AUTOLABEL % Contributed to SOM Toolbox 2.0, February 11th, 2000 by Johan Himberg % Copyright (c) by Johan Himberg % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta Johan 040200 %% Init %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This must exist later classnames=''; % Check K if nargin<4 | isempty(K), K=1; end if ~vis_valuetype(K,{'1x1'}) error('Value for K must be a scalar.'); end % Take data from data or map struct if isstruct(Data); if isfield(Data,'type') & ischar(Data.type), ; else error('Invalid map/data struct?'); end switch Data.type case 'som_map' data=Data.codebook; case 'som_data' data=Data.data; end else % is already a matrix data=Data; end % Take prototype vectors from prototype struct if isstruct(Proto), if isfield(Proto,'type') & ischar(Proto.type), ; else error('Invalid map/data struct?'); end switch Proto.type case 'som_map' proto=Proto.codebook; case 'som_data' proto=Proto.data; end else % is already a matrix proto=Proto; end % Check that inputs are matrices if ~vis_valuetype(proto,{'nxm'}) | ~vis_valuetype(data,{'nxm'}), error('Prototype or data input not valid.') end % Record data&proto sizes and check their dims [N_data dim_data]=size(data); [N_proto dim_proto]=size(proto); if dim_proto ~= dim_data, error('Data and prototype vector dimension does not match.'); end % Check if the classes are given as labels (no class input arg.) % if they are take them from prototype struct if nargin<3 | isempty(proto_class) if ~isstruct(Proto) error(['If prototypes are not in labeled map or data struct' ... 'class must be given.']); % transform to interger (numerical) class labels else [proto_class,classnames]=class2num(Proto.labels); end end % Check class label vector: must be numerical and of integers if ~vis_valuetype(proto_class,{[N_proto 1]}); error(['Class vector is invalid: has to be a N-of-data_rows x 1' ... ' vector of integers']); elseif sum(fix(proto_class)-proto_class)~=0 error('Class labels in vector ''Class'' must be integers.'); end % Find all class labels ClassIndex=unique(proto_class); N_class=length(ClassIndex); % number of different classes % Calculate euclidean distances between classifiees and prototypes d=distance(proto,data); %%%% Classification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if K==1, % sort distances only if K>1 % 1NN % Select the closest prototype [tmp,proto_index]=min(d); class=proto_class(proto_index); else % Sort the prototypes for each classifiee according to distance [tmp,proto_index]=sort(d); %% Select K closest prototypes proto_index=proto_index(1:K,:); knn_class=proto_class(proto_index); for i=1:N_class, classcounter(i,:)=sum(knn_class==ClassIndex(i)); end %% Vote between classes of K neighbors [winner,vote_index]=max(classcounter); %% Handle ties % set index to clases that got as amuch votes as winner equal_to_winner=(repmat(winner,N_class,1)==classcounter); % set index to ties tie_index=find(sum(equal_to_winner)>1); % drop the winner from counter % Go through equal classes and reset vote_index randomly to one % of them for i=1:length(tie_index), tie_class_index=find(equal_to_winner(:,tie_index(i))); fortuna=randperm(length(tie_class_index)); vote_index(tie_index(i))=tie_class_index(fortuna(1)); end class=ClassIndex(vote_index); end %% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Relative amount of classes in K neighbors for each classifiee if K==1, P=zeros(N_data,N_class); if nargout>1, for i=1:N_data, P(i,ClassIndex==class(i))=1; end end else P=classcounter'./K; end % xMake class names to struct if they exist if ~isempty(classnames), Class=Data; for i=1:N_data, Class.labels{i,1}=classnames{class(i)}; end else Class=class; end %%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nos,names] = class2num(class) % Change string labels in map/data struct to integer numbers names = {}; nos = zeros(length(class),1); for i=1:length(class) if ~isempty(class{i}) & ~any(strcmp(class{i},names)) names=cat(1,names,class(i)); end end tmp_nos = (1:length(names))'; for i=1:length(class) if ~isempty(class{i}) nos(i,1) = find(strcmp(class{i},names)); end end function d=distance(X,Y); % Euclidean distance matrix between row vectors in X and Y U=~isnan(Y); Y(~U)=0; V=~isnan(X); X(~V)=0; d=X.^2*U'+V*Y'.^2-2*X*Y';
github
martinarielhartmann/mirtooloct-master
som_trajectory.m
.m
mirtooloct-master/somtoolbox/som_trajectory.m
9,582
utf_8
943fbebf146286d22761e716b557cf75
function som_trajectory(bmus,varargin) %SOM_TRAJECTORY Launch a "comet" trajectory visualization GUI. % % som_show(sM,'umat','all') % bmus = som_bmus(sM,sD); % som_trajectory(bmus) % som_trajectory(bmus, 'data1', sD, 'trajsize', [12 6 3 1]') % som_trajectory(bmus, 'data1', sD.data(:,[1 2 3]), 'name1', {'fii' 'faa' 'foo'}) % % Input arguments ([]'s are optional): % bmus (matrix) size Nx1, vector of BMUS % ['argID', (string) Other arguments can be given as 'argID', value % value] (varies) pairs. See list below for valid values. % % NOTE: the GUI only works on a figure which has been made with SOM_SHOW. % % Here are the valid argument IDs (case insensitive) and associated values: % 'color' string 'xor' or ColorSpec, default: 'xor'. % (default: according to lattice as in som_cplane) % 'TrajSize' vector of size Nx1 to define the length of comet % (N) and size of the comet dots in points. % default: [16 12 10 8 6 4]' % 'Data1' SOM Toolbox data struct or matrix. The size of % data matrix (in data struct the field .data) is % Nxd, where N must be the same as the amount of % BMUS given in the first input argument 'bmus' % This data is shown in a new window in d subplots. % Default: BMU indices (first input argument) % 'Name1' cell array of d strings which contains names % for the components in 'Data1'. If 'Data1' is a SOM % Toolbox data struct, the existing component names % are overdone. % 'Figure' scalar that must be a handle to an existing figure % which has been made using SOM_SHOW function. % Default: current active figure (gcf). % % The following tools can be found in the 'Tools' -menu. % % Remove Trajectory: removes trajectory from the map. % Dye Nodes : opens GUI for selecting color for the nodes % and points selected. % Clear Markers : removes markers from map and data figure. % Save : saves the current situation as a struct. % Load : loads the struct from workspace and draws markers. % % Mouse operation % % In data window: Left button is used to drag the operation point ruler % if left button is on blank area, it starts % In map window : Left button starts a polygon; right button % finishes; middle button toggles a unit. % % SOM_TRAJECTORY is an application for observing trajectory behavior. % % Using mouse the line in data figure can be dragged and the % trajectory moves in the SOM SHOW figure. It is also possible to move % trajectory by pressing keys '>' and '<' when mouse pointer is above % data figure. % % Regions can be chosen from the data and the points in that region % are mapped to the component planes. Regions can be chosen also in % the map. In this situation data points and map nodes are also % marked (Left mouse button adds point to the polygon indicating the % region and right button finals the polygon). By clicking a node (the % middle button) that node is either added or removed from selection. % % It should be noticed that choosing intervals from data may cause % situations that seem to be bugs. If there exisist marks of different % color, removing them by clicking the map may left some marks in the % data, because more than one point in the data is mapped to the same % node in the map and the removing operation depends on the color of % the marks. However, all the marks can be removed by using the 'Clear % Markers' -operation. % % FEATURES % % The first input argument 'bmus' may also be a munits x N matrix % In this case each column defines a "fuzzy response". That is, % each column defines a hit histogram function). The element % bmus(i,t) sets the size of marker on unit i at time t. % NOTE: - in this case no regions can be selcted on the map! % - only > and < keys can be used to move the operation point % line: it can't be dragged % - "fuzzy response is always black (hope this will be fixed) % % It is possible to open a second data window showing different data: % use indetifiers 'Data2' (and 'Name2'). The argument syntax is % identical to 'Data1' (and 'Name1'). % % See also SOM_SHOW, SOM_SHOW_ADD, SOM_BMUS. % Contributed to SOM Toolbox 2.0, February 11th, 2000 by Johan % Himberg and Juha Parhankangas % Copyright (c) 2000 by the Johan Himberg and Juha Parhankangas % http://www.cis.hut.fi/projects/somtoolbox/ % Check arguments error(nargchk(1,Inf,nargin)); % Check no. of input arguments %% Init input argument struct (see subfunction) Traj=iniTraj(bmus); % Check tentative BMU input validity if ~vis_valuetype(bmus,{'nxm'}), error(['First input should be a vector of BMU indices or' ... ' a "response matrix"']); end %% Check optional arguments for i=1:2:length(varargin) identifier=lower(varargin{i}); value=varargin{i+1}; % Trajectory color switch identifier case 'color' if isempty(value) value='xor'; end if vis_valuetype(value,{'colorstyle','xor'}) Traj.color=value; else error('''Color'' has to be ColorSpec or string ''xor''.'); end % 1st data case 'data1' if isempty(value), value=[]; elseif vis_valuetype(value,{'nxm'}) Traj.primary_data=value; elseif isstruct(value) & isfield(value,'type') & ... ischar(value.type) & strcmp(value.type,'som_data'), Traj.primary_data=value.data; if isempty(Traj.primary_names), Traj.primary_names=value.comp_names; end end % 2nd data case 'data2' if isempty(value), value=[]; elseif vis_valuetype(value,{'nxm'}) Traj.secondary_data=value; elseif isstruct(value) & isfield(value,'type') & ... ischar(value.type) & strcmp(value.type,'som_data'), Traj.secondary_data=value.data; if isempty(Traj.secondary_names), Traj.secondary_names=value.comp_names; end end % Trajectory length & size case 'trajsize' if isempty(value), Traj.size=[16 12 10 8 6 4]'; end if vis_valuetype(value,{'nx1'}) Traj.size=value else error('''TrajSize'' has to be a nx1 vector.'); end % Names for first data variables case 'name1' if isempty(value), Traj.primary_names=[]; elseif ~vis_valuetype(value,{'cellcolumn_of_char'}), error('''Name1'': variable names must be in a cell column array.') else Traj.primary_names = value; end % Names for 2nd data variables case 'name2' if isempty(value), Traj.secondary_names=[]; elseif ~vis_valuetype(value,{'cellcolumn_of_char'}), error('''Name2'': variable names must be in a cell column array.') else Traj.secondary_names = value; end % Figure number case 'figure' if isempty(value) Traj.figure='gcf'; end if vis_valuetype(value,{'1x1'}) Traj.figure=value; else error('''Figure'' should be number of an existing figure.') end end end %% Get SOM data from figure [h,msg,lattice,msize,dim]=vis_som_show_data('all',Traj.figure); %% Not a SOM_SHOW figure? if ~isempty(msg); error('Figure is invalid: use SOM_SHOW to draw the figure.'); end % Get map size from figure data Traj.lattice=lattice; Traj.msize=msize; if length(msize)>2, error(['This function works only with 2D maps: figure contains' ... ' something else.']); end munits=prod(msize); % Check BMU (or response) and map match if vis_valuetype(bmus,{'nx1'}); if max(bmus)>prod(msize) | min(bmus) <1 error('BMU indexes out of range.') elseif any(round(bmus)~=bmus) error('BMU indexes must be integer.'); elseif isempty(Traj.primary_data), Traj.primary_data=bmus; end elseif size(bmus,1) ~= munits error(['Response matrix column number must match with the number of' ... ' map units.']); else bmus=bmus'; if isempty(Traj.primary_data), Traj.primary_data=[1:size(bmus,1)]'; Traj.primary_names={'BMU Index'}; end end size1=size(Traj.primary_data); size2=size(Traj.secondary_data); % Data2 must not be defined alone if isempty(Traj.primary_data)&~isempty(Traj.secondary_data), error('If ''Data2'' is specified ''Data1'' must be specified, too.'); elseif ~isempty(Traj.secondary_data) ... & size1~= size2 % If data1 and data2 exist both, check data1 and data2 match error('''Data1'' and ''Data2'' have different amount of data vectors.') end % Check BMU and data1 match (data2 matches with 1 anyway) if ~isempty(Traj.primary_data) & size(bmus,1) ~= size1, error(['The number of data vectors in ''data1'' must match with' ... ' the number of rows in the first input argument (bmus).']); end % Check that number of names and data dimension is consistent if ~isempty(Traj.primary_names) & (size1(2)~=length(Traj.primary_names)), error('Number of component names and ''Data1'' dimension mismatch.'); end if ~isempty(Traj.secondary_names) & ... (size2(2)~=length(Traj.secondary_names)), error('Number of component names and ''Data2'' dimension mismatch.'); end %% Call the function that does the job vis_trajgui(Traj); %%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Traj=iniTraj(bmus) Traj.figure=gcf; Traj.primary_data=[]; Traj.secondary_data=[]; Traj.primary_names = []; Traj.secondary_names = []; Traj.size=[16 12 10 8 6 4]'; Traj.bmus=bmus; Traj.color='xor'; Traj.msize=[]; Traj.lattice=[];
github
martinarielhartmann/mirtooloct-master
som_vs1to2.m
.m
mirtooloct-master/somtoolbox/som_vs1to2.m
7,005
utf_8
ff7eede3183ba5dfa54884255dc76c4e
function sS = som_vs1to2(sS) %SOM_VS1TO2 Convert version 1 structure to version 2. % % sSnew = som_vs1to2(sSold) % % sMnew = som_vs1to2(sMold); % sDnew = som_vs1to2(sDold); % % Input and output arguments: % sSold (struct) a SOM Toolbox version 1 structure % sSnew (struct) a SOM Toolbox version 2 structure % % For more help, try 'type som_vs1to2' or check out online documentation. % See also SOM_SET, SOM_VS2TO1. %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_vs1to2 % % PURPOSE % % Transforms SOM Toolbox 1 version structs from to 2 version structs. % % SYNTAX % % sS2 = som_vs1to2(sS1) % % DESCRIPTION % % This function is offered to allow the change of old map and data structs % to new ones. There are quite a lot of changes between the versions, % especially in the map struct, and this function makes it easy to update % the structs. % % WARNING! % % 'som_unit_norm' normalization type is not supported by version 2, % so this type of normalization will be lost. % % REQUIRED INPUT ARGUMENTS % % sS1 (struct) any SOM Toolbox version 1 struct (map, data, % training or normalization struct) % % OUTPUT ARGUMENTS % % sS2 (struct) the corresponding SOM Toolbox 2 version struct % % EXAMPLES % % sM = som_vs1to2(sMold); % sD = som_vs1to2(sDold); % sT = som_vs1to2(sMold.train_sequence{1}); % sN = som_vs1to2(sDold.normalization); % % SEE ALSO % % som_set Set values and create SOM Toolbox structs. % som_vs2to1 Transform structs from version 2.0 to 1.0. % Copyright (c) 1999-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 101199 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% check arguments error(nargchk(1, 1, nargin)); % check no. of input arguments is correct %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% set field values if isfield(sS,'codebook'), type='som_map'; elseif isfield(sS,'data'), type='som_data'; elseif isfield(sS,'algorithm'), type = 'som_train'; elseif isfield(sS,'inv_params'), type = 'som_norm'; else error('Unrecognized input struct.'); end switch type, case 'som_map', msize = sS.msize; munits = prod(msize); dim = prod(size(sS.codebook))/munits; M = reshape(sS.codebook,[munits dim]); % topology if strcmp(sS.shape,'rect'), shape = 'sheet'; else shape = sS.shape; end sTopol = struct('type','som_topol','msize',msize,'lattice',sS.lattice,'shape',shape); % labels labels = cell(munits,1); for i=1:munits, for j=1:length(sS.labels{i}), labels{i,j} = sS.labels{i}{j}; end end % trainhist tl = length(sS.train_sequence); if strcmp(sS.init_type,'linear'); alg = 'lininit'; else alg = 'randinit'; end trh = struct('type','som_train'); trh.algorithm = alg; trh.neigh = sS.neigh; trh.mask = sS.mask; trh.data_name = sS.data_name; trh.radius_ini = NaN; trh.radius_fin = NaN; trh.alpha_ini = NaN; trh.alpha_type = ''; trh.trainlen = NaN; trh.time = ''; for i=1:tl, trh(i+1) = som_vs1to2(sS.train_sequence{i}); trh(i+1).mask = sS.mask; trh(i+1).neigh = sS.neigh; trh(i+1).data_name = sS.data_name; end % component normalizations cnorm = som_vs1to2(sS.normalization); if isempty(cnorm), cnorm = cell(dim,1); elseif length(cnorm) ~= dim, warning('Incorrect number of normalizations. Normalizations ignored.\n'); cnorm = cell(dim,1); else if strcmp(cnorm{1}.method,'histD'), M = redo_hist_norm(M,sS.normalization.inv_params,cnorm); end end % map sSnew = struct('type','som_map'); sSnew.codebook = M; sSnew.topol = sTopol; sSnew.labels = labels; sSnew.neigh = sS.neigh; sSnew.mask = sS.mask; sSnew.trainhist = trh; sSnew.name = sS.name; sSnew.comp_norm = cnorm; sSnew.comp_names = sS.comp_names; case 'som_data', [dlen dim] = size(sS.data); % component normalizations cnorm = som_vs1to2(sS.normalization); if isempty(cnorm), cnorm = cell(dim,1); elseif length(cnorm) ~= dim, warning('Incorrect number of normalizations. Normalizations ignored.\n'); cnorm = cell(dim,1); else if strcmp(cnorm{1}.method,'histD'), sS.data = redo_hist_norm(sS.data,sS.normalization.inv_params,cnorm); end end % data sSnew = struct('type','som_data'); sSnew.data = sS.data; sSnew.name = sS.name; sSnew.labels = sS.labels; sSnew.comp_names = sS.comp_names; sSnew.comp_norm = cnorm; sSnew.label_names = []; case 'som_norm', if isempty(sS.inv_params), sSnew = []; else dim = size(sS.inv_params,2); sSnew = cell(dim,1); switch sS.name, case 'som_var_norm', method = 'var'; case 'som_lin_norm', method = 'range'; case 'som_hist_norm', method = 'histD'; case 'som_unit_norm', method = ''; warning(['Normalization method ''som_unit_norm'' is not available' ... ' in version 2 of SOM Toolbox.\n']); end if ~isempty(method), for i=1:dim, sSnew{i} = struct('type','som_norm'); sSnew{i}.method = method; sSnew{i}.params = []; sSnew{i}.status = 'done'; switch method, case 'var', me = sS.inv_params(1,i); st = sS.inv_params(2,i); sSnew{i}.params = [me, st]; case 'range', mi = sS.inv_params(1,i); ma = sS.inv_params(2,i); sSnew{i}.params = [mi, ma-mi]; case 'histD', vals = sS.inv_params(1:(end-1),i); bins = sum(isfinite(vals)); vals = vals(1:bins); sSnew{i}.params = vals; end end end end case 'som_train', sSnew = struct('type','som_train'); sSnew.algorithm = sS.algorithm; sSnew.neigh = 'gaussian'; sSnew.mask = []; sSnew.data_name = 'unknown'; sSnew.radius_ini = sS.radius_ini; sSnew.radius_fin = sS.radius_fin; sSnew.alpha_ini = sS.alpha_ini; sSnew.alpha_type = sS.alpha_type; sSnew.trainlen = sS.trainlen; sSnew.time = sS.time; case 'som_topol', disp('Version 1.0 of SOM Toolbox did not have topology structure.\n'); case {'som_grid','som_vis'} disp('Version 1.0 of SOM Toolbox did not have visualization structs.\n'); otherwise, error('Unrecognized struct.'); end sS = sSnew; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function D = redo_hist_norm(D,inv_params,cnorm) dim = size(D,2); % first - undo the old way n_bins = inv_params(end,:); D = round(D * sparse(diag(n_bins))); for i = 1:dim, if any(isnan(D(:, i))), D(isnan(D(:, i)), i) = n_bins(i); end D(:, i) = inv_params(D(:, i), i); end % then - redo the new way for i=1:dim, bins = length(cnorm{i}.params); x = D(:,i); inds = find(~isnan(x) & ~isinf(x))'; for j = inds, [dummy ind] = min(abs(x(j) - cnorm{i}.params)); if x(j) > cnorm{i}.params(ind) & ind < bins, x(j) = ind + 1; else x(j) = ind; end end D(:,i) = (x-1)/(bins-1); end
github
martinarielhartmann/mirtooloct-master
rep_utils.m
.m
mirtooloct-master/somtoolbox/rep_utils.m
18,698
utf_8
729db4f7bcce5f1f91eab7a63c3acdc1
function aout = rep_utils(action,fmt,fid) %REP_UTILS Utilities for print reports and report elements. % % aout = rep_utils(action,fmt,[fid]) % % Input and output arguments ([]'s are optional): % action (string) action identifier % (cell array) {action,par1,par2,...} % the action identifier, followed by action % parameters % [fmt] (string) format of output, 'txt' by default % [fid] (scalar) output file id, by default NaN in which % case output is not written, only returned % in aout % % aout (varies) output of the action % % Here are the actions and their arguments: % 'printlines' par1 (cellstr) print par1, each cell on a new line % 'header' par1 (string) print document header using par1 as title % 'footer' print document footer % 'compile' par1 (string) compile the named document (only 'ps' and 'pdf') % 'inserttable' par1 (struct) print given table % par2 (scalar) print lines between rows if par2=1 % par3 (scalar) use longtable format (only 'ps' and 'pdf') % 'printfigure' par1 (string) print current figure to file, par1 = filename % par2 (scalar) used resolution (150 dpi by default) % par3 (scalar) if par3=1, insert figure in minipage % 'insertfigure' par1 (string) insert figure to report, par1 = filename of figure % par2 (vector) size 2 x 1, size of figure relative to page size % NaN = automatic scaling % par3 (scalar) if par3=1, insert figure in minipage (only 'ps' and 'pdf') % 'insertbreak' insert paragraph break into report % % See also REP_STATS. % Contributed to SOM Toolbox 2.0, January 2nd, 2002 by Juha Vesanto % Copyright (c) by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 020102 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% input arguments pars = {''}; if iscell(action), if length(action)>1, pars = action(2:end); end action = action{1}; end if nargin<2 | isempty(fmt), fmt = 'txt'; end global REPORT_OUTPUT_FMT REPORT_OUTPUT_FMT = fmt; if nargin<3 | isempty(fid), fid = NaN; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% action aout = []; printable = 0; switch action, case 'printlines', aout = pars{1}; case 'header', switch fmt, case {'ps','pdf'}, aout = tex_startdocument(pars{1}); case 'html', aout = html_startpage(pars{1}); case 'txt', aout = cell(0); end printable = 1; case 'footer', switch fmt, case {'ps','pdf'}, aout = tex_enddocument; case 'html', aout = html_endpage; case 'txt', aout = cell(0); end printable = 1; case 'compile', aout = compiledocument(pars{1}); case 'inserttable', aout = inserttable(pars{:}); printable = 1; case 'printfigure', printfigure(pars{:}); case 'insertfigure', aout = insertfigure(pars{:}); printable = 1; case 'insertbreak', aout = insertbreak; printable = 1; case 'joinstr', aout = joinstr(pars{:}); printable = 1; case 'rulestr', aout = rulestr(pars{:}); printable = 1; case 'c_and_p_str', aout = c_and_p_str(pars{:}); printable = 1; case 'p_str', aout = p_str(pars{:}); printable = 1; end % if output file is given, print lines if ~isnan(fid) & printable, if ~iscell(aout), aout = {aout}; end for i = 1:length(aout), fprintf(fid,'%s\n',fmtline(aout{i})); end end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions %% simple formatter strings function s = joinstr(cs, sep1, sep2) if nargin==1, sep1 = ', '; sep2 = ' and '; end if nargin<3, sep2 = sep1; end if isempty(cs), s = ''; elseif strcmp(sep1,'\n'), if size(cs,1)==1, cs = cs'; end s = char(cs); else s = cs{1}; for i=2:length(cs)-1, s = [s sep1 cs{i}]; end if length(cs)>1, s = [s sep2 cs{end}]; end end return; function str = c_and_p_str(n,m) % return a string of form # (%), e.g. '23 (12%)' if n==m, p = '100'; elseif n==0, p = '0'; else p = sprintf('%.2g',100*n/m); end str = sprintf('%d (%s%%)',round(n),p); return; function str = p_str(p) % return a string of form %, e.g. '12%' if round(p*100)>=100, p = sprintf('%3g',100*p); elseif abs(p)<eps, p = '0'; else p = sprintf('%.2g',100*p); end str = sprintf('%s%%',p); return; function cs = rulestr(sR,cnames) global REPORT_OUTPUT_FMT switch REPORT_OUTPUT_FMT case {'ps','pdf'}, [leq,geq,infi,m,less,in] = deal('\leq','\geq','\inf','$','<','\in'); case 'html', [leq,geq,infi,m,less,in] = deal('&lt;=','&gt;=','Inf',' ','&lt;',' '); case 'txt', [leq,geq,infi,m,less,in] = deal('<=','>=','inf',' ','<',''); end nr = length(sR); cs = cell(nr,1); fmt = '%.2g'; if nargin<2, cnames = {sR.name}; end if isempty(cnames), cnames = cell(nr,1); cnames(:) = {''}; end for i=1:nr, low = sR(i).low; high = sR(i).high; switch isfinite(low) + 2*isfinite(high), case 0, cs{i} = [cnames{i} ' ' 'any']; case 1, cs{i} = [cnames{i} ' ' m geq sprintf(fmt,low) m]; case 2, cs{i} = [cnames{i} ' ' m less sprintf(fmt,high) m]; case 3, cs{i} = [cnames{i} ' ' m in '[' sprintf(fmt,low) ',' sprintf(fmt,high) ']' m]; end end return; %% print figure function imgfmt = fmt2imgfmt global REPORT_OUTPUT_FMT switch REPORT_OUTPUT_FMT, case 'ps', imgfmt = 'ps'; case 'pdf', imgfmt = 'pdf'; case 'html', imgfmt = 'png'; case 'txt', imgfmt = ''; end return; function printfigure(fname,resolution) if nargin<2, resolution = 150; end fnameps = [fname '.ps']; switch fmt2imgfmt, case 'ps', print('-dpsc2',fnameps); case 'pdf', print('-dpsc2',fnameps); eval(sprintf('!ps2pdf %s',fnameps)); case 'gif', print('-dpsc2',fnameps); cmd = 'pstogif'; opt = sprintf('-depth 1 -density %d',resolution); unix(sprintf('%s %s -out %s %s',cmd,opt,[fname '.gif'],fnameps)); case 'png', opt = sprintf('-r%d',resolution); print('-dpng',opt,[fname '.png']); end return; %% headers and footers, and compilation function cs = tex_startdocument(title) % tex document headers global REPORT_OUTPUT_FMT cs = cell(0); cs{end+1} = '\documentclass[10pt,a4paper]{article}'; cs{end+1} = '\usepackage[dvips]{epsfig,graphicx,color}'; cs{end+1} = '\usepackage{float,graphics,subfigure}'; cs{end+1} = '\usepackage{multirow,rotating,portland,lscape,longtable,pifont}'; cs{end+1} = '\usepackage[T1]{fontenc}'; if strcmp(REPORT_OUTPUT_FMT,'pdf'), cs{end+1} = '\usepackage{pslatex}'; end cs{end+1} = '\usepackage[english]{babel}'; cs{end+1} = '\oddsidemargin 0 mm'; cs{end+1} = '\evensidemargin 0 mm'; cs{end+1} = '\textwidth 17 cm'; cs{end+1} = '\topmargin 0 mm'; cs{end+1} = '\textheight 21 cm'; cs{end+1} = '\voffset 0 mm'; cs{end+1} = '\begin{document}'; cs{end+1} = ['\title{' title '}']; cs{end+1} = '\maketitle'; %cs{end+1} = '\tableofcontents'; %cs{end+1} = '\clearpage'; return; function cs = tex_enddocument cs = cell(0); cs{end+1} = '\end{document}'; return; function cs = html_startpage(title) % print HTML document headers cs = cell(0); cs{end+1} = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">'; cs{end+1} = '<HTML>'; cs{end+1} = '<HEAD>'; cs{end+1} = sprintf(' <TITLE>%s</TITLE>',title); cs{end+1} = '</HEAD>'; cs{end+1} = '<BODY bgcolor=white vlink="#000033" link="#0000ff" text="#000000">'; if ~isempty(title), cs{end+1} = sprintf('<H1>%s</H1>',title); end return; function cs = html_endpage % print HTML document footers cs = cell(0); cs{end+1} = '<P><HR>'; cs{end+1} = '</BODY>'; cs{end+1} = '</HTML>'; return; function files = compiledocument(filename) global REPORT_OUTPUT_FMT switch REPORT_OUTPUT_FMT, case 'pdf', eval(sprintf('!pdflatex --interaction batchmode %s.tex',filename)); eval(sprintf('!pdflatex --interaction batchmode %s.tex',filename)); %eval(sprintf('!acroread %s.pdf &',filename)); files = {[filename '.aux'],[filename '.log'],[filename '.out'],[filename '.pdf']}; case 'ps', eval(sprintf('!latex --interaction batchmode %s.tex',filename)); eval(sprintf('!latex --interaction batchmode %s.tex',filename)); eval(sprintf('!dvips %s.dvi',filename)); eval(sprintf('!ps2pdf %s.ps',filename)); %eval(sprintf('!ghostview %s.ps &',filename)); files = {[filename '.aux'],[filename '.log'],[filename '.out'],[filename '.dvi'],[filename '.pdf']}; case 'html', case 'txt', end return; function vstr = defaultformat(val) global REPORT_OUTPUT_FMT if ischar(val), vstr = val; elseif iscellstr(val), vstr = char(val); elseif isempty(val), vstr = ''; elseif isnumeric(val), if val==round(val), fmt = '%d'; else fmt = '%.3g'; end if abs(val)<=eps, vstr = '0'; else vstr = sprintf(fmt,val); end elseif isstruct(val) & isfield(val,'values') & isfield(val,'headers'), % a table vstr = joinstr(inserttable(val,0),'\n'); if any(strcmp(REPORT_OUTPUT_FMT,{'ps','pdf'})), vstr= inserttominipage(vstr); end else vstr = ''; fprintf(1,'defaultformat unable to handle input\n'); whos val end return; %% report elements (list, table, image, link) function str = fmtline(str) % replace some formatting elements depeding on output format global REPORT_OUTPUT_FMT if isempty(str), str = ''; return; end switch REPORT_OUTPUT_FMT, case {'ps','pdf'}, str = strrep(str,'<B>', '{\bf '); str = strrep(str,'<I>', '{\em '); str = strrep(str,'<TT>', '{\tt '); str = strrep(str,'</B>', '}'); str = strrep(str,'</I>', '}'); str = strrep(str,'</TT>','}'); str = strrep(str,'#','\#'); str = strrep(str,'%','\%'); case 'html', % nil case 'txt', str = strrep(str,'<B>', '*'); str = strrep(str,'<I>', '*'); str = strrep(str,'<TT>', ''); str = strrep(str,'</B>', '*'); str = strrep(str,'</I>', '*'); str = strrep(str,'</TT>',''); end return; function cs = insertbreak global REPORT_OUTPUT_FMT cs = cell(0); switch REPORT_OUTPUT_FMT case {'ps','pdf'}, cs{end+1} = ''; case 'html', cs{end+1} = '<P>'; case 'txt', cs{end+1} = ''; end return; function insertlist(list,enum) % make list global REPORT_OUTPUT_FMT if nargin<2, enum = 0; end cs = cell(0); switch REPORT_OUTPUT_FMT case {'ps','pdf'}, if enum, tag = 'enumerate'; else tag = 'itemize'; end starttag = ['\begin{' tag '}']; listtag = '\item '; endtag = ['\end{' tag '}']; case 'html', if enum, tag = 'OL'; else tag = 'UL'; end starttag = ['<' tag '>']; listtag = '<LI>'; endtag = ['</' tag '>']; case 'txt', starttag = ''; listtag = '- '; endtag = ''; end cs{end+1} = starttag; for i=1:length(list), cs{end+1} = sprintf('%s %s',listtag,list{i}); end cs{end+1} = endtag; return; function csout = tablerow(cs,emp,span) % construct one table row global REPORT_OUTPUT_FMT if nargin<2 | isempty(emp), emp = 'none'; end if nargin<3 | isempty(span), span = ones(length(cs),2); end rowspan = span(:,1); colspan = span(:,2); switch emp, case 'bold', emp1 = '<B>'; emp2 = '</B>'; case 'italic', emp1 = '<I>'; emp2 = '</I>'; case 'fixed', emp1 = '<TT>'; emp2 = '</TT>'; case 'none', emp1 = ''; emp2 = ''; case 'header', emp1 = ''; emp2 = ''; tag = 'TH'; end csout = cell(0); switch REPORT_OUTPUT_FMT, case {'pdf','ps'}, %switch emp, % case 'bold', emp1 = '{\bf '; emp2 = '}'; % case 'italic', emp1 = '{\em '; emp2 = '}'; % case 'fixed', emp1 = '{\tt '; emp2 = '}'; % case 'none', emp1 = ''; emp2 = ''; %end s0 = ''; for i=1:length(cs), if rowspan(i) & colspan(i), sp1 = ''; sp2 = ''; if colspan(i)>1, sp1 = [sp1 ' \multicolumn{' num2str(colspan(i)) '}{|c|}{']; sp2 = [sp2 '}']; end if rowspan(i)>1, sp1 = [sp1 ' \multirow{' num2str(rowspan(i)) '}{2cm}{']; sp2 = [sp2 '}']; end s = s0; content = cellstr(defaultformat(cs{i})); csout{end+1} = [s sp1 emp1 content{1}]; for j=2:length(content), csout{end+1} = content{j}; end csout{end} = [csout{end} emp2 sp2]; s0 = ' & '; end end csout{end} = [csout{end} ' \\']; case 'html', tag = 'TD'; csout{end+1} = '<TR>'; for i=1:length(cs), if rowspan(i) & colspan(i), sp = ''; if rowspan(i)>1, sp = [sp ' ROWSPAN=' num2str(rowspan(i))]; end if colspan(i)>1, sp = [sp ' COLSPAN=' num2str(colspan(i))]; end s = sprintf('<%s%s>%s',tag,sp,emp1); content = cellstr(defaultformat(cs{i})); csout{end+1} = [s content{1}]; for j=2:length(content), csout{end+1} = content{j}; end csout{end} = [csout{end} emp2 '</' tag '>']; end end csout{end+1} = '</TR>'; case 'txt', for i=1:length(cs), csout{end+1} = defaultformat(cs{i}); end end return; function cs = inserttable(sTable,rowlines,long) % put table contents to cellstr global REPORT_OUTPUT_FMT if nargin<2, rowlines = 1; end if nargin<3, long = 0; end [rows cols] = size(sTable.values); cs = cell(0); if isempty(sTable.colfmt), cf = 'c'; sTable.colfmt = cf(ones(1,cols)); end if isempty(sTable.span), sTable.span = ones([rows cols 2]); end switch REPORT_OUTPUT_FMT case {'ps','pdf','tex','latex'} li1 = ' \hline'; if rowlines>0, li2 = li1; li3 = li1; elseif rowlines==0, li2 = ''; li3 = li1; else li1 = ''; li2 = ''; li3 = ''; end if long, tbl = 'longtable'; else tbl = 'tabular'; end cs{end+1} = ['\begin{' tbl '}{' sTable.colfmt '}' li1]; if ~isempty(sTable.headers), row = tablerow(sTable.headers,'bold'); for i=1:length(row), cs{end+1} = row{i}; end cs{end} = [cs{end} li1 li2]; end for i=1:rows, row = tablerow(sTable.values(i,:),'',squeeze(sTable.span(i,:,:))); for i=1:length(row), cs{end+1} = row{i}; end cs{end} = [cs{end} li2]; end if ~rowlines, cs{end} = [cs{end} li3]; end cs{end+1} = ['\end{' tbl '}']; case 'html' cs{end+1} = ['<TABLE BORDER=' num2str(rowlines>0) '>']; if ~isempty(sTable.headers), row = tablerow(sTable.headers,'header'); for i=1:length(row), cs{end+1} = row{i}; end end for i=1:rows, row = tablerow(sTable.values(i,:),'',squeeze(sTable.span(i,:,:))); for i=1:length(row), cs{end+1} = row{i}; end end cs{end+1} = '</TABLE>'; case 'txt' cT = [sTable.headers(:)'; sTable.values]; A = cell2char(cT); for i=1:size(A,1), cs{end+1} = A(i,:); end end return; function A = cell2char(T) [nrow,ncol] = size(T); rowsep = 0; colsep = 1; % change to strings for i=1:nrow, for j=1:ncol, t = T{i,j}; if ischar(t), % ok elseif isempty(t), T{i,j} = ''; elseif isstruct(t), % ?? elseif iscell(t), T{i,j} = cell2char(t); elseif isnumeric(t), T{i,j} = num2str(t,3); end end end % widths of columns and heights of rows HW = ones(nrow,ncol,2); for i=1:nrow, for j=1:ncol, HW(i,j,:) = size(T{i,j}); end, end colw = max(HW(:,:,2),[],1); rowh = max(HW(:,:,1),[],2); % the table itself A = char(32*ones(sum(rowh)+rowsep*(nrow-1),sum(colw)+colsep*(ncol-1))); for i=1:nrow, for j=1:ncol, i0 = (i-1)*rowsep+sum(rowh(1:i-1)); j0 = (j-1)*colsep+sum(colw(1:j-1)); S = char(32*ones(rowh(i),colw(j))); si = size(T{i,j}); S(1:si(1),1:si(2)) = T{i,j}; A(i0+[1:rowh(i)],j0+[1:colw(j)]) = S; end end return; function s = inserttominipage(s,width) if nargin<2 | isempty(width) | isnan(width), width = 1; end width = ['{' num2str(width) '\columnwidth}']; mp1 = '\begin{minipage}[t]'; mp2 = '\end{minipage}'; if size(s,1)==1, s = [mp1 width s mp2]; else s = char({[mp1 width]; s; mp2}); end return; function cs = insertfigure(fname,boxsize,inminipage) global REPORT_OUTPUT_FMT if nargin<2, boxsize = [NaN 1]; end if nargin<3, inminipage = 0; end htmlpagewidth = 800; si = cell(0); switch REPORT_OUTPUT_FMT, case {'ps','pdf'}, if ~isnan(boxsize(1)), si{end+1} = ['height=' num2str(boxsize(1)) '\textheight']; end if ~isnan(boxsize(2)), si{end+1} = ['width=' num2str(boxsize(2)) '\columnwidth']; end if length(si), si = [', ' joinstr(si, ', ', ', ')]; end case 'html', if ~isnan(boxsize(1)), si{end+1} = ['HEIGHT=' num2str(htmlpagewidth*boxsize(1))]; end if ~isnan(boxsize(2)), si{end+1} = ['WIDTH=' num2str(htmlpagewidth*boxsize(2))]; end if length(si), si = [' ' joinstr(si, ' ', ' ')]; end case 'txt', % nil end switch REPORT_OUTPUT_FMT, case 'ps', s = ['\epsfig{file=./' fname '.ps ' si '}']; case 'pdf', s = ['\includegraphics[' si ']{./' fname '.pdf}']; case 'html', fn = [fname '.' fmt2imgfmt]; s = ['<IMG SRC="' fn '" ALIGN="center" ALT="' fname '"' si '>']; s = makelinkfrom(fn,s); case 'txt', s = ['[image:' fname ']']; end switch REPORT_OUTPUT_FMT, case {'ps','pdf'}, if inminipage, s = inserttominipage(s,boxsize(2)); end case 'html', s = ['<CENTER>' s '</CENTER>']; case 'txt', % nil end cs = {s}; return; function str = makelinkfrom(linkto,anchor) global REPORT_OUTPUT_FMT if iscell(linkto), if strcmp(REPORT_OUTPUT_FMT,'html'), linkto = joinstr(linkto,'','#'); else linkto = joinstr(linkto,'',''); end end switch REPORT_OUTPUT_FMT, case 'pdf', str = ['\hyperlink{' linkto '}{' anchor '}']; case 'ps', str = [anchor ' (p.\pageref{' linkto '})']; case 'html', str = ['<a href="' linkto '">' anchor '</a>']; case 'txt', str = ''; end return; function str = makelinkto(linkname) global REPORT_OUTPUT_FMT switch REPORT_OUTPUT_FMT, case 'pdf', fmt = '\pdfdest name {%s} fit \pdfoutline goto name {%s} {%s}'; str = sprintf(fmt,linkname,linkname,linkname); case 'ps', str = ['\label{' linkname '}']; case 'html', str = ['<a name="' linkname '"> </a>']; case 'txt', str = ''; end return;
github
martinarielhartmann/mirtooloct-master
som_vs2to1.m
.m
mirtooloct-master/somtoolbox/som_vs2to1.m
8,359
utf_8
7ae2b5258b2e375dd754f63d956a5dcd
function sS = som_vs2to1(sS) %SOM_VS2TO1 Convert version 2 struct to version 1. % % sSold = som_vs2to1(sSnew) % % sMold = som_vs2to1(sMnew); % sDold = som_vs2to1(sDnew); % % Input and output arguments: % sSnew (struct) a SOM Toolbox version 2 struct % sSold (struct) a SOM Toolbox version 1 struct % % For more help, try 'type som_vs2to1' or check out online documentation. % See also SOM_SET, SOM_VS1TO2. %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_vs2to1 % % PURPOSE % % Converts SOM Toolbox version 2 structs to version 1 structs. % % SYNTAX % % sS1 = som_vs2to1(sS2) % % DESCRIPTION % % This function is offered to allow the change of new map and data structs % to old ones. There are quite a lot of changes between the versions, % especially in the map struct, and this function makes it possible to % use the old functions with new structs. % % Note that part of the information is lost in the conversion. Especially, % training history is lost, and the normalization is, except in the simplest % cases (like all have 'range' or 'var' normalization) screwed up. % % REQUIRED INPUT ARGUMENTS % % sS2 (struct) som SOM Toolbox version 2.0 struct (map, data, % training or normalization struct) % % OUTPUT ARGUMENTS % % sS1 (struct) the corresponding SOM Toolbox version 2.0 struct % % EXAMPLES % % sM = som_vs2to1(sMnew); % sD = som_vs2to1(sDnew); % sT = som_vs2to1(sMnew.trainhist(1)); % % SEE ALSO % % som_set Set values and create SOM Toolbox structs. % som_vs1to2 Transform structs from 1.0 version to 2.0. % Copyright (c) 1999-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 101199 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% check arguments error(nargchk(1, 1, nargin)); % check no. of input arguments is correct %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% set field values switch sS.type, case 'som_map', msize = sS.topol.msize; [munits dim] = size(sS.codebook); % topology if strcmp(sS.topol.shape,'sheet'), shape = 'rect'; else shape = sS.shape; end % labels labels = cell(munits,1); nl = size(sS.labels,2); for i=1:munits, labels{i} = cell(nl,1); for j=1:nl, labels{i}{j} = sS.labels{i,j}; end end % trainhist tl = length(sS.trainhist); if tl==0 | strcmp(sS.trainhist(1).algorithm,'lininit'), init_type = 'linear'; else init_type = 'random'; end if tl>1, for i=2:tl, train_seq{i-1} = som_vs2to1(sS.trainhist(i)); end train_type = sS.trainhist(tl).algorithm; else train_seq = []; train_type = 'batch'; end if tl>0, data_name = sS.trainhist(tl).data_name; else data_name = ''; end % component normalizations sN = convert_normalizations(sS.comp_norm); if strcmp(sN.name,'som_hist_norm'), sS.codebook = redo_hist_norm(sS.codebook,sS.comp_norm,sN); end % map sSnew = struct('init_type', 'linear', 'train_type', 'batch', 'lattice' ,... 'hexa', 'shape', 'rect', 'neigh', 'gaussian', 'msize', msize, ... 'train_sequence', [], 'codebook', [], 'labels', [], ... 'mask', [], 'data_name', 'unnamed', 'normalization', [], ... 'comp_names', [], 'name', 'unnamed'); sSnew.init_type = init_type; sSnew.train_type = train_type; sSnew.lattice = sS.topol.lattice; sSnew.shape = shape; sSnew.neigh = sS.neigh; sSnew.msize = sS.topol.msize; sSnew.train_sequence = train_seq; sSnew.codebook = reshape(sS.codebook,[sS.topol.msize dim]); sSnew.labels = labels; sSnew.mask = sS.mask; sSnew.data_name = data_name; sSnew.normalization = sN; sSnew.comp_names = sS.comp_names; sSnew.name = sS.name; case 'som_data', [dlen dim] = size(sS.data); % component normalizations sN = convert_normalizations(sS.comp_norm); if strcmp(sN.name,'som_hist_norm'), sS.codebook = redo_hist_norm(sS.codebook,sS.comp_norm,sN); end % data sSnew = struct('data', [], 'name', '', 'labels' , [], 'comp_names', ... [], 'normalization', []); sSnew.data = sS.data; sSnew.name = sS.name; sSnew.labels = sS.labels; sSnew.comp_names = sS.comp_names; sSnew.normalization = sN; case 'som_norm', sSnew = struct('name','som_var_norm','inv_params',[]); switch sS.method, case 'var', sSnew.name = 'som_var_norm'; case 'range', sSnew.name = 'som_lin_norm'; case 'histD', sSnew.name = 'som_hist_norm'; otherwise, warning(['Method ' method ' does not exist in version 1.']) end if strcmp(sS.status,'done'), switch sS.method, case 'var', sSnew.inv_params = zeros(2,1); sSnew.inv_params(1) = sS.params(1); sSnew.inv_params(2) = sS.params(2); case 'range', sSnew.inv_params = zeros(2,1); sSnew.inv_params(1) = sS.params(1); sSnew.inv_params(2) = sS.params(2) + sS.params(1);; case 'histD', bins = length(sS.params); sSnew.inv_params = zeros(bins+1,1) + Inf; sSnew.inv_params(1:bins,i) = sS.params; sSnew.inv_params(end,i) = bins; end end case 'som_train', sSnew = struct('algorithm', sS.algorithm, 'radius_ini', ... sS.radius_ini, 'radius_fin', sS.radius_fin, 'alpha_ini', ... sS.alpha_ini, 'alpha_type', sS.alpha_type, 'trainlen', sS.trainlen, ... 'qerror', NaN, 'time', sS.time); case 'som_topol', disp('Version 1 of SOM Toolbox did not have topology structure.\n'); otherwise, error('Unrecognized struct.'); end sS = sSnew; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function sN = convert_normalizations(cnorm) dim = length(cnorm); sN = struct('name','som_var_norm','inv_params',[]); % check that there is exactly one normalization per component % and that their status and method is the same ok = 1; nof = zeros(dim,1); for i=1:dim, nof(i) = length(cnorm{i}); end if any(nof>1), ok=0; elseif any(nof==1) & any(nof==0), ok=0; elseif any(nof>0), status = cnorm{1}.status; method = cnorm{1}.method; for i=2:dim, if ~strcmp(cnorm{i}.status,status) | ~strcmp(cnorm{i}.method,method), ok = 0; end end elseif all(nof==0), return; end if ~ok, warning(['Normalization could not be converted. All variables can' ... ' only be normalized with a single, and same, method.']); return; end % method name switch method, case 'var', sN.name = 'som_var_norm'; case 'range', sN.name = 'som_lin_norm'; case 'histD', sN.name = 'som_hist_norm'; otherwise, warning(['Normalization could not be converted. Method ' method ... 'does not exist in version 1.']); return; end % if not done, inv_params is empty if ~strcmp(status,'done'), return; end % ok, make the conversion switch method, case 'var', sN.inv_params = zeros(2,dim); for i=1:dim, sN.inv_params(1,i) = cnorm{i}.params(1); sN.inv_params(2,i) = cnorm{i}.params(2); end case 'range', sN.inv_params = zeros(2,dim); for i=1:dim, sN.inv_params(1,i) = cnorm{i}.params(1); sN.inv_params(2,i) = cnorm{i}.params(2) + cnorm{i}.params(1); end case 'histD', bins = zeros(dim,1); for i=1:dim, bins(i) = length(cnorm{i}.params); end m = max(bins); sN.inv_params = zeros(m+1,dim) + Inf; for i=1:dim, sN.inv_params(1:bins(i),i) = cnorm{i}.params; if bins(i)<m, sN.inv_params(bins(i)+1,i) = NaN; end sN.inv_params(end,i) = bins(i); end end function D = redo_hist_norm(D,cnorm,sN) dim = size(D,2); % first - undo the new way for i=1:dim, bins = length(cnorm{i}.params); D(:,i) = round(D(:,i)*(bins-1)+1); inds = find(~isnan(D(:,i)) & ~isinf(D(:,i))); D(inds,i) = cnorm{i}.params(D(inds,i)); end % then - redo the old way n_bins = sN.inv_params(size(sN.inv_params,1),:); for j = 1:dim, for i = 1:size(D, 1) if ~isnan(D(i, j)), [d ind] = min(abs(D(i, j) - sN.inv_params(1:n_bins(j), j))); if (D(i, j) - sN.inv_params(ind, j)) > 0 & ind < n_bins(j), D(i, j) = ind + 1; else D(i, j) = ind; end end end end D = D * sparse(diag(1 ./ n_bins));
github
martinarielhartmann/mirtooloct-master
som_dendrogram.m
.m
mirtooloct-master/somtoolbox/som_dendrogram.m
9,039
utf_8
43f32770e95d19d4a12855bd8bfb91f3
function [h,Coord,Color,height] = som_dendrogram(Z,varargin) %SOM_DENDROGRAM Visualize a dendrogram. % % [h,Coord,Color,height] = som_dendrogram(Z, [[argID,] value, ...]) % % Z = som_linkage(sM); % som_dendrogram(Z); % som_dendrogram(Z,sM); % som_dendrogram(Z,'coord',co); % % Input and output arguments ([]'s are optional): % h (vector) handle to the arc lines % Z (matrix) size n-1 x 1, the hierarchical cluster matrix % returned by functions like LINKAGE and SOM_LINKAGE % n is the number of original data samples. % [argID, (string) See below. The values which are unambiguous can % value] (varies) be given without the preceeding argID. % Coord (matrix) size 2*n-1 x {1,2}, the coordinates of the % original data samples and cluster nodes used % in the visualization % Color (matrix) size 2*n-1 x 3, the colors of ... % height (vector) size 2*n-1 x 1, the heights of ... % % Here are the valid argument IDs and corresponding values. The values % which are unambiguous (marked with '*') can be given without the % preceeding argID. % 'data' *(struct) map or data struct: many other optional % arguments require this % (matrix) data matrix % 'coord' (matrix) size n x 1 or n x 2, the coordinates of % the original data samples either in 1D or 2D % (matrix) size 2*n-1 x {1,2}, the coordinates of both % original data samples and each cluster % *(string) 'SOM', 'pca#', 'sammon#', or 'cca#': the coordinates % are calculated using the given data and the % required projection algorithm. The '#' at the % end of projection algorithms refers to the % desired output dimension and can be either 1 or 2 % (2 by default). In case of 'SOM', the unit % coordinates (given by SOM_VIS_COORDS) are used. % 'color' (matrix) size n x 3, the color of the original data samples % (matrix) size 2*n-1 x 3, the colors of both original % data samples and each cluster % (string) color specification, e.g. 'r.', used for each node % 'height' (vector) size n-1 x 1, the heights used for each cluster % (vector) size 2*n-1 x 1, the heights used for both original % data samples and each cluster % *(string) 'order', the order of combination determines height % 'depth', the depth at which the combination % happens determines height % 'linecolor' (string) color specification for the arc color, 'k' by default % (vector) size 1 x 3 % % See also SOM_LINKAGE, DENDROGRAM. % Copyright (c) 2000 by Juha Vesanto % Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 160600 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% read the arguments % Z nd = size(Z,1)+1; nc = size(Z,1); % varargin Coordtype = 'natural'; Coord = []; codim = 1; Colortype = 'none'; Color = []; height = [zeros(nd,1); Z(:,3)]; M = []; linecol = 'k'; i=1; while i<=length(varargin), argok = 1; if ischar(varargin{i}), switch varargin{i}, case 'data', i = i + 1; M = varargin{i}; case 'coord', i=i+1; if isnumeric(varargin{i}), Coord = varargin{i}; Coordtype = 'given'; else if strcmp(varargin{i},'SOM'), Coordtype = 'SOM'; else Coordtype = 'projection'; Coord = varargin{i}; end end case 'color', i=i+1; if isempty(varargin{i}), Colortype = 'none'; elseif ischar(varargin{i}), Colortype = 'colorspec'; Color = varargin{i}; else Colortype = 'given'; Color = varargin{i}; end case 'height', i=i+1; height = varargin{i}; case 'linecolor', i=i+1; linecol = varargin{i}; case 'SOM', Coordtype = 'SOM'; case {'pca','pca1','pca2','sammon','sammon1','sammon2','cca','cca1','cca2'}, Coordtype = 'projection'; Coord = varargin{i}; case {'order','depth'}, height = varargin{i}; end elseif isstruct(varargin{i}), M = varargin{i}; else argok = 0; end if ~argok, disp(['(som_dendrogram) Ignoring invalid argument #' num2str(i+1)]); end i = i+1; end switch Coordtype, case 'SOM', if isempty(M) | ~any(strcmp(M.type,{'som_map','som_topol'})) , error('Cannot determine SOM coordinates without a SOM.'); end if strcmp(M.type,'som_map'), M = M.topol; end case 'projection', if isempty(M), error('Cannot do projection without the data.'); end if isstruct(M), if strcmp(M.type,'som_data'), M = M.data; elseif strcmp(M.type,'som_map'), M = M.codebook; end end if size(M,1) ~= nd, error('Given data must be equal in length to the number of original data samples.') end case 'given', if size(Coord,1) ~= nd & size(Coord,1) ~= nd+nc, error('Size of given coordinate matrix does not match the cluster hierarchy.'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% initialization % Coordinates switch Coordtype, case 'natural', o = leavesorder(Z)'; [dummy,Coord] = sort(o); codim = 1; case 'SOM', Coord = som_vis_coords(M.lattice,M.msize); codim = 2; case 'projection', switch Coord, case {'pca','pca2'}, Coord = pcaproj(M,2); codim = 2; case 'pca1', Coord = pcaproj(M,1); codim = 1; case {'cca','cca2'}, Coord = cca(M,2,20); codim = 2; case 'cca1', Coord = cca(M,1,20); codim = 1; case {'sammon','sammon2'}, Coord = sammon(M,2,50); codim = 2; case 'sammon1', Coord = sammon(M,1,50); codim = 1; end case 'given', codim = min(size(Coord,2),2); % nill end if size(Coord,1) == nd, Coord = [Coord; zeros(nc,size(Coord,2))]; for i=(nd+1):(nd+nc), leaves = leafnodes(Z,i,nd); if any(leaves), Coord(i,:) = mean(Coord(leaves,:),1); else Coord(i,:) = Inf; end end end % Colors switch Colortype, case 'colorspec', % nill case 'none', Color = ''; case 'given', if size(Color,1) == nd, Color = [Color; zeros(nc,3)]; for i=(nd+1):(nd+nc), leaves = leafnodes(Z,i,nd); if any(leaves), Color(i,:) = mean(Color(leaves,:),1); else Color(i,:) = 0.8; end end end end % height if ischar(height), switch height, case 'order', height = [zeros(nd,1); [1:nc]']; case 'depth', height = nodedepth(Z); height = max(height) - height; end else if length(height)==nc, height = [zeros(nd,1); height]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% draw % the arcs lfrom = []; lto = []; for i=1:nd+nc, if i<=nd, ch = []; elseif ~isfinite(Z(i-nd,3)), ch = []; else ch = Z(i-nd,1:2)'; end if any(ch), lfrom = [lfrom; i*ones(length(ch),1)]; lto = [lto; ch]; end end % the coordinates of the arcs if codim == 1, Lx = [Coord(lfrom), Coord(lto), Coord(lto)]; Ly = [height(lfrom), height(lfrom), height(lto)]; Lz = []; else Lx = [Coord(lfrom,1), Coord(lto,1), Coord(lto,1)]; Ly = [Coord(lfrom,2), Coord(lto,2), Coord(lto,2)]; Lz = [height(lfrom), height(lfrom), height(lto)]; end washold = ishold; if ~washold, cla; end % plot the lines if isempty(Lz), h = line(Lx',Ly','color',linecol); else h = line(Lx',Ly',Lz','color',linecol); if ~washold, view(3); end rotate3d on end % plot the nodes hold on switch Colortype, case 'none', % nill case 'colorspec', if codim == 1, plot(Coord,height,Color); else plot3(Coord(:,1), Coord(:,2), height, Color); end case 'given', som_grid('rect',[nd+nc 1],'line','none','Coord',[Coord, height],... 'Markersize',10,'Markercolor',Color); end if ~washold, hold off, end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function depth = nodedepth(Z) nd = size(Z,1)+1; nc = size(Z,1); depth = zeros(nd+nc,1); ch = nc+nd-1; while any(ch), c = ch(1); ch = ch(2:end); if c>nd & isfinite(Z(c-nd,3)), chc = Z(c-nd,1:2); depth(chc) = depth(c) + 1; ch = [ch, chc]; end end return; function inds = leafnodes(Z,i,nd) inds = []; ch = i; while any(ch), c = ch(1); ch = ch(2:end); if c>nd & isfinite(Z(c-nd,3)), ch = [ch, Z(c-nd,1:2)]; end if c<=nd, inds(end+1) = c; end end return; function order = leavesorder(Z) nd = size(Z,1)+1; order = 2*nd-1; nonleaves = 1; while any(nonleaves), j = nonleaves(1); ch = Z(order(j)-nd,1:2); if j==1, oleft = []; else oleft = order(1:(j-1)); end if j==length(order), oright = []; else oright = order((j+1):length(order)); end order = [oleft, ch, oright]; nonleaves = find(order>nd); end return;
github
martinarielhartmann/mirtooloct-master
som_plotplane.m
.m
mirtooloct-master/somtoolbox/som_plotplane.m
8,877
utf_8
afada5a6c93a0270c32acbd532af0679
function h=som_plotplane(varargin) %SOM_PLOTPLANE Visualize the map prototype vectors as line graphs % % h=som_plotplane(lattice, msize, data, [color], [scaling], [pos]) % h=som_plotplane(topol, data, [color], [scaling], [pos]) % % som_plotplane('hexa',[5 5], rand(25,4), jet(25)) % som_plotplane(sM, sM.codebook) % % Input and output arguments ([]'s are optional) % lattice (string) grid 'hexa' or 'rect' % msize (vector) size 1x2, defines the grid size % (matrix) size Mx2, defines explicit coordinates: in % this case the first argument does not matter % topol (struct) map or topology struct % data (matrix) Mxd matrix, M=prod(msize) % [color] (matrix) size Mx3, gives an individual color for each graph % (string) ColorSpec gives the same color for each % graph, default is 'k' (black) % [scaling] (string) 'on' or 'off', default is 'on' % [pos] (vector) 1x2 vector that determines translation. % Default is no translation. % % h (vector) the object handles for the LINE objects % % If scaling is set on, the data will be linearly scaled in each % unit so that min and max values span from lower to upper edge % in each unit. If scaling is 'off', the proper scaling is left to % the user: values in range [-.5,.5] will be plotted within the limits of the % unit while values exceeding this range will be out of the unit. % Axis are set as in SOM_CPLANE. % % For more help, try 'type som_plotplane' or check out online documentation. % See also SOM_PLANE, SOM_PIEPLANE, SOM_BARPLANE %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_plotplane % % PURPOSE % % Visualizes the map prototype vectors as line graph % % SYNTAX % % h = som_plotplane(topol, data) % h = som_plotplane(lattice, msize, data) % h = som_plotplane(..., color) % h = som_plotplane(..., color, scaling) % h = som_plotplane(..., color, scaling, pos) % % DESCRIPTION % % Visualizes the map prototype vectors as line graph % % KNOWN BUGS % % It is not possible to specify explicit coordinates for map % consistig of just one unit as then the msize is interpreted as % map size. % % FEATURES % % - the colors are fixed: changing colormap in the figure (see % COLORMAP) will not affect the coloring of the plots % % REQUIRED INPUT ARGUMENTS % % lattice The basic topology % % (string) 'hexa' or 'rect' positions the plots according to hexagonal or % rectangular map lattice. % % msize The size of the map grid % % (vector) [n1 n2] vector defines the map size (height n1 units, width n2 % units, total M=n1 x n2 units). The units will be placed to their % topological locations in order to form a uniform hexagonal or % rectangular grid. % (matrix) Mx2 matrix defines arbitary coordinates for the M units. % In this case the argument 'lattice' has no effect. % % topol Topology of the map grid % % (struct) map or topology struct from which the topology is taken % % data The data to be visualized % % (matrix) Mxd matrix of data vectors. % % OPTIONAL INPUT ARGUMENTS % % If unspecified or given empty values ('' or []), default values % will be used for optional input arguments. % % color The color of the plots % % (string) Matlab's ColorSpec (see help plot) string gives the same color % for each line. % % (matrix) Mx3 matrix assigns an RGB color determined by the Nth row of % the matrix to the Nth plot. % % (vector) 1x3 RGB vector gives the same color for each line. % % scaling The data scaling mode % % (string) 'on or 'off': if scaling is set on, the data will be % linearly scaled in each unit so that min and max values span from % lower to upper edge in each unit. If scaling is 'off', the proper % scaling is left to the user: values in range [-.5,.5] will be plotted % within the limits of the unit while values exceeding this % range will be out of the unit. % % pos Position of the origin % % (vector) This is meant for drawing the plane in arbitary location in a % figure. Note the operation: if this argument is given, the % axis limits setting part in the routine is skipped and the limits % setting will be left to be done by MATLAB's % defaults. By default no translation is done. % % OUTPUT ARGUMENTS % % h (scalar) Handle to the created patch object % % OBJECT TAG % % Object property 'Tag' is set to 'planePlot'. % % EXAMPLES % % %%% Create the data and make a map % % data=rand(1000,20); map=som_make(data); % % %%% Create a 'gray' colormap that has 64 levels % % color_map=gray(64); % % %%% Draw plots using red color % % som_plotplane(map, map.codebook,'r'); % % %%% Calculate hits on the map and calculate colors so that % black = min. number of hits and white = max. number of hits % % hit=som_hits(map,data); color=som_normcolor(hit(:),color_map); % % %%% Draw plots again. Now the gray level indicates the number of hits to % each node % % som_plotplane(map, map.codebook, color); % % SEE ALSO % % som_cplane Visualize a 2D component plane, u-matrix or color plane % som_barplane Visualize the map prototype vectors as bar diagrams. % som_pieplane Visualize the map prototype vectors as pie charts % Copyright (c) 1999-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta Johan 160799 juuso 151199 070600 %%% Init & Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [nargin, lattice, msize, data, color, scaling, pos] = vis_planeGetArgs(varargin{:}); error(nargchk(3, 5, nargin)); % check no. of input args is correct s=0.8; % size of plot if nargin < 6 | isempty(pos) pos=NaN; end if nargin < 5 | isempty(scaling) scaling='on'; elseif ~vis_valuetype(scaling,{'string'}) | ... ~any(strcmp(scaling,{'on','off'})), error('Scaling should be string ''on'' or ''off''.'); end l=size(data,2); if ~isnumeric(msize) | ndims(msize) ~= 2 | size(msize,2)~=2, error('msize has to be 1x2 grid size vector or a Nx2 coordinate matrix.'); elseif size(msize,1) == 1, xdim=msize(2); ydim=msize(1); N=xdim*ydim; y=repmat(repmat([1:ydim]',xdim,1),1,l); x=reshape(repmat([1:xdim],ydim*l,1),l,N)'; else x=repmat(msize(:,1),1,l);y=repmat(msize(:,2),1,l); N=size(msize,1); lattice='rect'; if isnan(pos), pos=[0 0]; end end switch lattice case {'hexa', 'rect'} ; otherwise error(['Lattice' lattice ' not implemented!']); end if ~isnumeric(data) | size(data,1) ~= N error('Data matrix is invalid or has wrong size!'); end if nargin < 4 | isempty(color), color='k'; elseif vis_valuetype(color, {'colorstyle',[N 3]}), if ischar(color) & strcmp(color,'none'), error('Colorstyle ''none'' not allowed in som_plotplane.'); end elseif vis_valuetype(color,{'1x3rgb'}) ; elseif ~vis_valuetype(color,{'nx3rgb',[N 3]},'all'), error('The color matrix has wrong size or contains invalid RGB values or colorstyle.'); end [linesx, linesy]=vis_line(data,scaling); %%%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Making the lattice. % Command view([0 90]) shows the map in 2D properly oriented switch lattice case 'hexa' t=find(rem(y(:,1),2)); % move even rows by .5 x(t,:)=x(t,:)-.5; x=(x./s+linesx).*s+.5; y=(y./s+linesy).*s; % scale with s case 'rect' x=(x./s+linesx).*s; y=(y./s+linesy).*s; % scale with s end %% Draw the map! ... h_=plot(x',y'); if size(color,1) == 1 set(h_,'Color',color); else for i=1:N, set(h_(i,:),'Color',color(i,:)); end end if ~isnan(pos) x=x+pos(1);y=y+pos(2); % move upper left corner end % to pos(1),pos(2) %% Set axes properties ax=gca; vis_PlaneAxisProperties(ax, lattice, msize, pos); %%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% set(h_,'Tag','planePlot'); % tag the lineobject if nargout>0, h=h_; end % Set h only, % if there really is output %% Subfuntion %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [x,y]=vis_line(data, scaling) s=size(data); % normalization between [0,1] if scaling is on if strcmp(scaling,'on') mn=repmat(min(data,[],2),1,s(2)); mx=repmat(max(data,[],2),1,s(2)); y=-((data-mn)./(mx-mn))+.5; else % -sign is beacuse we do axis ij y=-data; end x=repmat(linspace(-.5, .5, size(data,2)), size(data,1),1);
github
martinarielhartmann/mirtooloct-master
som_seqtrain.m
.m
mirtooloct-master/somtoolbox/som_seqtrain.m
20,925
utf_8
10804404d112d52c0bf9538861655c63
function [sMap, sTrain] = som_seqtrain(sMap, D, varargin) %SOM_SEQTRAIN Use sequential algorithm to train the Self-Organizing Map. % % [sM,sT] = som_seqtrain(sM, D, [[argID,] value, ...]) % % sM = som_seqtrain(sM,D); % sM = som_seqtrain(sM,sD,'alpha_type','power','tracking',3); % [M,sT] = som_seqtrain(M,D,'ep','trainlen',10,'inv','hexa'); % % Input and output arguments ([]'s are optional): % sM (struct) map struct, the trained and updated map is returned % (matrix) codebook matrix of a self-organizing map % size munits x dim or msize(1) x ... x msize(k) x dim % The trained map codebook is returned. % D (struct) training data; data struct % (matrix) training data, size dlen x dim % [argID, (string) See below. The values which are unambiguous can % value] (varies) be given without the preceeding argID. % % sT (struct) learning parameters used during the training % % Here are the valid argument IDs and corresponding values. The values which % are unambiguous (marked with '*') can be given without the preceeding argID. % 'mask' (vector) BMU search mask, size dim x 1 % 'msize' (vector) map size % 'radius' (vector) neighborhood radiuses, length 1, 2 or trainlen % 'radius_ini' (scalar) initial training radius % 'radius_fin' (scalar) final training radius % 'alpha' (vector) learning rates, length trainlen % 'alpha_ini' (scalar) initial learning rate % 'tracking' (scalar) tracking level, 0-3 % 'trainlen' (scalar) training length % 'trainlen_type' *(string) is the given trainlen 'samples' or 'epochs' % 'train' *(struct) train struct, parameters for training % 'sTrain','som_train ' = 'train' % 'alpha_type' *(string) learning rate function, 'inv', 'linear' or 'power' % 'sample_order'*(string) order of samples: 'random' or 'ordered' % 'neigh' *(string) neighborhood function, 'gaussian', 'cutgauss', % 'ep' or 'bubble' % 'topol' *(struct) topology struct % 'som_topol','sTopo l' = 'topol' % 'lattice' *(string) map lattice, 'hexa' or 'rect' % 'shape' *(string) map shape, 'sheet', 'cyl' or 'toroid' % % For more help, try 'type som_seqtrain' or check out online documentation. % See also SOM_MAKE, SOM_BATCHTRAIN, SOM_TRAIN_STRUCT. %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_seqtrain % % PURPOSE % % Trains a Self-Organizing Map using the sequential algorithm. % % SYNTAX % % sM = som_seqtrain(sM,D); % sM = som_seqtrain(sM,sD); % sM = som_seqtrain(...,'argID',value,...); % sM = som_seqtrain(...,value,...); % [sM,sT] = som_seqtrain(M,D,...); % % DESCRIPTION % % Trains the given SOM (sM or M above) with the given training data % (sD or D) using sequential SOM training algorithm. If no optional % arguments (argID, value) are given, a default training is done, the % parameters are obtained from SOM_TRAIN_STRUCT function. Using % optional arguments the training parameters can be specified. Returns % the trained and updated SOM and a train struct which contains % information on the training. % % REFERENCES % % Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, % Berlin, 1995, pp. 78-82. % Kohonen, T., "Clustering, Taxonomy, and Topological Maps of % Patterns", International Conference on Pattern Recognition % (ICPR), 1982, pp. 114-128. % Kohonen, T., "Self-Organized formation of topologically correct % feature maps", Biological Cybernetics 43, 1982, pp. 59-69. % % REQUIRED INPUT ARGUMENTS % % sM The map to be trained. % (struct) map struct % (matrix) codebook matrix (field .data of map struct) % Size is either [munits dim], in which case the map grid % dimensions (msize) should be specified with optional arguments, % or [msize(1) ... msize(k) dim] in which case the map % grid dimensions are taken from the size of the matrix. % Lattice, by default, is 'rect' and shape 'sheet'. % D Training data. % (struct) data struct % (matrix) data matrix, size [dlen dim] % % OPTIONAL INPUT ARGUMENTS % % argID (string) Argument identifier string (see below). % value (varies) Value for the argument (see below). % % The optional arguments can be given as 'argID',value -pairs. If an % argument is given value multiple times, the last one is % used. The valid IDs and corresponding values are listed below. The values % which are unambiguous (marked with '*') can be given without the % preceeding argID. % % 'mask' (vector) BMU search mask, size dim x 1. Default is % the one in sM (field '.mask') or a vector of % ones if only a codebook matrix was given. % 'msize' (vector) map grid dimensions. Default is the one % in sM (field sM.topol.msize) or % 'si = size(sM); msize = si(1:end-1);' % if only a codebook matrix was given. % 'radius' (vector) neighborhood radius % length = 1: radius_ini = radius % length = 2: [radius_ini radius_fin] = radius % length > 2: the vector given neighborhood % radius for each step separately % trainlen = length(radius) % 'radius_ini' (scalar) initial training radius % 'radius_fin' (scalar) final training radius % 'alpha' (vector) learning rate % length = 1: alpha_ini = alpha % length > 1: the vector gives learning rate % for each step separately % trainlen is set to length(alpha) % alpha_type is set to 'user defined' % 'alpha_ini' (scalar) initial learning rate % 'tracking' (scalar) tracking level: 0, 1 (default), 2 or 3 % 0 - estimate time % 1 - track time and quantization error % 2 - plot quantization error % 3 - plot quantization error and two first % components % 'trainlen' (scalar) training length (see also 'tlen_type') % 'trainlen_type' *(string) is the trainlen argument given in 'epochs' % or in 'samples'. Default is 'epochs'. % 'sample_order'*(string) is the sample order 'random' (which is the % the default) or 'ordered' in which case % samples are taken in the order in which they % appear in the data set % 'train' *(struct) train struct, parameters for training. % Default parameters, unless specified, % are acquired using SOM_TRAIN_STRUCT (this % also applies for 'trainlen', 'alpha_type', % 'alpha_ini', 'radius_ini' and 'radius_fin'). % 'sTrain', 'som_train' (struct) = 'train' % 'neigh' *(string) The used neighborhood function. Default is % the one in sM (field '.neigh') or 'gaussian' % if only a codebook matrix was given. Other % possible values is 'cutgauss', 'ep' and 'bubble'. % 'topol' *(struct) topology of the map. Default is the one % in sM (field '.topol'). % 'sTopol', 'som_topol' (struct) = 'topol' % 'alpha_type'*(string) learning rate function, 'inv', 'linear' or 'power' % 'lattice' *(string) map lattice. Default is the one in sM % (field sM.topol.lattice) or 'rect' % if only a codebook matrix was given. % 'shape' *(string) map shape. Default is the one in sM % (field sM.topol.shape) or 'sheet' % if only a codebook matrix was given. % % OUTPUT ARGUMENTS % % sM the trained map % (struct) if a map struct was given as input argument, a % map struct is also returned. The current training % is added to the training history (sM.trainhist). % The 'neigh' and 'mask' fields of the map struct % are updated to match those of the training. % (matrix) if a matrix was given as input argument, a matrix % is also returned with the same size as the input % argument. % sT (struct) train struct; information of the accomplished training % % EXAMPLES % % Simplest case: % sM = som_seqtrain(sM,D); % sM = som_seqtrain(sM,sD); % % To change the tracking level, 'tracking' argument is specified: % sM = som_seqtrain(sM,D,'tracking',3); % % The change training parameters, the optional arguments 'train', % 'neigh','mask','trainlen','radius','radius_ini', 'radius_fin', % 'alpha', 'alpha_type' and 'alpha_ini' are used. % sM = som_seqtrain(sM,D,'neigh','cutgauss','trainlen',10,'radius_fin',0); % % Another way to specify training parameters is to create a train struct: % sTrain = som_train_struct(sM,'dlen',size(D,1),'algorithm','seq'); % sTrain = som_set(sTrain,'neigh','cutgauss'); % sM = som_seqtrain(sM,D,sTrain); % % By default the neighborhood radius goes linearly from radius_ini to % radius_fin. If you want to change this, you can use the 'radius' argument % to specify the neighborhood radius for each step separately: % sM = som_seqtrain(sM,D,'radius',[5 3 1 1 1 1 0.5 0.5 0.5]); % % By default the learning rate (alpha) goes from the alpha_ini to 0 % along the function defined by alpha_type. If you want to change this, % you can use the 'alpha' argument to specify the learning rate % for each step separately: % alpha = 0.2*(1 - log([1:100])); % sM = som_seqtrain(sM,D,'alpha',alpha); % % You don't necessarily have to use the map struct, but you can operate % directly with codebook matrices. However, in this case you have to % specify the topology of the map in the optional arguments. The % following commads are identical (M is originally a 200 x dim sized matrix): % M = som_seqtrain(M,D,'msize',[20 10],'lattice','hexa','shape','cyl'); % % M = som_seqtrain(M,D,'msize',[20 10],'hexa','cyl'); % % sT= som_set('som_topol','msize',[20 10],'lattice','hexa','shape','cyl'); % M = som_seqtrain(M,D,sT); % % M = reshape(M,[20 10 dim]); % M = som_seqtrain(M,D,'hexa','cyl'); % % The som_seqtrain also returns a train struct with information on the % accomplished training. This is the same one as is added to the end of the % trainhist field of map struct, in case a map struct is given. % [M,sTrain] = som_seqtrain(M,D,'msize',[20 10]); % % [sM,sTrain] = som_seqtrain(sM,D); % sM.trainhist{end}==sTrain % % SEE ALSO % % som_make Initialize and train a SOM using default parameters. % som_batchtrain Train SOM with batch algorithm. % som_train_struct Determine default training parameters. % Copyright (c) 1997-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 1.0beta juuso 220997 % Version 2.0beta juuso 101199 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Check arguments error(nargchk(2, Inf, nargin)); % check the number of input arguments % map struct_mode = isstruct(sMap); if struct_mode, sTopol = sMap.topol; else orig_size = size(sMap); if ndims(sMap) > 2, si = size(sMap); dim = si(end); msize = si(1:end-1); M = reshape(sMap,[prod(msize) dim]); else msize = [orig_size(1) 1]; dim = orig_size(2); end sMap = som_map_struct(dim,'msize',msize); sTopol = sMap.topol; end [munits dim] = size(sMap.codebook); % data if isstruct(D), data_name = D.name; D = D.data; else data_name = inputname(2); end D = D(find(sum(isnan(D),2) < dim),:); % remove empty vectors from the data [dlen ddim] = size(D); % check input dimension if dim ~= ddim, error('Map and data input space dimensions disagree.'); end % varargin sTrain = som_set('som_train','algorithm','seq','neigh', ... sMap.neigh,'mask',sMap.mask,'data_name',data_name); radius = []; alpha = []; tracking = 1; sample_order_type = 'random'; tlen_type = 'epochs'; i=1; while i<=length(varargin), argok = 1; if ischar(varargin{i}), switch varargin{i}, % argument IDs case 'msize', i=i+1; sTopol.msize = varargin{i}; case 'lattice', i=i+1; sTopol.lattice = varargin{i}; case 'shape', i=i+1; sTopol.shape = varargin{i}; case 'mask', i=i+1; sTrain.mask = varargin{i}; case 'neigh', i=i+1; sTrain.neigh = varargin{i}; case 'trainlen', i=i+1; sTrain.trainlen = varargin{i}; case 'trainlen_type', i=i+1; tlen_type = varargin{i}; case 'tracking', i=i+1; tracking = varargin{i}; case 'sample_order', i=i+1; sample_order_type = varargin{i}; case 'radius_ini', i=i+1; sTrain.radius_ini = varargin{i}; case 'radius_fin', i=i+1; sTrain.radius_fin = varargin{i}; case 'radius', i=i+1; l = length(varargin{i}); if l==1, sTrain.radius_ini = varargin{i}; else sTrain.radius_ini = varargin{i}(1); sTrain.radius_fin = varargin{i}(end); if l>2, radius = varargin{i}; tlen_type = 'samples'; end end case 'alpha_type', i=i+1; sTrain.alpha_type = varargin{i}; case 'alpha_ini', i=i+1; sTrain.alpha_ini = varargin{i}; case 'alpha', i=i+1; sTrain.alpha_ini = varargin{i}(1); if length(varargin{i})>1, alpha = varargin{i}; tlen_type = 'samples'; sTrain.alpha_type = 'user defined'; end case {'sTrain','train','som_train'}, i=i+1; sTrain = varargin{i}; case {'topol','sTopol','som_topol'}, i=i+1; sTopol = varargin{i}; if prod(sTopol.msize) ~= munits, error('Given map grid size does not match the codebook size.'); end % unambiguous values case {'inv','linear','power'}, sTrain.alpha_type = varargin{i}; case {'hexa','rect'}, sTopol.lattice = varargin{i}; case {'sheet','cyl','toroid'}, sTopol.shape = varargin{i}; case {'gaussian','cutgauss','ep','bubble'}, sTrain.neigh = varargin{i}; case {'epochs','samples'}, tlen_type = varargin{i}; case {'random', 'ordered'}, sample_order_type = varargin{i}; otherwise argok=0; end elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), switch varargin{i}(1).type, case 'som_topol', sTopol = varargin{i}; if prod(sTopol.msize) ~= munits, error('Given map grid size does not match the codebook size.'); end case 'som_train', sTrain = varargin{i}; otherwise argok=0; end else argok = 0; end if ~argok, disp(['(som_seqtrain) Ignoring invalid argument #' num2str(i+2)]); end i = i+1; end % training length if ~isempty(radius) | ~isempty(alpha), lr = length(radius); la = length(alpha); if lr>2 | la>1, tlen_type = 'samples'; if lr> 2 & la<=1, sTrain.trainlen = lr; elseif lr<=2 & la> 1, sTrain.trainlen = la; elseif lr==la, sTrain.trainlen = la; else error('Mismatch between radius and learning rate vector lengths.') end end end if strcmp(tlen_type,'samples'), sTrain.trainlen = sTrain.trainlen/dlen; end % check topology if struct_mode, if ~strcmp(sTopol.lattice,sMap.topol.lattice) | ... ~strcmp(sTopol.shape,sMap.topol.shape) | ... any(sTopol.msize ~= sMap.topol.msize), warning('Changing the original map topology.'); end end sMap.topol = sTopol; % complement the training struct sTrain = som_train_struct(sTrain,sMap,'dlen',dlen); if isempty(sTrain.mask), sTrain.mask = ones(dim,1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% initialize M = sMap.codebook; mask = sTrain.mask; trainlen = sTrain.trainlen*dlen; % neighborhood radius if length(radius)>2, radius_type = 'user defined'; else radius = [sTrain.radius_ini sTrain.radius_fin]; rini = radius(1); rstep = (radius(end)-radius(1))/(trainlen-1); radius_type = 'linear'; end % learning rate if length(alpha)>1, sTrain.alpha_type ='user defined'; if length(alpha) ~= trainlen, error('Trainlen and length of neighborhood radius vector do not match.') end if any(isnan(alpha)), error('NaN is an illegal learning rate.') end else if isempty(alpha), alpha = sTrain.alpha_ini; end if strcmp(sTrain.alpha_type,'inv'), % alpha(t) = a / (t+b), where a and b are chosen suitably % below, they are chosen so that alpha_fin = alpha_ini/100 b = (trainlen - 1) / (100 - 1); a = b * alpha; end end % initialize random number generator rand('state',sum(100*clock)); % distance between map units in the output space % Since in the case of gaussian and ep neighborhood functions, the % equations utilize squares of the unit distances and in bubble case % it doesn't matter which is used, the unitdistances and neighborhood % radiuses are squared. Ud = som_unit_dists(sTopol).^2; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Action update_step = 100; mu_x_1 = ones(munits,1); samples = ones(update_step,1); r = samples; alfa = samples; qe = 0; start = clock; if tracking > 0, % initialize tracking track_table = zeros(update_step,1); qe = zeros(floor(trainlen/update_step),1); end for t = 1:trainlen, % Every update_step, new values for sample indeces, neighborhood % radius and learning rate are calculated. This could be done % every step, but this way it is more efficient. Or this could % be done all at once outside the loop, but it would require much % more memory. ind = rem(t,update_step); if ind==0, ind = update_step; end if ind==1, steps = [t:min(trainlen,t+update_step-1)]; % sample order switch sample_order_type, case 'ordered', samples = rem(steps,dlen)+1; case 'random', samples = ceil(dlen*rand(update_step,1)+eps); end % neighborhood radius switch radius_type, case 'linear', r = rini+(steps-1)*rstep; case 'user defined', r = radius(steps); end r=r.^2; % squared radius (see notes about Ud above) r(r==0) = eps; % zero radius might cause div-by-zero error % learning rate switch sTrain.alpha_type, case 'linear', alfa = (1-steps/trainlen)*alpha; case 'inv', alfa = a ./ (b + steps-1); case 'power', alfa = alpha * (0.005/alpha).^((steps-1)/trainlen); case 'user defined', alfa = alpha(steps); end end % find BMU x = D(samples(ind),:); % pick one sample vector known = ~isnan(x); % its known components Dx = M(:,known) - x(mu_x_1,known); % each map unit minus the vector [qerr bmu] = min((Dx.^2)*mask(known)); % minimum distance(^2) and the BMU % tracking if tracking>0, track_table(ind) = sqrt(qerr); if ind==update_step, n = ceil(t/update_step); qe(n) = mean(track_table); trackplot(M,D,tracking,start,n,qe); end end % neighborhood & learning rate % notice that the elements Ud and radius have been squared! % (see notes about Ud above) switch sTrain.neigh, case 'bubble', h = (Ud(:,bmu)<=r(ind)); case 'gaussian', h = exp(-Ud(:,bmu)/(2*r(ind))); case 'cutgauss', h = exp(-Ud(:,bmu)/(2*r(ind))) .* (Ud(:,bmu)<=r(ind)); case 'ep', h = (1-Ud(:,bmu)/r(ind)) .* (Ud(:,bmu)<=r(ind)); end h = h*alfa(ind); % update M M(:,known) = M(:,known) - h(:,ones(sum(known),1)).*Dx; end; % for t = 1:trainlen %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Build / clean up the return arguments if tracking, fprintf(1,'\n'); end % update structures sTrain = som_set(sTrain,'time',datestr(now,0)); if struct_mode, sMap = som_set(sMap,'codebook',M,'mask',sTrain.mask,'neigh',sTrain.neigh); tl = length(sMap.trainhist); sMap.trainhist(tl+1) = sTrain; else sMap = reshape(M,orig_size); end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions %%%%%%%% function [] = trackplot(M,D,tracking,start,n,qe) l = length(qe); elap_t = etime(clock,start); tot_t = elap_t*l/n; fprintf(1,'\rTraining: %3.0f/ %3.0f s',elap_t,tot_t) switch tracking case 1, case 2, plot(1:n,qe(1:n),(n+1):l,qe((n+1):l)) title('Quantization errors for latest samples') drawnow otherwise, subplot(2,1,1), plot(1:n,qe(1:n),(n+1):l,qe((n+1):l)) title('Quantization error for latest samples'); subplot(2,1,2), plot(M(:,1),M(:,2),'ro',D(:,1),D(:,2),'b.'); title('First two components of map units (o) and data vectors (+)'); drawnow end % end of trackplot
github
martinarielhartmann/mirtooloct-master
som_kmeanscolor2.m
.m
mirtooloct-master/somtoolbox/som_kmeanscolor2.m
5,856
utf_8
b167d8ae2e8d9e2099002b0b6c376772
function [color,centroids]=som_kmeanscolor2(mode,sM,C,initRGB,contrast,R) % SOM_KMEANSCOLOR2 Color codes a SOM according to averaged or best K-means clustering % % color = som_kmeanscolor2('average',sM, C, [initRGB], [contrast],[R]) % % color=som_kmeanscolor2('average',sM,[2 4 8 16],som_colorcode(sM,'rgb1'),'enhanced'); % [color,centroid]=som_kmeanscolor2('best',sM,15,[],'flat',R); % % Input and output arguments ([]'s are optional): % % mode (string) 'average' or 'best', defalut: 'average' % sM (struct) a map struct % C (vector) number of clusters % [initRGB] (string, matrix) a color code string accepted by SOM_COLORCODE % or an Mx3 matrix of RGB triples, where M is the number % of map units. Default: SOM_COLORCODEs default % [contrast] (string) 'flat', 'enhanced' color contrast mode, default: % 'enhanced'. % [R] (scalar) number of K-means trials, default: 30. % color (matrix) Mx3xC of RGB triples % centroid (array of matrices) centroid{i} includes codebook for the best % k-means for C(i) clusters, i.e. the cluster centroids corresponding to % the color code color(:,:,i). % % The function gives a set of color codes for the SOM according to K-means % clustering. It has two operation modes: % % 'average': The idea of coloring is that the color of the units belonging to the same % cluster is the mean of the original RGB values (see SOM_COLORCODE) of the map units % belonging to the cluster (see SOM_CLUSTERCOLOR). The K-means clustering is made, % by default, 30 times and the resulting color codes are averaged for % each specified number of clusters C(i), i=1,...,k. In a way, the resulting averaged color % codes reflect the stability of the K-means clustering made on the map units. % % 'best': runs the k-means R times for C(i), i=1,...,n clusters as in previous mode, % but instead of averaging all the R color codes, it picks the one that corresponds to the % best k-means clustering for each C(i). The 'best' is the one with the lowest % quantization error. The result may differ from run to run. % % EXAMPLE % % load iris; % or any other map struct sM % color=som_kmeanscolor2('average',sM,[2:6]); % som_show(sM,'umat','all','color',color); % % See also SOM_KMEANS, SOM_SHOW, SOM_COLORCODE, SOM_CLUSTERCOLOR, SOM_KMEANSCOLOR % Contributed to SOM Toolbox 2.0, 2001 February by Johan Himberg % Copyright (c) by Johan Himberg % http://www.cis.hut.fi/projects/somtoolbox/ %%% Check number of inputs error(nargchk(3, 6, nargin)); % check no. of input args %%% Check input args & set defaults if ~vis_valuetype(mode,{'string'}), error('Mode must be a string.'); end switch lower(mode), case{'average','best'} ; otherwise error('Mode must be string ''average'' or ''best''.'); end if isstruct(sM) & isfield(sM,'type') & strcmp(sM.type,'som_map'), [tmp,lattice,msize]=vis_planeGetArgs(sM); munits=prod(msize); if length(msize)>2 error('Does not work with 3D maps.') end else error('Map struct required for the second input argument!'); end if ~vis_valuetype(C,{'1xn','nx1'}), error('Vector value expected for cluster number.'); end % Round C and check C=round(C(:)'); if any(C<2), error('Cluster number must be 2 or more.'); end % check initial color coding if nargin<4 | isempty(initRGB) initRGB=som_colorcode(sM); end % check contrast checking if nargin<5 | isempty(contrast), contrast='enhanced'; end if ~ischar(contrast), error('String input expected for input arg. ''contrast''.'); else switch lower(contrast) case {'flat','enhanced'} ; otherwise error(['''flat'' or ''enhanced'' expected for '... 'input argument ''contrast''.']); end end if ischar(initRGB), try initRGB=som_colorcode(sM,initRGB); catch error(['Color code ' initRGB ... 'was not recognized by SOM_COLORCODE.']); end elseif vis_valuetype(initRGB,{'nx3rgb',[munits 3]},'all'), ; else error(['The initial color code must be a string '... 'or an Mx3 matrix of RGB triples.']); end if nargin<6|isempty(R), R=30; end if ~vis_valuetype(R,{'1x1'}), error('''R'' must be scalar.'); end %%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% disp('Wait...'); index=0; hit_=zeros(munits,munits); switch mode, %% Averaged k-means coloring case 'average' for k=C, disp(['Running K-means for ' num2str(k) ' clusters...']); color_=zeros(munits,3); colord_=color_; % Average R k-means colorings for C clusters for j=1:R, [dummy,c]=som_kmeans('batch',sM,k,100,0); % max 100 iterations, verbose off color_=color_+som_clustercolor(sM,c,initRGB); end index=index+1; color(:,:,index)=color_./R; end %% coloring for 'best' k-means coloring case 'best' for k=C, disp(['Running K-means for ' num2str(k) ' clusters...']); c=[];err=Inf; div=[]; %% look for the best k-means among R trials for i=1:R, [c_,div_,err_(i)]=som_kmeans('batch',sM,k,100,0); % max 100 iterations, verbose off if err_(i)<err, err=err_(i); c=c_; div=div_; end end % record the 'best' k-means for C clusters index=index+1; color(:,:,index)=som_clustercolor(sM,div,initRGB); centroid{index}=c; end end %%% Build output switch contrast case 'flat' ; case 'enhanced' warning off; ncolor=maxnorm(color); ncolor(~isfinite(ncolor))=color(~isfinite(ncolor)); color=ncolor; warning on; end %%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function X=maxnorm(x) % normalize columns of x between [0,1] x=x-repmat(min(x),[size(x,1) 1 1]); X=x./repmat(max(x),[size(x,1) 1 1]);
github
martinarielhartmann/mirtooloct-master
som_stats_plot.m
.m
mirtooloct-master/somtoolbox/som_stats_plot.m
4,911
utf_8
04eb5e46e18587318f497985e2ef3672
function som_stats_plot(csS,plottype,varargin) %SOM_STATS_PLOT Plots of data set statistics. % % som_stats_plot(csS, plottype, [argID, value, ...]) % % som_stats_plot(csS,'stats') % som_stats_plot(csS,'stats','p','vert','color','r') % % Input and output arguments ([]'s are optional): % csS (cell array) of statistics structs % (struct) a statistics struct % plottype (string) some of the following % 'hist' histogram % 'box' min, max, mean, and std shown as a boxplot % 'stats' both histogram (with black) and the boxplot % [argID, (string) See below. The values which are unambiguous can % value] (varies) be given without the preceeding argID. % % Here are the valid argument IDs and corresponding values. The values which % are unambiguous (marked with '*') can be given without the preceeding argID. % 'counts' *(string) 'c' (for counts, the default) or 'p' (for percentages) % 'color' (vector) size 1 x 3, color to be used % (string) a color string % 'title' (string) 'on' (default) or 'off' % 'orientation' *(string) 'horiz' or 'vert' (default): orientation for the % bin values (horizontally or vertically) % % See also SOM_STATS, SOM_STATS_TABLE, SOM_TABLE_PRINT, SOM_STATS_REPORT. % Contributed to SOM Toolbox 2.0, December 31st, 2001 by Juha Vesanto % Copyright (c) by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 311201 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% arguments % statistics if isstruct(csS), csS = {csS}; end % default values useprob = 0; color = [0 0 1]; showtitle = 1; horiz = 0; % varargin i=1; while i<=length(varargin), argok = 1; if ischar(varargin{i}), switch varargin{i}, % argument IDs case 'counts', i=i+1; useprob = strcmp(varargin{i}(1),'p'); case 'color', i=i+1; color = varargin{i}; case 'title', i=i+1; showtitle = strcmp(varargin{i},'on'); case 'orientation', i=i+1; horiz = strcmp(varargin{i},'horiz'); % unambiguous values case {'horiz','vert'}, horiz = strcmp(varargin{i},'horiz'); case {'c','p'}, useprob = strcmp(varargin{i}(1),'p'); otherwise argok=0; end elseif isstruct(varargin{i}) & isfield(varargin{i},'type'), argok = 0; else argok = 0; end if ~argok, disp(['(som_stats_plot) Ignoring invalid argument #' num2str(i+2)]); end i = i+1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 %% action ss = ceil(sqrt(length(csS))); ss = [ss, ceil(length(csS)/ss)]; for j = 1:length(csS), sS = csS{j}; subplot(ss(1),ss(2),j); switch plottype, case 'stats', cla, hold on Counts = sS.hist.counts; if useprob, for i=1:size(Counts,2), Counts(:,i) = Counts(:,i)/sum(Counts(:,i)); end, end hist_plot(sS.hist.bins,sS.hist.binlabels,Counts,color); box_plot(sS.min,sS.max,sS.mean,sS.std,[0 0 0]); case 'hist', cla, hold on Counts = sS.hist.counts; if useprob, for i=1:size(Counts,2), Counts(:,i) = Counts(:,i)/sum(Counts(:,i)); end, end hist_plot(sS.hist.bins,sS.hist.binlabels,Counts,color); case 'box', cla box_plot(sS.min,sS.max,sS.mean,sS.std,color); end if showtitle, title(sprintf('%s (valid: %d/%d)',sS.name,sS.nvalid,sS.ntotal)); end if ~horiz, view(90,-90); end a = axis; a(1) = sS.min; a(2) = sS.max; axis(a); end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 %% subfunctions function hist_plot(bins,binlabels,Counts,color) if nargin<4, color = jet(size(Counts,2)); end h = bar(bins,Counts); for j=1:length(h), set(h(j),'facecolor',color(j,:),'edgecolor','none'); end a = axis; a(3:4) = [0 max(Counts(:))]; axis(a); set(gca,'XTick',bins,'XTickLabel',binlabels); return; function vstr = numtostring(v,d) nearzero = (abs(v)/(max(v)-min(v)) < 10.^-d); i1 = find(v > 0 & nearzero); i2 = find(v < 0 & nearzero); vstr = strrep(cellstr(num2str(v,d)),' ',''); vstr(i1) = {'0.0'}; vstr(i2) = {'-0.0'}; return; function box_plot(mi,ma,me,st,Color) if nargin < 5, Color = jet(length(mi)); end a = axis; y = linspace(a(3),a(4),length(mi)+2); y = y(2:end); d = (y(2)-y(1))/20; for i=1:length(mi), h1 = line([mi(i) ma(i)],[y(i) y(i)]); h2 = line([mi(i) mi(i) NaN ma(i) ma(i)],[y(i)-d y(i)+d NaN y(i)-d y(i)+d]); h3 = line([me(i)-st(i) me(i)+st(i)],[y(i) y(i)]); h4 = line([me(i) me(i)],[y(i)-2*d y(i)+2*d]); set([h1 h2 h3 h4],'color',Color(i,:)); set([h1 h2],'linewidth',1); set([h3 h4],'linewidth',3); end return;
github
martinarielhartmann/mirtooloct-master
sompak_train.m
.m
mirtooloct-master/somtoolbox/sompak_train.m
6,477
utf_8
c1f8430b537283c08dd052265ce60c99
function sMap=sompak_train(sMap,ft,cout,ct,din,dt,rlen,alpha,radius) %SOMPAK_TRAIN Call SOM_PAK training program from Matlab. % % sMap=sompak_train(sMap,ft,cout,ct,din,dt,rlen,alpha,radius) % % ARGUMENTS ([]'s are optional and can be given as empty: [] or '') % sMap (struct) map struct % (string) filename % [ft] (string) 'pak' or 'box'. Argument must be defined, if input file % is used. % [cout] (string) filename for output SOM, if argument is not defined % (i.e. argument is '[]') temporary file '__abcdef' is % used in operations and *it_is_removed* after % operations!!! % [ct] (string) 'pak' or 'box'. Argument must be defined, if output % file is used. % din (struct) data struct to be used in teaching % (matrix) data matrix % (string) filename % If argument is not a filename or file is .mat -file, % temporary file '__din' is used in operations % and *it_is_removed* after operations!!! % [dt] (string) 'pak' or 'box'. Argument must be defined, if input file % is used. % rlen (scalar) running length of teaching % alpha (float) initial alpha value % radius (float) initial radius of neighborhood % % RETURNS % sMap (struct) map struct % % Calls SOM_PAK training program (vsom) from Matlab. Notice that to % use this function, the SOM_PAK programs must be in your search path, % or the variable 'SOM_PAKDIR' which is a string containing the % program path, must be defined in the workspace. SOM_PAK programs can % be found from: http://www.cis.hut.fi/research/som_lvq_pak.shtml % % See also SOMPAK_TRAIN, SOMPAK_SAMMON, SOMPAK_TRAIN_GUI, % SOMPAK_GUI, SOM_SEQTRAIN. % Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas % Copyright (c) by Juha Parhankangas % http://www.cis.hut.fi/projects/somtoolbox/ % Juha Parhankangas 050100 nargchk(9,9,nargin); NO_FILE=0; DIN_FILE = 0; if ~isstruct(sMap) & ~isstr(sMap) error('Argument ''sMap'' must be a struct or string.'); end if isstr(sMap) if isempty(ft) error('Argument ''ft'' must be defined.'); end if strcmp(ft,'pak') sMap=som_read_cod(sMap); elseif strcmp(ft,'box') new_var=diff_varname; varnames=evalin('base','who'); loadname=eval(cat(2,'who(''-file'',''',sMap,''')')); if any(strcmp(loadname{1},evalin('base','who'))) assignin('base',new_var,evalin('base',loadname{1})); evalin('base',cat(2,'load(''',sMap,''');')); new_var2=diff_varname; assignin('base',new_var2,evalin('base',loadname{1})); assignin('base',loadname{1},evalin('base',new_var)); evalin('base',cat(2,'clear ',new_var)); sMap=evalin('base',new_var2); evalin('base',cat(2,'clear ',new_var2)); else evalin('base',cat(2,'load(''',sMap,''');')); sMap=evalin('base',loadname{1}); evalin('base',cat(2,'clear ',loadname{1})); end end end if ~isstr(cout) & isempty(cout) cout = '__abcdef'; NO_FILE = 1; elseif ~isstr(cout) | (isstr(cout) & isempty(cout)) error('Argument ''cout'' must be a string or ''[]''.'); end if ~NO_FILE & (isempty(ct) | ~(~isempty(ct) & ... (strcmp(ct,'pak') | strcmp(ct,'box')))) error('Argument ''ct'' must be string ''pak'' or ''box''.'); end map_name=sMap.name; som_write_cod(sMap,cout); if ~isempty(din) som_write_data(din, '__din'); DIN_FILE = 1; din = '__din'; else DIN_FILE=0; end if ~DIN_FILE if isempty(dt) | ~isstr(dt) | ~(strcmp(dt,'box') | strcmp(dt,'pak')) error('Argument ''dt'' must be string ''pak'' or ''box''.'); end if strcmp(dt,'box'); DIN_FILE = 1; din_var=diff_varname; varnames=evalin('base','who'); loadname=eval(cat(2,'who(''-file'',''',din,''')')); if any(strcmp(loadname{1},evalin('base','who'))) assignin('base',din_var,evalin('base',loadname{1})); evalin('base',cat(2,'load(''',din,''');')); din_var2=diff_varname; assignin('base',new_var2,evalin('base',loadname{1})); assignin('base',loadname{1},evalin('base',din_var)); evalin('base',cat(2,'clear ',din_var)); din=evalin('base',din_var2); else evalin('base',cat(2,'load(''',din,''')')); din=evalin('base',loadname{1}); evalin('base',cat(2,'clear ',loadname{1})); end som_write_data(din,'__din'); din = '__din'; end end if ~is_positive_integer(rlen) error('Argument ''rlen'' must be positive integer.'); end if ~(isreal(alpha) & all(size(alpha)==1)) error('Argument ''alpha'' must be a floating point number.'); end if ~(isreal(radius) & all(size(radius)==1) & radius > 0) error('Argument ''radius'' must be a positive floating point number.'); end if any(strcmp('SOM_PAKDIR',evalin('base','who'))) traincommand=cat(2,evalin('base','SOM_PAKDIR'),'vsom '); else traincommand='vsom '; end str=cat(2,traincommand,sprintf('-cin %s -din %s -cout %s ',cout,din,cout),... sprintf(' -rlen %d -alpha %f -radius %f',rlen,alpha,radius)); if isunix unix(str); else dos(str); end sMap=som_read_cod(cout); sMap.name=map_name; if ~NO_FILE if isunix unix(cat(2,'/bin/rm ',cout)); else dos(cat(2,'del ',cout)); end if isempty(ct) | ~isstr(ct) | ~(strcmp(ct,'pak') | strcmp(ct,'box')) error('Argument ''ct'' must be string ''pak'' or ''box''.'); elseif strcmp(ct,'box'); eval(cat(2,'save ',cout,' sMap')); disp(cat(2,'Output written to the file ',sprintf('''%s.mat''.',cout))); else som_write_cod(sMap,cout); end else if isunix unix('/bin/rm __abcdef'); else dos('del __abcdef'); end end if DIN_FILE if isunix unix('/bin/rm __din'); else dos('del __abcdef'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bool = is_positive_integer(x) bool = ~isempty(x) & isreal(x) & all(size(x) == 1) & x > 0; if ~isempty(bool) if bool & x~=round(x) bool = 0; end else bool = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = diff_varname(); array=evalin('base','who'); if isempty(array) str='a'; return; end for i=1:length(array) lens(i)=length(array{i}); end ind=max(lens); str(1:ind+1)='a'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
martinarielhartmann/mirtooloct-master
som_kmeanscolor.m
.m
mirtooloct-master/somtoolbox/som_kmeanscolor.m
4,375
utf_8
b90f1bc73191e2f5c68e2e8afe11269a
function [color,best,kmeans]=som_kmeanscolor(sM,C,initRGB,contrast) % SOM_KMEANSCOLOR Map unit color code according to K-means clustering % % [color, best, kmeans] = som_kmeanscolor(sM, C, [initRGB],[contrast]) % % color = som_kmeanscolor(sM,15,som_colorcode(sM,'rgb1'),'enhance'); % [color,best] = som_kmeanscolor(sM,15,[],'normal'); % % Input and output arguments ([]'s are optional): % sM (struct) map struct % C (scalar) maximum number of clusters % initRGB (string, matrix) color code string accepted by SOM_COLORCODE % or an Mx3 matrix of RGB triples, where M is the number % of map units. Default: SOM_COLORCODEs default % contrast (string) 'flat', 'enhanced' color contrast mode, default: % 'enhanced' % % color (matrix) MxCx3 of RGB triples % best (scalar) index for "best" clustering according to % Davies-Boulding index; color(:,:,best) includes the % corresponding color code. % kmeans (cell) output of KMEANS_CLUSTERS in a cell array. % % The function gives a set of color codings according to K-means % clustering. For clustering, it uses function KMEANS_CLUSTERS for map units, % and it calculates color codings for 1,2,...,C clusters. % The idea of coloring is that the color of a cluster is the mean of the % original colors (RGB values) of the map units belonging to that cluster, % see SOM_CLUSTERCOLOR. The original colors are defined by SOM_COLORCODE % by default. Input 'contrast' simply specifies whether or not % to linearly redistribute R,G, and B values so that minimum is 0 and % maximum 1 ('enahanced') or to use directly the output of % SOM_CLUSTERCOLOR ('flat'). KMEANS_CLUSTERS uses certain heuristics to % select the best of 5 trials for each number of clusters. Evaluating the % clustering multiple times may take some time. % % EXAMPLE % % load iris; % or any other map struct sM % [color,b]=som_kmeanscolor(sM,10); % som_show(sM,'color',color,'color',{color(:,:,b),'"Best clustering"'); % % See also SOM_SHOW, SOM_COLORCODE, SOM_CLUSTERCOLOR, KMEANS_CLUSTERS % Contributed to SOM Toolbox 2.0, April 1st, 2000 by Johan Himberg % Copyright (c) by Johan Himberg % http://www.cis.hut.fi/projects/somtoolbox/ % corrected help text 11032005 johan %%% Check number of inputs error(nargchk(2, 4, nargin)); % check no. of input args %%% Check input args & set defaults if isstruct(sM) & isfield(sM,'type') & strcmp(sM.type,'som_map'), [tmp,lattice,msize]=vis_planeGetArgs(sM); munits=prod(msize); if length(msize)>2 error('Does not work with 3D maps.') end else error('Map struct requires for first input argument!'); end if ~vis_valuetype(C,{'1x1'}), error('Scalar value expect for maximum number of clusters.'); end % check initial color coding if nargin<3 | isempty(initRGB) initRGB=som_colorcode(sM); end % check contrast checking if nargin<4 | isempty(contrast), contrast='enhanced'; end if ~ischar(contrast), error('String input expected for input arg. ''contrast''.'); else switch lower(contrast) case {'flat','enhanced'} ; otherwise error(['''flat'' or ''enhanced'' expected for '... 'input argument ''contrast''.']); end end if ischar(initRGB), try initRGB=som_colorcode(sM,initRGB); catch error(['Color code ' initRGB ... 'was not recognized by SOM_COLORCODE.']); end elseif vis_valuetype(initRGB,{'nx3rgb',[munits 3]},'all'), ; else error(['The initial color code must be a string '... 'or an Mx3 matrix of RGB triples.']); end %%% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% disp('Wait...'); [c,p,err,ind]=kmeans_clusters(sM,C,5,0); % use 5 trials, verbose off % Store outputs to kmeans kmeans{1}=c; kmeans{2}=p; kmeans{3}=err; kmeans{4}=ind; %%% Build output color=som_clustercolor(sM,cat(2,p{:}),initRGB); [tmp,best]=min(ind); switch contrast case 'flat' ; case 'enhanced' warning off; ncolor=maxnorm(color); ncolor(~isfinite(ncolor))=color(~isfinite(ncolor)); color=ncolor; warning on; end %%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function X=maxnorm(x) % normalize columns of x between [0,1] x=x-repmat(min(x),[size(x,1) 1 1]); X=x./repmat(max(x),[size(x,1) 1 1]);
github
martinarielhartmann/mirtooloct-master
vis_valuetype.m
.m
mirtooloct-master/somtoolbox/vis_valuetype.m
7,502
utf_8
cb7a373fcda9120d69231b2748371740
function flag=vis_valuetype(value, valid, str); % VIS_VALUETYPE Used for type checks in SOM Toolbox visualization routines % % flag = vis_valuetype(value, valid, str) % % Input and output arguments: % value (varies) variable to be checked % valid (cell array) size 1xN, cells are strings or vectors (see below) % str (string) 'all' or 'any' (default), determines whether % all or just any of the types listed in argument 'valid' % should be true for 'value' % % flag (scalar) 1 or 0 (true or false) % % This is an internal function of SOM Toolbox visualization. It makes % various type checks. For example: % % % Return 1 if X is a numeric scalar otherwise 0: % f=vis_valuetype(X,{'1x1'}); % % % Return 1 if X is a ColorSpec, that is, a 1x3 vector presenting an RGB % % value or any of strings 'red','blue','green','yellow','magenta','cyan', % % 'white' or 'black' or their shortenings 'r','g','b','y','m','c','w','k': % f=vis_valueype(X,{'1x3rgb','colorstyle'}) % % % Return 1 if X is _both_ 10x3 size numeric matrix and has RGB values as rows % f=vis_valuetype(X,{'nx3rgb',[10 3]},'all') % % Strings that may be used in argument valid: % id is true if value is % % [n1 n2 ... nn] any n1 x n2 x ... x nn sized numeric matrix % '1x1' scalar (numeric) % '1x2' 1x2 vector (numeric) % 'nx1' any nx1 numeric vector % 'nx2' nx2 % 'nx3' nx3 % 'nxn' any numeric square matrix % 'nxn[0,1]' numeric square matrix with values in interval [0,1] % 'nxm' any numeric matrix % '1xn' any 1xn numeric vector % '1x3rgb' 1x3 vector v for which all(v>=0 & v<=1), e.g., a RGB code % 'nx3rgb' nx3 numeric matrix that contains n RGB values as rows % 'nx3dimrgb' nx3xdim numeric matrix that contains RGB values % 'nxnx3rgb' nxnx3 numeric matrix of nxn RGB triples % 'none' string 'none' % 'xor' string 'xor' % 'indexed' string 'indexed' % 'colorstyle' strings 'red','blue','green','yellow','magenta','cyan','white' % or 'black', or 'r','g','b','y','m','c','w','k' % 'markerstyle' any of Matlab's marker chars '.','o','x','+','*','s','d','v', % '^','<','>','p'or 'h' % 'linestyle' any or Matlab's line style strings '-',':','--', or '-.' % 'cellcolumn' a nx1 cell array % 'topol_cell' {lattice, msize, shape} % 'topol_cell_no_shape' {lattice, msize} % 'string' any string (1xn array of char) % 'chararray' any MxN char array % Copyright (c) 1999-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta Johan 201099 juuso 280800 if nargin == 2 str='any'; end flag=0; sz=size(value); dims=ndims(value); % isnumeric numeric=isnumeric(value); character=ischar(value); % main loop: go through all types in arg. 'valid' for i=1:length(valid), if isnumeric(valid{i}), % numeric size for double matrix if numeric & length(valid{i}) == dims, flag(i)=all(sz == valid{i}); else flag(i)=0; % not numeric or wrong dimension end else msg=''; % for a error message inside try try switch valid{i} % scalar case '1x1' flag(i)=numeric & dims == 2 & sz(1)==1 & sz(2) ==1; % 1x2 numeric vector case '1x2' flag(i)=numeric & dims == 2 & sz(1)==1 & sz(2) == 2; % 1xn numeric vector case '1xn' flag(i)=numeric & dims == 2 & sz(1) == 1; % any numeric matrix case 'nxm' flag(i)=numeric & dims == 2; % nx3 numeric matrix case 'nx3' flag(i)=numeric & dims == 2 & sz(2) == 3; % nx2 numeric matrix case 'nx2' flag(i)=numeric & dims == 2 & sz(2) == 2; % nx1 numeric vector case 'nx1' flag(i)=numeric & dims == 2 & sz(2) == 1; % nx1xm numric matrix case 'nx1xm' flag(i)=numeric & dims == 3 & sz(2) == 1; % nx3 matrix of RGB triples case 'nx3rgb' flag(i)=numeric & dims == 2 & sz(2) == 3 & in0_1(value); % RGB triple (ColorSpec vector) case '1x3rgb' flag(i) = numeric & dims == 2 & sz(1)==1 & sz(2) == 3 & in0_1(value); % any square matrix case 'nxn' flag(i)=numeric & dims == 2 & sz(1) == sz(2); % nx3xdim array of nxdim RGB triples case 'nx3xdimrgb' flag(i)=numeric & dims == 3 & sz(2) == 3 & in0_1(value); % nxnx3 array of nxn RGB triples case 'nxnx3rgb' flag(i)= numeric & dims == 3 & sz(1) == sz(2) & sz(3) == 3 ... & in0_1(value); % nxn matrix of values between [0,1] case 'nxn[0,1]' flag(i)=numeric & dims == 2 & sz(1) == sz(2) & in0_1(value); % string 'indexed' case 'indexed' flag(i) = ischar(value) & strcmp(value,'indexed'); % string 'none' case 'none' flag(i) = character & strcmp(value,'none'); % string 'xor' case 'xor' flag(i) = character & strcmp(value,'xor'); % any string (1xn char array) case 'string' flag(i) = character & dims == 2 & sz(1)<=1; % any char array case 'chararray' flag(i) = character & dims == 2 & sz(1)>0; % ColorSpec string case 'colorstyle' flag(i)=(character & sz(1) == 1 & sz(2) == 1 & ... any(ismember('ymcrgbwk',value))) | ... (ischar(value) & any(strcmp(value,{'none','yellow','magenta',... 'cyan','red','green','blue','white','black'}))); % any valid Matlab's Marker case 'markerstyle' flag(i)=character & sz(1) == 1 & sz(2) == 1 & ... any(ismember('.ox+*sdv^<>ph',value)); % any valid Matlab's LineStyle case 'linestyle' str=strrep(strrep(strrep(value,'z','1'),'--','z'),'-.','z'); flag(i)=character & any(ismember(str,'z-:')) & sz(1)==1 & (sz(2)==1 | sz(2)==2); % any struct case 'struct' flag(i)=isstruct(value); % nx1 cell array of strings case 'cellcolumn_of_char' flag(i)=iscell(value) & dims == 2 & sz(2)==1; try, char(value); catch, flag(i)=0; end % mxn cell array of strings case '2Dcellarray_of_char' flag(i)=iscell(value) & dims == 2; try, char(cat(2,value{:})); catch, flag(i)=0; end % valid {lattice, msize} case 'topol_cell_no_shape' flag(i)=1; if ~iscell(value) | length(size(value)) ~= 2 | size(value,2)~=2 flag(i)=0; else if vis_valuetype(value{1},{'string'}), switch value{1} case { 'hexa','rect'} ; otherwise flag(i)=0; end end if ~vis_valuetype(value{2},{'1xn'}), flag(i)=0; end end % valid {lattice, msize, shape} case 'topol_cell' flag(i)=1; if ~iscell(value) | length(size(value)) ~= 2 | size(value,2) ~= 3, flag(i)=0; else if vis_valuetype(value{1},{'string'}), switch value{1} case { 'hexa','rect'} ; otherwise flag(i)=0; end end if ~vis_valuetype(value{2},{'1xn'}) flag(i)=0; end if ~vis_valuetype(value{3},{'string'}) flag(i)=0; else switch value{3} case { 'sheet','cyl', 'toroid'} ; otherwise flag(i)=0; end end end otherwise msg='Unknown valuetype!'; end catch % error during type check is due to wrong type of value: % lets set flag(i) to 0 flag(i)=0; end % Unknown indetifier? error(msg); end % set flag according to 3rd parameter (all ~ AND, any ~ OR) if strcmp(str,'all'); flag=all(flag); else flag=any(flag); end end function f=in0_1(value) f=all(value(:) >= 0 & value(:)<=1);
github
martinarielhartmann/mirtooloct-master
som_neighf.m
.m
mirtooloct-master/somtoolbox/som_neighf.m
3,518
utf_8
d37974390d75ef52b98cff7dc7fa6a53
function H = som_neighf(sMap,radius,neigh,ntype) %SOM_NEIGHF Return neighborhood function values. % % H = som_neighf(sMap,[radius],[neigh],[ntype]); % % Input and output arguments ([]'s are optional): % sMap (struct) map or topology struct % [radius] (scalar) neighborhood radius (by default, the last used value % in sMap.trainhist is used, or 1 if that is unavailable) % [neigh] (string) neighborhood function type (by default, ..., or % 'gaussian' if that is unavailable) % [ntype] (string) 'normal' (default), 'probability' or 'mirror' % % H (matrix) [munits x munits] neighborhood function values from % each map unit to each other map unit % % For more help, try 'type som_batchtrain' or check out online documentation. % See also SOM_MAKE, SOM_SEQTRAIN, SOM_TRAIN_STRUCT. % Copyright (c) 1997-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Check arguments % defaults rdefault = 1; ndefault = 'gaussian'; tdefault = 'normal'; % map switch sMap.type, case 'som_map', sTopol = sMap.topol; sTrain = sMap.trainhist(end); if isempty(sTrain.radius_fin) | isnan(sTrain.radius_fin), rdefault = 1; else rdefault = sTrain.radius_fin; end if ~isempty(sTrain.neigh) & ~isnan(sTrain.neigh), ndefault = sTrain.neigh; end case 'som_topol', sTopol = sMap; end munits = prod(sTopol.msize); % other parameters if nargin<2 | isempty(radius), radius = rdefault; end if nargin<3 | isempty(neigh), neigh = ndefault; end if nargin<4 | isempty(ntype), ntype = tdefault; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% initialize % basic neighborhood Ud = som_unit_dists(sTopol); Ud = Ud.^2; radius = radius.^2; if radius==0, radius = eps; end % zero neighborhood radius may cause div-by-zero error switch ntype, case 'normal', H = neighf(neigh,Ud,radius); case 'probability', H = neighf(neigh,Ud,radius); for i=1:munits, H(i,:) = H(i,:)/sum(H(i,:)); end case 'mirror', % only works for 2-dim grid!!! H = zeros(munits,munits); Co = som_unit_coords(sTopol); for i=-1:1, for j=-1:1, Ud = gridmirrordist(Co,i,j); H = H + neighf(neigh,Ud,radius); end end end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function H = neighf(neigh,Ud,radius) switch neigh, case 'bubble', H = (Ud<=radius); case 'gaussian', H = exp(-Ud/(2*radius)); case 'cutgauss', H = exp(-Ud/(2*radius)) .* (Ud<=radius); case 'ep', H = (1-Ud/radius) .* (Ud<=radius); end return; function Ud = gridmirrordist(Co,mirrorx,mirrory) [munits,mdim] = size(Co); if mdim>2, error('Mirrored neighborhood only works for 2-dim map grids.'); end % width and height of the grid dx = max(Co(:,1))-min(Co(:,1)); dy = max(Co(:,2))-min(Co(:,2)); % calculate distance from each location to each other location Ud = zeros(munits,munits); for i=1:munits, inds = [i:munits]; coi = Co(i,:); % take hexagonal shift into account coi(1) = coi(1)*(1-2*(mirrorx~=0)) + 2*dx*(mirrorx==1); % +mirrorx * step coi(2) = coi(2)*(1-2*(mirrory~=0)) + 2*dy*(mirrory==1); % +mirrory * step Dco = (Co(inds,:) - coi(ones(munits-i+1,1),:))'; Ud(i,inds) = sqrt(sum(Dco.^2)); Ud(inds,i) = Ud(i,inds)'; end return;
github
martinarielhartmann/mirtooloct-master
som_gui.m
.m
mirtooloct-master/somtoolbox/som_gui.m
99,745
utf_8
46047f777569e35ebc2596223c5cc512
function som_gui(varargin) %SOM_GUI A GUI for initialization and training of SOM. % % som_gui([sD]) % % som_gui % som_gui(sD) % % Input and output arguments ([]'s are optional) % [sD] (struct) SOM data struct % (matrix) a data matrix, size dlen x dim % % Actually, there are more arguments the function takes, but % they are for internal action of the function only. DO NOT use % them. % % For a more throughout description, see the online documentation. % See also PREPROCESS. %%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IN FILES: som_gui.html,browsewin.jpg,wspace.jpg,loadgui.jpg,initgui.jpg,questdlg.jpg,paragui.jpg,mwindow.jpg,visgui.gif,reload.gif,savemap.gif,browse.gif % % Contributed to SOM Toolbox vs2, February 2nd, 2000 by Mika Pollari % Copyright (c) by Mika Pollari and SOM Toolbox Team % http://www.cis.hut.fi/projects/somtoolbox/ % Mika Pollari 31.1.2000 vs 1.1 global NEWMAP NEWST MAPSAVED MAP DATA LOAD_NAME LOAD_DATA; global SAVEMAP ALGORITHM HANDLE2 STOPOLINIT INIT_TYPE; global STRAIN1 STRAIN2 SOTHERS; if nargin == 0 main_gui; action = 'dummy'; elseif nargin == 1 temp = varargin{1}; if isstruct(temp), DATA = temp; main_gui; action = 'input_data'; elseif isnumeric(temp), DATA = som_data_struct(temp); main_gui; action = 'input_data'; else action = temp; end end switch(action) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LOAD %%%%%%%%%%%%%%%%%%%%%%%%%% case 'load_data' loadgui3; %%% Activates load GUI case 'workspace' workspace; %%% Workspace selected case 'file' file; %%% File Selected case 'file_select' file_select; case 'missing' Handle = findobj(gcf,'Tag','Checkbox1'); set(Handle,'Value',1); case 'load_ok' %%% <Load OK> pushed load_ok; case 'input_data' %%% GUI activated with data as arg1 input_data; %%% eg. som_gui(data) case 'browse' %%% Activates Browse GUI browse; %%% Browse files or workspace variables case 'works_ok' %%% <OK> pushed in (workspace) browse GUI works_ok; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%% Initialization %%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'def_initialization' %%% Finds default initialization ... def_initialization; %%% parameters case 'change_initialization' %%% Activates change (init) parameters GUI change_initialization; case 'change_initialization_ok'%%% Set new init. parameters change_initialization_ok; case 'change_initialization_cancel' close(gcf); return; case 'map_size' %%% Checks that 'map_size' is given in correct form map_size; case 'munits' %%% Checks that 'munits' is given in correct form munits; case 'init' %%% Initialize Map init; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%% Train %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'def_values_others' def_values_others; case 'def_values_train' STRAIN1 = som_train_struct('algorithm',ALGORITHM,'phase','rough','data',DATA); STRAIN2 = som_train_struct('previous',STRAIN1); case 'fill_fields' %%% Fill text fields in GUI fill_fields; case 'def_train' %%% Train Map def_train; case 'change_def' %%% Change default training parameters change_def; %%% Activate GUI case 'fill_new_defaults' fill_new_defaults; case 'set_batch_mask' set_batch_mask; case 'set_new_parameters' set_new_parameters; case 'only_finetune' %%% Train only once with finetune parameters only_finetune; %%%%%%% Next function check correctnes of new training parameters. case 'check_rough_radini' check_rough_radini; case 'check_fine_radini' check_fine_radini; case 'check_rough_radfin' check_rough_radfin; case 'check_fine_radfin' check_fine_radfin; case 'check_rough_alphaini' check_rough_alphaini; case 'check_fine_alphaini' check_fine_alphaini; case 'check_rough_trainlen' check_rough_trainlen; case 'check_fine_trainlen' check_fine_trainlen; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%% Save Map %%%%%%%%%%%%%%%%%%%%%% case 'savemap' %%% Save as <.cod> file savemap; case 'save_workspace' %%% Save in workspace save_workspace; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%% Help & Info %%%%%%%%%%%%%%%%%%%%%%% case 'help' web file:///share/somtoolbox/vs2/html/som_GUI.html; case 'helpwin' helpwin1; case 'helpwin2' helpwin som_gui; case 'data_info' data_info; %%% Info about data case 'map_info' %%% Info about map map_info; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% Other Functions %%%%%%%%%%%%%%%%%%%%%%% case 'preprocess' preprocess_gui; %%%%% Call preprocess GUI case 'visualize' visualize; %%%%% Call visualization GUI case 'clear_all' %%%%% Clear all filds clear_all; case 'close' close_fig; %%%%% Close active GUI end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%% END OF SWITCH-STATEMENT %%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% (SUB) FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% LOAD SECTION STARTS %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = workspace() Handle = findobj(gcbf,'Tag','Radiobutton2'); Value = get(Handle,'Value'); HandleTemp = findobj(gcbf,'Tag','Radiobutton1'); if Value == 1 set(HandleTemp,'Value',0); HandleBar = findobj(gcbf,'Tag','PopupMenu1'); set(HandleBar,'Enable','off'); set(HandleBar,'Visible','off'); Handle3 = findobj(gcbf,'Tag','StaticText3'); set(Handle3,'Visible','off'); Handle3 = findobj(gcbf,'Tag','Checkbox1'); set(Handle3,'Visible','off'); Handle3 = findobj(gcbf,'Tag','EditText3'); set(Handle3,'Visible','off'); Handle = findobj(gcbf,'Tag','EditText2'); set(Handle,'String',''); end function [] = file() Handle = findobj(gcbf,'Tag','Radiobutton1'); Value = get(Handle,'Value'); HandleTemp = findobj(gcbf,'Tag','Radiobutton2'); if Value == 1 set(HandleTemp,'Value',0); HandleBar = findobj(gcbf,'Tag','PopupMenu1'); set(HandleBar,'Enable','on'); set(HandleBar,'Visible','on'); Handle3 = findobj(gcbf,'Tag','StaticText3'); set(Handle3,'Visible','on'); Handle3 = findobj(gcbf,'Tag','Checkbox1'); set(Handle3,'Visible','on'); Handle3 = findobj(gcbf,'Tag','EditText3'); set(Handle3,'Visible','on'); Handle = findobj(gcbf,'Tag','EditText1'); set(Handle,'String',''); end function [] = file_select() Handle = findobj(gcbf,'Tag','PopupMenu1'); temp = get(Handle,'String'); val = get(Handle,'Value'); Handle1 = findobj(gcbf,'Tag','Checkbox1'); Handle2 = findobj(gcbf,'Tag','EditText3'); if strcmp(temp{val},'dat file') set(Handle2,'String','x'); set(Handle1,'Enable','on'); set(Handle2,'Enable','on'); set(Handle1,'Visible','on'); set(Handle2,'Visible','on'); else set(Handle1,'Value',0); set(Handle1,'Enable','off'); set(Handle2,'Enable','off'); set(Handle1,'Visible','off'); set(Handle2,'Visible','off'); end function [] = load_ok() global MAP DATA LOAD_DATA LOAD_NAME; Handle1 = findobj(gcbf,'Tag','EditText1'); Handle2 = findobj(gcbf,'Tag','EditText2'); Name1 = get(Handle1,'String'); Name2 = get(Handle2,'String'); if isempty(Name1) & not(isempty(Name2)) Handle = findobj(gcbf,'Tag','PopupMenu1') type = get(Handle,'String'); val = get(Handle,'Value'); type = type{val}; if strcmp(type,'mat file') ltemp = 'load:::'; ltemp = strcat(ltemp,Name2); ltemp = strrep(ltemp,':::',' '); evalin('base',ltemp); DATA = evalin('base','sD'); LOAD_DATA = evalin('base','sD.data'); LOAD_NAME = evalin('base','sD.name'); LOAD_NAME = strrep(LOAD_NAME,'.','_'); load_labels = evalin('base','sD.labels'); load_comp_names = evalin('base','sD.comp_names'); DATA = som_data_struct(LOAD_DATA); DATA.name = LOAD_NAME; DATA.comp_names = load_comp_names; DATA.labels = load_labels; else Handle = findobj(gcbf,'Tag','Checkbox1'); value = get(Handle,'Value'); if value == 0 temp = 'som_read_data('''; temp = strcat(temp,Name2,''');'); else Handle = findobj(gcbf,'Tag','EditText3'); missing = get(Handle,'String'); if not(isempty(missing)) temp = 'som_read_data('''; temp = strcat(temp,Name2,'''',',','''',missing,''');'); else temp = 'som_read_data('''; temp = strcat(temp,Name2,''');'); end end evalin('base',temp); DATA = evalin('base','ans'); name = DATA.name; temp = findstr('/',name); if not(isempty(temp)) name = name(temp(end)+1:end); end name = strrep(name,'.','_'); LOAD_NAME = name; DATA.name = name; end elseif isempty(Name2) & not(isempty(Name1)) LOAD_DATA = evalin('base',Name1); if not(isstruct(LOAD_DATA)) DATA = som_data_struct(LOAD_DATA); LOAD_NAME = Name1; DATA.name = Name1; else DATA = LOAD_DATA; name = DATA.name; temp = findstr('/',name); if not(isempty(temp)) name = name(temp(end)+1:end); end name = strrep(name,'.','_'); LOAD_NAME = name; DATA.name = name; end else errmsg = {'Give name of data before loading'}; errordlg(errmsg,'Empty data name!'); return; end close(gcbf); if not(isempty(MAP)) clear MAP; global MAP; str1 = 'Map: <empty>'; str2 = 'Train'; Handle = findobj(gcf,'Tag','StaticText3'); set(Handle,'String',str1); Handle = findobj(gcf,'Tag','StaticText8'); set(Handle,'String',str2); end temp = 'Data:'; temp = strcat(temp,' <',LOAD_NAME,'>'); Handle = findobj(gcf,'Tag','StaticText4'); set(Handle,'String',temp); som_gui('def_initialization'); Handle = findobj(gcf,'Tag','Pushbutton2'); set(Handle,'Enable','off'); Handle = findobj(gcf,'Tag','Pushbutton4'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','Pushbutton9'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','Subuimenu2'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','&Help/InfoHelp windowuimenu1'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','&Init&Trainuimenu1'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','&Init&TrainInitialize1'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','Subuimenu1'); set(Handle,'Enable','off'); %%%%%%???????? Handle = findobj(gcf,'Tag','StaticText10'); set(Handle,'String','Status <data loaded>'); function [] = input_data() global DATA; name = DATA.name; newname = strrep(name,'.','_'); DATA.name = newname; temp = strcat('Data: <',newname,'>'); Handle = findobj(gcf,'Tag','StaticText4'); set(Handle,'String',temp); som_gui('def_initialization'); Handle = findobj(gcf,'Tag','Pushbutton2'); set(Handle,'Enable','off'); Handle = findobj(gcf,'Tag','Pushbutton4'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','Pushbutton9'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','Subuimenu2'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','&Help/InfoHelp windowuimenu1'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','&Init&Trainuimenu1'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','&Init&TrainInitialize1'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Tag','Subuimenu1'); set(Handle,'Enable','off'); %%%%%%???????? Handle = findobj(gcf,'Tag','StaticText10'); set(Handle,'String','Status <data loaded>'); function [] = browse() global HANDLE2; HandleWorkspace = findobj(gcbf,'Tag','Radiobutton2'); HandleFile = findobj(gcbf,'Tag','Radiobutton1'); WorkspaceVal = get(HandleWorkspace,'Value'); FileVal = get(HandleFile,'Value'); if FileVal == 1 Handle = findobj(gcbf,'Tag','PopupMenu1'); str = get(Handle,'String'); value = get(Handle,'Value'); str = str{value}; if strcmp(str,'mat file') filtter = '*.mat'; else filtter = '*.dat*'; end [filename pathname] = uigetfile(filtter,'Load file.'); temp = strcat(pathname,filename); Handle = findobj(gcbf,'Tag','EditText2'); set(Handle,'String',temp); elseif WorkspaceVal == 1 HANDLE2 = gcf; works; temp = evalin('base','who'); index2 = 1; names = ''; for index = 1:length(temp) if isnumeric(evalin('base',temp{index})) test = size(evalin('base',temp{index})); if test(1) ~= 1 & test(2) ~= 1 names{index2} = temp{index}; index2 = index2 + 1; end end end for index = 1:length(temp) variable = evalin('base',temp{index}); if isstruct(variable) fnames = fieldnames(variable); if size(fnames,1) == 6 & strcmp(fnames(1),'type') & strcmp(variable.type,'som_data') names{index2} = temp{index}; index2 = index2 + 1; end end end Handle = findobj(gcf,'Tag','Listbox1'); %%%%%% if is empty string#%%% set(Handle,'String',names); else errmsg = 'Select browse type: Workspace or file.'; errordlg(errmsg,'Browse error!'); return; end function [] = works_ok() global HANDLE2; Handle = findobj(gcbf,'Tag','Listbox1'); temp = get(Handle,'String'); val = get(Handle,'Value'); data = temp{val}; Handle = findobj(HANDLE2,'Tag','EditText1'); set(Handle,'String',data); close; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% END OF LOAD SECTION %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% START OF INITIALIZATION %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = def_initialization() global DATA STOPOLINIT INIT_TYPE; sTopol = som_topol_struct('data',DATA); Handle = findobj(gcf,'Tag','StaticText5'); temp = num2str(sTopol.msize); temp = strcat('map size:',' [',temp,']'); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText6'); set(Handle,'String','type: linear'); Handle = findobj(gcf,'Tag','StaticText20'); temp = strcat('lattice:',sTopol.lattice); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText21'); temp = strcat('shape:',sTopol.shape); set(Handle,'String',temp); STOPOLINIT = sTopol; INIT_TYPE = 'linear'; function [] = change_initialization() global INIT_TYPE STOPOLINIT; initialization2; Handle = findobj(gcf,'Tag','PopupMenu1'); temp = get(Handle,'String'); val = loop(temp,INIT_TYPE); set(Handle,'Value',val); Handle = findobj(gcf,'Tag','PopupMenu2'); temp = get(Handle,'String'); val = loop(temp,STOPOLINIT.lattice); set(Handle,'Value',val); Handle = findobj(gcf,'Tag','PopupMenu3'); temp = get(Handle,'String'); val = loop(temp,STOPOLINIT.shape); set(Handle,'Value',val); Handle = findobj(gcf,'Tag','EditText1'); temp = num2str(STOPOLINIT.msize); msize = strcat('[',temp,']'); set(Handle,'String',msize); function [] = change_initialization_ok() Handle = findobj(gcbf,'Tag','PopupMenu1'); temp = get(Handle,'String'); val = get(Handle,'Value'); INIT_TYPE = temp{val}; Handle = findobj(gcbf,'Tag','PopupMenu2'); temp = get(Handle,'String'); val = get(Handle,'Value'); lattice = temp{val}; Handle = findobj(gcbf,'Tag','PopupMenu3'); temp = get(Handle,'String'); val = get(Handle,'Value'); shape = temp{val}; Handle = findobj(gcbf,'Tag','EditText1'); temp = get(Handle,'String'); msize = str2num(temp); STOPOLINIT = som_set('som_topol','msize',msize,'lattice',lattice,'shape',shape); close(gcf); Handle = findobj(gcf,'Tag','StaticText5'); temp = num2str(STOPOLINIT.msize); temp = strcat('map size:',' [',temp,']'); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText6'); temp = strcat('type:',INIT_TYPE); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText20'); temp = strcat('lattice:',STOPOLINIT.lattice); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText21'); temp = strcat('shape:',STOPOLINIT.shape); set(Handle,'String',temp); function [] = def_values_others() global SOTHERS; Handle = findobj(gcf,'Tag','StaticText19'); temp = strcat('tracking:',SOTHERS.tracking); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText12'); temp = strcat('order:',SOTHERS.oder); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText14'); temp = strcat('length_type:',SOTHERS.length_type); set(Handle,'String',temp); function [] = fill_fields() global STRAIN1 STRAIN2 ALGORITHM neigh = STRAIN1.neigh; mask = STRAIN1.mask; rad_ini1 = STRAIN1.radius_ini; rad_ini2 = STRAIN2.radius_ini; rad_fin1 = STRAIN1.radius_fin; rad_fin2 = STRAIN2.radius_fin; trainlen1 = num2str(STRAIN1.trainlen); trainlen2 = num2str(STRAIN2.trainlen); alpha_ini1 = num2str(STRAIN1.alpha_ini); alpha_ini2 = num2str(STRAIN2.alpha_ini); if strcmp(ALGORITHM,'seq') alpha_type = STRAIN1.alpha_type; %%% only in sequential Handle = findobj(gcf,'Tag','StaticText28'); temp = strcat('alpha type:',alpha_type); set(Handle,'String',temp); end Handle = findobj(gcf,'Tag','StaticText11'); temp = strcat('neigh: ',neigh); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText22'); temp = num2str(rad_fin1); temp = strcat('radius final:',temp); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText25'); temp = num2str(rad_fin2); temp = strcat('radius final:',temp); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText11'); temp = strcat('neigh: ',neigh); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText17'); temp = num2str(rad_ini1); temp = strcat('radius initial:',temp); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText24'); temp = num2str(rad_ini2); temp = strcat('radius initial:',temp); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText16'); temp = num2str(trainlen1); temp = strcat('training length:',temp); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText23'); temp = num2str(trainlen2); temp = strcat('training length:',temp); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText26'); temp = strcat('alpha initial:',alpha_ini1); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText27'); temp = strcat('alpha initial:',alpha_ini2); set(Handle,'String',temp); function [] = init(); global INIT_TYPE MAP NEWMAP ALGORITHM SOTHERS DATA STOPOLINIT; if strcmp(INIT_TYPE,'random') MAP = som_randinit(DATA,STOPOLINIT); else MAP = som_lininit(DATA,STOPOLINIT); end NEWMAP = MAP; temp = 'Map:'; temp = strcat(temp,' <',MAP.name,'>'); Handle = findobj(gcbf,'Tag','StaticText3'); set(Handle,'String',temp); Handle = findobj(gcbf,'Tag','StaticText10'); set(Handle,'String','Status <map initialized>'); ALGORITHM = 'batch'; Handle = findobj(gcbf,'Tag','Pushbutton4'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','Pushbutton6'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','Pushbutton5'); set(Handle,'Enable','on'); SOTHERS.tracking = '1'; SOTHERS.length_type = 'epochs'; SOTHERS.oder = 'random'; som_gui('def_values_topol'); som_gui('def_values_train'); som_gui('def_values_others'); som_gui('fill_fields'); Handle = findobj(gcbf,'Tag','Pushbutton4'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','Pushbutton9'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','Radiobutton1'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','&Init&TrainChange initialization valuesuimenu1'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','&Init&TrainTrain1'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','&Help/InfoData infouimenu1'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','Subuimenu2'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','&Init&Trainuimenu1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','&Init&TrainInitialize1'); set(Handle,'Enable','off'); %%%%%%%%%%%?????????? Handle = findobj(gcbf,'Tag','StaticText9'); set(Handle,'String','training type: batch'); function [] = set_batch_mask() Handle = findobj(gcbf,'Tag','Listbox2'); temp = get(Handle,'String'); mask = str2num(temp); Handle = findobj(gcbf,'Tag','Listbox1'); replace = get(Handle,'Value'); Handle = findobj(gcbf,'Tag','EditText2'); temp = get(Handle,'String'); value = str2num(temp); if not(isempty(value)) mask(replace) = value; Handle = findobj(gcbf,'Tag','Listbox2'); temp = num2str(mask); set(Handle,'String',temp); end function [] = munits() global DATA STOPOLINIT; msgs = {'Correct map units is number';'Correct map units is number'}; [msgs_nro, value] = check_ok('EditText2'); if msgs_nro > 0 errordlg({msgs{msgs_nro}},'Incorrect map units!') return; end STOPOLINIT = som_topol_struct('munits',value,'data',DATA); Handle = findobj(gcbf,'Tag','EditText1'); temp = num2str(STOPOLINIT.msize); msize = strcat('[',temp,']'); set(Handle,'String',msize); function [] = map_size() global STOPOLINIT; msgs = {'Map size must be in form [x y]';... 'Map size must be in form [x y]'}; [msgs_nro, value, Handle] = msize_ok('EditText1'); if msgs_nro > 0 errordlg({msgs{msgs_nro}},'Incorrect map size!'); temp = num2str(STOPOLINIT.msize); temp = strcat('[',temp,']'); set(Handle,'String',temp); return; end STOPOLINIT.msize = value; Handle = findobj(gcbf,'Tag','EditText2'); set(Handle,'String',''); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% END OF INITIALIZATION %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% START OF TRAINING %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = def_train() global SOTHERS ALGORITHM MAP NEWST DATA STRAIN1 STRAIN2 MAPSAVED; tlen_type = SOTHERS.length_type; sample_order = SOTHERS.oder; tracking = SOTHERS.tracking; test = str2num(tracking); Handle = findobj(gcbf,'Tag','Radiobutton1'); tempval = get(Handle,'Value'); if strcmp(ALGORITHM,'seq') if tempval ~= 1 [MAP NEWST] = som_seqtrain(MAP,DATA,'train',STRAIN1,tlen_type,sample_order); end if test > 1 figure; set(gcf,'Name',MAP.name); set(gcf,'NumberTitle','off'); end [NEWMAP NEWST] = som_seqtrain(MAP,DATA,'train',STRAIN2,'tracking',test,tlen_type,sample_order); else if tempval ~= 1 [MAP NEWST] = som_batchtrain(MAP,DATA,'train',STRAIN1); end if test > 1 figure; set(gcf,'Name',MAP.name); set(gcf,'NumberTitle','off'); end [NEWMAP NEWST] = som_batchtrain(MAP,DATA,'train',STRAIN2,'tracking',test); end MAP = NEWMAP; clear MAPSAVED; Handle = findobj(gcbf,'Tag','StaticText10'); set(Handle,'String','Status <map trained>'); Handle = findobj(gcbf,'Tag','Load/SaveSubuimenu1'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','Load/SaveSave mapuimenu1'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','&Load/SaveSave mapSave in workspaceuimenu1'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','&ToolsSubuimenu1'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','&Init&TrainChange initialization valuesuimenu1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','&Init&TrainTrain1'); set(Handle,'Enable','off'); function [] = change_def() global ALGORITHM STRAIN1 DATA; ButtonName = questdlg('Select training type!',... 'Change values.',... 'Batch','Sequential','Cancel',... 'Batch'); if strcmp(ButtonName,'Sequential') Handle = findobj(gcbf,'Visible','off'); set(Handle,'Visible','on'); ALGORITHM = 'seq'; Handle = findobj(gcf,'Tag','StaticText9'); set(Handle,'String','training type: sequential'); new_para2_2; Handle = findobj(gcf,'Tag','StaticText1'); set(Handle,'String','Change parameters for sequential training'); Handle = findobj(gcf,'Enable','off'); set(Handle,'Enable','on'); Handle = findobj(gcf,'Visible','off'); set(Handle,'Visible','on'); elseif strcmp(ButtonName,'Batch') ALGORITHM = 'batch'; Handle = findobj(gcbf,'Tag','StaticText26'); set(Handle,'Visible','off'); Handle = findobj(gcbf,'Tag','StaticText27'); set(Handle,'Visible','off'); Handle = findobj(gcf,'Tag','StaticText9'); set(Handle,'String','training type: batch'); Handle = findobj(gcf,'Tag','StaticText12'); set(Handle,'Visible','off'); Handle = findobj(gcf,'Tag','StaticText28'); set(Handle,'Visible','off'); Handle = findobj(gcf,'Tag','StaticText14'); set(Handle,'Visible','off'); new_para2_2; Handle = findobj(gcf,'Tag','StaticText1'); set(Handle,'String','Change parameters for batch training'); Handle = findobj(gcf,'Tag','PopupMenu3'); set(Handle,'Enable','off'); set(Handle,'Visible','off'); Handle = findobj(gcf,'Tag','PopupMenu4'); set(Handle,'Enable','off'); set(Handle,'Visible','off'); Handle = findobj(gcf,'Tag','PopupMenu5'); set(Handle,'Enable','off'); set(Handle,'Visible','off'); Handle = findobj(gcf,'Tag','StaticText17'); set(Handle,'Visible','off'); Handle = findobj(gcf,'Tag','StaticText18'); set(Handle,'Visible','off'); Handle = findobj(gcf,'Tag','StaticText19'); set(Handle,'Visible','off'); Handle = findobj(gcf,'Tag','StaticText13'); set(Handle,'Visible','off'); Handle = findobj(gcf,'Tag','StaticText14'); set(Handle,'Visible','off'); Handle = findobj(gcf,'Tag','EditText6'); set(Handle,'Visible','off'); set(Handle,'Enable','off'); Handle = findobj(gcf,'Tag','EditText10'); set(Handle,'Visible','off'); set(Handle,'Enable','off'); else return; end som_gui('def_values_train'); mask = STRAIN1.mask; Handle = findobj(gcf,'Tag','Listbox1'); set(Handle,'String',DATA.comp_names); som_gui('fill_new_defaults'); function [] = fill_new_defaults() global STRAIN1 STRAIN2 SOTHERS ALGORITHM; Handle = findobj(gcf,'Tag','EditText4'); temp = num2str(STRAIN1.radius_ini); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','EditText8'); temp = num2str(STRAIN2.radius_ini); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','EditText5'); temp = num2str(STRAIN1.radius_fin); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','EditText9'); temp = num2str(STRAIN2.radius_fin); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','EditText6'); temp = num2str(STRAIN1.alpha_ini); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','EditText10'); temp = num2str(STRAIN2.alpha_ini); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','EditText7'); temp = num2str(STRAIN1.trainlen); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','EditText11'); temp = num2str(STRAIN2.trainlen); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','Listbox2'); temp = num2str(STRAIN1.mask'); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','PopupMenu2'); string = get(Handle,'String'); val = loop(string,SOTHERS.tracking); set(Handle,'Value',val); Handle = findobj(gcf,'Tag','PopupMenu1'); string = get(Handle,'String'); val = loop(string,STRAIN1.neigh); set(Handle,'Value',val); if strcmp(ALGORITHM,'seq') Handle = findobj(gcf,'Tag','PopupMenu3'); string = get(Handle,'String'); val = loop(string,SOTHERS.length_type); set(Handle,'Value',val); Handle = findobj(gcf,'Tag','PopupMenu4'); string = get(Handle,'String'); val = loop(string,SOTHERS.oder); set(Handle,'Value',val); Handle = findobj(gcf,'Tag','PopupMenu5'); string = get(Handle,'String'); val = loop(string,STRAIN1.alpha_type); set(Handle,'Value',val); end function [] = set_new_parameters() global STRAIN1 STRAIN2 ALGORITHM SOTHERS; Handle = findobj(gcbf,'Tag','Listbox2'); temp = get(Handle,'String'); mask = str2num(temp); %%%%%%%%%%%%% Do somthing mask = mask'; Handle = findobj(gcbf,'Tag','PopupMenu1'); temp = get(Handle,'String'); val = get(Handle,'Value'); neigh = temp{val}; Handle = findobj(gcbf,'Tag','PopupMenu2'); temp = get(Handle,'String'); val = get(Handle,'Value'); SOTHERS.tracking = temp{val}; %%%%% finetune phase! Handle = findobj(gcbf,'Tag','EditText4'); temp = get(Handle,'String'); rad_ini1 = str2num(temp); Handle = findobj(gcbf,'Tag','EditText8'); temp = get(Handle,'String'); rad_ini2 = str2num(temp); Handle = findobj(gcbf,'Tag','EditText5'); temp = get(Handle,'String'); rad_fin1 = str2num(temp); Handle = findobj(gcbf,'Tag','EditText9'); temp = get(Handle,'String'); rad_fin2 = str2num(temp); Handle = findobj(gcbf,'Tag','EditText6'); temp = get(Handle,'String'); alpha_ini1 = str2num(temp); Handle = findobj(gcbf,'Tag','EditText10'); temp = get(Handle,'String'); alpha_ini2 = str2num(temp); Handle = findobj(gcbf,'Tag','EditText7'); temp = get(Handle,'String'); train_length1 = str2num(temp); Handle = findobj(gcbf,'Tag','EditText11'); temp = get(Handle,'String'); train_length2 = str2num(temp); if strcmp(ALGORITHM,'seq') Handle = findobj(gcbf,'Tag','PopupMenu3'); temp = get(Handle,'String'); val = get(Handle,'Value'); SOTHERS.length_type = temp{val}; Handle = findobj(gcbf,'Tag','PopupMenu4'); temp = get(Handle,'String'); val = get(Handle,'Value'); SOTHERS.oder= temp{val}; Handle = findobj(gcbf,'Tag','PopupMenu5'); temp = get(Handle,'String'); val = get(Handle,'Value'); alpha_type = temp{val}; else alpha_type = 'inv'; end STRAIN1.neigh = neigh; STRAIN2.neigh = neigh; STRAIN1.mask = mask; STRAIN2.mask = mask; STRAIN1.radius_ini = rad_ini1; STRAIN2.radius_ini = rad_ini2; STRAIN1.radius_fin = rad_fin1; STRAIN2.radius_fin = rad_fin2; STRAIN1.alpha_ini = alpha_ini1; STRAIN2.alpha_ini = alpha_ini2; STRAIN1.alpha_type = alpha_type; STRAIN2.alpha_type = alpha_type; STRAIN1.trainlen = train_length1; STRAIN2.trainlen = train_length2; close(gcbf); som_gui('fill_fields'); som_gui('def_values_others'); function [] = only_finetune() Handle = findobj(gcbf,'Tag','Radiobutton1'); test = get(Handle,'Value'); if test == 1 Handle = findobj(gcbf,'Tag','StaticText16'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','StaticText17'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','StaticText22'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','StaticText26'); set(Handle,'Enable','off'); else Handle = findobj(gcbf,'Tag','StaticText16'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','StaticText17'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','StaticText22'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','StaticText26'); set(Handle,'Enable','on'); end function [] = check_rough_radini() global STRAIN1; msgs = {'Initial radius must be number!';... 'Initial radius must be single valued number!'}; [msgs_nro, value, Handle] = check_ok('EditText4'); if msgs_nro > 0 errordlg({msgs{msgs_nro}},'Incorrect initial radius!') temp = num2str(STRAIN1.radius_ini); set(Handle,'String',temp); return; end function [] = check_fine_radini() global STRAIN2; msgs = {'Initial radius must be number!';... 'Initial radius must be single valued number!'}; [msgs_nro, value, Handle] = check_ok('EditText8'); if msgs_nro > 0 errordlg({msgs{msgs_nro}},'Incorrect initial radius!') temp = num2str(STRAIN2.radius_ini); set(Handle,'String',temp); return; end function [] = check_rough_radfin() global STRAIN1; msgs = {'Final radius must be number!';... 'Final radius must be single valued number!'}; [msgs_nro, value, Handle] = check_ok('EditText5'); if msgs_nro > 0 errordlg({msgs{msgs_nro}},'Incorrect final radius!') temp = num2str(STRAIN1.radius_fin); set(Handle,'String',temp); return; end function [] = check_fine_radfin() global STRAIN2; msgs = {'Final radius must be number!';... 'Final radius must be single valued number!'}; [msgs_nro, value, Handle] = check_ok('EditText9'); if msgs_nro > 0 errordlg({msgs{msgs_nro}},'Incorrect final radius!') temp = num2str(STRAIN2.radius_fin); set(Handle,'String',temp); return; end function [] = check_rough_alphaini() global STRAIN1; msgs = {'Alpha initial must be number!';... 'Alpha initial must be single valued number!'}; [msgs_nro, value, Handle] = check_ok('EditText6'); if msgs_nro > 0 errordlg({msgs{msgs_nro}},'Incorrect initial alpha!') temp = num2str(STRAIN1.alpha_ini); set(Handle,'String',temp); return; end function [] = check_fine_alphaini() global STRAIN2; msgs = {'Alpha initial must be number!';... 'Alpha initial must be single valued number!'}; [msgs_nro, value, Handle] = check_ok('EditText10'); if msgs_nro > 0 errordlg({msgs{msgs_nro}},'Incorrect initial alpha!') temp = num2str(STRAIN2.alpha_ini); set(Handle,'String',temp); return; end function [] = check_rough_trainlen() global STRAIN1; msgs = {'Training length must be number!';... 'Training length must be single valued number!'}; [msgs_nro, value, Handle] = check_ok('EditText7'); if msgs_nro > 0 errordlg({msgs{msgs_nro}},'Incorrect training length!') temp = num2str(STRAIN1.trainlen); set(Handle,'String',temp); return; end function [] = check_fine_trainlen() global STRAIN2; msgs = {'Training length must be number!';... 'Training length must be single valued number!'}; [msgs_nro, value, Handle] = check_ok('EditText11'); if msgs_nro > 0 errordlg({msgs{msgs_nro}},'Incorrect training length!') temp = num2str(STRAIN2.trainlen); set(Handle,'String',temp); return; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% END OF TRAINING %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% START OF SAVING %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = savemap() global MAP MAPSAVED; if isempty(MAP) str = {'There is no map to be saved! Train map before saving.'}; helpdlg(str,'Empty map!'); return; end [FileName Path] = uiputfile('*.cod','Save file!'); if FileName ~= 0 temp = strcat(Path,FileName); som_write_cod(MAP,temp); MAPSAVED = 'SAVED'; end Handle = findobj(gcf,'Tag','StaticText10'); set(Handle,'String','Status <map saved>'); function [] = save_workspace() global MAP MAPSAVED; if isempty(MAP) str = {'There is no map to be saved! Train map before saving.'}; helpdlg(str,'Empty map!'); return; else prompt = {'Save map as?'}; title = 'Save map!'; lineNo = 1; answer = inputdlg(prompt,title,lineNo); if isempty(answer) return; end if not(isempty(answer{1})) ws_variable = evalin('base','who'); max_length = 0; for index = 1:size(ws_variable,1) if max_length < size(ws_variable{index},2) max_length = size(ws_variable{index},2); end end length = max_length + 1; tempfoo(1:1:length) = 'A'; assignin('base',tempfoo,answer{1}); str = ['exist(' tempfoo ')']; temp = evalin('base',str); %%%%%%%%%%@@@@@@@@@ evalin('base',['clear ' tempfoo ]) if temp == 0 assignin('base',answer{1},MAP); MAPSAVED = 'SAVED'; elseif temp ~= 0 Questmsg = strcat('Variable',' ''',answer{1},'''',... ' exist. Overwrite?'); ButtonName = questdlg(Questmsg); switch(ButtonName) case 'Yes' assignin('base',answer{1},MAP); MAPSAVED = 'SAVED'; case 'No' som_gui('save_workspace'); end end else helpmsg = {'There cannot be any empty field in ''save'''}; helpdlg(helpmsg,'Help Save!'); som_gui('save'); end end Handle = findobj(gcf,'Tag','StaticText10'); set(Handle,'String','Status <map saved>'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% END OF SAVING %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% START OF HELP & INFO %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %HEREXX function [] = data_info() global DATA; if isempty(DATA) helpmsg = 'Load data first!'; helpdlg(helpmsg,'Empty data!'); return; end file_name = tempname; file_name = strcat(file_name,'.m'); fid = fopen(file_name,'w'); fprintf(fid,'%% %+35s\n','DATA INFO'); fprintf(fid,'%%\n'); print_info(DATA,2,fid); directory = tempdir; addpath (directory); helpwin (file_name); fclose(fid); delete(file_name); rmpath (directory); function [] = map_info() global MAP; if isempty(MAP) helpmsg = 'There is no map!'; helpdlg(helpmsg,'Empty map!'); return; end file_name = tempname; file_name = strcat(file_name,'.m'); fid = fopen(file_name,'w'); fprintf(fid,'%% %+35s\n','MAP INFO'); fprintf(fid,'%%\n'); print_info(MAP,2,fid); directory = tempdir; addpath (directory); helpwin (file_name); fclose(fid); delete(file_name); rmpath (directory); function [] = helpwin1() file1 = tempname; file1 = strcat(file1,'.m'); directory = tempdir; html2tex('file:///share/somtoolbox/vs2/html/som_GUI.html',file1); addpath (directory); helpwin (file1); rmpath (directory); delete (file1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% END OF HELP & INFO %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% START OF OTHER FUNC %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [msgs_nro, value, Handle] = check_ok(Tag) Handle = findobj(gcbf,'Tag',Tag); temp = get(Handle,'String'); value = str2num(temp); if isempty(value) msgs_nro = 1; return; end [test1 test2] = size(value); if test1 ~= 1 | test2 ~= 1 msgs_nro = 2; return; end msgs_nro = 0; function [msgs_nro, value, Handle] = msize_ok(Tag) Handle = findobj(gcbf,'Tag',Tag); temp = get(Handle,'String'); value = str2num(temp); if isempty(value) msgs_nro = 1; return; end [test1 test2] = size(value); if test1 ~= 1 | test2 ~= 2 msgs_nro = 2; return; end msgs_nro = 0; %%% Changed 1.2.2000 function [] = visualize() global MAP; if isempty(MAP) helpmsg = {'Train map before tryinig to visualize it!'}; helpdlg(helpmsg,'Empty Map!'); return; end dim = size(MAP.codebook,2); odim = 2; [P,V] = pcaproj(MAP.codebook,odim); ccode = som_colorcode(MAP, 'rgb1'); figure; som_show(MAP,'umat','all','comp',1:dim,'norm','d'); figure; subplot(1,2,1) som_grid(MAP,'Coord',P,'MarkerColor',ccode,'Markersize',5, ... 'Linewidth',1,'Linecolor','k'); xlabel('PC1'), ylabel('PC2') title('PCA-projection (on the left), color coding (on the right)') axis tight, axis equal subplot(1,2,2) som_cplane(MAP.topol.lattice,MAP.topol.msize,ccode); %msgbox('Save map in workspace. Load it from there.'); %som_gui('save_workspace'); %som_comp_vis; %%%%%%%%%%%%%%%% function [] = clear_all() Handle = findobj(gcbf,'Enable','off'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','Radiobutton1'); set(Handle,'Value',0); Handle = findobj(gcbf,'Tag','StaticText10'); set(Handle,'String','Status <no action>'); Handle = findobj(gcbf,'Tag','StaticText3'); set(Handle,'String','Map: <empty>'); Handle = findobj(gcbf,'Tag','StaticText4'); set(Handle,'String','Data: <empty>'); Handle = findobj(gcbf,'Tag','StaticText20'); set(Handle,'String','lattice:'); Handle = findobj(gcbf,'Tag','StaticText11'); set(Handle,'String','neigh:'); Handle = findobj(gcbf,'Tag','StaticText16'); set(Handle,'String','training length:'); Handle = findobj(gcbf,'Tag','StaticText23'); set(Handle,'String','training length:'); Handle = findobj(gcbf,'Tag','StaticText17'); set(Handle,'String','radius initial:'); Handle = findobj(gcbf,'Tag','StaticText24'); set(Handle,'String','radius initial:'); Handle = findobj(gcbf,'Tag','StaticText5'); set(Handle,'String','map size:'); Handle = findobj(gcbf,'Tag','StaticText21'); set(Handle,'String','shape:'); Handle = findobj(gcbf,'Tag','StaticText12'); set(Handle,'String','order:'); set(Handle,'Visible','off'); Handle = findobj(gcbf,'Tag','StaticText14'); set(Handle,'String','length type:'); set(Handle,'Visible','off'); Handle = findobj(gcbf,'Tag','StaticText22'); set(Handle,'String','radius final:'); Handle = findobj(gcbf,'Tag','StaticText25'); set(Handle,'String','radius final:'); Handle = findobj(gcbf,'Tag','StaticText19'); set(Handle,'String','tracking:'); Handle = findobj(gcbf,'Tag','StaticText7'); set(Handle,'String','Initialization'); Handle = findobj(gcbf,'Tag','StaticText28'); set(Handle,'String','alpha type:'); set(Handle,'Visible','off'); Handle = findobj(gcbf,'Tag','StaticText26'); set(Handle,'String','alpha initial:'); Handle = findobj(gcbf,'Tag','StaticText27'); set(Handle,'String','alpha initial:'); Handle = findobj(gcbf,'Tag','StaticText6'); set(Handle,'String','type:'); Handle = findobj(gcbf,'Tag','StaticText9'); set(Handle,'String','training type:'); Handle = findobj(gcbf,'Tag','Pushbutton9'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','Pushbutton6'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','Pushbutton4'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','Pushbutton5'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','Pushbutton2'); set(Handle,'Enable','on'); Handle = findobj(gcbf,'Tag','Radiobutton1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','Load/SaveSave mapuimenu1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','&Load/SaveSave mapSave in workspaceuimenu1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','Subuimenu2'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','&ToolsSubuimenu1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','&Help/InfoHelp windowuimenu1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','&Help/InfoData infouimenu1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','&Init&Trainuimenu1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','&Init&TrainInitialize1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','&Init&TrainChange initialization valuesuimenu1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','&Init&TrainTrain1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'Tag','Load/SaveSubuimenu1'); set(Handle,'Enable','off'); Handle = findobj(gcbf,'String','alpha initial:'); set(Handle,'Visible','off'); clear; clear global; function [] = close_fig() global MAPSAVED NEWMAP; if isempty(MAPSAVED) if not(isempty(NEWMAP)) quest = 'Save map before closing?'; ButtonName = questdlg(quest); switch ButtonName case 'Yes' som_gui('savemap'); som_gui('clear'); clear global; close(gcbf); case 'No' som_gui('clear'); clear global; close(gcbf); case 'Cancel' end else som_gui('clear'); clear global; close(gcbf); end else som_gui('clear'); clear global; close(gcbf); end function [] = preprocess_gui() global DATA; if isempty(DATA) helpmsg = {'Load data before tryinig to preprocess!'}; helpdlg(helpmsg,'Empty Data!'); return; end preprocess(DATA); waitfor(gcf); prompt = {'Name of preprocessed data in workspace?'}; tittle = 'Reload preprocessed data!'; lineNo = 1; def = {DATA.name}; answer = inputdlg(prompt,tittle,lineNo,def); if isempty(answer) return; end data = answer{1}; new_name = retname; assignin('base',new_name,data); str = ['exist(' new_name ')']; temp = evalin('base',str); if temp ~= 1 temp = strcat('Variable ''',data,''' doesn''t exist in workspace.',... 'Old Data which is not preprocessed will be used.'); errordlg(temp,'Unknown variable!'); return; end evalin('base',['clear ' new_name ]) Handle = findobj(gcf,'Tag','StaticText4'); temp = strcat('Data: <',data,'>'); set(Handle,'String',temp); Handle = findobj(gcf,'Tag','StaticText10'); set(Handle,'String','Status <data preprocessed>'); temp = evalin('base',data); DATA.data = temp; som_gui('def_initialization'); function [val] = loop(cell_data, search_data) for val = 1: length(cell_data) if strcmp(cell_data{val},search_data) break; end end if not(strcmp(cell_data{val},search_data)) val = -1; end function [] = comp_names(names,fid) last = size(names); for index=1:last fprintf(fid,'%% %s\n',names{index}) end function [] = fill_field(names,mask,fid) last = size(mask); for index=1:last num = num2str(mask(index)) fprintf(fid,'%% %-15s %-2s\n',names{index},num) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% END OF OTHER FUNC %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fig = main_gui() v = version; ver_53_or_newer = (str2num(v(1:3)) >= 5.3); h0 = figure('Units','normalized', ... 'Color',[0.85 0.85 0.85], ... 'Name','SOM Toolbox -- Initialization & Training', ... 'NumberTitle','off', ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',[0.3296875 0.28125 0.3828125 0.576171875], ... 'Tag','Fig1'); if ver_53_or_newer, set(h0,'ToolBar','none'); end h1 = uimenu('Parent',h0, ... 'Label','&Load/Save', ... 'Tag','uimenu1'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''load_data'');',... 'Label','Load Data', ... 'Tag','Subuimenu1'); h2 = uimenu('Parent',h1, ... 'Label','Save map', ... 'Enable','off',... 'Tag','Load/SaveSubuimenu1'); h3 = uimenu('Parent',h2, ... 'Callback','som_gui(''save_workspace'');', ... 'Enable','off', ... 'Label','Save in workspace', ... 'Tag','Load/SaveSave mapuimenu1'); h3 = uimenu('Parent',h2, ... 'Callback','som_gui(''savemap'');', ... 'Enable','off', ... 'Label','Write cod-file', ... 'Tag','&Load/SaveSave mapSave in workspaceuimenu1'); h1 = uimenu('Parent',h0, ... 'Label','&Utilities', ... 'Tag','uimenu2'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''preprocess'');', ... 'Enable','off', ... 'Label','Preprocess Data', ... 'Tag','Subuimenu2'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''visualize'');', ... 'Enable','off', ... 'Label','Visualize Map', ... 'Tag','&ToolsSubuimenu1'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''clear_all'');', ... 'Label','Clear all', ... 'Tag','&ToolsSubuimenu2'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''close'');', ... 'Label','Close Figure', ... 'Tag','&ToolsClear alluimenu1'); h1 = uimenu('Parent',h0, ... 'Label','&Info', ... 'Tag','&ToolsClose Figureuimenu1'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''help'');', ... 'Label','WWW Help', ... 'Tag','Helpuimenu1'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''helpwin'');', ... 'Label','Help window', ... 'Tag','Helpuimenu2'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''helpwin2'');', ... 'Label','About GUI', ... 'Tag','&Help/InfoHelp windowuimenu2'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''data_info'');', ... 'Enable','off', ... 'Label','Data info', ... 'Tag','&Help/InfoHelp windowuimenu1'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''map_info'');', ... 'Enable','off', ... 'Label','Map info', ... 'Tag','&Help/InfoData infouimenu1'); h1 = uimenu('Parent',h0, ... 'Label','&Init/Train', ... 'Tag','&Init/Train1'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''change_initialization'');', ... 'Enable','off', ... 'Label','Change initialization values', ... 'Tag','&Init&Trainuimenu1'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''init'');', ... 'Enable','off', ... 'Label','Initialize', ... 'Tag','&Init&TrainInitialize1'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''change_def'');', ... 'Enable','off', ... 'Label','Change training values', ... 'Tag','&Init&TrainChange initialization valuesuimenu1'); h2 = uimenu('Parent',h1, ... 'Callback','som_gui(''def_train'');', ... 'Enable','off', ... 'Label','Train', ... 'Tag','&Init&TrainTrain1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.04081632653061224 0.01129943502824859 0.7619047619047619 0.9717514124293786], ... 'Style','frame', ... 'Tag','Frame1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.06802721088435373 0.7909604519774012 0.7074829931972788 0.1807909604519774], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.8527570621468927 0.6530612244897959 0.03389830508474576], ... 'FontUnits','normalized',... 'String','Map <empty>', ... 'Style','text', ... 'Tag','StaticText3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.8075593220338984 0.6530612244897959 0.03389830508474576], ... 'String','Data <empty>', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.06802721088435373 0.5988700564971752 0.7074829931972788 0.1694915254237288], ... 'Style','frame', ... 'Tag','Frame3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.1041 0.7356 0.6286 0.0271], ... 'String','Initialization', ... 'FontUnits','normalized',... 'Style','text', ... 'FontWeight','bold', ... 'Tag','StaticText7'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.4489795918367346 0.7005649717514124 0.2993197278911565 0.03389830508474576], ... 'String','map size:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.6553672316384182 0.2993197278911565 0.03389830508474576], ... 'String','lattice:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText20'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.7000000000000001 0.2993197278911565 0.03389830508474576], ... 'String','type:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText6'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.4489795918367346 0.6553672316384182 0.2993197278911565 0.03389830508474576], ... 'String','shape:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText21'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'ListboxTop',0, ... 'Position',[0.3129251700680272 0.6101694915254238 0.217687074829932 0.03389830508474576], ... 'String','Change values', ... 'FontUnits','normalized',... 'Callback','som_gui(''change_initialization'');', ... 'Enable','off', ... 'Tag','Pushbutton9'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.06802721088435373 0.02259887005649718 0.7074829931972788 0.5536723163841808], ... 'Style','frame', ... 'Tag','Frame4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.1041 0.5316 0.6429 0.0339], ... 'String','Training', ... 'FontUnits','normalized',... 'Style','text', ... 'FontWeight','bold', ... 'Tag','StaticText8'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.4971751412429379 0.6530612244897959 0.03389830508474576], ... 'String','training type', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText9'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.4489795918367346 0.4519774011299435 0.2993197278911565 0.03389830508474576], ... 'String','tracking:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText19'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.4519774011299435 0.2993197278911565 0.03389830508474576], ... 'String','neigh:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText11'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.36519774011299435 0.2993197278911565 0.03389830508474576], ... 'String','alpha type:', ... 'FontUnits','normalized',... 'Style','text', ... 'Visible','off',... 'Tag','StaticText28'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'ListboxTop',0, ... 'HorizontalAlignment','left', ... 'Position',[0.09523809523809523 0.4067796610169492 0.2993197278911565 0.03389830508474576], ... 'String','length type:', ... 'FontUnits','normalized',... 'Style','text', ... 'Visible','off',... 'Tag','StaticText14'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.4489795918367346 0.4067796610169492 0.2993197278911565 0.03389830508474576], ... 'String','order:', ... 'FontUnits','normalized',... 'Style','text', ... 'Visible','off',... 'Tag','StaticText12'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.07909604519774012 0.2993197278911565 0.2711864406779661], ... 'Style','frame', ... 'Tag','Frame5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.4353741496598639 0.07909604519774012 0.2993197278911565 0.2711864406779661], ... 'Style','frame', ... 'Tag','Frame6'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.108843537414966 0.3050847457627119 0.2721088435374149 0.03389830508474576], ... 'String','Rough', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText13'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.4489795918367346 0.3050847457627119 0.2721088435374149 0.03389830508474576], ... 'String','Finetune', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText15'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.108843537414966 0.1807909604519774 0.2721088435374149 0.03389830508474576], ... 'String','training length:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText16'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.108843537414966 0.2694915254237288 0.2714285714285714 0.03389830508474576], ... 'String','radius initial:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText17'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.1088 0.2260 0.2721 0.0339], ... 'String','radius final:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText22'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'ListboxTop',0, ... 'Position',[0.108843537414966 0.13694915254237288 0.2714285714285714 0.03389830508474576], ... 'String','alpha initial:', ... 'FontUnits','normalized',... 'HorizontalAlignment','left', ... 'Style','text', ... 'Visible','off',... 'Tag','StaticText26'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.4489795918367346 0.1807909604519774 0.2721088435374149 0.03389830508474576], ... 'String','training length:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText23'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.4489795918367346 0.2711864406779661 0.2721088435374149 0.03389830508474576], ... 'String','radius initial:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText24'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.4490 0.2260 0.2721 0.0339], ... 'String','radius final:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText25'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'ListboxTop',0, ... 'Position',[0.4489795918367346 0.13694915254237288 0.2721088435374149 0.03389830508474576], ... 'String','alpha initial:', ... 'FontUnits','normalized',... 'HorizontalAlignment','left', ... 'Style','text', ... 'Visible','off',... 'Tag','StaticText27'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'ListboxTop',0, ... 'Position',[0.3129251700680272 0.03389830508474576 0.217687074829932 0.03389830508474576], ... 'String','Change values', ... 'FontUnits','normalized',... 'Callback','som_gui(''change_def'');', ... 'Enable','off', ... 'Tag','Pushbutton6'); if ver_53_or_newer, set(h1,'TooltipString','Change default values in training.'); end h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'ListboxTop',0, ... 'Position',[0.8163265306122448 0.8152542372881356 0.163265306122449 0.05593220338983051], ... 'String','LOAD', ... 'FontUnits','normalized',... 'Callback','som_gui(''load_data'');', ... 'Tag','Pushbutton2'); if ver_53_or_newer, set(h1,'TooltipString','Load data file.'); end h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'ListboxTop',0, ... 'Position',[0.8163265306122448 0.6457627118644068 0.163265306122449 0.05593220338983051], ... 'String','INITIALIZE', ... 'FontUnits','normalized',... 'Callback','som_gui(''init'');', ... 'Enable','off', ... 'Tag','Pushbutton4'); if ver_53_or_newer, set(h1,'TooltipString','Initialize map.'); end h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'ListboxTop',0, ... 'Position',[0.8163265306122448 0.384180790960452 0.163265306122449 0.05649717514124294], ... 'String','TRAIN', ... 'FontUnits','normalized',... 'Callback','som_gui(''def_train'');', ... 'Enable','off', ... 'Tag','Pushbutton5'); if ver_53_or_newer, set(h1,'TooltipString','Train map whit default values.'); end h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'ListboxTop',0, ... 'Position',[0.8163265306122448 0.06779661016949153 0.163265306122449 0.05649717514124294], ... 'Callback','som_gui(''close'');', ... 'String','CLOSE', ... 'FontUnits','normalized',... 'Tag','Pushbutton8'); if ver_53_or_newer, set(h1,'TooltipString','Close figure.'); end h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.9 0.9 0.9], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.09387755102040815 0.897954802259887 0.6530612244897959 0.03389830508474576], ... 'String','Status <no action>', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText10'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.108843537414966 0.0903954802259887 0.2721088435374149 0.03389830508474576], ... 'String','Only finetune', ... 'FontUnits','normalized',... 'Callback','som_gui(''only_finetune'');', ... 'Enable','off', ... 'Style','radiobutton', ... 'Tag','Radiobutton1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.9418531073446328 0.6530612244897959 0.0259887005649718], ... 'String','Information', ... 'FontUnits','normalized',... 'FontWeight','bold', ... 'Style','text', ... 'Tag','StaticText18'); if nargout > 0, fig = h0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fig = loadgui3() temp = {'dat file';'mat file'}; h0 = figure('Units','normalized', ... 'Color',[0.8 0.8 0.8], ... 'Name','Load data!', ... 'NumberTitle','off', ... 'PaperType','a4letter', ... 'Position',[0.3828125 0.5 0.3421875 0.189453125], ... 'Tag','Fig1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.02853881278538813 0.06443298969072164 0.7705479452054794 0.8698453608247422], ... 'Style','frame', ... 'Tag','Frame1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.04337899543378995 0.547680412371134 0.7420091324200913 0.354381443298969], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.04280821917808219 0.09664948453608246 0.7420091324200913 0.4188144329896907], ... 'Style','frame', ... 'Tag','Frame3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'FontWeight','bold', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.05717762557077625 0.7881958762886597 0.2853881278538812 0.09664948453608246], ... 'String','From', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'Callback','som_gui(''workspace'');', ... 'ListboxTop',0, ... 'Position',[0.05107762557077625 0.7087628865979381 0.1997716894977169 0.09664948453608246], ... 'String','Ws', ... 'FontUnits','normalized',... 'Style','radiobutton', ... 'Tag','Radiobutton2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'Callback','som_gui(''file'');', ... 'ListboxTop',0, ... 'Position',[0.05107762557077625 0.5773195876288659 0.2009132420091324 0.09793814432989689], ... 'String','File', ... 'FontUnits','normalized',... 'Style','radiobutton', ... 'Tag','Radiobutton1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','Handle = findobj(gcbf,''Tag'',''EditText2'');set(Handle,''String'','''');',... 'FontUnits','normalized',... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.2893881278538812 0.7087628865979381 0.3139269406392694 0.09664948453608246], ... 'Style','edit', ... 'Tag','EditText1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','Handle = findobj(gcbf,''Tag'',''EditText1'');set(Handle,''String'','''');',... 'FontUnits','normalized',... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.2893881278538812 0.5798969072164948 0.3139269406392694 0.09664948453608246], ... 'Style','edit', ... 'Tag','EditText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'Callback','som_gui(''browse'');', ... 'ListboxTop',0, ... 'Position',[0.6279 0.5799 0.1427 0.2255], ... 'String','Browse', ... 'FontUnits','normalized',... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'Callback','som_gui(''load_ok'');', ... 'ListboxTop',0, ... 'Position',[0.8276 0.5577 0.1427 0.2255], ... 'String','Load', ... 'FontUnits','normalized',... 'Tag','Pushbutton2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'Callback','close;',... 'ListboxTop',0, ... 'Position',[0.8276 0.2577 0.1427 0.2255], ... 'String','Cancel', ... 'FontUnits','normalized',... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'Callback','som_gui(''file_select'');', ... 'ListboxTop',0, ... 'Max',2, ... 'Min',1, ... 'String',temp,... 'FontUnits','normalized',... 'Position',[0.3995433789954338 0.2977319587628866 0.1997716894977169 0.08664948453608246], ... 'Style','popupmenu', ... 'Tag','PopupMenu1', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'FontWeight','bold', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.05707762557077625 0.3865979381443299 0.7134703196347032 0.09664948453608246], ... 'String','Parameters for file', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.05707762557077625 0.2777319587628866 0.2568493150684931 0.09664948453608246], ... 'String','File type ', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.05707762557077625 0.1288659793814433 0.2996575342465753 0.09664948453608246], ... 'String','Missing value', ... 'Style','checkbox', ... 'FontUnits','normalized',... 'Tag','Checkbox1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''missing'');',... 'ListboxTop',0, ... 'Position',[0.5136986301369862 0.1258659793814433 0.08561643835616438 0.10664948453608246], ... 'String','x', ... 'FontUnits','normalized',... 'Style','edit', ... 'Tag','EditText3'); if nargout > 0, fig = h0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fig = works() v = version; ver_53_or_newer = (str2num(v(1:3)) >= 5.3); h0 = figure('Units','normalized', ... 'Color',[0.8 0.8 0.8], ... 'Name','Load from workspace!', ... 'NumberTitle','off', ... 'PaperPosition',[18 180 576 432], ... 'PaperType','a4letter', ... 'PaperUnits','points', ... 'Position',[0.5390625 0.2490234375 0.203125 0.251953125], ... 'Tag','Fig1'); if ver_53_or_newer, set(h0,'ToolBar','none'); end h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.05384615384615385 0.1472868217054263 0.9076923076923078 0.8255813953488372], ... 'Style','frame', ... 'Tag','Frame1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'Callback','som_gui(''works_ok'');', ... 'ListboxTop',0, ... 'Position',[0.1077 0.0194 0.2885 0.1202], ... 'String','OK', ... 'FontUnits','normalized',... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'Callback','close;', ... 'ListboxTop',0, ... 'Position',[0.6115 0.0155 0.2885 0.1202], ... 'String','Cancel', ... 'FontUnits','normalized',... 'Tag','Pushbutton2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Position',[0.1192 0.1977 0.7692 0.6395], ... 'String',' ', ... 'FontUnits','normalized',... 'Style','listbox', ... 'Tag','Listbox1', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'FontWeight','bold', ... 'ListboxTop',0, ... 'Position',[0.2115384615384616 0.8720930232558139 0.576923076923077 0.06976744186046512], ... 'String','Your options', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText1'); if nargout > 0, fig = h0; end function fig = initialization2() temp1 = {'random';'linear'}; temp2 = {'hexa';'rect'}; temp3 = {'sheet';'cyl';'toroid'}; % position bug in following corrected 1.12.04 KimmoR h0 = figure('Units','normalized', ... 'Color',[0.8 0.8 0.8], ... 'Name','Change initialization parameters!', ... 'NumberTitle','off', ... 'PaperType','a4letter', ... 'Position',[0.48828125 0.4267578125 0.3515625 0.146484375], ... 'Tag','Fig1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.02777777777777778 0.08333333333333333 0.8055555555555556 0.8333333333333334], ... 'Style','frame', ... 'Tag','Frame1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'Callback','som_gui(''change_initialization_ok'');', ... 'ListboxTop',0, ... 'Position',[0.8472222222222222 0.55 0.125 0.25], ... 'FontUnits','normalized',... 'String','OK', ... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'Callback','som_gui(''change_initialization_cancel'');', ... 'ListboxTop',0, ... 'Position',[0.8472222222222222 0.25 0.125 0.25], ... 'FontUnits','normalized',... 'String','Cancel', ... 'Tag','Pushbutton2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'FontWeight','bold', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.08333333333333334 0.6666666666666666 0.7066666666666667 0.1933333333333333], ... 'String','Initialization parameters:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.0556 0.200 0.1667 0.1250],... 'String','type:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'ListboxTop',0, ... 'Max',2, ... 'Min',1, ... 'Position',[0.2500 0.200 0.1667 0.1250], ... 'String',temp1, ... 'FontUnits','normalized',... 'Style','popupmenu', ... 'Tag','PopupMenu1', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.05555555555555556 0.6 0.1666666666666667 0.125], ... 'String','map size:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''map_size'');', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.25 0.6 0.1666666666666667 0.125], ... 'FontUnits','normalized',... 'Style','edit', ... 'Tag','EditText1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.05555555555555556 0.4033333333333333 0.1666666666666667 0.125], ... 'String','lattice:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Max',2, ... 'Min',1, ... 'Position',[0.25 0.4333333333333333 0.1666666666666667 0.125], ... 'String',temp2, ... 'FontUnits','normalized',... 'Style','popupmenu', ... 'Tag','PopupMenu2', ... 'Value',2); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.4444444444444445 0.4033333333333333 0.1666666666666667 0.125], ... 'String','shape:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Max',3, ... 'Min',1, ... 'Position',[0.638888888888889 0.4333333333333333 0.1666666666666667 0.125], ... 'String',temp3, ... 'FontUnits','normalized',... 'Style','popupmenu', ... 'Tag','PopupMenu3', ... 'Value',2); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.4444444444444445 0.6 0.1666666666666667 0.125], ... 'FontUnits','normalized',... 'String','munits:', ... 'Style','text', ... 'Tag','StaticText5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''munits'');', ... 'ListboxTop',0, ... 'Position',[0.638888888888889 0.6 0.1666666666666667 0.125], ... 'Style','edit', ... 'FontUnits','normalized',... 'Tag','EditText2'); if nargout > 0, fig = h0; end function fig = new_para2_2() temp1 = {'0';'1';'2';'3'}; temp2 = {'gaussian';'cutgauss';'ep';'bubble'}; temp3 = {'epochs';'samples'}; temp4 = {'random';'ordered'}; temp5 = {'inv';'linear';'power'}; v = version; ver_53_or_newer = (str2num(v(1:3)) >= 5.3); h0 = figure('Units','normalized', ... 'Color',[0.8 0.8 0.8], ... 'Name','Change training parameters!', ... 'NumberTitle','off', ... 'PaperPosition',[18 180 576 432], ... 'PaperType','a4letter', ... 'PaperUnits','points', ... 'Position',[0.59140625 0.4560546875 0.3046875 0.4619140625], ... 'Tag','Fig3'); if ver_53_or_newer, set(h0,'ToolBar','none'); end h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.02051282051282051 0.08456659619450317 0.9641025641025641 0.8921775898520086], ... 'Style','frame', ... 'Tag','Frame1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.5308 0.1374 0.4000 0.3742], ... 'Style','frame', ... 'Tag','Frame3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.08012820512820512 0.1416490486257928 0.4102564102564102 0.3699788583509514], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'Callback','close(gcbf);', ... 'ListboxTop',0, ... 'Position',[0.6410 0.0036 0.2897 0.0740], ... 'FontUnits','normalized',... 'String','Cancel', ... 'Tag','Pushbutton2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'Callback','som_gui(''set_new_parameters'');', ... 'ListboxTop',0, ... 'Position',[0.1026 0.0036 0.2897 0.0740], ... 'String','Set parameters', ... 'FontUnits','normalized',... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'ListboxTop',0, ... 'Max',4, ... 'Min',1, ... 'Position',[0.7051282051282051 0.6723044397463003 0.1923076923076923 0.040169133192389], ... 'String',temp1, ... 'FontUnits','normalized',... 'Style','popupmenu', ... 'Tag','PopupMenu2', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'ListboxTop',0, ... 'Max',4, ... 'Min',1, ... 'Position',[0.2948717948717949 0.6670190274841438 0.1923076923076923 0.03964059196617336], ... 'String',temp2, ... 'FontUnits','normalized',... 'Style','popupmenu', ... 'Tag','PopupMenu1', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'Callback','som_gui(''batch_cancel'');', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.5076923076923077 0.6575052854122622 0.1923076923076923 0.05285412262156448], ... 'String','tracking', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText6'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'Callback','som_gui(''batch_cancel'');', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.09615384615384615 0.6553911205073996 0.1923076923076923 0.05285412262156448], ... 'String','neigh.', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.09615384615384615 0.7526427061310783 0.09487179487179487 0.04228329809725159], ... 'String','mask:', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Position',[0.2948717948717949 0.7399577167019028 0.6025641025641025 0.07399577167019028], ... 'String',' ', ... 'FontUnits','normalized',... 'Style','listbox', ... 'Tag','Listbox2', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.0962 0.8060 0.1154 0.0529], ... 'FontUnits','normalized',... 'String','Set', ... 'Style','text', ... 'Tag','StaticText3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''set_batch_mask'');', ... 'Position',[0.2948717948717949 0.8165961945031712 0.3205128205128205 0.05285412262156448], ... 'String',' ', ... 'FontUnits','normalized',... 'Style','listbox', ... 'Tag','Listbox1', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.6250 0.8060 0.1603 0.0529], ... 'String','to value', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''set_batch_mask'');', ... 'ListboxTop',0, ... 'Position',[0.7923076923076923 0.8181818181818182 0.09487179487179487 0.05285412262156448], ... 'Style','edit', ... 'FontUnits','normalized',... 'Tag','EditText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''check_fine_trainlen'');', ... 'ListboxTop',0, ... 'Position',[0.7923 0.2352 0.0974 0.0402], ... 'FontUnits','normalized',... 'Style','edit', ... 'Tag','EditText11'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''check_fine_alphaini'');', ... 'Enable','off', ... 'ListboxTop',0, ... 'Position',[0.7923076923076923 0.1664904862579281 0.09743589743589742 0.03805496828752643], ... 'Style','edit', ... 'FontUnits','normalized',... 'Tag','EditText10', ... 'Visible','off'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''check_fine_radfin'');', ... 'ListboxTop',0, ... 'Position',[0.7923076923076923 0.3002114164904862 0.09743589743589742 0.040169133192389], ... 'Style','edit', ... 'FontUnits','normalized',... 'Tag','EditText9'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''check_fine_radini'');', ... 'ListboxTop',0, ... 'Position',[0.7923076923076923 0.3657505285412262 0.09743589743589742 0.040169133192389], ... 'Style','edit', ... 'FontUnits','normalized',... 'Tag','EditText8'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.5590 0.2326 0.2179 0.0402], ... 'String','training length', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText16'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.5590 0.1665 0.2179 0.0381], ... 'String','alpha initial', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText14', ... 'Visible','off'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.5590 0.2981 0.2179 0.0402], ... 'String','radius final', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText12'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.5590 0.3636 0.2179 0.0402], ... 'String','radius initial', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText10'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''check_rough_trainlen'');', ... 'ListboxTop',0, ... 'Position',[0.3590 0.2352 0.0949 0.0402], ... 'Style','edit', ... 'FontUnits','normalized',... 'Tag','EditText7'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''check_rough_alphaini'');', ... 'Enable','off', ... 'ListboxTop',0, ... 'Position',[0.3590 0.1691 0.0949 0.0381], ... 'Style','edit', ... 'FontUnits','normalized',... 'Tag','EditText6', ... 'Visible','off'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''check_rough_radfin'');', ... 'ListboxTop',0, ... 'Position',[0.358974358974359 0.3044397463002114 0.09487179487179487 0.040169133192389], ... 'Style','edit', ... 'FontUnits','normalized',... 'Tag','EditText5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Callback','som_gui(''check_rough_radini'');', ... 'ListboxTop',0, ... 'Position',[0.358974358974359 0.3699788583509514 0.09487179487179487 0.040169133192389], ... 'Style','edit', ... 'FontUnits','normalized',... 'Tag','EditText4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.0962 0.2326 0.2179 0.0402], ... 'String','training length', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText15'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.0962 0.1691 0.2179 0.0381], ... 'String','alpha initial', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText13', ... 'Visible','off'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.0962 0.3023 0.2179 0.0402], ... 'String','radius final', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText11'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.0962 0.3679 0.2179 0.0402], ... 'FontUnits','normalized',... 'String','radius initial', ... 'Style','text', ... 'Tag','StaticText9'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'ListboxTop',0, ... 'Position',[0.5948717948717949 0.4291754756871036 0.2871794871794872 0.05285412262156448], ... 'String','Finetune', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText8'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'ListboxTop',0, ... 'Position',[0.1205128205128205 0.4355179704016914 0.3153846153846154 0.04862579281183932], ... 'String','Rough', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText7'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'FontWeight','bold', ... 'ListboxTop',0, ... 'Position',[0.1641025641025641 0.8900634249471459 0.7025641025641025 0.05285412262156448], ... 'String','Change parameters for batch training', ... 'Style','text', ... 'FontUnits','normalized',... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.09615384615384615 0.6025369978858351 0.1743589743589744 0.040169133192389], ... 'String','length type:', ... 'Style','text', ... 'FontUnits','normalized',... 'Tag','StaticText17'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'ListboxTop',0, ... 'Max',2, ... 'Min',1, ... 'Position',[0.2948717948717949 0.6062367864693446 0.1923076923076923 0.03964059196617336], ... 'String',temp3, ... 'FontUnits','normalized',... 'Style','popupmenu', ... 'Tag','PopupMenu3', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.5102564102564102 0.6004228329809724 0.1641025641025641 0.040169133192389], ... 'String','order', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText18'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Max',2, ... 'Min',1, ... 'Position',[0.7051282051282051 0.6109936575052853 0.1923076923076923 0.040169133192389], ... 'String',temp4, ... 'FontUnits','normalized',... 'Style','popupmenu', ... 'Tag','PopupMenu4', ... 'Value',1); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.09615384615384615 0.5369978858350951 0.2051282051282051 0.040169133192389], ... 'String','learning func', ... 'FontUnits','normalized',... 'Style','text', ... 'Tag','StaticText19'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.701960784313725 0.701960784313725 0.701960784313725], ... 'ListboxTop',0, ... 'Max',3, ... 'Min',1, ... 'Position',[0.2948717948717949 0.5454545454545455 0.1923076923076923 0.03964059196617336], ... 'String',temp5, ... 'FontUnits','normalized',... 'Style','popupmenu', ... 'Tag','PopupMenu5', ... 'Value',1); if nargout > 0, fig = h0; end function print_info(sS,level,fid) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% check arguments %error(nargchk(1, 2, nargin)) % check no. of input args is correct if ~isstruct(sS), if ~iscell(sS) | ~isstruct(sS{1}), error('Input argument is not a struct or a cell array of structs.') end csS = sS; else csS = {sS}; end if nargin<2 | isempty(level) | isnan(level), level = 1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% print struct information for c=1:length(csS), sS = csS{c}; switch sS.type, case 'som_map', mdim = length(sS.topol.msize); [munits dim] = size(sS.codebook); t = length(sS.trainhist); if t==0, st='uninitialized'; elseif t==1, st = 'initialized'; else st = sprintf('initialized, trained %d times',t-1); end % level 1 fprintf(fid,'%% Struct type : %s\n', sS.type); fprintf(fid,'%% Map name : %s\n', sS.name); fprintf(fid,'%% Input dimension : %d\n', dim); fprintf(fid,'%% Map grid size : '); for i = 1:mdim - 1, fprintf(fid,'%d x ',sS.topol.msize(i)); end fprintf(fid,'%d\n', sS.topol.msize(mdim)); fprintf(fid,'%% Lattice type (rect/hexa) : %s\n', sS.topol.lattice); fprintf(fid,'%% Shape (sheet/cyl/toroid) : %s\n', sS.topol.shape); fprintf(fid,'%% Neighborhood type : %s\n', sS.neigh); fprintf(fid,'%% Mask : '); if dim, for i = 1:dim-1, fprintf(fid,'%d ',sS.mask(i)); end; fprintf(fid,'%d\n',sS.mask(dim)); else fprintf(fid,'%% \n'); end fprintf(fid,'%% Training status : %s\n', st); % level 1, status = cell(dim,1); for i=1:dim, n = length(sS.comp_norm{i}); if n, uninit = strcmp('uninit',{sS.comp_norm{i}.status}); done = strcmp('done',{sS.comp_norm{i}.status}); undone = strcmp('undone',{sS.comp_norm{i}.status}); if sum(uninit)==n, status{i} = 'no normalization'; elseif sum(done)==n, status{i} = 'normalized'; elseif sum(undone)==n, status{i} = 'denormalized'; else status{i} = 'partial'; end else status{i} = 'no normalization'; end end if level>1, fprintf(fid,'%% Vector components\n'); M = sS.codebook; fprintf(fid,'%% # name mask min mean max std status\n'); fprintf(fid,'%% --- ------------ ---- ------ ------ ------ ------ ------\n'); for i = 1:dim, fprintf(fid,'%% %-3d %-12s %-4.2f %6.1g %6.1g %6.1g %6.1g %s\n', ... i,sS.comp_names{i}, sS.mask(i), ... min(M(:,i)),mean(M(:,i)),max(M(:,i)),std(M(:,i)),status{i}); end end % level 3 if level>2, fprintf(fid,'%% Vector component normalizations\n'); fprintf(fid,'%% # name method (i=uninit,u=undone,d=done)\n'); fprintf(fid,'%% --- ------------ ---------------------------------------\n'); for i=1:dim, fprintf(fid,'%% %-3d %-12s ',i,sS.comp_names{i}); n = length(sS.comp_norm{i}); for j=1:n, m = sS.comp_norm{i}(j).method; s = sS.comp_norm{i}(j).status; if strcmp(s,'uninit'), c='i'; elseif strcmp(s,'undone'), c='u'; else c='d'; end fprintf(fid,'%% %s[%s] ',m,c); end fprintf(fid,'%% \n'); end end % level 4 if level>3, fprintf(fid,'%% Training history\n'); for i=1:t, sT = sS.trainhist(i); fprintf(fid,'%% * Algorithm: %8s Data: %13s Trainlen: %8d\n',... sT.algorithm,sT.data_name,sT.trainlen); %if i>1, fprintf(fid,'%% Neighborh: %8s Mask: ',sT.neigh); for i = 1:dim-1, fprintf(fid,'%% %d ',sT.mask(i)); end; fprintf(fid,'%% %d\n',sT.mask(mdim)); fprintf(fid,'%% Radius: %4.2f->%4.2f Alpha: %5.3f (%s)\n', ... sT.radius_ini,sT.radius_fin,sT.alpha_ini,sT.alpha_type); %end fprintf(fid,'%% Time: %s\n',sT.time); end end case 'som_data', [dlen dim] = size(sS.data); if dlen*dim ind = find(~isnan(sum(sS.data),2)); else ind = []; end complete = size(sS.data(ind,:),1); partial = dlen - complete; values = prod(size(sS.data)); missing = sum(sum(isnan(sS.data))); % level 1 fprintf(fid,'%% Struct type : %s\n', sS.type); fprintf(fid,'%% Data name : %s\n', sS.name); fprintf(fid,'%% Vector dimension : %d\n', dim); fprintf(fid,'%% Number of data vectors : %d\n', dlen); fprintf(fid,'%% Complete data vectors : %d\n', complete); fprintf(fid,'%% Partial data vectors : %d\n', partial); if values, r = floor(100 * (values - missing) / values); else r = 0; end fprintf(fid,'%% Complete values : %d of %d (%d%%)\n', ... values-missing, values, r); % level 2, status = cell(dim,1); for i=1:dim, n = length(sS.comp_norm{i}); if n, uninit = strcmp('uninit',{sS.comp_norm{i}.status}); done = strcmp('done',{sS.comp_norm{i}.status}); undone = strcmp('undone',{sS.comp_norm{i}.status}); if sum(uninit)==n, status{i} = 'no normalization'; elseif sum(done)==n, status{i} = 'normalized'; elseif sum(undone)==n, status{i} = 'denormalized'; else status{i} = 'partial'; end else status{i} = 'no normalization'; end end if level>1, fprintf(fid,'%% Vector components\n'); D = sS.data; fprintf(fid,'%% # name min mean max std missing status\n'); fprintf(fid,'%% --- ------------ ------ ------ ------ ------ ----------- ------\n'); for i = 1:dim, known = find(~isnan(D(:,i))); miss = dlen-length(known); fprintf(fid,'%% %-3d %-12s %6.1g %6.1g %6.1g %6.1g %5d (%2d%%) %s\n', ... i,sS.comp_names{i}, ... min(D(known,i)),mean(D(known,i)),max(D(known,i)),std(D(known,i)), ... miss,floor(100*miss/dlen),status{i}); end end % level 3 if level>2, fprintf(fid,'%% Vector component normalizations\n'); fprintf(fid,'%% # name method (i=uninit,u=undone,d=done)\n'); fprintf(fid,'%% --- ------------ ---------------------------------------\n'); for i=1:dim, fprintf(fid,'%% %-3d %-12s ',i,sS.comp_names{i}); n = length(sS.comp_norm{i}); for j=1:n, m = sS.comp_norm{i}(j).method; s = sS.comp_norm{i}(j).status; if strcmp(s,'uninit'), c='i'; elseif strcmp(s,'undone'), c='u'; else c='d'; end fprintf(fid,'%% %s[%s] ',m,c); end fprintf(fid,'%% \n'); end end case 'som_topol', mdim = length(sS.msize); % level 1 fprintf(fid,'%% Struct type : %s\n',sS.type); fprintf(fid,'%% Map grid size : '); for i = 1:mdim - 1, fprintf(fid,'%% %d x ',sS.msize(i)); end fprintf(fid,'%% %d\n', sS.msize(mdim)); fprintf(fid,'%% Lattice type (rect/hexa) : %s\n', sS.lattice); fprintf(fid,'%% Shape (sheet/cyl/toroid) : %s\n', sS.shape); case 'som_train', % level 1 fprintf(fid,'%% Struct type : %s\n',sS.type); fprintf(fid,'%% Training algorithm : %s\n',sS.algorithm); fprintf(fid,'%% Training data : %s\n',sS.data_name); fprintf(fid,'%% Neighborhood function : %s\n',sS.neigh); fprintf(fid,'%% Mask : '); dim = length(sS.mask); if dim, for i = 1:dim-1, fprintf(fid,'%% %d ',sS.mask(i)); end; fprintf(fid,'%% %d\n',sS.mask(end)); else fprintf(fid,'%% \n'); end fprintf(fid,'%% Initial radius : %-6.1f\n',sS.radius_ini); fprintf(fid,'%% Final radius : %-6.1f\n',sS.radius_fin); fprintf(fid,'%% Initial learning rate (alpha) : %-6.1f\n',sS.alpha_ini); fprintf(fid,'%% Alpha function type (linear/inv) : %s\n',sS.alpha_type); fprintf(fid,'%% Training length : %d\n',sS.trainlen); fprintf(fid,'%% Average quantization error : %-6.1f\n',sS.qerror); fprintf(fid,'%% When training was done : %s\n',sS.time); case 'som_norm', % level 1 fprintf(fid,'%% Struct type : %s\n',sS.type); fprintf(fid,'%% Normalization method : %s\n',sS.method); fprintf(fid,'%% Status : %s\n',sS.status); % level 2 if level>1, fprintf(fid,'%% Parameters:\n'); sS.params end end end function [] = html2tex(html_addres,texfile) tempfile = tempname; fid = fopen(texfile,'w'); eval(['!lynx -dump ' html_addres ' > ' tempfile]); fid2 = fopen(tempfile,'r'); while not(feof(fid2)) line = fgets(fid2); line = strcat('%',line); fprintf(fid,'%s',line); end fclose(fid); fclose(fid2); delete (tempfile); function [name] = retname resnames = who; if size(resnames,1) > 0 max_length = size(resnames{1},2); for index = 1:size(resnames,1) if size(resnames{index},2) > max_length max_length = size(resnames{index},2); end end length = max_length + 1; name(:,1:1:length) = 'A' else name = 'A'; end %%
github
martinarielhartmann/mirtooloct-master
som_dmatminima.m
.m
mirtooloct-master/somtoolbox/som_dmatminima.m
2,009
utf_8
9e535d4906164073484193ea7ef10560
function minima = som_dmatminima(sM,U,Ne) %SOM_DMATMINIMA Find clusters based on local minima of U-matrix. % % minima = som_dmatminima(sM,[U],[Ne]) % % Input and output arguments ([]'s are optional): % sM (struct) map struct % U (matrix) the distance matrix from which minima is % searched from % size msize(1) x ... x msize(end) or % 2*msize(1)-1 x 2*msize(2)-1 or % munits x 1 % Ne (matrix) neighborhood connections matrix % % minima (vector) indeces of the map units where locla minima of % of U-matrix (or other distance matrix occured) % % See also KMEANS_CLUSTERS, SOM_CLLINKAGE, SOM_CLSTRUCT. % Copyright (c) 2000 by Juha Vesanto % Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 220800 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % map if isstruct(sM), switch sM.type, case 'som_map', M = sM.codebook; mask = sM.mask; case 'som_data', M = sM.data; mask = ones(size(M,2),1); end else M = sM; mask = ones(size(M,2),1); end [munits dim] = size(M); % distances between map units if nargin<2, U = []; end % neighborhoods if nargin<3, Ne = som_neighbors(sM); end % distance matrix if nargin<2 | isempty(U), U = som_dmat(sM,Ne,'median'); end if prod(size(U))>munits, U = U(1:2:size(U,1),1:2:size(U,2)); end U = U(:); if length(U) ~= munits, error('Distance matrix has incorrect size.'); end % find local minima minima = []; for i=1:munits, ne = find(Ne(i,:)); if all(U(i)<=U(ne)) & ~anycommon(ne,minima), minima(end+1)=i; end end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function t = anycommon(i1,i2) if isempty(i1) | isempty(i2), t = 0; else m = max(max(i1),max(i2)); t = any(sparse(i1,1,1,m,1) & sparse(i2,1,1,m,1)); end return;
github
martinarielhartmann/mirtooloct-master
som_stats_table.m
.m
mirtooloct-master/somtoolbox/som_stats_table.m
3,684
utf_8
0dec0a499ac0af8b81c9d1eae7c1e819
function [sTstats,csThist] = som_stats_table(csS,histlabel) %SOM_STATS_TABLE Statistics table. % % [sTstats,csThist] = som_stats_table(csS) % % sTstats = som_stats_table(csS); % som_table_print(sTstats); % % Input and output arguments ([]'s are optional): % csS (cell array) of statistics structs % (struct) a statistics struct % % sTstats (struct) a table struct with basic descriptive % statistics for each variable % csThist (cell array) of table structs, with histograms for % each variable % % See also SOM_STATS, SOM_STATS_PLOT, SOM_TABLE_PRINT, SOM_STATS_REPORT. % Contributed to SOM Toolbox 2.0, December 31st, 2001 by Juha Vesanto % Copyright (c) by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 311201 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% arguments if isstruct(csS), csS = {csS}; end dim = length(csS); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 %% action sTable = struct('colfmt','','headers',[],'values',[],'span',[]); % summary table of all variables sT = sTable; sT.headers = {'name','min','mean','max','std','missing'}; if ~isnan(csS{1}.nunique), sT.headers{end+1} = 'unique'; end %if length(col_values), sT.headers = [sT.headers, col_headers]; end sT.values = cell(dim,length(sT.headers)); sT.span = ones([size(sT.values) 2]); %if length(col_values), sT.values(:,end-size(col_values,2)+1:end) = col_values; end %if length(col_spans), sT.span(:,end-size(col_spans,2)+1:end,:) = col_spans; end for i=1:dim, sT.values{i,1} = csS{i}.name; v = [csS{i}.min,csS{i}.mean,csS{i}.max,csS{i}.std]; v = som_denormalize(v,csS{i}.normalization); vstr = numtostring(v,6); sT.values(i,2:5) = vstr'; sT.values{i,6} = c_and_p_str(csS{i}.ntotal-csS{i}.nvalid,csS{i}.ntotal); if ~isnan(csS{1}.nunique), sT.values{i,7} = c_and_p_str(csS{i}.nunique,csS{i}.nvalid); end end sTstats = sT; % histograms csThist = cell(dim,1); for i=1:dim, sH = csS{i}.hist; nvalid = csS{i}.nvalid; nbins = length(sH.bins); sT = sTable; sT.headers = {[csS{i}.name ' values'],'frequency #','frequency %'}; sT.values = cell(nbins,length(sT.headers)); sT.span = ones(nbins,length(sT.headers),2); for j=1:nbins, if length(sH.bins) < csS{i}.nunique, sT.values{j,1} = sH.binlabels2{j}; else sT.values{j,1} = sH.binlabels{j}; end sT.values{j,2} = sprintf('%d',round(sH.counts(j))); sT.values{j,3} = p_str(sH.counts(j)/nvalid); end csThist{i} = sT; end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 %% subfunctions function vstr = numtostring(v,d) tp = (size(v,2)>1); if tp, v = v'; end nearzero = (abs(v)/(max(v)-min(v)) < 10.^-d); i1 = find(v > 0 & nearzero); i2 = find(v < 0 & nearzero); vstr = strrep(cellstr(num2str(v,d)),' ',''); vstr(i1) = {'0.0'}; vstr(i2) = {'-0.0'}; if tp, vstr = vstr'; end return; function str = c_and_p_str(n,m) % return a string of form # (%), e.g. '23 (12%)' if n==m, p = '100'; elseif n==0, p = '0'; else p = sprintf('%.2g',100*n/m); end str = sprintf('%d (%s%%)',round(n),p); return; function str = p_str(p) % return a string of form %, e.g. '12%' if round(p*100)>100, p = sprintf('%3g',100*p); elseif p==1, p = '100'; elseif abs(p)<eps, p = '0'; else p = sprintf('%.2g',100*p); end str = sprintf('%s%%',p); return;
github
martinarielhartmann/mirtooloct-master
som_barplane.m
.m
mirtooloct-master/somtoolbox/som_barplane.m
13,935
utf_8
75467b21870c4a890f9d50bd7db8c647
function h = som_barplane(varargin) %SOM_BARPLANE Visualize the map prototype vectors as bar charts % % h = som_barplane(lattice, msize, data, [color], [scaling], [gap], [pos]) % h = som_barplane(topol, data, [color], [scaling], [gap], [pos]) % % som_barplane('hexa',[5 5], rand(25,4), jet(4)) % som_barplane(sM, sM.codebook,'none') % % Input and output argumetns ([]'s are optional): % lattice (string) grid 'hexa' or 'rect' % msize (vector) size 1x2, defines the map grid size msize, M=prod(msize) % (matrix) size Mx2, gives explicit coordinates for each node: % in this case the first argument does not matter. % topol (struct) map or topology struct % data (matrix) size Mxd, each row defines heights of the bars % [color] (matrix) size dx3, of RGB triples. The rows define colors % for each bar in a node. Default is hsv(d). A ColorSpec or % (string) A ColorSpec or 'none' gives each bar the same color. % [scaling] (string) 'none', 'unitwise' or 'varwise'. The scaling % mode for the values. Default is 'varwise'. % [gap] (scalar) Defines the gap between bars, limits: 0 <= gap <= 1 % where 0=no gap, 1=bars are thin lines. Default is 0.25. % [pos] (vector) 1x2 vector defines the position of origin. % Default is [1 1]. % % h (scalar) the object handle to the PATCH object % % Axis are set as in SOM_CPLANE. % % For more help, try 'type som_barplane' or check out online documentation. % See also SOM_CPLANE, SOM_PLOTPLANE, SOM_PIEPLANE. %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_barplane % % PURPOSE % % Visualizes the map prototype vectors as bar charts. % % SYNTAX % % h = som_barplane(topol, data) % h = som_barplane(lattice, msize, data) % h = som_barplane(..., color) % h = som_barplane(..., color, scaling) % h = som_barplane(..., color, scaling, gap) % h = som_barplane(..., color, scaling, gap, pos) % % DESCRIPTION % % Visualizes the map prototype vectors as bar charts. % % REQUIRED INPUT ARGUMENTS % % lattice The basic shape of the map units % (string) 'hexa' or 'rect' positions the bar charts according to % hexagonal or rectangular map lattice % % msize The size of the map grid % (vector) [n1 n2] vector defines the map size (height: n1 units widht: n2 % units, total: M=n1xn2 units). The units will be placed to their % topological locations in order to form a uniform hexagonal or % rectangular grid. % (matrix) Mx2 matrix defines arbitary coordinates for the N units. In % this case the argument 'lattice' has no effect % % topol Topology of the map grid % % (struct) map or topology struct from which the topology is taken % % data The data to use when constructing the bar charts. % Typically, the map codebook or some of its components. % (matrix) Mxd matrix. A row defines heights of the bars. % % OPTIONAL INPUT ARGUMENTS % % Note: if unspecified or given an empty value ('' or []), default % values are used for optional input arguments. % % color The color of the bars in each pie % (ColorSpec) or (string) 'none' gives the same color for each slice. % (matrix) dx3 matrix assigns an RGB color determined by the dth row of % the matrix to the dth bar (variable) in each bar plot. % Default value is hsv(d). % % scaling How to scale the values % (string) 'none', 'unitwise' or 'varwise'. This determines the % scaling of codebook values when drawing the bars. % % 'none' don't scale at all. The bars are not limited % to remain inside he units' area: That is, if value of % some variable exceeds [-.625,.625] for 'rect' (and % in "worst case" [-.5,-.5] for 'hexa') the bars may % overlap other units. % % Base line (zero value line) % - is in the middle of the unit if data (codebook) contains both % negative and positive values (or is completely zero). % - is in the top the unit if data (codebook) contains only % non-positive values (everything <=0). % - is in the bottom the unit if data (codebook) contains only % non-negative values (everything >=0). % % 'varwise' scales values so that each variable is scaled separately % so that when it gets its overall maximum value, the % corresponding bar gets maximum range and for minimum value % it gets the minimum range. Baseline: see scaling 'none' % This is the default. % % 'unitwise' scales values in each unit individually so that the % bars for variables having minimum and maximum values have minimum % and maximum range inside each unit, respectively. % In this case the zero value line may move depending on the values. % % gap The gap between bars % (scalar) 0: no gap: bars are glued together % ... default value is 0.25 % 1: maximum gap: bars are thin lines % % pos Position of origin % (vector) size 1x2. This is meant for drawing the plane in arbitrary % location in a figure. Note the operation: if this argument is % given, the axis limits setting part in the routine is skipped and % the limits setting will be left to be done by MATLAB's defaults. % Default is [1 1]. % % OUTPUT ARGUMENTS % % h (scalar) handle to the created patch object % % OBJECT TAGS % % One object handle is returned: field Tag is set to 'planeBar' % % FEATURES % % - The colors are fixed: changing colormap in the figure (see help % colormap) will not change the coloring of the bars. % % EXAMPLES % % %%% Create the data and make a map % % data=rand(100,5); map=som_make(data); % % %%% Create a 'jet' colormap that has as many rows as the data has variables % % colors=jet(5); % % %%% Draw bars % % som_barplane(map.topol.lattice, map.topol.msize, map.codebook, colors); % or som_barplane(map.topol, map.codebook, colors); % or som_barplane(map, map.codebook, colors); % % %%% Draw the bars so that the gap between the bars is bigger and all % bars are black % % som_barplane(map, map.codebook, 'k', '', 0.6); % % SEE ALSO % % som_cplane Visualize a 2D component plane, u-matrix or color plane % som_plotplane Visualize the map prototype vectors as line graphs % som_pieplane Visualize the map prototype vectors as pie charts % Copyright (c) 1999-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta Juha P 110599, Johan 140799, juuso 151199 140300 070600 %%% Check & Init arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [nargin, lattice, msize, data, color, scaling, gap, pos] = vis_planeGetArgs(varargin{:}); error(nargchk(3, 7, nargin)) % check that no. of input args is correct % Check pos if nargin < 7 | isempty(pos) pos=NaN; % default value for pos (no translation) elseif ~vis_valuetype(pos,{'1x2'}) error('Position of origin has to be given as an 1x2 vector'); end % Check gap if nargin < 6 | isempty(gap), gap=0.25; % default value for gap elseif ~vis_valuetype(gap, {'1x1'}), error('Gap value must be scalar.'); elseif ~(gap >= 0 & gap<=1) error('Gap value must be in interval [0,1].') end % Check scaling if nargin < 5 | isempty(scaling), scaling='varwise'; elseif ~vis_valuetype(scaling,{'string'}) | ... ~any(strcmp(scaling,{'none','unitwise','varwise'})), error('scaling sholud be ''none'', ''unitwise'' or ''varwise''.'); end % Check msize if ~vis_valuetype(msize,{'1x2','nx2'}), error('msize has to be 1x2 grid size vector or a Nx2 coordinate matrix.'); end % Check data if ~isnumeric(data), error('Data matrix has to be numeric.'); elseif length(size((data)))>2 error('Data matrix has too many dimensions!'); else d=size(data,2); N=size(data,1); end s=.8; % patch size scaling factor switch scaling, case 'none' % no scaling: don't scale % Check data max and min values positive=any(data(:)>0); negative=any(data(:)<0); if (positive & negative) | (~positive & ~negative), % Data contains both negative and positive values (or is % completely zero) baseline to centre zeroline='zero'; elseif positive & ~negative % Data contains only positive values: baseline to bottom zeroline='bottom'; elseif ~positive & negative % Data contains only negative values: baseline to top zeroline='top'; end case 'unitwise' % scale the variables so that the bar for variable with the maximum % value in the unit spans to the upper edge of the unit % and the bar for the variable with minimum value spans to the lower edge, % respectively. zeroline='moving'; case 'varwise' % Check data max and min values positive=any(data(:)>0); negative=any(data(:)<0); if (positive & negative) | (~positive & ~negative), % Data contains both negative and positive values (or is % completely zero) baseline to % centre, scale data so that it doesn't overflow data=data./repmat(max(abs([max(data); min(data)])),N,1)*.5; zeroline='zero'; elseif positive & ~negative % Data contains only positive values: baseline to % bottom, scale data so that it doesn't overflow data=data./repmat(max(abs([max(data); min(data)])),N,1)*.5; zeroline='bottom'; elseif ~positive & negative % Data contains only negative values: baseline to % top, scale data so that it doesn't overflow zeroline='top'; data=data./repmat(max(abs([max(data); min(data)])),N,1)*.5; end otherwise error('Unknown scaling mode?'); end for i=1:N, % calculate patch coordinates for v=data(i,:); [nx,ny]=vis_barpatch(v,gap,zeroline); % bars barx(:,(1+(i-1)*d):(i*d))=s*nx; bary(:,(1+(i-1)*d):(i*d))=s*ny; end l=size(barx,1); if size(msize,1) == 1, xdim=msize(2); ydim=msize(1); if xdim*ydim~=N error('Data matrix has wrong size.'); else y=reshape(repmat(1:ydim,d,1),1,d*ydim); y=repmat(repmat(y,l,1),1,xdim); x=reshape(repmat(1:xdim,l*ydim*d,1),l,N*d); end else x=reshape(repmat(msize(:,1),1,l*d)',l,d*N); y=reshape(repmat(msize(:,2),1,l*d)',l,d*N); if N ~= size(msize,1), error('Data matrix has wrong size.'); else lattice='rect'; if isnan(pos), pos=[0 0]; end end end % Check lattice if ~ischar(lattice) error('Invalid lattice.'); end switch lattice case {'hexa','rect'} pos=pos-1; otherwise error([ 'Lattice' lattice ' not implemented!']); end % Check color % C_FLAG is for color 'none' if nargin < 4 | isempty(color) color=hsv(d); % default n hsv colors end if ~vis_valuetype(color, {[d 3],'nx3rgb'},'all') & ... ~vis_valuetype(color,{'colorstyle','1x3rgb'}) error('The color matrix has wrong size or has invalid values.'); elseif ischar(color) & strcmp(color,'none') C_FLAG=1; color='w'; else C_FLAG=0; end %% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Making lattice. % Command view([0 90]) shows the map in 2D properly oriented switch lattice case 'hexa' t=find(rem(y(1,:),2)); % move even rows by .5 x(:,t)=x(:,t)-.5; x=x+barx+.5; y=y+bary; case 'rect' x=x+barx; y=y+bary; end % NB: The coordinates in hexa are not uniform in order to get even % y-coordinates for the nodes. This is handled by setting _axis scaling_ % so that the hexa-nodes look like uniform hexagonals. See % vis_PlaneAxisProperties if ~isnan(pos) x=x+pos(1);y=y+pos(2); % move upper left corner end % to pos %% Set axes properties ax=newplot; % get current axis vis_PlaneAxisProperties(ax,lattice, msize, pos); %% Rearrange dx3 color matrix if ~isstr(color) & size(color,1)~=1, color=reshape(repmat(color,N,1),[1 N*d 3]); end %% Draw the plane! if isnumeric(color), % explicit color settings by RGB-triplets won't work with % patch in 'painters' mode, unless there only a single triplet si = size(color); if length(si)~=2 | any(si==[1 3]), set(gcf,'renderer','zbuffer'); end end h_=patch(x,y,color); if C_FLAG set(h_,'FaceColor','none'); end set(h_,'Tag','planeBar'); % tag the object %%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargout>0, h=h_; end % Set h only if % there really is output %%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [xcoord,ycoord]=vis_barpatch(y,gap,zeroline) x = length(y); d = gap/(2*(x-1)+2); step= -.5:1/x:.5; miny=min(y); maxy=max(y); switch(zeroline) case 'moving' if miny < 0 if maxy > 0 zl = .5 - (abs(miny)/(maxy-miny)); %reverse mode y= .5 - ((y-miny*ones(1,x))./(maxy-miny)); else zl = -.5; y=-.5+abs(y./miny); end else zl = .5; %reverse mode y=.5-y./maxy; end case 'moveNotScale' if miny < 0 if maxy > 0 zl = 0.5+miny; y = zl - y; else zl=-.5; y=-.5+abs(y); end else zl=.5; y =.5-y; end case 'zero' zl=0; y=zl-y; case 'top' zl=-.5; y=zl-2*y; case 'bottom' zl=.5; y=zl-2*y; end for i=1:x xcoord(:,i) = [d+step(i);d+step(i);step(i+1)-d;step(i+1)-d;d+step(i)]; ycoord(:,i) = [zl;y(i);y(i);zl;zl]; end
github
martinarielhartmann/mirtooloct-master
som_recolorbar.m
.m
mirtooloct-master/somtoolbox/som_recolorbar.m
12,433
utf_8
f6539ba0228a1c13d3b9e317d75ddabf
function h=som_recolorbar(p, ticks, scale, labels) %SOM_RECOLORBAR Refresh and rescale colorbars in the current SOM_SHOW fig. % % h = som_recolorbar([p], [ticks], [scaling], [labels]) % % colormap(jet); som_recolorbar % % Input and output arguments ([]'s are optional) % [p] (vector) subplot number vector % (string) 'all' (the default), 'comp' to process only % component planes % [ticks] (string) 'auto' or 'border', default: 'auto' % (cell array) p x 1 cell array of p row vectors % (vector) the same ticks are applied to all given subplots % (scalar) value is at least 2: the number of ticks to show, % evenly spaced between and including minimum and maximum % [scale] (string) 'denormalized' or 'normalized' (the default) % [labels] (cell array) p x 1 cell array of cells containing strings % % h (vector) handles to the colorbar objects. % % This function refreshes the colorbars in the figure created by SOM_SHOW. % Refreshing is necessary if you have changed the colormap. % Each colorbar has letter 'd' or 'n' and possibly 'u' as label. Letter 'd' means % that the scale is denormalized, letter 'n' that the scale is % normalized, and 'u' is for user specified labels. % % For more help, try 'type som_recolorbar' or check out online documentation. % See also SOM_SHOW %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_recolorbar % % PURPOSE % % Refreshes the the colorbars in the figure. % % SYNTAX % % h = som_recolorbar % h = som_recolorbar(p) % h = som_recolorbar(p, ticks) % h = som_recolorbar(p, ticks, scaling) % h = som_recolorbar(p, ticks, scaling, labels) % % DESCRIPTION % % This function refreshes the colorbars in the figure created by SOM_SHOW. % Refreshing is necessary if you have changed the colormap. Each colorbar % has letter 'd' or 'n' and possibly 'u' as label. Letter 'd' means that the % scale is denormalized, letter 'n' that the scale is normalized, and 'u' is % for user specified labels. % % Different argument combinations: % % 1. Argument 'ticks' has string values: % - 'auto' for input argument ticks sets the automatic tick % marking on (factory default). % - 'border' sets the tick marks to the color borders. This is % convenient if there are only few colors in use. % % Argument scale controls the scaling of the tick mark label values. % 'normalized' means that the tick mark labels are directly the values % of the ticks, that is, they refer to the map codebook values. % Value 'denormalized' scales the tick mark label values back to the original % data scaling. This is made using som_denormalize_data. % % 2. Argument 'ticks' is a cell array of vectors: % The values are set to be the tick marks to the colorbar specified by p. % - if arg. scale is 'normalized' the ticks are set directly to the colorbar. % - if arg. scale is 'denormalized' the tick values are first normalized % in the same way as the data. % % 3. Argument 'ticks' is a vector % As above, but the same values are used for all (given) subplots. % % 4. Argument 'ticks' is a scalar % The ticks are set to equally spaced values between (and including) % minimum and maximum. % % Argument 'labels' specify user defined labels to the tick marks % % NOTE: ticks are rounded to contain three significant digits. % % OPTIONAL INPUT ARGUMENTS % % p (vector) subplot number vector % (string) 'all' (the default), 'comp' to effect only % component planes % % ticks (string) 'auto' or 'border', default: 'auto' % (cell array) p x 1 cell array of p row vectors % (vector) as the cell array, but the same vector is % applied to all given subplots % (scalar) the number of ticks to show: these are % evenly space between minimum and maximum % % scale (string) 'denormalized' or 'normalized' (the default) % % labels (cell array) p x 1 cell array of cells containing strings % % OUTPUT ARGUMENTS % % h (vector) handles to the colorbar objects. % % EXAMPLE % % colormap(jet(5)); som_recolorbar('all','border','denormalized') % % Uses five colors and sets the ticks on the color borders. % % Tick label values are denormalized back to the original data scaling % % colormap(copper(64));som_recolorbar % % changes to colormap copper and resets default ticking and labeling % % som_recolorbar('all',3) % % To put 3 ticks to each colorbar so that minimum, mean and % % maximum values on the colorbar are shown. % % som_recolorbar([1 3],{[0.1 0.2 0.3];[0.2 0.4]},'denormalized') % % Ticks colorbar 1 by first normalizing values 0.1, 0.2, 0.3 and % % then setting the ticks to the colorbar. Labels are of course % % 0.1, 0.2 and 0.3. Ticks colorbar 3 in the same way using values % % 0.2 and 0.4. % % som_recolorbar([2 4],{[0.1 0.2];[-1.2 3]},'normalized',{{'1' '2'};{'a' 'b'}}) % % Ticks colorbar 2 and 4 directly to the specified values. Sets labels % % '1' '2' and 'a' 'b' to the ticks. % % som_recolorbar([2 4],{[0.1 0.2];[-1.2 3]},'normalized',{{'1' '2'};{'a' 'b'}}) % % as previous one, but normalizes tick values first % % SEE ALSO % % som_show Basic SOM visualization. % som_normalize Normalization operations. % som_denormalize Denormalization operations. % Copyright (c) 1997-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 1.0beta Johan 061197 % Version 2.0beta juuso 151199 130300 160600 181101 %% Init & check %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% error(nargchk(0, 4, nargin)) % check no. of input args % Check the subplot vector p and get the handles, exit if error % Default subplot vector is 'all' if nargin < 1 | isempty(p) % default p p= 'all'; end % check SOM_SHOW and get the figure data. Exit, if error [handles, msg, lattice, msize, dim, normalization, comps]= ... vis_som_show_data(p, gcf); error(msg); if nargin < 2 | isempty(ticks) % default tick mode is 'auto' ticks = 'auto'; elseif isa(ticks,'cell') % check for cell tickValues = ticks; ticks= 'explicit'; elseif isa(ticks,'double') & length(ticks)>1, tickValues = {ticks}; ticks = 'explicit'; elseif isa(ticks,'double') & length(ticks)==1, tickValues = max(2,round(ticks)); ticks = 'evenspace'; end if ~ischar(ticks) % invalid argument error('The second argument should be a string or a cell array of vectors.'); end switch ticks % check ticks case {'auto','border'}, % nill case 'evenspace', tickValues_tmp = cell(length(handles),1); for i=1:length(handles), tickValues_tmp{i} = tickValues; end tickValues = tickValues_tmp; case 'explicit', if length(tickValues)==1 & length(handles)>1, tickValues_tmp = cell(length(handles),1); for i=1:length(handles), tickValues_tmp{i} = tickValues{1}; end tickValues = tickValues_tmp; end if length(tickValues) ~= length(handles), error('Cell containing the ticks has wrong size.') end otherwise error('''auto'' or ''border'' expected for the second argument.'); end if nargin < 3 | isempty(scale) % default mode is normalized scale= 'normalized'; end if ~ischar(scale) % check scale type error('The third argument should be a string.'); end switch scale % check the string case { 'normalized', 'denormalized'} % ok case 'n', scale = 'normalized'; case 'd', scale = 'denormalized'; otherwise error('''normalized'' or ''denormalized'' expected for the third argument.') end if nargin < 4 | isempty(labels) % default is autolabeling labels = 'auto'; elseif ~isa(labels,'cell') % check type error('The fourth argument should be a cell array of cells containing strings.') else labelValues=labels; % set labels labels = 'explicit'; if length(labelValues) == length(handles) % check size ; else error('Cell containing the labels has wrong size') end end %% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% n = size(colormap,1)+1; % number of colors+1 h_ = zeros(length(handles),1); for i=1:length(handles), % MAIN LOOP BEGINS axes(handles(i)); % set axes, refres colorbar and if comps(i)>=0, h_(i)=colorbar; % get colorbar handles colorbardir=get(h_(i),'YaxisLocation'); switch colorbardir % get colorbar direction & case 'left' % set some strings Tick='Xtick'; Lim='Xlim'; LabelMode='XTickLabelMode'; Label='XtickLabel'; case 'right' Tick='Ytick'; Lim='Ylim'; LabelMode='YTickLabelMode'; Label='YtickLabel'; otherwise error('Internal error: unknown value for YaxisLocation'); % fatal end switch ticks case 'auto' set(h_(i),LabelMode,'auto'); % factory default ticking tickValues{i}=get(h_(i),Tick); % get tick values case 'border' limit=caxis; t=linspace(limit(1),limit(2),n); % set n ticks between min and max t([1 length(t)])=get(h_(i),Lim); % <- caxis is not necerraily the same tickValues{i}=t; % as the colorbar min & max values case 'evenspace' limit = caxis; t = linspace(limit(1),limit(2),tickValues{i}); t([1 length(t)])=get(h_(i),Lim); tickValues{i}=t; case 'explicit' if comps(i)>0, if strcmp(scale,'normalized') % normalize tick values tickValues{i} = som_normalize(tickValues{i},normalization{comps(i)}); end end otherwise error('Internal error: unknown tick type') % this shouldn't happen end %tickValues{i} = epsto0(tickValues{i}); switch labels case 'auto' switch scale case 'normalized' labelValues{i} = round2(tickValues{i}); % use the raw ones case 'denormalized' % denormalize tick values if comps(i)>0, labelValues{i} = som_denormalize(tickValues{i},normalization{comps(i)}); labelValues{i} = round2(labelValues{i}); % round the scale else labelValues{i} = round2(tickValues{i}); end otherwise error('Internal error: unknown scale type'); % this shouldn't happen end case 'explicit' ; % they are there already otherwise error('Internal error: unknown label type'); % this shouldn't happen end set(h_(i),Tick,tickValues{i}); % set ticks and labels set(h_(i),Label,labelValues{i}); if comps(i)>0, % Label the colorbar with letter 'n' if normalized, with letter 'd' % if denormalized and 'u' if the labels are user specified mem_axes=gca; axes(h_(i)); ch=' '; if strcmp(scale,'normalized'), ch(1)='n'; end if strcmp(scale,'denormalized'), ch(1)='d'; end if strcmp(labels,'explicit'), ch(2)='u'; end xlabel(ch); axes(mem_axes); end end end % MAIN LOOP ENDS %% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargout>0 h=h_; end return; %% Subfunction: ROUND2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ROUND2 rounds the labels to tol significant digits function r=round2(d) tol=3; zero=(d==0); d(zero)=1; k=floor(log10(abs(d)))-(tol-1); r=round(d./10.^k).*10.^k; r(zero)=0; %r=epsto0(r); %% Subfunction: ISVECTOR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function t=isvector(v) % ISVECTOR checks if a matrix is a vector or not t=(ndims(v) == 2 & min(size(v)) == 1) & isnumeric(v); %% Subfunction: EPSTO0 function t=epsto0(t) % EPSTO0 checks whether first tick value is *very* close to zero, % if so sets it to zero. if (t(end)-t(1))/t(end) > 1-0.005 & abs(t(1))<1, t(1) = 0; end
github
martinarielhartmann/mirtooloct-master
som_show.m
.m
mirtooloct-master/somtoolbox/som_show.m
28,122
utf_8
d4dcabfc93b9206fb6cb14eeffb497f1
function h=som_show(sMap, varargin) % SOM_SHOW Basic SOM visualizations: component planes, u-matrix etc. % % h = som_show(sMap, ['argID', value, ...]) % % som_show(sMap); % som_show(sMap,'bar','none'); % som_show(sMap,'comp',[1:3],'umat','all'); % som_show(sMap,'comp',[1 2],'umat',{[1 2],'1,2 only'},'comp',[3:6]); % som_show(sMap,'size',m,'bar','vert','edge','off'); % % Input and output arguments ([]'s are optional): % sMap (struct) map struct % [argID, (string) Additional parameters are given as argID, value % value] (varies) pairs. See below for list of valid IDs and values. % % h (struct) struct with the following fields: % .plane (vector) handles to the axes objecets (subplots) % .colorbar (vector) handles to the colorbars. Colorbars for empty % grids & RGB color planes do not exist: the % value for them in the vector is -1. % .label (vector) handles to the axis labels % % Here are the valid argument IDs and corresponding values. M is % the number of map units % 'comp' Which component planes to draw, title is % the name of the component (from sMap.comp_names) % (vector) a vector of component indices % (string) 'all' (or '' or []) for all components % 'compi' as 'comp' but uses interpolated shading % 'umat' Show u-matrix calculated using specified % components % (vector) a vector of component indeces % (string) 'all' (or '' or []) to use all components % (cell) of form {v, str} uses v as the vector, and put % str as title instead of the default 'U-matrix' % 'umati' as 'umat' but uses interpolated shading of colors % 'empty' (string) Make an empty plane using given string as title % 'color' Set arbitrary unit colors explicitly % (matrix) size Mx1 or Mx3, Mx1 matrix uses indexed % coloring; Mx3 matrix (RGB triples as rows) % defines fixed unit colors % (cell) of from {color, str}. 'color' is the Mx1 % or Mx3 RGB triple matrix and 'str' is title % string % 'colori' as 'color' but uses interpolated shading of colors % 'norm' (string) 'n' or 'd': Whether to show normalized 'n' or % denormalized 'd' data values on the % colorbar. By default denormalized values are used. % 'bar' (string) Colorbar direction: 'horiz', 'vert' (default) % or 'none' % 'size' size of the units % (scalar) same size for each unit, default is 1 % (vector) size Mx1, individual size for each unit % 'edge' (string) Unit edges on component planes 'on' % (default) or 'off' % 'footnote' (string) Footnote string, sMap.name by default % 'colormap' (matrix) user defined colormap % 'subplots' (vector) size 1 x 2, the number of subplots in y- and % and x-directions (as in SUBPLOT command) % % If identifiers 'comp', 'compi', 'umat', 'umati', 'color', 'colori' % or 'empty' are not specified at all, e.g. som_show(sMap) or % som_show(sMap,'bar','none'), the U-matrix and all component planes % are shown. % % For more help, try 'type som_show' or check out online documentation. % See also SOM_SHOW_ADD, SOM_SHOW_CLEAR, SOM_UMAT, SOM_CPLANE, SOM_GRID. %%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_show % % PURPOSE % % Shows basic visualizations of SOM: component planes, unified distance % matrices as well as empty planes and fixed color planes. % % SYNTAX % % h = som_show(sMap) % h = som_show(sMap, 'argID', value, ...) % % DESCRIPTION % % This function is used for basic visualization of the SOM. Four % kinds of SOM planes can be shown: % % 1. U-matrix (see SOM_UMAT) which shows clustering structure of % the SOM. Either all or just part of the components can % be used in calculating the U-matrix. % 2. component planes: each component plane shows the values of % one variable in each map unit % 3. an empty plane which may be used as a base for, e.g., hit % histogram visualization or labeling (see SOM_SHOW_ADD) % 4. a fixed or indexed color representation for showing color coding or % clustering % % The component planes and u-matrices may have colorbars showing the % scale for the variable. The scale shows by default the values that % variables have in the map struct. It may be changed to show the % original data values (estimated by SOM_DENORMALIZE). In this case a % small 'd' appears below the colorbar. The orientation of these % colorbars may be changed, or they can be removed. % % By default the u-matrix - calculated using all variables - and all % component planes are shown. This is achieved by giving command % som_show(sMap) without any further arguments % % REQUIRED INPUT ARGUMENTS % % sMap (struct) Map to be shown. If only this argument is % specified, the function draws first the u-matrix % calculated using all the variables followed by all % the component planes. % % OPTIONAL INPUT ARGUMENTS % % (M is the number of map units) % % Optional arguments must be given as 'argID',value -pairs % % 'comp' Defines the variabels to be shown as component planes. % (vector) 1xN or Nx1 vector with integer positive numbers ranging % from 1 to the number of variables in the map codebook % (dim). This vector determines the variables to be show % as component planes and their order. Note that the same % component plane (the same variable index) is allowed to % occur several times. % (string) 'all' or '' or []. This uses all variables, that is, it's % the same that using value [1:dim] where dim is the % number of variables in the codebook. % % 'compi' Same as 'comp' but uses a Gouraud shaded color plane % (made using SOM_GRID function) instead of the cell-like % visualization of 'comp' (made using SOM_CPLANE). Note % that the color interpolation doesn't work strictly % correctly on 'hexa' grid, as it uses rectangular grid % (see SURF). % % 'umat' Show U-matrix: value defines the variables to be used % for calculating a u-matrix. % (vector) as in 'comps'. However, multiple occurences of the % same variable (same variable index) are ignored. % (string) 'all' or '' or []. This uses all variables, that is, % is the same as using value [1:dim] where dim is the % number of variables in the codebook. % (cell) of form {v, str} where v is a valid index vector for 'umat' % (see above) and str is a string that is used as a title % for the u-matrix instead of the default title % 'U-matrix'. This may be useful if several u-matrices % are shown in the same figure. % % 'umati' Same as 'umat' but uses shaded color plane (see 'compi'). % % 'empty' Show an empty plane (patch edges only) % (string) value is used as title % % 'color' Define fixed RGB colors for the map units % (matrix) a Mx3 matrix of RGB triples as rows % (vector) a Mx1 vector of any values: sets indexed coloring using % the current colormap (as SURF does) % (matrix) a Mx3xN matrix of RGB triples as rows. This gives N % color planes. % (matrix) a Mx1xN matrix of any values: sets indexed coloring using % the current colormap (as SURF does). This gives N % color planes. % (cell) of form {rgb, str} where rgb is a Mx3 (xN) matrix of RGB % triples as rows and str is a string that is used as % title(s). % (cell) of form {v, str} where v is a Mx1(xN) matrix of values % and str is a string that is used as title(s). % % 'colori' Same as 'color' but uses shaded color plane (see 'compi'). % % 'norm' Defines whether to use normalized or denormalized % values in the colorbar. If denormalized values are % used, they are acquired from SOM_DENORMALIZE function % using sMap.comp_norm field. % (string) 'd' (default) for denormalized values and 'n' for % normalized values. The corresponding letter appears % below the colorbar. % % 'bar' Define the direction of the colorbars for component planes % and U-matrices or turn them completely off. % (string) 'vert' (default), 'horiz' or 'none'. 'vert' gives % vertical and 'horiz' horizontal colorbars. 'none' % shows no colorbars at all. % % 'size' Define sizes of the units. % (scalar) all units have the same size (1 by default) % (vector) size Mx1, each unit gets individual size scaling % (as in SOM_CPLANE) % % 'edge' Unit edges on component plane visualizations. % (string) 'on' or 'off' determines whether the unit edges on component % planes ('comp') are shown or not. Default is 'off'. Note that % U-matrix and color planes are _always_ drawn without edges. % % 'footnote' Text on the figure % (string) is printed as a movable text object on the figure % where it may be moved using mouse. Default value is the % string in the sMap.name field. Note: value [] gives the % string, but input value '' gives no footnote a all. % See VIS_FOOTNOTE for more information on the text object % and ways to change its font size. % % 'colormap' som_show ghages the colormap by default to a gray-level map % (matrix) This argument is used to set some other colormap. % % 'subplots' the number of subplots in y- and x-directions, as in % (vector) command SUBPLOT % % OUTPUT ARGUMENTS % % h (struct) % .plane (vector) handles to the axes objects (subplots) % .colorbar (vector) handles to the colorbars. Colorbars of empty % & color planes do not exist: the corresponding % value in the vector is -1 % .label (vector) handles to the axis labels % % OBJECT TAGS % % The property field 'Tag' of the axis objects created by this function % are set to contain string 'Cplane' if the axis contains component plane % ('comp'), color plane ('color') or empty plane ('empty') and string % 'Uplane' if it contains a u-matrix ('umat'). The tag is set to % 'CplaneI' for planes created using 'compi' and 'colori', and % 'UplaneI' for 'umati'. % % FEATURES % % Note that when interpolated shading is used in coloring ('compi' and % 'colori') the standard built-in bilinear Gouraud interpolation for a % SURF object is used. If the lattice is hexagonal - or anything else than % rectangular in general - the result is not strictly what is looked % for, especially if the map is small. % % EXAMPLES % %% Make random data, normalize it, and give component names %% Make a map % % data=som_data_struct(rand(1000,3),'comp_names',{'One','Two','Three'}); % data=som_normalize(data,'var'); % map=som_make(data); % %% Do the basic visualization with som_show: u-matrix and all %% component planes % % som_show(map); % %% The values shown in the colorbar are denormalized codebook values %% (if denormalization is possible). To view the actual values, use %% the ..., 'norm', 'n' argument pair. % % som_show(map,'norm','n') % %% Something more complex: %% Show 1-2. Component planes 1 and 2 (variables 'One' and 'Two') %% 3. U-matrix that is calculated only using variables %% 'One' and 'Two' %% with title '1,2 only' %% 4. U-matrix that is calculated using all variables with the %% deafult title 'U-matrix' %% 5. The color code (in c) with title 'Color code' %% 6. Component plane 3 (variable 'Three') %% and use vertical colorbars and and the values %% But first: make a continuous color code (see som_colorcode) % % c=som_colorcode(map,'rgb1'); % % som_show(map,'comp',[1 2],'umat',{1:2,'1,2 only'},'umat','all', ... % 'color',{c,'Color code'},'bar','vert','norm','n','comp',3) % % SEE ALSO % % som_show_add Show hits, labels and trajectories on SOM_SHOW visualization. % som_show_clear Clear hit marks, labels or trajectories from current figure. % som_umat Compute unified distance matrix of self-organizing map. % som_grid Visualization of a SOM grid. % som_cplane Visualization of component, u-matrix and color planes. % Copyright (c) 1997-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 1.0beta johan 100298 % Version 2.0beta johan 201099 juuso 181199 johan 011299-100200 % juuso 130300 190600 %% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% error(nargchk(1,Inf,nargin)) % check no. of input args if isstruct(sMap), % check map [tmp,ok,tmp]=som_set(sMap); if all(ok) & strcmp(sMap.type,'som_map') ; else error('Map struct is invalid!'); end else error('Requires a map struct!') end munits=size(sMap.codebook,1); % numb. of map units d=size(sMap.codebook,2); % numb. of components msize=sMap.topol.msize; % size of the map lattice=sMap.topol.lattice; % lattice if length(msize)>2 error('This visualizes only 2D maps!') end if rem(length(varargin),2) error('Mismatch in identifier-value pairs.'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read in optional arguments if isempty(varargin), varargin = { 'umat','all','comp','all'}; end %% check the varargin and build visualization infostrcuts % Vis: what kind of planes, in which order, what are the values in % the units % Vis_param: general properties % see subfunction % The try-catch construction is here just for avoiding the % possible termination to happen in subfunction because an error % message containing subfunction line numbers etc. might be confusing, as % there probably is nothing wrong with the subfunction but with the % input. Ok, this isn't proper programming sytle... try [Plane, General]= check_varargin(varargin, munits, d, sMap.name); catch error(lasterr); end % Set default values for missing ones % No planes at all (only general properties given in varargin): % set default visualization if isempty(Plane) varargin = [varargin, { 'umat','all','comp','all'}]; % and again we go... try [Plane, General]= check_varargin(varargin, munits, d, sMap.name); catch error(lasterr); end end % set defaults for general properties if isempty(General.colorbardir) General.colorbardir='vert'; end if isempty(General.scale) General.scale='denormalized'; end if isempty(General.size) General.size=1; end if isempty(General.edgecolor) General.edgecolor='none'; end %% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get rid of an annoying warning: "RGB color data not yet supported in % Painter's mode." %set(gcf, 'renderer','zbuffer'); %% -> a much more annoying thing results: the output to PostScript is %% as bitmap, making the files over 6MB in size... n=length(Plane); % the number of subfigures % get the unique component indices c=General.comp(General.comp>0); c=setdiff(unique(c),[0 -1]); c=c(~isnan(c)); % estimate the suitable dimension for if isempty(General.subplots), y=ceil(sqrt(n)); % subplots x=ceil(n/y); else y = General.subplots(2); x = General.subplots(1); if y*x<n, error(['Given subplots grid size is too small: should be >=' num2str(n)]); end end clf; % clear figure for i=1:n, % main loop h_axes(i,1)=subplot(x,y,i); % open a new subplot % Main switch: select function according to the flags set in comps switch Plane{i}.mode case 'comp' %%% Component plane tmp_h=som_cplane(lattice,msize, sMap.codebook(:,General.comp(i)), ... General.size); set(tmp_h,'EdgeColor', General.edgecolor); set(h_axes(i),'Tag','Cplane'); h_label(i,1)=xlabel(sMap.comp_names{General.comp(i)}); case 'compi' %%% Component plane (interpolated shading) tmp_h=som_grid(lattice, msize, 'surf', sMap.codebook(:,Plane{i}.value), ... 'Marker', 'none', 'Line', 'none'); set(h_axes(i),'Tag','CplaneI'); h_label(i,1)=xlabel(sMap.comp_names(Plane{i}.value)); vis_PlaneAxisProperties(gca,lattice,msize,NaN); case 'color' %%% Color plane tmp_h=som_cplane(lattice,msize,Plane{i}.value,General.size); set(tmp_h,'EdgeColor','none'); set(h_axes(i),'Tag','Cplane'); h_label(i,1)=xlabel(Plane{i}.name); case 'colori' %%% Color plane (interpolated shading) tmp_h=som_grid(lattice, msize, 'surf', Plane{i}.value, 'Marker', 'none', ... 'Line', 'none'); set(h_axes(i),'Tag','CplaneI'); h_label(i,1)=xlabel(Plane{i}.name); vis_PlaneAxisProperties(gca,lattice,msize,NaN); case 'empty' %%% Empty plane tmp_h=som_cplane(lattice,msize,'none'); h_label(i,1)=xlabel(Plane{i}.name); set(h_axes(i),'Tag','Cplane'); case 'umat' %%% Umatrix u=som_umat(sMap.codebook(:,Plane{i}.value),sMap.topol,'median',... 'mask',sMap.mask(Plane{i}.value)); u=u(:); tmp_h=som_cplane([lattice 'U'],msize,u); set(tmp_h,'EdgeColor','none'); set(h_axes(i),'Tag','Uplane'); h_label(i,1)=xlabel(Plane{i}.name); case 'umati' %%% Umatrix (interpolated shading) u=som_umat(sMap.codebook(:,Plane{i}.value),sMap.topol,'mean',... 'mask',sMap.mask(Plane{i}.value)); u=u(1:2:end,1:2:end); u=u(:); tmp_h=som_grid('rect', msize, 'surf', u, ... 'Marker', 'none', 'Line', 'none', ... 'coord', som_vis_coords(lattice,msize)); set(h_axes(i),'Tag','UplaneI'); h_label(i,1)=xlabel(Plane{i}.name); vis_PlaneAxisProperties(gca,lattice,msize,NaN); otherwise error('INTERNAL ERROR: unknown visualization mode.'); end %%% Adjust axis ratios to optimal (only 2D!) and put the %%% title as close to axis as possible set(h_label,'Visible','on','verticalalignment','top'); set(gca,'plotboxaspectratio',[msize(2) msize(1) msize(1)]); %%% Draw colorbars if they are turned on and the plane is umat or c-plane if General.comp(i)> -1 & ~strcmp(General.colorbardir,'none'), h_colorbar(i,1)=colorbar(General.colorbardir); % colorbars else h_colorbar(i,1)=-1; General.comp(i)=-1; end end %% main loop ends % Set window name set(gcf,'Name',[ 'Map name: ' sMap.name]); %% Set axes handles to the UserData field (for som_addxxx functions %% and som_recolorbar) %% set component indexes and normalization struct for som_recolorbar SOM_SHOW.subplotorder=h_axes; SOM_SHOW.msize=msize; SOM_SHOW.lattice=lattice; SOM_SHOW.dim=d; SOM_SHOW.comps=General.comp; SOM_SHOW.comp_norm=sMap.comp_norm; %(General.comp(find(General.comp>0))); set(gcf,'UserData', SOM_SHOW); % Set text property 'interp' to 'none' in title texts set(h_label,'interpreter','none'); h_colorbar=som_recolorbar('all', 3, General.scale); %refresh colorbars % Set a movable text to lower corner pointsize 12. vis_footnote(General.footnote); vis_footnote(12); % set colormap colormap(General.colormap); %% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargout > 0 h.plane=h_axes; h.colorbar=h_colorbar; h.label=h_label; end %%%%%% SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Plane, General]=check_varargin(args, munits, dim, name) % args: varargin of the main function % munits: number of map units % dim: map codebook dimension % name: map name % Define some variables (they must exist later) Plane={}; % stores the visualization data for each subplot General.comp=[]; % information stored on SOM_SHOW figure (which component) General.size=[]; % unit size General.scale=[]; % normalization General.colorbardir=[]; % colorbar direction General.edgecolor=[]; % edge colors General.footnote=name; % footnote text General.colormap=colormap; % default colormap (used to be gray(64).^.5;) General.subplots=[]; % number of subplots in y- and x-directions for i=1:2:length(args), %% Check that all argument types are strings if ~ischar(args{i}), error('Invalid input identifier names or input argument order.'); end %% Lower/uppercase in identifier types doesn't matter: identifier=lower(args{i}); % identifier (lowercase) value=args{i+1}; %%% Check first the identifiers that define planes and get values %%% to the visualization data struct array Plane. %%% (comps,compi,umat,color,empty) Note that name, value and comp_ %%% must be specified in these cases %%% comp_ are collected to comp in order. This is stored to the %%% SOM_SHOW user property field to give information for SOM_RECOLROBAR %%% how to operate, i.e., which component is in which subplot: %%% comp(i)=0: draw colorbar, but no normalization (umat) %%% comp(i)=1...N: a component plane of variable comp(i) %%% comp(i)=-1: no colorbar (color or empty plane) switch identifier case {'comp','compi'} %%% Component planes: check values & set defaults if ~vis_valuetype(value,{'nx1','1xn','string'}) & ~isempty(value), error([ 'A vector argument or string ''all'' expected for ''' ... identifier '''.']) end if isempty(value) value=1:dim; elseif ischar(value), if ~strcmp(value,'all') error([ 'Only string value ''all'' is valid for ''' ... identifier '''.']); else value=1:dim; end else value=round(value); if min(value)<1 | max(value)>dim, error([ 'Component indices out of range in ''' identifier '''.']) end end if size(value,1)==1, value=value';end comp_=value; name=[]; % name is taken form sMap by index in main loop case {'umat','umati'} %%% Check first the possible cell input if iscell(value), if ndims(value) ~= 2 | any(size(value) ~= [1 2]) | ... ~vis_valuetype(value{2},{'string'}), error('Cell input for ''umat'' has to be of form {vector, string}.'); else name=value{2}; value=value{1}; end else name='U-matrix'; % no cell: default title is set end if ~vis_valuetype(value,{'nx1','1xn','string'}) & ~isempty(value), error('Vector, string ''all'', or cell {vector, string} expected for ''umat''.') end if isempty(value) value=1:dim; elseif ischar(value), if ~strcmp(value,'all') error('Only string value ''all'' is valid for ''umat''.') else value=1:dim; end else value=unique(round(value)); end if min(value)<1 | max(value)>dim, error('Component indices out of range in ''umat''.') end if size(value,1)==1, value=value';end comp_=0; case 'empty' %%% Empty plane: check values & set defaults if ~vis_valuetype(value,{'string'}), error('A string value for title name expected for ''empty''.'); end name=value; comp_=-1; case { 'color','colori'} %%% Color plane: check values & set defaults % Check first the possible cell input if iscell(value), if ndims(value)~=2 | any(size(value) ~= [1 2]) | ... ~vis_valuetype(value{2},{'string'}), error([ 'Cell input for ''' identifier ... ''' has to be of form {M, string}.']); else name=value{2}; value=value{1}; end else name='Color code'; % no cell: default title is set end if size(value,1)~=munits | ... (~vis_valuetype(value,{'nx3rgb'}) & ... ~vis_valuetype(value,{'nx1'}) & ... ~vis_valuetype(value,{'nx1xm'}) & ... ~vis_valuetype(value,{'nx3xdimrgb'})), error(['Mx3 or Mx3xN RGBmatrix, Mx1 or Mx1xN matrix, cell '... '{RGBmatrix, string},' ... ' or {matrix, string} expected for ''' identifier '''.']); end % if colormap is fixed, we don't draw colorbar (comp_ flag is -1) % if colormap is indexed, we draw colorbar as in umat (comp_=0) if size(value,2)==3 comp_=-1; else comp_=0; end %%%% The next things are general properties of the visualization--- %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'size' %%% Unit size: check & set if ~vis_valuetype(value,{'1x1',[munits 1]}) error('A munits x 1 vector or a scalar expected for ''size''.') end if isempty(value), General.size=1; else General.size=value; end case 'bar' %%% Colorbar existence & direction: check & set if ~vis_valuetype(value,{'string'}) error('String value expected for ''bar''.') elseif isempty(value) value='vert'; end if any(strcmp(value,{'vert','horiz','none'})), General.colorbardir=value; else error('String ''vert'', ''horiz'' or ''none'' expected for ''bar''.'); end case 'norm' %%% Value normalization: check & set if ~vis_valuetype(value,{'string'}) error('String ''n'' or ''d'' expected for ''norm''.'); elseif isempty(value) value='n'; end if strcmp(value(1),'n'), General.scale='normalized'; elseif strcmp(value(1),'d'), General.scale='denormalized'; else error('String ''n(ormalized)'' or ''d(enormalized)'' expected for ''norm''.'); end case 'edge' %%% Edge on or off : check % set if ~vis_valuetype(value,{'string'}) & ~isempty(value), error('String value expected for ''edge''.') elseif ~isempty(value), switch value case 'on' General.edgecolor='k'; case 'off' General.edgecolor='none'; otherwise error('String value ''on'' or ''off'' expected for ''edge''.') end end case 'footnote' %%% Set the movable footnote text if ~vis_valuetype(value,{'string'}) if ~isempty(value), error('String value expected for ''footnote''.'); else General.footnote=sMap.name; end else General.footnote=value; end case 'colormap' %%% Set the colormap if isempty(value) General.colormap=gray(64).^2; elseif ~vis_valuetype(value,{'nx3rgb'}) error('Colormap is invalid!'); else General.colormap=value; end case 'subplots' %%% set the number of subplots if ~vis_valuetype(value,{'1x2'}) & ~vis_valuetype(value,{'2x1'}) error('Subplots grid size is invalid!'); else General.subplots=value; end otherwise %%% Unknown identifier error(['Invalid argument identifier ''' identifier '''!']); end %%% Set new entry to the Plane array if the indentifier means %%% making a new plane/planes tail=length(Plane); switch identifier case {'comp','compi'} for i=1:length(value) Plane{tail+i}.mode=identifier; Plane{tail+i}.value=value(i); Plane{tail+i}.name=name; % not used actually end General.comp = [General.comp; comp_]; case {'umat','umati','empty'} Plane{tail+1}.mode=identifier; Plane{tail+1}.value=value; Plane{tail+1}.name=name; General.comp = [General.comp; comp_]; case {'color','colori'}, for i=1:size(value,3), Plane{tail+i}.mode=identifier; Plane{tail+i}.name=[name '_' num2str(i)]; Plane{tail+i}.value=value(:,:,i); General.comp = [General.comp; comp_]; end if size(value,3)==1, Plane{tail+1}.name=name; end otherwise ; % do nothing end end
github
martinarielhartmann/mirtooloct-master
som_show_gui.m
.m
mirtooloct-master/somtoolbox/som_show_gui.m
21,167
utf_8
04711e9a1ccd09acfe6f6d238cf212f5
function fig = som_show_gui(input,varargin) %SOM_SHOW_GUI A GUI for using SOM_SHOW and associated functions. % % h = som_show_gui(sM); % % Input and output arguments: % sM (struct) a map struct: the SOM to visualize % h (scalar) a handle to the GUI figure % % This is a graphical user interface to make the usage of SOM_SHOW and % associated functions somewhat easier for beginning users of the SOM % Toolbox. % % How to use the GUI: % 1. Start the GUI by giving command som_show_gui(sM); % 2. Build a list of visualization planes using the buttons % ('Add components', etc.) on the right % - the options associated with each of the planes can be % modified by selecting a plane from the list, and pressing % the 'Plane options' button % - the controls below the list apply to all planes % - the subplot grid size can be controlled using the 'subplots' % field on top right corner, e.g. '4 3' to get 4 times 3 grid % 3. To visualize the planes, press the 'Visualize' button on the bottom. % 4. To add hits, labels, trajectories (or comets) to the % visualization, or clear them, or reset the colorbars, % see the tools available from the 'Tools' menu. % - the arguments to those tools are either given in the tool, % or read from the workspace ('Select variable' buttons) % - the tools always apply to the latest figure created % by the GUI % 5. To quit, press the 'Close' button on the bottom. % % Known bugs: % - Especially when using the adding tools, you can easily % give arguments which do not fit each other, and this % results in a lengthy (and often cryptic) error message. % In such a case, check the arguments you are giving to see % if there's something wrong with them. See function % SOM_SHOW_ADD for more information on how the options % can be set. % - The default values in the adding tools may not be % very reasonable: you may have to try out different % values for e.g. markersize before getting the kind of % result you want. % % SOM_SHOW_GUI has two subfunctions: VIS_SHOW_GUI_COMP and % VIS_SHOW_GUI_TOOL. These are for internal use of SOM_SHOW_GUI. % % See also SOM_SHOW, SOM_SHOW_ADD, SOM_SHOW_CLEAR, SOM_RECOLORBAR. % Copyright (c) 2000 by Roman Feldman and Juha Vesanto % Contributed to SOM Toolbox on August 22nd, 2000 % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta roman 160800 juuso 220800 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % MAIN % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% warning off; if (nargin < 1) errordlg({'Make sure you have SOM as input argument'; ''; ... 'example: som_show_gui(sMap)'},'Error in SOM_VIS: input arguments'); return end if isstruct(input) fig_h = create_main_gui(input); if (nargout > 0) fig = fig_h; end return; elseif ischar(input) action = lower(input); % udata = get(varargin{1},'UserData'); plot_array = udata.plot_array; l = length(plot_array); list1_h = udata.h(1); if (strcmp(action,'')) errordlg('','Error in SOM_VIS: input arguments'); return; %%%%%%%%%%%%%%%%%%%% % add_selected_comp % elseif (strcmp(action,'add_selected_comp')) if isempty(plot_array(1).string), tmp = 1; else tmp = l+1; end [sel,ok] = listdlg('ListString',udata.sM.comp_names,... 'Name','Component selection',... 'PromptString','Select components to add'); if ok & ~isempty(sel), for i=1:length(sel), plot_array(tmp+i-1).string = udata.sM.comp_names{sel(i)}; plot_array(tmp+i-1).args = {'comp' sel(i)}; udata.property{tmp+i-1} = {0}; end set(list1_h,'Value',tmp+i-1, ... 'String',{plot_array(:).string}); end udata.plot_array = plot_array; set(varargin{1},'UserData',udata); %%%%%%%%%%%%%%%%%%%% % add_all_comps % elseif (strcmp(action,'add_all_comps')) if (strcmp(plot_array(1).string,'')) tmp = 1; else tmp = l+1; end indx = length(udata.sM.comp_names); for (i=1:indx) plot_array(tmp+i-1).string = udata.sM.comp_names{i}; plot_array(tmp+i-1).args = {'comp' i}; udata.property{tmp+i-1} = {0}; end % update list set(list1_h,'Value',tmp+indx-1, ... 'String',{plot_array(:).string}); udata.plot_array = plot_array; set(varargin{1},'UserData',udata); %%%%%%%%%%%%%%%%%%%% % add_u_matrix % elseif (strcmp(action,'add_u_matrix')) if (strcmp(plot_array(1).string,'')) tmp = 1; else tmp = l+1; end plot_array(tmp).string = 'U-matrix'; plot_array(tmp).args = {'umat' 'all'}; udata.property{tmp} = {0 'U-matrix' 1:length(udata.sM.comp_names)}; % update list set(list1_h,'Value',tmp, ... 'String',{plot_array(:).string}); udata.plot_array = plot_array; set(varargin{1},'UserData',udata); %%%%%%%%%%%%%%%%%%%% % add_colorplane % elseif (strcmp(action,'add_colorplane')) if (strcmp(plot_array(1).string,'')) tmp = 1; else tmp = l+1; end plot_array(tmp).string = 'color plane'; c = som_colorcode(udata.sM); plot_array(tmp).args = {'color' c}; udata.property{tmp} = {0 'Color code' {'rgb1' 'rgb2' 'rgb3' 'rgb4' 'hsv' '-variable-'} 1}; % update list set(list1_h,'Value',tmp, ... 'String',{plot_array(:).string}); udata.plot_array = plot_array; set(varargin{1},'UserData',udata); %%%%%%%%%%%%%%%%%%%% % add_empty % elseif (strcmp(action,'add_empty')) if (strcmp(plot_array(1).string,'')) tmp = 1; else tmp = l+1; end plot_array(tmp).string = 'empty plane'; plot_array(tmp).args = {'empty' ''}; udata.property{tmp} = {''}; % update list set(list1_h,'Value',tmp, ... 'String',{plot_array(:).string}); udata.plot_array = plot_array; set(varargin{1},'UserData',udata); %%%%%%%%%%%%%%%%%%%% % remove % elseif (strcmp(action,'remove')) rm_indx = get(list1_h,'Value'); rm_l = length(rm_indx); % rebuild array incl_inds = setdiff(1:length(plot_array),rm_indx); if isempty(incl_inds), clear plot_array; plot_array(1).args = {}; plot_array(1).string = ''; udata.property = {}; udata.property{1} = {}; else plot_array = plot_array(incl_inds); udata.property = udata.property(incl_inds); end set(list1_h,'Value',length(plot_array), ... 'String',{plot_array(:).string}); udata.plot_array = plot_array; set(varargin{1},'UserData',udata); %%%%%%%%%%%%%%%%%%%% % remove_all % elseif (strcmp(action,'remove_all')) plot_array = []; plot_array(1).args = {}; plot_array(1).string = ''; udata.property = {}; set(list1_h,'Value',1, ... 'String',{plot_array(:).string}); udata.plot_array = plot_array; set(varargin{1},'UserData',udata); %%%%%%%%%%%%%%%%%%%% % more_options % elseif (strcmp(action,'more_options')) vis_show_gui_comp(varargin{1},get(list1_h,'Value'),'init'); %%%%%%%%%%%%%%%%%%%% % close % elseif (strcmp(action,'close')) close(varargin{1}); %%%%%%%%%%%%%%%%%%%% % visualize % elseif (strcmp(action,'visualize')) %% s = {k k.^2}; plot(s{:}); current_fig = varargin{1}; figure; args = [{udata.sM} plot_array(:).args]; % edge tmp = get(udata.h(2),'UserData'); i = get(udata.h(2),'Value'); args = [args {'edge' tmp{i}}]; % bar tmp = get(udata.h(3),'UserData'); i = get(udata.h(3),'Value'); args = [args {'bar' tmp{i}}]; % norm tmp = get(udata.h(4),'UserData'); i = get(udata.h(4),'Value'); args = [args {'norm' tmp{i}}]; % size tmp = get(udata.h(5),'String'); args = [args {'size' eval(tmp)}]; % colormap tmp = get(udata.h(6),'String'); if ~isempty(tmp) args = [args {'colormap' eval(tmp)}]; end % footnote tmp = get(udata.h(7),'String'); args = [args {'footnote' tmp}]; % subplots tmp = get(udata.h(8),'String'); if ~(strcmp(tmp,'default') | isempty(tmp)) tmp2 = sscanf(tmp,'%i %i'); if length(tmp2)<2, tmp2 = sscanf(tmp,'%ix%i'); end if length(tmp2)<2, tmp = eval(tmp); else tmp = tmp2'; end if length(tmp)<2, tmp(2) = 1; end if tmp(1)*tmp(2)<length(get(udata.h(1),'string')), close(varargin{1}); errordlg('Too small subplot size', ... 'Error in SOM_VIS: subplot size'); return; end args = [args {'subplots' tmp}]; end som_show(args{:}); % udata.vis_h = varargin{1}; % first refresh plot info udata.vis_h = setdiff( ... udata.vis_h, ... setdiff(udata.vis_h,get(0,'children'))); udata.vis_h = [udata.vis_h gcf]; set(current_fig,'UserData',udata); else ; end else errordlg({'Make sure you have SOM as input argument'; ''; ... 'example: som_show_gui(sMap)'},'Error in SOM_VIS: input arguments'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ---------------------- SUBFUNCTIONS ----------------------- % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CREATE_MAIN_GUI % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fig_h = create_main_gui(sM) oldFigNumber=watchon; % init variables FIGURENAME = 'SOM_SHOW_GUI'; plot_array = []; plot_array(1).args = {}; plot_array(1).string = ''; % colors fig_color = [0.8 0.8 0.8]; bg_color1 = [0.701960784313725 0.701960784313725 0.701960784313725]; bg_color2 = [0.9 0.9 0.9]; %%%% positions %%%%% %--------- figure fig_i = [0.02 0.25]; fig_s = [0.24 0.55]; %--------- ue = 0.02; th = 0.03; hint_text_pos = [0.05 0.94 0.8 th]; big_frame_pos = [ue 0.38 (1-2*ue) 0.56]; planes_listbox_text_pos = [0.07 0.87 0.3 th]; planes_listbox_pos = [(ue+0.03) 0.395 0.46 0.47]; subplots_text_pos = [0.53 0.885 0.2 th]; subplots_pos = [0.73 0.88 0.22 0.05]; ah = 0.045; d = (planes_listbox_pos(4) - 10*ah)/7; add_components_pos = [0.53 (sum(planes_listbox_pos([2 4]))-ah) 0.42 ah]; tmp = add_components_pos(2)-(d+ah); add_all_components_pos = [0.53 tmp 0.42 ah]; tmp = add_all_components_pos(2)-(d+ah); add_u_matrix_pos = [0.53 tmp 0.42 ah]; tmp = add_u_matrix_pos(2)-(d+ah); add_colorplane_pos = [0.53 tmp 0.42 ah]; tmp = add_colorplane_pos(2)-(d+ah); add_empty_pos = [0.53 tmp 0.42 ah]; tmp = add_empty_pos(2)-2*(d+ah)+d; remove_pos = [0.53 tmp 0.42 ah]; tmp = remove_pos(2)-(d+ah); remove_all_pos = [0.53 tmp 0.42 ah]; tmp = remove_all_pos(2)-2*(d+ah)+d; plane_options_pos = [0.53 tmp 0.42 ah]; ph = 0.041; dd = (ph-th)/2; tmp = big_frame_pos(2) - (planes_listbox_pos(2)-big_frame_pos(2)) - ph; ie1 = 0.25; tw = 0.21; iw = 0.28; unit_edges_text_pos = [ue (tmp+dd) tw th]; unit_edges_pos = [ie1 tmp iw ph]; tmp = unit_edges_pos(2)-(d+ph) - d; unit_sizes_text_pos = [ue (tmp+dd) tw th]; unit_sizes_pos = [ie1 tmp iw ph]; tmp = unit_sizes_pos(2)-(d+ph) - d; colorbar_dir_text_pos = [ue (tmp+dd) tw th]; colorbar_dir_pos = [ie1 tmp iw ph]; tmp2 = sum(colorbar_dir_pos([1 3])); colorbar_norm_text_pos = [(tmp2) (tmp+dd) 0.11 th]; colorbar_norm_pos = [(1-ue-(iw+0.06)) tmp (iw+0.06) ph]; tmp = colorbar_norm_pos(2)-(d+ph) - d; colormap_text_pos = [ue (tmp+dd) tw th]; colormap_pos = [ie1 tmp iw ph]; tmp = colormap_pos(2)-(d+ph) - d; footnote_text_pos = [ue (tmp+dd) tw th]; footnote_pos = [ie1 tmp (1-ue-ie1) ph]; tmp = planes_listbox_pos(2)-big_frame_pos(2); tmp2 = ah+2*tmp; little_frame_pos = [ue tmp (1-2*ue) tmp2]; tmp2 = little_frame_pos(2)+tmp; ddd = 0.1; bw = (little_frame_pos(3)-2*0.03-ddd)/2; visualize_pos = [(ue+0.03) tmp2 bw ah]; close_pos = [(sum(visualize_pos([1 3]))+ddd) tmp2 bw ah]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % main figure % fig_h = figure( ... 'Units','normalized', ... 'Color',fig_color, ... 'PaperPosition',[18 180 576 432], ... 'PaperType','A4', ... 'PaperUnits','normalized', ... 'Position',[fig_i fig_s], ... 'ToolBar','none', ... 'NumberTitle','off', ... 'Name',FIGURENAME, ... 'Visible','off'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % hint text % uicontrol( ... 'Units','normalized', ... 'BackgroundColor',fig_color, ... 'HorizontalAlignment','left', ... 'Position',hint_text_pos, ... 'String','Add planes and then visualize', ... 'Style','text'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % planes listbox % uicontrol( ... 'Units','normalized', ... 'Position',big_frame_pos, ... 'Style','frame'); uicontrol( ... 'Units','normalized', ... 'BackgroundColor',bg_color1, ... 'HorizontalAlignment','left', ... 'Position',planes_listbox_text_pos, ... 'String','Planes', ... 'Style','text'); list1_h = uicontrol( ... 'Units','normalized', ... 'BackgroundColor',bg_color2, ... 'Position',planes_listbox_pos, ... 'String',{plot_array(:).string}, ... 'Style','listbox', ... 'Max',2, ... 'Value',1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % edit subplots % uicontrol( ... 'Units','normalized', ... 'BackgroundColor',bg_color1, ... 'HorizontalAlignment','center', ... 'Position',subplots_text_pos, ... 'String','subplots', ... 'Style','text'); edit4_h = uicontrol( ... 'Units','normalized', ... 'BackgroundColor',bg_color2, ... 'Position',subplots_pos, ... 'FontSize',14, ... 'String','', ... 'Style','edit'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pushbutton 'Add components' % uicontrol( ... 'Units','normalized', ... 'BackgroundColor',bg_color1, ... 'HorizontalAlignment','left', ... 'Position',add_components_pos, ... 'String',' Add components', ... 'Callback',['som_show_gui(''add_selected_comp'',' mat2str(gcf) ')']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pushbutton 'Add all components' % uicontrol( ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'Position',add_all_components_pos, ... 'String',' Add all components', ... 'Callback',['som_show_gui(''add_all_comps'',' mat2str(gcf) ')']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pushbutton 'Add U-matrix' % uicontrol( ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'Position',add_u_matrix_pos, ... 'String',' Add U-matrix', ... 'Callback',['som_show_gui(''add_u_matrix'',' mat2str(gcf) ')']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pushbutton 'Add colorplane' % uicontrol( ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'Position',add_colorplane_pos, ... 'String',' Add colorplane', ... 'Callback',['som_show_gui(''add_colorplane'',' mat2str(gcf) ')']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pushbutton 'Add empty' % uicontrol( ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'Position',add_empty_pos, ... 'String',' Add empty', ... 'Callback',['som_show_gui(''add_empty'',' mat2str(gcf) ')']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pushbutton 'Remove' % uicontrol( ... 'Units','normalized', ... 'HorizontalAlignment','left', ... 'Position',remove_pos, ... 'String',' Remove', ... 'Callback',['som_show_gui(''remove'',' mat2str(gcf) ')']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % creat pushbutton 'Remove all' % uicontrol( ... 'Units','normalized', ... 'BackgroundColor',bg_color1, ... 'HorizontalAlignment','left', ... 'Position',remove_all_pos, ... 'String',' Remove all', ... 'Callback',['som_show_gui(''remove_all'',' mat2str(gcf) ')']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pushbutton 'Plane options' % uicontrol( ... 'Units','normalized', ... 'Position',plane_options_pos, ... 'String',' Plane options', ... 'Callback',['som_show_gui(''more_options'',' mat2str(gcf) ')']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % popupmenu unitedges % uicontrol( ... 'Units','normalized', ... 'BackgroundColor',fig_color, ... 'HorizontalAlignment','left', ... 'Position',unit_edges_text_pos, ... 'String','unit edges are', ... 'Style','text'); popup1_h = uicontrol( ... 'Units','normalized', ... 'Max',2, ... 'Min',1, ... 'Position',unit_edges_pos, ... 'UserData',{'off' 'on'}, ... 'String',{'off' 'on'}, ... 'Style','popupmenu', ... 'Value',1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % unit sizes edit % uicontrol( ... 'Units','normalized', ... 'BackgroundColor',fig_color, ... 'HorizontalAlignment','left', ... 'Position',unit_sizes_text_pos, ... 'String','unit sizes', ... 'Style','text'); edit1_h = uicontrol( ... 'Units','normalized', ... 'BackgroundColor',bg_color2, ... 'Position',unit_sizes_pos, ... 'FontSize',12, ... 'String','1', ... 'Style','edit'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % popupmenu colorbardir % uicontrol( ... 'Units','normalized', ... 'BackgroundColor',fig_color, ... 'HorizontalAlignment','left', ... 'Position',colorbar_dir_text_pos, ... 'String','colorbar is', ... 'Style','text'); popup2_h = uicontrol( ... 'Units','normalized', ... 'Max',3, ... 'Min',1, ... 'Position',colorbar_dir_pos, ... 'UserData', {'vert' 'horiz' 'none'}, ... 'String','vert| horiz| none', ... 'Style','popupmenu', ... 'Value',1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % popupmenu colorbarnorm % uicontrol( ... 'Units','normalized', ... 'BackgroundColor',fig_color, ... 'HorizontalAlignment','left', ... 'Position',colorbar_norm_text_pos, ... 'String',' and ', ... 'Style','text'); popup3_h = uicontrol( ... 'Units','normalized', ... 'Max',2, ... 'Min',1, ... 'Position',colorbar_norm_pos, ... 'UserData', {'d' 'n'}, ... 'String',{'denormalized','normalized'}, ... 'Style','popupmenu', ... 'Value',1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % colormap edittext % uicontrol( ... 'Units','normalized', ... 'BackgroundColor',fig_color, ... 'HorizontalAlignment','left', ... 'Position',colormap_text_pos, ... 'String','colormap', ... 'Style','text'); edit2_h = uicontrol( ... 'Units','normalized', ... 'BackgroundColor',bg_color2, ... 'Position',colormap_pos, ... 'FontSize',12, ... 'String','', ... 'Style','edit'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % footnote edittext % uicontrol( ... 'Units','normalized', ... 'BackgroundColor',fig_color, ... 'HorizontalAlignment','left', ... 'Position',footnote_text_pos, ... 'String','footnote', ... 'Style','text'); edit3_h = uicontrol( ... 'Units','normalized', ... 'BackgroundColor',bg_color2, ... 'Position',footnote_pos, ... 'FontSize',12, ... 'String',sM.name, ... 'Style','edit'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pushbutton 'Visualize' % uicontrol( ... 'Units','normalized', ... 'Position',little_frame_pos, ... 'Style','frame'); uicontrol( ... 'Units','normalized', ... 'Position',visualize_pos, ... 'String','Visualize', ... 'Callback',['som_show_gui(''visualize'',' mat2str(gcf) ')']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pushbutton 'Close' % uicontrol( ... 'Units','normalized', ... 'BackgroundColor',bg_color1, ... 'Position',close_pos, ... 'String','Close', ... 'Callback',['som_show_gui(''close'',' mat2str(gcf) ')']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % menus % uimenu('Parent',fig_h','Label',' ','Enable','off'); m = uimenu('Parent',fig_h,'Label','Tools'); a = uimenu('Parent',m,'Label','Add'); s = strcat('vis_show_gui_tool(',mat2str(gcf),',''add_label'')'); uimenu('Parent',a,'Label','label','Callback',s); s = strcat('vis_show_gui_tool(',mat2str(gcf),',''add_hit'')'); uimenu('Parent',a,'Label','hit','Callback',s); s = strcat('vis_show_gui_tool(',mat2str(gcf),',''add_traj'')'); uimenu('Parent',a,'Label','traj','Callback',s); s = strcat('vis_show_gui_tool(',mat2str(gcf),',''add_comet'')'); uimenu('Parent',a,'Label','comet','Callback',s); s = ['vis_show_gui_tool(',mat2str(gcf),',''clear'')']; c = uimenu('Parent',m,'Label','Clear','Separator','on','callback',s); s = strcat('vis_show_gui_tool(',mat2str(gcf),',''recolorbar'')'); r = uimenu('Parent',m,'Label','Recolorbar','Separator','on', ... 'Callback',s); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % end % ud.sM = sM; ud.plot_array = plot_array; ud.property = {}; ud.vis_h = []; ud.h = [list1_h popup1_h popup2_h popup3_h ... edit1_h edit2_h edit3_h edit4_h]; watchoff(oldFigNumber); set(fig_h,'Visible','on', ... 'UserData', ud, ... 'handlevisibility','off');
github
martinarielhartmann/mirtooloct-master
som_label.m
.m
mirtooloct-master/somtoolbox/som_label.m
9,503
utf_8
8288c9b7322af1c25b20c13d01f82aef
function [sTo] = som_label(sTo, mode, inds, labels) %SOM_LABEL Give/clear labels to/from map or data struct. % % sTo = som_label(sTo, mode, inds [, labels]) % % sD = som_label(sD,'add',20,'a_label'); % sM = som_label(sM,'replace',[2 4],'a_label'); % sM = som_label(sM,'add',som_bmus(sM,x),'BMU'); % sD = som_label(sD,'prune',[1:10]'); % sM = som_label(sM,'clear','all'); % % Input and output arguments ([]'s are optional): % sTo (struct) data or map struct to which the labels are put % mode (string) 'add' or 'replace' or 'prune' or 'clear' % inds (vector) indeces of the vectors to which the labels % are put. Note: this must be a column vector! % (matrix) subscript indeces to the '.labels' field. The vector % is given by the first index (e.g. inds(i,1)). % (string) for 'prune' and 'clear' modes, the string 'all' % means that all vectors should be pruned/cleared % [labels] The labels themselves. The number of rows much match % the number of given indeces, except if there is either % only one index or only one label. If mode is % 'prune' or 'clear', labels argument is ignored. % (string) Label. % (string array) Each row is a label. % (cell array of strings) All labels in a cell are handled % as a group and are applied to the same vector given % on the corresponding row of inds. % % Note: If there is only one label/index, it is used for each specified % index/label. % % For more help, try 'type som_label' or check out online documentation. % See also SOM_AUTOLABEL, SOM_SHOW_ADD, SOM_SHOW. %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_label % % PURPOSE % % Add (or remove) labels to (from) map and data structs. % % SYNTAX % % sTo = som_label(sTo, 'clear', inds) % sTo = som_label(sTo, 'prune', inds) % sTo = som_label(sTo, 'add', inds, labels) % sTo = som_label(sTo, 'replace', inds, labels) % % DESCRIPTION % % This function can be used to give and remove labels in map and data % structs. Of course the same operation could be done by hand, but this % function offers an alternative and hopefully slightly user-friendlier % way to do it. % % REQUIRED INPUT ARGUMENTS % % sTo (struct) data or map struct to which the labels are put % mode (string) The mode of operation. % 'add' : adds the given labels % 'clear' : removes labels % 'replace' : replaces current labels with given % labels; basically same as 'clear' % followed by 'add' % 'prune' : removes empty labels ('') from between % non-empty labels, e.g. if the labels of % a vector were {'A','','','B','','C'} % they'd become {'A','B','C'}. Some empty % labels may be left at the end of the list. % % inds Identifies the vectors to which the operation % (given by mode) is applied to. % (vector) Linear indexes of the vectors, size n x 1. % Notice! This should be a column vector! % (matrix) The labels are in a cell matrix. By giving matrix % argument for inds, you can address this matrix % directly. The first index gives the vector and the % second index the vertical position of the label in % the labels array. Size n x 2, where n is the % number of labels. % (string) for 'prune' and 'clear' modes, the string 'all' % means that all vectors should be pruned/cleared % % OPTIONAL INPUT ARGUMENTS % % [labels] The labels themselves. The number of rows much match % the number of given indeces, except if there is either % only one index or only one label. % (string) Label, e.g. 'label' % (string array) Each row is a label, % e.g. ['label1'; 'label2'; 'label3'] % (cell array of strings) All labels in a cell are handled % as a group and are applied to the same vector given % on the corresponding row of inds. % e.g. three labels: {'label1'; 'label2'; 'label3'} % e.g. a group of labels: {'label1', 'label2', 'label3'} % e.g. three groups: {{'la1'},{'la21','la22'},{'la3'} % % OUTPUT ARGUMENTS % % sTo (struct) the given data/map struct with modified labels % % EXAMPLES % % This is the basic way to add a label to map structure: % sMap = som_label(sMap,'add',3,'label'); % % The following examples have identical results: % sMap = som_label(sMap,'add',[4; 13], ['label1'; 'label2']); % sMap = som_label(sMap,'add',[4; 13], {{'label1'};{'label2'}}); % % Labeling the BMU of a vector x (and removing any old labels) % sMap = som_label(sMap,'replace',som_bmus(sMap,x),'BMU'); % % Pruning labels % sMap = som_label(sMap,'prune','all'); % % Clearing labels from a struct % sMap = som_label(sMap,'clear','all'); % sMap = som_label(sMap,'clear',[1:4, 9:30]'); % % SEE ALSO % % som_autolabel Automatically label a map/data set. % som_show Show map planes. % som_show_add Add for example labels to the SOM_SHOW visualization. % Copyright (c) 1997-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 101199 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% check arguments error(nargchk(3, 4, nargin)); % check no. of input args is correct % sTo switch sTo.type, case 'som_map', [dlen dim] = size(sTo.codebook); case 'som_data', [dlen dim] = size(sTo.data); end maxl = size(sTo.labels,2); % maximum number of labels for a single vector % inds if ischar(inds) & strcmp(inds,'all'), inds = [1:dlen]'; end if length(inds)>2 & size(inds,2)>2, inds = inds'; end ni = size(inds,1); n = ni; % labels if nargin==4, % convert labels to a cell array of cells if ischar(labels), labels = cellstr(labels); end if iscellstr(labels), tmplab = labels; nl = size(labels,1); labels = cell(nl,1); for i=1:nl, if ~iscell(tmplab{i}) if ~isempty(tmplab{i}), labels{i} = tmplab(i,:); else labels{i} = {}; end else labels(i) = tmplab(i); end end clear tmplab; end nl = size(labels,1); end % the case of a single label/index if any(strcmp(mode,{'add','replace'})), n = max(nl,ni); if n>1, if ni==1, inds = zeros(n,1)+inds(1); elseif nl==1, label = labels{1}; labels = cell(n,1); for i=1:n, labels{i} = label; end elseif ni ~= nl, error('The number of labels and indexes does not match.'); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% action switch mode, case 'clear', if size(inds,2)>2, inds = inds(find(inds(:,2)<=maxl),:); % ignore if subindex is out-of-range inds = sub2ind([dlen maxl],inds(:,1),inds(:,2)); sTo.labels{inds} = []; else sTo.labels(inds,:) = cell(n,maxl); end case 'prune', if size(inds,2)==1, % subindex gives the index from which the pruning is started inds = [inds, ones(n,1)]; % from 1 by default end select = ones(1,maxl); for i=1:n, v = inds(i,1); s = inds(i,2); select(:) = 1; for j=s:maxl, select(j) = ~isempty(sTo.labels{v,j}); end if ~all(select), labs = cell(1,maxl); labs(1:sum(select)) = sTo.labels(v,find(select)); sTo.labels(v,:) = labs; end end case 'add', if size(inds,2)==1, % subindex gives the index from which the adding is started inds = [inds, ones(n,1)]; % from 1 by default end for i=1:n, v = inds(i,1); s = inds(i,2); l = length(labels{i}); for j=1:l, while s<=size(sTo.labels,2) & ~isempty(sTo.labels{v,s}), s=s+1; end sTo.labels{v,s} = labels{i}{j}; s=s+1; end end case 'replace', if size(inds,2)==1, % subindex gives the index from which the replacing is started inds = [inds, ones(n,1)]; % from 1 by default end for i=1:n, v = inds(i,1); s = inds(i,2); l = length(labels(i)); for j=1:l, sTo.labels{v,s-1+j} = labels{i}{j}; end end otherwise error(['Unrecognized mode: ' mode]); end sTo.labels = remove_empty_columns(sTo.labels); [dlen maxl] = size(sTo.labels); for i=1:dlen, for j=1:maxl, if isempty(sTo.labels{i,j}) & ~ischar(sTo.labels{i,j}), sTo.labels{i,j} = ''; end end end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function labels = remove_empty_columns(labels) [dlen maxl] = size(labels); % find which columns are empty cols = zeros(1,maxl); for i=1:dlen, for j=1:maxl, cols(j) = cols(j) + ~isempty(labels{i,j}); end end while maxl>0 & cols(maxl)==0, maxl = maxl-1; end % check starting from end if maxl==0, labels = cell(dlen,1); elseif maxl<size(labels,2), labels = labels(:,1:maxl); else % ok end % end of remove_empty_columns %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
martinarielhartmann/mirtooloct-master
som_clset.m
.m
mirtooloct-master/somtoolbox/som_clset.m
10,182
utf_8
38150d23d264f8096f36eb455bd10bdb
function [sC,old2new,newi] = som_clset(sC,action,par1,par2) % SOM_CLSET Create and/or set values in the som_clustering struct. % % first argument % sC (struct) a som_clustering struct % Z (matrix) size nb-1 x 3, as given by LINKAGE function % base (vector) size dlen x 1, a partitioning of the data % % actions % 'remove' removes the indicated clusters (par1: vector) % 'add' add a cluster by making a combination of the indicated % clusters (par1: vector) % %'move' moves a child cluster (par1: scalar) from a parent to another % % (par2: vector 1 x 2) % 'merge' like 'add', followed by removing the indicated clusters (par1: vector) % %'split' the indicated cluster (par1: scalar) is partitioned into indicated % % parts (par2: vector), which are then added, while the indicated cluster % % (par1) is removed % 'coord' sets the coordinates of base clusters (par1: matrix nb x *), and % recalculates coordinates of the derived clusters (by averaging base cluster % coordinates) % 'color' sets the colors of base clusters (par1: matrix nb x 3), and recalculates % colors of the derived clusters (as averages of base cluster colors) % % sC % .type (string) 'som_clustering' % .name (string) Identifier for the clustering. % .nb (scalar) Number of base clusters in the clustering. % .base (vector) Size dlen x 1, the basic groups of data % forming the base clusters, e.g. as a result % of partitive clustering. Allowed values are % 1:nb indicating the base cluster % to which the data belongs to. % NaN indicating that the data has % been ignored in the clustering % .nc (scalar) Number of clusters in the clustering (nb + derived clusters). % .children (cellarray) size nc x 1, each cell gives the list of indeces % of child clusters for the cluster % .parent (vector) size nc x 1, the index of parent of each cluster % (or zero if the cluster does not have a parent) % .coord (matrix) size nc x *, visualization coordinates for each cluster % By default the coordinates are set so that % the base clusters are ordered on a line, and the % position of each combined cluster is average of % the base clusters that constitute it. % .color (matrix) size nc x 3, color for each cluster. % By default the colors are set so that the % base clusters are ordered on a line, % and then colors are assigned from the 'hsv' % colormap to the base clusters. The color % of each combined cluster is average as above. % .cldist (string) Default cluster distance function. inew = []; if isstruct(sC), % it should be a som_clustering struct old2new = [1:sC.nc]; elseif size(sC,2)==3, % assume it is a cluster hierarchy matrix Z sC = Z2sC(sC); old2new = [1:sC.nc]; else % assume it is a partitioning vector base = sC; u = unique(base(isfinite(base))); old2new = sparse(u,1,1:length(u)); base = old2new(base); sC = part2sC(base); end switch action, case 'remove', for i=1:length(par1), [sC,o2n] = removecluster(sC,old2new(par1(i))); old2new = o2n(old2new); end case 'add', [sC,old2new,inew] = addmergedcluster(sC,par1); case 'move', % not implemented yet case 'split', % not implemented yet case 'merge', [sC,old2new,inew] = addmergedcluster(sC,par1); for i=1:length(par1), [sC,o2n] = removecluster(sC,old2new(par1(i))); old2new = o2n(old2new); end case 'color', sC.color = derivative_average(sC,par1); case 'coord', sC.coord = derivative_average(sC,par1); end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function sC = clstruct(nb,nc) sC = struct('type','som_clustering',... 'name','','base',[],'nb',nb,'nc',nc,... 'parent',[],'children',[],'coord',[],'color',[],'cldist','centroid'); sC.base = [1:nb]; sC.parent = zeros(nc,1); sC.children = cell(nc,1); sC.children(:) = {[]}; sC.coord = zeros(nc,2); sC.color = zeros(nc,3); return; function Z = sC2Z(sC,height) if nargin<2, height = 'level'; end root = find(sC.parent==0); order = [root]; ch = sC.children(root); while any(ch), i = ch(1); order = [ch(1), order]; ch = [ch(2:end), sC.children{i}]; end he = zeros(sC.nc,1); if strcmp(height,'level'), ch = sC.children{root}; while any(ch), i = ch(1); he(i) = he(sC.parent(i))+1; ch = [ch(2:end), sC.children{i}]; end he = max(he)-he; elseif strcmp(height,'level2'), for i=order, if any(sC.children{i}), he(i) = max(he(sC.children{i}))+1; end, end else %he = som_cldist ( between children ) end Z = zeros(sC.nb-1,3); i = sC.nb-1; inds = root; while i>0, ch = sC.children{inds(1)}; h = he(inds(1)); inds = [inds(2:end), ch]; if length(ch)>=2, for k=1:length(ch)-2, Z(i,:) = [i-1, ch(k), h]; i = i - 1; end Z(i,:) = [ch(end-1) ch(end) h]; i = i - 1; end end return; function sC = Z2sC(Z) nb = size(Z,1)+1; nc = 2*nb-1; sC = clstruct(nb,nc); sC.base = [1:nb]; for i=1:nc, j = find(Z(:,1)==i | Z(:,2)==i); sC.parent(i) = nb+j; sC.children{sC.parent(i)}(end+1) = i; end % coords and color order = nc; nonleaves = 1; while any(nonleaves), j = nonleaves(1); ch = sC.children{order(j)}; if j==1, oleft = []; else oleft = order(1:(j-1)); end if j==length(order), oright = []; else oright = order((j+1):length(order)); end order = [oleft, ch, oright]; nonleaves = find(order>nb); end [dummy,co] = sort(order); sC.coord = derivative_average(sC,co'); H = hsv(nb+1); sC.color = derivative_average(sC,H(co,:)); return; function sC = part2sC(part) nb = max(part); nc = nb+1; sC = clstruct(nb,nc); sC.base = part; sC.parent(1:nb) = nc; sC.children{nc} = [1:nb]; co = [1:nb]'; sC.coord = derivative_average(sC,co); H = hsv(nb+1); sC.color = derivative_average(sC,H(1:nb,:)); return; function [sC,old2new] = removecluster(sC,ind) old2new = [1:sC.nc]; parent_ind = sC.parent(ind); ch = sC.children{ind}; if ~parent_ind, % trying to remove root cluster - no go return; elseif ~any(ch), % trying to remove a base cluster - no go return; else % ok, proceed old2new = [1:ind-1 0 ind:sC.nc-1]; % update parent and child fields sC.parent(ch) = parent_ind; sC.children{parent_ind} = setdiff([sC.children{parent_ind}, ch],ind); % remove old cluster j = [1:ind-1, ind+1:sC.nc]; sC.parent = sC.parent(j); sC.children = sC.children(j); sC.color = sC.color(j,:); sC.coord = sC.coord(j,:); sC.nc = sC.nc-1; % update old indeces to new indices sC.parent = old2new(sC.parent); for i=1:sC.nc, sC.children{i} = old2new(sC.children{i}); end end return; function [sC,old2new,inew] = addmergedcluster(sC,inds) old2new = [1:sC.nc]; inew = 0; p_inds = sC.parent(inds); if ~all(p_inds(1)==p_inds), % clusters are not siblings - no go return; end parent_ind = p_inds(1); if isempty(setdiff(sC.children{parent_ind},inds)), % such a merged cluster exists already return; else % ok, proceed inew = parent_ind; old2new = [1:inew-1,inew+1:sC.nc+1]; % add the new cluster (=copy of parent_ind) j = [1:inew,inew:sC.nc]; sC.parent = sC.parent(j); sC.children = sC.children(j); sC.color = sC.color(j,:); sC.coord = sC.coord(j,:); sC.nc = sC.nc+1; % update old indeces to new indices sC.parent = old2new(sC.parent); for i=1:sC.nc, sC.children{i} = old2new(sC.children{i}); end inds = old2new(inds); parent_ind = old2new(parent_ind); % update parent, child, color and coord fields sC.parent(inds) = inew; sC.parent(inew) = parent_ind; sC.children{inew} = inds; sC.children{parent_ind} = [setdiff(sC.children{parent_ind}, inds), inew]; b = baseind(sC,inew); sC.color(inew,:) = mean(sC.color(b,:)); sC.coord(inew,:) = mean(sC.coord(b,:)); end return; function C = derivative_average(sC,Cbase) [n dim] = size(Cbase); if n ~= sC.nb, error('Color / Coord matrix should have nb rows'); end C = zeros(sC.nc,dim); for i=1:sC.nc, C(i,:) = mean(Cbase(baseind(sC,i),:)); end return; function bi = baseind(sC,ind) bi = [ind]; i = 1; while i<=length(bi), bi = [bi, sC.children{bi(i)}]; end bi = bi(bi<=sC.nb); return;
github
martinarielhartmann/mirtooloct-master
sompak_init.m
.m
mirtooloct-master/somtoolbox/sompak_init.m
6,118
utf_8
326ecf24211ec0f7576c9caa06b50998
function sMap=sompak_init(sData,ft,init_type,cout,ct,xdim,ydim,topol,neigh) %SOMPAK_INIT Call SOM_PAK initialization programs from Matlab. % % sMap=sompak_init(sData,ft,init_type,cout,ct,xdim,ydim,topol,neigh) % % ARGUMENTS ([]'s are optional and can be given as empty: [] or '') % sData (struct) data struct % (matrix) data matrix % (string) filename % [ft] (string) 'pak' or 'box'. Argument must be defined, if input % file is used. % init_type (string) string 'rand' or 'linear' % [cout] (string) filename for output SOM, if argument is not defined % (i.e. argument is '[]') temporary file '__abcdef' is % used in operations and *it_is_removed* after % operations!!! % [ct] (string) 'pak' or 'box'. Argument must be defined, if output % file is used. % xdim (scalar) Number of units of the map in x-direction. % ydim (scalar) Number of units of the map in y-direction. % topol (string) string 'hexa' or 'rect' % neigh (string) string 'bubble' or 'gaussian'. % % RETURNS % sMap (struct) map struct % % Calls SOM_PAK initialization programs (randinit and lininit) from % Matlab. Notice that to use this function, the SOM_PAK programs must % be in your search path, or the variable 'SOM_PAKDIR' which is a % string containing the program path, must be defined in the % workspace. SOM_PAK programs can be found from: % http://www.cis.hut.fi/research/som_lvq_pak.shtml % % See also SOMPAK_TRAIN, SOMPAK_SAMMON, SOMPAK_INIT_GUI, % SOMPAK_GUI, SOM_LININIT, SOM_RANDINIT. % Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas % Copyright (c) by Juha Parhankangas % http://www.cis.hut.fi/projects/somtoolbox/ % Juha Parhankangas 050100 nargchk(9,9,nargin); NO_FILE = 0; if isstruct(sData); sData=sData.data; elseif ~(isreal(sData) | isstr(sData)) error('Argument ''sData'' must be a struct or a real matrix.'); else if isempty(ft) if isstr(sData) error('Argument ''file_type'' must be defined when input file is used.'); end elseif strcmp(ft,'pak'); sData=som_read_data(sData); elseif strcmp(ft,'box') new_var=diff_varname; varnames=evalin('base','who'); loadname=eval(cat(2,'who(''-file'',''',sData,''')')); if any(strcmp(loadname{1},evalin('base','who'))) assignin('base',new_var,evalin('base',loadname{1})); evalin('base',cat(2,'load(''',sData,''');')); new_var2=diff_varname; assignin('base',new_var2,evalin('base',loadname{1})); assignin('base',loadname{1},evalin('base',new_var)); evalin('base',cat(2,'clear ',new_var)); sData=evalin('base',new_var2); evalin('base',cat(2,'clear ',new_var2)); else evalin('base',cat(2,'load(''',sData,''');')); sData=evalin('base',loadname{1}); evalin('base',cat(2,'clear ',loadname{1})); end else error('Argument ''ft'' must be a string ''pak'' or ''box''.'); end end if isstr(init_type) if strcmp(init_type,'rand') if any(strcmp('SOM_PAKDIR',evalin('base','who'))) init_command=cat(2,evalin('base','SOM_PAKDIR'),'randinit'); else init_command='randinit'; end elseif strcmp(init_type,'linear') if any(strcmp('SOM_PAKDIR',evalin('base','who'))) init_command=cat(2,evalin('base','SOM_PAKDIR'),'lininit'); else init_command='lininit'; end else error('Argument ''init_type'' must be string ''rand'' or ''linear''.'); end else error('Argument ''init_type'' must be string ''rand'' or ''linear''.'); end if (isstr(cout) & isempty(cout)) | (~isstr(cout) & isempty(cout)) NO_FILE = 1; cout = '__abcdef'; elseif ~isstr(cout) & ~isempty(cout) error('Argument ''cout'' must be a string or ''[]''.'); end if ~is_positive_integer(xdim) error('Argument ''xdim'' must be a positive integer.'); end if ~is_positive_integer(ydim) error('Argument ''ydim'' must be a positive integer.'); end if isstr(topol) if isempty(topol) | (~strcmp(topol,'hexa') & ~strcmp(topol,'rect')) error ('Argument ''topol'' must be either a string ''hexa'' or ''rect''.'); end else error ('Argument ''topol'' must be either a string ''hexa'' or ''rect''.'); end if isstr(neigh) if isempty(neigh) | (~strcmp(neigh,'bubble') & ~strcmp(neigh,'gaussian')) error(sprintf(cat(2,'Argument ''neigh'' must be either a string ',... '''bubble'' or ''gaussian''.'))); end else error(sprintf(cat(2,'Argument ''neigh'' must be either a string ',... '''bubble'' or ''gaussian''.'))); end som_write_data(sData, cout); str=cat(2,init_command,sprintf(' -din %s -cout %s ', cout ,cout),... sprintf('-topol %s ',topol),... sprintf('-neigh %s ',neigh),... sprintf('-xdim %d -ydim %d',xdim,ydim)); if isunix unix(str); else dos(str); end sMap=som_read_cod(cout); if ~NO_FILE if isunix unix(cat(2,'/bin/rm ',cout)); else dos(cat(2,'del ',cout)); end if strcmp(ct,'pak') som_write_cod(sMap,cout); disp(cat(2,'Output written to the file ',cout,'.')); elseif strcmp(ct,'box') eval(cat(2,'save ',cout,' sMap')); disp(cat(2,'Output written to the file ',sprintf('''%s.mat''.',cout))); end else sMap.name=cat(2,'SOM ',date); if isunix unix('/bin/rm __abcdef'); else dos('del __abcdef'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bool = is_positive_integer(x) bool = ~isempty(x) & isreal(x) & all(size(x) == 1) & x > 0; if ~isempty(bool) if bool & x~=round(x) bool = 0; end else bool = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = diff_varname(); array=evalin('base','who'); if isempty(array) str='a'; return; end for i=1:length(array) lens(i)=length(array{i}); end ind=max(lens); str(1:ind+1)='a'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
martinarielhartmann/mirtooloct-master
som_distortion3.m
.m
mirtooloct-master/somtoolbox/som_distortion3.m
5,404
utf_8
13e98906922a0ded1181732268ac671c
function [Err,sPropTotal,sPropMunits,sPropComps] = som_distortion3(sM,D,rad) %SOM_DISTORTION3 Map distortion measures. % % [sE,Err] = som_distortion3(sM,[D],[rad]); % % sE = som_distortion3(sM); % % Input and output arguments ([]'s are optional): % sM (struct) map struct % [D] (matrix) a matrix, size dlen x dim % (struct) data or map struct % by default the map struct is used % [rad] (scalar) neighborhood radius, looked from sM.trainhist % by default, or = 1 if that has no valid values % % Err (matrix) size munits x dim x 3 % distortion error elements (quantization error, % neighborhood bias, and neighborhood variance) % for each map unit and component % sPropTotal (struct) .n = length of data % .h = mean neighborhood function value % .err = errors % sPropMunits (struct) .Ni = hits per map unit % .Hi = sum of neighborhood values for each map unit % .Err = errors per map unit % sPropComps (struct) .e1 = total squared distance to centroid % .eq = total squared distance to BMU % .Err = errors per component % % See also SOM_QUALITY. % Contributed to SOM Toolbox 2.0, January 3rd, 2002 by Juha Vesanto % Copyright (c) by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 030102 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% arguments % map [munits dim] = size(sM.codebook); % neighborhood radius if nargin<3, if ~isempty(sM.trainhist), rad = sM.trainhist(end).radius_fin; else rad = 1; end end if rad<eps, rad = eps; end if isempty(rad) | isnan(rad), rad = 1; end % neighborhood function Ud = som_unit_dists(sM.topol); switch sM.neigh, case 'bubble', H = (Ud <= rad); case 'gaussian', H = exp(-(Ud.^2)/(2*rad*rad)); case 'cutgauss', H = exp(-(Ud.^2)/(2*rad*rad)) .* (Ud <= rad); case 'ep', H = (1 - (Ud.^2)/rad) .* (Ud <= rad); end Hi = sum(H,2); % data if nargin<2, D = sM.codebook; end if isstruct(D), D = D.data; end [dlen dim] = size(D); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% quality measures % find Voronoi sets, and calculate their properties [bmus,qerr] = som_bmus(sM,D); M = sM.codebook; Vn = M; Vm = M; Ni = zeros(munits,dim); for i=1:munits, inds = find(bmus==i); Ni(i,:) = sum(isfinite(D(inds,:)),1); % size of Voronoi set if any(Ni(i,:)), Vn(i,:) = centroid(D(inds,:),M(i,:)); end % centroid of Voronoi set Vm(i,:) = centroid(M,M(i,:),H(i,:)'); % centroid of neighborhood end HN = repmat(Hi,1,dim).*Ni; %% distortion % quantization error (in each Voronoi set and for each component) Eqx = zeros(munits,dim); Dx = (Vn(bmus,:) - D).^2; Dx(isnan(Dx)) = 0; for i = 1:dim, Eqx(:,i) = full(sum(sparse(bmus,1:dlen,Dx(:,i),munits,dlen),2)); end Eqx = repmat(Hi,1,dim).*Eqx; % bias in neighborhood (in each Voronoi set / component) Enb = (Vn-Vm).^2; Enb = HN.*Enb; % variance in neighborhood (in each Voronoi set / component) Env = zeros(munits,dim); for i=1:munits, Env(i,:) = H(i,:)*(M-Vm(i*ones(munits,1),:)).^2; end Env = Ni.*Env; % total distortion (in each Voronoi set / component) Ed = Eqx + Enb + Env; %% other error measures % squared quantization error (to data centroid) me = centroid(D,mean(M)); Dx = D - me(ones(dlen,1),:); Dx(isnan(Dx)) = 0; e1 = sum(Dx.^2,1); % squared quantization error (to map units) Dx = D - M(bmus,:); Dx(isnan(Dx)) = 0; eq = sum(Dx.^2,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% output % distortion error matrix Err = zeros(munits,dim,5); Err(:,:,1) = Eqx; Err(:,:,2) = Enb; Err(:,:,3) = Env; % total errors sPropTotal = struct('n',sum(Ni),'h',mean(Hi),'e1',sum(e1),'err',sum(sum(Err,2),1)); % properties of map units sPropMunits = struct('Ni',[],'Hi',[],'Err',[]); sPropMunits.Ni = Ni; sPropMunits.Hi = Hi; sPropMunits.Err = squeeze(sum(Err,2)); % properties of components sPropComps = struct('Err',[],'e1',[],'eq',[]); sPropComps.Err = squeeze(sum(Err,1)); sPropComps.e1 = e1; sPropComps.eq = eq; return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55 %% subfunctions function v = centroid(D,default,weights) [n dim] = size(D); I = sparse(isnan(D)); D(I) = 0; if nargin==3, W = weights(:,ones(1,dim)); W(I) = 0; D = D.*W; nn = sum(W,1); else nn = n-sum(I,1); end c = sum(D,1); v = default; i = find(nn>0); v(i) = c(i)./nn(i); return; function vis figure som_show(sM,'color',{Hi,'Hi'},'color',{Ni,'hits'},... 'color',{Ed,'distortion'},'color',{Eqx,'qxerror'},... 'color',{Enb,'N-bias'},'color',{Env,'N-Var'}); ed = Eqx + Enb + Env; i = find(ed>0); eqx = 0*ed; eqx(i) = Eqx(i)./ed(i); enb = 0*ed; enb(i) = Enb(i)./ed(i); env = 0*ed; env(i) = Env(i)./ed(i); figure som_show(sM,'color',Hi,'color',Ni,'color',Ed,... 'color',eqx,'color',enb,'color',env);
github
martinarielhartmann/mirtooloct-master
som_drmake.m
.m
mirtooloct-master/somtoolbox/som_drmake.m
5,514
utf_8
89709796bebe24488d9640dffa2a6465
function [sR,best,sig,Cm] = som_drmake(D,inds1,inds2,sigmea,nanis) % SOM_DRMAKE Make descriptive rules for given group within the given data. % % sR = som_drmake(D,[inds1],[inds2],[sigmea],[nanis]) % % D (struct) map or data struct % (matrix) the data, of size [dlen x dim] % [inds1] (vector) indeces belonging to the group % (the whole data set by default) % [inds2] (vector) indeces belonging to the contrast group % (the rest of the data set by default) % [sigmea] (string) significance measure: 'accuracy', % 'mutuconf' (default), or 'accuracyI'. % (See definitions below). % [nanis] (scalar) value given for NaNs: 0 (=FALSE, default), % 1 (=TRUE) or NaN (=ignored) % % sR (struct array) best rule for each component. Each % struct has the following fields: % .type (string) 'som_rule' % .name (string) name of the component % .low (scalar) the low end of the rule range % .high (scalar) the high end of the rule range % .nanis (scalar) how NaNs are handled: NaN, 0 or 1 % % best (vector) indeces of rules which make the best combined rule % sig (vector) significance measure values for each rule, and for the combined rule % Cm (matrix) A matrix of vectorized confusion matrices for each rule, % and for the combined rule: [a, c, b, d] (see below). % % For each rule, such rules sR.low <= x < sR.high are found % which optimize the given significance measure. The confusion % matrix below between the given grouping (G: group - not G: contrast group) % and rule (R: true or false) is used to determine the significance values: % % G not G % --------------- accuracy = (a+d) / (a+b+c+d) % true | a | b | % |-------------- mutuconf = a*a / ((a+b)(a+c)) % false | c | d | % --------------- accuracyI = a / (a+b+c) % % See also SOM_DREVAL, SOM_DRTABLE. % Contributed to SOM Toolbox 2.0, January 7th, 2002 by Juha Vesanto % Copyright (c) by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 070102 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% input arguments if isstruct(D), switch D.type, case 'som_data', cn = D.comp_names; D = D.data; case 'som_map', cn = D.comp_names; D = D.codebook; end else cn = cell(size(D,2),1); for i=1:size(D,2), cn{i} = sprintf('Variable%d',i); end end [dlen,dim] = size(D); if nargin<2 | isempty(inds1), inds1 = 1:dlen; end if nargin<3 | isempty(inds2), i = ones(dlen,1); i(inds1) = 0; inds2 = find(i); end if nargin<4, sigmea = 'mutuconf'; end if nargin<5, nanis = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% input arguments sig = zeros(dim+1,1); Cm = zeros(dim+1,4); sR1tmp = struct('type','som_rule','name','','low',-Inf,'high',Inf,'nanis',nanis,'lowstr','','highstr',''); sR = sR1tmp; % single variable rules for i=1:dim, % bin edges mi = min(D(:,i)); ma = max(D(:,i)); [histcount,bins] = hist([mi,ma],10); if size(bins,1)>1, bins = bins'; end edges = [-Inf, (bins(1:end-1)+bins(2:end))/2, Inf]; % find the rule for this variable [low,high,s,cm] = onevar_descrule(D(inds1,i),D(inds2,i),sigmea,nanis,edges); sR1 = sR1tmp; sR1.name = cn{i}; sR1.low = low; sR1.high = high; sR(i) = sR1; sig(i) = s; Cm(i,:) = cm; end % find combined rule [dummy,order] = sort(-sig); maxsig = sig(order(1)); bestcm = Cm(order(1),:); best = order(1); for i=2:dim, com = [best, order(i)]; [s,cm,truex,truey] = som_dreval(sR(com),D(:,com),sigmea,inds1,inds2,'and'); if s>maxsig, best = com; maxsig = s; bestcm = cm; end end sig(end) = maxsig; Cm(end,:) = cm; return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55 %% descriptive rules function [low,high,sig,cm] = onevar_descrule(x,y,sigmea,nanis,edges) % Given a set of bin edges, find the range of bins with best significance. % % x data values in cluster % y data values not in cluster % sigmea significance measure % bins bin centers % nanis how to handle NaNs % histogram counts if isnan(nanis), x = x(~isnan(x)); y = y(~isnan(y)); end [xcount,xbin] = histc(x,edges); [ycount,ybin] = histc(y,edges); xcount = xcount(1:end-1); ycount = ycount(1:end-1); xnan=sum(isnan(x)); ynan=sum(isnan(y)); % find number of true items in both groups in all possible ranges n = length(xcount); V = zeros(n*(n+1)/2,4); s1 = cumsum(xcount); s2 = cumsum(xcount(end:-1:1)); s2 = s2(end:-1:1); m = s1(end); Tx = triu(s1(end)-m*log(exp(s1/m)*exp(s2/m)')+repmat(xcount',[n 1])+repmat(xcount,[1 n]),0); s1 = cumsum(ycount); s2 = cumsum(ycount(end:-1:1)); s2 = s2(end:-1:1); Ty = triu(s1(end)-m*log(exp(s1/m)*exp(s2/m)')+repmat(ycount',[n 1])+repmat(ycount,[1 n]),0); [i,j] = find(Tx+Ty); k = sub2ind(size(Tx),i,j); V = [i, j, Tx(k), Ty(k)]; tix = V(:,3) + nanis*xnan; tiy = V(:,4) + nanis*ynan; % select the best range nix = length(x); niy = length(y); Cm = [tix,nix-tix,tiy,niy-tiy]; [s,k] = max(som_drsignif(sigmea,Cm)); % output low = edges(V(k,1)); high = edges(V(k,2)+1); sig = s; cm = Cm(k,:); return;
github
martinarielhartmann/mirtooloct-master
preprocess.m
.m
mirtooloct-master/somtoolbox/preprocess.m
176,966
utf_8
a8170717a6766685b74076da97fb351e
function preprocess(sData,arg2) %PREPROCESS A GUI for data preprocessing. % % preprocess(sData) % % preprocess(sData) % % Launches a preprocessing GUI. The optional input argument can be % either a data struct or a struct array of such. However, primarily % the processed data sets are loaded to the application using the % tools in the GUI. Also, the only way to get the preprocessed data % sets back into the workspace is to use the tools in the GUI (press % the button DATA SET MANAGEMENT). % % For a more throughout description, see online documentation. % See also SOM_GUI. %%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IN FILES: preprocess.html,preproc.jpg,sDman.jpg,clip.jpg,delay.jpg,window.jpg,selVect.jpg % Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas % Copyright (c) by Juha Parhankangas and the SOM Toolbox team % http://www.cis.hut.fi/projects/somtoolbox/ % Juha Parhankangas 050100 global no_of_sc % every Nth component in 'relative values' is drawn stronger. no_of_sc=5; if nargin < 1 | nargin > 2 error('Invalid number of input arguments'); return; end if nargin == 1, arg2=[]; end if ~isstr(sData) %%% Preprocess is started... data.LOG{1}='% Starting the ''Preprocess'' -window...'; data.LOG{2}=cat(2,'preprocess(',... sprintf('%s);',inputname(1))); pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); if ~isempty(pre_h) figure(pre_h); msgbox('''Preprocess''-figure already exists.'); return; end h0 = figure('Color',[0.8 0.8 0.8], ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',[595 216 600 775], ... 'Tag','Preprocess'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.015 0.06064516129032258 0.9550000000000001 0.1458064516129032], ... 'Style','text', ... 'Tag','StaticText1'); data.results_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'Callback','preprocess close', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.8067 0.0142 0.1667 0.0348],... 'String','CLOSE', ... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.01833333333333333 0.2141935483870968 0.07000000000000001 0.01806451612903226], ... 'String','LOG', ... 'Style','text', ... 'Tag','StaticText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'Callback','preprocess sel_comp',... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.7983333333333333 0.2090322580645161 0.1666666666666667 0.03483870967741935], ... 'String',' ', ... 'Style','popupmenu', ... 'Tag','sel_comp_h', ... 'Value',1); data.sel_comp_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.0183 0.2568 0.2133 0.1290], ... 'Style','text', ... 'Tag','StaticText3'); data.sel_cdata_h=h1; h1 = axes('Parent',h0, ... 'CameraUpVector',[0 1 0], ... 'CameraUpVectorMode','manual', ... 'Color',[1 1 1], ... 'Position',[0.2583 0.2568 0.2133 0.1290], ... 'Tag','Axes1', ... 'XColor',[0 0 0], ... 'XTickLabel',['0 ';'0.5';'1 '], ... 'XTickLabelMode','manual', ... 'XTickMode','manual', ... 'YColor',[0 0 0], ... 'YTickMode','manual', ... 'ZColor',[0 0 0]); data.sel_chist_h=h1; h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','center', ... 'Position',[0.4960629921259843 -0.08080808080808044 9.160254037844386], ... 'Tag','Axes1Text4', ... 'VerticalAlignment','cap'); set(get(h2,'Parent'),'XLabel',h2); h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','center', ... 'Position',[-0.0551181102362206 0.4848484848484853 9.160254037844386], ... 'Rotation',90, ... 'Tag','Axes1Text3', ... 'VerticalAlignment','baseline'); set(get(h2,'Parent'),'YLabel',h2); h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','right', ... 'Position',[-1.2283 5.7980 9.1603], ... 'Tag','Axes1Text2', ... 'Visible','off'); set(get(h2,'Parent'),'ZLabel',h2); h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','center', ... 'Position',[0.4960629921259843 1.070707070707071 9.160254037844386], ... 'Tag','Axes1Text1', ... 'VerticalAlignment','bottom'); set(get(h2,'Parent'),'Title',h2); h1 = axes('Parent',h0, ... 'CameraUpVector',[0 1 0], ... 'CameraUpVectorMode','manual', ... 'Color',[0.7529 0.7529 0.7529], ... 'Position',[0.4950000000000001 0.2567741935483871 0.4766666666666667 0.1290322580645161], ... 'Tag','Axes2', ... 'XColor',[0 0 0], ... 'XTickMode','manual', ... 'YColor',[0 0 0], ... 'YTick',[0 0.5 1], ... 'YTickMode','manual', ... 'ZColor',[0 0 0]); data.vector_h=h1; h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','center', ... 'Position',[0.4982456140350879 -0.08080808080808044 9.160254037844386], ... 'Tag','Axes2Text4', ... 'VerticalAlignment','cap'); set(get(h2,'Parent'),'XLabel',h2); h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','center', ... 'Position',[-0.1018 0.4848 9.1603], ... 'Rotation',90, ... 'Tag','Axes2Text3', ... 'VerticalAlignment','baseline'); set(get(h2,'Parent'),'YLabel',h2); h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','right', ... 'Position',[-1.045614035087719 5.797979797979799 9.160254037844386], ... 'Tag','Axes2Text2', ... 'Visible','off'); set(get(h2,'Parent'),'ZLabel',h2); h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','center', ... 'Position',[0.4982456140350879 1.070707070707071 9.160254037844386], ... 'Tag','Axes2Text1', ... 'VerticalAlignment','bottom'); set(get(h2,'Parent'),'Title',h2); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.01833333333333333 0.3922580645161291 0.17 0.01806451612903226], ... 'String','STATISTICS', ... 'Style','text', ... 'Tag','StaticText4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.2583333333333334 0.3922580645161291 0.1633333333333333 0.01806451612903226], ... 'String','HISTOGRAM', ... 'Style','text', ... 'Tag','StaticText5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi',... 'FontSize',6,... 'HorizontalAlignment','left',... 'String',{'LEFT: NEW SELECTION';'RIGHT: ADD TO SELECTION'}, ... 'ListboxTop',0, ... 'Position',[0.5016666666666667 0.38 0.235 0.03741935483870968], ... 'Style','text', ... 'Tag','StaticText6', ... 'UserData','[ ]'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'Callback','preprocess selall', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.8066666666666668 0.3922580645161291 0.1666666666666667 0.03483870967741935], ... 'String','SELECT ALL', ... 'Tag','Pushbutton2', ... 'UserData','[ ]'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.7529 0.7529 0.7529], ... 'Position',[0.01833333333333333 0.4503225806451613 0.23 0.3225806451612903], ... 'String',' ', ... 'Style','listbox', ... 'Tag','Listbox1', ... 'Value',1); data.comp_names_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'Position',[0.4950000000000001 0.4503225806451613 0.2333333333333333 0.3225806451612903], ... 'String',' ', ... 'Style','listbox', ... 'Tag','Listbox2', ... 'Value',1); data.vect_mean_h = h1; h1 = axes('Parent',h0, ... 'CameraUpVector',[0 1 0], ... 'CameraUpVectorMode','manual', ... 'Color',[1 1 1], ... 'Position',[0.7383333333333334 0.4503225806451613 0.2333333333333333 0.3225806451612903], ... 'Tag','Axes3', ... 'XColor',[0 0 0], ... 'XTickMode','manual', ... 'YColor',[0 0 0], ... 'YTickMode','manual', ... 'ZColor',[0 0 0]); data.sel_cplot_h = h1; h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','center', ... 'Position',[0.4964028776978418 -0.03212851405622486 9.160254037844386], ... 'Tag','Axes3Text4', ... 'VerticalAlignment','cap'); set(get(h2,'Parent'),'XLabel',h2); h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','center', ... 'Position',[-0.05035971223021596 0.493975903614458 9.160254037844386], ... 'Rotation',90, ... 'Tag','Axes3Text3', ... 'VerticalAlignment','baseline'); set(get(h2,'Parent'),'YLabel',h2); h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','right', ... 'Position',[-3.1942 1.7028 9.1603], ... 'Tag','Axes3Text2', ... 'Visible','off'); set(get(h2,'Parent'),'ZLabel',h2); h2 = text('Parent',h1, ... 'Color',[0 0 0], ... 'HandleVisibility','off', ... 'HorizontalAlignment','center', ... 'Position',[0.4964028776978418 1.028112449799197 9.160254037844386], ... 'Tag','Axes3Text1', ... 'VerticalAlignment','bottom'); set(get(h2,'Parent'),'Title',h2); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'Callback','preprocess plxy', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.265 0.4683870967741936 0.125 0.03483870967741935], ... 'String','XY-PLOT', ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'Callback','preprocess hist', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.265 0.5303225806451613 0.125 0.03483870967741935], ... 'String','HISTOGRAM', ... 'Tag','Pushbutton4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'Callback','preprocess bplo', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.265 0.5922580645161291 0.125 0.03483870967741935], ... 'String','BOX PLOT', ... 'Tag','Pushbutton5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'Callback','preprocess plot', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.265 0.654195483870968 0.125 0.03483870967741935], ... 'String','PLOT', ... 'Tag','Pushbutton6'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.4088888888888889 0.5333333333333333 0.06 0.03268817204301075], ... 'String','30', ... 'Style','edit', ... 'Tag','EditText1'); data.no_of_bins_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.01833333333333333 0.775483870967742 0.2016666666666667 0.01806451612903226], ... 'String','COMPONENT LIST', ... 'Style','text', ... 'Tag','StaticText7'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.4950000000000001 0.775483870967742 0.1966666666666667 0.01806451612903226], ... 'String','AVERAGE', ... 'Style','text', ... 'Tag','StaticText8'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.7383333333333334 0.775483870967742 0.225 0.01806451612903226], ... 'String','RELATIVE VALUES', ... 'Style','text', ... 'Tag','StaticText9'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',10, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.01833333333333333 0.8154838709677419 0.2033333333333333 0.0232258064516129], ... 'String','COMPONENTS', ... 'Style','text', ... 'Tag','StaticText10'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',10, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.4950000000000001 0.8154838709677419 0.2 0.0232258064516129], ... 'String','VECTORS', ... 'Style','text', ... 'Tag','StaticText11'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'Callback','preprocess sD_management', ... 'FontSize',5, ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.01833333333333333 0.8503225806451613 0.1666666666666667 0.03483870967741935], ... 'String','DATA SET MANAGEMENT', ... 'Tag','Pushbutton7'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'Callback','preprocess sel_sD', ... 'ListboxTop',0, ... 'Position',[0.01833333333333333 0.8890322580645161 0.1666666666666667 0.03483870967741935], ... 'String',' ', ... 'Style','popupmenu', ... 'Tag','PopupMenu2', ... 'Value',1); data.sD_set_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.2516666666666667 0.8503225806451613 0.7216666666666667 0.07354838709677419], ... 'Style','text', ... 'Tag','StaticText12'); data.sD_name_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',10, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.01833333333333333 0.9341935483870968 0.1616666666666667 0.02064516129032258], ... 'String','DATA SETS', ... 'Style','text', ... 'Tag','StaticText13'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',10, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.2516666666666667 0.9341935483870968 0.2833333333333333 0.02064516129032258], ... 'String','SELECTED DATA SET', ... 'Style','text', ... 'Tag','StaticText14'); if ~isstruct(sData), sData=som_data_struct(sData); end ui_h=uimenu('Label','&Normalization'); uimenu(ui_h,'Label','Scale [0,1]','Callback','preprocess zscale'); uimenu(ui_h,'Label','Scale var=1','Callback','preprocess vscale'); uimenu(ui_h,'Label','HistD','Callback','preprocess histeq'); uimenu(ui_h,'Label','HistC','Callback','preprocess histeq2'); uimenu(ui_h,'Label','Log','Callback','preprocess log'); uimenu(ui_h,'Label','Eval (1-comp)','Callback','preprocess eval1'); ui_h=uimenu('Label','&Components'); uimenu(ui_h,'Label','Move component','Callback','preprocess move'); uimenu(ui_h,'Label','Copy component','Callback','preprocess copy'); uimenu(ui_h,'Label','Add: N binary types','Callback','preprocess oneo'); uimenu(ui_h,'Label','Add: zeros','Callback','preprocess zero'); uimenu(ui_h,'Label','Remove component','Callback','preprocess remove'); uimenu(ui_h,'Label','Remove selected vectors',... 'Callback','preprocess remove_vects'); uimenu(ui_h,'Label','Select all components',... 'Callback','preprocess sel_all_comps'); ui_h=uimenu('Label','&Misc'); ui_h1=uimenu(ui_h,'Label','Calculate'); ui_h2=uimenu(ui_h,'Label','Process'); uimenu(ui_h,'Label','Get LOG-file','Callback','preprocess LOG'); uimenu(ui_h,'Label','Indices of the selected vectors',... 'Callback','preprocess get_inds'); uimenu(ui_h,'Label','Undo','Callback','preprocess undo'); uimenu(ui_h1,'Label','Number of values','Callback','preprocess noof'); uimenu(ui_h1,'Label','Number of selected vectors',... 'Callback','preprocess no_of_sel'); uimenu(ui_h1,'Label','Correlation','Callback','preprocess corr'); uimenu(ui_h2,'Label','Unit length','Callback','preprocess unit'); uimenu(ui_h2,'Label','Eval','Callback','preprocess eval2'); uimenu(ui_h2,'Label','Clipping','Callback','preprocess clipping'); uimenu(ui_h2,'Label','Delay','Callback','preprocess delay'); uimenu(ui_h2,'Label','Windowed','Callback','preprocess window'); uimenu(ui_h2,'Label','Select vectors','Callback','preprocess select'); len=getfield(size(sData(1).data),{1}); data.selected_vects=find(ones(1,len)); data.sD_set=sData; set(data.vector_h,'ButtonDownFcn','preprocess(''vector_bdf'',''down'')'); set(gcf,'UserData',data); if ~set_sD_stats; return; end sel_sD; return; %%% Preprocess-window is ready. else arg=sData; if strcmp(arg,'rename') rename(arg2); elseif strcmp(arg,'sel_sD') if isempty(arg2) sel_sD; else sel_sD(arg2); end elseif strcmp(arg,'zscale') if isempty(arg2) zero2one_scale; else zero2one_scale(arg2); end elseif strcmp(arg,'vscale'); if isempty(arg2) var_scale; else var_scale(arg2); end elseif strcmp(arg,'histeq2') if isempty(arg2) hist_eq2; else hist_eq2(arg2); end elseif strcmp(arg,'log') if isempty(arg2) logarithm; else logarithm(arg2); end elseif strcmp(arg,'eval1') if isempty(arg2) eval1; else eval1(arg2); end elseif strcmp(arg,'eval2') if isempty(arg2) eval2; else eval2(arg2); end elseif strcmp(arg,'histeq'); if isempty(arg2) hist_eq; else hist_eq(arg2); end elseif strcmp(arg,'selall') if isempty(arg2) select_all; else select_all(arg2); end elseif strcmp(arg,'sel_button'); if isempty(arg2) sel_button; else sel_button(arg2); end elseif strcmp(arg,'clear_button') if isempty(arg2) clear_button; else clear_button(arg2) end elseif(strcmp(arg,'move')) if isempty(arg2) move_component; else move_component(arg2); end elseif(strcmp(arg,'copy')) if isempty(arg2) copy_component; else copy_component(arg2); end elseif strcmp(arg,'oneo') if isempty(arg2) one_of_n; else one_of_n(arg2); end elseif strcmp(arg,'zero') if isempty(arg2) add_zeros; else add_zeros(arg2); end elseif strcmp(arg,'remove') if isempty(arg2) remove_component; else remove_component(arg2); end elseif strcmp(arg,'remove_vects') if isempty(arg2) remove_vects; else remove_vects(arg2); end elseif strcmp(arg,'noof') if isempty(arg2) no_of_values; else no_of_values(arg2); end elseif strcmp(arg,'corr'); if isempty(arg2) correlation; else correlation(arg2); end elseif strcmp(arg,'unit') if isempty(arg2) unit_length; else unit_length(arg2); end elseif strcmp(arg,'clip_data') clip_data(arg2); elseif strcmp(arg,'copy_delete') copy_delete(arg2); elseif strcmp(arg,'and_or_cb') and_or_cb(arg2); elseif strcmp(arg,'all_sel_cb') all_sel_cb(arg2); elseif strcmp(arg,'clip_exp_cb') clip_exp_cb(arg2); elseif strcmp(arg,'window_cb') window_cb(arg2); elseif strcmp(arg,'set_state_vals') set_state_vals(arg2); elseif strcmp(arg,'vector_bdf') vector_bdf(arg2); elseif strcmp(arg,'sD_management'); if isempty(arg2) sD_management; else sD_management(arg2); end elseif strcmp(arg,'clipping') if isempty(arg2) clipping; else clipping(arg2); end elseif strcmp(arg,'delay') if isempty(arg2) delay; else delay(arg2); end elseif strcmp(arg,'window'); if isempty(arg2) window; else window(arg2); end elseif strcmp(arg,'select'); if isempty(arg2) select; else select(arg2); end elseif strcmp(arg,'import') if isempty(arg2) import; else import(arg2); end elseif strcmp(arg,'export') if isempty(arg2) export; else export(arg2); end elseif strcmp(arg,'undo'); if isempty(arg2) undo; else undo(arg2); end elseif strcmp(arg,'delay_data') if isempty(arg2) delay_data; else delay_data(arg2); end elseif strcmp(arg,'eval_windowed') if isempty(arg2) eval_windowed; else eval_windowed(arg2); end elseif strcmp(arg,'get_inds') if isempty(arg2) get_selected_inds; else get_selected_inds(arg2); end elseif strcmp(arg,'no_of_sel') if isempty(arg2) no_of_selected; else no_of_selected(arg2); end elseif strcmp(arg,'sel_comp'); if isempty(arg2) sel_comp; else sel_comp(arg2); end elseif strcmp(arg,'sel_all_comps') if isempty(arg2) select_all_comps; else select_all_comps(arg2); end elseif strcmp(arg,'refresh') set_var_names; elseif any(strcmp(arg,{'close_c','close_d','close_s','close_w','close_sD'})) if isempty(arg2) close_func(arg) else close_func(arg,arg2); end end switch arg case 'sD_stats' sD_stats; case 'LOG' log_file; otherwise pro_tools(arg); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function set_compnames(sData,h) %SET_COMPNAMES % % set_compnames(sData,h) % % ARGUMENTS % % sData (struct) som_data_struct % h (scalar) handle to a list box object % % % This function sets the component names of sData to the list box % indicated by 'h'. % pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); if isempty(pre_h) error('Figure ''Preprocess'' does not exist. Closing program...'); close_preprocess; end udata=get(pre_h,'UserData'); set(h,'Value',[]); for i=1:length(sData.comp_names) tmp=sprintf('#%d: ',i); names{i,1}=cat(2,tmp, sData.comp_names{i}); end set(h,'String',names,'Max',2); set(udata.sel_comp_h,'String',names); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function draw_vectors(vectors,h) %DRAW_VECTORS % % draw_vectors(vectors,h) % % ARGUMENTS % % vectors (vector) vector of 0's and 1's % h (scalar) handle to an axis object % % % This function draws an horizontal bar of 'vectors' in the axis % indicated by 'h'. % % pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); subplot(h); hold off; cla; set(h,'YLim',[0 1]); set(h,'YTick',[]); set(h,'XLim',[0 length(vectors)+1]); hold on; comp_no=get(getfield(get(pre_h,'UserData'),'sel_comp_h'),'Value'); comp=getfield(get(pre_h,'UserData'),'sData'); comp=comp.data(:,comp_no); Max = max(comp); Min = min(comp); lims=get(gca,'YLim'); lims(1)=Min; h=abs(0.1*Max); lims(2)=Max; if Max - Min <= eps tmp=Max; lims(1)=tmp-1; lims(2)=tmp+1; end lims(2)=lims(2)+h; if ~all(isnan(lims)) set(gca,'YLim',lims); end h=(lims(2)-lims(1))/4; set(gca,'YTickMode','auto'); t=1:length(vectors); h=plot(t,comp); set(h,'ButtonDownFcn','preprocess(''vector_bdf'',''down'')'); indices =find(vectors); vectors(indices)=0.1*(getfield(get(gca,'YLim'),... {2})-getfield(get(gca,'YLim'),{1})); plot(indices,vectors(indices)+getfield(get(gca,'YLim'),{1}),... 'ored','MarkerSize',4); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function vect_means(sData,handle,indices) %VECT_MEANS % % vect_means(sData,handle,indices) % % ARGUMENTS % % sData (struct) som_data_struct % handle (scalar) handle to the static text box object % indices (vector) indices of selected vectors % % % This function calculates means of selected vectors' components % and writes them in the static text box indicated by 'handle'. % % sData= sData.data(indices,:); for i=1:length(sData(1,:)) names{i}=sprintf('#%d: ',i); end for i=1:length(sData(1,:)) tmp=sData(:,i); tmp=cat(2,names{i},sprintf('%-10.3g',mean(tmp(find(~isnan(tmp)))))); string{i}=tmp; end set(handle,'String',string); set(handle,'HorizontalAlignment','left'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function vector_bdf(arg) %VECTOR_BDF A button down function. % % vector_bdf(arg) % % ARGUMENTS % % arg (string) 'down' or 'up', tells the mouse button's state. % % % This function selects vectors in the vector-window and plots maxima, % minima and means of the selected vectors. It also writes means of the % selected vectors' components in a static text box and takes care of % changes of the chosen component's data. % % See also VECTOR_MEANS, SEL_COMP % % arg2=arg(6:length(arg)); if ~isempty(arg2) LOG=1; else LOG=0; end arg=arg(1:4); %%% arg's first "word" is 4 letters long and it can be: %%% %%% 'key ' %%% 'down' %%% 'drag' %%% 'up ' if strcmp(arg,'key ') %string is 'key' + 1 space!!! if ~LOG key=get(gcf,'CurrentCharacter'); else key=arg2 end if ~strcmp(key,'<') & ~strcmp(key,'>') return; end data=get(gcf,'UserData'); sel=data.selected_vects; if length(sel) == 1 if strcmp(key,'<') & sel ~= 1 data.selected_vects=sel-1; set(gcf,'UserData',data); elseif strcmp(key,'>') & sel ~= length(data.sData.data(:,1)) data.selected_vects = sel + 1; set(gcf,'UserData',data); end else if strcmp(key,'<') & sel(1) ~= 1 data.selected_vects=cat(2,sel(1)-1,sel); set(gcf,'UserData',data); elseif strcmp(key,'>') & sel(length(sel)) ~= length(sel) data.selected_vects=cat(2,sel,sel(length(sel))+1); set(gcf,'UserData',data); end end cplot_mimema; pro_tools('plot_hist'); pro_tools('c_stat'); vects=zeros(1,length(data.sData.data(:,1))); vects(data.selected_vects)=1; draw_vectors(vects,data.vector_h); if ~LOG data=get(gcf,'UserData'); data.LOG{length(data.LOG)+1}=... sprintf('preprocess(''vector_bdf'',''key %s'');',key); %string is 'key'+2spaces+%s set(gcf,'UserData',data); end return; end switch arg case 'down' set(gcf,'WindowButtonUpFcn','preprocess(''vector_bdf'',''up '')'); set(gcf,'WindowButtonMotionFcn','preprocess(''vector_bdf'',''drag'')'); switch get(gcf,'SelectionType') case 'normal' data.lims1=round(getfield(get(gca,'CurrentPoint'),{1,1})); data.lims2=[]; case 'alt' tmp=round(getfield(get(gca,'CurrentPoint'),{1,1})); if isempty(get(gca,'UserData')) data.lims1=tmp; data.lims2=[]; else data.lims1=cat(2,getfield(get(gca,'UserData'),'lims1'),tmp); data.lims2=getfield(get(gca,'UserData'),'lims2'); end end coords=get(gca,'CurrentPoint'); h=line([coords(1),coords(1)],get(gca,'YLim'),'EraseMode','xor'); set(h,'Color','red'); h2=line([coords(1),coords(1)],get(gca,'YLim'),'EraseMode','xor'); set(h2,'Color','red'); data.h=h; data.h2=h2; set(gca,'UserData',data); case 'drag' coords=get(gca,'CurrentPoint'); lim=get(gca,'XLim'); h2=getfield(get(gca,'UserData'),'h2'); if lim(1) >= coords(1) set(h2,'XData',[lim(1) lim(1)]); elseif lim(2) <= coords(2) set(h2,'XData',[lim(2) lim(2)]); else set(h2,'XData',[coords(1) coords(1)]); end case 'up ' % string is 'up' + 2 spaces!!! set(gcf,'WindowButtonUpFcn',''); set(gcf,'WindowButtonMotionFcn',''); if ~LOG data=get(gca,'UserData'); delete(data.h); delete(data.h2); tmp=round(getfield(get(gca,'CurrentPoint'),{1,1})); data.lims2=cat(2,data.lims2,tmp); tmp_data=sort(cat(1,data.lims1,data.lims2)); high=getfield(get(gca,'XLim'),{2})-1; vectors=zeros(1,high); tmp_data(find(tmp_data<1))=1; tmp_data(find(tmp_data>high))=high; for i=1:getfield(size(tmp_data),{2}) vectors(tmp_data(1,i):tmp_data(2,i))=1; end selected_vects=find(vectors); else pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); len=size(getfield(getfield(get(pre_h,'UserData'),'sData'),'data')); vectors=zeros(1,len(1)); i=1; while i <= length(arg2) & (isspace(arg2(i)) | ~isletter(arg2(i))) i=i+1; end arg3=arg2(i:length(arg2)); selected_vects=str2num(arg2(1:i-1)); if ~isempty(arg3) & ~all(isspace(arg3)) selected_vects=unique(cat(2,selected_vects,... getfield(get(pre_h,'UserData'),'selected_vects'))); end vectors(selected_vects)=1; set(pre_h,'CurrentAxes',getfield(get(pre_h,'UserData'),'vector_h')); set(0,'CurrentFigure',pre_h); end draw_vectors(vectors,gca); sData=getfield(get(gcf,'UserData'),'sData'); h=getfield(get(gcf,'UserData'),'vect_mean_h'); vect_means(sData,h,selected_vects); if ~LOG set(gca,'UserData',data); end data=get(gcf,'UserData'); data.undo.sData=data.sData; data.undo.selected=data.selected_vects; data.selected_vects=selected_vects; if ~LOG data.LOG{length(data.LOG)+1}='% Vector selection by using the mouse...'; tmp=sprintf('preprocess(''vector_bdf'',''up %s'');',... num2str(data.selected_vects)); if length(tmp) > 500 tmp=textwrap({tmp},500); data.LOG{length(data.LOG)+1}=cat(2,tmp{1},''');'); for i=2:length(tmp)-1 data.LOG{length(data.LOG)+1}=... cat(2,sprintf('preprocess(''vector_bdf'',''up %s',... tmp{i}),'add'');'); end data.LOG{length(data.LOG)+1}=... cat(2,sprintf('preprocess(''vector_bdf'',''up %s',... tmp{length(tmp)}(1:length(tmp{length(tmp)})-3)),' add'');'); else data.LOG{length(data.LOG)+1}=tmp; end end set(gcf,'UserData',data); cplot_mimema; sel_comp; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sel_button(varargin) %SEL_BUTTON A Callback function. It performs the operations needed % when vector components are selected. % % See also SEL_COMP % if nargin == 1 LOG=1; pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); string=getfield(get(pre_h,'UserData'),'comp_names_h'); string=getfield(get(string,'String'),{str2num(varargin{1})}); set(0,'CurrentFigure',pre_h); else LOG=0; val=get(getfield(get(gcf,'UserData'),'comp_names_h'),'Value'); end sel_button_h=getfield(get(gcf,'UserData'),'sel_button_h'); sel_comps_h=getfield(get(gcf,'UserData'),'sel_comps_h'); comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h'); if ~LOG string=getfield(get(comp_names_h,'String'),{get(comp_names_h,'Value')}); end tmp_string=get(sel_comps_h,'String'); if iscell(tmp_string) for i=1:length(string) if ~any(strcmp(string{i},tmp_string)) tmp_string=cat(1,tmp_string,string(i)); end end string=tmp_string; end set(sel_comps_h,'String',string); set(comp_names_h,'Value',[]); sel_comp; if ~LOG data=get(gcf,'UserData'); data.LOG{length(data.LOG)+1}='% Select components'; data.LOG{length(data.LOG)+1}=sprintf('preprocess(''sel_button'',''%s'');',... num2str(val)); set(gcf,'UserData',data); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function clear_button(varargin) %CLEAR_BUTTON Function callback evaluated when a 'Clear'-button is % pressed. It removes texts from the 'selected components' % -window and the 'selected component data' -window and % clears the 'histogram' -axis. % % if nargin==1 LOG=1; pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); set(0,'CurrentFigure',pre_h); else LOG=0; end sel_comp_h=getfield(get(gcf,'UserData'),'sel_comp_h'); sel_cdata_h=getfield(get(gcf,'UserData'),'sel_cdata_h'); sel_cplot_h=getfield(get(gcf,'UserData'),'sel_cplot_h'); sel_chist_h=getfield(get(gcf,'UserData'),'sel_chist_h'); vector_h=getfield(get(gcf,'UserData'),'vector_h'); set(sel_comp_h,'Value',1); set(sel_cdata_h,'String',' '); subplot(sel_chist_h); hold off; cla; selected=getfield(get(gcf,'UserData'),'selected_vects'); dims=size(getfield(getfield(get(gcf,'UserData'),'sData'),'data')); vectors=zeros(1,dims(1)); vectors(selected)=1; subplot(vector_h); draw_vectors(vectors,vector_h); if ~LOG data=get(gcf,'UserData'); data.LOG{length(data.LOG)+1}='% Remove components from the selected list.'; data.LOG{length(data.LOG)+1}='preprocess(''clear_button'',''foo'');'; set(gcf,'UserData',data); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sel_comp(varargin) %SEL_COMP performs the operations needed when vector components are % chosen. It writes maxima, minima, mean and standard deviation % of the chosen component to a text box window and draws a % histogram of the chosen component of selected vectors' % % pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); set(0,'CurrentFigure',pre_h); sel_comp_h=getfield(get(pre_h,'UserData'),'sel_comp_h'); if nargin == 1 set(sel_comp_h,'Value',str2num(varargin{1})); elseif ~isempty(gcbo) no=get(sel_comp_h,'Value'); data=get(gcf,'UserData'); data.LOG{length(data.LOG)+1}='% Select one component'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''sel_comp'',''',... num2str(no),''');'); set(gcf,'UserData',data); end pro_tools('c_stat'); pro_tools('plot_hist'); data=get(gcf,'UserData'); sData=data.sData; vector_h=data.vector_h; len=length(sData.data(:,1)); vects=zeros(1,len); vects(data.selected_vects)=1; draw_vectors(vects,vector_h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cplot_mimema global no_of_sc sData=getfield(get(gcf,'UserData'),'sData'); sel_cplot_h=getfield(get(gcf,'UserData'),'sel_cplot_h'); selected=getfield(get(gcf,'UserData'),'selected_vects'); set(sel_cplot_h,'YLim',[0 length(sData.data(1,:))+1]); subplot(sel_cplot_h); hold off; cla; hold on; for i=1:length(sData.data(1,:)) Max=max(sData.data(:,i)); Min=min(sData.data(:,i)); tmp=sData.data(selected,i); selMax=max(tmp); selMin=min(tmp); Mean=abs(mean(tmp(find(~isnan(tmp))))); Median=abs(median(tmp(find(~isnan(tmp))))); if Max ~= Min & ~all(isnan(sData.data(:,i))) if rem(i,no_of_sc) % no_of_sc is defined in the beginning of this file... line([abs(selMin-Min)/(Max-Min) (selMax-Min)/(Max-Min)],... [i i],'Color','black'); plot(abs(Mean-Min)/(Max-Min),i,'oblack'); plot(abs(Median-Min)/(Max-Min),i,'xblack'); else line([abs(selMin-Min)/(Max-Min) (selMax-Min)/(Max-Min)],... [i i],'Color','black','LineWidth',2); plot(abs(Mean-Min)/(Max-Min),i,'oblack','LineWidth',2); plot(abs(Median-Min)/(Max-Min),i,'xblack','LineWidth',2); end else if rem(i,no_of_sc) % N is defined in the beginning of this file. plot(mean(get(gca,'XLim')),i,'oblack'); plot(mean(get(gca,'XLim')),i,'xblack'); else plot(mean(get(gca,'XLim')),i,'oblack','LineWidth',2); plot(mean(get(gca,'XLim')),i,'xblack','LineWidth',2); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bool=set_sD_stats %SET_SD_STATS Writes the data set names to popup menu. % % bool=1; data=get(gcf,'UserData'); for i=1:length(data.sD_set) % if ~isvalid_var_name({data.sD_set(i).name}) % close_preprocess; % bool=0; % return; % end string{i}=cat(2,sprintf('#%d: ',i),data.sD_set(i).name); end set(data.sD_set_h,'String',string); data.sData=data.sD_set(get(data.sD_set_h,'Value')); data.sData.MODIFIED=0; data.sData.INDEX=1; set(gcf,'UserData',data); write_sD_stats; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function write_sD_stats %WRITE_SD_STATS writes data's name, length and dimension to text box. % % pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); sD_name_h=getfield(get(pre_h,'UserData'),'sD_name_h'); sData=getfield(get(pre_h,'UserData'),'sData'); dims=size(sData.data); string{1}=cat(2,'Name: ',sData.name); string{2}=cat(2,'Length: ',sprintf('%d',dims(1))); string{3}=cat(2,'Dim: ',sprintf('%d',dims(2))); set(sD_name_h,'String',string); set(sD_name_h,'HorizontalAlignment','left'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sel_sD(varargin) %SEL_SD sets new data to UserData's 'sData'. % % if nargin==1 LOG=1; index=str2num(varargin{1}); pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); set(0,'CurrentFigure',pre_h); else LOG=0; end sD_set_h=getfield(get(gcf,'UserData'),'sD_set_h'); comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h'); vector_h=getfield(get(gcf,'UserData'),'vector_h'); vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h'); if ~LOG index=get(sD_set_h,'Value'); end data=get(gcf,'UserData'); data.undo = []; INDEX=data.sData.INDEX; data.sData=rmfield(data.sData,'MODIFIED'); data.sData=rmfield(data.sData,'INDEX'); tmp=data.sD_set(index); tmp.MODIFIED=0; tmp.INDEX=index; data.sD_set(INDEX)=data.sData; data.sData=tmp; len=getfield(size(tmp.data),{1}); data.selected_vects=find(ones(1,len)); if ~LOG data.LOG{length(data.LOG)+1}='% Select a new data set.'; data.LOG{length(data.LOG)+1}=sprintf('preprocess(''sel_sD'',''%s'');',... num2str(index)); end set(gcf,'UserData',data); write_sD_stats; set_compnames(tmp,comp_names_h); draw_vectors(ones(1,len),vector_h); vect_means(tmp,vect_mean_h,data.selected_vects); clear_button; sel_comp; cplot_mimema; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function indices=get_indices pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); comp_names_h=getfield(get(pre_h,'UserData'),'comp_names_h'); indices = get(comp_names_h,'Value'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sD_management(varargin) if nargin ~= 1 pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); preh_udata=get(pre_h,'UserData'); preh_udata.LOG{length(preh_udata.LOG)+1}=... '% Starting the ''Data Set Management'' -window...'; preh_udata.LOG{length(preh_udata.LOG)+1}=... 'preprocess(''sD_management'',''foo'');'; set(pre_h,'UserData',preh_udata); end man_h=findobj(get(0,'Children'),'Tag','Management'); if ~isempty(man_h) figure(man_h); return; end h0 = figure('BackingStore','off', ... 'Color',[0.8 0.8 0.8], ... 'Name','Data Set Management', ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',[753 523 324 470], ... 'RendererMode','manual', ... 'Tag','Management'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Max',2, ... 'Position',[0.02777777777777778 0.0723404255319149 0.7716049382716049 0.1914893617021277], ... 'String',' ', ... 'Style','edit', ... 'Tag','EditText1'); data.new_c_name_h = h1; h1 = uicontrol('Parent',h0, ... 'Callback','preprocess rename comp',... 'Units','normalized', ... 'FontSize',6, ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.8240740740740741 0.2106382978723404 0.154320987654321 0.05319148936170213], ... 'String','RENAME', ... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Callback','preprocess close_sD',... 'Units','normalized', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.8240740740740741 0.01914893617021277 0.154320987654321 0.05319148936170213], ... 'String','CLOSE', ... 'Tag','Pushbutton2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.02777777777777778 0.2680851063829787 0.345679012345679 0.02978723404255319], ... 'String','COMPONENTS:', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'HorizontalAlignment','left', ... 'Position',[0.02777777777777778 0.3170212765957447 0.3549382716049382 0.5319148936170213], ... 'String',' ', ... 'Style','listbox', ... 'Tag','Listbox1', ... 'Value',1); data.sets_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'HorizontalAlignment','left', ... 'Position',[0.6234567901234568 0.3170212765957447 0.3549382716049382 0.5319148936170213], ... 'String',' ', ... 'Style','listbox', ... 'Tag','Listbox2', ... 'Value',1); data.variables_h = h1; h1 = uicontrol('Parent',h0, ... 'Callback','preprocess export',... 'Units','normalized', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.4259259259259259 0.551063829787234 0.154320987654321 0.0425531914893617], ... 'String','->', ... 'Tag','Pushbutton4'); h1 = uicontrol('Parent',h0, ... 'Callback','preprocess import',... 'Units','normalized', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.4259259259259259 0.625531914893617 0.154320987654321 0.0425531914893617], ... 'String','<-', ... 'Tag','Pushbutton3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.02777777777777778 0.8531914893617022 0.2993827160493827 0.02978723404255319], ... 'String','DATA SETS', ... 'Style','text', ... 'Tag','StaticText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.6234567901234568 0.8531914893617022 0.2561728395061728 0.02978723404255319], ... 'String','WORKSPACE', ... 'Style','text', ... 'Tag','StaticText3'); h1 = uicontrol('Parent',h0, ... 'Callback','preprocess rename set',... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.1820987654320987 0.9127659574468086 0.7808641975308641 0.0425531914893617], ... 'Style','edit', ... 'Tag','EditText2'); data.new_name_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.02777777777777778 0.9127659574468086 0.1388888888888889 0.02978723404255319], ... 'String','NAME:', ... 'Style','text', ... 'Tag','StaticText4'); ui_h=uimenu('Label','&Tools'); uimenu(ui_h,'Label','Copy','Callback','preprocess copy_delete copy'); uimenu(ui_h,'Label','Delete','Callback','preprocess copy_delete delete'); uimenu(ui_h,'Label','Refresh','Callback','preprocess refresh'); set(gcf,'UserData',data); set_var_names; sD_names; sD_stats; %%% Subfunction: set_var_names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function set_var_names variables_h=getfield(get(gcf,'UserData'),'variables_h'); value=get(variables_h,'Value'); len=evalin('base','length(who)'); names=cell(len,1); for i=1:len string=cat(2,'getfield(who,{',num2str(i),'})'); names(i)=evalin('base',string); end set(variables_h,'String',names); if(value > length(names)) set(variables_h,'Value',1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: sD_names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sD_names sets_h=getfield(get(gcf,'UserData'),'sets_h'); pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); sD_set = getfield(get(pre_h,'UserData'),'sD_set'); for i=1:length(sD_set) names{i,1}=cat(2,sprintf('#%d: ',i),sD_set(i).name); end set(sets_h,'String',names); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: sD_stats %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sD_stats man_h=findobj(get(0,'Children'),'Tag','Management'); c_names_h=getfield(get(man_h,'UserData'),'new_c_name_h'); sD_name_h=getfield(get(man_h,'UserData'),'new_name_h'); pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); INDEX=getfield(getfield(get(pre_h,'UserData'),'sData'),'INDEX'); MODIFIED=getfield(getfield(get(pre_h,'UserData'),'sData'),'MODIFIED'); value=get(getfield(get(man_h,'UserData'),'sets_h'),'Value'); if value==INDEX data=get(pre_h,'UserData'); sData=rmfield(data.sData,[{'INDEX'};{'MODIFIED'}]); data.sD_set(INDEX)=sData; data.sData.MODIFIED=0; set(pre_h,'UserData',data); end sData=getfield(getfield(get(pre_h,'UserData'),'sD_set'),{value}); string1=[{sData.name}]; set(sD_name_h,'String',string1); set(c_names_h,'String',sData.comp_names); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: import %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function import(varargin) if nargin==1 LOG=1; man_h=findobj(get(0,'Children'),'Tag','Management'); set(0,'CurrentFigure',man_h); name=varargin; else LOG=0; end variables_h=getfield(get(gcf,'UserData'),'variables_h'); pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); if ~LOG name=getfield(get(variables_h,'String'),{get(variables_h,'Value')}); end errstr='Data to be imported must be real matrix or ''som_data_struct''.'; new_sD=evalin('base',name{1}); if isempty(pre_h) errordlg('''Preprocess'' -figure does not exist. Terminating program...'); close_preprocess; return; end if isstr(new_sD) | (~isstruct(new_sD) & ~isreal(new_sD)) errordlg(errstr); return; elseif isstruct(new_sD) & length(new_sD) > 1 errordlg(errstr) return; elseif ~isstruct(new_sD) new_sD=som_data_struct(new_sD); new_sD.name=name{1}; end new_sD_names=fieldnames(new_sD); right_names=fieldnames(som_data_struct(1)); for i=1:length(new_sD_names) if ~any(strcmp(new_sD_names(i),right_names)); errordlg(errstr); return; end end data=get(pre_h,'UserData'); data.sD_set(length(data.sD_set) + 1)=new_sD; if ~LOG data.LOG{length(data.LOG)+1}='% Import a data set from the workspace.'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''import'',''',... name{1},''');'); end set(pre_h,'UserData',data); sD_names; sD_stats; old =gcf; set(0,'CurrentFigure',pre_h); set_sD_stats; set(0,'CurrentFigure',old); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: export %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function export(varargin) if nargin == 1 LOG=1; man_h=findobj(get(0,'Children'),'Tag','Management'); set(0,'CurrentFigure',man_h); index=str2num(varargin{1}); else LOG=0; end sets_h=getfield(get(gcf,'UserData'),'sets_h'); pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); if ~LOG index=get(sets_h,'Value'); end if isempty(pre_h) errordlg('''Preprocess''-figure does not exist. Terminating program...'); close(findobj(get(0,'Children'),'Tag','Management')); close(findobj(get(0,'Children'),'Tag','PlotWin')); return; end sData=getfield(getfield(get(pre_h,'UserData'),'sD_set'),{index}); if ~isvalid_var_name({sData.name}) return; end assignin('base',sData.name,sData); disp(sprintf('Data set ''%s'' is set to the workspace.',sData.name)); if ~LOG data=get(pre_h,'UserData'); data.LOG{length(data.LOG)+1}='% Export a data set to the workspace.'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''export'',''',... num2str(index),''');'); set(pre_h,'UserData',data); end set_var_names; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: rename %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rename(arg) i=1; while i <= length(arg) & arg(i) ~= ' ' i=i+1; end arg2=arg(i+1:length(arg)); arg=arg(1:i-1); if ~isempty(arg2) LOG=1; i=1; if arg2(1) ~= '{' while i <= length(arg2) & arg2(i) ~= ' ' i=i+1; end index=str2num(arg2(i+1:length(arg2))); arg2=arg2(1:i-1); else while i <= length(arg2) & arg2(i) ~= '}' i=i+1; end index=str2num(arg2(i+1:length(arg2))); arg2=arg2(1:i); end else LOG=0; end new_name_h=getfield(get(gcf,'UserData'),'new_name_h'); new_c_name_h=getfield(get(gcf,'UserData'),'new_c_name_h'); pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); if isempty(pre_h) errordlg('''Preprocess'' -figure does not exist. Terminating program...'); close_preprocess; return; end switch arg case 'set' if LOG name={arg2}; else name=get(new_name_h,'String'); end if ~isempty(name{1}) & ~any(isspace(name{1})) if ~isvalid_var_name(name) sD_stats; return; end if ~LOG index=get(getfield(get(gcf,'UserData'),'sets_h'),'Value'); end data=get(pre_h,'UserData'); tmp_set.name=name{1}; data.sD_set(index).name=name{1}; if data.sData.INDEX == index data.sData.name=name{1}; end if ~LOG data.LOG{length(data.LOG)+1}='% Rename a data set.'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''rename'',''set ',... name{1},' ',... num2str(index),... ''');'); end set(pre_h,'UserData',data); sD_names; string=get(data.sD_set_h,'String'); string{index}=cat(2,sprintf('#%d: ',index),name{1}); set(data.sD_set_h,'String',string); string=get(data.sD_name_h,'String'); string{1}=cat(2,'Name: ',name{1}); if index==data.sData.INDEX set(data.sD_name_h,'String',string); end else sD_stats; end case 'comp' if ~LOG names=get(new_c_name_h,'String'); index=get(getfield(get(gcf,'UserData'),'sets_h'),'Value'); else names=eval(arg2); end if check_cell_names(names) data=get(pre_h,'UserData'); sData=data.sD_set(index); if length(sData.comp_names)==length(names) data.sD_set(index).comp_names=names; if index == data.sData.INDEX for i=1:length(names) names{i}=cat(2,sprintf('#%d: ',i),names{i}); end set(data.comp_names_h,'String',names); set(data.sel_comp_h,'String',names); end if ~LOG data.LOG{length(data.LOG)+1}='% Rename components.'; str='preprocess(''rename'',''comp {'; for i=1:length(names)-1 str=cat(2,str,'''''',names{i},''''','); end str=cat(2,str,'''''',names{length(names)},'''''} ',... num2str(index),''');'); data.LOG{length(data.LOG)+1}=str; else set(new_c_name_h,'String',names); end set(pre_h,'UserData',data); else errordlg('There are less components in data.'); sD_stats; return; end else sD_stats; end end %%% Subfunction: check_cell_names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bool=check_cell_names(names) bool = 1; if isempty(names) bool= 0; return; end for i=1:length(names) if isempty(names{i}) | isspace(names{i}) bool = 0; return; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: isvalid_var_name %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bool=isvalid_var_name(name) bool=1; tmp=name{1}; if ~((tmp(1)>='a' & tmp(1)<='z') | (tmp(1)>='A' & tmp(1)<='Z')) errordlg('Invalid name.'); bool=0; return; end for j=1:length(tmp) if ~((tmp(j)>='a' & tmp(j)<='z') | ... (tmp(j)>='A' & tmp(j)<='Z') | ... (j>1 & tmp(j) == '_') | ... (tmp(j)>='0' & tmp(j) <= '9')) | tmp(j) == '.' errordlg('Invalid name.'); bool=0; return; end if j == length(tmp) & tmp(j) == '_' errordlg('Invalid name.'); bool=0; return; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: copy_delete %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function copy_delete(arg) i=1; while i <= length(arg) & arg(i) ~= ' ' i=i+1; end arg2=arg(i+1:length(arg)); arg=arg(1:i-1); if ~isempty(arg2) index=str2num(arg2); LOG=1; else LOG=0; end sets_h=getfield(get(gcf,'UserData'),'sets_h'); if ~LOG index=get(sets_h,'Value'); end pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); if isempty(pre_h) errordlg('''Preprocess'' -figure does not exist. Terminating program.'); close_preprocess; return; end switch arg case 'copy' data=get(pre_h,'UserData'); data.sD_set(length(data.sD_set)+1)=data.sD_set(index); if ~LOG data.LOG{length(data.LOG)+1}='% Copy a data set.'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''copy_delete'',''',... 'copy ',num2str(index),''');'); end set(pre_h,'UserData',data); sD_names; old=gcf; set(0,'CurrentFigure',pre_h); set_sD_stats; set(0,'CurrentFigure',old); case 'delete' if length(get(sets_h,'String')) == 1 msgbox('No data left. Closing program...') close_preprocess; return; end data=get(pre_h,'UserData'); if ~isempty(data.undo) & any(strcmp('index',fieldnames(data.undo))) if data.undo.index > index data.undo.index = data.undo.index-1; elseif data.undo.index==index; data.undo=[]; end end set1=data.sD_set(1:index-1); set2=data.sD_set(index+1:length(data.sD_set)); if ~isempty(set1) data.sD_set=[set1 set2]; else data.sD_set=set2; end if ~LOG data.LOG{length(data.LOG)+1}='% Delete a data set.'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''copy_delete'',''',... 'delete ',num2str(index),''');'); end set(pre_h,'UserData',data); set(sets_h,'Value',1); sD_names; sD_stats; old = gcf; set(0,'CurrentFigure',pre_h); for i=1:length(data.sD_set) string{i}=cat(2,sprintf('#%d: ',i),data.sD_set(i).name); end set(data.sD_set_h,'String',string); data.sData=data.sD_set(get(data.sD_set_h,'Value')); data.sData.MODIFIED=0; data.sData.INDEX=1; set(gcf,'UserData',data); write_sD_stats; sData=getfield(get(gcf,'UserData'),'sData'); if sData.INDEX > index value=get(getfield(get(gcf,'UserData'),'sD_set_h'),'Value'); set(getfield(get(gcf,'UserData'),'sD_set_h'),'Value',value-1); sData.INDEX = sData.INDEX -1; elseif sData.INDEX == index set(getfield(get(gcf,'UserData'),'sD_set_h'),'Value',1); end sel_sD; set(0,'CurrentFigure',old); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function clipping(varargin) if nargin ~= 1 pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); preh_udata=get(pre_h,'UserData'); preh_udata.LOG{length(preh_udata.LOG)+1}=... '% Starting the ''Clipping'' -window...'; preh_udata.LOG{length(preh_udata.LOG)+1}='preprocess(''clipping'',''foo'');'; set(pre_h,'UserData',preh_udata); end clip_h=findobj(get(0,'Children'),'Tag','Clipping'); if ~isempty(clip_h) figure(clip_h); return; end h0 = figure('Color',[0.8 0.8 0.8], ... 'PaperPosition',[18 180 575 432], ... 'PaperUnits','points', ... 'Position',[718 389 300 249], ... 'Tag','Clipping'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'ListboxTop',0, ... 'Position',[0.03 0.03614457831325301 0.4666666666666667 0.9236947791164658], ... 'Style','frame', ... 'Tag','Frame1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.05333333333333334 0.5983935742971887 0.42 0.3333333333333333], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Style','frame', ... 'Position',[0.05333333333333334 0.33 0.42 0.24], ... 'Tag','Frame3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Style','frame', ... 'Position',[0.05333333333333334 0.06 0.42 0.24],... 'Tag','Frame4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'ListboxTop',0, ... 'Position',[0.5133333333333334 0.6385542168674698 0.4666666666666667 0.321285140562249], ... 'Style','frame', ... 'Tag','Frame5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.5366666666666667 0.6666666666666666 0.42 0.2650602409638554], ... 'Style','frame', ... 'Tag','Frame6'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.31 0.823293172690763 0.15 0.09638554216867469], ... 'Style','edit', ... 'Tag','EditText1'); data.big_val_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.31 0.7148594377510039 0.15 0.09638554216867469], ... 'Style','edit', ... 'Tag','EditText2'); data.small_val_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.31 0.606425702811245 0.15 0.09638554216867469], ... 'Style','edit', ... 'Tag','EditText3'); data.equal_val_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',6, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.06000000000000001 0.8473895582329316 0.22 0.05622489959839357], ... 'String','Bigger than', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',6, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.06000000000000001 0.7389558232931727 0.24 0.04819277108433735], ... 'String','Smaller than', ... 'Style','text', ... 'Tag','StaticText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',6, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.06000000000000001 0.610441767068273 0.22 0.07228915662650602], ... 'String','Equal to', ... 'Style','text', ... 'Tag','StaticText3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.07000000000000001 0.465863453815261 0.06333333333333334 0.07228915662650602], ... 'Style','radiobutton', ... 'Value',1,... 'Tag','Radiobutton1'); data.and_button_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.07000000000000001 0.3734939759036144 0.06333333333333334 0.07228915662650602], ... 'Style','radiobutton', ... 'Tag','Radiobutton2'); data.or_button_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',6, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'Position',[0.1466666666666667 0.45 0.2333333333333333 0.07228915662650602], ... 'String','AND', ... 'Style','text', ... 'Tag','StaticText4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',6, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'String','OR', ... 'Position',[0.1466666666666667 0.35 0.2333333333333333 0.07228915662650602], ... 'Style','text', ... 'Tag','StaticText5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.07000000000000001 0.1967871485943775 0.06333333333333334 0.07228915662650602], ... 'Style','radiobutton', ... 'Value',1,... 'Tag','Radiobutton3'); data.all_button_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.07000000000000001 0.09236947791164658 0.06333333333333334 0.07228915662650602], ... 'Style','radiobutton', ... 'Tag','Radiobutton4'); data.sel_vects_button_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',6, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.1466666666666667 0.1927710843373494 0.2333333333333333 0.07228915662650602], ... 'String','All vectors', ... 'Style','text', ... 'Tag','StaticText6'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',6, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.1466666666666667 0.09638554216867469 0.3133333333333334 0.05622489959839357], ... 'String','Among selected', ... 'Style','text', ... 'Tag','StaticText7'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.7866666666666667 0.823293172690763 0.1366666666666667 0.09236947791164658], ... 'Style','edit', ... 'Tag','EditText4'); data.replace_val_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',6, ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.5633333333333334 0.8273092369477911 0.2066666666666667 0.07630522088353413], ... 'String','Replace', ... 'Style','text', ... 'Tag','StaticText8'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.5700000000000001 0.6827309236947791 0.3566666666666667 0.08032128514056225], ... 'String','Replace', ... 'Tag','Pushbutton1'); data.OK_button_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'Callback','preprocess close_c',... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.6633333333333333 0.07228915662650602 0.2833333333333333 0.09638554216867469], ... 'String','Close', ... 'Tag','Pushbutton2'); data.state.and=1; data.state.all=1; data.state.big=[]; data.state.small=[]; data.state.equal=[]; data.state.replace=[]; set(data.or_button_h,'Callback','preprocess and_or_cb or'); set(data.and_button_h,'Callback','preprocess and_or_cb and'); set(data.and_button_h,'Value',1); set(data.all_button_h,'Callback','preprocess all_sel_cb all'); set(data.sel_vects_button_h,'Callback','preprocess all_sel_cb sel'); set(data.big_val_h,'Callback','preprocess set_state_vals big'); set(data.small_val_h,'Callback','preprocess set_state_vals small'); set(data.equal_val_h,'Callback','preprocess set_state_vals equal'); set(data.replace_val_h,'Callback','preprocess set_state_vals replace'); set(data.OK_button_h,'Callback','preprocess clip_data clip'); set(h0,'UserData',data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select(varargin) if nargin ~= 1 pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); preh_udata=get(pre_h,'UserData'); preh_udata.LOG{length(preh_udata.LOG)+1}=... '% Starting the ''Select'' -window...'; preh_udata.LOG{length(preh_udata.LOG)+1}='preprocess(''select'',''foo'');'; set(pre_h,'UserData',preh_udata); end sel_h=findobj(get(0,'Children'),'Tag','Select'); if ~isempty(sel_h) figure(sel_h); return; end h0 = figure('Color',[0.8 0.8 0.8], ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',[750 431 168 365], ... 'Tag','Select'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'ListboxTop',0, ... 'Position',[0.05357142857142857 0.2712328767123288 0.8333333333333333 0.6301369863013698], ... 'Style','frame', ... 'Tag','Frame1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'ListboxTop',0, ... 'Position',[0.05357142857142857 0.1041095890410959 0.8333333333333333 0.1397260273972603], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0,... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.6547945205479452 0.75 0.2273972602739726], ... 'Style','frame', ... 'Tag','Frame3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.4794520547945206 0.75 0.1506849315068493], ... 'Style','frame', ... 'Tag','Frame4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.09523809523809523 0.2986301369863014 0.75 0.1506849315068493], ... 'Style','frame', ... 'Tag','Frame5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.5535714285714285 0.8082191780821918 0.2678571428571429 0.06575342465753425], ... 'Style','edit', ... 'Tag','EditText1'); data.big_val_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.5535714285714285 0.7342465753424657 0.2678571428571429 0.06575342465753425], ... 'Style','edit', ... 'Tag','EditText2'); data.small_val_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.5535714285714285 0.6602739726027397 0.2678571428571429 0.06575342465753425], ... 'Style','edit', ... 'Tag','EditText3'); data.equal_val_h=h1; h1 = uicontrol('Parent',h0, ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Units','normalized', ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.1071 0.8247 0.3929 0.0384], ... 'String','Bigger than', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Units','normalized', ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.1071 0.7507 0.4286 0.0329], ... 'String','Smaller than', ... 'Style','text', ... 'Tag','StaticText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.1071 0.6630 0.3929 0.0493], ... 'String','Equal to', ... 'Style','text', ... 'Tag','StaticText3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.125 0.5643835616438356 0.1130952380952381 0.04931506849315068], ... 'Style','radiobutton', ... 'Tag','Radiobutton1'); data.and_button_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.125 0.5013698630136987 0.1130952380952381 0.04931506849315068], ... 'Style','radiobutton', ... 'Tag','Radiobutton2'); data.or_button_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.2619047619047619 0.5561643835616439 0.3809523809523809 0.05205479452054795], ... 'String','AND', ... 'Style','text', ... 'Tag','StaticText4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.2619047619047619 0.4986301369863014 0.3809523809523809 0.04657534246575343], ... 'String','OR', ... 'Style','text', ... 'Tag','StaticText5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.125 0.3808219178082192 0.1130952380952381 0.04931506849315068], ... 'Style','radiobutton', ... 'Tag','Radiobutton3'); data.all_button_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.125 0.3095890410958904 0.1130952380952381 0.04931506849315068], ... 'Style','radiobutton', ... 'Tag','Radiobutton4'); data.sel_vects_button_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.2619047619047619 0.3780821917808219 0.4166666666666666 0.04931506849315068], ... 'String','All vectors', ... 'Style','text', ... 'Tag','StaticText6'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.2619047619047619 0.3123287671232877 0.5595238095238095 0.03835616438356165], ... 'String','Among selected', ... 'Style','text', ... 'Tag','StaticText7'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.0952 0.1178 0.7500 0.1068], ... 'Style','frame', ... 'Tag','Frame6'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.5298 0.1342 0.2738 0.0712], ... 'Style','edit', ... 'Tag','EditText4'); data.replace_val_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontSize',8,... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.1369047619047619 0.136986301369863 0.3214285714285714 0.06027397260273973], ... 'String','Vectors', ... 'Style','text', ... 'Tag','StaticText8'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.05357142857142857 0.01917808219178082 0.3869047619047619 0.0684931506849315], ... 'String','OK', ... 'Tag','Pushbutton1'); data.OK_button_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'Callback','preprocess close_s',... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.5 0.01917808219178082 0.3869047619047619 0.0684931506849315], ... 'String','Close', ... 'Tag','Pushbutton2'); data.state.and=1; data.state.all=1; data.state.big=[]; data.state.small=[]; data.state.equal=[]; data.state.replace=[]; set(data.or_button_h,'Callback','preprocess and_or_cb or'); set(data.and_button_h,'Callback','preprocess and_or_cb and'); set(data.and_button_h,'Value',1); set(data.all_button_h,'Callback','preprocess all_sel_cb all'); set(data.sel_vects_button_h,'Callback','preprocess all_sel_cb sel'); set(data.big_val_h,'Callback','preprocess set_state_vals big'); set(data.small_val_h,'Callback','preprocess set_state_vals small'); set(data.equal_val_h,'Callback','preprocess set_state_vals equal'); set(data.replace_val_h,'Callback','preprocess set_state_vals replace'); set(data.OK_button_h,'Callback','preprocess clip_data sel'); set(h0,'UserData',data); %%% Subfunction: and_or_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function and_or_cb(arg) %AND_OR_CB A callback function. Checks that only one of the radiobox % buttons 'AND' and 'OR' is pressed down. % % and_button_h=getfield(get(gcf,'UserData'),'and_button_h'); or_button_h=getfield(get(gcf,'UserData'),'or_button_h'); data=get(gcf,'UserData'); switch arg case 'or' set(and_button_h,'Value',0); set(or_button_h,'Value',1); data.state.and=0; case 'and' set(or_button_h,'Value',0); set(and_button_h,'Value',1); data.state.and=1; end set(gcf,'UserData',data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: all_sel_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function all_sel_cb(arg) all_button_h=getfield(get(gcf,'UserData'),'all_button_h'); sel_vects_button_h=getfield(get(gcf,'UserData'),'sel_vects_button_h'); data=get(gcf,'UserData'); switch arg case 'all' set(sel_vects_button_h,'Value',0); set(all_button_h,'Value',1); data.state.all=1; case 'sel' set(all_button_h,'Value',0); set(sel_vects_button_h,'Value',1); data.state.all=0; end set(gcf,'UserData',data); %%% Subfunction: set_state_vals %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function set_state_vals(arg) %SET_STATE_VALS sets the values to the UserData's state-struct. % % data=get(gcf,'UserData'); switch arg case 'big' big_val_h=getfield(get(gcf,'UserData'),'big_val_h'); val =str2num(get(big_val_h,'String')); dims=size(val); if dims(1) ~= 1 | dims(2) ~= 1 errordlg('Argument of the operation must be scalar.'); set(big_val_h,'String',''); return; end if isreal(val) data.state.big=val; else errordlg('Limits of the operation must be real.'); set(big_val_h,'String',''); return; end case 'small' small_val_h=getfield(get(gcf,'UserData'),'small_val_h'); val=str2num(get(small_val_h,'String')); dims=size(val); if dims(1) ~= 1 | dims(2) ~= 1 errordlg('Argument of the operation must be scalar.') set(small_val_h,'String',''); return; end if isreal(val) data.state.small=val; else errordlg('Limits of the operation must be real.'); set(small_val_h,'String',''); return; end case 'equal' equal_val_h=getfield(get(gcf,'UserData'),'equal_val_h'); val = str2num(get(equal_val_h,'String')); dims=size(val); if dims(1) ~= 1 | dims(2) ~= 1 errordlg('Argument of the operation must be scalar.'); set(equal_val_h,'String',''); return; end if isreal(val) data.state.equal=val; else errordlg('Limits of the operation must be real.'); set(equal_val_h,'String',''); return; end case 'replace' replace_val_h=getfield(get(gcf,'UserData'),'replace_val_h'); val=str2num(get(replace_val_h,'String')); dims=size(val); if (dims(1) ~= 1 | dims(2) ~= 1) & ~strcmp(get(gcf,'Tag'),'Select') errordlg('Argument of the operation must be scalar.'); set(replace_val_h,'String',''); return; end if isreal(val) data.state.replace=val; else errordlg('Limits of the operation must be real.'); set(replace_val_h,'String',''); return; end end set(gcf,'UserData',data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: clip_data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function clip_data(arg) %CLIP_DATA A callback function. Filters the data. % % i=1; while i <= length(arg) & arg(i) ~= ' ' i=i+1; end arg2=arg(i+1:length(arg)); arg=arg(1:i-1); if ~isempty(arg2) LOG=1; if strcmp(arg,'sel') c_h=findobj(get(0,'Children'),'Tag','Select'); else c_h=findobj(get(0,'Children'),'Tag','Clipping'); end set(0,'CurrentFigure',c_h); i=1; while i <= length(arg2) & arg2(i) ~= ' ' i=i+1; end BT=str2num(arg2(1:i-1)); i=i+1; j=i; while i <= length(arg2) & arg2(i) ~= ' ' i=i+1; end ST=str2num(arg2(j:i-1)); i=i+1; j=i; while i <= length(arg2) & arg2(i) ~= ' ' i=i+1; end EQ=str2num(arg2(j:i-1)); i=i+1; j=i; while i <= length(arg2) & arg2(i) ~= ' ' i=i+1; end AND_OR=str2num(arg2(j:i-1)); i=i+1; j=i; while i <= length(arg2) & arg2(i) ~= ' ' i=i+1; end ALL_AMONG=str2num(arg2(j:i-1)); i=i+1; j=i; while i <= length(arg2) i=i+1; end VECT_REPL=str2num(arg2(j:i-1)); else LOG=0; end if ~LOG big_val_h=getfield(get(gcf,'UserData'),'big_val_h'); small_val_h=getfield(get(gcf,'UserData'),'small_val_h'); equal_val_h=getfield(get(gcf,'UserData'),'equal_val_h'); replace_val_h=getfield(get(gcf,'UserData'),'replace_val_h'); end pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); if isempty(pre_h) errordlg('''Preprocess'' -figure does not exist. Terminating program...'); pro_tools('close'); return; end comp_names_h=getfield(get(pre_h,'UserData'),'comp_names_h'); selected=getfield(get(pre_h,'UserData'),'selected_vects'); sData=getfield(get(pre_h,'UserData'),'sData'); undo = sData; state=getfield(get(gcf,'UserData'),'state'); if LOG state.big=BT; state.small=ST; state.equal=EQ; state.replace=VECT_REPL; state.and=AND_OR; state.all=ALL_AMONG; end if isempty(pre_h) pro_tools('close'); end if isempty(get(comp_names_h,'Value')) clear_state_vals; errordlg('There must be one component chosen for the operation.'); return; end n_th_comp=getfield(get_indices,{1}); if isempty(state.big) & isempty(state.small) & isempty(state.equal) & ... strcmp(arg,'clip') clear_state_vals; errordlg('At least one limit must be chosen for the-operation.'); return; end if ~isempty(state.replace) & strcmp(arg,'sel') if ~all(state.replace == round(state.replace)) | any(state.replace < 1) errordlg('Indices of vectors must be positive integers.'); return; elseif any(state.replace > length(sData.data(:,1))) errordlg('Indices of the vectors to be selected are too big.'); return; end end if isempty(state.replace) & strcmp(arg,'clip') clear_state_vals; errordlg('Replace value must be determined for Clipping-operation.'); return; end if isempty(state.big) & isempty(state.small) & isempty(state.equal) & ... isempty(state.replace) clear_state_vals; return; end bt_indices=[]; lt_indices=[]; equal_indices=[]; if ~isempty(state.big) if state.all bt_indices=find(sData.data(:,n_th_comp) > state.big); else bt_indices=selected(find(sData.data(selected,n_th_comp) > state.big)); end end if ~isempty(state.small) if state.all lt_indices=find(sData.data(:,n_th_comp) < state.small); else lt_indices=selected(find(sData.data(selected,n_th_comp) < state.small)); end end if ~isempty(state.equal) if isnan(state.equal) if state.all equal_indices=find(isnan(sData.data(:,n_th_comp))); else equal_indices=selected(find(isnan(sData.data(selected,n_th_comp)))); end elseif state.all equal_indices=find(sData.data(:,n_th_comp)==state.equal); else equal_indices=selected(find(sData.data(selected,n_th_comp)==state.equal)); end end if state.and if ~isempty(bt_indices) | ~isempty(lt_indices) | ~isempty(equal_indices)... | strcmp(arg,'sel') if isempty(bt_indices) & isempty(lt_indices) & isempty(equal_indices) &... isempty(state.replace) clear_state_vals; return; end if isempty(bt_indices) if ~state.all bt_indices=selected; else bt_indices=1:getfield(size(sData.data),{1}); end end if isempty(lt_indices) if ~state.all lt_indices=selected; else lt_indices=1:getfield(size(sData.data),{1}); end end if isempty(equal_indices) if ~state.all equal_indices=selected; else equal_indices=1:getfield(size(sData.data),{1}); end end indices=intersect(intersect(bt_indices,lt_indices),equal_indices); if strcmp(arg,'sel') if ~isempty(indices) | ~isempty(state.replace) if isempty(state.replace) NOTEMPTY=0; if ~state.all state.replace=selected; else state.replace=1:getfield(size(sData.data),{1}); end else NOTEMPTY=1; end if isempty(indices) indices=selected; end indices=intersect(indices,state.replace); if isempty(indices) indices=selected; end data=get(pre_h,'UserData'); data.undo.sData=sData; data.undo.selected=data.selected_vects; data.selected_vects=indices; if ~LOG if ~NOTEMPTY data.LOG{length(data.LOG)+1}='% Select vectors.'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''clip_data'',''',... arg,... ' ',num2str(state.big),... ' ',num2str(state.small),... ' ',num2str(state.equal),... ' ',num2str(state.and),... ' ',num2str(state.all),... ''');'); else code=write_log_code(state.replace,... arg,... state.big,... state.small,... state.equal,... state.and,... state.all); data.LOG(length(data.LOG)+1:length(data.LOG)+length(code))=code; end end set(pre_h,'UserData',data); old=gcf; set(0,'CurrentFigure',pre_h); sel_comp; cplot_mimema; vect_means(data.sData,data.vect_mean_h,data.selected_vects); set(0,'CurrentFigure',old); end clear_state_vals; return; end sData.data(indices,n_th_comp) = state.replace; sData.MODIFIED=1; end else indices=union(union(bt_indices,lt_indices),equal_indices); if ~isempty(indices) | strcmp(arg,'sel') if strcmp(arg,'sel') if ~isempty(indices) | ~isempty(state.replace') data=get(pre_h,'UserData'); data.undo.sData=sData; data.undo.selected=data.selected_vects; data.selected_vects=union(indices,state.replace); if ~LOG if isempty(state.replace); data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''clip_data'',''',... arg,... ' ',num2str(state.big),... ' ',num2str(state.small),... ' ',num2str(state.equal),... ' ',num2str(state.and),... ' ',num2str(state.all),... ''');'); else code=write_log_code(state.replace,... arg,... state.big,... state.small,... state.equal,... state.and,... state.all); data.LOG(length(data.LOG)+1:length(data.LOG)+length(code))=code; end end set(pre_h,'UserData',data); old=gcf; set(0,'CurrentFigure',pre_h); sel_comp; vect_means(data.sData,data.vect_mean_h,data.selected_vects); cplot_mimema; set(0,'CurrentFigure',old); end clear_state_vals; return; end sData.data(indices,n_th_comp)=state.replace; sData.MODIFIED=1; end end if sData.MODIFIED data=get(pre_h,'UserData'); data.sData=sData; data.undo.sData=undo; if ~LOG if strcmp(arg,'sel') data.LOG{length(data.LOG)+1}='% Select vectors'; else data.LOG{length(data.LOG)+1}='% Clip values.'; end if strcmp(arg,'clip') | isempty(state.replace) data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''clip_data'',''',arg,... ' ',num2str(state.big),... ' ',num2str(state.small),... ' ',num2str(state.equal),... ' ',num2str(state.and),... ' ',num2str(state.all),... ' ',num2str(state.replace),... ''');'); else code=write_log_code(state.replace,... arg,... state.big,... state.small,... state.equal,... state.and,... state.all); data.LOG(length(data.LOG)+1:length(data.LOG)+length(code))=code; end end set(pre_h,'UserData',data); old=gcf; set(0,'CurrentFigure',pre_h) vector_h=getfield(get(gcf,'UserData'),'vector_h'); vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h'); set(gcf,'CurrentAxes',vector_h); vect_means(sData,vect_mean_h,selected); cplot_mimema; sel_comp; set(0,'CurrentFigure',old); end clear_state_vals; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: clear_state_vals %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function clear_state_vals %CLEAR_STATE_VALS Sets the fields of the UserData's state-struct empty. % % data=get(gcf,'UserData'); set(data.big_val_h,'String',''); set(data.small_val_h,'String',''); set(data.equal_val_h,'String',''); set(data.replace_val_h,'String',''); data.state.big=[]; data.state.small=[]; data.state.equal=[]; data.state.replace=[]; set(gcf,'UserData',data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function delay(varargin) delay_h=findobj(get(0,'Children'),'Tag','Delay'); if nargin ~= 1 pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); preh_udata=get(pre_h,'UserData'); preh_udata.LOG{length(preh_udata.LOG)+1}=... '% Starting the ''Delay'' -window...'; preh_udata.LOG{length(preh_udata.LOG)+1}='preprocess(''delay'',''foo'');'; set(pre_h,'UserData',preh_udata); end if ~isempty(delay_h) figure(delay_h); return; end h0 = figure('Color',[0.8 0.8 0.8], ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',[759 664 162 215], ... 'Tag','Delay'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'ListboxTop',0, ... 'Position',[0.05555555555555555 0.2046511627906977 0.8950617283950617 0.7441860465116279], ... 'Style','frame', ... 'Tag','Frame1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.08641975308641975 0.6976744186046512 0.8333333333333333 0.2232558139534884], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.08641975308641975 0.227906976744186 0.8333333333333333 0.4418604651162791], ... 'Style','frame', ... 'Tag','Frame3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'Callback','preprocess delay_data',... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.0556 0.0326 0.4012 0.1163], ... 'String','OK', ... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'Callback','preprocess close_d',... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.5494 0.0326 0.4012 0.1163], ... 'String','Close', ... 'Tag','Pushbutton2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.4876543209876543 0.7534883720930232 0.3518518518518519 0.1255813953488372], ... 'Style','edit', ... 'Tag','EditText1'); data.delay_val_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.1173 0.7860 0.3086 0.0651], ... 'String','Delay', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'Callback','preprocess clip_exp_cb c_this',... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.1173 0.5349 0.1173 0.0837], ... 'Style','radiobutton', ... 'Tag','Radiobutton1'); data.c_this_button_h=h1; data.mode='c_this'; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Callback','preprocess clip_exp_cb c_all',... 'ListboxTop',0, ... 'Position',[0.1173 0.4047 0.1173 0.0837], ... 'Style','radiobutton', ... 'Tag','Radiobutton2'); data.c_all_button_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Callback','preprocess clip_exp_cb e_all',... 'ListboxTop',0, ... 'Position',[0.1173 0.2651 0.1173 0.0837], ... 'Style','radiobutton', ... 'Tag','Radiobutton3'); data.e_all_button_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.26 0.5534883720930233 0.4135802469135802 0.06511627906976744], ... 'String','Clip this', ... 'Style','text', ... 'Tag','StaticText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.26 0.413953488372093 0.3765432098765432 0.06511627906976744], ... 'String','Clip all', ... 'Style','text', ... 'Tag','StaticText3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.26 0.2744186046511628 0.4197530864197531 0.06511627906976744], ... 'String','Expand all', ... 'Style','text', ... 'Tag','StaticText4'); set(gcf,'UserData',data); %%% Subfunction clip_exp_cb %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function clip_exp_cb(arg) c_this_button_h=getfield(get(gcf,'UserData'),'c_this_button_h'); c_all_button_h=getfield(get(gcf,'UserData'),'c_all_button_h'); e_all_button_h=getfield(get(gcf,'UserData'),'e_all_button_h'); data=get(gcf,'UserData'); switch arg case 'c_this' set(c_all_button_h,'Value',0); set(e_all_button_h,'Value',0); set(c_this_button_h,'Value',1); data.mode='c_this'; case 'c_all' set(c_this_button_h,'Value',0); set(e_all_button_h,'Value',0); set(c_all_button_h,'Value',1); data.mode='c_all'; case 'e_all' set(c_this_button_h,'Value',0); set(c_all_button_h,'Value',0); set(e_all_button_h,'Value',1); data.mode='e_all'; end set(gcf,'UserData',data); %%% Subfunction: delay_data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function delay_data(varargin) if nargin == 1 del_h=findobj(get(0,'Children'),'Tag','Delay'); set(0,'CurrentFigure',del_h); LOG=1; arg=varargin{1}; i=1; while i <= length(arg) & arg(i) ~= ' ' i=i+1; end delay=str2num(arg(1:i-1)); no=str2num(arg(i+1:length(arg))); else LOG=0; end pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); q='Delay operation is not evaluated.'; t='Warning'; if isempty(pre_h) errordlg('''Preprocess'' -figure does not exist. Terminating program...'); pro_tools('close'); return; end sData=getfield(get(pre_h,'UserData'),'sData'); undo = sData; data=get(gcf,'UserData'); if ~LOG delay=str2num(get(data.delay_val_h,'String')); if isempty(delay) errordlg('Value of ''Delay'' must be defined.'); return end set(data.delay_val_h,'String',''); if round(delay) ~= delay errordlg('Value of ''Delay'' must be integer.'); return; end end comp_names_h=getfield(get(pre_h,'UserData'),'comp_names_h'); if isempty(get(comp_names_h,'Value')) errordlg('There are not components chosen.'); return; end n_th_comp=getfield(get_indices,{1}); len=length(sData.data(:,1)); if LOG switch no case 1 data.mode='c_this'; preprocess('clip_exp_cb','c_this'); case 2 data.mode='c_all'; preprocess('clip_exp_cb','c_all'); case 3 data.mode='e_all'; preprocess('clip_exp_cb','e_all'); end end switch data.mode case 'c_this' MODE='1'; if delay > 0 sData.data(delay+1:len,n_th_comp)=sData.data(1:len-delay); if delay >= len errordlg(q,t); return; else sData.data(1:delay,n_th_comp)=NaN; end elseif delay < 0 sData.data(1:len+delay,n_th_comp)=... sData.data(abs(delay)+1:len,n_th_comp); if abs(delay) >= len errordlg(q,t); return; else sData.data(len+delay+1:len,n_th_comp)=NaN; end end if delay ~= 0 data=get(pre_h,'UserData'); sData.MODIFIED=1; sData.comp_norm(n_th_comp)=[]; data.sData=sData; data.undo.sData=undo; set(pre_h,'UserData',data); old = gcf; set(0,'CurrentFigure',pre_h); sel_comp; cplot_mimema; set(0,'CurrentFigure',old); end case 'c_all' MODE='2'; if delay > 0 sData.data(delay+1:len,n_th_comp)=sData.data(1:len-delay,n_th_comp); if delay >= len errordlg(q,t); return; else sData.data=sData.data(delay+1:len,:); end elseif delay < 0 sData.data(1:len+delay,n_th_comp)=sData.data(abs(delay)+1:len,n_th_comp); if abs(delay) >= len errordlg(q,t); return; else sData.data=sData.data(1:len+delay,:); end end if delay ~= 0 data=get(pre_h,'UserData'); sData.MODIFIED=1; sData.comp_norm(:,:)={[]}; data.sData=sData; data.undo.sData=undo; data.undo.selected=data.selected_vects; if delay > 0 data.selected_vects=... data.selected_vects(find(data.selected_vects>delay)); data.selected_vects=data.selected_vects-delay; elseif nargin == 1 data.selected_vects=... data.selected_vects(find(data.selected_vects<=len-abs(delay))); end set(pre_h,'UserData',data); old=gcf; set(0,'CurrentFigure',pre_h); vects=zeros(1,length(sData.data(:,1))); vects(data.selected_vects)=1; write_sD_stats; draw_vectors(vects,data.vector_h); sel_comp; cplot_mimema; set(0,'CurrentFigure',old); end case 'e_all' MODE='3'; if delay > 0 sData.data(len+1:len+delay,:)=NaN; sData.data(1+delay:delay+len,n_th_comp)=sData.data(1:len,n_th_comp); sData.data(1:delay,n_th_comp)=NaN; elseif delay < 0 delay=abs(delay); sData.data(delay+1:len+delay,:)=sData.data; sData.data(1:delay,:)=NaN; sData.data(1:len,n_th_comp)=sData.data(delay+1:len+delay,n_th_comp); sData.data(len+1:len+delay,n_th_comp)=NaN; end if delay ~= 0 data=get(pre_h,'UserData'); sData.MODIFIED=1; sData.comp_norm(:,:)={[]}; data.sData=sData; data.undo.sData=undo; data.undo.selected=data.selected_vects; set(pre_h,'UserData',data); old=gcf; set(0,'CurrentFigure',pre_h); write_sD_stats; pro_tools('selall'); set(0,'CurrentFigure',old); end end if ~LOG data=get(pre_h,'UserData'); data.LOG{length(data.LOG)+1}='% Delay a component.'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''delay_data'',''',... num2str(delay),' ',MODE,''');'); set(pre_h,'UserData',data); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function window(varargin) if nargin ~= 1 pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); preh_udata=get(pre_h,'UserData'); preh_udata.LOG{length(preh_udata.LOG)+1}=... '% Starting the ''Windowed'' -window...'; preh_udata.LOG{length(preh_udata.LOG)+1}='preprocess(''window'',''foo'');'; set(pre_h,'UserData',preh_udata); end win_h=findobj(get(0,'Children'),'Tag','Window'); if ~isempty(win_h) figure(win_h); return; end h0 = figure('Color',[0.8 0.8 0.8], ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'Position',[513 703 288 219], ... 'Tag','Window'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.752941176470588 0.752941176470588 0.752941176470588], ... 'ListboxTop',0, ... 'Position',[0.03125 0.1552511415525114 0.9375 0.7990867579908676], ... 'Style','frame', ... 'Tag','Frame1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.04861111111111111 0.7214611872146118 0.9027777777777777 0.2009132420091324], ... 'Style','frame', ... 'Tag','Frame2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.04861111111111111 0.1780821917808219 0.2777777777777778 0.5251141552511416], ... 'Style','frame', ... 'Tag','Frame3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.3611111111111111 0.1780821917808219 0.2777777777777778 0.5251141552511416], ... 'Style','frame', ... 'Tag','Frame4'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.6736111111111111 0.1780821917808219 0.2777777777777778 0.5251141552511416], ... 'Style','frame', ... 'Tag','Frame5'); h1 = uicontrol('Parent',h0, ... 'Callback','preprocess eval_windowed',... 'Units','normalized', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.03125 0.0319634703196347 0.2256944444444444 0.091324200913242], ... 'String','OK', ... 'Tag','Pushbutton1'); h1 = uicontrol('Parent',h0, ... 'Callback','preprocess close_w', ... 'Units','normalized', ... 'FontWeight','demi', ... 'ListboxTop',0, ... 'Position',[0.7430555555555555 0.0319634703196347 0.2256944444444444 0.091324200913242], ... 'String','Close', ... 'Tag','Pushbutton2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[1 1 1], ... 'ListboxTop',0, ... 'Position',[0.7083333333333333 0.7625570776255708 0.2083333333333333 0.1232876712328767], ... 'Style','edit', ... 'Tag','EditText1'); data.win_len_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.07638888888888888 0.8036529680365296 0.3784722222222222 0.0547945205479452], ... 'String','Window length', ... 'Style','text', ... 'Tag','StaticText1'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Callback','preprocess window_cb centered',... 'ListboxTop',0, ... 'Position',[0.06597222222222222 0.5616438356164384 0.06597222222222222 0.0821917808219178], ... 'Style','radiobutton', ... 'Tag','Radiobutton1'); data.centered_h=h1; data.position='center'; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Callback','preprocess window_cb previous',... 'ListboxTop',0, ... 'Position',[0.06597222222222222 0.4018264840182648 0.06597222222222222 0.0821917808219178], ... 'Style','radiobutton', ... 'Tag','Radiobutton2'); data.previous_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Callback','preprocess window_cb next',... 'ListboxTop',0, ... 'Position',[0.06597222222222222 0.2465753424657534 0.06597222222222222 0.0821917808219178], ... 'Style','radiobutton', ... 'Tag','Radiobutton3'); data.next_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Callback','preprocess window_cb mean',... 'ListboxTop',0, ... 'Position',[0.3784722222222222 0.5799086757990868 0.06597222222222222 0.0821917808219178], ... 'Style','radiobutton', ... 'Tag','Radiobutton4'); data.mean_h=h1; data.mode='mean'; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Callback','preprocess window_cb median',... 'ListboxTop',0, ... 'Position',[0.3784722222222222 0.4611872146118721 0.06597222222222222 0.0821917808219178], ... 'Style','radiobutton', ... 'Tag','Radiobutton5'); data.median_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Callback','preprocess window_cb max',... 'ListboxTop',0, ... 'Position',[0.3784722222222222 0.3515981735159817 0.06597222222222222 0.0821917808219178], ... 'Style','radiobutton', ... 'Tag','Radiobutton6'); data.max_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'Callback','preprocess window_cb min',... 'BackgroundColor',[0.8 0.8 0.8], ... 'ListboxTop',0, ... 'Position',[0.3784722222222222 0.2374429223744292 0.06597222222222222 0.0821917808219178], ... 'Style','radiobutton', ... 'Tag','Radiobutton7'); data.min_h = h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Callback','preprocess window_cb clip',... 'ListboxTop',0, ... 'Position',[0.6909722222222222 0.5525114155251141 0.06597222222222222 0.0821917808219178], ... 'Style','radiobutton', ... 'Tag','Radiobutton8'); data.clip_h=h1; data.eval_mode='clip'; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'Callback','preprocess window_cb expand',... 'ListboxTop',0, ... 'Position',[0.6909722222222222 0.2922374429223744 0.06597222222222222 0.0821917808219178], ... 'Style','radiobutton', ... 'Tag','Radiobutton9'); data.expand_h=h1; h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.132 0.5799 0.19 0.0548], ... 'String','Centered', ... 'Style','text', ... 'Tag','StaticText2'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.132 0.4247 0.1667 0.0548], ... 'String','Previous', ... 'Style','text', ... 'Tag','StaticText3'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.132 0.2648 0.1632 0.0548], ... 'String','Next', ... 'Style','text', ... 'Tag','StaticText4'); h1 = uicontrol('Parent',h0, ..., 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.445 0.6027397260273972 0.19 0.0547945205479452], ... 'String','Mean', ... 'Style','text', ... 'Tag','StaticText5'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.445 0.4795 0.1806 0.0548], ... 'String','Median', ... 'Style','text', ... 'Tag','StaticText6'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.445 0.3699 0.1667 0.0548], ... 'String','Max', ... 'Style','text', ... 'Tag','StaticText7'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.445 0.2557077625570776 0.1597222222222222 0.0547945205479452], ... 'String','Min', ... 'Style','text', ... 'Tag','StaticText8'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.7535 0.5753 0.1354 0.054], ... 'String','Clip', ... 'Style','text', ... 'Tag','StaticText9'); h1 = uicontrol('Parent',h0, ... 'Units','normalized', ... 'BackgroundColor',[0.8 0.8 0.8], ... 'FontWeight','demi', ... 'FontSize',8,... 'HorizontalAlignment','left', ... 'ListboxTop',0, ... 'Position',[0.7534722222222222 0.3150684931506849 0.1527777777777778 0.0547945205479452], ... 'String','Expand', ... 'Style','text', ... 'Tag','StaticText10'); set(gcf,'UserData',data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function window_cb(arg) data=get(gcf,'UserData'); if any(strcmp(arg,[{'centered'},{'previous'},{'next'}])) switch arg case 'centered' data.position='center'; set(data.previous_h,'Value',0); set(data.next_h,'Value',0); set(data.centered_h,'Value',1); case 'previous' data.position='previous'; set(data.centered_h,'Value',0); set(data.next_h,'Value',0); set(data.previous_h,'Value',1); case 'next' data.position='next'; set(data.centered_h,'Value',0); set(data.previous_h,'Value',0); set(data.next_h,'Value',1); end elseif any(strcmp(arg,[{'mean'},{'median'},{'min'},{'max'}])) switch arg case 'mean' data.mode='mean'; set(data.median_h,'Value',0); set(data.min_h,'Value',0); set(data.max_h,'Value',0); set(data.mean_h,'Value',1); case 'median' data.mode='median'; set(data.mean_h,'Value',0); set(data.max_h,'Value',0); set(data.min_h,'Value',0); set(data.median_h,'Value',1); case 'max' data.mode='max'; set(data.mean_h,'Value',0); set(data.median_h,'Value',0); set(data.min_h,'Value',0); set(data.max_h,'Value',1); case 'min' data.mode='min'; set(data.mean_h,'Value',0); set(data.median_h,'Value',0); set(data.max_h,'Value',0); set(data.min_h,'Value',1); end elseif any(strcmp(arg,[{'clip','expand'}])) switch arg case 'clip' data.eval_mode='clip'; set(data.expand_h,'Value',0); set(data.clip_h,'Value',1); case 'expand' data.eval_mode='expand'; set(data.clip_h,'Value',0); set(data.expand_h,'Value',1); end end set(gcf,'UserData',data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function eval_windowed(varargin) if nargin == 1 LOG=1; i=1; arg=varargin{1}; while i <= length(arg) & arg(i) ~= ' ' i=i+1; end value=str2num(arg(1:i-1)); i=i+1; j=i; while i <= length(arg) & arg(i) ~= ' ' i=i+1; end position=arg(j:i-1); i=i+1; j=i; while i <= length(arg) & arg(i) ~= ' ' i=i+1; end mode=arg(j:i-1); i=i+1; j=i; while i <= length(arg) & arg(i) ~= ' ' i=i+1; end eval_mode=arg(j:i-1); else LOG=0; end data=get(gcf,'UserData'); if LOG data.position=position; data.eval_mode=eval_mode; data.mode=mode; end pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); if isempty(pre_h) errordlg('''Preprocess''-window does not exist. Terminating program...'); pro_tools('close'); return; end comp_names_h=getfield(get(pre_h,'UserData'),'comp_names_h'); sData=getfield(get(pre_h,'UserData'),'sData'); undo=sData; if isempty(get(comp_names_h,'Value')) errordlg('There are not components chosen.'); return; end if ~LOG if isempty(get(data.win_len_h,'String')) errordlg('Window length must be defined'); return; end value=str2num(get(data.win_len_h,'String')); end set(data.win_len_h,'String',''); if ~LOG if isempty(value) | value < 0 | value ~= round(value) errordlg('Window length must be positive integer.'); return; end if value > length(sData.data(:,1)) errordlg('Length of window is too big.'); return; end end index=getfield(get_indices,{1}); sData=eval_operation(sData,value,data.mode,data.eval_mode,data.position,index); sData.comp_norm(index)={[]}; u_data=get(pre_h,'UserData'); u_data.sData=sData; u_data.undo.sData=undo; u_data.undo.selected=u_data.selected_vects; if ~LOG u_data.LOG{length(u_data.LOG)+1}=... '% Evaluating the wanted ''windowed'' -operation.'; u_data.LOG{length(u_data.LOG)+1}=cat(2,'preprocess(''eval_windowed'',',... '''',num2str(value),... ' ',data.position,' ',data.mode,... ' ',data.eval_mode,''');'); end set(pre_h,'UserData',u_data); old=gcf; set(0,'CurrentFigure',pre_h); if strcmp(data.eval_mode,'expand'); write_sD_stats; pro_tools('selall'); else sel_comp; cplot_mimema; end set(0,'CurrentFigure',old); %%% Subfunction: eval_operation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sData=eval_operation(sData,winlen,mode,evalmode,position,n) len=length(sData.data(:,1)); dim=length(sData.data(1,:)); switch(position) case 'center' prev=round(winlen/2)-1; next=winlen-round(winlen/2); case 'previous' prev=winlen-1; next=0; case 'next' prev=0; next=winlen-1; end switch(evalmode) case 'clip' for center=1:len win=center-prev:center-prev+winlen-1; win=win(find(win > 0 & win <= len)); str=cat(2,mode,'(sData.data(win(find(~isnan(sData.data(win,n)))),n))'); tmp(center)=eval(str); end sData.data(:,n)=tmp; case 'expand' for i=1:len+winlen-1 win=i-(winlen-1):i; win=win(find(win > 0 & win <= len)); str=cat(2,mode,'(sData.data(win(find(~isnan(sData.data(win,n)))),n))'); tmp(i)=eval(str); end sData.data=cat(1,repmat(NaN,next,dim),sData.data,repmat(NaN,prev,dim)); sData.data(:,n)=tmp; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function pro_tools(arg) switch arg case 'close' close_preprocess; case 'c_stat' write_c_stats; case 'plot_hist' plot_hist; case 'plot' plot_button; case 'plxy' plxy_button; case 'bplo' bplo_button; case 'hist' hist_button; end %%% Subfunction close_preprocess %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function close_preprocess pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); man_h=findobj(get(0,'Children'),'Tag','Management'); clip_h=findobj(get(0,'Children'),'Tag','Clipping'); plot_h=findobj(get(0,'Children'),'Tag','PlotWin'); delay_h=findobj(get(0,'Children'),'Tag','Delay'); window_h=findobj(get(0,'Children'),'Tag','Window'); sel_h=findobj(get(0,'Children'),'Tag','Select'); if ~isempty(man_h) close(man_h); end if ~isempty(clip_h) close(clip_h); end if ~isempty(plot_h) close(plot_h); end if ~isempty(delay_h) close(delay_h); end if ~isempty(window_h) close(window_h); end if ~isempty(sel_h) close(sel_h); end if ~isempty(pre_h) close(pre_h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: undo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function undo(varargin) if nargin == 1 pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); set(0,'CurrentFigure',pre_h); LOG=1; else LOG=0; end data=get(gcf,'UserData'); if ~isempty(data.undo) if any(strcmp('selected',fieldnames(data.undo))) data.selected_vects=data.undo.selected; end if ~any(strcmp('index',fieldnames(data.undo))) data.sData=data.undo.sData; data.undo=[]; if ~LOG data.LOG{length(data.LOG)+1}='% Undo the most recent operation.'; data.LOG{length(data.LOG)+1}='preprocess(''undo'',''foo'');'; end set(gcf,'UserData',data); set_compnames(data.sData,data.comp_names_h); write_sD_stats; vect_means(data.sData,data.vect_mean_h,data.selected_vects); sel_comp; cplot_mimema; return; end % 'undo.sData' does not exist in sD_set - array index=data.undo.index; data.undo.sData=rmfield(data.undo.sData,[{'INDEX'};{'MODIFIED'}]); if index<=length(data.sD_set) rest=data.sD_set(index:length(data.sD_set)); else rest=[]; end data.sD_set=cat(2,data.sD_set(1:index-1),data.undo.sData,rest); data.undo=[]; if ~LOG data.LOG{length(data.LOG)+1}='% Undo the most recent operation.'; data.LOG{length(data.LOG)+1}='preprocess(''undo'',''foo'');'; end set(gcf,'UserData',data); set(getfield(get(gcf,'UserData'),'sD_set_h'),'Value',index); set_sD_stats; sel_sD; else msgbox('Can''t do...'); end %%% Subfunction: write_c_stats %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function write_c_stats(varargin) pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); comp_names_h=getfield(get(pre_h,'UserData'),'comp_names_h'); sel_comp_h=getfield(get(pre_h,'UserData'),'sel_comp_h'); sel_chist_h=getfield(get(pre_h,'UserData'),'sel_chist_h'); if nargin==1 val1=varargin(1); else val1=get(sel_comp_h,'String'); end if ~isempty(val1) & iscell(val1) selected_vects=getfield(get(pre_h,'UserData'),'selected_vects'); sData=getfield(get(pre_h,'UserData'),'sData'); sel_cdata_h=getfield(get(pre_h,'UserData'),'sel_cdata_h'); name=getfield(get(sel_comp_h,'String'),{get(sel_comp_h,'Value')}); name=name{1}; i=2; while ~isempty(str2num(name(i))) value(i-1)=name(i); i=i+1; end value=str2num(value); data=sData.data(selected_vects,value); string{1} = cat(2,'Min: ',sprintf('%-10.3g',min(data))); string{2} = cat(2,'Mean: ',sprintf('%-10.3g',mean(data(find(~isnan(data)))))); string{3} = cat(2,'Max: ',sprintf('%-10.3g',max(data))); string{4} = cat(2,'Std: ',sprintf('%-10.3g',std(data(find(~isnan(data)))))); string{5} = cat(2,'Number of NaNs: ',sprintf('%-10.3g',sum(isnan(data)))); string{6} = cat(2,'NaN (%):',... sprintf('%-10.3g',100*sum(isnan(data))/length(data))); string{7} = cat(2,'Number of values: ',sprintf('%-10.3g',... length(find(~isnan(unique(data)))))); set(sel_cdata_h,'String',string); set(sel_cdata_h,'HorizontalAlignment','left'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction plot_hist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_hist pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); sel_chist_h=getfield(get(pre_h,'UserData'),'sel_chist_h'); sData=getfield(get(pre_h,'UserData'),'sData'); selected=getfield(get(pre_h,'UserData'),'selected_vects'); value=get(getfield(get(pre_h,'UserData'),'sel_comp_h'),'Value'); subplot(sel_chist_h); hold off; cla; if all(isnan(sData.data(:,value))); return; end hold on; lim1=min(sData.data(:,value)); lim2=max(sData.data(:,value)); if lim2 - lim1 >= eps x=lim1:(lim2-lim1)/(30-1):lim2; set(sel_chist_h,'XLim',[lim1 lim2]); elseif lim1 ~= 0 x=(lim1)/2:lim1/(30-1):lim1+(lim1)/2; set(sel_chist_h,'Xlim',[lim1-abs(lim1/2) lim1+abs(lim1/2)]); else x=-1:2/(30-1):1; set(sel_chist_h,'XLim',[-1 1]); end hist(sData.data(selected,value),x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: select_all %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_all(varargin) if nargin == 1 LOG=1; else LOG=0; end data=get(gcf,'UserData'); data.selected_vects=(1:length(data.sData.data(:,1))); if ~LOG data.LOG{length(data.LOG)+1}='% Select all vectors.'; data.LOG{length(data.LOG)+1}='selall(''foo'');'; end set(gcf,'UserData',data); tmp=zeros(1,length(data.sData.data(:,1))); tmp(data.selected_vects)=1; draw_vectors(tmp,data.vector_h); cplot_mimema; vect_means(data.sData,data.vect_mean_h,data.selected_vects); sel_comp; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: plot_button %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_button %PLOT_BUTTON A callback function. Plots all the components and marks % the chosen components. % % sData=getfield(get(gcf,'UserData'),'sData'); selected=getfield(get(gcf,'UserData'),'selected_vects'); indices=get_indices; if isempty(indices) return; end h=findobj(get(0,'Children'),'Tag','PlotWin'); if isempty(h) h= figure; set(h,'Tag','PlotWin'); end names=sData.comp_names(indices); data=sData.data(:,indices); set(0,'CurrentFigure',h); hold off; clf; t=0:1/(getfield(size(data),{1})-1):1; tmp=setdiff(1:length(data(:,1)),selected); for i=1:length(names) subplot(length(names),1,i); hold on; if max(data(:,i))- min(data(:,i)) <= eps set(gca,'YLim',[max(data(:,i))-1 max(data(:,i))+1]); end plot(t,data(:,i)); if ~isempty(tmp); data(tmp,i)=NaN; end plot(t,data(:,i),'red'); ylabel(names{i}); set(gca,'XTick',[]); end set(gcf,'Name','Plotted Data Components'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: plxy_button %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plxy_button %PLXY_BUTTON A callback function. XY-plots the first and the second % components chosen. % % sData=getfield(get(gcf,'UserData'),'sData'); selected=getfield(get(gcf,'UserData'),'selected_vects'); inds = get_indices; if length(inds) < 2 errordlg('There must be two components chosen for XY-plot.'); return; end inds=inds(1:2); names=getfield(sData,'comp_names',{inds}); h=findobj(get(0,'Children'),'Tag','PlotWin'); if isempty(h) h= figure; set(h,'Tag','PlotWin'); end set(0,'CurrentFigure',h); clf; axes; if max(sData.data(:,inds(1))) - min(sData.data(:,inds(1))) <= eps set(gca,'XLim',[max(sData.data(:,inds(1)))-1 max(sData.data(:,inds(1)))+1]); end if max(sData.data(:,inds(2))) - min(sData.data(:,inds(2))) <= eps set(gca,'YLim',[max(sData.data(:,inds(2)))-1 max(sData.data(:,inds(2)))+1]); end hold on; plot(sData.data(:,inds(1)),sData.data(:,inds(2)),'o'); x=sData.data(selected,inds(1)); y=sData.data(selected,inds(2)); plot(x,y,'ored','MarkerSize',4); xlabel(names(1)); ylabel(names(2)); set(h,'Name','Plotted Data Components'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Sub_function: bplo_button %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bplo_button %BPLO_BUTTON A callback function. Box-plots the first component chosen. sData=getfield(get(gcf,'UserData'),'sData'); selected=getfield(get(gcf,'UserData'),'selected_vects'); if length(selected) == 1 errordlg('There are too few vectors chosen for box-plotting.'); else indices=get_indices; if isempty(indices) return; end for i=1:length(indices) if length(unique(sData.data(selected,indices(i))))==1 errordlg('All the values are the same. Operation can''t be evaluated.'); return; end end names=getfield(sData,'comp_names',{indices}); h= findobj(get(0,'Children'),'Tag','PlotWin'); if isempty(h) h= figure; set(h,'Tag','PlotWin'); end data=sData.data(selected,indices); set(0,'CurrentFigure',h); hold off; clf; hold on; for i=1:getfield(size(data),{2}) subplot(getfield(size(data),{2}),1,i); if ~all(isnan(data(:,i))) boxplot(data(:,i)); end name=names{i}; tmp=get(get(gca,'YLabel'),'String'); ylabel(cat(2,sprintf('[%s] ',name),tmp)); end set(h,'Name','Box-plot'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: hist_button %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hist_button no_of_bins_h=getfield(get(gcf,'UserData'),'no_of_bins_h'); selected=getfield(get(gcf,'UserData'),'selected_vects'); sData=getfield(get(gcf,'UserData'),'sData'); n=str2num(get(no_of_bins_h,'String')); s1='Invalid number of bins.'; s2=sprintf('\nSet new value to the box under the ''Histogram''-button.'); if isempty(n) errordlg(cat(2,s1,s2)); else indices=get_indices; if isempty(indices) return; end n=round(n); if n < 1 errordlg('Number of bins must be positive integer.'); else h= findobj(get(0,'Children'),'Tag','PlotWin'); if isempty(h) h= figure; set(h,'Tag','PlotWin'); end set(0,'CurrentFigure',h); hold off; clf; data=sData.data(selected,indices); names=sData.comp_names(indices); for i=1:length(names) subplot(length(names),1,i); hold on; lim1=min(sData.data(:,indices(i))); lim2=max(sData.data(:,indices(i))); if n > 1 if lim2 - lim1 >= eps x=lim1:(lim2-lim1)/(n-1):lim2; set(gca,'XLim',[lim1 lim2]); elseif lim1 ~= 0 x=lim1/2:lim1/(n-1):lim1/2+lim1; if ~all(isnan([lim1 lim2])) set(gca,'XLim',[lim1-abs(lim1/2) lim1+abs(lim1/2)]); end else x=-1:2/(n-1):1; set(gca,'XLim',[-1 1]); end else x=1; if lim2 ~= lim1 set(gca,'XLim',[lim1 lim2]); else set(gca,'XLim',[lim1/2 lim1/2+lim1]); end end if ~all(isnan(data(:,i))) hist(data(:,i),x); end name=names{i}; xlabel(name); end set(h,'Name','Histogram'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: no_of_values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function no_of_values(varargin); %NO_OF_VALUES A callback function. Calculates the number of different % values of the chosen components. % % if nargin==1; LOG=1; else LOG=0; end pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); results_h=getfield(get(pre_h,'UserData'),'results_h'); sData=getfield(get(pre_h,'UserData'),'sData'); selected=getfield(get(pre_h,'UserData'),'selected_vects'); str1='There must be one component chosen for ''Number of Values''-operation'; if ~LOG & isempty(get_indices) errordlg(str1); else indices=get_indices; data=sData.data(selected,indices); string{1} = 'Number of different values:'; for i=1:getfield(size(data),{2}) tmp=data(:,i); string{i+1}=cat(2,sprintf('#%d:',indices(i)),... sprintf('%d',length(find(~isnan(unique(data(:,i))))))); end set(results_h,'String',string); set(results_h,'HorizontalAlignment','left'); if ~LOG data=get(pre_h,'UserData'); data.LOG{length(data.LOG)+1}='% Number of values'; data.LOG{length(data.LOG)+1}='preprocess(''noof'',''foo'');'; set(pre_h,'UserData',data); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: correlation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function correlation(varargin) if nargin == 1 LOG=1; else LOG=0; end pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); results_h=getfield(get(pre_h,'UserData'),'results_h'); selected=getfield(get(pre_h,'UserData'),'selected_vects'); sData=getfield(get(pre_h,'UserData'),'sData'); if length(get_indices) < 2 errordlg('There must be two components chosen for Correlation'); else indices=getfield(get_indices,{1:2}); data=sData.data(selected,indices); inds=find(~isnan(data(:,1)) & ~isnan(data(:,2))); value=getfield(corrcoef(data(inds,1),data(inds,2)),{1,2}); names=sData.comp_names(indices); string{1}='Correlation between'; string{2}=cat(2,names{1},' and ',names{2},':'); string{3}=sprintf('%-10.3g',value); set(results_h,'String',string); set(results_h,'HorizontalAlignment','left'); if ~LOG data=get(pre_h,'UserData'); data.LOG{length(data.LOG)+1}='% Correlation'; data.LOG{length(data.LOG)+1}='preprocess(''corr'',''foo'');'; set(pre_h,'UserData',data); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: unit_length %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function unit_length(varargin) %UNIT_LENGTH A callback function Scales all the vectors to the unit % length. % % if nargin==1 LOG=1; else LOG=0; end vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h'); sData=getfield(get(gcf,'UserData'),'sData'); sData.MODIFIED=1; scaled=sData.data; comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h'); if ~LOG & isempty(get(comp_names_h,'Value')) errordlg('There must be components chosen for the ''unit length''- operation'); return; end inds=get_indices; for i=1:length(scaled(:,1)); x=find(~isnan(scaled(i,inds))); scaled(i,inds(x))=(1/sqrt(sum(scaled(i,inds(x)).^2)))*scaled(i,inds(x)); end data=get(gcf,'UserData'); data.undo.sData = sData; data.sData.data=scaled; for i=1:length(inds) data.sData.comp_norm{inds(i)}=[]; end if ~LOG data.LOG{length(data.LOG)+1}='% Unit length'; data.LOG{length(data.LOG)+1}='preprocess(''unit'',''foo'');'; end set(gcf,'UserData',data); vects=zeros(1,length(sData.data(:,1))); vects(data.selected_vects)=1; draw_vectors(vects,data.vector_h); vect_means(sData,vect_mean_h,data.selected_vects); cplot_mimema; plot_hist; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: one_of_n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function one_of_n(varargin) if nargin==1 LOG=1; else LOG=0; end data=get(gcf,'UserData'); vector_h=getfield(get(gcf,'Userdata'),'vector_h'); comp_names_h=getfield(get(gcf,'Userdata'),'comp_names_h'); vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h'); sData=data.sData; undo=data.sData; selected=getfield(get(gcf,'UserData'),'selected_vects'); msg='Creating over 10 new components. Stop operation?'; if ~LOG if isempty(get(data.comp_names_h,'Value')) errordlg('There must be one component chosen for ''Add: N binary types'' -operation'); return; end end index=getfield(get_indices,{1}); tmp=unique(sData.data(:,index)); n=length(tmp); if ~LOG if n>10 answer=questdlg(msg,'Question','Yes','No','Yes'); if strcmp(answer,'Yes') msgbox('Operation stopped.'); return; end end end dim1=getfield(size(sData.data),{1}); dim2=getfield(size(sData.data),{2}); sData.data=cat(2,sData.data,zeros(dim1,n)); dim=dim2+n; for i=1:n sData.data(:,dim-(n-i))=(sData.data(:,index) == tmp(i)); end INDEX=sData.INDEX; for i=1:n sData.comp_names{dim2+i}=sprintf('%dNewVar',dim2+i); end tmp_norm=cat(1,sData.comp_norm,cell(n,1)); sData=som_data_struct(sData.data,... 'name',sData.name,... 'labels',sData.labels,... 'comp_names',sData.comp_names); sData.MODIFIED=1; sData.INDEX=INDEX; sData.comp_norm=tmp_norm; data.undo.sData=undo; data.sData=sData; data.selected_vects=1:length(sData.data(:,1)); if ~LOG data.LOG{length(data.LOG)+1}='% Add: N binary types'; data.LOG{length(data.LOG)+1}='preprocess(''oneo'',''foo'');'; end set(gcf,'UserData',data); clear_button; write_sD_stats; set_compnames(sData,comp_names_h); tmp=ones(1,length(sData.data(:,1))); draw_vectors(tmp,vector_h); vect_means(sData,vect_mean_h,1:length(sData.data(:,1))); cplot_mimema; sel_comp; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: add_zeros %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function add_zeros(varargin) if nargin == 1 LOG=1; else LOG=0; end data=get(gcf,'UserData'); vector_h=getfield(get(gcf,'Userdata'),'vector_h'); comp_names_h=getfield(get(gcf,'Userdata'),'comp_names_h'); vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h'); sData=data.sData; undo=sData; dim1=getfield(size(sData.data),{1}); dim2=getfield(size(sData.data),{2}); sData.data=cat(2,sData.data,zeros(dim1,1)); INDEX=sData.INDEX; sData.comp_names{dim2+1}=sprintf('%dNewVar',dim2+1); tmp_norm=cat(1,sData.comp_norm,cell(1,1)); sData=som_data_struct(sData.data,... 'name',sData.name,... 'labels',sData.labels,... 'comp_names',sData.comp_names); sData.MODIFIED=1; sData.INDEX=INDEX; sData.comp_norm=tmp_norm; data.sData=sData; data.undo.sData=undo; data.selected_vects=1:length(sData.data(:,1)); if ~LOG data.LOG{length(data.LOG)+1}='% Add: zeros'; data.LOG{length(data.LOG)+1}='preprocess(''zero'',''foo'');'; end set(gcf,'UserData',data); clear_button; write_sD_stats; set_compnames(sData,comp_names_h); tmp=ones(1,length(sData.data(:,1))); draw_vectors(tmp,vector_h); vect_means(sData,vect_mean_h,1:length(sData.data(:,1))); cplot_mimema; sel_comp; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: move_component %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function move_component(varargin) %MOVE_COMPONENT A callback function. Moves one component of vectors to % the position wanted. % % if nargin == 1 LOG=1; i=1; while varargin{1}(i) ~= ' ' value(i)=varargin{1}(i); i=i+1; end value=str2num(value); % the new place index=str2num(varargin{1}(i:length(varargin{1}))); % index of the chosen % component else LOG=0; end data=get(gcf,'UserData'); sData=data.sData; undo=sData; prompt='Enter the number of the new component place:'; if isempty(get(data.comp_names_h,'Value')) errordlg('There must be one component chosen for ''Move Component''-operation'); return; end if ~LOG index=getfield(get_indices,{1}); answer=inputdlg(prompt); if isempty(answer) | (iscell(answer) & isempty(answer{1})) msgbox('No components moved'); return; end value=str2num(answer{1}); dims=size(value); if dims(1) ~= 1 | dims(2) ~= 1 | ~isreal(value) errordlg('The new component place must be positive integer.') return; end if value <= 0 | round(value) ~= value errordlg('The new component place must be positive integer.'); return; end if value > getfield(size(sData.data),{2}) errordlg('Too big value for the new component place.'); return; end end sData.MODIFIED=1; if index < value indices1=setdiff(1:value,index); indices2=setdiff(value+1:length(sData.data(1,:)),index); elseif index > value indices1=setdiff(1:value-1,index); indices2=setdiff(value:length(sData.data(1,:)),index); else data.sData=sData; data.undo.sData=undo; set(gcf,'UserData',data); return; end tmp1=sData.data(:,indices1); tmp2=sData.data(:,indices2); sData.data=cat(2,tmp1,sData.data(:,index),tmp2); tmp1=sData.comp_names(indices1); tmp2=sData.comp_names(indices2); sData.comp_names=cat(1,tmp1,sData.comp_names(index),tmp2); tmp1=sData.comp_norm(indices1); tmp2=sData.comp_norm(indices2); sData.comp_norm=cat(1,tmp1,sData.comp_norm(index),tmp2); data.sData=sData; data.undo.sData=undo; if ~LOG data.LOG{length(data.LOG)+1}='% Move component.'; data.LOG{length(data.LOG)+1}=sprintf('preprocess(''move'',''%s %s'');',... num2str(value),num2str(index)); end comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h'); vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h'); vector_h=getfield(get(gcf,'UserData'),'vector_h'); data.selected_vects=1:length(sData.data(:,1)); set(gcf,'UserData',data); clear_button; set_compnames(sData,comp_names_h); draw_vectors(ones(1,length(sData.data(:,1))),vector_h); vect_means(sData,vect_mean_h,data.selected_vects); cplot_mimema; sel_comp; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: copy_component %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function copy_component(varargin) %COPY_COMPONENT Copies one component of vectors to the position wanted. % % if nargin == 1 LOG=1; i=1; while varargin{1}(i) ~= ' ' value(i)=varargin{1}(i); i=i+1; end value=str2num(value); % the new place index=str2num(varargin{1}(i:length(varargin{1}))); % index of the chosen % component else LOG=0; end data=get(gcf,'UserData'); sData=data.sData; undo=sData; if ~LOG prompt='Enter the number of the new component place:'; if isempty(get(data.comp_names_h,'Value')) errordlg('There must be one component chosen for ''Copy Component''-operation'); return; end index=getfield(get_indices,{1}); answer=inputdlg(prompt); if isempty(answer) | (iscell(answer) & isempty(answer{1})) msgbox('No components moved'); return end value=str2num(answer{1}); dims=size(value); if dims(1) ~= 1 | dims(2) ~= 1 | ~isreal(value) errordlg('The new component place must be positive integer.') return; end if value <= 0 | round(value) ~= value errordlg('The new component place must be positive integer.'); return; end if value > getfield(size(sData.data),{2}) + 1 errordlg('Too big value for the new component place.'); return; end end sData.MODIFIED=1; indices1=1:value-1; indices2=value:length(sData.data(1,:)); tmp1=sData.data(:,indices1); tmp2=sData.data(:,indices2); sData.data=cat(2,tmp1,sData.data(:,index),tmp2); tmp1=sData.comp_names(indices1); tmp2=sData.comp_names(indices2); name=cell(1,1); name{1}=cat(2,'Copied',sData.comp_names{index}); sData.comp_names=cat(1,tmp1,name,tmp2); tmp1=sData.comp_norm(indices1); tmp2=sData.comp_norm(indices2); norm=cell(1,1); norm{1}=sData.comp_norm{index}; sData.comp_norm=cat(1,tmp1,norm,tmp2); data.sData=sData; data.undo.sData=undo; if ~LOG data.LOG{length(data.LOG)+1}='% Copy component'; data.LOG{length(data.LOG)+1}=sprintf('preprocess(''copy'',''%s %s'');',... num2str(value),num2str(index)); end comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h'); vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h'); vector_h=getfield(get(gcf,'UserData'),'vector_h'); data.selected_vects=1:length(sData.data(:,1)); set(gcf,'UserData',data); clear_button; write_sD_stats; set_compnames(sData,comp_names_h); draw_vectors(ones(1,length(sData.data(:,1))),vector_h); vect_means(sData,vect_mean_h,data.selected_vects); cplot_mimema; sel_comp; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: remove_component %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function remove_component(varargin) if nargin == 1 LOG=1; value=str2num(varargin{1}); else LOG=0; end data=get(gcf,'UserData'); vect_mean_h=getfield(get(gcf,'UserData'),'vect_mean_h'); vector_h=getfield(get(gcf,'UserData'),'vector_h'); comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h'); sData=data.sData; undo=sData; prompt='Enter the number of component to be removed.'; dim=length(sData.data(1,:)); if ~LOG answer=inputdlg(prompt); if isempty(answer) | (iscell(answer) & isempty(answer{1})) msgbox('Components not removed.'); return; end value=str2num(answer{1}); dims=size(value); if dims(1) ~= 1 | dims(2) ~= 1 | ~isreal(value) errordlg('Number of the component to be removed must be positive integer.') return; end if value <= 0 | round(value) ~= value errordlg('Number of the component to be removed must be positive integer.'); return; end if value > getfield(size(sData.data),{2}) errordlg('There are less components.'); return; end end sD_set_h=getfield(get(gcf,'UserData'),'sD_set_h'); index=get(sD_set_h,'Value'); if value == 1 & getfield(size(sData.data),{2}) == 1 if length(get(sD_set_h,'String')) == 1 msgbox('No data left. Closing program...') pro_tools('close'); return; end set1=data.sD_set(1:index-1); set2=data.sD_set(index+1:length(data.sD_set)); data.sD_set=[set1 set2]; set(gcf,'UserData',data); set_sD_stats; sel_sD; data=get(gcf,'UserData'); data.undo.sData=undo; data.undo.index=index; set(gcf,'UserData',data); return; end dims=size(sData.data); tmp_data=cat(2,sData.data(:,1:value-1),sData.data(:,value+1:dims(2))); tmp_norm=cat(1,sData.comp_norm(1:value-1),sData.comp_norm(value+1:dims(2))); names=cat(1,sData.comp_names(1:value-1),sData.comp_names(value+1:dims(2))); INDEX=sData.INDEX; comp_norm=sData.comp_norm; sData=som_data_struct(tmp_data,... 'name',sData.name,... 'labels',sData.labels,... 'comp_names',names); sData.comp_norm=tmp_norm; sData.MODIFIED=1; sData.INDEX=INDEX; data=get(gcf,'UserData'); data.sData=sData; data.undo.sData=undo; data.selected_vects=1:length(sData.data(:,1)); if ~LOG data.LOG{length(data.LOG)+1}='% Remove component'; data.LOG{length(data.LOG)+1}=sprintf('preprocess(''remove'',''%s'');',... answer{1}); end set(gcf,'UserData',data); clear_button; write_sD_stats; set_compnames(sData,comp_names_h); tmp=ones(1,length(sData.data(:,1))); draw_vectors(tmp,vector_h); vect_means(sData,vect_mean_h,1:length(sData.data(:,1))); cplot_mimema; sel_comp; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: remove_vects %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function remove_vects(varargin) if nargin==1 LOG=1; tmp_str=varargin{1}; else LOG=0; tmp_str='_foo'; end data=get(gcf,'UserData'); vect_mean_h=data.vect_mean_h; vector_h=data.vector_h; sData=data.sData; undo=sData; if length(data.selected_vects) == getfield(size(sData.data),{1}) if LOG answer='Yes'; else answer=questdlg('Do you want to delete this data set?'); end if strcmp(answer,'No') return; else index=get(data.sD_set_h,'Value'); if length(get(data.sD_set_h,'String')) == 1 msgbox('No data left. Closing program...') pro_tools('close'); return; end set1=data.sD_set(1:index-1); set2=data.sD_set(index+1:length(data.sD_set)); data.sD_set=[set1 set2]; set(gcf,'UserData',data); set(data.sD_set_h,'Value',1); set_sD_stats; sel_sD; data=get(gcf,'UserData'); data.undo.sData=undo; data.undo.index=index; if ~LOG data.LOG{length(data.LOG)+1}='% Remove selected vectors'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''remove_vects'',''',... tmp_str,''');'); end set(gcf,'UserData',data); return; end end tmp=sData.data(data.selected_vects,:); if ~LOG answer=questdlg('Do you want to save removed values to workspace?'); else if ~strcmp(tmp_str,'_foo') answer='Yes'; else answer='No'; end end old=gcf; if strcmp(answer,'Yes') if ~LOG answer=inputdlg('Give the name of the output -variable.'); else answer={tmp_str}; end if isvalid_var_name(answer) assignin('base',answer{1},tmp); disp(sprintf('Removed values are set to workspace as''%s''.',answer{1})); tmp_str=answer{1}; end end set(0,'CurrentFigure',old); sData.data(data.selected_vects,:)=[]; sData.labels(data.selected_vects,:)=[]; sData.MODIFIED=1; data.sData=sData; data.selected=1:length(sData.data(:,1)); data.undo.sData=undo; if ~LOG data.LOG{length(data.LOG)}='% Remove selected vectors'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''remove_vects'',''',... tmp_str,''');'); end set(gcf,'UserData',data); draw_vectors(ones(1,length(data.selected)),data.vector_h); write_sD_stats; select_all('foo'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: eval1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function eval1(varargin); if nargin == 1 answer=varargin LOG=1; else LOG=0; end pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); if isempty(pre_h) errordlg('''Preprocess''-figure does not exist. Terminating program...'); pro_tools('close'); return; end undo=getfield(get(pre_h,'UserData'),'sData'); if ~LOG prompt={'Enter the expression to be evaluated.',... 'Enter the inverse normalization method (optional).'}; title='Single component eval.'; answer= inputdlg(prompt,title,1); end if ~isempty(answer) tmp=[]; if ~isempty(answer{1}) [tmp,method]=build_expr(answer{1},'single'); if ~isstr(tmp) sData=getfield(get(gcf,'UserData'),'sData'); tmp='Done.'; %if ~isempty(answer{2}) % sN=som_norm_struct('eval',{method,answer{2}}); %else % sN=som_norm_struct('eval',{method}); %end %sN=som_set(sN,'status','done'); params={answer{1};answer{2}}; ind=getfield(get_indices,{1}); x.type=''; x.method='eval'; x.params={answer{1};answer{2}}; x.status=''; sData.comp_norm{ind}=x; data=get(gcf,'UserData'); data.undo.sData=undo; data.sData=sData; if ~LOG data.LOG{length(data.LOG)+1}='% Eval (1-comp)'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess eval1 ',... sprintf('{''%s'' ''%s''};',answer{1},answer{2})); end set(pre_h,'UserData',data); end end set(getfield(get(pre_h,'UserData'),'results_h'),'String',tmp); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: eval2 function eval2(varargin) if nargin == 1 answer=varargin{1}; LOG=1; else LOG=0; end undo=getfield(get(gcf,'UserData'),'sData'); pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); if isempty(pre_h) errordlg('''Preprocess''-figure does not exist. Terminating program.'); pro_tools('close'); return; end if ~LOG prompt='Enter the expression to be evaluated.'; title ='Eval'; answer=inputdlg(prompt,title,1); end if ~isempty(answer) & ~isempty(answer{1}) str=answer{1}; [answer,foo]=build_expr(answer{1},'multiple'); if ~isstr(answer) answer='Done.'; data=get(gcf,'UserData'); data.undo.sData=undo; if ~LOG data.LOG{length(data.LOG)+1}='% Eval'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''eval2'',',... sprintf('{''%s''});',str)); end set(gcf,'UserData',data); end end set(getfield(get(pre_h,'UserData'),'results_h'),'String',answer); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: zero2one_scale %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function zero2one_scale(varargin) if nargin == 1 LOG=1; else LOG=0; end data=get(gcf,'UserData'); sData=data.sData; undo=sData; INDEX=sData.INDEX; sData=rmfield(sData,[{'INDEX'};{'MODIFIED'}]); if isempty(get(data.comp_names_h,'Value')) errordlg('There must be components chosen for scaling.'); return; end sData=som_normalize(sData,'range',get_indices); sData.MODIFIED=1; sData.INDEX=INDEX; data.sData=sData; data.undo.sData=undo; if ~LOG data.LOG{length(data.LOG)+1}='% Scale [0,1]'; data.LOG{length(data.LOG)+1}='preprocess(''zscale'', ''foo'');'; end set(gcf,'UserData',data); vects=zeros(1,length(sData.data(:,1))); vects(data.selected_vects)=1; cplot_mimema; plot_hist; vect_means(sData,data.vect_mean_h,data.selected_vects); draw_vectors(vects,data.vector_h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: var_scale %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function var_scale(varargin) if nargin == 1 LOG=1; else LOG=0; end data=get(gcf,'UserData'); sData=data.sData; undo=sData; INDEX=sData.INDEX; sData=rmfield(sData,[{'INDEX'};{'MODIFIED'}]); if isempty(get(data.comp_names_h,'Value')) errordlg('There must be components chosen for scaling.'); return; end sData=som_normalize(sData,'var',get_indices); sData.INDEX=INDEX; sData.MODIFIED=1; data.sData=sData; data.undo.sData=undo; if ~LOG data.LOG{length(data.LOG)+1}='% Scale var=1'; data.LOG{length(data.LOG)+1}='preprocess(''vscale'', ''foo'');'; end set(gcf,'UserData',data); vects=zeros(1,length(sData.data(:,1))); vects(data.selected_vects)=1; cplot_mimema; plot_hist; vect_means(sData,data.vect_mean_h,data.selected_vects); draw_vectors(vects,data.vector_h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: hist_eq %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hist_eq(varargin) if nargin == 1 LOG=1; else LOG=0; end data=get(gcf,'UserData'); sData=data.sData; undo=sData; INDEX=sData.INDEX; sData=rmfield(sData,[{'INDEX'},{'MODIFIED'}]); if isempty(get(data.comp_names_h,'Value')) errordlg('There must be components chosen for ''Histogram eq''.'); return; end sData=som_normalize(sData,'histD',get_indices); sData.INDEX=INDEX; sData.MODIFIED=1; data.sData=sData; data.undo.sData=undo; if ~LOG data.LOG{length(data.LOG)+1}='% Histogram eq'; data.LOG{length(data.LOG)+1}='preprocess(''histeq'', ''foo'');'; end set(gcf,'UserData',data); vects=zeros(1,length(sData.data(:,1))); vects(data.selected_vects)=1; cplot_mimema; plot_hist; vect_means(sData,data.vect_mean_h,data.selected_vects); draw_vectors(vects,data.vector_h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: hist_eq2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hist_eq2(varargin) if nargin == 1 LOG=1; else LOG=0; end data=get(gcf,'UserData'); sData=data.sData; undo=sData; INDEX=sData.INDEX; sData=rmfield(sData,[{'INDEX'};{'MODIFIED'}]); if isempty(get(data.comp_names_h,'Value')) errordlg('There must be components chosen for ''Histogram eq2''.'); return; end inds=get_indices; %%%[sData,ok]=som_normalize(sData,inds,'histC'); sData=som_normalize(sData,'histC',inds); sData.INDEX=INDEX; sData.MODIFIED=1; data.sData=sData; data.undo.sData=undo; if ~LOG data.LOG{length(data.LOG)+1}='% Histogram eq2'; data.LOG{length(data.LOG)+1}='preprocess(''histeq2'', ''foo'');'; end set(gcf,'UserData',data); vects=zeros(1,length(sData.data(:,1))); vects(data.selected_vects)=1; cplot_mimema; plot_hist; vect_means(sData,data.vect_mean_h,data.selected_vects); draw_vectors(vects,data.vector_h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: logarithm %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function logarithm(varargin) if nargin == 1 LOG=1; else LOG=0; end data=get(gcf,'UserData'); sData=data.sData; undo=sData; INDEX=sData.INDEX; sData=rmfield(sData,[{'INDEX'},{'MODIFIED'}]); if isempty(get(data.comp_names_h,'Value')) errordlg('There must be components chosen for ''Log''.'); return; end Data=som_normalize(sData,'log',get_indices); sData.INDEX=INDEX; sData.MODIFIED=1; data.sData=sData; data.undo.sData=undo; if ~LOG data.LOG{length(data.LOG)+1}='% Log'; data.LOG{length(data.LOG)+1}='preprocess(''log'', ''foo'');'; end set(gcf,'UserData',data); vects=zeros(1,length(sData.data(:,1))); vects(data.selected_vects)=1; cplot_mimema; plot_hist; vect_means(sData,data.vect_mean_h,data.selected_vects); draw_vectors(vects,data.vector_h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [answer,method]=build_expr(string,evaltype) pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); method=[]; if isempty(pre_h) close_preprocess; errordlg('''Preprocess'' -figure does not exist. Terminating program...'); return; end if isempty(string) str = '[]'; return; end tmp=[]; [name,assign,skip]=check_assign(string,evaltype); if ~strcmp(assign,'NOTASSIGN') & ~strcmp(assign,'error') string=string(skip:length(string)); end if ~strcmp(assign,'error') if isempty(string) answer='Illegal expression.'; return; end [str,skip]=check_token(string,evaltype); method=string; while ~strcmp(str,'error') & ~strcmp(tmp,'error') & skip < length(string) if ~strcmp(tmp,')') str=cat(2,str,tmp); end [tmp,skip2]=check_token(string(skip+1:length(string)),evaltype); skip=skip+skip2; end if ~strcmp(tmp,')') & ~strcmp(tmp,'error') str=cat(2,str,tmp); elseif strcmp(tmp,'error') str='error'; end end if ~strcmp(assign,'error') & ~strcmp(str,'error'); answer=evalin('caller',str,'lasterr'); else answer='??? Illegal expression.'; end data=get(pre_h,'UserData'); sData=data.sData; if strcmp(assign,'NOTASSIGN') & strcmp(evaltype,'single') & ~isstr(answer) if isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value')) errordlg('There are not components chosen.'); answer='??? Illegal expression.'; return; end index=getfield(get_indices,{1}); if strcmp(assign,'NOTASSIGN') if length(sData.data(:,index)) ~=length(answer) & ~isscalar(answer) answer='??? Illegal assignment.'; else sData.data(:,index)=answer; sData.MODIFIED=1; data.sData=sData; set(pre_h,'UserData',data); end else if length(sData.data(str2num(assign),index)) ~=length(answer) & ~isscalar(answer) answer='??? Illegal assignment.'; else sData.data(str2num(assign),index)=answer; sData.MODIFIED=1; data.sData=sData; set(pre_h,'UserData',data); end end elseif ~strcmp(assign,'error') & ~isstr(answer) & ~strcmp(assign,'NOTASSIGN') switch name case 'x' if isempty(get(data.comp_names_h,'Value')) return; end index = getfield(get_indices,{1}); if isempty(assign) if length(sData.data(:,index)) ~= length(answer) & ~isscalar(answer) answer='??? Illegal assignment.'; else sData.data(:,index)=answer; sData.MODIFIED=1; data.sData=sData; if strcmp(evaltype,'multiple') data.sData.comp_norm(index)={[]}; end set(pre_h,'UserData',data); end else args=create_args(assign,'x'); if length(args) == 1 len=max(str2num(args{1})); if ~isscalar(len) answer='??? Illegal assignment.'; return; elseif len > length(sData.data(:,1)) | min(str2num(args{1})) < 1 answer='??? Illegal assignment.'; return; elseif ~all(size(sData.data(str2num(args{1}),index))) == size(answer) & ~isscalar(answer) answer='??? Illegal assignment.'; return; else sData.data(str2num(args{1}),index)=answer; sData.MODIFIED=1; data.sData=sData; if strcmp(evaltype,'multiple') data.sData.comp_norm(index)={[]}; end set(pre_h,'UserData',data); end else len=max(str2num(args{1})); dim=max(str2num(args{2})); asize=size(answer); msize=size(sData.data); if ~isscalar(len) | ~isscalar(dim) answer='??? Illegal assignment.'; return; elseif len > length(sData.data(:,1)) | len < 1 answer='??? Illegal assignment.'; return; elseif dim > 1 | dim > msize(2) | min(str2num(args{2})) < 1 answer='??? Illegal assignment.'; return; end len=length(str2num(args{1})); dim=length(str2num(args{1})); if ~all([len dim] == asize) & ~isscalar(answer) answer='??? Illegal assignment.'; return; else tmp=sData.data(:,index); tmp([str2num(args{1})],[str2num(args{2})])=answer; sData.data(:,index)=tmp; sData.MODIFIED=1; data.sData=sData; if strcmp(evaltype,'multiple') data.sData.comp_norm(index)={[]}; end set(pre_h,'UserData',data); end end end case 'xs' if isempty(get(data.comp_names_h,'Value')) return; end indices=get_indices; if isempty(assign) if ~all(size(answer) == size(sData.data(:,indices))) & ~isscalar(answer) answer='??? Illegal assignment.'; else sData.data(:,indices) = answer; sData.MODIFIED=1; data.sData=sData; data.sData.comp_norm(indices)={[]}; set(pre_h,'UserData',data); end else args=create_args(assign,'xs'); if length(args) == 1 len=max(str2num(args{1})); if ~isscalar(len) answer='??? Illegal assignment.'; return; elseif len > length(sData.data(:,1)) | min(str2num(args{1})) < 1 answer='??? Illegal assignment.'; return; end if ~all(size(answer) == size(sData.data(str2num(args{1})))) &... ~isscalar(answer) answer='??? Illegal assignment.'; return; else tmp=sData.data(:,indices); tmp(str2num(args{1}))=answer; sData.data(:,indices)=tmp; sData.MODIFIED=1; sData.comp_norm{indices}={[]}; data.sData=sData; set(pre_h,'UserData',data); end else len=max(str2num(args{1})); dim=max(str2num(args{2})); asize=size(answer); msize=size(sData.data(:,indices)); if ~isscalar(len) | ~isscalar(dim) answer='??? Illegal assignment.'; return; elseif len > msize(1) | min(str2num(args{1})) < 1 answer='??? Illegal assignment.'; return; elseif dim > msize(2) | min(str2num(args{2})) < 1 answer='??? Illegal assignment.'; return; end len=length(str2num(args{1})); dim=length(str2num(args{2})); if ~all([len dim] == asize) & ~isscalar(answer) answer='??? Illegal assignment'; return; else tmp=sData.data(:,indices); tmp([str2num(args{1})],[str2num(args{2})])=answer; sData.MODIFIED=1; sData.data(:,indices)=tmp; data.sData=sData; data.sData.comp_norm(indices)={[]}; set(pre_h,'UserData',data); end end end case 'D' if isempty(assign) if ~all(size(answer) == size(sData.data)) & ~isscalar(answer) answer='??? Illegal assignment.'; else if isscalar(answer) sData.data(:,:)=answer; else sData.data=answer; end sData.MODIFIED=1; data.sData=sData; data.sData.comp_norm(1:length(sData.data(1,:)))={[]}; set(pre_h,'UserData',data); end else args=create_args(assign,'D'); if length(args) == 1 len=max(str2num(args{1})); if ~isscalar(len) answer='??? Illegal assignment.'; return; elseif len > length(sData.data(:,1)) | min(str2num(args{1})) < 1 answer='??? Illegal assignment.'; return; end if ~all(size(answer) == size(sData.data(str2num(args{1})))) &... ~isscalar(answer) answer='??? Illegal assignment.'; else sData.data(str2num(args{1}))=answer; sData.MODIFIED=1; data.sData=sData; [i,j]=ind2sub(size(sData.data),str2num(args{1})); data.sData.comp_norm(j)={[]}; set(pre_h,'UserData',data); end else len=max(str2num(args{1})); dim=max(str2num(args{2})); asize=size(answer); msize=size(sData.data); if ~isscalar(len) | ~isscalar(dim) answer='??? Illegal assignment.'; return; elseif len > msize(1) | min(str2num(args{1})) < 1 answer='??? Illegal assignment.'; return; elseif dim > msize(2) | min(str2num(args{2})) < 1 answer= '??? Illegal assignment.'; return; end len = length(str2num(args{1})); dim = length(str2num(args{2})); if ~all([len dim] == asize) & ~isscalar(answer) answer='??? Illegal assignment.'; return; else sData.data([str2num(args{1})],[str2num(args{2})])=answer; sData.MODIFIED=1; data.sData=sData; data.sData.comp_norm(str2num(args{2}))={[]}; set(pre_h,'UserData',data); end end end end end if sData.MODIFIED selected=getfield(get(pre_h,'UserData'),'selected_vects'); vector_h=getfield(get(pre_h,'UserData'),'vector_h'); vect_mean_h=getfield(get(pre_h,'UserData'),'vect_mean_h'); vects=zeros(length(sData.data(:,1))); vects(selected)=1; draw_vectors(vects,vector_h); vect_means(sData,vect_mean_h,selected); pro_tools('plot_hist'); pro_tools('c_stat'); cplot_mimema; end %%% Subfunction: check_assign %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [name,string,skip]=check_assign(string,evaltype) reswords=[{'D'};{'x'};{'xs'}]; flag=0; pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); if isempty(pre_h) man_h=findobj(get(0,'Children'),'Tag','Management'); clip_h=findobj(get(0,'Children'),'Tag','Clipping'); errordlg('''Preprocess'' -window does not exist. Terminating program.'); if ~isempty(man_h) close man_h; end if ~isempty(clip_h) close clip_h; end return; end EMPTY=isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value')); [name,s]=give_token(string,evaltype); skip=length(s); if strcmp(evaltype,'single') & ~strcmp(name,'x') string='NOTASSIGN'; return; end if strcmp(name,'other') & ~strcmp(s,'x') string = 'error'; return; end if strcmp(name,[{'x'};{'xs'}]) comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h'); if isempty(get(comp_names_h,'Value')) errordlg('There are not components chosen.'); string='error'; return; end end if skip == length(string) | ~strcmp(name,reswords) string = 'NOTASSIGN'; return; end if (strcmp(name,'x') | strcmp(name,'xs')) & EMPTY errordlg('There are not components chosen.'); string = 'error'; return; end [t,s]=give_token(string(length(name)+1),evaltype); if strcmp(t,'(') flag=1; end [foo,skip]=check_token(string,evaltype); if length(name) ~= skip-1 skip=skip-1; tmp=string(length(name)+1:skip); else tmp = []; end if flag & tmp(length(tmp)) ~= ')' tmp(length(tmp)+1)=')'; end if skip==length(string) return; end skip=skip+1; if length(string) ~= skip [t,s]=give_token(string(skip+1:length(string)),evaltype); else string='NOTASSIGN'; return; end if ~strcmp(t,'=') string = 'NOTASSIGN'; return; end string=tmp; skip = skip+2; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: isscalar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bool = isscalar(x) m= size(x); bool = m(1) == 1 & m(2) == 1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: create_args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function args=create_args(string,type) arg2=''; i=2; j=1; pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); msize=size(getfield(getfield(get(pre_h,'UserData'),'sData'),'data')); if string(i) == ':' arg1=num2str(cat(2,'1:',num2str(msize(1)))); i=i+1; j=j+length(arg1); end while string(i) ~=',' & string(i) ~=')' arg1(j)=string(i); i=i+1; j=j+1; end if string(i) ==',' j=1; i=i+1; if string(i)==':' switch type case 'x' arg2='1'; case 'cs' arg2=num2str(get_indices); case 'D' arg2=num2str(cat(2,'1:',num2str(msize(2)))); end i=i+1; j=j+length(arg2); end while string(i) ~= ')' arg2(j)=string(i); j=j+1; i=i+1; end end args{1}=arg1; if ~isempty(arg2) args{2} = arg2; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [str,skip] = check_token(string,evaltype) pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); tmp_string=string; [t,s]=give_token(tmp_string,evaltype); skip=length(s); if strcmp(t,'c') if isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value')) errordlg('There are no components chosen.'); str='error'; return; end index=getfield(get_indices,{1}); str=cat(2,'[',num2str(index),']'); if skip == length(tmp_string) return; end tmp_string=tmp_string(skip+1:length(tmp_string)); [t,s] = give_token(tmp_string,evaltype); if ~strcmp(t,'(') return; end [args,skip2] = get_args(tmp_string(length(s)+1:length(tmp_string)),'c',... evaltype); skip=skip+skip2+2; if strcmp(args,'error') str = 'error' return; elseif ~strcmp(args,'all') str=cat(2,'getfield(',str,',',args,')'); else str=cat(2,'getfield(',str,',{[1]})'); end elseif strcmp(t,'cs') if isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value')) errordlg('There are no components chosen.'); str='error'; return; end str =cat(2,'[',num2str(get_indices),']'); if length(s) == length(string) return; end tmp_string=tmp_string(1+length(s):length(string)); [t,s]=give_token(tmp_string,evaltype); if ~strcmp(t,'(') return; else [args,skip2]=get_args(tmp_string(1+length(s):length(tmp_string)),'cs',... evaltype); skip=2+skip+skip2; if strcmp(args,'error') str='error'; return; elseif ~strcmp(args,'all') str = cat(2,'getfield(',str,',',args,')'); else tmp_str=str; str=cat(2,'[getfield(',str,',','{1})'); for i=2:length(get_indices) str=cat(2,str,';getfield(',tmp_str,',',sprintf('{%d})',i)); end str=cat(2,str,']'); end end elseif strcmp(t,'dim') ind1=getfield(size(getfield(getfield(get(pre_h,'UserData'),'sData'),'data')),{2}); str=cat(2,'[',num2str(ind1),']'); if length(s)==length(string) return; end tmp_string=string(1+length(s):length(string)); [t,s]=give_token(tmp_string,evaltype); if ~strcmp(t,'(') return; end skip=1+skip+length(s); [args,skip2]=get_args(tmp_string(1+length(s):length(tmp_string)),'dim',... evaltype); if strcmp(args,'error') str = 'error'; return; else skip=skip+skip2; if ~strcmp(args,'all') str=cat(2,'getfield(',str,',',args,')'); end end elseif strcmp(t,'dlen') ind1=getfield(size(getfield(getfield(get(pre_h,'UserData'),'sData'),'data')),{1}); str=cat(2,'[',num2str(ind1),']'); if length(s)==length(string) return; end tmp_string=string(1+length(s):length(string)); [t,s]=give_token(tmp_string,evaltype); if ~strcmp(t,'(') return; end skip=skip+length(s); [args,skip2]=get_args(tmp_string(1+length(s):length(tmp_string)),'dlen',... evaltype); if strcmp(args,'error') str='error'; return; else skip=1+skip+skip2; if ~strcmp(args,'all') str=cat(2,'getfield(',str,',',args,')'); end end elseif strcmp(t,'x') if isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value')) errordlg('There are not components chosen.'); str='error'; return; end len=getfield(size(getfield(getfield(get(pre_h,'UserData'),... 'sData'),'data')),{1}); index=num2str(getfield(get_indices,{1})); h_str='findobj(get(0,''Children''),''Tag'',''Preprocess'')'; get_str=cat(2,'getfield(get(',h_str,',''UserData''),''sData'')'); get_str=cat(2,'getfield(',get_str,',''data'')'); str=cat(2,'getfield(',get_str,',{[1:',num2str(len),'],',index,'})'); if length(s) == length(string) return; end tmp_string=string(1+length(s):length(string)); [t,s]=give_token(tmp_string,evaltype); if ~strcmp(t,'('); return; end skip=skip+length(s); [args,skip2]=get_args(tmp_string(1+length(s):length(tmp_string)),'x',... evaltype); if strcmp(args,'error') str = 'error'; return; else skip=1+skip+skip2; if ~strcmp(args,'all') str=cat(2,'getfield(',str,',',args,')'); end end elseif strcmp(t,'xs') if isempty(get(getfield(get(pre_h,'UserData'),'comp_names_h'),'Value')) errordlg('There are not components chosen.'); str='error'; return; end len=getfield(size(getfield(getfield(get(pre_h,'UserData'),... 'sData'),'data')),{1}); index=get_indices; index=cat(2,'[',num2str(index),']'); h_str='findobj(get(0,''Children''),''Tag'',''Preprocess'')'; get_str=cat(2,'getfield(get(',h_str,',''UserData''),''sData'')'); get_str=cat(2,'getfield(',get_str,',''data'')'); str=cat(2,'getfield(',get_str,',{[1:',num2str(len),'],',index,'})'); if length(s) == length(string) return; end tmp_string=string(1+length(s):length(string)); [t,s]=give_token(tmp_string,evaltype); if ~strcmp(t,'(') return; end skip=1+skip+length(s); [args,skip2]=get_args(tmp_string(1+length(s):length(tmp_string)),'xs',... evaltype); if strcmp(args,'error') str = 'error'; return; elseif ~strcmp(args,'all') str=cat(2,'getfield(',str,',',args,')'); skip=skip+skip2; else skip=skip+skip2; [dlen,dim]=size(eval(str)); tmp_str=str; str=cat(2,'[','getfield(',tmp_str,sprintf(',{1:%d,1})',dlen)); for i=2:dim tmp=sprintf(',{1:%d,%d})',dlen,dim); str=cat(2,str,';','getfield(',tmp_str,tmp); end str=cat(2,str,']'); end elseif strcmp(t,'D') get_h='findobj(get(0,''Children''),''Tag'',''Preprocess'')'; str=cat(2,'getfield(getfield(get(',get_h,',''UserData''),''sData''),''data'')'); if length(s) >= length(tmp_string) return; end tmp_string=tmp_string(1+length(s):length(tmp_string)); [t,s]=give_token(tmp_string,evaltype); if ~strcmp(t,'(') return; else tmp_string=tmp_string(1+length(s):length(tmp_string)); skip = skip+length(s); [args, skip2]=get_args(tmp_string,'D',evaltype); if strcmp(args,'error') str='error'; return; elseif ~strcmp(args,'all') str=cat(2,'getfield(',str,',',args,')'); skip=1+skip+skip2; else skip=1+skip+skip2; [dlen,dim]=size(eval(str)); tmp_str=str; str=cat(2,'[getfield(',str,sprintf(',{1:%d,1})',dlen)); for i=2:dim tmp=sprintf(',{1:%d,%d}',dlen,i); str=cat(2,str,';getfield(',tmp_str,tmp,')'); end str=cat(2,str,']'); end end else if strcmp(t,'(') str = t; str2=''; tmp_string=tmp_string(1+length(s):length(tmp_string)); while ~strcmp(str2,')') & ~isempty(tmp_string) [str2,skip2]=check_token(tmp_string,evaltype); if strcmp(str2,'error') str='error'; return; end skip=skip+skip2; tmp_string=tmp_string(skip2+1:length(tmp_string)); str=cat(2,str,str2); end if ~strcmp(str2,')') str = 'error'; end else str = s; end end %%% Subfunction: get_args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [str,skip] = get_args(string,flag,evaltype) res_words=[{'D'};{'c'};{'cs'};{'dim'};{'dlen'};{'x'};{'xs'}]; NOTALL=1; if isempty(string) str='error' skip=[]; return; end [t,s] = give_token(string,evaltype); skip=length(s); if any(strcmp(t,res_words)); [str,skip2] = check_token(string,evaltype); string=string(1+length(s):length(string)); str=cat(2,'{[',str); [t,s]=give_token(string,evaltype); elseif t==')' | t==',' str = 'error'; return; elseif strcmp(t,':'); if length(s) == length(string) str='error'; return; end [t,s]=give_token(string(1+length(s):length(string)),evaltype); if t == ')' str = 'all'; return; end switch flag case {'c','cs','dim','dlen'} str= '{[1'; otherwise str=cat(2,'{[',get_all('vect')); end NOTALL=0; string=string(1+length(s):length(string)); [t,s]=give_token(string,evaltype); skip=skip+1; else str = cat(2,'{[',s); end str2 =[]; if ~strcmp(t,',') & ~strcmp(t,')') skip=skip-length(s); end while ~strcmp(t,',') & ~strcmp(t,')') & NOTALL; str=cat(2,str,str2); [t,s] = give_token(string,evaltype); if length(s) == length(string) str = 'error'; return; end string=string(1+length(s):length(string)); skip=skip+length(s); [t,s]=give_token(string,evaltype); if length(s) == length(string) & ~strcmp(t,')') str = 'error'; return; end [str2,foo]=check_token(string,evaltype); end if NOTALL & ~strcmp(t,')') skip=skip+1; end if strcmp(t,')') str=cat(2,str,']}'); return end str=cat(2,str,']',',','['); str2 = []; [t,s] = give_token(string,evaltype); if strcmp(t,')') str = 'error' return; end NOTALL=1; string=string(1+length(s):length(string)); [t,s]=give_token(string,evaltype); if strcmp(t,':'); switch flag case {'c','dim','dlen','x'} str=cat(2,str,'1'); case 'D' str=cat(2,str,get_all('comp')); case {'cs','xs'} str=cat(2,str,'1:',num2str(length(get_indices))); end NOTALL=0; if length(s) == length(string) str='error'; return; end string=string(1+length(s):length(string)); [t,s]=give_token(string,evaltype); end if ~strcmp(t,')') & NOTALL skip=skip-1; end while ~strcmp(t,')') & NOTALL str=cat(2,str,str2); skip=skip+length(s); if length(s) == length(string) & ~strcmp(t,')') str='error'; return; end [str2,foo]=check_token(string,evaltype); string=string(1+length(s):length(string)); [t,s]=give_token(string,evaltype); end if ~strcmp(t,')') str='error'; return; end str=cat(2,str,str2,']}'); skip=skip+length(s); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: get_all %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str=get_all(vect_or_comp) pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); switch vect_or_comp case 'vect' dim=getfield(size(getfield(getfield(get(pre_h,'UserData'),... 'sData'),'data')),{1}); str=cat(2,'1:',num2str(dim)); case 'comp' dim=getfield(size(getfield(getfield(get(pre_h,'UserData'),... 'sData'),'data')),{2}); str=cat(2,'1:',num2str(dim)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [token,str]=give_token(string,evaltype) n=length(string); i=1; char=string(i); switch analyze_char(string(i)); case 'num' token='num'; while i <= n & strcmp('num',analyze_char(string(i))) str(i)=string(i); i=i+1; end case 'other' switch string(i) case ':' token = ':'; case ',' token = ','; case '(' token = '('; case ')' token = ')'; case '=' token = '='; otherwise token='other'; end str=string(i); case 'alpha' while i <= n & strcmp('alpha',analyze_char(string(i))) str(i)=string(i); i=i+1; end token = find_res_word(str,evaltype); end %%% Subfunction: analyze_char %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function type=analyze_char(char) if ((char-0) >= ('0'-0) & (char-0) <= ('9'-0)) type='num'; elseif ((char-0) >= ('a'-0) & (char-0) <= ('z'-0)) ... | ((char-0) >= ('A'-0) & (char-0) <= ('Z'-0)) type='alpha'; else type='other'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Subfunction: find_res_word %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function token = find_res_word(string,evaltype) reswords=[{'D'};{'c'};{'cs'};{'dim'};{'dlen'};{'x'};{'xs'};{'other'}]; for i=1:length(reswords); token=reswords{i}; if strcmp(string,reswords{i}) if strcmp(evaltype,'single') & ~strcmp(string,'x') token = 'other'; end return; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function close_func(varargin) switch varargin{1} case 'close_c' str='% Closing the ''Clipping'' -window...'; clip_h=findobj(get(0,'Children'),'Tag','Clipping'); close(clip_h); case 'close_sD' str='% Closing the ''Data Set Management'' -window...'; sD_h=findobj(get(0,'Children'),'Tag','Management'); close(sD_h); case 'close_w' str='% Closing the ''Windowed'' -window...'; win_h=findobj(get(0,'Children'),'Tag','Window'); close(win_h); case 'close_s' str='% Closing the ''Select'' -window...'; sel_h=findobj(get(0,'Children'),'Tag','Select'); close(sel_h); case 'close_d' str='% Closing the ''Delay'' -window...'; del_h=findobj(get(0,'Children'),'Tag','Delay'); close(del_h); end if nargin ~= 2 pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); preh_udata=get(pre_h,'UserData'); str2=cat(2,'preprocess(''',varargin{1},''',''foo'');'); preh_udata.LOG{length(preh_udata.LOG)+1}=str; preh_udata.LOG{length(preh_udata.LOG)+1}=str2; set(pre_h,'UserData',preh_udata); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function log_file answer=inputdlg('Give the name of the outputfile:','LOG function',1,... {'log_function'}); if isempty(answer) return; end tmp=clock; str =cat(2,'% Created: ',... date,... ' ',sprintf('%d:%d\n%\n\n',tmp(4),tmp(5))); pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); LOG=getfield(get(pre_h,'UserData'),'LOG'); file=cat(2,pwd,'/',answer{1},'.m'); fid =fopen(file,'w'); arg=LOG{2}(12:length(LOG{2})-2); fprintf(fid,'%s\n \n',cat(2,'function ',answer{1},'(',arg,')')); fprintf(fid,'%s\n',str); for i=1:length(LOG) fprintf(fid,'%s\n',LOG{i}); end fclose(fid); disp(sprintf('LOG-file ''%s'' is done.',file)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function get_selected_inds(varargin) if nargin == 1 LOG=1; answer = {varargin{1}}; else LOG=0; end selected=getfield(get(gcf,'UserData'),'selected_vects'); if ~LOG answer=inputdlg('Give the name of the output variable:',... '',1,{'indices'}); end if isempty(answer) | isempty(answer{1}) return; else assignin('base',answer{1},selected); disp(cat(2,'Indices of the selected vectors are set to the workspace ',... sprintf(' as ''%s''.',answer{1}))); if ~LOG data=get(gcf,'UserData'); data.LOG{length(data.LOG)+1}=... '% Saving indices of the selected vectors to the workspace.'; data.LOG{length(data.LOG)+1}=cat(2,'preprocess(''get_inds'',',... '''',answer{1},''');'); set(gcf,'UserData',data); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function no_of_selected(varargin) if nargin == 1 pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); set(0,'CurrentFigure',pre_h); LOG = 1; else LOG = 0; end results_h=getfield(get(gcf,'UserData'),'results_h'); no=length(getfield(get(gcf,'UserData'),'selected_vects')); str={sprintf('Number of selected vectors: %d\n', no)}; set(results_h,'String',str,'HorizontalAlignment','left'); if ~LOG data=get(gcf,'UserData'); data.LOG{length(data.LOG)+1}='% Number of selected vectors'; data.LOG{length(data.LOG)+1}='preprocess(''no_of_sel'',''foo'');'; set(gcf,'UserData',data); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_all_comps(varargin) if nargin == 1 pre_h=findobj(get(0,'Children'),'Tag','Preprocess'); set(0,'CurrentFigure',pre_h); LOG=1; else LOG=0; end comp_names_h=getfield(get(gcf,'UserData'),'comp_names_h'); set(comp_names_h,'Value',[1:length(get(comp_names_h,'String'))]); sel_comp; if ~LOG data=get(gcf,'UserData'); data.LOG{length(data.LOG)+1}='% Select all components'; data.LOG{length(data.LOG)+1}='preprocess(''sel_all_comps'',''foo'');'; set(gcf,'UserData',data); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function code=write_log_code(indices,arg1,arg2,arg3,arg4,arg5,arg6); str=textwrap({num2str(indices)},500); code{1}=sprintf('inds=[];'); for i=1:length(str); code{i+1}=sprintf(' inds=cat(2,inds,[%s]);',str{i}); end str=cat(2,'preprocess(''''clip_data'''',''''',arg1,' ',num2str(arg2),' ',... num2str(arg3),' ',num2str(arg4),... ' ',num2str(arg5),' ',num2str(arg6),' '); code{length(code)+1}=cat(2,'eval(cat(2,',... '''',str,'''',... ',num2str(inds),'''''');''));'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
martinarielhartmann/mirtooloct-master
som_kmeans.m
.m
mirtooloct-master/somtoolbox/som_kmeans.m
4,244
utf_8
dca5b32dd99e19a186277df2a168dcf2
function [codes,clusters,err] = som_kmeans(method, D, k, epochs, verbose) % SOM_KMEANS K-means algorithm. % % [codes,clusters,err] = som_kmeans(method, D, k, [epochs], [verbose]) % % Input and output arguments ([]'s are optional): % method (string) k-means algorithm type: 'batch' or 'seq' % D (matrix) data matrix % (struct) data or map struct % k (scalar) number of centroids % [epochs] (scalar) number of training epochs % [verbose] (scalar) if <> 0 display additonal information % % codes (matrix) codebook vectors % clusters (vector) cluster number for each sample % err (scalar) total quantization error for the data set % % See also KMEANS_CLUSTERS, SOM_MAKE, SOM_BATCHTRAIN, SOM_SEQTRAIN. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Function has been renamed by Kimmo Raivio, because matlab65 also have % kmeans function 1.10.02 %% input arguments if isstruct(D), switch D.type, case 'som_map', data = D.codebook; case 'som_data', data = D.data; end else data = D; end [l dim] = size(data); if nargin < 4 | isempty(epochs) | isnan(epochs), epochs = 100; end if nargin < 5, verbose = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% action rand('state', sum(100*clock)); % init rand generator lr = 0.5; % learning rate for sequential k-means temp = randperm(l); centroids = data(temp(1:k),:); res = zeros(k,l); clusters = zeros(1, l); if dim==1, [codes,clusters,err] = scalar_kmeans(data,k,epochs); return; end switch method case 'seq', len = epochs * l; l_rate = linspace(lr,0,len); order = randperm(l); for iter = 1:len x = D(order(rem(iter,l)+1),:); dx = x(ones(k,1),:) - centroids; [dist nearest] = min(sum(dx.^2,2)); centroids(nearest,:) = centroids(nearest,:) + l_rate(iter)*dx(nearest,:); end [dummy clusters] = min(((ones(k, 1) * sum((data.^2)', 1))' + ... ones(l, 1) * sum((centroids.^2)',1) - ... 2.*(data*(centroids')))'); case 'batch', iter = 0; old_clusters = zeros(k, 1); while iter<epochs [dummy clusters] = min(((ones(k, 1) * sum((data.^2)', 1))' + ... ones(l, 1) * sum((centroids.^2)',1) - ... 2.*(data*(centroids')))'); for i = 1:k f = find(clusters==i); s = length(f); if s, centroids(i,:) = sum(data(f,:)) / s; end end if iter if sum(old_clusters==clusters)==0 if verbose, fprintf(1, 'Convergence in %d iterations\n', iter); end break; end end old_clusters = clusters; iter = iter + 1; end [dummy clusters] = min(((ones(k, 1) * sum((data.^2)', 1))' + ... ones(l, 1) * sum((centroids.^2)',1) - ... 2.*(data*(centroids')))'); otherwise, fprintf(2, 'Unknown method\n'); end err = 0; for i = 1:k f = find(clusters==i); s = length(f); if s, err = err + sum(sum((data(f,:)-ones(s,1)*centroids(i,:)).^2,2)); end end codes = centroids; return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [y,bm,qe] = scalar_kmeans(x,k,maxepochs) nans = ~isfinite(x); x(nans) = []; n = length(x); mi = min(x); ma = max(x) y = linspace(mi,ma,k)'; bm = ones(n,1); bmold = zeros(n,1); i = 0; while ~all(bm==bmold) & i<maxepochs, bmold = bm; [c bm] = histc(x,[-Inf; (y(2:end)+y(1:end-1))/2; Inf]); y = full(sum(sparse(bm,1:n,x,k,n),2)); zh = (c(1:end-1)==0); y(~zh) = y(~zh)./c(~zh); inds = find(zh)'; for j=inds, if j==1, y(j) = mi; else y(j) = y(j-1) + eps; end, end i=i+1; end if i==maxepochs, [c bm] = histc(x,[-Inf; (y(2:end)+y(1:end-1))/2; Inf]); end if nargout>2, qe = sum(abs(x-y(bm)))/n; end if any(nans), notnan = find(~nans); n = length(nans); y = full(sparse(notnan,1,y ,n,1)); y(nans) = NaN; bm = full(sparse(notnan,1,bm,n,1)); bm(nans) = NaN; if nargout>2, qe = full(sparse(notnan,1,qe,n,1)); qe(nans) = NaN; end end return;
github
martinarielhartmann/mirtooloct-master
sompak_rb_control.m
.m
mirtooloct-master/somtoolbox/sompak_rb_control.m
7,240
utf_8
bcfb4ce0fc8edd340c4a5b73afa57746
function varargout=sompak_rb_control(str) %SOMPAK_RB_CONTROL An auxiliary function for SOMPAK_*_GUI functions. % % This is an auxiliary function for SOMPAK_GUI, SOMPAK_INIT_GUI, % SOMPAK_SAMMON_GUI and SOMPAK_TRAIN_GUI functions. It controls the % radio buttons in the GUIs. % % See also SOMPAK_GUI, SOMPAK_INIT_GUI, SOMPAK_SAMMON_GUI, SOMPAK_TRAIN_GUI. % Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas % Copyright (c) by Juha Parhankangas % http://www.cis.hut.fi/projects/somtoolbox/ % Juha Parhankangas 050100 data=get(gcf,'UserData'); switch str case {'rand','linear'} h=cat(2,findobj(get(gcf,'Children'),'Tag','RANDOM'),... findobj(get(gcf,'Children'),'Tag','LINEAR')); set(h,'Value',0); set(gcbo,'Value',1); data.inittype=str; case {'bubble','gaussian'} h=cat(2,findobj(get(gcf,'Children'),'Tag','BUBBLE'),... findobj(get(gcf,'Children'),'Tag','GAUSSIAN')); set(h,'Value',0); set(gcbo,'Value',1); data.neigh=str; case {'hexa','rect'} h=cat(2,findobj(get(gcf,'Children'),'Tag','HEXA'),... findobj(get(gcf,'Children'),'Tag','RECT')); set(h,'Value',0); set(gcbo,'Value',1); data.topol=str; case {'out_ft'} value=get(gcbo,'Value'); switch value case 1 h=findobj(get(gcf,'Children'),'Tag','OUT_FILE'); data.out_file_type=''; set(h,'String',''); case 2 data.out_file_type='box'; case 3 data.out_file_type='pak'; end case {'input_ft'} value=get(gcbo,'Value'); switch value case 1 data.input_file_type=''; case 2 data.input_file_type='box'; case 3 data.input_file_type='pak'; end case {'map_ft'} value=get(gcbo,'Value'); switch value case 1 data.map_type=''; case 2 data.map_type='box'; case 3 data.map_type='pak'; end case {'out_file'} if isempty(data.out_file_type) data.out_file=''; h=findobj(get(gcf,'Children'),'Tag','OUT_FILE'); set(h,'String',''); else data.out_file=get(findobj(get(gcf,'Children'),'Tag','OUT_FILE'),'String'); if isempty(data.out_file) h=findobj(get(gcf,'Children'),'Tag','OUT_FILE_TYPE'); set(h,'Value',1); end end case {'out_var'} h=findobj(get(gcf,'Children'),'Tag','OUT_VAR'); if ~isempty(get(h,'String')) data.out_var=get(h,'String'); else data.out_var=[]; set(h,'String','''ans'''); end case {'xdim'} h=findobj(get(gcf,'Children'),'Tag','XDIM'); data.xdim=str2num(get(h,'String')); case {'ydim'} h=findobj(get(gcf,'Children'),'Tag','YDIM'); data.ydim=str2num(get(h,'String')); case {'radius'} h=findobj(get(gcf,'Children'),'Tag','RADIUS'); data.radius=str2num(get(h,'String')); case {'data'} h=findobj(get(gcf,'Children'),'Tag','DATA'); data.data=get(h,'String'); case {'rlen'} h=findobj(get(gcf,'Children'),'Tag','RLEN'); data.rlen=str2num(get(h,'String')); case {'alpha'} h=findobj(get(gcf,'Children'),'Tag','ALPHA'); data.alpha=str2num(get(h,'String')); case {'map'} h=findobj(get(gcf,'Children'),'Tag','MAP'); data.map=get(h,'String'); case 'init_ok' if isempty(data.xdim) | ~is_positive_integer(data.xdim) errordlg('Argument ''xdim'' must be positive integer.'); return; end if isempty(data.ydim) | ~is_positive_integer(data.ydim) errordlg('Argument ''ydim'' must be positive integer.'); return; end if isempty(data.data) errordlg('Argument ''Workspace data'' must be a string.'); return; end if isempty(data.input_file_type) sData=evalin('base',data.data); else sData=data.data; end if isempty(data.out_file) if ~isempty(data.out_file_type) errordlg('Argument ''Output file'' is not defined.'); return; end data.out_file=[]; end answer=sompak_init(sData,... data.input_file_type,... data.inittype,... data.out_file,... data.out_file_type,... data.xdim,... data.ydim,... data.topol,... data.neigh); if any(strcmp(data.out_var,{'ans','''ans'''})) | isstr(answer) varargout{1}=answer; else assignin('base',data.out_var,answer); disp(sprintf('Map is set to workspace as ''%s''.',data.out_var)); end close(findobj(get(0,'Children'),'Tag','InitGUI')); return; case 'train_ok' if isempty(data.rlen) | ~is_positive_integer(data.rlen) errordlg('Argument ''Running Length'' must be positive integer.'); return; end if isempty(data.alpha) | data.alpha <= 0 errordlg('Argument ''Initial Alpha Value'' must be a positive float.'); return; end if isempty(data.radius) | data.radius <= 0 errordlg('Argument ''Neighborhood Radius'' must be a positive float.'); return; end if isempty(data.data) errordlg('Argument ''Teaching Data'' must be a string.'); return; end if isempty(data.input_file_type) sData=evalin('base',data.data); else sData=data.data; end if isempty(data.out_file); data.outfile = []; end if isempty(data.map) errordlg('Argument ''Workspace Map'' must be a string.'); return; end if isempty(data.map_type) sMap=evalin('base',data.map); else sMap=data.map; end answer=sompak_train(sMap,... data.map_type,... data.out_file,... data.out_file_type,... data.data,... data.input_file_type,... data.rlen,... data.alpha,... data.radius); if any(strcmp(data.out_var,{'''ans''','ans'})) | isstr(answer) varargout{1}=answer; else assignin('base',data.out_var,answer); disp(sprintf('Map is set to workspace as ''%s''.',data.out_var)); end close(findobj(get(0,'Children'),'Tag','TrainGUI')); return; case 'sammon_ok' if isempty(data.map) errordlg('Argument ''Workspace Map'' must be a string.'); return; end if isempty(data.map_type) sMap=evalin('base',data.map); else sMap=data.map; end if isempty(data.out_file); data.outfile = []; end answer=sompak_sammon(sMap,... data.map_type,... data.out_file,... data.out_file_type,... data.rlen); if strcmp(data.out_var,'''ans''')|strcmp(data.out_var,'ans')|isstr(answer) varargout{1}=answer; else assignin('base',data.out_var,answer); disp(sprintf('Codebook is set to workspace as ''%s''.',data.out_var)); end close(findobj(get(0,'Children'),'Tag','SammonGUI')); return; end set(gcf,'UserData',data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bool = is_positive_integer(x) bool = ~isempty(x) & isreal(x) & all(size(x) == 1) & x > 0; if ~isempty(bool) if bool & x~=round(x) bool = 0; end else bool = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
martinarielhartmann/mirtooloct-master
lvq1.m
.m
mirtooloct-master/somtoolbox/lvq1.m
5,022
utf_8
86a6a5093c040aededf200f82b599cc0
function codebook=lvq1(codebook, data, rlen, alpha); %LVQ1 Trains a codebook with the LVQ1 -algorithm. % % sM = lvq1(sM, D, rlen, alpha) % % sM = lvq1(sM,sD,30*length(sM.codebook),0.08); % % Input and output arguments: % sM (struct) map struct, the class information must be % present on the first column of .labels field % D (struct) data struct, the class information must % be present on the first column of .labels field % rlen (scalar) running length % alpha (scalar) learning parameter % % sM (struct) map struct, the trained codebook % % NOTE: does not take mask into account. % % For more help, try 'type lvq1', or check out online documentation. % See also LVQ3, SOM_SUPERVISED, SOM_SEQTRAIN. %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % lvq1 % % PURPOSE % % Trains codebook with the LVQ1 -algorithm (described below). % % SYNTAX % % sM = lvq1(sM, D, rlen, alpha) % % DESCRIPTION % % Trains codebook with the LVQ1 -algorithm. Codebook contains a number % of vectors (mi, i=1,2,...,n) and so does data (vectors xj, % j=1,2,...,k). Both vector sets are classified: vectors may have a % class (classes are set to the first column of data or map -structs' % .labels -field). For each xj there is defined the nearest codebook % -vector index c by searching the minimum of the euclidean distances % between the current xj and codebook -vectors: % % c = min{ ||xj - mi|| }, i=[1,..,n], for fixed xj % i % If xj and mc belong to the same class, mc is updated as follows: % mc(t+1) = mc(t) + alpha * (xj(t) - mc(t)) % If xj and mc belong to different classes, mc is updated as follows: % mc(t+1) = mc(t) - alpha * (xj(t) - mc(t)) % Otherwise updating is not performed. % % Argument 'rlen' tells how many times training sequence is performed. % LVQ1 -algorithm may be stopped after a number of steps, that is % 30-50 times the number of codebook vectors. % % Argument 'alpha' is the learning rate, recommended to be smaller % than 0.1. % % NOTE: does not take mask into account. % % REFERENCES % % Kohonen, T., "Self-Organizing Map", 2nd ed., Springer-Verlag, % Berlin, 1995, pp. 176-179. % % See also LVQ_PAK from http://www.cis.hut.fi/research/som_lvq_pak.shtml % % REQUIRED INPUT ARGUMENTS % % sM The data to be trained. % (struct) A map struct. % % D The data to use in training. % (struct) A data struct. % % rlen (integer) Running length of LVQ1 -algorithm. % % alpha (float) Learning rate used in training. % % OUTPUT ARGUMENTS % % codebook Trained data. % (struct) A map struct. % % EXAMPLE % % lab = unique(sD.labels(:,1)); % different classes % mu = length(lab)*5; % 5 prototypes for each % sM = som_randinit(sD,'msize',[mu 1]); % initial prototypes % sM.labels = [lab;lab;lab;lab;lab]; % their classes % sM = lvq1(sM,sD,50*mu,0.05); % use LVQ1 to adjust % % the prototypes % sM = lvq3(sM,sD,50*mu,0.05,0.2,0.3); % then use LVQ3 % % SEE ALSO % % lvq3 Use LVQ3 algorithm for training. % som_supervised Train SOM using supervised training. % som_seqtrain Train SOM with sequential algorithm. % Contributed to SOM Toolbox vs2, February 2nd, 2000 by Juha Parhankangas % Copyright (c) Juha Parhankangas % http://www.cis.hut.fi/projects/somtoolbox/ % Juha Parhankangas 310100 juuso 020200 cod = codebook.codebook; c_class = class2num(codebook.labels(:,1)); dat = data.data; d_class = class2num(data.labels(:,1)); x=size(dat,1); y=size(cod,2); ONES=ones(size(cod,1),1); for t=1:rlen fprintf(1,'\rTraining round: %d',t); tmp=NaN*ones(x,y); for j=1:x no_NaN=find(~isnan(dat(j,:))); di = sqrt(sum([cod(:,no_NaN) - ONES*dat(j,no_NaN)].^2,2)); [foo,ind] = min(di); if d_class(j) & d_class(j) == c_class(ind) % 0 is for unclassified vectors tmp(ind,:) = cod(ind,:) + alpha * (dat(j,:) - cod(ind,:)); elseif d_class(j) tmp(ind,:) = cod(ind,:) - alpha*(dat(j,:) - cod(ind,:)); end end inds = find(~isnan(sum(tmp,2))); cod(inds,:) = tmp(inds,:); end codebook.codebook = cod; sTrain = som_set('som_train','algorithm','lvq1',... 'data_name',data.name,... 'neigh','',... 'mask',ones(y,1),... 'radius_ini',NaN,... 'radius_fin',NaN,... 'alpha_ini',alpha,... 'alpha_type','constant',... 'trainlen',rlen,... 'time',datestr(now,0)); codebook.trainhist(end+1) = sTrain; return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function nos = class2num(class) names = {}; nos = zeros(length(class),1); for i=1:length(class) if ~isempty(class{i}) & ~any(strcmp(class{i},names)) names=cat(1,names,class(i)); end end tmp_nos = (1:length(names))'; for i=1:length(class) if ~isempty(class{i}) nos(i,1) = find(strcmp(class{i},names)); end end
github
martinarielhartmann/mirtooloct-master
som_colorcode.m
.m
mirtooloct-master/somtoolbox/som_colorcode.m
7,983
utf_8
e110e71452756946ea1943fa0b627791
function colors=som_colorcode(m, colorcode, scaling) %SOM_COLORCODE Calculates a heuristic color coding for the SOM grid % % colors = som_colorcode(m, colorcode, scaling) % % Input and output arguments ([]'s are optional): % m (struct) map or topol struct % (cell array) of form {str,[m1 m2]} where % str = 'hexa' or 'rect' and [m1 m2] = msize % (matrix) size N x 2, unit coordinates % [colorcode] (string) 'rgb1' (default),'rgb2','rgb3','rgb4','hsv' % [scaling] (scalar) 1=on (default), 0=off. Has effect only % if m is a Nx2 matrix of coordinates: % controls whether these are scaled to % range [0,1] or not. % % colors (matrix) size N x 3, RGB colors for each unit (or point) % % The function gives a color coding by location for the map grid % (or arbitrary set of points). Map grid coordinates are always linearly % normalized to a unit square (x and y coordinates between [0,1]), except % if m is a Nx2 matrix and scaling=0. In that case too, the coordinates % must be in range [0,1]. % % Following heuristic color codings are available: % % 'rgb1' slice of RGB-cube so that green - yellow % the corners have colors: | | % blue - magenta % % 'rgb2' slice of RGB-cube so that red - yellow % the corners have colors: | | % blue - cyan % % 'rgb3' slice of RGB-cube so that mixed_green - orange % the corners have colors: | | % light_blue - pink % % 'rgb4' has 'rgb1' on the diagonal + additional colors in corners % (more resolution but visually strongly discontinuous) % % 'hsv' angle and radius from map centre are coded by hue and % intensity (more resoluton but visually discontinuous) % % See also SOM_CPLANE, SOM_SHOW, SOM_CLUSTERCOLOR, SOM_KMEANSCOLOR, % SOM_BMUCOLOR. % Contributed to SOM Toolbox 2.0, February 11th, 2000 by Johan Himberg % Copyright (c) by Johan Himberg % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0 Johan 140799 %%% Check arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% error(nargchk(1, 3, nargin)); % check no. of input args is correct %% Check m: map, topol, cell or data? if vis_valuetype(m,{'nx2'}), p=m; % explicit coordinates else % map, topol, cell [tmp,ok,tmp]=som_set(m); if isstruct(m) & all(ok) switch m.type case 'som_topol' % topol msize=m.msize; lattice=m.lattice; case 'som_map' msize=m.topol.msize; % map lattice=m.topol.lattice; otherwise error('Invalid map or topol struct.'); end % cell elseif iscell(m) & vis_valuetype(size(m),{[1 2]}), if vis_valuetype(m{2},{[1 2]}) & vis_valuetype(m{1},{'string'}), lattice=m{1}; msize=m{2}; else error('Invalid map size information.'); end end %% Check map parameters switch lattice % lattice case 'hexa' ; case 'rect' ; otherwise error('Unknown lattice type'); end if length(msize)>2 % dimension error('Only 2D maps allowed!'); end % Calculate coordinates p=som_unit_coords(msize,lattice,'sheet'); % Set scaling to 1 as it is done always in this case scaling=1; end % Check colorcode if nargin < 2 | isempty(colorcode), colorcode='rgb1'; end if ~ischar(colorcode) error('String value for colorcode mode expected.'); else switch colorcode case { 'rgb1', 'rgb2', 'rgb3' , 'rgb4' ,'hsv'} otherwise error([ 'Colorcode mode ' colorcode ' not implemented.']); end end % Check scaling if nargin < 3 | isempty(scaling) scaling=1; end if ~vis_valuetype(scaling,{'1x1'}) error('Scaling should be 0 (off) or 1 (on).'); end %% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % scale coordintes between [0,1] if scaling n=size(p,1); mn=min(p); e=max(p)-mn; p=(p-repmat(mn,n,1))./repmat(e,n,1); elseif sum(p(:,1)>1+p(:,1)<0+p(:,2)>1+p(:,2)<0), error('Coordinates out of range [0,1].'); end switch colorcode case 'rgb1' h(:,1)=p(:,1); h(:,2)=1-p(:,2); h(:,3)=p(:,2); case 'rgb2' h(:,1)=p(:,1); h(:,2)=1-p(:,2); h(:,3)=1-p(:,1); case 'rgb3' h(:,1)=p(:,1); h(:,2)=.5; h(:,3)=p(:,2); case 'rgb4' p=rgb4(p); h(:,1)=p(:,1); h(:,2)=1-p(:,2); h(:,3)=p(:,3); case 'hsv' munits = n; Hsv = zeros(munits,3); for i=1:n, dx = .5-p(i,1); dy = .5-p(i,2); r = sqrt(dx^2+dy^2); if r==0, h=1; elseif dx==0, h=.5; %h=ay; elseif dy==0, h=.5; %h=ax; else h = min(abs(.5/(dx/r)),abs(.5/(dy/r))); end if r==0, angle = 0; else angle = acos(dx/r); if dy<0, angle = 2*pi-angle; end end Hsv(i,1) = 1-sin(angle/4); Hsv(i,2) = 1; Hsv(i,3) = r/h; h = hsv2rgb(Hsv); end end %% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% colors=h; %% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% juha %%%% function p=rgb4(coord) for i=1:size(coord,1); p(i,:)=get_coords(coord(i,:))'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function coords=get_coords(coords) %GET_COORDS % % get_coords(coords) % % ARGUMENTS % % coords (1x2 or 2x1 vector) coords(1) is an x-coordinate and coords(2) % y-coordinate. % % % RETURNS % % coords (3x1 vector) x,y and z-coordinates. % if ~(all(size(coords) == [1 2]) | all(size(coords) == [2 1])) error('Argument ''coords'' must be an 2x1 or 1x2 vector.'); end if all(size(coords) == [1 2]) coords=coords'; end if any(coords > 1) any(coords < 0) error('Coordinates must lay inside the interval [0,1].'); end if coords(1) <= 1/(sqrt(2)+1), if coords(2) <= line3(coords(1)) coords=coords_in_base(4,coords); elseif coords(2) <= line2(coords(1)) coords=coords_in_base(1,coords); else coords=coords_in_base(2,coords); end elseif coords(1) <= sqrt(2)/(sqrt(2)+1) if coords(2) <= line1(coords(1)) coords=coords_in_base(3,coords); elseif coords(2) <= line2(coords(1)) coords=coords_in_base(1,coords); else coords=coords_in_base(2,coords); end else if coords(2) <= line1(coords(1)), coords=coords_in_base(3,coords); elseif coords(2) <= line4(coords(1)) coords=coords_in_base(1,coords); else coords=coords_in_base(5,coords); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function coords=coords_in_base(base_no,coords) A=[0;1/(sqrt(2)+1)]; E=[1;1]; F=[0;0]; G=[1;0]; H=[0;1]; const=1+1/sqrt(2); switch base_no case 1 x=(coords-A)*const; coords=[(1/sqrt(2))*(x(1)-x(2));0.5*(x(1)+x(2));0.5*(x(1)+x(2))]; case 2 x=(coords-H)*const; coords=[0;x(1);1+x(2)]; case 3 x=(coords-G)*const; coords=[1;1+x(1);x(2)]; case 4 x=(coords-F)*const; coords=[0.5+(1/sqrt(2))*(x(1)-x(2));... 0.5-(1/sqrt(2))*(x(1)+x(2));... 0]; case 5 x=(coords-E)*const; coords=[0.5+(1/sqrt(2))*(x(1)-x(2));... 0.5-(1/sqrt(2))*(x(1)+x(2));... 1]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y=line1(x) y = x-1/(sqrt(2)+1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y=line2(x) y = x+1/(sqrt(2)+1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y=line3(x) y = -x+1/(sqrt(2)+1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y= line4(x) y = -x+(2*sqrt(2)+1)/(sqrt(2)+1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
martinarielhartmann/mirtooloct-master
som_pieplane.m
.m
mirtooloct-master/somtoolbox/som_pieplane.m
9,892
utf_8
7d00431bbaad7c3344ddb3a827ada08b
function h=som_pieplane(varargin) %SOM_PIEPLANE Visualize the map prototype vectors as pie charts % % h=som_pieplane(lattice, msize, data, [color], [s], [pos]) % h=som_pieplane(topol, data, [color], [s], [pos]) % % som_pieplane('hexa',[5 5], rand(25,4), jet(4), rand(25,1)) % som_pieplane(sM, sM.codebook); % % Input and output arguments ([]'s are optional): % lattice (string) grid 'hexa' or 'rect' % msize (vector) size 1x2, defines the grid, M=msize(1)*msize(2) % (matrix) size Mx2, gives explicit coordinates for each node: in % this case the lattice does not matter. % topol (struct) map or topology struct % data (matrix) size Mxd, Mth row is the data for Mth pie. The % values will be normalized to have unit sum in each row. % [color] (matrix) size dx3, RGB triples. The first row is the % color of the first slice in each pie etc. Default is hsv(d). % (string) ColorSpec or 'none' gives the same color for each slice. % [s] (matrix) size Mx1, gives an individual size scaling for each node. % (scalar) gives the same size for each node. Default is 0.8. % [pos] (vectors) a 1x2 vector that determines position for the % origin, i.e. upper left corner. Default is no translation. % % h (scalar) the object handle to the PATCH object % % The data will be linearly scaled so that its sum is 1 in each unit. % Negative values are invalid. Axis are set as in som_cplane. % % For more help, try 'type som_pieplane' or check out online documentation. % See also SOM_CPLANE, SOM_PLOTPLANE, SOM_BARPLANE %%%%%%%%%%%%% DETAILED DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % som_pieplane % % PURPOSE % % Visualizes the map prototype vectors as pie charts. % % SYNTAX % % h = som_pieplane(topol, data) % h = som_pieplane(lattice, msize, data) % h = som_pieplane(..., color) % h = som_pieplane(..., color, s) % h = som_pieplane(..., color, s, pos) % % DESCRIPTION % % Visualizes the map prototype vectors as pie charts. % % KNOWN BUGS % % It is not possible to specify explicit coordinates for map % consisting of just one unit as then the msize is interpreted as % map size. % % FEATURES % % - negative values in data cause an error % % - the colors are fixed: changing colormap in the figure (see help % colormap) will not affect the coloring of the slices. % % - if input variable s has size Nxd it gives each slice an individual % scaling factor. This may be used to create a glyph where % the radius of the slice, not the angle, shows the variable % try, e.g., som_pieplane('rect',[5 4],ones(20,4),'w',rand(20,4)); % % REQUIRED INPUT ARGUMENTS % % lattice The basic shape of the map units % % (string) 'hexa' or 'rect' positions the pies according to hexagonal or % rectangular map lattice. % % msize The size of the map grid % % (vector) [n1 n2] vector defines the map size (height n1 units, % width n2 units, total M=n1xn2 units). The units will % be placed to their topological locations to form a % uniform hexagonal or rectangular grid. % (matrix) Mx2 matrix defines arbitary coordinates for the M units. In % this case the argument 'lattice' has no effect. % % topol Topology of the map grid % % (struct) map or topology struct from which the topology is taken % % data The data to be visualized % % (matrix) Mxd matrix of data vectors. Negative values are invalid. % % OPTIONAL INPUT ARGUMENTS % % If value is unspecified or empty ([] or ''), the default values % are used for optional input arguments. % % s The size scaling factors for the units % % (scalar) gives each unit the same size scaling: % 0 unit disappears (edges can be seen as a dot) % ... default size is 0.8 % >1 unit overlaps others % (matrix) Mx1 double: each unit gets individual size scaling % % color The color of the slices in each pie % % (string) ColorSpec or 'none' gives the same color for each slice % (matrix) dx3 matrix assigns an RGB color determined by the dth row of % the matrix to the dth slice (variable) in each pie plot % % pos Position of origin % % (vector) size 1x2: this is meant for drawing the plane in arbitary % location in a figure. Note the operation: if this argument is % given, the axis limits setting part in the routine is skipped and % the limits setting will be left to be done by % MATLAB's defaults. Default is no translation. % % OUTPUT ARGUMENTS % % h (scalar) Handle to the created patch object. % % OBJECT TAGS % % One object handle is returned: field Tag is set to 'planePie' % % EXAMPLES % % %%% Create the data and make a map % % data=rand(100,5); map=som_make(data); % % %%% Create a 'jet' colormap that has as many rows as the data has variables % % colors=jet(5); % % %%% Draw pies % % som_pieplane(map, map.codebook, colors); % % %%% Calculate the hits of data on the map and normalize them between [0,1] % % hit=som_hits(map,data); hit=hit./max(max(hit)); % % %%% Draw the pies so that their size tells the hit count % % som_pieplane(map, map.codebook, colors, hit); % % %%% Try this! (see section FEATURES) % % som_pieplane('rect',[5 4],ones(20,4),'w',rand(20,4)); % % SEE ALSO % % som_cplane Visualize a 2D component plane, u-matrix or color plane % som_barplane Visualize the map prototype vectors as bar diagrams % som_plotplane Visualize the map prototype vectors as line graphs % Copyright (c) 1999-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta Johan 140799 juuso 310300 070600 %%% Check & Init arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [nargin, lattice, msize, data, color, s, pos] = vis_planeGetArgs(varargin{:}); error(nargchk(3, 6, nargin)); % check no. of input args is correct % check pos if nargin < 6 | isempty(pos) pos=NaN; % default value for pos (no translation) elseif ~vis_valuetype(pos,{'1x2'}) error('Position of origin has to be given as an 1x2 vector'); end % check msize if ~vis_valuetype(msize,{'1x2','nx2'}), error('msize has to be 1x2 grid size vector or a Nx2 coordinate matrix.'); end % check data if ~isnumeric(data), error('Data matrix must be numeric.'); elseif length(size((data)))>2 error('Data matrix has too many dimensions!'); else d=size(data,2); N=size(data,1); end if any(data(:)<0) error('Negative data values not allowed in pie plots!'); end % Check lattice if ~ischar(lattice) | ~any(strcmp(lattice,{'hexa','rect'})), error('Invalid lattice.'); end %% Calculate patch coordinates for slices for i=1:N, [nx,ny]=vis_piepatch(data(i,:)); piesx(:,(1+(i-1)*d):(i*d))=nx; piesy(:,(1+(i-1)*d):(i*d))=ny; end l=size(piesx,1); if size(msize,1) == 1, if prod(msize) ~= N error('Data matrix has wrong size.'); else coord=som_vis_coords(lattice, msize); end else if N ~= size(msize,1), error('Data matrix has wrong size.'); end coord=msize; % This turns the axis tightening off, % as now we don't now the limits (no fixed grid) if isnan(pos); pos=[0 0]; end end x=reshape(repmat(coord(:,1),1,l*d)',l,d*N); y=reshape(repmat(coord(:,2),1,l*d)',l,d*N); % Check size if nargin < 5 | isempty(s), s=0.8; % default value for scaling elseif ~vis_valuetype(s, {'1x1', [N 1], [N d]}), error('Size matrix does not match with the data matrix.'); elseif size(s) == [N 1], s=reshape(repmat(s,1,l*d)',l,d*N); elseif all(size(s) ~= [1 1]), s=reshape(repmat(reshape(s',d*N,1),1,l)',l,d*N); end % Check color % C_FLAG is a flag for color 'none' if nargin < 4 | isempty(color) color=hsv(d); C_FLAG=0; % default n hsv colors end if ~(vis_valuetype(color, {[d 3], 'nx3rgb'},'all')) & ... ~vis_valuetype(color,{'colorstyle','1x3rgb'}), error('The color matrix has wrong size or contains invalid values.'); elseif ischar(color) & strcmp(color,'none'), C_FLAG=1; % check for color 'none' color='w'; else C_FLAG=0; % valid color string or colormap end %% Action %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Size zero would cause division by zero. eps is as good (node disappears) % The edge may be visible, though. (NaN causes some other problems) s(s==0)=eps; %% 1. Scaling x=(x./s+piesx).*s; y=(y./s+piesy).*s; %% 2. Translation if ~isnan(pos) x=x+pos(1);y=y+pos(2); end %% 3. Rearrange dx3 color matrix if ~isstr(color) & size(color,1)~=1, color=reshape(repmat(color,N,1),[1 N*d 3]); end %% Set axes properties ax=newplot; % get current axis vis_PlaneAxisProperties(ax,lattice, msize, pos); %% Draw the plane! h_=patch(x,y,color); if C_FLAG set(h_,'FaceColor','none'); end set(h_,'Tag','planePie'); % tag the object %%% Build output %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargout>0, h=h_; end % Set h only if % there really is output %%% Subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [x,y]=vis_piepatch(v) % Do a pie (see e.g. the MathWorks function PIE). % Origin is at (0,0) and the radius is .5. N=25; if sum(v)==0, v_is_zero = 1; v(1) = 1; else v_is_zero = 0; end v(v==0) = eps; % Matlab 5.2 version of linspace doesn't work otherwise phi=[0 2*pi*cumsum(v./sum(v))]; for i=2:length(phi), [xi,yi]=pol2cart(linspace(phi(i-1),phi(i),N),0.5); x(:,i-1)=[0 xi 0]'; y(:,i-1)=[0 yi 0]'; end if v_is_zero, x = x*0; y = y*0; end
github
martinarielhartmann/mirtooloct-master
metrop.m
.m
mirtooloct-master/netlab/metrop.m
4,976
utf_8
53e05637fbfd2fcd95efaadd86e97ce9
function [samples, energies, diagn] = metrop(f, x, options, gradf, varargin) %METROP Markov Chain Monte Carlo sampling with Metropolis algorithm. % % Description % SAMPLES = METROP(F, X, OPTIONS) uses the Metropolis algorithm to % sample from the distribution P ~ EXP(-F), where F is the first % argument to METROP. The Markov chain starts at the point X and each % candidate state is picked from a Gaussian proposal distribution and % accepted or rejected according to the Metropolis criterion. % % SAMPLES = METROP(F, X, OPTIONS, [], P1, P2, ...) allows additional % arguments to be passed to F(). The fourth argument is ignored, but % is included for compatibility with HMC and the optimisers. % % [SAMPLES, ENERGIES, DIAGN] = METROP(F, X, OPTIONS) also returns a log % of the energy values (i.e. negative log probabilities) for the % samples in ENERGIES and DIAGN, a structure containing diagnostic % information (position and acceptance threshold) for each step of the % chain in DIAGN.POS and DIAGN.ACC respectively. All candidate states % (including rejected ones) are stored in DIAGN.POS. % % S = METROP('STATE') returns a state structure that contains the state % of the two random number generators RAND and RANDN. These are % contained in fields randstate, randnstate. % % METROP('STATE', S) resets the state to S. If S is an integer, then % it is passed to RAND and RANDN. If S is a structure returned by % METROP('STATE') then it resets the generator to exactly the same % state. % % The optional parameters in the OPTIONS vector have the following % interpretations. % % OPTIONS(1) is set to 1 to display the energy values and rejection % threshold at each step of the Markov chain. If the value is 2, then % the position vectors at each step are also displayed. % % OPTIONS(14) is the number of samples retained from the Markov chain; % default 100. % % OPTIONS(15) is the number of samples omitted from the start of the % chain; default 0. % % OPTIONS(18) is the variance of the proposal distribution; default 1. % % See also % HMC % % Copyright (c) Ian T Nabney (1996-2001) if nargin <= 2 if ~strcmp(f, 'state') error('Unknown argument to metrop'); end switch nargin case 1 % Return state of sampler samples = get_state(f); % Function defined in this module return; case 2 % Set the state of the sampler set_state(f, x); % Function defined in this module return; end end display = options(1); if options(14) > 0 nsamples = options(14); else nsamples = 100; end if options(15) >= 0 nomit = options(15); else nomit = 0; end if options(18) > 0.0 std_dev = sqrt(options(18)); else std_dev = 1.0; % default end nparams = length(x); % Set up string for evaluating potential function. f = fcnchk(f, length(varargin)); samples = zeros(nsamples, nparams); % Matrix of returned samples. if nargout >= 2 en_save = 1; energies = zeros(nsamples, 1); else en_save = 0; end if nargout >= 3 diagnostics = 1; diagn_pos = zeros(nsamples, nparams); diagn_acc = zeros(nsamples, 1); else diagnostics = 0; end % Main loop. n = - nomit + 1; Eold = feval(f, x, varargin{:}); % Evaluate starting energy. nreject = 0; % Initialise count of rejected states. while n <= nsamples xold = x; % Sample a new point from the proposal distribution x = xold + randn(1, nparams)*std_dev; % Now apply Metropolis algorithm. Enew = feval(f, x, varargin{:}); % Evaluate new energy. a = exp(Eold - Enew); % Acceptance threshold. if (diagnostics & n > 0) diagn_pos(n,:) = x; diagn_acc(n,:) = a; end if (display > 1) fprintf(1, 'New position is\n'); disp(x); end if a > rand(1) % Accept the new state. Eold = Enew; if (display > 0) fprintf(1, 'Finished step %4d Threshold: %g\n', n, a); end else % Reject the new state if n > 0 nreject = nreject + 1; end x = xold; % Reset position if (display > 0) fprintf(1, ' Sample rejected %4d. Threshold: %g\n', n, a); end end if n > 0 samples(n,:) = x; % Store sample. if en_save energies(n) = Eold; % Store energy. end end n = n + 1; end if (display > 0) fprintf(1, '\nFraction of samples rejected: %g\n', ... nreject/(nsamples)); end if diagnostics diagn.pos = diagn_pos; diagn.acc = diagn_acc; end % Return complete state of the sampler. function state = get_state(f) state.randstate = rand('state'); state.randnstate = randn('state'); return % Set state of sampler, either from full state, or with an integer function set_state(f, x) if isnumeric(x) rand('state', x); randn('state', x); else if ~isstruct(x) error('Second argument to metrop must be number or state structure'); end if (~isfield(x, 'randstate') | ~isfield(x, 'randnstate')) error('Second argument to metrop must contain correct fields') end rand('state', x.randstate); randn('state', x.randnstate); end return
github
martinarielhartmann/mirtooloct-master
hmc.m
.m
mirtooloct-master/netlab/hmc.m
7,683
utf_8
64c15e958297afe69787b8617dc1a56a
function [samples, energies, diagn] = hmc(f, x, options, gradf, varargin) %HMC Hybrid Monte Carlo sampling. % % Description % SAMPLES = HMC(F, X, OPTIONS, GRADF) uses a hybrid Monte Carlo % algorithm to sample from the distribution P ~ EXP(-F), where F is the % first argument to HMC. The Markov chain starts at the point X, and % the function GRADF is the gradient of the `energy' function F. % % HMC(F, X, OPTIONS, GRADF, P1, P2, ...) allows additional arguments to % be passed to F() and GRADF(). % % [SAMPLES, ENERGIES, DIAGN] = HMC(F, X, OPTIONS, GRADF) also returns a % log of the energy values (i.e. negative log probabilities) for the % samples in ENERGIES and DIAGN, a structure containing diagnostic % information (position, momentum and acceptance threshold) for each % step of the chain in DIAGN.POS, DIAGN.MOM and DIAGN.ACC respectively. % All candidate states (including rejected ones) are stored in % DIAGN.POS. % % [SAMPLES, ENERGIES, DIAGN] = HMC(F, X, OPTIONS, GRADF) also returns % the ENERGIES (i.e. negative log probabilities) corresponding to the % samples. The DIAGN structure contains three fields: % % POS the position vectors of the dynamic process. % % MOM the momentum vectors of the dynamic process. % % ACC the acceptance thresholds. % % S = HMC('STATE') returns a state structure that contains the state of % the two random number generators RAND and RANDN and the momentum of % the dynamic process. These are contained in fields randstate, % randnstate and mom respectively. The momentum state is only used for % a persistent momentum update. % % HMC('STATE', S) resets the state to S. If S is an integer, then it % is passed to RAND and RANDN and the momentum variable is randomised. % If S is a structure returned by HMC('STATE') then it resets the % generator to exactly the same state. % % The optional parameters in the OPTIONS vector have the following % interpretations. % % OPTIONS(1) is set to 1 to display the energy values and rejection % threshold at each step of the Markov chain. If the value is 2, then % the position vectors at each step are also displayed. % % OPTIONS(5) is set to 1 if momentum persistence is used; default 0, % for complete replacement of momentum variables. % % OPTIONS(7) defines the trajectory length (i.e. the number of leap- % frog steps at each iteration). Minimum value 1. % % OPTIONS(9) is set to 1 to check the user defined gradient function. % % OPTIONS(14) is the number of samples retained from the Markov chain; % default 100. % % OPTIONS(15) is the number of samples omitted from the start of the % chain; default 0. % % OPTIONS(17) defines the momentum used when a persistent update of % (leap-frog) momentum is used. This is bounded to the interval [0, % 1). % % OPTIONS(18) is the step size used in leap-frogs; default 1/trajectory % length. % % See also % METROP % % Copyright (c) Ian T Nabney (1996-2001) % Global variable to store state of momentum variables: set by set_state % Used to initialise variable if set global HMC_MOM if nargin <= 2 if ~strcmp(f, 'state') error('Unknown argument to hmc'); end switch nargin case 1 samples = get_state(f); return; case 2 set_state(f, x); return; end end display = options(1); if (round(options(5) == 1)) persistence = 1; % Set alpha to lie in [0, 1) alpha = max(0, options(17)); alpha = min(1, alpha); salpha = sqrt(1-alpha*alpha); else persistence = 0; end L = max(1, options(7)); % At least one step in leap-frogging if options(14) > 0 nsamples = options(14); else nsamples = 100; % Default end if options(15) >= 0 nomit = options(15); else nomit = 0; end if options(18) > 0 step_size = options(18); % Step size. else step_size = 1/L; % Default end x = x(:)'; % Force x to be a row vector nparams = length(x); % Set up strings for evaluating potential function and its gradient. f = fcnchk(f, length(varargin)); gradf = fcnchk(gradf, length(varargin)); % Check the gradient evaluation. if (options(9)) % Check gradients feval('gradchek', x, f, gradf, varargin{:}); end samples = zeros(nsamples, nparams); % Matrix of returned samples. if nargout >= 2 en_save = 1; energies = zeros(nsamples, 1); else en_save = 0; end if nargout >= 3 diagnostics = 1; diagn_pos = zeros(nsamples, nparams); diagn_mom = zeros(nsamples, nparams); diagn_acc = zeros(nsamples, 1); else diagnostics = 0; end n = - nomit + 1; Eold = feval(f, x, varargin{:}); % Evaluate starting energy. nreject = 0; if (~persistence | isempty(HMC_MOM)) p = randn(1, nparams); % Initialise momenta at random else p = HMC_MOM; % Initialise momenta from stored state end lambda = 1; % Main loop. while n <= nsamples xold = x; % Store starting position. pold = p; % Store starting momenta Hold = Eold + 0.5*(p*p'); % Recalculate Hamiltonian as momenta have changed if ~persistence % Choose a direction at random if (rand < 0.5) lambda = -1; else lambda = 1; end end % Perturb step length. epsilon = lambda*step_size*(1.0 + 0.1*randn(1)); % First half-step of leapfrog. p = p - 0.5*epsilon*feval(gradf, x, varargin{:}); x = x + epsilon*p; % Full leapfrog steps. for m = 1 : L - 1 p = p - epsilon*feval(gradf, x, varargin{:}); x = x + epsilon*p; end % Final half-step of leapfrog. p = p - 0.5*epsilon*feval(gradf, x, varargin{:}); % Now apply Metropolis algorithm. Enew = feval(f, x, varargin{:}); % Evaluate new energy. p = -p; % Negate momentum Hnew = Enew + 0.5*p*p'; % Evaluate new Hamiltonian. a = exp(Hold - Hnew); % Acceptance threshold. if (diagnostics & n > 0) diagn_pos(n,:) = x; diagn_mom(n,:) = p; diagn_acc(n,:) = a; end if (display > 1) fprintf(1, 'New position is\n'); disp(x); end if a > rand(1) % Accept the new state. Eold = Enew; % Update energy if (display > 0) fprintf(1, 'Finished step %4d Threshold: %g\n', n, a); end else % Reject the new state. if n > 0 nreject = nreject + 1; end x = xold; % Reset position p = pold; % Reset momenta if (display > 0) fprintf(1, ' Sample rejected %4d. Threshold: %g\n', n, a); end end if n > 0 samples(n,:) = x; % Store sample. if en_save energies(n) = Eold; % Store energy. end end % Set momenta for next iteration if persistence p = -p; % Adjust momenta by a small random amount. p = alpha.*p + salpha.*randn(1, nparams); else p = randn(1, nparams); % Replace all momenta. end n = n + 1; end if (display > 0) fprintf(1, '\nFraction of samples rejected: %g\n', ... nreject/(nsamples)); end if diagnostics diagn.pos = diagn_pos; diagn.mom = diagn_mom; diagn.acc = diagn_acc; end % Store final momentum value in global so that it can be retrieved later HMC_MOM = p; return % Return complete state of sampler (including momentum) function state = get_state(f) global HMC_MOM state.randstate = rand('state'); state.randnstate = randn('state'); state.mom = HMC_MOM; return % Set complete state of sampler (including momentum) or just set randn % and rand with integer argument. function set_state(f, x) global HMC_MOM if isnumeric(x) rand('state', x); randn('state', x); HMC_MOM = []; else if ~isstruct(x) error('Second argument to hmc must be number or state structure'); end if (~isfield(x, 'randstate') | ~isfield(x, 'randnstate') ... | ~isfield(x, 'mom')) error('Second argument to hmc must contain correct fields') end rand('state', x.randstate); randn('state', x.randnstate); HMC_MOM = x.mom; end return
github
martinarielhartmann/mirtooloct-master
gtminit.m
.m
mirtooloct-master/netlab/gtminit.m
5,204
utf_8
ab76f6114a7e85375ade5e5889d5f6a7
function net = gtminit(net, options, data, samp_type, varargin) %GTMINIT Initialise the weights and latent sample in a GTM. % % Description % NET = GTMINIT(NET, OPTIONS, DATA, SAMPTYPE) takes a GTM NET and % generates a sample of latent data points and sets the centres (and % widths if appropriate) of NET.RBFNET. % % If the SAMPTYPE is 'REGULAR', then regular grids of latent data % points and RBF centres are created. The dimension of the latent data % space must be 1 or 2. For one-dimensional latent space, the % LSAMPSIZE parameter gives the number of latent points and the % RBFSAMPSIZE parameter gives the number of RBF centres. For a two- % dimensional latent space, these parameters must be vectors of length % 2 with the number of points in each of the x and y directions to % create a rectangular grid. The widths of the RBF basis functions are % set by a call to RBFSETFW passing OPTIONS(7) as the scaling % parameter. % % If the SAMPTYPE is 'UNIFORM' or 'GAUSSIAN' then the latent data is % found by sampling from a uniform or Gaussian distribution % correspondingly. The RBF basis function parameters are set by a call % to RBFSETBF with the DATA parameter as dataset and the OPTIONS % vector. % % Finally, the output layer weights of the RBF are initialised by % mapping the mean of the latent variable to the mean of the target % variable, and the L-dimensional latent variale variance to the % variance of the targets along the first L principal components. % % See also % GTM, GTMEM, PCA, RBFSETBF, RBFSETFW % % Copyright (c) Ian T Nabney (1996-2001) % Check for consistency errstring = consist(net, 'gtm', data); if ~isempty(errstring) error(errstring); end % Check type of sample stypes = {'regular', 'uniform', 'gaussian'}; if (strcmp(samp_type, stypes)) == 0 error('Undefined sample type.') end if net.dim_latent > size(data, 2) error('Latent space dimension must not be greater than data dimension') end nlatent = net.gmmnet.ncentres; nhidden = net.rbfnet.nhidden; % Create latent data sample and set RBF centres switch samp_type case 'regular' if nargin ~= 6 error('Regular type must specify latent and RBF shapes'); end l_samp_size = varargin{1}; rbf_samp_size = varargin{2}; if round(l_samp_size) ~= l_samp_size error('Latent sample specification must contain integers') end % Check existence and size of rbf specification if any(size(rbf_samp_size) ~= [1 net.dim_latent]) | ... prod(rbf_samp_size) ~= nhidden error('Incorrect specification of RBF centres') end % Check dimension and type of latent data specification if any(size(l_samp_size) ~= [1 net.dim_latent]) | ... prod(l_samp_size) ~= nlatent error('Incorrect dimension of latent sample spec.') end if net.dim_latent == 1 net.X = [-1:2/(l_samp_size-1):1]'; net.rbfnet.c = [-1:2/(rbf_samp_size-1):1]'; net.rbfnet = rbfsetfw(net.rbfnet, options(7)); elseif net.dim_latent == 2 net.X = gtm_rctg(l_samp_size); net.rbfnet.c = gtm_rctg(rbf_samp_size); net.rbfnet = rbfsetfw(net.rbfnet, options(7)); else error('For regular sample, input dimension must be 1 or 2.') end case {'uniform', 'gaussian'} if strcmp(samp_type, 'uniform') net.X = 2 * (rand(nlatent, net.dim_latent) - 0.5); else % Sample from N(0, 0.25) distribution to ensure most latent % data is inside square net.X = randn(nlatent, net.dim_latent)/2; end net.rbfnet = rbfsetbf(net.rbfnet, options, net.X); otherwise % Shouldn't get here error('Invalid sample type'); end % Latent data sample and basis function parameters chosen. % Now set output weights [PCcoeff, PCvec] = pca(data); % Scale PCs by eigenvalues A = PCvec(:, 1:net.dim_latent)*diag(sqrt(PCcoeff(1:net.dim_latent))); [temp, Phi] = rbffwd(net.rbfnet, net.X); % Normalise X to ensure 1:1 mapping of variances and calculate weights % as solution of Phi*W = normX*A' normX = (net.X - ones(size(net.X))*diag(mean(net.X)))*diag(1./std(net.X)); net.rbfnet.w2 = Phi \ (normX*A'); % Bias is mean of target data net.rbfnet.b2 = mean(data); % Must also set initial value of variance % Find average distance between nearest centres % Ensure that distance of centre to itself is excluded by setting diagonal % entries to realmax net.gmmnet.centres = rbffwd(net.rbfnet, net.X); d = dist2(net.gmmnet.centres, net.gmmnet.centres) + ... diag(ones(net.gmmnet.ncentres, 1)*realmax); sigma = mean(min(d))/2; % Now set covariance to minimum of this and next largest eigenvalue if net.dim_latent < size(data, 2) sigma = min(sigma, PCcoeff(net.dim_latent+1)); end net.gmmnet.covars = sigma*ones(1, net.gmmnet.ncentres); % Sub-function to create the sample data in 2d function sample = gtm_rctg(samp_size) xDim = samp_size(1); yDim = samp_size(2); % Produce a grid with the right number of rows and columns [X, Y] = meshgrid([0:1:(xDim-1)], [(yDim-1):-1:0]); % Change grid representation sample = [X(:), Y(:)]; % Shift grid to correct position and scale it maxXY= max(sample); sample(:,1) = 2*(sample(:,1) - maxXY(1)/2)./maxXY(1); sample(:,2) = 2*(sample(:,2) - maxXY(2)/2)./maxXY(2); return;
github
martinarielhartmann/mirtooloct-master
mlphess.m
.m
mirtooloct-master/netlab/mlphess.m
1,633
utf_8
b91a15ca11b4886de6c1671c33a735d3
function [h, hdata] = mlphess(net, x, t, hdata) %MLPHESS Evaluate the Hessian matrix for a multi-layer perceptron network. % % Description % H = MLPHESS(NET, X, T) takes an MLP network data structure NET, a % matrix X of input values, and a matrix T of target values and returns % the full Hessian matrix H corresponding to the second derivatives of % the negative log posterior distribution, evaluated for the current % weight and bias values as defined by NET. % % [H, HDATA] = MLPHESS(NET, X, T) returns both the Hessian matrix H and % the contribution HDATA arising from the data dependent term in the % Hessian. % % H = MLPHESS(NET, X, T, HDATA) takes a network data structure NET, a % matrix X of input values, and a matrix T of target values, together % with the contribution HDATA arising from the data dependent term in % the Hessian, and returns the full Hessian matrix H corresponding to % the second derivatives of the negative log posterior distribution. % This version saves computation time if HDATA has already been % evaluated for the current weight and bias values. % % See also % MLP, HESSCHEK, MLPHDOTV, EVIDENCE % % Copyright (c) Ian T Nabney (1996-2001) % Check arguments for consistency errstring = consist(net, 'mlp', x, t); if ~isempty(errstring); error(errstring); end if nargin == 3 % Data term in Hessian needs to be computed hdata = datahess(net, x, t); end [h, hdata] = hbayes(net, hdata); % Sub-function to compute data part of Hessian function hdata = datahess(net, x, t) hdata = zeros(net.nwts, net.nwts); for v = eye(net.nwts); hdata(find(v),:) = mlphdotv(net, x, t, v); end return
github
martinarielhartmann/mirtooloct-master
glmhess.m
.m
mirtooloct-master/netlab/glmhess.m
4,024
utf_8
2d706b82d25cb35ff9467fe8837ef26f
function [h, hdata] = glmhess(net, x, t, hdata) %GLMHESS Evaluate the Hessian matrix for a generalised linear model. % % Description % H = GLMHESS(NET, X, T) takes a GLM network data structure NET, a % matrix X of input values, and a matrix T of target values and returns % the full Hessian matrix H corresponding to the second derivatives of % the negative log posterior distribution, evaluated for the current % weight and bias values as defined by NET. Note that the target data % is not required in the calculation, but is included to make the % interface uniform with NETHESS. For linear and logistic outputs, the % computation is very simple and is done (in effect) in one line in % GLMTRAIN. % % [H, HDATA] = GLMHESS(NET, X, T) returns both the Hessian matrix H and % the contribution HDATA arising from the data dependent term in the % Hessian. % % H = GLMHESS(NET, X, T, HDATA) takes a network data structure NET, a % matrix X of input values, and a matrix T of target values, together % with the contribution HDATA arising from the data dependent term in % the Hessian, and returns the full Hessian matrix H corresponding to % the second derivatives of the negative log posterior distribution. % This version saves computation time if HDATA has already been % evaluated for the current weight and bias values. % % See also % GLM, GLMTRAIN, HESSCHEK, NETHESS % % Copyright (c) Ian T Nabney (1996-2001) % Check arguments for consistency errstring = consist(net, 'glm', x, t); if ~isempty(errstring); error(errstring); end ndata = size(x, 1); nparams = net.nwts; nout = net.nout; p = glmfwd(net, x); inputs = [x ones(ndata, 1)]; if nargin == 3 hdata = zeros(nparams); % Full Hessian matrix % Calculate data component of Hessian switch net.outfn case 'linear' % No weighting function here out_hess = [x ones(ndata, 1)]'*[x ones(ndata, 1)]; for j = 1:nout hdata = rearrange_hess(net, j, out_hess, hdata); end case 'logistic' % Each output is independent e = ones(1, net.nin+1); link_deriv = p.*(1-p); out_hess = zeros(net.nin+1); for j = 1:nout inputs = [x ones(ndata, 1)].*(sqrt(link_deriv(:,j))*e); out_hess = inputs'*inputs; % Hessian for this output hdata = rearrange_hess(net, j, out_hess, hdata); end case 'softmax' bb_start = nparams - nout + 1; % Start of bias weights block ex_hess = zeros(nparams); % Contribution to Hessian from single example for m = 1:ndata X = x(m,:)'*x(m,:); a = diag(p(m,:))-((p(m,:)')*p(m,:)); ex_hess(1:nparams-nout,1:nparams-nout) = kron(a, X); ex_hess(bb_start:nparams, bb_start:nparams) = a.*ones(net.nout, net.nout); temp = kron(a, x(m,:)); ex_hess(bb_start:nparams, 1:nparams-nout) = temp; ex_hess(1:nparams-nout, bb_start:nparams) = temp'; hdata = hdata + ex_hess; end otherwise error(['Unknown activation function ', net.outfn]); end end [h, hdata] = hbayes(net, hdata); function hdata = rearrange_hess(net, j, out_hess, hdata) % Because all the biases come after all the input weights, % we have to rearrange the blocks that make up the network Hessian. % This function assumes that we are on the jth output and that all outputs % are independent. bb_start = net.nwts - net.nout + 1; % Start of bias weights block ob_start = 1+(j-1)*net.nin; % Start of weight block for jth output ob_end = j*net.nin; % End of weight block for jth output b_index = bb_start+(j-1); % Index of bias weight % Put input weight block in right place hdata(ob_start:ob_end, ob_start:ob_end) = out_hess(1:net.nin, 1:net.nin); % Put second derivative of bias weight in right place hdata(b_index, b_index) = out_hess(net.nin+1, net.nin+1); % Put cross terms (input weight v bias weight) in right place hdata(b_index, ob_start:ob_end) = out_hess(net.nin+1,1:net.nin); hdata(ob_start:ob_end, b_index) = out_hess(1:net.nin, net.nin+1); return
github
martinarielhartmann/mirtooloct-master
rbfhess.m
.m
mirtooloct-master/netlab/rbfhess.m
3,138
utf_8
0a6ef29c8be32e9991cacfe42bdfa0b3
function [h, hdata] = rbfhess(net, x, t, hdata) %RBFHESS Evaluate the Hessian matrix for RBF network. % % Description % H = RBFHESS(NET, X, T) takes an RBF network data structure NET, a % matrix X of input values, and a matrix T of target values and returns % the full Hessian matrix H corresponding to the second derivatives of % the negative log posterior distribution, evaluated for the current % weight and bias values as defined by NET. Currently, the % implementation only computes the Hessian for the output layer % weights. % % [H, HDATA] = RBFHESS(NET, X, T) returns both the Hessian matrix H and % the contribution HDATA arising from the data dependent term in the % Hessian. % % H = RBFHESS(NET, X, T, HDATA) takes a network data structure NET, a % matrix X of input values, and a matrix T of target values, together % with the contribution HDATA arising from the data dependent term in % the Hessian, and returns the full Hessian matrix H corresponding to % the second derivatives of the negative log posterior distribution. % This version saves computation time if HDATA has already been % evaluated for the current weight and bias values. % % See also % MLPHESS, HESSCHEK, EVIDENCE % % Copyright (c) Ian T Nabney (1996-2001) % Check arguments for consistency errstring = consist(net, 'rbf', x, t); if ~isempty(errstring); error(errstring); end if nargin == 3 % Data term in Hessian needs to be computed [a, z] = rbffwd(net, x); hdata = datahess(net, z, t); end % Add in effect of regularisation [h, hdata] = hbayes(net, hdata); % Sub-function to compute data part of Hessian function hdata = datahess(net, z, t) % Only works for output layer Hessian currently if (isfield(net, 'mask') & ~any(net.mask(... 1:(net.nwts - net.nout*(net.nhidden+1))))) hdata = zeros(net.nwts); ndata = size(z, 1); out_hess = [z ones(ndata, 1)]'*[z ones(ndata, 1)]; for j = 1:net.nout hdata = rearrange_hess(net, j, out_hess, hdata); end else error('Output layer Hessian only.'); end return % Sub-function to rearrange Hessian matrix function hdata = rearrange_hess(net, j, out_hess, hdata) % Because all the biases come after all the input weights, % we have to rearrange the blocks that make up the network Hessian. % This function assumes that we are on the jth output and that all outputs % are independent. % Start of bias weights block bb_start = net.nwts - net.nout + 1; % Start of weight block for jth output ob_start = net.nwts - net.nout*(net.nhidden+1) + (j-1)*net.nhidden... + 1; % End of weight block for jth output ob_end = ob_start + net.nhidden - 1; % Index of bias weight b_index = bb_start+(j-1); % Put input weight block in right place hdata(ob_start:ob_end, ob_start:ob_end) = out_hess(1:net.nhidden, ... 1:net.nhidden); % Put second derivative of bias weight in right place hdata(b_index, b_index) = out_hess(net.nhidden+1, net.nhidden+1); % Put cross terms (input weight v bias weight) in right place hdata(b_index, ob_start:ob_end) = out_hess(net.nhidden+1, ... 1:net.nhidden); hdata(ob_start:ob_end, b_index) = out_hess(1:net.nhidden, ... net.nhidden+1); return
github
JoHof/semantic-profiles-master
plotTrainingData.m
.m
semantic-profiles-master/testData/plotTrainingData.m
1,013
utf_8
64d0eb06ad1195992191e94809702544
% (c) 2015 Johannes Hofmanninger, [email protected] % For academic research / private use only, commercial use prohibited function [ ] = plotTrainingData(data, weakLabels, trueLabels ) %% plotting the training data figure; subplot(2,2,1); scatter(data(1,weakLabels(:,1)),data(2,weakLabels(:,1)),'blue'); title('records with weak label blue') xlabel('feature1'); ylabel('feature2'); subplot(2,2,2); scatter(data(1,weakLabels(:,2)),data(2,weakLabels(:,2)),'red'); title('records with weak label red') xlabel('feature1'); ylabel('feature2'); subplot(2,2,3); scatter(data(1,weakLabels(:,3)),data(2,weakLabels(:,3)),'green'); title('records with weak label green') xlabel('feature1'); ylabel('feature2'); subplot(2,2,4); scatter(data(1,trueLabels==1),data(2,trueLabels==1),'blue'); hold on; scatter(data(1,trueLabels==2),data(2,trueLabels==2),'red'); scatter(data(1,trueLabels==3),data(2,trueLabels==3),'green'); title('true labeling of records') xlabel('feature1'); ylabel('feature2'); end
github
JoHof/semantic-profiles-master
semSynthWeakTrainingData.m
.m
semantic-profiles-master/testData/semSynthWeakTrainingData.m
600
utf_8
6e81b0bda8c665bba8190c8fdb846553
% (c) 2015 Johannes Hofmanninger, [email protected] % For academic research / private use only, commercial use prohibited function [ data, weakLabels, trueLabels ] = semSynthWeakTrainingData() [data, trueLabels] = semSynthTestData(); classes = unique(trueLabels); numClasses = length(classes); tClassLabels = zeros(size(trueLabels,1),length(unique(trueLabels))); randTrue = randperm(numel(tClassLabels)); tClassLabels(randTrue(1:ceil(length(randTrue)/2))) = 1; for i = 1:numClasses tClassLabels(trueLabels==classes(i),i) = 1; end weakLabels = logical(tClassLabels); end
github
JoHof/semantic-profiles-master
preRecall.m
.m
semantic-profiles-master/testData/preRecall.m
1,559
utf_8
d7829c75a484a69707cce9697b83588c
% (c) 2015 Johannes Hofmanninger, [email protected] % For academic research / private use only, commercial use prohibited function [ mprecision MAP base] = preRecall( trainingVectors,testVectors,trainingLabels,testLabels, queryInDatabase ) M = pdist2(trainingVectors',testVectors'); [~, indices] = sort(M); clear M indices = uint32(indices); if queryInDatabase indices = indices(2:end,:); end labels = trainingLabels(indices); clear indices classes = unique(testLabels); for j = 1:length(classes) class = classes(j); classQueries = find(testLabels==class); pr = zeros(length(classQueries),20); parfor kk = 1:length(classQueries) queryResults = labels(:,classQueries(kk)); classhit = queryResults==class; [pr(kk,:) mp(kk)] = precRecallAP(classhit); end mprecision(:,j) = mean(pr); %#ok<AGROW> MAP(j) = mean(mp); %#ok<AGROW> base(j) = sum(trainingLabels==class)/length(trainingLabels); %#ok<AGROW> end end function [ precision AP ] = precRecallAP( hits ) hitPos = find(hits); %ceil(recallLevels*nClass); parfor jj = 1:length(hitPos) k = hitPos(jj); Allprecision(jj) = jj/k; end AP = mean(Allprecision); recallLevels = 0.05:0.05:1; kForRecall = ceil(recallLevels*length(hitPos)); precision = Allprecision(kForRecall); end
github
JoHof/semantic-profiles-master
semSynthTestData.m
.m
semantic-profiles-master/testData/semSynthTestData.m
998
utf_8
c2bcd9636ff4921a96bffa06a904bdb8
% (c) 2015 Johannes Hofmanninger, [email protected] % For academic research / private use only, commercial use prohibited function [data labels] = semSynthTestData() CL1 = 200; CL2 = 200; CL3 = 300; data1 = zeros(CL1,2); data2 = zeros(CL2,2); data3 = zeros(CL3,2); data32 = zeros(CL3,2); for i=1:CL1 % rand value for x and y axis data1(i,1) = 1.5+randn*0.7; data1(i,2) = 1+randn; end for i = 1 : CL2 % rand value for x and y axis data2(i,1) = 3 + randn*0.3; data2(i,2) = 2 + randn*3; end for i = 1:CL3 % rand value for x and y axis data32(i,1) = rand*5.2-1; data32(i,2) = 1 + randn*0.4; end [tdatay, tadayidx] = sort(data32(:,1)); for i = 1:CL3 data3(tadayidx(i),1) = data32(tadayidx(i),1); data3(tadayidx(i),2) = real(data32(tadayidx(i),2) + 3*sqrt((mean(data32(:,1))-tdatay(1)).^2-abs(data32(tadayidx(i),1)-mean(data32(:,1))).^2)-1); end data = [data1; data2; data3]'; labels = [ones(CL1,1); ones(CL2,1)*2; ones(CL3,1)*3 ]; end
github
JoHof/semantic-profiles-master
spgetprofiles.m
.m
semantic-profiles-master/semProf/spgetprofiles.m
1,782
utf_8
591269a51cfc50e22f35a0fad3ed1754
% (c) 2015 Johannes Hofmanninger, [email protected] % For academic research / private use only, commercial use prohibited %% [ semProfiles ] = spgetprofiles(records, model) % % calculates the semantic profiles for a novel set of records given trained % model % % Input: % % records: a set of vecors in the from dxn % model: model returned by function sptrainmodel % model = sptrainmodel(trainingData,weakLabels,p); % % Output: % % semProfiles: dxn a set of sem Profiles where d=number of classes % function [ semProfiles ] = spgetprofiles(records, model) numClasses = length(model.sIdx); t1 = tic; [fernsVec] = getFernsResponse(records', model.ferns); tfernsResp = toc(t1); disp(['Ferns response in ... ' num2str(tfernsResp) 's']); semHist = single(zeros(size(fernsVec,1),numClasses)); t2 = tic; for i = 1:numClasses disp([num2str(i) '...Processing: ' num2str(i)]); [num fern] = ind2sub([2^model.ferns_depth model.num_ferns],model.sIdx{i}); num=uint8(num)-1; runs = ceil(length(num)/10000); % splitting data for saving some memory very = zeros(size(fernsVec,1),1); itemsPerIteration = 2e6; N = size(fernsVec,1); tv = zeros(N,1); for run = 1:runs subset = ((run-1)*10000)+1:min(run*10000,length(num)); Nruns = ceil(size(fernsVec,1)/itemsPerIteration); for Nrun = 1:Nruns Nsubset = ((Nrun-1)*itemsPerIteration)+1:min(Nrun*itemsPerIteration,N); tv(Nsubset) = sum(bsxfun(@eq,fernsVec(Nsubset,fern(subset)),num(subset)'),2); end very = very+tv; end veryProp = very/model.maxCount(i); semHist(:,i) = veryProp; end tProfiles = toc(t2); disp(['Profiles generation in ... ' num2str(tProfiles) 's']); semProfiles = semHist'; end
github
JoHof/semantic-profiles-master
sptrainmodel.m
.m
semantic-profiles-master/semProf/sptrainmodel.m
4,115
utf_8
2e41e116bceaf8f144b2a80f93ed9830
% (c) 2015 Johannes Hofmanninger, [email protected] % For academic research / private use only, commercial use prohibited %% [ r ] = sptrainmodel(records, classLabels, p) % % calculates the semantic profiles for a novel set of records given trained % model % % Input: % % records: a set of vecors in the from dxn % classLabels: weakLabels in the form nxc in [0,1] where c = number of % Classes. Each record is labeled with one to c classes % where only one is the true class. % p = struct holding parameters. Default parameters are: % % dp.num_ferns = 1200; % number of ferns to be generated % dp.ferns_depth = 8; % depth of one fern (e.g. 2^8 partitions per fern) % dp.sub_dims = 9; % number of sub-dimensions used on each split (usually <12) % dp.partitionRes = 5000; % parameter K in the Paper % dp.classSmoothing = 20; % parameter gamma in the paper (prevents overfitting) % % Output: % % r: struct holding all the model information needed to infer semantic % profiles for a novel record (e.g. like random ferns and relative class % frequencies in the partitions selected partitions % function [ r ] = sptrainmodel(records, classLabels, p) dp.num_ferns = 1200; % number of ferns to be generated dp.ferns_depth = 8; % depth of one fern (e.g. 2^8 partitions per fern) dp.sub_dims = 9; % number of sub-dimensions used on each split (usually <12) dp.partitionRes = 5000; % parameter K in the Paper dp.classSmoothing = 20; % parameter gamma in the paper (prevents overfitting) p = defaultParams(p,dp); if (size(classLabels,2)==1 && length(unique(classLabels))>2) classes = unique(classLabels); numClasses = length(classes); tClassLabels = zeros(size(classLabels,1),length(unique(classLabels))); for i = 1:numClasses tClassLabels(classLabels==classes(i),i) = 1; end classLabels = tClassLabels; end numClasses = size(classLabels,2); disp('Train the ferns...'); t1 = tic; [fernsVec r.ferns] = createFerns(records', p.num_ferns, p.ferns_depth, p.sub_dims); fernsTime = toc(t1); disp(['Feature space partitioning in ... ' num2str(fernsTime) 's']); disp('Building class distribution models...'); t2 = tic; ii = 0:(2^p.ferns_depth)-1; jj = p.num_ferns; histClass = zeros(length(ii),jj); fernsVecT = fernsVec'; %for efficiency classN = zeros(2^p.ferns_depth,jj); parfor j = 1:jj classN(:,j) = hist(double(fernsVec(:,j)),ii); end classN = classN(:); for i = 1:numClasses %actClass = classes(i); disp([num2str(i) '...Processing: ' num2str(i)]); classHit = logical(classLabels(:,i)); fVclassHit = single(fernsVecT(:,classHit))'; %slicing for parfor %fVnclassHit = double(fernsVecT(:,nclassHit))'; %slicing for parfor parfor j = 1:jj %histnClass(:,j) = hist(fVnclassHit(:,j),ii); histClass(:,j) = hist(fVclassHit(:,j),ii); end relTermFrequency = (histClass(:)+1)./(classN(:)+p.classSmoothing); %dirichlet prior relTermFrequency(isnan(relTermFrequency)) = 0; relTermFrequency(relTermFrequency<0) = 0; [~, scIdx] = sort(relTermFrequency,1,'descend'); sIdx{i} = scIdx(1:p.partitionRes,:); [num fern] = ind2sub([2^p.ferns_depth p.num_ferns],sIdx{i}); num=uint8(num)-1; runs = ceil(length(num)/10000); very = zeros(size(fernsVec,1),1); itemsPerIteration = 3e6; N = size(fernsVec,1); tv = zeros(N,1); for run = 1:runs subset = ((run-1)*10000)+1:min(run*10000,length(num)); Nruns = ceil(size(fernsVec,1)/itemsPerIteration); for Nrun = 1:Nruns Nsubset = ((Nrun-1)*itemsPerIteration)+1:min(Nrun*itemsPerIteration,N); tv(Nsubset) = sum(bsxfun(@eq,fernsVec(Nsubset,fern(subset)),num(subset)'),2); end very = very+tv; end r.maxCount(i) = max(very); end clear fVclassHit clear fVnclassHit modelTime = toc(t2); disp(['Distribution model learning in ... ' num2str(modelTime) 's']); r.sIdx = sIdx; r.num_ferns = p.num_ferns; r.ferns_depth = p.ferns_depth; end
github
JoHof/semantic-profiles-master
defaultParams.m
.m
semantic-profiles-master/semProf/utilFunctions/defaultParams.m
522
utf_8
388caf785537f6f53256b4f8201f1a20
% Functional Matlab Library % (c) 2013 Rene Donner, [email protected] % For academic research / private use only, commercial use prohibited %% function p = defaultParams(p,defaultp) % % Compare fields of "p" with "defaultp". % If field from "defaultp" is not existent in "p", add it. function p = defaultParams(p,defaultp) names = fieldnames(defaultp); for n = 1:length(names) name = names{n}; if not(isfield(p,name)) p = setfield(p,name,getfield(defaultp,name)); %#ok<GFLD,SFLD> end end
github
JoHof/semantic-profiles-master
d2b.m
.m
semantic-profiles-master/semProf/utilFunctions/d2b.m
482
utf_8
515c221dc19dfff23e689bc46e828679
% (c) 2015 Johannes Hofmanninger, [email protected] % For academic research / private use only, commercial use prohibited function y = d2b(x,nBits) % Convert a decimanl number into a binary array % % Similar to dec2bin but yields a numerical array instead of a string and is found to % be rather faster y =zeros([length(x) nBits],'single'); for iBit = 1:nBits % Loop over the bits y(:,iBit) = bitget(x,iBit); % Get the bit values end
github
JoHof/semantic-profiles-master
b2d.m
.m
semantic-profiles-master/semProf/utilFunctions/b2d.m
409
utf_8
4ea979cc601122efc8af700fdf979da7
% (c) 2015 Johannes Hofmanninger, [email protected] % For academic research / private use only, commercial use prohibited function y = b2d(x) % Convert a binary array to a decimal number % % Similar to bin2dec but works with arrays instead of strings and is found to be % rather faster z = single(2.^(0:1:size(x,2)-1)); y = single(x)*z'; y = cast(y,class(x)); %y = bsxfun(@times,x,z')
github
JoHof/semantic-profiles-master
createFerns.m
.m
semantic-profiles-master/semProf/randomFerns/createFerns.m
1,959
utf_8
1bf77a9732ac27cc920c3ec0aa7da732
% (c) 2015 Johannes Hofmanninger, [email protected] % For academic research / private use only, commercial use prohibited function [ wordVector, ferns ] = createFerns( featureVector, num_ferns, num_nodes, dim ) %CREATE_FERNS Trains ferns out of featureVectore provided vector_dim = size(featureVector,2); sub = size(featureVector,1); if(dim>vector_dim) error('createFern:chkInput', 'featureVector dimension lower than split dimensions!'); end if(sub<vector_dim) fprintf('nDim < N, Input should be provided as column vectors!'); end switch (ceil(num_nodes/8)) case 1 type = 'uint8'; case 2 type = 'uint16'; case {3,4} type = 'uint32'; otherwise error('createFern:chkInput', 'Max fern depth is 32!'); end %allocating memory binaryVector = zeros([sub num_nodes], type); wordVector = zeros([sub num_ferns],type); ferns.dims = zeros(dim,num_ferns,num_nodes); ferns.proj_vector = zeros(dim,num_ferns,num_nodes); ferns.threshold = zeros(num_ferns,num_nodes); for fern=1:1:num_ferns for node=1:1:num_nodes x = randperm(vector_dim); rand_dims = x(1:dim); subspace = featureVector(:,rand_dims); %produce a random subspace rand_proj_vector =randn([size(subspace,2) 1]); %generate random peojection vector projection_values = subspace * rand_proj_vector; %project the subvectors ridx = randi(length(projection_values)); %random value with distribution on projection threshold = projection_values(ridx); %choose the value binaryVector(:,node) = projection_values>threshold; %thresholding of values %save fern in data structure ferns.dims(:,fern,node) = rand_dims; ferns.proj_vector(:,fern,node) = rand_proj_vector; ferns.threshold(fern,node) = threshold; end wordVector(:,fern) = b2d(binaryVector); %save the outcome end end
github
JoHof/semantic-profiles-master
getFernsResponse.m
.m
semantic-profiles-master/semProf/randomFerns/getFernsResponse.m
1,382
utf_8
c064bca01e8de189931c41bf41c5f578
% (c) 2015 Johannes Hofmanninger, [email protected] % For academic research / private use only, commercial use prohibited function [ leafIndizes ] = getFernsResponse( queryVector, ferns ) % gets the fern response for provided vector and fern num_ferns = size(ferns.dims,2); num_nodes = size(ferns.dims,3); switch (ceil(num_nodes/8)) case 1 type = 'uint8'; case 2 type = 'uint16'; case {3,4} type = 'uint32'; otherwise fprintf('Max fern depth is 32!\n'); return; end sub = size(queryVector,1); %memory pre-allocation binaryVector = zeros([sub num_nodes], type); leafIndizes = zeros([sub num_ferns],type); for fern=1:num_ferns for node=1:num_nodes rand_dims = ferns.dims(:,fern,node); subspace = queryVector(:,rand_dims); %produce a random subspace rand_proj_vector = ferns.proj_vector(:,fern,node); projection_values = subspace * rand_proj_vector; %project the subvectors threshold = ferns.threshold(fern,node); binaryVector(:,node) = projection_values>(threshold+(1e-10)); %save the outcome and floating point error correction %leafIndizes(:,fern) = leafIndizes(:,fern) + cast((projection_values>(threshold+(1e-10)))*2^(node-1),type); end leafIndizes(:,fern) = b2d(binaryVector); end end
github
maeager/Agilent2Dicom-master
call_mci.m
.m
Agilent2Dicom-master/matlab/call_mci.m
4,352
utf_8
5af977ebde5cecfe6cf1052bc018648f
function call_mci(in1,in2,out,saveRI) % Calling MCI - max contrast imaging % % - (C) 2015 Michael Eager ([email protected]) % - Monash Biomedical Imaging [a,b,c] = fileparts(mfilename('fullpath')) ; [a,b,c] = fileparts(a) ; root_path=a; addpath(fullfile(root_path,'matlab')) addpath(fullfile(root_path,'matlab/NIFTI')) addpath(fullfile(root_path, 'matlab/Agilent/')) display('Calling MCI') if nargin == 3 saveRI=0; end %% Clean input strings in1 = regexprep(in1,'["\[\]]',''); if ~isempty(in2) if isstr(in2) in2 = regexprep(in2,'["\[\]]',''); else in2=[]; end end out = regexprep(out,'["\[\]]',''); voxelsize=[]; ksp1=[];ksp2=[]; if exist(in1,'file')==2 && ~isempty(strfind(in1,'.nii')) nii1_in=load_nii(in1); img=nii1_in.img; ksp1=fftn(img); voxelsize1=nii1_in.dime.pixdim(2:4); elseif ~isempty(strfind(in1,'.img')) && isdir(in1) [img hdr] =readfdf(in1); % voxelsize=hdr.FOVcm/size(img)*10; ksp1=fftn(img); % voxelsize1=hdr.roi*10/hdr.matrix; voxelsize1 = hdr.voxelsize*10; elseif ~isempty(strfind(in1,'.fid')) && isdir(in1) [img, hdr, ksp1, RE, IM] = readfid(in1); voxelsize1=hdr.voxelmm; % voxelsize=hdr.FOVcm*10/size(img); else display(['Cannot find ' in1]) return end if ~isempty(in2) if exist(in2,'file')==2 && ~isempty(strfind(in2,'.nii')) nii2_in=load_nii(in2); img=nii2_in.img; ksp2=fftn(img); voxelsize2=nii2_in.dime.pixdim(2:4); elseif ~isempty(strfind(in2,'.img')) && isdir(in2) [img hdr] =readfdf(in2); % voxelsize=hdr.FOVcm/size(img)*10; ksp2=fftn(img); %voxelsize2=hdr.roi*10/hdr.matrix; voxelsize2 = hdr.voxelsize*10; elseif ~isempty(strfind(in2,'.fid')) && isdir(in2) [img, hdr, ksp2, RE, IM] = readfid(in2); % voxelsize2=hdr.FOVcm*10/size(img); voxelsize2=hdr.voxelmm; else display(['Cannot find ' in2]) % return end end if ~isempty(in2) && sum(voxelsize1) ~= sum(voxelsize2) display(['Voxelsizes don''t match: ' str2num(voxelsize1) ' ' ... str2num(voxelsize2)]) return end voxelsize=voxelsize1; [pha1, swi_n1, swi_p1, mag1] = phaserecon_v1(ksp1,ksp1,0.4,1,0.05); % Necessary translations to match FDF images mag1=flipdim(flipdim(flipdim(mag1,1),2),3); mag1=circshift(mag1,[1,1,1]); pha1=flipdim(flipdim(flipdim(pha1,1),2),3); pha1=circshift(pha1,[1,1,1]); if ~isempty(ksp2) [pha2, swi_n2, swi_p2, mag2] = phaserecon_v1(ksp2,ksp2,0.4,1, ... 0.05); mag2=flipdim(flipdim(flipdim(mag2,1),2),3); mag2=circshift(mag2,[1,1,1]); pha2=flipdim(flipdim(flipdim(pha2,1),2),3); pha2=circshift(pha2,[1,1,1]); end stdmask=stdfilt(mag1); stdphmask=stdfilt(pha1); gbmask =getbiggestobject(stdphmask<0.013 | stdmask>2000); mask=(gbmask.*(pha1>0)); r_mag = mean(mag1(mask==1)); r_pha = mean(pha1(mask==1)); mci_mag1 = mci(mag1,pha1,[r_mag, r_pha]); if exist(out,'file')~=2 && ~isdir(out) %if not a file or a dir, create dir mkdir (out) end if isdir(out) out=[out '/mci_magn.nii.gz']; end if exist(out,'file') delete(out) end if isempty(ksp2) save_nii(make_nii(abs(mci_mag1),voxelsize,[],16),out) else mci_mag2 = mci(mag2,pha2,[r_mag,rpha]); save_nii(make_nii(abs((mci_mag1+mci_mag2)/2.0),voxelsize,[],16),out) end if saveRI if isempty(ksp2) save_nii(make_nii(real(mci_mag1),voxelsize,[],16),regexprep(out,'magn','real')) save_nii(make_nii(imag(mci_mag1),voxelsize,[],16),regexprep(out,'magn','imag')) else save_nii(make_nii(real((mci_mag1+mci_mag2)/2.0),voxelsize, ... [],16),regexprep(out,'magn','real')) save_nii(make_nii(imag((mci_mag1+mci_mag2)/2.0),voxelsize, ... [],16),regexprep(out,'magn','imag')) end end function output = mci(magnitude,phase,reference) % MCI create Maximum Contrast Image % % OUTPUT = MCI(MAGNITUDE,PHASE,REFERENCE) % % MAGNITUDE = magnitude image % PHASE = phase image % REFERENCE = reference point % % Created by Zhaolin Chen % Adapted by Amanda Ng on 11 March 2009 % Updated by Michael Eager July 2015 phasereg=phase.*0; phasereg(phase>0)=phase(phase>0)-reference(2); phasereg(phase<0)=phase(phase<0)+reference(2); output = sqrt((magnitude-reference(1)).^2 + (phasereg).^2);
github
maeager/Agilent2Dicom-master
call_swi.m
.m
Agilent2Dicom-master/matlab/call_swi.m
5,198
utf_8
f4bde8fd7e63390cac2b6b4cfe3c7669
function call_swi(in1,in2,out,order,preprocess,saveRI,swineg,swipos) % Calling susceptibility weighted imaging filter % % - (C) 2015 Michael Eager ([email protected]) % - Monash Biomedical Imaging [a,b,c] = fileparts(mfilename('fullpath')) ; [a,b,c] = fileparts(a) ; root_path=a; addpath(fullfile(root_path,'matlab')) addpath(fullfile(root_path,'matlab/NIFTI')) addpath(fullfile(root_path, 'matlab/Agilent/')) %% Clean input strings in1 = regexprep(in1,'["\[\]]',''); if ~isempty(in2) if isstr(in2) in2 = regexprep(in2,'["\[\]]',''); else in2=[]; end end out = regexprep(out,'["\[\]]',''); %" display('Calling SWI') display(in1) display (in2) display (out) if nargin < 8 swipos=0; end if nargin < 7 swipneg=0; end if nargin < 6 saveRI=0; end if nargin < 5 preprocess=0; end if nargin < 4 order=0; end voxelsize=[]; ksp1=[];ksp2=[]; if exist(in1,'file')==2 && ~isempty(strfind(in1,'.nii')) nii1_in=load_nii(in1); img=nii1_in.img; ksp1=fftn(img); voxelsize1=nii1_in.dime.pixdim(2:4); elseif ~isempty(strfind(in1,'.img')) && isdir(in1) [img hdr] =readfdf(in1); % voxelsize=hdr.FOVcm/size(img)*10; ksp1=fftn(img); % voxelsize1=hdr.roi*10/hdr.matrix; voxelsize1 = hdr.voxelsize*10; elseif ~isempty(strfind(in1,'.fid')) && isdir(in1) [img, hdr, ksp1, RE, IM] = readfid(in1); voxelsize1=hdr.voxelmm; % voxelsize=hdr.FOVcm*10/size(img); else display(['Cannot find ' in1]) return end if ~isempty(in2) if exist(in2,'file')==2 && ~isempty(strfind(in2,'.nii')) nii2_in=load_nii(in2); img=nii2_in.img; ksp2=fftn(img); voxelsize2=nii2_in.dime.pixdim(2:4); elseif ~isempty(strfind(in2,'.img')) && isdir(in2) [img hdr] =readfdf(in2); % voxelsize=hdr.FOVcm/size(img)*10; ksp2=fftn(img); %voxelsize2=hdr.roi*10/hdr.matrix; voxelsize2 = hdr.voxelsize*10; elseif ~isempty(strfind(in2,'.fid')) && isdir(in2) [img, hdr, ksp2, RE, IM] = readfid(in2); % voxelsize2=hdr.FOVcm*10/size(img); voxelsize2=hdr.voxelmm; else display(['Cannot find second image ' in2]) % return end end if ~isempty(in2) && sum(voxelsize1) ~= sum(voxelsize2) display(['Voxelsizes don''t match: ' str2num(voxelsize1) ' ' ... str2num(voxelsize2)]) return end voxelsize=voxelsize1; ksp1=squeeze(ksp1); if length(size(ksp1)) == 3 [pha, swi_n, swi_p, mag] = phaserecon_v1(ksp1,ksp1,0.4,1,0.05); % Necessary translations to match FDF images swi_n=flipdim(flipdim(flipdim(swi_n,1),2),3); swi_n=circshift(swi_n,[1,1,1]); img=mag.*exp(1i*pha); elseif length(size(ksp1)) == 4 for echo=1:size(ksp1,4) [pha(:,:,:,echo), swi_n(:,:,:,echo), swi_p(:,:,:,echo), mag(:,:,:,echo)] = phaserecon_v1(ksp1(:,:,:,echo),ksp1(:,:,:,echo),0.4,1,0.05); % Necessary translations to match FDF images swi_n(:,:,:,echo)=flipdim(flipdim(flipdim(swi_n(:,:,:,echo),1),2),3); swi_n(:,:,:,echo)=circshift(swi_n(:,:,:,echo),[1,1,1]); img(:,:,:,echo)=mag(:,:,:,echo).*exp(1i*pha(:,:,:,echo)); end end if ~isempty(ksp2) if length(size(ksp2)) == 3 [pha2, swi_n2, swi_p2, mag2] = phaserecon_v1(ksp2,ksp2,0.4,1, ... 0.05); swi_n2=flipdim(flipdim(flipdim(swi_n2,1),2),3); swi_n2=circshift(swi_n2,[1,1,1]); elseif length(size(ksp2)) == 4 pha2=zeros(size(ksp2)); mag2=zeros(size(ksp2)); swi_n2=zeros(size(ksp2)); swi_p2=zeros(size(ksp2)); img2=zeros(size(ksp2)); for echo=1:size(ksp2,4) [pha2(:,:,:,echo), swi_n2(:,:,:,echo), swi_p2(:,:,:,echo), mag2(:,:,:,echo)] = phaserecon_v1(ksp2(:,:,:,echo),ksp2(:,:,:,echo),0.4,1,0.05); % Necessary translations to match FDF images swi_n2(:,:,:,echo)=flipdim(flipdim(flipdim(swi_n2(:,:,:,echo),1),2),3); swi_n2(:,:,:,echo)=circshift(swi_n2(:,:,:,echo),[1,1,1]); img2(:,:,:,echo)=mag2(:,:,:,echo).*exp(1i*pha2(:,:,:,echo)); end end % Combine input 1 and 2 swi_n = (swi_n+swi_n2)/2; swi_p = (swi_p+swi_p2)/2; img = (img+ (mag2.*exp(1i*pha2)))/2; end %% Write output if exist(out,'file')~=2 && ~isdir(out) %if not a file or a dir, create dir mkdir (out) end if isdir(out) out=[out '/swi_neg.nii.gz']; end if exist(out,'file') delete(out) end savetonii(swi_n,voxelsize,out) if swipos swi_p=flipdim(flipdim(flipdim(swi_p,1),2),3); swi_p=circshift(swi_p,[1,1,1]); outp = regexprep(out,'neg','pos'); savetonii(swi_p,voxelsize,outp) end if saveRI savetonii(real(img),voxelsize,regexprep(out,'neg','real')) savetonii(imag(img),voxelsize,regexprep(out,'neg','imag')) end function savetonii(vol,vsize,fname) if length(size(ksp1)) ==3 save_nii(make_nii(single(vol),vsize,[0,0,0],16),fname) elseif length(size(ksp1)) == 4 for echo=1:size(vol,4) save_nii(make_nii(single(vol(:,:,:,1,echo)),vsize,[0,0,0],16),regexprep(fname,'.nii.gz',['echo' num2str(echo) '.nii.gz'])) end end
github
maeager/Agilent2Dicom-master
call_mee.m
.m
Agilent2Dicom-master/matlab/call_mee.m
4,619
utf_8
b8b8430d463afad48497ddc86880095b
function call_mee(in1,in2,out,porder,preprocess,saveRI,useswi) % Calling MEE - multi-echo enhancement % % - (C) 2015 Michael Eager ([email protected]) % - Monash Biomedical Imaging [a,b,c] = fileparts(mfilename('fullpath')) ; [a,b,c] = fileparts(a) ; root_path=a; addpath(fullfile(root_path,'./matlab')) addpath(fullfile(root_path,'./matlab/NIFTI')) addpath(fullfile(root_path, './matlab/Agilent/')) display('Calling MCI') if nargin < 4 porder=3; end if nargin < 5 preprocess=0; end if nargin < 6 saveRI=0; end if nargin < 7 useswi=0; end %% Clean input strings in1 = regexprep(in1,'["\[\]]',''); if ~isempty(in2) if isstr(in2) in2 = regexprep(in2,'["\[\]]',''); else in2=[]; end end out = regexprep(out,'["\[\]]',''); voxelsize=[]; ksp1=[];ksp2=[]; if exist(in1,'file')==2 && ~isempty(strfind(in1,'.nii')) nii1_in=load_nii(in1); img=nii1_in.img; ksp1=fftn(img); voxelsize1=nii1_in.dime.pixdim(2:4); elseif ~isempty(strfind(in1,'.img')) && isdir(in1) [img hdr] =readfdf(in1); % voxelsize=hdr.FOVcm/size(img)*10; ksp1=fftn(img); % voxelsize1=hdr.roi*10/hdr.matrix; voxelsize1 = hdr.voxelsize*10; elseif ~isempty(strfind(in1,'.fid')) && isdir(in1) [img, hdr, ksp1, RE, IM] = readfid(in1); voxelsize1=hdr.voxelmm; % voxelsize=hdr.FOVcm*10/size(img); else display(['Cannot find ' in1]) return end if ~isempty(in2) if exist(in2,'file')==2 && ~isempty(strfind(in2,'.nii')) nii2_in=load_nii(in2); img=nii2_in.img; ksp2=fftn(img); voxelsize2=nii2_in.dime.pixdim(2:4); elseif ~isempty(strfind(in2,'.img')) && isdir(in2) [img hdr] =readfdf(in2); % voxelsize=hdr.FOVcm/size(img)*10; ksp2=fftn(img); %voxelsize2=hdr.roi*10/hdr.matrix; voxelsize2 = hdr.voxelsize*10; elseif ~isempty(strfind(in2,'.fid')) && isdir(in2) [img, hdr, ksp2, RE, IM] = readfid(in2); % voxelsize2=hdr.FOVcm*10/size(img); voxelsize2=hdr.voxelmm; else display(['Cannot find ' in2]) % return end end if ~isempty(in2) && sum(voxelsize1) ~= sum(voxelsize2) display(['Voxelsizes don''t match: ' str2num(voxelsize1) ' ' ... str2num(voxelsize2)]) return end voxelsize=voxelsize1; %% If using preprocessing % add content %% Homodyne filter [pha1, swi_n1, swi_p1, mag1] = phaserecon_v1(ksp1,ksp1,0.4,1,0.05); % Necessary translations to match FDF images if ~useswi mag1=flipdim(flipdim(flipdim(mag1,1),2),3); mag1=circshift(mag1,[1,1,1]); pha1=flipdim(flipdim(flipdim(pha1,1),2),3); pha1=circshift(pha1,[1,1,1]); if ~isempty(ksp2) [pha2, swi_n2, swi_p2, mag2] = phaserecon_v1(ksp2,ksp2,0.4,1, 0.05); mag2=flipdim(flipdim(flipdim(mag2,1),2),3); mag2=circshift(mag2,[1,1,1]); pha2=flipdim(flipdim(flipdim(pha2,1),2),3); pha2=circshift(pha2,[1,1,1]); end mee_mag1 = mee((mag1.*exp(1i*pha1)),porder); else swi1=flipdim(flipdim(flipdim(swi_n1,1),2),3); swi1=circshift(swi1,[1,1,1]); mee_mag1 = mee(swi1,porder); end if exist(out,'file')~=2 && ~isdir(out) %if not a file or a dir, create dir mkdir (out) end if isdir(out) out=[out '/mee_magn.nii.gz']; end if exist(out,'file') delete(out) end if isempty(ksp2) save_nii(make_nii(abs(mee_mag1),voxelsize,[],16),out) else if ~useswi mee_mag2 = mee((mag2.*exp(1i*pha2)),porder); else swi2=flipdim(flipdim(flipdim(swi_n2,1),2),3); swi2=circshift(swi2,[1,1,1]); mee_mag2 = mee(swi2,porder); end save_nii(make_nii(abs((mee_mag1+mee_mag2)/2.0),voxelsize,[],16),out) end if saveRI && ~useswi if isempty(ksp2) save_nii(make_nii(real(mee_mag1),voxelsize,[],16),regexprep(out,'magn','real')) save_nii(make_nii(imag(mee_mag1),voxelsize,[],16),regexprep(out,'magn','imag')) else save_nii(make_nii(real((mee_mag1+mee_mag2)/2.0),voxelsize, ... [],16),regexprep(out,'magn','real')) save_nii(make_nii(imag((mee_mag1+mee_mag2)/2.0),voxelsize, ... [],16),regexprep(out,'magn','imag')) end end function output = mee(img,order) % Multi-echo enhancement % % img = 5D magnitude image % % Created by Michael Eager July 2015 sz=size(img);output=[]; if len(sz)==4 sz(5)=sz(4);sz(4)=1; img = reshape(img,sz); elseif len(sz)~=5 return end if sz(4)~=1 && sz(5) == 1 output=img; return end img = (abs(img)); if nargin==1 p=3.0; else p=order; end output = (sum(img.^-p,5)./sz).^(-1/p);
github
maeager/Agilent2Dicom-master
ReadProcpar.m
.m
Agilent2Dicom-master/matlab/ReadProcpar.m
1,951
utf_8
da490bc01ee896267897830ecffd509e
function vals = ReadProcpar( ppName, ppPath ) % Get the values for parameter name in procpar file path % Usage: vals = getPPV( ppName, ppPath ) % fn = 'I_t.fid/procpar' ppPath; fp = fopen( ppPath, 'r'); done = 0; vals = []; while( done == 0 ) line = fgetl(fp); if (line == -1) done = 1; elseif isempty(line) disp('Warning,there is an empty space in the procpar file') line = fgetl(fp); else % if ~isletter(line) % disp(line); % error( 'bad format') % else if (strcmp(line(1),ppName(1))) [name, attr] = strtok(line); if (strcmp(name, ppName)) attr = str2num(attr); % Read in the values line = fgetl(fp); %disp(line); [cnt, parm] = strtok(line); cnt = str2num(cnt); % REAL_VALS if (attr(2) == 1) vals = str2num( parm ); % STRING_VALS else vals = dbl_quote_extract( parm ); while( size(vals,1) ~= cnt ) line = fgetl(fp); vals = char(vals, dbl_quote_extract( line ) ); end end if (strcmp(name, ppName)) break; else vals=[]; end % Read in the enums enum_line = fgetl(fp); end end % end end end fclose( fp ); function outStr = dbl_quote_extract( inStr ) %dbl_quote_extract - Extract String from between pair of Double Quotes dqIdx = findstr(inStr, '"'); dqCnt = size(dqIdx,2); if ((dqCnt == 0) | (1 == mod(dqCnt,2))) error( 'Bad string double quote balance') end for idx = 1:2:dqCnt off = [dqIdx(idx) + 1, dqIdx(idx+1) - 1]; if (idx == 1) outStr = inStr(off(1):off(2)); else outStr = char(outStr, inStr(off(1):off(2))); end end
github
michtesar/asymmetry_toolbox-master
eegplugin_faa.m
.m
asymmetry_toolbox-master/faa/eegplugin_faa.m
445
utf_8
83c4cda851f338a5163d7300dde14946
% This book/study is a result of the research funded by the project % Nr. LO1611 with a financial support from the MEYS under the NPU I program. function eegplugin_faa(fig, try_strings, catch_strings) % Create menu toolsmenu = findobj(fig, 'tag', 'tools'); submenu = uimenu( toolsmenu, 'label', 'Compute FAA'); % Compute FAA index uimenu( submenu, 'label', 'Compute FAA index', 'callback',... 'faa_index'); end
github
OrangeOwlSolutions/Optimization-master
dbrent.m
.m
Optimization-master/Polak-Ribiere/Matlab/dbrent.m
7,146
utf_8
b79e27e7cc8bb2f0c8c9687e2a3ec230
% Given a function costfunctional and its derivative function grad_costfunctional, and given a bracketing triplet of abscissas ax, % bx, cx [such that ax < bx < cx, and f(bx) < f(ax) and f(bx) < f(cx), tipically the output of mnbrak], this routine isolates the % minimum to a fractional precision of about tol using a modification of Brent’s method that uses derivatives. The abscissa of the % minimum is returned as lambdamin, and the minimum function value is returned as out. % --- The function f(lambda) is a contraction for f(x + lambda * p) function [lambdamin out] = dbrent(ax, bx, cx, tol, x, p, itmax, costfunctional, grad_costfunctional) % --- itmax number of iterations zeps = 1.e-10; % --- a and b are fixed as the extremes of the bracketing interval so that % a < b a = min([ax cx]); b = max([ax cx]); % --- lambda, lambda_1 and lambda_2 are the estimates of the minimum at the current iteration, at two iterations % before, and at the last iteration, respectively. They are all initialized at initial estimate of the minimum lambda = bx; lambda_1 = lambda; lambda_2 = lambda; % --- xt = x + lambda * p % --- flambda = f(x + lambda * p) is the functional value at the current % estimate of the minimum [flambda xt] = f1dim(lambda, x, p, costfunctional); flambda_1 = flambda; flambda_2 = flambda; % --- dotlambda = <Gradf_xt,p> dotlambda = df1dim(xt, p, grad_costfunctional); dotlambda_2 = dotlambda; dotlambda_1 = dotlambda; e = 0.; for iter=1:itmax % --- Bisection step xm = 0.5 * (a + b); tol1 = tol * abs(lambda) + zeps; tol2 = 2. * tol1; % --- Convergence check. If the current minimum estimate lambda is % sufficiently close to the bisected point, then the minimum is % considered to be reached. if (abs(lambda - xm) <= (tol2 - 0.5 * (b - a))) lambdamin = lambda; out = flambda; return; end if (abs(e) > tol1) % --- Initialize these increment d’s to an out-of-bracket value d1 = 2. * (b - a); d2 = d1; % --- Secant method with one point if (dotlambda_1 ~= dotlambda) d1 = (lambda_2 - lambda) * dotlambda / (dotlambda - dotlambda_1); end if (dotlambda_2 ~= dotlambda) d2 = (lambda_1 - lambda) * dotlambda / (dotlambda - dotlambda_2); end % --- Which of these two estimates of d shall we take? We will insist that they be within % the bracket, and on the side pointed to by the derivative at x: u1 = lambda + d1; u2 = lambda + d2; ok1 = ((a - u1) * (u1 - b) > 0.) && (dotlambda * d1 <= 0.); ok2 = ((a - u2) * (u2 - b) > 0.) && (dotlambda * d2 <= 0.); olde = e; e = d; % --- Take only an acceptable d, and if both are acceptable, then take the smallest one. if (ok1 || ok2) if (ok1 && ok2) if (abs(d1) < abs(d2)) d = d1; else d = d2; end else if (ok1) d = d1; else d = d2; end end if (abs(d) <= abs(0.5 * olde)) u = lambda + d; if (((u - a) < tol2) || ((b - u) < tol2)) d = abs(tol1) * sign(xm - lambda); end else if (dotlambda >= 0.) e = a - lambda; else e = b - lambda; end d = 0.5 * e; end else if (dotlambda >= 0.) e = a - lambda; else e = b - lambda; end d = 0.5 * e; end else % --- If the scalar product between the gradient at the current % point and the search direction > 0, then set the bisection step d to bisect (a, lambda) % otherwise set the bisection step d to bisect (lambda, b) if (dotlambda >= 0.) e = a - lambda; else e = b - lambda; end d = 0.5 * e; end if (abs(d) >= tol1) % --- If the bisection step d is not too small, use d to perform a real bisection u = lambda + d; [fu xt] = f1dim(u, x, p, costfunctional); else % --- If the bisection step d is not too small, use d to perform a real bisection u = lambda + abs(tol1) * sign(d); [fu xt] = f1dim(u, x, p, costfunctional); % --- If the minimum step in the downhill direction takes us uphill, then we are done. if (fu > flambda) lambdamin = lambda; out = flambda; return; end end du = df1dim(xt, p, grad_costfunctional); if (fu < flambda) % --- Enters here if the new trial minimum produces a lower % functional value if (u >= lambda) % --- Advance a to lambda if the current trial minimum is % larger than lambda a = lambda; else % --- Decrease b to lambda if the current trial minimim is % lower than lambda b = lambda; end % --- Saves the estimate of the minimum, its functional and the dot % product at two iterations before lambda_2 = lambda_1; flambda_2 = flambda_1; dotlambda_2 = dotlambda_1; % --- Saves the estimate of the minimum, its functional and the dot % product at the previous iteration lambda_1 = lambda; flambda_1 = flambda; dotlambda_1 = dotlambda; % --- Saves the estimate of the minimum, its functional and the dot % product at the current iteration lambda = u; flambda = fu; dotlambda = du; else % --- Here fu > flambda if (u < lambda) a = u; else b = u; end if ((fu <= flambda_1) || (lambda_1 == lambda)) % --- If the bisection point does not improve on the current % minimum estimate, but improves on the previous estimate (step -1), then % shift lambda_1 -> lambda_2 and u -> lambda_1 lambda_2 = lambda_1; flambda_2 = flambda_1; dotlambda_2 = dotlambda_1; lambda_1 = u; flambda_1 = fu; dotlambda_1 = du; else if ((fu <= flambda_2) || (lambda_2 == lambda) || (lambda_2 == lambda_1)) % --- If the bisection point does not improve on the current % minimum estimate, but improves on the previous estimate (step -1), then % shift u -> lambda_1 lambda_2 = u; flambda_2 = fu; dotlambda_2 = du; end end end end disp('Too many iterations in dbrent') lambdamin = lambda; out = flambda;
github
OrangeOwlSolutions/Optimization-master
mnbrak.m
.m
Optimization-master/Polak-Ribiere/Matlab/mnbrak.m
3,496
utf_8
8c9911a490d4309896419e613ecbe22e
% Given a function costfunctional, and given distinct initial points ax and bx, this routine searches in % the downhill direction (defined by the function as evaluated at the initial points) and returns % new points ax, bx, cx that bracket a minimum of the function. The points ax, bx and cx are such that % the minimum is within ax and cx and in the proximity of bx. In other words, ax < bx < cx function [ax, bx, cx] = mnbrak(ax, bx, cx, x, p, costfunctional) % --- p Search direction gold = 1.618034; glimit = 100.; tiny = 1.e-20; % --- It is assumed that fb < fa. If not, swap ax and bx fa = f1dim(ax, x, p, costfunctional); fb = f1dim(bx, x, p, costfunctional); if (fb > fa) [ax bx] = swap(ax, bx); [fa fb] = swap(fa, fb); end % --- First guess for cx cx = bx + gold * (bx - ax); fc = f1dim(cx, x, p, costfunctional); % --- Keep runnning until we bracket while (fb > fc) % --- Compute u by parabolic extrapolation from ax, bx, cx. TINY is used to prevent any possible division by zero r = (bx - ax) * (fb - fc); q = (bx - cx) * (fb - fa); u = bx - ((bx - cx) * q - (bx - ax) * r) / (2. * (abs(max([abs(q - r), tiny])) * sign(q - r))); ulim = bx + glimit * (cx - bx); if (((bx - u) * (u - cx)) > 0.) % --- Enters this branch if u is in between bx and cx, that is, cx < u < bx or bx < u < cx fu = f1dim(u, x, p, costfunctional); if (fu < fc) % --- Enters here if u is in between bx and cx and fu < fc < fb % (the last inequality is due to the while loop) => we have a % minimum between bx and cx ax = bx; fa = fb; bx = u; fb = fu; return; else if (fu > fb) % --- Enters here if fb < fu and fb < fa (the last % inequality is due to the first swap) => we have a minimum % between ax and u cx = u; fc = fu; return; end end % --- No minimum found yet. Use default magnification. u = cx + gold * (cx - bx); fu=f1dim(u, x, p, costfunctional); else if ((cx - u) * (u - ulim) > 0.) % --- Enters this branch if u is in between cx and its allowed limit ulim fu=f1dim(u, x, p, costfunctional); if (fu < fc) % --- fa > fb > fc > fu => the function is decreasing % towards fu => shift everything towards u bx = cx; cx = u; u = cx + gold * (cx - bx); fb = fc; fc = fu; fu = f1dim(u, x, p, costfunctional); end else if ((u - ulim) * (ulim - cx) >= 0.) % --- ulim is between u and cx which means that u is beyond % its maximum allowed value => limit u to its maximum value % ulim u = ulim; fu = f1dim(u, x, p, costfunctional); else % --- Move u ahead with default magnification u = cx + gold * (cx - bx); fu = f1dim(u, x, p, costfunctional); end end end % --- Update the points ax = bx; bx = cx; cx = u; fa = fb; fb = fc; fc = fu; end
github
OrangeOwlSolutions/Optimization-master
linmin.m
.m
Optimization-master/Polak-Ribiere/Matlab/linmin.m
690
utf_8
a6bebec04d1c563720ecad807edcdca0
% --- Line minimization ... see Numerical Recipes function [x p] = linmin(x, p, itmax, costfunctional, grad_costfunctional) % --- p Search direction % --- x Unknowns (input - output) % --- itmax Maximum number of iterations % --- Bracketing tolerance tol = 1.e-8; lsm = max(abs(p)); disp('Prima di mnbrak') ax = 0.; xx = .1e-2/(lsm+1.e-10); bx = .2e-2/(lsm+1.e-10); % xx = 0; % bx = 1; [ax bx cx] = mnbrak(ax, xx, bx, x, p, costfunctional); lambdamin = dbrent(ax, cx, bx, tol, x, p, itmax, costfunctional, grad_costfunctional); p = lambdamin * p; x = x + p;