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
|
BII-wushuang/FLLIT-master
|
train_boost_hd.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_hd.m
| 6,367 |
utf_8
|
d698663f6ad6929515c06eb563151f6f
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners] = train_boost_hd(params,data,hd,samples_idx)
% Train a KernelBoost classifier on the given samples
% the classifier combine the histogram discriptor
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
weak_learners(params.wl_no).alpha = 0;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores = zeros(params.wl_no,3);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
% add the histogram discriptor
hd1 = hd(T2_idx,:);
features = [features,hd1];
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree,...
weak_learners(i_w).hd_feature] = remove_useless_filters_hd(reg_tree,kernels,kernel_params);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
% add the hd feature
hd_aug = hd(:,weak_learners(i_w).hd_feature);
features = [features,hd_aug];
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
weak_learners(i_w).alpha = alpha;
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
pirovc/fgap-master
|
fgap.m
|
.m
|
fgap-master/fgap.m
| 66,228 |
utf_8
|
9568dac0e7f59e09c35645295dfbc255
|
% FGAP: an automated gap closing tool
% Vitor C Piro, Helisson Faoro, Vinicius A Weiss, Maria BR Steffens, Fabio O Pedrosa, Emanuel M Souza and Roberto T Raittz
% BMC Research Notes 2014, 7:371 doi:10.1186/1756-0500-7-371
%
% The MIT License (MIT)
%
% Copyright (c) 2014 UFPR - Universidade Federal do Paraná (Vitor C. Piro - [email protected])
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
% THE SOFTWARE.
%
function [] = fgap(varargin)
% Status:
% s1 - Regions were not found in datasets
% s2 - BLAST returned no significant results
% s3 - Can not find significant alignments (pairs)
% s4 - There were no pre-candidates in dataset
% s5 - There were no candidates for closing
% s6 - There were no compatible blast results
%Inicia contador de tempo
tic ();
global minScore maxEValue minIdentity contigEndLength edgeTrimLength gapChar maxRemoveLength maxInsertLength ...
blastAlignParam blastMaxResults threads outputPrefix moreOutput blastPath positiveGap zeroGap negativeGap ...
plusBasesMoreOutput saveDatasetsPath loadDatasetsPath;
minScore = 25;
maxEValue = 1e-7;
minIdentity = 70;
contigEndLength = 300;
edgeTrimLength = 0;
maxRemoveLength = 500;
maxInsertLength = 500;
positiveGap = 1;
zeroGap = 0;
negativeGap = 0;
gapChar = 'N';
blastPath = '';
blastAlignParam = '1,1,1,-3,15';
blastMaxResults = 200;
threads = 1;
moreOutput = 0;
outputPrefix = 'output_fgap';
%%%%% VERSAO %%%%%%%
global version;
version = '1.8.1';
%%%%%%%%%%%%%%%%%%%%
disp([repmat('-',1,42) 10 9 9 'FGAP v' version 10 repmat('-',1,42) 10]);
%%%%%%%%%%%%%%%%%%%%
%% Declaração
%disp(num2str(nargin));
%disp(char(varargin));
if(nargin==1)
showHelp();
return;
elseif (nargin<4)
disp('Not enough input arguments');
showHelp();
return;
elseif (rem(nargin,2)~=0)
disp('Incorrect number of arguments');
showHelp();
return;
else
okargs = {'-d','--draft-file',...
'-a','--datasets-files',...
'-S','--save-datasets',...
'-L','--load-datasets',...
'-s','--min-score', ...
'-e','--max-evalue', ...
'-i','--min-identity', ...
'-C','--contig-end-length', ...
'-T','--edge-trim-length', ...
'-R','--max-remove-length', ...
'-I','--max-insert-length', ...
'-p','--positive-gap', ...
'-z','--zero-gap', ...
'-g','--negative-gap', ...
'-c','--gap-char', ...
'-b','--blast-path', ...
'-l','--blast-alignment-parameters', ...
'-r','--blast-max-results', ...
'-t','--threads', ...
'-m','--more-output', ...
'-o','--output-prefix',...
'-h','--help'};
% Caso possua argumentos que não pertencam a lista
if length(setdiff(varargin(1:2:end),okargs(1:1:end)))>0
disp('Incorrect arguments');
showHelp();
return;
else
for i=1:2:nargin
if(strcmp(varargin{i},'-d') || strcmp(varargin{i},'--draft-file'))
draftFile = varargin{i+1};
elseif(strcmp(varargin{i},'-a') || strcmp(varargin{i},'--datasets-files'))
datasetsFiles = varargin{i+1};
elseif(strcmp(varargin{i},'-s') || strcmp(varargin{i},'--min-score'))
minScore = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-e') || strcmp(varargin{i},'--max-evalue'))
maxEValue = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-i') || strcmp(varargin{i},'--min-identity'))
minIdentity = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-C') || strcmp(varargin{i},'--contig-end-length'))
contigEndLength = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-T') || strcmp(varargin{i},'--edge-trim-length'))
edgeTrimLength = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-R') || strcmp(varargin{i},'--max-remove-length'))
maxRemoveLength = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-I') || strcmp(varargin{i},'--max-insert-length'))
maxInsertLength = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-p') || strcmp(varargin{i},'--positive-gap'))
positiveGap = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-z') || strcmp(varargin{i},'--zero-gap'))
zeroGap = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-g') || strcmp(varargin{i},'--negative-gap'))
negativeGap = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-c') || strcmp(varargin{i},'--gap-char'))
gapChar = varargin{i+1};
elseif(strcmp(varargin{i},'-b') || strcmp(varargin{i},'--blast-path'))
blastPath = varargin{i+1};
elseif(strcmp(varargin{i},'-l') || strcmp(varargin{i},'--blast-alignment-parameters'))
blastAlignParam = varargin{i+1};
elseif(strcmp(varargin{i},'-r') || strcmp(varargin{i},'--blast-max-results'))
blastMaxResults = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-t') || strcmp(varargin{i},'--threads'))
threads = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-m') || strcmp(varargin{i},'--more-output'))
moreOutput = str2num(varargin{i+1});
elseif(strcmp(varargin{i},'-o') || strcmp(varargin{i},'--output-prefix'))
outputPrefix = varargin{i+1};
end
end
end
end
% Quantidade de bases dos contigs ends no outputmore
plusBasesMoreOutput = contigEndLength;
% Salvar dataset para uso posterior
saveDatasetsPath = '';
loadDatasetsPath = '';
%% Verificações
if ~exist('draftFile','var') || ~exist('datasetsFiles','var')
disp('Not enough input arguments');
return;
elseif ~exist(draftFile,'file')
disp(['File not found: ' draftFile]);
return;
elseif ~isFasta(draftFile)
disp(['File is not in fasta format: ' draftFile]);
return;
else
if(sum(regexp(datasetsFiles,','))==0 && isempty(datasetsFiles))
disp(['Wrong input arguments (use commas between datasets)']);
return;
end
ds = regexp(datasetsFiles,',','split');
for dt = 1:length(ds)
df = char(ds(dt));
if (length(ds)==1 && strcmp(df(end-8:end),'.datasets'))
if ~exist([df '.mat'],'file') || ~exist([df '.nhr'],'file') || ~exist([df '.nin'],'file') || ~exist([df '.nsq'],'file')
disp(['File(s) not found: ' df ' (.mat, .nhr, .nin, .nsq)']);
return;
else
loadDatasetsPath = df;
end
elseif (dt==length(ds) && strcmp(df(end-8:end),'.datasets'))
[fo, ~, ~] = fileparts(df);
if ~isempty(fo)
if ~exist(fo,'dir')
disp(['Directory not found: ' fo]);
else
saveDatasetsPath = df;
end
else
saveDatasetsPath = df;
end
else
if ~exist(df,'file')
disp(['File not found: ' df]);
return;
elseif ~isFasta(df)
disp(['File is not in fasta format: ' df]);
return;
end
end
end
end
% Verifica se pasta de saída existe
[folder_outputPrefix,~,~] = fileparts(outputPrefix);
if ~exist(folder_outputPrefix,'dir') && ~isempty(folder_outputPrefix)
disp('Output folder does not exist');
return;
elseif ~isempty(folder_outputPrefix)
folder_outputPrefix = [folder_outputPrefix '/'];
end
% Verifica caminho blast
global makeblastdbAlgorithm;
[makeblastdbAlgortihmStatus, makeblastdbAlgorithm] = system([blastPath 'makeblastdb -version']);
if makeblastdbAlgortihmStatus>0
disp(['Error MAKEBLASTDB path: ' makeblastdbAlgorithm]);
return;
else
makeblastdbAlgorithm = strtrim(makeblastdbAlgorithm);
disp(makeblastdbAlgorithm);
end
global blastnAlgorithm;
[blastnAlgortihmStatus, blastnAlgorithm] = system([blastPath 'blastn -version']);
if blastnAlgortihmStatus>0
disp(['Error BLASTN path: ' blastnAlgorithm]);
return;
else
blastnAlgorithm = strtrim(blastnAlgorithm);
disp(blastnAlgorithm);
end
%% Inicialização de componentes
% Para notação cientifica na matriz
%format('shortG');
% Cria pasta temporária
global tmp_folder;
tmp_folder = [folder_outputPrefix 'tmp_fgap/'];
if exist(tmp_folder,'dir')
rmdir(tmp_folder,'s');
end
[mkdirStatus, mkdirMsg] = mkdir(tmp_folder);
if mkdirStatus==0
disp(['Temporary folder ' tmp_folder ' could not be created: ' mkdirMsg]);
return;
end
% Arquivo de stats
global stats_file;
stats_file = [outputPrefix '.stats'];
if exist(stats_file,'file')
delete(stats_file);
end
% Estatísticas - totalizadores
global stats;
stats = struct('before',[],'after',[],'removedBases',0,'insertedBases',0,'totalGapsClosed',0,'datasetCount',[],'typeCount',[0 0 0]);
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %% %% %%%%%%%%%%%%%%%% INICIA FGAP %%%%%%%%%%%%%%%% %% %% %%
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
warning off
[draft_genome_fasta error_msg] = loadDraftFile(draftFile);
if isempty(error_msg)
stats.before = getStats(draft_genome_fasta,0);
[datasets_fasta error_msg] = loadDatasetsFiles(datasetsFiles);
if isempty(error_msg)
if isempty(buildDatabase(datasets_fasta))
[draft_genome_fasta error_msg] = identifyGaps(draft_genome_fasta);
if isempty(error_msg)
disp('Starting gap closure ...');
pre_fasta = draftFile;
out_more_before = [outputPrefix '.before.fasta' ];
out_more_after = [outputPrefix '.after.fasta' ];
total_char = getTotalChars(draft_genome_fasta);
total_char_before = 0;
log_round = [];
more_before = cell(1); more_after = cell(1);
round = 0;
while total_char~=0 && total_char_before~=total_char
round=round+1;
% Função principal
pre_draft_genome_fasta = draft_genome_fasta;
[draft_genome_fasta candidates error_msg status_msg] = closeGaps(draft_genome_fasta, datasets_fasta);
if isempty(error_msg) && isempty(status_msg)
out_fasta = [outputPrefix '_' num2str(round) '.fasta'];
out_final = [outputPrefix '.final.fasta'];
out_log = [outputPrefix '_' num2str(round) '.log' ];
% Gera log
[log] = generateLog(candidates,pre_draft_genome_fasta,datasets_fasta,pre_fasta);
% Salva total de gaps anteriores e atual
total_char_before = total_char;
total_char = getTotalChars(draft_genome_fasta);
stats.totalGapsClosed = stats.totalGapsClosed + (total_char_before-total_char);
% Mostra informações na tela
gapsclosed_round = ['Round ' num2str(round) ': ' num2str(total_char_before-total_char) ' gaps'];
disp(gapsclosed_round);
% Salva dados da rodada no arquivo de stats
log_round(round).log = [gapsclosed_round 10 ' Output log: ' hidePath(out_log) 10 ' Output fasta: ' hidePath(out_fasta) 10 ' After round ' num2str(round) ':' 10 ' ' getStats(draft_genome_fasta,1) 10];
% Escreve Log da rodada
writeLog(out_log,log);
% Escreve fasta da rodada
writeFasta(out_fasta, draft_genome_fasta);
if(moreOutput)
[more_before{round} more_after{round}] = generateMoreOutput(candidates,pre_draft_genome_fasta);
end
pre_fasta = [outputPrefix '_' num2str(round) '.fasta'];
elseif ~isempty(status_msg)
disp(status_msg);
total_char_before = total_char;
elseif ~isempty(error_msg)
break;
end
end
stats.after = getStats(draft_genome_fasta,0);
if(moreOutput)
writeMoreOutput(more_before,out_more_before,more_after,out_more_after);
end
%Escreve arquivo final
if(exist('out_fasta','var'))
copyfile(out_fasta,out_final);
end
elapsed = ['Elapsed time is ' num2str(toc ()) ' seconds'];
writeStats(draftFile,datasets_fasta,log_round,elapsed);
end
end
end
end
if ~isempty(error_msg)
disp(error_msg);
end
disp('Cleaning files ...');
rmdir(tmp_folder,'s');
if exist('elapsed','var')
disp(elapsed);
end
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %% %% %%%%%%%%%%%%%%%%%% FUNCOES %%%%%%%%%%%%%%%%%% %% %% %%
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [out_draft candidates error_msg status_msg] = closeGaps(draft_genome_fasta, datasets_fasta)
global contigEndLength edgeTrimLength minScore maxEValue minIdentity blastMaxResults blastAlignParam threads tmp_folder blastPath stats saveDatasetsPath loadDatasetsPath;
out_draft = draft_genome_fasta;
candidates = [];
error_msg = '';
status_msg = '';
%% Procura Chars válidos no Draft
for i = 1:length(draft_genome_fasta)
if ~isempty(draft_genome_fasta(i).Pos)
% Marca gaps que já tentaram ser fechados (1) com -1
draft_genome_fasta(i).Pos(draft_genome_fasta(i).Pos(:,4)==1,4) = -1;
% Gaps que ainda nao foram fechados (0)
new_chars = draft_genome_fasta(i).Pos(draft_genome_fasta(i).Pos(:,4)==0,1:3);
if ~isempty(new_chars)
% Pega apenas chars que estão distantes um do outros (areas de contigEndLength nao se encontram)
cnt=1;
draft_genome_fasta(i).Pos(draft_genome_fasta(i).Pos(:,3)==new_chars(1,3),4) = 1;
for j=2:length(new_chars(:,1))
% Caso tenha diferenca de dois lados do ultimo gap valido, marca como candidato (1)
if (new_chars(j,1) - new_chars(j-cnt,2)) >= (edgeTrimLength*2)+(contigEndLength*2)
draft_genome_fasta(i).Pos(draft_genome_fasta(i).Pos(:,3)==new_chars(j,3),4) = 1;
cnt = 1;
else
cnt = cnt + 1;
end
end
end
end
end
%% Gera regiões de ancoragem
cont = 0;
draft_contig = struct('draft_char',struct());
for i = 1:length(draft_genome_fasta)
if ~isempty(draft_genome_fasta(i).Pos)
% Verifica apenas chars candidatos (1)
cand_chars = draft_genome_fasta(i).Pos(draft_genome_fasta(i).Pos(:,4)==1,1:3);
if ~isempty(cand_chars)
for j = 1:length(cand_chars(:,1))
% Caso edges ultrapassem regiao possível (sem deixar área para o contigEndLength)
if edgeTrimLength >= cand_chars(j,1)-1 || (cand_chars(j,2) + edgeTrimLength) >= length(draft_genome_fasta(i).Sequence)
continue;
end
% Posição inicial e final de ancoragem
seq_start = cand_chars(j,1)-(contigEndLength+edgeTrimLength);
seq_end = cand_chars(j,2)+(contigEndLength+edgeTrimLength);
% Caso não possua região de aconragem suficiente (excede arquivo)
if seq_start<1
seq_start_len = cand_chars(j,1)-edgeTrimLength-1;
seq_start = 1;
else
seq_start_len = contigEndLength;
end
if seq_end>length(draft_genome_fasta(i).Sequence)
seq_end_len = (length(draft_genome_fasta(i).Sequence)-cand_chars(j,2))-edgeTrimLength;
seq_end = length(draft_genome_fasta(i).Sequence);
else
seq_end_len = contigEndLength;
end
% Para recuperação de dados
draft_contig(i).draft_char(cand_chars(j,3)).Header = ['draft_' num2str(i) '_' num2str(cand_chars(j,3))];
draft_contig(i).draft_char(cand_chars(j,3)).Sequence = draft_genome_fasta(i).Sequence(seq_start:seq_end);
% Para arquivo fasta, grava lado A (montante) e B (jusante) em relação ao char
cont = cont + 1;
draft_regions(cont).Header = ['draft_' num2str(i) '_' num2str(cand_chars(j,3)) '_A'];
draft_regions(cont).Sequence = draft_genome_fasta(i).Sequence(seq_start:seq_start+seq_start_len-1);
cont = cont + 1;
draft_regions(cont).Header = ['draft_' num2str(i) '_' num2str(cand_chars(j,3)) '_B'];
draft_regions(cont).Sequence = draft_genome_fasta(i).Sequence(seq_end-seq_end_len+1:seq_end);
end
end
end
end
if ~exist('draft_regions','var')
status_msg = 'There are no more possible gaps to be closed (s1)';
return;
end
%% BLAST
% Salva arquivo
fastawrite2([tmp_folder 'draft_regions.fasta'],draft_regions);
% Verifica se está carregando de arquivo específico ou pasta temporária
% (se está salvando também está em pasta diferente)
if ~isempty(loadDatasetsPath)
dboutputfolder = loadDatasetsPath;
elseif ~isempty(saveDatasetsPath)
dboutputfolder = saveDatasetsPath;
else
dboutputfolder = [tmp_folder 'datasets'];
end
blastAlignParamSplit = regexp(blastAlignParam,',','split');
% Executa BLAST - blastn
blastn = ['-query ' tmp_folder 'draft_regions.fasta' ...
' -db ' dboutputfolder ...
' -task blastn ' ...
' -min_raw_gapped_score ' num2str(minScore) ...
' -evalue ' num2str(maxEValue) ...
' -perc_identity ' num2str(minIdentity) ...
' -word_size ' char(blastAlignParamSplit(5)) ...
' -gapopen ' char(blastAlignParamSplit(1)) ...
' -gapextend ' char(blastAlignParamSplit(2)) ...
' -penalty ' char(blastAlignParamSplit(4)) ...
' -reward ' char(blastAlignParamSplit(3)) ...
' -max_target_seqs ' num2str(blastMaxResults) ...
' -out ' [tmp_folder 'blastn.out'] ...
' -num_threads ' num2str(threads) ...%' -dust no ' % fechou mais mas piorou a validacao ...
' -outfmt "6 qseqid sseqid score bitscore evalue pident nident mismatch sstrand qstart qseq qend sstart sseq send qlen length qcovhsp"'
];
%qseqid sseqid score bitscore evalue pident nident mismatch sstrand qstart qseq qend sstart sseq send qlen
%1 Query Seq-id
%2 Subject Seq-id
%3 Raw score
%4 Bit score
%5 Expect value
%6 Percentage of identical matches
%7 Number of identical matches
%8 Number of mismatches
%9 Subject Strand
%10 Start of alignment in query
%11 Aligned part of query sequence
%12 End of alignment in query
%13 Start of alignment in subject
%14 Aligned part of subject sequence
%15 End of alignment in subject
%16 Query sequence length
%17 Alignment length
%18 Query Coverage Per HSP
[blastnStatus, ~] = system([blastPath 'blastn ' blastn]);
if blastnStatus>0
error_msg = ['Error BLASTN: ' blastnStatus];
return;
end
fid = fopen([tmp_folder 'blastn.out'],'r'); % Open text file
blastnResult = textscan(fid,'%s','delimiter','\n','bufsize',(contigEndLength*2)+1000);
fclose(fid);
if isempty(blastnResult)
status_msg = 'There are no more possible gaps to be closed (s2)';
return;
end
cont = 0;
old_draft_head = '';
for i=1:length(blastnResult{1})
parts = regexp(blastnResult{1}{i},'\t','split');
if ~strcmp(old_draft_head,parts(1))
cont = cont + 1;
posi = 1;
else
posi = posi + 1;
end
blast_result{cont}{posi} = parts;
old_draft_head=parts(1);
end
if ~exist('blast_result','var')
status_msg = 'There are no more possible gaps to be closed (s6)';
return;
end
%% Filtra resultados do BLAST (retira lados orfãos)
i=0;
cont = 0;
% Apenas mantem resultados que possuem outro lado com resultados também
while i <= length(blast_result) - 2
if i <= length(blast_result) - 2
i = i + 1;
A = blast_result{i};
A_q = A{1}{1};
i = i + 1;
B = blast_result{i};
B_q = B{1}{1};
if ~strcmp(A_q(1:end-2),B_q(1:end-2))
i = i - 1;
else
cont = cont + 1;
blast_result_filter{cont} = A;
cont = cont + 1;
blast_result_filter{cont} = B;
end
end
end
if ~exist('blast_result_filter','var')
status_msg = 'There are no more possible gaps to be closed (s3)';
return;
end
%% Loop nos resultados para pegar candidatos
i=0;
cont = 0;
while i < length(blast_result_filter)
% Pega HSPs dos dois lados
i = i + 1;
A = blast_result_filter{i};
A_hsps = getHSPs(A,i);
i = i + 1;
B = blast_result_filter{i};
B_hsps = getHSPs(B,i);
% Caso possua HSPs compativeis com os parametros
if (~isempty(A_hsps) && ~isempty(B_hsps))
% Loop nos resultados do A procurando no B
for j=1:length(A_hsps(:,1))
vA = []; vB = []; vB_list=[];
vA = A_hsps(j,:);
% Compara coluna 1 (file) 2 (ctg) e 9 (strand) - se bateu no
% mesmo arquivo e contig do dataset e strand
vB_list = B_hsps(A_hsps(j,1)==B_hsps(:,1) & A_hsps(j,2)==B_hsps(:,2) & A_hsps(j,9)==B_hsps(:,9),:);
% Caso possua hits no B_hsps(vB_list) referente ao A_hsps
if (~isempty(vB_list))
% Adiciona todos os possiveis candidatos do lado B que tenham referencia no lado A
for k=1:length(vB_list(:,1))
% Pega ocorrencia de vB
vB = vB_list(k,:);
cont = cont +1;
id = regexp(A{1}{1}, '_', 'split');
id_draft_scaf = str2num(id{2});
id_char = str2num(id{3});
% Grava pré-candidatos
pre_candidates(cont).id_DtsetFile = vA(1);
pre_candidates(cont).id_DtsetContig = vA(2);
pre_candidates(cont).id_DraftScaf = id_draft_scaf;
pre_candidates(cont).id_DraftChar = id_char;
pre_candidates(cont).rawScore = [vA(16) vB(16)];
pre_candidates(cont).bitScore = [vA(3) vB(3)];
pre_candidates(cont).eValue = [vA(4) vB(4)];
pre_candidates(cont).identitiesPercent = [vA(12) vB(12)];
pre_candidates(cont).identitiesPossible = [vA(13) vB(13)];
pre_candidates(cont).identitiesMatch = [vA(14) vB(14)];
pre_candidates(cont).queryIndices = [vA(5) vA(6) vB(5) vB(6)];
pre_candidates(cont).subjectIndices = [vA(7) vA(8) vB(7) vB(8)];
pre_candidates(cont).alignmentBlastQuery = [blast_result_filter{vA(10)}{vA(11)}(11) ; blast_result_filter{vB(10)}{vB(11)}(11)];
pre_candidates(cont).alignmentBlastSubject = [blast_result_filter{vA(10)}{vA(11)}(14) ; blast_result_filter{vB(10)}{vB(11)}(14)];
pre_candidates(cont).strand = [vA(9) vB(9)];
pre_candidates(cont).lengthcontigEndLengths = [vA(15) vB(15)];
pre_candidates(cont).queryCoverage = [vA(17) vB(17)];
end
end
end
end
end
if ~exist('pre_candidates','var')
status_msg = 'There are no more possible gaps to be closed (s4)';
return;
end
%% Verifica candidatos
pre_candidates = verifyPreCandidates(pre_candidates,draft_genome_fasta, datasets_fasta);
if ~isempty(pre_candidates)
candidates = selectCandidates(pre_candidates,datasets_fasta);
end
if isempty(candidates)
status_msg = 'There are no more possible gaps to be closed (s5)';
return;
end
%% Adiciona informações ao candidato
candidates = addCandidateData(candidates,draft_genome_fasta,datasets_fasta);
%% Gera novo draft com gap fechado
new_draft = draft_genome_fasta;
for i=1:length(candidates)
% NÃO USAR DA STRUCT - Precisa gerar a cada rodada pois dados da tabela mudam
[remove_start remove_end remove_seq] = getRemovedSeqDraft(candidates(i),new_draft);
% Caso tenha fechado mais de um gap, verifica se foi antes ou
% depois e quantos para cada lado (para atualizar a tabela de Pos)
closed_chars = getChars(remove_seq);
closed_chars = length(closed_chars(:,1));
if closed_chars>1
[n_start n_end] = getPosN(candidates(i),new_draft);
rem_before = n_start - remove_start;
rem_after = remove_end - n_end;
closed_chars_before = size(getChars(remove_seq(1:rem_before)),1);
closed_chars_after = size(getChars(remove_seq(end-rem_after+1:end)),1);
% Verifica apenas chars disponiveis para fechamento (~=2)
open_chars = new_draft(candidates(i).id_DraftScaf).Pos(new_draft(candidates(i).id_DraftScaf).Pos(:,4)~=2,:);
% Identifica posicao relativa
pos_open_chars = find(open_chars(:,3)==candidates(i).id_DraftChar);
% Encontra quais chars antes e depois foram fechados
chars_bef_aft = open_chars(pos_open_chars-closed_chars_before:pos_open_chars+closed_chars_after,3);
index_chars_closed = ismember(new_draft(candidates(i).id_DraftScaf).Pos(:,3),chars_bef_aft);
else
index_chars_closed = candidates(i).id_DraftChar;
end
% Tamanho anterior para comparacao de bases
old_length = length(new_draft(candidates(i).id_DraftScaf).Sequence);
% Insere nova sequencia no draft
new_draft(candidates(i).id_DraftScaf).Sequence = [new_draft(candidates(i).id_DraftScaf).Sequence(1:remove_start-1) lower(candidates(i).insertedSeqDtset) new_draft(candidates(i).id_DraftScaf).Sequence(remove_end+1:end)];
new_length = length(new_draft(candidates(i).id_DraftScaf).Sequence);
% Move os outros gaps do contig para a posição correta apos inserir nova sequencia
% Calcula diferenca de area
new_area_size = new_length - old_length;
% Pega todos os chars abaixo do gap fechado
pos_chars_below = new_draft(candidates(i).id_DraftScaf).Pos(:,3)>candidates(i).id_DraftChar;
% Altera posicao dos chars abaixo
new_draft(candidates(i).id_DraftScaf).Pos(pos_chars_below,1:2) = new_draft(candidates(i).id_DraftScaf).Pos(pos_chars_below,1:2)+new_area_size;
% Marca gaps como fechado (2) no Pos (verifica se nao fechou mais de um por vez)
new_draft(candidates(i).id_DraftScaf).Pos(index_chars_closed,4) = 2;
stats.datasetCount(candidates(i).id_DtsetFile) = stats.datasetCount(candidates(i).id_DtsetFile) + closed_chars;
stats.typeCount(candidates(i).gapType+2) = stats.typeCount(candidates(i).gapType+2) + closed_chars;
stats.removedBases = stats.removedBases + (remove_end - remove_start + 1);
stats.insertedBases = stats.insertedBases + length(candidates(i).insertedSeqDtset);
end
out_draft = new_draft;
end
%%
function [cand] = addCandidateData(cand,draft_genome_fasta,datasets_fasta)
for i=1:length(cand)
% Salva dados de inserção
[insert_start insert_end insert_seq] = getInsertedSeqDtset(cand(i),datasets_fasta(cand(i).id_DtsetFile).fasta);
cand(i).insertedSeqDtset = insert_seq;
cand(i).insertedPosDtset = [insert_start insert_end];
% Salva dados de remoção
[remove_start remove_end remove_seq] = getRemovedSeqDraft(cand(i),draft_genome_fasta);
cand(i).removedSeqDraft = remove_seq;
cand(i).removedPosDraft = [remove_start remove_end];
end
end
%%
function [log_complete] = generateLog(candidates,pre_draft_genome_fasta,datasets_fasta,pre_fasta)
for c=1:length(candidates)
% Query(draft/Cends) 1
% |||||||||||||||||| 2
% Subject (datasets) 3
vAl = (candidates(c).alignmentBlastQuery{1}==candidates(c).alignmentBlastSubject{1})*'|';
vAl(vAl==0) = 32;
blastA = [candidates(c).alignmentBlastQuery{1}; vAl ;candidates(c).alignmentBlastSubject{1}];
vBl = (candidates(c).alignmentBlastQuery{2}==candidates(c).alignmentBlastSubject{2})*'|';
vBl(vBl==0) = 32;
blastB = [candidates(c).alignmentBlastQuery{2}; vBl ;candidates(c).alignmentBlastSubject{2}];
dtset_min = min(candidates(c).subjectIndices);
dtset_max = max(candidates(c).subjectIndices);
openSubjectA = 0;
if(candidates(c).gapType==1)
% 'empurra' começo do B quando existe open gap no lado A
openSubjectA = length(regexp(blastA(3,:),'-')) ;
end
if(candidates(c).strand(1)==1)
A_st = candidates(c).subjectIndices(1) - dtset_min + 1;
B_st = candidates(c).subjectIndices(3) - dtset_min + 1 + openSubjectA;
elseif(candidates(c).strand(1)==2)
A_st = dtset_max - candidates(c).subjectIndices(1) + 1;
B_st = dtset_max - candidates(c).subjectIndices(3) + 1 + openSubjectA;
end
A_en = A_st + length(candidates(c).alignmentBlastSubject{1}) - 1;
B_en = B_st + length(candidates(c).alignmentBlastSubject{2}) - 1;
% ajusta visualização de gaps sobrepostos
if candidates(c).gapType==-1 && B_en > A_st
if A_st > B_st
openStart = length(regexp(candidates(c).alignmentBlastSubject{2}(1:A_st-1),'-')) ;
A_st = A_st + openStart;
A_en = A_en + openStart;
elseif B_st > A_st
openStart = length(regexp(candidates(c).alignmentBlastSubject{1}(1:B_st-1),'-')) ;
B_st = B_st + openStart;
B_en = B_en + openStart;
end
end
% Tamamanho geral do log
dtset_len = max([A_en B_en]);
% Contig End 3' Sequencia
a1A = blanks(dtset_len);
a1A(A_st:A_en) = blastA(1,:);
% Contig End 5' Sequencia
a1B = blanks(dtset_len);
a1B(B_st:B_en) = blastB(1,:);
% Contig End 3' Alinhamento
a2A = blanks(dtset_len);
a2A(A_st:A_en) = blastA(2,:);
% Contig End 5' Alinhamento
a2B = blanks(dtset_len);
a2B(B_st:B_en) = blastB(2,:);
% Subject - Dataset Sequencia
a3A = blanks(dtset_len);
a3A(A_st:A_en) = blastA(3,:);
a3B = blanks(dtset_len);
a3B(B_st:B_en) = blastB(3,:);
% Caso seja gap positivo, região inserida
insert_seq = '';
if(candidates(c).gapType==1)
insert_seq = lower(candidates(c).insertedSeqDtset);
a3A(A_en+1:B_st-1) = insert_seq;
a3B(A_en+1:B_st-1) = insert_seq;
end
% Posições
[queryA_start queryA_end queryB_start queryB_end] = getRealQueryPos(candidates(c),pre_draft_genome_fasta);
subjectA_start = candidates(c).subjectIndices(1);
subjectA_end = candidates(c).subjectIndices(2);
subjectB_start = candidates(c).subjectIndices(3);
subjectB_end = candidates(c).subjectIndices(4);
if(candidates(c).strand(1)==1 && candidates(c).gapType==1)
subjectA_end = subjectA_end + length(insert_seq);
subjectB_start = subjectB_start - length(insert_seq);
elseif(candidates(c).strand(1)==2 && candidates(c).gapType==1)
subjectA_end = subjectA_end - length(insert_seq);
subjectB_start = subjectB_start + length(insert_seq);
end
gap_id = getGapId(candidates(c));
% INICIO - escreve log em cell
log = cell(1);
l = 1;
log{l} = ['Gap ID: ' gap_id];
l=l+1;
log{l} = ['Gap Type: ' gapTypeName(candidates(c).gapType) 10];
l=l+1;
log{l} = ['Draft file: ' hidePath(pre_fasta) ' (' pre_draft_genome_fasta(candidates(c).id_DraftScaf).Header ')'];
l=l+1;
log{l} = ['DtSet file: ' hidePath(datasets_fasta(candidates(c).id_DtsetFile).file) ' (' datasets_fasta(candidates(c).id_DtsetFile).fasta(candidates(c).id_DtsetContig).Header ')' 10];
l=l+1;
log{l} = ['Contig end 3'':'];
l=l+1;
log{l} = [' Bit Score: ' num2str(candidates(c).bitScore(1)) ' bits (' num2str(candidates(c).rawScore(1)) ')'];
l=l+1;
log{l} = [' E-Value: ' num2str(candidates(c).eValue(1))];
l=l+1;
log{l} = [' Identity: ' num2str(candidates(c).identitiesMatch(1)) '/' num2str(candidates(c).identitiesPossible(1)) ' (' num2str(candidates(c).identitiesPercent(1)) '%)'];
l=l+1;
log{l} = [' Query Cov.: ' num2str(candidates(c).queryCoverage(1)) '%'];
l=l+1;
log{l} = ['Contig end 5'':'];
l=l+1;
log{l} = [' Bit Score: ' num2str(candidates(c).bitScore(2)) ' bits (' num2str(candidates(c).rawScore(2)) ')'];
l=l+1;
log{l} = [' E-Value: ' num2str(candidates(c).eValue(2))];
l=l+1;
log{l} = [' Identity: ' num2str(candidates(c).identitiesMatch(2)) '/' num2str(candidates(c).identitiesPossible(2)) ' (' num2str(candidates(c).identitiesPercent(2)) '%)'];
l=l+1;
log{l} = [' Query Cov.: ' num2str(candidates(c).queryCoverage(2)) '%'];
l=l+1;
log{l} = ['Strand (CEnds/Dtset): ' verifyStrandRev(candidates(c).strand(1)) 10];
l=l+1;
%len_res = dtset_len;
len_res = 60;
len_max_number = length(num2str(max([queryA_start queryB_start subjectA_start subjectB_start])));
pos_qA = ''; pos_qB = '';pos_sA='';pos_sB='';
for x=1:len_res:dtset_len
if(x+len_res>dtset_len)
e = dtset_len;
pos_qA = [' ' num2str(queryA_end,'%.f')];
pos_qB = [' ' num2str(queryB_end,'%.f')];
pos_sA = [' ' num2str(subjectA_end,'%.f')];
pos_sB = [' ' num2str(subjectB_end,'%.f')];
else
e = x+len_res-1;
end
if x==1
pre_qA = sprintf(['%' num2str(len_max_number) 'd'],queryA_start);
pre_qB = sprintf(['%' num2str(len_max_number) 'd'],queryB_start);
pre_sA = sprintf(['%' num2str(len_max_number) 'd'],subjectA_start);
pre_sB = sprintf(['%' num2str(len_max_number) 'd'],subjectB_start);
else
pre_qA = blanks(len_max_number);
pre_qB = blanks(len_max_number);
pre_sA = blanks(len_max_number);
pre_sB = blanks(len_max_number);
end
pre_al = blanks(len_max_number);
log{l} = ['CEnd3 ' pre_qA ' ' a1A(x:e) pos_qA];
l=l+1;
log{l} = [' ' pre_al ' ' a2A(x:e)];
l=l+1;
log{l} = ['Dtset ' pre_sA ' ' a3A(x:e) pos_sA];
l=l+1;
log{l} = ['Dtset ' pre_sB ' ' a3B(x:e) pos_sB];
l=l+1;
log{l} = [' ' pre_al ' ' a2B(x:e)];
l=l+1;
log{l} = ['CEnd5 ' pre_qB ' ' a1B(x:e) pos_qB];
l=l+1;
log{l} = [10];
l=l+1;
end
log{l} = ['Removed sequence (' num2str(length(candidates(c).removedSeqDraft)) 'bp):'];
l=l+1;
len_max_number = length(num2str(candidates(c).removedPosDraft(1)));
remove_seq_p = regexp(candidates(c).removedSeqDraft, ['\w{1,' num2str(len_res) '}'], 'match');
log{l} = [num2str(candidates(c).removedPosDraft(1),'%.f') ' ' remove_seq_p{1}];
for p=2:length(remove_seq_p)
log{l} = [log{l} 10 blanks(len_max_number) ' ' remove_seq_p{p}];
end
log{l} = [log{l} ' ' num2str(candidates(c).removedPosDraft(2),'%.f')];
l=l+1;
if(candidates(c).gapType==1)
log{l} = ['Inserted sequence (' num2str(length(insert_seq)) 'bp):'];
l=l+1;
if(candidates(c).strand==1)
is = candidates(c).insertedPosDtset(1);
ie = candidates(c).insertedPosDtset(2);
else
is = candidates(c).insertedPosDtset(2);
ie = candidates(c).insertedPosDtset(1);
end
len_max_number = length(num2str(is));
insert_seq_p = regexp(insert_seq, ['\w{1,' num2str(len_res) '}'], 'match');
log{l} = [num2str(is,'%.f') ' ' insert_seq_p{1}];
for p=2:length(insert_seq_p)
log{l} = [log{l} 10 blanks(len_max_number) ' ' insert_seq_p{p}];
end
log{l} = [log{l} ' ' num2str(ie,'%.f')];
l=l+1;
end
log{l} = [10 repmat('-',1,80)];
l=l+1;
log_complete{c} = log;
end
end
%%
function [hsps_out] = getHSPs(blast_result,id_blast)
global minScore;
% Output:
%1 id_file
%2 id_contig
%3 Score
%4 eValue
%5 QueryIndices start
%6 QueryIndices end
%7 SubjectIndices start
%8 SubjectIndices end
%9 Strand (1 - Plus/Plus, 2 - Plus/Minus)
%10 id blast_result_filter
%11 id HSP
%12 Identity Percent
%13 Identity Possible (Alignment length)
%14 Identity Match
%15 Query Length
%16 Bit Score
%17 Query Coverage Per HSP
hsps_out = [];
for j=1:length(blast_result)
id = regexp(char(blast_result{j}(2)), '_', 'split');
id_dataset = str2num(id{2});
id_contig = str2num(id{3});
%if (str2num(blast_result{j}{4}) >= minScore)
hsps_out = [hsps_out; ...
id_dataset ...
id_contig ...
str2num(blast_result{j}{4}) ...
str2num(blast_result{j}{5}) ...
str2num(blast_result{j}{10}) ...
str2num(blast_result{j}{12}) ...
str2num(blast_result{j}{13}) ...
str2num(blast_result{j}{15}) ...
verifyStrand(blast_result{j}{9}) ...
id_blast j ...
str2num(blast_result{j}{6}) ...
str2num(blast_result{j}{17}) ...
str2num(blast_result{j}{7}) ...
str2num(blast_result{j}{16}) ...
str2num(blast_result{j}{3}) ...
str2num(blast_result{j}{18}) ...
];
%end
end
end
%%
function [pre_cand] = verifyPreCandidates(pre_candidates,draft_genome_fasta,datasets_fasta)
global gapChar maxInsertLength maxRemoveLength positiveGap zeroGap negativeGap;
cont = 0;
for i=1:length(pre_candidates)
[insert_start insert_end] = getInsertedPosDtset(pre_candidates(i));
% Tipo do gap
if (insert_end-insert_start+1)==0
% ZERO GAP
pre_candidates(i).gapType = 0;
if(~zeroGap) continue; end
elseif (insert_end-insert_start+1)<0
% NEGATIVE GAP
pre_candidates(i).gapType = -1;
if(~negativeGap) continue; end
else
% POSITIVE GAP
pre_candidates(i).gapType = 1;
if(~positiveGap) continue; end
end
% Verifica se nova regiao inserida é menor ou igual ao permitido
if (insert_end-insert_start+1)>maxInsertLength
continue;
end
[remove_start remove_end] = getRemovedPosDraft(pre_candidates(i),draft_genome_fasta);
if (remove_end-remove_start+1) > maxRemoveLength
continue;
end
if(pre_candidates(i).gapType==1)
[~,~,insert_seq] = getInsertedSeqDtset(pre_candidates(i),datasets_fasta(pre_candidates(i).id_DtsetFile).fasta);
% Verifica se possui o char na nova região (fecha gap com outro gap)
if sum(insert_seq==gapChar)>=1
continue;
end
end
cont = cont + 1;
pre_cand(cont) = pre_candidates(i);
end
if ~exist('pre_cand','var')
pre_cand = [];
end
end
%%
function [cand] = selectCandidates(pre_candidates,datasets_fasta)
pc = zeros(length(pre_candidates),8);
for i=1:length(pre_candidates)
p = pre_candidates(i);
pc(i,:) = [i ...
p.id_DraftScaf ...
p.id_DraftChar ...
sum(p.rawScore) ...
sum(p.queryCoverage) ...
sum(p.identitiesPercent) ...
sum(p.eValue) ...
length(datasets_fasta(p.id_DtsetFile).fasta(p.id_DtsetContig).Sequence)];
end
pc = sortrows(pc,[2 3 -4 -5 -6 7 -8]);
[~, idx, ~] = unique(pc(:,2:3),'rows','first');
pc = pc(idx,:);
cand = pre_candidates(pc(:,1));
if ~exist('cand','var')
cand = [];
end
end
%%
function [stats] = getStats(fasta,inline)
global gapChar;
if(inline==1)
separator = 9;
else
separator = 10;
end
c=0;g=0;chars=0;ls=[];
for i=1:length(fasta)
seq = upper(fasta(i).Sequence);
c = c + sum(seq=='C');
g = g + sum(seq=='G');
chars = chars + sum(seq==gapChar);
ls = [ls; length(seq)];
end
lseq = sum(ls);
gc = (c+g) / lseq;
ls = sortrows(ls,-1);
aux_sum = 0;n50 = 0;
h = lseq/2;
for x=1:length(ls)
aux_sum = aux_sum + ls(x);
if(aux_sum >= h)
n50 = ls(x);
break;
end
end
stats = [' Gaps: ' num2str(getTotalChars(fasta),'%.f') separator ' Sequences: ' num2str(length(fasta),'%.f') separator ' Length: ' num2str(lseq,'%.f') 'bp ' separator ' GC: ' num2str(gc*100) '%' separator ' N50: ' num2str(n50,'%.f') separator ' Min: ' num2str(min(ls),'%.f') separator ' Max: ' num2str(max(ls),'%.f') separator ' ' gapChar 's: ' num2str(chars,'%.f')];
end
%%
function [s] = verifyStrand(strand)
% Strand (1 - Plus/Plus, 2 - Plus/Minus)
if strcmp(strand,'plus')
s=1;
elseif strcmp(strand,'minus')
s=2;
end
end
%%
function [s] = verifyStrandRev(strand)
% Strand (1 - Plus/Plus, 2 - Plus/Minus)
if strand==1
s='Plus/Plus';
elseif strand==2
s='Plus/Minus';
end
end
%%
function [sequence_fasta] = fastaUpper(sequence_fasta)
for i=1:length(sequence_fasta)
sequence_fasta(i).Sequence = upper(sequence_fasta(i).Sequence);
end
end
%%
function [char_list] = getChars(sequence)
global gapChar;
char_list = [];
if ~isempty(sequence)
[sn,en] = regexpi(sequence,[gapChar '[' gapChar ']*']);
char_list = [sn' en'];
end
end
%%
function [total] = getTotalChars(sequence_fasta)
total = 0;
for i=1:length(sequence_fasta)
ch = getChars(sequence_fasta(i).Sequence);
if ~isempty(ch)
total = total + length(ch(:,1));
end
end
end
%%
function [n_start n_end] = getPosN(cand,seq)
n_start=[];n_end=[];
N = seq(cand.id_DraftScaf).Pos(cand.id_DraftChar,1:2);
n_start = N(1);
n_end = N(2);
end
%%
function [remove_start remove_end] = getRemovedPosDraft(cand,seq)
[queryA_start queryA_end queryB_start queryB_end] = getRealQueryPos(cand,seq);
remove_start = queryA_end + 1;
remove_end = queryB_start - 1;
% Ajusta caso possua alinhamento negativo
if(cand.gapType==-1)
openQueryA= 0;
openSubjectA = 0;
% Identifica posições no alinhamento em relação ao lado A
dtsetA_min = min(cand.subjectIndices(1:2));
dtsetA_max = max(cand.subjectIndices(1:2));
if(cand.strand(1)==1)
A_st = cand.subjectIndices(1) - dtsetA_min + 1;
B_st = cand.subjectIndices(3) - dtsetA_min + 1;
elseif(cand.strand(1)==2)
A_st = dtsetA_max - cand.subjectIndices(1) + 1;
B_st = dtsetA_max - cand.subjectIndices(3) + 1;
end
A_en = A_st + length(cand.alignmentBlastSubject{1}) -1;
B_en = B_st + length(cand.alignmentBlastSubject{2}) -1;
% Apenas quando há sobreposição
if B_en > A_st
% Conta número de opengaps na sobreposição
p = sort([A_st A_en B_st B_en]);
openQueryA = length(regexp(cand.alignmentBlastQuery{1}(p(2):p(3)),'-'));
openSubjectA = length(regexp(cand.alignmentBlastSubject{1}(p(2):p(3)),'-'));
end
remove_start = remove_start - (abs(cand.subjectIndices(2) - cand.subjectIndices(3)) + 1) + openQueryA - openSubjectA;
if remove_start<1 remove_start=1; end
end
end
%%
function [remove_start remove_end remove_seq] = getRemovedSeqDraft(cand,seq)
[remove_start remove_end] = getRemovedPosDraft(cand,seq);
if remove_start>0 && remove_end>0 && remove_end>=remove_start
remove_seq = seq(cand.id_DraftScaf).Sequence(remove_start:remove_end);
else
remove_seq = [];
end
end
%%
function [insert_start insert_end] = getInsertedPosDtset(cand)
if(cand.strand(1)==1)
insert_start = cand.subjectIndices(2)+1;
insert_end = cand.subjectIndices(3)-1;
elseif(cand.strand(1)==2)
insert_start = cand.subjectIndices(3)+1;
insert_end = cand.subjectIndices(2)-1;
end
end
%%
function [insert_start insert_end insert_seq] = getInsertedSeqDtset(cand,seq)
[insert_start insert_end] = getInsertedPosDtset(cand);
insert_seq = [];
if insert_end >= insert_start
if(cand.strand(1)==1)
insert_seq = seq(cand.id_DtsetContig).Sequence(insert_start:insert_end);
elseif(cand.strand(1)==2)
insert_seq = seqrcomplement2(seq(cand.id_DtsetContig).Sequence(insert_start:insert_end));
end
end
end
%%
function [queryA_start queryA_end queryB_start queryB_end] = getRealQueryPos(cand,seq)
global edgeTrimLength;
[n_start n_end] = getPosN(cand,seq);
queryA_start = n_start - edgeTrimLength - cand.lengthcontigEndLengths(1) + cand.queryIndices(1) - 1;
queryA_end = n_start - edgeTrimLength - cand.lengthcontigEndLengths(1) + cand.queryIndices(1) + length(regexp(cand.alignmentBlastQuery{1},'[^-]')) - 2;
queryB_start = n_end + edgeTrimLength + cand.queryIndices(3);
queryB_end = n_end + edgeTrimLength + cand.queryIndices(3) + length(regexp(cand.alignmentBlastQuery{2},'[^-]')) - 1;
end
%%
function [name] = gapTypeName(gapType)
if(gapType==-1)
name = 'Negative gap';
elseif(gapType==0)
name = 'Zero gap';
elseif(gapType==1)
name = 'Positive gap';
end
end
%%
function [filename] = hidePath(filepath)
%[~,n,e] = fileparts(filepath);
%filename = [n e];
filename = filepath;
end
%%
function fastawrite2(filename, fastadata)
len_line = 60;
fid = fopen(filename,'w');
for i=1:length(fastadata)
fprintf(fid,'>%s\n',fastadata(i).Header);
len_seq = length(fastadata(i).Sequence);
for s=1:len_line:len_seq
if(s+len_line>len_seq)
e = len_seq;
else
e = s+len_line-1;
end
fprintf(fid,'%s\n',fastadata(i).Sequence(s:e));
end
end
fclose(fid);
end
%%
function fastawritefast(filename, fastadata)
text = '';
for d=1:length(fastadata)
text = [text '>' fastadata(d).Header 10 fastadata(d).Sequence 10];
end
fid = fopen(filename,'w');
fprintf(fid,'%s',text);
fclose(fid);
end
%%
function [fasta] = fastaread2(filename)
i = 1;
fid = fopen(filename);
l = fgets(fid);
while l > -1
fasta(i).Header = l(2:end-1);
l = fscanf(fid, '%[^>]s');
l(find(l==char(13) | l==char(10) | l==' ')) = [];
fasta(i).Sequence = l;
i = i + 1;
l = fgets(fid);
end
fclose(fid);
end
%%
function [bool] = isFasta(filename)
fid = fopen(filename);
l = fgets(fid);
if (l(1)~='>')
bool=0;
else
bool=1;
end
fclose(fid);
end
%%
function [draft_genome_fasta error_msg] = loadDraftFile(draftFile)
error_msg='';
disp([10 'Reading draft: ' draftFile]);
draft_genome_fasta = fastaUpper(fastaread2(draftFile));
if(getTotalChars(draft_genome_fasta)==0)
error_msg = ['Draft file ' draftFile ' does not have gaps'];
return;
end
end
%%
function [datasets_fasta error_msg] = loadDatasetsFiles(datasetsFiles)
global stats saveDatasetsPath loadDatasetsPath;
error_msg='';
ds = regexp(datasetsFiles,',','split');
% Caso esteja carregando os datasets de arquivo salvo
if ~isempty(loadDatasetsPath)
disp(['Loading datasets: ' loadDatasetsPath]);
if 1==1
end
load([loadDatasetsPath '.mat']);
for d=1:length(datasets_fasta)
disp([' - ' datasets_fasta(d).file ' loaded']);
end
else
% Caso rodando pela primeira vez e salvando
if ~isempty(saveDatasetsPath)
ds = ds(1:end-1);
end
% Carrega arquivos
for dt = 1:length(ds)
disp(['Reading dataset: ' char(ds(dt))]);
datasets_fasta(dt).file = char(ds(dt));
datasets_fasta(dt).fasta = fastaUpper(fastaread2(char(ds(dt))));
end
% Caso rodando pela primeira vez e salvando
if ~isempty(saveDatasetsPath)
disp(['Saving datasets: ' saveDatasetsPath]);
pause(0.001);
save([saveDatasetsPath '.mat'],'datasets_fasta','-v7.3');
end
end
stats.datasetCount(length(datasets_fasta)) = 0;
end
%%
function [error_msg] = buildDatabase(datasets_fasta)
global tmp_folder blastPath saveDatasetsPath loadDatasetsPath;
error_msg='';
if ~isempty(loadDatasetsPath)
disp('Loading database ...');
else
% Salva em arquivo específico ou temporário
if ~isempty(saveDatasetsPath)
dboutputfolder = saveDatasetsPath;
else
dboutputfolder = [tmp_folder 'datasets'];
end
disp('Building database ...');
% Monta fasta para banco
cont = 0;
for dt=1:length(datasets_fasta)
for i=1:length(datasets_fasta(dt).fasta)
if(~isempty(datasets_fasta(dt).fasta(i).Sequence))
% Para arquivo fasta
cont = cont + 1;
datasets(cont).Header = ['dataset_' num2str(dt) '_' num2str(i)];
datasets(cont).Sequence = datasets_fasta(dt).fasta(i).Sequence;
end
end
end
fastawrite2([tmp_folder 'datasets.fasta'], datasets);
makeblastdb = ['-dbtype nucl -in ' tmp_folder 'datasets.fasta -out ' dboutputfolder ' -title datasets -logfile ' tmp_folder 'makeblastdb.log'];
[makeblastdbStatus, makeblastdbResult] = system([blastPath 'makeblastdb ' makeblastdb]);
if makeblastdbStatus>0
error_msg = ['Error MAKEBLASTDB: ' makeblastdbResult];
return;
end
end
end
%%
function [draft_genome_fasta error_msg] = identifyGaps(draft_genome_fasta)
% Identifica gaps (0-inicial, 1-candidato, 2-fechado, -1-não fechado/pular)
error_msg='';
for i = 1:length(draft_genome_fasta)
chars = getChars(draft_genome_fasta(i).Sequence);
if ~isempty(chars)
lc = length(chars(:,1));
c = 1:lc;
chars = [chars c' zeros(lc,1)];
end
draft_genome_fasta(i).Pos = chars;
end
end
%%
function writeStats(draftFile,datasets_fasta,log_round,elapsed)
global stats stats_file minScore maxEValue minIdentity contigEndLength edgeTrimLength ...
gapChar maxRemoveLength maxInsertLength blastAlignParam blastMaxResults blastPath threads ...
outputPrefix moreOutput version blastnAlgorithm makeblastdbAlgorithm positiveGap zeroGap negativeGap ...
saveDatasetsPath loadDatasetsPath;
fid = fopen(stats_file, 'a');
fprintf(fid, '%s GENERAL STATS %s\n',repmat('-',1,20),repmat('-',1,20));
fprintf(fid, '\nClosed gaps (%s): %s\n\n', gapChar, num2str(stats.totalGapsClosed) );
fprintf(fid, 'Before FGAP: \n%s\n\n', stats.before );
fprintf(fid, 'After FGAP: \n%s\n\n', stats.after);
fprintf(fid, 'Inserted: %sbp\n', num2str(stats.insertedBases,'%.f'));
fprintf(fid, 'Removed : %sbp\n\n', num2str(stats.removedBases,'%.f'));
fprintf(fid, 'Closed gaps by each dataset:\n');
for i=1:length(datasets_fasta)
fprintf(fid, ' %s: %s gaps\n', hidePath(datasets_fasta(i).file), num2str(stats.datasetCount(i),'%.f'));
end
fprintf(fid, '\nClosed gaps by type:\n');
for i=1:3
fprintf(fid, ' %s: %s gaps\n', gapTypeName(i-2), num2str(stats.typeCount(i),'%.f'));
end
if(~isempty(log_round))
fprintf(fid, '\n%s STATS PER ROUND %s\n\n',repmat('-',1,20),repmat('-',1,20));
for j=1:length(log_round)
fprintf(fid, '%s\n', log_round(j).log);
end
end
fprintf(fid, '%s PARAMETERS %s\n\n',repmat('-',1,20),repmat('-',1,20));
fprintf(fid, '\tdraftFile: %s\n', hidePath(draftFile));
if ~isempty(loadDatasetsPath)
fprintf(fid, '\tDatasets loaded: %s\n', loadDatasetsPath);
end
for i=1:length(datasets_fasta)
fprintf(fid, '\tdatasetsFiles: %s\n', hidePath(datasets_fasta(i).file));
end
if ~isempty(saveDatasetsPath)
fprintf(fid, '\tDatasets saved: %s\n', saveDatasetsPath);
end
fprintf(fid, '\tminScore: %s\n', num2str(minScore));
fprintf(fid, '\tmaxEValue: %s\n', num2str(maxEValue));
fprintf(fid, '\tminIdentity: %s\n', num2str(minIdentity));
fprintf(fid, '\tcontigEndLength: %s\n', num2str(contigEndLength));
fprintf(fid, '\tedgeTrimLength: %s\n', num2str(edgeTrimLength));
fprintf(fid, '\tmaxRemoveLength: %s\n', num2str(maxRemoveLength));
fprintf(fid, '\tmaxInsertLength: %s\n', num2str(maxInsertLength));
fprintf(fid, '\tpositiveGap: %s\n', num2str(positiveGap));
fprintf(fid, '\tzeroGap: %s\n', num2str(zeroGap));
fprintf(fid, '\tnegativeGap: %s\n', num2str(negativeGap));
fprintf(fid, '\tgapChar: %s\n', gapChar);
fprintf(fid, '\tblastPath: %s\n', num2str(blastPath));
fprintf(fid, '\tblastAlignParam: %s\n', num2str(blastAlignParam));
fprintf(fid, '\tblastMaxResults: %s\n', num2str(blastMaxResults));
fprintf(fid, '\tthreads: %s\n', num2str(threads));
fprintf(fid, '\tmoreOutput: %s\n', num2str(moreOutput));
fprintf(fid, '\toutputPrefix: %s\n\n', hidePath(outputPrefix));
fprintf(fid, '%s\n',repmat('-',1,50));
fprintf(fid, '\n%s\n', elapsed);
fprintf(fid, '%s\n', datestr(now));
fprintf(fid, 'FGAP v%s\n', version);
fprintf(fid, '%s\n', makeblastdbAlgorithm);
fprintf(fid, '%s\n', blastnAlgorithm);
fclose(fid);
end
%%
function [more_before more_after] = generateMoreOutput(candidates,pre_draft_genome_fasta)
for c=1:length(candidates)
gap_id = getGapId(candidates(c));
chars = getChars(candidates(c).removedSeqDraft);
total_chars = length(chars(:,1));
more_id = [gap_id '|' num2str(candidates(c).gapType) '|' num2str(total_chars,'%.f')];
[more_before(c).Sequence gap_start gap_end] = generateBeforeSequence(candidates(c),pre_draft_genome_fasta);
more_before(c).Header = [more_id '|' num2str(gap_start,'%.f') '|' num2str(gap_end,'%.f')];
[more_after(c).Sequence insert_start insert_end] = generateAfterSequence(candidates(c),pre_draft_genome_fasta);
more_after(c).Header = [more_id '|' num2str(insert_start,'%.f') '|' num2str(insert_end,'%.f')];
end
end
%%
function writeMoreOutput(more_before,out_more_before,more_after,out_more_after)
more_before_all = [];
more_after_all = [];
for i=1:length(more_before)
more_before_all = [more_before_all more_before{i}];
more_after_all = [more_after_all more_after{i}];
end
if ~isempty(out_more_before)
fastawrite2(out_more_before,more_before_all);
fastawrite2(out_more_after,more_after_all);
end
end
%%
function writeLog(out_log,log)
fid = fopen(out_log, 'wt');
for i=1:length(log)
fprintf(fid, '%s\n', log{i}{:});
end
fclose(fid);
end
%%
function writeFasta(out_fasta, draft_genome_fasta)
fastawrite2(out_fasta, draft_genome_fasta);
end
%%
function [gap_id] = getGapId(cand)
gap_id = [num2str(cand.id_DraftScaf) '_' num2str(cand.id_DraftChar)];
end
%%
function [after_seq insert_start insert_end] = generateAfterSequence(cand,pre_draft_genome_fasta)
global gapChar plusBasesMoreOutput;
len_seq = length(pre_draft_genome_fasta(cand.id_DraftScaf).Sequence);
if(cand.gapType==-1)
insert_start = 0;
insert_end = 0;
st_plus = cand.removedPosDraft(1) - plusBasesMoreOutput;
if st_plus < 1 st_plus=1; end
en_plus = cand.removedPosDraft(2) + plusBasesMoreOutput;
if en_plus > len_seq en_plus = len_seq; end
after_seq = [pre_draft_genome_fasta(cand.id_DraftScaf).Sequence(st_plus:cand.removedPosDraft(1)-1) ...
pre_draft_genome_fasta(cand.id_DraftScaf).Sequence(cand.removedPosDraft(2)+1:en_plus)];
%Condensa gaps das pontas para melhorar validação
after_seq = regexprep(after_seq,[gapChar '[' gapChar ']*'],gapChar);
else
len_seq = length(pre_draft_genome_fasta(cand.id_DraftScaf).Sequence);
st_plus = cand.removedPosDraft(1) - plusBasesMoreOutput;
if st_plus < 1 st_plus=1; end
en_plus = cand.removedPosDraft(2) + plusBasesMoreOutput;
if en_plus > len_seq en_plus = len_seq; end
pre_seq = pre_draft_genome_fasta(cand.id_DraftScaf).Sequence(st_plus:cand.removedPosDraft(1)-1);
pos_seq = pre_draft_genome_fasta(cand.id_DraftScaf).Sequence(cand.removedPosDraft(2)+1:en_plus);
% Retira sequencia caso possua N nos contigsEnds para fazer validação
[~,n_pre_en] = regexpi(pre_seq,[gapChar '[' gapChar ']*']);
if ~isempty(n_pre_en)
pre_seq = pre_seq(n_pre_en(length(n_pre_en))+1:end);
end
[n_pos_st,~] = regexpi(pos_seq,[gapChar '[' gapChar ']*']);
if ~isempty(n_pos_st)
pos_seq = pos_seq(1:n_pos_st(1)-1);
end
after_seq = [pre_seq lower(cand.insertedSeqDtset) pos_seq ];
insert_start = length(pre_seq)+1;
insert_end = insert_start + length(cand.insertedSeqDtset) - 1;
%Condensa gaps das pontas para melhorar validação
%after_seq = regexprep(after_seq,[gapChar '[' gapChar ']*'],gapChar);
end
end
%%
function [before_seq gap_start gap_end] = generateBeforeSequence(cand,pre_draft_genome_fasta)
global edgeTrimLength plusBasesMoreOutput;
len_seq = length(pre_draft_genome_fasta(cand.id_DraftScaf).Sequence);
[n_start n_end] = getPosN(cand,pre_draft_genome_fasta);
st_plus = n_start - edgeTrimLength - plusBasesMoreOutput;
if st_plus < 1 st_plus=1; end
en_plus = n_end + edgeTrimLength + plusBasesMoreOutput;
if en_plus > len_seq en_plus = len_seq; end
before_seq = pre_draft_genome_fasta(cand.id_DraftScaf).Sequence(st_plus:en_plus);
gap_start = edgeTrimLength + plusBasesMoreOutput + 1;
gap_end = gap_start + (n_end - n_start);
end
%%
function [seqrc] = seqrcomplement2(seq)
%Inverte
seqr = seq(end:-1:1);
seqrc = ones(1,length(seqr));
l = {'A','C','G','T','R','Y','K','M','S','W','B','D','H','V','N','-','*'};
t = {'T','G','C','A','Y','R','M','K','S','W','V','H','D','B','N','-','*'};
for i=1:length(l)
seqrc(seqr==l{i})=t{i};
end
seqrc = char(seqrc);
end
%%
function [] = showHelp()
disp([ 10 'Usage in command-line mode (compiled): ./run_fgap.sh <MCR installation folder> -d <draft file> -a "<dataset(s) file(s)>" [parameters]']);
disp(['Usage in Matlab/Octave (source): fgap -d <draft file> -a ''<dataset(s) file(s)>'' [parameters]' 10]);
disp(['-d /--draft-file' 9 'Draft genome file [fasta format - Ex: ''draft.fasta'']']);
disp(['-a /--datasets-files' 9 'List of datasets files to close gaps [fasta format - Ex: ''dataset1.fasta,dataset2.fasta'']' 10]);
%disp(['--save-datasets']);
%disp(['--load-datasets']);
disp(['-s /--min-score' 9 9 'Min Score (raw) to return results from BLAST (integer) - Default: 25']);
disp(['-e /--max-evalue' 9 'Max E-Value to return results from BLAST (float) - Default: 1e-7']);
disp(['-i /--min-identity' 9 'Min identity (%) to return results from BLAST (integer [0-100]) - Default: 70' 10]);
disp(['-C /--contig-end-length' 9 'Length (bp) of contig ends to perform BLAST alignment (integer) - Default: 300']);
disp(['-T /--edge-trim-length' 9 'Length of ignored bases (bp) upstream and downstrem of the gap (integer) - Default: 0']);
disp(['-R /--max-remove-length' 9 'Max number of bases (bp) that can be removed (integer) - Default: 500']);
disp(['-I /--max-insert-length' 9 'Max number of bases (bp) that can be inserted (integer) - Default: 500' 10]);
disp(['-p /--positive-gap' 9 'Enable closing of positive gaps (with insertion) (integer [0-1]) - Default: 1']);
disp(['-z /--zero-gap' 9 9 'Enable closing of zero gaps (without insert any base) (integer [0-1]) - Default: 0']);
disp(['-g /--negative-gap' 9 'Enable closing of negative gaps (overlapping contig ends) (integer [0-1]) - Default: 0' 10]);
disp(['-c /--gap-char' 9 9 9 9 'Base that represents the gap (char) - Default: ''N''']);
disp(['-b /--blast-path' 9 9 9 'Blast+ package path (only makeblastdb and blastn are needed, version 2.2.28+ or higher) - Default: ''''']);
disp(['-l /--blast-alignment-parameters' 9 'BLAST alignment parameters (opengap,extendgap,match,mismatch,wordsize) - Default: ''1,1,1,-3,15''']);
disp(['-r /--blast-max-results' 9 9 9 'Max results from BLAST for each query (integer) - Default: 200']);
disp(['-t /--threads' 9 9 9 9 'Number of threads (integer) - Default: 1' 10]);
disp(['-m /--more-output' 9 'More output files with gap regions after and before gap closing (integer [0-1]) - Default: 0']);
disp(['-o /--output-prefix' 9 'Output prefix [File or folder - Ex: ''out'' or ''out_folder/out'' ] - Default: ''output_fgap''']);
disp(['-h /--help' 9 9 'This help message']);
end
|
github
|
rashwin1989/plicFoam-master
|
umfpack_report.m
|
.m
|
plicFoam-master/UMFPACK/MATLAB/umfpack_report.m
| 16,015 |
utf_8
|
ab2ab9204411376267d5931f57b6b59b
|
function umfpack_report (Control, Info)
%UMFPACK_REPORT prints optional control settings and statistics
%
% Example:
% umfpack_report (Control, Info) ;
%
% Prints the current Control settings for umfpack2, and the statistical
% information returned by umfpack2 in the Info array. If Control is
% an empty matrix, then the default control settings are printed.
%
% Control is 20-by-1, and Info is 90-by-1. Not all entries are used.
%
% Alternative usages:
%
% umfpack_report ([ ], Info) ; print the default control parameters
% and the Info array.
% umfpack_report (Control) ; print the control parameters only.
% umfpack_report ; print the default control parameters
% and an empty Info array.
%
% See also umfpack, umfpack2, umfpack_make, umfpack_details,
% umfpack_demo, and umfpack_simple.
% Copyright 1995-2007 by Timothy A. Davis.
%-------------------------------------------------------------------------------
% get inputs, use defaults if input arguments not present
%-------------------------------------------------------------------------------
% The contents of Control and Info are defined in umfpack.h
if (nargin < 1)
Control = [] ;
end
if (nargin < 2)
Info = [] ;
end
if (isempty (Control))
Control = umfpack2 ;
end
if (isempty (Info))
Info = [ 0 (-ones (1, 89)) ] ;
end
%-------------------------------------------------------------------------------
% control settings
%-------------------------------------------------------------------------------
fprintf ('\nUMFPACK: Control settings:\n\n') ;
fprintf (' Control (1): print level: %d\n', Control (1)) ;
fprintf (' Control (2): dense row parameter: %g\n', Control (2)) ;
fprintf (' "dense" rows have > max (16, (%g)*16*sqrt(n_col)) entries\n', Control (2)) ;
fprintf (' Control (3): dense column parameter: %g\n', Control (3)) ;
fprintf (' "dense" columns have > max (16, (%g)*16*sqrt(n_row)) entries\n', Control (3)) ;
fprintf (' Control (4): pivot tolerance: %g\n', Control (4)) ;
fprintf (' Control (5): max block size for dense matrix kernels: %d\n', Control (5)) ;
prstrat (' Control (6): strategy: %g ', Control (6)) ;
fprintf (' Control (7): initial allocation ratio: %g\n', Control (7)) ;
fprintf (' Control (8): max iterative refinement steps: %d\n', Control (8)) ;
fprintf (' Control (13): 2-by-2 pivot tolerance: %g\n', Control (13)) ;
fprintf (' Control (14): Q fixed during numeric factorization: %g ', Control (14)) ;
if (Control (14) > 0)
fprintf ('(yes)\n') ;
elseif (Control (14) < 0)
fprintf ('(no)\n') ;
else
fprintf ('(auto)\n') ;
end
fprintf (' Control (15): AMD dense row/column parameter: %g\n', Control (15)) ;
fprintf (' "dense" rows/columns in A+A'' have > max (16, (%g)*sqrt(n)) entries.\n', Control (15)) ;
fprintf (' Only used if the AMD ordering is used.\n') ;
fprintf (' Control (16): diagonal pivot tolerance: %g\n', Control (16)) ;
fprintf (' Only used if diagonal pivoting is attempted.\n') ;
fprintf (' Control (17): scaling option: %g ', Control (17)) ;
if (Control (17) == 0)
fprintf ('(none)\n') ;
elseif (Control (17) == 2)
fprintf ('(scale the matrix by\n') ;
fprintf (' dividing each row by max. abs. value in each row)\n') ;
else
fprintf ('(scale the matrix by\n') ;
fprintf (' dividing each row by sum of abs. values in each row)\n') ;
end
fprintf (' Control (18): frontal matrix allocation ratio: %g\n', Control (18)) ;
fprintf (' Control (19): drop tolerance: %g\n', Control (19)) ;
fprintf (' Control (20): AMD and COLAMD aggressive absorption: %g ', Control (20)) ;
yes_no (Control (20)) ;
% compile-time options:
fprintf ('\n The following options can only be changed at compile-time:\n') ;
if (Control (9) == 1)
fprintf (' Control (9): compiled to use the BLAS\n') ;
else
fprintf (' Control (9): compiled without the BLAS\n') ;
fprintf (' (you will not get the best possible performance)\n') ;
end
if (Control (10) == 1)
fprintf (' Control (10): compiled for MATLAB\n') ;
elseif (Control (10) == 2)
fprintf (' Control (10): compiled for MATLAB\n') ;
else
fprintf (' Control (10): not compiled for MATLAB\n') ;
fprintf (' Printing will be in terms of 0-based matrix indexing,\n') ;
fprintf (' not 1-based as is expected in MATLAB. Diary output may\n') ;
fprintf (' not be properly recorded.\n') ;
end
if (Control (11) == 2)
fprintf (' Control (11): uses POSIX times ( ) to get CPU time and wallclock time.\n') ;
elseif (Control (11) == 1)
fprintf (' Control (11): uses getrusage to get CPU time.\n') ;
else
fprintf (' Control (11): uses ANSI C clock to get CPU time.\n') ;
fprintf (' The CPU time may wrap around, type "help cputime".\n') ;
end
if (Control (12) == 1)
fprintf (' Control (12): compiled with debugging enabled\n') ;
fprintf (' ###########################################\n') ;
fprintf (' ### This will be exceedingly slow! ########\n') ;
fprintf (' ###########################################\n') ;
else
fprintf (' Control (12): compiled for normal operation (no debugging)\n') ;
end
%-------------------------------------------------------------------------------
% Info:
%-------------------------------------------------------------------------------
if (nargin == 1)
return
end
status = Info (1) ;
fprintf ('\nUMFPACK status: Info (1): %d, ', status) ;
if (status == 0)
fprintf ('OK\n') ;
elseif (status == 1)
fprintf ('WARNING matrix is singular\n') ;
elseif (status == -1)
fprintf ('ERROR out of memory\n') ;
elseif (status == -3)
fprintf ('ERROR numeric LU factorization is invalid\n') ;
elseif (status == -4)
fprintf ('ERROR symbolic LU factorization is invalid\n') ;
elseif (status == -5)
fprintf ('ERROR required argument is missing\n') ;
elseif (status == -6)
fprintf ('ERROR n <= 0\n') ;
elseif (status <= -7 & status >= -12 | status == -14) %#ok
fprintf ('ERROR matrix A is corrupted\n') ;
elseif (status == -13)
fprintf ('ERROR invalid system\n') ;
elseif (status == -15)
fprintf ('ERROR invalid permutation\n') ;
elseif (status == -911)
fprintf ('ERROR internal error!\n') ;
fprintf ('Please report this error to Tim Davis ([email protected])\n') ;
else
fprintf ('ERROR unrecognized error. Info array corrupted\n') ;
end
fprintf (' (a -1 means the entry has not been computed):\n') ;
fprintf ('\n Basic statistics:\n') ;
fprintf (' Info (2): %d, # of rows of A\n', Info (2)) ;
fprintf (' Info (17): %d, # of columns of A\n', Info (17)) ;
fprintf (' Info (3): %d, nnz (A)\n', Info (3)) ;
fprintf (' Info (4): %d, Unit size, in bytes, for memory usage reported below\n', Info (4)) ;
fprintf (' Info (5): %d, size of int (in bytes)\n', Info (5)) ;
fprintf (' Info (6): %d, size of UF_long (in bytes)\n', Info (6)) ;
fprintf (' Info (7): %d, size of pointer (in bytes)\n', Info (7)) ;
fprintf (' Info (8): %d, size of numerical entry (in bytes)\n', Info (8)) ;
fprintf ('\n Pivots with zero Markowitz cost removed to obtain submatrix S:\n') ;
fprintf (' Info (57): %d, # of pivots with one entry in pivot column\n', Info (57)) ;
fprintf (' Info (58): %d, # of pivots with one entry in pivot row\n', Info (58)) ;
fprintf (' Info (59): %d, # of rows/columns in submatrix S (if square)\n', Info (59)) ;
fprintf (' Info (60): ') ;
if (Info (60) > 0)
fprintf ('submatrix S square and diagonal preserved\n') ;
elseif (Info (60) == 0)
fprintf ('submatrix S not square or diagonal not preserved\n') ;
else
fprintf ('\n') ;
end
fprintf (' Info (9): %d, # of "dense" rows in S\n', Info (9)) ;
fprintf (' Info (10): %d, # of empty rows in S\n', Info (10)) ;
fprintf (' Info (11): %d, # of "dense" columns in S\n', Info (11)) ;
fprintf (' Info (12): %d, # of empty columns in S\n', Info (12)) ;
fprintf (' Info (34): %g, symmetry of pattern of S\n', Info (34)) ;
fprintf (' Info (35): %d, # of off-diagonal nonzeros in S+S''\n', Info (35)) ;
fprintf (' Info (36): %d, nnz (diag (S))\n', Info (36)) ;
fprintf ('\n 2-by-2 pivoting to place large entries on diagonal:\n') ;
fprintf (' Info (52): %d, # of small diagonal entries of S\n', Info (52)) ;
fprintf (' Info (53): %d, # of unmatched small diagonal entries\n', Info (53)) ;
fprintf (' Info (54): %g, symmetry of P2*S\n', Info (54)) ;
fprintf (' Info (55): %d, # of off-diagonal entries in (P2*S)+(P2*S)''\n', Info (55)) ;
fprintf (' Info (56): %d, nnz (diag (P2*S))\n', Info (56)) ;
fprintf ('\n AMD results, for strict diagonal pivoting:\n') ;
fprintf (' Info (37): %d, est. nz in L and U\n', Info (37)) ;
fprintf (' Info (38): %g, est. flop count\n', Info (38)) ;
fprintf (' Info (39): %g, # of "dense" rows in S+S''\n', Info (39)) ;
fprintf (' Info (40): %g, est. max. nz in any column of L\n', Info (40)) ;
fprintf ('\n Final strategy selection, based on the analysis above:\n') ;
prstrat (' Info (19): %d, strategy used ', Info (19)) ;
fprintf (' Info (20): %d, ordering used ', Info (20)) ;
if (Info (20) == 0)
fprintf ('(COLAMD on A)\n') ;
elseif (Info (20) == 1)
fprintf ('(AMD on A+A'')\n') ;
elseif (Info (20) == 2)
fprintf ('(provided by user)\n') ;
else
fprintf ('(undefined ordering option)\n') ;
end
fprintf (' Info (32): %d, Q fixed during numeric factorization: ', Info (32)) ;
yes_no (Info (32)) ;
fprintf (' Info (33): %d, prefer diagonal pivoting: ', Info (33)) ;
yes_no (Info (33)) ;
fprintf ('\n symbolic analysis time and memory usage:\n') ;
fprintf (' Info (13): %d, defragmentations during symbolic analysis\n', Info (13)) ;
fprintf (' Info (14): %d, memory used during symbolic analysis (Units)\n', Info (14)) ;
fprintf (' Info (15): %d, final size of symbolic factors (Units)\n', Info (15)) ;
fprintf (' Info (16): %.2f, symbolic analysis CPU time (seconds)\n', Info (16)) ;
fprintf (' Info (18): %.2f, symbolic analysis wall clock time (seconds)\n', Info (18)) ;
fprintf ('\n Estimates computed in the symbolic analysis:\n') ;
fprintf (' Info (21): %d, est. size of LU factors (Units)\n', Info (21)) ;
fprintf (' Info (22): %d, est. total peak memory usage (Units)\n', Info (22)) ;
fprintf (' Info (23): %d, est. factorization flop count\n', Info (23)) ;
fprintf (' Info (24): %d, est. nnz (L)\n', Info (24)) ;
fprintf (' Info (25): %d, est. nnz (U)\n', Info (25)) ;
fprintf (' Info (26): %d, est. initial size, variable-part of LU (Units)\n', Info (26)) ;
fprintf (' Info (27): %d, est. peak size, of variable-part of LU (Units)\n', Info (27)) ;
fprintf (' Info (28): %d, est. final size, of variable-part of LU (Units)\n', Info (28)) ;
fprintf (' Info (29): %d, est. max frontal matrix size (# of entries)\n', Info (29)) ;
fprintf (' Info (30): %d, est. max # of rows in frontal matrix\n', Info (30)) ;
fprintf (' Info (31): %d, est. max # of columns in frontal matrix\n', Info (31)) ;
fprintf ('\n Computed in the numeric factorization (estimates shown above):\n') ;
fprintf (' Info (41): %d, size of LU factors (Units)\n', Info (41)) ;
fprintf (' Info (42): %d, total peak memory usage (Units)\n', Info (42)) ;
fprintf (' Info (43): %d, factorization flop count\n', Info (43)) ;
fprintf (' Info (44): %d, nnz (L)\n', Info (44)) ;
fprintf (' Info (45): %d, nnz (U)\n', Info (45)) ;
fprintf (' Info (46): %d, initial size of variable-part of LU (Units)\n', Info (46)) ;
fprintf (' Info (47): %d, peak size of variable-part of LU (Units)\n', Info (47)) ;
fprintf (' Info (48): %d, final size of variable-part of LU (Units)\n', Info (48)) ;
fprintf (' Info (49): %d, max frontal matrix size (# of numerical entries)\n', Info (49)) ;
fprintf (' Info (50): %d, max # of rows in frontal matrix\n', Info (50)) ;
fprintf (' Info (51): %d, max # of columns in frontal matrix\n', Info (51)) ;
fprintf ('\n Computed in the numeric factorization (no estimates computed a priori):\n') ;
fprintf (' Info (61): %d, defragmentations during numeric factorization\n', Info (61)) ;
fprintf (' Info (62): %d, reallocations during numeric factorization\n', Info (62)) ;
fprintf (' Info (63): %d, costly reallocations during numeric factorization\n', Info (63)) ;
fprintf (' Info (64): %d, integer indices in compressed pattern of L and U\n', Info (64)) ;
fprintf (' Info (65): %d, numerical values stored in L and U\n', Info (65)) ;
fprintf (' Info (66): %.2f, numeric factorization CPU time (seconds)\n', Info (66)) ;
fprintf (' Info (76): %.2f, numeric factorization wall clock time (seconds)\n', Info (76)) ;
if (Info (66) > 0.05 & Info (43) > 0) %#ok
fprintf (' mflops in numeric factorization phase: %.2f\n', 1e-6 * Info (43) / Info (66)) ;
end
fprintf (' Info (67): %d, nnz (diag (U))\n', Info (67)) ;
fprintf (' Info (68): %g, reciprocal condition number estimate\n', Info (68)) ;
fprintf (' Info (69): %g, matrix was ', Info (69)) ;
if (Info (69) == 0)
fprintf ('not scaled\n') ;
elseif (Info (69) == 2)
fprintf ('scaled (row max)\n') ;
else
fprintf ('scaled (row sum)\n') ;
end
fprintf (' Info (70): %g, min. scale factor of rows of A\n', Info (70)) ;
fprintf (' Info (71): %g, max. scale factor of rows of A\n', Info (71)) ;
fprintf (' Info (72): %g, min. abs. on diagonal of U\n', Info (72)) ;
fprintf (' Info (73): %g, max. abs. on diagonal of U\n', Info (73)) ;
fprintf (' Info (74): %g, initial allocation parameter used\n', Info (74)) ;
fprintf (' Info (75): %g, # of forced updates due to frontal growth\n', Info (75)) ;
fprintf (' Info (77): %d, # of off-diaogonal pivots\n', Info (77)) ;
fprintf (' Info (78): %d, nnz (L), if no small entries dropped\n', Info (78)) ;
fprintf (' Info (79): %d, nnz (U), if no small entries dropped\n', Info (79)) ;
fprintf (' Info (80): %d, # of small entries dropped\n', Info (80)) ;
fprintf ('\n Computed in the solve step:\n') ;
fprintf (' Info (81): %d, iterative refinement steps taken\n', Info (81)) ;
fprintf (' Info (82): %d, iterative refinement steps attempted\n', Info (82)) ;
fprintf (' Info (83): %g, omega(1), sparse-backward error estimate\n', Info (83)) ;
fprintf (' Info (84): %g, omega(2), sparse-backward error estimate\n', Info (84)) ;
fprintf (' Info (85): %d, solve flop count\n', Info (85)) ;
fprintf (' Info (86): %.2f, solve CPU time (seconds)\n', Info (86)) ;
fprintf (' Info (87): %.2f, solve wall clock time (seconds)\n', Info (87)) ;
fprintf ('\n Info (88:90): unused\n\n') ;
%-------------------------------------------------------------------------------
function prstrat (fmt, strategy)
% prstrat print the ordering strategy
fprintf (fmt, strategy) ;
if (strategy == 1)
fprintf ('(unsymmetric)\n') ;
fprintf (' Q = COLAMD (A), Q refined during numerical\n') ;
fprintf (' factorization, and no attempt at diagonal pivoting.\n') ;
elseif (strategy == 2)
fprintf ('(symmetric, with 2-by-2 pivoting)\n') ;
fprintf (' P2 = row permutation to place large values on the diagonal\n') ;
fprintf (' Q = AMD (P2*A+(P2*A)''), Q not refined during numeric factorization,\n') ;
fprintf (' and diagonal pivoting attempted.\n') ;
elseif (strategy == 3)
fprintf ('(symmetric)\n') ;
fprintf (' Q = AMD (A+A''), Q not refined during numeric factorization,\n') ;
fprintf (' and diagonal pivoting (P=Q'') attempted.\n') ;
else
% strategy = 0 ;
fprintf ('(auto)\n') ;
end
%-------------------------------------------------------------------------------
function yes_no (s)
% yes_no print yes or no
if (s == 0)
fprintf ('(no)\n') ;
else
fprintf ('(yes)\n') ;
end
|
github
|
rashwin1989/plicFoam-master
|
umfpack_make.m
|
.m
|
plicFoam-master/UMFPACK/MATLAB/umfpack_make.m
| 11,580 |
utf_8
|
64f05bca5117d3c3bdc652a04a176080
|
function umfpack_make (lapack)
%UMFPACK_MAKE to compile umfpack2 for use in MATLAB
%
% Compiles the umfpack2 mexFunction and then runs a simple demo.
%
% Example:
% umfpack_make % use default LAPACK and BLAS
% umfpack_make ('lcc_lib/libmwlapack.lib') % for Windows
% umfpack_make ('-lmwlapack -lmwblas') % for Linux, Unix, Mac
%
% the string gives the locations of the LAPACK and BLAS libraries.
%
% See also: umfpack, umfpack2, umfpack_details, umfpack_report, umfpack_demo,
% and umfpack_simple.
% Copyright 1995-2007 by Timothy A. Davis.
details = 0 ;
d = '' ;
if (~isempty (strfind (computer, '64')))
d = ' -largeArrayDims' ;
end
v = getversion ;
try
% ispc does not appear in MATLAB 5.3
pc = ispc ;
catch
% if ispc fails, assume we are on a Windows PC if it's not unix
pc = ~isunix ;
end
fprintf ('Compiling UMFPACK for MATLAB Version %g\n', v) ;
if (pc)
obj = 'obj' ;
else
obj = 'o' ;
end
kk = 0 ;
%-------------------------------------------------------------------------------
% BLAS option
%-------------------------------------------------------------------------------
% This is exceedingly ugly. The MATLAB mex command needs to be told where to
% fine the LAPACK and BLAS libraries, which is a real portability nightmare.
if (nargin < 1)
if (pc)
if (v < 6.5)
% MATLAB 6.1 and earlier: use the version supplied here
lapack = 'lcc_lib/libmwlapack.lib' ;
fprintf ('Using %s. If this fails with dgemm and others\n',lapack);
fprintf ('undefined, then edit umfpack_make.m and modify the') ;
fprintf (' statement:\nlapack = ''%s'' ;\n', lapack) ;
elseif (v < 7.5)
lapack = 'libmwlapack.lib' ;
else
% MATLAB R2007b (7.5) made the problem worse
lapack = 'libmwlapack.lib libmwblas.lib' ;
end
else
% For other systems, mex should find lapack on its own, but this has
% been broken in MATLAB R2007a; the following is now required.
if (v < 7.5)
lapack = '-lmwlapack' ;
else
% MATLAB R2007b (7.5) made the problem worse
lapack = '-lmwlapack -lmwblas' ;
end
end
end
%-------------------------------------------------------------------------------
% -DNPOSIX option (for sysconf and times timer routines)
%-------------------------------------------------------------------------------
posix = '' ;
% if (~pc)
% msg = [ ...
% '--------------------------------------------------------------\n', ...
% '\nUMFPACK can use the POSIX routines sysconf () and times ()\n', ...
% 'to provide CPU time and wallclock time statistics. If you do not\n', ...
% 'have a POSIX-compliant operating system, then UMFPACK won''t\n', ...
% 'compile. If you don''t know which option to pick, try the\n', ...
% 'default. If you get an error saying that sysconf and/or times\n', ...
% 'are not defined, then recompile with the non-POSIX option.\n', ...
% '\nPlease select one of the following options:\n', ...
% ' 1: use POSIX sysconf and times routines (default)\n', ...
% ' 2: do not use POSIX routines\n'] ;
% fprintf (msg) ;
% posix = str2num (input (': ', 's')) ;
% if (isempty (posix))
% posix = 1 ;
% end
% if (posix == 2)
% fprintf ('\nNot using POSIX sysconf and times routines.\n') ;
% posix = ' -DNPOSIX' ;
% else
% fprintf ('\nUsing POSIX sysconf and times routines.\n') ;
% posix = '' ;
% end
% end
%-------------------------------------------------------------------------------
% mex command
%-------------------------------------------------------------------------------
umfdir = '../Source/' ;
amddir = '../../AMD/Source/' ;
incdir = ' -I../Include -I../Source -I../../AMD/Include -I../../UFconfig' ;
mx = sprintf ('mex -O%s%s%s ', posix, incdir, d) ;
% fprintf ('compile options:\n%s\n', mx) ;
%-------------------------------------------------------------------------------
% source files
%-------------------------------------------------------------------------------
% non-user-callable umf_*.[ch] files:
umfch = { 'assemble', 'blas3_update', ...
'build_tuples', 'create_element', ...
'dump', 'extend_front', 'garbage_collection', ...
'get_memory', 'init_front', 'kernel', ...
'kernel_init', 'kernel_wrapup', ...
'local_search', 'lsolve', 'ltsolve', ...
'mem_alloc_element', 'mem_alloc_head_block', ...
'mem_alloc_tail_block', 'mem_free_tail_block', ...
'mem_init_memoryspace', ...
'report_vector', 'row_search', 'scale_column', ...
'set_stats', 'solve', 'symbolic_usage', 'transpose', ...
'tuple_lengths', 'usolve', 'utsolve', 'valid_numeric', ...
'valid_symbolic', 'grow_front', 'start_front', '2by2', ...
'store_lu', 'scale' } ;
% non-user-callable umf_*.[ch] files, int versions only (no real/complex):
umfint = { 'analyze', 'apply_order', 'colamd', 'free', 'fsize', ...
'is_permutation', 'malloc', 'realloc', 'report_perm', ...
'singletons' } ;
% non-user-callable and user-callable amd_*.[ch] files (int versions only):
amdsrc = { 'aat', '1', '2', 'dump', 'postorder', 'post_tree', 'defaults', ...
'order', 'control', 'info', 'valid', 'preprocess', 'global' } ;
% user-callable umfpack_*.[ch] files (real/complex):
user = { 'col_to_triplet', 'defaults', 'free_numeric', ...
'free_symbolic', 'get_numeric', 'get_lunz', ...
'get_symbolic', 'get_determinant', 'numeric', 'qsymbolic', ...
'report_control', 'report_info', 'report_matrix', ...
'report_numeric', 'report_perm', 'report_status', ...
'report_symbolic', 'report_triplet', ...
'report_vector', 'solve', 'symbolic', ...
'transpose', 'triplet_to_col', 'scale' ...
'load_numeric', 'save_numeric', 'load_symbolic', 'save_symbolic' } ;
% user-callable umfpack_*.[ch], only one version
generic = { 'timer', 'tictoc', 'global' } ;
M = cell (0) ;
%-------------------------------------------------------------------------------
% Create the umfpack2 and amd2 mexFunctions for MATLAB (int versions only)
%-------------------------------------------------------------------------------
for k = 1:length(umfint)
[M, kk] = make (M, '%s -DDLONG -c %sumf_%s.c', 'umf_%s.%s', ...
'umf_%s_%s.%s', mx, umfint {k}, umfint {k}, 'm', obj, umfdir, ...
kk, details) ;
end
rules = { [mx ' -DDLONG'] , [mx ' -DZLONG'] } ;
kinds = { 'md', 'mz' } ;
for what = 1:2
rule = rules {what} ;
kind = kinds {what} ;
[M, kk] = make (M, '%s -DCONJUGATE_SOLVE -c %sumf_%s.c', 'umf_%s.%s', ...
'umf_%s_%s.%s', rule, 'ltsolve', 'lhsolve', kind, obj, umfdir, ...
kk, details) ;
[M, kk] = make (M, '%s -DCONJUGATE_SOLVE -c %sumf_%s.c', 'umf_%s.%s', ...
'umf_%s_%s.%s', rule, 'utsolve', 'uhsolve', kind, obj, umfdir, ...
kk, details) ;
[M, kk] = make (M, '%s -DDO_MAP -c %sumf_%s.c', 'umf_%s.%s', ...
'umf_%s_%s_map_nox.%s', rule, 'triplet', 'triplet', kind, obj, ...
umfdir, kk, details) ;
[M, kk] = make (M, '%s -DDO_VALUES -c %sumf_%s.c', 'umf_%s.%s', ...
'umf_%s_%s_nomap_x.%s', rule, 'triplet', 'triplet', kind, obj, ...
umfdir, kk, details) ;
[M, kk] = make (M, '%s -c %sumf_%s.c', 'umf_%s.%s', ...
'umf_%s_%s_nomap_nox.%s', rule, 'triplet', 'triplet', kind, obj, ...
umfdir, kk, details) ;
[M, kk] = make (M, '%s -DDO_MAP -DDO_VALUES -c %sumf_%s.c', 'umf_%s.%s', ...
'umf_%s_%s_map_x.%s', rule, 'triplet', 'triplet', kind, obj, ...
umfdir, kk, details) ;
[M, kk] = make (M, '%s -DFIXQ -c %sumf_%s.c', 'umf_%s.%s', ...
'umf_%s_%s_fixq.%s', rule, 'assemble', 'assemble', kind, obj, ...
umfdir, kk, details) ;
[M, kk] = make (M, '%s -DDROP -c %sumf_%s.c', 'umf_%s.%s', ...
'umf_%s_%s_drop.%s', rule, 'store_lu', 'store_lu', kind, obj, ...
umfdir, kk, details) ;
for k = 1:length(umfch)
[M, kk] = make (M, '%s -c %sumf_%s.c', 'umf_%s.%s', 'umf_%s_%s.%s', ...
rule, umfch {k}, umfch {k}, kind, obj, umfdir, kk, details) ;
end
[M, kk] = make (M, '%s -DWSOLVE -c %sumfpack_%s.c', 'umfpack_%s.%s', ...
'umfpack_%s_w%s.%s', rule, 'solve', 'solve', kind, obj, umfdir, ...
kk, details) ;
for k = 1:length(user)
[M, kk] = make (M, '%s -c %sumfpack_%s.c', 'umfpack_%s.%s', ...
'umfpack_%s_%s.%s', rule, user {k}, user {k}, kind, obj, ...
umfdir, kk, details) ;
end
end
for k = 1:length(generic)
[M, kk] = make (M, '%s -c %sumfpack_%s.c', 'umfpack_%s.%s', ...
'umfpack_%s_%s.%s', mx, generic {k}, generic {k}, 'm', obj, ...
umfdir, kk, details) ;
end
%----------------------------------------
% AMD routines (int only)
%----------------------------------------
for k = 1:length(amdsrc)
[M, kk] = make (M, '%s -DDLONG -c %samd_%s.c', 'amd_%s.%s', ...
'amd_%s_%s.%s', mx, amdsrc {k}, amdsrc {k}, 'm', obj, amddir, ...
kk, details) ;
end
%----------------------------------------
% compile the umfpack2 mexFunction
%----------------------------------------
C = sprintf ('%s -output umfpack2 umfpackmex.c', mx) ;
for i = 1:length (M)
C = [C ' ' (M {i})] ; %#ok
end
C = [C ' ' lapack] ;
kk = cmd (C, kk, details) ;
%----------------------------------------
% delete the object files
%----------------------------------------
for i = 1:length (M)
rmfile (M {i}) ;
end
%----------------------------------------
% compile the luflop mexFunction
%----------------------------------------
cmd (sprintf ('%s -output luflop luflopmex.c', mx), kk, details) ;
fprintf ('\nUMFPACK successfully compiled\n') ;
%===============================================================================
% end of umfpack_make
%===============================================================================
%-------------------------------------------------------------------------------
function rmfile (file)
% rmfile: delete a file, but only if it exists
if (length (dir (file)) > 0) %#ok
delete (file) ;
end
%-------------------------------------------------------------------------------
function cpfile (src, dst)
% cpfile: copy the src file to the filename dst, overwriting dst if it exists
rmfile (dst)
if (length (dir (src)) == 0) %#ok
fprintf ('File does not exist: %s\n', src) ;
error ('File does not exist') ;
end
copyfile (src, dst) ;
%-------------------------------------------------------------------------------
function mvfile (src, dst)
% mvfile: move the src file to the filename dst, overwriting dst if it exists
cpfile (src, dst) ;
rmfile (src) ;
%-------------------------------------------------------------------------------
function kk = cmd (s, kk, details)
%CMD: evaluate a command, and either print it or print a "."
if (details)
fprintf ('%s\n', s) ;
else
if (mod (kk, 60) == 0)
fprintf ('\n') ;
end
kk = kk + 1 ;
fprintf ('.') ;
end
eval (s) ;
%-------------------------------------------------------------------------------
function [M, kk] = make (M, s, src, dst, rule, file1, file2, kind, obj, ...
srcdir, kk, details)
% make: execute a "make" command for a source file
kk = cmd (sprintf (s, rule, srcdir, file1), kk, details) ;
src = sprintf (src, file1, obj) ;
dst = sprintf (dst, kind, file2, obj) ;
mvfile (src, dst) ;
M {end + 1} = dst ;
%-------------------------------------------------------------------------------
function v = getversion
% determine the MATLAB version, and return it as a double.
v = sscanf (version, '%d.%d.%d') ;
v = 10.^(0:-1:-(length(v)-1)) * v ;
|
github
|
rashwin1989/plicFoam-master
|
umfpack_btf.m
|
.m
|
plicFoam-master/UMFPACK/MATLAB/umfpack_btf.m
| 4,651 |
utf_8
|
905709090e298d8bfd5e9937181c95b6
|
function [x, info] = umfpack_btf (A, b, Control)
%UMFPACK_BTF factorize A using a block triangular form
%
% Example:
% x = umfpack_btf (A, b, Control)
%
% solve Ax=b by first permuting the matrix A to block triangular form via dmperm
% and then using UMFPACK to factorize each diagonal block. Adjacent 1-by-1
% blocks are merged into a single upper triangular block, and solved via
% MATLAB's \ operator. The Control parameter is optional (Type umfpack_details
% and umfpack_report for details on its use). A must be square.
%
% See also umfpack, umfpack2, umfpack_details, dmperm
% Copyright 1995-2007 by Timothy A. Davis.
if (nargin < 2)
help umfpack_btf
error ('Usage: x = umfpack_btf (A, b, Control)') ;
end
[m n] = size (A) ;
if (m ~= n)
help umfpack_btf
error ('umfpack_btf: A must be square') ;
end
m1 = size (b,1) ;
if (m1 ~= n)
help umfpack_btf
error ('umfpack_btf: b has the wrong dimensions') ;
end
if (nargin < 3)
Control = umfpack2 ;
end
%-------------------------------------------------------------------------------
% find the block triangular form
%-------------------------------------------------------------------------------
% dmperm built-in may segfault in MATLAB 7.4 or earlier; fixed in MATLAB 7.5
% since dmperm now uses CSparse
[p,q,r] = dmperm (A) ;
nblocks = length (r) - 1 ;
info = [0 0 0] ; % [nnz(L), nnz(U), nnz(F)], optional 2nd output
%-------------------------------------------------------------------------------
% solve the system
%-------------------------------------------------------------------------------
if (nblocks == 1 | sprank (A) < n) %#ok
%---------------------------------------------------------------------------
% matrix is irreducible or structurally singular
%---------------------------------------------------------------------------
[x info2] = umfpack2 (A, '\', b, Control) ;
info = [info2(78) info2(79) 0] ;
else
%---------------------------------------------------------------------------
% A (p,q) is in block triangular form
%---------------------------------------------------------------------------
b = b (p,:) ;
A = A (p,q) ;
x = zeros (size (b)) ;
%---------------------------------------------------------------------------
% merge adjacent singletons into a single upper triangular block
%---------------------------------------------------------------------------
[r, nblocks, is_triangular] = merge_singletons (r) ;
%---------------------------------------------------------------------------
% solve the system: x (q) = A\b
%---------------------------------------------------------------------------
for k = nblocks:-1:1
% get the kth block
k1 = r (k) ;
k2 = r (k+1) - 1 ;
% solve the system
[x2 info2] = solver (A (k1:k2, k1:k2), b (k1:k2,:), ...
is_triangular (k), Control) ;
x (k1:k2,:) = x2 ;
% off-diagonal block back substitution
F2 = A (1:k1-1, k1:k2) ;
b (1:k1-1,:) = b (1:k1-1,:) - F2 * x (k1:k2,:) ;
info (1:2) = info (1:2) + info2 (1:2) ;
info (3) = info (3) + nnz (F2) ;
end
x (q,:) = x ;
end
%-------------------------------------------------------------------------------
% merge_singletons
%-------------------------------------------------------------------------------
function [r, nblocks, is_triangular] = merge_singletons (r)
%
% Given r from [p,q,r] = dmperm (A), where A is square, return a modified r that
% reflects the merger of adjacent singletons into a single upper triangular
% block. is_triangular (k) is 1 if the kth block is upper triangular. nblocks
% is the number of new blocks.
nblocks = length (r) - 1 ;
bsize = r (2:nblocks+1) - r (1:nblocks) ;
t = [0 (bsize == 1)] ;
z = (t (1:nblocks) == 0 & t (2:nblocks+1) == 1) | t (2:nblocks+1) == 0 ;
y = [(find (z)) nblocks+1] ;
r = r (y) ;
nblocks = length (y) - 1 ;
is_triangular = y (2:nblocks+1) - y (1:nblocks) > 1 ;
%-------------------------------------------------------------------------------
% solve Ax=b, but check for small and/or triangular systems
%-------------------------------------------------------------------------------
function [x, info] = solver (A, b, is_triangular, Control)
if (is_triangular)
% back substitution only
x = A \ b ;
info = [nnz(A) 0 0] ;
elseif (size (A,1) < 4)
% a very small matrix, solve it as a dense linear system
x = full (A) \ b ;
n = size (A,1) ;
info = [(n^2+n)/2 (n^2+n)/2 0] ;
else
% solve it as a sparse linear system
[x info] = umfpack_solve (A, '\', b, Control) ;
end
|
github
|
pooya-git/DeepNeuralDecoder-master
|
SteaneTrainingSetd5.m
|
.m
|
DeepNeuralDecoder-master/Data/Generator/Steane_CNOT_D5/SteaneTrainingSetd5.m
| 113,759 |
utf_8
|
f0dabe553929f5beb0a63b422cbf428b
|
% MIT License
%
% Copyright (c) 2018 Chris Chamberland
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.
function SteaneTrainingSetd5
% Circuit descriptors:
% -1: qubit non-active
% 0: Noiseless memory
% 1: Gate memory
% 2: Measurement memory
% 3: Preparation in X basis (|+> state)
% 4: Preparation in Z basis (|0> state)
% 5: Measurement in X basis
% 6: Measurement in Z basis
% 7: X gate
% 8: Z gate
% 10: H gate
% 11: S gate
% 20: T gate
%1---: Control qubit for CNOT with target ---
%1000: Target qubit for CNOT
% Circuit for CNOT 1-exRec
n = 19;
% Generate lookup table
lookUpO = lookUpOFunc(1,n);
lookUpPlus = lookUpPlusFunc(1,n);
%Test
% CNOT circuit containing all four EC blocks
CFull = [0,0,0,0,0,1000,1006,0,1010,0,0,0,0,0,1000,1006,0;
4,1003,0,1000,2,1001,0,5,-1,4,1003,0,1000,2,1001,0,5;
4,1000,6,-1,-1,-1,-1,-1,-1,4,1000,6,-1,-1,-1,-1,-1;
4,1005,0,1002,5,-1,-1,-1,-1,4,1005,0,1002,5,-1,-1,-1;
4,1000,6,-1,-1,-1,-1,-1,-1,4,1000,6,-1,-1,-1,-1,-1;
3,1000,0,1008,2,0,1000,6,-1,3,1000,0,1008,2,0,1000,6;
3,1006,5,-1,-1,-1,-1,-1,-1,3,1006,5,-1,-1,-1,-1,-1;
3,1000,0,1000,6,-1,-1,-1,-1,3,1000,0,1000,6,-1,-1,-1;
3,1008,5,-1,-1,-1,-1,-1,-1,3,1008,5,-1,-1,-1,-1,-1;
0,0,0,0,0,1011,1000,0,1000,0,0,0,0,0,1011,1000,0;
3,1000,0,1013,2,1000,0,6,-1,3,1000,0,1013,2,1000,0,6;
3,1011,5,-1,-1,-1,-1,-1,-1,3,1011,5,-1,-1,-1,-1,-1;
3,1000,0,1000,6,-1,-1,-1,-1,3,1000,0,1000,6,-1,-1,-1;
3,1013,5,-1,-1,-1,-1,-1,-1,3,1013,5,-1,-1,-1,-1,-1;
4,1016,0,1000,2,0,1010,5,-1,4,1016,0,1000,2,0,1010,5;
4,1000,6,-1,-1,-1,-1,-1,-1,4,1000,6,-1,-1,-1,-1,-1;
4,1018,0,1015,5,-1,-1,-1,-1,4,1018,0,1015,5,-1,-1,-1;
4,1000,6,-1,-1,-1,-1,-1,-1,4,1000,6,-1,-1,-1,-1,-1];
parfor i = 1:7
numIterations = 2*10^7;
v = [6*10^-4,7*10^-4,8*10^-4,9*10^-4,10^-3,1.5*10^-3,2*10^-3];
errRate = v(1,i);
errStatePrepString = 'ErrorStatePrep';
str_errRate = num2str(errRate,'%0.3e');
str_mat = '.mat';
str_temp = strcat(errStatePrepString,str_errRate);
str_errStatePrep = strcat(str_temp,str_mat);
% numIterations1 = 10^5;
%
% [eO,eOIndex,numAcceptedO] = PacceptErrorGeneratorOPrepUpper(errRate,numIterations1,n,lookUpPlus,lookUpO);
% [ePlus,ePlusIndex,numAcceptedPlus] = PacceptErrorGeneratorPlusPrepUpper(errRate,numIterations1,n,lookUpPlus,lookUpO);
% parsaveErrorStatePrep(str_errStatePrep,eO,eOIndex,numAcceptedO,ePlus,ePlusIndex,numAcceptedPlus);
switch i
case 1
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep6.000e-04.mat');
case 2
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep7.000e-04.mat');
case 3
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep8.000e-04.mat');
case 4
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep9.000e-04.mat');
case 5
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep1.000e-03.mat');
case 6
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep1.500e-03.mat');
otherwise
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep2.000e-03.mat');
end
if (~isempty(eOIndex)) && (~isempty(ePlusIndex))
[A1,A2,OutputCount] = OutSynAndError(eO,eOIndex,ePlus,ePlusIndex,errRate,numIterations,CFull,n,lookUpPlus,lookUpO);
TempStr1 = 'SyndromeOnly';
TempStr2 = '.txt';
TempStr3 = 'ErrorOnly';
str_Final1 = strcat(TempStr1,str_errRate);
str_Final2 = strcat(str_Final1,TempStr2);
str_Final3 = strcat(TempStr3,str_errRate);
str_Final4 = strcat(str_Final3,TempStr2);
fid = fopen(str_Final2, 'w+t');
for ii = 1:size(A1,1)
fprintf(fid,'%g\t',A1(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
fid = fopen(str_Final4, 'w+t');
for ii = 1:size(A2,1)
fprintf(fid,'%g\t',A2(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
end
str_Count = strcat('Count',str_errRate);
str_CountFinal = strcat(str_Count,'.mat');
parsaveCount(str_CountFinal,OutputCount);
end
end
function parsaveErrorStatePrep(fname,eO,eOIndex,numAcceptedO,ePlus,ePlusIndex,numAcceptedPlus)
save(fname,'eO','eOIndex','numAcceptedO','ePlus','ePlusIndex','numAcceptedPlus');
end
function parsaveErrorVec(fname,errorVecMat)
save(fname,'errorVecMat');
end
function [out1,out2,out3,out4] = parload(fname)
load(fname);
out1 = eO;
out2 = eOIndex;
out3 = ePlus;
out4 = ePlusIndex;
end
function parsaveCount(fname,OutputCount)
save(fname,'OutputCount');
end
function Output = lookUpOFunc(n,numQubits)
% Circuit for |0> state prep
lookUpO = zeros(70,5,numQubits);
C = [3 1018 1014 1013 1009 1004 1010 1007
3 1014 1018 1009 1019 1010 1015 1004
3 0 0 1019 1015 1007 1004 1013
4 0 0 0 0 1000 1000 1000
3 1019 1009 1018 1014 1015 1007 1010
3 0 0 0 0 1009 1018 1017
4 0 0 0 0 1000 1000 1000
3 0 0 1017 1010 1014 1013 1009
4 0 1000 1000 1000 1000 1 1000
4 0 0 0 1000 1000 1000 1000
3 0 0 1014 1013 1018 1017 1019
3 0 0 0 0 1013 1014 1015
4 0 0 1000 1000 1000 1000 1000
4 1000 1000 1000 1000 1000 1000 1
4 0 0 0 1000 1000 1000 1000
3 0 0 0 0 1017 1019 1018
4 0 0 1000 1 1000 1000 1000
4 1000 1000 1000 1 1000 1000 1000
4 1000 1 1000 1000 1 1000 1000];
% Find the number of gate storage locations in C
counterStorage = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) == 1
counterStorage = counterStorage + 1;
end
end
end
% Find the number of CNOT locations in C
counterCNOT = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) > 1000
counterCNOT = counterCNOT + 1;
end
end
end
% fills in lookUpTable locations where lookUpO(i,j,k) has j = k = 1.
counter = 1;
for i = 1:counterStorage
lookUpO(i,1,1) = 1;
counter = counter + 1;
end
for i = 1 : length(C(:,1))
lookUpO(counter,1,1) = C(i,1);
counter = counter + 1;
end
for i = 1 : counterCNOT
lookUpO(counter,1,1) = 1000;
counter = counter + 1;
end
e = zeros(1,4);
% fills in LookUpO(i,j,:) for storage gate errors j = 2,3.
counter = 1;
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = 2:3
if jj == 2
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
else
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
% fills in LookUpO(i,j,:) for state prep errors j = 2,3.
for i = 1:length(C(:,1))
if C(i,1) == 3
e(1,:) = [2,i,1,1];
lookUpO(counter,3,:) = zVector(C, n, e);
counter = counter + 1;
else
e(1,:) = [1,i,1,1];
lookUpO(counter,2,:) = xVector(C, n, e);
counter = counter + 1;
end
end
% fills in LookUpO(i,j,:) for CNOT erros, j = 2,3.
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = [2,3,4,5]
switch jj
case 2
if C(j,i) > 1000
e(1,:) = [1,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
case 3
if C(j,i) > 1000
e(1,:) = [2,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
end
case 4
if C(j,i) > 1000
e(1,:) = [4,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
otherwise
if C(j,i) > 1000
e(1,:) = [8,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
Output = lookUpO;
end
function Output = lookUpPlusFunc(n,numQubits)
% Circuit for |+> state prep
lookUpPlus = zeros(70,5,numQubits);
C = [4 1000 1000 1000 1000 1000 1000 1000
4 1000 1000 1000 1000 1000 1000 1000
4 0 0 1000 1000 1000 1000 1000
3 0 0 0 0 1001 1003 1002
4 1000 1000 1000 1000 1000 1000 1000
4 0 0 0 0 1000 1000 1000
3 0 0 0 0 1003 1005 1001
4 0 0 1000 1000 1000 1000 1000
3 0 1005 1002 1001 1006 1 1008
3 0 0 0 1008 1002 1001 1005
4 0 0 1000 1000 1000 1000 1000
4 0 0 0 0 1000 1000 1000
3 0 0 1001 1011 1012 1008 1003
3 1002 1001 1011 1005 1008 1012 1
3 0 0 0 1003 1005 1002 1012
4 0 0 0 0 1000 1000 1000
3 0 0 1008 1 1016 1011 1006
3 1001 1002 1005 1 1011 1006 1016
3 1005 1 1003 1002 1 1016 1011];
% Find the number of gate storage locations in C
counterStorage = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) == 1
counterStorage = counterStorage + 1;
end
end
end
% Find the number of CNOT locations in C
counterCNOT = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) > 1000
counterCNOT = counterCNOT + 1;
end
end
end
% fills in lookUpTable locations where lookUpO(i,j,k) has j = k = 1.
counter = 1;
for i = 1:counterStorage
lookUpPlus(i,1,1) = 1;
counter = counter + 1;
end
for i = 1 : length(C(:,1))
lookUpPlus(counter,1,1) = C(i,1);
counter = counter + 1;
end
for i = 1 : counterCNOT
lookUpPlus(counter,1,1) = 1000;
counter = counter + 1;
end
e = zeros(1,4);
% fills in LookUpO(i,j,:) for storage gate errors j = 2,3.
counter = 1;
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = 2:3
if jj == 2
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
else
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
% fills in LookUpO(i,j,:) for state prep errors j = 2,3.
for i = 1:length(C(:,1))
if C(i,1) == 3
e(1,:) = [2,i,1,1];
lookUpPlus(counter,3,:) = zVector(C, n, e);
counter = counter + 1;
else
e(1,:) = [1,i,1,1];
lookUpPlus(counter,2,:) = xVector(C, n, e);
counter = counter + 1;
end
end
% fills in LookUpO(i,j,:) for CNOT erros, j = 2,3.
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = [2,3,4,5]
switch jj
case 2
if C(j,i) > 1000
e(1,:) = [1,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
case 3
if C(j,i) > 1000
e(1,:) = [2,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
end
case 4
if C(j,i) > 1000
e(1,:) = [4,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
otherwise
if C(j,i) > 1000
e(1,:) = [8,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
Output = lookUpPlus;
end
function Output = PropagationStatePrepArb(C, n, e)
% C encodes information about the circuit
% n is the number of qubits per encoded codeblock
% eN are the error entries (location and time)
% The Output matrix will contain (2q+m) rows and n columns. The paramters Output(i,j) are:
% i <= 2q and odd: Stores X type errors for output qubit #ceil(i/2) (order based on matrix C)
% i <= 2q and even: Stores Z type errors for output qubit #ceil(i/2) (order based on matrix C)
% i > 2q: Stores measurement error for measurement number #i-2q (type is X or Z depending on measurement type)
% The Errors matrix will be a tensor with 2 parameters Output(i, j)
% i: logical qubit number
% j<=n: X error at physical qubit number j
% j>n : Z error at physical qubit number j
% Error inputs eN are characterized by four parameters, thus a vector (i,j, k, l)
% i: error type: 0 = I, 1 = X, 2 = Z, 3 = Y
% j: logical qubit number (if the entry here is '0' then this will correspond to an identity "error")
% k: physical qubit number within a codeblock
% l: time location
N_meas = length(find(C==5)) + length(find(C==6)); % number of logical measurements in the circuit
N_output = length(C(:,end)) - sum(C(:,end)==-1) - sum(C(:,end)==5) - sum(C(:,end)==6); % number of output active qubits that have not been measured
Meas_dict = [find(C==5); find(C==6)];
Meas_dict = sort(Meas_dict);
Output = zeros(2*N_output + N_meas, n);
Errors = zeros(length(C(:,1)), 2*n);
for t= 1:length(C(1,:))
% If the error occurs at a measurement location then the error is introduced before propagation of faults
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( ( C(e(j,2),t) == 5 ) || ( C(e(j,2),t) == 6 ) )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
end
end
% Propagation of errors (do not need to do it for the first step of circuit
if t>1
for i = 1:length(C(:,t))
if C(i, t) == 10
% In this case must flip the X and Z error information
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = v2;
Errors(i, n+1:end) = v1;
end
if C(i, t) == 11
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = mod(v1+v2, 2);
end
if C(i,t) > 1000
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 1000, t) == 1000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 1000, 1:n);
w2 = Errors(C(i,t) - 1000, (n+1):end);
%mod(v2+w2,2)
Errors(C(i,t) - 1000, 1:n) = mod(v1+w1, 2);
Errors(i, (n+1):end) = mod(v2+w2, 2);
end
end
if C(i,t) == 5
% This corresponds to X measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, (n+1):end);
Errors(i, 1:end) = 0;
end
if C(i,t) == 6
% This corresponds to Z measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, 1:n);
Errors(i, 1:end) = 0;
end
end
end
% Introduce faults for locations that are not measurements
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( C(e(j,2),t) ~= 5 ) && ( C(e(j,2),t) ~= 6 )
% This IF statement checks to see if the gate at this location is NOT a CNOT or Prep
if ( C(e(j,2),t) < 1000 ) %&& ( C(e(j,2),t) ~= 3 ) && ( C(e(j,2),t) ~= 4 )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
% Introduce errors in the case of CNOT gate for control and target qubits
% Errors for control qubit are entry mod(e(j,1),4) according to standard indexing above
if ( C(e(j,2),t) > 1000 )
if C(C(e(j,2),t) - 1000, t) == 1000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 1000, e(j,3)) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 1000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)+n) + 1, 2);
end
end
end
end
end
end
end
%Errors
counter = 1; % This will be used to iterate over the different qubits
for j = 1:length(C(:,end))
if (C(j,end) ~= -1) && (C(j,end) ~= 5) && (C(j,end) ~= 6)
Output(counter,:) = Errors(j,1:n);
Output(counter+1,:) = Errors(j,(n+1):end);
counter = counter + 2;
end
end
end
function Output = xVector(C, n, e)
outputMatrix = PropagationStatePrepArb(C, n, e);
jx = 1;
for i = 1:length(outputMatrix)
if mod(i,2) == 1
xvector(jx) = outputMatrix(i,1);
jx = jx + 1;
end
end
Output = xvector;
end
function Output = zVector(C, n, e)
outputMatrix = PropagationStatePrepArb(C, n, e);
jz = 1;
for i = 1:length(outputMatrix)
if mod(i,2) == 0
zvector(jz) = outputMatrix(i,1);
jz = jz + 1;
end
end
Output = zvector;
end
function Output = PropagationArb(C, n, e, XPrepTable, ZPrepTable)
% C encodes information about the circuit
% n is the number of qubits per encoded codeblock
% eN are the error entries (location and time)
% The Output matrix will contain (2q+m) rows and n columns. The paramters Output(i,j) are:
% i <= 2q and odd: Stores X type errors for output qubit #ceil(i/2) (order based on matrix C)
% i <= 2q and even: Stores Z type errors for output qubit #ceil(i/2) (order based on matrix C)
% i > 2q: Stores measurement error for measurement number #i-2q (type is X or Z depending on measurement type)
% The Errors matrix will be a tensor with 2 parameters Output(i, j)
% i: logical qubit number
% j<=n: X error at physical qubit number j
% j>n : Z error at physical qubit number j
% Error inputs eN are characterized by four parameters, thus a vector (i,j, k, l)
% i: error type: 0 = I, 1 = X, 2 = Z, 3 = Y
% j: logical qubit number (if the entry here is '0' then this will correspond to an identity "error")
% k: physical qubit number within a codeblock
% l: time location
N_meas = length(find(C==5)) + length(find(C==6)); % number of logical measurements in the circuit
N_output = length(C(:,end)) - sum(C(:,end)==-1) - sum(C(:,end)==5) - sum(C(:,end)==6); % number of output active qubits that have not been measured
Meas_dict = [find(C==5); find(C==6)];
Meas_dict = sort(Meas_dict);
Output = zeros(2*N_output + N_meas, n);
Errors = zeros(length(C(:,1)), 2*n);
for t= 1:length(C(1,:))
% If the error occurs at a measurement location then the error is introduced before propagation of faults
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( ( C(e(j,2),t) == 5 ) || ( C(e(j,2),t) == 6 ) )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
end
end
% Propagation of errors (do not need to do it for the first step of
% circuit)
if t>1
for i = 1:length(C(:,t))
if C(i, t) == 10
% In this case must flip the X and Z error information
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = v2;
Errors(i, n+1:end) = v1;
end
if C(i, t) == 11
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = mod(v1+v2, 2);
end
if C(i,t) > 1000
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 1000, t) == 1000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 1000, 1:n);
w2 = Errors(C(i,t) - 1000, (n+1):end);
%mod(v2+w2,2)
Errors(C(i,t) - 1000, 1:n) = mod(v1+w1, 2);
Errors(i, (n+1):end) = mod(v2+w2, 2);
end
end
if C(i,t) == 5
% This corresponds to X measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, (n+1):end);
Errors(i, 1:end) = 0;
end
if C(i,t) == 6
% This corresponds to Z measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, 1:n);
Errors(i, 1:end) = 0;
end
end
end
% Introduce faults for locations that are not measurements
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( C(e(j,2),t) ~= 5 ) && ( C(e(j,2),t) ~= 6 )
% This IF statement checks to see if the gate at this location is NOT a CNOT or Prep
if ( C(e(j,2),t) < 1000 ) && ( C(e(j,2),t) ~= 3 ) && ( C(e(j,2),t) ~= 4 )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
% Introduce errors in the case of CNOT gate for control and target qubits
% Errors for control qubit are entry mod(e(j,1),4) according to standard indexing above
if ( C(e(j,2),t) > 1000 )
if C(C(e(j,2),t) - 1000, t) == 1000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 1000, e(j,3)) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 1000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)+n) + 1, 2);
end
end
end
% Introduce errors in the case of |0> prep
if ( C(e(j,2),t) == 4 )
eVec = zeros(1,n);
if mod(e(j,1),2) == 1
% Need to translate the entries in the Prep tables to right format
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 2, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(e(j,1),4) > 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 3, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end)+eVec, 2);
end
if mod(floor(e(j,1)/4),2) == 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 4, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(floor(e(j,1)/4),4) > 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 5, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end) + eVec, 2);
end
end
% Introduce errors in the case of |+> prep
if ( C(e(j,2),t) == 3 )
eVec = zeros(1,n);
if mod(e(j,1),2) == 1
% Need to translate the entries in the Prep tables to right format
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 2, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(e(j,1),4) > 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 3, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end)+eVec, 2);
end
if mod(floor(e(j,1)/4),2) == 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 4, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(floor(e(j,1)/4),4) > 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 5, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end) + eVec, 2);
end
end
end
end
end
end
%Errors
counter = 1; % This will be used to iterate over the different qubits
for j = 1:length(C(:,end))
if (C(j,end) ~= -1) && (C(j,end) ~= 5) && (C(j,end) ~= 6)
Output(counter,:) = Errors(j,1:n);
Output(counter+1,:) = Errors(j,(n+1):end);
counter = counter + 2;
end
end
end
function Output = IdealDecoder19QubitColor(xErr)
Stabs = [1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 1 1 0 0 1 1 1 0 0 0 0 0 0
1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0];
newMat = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0
0 0 0 0 0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 0 0 0 0 0 0 1 0 0 0 1 0 0
1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0
1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0
1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0
0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0
0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0
1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0
1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0];
Syn = zeros(1,9);
for i = 1:9
Syn(i) = mod(sum(conj(xErr).* Stabs(i,1:19)),2); % obtain error syndrom
end
correctionRow = 1;
% convert binary syndrome to decimal to find row in matrix newMat
% corresponding to measured syndrome
for i = 1:length(Syn)
correctionRow = correctionRow + 2^(9-i)*Syn(i);
end
Output = newMat(correctionRow,:);
end
function Output = Syndrome(errIn)
g = [1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 1 1 0 0 1 1 1 0 0 0 0 0 0
1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0];
syn = zeros(1,9);
for i = 1:9
syn(1,i) = mod( sum(errIn.*g(i,:)), 2);
end
Output = syn;
end
function Output = errorGeneratorPacceptOprepUpper(errRate)
% Generates errors in the ancilla preparation part of the EC's
e = zeros(1,4);
rows = 1;
% Locations within the state prep |0> circuit
for i = 1:2
for l = 1:6
xi = rand;
if xi < errRate
k = randi([1,3]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
for l = 7:25
if (l == 7) || (l == 8) || (l == 9) || (l == 11) || (l == 12) || (l == 14) || (l == 17) || (l == 18) || (l == 22)
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,1];
rows = rows + 1;
end
else
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,1];
rows = rows + 1;
end
end
end
for l = 26:70
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
end
for i = [1,3]
for l = 1:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,2];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:19
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,3];
rows = rows + 1;
end
end
end
for l = 1:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,3,l,4];
rows = rows + 1;
end
end
for l = 1:19
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,3,l,5];
rows = rows + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3] = PacceptErrorGeneratorOPrepUpper(errRate,numIterations,n,lookUpPlus,lookUpO)
C = [4,1002,0,1000,2;
4,1000,6,-1,-1;
4,1004,0,1001,5;
4,1000,6,-1,-1];
eAccepted = zeros(1,4);
eIndex = zeros(1,1);
countereIndex = 1;
counterRows = 0;
numAccepted = 0;
while length(eAccepted(:,1)) < numIterations
e = errorGeneratorPacceptOprepUpper(errRate);
if isequal(e,zeros(1,4))
counter = 0;
else
counter = length(e(:,1));
end
propagatedMatrix = PropagationArb(C,n,e,lookUpPlus,lookUpO);
if (sum(IdealDecoder19QubitColor(propagatedMatrix(3,:)))==0) && (sum(IdealDecoder19QubitColor(propagatedMatrix(4,:)))==0) && (sum(IdealDecoder19QubitColor(propagatedMatrix(5,:)))==0) && (mod(sum(propagatedMatrix(3,:)),2)==0) && (mod(sum(propagatedMatrix(4,:)),2)==0) && (mod(sum(propagatedMatrix(5,:)),2)==0)
if counter ~= 0
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + counter;
eAccepted((counterLast + 1):(counterLast + counter),:) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
else
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + 1;
eAccepted((counterLast + 1),1:4) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
end
end
end
Output1 = eAccepted;
Output2 = eIndex;
Output3 = numAccepted;
end
function Output = errorGeneratorPacceptPlusprepUpper(errRate)
e = zeros(1,4);
rows = 1;
for i = 1:2
for l = 1:6
xi = rand;
if xi < errRate
k = randi([1,3]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
for l = 7:25
if (l == 7) || (l == 8) || (l == 9) || (l == 11) || (l == 12) || (l == 14) || (l == 17) || (l == 18) || (l == 22)
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,1];
rows = rows + 1;
end
else
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,1];
rows = rows + 1;
end
end
end
for l = 26:70
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,2];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:19
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,3];
rows = rows + 1;
end
end
end
for l = 1:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,1,l,4];
rows = rows + 1;
end
end
for l = 1:19
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,3,l,5];
rows = rows + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3] = PacceptErrorGeneratorPlusPrepUpper(errRate,numIterations,n,lookUpPlus,lookUpO)
C = [3,1000,0,1003,2;
3,1001,5,-1,-1;
3,1000,0,1000,6;
3,1003,5,-1,-1];
eAccepted = zeros(1,4);
eIndex = zeros(1,1);
countereIndex = 1;
counterRows = 0;
numAccepted = 0;
while length(eAccepted(:,1)) < numIterations
e = errorGeneratorPacceptPlusprepUpper(errRate);
if isequal(e,zeros(1,4))
counter = 0;
else
counter = length(e(:,1));
end
propagatedMatrix = PropagationArb(C, n, e,lookUpPlus, lookUpO);
if (sum(IdealDecoder19QubitColor(propagatedMatrix(3,:)))==0) && (sum(IdealDecoder19QubitColor(propagatedMatrix(4,:)))==0) && (sum(IdealDecoder19QubitColor(propagatedMatrix(5,:)))==0) && (mod(sum(propagatedMatrix(3,:)),2)==0) && (mod(sum(propagatedMatrix(4,:)),2)==0) && (mod(sum(propagatedMatrix(5,:)),2)==0)
if counter ~= 0
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + counter;
eAccepted((counterLast + 1):(counterLast + counter),:) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
else
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + 1;
eAccepted((counterLast + 1),1:4) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
end
end
end
Output1 = eAccepted;
Output2 = eIndex;
Output3 = numAccepted;
end
function Output = errorGeneratorRemaining(errRate,numQubits)
% generates remaining errors outside state-prep circuits.
e = zeros(1,4);
counter = 1;
% Errors in first block
for i = [2,6] % Storage locations in first block
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,5];
counter = counter + 1;
end
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,2,l,6];
counter = counter + 1;
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,1,l,7];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in X basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,2,l,8];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in Z basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,6,l,8];
counter = counter + 1;
end
end
% Error at encoded CNOT location
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,1,l,9];
counter = counter + 1;
end
end
% Error in second block (connected to first data qubit)
for i = [2,6] % Storage locations in first block
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,14];
counter = counter + 1;
end
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,2,l,15];
counter = counter + 1;
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,1,l,16];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in X basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,2,l,17];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in Z basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,6,l,17];
counter = counter + 1;
end
end
% Errors in third block (connected to second data qubit)
for i = [11,15] % Storage locations in first block
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,5];
counter = counter + 1;
end
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,10,l,6];
counter = counter + 1;
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,15,l,7];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in Z basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,11,l,8];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in X basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,15,l,8];
counter = counter + 1;
end
end
% Errors in fourth block
for i = [11,15] % Storage locations in first block
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,14];
counter = counter + 1;
end
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,10,l,15];
counter = counter + 1;
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,15,l,16];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in Z basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,11,l,17];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in X basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,15,l,17];
counter = counter + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3] = OutSynAndError(eO,eOIndex,ePlus,ePlusIndex,errRate,numIterations,CFull,n,lookUpPlus,lookUpO)
MatSyn = zeros(4*numIterations,18); % Format (XSyn|ZSyn);
MatErr = zeros(2*numIterations,38); %Format (XErr|ZErr);
numRows = 1;
countIterations = 0;
while numRows < (numIterations+1)
% Generate errors from |0> state-prep circuit in first 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e = errorO;
rows = length(e(:,1));
% Genrate errors from |+> state-prep circuit in first 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e1Plus = errorPlus;
rowse1Plus = length(e1Plus(:,1));
e((rows + 1):(rows + rowse1Plus),:) = e1Plus;
rows = rows + rowse1Plus;
% Generate errors from |0> state-prep circuit in the second 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e2O = errorO;
for i = 1:length(e2O(:,1))
e2O(i,2) = e2O(i,2) + 13;
end
rowse2O = length(e2O(:,1));
e((rows + 1):(rows + rowse2O),:) = e2O;
rows = rows + rowse2O;
% Generate errors from |+> state-prep in the second 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e2Plus = errorPlus;
for i = 1:length(e2Plus(:,1))
e2Plus(i,2) = e2Plus(i,2) + 5;
end
rowse2Plus = length(e2Plus(:,1));
e((rows + 1):(rows + rowse2Plus),:) = e2Plus;
rows = rows + rowse2Plus;
% Generate errors from |0> state-prep circuit in third 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e3O = errorO;
for i = 1:length(e3O(:,1))
e3O(i,4) = e3O(i,4) + 9;
end
rowse3O = length(e3O(:,1));
e((rows + 1):(rows + rowse3O),:) = e3O;
rows = rows + rowse3O;
% Genrate errors from |+> state-prep circuit in third 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e3Plus = errorPlus;
for i = 1:length(e3Plus(:,1))
e3Plus(i,4) = e3Plus(i,4) + 9;
end
rowse3Plus = length(e3Plus(:,1));
e((rows + 1):(rows + rowse3Plus),:) = e3Plus;
rows = rows + rowse3Plus;
% Generate errors from |0> state-prep circuit in the fourth 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e4O = errorO;
for i = 1:length(e4O(:,1))
e4O(i,2) = e4O(i,2) + 13;
e4O(i,4) = e4O(i,4) + 9;
end
rowse4O = length(e4O(:,1));
e((rows + 1):(rows + rowse4O),:) = e4O;
rows = rows + rowse4O;
% Generate errors from |+> state-prep in the fourth 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e4Plus = errorPlus;
for i = 1:length(e4Plus(:,1))
e4Plus(i,2) = e4Plus(i,2) + 5;
e4Plus(i,4) = e4Plus(i,4) + 9;
end
rowse4Plus = length(e4Plus(:,1));
e((rows + 1):(rows + rowse4Plus),:) = e4Plus;
rows = rows + rowse4Plus;
% Next we generate a random error in the circuit (outside of state-prep
% circuits) to add to the matrix e (given the error rate errRate).
eRemain = errorGeneratorRemaining(errRate,n);
e((rows + 1):(rows + length(eRemain(:,1))),:) = eRemain;
Cfinal = PropagationArb(CFull,n,e,lookUpPlus,lookUpO); % Propagate errors through the full CNOT circuit
% Store measurment syndromes
ErrZ17 = Cfinal(17,:);
SynZ17 = Syndrome(ErrZ17);
ErrX18 = Cfinal(18,:);
SynX18 = Syndrome(ErrX18);
ErrX19 = Cfinal(19,:);
SynX19 = Syndrome(ErrX19);
ErrZ20 = Cfinal(20,:);
SynZ20 = Syndrome(ErrZ20);
ErrZ33 = Cfinal(2,:);
SynZ33 = Syndrome(Cfinal(33,:));
ErrX34 = Cfinal(1,:);
SynX34 = Syndrome(Cfinal(34,:));
ErrX35 = Cfinal(3,:);
SynX35 = Syndrome(Cfinal(35,:));
ErrZ36 = Cfinal(4,:);
SynZ36 = Syndrome(Cfinal(36,:));
t1 = sum(SynX18+SynZ17+SynX19+SynZ20+SynX34+SynZ33+SynX35+SynZ36);
t2 = sum(ErrZ33+ErrX34+ErrX35+ErrZ36);
if (t1 ~= 0) || (t2 ~= 0)
MatSynTemp = [SynX18,SynZ17;SynX19,SynZ20;SynX34,SynZ33;SynX35,SynZ36];
MatErrorTemp = [ErrX34,ErrZ33;ErrX35,ErrZ36];
MatSyn((4*(numRows-1)+1):(4*numRows),:) = MatSynTemp;
MatErr((2*(numRows-1)+1):(2*numRows),:) = MatErrorTemp;
numRows = numRows + 1;
end
countIterations = countIterations + 1;
end
Output1 = MatSyn;
Output2 = MatErr;
Output3 = countIterations;
end
|
github
|
pooya-git/DeepNeuralDecoder-master
|
SteaneTrainingSetd3.m
|
.m
|
DeepNeuralDecoder-master/Data/Generator/Steane_CNOT_D3/SteaneTrainingSetd3.m
| 61,494 |
utf_8
|
17049c07b5d6cc375a5d6f39bd9c3c9b
|
% MIT License
%
% Copyright (c) 2018 Chris Chamberland
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.
function SteaneTrainingSetd3
% Circuit descriptors:
% -1: qubit non-active
% 0: Noiseless memory
% 1: Gate memory
% 2: Measurement memory
% 3: Preparation in X basis (|+> state)
% 4: Preparation in Z basis (|0> state)
% 5: Measurement in X basis
% 6: Measurement in Z basis
% 7: X gate
% 8: Z gate
% 10: H gate
% 11: S gate
% 20: T gate
%1---: Control qubit for CNOT with target ---
%1000: Target qubit for CNOT
% Circuit for CNOT 1-exRec
n = 7;
% Generate lookup table
lookUpO = lookUpOFunc(1,n);
lookUpPlus = lookUpPlusFunc(1,n);
%Test
% CNOT circuit containing all four EC blocks
CFull = [0,0,0,0,0,1000,1006,0,1010,0,0,0,0,0,1000,1006,0;
4,1003,0,1000,2,1001,0,5,-1,4,1003,0,1000,2,1001,0,5;
4,1000,6,-1,-1,-1,-1,-1,-1,4,1000,6,-1,-1,-1,-1,-1;
4,1005,0,1002,5,-1,-1,-1,-1,4,1005,0,1002,5,-1,-1,-1;
4,1000,6,-1,-1,-1,-1,-1,-1,4,1000,6,-1,-1,-1,-1,-1;
3,1000,0,1008,2,0,1000,6,-1,3,1000,0,1008,2,0,1000,6;
3,1006,5,-1,-1,-1,-1,-1,-1,3,1006,5,-1,-1,-1,-1,-1;
3,1000,0,1000,6,-1,-1,-1,-1,3,1000,0,1000,6,-1,-1,-1;
3,1008,5,-1,-1,-1,-1,-1,-1,3,1008,5,-1,-1,-1,-1,-1;
0,0,0,0,0,1011,1000,0,1000,0,0,0,0,0,1011,1000,0;
3,1000,0,1013,2,1000,0,6,-1,3,1000,0,1013,2,1000,0,6;
3,1011,5,-1,-1,-1,-1,-1,-1,3,1011,5,-1,-1,-1,-1,-1;
3,1000,0,1000,6,-1,-1,-1,-1,3,1000,0,1000,6,-1,-1,-1;
3,1013,5,-1,-1,-1,-1,-1,-1,3,1013,5,-1,-1,-1,-1,-1;
4,1016,0,1000,2,0,1010,5,-1,4,1016,0,1000,2,0,1010,5;
4,1000,6,-1,-1,-1,-1,-1,-1,4,1000,6,-1,-1,-1,-1,-1;
4,1018,0,1015,5,-1,-1,-1,-1,4,1018,0,1015,5,-1,-1,-1;
4,1000,6,-1,-1,-1,-1,-1,-1,4,1000,6,-1,-1,-1,-1,-1];
parfor i = 1:7
numIterations = 2*10^6;
v = [10^-4,2*10^-4,3*10^-4,4*10^-4,5*10^-4,6*10^-4,7*10^-4];
errRate = v(1,i);
errStatePrepString = 'ErrorStatePrep';
str_errRate = num2str(errRate,'%0.3e');
str_mat = '.mat';
str_temp = strcat(errStatePrepString,str_errRate);
str_errStatePrep = strcat(str_temp,str_mat);
% numIterations1 = 10^5;
%
% [eO,eOIndex,numAcceptedO] = PacceptErrorGeneratorOPrepUpper(errRate,numIterations1,n,lookUpPlus,lookUpO);
% [ePlus,ePlusIndex,numAcceptedPlus] = PacceptErrorGeneratorPlusPrepUpper(errRate,numIterations1,n,lookUpPlus,lookUpO);
% parsaveErrorStatePrep(str_errStatePrep,eO,eOIndex,numAcceptedO,ePlus,ePlusIndex,numAcceptedPlus);
switch i
case 1
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep1.000e-04.mat');
case 2
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep2.000e-04.mat');
case 3
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep3.000e-04.mat');
case 4
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep4.000e-04.mat');
case 5
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep5.000e-04.mat');
case 6
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep6.000e-04.mat');
case 7
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep7.000e-04.mat');
end
if (~isempty(eOIndex)) && (~isempty(ePlusIndex))
[A1,A2,OutputCount] = OutSynAndError(eO,eOIndex,ePlus,ePlusIndex,errRate,numIterations,CFull,n,lookUpPlus,lookUpO);
TempStr1 = 'SyndromeOnly';
TempStr2 = '.txt';
TempStr3 = 'ErrorOnly';
str_Final1 = strcat(TempStr1,str_errRate);
str_Final2 = strcat(str_Final1,TempStr2);
str_Final3 = strcat(TempStr3,str_errRate);
str_Final4 = strcat(str_Final3,TempStr2);
fid = fopen(str_Final2, 'w+t');
for ii = 1:size(A1,1)
fprintf(fid,'%g\t',A1(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
fid = fopen(str_Final4, 'w+t');
for ii = 1:size(A2,1)
fprintf(fid,'%g\t',A2(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
end
str_Count = strcat('Count',str_errRate);
str_CountFinal = strcat(str_Count,'.mat');
parsaveCount(str_CountFinal,OutputCount);
end
end
function parsaveErrorStatePrep(fname,eO,eOIndex,numAcceptedO,ePlus,ePlusIndex,numAcceptedPlus)
save(fname,'eO','eOIndex','numAcceptedO','ePlus','ePlusIndex','numAcceptedPlus');
end
function parsaveErrorVec(fname,errorVecMat)
save(fname,'errorVecMat');
end
function [out1,out2,out3,out4] = parload(fname)
load(fname);
out1 = eO;
out2 = eOIndex;
out3 = ePlus;
out4 = ePlusIndex;
end
function parsaveCount(fname,OutputCount)
save(fname,'OutputCount');
end
function Output = lookUpOFunc(n,numQubits)
% Circuit for |0> state prep
lookUpO = zeros(19,5,numQubits);
C = [3,1007,1005,1003;
3,1003,1006,1;
4,1000,1,1000;
3,1006,1,1005;
4,0,1000,1000;
4,1000,1000,1007;
4,1000,1,1000];
% Find the number of gate storage locations in C
counterStorage = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) == 1
counterStorage = counterStorage + 1;
end
end
end
% Find the number of CNOT locations in C
counterCNOT = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) > 1000
counterCNOT = counterCNOT + 1;
end
end
end
% fills in lookUpTable locations where lookUpO(i,j,k) has j = k = 1.
counter = 1;
for i = 1:counterStorage
lookUpO(i,1,1) = 1;
counter = counter + 1;
end
for i = 1 : length(C(:,1))
lookUpO(counter,1,1) = C(i,1);
counter = counter + 1;
end
for i = 1 : counterCNOT
lookUpO(counter,1,1) = 1000;
counter = counter + 1;
end
e = zeros(1,4);
% fills in LookUpO(i,j,:) for storage gate errors j = 2,3.
counter = 1;
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = 2:3
if jj == 2
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
else
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
% fills in LookUpO(i,j,:) for state prep errors j = 2,3.
for i = 1:length(C(:,1))
if C(i,1) == 3
e(1,:) = [2,i,1,1];
lookUpO(counter,3,:) = zVector(C, n, e);
counter = counter + 1;
else
e(1,:) = [1,i,1,1];
lookUpO(counter,2,:) = xVector(C, n, e);
counter = counter + 1;
end
end
% fills in LookUpO(i,j,:) for CNOT erros, j = 2,3.
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = [2,3,4,5]
switch jj
case 2
if C(j,i) > 1000
e(1,:) = [1,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
case 3
if C(j,i) > 1000
e(1,:) = [2,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
end
case 4
if C(j,i) > 1000
e(1,:) = [4,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
otherwise
if C(j,i) > 1000
e(1,:) = [8,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
Output = lookUpO;
end
function Output = lookUpPlusFunc(n,numQubits)
% Circuit for |+> state prep
lookUpPlus = zeros(19,5,numQubits);
C = [4,1000,1000,1000;
4,1000,1000,1;
3,1002,1,1001;
4,1000,1,1000;
3,0,1001,1004;
3,1004,1002,1000;
3,1001,1,1006];
% Find the number of gate storage locations in C
counterStorage = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) == 1
counterStorage = counterStorage + 1;
end
end
end
% Find the number of CNOT locations in C
counterCNOT = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) > 1000
counterCNOT = counterCNOT + 1;
end
end
end
% fills in lookUpTable locations where lookUpO(i,j,k) has j = k = 1.
counter = 1;
for i = 1:counterStorage
lookUpPlus(i,1,1) = 1;
counter = counter + 1;
end
for i = 1 : length(C(:,1))
lookUpPlus(counter,1,1) = C(i,1);
counter = counter + 1;
end
for i = 1 : counterCNOT
lookUpPlus(counter,1,1) = 1000;
counter = counter + 1;
end
e = zeros(1,4);
% fills in LookUpO(i,j,:) for storage gate errors j = 2,3.
counter = 1;
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = 2:3
if jj == 2
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
else
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
% fills in LookUpO(i,j,:) for state prep errors j = 2,3.
for i = 1:length(C(:,1))
if C(i,1) == 3
e(1,:) = [2,i,1,1];
lookUpPlus(counter,3,:) = zVector(C, n, e);
counter = counter + 1;
else
e(1,:) = [1,i,1,1];
lookUpPlus(counter,2,:) = xVector(C, n, e);
counter = counter + 1;
end
end
% fills in LookUpO(i,j,:) for CNOT erros, j = 2,3.
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = [2,3,4,5]
switch jj
case 2
if C(j,i) > 1000
e(1,:) = [1,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
case 3
if C(j,i) > 1000
e(1,:) = [2,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
end
case 4
if C(j,i) > 1000
e(1,:) = [4,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
otherwise
if C(j,i) > 1000
e(1,:) = [8,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
Output = lookUpPlus;
end
function Output = PropagationStatePrepArb(C, n, e)
% C encodes information about the circuit
% n is the number of qubits per encoded codeblock
% eN are the error entries (location and time)
% The Output matrix will contain (2q+m) rows and n columns. The paramters Output(i,j) are:
% i <= 2q and odd: Stores X type errors for output qubit #ceil(i/2) (order based on matrix C)
% i <= 2q and even: Stores Z type errors for output qubit #ceil(i/2) (order based on matrix C)
% i > 2q: Stores measurement error for measurement number #i-2q (type is X or Z depending on measurement type)
% The Errors matrix will be a tensor with 2 parameters Output(i, j)
% i: logical qubit number
% j<=n: X error at physical qubit number j
% j>n : Z error at physical qubit number j
% Error inputs eN are characterized by four parameters, thus a vector (i,j, k, l)
% i: error type: 0 = I, 1 = X, 2 = Z, 3 = Y
% j: logical qubit number (if the entry here is '0' then this will correspond to an identity "error")
% k: physical qubit number within a codeblock
% l: time location
N_meas = length(find(C==5)) + length(find(C==6)); % number of logical measurements in the circuit
N_output = length(C(:,end)) - sum(C(:,end)==-1) - sum(C(:,end)==5) - sum(C(:,end)==6); % number of output active qubits that have not been measured
Meas_dict = [find(C==5); find(C==6)];
Meas_dict = sort(Meas_dict);
Output = zeros(2*N_output + N_meas, n);
Errors = zeros(length(C(:,1)), 2*n);
for t= 1:length(C(1,:))
% If the error occurs at a measurement location then the error is introduced before propagation of faults
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( ( C(e(j,2),t) == 5 ) || ( C(e(j,2),t) == 6 ) )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
end
end
% Propagation of errors (do not need to do it for the first step of circuit
if t>1
for i = 1:length(C(:,t))
if C(i, t) == 10
% In this case must flip the X and Z error information
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = v2;
Errors(i, n+1:end) = v1;
end
if C(i, t) == 11
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = mod(v1+v2, 2);
end
if C(i,t) > 1000
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 1000, t) == 1000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 1000, 1:n);
w2 = Errors(C(i,t) - 1000, (n+1):end);
%mod(v2+w2,2)
Errors(C(i,t) - 1000, 1:n) = mod(v1+w1, 2);
Errors(i, (n+1):end) = mod(v2+w2, 2);
end
end
if C(i,t) == 5
% This corresponds to X measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, (n+1):end);
Errors(i, 1:end) = 0;
end
if C(i,t) == 6
% This corresponds to Z measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, 1:n);
Errors(i, 1:end) = 0;
end
end
end
% Introduce faults for locations that are not measurements
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( C(e(j,2),t) ~= 5 ) && ( C(e(j,2),t) ~= 6 )
% This IF statement checks to see if the gate at this location is NOT a CNOT or Prep
if ( C(e(j,2),t) < 1000 ) %&& ( C(e(j,2),t) ~= 3 ) && ( C(e(j,2),t) ~= 4 )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
% Introduce errors in the case of CNOT gate for control and target qubits
% Errors for control qubit are entry mod(e(j,1),4) according to standard indexing above
if ( C(e(j,2),t) > 1000 )
if C(C(e(j,2),t) - 1000, t) == 1000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 1000, e(j,3)) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 1000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)+n) + 1, 2);
end
end
end
end
end
end
end
%Errors
counter = 1; % This will be used to iterate over the different qubits
for j = 1:length(C(:,end))
if (C(j,end) ~= -1) && (C(j,end) ~= 5) && (C(j,end) ~= 6)
Output(counter,:) = Errors(j,1:n);
Output(counter+1,:) = Errors(j,(n+1):end);
counter = counter + 2;
end
end
end
function Output = xVector(C, n, e)
outputMatrix = PropagationStatePrepArb(C, n, e);
jx = 1;
for i = 1:length(outputMatrix)
if mod(i,2) == 1
xvector(jx) = outputMatrix(i,1);
jx = jx + 1;
end
end
Output = xvector;
end
function Output = zVector(C, n, e)
outputMatrix = PropagationStatePrepArb(C, n, e);
jz = 1;
for i = 1:length(outputMatrix)
if mod(i,2) == 0
zvector(jz) = outputMatrix(i,1);
jz = jz + 1;
end
end
Output = zvector;
end
function Output = PropagationArb(C, n, e, XPrepTable, ZPrepTable)
% C encodes information about the circuit
% n is the number of qubits per encoded codeblock
% eN are the error entries (location and time)
% The Output matrix will contain (2q+m) rows and n columns. The paramters Output(i,j) are:
% i <= 2q and odd: Stores X type errors for output qubit #ceil(i/2) (order based on matrix C)
% i <= 2q and even: Stores Z type errors for output qubit #ceil(i/2) (order based on matrix C)
% i > 2q: Stores measurement error for measurement number #i-2q (type is X or Z depending on measurement type)
% The Errors matrix will be a tensor with 2 parameters Output(i, j)
% i: logical qubit number
% j<=n: X error at physical qubit number j
% j>n : Z error at physical qubit number j
% Error inputs eN are characterized by four parameters, thus a vector (i,j, k, l)
% i: error type: 0 = I, 1 = X, 2 = Z, 3 = Y
% j: logical qubit number (if the entry here is '0' then this will correspond to an identity "error")
% k: physical qubit number within a codeblock
% l: time location
N_meas = length(find(C==5)) + length(find(C==6)); % number of logical measurements in the circuit
N_output = length(C(:,end)) - sum(C(:,end)==-1) - sum(C(:,end)==5) - sum(C(:,end)==6); % number of output active qubits that have not been measured
Meas_dict = [find(C==5); find(C==6)];
Meas_dict = sort(Meas_dict);
Output = zeros(2*N_output + N_meas, n);
Errors = zeros(length(C(:,1)), 2*n);
for t= 1:length(C(1,:))
% If the error occurs at a measurement location then the error is introduced before propagation of faults
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( ( C(e(j,2),t) == 5 ) || ( C(e(j,2),t) == 6 ) )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
end
end
% Propagation of errors (do not need to do it for the first step of
% circuit)
if t>1
for i = 1:length(C(:,t))
if C(i, t) == 10
% In this case must flip the X and Z error information
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = v2;
Errors(i, n+1:end) = v1;
end
if C(i, t) == 11
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = mod(v1+v2, 2);
end
if C(i,t) > 1000
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 1000, t) == 1000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 1000, 1:n);
w2 = Errors(C(i,t) - 1000, (n+1):end);
%mod(v2+w2,2)
Errors(C(i,t) - 1000, 1:n) = mod(v1+w1, 2);
Errors(i, (n+1):end) = mod(v2+w2, 2);
end
end
if C(i,t) == 5
% This corresponds to X measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, (n+1):end);
Errors(i, 1:end) = 0;
end
if C(i,t) == 6
% This corresponds to Z measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, 1:n);
Errors(i, 1:end) = 0;
end
end
end
% Introduce faults for locations that are not measurements
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( C(e(j,2),t) ~= 5 ) && ( C(e(j,2),t) ~= 6 )
% This IF statement checks to see if the gate at this location is NOT a CNOT or Prep
if ( C(e(j,2),t) < 1000 ) && ( C(e(j,2),t) ~= 3 ) && ( C(e(j,2),t) ~= 4 )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
% Introduce errors in the case of CNOT gate for control and target qubits
% Errors for control qubit are entry mod(e(j,1),4) according to standard indexing above
if ( C(e(j,2),t) > 1000 )
if C(C(e(j,2),t) - 1000, t) == 1000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 1000, e(j,3)) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 1000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)+n) + 1, 2);
end
end
end
% Introduce errors in the case of |0> prep
if ( C(e(j,2),t) == 4 )
eVec = zeros(1,n);
if mod(e(j,1),2) == 1
% Need to translate the entries in the Prep tables to right format
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 2, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(e(j,1),4) > 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 3, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end)+eVec, 2);
end
if mod(floor(e(j,1)/4),2) == 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 4, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(floor(e(j,1)/4),4) > 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 5, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end) + eVec, 2);
end
end
% Introduce errors in the case of |+> prep
if ( C(e(j,2),t) == 3 )
eVec = zeros(1,n);
if mod(e(j,1),2) == 1
% Need to translate the entries in the Prep tables to right format
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 2, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(e(j,1),4) > 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 3, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end)+eVec, 2);
end
if mod(floor(e(j,1)/4),2) == 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 4, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(floor(e(j,1)/4),4) > 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 5, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end) + eVec, 2);
end
end
end
end
end
end
%Errors
counter = 1; % This will be used to iterate over the different qubits
for j = 1:length(C(:,end))
if (C(j,end) ~= -1) && (C(j,end) ~= 5) && (C(j,end) ~= 6)
Output(counter,:) = Errors(j,1:n);
Output(counter+1,:) = Errors(j,(n+1):end);
counter = counter + 2;
end
end
end
function Output = equivalenceTable(errIn) % used for measurments in the Z basis
g1 = [0,0,0,1,1,1,1];
g2 = [0,1,1,0,0,1,1];
g3 = [1,0,1,0,1,0,1];
g = [g1;g2;g3];
syn = zeros(1,3);
for i = 1:3
syn(1,i) = mod(sum(errIn.*g(i,:)), 2);
end
if isequal(syn,[0,0,0])
corr = zeros(1,7);
elseif isequal(syn,[0,0,1])
corr = [1,0,0,0,0,0,0];
elseif isequal(syn,[0,1,0])
corr = [0,1,0,0,0,0,0];
elseif isequal(syn,[0,1,1])
corr = [0,0,1,0,0,0,0];
elseif isequal(syn,[1,0,0])
corr = [0,0,0,1,0,0,0];
elseif isequal(syn,[1,0,1])
corr = [0,0,0,0,1,0,0];
elseif isequal(syn,[1,1,0])
corr = [0,0,0,0,0,1,0];
elseif isequal(syn,[1,1,1])
corr = [0,0,0,0,0,0,1];
end
Output = corr;
end
function Output = Syndrome(errIn)
g1 = [0,0,0,1,1,1,1];
g2 = [0,1,1,0,0,1,1];
g3 = [1,0,1,0,1,0,1];
g = [g1;g2;g3];
syn = zeros(1,3);
for i = 1:3
syn(1,i) = mod( sum(errIn.*g(i,:)), 2);
end
Output = syn;
end
function Output = errorGeneratorPacceptOprepUpper(errRate)
% Generates errors in the ancilla preparation part of the EC's
e = zeros(1,4);
rows = 1;
% Locations within the state prep |0> circuit
for i = 1:4
for l = 1:4
xi = rand;
if xi < errRate
k = randi([1,3]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
for l = 5:11
if (l == 5) || (l == 6) || (l == 8)
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,1];
rows = rows + 1;
end
else
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,1];
rows = rows + 1;
end
end
end
for l = 12:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
end
for i = [1,3]
for l = 1:7
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,2];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:7
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,3];
rows = rows + 1;
end
end
end
for l = 1:7
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,3,l,4];
rows = rows + 1;
end
end
for l = 1:7
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,3,l,5];
rows = rows + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3] = PacceptErrorGeneratorOPrepUpper(errRate,numIterations,n,lookUpPlus,lookUpO)
C = [4,1002,0,1000,2;
4,1000,6,-1,-1;
4,1004,0,1001,5;
4,1000,6,-1,-1];
eAccepted = zeros(1,4);
eIndex = zeros(1,1);
countereIndex = 1;
counterRows = 0;
numAccepted = 0;
while length(eAccepted(:,1)) < numIterations
e = errorGeneratorPacceptOprepUpper(errRate);
if isequal(e,zeros(1,4))
counter = 0;
else
counter = length(e(:,1));
end
propagatedMatrix = PropagationArb(C,n,e,lookUpPlus,lookUpO);
if (sum(equivalenceTable(propagatedMatrix(3,:)))==0) && (sum(equivalenceTable(propagatedMatrix(4,:)))==0) && (sum(equivalenceTable(propagatedMatrix(5,:)))==0) && (mod(sum(propagatedMatrix(3,:)),2)==0) && (mod(sum(propagatedMatrix(4,:)),2)==0) && (mod(sum(propagatedMatrix(5,:)),2)==0)
if counter ~= 0
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + counter;
eAccepted((counterLast + 1):(counterLast + counter),:) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
else
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + 1;
eAccepted((counterLast + 1),1:4) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
end
end
end
Output1 = eAccepted;
Output2 = eIndex;
Output3 = numAccepted;
end
function Output = errorGeneratorPacceptPlusprepUpper(errRate)
e = zeros(1,4);
rows = 1;
for i = 1:4
for l = 1:4
xi = rand;
if xi < errRate
k = randi([1,3]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
for l = 5:11
if (l == 7) || (l == 9) || (l == 10) || (l == 11)
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,1];
rows = rows + 1;
end
else
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,1];
rows = rows + 1;
end
end
end
for l = 12:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:7
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,2];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:7
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,3];
rows = rows + 1;
end
end
end
for l = 1:7
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,1,l,4];
rows = rows + 1;
end
end
for l = 1:7
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,3,l,5];
rows = rows + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3] = PacceptErrorGeneratorPlusPrepUpper(errRate,numIterations,n,lookUpPlus,lookUpO)
C = [3,1000,0,1003,2;
3,1001,5,-1,-1;
3,1000,0,1000,6;
3,1003,5,-1,-1];
eAccepted = zeros(1,4);
eIndex = zeros(1,1);
countereIndex = 1;
counterRows = 0;
numAccepted = 0;
while length(eAccepted(:,1)) < numIterations
e = errorGeneratorPacceptPlusprepUpper(errRate);
if isequal(e,zeros(1,4))
counter = 0;
else
counter = length(e(:,1));
end
propagatedMatrix = PropagationArb(C, n, e,lookUpPlus, lookUpO);
if (sum(equivalenceTable(propagatedMatrix(3,:)))==0) && (sum(equivalenceTable(propagatedMatrix(4,:)))==0) && (sum(equivalenceTable(propagatedMatrix(5,:)))==0) && (mod(sum(propagatedMatrix(3,:)),2)==0) && (mod(sum(propagatedMatrix(4,:)),2)==0) && (mod(sum(propagatedMatrix(5,:)),2)==0)
if counter ~= 0
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + counter;
eAccepted((counterLast + 1):(counterLast + counter),:) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
else
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + 1;
eAccepted((counterLast + 1),1:4) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
end
end
end
Output1 = eAccepted;
Output2 = eIndex;
Output3 = numAccepted;
end
function Output = errorGeneratorRemaining(errRate,numQubits)
% generates remaining errors outside state-prep circuits.
e = zeros(1,4);
counter = 1;
% Errors in first block
for i = [2,6] % Storage locations in first block
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,5];
counter = counter + 1;
end
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,2,l,6];
counter = counter + 1;
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,1,l,7];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in X basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,2,l,8];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in Z basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,6,l,8];
counter = counter + 1;
end
end
% Error at encoded CNOT location
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,1,l,9];
counter = counter + 1;
end
end
% Error in second block (connected to first data qubit)
for i = [2,6] % Storage locations in first block
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,14];
counter = counter + 1;
end
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,2,l,15];
counter = counter + 1;
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,1,l,16];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in X basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,2,l,17];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in Z basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,6,l,17];
counter = counter + 1;
end
end
% Errors in third block (connected to second data qubit)
for i = [11,15] % Storage locations in first block
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,5];
counter = counter + 1;
end
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,10,l,6];
counter = counter + 1;
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,15,l,7];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in Z basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,11,l,8];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in X basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,15,l,8];
counter = counter + 1;
end
end
% Errors in fourth block
for i = [11,15] % Storage locations in first block
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,14];
counter = counter + 1;
end
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,10,l,15];
counter = counter + 1;
end
end
for l = 1:numQubits % CNOT locations
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,15,l,16];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in Z basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,11,l,17];
counter = counter + 1;
end
end
for l = 1:numQubits % measurment in X basis
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,15,l,17];
counter = counter + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3,Output4] = depolarizingGenerator(eO,eOIndex,ePlus,ePlusIndex,errRate,numIterations,CFull,CFirst,n,lookUpPlus,lookUpO)
errorVec1 = zeros(1,15);
errorVec2 = zeros(1,15);
errorVec3 = zeros(1,15);
errorVec4 = zeros(1,15);
for ii = 1:numIterations
% Generate errors from |0> state-prep circuit in first 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e = errorO;
rows = length(e(:,1));
% Genrate errors from |+> state-prep circuit in first 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e1Plus = errorPlus;
rowse1Plus = length(e1Plus(:,1));
e((rows + 1):(rows + rowse1Plus),:) = e1Plus;
rows = rows + rowse1Plus;
% Generate errors from |0> state-prep circuit in the second 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e2O = errorO;
for i = 1:length(e2O(:,1))
e2O(i,2) = e2O(i,2) + 13;
end
rowse2O = length(e2O(:,1));
e((rows + 1):(rows + rowse2O),:) = e2O;
rows = rows + rowse2O;
% Generate errors from |+> state-prep in the second 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e2Plus = errorPlus;
for i = 1:length(e2Plus(:,1))
e2Plus(i,2) = e2Plus(i,2) + 5;
end
rowse2Plus = length(e2Plus(:,1));
e((rows + 1):(rows + rowse2Plus),:) = e2Plus;
rows = rows + rowse2Plus;
% Generate errors from |0> state-prep circuit in third 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e3O = errorO;
for i = 1:length(e3O(:,1))
e3O(i,4) = e3O(i,4) + 9;
end
rowse3O = length(e3O(:,1));
e((rows + 1):(rows + rowse3O),:) = e3O;
rows = rows + rowse3O;
% Genrate errors from |+> state-prep circuit in third 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e3Plus = errorPlus;
for i = 1:length(e3Plus(:,1))
e3Plus(i,4) = e3Plus(i,4) + 9;
end
rowse3Plus = length(e3Plus(:,1));
e((rows + 1):(rows + rowse3Plus),:) = e3Plus;
rows = rows + rowse3Plus;
% Generate errors from |0> state-prep circuit in the fourth 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e4O = errorO;
for i = 1:length(e4O(:,1))
e4O(i,2) = e4O(i,2) + 13;
e4O(i,4) = e4O(i,4) + 9;
end
rowse4O = length(e4O(:,1));
e((rows + 1):(rows + rowse4O),:) = e4O;
rows = rows + rowse4O;
% Generate errors from |+> state-prep in the fourth 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e4Plus = errorPlus;
for i = 1:length(e4Plus(:,1))
e4Plus(i,2) = e4Plus(i,2) + 5;
e4Plus(i,4) = e4Plus(i,4) + 9;
end
rowse4Plus = length(e4Plus(:,1));
e((rows + 1):(rows + rowse4Plus),:) = e4Plus;
rows = rows + rowse4Plus;
% Next we generate a random error in the circuit (outside of state-prep
% circuits) to add to the matrix e (given the error rate errRate).
eRemain = errorGeneratorRemaining(errRate);
e((rows + 1):(rows + length(eRemain(:,1))),:) = eRemain;
Cint = PropagationArb(CFirst,n,e,lookUpPlus,lookUpO); % Propagate errors up to one time step past the encoded CNOT
Cfinal = PropagationArb(CFull,n,e,lookUpPlus,lookUpO); % Propagate errors through the full CNOT circuit
% Store measurment syndromes
czRow17 = equivalenceTable(Cfinal(17,1:n));
cxRow18 = equivalenceTable(Cfinal(18,1:n));
cxRow19 = equivalenceTable(Cfinal(19,1:n));
czRow20 = equivalenceTable(Cfinal(20,1:n));
czRow33 = equivalenceTable(Cfinal(33,1:n));
cxRow34 = equivalenceTable(Cfinal(34,1:n));
cxRow35 = equivalenceTable(Cfinal(35,1:n));
czRow36 = equivalenceTable(Cfinal(36,1:n));
% Case where both TEC's have been removed
CBothECRemoved(1,:) = mod(Cint(1,:) + cxRow18,2);
CBothECRemoved(2,:) = mod(Cint(2,:) + czRow17,2);
CBothECRemoved(3,:) = mod(Cint(3,:) + cxRow19,2);
CBothECRemoved(4,:) = mod(Cint(4,:) + czRow20,2);
ef1BothECRemoved = mod(sum(mod(CBothECRemoved(1,:) + equivalenceTableX(CBothECRemoved(1,:)),2)),2);
ef2BothECRemoved = mod(sum(mod(CBothECRemoved(2,:) + equivalenceTableZ(CBothECRemoved(2,:)),2)),2);
ef3BothECRemoved = mod(sum(mod(CBothECRemoved(3,:) + equivalenceTableX(CBothECRemoved(3,:)),2)),2);
ef4BothECRemoved = mod(sum(mod(CBothECRemoved(4,:) + equivalenceTableZ(CBothECRemoved(4,:)),2)),2);
stringVec1 = [ef1BothECRemoved,ef2BothECRemoved,ef3BothECRemoved,ef4BothECRemoved];
if (sum(stringVec1) ~= 0)
ind1 = (2^3)*ef4BothECRemoved + (2^2)*ef3BothECRemoved + 2*ef2BothECRemoved + ef1BothECRemoved;
errorVec1(1,ind1) = errorVec1(1,ind1) + 1;
end
% Case where both TEC's are kept
CFullMat(1,:) = mod(Cfinal(1,:) + cxRow18 + multilayerDecoderX(mod(cxRow18 + cxRow34,2)),2);
CFullMat(2,:) = mod(Cfinal(2,:) + czRow17 + czRow20 + multilayerDecoderZ(mod(czRow17 + czRow20 + czRow33,2)),2);
CFullMat(3,:) = mod(Cfinal(3,:) + cxRow18 + cxRow19 + multilayerDecoderX(mod(cxRow18 + cxRow19 + cxRow35,2)),2);
CFullMat(4,:) = mod(Cfinal(4,:) + czRow20 + multilayerDecoderZ(mod(czRow20+ czRow36,2)),2);
ef1Full = mod(sum(mod(CFullMat(1,:) + multilayerDecoderX(CFullMat(1,:)),2)),2);
ef2Full = mod(sum(mod(CFullMat(2,:) + multilayerDecoderZ(CFullMat(2,:)),2)),2);
ef3Full = mod(sum(mod(CFullMat(3,:) + multilayerDecoderX(CFullMat(3,:)),2)),2);
ef4Full = mod(sum(mod(CFullMat(4,:) + multilayerDecoderZ(CFullMat(4,:)),2)),2);
stringVec2 = [ef1Full,ef2Full,ef3Full,ef4Full];
if (sum(stringVec2) ~= 0)
ind2 = (2^3)*ef4Full + (2^2)*ef3Full + 2*ef2Full + ef1Full;
errorVec2(1,ind2) = errorVec2(1,ind2) + 1;
end
% Case where control TEC is removed
CConECRem(1,:) = mod(Cint(1,:) + cxRow18,2);
CConECRem(2,:) = mod(Cint(2,:) + czRow17 + czRow20 + multilayerDecoderZ(mod(czRow17 + czRow20,2)),2);
CConECRem(3,:) = mod(Cfinal(3,:) + cxRow18 + cxRow19 + multilayerDecoderX(mod(cxRow18 + cxRow19 + cxRow35,2)),2);
CConECRem(4,:) = mod(Cfinal(4,:) + czRow20 + multilayerDecoderZ(mod(czRow20+ czRow36,2)),2);
ef1ConECRem = mod(sum(mod(CConECRem(1,:) + multilayerDecoderX(CConECRem(1,:)),2)),2);
ef2ConECRem = mod(sum(mod(CConECRem(2,:) + multilayerDecoderZ(CConECRem(2,:)),2)),2);
ef3ConECRem = mod(sum(mod(CConECRem(3,:) + multilayerDecoderX(CConECRem(3,:)),2)),2);
ef4ConECRem = mod(sum(mod(CConECRem(4,:) + multilayerDecoderZ(CConECRem(4,:)),2)),2);
stringVec3 = [ef1ConECRem,ef2ConECRem,ef3ConECRem,ef4ConECRem];
if (sum(stringVec3) ~= 0)
ind3 = (2^3)*ef4ConECRem + (2^2)*ef3ConECRem + 2*ef2ConECRem + ef1ConECRem;
errorVec3(1,ind3) = errorVec3(1,ind3) + 1;
end
% Case where target TEC is removed
CTarECRem(1,:) = mod(Cfinal(1,:) + cxRow18 + multilayerDecoderX(mod(cxRow18 + cxRow34,2)),2);
CTarECRem(2,:) = mod(Cfinal(2,:) + czRow17 + czRow20 + multilayerDecoderZ(mod(czRow17 + czRow20 + czRow33,2)),2);
CTarECRem(3,:) = mod(Cint(3,:) + cxRow18 + cxRow19 + multilayerDecoderX(mod(cxRow18 + cxRow19,2)),2);
CTarECRem(4,:) = mod(Cint(4,:) + czRow20,2);
ef1TarECRem = mod(sum(mod(CTarECRem(1,:) + multilayerDecoderX(CTarECRem(1,:)),2)),2);
ef2TarECRem = mod(sum(mod(CTarECRem(2,:) + multilayerDecoderZ(CTarECRem(2,:)),2)),2);
ef3TarECRem = mod(sum(mod(CTarECRem(3,:) + multilayerDecoderX(CTarECRem(3,:)),2)),2);
ef4TarECRem = mod(sum(mod(CTarECRem(4,:) + multilayerDecoderZ(CTarECRem(4,:)),2)),2);
stringVec4 = [ef1TarECRem,ef2TarECRem,ef3TarECRem,ef4TarECRem];
if (sum(stringVec4) ~= 0)
ind4 = (2^3)*ef4TarECRem + (2^2)*ef3TarECRem + 2*ef2TarECRem + ef1TarECRem;
errorVec4(1,ind4) = errorVec4(1,ind4) + 1;
end
end
Output1 = errorVec1;
Output2 = errorVec2;
Output3 = errorVec3;
Output4 = errorVec4;
end
function [Output1,Output2,Output3] = OutSynAndError(eO,eOIndex,ePlus,ePlusIndex,errRate,numIterations,CFull,n,lookUpPlus,lookUpO)
MatSyn = zeros(4*numIterations,6); % Format (XSyn|ZSyn);
MatErr = zeros(2*numIterations,14); %Format (XErr|ZErr);
numRows = 1;
countIterations = 0;
while numRows < (numIterations+1)
% Generate errors from |0> state-prep circuit in first 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e = errorO;
rows = length(e(:,1));
% Genrate errors from |+> state-prep circuit in first 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e1Plus = errorPlus;
rowse1Plus = length(e1Plus(:,1));
e((rows + 1):(rows + rowse1Plus),:) = e1Plus;
rows = rows + rowse1Plus;
% Generate errors from |0> state-prep circuit in the second 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e2O = errorO;
for i = 1:length(e2O(:,1))
e2O(i,2) = e2O(i,2) + 13;
end
rowse2O = length(e2O(:,1));
e((rows + 1):(rows + rowse2O),:) = e2O;
rows = rows + rowse2O;
% Generate errors from |+> state-prep in the second 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e2Plus = errorPlus;
for i = 1:length(e2Plus(:,1))
e2Plus(i,2) = e2Plus(i,2) + 5;
end
rowse2Plus = length(e2Plus(:,1));
e((rows + 1):(rows + rowse2Plus),:) = e2Plus;
rows = rows + rowse2Plus;
% Generate errors from |0> state-prep circuit in third 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e3O = errorO;
for i = 1:length(e3O(:,1))
e3O(i,4) = e3O(i,4) + 9;
end
rowse3O = length(e3O(:,1));
e((rows + 1):(rows + rowse3O),:) = e3O;
rows = rows + rowse3O;
% Genrate errors from |+> state-prep circuit in third 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e3Plus = errorPlus;
for i = 1:length(e3Plus(:,1))
e3Plus(i,4) = e3Plus(i,4) + 9;
end
rowse3Plus = length(e3Plus(:,1));
e((rows + 1):(rows + rowse3Plus),:) = e3Plus;
rows = rows + rowse3Plus;
% Generate errors from |0> state-prep circuit in the fourth 1-EC
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
for i = 1:length(errorO(:,1))
errorO(i,2) = errorO(i,2) + 1; % Increase index of column 2 by one so that error is inserted in the correct row in the full circuit.
end
e4O = errorO;
for i = 1:length(e4O(:,1))
e4O(i,2) = e4O(i,2) + 13;
e4O(i,4) = e4O(i,4) + 9;
end
rowse4O = length(e4O(:,1));
e((rows + 1):(rows + rowse4O),:) = e4O;
rows = rows + rowse4O;
% Generate errors from |+> state-prep in the fourth 1-EC
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
for i = 1:length(errorPlus(:,1))
errorPlus(i,2) = errorPlus(i,2) + 5;
end
e4Plus = errorPlus;
for i = 1:length(e4Plus(:,1))
e4Plus(i,2) = e4Plus(i,2) + 5;
e4Plus(i,4) = e4Plus(i,4) + 9;
end
rowse4Plus = length(e4Plus(:,1));
e((rows + 1):(rows + rowse4Plus),:) = e4Plus;
rows = rows + rowse4Plus;
% Next we generate a random error in the circuit (outside of state-prep
% circuits) to add to the matrix e (given the error rate errRate).
eRemain = errorGeneratorRemaining(errRate,n);
e((rows + 1):(rows + length(eRemain(:,1))),:) = eRemain;
Cfinal = PropagationArb(CFull,n,e,lookUpPlus,lookUpO); % Propagate errors through the full CNOT circuit
% Store measurment syndromes
ErrZ17 = Cfinal(17,:);
SynZ17 = Syndrome(ErrZ17);
ErrX18 = Cfinal(18,:);
SynX18 = Syndrome(ErrX18);
ErrX19 = Cfinal(19,:);
SynX19 = Syndrome(ErrX19);
ErrZ20 = Cfinal(20,:);
SynZ20 = Syndrome(ErrZ20);
ErrZ33 = Cfinal(2,:);
SynZ33 = Syndrome(Cfinal(33,:));
ErrX34 = Cfinal(1,:);
SynX34 = Syndrome(Cfinal(34,:));
ErrX35 = Cfinal(3,:);
SynX35 = Syndrome(Cfinal(35,:));
ErrZ36 = Cfinal(4,:);
SynZ36 = Syndrome(Cfinal(36,:));
t1 = sum(SynX18+SynZ17+SynX19+SynZ20+SynX34+SynZ33+SynX35+SynZ36);
t2 = sum(ErrZ33+ErrX34+ErrX35+ErrZ36);
if (t1 ~= 0) || (t2 ~= 0)
MatSynTemp = [SynX18,SynZ17;SynX19,SynZ20;SynX34,SynZ33;SynX35,SynZ36];
MatErrorTemp = [ErrX34,ErrZ33;ErrX35,ErrZ36];
MatSyn((4*(numRows-1)+1):(4*numRows),:) = MatSynTemp;
MatErr((2*(numRows-1)+1):(2*numRows),:) = MatErrorTemp;
numRows = numRows + 1;
end
countIterations = countIterations + 1;
end
Output1 = MatSyn;
Output2 = MatErr;
Output3 = countIterations;
end
|
github
|
pooya-git/DeepNeuralDecoder-master
|
KnillTrainingSetd5.m
|
.m
|
DeepNeuralDecoder-master/Data/Generator/Knill_CNOT_D5/KnillTrainingSetd5.m
| 115,585 |
utf_8
|
2d49b56c69ce10f5248a535f239fb15b
|
% MIT License
%
% Copyright (c) 2018 Chris Chamberland
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.
function KnillTrainingSetd3
% Circuit descriptors:
% -1: qubit non-active
% 0: Noiseless memory
% 1: Gate memory
% 2: Measurement memory
% 3: Preparation in X basis (|+> state)
% 4: Preparation in Z basis (|0> state)
% 5: Measurement in X basis
% 6: Measurement in Z basis
% 7: X gate
% 8: Z gate
% 10: H gate
% 11: S gate
% 20: T gate
%1---: Control qubit for CNOT with target ---
%1000: Target qubit for CNOT
% Circuit for CNOT 1-exRec
n = 19;
% Generate lookup table
lookUpO = lookUpOFunc(1,n);
lookUpPlus = lookUpPlusFunc(1,n);
%Test
% Knill-EC CNOT exRec circuit containing all four EC blocks
CFirst = [0,0,0,0,0,0,1002,5,-1
3,1000,0,1004,1,1006,1000,6,-1
3,1002,5,-1,-1,-1,-1,-1,-1
3,1000,0,1000,6,-1,-1,-1,-1
3,1004,5,-1,-1,-1,-1,-1,-1
4,1007,0,1000,1,1000,1,0,0
4,1000,6,-1,-1,-1,-1,-1,-1
4,1009,0,1006,5,-1,-1,-1,-1
4,1000,6,-1,-1,-1,-1,-1,-1
0,0,0,0,0,0,1011,5,-1
3,1000,0,1013,1,1015,1000,6,-1
3,1011,5,-1,-1,-1,-1,-1,-1
3,1000,0,1000,6,-1,-1,-1,-1
3,1013,5,-1,-1,-1,-1,-1,-1
4,1016,0,1000,1,1000,1,0,0
4,1000,6,-1,-1,-1,-1,-1,-1
4,1018,0,1015,5,-1,-1,-1,-1
4,1000,6,-1,-1,-1,-1,-1,-1];
CLastWithCNOT = [0,1010,0,0,0,0,0,0,1002,5,-1
0,0,3,1000,0,1004,1,1006,1000,6,-1
0,0,3,1002,5,-1,-1,-1,-1,-1,-1
0,0,3,1000,0,1000,6,-1,-1,-1,-1
0,0,3,1004,5,-1,-1,-1,-1,-1,-1
0,0,4,1007,0,1000,1,1000,1,0,0
0,0,4,1000,6,-1,-1,-1,-1,-1,-1
0,0,4,1009,0,1006,5,-1,-1,-1,-1
0,0,4,1000,6,-1,-1,-1,-1,-1,-1
0,1000,0,0,0,0,0,0,1011,5,-1
0,0,3,1000,0,1013,1,1015,1000,6,-1
0,0,3,1011,5,-1,-1,-1,-1,-1,-1
0,0,3,1000,0,1000,6,-1,-1,-1,-1
0,0,3,1013,5,-1,-1,-1,-1,-1,-1
0,0,4,1016,0,1000,1,1000,1,0,0
0,0,4,1000,6,-1,-1,-1,-1,-1,-1
0,0,4,1018,0,1015,5,-1,-1,-1,-1
0,0,4,1000,6,-1,-1,-1,-1,-1,-1];
tic
parfor i = 1:7
v = [6*10^-4,7*10^-4,8*10^-4,9*10^-4,10^-3,1.5*10^-3,2*10^-3];
errRate = v(1,i);
errStatePrepString = 'ErrorStatePrep';
str_errRate = num2str(errRate,'%0.3e');
str_mat = '.mat';
str_temp = strcat(errStatePrepString,str_errRate);
str_errStatePrep = strcat(str_temp,str_mat);
% numIterations1 = 10^5;
%
% [eO,eOIndex,numAcceptedO] = PacceptErrorGeneratorOPrepUpper(errRate,numIterations1,n,lookUpPlus,lookUpO);
% [ePlus,ePlusIndex,numAcceptedPlus] = PacceptErrorGeneratorPlusPrepUpper(errRate,numIterations1,n,lookUpPlus,lookUpO);
% parsaveErrorStatePrep(str_errStatePrep,eO,eOIndex,numAcceptedO,ePlus,ePlusIndex,numAcceptedPlus);
switch i
case 1
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep6.000e-04.mat');
case 2
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep7.000e-04.mat');
case 3
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep8.000e-04.mat');
case 4
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep9.000e-04.mat');
case 5
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep1.000e-03.mat');
case 6
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep1.500e-03.mat');
otherwise
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep2.000e-03.mat');
end
numIterations = 2*10^7;
if (~isempty(eOIndex)) && (~isempty(ePlusIndex))
[A1,A2,OutputCount] = OutSynAndError(eO,eOIndex,ePlus,ePlusIndex,errRate,numIterations,CFirst,CLastWithCNOT,n,lookUpPlus,lookUpO);
TempStr1 = 'SyndromeOnly';
TempStr2 = '.txt';
TempStr3 = 'ErrorOnly';
str_Final1 = strcat(TempStr1,str_errRate);
str_Final2 = strcat(str_Final1,TempStr2);
str_Final3 = strcat(TempStr3,str_errRate);
str_Final4 = strcat(str_Final3,TempStr2);
fid = fopen(str_Final2, 'w+t');
for ii = 1:size(A1,1)
fprintf(fid,'%g\t',A1(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
fid = fopen(str_Final4, 'w+t');
for ii = 1:size(A2,1)
fprintf(fid,'%g\t',A2(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
end
str_Count = strcat('Count',str_errRate);
str_CountFinal = strcat(str_Count,'.mat');
parsaveCount(str_CountFinal,OutputCount);
end
toc
end
function parsaveErrorStatePrep(fname,eO,eOIndex,numAcceptedO,ePlus,ePlusIndex,numAcceptedPlus)
save(fname,'eO','eOIndex','numAcceptedO','ePlus','ePlusIndex','numAcceptedPlus');
end
function parsaveErrorVec(fname,errorVecMat)
save(fname,'errorVecMat');
end
function parsaveCount(fname,OutputCount)
save(fname,'OutputCount');
end
function [out1,out2,out3,out4] = parload(fname)
load(fname);
out1 = eO;
out2 = eOIndex;
out3 = ePlus;
out4 = ePlusIndex;
end
function Output = lookUpOFunc(n,numQubits)
% Circuit for |0> state prep
lookUpO = zeros(70,5,numQubits);
C = [3 1018 1014 1013 1009 1004 1010 1007
3 1014 1018 1009 1019 1010 1015 1004
3 0 0 1019 1015 1007 1004 1013
4 0 0 0 0 1000 1000 1000
3 1019 1009 1018 1014 1015 1007 1010
3 0 0 0 0 1009 1018 1017
4 0 0 0 0 1000 1000 1000
3 0 0 1017 1010 1014 1013 1009
4 0 1000 1000 1000 1000 1 1000
4 0 0 0 1000 1000 1000 1000
3 0 0 1014 1013 1018 1017 1019
3 0 0 0 0 1013 1014 1015
4 0 0 1000 1000 1000 1000 1000
4 1000 1000 1000 1000 1000 1000 1
4 0 0 0 1000 1000 1000 1000
3 0 0 0 0 1017 1019 1018
4 0 0 1000 1 1000 1000 1000
4 1000 1000 1000 1 1000 1000 1000
4 1000 1 1000 1000 1 1000 1000];
% Find the number of gate storage locations in C
counterStorage = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) == 1
counterStorage = counterStorage + 1;
end
end
end
% Find the number of CNOT locations in C
counterCNOT = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) > 1000
counterCNOT = counterCNOT + 1;
end
end
end
% fills in lookUpTable locations where lookUpO(i,j,k) has j = k = 1.
counter = 1;
for i = 1:counterStorage
lookUpO(i,1,1) = 1;
counter = counter + 1;
end
for i = 1 : length(C(:,1))
lookUpO(counter,1,1) = C(i,1);
counter = counter + 1;
end
for i = 1 : counterCNOT
lookUpO(counter,1,1) = 1000;
counter = counter + 1;
end
e = zeros(1,4);
% fills in LookUpO(i,j,:) for storage gate errors j = 2,3.
counter = 1;
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = 2:3
if jj == 2
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
else
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
% fills in LookUpO(i,j,:) for state prep errors j = 2,3.
for i = 1:length(C(:,1))
if C(i,1) == 3
e(1,:) = [2,i,1,1];
lookUpO(counter,3,:) = zVector(C, n, e);
counter = counter + 1;
else
e(1,:) = [1,i,1,1];
lookUpO(counter,2,:) = xVector(C, n, e);
counter = counter + 1;
end
end
% fills in LookUpO(i,j,:) for CNOT erros, j = 2,3.
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = [2,3,4,5]
switch jj
case 2
if C(j,i) > 1000
e(1,:) = [1,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
case 3
if C(j,i) > 1000
e(1,:) = [2,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
end
case 4
if C(j,i) > 1000
e(1,:) = [4,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
otherwise
if C(j,i) > 1000
e(1,:) = [8,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
Output = lookUpO;
end
function Output = lookUpPlusFunc(n,numQubits)
% Circuit for |+> state prep
lookUpPlus = zeros(70,5,numQubits);
C = [4 1000 1000 1000 1000 1000 1000 1000
4 1000 1000 1000 1000 1000 1000 1000
4 0 0 1000 1000 1000 1000 1000
3 0 0 0 0 1001 1003 1002
4 1000 1000 1000 1000 1000 1000 1000
4 0 0 0 0 1000 1000 1000
3 0 0 0 0 1003 1005 1001
4 0 0 1000 1000 1000 1000 1000
3 0 1005 1002 1001 1006 1 1008
3 0 0 0 1008 1002 1001 1005
4 0 0 1000 1000 1000 1000 1000
4 0 0 0 0 1000 1000 1000
3 0 0 1001 1011 1012 1008 1003
3 1002 1001 1011 1005 1008 1012 1
3 0 0 0 1003 1005 1002 1012
4 0 0 0 0 1000 1000 1000
3 0 0 1008 1 1016 1011 1006
3 1001 1002 1005 1 1011 1006 1016
3 1005 1 1003 1002 1 1016 1011];
% Find the number of gate storage locations in C
counterStorage = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) == 1
counterStorage = counterStorage + 1;
end
end
end
% Find the number of CNOT locations in C
counterCNOT = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) > 1000
counterCNOT = counterCNOT + 1;
end
end
end
% fills in lookUpTable locations where lookUpO(i,j,k) has j = k = 1.
counter = 1;
for i = 1:counterStorage
lookUpPlus(i,1,1) = 1;
counter = counter + 1;
end
for i = 1 : length(C(:,1))
lookUpPlus(counter,1,1) = C(i,1);
counter = counter + 1;
end
for i = 1 : counterCNOT
lookUpPlus(counter,1,1) = 1000;
counter = counter + 1;
end
e = zeros(1,4);
% fills in LookUpO(i,j,:) for storage gate errors j = 2,3.
counter = 1;
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = 2:3
if jj == 2
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
else
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
% fills in LookUpO(i,j,:) for state prep errors j = 2,3.
for i = 1:length(C(:,1))
if C(i,1) == 3
e(1,:) = [2,i,1,1];
lookUpPlus(counter,3,:) = zVector(C, n, e);
counter = counter + 1;
else
e(1,:) = [1,i,1,1];
lookUpPlus(counter,2,:) = xVector(C, n, e);
counter = counter + 1;
end
end
% fills in LookUpO(i,j,:) for CNOT erros, j = 2,3.
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = [2,3,4,5]
switch jj
case 2
if C(j,i) > 1000
e(1,:) = [1,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
case 3
if C(j,i) > 1000
e(1,:) = [2,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
end
case 4
if C(j,i) > 1000
e(1,:) = [4,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
otherwise
if C(j,i) > 1000
e(1,:) = [8,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
Output = lookUpPlus;
end
function Output = PropagationStatePrepArb(C, n, e)
% C encodes information about the circuit
% n is the number of qubits per encoded codeblock
% eN are the error entries (location and time)
% The Output matrix will contain (2q+m) rows and n columns. The paramters Output(i,j) are:
% i <= 2q and odd: Stores X type errors for output qubit #ceil(i/2) (order based on matrix C)
% i <= 2q and even: Stores Z type errors for output qubit #ceil(i/2) (order based on matrix C)
% i > 2q: Stores measurement error for measurement number #i-2q (type is X or Z depending on measurement type)
% The Errors matrix will be a tensor with 2 parameters Output(i, j)
% i: logical qubit number
% j<=n: X error at physical qubit number j
% j>n : Z error at physical qubit number j
% Error inputs eN are characterized by four parameters, thus a vector (i,j, k, l)
% i: error type: 0 = I, 1 = X, 2 = Z, 3 = Y
% j: logical qubit number (if the entry here is '0' then this will correspond to an identity "error")
% k: physical qubit number within a codeblock
% l: time location
N_meas = length(find(C==5)) + length(find(C==6)); % number of logical measurements in the circuit
N_output = length(C(:,end)) - sum(C(:,end)==-1) - sum(C(:,end)==5) - sum(C(:,end)==6); % number of output active qubits that have not been measured
Meas_dict = [find(C==5); find(C==6)];
Meas_dict = sort(Meas_dict);
Output = zeros(2*N_output + N_meas, n);
Errors = zeros(length(C(:,1)), 2*n);
for t= 1:length(C(1,:))
% If the error occurs at a measurement location then the error is introduced before propagation of faults
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( ( C(e(j,2),t) == 5 ) || ( C(e(j,2),t) == 6 ) )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
end
end
% Propagation of errors (do not need to do it for the first step of circuit
if t>1
for i = 1:length(C(:,t))
if C(i, t) == 10
% In this case must flip the X and Z error information
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = v2;
Errors(i, n+1:end) = v1;
end
if C(i, t) == 11
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = mod(v1+v2, 2);
end
if C(i,t) > 1000
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 1000, t) == 1000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 1000, 1:n);
w2 = Errors(C(i,t) - 1000, (n+1):end);
%mod(v2+w2,2)
Errors(C(i,t) - 1000, 1:n) = mod(v1+w1, 2);
Errors(i, (n+1):end) = mod(v2+w2, 2);
end
end
if C(i,t) == 5
% This corresponds to X measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, (n+1):end);
Errors(i, 1:end) = 0;
end
if C(i,t) == 6
% This corresponds to Z measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, 1:n);
Errors(i, 1:end) = 0;
end
end
end
% Introduce faults for locations that are not measurements
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( C(e(j,2),t) ~= 5 ) && ( C(e(j,2),t) ~= 6 )
% This IF statement checks to see if the gate at this location is NOT a CNOT or Prep
if ( C(e(j,2),t) < 1000 ) %&& ( C(e(j,2),t) ~= 3 ) && ( C(e(j,2),t) ~= 4 )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
% Introduce errors in the case of CNOT gate for control and target qubits
% Errors for control qubit are entry mod(e(j,1),4) according to standard indexing above
if ( C(e(j,2),t) > 1000 )
if C(C(e(j,2),t) - 1000, t) == 1000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 1000, e(j,3)) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 1000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)+n) + 1, 2);
end
end
end
end
end
end
end
%Errors
counter = 1; % This will be used to iterate over the different qubits
for j = 1:length(C(:,end))
if (C(j,end) ~= -1) && (C(j,end) ~= 5) && (C(j,end) ~= 6)
Output(counter,:) = Errors(j,1:n);
Output(counter+1,:) = Errors(j,(n+1):end);
counter = counter + 2;
end
end
end
function Output = xVector(C, n, e)
outputMatrix = PropagationStatePrepArb(C, n, e);
jx = 1;
for i = 1:length(outputMatrix)
if mod(i,2) == 1
xvector(jx) = outputMatrix(i,1);
jx = jx + 1;
end
end
Output = xvector;
end
function Output = zVector(C, n, e)
outputMatrix = PropagationStatePrepArb(C, n, e);
jz = 1;
for i = 1:length(outputMatrix)
if mod(i,2) == 0
zvector(jz) = outputMatrix(i,1);
jz = jz + 1;
end
end
Output = zvector;
end
function Output = PropagationArb(C, n, e, XPrepTable, ZPrepTable)
% C encodes information about the circuit
% n is the number of qubits per encoded codeblock
% eN are the error entries (location and time)
% The Output matrix will contain (2q+m) rows and n columns. The paramters Output(i,j) are:
% i <= 2q and odd: Stores X type errors for output qubit #ceil(i/2) (order based on matrix C)
% i <= 2q and even: Stores Z type errors for output qubit #ceil(i/2) (order based on matrix C)
% i > 2q: Stores measurement error for measurement number #i-2q (type is X or Z depending on measurement type)
% The Errors matrix will be a tensor with 2 parameters Output(i, j)
% i: logical qubit number
% j<=n: X error at physical qubit number j
% j>n : Z error at physical qubit number j
% Error inputs eN are characterized by four parameters, thus a vector (i,j, k, l)
% i: error type: 0 = I, 1 = X, 2 = Z, 3 = Y
% j: logical qubit number (if the entry here is '0' then this will correspond to an identity "error")
% k: physical qubit number within a codeblock
% l: time location
N_meas = length(find(C==5)) + length(find(C==6)); % number of logical measurements in the circuit
N_output = length(C(:,end)) - sum(C(:,end)==-1) - sum(C(:,end)==5) - sum(C(:,end)==6); % number of output active qubits that have not been measured
Meas_dict = [find(C==5); find(C==6)];
Meas_dict = sort(Meas_dict);
Output = zeros(2*N_output + N_meas, n);
Errors = zeros(length(C(:,1)), 2*n);
for t= 1:length(C(1,:))
% If the error occurs at a measurement location then the error is introduced before propagation of faults
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( ( C(e(j,2),t) == 5 ) || ( C(e(j,2),t) == 6 ) )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
end
end
% Propagation of errors (do not need to do it for the first step of
% circuit)
if t>1
for i = 1:length(C(:,t))
if C(i, t) == 10
% In this case must flip the X and Z error information
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = v2;
Errors(i, n+1:end) = v1;
end
if C(i, t) == 11
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = mod(v1+v2, 2);
end
if C(i,t) > 1000
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 1000, t) == 1000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 1000, 1:n);
w2 = Errors(C(i,t) - 1000, (n+1):end);
%mod(v2+w2,2)
Errors(C(i,t) - 1000, 1:n) = mod(v1+w1, 2);
Errors(i, (n+1):end) = mod(v2+w2, 2);
end
end
if C(i,t) == 5
% This corresponds to X measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, (n+1):end);
Errors(i, 1:end) = 0;
end
if C(i,t) == 6
% This corresponds to Z measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, 1:n);
Errors(i, 1:end) = 0;
end
end
end
% Introduce faults for locations that are not measurements
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( C(e(j,2),t) ~= 5 ) && ( C(e(j,2),t) ~= 6 )
% This IF statement checks to see if the gate at this location is NOT a CNOT or Prep
if ( C(e(j,2),t) < 1000 ) && ( C(e(j,2),t) ~= 3 ) && ( C(e(j,2),t) ~= 4 )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
% Introduce errors in the case of CNOT gate for control and target qubits
% Errors for control qubit are entry mod(e(j,1),4) according to standard indexing above
if ( C(e(j,2),t) > 1000 )
if C(C(e(j,2),t) - 1000, t) == 1000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 1000, e(j,3)) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 1000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)+n) + 1, 2);
end
end
end
% Introduce errors in the case of |0> prep
if ( C(e(j,2),t) == 4 )
eVec = zeros(1,n);
if mod(e(j,1),2) == 1
% Need to translate the entries in the Prep tables to right format
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 2, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(e(j,1),4) > 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 3, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end)+eVec, 2);
end
if mod(floor(e(j,1)/4),2) == 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 4, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(floor(e(j,1)/4),4) > 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 5, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end) + eVec, 2);
end
end
% Introduce errors in the case of |+> prep
if ( C(e(j,2),t) == 3 )
eVec = zeros(1,n);
if mod(e(j,1),2) == 1
% Need to translate the entries in the Prep tables to right format
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 2, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(e(j,1),4) > 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 3, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end)+eVec, 2);
end
if mod(floor(e(j,1)/4),2) == 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 4, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(floor(e(j,1)/4),4) > 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 5, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end) + eVec, 2);
end
end
end
end
end
end
%Errors
counter = 1; % This will be used to iterate over the different qubits
for j = 1:length(C(:,end))
if (C(j,end) ~= -1) && (C(j,end) ~= 5) && (C(j,end) ~= 6)
Output(counter,:) = Errors(j,1:n);
Output(counter+1,:) = Errors(j,(n+1):end);
counter = counter + 2;
end
end
end
function Output = IdealDecoder19QubitColor(xErr)
Stabs = [1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 1 1 0 0 1 1 1 0 0 0 0 0 0
1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0];
newMat = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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od(sum(conj(xErr).* Stabs(i,1:19)),2); % obtain error syndrom
end
correctionRow = 1;
% convert binary syndrome to decimal to find row in matrix newMat
% corresponding to measured syndrome
for i = 1:length(Syn)
correctionRow = correctionRow + 2^(9-i)*Syn(i);
end
Output = newMat(correctionRow,:);
end
function Output = Syndrome(errIn)
g = [1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 1 1 0 0 1 1 1 0 0 0 0 0 0
1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0];
syn = zeros(1,9);
for i = 1:9
syn(1,i) = mod( sum(errIn.*g(i,:)), 2);
end
Output = syn;
end
function Output = errorGeneratorPacceptOprepUpper(errRate)
% Generates errors in the ancilla preparation part of the EC's
e = zeros(1,4);
rows = 1;
% Locations within the state prep |0> circuit
for i = 1:2
for l = 1:6
xi = rand;
if xi < errRate
k = randi([1,3]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
for l = 7:25
if (l == 7) || (l == 8) || (l == 9) || (l == 11) || (l == 12) || (l == 14) || (l == 17) || (l == 18) || (l == 22)
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,1];
rows = rows + 1;
end
else
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,1];
rows = rows + 1;
end
end
end
for l = 26:70
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
end
for i = [1,3]
for l = 1:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,2];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:19
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,3];
rows = rows + 1;
end
end
end
for l = 1:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,3,l,4];
rows = rows + 1;
end
end
for l = 1:19
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,3,l,5];
rows = rows + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3] = PacceptErrorGeneratorOPrepUpper(errRate,numIterations,n,lookUpPlus,lookUpO)
C = [4,1002,0,1000,2;
4,1000,6,-1,-1;
4,1004,0,1001,5;
4,1000,6,-1,-1];
eAccepted = zeros(1,4);
eIndex = zeros(1,1);
countereIndex = 1;
counterRows = 0;
numAccepted = 0;
while length(eAccepted(:,1)) < numIterations
e = errorGeneratorPacceptOprepUpper(errRate);
if isequal(e,zeros(1,4))
counter = 0;
else
counter = length(e(:,1));
end
propagatedMatrix = PropagationArb(C,n,e,lookUpPlus,lookUpO);
if (sum(IdealDecoder19QubitColor(propagatedMatrix(3,:)))==0) && (sum(IdealDecoder19QubitColor(propagatedMatrix(4,:)))==0) && (sum(IdealDecoder19QubitColor(propagatedMatrix(5,:)))==0) && (mod(sum(propagatedMatrix(3,:)),2)==0) && (mod(sum(propagatedMatrix(4,:)),2)==0) && (mod(sum(propagatedMatrix(5,:)),2)==0)
if counter ~= 0
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + counter;
eAccepted((counterLast + 1):(counterLast + counter),:) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
else
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + 1;
eAccepted((counterLast + 1),1:4) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
end
end
end
Output1 = eAccepted;
Output2 = eIndex;
Output3 = numAccepted;
end
function Output = errorGeneratorPacceptPlusprepUpper(errRate)
e = zeros(1,4);
rows = 1;
for i = 1:2
for l = 1:6
xi = rand;
if xi < errRate
k = randi([1,3]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
for l = 7:25
if (l == 7) || (l == 8) || (l == 9) || (l == 11) || (l == 12) || (l == 14) || (l == 17) || (l == 18) || (l == 22)
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,1];
rows = rows + 1;
end
else
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,1];
rows = rows + 1;
end
end
end
for l = 26:70
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,2];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:19
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,3];
rows = rows + 1;
end
end
end
for l = 1:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,1,l,4];
rows = rows + 1;
end
end
for l = 1:19
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,3,l,5];
rows = rows + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3] = PacceptErrorGeneratorPlusPrepUpper(errRate,numIterations,n,lookUpPlus,lookUpO)
C = [3,1000,0,1003,2;
3,1001,5,-1,-1;
3,1000,0,1000,6;
3,1003,5,-1,-1];
eAccepted = zeros(1,4);
eIndex = zeros(1,1);
countereIndex = 1;
counterRows = 0;
numAccepted = 0;
while length(eAccepted(:,1)) < numIterations
e = errorGeneratorPacceptPlusprepUpper(errRate);
if isequal(e,zeros(1,4))
counter = 0;
else
counter = length(e(:,1));
end
propagatedMatrix = PropagationArb(C, n, e,lookUpPlus, lookUpO);
if (sum(IdealDecoder19QubitColor(propagatedMatrix(3,:)))==0) && (sum(IdealDecoder19QubitColor(propagatedMatrix(4,:)))==0) && (sum(IdealDecoder19QubitColor(propagatedMatrix(5,:)))==0) && (mod(sum(propagatedMatrix(3,:)),2)==0) && (mod(sum(propagatedMatrix(4,:)),2)==0) && (mod(sum(propagatedMatrix(5,:)),2)==0)
if counter ~= 0
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + counter;
eAccepted((counterLast + 1):(counterLast + counter),:) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
else
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + 1;
eAccepted((counterLast + 1),1:4) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
end
end
end
Output1 = eAccepted;
Output2 = eIndex;
Output3 = numAccepted;
end
function Output = errorGeneratorRemainingCFirst(errRate,numQubits)
% This function generates remaining errors outside state-prep circuits in
% a Knill-EC CNOT exRec circuit.
e = zeros(1,4);
counter = 1;
% Errors at all the storage locations
for i = [2,6,11,15]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,5];
counter = counter + 1;
end
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,6,l,7];
counter = counter + 1;
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,15,l,7];
counter = counter + 1;
end
end
% Errors at measurement locations
% X-measurement locations
for i = [1,10]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,i,l,8];
counter = counter + 1;
end
end
end
% Z-measurement locations
for i = [2,11]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,i,l,8];
counter = counter + 1;
end
end
end
% Errors at CNOT locations
% Full CNOT's
for i = [2,11]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,i,l,6];
counter = counter + 1;
end
end
end
% CNOT's coupling to data prior to teleportation
for i = [1,10]
for l = 1:numQubits
xi = rand;
if xi < 12*errRate/15
vecErr = [2,4,6];
vecRand = randi([1,3]);
k = vecErr(1,vecRand);
e(counter,:) = [k,i,l,7];
counter = counter + 1;
end
end
end
Output = e;
end
function Output = errorGeneratorRemainingCLastWithCNOT(errRate,numQubits)
% This function generates remaining errors outside state-prep circuits in
% a Knill-EC CNOT exRec circuit.
e = zeros(1,4);
counter = 1;
% Errors at all the storage locations
for i = [2,6,11,15]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,7];
counter = counter + 1;
end
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,6,l,9];
counter = counter + 1;
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,15,l,9];
counter = counter + 1;
end
end
% Errors at measurement locations
% X-measurement locations
for i = [1,10]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,i,l,10];
counter = counter + 1;
end
end
end
% Z-measurement locations
for i = [2,11]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,i,l,10];
counter = counter + 1;
end
end
end
% Errors at CNOT locations
% Full CNOT's
for i = [2,11]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,i,l,8];
counter = counter + 1;
end
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,1,l,2];
counter = counter + 1;
end
end
% CNOT's coupling to data prior to teleportation
for i = [1,10]
for l = 1:numQubits
xi = rand;
if xi < 12*errRate/15
vecErr = [2,4,6];
vecRand = randi([1,3]);
k = vecErr(1,vecRand);
e(counter,:) = [k,i,l,9];
counter = counter + 1;
end
end
end
Output = e;
end
function Output = ConvertVecXToErrMatX(ErrIn)
e = zeros(1,4);
counter = 1;
for i = 1:length(ErrIn(1,:))
if ErrIn(1,i) ~= 0
e(counter,:) = [1,1,i,1];
counter = counter + 1;
end
end
Output = e;
end
function Output = ConvertVecZToErrMatZ(ErrIn)
e = zeros(1,4);
counter = 1;
for i = 1:length(ErrIn(1,:))
if ErrIn(1,i) ~= 0
e(counter,:) = [2,1,i,1];
counter = counter + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3] = OutSynAndError(eO,eOIndex,ePlus,ePlusIndex,errRate,numIterations,CFirst,CLastWithCNOT,n,lookUpPlus,lookUpO)
MatSyn = zeros(4*numIterations,18); % Format (XSyn|ZSyn);
MatErr = zeros(2*numIterations,38); %Format (XErr|ZErr);
numRows = 1;
countIterations = 0;
while numRows < (numIterations+1)
% We will first propagate errors through the leading EC's. Recall that
% errors on blocks 1 and 10 should be copied to bloks 6 and 15 due to
% the teleportation occuring in Knill EC.
% Generate errors from |0> state-prep circuit in the first EC block
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
errorO(:,2) = errorO(:,2) + 5; % Insert errors on the appropriate block of the EC circuit
e = errorO;
rows = length(e(:,1));
% Genrate errors from |+> state-prep circuit in the first EC block
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
errorPlus(:,2) = errorPlus(:,2) + 1; % Insert errors on the appropriate block of the EC circuit
rowse1Plus = length(errorPlus(:,1));
e((rows + 1):(rows + rowse1Plus),:) = errorPlus;
rows = rows + rowse1Plus;
% Generate errors from |0> state-prep circuit in the second EC block
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
errorO(:,2) = errorO(:,2) + 14; % Insert errors on the appropriate block of the EC circuit
rowse2O = length(errorO(:,1));
e((rows + 1):(rows + rowse2O),:) = errorO;
rows = rows + rowse2O;
% Generate errors from |+> state-prep in the second EC block
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
errorPlus(:,2) = errorPlus(:,2) + 10; % Insert errors on the appropriate block of the EC circuit
rowse2Plus = length(errorPlus(:,1));
e((rows + 1):(rows + rowse2Plus),:) = errorPlus;
rows = rows + rowse2Plus;
% Next we generate a random error in the circuit (outside of state-prep
% circuits) to add to the matrix e (given the error rate errRate).
eRemain = errorGeneratorRemainingCFirst(errRate,n);
e((rows + 1):(rows + length(eRemain(:,1))),:) = eRemain;
ErrOutFirst = PropagationArb(CFirst,n,e,lookUpPlus,lookUpO); % Propagate errors through the CFirst circuit
% Next we store the syndromes based on the measured syndromes
XSynB1EC1 = Syndrome(ErrOutFirst(18,:));
ZSynB1EC1 = Syndrome(ErrOutFirst(17,:));
XSynB2EC1 = Syndrome(ErrOutFirst(20,:));
ZSynB2EC1 = Syndrome(ErrOutFirst(19,:));
% Add X errors of control input qubit to control teleported qubit
XerrB1EC1 = mod(ErrOutFirst(1,:)+ErrOutFirst(18,:),2);
% Add Z errors of control input qubit to control teleported qubit
ZerrB1EC1 = mod(ErrOutFirst(2,:)+ErrOutFirst(17,:),2);
% Add X errors of target input qubit to target teleported qubit
XerrB2EC1 = mod(ErrOutFirst(3,:)+ErrOutFirst(20,:),2);
% Add Z errors of target input qubit to target teleported qubit
ZerrB2EC1 = mod(ErrOutFirst(4,:)+ErrOutFirst(19,:),2);
% Next we convert the output errors into matrix form for input into the
% final part of the CNOT exRec circuit
e1X = ConvertVecXToErrMatX(XerrB1EC1);
e1Z = ConvertVecZToErrMatZ(ZerrB1EC1);
e2X = ConvertVecXToErrMatX(XerrB2EC1);
e2Z = ConvertVecZToErrMatZ(ZerrB2EC1);
e2X(1,2) = 10;
e2Z(1,2) = 10;
eFinal = [e1X;e1Z;e2X;e2Z];
rows = length(eFinal(:,1));
% Generate errors from |0> state-prep circuit in the third EC block
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
errorO(:,2) = errorO(:,2) + 5;
errorO(:,4) = errorO(:,4) + 2;
rowse3O = length(errorO(:,1));
eFinal((rows + 1):(rows + rowse3O),:) = errorO;
rows = rows + rowse3O;
% Genrate errors from |+> state-prep circuit in the first EC block
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
errorPlus(:,2) = errorPlus(:,2) + 1;
errorPlus(:,4) = errorPlus(:,4) + 2;
rowse3Plus = length(errorPlus(:,1));
eFinal((rows + 1):(rows + rowse3Plus),:) = errorPlus;
rows = rows + rowse3Plus;
% Generate errors from |0> state-prep circuit in the fourth EC block
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
errorO(:,2) = errorO(:,2) + 14;
errorO(:,4) = errorO(:,4) + 2;
rowse4O = length(errorO(:,1));
eFinal((rows + 1):(rows + rowse4O),:) = errorO;
rows = rows + rowse4O;
% Generate errors from |+> state-prep in the fourth EC block
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
errorPlus(:,2) = errorPlus(:,2) + 10;
errorPlus(:,4) = errorPlus(:,4) + 2;
rowse4Plus = length(errorPlus(:,1));
eFinal((rows + 1):(rows + rowse4Plus),:) = errorPlus;
rows = rows + rowse4Plus;
% Next we generate a random error in the final output circuit
% (outside of state-prep circuits) to add to the matrix e
% (given the error rate errRate).
errorRemainFinal = errorGeneratorRemainingCLastWithCNOT(errRate,n);
eFinal((rows + 1):(rows + length(errorRemainFinal(:,1))),:) = errorRemainFinal;
ErrOutLast = PropagationArb(CLastWithCNOT,n,eFinal,lookUpPlus,lookUpO); % Propagate errors through the CFirst circuit
% Next we store the syndromes based on the measured syndromes
XSynB1EC2 = Syndrome(ErrOutLast(18,:));
ZSynB1EC2 = Syndrome(ErrOutLast(17,:));
XSynB2EC2 = Syndrome(ErrOutLast(20,:));
ZSynB2EC2 = Syndrome(ErrOutLast(19,:));
% Add X errors of control input qubit to control teleported qubit
XerrB1EC2 = mod(ErrOutLast(1,:)+ ErrOutLast(18,:),2);
% Add Z errors of control input qubit to control teleported qubit
ZerrB1EC2 = mod(ErrOutLast(2,:)+ ErrOutLast(17,:),2);
% Add X errors of target input qubit to target teleported qubit
XerrB2EC2 = mod(ErrOutLast(3,:)+ ErrOutLast(20,:),2);
% Add Z errors of target input qubit to target teleported qubit
ZerrB2EC2 = mod(ErrOutLast(4,:)+ ErrOutLast(19,:),2);
t1 = sum(XSynB1EC1 + ZSynB1EC1 + XSynB2EC1 + ZSynB2EC1 + XSynB1EC2 + ZSynB1EC2 + XSynB2EC2 + ZSynB2EC2);
t2 = sum(XerrB1EC2 + ZerrB1EC2 + XerrB2EC2 + ZerrB2EC2);
if (t1 ~= 0) || (t2 ~= 0)
MatSynTemp = [XSynB1EC1,ZSynB1EC1;XSynB2EC1,ZSynB2EC1;XSynB1EC2,ZSynB1EC2;XSynB2EC2,ZSynB2EC2];
MatErrorTemp = [XerrB1EC2,ZerrB1EC2;XerrB2EC2,ZerrB2EC2];
MatSyn((4*(numRows-1)+1):(4*numRows),:) = MatSynTemp;
MatErr((2*(numRows-1)+1):(2*numRows),:) = MatErrorTemp;
numRows = numRows + 1;
end
countIterations = countIterations + 1;
end
Output1 = MatSyn;
Output2 = MatErr;
Output3 = countIterations;
end
|
github
|
pooya-git/DeepNeuralDecoder-master
|
KnillTrainingSetd3.m
|
.m
|
DeepNeuralDecoder-master/Data/Generator/Knill_CNOT_D3/KnillTrainingSetd3.m
| 54,575 |
utf_8
|
9fda8f3ecaae3b68dc4a0a6fa3389b07
|
% MIT License
%
% Copyright (c) 2018 Chris Chamberland
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.
function KnillTrainingSetd3
% Circuit descriptors:
% -1: qubit non-active
% 0: Noiseless memory
% 1: Gate memory
% 2: Measurement memory
% 3: Preparation in X basis (|+> state)
% 4: Preparation in Z basis (|0> state)
% 5: Measurement in X basis
% 6: Measurement in Z basis
% 7: X gate
% 8: Z gate
% 10: H gate
% 11: S gate
% 20: T gate
%1---: Control qubit for CNOT with target ---
%1000: Target qubit for CNOT
% Circuit for CNOT 1-exRec
n = 7;
% Generate lookup table
lookUpO = lookUpOFunc(1,n);
lookUpPlus = lookUpPlusFunc(1,n);
CFirst = [0,0,0,0,0,0,1002,5,-1
3,1000,0,1004,1,1006,1000,6,-1
3,1002,5,-1,-1,-1,-1,-1,-1
3,1000,0,1000,6,-1,-1,-1,-1
3,1004,5,-1,-1,-1,-1,-1,-1
4,1007,0,1000,1,1000,1,0,0
4,1000,6,-1,-1,-1,-1,-1,-1
4,1009,0,1006,5,-1,-1,-1,-1
4,1000,6,-1,-1,-1,-1,-1,-1
0,0,0,0,0,0,1011,5,-1
3,1000,0,1013,1,1015,1000,6,-1
3,1011,5,-1,-1,-1,-1,-1,-1
3,1000,0,1000,6,-1,-1,-1,-1
3,1013,5,-1,-1,-1,-1,-1,-1
4,1016,0,1000,1,1000,1,0,0
4,1000,6,-1,-1,-1,-1,-1,-1
4,1018,0,1015,5,-1,-1,-1,-1
4,1000,6,-1,-1,-1,-1,-1,-1];
CLastWithCNOT = [0,1010,0,0,0,0,0,0,1002,5,-1
0,0,3,1000,0,1004,1,1006,1000,6,-1
0,0,3,1002,5,-1,-1,-1,-1,-1,-1
0,0,3,1000,0,1000,6,-1,-1,-1,-1
0,0,3,1004,5,-1,-1,-1,-1,-1,-1
0,0,4,1007,0,1000,1,1000,1,0,0
0,0,4,1000,6,-1,-1,-1,-1,-1,-1
0,0,4,1009,0,1006,5,-1,-1,-1,-1
0,0,4,1000,6,-1,-1,-1,-1,-1,-1
0,1000,0,0,0,0,0,0,1011,5,-1
0,0,3,1000,0,1013,1,1015,1000,6,-1
0,0,3,1011,5,-1,-1,-1,-1,-1,-1
0,0,3,1000,0,1000,6,-1,-1,-1,-1
0,0,3,1013,5,-1,-1,-1,-1,-1,-1
0,0,4,1016,0,1000,1,1000,1,0,0
0,0,4,1000,6,-1,-1,-1,-1,-1,-1
0,0,4,1018,0,1015,5,-1,-1,-1,-1
0,0,4,1000,6,-1,-1,-1,-1,-1,-1];
parfor i = 1:7
v = [10^-4,2*10^-4,3*10^-4,4*10^-4,5*10^-4,6*10^-4,7*10^-4];
errRate = v(1,i);
errStatePrepString = 'ErrorStatePrep';
str_errRate = num2str(errRate,'%0.3e');
str_mat = '.mat';
str_temp = strcat(errStatePrepString,str_errRate);
str_errStatePrep = strcat(str_temp,str_mat);
% numIterations1 = 10^5;
%
% [eO,eOIndex,numAcceptedO] = PacceptErrorGeneratorOPrepUpper(errRate,numIterations1,n,lookUpPlus,lookUpO);
% [ePlus,ePlusIndex,numAcceptedPlus] = PacceptErrorGeneratorPlusPrepUpper(errRate,numIterations1,n,lookUpPlus,lookUpO);
% parsaveErrorStatePrep(str_errStatePrep,eO,eOIndex,numAcceptedO,ePlus,ePlusIndex,numAcceptedPlus);
switch i
case 1
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep1.000e-04.mat');
case 2
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep2.000e-04.mat');
case 3
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep3.000e-04.mat');
case 4
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep4.000e-04.mat');
case 5
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep5.000e-04.mat');
case 6
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep6.000e-04.mat');
case 7
[eO,eOIndex,ePlus,ePlusIndex] = parload('ErrorStatePrep7.000e-04.mat');
end
numIterations = 2*10^6;
if (~isempty(eOIndex)) && (~isempty(ePlusIndex))
[A1,A2,OutputCount] = OutSynAndError(eO,eOIndex,ePlus,ePlusIndex,errRate,numIterations,CFirst,CLastWithCNOT,n,lookUpPlus,lookUpO);
TempStr1 = 'SyndromeOnly';
TempStr2 = '.txt';
TempStr3 = 'ErrorOnly';
str_Final1 = strcat(TempStr1,str_errRate);
str_Final2 = strcat(str_Final1,TempStr2);
str_Final3 = strcat(TempStr3,str_errRate);
str_Final4 = strcat(str_Final3,TempStr2);
fid = fopen(str_Final2, 'w+t');
for ii = 1:size(A1,1)
fprintf(fid,'%g\t',A1(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
fid = fopen(str_Final4, 'w+t');
for ii = 1:size(A2,1)
fprintf(fid,'%g\t',A2(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
end
str_Count = strcat('Count',str_errRate);
str_CountFinal = strcat(str_Count,'.mat');
parsaveCount(str_CountFinal,OutputCount);
end
end
function parsaveErrorStatePrep(fname,eO,eOIndex,numAcceptedO,ePlus,ePlusIndex,numAcceptedPlus)
save(fname,'eO','eOIndex','numAcceptedO','ePlus','ePlusIndex','numAcceptedPlus');
end
function parsaveErrorVec(fname,errorVecMat)
save(fname,'errorVecMat');
end
function parsaveCount(fname,OutputCount)
save(fname,'OutputCount');
end
function [out1,out2,out3,out4] = parload(fname)
load(fname);
out1 = eO;
out2 = eOIndex;
out3 = ePlus;
out4 = ePlusIndex;
end
function Output = lookUpOFunc(n,numQubits)
% Circuit for |0> state prep
lookUpO = zeros(19,5,numQubits);
C = [3,1007,1005,1003;
3,1003,1006,1;
4,1000,1,1000;
3,1006,1,1005;
4,0,1000,1000;
4,1000,1000,1007;
4,1000,1,1000];
% Find the number of gate storage locations in C
counterStorage = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) == 1
counterStorage = counterStorage + 1;
end
end
end
% Find the number of CNOT locations in C
counterCNOT = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) > 1000
counterCNOT = counterCNOT + 1;
end
end
end
% fills in lookUpTable locations where lookUpO(i,j,k) has j = k = 1.
counter = 1;
for i = 1:counterStorage
lookUpO(i,1,1) = 1;
counter = counter + 1;
end
for i = 1 : length(C(:,1))
lookUpO(counter,1,1) = C(i,1);
counter = counter + 1;
end
for i = 1 : counterCNOT
lookUpO(counter,1,1) = 1000;
counter = counter + 1;
end
e = zeros(1,4);
% fills in LookUpO(i,j,:) for storage gate errors j = 2,3.
counter = 1;
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = 2:3
if jj == 2
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
else
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
% fills in LookUpO(i,j,:) for state prep errors j = 2,3.
for i = 1:length(C(:,1))
if C(i,1) == 3
e(1,:) = [2,i,1,1];
lookUpO(counter,3,:) = zVector(C, n, e);
counter = counter + 1;
else
e(1,:) = [1,i,1,1];
lookUpO(counter,2,:) = xVector(C, n, e);
counter = counter + 1;
end
end
% fills in LookUpO(i,j,:) for CNOT erros, j = 2,3.
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = [2,3,4,5]
switch jj
case 2
if C(j,i) > 1000
e(1,:) = [1,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
case 3
if C(j,i) > 1000
e(1,:) = [2,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
end
case 4
if C(j,i) > 1000
e(1,:) = [4,j,1,i];
lookUpO(counter,jj,:) = xVector(C, n, e);
end
otherwise
if C(j,i) > 1000
e(1,:) = [8,j,1,i];
lookUpO(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
Output = lookUpO;
end
function Output = lookUpPlusFunc(n,numQubits)
% Circuit for |+> state prep
lookUpPlus = zeros(19,5,numQubits);
C = [4,1000,1000,1000;
4,1000,1000,1;
3,1002,1,1001;
4,1000,1,1000;
3,0,1001,1004;
3,1004,1002,1000;
3,1001,1,1006];
% Find the number of gate storage locations in C
counterStorage = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) == 1
counterStorage = counterStorage + 1;
end
end
end
% Find the number of CNOT locations in C
counterCNOT = 0;
for i = 1:length(C(1,:))
for j = 1:length(C(:,1))
if C(j,i) > 1000
counterCNOT = counterCNOT + 1;
end
end
end
% fills in lookUpTable locations where lookUpO(i,j,k) has j = k = 1.
counter = 1;
for i = 1:counterStorage
lookUpPlus(i,1,1) = 1;
counter = counter + 1;
end
for i = 1 : length(C(:,1))
lookUpPlus(counter,1,1) = C(i,1);
counter = counter + 1;
end
for i = 1 : counterCNOT
lookUpPlus(counter,1,1) = 1000;
counter = counter + 1;
end
e = zeros(1,4);
% fills in LookUpO(i,j,:) for storage gate errors j = 2,3.
counter = 1;
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = 2:3
if jj == 2
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
else
if C(j,i) == 1
e(1,:) = [jj-1,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
% fills in LookUpO(i,j,:) for state prep errors j = 2,3.
for i = 1:length(C(:,1))
if C(i,1) == 3
e(1,:) = [2,i,1,1];
lookUpPlus(counter,3,:) = zVector(C, n, e);
counter = counter + 1;
else
e(1,:) = [1,i,1,1];
lookUpPlus(counter,2,:) = xVector(C, n, e);
counter = counter + 1;
end
end
% fills in LookUpO(i,j,:) for CNOT erros, j = 2,3.
for i = 2:length(C(1,:))
for j = 1:length(C(:,1))
for jj = [2,3,4,5]
switch jj
case 2
if C(j,i) > 1000
e(1,:) = [1,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
case 3
if C(j,i) > 1000
e(1,:) = [2,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
end
case 4
if C(j,i) > 1000
e(1,:) = [4,j,1,i];
lookUpPlus(counter,jj,:) = xVector(C, n, e);
end
otherwise
if C(j,i) > 1000
e(1,:) = [8,j,1,i];
lookUpPlus(counter,jj,:) = zVector(C, n, e);
counter = counter + 1;
end
end
end
end
end
Output = lookUpPlus;
end
function Output = PropagationStatePrepArb(C, n, e)
% C encodes information about the circuit
% n is the number of qubits per encoded codeblock
% eN are the error entries (location and time)
% The Output matrix will contain (2q+m) rows and n columns. The paramters Output(i,j) are:
% i <= 2q and odd: Stores X type errors for output qubit #ceil(i/2) (order based on matrix C)
% i <= 2q and even: Stores Z type errors for output qubit #ceil(i/2) (order based on matrix C)
% i > 2q: Stores measurement error for measurement number #i-2q (type is X or Z depending on measurement type)
% The Errors matrix will be a tensor with 2 parameters Output(i, j)
% i: logical qubit number
% j<=n: X error at physical qubit number j
% j>n : Z error at physical qubit number j
% Error inputs eN are characterized by four parameters, thus a vector (i,j, k, l)
% i: error type: 0 = I, 1 = X, 2 = Z, 3 = Y
% j: logical qubit number (if the entry here is '0' then this will correspond to an identity "error")
% k: physical qubit number within a codeblock
% l: time location
N_meas = length(find(C==5)) + length(find(C==6)); % number of logical measurements in the circuit
N_output = length(C(:,end)) - sum(C(:,end)==-1) - sum(C(:,end)==5) - sum(C(:,end)==6); % number of output active qubits that have not been measured
Meas_dict = [find(C==5); find(C==6)];
Meas_dict = sort(Meas_dict);
Output = zeros(2*N_output + N_meas, n);
Errors = zeros(length(C(:,1)), 2*n);
for t= 1:length(C(1,:))
% If the error occurs at a measurement location then the error is introduced before propagation of faults
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( ( C(e(j,2),t) == 5 ) || ( C(e(j,2),t) == 6 ) )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
end
end
% Propagation of errors (do not need to do it for the first step of circuit
if t>1
for i = 1:length(C(:,t))
if C(i, t) == 10
% In this case must flip the X and Z error information
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = v2;
Errors(i, n+1:end) = v1;
end
if C(i, t) == 11
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = mod(v1+v2, 2);
end
if C(i,t) > 1000
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 1000, t) == 1000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 1000, 1:n);
w2 = Errors(C(i,t) - 1000, (n+1):end);
%mod(v2+w2,2)
Errors(C(i,t) - 1000, 1:n) = mod(v1+w1, 2);
Errors(i, (n+1):end) = mod(v2+w2, 2);
end
end
if C(i,t) == 5
% This corresponds to X measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, (n+1):end);
Errors(i, 1:end) = 0;
end
if C(i,t) == 6
% This corresponds to Z measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, 1:n);
Errors(i, 1:end) = 0;
end
end
end
% Introduce faults for locations that are not measurements
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( C(e(j,2),t) ~= 5 ) && ( C(e(j,2),t) ~= 6 )
% This IF statement checks to see if the gate at this location is NOT a CNOT or Prep
if ( C(e(j,2),t) < 1000 ) %&& ( C(e(j,2),t) ~= 3 ) && ( C(e(j,2),t) ~= 4 )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
% Introduce errors in the case of CNOT gate for control and target qubits
% Errors for control qubit are entry mod(e(j,1),4) according to standard indexing above
if ( C(e(j,2),t) > 1000 )
if C(C(e(j,2),t) - 1000, t) == 1000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 1000, e(j,3)) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 1000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)+n) + 1, 2);
end
end
end
end
end
end
end
%Errors
counter = 1; % This will be used to iterate over the different qubits
for j = 1:length(C(:,end))
if (C(j,end) ~= -1) && (C(j,end) ~= 5) && (C(j,end) ~= 6)
Output(counter,:) = Errors(j,1:n);
Output(counter+1,:) = Errors(j,(n+1):end);
counter = counter + 2;
end
end
end
function Output = xVector(C, n, e)
outputMatrix = PropagationStatePrepArb(C, n, e);
jx = 1;
for i = 1:length(outputMatrix)
if mod(i,2) == 1
xvector(jx) = outputMatrix(i,1);
jx = jx + 1;
end
end
Output = xvector;
end
function Output = zVector(C, n, e)
outputMatrix = PropagationStatePrepArb(C, n, e);
jz = 1;
for i = 1:length(outputMatrix)
if mod(i,2) == 0
zvector(jz) = outputMatrix(i,1);
jz = jz + 1;
end
end
Output = zvector;
end
function Output = PropagationArb(C, n, e, XPrepTable, ZPrepTable)
% C encodes information about the circuit
% n is the number of qubits per encoded codeblock
% eN are the error entries (location and time)
% The Output matrix will contain (2q+m) rows and n columns. The paramters Output(i,j) are:
% i <= 2q and odd: Stores X type errors for output qubit #ceil(i/2) (order based on matrix C)
% i <= 2q and even: Stores Z type errors for output qubit #ceil(i/2) (order based on matrix C)
% i > 2q: Stores measurement error for measurement number #i-2q (type is X or Z depending on measurement type)
% The Errors matrix will be a tensor with 2 parameters Output(i, j)
% i: logical qubit number
% j<=n: X error at physical qubit number j
% j>n : Z error at physical qubit number j
% Error inputs eN are characterized by four parameters, thus a vector (i,j, k, l)
% i: error type: 0 = I, 1 = X, 2 = Z, 3 = Y
% j: logical qubit number (if the entry here is '0' then this will correspond to an identity "error")
% k: physical qubit number within a codeblock
% l: time location
N_meas = length(find(C==5)) + length(find(C==6)); % number of logical measurements in the circuit
N_output = length(C(:,end)) - sum(C(:,end)==-1) - sum(C(:,end)==5) - sum(C(:,end)==6); % number of output active qubits that have not been measured
Meas_dict = [find(C==5); find(C==6)];
Meas_dict = sort(Meas_dict);
Output = zeros(2*N_output + N_meas, n);
Errors = zeros(length(C(:,1)), 2*n);
for t= 1:length(C(1,:))
% If the error occurs at a measurement location then the error is introduced before propagation of faults
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( ( C(e(j,2),t) == 5 ) || ( C(e(j,2),t) == 6 ) )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
end
end
% Propagation of errors (do not need to do it for the first step of
% circuit)
if t>1
for i = 1:length(C(:,t))
if C(i, t) == 10
% In this case must flip the X and Z error information
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = v2;
Errors(i, n+1:end) = v1;
end
if C(i, t) == 11
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = mod(v1+v2, 2);
end
if C(i,t) > 1000
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 1000, t) == 1000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 1000, 1:n);
w2 = Errors(C(i,t) - 1000, (n+1):end);
%mod(v2+w2,2)
Errors(C(i,t) - 1000, 1:n) = mod(v1+w1, 2);
Errors(i, (n+1):end) = mod(v2+w2, 2);
end
end
if C(i,t) == 5
% This corresponds to X measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, (n+1):end);
Errors(i, 1:end) = 0;
end
if C(i,t) == 6
% This corresponds to Z measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, 1:n);
Errors(i, 1:end) = 0;
end
end
end
% Introduce faults for locations that are not measurements
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( C(e(j,2),t) ~= 5 ) && ( C(e(j,2),t) ~= 6 )
% This IF statement checks to see if the gate at this location is NOT a CNOT or Prep
if ( C(e(j,2),t) < 1000 ) && ( C(e(j,2),t) ~= 3 ) && ( C(e(j,2),t) ~= 4 )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
% Introduce errors in the case of CNOT gate for control and target qubits
% Errors for control qubit are entry mod(e(j,1),4) according to standard indexing above
if ( C(e(j,2),t) > 1000 )
if C(C(e(j,2),t) - 1000, t) == 1000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 1000, e(j,3)) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 1000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)+n) + 1, 2);
end
end
end
% Introduce errors in the case of |0> prep
if ( C(e(j,2),t) == 4 )
eVec = zeros(1,n);
if mod(e(j,1),2) == 1
% Need to translate the entries in the Prep tables to right format
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 2, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(e(j,1),4) > 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 3, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end)+eVec, 2);
end
if mod(floor(e(j,1)/4),2) == 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 4, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(floor(e(j,1)/4),4) > 1
for a = 1:n
eVec(a) = ZPrepTable(e(j,3), 5, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end) + eVec, 2);
end
end
% Introduce errors in the case of |+> prep
if ( C(e(j,2),t) == 3 )
eVec = zeros(1,n);
if mod(e(j,1),2) == 1
% Need to translate the entries in the Prep tables to right format
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 2, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(e(j,1),4) > 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 3, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end)+eVec, 2);
end
if mod(floor(e(j,1)/4),2) == 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 4, a);
end
Errors(e(j,2), 1:n ) = mod(Errors(e(j,2), 1:n) + eVec, 2);
end
if mod(floor(e(j,1)/4),4) > 1
for a = 1:n
eVec(a) = XPrepTable(e(j,3), 5, a);
end
Errors(e(j,2), (n+1):end ) = mod(Errors(e(j,2), (n+1):end) + eVec, 2);
end
end
end
end
end
end
%Errors
counter = 1; % This will be used to iterate over the different qubits
for j = 1:length(C(:,end))
if (C(j,end) ~= -1) && (C(j,end) ~= 5) && (C(j,end) ~= 6)
Output(counter,:) = Errors(j,1:n);
Output(counter+1,:) = Errors(j,(n+1):end);
counter = counter + 2;
end
end
end
function Output = equivalenceTable(errIn) % used for measurments in the Z basis
g = [0,0,0,1,1,1,1
0,1,1,0,0,1,1
1,0,1,0,1,0,1];
MatRecovery = [0,0,0,0,0,0,0
1,0,0,0,0,0,0
0,1,0,0,0,0,0
0,0,1,0,0,0,0
0,0,0,1,0,0,0
0,0,0,0,1,0,0
0,0,0,0,0,1,0
0,0,0,0,0,0,1];
syn = zeros(1,3);
for i = 1:length(g(:,1))
syn(1,i) = mod(sum(conj(errIn).* g(i,:)),2);
end
% Find the correction corresponding to the syndrome
correctionRow = 1;
for i = 1:length(syn)
correctionRow = correctionRow + 2^(3-i)*syn(i);
end
Output = MatRecovery(correctionRow,:);
end
function Output = Syndrome(errIn)
g1 = [0,0,0,1,1,1,1];
g2 = [0,1,1,0,0,1,1];
g3 = [1,0,1,0,1,0,1];
g = [g1;g2;g3];
syn = zeros(1,3);
for i = 1:3
syn(1,i) = mod( sum(errIn.*g(i,:)), 2);
end
Output = syn;
end
function Output = errorGeneratorPacceptOprepUpper(errRate)
% Generates errors in the ancilla preparation part of the EC's
e = zeros(1,4);
rows = 1;
% Locations within the state prep |0> circuit
for i = 1:4
for l = 1:4
xi = rand;
if xi < errRate
k = randi([1,3]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
for l = 5:11
if (l == 5) || (l == 6) || (l == 8)
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,1];
rows = rows + 1;
end
else
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,1];
rows = rows + 1;
end
end
end
for l = 12:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
end
for i = [1,3]
for l = 1:7
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,2];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:7
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,3];
rows = rows + 1;
end
end
end
for l = 1:7
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,3,l,4];
rows = rows + 1;
end
end
for l = 1:7
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,3,l,5];
rows = rows + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3] = PacceptErrorGeneratorOPrepUpper(errRate,numIterations,n,lookUpPlus,lookUpO)
C = [4,1002,0,1000,2;
4,1000,6,-1,-1;
4,1004,0,1001,5;
4,1000,6,-1,-1];
eAccepted = zeros(1,4);
eIndex = zeros(1,1);
countereIndex = 1;
counterRows = 0;
numAccepted = 0;
while length(eAccepted(:,1)) < numIterations
e = errorGeneratorPacceptOprepUpper(errRate);
if isequal(e,zeros(1,4))
counter = 0;
else
counter = length(e(:,1));
end
propagatedMatrix = PropagationArb(C,n,e,lookUpPlus,lookUpO);
if (sum(equivalenceTable(propagatedMatrix(3,:)))==0) && (sum(equivalenceTable(propagatedMatrix(4,:)))==0) && (sum(equivalenceTable(propagatedMatrix(5,:)))==0) && (mod(sum(propagatedMatrix(3,:)),2)==0) && (mod(sum(propagatedMatrix(4,:)),2)==0) && (mod(sum(propagatedMatrix(5,:)),2)==0)
if counter ~= 0
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + counter;
eAccepted((counterLast + 1):(counterLast + counter),:) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
else
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + 1;
eAccepted((counterLast + 1),1:4) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
end
end
end
Output1 = eAccepted;
Output2 = eIndex;
Output3 = numAccepted;
end
function Output = errorGeneratorPacceptPlusprepUpper(errRate)
e = zeros(1,4);
rows = 1;
for i = 1:4
for l = 1:4
xi = rand;
if xi < errRate
k = randi([1,3]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
for l = 5:11
if (l == 7) || (l == 9) || (l == 10) || (l == 11)
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,1];
rows = rows + 1;
end
else
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,i,l,1];
rows = rows + 1;
end
end
end
for l = 12:19
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,1];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:7
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,i,l,2];
rows = rows + 1;
end
end
end
for i = [2,4]
for l = 1:7
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [2,i,l,3];
rows = rows + 1;
end
end
end
for l = 1:7
xi = rand;
if xi < errRate
k = randi([1,15]);
e(rows,:) = [k,1,l,4];
rows = rows + 1;
end
end
for l = 1:7
xi = rand;
if xi < 2*errRate/3
e(rows,:) = [1,3,l,5];
rows = rows + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3] = PacceptErrorGeneratorPlusPrepUpper(errRate,numIterations,n,lookUpPlus,lookUpO)
C = [3,1000,0,1003,2;
3,1001,5,-1,-1;
3,1000,0,1000,6;
3,1003,5,-1,-1];
eAccepted = zeros(1,4);
eIndex = zeros(1,1);
countereIndex = 1;
counterRows = 0;
numAccepted = 0;
while length(eAccepted(:,1)) < numIterations
e = errorGeneratorPacceptPlusprepUpper(errRate);
if isequal(e,zeros(1,4))
counter = 0;
else
counter = length(e(:,1));
end
propagatedMatrix = PropagationArb(C, n, e,lookUpPlus, lookUpO);
if (sum(equivalenceTable(propagatedMatrix(3,:)))==0) && (sum(equivalenceTable(propagatedMatrix(4,:)))==0) && (sum(equivalenceTable(propagatedMatrix(5,:)))==0) && (mod(sum(propagatedMatrix(3,:)),2)==0) && (mod(sum(propagatedMatrix(4,:)),2)==0) && (mod(sum(propagatedMatrix(5,:)),2)==0)
if counter ~= 0
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + counter;
eAccepted((counterLast + 1):(counterLast + counter),:) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
else
numAccepted = numAccepted + 1;
counterLast = counterRows;
counterRows = counterRows + 1;
eAccepted((counterLast + 1),1:4) = e;
eIndex(countereIndex,1) = counterLast + 1;
countereIndex = countereIndex + 1;
end
end
end
Output1 = eAccepted;
Output2 = eIndex;
Output3 = numAccepted;
end
function Output = errorGeneratorRemaining(errRate,numQubits)
% This function generates remaining errors outside state-prep circuits in
% a Knill-EC CNOT exRec circuit.
e = zeros(1,4);
counter = 1;
% Errors at all the storage locations
for i = [2,6,11,15]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,5];
counter = counter + 1;
end
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,6,l,7];
counter = counter + 1;
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,15,l,7];
counter = counter + 1;
end
end
for i = [7,11,16,20]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,15];
counter = counter + 1;
end
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,11,l,17];
counter = counter + 1;
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,20,l,17];
counter = counter + 1;
end
end
% Errors at measurement locations
% X-measurement locations
for i = [1,10]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,i,l,8];
counter = counter + 1;
end
end
end
for i = [6,15]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,i,l,18];
counter = counter + 1;
end
end
end
% Z-measurement locations
for i = [2,11]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,i,l,8];
counter = counter + 1;
end
end
end
for i = [7,16]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,i,l,18];
counter = counter + 1;
end
end
end
% Errors at CNOT locations
% Full CNOT's
for i = [2,11]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,i,l,6];
counter = counter + 1;
end
end
end
for i = [7,16]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,i,l,16];
counter = counter + 1;
end
end
end
% CNOT's coupling to data prior to teleportation
for i = [1,10]
for l = 1:numQubits
xi = rand;
if xi < 12*errRate/15
k = randi([2,4,6]);
e(counter,:) = [k,i,l,7];
counter = counter + 1;
end
end
end
for i = [6,15]
for l = 1:numQubits
xi = rand;
if xi < 12*errRate/15
k = randi([2,4,6]);
e(counter,:) = [k,i,l,17];
counter = counter + 1;
end
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,6,l,10];
counter = counter + 1;
end
end
Output = e;
end
function Output = errorGeneratorRemainingCFirst(errRate,numQubits)
% This function generates remaining errors outside state-prep circuits in
% a Knill-EC CNOT exRec circuit.
e = zeros(1,4);
counter = 1;
% Errors at all the storage locations
for i = [2,6,11,15]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,5];
counter = counter + 1;
end
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,6,l,7];
counter = counter + 1;
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,15,l,7];
counter = counter + 1;
end
end
% Errors at measurement locations
% X-measurement locations
for i = [1,10]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,i,l,8];
counter = counter + 1;
end
end
end
% Z-measurement locations
for i = [2,11]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,i,l,8];
counter = counter + 1;
end
end
end
% Errors at CNOT locations
% Full CNOT's
for i = [2,11]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,i,l,6];
counter = counter + 1;
end
end
end
% CNOT's coupling to data prior to teleportation
for i = [1,10]
for l = 1:numQubits
xi = rand;
if xi < 12*errRate/15
vecErr = [2,4,6];
vecRand = randi([1,3]);
k = vecErr(1,vecRand);
e(counter,:) = [k,i,l,7];
counter = counter + 1;
end
end
end
Output = e;
end
function Output = errorGeneratorRemainingCLastWithCNOT(errRate,numQubits)
% This function generates remaining errors outside state-prep circuits in
% a Knill-EC CNOT exRec circuit.
e = zeros(1,4);
counter = 1;
% Errors at all the storage locations
for i = [2,6,11,15]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,l,7];
counter = counter + 1;
end
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,6,l,9];
counter = counter + 1;
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,15,l,9];
counter = counter + 1;
end
end
% Errors at measurement locations
% X-measurement locations
for i = [1,10]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,i,l,10];
counter = counter + 1;
end
end
end
% Z-measurement locations
for i = [2,11]
for l = 1:numQubits
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,i,l,10];
counter = counter + 1;
end
end
end
% Errors at CNOT locations
% Full CNOT's
for i = [2,11]
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,i,l,8];
counter = counter + 1;
end
end
end
for l = 1:numQubits
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,1,l,2];
counter = counter + 1;
end
end
% CNOT's coupling to data prior to teleportation
for i = [1,10]
for l = 1:numQubits
xi = rand;
if xi < 12*errRate/15
vecErr = [2,4,6];
vecRand = randi([1,3]);
k = vecErr(1,vecRand);
e(counter,:) = [k,i,l,9];
counter = counter + 1;
end
end
end
Output = e;
end
function Output = ConvertVecXToErrMatX(ErrIn)
e = zeros(1,4);
counter = 1;
for i = 1:length(ErrIn(1,:))
if ErrIn(1,i) ~= 0
e(counter,:) = [1,1,i,1];
counter = counter + 1;
end
end
Output = e;
end
function Output = ConvertVecZToErrMatZ(ErrIn)
e = zeros(1,4);
counter = 1;
for i = 1:length(ErrIn(1,:))
if ErrIn(1,i) ~= 0
e(counter,:) = [2,1,i,1];
counter = counter + 1;
end
end
Output = e;
end
function [Output1,Output2,Output3] = OutSynAndError(eO,eOIndex,ePlus,ePlusIndex,errRate,numIterations,CFirst,CLastWithCNOT,n,lookUpPlus,lookUpO)
MatSyn = zeros(4*numIterations,6); % Format (XSyn|ZSyn);
MatErr = zeros(2*numIterations,14); %Format (XErr|ZErr);
numRows = 1;
countIterations = 0;
while numRows < (numIterations+1)
% We will first propagate errors through the leading EC's. Recall that
% errors on blocks 1 and 10 should be copied to bloks 6 and 15 due to
% the teleportation occuring in Knill EC.
% Generate errors from |0> state-prep circuit in the first EC block
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
errorO(:,2) = errorO(:,2) + 5; % Insert errors on the appropriate block of the EC circuit
e = errorO;
rows = length(e(:,1));
% Genrate errors from |+> state-prep circuit in the first EC block
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
errorPlus(:,2) = errorPlus(:,2) + 1; % Insert errors on the appropriate block of the EC circuit
rowse1Plus = length(errorPlus(:,1));
e((rows + 1):(rows + rowse1Plus),:) = errorPlus;
rows = rows + rowse1Plus;
% Generate errors from |0> state-prep circuit in the second EC block
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
errorO(:,2) = errorO(:,2) + 14; % Insert errors on the appropriate block of the EC circuit
rowse2O = length(errorO(:,1));
e((rows + 1):(rows + rowse2O),:) = errorO;
rows = rows + rowse2O;
% Generate errors from |+> state-prep in the second EC block
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
errorPlus(:,2) = errorPlus(:,2) + 10; % Insert errors on the appropriate block of the EC circuit
rowse2Plus = length(errorPlus(:,1));
e((rows + 1):(rows + rowse2Plus),:) = errorPlus;
rows = rows + rowse2Plus;
% Next we generate a random error in the circuit (outside of state-prep
% circuits) to add to the matrix e (given the error rate errRate).
eRemain = errorGeneratorRemainingCFirst(errRate,n);
e((rows + 1):(rows + length(eRemain(:,1))),:) = eRemain;
ErrOutFirst = PropagationArb(CFirst,n,e,lookUpPlus,lookUpO); % Propagate errors through the CFirst circuit
% Next we store the syndromes based on the measured syndromes
XSynB1EC1 = Syndrome(ErrOutFirst(18,:));
ZSynB1EC1 = Syndrome(ErrOutFirst(17,:));
XSynB2EC1 = Syndrome(ErrOutFirst(20,:));
ZSynB2EC1 = Syndrome(ErrOutFirst(19,:));
% Add X errors of control input qubit to control teleported qubit
XerrB1EC1 = mod(ErrOutFirst(1,:)+ErrOutFirst(18,:),2);
% Add Z errors of control input qubit to control teleported qubit
ZerrB1EC1 = mod(ErrOutFirst(2,:)+ErrOutFirst(17,:),2);
% Add X errors of target input qubit to target teleported qubit
XerrB2EC1 = mod(ErrOutFirst(3,:)+ErrOutFirst(20,:),2);
% Add Z errors of target input qubit to target teleported qubit
ZerrB2EC1 = mod(ErrOutFirst(4,:)+ErrOutFirst(19,:),2);
% Next we convert the output errors into matrix form for input into the
% final part of the CNOT exRec circuit
e1X = ConvertVecXToErrMatX(XerrB1EC1);
e1Z = ConvertVecZToErrMatZ(ZerrB1EC1);
e2X = ConvertVecXToErrMatX(XerrB2EC1);
e2Z = ConvertVecZToErrMatZ(ZerrB2EC1);
e2X(1,2) = 10;
e2Z(1,2) = 10;
eFinal = [e1X;e1Z;e2X;e2Z];
rows = length(eFinal(:,1));
% Generate errors from |0> state-prep circuit in the third EC block
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
errorO(:,2) = errorO(:,2) + 5;
errorO(:,4) = errorO(:,4) + 2;
rowse3O = length(errorO(:,1));
eFinal((rows + 1):(rows + rowse3O),:) = errorO;
rows = rows + rowse3O;
% Genrate errors from |+> state-prep circuit in the first EC block
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
errorPlus(:,2) = errorPlus(:,2) + 1;
errorPlus(:,4) = errorPlus(:,4) + 2;
rowse3Plus = length(errorPlus(:,1));
eFinal((rows + 1):(rows + rowse3Plus),:) = errorPlus;
rows = rows + rowse3Plus;
% Generate errors from |0> state-prep circuit in the fourth EC block
lORand = randi([1,length(eOIndex(:,1))]);
if eOIndex(lORand,1) ~= 0
indexStart = eOIndex(lORand,1);
if lORand == length(eOIndex(:,1))
indexEnd = length(eO(:,1));
else
indexEnd = eOIndex(lORand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorO = eO(indexStart:indexEnd,:);
errorO(:,2) = errorO(:,2) + 14;
errorO(:,4) = errorO(:,4) + 2;
rowse4O = length(errorO(:,1));
eFinal((rows + 1):(rows + rowse4O),:) = errorO;
rows = rows + rowse4O;
% Generate errors from |+> state-prep in the fourth EC block
lPlusRand = randi([1,length(ePlusIndex(:,1))]);
if ePlusIndex(lPlusRand,1) ~= 0
indexStart = ePlusIndex(lPlusRand,1);
if lPlusRand == length(ePlusIndex(:,1))
indexEnd = length(ePlus(:,1));
else
indexEnd = ePlusIndex(lPlusRand + 1,1) - 1;
end
else
indexStart = 1;
indexEnd = 1;
end
errorPlus = ePlus(indexStart:indexEnd,:);
errorPlus(:,2) = errorPlus(:,2) + 10;
errorPlus(:,4) = errorPlus(:,4) + 2;
rowse4Plus = length(errorPlus(:,1));
eFinal((rows + 1):(rows + rowse4Plus),:) = errorPlus;
rows = rows + rowse4Plus;
% Next we generate a random error in the final output circuit
% (outside of state-prep circuits) to add to the matrix e
% (given the error rate errRate).
errorRemainFinal = errorGeneratorRemainingCLastWithCNOT(errRate,n);
eFinal((rows + 1):(rows + length(errorRemainFinal(:,1))),:) = errorRemainFinal;
ErrOutLast = PropagationArb(CLastWithCNOT,n,eFinal,lookUpPlus,lookUpO); % Propagate errors through the CFirst circuit
% Next we store the syndromes based on the measured syndromes
XSynB1EC2 = Syndrome(ErrOutLast(18,:));
ZSynB1EC2 = Syndrome(ErrOutLast(17,:));
XSynB2EC2 = Syndrome(ErrOutLast(20,:));
ZSynB2EC2 = Syndrome(ErrOutLast(19,:));
% Add X errors of control input qubit to control teleported qubit
ErrOutLast(1,:) = mod(ErrOutLast(1,:)+ ErrOutLast(18,:),2);
% Add Z errors of control input qubit to control teleported qubit
ErrOutLast(2,:) = mod(ErrOutLast(2,:)+ ErrOutLast(17,:),2);
% Add X errors of target input qubit to target teleported qubit
ErrOutLast(3,:) = mod(ErrOutLast(3,:)+ ErrOutLast(20,:),2);
% Add Z errors of target input qubit to target teleported qubit
ErrOutLast(4,:) = mod(ErrOutLast(4,:)+ ErrOutLast(19,:),2);
% Store the errors of the first two blocks
XerrB1EC2 = ErrOutLast(1,:);
ZerrB1EC2 = ErrOutLast(2,:);
XerrB2EC2 = ErrOutLast(3,:);
ZerrB2EC2 = ErrOutLast(4,:);
t1 = sum(XSynB1EC1 + ZSynB1EC1 + XSynB2EC1 + ZSynB2EC1 + XSynB1EC2 + ZSynB1EC2 + XSynB2EC2 + ZSynB2EC2);
t2 = sum(XerrB1EC2 + ZerrB1EC2 + XerrB2EC2 + ZerrB2EC2);
if (t1 ~= 0) || (t2 ~= 0)
MatSynTemp = [XSynB1EC1,ZSynB1EC1;XSynB2EC1,ZSynB2EC1;XSynB1EC2,ZSynB1EC2;XSynB2EC2,ZSynB2EC2];
MatErrorTemp = [XerrB1EC2,ZerrB1EC2;XerrB2EC2,ZerrB2EC2];
MatSyn((4*(numRows-1)+1):(4*numRows),:) = MatSynTemp;
MatErr((2*(numRows-1)+1):(2*numRows),:) = MatErrorTemp;
numRows = numRows + 1;
end
countIterations = countIterations + 1;
end
Output1 = MatSyn;
Output2 = MatErr;
Output3 = countIterations;
end
|
github
|
pooya-git/DeepNeuralDecoder-master
|
SurfaceCodeTrainingSetd3.m
|
.m
|
DeepNeuralDecoder-master/Data/Generator/Surface_1EC_D3/SurfaceCodeTrainingSetd3.m
| 32,816 |
utf_8
|
15195dd006d9959226e29930688b525b
|
% MIT License
%
% Copyright (c) 2018 Chris Chamberland
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.
function SurfaceCodeTrainingSetd3
n=1;
parfor i = 1:16
numIterations = 2*10^6;
v = [7*10^-5,8*10^-5,9*10^-5,9.5*10^-5,10^-4,1.5*10^-4,2*10^-4,2.5*10^-4,3*10^-4,4*10^-4,5*10^-4,6*10^-4,7*10^-4,8*10^-4,9*10^-4,10^-3];
errRate = v(1,i);
str_errRate = num2str(errRate,'%0.3e');
[OutputSynX1,OutputSynZ1,OutputErrX1,OutputErrZ1,OutputCount] = depolarizingSimulator(numIterations,errRate,n);
A = [OutputSynX1,OutputSynZ1,OutputErrX1,OutputErrZ1];
TempStr1 = 'SyndromeAndError';
TempStr2 = '.txt';
str_Final1 = strcat(TempStr1,str_errRate);
str_Final2 = strcat(str_Final1,TempStr2);
fid = fopen(str_Final2, 'w+t');
for ii = 1:size(A,1)
fprintf(fid,'%g\t',A(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
str_Count = strcat('Count',str_errRate);
str_CountFinal = strcat(str_Count,'.mat');
parsaveCount(str_CountFinal,OutputCount);
end
end
function parsaveErrorVec(fname,errorVecMat)
save(fname,'errorVecMat');
end
function parsaveCount(fname,OutputCount)
save(fname,'OutputCount');
end
function Output = PropagationStatePrepArb(C, n, e)
% C encodes information about the circuit
% n is the number of qubits per encoded codeblock
% eN are the error entries (location and time)
% The Output matrix will contain (2q+m) rows and n columns. The paramters Output(i,j) are:
% i <= 2q and odd: Stores X type errors for output qubit #ceil(i/2) (order based on matrix C)
% i <= 2q and even: Stores Z type errors for output qubit #ceil(i/2) (order based on matrix C)
% i > 2q: Stores measurement error for measurement number #i-2q (type is X or Z depending on measurement type)
% The Errors matrix will be a tensor with 2 parameters Output(i, j)
% i: logical qubit number
% j<=n: X error at physical qubit number j
% j>n : Z error at physical qubit number j
% Error inputs eN are characterized by four parameters, thus a vector (i,j, k, l)
% i: error type: 0 = I, 1 = X, 2 = Z, 3 = Y
% j: logical qubit number (if the entry here is '0' then this will correspond to an identity "error")
% k: physical qubit number within a codeblock
% l: time location
N_meas = length(find(C==5)) + length(find(C==6)); % number of logical measurements in the circuit
N_output = length(C(:,end)) - sum(C(:,end)==-1) - sum(C(:,end)==5) - sum(C(:,end)==6); % number of output active qubits that have not been measured
Meas_dict = [find(C==5); find(C==6)];
Meas_dict = sort(Meas_dict);
Output = zeros(2*N_output + N_meas, n);
Errors = zeros(length(C(:,1)), 2*n);
for t= 1:length(C(1,:))
% If the error occurs at a measurement location then the error is introduced before propagation of faults
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( ( C(e(j,2),t) == 5 ) || ( C(e(j,2),t) == 6 ) )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
end
end
% Propagation of errors (do not need to do it for the first step of circuit
if t>1
for i = 1:length(C(:,t))
if C(i, t) == 10
% In this case must flip the X and Z error information
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = v2;
Errors(i, n+1:end) = v1;
end
if C(i, t) == 11
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = mod(v1+v2, 2);
end
if (C(i,t) > 1000) && (C(i,t) < 2000)
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 1000, t) == 1000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 1000, 1:n);
w2 = Errors(C(i,t) - 1000, (n+1):end);
%mod(v2+w2,2)
Errors(C(i,t) - 1000, 1:n) = mod(v1+w1, 2);
Errors(i, (n+1):end) = mod(v2+w2, 2);
end
end
if C(i,t) > 2000
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 2000, t) == 2000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 2000, 1:n);
w2 = Errors(C(i,t) - 2000, (n+1):end);
Errors(C(i,t) - 2000, 1:n) = v1;
Errors(C(i,t) - 2000, (n+1):end) = v2;
Errors(i, 1:end) = w1;
Errors(i, (n+1):end) = w2;
end
end
if C(i,t) == 5
% This corresponds to X measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, (n+1):end);
Errors(i, 1:end) = 0;
end
if C(i,t) == 6
% This corresponds to Z measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, 1:n);
Errors(i, 1:end) = 0;
end
end
end
% Introduce faults for locations that are not measurements
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( C(e(j,2),t) ~= 5 ) && ( C(e(j,2),t) ~= 6 )
% This IF statement checks to see if the gate at this location is NOT a CNOT or Prep
if ( C(e(j,2),t) < 1000 ) %&& ( C(e(j,2),t) ~= 3 ) && ( C(e(j,2),t) ~= 4 )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
% Introduce errors in the case of CNOT gate for control and target qubits
% Errors for control qubit are entry mod(e(j,1),4) according to standard indexing above
if ( (C(e(j,2),t) > 1000) && (C(e(j,2),t) < 2000))
if C(C(e(j,2),t) - 1000, t) == 1000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 1000, e(j,3)) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 1000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)+n) + 1, 2);
end
end
end
if C(e(j,2),t) > 2000
if C(C(e(j,2),t) - 2000, t) == 2000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 2000, e(j,3)) = mod(Errors(C(e(j,2),t) - 2000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 2000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 2000, e(j,3)+n) + 1, 2);
end
end
end
end
end
end
end
%Errors
counter = 1; % This will be used to iterate over the different qubits
for j = 1:length(C(:,end))
if (C(j,end) ~= -1) && (C(j,end) ~= 5) && (C(j,end) ~= 6)
Output(counter,:) = Errors(j,1:n);
Output(counter+1,:) = Errors(j,(n+1):end);
counter = counter + 2;
end
end
end
function Output = SurfaceCodeCircuitGenerator(d)
% Creates d = 3 surface code circuit Matteo
% Circuit descriptors:
% -1: qubit non-active
% 0: Noiseless memory
% 1: Gate memory
% 2: Measurement memory
% 3: Preparation in X basis (|+> state)
% 4: Preparation in Z basis (|0> state)
% 5: Measurement in X basis
% 6: Measurement in Z basis
% 7: X gate
% 8: Z gate
% 10: H gate
% 11: S gate
% 20: T gate
%1---: Control qubit for CNOT with target ---
%1000: Target qubit for CNOT
%2000: Qubit for SWAP gate
numRows = 2*(d^2) -1 ;
numTimeSteps = 6;
qubitNum = (d^2-1)/2;
Cd3 = zeros(numRows,numTimeSteps);
% Set the storage locations at all qubit locations (first two and last two
% time steps)
for i = 1:(d^2)
for j = 1:numTimeSteps
Cd3(i + qubitNum,j) = 1;
Cd3(i + qubitNum,j) = 1;
Cd3(i + qubitNum,j) = 1;
Cd3(i + qubitNum,j) = 1;
end
end
% Initialise X stabilizer state prep and measurements
for i = 1:((d^2)-1)/2
Cd3(i,1) = 3;
Cd3(i,6) = 5;
end
% Initialise Z stabilizer state prep and measurements
for i = (((3*(d^2)-1)/2)+1):(2*(d^2)-1)
Cd3(i,1) = 4;
Cd3(i,6) = 6;
end
% Creat matrix of data qubit number
dataMat = zeros(d,d);
counter = 1;
for i = 1:d
for j = 1:d
dataMat(i,j) = counter + (((d^2)-1)/2);
counter = counter + 1;
end
end
% Creat matrix for X and Z stabilizer ancilla qubit numbers
ancillaStabXMat = zeros(((d+1)/2),d-1);
ancillaStabZMat = zeros(d-1,((d+1)/2));
counter = 1;
for i = 1:length(ancillaStabXMat(1,:))
for j = 1:length(ancillaStabXMat(:,1))
ancillaStabXMat(j,i) = counter;
counter = counter + 1;
end
end
counter = 1;
for i = 1:length(ancillaStabZMat(:,1))
for j = 1:length(ancillaStabZMat(1,:))
ancillaStabZMat(i,j) = counter;
counter = counter + 1;
end
end
% Next we input gates from measurement qubits to data qubits
% First cycle (measure upper right qubits)
% Input target and control of the CNOT gates for X stabilizers
timeStep = 2;
rwoXstab = 1;
for i = 1:length(dataMat(:,1))
if mod(i,2) == 0
colXstab = 2;
else
colXstab = 1;
end
for j = 1:length(dataMat(1,:))
if mod(i,2) == 1
if mod(j,2) == 0
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
end
else
if mod(j,2) == 1 && j ~= 1
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
end
end
end
if mod(i,2) == 1
rwoXstab = rwoXstab + 1;
end
end
% Input target and control of the CNOT gates for Z stabilizers
rwoZstab = 1;
for i = 1:(length(dataMat(:,1))-1)
colZstab = 1;
for j = 1:length(dataMat(1,:))
if mod(i,2) == 1
if mod(j,2) == 1
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
end
else
if mod(j,2) == 0
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
end
end
end
rwoZstab = rwoZstab + 1;
end
% Second cycle (measure upper left qubits for X stabilizers and lower right qubits for Z stabilizers)
timeStep = timeStep + 1;
% Input target and control of the CNOT gates for X stabilizers
rwoXstab = 1;
for i = 1:length(dataMat(:,1))
if mod(i,2) == 0
colXstab = 2;
else
colXstab = 1;
end
for j = 1:length(dataMat(1,:))
if (mod(i,2) == 1) && (mod(j,2) == 1) && (j < length(dataMat(1,:)))
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
elseif (mod(i,2) == 0) && (mod(j,2) == 0)
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
end
end
if mod(i,2) == 1
rwoXstab = rwoXstab + 1;
end
end
% Input target and control of the CNOT gates for Z stabilizers
rwoZstab = 1;
for i = 2:length(dataMat(:,1))
colZstab = 1;
for j = 1:length(dataMat(1,:))
if (mod(i,2) == 0) && (mod(j,2) == 1)
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
elseif (mod(i,2) == 1) && (mod(j,2) == 0)
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
end
end
rwoZstab = rwoZstab + 1;
end
% Third cycle (lower right qubits for X stabilizers and upper left qubits for Z stabilizers)
timeStep = timeStep + 1;
% Input target and control of the CNOT gates for X stabilizers
rwoXstab = 1;
for i = 1:length(dataMat(:,1))
if mod(i,2) == 0
colXstab = 1;
else
colXstab = 2;
end
for j = 2:length(dataMat(1,:))
if mod(i,2) == 1 && mod(j,2) == 1
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
elseif mod(i,2) == 0 && mod(j,2) == 0
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
end
end
if mod(i,2) == 0
rwoXstab = rwoXstab + 1;
end
end
% Input target and control of the CNOT gates for Z stabilizers
rwoZstab = 1;
for i = 1:(length(dataMat(:,1))-1)
if mod(i,2) == 1
colZstab = 2;
else
colZstab = 1;
end
for j = 1:length(dataMat(1,:))
if mod(i,2) == 1 && mod(j,2) == 0
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
elseif mod(i,2) == 0 && mod(j,2) == 1
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
end
end
rwoZstab = rwoZstab + 1;
end
% Fourth cycle (lower right qubits for X stabilizers and upper left qubits for Z stabilizers)
timeStep = timeStep + 1;
% Input target and control of the CNOT gates for X stabilizers
rwoXstab = 1;
for i = 1:length(dataMat(:,1))
if mod(i,2) == 0
colXstab = 1;
else
colXstab = 2;
end
for j = 1:(length(dataMat(1,:))-1)
if mod(i,2) == 1 && mod(j,2) == 0
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
elseif mod(i,2) == 0 && mod(j,2) == 1
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
end
end
if mod(i,2) == 0
rwoXstab = rwoXstab + 1;
end
end
% Input target and control of the CNOT gates for Z stabilizers
rwoZstab = 1;
for i = 2:length(dataMat(:,1))
if mod(i,2) == 0
colZstab = 2;
else
colZstab = 1;
end
for j = 1:length(dataMat(1,:))
if mod(i,2) == 0 && mod(j,2) == 0
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
elseif mod(i,2) == 1 && mod(j,2) == 1
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
end
end
rwoZstab = rwoZstab + 1;
end
Output = Cd3;
end
function Output = FullLookupTableXCorrection(errX)
gZ = [1,0,0,1,0,0,0,0,0;
0,1,1,0,1,1,0,0,0;
0,0,0,1,1,0,1,1,0;
0,0,0,0,0,1,0,0,1];
XcorrectionMat = [0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 0 0
0 0 0 0 1 1 0 0 0
0 1 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 1
1 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 1
0 0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0 1
1 1 0 0 0 0 0 0 0
1 0 0 0 0 1 0 0 0
1 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0];
syn = zeros(1,4);
for i = 1:length(gZ(:,1))
syn(1,i) = mod(errX*transpose(gZ(i,:)),2);
end
correctionRow = 1;
for ii = 1:length(syn)
correctionRow = correctionRow + 2^(4-ii)*syn(ii);
end
Output = XcorrectionMat(correctionRow,:);
end
function Output = FullLookupTableZCorrection(errZ)
gX = [1,1,0,1,1,0,0,0,0;
0,1,1,0,0,0,0,0,0;
0,0,0,0,1,1,0,1,1;
0,0,0,0,0,0,1,1,0];
ZcorrectionMat = [0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0
0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 1 0 0 0 0
0 0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0
0 0 0 1 0 0 1 0 0
0 0 0 0 1 0 0 0 0
1 0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0 0
0 1 0 0 0 0 1 0 0
0 1 0 0 0 1 0 0 0
0 1 0 0 0 0 0 1 0];
syn = zeros(1,4);
for i = 1:length(gX(:,1))
syn(1,i) = mod(errZ*transpose(gX(i,:)),2);
end
correctionRow = 1;
for ii = 1:length(syn)
correctionRow = correctionRow + 2^(4-ii)*syn(ii);
end
Output = ZcorrectionMat(correctionRow,:);
end
function Output = ErrorGenerator(Cmat,errRate)
%This function outputs an error vector based on the input circuit
%represented by Cmat. We have the following noise model.
% 1) |0> state preparation: Perfect |0> state followed by X error with probability p
% 2) Z-measurement: X pauli with probability p followed by perfect Z-basis
% measurement.
% 3) CNOT: Perfect CNOT followed by
%{IX,IY,IZ,XI,YI,ZI,XX,XY,XZ,ZX,ZY,ZZ,YX,YY,YZ} with probability p/15 each.
% 4) Hadamard: Perfect Hadamard followed by {X,Y,Z} with probability p/12
%each.
% 5) SWAP: Perfect SWAP followed by
% {IX,IY,IZ,XI,YI,ZI,XX,XY,XZ,ZX,ZY,ZZ,YX,YY,YZ} with probability p/60
% each.
% Storage: Pauli {X,Y,Z} with probability p/30 each.
% Here errRate = p and Cmat is the circuit representing the surface code
% lattice.
e = zeros(1,4);
counter = 1;
for i = 1:length(Cmat(:,1))
for j = 1:length(Cmat(1,:))
% Adds storage errors with probability p
if (Cmat(i,j) == 1)
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,1,j];
counter = counter + 1;
end
end
% Adds state-preparation errors with probability 2p/3
if Cmat(i,j) == 4
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,i,1,j];
counter = counter + 1;
end
end
if Cmat(i,j) == 3
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,i,1,j];
counter = counter + 1;
end
end
% Adds measurement errors with probability 2p/3
if Cmat(i,j) == 6
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,i,1,j];
counter = counter + 1;
end
end
if Cmat(i,j) == 5
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,i,1,j];
counter = counter + 1;
end
end
% Adds CNOT errors with probability p
if (Cmat(i,j) > 1000)
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,i,1,j];
counter = counter + 1;
end
end
end
end
Output = e;
end
function Output = ConvertErrorXStringToErrorVec(ErrStrX)
e = zeros(1,4);
counter = 1;
for i = 1:length(ErrStrX(1,:))
if ErrStrX(1,i) == 1
e(counter,:) = [1,i+4,1,1];
counter = counter + 1;
end
end
Output = e;
end
function Output = ConvertErrorZStringToErrorVec(ErrStrZ)
e = zeros(1,4);
counter = 1;
for i = 1:length(ErrStrZ(1,:))
if ErrStrZ(1,i) == 1
e(counter,:) = [2,i+4,1,1];
counter = counter + 1;
end
end
Output = e;
end
function Output = FaultTolerantCorrectionX(Syn1,Syn2,Syn3)
% Corrects X errors based on syndromes from 3 rounds of syndrome
% measurement
XcorrectionMat = [0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 0 0
0 0 0 0 1 1 0 0 0
0 1 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 1
1 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 1
0 0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0 1
1 1 0 0 0 0 0 0 0
1 0 0 0 0 1 0 0 0
1 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0];
s1 = max(Syn1);
s2 = max(Syn2);
s3 = max(Syn3);
if (s1 == 0 && (s2 == 0 || s3 == 0)) || (s2 == 0 && s3 == 0) % If at least two syndromes are trivial, apply no correction
corrX = zeros(1,9);
elseif isequal(Syn1,Syn2) || isequal(Syn1,Syn3) % If at least two syndromes are equal
correctionRow = 1;
for ii = 1:length(Syn1)
correctionRow = correctionRow + 2^(4-ii)*Syn1(ii);
end
corrX = XcorrectionMat(correctionRow,:);
elseif isequal(Syn2,Syn3)
correctionRow = 1;
for ii = 1:length(Syn2)
correctionRow = correctionRow + 2^(4-ii)*Syn2(ii);
end
corrX = XcorrectionMat(correctionRow,:);
else % If all three syndromes are non-trivial and different, use the last syndrome to correct
correctionRow = 1;
for ii = 1:length(Syn3)
correctionRow = correctionRow + 2^(4-ii)*Syn3(ii);
end
corrX = XcorrectionMat(correctionRow,:);
end
Output = corrX;
end
function Output = FaultTolerantCorrectionZ(Syn1,Syn2,Syn3)
% Corrects X errors based on syndromes from 3 rounds of syndrome
% measurement
ZcorrectionMat = [0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 0
0 1 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0
0 1 0 0 0 0 0 0 0
0 1 0 0 0 1 0 0 0
1 0 0 0 0 0 1 0 0
1 0 0 0 0 0 0 1 0
0 1 0 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0];
s1 = max(Syn1);
s2 = max(Syn2);
s3 = max(Syn3);
if (s1 == 0 && (s2 == 0 || s3 == 0)) || (s2 == 0 && s3 == 0) % If at least two syndromes are trivial, apply no correction
corrZ = zeros(1,9);
elseif isequal(Syn1,Syn2) || isequal(Syn1,Syn3) % If at least two syndromes are equal
correctionRow = 1;
for ii = 1:length(Syn1)
correctionRow = correctionRow + 2^(4-ii)*Syn1(ii);
end
corrZ = ZcorrectionMat(correctionRow,:);
elseif isequal(Syn2,Syn3)
correctionRow = 1;
for ii = 1:length(Syn2)
correctionRow = correctionRow + 2^(4-ii)*Syn2(ii);
end
corrZ = ZcorrectionMat(correctionRow,:);
else % If all three syndromes are non-trivial and different, use the last syndrome to correct
correctionRow = 1;
for ii = 1:length(Syn3)
correctionRow = correctionRow + 2^(4-ii)*Syn3(ii);
end
corrZ = ZcorrectionMat(correctionRow,:);
end
Output = corrZ;
end
function [OutputSynX1,OutputSynZ1,OutputErrX1,OutputErrZ1,OutputCount] = depolarizingSimulator(numIterations,errRate,n)
% This function generates X and Z syndrome measurement results for three
% rounds of error correction of the d=3 rotated surface code as well as the
% X and Z errors for each round
% Circuit descriptors:
% -1: qubit non-active
% 0: Noiseless memory
% 1: Gate memory
% 2: Measurement memory
% 3: Preparation in X basis (|+> state)
% 4: Preparation in Z basis (|0> state)
% 5: Measurement in X basis
% 6: Measurement in Z basis
% 7: X gate
% 8: Z gate
% 10: H gate
% 11: S gate
% 20: T gate
%1---: Control qubit for CNOT with target ---
%1000: Target qubit for CNOT
% Full circuit for measuring the X and Z stabilizers of the d=3 rotated
% surface code
Circuit = [3 1006 1005 1009 1008 5
3 1012 1011 0 0 5
3 0 0 1007 1006 5
3 1010 1009 1013 1012 5
1 1014 1000 1 1 1
1 1000 1 1015 1000 1
1 1015 1 1000 1 1
1 1 1014 1016 1000 1
1 1016 1000 1000 1015 1
1 1000 1015 1017 1 1
1 1 1000 1 1016 1
1 1000 1016 1 1000 1
1 1 1 1000 1017 1
4 1000 1000 0 0 6
4 1000 1000 1000 1000 6
4 1000 1000 1000 1000 6
4 0 0 1000 1000 6];
ErrXOutputBlock1 = zeros(3*numIterations,9);
ErrZOutputBlock1 = zeros(3*numIterations,9);
SynXOutputBlock1 = zeros(3*numIterations,4);
SynZOutputBlock1 = zeros(3*numIterations,4);
numSize = 1;
countIterations = 0;
while numSize < numIterations
e = zeros(1,4);
XSyn = zeros(3,4);
ZSyn = zeros(3,4);
eXString = zeros(3,9);
eZString = zeros(3,9);
for i = 1:3
eCircuit = ErrorGenerator(Circuit,errRate);
eTemp = [e;eCircuit];
Cout = transpose(PropagationStatePrepArb(Circuit,n,eTemp));
Xerror = Cout(1,1:2:18);
Zerror = Cout(1,2:2:18);
ZSyn(i,:) = Cout(1,19:22);
XSyn(i,:) = Cout(1,23:26);
eXString(i,:) = Xerror;
eZString(i,:) = Zerror;
eX = ConvertErrorXStringToErrorVec(Xerror);
eZ = ConvertErrorZStringToErrorVec(Zerror);
if i ~= 3
e = [eX;eZ];
end
end
if sum(any(XSyn)) ~= 0 || sum(any(ZSyn)) ~= 0 || sum(any(eXString)) ~= 0 || sum(any(eZString)) ~= 0
ErrXOutputBlock1(3*(numSize-1)+1:3*numSize,:) = eXString;
ErrZOutputBlock1(3*(numSize-1)+1:3*numSize,:) = eZString;
SynXOutputBlock1(3*(numSize-1)+1:3*numSize,:) = XSyn;
SynZOutputBlock1(3*(numSize-1)+1:3*numSize,:) = ZSyn;
numSize = numSize + 1;
end
countIterations = countIterations + 1;
end
OutputSynX1 = SynXOutputBlock1;
OutputSynZ1 = SynZOutputBlock1;
OutputErrX1 = ErrXOutputBlock1;
OutputErrZ1 = ErrZOutputBlock1;
OutputCount = countIterations;
end
|
github
|
pooya-git/DeepNeuralDecoder-master
|
SurfaceCodeTrainingSetd5.m
|
.m
|
DeepNeuralDecoder-master/Data/Generator/Surface_1EC_D5/SurfaceCodeTrainingSetd5.m
| 29,093 |
utf_8
|
c7189ded75707169c19b5618d5c38518
|
% MIT License
%
% Copyright (c) 2018 Chris Chamberland
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.
function SurfaceCodeTrainingSetd5
n=1;
t=2;
parfor i = 1:6
numIterations = 2*10^2;
v = [3*10^-4,4*10^-4,5*10^-4,6*10^-4,7*10^-4,8*10^-4];
errRate = v(1,i);
str_errRate = num2str(errRate,'%0.3e');
[OutputSynX1,OutputSynZ1,OutputErrX1,OutputErrZ1,OutputCount] = depolarizingSimulator(numIterations,errRate,n,t);
A1 = [OutputSynX1,OutputSynZ1];
A2 = [OutputErrX1,OutputErrZ1];
%clear OutputSynX1 OutputSynZ1 OutputErrX1 OutputErrZ1
TempStr1 = 'SyndromeOnly';
TempStr2 = '.txt';
TempStr3 = 'ErrorOnly';
str_Final1 = strcat(TempStr1,str_errRate);
str_Final2 = strcat(str_Final1,TempStr2);
str_Final3 = strcat(TempStr3,str_errRate);
str_Final4 = strcat(str_Final3,TempStr2);
fid = fopen(str_Final2, 'w+t');
for ii = 1:size(A1,1)
fprintf(fid,'%g\t',A1(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
fid = fopen(str_Final4, 'w+t');
for ii = 1:size(A2,1)
fprintf(fid,'%g\t',A2(ii,:));
fprintf(fid,'\n');
end
fclose(fid);
%clear A1 A2
str_Count = strcat('Count',str_errRate);
str_CountFinal = strcat(str_Count,'.mat');
parsaveCount(str_CountFinal,OutputCount);
end
end
function parsaveErrorVec(fname,errorVecMat)
save(fname,'errorVecMat');
end
function parsaveCount(fname,OutputCount)
save(fname,'OutputCount');
end
function Output = PropagationStatePrepArb(C, n, e)
% C encodes information about the circuit
% n is the number of qubits per encoded codeblock
% eN are the error entries (location and time)
% The Output matrix will contain (2q+m) rows and n columns. The paramters Output(i,j) are:
% i <= 2q and odd: Stores X type errors for output qubit #ceil(i/2) (order based on matrix C)
% i <= 2q and even: Stores Z type errors for output qubit #ceil(i/2) (order based on matrix C)
% i > 2q: Stores measurement error for measurement number #i-2q (type is X or Z depending on measurement type)
% The Errors matrix will be a tensor with 2 parameters Output(i, j)
% i: logical qubit number
% j<=n: X error at physical qubit number j
% j>n : Z error at physical qubit number j
% Error inputs eN are characterized by four parameters, thus a vector (i,j, k, l)
% i: error type: 0 = I, 1 = X, 2 = Z, 3 = Y
% j: logical qubit number (if the entry here is '0' then this will correspond to an identity "error")
% k: physical qubit number within a codeblock
% l: time location
N_meas = length(find(C==5)) + length(find(C==6)); % number of logical measurements in the circuit
N_output = length(C(:,end)) - sum(C(:,end)==-1) - sum(C(:,end)==5) - sum(C(:,end)==6); % number of output active qubits that have not been measured
Meas_dict = [find(C==5); find(C==6)];
Meas_dict = sort(Meas_dict);
Output = zeros(2*N_output + N_meas, n);
Errors = zeros(length(C(:,1)), 2*n);
for t= 1:length(C(1,:))
% If the error occurs at a measurement location then the error is introduced before propagation of faults
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( ( C(e(j,2),t) == 5 ) || ( C(e(j,2),t) == 6 ) )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
end
end
% Propagation of errors (do not need to do it for the first step of circuit
if t>1
for i = 1:length(C(:,t))
if C(i, t) == 10
% In this case must flip the X and Z error information
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = v2;
Errors(i, n+1:end) = v1;
end
if C(i, t) == 11
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
Errors(i, 1:n) = mod(v1+v2, 2);
end
if (C(i,t) > 1000) && (C(i,t) < 2000)
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 1000, t) == 1000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 1000, 1:n);
w2 = Errors(C(i,t) - 1000, (n+1):end);
%mod(v2+w2,2)
Errors(C(i,t) - 1000, 1:n) = mod(v1+w1, 2);
Errors(i, (n+1):end) = mod(v2+w2, 2);
end
end
if C(i,t) > 2000
% check to see if target qubit according to control qubit is actually a target qubit
if C(C(i,t) - 2000, t) == 2000
v1 = Errors(i, 1:n);
v2 = Errors(i, (n+1):end);
w1 = Errors(C(i,t) - 2000, 1:n);
w2 = Errors(C(i,t) - 2000, (n+1):end);
Errors(C(i,t) - 2000, 1:n) = v1;
Errors(C(i,t) - 2000, (n+1):end) = v2;
Errors(i, 1:end) = w1;
Errors(i, (n+1):end) = w2;
end
end
if C(i,t) == 5
% This corresponds to X measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, (n+1):end);
Errors(i, 1:end) = 0;
end
if C(i,t) == 6
% This corresponds to Z measurement, therefore need to look at Z errors
find(Meas_dict==(i+(t-1)*length(C(:,1))) ); % Dont think these are needed, used for checking
Output(2*N_output + find(Meas_dict==(i+(t-1)*length(C(:,1))) ), :) = Errors(i, 1:n);
Errors(i, 1:end) = 0;
end
end
end
% Introduce faults for locations that are not measurements
for j = 1:length(e(:,1))
if e(j,1) ~= 0
if e(j,4) == t && ( C(e(j,2),t) ~= 5 ) && ( C(e(j,2),t) ~= 6 )
% This IF statement checks to see if the gate at this location is NOT a CNOT or Prep
if ( C(e(j,2),t) < 1000 ) %&& ( C(e(j,2),t) ~= 3 ) && ( C(e(j,2),t) ~= 4 )
if e(j,1) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if e(j,1) == 2
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if e(j,1) == 3
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
end
% Introduce errors in the case of CNOT gate for control and target qubits
% Errors for control qubit are entry mod(e(j,1),4) according to standard indexing above
if ( (C(e(j,2),t) > 1000) && (C(e(j,2),t) < 2000))
if C(C(e(j,2),t) - 1000, t) == 1000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 1000, e(j,3)) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 1000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 1000, e(j,3)+n) + 1, 2);
end
end
end
if C(e(j,2),t) > 2000
if C(C(e(j,2),t) - 2000, t) == 2000
if mod(e(j,1),2) == 1
Errors(e(j,2), e(j,3)) = mod(Errors(e(j,2), e(j,3)) + 1, 2);
end
if mod(e(j,1),4) > 1
Errors(e(j,2), e(j,3)+n) = mod(Errors(e(j,2), e(j,3)+n) + 1, 2);
end
if mod(floor(e(j,1)/4),2) == 1
Errors(C(e(j,2),t) - 2000, e(j,3)) = mod(Errors(C(e(j,2),t) - 2000, e(j,3)) + 1, 2);
end
if mod(floor(e(j,1)/4),4) > 1
Errors(C(e(j,2),t) - 2000, e(j,3)+n) = mod(Errors(C(e(j,2),t) - 2000, e(j,3)+n) + 1, 2);
end
end
end
end
end
end
end
%Errors
counter = 1; % This will be used to iterate over the different qubits
for j = 1:length(C(:,end))
if (C(j,end) ~= -1) && (C(j,end) ~= 5) && (C(j,end) ~= 6)
Output(counter,:) = Errors(j,1:n);
Output(counter+1,:) = Errors(j,(n+1):end);
counter = counter + 2;
end
end
end
function Output = SurfaceCodeCircuitGenerator(d)
% Creates d = 3 surface code circuit Matteo
% Circuit descriptors:
% -1: qubit non-active
% 0: Noiseless memory
% 1: Gate memory
% 2: Measurement memory
% 3: Preparation in X basis (|+> state)
% 4: Preparation in Z basis (|0> state)
% 5: Measurement in X basis
% 6: Measurement in Z basis
% 7: X gate
% 8: Z gate
% 10: H gate
% 11: S gate
% 20: T gate
%1---: Control qubit for CNOT with target ---
%1000: Target qubit for CNOT
%2000: Qubit for SWAP gate
numRows = 2*(d^2) -1 ;
numTimeSteps = 6;
qubitNum = (d^2-1)/2;
Cd3 = zeros(numRows,numTimeSteps);
% Set the storage locations at all qubit locations (first two and last two
% time steps)
for i = 1:(d^2)
for j = 1:numTimeSteps
Cd3(i + qubitNum,j) = 1;
Cd3(i + qubitNum,j) = 1;
Cd3(i + qubitNum,j) = 1;
Cd3(i + qubitNum,j) = 1;
end
end
% Initialise X stabilizer state prep and measurements
for i = 1:((d^2)-1)/2
Cd3(i,1) = 3;
Cd3(i,6) = 5;
end
% Initialise Z stabilizer state prep and measurements
for i = (((3*(d^2)-1)/2)+1):(2*(d^2)-1)
Cd3(i,1) = 4;
Cd3(i,6) = 6;
end
% Creat matrix of data qubit number
dataMat = zeros(d,d);
counter = 1;
for i = 1:d
for j = 1:d
dataMat(i,j) = counter + (((d^2)-1)/2);
counter = counter + 1;
end
end
% Creat matrix for X and Z stabilizer ancilla qubit numbers
ancillaStabXMat = zeros(((d+1)/2),d-1);
ancillaStabZMat = zeros(d-1,((d+1)/2));
counter = 1;
for i = 1:length(ancillaStabXMat(1,:))
for j = 1:length(ancillaStabXMat(:,1))
ancillaStabXMat(j,i) = counter;
counter = counter + 1;
end
end
counter = 1;
for i = 1:length(ancillaStabZMat(:,1))
for j = 1:length(ancillaStabZMat(1,:))
ancillaStabZMat(i,j) = counter;
counter = counter + 1;
end
end
% Next we input gates from measurement qubits to data qubits
% First cycle (measure upper right qubits)
% Input target and control of the CNOT gates for X stabilizers
timeStep = 2;
rwoXstab = 1;
for i = 1:length(dataMat(:,1))
if mod(i,2) == 0
colXstab = 2;
else
colXstab = 1;
end
for j = 1:length(dataMat(1,:))
if mod(i,2) == 1
if mod(j,2) == 0
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
end
else
if mod(j,2) == 1 && j ~= 1
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
end
end
end
if mod(i,2) == 1
rwoXstab = rwoXstab + 1;
end
end
% Input target and control of the CNOT gates for Z stabilizers
rwoZstab = 1;
for i = 1:(length(dataMat(:,1))-1)
colZstab = 1;
for j = 1:length(dataMat(1,:))
if mod(i,2) == 1
if mod(j,2) == 1
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
end
else
if mod(j,2) == 0
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
end
end
end
rwoZstab = rwoZstab + 1;
end
% Second cycle (measure upper left qubits for X stabilizers and lower right qubits for Z stabilizers)
timeStep = timeStep + 1;
% Input target and control of the CNOT gates for X stabilizers
rwoXstab = 1;
for i = 1:length(dataMat(:,1))
if mod(i,2) == 0
colXstab = 2;
else
colXstab = 1;
end
for j = 1:length(dataMat(1,:))
if (mod(i,2) == 1) && (mod(j,2) == 1) && (j < length(dataMat(1,:)))
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
elseif (mod(i,2) == 0) && (mod(j,2) == 0)
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
end
end
if mod(i,2) == 1
rwoXstab = rwoXstab + 1;
end
end
% Input target and control of the CNOT gates for Z stabilizers
rwoZstab = 1;
for i = 2:length(dataMat(:,1))
colZstab = 1;
for j = 1:length(dataMat(1,:))
if (mod(i,2) == 0) && (mod(j,2) == 1)
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
elseif (mod(i,2) == 1) && (mod(j,2) == 0)
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
end
end
rwoZstab = rwoZstab + 1;
end
% Third cycle (lower right qubits for X stabilizers and upper left qubits for Z stabilizers)
timeStep = timeStep + 1;
% Input target and control of the CNOT gates for X stabilizers
rwoXstab = 1;
for i = 1:length(dataMat(:,1))
if mod(i,2) == 0
colXstab = 1;
else
colXstab = 2;
end
for j = 2:length(dataMat(1,:))
if mod(i,2) == 1 && mod(j,2) == 1
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
elseif mod(i,2) == 0 && mod(j,2) == 0
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
end
end
if mod(i,2) == 0
rwoXstab = rwoXstab + 1;
end
end
% Input target and control of the CNOT gates for Z stabilizers
rwoZstab = 1;
for i = 1:(length(dataMat(:,1))-1)
if mod(i,2) == 1
colZstab = 2;
else
colZstab = 1;
end
for j = 1:length(dataMat(1,:))
if mod(i,2) == 1 && mod(j,2) == 0
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
elseif mod(i,2) == 0 && mod(j,2) == 1
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
end
end
rwoZstab = rwoZstab + 1;
end
% Fourth cycle (lower right qubits for X stabilizers and upper left qubits for Z stabilizers)
timeStep = timeStep + 1;
% Input target and control of the CNOT gates for X stabilizers
rwoXstab = 1;
for i = 1:length(dataMat(:,1))
if mod(i,2) == 0
colXstab = 1;
else
colXstab = 2;
end
for j = 1:(length(dataMat(1,:))-1)
if mod(i,2) == 1 && mod(j,2) == 0
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
elseif mod(i,2) == 0 && mod(j,2) == 1
Cd3(dataMat(i,j),timeStep) = 1000;
Cd3(ancillaStabXMat(rwoXstab,colXstab),timeStep) = 1000 + dataMat(i,j);
colXstab = colXstab + 2;
end
end
if mod(i,2) == 0
rwoXstab = rwoXstab + 1;
end
end
% Input target and control of the CNOT gates for Z stabilizers
rwoZstab = 1;
for i = 2:length(dataMat(:,1))
if mod(i,2) == 0
colZstab = 2;
else
colZstab = 1;
end
for j = 1:length(dataMat(1,:))
if mod(i,2) == 0 && mod(j,2) == 0
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
elseif mod(i,2) == 1 && mod(j,2) == 1
Cd3(ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2,timeStep) = 1000;
Cd3(dataMat(i,j),timeStep) = 1000 + ancillaStabZMat(rwoZstab,colZstab)+d^2+((d^2)-1)/2;
colZstab = colZstab + 1;
end
end
rwoZstab = rwoZstab + 1;
end
Output = Cd3;
end
function Output = ErrorGenerator(Cmat,errRate)
%This function outputs an error vector based on the input circuit
%represented by Cmat. We have the following noise model.
% 1) |0> state preparation: Perfect |0> state followed by X error with probability p
% 2) Z-measurement: X pauli with probability p followed by perfect Z-basis
% measurement.
% 3) CNOT: Perfect CNOT followed by
%{IX,IY,IZ,XI,YI,ZI,XX,XY,XZ,ZX,ZY,ZZ,YX,YY,YZ} with probability p/15 each.
% 4) Hadamard: Perfect Hadamard followed by {X,Y,Z} with probability p/12
%each.
% 5) SWAP: Perfect SWAP followed by
% {IX,IY,IZ,XI,YI,ZI,XX,XY,XZ,ZX,ZY,ZZ,YX,YY,YZ} with probability p/60
% each.
% Storage: Pauli {X,Y,Z} with probability p/30 each.
% Here errRate = p and Cmat is the circuit representing the surface code
% lattice.
e = zeros(1,4);
counter = 1;
for i = 1:length(Cmat(:,1))
for j = 1:length(Cmat(1,:))
% Adds storage errors with probability p
if (Cmat(i,j) == 1)
xi = rand;
if xi < errRate
k = randi([1,3]);
e(counter,:) = [k,i,1,j];
counter = counter + 1;
end
end
% Adds state-preparation errors with probability 2p/3
if Cmat(i,j) == 4
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,i,1,j];
counter = counter + 1;
end
end
if Cmat(i,j) == 3
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,i,1,j];
counter = counter + 1;
end
end
% Adds measurement errors with probability 2p/3
if Cmat(i,j) == 6
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [1,i,1,j];
counter = counter + 1;
end
end
if Cmat(i,j) == 5
xi = rand;
if xi < 2*errRate/3
e(counter,:) = [2,i,1,j];
counter = counter + 1;
end
end
% Adds CNOT errors with probability p
if (Cmat(i,j) > 1000)
xi = rand;
if xi < errRate
k = randi([1,15]);
e(counter,:) = [k,i,1,j];
counter = counter + 1;
end
end
end
end
Output = e;
end
function Output = ConvertErrorXStringToErrorVec(ErrStrX)
e = zeros(1,4);
counter = 1;
for i = 1:length(ErrStrX(1,:))
if ErrStrX(1,i) == 1
e(counter,:) = [1,i+12,1,1];
counter = counter + 1;
end
end
Output = e;
end
function Output = ConvertErrorZStringToErrorVec(ErrStrZ)
e = zeros(1,4);
counter = 1;
for i = 1:length(ErrStrZ(1,:))
if ErrStrZ(1,i) == 1
e(counter,:) = [2,i+12,1,1];
counter = counter + 1;
end
end
Output = e;
end
function [OutputSynX1,OutputSynZ1,OutputErrX1,OutputErrZ1,OutputCount] = depolarizingSimulator(numIterations,errRate,n,t)
% This function generates X and Z syndrome measurement results for three
% rounds of error correction of the d=3 rotated surface code as well as the
% X and Z errors for each round
% Circuit descriptors:
% -1: qubit non-active
% 0: Noiseless memory
% 1: Gate memory
% 2: Measurement memory
% 3: Preparation in X basis (|+> state)
% 4: Preparation in Z basis (|0> state)
% 5: Measurement in X basis
% 6: Measurement in Z basis
% 7: X gate
% 8: Z gate
% 10: H gate
% 11: S gate
% 20: T gate
%1---: Control qubit for CNOT with target ---
%1000: Target qubit for CNOT
% Full circuit for measuring the X and Z stabilizers of the d=3 rotated
% surface code
Circuit = [3 1014 1013 1019 1018 5
3 1024 1023 1029 1028 5
3 1034 1033 0 0 5
3 0 0 1015 1014 5
3 1020 1019 1025 1024 5
3 1030 1029 1035 1034 5
3 1016 1015 1021 1020 5
3 1026 1025 1031 1030 5
3 1036 1035 0 0 5
3 0 0 1017 1016 5
3 1022 1021 1027 1026 5
3 1032 1031 1037 1036 5
1 1038 1000 1 1 1
1 1000 1 1039 1000 1
1 1039 1000 1000 1 1
1 1000 1 1040 1000 1
1 1040 1 1000 1 1
1 1 1038 1041 1000 1
1 1041 1000 1000 1039 1
1 1000 1039 1042 1000 1
1 1042 1000 1000 1040 1
1 1000 1040 1043 1 1
1 1044 1000 1 1041 1
1 1000 1041 1045 1000 1
1 1045 1000 1000 1042 1
1 1000 1042 1046 1000 1
1 1046 1 1000 1043 1
1 1 1044 1047 1000 1
1 1047 1000 1000 1045 1
1 1000 1045 1048 1000 1
1 1048 1000 1000 1046 1
1 1000 1046 1049 1 1
1 1 1000 1 1047 1
1 1000 1047 1 1000 1
1 1 1000 1000 1048 1
1 1000 1048 1 1000 1
1 1 1 1000 1049 1
4 1000 1000 0 0 6
4 1000 1000 1000 1000 6
4 1000 1000 1000 1000 6
4 1000 1000 1000 1000 6
4 1000 1000 1000 1000 6
4 0 0 1000 1000 6
4 1000 1000 0 0 6
4 1000 1000 1000 1000 6
4 1000 1000 1000 1000 6
4 1000 1000 1000 1000 6
4 1000 1000 1000 1000 6
4 0 0 1000 1000 6];
totalIt = 0.5*((t^2)+3*t+2);
ErrXOutputBlock1 = zeros(totalIt*numIterations,25);
ErrZOutputBlock1 = zeros(totalIt*numIterations,25);
SynXOutputBlock1 = zeros(totalIt*numIterations,12);
SynZOutputBlock1 = zeros(totalIt*numIterations,12);
numSize = 1;
countIterations = 0;
while numSize < (numIterations+1)
XSyn = zeros(totalIt,12); % Stores the X syndromes for each round
ZSyn = zeros(totalIt,12); % Stores the Z syndromes for each round
XErrTrack = zeros(totalIt,25); % Stores the X errors for each round
ZErrTrack = zeros(totalIt,25); % Stores the Z errors for each round
e = zeros(1,4);
for numRound = 1:6
eCircuit = ErrorGenerator(Circuit,errRate);
eTemp = [e;eCircuit];
Cout = transpose(PropagationStatePrepArb(Circuit, n, eTemp));
Xerror = Cout(1,1:2:50);
Zerror = Cout(1,2:2:50);
XErrTrack(numRound,:) = Xerror;
ZErrTrack(numRound,:) = Zerror;
ZSyn(numRound,:) = Cout(1,51:62);
XSyn(numRound,:) = Cout(1,63:74);
eX = ConvertErrorXStringToErrorVec(Xerror);
eZ = ConvertErrorZStringToErrorVec(Zerror);
e = [eX;eZ];
end
if sum(any(XSyn)) ~= 0 || sum(any(ZSyn)) ~= 0 || sum(any(Xerror)) ~= 0 || sum(any(Zerror)) ~= 0
ErrXOutputBlock1(totalIt*(numSize-1)+1:totalIt*numSize,:) = XErrTrack;
ErrZOutputBlock1(totalIt*(numSize-1)+1:totalIt*numSize,:) = ZErrTrack;
SynXOutputBlock1(totalIt*(numSize-1)+1:totalIt*numSize,:) = XSyn;
SynZOutputBlock1(totalIt*(numSize-1)+1:totalIt*numSize,:) = ZSyn;
numSize = numSize + 1;
end
countIterations = countIterations + 1;
end
OutputSynX1 = SynXOutputBlock1;
OutputSynZ1 = SynZOutputBlock1;
OutputErrX1 = ErrXOutputBlock1;
OutputErrZ1 = ErrZOutputBlock1;
OutputCount = countIterations;
end
|
github
|
cellgeometry/heteromotility-master
|
dist_v_mag.m
|
.m
|
heteromotility-master/analysis/dist_v_mag.m
| 583 |
utf_8
|
e60f1112cfd713a52381b1a4c364beac
|
%% Calculate distance and vector magnitude at each point in a divergence matrix
function [result] = dist_v_mag(div, m_u, m_v, m_s);
% div = N x M divergence matrix
% m_u = N x M matrix of vector field x-component
% m_v = N x M matrix of vector field y-component
% m_s = 2 x 1 vector i, j index for minimum divergence (metastable state)
result = zeros(length(div(:)), 2);
for k = 1:length(div(:));
[i,j] = ind2sub(size(div), k);
u = [i j];
d = sqrt( sum((m_s-u).^2) );
flux = [m_u(i,j), m_v(i,j)];
mag = sqrt( dot(flux,flux) );
result(k,:) = [d mag];
end
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
get_image_paths.m
|
.m
|
SceneRecognition-master/code/get_image_paths.m
| 1,671 |
utf_8
|
50df335e4058c9fe2f305b5711efa9a3
|
%we used this function from James Hayes Course to load the image paths
%This function returns cell arrays containing the file path for each train
%and test image, as well as cell arrays with the label of each train and
%test image.
function [train_image_paths, test_image_paths, train_labels, test_labels] = ...
get_image_paths(data_path, categories, num_train_per_cat)
num_categories = length(categories); %number of scene categories.
%This paths for each training and test image. By default it will have 1500
%entries (15 categories * 100 training and test examples each)
train_image_paths = cell(num_categories * num_train_per_cat, 1);
test_image_paths = cell(num_categories * num_train_per_cat, 1);
%The name of the category for each training and test image. With the
%default setup, these arrays will actually be the same, but they are built
%independently for clarity and ease of modification.
train_labels = cell(num_categories * num_train_per_cat, 1);
test_labels = cell(num_categories * num_train_per_cat, 1);
for i=1:num_categories
images = dir(fullfile(data_path, 'train', categories{i}, '*.jpg'));
for j=1:num_train_per_cat
train_image_paths{(i-1)*num_train_per_cat + j} = fullfile(data_path, 'train', categories{i}, images(j).name);
train_labels{(i-1)*num_train_per_cat + j} = categories{i};
end
images = dir( fullfile(data_path, 'test', categories{i}, '*.jpg'));
for j=1:num_train_per_cat
test_image_paths{(i-1)*num_train_per_cat + j} = fullfile(data_path, 'test', categories{i}, images(j).name);
test_labels{(i-1)*num_train_per_cat + j} = categories{i};
end
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
create_results_webpage.m
|
.m
|
SceneRecognition-master/code/create_results_webpage.m
| 12,092 |
utf_8
|
cb211d5fedc6451c228c5b7a3f1104cc
|
% This function creates a webpage (html and images) visualizing the
% classiffication results. This webpage will contain
% (1) A confusion matrix plot
% (2) A table with one row per category, with 3 columns - training
% examples, true positives, false positives, and false negatives.
% false positives are instances claimed as that category but belonging to
% another category, e.g. in the 'forest' row an image that was classified
% as 'forest' but is actually 'mountain'. This same image would be
% considered a false negative in the 'mountain' row, because it should have
% been claimed by the 'mountain' classifier but was not.
function create_results_webpage( train_image_paths, test_image_paths, train_labels, test_labels, categories, abbr_categories, predicted_categories)
fprintf('Creating results_webpage/index.html, thumbnails, and confusion matrix\n')
%number of examples of training examples, true positives, false positives,
%and false negatives. Thus the table will be num_samples * 4 images wide
%(unless there aren't enough images)
num_samples = 2;
thumbnail_height = 75; %pixels
%delete the old thumbnails, if there are any
delete('results_webpage/thumbnails/*.jpg')
[success,message,messageid] = mkdir('results_webpage');
[success,message,messageid] = mkdir('results_webpage/thumbnails');
fclose('all');
fid = fopen('results_webpage/index.html', 'w+t');
num_categories = length(categories);
%% Create And Save Confusion Matrix
% Based on the predicted category for each test case, we will now build a
% confusion matrix. Entry (i,j) in this matrix well be the proportion of
% times a test image of ground truth category i was predicted to be
% category j. An identity matrix is the ideal case. You should expect
% roughly 50-95% along the diagonal depending on your features,
% classifiers, and particular categories. For example, suburb is very easy
% to recognize.
confusion_matrix = zeros(num_categories, num_categories);
for i=1:length(predicted_categories)
row = find(strcmp(test_labels{i}, categories));
column = find(strcmp(predicted_categories{i}, categories));
confusion_matrix(row, column) = confusion_matrix(row, column) + 1;
end
%if the number of training examples and test casees are not equal, this
%statement will be invalid.
num_test_per_cat = length(test_labels) / num_categories;
confusion_matrix = confusion_matrix ./ num_test_per_cat;
accuracy = mean(diag(confusion_matrix));
fprintf( 'Accuracy (mean of diagonal of confusion matrix) is %.3f\n', accuracy)
fig_handle = figure;
imagesc(confusion_matrix, [0 1]);
set(fig_handle, 'Color', [.988, .988, .988])
axis_handle = get(fig_handle, 'CurrentAxes');
set(axis_handle, 'XTick', 1:15)
set(axis_handle, 'XTickLabel', abbr_categories)
set(axis_handle, 'YTick', 1:15)
set(axis_handle, 'YTickLabel', categories)
visualization_image = frame2im(getframe(fig_handle));
% getframe() is unreliable. Depending on the rendering settings, it will
% grab foreground windows instead of the figure in question. It could also
% return a partial image.
imwrite(visualization_image, 'results_webpage/confusion_matrix.png')
%% Create webpage header
fprintf(fid,'<!DOCTYPE html>\n');
fprintf(fid,'<html>\n');
fprintf(fid,'<head>\n');
fprintf(fid,'<link href=''http://fonts.googleapis.com/css?family=Nunito:300|Crimson+Text|Droid+Sans+Mono'' rel=''stylesheet'' type=''text/css''>\n');
fprintf(fid,'<style type="text/css">\n');
fprintf(fid,'body {\n');
fprintf(fid,' margin: 0px;\n');
fprintf(fid,' width: 100%%;\n');
fprintf(fid,' font-family: ''Crimson Text'', serif;\n');
fprintf(fid,' background: #fcfcfc;\n');
fprintf(fid,'}\n');
fprintf(fid,'table td {\n');
fprintf(fid,' text-align: center;\n');
fprintf(fid,' vertical-align: middle;\n');
fprintf(fid,'}\n');
fprintf(fid,'h1 {\n');
fprintf(fid,' font-family: ''Nunito'', sans-serif;\n');
fprintf(fid,' font-weight: normal;\n');
fprintf(fid,' font-size: 28px;\n');
fprintf(fid,' margin: 25px 0px 0px 0px;\n');
fprintf(fid,' text-transform: lowercase;\n');
fprintf(fid,'}\n');
fprintf(fid,'.container {\n');
fprintf(fid,' margin: 0px auto 0px auto;\n');
fprintf(fid,' width: 1160px;\n');
fprintf(fid,'}\n');
fprintf(fid,'</style>\n');
fprintf(fid,'</head>\n');
fprintf(fid,'<body>\n\n');
fprintf(fid,'<div class="container">\n\n\n');
fprintf(fid,'<center>\n');
fprintf(fid,'<h1>CS 143 Project 3 results visualization</h1>\n');
fprintf(fid,'<img src="confusion_matrix.png">\n\n');
fprintf(fid,'<br>\n');
fprintf(fid,'Accuracy (mean of diagonal of confusion matrix) is %.3f\n', accuracy);
fprintf(fid,'<p>\n\n');
%% Create results table
fprintf(fid,'<table border=0 cellpadding=4 cellspacing=1>\n');
fprintf(fid,'<tr>\n');
fprintf(fid,'<th>Category name</th>\n');
fprintf(fid,'<th>Accuracy</th>\n');
fprintf(fid,'<th colspan=%d>Sample training images</th>\n', num_samples);
fprintf(fid,'<th colspan=%d>Sample true positives</th>\n', num_samples);
fprintf(fid,'<th colspan=%d>False positives with true label</th>\n', num_samples);
fprintf(fid,'<th colspan=%d>False negatives with wrong predicted label</th>\n', num_samples);
fprintf(fid,'</tr>\n');
for i = 1:num_categories
fprintf(fid,'<tr>\n');
fprintf(fid,'<td>'); %category name
fprintf(fid,'%s', categories{i});
fprintf(fid,'</td>\n');
fprintf(fid,'<td>'); %category accuracy
fprintf(fid,'%.3f', confusion_matrix(i,i));
fprintf(fid,'</td>\n');
%collect num_samples random paths to images of each type.
%Training examples.
train_examples = train_image_paths(strcmp(categories{i}, train_labels));
%True positives. There might not be enough of these if the classifier
%is bad
true_positives = test_image_paths(strcmp(categories{i}, test_labels) & ...
strcmp(categories{i}, predicted_categories));
%False positives. There might not be enough of them if the classifier
%is good
false_positive_inds = ~strcmp(categories{i}, test_labels) & ...
strcmp(categories{i}, predicted_categories);
false_positives = test_image_paths(false_positive_inds);
false_positive_labels = test_labels(false_positive_inds);
%False negatives. There might not be enough of them if the classifier
%is good
false_negative_inds = strcmp(categories{i}, test_labels) & ...
~strcmp(categories{i}, predicted_categories);
false_negatives = test_image_paths( false_negative_inds );
false_negative_labels = predicted_categories(false_negative_inds);
%Randomize each list of files
train_examples = train_examples( randperm(length(train_examples)));
true_positives = true_positives( randperm(length(true_positives)));
false_positive_shuffle = randperm(length(false_positives));
false_positives = false_positives(false_positive_shuffle);
false_positive_labels = false_positive_labels(false_positive_shuffle);
false_negative_shuffle = randperm(length(false_negatives));
false_negatives = false_negatives(false_negative_shuffle);
false_negative_labels = false_negative_labels(false_negative_shuffle);
%Truncate each list to length at most num_samples
train_examples = train_examples( 1:min(length(train_examples), num_samples));
true_positives = true_positives( 1:min(length(true_positives), num_samples));
false_positives = false_positives(1:min(length(false_positives),num_samples));
false_positive_labels = false_positive_labels(1:min(length(false_positive_labels),num_samples));
false_negatives = false_negatives(1:min(length(false_negatives),num_samples));
false_negative_labels = false_negative_labels(1:min(length(false_negative_labels),num_samples));
%sample training images
%Create and save all of the thumbnails
for j=1:num_samples
if(j <= length(train_examples))
tmp = imread(train_examples{j});
height = size(tmp,1);
rescale_factor = thumbnail_height / height;
tmp = imresize(tmp, rescale_factor);
[height, width] = size(tmp);
[pathstr,name, ext] = fileparts(train_examples{j});
imwrite(tmp, ['results_webpage/thumbnails/' categories{i} '_' name '.jpg'], 'quality', 100)
fprintf(fid,'<td bgcolor=LightBlue>');
fprintf(fid,'<img src="%s" width=%d height=%d>', ['thumbnails/' categories{i} '_' name '.jpg'], width, height);
fprintf(fid,'</td>\n');
else
fprintf(fid,'<td bgcolor=LightBlue>');
fprintf(fid,'</td>\n');
end
end
for j=1:num_samples
if(j <= length(true_positives))
tmp = imread(true_positives{j});
height = size(tmp,1);
rescale_factor = thumbnail_height / height;
tmp = imresize(tmp, rescale_factor);
[height, width] = size(tmp);
[pathstr,name, ext] = fileparts(true_positives{j});
imwrite(tmp, ['results_webpage/thumbnails/' categories{i} '_' name '.jpg'], 'quality', 100)
fprintf(fid,'<td bgcolor=LightGreen>');
fprintf(fid,'<img src="%s" width=%d height=%d>', ['thumbnails/' categories{i} '_' name '.jpg'], width, height);
fprintf(fid,'</td>\n');
else
fprintf(fid,'<td bgcolor=LightGreen>');
fprintf(fid,'</td>\n');
end
end
for j=1:num_samples
if(j <= length(false_positives))
tmp = imread(false_positives{j});
height = size(tmp,1);
rescale_factor = thumbnail_height / height;
tmp = imresize(tmp, rescale_factor);
[height, width] = size(tmp);
[pathstr,name, ext] = fileparts(false_positives{j});
imwrite(tmp, ['results_webpage/thumbnails/' false_positive_labels{j} '_' name '.jpg'], 'quality', 100)
fprintf(fid,'<td bgcolor=LightCoral>');
fprintf(fid,'<img src="%s" width=%d height=%d>', ['thumbnails/' false_positive_labels{j} '_' name '.jpg'], width, height);
fprintf(fid,'<br><small>%s</small>', false_positive_labels{j});
fprintf(fid,'</td>\n');
else
fprintf(fid,'<td bgcolor=LightCoral>');
fprintf(fid,'</td>\n');
end
end
for j=1:num_samples
if(j <= length(false_negatives))
tmp = imread(false_negatives{j});
height = size(tmp,1);
rescale_factor = thumbnail_height / height;
tmp = imresize(tmp, rescale_factor);
[height, width] = size(tmp);
[pathstr,name, ext] = fileparts(false_negatives{j});
imwrite(tmp, ['results_webpage/thumbnails/' categories{i} '_' name '.jpg'], 'quality', 100)
fprintf(fid,'<td bgcolor=#FFBB55>');
fprintf(fid,'<img src="%s" width=%d height=%d>', ['thumbnails/' categories{i} '_' name '.jpg'], width, height);
fprintf(fid,'<br><small>%s</small>', false_negative_labels{j});
fprintf(fid,'</td>\n');
else
fprintf(fid,'<td bgcolor=#FFBB55>');
fprintf(fid,'</td>\n');
end
end
fprintf(fid,'</tr>\n');
end
fprintf(fid,'<tr>\n');
fprintf(fid,'<th>Category name</th>\n');
fprintf(fid,'<th>Accuracy</th>\n');
fprintf(fid,'<th colspan=%d>Sample training images</th>\n', num_samples);
fprintf(fid,'<th colspan=%d>Sample true positives</th>\n', num_samples);
fprintf(fid,'<th colspan=%d>False positives with true label</th>\n', num_samples);
fprintf(fid,'<th colspan=%d>False negatives with wrong predicted label</th>\n', num_samples);
fprintf(fid,'</tr>\n');
fprintf(fid,'</table>\n');
fprintf(fid,'</center>\n\n\n');
fprintf(fid,'</div>\n')
%% Create end of web page
fprintf(fid,'</body>\n');
fprintf(fid,'</html>\n');
fclose(fid);
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
svm_classify.m
|
.m
|
SceneRecognition-master/code/svm_classify.m
| 3,037 |
utf_8
|
20eadab16b1ff5e3902e2b9641cf7254
|
%train a one vs all linear SVM classifier, and apply each classifier of the 15 to each image
%and the category is assigned based on the highest result
%5 fold cross validation is applied to get the best regularization parameter (lambda) and avoid overfitting
function predicted_categories = svm_classify(train_features, labels, test_features, categories)
start = tic;
lambda = [0.00001, 0.0001, 0.001, 0.005, 0.01, 0.04, 0.07, 0.1, 0.3, 0.5, 0.7, 1, 10]; % Regularization parameters to choose from
accuracy_f = zeros(1,length(lambda)); %accuracy when using each lambda in the cross validation step
maxIter = 100000; % Maximum number of iterations
fold = 5.; %leave five items from the data set each iteration for cross validation
for i = 1 : length(categories)
for j = 1:length(labels)
if strcmp(labels(j),categories(i)) y(j) = 1; %%convert the training labels to either 1 (for this category) or -1 (for all other categories) to train one vs all classifier for each category
else y(j) = -1;
end
end
%take a sample from the negatives to prevent it's over representation (1:3 positives to negatives), with the negatives taken randomly from all the negatives
no_positives = sum(y==1);
order_ = randperm(length(labels),no_positives*4);
order = ones(1,no_positives*3);
count = 1;
%make sure that this random sample contains negatives only (as positives will be added in the next step)
for k = 1:length(order_)
if count > length(order)
break;
end
if (order_(k) < (i-1)*no_positives + 1 || order_(k) > i*no_positives) order(count) = order_(k); count = count + 1;
end
end
%put all the positives in the beginning for easier manipulation
[y_1 I] = sort(y,'descend'); y = [y_1(1:no_positives) y_1(order)];
x = [train_features(:,I(1:no_positives)) train_features(:,order)];
no_folds = uint16(length(y)/fold); %%the no of iterations needed to span the whole training set based on the fold size
%cross validation for regularization parameter
for k = 1:length(lambda)
accuracy = zeros(1,no_folds);
for j = 1 : no_folds
x_ = [x(:,1:(j-1)*fold) x(:, j*fold+1:size(x,2))];
y_ = [y(1:(j-1)*fold) y(j*fold+1:size(x,2))];
[w_ b_] = vl_svmtrain(x_, y_, lambda(k), 'MaxNumIterations', maxIter);
accuracy(j) = sum(y((j-1)*fold+1:j*fold) == sign(w_'*x(:,(j-1)*fold+1:j*fold) + b_)) / fold;
end
accuracy_f(k) = sum(accuracy) / double(no_folds); %%cross validation accuracy of each lambda
end
[a(i) ind(i)] = max(accuracy_f); %%get the best lambda
[w(:,i) b(i)] = vl_svmtrain(x, y, lambda(ind(i)), 'MaxNumIterations', maxIter); %%the training on the whole data set with the lambda choosen
end
%classifying the test set
for i = 1 : length(test_features)
classification = w'*test_features(:,i) + b';
[acc(i) indx(i)] = max(classification);
predicted_categories(i,1) = categories(indx(i));
end
telapsed = toc(start);
fprintf('time for getting classifying: %d secs\n', telapsed)
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_compile.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/vl_compile.m
| 5,060 |
utf_8
|
978f5189bb9b2a16db3368891f79aaa6
|
function vl_compile(compiler)
% VL_COMPILE Compile VLFeat MEX files
% VL_COMPILE() uses MEX() to compile VLFeat MEX files. This command
% works only under Windows and is used to re-build problematic
% binaries. The preferred method of compiling VLFeat on both UNIX
% and Windows is through the provided Makefiles.
%
% VL_COMPILE() only compiles the MEX files and assumes that the
% VLFeat DLL (i.e. the file VLFEATROOT/bin/win{32,64}/vl.dll) has
% already been built. This file is built by the Makefiles.
%
% By default VL_COMPILE() assumes that Visual C++ is the active
% MATLAB compiler. VL_COMPILE('lcc') assumes that the active
% compiler is LCC instead (see MEX -SETUP). Unfortunately LCC does
% not seem to be able to compile the latest versions of VLFeat due
% to bugs in the support of 64-bit integers. Therefore it is
% recommended to use Visual C++ instead.
%
% See also: VL_NOPREFIX(), VL_HELP().
% Authors: Andrea Vedadli, Jonghyun Choi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin < 1, compiler = 'visualc' ; end
switch lower(compiler)
case 'visualc'
fprintf('%s: assuming that Visual C++ is the active compiler\n', mfilename) ;
useLcc = false ;
case 'lcc'
fprintf('%s: assuming that LCC is the active compiler\n', mfilename) ;
warning('LCC may fail to compile VLFeat. See help vl_compile.') ;
useLcc = true ;
otherwise
error('Unknown compiler ''%s''.', compiler)
end
vlDir = vl_root ;
toolboxDir = fullfile(vlDir, 'toolbox') ;
switch computer
case 'PCWIN'
fprintf('%s: compiling for PCWIN (32 bit)\n', mfilename);
mexwDir = fullfile(toolboxDir, 'mex', 'mexw32') ;
binwDir = fullfile(vlDir, 'bin', 'win32') ;
case 'PCWIN64'
fprintf('%s: compiling for PCWIN64 (64 bit)\n', mfilename);
mexwDir = fullfile(toolboxDir, 'mex', 'mexw64') ;
binwDir = fullfile(vlDir, 'bin', 'win64') ;
otherwise
error('The architecture is neither PCWIN nor PCWIN64. See help vl_compile.') ;
end
impLibPath = fullfile(binwDir, 'vl.lib') ;
libDir = fullfile(binwDir, 'vl.dll') ;
mkd(mexwDir) ;
% find the subdirectories of toolbox that we should process
subDirs = dir(toolboxDir) ;
subDirs = subDirs([subDirs.isdir]) ;
discard = regexp({subDirs.name}, '^(.|..|noprefix|mex.*)$', 'start') ;
keep = cellfun('isempty', discard) ;
subDirs = subDirs(keep) ;
subDirs = {subDirs.name} ;
% Copy support files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if ~exist(fullfile(binwDir, 'vl.dll'))
error('The VLFeat DLL (%s) could not be found. See help vl_compile.', ...
fullfile(binwDir, 'vl.dll')) ;
end
tmp = dir(fullfile(binwDir, '*.dll')) ;
supportFileNames = {tmp.name} ;
for fi = 1:length(supportFileNames)
name = supportFileNames{fi} ;
cp(fullfile(binwDir, name), ...
fullfile(mexwDir, name) ) ;
end
% Ensure implib for LCC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if useLcc
lccImpLibDir = fullfile(mexwDir, 'lcc') ;
lccImpLibPath = fullfile(lccImpLibDir, 'VL.lib') ;
lccRoot = fullfile(matlabroot, 'sys', 'lcc', 'bin') ;
lccImpExePath = fullfile(lccRoot, 'lcc_implib.exe') ;
mkd(lccImpLibDir) ;
cp(fullfile(binwDir, 'vl.dll'), fullfile(lccImpLibDir, 'vl.dll')) ;
cmd = ['"' lccImpExePath '"', ' -u ', '"' fullfile(lccImpLibDir, 'vl.dll') '"'] ;
fprintf('Running:\n> %s\n', cmd) ;
curPath = pwd ;
try
cd(lccImpLibDir) ;
[d,w] = system(cmd) ;
if d, error(w); end
cd(curPath) ;
catch
cd(curPath) ;
error(lasterr) ;
end
end
% Compile each mex file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for i = 1:length(subDirs)
thisDir = fullfile(toolboxDir, subDirs{i}) ;
fileNames = ls(fullfile(thisDir, '*.c'));
for f = 1:size(fileNames,1)
fileName = fileNames(f, :) ;
sp = strfind(fileName, ' ');
if length(sp) > 0, fileName = fileName(1:sp-1); end
filePath = fullfile(thisDir, fileName);
fprintf('MEX %s\n', filePath);
dot = strfind(fileName, '.');
mexFile = fullfile(mexwDir, [fileName(1:dot) 'dll']);
if exist(mexFile)
delete(mexFile)
end
cmd = {['-I' toolboxDir], ...
['-I' vlDir], ...
'-O', ...
'-outdir', mexwDir, ...
filePath } ;
if useLcc
cmd{end+1} = lccImpLibPath ;
else
cmd{end+1} = impLibPath ;
end
mex(cmd{:}) ;
end
end
% --------------------------------------------------------------------
function cp(src,dst)
% --------------------------------------------------------------------
if ~exist(dst,'file')
fprintf('Copying ''%s'' to ''%s''.\n', src,dst) ;
copyfile(src,dst) ;
end
% --------------------------------------------------------------------
function mkd(dst)
% --------------------------------------------------------------------
if ~exist(dst, 'dir')
fprintf('Creating directory ''%s''.', dst) ;
mkdir(dst) ;
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_noprefix.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/vl_noprefix.m
| 1,875 |
utf_8
|
97d8755f0ba139ac1304bc423d3d86d3
|
function vl_noprefix
% VL_NOPREFIX Create a prefix-less version of VLFeat commands
% VL_NOPREFIX() creats prefix-less stubs for VLFeat functions
% (e.g. SIFT for VL_SIFT). This function is seldom used as the stubs
% are included in the VLFeat binary distribution anyways. Moreover,
% on UNIX platforms, the stubs are generally constructed by the
% Makefile.
%
% See also: VL_COMPILE(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
root = fileparts(which(mfilename)) ;
list = listMFilesX(root);
outDir = fullfile(root, 'noprefix') ;
if ~exist(outDir, 'dir')
mkdir(outDir) ;
end
for li = 1:length(list)
name = list(li).name(1:end-2) ; % remove .m
nname = name(4:end) ; % remove vl_
stubPath = fullfile(outDir, [nname '.m']) ;
fout = fopen(stubPath, 'w') ;
fprintf('Creating stub %s for %s\n', stubPath, nname) ;
fprintf(fout, 'function varargout = %s(varargin)\n', nname) ;
fprintf(fout, '%% %s Stub for %s\n', upper(nname), upper(name)) ;
fprintf(fout, '[varargout{1:nargout}] = %s(varargin{:})\n', name) ;
fclose(fout) ;
end
end
function list = listMFilesX(root)
list = struct('name', {}, 'path', {}) ;
files = dir(root) ;
for fi = 1:length(files)
name = files(fi).name ;
if files(fi).isdir
if any(regexp(name, '^(\.|\.\.|noprefix)$'))
continue ;
else
tmp = listMFilesX(fullfile(root, name)) ;
list = [list, tmp] ;
end
end
if any(regexp(name, '^vl_(demo|test).*m$'))
continue ;
elseif any(regexp(name, '^vl_(demo|setup|compile|help|root|noprefix)\.m$'))
continue ;
elseif any(regexp(name, '\.m$'))
list(end+1) = struct(...
'name', {name}, ...
'path', {fullfile(root, name)}) ;
end
end
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_pegasos.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/misc/vl_pegasos.m
| 2,837 |
utf_8
|
d5e0915c439ece94eb5597a07090b67d
|
% VL_PEGASOS [deprecated]
% VL_PEGASOS is deprecated. Please use VL_SVMTRAIN() instead.
function [w b info] = vl_pegasos(X,Y,LAMBDA, varargin)
% Verbose not supported
if (sum(strcmpi('Verbose',varargin)))
varargin(find(strcmpi('Verbose',varargin),1))=[];
fprintf('Option VERBOSE is no longer supported.\n');
end
% DiagnosticCallRef not supported
if (sum(strcmpi('DiagnosticCallRef',varargin)))
varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[];
varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[];
fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n');
end
% different default value for MaxIterations
if (sum(strcmpi('MaxIterations',varargin)) == 0)
varargin{end+1} = 'MaxIterations';
varargin{end+1} = ceil(10/LAMBDA);
end
% different default value for BiasMultiplier
if (sum(strcmpi('BiasMultiplier',varargin)) == 0)
varargin{end+1} = 'BiasMultiplier';
varargin{end+1} = 0;
end
% parameters for vl_maketrainingset
setvarargin = {};
if (sum(strcmpi('HOMKERMAP',varargin)))
setvarargin{end+1} = 'HOMKERMAP';
setvarargin{end+1} = varargin{find(strcmpi('HOMKERMAP',varargin),1)+1};
varargin(find(strcmpi('HOMKERMAP',varargin),1)+1)=[];
varargin(find(strcmpi('HOMKERMAP',varargin),1))=[];
end
if (sum(strcmpi('KChi2',varargin)))
setvarargin{end+1} = 'KChi2';
varargin(find(strcmpi('KChi2',varargin),1))=[];
end
if (sum(strcmpi('KINTERS',varargin)))
setvarargin{end+1} = 'KINTERS';
varargin(find(strcmpi('KINTERS',varargin),1))=[];
end
if (sum(strcmpi('KL1',varargin)))
setvarargin{end+1} = 'KL1';
varargin(find(strcmpi('KL1',varargin),1))=[];
end
if (sum(strcmpi('KJS',varargin)))
setvarargin{end+1} = 'KJS';
varargin(find(strcmpi('KJS',varargin),1))=[];
end
if (sum(strcmpi('Period',varargin)))
setvarargin{end+1} = 'Period';
setvarargin{end+1} = varargin{find(strcmpi('Period',varargin),1)+1};
varargin(find(strcmpi('Period',varargin),1)+1)=[];
varargin(find(strcmpi('Period',varargin),1))=[];
end
if (sum(strcmpi('Window',varargin)))
setvarargin{end+1} = 'Window';
setvarargin{end+1} = varargin{find(strcmpi('Window',varargin),1)+1};
varargin(find(strcmpi('Window',varargin),1)+1)=[];
varargin(find(strcmpi('Window',varargin),1))=[];
end
if (sum(strcmpi('Gamma',varargin)))
setvarargin{end+1} = 'Gamma';
setvarargin{end+1} = varargin{find(strcmpi('Gamma',varargin),1)+1};
varargin(find(strcmpi('Gamma',varargin),1)+1)=[];
varargin(find(strcmpi('Gamma',varargin),1))=[];
end
setvarargin{:}
DATA = vl_maketrainingset(double(X),int8(Y),setvarargin{:});
DATA
[w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:});
fprintf('\n vl_pegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n');
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_svmpegasos.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/misc/vl_svmpegasos.m
| 1,178 |
utf_8
|
009c2a2b87a375d529ed1a4dbe3af59f
|
% VL_SVMPEGASOS [deprecated]
% VL_SVMPEGASOS is deprecated. Please use VL_SVMTRAIN() instead.
function [w b info] = vl_svmpegasos(DATA,LAMBDA, varargin)
% Verbose not supported
if (sum(strcmpi('Verbose',varargin)))
varargin(find(strcmpi('Verbose',varargin),1))=[];
fprintf('Option VERBOSE is no longer supported.\n');
end
% DiagnosticCallRef not supported
if (sum(strcmpi('DiagnosticCallRef',varargin)))
varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[];
varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[];
fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n');
end
% different default value for MaxIterations
if (sum(strcmpi('MaxIterations',varargin)) == 0)
varargin{end+1} = 'MaxIterations';
varargin{end+1} = ceil(10/LAMBDA);
end
% different default value for BiasMultiplier
if (sum(strcmpi('BiasMultiplier',varargin)) == 0)
varargin{end+1} = 'BiasMultiplier';
varargin{end+1} = 0;
end
[w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:});
fprintf('\n vl_svmpegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n');
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_override.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/misc/vl_override.m
| 4,654 |
utf_8
|
e233d2ecaeb68f56034a976060c594c5
|
function config = vl_override(config,update,varargin)
% VL_OVERRIDE Override structure subset
% CONFIG = VL_OVERRIDE(CONFIG, UPDATE) copies recursively the fileds
% of the structure UPDATE to the corresponding fields of the
% struture CONFIG.
%
% Usually CONFIG is interpreted as a list of paramters with their
% default values and UPDATE as a list of new paramete values.
%
% VL_OVERRIDE(..., 'Warn') prints a warning message whenever: (i)
% UPDATE has a field not found in CONFIG, or (ii) non-leaf values of
% CONFIG are overwritten.
%
% VL_OVERRIDE(..., 'Skip') skips fields of UPDATE that are not found
% in CONFIG instead of copying them.
%
% VL_OVERRIDE(..., 'CaseI') matches field names in a
% case-insensitive manner.
%
% Remark::
% Fields are copied at the deepest possible level. For instance,
% if CONFIG has fields A.B.C1=1 and A.B.C2=2, and if UPDATE is the
% structure A.B.C1=3, then VL_OVERRIDE() returns a strucuture with
% fields A.B.C1=3, A.B.C2=2. By contrast, if UPDATE is the
% structure A.B=4, then the field A.B is copied, and VL_OVERRIDE()
% returns the structure A.B=4 (specifying 'Warn' would warn about
% the fact that the substructure B.C1, B.C2 is being deleted).
%
% Remark::
% Two fields are matched if they correspond exactly. Specifically,
% two fileds A(IA).(FA) and B(IA).FB of two struct arrays A and B
% match if, and only if, (i) A and B have the same dimensions,
% (ii) IA == IB, and (iii) FA == FB.
%
% See also: VL_ARGPARSE(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
warn = false ;
skip = false ;
err = false ;
casei = false ;
if length(varargin) == 1 & ~ischar(varargin{1})
% legacy
warn = 1 ;
end
if ~warn & length(varargin) > 0
for i=1:length(varargin)
switch lower(varargin{i})
case 'warn'
warn = true ;
case 'skip'
skip = true ;
case 'err'
err = true ;
case 'argparse'
argparse = true ;
case 'casei'
casei = true ;
otherwise
error(sprintf('Unknown option ''%s''.',varargin{i})) ;
end
end
end
% if CONFIG is not a struct array just copy UPDATE verbatim
if ~isstruct(config)
config = update ;
return ;
end
% if CONFIG is a struct array but UPDATE is not, no match can be
% established and we simply copy UPDATE verbatim
if ~isstruct(update)
config = update ;
return ;
end
% if CONFIG and UPDATE are both struct arrays, but have different
% dimensions then nom atch can be established and we simply copy
% UPDATE verbatim
if numel(update) ~= numel(config)
config = update ;
return ;
end
% if CONFIG and UPDATE are both struct arrays of the same
% dimension, we override recursively each field
for idx=1:numel(update)
fields = fieldnames(update) ;
for i = 1:length(fields)
updateFieldName = fields{i} ;
if casei
configFieldName = findFieldI(config, updateFieldName) ;
else
configFieldName = findField(config, updateFieldName) ;
end
if ~isempty(configFieldName)
config(idx).(configFieldName) = ...
vl_override(config(idx).(configFieldName), ...
update(idx).(updateFieldName)) ;
else
if warn
warning(sprintf('copied field ''%s'' which is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
if err
error(sprintf('The field ''%s'' is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
if skip
if warn
warning(sprintf('skipping field ''%s'' which is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
continue ;
end
config(idx).(updateFieldName) = update(idx).(updateFieldName) ;
end
end
end
% --------------------------------------------------------------------
function field = findFieldI(S, matchField)
% --------------------------------------------------------------------
field = '' ;
fieldNames = fieldnames(S) ;
for fi=1:length(fieldNames)
if strcmpi(fieldNames{fi}, matchField)
field = fieldNames{fi} ;
end
end
% --------------------------------------------------------------------
function field = findField(S, matchField)
% --------------------------------------------------------------------
field = '' ;
fieldNames = fieldnames(S) ;
for fi=1:length(fieldNames)
if strcmp(fieldNames{fi}, matchField)
field = fieldNames{fi} ;
end
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_quickvis.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/quickshift/vl_quickvis.m
| 3,696 |
utf_8
|
27f199dad4c5b9c192a5dd3abc59f9da
|
function [Iedge dists map gaps] = vl_quickvis(I, ratio, kernelsize, maxdist, maxcuts)
% VL_QUICKVIS Create an edge image from a Quickshift segmentation.
% IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) creates an edge
% stability image from a Quickshift segmentation. RATIO controls the tradeoff
% between color consistency and spatial consistency (See VL_QUICKSEG) and
% KERNELSIZE controls the bandwidth of the density estimator (See VL_QUICKSEG,
% VL_QUICKSHIFT). MAXDIST is the maximum distance between neighbors which
% increase the density.
%
% VL_QUICKVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at
% most MAXCUTS segmentations. The edges between regions in each of these
% segmentations are labeled in IEDGE, where the label corresponds to the
% largest DIST which preserves the edge.
%
% [IEDGE,DISTS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) also
% returns the DIST thresholds that were chosen.
%
% IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, DISTS) will use the DISTS
% specified
%
% [IEDGE,DISTS,MAP,GAPS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS)
% also returns the MAP and GAPS from VL_QUICKSHIFT.
%
% See Also: VL_QUICKSHIFT(), VL_QUICKSEG(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin == 4
dists = maxdist;
maxdist = max(dists);
[Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist);
else
[Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist);
dists = unique(floor(gaps(:)));
dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh
if length(dists) > maxcuts
ind = round(linspace(1,length(dists), maxcuts));
dists = dists(ind);
end
end
[Iedge dists] = mapvis(map, gaps, dists);
function [Iedge dists] = mapvis(map, gaps, maxdist, maxcuts)
% MAPVIS Create an edge image from a Quickshift segmentation.
% IEDGE = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) creates an edge
% stability image from a Quickshift segmentation. MAXDIST is the maximum
% distance between neighbors which increase the density.
%
% MAPVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at most
% MAXCUTS segmentations. The edges between regions in each of these
% segmentations are labeled in IEDGE, where the label corresponds to the
% largest DIST which preserves the edge.
%
% [IEDGE,DISTS] = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) also returns the DIST
% thresholds that were chosen.
%
% IEDGE = MAPVIS(MAP, GAPS, DISTS) will use the DISTS specified
%
% See Also: VL_QUICKVIS, VL_QUICKSHIFT, VL_QUICKSEG
if nargin == 3
dists = maxdist;
maxdist = max(dists);
else
dists = unique(floor(gaps(:)));
dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh
% throw away min region size instead of maxdist?
ind = find(dists < maxdist);
dists = dists(ind);
if length(dists) > maxcuts
ind = round(linspace(1,length(dists), maxcuts));
dists = dists(ind);
end
end
Iedge = zeros(size(map));
for i = 1:length(dists)
s = find(gaps >= dists(i));
mapdist = map;
mapdist(s) = s;
[mapped labels] = vl_flatmap(mapdist);
fprintf('%d/%d %d regions\n', i, length(dists), length(unique(mapped)))
borders = getborders(mapped);
Iedge(borders) = dists(i);
%Iedge(borders) = Iedge(borders) + 1;
%Iedge(borders) = i;
end
%%%%%%%%% GETBORDERS
function borders = getborders(map)
dx = conv2(map, [-1 1], 'same');
dy = conv2(map, [-1 1]', 'same');
borders = find(dx ~= 0 | dy ~= 0);
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_demo_aib.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/demo/vl_demo_aib.m
| 2,928 |
utf_8
|
590c6db09451ea608d87bfd094662cac
|
function vl_demo_aib
% VL_DEMO_AIB Test Agglomerative Information Bottleneck (AIB)
D = 4 ;
K = 20 ;
randn('state',0) ;
rand('state',0) ;
X1 = randn(2,300) ; X1(1,:) = X1(1,:) + 2 ;
X2 = randn(2,300) ; X2(1,:) = X2(1,:) - 2 ;
X3 = randn(2,300) ; X3(2,:) = X3(2,:) + 2 ;
figure(1) ; clf ; hold on ;
vl_plotframe(X1,'color','r') ;
vl_plotframe(X2,'color','g') ;
vl_plotframe(X3,'color','b') ;
axis equal ;
xlim([-4 4]);
ylim([-4 4]);
axis off ;
rectangle('position',D*[-1 -1 2 2])
vl_demo_print('aib_basic_data', .6) ;
C = 1:K*K ;
Pcx = zeros(3,K*K) ;
f1 = quantize(X1,D,K) ;
f2 = quantize(X2,D,K) ;
f3 = quantize(X3,D,K) ;
Pcx(1,:) = vl_binsum(Pcx(1,:), ones(size(f1)), f1) ;
Pcx(2,:) = vl_binsum(Pcx(2,:), ones(size(f2)), f2) ;
Pcx(3,:) = vl_binsum(Pcx(3,:), ones(size(f3)), f3) ;
Pcx = Pcx / sum(Pcx(:)) ;
[parents, cost] = vl_aib(Pcx) ;
cutsize = [K*K, 10, 3, 2, 1] ;
for i=1:length(cutsize)
[cut,map,short] = vl_aibcut(parents, cutsize(i)) ;
parents_cut(short > 0) = parents(short(short > 0)) ;
C = short(1:K*K+1) ; [drop1,drop2,C] = unique(C) ;
figure(i+1) ; clf ;
plotquantization(D,K,C) ; hold on ;
%plottree(D,K,parents_cut) ;
axis equal ;
axis off ;
title(sprintf('%d clusters', cutsize(i))) ;
vl_demo_print(sprintf('aib_basic_clust_%d',i),.6) ;
end
% --------------------------------------------------------------------
function f = quantize(X,D,K)
% --------------------------------------------------------------------
d = 2*D / K ;
j = round((X(1,:) + D) / d) ;
i = round((X(2,:) + D) / d) ;
j = max(min(j,K),1) ;
i = max(min(i,K),1) ;
f = sub2ind([K K],i,j) ;
% --------------------------------------------------------------------
function [i,j] = plotquantization(D,K,C)
% --------------------------------------------------------------------
hold on ;
cl = [[.3 .3 .3] ; .5*hsv(max(C)-1)+.5] ;
d = 2*D / K ;
for i=0:K-1
for j=0:K-1
patch(d*(j+[0 1 1 0])-D, ...
d*(i+[0 0 1 1])-D, ...
cl(C(j*K+i+1),:)) ;
end
end
% --------------------------------------------------------------------
function h = plottree(D,K,parents)
% --------------------------------------------------------------------
d = 2*D / K ;
C = zeros(2,2*K*K-1)+NaN ;
N = zeros(1,2*K*K-1) ;
for i=0:K-1
for j=0:K-1
C(:,j*K+i+1) = [d*j-D; d*i-D]+d/2 ;
N(:,j*K+i+1) = 1 ;
end
end
for i=1:length(parents)
p = parents(i) ;
if p==0, continue ; end;
if all(isnan(C(:,i))), continue; end
if all(isnan(C(:,p)))
C(:,p) = C(:,i) / N(i) ;
else
C(:,p) = C(:,p) + C(:,i) / N(i) ;
end
N(p) = N(p) + 1 ;
end
C(1,:) = C(1,:) ./ N ;
C(2,:) = C(2,:) ./ N ;
xt = zeros(3, 2*length(parents)-1)+NaN ;
yt = zeros(3, 2*length(parents)-1)+NaN ;
for i=1:length(parents)
p = parents(i) ;
if p==0, continue ; end;
xt(1,i) = C(1,i) ; xt(2,i) = C(1,p) ;
yt(1,i) = C(2,i) ; yt(2,i) = C(2,p) ;
end
h=line(xt(:),yt(:),'linestyle','-','marker','.','linewidth',3) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_demo_alldist.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/demo/vl_demo_alldist.m
| 5,460 |
utf_8
|
6d008a64d93445b9d7199b55d58db7eb
|
function vl_demo_alldist
%
numRepetitions = 3 ;
numDimensions = 1000 ;
numSamplesRange = [300] ;
settingsRange = {{'alldist2', 'double', 'l2', }, ...
{'alldist', 'double', 'l2', 'nosimd'}, ...
{'alldist', 'double', 'l2' }, ...
{'alldist2', 'single', 'l2', }, ...
{'alldist', 'single', 'l2', 'nosimd'}, ...
{'alldist', 'single', 'l2' }, ...
{'alldist2', 'double', 'l1', }, ...
{'alldist', 'double', 'l1', 'nosimd'}, ...
{'alldist', 'double', 'l1' }, ...
{'alldist2', 'single', 'l1', }, ...
{'alldist', 'single', 'l1', 'nosimd'}, ...
{'alldist', 'single', 'l1' }, ...
{'alldist2', 'double', 'chi2', }, ...
{'alldist', 'double', 'chi2', 'nosimd'}, ...
{'alldist', 'double', 'chi2' }, ...
{'alldist2', 'single', 'chi2', }, ...
{'alldist', 'single', 'chi2', 'nosimd'}, ...
{'alldist', 'single', 'chi2' }, ...
{'alldist2', 'double', 'hell', }, ...
{'alldist', 'double', 'hell', 'nosimd'}, ...
{'alldist', 'double', 'hell' }, ...
{'alldist2', 'single', 'hell', }, ...
{'alldist', 'single', 'hell', 'nosimd'}, ...
{'alldist', 'single', 'hell' }, ...
{'alldist2', 'double', 'kl2', }, ...
{'alldist', 'double', 'kl2', 'nosimd'}, ...
{'alldist', 'double', 'kl2' }, ...
{'alldist2', 'single', 'kl2', }, ...
{'alldist', 'single', 'kl2', 'nosimd'}, ...
{'alldist', 'single', 'kl2' }, ...
{'alldist2', 'double', 'kl1', }, ...
{'alldist', 'double', 'kl1', 'nosimd'}, ...
{'alldist', 'double', 'kl1' }, ...
{'alldist2', 'single', 'kl1', }, ...
{'alldist', 'single', 'kl1', 'nosimd'}, ...
{'alldist', 'single', 'kl1' }, ...
{'alldist2', 'double', 'kchi2', }, ...
{'alldist', 'double', 'kchi2', 'nosimd'}, ...
{'alldist', 'double', 'kchi2' }, ...
{'alldist2', 'single', 'kchi2', }, ...
{'alldist', 'single', 'kchi2', 'nosimd'}, ...
{'alldist', 'single', 'kchi2' }, ...
{'alldist2', 'double', 'khell', }, ...
{'alldist', 'double', 'khell', 'nosimd'}, ...
{'alldist', 'double', 'khell' }, ...
{'alldist2', 'single', 'khell', }, ...
{'alldist', 'single', 'khell', 'nosimd'}, ...
{'alldist', 'single', 'khell' }, ...
} ;
%settingsRange = settingsRange(end-5:end) ;
styles = {} ;
for marker={'x','+','.','*','o'}
for color={'r','g','b','k','y'}
styles{end+1} = {'color', char(color), 'marker', char(marker)} ;
end
end
for ni=1:length(numSamplesRange)
for ti=1:length(settingsRange)
tocs = [] ;
for ri=1:numRepetitions
rand('state',ri) ;
randn('state',ri) ;
numSamples = numSamplesRange(ni) ;
settings = settingsRange{ti} ;
[tocs(end+1), D] = run_experiment(numDimensions, ...
numSamples, ...
settings) ;
end
means(ni,ti) = mean(tocs) ;
stds(ni,ti) = std(tocs) ;
if mod(ti-1,3) == 0
D0 = D ;
else
err = max(abs(D(:)-D0(:))) ;
fprintf('err %f\n', err) ;
if err > 1, keyboard ; end
end
end
end
if 0
figure(1) ; clf ; hold on ;
numStyles = length(styles) ;
for ti=1:length(settingsRange)
si = mod(ti - 1, numStyles) + 1 ;
h(ti) = plot(numSamplesRange, means(:,ti), styles{si}{:}) ;
leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ;
errorbar(numSamplesRange, means(:,ti), stds(:,ti), 'linestyle', 'none') ;
end
end
for ti=1:length(settingsRange)
leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ;
end
figure(1) ; clf ;
barh(means(end,:)) ;
set(gca,'ytick', 1:length(leg), 'yticklabel', leg,'ydir','reverse') ;
xlabel('Time [s]') ;
function [elaps, D] = run_experiment(numDimensions, numSamples, settings)
distType = 'l2' ;
algType = 'alldist' ;
classType = 'double' ;
useSimd = true ;
for si=1:length(settings)
arg = settings{si} ;
switch arg
case {'l1', 'l2', 'chi2', 'hell', 'kl2', 'kl1', 'kchi2', 'khell'}
distType = arg ;
case {'alldist', 'alldist2'}
algType = arg ;
case {'single', 'double'}
classType = arg ;
case 'simd'
useSimd = true ;
case 'nosimd'
useSimd = false ;
otherwise
assert(false) ;
end
end
X = rand(numDimensions, numSamples) ;
X(X < .3) = 0 ;
switch classType
case 'double'
case 'single'
X = single(X) ;
end
vl_simdctrl(double(useSimd)) ;
switch algType
case 'alldist'
tic ; D = vl_alldist(X, distType) ; elaps = toc ;
case 'alldist2'
tic ; D = vl_alldist2(X, distType) ; elaps = toc ;
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_demo_ikmeans.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/demo/vl_demo_ikmeans.m
| 774 |
utf_8
|
17ff0bb7259d390fb4f91ea937ba7de0
|
function vl_demo_ikmeans()
% VL_DEMO_IKMEANS
numData = 10000 ;
dimension = 2 ;
data = uint8(255*rand(dimension,numData)) ;
numClusters = 3^3 ;
[centers, assignments] = vl_ikmeans(data, numClusters);
figure(1) ; clf ; axis off ;
plotClusters(data, centers, assignments) ;
vl_demo_print('ikmeans_2d',0.6);
[tree, assignments] = vl_hikmeans(data,3,numClusters) ;
figure(2) ; clf ; axis off ;
plotClusters(data, [], [4 2 1] * double(assignments)) ;
vl_demo_print('hikmeans_2d',0.6);
function plotClusters(data, centers, assignments)
hold on ;
cc=jet(double(max(assignments(:))));
for i=1:max(assignments(:))
plot(data(1,assignments == i),data(2,assignments == i),'.','color',cc(i,:));
end
if ~isempty(centers)
plot(centers(1,:),centers(2,:),'k.','MarkerSize',20)
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_demo_svm.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/demo/vl_demo_svm.m
| 1,235 |
utf_8
|
7cf6b3504e4fc2cbd10ff3fec6e331a7
|
% VL_DEMO_SVM Demo: SVM: 2D linear learning
function vl_demo_svm
y=[];X=[];
% Load training data X and their labels y
load('vl_demo_svm_data.mat')
Xp = X(:,y==1);
Xn = X(:,y==-1);
figure
plot(Xn(1,:),Xn(2,:),'*r')
hold on
plot(Xp(1,:),Xp(2,:),'*b')
axis equal ;
vl_demo_print('svm_training') ;
% Parameters
lambda = 0.01 ; % Regularization parameter
maxIter = 1000 ; % Maximum number of iterations
energy = [] ;
% Diagnostic function
function diagnostics(svm)
energy = [energy [svm.objective ; svm.dualObjective ; svm.dualityGap ] ] ;
end
% Training the SVM
energy = [] ;
[w b info] = vl_svmtrain(X, y, lambda,...
'MaxNumIterations',maxIter,...
'DiagnosticFunction',@diagnostics,...
'DiagnosticFrequency',1)
% Visualisation
eq = [num2str(w(1)) '*x+' num2str(w(2)) '*y+' num2str(b)];
line = ezplot(eq, [-0.9 0.9 -0.9 0.9]);
set(line, 'Color', [0 0.8 0],'linewidth', 2);
vl_demo_print('svm_training_result') ;
figure
hold on
plot(energy(1,:),'--b') ;
plot(energy(2,:),'-.g') ;
plot(energy(3,:),'r') ;
legend('Primal objective','Dual objective','Duality gap')
xlabel('Diagnostics iteration')
ylabel('Energy')
vl_demo_print('svm_energy') ;
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_demo_kdtree_sift.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/demo/vl_demo_kdtree_sift.m
| 6,832 |
utf_8
|
e676f80ac330a351f0110533c6ebba89
|
function vl_demo_kdtree_sift
% VL_DEMO_KDTREE_SIFT
% Demonstrates the use of a kd-tree forest to match SIFT
% features. If FLANN is present, this function runs a comparison
% against it.
% AUTORIGHS
rand('state',0) ;
randn('state',0);
do_median = 0 ;
do_mean = 1 ;
% try to setup flann
if ~exist('flann_search', 'file')
if exist(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab'))
addpath(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) ;
end
end
do_flann = exist('nearest_neighbors') == 3 ;
if ~do_flann
warning('FLANN not found. Comparison disabled.') ;
end
maxNumComparisonsRange = [1 10 50 100 200 300 400] ;
numTreesRange = [1 2 5 10] ;
% get data (SIFT features)
im1 = imread(fullfile(vl_root, 'data', 'roofs1.jpg')) ;
im2 = imread(fullfile(vl_root, 'data', 'roofs2.jpg')) ;
im1 = single(rgb2gray(im1)) ;
im2 = single(rgb2gray(im2)) ;
[f1,d1] = vl_sift(im1,'firstoctave',-1,'floatdescriptors','verbose') ;
[f2,d2] = vl_sift(im2,'firstoctave',-1,'floatdescriptors','verbose') ;
% add some noise to make matches unique
d1 = single(d1) + rand(size(d1)) ;
d2 = single(d2) + rand(size(d2)) ;
% match exhaustively to get the ground truth
elapsedDirect = tic ;
D = vl_alldist(d1,d2) ;
[drop, best] = min(D, [], 1) ;
elapsedDirect = toc(elapsedDirect) ;
for ti=1:length(numTreesRange)
for vi=1:length(maxNumComparisonsRange)
v = maxNumComparisonsRange(vi) ;
t = numTreesRange(ti) ;
if do_median
tic ;
kdtree = vl_kdtreebuild(d1, ...
'verbose', ...
'thresholdmethod', 'median', ...
'numtrees', t) ;
[i, d] = vl_kdtreequery(kdtree, d1, d2, ...
'verbose', ...
'maxcomparisons',v) ;
elapsedKD_median(vi,ti) = toc ;
errors_median(vi,ti) = sum(double(i) ~= best) / length(best) ;
errorsD_median(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
if do_mean
tic ;
kdtree = vl_kdtreebuild(d1, ...
'verbose', ...
'thresholdmethod', 'mean', ...
'numtrees', t) ;
%kdtree = readflann(kdtree, '/tmp/flann.txt') ;
%checkx(kdtree, d1, 1, 1) ;
[i, d] = vl_kdtreequery(kdtree, d1, d2, ...
'verbose', ...
'maxcomparisons', v) ;
elapsedKD_mean(vi,ti) = toc ;
errors_mean(vi,ti) = sum(double(i) ~= best) / length(best) ;
errorsD_mean(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
if do_flann
tic ;
[i, d] = flann_search(d1, d2, 1, struct('algorithm','kdtree', ...
'trees', t, ...
'checks', v));
ifla = i ;
elapsedKD_flann(vi,ti) = toc;
errors_flann(vi,ti) = sum(i ~= best) / length(best) ;
errorsD_flann(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
end
end
figure(1) ; clf ;
leg = {} ;
hnd = [] ;
sty = {{'color','r'},{'color','g'},...
{'color','b'},{'color','c'},...
{'color','k'}} ;
for ti=1:length(numTreesRange)
s = sty{mod(ti,length(sty))+1} ;
if do_median
h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errors_median(:,ti),'-*',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h1 ;
end
if do_mean
h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errors_mean(:,ti), '-o',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h2 ;
end
if do_flann
h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errors_flann(:,ti), '+--',s{:}) ; hold on ;
leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h3 ;
end
end
set([hnd], 'linewidth', 2) ;
xlabel('speedup over linear search (log times)') ;
ylabel('percentage of incorrect matches (%)') ;
h=legend(hnd, leg{:}, 'location', 'southeast') ;
set(h,'fontsize',8) ;
grid on ;
axis square ;
vl_demo_print('kdtree_sift_incorrect',.6) ;
figure(2) ; clf ;
leg = {} ;
hnd = [] ;
for ti=1:length(numTreesRange)
s = sty{mod(ti,length(sty))+1} ;
if do_median
h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errorsD_median(:,ti),'*-',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h1 ;
end
if do_mean
h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errorsD_mean(:,ti), 'o-',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h2 ;
end
if do_flann
h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errorsD_flann(:,ti), '+--',s{:}) ; hold on ;
leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h3 ;
end
end
set([hnd], 'linewidth', 2) ;
xlabel('speedup over linear search (log times)') ;
ylabel('relative overestimation of minmium distannce (%)') ;
h=legend(hnd, leg{:}, 'location', 'southeast') ;
set(h,'fontsize',8) ;
grid on ;
axis square ;
vl_demo_print('kdtree_sift_distortion',.6) ;
% --------------------------------------------------------------------
function checkx(kdtree, X, t, n, mib, mab)
% --------------------------------------------------------------------
if nargin <= 4
mib = -inf * ones(size(X,1),1) ;
mab = +inf * ones(size(X,1),1) ;
end
lc = kdtree.trees(t).nodes.lowerChild(n) ;
uc = kdtree.trees(t).nodes.upperChild(n) ;
if lc < 0
for i=-lc:-uc-1
di = kdtree.trees(t).dataIndex(i) ;
if any(X(:,di) > mab)
error('a') ;
end
if any(X(:,di) < mib)
error('b') ;
end
end
return
end
i = kdtree.trees(t).nodes.splitDimension(n) ;
v = kdtree.trees(t).nodes.splitThreshold(n) ;
mab_ = mab ;
mab_(i) = min(mab(i), v) ;
checkx(kdtree, X, t, lc, mib, mab_) ;
mib_ = mib ;
mib_(i) = max(mib(i), v) ;
checkx(kdtree, X, t, uc, mib_, mab) ;
% --------------------------------------------------------------------
function kdtree = readflann(kdtree, path)
% --------------------------------------------------------------------
data = textread(path)' ;
for i=1:size(data,2)
nodeIds = data(1,:) ;
ni = find(nodeIds == data(1,i)) ;
if ~isnan(data(2,i))
% internal node
li = find(nodeIds == data(4,i)) ;
ri = find(nodeIds == data(5,i)) ;
kdtree.trees(1).nodes.lowerChild(ni) = int32(li) ;
kdtree.trees(1).nodes.upperChild(ni) = int32(ri) ;
kdtree.trees(1).nodes.splitThreshold(ni) = single(data(2,i)) ;
kdtree.trees(1).nodes.splitDimension(ni) = single(data(3,i)+1) ;
else
di = data(3,i) + 1 ;
kdtree.trees(1).nodes.lowerChild(ni) = int32(- di) ;
kdtree.trees(1).nodes.upperChild(ni) = int32(- di - 1) ;
end
kdtree.trees(1).dataIndex = uint32(1:kdtree.numData) ;
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_impattern.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/imop/vl_impattern.m
| 6,876 |
utf_8
|
1716a4d107f0186be3d11c647bc628ce
|
function im = vl_impattern(varargin)
% VL_IMPATTERN Generate an image from a stock pattern
% IM=VLPATTERN(NAME) returns an instance of the specified
% pattern. These stock patterns are useful for testing algoirthms.
%
% All generated patterns are returned as an image of class
% DOUBLE. Both gray-scale and colour images have range in [0,1].
%
% VL_IMPATTERN() without arguments shows a gallery of the stock
% patterns. The following patterns are supported:
%
% Wedge::
% The image of a wedge.
%
% Cone::
% The image of a cone.
%
% SmoothChecker::
% A checkerboard with Gaussian filtering on top. Use the
% option-value pair 'sigma', SIGMA to specify the standard
% deviation of the smoothing and the pair 'step', STEP to specfity
% the checker size in pixels.
%
% ThreeDotsSquare::
% A pattern with three small dots and two squares.
%
% UniformNoise::
% Random i.i.d. noise.
%
% Blobs:
% Gaussian blobs of various sizes and anisotropies.
%
% Blobs1:
% Gaussian blobs of various orientations and anisotropies.
%
% Blob:
% One Gaussian blob. Use the option-value pairs 'sigma',
% 'orientation', and 'anisotropy' to specify the respective
% parameters. 'sigma' is the scalar standard deviation of an
% isotropic blob (the image domain is the rectangle
% [-1,1]^2). 'orientation' is the clockwise rotation (as the Y
% axis points downards). 'anisotropy' (>= 1) is the ratio of the
% the largest over the smallest axis of the blob (the smallest
% axis length is set by 'sigma'). Set 'cut' to TRUE to cut half
% half of the blob.
%
% A stock image::
% Any of 'box', 'roofs1', 'roofs2', 'river1', 'river2', 'spotted'.
%
% All pattern accept a SIZE parameter [WIDTH,HEIGHT]. For all but
% the stock images, the default size is [128,128].
% Author: Andrea Vedaldi
% Copyright (C) 2012 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin > 0
pattern=varargin{1} ;
varargin=varargin(2:end) ;
else
pattern = 'gallery' ;
end
patterns = {'wedge','cone','smoothChecker','threeDotsSquare', ...
'blob', 'blobs', 'blobs1', ...
'box', 'roofs1', 'roofs2', 'river1', 'river2'} ;
% spooling
switch lower(pattern)
case 'wedge', im = wedge(varargin) ;
case 'cone', im = cone(varargin) ;
case 'smoothchecker', im = smoothChecker(varargin) ;
case 'threedotssquare', im = threeDotSquare(varargin) ;
case 'uniformnoise', im = uniformNoise(varargin) ;
case 'blob', im = blob(varargin) ;
case 'blobs', im = blobs(varargin) ;
case 'blobs1', im = blobs1(varargin) ;
case {'box','roofs1','roofs2','river1','river2','spots'}
im = stockImage(pattern, varargin) ;
case 'gallery'
clf ;
num = numel(patterns) ;
for p = 1:num
vl_tightsubplot(num,p,'box','outer') ;
imagesc(vl_impattern(patterns{p}),[0 1]) ;
axis image off ;
title(patterns{p}) ;
end
colormap gray ;
return ;
otherwise
error('Unknown patter ''%s''.', pattern) ;
end
if nargout == 0
clf ; imagesc(im) ; hold on ;
colormap gray ; axis image off ;
title(pattern) ;
clear im ;
end
function [u,v,opts,args] = commonOpts(args)
opts.size = [128 128] ;
[opts,args] = vl_argparse(opts, args) ;
ur = linspace(-1,1,opts.size(2)) ;
vr = linspace(-1,1,opts.size(1)) ;
[u,v] = meshgrid(ur,vr);
function im = wedge(args)
[u,v,opts,args] = commonOpts(args) ;
im = abs(u) + abs(v) > (1/4) ;
im(v < 0) = 0 ;
function im = cone(args)
[u,v,opts,args] = commonOpts(args) ;
im = sqrt(u.^2+v.^2) ;
im = im / max(im(:)) ;
function im = smoothChecker(args)
opts.size = [128 128] ;
opts.step = 16 ;
opts.sigma = 2 ;
opts = vl_argparse(opts, args) ;
[u,v] = meshgrid(0:opts.size(1)-1, 0:opts.size(2)-1) ;
im = xor((mod(u,opts.step*2) < opts.step),...
(mod(v,opts.step*2) < opts.step)) ;
im = double(im) ;
im = vl_imsmooth(im, opts.sigma) ;
function im = threeDotSquare(args)
[u,v,opts,args] = commonOpts(args) ;
im = ones(size(u)) ;
im(-2/3<u & u<2/3 & -2/3<v & v<2/3) = .75 ;
im(-1/3<u & u<1/3 & -1/3<v & v<1/3) = .50 ;
[drop,i] = min(abs(v(:,1))) ;
[drop,j1] = min(abs(u(1,:)-1/6)) ;
[drop,j2] = min(abs(u(1,:))) ;
[drop,j3] = min(abs(u(1,:)+1/6)) ;
im(i,j1) = 0 ;
im(i,j2) = 0 ;
im(i,j3) = 0 ;
function im = blobs(args)
[u,v,opts,args] = commonOpts(args) ;
im = zeros(size(u)) ;
num = 5 ;
square = 2 / num ;
sigma = square / 2 / 3 ;
scales = logspace(log10(0.5), log10(1), num) ;
skews = linspace(1,2,num) ;
for i=1:num
for j=1:num
cy = (i-1) * square + square/2 - 1;
cx = (j-1) * square + square/2 - 1;
A = sigma * diag([scales(i) scales(i)/skews(j)]) * [1 -1 ; 1 1] / sqrt(2) ;
C = inv(A'*A) ;
x = u - cx ;
y = v - cy ;
im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ;
end
end
im = im / max(im(:)) ;
function im = blob(args)
[u,v,opts,args] = commonOpts(args) ;
opts.sigma = 0.15 ;
opts.anisotropy = .5 ;
opts.orientation = 2/3 * pi ;
opts.cut = false ;
opts = vl_argparse(opts, args) ;
im = zeros(size(u)) ;
th = opts.orientation ;
R = [cos(th) -sin(th) ; sin(th) cos(th)] ;
A = opts.sigma * R * diag([opts.anisotropy 1]) ;
T = [0;0] ;
[x,y] = vl_waffine(inv(A),-inv(A)*T,u,v) ;
im = exp(-0.5 *(x.^2 + y.^2)) ;
if opts.cut
im = im .* double(x > 0) ;
end
function im = blobs1(args)
[u,v,opts,args] = commonOpts(args) ;
opts.number = 5 ;
opts.sigma = [] ;
opts = vl_argparse(opts, args) ;
im = zeros(size(u)) ;
square = 2 / opts.number ;
num = opts.number ;
if isempty(opts.sigma)
sigma = 1/6 * square ;
else
sigma = opts.sigma * square ;
end
rotations = linspace(0,pi,num+1) ;
rotations(end) = [] ;
skews = linspace(1,2,num) ;
for i=1:num
for j=1:num
cy = (i-1) * square + square/2 - 1;
cx = (j-1) * square + square/2 - 1;
th = rotations(i) ;
R = [cos(th) -sin(th); sin(th) cos(th)] ;
A = sigma * R * diag([1 1/skews(j)]) ;
C = inv(A*A') ;
x = u - cx ;
y = v - cy ;
im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ;
end
end
im = im / max(im(:)) ;
function im = uniformNoise(args)
opts.size = [128 128] ;
opts.seed = 1 ;
opts = vl_argparse(opts, args) ;
state = vl_twister('state') ;
vl_twister('state',opts.seed) ;
im = vl_twister(opts.size([2 1])) ;
vl_twister('state',state) ;
function im = stockImage(pattern,args)
opts.size = [] ;
opts = vl_argparse(opts, args) ;
switch pattern
case 'river1', path='river1.jpg' ;
case 'river2', path='river2.jpg' ;
case 'roofs1', path='roofs1.jpg' ;
case 'roofs2', path='roofs2.jpg' ;
case 'box', path='box.pgm' ;
case 'spots', path='spots.jpg' ;
end
im = imread(fullfile(vl_root,'data',path)) ;
im = im2double(im) ;
if ~isempty(opts.size)
im = imresize(im, opts.size) ;
im = max(im,0) ;
im = min(im,1) ;
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_tpsu.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/imop/vl_tpsu.m
| 1,755 |
utf_8
|
09f36e1a707c069b375eb2817d0e5f13
|
function [U,dU,delta]=vl_tpsu(X,Y)
% VL_TPSU Compute the U matrix of a thin-plate spline transformation
% U=VL_TPSU(X,Y) returns the matrix
%
% [ U(|X(:,1) - Y(:,1)|) ... U(|X(:,1) - Y(:,N)|) ]
% [ ]
% [ U(|X(:,M) - Y(:,1)|) ... U(|X(:,M) - Y(:,N)|) ]
%
% where X is a 2xM matrix and Y a 2xN matrix of points and U(r) is
% the opposite -r^2 log(r^2) of the radial basis function of the
% thin plate spline specified by X and Y.
%
% [U,dU]=vl_tpsu(x,y) returns the derivatives of the columns of U with
% respect to the parameters Y. The derivatives are arranged in a
% Mx2xN array, one layer per column of U.
%
% See also: VL_TPS(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if exist('tpsumx')
U = tpsumx(X,Y) ;
else
M=size(X,2) ;
N=size(Y,2) ;
% Faster than repmat, but still fairly slow
r2 = ...
(X( ones(N,1), :)' - Y( ones(1,M), :)).^2 + ...
(X( 1+ones(N,1), :)' - Y(1+ones(1,M), :)).^2 ;
U = - rb(r2) ;
end
if nargout > 1
M=size(X,2) ;
N=size(Y,2) ;
dx = X( ones(N,1), :)' - Y( ones(1,M), :) ;
dy = X(1+ones(N,1), :)' - Y(1+ones(1,M), :) ;
r2 = (dx.^2 + dy.^2) ;
r = sqrt(r2) ;
coeff = drb(r)./(r+eps) ;
dU = reshape( [coeff .* dx ; coeff .* dy], M, 2, N) ;
end
% The radial basis function
function y = rb(r2)
y = zeros(size(r2)) ;
sel = find(r2 ~= 0) ;
y(sel) = - r2(sel) .* log(r2(sel)) ;
% The derivative of the radial basis function
function y = drb(r)
y = zeros(size(r)) ;
sel = find(r ~= 0) ;
y(sel) = - 4 * r(sel) .* log(r(sel)) - 2 * r(sel) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_xyz2lab.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/imop/vl_xyz2lab.m
| 1,570 |
utf_8
|
09f95a6f9ae19c22486ec1157357f0e3
|
function J=vl_xyz2lab(I,il)
% VL_XYZ2LAB Convert XYZ color space to LAB
% J = VL_XYZ2LAB(I) converts the image from XYZ format to LAB format.
%
% VL_XYZ2LAB(I,IL) uses one of the illuminants A, B, C, E, D50, D55,
% D65, D75, D93. The default illuminatn is E.
%
% See also: VL_XYZ2LUV(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin < 2
il='E' ;
end
switch lower(il)
case 'a'
xw = 0.4476 ;
yw = 0.4074 ;
case 'b'
xw = 0.3324 ;
yw = 0.3474 ;
case 'c'
xw = 0.3101 ;
yw = 0.3162 ;
case 'e'
xw = 1/3 ;
yw = 1/3 ;
case 'd50'
xw = 0.3457 ;
yw = 0.3585 ;
case 'd55'
xw = 0.3324 ;
yw = 0.3474 ;
case 'd65'
xw = 0.312713 ;
yw = 0.329016 ;
case 'd75'
xw = 0.299 ;
yw = 0.3149 ;
case 'd93'
xw = 0.2848 ;
yw = 0.2932 ;
end
J=zeros(size(I)) ;
% Reference white
Yw = 1.0 ;
Xw = xw/yw ;
Zw = (1-xw-yw)/yw * Yw ;
% XYZ components
X = I(:,:,1) ;
Y = I(:,:,2) ;
Z = I(:,:,3) ;
x = X/Xw ;
y = Y/Yw ;
z = Z/Zw ;
L = 116 * f(y) - 16 ;
a = 500*(f(x) - f(y)) ;
b = 200*(f(y) - f(z)) ;
J = cat(3,L,a,b) ;
% --------------------------------------------------------------------
function b=f(a)
% --------------------------------------------------------------------
sp = find(a > 0.00856) ;
sm = find(a <= 0.00856) ;
k = 903.3 ;
b=zeros(size(a)) ;
b(sp) = a(sp).^(1/3) ;
b(sm) = (k*a(sm) + 16)/116 ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_gmm.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_gmm.m
| 1,332 |
utf_8
|
76782cae6c98781c6c38d4cbf5549d94
|
function results = vl_test_gmm(varargin)
% VL_TEST_GMM
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
vl_test_init ;
end
function s = setup()
randn('state',0) ;
s.X = randn(128, 1000) ;
end
function test_multithreading(s)
dataTypes = {'single','double'} ;
for dataType = dataTypes
conversion = str2func(char(dataType)) ;
X = conversion(s.X) ;
vl_twister('state',0) ;
vl_threads(0) ;
[means, covariances, priors, ll, posteriors] = ...
vl_gmm(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Initialization', 'rand') ;
vl_twister('state',0) ;
vl_threads(1) ;
[means_, covariances_, priors_, ll_, posteriors_] = ...
vl_gmm(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Initialization', 'rand') ;
vl_assert_almost_equal(means, means_, 1e-2) ;
vl_assert_almost_equal(covariances, covariances_, 1e-2) ;
vl_assert_almost_equal(priors, priors_, 1e-2) ;
vl_assert_almost_equal(ll, ll_, 1e-2 * abs(ll)) ;
vl_assert_almost_equal(posteriors, posteriors_, 1e-2) ;
end
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_twister.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_twister.m
| 1,251 |
utf_8
|
2bfb5a30cbd6df6ac80c66b73f8646da
|
function results = vl_test_twister(varargin)
% VL_TEST_TWISTER
vl_test_init ;
function test_illegal_args()
vl_assert_exception(@() vl_twister(-1), 'vl:invalidArgument') ;
vl_assert_exception(@() vl_twister(1, -1), 'vl:invalidArgument') ;
vl_assert_exception(@() vl_twister([1, -1]), 'vl:invalidArgument') ;
function test_seed_by_scalar()
rand('twister',1) ; a = rand ;
vl_twister('state',1) ; b = vl_twister ;
vl_assert_equal(a,b,'seed by scalar + VL_TWISTER()') ;
function test_get_set_state()
rand('twister',1) ; a = rand('twister') ;
vl_twister('state',1) ; b = vl_twister('state') ;
vl_assert_equal(a,b,'read state') ;
a(1) = a(1) + 1 ;
vl_twister('state',a) ; b = vl_twister('state') ;
vl_assert_equal(a,b,'set state') ;
function test_multi_dimensions()
b = rand('twister') ;
rand('twister',b) ;
vl_twister('state',b) ;
a=rand([1 2 3 4 5]) ;
b=vl_twister([1 2 3 4 5]) ;
vl_assert_equal(a,b,'VL_TWISTER([M N P ...])') ;
function test_multi_multi_args()
rand('twister',1) ; a=rand(1, 2, 3, 4, 5) ;
vl_twister('state',1) ; b=vl_twister(1, 2, 3, 4, 5) ;
vl_assert_equal(a,b,'VL_TWISTER(M, N, P, ...)') ;
function test_square()
rand('twister',1) ; a=rand(10) ;
vl_twister('state',1) ; b=vl_twister(10) ;
vl_assert_equal(a,b,'VL_TWISTER(N)') ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_kdtree.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_kdtree.m
| 2,449 |
utf_8
|
9d7ad2b435a88c22084b38e5eb5f9eb9
|
function results = vl_test_kdtree(varargin)
% VL_TEST_KDTREE
vl_test_init ;
function s = setup()
randn('state',0) ;
s.X = single(randn(10, 1000)) ;
s.Q = single(randn(10, 10)) ;
function test_nearest(s)
for tmethod = {'median', 'mean'}
for type = {@single, @double}
conv = type{1} ;
tmethod = char(tmethod) ;
X = conv(s.X) ;
Q = conv(s.Q) ;
tree = vl_kdtreebuild(X,'ThresholdMethod', tmethod) ;
[nn, d2] = vl_kdtreequery(tree, X, Q) ;
D2 = vl_alldist2(X, Q, 'l2') ;
[d2_, nn_] = min(D2) ;
vl_assert_equal(...
nn,uint32(nn_),...
'incorrect nns: type=%s th. method=%s', func2str(conv), tmethod) ;
vl_assert_almost_equal(...
d2,d2_,...
'incorrect distances: type=%s th. method=%s', func2str(conv), tmethod) ;
end
end
function test_nearests(s)
numNeighbors = 7 ;
tree = vl_kdtreebuild(s.X) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
vl_assert_equal(nn,uint32(nn_)) ;
vl_assert_almost_equal(d2,d2_) ;
function test_ann(s)
vl_twister('state', 1) ;
numNeighbors = 7 ;
maxComparisons = numNeighbors * 50 ;
tree = vl_kdtreebuild(s.X) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors, ...
'maxComparisons', maxComparisons) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
for i=1:size(s.Q,2)
overlap = numel(intersect(nn(:,i), nn_(:,i))) / ...
numel(union(nn(:,i), nn_(:,i))) ;
assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ;
end
function test_ann_forest(s)
vl_twister('state', 1) ;
numNeighbors = 7 ;
maxComparisons = numNeighbors * 25 ;
numTrees = 5 ;
tree = vl_kdtreebuild(s.X, 'numTrees', 5) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors, ...
'maxComparisons', maxComparisons) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
for i=1:size(s.Q,2)
overlap = numel(intersect(nn(:,i), nn_(:,i))) / ...
numel(union(nn(:,i), nn_(:,i))) ;
assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ;
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_imwbackward.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_imwbackward.m
| 514 |
utf_8
|
33baa0784c8f6f785a2951d7f1b49199
|
function results = vl_test_imwbackward(varargin)
% VL_TEST_IMWBACKWARD
vl_test_init ;
function s = setup()
s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
function test_identity(s)
xr = 1:size(s.I,2) ;
yr = 1:size(s.I,1) ;
[x,y] = meshgrid(xr,yr) ;
vl_assert_almost_equal(s.I, vl_imwbackward(xr,yr,s.I,x,y)) ;
function test_invalid_args(s)
xr = 1:size(s.I,2) ;
yr = 1:size(s.I,1) ;
[x,y] = meshgrid(xr,yr) ;
vl_assert_exception(@() vl_imwbackward(xr,yr,single(s.I),x,y), 'vl:invalidArgument') ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_alphanum.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_alphanum.m
| 1,624 |
utf_8
|
2da2b768c2d0f86d699b8f31614aa424
|
function results = vl_test_alphanum(varargin)
% VL_TEST_ALPHANUM
vl_test_init ;
function s = setup()
s.strings = ...
{'1000X Radonius Maximus','10X Radonius','200X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','Allegia 50 Clasteron','Allegia 500 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 6R Clasteron','Alpha 100','Alpha 2','Alpha 200','Alpha 2A','Alpha 2A-8000','Alpha 2A-900','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 5000','Callisto Morphamax 600','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 700','Callisto Morphamax 7000','Xiph Xlater 10000','Xiph Xlater 2000','Xiph Xlater 300','Xiph Xlater 40','Xiph Xlater 5','Xiph Xlater 50','Xiph Xlater 500','Xiph Xlater 5000','Xiph Xlater 58'} ;
s.sortedStrings = ...
{'10X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','200X Radonius','1000X Radonius Maximus','Allegia 6R Clasteron','Allegia 50 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 500 Clasteron','Alpha 2','Alpha 2A','Alpha 2A-900','Alpha 2A-8000','Alpha 100','Alpha 200','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 600','Callisto Morphamax 700','Callisto Morphamax 5000','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 7000','Xiph Xlater 5','Xiph Xlater 40','Xiph Xlater 50','Xiph Xlater 58','Xiph Xlater 300','Xiph Xlater 500','Xiph Xlater 2000','Xiph Xlater 5000','Xiph Xlater 10000'} ;
function test_basic(s)
sorted = vl_alphanum(s.strings) ;
assert(isequal(sorted,s.sortedStrings)) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_printsize.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_printsize.m
| 1,447 |
utf_8
|
0f0b6437c648b7a2e1310900262bd765
|
function results = vl_test_printsize(varargin)
% VL_TEST_PRINTSIZE
vl_test_init ;
function s = setup()
s.fig = figure(1) ;
s.usletter = [8.5, 11] ; % inches
s.a4 = [8.26772, 11.6929] ;
clf(s.fig) ; plot(1:10) ;
function teardown(s)
close(s.fig) ;
function test_basic(s)
for sigma = [1 0.5 0.2]
vl_printsize(s.fig, sigma) ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), sigma*s.usletter(1), 1e-4) ;
vl_assert_almost_equal(pos(1), 0, 1e-4) ;
vl_assert_almost_equal(pos(3), sigma*s.usletter(1), 1e-4) ;
end
function test_papertype(s)
vl_printsize(s.fig, 1, 'papertype', 'a4') ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), s.a4(1), 1e-4) ;
function test_margin(s)
m = 0.5 ;
vl_printsize(s.fig, 1, 'margin', m) ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), s.usletter(1) * (1 + 2*m), 1e-4) ;
vl_assert_almost_equal(pos(1), s.usletter(1) * m, 1e-4) ;
function test_reference(s)
sigma = 1 ;
vl_printsize(s.fig, 1, 'reference', 'vertical') ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(2), sigma*s.usletter(2), 1e-4) ;
vl_assert_almost_equal(pos(2), 0, 1e-4) ;
vl_assert_almost_equal(pos(4), sigma*s.usletter(2), 1e-4) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_cummax.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_cummax.m
| 838 |
utf_8
|
5e98ee1681d4823f32ecc4feaa218611
|
function results = vl_test_cummax(varargin)
% VL_TEST_CUMMAX
vl_test_init ;
function test_basic()
vl_assert_almost_equal(...
vl_cummax(1), 1) ;
vl_assert_almost_equal(...
vl_cummax([1 2 3 4], 2), [1 2 3 4]) ;
function test_multidim()
a = [1 2 3 4 3 2 1] ;
b = [1 2 3 4 4 4 4] ;
for k=1:6
dims = ones(1,6) ;
dims(k) = numel(a) ;
a = reshape(a, dims) ;
b = reshape(b, dims) ;
vl_assert_almost_equal(...
vl_cummax(a, k), b) ;
end
function test_storage_classes()
types = {@double, @single, ...
@int32, @uint32, ...
@int16, @uint16, ...
@int8, @uint8} ;
if vl_matlabversion() > 71000
types = horzcat(types, {@int64, @uint64}) ;
end
for a = types
a = a{1} ;
for b = types
b = b{1} ;
vl_assert_almost_equal(...
vl_cummax(a(eye(3))), a(toeplitz([1 1 1], [1 0 0 ]))) ;
end
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_imintegral.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_imintegral.m
| 1,429 |
utf_8
|
4750f04ab0ac9fc4f55df2c8583e5498
|
function results = vl_test_imintegral(varargin)
% VL_TEST_IMINTEGRAL
vl_test_init ;
function state = setup()
state.I = ones(5,6) ;
state.correct = [ 1 2 3 4 5 6 ;
2 4 6 8 10 12 ;
3 6 9 12 15 18 ;
4 8 12 16 20 24 ;
5 10 15 20 25 30 ; ] ;
function test_matlab_equivalent(s)
vl_assert_equal(slow_imintegral(s.I), s.correct) ;
function test_basic(s)
vl_assert_equal(vl_imintegral(s.I), s.correct) ;
function test_multi_dimensional(s)
vl_assert_equal(vl_imintegral(repmat(s.I, [1 1 3])), ...
repmat(s.correct, [1 1 3])) ;
function test_random(s)
numTests = 50 ;
for i = 1:numTests
I = rand(5) ;
vl_assert_almost_equal(vl_imintegral(s.I), ...
slow_imintegral(s.I)) ;
end
function test_datatypes(s)
vl_assert_equal(single(vl_imintegral(s.I)), single(s.correct)) ;
vl_assert_equal(double(vl_imintegral(s.I)), double(s.correct)) ;
vl_assert_equal(uint32(vl_imintegral(s.I)), uint32(s.correct)) ;
vl_assert_equal(int32(vl_imintegral(s.I)), int32(s.correct)) ;
vl_assert_equal(int32(vl_imintegral(-s.I)), -int32(s.correct)) ;
function integral = slow_imintegral(I)
integral = zeros(size(I));
for k = 1:size(I,3)
for r = 1:size(I,1)
for c = 1:size(I,2)
integral(r,c,k) = sum(sum(I(1:r,1:c,k)));
end
end
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_sift.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_sift.m
| 1,318 |
utf_8
|
806c61f9db9f2ebb1d649c9bfcf3dc0a
|
function results = vl_test_sift(varargin)
% VL_TEST_SIFT
vl_test_init ;
function s = setup()
s.I = im2single(imread(fullfile(vl_root,'data','box.pgm'))) ;
[s.ubc.f, s.ubc.d] = ...
vl_ubcread(fullfile(vl_root,'data','box.sift')) ;
function test_ubc_descriptor(s)
err = [] ;
[f, d] = vl_sift(s.I,...
'firstoctave', -1, ...
'frames', s.ubc.f) ;
D2 = vl_alldist(f, s.ubc.f) ;
[drop, perm] = min(D2) ;
f = f(:,perm) ;
d = d(:,perm) ;
error = mean(sqrt(sum((single(s.ubc.d) - single(d)).^2))) ...
/ mean(sqrt(sum(single(s.ubc.d).^2))) ;
assert(error < 0.1, ...
'sift descriptor did not produce desctiptors similar to UBC ones') ;
function test_ubc_detector(s)
[f, d] = vl_sift(s.I,...
'firstoctave', -1, ...
'peakthresh', .01, ...
'edgethresh', 10) ;
s.ubc.f(4,:) = mod(s.ubc.f(4,:), 2*pi) ;
f(4,:) = mod(f(4,:), 2*pi) ;
% scale the components so that 1 pixel erro in x,y,z is equal to a
% 10-th of angle.
S = diag([1 1 1 20/pi]);
D2 = vl_alldist(S * s.ubc.f, S * f) ;
[d2,perm] = sort(min(D2)) ;
error = sqrt(d2) ;
quant80 = round(.8 * size(f,2)) ;
% check for less than one pixel error at 80% quantile
assert(error(quant80) < 1, ...
'sift detector did not produce enough keypoints similar to UBC ones') ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_binsum.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_binsum.m
| 1,377 |
utf_8
|
f07f0f29ba6afe0111c967ab0b353a9d
|
function results = vl_test_binsum(varargin)
% VL_TEST_BINSUM
vl_test_init ;
function test_three_args()
vl_assert_almost_equal(...
vl_binsum([0 0], 1, 2), [0 1]) ;
vl_assert_almost_equal(...
vl_binsum([1 7], -1, 1), [0 7]) ;
vl_assert_almost_equal(...
vl_binsum([1 7], -1, [1 2 2 2 2 2 2 2]), [0 0]) ;
function test_four_args()
vl_assert_almost_equal(...
vl_binsum(eye(3), [1 1 1], [1 2 3], 1), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), [1 1 1]', [1 2 3]', 2), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), 1, [1 2 3], 1), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), 1, [1 2 3]', 2), 2*eye(3)) ;
function test_3d_one()
Z = zeros(3,3,3) ;
B = 3*ones(3,1,3) ;
R = Z ; R(:,3,:) = 17 ;
vl_assert_almost_equal(...
vl_binsum(Z, 17, B, 2), R) ;
function test_3d_two()
Z = zeros(3,3,3) ;
B = 3*ones(3,3,1) ;
X = zeros(3,3,1) ; X(:,:,1) = 17 ;
R = Z ; R(:,:,3) = 17 ;
vl_assert_almost_equal(...
vl_binsum(Z, X, B, 3), R) ;
function test_storage_classes()
types = {@double, @single, ...
@int32, @uint32, ...
@int16, @uint16, ...
@int8, @uint8} ;
if vl_matlabversion() > 71000
types = horzcat(types, {@int64, @uint64}) ;
end
for a = types
a = a{1} ;
for b = types
b = b{1} ;
vl_assert_almost_equal(...
vl_binsum(a(eye(3)), a([1 1 1]), b([1 2 3]), 1), a(2*eye(3))) ;
end
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_lbp.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_lbp.m
| 892 |
utf_8
|
a79c0ce0c85e25c0b1657f3a0b499538
|
function results = vl_test_lbp(varargin)
% VL_TEST_TWISTER
vl_test_init ;
function test_unfiorm_lbps(s)
% enumerate the 56 uniform lbps
q = 0 ;
for i=0:7
for j=1:7
I = zeros(3) ;
p = mod(s.pixels - i + 8, 8) + 1 ;
I(p <= j) = 1 ;
f = vl_lbp(single(I), 3) ;
q = q + 1 ;
vl_assert_equal(find(f), q) ;
end
end
% constant lbps
I = [1 1 1 ; 1 0 1 ; 1 1 1] ;
f = vl_lbp(single(I), 3) ;
vl_assert_equal(find(f), 57) ;
I = [1 1 1 ; 1 1 1 ; 1 1 1] ;
f = vl_lbp(single(I), 3) ;
vl_assert_equal(find(f), 57) ;
% other lbps
I = [1 0 1 ; 0 0 0 ; 1 0 1] ;
f = vl_lbp(single(I), 3) ;
vl_assert_equal(find(f), 58) ;
function test_fliplr(s)
randn('state',0) ;
I = randn(256,256,1,'single') ;
f = vl_lbp(fliplr(I), 8) ;
f_ = vl_lbpfliplr(vl_lbp(I, 8)) ;
vl_assert_almost_equal(f,f_,1e-3) ;
function s = setup()
s.pixels = [5 6 7 ;
4 NaN 0 ;
3 2 1] ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_colsubset.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_colsubset.m
| 828 |
utf_8
|
be0c080007445b36333b863326fb0f15
|
function results = vl_test_colsubset(varargin)
% VL_TEST_COLSUBSET
vl_test_init ;
function s = setup()
s.x = [5 2 3 6 4 7 1 9 8 0] ;
function test_beginning(s)
vl_assert_equal(1:5, vl_colsubset(1:10, 5, 'beginning')) ;
vl_assert_equal(1:5, vl_colsubset(1:10, .5, 'beginning')) ;
function test_ending(s)
vl_assert_equal(6:10, vl_colsubset(1:10, 5, 'ending')) ;
vl_assert_equal(6:10, vl_colsubset(1:10, .5, 'ending')) ;
function test_largest(s)
vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, 5, 'largest')) ;
vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, .5, 'largest')) ;
function test_smallest(s)
vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, 5, 'smallest')) ;
vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, .5, 'smallest')) ;
function test_random(s)
assert(numel(intersect(s.x, vl_colsubset(s.x, 5, 'random'))) == 5) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_alldist.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_alldist.m
| 2,373 |
utf_8
|
9ea1a36c97fe715dfa2b8693876808ff
|
function results = vl_test_alldist(varargin)
% VL_TEST_ALLDIST
vl_test_init ;
function s = setup()
vl_twister('state', 0) ;
s.X = 3.1 * vl_twister(10,10) ;
s.Y = 4.7 * vl_twister(10,7) ;
function test_null_args(s)
vl_assert_equal(...
vl_alldist(zeros(15,12), zeros(15,0), 'kl2'), ...
zeros(12,0)) ;
vl_assert_equal(...
vl_alldist(zeros(15,0), zeros(15,0), 'kl2'), ...
zeros(0,0)) ;
vl_assert_equal(...
vl_alldist(zeros(15,0), zeros(15,12), 'kl2'), ...
zeros(0,12)) ;
vl_assert_equal(...
vl_alldist(zeros(0,15), zeros(0,12), 'kl2'), ...
zeros(15,12)) ;
function test_self(s)
vl_assert_almost_equal(...
vl_alldist(s.X, 'kl2'), ...
makedist(@(x,y) x*y, s.X, s.X), ...
1e-6) ;
function test_distances(s)
dists = {'chi2', 'l2', 'l1', 'hell', 'js', ...
'kchi2', 'kl2', 'kl1', 'khell', 'kjs'} ;
distsEquiv = { ...
@(x,y) (x-y)^2 / (x + y), ...
@(x,y) (x-y)^2, ...
@(x,y) abs(x-y), ...
@(x,y) (sqrt(x) - sqrt(y))^2, ...
@(x,y) x - x .* log2(1 + y/x) + y - y .* log2(1 + x/y), ...
@(x,y) 2 * (x*y) / (x + y), ...
@(x,y) x*y, ...
@(x,y) min(x,y), ...
@(x,y) sqrt(x.*y), ...
@(x,y) .5 * (x .* log2(1 + y/x) + y .* log2(1 + x/y))} ;
types = {'single', 'double'} ;
for simd = [0 1]
for d = 1:length(dists)
for t = 1:length(types)
vl_simdctrl(simd) ;
X = feval(str2func(types{t}), s.X) ;
Y = feval(str2func(types{t}), s.Y) ;
vl_assert_almost_equal(...
vl_alldist(X,Y,dists{d}), ...
makedist(distsEquiv{d},X,Y), ...
1e-4, ...
'alldist failed for dist=%s type=%s simd=%d', ...
dists{d}, ...
types{t}, ...
simd) ;
end
end
end
function test_distance_kernel_pairs(s)
dists = {'chi2', 'l2', 'l1', 'hell', 'js'} ;
for d = 1:length(dists)
dist = char(dists{d}) ;
X = s.X ;
Y = s.Y ;
ker = ['k' dist] ;
kxx = vl_alldist(X,X,ker) ;
kyy = vl_alldist(Y,Y,ker) ;
kxy = vl_alldist(X,Y,ker) ;
kxx = repmat(diag(kxx), 1, size(s.Y,2)) ;
kyy = repmat(diag(kyy), 1, size(s.X,1))' ;
d2 = vl_alldist(X,Y,dist) ;
vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ;
end
function D = makedist(cmp,X,Y)
[d,m] = size(X) ;
[d,n] = size(Y) ;
D = zeros(m,n) ;
for i = 1:m
for j = 1:n
acc = 0 ;
for k = 1:d
acc = acc + cmp(X(k,i),Y(k,j)) ;
end
D(i,j) = acc ;
end
end
conv = str2func(class(X)) ;
D = conv(D) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_ihashsum.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_ihashsum.m
| 581 |
utf_8
|
edc283062469af62056b0782b171f5fc
|
function results = vl_test_ihashsum(varargin)
% VL_TEST_IHASHSUM
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(round(16*rand(2,100))) ;
sel = find(all(s.data==0)) ;
s.data(1,sel)=1 ;
function test_hash(s)
D = size(s.data,1) ;
K = 5 ;
h = zeros(1,K,'uint32') ;
id = zeros(D,K,'uint8');
next = zeros(1,K,'uint32') ;
[h,id,next] = vl_ihashsum(h,id,next,K,s.data) ;
sel = vl_ihashfind(id,next,K,s.data) ;
count = double(h(sel)) ;
[drop,i,j] = unique(s.data','rows') ;
for k=1:size(s.data,2)
count_(k) = sum(j == j(k)) ;
end
vl_assert_equal(count,count_) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_grad.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_grad.m
| 434 |
utf_8
|
4d03eb33a6a4f68659f868da95930ffb
|
function results = vl_test_grad(varargin)
% VL_TEST_GRAD
vl_test_init ;
function s = setup()
s.I = rand(150,253) ;
s.I_small = rand(2,2) ;
function test_equiv(s)
vl_assert_equal(gradient(s.I), vl_grad(s.I)) ;
function test_equiv_small(s)
vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;
function test_equiv_forward(s)
Ix = diff(s.I,2,1) ;
Iy = diff(s.I,2,1) ;
vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_whistc.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_whistc.m
| 1,384 |
utf_8
|
81c446d35c82957659840ab2a579ec2c
|
function results = vl_test_whistc(varargin)
% VL_TEST_WHISTC
vl_test_init ;
function test_acc()
x = ones(1, 10) ;
e = 1 ;
o = 1:10 ;
vl_assert_equal(vl_whistc(x, o, e), 55) ;
function test_basic()
x = 1:10 ;
e = 1:10 ;
o = ones(1, 10) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
x = linspace(-1,11,100) ;
o = ones(size(x)) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
function test_multidim()
x = rand(10, 20, 30) ;
e = linspace(0,1,10) ;
o = ones(size(x)) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;
vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;
vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;
function test_nan()
x = rand(10, 20, 30) ;
e = linspace(0,1,10) ;
o = ones(size(x)) ;
x(1:7:end) = NaN ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;
vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;
vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;
function test_no_edges()
x = rand(10, 20, 30) ;
o = ones(size(x)) ;
vl_assert_equal(histc(1, []), vl_whistc(1, 1, [])) ;
vl_assert_equal(histc(x, []), vl_whistc(x, o, [])) ;
vl_assert_equal(histc(x, [], 1), vl_whistc(x, o, [], 1)) ;
vl_assert_equal(histc(x, [], 2), vl_whistc(x, o, [], 2)) ;
vl_assert_equal(histc(x, [], 3), vl_whistc(x, o, [], 3)) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_roc.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_roc.m
| 1,019 |
utf_8
|
9b2ae71c9dc3eda0fc54c65d55054d0c
|
function results = vl_test_roc(varargin)
% VL_TEST_ROC
vl_test_init ;
function s = setup()
s.scores0 = [5 4 3 2 1] ;
s.scores1 = [5 3 4 2 1] ;
s.labels = [1 1 -1 -1 -1] ;
function test_perfect_tptn(s)
[tpr,tnr] = vl_roc(s.labels,s.scores0) ;
vl_assert_almost_equal(tpr, [0 1 2 2 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 3 3 2 1 0] / 3) ;
function test_perfect_metrics(s)
[tpr,tnr,info] = vl_roc(s.labels,s.scores0) ;
vl_assert_almost_equal(info.eer, 0) ;
vl_assert_almost_equal(info.auc, 1) ;
function test_swap1_tptn(s)
[tpr,tnr] = vl_roc(s.labels,s.scores1) ;
vl_assert_almost_equal(tpr, [0 1 1 2 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 3 2 2 1 0] / 3) ;
function test_swap1_tptn_stable(s)
[tpr,tnr] = vl_roc(s.labels,s.scores1,'stable',true) ;
vl_assert_almost_equal(tpr, [1 2 1 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 2 2 1 0] / 3) ;
function test_swap1_metrics(s)
[tpr,tnr,info] = vl_roc(s.labels,s.scores1) ;
vl_assert_almost_equal(info.eer, 1/3) ;
vl_assert_almost_equal(info.auc, 1 - 1/(2*3)) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_dsift.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_dsift.m
| 2,048 |
utf_8
|
fbbfb16d5a21936c1862d9551f657ccc
|
function results = vl_test_dsift(varargin)
% VL_TEST_DSIFT
vl_test_init ;
function s = setup()
I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
s.I = rgb2gray(single(I)) ;
function test_fast_slow(s)
binSize = 4 ; % bin size in pixels
magnif = 3 ; % bin size / keypoint scale
scale = binSize / magnif ;
windowSize = 5 ;
[f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors') ;
[f_, d_] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors', ...
'fast') ;
error = std(d_(:) - d(:)) / std(d(:)) ;
assert(error < 0.1, 'dsift fast approximation not close') ;
function test_sift(s)
binSize = 4 ; % bin size in pixels
magnif = 3 ; % bin size / keypoint scale
scale = binSize / magnif ;
windowSizeRange = [1 1.2 5] ;
for wi = 1:length(windowSizeRange)
windowSize = windowSizeRange(wi) ;
[f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors') ;
numKeys = size(f, 2) ;
f_ = [f ; ones(1, numKeys) * scale ; zeros(1, numKeys)] ;
[f_, d_] = vl_sift(s.I, ...
'magnif', magnif, ...
'frames', f_, ...
'firstoctave', -1, ...
'levels', 5, ...
'floatdescriptors', ...
'windowsize', windowSize) ;
error = std(d_(:) - d(:)) / std(d(:)) ;
assert(error < 0.1, 'dsift and sift equivalence') ;
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_alldist2.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_alldist2.m
| 2,284 |
utf_8
|
89a787e3d83516653ae8d99c808b9d67
|
function results = vl_test_alldist2(varargin)
% VL_TEST_ALLDIST
vl_test_init ;
% TODO: test integer classes
function s = setup()
vl_twister('state', 0) ;
s.X = 3.1 * vl_twister(10,10) ;
s.Y = 4.7 * vl_twister(10,7) ;
function test_null_args(s)
vl_assert_equal(...
vl_alldist2(zeros(15,12), zeros(15,0), 'kl2'), ...
zeros(12,0)) ;
vl_assert_equal(...
vl_alldist2(zeros(15,0), zeros(15,0), 'kl2'), ...
zeros(0,0)) ;
vl_assert_equal(...
vl_alldist2(zeros(15,0), zeros(15,12), 'kl2'), ...
zeros(0,12)) ;
vl_assert_equal(...
vl_alldist2(zeros(0,15), zeros(0,12), 'kl2'), ...
zeros(15,12)) ;
function test_self(s)
vl_assert_almost_equal(...
vl_alldist2(s.X, 'kl2'), ...
makedist(@(x,y) x*y, s.X, s.X), ...
1e-6) ;
function test_distances(s)
dists = {'chi2', 'l2', 'l1', 'hell', ...
'kchi2', 'kl2', 'kl1', 'khell'} ;
distsEquiv = { ...
@(x,y) (x-y)^2 / (x + y), ...
@(x,y) (x-y)^2, ...
@(x,y) abs(x-y), ...
@(x,y) (sqrt(x) - sqrt(y))^2, ...
@(x,y) 2 * (x*y) / (x + y), ...
@(x,y) x*y, ...
@(x,y) min(x,y), ...
@(x,y) sqrt(x.*y)};
types = {'single', 'double', 'sparse'} ;
for simd = [0 1]
for d = 1:length(dists)
for t = 1:length(types)
vl_simdctrl(simd) ;
X = feval(str2func(types{t}), s.X) ;
Y = feval(str2func(types{t}), s.Y) ;
a = vl_alldist2(X,Y,dists{d}) ;
b = makedist(distsEquiv{d},X,Y) ;
vl_assert_almost_equal(a,b, ...
1e-4, ...
'alldist failed for dist=%s type=%s simd=%d', ...
dists{d}, ...
types{t}, ...
simd) ;
end
end
end
function test_distance_kernel_pairs(s)
dists = {'chi2', 'l2', 'l1', 'hell'} ;
for d = 1:length(dists)
dist = char(dists{d}) ;
X = s.X ;
Y = s.Y ;
ker = ['k' dist] ;
kxx = vl_alldist2(X,X,ker) ;
kyy = vl_alldist2(Y,Y,ker) ;
kxy = vl_alldist2(X,Y,ker) ;
kxx = repmat(diag(kxx), 1, size(s.Y,2)) ;
kyy = repmat(diag(kyy), 1, size(s.X,1))' ;
d2 = vl_alldist2(X,Y,dist) ;
vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ;
end
function D = makedist(cmp,X,Y)
[d,m] = size(X) ;
[d,n] = size(Y) ;
D = zeros(m,n) ;
for i = 1:m
for j = 1:n
acc = 0 ;
for k = 1:d
acc = acc + cmp(X(k,i),Y(k,j)) ;
end
D(i,j) = acc ;
end
end
conv = str2func(class(X)) ;
D = conv(D) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_fisher.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_fisher.m
| 2,097 |
utf_8
|
c9afd9ab635bd412cbf8be3c2d235f6b
|
function results = vl_test_fisher(varargin)
% VL_TEST_FISHER
vl_test_init ;
function s = setup()
randn('state',0) ;
dimension = 5 ;
numData = 21 ;
numComponents = 3 ;
s.x = randn(dimension,numData) ;
s.mu = randn(dimension,numComponents) ;
s.sigma2 = ones(dimension,numComponents) ;
s.prior = ones(1,numComponents) ;
s.prior = s.prior / sum(s.prior) ;
function test_basic(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior) ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_norm(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'normalized') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_sqrt(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'squareroot') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_improved(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_fast(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior, true) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved', 'fast') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function enc = simple_fisher(x, mu, sigma2, pri, fast)
if nargin < 5, fast = false ; end
sigma = sqrt(sigma2) ;
for k = 1:size(mu,2)
delta{k} = bsxfun(@times, bsxfun(@minus, x, mu(:,k)), 1./sigma(:,k)) ;
q(k,:) = log(pri(k)) - 0.5 * sum(log(sigma2(:,k))) - 0.5 * sum(delta{k}.^2,1) ;
end
q = exp(bsxfun(@minus, q, max(q,[],1))) ;
q = bsxfun(@times, q, 1 ./ sum(q,1)) ;
n = size(x,2) ;
if fast
[~,i] = max(q) ;
q = zeros(size(q)) ;
q(sub2ind(size(q),i,1:n)) = 1 ;
end
for k = 1:size(mu,2)
u{k} = delta{k} * q(k,:)' / n / sqrt(pri(k)) ;
v{k} = (delta{k}.^2 - 1) * q(k,:)' / n / sqrt(2*pri(k)) ;
end
enc = cat(1, u{:}, v{:}) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_imsmooth.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_imsmooth.m
| 1,837 |
utf_8
|
718235242cad61c9804ba5e881c22f59
|
function results = vl_test_imsmooth(varargin)
% VL_TEST_IMSMOOTH
vl_test_init ;
function s = setup()
I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
I = max(min(vl_imdown(I),1),0) ;
s.I = single(I) ;
function test_pad_by_continuity(s)
% Convolving a constant signal padded with continuity does not change
% the signal.
I = ones(3) ;
for ker = {'triangular', 'gaussian'}
ker = char(ker) ;
J = vl_imsmooth(I, 2, ...
'kernel', ker, ...
'padding', 'continuity') ;
vl_assert_almost_equal(J, I, 1e-4, ...
'padding by continutiy with kernel = %s', ker) ;
end
function test_kernels(s)
for ker = {'triangular', 'gaussian'}
ker = char(ker) ;
for type = {@single, @double}
for simd = [0 1]
for sigma = [1 2 7]
for step = [1 2 3]
vl_simdctrl(simd) ;
conv = type{1} ;
g = equivalent_kernel(ker, sigma) ;
J = vl_imsmooth(conv(s.I), sigma, ...
'kernel', ker, ...
'padding', 'zero', ...
'subsample', step) ;
J_ = conv(convolve(s.I, g, step)) ;
vl_assert_almost_equal(J, J_, 1e-4, ...
'kernel=%s sigma=%f step=%d simd=%d', ...
ker, sigma, step, simd) ;
end
end
end
end
end
function g = equivalent_kernel(ker, sigma)
switch ker
case 'gaussian'
W = ceil(4*sigma) ;
g = exp(-.5*((-W:W)/(sigma+eps)).^2) ;
case 'triangular'
W = max(round(sigma),1) ;
g = W - abs(-W+1:W-1) ;
end
g = g / sum(g) ;
function I = convolve(I, g, step)
if strcmp(class(I),'single')
g = single(g) ;
else
g = double(g) ;
end
for k=1:size(I,3)
I(:,:,k) = conv2(g,g,I(:,:,k),'same');
end
I = I(1:step:end,1:step:end,:) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_svmtrain.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_svmtrain.m
| 4,277 |
utf_8
|
071b7c66191a22e8236fda16752b27aa
|
function results = vl_test_svmtrain(varargin)
% VL_TEST_SVMTRAIN
vl_test_init ;
end
function s = setup()
randn('state',0) ;
Np = 10 ;
Nn = 10 ;
xp = diag([1 3])*randn(2, Np) ;
xn = diag([1 3])*randn(2, Nn) ;
xp(1,:) = xp(1,:) + 2 + 1 ;
xn(1,:) = xn(1,:) - 2 + 1 ;
s.x = [xp xn] ;
s.y = [ones(1,Np) -ones(1,Nn)] ;
s.lambda = 0.01 ;
s.biasMultiplier = 10 ;
if 0
figure(1) ; clf;
vl_plotframe(xp, 'g') ; hold on ;
vl_plotframe(xn, 'r') ;
axis equal ; grid on ;
end
% Run LibSVM as an accuate solver to compare results with. Note that
% LibSVM optimizes a slightly different cost function due to the way
% the bias is handled.
% [s.w, s.b] = accurate_solver(s.x, s.y, s.lambda, s.biasMultiplier) ;
s.w = [1.180762951236242; 0.098366470721632] ;
s.b = -1.540018443946204 ;
s.obj = obj(s, s.w, s.b) ;
end
function test_sgd_basic(s)
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
[w b info] = vl_svmtrain(s.x, s.y, s.lambda, ...
'Solver', 'sgd', ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', 1/s.biasMultiplier, ...
'MaxNumIterations', 1e5, ...
'Epsilon', 1e-3) ;
% there are no absolute guarantees on the objective gap, but
% the heuristic SGD uses as stopping criterion seems reasonable
% within a factor 10 at least.
o = obj(s, w, b) ;
gap = o - s.obj ;
vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ;
assert(gap <= 1e-2) ;
end
end
function test_sdca_basic(s)
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
[w b info] = vl_svmtrain(s.x, s.y, s.lambda, ...
'Solver', 'sdca', ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e5, ...
'Epsilon', 1e-3) ;
% the gap with the accurate solver cannot be
% greater than the duality gap.
o = obj(s, w, b) ;
gap = o - s.obj ;
vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ;
assert(gap <= 1e-3) ;
end
end
function test_weights(s)
for algo = {'sgd', 'sdca'}
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
numRepeats = 10 ;
pos = find(s.y > 0) ;
neg = find(s.y < 0) ;
weights = ones(1, numel(s.y)) ;
weights(pos) = numRepeats ;
% simulate weighting by repeating positives
[w b info] = vl_svmtrain(...
s.x(:, [repmat(pos,1,numRepeats) neg]), ...
s.y(:, [repmat(pos,1,numRepeats) neg]), ...
s.lambda / (numel(pos) *numRepeats + numel(neg)) / (numel(pos) + numel(neg)), ...
'Solver', 'sdca', ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e6, ...
'Epsilon', 1e-4) ;
% apply weigthing
[w_ b_ info_] = vl_svmtrain(...
s.x, ...
s.y, ...
s.lambda, ...
'Solver', char(algo), ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e6, ...
'Epsilon', 1e-4, ...
'Weights', weights) ;
vl_assert_almost_equal(conv([w; b]), conv([w_; b_]), 0.05) ;
end
end
end
function test_homkermap(s)
for solver = {'sgd', 'sdca'}
for conv = {@single,@double}
conv = conv{1} ;
dataset = vl_svmdataset(conv(s.x), 'homkermap', struct('order',1)) ;
vl_twister('state',0) ;
[w_ b_] = vl_svmtrain(dataset, s.y, s.lambda) ;
x_hom = vl_homkermap(conv(s.x), 1) ;
vl_twister('state',0) ;
[w b] = vl_svmtrain(x_hom, s.y, s.lambda) ;
vl_assert_almost_equal([w; b],[w_; b_], 1e-7) ;
end
end
end
function [w,b] = accurate_solver(X, y, lambda, biasMultiplier)
addpath opt/libsvm/matlab/
N = size(X,2) ;
model = svmtrain(y', [(1:N)' X'*X], sprintf(' -c %f -t 4 -e 0.00001 ', 1/(lambda*N))) ;
w = X(:,model.SVs) * model.sv_coef ;
b = - model.rho ;
format long ;
disp('model w:')
disp(w)
disp('bias b:')
disp(b)
end
function o = obj(s, w, b)
o = (sum(w.*w) + b*b) * s.lambda / 2 + mean(max(0, 1 - s.y .* (w'*s.x + b))) ;
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_phow.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_phow.m
| 549 |
utf_8
|
f761a3bb218af855986263c67b2da411
|
function results = vl_test_phow(varargin)
% VL_TEST_PHOPW
vl_test_init ;
function s = setup()
s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
s.I = single(s.I) ;
function test_gray(s)
[f,d] = vl_phow(s.I, 'color', 'gray') ;
assert(size(d,1) == 128) ;
function test_rgb(s)
[f,d] = vl_phow(s.I, 'color', 'rgb') ;
assert(size(d,1) == 128*3) ;
function test_hsv(s)
[f,d] = vl_phow(s.I, 'color', 'hsv') ;
assert(size(d,1) == 128*3) ;
function test_opponent(s)
[f,d] = vl_phow(s.I, 'color', 'opponent') ;
assert(size(d,1) == 128*3) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_kmeans.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_kmeans.m
| 3,632 |
utf_8
|
0e1d6f4f8101c8982a0e743e0980c65a
|
function results = vl_test_kmeans(varargin)
% VL_TEST_KMEANS
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
vl_test_init ;
function s = setup()
randn('state',0) ;
s.X = randn(128, 100) ;
function test_basic(s)
[centers, assignments, en] = vl_kmeans(s.X, 10, 'NumRepetitions', 10) ;
[centers_, assignments_, en_] = simpleKMeans(s.X, 10) ;
assert(en_ <= 1.1 * en, 'vl_kmeans did not optimize enough') ;
function test_algorithms(s)
distances = {'l1', 'l2'} ;
dataTypes = {'single','double'} ;
for dataType = dataTypes
for distance = distances
distance = char(distance) ;
conversion = str2func(char(dataType)) ;
X = conversion(s.X) ;
vl_twister('state',0) ;
[centers, assignments, en] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'Lloyd', ...
'Distance', distance) ;
vl_twister('state',0) ;
[centers_, assignments_, en_] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'Elkan', ...
'Distance', distance) ;
vl_twister('state',0) ;
[centers__, assignments__, en__] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'ANN', ...
'Distance', distance, ...
'NumTrees', 3, ...
'MaxNumComparisons',0) ;
vl_assert_almost_equal(centers, centers_, 1e-5) ;
vl_assert_almost_equal(assignments, assignments_, 1e-5) ;
vl_assert_almost_equal(en, en_, 1e-4) ;
vl_assert_almost_equal(centers, centers__, 1e-5) ;
vl_assert_almost_equal(assignments, assignments__, 1e-5) ;
vl_assert_almost_equal(en, en__, 1e-4) ;
vl_assert_almost_equal(centers_, centers__, 1e-5) ;
vl_assert_almost_equal(assignments_, assignments__, 1e-5) ;
vl_assert_almost_equal(en_, en__, 1e-4) ;
end
end
function test_patterns(s)
distances = {'l1', 'l2'} ;
dataTypes = {'single','double'} ;
for dataType = dataTypes
for distance = distances
distance = char(distance) ;
conversion = str2func(char(dataType)) ;
data = [1 1 0 0 ;
1 0 1 0] ;
data = conversion(data) ;
[centers, assignments, en] = vl_kmeans(data, 4, ...
'NumRepetitions', 100, ...
'Distance', distance) ;
assert(isempty(setdiff(data', centers', 'rows'))) ;
end
end
function [centers, assignments, en] = simpleKMeans(X, numCenters)
[dimension, numData] = size(X) ;
centers = randn(dimension, numCenters) ;
for iter = 1:10
[dists, assignments] = min(vl_alldist(centers, X)) ;
en = sum(dists) ;
centers = [zeros(dimension, numCenters) ; ones(1, numCenters)] ;
centers = vl_binsum(centers, ...
[X ; ones(1,numData)], ...
repmat(assignments, dimension+1, 1), 2) ;
centers = centers(1:end-1, :) ./ repmat(centers(end,:), dimension, 1) ;
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_hikmeans.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_hikmeans.m
| 463 |
utf_8
|
dc3b493646e66316184e86ff4e6138ab
|
function results = vl_test_hikmeans(varargin)
% VL_TEST_IKMEANS
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(rand(2,1000) * 255) ;
function test_basic(s)
[tree, assign] = vl_hikmeans(s.data,3,100) ;
assign_ = vl_hikmeanspush(tree, s.data) ;
vl_assert_equal(assign,assign_) ;
function test_elkan(s)
[tree, assign] = vl_hikmeans(s.data,3,100,'method','elkan') ;
assign_ = vl_hikmeanspush(tree, s.data) ;
vl_assert_equal(assign,assign_) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_aib.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_aib.m
| 1,277 |
utf_8
|
78978ae54e7ebe991d136336ba4bf9c6
|
function results = vl_test_aib(varargin)
% VL_TEST_AIB
vl_test_init ;
function s = setup()
s = [] ;
function test_basic(s)
Pcx = [.3 .3 0 0
0 0 .2 .2] ;
% This results in the AIB tree
%
% 1 - \
% 5 - \
% 2 - / \
% - 7
% 3 - \ /
% 6 - /
% 4 - /
%
% coded by the map [5 5 6 6 7 1] (1 denotes the root).
[parents,cost] = vl_aib(Pcx) ;
vl_assert_equal(parents, [5 5 6 6 7 7 1]) ;
vl_assert_almost_equal(mi(Pcx)*[1 1 1], cost(1:3), 1e-3) ;
[cut,map,short] = vl_aibcut(parents,2) ;
vl_assert_equal(cut, [5 6]) ;
vl_assert_equal(map, [1 1 2 2 1 2 0]) ;
vl_assert_equal(short, [5 5 6 6 5 6 7]) ;
function test_cluster_null(s)
Pcx = [.5 .5 0 0
0 0 0 0] ;
% This results in the AIB tree
%
% 1 - \
% 5
% 2 - /
%
% 3 x
%
% 4 x
%
% If ClusterNull is specified, the values 3 and 4
% which have zero probability are merged first
%
% 1 ----------\
% 7
% 2 ----- \ /
% 6-/
% 3 -\ /
% 5 -/
% 4 -/
parents1 = vl_aib(Pcx) ;
parents2 = vl_aib(Pcx,'ClusterNull') ;
vl_assert_equal(parents1, [5 5 0 0 1 0 0]) ;
vl_assert_equal(parents2(3), parents2(4)) ;
function x = mi(P)
% mutual information
P1 = sum(P,1) ;
P2 = sum(P,2) ;
x = sum(sum(P .* log(max(P,1e-10) ./ (P2*P1)))) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_plotbox.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_plotbox.m
| 414 |
utf_8
|
aa06ce4932a213fb933bbede6072b029
|
function results = vl_test_plotbox(varargin)
% VL_TEST_PLOTBOX
vl_test_init ;
function test_basic(s)
figure(1) ; clf ;
vl_plotbox([-1 -1 1 1]') ;
xlim([-2 2]) ;
ylim([-2 2]) ;
close(1) ;
function test_multiple(s)
figure(1) ; clf ;
randn('state', 0) ;
vl_plotbox(randn(4,10)) ;
close(1) ;
function test_style(s)
figure(1) ; clf ;
randn('state', 0) ;
vl_plotbox(randn(4,10), 'r-.', 'LineWidth', 3) ;
close(1) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_imarray.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_imarray.m
| 795 |
utf_8
|
c5e6a5aa8c2e63e248814f5bd89832a8
|
function results = vl_test_imarray(varargin)
% VL_TEST_IMARRAY
vl_test_init ;
function test_movie_rgb(s)
A = rand(23,15,3,4) ;
B = vl_imarray(A,'movie',true) ;
function test_movie_indexed(s)
cmap = get(0,'DefaultFigureColormap') ;
A = uint8(size(cmap,1)*rand(23,15,4)) ;
A = min(A,size(cmap,1)-1) ;
B = vl_imarray(A,'movie',true) ;
function test_movie_gray_indexed(s)
A = uint8(255*rand(23,15,4)) ;
B = vl_imarray(A,'movie',true,'cmap',gray(256)) ;
for k=1:size(A,3)
vl_assert_equal(squeeze(A(:,:,k)), ...
frame2im(B(k))) ;
end
function test_basic(s)
M = 3 ;
N = 4 ;
width = 32 ;
height = 15 ;
for i=1:M
for j=1:N
A{i,j} = rand(width,height) ;
end
end
A1 = A';
A1 = cat(3,A1{:}) ;
A2 = cell2mat(A) ;
B = vl_imarray(A1, 'layout', [M N]) ;
vl_assert_equal(A2,B) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_homkermap.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_homkermap.m
| 1,903 |
utf_8
|
c157052bf4213793a961bde1f73fb307
|
function results = vl_test_homkermap(varargin)
% VL_TEST_HOMKERMAP
vl_test_init ;
function check_ker(ker, n, window, period)
args = {n, ker, 'window', window} ;
if nargin > 3
args = {args{:}, 'period', period} ;
end
x = [-1 -.5 0 .5 1] ;
y = linspace(0,2,100) ;
for conv = {@single, @double}
x = feval(conv{1}, x) ;
y = feval(conv{1}, y) ;
sx = sign(x) ;
sy = sign(y) ;
psix = vl_homkermap(x, args{:}) ;
psiy = vl_homkermap(y, args{:}) ;
k = vl_alldist(psix,psiy,'kl2') ;
k_ = (sx'*sy) .* vl_alldist(sx.*x,sy.*y,ker) ;
vl_assert_almost_equal(k, k_, 2e-2) ;
end
function test_uniform_kchi2(), check_ker('kchi2', 3, 'uniform', 15) ;
function test_uniform_kjs(), check_ker('kjs', 3, 'uniform', 15) ;
function test_uniform_kl1(), check_ker('kl1', 29, 'uniform', 15) ;
function test_rect_kchi2(), check_ker('kchi2', 3, 'rectangular', 15) ;
function test_rect_kjs(), check_ker('kjs', 3, 'rectangular', 15) ;
function test_rect_kl1(), check_ker('kl1', 29, 'rectangular', 10) ;
function test_auto_uniform_kchi2(),check_ker('kchi2', 3, 'uniform') ;
function test_auto_uniform_kjs(), check_ker('kjs', 3, 'uniform') ;
function test_auto_uniform_kl1(), check_ker('kl1', 25, 'uniform') ;
function test_auto_rect_kchi2(), check_ker('kchi2', 3, 'rectangular') ;
function test_auto_rect_kjs(), check_ker('kjs', 3, 'rectangular') ;
function test_auto_rect_kl1(), check_ker('kl1', 25, 'rectangular') ;
function test_gamma()
x = linspace(0,1,20) ;
for gamma = linspace(.2,2,10)
k = vl_alldist(x, 'kchi2') .* (x'*x + 1e-12).^((gamma-1)/2) ;
psix = vl_homkermap(x, 3, 'kchi2', 'gamma', gamma) ;
assert(norm(k - psix'*psix) < 1e-2) ;
end
function test_negative()
x = linspace(-1,1,20) ;
k = vl_alldist(abs(x), 'kchi2') .* (sign(x)'*sign(x)) ;
psix = vl_homkermap(x, 3, 'kchi2') ;
assert(norm(k - psix'*psix) < 1e-2) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_slic.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_slic.m
| 200 |
utf_8
|
12a6465e3ef5b4bcfd7303cd8a9229d4
|
function results = vl_test_slic(varargin)
% VL_TEST_SLIC
vl_test_init ;
function s = setup()
s.im = im2single(vl_impattern('roofs1')) ;
function test_slic(s)
segmentation = vl_slic(s.im, 10, 0.1) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_ikmeans.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_ikmeans.m
| 466 |
utf_8
|
1ee2f647ac0035ed0d704a0cd615b040
|
function results = vl_test_ikmeans(varargin)
% VL_TEST_IKMEANS
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(rand(2,1000) * 255) ;
function test_basic(s)
[centers, assign] = vl_ikmeans(s.data,100) ;
assign_ = vl_ikmeanspush(s.data, centers) ;
vl_assert_equal(assign,assign_) ;
function test_elkan(s)
[centers, assign] = vl_ikmeans(s.data,100,'method','elkan') ;
assign_ = vl_ikmeanspush(s.data, centers) ;
vl_assert_equal(assign,assign_) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_mser.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_mser.m
| 242 |
utf_8
|
1ad33563b0c86542a2978ee94e0f4a39
|
function results = vl_test_mser(varargin)
% VL_TEST_MSER
vl_test_init ;
function s = setup()
s.im = im2uint8(rgb2gray(vl_impattern('roofs1'))) ;
function test_mser(s)
[regions,frames] = vl_mser(s.im) ;
mask = vl_erfill(s.im, regions(1)) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_inthist.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_inthist.m
| 811 |
utf_8
|
459027d0c54d8f197563a02ab66ef45d
|
function results = vl_test_inthist(varargin)
% VL_TEST_INTHIST
vl_test_init ;
function s = setup()
rand('state',0) ;
s.labels = uint32(8*rand(123, 76, 3)) ;
function test_basic(s)
l = 10 ;
hist = vl_inthist(s.labels, 'numlabels', l) ;
hist_ = inthist_slow(s.labels, l) ;
vl_assert_equal(double(hist),hist_) ;
function test_sample(s)
rand('state',0) ;
boxes = 10 * rand(4,20) + .5 ;
boxes(3:4,:) = boxes(3:4,:) + boxes(1:2,:) ;
boxes = min(boxes, 10) ;
boxes = uint32(boxes) ;
inthist = vl_inthist(s.labels) ;
hist = vl_sampleinthist(inthist, boxes) ;
function hist = inthist_slow(labels, numLabels)
m = size(labels,1) ;
n = size(labels,2) ;
l = numLabels ;
b = zeros(m*n,l) ;
b = vl_binsum(b, 1, reshape(labels,m*n,[]), 2) ;
b = reshape(b,m,n,l) ;
for k=1:l
hist(:,:,k) = cumsum(cumsum(b(:,:,k)')') ;
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_imdisttf.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_imdisttf.m
| 1,885 |
utf_8
|
ae921197988abeb984cbcdf9eaf80e77
|
function results = vl_test_imdisttf(varargin)
% VL_TEST_DISTTF
vl_test_init ;
function test_basic()
for conv = {@single, @double}
conv = conv{1} ;
I = conv([0 0 0 ; 0 -2 0 ; 0 0 0]) ;
D = vl_imdisttf(I);
assert(isequal(D, conv(- [0 1 0 ; 1 2 1 ; 0 1 0]))) ;
I(2,2) = -3 ;
[D,map] = vl_imdisttf(I) ;
assert(isequal(D, conv(-1 - [0 1 0 ; 1 2 1 ; 0 1 0]))) ;
assert(isequal(map, 5 * ones(3))) ;
end
function test_1x1()
assert(isequal(1, vl_imdisttf(1))) ;
function test_rand()
I = rand(13,31) ;
for t=1:4
param = [rand randn rand randn] ;
[D0,map0] = imdisttf_equiv(I,param) ;
[D,map] = vl_imdisttf(I,param) ;
vl_assert_almost_equal(D,D0,1e-10)
assert(isequal(map,map0)) ;
end
function test_param()
I = zeros(3,4) ;
I(1,1) = -1 ;
[D,map] = vl_imdisttf(I,[1 0 1 0]);
assert(isequal(-[1 0 0 0 ;
0 0 0 0 ;
0 0 0 0 ;], D)) ;
D0 = -[1 .9 .6 .1 ;
0 0 0 0 ;
0 0 0 0 ;] ;
[D,map] = vl_imdisttf(I,[.1 0 1 0]);
vl_assert_almost_equal(D,D0,1e-10);
D0 = -[1 .9 .6 .1 ;
.9 .8 .5 0 ;
.6 .5 .2 0 ;] ;
[D,map] = vl_imdisttf(I,[.1 0 .1 0]);
vl_assert_almost_equal(D,D0,1e-10);
D0 = -[.9 1 .9 .6 ;
.8 .9 .8 .5 ;
.5 .6 .5 .2 ; ] ;
[D,map] = vl_imdisttf(I,[.1 1 .1 0]);
vl_assert_almost_equal(D,D0,1e-10);
function test_special()
I = rand(13,31) -.5 ;
D = vl_imdisttf(I, [0 0 1e5 0]) ;
vl_assert_almost_equal(D(:,1),min(I,[],2),1e-10);
D = vl_imdisttf(I, [1e5 0 0 0]) ;
vl_assert_almost_equal(D(1,:),min(I,[],1),1e-10);
function [D,map]=imdisttf_equiv(I,param)
D = inf + zeros(size(I)) ;
map = zeros(size(I)) ;
ur = 1:size(D,2) ;
vr = 1:size(D,1) ;
[u,v] = meshgrid(ur,vr) ;
for v_=vr
for u_=ur
E = I(v_,u_) + ...
param(1) * (u - u_ - param(2)).^2 + ...
param(3) * (v - v_ - param(4)).^2 ;
map(E < D) = sub2ind(size(I),v_,u_) ;
D = min(D,E) ;
end
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_vlad.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_vlad.m
| 1,977 |
utf_8
|
d3797288d6edb1d445b890db3780c8ce
|
function results = vl_test_vlad(varargin)
% VL_TEST_VLAD
vl_test_init ;
function s = setup()
randn('state',0) ;
s.x = randn(128,256) ;
s.mu = randn(128,16) ;
assignments = rand(16, 256) ;
s.assignments = bsxfun(@times, assignments, 1 ./ sum(assignments,1)) ;
function test_basic (s)
x = [1, 2, 3] ;
mu = [0, 0, 0] ;
assignments = eye(3) ;
phi = vl_vlad(x, mu, assignments, 'unnormalized') ;
vl_assert_equal(phi, [1 2 3]') ;
mu = [0, 1, 2] ;
phi = vl_vlad(x, mu, assignments, 'unnormalized') ;
vl_assert_equal(phi, [1 1 1]') ;
phi = vl_vlad([x x], mu, [assignments assignments], 'unnormalized') ;
vl_assert_equal(phi, [2 2 2]') ;
function test_rand (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized') ;
vl_assert_equal(phi, phi_) ;
function test_norm (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_vlad(s.x, s.mu, s.assignments) ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function test_sqrt (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'squareroot') ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function test_individual (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = reshape(phi_, size(s.x,1), []) ;
phi_ = bsxfun(@times, phi_, 1 ./ sqrt(sum(phi_.^2))) ;
phi_ = phi_(:) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizecomponents') ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function test_mass (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = reshape(phi_, size(s.x,1), []) ;
phi_ = bsxfun(@times, phi_, 1 ./ sum(s.assignments,2)') ;
phi_ = phi_(:) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizemass') ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function enc = simple_vlad(x, mu, assign)
for i = 1:size(assign,1)
enc{i} = x * assign(i,:)' - sum(assign(i,:)) * mu(:,i) ;
end
enc = cat(1, enc{:}) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_pr.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_pr.m
| 3,763 |
utf_8
|
4d1da5ccda1a7df2bec35b8f12fdd620
|
function results = vl_test_pr(varargin)
% VL_TEST_PR
vl_test_init ;
function s = setup()
s.scores0 = [5 4 3 2 1] ;
s.scores1 = [5 3 4 2 1] ;
s.labels = [1 1 -1 -1 -1] ;
function test_perfect_tptn(s)
[rc,pr] = vl_pr(s.labels,s.scores0) ;
vl_assert_almost_equal(pr, [1 1/1 2/2 2/3 2/4 2/5]) ;
vl_assert_almost_equal(rc, [0 1 2 2 2 2] / 2) ;
function test_perfect_metrics(s)
[rc,pr,info] = vl_pr(s.labels,s.scores0) ;
vl_assert_almost_equal(info.auc, 1) ;
vl_assert_almost_equal(info.ap, 1) ;
vl_assert_almost_equal(info.ap_interp_11, 1) ;
function test_swap1_tptn(s)
[rc,pr] = vl_pr(s.labels,s.scores1) ;
vl_assert_almost_equal(pr, [1 1/1 1/2 2/3 2/4 2/5]) ;
vl_assert_almost_equal(rc, [0 1 1 2 2 2] / 2) ;
function test_swap1_tptn_stable(s)
[rc,pr] = vl_pr(s.labels,s.scores1,'stable',true) ;
vl_assert_almost_equal(pr, [1/1 2/3 1/2 2/4 2/5]) ;
vl_assert_almost_equal(rc, [1 2 1 2 2] / 2) ;
function test_swap1_metrics(s)
[rc,pr,info] = vl_pr(s.labels,s.scores1) ;
clf; vl_pr(s.labels,s.scores1) ;
vl_assert_almost_equal(info.auc, [.5 + .5 * (.5 + 2/3)/2]) ;
vl_assert_almost_equal(info.ap, [1/1 + 2/3]/2) ;
vl_assert_almost_equal(info.ap_interp_11, mean([1 1 1 1 1 1 2/3 2/3 2/3 2/3 2/3])) ;
function test_inf(s)
scores = [1 -inf -1 -1 -1 -1] ;
labels = [1 1 -1 -1 -1 -1] ;
[rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true) ;
[rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false) ;
vl_assert_equal(numel(rc1), numel(rc2) + 1) ;
vl_assert_almost_equal(info1.auc, [1 * .5 + (1/5 + 2/6)/2 * .5]) ;
vl_assert_almost_equal(info1.ap, [1 * .5 + 2/6 * .5]) ;
vl_assert_almost_equal(info1.ap_interp_11, [1 * 6/11 + 2/6 * 5/11]) ;
vl_assert_almost_equal(info2.auc, 0.5) ;
vl_assert_almost_equal(info2.ap, 0.5) ;
vl_assert_almost_equal(info2.ap_interp_11, 1 * 6 / 11) ;
function test_inf_stable(s)
scores = [-1 -1 -1 -1 -inf +1] ;
labels = [-1 -1 -1 -1 +1 +1] ;
[rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true, 'stable', true) ;
[rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false, 'stable', true) ;
[rc1_,pr1_,info1_] = vl_pr(labels, scores, 'includeInf', true, 'stable', false) ;
[rc2_,pr2_,info2_] = vl_pr(labels, scores, 'includeInf', false, 'stable', false) ;
% stability does not change scores
vl_assert_almost_equal(info1,info1_) ;
vl_assert_almost_equal(info2,info2_) ;
% unstable with inf (first point (0,1) is conventional)
vl_assert_almost_equal(rc1_, [0 .5 .5 .5 .5 .5 1])
vl_assert_almost_equal(pr1_, [1 1 1/2 1/3 1/4 1/5 2/6])
% unstable without inf
vl_assert_almost_equal(rc2_, [0 .5 .5 .5 .5 .5])
vl_assert_almost_equal(pr2_, [1 1 1/2 1/3 1/4 1/5])
% stable with inf (no conventional point here)
vl_assert_almost_equal(rc1, [.5 .5 .5 .5 1 .5]) ;
vl_assert_almost_equal(pr1, [1/2 1/3 1/4 1/5 2/6 1]) ;
% stable without inf (no conventional point and -inf are NaN)
vl_assert_almost_equal(rc2, [.5 .5 .5 .5 NaN .5]) ;
vl_assert_almost_equal(pr2, [1/2 1/3 1/4 1/5 NaN 1]) ;
function test_normalised_pr(s)
scores = [+1 +2] ;
labels = [+1 -1] ;
[rc1,pr1,info1] = vl_pr(labels,scores) ;
[rc2,pr2,info2] = vl_pr(labels,scores,'normalizePrior',.5) ;
vl_assert_almost_equal(pr1, pr2) ;
vl_assert_almost_equal(rc1, rc2) ;
scores_ = [+1 +2 +2 +2] ;
labels_ = [+1 -1 -1 -1] ;
[rc3,pr3,info3] = vl_pr(labels_,scores_) ;
[rc4,pr4,info4] = vl_pr(labels,scores,'normalizePrior',1/4) ;
vl_assert_almost_equal(info3, info4) ;
function test_normalised_pr_corner_cases(s)
scores = 1:10 ;
labels = ones(1,10) ;
[rc1,pr1,info1] = vl_pr(labels,scores) ;
vl_assert_almost_equal(rc1, (0:10)/10) ;
vl_assert_almost_equal(pr1, ones(1,11)) ;
scores = 1:10 ;
labels = zeros(1,10) ;
[rc2,pr2,info2] = vl_pr(labels,scores) ;
vl_assert_almost_equal(rc2, zeros(1,11)) ;
vl_assert_almost_equal(pr2, ones(1,11)) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_hog.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_hog.m
| 1,555 |
utf_8
|
eed7b2a116d142040587dc9c4eb7cd2e
|
function results = vl_test_hog(varargin)
% VL_TEST_HOG
vl_test_init ;
function s = setup()
s.im = im2single(vl_impattern('roofs1')) ;
[x,y]= meshgrid(linspace(-1,1,128)) ;
s.round = single(x.^2+y.^2);
s.imSmall = s.im(1:128,1:128,:) ;
s.imSmall = s.im ;
s.imSmallFlipped = s.imSmall(:,end:-1:1,:) ;
function test_basic_call(s)
cellSize = 8 ;
hog = vl_hog(s.im, cellSize) ;
function test_bilinear_orientations(s)
cellSize = 8 ;
vl_hog(s.im, cellSize, 'bilinearOrientations') ;
function test_variants_and_flipping(s)
variants = {'uoctti', 'dalaltriggs'} ;
numOrientationsRange = 3:9 ;
cellSize = 8 ;
for cellSize = [4 8 16]
for i=1:numel(variants)
for j=1:numel(numOrientationsRange)
args = {'bilinearOrientations', ...
'variant', variants{i}, ...
'numOrientations', numOrientationsRange(j)} ;
hog = vl_hog(s.imSmall, cellSize, args{:}) ;
perm = vl_hog('permutation', args{:}) ;
hog1 = vl_hog(s.imSmallFlipped, cellSize, args{:}) ;
hog2 = hog(:,end:-1:1,perm) ;
%norm(hog1(:)-hog2(:))
vl_assert_almost_equal(hog1,hog2,1e-3) ;
end
end
end
function test_polar(s)
cellSize = 8 ;
im = s.round ;
for b = [0 1]
if b
args = {'bilinearOrientations'} ;
else
args = {} ;
end
hog1 = vl_hog(im, cellSize, args{:}) ;
[ix,iy] = vl_grad(im) ;
m = sqrt(ix.^2 + iy.^2) ;
a = atan2(iy,ix) ;
m(:,[1 end]) = 0 ;
m([1 end],:) = 0 ;
hog2 = vl_hog(cat(3,m,a), cellSize, 'DirectedPolarField', args{:}) ;
vl_assert_almost_equal(hog1,hog2,norm(hog1(:))/1000) ;
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_argparse.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_argparse.m
| 795 |
utf_8
|
e72185b27206d0ee1dfdc19fe77a5be6
|
function results = vl_test_argparse(varargin)
% VL_TEST_ARGPARSE
vl_test_init ;
function test_basic()
opts.field1 = 1 ;
opts.field2 = 2 ;
opts.field3 = 3 ;
opts_ = opts ;
opts_.field1 = 3 ;
opts_.field2 = 10 ;
opts = vl_argparse(opts, {'field2', 10, 'field1', 3}) ;
assert(isequal(opts, opts_)) ;
opts_.field1 = 9 ;
opts = vl_argparse(opts, {'field1', 4, 'field1', 9}) ;
assert(isequal(opts, opts_)) ;
function test_error()
opts.field1 = 1 ;
try
opts = vl_argparse(opts, {'field2', 5}) ;
catch e
return ;
end
assert(false) ;
function test_leftovers()
opts1.field1 = 1 ;
opts2.field2 = 1 ;
opts1_.field1 = 2 ;
opts2_.field2 = 2 ;
[opts1,args] = vl_argparse(opts1, {'field1', 2, 'field2', 2}) ;
opts2 = vl_argparse(opts2, args) ;
assert(isequal(opts1,opts1_), isequal(opts2,opts2_)) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_liop.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_liop.m
| 1,023 |
utf_8
|
a162be369073bed18e61210f44088cf3
|
function results = vl_test_liop(varargin)
% VL_TEST_SIFT
vl_test_init ;
function s = setup()
randn('state',0) ;
s.patch = randn(65,'single') ;
xr = -32:32 ;
[x,y] = meshgrid(xr) ;
s.blob = - single(x.^2+y.^2) ;
function test_basic(s)
d = vl_liop(s.patch) ;
function test_blob(s)
% with a blob, all local intensity order pattern are equal. In
% particular, if the blob intensity decreases away from the center,
% then all local intensities sampled in a neighbourhood of 2 elements
% are already sorted (see LIOP details).
d = vl_liop(s.blob, ...
'IntensityThreshold', 0, ...
'NumNeighbours', 2, ...
'NumSpatialBins', 1) ;
assert(isequal(d, single([1;0]))) ;
function test_neighbours(s)
for n=2:5
for p=1:3
d = vl_liop(s.patch, 'NumNeighbours', n, 'NumSpatialBins', p) ;
assert(numel(d) == p * factorial(n)) ;
end
end
function test_multiple(s)
x = randn(31,31,3, 'single') ;
d = vl_liop(x) ;
for i=1:3
d_(:,i) = vl_liop(squeeze(x(:,:,i))) ;
end
assert(isequal(d,d_)) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_test_binsearch.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/xtest/vl_test_binsearch.m
| 1,339 |
utf_8
|
85dc020adce3f228fe7dfb24cf3acc63
|
function results = vl_test_binsearch(varargin)
% VL_TEST_BINSEARCH
vl_test_init ;
function test_inf_bins()
x = [-inf -1 0 1 +inf] ;
vl_assert_equal(vl_binsearch([], x), [0 0 0 0 0]) ;
vl_assert_equal(vl_binsearch([-inf 0], x), [1 1 2 2 2]) ;
vl_assert_equal(vl_binsearch([-inf], x), [1 1 1 1 1]) ;
vl_assert_equal(vl_binsearch([-inf +inf], x), [1 1 1 1 2]) ;
function test_empty()
vl_assert_equal(vl_binsearch([], []), []) ;
function test_bnd()
vl_assert_equal(vl_binsearch([], [1]), [0]) ;
vl_assert_equal(vl_binsearch([], [-inf]), [0]) ;
vl_assert_equal(vl_binsearch([], [+inf]), [0]) ;
vl_assert_equal(vl_binsearch([1], [.9]), [0]) ;
vl_assert_equal(vl_binsearch([1], [1]), [1]) ;
vl_assert_equal(vl_binsearch([1], [-inf]), [0]) ;
vl_assert_equal(vl_binsearch([1], [+inf]), [1]) ;
function test_basic()
vl_assert_equal(vl_binsearch(-10:10, -10:10), 1:21) ;
vl_assert_equal(vl_binsearch(-10:10, -11:10), 0:21) ;
vl_assert_equal(vl_binsearch(-10:10, [-inf, -11:10, +inf]), [0 0:21 21]) ;
function test_frac()
vl_assert_equal(vl_binsearch(1:10, 1:.5:10), floor(1:.5:10))
vl_assert_equal(vl_binsearch(1:10, fliplr(1:.5:10)), ...
fliplr(floor(1:.5:10))) ;
function test_array()
a = reshape(1:100,10,10) ;
b = reshape(1:.5:100.5, 2, []) ;
c = floor(b) ;
vl_assert_equal(vl_binsearch(a,b), c) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_roc.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/plotop/vl_roc.m
| 10,113 |
utf_8
|
22fd8ff455ee62a96ffd94b9074eafeb
|
function [tpr,tnr,info] = vl_roc(labels, scores, varargin)
%VL_ROC ROC curve.
% [TPR,TNR] = VL_ROC(LABELS, SCORES) computes the Receiver Operating
% Characteristic (ROC) curve [1]. LABELS is a row vector of ground
% truth labels, greater than zero for a positive sample and smaller
% than zero for a negative one. SCORES is a row vector of
% corresponding sample scores, usually obtained from a
% classifier. The scores induce a ranking of the samples where
% larger scores should correspond to positive labels.
%
% Without output arguments, the function plots the ROC graph of the
% specified data in the current graphical axis.
%
% Otherwise, the function returns the true positive and true
% negative rates TPR and TNR. These are vectors of the same size of
% LABELS and SCORES and are computed as follows. Samples are ranked
% by decreasing scores, starting from rank 1. TPR(K) and TNR(K) are
% the true positive and true negative rates when samples of rank
% smaller or equal to K-1 are predicted to be positive. So for
% example TPR(3) is the true positive rate when the two samples with
% largest score are predicted to be positive. Similarly, TPR(1) is
% the true positive rate when no samples are predicted to be
% positive, i.e. the constant 0.
%
% Setting a label to zero ignores the corresponding sample in the
% calculations, as if the sample was removed from the data. Setting
% the score of a sample to -INF causes the function to assume that
% that sample was never retrieved. If there are samples with -INF
% score, the ROC curve is incomplete as the maximum recall is less
% than 1.
%
% [TPR,TNR,INFO] = VL_ROC(...) returns an additional structure INFO
% with the following fields:
%
% info.auc:: Area under the ROC curve (AUC).
% This is the area under the ROC plot, the parametric curve
% (FPR(S), TPR(S)). The PLOT option can be used to plot variants
% of this curve, which affects the calculation of a corresponding
% AUC.
%
% info.eer:: Equal error rate (EER).
% The equal error rate is the value of FPR (or FNR) when the ROC
% curves intersects the line connecting (0,0) to (1,1).
%
% info.eerThreshold:: EER threshold.
% The value of the score for which the EER is attained.
%
% VL_ROC() accepts the following options:
%
% Plot:: []
% Setting this option turns on plotting unconditionally. The
% following plot variants are supported:
%
% tntp:: Plot TPR against TNR (standard ROC plot).
% tptn:: Plot TNR against TPR (recall on the horizontal axis).
% fptp:: Plot TPR against FPR.
% fpfn:: Plot FNR against FPR (similar to a DET curve).
%
% Note that this option will affect the INFO.AUC value computation
% too.
%
% NumPositives:: []
% NumNegatives:: []
% If either of these parameters is set to a number, the function
% pretends that LABELS contains the specified number of
% positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be
% smaller than the actual number of positive/negative entries in
% LABELS. The additional positive/negative labels are appended to
% the end of the sequence as if they had -INF scores (as explained
% above, the function interprets such samples as `not
% retrieved'). This feature can be used to evaluate the
% performance of a large-scale retrieval experiment in which only
% a subset of highly-scoring results are recorded for efficiency
% reason.
%
% Stable:: false
% If set to true, TPR and TNR are returned in the same order
% of LABELS and SCORES rather than being sorted by decreasing
% score.
%
% About the ROC curve::
% Consider a classifier that predicts as positive all samples whose
% score is not smaller than a threshold S. The ROC curve represents
% the performance of such classifier as the threshold S is
% changed. Formally, define
%
% P = overall num. of positive samples,
% N = overall num. of negative samples,
%
% and for each threshold S
%
% TP(S) = num. of samples that are correctly classified as positive,
% TN(S) = num. of samples that are correctly classified as negative,
% FP(S) = num. of samples that are incorrectly classified as positive,
% FN(S) = num. of samples that are incorrectly classified as negative.
%
% Consider also the rates:
%
% TPR = TP(S) / P, FNR = FN(S) / P,
% TNR = TN(S) / N, FPR = FP(S) / N,
%
% and notice that, by definition,
%
% P = TP(S) + FN(S) , N = TN(S) + FP(S),
% 1 = TPR(S) + FNR(S), 1 = TNR(S) + FPR(S).
%
% The ROC curve is the parametric curve (FPR(S), TPR(S)) obtained
% as the classifier threshold S is varied in the reals. The TPR is
% the same as `recall' in a PR curve (see VL_PR()).
%
% The ROC curve is contained in the square with vertices (0,0) The
% (average) ROC curve of a random classifier is a line which
% connects (1,0) and (0,1).
%
% The ROC curve is independent of the prior probability of the
% labels (i.e. of P/(P+N) and N/(P+N)).
%
% REFERENCES:
% [1] http://en.wikipedia.org/wiki/Receiver_operating_characteristic
%
% See also: VL_PR(), VL_DET(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
[tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ;
opts.plot = [] ;
opts.stable = false ;
opts = vl_argparse(opts,varargin) ;
% compute the rates
small = 1e-10 ;
tpr = tp / max(p, small) ;
fpr = fp / max(n, small) ;
fnr = 1 - tpr ;
tnr = 1 - fpr ;
do_plots = ~isempty(opts.plot) || nargout == 0 ;
if isempty(opts.plot), opts.plot = 'fptp' ; end
% --------------------------------------------------------------------
% Additional info
% --------------------------------------------------------------------
if nargout > 2 || do_plots
% Area under the curve. Since the curve is a staircase (in the
% sense that for each sample either tn is decremented by one
% or tp is incremented by one but the other remains fixed),
% the integral is particularly simple and exact.
switch opts.plot
case 'tntp', info.auc = -sum(tpr .* diff([0 tnr])) ;
case 'fptp', info.auc = +sum(tpr .* diff([0 fpr])) ;
case 'tptn', info.auc = +sum(tnr .* diff([0 tpr])) ;
case 'fpfn', info.auc = +sum(fnr .* diff([0 fpr])) ;
otherwise
error('''%s'' is not a valid PLOT type.', opts.plot);
end
% Equal error rate. One must find the index S in correspondence of
% which TNR(S) and TPR(s) cross. Note that TPR(S) is non-decreasing,
% TNR(S) is non-increasing, and from rank S to rank S+1 only one of
% the two quantities can change. Hence there are exactly two types
% of crossing points:
%
% 1) TNR(S) = TNR(S+1) = EER and TPR(S) <= EER, TPR(S+1) > EER,
% 2) TPR(S) = TPR(S+1) = EER and TNR(S) > EER, TNR(S+1) <= EER.
%
% Moreover, if the maximum TPR is smaller than 1, then it is
% possible that neither of the two cases realizes. In the latter
% case, we return EER=NaN.
s = max(find(tnr > tpr)) ;
if s == length(tpr)
info.eer = NaN ;
info.eerThreshold = 0 ;
else
if tpr(s) == tpr(s+1)
info.eer = 1 - tpr(s) ;
else
info.eer = 1 - tnr(s) ;
end
info.eerThreshold = scores(perm(s)) ;
end
end
% --------------------------------------------------------------------
% Plot
% --------------------------------------------------------------------
if do_plots
cla ; hold on ;
switch lower(opts.plot)
case 'tntp'
hroc = plot(tnr, tpr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;
spline([0 1], [0 1], 'k--', 'linewidth', 1) ;
plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;
xlabel('true negative rate') ;
ylabel('true positive rate (recall)') ;
loc = 'sw' ;
case 'fptp'
hroc = plot(fpr, tpr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [0 1], 'r--', 'linewidth', 2) ;
spline([1 0], [0 1], 'k--', 'linewidth', 1) ;
plot(info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;
xlabel('false positive rate') ;
ylabel('true positive rate (recall)') ;
loc = 'se' ;
case 'tptn'
hroc = plot(tpr, tnr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;
spline([0 1], [0 1], 'k--', 'linewidth', 1) ;
plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;
xlabel('true positive rate (recall)') ;
ylabel('false positive rate') ;
loc = 'sw' ;
case 'fpfn'
hroc = plot(fpr, fnr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;
spline([0 1], [0 1], 'k--', 'linewidth', 1) ;
plot(info.eer, info.eer, 'k*', 'linewidth', 1) ;
xlabel('false positive (false alarm) rate') ;
ylabel('false negative (miss) rate') ;
loc = 'ne' ;
otherwise
error('''%s'' is not a valid PLOT type.', opts.plot);
end
grid on ;
xlim([0 1]) ;
ylim([0 1]) ;
axis square ;
title(sprintf('ROC (AUC: %.2f%%, EER: %.2f%%)', info.auc * 100, info.eer * 100), ...
'interpreter', 'none') ;
legend([hroc hrand], 'ROC', 'ROC rand.', 'location', loc) ;
end
% --------------------------------------------------------------------
% Stable output
% --------------------------------------------------------------------
if opts.stable
tpr(1) = [] ;
tnr(1) = [] ;
tpr_ = tpr ;
tnr_ = tnr ;
tpr = NaN(size(tpr)) ;
tnr = NaN(size(tnr)) ;
tpr(perm) = tpr_ ;
tnr(perm) = tnr_ ;
end
% --------------------------------------------------------------------
function h = spline(x,y,spec,varargin)
% --------------------------------------------------------------------
prop = vl_linespec2prop(spec) ;
h = line(x,y,prop{:},varargin{:}) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_click.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/plotop/vl_click.m
| 2,661 |
utf_8
|
6982e869cf80da57fdf68f5ebcd05a86
|
function P = vl_click(N,varargin) ;
% VL_CLICK Click a point
% P=VL_CLICK() let the user click a point in the current figure and
% returns its coordinates in P. P is a two dimensiona vectors where
% P(1) is the point X-coordinate and P(2) the point Y-coordinate. The
% user can abort the operation by pressing any key, in which case the
% empty matrix is returned.
%
% P=VL_CLICK(N) lets the user select N points in a row. The user can
% stop inserting points by pressing any key, in which case the
% partial list is returned.
%
% VL_CLICK() accepts the following options:
%
% PlotMarker:: [0]
% Plot a marker as points are selected. The markers are deleted on
% exiting the function.
%
% See also: VL_CLICKPOINT(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
plot_marker = 0 ;
for k=1:2:length(varargin)
switch lower(varargin{k})
case 'plotmarker'
plot_marker = varargin{k+1} ;
otherwise
error(['Uknown option ''', varargin{k}, '''.']) ;
end
end
if nargin < 1
N=1;
end
% --------------------------------------------------------------------
% Do job
% --------------------------------------------------------------------
fig = gcf ;
is_hold = ishold ;
hold on ;
bhandler = get(fig,'WindowButtonDownFcn') ;
khandler = get(fig,'KeyPressFcn') ;
pointer = get(fig,'Pointer') ;
set(fig,'WindowButtonDownFcn',@click_handler) ;
set(fig,'KeyPressFcn',@key_handler) ;
set(fig,'Pointer','crosshair') ;
P=[] ;
h=[] ;
data.exit=0;
guidata(fig,data) ;
while size(P,2) < N
uiwait(fig) ;
data = guidata(fig) ;
if(data.exit)
break ;
end
P = [P data.P] ;
if( plot_marker )
h=[h plot(data.P(1),data.P(2),'rx')] ;
end
end
if ~is_hold
hold off ;
end
if( plot_marker )
pause(.1);
delete(h) ;
end
set(fig,'WindowButtonDownFcn',bhandler) ;
set(fig,'KeyPressFcn',khandler) ;
set(fig,'Pointer',pointer) ;
% ====================================================================
function click_handler(obj,event)
% --------------------------------------------------------------------
data = guidata(gcbo) ;
P = get(gca, 'CurrentPoint') ;
P = [P(1,1); P(1,2)] ;
data.P = P ;
guidata(obj,data) ;
uiresume(gcbo) ;
% ====================================================================
function key_handler(obj,event)
% --------------------------------------------------------------------
data = guidata(gcbo) ;
data.exit = 1 ;
guidata(obj,data) ;
uiresume(gcbo) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_pr.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/plotop/vl_pr.m
| 9,138 |
utf_8
|
c7fe6832d2b6b9917896810c52a05479
|
function [recall, precision, info] = vl_pr(labels, scores, varargin)
%VL_PR Precision-recall curve.
% [RECALL, PRECISION] = VL_PR(LABELS, SCORES) computes the
% precision-recall (PR) curve. LABELS are the ground truth labels,
% greather than zero for a positive sample and smaller than zero for
% a negative one. SCORES are the scores of the samples obtained from
% a classifier, where lager scores should correspond to positive
% samples.
%
% Samples are ranked by decreasing scores, starting from rank 1.
% PRECISION(K) and RECALL(K) are the precison and recall when
% samples of rank smaller or equal to K-1 are predicted to be
% positive and the remaining to be negative. So for example
% PRECISION(3) is the percentage of positive samples among the two
% samples with largest score. PRECISION(1) is the precision when no
% samples are predicted to be positive and is conventionally set to
% the value 1.
%
% Set to zero the lables of samples that should be ignored in the
% evaluation. Set to -INF the scores of samples which are not
% retrieved. If there are samples with -INF score, then the PR curve
% may have maximum recall smaller than 1, unless the INCLUDEINF
% option is used (see below). The options NUMNEGATIVES and
% NUMPOSITIVES can be used to add additional surrogate samples with
% -INF score (see below).
%
% [RECALL, PRECISION, INFO] = VL_PR(...) returns an additional
% structure INFO with the following fields:
%
% info.auc::
% The area under the precision-recall curve. If the INTERPOLATE
% option is set to FALSE, then trapezoidal interpolation is used
% to integrate the PR curve. If the INTERPOLATE option is set to
% TRUE, then the curve is piecewise constant and no other
% approximation is introduced in the calculation of the area. In
% the latter case, INFO.AUC is the same as INFO.AP.
%
% info.ap::
% Average precision as defined by TREC. This is the average of the
% precision observed each time a new positive sample is
% recalled. In this calculation, any sample with -INF score
% (unless INCLUDEINF is used) and any additional positive induced
% by NUMPOSITIVES has precision equal to zero. If the INTERPOLATE
% option is set to true, the AP is computed from the interpolated
% precision and the result is the same as INFO.AUC. Note that AP
% as defined by TREC normally does not use interpolation [1].
%
% info.ap_interp_11::
% 11-points interpolated average precision as defined by TREC.
% This is the average of the maximum precision for recall levels
% greather than 0.0, 0.1, 0.2, ..., 1.0. This measure was used in
% the PASCAL VOC challenge up to the 2008 edition.
%
% info.auc_pa08::
% Deprecated. It is the same of INFO.AP_INTERP_11.
%
% VL_PR(...) with no output arguments plots the PR curve in the
% current axis.
%
% VL_PR() accepts the following options:
%
% Interpolate:: false
% If set to true, use interpolated precision. The interpolated
% precision is defined as the maximum precision for a given recall
% level and onwards. Here it is implemented as the culumative
% maximum from low to high scores of the precision.
%
% NumPositives:: []
% NumNegatives:: []
% If set to a number, pretend that LABELS contains this may
% positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be
% smaller than the actual number of positive/negative entrires in
% LABELS. The additional positive/negative labels are appended to
% the end of the sequence, as if they had -INF scores (not
% retrieved). This is useful to evaluate large retrieval systems
% for which one stores ony a handful of top results for efficiency
% reasons.
%
% IncludeInf:: false
% If set to true, data with -INF score SCORES is included in the
% evaluation and the maximum recall is 1 even if -INF scores are
% present. This option does not include any additional positive or
% negative data introduced by specifying NUMPOSITIVES and
% NUMNEGATIVES.
%
% Stable:: false
% If set to true, RECALL and PRECISION are returned in the same order
% of LABELS and SCORES rather than being sorted by decreasing
% score (increasing recall). Samples with -INF scores are assigned
% RECALL and PRECISION equal to NaN.
%
% NormalizePrior:: []
% If set to a scalar, reweights positive and negative labels so
% that the fraction of positive ones is equal to the specified
% value. This computes the normalised PR curves of [2]
%
% About the PR curve::
% This section uses the same symbols used in the documentation of
% the VL_ROC() function. In addition to those quantities, define:
%
% PRECISION(S) = TP(S) / (TP(S) + FP(S))
% RECALL(S) = TPR(S) = TP(S) / P
%
% The precision is the fraction of positivie predictions which are
% correct, and the recall is the fraction of positive labels that
% have been correctly classified (recalled). Notice that the recall
% is also equal to the true positive rate for the ROC curve (see
% VL_ROC()).
%
% REFERENCES:
% [1] C. D. Manning, P. Raghavan, and H. Schutze. An Introduction to
% Information Retrieval. Cambridge University Press, 2008.
% [2] D. Hoiem, Y. Chodpathumwan, and Q. Dai. Diagnosing error in
% object detectors. In Proc. ECCV, 2012.
%
% See also VL_ROC(), VL_HELP().
% Author: Andrea Vedaldi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
% TP and FP are the vectors of true positie and false positve label
% counts for decreasing scores, P and N are the total number of
% positive and negative labels. Note that if certain options are used
% some labels may actually not be stored explicitly by LABELS, so P+N
% can be larger than the number of element of LABELS.
[tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ;
opts.stable = false ;
opts.interpolate = false ;
opts.normalizePrior = [] ;
opts = vl_argparse(opts,varargin) ;
% compute precision and recall
small = 1e-10 ;
recall = tp / max(p, small) ;
if isempty(opts.normalizePrior)
precision = max(tp, small) ./ max(tp + fp, small) ;
else
a = opts.normalizePrior ;
precision = max(tp * a/max(p,small), small) ./ ...
max(tp * a/max(p,small) + fp * (1-a)/max(n,small), small) ;
end
% interpolate precision if needed
if opts.interpolate
precision = fliplr(vl_cummax(fliplr(precision))) ;
end
% --------------------------------------------------------------------
% Additional info
% --------------------------------------------------------------------
if nargout > 2 || nargout == 0
% area under the curve using trapezoid interpolation
if ~opts.interpolate
info.auc = 0.5 * sum((precision(1:end-1) + precision(2:end)) .* diff(recall)) ;
end
% average precision (for each recalled positive sample)
sel = find(diff(recall)) + 1 ;
info.ap = sum(precision(sel)) / p ;
if opts.interpolate
info.auc = info.ap ;
end
% TREC 11 points average interpolated precision
info.ap_interp_11 = 0.0 ;
for rc = linspace(0,1,11)
pr = max([0, precision(recall >= rc)]) ;
info.ap_interp_11 = info.ap_interp_11 + pr / 11 ;
end
% legacy definition
info.auc_pa08 = info.ap_interp_11 ;
end
% --------------------------------------------------------------------
% Plot
% --------------------------------------------------------------------
if nargout == 0
cla ; hold on ;
plot(recall,precision,'linewidth',2) ;
if isempty(opts.normalizePrior)
randomPrecision = p / (p + n) ;
else
randomPrecision = opts.normalizePrior ;
end
spline([0 1], [1 1] * randomPrecision, 'r--', 'linewidth', 2) ;
axis square ; grid on ;
xlim([0 1]) ; xlabel('recall') ;
ylim([0 1]) ; ylabel('precision') ;
title(sprintf('PR (AUC: %.2f%%, AP: %.2f%%, AP11: %.2f%%)', ...
info.auc * 100, ...
info.ap * 100, ...
info.ap_interp_11 * 100)) ;
if opts.interpolate
legend('PR interp.', 'PR rand.', 'Location', 'SouthEast') ;
else
legend('PR', 'PR rand.', 'Location', 'SouthEast') ;
end
clear recall precision info ;
end
% --------------------------------------------------------------------
% Stable output
% --------------------------------------------------------------------
if opts.stable
precision(1) = [] ;
recall(1) = [] ;
precision_ = precision ;
recall_ = recall ;
precision = NaN(size(precision)) ;
recall = NaN(size(recall)) ;
precision(perm) = precision_ ;
recall(perm) = recall_ ;
end
% --------------------------------------------------------------------
function h = spline(x,y,spec,varargin)
% --------------------------------------------------------------------
prop = vl_linespec2prop(spec) ;
h = line(x,y,prop{:},varargin{:}) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_ubcread.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/sift/vl_ubcread.m
| 3,015 |
utf_8
|
e8ddd3ecd87e76b6c738ba153fef050f
|
function [f,d] = vl_ubcread(file, varargin)
% SIFTREAD Read Lowe's SIFT implementation data files
% [F,D] = VL_UBCREAD(FILE) reads the frames F and the descriptors D
% from FILE in UBC (Lowe's original implementation of SIFT) format
% and returns F and D as defined by VL_SIFT().
%
% VL_UBCREAD(FILE, 'FORMAT', 'OXFORD') assumes the format used by
% Oxford VGG implementations .
%
% See also: VL_SIFT(), VL_HELP().
% Authors: Andrea Vedaldi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.verbosity = 0 ;
opts.format = 'ubc' ;
opts = vl_argparse(opts, varargin) ;
g = fopen(file, 'r');
if g == -1
error(['Could not open file ''', file, '''.']) ;
end
[header, count] = fscanf(g, '%d', [1 2]) ;
if count ~= 2
error('Invalid keypoint file header.');
end
switch opts.format
case 'ubc'
numKeypoints = header(1) ;
descrLen = header(2) ;
case 'oxford'
numKeypoints = header(2) ;
descrLen = header(1) ;
otherwise
error('Unknown format ''%s''.', opts.format) ;
end
if(opts.verbosity > 0)
fprintf('%d keypoints, %d descriptor length.\n', numKeypoints, descrLen) ;
end
%creates two output matrices
switch opts.format
case 'ubc'
P = zeros(4,numKeypoints) ;
case 'oxford'
P = zeros(5,numKeypoints) ;
end
L = zeros(descrLen, numKeypoints) ;
%parse tmp.key
for k = 1:numKeypoints
switch opts.format
case 'ubc'
% Record format: i,j,s,th
[record, count] = fscanf(g, '%f', [1 4]) ;
if count ~= 4
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) );
end
P(:,k) = record(:) ;
case 'oxford'
% Record format: x, y, a, b, c such that x' [a b ; b c] x = 1
[record, count] = fscanf(g, '%f', [1 5]) ;
if count ~= 5
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) );
end
P(:,k) = record(:) ;
end
% Record format: descriptor
[record, count] = fscanf(g, '%d', [1 descrLen]) ;
if count ~= descrLen
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, descriptor part)',k) );
end
L(:,k) = record(:) ;
end
fclose(g) ;
switch opts.format
case 'ubc'
P(1:2,:) = flipud(P(1:2,:)) + 1 ; % i,j -> x,y
f=[ P(1:2,:) ; P(3,:) ; -P(4,:) ] ;
d=uint8(L) ;
p=[1 2 3 4 5 6 7 8] ;
q=[1 8 7 6 5 4 3 2] ;
for j=0:3
for i=0:3
d(8*(i+4*j)+p,:) = d(8*(i+4*j)+q,:) ;
end
end
case 'oxford'
P(1:2,:) = P(1:2,:) + 1 ; % matlab origin
f = P ;
f(3:5,:) = inv2x2(f(3:5,:)) ;
d = uint8(L) ;
end
% --------------------------------------------------------------------
function S = inv2x2(C)
% --------------------------------------------------------------------
den = C(1,:) .* C(3,:) - C(2,:) .* C(2,:) ;
S = [C(3,:) ; -C(2,:) ; C(1,:)] ./ den([1 1 1], :) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_frame2oell.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/sift/vl_frame2oell.m
| 2,806 |
utf_8
|
c93792632f630743485fa4c2cf12d647
|
function eframes = vl_frame2oell(frames)
% VL_FRAMES2OELL Convert a geometric frame to an oriented ellipse
% EFRAME = VL_FRAME2OELL(FRAME) converts the generic FRAME to an
% oriented ellipses EFRAME. FRAME and EFRAME can be matrices, with
% one frame per column.
%
% A frame is either a point, a disc, an oriented disc, an ellipse,
% or an oriented ellipse. These are represented respectively by 2,
% 3, 4, 5 and 6 parameters each, as described in VL_PLOTFRAME(). An
% oriented ellipse is the most general geometric frame; hence, there
% is no loss of information in this conversion.
%
% If FRAME is an oriented disc or ellipse, then the conversion is
% immediate. If, however, FRAME is not oriented (it is either a
% point or an unoriented disc or ellipse), then an orientation must
% be assigned. The orientation is chosen in such a way that the
% affine transformation that maps the standard oriented frame into
% the output EFRAME does not rotate the Y axis. If frames represent
% detected visual features, this convention corresponds to assume
% that features are upright.
%
% If FRAME is a point, then the output is an ellipse with null area.
%
% See: <a href="matlab:vl_help('tut.frame')">feature frames</a>,
% VL_PLOTFRAME(), VL_HELP().
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
[D,K] = size(frames) ;
eframes = zeros(6,K) ;
switch D
case 2
eframes(1:2,:) = frames(1:2,:) ;
case 3
eframes(1:2,:) = frames(1:2,:) ;
eframes(3,:) = frames(3,:) ;
eframes(6,:) = frames(3,:) ;
case 4
r = frames(3,:) ;
c = r.*cos(frames(4,:)) ;
s = r.*sin(frames(4,:)) ;
eframes(1:2,:) = frames(1:2,:) ;
eframes(3:6,:) = [c ; s ; -s ; c] ;
case 5
eframes(1:2,:) = frames(1:2,:) ;
eframes(3:6,:) = mapFromS(frames(3:5,:)) ;
case 6
eframes = frames ;
otherwise
error('FRAMES format is unknown.') ;
end
% --------------------------------------------------------------------
function A = mapFromS(S)
% --------------------------------------------------------------------
% Returns the (stacking of the) 2x2 matrix A that maps the unit circle
% into the ellipses satisfying the equation x' inv(S) x = 1. Here S
% is a stacked covariance matrix, with elements S11, S12 and S22.
%
% The goal is to find A such that AA' = S. In order to let the Y
% direction unaffected (upright feature), the assumption is taht
% A = [a b ; 0 c]. Hence
%
% AA' = [a^2, ab ; ab, b^2+c^2] = S.
A = zeros(4,size(S,2)) ;
a = sqrt(S(1,:));
b = S(2,:) ./ max(a, 1e-18) ;
A(1,:) = a ;
A(2,:) = b ;
A(4,:) = sqrt(max(S(3,:) - b.*b, 0)) ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
vl_plotsiftdescriptor.m
|
.m
|
SceneRecognition-master/code/vlfeat/toolbox/sift/vl_plotsiftdescriptor.m
| 5,114 |
utf_8
|
a4e125a8916653f00143b61cceda2f23
|
function h=vl_plotsiftdescriptor(d,f,varargin)
% VL_PLOTSIFTDESCRIPTOR Plot SIFT descriptor
% VL_PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptor D. If D is a
% matrix, it plots one descriptor per column. D has the same format
% used by VL_SIFT().
%
% VL_PLOTSIFTDESCRIPTOR(D,F) plots the SIFT descriptors warped to
% the SIFT frames F, specified as columns of the matrix F. F has the
% same format used by VL_SIFT().
%
% H=VL_PLOTSIFTDESCRIPTOR(...) returns the handle H to the line
% drawing representing the descriptors.
%
% The function assumes that the SIFT descriptors use the standard
% configuration of 4x4 spatial bins and 8 orientations bins. The
% following parameters can be used to change this:
%
% NumSpatialBins:: 4
% Number of spatial bins in both spatial directions X and Y.
%
% NumOrientationBins:: 8
% Number of orientation bis.
%
% MagnificationFactor:: 3
% Magnification factor. The width of one bin is equal to the scale
% of the keypoint F multiplied by this factor.
%
% See also: VL_SIFT(), VL_PLOTFRAME(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.magnificationFactor = 3.0 ;
opts.numSpatialBins = 4 ;
opts.numOrientationBins = 8 ;
opts.maxValue = 0 ;
if nargin > 1
if ~ isnumeric(f)
error('F must be a numeric type (use [] to leave it unspecified)') ;
end
end
opts = vl_argparse(opts, varargin) ;
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(size(d,1) ~= opts.numSpatialBins^2 * opts.numOrientationBins)
error('The number of rows of D does not match the geometry of the descriptor') ;
end
if nargin > 1
if (~isempty(f) & (size(f,1) < 2 | size(f,1) > 6))
error('F must be either empty of have from 2 to six rows.');
end
if size(f,1) == 2
% translation only
f(3:6,:) = deal([10 0 0 10]') ;
%f = [f; 10 * ones(1, size(f,2)) ; 0 * zeros(1, size(f,2))] ;
end
if size(f,1) == 3
% translation and scale
f(3:6,:) = [1 0 0 1]' * f(3,:) ;
%f = [f; 0 * zeros(1, size(f,2))] ;
end
if size(f,1) == 4
c = cos(f(4,:)) ;
s = sin(f(4,:)) ;
f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ;
end
if size(f,1) == 5
assert(false) ;
c = cos(f(4,:)) ;
s = sin(f(4,:)) ;
f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ;
end
if(~isempty(f) & size(f,2) ~= size(d,2))
error('D and F have incompatible dimension') ;
end
end
% Descriptors are often non-double numeric arrays
d = double(d) ;
K = size(d,2) ;
if nargin < 2 | isempty(f)
f = repmat([0;0;1;0;0;1],1,K) ;
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
xall=[] ;
yall=[] ;
for k=1:K
[x,y] = render_descr(d(:,k), opts.numSpatialBins, opts.numOrientationBins, opts.maxValue) ;
xall = [xall opts.magnificationFactor*f(3,k)*x + opts.magnificationFactor*f(5,k)*y + f(1,k)] ;
yall = [yall opts.magnificationFactor*f(4,k)*x + opts.magnificationFactor*f(6,k)*y + f(2,k)] ;
end
h=line(xall,yall) ;
% --------------------------------------------------------------------
function [x,y] = render_descr(d, numSpatialBins, numOrientationBins, maxValue)
% --------------------------------------------------------------------
% Get the coordinates of the lines of the SIFT grid; each bin has side 1
[x,y] = meshgrid(-numSpatialBins/2:numSpatialBins/2,-numSpatialBins/2:numSpatialBins/2) ;
% Get the corresponding bin centers
xc = x(1:end-1,1:end-1) + 0.5 ;
yc = y(1:end-1,1:end-1) + 0.5 ;
% Rescale the descriptor range so that the biggest peak fits inside the bin diagram
if maxValue
d = 0.4 * d / maxValue ;
else
d = 0.4 * d / max(d(:)+eps) ;
end
% We scramble the the centers to have them in row major order
% (descriptor convention).
xc = xc' ;
yc = yc' ;
% Each spatial bin contains a star with numOrientationBins tips
xc = repmat(xc(:)',numOrientationBins,1) ;
yc = repmat(yc(:)',numOrientationBins,1) ;
% Do the stars
th=linspace(0,2*pi,numOrientationBins+1) ;
th=th(1:end-1) ;
xd = repmat(cos(th), 1, numSpatialBins*numSpatialBins) ;
yd = repmat(sin(th), 1, numSpatialBins*numSpatialBins) ;
xd = xd .* d(:)' ;
yd = yd .* d(:)' ;
% Re-arrange in sequential order the lines to draw
nans = NaN * ones(1,numSpatialBins^2*numOrientationBins) ;
x1 = xc(:)' ;
y1 = yc(:)' ;
x2 = x1 + xd ;
y2 = y1 + yd ;
xstars = [x1;x2;nans] ;
ystars = [y1;y2;nans] ;
% Horizontal lines of the grid
nans = NaN * ones(1,numSpatialBins+1);
xh = [x(:,1)' ; x(:,end)' ; nans] ;
yh = [y(:,1)' ; y(:,end)' ; nans] ;
% Verical lines of the grid
xv = [x(1,:) ; x(end,:) ; nans] ;
yv = [y(1,:) ; y(end,:) ; nans] ;
x=[xstars(:)' xh(:)' xv(:)'] ;
y=[ystars(:)' yh(:)' yv(:)'] ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
phow_caltech101.m
|
.m
|
SceneRecognition-master/code/vlfeat/apps/phow_caltech101.m
| 11,594 |
utf_8
|
7f4890a2e6844ca56debbfe23cca64f3
|
function phow_caltech101()
% PHOW_CALTECH101 Image classification in the Caltech-101 dataset
% This program demonstrates how to use VLFeat to construct an image
% classifier on the Caltech-101 data. The classifier uses PHOW
% features (dense SIFT), spatial histograms of visual words, and a
% Chi2 SVM. To speedup computation it uses VLFeat fast dense SIFT,
% kd-trees, and homogeneous kernel map. The program also
% demonstrates VLFeat PEGASOS SVM solver, although for this small
% dataset other solvers such as LIBLINEAR can be more efficient.
%
% By default 15 training images are used, which should result in
% about 64% performance (a good performance considering that only a
% single feature type is being used).
%
% Call PHOW_CALTECH101 to train and test a classifier on a small
% subset of the Caltech-101 data. Note that the program
% automatically downloads a copy of the Caltech-101 data from the
% Internet if it cannot find a local copy.
%
% Edit the PHOW_CALTECH101 file to change the program configuration.
%
% To run on the entire dataset change CONF.TINYPROBLEM to FALSE.
%
% The Caltech-101 data is saved into CONF.CALDIR, which defaults to
% 'data/caltech-101'. Change this path to the desired location, for
% instance to point to an existing copy of the Caltech-101 data.
%
% The program can also be used to train a model on custom data by
% pointing CONF.CALDIR to it. Just create a subdirectory for each
% class and put the training images there. Make sure to adjust
% CONF.NUMTRAIN accordingly.
%
% Intermediate files are stored in the directory CONF.DATADIR. All
% such files begin with the prefix CONF.PREFIX, which can be changed
% to test different parameter settings without overriding previous
% results.
%
% The program saves the trained model in
% <CONF.DATADIR>/<CONF.PREFIX>-model.mat. This model can be used to
% test novel images independently of the Caltech data.
%
% load('data/baseline-model.mat') ; # change to the model path
% label = model.classify(model, im) ;
%
% Author: Andrea Vedaldi
% Copyright (C) 2011-2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
conf.calDir = 'data/caltech-101' ;
conf.dataDir = 'data/' ;
conf.autoDownloadData = true ;
conf.numTrain = 15 ;
conf.numTest = 15 ;
conf.numClasses = 102 ;
conf.numWords = 600 ;
conf.numSpatialX = [2 4] ;
conf.numSpatialY = [2 4] ;
conf.quantizer = 'kdtree' ;
conf.svm.C = 10 ;
conf.svm.solver = 'sdca' ;
%conf.svm.solver = 'sgd' ;
%conf.svm.solver = 'liblinear' ;
conf.svm.biasMultiplier = 1 ;
conf.phowOpts = {'Step', 3} ;
conf.clobber = false ;
conf.tinyProblem = true ;
conf.prefix = 'baseline' ;
conf.randSeed = 1 ;
if conf.tinyProblem
conf.prefix = 'tiny' ;
conf.numClasses = 5 ;
conf.numSpatialX = 2 ;
conf.numSpatialY = 2 ;
conf.numWords = 300 ;
conf.phowOpts = {'Verbose', 2, 'Sizes', 7, 'Step', 5} ;
end
conf.vocabPath = fullfile(conf.dataDir, [conf.prefix '-vocab.mat']) ;
conf.histPath = fullfile(conf.dataDir, [conf.prefix '-hists.mat']) ;
conf.modelPath = fullfile(conf.dataDir, [conf.prefix '-model.mat']) ;
conf.resultPath = fullfile(conf.dataDir, [conf.prefix '-result']) ;
randn('state',conf.randSeed) ;
rand('state',conf.randSeed) ;
vl_twister('state',conf.randSeed) ;
% --------------------------------------------------------------------
% Download Caltech-101 data
% --------------------------------------------------------------------
if ~exist(conf.calDir, 'dir') || ...
(~exist(fullfile(conf.calDir, 'airplanes'),'dir') && ...
~exist(fullfile(conf.calDir, '101_ObjectCategories', 'airplanes')))
if ~conf.autoDownloadData
error(...
['Caltech-101 data not found. ' ...
'Set conf.autoDownloadData=true to download the required data.']) ;
end
vl_xmkdir(conf.calDir) ;
calUrl = ['http://www.vision.caltech.edu/Image_Datasets/' ...
'Caltech101/101_ObjectCategories.tar.gz'] ;
fprintf('Downloading Caltech-101 data to ''%s''. This will take a while.', conf.calDir) ;
untar(calUrl, conf.calDir) ;
end
if ~exist(fullfile(conf.calDir, 'airplanes'),'dir')
conf.calDir = fullfile(conf.calDir, '101_ObjectCategories') ;
end
% --------------------------------------------------------------------
% Setup data
% --------------------------------------------------------------------
classes = dir(conf.calDir) ;
classes = classes([classes.isdir]) ;
classes = {classes(3:conf.numClasses+2).name} ;
images = {} ;
imageClass = {} ;
for ci = 1:length(classes)
ims = dir(fullfile(conf.calDir, classes{ci}, '*.jpg'))' ;
ims = vl_colsubset(ims, conf.numTrain + conf.numTest) ;
ims = cellfun(@(x)fullfile(classes{ci},x),{ims.name},'UniformOutput',false) ;
images = {images{:}, ims{:}} ;
imageClass{end+1} = ci * ones(1,length(ims)) ;
end
selTrain = find(mod(0:length(images)-1, conf.numTrain+conf.numTest) < conf.numTrain) ;
selTest = setdiff(1:length(images), selTrain) ;
imageClass = cat(2, imageClass{:}) ;
model.classes = classes ;
model.phowOpts = conf.phowOpts ;
model.numSpatialX = conf.numSpatialX ;
model.numSpatialY = conf.numSpatialY ;
model.quantizer = conf.quantizer ;
model.vocab = [] ;
model.w = [] ;
model.b = [] ;
model.classify = @classify ;
% --------------------------------------------------------------------
% Train vocabulary
% --------------------------------------------------------------------
if ~exist(conf.vocabPath) || conf.clobber
% Get some PHOW descriptors to train the dictionary
selTrainFeats = vl_colsubset(selTrain, 30) ;
descrs = {} ;
%for ii = 1:length(selTrainFeats)
parfor ii = 1:length(selTrainFeats)
im = imread(fullfile(conf.calDir, images{selTrainFeats(ii)})) ;
im = standarizeImage(im) ;
[drop, descrs{ii}] = vl_phow(im, model.phowOpts{:}) ;
end
descrs = vl_colsubset(cat(2, descrs{:}), 10e4) ;
descrs = single(descrs) ;
% Quantize the descriptors to get the visual words
vocab = vl_kmeans(descrs, conf.numWords, 'verbose', 'algorithm', 'elkan', 'MaxNumIterations', 50) ;
save(conf.vocabPath, 'vocab') ;
else
load(conf.vocabPath) ;
end
model.vocab = vocab ;
if strcmp(model.quantizer, 'kdtree')
model.kdtree = vl_kdtreebuild(vocab) ;
end
% --------------------------------------------------------------------
% Compute spatial histograms
% --------------------------------------------------------------------
if ~exist(conf.histPath) || conf.clobber
hists = {} ;
parfor ii = 1:length(images)
% for ii = 1:length(images)
fprintf('Processing %s (%.2f %%)\n', images{ii}, 100 * ii / length(images)) ;
im = imread(fullfile(conf.calDir, images{ii})) ;
hists{ii} = getImageDescriptor(model, im);
end
hists = cat(2, hists{:}) ;
save(conf.histPath, 'hists') ;
else
load(conf.histPath) ;
end
% --------------------------------------------------------------------
% Compute feature map
% --------------------------------------------------------------------
psix = vl_homkermap(hists, 1, 'kchi2', 'gamma', .5) ;
% --------------------------------------------------------------------
% Train SVM
% --------------------------------------------------------------------
if ~exist(conf.modelPath) || conf.clobber
switch conf.svm.solver
case {'sgd', 'sdca'}
lambda = 1 / (conf.svm.C * length(selTrain)) ;
w = [] ;
parfor ci = 1:length(classes)
perm = randperm(length(selTrain)) ;
fprintf('Training model for class %s\n', classes{ci}) ;
y = 2 * (imageClass(selTrain) == ci) - 1 ;
[w(:,ci) b(ci) info] = vl_svmtrain(psix(:, selTrain(perm)), y(perm), lambda, ...
'Solver', conf.svm.solver, ...
'MaxNumIterations', 50/lambda, ...
'BiasMultiplier', conf.svm.biasMultiplier, ...
'Epsilon', 1e-3);
end
case 'liblinear'
svm = train(imageClass(selTrain)', ...
sparse(double(psix(:,selTrain))), ...
sprintf(' -s 3 -B %f -c %f', ...
conf.svm.biasMultiplier, conf.svm.C), ...
'col') ;
w = svm.w(:,1:end-1)' ;
b = svm.w(:,end)' ;
end
model.b = conf.svm.biasMultiplier * b ;
model.w = w ;
save(conf.modelPath, 'model') ;
else
load(conf.modelPath) ;
end
% --------------------------------------------------------------------
% Test SVM and evaluate
% --------------------------------------------------------------------
% Estimate the class of the test images
scores = model.w' * psix + model.b' * ones(1,size(psix,2)) ;
[drop, imageEstClass] = max(scores, [], 1) ;
% Compute the confusion matrix
idx = sub2ind([length(classes), length(classes)], ...
imageClass(selTest), imageEstClass(selTest)) ;
confus = zeros(length(classes)) ;
confus = vl_binsum(confus, ones(size(idx)), idx) ;
% Plots
figure(1) ; clf;
subplot(1,2,1) ;
imagesc(scores(:,[selTrain selTest])) ; title('Scores') ;
set(gca, 'ytick', 1:length(classes), 'yticklabel', classes) ;
subplot(1,2,2) ;
imagesc(confus) ;
title(sprintf('Confusion matrix (%.2f %% accuracy)', ...
100 * mean(diag(confus)/conf.numTest) )) ;
print('-depsc2', [conf.resultPath '.ps']) ;
save([conf.resultPath '.mat'], 'confus', 'conf') ;
% -------------------------------------------------------------------------
function im = standarizeImage(im)
% -------------------------------------------------------------------------
im = im2single(im) ;
if size(im,1) > 480, im = imresize(im, [480 NaN]) ; end
% -------------------------------------------------------------------------
function hist = getImageDescriptor(model, im)
% -------------------------------------------------------------------------
im = standarizeImage(im) ;
width = size(im,2) ;
height = size(im,1) ;
numWords = size(model.vocab, 2) ;
% get PHOW features
[frames, descrs] = vl_phow(im, model.phowOpts{:}) ;
% quantize local descriptors into visual words
switch model.quantizer
case 'vq'
[drop, binsa] = min(vl_alldist(model.vocab, single(descrs)), [], 1) ;
case 'kdtree'
binsa = double(vl_kdtreequery(model.kdtree, model.vocab, ...
single(descrs), ...
'MaxComparisons', 50)) ;
end
for i = 1:length(model.numSpatialX)
binsx = vl_binsearch(linspace(1,width,model.numSpatialX(i)+1), frames(1,:)) ;
binsy = vl_binsearch(linspace(1,height,model.numSpatialY(i)+1), frames(2,:)) ;
% combined quantization
bins = sub2ind([model.numSpatialY(i), model.numSpatialX(i), numWords], ...
binsy,binsx,binsa) ;
hist = zeros(model.numSpatialY(i) * model.numSpatialX(i) * numWords, 1) ;
hist = vl_binsum(hist, ones(size(bins)), bins) ;
hists{i} = single(hist / sum(hist)) ;
end
hist = cat(1,hists{:}) ;
hist = hist / sum(hist) ;
% -------------------------------------------------------------------------
function [className, score] = classify(model, im)
% -------------------------------------------------------------------------
hist = getImageDescriptor(model, im) ;
psix = vl_homkermap(hist, 1, 'kchi2', 'gamma', .5) ;
scores = model.w' * psix + model.b' ;
[score, best] = max(scores) ;
className = model.classes{best} ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
sift_mosaic.m
|
.m
|
SceneRecognition-master/code/vlfeat/apps/sift_mosaic.m
| 4,621 |
utf_8
|
8fa3ad91b401b8f2400fb65944c79712
|
function mosaic = sift_mosaic(im1, im2)
% SIFT_MOSAIC Demonstrates matching two images using SIFT and RANSAC
%
% SIFT_MOSAIC demonstrates matching two images based on SIFT
% features and RANSAC and computing their mosaic.
%
% SIFT_MOSAIC by itself runs the algorithm on two standard test
% images. Use SIFT_MOSAIC(IM1,IM2) to compute the mosaic of two
% custom images IM1 and IM2.
% AUTORIGHTS
if nargin == 0
im1 = imread(fullfile(vl_root, 'data', 'river1.jpg')) ;
im2 = imread(fullfile(vl_root, 'data', 'river2.jpg')) ;
end
% make single
im1 = im2single(im1) ;
im2 = im2single(im2) ;
% make grayscale
if size(im1,3) > 1, im1g = rgb2gray(im1) ; else im1g = im1 ; end
if size(im2,3) > 1, im2g = rgb2gray(im2) ; else im2g = im2 ; end
% --------------------------------------------------------------------
% SIFT matches
% --------------------------------------------------------------------
[f1,d1] = vl_sift(im1g) ;
[f2,d2] = vl_sift(im2g) ;
[matches, scores] = vl_ubcmatch(d1,d2) ;
numMatches = size(matches,2) ;
X1 = f1(1:2,matches(1,:)) ; X1(3,:) = 1 ;
X2 = f2(1:2,matches(2,:)) ; X2(3,:) = 1 ;
% --------------------------------------------------------------------
% RANSAC with homography model
% --------------------------------------------------------------------
clear H score ok ;
for t = 1:100
% estimate homograpyh
subset = vl_colsubset(1:numMatches, 4) ;
A = [] ;
for i = subset
A = cat(1, A, kron(X1(:,i)', vl_hat(X2(:,i)))) ;
end
[U,S,V] = svd(A) ;
H{t} = reshape(V(:,9),3,3) ;
% score homography
X2_ = H{t} * X1 ;
du = X2_(1,:)./X2_(3,:) - X2(1,:)./X2(3,:) ;
dv = X2_(2,:)./X2_(3,:) - X2(2,:)./X2(3,:) ;
ok{t} = (du.*du + dv.*dv) < 6*6 ;
score(t) = sum(ok{t}) ;
end
[score, best] = max(score) ;
H = H{best} ;
ok = ok{best} ;
% --------------------------------------------------------------------
% Optional refinement
% --------------------------------------------------------------------
function err = residual(H)
u = H(1) * X1(1,ok) + H(4) * X1(2,ok) + H(7) ;
v = H(2) * X1(1,ok) + H(5) * X1(2,ok) + H(8) ;
d = H(3) * X1(1,ok) + H(6) * X1(2,ok) + 1 ;
du = X2(1,ok) - u ./ d ;
dv = X2(2,ok) - v ./ d ;
err = sum(du.*du + dv.*dv) ;
end
if exist('fminsearch') == 2
H = H / H(3,3) ;
opts = optimset('Display', 'none', 'TolFun', 1e-8, 'TolX', 1e-8) ;
H(1:8) = fminsearch(@residual, H(1:8)', opts) ;
else
warning('Refinement disabled as fminsearch was not found.') ;
end
% --------------------------------------------------------------------
% Show matches
% --------------------------------------------------------------------
dh1 = max(size(im2,1)-size(im1,1),0) ;
dh2 = max(size(im1,1)-size(im2,1),0) ;
figure(1) ; clf ;
subplot(2,1,1) ;
imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ;
o = size(im1,2) ;
line([f1(1,matches(1,:));f2(1,matches(2,:))+o], ...
[f1(2,matches(1,:));f2(2,matches(2,:))]) ;
title(sprintf('%d tentative matches', numMatches)) ;
axis image off ;
subplot(2,1,2) ;
imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ;
o = size(im1,2) ;
line([f1(1,matches(1,ok));f2(1,matches(2,ok))+o], ...
[f1(2,matches(1,ok));f2(2,matches(2,ok))]) ;
title(sprintf('%d (%.2f%%) inliner matches out of %d', ...
sum(ok), ...
100*sum(ok)/numMatches, ...
numMatches)) ;
axis image off ;
drawnow ;
% --------------------------------------------------------------------
% Mosaic
% --------------------------------------------------------------------
box2 = [1 size(im2,2) size(im2,2) 1 ;
1 1 size(im2,1) size(im2,1) ;
1 1 1 1 ] ;
box2_ = inv(H) * box2 ;
box2_(1,:) = box2_(1,:) ./ box2_(3,:) ;
box2_(2,:) = box2_(2,:) ./ box2_(3,:) ;
ur = min([1 box2_(1,:)]):max([size(im1,2) box2_(1,:)]) ;
vr = min([1 box2_(2,:)]):max([size(im1,1) box2_(2,:)]) ;
[u,v] = meshgrid(ur,vr) ;
im1_ = vl_imwbackward(im2double(im1),u,v) ;
z_ = H(3,1) * u + H(3,2) * v + H(3,3) ;
u_ = (H(1,1) * u + H(1,2) * v + H(1,3)) ./ z_ ;
v_ = (H(2,1) * u + H(2,2) * v + H(2,3)) ./ z_ ;
im2_ = vl_imwbackward(im2double(im2),u_,v_) ;
mass = ~isnan(im1_) + ~isnan(im2_) ;
im1_(isnan(im1_)) = 0 ;
im2_(isnan(im2_)) = 0 ;
mosaic = (im1_ + im2_) ./ mass ;
figure(2) ; clf ;
imagesc(mosaic) ; axis image off ;
title('Mosaic') ;
if nargout == 0, clear mosaic ; end
end
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
encodeImage.m
|
.m
|
SceneRecognition-master/code/vlfeat/apps/recognition/encodeImage.m
| 5,278 |
utf_8
|
5d9dc6161995b8e10366b5649bf4fda4
|
function descrs = encodeImage(encoder, im, varargin)
% ENCODEIMAGE Apply an encoder to an image
% DESCRS = ENCODEIMAGE(ENCODER, IM) applies the ENCODER
% to image IM, returning a corresponding code vector PSI.
%
% IM can be an image, the path to an image, or a cell array of
% the same, to operate on multiple images.
%
% ENCODEIMAGE(ENCODER, IM, CACHE) utilizes the specified CACHE
% directory to store encodings for the given images. The cache
% is used only if the images are specified as file names.
%
% See also: TRAINENCODER().
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.cacheDir = [] ;
opts.cacheChunkSize = 512 ;
opts = vl_argparse(opts,varargin) ;
if ~iscell(im), im = {im} ; end
% break the computation into cached chunks
startTime = tic ;
descrs = cell(1, numel(im)) ;
numChunks = ceil(numel(im) / opts.cacheChunkSize) ;
for c = 1:numChunks
n = min(opts.cacheChunkSize, numel(im) - (c-1)*opts.cacheChunkSize) ;
chunkPath = fullfile(opts.cacheDir, sprintf('chunk-%03d.mat',c)) ;
if ~isempty(opts.cacheDir) && exist(chunkPath)
fprintf('%s: loading descriptors from %s\n', mfilename, chunkPath) ;
load(chunkPath, 'data') ;
else
range = (c-1)*opts.cacheChunkSize + (1:n) ;
fprintf('%s: processing a chunk of %d images (%3d of %3d, %5.1fs to go)\n', ...
mfilename, numel(range), ...
c, numChunks, toc(startTime) / (c - 1) * (numChunks - c + 1)) ;
data = processChunk(encoder, im(range)) ;
if ~isempty(opts.cacheDir)
save(chunkPath, 'data') ;
end
end
descrs{c} = data ;
clear data ;
end
descrs = cat(2,descrs{:}) ;
% --------------------------------------------------------------------
function psi = processChunk(encoder, im)
% --------------------------------------------------------------------
psi = cell(1,numel(im)) ;
if numel(im) > 1 & matlabpool('size') > 1
parfor i = 1:numel(im)
psi{i} = encodeOne(encoder, im{i}) ;
end
else
% avoiding parfor makes debugging easier
for i = 1:numel(im)
psi{i} = encodeOne(encoder, im{i}) ;
end
end
psi = cat(2, psi{:}) ;
% --------------------------------------------------------------------
function psi = encodeOne(encoder, im)
% --------------------------------------------------------------------
im = encoder.readImageFn(im) ;
features = encoder.extractorFn(im) ;
imageSize = size(im) ;
psi = {} ;
for i = 1:size(encoder.subdivisions,2)
minx = encoder.subdivisions(1,i) * imageSize(2) ;
miny = encoder.subdivisions(2,i) * imageSize(1) ;
maxx = encoder.subdivisions(3,i) * imageSize(2) ;
maxy = encoder.subdivisions(4,i) * imageSize(1) ;
ok = ...
minx <= features.frame(1,:) & features.frame(1,:) < maxx & ...
miny <= features.frame(2,:) & features.frame(2,:) < maxy ;
descrs = encoder.projection * bsxfun(@minus, ...
features.descr(:,ok), ...
encoder.projectionCenter) ;
if encoder.renormalize
descrs = bsxfun(@times, descrs, 1./max(1e-12, sqrt(sum(descrs.^2)))) ;
end
w = size(im,2) ;
h = size(im,1) ;
frames = features.frame(1:2,:) ;
frames = bsxfun(@times, bsxfun(@minus, frames, [w;h]/2), 1./[w;h]) ;
descrs = extendDescriptorsWithGeometry(encoder.geometricExtension, frames, descrs) ;
switch encoder.type
case 'bovw'
[words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ...
descrs, ...
'MaxComparisons', 100) ;
z = vl_binsum(zeros(encoder.numWords,1), 1, double(words)) ;
z = sqrt(z) ;
case 'fv'
z = vl_fisher(descrs, ...
encoder.means, ...
encoder.covariances, ...
encoder.priors, ...
'Improved') ;
case 'vlad'
[words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ...
descrs, ...
'MaxComparisons', 15) ;
assign = zeros(encoder.numWords, numel(words), 'single') ;
assign(sub2ind(size(assign), double(words), 1:numel(words))) = 1 ;
z = vl_vlad(descrs, ...
encoder.words, ...
assign, ...
'SquareRoot', ...
'NormalizeComponents') ;
end
z = z / max(sqrt(sum(z.^2)), 1e-12) ;
psi{i} = z(:) ;
end
psi = cat(1, psi{:}) ;
% --------------------------------------------------------------------
function psi = getFromCache(name, cache)
% --------------------------------------------------------------------
[drop, name] = fileparts(name) ;
cachePath = fullfile(cache, [name '.mat']) ;
if exist(cachePath, 'file')
data = load(cachePath) ;
psi = data.psi ;
else
psi = [] ;
end
% --------------------------------------------------------------------
function storeToCache(name, cache, psi)
% --------------------------------------------------------------------
[drop, name] = fileparts(name) ;
cachePath = fullfile(cache, [name '.mat']) ;
vl_xmkdir(cache) ;
data.psi = psi ;
save(cachePath, '-STRUCT', 'data') ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
experiments.m
|
.m
|
SceneRecognition-master/code/vlfeat/apps/recognition/experiments.m
| 6,905 |
utf_8
|
1e4a4911eed4a451b9488b9e6cc9b39c
|
function experiments()
% EXPERIMENTS Run image classification experiments
% The experimens download a number of benchmark datasets in the
% 'data/' subfolder. Make sure that there are several GBs of
% space available.
%
% By default, experiments run with a lite option turned on. This
% quickly runs all of them on tiny subsets of the actual data.
% This is used only for testing; to run the actual experiments,
% set the lite variable to false.
%
% Running all the experiments is a slow process. Using parallel
% MATLAB and several cores/machiens is suggested.
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
lite = true ;
clear ex ;
ex(1).prefix = 'fv-aug' ;
ex(1).trainOpts = {'C', 10} ;
ex(1).datasets = {'fmd', 'scene67'} ;
ex(1).seed = 1 ;
ex(1).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(2) = ex(1) ;
ex(2).datasets = {'caltech101'} ;
ex(2).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(3) = ex(1) ;
ex(3).datasets = {'voc07'} ;
ex(3).C = 1 ;
ex(4) = ex(1) ;
ex(4).prefix = 'vlad-aug' ;
ex(4).opts = {...
'type', 'vlad', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 100, ...
'whitening', true, ...
'whiteningRegul', 0.01, ...
'renormalize', true, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(5) = ex(4) ;
ex(5).datasets = {'caltech101'} ;
ex(5).opts{end} = ex(2).opts{end} ;
ex(6) = ex(4) ;
ex(6).datasets = {'voc07'} ;
ex(6).C = 1 ;
ex(7) = ex(1) ;
ex(7).prefix = 'bovw-aug' ;
ex(7).opts = {...
'type', 'bovw', ...
'numWords', 4096, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 100, ...
'whitening', true, ...
'whiteningRegul', 0.01, ...
'renormalize', true, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(8) = ex(7) ;
ex(8).datasets = {'caltech101'} ;
ex(8).opts{end} = ex(2).opts{end} ;
ex(9) = ex(7) ;
ex(9).datasets = {'voc07'} ;
ex(9).C = 1 ;
ex(10).prefix = 'fv' ;
ex(10).trainOpts = {'C', 10} ;
ex(10).datasets = {'fmd', 'scene67'} ;
ex(10).seed = 1 ;
ex(10).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'none', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(11) = ex(10) ;
ex(11).datasets = {'caltech101'} ;
ex(11).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(12) = ex(10) ;
ex(12).datasets = {'voc07'} ;
ex(12).C = 1 ;
ex(13).prefix = 'fv-sp' ;
ex(13).trainOpts = {'C', 10} ;
ex(13).datasets = {'fmd', 'scene67'} ;
ex(13).seed = 1 ;
ex(13).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1', '3x1'}, ...
'geometricExtension', 'none', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(14) = ex(13) ;
ex(14).datasets = {'caltech101'} ;
ex(14).opts{6} = {'1x1', '2x2'} ;
ex(14).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(15) = ex(13) ;
ex(15).datasets = {'voc07'} ;
ex(15).C = 1 ;
if lite, tag = 'lite' ;
else, tag = 'ex' ; end
for i=1:numel(ex)
for j=1:numel(ex(i).datasets)
dataset = ex(i).datasets{j} ;
if ~isfield(ex(i), 'trainOpts') || ~iscell(ex(i).trainOpts)
ex(i).trainOpts = {} ;
end
traintest(...
'prefix', [tag '-' dataset '-' ex(i).prefix], ...
'seed', ex(i).seed, ...
'dataset', char(dataset), ...
'datasetDir', fullfile('data', dataset), ...
'lite', lite, ...
ex(i).trainOpts{:}, ...
'encoderParams', ex(i).opts) ;
end
end
% print HTML table
pf('<table>\n') ;
ph('method', 'VOC07', 'Caltech 101', 'Scene 67', 'FMD') ;
pr('FV', ...
ge([tag '-voc07-fv'],'ap11'), ...
ge([tag '-caltech101-fv']), ...
ge([tag '-scene67-fv']), ...
ge([tag '-fmd-fv'])) ;
pr('FV + aug.', ...
ge([tag '-voc07-fv-aug'],'ap11'), ...
ge([tag '-caltech101-fv-aug']), ...
ge([tag '-scene67-fv-aug']), ...
ge([tag '-fmd-fv-aug'])) ;
pr('FV + s.p.', ...
ge([tag '-voc07-fv-sp'],'ap11'), ...
ge([tag '-caltech101-fv-sp']), ...
ge([tag '-scene67-fv-sp']), ...
ge([tag '-fmd-fv-sp'])) ;
%pr('VLAD', ...
% ge([tag '-voc07-vlad'],'ap11'), ...
% ge([tag '-caltech101-vlad']), ...
% ge([tag '-scene67-vlad']), ...
% ge([tag '-fmd-vlad'])) ;
pr('VLAD + aug.', ...
ge([tag '-voc07-vlad-aug'],'ap11'), ...
ge([tag '-caltech101-vlad-aug']), ...
ge([tag '-scene67-vlad-aug']), ...
ge([tag '-fmd-vlad-aug'])) ;
%pr('VLAD+sp', ...
% ge([tag '-voc07-vlad-sp'],'ap11'), ...
% ge([tag '-caltech101-vlad-sp']), ...
% ge([tag '-scene67-vlad-sp']), ...
% ge([tag '-fmd-vlad-sp'])) ;
%pr('BOVW', ...
% ge([tag '-voc07-bovw'],'ap11'), ...
% ge([tag '-caltech101-bovw']), ...
% ge([tag '-scene67-bovw']), ...
% ge([tag '-fmd-bovw'])) ;
pr('BOVW + aug.', ...
ge([tag '-voc07-bovw-aug'],'ap11'), ...
ge([tag '-caltech101-bovw-aug']), ...
ge([tag '-scene67-bovw-aug']), ...
ge([tag '-fmd-bovw-aug'])) ;
%pr('BOVW+sp', ...
% ge([tag '-voc07-bovw-sp'],'ap11'), ...
% ge([tag '-caltech101-bovw-sp']), ...
% ge([tag '-scene67-bovw-sp']), ...
% ge([tag '-fmd-bovw-sp'])) ;
pf('</table>\n');
function pf(str)
fprintf(str) ;
function str = ge(name, format)
if nargin == 1, format = 'acc'; end
data = load(fullfile('data', name, 'result.mat')) ;
switch format
case 'acc'
str = sprintf('%.2f%% <span style="font-size:8px;">Acc</span>', mean(diag(data.confusion)) * 100) ;
case 'ap11'
str = sprintf('%.2f%% <span style="font-size:8px;">mAP</span>', mean(data.ap11) * 100) ;
end
function pr(varargin)
fprintf('<tr>') ;
for i=1:numel(varargin), fprintf('<td>%s</td>',varargin{i}) ; end
fprintf('</tr>\n') ;
function ph(varargin)
fprintf('<tr>') ;
for i=1:numel(varargin), fprintf('<th>%s</th>',varargin{i}) ; end
fprintf('</tr>\n') ;
|
github
|
MohamedAbdelsalam9/SceneRecognition-master
|
getDenseSIFT.m
|
.m
|
SceneRecognition-master/code/vlfeat/apps/recognition/getDenseSIFT.m
| 1,679 |
utf_8
|
2059c0a2a4e762226d89121408c6e51c
|
function features = getDenseSIFT(im, varargin)
% GETDENSESIFT Extract dense SIFT features
% FEATURES = GETDENSESIFT(IM) extract dense SIFT features from
% image IM.
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.scales = logspace(log10(1), log10(.25), 5) ;
opts.contrastthreshold = 0 ;
opts.step = 3 ;
opts.rootSift = false ;
opts.normalizeSift = true ;
opts.binSize = 8 ;
opts.geometry = [4 4 8] ;
opts.sigma = 0 ;
opts = vl_argparse(opts, varargin) ;
dsiftOpts = {'norm', 'fast', 'floatdescriptors', ...
'step', opts.step, ...
'size', opts.binSize, ...
'geometry', opts.geometry} ;
if size(im,3)>1, im = rgb2gray(im) ; end
im = im2single(im) ;
im = vl_imsmooth(im, opts.sigma) ;
for si = 1:numel(opts.scales)
im_ = imresize(im, opts.scales(si)) ;
[frames{si}, descrs{si}] = vl_dsift(im_, dsiftOpts{:}) ;
% root SIFT
if opts.rootSift
descrs{si} = sqrt(descrs{si}) ;
end
if opts.normalizeSift
descrs{si} = snorm(descrs{si}) ;
end
% zero low contrast descriptors
info.contrast{si} = frames{si}(3,:) ;
kill = info.contrast{si} < opts.contrastthreshold ;
descrs{si}(:,kill) = 0 ;
% store frames
frames{si}(1:2,:) = (frames{si}(1:2,:)-1) / opts.scales(si) + 1 ;
frames{si}(3,:) = opts.binSize / opts.scales(si) / 3 ;
end
features.frame = cat(2, frames{:}) ;
features.descr = cat(2, descrs{:}) ;
features.contrast = cat(2, info.contrast{:}) ;
function x = snorm(x)
x = bsxfun(@times, x, 1./max(1e-5,sqrt(sum(x.^2,1)))) ;
|
github
|
ColeLab/ColeAnticevicNetPartition-master
|
save.m
|
.m
|
ColeAnticevicNetPartition-master/code/gifti-1.6/@gifti/save.m
| 9,801 |
utf_8
|
d7999ec374bfbb32da9b38b849ef15ab
|
function save(this,filename,encoding)
% Save GIfTI object in a GIfTI format file
% FORMAT save(this,filename,encoding)
% this - GIfTI object
% filename - name of GIfTI file to be created [Default: 'untitled.gii']
% encoding - optional argument to specify encoding format, among
% ASCII, Base64Binary, GZipBase64Binary, ExternalFileBinary.
% [Default: 'GZipBase64Binary']
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: save.m 6516 2015-08-07 17:28:33Z guillaume $
% Check filename
%--------------------------------------------------------------------------
ext = '.gii';
if nargin == 1
filename = 'untitled';
end
[p,f,e] = fileparts(filename);
if ~ismember(lower(e),{ext})
e = ext;
end
filename = fullfile(p,[f e]);
% Open file for writing
%--------------------------------------------------------------------------
fid = fopen(filename,'wt');
if fid == -1
error('Unable to write file %s: permission denied.',filename);
end
% Write file
%--------------------------------------------------------------------------
if nargin < 3, encoding = 'GZipBase64Binary'; end
switch encoding
case {'ASCII','Base64Binary','GZipBase64Binary','ExternalFileBinary'}
otherwise
error('Unknown encoding.');
end
fid = save_gii(fid,this,encoding);
% Close file
%--------------------------------------------------------------------------
fclose(fid);
%==========================================================================
% function fid = save_gii(fid,this,encoding)
%==========================================================================
function fid = save_gii(fid,this,encoding)
% Defaults for DataArray's attributes
%--------------------------------------------------------------------------
[unused,unused,mach] = fopen(fid);
if strncmp('ieee-be',mach,7)
def.Endian = 'BigEndian';
elseif strncmp('ieee-le',mach,7)
def.Endian = 'LittleEndian';
else
error('[GIFTI] Unknown byte order "%s".',mach);
end
def.Encoding = encoding;
def.Intent = 'NIFTI_INTENT_NONE';
def.DataType = 'NIFTI_TYPE_FLOAT32';
def.ExternalFileName = '';
def.ExternalFileOffset = '';
def.offset = 0;
% Edit object DataArray attributes
%--------------------------------------------------------------------------
for i=1:length(this.data)
% Revert the dimension storage
d = this.data{i}.attributes.Dim;
if numel(d) > 1 && d(end) == 1
d = d(1:end-1);
end
this.data{i}.attributes = rmfield(this.data{i}.attributes,'Dim');
this.data{i}.attributes.Dimensionality = num2str(length(d));
for j=1:length(d)
this.data{i}.attributes.(sprintf('Dim%d',j-1)) = num2str(d(j));
end
% Enforce some conventions
this.data{i}.attributes.ArrayIndexingOrder = 'ColumnMajorOrder';
if ~isfield(this.data{i}.attributes,'DataType') || ...
isempty(this.data{i}.attributes.DataType)
warning('DataType set to default: %s', def.DataType);
this.data{i}.attributes.DataType = def.DataType;
end
if ~isfield(this.data{i}.attributes,'Intent') || ...
isempty(this.data{i}.attributes.Intent)
warning('Intent code set to default: %s', def.Intent);
this.data{i}.attributes.Intent = def.Intent;
end
this.data{i}.attributes.Encoding = def.Encoding;
this.data{i}.attributes.Endian = def.Endian;
this.data{i}.attributes.ExternalFileName = def.ExternalFileName;
this.data{i}.attributes.ExternalFileOffset = def.ExternalFileOffset;
switch this.data{i}.attributes.Encoding
case {'ASCII', 'Base64Binary','GZipBase64Binary' }
case 'ExternalFileBinary'
extfilename = this.data{i}.attributes.ExternalFileName;
if isempty(extfilename)
[p,f] = fileparts(fopen(fid));
extfilename = [f '.dat'];
end
[p,f,e] = fileparts(extfilename);
this.data{i}.attributes.ExternalFileName = fullfile(fileparts(fopen(fid)),[f e]);
this.data{i}.attributes.ExternalFileOffset = num2str(def.offset);
otherwise
error('[GIFTI] Unknown data encoding: %s.',this.data{i}.attributes.Encoding);
end
end
% Prolog
%--------------------------------------------------------------------------
fprintf(fid,'<?xml version="1.0" encoding="UTF-8"?>\n');
fprintf(fid,'<!DOCTYPE GIFTI SYSTEM "http://www.nitrc.org/frs/download.php/115/gifti.dtd">\n');
fprintf(fid,'<GIFTI Version="1.0" NumberOfDataArrays="%d">\n',numel(this.data));
o = @(x) blanks(x*3);
% MetaData
%--------------------------------------------------------------------------
fprintf(fid,'%s<MetaData',o(1));
if isempty(this.metadata)
fprintf(fid,'/>\n');
else
fprintf(fid,'>\n');
for i=1:length(this.metadata)
fprintf(fid,'%s<MD>\n',o(2));
fprintf(fid,'%s<Name><![CDATA[%s]]></Name>\n',o(3),...
this.metadata(i).name);
fprintf(fid,'%s<Value><![CDATA[%s]]></Value>\n',o(3),...
this.metadata(i).value);
fprintf(fid,'%s</MD>\n',o(2));
end
fprintf(fid,'%s</MetaData>\n',o(1));
end
% LabelTable
%--------------------------------------------------------------------------
fprintf(fid,'%s<LabelTable',o(1));
if isempty(this.label)
fprintf(fid,'/>\n');
else
fprintf(fid,'>\n');
for i=1:length(this.label.name)
if ~all(isnan(this.label.rgba(i,:)))
label_rgba = sprintf(' Red="%f" Green="%f" Blue="%f" Alpha="%f"',...
this.label.rgba(i,:));
else
label_rgba = '';
end
fprintf(fid,'%s<Label Key="%d"%s><![CDATA[%s]]></Label>\n',o(2),...
this.label.key(i), label_rgba, this.label.name{i});
end
fprintf(fid,'%s</LabelTable>\n',o(1));
end
% DataArray
%--------------------------------------------------------------------------
for i=1:length(this.data)
fprintf(fid,'%s<DataArray',o(1));
if def.offset
this.data{i}.attributes.ExternalFileOffset = num2str(def.offset);
end
fn = sort(fieldnames(this.data{i}.attributes));
oo = repmat({o(5) '\n'},length(fn),1); oo{1} = ' '; oo{end} = '';
for j=1:length(fn)
if strcmp(fn{j},'ExternalFileName')
[p,f,e] = fileparts(this.data{i}.attributes.(fn{j}));
attval = [f e];
else
attval = this.data{i}.attributes.(fn{j});
end
fprintf(fid,'%s%s="%s"%s',oo{j,1},...
fn{j},attval,sprintf(oo{j,2}));
end
fprintf(fid,'>\n');
% MetaData
%----------------------------------------------------------------------
fprintf(fid,'%s<MetaData>\n',o(2));
for j=1:length(this.data{i}.metadata)
fprintf(fid,'%s<MD>\n',o(3));
fprintf(fid,'%s<Name><![CDATA[%s]]></Name>\n',o(4),...
this.data{i}.metadata(j).name);
fprintf(fid,'%s<Value><![CDATA[%s]]></Value>\n',o(4),...
this.data{i}.metadata(j).value);
fprintf(fid,'%s</MD>\n',o(3));
end
fprintf(fid,'%s</MetaData>\n',o(2));
% CoordinateSystemTransformMatrix
%----------------------------------------------------------------------
for j=1:length(this.data{i}.space)
fprintf(fid,'%s<CoordinateSystemTransformMatrix>\n',o(2));
fprintf(fid,'%s<DataSpace><![CDATA[%s]]></DataSpace>\n',o(3),...
this.data{i}.space(j).DataSpace);
fprintf(fid,'%s<TransformedSpace><![CDATA[%s]]></TransformedSpace>\n',o(3),...
this.data{i}.space(j).TransformedSpace);
fprintf(fid,'%s<MatrixData>%s</MatrixData>\n',o(3),...
sprintf('%f ',this.data{i}.space(j).MatrixData'));
fprintf(fid,'%s</CoordinateSystemTransformMatrix>\n',o(2));
end
% Data (saved using MATLAB's ColumnMajorOrder)
%----------------------------------------------------------------------
fprintf(fid,'%s<Data>',o(2));
tp = getdict;
try
tp = tp.(this.data{i}.attributes.DataType);
catch
error('[GIFTI] Unknown DataType.');
end
switch this.data{i}.attributes.Encoding
case 'ASCII'
fprintf(fid, [tp.format ' '], this.data{i}.data);
case 'Base64Binary'
fprintf(fid,base64encode(typecast(this.data{i}.data(:),'uint8')));
% uses native machine format
case 'GZipBase64Binary'
fprintf(fid,base64encode(zstream('C',typecast(this.data{i}.data(:),'uint8'))));
% uses native machine format
case 'ExternalFileBinary'
extfilename = this.data{i}.attributes.ExternalFileName;
dat = this.data{i}.data;
if isa(dat,'file_array')
dat = subsref(dat,substruct('()',repmat({':'},1,numel(dat.dim))));
end
if ~def.offset
fide = fopen(extfilename,'w'); % uses native machine format
else
fide = fopen(extfilename,'a'); % uses native machine format
end
if fide == -1
error('Unable to write file %s: permission denied.',extfilename);
end
fseek(fide,0,1);
fwrite(fide,dat,tp.class);
def.offset = ftell(fide);
fclose(fide);
otherwise
error('[GIFTI] Unknown data encoding.');
end
fprintf(fid,'</Data>\n');
fprintf(fid,'%s</DataArray>\n',o(1));
end
fprintf(fid,'</GIFTI>\n');
|
github
|
ColeLab/ColeAnticevicNetPartition-master
|
gifti.m
|
.m
|
ColeAnticevicNetPartition-master/code/gifti-1.6/@gifti/gifti.m
| 3,918 |
utf_8
|
59128f02da0486e8123d2abf2d645bf1
|
function this = gifti(varargin)
% GIfTI Geometry file format class
% Geometry format under the Neuroimaging Informatics Technology Initiative
% (NIfTI):
% http://www.nitrc.org/projects/gifti/
% http://nifti.nimh.nih.gov/
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: gifti.m 6347 2015-02-24 17:59:16Z guillaume $
switch nargin
case 0
this = giftistruct;
this = class(this,'gifti');
case 1
if isa(varargin{1},'gifti')
this = varargin{1};
elseif isstruct(varargin{1})
f = {'faces', 'face', 'tri' 'vertices', 'vert', 'pnt', 'cdata', 'indices'};
ff = {'faces', 'faces', 'faces', 'vertices', 'vertices', 'vertices', 'cdata', 'indices'};
[c, ia] = intersect(f,fieldnames(varargin{1}));
if ~isempty(c)
this = gifti;
for i=1:length(c)
this = subsasgn(this,...
struct('type','.','subs',ff{ia(i)}),...
varargin{1}.(c{i}));
end
elseif isempty(setxor(fieldnames(varargin{1}),...
{'metadata','label','data'}))
this = class(varargin{1},'gifti');
else
error('[GIFTI] Invalid structure.');
end
elseif ishandle(varargin{1})
this = struct('vertices',get(varargin{1},'Vertices'), ...
'faces', get(varargin{1},'Faces'));
if ~isempty(get(varargin{1},'FaceVertexCData'));
this.cdata = get(varargin{1},'FaceVertexCData');
end
this = gifti(this);
elseif isnumeric(varargin{1})
this = gifti;
this = subsasgn(this,...
struct('type','.','subs','cdata'),...
varargin{1});
elseif ischar(varargin{1})
if size(varargin{1},1)>1
this = gifti(cellstr(varargin{1}));
return;
end
[p,n,e] = fileparts(varargin{1});
if strcmpi(e,'.mat')
try
this = gifti(load(varargin{1}));
catch
error('[GIFTI] Loading of file %s failed.', varargin{1});
end
elseif strcmpi(e,'.asc') || strcmpi(e,'.srf')
this = read_freesurfer_file(varargin{1});
this = gifti(this);
else
this = read_gifti_file_standalone(varargin{1},giftistruct);
this = class(this,'gifti');
end
elseif iscellstr(varargin{1})
fnames = varargin{1};
this(numel(fnames)) = giftistruct;
this = class(this,'gifti');
for i=1:numel(fnames)
this(i) = gifti(fnames{i});
end
else
error('[GIFTI] Invalid object construction.');
end
otherwise
error('[GIFTI] Invalid object construction.');
end
%==========================================================================
function s = giftistruct
s = struct(...
'metadata', ...
struct(...
'name', {}, ...
'value', {} ...
), ...
'label', ...
struct(...
'name', {}, ...
'index', {} ...
), ...
'data', ...
struct(...
'attributes', {}, ...
'metadata', struct('name',{}, 'value',{}), ...
'space', {}, ...
'data', {} ...
) ...
);
|
github
|
ColeLab/ColeAnticevicNetPartition-master
|
saveas.m
|
.m
|
ColeAnticevicNetPartition-master/code/gifti-1.6/@gifti/saveas.m
| 13,730 |
utf_8
|
93c2b293811510f3a6bd3359f2f5e8d5
|
function saveas(this,filename,format)
% Save GIfTI object in external file format
% FORMAT saveas(this,filename,format)
% this - GIfTI object
% filename - name of file to be created [Default: 'untitled.vtk']
% format - optional argument to specify encoding format, among
% VTK (.vtk,.vtp), Collada (.dae), IDTF (.idtf). [Default: VTK]
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id$
% Check filename and file format
%--------------------------------------------------------------------------
ext = '.vtk';
if nargin == 1
filename = ['untitled' ext];
else
if nargin == 3 && strcmpi(format,'collada')
ext = '.dae';
end
if nargin == 3 && strcmpi(format,'idtf')
ext = '.idtf';
end
if nargin == 3 && strncmpi(format,'vtk',3)
format = lower(format(5:end));
ext = '.vtk';
end
[p,f,e] = fileparts(filename);
if strcmpi(e,'.gii')
warning('Use save instead of saveas.');
save(this,filename);
return;
end
if ~ismember(lower(e),{ext})
warning('Changing file extension from %s to %s.',e,ext);
e = ext;
end
filename = fullfile(p,[f e]);
end
% Write file
%--------------------------------------------------------------------------
s = struct(this);
switch ext
case '.dae'
save_dae(s,filename);
case '.idtf'
save_idtf(s,filename);
case {'.vtk','.vtp'}
if nargin < 3, format = 'legacy-ascii'; end
mvtk_write(s,filename,format);
otherwise
error('Unknown file format.');
end
%==========================================================================
% function save_dae(s,filename)
%==========================================================================
function save_dae(s,filename)
o = @(x) blanks(x*3);
% Split the mesh into connected components
%--------------------------------------------------------------------------
try
C = spm_mesh_label(s.faces);
d = [];
for i=1:numel(unique(C))
d(i).faces = s.faces(C==i,:);
u = unique(d(i).faces);
d(i).vertices = s.vertices(u,:);
a = 1:max(d(i).faces(:));
a(u) = 1:size(d(i).vertices,1);
%a = sparse(1,double(u),1:1:size(d(i).vertices,1));
d(i).faces = a(d(i).faces);
end
s = d;
end
% Open file for writing
%--------------------------------------------------------------------------
fid = fopen(filename,'wt');
if fid == -1
error('Unable to write file %s: permission denied.',filename);
end
% Prolog & root of the Collada XML file
%--------------------------------------------------------------------------
fprintf(fid,'<?xml version="1.0"?>\n');
fprintf(fid,'<COLLADA xmlns="http://www.collada.org/2008/03/COLLADASchema" version="1.5.0">\n');
% Assets
%--------------------------------------------------------------------------
fprintf(fid,'%s<asset>\n',o(1));
fprintf(fid,'%s<contributor>\n',o(2));
fprintf(fid,'%s<author_website>%s</author_website>\n',o(3),...
'http://www.fil.ion.ucl.ac.uk/spm/');
fprintf(fid,'%s<authoring_tool>%s</authoring_tool>\n',o(3),'SPM');
fprintf(fid,'%s</contributor>\n',o(2));
fprintf(fid,'%s<created>%s</created>\n',o(2),datestr(now,'yyyy-mm-ddTHH:MM:SSZ'));
fprintf(fid,'%s<modified>%s</modified>\n',o(2),datestr(now,'yyyy-mm-ddTHH:MM:SSZ'));
fprintf(fid,'%s<unit name="millimeter" meter="0.001"/>\n',o(2));
fprintf(fid,'%s<up_axis>Z_UP</up_axis>\n',o(2));
fprintf(fid,'%s</asset>\n',o(1));
% Image, Materials, Effects
%--------------------------------------------------------------------------
%fprintf(fid,'%s<library_images/>\n',o(1));
fprintf(fid,'%s<library_materials>\n',o(1));
for i=1:numel(s)
fprintf(fid,'%s<material id="material%d" name="material%d">\n',o(2),i,i);
fprintf(fid,'%s<instance_effect url="#material%d-effect"/>\n',o(3),i);
fprintf(fid,'%s</material>\n',o(2));
end
fprintf(fid,'%s</library_materials>\n',o(1));
fprintf(fid,'%s<library_effects>\n',o(1));
for i=1:numel(s)
fprintf(fid,'%s<effect id="material%d-effect" name="material%d-effect">\n',o(2),i,i);
fprintf(fid,'%s<profile_COMMON>\n',o(3));
fprintf(fid,'%s<technique sid="COMMON">\n',o(4));
fprintf(fid,'%s<lambert>\n',o(5));
fprintf(fid,'%s<emission>\n',o(6));
fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0 0 0 1]);
fprintf(fid,'%s</emission>\n',o(6));
fprintf(fid,'%s<ambient>\n',o(6));
fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0 0 0 1]);
fprintf(fid,'%s</ambient>\n',o(6));
fprintf(fid,'%s<diffuse>\n',o(6));
fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0.5 0.5 0.5 1]);
fprintf(fid,'%s</diffuse>\n',o(6));
fprintf(fid,'%s<transparent>\n',o(6));
fprintf(fid,'%s<color>%d %d %d %d</color>\n',o(7),[1 1 1 1]);
fprintf(fid,'%s</transparent>\n',o(6));
fprintf(fid,'%s<transparency>\n',o(6));
fprintf(fid,'%s<float>%f</float>\n',o(7),0);
fprintf(fid,'%s</transparency>\n',o(6));
fprintf(fid,'%s</lambert>\n',o(5));
fprintf(fid,'%s</technique>\n',o(4));
fprintf(fid,'%s</profile_COMMON>\n',o(3));
fprintf(fid,'%s</effect>\n',o(2));
end
fprintf(fid,'%s</library_effects>\n',o(1));
% Geometry
%--------------------------------------------------------------------------
fprintf(fid,'%s<library_geometries>\n',o(1));
for i=1:numel(s)
fprintf(fid,'%s<geometry id="shape%d" name="shape%d">\n',o(2),i,i);
fprintf(fid,'%s<mesh>\n',o(3));
fprintf(fid,'%s<source id="shape%d-positions">\n',o(4),i);
fprintf(fid,'%s<float_array id="shape%d-positions-array" count="%d">',o(5),i,numel(s(i).vertices));
fprintf(fid,'%f ',reshape(s(i).vertices',1,[]));
fprintf(fid,'</float_array>\n');
fprintf(fid,'%s<technique_common>\n',o(5));
fprintf(fid,'%s<accessor count="%d" offset="0" source="#shape%d-positions-array" stride="3">\n',o(6),size(s(i).vertices,1),i);
fprintf(fid,'%s<param name="X" type="float" />\n',o(7));
fprintf(fid,'%s<param name="Y" type="float" />\n',o(7));
fprintf(fid,'%s<param name="Z" type="float" />\n',o(7));
fprintf(fid,'%s</accessor>\n',o(6));
fprintf(fid,'%s</technique_common>\n',o(5));
fprintf(fid,'%s</source>\n',o(4));
fprintf(fid,'%s<vertices id="shape%d-vertices">\n',o(4),i);
fprintf(fid,'%s<input semantic="POSITION" source="#shape%d-positions"/>\n',o(5),i);
fprintf(fid,'%s</vertices>\n',o(4));
fprintf(fid,'%s<triangles material="material%d" count="%d">\n',o(4),i,size(s(i).faces,1));
fprintf(fid,'%s<input semantic="VERTEX" source="#shape%d-vertices" offset="0"/>\n',o(5),i);
fprintf(fid,'%s<p>',o(5));
fprintf(fid,'%d ',reshape(s(i).faces',1,[])-1);
fprintf(fid,'</p>\n');
fprintf(fid,'%s</triangles>\n',o(4));
fprintf(fid,'%s</mesh>\n',o(3));
fprintf(fid,'%s</geometry>\n',o(2));
end
fprintf(fid,'%s</library_geometries>\n',o(1));
% Scene
%--------------------------------------------------------------------------
fprintf(fid,'%s<library_visual_scenes>\n',o(1));
fprintf(fid,'%s<visual_scene id="VisualSceneNode" name="SceneNode">\n',o(2));
for i=1:numel(s)
fprintf(fid,'%s<node id="node%d">\n',o(3),i);
fprintf(fid,'%s<instance_geometry url="#shape%d">\n',o(4),i);
fprintf(fid,'%s<bind_material>\n',o(5));
fprintf(fid,'%s<technique_common>\n',o(6));
fprintf(fid,'%s<instance_material symbol="material%d" target="#material%d"/>\n',o(7),i,i);
fprintf(fid,'%s</technique_common>\n',o(6));
fprintf(fid,'%s</bind_material>\n',o(5));
fprintf(fid,'%s</instance_geometry>\n',o(4));
fprintf(fid,'%s</node>\n',o(3));
end
fprintf(fid,'%s</visual_scene>\n',o(2));
fprintf(fid,'%s</library_visual_scenes>\n',o(1));
fprintf(fid,'%s<scene>\n',o(1));
fprintf(fid,'%s<instance_visual_scene url="#VisualSceneNode" />\n',o(2));
fprintf(fid,'%s</scene>\n',o(1));
% End of XML
%--------------------------------------------------------------------------
fprintf(fid,'</COLLADA>\n');
% Close file
%--------------------------------------------------------------------------
fclose(fid);
%==========================================================================
% function save_idtf(s,filename)
%==========================================================================
function save_idtf(s,filename)
o = @(x) blanks(x*3);
% Compute normals
%--------------------------------------------------------------------------
if ~isfield(s,'normals')
try
s.normals = spm_mesh_normals(...
struct('vertices',s.vertices,'faces',s.faces),true);
catch
s.normals = [];
end
end
% Split the mesh into connected components
%--------------------------------------------------------------------------
try
C = spm_mesh_label(s.faces);
d = [];
try
if size(s.cdata,2) == 1 && (any(s.cdata>1) || any(s.cdata<0))
mi = min(s.cdata); ma = max(s.cdata);
s.cdata = (s.cdata-mi)/ (ma-mi);
else
end
end
for i=1:numel(unique(C))
d(i).faces = s.faces(C==i,:);
u = unique(d(i).faces);
d(i).vertices = s.vertices(u,:);
d(i).normals = s.normals(u,:);
a = 1:max(d(i).faces(:));
a(u) = 1:size(d(i).vertices,1);
%a = sparse(1,double(u),1:1:size(d(i).vertices,1));
d(i).faces = a(d(i).faces);
d(i).mat = s.mat;
try
d(i).cdata = s.cdata(u,:);
if size(d(i).cdata,2) == 1
d(i).cdata = repmat(d(i).cdata,1,3);
end
end
end
s = d;
end
% Open file for writing
%--------------------------------------------------------------------------
fid = fopen(filename,'wt');
if fid == -1
error('Unable to write file %s: permission denied.',filename);
end
% FILE_HEADER
%--------------------------------------------------------------------------
fprintf(fid,'FILE_FORMAT "IDTF"\n');
fprintf(fid,'FORMAT_VERSION 100\n\n');
% NODES
%--------------------------------------------------------------------------
for i=1:numel(s)
fprintf(fid,'NODE "MODEL" {\n');
fprintf(fid,'%sNODE_NAME "%s"\n',o(1),sprintf('Mesh%04d',i));
fprintf(fid,'%sPARENT_LIST {\n',o(1));
fprintf(fid,'%sPARENT_COUNT %d\n',o(2),1);
fprintf(fid,'%sPARENT %d {\n',o(2),0);
fprintf(fid,'%sPARENT_NAME "%s"\n',o(3),'<NULL>');
fprintf(fid,'%sPARENT_TM {\n',o(3));
I = s(i).mat; % eye(4);
for j=1:size(I,2)
fprintf(fid,'%s',o(4)); fprintf(fid,'%f ',I(:,j)'); fprintf(fid,'\n');
end
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%s}\n',o(2));
fprintf(fid,'%s}\n',o(1));
fprintf(fid,'%sRESOURCE_NAME "%s"\n',o(1),sprintf('Mesh%04d',i));
%fprintf(fid,'%sMODEL_VISIBILITY "BOTH"\n',o(1));
fprintf(fid,'}\n\n');
end
% NODE_RESOURCES
%--------------------------------------------------------------------------
for i=1:numel(s)
fprintf(fid,'RESOURCE_LIST "MODEL" {\n');
fprintf(fid,'%sRESOURCE_COUNT %d\n',o(1),1);
fprintf(fid,'%sRESOURCE %d {\n',o(1),0);
fprintf(fid,'%sRESOURCE_NAME "%s"\n',o(2),sprintf('Mesh%04d',i));
fprintf(fid,'%sMODEL_TYPE "MESH"\n',o(2));
fprintf(fid,'%sMESH {\n',o(2));
fprintf(fid,'%sFACE_COUNT %d\n',o(3),size(s(i).faces,1));
fprintf(fid,'%sMODEL_POSITION_COUNT %d\n',o(3),size(s(i).vertices,1));
fprintf(fid,'%sMODEL_NORMAL_COUNT %d\n',o(3),size(s(i).normals,1));
if ~isfield(s(i),'cdata') || isempty(s(i).cdata)
c = 0;
else
c = size(s(i).cdata,1);
end
fprintf(fid,'%sMODEL_DIFFUSE_COLOR_COUNT %d\n',o(3),c);
fprintf(fid,'%sMODEL_SPECULAR_COLOR_COUNT %d\n',o(3),0);
fprintf(fid,'%sMODEL_TEXTURE_COORD_COUNT %d\n',o(3),0);
fprintf(fid,'%sMODEL_BONE_COUNT %d\n',o(3),0);
fprintf(fid,'%sMODEL_SHADING_COUNT %d\n',o(3),1);
fprintf(fid,'%sMODEL_SHADING_DESCRIPTION_LIST {\n',o(3));
fprintf(fid,'%sSHADING_DESCRIPTION %d {\n',o(4),0);
fprintf(fid,'%sTEXTURE_LAYER_COUNT %d\n',o(5),0);
fprintf(fid,'%sSHADER_ID %d\n',o(5),0);
fprintf(fid,'%s}\n',o(4));
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMESH_FACE_POSITION_LIST {\n',o(3));
fprintf(fid,'%d %d %d\n',s(i).faces'-1);
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMESH_FACE_NORMAL_LIST {\n',o(3));
fprintf(fid,'%d %d %d\n',s(i).faces'-1);
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMESH_FACE_SHADING_LIST {\n',o(3));
fprintf(fid,'%d\n',zeros(size(s(i).faces,1),1));
fprintf(fid,'%s}\n',o(3));
if c
fprintf(fid,'%sMESH_FACE_DIFFUSE_COLOR_LIST {\n',o(3));
fprintf(fid,'%d %d %d\n',s(i).faces'-1);
fprintf(fid,'%s}\n',o(3));
end
fprintf(fid,'%sMODEL_POSITION_LIST {\n',o(3));
fprintf(fid,'%f %f %f\n',s(i).vertices');
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMODEL_NORMAL_LIST {\n',o(3));
fprintf(fid,'%f %f %f\n',s(i).normals');
fprintf(fid,'%s}\n',o(3));
if c
fprintf(fid,'%sMODEL_DIFFUSE_COLOR_LIST {\n',o(3));
fprintf(fid,'%f %f %f\n',s(i).cdata');
fprintf(fid,'%s}\n',o(3));
end
fprintf(fid,'%s}\n',o(2));
fprintf(fid,'%s}\n',o(1));
fprintf(fid,'}\n');
end
% Close file
%--------------------------------------------------------------------------
fclose(fid);
|
github
|
ColeLab/ColeAnticevicNetPartition-master
|
xml_parser.m
|
.m
|
ColeAnticevicNetPartition-master/code/gifti-1.6/@gifti/private/xml_parser.m
| 16,915 |
utf_8
|
de0a4766201059ea1860acc2a4a1a019
|
function tree = xml_parser(xmlstr)
% XML (eXtensible Markup Language) Processor
% FORMAT tree = xml_parser(xmlstr)
%
% xmlstr - XML string to parse
% tree - tree structure corresponding to the XML file
%__________________________________________________________________________
%
% xml_parser.m is an XML 1.0 (http://www.w3.org/TR/REC-xml) parser.
% It aims to be fully conforming. It is currently not a validating
% XML processor.
%
% A description of the tree structure provided in output is detailed in
% the header of this m-file.
%__________________________________________________________________________
% Copyright (C) 2002-2015 http://www.artefact.tk/
% Guillaume Flandin
% $Id: xml_parser.m 6480 2015-06-13 01:08:30Z guillaume $
% XML Processor for GNU Octave and MATLAB (The Mathworks, Inc.)
% Copyright (C) 2002-2015 Guillaume Flandin <[email protected]>
%
% 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 any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
%--------------------------------------------------------------------------
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% Check also the latest developments on the following webpage:
% <http://www.artefact.tk/software/matlab/xml/>
%--------------------------------------------------------------------------
% The implementation of this XML parser is much inspired from a
% Javascript parser that used to be available at <http://www.jeremie.com/>
% A C-MEX file xml_findstr.c is also required, to encompass some
% limitations of the built-in FINDSTR function.
% Compile it on your architecture using 'mex -O xml_findstr.c' command
% if the compiled version for your system is not provided.
% If this function does not behave as expected, comment the line
% '#define __HACK_MXCHAR__' in xml_findstr.c and compile it again.
%--------------------------------------------------------------------------
% Structure of the output tree:
% There are 5 types of nodes in an XML file: element, chardata, cdata,
% pi and comment.
% Each of them contains an UID (Unique Identifier): an integer between
% 1 and the number of nodes of the XML file.
%
% element (a tag <name key="value"> [contents] </name>
% |_ type: 'element'
% |_ name: string
% |_ attributes: cell array of struct 'key' and 'value' or []
% |_ contents: double array of uid's or [] if empty
% |_ parent: uid of the parent ([] if root)
% |_ uid: double
%
% chardata (a character array)
% |_ type: 'chardata'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% cdata (a litteral string <![CDATA[value]]>)
% |_ type: 'cdata'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% pi (a processing instruction <?target value ?>)
% |_ type: 'pi'
% |_ target: string (may be empty)
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% comment (a comment <!-- value -->)
% |_ type: 'comment'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
%--------------------------------------------------------------------------
% TODO/BUG/FEATURES:
% - [compile] only a warning if TagStart is empty ?
% - [attribution] should look for " and ' rather than only "
% - [main] with normalize as a preprocessing, CDATA are modified
% - [prolog] look for a DOCTYPE in the whole string even if it occurs
% only in a far CDATA tag, bug even if the doctype is inside a comment
% - [tag_element] erode should replace normalize here
% - remove globals? uppercase globals rather persistent (clear mfile)?
% - xml_findstr is indeed xml_strfind according to Mathworks vocabulary
% - problem with entities: do we need to convert them here? (é)
%--------------------------------------------------------------------------
%- XML string to parse and number of tags read
global xmlstring Xparse_count xtree;
%- Check input arguments
%error(nargchk(1,1,nargin));
if isempty(xmlstr)
error('[XML] Not enough parameters.')
elseif ~ischar(xmlstr) || sum(size(xmlstr)>1)>1
error('[XML] Input must be a string.')
end
%- Initialize number of tags (<=> uid)
Xparse_count = 0;
%- Remove prolog and white space characters from the XML string
xmlstring = normalize(prolog(xmlstr));
%- Initialize the XML tree
xtree = {};
tree = fragment;
tree.str = 1;
tree.parent = 0;
%- Parse the XML string
tree = compile(tree);
%- Return the XML tree
tree = xtree;
%- Remove global variables from the workspace
clear global xmlstring Xparse_count xtree;
%==========================================================================
% SUBFUNCTIONS
%--------------------------------------------------------------------------
function frag = compile(frag)
global xmlstring xtree Xparse_count;
while 1,
if length(xmlstring)<=frag.str || ...
(frag.str == length(xmlstring)-1 && strcmp(xmlstring(frag.str:end),' '))
return
end
TagStart = xml_findstr(xmlstring,'<',frag.str,1);
if isempty(TagStart)
%- Character data
error('[XML] Unknown data at the end of the XML file.');
Xparse_count = Xparse_count + 1;
xtree{Xparse_count} = chardata;
xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:end)));
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
frag.str = '';
elseif TagStart > frag.str
if strcmp(xmlstring(frag.str:TagStart-1),' ')
%- A single white space before a tag (ignore)
frag.str = TagStart;
else
%- Character data
Xparse_count = Xparse_count + 1;
xtree{Xparse_count} = chardata;
xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:TagStart-1)));
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
frag.str = TagStart;
end
else
if strcmp(xmlstring(frag.str+1),'?')
%- Processing instruction
frag = tag_pi(frag);
else
if length(xmlstring)-frag.str>4 && strcmp(xmlstring(frag.str+1:frag.str+3),'!--')
%- Comment
frag = tag_comment(frag);
else
if length(xmlstring)-frag.str>9 && strcmp(xmlstring(frag.str+1:frag.str+8),'![CDATA[')
%- Litteral data
frag = tag_cdata(frag);
else
%- A tag element (empty (<.../>) or not)
if ~isempty(frag.end)
endmk = ['/' frag.end '>'];
else
endmk = '/>';
end
if strcmp(xmlstring(frag.str+1:frag.str+length(frag.end)+2),endmk) || ...
strcmp(strip(xmlstring(frag.str+1:frag.str+length(frag.end)+2)),endmk)
frag.str = frag.str + length(frag.end)+3;
return
else
frag = tag_element(frag);
end
end
end
end
end
end
%--------------------------------------------------------------------------
function frag = tag_element(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'>',frag.str,1);
if isempty(close)
error('[XML] Tag < opened but not closed.');
else
empty = strcmp(xmlstring(close-1:close),'/>');
if empty
close = close - 1;
end
starttag = normalize(xmlstring(frag.str+1:close-1));
nextspace = xml_findstr(starttag,' ',1,1);
attribs = '';
if isempty(nextspace)
name = starttag;
else
name = starttag(1:nextspace-1);
attribs = starttag(nextspace+1:end);
end
Xparse_count = Xparse_count + 1;
xtree{Xparse_count} = element;
xtree{Xparse_count}.name = strip(name);
if frag.parent
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
end
if ~isempty(attribs)
xtree{Xparse_count}.attributes = attribution(attribs);
end
if ~empty
contents = fragment;
contents.str = close+1;
contents.end = name;
contents.parent = Xparse_count;
contents = compile(contents);
frag.str = contents.str;
else
frag.str = close+2;
end
end
%--------------------------------------------------------------------------
function frag = tag_pi(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'?>',frag.str,1);
if isempty(close)
warning('[XML] Tag <? opened but not closed.')
else
nextspace = xml_findstr(xmlstring,' ',frag.str,1);
Xparse_count = Xparse_count + 1;
xtree{Xparse_count} = pri;
if nextspace > close || nextspace == frag.str+2
xtree{Xparse_count}.value = erode(xmlstring(frag.str+2:close-1));
else
xtree{Xparse_count}.value = erode(xmlstring(nextspace+1:close-1));
xtree{Xparse_count}.target = erode(xmlstring(frag.str+2:nextspace));
end
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+2;
end
%--------------------------------------------------------------------------
function frag = tag_comment(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'-->',frag.str,1);
if isempty(close)
warning('[XML] Tag <!-- opened but not closed.')
else
Xparse_count = Xparse_count + 1;
xtree{Xparse_count} = comment;
xtree{Xparse_count}.value = erode(xmlstring(frag.str+4:close-1));
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+3;
end
%--------------------------------------------------------------------------
function frag = tag_cdata(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,']]>',frag.str,1);
if isempty(close)
warning('[XML] Tag <![CDATA[ opened but not closed.')
else
Xparse_count = Xparse_count + 1;
xtree{Xparse_count} = cdata;
xtree{Xparse_count}.value = xmlstring(frag.str+9:close-1);
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+3;
end
%--------------------------------------------------------------------------
function all = attribution(str)
%- Initialize attributs
nbattr = 0;
all = cell(nbattr);
%- Look for 'key="value"' substrings
while 1,
eq = xml_findstr(str,'=',1,1);
if isempty(str) || isempty(eq), return; end
id = sort([xml_findstr(str,'"',1,1),xml_findstr(str,'''',1,1)]); id=id(1);
nextid = sort([xml_findstr(str,'"',id+1,1),xml_findstr(str,'''',id+1,1)]);nextid=nextid(1);
nbattr = nbattr + 1;
all{nbattr}.key = strip(str(1:(eq-1)));
all{nbattr}.val = entity(str((id+1):(nextid-1)));
str = str((nextid+1):end);
end
%--------------------------------------------------------------------------
function elm = element
global Xparse_count;
elm = struct('type','element','name','','attributes',[],'contents',[],'parent',[],'uid',Xparse_count);
%--------------------------------------------------------------------------
function cdat = chardata
global Xparse_count;
cdat = struct('type','chardata','value','','parent',[],'uid',Xparse_count);
%--------------------------------------------------------------------------
function cdat = cdata
global Xparse_count;
cdat = struct('type','cdata','value','','parent',[],'uid',Xparse_count);
%--------------------------------------------------------------------------
function proce = pri
global Xparse_count;
proce = struct('type','pi','value','','target','','parent',[],'uid',Xparse_count);
%--------------------------------------------------------------------------
function commt = comment
global Xparse_count;
commt = struct('type','comment','value','','parent',[],'uid',Xparse_count);
%--------------------------------------------------------------------------
function frg = fragment
frg = struct('str','','parent','','end','');
%--------------------------------------------------------------------------
function str = prolog(str)
%- Initialize beginning index of elements tree
b = 1;
%- Initial tag
start = xml_findstr(str,'<',1,1);
if isempty(start)
error('[XML] No tag found.')
end
%- Header (<?xml version="1.0" ... ?>)
if strcmpi(str(start:start+2),'<?x')
close = xml_findstr(str,'?>',1,1);
if ~isempty(close)
b = close + 2;
else
warning('[XML] Header tag incomplete.')
end
end
%- Doctype (<!DOCTYPE type ... [ declarations ]>)
start = xml_findstr(str,'<!DOCTYPE',b,1); % length('<!DOCTYPE') = 9
if ~isempty(start)
close = xml_findstr(str,'>',start+9,1);
if ~isempty(close)
b = close + 1;
dp = xml_findstr(str,'[',start+9,1);
if (~isempty(dp) && dp < b)
k = xml_findstr(str,']>',start+9,1);
if ~isempty(k)
b = k + 2;
else
warning('[XML] Tag [ in DOCTYPE opened but not closed.')
end
end
else
warning('[XML] Tag DOCTYPE opened but not closed.')
end
end
%- Skip prolog from the xml string
str = str(b:end);
%--------------------------------------------------------------------------
function str = strip(str)
str(isspace(str)) = '';
%--------------------------------------------------------------------------
function str = normalize(str)
% Find white characters (space, newline, carriage return, tabs, ...)
i = isspace(str);
i = find(i == 1);
str(i) = ' ';
% replace several white characters by only one
if ~isempty(i)
j = i - [i(2:end) i(end)];
str(i(j == -1)) = [];
end
%--------------------------------------------------------------------------
function str = entity(str)
str = strrep(str,'<','<');
str = strrep(str,'>','>');
str = strrep(str,'"','"');
str = strrep(str,''','''');
str = strrep(str,'&','&');
%--------------------------------------------------------------------------
function str = erode(str)
if ~isempty(str) && str(1)==' ', str(1)=''; end;
if ~isempty(str) && str(end)==' ', str(end)=''; end;
%-----------------------------------------------------------------------
function k = xml_findstr(s,p,i,n)
% K = XML_FINDSTR(TEXT,PATTERN,INDICE,NBOCCUR)
% k = regexp(s(i:end),p,'once') + i - 1;
j = strfind(s,p);
k = j(j>=i);
if ~isempty(k), k = k(1:min(n,length(k))); end
|
github
|
ColeLab/ColeAnticevicNetPartition-master
|
read_gifti_file_standalone.m
|
.m
|
ColeAnticevicNetPartition-master/code/gifti-1.6/@gifti/private/read_gifti_file_standalone.m
| 8,244 |
utf_8
|
018a4c448f6eeab3ab67b1b95d3086ea
|
function this = read_gifti_file_standalone(filename, this)
% Low level reader of GIfTI 1.0 files
% FORMAT this = read_gifti_file(filename, this)
% filename - XML GIfTI filename
% this - structure with fields 'metaData', 'label' and 'data'.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: read_gifti_file_standalone.m 6404 2015-04-13 14:29:53Z guillaume $
% Import XML-based GIfTI file
%--------------------------------------------------------------------------
try
fid = fopen(filename,'rt');
xmlstr = fread(fid,'*char')';
fclose(fid);
t = xml_parser(xmlstr);
catch
error('[GIFTI] Loading of XML file %s failed.', filename);
end
% Root element of a GIFTI file
%--------------------------------------------------------------------------
if ~strcmp(xml_get(t,xml_root(t),'name'),'GIFTI')
error('[GIFTI] %s is not a GIFTI 1.0 file.', filename);
end
attr = cell2mat(xml_attributes(t,'get',xml_root(t)));
attr = cell2struct({attr.val},strrep({attr.key},':','___'),2);
if ~all(ismember({'Version','NumberOfDataArrays'},fieldnames(attr)))
error('[GIFTI] Missing mandatory attributes for GIFTI root element.');
end
if str2double(attr.Version) ~= 1
warning('[GIFTI] Unknown specification version of GIFTI file (%s).',attr.Version);
end
nbData = str2double(attr.NumberOfDataArrays);
% Read children elements
%--------------------------------------------------------------------------
uid = xml_children(t,xml_root(t));
for i=1:length(uid)
switch xml_get(t,uid(i),'name')
case 'MetaData'
this.metadata = gifti_MetaData(t,uid(i));
case 'LabelTable'
this.label = gifti_LabelTable(t,uid(i));
case 'DataArray'
this.data{end+1} = gifti_DataArray(t,uid(i),filename);
otherwise
warning('[GIFTI] Unknown element "%s": ignored.',xml_get(t,uid(i),'name'));
end
end
if nbData ~= length(this.data)
warning('[GIFTI] Mismatch between expected and effective number of datasets.');
end
%==========================================================================
function s = gifti_MetaData(t,uid)
s = struct('name',{}, 'value',{});
c = xml_children(t,uid);
for i=1:length(c)
for j=xml_children(t,c(i))
s(i).(lower(xml_get(t,j,'name'))) = xml_get(t,xml_children(t,j),'value');
end
end
%==========================================================================
function s = gifti_LabelTable(t,uid)
s = struct('name',{}, 'key',[], 'rgba',[]);
c = xml_children(t,uid);
for i=1:length(c)
a = xml_attributes(t,'get',c(i));
s(1).rgba(i,1:4) = NaN;
for j=1:numel(a)
switch lower(a{j}.key)
case {'key','index'}
s(1).key(i) = str2double(a{j}.val);
case 'red'
s(1).rgba(i,1) = str2double(a{j}.val);
case 'green'
s(1).rgba(i,2) = str2double(a{j}.val);
case 'blue'
s(1).rgba(i,3) = str2double(a{j}.val);
case 'alpha'
s(1).rgba(i,4) = str2double(a{j}.val);
otherwise
end
end
s(1).name{i} = xml_get(t,xml_children(t,c(i)),'value');
end
%==========================================================================
function s = gifti_DataArray(t,uid,filename)
s = struct(...
'attributes', {}, ...
'data', {}, ...
'metadata', struct([]), ...
'space', {} ...
);
attr = cell2mat(xml_attributes(t,'get',uid));
s(1).attributes = cell2struct({attr.val},{attr.key},2);
s(1).attributes.Dim = [];
for i=1:str2double(s(1).attributes.Dimensionality)
f = sprintf('Dim%d',i-1);
s(1).attributes.Dim(i) = str2double(s(1).attributes.(f));
s(1).attributes = rmfield(s(1).attributes,f);
end
s(1).attributes = rmfield(s(1).attributes,'Dimensionality');
if isfield(s(1).attributes,'ExternalFileName') && ...
~isempty(s(1).attributes.ExternalFileName)
s(1).attributes.ExternalFileName = fullfile(fileparts(filename),...
s(1).attributes.ExternalFileName);
end
c = xml_children(t,uid);
for i=1:length(c)
switch xml_get(t,c(i),'name')
case 'MetaData'
s(1).metadata = gifti_MetaData(t,c(i));
case 'CoordinateSystemTransformMatrix'
s(1).space(end+1) = gifti_Space(t,c(i));
case 'Data'
s(1).data = gifti_Data(t,c(i),s(1).attributes);
otherwise
error('[GIFTI] Unknown DataArray element "%s".',xml_get(t,c(i),'name'));
end
end
%==========================================================================
function s = gifti_Space(t,uid)
s = struct('DataSpace','', 'TransformedSpace','', 'MatrixData',[]);
for i=xml_children(t,uid)
s.(xml_get(t,i,'name')) = xml_get(t,xml_children(t,i),'value');
end
s.MatrixData = reshape(str2num(s.MatrixData),4,4)';
%==========================================================================
function d = gifti_Data(t,uid,s)
tp = getdict;
try
tp = tp.(s.DataType);
catch
error('[GIFTI] Unknown DataType.');
end
[unused,unused,mach] = fopen(1);
sb = @(x) x;
try
if (strcmp(s.Endian,'LittleEndian') && ~isempty(strmatch('ieee-be',mach))) ...
|| (strcmp(s.Endian,'BigEndian') && ~isempty(strmatch('ieee-le',mach)))
sb = @swapbyte;
end
catch
% Byte Order can be absent if encoding is ASCII, assume native otherwise
end
switch s.Encoding
case 'ASCII'
d = feval(tp.conv,sscanf(xml_get(t,xml_children(t,uid),'value'),tp.format));
case 'Base64Binary'
d = typecast(sb(base64decode(xml_get(t,xml_children(t,uid),'value'))), tp.cast);
case 'GZipBase64Binary'
d = typecast(zstream('D',sb(base64decode(xml_get(t,xml_children(t,uid),'value')))), tp.cast);
case 'ExternalFileBinary'
[p,f,e] = fileparts(s.ExternalFileName);
if isempty(p)
s.ExternalFileName = fullfile(pwd,[f e]);
end
if true
fid = fopen(s.ExternalFileName,'r');
if fid == -1
error('[GIFTI] Unable to read binary file %s.',s.ExternalFileName);
end
fseek(fid,str2double(s.ExternalFileOffset),0);
d = sb(fread(fid,prod(s.Dim),['*' tp.class]));
fclose(fid);
else
d = file_array(s.ExternalFileName, s.Dim, tp.class, ...
str2double(s.ExternalFileOffset),1,0,'rw');
end
otherwise
error('[GIFTI] Unknown data encoding: %s.',s.Encoding);
end
if length(s.Dim) == 1, s.Dim(end+1) = 1; end
switch s.ArrayIndexingOrder
case 'RowMajorOrder'
d = permute(reshape(d,fliplr(s.Dim)),length(s.Dim):-1:1);
case 'ColumnMajorOrder'
d = reshape(d,s.Dim);
otherwise
error('[GIFTI] Unknown array indexing order.');
end
%==========================================================================
%==========================================================================
function uid = xml_root(tree)
uid = 1;
for i=1:length(tree)
if strcmp(xml_get(tree,i,'type'),'element')
uid = i;
break
end
end
%--------------------------------------------------------------------------
function child = xml_children(tree,uid)
if strcmp(tree{uid}.type,'element')
child = tree{uid}.contents;
else
child = [];
end
%--------------------------------------------------------------------------
function value = xml_get(tree,uid,parameter)
if isempty(uid), value = {}; return; end
try
value = tree{uid}.(parameter);
catch
error(sprintf('[XML] Parameter %s not found.',parameter));
end
%--------------------------------------------------------------------------
function varargout = xml_attributes(tree,method,uid)
if ~strcmpi(method,'get'), error('[XML] Unknown attributes method.'); end
if isempty(tree{uid}.attributes)
varargout{1} = {};
else
varargout{1} = tree{uid}.attributes;
end
|
github
|
ColeLab/ColeAnticevicNetPartition-master
|
mvtk_write.m
|
.m
|
ColeAnticevicNetPartition-master/code/gifti-1.6/@gifti/private/mvtk_write.m
| 18,882 |
utf_8
|
006b1aa29abf46ab17ab3eb11c9cb992
|
function mvtk_write(M,filename,format)
% Write geometric data on disk using VTK file format (legacy/XML,ascii/binary)
% FORMAT mvtk_write(M,filename,format)
%
% M - data structure
% filename - output filename [Default: 'untitled']
% format - VTK file format: legacy, legacy-ascii, legacy-binary, xml,
% xml-ascii, xml-binary [Default: 'legacy-ascii']
%__________________________________________________________________________
%
% VTK File Formats Specifications:
% http://www.vtk.org/VTK/img/file-formats.pdf
%
% Requirements: zstream, base64encode
%__________________________________________________________________________
% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: mvtk_write.m 6520 2015-08-13 16:13:06Z guillaume $
%-Input parameters
%--------------------------------------------------------------------------
if nargin < 2 || isempty(filename), filename = 'untitled'; end
if nargin < 3 || isempty(format)
[pth,name,ext] = fileparts(filename);
switch ext
case {'','.vtk'}
ext = '.vtk';
format = 'legacy-ascii'; % default
case 'vtp'
format = 'xml-ascii';
case {'.vti','.vtr','.vts','.vtu'}
format = 'xml-ascii';
warning('Only partially handled.');
otherwise
error('Unknown file extension.');
end
else
switch lower(format)
case {'legacy','legacy-ascii','legacy-binary'}
ext = '.vtk';
case {'xml','xml-ascii','xml-binary','xml-appended'}
ext = '.vtp';
otherwise
error('Unknown file format.');
end
end
%-Filename
%--------------------------------------------------------------------------
[pth,name,e] = fileparts(filename);
if ~strcmpi(e,ext)
warning('Changing file extension from %s to %s.',e,ext);
end
filename = fullfile(pth,[name ext]);
%-Convert input structure if necessary
%--------------------------------------------------------------------------
%-Three scalars per item interpreted as color
% if isfield(M,'cdata') && size(M.cdata,2) == 3
% M.color = M.cdata;
% M = rmfield(M,'cdata');
% end
%-Compute normals
if ~isfield(M,'normals')
M.normals = compute_normals(M);
end
%-Write file
%--------------------------------------------------------------------------
switch lower(format)
case {'legacy','legacy-ascii'}
mvtk_write_legacy(M,filename,'ASCII');
case {'legacy-binary'}
mvtk_write_legacy(M,filename,'BINARY');
case {'xml','xml-ascii'}
mvtk_write_xml(M,filename,'ASCII');
case {'xml-binary'}
mvtk_write_xml(M,filename,'BINARY');
case {'xml-appended'}
mvtk_write_xml(M,filename,'APPENDED');
otherwise
error('Unknown file format.');
end
%==========================================================================
% function fid = mvtk_write_legacy(s,filename,format)
%==========================================================================
function fid = mvtk_write_legacy(s,filename,format)
%-Open file
%--------------------------------------------------------------------------
if nargin == 2, format = 'ASCII'; else format = upper(format); end
switch format
case 'ASCII'
fopen_opts = {'wt'};
write_data = @(fid,fmt,prec,dat) fprintf(fid,fmt,dat);
case 'BINARY'
fopen_opts = {'wb','ieee-be'};
write_data = @(fid,fmt,prec,dat) [fwrite(fid,dat,prec);fprintf(fid,'\n');];
otherwise
error('Unknown file format.');
end
fid = fopen(filename,fopen_opts{:});
if fid == -1
error('Unable to write file %s: permission denied.',filename);
end
%-Legacy VTK file format
%==========================================================================
%- Part 1: file version and identifier
%--------------------------------------------------------------------------
fprintf(fid,'# vtk DataFile Version 2.0\n');
%- Part 2: header
%--------------------------------------------------------------------------
hdr = 'Saved using mVTK';
fprintf(fid,'%s\n',hdr(1:min(length(hdr),256)));
%- Part 3: data type (either ASCII or BINARY)
%--------------------------------------------------------------------------
fprintf(fid,'%s\n',format);
%- Part 4: dataset structure: geometry/topology
%--------------------------------------------------------------------------
% One of: STRUCTURED_POINTS, STRUCTURED_GRID, UNSTRUCTURED_GRID, POLYDATA,
% RECTILINEAR_GRID, FIELD
if isfield(s,'vertices') || isfield(s,'faces')
type = 'POLYDATA';
elseif isfield(s,'spacing')
type = 'STRUCTURED_POINTS';
%elseif isfield(s,'mat')
% type = 'STRUCTURED_GRID';
else
error('Unknown dataset structure.');
end
fprintf(fid,'DATASET %s\n',type);
if isfield(s,'vertices')
fprintf(fid,'POINTS %d %s\n',size(s.vertices,1),'float');
write_data(fid,'%f %f %f\n','float32',s.vertices');
end
if isfield(s,'faces')
nFaces = size(s.faces,1);
nConn = size(s.faces,2);
fprintf(fid,'POLYGONS %d %d\n',nFaces,nFaces*(nConn+1));
dat = uint32([repmat(nConn,1,nFaces); (s.faces'-1)]);
fmt = repmat('%d ',1,size(dat,1)); fmt(end) = '';
write_data(fid,[fmt '\n'],'uint32',dat);
end
if isfield(s,'spacing')
fprintf(fid,'DIMENSIONS %d %d %d\n',size(s.cdata));
fprintf(fid,'ORIGIN %f %f %f\n',s.origin);
fprintf(fid,'SPACING %f %f %f\n',s.spacing);
s.cdata = s.cdata(:);
end
% if isfield(s,'mat')
% dim = size(s.cdata);
% fprintf(fid,'DIMENSIONS %d %d %d\n',dim);
% fprintf(fid,'POINTS %d %s\n',prod(dim),'float');
% [R,C,P] = ndgrid(1:dim(1),1:dim(2),1:dim(3));
% RCP = [R(:)';C(:)';P(:)'];
% clear R C P
% RCP(4,:) = 1;
% XYZmm = s.mat(1:3,:)*RCP;
% write_data(fid,'%f %f %f\n','float32',XYZmm);
% s.cdata = s.cdata(:);
% end
fprintf(fid,'\n');
%- Part 5: dataset attributes (POINT_DATA and CELL_DATA)
%--------------------------------------------------------------------------
point_data_hdr = false;
%-SCALARS (and LOOKUP_TABLE)
if isfield(s,'cdata') && ~isempty(s.cdata)
if ~point_data_hdr
fprintf(fid,'POINT_DATA %d\n',size(s.cdata,1));
point_data_hdr = true;
end
if ~isfield(s,'lut')
lut_name = 'default';
else
lut_name = 'my_lut';
if size(s.lut,2) == 3
s.lut = [s.lut ones(size(s.lut,1),1)]; % alpha
end
end
dataName = 'cdata';
fprintf(fid,'SCALARS %s %s %d\n',dataName,'float',size(s.cdata,2));
fprintf(fid,'LOOKUP_TABLE %s\n',lut_name);
fmt = repmat('%f ',1,size(s.cdata,2)); fmt(end) = '';
write_data(fid,[fmt '\n'],'float32',s.cdata');
if ~strcmp(lut_name,'default')
fprintf(fid,'LOOKUP_TABLE %s %d\n',lut_name,size(s.lut,1));
if strcmp(format,'ASCII')
% float values between (0,1)
write_data(fid,'%f %f %f %f\n','float32',s.lut'); % rescale
else
% four unsigned char values per table entry
write_data(fid,'','uint8',uint8(s.lut')); % rescale
end
end
end
%-COLOR_SCALARS
if isfield(s,'color') && ~isempty(s.color)
if ~point_data_hdr
fprintf(fid,'POINT_DATA %d\n',size(s.color,1));
point_data_hdr = true;
end
dataName = 'color';
fprintf(fid,'COLOR_SCALARS %s %d\n',dataName,size(s.color,2));
if strcmp(format,'ASCII')
% nValues float values between (0.1)
fmt = repmat('%f ',1,size(s.color,2)); fmt(end) = '';
write_data(fid,[fmt '\n'],'float32',s.color'); % rescale
else
% nValues unsigned char values per scalar value
write_data(fid,'','uint8',uint8(s.color')); % rescale
end
end
%-VECTORS
if isfield(s,'vectors') && ~isempty(s.vectors)
if ~point_data_hdr
fprintf(fid,'POINT_DATA %d\n',size(s.vectors,1));
point_data_hdr = true;
end
dataName = 'vectors';
fprintf(fid,'VECTORS %s %s\n',dataName,'float');
write_data(fid,'%f %f %f\n','float32',s.vectors');
end
%-NORMALS
if isfield(s,'normals') && ~isempty(s.normals)
if ~point_data_hdr
fprintf(fid,'POINT_DATA %d\n',size(s.vertices,1));
point_data_hdr = true;
end
dataName = 'normals';
fprintf(fid,'NORMALS %s %s\n',dataName,'float');
write_data(fid,'%f %f %f\n','float32',-s.normals');
end
%-TENSORS
if isfield(s,'tensors') && ~isempty(s.tensors)
if ~point_data_hdr
fprintf(fid,'POINT_DATA %d\n',size(s.tensors,1));
point_data_hdr = true;
end
dataName = 'tensors';
fprintf(fid,'TENSORS %s %s\n',dataName,'float');
write_data(fid,repmat('%f %f %f\n',1,3),'float32',s.tensors');
end
%-Close file
%--------------------------------------------------------------------------
fclose(fid);
%==========================================================================
% function fid = mvtk_write_xml(s,filename,format)
%==========================================================================
function fid = mvtk_write_xml(s,filename,format)
%-Open file
%--------------------------------------------------------------------------
if nargin == 2, format = 'ascii'; else format = lower(format); end
clear store_appended_data
switch format
case 'ascii'
fopen_opts = {'wt'};
write_data = @(fmt,dat) deal(NaN,sprintf(fmt,dat));
case 'binary'
fopen_opts = {'wb','ieee-le'};
write_data = @(fmt,dat) deal(NaN,[...
base64encode(typecast(uint32(numel(dat)*numel(typecast(dat(1),'uint8'))),'uint8')) ...
base64encode(typecast(dat(:),'uint8'))]);
case 'appended'
fopen_opts = {'wt'};
store_appended_data('start');
store_appended_data('base64'); % format: raw, [base64]
store_appended_data('none'); % compression: none, [zlib]
write_data = @(fmt,dat) deal(store_appended_data(fmt,dat),'');
otherwise
error('Unknown format.');
end
fid = fopen(filename,fopen_opts{:});
if fid == -1
error('Unable to write file %s: permission denied.',filename);
end
%-XML VTK file format
%==========================================================================
o = @(x) blanks(x*3);
%-XML prolog
%--------------------------------------------------------------------------
fprintf(fid,'<?xml version="1.0"?>\n');
%-VTKFile
%--------------------------------------------------------------------------
VTKFile = struct;
VTKFile.type = 'PolyData';
VTKFile.version = '0.1';
VTKFile.byte_order = 'LittleEndian';
VTKFile.header_type = 'UInt32';
if strcmp(store_appended_data('compression'),'zlib')
VTKFile.compressor = 'vtkZLibDataCompressor';
end
fprintf(fid,'<VTKFile');
for i=fieldnames(VTKFile)'
fprintf(fid,' %s="%s"',i{1},VTKFile.(i{1}));
end
fprintf(fid,'>\n');
%-PolyData
%--------------------------------------------------------------------------
fprintf(fid,'%s<PolyData>\n',o(1));
Piece = struct;
Piece.NumberOfPoints = sprintf('%d',size(s.vertices,1));
Piece.NumberOfVerts = sprintf('%d',0);
Piece.NumberOfLines = sprintf('%d',0);
Piece.NumberOfStrips = sprintf('%d',0);
Piece.NumberOfPolys = sprintf('%d',size(s.faces,1));
fprintf(fid,'%s<Piece',o(2));
for i=fieldnames(Piece)'
fprintf(fid,' %s="%s"',i{1},Piece.(i{1}));
end
fprintf(fid,'>\n');
%-PointData
%--------------------------------------------------------------------------
PointData = struct;
if isfield(s,'cdata') && ~isempty(s.cdata)
PointData.Scalars = 'scalars';
end
if isfield(s,'normals') && ~isempty(s.normals)
PointData.Normals = 'normals';
end
fprintf(fid,'%s<PointData',o(3));
for i=fieldnames(PointData)'
fprintf(fid,' %s="%s"',i{1},PointData.(i{1}));
end
fprintf(fid,'>\n');
%-Scalars
if isfield(s,'cdata') && ~isempty(s.cdata)
[offset,dat] = write_data('%f ',single(s.cdata'));
DataArray = struct;
DataArray.type = 'Float32';
DataArray.Name = 'scalars';
DataArray.NumberOfComponents = sprintf('%d',size(s.cdata,2));
DataArray.format = format;
if ~isnan(offset), DataArray.offset = sprintf('%d',offset); end
fprintf(fid,'%s<DataArray',o(4));
for i=fieldnames(DataArray)'
fprintf(fid,' %s="%s"',i{1},DataArray.(i{1}));
end
fprintf(fid,'>%s</DataArray>\n',dat);
end
%-Normals
if isfield(s,'normals') && ~isempty(s.normals)
[offset,dat] = write_data('%f ',single(-s.normals'));
DataArray = struct;
DataArray.type = 'Float32';
DataArray.Name = 'normals';
DataArray.NumberOfComponents = sprintf('%d',3);
DataArray.format = format;
if ~isnan(offset), DataArray.offset = sprintf('%d',offset); end
fprintf(fid,'%s<DataArray',o(4));
for i=fieldnames(DataArray)'
fprintf(fid,' %s="%s"',i{1},DataArray.(i{1}));
end
fprintf(fid,'>%s</DataArray>\n',dat);
end
fprintf(fid,'%s</PointData>\n',o(3));
%-CellData
%--------------------------------------------------------------------------
fprintf(fid,'%s<CellData/>\n',o(3));
%-Points
%--------------------------------------------------------------------------
fprintf(fid,'%s<Points>\n',o(3));
if isfield(s,'vertices')
[offset,dat] = write_data('%f ',single(s.vertices'));
DataArray = struct;
DataArray.type = 'Float32';
DataArray.Name = 'Vertices';
DataArray.NumberOfComponents = sprintf('%d',3);
DataArray.format = format;
if ~isnan(offset), DataArray.offset = sprintf('%d',offset); end
fprintf(fid,'%s<DataArray',o(4));
for i=fieldnames(DataArray)'
fprintf(fid,' %s="%s"',i{1},DataArray.(i{1}));
end
fprintf(fid,'>%s</DataArray>\n',dat);
end
fprintf(fid,'%s</Points>\n',o(3));
%-Verts
%--------------------------------------------------------------------------
fprintf(fid,'%s<Verts/>\n',o(3));
%-Lines
%--------------------------------------------------------------------------
fprintf(fid,'%s<Lines/>\n',o(3));
%-Strips
%--------------------------------------------------------------------------
fprintf(fid,'%s<Strips/>\n',o(3));
%-Polys
%--------------------------------------------------------------------------
fprintf(fid,'%s<Polys>\n',o(3));
if isfield(s,'faces')
[offset,dat] = write_data('%d ',uint32(s.faces'-1));
DataArray = struct;
DataArray.type = 'UInt32';
DataArray.Name = 'connectivity';
DataArray.format = format;
if ~isnan(offset), DataArray.offset = sprintf('%d',offset); end
fprintf(fid,'%s<DataArray',o(4));
for i=fieldnames(DataArray)'
fprintf(fid,' %s="%s"',i{1},DataArray.(i{1}));
end
fprintf(fid,'>%s</DataArray>\n',dat);
[offset,dat] = write_data('%d ',uint32(3:3:3*size(s.faces,1)));
DataArray = struct;
DataArray.type = 'UInt32';
DataArray.Name = 'offsets';
DataArray.format = format;
if ~isnan(offset), DataArray.offset = sprintf('%d',offset); end
fprintf(fid,'%s<DataArray',o(4));
for i=fieldnames(DataArray)'
fprintf(fid,' %s="%s"',i{1},DataArray.(i{1}));
end
fprintf(fid,'>%s</DataArray>\n',dat);
end
fprintf(fid,'%s</Polys>\n',o(3));
fprintf(fid,'%s</Piece>\n',o(2));
fprintf(fid,'%s</PolyData>\n',o(1));
%-AppendedData
%--------------------------------------------------------------------------
if strcmp(format,'appended')
dat = store_appended_data('retrieve');
store_appended_data('stop');
AppendedData = struct;
AppendedData.encoding = store_appended_data('encoding');
fprintf(fid,'%s<AppendedData',o(1));
for i=fieldnames(AppendedData)'
fprintf(fid,' %s="%s"',i{1},AppendedData.(i{1}));
end
fprintf(fid,'>\n%s_',o(2));
fwrite(fid,dat);
fprintf(fid,'\n%s</AppendedData>\n',o(1));
end
fprintf(fid,'</VTKFile>\n');
%-Close file
%--------------------------------------------------------------------------
fclose(fid);
%==========================================================================
% function varargout = store_appended_data(fmt,dat)
%==========================================================================
function varargout = store_appended_data(fmt,dat)
persistent fid encoding compression
if isempty(encoding), encoding = 'raw'; end
if isempty(compression), compression = 'none'; end
if ~nargin, fmt = 'start'; end
if nargin < 2
varargout = {};
switch lower(fmt)
case 'start'
filename = tempname;
fid = fopen(filename,'w+b');
if fid == -1
error('Cannot open temporary file.');
end
case 'stop'
filename = fopen(fid);
fclose(fid);
delete(filename);
fid = -1;
case 'retrieve'
frewind(fid);
varargout = {fread(fid)};
case 'encoding'
varargout = {encoding};
case 'compression'
varargout = {compression};
case {'raw','base64'}
encoding = fmt;
case {'none','zlib'}
compression = fmt;
otherwise
error('Unknown action.');
end
return;
end
varargout = {ftell(fid)};
N = uint32(numel(dat)*numel(typecast(dat(1),'uint8')));
switch encoding
case 'raw'
switch compression
case 'none'
dat = typecast(dat(:),'uint8');
hdr = N;
case 'zlib'
dat = zstream('C',typecast(dat(:),'uint8'));
hdr = uint32([1 N N numel(dat)]);
otherwise
error('Unknown compression.');
end
fwrite(fid,hdr,'uint32');
fwrite(fid,dat,class(dat));
case 'base64'
switch compression
case 'none'
dat = typecast(dat(:),'uint8');
hdr = N;
case 'zlib'
dat = zstream('C',typecast(dat(:),'uint8'));
hdr = uint32([1 N N numel(dat)]);
otherwise
error('Unknown compression.');
end
fwrite(fid,base64encode(typecast(hdr,'uint8')));
fwrite(fid,base64encode(dat));
otherwise
error('Unknown encoding.');
end
%==========================================================================
% function N = compute_normals(S)
%==========================================================================
function N = compute_normals(S)
try
t = triangulation(double(S.faces),double(S.vertices));
N = -double(t.vertexNormal);
normN = sqrt(sum(N.^2,2));
normN(normN < eps) = 1;
N = N ./ repmat(normN,1,3);
catch
N = [];
end
|
github
|
ColeLab/ColeAnticevicNetPartition-master
|
isintent.m
|
.m
|
ColeAnticevicNetPartition-master/code/gifti-1.6/@gifti/private/isintent.m
| 2,803 |
utf_8
|
059679d968315674d5e6cccbbd6f128c
|
function [a, b] = isintent(this,intent)
% Correspondance between fieldnames and NIfTI intent codes
% FORMAT ind = isintent(this,intent)
% this - GIfTI object
% intent - fieldnames
% a - indices of found intent(s)
% b - indices of dataarrays of found intent(s)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: isintent.m 6345 2015-02-20 12:25:50Z guillaume $
a = [];
b = [];
if ischar(intent), intent = cellstr(intent); end
for i=1:length(this(1).data)
switch this(1).data{i}.attributes.Intent(14:end)
case 'POINTSET'
[tf, loc] = ismember('vertices',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
[tf, loc] = ismember('mat',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
case 'TRIANGLE'
[tf, loc] = ismember('faces',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
case 'VECTOR'
[tf, loc] = ismember('normals',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
case 'NODE_INDEX'
[tf, loc] = ismember('indices',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
case cdata
[tf, loc] = ismember('cdata',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
if strcmp(this(1).data{i}.attributes.Intent(14:end),'LABEL')
[tf, loc] = ismember('labels',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
end
otherwise
fprintf('Intent %s is ignored.\n',this.data{i}.attributes.Intent);
end
end
%[d,i] = unique(a);
%if length(d) < length(a)
% warning('Several fields match intent type. Using first.');
% a = a(i);
% b = b(i);
%end
function c = cdata
c = {
'NONE'
'CORREL'
'TTEST'
'FTEST'
'ZSCORE'
'CHISQ'
'BETA'
'BINOM'
'GAMMA'
'POISSON'
'NORMAL'
'FTEST_NONC'
'CHISQ_NONC'
'LOGISTIC'
'LAPLACE'
'UNIFORM'
'TTEST_NONC'
'WEIBULL'
'CHI'
'INVGAUSS'
'EXTVAL'
'PVAL'
'LOGPVAL'
'LOG10PVAL'
'ESTIMATE'
'LABEL'
'NEURONAMES'
'GENMATRIX'
'SYMMATRIX'
'DISPVECT'
'QUATERNION'
'DIMLESS'
'TIME_SERIES'
'RGB_VECTOR'
'RGBA_VECTOR'
'SHAPE'
'CONNECTIVITY_DENSE'
'CONNECTIVITY_DENSE_TIME'
'CONNECTIVITY_PARCELLATED'
'CONNECTIVITY_PARCELLATED_TIME'
'CONNECTIVITY_CONNECTIVITY_TRAJECTORY'
};
|
github
|
anilbas/3DMMasSTN-master
|
dagnn_3dmmasstn.m
|
.m
|
3DMMasSTN-master/dagnn_3dmmasstn.m
| 3,391 |
utf_8
|
1390f606b065f165349ee949d51a3164
|
function [net, info] = dagnn_3dmmasstn(imdb,varargin)
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.networkType = 'dagnn' ;
opts.derOutputs = {'objective1',0.8998,'objective2',0.1,'objective3',0.0001,'objective4',0.0001};
% expDir: Output directory for the net-epoch-* files and the train.pdf figure
opts.expDir = fullfile(vl_rootnn, 'examples', '3DMMasSTN', 'data') ;
% dataDir: The VGG directory
opts.dataDir = fullfile(vl_rootnn, 'data', 'models') ;
% The imdb.mat file
opts.imdbPath = fullfile(vl_rootnn, 'data', 'imdb.mat');
opts.theta_learningRate = [4 8];
opts.thetab_weightDecay = 0;
opts.learningRate = 1e-10;
opts.batchSize = 32;
opts.numEpochs = 1000;
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end
% -------------------------------------------------------------------------
% Prepare model and data
% -------------------------------------------------------------------------
addpath(genpath(pwd));
% load landmarks
idx = readLandmarks('util/landmarks/Landmarks21_112.anl');
% load model
model = load('model.mat');
% load network
net = dagnn_3dmmasstn_init(model,idx,opts);
% load data
if (~exist('imdb', 'var') || isempty(imdb)), imdb = load(opts.imdbPath); end
% -------------------------------------------------------------------------
% Train
% -------------------------------------------------------------------------
[net, info] = cnn_train_dag(net, imdb, getBatch(opts), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train, ...
'derOutputs',opts.derOutputs, ...
'val', find(imdb.images.set == 2));
% -------------------------------------------------------------------------
function fn = getBatch(opts)
% -------------------------------------------------------------------------
bopts = struct('numGpus', numel(opts.train.gpus));
fn = @(x,y) getDagNNBatch(bopts,x,y);
% -------------------------------------------------------------------------
function inputs = getDagNNBatch(opts, imdb, batch)
% -------------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch);
labels = imdb.images.labels(:,:,:,batch);
[images, labels] = refineData(images, labels);
if opts.numGpus > 0
images = gpuArray(images);
labels = gpuArray(labels);
end
inputs = {'input', images, 'label', labels};
% -------------------------------------------------------------------------
function [Images, Labels] = refineData(images, labels)
% -------------------------------------------------------------------------
batchSize = size(images,4);
Images = zeros(224,224,3,batchSize*2,'single');
Labels = zeros(1,3,21,batchSize*2,'single');
for i=1:batchSize
id = 2*(i-1)+1;
im = images(:,:,:,i);
xp = squeeze(labels(:,1:2,:,i));
vis = squeeze(labels(:,3,:,i));
flippedxp = xp;
flippedxp(1,:) = ( size(im,2)+1-xp(1,:) ) .*(xp(1,:)~=0);
flippedxp = syncFlippedLandmarks( flippedxp );
Images(:,:,:,id) = im;
Labels(1,1:2,:,id) = xp;
Labels(1,3,:,id) = vis;
Images(:,:,:,id+1) = fliplr(im);
Labels(1,1:2,:,id+1) = flippedxp;
Labels(1,3,:,id+1) = syncFlippedLandmarks(vis);
end
|
github
|
KleinYuan/doppia-master
|
use_cimgmatlab.m
|
.m
|
doppia-master/libs/CImg/examples/use_cimgmatlab.m
| 1,242 |
utf_8
|
c7cefea57d7bf6077ec6a77f3bdda6b6
|
/*-----------------------------------------------------------------------
File : use_cimgmatlab.m
Description: Example of use for the CImg plugin 'plugins/cimgmatlab.h'
which allows to use CImg in order to develop matlab external
functions (mex functions).
User should be familiar with Matlab C/C++ mex function concepts,
as this file is by no way a mex programming tutorial.
This simple example implements a mex function that can be called
as
- v = cimgmatlab_cannyderiche(u,s)
- v = cimgmatlab_cannyderiche(u,sx,sy)
- v = cimgmatlab_cannyderiche(u,sx,sy,sz)
The corresponding m-file is cimgmatlab_cannyderiche.m
Copyright : Francois Lauze - http://www.itu.dk/people/francois
This software is governed by the Gnu General Public License
see http://www.gnu.org/copyleft/gpl.html
The plugin home page is at
http://www.itu.dk/people/francois/cimgmatlab.html
for the compilation: using the mex utility provided with matlab, just
remember to add the -I flags with paths to CImg.h and/or cimgmatlab.h.
The default lcc cannot be used, it is a C compiler and not a C++ one!
--------------------------------------------------------------------------*/
function v = cimgmatlab_cannyderiche(u,sx,sy,sz)
|
github
|
M-T3K/UPM-master
|
Lagrange.m
|
.m
|
UPM-master/Algoritmica Numerica I/prac_provincias/Lagrange.m
| 351 |
utf_8
|
e95f109d17853801395ded5014eac57f
|
% p(x) = sum(i = 0..n, Li(x)*f(x_i))
function px = Lagrange(x, y, xx)
px = 0;
n = length(x)
for i = 1:n
Li = 1;
% Hacemos Bases de Lagrange
for j = 1:n
if j ~= i
Li = Li .* ( (xx - x(j) )/ (x(i) - x(j) ) ); % Li(x_i)
end
end
px = px + Li * y(i);
end
end
|
github
|
M-T3K/UPM-master
|
cost.m
|
.m
|
UPM-master/Algoritmica Numerica I/prac_provincias/cost.m
| 536 |
utf_8
|
02d733abf7d4d7402613f3ee45fda36b
|
% trazo se refiere a la funcion
% x_p se refiere a las coordenadas x de los puntos elegidos
% y_p se refiere a las coorenadas y de los puntos elegidos
function coste = cost(trazo, len, xx, x_p, y_p)
coste = 0;
n = length(x_p);
m = length(trazo);
for j = 1:m
for i = 1:n
if xx(j) == x_p(i)
dx = abs(y_p(i) - trazo(j));
if dx ~= 0
coste = coste + dx*0.5;
end
end
end
end
% coste = coste + len * 2;
end
|
github
|
M-T3K/UPM-master
|
Lagrangio.m
|
.m
|
UPM-master/Algoritmica Numerica I/prac_provincias/Lagrangio.m
| 379 |
utf_8
|
b6531bc3e5ca77772970459ea57f1ea3
|
% p(x) = sum(i = 0..n, Li(x)*f(x_i))
function px = Lagrangio(x, y, xx)
px = 0;
n = length(x)
for i = 1:n
Li = 1;
% Hacemos Bases de Lagrange
for j = 1:n
if j ~= i
Li = Li .* ( (xx - x(j) )/ (x(i) - x(j) ) ); % Li(x_i)
end
end
subplot(n, 1, i)
plot(xx, Li, 'b')
end
end
|
github
|
fbs2112/adaptive_multifilters-master
|
formatFig.m
|
.m
|
adaptive_multifilters-master/Misc/formatFig.m
| 4,039 |
utf_8
|
522ecaf1d786e78433b2e93b3ad16ca6
|
function formatFig(varargin)
%
% This function was created by Leonardo Nunes ([email protected]).
%
% This script configures the current figure. The folowing figure properties are configured:
% - text (ticks and labels) size
% - text (ticks and labels) font
% - line width
% - figure size
%
% If the variable 'figName' exists, a .fig, a .png, and an .eps files with the name
% contained in 'figName' are saved.
%
% Example:
% figProp = struct('size',14,'font','Times','lineWidth',2,'figDim',[1 1 600 400]);
% figFileName = sprintf('figs/rse_pos-%d',pos);
% formatFig(gcf,figFileName,'en',figProp);
%
% Tip: Always save .fig using 'en' (language) option, because 'en' converts well to 'pt',
% but 'pt' does not convert well to 'en' (commas are not replaced by dots)
%
figHandler = varargin{1};
figName = varargin{2};
lang = varargin{3};
% Congigurarion:
if(length(varargin)==4)
size = varargin{4}.size;
font = varargin{4}.font;
lineWidth = varargin{4}.lineWidth;
figDim = varargin{4}.figDim;
else
size = 21;
font = 'Times';
lineWidth = 2;
figDim = [1 1 600 400];
end
%--------------------------------------------------------------------------
% Configuring figure
if(~isempty(get(0,'CurrentFigure')))
set(figHandler,'Position',figDim);
fc = get(figHandler,'children'); % children of the current figure.
% Cycling through children:
for ii9183=1:length(fc)
if(strcmp(get(fc(ii9183),'Type'),'axes'))
% Configuring axes text:
set(fc(ii9183),'FontSize',size);
set(fc(ii9183),'FontName',font);
% Configuring label text:
ax = get(fc(ii9183),'xlabel');
set(ax,'FontSize',size);
set(ax,'FontName',font);
ay = get(fc(ii9183),'ylabel');
set(ay,'FontSize',size);
set(ay,'FontName',font);
% Configuring title text:
at = get(fc(ii9183),'title');
set(at,'FontSize',size);
set(at,'FontName',font);
ac = get(fc(ii9183),'children'); % axes children.
for jj98719=1:length(ac)
if(strcmp(get(ac(jj98719),'Type'),'line'))
set(ac(jj98719),'LineWidth',lineWidth);
if(strcmp(get(ac(jj98719),'marker'),'.'))
set(ac(jj98719),'markerSize',15);
end
end
if(strcmp(get(ac(jj98719),'Type'),'text'))
set(ac(jj98719),'FontSize',size);
set(ac(jj98719),'FontName',font);
end
end
if(strcmpi(lang,'pt'))
tick = get(fc(ii9183),'XTickLabel');
tick = changeComma(tick);
set(fc(ii9183),'XTickLabel',tick);
tick = get(fc(ii9183),'YTickLabel');
tick = changeComma(tick);
set(fc(ii9183),'YTickLabel',tick);
tick = get(fc(ii9183),'ZTickLabel');
tick = changeComma(tick);
set(fc(ii9183),'ZTickLabel',tick);
set(fc(ii9183),'XTickMode','manual');
set(fc(ii9183),'YTickMode','manual');
set(fc(ii9183),'ZTickMode','manual');
end
end
end
set(figHandler,'Position',figDim);
set(figHandler,'PaperPositionMode','auto')
aux = [figName '.eps'];
saveas(figHandler,aux,'epsc2');
aux = [figName '.fig'];
saveas(figHandler,aux);
aux = [figName '.pdf']; % .png, pdf, jpg
saveas(figHandler,aux);
aux = [figName '.png'];
saveas(figHandler,aux);
end
function str = changeComma(str)
for ii = 1:size(str,1)
str(ii,:) = regexprep(str(ii,:),'[.]', ',');
end
|
github
|
xylimeng/WARP-master
|
phantom3d.m
|
.m
|
WARP-master/phantom3d.m
| 8,295 |
utf_8
|
dfa7b40691a0d7f82426d690e64afcda
|
function [p,ellipse]=phantom3d(varargin)
%PHANTOM3D Three-dimensional analogue of MATLAB Shepp-Logan phantom
% P = PHANTOM3D(DEF,N) generates a 3D head phantom that can
% be used to test 3-D reconstruction algorithms.
%
% DEF is a string that specifies the type of head phantom to generate.
% Valid values are:
%
% 'Shepp-Logan' A test image used widely by researchers in
% tomography
% 'Modified Shepp-Logan' (default) A variant of the Shepp-Logan phantom
% in which the contrast is improved for better
% visual perception.
%
% N is a scalar that specifies the grid size of P.
% If you omit the argument, N defaults to 64.
%
% P = PHANTOM3D(E,N) generates a user-defined phantom, where each row
% of the matrix E specifies an ellipsoid in the image. E has ten columns,
% with each column containing a different parameter for the ellipsoids:
%
% Column 1: A the additive intensity value of the ellipsoid
% Column 2: a the length of the x semi-axis of the ellipsoid
% Column 3: b the length of the y semi-axis of the ellipsoid
% Column 4: c the length of the z semi-axis of the ellipsoid
% Column 5: x0 the x-coordinate of the center of the ellipsoid
% Column 6: y0 the y-coordinate of the center of the ellipsoid
% Column 7: z0 the z-coordinate of the center of the ellipsoid
% Column 8: phi phi Euler angle (in degrees) (rotation about z-axis)
% Column 9: theta theta Euler angle (in degrees) (rotation about x-axis)
% Column 10: psi psi Euler angle (in degrees) (rotation about z-axis)
%
% For purposes of generating the phantom, the domains for the x-, y-, and
% z-axes span [-1,1]. Columns 2 through 7 must be specified in terms
% of this range.
%
% [P,E] = PHANTOM3D(...) returns the matrix E used to generate the phantom.
%
% Class Support
% -------------
% All inputs must be of class double. All outputs are of class double.
%
% Remarks
% -------
% For any given voxel in the output image, the voxel's value is equal to the
% sum of the additive intensity values of all ellipsoids that the voxel is a
% part of. If a voxel is not part of any ellipsoid, its value is 0.
%
% The additive intensity value A for an ellipsoid can be positive or negative;
% if it is negative, the ellipsoid will be darker than the surrounding pixels.
% Note that, depending on the values of A, some voxels may have values outside
% the range [0,1].
%
% Example
% -------
% ph = phantom3d(128);
% figure, imshow(squeeze(ph(64,:,:)))
%
% Copyright 2005 Matthias Christian Schabel (matthias @ stanfordalumni . org)
% University of Utah Department of Radiology
% Utah Center for Advanced Imaging Research
% 729 Arapeen Drive
% Salt Lake City, UT 84108-1218
%
% This code is released under the Gnu Public License (GPL). For more information,
% see : http://www.gnu.org/copyleft/gpl.html
%
% Portions of this code are based on phantom.m, copyrighted by the Mathworks
%
[ellipse,n] = parse_inputs(varargin{:});
p = zeros([n n n]);
rng = ( (0:n-1)-(n-1)/2 ) / ((n-1)/2);
[x,y,z] = meshgrid(rng,rng,rng);
coord = [flatten(x); flatten(y); flatten(z)];
p = flatten(p);
for k = 1:size(ellipse,1)
A = ellipse(k,1); % Amplitude change for this ellipsoid
asq = ellipse(k,2)^2; % a^2
bsq = ellipse(k,3)^2; % b^2
csq = ellipse(k,4)^2; % c^2
x0 = ellipse(k,5); % x offset
y0 = ellipse(k,6); % y offset
z0 = ellipse(k,7); % z offset
phi = ellipse(k,8)*pi/180; % first Euler angle in radians
theta = ellipse(k,9)*pi/180; % second Euler angle in radians
psi = ellipse(k,10)*pi/180; % third Euler angle in radians
cphi = cos(phi);
sphi = sin(phi);
ctheta = cos(theta);
stheta = sin(theta);
cpsi = cos(psi);
spsi = sin(psi);
% Euler rotation matrix
alpha = [cpsi*cphi-ctheta*sphi*spsi cpsi*sphi+ctheta*cphi*spsi spsi*stheta;
-spsi*cphi-ctheta*sphi*cpsi -spsi*sphi+ctheta*cphi*cpsi cpsi*stheta;
stheta*sphi -stheta*cphi ctheta];
% rotated ellipsoid coordinates
coordp = alpha*coord;
idx = find((coordp(1,:)-x0).^2./asq + (coordp(2,:)-y0).^2./bsq + (coordp(3,:)-z0).^2./csq <= 1);
p(idx) = p(idx) + A;
end
p = reshape(p,[n n n]);
return;
function out = flatten(in)
out = reshape(in,[1 prod(size(in))]);
return;
function [e,n] = parse_inputs(varargin)
% e is the m-by-10 array which defines ellipsoids
% n is the size of the phantom brain image
n = 128; % The default size
e = [];
defaults = {'shepp-logan', 'modified shepp-logan', 'yu-ye-wang'};
for i=1:nargin
if ischar(varargin{i}) % Look for a default phantom
def = lower(varargin{i});
idx = strmatch(def, defaults);
if isempty(idx)
eid = sprintf('Images:%s:unknownPhantom',mfilename);
msg = 'Unknown default phantom selected.';
error(eid,'%s',msg);
end
switch defaults{idx}
case 'shepp-logan'
e = shepp_logan;
case 'modified shepp-logan'
e = modified_shepp_logan;
case 'yu-ye-wang'
e = yu_ye_wang;
end
elseif numel(varargin{i})==1
n = varargin{i}; % a scalar is the image size
elseif ndims(varargin{i})==2 && size(varargin{i},2)==10
e = varargin{i}; % user specified phantom
else
eid = sprintf('Images:%s:invalidInputArgs',mfilename);
msg = 'Invalid input arguments.';
error(eid,'%s',msg);
end
end
% ellipse is not yet defined
if isempty(e)
e = modified_shepp_logan;
end
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Default head phantoms: %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function e = shepp_logan
e = modified_shepp_logan;
e(:,1) = [1 -.98 -.02 -.02 .01 .01 .01 .01 .01 .01];
return;
function e = modified_shepp_logan
%
% This head phantom is the same as the Shepp-Logan except
% the intensities are changed to yield higher contrast in
% the image. Taken from Toft, 199-200.
%
% A a b c x0 y0 z0 phi theta psi
% -----------------------------------------------------------------
e = [ 1 .6900 .920 .810 0 0 0 0 0 0
-.8 .6624 .874 .780 0 -.0184 0 0 0 0
-.2 .1100 .310 .220 .22 0 0 -18 0 10
-.2 .1600 .410 .280 -.22 0 0 18 0 10
.1 .2100 .250 .410 0 .35 -.15 0 0 0
.1 .0460 .046 .050 0 .1 .25 0 0 0
.1 .0460 .046 .050 0 -.1 .25 0 0 0
.1 .0460 .023 .050 -.08 -.605 0 0 0 0
.1 .0230 .023 .020 0 -.606 0 0 0 0
.1 .0230 .046 .020 .06 -.605 0 0 0 0 ];
return;
function e = yu_ye_wang
%
% Yu H, Ye Y, Wang G, Katsevich-Type Algorithms for Variable Radius Spiral Cone-Beam CT
%
% A a b c x0 y0 z0 phi theta psi
% -----------------------------------------------------------------
e = [ 1 .6900 .920 .900 0 0 0 0 0 0
-.8 .6624 .874 .880 0 0 0 0 0 0
-.2 .4100 .160 .210 -.22 0 -.25 108 0 0
-.2 .3100 .110 .220 .22 0 -.25 72 0 0
.2 .2100 .250 .500 0 .35 -.25 0 0 0
.2 .0460 .046 .046 0 .1 -.25 0 0 0
.1 .0460 .023 .020 -.08 -.65 -.25 0 0 0
.1 .0460 .023 .020 .06 -.65 -.25 90 0 0
.2 .0560 .040 .100 .06 -.105 .625 90 0 0
-.2 .0560 .056 .100 0 .100 .625 0 0 0 ];
return;
|
github
|
xylimeng/WARP-master
|
mex_this.m
|
.m
|
WARP-master/mex_this.m
| 644 |
utf_8
|
8a2d4ddbd2fe11a7a6155a00fa0a0e2b
|
% 'path' is the absolute path of the directory containing the header 'armadillo'
% For example, it could be '/usr/local/include' in macOS
function mex_this(path)
if nargin == 0
path = '/usr/local/include'; % default
end
ipath = ['-I' path];
mex('-v', ipath, '-larmadillo', '-lgfortran', 'treeLikelihood.cpp', 'tree_class.cpp','helper.cpp');
mex('-v', ipath, '-larmadillo', '-lgfortran', 'treeFit.cpp', 'tree_class.cpp','helper.cpp');
% mex -I/usr/local/include -larmadillo -lgfortran treeLikelihood.cpp tree_class.cpp helper.cpp -v
% mex -I/usr/local/include -larmadillo -lgfortran treeFit.cpp tree_class.cpp helper.cpp -v
end
|
github
|
xylimeng/WARP-master
|
sim_data.m
|
.m
|
WARP-master/sim_data.m
| 2,141 |
utf_8
|
8109f9b7e8ce14b9c0cb272cdd5ab881
|
% function to generate the true 3D images
% f1: f1 in Peihua Qiu's paper
% f2: f2 in Peihua Qiu's paper
% f3: 3D phantom
% Input: n - length of each dimensiona;
% sigma_noise - standard deviation of Gaussian noise;
% type - type of simulated data, could be f1, f2 or f3
function [true, obs] = sim_data(n, sigma_noise, type)
if type ~= 3
n1 = n;
n2= n;
n3 = n;
z = zeros([1,n1*n2*n3]);
if (type == 1)
for (i = 1:n1)
for (j = 1:n2)
for (k = 1:n3)
z((i-1)*n2*n3+(j-1)*n3+k) = -(i/n1-0.5)^2 -(j/n2-0.5)^2 -(k/n3-0.5)^2;
if ( ((abs(i/n1-0.5)<=0.25) & (abs(j/n2-0.5)<=0.25) & (abs(k/n3-0.5)<=0.25)) )
z((i-1)*n2*n3+(j-1)*n3+k) = -(i/n1-0.5)^2 -(j/n2-0.5)^2 -(k/n3-0.5)^2 + 1;
end
if ( (((i/n1-0.5)^2+(j/n2-0.5)^2 <=0.15^2) & (abs(k/n3-0.5)<=0.35)) )
z((i-1)*n2*n3+(j-1)*n3+k) = -(i/n1-0.5)^2 -(j/n2-0.5)^2 -(k/n3-0.5)^2 + 1;
end
end
end
end
end
if (type == 2)
for (i = 1:n1)
for (j = 1:n2)
for (k = 1:n3)
z((i-1)*n2*n3+(j-1)*n3+k) = 1/4 * sin(2*pi*(i/n1 + j/n2 + k/n3) + 1) + 0.25;
if ( (((i/n1-0.5)^2 + (j/n2 - 0.5)^2 <= 1/4 * (k/n3 - 0.5)^2)) & (k/n3 >= 0.2) & (k/n3 <= 0.5) )
z((i-1)*n2*n3+(j-1)*n3+k) = 1/4 * sin(2*pi*(i/n1 + j/n2 + k/n3) + 1) + 1.25;
end
if ( (((i/n1-0.5)^2+(j/n2-0.5)^2 + (k/n3 - 0.5)^2) <= 0.4^2) & ((i/n1-0.5)^2+(j/n2-0.5)^2 + (k/n3 - 0.5)^2 > 0.2^2) & (k/n3 < 0.45) )
z((i-1)*n2*n3+(j-1)*n3+k) = 1/4 * sin(2*pi*(i/n1 + j/n2 + k/n3) + 1) + 1.25;
end
end
end
end
end
g = z + randn(size(z)) * sigma_noise;
true = zeros([n1,n2,n3]);
obs = true;
for (i = 1:n1)
for (j = 1:n2)
for (k = 1:n3)
true(i,j,k) = z((i-1)*n2*n3+(j-1)*n3+k);
obs(i,j,k) = g((i-1)*n2*n3+(j-1)*n3+k);
end
end
end
end
if type == 3
true = phantom3d(n);
obs = true + randn([n,n,n]) .* sigma_noise;
end
end
|
github
|
dustin-cook/Opensees-master
|
collect_sensitivity_data.m
|
.m
|
Opensees-master/collect_sensitivity_data.m
| 4,863 |
utf_8
|
c3f518cdc4fd91f19e9f82de229a7001
|
clear all
close all
clc
% Collect results from model sensitivity study
% Define Model
analysis.model_id = 18;
analysis.proceedure = 'NDP';
analysis.id = 'baseline_beams';
analysis.model = 'ICBS_model_5ew_col_base';
%% Define outputs directories
analysis_name = [analysis.proceedure '_' analysis.id];
outputs_dir = ['outputs' filesep analysis.model filesep analysis_name filesep 'sensitivity_study' ];
%% Define sensitivity study parameters
% model_name = {'ductility', 'ductility_no_var', 'strength', 'both', 'both_more'};
model_name = {'ductility', 'strength', 'both'};
% model_name = {'both'};
num_bays = 5; % just hardcoded for now
%% Collect baseline data
% Baseline for sensitivity
baseline_dir = ['outputs' filesep analysis.model filesep analysis_name];
id = 1;
[ outputs_table_base, baseline_input_dir ] = collect_baseline_data( baseline_dir, id, 'baseline', num_bays );
% % ICSB 2D Model
% baseline_dir = ['outputs' filesep 'ICBS_model_5ew' filesep 'NDP_baseline'];
% id = 2;
% [ outputs_table_2D, ~ ] = collect_baseline_data( baseline_dir, id, 'ICSB_2D', num_bays );
% % ICSB 3D Model
% baseline_dir = ['outputs' filesep 'ICBS_model_3D_fixed' filesep 'NDP_baseline'];
% id = 3;
% [ outputs_table_3D, ~ ] = collect_baseline_data( baseline_dir, id, 'ICSB_3D', num_bays );
% Join tables
% outputs_table = [outputs_table_base; outputs_table_2D; outputs_table_3D];
% outputs_table = [outputs_table_base; outputs_table_2D];
outputs_table = outputs_table_base;
%% Collect data for each sensitivity study
for m = 1:length(model_name)
% Read all models
model_dir = [outputs_dir filesep model_name{m} filesep 'model_files'];
models = dir([model_dir filesep 'model_*']);
for mdl = 1:length(models)
% Define model directories
this_model_dir = [model_dir filesep models(mdl).name];
inputs_dir = [this_model_dir filesep 'asce_41_data'];
load([inputs_dir filesep 'element_analysis.mat'])
load([inputs_dir filesep 'joint_analysis.mat'])
load([baseline_input_dir filesep 'story_analysis.mat'])
% Calculate input parameters
[strength_cov, ductility_cov, energy_cov, scwb_ratio] = collect_model_inputs(element, story, joint);
% Load sensitivity summary results
summary_results = readtable([this_model_dir filesep 'IDA' filesep 'Fragility Data' filesep 'summary_outputs.csv']);
% Join tables
id = id + 1;
[outputs_table_row] = create_outputs_table(id, model_name{m}, mdl, strength_cov, ductility_cov, energy_cov, scwb_ratio, num_bays, summary_results);
outputs_table = [outputs_table; outputs_table_row];
end
end
% Write sensitivity study outputs file
writetable(outputs_table,[outputs_dir filesep 'summary_results.csv'])
% Functions
function [strength_cov, ductility_cov, energy_cov, scwb_ratio] = collect_model_inputs(element, story, joint)
first_story_columns = element(element.story == 1 & strcmp(element.type,'column'),:);
strength_cov = std(first_story_columns.Mn_pos_1)/mean(first_story_columns.Mn_pos_1);
ductility_cov = std(first_story_columns.b_hinge_1)/mean(first_story_columns.b_hinge_1);
energy_cov = std(first_story_columns.b_hinge_1.*first_story_columns.Mn_pos_1)/mean(first_story_columns.b_hinge_1.*first_story_columns.Mn_pos_1);
for s = 1:height(story)
story.scwb(s) = mean(joint.col_bm_ratio(joint.story == s));
end
scwb_ratio = mean(story.scwb);
end
function [outputs_table_row] = create_outputs_table(id, group, variant, strength_cov, ductility_cov, energy_cov, scwb_ratio, num_bays, summary_results)
inputs.id = id;
summary_results.id = id;
inputs.group = {group};
inputs.variant = variant;
inputs.strength_cov = strength_cov;
inputs.ductility_cov = ductility_cov;
inputs.energy_cov = energy_cov;
inputs.scwb_ratio = scwb_ratio;
inputs.num_bays = num_bays;
inputs_table = struct2table(inputs);
outputs_table_row = join(inputs_table, summary_results);
end
function [ outputs_table, baseline_input_dir ] = collect_baseline_data( baseline_dir, id, model_name, num_bays )
% Define model directories
baseline_input_dir = [baseline_dir filesep 'asce_41_data'];
% Calculate input parameters
load([baseline_input_dir filesep 'element_analysis.mat'])
load([baseline_input_dir filesep 'joint_analysis.mat'])
load([baseline_input_dir filesep 'story_analysis.mat'])
[strength_cov, ductility_cov, energy_cov, scwb_ratio] = collect_model_inputs(element, story, joint);
% Load sensitivity summary results
summary_results = readtable([baseline_dir filesep 'IDA' filesep 'Fragility Data' filesep 'summary_outputs.csv']);
% Create Outputs Table
[outputs_table] = create_outputs_table(id, model_name, 1, strength_cov, ductility_cov, energy_cov, scwb_ratio, num_bays, summary_results);
end
|
github
|
dustin-cook/Opensees-master
|
process_multiple_IDA.m
|
.m
|
Opensees-master/process_multiple_IDA.m
| 5,504 |
utf_8
|
df05c881e505cb66a8b6a1aead7363d6
|
%% Script to:
% 1. pull sensitivity results from Dropbox
% 2. run frag curve post processors on all of them
% 3. save results in repo folders
% 4. Create cummulative plots
clear all
close all
clc
import ida.*
import plotting_tools.*
%% Define inputs
model_baseline_name = 'NDP_baseline_1';
model.name{1} = 'ICBS_model_5ew_col_base';
model_names = {'Model_uniform' 'NDP_baseline' 'Model' 'Model' 'Model' 'Model' 'Model' 'NDP_Model_extreme' };
model_ids = {'1' '1' '1' '4' '6' '8' '10' '1'};
% model_names = {'NDP_Model_extreme'};
% model_ids = {'1'};
analysis.run_z_motion = 0;
ida_results.direction = {'EW'; 'NS'};
ida_results.period = [1.14; 0.35];
ida_results.spectra = [0.56; 1.18]; % max direction spectra of ICSB motion
ida_results.mce = [0.79; 1.55]; % MCE Max from SP3, fixed to this site and model period
% Load ground motion data
gm_set_table = readtable(['ground_motions' filesep 'FEMA_far_field' filesep 'ground_motion_set.csv'],'ReadVariableNames',true);
%% For each model
for m = 1:length(model_names)
% Define Analysis Name and Location
analysis.proceedure = model_names{m};
analysis.id = model_ids{m};
write_dir = ['outputs/' model.name{1} '/' analysis.proceedure '_' analysis.id '/IDA/Fragility Data'];
pushover_dir = ['outputs' '/' model.name{1} '/' model_baseline_name '/' 'pushover'];
model_dir = ['outputs' '/' model.name{1} '/' model_baseline_name '/' 'opensees_data'];
if ~exist(write_dir,'dir')
mkdir(write_dir)
end
% Post Process for Fragilities
sprintf('%s_%s', analysis.proceedure, analysis.id)
% fn_collect_ida_data(analysis, model, gm_set_table, ida_results, write_dir, pushover_dir, model_dir)
% fn_create_fragilities(analysis, gm_set_table, write_dir)
% Collect Summary Statistics
read_dir = ['outputs' '/' model.name{1} '/' analysis.proceedure '_' analysis.id '/' 'IDA' '/' 'Fragility Data'];
ele_dir = ['outputs' '/' model.name{1} '/' analysis.proceedure '_' analysis.id '/' 'asce_41_data'];
[percent_CP, sa_med_col, sa_med_cp, col_margin, min_cp_med, mean_cp_med, max_cp_med, column_cov, column_base_cov, column_min, column_range] = fn_collect_cummary_data(read_dir, ele_dir);
models.percent_CP(:,m) = percent_CP;
models.sa_med_col(m) = sa_med_col;
models.sa_med_cp(m) = sa_med_cp;
models.col_margin(m) = col_margin;
models.min_cp_med(m) = min_cp_med;
models.mean_cp_med(m) = mean_cp_med;
models.max_cp_med(m) = max_cp_med;
models.column_cov(m) = column_cov;
models.column_base_cov(m) = column_base_cov;
models.column_min(m) = column_min;
models.column_range(m) = column_range;
end
%% Create Plots
outputs_dir = ['outputs' filesep 'ICBS_model_3D_fixed' filesep 'NDP_IDA_new' filesep 'sensitivity_study'];
rank = ((1:44)/44)';
cmap = colormap(jet(100));
hold on
for i = 1:length(model_names)
plot(models.percent_CP(:,i),rank,'color',cmap(max(round(100*models.column_cov(i)),1),:),'linewidth',1.25)
end
xlabel('Fraction of Components Exceeding CP')
ylabel('P[Collapse]')
h = colorbar;
h.Limits = [0,0.7];
ylabel(h, 'Column Deformation Capacity COV')
grid on
box on
fn_format_and_save_plot( outputs_dir, 'Multi Percent CP plot', 4, 1 )
hold on
plot(models.column_cov, models.sa_med_cp,'b','marker','o','DisplayName','CP')
plot(models.column_cov, models.sa_med_col,'k','marker','d','DisplayName','Collapse')
ylim([0,1])
xlabel('Column Deformation Capacity COV')
ylabel('Median Sa')
legend('location','northeast')
grid on
box on
fn_format_and_save_plot( outputs_dir, 'Median Exceedence Trend', 4, 1 )
plot(models.column_cov, models.col_margin,'k','marker','o')
ylim([0,2])
xlabel('Column Deformation Capacity COV')
ylabel('Collapse Margin')
grid on
box on
fn_format_and_save_plot( outputs_dir, 'Collapse Margin Trend', 4, 1 )
hold on
plot(models.column_cov, models.min_cp_med,'b','marker','o','DisplayName','Min')
plot(models.column_cov, models.mean_cp_med,'k','marker','d','DisplayName','Mean')
plot(models.column_cov, models.max_cp_med,'r','marker','s','DisplayName','Max')
ylim([0,2])
xlabel('Column Deformation Capacity COV')
ylabel('Median Deformation Demand to CP Ratio')
legend('location','northeast')
grid on
box on
fn_format_and_save_plot( outputs_dir, 'Min Mean Max Trend', 4, 1 )
function [percent_CP, sa_med_col, sa_med_cp, col_margin, min_cp_med, mean_cp_med, max_cp_med, column_cov, column_base_cov, column_min, column_range] = fn_collect_cummary_data(read_dir, ele_dir)
load([read_dir filesep 'frag_curves.mat'])
load([read_dir filesep 'new_frag_curves.mat'])
load([read_dir filesep 'gm_data.mat'])
load([ele_dir filesep 'element_analysis.mat'])
% Percent Comps exceede CP discrete fragilitu
percent_CP = sort(gm_data.collapse.cols_walls_1_percent_cp);
% Median Collapse Capacity
sa_med_col = frag_curves.collapse.theta;
% Collapse Margin
sa_med_cp = frag_curves.cols_walls_1.cp.theta(1);
col_margin = sa_med_col / sa_med_cp;
% Min Mean Max CP
min_cp_med = new_frag_curves.collapse.cols_walls_1_min_cp.theta;
mean_cp_med = new_frag_curves.collapse.cols_walls_1_mean_cp.theta;
max_cp_med = new_frag_curves.collapse.cols_walls_1_max_cp.theta;
% Calculate Element COV
columns = element(element.story == 1 & strcmp(element.type,'column'),:);
column_cov = std(columns.b_hinge_1 + columns.b_hinge_2) / mean(columns.b_hinge_1 + columns.b_hinge_2);
column_base_cov = std(columns.b_hinge_1) / mean(columns.b_hinge_1);
column_min = min(columns.b_hinge_1);
column_range = max(columns.b_hinge_1) - min(columns.b_hinge_1);
end
|
github
|
dustin-cook/Opensees-master
|
xml2struct.m
|
.m
|
Opensees-master/+file_exchange/xml2struct.m
| 6,766 |
utf_8
|
fef7daf056271b3557a6d729d3dd392a
|
function [ s ] = xml2struct( file )
%Convert xml file into a MATLAB structure
% [ s ] = xml2struct( file )
%
% A file containing:
% <XMLname attrib1="Some value">
% <Element>Some text</Element>
% <DifferentElement attrib2="2">Some more text</Element>
% <DifferentElement attrib3="2" attrib4="1">Even more text</DifferentElement>
% </XMLname>
%
% Will produce:
% s.XMLname.Attributes.attrib1 = "Some value";
% s.XMLname.Element.Text = "Some text";
% s.XMLname.DifferentElement{1}.Attributes.attrib2 = "2";
% s.XMLname.DifferentElement{1}.Text = "Some more text";
% s.XMLname.DifferentElement{2}.Attributes.attrib3 = "2";
% s.XMLname.DifferentElement{2}.Attributes.attrib4 = "1";
% s.XMLname.DifferentElement{2}.Text = "Even more text";
%
% Please note that the following characters are substituted
% '-' by '_dash_', ':' by '_colon_' and '.' by '_dot_'
%
% Written by W. Falkena, ASTI, TUDelft, 21-08-2010
% Attribute parsing speed increased by 40% by A. Wanner, 14-6-2011
% Added CDATA support by I. Smirnov, 20-3-2012
%
% Modified by X. Mo, University of Wisconsin, 12-5-2012
if (nargin < 1)
clc;
help xml2struct
return
end
if isa(file, 'org.apache.xerces.dom.DeferredDocumentImpl') || isa(file, 'org.apache.xerces.dom.DeferredElementImpl')
% input is a java xml object
xDoc = file;
else
%check for existance
if (exist(file,'file') == 0)
%Perhaps the xml extension was omitted from the file name. Add the
%extension and try again.
if (isempty(strfind(file,'.xml')))
file = [file '.xml'];
end
if (exist(file,'file') == 0)
error(['The file ' file ' could not be found']);
end
end
%read the xml file
xDoc = xmlread(file);
end
%parse xDoc into a MATLAB structure
s = parseChildNodes(xDoc);
end
% ----- Subfunction parseChildNodes -----
function [children,ptext,textflag] = parseChildNodes(theNode)
% Recurse over node children.
children = struct;
ptext = struct; textflag = 'Text';
if hasChildNodes(theNode)
childNodes = getChildNodes(theNode);
numChildNodes = getLength(childNodes);
for count = 1:numChildNodes
theChild = item(childNodes,count-1);
[text,name,attr,childs,textflag] = getNodeData(theChild);
if (~strcmp(name,'#text') && ~strcmp(name,'#comment') && ~strcmp(name,'#cdata_dash_section'))
%XML allows the same elements to be defined multiple times,
%put each in a different cell
if (isfield(children,name))
if (~iscell(children.(name)))
%put existsing element into cell format
children.(name) = {children.(name)};
end
index = length(children.(name))+1;
%add new element
children.(name){index} = childs;
if(~isempty(fieldnames(text)))
children.(name){index} = text;
end
if(~isempty(attr))
children.(name){index}.('Attributes') = attr;
end
else
%add previously unknown (new) element to the structure
children.(name) = childs;
if(~isempty(text) && ~isempty(fieldnames(text)))
children.(name) = text;
end
if(~isempty(attr))
children.(name).('Attributes') = attr;
end
end
else
ptextflag = 'Text';
if (strcmp(name, '#cdata_dash_section'))
ptextflag = 'CDATA';
elseif (strcmp(name, '#comment'))
ptextflag = 'Comment';
end
%this is the text in an element (i.e., the parentNode)
if (~isempty(regexprep(text.(textflag),'[\s]*','')))
if (~isfield(ptext,ptextflag) || isempty(ptext.(ptextflag)))
ptext.(ptextflag) = text.(textflag);
else
%what to do when element data is as follows:
%<element>Text <!--Comment--> More text</element>
%put the text in different cells:
% if (~iscell(ptext)) ptext = {ptext}; end
% ptext{length(ptext)+1} = text;
%just append the text
ptext.(ptextflag) = [ptext.(ptextflag) text.(textflag)];
end
end
end
end
end
end
% ----- Subfunction getNodeData -----
function [text,name,attr,childs,textflag] = getNodeData(theNode)
% Create structure of node info.
%make sure name is allowed as structure name
name = toCharArray(getNodeName(theNode))';
name = strrep(name, '-', '_dash_');
name = strrep(name, ':', '_colon_');
name = strrep(name, '.', '_dot_');
attr = parseAttributes(theNode);
if (isempty(fieldnames(attr)))
attr = [];
end
%parse child nodes
[childs,text,textflag] = parseChildNodes(theNode);
if (isempty(fieldnames(childs)) && isempty(fieldnames(text)))
%get the data of any childless nodes
% faster than if any(strcmp(methods(theNode), 'getData'))
% no need to try-catch (?)
% faster than text = char(getData(theNode));
text.(textflag) = toCharArray(getTextContent(theNode))';
end
end
% ----- Subfunction parseAttributes -----
function attributes = parseAttributes(theNode)
% Create attributes structure.
attributes = struct;
if hasAttributes(theNode)
theAttributes = getAttributes(theNode);
numAttributes = getLength(theAttributes);
for count = 1:numAttributes
%attrib = item(theAttributes,count-1);
%attr_name = regexprep(char(getName(attrib)),'[-:.]','_');
%attributes.(attr_name) = char(getValue(attrib));
%Suggestion of Adrian Wanner
str = toCharArray(toString(item(theAttributes,count-1)))';
k = strfind(str,'=');
attr_name = str(1:(k(1)-1));
attr_name = strrep(attr_name, '-', '_dash_');
attr_name = strrep(attr_name, ':', '_colon_');
attr_name = strrep(attr_name, '.', '_dot_');
attributes.(attr_name) = str((k(1)+2):(end-1));
end
end
end
|
github
|
dustin-cook/Opensees-master
|
main_ASCE_41_post_process.m
|
.m
|
Opensees-master/+asce_41/main_ASCE_41_post_process.m
| 4,838 |
utf_8
|
b2dd01dfc4dd125661da841739818ef9
|
function [ capacity, torsion ] = main_ASCE_41_post_process( analysis, ele_prop_table )
% Description: Main script that post process an ASCE 41 analysis
% Created By: Dustin Cook
% Date Created: 1/3/2019
% Inputs:
% Outputs:
% Assumptions:
%% Initial Setup
% Import Packages
import asce_41.*
% Define Read and Write Directories
read_dir = [analysis.out_dir filesep 'opensees_data'];
write_dir = [analysis.out_dir filesep 'asce_41_data'];
if ~exist(write_dir,'dir')
fn_make_directory( write_dir )
end
% Load Analysis Data
load([read_dir filesep 'model_analysis.mat'])
load([read_dir filesep 'story_analysis.mat'])
load([read_dir filesep 'element_analysis.mat'])
load([read_dir filesep 'joint_analysis.mat'])
load([read_dir filesep 'node_analysis.mat'])
%% Calculate Element Properties and Modify Analysis Results based on ASCE 41-17
% Basic building or analysis properties
[ model, element, torsion, node ] = fn_basic_analysis_properties( model, story, element, node );
% Filter Accelerations
if analysis.type == 1 && analysis.filter_accel == 1
[ story ] = fn_accel_filter(node, story, analysis.filter_freq_range, read_dir, write_dir);
end
if analysis.asce_41_post_process
% Procedure Specific Analysis
if strcmp(analysis.proceedure,'NDP') && analysis.type == 1 % Nonlinear Dynamic Proceedure
% Merge demands from analysis into capacities from pushover
[element] = fn_merge_demands(element, write_dir, model);
[joint] = fn_merge_joint_demands(joint, element, ele_prop_table, write_dir, read_dir);
% calculate hinge demand to capacity ratios
load([read_dir filesep 'hinge_analysis.mat'])
[ hinge ] = fn_accept_hinge( element, ele_prop_table, hinge, read_dir, node );
[ joint ] = fn_accept_joint( joint, analysis.joint_explicit, read_dir);
elseif strcmp(analysis.proceedure,'LDP') && analysis.type == 1 % Linear Dynamic Proceedure
% Merge demands from analysis into capacities from pushover
[element] = fn_merge_demands(element, write_dir, model);
[joint] = fn_merge_joint_demands(joint, element, ele_prop_table, write_dir);
else % Pushovers and all other cases
[ element, joint ] = main_element_capacity( story, ele_prop_table, element, analysis, joint, read_dir, write_dir );
[ element, joint ] = main_hinge_properties( ele_prop_table, element, joint );
end
end
%% Save Data
save([write_dir filesep 'model_analysis.mat'],'model')
save([write_dir filesep 'story_analysis.mat'],'story')
save([write_dir filesep 'element_analysis.mat'],'element')
save([write_dir filesep 'joint_analysis.mat'],'joint')
save([write_dir filesep 'node_analysis.mat'],'node')
if exist('hinge','var')
save([write_dir filesep 'hinge_analysis.mat'],'hinge')
end
% Save load case info
if ~strcmp(analysis.case,'NA')
write_dir = [analysis.out_dir filesep analysis.case];
fn_make_directory( write_dir )
save([write_dir filesep 'story_analysis.mat'],'story')
save([write_dir filesep 'element_analysis.mat'],'element')
if exist('hinge','var')
save([write_dir filesep 'hinge_analysis.mat'],'hinge')
end
end
% % Save capacities to compare iterations
% if analysis.asce_41_post_process
% capacity = element.capacity;
% else
% capacity = [];
% end
end
function [element] = fn_merge_demands(element, write_dir, model)
% Save demand tables from most recent opensees run
OS_demands = element;
% Load Post process capacity data
load([write_dir filesep 'element_analysis.mat'])
% Merge demands into capacity tables
element.Pmax = OS_demands.Pmax;
element.Pmin = OS_demands.Pmin;
element.Vmax_1 = OS_demands.Vmax_1;
element.Vmax_2 = OS_demands.Vmax_2;
if strcmp(model.dimension,'3D')
element.Vmax_oop_1 = OS_demands.Vmax_oop_1;
element.Vmax_oop_2 = OS_demands.Vmax_oop_2;
end
element.Mmax_1 = OS_demands.Mmax_1;
element.Mmax_2 = OS_demands.Mmax_2;
% Keep node info from latest run (for linear sake)
element.node_1 = OS_demands.node_1;
element.node_2 = OS_demands.node_2;
end
function [joint] = fn_merge_joint_demands(joint, element, ele_prop_table, write_dir, read_dir)
%% Joints
% import packages
import asce_41.fn_joint_capacity
% Load Post process capacity data
load([write_dir filesep 'joint_analysis.mat'])
% Save demand tables from most recent opensees run
OS_joint = joint;
% Determine Joint demands based on element capacities
for i = 1:height(OS_joint)
OS_jnt = OS_joint(i,:);
TH_file = [read_dir filesep 'joint_TH_' num2str(OS_jnt.id) '.mat'];
if ~exist(TH_file,'file')
jnt_TH = [];
else
load(TH_file)
end
[ OS_jnt ] = fn_joint_capacity( OS_jnt, element, ele_prop_table, jnt_TH );
% Merge joint demands into capacity table
joint.Pmax(i) = OS_jnt.Pmax;
joint.Vmax(i) = OS_jnt.Vmax;
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.