Added source Matlab code for reference

This commit is contained in:
Waldir Leoncio 2019-12-16 16:47:21 +01:00
parent b8af977117
commit b5d99903d2
186 changed files with 61405 additions and 1 deletions

993
matlab/general/baps4cbf.m Normal file
View file

@ -0,0 +1,993 @@
function baps4cbf(action)
base = findobj('Tag','base_figure');
%setWindowOnTop(base,'false')
switch action
case 'mix1_button'
greedyMix(-1);
case 'mix2_button'
greedyPopMix;
case 'trained_button'
trainedMix;
case 'spatial_button'
spatialMixture;
showmethebaps;
case 'spatial2_button'
spatialPopMixture;
showmethebaps;
case 'linkage_button'
linkageMixture_speed;
%linkageMixture_ultraspeed;
showmethebaps;
case 'admix1_button'
admix1(-1);
showmethebaps;
case 'admix2_button'
admix2;
case 'compare_menu'
compare;
case 'compare_admix_menu'
compare_admix;
case 'load_mixture_menu'
loadMixture;
case 'load_admixture_menu'
loadAdmixture;
case 'load_spatial_menu'
loadSpatial;
case 'output_menu'
asetaOutputFile;
case 'remove_outputfile_menu'
poistaOutputFile;
case 'close_menu'
closeFile;
case 'exit_menu'
h0 = findobj('Tag','base_figure'); delete(h0);
h0 = findobj('Tag','image_figure'); delete(h0);
case 'loadfigure_menu'
loadFigure;
case 'plot_coordinates_menu'
plotCoordinates;
case 'partitio_menu'
viewPartitio;
case 'admix_menu'
viewAdmixture;
case 'likelihood_menu'
viewLoghood;
case 'energy_menu'
viewEnergy;
case 'geneflow_menu'
viewGeneflow;
case 'voronoi_menu'
voronoiTessellation;
case 'varmuus_menu'
localUncertainty;
case 'changecolor_menu'
changeColor;
case 'helpdoc'
openHelpDoc;
case 'helponline'
openHelpHtml;
case 'about'
openAboutWindow;
case 'calculate_kl'
calculateDis('KL');
case 'calculate_nei'
calculateDis('Nei');
case 'calculate_hamming'
calculateDis('Hamming');
case 'upgma_menu'
viewPhylogeny('upgma');
case 'nj_menu'
viewPhylogeny('nj');
case 'mutationplot_menu'
mutationPlot(-1);
case 'fixk_menu'
goToFixedK;
case 'partitioncompare_menu'
goToPartitionCompare;
end
return
%--------------------------------------------------------------------------
%KUVIEN LATAAMINEN
%--------------------------------------------------------------------------
function loadFigure
waitALittle;
[filename,pathname] = uigetfile('*.fig','Load Figure');
if (sum(filename)==0) || (sum(pathname)==0)
return;
end
fig_file_name = [pathname filename];
open(fig_file_name);
% ----------------------------
% Old version
% ----------------------------
% % Loads previously saved figure.
%
% waitALittle;
% [filename,pathname] = uigetfile('*.mat','Load Figure');
% if (sum(filename)==0) || (sum(pathname)==0)
% return;
% end
% fig_file_name = [pathname filename];
% %Figure file format must be *.mat. Ensure it:
% isMat = isTheFileMatFile(fig_file_name);
% if isMat == 0
% msgbox(['Only figures that have been saved in BAPS can be loaded in BAPS. ' ...
% 'Those figures have extension ".mat".'],'Error', ...
% 'error');
% return;
% end;
% struct_array = load([pathname filename]);
% if isfield(struct_array,'tiedot') %Matlab versio
% tiedot = struct_array.tiedot;
% if ~isfield(tiedot,'info')
% disp('Incorrect file format');
% return
% end
% elseif isfield(struct_array,'info') %Mideva versio
% tiedot = struct_array;
% else
% disp('Incorrect file format');
% return;
% end
%
% if isfield(tiedot, 'rows')
% rows = tiedot.rows;
% partition = tiedot.info;
% popnames = tiedot.popnames;
% viewPopMixPartition(partition, rows, popnames);
% else
% popnames = tiedot.popnames;
% info = tiedot.info;
% if (size(info,2)>1)
% %info on osuudet
% osuudet = info;
% viewPartition(osuudet,popnames);
% else
% info = round(info);
% partition = info;
% viewMixPartition(partition, popnames);
% end
% end
function isMat = isTheFileMatFile(filename)
%Checks that the file 'filename' is of the
%*.mat format. If so, isMat = 1. Otherwise, isMat = 0.
len = length(filename);
if len < 5
isMat = 0; return;
end;
ending = filename(end-3:end);
if isequal(ending,'.mat')
isMat = 1;
else
isMat = 0;
end;
%--------------------------------------------------------------------
function asetaOutputFile
waitALittle;
[filename, pathname] = uiputfile('*.txt', 'Specify output file');
if filename==0
return
end
h0 = findobj('Tag','filename2_text');
set(h0,'String',[pathname filename]);
%---------------------------------------------------
function poistaOutputFile
h0 = findobj('Tag','filename2_text');
set(h0,'String','');
%-----------------------------------------------------
function plotCoordinates
waitALittle;
[filename, pathname] = uigetfile('*.txt', 'Load Coordinate File');
if filename==0
return
end
X = load([pathname filename]);
if size(X,2)~=2
disp('Incorrect file format');
return
end
waitALittle;
[filename, pathname] = uigetfile('*.mat', 'Load mixture clustering of individuals');
%load([pathname filename],'c');
struct_array = load([pathname filename]);
if isfield(struct_array,'c') %Matlab versio
c = struct_array.c;
if ~isfield(c,'PARTITION') || ~isfield(c,'rowsFromInd')
disp('Incorrect file format');
return
end
elseif isfield(struct_array,'PARTITION') %Mideva versio
c = struct_array;
if ~isfield(c,'rowsFromInd')
disp('Incorrect file format');
return
end
else
disp('Incorrect file format');
return;
end
PARTITION = c.PARTITION;
if length(PARTITION) ~= size(X,1)
disp('Incorrect number of coordinate pairs.');
return
end
% h0 = image_figure;
hold on;
for i=1:length(PARTITION)
if X(i,1)>=0
plot(X(i,1),X(i,2),'Color',[.8 .8 .8]);
text(X(i,1),X(i,2),num2str(PARTITION(i)));
end
end
hold off;
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
function voronoiTessellation
% Tekee tulostiedostosta voronoi tessellaation.
h0 = findobj('Tag','load_menu');
c = get(h0,'UserData');
% waitALittle;
% [filename, pathname] = uigetfile('*.mat', 'Load mixture clustering');
% %load([pathname filename],'c');
% struct_array = load([pathname filename]);
% if isfield(struct_array,'c') %Matlab versio
% c = struct_array.c;
% if ~isfield(c,'PARTITION') || ~isfield(c,'rowsFromInd')
% disp('Incorrect file format');
% return
% end
% elseif isfield(struct_array,'PARTITION') %Mideva versio
% c = struct_array;
% if ~isfield(c,'rowsFromInd')
% disp('Incorrect file format');
% return
% end
% else
% disp('Incorrect file format');
% return;
% end
%
% if ~isfield(c, 'pointers')
% disp('Coordinate data missing from the result file');
% return;
% end
pointers = c.pointers; vorPoints = c.vorPoints; vorCells = c.vorCells;
coordinates = c.coordinates; names = c.names;
if isequal(c.mixtureType, 'pop') || isequal(c.mixtureType, 'spatialPop')
PARTITION = c.groupPartition;
else
PARTITION = c.PARTITION;
end
talle = questdlg(['Do you want names to be visible in the colored ' ...
'Voronoi tessellation?'], 'Names visible?', 'Yes', 'No', 'Yes');
if isequal(talle,'No')
names = -1;
end
vorPlot(vorPoints, vorCells, PARTITION, pointers, coordinates, names);
%--------------------------------------------------------------------------
function localUncertainty
% Tekee tulostiedostosta kolmiulotteisen lokaalia epävarmuutta kuvaavan
% kuvan.
h0 = findobj('Tag','load_menu');
c = get(h0,'UserData');
% waitALittle;
% [filename, pathname] = uigetfile('*.mat', 'Load mixture clustering');
% %load([pathname filename],'c');
% struct_array = load([pathname filename]);
% if isfield(struct_array,'c') %Matlab versio
% c = struct_array.c;
% if ~isfield(c,'PARTITION') || ~isfield(c,'rowsFromInd')
% disp('Incorrect file format');
% return
% end
% elseif isfield(struct_array,'PARTITION') %Mideva versio
% c = struct_array;
% if ~isfield(c,'rowsFromInd')
% disp('Incorrect file format');
% return
% end
% else
% disp('Incorrect file format');
% return;
% end
%
% if ~isfield(c, 'pointers')
% disp('Coordinate data missing from the result file');
% return;
% end
pointers = c.pointers; vorPoints = c.vorPoints; vorCells = c.vorCells;
coordinates = c.coordinates; names = c.names;
varmuus = c.varmuus;
if isequal(c.mixtureType, 'pop') || isequal(c.mixtureType, 'spatialPop')
PARTITION = c.groupPartition;
else
PARTITION = c.PARTITION;
end
talle = questdlg('Do you want names to be visible in the plot?', ...
'Names visible?', 'Yes', 'No', 'Yes');
if isequal(talle,'No')
names = -1;
end
plotVarmuus(vorPoints, vorCells, pointers, varmuus, coordinates, ...
PARTITION, names);
%--------------------------------------------------------------------------
function viewPartitio
h0 = findobj('Tag','load_menu');
c = get(h0,'UserData');
% waitALittle;
% [filename, pathname] = uigetfile('*.mat', 'Load mixture clustering');
% %load([pathname filename],'c');
% if (sum(filename)==0) || (sum(pathname)==0)
% return;
% end
% struct_array = load([pathname filename]);
% if isfield(struct_array,'c') %Matlab versio
% c = struct_array.c;
% if ~isfield(c,'PARTITION') || ~isfield(c,'rowsFromInd')
% disp('Incorrect file format');
% return
% end
% elseif isfield(struct_array,'PARTITION') %Mideva versio
% c = struct_array;
% if ~isfield(c,'rowsFromInd')
% disp('Incorrect file format');
% return
% end
% else
% disp('Incorrect file format');
% return;
% end
if isequal(c.mixtureType, 'pop') || isequal(c.mixtureType, 'spatialPop')
viewPopMixPartition(c.groupPartition, c.rows, c.popnames);
elseif isequal(c.mixtureType, 'trained')
viewMixPartition(c.PARTITION, []);
else
viewMixPartition(c.PARTITION, c.popnames);
end
function openHelpDoc
% s = fileparts(which('BAPS4manual.doc'));
% helpwin(s);
if strcmp(computer,'PCWIN')
% s = fileparts(which('baps4.exe'));
% winopen([s '\BAPS4manual.doc']);
winopen('BAPS5manual.doc');
end
function openHelpHtml
% web http://www.rni.helsinki.fi/~jic/bapspage.html
% web('http://www.rni.helsinki.fi/~jic/bapspage.html','-browser')
% web http://www.rni.helsinki.fi/~jic/bapspage.html -new;
if strcmp(computer,'PCWIN')
dos('start http://www.abo.fi/fak/mnf/mate/jc/software/baps.html'); % For the compiled version
end
function openAboutWindow
info{1}='';
info{2}='Bayesian Analysis of Population Structure (BAPS)';
info{3}='';
info{4}='Version 6.0';
info{5}='';
info{6}='Author: Jukka Corander, Pekka Marttinen, Jukka Siren, Jing Tang and Lu Cheng';
info{7}='';
info{8}='Copyright 2005-2012. All Rights Reserved';
info{9}='';
info{10}='Please view the reference page when using as part of research';
info{11}='at http://www.helsinki.fi/bsg/software/BAPS';
info{12} ='';
helpdlg(info,'About');
%--------------------------------------------------------------------------
function viewAdmixture
% waitALittle;
% [filename, pathname] = uigetfile('*.mat', 'Load admixture results.');
% if (sum(filename)==0) || (sum(pathname)==0)
% return;
% end
% %load([pathname filename],'c');
% struct_array = load([pathname filename]);
disp('---------------------------------------------------');
disp('Viewing the admixture result...');
h0 = findobj('Tag','load_menu');
c = get(h0,'UserData');
h0 = findobj('Tag','filename1_text');
filename = get(h0,'String');
% if isfield(struct_array,'c') %Matlab versio
% c = struct_array.c;
% if ~isfield(c,'proportionsIt')
% disp('*** ERROR: Incorrect file format');
% return
% end
% elseif isfield(struct_array,'proportionsIt') %Mideva versio
% c = struct_array;
% if ~isfield(c,'proportionsIt')
% disp('*** ERROR: Incorrect file format');
% return
% end
% else
% disp('*** ERROR: Incorrect file format');
% return;
% end
% mixtureType = c.mixtureType;
proportionsIt = c.proportionsIt;
popnames = c.popnames; partition = c.PARTITION;
mixtureType = c.mixtureType;
% if strcmp(mixtureType,'linkage_mix') % For bacterial clustering data
% if isempty(popnames) || size(popnames,1)==size(partition,1)
%if strcmp(mixtureType, 'admix')
if isempty(popnames)
ninds = size(partition,1);
popnames=cell(ninds,2);
for ind=1:ninds
popnames{ind,1}=cellstr(num2str(ind));
end
popnames(:,2)=num2cell((1:ninds)');
end
npops = c.npops; % all the clusters including outliers
admixnpops = c.admixnpops;
if ~isfield(c,'pvalue') % compatiable with old data
disp('*** WARNING: pvalue is not found in the admixture result.');
disp('*** WARNING: Old admixture file.');
pvalue = ones(size(partition,1),1);
else
pvalue = c.pvalue;
end
view_admixture(proportionsIt,npops,admixnpops, ...
popnames,partition,pvalue,filename);
%else
% disp('*** ERROR: incorrect admixture data.');
% put which variable as the input?
% admixnpops = c.admixnpops;
% npops = c.npops;
% talle = questdlg(['Do you want individual names to be visible in the admixture ' ...
% 'result graphics?'], 'Names visible?', 'Yes', 'No', 'Yes');
% if isequal(talle,'No')
% viewPartition2(proportionsIt, [], npops, partition, filename);
% else
% viewPartition2(proportionsIt, popnames, npops, partition, filename);
% end
% end
%--------------------------------------------------------------------------
function viewLoghood
view_loglikelihood;
function viewEnergy
view_energy;
%--------------------------------------------------------------------------
function viewGeneflow
view_geneflow;
%--------------------------------------------------------------------------
function changeColor()
h0 = findobj('Tag','base_figure');
c = uisetcolor(h0,'Change color');
h1 = findobj('Tag','datafile_text');
h2 = findobj('Tag','outputfile_text');
h3 = findobj('Tag','filename1_text');
h4 = findobj('Tag','filename2_text');
set(h1,'BackGroundColor',c);
set(h2,'BackGroundColor',c);
set(h3,'BackGroundColor',c);
set(h4,'BackGroundColor',c);
drawnow;
%-----------------------------------------------------------------------
function showmethebaps()
h0 = findobj('Tag','base_figure');
%setWindowOnTop(h0,'true')
goToDefault
h0 = findobj('Tag','load_menu');
set(h0,'UserData',[]);
%setWindowOnTop(h0,'false')
%-----------------------------------------------------------------------
function loadMixture
waitALittle;
[filename, pathname] = uigetfile('*.mat', 'Load mixture result');
%load([pathname filename],'c');
if (sum(filename)==0) || (sum(pathname)==0)
return;
end
disp('---------------------------------------------------');
disp('In loading the mixture result...');
struct_array = load([pathname filename]);
if isfield(struct_array,'c') %Matlab versio
c = struct_array.c;
if ~isfield(c,'PARTITION') || ~isfield(c,'rowsFromInd')
disp('*** ERROR: Incorrect file format');
return
end
elseif isfield(struct_array,'PARTITION') %Mideva versio
c = struct_array;
if ~isfield(c,'rowsFromInd')
disp('*** ERROR: Incorrect file format');
return
end
else
disp('*** ERROR: Incorrect file format');
return;
end
% Save gathered information to 'mixture_menu's UserData:
h0 = findobj('Tag','load_menu');
set(h0,'UserData',c);
clear c;
%Set the name of the datafile to screen.
h1 = findobj('Tag','filename1_text');
if exist('pathname')
filename = [pathname filename];
end
set(h1,'String',filename);
h1 = findobj('Tag','datafile_text');
set(h1,'String','Mixture result:');
disp('Mixture result loaded.');
goToMixtureAnalysis
%--------------------------------------------------------------------------
function goToMixtureAnalysis
set(findobj('Tag','graph_menu'), 'Enable','on');
set(findobj('Tag','partitio_menu'), 'Enable','on');
set(findobj('Tag','likelihood_menu'), 'Enable','on');
set(findobj('Tag','energy_menu'), 'Enable','on');
set(findobj('Tag','distances_menu'), 'Enable','on');
set(findobj('Tag','kl_menu'), 'Enable','on');
set(findobj('Tag','nei_menu'), 'Enable','on');
set(findobj('Tag','close_menu'), 'Enable','on');
set(findobj('Tag','phylogeny_menu'), 'Enable','on');
set(findobj('Tag','upgma_menu'), 'Enable','on');
set(findobj('Tag','nj_menu'), 'Enable','on');
set(findobj('Tag','geneflow_menu'), 'Enable','off');
set(findobj('Tag','admix_menu'), 'Enable','off');
set(findobj('Tag','mutationplot_menu'), 'Enable','on');
%--------------------------------------------------------------------------
function goToDefault
set(findobj('Tag','graph_menu'), 'Enable','off');
set(findobj('Tag','distances_menu'), 'Enable','off');
%--------------------------------------------------------------------------
function loadSpatial
% Tekee tulostiedostosta voronoi tessellaation.
waitALittle;
[filename, pathname] = uigetfile('*.mat', 'Load spatial mixture/admixture clustering');
%load([pathname filename],'c');
if (sum(filename)==0) || (sum(pathname)==0)
return;
end
struct_array = load([pathname filename]);
disp('---------------------------------------------------');
disp('In loading the spatial mixture/admixture result...');
if isfield(struct_array,'c') %Matlab versio
c = struct_array.c;
if ~isfield(c,'PARTITION') || ~isfield(c,'mixtureType')
disp('*** ERROR: Incorrect file format');
return
end
if ~strcmp(c.mixtureType,'spatial') && ~strcmp(c.mixtureType,'spatialPop')
disp('*** ERROR: Incorrect file format');
return
end
elseif isfield(struct_array,'PARTITION') %Mideva versio
c = struct_array;
if ~isfield(c,'rowsFromInd')
disp('*** ERROR: Incorrect file format');
return
end
else
disp('*** ERROR: Incorrect file format');
return;
end
if ~isfield(c, 'pointers')
disp('*** ERROR: Coordinate data missing from the result file');
return;
end
% Save gathered information to 'spatialmixture_menu's UserData:
h0 = findobj('Tag','load_menu');
set(h0,'UserData',c);
%Set the name of the datafile to screen.
h1 = findobj('Tag','filename1_text');
if exist('pathname')
filename = [pathname filename];
end
set(h1,'String',filename);
h1 = findobj('Tag','datafile_text');
if isfield(c,'admixnpops')
set(h1,'String','Spatial AdMixture Result:');
disp('Spatial admixture result loaded.');
goToSpatialAdMixtureAnalysis
else
set(h1,'String','Spatial Mixture Result:');
disp('Spatial mixture result loaded.');
goToSpatialMixtureAnalysis
end
clear c;
%--------------------------------------------------------------------------
function goToSpatialMixtureAnalysis
set(findobj('Tag','graph_menu'), 'Enable','on');
set(findobj('Tag','plot_coordinates_menu'), 'Enable','on');
set(findobj('Tag','voronoi_menu'), 'Enable','on');
set(findobj('Tag','varmuus_menu'), 'Enable','on');
set(findobj('Tag','distances_menu'), 'Enable','on');
set(findobj('Tag','kl_menu'), 'Enable','on');
set(findobj('Tag','nei_menu'), 'Enable','on');
set(findobj('Tag','close_menu'), 'Enable','on');
set(findobj('Tag','geneflow_menu'), 'Enable','off');
set(findobj('Tag','admix_menu'), 'Enable','off');
set(findobj('Tag','likelihood_menu'), 'Enable','on');
set(findobj('Tag','partitio_menu'), 'Enable','off');
%--------------------------------------------------------------------------
function goToSpatialAdMixtureAnalysis
set(findobj('Tag','graph_menu'), 'Enable','on');
set(findobj('Tag','plot_coordinates_menu'), 'Enable','on');
set(findobj('Tag','voronoi_menu'), 'Enable','on');
set(findobj('Tag','varmuus_menu'), 'Enable','on');
set(findobj('Tag','distances_menu'), 'Enable','on');
set(findobj('Tag','kl_menu'), 'Enable','on');
set(findobj('Tag','nei_menu'), 'Enable','on');
set(findobj('Tag','close_menu'), 'Enable','on');
set(findobj('Tag','geneflow_menu'), 'Enable','off');
set(findobj('Tag','admix_menu'), 'Enable','on');
set(findobj('Tag','likelihood_menu'), 'Enable','on');
set(findobj('Tag','partitio_menu'), 'Enable','off');
%--------------------------------------------------------------------------
function closeFile
h0 = findobj('Tag','load_menu');
set(h0,'UserData',[]);
h0 = findobj('Tag','datafile_text');
set(h0,'String','Data File:');
h0 = findobj('Tag','filename1_text');
set(h0,'String','');
set(findobj('Tag','close_menu'), 'Enable','off');
set(findobj('Tag','graph_menu'), 'Enable','off');
set(findobj('Tag','plot_coordinates_menu'), 'Enable','off');
set(findobj('Tag','partitio_menu'), 'Enable','off');
set(findobj('Tag','likelihood_menu'), 'Enable','off');
set(findobj('Tag','admix_menu'), 'Enable','off');
set(findobj('Tag','geneflow_menu'), 'Enable','off');
set(findobj('Tag','voronoi_menu'), 'Enable','off');
set(findobj('Tag','varmuus_menu'), 'Enable','off');
set(findobj('Tag','distances_menu'), 'Enable','off');
set(findobj('Tag','kl_menu'), 'Enable','off');
set(findobj('Tag','nei_menu'), 'Enable','off');
%-----------------------------------------------------------------------
function loadAdmixture
waitALittle;
[filename, pathname] = uigetfile('*.mat', 'Load admixture results.');
if (sum(filename)==0) || (sum(pathname)==0)
return;
end
%load([pathname filename],'c');
disp('---------------------------------------------------');
disp('In loading the admixture result...');
struct_array = load([pathname filename]);
if isfield(struct_array,'c') %Matlab versio
c = struct_array.c;
if ~isfield(c,'proportionsIt')
disp('*** ERROR: Incorrect file format');
return
end
elseif isfield(struct_array,'proportionsIt') %Mideva versio
c = struct_array;
if ~isfield(c,'proportionsIt')
disp('*** ERROR: Incorrect file format');
return
end
elseif isfield(struct_array,'tietue')
c = struct_array.tietue;
if ~isfield(c,'proportionsIt')
disp('*** ERROR: Incorrect file format');
return
end
else
disp('*** ERROR: Incorrect file format');
return;
end
% Save gathered information to 'mixture_menu's UserData:
h0 = findobj('Tag','load_menu');
set(h0,'UserData',c);
clear c;
%Set the name of the datafile to screen.
h1 = findobj('Tag','filename1_text');
if exist('pathname')
filename = [pathname filename];
end
set(h1,'String',filename);
h1 = findobj('Tag','datafile_text');
set(h1,'String','Admixture result:');
disp('Admixture result loaded.');
goToAdmixtureAnalysis
%--------------------------------------------------------------------------
function goToAdmixtureAnalysis
set(findobj('Tag','graph_menu'), 'Enable','on');
set(findobj('Tag','admix_menu'), 'Enable','on');
set(findobj('Tag','geneflow_menu'), 'Enable','on');
% set(findobj('Tag','distances_menu'), 'Enable','on');
% set(findobj('Tag','kl_menu'), 'Enable','on');
% set(findobj('Tag','nei_menu'), 'Enable','on');
set(findobj('Tag','close_menu'), 'Enable','on');
% set(findobj('Tag','likelihood_menu'), 'Enable','on');
%--------------------------------------------------------------------------
function calculateDis(type)
if exist('baps4_output.baps','file')
delete('baps4_output.baps')
else
diary('baps4_output.baps')
end
h0 = findobj('Tag','load_menu');
c = get(h0,'UserData');
npops = c.npops;
COUNTS = c.COUNTS;
adjprior = c.adjprior;
data = c.data;
partition = c.PARTITION;
clear c;
if npops > 1
dist_mat = zeros(npops, npops);
maxnoalle = size(COUNTS,1);
nloci = size(COUNTS,2);
d = zeros(maxnoalle, nloci, npops);
switch type
case 'KL'
prior = adjprior;
prior(find(prior==1))=0;
nollia = find(all(prior==0)); %Lokukset, joissa oli havaittu vain yht?alleelia.
prior(1,nollia)=1;
for pop1 = 1:npops
d(:,:,pop1) = (squeeze(COUNTS(:,:,pop1))+prior) ./ repmat(sum(squeeze(COUNTS(:,:,pop1))+prior),maxnoalle,1);
%dist1(pop1) = (squeeze(COUNTS(:,:,pop1))+adjprior) ./ repmat((SUMCOUNTS(pop1,:)+adjprior), maxnoalle, 1);
end
ekarivi = num2str(npops);
disp('--------------------------------------');
disp('KL-divergence matrix in PHYLIP format:');
disp('--------------------------------------');
disp(ekarivi);
for pop1 = 1:npops
% rivi = [blanks(2-floor(log10(pop1))) num2str(pop1) ' '];
for pop2 = 1:pop1-1
dist1 = d(:,:,pop1); dist2 = d(:,:,pop2);
div12 = sum(sum(dist1.*log2((dist1+10^-10) ./ (dist2+10^-10))))/nloci;
div21 = sum(sum(dist2.*log2((dist2+10^-10) ./ (dist1+10^-10))))/nloci;
div = (div12+div21)/2;
dist_mat(pop1,pop2) = div;
end
end
case 'Nei'
for pop1 = 1:npops
d(:,:,pop1) = (squeeze(COUNTS(:,:,pop1))) ./ repmat(sum(squeeze(COUNTS(:,:,pop1))),maxnoalle,1);
%dist1(pop1) = (squeeze(COUNTS(:,:,pop1))+adjprior) ./ repmat((SUMCOUNTS(pop1,:)+adjprior), maxnoalle, 1);
end
ekarivi = num2str(npops);
disp('--------------------------------------');
disp('Nei-divergence matrix in PHYLIP format:');
disp('--------------------------------------');
disp(ekarivi);
for pop1 = 1:npops
% rivi = [blanks(2-floor(log10(pop1))) num2str(pop1) ' '];
for pop2 = 1:pop1-1
dist1 = d(:,:,pop1); dist2 = d(:,:,pop2);
div1 = sum(sum(dist1.*dist2));
div2 = sqrt(sum(sum(dist1.^2)))*sqrt(sum(sum(dist2.^2)));
div = -log(div1/div2);
dist_mat(pop1,pop2) = div;
end
end
case 'Hamming'
ekarivi = num2str(npops);
disp('--------------------------------------');
disp('Hamming distance matrix in PHYLIP format:');
disp('--------------------------------------');
disp(ekarivi);
for pop1 = 1:npops
for pop2 = 1:pop1-1
dist_mat(pop1,pop2) = hamming_dist(data(logical(partition==pop1),[1:end-1]),...
data(logical(partition==pop2),[1:end-1]));
end
end
end
end
dist_mat = dist_mat + dist_mat'; % make it symmetric
for pop1 = 1:npops
rivi = ['Cluster_' num2str(pop1) ' '];
for pop2 = 1:npops
rivi = [rivi kldiv2str(dist_mat(pop1,pop2)) ' '];
end
disp(rivi);
end
diary off
% ---------------------------------------------------------------------
% Save the result.
% Jing - 26.12.2005
talle = questdlg(['Do you want to save the distance matrix in PHYLIP format? '], ...
'Save distance matrix?','Yes','No','Yes');
if isequal(talle,'Yes')
%%%waitALittle;
[filename, pathname] = uiputfile('*.txt','Save results as');
if (sum(filename)==0) || (sum(pathname)==0)
% Cancel was pressed
return
else % copy 'baps4_output.baps' into the text file with the same name.
if exist('baps4_output.baps','file')
copyfile('baps4_output.baps',[pathname filename])
delete('baps4_output.baps')
end
end
else
delete('baps4_output.baps')
end
% -------------------------------------------------------------------------
function mjono = kldiv2str(div)
mjono = ' ';
if abs(div)<100
%Ei tarvita e-muotoa
mjono(6) = num2str(rem(floor(div*1000),10));
mjono(5) = num2str(rem(floor(div*100),10));
mjono(4) = num2str(rem(floor(div*10),10));
mjono(3) = '.';
mjono(2) = num2str(rem(floor(div),10));
arvo = rem(floor(div/10),10);
if arvo>0
mjono(1) = num2str(arvo);
end
else
suurinYks = floor(log10(div));
mjono(6) = num2str(suurinYks);
mjono(5) = 'e';
mjono(4) = palautaYks(abs(div),suurinYks-1);
mjono(3) = '.';
mjono(2) = palautaYks(abs(div),suurinYks);
end
% -------------------------------------------------------------------------
function dist = hamming_dist(data1,data2)
[length1,nloci] = size(data1);
length2 = size(data2,1);
dist1 = 0;
for i = 1:length1
dist2 = 0;
for j = 1:length2
dist2 = dist2 + sum(data1(i,:)~=data2(j,:))/nloci;
end
dist1 = dist1 + dist2/length2;
end
dist = dist1/length1;
%--------------------------------------------------------------------------
function digit = palautaYks(num,yks)
% palauttaa luvun num 10^yks termin kertoimen
% string:in?
% yks täytyy olla kokonaisluku, joka on
% vähintään -1:n suuruinen. Pienemmill?
% luvuilla tapahtuu jokin pyöristysvirhe.
if yks>=0
digit = rem(num, 10^(yks+1));
digit = floor(digit/(10^yks));
else
digit = num*10;
digit = floor(rem(digit,10));
end
digit = num2str(digit);

377
matlab/general/baps6.m Normal file
View file

@ -0,0 +1,377 @@
function baps5(varargin)
% This is the machine-generated representation of a Handle Graphics object
% and its children. Note that handle values may change when these objects
% are re-created. This may cause problems with any callbacks written to
% depend on the value of the handle at the time the object was saved.
%
% To reopen this object, just type the name of the M-file at the MATLAB
% prompt. The M-file and its associated MAT-file must be on your path.
% NEW: script version was added. 09.07.2007
% Script function has been added by Lu Cheng, 11.03.2010
% The script function is designed for semi-supervised clustering in the
% trained clustering module, it adopts a codon linkage model for the DNA
% sequence data
% The calling command: baps5 -semi script_file
global PARAMETERS; PARAMETERS = [];
global SCRIPT_MODE; SCRIPT_MODE = [];
if nargin == 1 % script version
readScript(varargin{1});
return
else if nargin==2
%----------------added by Lu Cheng, 11.03.2010
if isequal(varargin{1},'-semi');
script_file = varargin{2};
PARAMETERS = semiReadScript(script_file);
SCRIPT_MODE = true;
trainedMix
SCRIPT_MODE = [];
PARAMETERS = [];
else
disp(cat(2,'Unknown option: ',varargin{1}));
end
return
%---------------------------------------------
end
end
% load baps4
% Base frame
h0 = figure('Color',[0.8 0.8 0.8], ...
'MenuBar','none', ...
'Position',[364 175 750 500], ...
'Resize','on', ...
'Tag','base_figure',...
'Name','Bayesian Analysis of Population Structure',...
'NumberTitle','off',...
'Color',[.7 .9 .7]);
% File menu
h1 = uimenu('Parent',h0, ...
'Label','File', ...
'Tag','file_menu');
h2 = uimenu('Parent',h1, ...
'Label','Load Result', ...
'Tag','load_menu');
h3 = uimenu('Parent',h2, ...
'Callback','baps4cbf load_mixture_menu', ...
'Label','Mixture result', ...
'Tag','mixture_menu');
h3 = uimenu('Parent',h2, ...
'Callback','baps4cbf load_spatial_menu', ...
'Label','Spatial mixture result', ...
'Tag','spatialmixture_menu');
h3 = uimenu('Parent',h2, ...
'Callback','baps4cbf load_admixture_menu', ...
'Label','Admixture result', ...
'Tag','admixture_menu');
h2 = uimenu('Parent',h1, ...
'Enable','on',...
'Label','Compare Results', ...
'Tag','compare_menu');
h3 = uimenu('Parent',h2, ...
'Callback','baps4cbf compare_menu', ...
'Label','Mixture results', ...
'Tag','compare_menu');
h3 = uimenu('Parent',h2, ...
'Callback','baps4cbf compare_admix_menu', ...
'Label','AdMixture results', ...
'Tag','compare_admix_menu');
h2 = uimenu('Parent',h1, ...
'Enable','off',...
'Callback','baps4cbf close_menu', ...
'Label','Close Results', ...
'Tag','close_menu');
h2 = uimenu('Parent',h1, ...
'Label','Output File', ...
'Tag','output_menu');
h3 = uimenu('Parent',h2, ...
'Callback','baps4cbf output_menu', ...
'Label','Set', ...
'Tag','set_menu');
h3 = uimenu('Parent',h2, ...
'Callback','baps4cbf remove_outputfile_menu', ...
'Label','Remove', ...
'Tag','remove_menu');
h2 = uimenu('Parent',h1, ...
'Callback','baps4cbf exit_menu', ...
'Label','Exit', ...
'Tag','exit_menu');
% Distances menu
h1 = uimenu('Parent',h0, ...
'Enable','off',...
'Label','Distances', ...
'Tag','distances_menu');
h2 = uimenu('Parent',h1, ...
'Callback','baps4cbf calculate_kl', ...
'Label','KL distance', ...
'Tag','kl_menu');
h2 = uimenu('Parent',h1, ...
'Callback','baps4cbf calculate_nei', ...
'Label','Nei distance', ...
'Tag','nei_menu');
h2 = uimenu('Parent',h1, ...
'Callback','baps4cbf calculate_hamming', ...
'Label','Hamming distance', ...
'Tag','hamming_menu');
% Graph menu
h1 = uimenu('Parent',h0, ...
'Enable','off', ...
'Label','Graph', ...
'Tag','graph_menu');
h2 = uimenu('Parent',h1, ...
'Enable','off', ...
'Callback','baps4cbf plot_coordinates_menu', ...
'Label','Plot Coordinates', ...
'Tag','plot_coordinates_menu');
h2 = uimenu('Parent',h1, ...
'Enable','off', ...
'Callback','baps4cbf partitio_menu', ...
'Label','View Partition', ...
'Tag','partitio_menu');
h2 = uimenu('Parent',h1, ...
'Enable','off', ...
'Callback','baps4cbf admix_menu', ...
'Label','View Admixture Results', ...
'Tag','admix_menu');
h2 = uimenu('Parent',h1, ...
'Enable','off', ...
'Callback','baps4cbf likelihood_menu', ...
'Label','Changes of Log Likelihood', ...
'Tag','likelihood_menu');
h2 = uimenu('Parent',h1, ...
'Enable','off', ...
'Callback','baps4cbf energy_menu', ...
'Label','Energy landscape', ...
'Tag','energy_menu');
h2 = uimenu('Parent',h1, ...
'Enable','off', ...
'Callback','baps4cbf geneflow_menu', ...
'Label','Plot Gene Flow', ...
'Tag','geneflow_menu');
h2 = uimenu('Parent',h1, ...
'Enable','off', ...
'Callback','baps4cbf voronoi_menu', ...
'Label','Voronoi Tessellation', ...
'Tag','voronoi_menu');
h2 = uimenu('Parent',h1, ...
'Enable','off', ...
'Callback','baps4cbf varmuus_menu', ...
'Label','Local Uncertainty', ...
'Tag','varmuus_menu');
h2 = uimenu('Parent',h1, ...
'Enable','off', ...
'Callback','baps4cbf phylogeny_menu', ...
'Label','Phylogeny', ...
'Tag','phylogeny_menu');
h3 = uimenu('Parent',h2, ...
'Enable','off', ...
'Callback','baps4cbf upgma_menu',...
'Label', 'UPGMA', ...
'Tag','upgma_menu');
h3 = uimenu('Parent',h2, ...
'Enable','off', ...
'Callback','baps4cbf nj_menu',...
'Label', 'Neighbor-Joining', ...
'Tag','nj_menu');
h2 = uimenu('Parent',h1, ...
'Enable','off', ...
'Callback','baps4cbf mutationplot_menu', ...
'Label','Mutation Plot', ...
'Tag','mutationplot_menu');
% Tools menu
h1 = uimenu('Parent',h0, ...
'Label','Tools', ...
'Tag','tools_menu');
h2 = uimenu('Parent',h1, ...
'Callback','baps4cbf fixk_menu', ...
'Label','Enable Fixed-K Clustering', ...
'Tag','fixk_menu', ...
'Userdata', 0);
h2 = uimenu('Parent',h1, ...
'Callback','baps4cbf partitioncompare_menu', ...
'Label','Partition Compare', ...
'Tag','partitioncompare_menu', ...
'Userdata', []);
h2 = uimenu('Parent',h1, ...
'Callback','baps4cbf loadfigure_menu', ...
'Label','Load Figure', ...
'Tag','loadfigure_menu');
h2 = uimenu('Parent',h1, ...
'Callback','baps4cbf changecolor_menu',...
'Label', 'Change BAPS Color', ...
'Tag','changecolor_menu');
% Help menu
h1 = uimenu('Parent',h0, ...
'Label','Help', ...
'Tag','help_menu');
h2 = uimenu('Parent',h1, ...
'Callback','baps4cbf helpdoc', ...
'Enable','on', ...
'Label','Help contents (doc)', ...
'Tag','helpman_menu');
h2 = uimenu('Parent',h1, ...
'Callback','baps4cbf helponline', ...
'Enable','on', ...
'Label','BAPS on the web', ...
'Tag','online_menu');
h2 = uimenu('Parent',h1, ...
'Callback','baps4cbf about', ...
'Enable','on', ...
'Label','About', ...
'Tag','about_menu');
% uicontrol
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'BackgroundColor',[0.82 0.82 0.77], ...
'ListboxTop',0, ...
'Position',[38.25 154.268575851393 381 148.721320743034], ...
'Style','frame', ...
'Tag','mix_frame');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'BackgroundColor',[0.82 0.82 0.77], ...
'ListboxTop',0, ...
'Position',[38.25 56 381 79.721320743034], ...
'Style','frame', ...
'Tag','admix_frame');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'BackgroundColor',[0.82 0.82 0.77], ...
'ListboxTop',0, ...
'Position',[156.75 279.545624148607 158 11.9465944272446], ...
'String','Population mixture analysis', ...
'Style','text', ...
'Tag','mix_text');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'BackgroundColor',[0.82 0.82 0.77], ...
'ListboxTop',0, ...
'Position',[156.75 111.545624148607 138 11.9465944272446], ...
'String','Population admixture analysis', ...
'Style','text', ...
'Tag','admix_text');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'Callback','baps4cbf mix1_button', ...
'ListboxTop',0, ...
'Position',[51.75 245.412497213622 163.5 22.7554179566563], ...
'String','Clustering of individuals', ...
'Tag','mix1_button');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'Callback','baps4cbf mix2_button', ...
'ListboxTop',0, ...
'Position',[51.75 212.75 163.5 23.25], ...
'String','Clustering of groups of individuals', ...
'Tag','mix2_button');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'Callback','baps4cbf trained_button', ...
'ListboxTop',0, ...
'Position',[51.75 178.284055727554 163.5 22.7554179566563], ...
'String','Trained clustering', ...
'Tag','trained_button');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'Callback','baps4cbf admix1_button', ...
'ListboxTop',0, ...
'Position',[51.7 75.412497213622 163.5 22.7554179566563], ...
'String','Admixture based on mixture clustering', ...
'Tag','admix1_button');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'Callback','baps4cbf admix2_button', ...
'ListboxTop',0, ...
'Position',[245.75 75.412497213622 163.5 22.7554179566563], ...
'String','Admixture based on pre-defined populations', ...
'Tag','admix2_button');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'BackgroundColor',[.7 .9 .7], ...
'FontSize',10, ...
'HorizontalAlignment','left', ...
'ListboxTop',0, ...
'Position',[36 28.5 100.75 14.25], ...
'String','Data File:', ...
'Style','text', ...
'Tag','datafile_text');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'BackgroundColor',[.7 .9 .7], ...
'FontSize',10, ...
'HorizontalAlignment','left', ...
'ListboxTop',0, ...
'Position',[36 9.75 51 14.25], ...
'String','Output File:', ...
'Style','text', ...
'Tag','outputfile_text');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'BackgroundColor',[.7 .9 .7], ...
'FontSize',10, ...
'HorizontalAlignment','left', ...
'ListboxTop',0, ...
'Position',[140.75 28.5 314.5 14.25], ...
'Style','text', ...
'Tag','filename1_text');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'BackgroundColor',[.7 .9 .7], ...
'FontSize',10, ...
'HorizontalAlignment','left', ...
'ListboxTop',0, ...
'Position',[93.75 9.75 314.5 14.25], ...
'Style','text', ...
'Tag','filename2_text');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'Callback','baps4cbf spatial_button', ...
'ListboxTop',0, ...
'Position',[245.75 245.412497213622 163.5 22.7554179566563], ...
'String','Spatial clustering of individuals', ...
'Tag','spatial_button');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'Callback','baps4cbf spatial2_button', ...
'ListboxTop',0, ...
'Position',[245.75 212.75 163.5 23.25], ...
'String','Spatial clustering of groups', ...
'Tag','spatial2_button');
h1 = uicontrol('Parent',h0, ...
'Units','points', ...
'Callback','baps4cbf linkage_button', ...
'ListboxTop',0, ...
'Position',[245.75 178.284055727554 163.5 23.25], ...
'String','Clustering with linked loci', ...
'Tag','linkage_button');
% Starting text in the log window:
disp('**********************************************************');
disp('********************** BAPS 6.0 *************************');
disp('**********************************************************');
disp(' ');
disp('Closing this window will end the execution of the program.');
disp('However, it is recommended that you use ''Exit'' on the ''File''');
disp('menu of the main window or use the close-button in the upper');
disp('right-hand corner of the main window to exit the program.');
disp(' ');
if strcmp(computer,'PCWIN') || strcmp(computer,'PCWIN64')
if nargout > 0, fig = h0; end
drawnow
% seticon(h0, ['baps5.ico']);
end
% uimenufcn(gcf,'WindowCommandWindow')

