text:
filename = 'SquareCantilever6400';%'CantileverSquareNew';%'CantileverSquareSym';%'CantileverSquareNewFine';%'LshapeTriFine';%'CantileverSquareNew';'ArchTriFine';%'CantileverSquare';%'ArchTriFine';%'CantileverSquare';%'Lshape';%'LshapeTriFine';%'CantileverSquareSmall';%'';%'Lshape';'CantileverSquare';'Lshape';%'CantileverSquare';%'LshapeFine';%'Bridge_quad_coarse';%'Arch_quad_coarse';%'BridgeCool_Quadrilateral_Bilinear_Structured_Coarse';%'Bridge';%'CantileverSquareSmall';
ptype = 'MACRO';
initial_case = 'given';
m1 = 0.0101;
m2 = 0.0101;
cost = {'compliance'};
%cost = {'stressNorm'};
%cost = {'stressNorm','compliance'};
%weights = [0.55,0.45];
weights = 1;
constraint = {'volumeConstraint'};
filterType = 'PDE';
constraint_case = 'EQUALITY';

Vfrac_initial = 0.3;
optimality_initial = 1e-5;
constr_initial = 1e-5;

Vfrac_final = 0.3;
optimality_final = 1e-5;
constr_final = 1e-5;

stressNormExponent_initial = 2;
stressNormExponent_final = 16;

optimizer = 'DualNestedInPrimal';
optimizerUnconstrained = 'PROJECTED GRADIENT';

designVariable = 'MicroParams';
ub = 0.989;
lb = 0.011;
homegenizedVariablesComputer = 'ByVademecum';
%
%vademecumFileName = 'SuperEllipseQMax';
%vademecumFileName = 'SuperEllipseQ2';
vademecumFileName = 'SuperEllipseQOptAnalytic';
%
% designVariable = 'Density';
% homegenizedVariablesComputer = 'ByInterpolation';
% method = 'SIMPALL';
% materialType = 'ISOTROPIC';

line_search_initiator = 'INCREASING LAST STEP';
incrementFactor = 1.95;
%

%kfrac = 2;
nsteps = 8;%17;

plotting = true;
printing = true;
monitoring = true;
monitoring_interval = 3;
maxiter = 800;

%
%
% % % %
% isDirichletPartX = @(x) x > -1e-12 & x < 0.1;
% %isDirichletPart1 = @(y) y > 0.20 & y < 0.30;
% isDirichletPart1 = @(y) y > 0.30 & y < 0.50;
% isDirichletPartY = @(y) isDirichletPart1(y) ;%| isDirichletPart2(y);
% isDirichletPart = @(x,y) isDirichletPartX(x) & isDirichletPartY(y);
% isNeumannPartX = @(x) x > (2-0.1) & x < (2+1e-12);
% isNeumannPartY = @(y) y > 0.00 & y < 0.1;
% isNeumannPart = @(x,y) isNeumannPartX(x) & isNeumannPartY(y);
%
% iNotOptimizable = @(coord) isDirichletPart(coord(:,1),coord(:,2)) | isNeumannPart(coord(:,1),coord(:,2));
%
% costDomainNotOptimizable       = {iNotOptimizable};
% constraintDomainNotOptimizable = {[]};
%
% isDesignVariableFixed.nodes  = iNotOptimizable;
% isDesignVariableFixed.values = @(x) [m1*ones(size(x,1),1);m2*ones(size(x,1),1)];

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function b = bernsteincop(x,g)
%BERNSTEINCOP Bernstrein Empirical copula based on sample X.
%   B = BERNSTEINCOP(X,G) returns bivariate bernstein empirical copula
%   for GxG points grid. Extension to n dimensional bernstein empirical
%   copula is straightforward.
%
%   Written by Robert Kopocinski, Wroclaw University of Technology,
%   for Master Thesis: "Simulating dependent random variables using copulas.
%   Applications to Finance and Insurance".
%   Date: 2007/05/12
%
%   Reference:
%      [1]  Durrleman, V. and Nikeghbali, A. and Roncalli, T. (2000) Copulas approximation and
%           new families, Groupe de Recherche Operationnelle Credit Lyonnais

c = ecopula(x);

[m n] = size(c);

b=zeros(g);