46
matlab/general/distance.m Normal file
View file

@ -0,0 +1,46 @@
function d = distance(a,b)
% DISTANCE - computes Euclidean distance matrix
%
% E = distance(A,B)
%
% A - (DxM) matrix
% B - (DxN) matrix
%
% Returns:
% E - (MxN) Euclidean distances between vectors in A and B
%
%
% Description :
% This fully vectorized (VERY FAST!) m-file computes the
% Euclidean distance between two vectors by:
%
% ||A-B|| = sqrt ( ||A||^2 + ||B||^2 - 2*A.B )
%
% Example :
% A = rand(400,100); B = rand(400,200);
% d = distance(A,B);
% Author : Roland Bunschoten
% University of Amsterdam
% Intelligent Autonomous Systems (IAS) group
% Kruislaan 403 1098 SJ Amsterdam
% tel.(+31)20-5257524
% bunschot@wins.uva.nl
% Last Rev : Oct 29 16:35:48 MET DST 1999
% Tested : PC Matlab v5.2 and Solaris Matlab v5.3
% Thanx : Nikos Vlassis
% Copyright notice: You are free to modify, extend and distribute
% this code granted that the author of the original code is
% mentioned as the original author of the code.
if (nargin ~= 2)
error('Not enough input arguments');
end
if (size(a,1) ~= size(b,1))
error('A and B should be of same dimensionality');
end
aa=sum(a.*a,1); bb=sum(b.*b,1); ab=a'*b;
d = sqrt(abs(repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab));

View file

@ -0,0 +1,14 @@
%-------------------------------------------------------------------------
function fixedK = fixKWarning()
% The function is to ask further confirmation of running fixed K clustering
button = questdlg('You have selected a clustering analysis with the Fixed-K Mode. Are you sure to continue?',...
'Fixed-K Mode');
switch button
case 'Yes'
fixedK = 1;
case 'No'
fixedK = 0;
goToFixedK
case 'Cancel'
fixedK = 0.5;
end

View file

@ -0,0 +1,28 @@
%-------------------------------------------------------------------------
function goToFixedK
% The function to do fix K algorithm
h0 = findobj('Tag','fixk_menu');
h1 = findobj('Tag','mix_text');
old = get(h0, 'UserData');
if old == 0
set(h0,'UserData',1, 'label', 'Disable Fixed-K Clustering');
set(h1,'String', 'Population mixture analysis (Fixed-K Mode)');
% disable all the non-relevant buttons
set(findobj('Tag','partitioncompare_menu'),'Enable','off');
% set(findobj('Tag','file_menu'),'Enable','off');
% set(findobj('Tag','admix_text'),'Enable','off');
% set(findobj('Tag','admix1_button'),'Enable','off');
% set(findobj('Tag','admix2_button'),'Enable','off');
disp('Fixed-K Mode is enabled.');
else
set(h0,'UserData',0, 'label', 'Enable Fixed-K Clustering');
set(h1,'String', 'Population mixture analysis');
set(findobj('Tag','partitioncompare_menu'),'Enable','on');
% set(findobj('Tag','file_menu'),'Enable','on');
% set(findobj('Tag','admix_text'),'Enable','on');
% set(findobj('Tag','admix1_button'),'Enable','on');
% set(findobj('Tag','admix2_button'),'Enable','on');
disp('Fixed-K Mode is disabled.');
end