for i=1:g
    for j=1:g
        b(i,j)=sum(sum( bernstein(i/g,1:m,m)'*(bernstein(j/g,1:m,m)).*c ));
    end
end

%------------------------------------------------------------
function y = bernstein(u,i,n)
% BERNSTEIN calculates values of Bernstein polynomials.

y = factorial(n)./factorial(i)./factorial(n-i).*u.^i.*(1-u).^(n-i);

author: Sable

repo: mcbench-benchmarks


text:
function [ r, center ] = sphere_dia2imp_3d ( p1, p2 )

%*****************************************************************************80
%
%% SPHERE_DIA2IMP_3D converts a diameter to an implicit sphere in 3D.
%
%  Discussion:
%
%    An implicit sphere in 3D satisfies the equation:
%
%      ( X - CENTER(1) )**2 + ( Y - CENTER(2) )**2 + ( Z - CENTER(3) )**2 = R**2
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 May 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real P1(3), P2(3), are two points which form a diameter
%    of the sphere.
%
%    Output, real R, the computed radius of the sphere.
%
%    Output, real CENTER(3), the computed center of the sphere.
%
  dim_num = 3;

  r = 0.5 * sqrt ( sum ( ( p2(1:dim_num) - p1(1:dim_num) ).^2 ) );

  center(1:dim_num) = 0.5 * ( p1(1:dim_num) + p2(1:dim_num) );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function divdif_test05 ( )

%*****************************************************************************80
%
%% DIVDIF_TEST05 tests DIF_TO_R8POLY and DIF_SHIFT_ZERO.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 October 2006
%
%  Author:
%
%    John Burkardt
%
  maxtab = 10;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'DIVDIF_TEST05\n' );
  fprintf ( 1, '  DIF_TO_R8POLY converts a difference table to a\n' );
  fprintf ( 1, '  polynomial;\n' );
  fprintf ( 1, '  DIF_SHIFT_ZERO shifts a divided difference\n' );
  fprintf ( 1, '  table to all zero abscissas;\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  These are equivalent operations!\n' );
  fprintf ( 1, '\n' );
%
%  Set XTAB, YTAB to X, F(X)
%
  ntab = 4;

  xtab1 = r8vec_indicator ( ntab );

  ytab1(1:ntab) = xtab1(1:ntab).^3 - 2.0 * xtab1(1:ntab).^2 ...
    + 3.0 * xtab1(1:ntab) - 4.0;

  xtab2 = r8vec_indicator ( ntab );

  ytab2(1:ntab) = xtab2(1:ntab).^3 - 2.0 * xtab2(1:ntab).^2 ...
    + 3.0 * xtab2(1:ntab) - 4.0;
%
%  Compute and display the finite difference table.
%
  diftab1 = data_to_dif_display ( ntab, xtab1, ytab1 );

  diftab2 = data_to_dif_display ( ntab, xtab2, ytab2 );
%
%  Examine corresponding polynomial.
%
  dif_print ( ntab, xtab1, diftab1, '  The divided difference polynomial:' );
%
%  Shift to zero.
%
  [ xtab1, diftab1 ] = dif_shift_zero ( ntab, xtab1, diftab1 );

  r8poly_print ( ntab, diftab1, '  Using DIF_SHIFT_ZERO' );
%
%  Shift to zero.
%
  c = dif_to_r8poly ( ntab, xtab2, diftab2 );

  r8poly_print ( ntab, c, '  Using DIF_TO_R8POLY' );

  return
end


text:
% test_this.m is a function-file test case.
function test_this

author: ricedsp


text:
function varargout=rotpl2ro(varargin)
%
% For calling details please see v_rotpl2ro.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_rotpl2ro.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: rotpl2ro.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_rotpl2ro(varargin{:});
else
    v_rotpl2ro(varargin{:});
end

author: ImperialCollegeLondon

repo: sap-voicebox


text:
function y = denC2D(x,T);

% % Example
% s1 = double(imread('st.tif'));
% s = s1(:,:,3);
% x = s + 20*randn(size(s));
% T = 40;
% y = denC2D(x,T);
% imagesc(y)
% colormap(gray)
% axis image
% sqrt(mean(mean((y-s).^2)))

[Faf, Fsf] = FSfarras;
[af, sf] = dualfilt1;
J = 4;
w = cplxdual2D(x,J,Faf,af);
I = sqrt(-1);
% loop thru scales:
for j = 1:J
    % loop thru subbands
    for s1 = 1:2
        for s2 = 1:3
            C = w{j}{1}{s1}{s2} + I*w{j}{2}{s1}{s2};
            C = soft(C,T);
            w{j}{1}{s1}{s2} = real(C);
            w{j}{2}{s1}{s2} = imag(C);
        end
    end
end
y = icplxdual2D(w,J,Fsf,sf);

author: thomaskuestner


text:
caffe.reset_all();
caffe.set_mode_gpu();
gpu_id = 0;  % we will use the first gpu in this demo
caffe.set_device(gpu_id);

addpath('../PrototxtGen');
net_model = 'net_define.prototxt';
inception_file = 'inception.prototxt';
inception_content = fileread(inception_file);
conv1x1_file = '1x1conv.prototxt';
conv1x1_content = fileread(conv1x1_file);
pooling_file = 'pooling.prototxt';
pooling_content = fileread(pooling_file);
output_file = 'output.prototxt';
output_content = fileread(output_file);

activation = 'ReLU';

layers = {
    struct('type', 'convolution', 'outputmaps', 10, 'kernelsize', 3, 'activation', activation) %convolution layer
    struct('type', 'convolution', 'outputmaps', 10, 'kernelsize', 3, 'activation', activation) %convolution layer
%     struct('type', 'convolution', 'outputmaps', 100, 'kernelsize', 3, 'activation', activation) %convolution layer
%     struct('type', 'pooling', 'scale', 2, 'method', 'AVE')
%     struct('type', 'inception', 'node1x1', 100, 'reduce3x3', 50, 'node3x3', 100, 'reduce5x5', 50, 'node5x5', 100, 'poolconv', 100)
%     struct('type', 'inception', 'node1x1', 20, 'reduce3x3', 10, 'node3x3', 20, 'reduce5x5', 10, 'node5x5', 20, 'poolconv', 20)
%     struct('type', 'inception', 'node1x1', 20, 'reduce3x3', 10, 'node3x3', 20, 'reduce5x5', 10, 'node5x5', 20, 'poolconv', 20)
    struct('type', 'convolution', 'outputmaps', 20, 'kernelsize', 1, 'activation', activation) %convolution layer
    struct('type', 'convolution', 'outputmaps', 20, 'kernelsize', 1, 'activation', activation) %convolution layer
%     struct('type', 'pooling', 'scale', 2, 'method', 'AVE')
};
width = 600;
height = 400;
border = 5;

fid = fopen(net_model,'w');
proto_file{1} = 'name: "mnist_siamese_train_test"';
proto_file{2} = 'input: "data"';
proto_file{3} = 'input_dim: 1';
proto_file{4} = 'input_dim: 2';
proto_file{5} = ['input_dim: ' num2str(width)];
proto_file{6} = ['input_dim: ' num2str(height)];
for i=1:6
    fprintf(fid,'%s\r\n',proto_file{i});
end;
top_layer = 'data';
top_layer_exp = 'top: "(.+?)"';
for i=1:length(layers)
    if strcmp(layers{i}.type,'convolution')
        this_layer = strrep(conv1x1_content,'{num}',num2str(i));
        this_layer = strrep(this_layer,'{node_num}',num2str(layers{i}.outputmaps));
        this_layer = strrep(this_layer,'{bottom_name}',top_layer);
        this_layer = strrep(this_layer,'{kernel_size}',num2str(layers{i}.kernelsize));
        this_layer = strrep(this_layer,'{activation}',layers{i}.activation);
    elseif strcmp(layers{i}.type,'pooling')
        this_layer = strrep(pooling_content,'{num}',num2str(i));
        this_layer = strrep(this_layer,'{bottom_name}',top_layer);
        this_layer = strrep(this_layer,'{method}',layers{i}.method);
        this_layer = strrep(this_layer,'{scale}',num2str(layers{i}.scale));
    elseif strcmp(layers{i}.type,'inception')
        this_layer = strrep(inception_content,'{num}',num2str(i));
        this_layer = strrep(this_layer,'{bottom_name}',top_layer);
        this_layer = strrep(this_layer,'{1x1node}',num2str(layers{i}.node1x1));
        this_layer = strrep(this_layer,'{3x3reduce}',num2str(layers{i}.reduce3x3));
        this_layer = strrep(this_layer,'{3x3node}',num2str(layers{i}.node3x3));
        this_layer = strrep(this_layer,'{5x5reduce}',num2str(layers{i}.reduce5x5));
        this_layer = strrep(this_layer,'{5x5node}',num2str(layers{i}.node5x5));
        this_layer = strrep(this_layer,'{poolconv}',num2str(layers{i}.poolconv));
    end;
    top_layer = regexp(this_layer,top_layer_exp,'tokens');
    top_layer = top_layer{end}{1};
    fprintf(fid,'%s\r\n',this_layer);
end;
this_layer = strrep(output_content,'{bottom_name}',top_layer);
fprintf(fid,'%s\r\n',this_layer);
fclose(fid);

train_net = caffe.Net(net_model,'train');

input_data = zeros(height, width, 2, 1, 'single');
input_data(:,:,1,1) = repmat((1:height)',1,width) / height;
input_data(:,:,2,1) = repmat((1:width),height,1) / width;
input_data = input_data - 0.5;

output_data = train_net.forward({input_data});

output = output_data{1};
output = output(border+1:end-border,border+1:end-border,:);
output = bsxfun(@minus,output,min(min(output,[],1),[],2));
output = bsxfun(@rdivide,output,max(max(output,[],1),[],2));
figure(1);
imshow(Lab2RGB(output));
% imshow(output);

author: happynear

repo: DeepVisualization


text:
clear;
load('.\exportData\S3\30T40_\ALL.mat');
cost_Batt = sum( fcnCalCostonlyDegradation(fst, mpcdata) ) / fst.iter;
cost24 = sum( fcnCalCostwithDegradation(fst, mpcdata) ) / fst.iter;

author: juchengquan


text:
% This file is only useful if you're using BCILAB to rebuild the .c files in here.
Libraries = 'dl';

author: PatternRecognition

repo: OpenBMI


text:
function p = p25_p_val ( action, p )

%*****************************************************************************80
%
%% P25_P_VAL sets or gets the value of a parameter for problem 25.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 October 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string ACTION.
%    'S', set the interval value to the input value of P.
%    'G', set the output value of P to the internal value.
%
%    Input/output, real P, the value of the parameter that
%    multiplies the Gaussian noise.
%
  persistent p_save

  if ( action(1) == 'S' || action(1) == 's' )
    p_save = p;
  elseif ( action(1) == 'G' || action(1) == 'g' )
    p = p_save;
  end

  return
end


text:
function accuracy = lcdrc(TrainSet, TestSet, train_num, test_num, class_num, reduce_dimension, options)
% Linear collaborative discriminant regression classificatoin (LCDRC) algorithm
%
% Inputs:
%       TrainSet            train sets of size dxn, where d is dimension and n is number of sets
%       TestSet             test sets of size dxn, where d is dimension and n is number of sets
%       test_num            numner of test sets
%       class_num           numner of classes
%       options             options
% Output:
%       accuracy            classification accurary
%
% References:
%       X. Qu, S. Kim, R. Cui and H. J. Kim,
%       "Linear collaborative discriminant regression classification for face recognition,"
%       J. Visual Communication Image Represetation, vol.31, pp. 312-319, 2015.
%
%
% Created by H.Kasai on July 04, 2017

    % extract options
    if ~isfield(options, 'verbose')
        verbose = false;
    else
        verbose = options.verbose;
    end

    if verbose
        fprintf('# LCDRC: calculate projection matrix U ...');
    end
    Eb = 0;
    Ew = 0;
    for j = 1 : train_num

        j_class = TrainSet.y(1, j);

        % calcuate Ew
        intra_class_index = find(TrainSet.y == j_class);
        intra_class_index(intra_class_index == j) = [];
        X_intra_wo_j = TrainSet.X(:, intra_class_index);                                    % X^{intra}
        alpha_intra = X_intra_wo_j * pinv(X_intra_wo_j' * X_intra_wo_j) * X_intra_wo_j';    % alpha^{intra} in Eq.(2)
        error_intra = TrainSet.X(:,j) - alpha_intra * TrainSet.X(:,j);
        Ew = Ew + error_intra * error_intra';

        % calcuate Eb
        inter_class_index = find(TrainSet.y ~= j_class);
        X_inter = TrainSet.X(:, inter_class_index);%                                        % X^{iner}
        alpha_inter= X_inter * pinv(X_inter' * X_inter) * X_inter';                         % alpha^{inter} in Eq.(2)
        error_inter = TrainSet.X(:,j) - alpha_inter * TrainSet.X(:,j);
        Eb = Eb + error_inter * error_inter';
    end

    % calc
    Ew = Ew/train_num;
    Eb = Eb/train_num;
    lambda = 0.001;
    Ew = Ew + lambda*eye(size(Ew,2));

    [V, ~] = eig(Eb, Ew);
    for i = 1:reduce_dimension
        U(:,i) = V(:,size(V,2)+1-i);                                                        % Eq.(13)
    end
    if verbose
        fprintf('done\n');
    end

    % reduce dimention
    TrainSet.X_red  = U' * TrainSet.X;
    TestSet.X_red   = U' * TestSet.X;

    % prepare projection matrix (hat matrix)
    H = cell(1, class_num);
    for i = 1 : class_num
        class_index = find(TrainSet.y == i);

        X_i = TrainSet.X_red(:, class_index);           % Eq.(1)
        alpha_i = pinv(X_i' * X_i) *  X_i';                  % Eq.(2) exept y (beta_i = inv(X_i' * X_i) * X_i')
        H{i} = X_i * alpha_i;                           % Eq.(3) exept y

        if verbose
            fprintf('# LCDRC: calc Hi for class : %03d/%03d (samples: %03d)\n', i, class_num, length(class_index));
        end
    end

    % prepare predicted label array
    identity = zeros(1, test_num);

    % predict the class
    for j = 1 : test_num

        dis = zeros(1, class_num);
        y = TestSet.X_red(:, j);
        for i = 1 : class_num
            y_pred = H{i} * y;
            dis(1, i) = norm(y - y_pred);               % Eq.(5)
        end
        [~, label] = min(dis);                          % Eq.(6)
        identity(j) = label;

        if verbose
            correct = (label == TestSet.y(1, j));
            fprintf('# LCDRC: test:%03d, predict class: %03d --> ground truth :%03d (%d)\n', j, label, TestSet.y(1, j), correct);
        end
    end

    % calculate accuracy
    correct_num = sum(identity == TestSet.y);
    accuracy = correct_num / test_num;
end

author: hiroyuki-kasai

repo: ClassifierToolbox


text:
function [mph] = ftps2mph(ftps)
% Convert speed from feet per second to miles per hour
mph = ftps*0.6818181818182 ;


text:
function ihs_test01 ( )

%*****************************************************************************80
%
%% IHS_TEST01 tests the improved distributed hypercube sampling algorithm.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 March 2004
%
%  Author:
%
%    John Burkardt
%
  point_num = 10;
  duplication = 5;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'IHS_TEST01' );
  fprintf ( 1, '  IHS implements the IHS Algorithm\n' );
  fprintf ( 1, '  (Improved Distributed Hypercube Sampling)\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Demonstrate the code for a fixed number of points\n' );
  fprintf ( 1, '  and an increasing dimension.\n' );

  for dim_num = 1 : 4

    opt = point_num / point_num^( 1.0 / dim_num );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Spatial dimension =        %d\n', dim_num );
    fprintf ( 1, '  Number of points =         %d\n', point_num );
    fprintf ( 1, '  Duplication factor =       %d\n', duplication );
    fprintf ( 1, '  Desired minimum distance = %f\n', opt );
%
%  Get the points.
%
    x = ihs ( dim_num, point_num, duplication );
%
%  Compute the covariance.
%
    [ average, sd, covc ] = covariance ( dim_num, point_num, x );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Average minimum distance %f\n', average );
    fprintf ( 1, '  Standard deviation:      %f\n', sd );
    fprintf ( 1, '  Covariance:              %f\n', covc );

    fprintf ( 1, '\n' );

    for j = 1 : point_num
      fprintf ( 1, '%4d    ', j );
      for i = 1 : dim_num
        fprintf ( 1, '%4d  ', x(i,j) );
      end
      fprintf ( 1, '\n');
    end

  end

  return
end


text:
function [graphW, NNIndex] = gacBuildDigraph_c(distance_matrix, K, a)
%% Build directed graph
% Input:
%   - distance_matrix: pairwise distances, d_{i -> j}
%   - K: the number of nearest neighbors for KNN graph
%   - a: for covariance estimation
%       sigma^2 = (\sum_{i=1}^n \sum_{j \in N_i^3} d_{ij}^2) * a
% Output:
%   - graphW: asymmetric weighted adjacency matrix,
%               w_{ij} = exp(- d_{ij}^2 / sig2), if j \in N_i^K
%	- NNIndex: (2K) nearest neighbors, N x (2K+1) matrix
% by Wei Zhang (wzhang009 at gmail.com), June, 8, 2011
%
% Please cite the following paper, if you find the code is helpful
%
% W. Zhang, X. Wang, D. Zhao, and X. Tang.
% Graph Degree Linkage: Agglomerative Clustering on a Directed Graph.
% in Proceedings of European Conference on Computer Vision (ECCV), 2012.

%% NN indices
N = size(distance_matrix,1);
% find 2*K NNs in the sense of given distances
[sortedDist,NNIndex] = gacMink(distance_matrix,max(K+1,4),2);

%% estimate derivation
sig2 = mean(mean(sortedDist(:,2:max(K+1,4)))) * a;
%%%%%%%%%
tmpNNDist = min(sortedDist(:,2:end),[],2);
while any(exp(- tmpNNDist / sig2) < 1e-5) % check sig2 and magnify it if it is too small
    sig2 = 2*sig2;
end
%%%%%%%%%
disp(['  sigma = ' num2str(sqrt(sig2))]);

%% build graph
ND = sortedDist(:, 2:K+1);
NI = NNIndex(:, 2:K+1);
XI = repmat([1:N]', 1, K);
graphW = full(sparse(XI(:),NI(:),exp(-ND(:)*(1/sig2)), N, N));
graphW(1:N+1:end) = 1;

end

author: jwyang


text:
function t = uminus(t)
%UMINUS Unary minus for ktensor.
%
%   See also KTENSOR.
%
%MATLAB Tensor Toolbox.
%Copyright 2012, Sandia Corporation.

% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2012) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt

t.lambda = -t.lambda;

author: andrewssobral

repo: mtt

save_path: github-repos/MATLAB/andrewssobral-mtt


text:
function index=set_index(ver,sys,opt,tobs) %#ok

global glc
obscodes='CLDS';
index.n=0;
index.frq(1:glc.MAXOBSTYPE)=0;
index.pos(1:glc.MAXOBSTYPE)=0;
index.pri(1:glc.MAXOBSTYPE)=0;
index.type(1:glc.MAXOBSTYPE)=0;
index.code(1:glc.MAXOBSTYPE)=0;
index.shift(1:glc.MAXOBSTYPE)=0;

nn=size(tobs,1); n=0;
for i=1:nn
    if isempty(strfind(obscodes,tobs(i,1))),break;end

    [index.code(i),index.frq(i)]=obs2code(tobs(i,2:3),sys);

    type=strfind(obscodes,tobs(i,1));
    if ~isempty(type)
        index.type(i)=type;
    else
        index.type(i)=0;
    end

    index.pri(i)=getcodepri(sys,index.code(i),opt);
    index.pos(i)=-1;
    index.code(i)=index.code(i)-1;
    n=n+1;
end

for i=1:glc.MAXFREQ

    % search for the highest level code
    k=-1;
    for j=1:n
        if index.frq(j)==i&&index.pri(j)~=0&&(k<0||index.pri(j)>index.pri(k))
            k=j;
        end
    end

    if k<0,continue;end

    for j=1:n
        if index.code(j)==index.code(k),index.pos(j)=i;end
    end
end

index.n=n;

return

repo: GINav


text:
% demo_e2s2_full()
%
% Trains and tests a Region-based semantic segmentation with end-to-end training on SIFT Flow.
% Requires the version of VGG-16 pretrained with MatConvNet's beta16, and does not
% work with beta20. This is most likely due to exploding gradients, although the architecture is identical.
%
% Copyright by Holger Caesar, 2016

% Add folders to path
setup();

% Settings
global glFeaturesFolder; % Define global variables to be used in all scripts
labelingsFolder = fullfile(glFeaturesFolder, 'CNN-Models', 'E2S2', 'SiftFlow', 'Run1', sprintf('%s_e2s2_run1_exp2', 'SiftFlow'), 'labelings-test-epoch25');

% Download dataset
downloadSiftFlow();

% Download base network
downloadNetwork('version', 'beta16');

% Download Selective Search
downloadSelectiveSearch();

% Extract region proposals and labels
setupE2S2Regions();

% Train and test network
e2s2_wrapper_SiftFlow_full();

% Show example segmentation
fileList = dirSubfolders(labelingsFolder);
image = imread(fullfile(labelingsFolder, fileList{1}));
figure();
imshow(image);

author: nightrome

repo: matconvnet-calvin


text:
function [dx] = spm_dx(dfdx,f,t)
% returns dx(t) = (expm(dfdx*t) - I)*inv(dfdx)*f
% FORMAT [dx] = spm_dx(dfdx,f,[t])
% dfdx   = df/dx
% f      = dx/dt
% t      = integration time: (default t = Inf);
%          if t is a cell (i.e., {t}) then t is set to:
%          exp(t - log(diag(-dfdx))
%
% dx     = x(t) - x(0)
%--------------------------------------------------------------------------
% Integration of a dynamic system using local linearization.  This scheme
% accommodates nonlinearities in the state equation by using a functional of
% f(x) = dx/dt.  This uses the equality
%
%             expm([0   0     ]) = (expm(t*dfdx) - I)*inv(dfdx)*f
%                  [t*f t*dfdx]
%
% When t -> Inf this reduces to
%
%              dx(t) = -inv(dfdx)*f
%
% These are the solutions to the gradient ascent ODE
%
%            dx/dt   = k*f = k*dfdx*x =>
%
%            dx(t)   = expm(t*k*dfdx)*x(0)
%                    = expm(t*k*dfdx)*inv(dfdx)*f(0) -
%                      expm(0*k*dfdx)*inv(dfdx)*f(0)
%
% When f = dF/dx (and dfdx = dF/dxdx), dx represents the update from a
% Gauss-Newton ascent on F.  This can be regularised by specifying {t}
% A heavy regularization corresponds to t = -4 and a light
% regularization would be t = 4. This version of spm_dx uses an augmented
% system and the Pade approximation to compute requisite matrix
% exponentials
%
% references:
%
% Friston K, Mattout J, Trujillo-Barreto N, Ashburner J, Penny W. (2007).
% Variational free energy and the Laplace approximation. NeuroImage.
% 34(1):220-34
%
% Ozaki T (1992) A bridge between nonlinear time-series models and
% nonlinear stochastic dynamical systems: A local linearization approach.
% Statistica Sin. 2:113-135.
%
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_dx.m 7144 2017-07-31 13:55:55Z karl $

% defaults
%--------------------------------------------------------------------------
nmax  = 512;                        % threshold for numerical approximation
if nargin < 3, t = Inf; end         % integration time
xf    = f; f = spm_vec(f);          % vectorise
n     = length(f);                  % dimensionality

% t is a regulariser
%--------------------------------------------------------------------------
sw  = warning('off','MATLAB:log:logOfZero');
if iscell(t)

    % relative integration time
    %----------------------------------------------------------------------
    t      = t{:};
    if isscalar(t)
        t  = exp(t - spm_logdet(dfdx)/n);
    else
        t  = exp(t - log(diag(-dfdx)));
    end

end
warning(sw);

% use a [pseudo]inverse if all t > TOL
%==========================================================================
if min(t) > exp(16)

    dx = -spm_pinv(dfdx)*f;

else

    % ensure t is a scalar or matrix
    %----------------------------------------------------------------------
    if isvector(t), t = diag(t); end

    % augment Jacobian and take matrix exponential
    %======================================================================
    J = spm_cat({0  []      ;
                t*f t*dfdx});

    % solve using matrix expectation
    %----------------------------------------------------------------------
    if n  <= nmax
        dx    = spm_expm(J);
        dx    = dx(:,1);
    else
        x     = sparse(1,1,1,n + 1,1);
        dx    = expv(1,J,x);
    end

    % recover update
    %----------------------------------------------------------------------
    dx    = dx(2:end);

end
dx = spm_unvec(real(dx),xf);

return

%==========================================================================
%  Roger B. Sidje (rbs@maths.uq.edu.au)
%  EXPOKIT: Software Package for Computing Matrix Exponentials.
%  ACM - Transactions On Mathematical Software, 24(1):130-156, 1998

function  [w, err, hump] = expv( t, A, v, tol, m )
%  FOTMAT [w, err, hump] = expv( t, A, v, tol, m )
%  EXPV computes an approximation of w = exp(t*A)*v for a
%  general matrix A using Krylov subspace  projection techniques.
%  It does not compute the matrix exponential in isolation but instead,
%  it computes directly the action of the exponential operator on the
%  operand vector. This way of doing so allows for addressing large
%  sparse problems. The matrix under consideration interacts only
%  via matrix-vector products (matrix-free method).
%
%  w = expv( t, A, v )
%  computes w = exp(t*A)*v using a default tol = 1.0e-7 and m = 30.
%
%  [w, err] = expv( t, A, v )
%  renders an estimate of the error on the approximation.
%
%  [w, err] = expv( t, A, v, tol )
%  overrides default tolerance.
%
%  [w, err, hump] = expv( t, A, v, tol, m )
%  overrides default tolerance and dimension of the Krylov subspace,
%  and renders an approximation of the `hump'.
%
%  The hump is defined as:
%          hump = max||exp(sA)||, s in [0,t]  (or s in [t,0] if t < 0).
%  It is used as a measure of the conditioning of the matrix exponential
%  problem. The matrix exponential is well-conditioned if hump = 1,
%  whereas it is poorly-conditioned if hump >> 1. However the solution
%  can still be relatively fairly accurate even when the hump is large
%  (the hump is an upper bound), especially when the hump and
%  ||w(t)||/||v|| are of the same order of magnitude (further details in
%  reference below).
%
%  Example 1:
%  ----------
%    n = 100;
%    A = rand(n);
%    v = eye(n,1);
%    w = expv(1,A,v);
%
%  Example 2:
%  ----------
%    % generate a random sparse matrix
%    n = 100;
%    A = rand(n);
%    for j = 1:n
%        for i = 1:n
%            if rand < 0.5, A(i,j) = 0; end;
%        end;
%    end;
%    v = eye(n,1);
%    A = sparse(A); % invaluable for a large and sparse matrix.
%
%    tic
%    [w,err] = expv(1,A,v);
%    toc
%
%    disp('w(1:10) ='); disp(w(1:10));
%    disp('err =');     disp(err);
%
%    tic
%    w_matlab = expm(full(A))*v;
%    toc
%
%    disp('w_matlab(1:10) ='); disp(w_matlab(1:10));
%    gap = norm(w-w_matlab)/norm(w_matlab);
%    disp('||w-w_matlab|| / ||w_matlab|| ='); disp(gap);
%
%  In the above example, n could have been set to a larger value,
%  but the computation of w_matlab will be too long (feel free to
%  discard this computation).
%
%  See also MEXPV, EXPOKIT.

%  Roger B. Sidje (rbs@maths.uq.edu.au)
%  EXPOKIT: Software Package for Computing Matrix Exponentials.
%  ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
%__________________________________________________________________________

[n,n] = size(A);
if nargin == 3,
    tol = 1.0e-7;
    m = min(n,30);
end;
if nargin == 4,
    m = min(n,30);
end;

anorm = norm(A,'inf');
mxrej = 10;  btol  = 1.0e-7;
gamma = 0.9; delta = 1.2;
mb    = m; t_out   = abs(t);
nstep = 0; t_new   = 0;
t_now = 0; s_error = 0;
rndoff= anorm*eps;

k1    = 2; xm = 1/m; normv = norm(v); beta = normv;
fact  = (((m+1)/exp(1))^(m+1))*sqrt(2*pi*(m+1));
t_new = (1/anorm)*((fact*tol)/(4*beta*anorm))^xm;
s     = 10^(floor(log10(t_new))-1); t_new = ceil(t_new/s)*s;
sgn   = sign(t); nstep = 0;

w     = v;
hump  = normv;
while t_now < t_out
    nstep = nstep + 1;
    t_step = min( t_out-t_now,t_new );
    V = zeros(n,m+1);
    H = zeros(m+2,m+2);

    V(:,1) = (1/beta)*w;
    for j = 1:m
        p = A*V(:,j);
        for i = 1:j
            H(i,j) = V(:,i)'*p;
            p = p-H(i,j)*V(:,i);
        end;
        s = norm(p);
        if s < btol,
            k1 = 0;
            mb = j;
            t_step = t_out-t_now;
            break;
        end;
        H(j+1,j) = s;
        V(:,j+1) = (1/s)*p;
    end;
    if k1 ~= 0,
        H(m+2,m+1) = 1;
        avnorm = norm(A*V(:,m+1));
    end;
    ireject = 0;
    while ireject <= mxrej,
        mx = mb + k1;
        F = expm(sgn*t_step*H(1:mx,1:mx));
        if k1 == 0,
            err_loc = btol;
            break;
        else
            phi1 = abs( beta*F(m+1,1) );
            phi2 = abs( beta*F(m+2,1) * avnorm );
            if phi1 > 10*phi2,
                err_loc = phi2;
                xm = 1/m;
            elseif phi1 > phi2,
                err_loc = (phi1*phi2)/(phi1-phi2);
                xm = 1/m;
            else
                err_loc = phi1;
                xm = 1/(m-1);
            end;
        end;
        if err_loc <= delta * t_step*tol,
            break;
        else
            t_step = gamma * t_step * (t_step*tol/err_loc)^xm;
            s = 10^(floor(log10(t_step))-1);
            t_step = ceil(t_step/s) * s;
            if ireject == mxrej,
                error('The requested tolerance is too high.');
            end;
            ireject = ireject + 1;
        end;
    end;
    mx = mb + max( 0,k1-1 );
    w = V(:,1:mx)*(beta*F(1:mx,1));
    beta = norm( w );
    hump = max(hump,beta);

    t_now = t_now + t_step;
    t_new = gamma * t_step * (t_step*tol/err_loc)^xm;
    s = 10^(floor(log10(t_new))-1);
    t_new = ceil(t_new/s) * s;

    err_loc = max(err_loc,rndoff);
    s_error = s_error + err_loc;
end;
err  = s_error;
hump = hump / normv;

return

function E = padm( A, p )
%  FORMAT E = padm( A, p )
%  PADM computes the matrix exponential exp(A) using the irreducible
%  (p,p)-degree rational Pade approximation to the exponential function.
%
%  E = padm( A )
%  p is internally set to 6 (recommended and generally satisfactory).
%
%  See also CHBV, EXPOKIT and the MATLAB supplied functions EXPM and EXPM1.

%  Roger B. Sidje (rbs@maths.uq.edu.au)
%  EXPOKIT: Software Package for Computing Matrix Exponentials.
%  ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
%__________________________________________________________________________

if nargin == 1, p = 6; end;
[n,n] = size(A);

% Pade coefficients (1-based instead of 0-based as in the literature)
%--------------------------------------------------------------------------
c(1) = 1;
for k = 1:p
    c(k+1) = c(k)*((p+1-k)/(k*(2*p+1-k)));
end;

% Scaling
%--------------------------------------------------------------------------
s = norm(A,'inf');
if s > 0.5,
    s = max(0,fix(log(s)/log(2))+2);
    A = 2^(-s)*A;
end;

% Horner evaluation of the irreducible fraction (see ref. above)
%--------------------------------------------------------------------------
I = eye(n);
A2 = A*A;
Q = c(p+1)*I;
P = c(p)*I;
odd = 1;
for k = p-1:-1:1,
    if odd == 1,
        Q = Q*A2 + c(k)*I;
    else
        P = P*A2 + c(k)*I;
    end;
    odd = 1-odd;
end;
if odd == 1
    Q = Q*A;
    Q = Q - P;
    E = -(I + 2*(Q\P));
else
    P = P*A;
    Q = Q - P;
    E = I + 2*(Q\P);
end;

% Squaring
%--------------------------------------------------------------------------
for k = 1:s,
    E = E*E;
end;

return

author: spm


text:
clear;

load('./results/results_ceclm_general.mat');

% Generate a lot of possibilities and find best
weights = [1,1,1,0,0,0];
score_base = ranking_score(weights, experiment.lhoods, experiment.all_views_used, experiment.errors_view);
scores = zeros(1,1000);
score = score_base;
weights_all = zeros(1000,6);
for i=1:1000

    scores(i) = score;
    weights_all(i,:) = weights;
%         weights = weights + (0.999^i)*0.3 * ranking_score_grad(weights, l_hoods_view, experiment.all_views_used, errors_view);
    weights = weights + (0.999^i)*0.3 * ranking_score_grad(weights, experiment.lhoods, experiment.all_views_used, experiment.errors_view);
    score = ranking_score(weights, experiment.lhoods, experiment.all_views_used, experiment.errors_view);
end
[~,id] = max(scores);
weights_lhoods = weights_all(id,:);

%% Learn the cuttof
view_used = experiment.all_views_used;
weights_scale = ones(size( experiment.lhoods));
% As views 2-7, 3-6, 4-5 are mirrors of each other, trust their
% assessment the same amount
weights_scale(view_used == 2) = weights_lhoods(1);
weights_scale(view_used == 3) = weights_lhoods(2);
weights_scale(view_used == 4) = weights_lhoods(3);
weights_scale(view_used == 5) = weights_lhoods(3);
weights_scale(view_used == 6) = weights_lhoods(2);
weights_scale(view_used == 7) = weights_lhoods(1);

weights_add = zeros(size(experiment.lhoods));
weights_add(view_used == 2) = weights_lhoods(4);
weights_add(view_used == 3) = weights_lhoods(5);
weights_add(view_used == 4) = weights_lhoods(6);
weights_add(view_used == 5) = weights_lhoods(6);
weights_add(view_used == 6) = weights_lhoods(5);
weights_add(view_used == 7) = weights_lhoods(4);

lhoods = experiment.lhoods .* weights_scale + weights_add;

% As a very reliable detection, make sure that 98% of cases have high
% accuracy (less than 0.1)
% That is find the smallest number which leads to good accuracy
cutoffs = [];
for i=1:4
    ids = view_used==i;
    if(i > 1)
        if(i==2)
            mirr_id = 7;
        elseif(i==3)
            mirr_id = 6;
        elseif(i==4)
            mirr_id = 5;
        end
        ids = ids | view_used==mirr_id;
    end
    lhood_view = lhoods(ids);
    error = experiment.errors_view(ids);

    for c=-2:0.01:2
        if(mean(error(lhood_view >c)<0.1) >= 0.98)
            break;
        end
    end
    cutoffs = cat(1, cutoffs, c);
end
cutoffs = [cutoffs(1), cutoffs(2), cutoffs(3), cutoffs(4), cutoffs(4), cutoffs(3), cutoffs(2)];
weights_scale = weights_lhoods(1:end/2);
weights_scale = [1, weights_scale(1), weights_scale(2), weights_scale(3), weights_scale(3), weights_scale(2), weights_scale(1)];
weights_add = weights_lhoods(end/2+1:end);
weights_add = [0, weights_add(1), weights_add(2), weights_add(3), weights_add(3), weights_add(2), weights_add(1)];
early_term_params.weights_scale = weights_scale;
early_term_params.weights_add = weights_add;
early_term_params.cutoffs = cutoffs;
save('cen_general_mapping', 'early_term_params');

author: TadasBaltrusaitis

repo: OpenFace


text:
function [fhdr,chdr,ename,cnames,fcom,ftext] = read_egis_header(filename)

% READ_EGIS_HEADER reads the header information from an EGI EGIS format file
%
% Use as
%   [fhdr chdr] = read_egia_header(filename)
% with
%   fhdr        - the file header information
%   chdr        - the cell header information
%   ename       - experiment name
%   cnames      - cell names
%   fcom        - comments
%   ftext       - general text
% and
%   filename    - the name of the data file
%_______________________________________________________________________
%
%
% Modified from EGI's EGI Toolbox with permission 2007-06-28 Joseph Dien

% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

fh=fopen_or_error([filename],'r');

%Prep file for reading
fhdr=zeros(1,23);
status=fseek(fh,0,'bof');

%Read in fhdr fields.
fhdr(1)=fread(fh,1,'int32'); %BytOrd
[str,maxsize,cEndian]=computer;
if fhdr(1)==16909060
  if cEndian == 'B'
    endian = 'ieee-be';
  elseif cEndian == 'L'
    endian = 'ieee-le';
  end
elseif fhdr(1)==67305985
  if cEndian == 'B'
    endian = 'ieee-le';
  elseif cEndian == 'L'
    endian = 'ieee-be';
  end
else
  ft_error('This is not an EGIS average file.');
end

fhdr(2)=fread(fh,1,'int16',endian); %HdrVer

if (fhdr(2) ~= -1) && (fhdr(2) ~= 3)
  ft_error('This is not an EGIS average file.');
end

fhdr(3)=fread(fh,1,'uint16',endian); %LHeader
fhdr(4)=fread(fh,1,'uint32',endian); %LData
status=fseek(fh,80,'cof'); %Skip ExptNam
fhdr(5:10)=fread(fh,6,'int16',endian); %RunDate and RunTime

fhdr(11:23)=fread(fh,13,'int16',endian); %Everything else up to LCellHdr

fhdr(24:(24+fhdr(18)-1))=fread(fh,fhdr(18),'uint16',endian); %LCellHdr for each cell

%Read in chdr
chdr=zeros(fhdr(18),5);
status=fseek(fh,(4*fhdr(19)),'cof');
for loop=1:fhdr(18)
  chdr(loop,1)=fread(fh,1,'int16',endian);
  status=fseek(fh,80,'cof');
  chdr(loop, 2:5)=(fread(fh,4,'int16',endian))';
  lspectot=(chdr(loop,2)*(chdr(loop,5)/2));
  lastcol=(6+lspectot-1);
  if lastcol >= 6
    chdr(loop,lastcol)=0;
    chdr(loop,6:lastcol)=(fread(fh,lspectot,'int16',endian))';
  end
end

%Read experiment name
status=fseek(fh,12,'bof');
tempstr=fread(fh,80,'char');
ename=char(tempstr);

%Read cellnames
status=fseek(fh,(130+(2*fhdr(18))+(4*fhdr(19))),'bof');
status=fseek(fh,2,'cof');
for loop=1:fhdr(18)
  temp=fread(fh,80,'char');
  theName=strtok(temp,0);
  cnames{loop}=deblank(char(theName))';
  status=fseek(fh,fhdr(24+(loop-1))-80,'cof');
end

%Read comment
%status=fseek(fh,fhdr(3),'bof');
%status=fseek(fh,-(fhdr(22)+fhdr(21)+fhdr(20)),'cof');
fcom=fread(fh,fhdr(20),'char');

%Read text
%status=fseek(fh,fhdr(3),'bof');
%status=fseek(fh,-(fhdr(22)+fhdr(21)),'cof');
ftext=fread(fh,fhdr(21),'char');

fclose(fh);

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
%%% data randomization

function [data_out] = randomizer(data_in)
D=length(data_in);
State=[1 0 0 1 0 1 0 1 0 0 0 0 0 0 0];

for k=1:D
    fdB=bitxor(State(14),State(15));
    State=[fdB State(1:end-1)];
    data_out(k,1)=bitxor(data_in(k,1),fdB);
 end


text:
function class_info=gen_class_info_nyud()

class_info=[];

class_info.class_names={
    'wall'
    'floor'
    'cabinet'
    'bed'
    'chair'
    'sofa'
    'table'
    'door'
    'window'
    'bookshelf'
    'picture'
    'counter'
    'blinds'
    'desk'
    'shelves'
    'curtain'
    'dresser'
    'pillow'
    'mirror'
    'floor mat'
    'clothes'
    'ceiling'
    'books'
    'refridgerator'
    'television'
    'paper'
    'towel'
    'shower curtain'
    'box'
    'whiteboard'
    'person'
    'night stand'
    'toilet'
    'sink'
    'lamp'
    'bathtub'
    'bag'
    'otherstructure'
    'otherfurniture'
    'otherprop'
    'void'};

class_label_values=uint8([1:40 255]);
class_info.class_label_values=class_label_values;

class_info.background_label_value=uint8(1);
class_info.void_label_values=uint8(255);

class_info.mask_cmap = VOClabelcolormap(256);
class_info=process_class_info(class_info);

end

author: guosheng

repo: refinenet

save_path: github-repos/MATLAB/guosheng-refinenet


text:
classdef DetailHandler < OlyDat.ExperimentDetailHandler
  % Concrete ExperimentDetailHandler for Hantman MouseJAABA

  methods

    function open(obj,data) %#ok<INUSL>
      if ~isempty(data)
        jabs = data(1).jabs;
        jab = jabs{1};
        expfull = data(1).expfull;

        JLabelInterf.openJabExpFrame(jab,expfull,1);
      end
    end

  end

end

author: kristinbranson

repo: JAABA


text:
classdef DataFilesClass < handle

    properties
        files;
        filesErr;
        filetype;
        dirFormats;
        err;
        errmsg;
        rootdir;
        config;
        nfiles;
        logger
    end

    properties (Access = private)
        lookupTable
    end

    methods

        % ----------------------------------------------------
        function obj = DataFilesClass(varargin)
            obj.files = FileClass.empty();
            obj.filesErr = FileClass.empty();
            obj.filetype = '';
            obj.rootdir = pwd;
            obj.nfiles = 0;
            obj.err = -1;
            obj.errmsg = {};
            obj.dirFormats = struct('type',0, 'choices',{{}});

            global logger
            global cfg

            logger = InitLogger(logger);
            cfg    = InitConfig(cfg);

            obj.logger = logger;
            obj.lookupTable = [];

            skipconfigfile = false;
            askToFixNameConflicts = [];

            if nargin==0
                return
            end
            if nargin==1
                obj.rootdir = varargin{1};
            end
            if nargin==2
                obj.rootdir = varargin{1};
                obj.filetype = varargin{2};
            end
            if nargin==3
                obj.rootdir = varargin{1};
                obj.filetype = varargin{2};
                if strcmp(varargin{3}, 'standalone')
                    skipconfigfile = true;
                end
            end
            if nargin==4
                obj.rootdir = varargin{1};
                obj.filetype = varargin{2};
                if strcmp(varargin{3}, 'standalone')
                    skipconfigfile = true;
                end
                askToFixNameConflicts = varargin{4};
            end

            if obj.filetype(1) == '.'
                obj.filetype(1) = '';
            end
            obj.rootdir = filesepStandard(obj.rootdir,'full');

            % Configuration parameters
            obj.config = struct('RegressionTestActive','','AskToFixNameConflicts',1);
            if skipconfigfile==false
                str = cfg.GetValue('Regression Test Active');
                if strcmp(str,'true')
                    obj.config.RegressionTestActive=true;
                else
                    obj.config.RegressionTestActive=false;
                end
            else
                obj.config.RegressionTestActive=false;
            end
            obj.config.SuppressErrorChecking = false;
            if ~isempty(askToFixNameConflicts)
                obj.config.AskToFixNameConflicts = askToFixNameConflicts;
            elseif strcmp(cfg.GetValue('Fix File Name Conflicts'), sprintf('don''t ask again'))
                obj.config.AskToFixNameConflicts = 0;
            end

            if ~obj.config.AskToFixNameConflicts
                obj.config.SuppressErrorChecking = true;
            end

            if nargin==0
                return;
            end

            obj.err = 0;

            obj.InitFolderFromats();
            obj.GetDataSet();
        end

        % -----------------------------------------------------------------------------------
        function GetDataSet(obj)
            if exist(obj.rootdir, 'dir')~=7
                error('Invalid subject folder: ''%s''', obj.rootdir);
            end

            for ii = 1:length(obj.dirFormats.choices)
                obj.InitLookupTable();
                obj.FindDataSet(ii);

                % Remove any files that cannot pass the basic test of loading
                % its data
                obj.ErrorCheck();
                if ~isempty(obj.files)
                    break
                end
            end

            obj.ErrorCheckFinal();
        end

        % -----------------------------------------------------------------------------------
        function InitFolderFromats(obj)
            obj.dirFormats.choices = {

                %%%% 1. Flat #1
                {
                ['*_run*.', obj.filetype];
                }

                %%%% 2. Flat #2
                {
                ['*.', obj.filetype];
                }

                %%%% 3. Subjects
                {
                '*';
                ['*.', obj.filetype];
                }

                %%%% 4. BIDS #1,    sub-<label>[_ses-<label>][_task-<label>][_run-<index>]_nirs.snirf
                {
                'sub-*';
                'ses-*';
                ['nirs/sub-*_run-*_nirs.', obj.filetype];
                }

                %%%% 5. BIDS #2
                {
                'sub-*';
                ['nirs/sub-*_run-*_nirs.', obj.filetype];
                }

                %%%% 6. BIDS #3
                {
                'sub-*';
                ['nirs/sub-*_*_nirs.', obj.filetype];
                }

                %%%% 7. BIDS #4
                {
                '*';
                ['nirs/sub-*_*_nirs.', obj.filetype];
                }

                %%%% 8. BIDS folder structure
                {
                'sub-*';
                'ses-*';
                ['nirs/sub-*_run-*_nirs.', obj.filetype];
                }

                %%%% 9. BIDS-like folder structure without file naming restrictions
                {
                'sub-*';
                'ses-*';
                ['nirs/*.', obj.filetype];
                }

                %%%% 10. BIDS-like folder structure without nirs sub-folder
                {
                'sub-*';
                'ses-*';
                ['*.', obj.filetype];
                }

                };
        end

        % ----------------------------------------------------
        function FindDataSet(obj, iFormat, iPattern, parentdir)
            if ~exist('iFormat','var')
                iFormat = 1;
            end
            if ~exist('iPattern','var')
                iPattern = 1;
            end
            if ~exist('parentdir','var')
                parentdir = obj.rootdir;
            end

            if iFormat > length(obj.dirFormats.choices)
                return
            end
            if iPattern > length(obj.dirFormats.choices{iFormat})
                return
            end
            parentdir = filesepStandard(parentdir);
            pattern = obj.dirFormats.choices{iFormat}{iPattern};

            dirs = mydir([parentdir, pattern], obj.rootdir);

            dirnamePrev = '';
            for ii = 1:length(dirs)
                if dirs(ii).IsEmpty()
                    continue;
                end
                if dirs(ii).IsFile()
                    if strcmp(pattern, '*')
                        continue
                    end
                    if includes(dirs(ii).name, obj.filetype)
                        if ~strcmp(dirs(ii).name, dirnamePrev)
                            obj.AddParentDirs(dirs(ii));
                        end
                        obj.AddFile(dirs(ii));
                    end

                    if obj.dirFormats.type == 0
                        obj.dirFormats.type = iFormat;
                    end
                elseif dirs(ii).IsDir()
                    obj.FindDataSet(iFormat, iPattern+1, [parentdir, dirs(ii).filename])
                end
                dirnamePrev = dirs(ii).name;
            end
        end

        % ----------------------------------------------------
        function AddParentDirs(obj, dirname)
            pathrel = getPathRelative([dirname.rootdir, dirname.name], obj.rootdir);
            subdirs = str2cell_fast(pathrel, {'/','\'});
            N = length(subdirs);
            for ii = 1:N-1
                if strcmp(subdirs{ii}, 'nirs')
                    continue;
                end
                pathrel2 = buildpathfrompathparts(subdirs(1:ii));
                if obj.SearchLookupTable(pathrel2)
                    continue;
                end
                obj.files(end+1) = FileClass([obj.rootdir, '/', pathrel2], obj.rootdir);
                obj.AddLookupTable(obj.files(end).name)
            end
        end

        % ----------------------------------------------------
        function AddFile(obj, file)
            obj.files(end+1) = file;
            obj.nfiles = obj.nfiles+1;
            obj.AddLookupTable(obj.files(end).filename)
        end

        % ----------------------------------------------------
        function ErrorCheckName(obj)
            for ii = length(obj.files):-1:1
                if obj.files(ii).ErrorCheckName()<0
                    q = obj.AskToFixNameConflicts(ii);
                    if q == 1
                        obj.files(ii).FixNameConflict();
                    else
                        obj.files(ii).NameConflictFixed();
                    end
                end
                if obj.files(ii).GetError()<0
                    obj.err = -1;
                end
            end
        end

        % ----------------------------------------------------
        function ErrorCheckFinal(obj)
            obj.ErrorCheckName();

            % Find all acquisition files in group folder
            fileNames = findTypeFiles(obj.rootdir, ['.', obj.filetype]);

            % Make alist of all files excluded from current data set
            for ii = 1:length(fileNames)
                filefound = false;

                for jj = 1:length(obj.files)
                    if pathscompare(fileNames{ii}, [obj.rootdir, obj.files(jj).name])
                        filefound = true;
                        break;
                    end
                end

                for jj = 1:length(obj.filesErr)
                    if pathscompare(fileNames{ii}, [obj.rootdir, obj.filesErr(jj).name])
                        filefound = true;
                        break;
                    end
                end

                if ~filefound
                    obj.filesErr(end+1) = FileClass(fileNames{ii});
                    obj.filesErr(end).SetError('Invalid File Name');
                end
            end

        end

        % --------------------------------------------------------------------------
        function answer = AskToFixNameConflicts(obj, ii)
            global cfg

            ConfigFileClass
            answer = 0;
            if obj.config.AskToFixNameConflicts == 0
                obj.files(ii).NameConflictFixed();
                return
            end
            q = MenuBox(obj.GetErrorMsg(ii), {'YES','NO'},[],[],'askEveryTimeOptions');
            if q(1) == 0
                return;
            end
            if length(q)>1 && q(2) == 1
                cfg.SetValue('Fix File Name Conflicts', sprintf('don''t ask again'));
                cfg.Save()
                obj.config.AskToFixNameConflicts = 0;
            end
            if q(1)==2
                obj.files(ii).NameConflictFixed();
            end
            answer = q(1);
        end

        % -----------------------------------------------------
        function errmsg = GetErrorMsg(obj, ii)
            p1      = fileparts(obj.files(ii).GetName());
            [p2,f2] = fileparts(filesepStandard(obj.files(ii).rootdir,'nameonly:file'));
            [~,f3]  = fileparts(p2);
            if isfile_private(obj.files(ii).GetName())
                filetype = 'file'; %#ok<*PROPLC>
            else
                filetype = 'folder';
            end
            containingFolder = '';
            if obj.files(ii).GetError() == -1
                containingFolder = p1;
            end
            if obj.files(ii).GetError() == -2
                containingFolder = f2;
            end
            if obj.files(ii).GetError() == -3
                containingFolder = f3;
            end
            msg{1} = sprintf('WARNING: The current %s (%s) has the same name as the folder (%s) containing it. ', filetype, obj.files(ii).GetName(), containingFolder);
            msg{2} = sprintf('All %ss should have a different name than the folder containing them, otherwise ', ['F',filetype(2:end)]);
            msg{3} = sprintf('it may cause incorrect results in processing. Do you want to rename this %s?', filetype);
            errmsg = [msg{:}];
        end

        % -------------------------------------------------------
        function pushbuttonLoadDataset_Callback(~, hObject)
            hp = get(hObject,'parent');
            hc = get(hp,'children');
            for ii = 1:length(hc)

                if strcmp(get(hc(ii),'tag'),'pushbuttonLoad')
                    hButtnLoad = hc(ii);
                elseif strcmp(get(hc(ii),'tag'),'pushbuttonSelectAnother')
                    hButtnSelectAnother = hc(ii);
                end

            end

            if hObject==hButtnLoad
                delete(hButtnSelectAnother);
            elseif hObject==hButtnSelectAnother
                delete(hButtnLoad);
            end
            delete(hp);
        end

        % ----------------------------------------------------------
        function b = IsEmpty(obj)
            if isempty(obj.files)
                b = true;
            else
                b = false;
            end
        end

        % ----------------------------------------------------------
        function found = ConvertedFrom(obj, src)
            found = zeros(length(src.files), 1);
            for ii = 1:length(src.files)
                if src.files(ii).isdir
                    found(ii) = -1;
                    continue;
                end
                [ps, fs] = fileparts(src.files(ii).name);
                for jj = 1:length(obj.files)
                    [pd, fd] = fileparts(obj.files(jj).name);
                    if strcmp(filesepStandard([ps,'/',fs], 'nameonly'), filesepStandard([pd,'/',fd], 'nameonly'))
                        found(ii) = 1;
                        break;
                    end
                end
            end
        end

        % ----------------------------------------------------------
        function ErrorCheck(obj)
            errorIdxs = [];

            if isempty(obj.files)
                return
            end

            % Assume constructor name follows from name of data format type
            constructor = sprintf('%sClass', [upper(obj.filetype(1)), obj.filetype(2:end)]);

            % Make sure function by that name exists; otherwise no way to
            % use it to check loadability
            if isempty(which(constructor))
                return;
            end

            % Try to create object of data filetype and load data into it
            msg = 'Please wait while we check group folder for valid data files ...';
            hwait = waitbar_improved(0, msg);
            dataflag = false;
            for ii = 1:length(obj.files)
                if obj.files(ii).isdir
                    continue;
                end
                filename = [obj.rootdir, obj.files(ii).name]; %#ok<NASGU>
                eval( sprintf('o = %s(filename);', constructor) );
                if  o.GetError() < 0
                    obj.logger.Write('DataFilesClass.ErrorCheck - ERROR: In file "%s" %s. File will not be added to data set\n', obj.files(ii).name, o.GetErrorMsg());
                    errorIdxs = [errorIdxs, ii]; %#ok<AGROW>
                elseif  contains(o.GetErrorMsg(), '''data'' field corrupt and unusable')
                    obj.logger.Write('DataFilesClass.ErrorCheck - WARNING: In file "%s" %s. File will not be added to data set\n', obj.files(ii).name, o.GetErrorMsg());
                    errorIdxs = [errorIdxs, ii]; %#ok<AGROW>
                elseif  contains(o.GetErrorMsg(), '''data'' field is invalid')
                    obj.logger.Write('DataFilesClass.ErrorCheck - WARNING: In file "%s" %s. File will not be added to data set\n', obj.files(ii).name, o.GetErrorMsg());
                    errorIdxs = [errorIdxs, ii]; %#ok<AGROW>
                elseif ~isempty(o.GetErrorMsg())
                    obj.logger.Write('DataFilesClass.ErrorCheck - WARNING: In file  "%s"  %s. File will be added anyway.\n', obj.files(ii).name, o.GetErrorMsg());
                    dataflag = true;
                else
                    dataflag = true;
                end
                if ~isempty(o.GetErrorMsg())
                    obj.files(ii).SetError(o.GetErrorMsg());
                end
                hwait = waitbar_improved(ii/length(obj.files), hwait, msg);
            end

            if dataflag==false
                obj.files = FileClass.empty();
            else
                for jj = 1:length(errorIdxs)
                    obj.filesErr(end+1) = obj.files(errorIdxs(jj)).copy;
                end
            	obj.files(errorIdxs) = [];
                obj.nfiles = obj.nfiles - length(errorIdxs);
            end
            close(hwait);
        end

        % ----------------------------------------------------------
        function err = GetError(obj)
            err = -1;
            if isempty(obj)
                return;
            end
            err = obj.err;
        end

        % ----------------------------------------------------------
        function PrintFolderStructure(obj, options)
            if ~exist('options','var')
                options = '';
            end
            stepsize = 3;
            obj.logger.Write('\n');
            obj.logger.Write('DataTreeClass - Data Set Folder Structure:\n');
            for ii = 1:length(obj.files)
                k = length(find(obj.files(ii).name=='/'));
                if ii<10
                    j=3;
                elseif ii>9 && ii<100
                    j=2;
                else
                    j=3;
                end
                if optionExists(options, 'flat')
                    obj.logger.Write(sprintf('%d.%s%s\n', ii, blanks(j), obj.files(ii).name));
                else
                    if ii<10
                        j=3;
                    elseif ii>9 && ii<100
                        j=2;
                    else
                        j=3;
                    end
                    if optionExists(options, 'numbered')
                        n = k*stepsize+stepsize+j;
                        obj.logger.Write(sprintf('%d.%s%s\n', ii, blanks(n), obj.files(ii).filename));
                    else
                        n = k*stepsize+stepsize;
                        obj.logger.Write(sprintf('%s%s\n', blanks(n), obj.files(ii).filename));
                    end
                end
            end
            obj.logger.Write('\n');
        end

    end

    methods (Access = private)

        % ----------------------------------------------------------
        function InitLookupTable(obj)
            width = 4;
            if isempty(obj.lookupTable)
                obj.lookupTable = int32(zeros((10^width)-1, 1));
            else
                obj.lookupTable(:) = 0;
            end
        end

        % ----------------------------------------------------------
        function AddLookupTable(obj, str)
            n = round(log10(length(obj.lookupTable)));
            obj.lookupTable(string2hash(str, n)) = 1;
        end

        % ----------------------------------------------------------
        function b = SearchLookupTable(obj, str)
            n = round(log10(length(obj.lookupTable)));
            b = obj.lookupTable(string2hash(str, n));
        end

    end
end

author: BUNPC


text:
function y = cmpndNoiseOut(noise, mu, varsigma)

% CMPNDNOISEOUT Compute the output of the CMPND noise given the input mean and variance.
% FORMAT
% DESC computes the ouptut for the compound
% noise given input mean and variances.
% ARG noise : the noise structure for which the output is computed.
% ARG mu : the input mean values.
% ARG varSigma : the input variance values.
% RETURN y : the output from the noise model.
%
% SEEALSO : cmpndNoiseParamInit, noiseOut, noiseCreate,
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005

% NOISE

y = zeros(size(mu));
for i = 1:length(noise.comp)
  fhandle = str2func([noise.comp{i}.type 'NoiseOut']);
  y(:, i) = fhandle(noise.comp{i},...
                    mu(:, i), ...
                    varsigma(:, i));
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function M = getmassmatvec(elem2edge,area,Dlambda,elemType,K)
%% GETMASSMATVEC Get the mass matrix of vector finite element space
%
% M = GETMASSMATVEC(elem2edge,area,Dlambda,elemType,K) get mass matrix of the finite element
% space specified by elemType.
%
% The elemType can be:
%
% - "RT0": The lowest order Raviart-Thomas element
% - "BDM1": The lowest order Brezzi-Douglas-Michel element
% - "BDM1B": The BDM element enriched by the curl of cubic bubble function
% - "ND1': The lowest order Nedelec element
%
% Note that RT0 and ND1 share the same mass matrix.
%
% Created by Ming Wang at July, 2012. Improved by Long Chen.

if ~exist('K','var'), K = []; end
NE = double(max(elem2edge(:)));
NT = size(elem2edge,1);
DiDj = zeros(NT,3,3);
for i = 1:3
    for j = i:3
        DiDj(:,i,j) = dot(Dlambda(:,:,i),Dlambda(:,:,j),2);
        DiDj(:,j,i) = DiDj(:,i,j);
    end
end

localEdge = [2 3; 1 3; 1 2];
%% RT0
if strcmp(elemType,'RT0') || strcmp(elemType,'ND1')
    M = sparse(NE,NE);
    for i = 1:3
        for j = i:3
            % local to global index map and its sign
            ii = double(elem2edge(:,i));
            jj = double(elem2edge(:,j));
            i1 = localEdge(i,1); i2 = localEdge(i,2); % [i1,i2] is the edge opposite to vertex i.
            j1 = localEdge(j,1); j2 = localEdge(j,2);
            % computation of mass matrix --- (phi_i, phi_j)
            Mij = 1/12*area.*( (1+(i1==j1))*DiDj(:,i2,j2) ...
                             - (1+(i1==j2))*DiDj(:,i2,j1) ...
                             - (1+(i2==j1))*DiDj(:,i1,j2) ...
                             + (1+(i2==j2))*DiDj(:,i1,j1));
            if ~isempty(K)
                Mij = Mij./K;
            end
            if (j==i)
                M = M + sparse(ii,jj,Mij,NE,NE);
            else
                M = M + sparse([ii;jj],[jj;ii],[Mij; Mij],NE,NE);
            end
        end
    end
end
%% BDM1
if strcmp(elemType,'BDM1') || strcmp(elemType,'BDM1B')
    M = sparse(2*NE,2*NE);
    for i = 1:3
        for j = i:3
            % local to global index map and its sign
            ii = double(elem2edge(:,i));
            jj = double(elem2edge(:,j));
            i1 = localEdge(i,1); i2 = localEdge(i,2); % [i1,i2] is the edge opposite to vertex i.
            j1 = localEdge(j,1); j2 = localEdge(j,2);
            % computation of mass matrix, note that (rot u, rot v) = (grad u, grad v)
            % (phi_i, phi_j)
            Mij = 1/12*area.*( (1+(i1==j1))*DiDj(:,i2,j2) ...
                             - (1+(i1==j2))*DiDj(:,i2,j1) ...
                             - (1+(i2==j1))*DiDj(:,i1,j2) ...
                             + (1+(i2==j2))*DiDj(:,i1,j1));
            if ~isempty(K)
                Mij = Mij./K;
            end
            if (j==i)
                M = M + sparse(ii,jj,Mij,2*NE,2*NE);
            else
                M = M + sparse([ii;jj],[jj;ii],[Mij; Mij],2*NE,2*NE);
            end
            % (psi_i,psi_j)
            Mij = 1/12*area.*( (1+(i1==j1))*DiDj(:,i2,j2) ...
                             + (1+(i1==j2))*DiDj(:,i2,j1) ...
                             + (1+(i2==j1))*DiDj(:,i1,j2) ...
                             + (1+(i2==j2))*DiDj(:,i1,j1));
            if ~isempty(K)
                Mij = Mij./K;
            end
            if (j==i)
                M = M + sparse(ii+NE,jj+NE,Mij,2*NE,2*NE);
            else
                M = M + sparse([ii;jj]+NE,[jj;ii]+NE,[Mij; Mij],2*NE,2*NE);
            end
        end
    end
    for i = 1:3
        for j = 1:3
            % local to global index map and its sign
            ii = double(elem2edge(:,i));
            jj = double(elem2edge(:,j));
            i1 = localEdge(i,1); i2 = localEdge(i,2);
            j1 = localEdge(j,1); j2 = localEdge(j,2);
            % (psi_i,phi_j)
            Mij = 1/12*area.*( (1+(i1==j1))*DiDj(:,i2,j2) ...
                             - (1+(i1==j2))*DiDj(:,i2,j1) ...
                             + (1+(i2==j1))*DiDj(:,i1,j2) ...
                             - (1+(i2==j2))*DiDj(:,i1,j1));
            if ~isempty(K)
                Mij = Mij./K;
            end
            M = M + sparse([ii+NE;jj],[jj;ii+NE],[Mij; Mij],2*NE,2*NE);
        end
    end
end
%% BDM1B
if strcmp(elemType,'BDM1B')
    newM = sparse(2*NE+NT,2*NE+NT);
    newM(1:2*NE,1:2*NE) = M;
    M = newM;
    % (phi_i, bubble)
    for i = 1:3
        ii = double(elem2edge(:,i));
        jj = double((1:NT)');
        i1 = localEdge(i,1); i2 = localEdge(i,2); i3 = 6-i1-i2;
        Mij = 9/10*area.*(...
             dot(Dlambda(:,:,i2),Dlambda(:,:,i3),2)...
            +dot(Dlambda(:,:,i2),Dlambda(:,:,i2),2)...
            -dot(Dlambda(:,:,i1),Dlambda(:,:,i3),2)...
            -dot(Dlambda(:,:,i1),Dlambda(:,:,i1),2));
        if ~isempty(K)
            Mij = Mij./K;
        end
        M = M + sparse([ii;jj+2*NE],[jj+2*NE;ii],[Mij;Mij],2*NE+NT,2*NE+NT);
    end
    clear ii jj i1 i2 i3 Mij;
    % (psi_i, bubble)
    for i = 1:3
        ii = double(elem2edge(:,i));
        jj = double((1:NT)');
        i1 = localEdge(i,1); i2 = localEdge(i,2); i3 = 6-i1-i2;
        Mij = 9/10*area.*(...
             dot(Dlambda(:,:,i2),Dlambda(:,:,i3),2)...
            +dot(Dlambda(:,:,i1),Dlambda(:,:,i3),2)...
            +dot(Dlambda(:,:,i2),Dlambda(:,:,i2),2)...
            +dot(Dlambda(:,:,i1),Dlambda(:,:,i1),2)...
            +dot(Dlambda(:,:,i1),Dlambda(:,:,i2),2));
        if ~isempty(K)
            Mij = Mij./K;
        end
        M = M + sparse([ii+NE;jj+2*NE],[jj+2*NE;ii+NE],[Mij;Mij],2*NE+NT,2*NE+NT);
    end
    clear ii jj i1 i2 i3 Mij;
    % (bubble, bubble)
    ii = 1+2*NE:NT+2*NE;
    Mij = 81/10*area.*(...
          dot(Dlambda(:,:,1),Dlambda(:,:,1),2)...
         +dot(Dlambda(:,:,1),Dlambda(:,:,2),2)...
         +dot(Dlambda(:,:,1),Dlambda(:,:,3),2)...
         +dot(Dlambda(:,:,2),Dlambda(:,:,2),2)...
         +dot(Dlambda(:,:,2),Dlambda(:,:,3),2)...
         +dot(Dlambda(:,:,3),Dlambda(:,:,3),2));
    if ~isempty(K)
        Mij = Mij./K;
    end
    M = M + sparse(ii,ii,Mij,2*NE+NT,2*NE+NT);
end

repo: Aero-matlab


text:
function var = hlp_mergeVarargin(varargin)
% var = hlp_mergeVarargin(varargin)
% Checks if first argument in varargin is a struct and, if so, converts to
% arglist format (cell array of name-value pairs) and appends any remaining
% varargin arguments. Use in combination with finputcheck() to convert
% mixed-type varargin to structure format
%
% This function will be deprecated in SIFT 1.0-beta
%
% Example:
%   var = hlp_mergeVarargin(varargin);
%   g = finputcheck(var, hlp_getDefaultArglist(myPrefix), myFuncName,'ignore');
%
% Author: Tim Mullen 2010, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

% This function is part of the Source Information Flow Toolbox (SIFT)
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

if isempty(varargin)
    var = {};
    return;
end

if isstruct(varargin{1})
    var = hlp_struct2varargin(varargin{1});
    varargin = varargin(2:end);
else
    var = {};
end

if length(varargin)>1
    var = [var,varargin];
end

repo: REST


text:
function element_size = p09_element_size ( )

%*****************************************************************************80
%
%% P09_ELEMENT_SIZE returns a typical element size for problem 09.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Input, real ELEMENT_SIZE, a typical element size.
%
  element_size = 0.005;

  return
end

author: johannesgerer


text:
% repeat a matrix
%
function [output] = F_transpose(input_layer, curr_layer)
input = input_layer.a;

output = input';

end

author: singaxiong

repo: SignalGraph


text:
function C = struct2nameval(S)
%STRUCT2NAMEVAL Converts a structure to a cell array of name-value pairs.
% Usage:
%   nameval_cell = struct2nameval(struct)
%
% See also: nameval2struct

% Check input
validateattributes(S, {'struct'}, {'nonempty', 'scalar'})

% Convert to cell array
names = fieldnames(S);
C = cell(1, numel(names) * 2);
C(1:2:end) = names;
C(2:2:end) = struct2cell(S);

end

author: talmo

repo: leap

save_path: github-repos/MATLAB/talmo-leap


text:
function [hE,hV]=wgPlot(adjMat,coord,varargin)
%function [hE,hV]=wgPlot(adjMat,coord,varargin)
%
% Weighted Graph Plot from adjacency matrix [adjMat] and vertices
% coordinate [coord].
%
% INPUT:
%    [adjMat] = N x N sparse square adjacency matrix.
%     [coord] = N x 2 matrix of vertex coordinates of the graph to be plotted.
%  [varargin] = are specified as parameter value pairs where the parameters are
%     'edgeColorMap' = m1 x 3 edge colormap for coloring edges by their
%                      weight, {default=cool}
%        'edgeWidth' = scalar specifying the width of the edges. {default=0.1}
%     'vertexMarker' = single char, can be {.ox+*sdv^<>ph} as in plot {default='.'}
%   'vertexColorMap' = m2 x 3 vertex color map for coloring vertices by their
%                      weight, {default=summer}
%     'vertexWeight' = N x 1 vector of vertex weight that overrides using the
%                      diagonal of [adjMat] for specifying vertex size.
%      'vertexScale' = scalar vertex scaling factor for specifying scaling
%                      the size of vertices. {default=100}
%   'vertexmetadata' = N x 1 vector of vertex meta data for coloring the verticies.
% OUTPUT:
%  [hE] = vector/scalar of handles to edges of the drawn graph (1 per color).
%  [hV] = scalar handles to vertices of the drawn graph.
%
% SEE ALSO: gplot, treeplot, spy, plot
%
% By: Michael Wu  --  michael.wu@lithium.com (May 2009)
%
%====================

% Set default parameter values
%--------------------
h=gca; prh; hold on; axis off;
axesArea(h,[6 7 5 5]);
plotParm={'markerSize',6,'lineWidth',0.1,'marker','.','MarkerEdgeColor',[1,0.5,0.2]};
siz=size(adjMat);
vrtxSiz=100;
edgeMap=cool;
vrtxMap=summer;

% Parse parameter value pairs
%--------------------
nVarArgin=length(varargin);
for kk=1:2:nVarArgin
	switch lower(varargin{kk})
    case 'edgecolormap'
      edgeMap=varargin{kk+1};
    case 'edgewidth'
      plotParm=[plotParm,{'lineWidth',varargin{kk+1}}];
    case 'vertexmarker'
      plotParm=[plotParm,{'marker',varargin{kk+1}}];
    case 'vertexcolormap'
      vrtxMap=varargin{kk+1};
    case 'vertexweight'
      vrtxWt=varargin{kk+1};
    case 'vertexmetadata'
      vrtxCol=varargin{kk+1};
    case 'vertexscale'
      vrtxSiz=varargin{kk+1};
    otherwise
      error(['wgPlot >< Unknown parameter ''',varargin{kk},'''.']) ;
  end
end

% Determine if diagonal is weighted.
%--------------------
if exist('vrtxWt','var')
  vWt=vrtxWt;
else
  vWt=diag(adjMat);
end
vWeighted=length(setdiff(unique(vWt),0))>1;

% Map edge weight to edge colormap
%--------------------
if ~all(vWt==0)
  adjMat(speye(siz)~=0)=0;
end  % if ~any

% Determine if edges are weighted
%--------------------
[ii,jj,eWt] = find(adjMat);
qq=unique([ii,jj]);
minEWt=min(eWt);
maxEWt=max(eWt);
eWtRange=maxEWt-minEWt;
eWeighted=eWtRange>0;

% Map edge weight to edge colormap
%--------------------
if eWeighted
  neColor=size(edgeMap,1);
  eWt=ceil((neColor-1)*(eWt-minEWt)/(maxEWt-minEWt)+1);
end  % if eWtRange

% Plot edges
%--------------------
if eWeighted
  hE=[];
  maxX=max(coord(qq,1));
  minX=min(coord(qq,1));
  maxY=max(coord(qq,2));
  minY=min(coord(qq,2));
  legLim=linspace(minX,maxX,neColor+1);
  yStep=(maxY-minY)/20;
  legY=minY-yStep;

  for kk=1:neColor
    p=find(eWt==kk);
    nSegment=length(p);
    x=[coord(ii(p),1),coord(jj(p),1),repmat(nan,nSegment,1)]';
    y=[coord(ii(p),2),coord(jj(p),2),repmat(nan,nSegment,1)]';
    hE=[hE,plot(x(:),y(:),'color',edgeMap(kk,:),plotParm{:})];
    % Draw legend bar
    line([legLim(kk),legLim(kk+1)],[legY,legY],'lineWidth',15,'color',edgeMap(kk,:));
  end  % for kk

  % Draw Legend Label
  text([legLim(1),legLim(end)],[legY-0.5*yStep,legY-0.5*yStep], ...
    {num2str(minEWt),num2str(maxEWt)},'HorizontalAlignment','center','color',[0.5,0.5,0.5]);
else
    nSegment=length(ii);
    x=[coord(ii,1),coord(jj,1),nan(nSegment,1)]';
    y=[coord(ii,2),coord(jj,2),nan(nSegment,1)]';
    hE=plot(x(:),y(:),plotParm{:});
end  % if eWeighted

% Plot vertices
%--------------------
if vWeighted
  % Map vertex weight to vertex size
  %--------------------
  minVwt=min(vWt);
  maxVwt=max(vWt);
  vWt=vrtxSiz*(vWt-minVwt)/(maxVwt-minVwt)+1;

  % Map vertex metadata to vertex colormap
  %--------------------
  if exist('vrtxCol','var')
    colormap(vrtxMap);
    hV=scatter(coord(qq,1),coord(qq,2),vWt,vrtxCol,'filled');
    colorbar;
  else
    hV=scatter(coord(qq,1),coord(qq,2),vWt,'filled','MarkerFaceColor',[1,0.5,0.2]);
  end

else
  %hV=plot(coord(:,1),coord(:,2),plotParm{:},'LineStyle','none');
  hV=plot(coord(qq,1),coord(qq,2),plotParm{:},'LineStyle','none');
end

% Set axes
%--------------------
axis tight;
ax=axis;
dxRange=(ax(2)-ax(1))/500;
dyRange=(ax(4)-ax(3))/500;
axis([ax(1)-dxRange,ax(2)+dxRange,ax(3)-dyRange,ax(4)+dyRange]);

author: Sable

repo: mcbench-benchmarks