View file

@ -0,0 +1,138 @@
function goToPartitionCompare
% GOTOPARTITIONCOMPARE goes to the partition comaparing mode
% Load the partition result
[filename, pathname] = uigetfile('*.*', 'Load the priori specified partitions');
if (sum(filename)==0) || (sum(pathname)==0)
return;
end
disp('---------------------------------------------------');
disp('In loading the partition result...');
try
c = load([pathname filename]);
catch
fprintf(1,'***ERROR: incorrect partition result.\n');
return
end
if sum(c(1,:))~=1
fprintf(1,'***ERROR: invalid prior density.\n');
return
else
prior = c(1,:);
c = c([2:end],:);
end
[ninds, npartitions] = size(c);
fprintf(1,'# of sampling units: %d\n', ninds);
fprintf(1,'# of partitions in comparision: %d\n', npartitions);
h1 = findobj('Tag','partitioncompare_menu');
% Choose data type and model type
items(1).name = 'Model:';
items(1).default = 1;
items(1).indent = 1;
items(1).values = {'Independent';'Spatial';'Linkage'};
items(1).linked = [2 3 4];
items(2).name = 'Data type';
items(2).indent = 1;
items(2).values = {1};
items(3).name = 'individual level';
items(3).default = 1;
items(3).exclusive = 4;
items(3).indent = 2;
items(4).name = 'group level';
items(4).default = 0;
items(4).exclusive = 3;
items(4).indent = 2;
title = 'Specify data and model types';
out = CSEFlagDialog1(items, title);
if isempty(out)
disp(['cancelled.']);
return
end
userdata.partitions = c;
userdata.logmls = [];
set(h1,'UserData',userdata);
try
if out(1).answer == 1
if out(3).answer == 1 % independent model with individual level
disp(['Model: Independent clustering - Individual level']);
greedyMix(-1);
else % independent model with group level
disp(['Model: Independent clustering - Group level']);
greedyPopMix();
end
elseif out(1).answer == 2
if out(3).answer == 1 % spatial model with individual level
disp(['Model: Spatial clustering - Individual level']);
spatialMixture;
else
disp(['Model: Spatial clustering - Group level']);
spatialPopMixture;
end
elseif out(1).answer == 3
disp(['Model: Linkage clustering']);
linkageMixture_speed;
end
userdata = get(h1,'UserData');
logmls = userdata.logmls;
if isempty(logmls)
disp(['*** ERROR: program stopped.']);
set(findobj('Tag','filename1_text'),'String',[]);
else
diary('baps5_partitioncompare.out');
disp('---------------------------------------------------');
disp(['Partition Prior LogLikelihood Posterior']);
posterior = zeros(1, npartitions);
sum_posterior = exp(logmls)*prior';
if sum_posterior == 0 % meaning that one partition dominates
dominate_partition = find(logmls==max(logmls));
posterior(dominate_partition) = 1;
else
for i = 1:npartitions
posterior(i) = exp(userdata.logmls(i))*prior(i)/sum_posterior;
end
end
for i = 1:npartitions
disp([' ' ownNum2Str(i) ' ' ownNum2Str(prior(i)) ' ' ...
ownNum2Str(logmls(i)) ' ' ownNum2Str(posterior(i))]);
end
diary off
save_preproc = questdlg('Do you wish to save the partition compare result?',...
'Save result?',...
'Yes','No','Yes');
if isequal(save_preproc,'Yes');
waitALittle;
[filename, pathname] = uiputfile('*.txt','Save result as');
if (sum(filename)==0) || (sum(pathname)==0)
% Cancel was pressed
return;
else
% copy 'baps4_output.baps' into the text file with the same name.
if exist('baps5_partitioncompare.out','file')
copyfile('baps5_partitioncompare.out',[pathname filename])
delete('baps5_partitioncompare.out')
disp('result saved.');
else
disp('*** ERROR: result cannot be saved.');
end
end;
end
end
catch
disp('*** ERROR: incorrect format. Check model and data types');
end
set(h1,'UserData',[]);

18
matlab/general/iconn.m Normal file
View file

@ -0,0 +1,18 @@
function iconn
% Change the icon of all open figures to match the figure number
%
% iconn
%
% See also: seticon
%
% In order to have this feature automatically on for all new figures
% execute the following command:
% set(0,'defaultfigurecreatefcn','iconn')
% You may want to insert it into your startup.m file
% Copyright 2000-2002, Research and Development
h = get(0,'children');
for i=1:min(length(h), 9)
seticon(i, which(sprintf('icon%d.ico', i)))
end

67
matlab/general/imageCbf.m Normal file
View file

@ -0,0 +1,67 @@
function imageCbf(action)
%Tahan funktioon ohjataan image_figuren callback:it.
switch action
case 'save_image'
saveImage;
case 'export_bmp'
export('bmp');
case 'export_jpg'
export('jpg');
end
function saveImage
%Saves information needed to reconstruct the image later.
[filename,pathname] = uiputfile('*.mat','Save Figure');
if (filename == 0) & (pathname == 0)
%Cancel was clicked.
return;
end;
image_file_name = [pathname filename];
tiedot = get(gcbf,'UserData');
% tiedot on tietue, joka sisältää info:n ja popnames:in
% save(image_file_name,'tiedot');
save(image_file_name,'tiedot','-v7.3'); % added by Lu Cheng, 08.06.2012
%-------------------------------------------------------------------
function export(format)
%Saves a figure in a format which has been given
%as a parameter. Exported images cannot be opened using BAPS.
[filename,pathname] = uiputfile(['*.' format], ['Export to ' format]);
if (filename == 0) & (pathname == 0)
%Cancel was pressed:
return;
end;
filename = checkTheFormat(format,filename);
resultfilename = [pathname filename];
print(resultfilename);
%---------------------------------------------------------
function newfilename = checkTheFormat(format,oldfilename)
%Checks if the 'oldfilename' has ending *.'format'. If not, ending
%will be added to newfilename.
if length(oldfilename) < 4
newfilename = [oldfilename '.' format];
elseif isequal(oldfilename(end-3: end), ['.' format])
newfilename = oldfilename;
elseif any(oldfilename == '.')
n = 1;
while ~isequal(oldfilename(n),'.')
n = n+1;
end;
newfilename = [oldfilename(1:n) format];
else
newfilename = [oldfilename '.' format];
end;

View file

@ -0,0 +1,38 @@
function fig = image_figure()
% This is the machine-generated representation of a Handle Graphics object
% and its children. Note that handle values may change when these objects
% are re-created. This may cause problems with any callbacks written to
% depend on the value of the handle at the time the object was saved.
%
% To reopen this object, just type the name of the M-file at the MATLAB
% prompt. The M-file and its associated MAT-file must be on your path.
load image_figure
h0 = figure('Color',[0.8 0.8 0.8], ...
'Colormap',mat0, ...
'MenuBar','none', ...
'NumberTitle','off', ...
'PointerShapeCData',mat1, ...
'Position',[73 27 896 672], ...
'Resize','on', ...
'Tag','image_figure');
h1 = uimenu('Parent',h0, ...
'Label','File', ...
'Tag','image_fig_file_menu');
h2 = uimenu('Parent',h1, ...
'Callback','imageCbf save_image', ...
'Label','Save Figure', ...
'Tag','save_image_menu');
h2 = uimenu('Parent',h1, ...
'Label','Export', ...
'Tag','export_image_menu');
h3 = uimenu('Parent',h2, ...
'Callback','imageCbf export_jpg', ...
'Label','*.jpg', ...
'Tag','jpg_menu');
h3 = uimenu('Parent',h2, ...
'Callback','imageCbf export_bmp', ...
'Label','*.bmp', ...
'Tag','bmp_menu');
if nargout > 0, fig = h0; end

178
matlab/general/kstest2.m Normal file
View file

@ -0,0 +1,178 @@
function [H, pValue, KSstatistic] = kstest2(x1, x2, alpha, tail)
%KSTEST2 Two-sample Kolmogorov-Smirnov goodness-of-fit hypothesis test.
% H = KSTEST2(X1,X2,ALPHA,TAIL) performs a Kolmogorov-Smirnov (K-S) test
% to determine if independent random samples, X1 and X2, are drawn from
% the same underlying continuous population. ALPHA and TAIL are optional
% scalar inputs: ALPHA is the desired significance level (default = 0.05);
% TAIL indicates the type of test (default = 0). H indicates the result of
% the hypothesis test:
% H = 0 => Do not reject the null hypothesis at significance level ALPHA.
% H = 1 => Reject the null hypothesis at significance level ALPHA.
%
% Let S1(x) and S2(x) be the empirical distribution functions from the
% sample vectors X1 and X2, respectively, and F1(x) and F2(x) be the
% corresponding true (but unknown) population CDFs. The two-sample K-S
% test tests the null hypothesis that F1(x) = F2(x) for all x, against the
% alternative specified by TAIL:
% 'unequal' -- "F1(x) not equal to F2(x)" (two-sided test)
% 'larger' -- "F1(x) > F2(x)" (one-sided test)
% 'smaller' -- "F1(x) < F2(x)" (one-sided test)
%
% For TAIL = 'unequal', 'larger', and 'smaller', the test statistics are
% max|S1(x) - S2(x)|, max[S1(x) - S2(x)], and max[S2(x) - S1(x)],
% respectively.
%
% The decision to reject the null hypothesis occurs when the significance
% level, ALPHA, equals or exceeds the P-value.
%
% X1 and X2 are vectors of lengths N1 and N2, respectively, and represent
% random samples from some underlying distribution(s). Missing
% observations, indicated by NaNs (Not-a-Number), are ignored.
%
% [H,P] = KSTEST2(...) also returns the asymptotic P-value P.
%
% [H,P,KSSTAT] = KSTEST2(...) also returns the K-S test statistic KSSTAT
% defined above for the test type indicated by TAIL.
%
% The asymptotic P-value becomes very accurate for large sample sizes, and
% is believed to be reasonably accurate for sample sizes N1 and N2 such
% that (N1*N2)/(N1 + N2) >= 4.
%
% See also KSTEST, LILLIETEST, CDFPLOT.
%
% Copyright 1993-2007 The MathWorks, Inc.
% $Revision: 1.5.2.5 $ $ Date: 1998/01/30 13:45:34 $
% References:
% Massey, F.J., (1951) "The Kolmogorov-Smirnov Test for Goodness of Fit",
% Journal of the American Statistical Association, 46(253):68-78.
% Miller, L.H., (1956) "Table of Percentage Points of Kolmogorov Statistics",
% Journal of the American Statistical Association, 51(273):111-121.
% Stephens, M.A., (1970) "Use of the Kolmogorov-Smirnov, Cramer-Von Mises and
% Related Statistics Without Extensive Tables", Journal of the Royal
% Statistical Society. Series B, 32(1):115-122.
% Conover, W.J., (1980) Practical Nonparametric Statistics, Wiley.
% Press, W.H., et. al., (1992) Numerical Recipes in C, Cambridge Univ. Press.
if nargin < 2
error('stats:kstest2:TooFewInputs','At least 2 inputs are required.');
end
%
% Ensure each sample is a VECTOR.
%
if ~isvector(x1) || ~isvector(x2)
error('stats:kstest2:VectorRequired','The samples X1 and X2 must be vectors.');
end
%
% Remove missing observations indicated by NaN's, and
% ensure that valid observations remain.
%
x1 = x1(~isnan(x1));
x2 = x2(~isnan(x2));
x1 = x1(:);
x2 = x2(:);
if isempty(x1)
error('stats:kstest2:NotEnoughData', 'Sample vector X1 contains no data.');
end
if isempty(x2)
error('stats:kstest2:NotEnoughData', 'Sample vector X2 contains no data.');
end
%
% Ensure the significance level, ALPHA, is a scalar
% between 0 and 1 and set default if necessary.
%
if (nargin >= 3) && ~isempty(alpha)
if ~isscalar(alpha) || (alpha <= 0 || alpha >= 1)
error('stats:kstest2:BadAlpha',...
'Significance level ALPHA must be a scalar between 0 and 1.');
end
else
alpha = 0.05;
end
%
% Ensure the type-of-test indicator, TAIL, is a scalar integer from
% the allowable set, and set default if necessary.
%
if (nargin >= 4) && ~isempty(tail)
if ischar(tail)
tail = strmatch(lower(tail), {'smaller','unequal','larger'}) - 2;
if isempty(tail)
error('stats:kstest2:BadTail',...
'Type-of-test indicator TAIL must be ''unequal'', ''smaller'', or ''larger''.');
end
elseif ~isscalar(tail) || ~((tail==-1) || (tail==0) || (tail==1))
error('stats:kstest2:BadTail',...
'Type-of-test indicator TAIL must be ''unequal'', ''smaller'', or ''larger''.');
end
else
tail = 0;
end
%
% Calculate F1(x) and F2(x), the empirical (i.e., sample) CDFs.
%
binEdges = [-inf ; sort([x1;x2]) ; inf];
binCounts1 = histc (x1 , binEdges, 1);
binCounts2 = histc (x2 , binEdges, 1);
sumCounts1 = cumsum(binCounts1)./sum(binCounts1);
sumCounts2 = cumsum(binCounts2)./sum(binCounts2);
sampleCDF1 = sumCounts1(1:end-1);
sampleCDF2 = sumCounts2(1:end-1);
%
% Compute the test statistic of interest.
%
switch tail
case 0 % 2-sided test: T = max|F1(x) - F2(x)|.
deltaCDF = abs(sampleCDF1 - sampleCDF2);
case -1 % 1-sided test: T = max[F2(x) - F1(x)].
deltaCDF = sampleCDF2 - sampleCDF1;
case 1 % 1-sided test: T = max[F1(x) - F2(x)].
deltaCDF = sampleCDF1 - sampleCDF2;
end
KSstatistic = max(deltaCDF);
%
% Compute the asymptotic P-value approximation and accept or
% reject the null hypothesis on the basis of the P-value.
%
n1 = length(x1);
n2 = length(x2);
n = n1 * n2 /(n1 + n2);
lambda = max((sqrt(n) + 0.12 + 0.11/sqrt(n)) * KSstatistic , 0);
if tail ~= 0 % 1-sided test.
pValue = exp(-2 * lambda * lambda);
else % 2-sided test (default).
%
% Use the asymptotic Q-function to approximate the 2-sided P-value.
%
j = (1:101)';
pValue = 2 * sum((-1).^(j-1).*exp(-2*lambda*lambda*j.^2));
pValue = min(max(pValue, 0), 1);
end
H = (alpha >= pValue);

View file

@ -0,0 +1,67 @@
function mjono = logml2String(logml)
% Palauttaa logml:n string-esityksen.
mjono = ' ';
if isequal(logml,-Inf)
mjono(7) = '-';
return
end
if abs(logml)<10000
%Ei tarvita e-muotoa
mjono(7) = palautaYks(abs(logml),-1);
mjono(6) = '.';
mjono(5) = palautaYks(abs(logml),0);
mjono(4) = palautaYks(abs(logml),1);
mjono(3) = palautaYks(abs(logml),2);
mjono(2) = palautaYks(abs(logml),3);
pointer = 2;
while mjono(pointer)=='0' & pointer<7
mjono(pointer) = ' ';
pointer=pointer+1;
end
if logml<0
mjono(pointer-1) = '-';
end
else
suurinYks = 4;
while abs(logml)/(10^(suurinYks+1)) >= 1
suurinYks = suurinYks+1;
end
if suurinYks<10
mjono(7) = num2str(suurinYks);
mjono(6) = 'e';
mjono(5) = palautaYks(abs(logml),suurinYks-1);
mjono(4) = '.';
mjono(3) = palautaYks(abs(logml),suurinYks);
if logml<0
mjono(2) = '-';
end
elseif suurinYks>=10
mjono(6:7) = num2str(suurinYks);
mjono(5) = 'e';
mjono(4) = palautaYks(abs(logml),suurinYks-1);
mjono(3) = '.';
mjono(2) = palautaYks(abs(logml),suurinYks);
if logml<0
mjono(1) = '-';
end
end
end
function digit = palautaYks(num,yks)
% palauttaa luvun num 10^yks termin kertoimen
% string:inä
% yks täytyy olla kokonaisluku, joka on
% vähintään -1:n suuruinen. Pienemmillä
% luvuilla tapahtuu jokin pyöristysvirhe.
if yks>=0
digit = rem(num, 10^(yks+1));
digit = floor(digit/(10^yks));
else
digit = num*10;
digit = floor(rem(digit,10));
end
digit = num2str(digit);

11
matlab/general/noIndex.m Normal file
View file

@ -0,0 +1,11 @@
function puredata = noIndex(data, noalle)
% NOINDEX Check that the data contains no index column.
% Input: two variables from a mixture/admixture result structure.
% Output:
% puredata: a data contains no index column.
if size(data,2) == length(noalle) + 1
puredata = data(:,[1:end-1]); % remove the index column
else
puredata = data;
end

View file

@ -0,0 +1,35 @@
function str = ownNum2Str(number)
absolute = abs(number);
if absolute < 1000
str = num2str(number);
elseif absolute < 10000000
first_three = rem(number,1000);
next_four = (number - first_three) /1000;
first_three = abs(first_three);
if first_three<10
first_three = ['00' num2str(first_three)];
elseif first_three<100
first_three = ['0' num2str(first_three)];
else
first_three = num2str(first_three);
end;
str = [num2str(next_four) first_three];
elseif absolute < 100000000
first_four = rem(number,10000);
next_four = (number - first_four) /10000;
first_four = abs(first_four);
if first_four<10
first_four = ['000' num2str(first_four)];
elseif first_four<100
first_four = ['00' num2str(first_four)];
elseif first_four<1000
first_four = ['0' num2str(first_four)];
else
first_four = num2str(first_four);
end;
str = [num2str(next_four) first_four];
else
str = num2str(number);
end;

View file

@ -0,0 +1,124 @@
function setWindowOnTop(h,state)
% SETWINDOWONTOP sets a figures Always On Top state on or off
%
% Copyright (C) 2006 Matt Whitaker
%
% This program is free software; you can redistribute it and/or modify it
% under
% the terms of the GNU General Public License as published by the Free
% Software Foundation; either version 2 of the License, or (at your
% option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
% General Public License for more details.
%
% SETWINDOWONTOP(H,STATE): H is figure handle or a vector of figure handles
% STATE is a string or cell array of strings-
% 'true' - set figure to be always on top
% 'false' - set figure to normal
% if STATE is a string the state is applied to
% all H. If state is a cell array the length STATE
% must equal that of H and each state is applied
% individually.
% Examples:
% h= figure;
% s = 'true';
% setWindowOnTop(h,s) %sets h to be on top
%
% h(1) = figure;
% h(2) = figure;
% s = 'true';
% setWindowOnTop(h,s) %sets both figures to be on top
%
% h(1) = figure;
% h(2) = figure;
% s = {'true','false'};
% setWindowOnTop(h,s) %sets h(1) on top, h(2) normal
% Notes:
% 1. Figures must have 'Visible' set to 'on' and not be docked for
% setWindowOnTop to work.
% 2. Routine does not work for releases prior to R14SP2
% 3. The Java calls are undocumented by Mathworks
%
% Revisions: 09/28/06- Corrected call to warning and uopdated for R2006b
drawnow; %need to make sure that the figures have been rendered or Java error can occur
% setWindowOnTop disabled to ensure that compiled version runs properly
% Modified: 11/06/07 Jukka Siren
return
%check input argument number
error(nargchk(2, 2, nargin, 'struct'));
%is JVM available
if ~usejava('jvm')
error('setWindowOnTop requires Java to run.');
end
[j,s] = parseInput;
setOnTop; %set the on top state
function [j,s] = parseInput
% is h all figure handles
if ~all(ishandle(h)) || ~isequal(length(h),length(findobj(h,'flat','Type','figure')))
error('All input handles must be valid figure handles');
end %if
%handle state argument
if ischar(state)
%make it a cell
s = cellstr(repmat(state,[length(h),1]));
elseif iscellstr(state)
if length(state) ~= length(h)
error('Cell array of strings: state must be same length as figure handle input');
end %if
s = state;
else
error('state must be a character array or a cell array of strings');
end %if
%check that the states are all valid
if ~all(ismember(s,{'true','false'}))
error('Invalid states entered')
end %if
if length(h) == 1
j{1} = get(h,'javaframe');
else
j = get(h,'javaframe');
end %if
end %parseInput
function setOnTop
%get version so we know which method to call
v = ver('matlab');
%anticipating here that Mathworks will continue to change these
%undocumented calls
switch v(1).Release
case {'(R14SP2)','(R14SP3)'}
on_top = 1;
case {'(R2006a)','(R2006b)'}
on_top = 2;
otherwise %warn but try method 2
% warning('setWindowOnTop:UntestedVersion',['setWindowOnTop has not been tested with release: ',v.Release]);
on_top = 2;
end %switch
for i = 1:length(j)
switch on_top
case 1 %R14SP2-3
w = j{i}.fClientProxy.getFrameProxy.getClientFrame;
case 2 %R2006a+
w= j{i}.fFigureClient.getWindow;
otherwise %should not happen
error('Invalid on top method');
end %switch
awtinvoke(w,'setAlwaysOnTop',s{i});
end %for j
end %setOnTop
end %setWindowOnTop

59
matlab/general/seticon.m Normal file
View file

@ -0,0 +1,59 @@
function seticon(window, useicon)
% Set icon for window.
%
% seticon(window, useicon)
%
% Parameters:
% window: Figure number or name of window
% useicon: Icon number to use or file name of icon
% =1 : Application
% =2 : Hand (x)
% =3 : Question (?)
% =4 : Exclamation /!\
% =5 : Asterisk (i)
% =6 : Winlogo
%
% Examples:
% seticon(2,3)
% seticon(1, 'iconfile.ico')
% seticon('Microsoft Internet', 6)
% Copyright 2000-2002, Research and Development
if nargin~=2
error('Two arguments required')
end
if ~isstr(window)
window = wgetname(window);
end
if ~any(window)
warning('Window specification insufficient')
return
end
if isstr(useicon)
switch lower(useicon)
case 'application'
icon(1, window);
case 'hand'
icon(2, window);
case 'question'
icon(3, window);
case 'exclamation'
icon(4, window);
case 'asterisk'
icon(5, window);
case 'winlogo'
icon(6, window);
otherwise
icon(101, window, useicon);
end
else
if useicon>=1 & useicon<=6
icon(useicon, window);
else
error('Icon number out of range')
end
end

View file

@ -0,0 +1,3 @@
function waitALittle
A = rand(500);
gammaln(A);

21
matlab/general/wgetname.m Normal file
View file

@ -0,0 +1,21 @@
function s=wgetname(h)
% Returns the window name of a window
%
% s=wgetname(h)
%
% Parameters:
% h : window number
%
% See also: seticon
% Copyright 2000-2002, Research and Development
if strcmp(get(h,'numbertitle'), 'on')
if get(h,'name')
s = sprintf('Figure %d: %s', h, get(h,'name'));
else
s = sprintf('Figure %d', h);
end
else
s = get(h,'name');
end

Binary file not shown.

51
matlab/general/zscore.m Normal file
View file

@ -0,0 +1,51 @@
function [z,mu,sigma] = zscore(x,flag,dim)
%ZSCORE Standardized z score.
% Z = ZSCORE(X) returns a centered, scaled version of X, the same size as X.
% For vector input X, Z is the vector of z-scores (X-MEAN(X)) ./ STD(X). For
% matrix X, z-scores are computed using the mean and standard deviation
% along each column of X. For higher-dimensional arrays, z-scores are
% computed using the mean and standard deviation along the first
% non-singleton dimension.
%
% The columns of Z have sample mean zero and sample standard deviation one
% (unless a column of X is constant, in which case that column of Z is
% constant at 0).
%
% [Z,MU,SIGMA] = ZSCORE(X) also returns MEAN(X) in MU and STD(X) in SIGMA.
%
% [...] = ZSCORE(X,1) normalizes X using STD(X,1), i.e., by computing the
% standard deviation(s) using N rather than N-1, where N is the length of
% the dimension along which ZSCORE works. ZSCORE(X,0) is the same as
% ZSCORE(X).
%
% [...] = ZSCORE(X,FLAG,DIM) standardizes X by working along the dimension
% DIM of X. Pass in FLAG==0 to use the default normalization by N-1, or 1
% to use N.
%
% See also MEAN, STD.
% Copyright 1993-2006 The MathWorks, Inc.
% $Revision: 1.7.2.5 $ $Date: 2007/12/10 23:06:31 $
% [] is a special case for std and mean, just handle it out here.
if isequal(x,[]), z = []; return; end
if nargin < 2
flag = 0;
end
if nargin < 3
% Figure out which dimension to work along.
dim = find(size(x) ~= 1, 1);
if isempty(dim), dim = 1; end
end
% Compute X's mean and sd, and standardize it
mu = mean(x,dim);
sigma = std(x,flag,dim);
sigma0 = sigma;
sigma0(sigma0==0) = 1;
z = (x-mu)./sigma0;
% z = bsxfun(@minus,x, mu);
% z = bsxfun(@rdivide, z, sigma0);