text:
function model = run_finetuning(model)
% run generative finetuning
% Input: generatively pretrained model
% Output: generatively finetuned model

rng('shuffle');
kernels;
debug = 0;

data_list = read_data_list(model.data_path, model.classnames, ...
    model.volume_size + 2 * model.pad_size, 'train', debug);

num_layer = length(model.layers);
for l = 2 : num_layer
    model.layers{l}.grdw = zeros(size(model.layers{l}.w), 'single');
    model.layers{l}.grdb = zeros(size(model.layers{l}.b), 'single');
    model.layers{l}.grdc = zeros(size(model.layers{l}.c), 'single');
end

% fine-tuning phase: wake-sleep algorithm
param = [];
param.epochs = 200;
param.lr = 0.00003;
param.momentum = [0.9, 0.9];
param.kCD = 3;
param.persistant = 1;
param.batch_size = 32;
param.sparse_damping = 0;
param.sparse_target = 0;
param.sparse_cost = 0;

[model]= wake_sleep(model, data_list, param);

save('finetuned_model','model');

author: zhirongw


text:
function [x, objective, errorFlag, errorMsg] = quadraticProgramming(H, f, A, b, Aeq, beq, lb, ub, x0, options)
% Provides a common interface to several quadratic programming solvers.
% Checks each solver for errors.
%
% That is it solves the problem:
%   min 0.5 * x'*H*x + f'*x
%   subject to A*x<=b, Aeq*x=beq, lb<=x<=ub
%
% Requirements: at least one of the following quadratic programing solvers
% - clp -- open source solve quadratic programming solver
%   http://control.ee.ethz.ch/~joloef/mexclp.zip
% - minq
%   http://www.mat.univie.ac.at/~neum/software/minq/
% - qpip -- open source solve quadratic programming solver
%   http://sigpromu.org/quadprog/index.html
% - Optimization Toolbox - has quadprog, MATLAB's quadratic programming
%   solver. Note: quadprog is not very good. We suggest you use another
%   solver instead.
%   http://www.mathworks.com/products/optimization/
% - Wolf
%   http://www.mathworks.com/matlabcentral/fileexchange/27397-quadratic-programming-by-wolfs-method
%
% Author: Jonathan Karr
% Affiliation: Covert Lab, Department of Bioengineering, Stanford University
% Last updated: 1/17/2011

solver = 'clp';
if exist('options', 'var') && isstruct(options)
    solver = options.solver;
end

solverOptions = struct;
if exist('options', 'var') && isstruct(options) && isfield(options, 'solverOptions') && isfield(options.solverOptions, options.solver)
    solverOptions = options.solverOptions.(options.solver);
end

switch solver
    case 'clp'
        [x, objective, exitFlag] = clp(H, f, A, b, Aeq, beq, lb, ub, solverOptions);
        switch exitFlag
            case 0, errorMsg = 'optimal';
            case 1, errorMsg = 'infeasible';
            case 2, errorMsg = 'unbounded';
        end
        errorFlag = exitFlag ~= 0;
    case 'minqsep'
        [m, n] = size(Aeq);
        printLevel = 1;
        if isfield(solverOptions, 'printLevel'), printLevel = solverOptions.printLevel; end;
        [x, objective, errorFlag] = minqsep(f, diag(H), [Aeq; eye(n); -eye(n)], ...
            [beq; lb; -ub], [true(m, 1); false(n, 1); false(n, 1)], printLevel, x0);
        switch errorFlag
            case 0, errorMsg = 'global minimizer found';
            case 1, errorMsg = 'approximate solution; feasible set probably empty';
            case 99, errorMsg = 'approximate solution; maxit exceeded';
        end
    case 'qpip'
        display = 0;
        mu = 0.0;
        method = 1;
        if isfield(solverOptions, 'display'), display = solverOptions.display; end;
        if isfield(solverOptions, 'mu'),      mu      = solverOptions.mu;      end;
        if isfield(solverOptions, 'method'),  method  = solverOptions.method;  end;
        [x, exitFlag] = qpip(H, f, A, b, Aeq, beq, lb, ub, display, mu, method);
        objective = x' *H * x + f' * x;
        errorFlag = exitFlag ~= 0;
        switch exitFlag
            case 0,    errorMsg = 'optimal';
            otherwise, errorMsg = 'other error';
        end
    case 'quadprog'
        [x, objective, exitFlag, output] = quadprog(H, f, A, b, Aeq, beq, lb, ub, x0, solverOptions);
        errorFlag = exitFlag <= 0;
        errorMsg = output.message;
    case 'wolf'
        [m, n] = size(Aeq);
        [x, objective] = wolf(H, f, [beq; lb; ub],[Aeq; eye(n); eye(n)], ...
            [zeros(m, 1); ones(n, 1); -ones(n, 1)], 1);
        errorFlag = 0;
        errorMsg = 'optimal';
    otherwise
        throw(MException('ComputationUtil:error', 'Invalid solver'));
end

author: CovertLab

repo: WholeCell

save_path: github-repos/MATLAB/CovertLab-WholeCell


text:
%KERNELM Trainable kernel mapping, dissimilarity representation
%
%   [W,J] = KERNELM(A,KERNEL,SELECT,P1,P2 , ...)
%    W    = A*KERNELM([],KERNEL,SELECT,P1,P2 , ...)
%    W    = A*KERNELM(KERNEL,SELECT,P1,P2 , ...)
%    K    = B*W
%
% INPUT
%   A,B         Datasets
%   KERNEL      Untrained kernel / dissimilarity representation,
%               a mapping computing proximities between objects.
%               default: Euclidean dissimilarities: PROXM('d',1)
%   SELECT      Name of object selection procedure, see below
%   P1,P2, ...  Additional parameters for SELECT
%
% OUTPUT
%   W          Mapping
%   J          Vector with indices of selected objects for representation
%   K          Kernel matrix, dissimilarity representation,
%              size [SIZE(B,1) LENGTH(J)]
%
% DESCRIPTION
% Computes the kernel mapping W for the representation objects in A. The
% computation of the kernel matrix, which is a proximity matrix (similarities
% or dissimilarities) should be defined in KERNEL by an untrained mapping
% like PROXM for predefined proximities or USERKERNEL for user specified
% proximities.
% A*KERNEL should 'train' the kernel, i.e. specify A as representation set.
% B*(A*KERNEL) should compute the kernel matrix: a dataset.
%
% The only advantage of this routine over kernel mappings defined by PROXM
% or USERKERNEL is that it includes some options for object selection
% (prototype selection) of the initial representation set.
%
% Initially, the kernel mapping has a size [SIZE(A,2) SIZE(A,1)]. For
% increased efficiency or accuracy the representation set may be reduced
% by a routine given by the string SELECT to select to objects J, using
% possibly additional parameters P1, P2, etcetera.
%
% The following choices for SELECT are supported:
%
% 'random'    random selection of P1 objects, maximum P2
% 'gendat'    [X,Y,J] = GENDAT(A,P1)
% 'kcentres'  [LAB,J] = KCENTRES(DISTM(A),P1,P2)
% 'modeseek'  [LAB,J] = MODESEEK(DISTM(A),P1)
% 'edicon'    J = EDICON(DISTM(A),P1,P2,P3)
% 'featsel'   J = +FEATSELM(A*KERNELM(A,TYPE,P),P1,P2,P3)
%
% REFERENCES
% 1. E.Pekalska, R.P.W.Duin, P.Paclik, Prototype selection for dissimilarity-
% based classification, Pattern Recognition, vol. 39, no. 2, 2006, 189-208.
% 2. E.Pekalska and R.P.W.Duin, The Dissimilarity Representation for Pattern
% Recognition, Foundations and Applications, World Scientific, 2005, 1-607.
%
% EXAMPLE
% a = gendatb;
% w = (scalem*kernelm([],'random',5)*fisherc);
% scatterd(a)
% plotc(a*w)
% plotc(a*w,'r')
% plotc(a*w,'b')
%
% SEE ALSO (PRTools Guide)
% DATASETS, MAPPINGS, PROXM, USERKERNEL, KERNELC

% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands

% $Id: kernelm.m,v 1.7 2007/07/10 08:25:29 duin Exp $

function w = kernelm(varargin)

	argin = shiftargin(varargin,'prmapping');
	argin = shiftargin(varargin,'char',2);
  argin = setdefaults(argin,[],proxm([],'d',1),[],[],[],[]);
  if mapping_task(argin,'definition')
    w = define_mapping(argin,'untrained');
    w = setname(w,'Kernel mapping');
  else % training
    varargin = cell(1,numel(argin)-3);
    [a,kernel,select,varargin{:}] = deal(argin{:});
    if isstr(kernel) % old format of call: kernelm(a,type,p,n), training
      type = kernel;
      p = select;
      if ~isempty(varargin)
        if length(varargin) > 1
          error('Wrong parameters supplied')
        end
        n = varargin{1};
      else
        n = [];
      end
      [m,k] = size(a);
      kernel = proxm([],type,p);
      w = prmapping(mfilename,'trained',{a*kernel},getlab(a),k,m);
      if ~isempty(n)
        w = w*pcam(a*w,n);
      end
      w = setname(w,'Kernel Mapping');

    elseif isa(kernel,'prmapping') && ...
           ~strcmp(getmapping_file(kernel),mfilename) % training

      a = testdatasize(a);
      a = testdatasize(a,'objects');
      isuntrained(kernel);
      [m,k] = size(a);
      %w = prmapping('kernelm','trained',{a*kernel},getlab(a),k,m);
      if isempty(select)
        w = prmapping('kernelm','trained',{a*kernel},getlab(a),k,m);
      elseif ismapping(select)
        r = a*select;
        w = prmapping('kernelm','trained',{r*kernel},getlab(a),k,size(r,1));
      else
        switch select
          case 'random'
            J = randperm(m);
            n = varargin{1};
            if isempty(n) | n > m
              error('Number of objects to be selected not given or too large')
            end
            if n < 1, n = ceil(n*m); end % fraction given
            if ~isempty(varargin{2})
              n = min(n,varargin{2});
            end
            J = J(1:n);
          case 'gendat'
            [x,y,J] = gendat(a,varargin{1});
          case 'kcentres'
            [lab,J] = kcentres(distm(a),varargin{1:2});
          case 'modeseek'
            [lab,J] = modeseek(distm(a),varargin{1});
          case 'edicon'
            J = edicon(distm(a),varargin{1:3});
          case 'featsel'
            w = prmapping('kernelm','trained',{a*kernel},getlab(a),k,m);
            J = +featselm(a*w,varargin{1:3});
          otherwise
            error('Unknown choice for object selection')
        end
        % redefine mapping with reduced representation set
        labels_out = getlab(a);
        w = prmapping('kernelm','trained',{a(J,:)*kernel},labels_out(J,:),k,length(J));
      end
      w = setname(w,'Kernel Mapping');

    else % Execution of the mapping, w will be a dataset.

      kern = getdata(kernel,1); % trained kernel is stored in datafield
      K = a*kern;
      w = setdat(a,K,kern);

    end

  end

return

author: marianux

repo: ecg-kit

save_path: github-repos/MATLAB/marianux-ecg-kit


text:
function yp = p20_fun ( neqn, t, y )

%*****************************************************************************80
%
%% P20_FUN evaluates the function for problem P20.
%
%  Discussion:
%
%    4 equations
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Wayne Enright, John Pryce,
%    Algorithm 648,
%    ACM Transactions on Mathematical Software,
%    Volume 13, Number 1, pages 28-34.
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Input, real T, Y(NEQN), the arguments of the derivative
%    function.
%
%    Output, real YP(NEQN), the value of the derivative function.
%
  yp = zeros ( neqn, 1 );

  yp(1) = y(3);
  yp(2) = y(4);
  yp(3) = -y(1) / ( sqrt ( ( y(1).^2 + y(2).^2 ) ) ).^3;
  yp(4) = -y(2) / ( sqrt ( ( y(1).^2 + y(2).^2 ) ) ).^3;

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% Script demo_model_estimation_1st_level
% 1st level model specification and estimation
%
%  demo_model_estimation_1st_level
%
%
%   See also

% Author:   Saskia Bollmann & Lars Kasper
% Created:  2018-05-04
% Copyright (C) 2018 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public License (GPL), version 3.
% You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version).
% For further details, see the file COPYING or
%  <http://www.gnu.org/licenses/>.

clear;
close all;
clc;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% (0) User Inputs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% uses the output of demo_preprocessing; PLEASE MODIFY TO YOUR PATH
pathOutputDemoPreprocessing = fullfile(pwd, 'preprocessing', 'MrSeries_*');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% (1) Load data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

S = MrSeries(pathOutputDemoPreprocessing);
% change directory to get a separate it from the preprocessing
S.parameters.save.path = strrep(S.parameters.save.path, 'preprocessing', 'model_estimation');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% (2) Make brain mask
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% add white and grey matter TPMs
S.additionalImages{end+1} = S.tissueProbabilityMaps{1} + S.tissueProbabilityMaps{2};
S.additionalImages{4}.name = 'brain_tpm';
S.additionalImages{4}.parameters.save.fileName = 'brain_tpm.nii';
S.additionalImages{4}.plot;
% set parameters for mask
S.parameters.compute_masks.nameInputImages = 'brain_tpm';
S.parameters.compute_masks.nameTargetGeometry = 'mean';
S.compute_masks;
% check mask
S.mean.plot('overlayImages', S.masks{2});
% close mask
S.masks{3} = S.masks{2}.imclose(strel('disk', 5));
% check again
S.mean.plot('overlayImages', S.masks{3});
% perfect - save new mask
S.masks{3}.save;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% (3) Specify Model
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% timing in seconds
S.glm.timingUnits = 'secs';
% repetition time - check!
disp(['The specified TR is ', num2str(S.data.geometry.TR_s), 's.']);
S.glm.repetitionTime = S.data.geometry.TR_s;
% model derivatives
S.glm.hrfDerivatives = [1 1];

% add conditions
% specify block length
block_length = 20;
% specify condition onset
condition = 20:40:380;
% remove 5 first TRs
condition_onsets = condition - 5 * S.data.geometry.TR_s;

% add to glm
S.glm.conditions.names = {'tapping'};
S.glm.conditions.onsets = {condition_onsets};
% add durations
S.glm.conditions.durations = {block_length};
% add an explicit mask
S.glm.explicitMasking = S.masks{3}.get_filename;
% turn of inplicit masking threshold;
S.glm.maskingThreshold = -Inf;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% (4) Estimate Model
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute stat images
S.compute_stat_images;
% estimate
S.specify_and_estimate_1st_level;
% look at design matrix
S.glm.plot_design_matrix;

author: translationalneuromodeling

repo: tapas


text:
close all; clear all; clc;

audio = audioload();

file = 'text.txt';
fid  = fopen(file, 'r');
text = fread(fid,'*char')';
fclose(fid);

out = iss_enc(audio.data, text);
audiosave(out, audio, '.mp3', 128);

author: ktekeli

repo: audio-steganography-algorithms


text:
function p = addImpliedSDP(p)
if p.K.q(1)==0 && p.K.s(1) > 0
    % Search for rows where there is a constant, and a diagonal term
    % which thus has to be structly positive, we might leads us to a
    % constraints of the type sum x_i >= 1, if only non-negative integer
    % variables are involved, entering with positive coefficient (and v.s)
    newF = [];
    top = p.K.f + p.K.l + 1;
    for i = 1:length(p.K.s)
        F = p.F_struc(top:top + p.K.s(i)^2-1,:);
        X0 = reshape(F(:,1),p.K.s(i),p.K.s(i));
        candidates = find(any(X0-diag(diag(X0)),2) & (diag(X0)<=0));
        if ~isempty(candidates);
            I = speye(p.K.s(i),p.K.s(i));
            pos = find(I(:));
            for j = candidates(1:end)'
                row = F(pos(j),2:end);
                used = find(row);
                if ~isempty(used)
                    if ~any(row(p.noninteger_variables))
                        if all(row <=0) && all(p.ub(used)<=0)
                            row(find(row)) = 1;
                            newF = [newF;-1 -row];
                        elseif all(row >=0) && all(p.lb(used)>=0)
                            row(find(row)) = 1;
                            newF = [newF;-1 row];
                        end
                    end
                end
            end
        end
        top = top + p.K.s(i)^2;
    end
    if size(newF,1)>0
        p.F_struc = [p.F_struc(1:p.K.f + p.K.l,:);
            newF;
            p.F_struc(1+p.K.f+p.K.l:end,:)];
        p.K.l = p.K.l + size(newF,1);
    end

    % Search for trivial variables entering in diagonal elements alone, and
    % not entering anywhere else in model. Bad modelling?
    % First, they should not appear in LP cone (can be generalized by
    % checking that it acts in the correct direction)
    % TODO: Check for possibility of different signs etc, currently only
    % implemented for typical test cases
    candidates = find(~any(p.F_struc(1:p.K.f + p.K.l,2:end),1));
    fixable = nan(1,length(candidates));

    top = p.K.f + p.K.l + 1;
    for j = 1:length(p.K.s)
        F = p.F_struc(top:top + p.K.s(j)^2-1,:);
        for i = 1:length(candidates(:)')
            X0 = reshape(F(:,1 + candidates(i)),p.K.s(j),p.K.s(j));
            % Diagonal matrix?
            d = diag(X0);
            if nnz((X0-diag(d)))==0
                if all(sign(d)<=0) && p.c(i)>=0 && (isnan(fixable(i)) || fixable(i)==-1)
                    fixable(i) = -1;
                elseif all(sign(d)>=0) && p.c(i)<=0 && (isnan(fixable(i)) || fixable(i)==1)
                    fixable(i) = 1;
                else
                    fixable(i) = 0;
                end
            else
                fixable(i) = 0;
            end
        end
        top = top + p.K.s(j)^2;
    end
    p.adjustable = candidates(find(fixable));
    for i = candidates(find(~isnan(fixable)))
%         if fixable(i) == -1
%             if ~isinf(p.lb(i))
%                 %             p.ub(i) = p.lb(i);
%                 %             p.F_struc(:,1) = p.F_struc(:,1) + p.F_struc(:,i+1)*p.lb(i);
%                 %             p.F_struc(:,i+1) = 0;
%                 %         else
%                 %             % TODO whole row/column should be removed from the LMI!
%             end
%         elseif fixable(i) == 1
%             if ~isinf(p.ub(i))
%                 %             p.ub(i) = p.lb(i);
%                 %             p.F_struc(:,1) = p.F_struc(:,1) + p.F_struc(:,i+1)*p.lb(i);
%                 %             p.F_struc(:,i+1) = 0;
%                 %         else
%                 %             % TODO whole row/column should be removed from the LMI!
%             end
%         end

    end
end

author: zarathustr

repo: LibQPEP

save_path: github-repos/MATLAB/zarathustr-LibQPEP


text:
function varargout = fisher(varargin)
% VL_FISHER    Fisher vector feature encoding
%   ENC = VL_FISHER(X, MEANS, COVARIANCES, PRIORS) computes the Fisher
%   vector encoding of the vectors X relative to the Gaussian mixture
%   model with means MEANS, covariances COVARIANCES, and prior mode
%   probabilities PRIORS.
%
%   X has one column per data vector (e.g. a SIFT descriptor), and
%   MEANS and COVARIANCES one column per GMM component (covariance
%   matrices are assumed diagonal, hence these are simply the variance
%   of each data dimension). PRIORS has size equal to the number of
%   GMM components. All data must be of the same class, either SINGLE
%   or DOUBLE.
%
%   ENC is a vector of the same class of X of size equal to the
%   product of the data dimension and the number of components.
%
%   By default, the standard Fisher vector is computed. VL_FISHER()
%   accepts the following options:
%
%   Normalized::
%     If specified, L2 normalize the Fisher vector.
%
%   SquareRoot::
%     If specified, the signed square root function is applied to
%     ENC before normalization.
%
%   Improved::
%     If specified, compute the improved variant of the Fisher
%     Vector. This is equivalent to specifying the Normalized and
%     SquareRoot options.
%
%   Fast::
%     If specified, uses slightly less accurate computations but
%     significantly increase the speed in some cases (particularly
%     with a large number of Gaussian modes).
%
%   Verbose::
%     Increase the verbosity level (may be specified multiple times).
%
%   See: Fisher vectors, VL_HELP().
[varargout{1:nargout}] = vl_fisher(varargin{:});

author: yihui-he

repo: panorama

save_path: github-repos/MATLAB/yihui-he-panorama


text:
classdef testScnlobject < matlab.unittest.TestCase
   % testScnlobject validates the funcionality of scnlobject using matlab's
   % built in unit tests

   methods (Test)
      %---- test methods follow. each starts with "test" ---
      function testSimpleConstructors(testCase)
         % make sure these throw no error
         reftag = testScnlobject.createReference('N','S','L','C');
         testCase.verifyEqual(reftag,scnlobject('S', 'C', 'N', 'L'));  % 4 string constructor
         ct2 = reftag;
         testCase.verifyEqual(ct2, reftag);              % copy constructor
         testCase.verifyEqual(scnlobject('N.S.L.C'), reftag);           % string constructor
         testCase.verifyEqual(reftag,scnlobject({'N.S.L.C'}));         % cell constructor
      end

      function testWhitespaceConstructors(testCase)
         reftag = testScnlobject.createReference('N','S','L','C');
         ct = scnlobject('  N .S . L. C ');
         testCase.verifyEqual(reftag, ct);
         ct = scnlobject(' S ', ' C ', ' N ', ' L ');
         testCase.verifyEqual(reftag, ct);
      end

      function testArrayConstruction(testCase)
         reftag = testScnlobject.createReference('N','S','L','C');
         ct = scnlobject({'N .S . L. C ',' N. S . L.C '});
         testCase.verifyEqual(reftag, ct(1));
         testCase.verifyEqual(ct(1), ct(2));
         ct = scnlobject(['N.S.L.C      '; ' N.S  . L . C']);
         testCase.verifyEqual(reftag, ct(1));
         testCase.verifyEqual(ct(1), ct(2));
         ct = scnlobject({'S','S','S'},{'C','C','C'}, {'N','N','N'}, {'L','L','L'} );
         testCase.verifyEqual(ct(1), ct(2));
         testCase.verifyEqual(ct(2), ct(3));
         ct = scnlobject(['N.S.L.C ';' N.S.L.C'; 'N.S .L.C']);
         testCase.verifyEqual(ct(1), ct(2));
         testCase.verifyEqual(ct(2), ct(3));
         ct = scnlobject({'S1','S2'},'C','N','L');
         testCase.verifyEqual(get(ct(1),'station'),'S1')
         testCase.verifyEqual(get(ct(2),'station'), 'S2');
      end

      function testEqNe(testCase)
         A = testScnlobject.createReference('NW','STA','LOC','CHA');
         B = testScnlobject.createReference('NW','STA','LOC','CHA');
         C = testScnlobject.createReference('NW','STA','LOC','CHAN');
         testCase.verifyTrue(eq(A, B));
         testCase.verifyTrue(A == B);
         testCase.verifyFalse(A == C);
      end

      function testStringConversions(testCase)
         nslc = 'IU.ANMO.00.LOG';
         ct = scnlobject(nslc);
         testCase.verifyEqual(get(ct,'nscl_string'),'IU_ANMO_LOG_00');
      end

      function testIsmember(testCase)
         A = scnlobject('N.S.L.C');
         B = scnlobject('N1.S1.L1.C1');
         C = scnlobject('N2.S2.L2.C2');
         testCase.verifyEqual(ismember(A,[A, A, B]), true)
         testCase.verifyEqual(ismember([A, A, B],A), [true true false]);
         [LTA, LTB]   = ismember([A A B C],  [A scnlobject() B; B scnlobject() scnlobject()]);
         [NumA, NumB] = ismember([ 1 1 2 3], [1 0 2;2 0 0]);
         testCase.verifyEqual(LTA, NumA)
         testCase.verifyEqual(LTB, NumB)
      end

      function  testMatching(testCase)
         wildcardString = '*.*.*.*';
         A = scnlobject('N.S.L.C');
         B = scnlobject('N1.S1.L1.C1');
         % C = scnlobject('N2.S2.L2.C2');
         W = scnlobject(wildcardString);
         testCase.verifyTrue(ismember(scnlobject,wildcardString), 'Wildcards are not recognized');
         testCase.verifyError(@() ismember(A,B),'somexception')
         testCase.verifyTrue(ismember(A,W))
         testCase.verifyEqual(ismember([A, A, B],W), [true true true]);
         testCase.verifyTrue(ismember(A, [A A W]));
      end
   end

   methods(Static)
      function obj = createReference(N, S, L, C)
         obj = scnlobject();
         obj = set(obj,'network',N,'station',S,'channel',C,'location',L);
      end
   end
end

author: geoscience-community-codes

repo: GISMO


text:
function img = mrExtractImgVol(volume,iSize,numSlices,samp, ...
                                 dataRange,badVal)
%
%  img = mrExtractImgVol(volume,iSize,numSlices,samp,dataRange,badVal)
%
%AUTHOR:  Engel
%DATE:    November, 1994
%PURPOSE:
%  Extracts and interpolates the values from a volume of data.
% The locations to be returned are listed in the parameter samp.
%
% The input volume is formatted so that each row is an image
%
% The sampling grid is a matrix whose columns are x,y,and z.
% For the image to be displayable using myShowImage, the sampling
% matrix should run down columns fastest, rows slowest.
%
% volume:     a volume of data represented as a vector
% iSize:      the row and col size of individual images in the volume
% numSlices:  the number of image slices in the volume
% samp:       the sample locations we wish to extract from the volume.
%
% OPTIONAL ARGUMENTS:
% dataRange:  the starting and ending Z-coordinates for the
%	      volume of data.  It is optional. If no dataRange is given
%	      the Z range is assumed to be 1:numSlices. This allows subsets
%             of the full volume to be passed in.
%
% badVal:  specifies the value that should be returned
%	   for values outside the data set.
%
% global interpflag:  the value of this global specifies whether or not
% 	              to interpolate the volume data.
%
% RETURNED:
%   img:     an image is returned, selected from the volume data
%	     according to the samp values.
%

% BW 10/19/95

global interpflag

% Check arguments
%
if (nargin < 6) 	% No badVal
 badVal = 1;
end
if (nargin >= 5) 	% There is a dataRange argument
 samp(:,3) = samp(:,3) - dataRange(1) + 1;
end
if (nargin < 4)
 error('mrExtractImgVol:  Requires 4 arguments')
end

% If the global interpolation flag is set, then interpolate the data.
% to make sure there are values at the sample values.
%
if (interpflag)

% myCinterp3 uses trilinear interpolation to create a value
% at each samp location.  It refuses to extrapolate, so if
% a sample point is outside the volume size, badVal is returned
%
 img = myCinterp3(volume,iSize,numSlices,samp,badVal)';

else

% Check the samp range to make sure we are not out of bounds.
% Points that are out of bounds will be assigned badVal
%
 bad = (samp(:,1) > iSize(2)) | (samp(:,2) > iSize(1)) ...
 | (samp(:,3) > (numSlices+.5)) | (samp(:,1) < .5)  ...
 | (samp(:,2) < 1) | (samp(:,3) < 1);

% Convert the 3d coordinates to the volume coord.
%
  volcoords = mrVcoord(round(samp),iSize);
% volcoords = mr3d21d(samp,iSize,[1,numSlices]);

%Take care of out of bounds points
%
 bad = bad | (volcoords < 1 )| (volcoords > length(volume));

%Extract data.  Notice that badVal is used here, too.
%
 img = zeros(size(volcoords));
 img(~bad) = volume(volcoords(~bad));
 img(bad) = badVal*ones(1,sum(bad));

% Replaced this line.  Does this make trouble for someone? -- BW
%
% img(isnan(img)) = badVal*ones(1,sum(isnan(img)));
end

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function bvec_to_i4_test ( )

%*****************************************************************************80
%
%% BVEC_TO_I4_TEST tests BVEC_TO_I4;
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  n = 10;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'BVEC_TO_I4_TEST\n' );
  fprintf ( 1, '  BVEC_TO_I4 converts a signed binary vector\n' );
  fprintf ( 1, '  to an integer;\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  I --> BVEC  -->  I\n' );
  fprintf ( 1, '\n' );

  for i = -3 : 10
    bvec = i4_to_bvec ( i, n );
    i2 = bvec_to_i4 ( n, bvec );
    fprintf ( 1, '  %2d  ', i );
    for j = 1 : n
      fprintf ( 1, '%1d', bvec(j) );
    end
    fprintf ( 1, '  %2d\n', i2 );
  end

  return
end


text:
function [output_width_map, output_height_map] = proposal_calc_output_size(conf, test_net_def_file)
% [output_width_map, output_height_map] = proposal_calc_output_size(conf, test_net_def_file)
% --------------------------------------------------------
% Faster R-CNN
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------

%     caffe.init_log(fullfile(pwd, 'caffe_log'));
    caffe_net = caffe.Net(test_net_def_file, 'test');

     % set gpu/cpu
    if conf.use_gpu
        caffe.set_mode_gpu();
    else
        caffe.set_mode_cpu();
    end

    input = 100:conf.max_size;
    output_w = nan(size(input));
    output_h = nan(size(input));
    for i = 1:length(input)
        s = input(i);
        im_blob = single(zeros(s, s, 3, 1));
        net_inputs = {im_blob};

        % Reshape net's input blobs
        caffe_net.reshape_as_input(net_inputs);
        caffe_net.forward(net_inputs);

        cls_score = caffe_net.blobs('proposal_cls_score').get_data();
        output_w(i) = size(cls_score, 1);
        output_h(i) = size(cls_score, 2);
    end

    output_width_map = containers.Map(input, output_w)
    output_height_map = containers.Map(input, output_h)
    caffe.reset_all();
end

author: jasjeetIM

repo: Mask-RCNN

save_path: github-repos/MATLAB/jasjeetIM-Mask-RCNN


text:
function view=analyze4d2mrLoadRet3TSeries(view,inFile,scan,volsToSkip,rotateInplanes,scaleFact,flipudFlag,rotateFlag,flipSliceOrder)
% view=4danalyze2mrLoadRet3TSeries(view,inFile,scan,volsToSkip,rotateInplan
% es,scaleFact,flipudFlag,fliplrFlag,flipSliceOrder)
% Converts from 4d analyze functional image data to mrLoadRet TSeries
% format.
% Uses read_avw to read in 4d analyze files. Then saves out the block as
% mlr TSeries while skipping over any initial 'junk frames';
%
% The doRotate param allows to you rotate the functional data by doRotate*90 degrees
% Try to read the the first volume to see if it's there and get the
% dimensions of all the rest
% ARW 032703 : Now saves out data in mrLoadRet3.0 format (.mat as opposed to .dat files)

% AAB 2003.07.08 After the temporal normalization bug, I reconverted the
% Tuebingen data using the Brucker-2-analyze converter downloaded from the
% website. The new time series do not need to be rotated or flipped
% up/down, but do need to be flipped left/right. So, I changed flipFlag to
% flipudFlag (for up/down) and added fliplrFlag (for left/right). I set
% all three values to be off by default.
% ARW : 120805 : This function based on analyze2mrLoadRet3TSeries.

if (~exist('volsToSkip','var'))
    volsToSkip=0;
end

if (~exist('scaleFact','var'))
    scaleFact=[1 1]; % No interpolation. (Scaling=1)
end

if (length(scaleFact)~=2) % If we just get a scalar for the scale factor, assume that it applies in both dimensions
    scaleFact=repmat(scaleFact(1),2);
end

if (~exist('rotateInplanes','var'))
    rotateInplanes=0; % This is off by default. Rotates 1*90 degrees
end

if (~exist('flipudFlag','var'))
    flipudFlag=0; % This is off by default. Flips up/down after rotation
end

if (~exist('fliplrFlag','var'))
    fliplrFlag=0; % This is off by default. Flips left/right after rotation
end
if (~exist('flipSliceOrder','var'))
    flipSliceOrder=0; % This is off by default. Flips left/right after rotation
end

disp('Reading volume');
funcVol=read_avw(inFile);
disp('Done');

% Now take care of flipping...

%
% if (mod(doRotate,2)) % When we rotate by 180 degrees the x and y dimensions remain unchanged
%     funcVol=zeros(y,x,nSlices,nVols);
% else
%     funcVol=zeros(x,y,nSlices,nVols);
% end
%
% fprintf('Rotating by %d x 90, flipupFlag=%d, fliplrFlag=%d',doRotate,flipudFlag,fliplrFlag);
%
%
% for t=0:(nVols-1)
%     thisImIndex=t+firstVolIndex;
%     suffix=sprintf('%03d',thisImIndex);
%     fileName=[inFileRoot,suffix];
%     V=spm_vol(fileName);
%     im=spm_read_vols(V);
%
%     % Do the rotation and scaling
%
%     if (mod(doRotate,2)) % When we rotate by 180 degrees the x and y dimensions remain unchanged
%         im2=zeros(y,x,nSlices);
%     else
%         im2=zeros(x,y,nSlices);
%     end
%     fprintf('\nVol=%d',thisImIndex);
%
%     for thisSlice=1:nSlices
%         imSlice=squeeze(im(:,:,thisSlice));
% %         imSlice=imresize(imSlice,[scaleFact(1)*y,scaleFact(2)*x],'nearest');
%
%         im2(:,:,thisSlice)=rot90(imSlice,doRotate);
%
%         if (flipudFlag)
%             im2(:,:,thisSlice)=flipud(im2(:,:,thisSlice));
%         end
%
%         if (fliplrFlag)
%             im2(:,:,thisSlice)=fliplr(im2(:,:,thisSlice));
%         end
%
%     end % next imSlice
%
%
%     if (flipSliceOrder) % We can make it so the slice order is reversed
%         im2=im2(:,:,[thisSlice:-1:1]);
%     end
%
%     funcVol(:,:,:,t+1)=im2;
%     %fprintf('.');
%
% end

% Crop the skipped frames
funcVol=funcVol(:,:,:,(volsToSkip+1):end);

if (rotateInplanes)
disp('Rotating');

[y x nSlices nVols]=size(funcVol)
for thisVol=1:nVols
    for thisSlice=1:nSlices
        funcVol(:,:,thisSlice,thisVol)=rot90(squeeze(funcVol(:,:,thisSlice,thisVol)),rotateInplane);
    end
end
end

% Now write them out in a different format
fprintf('\nDone reading data: Writing now...\n');
for t=1:nSlices

    tSeries=squeeze(funcVol(:,:,t,:));
    tSeries=reshape(tSeries,x*y,nVols);
    tSeries=tSeries';
    view=saveTSeries(tSeries,view,scan,t);

    fprintf('_');
end

fprintf('\nDone\n');


text:
function SD
clc;
clear;
close all;
%% the example fuction
datasize=200;
var_noise=0.1;
x=linspace(-10,10,datasize)';
    f=sin(x)./x;
noise=var_noise*randn(datasize,1);
y=f+noise;
x_raw=x;
plot(x_raw,f,'r-','LineWidth',2),hold on;
%% the training data samples
Inset=30;
dataindex=randsample(datasize,Inset);
xI=x(dataindex);
yI=y(dataindex);
plot(xI,yI,'b+'),hold on;
%  x(dataindex)=[];
%  y(dataindex)=[];
x=xI;
y=yI;
K_mat=Kernel_func(x,x,0.7,1.2)+var_noise*eye(Inset);
% [vecmat,valmat]=eig(K_mat);
% valmat=diag(valmat);
% [valmat,ix]=sort(valmat,'descend');
% vecmat=vecmat(:,ix);
L=chol(K_mat,'lower');
%%
testnum=500;
x_test=linspace(-15,15,testnum)';
K_test_train=Kernel_func(x_test,x,0.7,1.2);
K_test=Kernel_func(x_test,x_test,0.7,1.2);

f_mean=K_test_train*(L'\(L\y));
for i=1:testnum
K_ss=Kernel_func(x_test(i),x_test(i),0.7,1.2);
K_s=Kernel_func(x_test(i),x,0.7,1.2);
v=L\K_s';
  f_var(i)=K_ss-v'*v;
end
f_var=f_var';
plot(x_test,f_mean,'b-','LineWidth',2),hold on;
%%
x_area=[x_test;flipdim(x_test,1)];
ybound_std=[(f_mean+1.96*sqrt(f_var));flipdim(f_mean-1.96*sqrt(f_var),1)];
fill(x_area,ybound_std,[187 255 0]/255,'EdgeColor','none');
plot(x_raw,f,'r-','LineWidth',2),hold on;
plot(xI,yI,'b+'),hold on;
plot(x_test,f_mean,'b-','LineWidth',2),hold on;
%%
legend1=legend('target function','training points','preditive distribution','95% confidence interval');
 set(legend1,'Box','off','Color','none',...
     'Location','NorthEast');
xlabel('SD with 30 points ')
set(gca,'XTick',[-15:3:15])
matlab2tikz( 'SubData30.tex' )

author: epfl-lasa


text:
%%generate data config
param.split_data_num=1;
param.file_path_cam1=fullfile(fileparts(pwd),'people_tuples','scen1');%for test
param.file_path_cam2=fullfile(fileparts(pwd),'people_tuples','scen2');%for train
param.file_path_cam3=fullfile(fileparts(pwd),'people_tuples','scen3');%for train
param.save_traindata_filename='train_data_LPW';
param.save_testdata_filename='test_data_LPW';
%%generate ten split train/test data
for split_num_start=1:param.split_data_num
    if ~exist(strcat(param.save_traindata_filename,num2str(split_num_start)),'file')
        mkdir(strcat(param.save_traindata_filename,num2str(split_num_start)));
    end
    if ~exist(strcat(param.save_testdata_filename,num2str(split_num_start)),'file')
        mkdir(strcat(param.save_testdata_filename,num2str(split_num_start)));
    end
    subdir_cam3_view1=dir(strcat(param.file_path_cam3,'view1'));
    subdir_cam3_view2=dir(strcat(param.file_path_cam3,'view2'));
    subdir_cam3_view3=dir(strcat(param.file_path_cam3,'view3'));
    subdir_cam3_view4=dir(strcat(param.file_path_cam3,'view4'));
    subdir_cam2_view1=dir(strcat(param.file_path_cam2,'view1'));
    subdir_cam2_view2=dir(strcat(param.file_path_cam2,'view2'));
    subdir_cam2_view3=dir(strcat(param.file_path_cam2,'view3'));
    subdir_cam2_view4=dir(strcat(param.file_path_cam2,'view4'));

    subdir_cam1_view1=dir(strcat(param.file_path_cam1,'view1'));
    subdir_cam1_view2=dir(strcat(param.file_path_cam1,'view2'));
    subdir_cam1_view3=dir(strcat(param.file_path_cam1,'view3'));

    label_train_cam2_view1=[];
    train_image_name_cam2_view1={};
    label_train_cam2_view2=[];
    train_image_name_cam2_view2={};
    label_train_cam2_view3=[];
    train_image_name_cam2_view3={};
    label_train_cam2_view4=[];
    train_image_name_cam2_view4={};
    label_train_cam3_view1=[];
    train_image_name_cam3_view1={};
    label_train_cam3_view2=[];
    train_image_name_cam3_view2={};
    label_train_cam3_view3=[];
    train_image_name_cam3_view3={};
    label_train_cam3_view4=[];
    train_image_name_cam3_view4={};
    nameMapLabel_cam2=[];
    nameMapLabel_cam3=[];
    for i=3:(length(subdir_cam2_view3))
        fprintf('process test data cam2 view3:%d/%d\n',i,(length(subdir_cam2_view3)));
        image_path_cam2=strcat(param.file_path_cam2,'view3/',subdir_cam2_view3(i).name,'/');
        image_list_cam2=dir(image_path_cam2);
        nameMapLabel_cam2=[nameMapLabel_cam2;str2num(subdir_cam2_view3(i).name)];
        for j=3:length(image_list_cam2);
            image_name=strcat(image_path_cam2,image_list_cam2(j).name);
            label_train_cam2_view3=[label_train_cam2_view3;str2num(subdir_cam2_view3(i).name)];
            train_image_name_cam2_view3=[train_image_name_cam2_view3,image_name];
        end
    end
    for i=3:(length(subdir_cam2_view1))
        fprintf('process test data cam2 view1:%d/%d\n',i,(length(subdir_cam2_view1)));
        image_path_cam2=strcat(param.file_path_cam2,'view1/',subdir_cam2_view1(i).name,'/');
        image_list_cam2=dir(image_path_cam2);
        for j=3:length(image_list_cam2);
            image_name=strcat(image_path_cam2,image_list_cam2(j).name);
            label_train_cam2_view1=[label_train_cam2_view1;str2num(subdir_cam2_view1(i).name)];
            train_image_name_cam2_view1=[train_image_name_cam2_view1,image_name];
        end
    end
    for i=3:(length(subdir_cam2_view2))
        fprintf('process test data cam2 view2:%d/%d\n',i,(length(subdir_cam2_view2)));
        image_path_cam2=strcat(param.file_path_cam2,'view2/',subdir_cam2_view2(i).name,'/');
        image_list_cam2=dir(image_path_cam2);
        for j=3:length(image_list_cam2);
            image_name=strcat(image_path_cam2,image_list_cam2(j).name);
            label_train_cam2_view2=[label_train_cam2_view2;str2num(subdir_cam2_view2(i).name)];
            train_image_name_cam2_view2=[train_image_name_cam2_view2,image_name];
        end
    end
    for i=3:(length(subdir_cam2_view4))
        fprintf('process test data cam2 view2:%d/%d\n',i,(length(subdir_cam2_view4)));
        image_path_cam2=strcat(param.file_path_cam2,'view4/',subdir_cam2_view4(i).name,'/');
        image_list_cam2=dir(image_path_cam2);
        for j=3:length(image_list_cam2);
            image_name=strcat(image_path_cam2,image_list_cam2(j).name);
            label_train_cam2_view4=[label_train_cam2_view4;str2num(subdir_cam2_view4(i).name)];
            train_image_name_cam2_view4=[train_image_name_cam2_view4,image_name];
        end
    end
    %generate data for cam3
    for i=3:(length(subdir_cam3_view3))
        fprintf('process test data cam3 view3:%d/%d\n',i,(length(subdir_cam3_view3)));
        image_path_cam3=strcat(param.file_path_cam3,'view3/',subdir_cam3_view3(i).name,'/');
        image_list_cam3=dir(image_path_cam3);
        nameMapLabel_cam3=[nameMapLabel_cam3;str2num(subdir_cam3_view3(i).name)];
        for j=3:length(image_list_cam3);
            image_name=strcat(image_path_cam3,image_list_cam3(j).name);
            label_train_cam3_view3=[label_train_cam3_view3;str2num(subdir_cam3_view3(i).name)];
            train_image_name_cam3_view3=[train_image_name_cam3_view3,image_name];
        end
    end
    for i=3:(length(subdir_cam3_view1))
        fprintf('process test data cam3 view1:%d/%d\n',i,(length(subdir_cam3_view1)));
        image_path_cam3=strcat(param.file_path_cam3,'view1/',subdir_cam3_view1(i).name,'/');
        image_list_cam3=dir(image_path_cam3);
        for j=3:length(image_list_cam3);
            image_name=strcat(image_path_cam3,image_list_cam3(j).name);
            label_train_cam3_view1=[label_train_cam3_view1;str2num(subdir_cam3_view1(i).name)];
            train_image_name_cam3_view1=[train_image_name_cam3_view1,image_name];
        end
    end
    for i=3:(length(subdir_cam3_view2))
        fprintf('process test data cam3 view2:%d/%d\n',i,(length(subdir_cam3_view2)));
        image_path_cam3=strcat(param.file_path_cam3,'view2/',subdir_cam3_view2(i).name,'/');
        image_list_cam3=dir(image_path_cam3);
        for j=3:length(image_list_cam3);
            image_name=strcat(image_path_cam3,image_list_cam3(j).name);
            label_train_cam3_view2=[label_train_cam3_view2;str2num(subdir_cam3_view2(i).name)];
            train_image_name_cam3_view2=[train_image_name_cam3_view2,image_name];
        end
    end
    for i=3:(length(subdir_cam3_view4))
        fprintf('process test data cam3 view4:%d/%d\n',i,(length(subdir_cam3_view4)));
        image_path_cam3=strcat(param.file_path_cam3,'view4/',subdir_cam3_view4(i).name,'/');
        image_list_cam3=dir(image_path_cam3);
        for j=3:length(image_list_cam3);
            image_name=strcat(image_path_cam3,image_list_cam3(j).name);
            label_train_cam3_view4=[label_train_cam3_view4;str2num(subdir_cam3_view4(i).name)];
            train_image_name_cam3_view4=[train_image_name_cam3_view4,image_name];
        end
    end
    for i=1:length(label_train_cam2_view1)
        temp=find(nameMapLabel_cam2==label_train_cam2_view1(i));
        label_train_cam2_view1(i)=temp;
    end
    for i=1:length(label_train_cam2_view2)
        temp=find(nameMapLabel_cam2==label_train_cam2_view2(i));
        label_train_cam2_view2(i)=temp;
    end
    for i=1:length(label_train_cam2_view3)
        temp=find(nameMapLabel_cam2==label_train_cam2_view3(i));
        label_train_cam2_view3(i)=temp;
    end
    for i=1:length(label_train_cam2_view4)
        temp=find(nameMapLabel_cam2==label_train_cam2_view4(i));
        label_train_cam2_view4(i)=temp;
    end
    cam_label_max=size(nameMapLabel_cam2,1);
    for i=1:length(label_train_cam3_view1)
        temp=find(nameMapLabel_cam3==label_train_cam3_view1(i));
        label_train_cam3_view1(i)=temp+cam_label_max;
    end
    for i=1:length(label_train_cam3_view2)
        temp=find(nameMapLabel_cam3==label_train_cam3_view2(i));
        label_train_cam3_view2(i)=temp+cam_label_max;
    end
    for i=1:length(label_train_cam3_view3)
        temp=find(nameMapLabel_cam3==label_train_cam3_view3(i));
        label_train_cam3_view3(i)=temp+cam_label_max;
    end
    for i=1:length(label_train_cam3_view4)
        temp=find(nameMapLabel_cam3==label_train_cam3_view4(i));
        label_train_cam3_view4(i)=temp+cam_label_max;
    end
    save(strcat(param.save_traindata_filename,num2str(split_num_start),'/train_data.mat'),'label_train_cam2_view1','label_train_cam2_view2','label_train_cam2_view3','label_train_cam2_view4', ...
        'label_train_cam3_view1','label_train_cam3_view2','label_train_cam3_view3','label_train_cam3_view4', ...
        'train_image_name_cam2_view1','train_image_name_cam2_view2','train_image_name_cam2_view3','train_image_name_cam2_view4', ...
        'train_image_name_cam3_view1','train_image_name_cam3_view2','train_image_name_cam3_view3','train_image_name_cam3_view4','-v7.3');
    %generate test data
    test_data_cam1=[];
    label_test_cam1=[];
    test_image_name_cam1={};
    test_data_cam2=[];
    label_test_cam2=[];
    test_image_name_cam2={};
    test_data_cam3=[];
    label_test_cam3=[];
    test_image_name_cam3={};
    nameMapLabel=[];
    for i=3:(length(subdir_cam1_view2))
        fprintf('process test data view2:%d/%d\n',i,(length(subdir_cam1_view2)));
        image_path_cam2=strcat(param.file_path_cam1,'view2/',subdir_cam1_view2(i).name,'/');
        image_list_cam2=dir(image_path_cam2);
        nameMapLabel=[nameMapLabel;str2num(subdir_cam1_view2(i).name)];
        for j=3:length(image_list_cam2);
            image_name=strcat(image_path_cam2,image_list_cam2(j).name);
            label_test_cam2=[label_test_cam2;str2num(subdir_cam1_view2(i).name)];
            test_image_name_cam2=[test_image_name_cam2,image_name];
        end
    end
    for i=3:(length(subdir_cam1_view1))
        fprintf('process test data view1:%d/%d\n',i,(length(subdir_cam1_view1)));
        image_path_cam1=strcat(param.file_path_cam1,'view1/',subdir_cam1_view1(i).name,'/');
        image_list_cam1=dir(image_path_cam1);
        for j=3:length(image_list_cam1);
            image_name=strcat(image_path_cam1,image_list_cam1(j).name);
            label_test_cam1=[label_test_cam1;str2num(subdir_cam1_view1(i).name)];
            test_image_name_cam1=[test_image_name_cam1,image_name];
        end
    end
    for i=3:(length(subdir_cam1_view3))
        fprintf('process test data view3:%d/%d\n',i,(length(subdir_cam1_view3)));
        image_path_cam3=strcat(param.file_path_cam1,'view3/',subdir_cam1_view3(i).name,'/');
        image_list_cam3=dir(image_path_cam3);
        for j=3:length(image_list_cam3);
            image_name=strcat(image_path_cam3,image_list_cam3(j).name);
            label_test_cam3=[label_test_cam3;str2num(subdir_cam1_view3(i).name)];
            test_image_name_cam3=[test_image_name_cam3,image_name];
        end
    end
    for i=1:length(label_test_cam1)
        temp=find(nameMapLabel==label_test_cam1(i));
        label_test_cam1(i)=temp;
    end
    for i=1:length(label_test_cam2)
        temp=find(nameMapLabel==label_test_cam2(i));
        label_test_cam2(i)=temp;
    end
    for i=1:length(label_test_cam3)
        temp=find(nameMapLabel==label_test_cam3(i));
        label_test_cam3(i)=temp;
    end
    save(strcat(param.save_testdata_filename,num2str(split_num_start),'/test_data.mat'),'label_test_cam1','label_test_cam2','label_test_cam3','test_image_name_cam1','test_image_name_cam2','test_image_name_cam3','-v7.3');
end

author: liuyuisanai

repo: Quality-Aware-Network


text:
%% Copyright (C) 2014-2016, 2019, 2022 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy 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 software 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 software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @defmethod  @@sym isAlways (@var{eq})
%% @defmethodx @@sym isAlways (@var{eq}, 'Unknown', 'false')
%% @defmethodx @@sym isAlways (@var{eq}, 'Unknown', 'true')
%% @defmethodx @@sym isAlways (@var{eq}, 'Unknown', 'error')
%% Test if expression is mathematically true.
%%
%% Example:
%% @example
%% @group
%% syms x y
%% isAlways(x*(1+y) == x+x*y)
%%   @result{} 1
%% @end group
%% @end example
%% Contrast this with a test for “structural equality“:
%% @example
%% @group
%% logical(x*(1+y) == x+x*y)
%%   @result{} 0
%% @end group
%% @end example
%%
%% The optional keyword argument @qcode{'Unknown'} specifies that happens
%% for expressions that cannot simplify.  By default these return
%% false (that is, cannot verify it is always true).  Pass the
%% strings @qcode{'true'}, @qcode{'false'} or @qcode{'error'} to change the behaviour.  You
%% can also pass logical true/false.
%%
%% If @code{isAlways} is called on expressions without relationals,
%% it will return true for non-zero numbers:
%% @example
%% @group
%% isAlways (sym (10))
%%   @result{} 1
%% @end group
%% @end example
%%
%% It is safe to use @code{isAlways} even when the expression does not
%% require simplifying:
%% @example
%% syms x
%% isAlways (sin(x) - sin(x) == 0)
%%   @result{} 1
%% @end example
%% In practice, @code{isAlways} might get called on a simple
%% boolean variable, so this package implements @code{@@logical/isAlways}
%% (which is essentially a no-op).
%%
%% @seealso{@@sym/logical, @@sym/isequal, @@sym/eq, @@logical/isAlways}
%% @end defmethod

function r = isAlways(p, varargin)

  if (~ ((nargin == 1) || (nargin == 3)))
    print_usage ();
  end

  if (nargin == 3)
    assert(strcmpi(varargin{1}, 'unknown'))
    cant = varargin{2};
    if islogical(cant)
      % SMT doesn't allow nonstring but it seems reasonable
    elseif strcmpi(cant, 'true')
      cant = true;
    elseif strcmpi(cant, 'false')
      cant = false;
    elseif strcmpi(cant, 'error')
      % no-op
    else
      error('isAlways: invalid argument for "unknown" keyword')
    end
  else
    cant = false;
  end

  cmd = {
    'def simplify_tfn(p):'
    '    if p in (S.true, S.false):'
    '        return bool(p)'
    '    r = simplify(p)'
    '    #FIXME; Boolean, simplify more than once?'
    '    if r in (S.true, S.false):'
    '        return bool(r)'
    '    # FIXME: hopefully we get sympy patched for some of this'
    '    #ver = sympy.__version__'
    '    #if ver == "0.7.5" or ver.startswith("0.7.6") or ver.startswith("0.7.7"):'
    '    if True:'
    '        if isinstance(p, Equality):'
    '            r = Eq(sp.simplify(p.lhs - p.rhs), 0)'
    '            r = simplify(r)'
    '            if r in (S.true, S.false):'
    '                 return bool(r)'
    '        if isinstance(p, Unequality):'
    '            r = Eq(sp.simplify(p.lhs - p.rhs), 0)'
    '            r = simplify(r)'
    '            if r in (S.true, S.false):'
    '                 return not bool(r)'
    '        if isinstance(p, (Lt, Gt, Le, Ge)):'
    '            r = p._eval_relation(sp.simplify(p.lhs - p.rhs), sp.S(0))'
    '            r = simplify(r)'
    '            if r in (S.true, S.false):'
    '                 return bool(r)'
    '    # for SMT compat'
    '    if p.is_number:'
    '        r = p.is_zero'  % FIXME: return bool(r)?
    '        if r in (S.true, S.false):'
    '            return not bool(r)'
    '    return None' };
  % could distinguish b/w None and return a string for this last case

  cmd = vertcat(cmd, {
    '(x, unknown) = _ins'
    'if x is not None and x.is_Matrix:'
    '    r = [a for a in x.T]' % note transpose
    'else:'
    '    r = [x,]'
    'r = [simplify_tfn(a) for a in r]'
    'r = [unknown if a is None else a for a in r]'
    'flag = True'
    'if r.count("error") > 0:'
    '    flag = False'
    '    r = "cannot reliably convert sym to bool"'
    'return (flag, r)' });

  [flag, r] = pycall_sympy__ (cmd, p, cant);

  if (~flag)
    assert (ischar (r), 'isAlways: programming error?')
    error(['isAlways: ' r])
  end

  r = cell2mat(r);
  r = reshape(r, size(p));

end

%!test
%! % basics
%! assert(isAlways(true))
%! assert(isAlways(1==1))
%! assert(isAlways(sym(1)==sym(1)))
%! assert(isAlways(sym(1)==1))

%!test
%! % numbers to logic?
%! assert (isAlways(sym(1)))
%! assert (isAlways(sym(-1)))
%! assert (~isAlways(sym(0)))

%!shared x
%! syms x

%!test
%! % in this case it is boolean
%! expr = x - x == 0;
%! assert (logical(expr))
%! assert (isAlways(expr))
%! % and both are logical type
%! assert (islogical(logical(expr)))
%! assert (islogical(isAlways(expr)))

%!test
%! % structurally same and mathematically true
%! % (here expr should be sym, non-boolean)
%! expr = x == x;
%! assert (logical(expr))
%! assert (isAlways(expr))
%! %assert (~islogical(expr))   % FIXME: Issue #56
%! %assert (isa(expr, 'sym))

%!test
%! % structurally same and mathematically true
%! % (here expr should be sym, non-boolean)
%! expr = 1 + x == x + 1;
%! assert (logical(expr))
%! assert (isAlways(expr))

%!test
%! % non-zero numbers are true
%! assert (isAlways(sym(1)))
%! assert (isAlways(sym(-10)))
%! assert (~isAlways(sym(0)))

% FIXME: should we support implicit == 0 like sympy?  SMT does oppositve, plus it ignores assumptions?  SMT behaviour is probably meant to mimic matlab doubles,
%expr = x - x;
%c=c+1; r(c) = logical(expr);
%c=c+1; r(c) = isAlways(expr);

%!shared x, y
%! syms x y

%!test
%! % structurally same and mathematically true
%! % (here expr should be sym, non-boolean)
%! expr = x*(1+y) == x*(y+1);
%! assert (logical(expr))
%! assert (isAlways(expr))
%! assert (islogical(isAlways(expr)))

%!test
%! % Now for some differences
%! % simplest example from SymPy FAQ
%! expr = x*(1+y) == x+x*y;
%! assert (~logical(expr))
%! assert (isAlways(expr))

%!test
%! % more differences 1, these don't simplify in sympy (as of 2016-01)
%! expr = (x+1)^2 == x*x + 2*x + 1;
%! assert (~logical(expr))
%! assert (isAlways(expr))

%!test
%! % more differences 2
%! expr = sin(2*x) == 2*sin(x)*cos(x);
%! assert (~logical(expr))
%! assert (isAlways(expr))

%!test
%! % more differences 3, false
%! expr =  x*(x+y) == x^2 + x*y + 1;
%! assert (~logical(expr))
%! assert (~isAlways(expr))
%! assert (~isAlways(expr, 'unknown', 'error'))

%!test
%! % logically not equal, math equal
%! exprn =  x*(x+y) ~= x^2 + x*y;
%! assert (logical(exprn))
%! assert (~isAlways(exprn))
%!test
%! % logically not equal, math not equal
%! exprn =  x*(x+y) ~= x^2 + x*y + 1;
%! assert (logical(exprn))
%! assert (isAlways(exprn))

%!test
%! % equal and not equal
%! e1 = sin(x)^2 + cos(x)^2 == 1;
%! e2 = sin(x)^2 + cos(x)^2 == 2;
%! assert (~logical(e1))
%! assert (isAlways(e1))
%! assert (~logical(e2))
%! assert (~isAlways(e2))
%! assert (~isAlways(e2, 'unknown', 'error'))

%!error <invalid argument .* keyword> isAlways(x, 'unknown', 'kevin')
%!error <Invalid call> isAlways(x, 'unknown')
%!error <assert .* failed> isAlways(x, 'kevin', 'true')

%!error <isAlways: cannot reliably convert sym to bool>
%! a = [x*(x+y)==x^2+x*y  x==y];
%! b = isAlways(a, 'unknown', 'error');

%!error <isAlways: cannot reliably convert sym to bool>
%! a = x==y;
%! b = isAlways(a, 'unknown', 'error');

%!test
%! % array, unknown keyword
%! a = [x==x x==x+1 x==y x*(x+y)==x^2+x*y cos(x)^2+sin(x)^2==2];
%! b = isAlways(a, 'unknown', false);
%! c = isAlways(a, 'unknown', 'false');
%! expect = [true false false true false];
%! assert (islogical(b))
%! assert (isequal (b, expect))
%! assert (isequal (c, expect))
%! b = isAlways(a, 'unknown', true);
%! c = isAlways(a, 'unknown', 'true');
%! expect = [true false true true false];
%! assert (islogical(b))
%! assert (isequal (b, expect))
%! assert (isequal (c, expect))

%!test
%! % ineq
%! e =  x*(x+y) <= x^2 + x*y + 1;
%! assert (~logical(e))
%! assert (isAlways(e))
%! e =  x*(x+y) <= x^2 + x*y;
%! assert (~logical(e))
%! assert (isAlways(e))

%test
% % FIXME; booleans
% e1 = x*(x+1) == x*x+x
% e2 = x*(x+1)+2 == x*x+x+2
% b = e1 & e2
% assert isAlways(b)

repo: octsympy


text:
function P = vecperm(m, n)
%VECPERM    Vec-permutation matrix.
%           VECPERM(M, N) is the vec-permutation matrix, an MN-by-MN
%           permutation matrix P with the property that if A is M-by-N then
%           vec(A) = P*vec(A').
%           If N is omitted, it defaults to M.

%   P is formed by taking every n'th row from EYE(M*N), starting with
%   the first and working down - see p. 277 of the reference.

%   Reference:
%   H. V. Henderson and S. R. Searle The vec-permutation matrix,
%   the vec operator and Kronecker products: A review Linear and
%   Multilinear Algebra, 9 (1981), pp. 271-288.

if nargin == 1, n = m; end

P = zeros(m*n);
I = eye(m*n);

k = 1;
for i=1:n
    for j=i:n:m*n
        P(k,:) = I(j,:);
        k = k+1;
    end
end
end

author: OshriHalimi


text:
function [ ux, uy, uz ] = HS3D( image1, image2, alpha, iterations, ...
    uxInitial, uyInitial, uzInitial)
%This function estimates deformations between two subsequent 3-D images
%using Horn-Schunck optical flow method.
%
%   Description :
%
%   -image1, image2 :   two subsequent images or frames
%   -alpha :    smoothness parameter, default value is 1.
%   -iterations :   number of iterations, default value is 10.
%   -uxInitial, uyInitial, uzInitial : initial flow vectors, default value
%                                     is 0;
%
%   Reference :
%   B. K. Horn and B. G. Schunck, Determining optical ow, Cambridge, MA,
%   USA, Tech. Rep., 1980.
%
%   Author : Mohammad Mustafa
%   By courtesy of The University of Nottingham and Mirada Medical Limited,
%   Oxford, UK
%
%   Published under a Creative Commons Attribution-Non-Commercial-Share Alike
%   3.0 Unported Licence http://creativecommons.org/licenses/by-nc-sa/3.0/
%
%   June 2012

ux=zeros(size(image1)); uy=ux; uz=ux;

if nargin==2
    alpha=1; iterations=10;
    ux=zeros(size(image1)); uy=ux; uz=ux;
elseif nargin==3
    iterations=10;
    ux=zeros(size(image1)); uy=ux; uz=ux;
elseif nargin==6
    ux=uxInitial; uy=uyInitial; uz=uzInitial;
end

[Ix,Iy,Iz,It]=imageDerivatives3D(image1,image2);

laplacian = zeros(3,3,3);
laplacian(:,:,1) = [0 3 0;3 10 3;0 3 0];
laplacian(:,:,3) = laplacian(:,:,1);
laplacian(:,:,2) = [3 10 3;10 -96 10;3 10 3];
laplacian=laplacian./96;

for i=1:iterations
    uxAvg=convn(ux,laplacian,'same');
    uyAvg=convn(uy,laplacian,'same');
    uzAvg=convn(uy,laplacian,'same');
    ux=uxAvg - ( Ix.*( (Ix.*uxAvg) + (Iy.*uxAvg) + (Iz.*uzAvg) + It))...
        ./ ( alpha.^2 + Ix.^2 + Iy.^ 2 + Iz.^ 2);
    uy=uyAvg - ( Iy.*( (Ix.*uxAvg) + (Iy.*uxAvg) + (Iz.*uzAvg) + It))...
        ./ ( alpha.^2 + Ix.^2 + Iy.^ 2 + Iz.^ 2);
    uz=uzAvg - ( Iz.*( (Ix.*uxAvg) + (Iy.*uxAvg) + (Iz.*uzAvg) + It))...
        ./ ( alpha.^2 + Ix.^2 + Iy.^ 2 + Iz.^ 2);
end

ux(isnan(ux))=0;
uy(isnan(uy))=0;
uz(isnan(uz))=0;
end

author: Sable

repo: mcbench-benchmarks


text:
function [options,u,dim] = VBA_check(y,u,f_fname,g_fname,dim,options)
% VBA_CHECK
% [options,u,dim] = VBA_check(y,u,f_fname,g_fname,dim,options)
% Checks (and fills in default) optional inputs to VBA_NLStateSpaceModel.m
% function [options,u,dim] = VBA_check(y,u,f_fname,g_fname,dim,options)
% This function checks the consistency of the arguments to the
% VBA_NLStateSpaceModel.m function. Importantly, it fills in the missing
% priors and optional arguments.
% NB: if the user-specified priors on the stochastic innovations precision
% is a delta Dirac at infinity (priors.a_alpha = Inf and priors.b_alpha =
% 0), the priors are modified to invert an ODE-like state-space model, i.e.
% the equivalent deterministic system.

%% ________________________________________________________________________
%  check model dimension

% set default if static model
if isempty(f_fname)
    dim = VBA_check_struct(dim, ...
        'n_theta', 0, ...
        'n', 0);
end

% check if hidden state dimension:
assert( ...
     isfield(dim,'n')          ... exists,
  && isscalar(dim.n)           ... is a scalar value
  && mod(dim.n,1) == 0         ... that is integer
  && dim.n >= 0                ... and non negative
, '*** Please provide the dimension of the hidden state in dim.n');

% check if evolution parameters dimension:
assert( ...
     isfield(dim,'n_theta')    ... exists
  && isscalar(dim.n_theta)     ... is a scalar value
  && mod(dim.n_theta,1) == 0   ... that is integer
  && dim.n_theta >= 0          ... and non negative
, '*** Please provide the dimension of the evolution parameters in dim.n_theta');

% check if observation parameters dimension:
assert( ...
     isfield(dim,'n_phi')      ... exists
  && isscalar(dim.n_phi)       ... is a scalar value
  && mod(dim.n_phi,1) == 0     ... that is integer
  && dim.n_phi >= 0            ... and non negative
, '*** Please provide the dimension of the observation parameters in dim.n_phi');

dim = VBA_check_struct(dim, ...
    'n_t'   , size(y,2), ... % number of trials or time samples
    'p'     , size(y,1)  ... % data dimension
);

if isempty(u)
    u = zeros(0,dim.n_t);
else
    u = full(u);
end
dim.u = size(u,1);

%% ________________________________________________________________________
%  check VBA's options structure

if isfield(options,'binomial') % check for legacy binomial field
    options.sources = struct('type', options.binomial , ...
                             'out' , 1:dim.p          );
    options = rmfield(options, 'binomial');
    fprintf('*** WARNING: options.binomial is now deprecated. Please use ''options.sources.type = 1'' to specify a binary observation distribution.\n');
end

% set defaults
options = VBA_check_struct(options, ...
    'decim'      , 1     , ...     % Micro-time resolution
    'microU'     , 0     , ...     % Micro-resolution input
    'inF'        , []    , ...     % Optional (internal) parameters of the evolution function
    'inG'        , []    , ...     % Optional (internal) parameters of the observation function
    'checkGrads' , 0     , ...     % Check analytical gradients against numerical gradients
    'updateX0'   , 1     , ...     % Flag for initial conditions update
    'updateHP'   , 1     , ...     % Flag for hyperparameters update
    'initHP'     , 1     , ...     % Flag for hyperparameters initialization
    'backwardLag', 1     , ...     % time lag of the short-sighted backward-pass
    'MaxIter'    , 32    , ...     % Maximum number of iterations
    'MaxIterInit', 32    , ...     % Maximum number of iterations for the initialization
    'MinIter'    , 0     , ...     % Minimum number of iterations
    'TolFun'     , 2e-2  , ...     % Minimum change in the free energy
    'DisplayWin' , 1     , ...     % VB display window
    'gradF'      , 0     , ...     % Gauss-Newton ascent on free (1) or variational (0) energy
    'GnMaxIter'  , 32    , ...     % Gauss-Newton coordinate ascent maximum number of iterations:
    'GnTolFun'   , 1e-5  , ...     % Gauss-Newton coordinate ascent threshold on relative variational energy:
    'GnFigs'     , 0     , ...     % Gauss-Newton inner-loops figures
    'verbose'    , 1     , ...     % matlab window messages
    'OnLine'     , 0     , ...     % On-line version (true when called from VBA_OnLineWrapper.m)
    'delays'     , []    , ...     % delays
    'kernelSize' , 16    , ...     % max lag of Volterra kernels
    'nmog'       , 1     , ...     % split-Laplace VB?
    'UNL'        , 0     , ...     % un-normalized likelihood?
    'UNL_width'  , 4     , ...     % for partition function estimation
    'UNL_ng'     , 64      ...     % for partition function estimation
) ;

options = VBA_check_struct(options, ...
    'isYout'    , zeros(dim.p,dim.n_t)    , ... % excluded data
    'skipf'     , zeros(1,dim.n_t)        , ... % steady evolution
    'sources'   , struct()                  ...
) ;

options.sources = VBA_check_struct(options.sources, ...
    'type', 0        , ... % default to gaussian
    'out' , 1:dim.p  );

% % retrocompatibility
% if ~isfield(options,'binomial') && numel(options.sources)==1
%         options.binomial = options.sources.type;
% end

options.backwardLag = min([max([floor(round(options.backwardLag)),1]),dim.n_t]);
options.kernelSize  = min([dim.n_t,options.kernelSize]);

for i=1:numel(options.sources)
    if options.sources(i).type ~= 0 % if binomial
        if ~isempty(y)
            isYoutSource = options.isYout(options.sources(i).out,:);
            ySource = y(options.sources(i).out,:);
            if ~ VBA_isBinary (ySource(~ isYoutSource))
                error('*** Data should be binary!')
            end
            if islogical(ySource(~isYoutSource))
                error('*** Binary data should be numerical (0,1) not logical (true,false).\n*** Use y=+y or y=double(y) to convert your observations.',[])
            end
        end
    end
end

% split in multisession
[f_fname,g_fname,dim,options,u] = VBA_multisession_expand(f_fname,g_fname,dim,options,u);

% Deal with micro-resolution input
u = VBA_getU(u,options,dim,'2macro');

%% ________________________________________________________________________
%  check priors
[options,options.params2update] = VBA_fillInPriors(dim,options);
priors = options.priors;
% check consistency of priors and model dimensions
assert(size(priors.muX0,1)==dim.n,'*** Dimension of options.priors.muX0 does not match dim.n!')
assert(isequal(size(priors.SigmaX0),dim.n*[1,1]),'*** Dimension of options.priors.SigmaX0 does not match dim.n!')
assert(size(priors.muPhi,1)==dim.n_phi,'*** Dimension of options.priors.muPhi does not match dim.n_phi!')
assert(isequal(size(priors.SigmaPhi),dim.n_phi*[1,1]),'*** Dimension of options.priors.SigmaPhi does not match dim.n_phi!')
assert(size(priors.muTheta,1)==dim.n_theta,'*** Dimension of options.priors.muTheta does not match dim.n_theta!')
assert(isequal(size(priors.SigmaTheta),dim.n_theta*[1,1]),'*** Dimension of options.priors.SigmaTheta does not match dim.n_theta!')

if dim.n>0 && isempty(options.params2update.x0)
    options.updateX0 = 0;
end

% Name of the display figure
if ~isfield(options,'figName')
    if dim.n > 0
        if isinf(priors.a_alpha) && isequal(priors.b_alpha,0)
            options.figName = 'VB-Laplace identification of deterministic system';
        else
            options.figName = 'VB-Laplace identification of stochastic system';
        end
    else
        options.figName = 'VB-Laplace inversion of static model';
    end
end

% % ensure excluded data consistency (gaussian sources)
% TODO: remove once VBA_Iphi deal with isYout
if numel(options.sources) == 1
gsi = find([options.sources.type]==0);
for i=1:numel(gsi)
    for t=1:dim.n_t
        diQ = (diag(priors.iQy{t,i}) == 0) | options.isYout(options.sources(gsi(i)).out,t);
        options.isYout(options.sources(gsi(i)).out,t) = +diQ;
        priors.iQy{t,i} = diag(~diQ)*priors.iQy{t,i}*diag(~diQ);
    end
end
end

% store evolution/observation function handles
options.f_fname = f_fname;
options.g_fname = g_fname;

%% ________________________________________________________________________
%  check inversion specific cases

% split-MoG sufficient statistics
if options.nmog > 1
    np = length(options.params2update.phi);
    [m0,s0,w0] = getMoG4N01(options.nmog,1,0);
    tic,[C] = get_nkdraws(options.nmog,np,0);toc
    nd = size(C,2);
    split.w = zeros(nd,1);
    split.m = zeros(np,nd);
    split.s = zeros(np,nd);
    for i=1:nd
        split.w(i) = prod(w0(C(:,i)));
        split.m(:,i) = m0(C(:,i));
        split.s(:,i) = s0(C(:,i));
    end
    split.w = split.w./sum(split.w);
    options.split = split;
end

% Delay embedding
if dim.n > 0 && sum(options.delays(:)) > 0
    % modify options:
    dim.n_embed = dim.n*max(options.delays(:));
    inF.dim = dim;
    inF.options = options;
    inF.f_fname = f_fname;
    inF.f_nout = nargout(f_fname);
    inG.dim = dim;
    inG.options = options;
    inG.g_fname = g_fname;
    inG.g_nout = nargout(g_fname);
    options.inF = inF;
    options.inG = inG;
    options.f_fname = @f_embed;
    options.g_fname = @g_embed;
    options.delays = [];
    % modify priors:
    Zeros = zeros(inF.dim.n,dim.n_embed);
    for t=1:dim.n_t
        tmp = 1e2*kron(eye(max(inG.options.delays(:))),priors.iQx{t});
        priors.iQx{t} = [   priors.iQx{t}	Zeros
                            Zeros'          tmp    ];
        priors.iQx{t}(isnan(priors.iQx{t})) = 0;
        dpc = diag(priors.iQx{t});
        iz = find(isinf(dpc));
        if ~isempty(iz)
            options.params2update.x{t} = setdiff(1:dim.n,iz);
        else
            options.params2update.x{t} = 1:dim.n;
        end
    end
    priors.muX0 = repmat(priors.muX0,max(inF.options.delays(:))+1,1);
    priors.SigmaX0 = kron(eye(max(inF.options.delays(:))+1),priors.SigmaX0);
    dpc = diag(priors.SigmaX0);
    iz = find(dpc==0);
    if ~isempty(iz)
        options.params2update.x0 = setdiff(1:length(priors.SigmaX0),iz);
    else
        options.params2update.x0 = 1:length(priors.SigmaX0);
    end
    dim.n = dim.n*(max(inF.options.delays(:))+1);
end

% Add other inputs in the options structure:
options.g_nout = nargout(options.g_fname);
options.priors = priors;
options.dim = dim;

% Special case: DCM check
if isequal(options.f_fname,@f_DCMwHRF) && isequal(options.g_fname,@g_HRF3)
    % DCM for fMRI
    [options] = VBA_check4DCM(options);
end

if dim.n > 0
    options.f_nout = nargout(options.f_fname);
    if isinf(priors.a_alpha) && isequal(priors.b_alpha,0)
        % Check whether SDE --> ODE [ p(alpha) = Dirac at 0 ]
        % This will allow the algorithm to shortcut the VB-Laplace extended Kalman
        % smoother, treating the model as non-stochastic DCM. In this version, the
        % hidden states are assumed to obey an ODE, which is the deterministic
        % variant of the more general SDE.
        priors0 = priors;
        dim0 = dim;
        options0 = options;
        % Embed evolution parameters and initial conditions in observation
        % parameters  --> modify prior structure accordingly
        priors.muTheta = [];
        priors.SigmaTheta = [];
        priors.muX0 = [];
        priors.SigmaX0 = [];
        if dim0.n_theta > 0
            priors.muPhi = [priors0.muPhi;priors0.muTheta];
            Zeros = zeros(dim0.n_phi,dim0.n_theta);
            priors.SigmaPhi = [ priors0.SigmaPhi  Zeros
                                Zeros'            priors0.SigmaTheta ];
            options.params2update.phi = [options0.params2update.phi,options0.params2update.theta + dim0.n_phi];
        end
        if options.updateX0
            priors.muPhi = [priors.muPhi;priors0.muX0];
            Zeros = zeros(dim0.n_phi+dim0.n_theta,dim0.n);
            priors.SigmaPhi = [ priors.SigmaPhi  Zeros
                                Zeros'           priors0.SigmaX0 ];
            options.params2update.phi = [options.params2update.phi,options0.params2update.x0 + dim0.n_phi + dim0.n_theta];
        end
        % Modify dim and options structures
        dim.n_theta = 0;
        dim.n_phi = size(priors.muPhi,1);
        dim.n = 0;
        options.f_fname = [];
        options.f_nout = 0;
        options.g_fname = @VBA_odeLim;
        options.g_nout = nargout(@VBA_odeLim);
        options.inF = [];
        options.inG = [];
        options.inG.old.dim = dim0;
        options.inG.old.options = options0;
        options.inG.dim = dim;
        options.priors = priors;
        options.dim = dim;
    else % stochastic inversion
        % Derive marginalization operators for the lagged Kalman filter
        n = dim.n;
        lag = options.backwardLag + 1;
        options.lagOp.C = [zeros(n,n*(lag-1)),eye(n)];
        options.lagOp.D = [zeros(n,n*(lag-2)),eye(n),zeros(n,n)];
        options.lagOp.E = [eye(n*(lag-1)),zeros(n*(lag-1),n)];
        options.lagOp.Eu = [zeros(n*(lag-1),n),eye(n*(lag-1))];
        options.lagOp.M = [eye(n),zeros(n,n*(lag-1))];
    end
end

author: MBB-team

repo: VBA-toolbox


text:
function x = p14_start ( i, x )

%*****************************************************************************80
%
%% P14_START returns a starting point for problem 14.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 May 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer I, the index of the starting point.
%
%    Output, real X, the starting point.
%
  if ( i == 1 )
    x = 3.0;
  elseif ( i == 2 )
    x = - 0.5;
  elseif ( i == 3 )
    x = 0.0;
  elseif ( i == 4 )
    x = 2.12742;
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P14_START - Fatal error!\n' );
    fprintf ( 1, '  Illegal starting point index = %d\n', i );
    error ( 'P14_START - Fatal error!' );
  end

  return
end


text:
% Test file for @chebfun/svd.m.

function pass = test_svd()

if ( nargin < 1 )
    pref = chebfunpref();
end

% Check a simple example.
f = chebfun(@(x) [sin(x) cos(x) exp(x)], [-1 -0.5 0 0.5 1]);
[U, S, V] = svd(f);
g = U*S*V';
pass(1) = ~U.isTransposed && (normest(f - g) < ...
    1e2*max(vscale(f)*eps, vscale(g)*eps));

pass(2) = norm(U'*U - eye(3), 'fro') < 10*vscale(U)*eps;
pass(3) = norm(V'*V - eye(3), 'fro') < 10*vscale(f)*eps;
pass(4) = isequal(svd(f), diag(S));

ft = f.';
[U, S, V] = svd(ft);
g = U*S*V';
pass(5) = ~V.isTransposed && (normest(ft - g) < ...
    1e2*max(vscale(ft)*eps, vscale(g)*eps));

pass(6) = norm(U'*U - eye(3), 'fro') < 10*vscale(f)*eps;
pass(7) = norm(V'*V - eye(3), 'fro') < 10*vscale(V)*eps;

% Check error conditions.
try
    g = svd(f, 1);
    pass(8) = false;
catch ME
    pass(7) = strcmp(ME.identifier, 'CHEBFUN:CHEBFUN:svd:twoArgs');
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function im_warp = warpImageFast(im,XXdense, YYdense)

%{
Citation:
J. Xiao, K. A. Ehinger, A. Oliva and A. Torralba.
Recognizing Scene Viewpoint using Panoramic Place Representation.
Proceedings of 25th IEEE Conference on Computer Vision and Pattern Recognition, 2012.
http://sun360.mit.edu
%}

minX = max(1,floor(min(min(XXdense)))-1);
minY = max(1,floor(min(min(YYdense)))-1);

maxX = min(size(im,2),ceil(max(max(XXdense)))+1);
maxY = min(size(im,1),ceil(max(max(YYdense)))+1);

im = im(minY:maxY,minX:maxX,:);

for c=1:size(im,3)
    % im_warp(:,:,c) = uint8(interp2(double(im(:,:,c)), XXdense-minX+1, YYdense-minY+1,'*cubic'));
    %im_warp(:,:,c) = interp2(im(:,:,c), XXdense-minX+1, YYdense-minY+1,'*cubic');
    im_warp(:,:,c) = interp2(im(:,:,c), XXdense-minX+1, YYdense-minY+1,'*linear');
%     im_warp(:,:,c) = interp2(im(:,:,c), XXdense-minX+1, YYdense-minY+1,'*nearest');
%     im_warp(:,:,c) = interp2(im(:,:,c), XXdense-minX+1, YYdense-minY+1,'linear');
end

author: zouchuhang

repo: LayoutNet


text:
function [ suborder_xyz, suborder_w ] = tetrahedron_ncc_subrule ( rule, suborder_num )

%*****************************************************************************80
%
%% TETRAHEDRON_NCC_SUBRULE returns a compressed NCC rule.
%
%  Discussion:
%
%    In order for these compressed rules to be "unwrapped" correctly,
%    it's necessary that the values in SUBORDER_XYZ_N be listed
%    in a particular order for each kind of symmetry.  Basically,
%    the repeated equal values must come first.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 January 2007
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Peter Silvester,
%    Symmetric Quadrature Formulae for Simplexes,
%    Mathematics of Computation,
%    Volume 24, Number 109, January 1970, pages 95-100.
%
%  Parameters:
%
%    Input, integer RULE, the index of the rule.
%
%    Input, integer SUBORDER_NUM, the number of suborders of the rule.
%
%    Output, real SUBORDER_XYZ(3,SUBORDER_NUM),
%    the barycentric coordinates of the abscissas.
%
%    Output, real SUBORDER_W(SUBORDER_NUM), the suborder weights.
%
  if ( rule == 1 )

    suborder_xyz_n(1:4,1:suborder_num) = [ ...
      1,  1, 1, 1 ]';

    suborder_xyz_d = 4;

    suborder_w_n(1:suborder_num) = [ 1 ];

    suborder_w_d = 1;

  elseif ( rule == 2 )

    suborder_xyz_n(1:4,1:suborder_num) = [ ...
      0, 0, 0, 1 ]';

    suborder_xyz_d = 1;

    suborder_w_n(1:suborder_num) = [ 1 ];

    suborder_w_d = 4;

  elseif ( rule == 3 )

    suborder_xyz_n(1:4,1:suborder_num) = [ ...
      0, 0, 0, 2; ...
      1, 1, 0, 0 ]';

    suborder_xyz_d = 2;

    suborder_w_n(1:suborder_num) = [ -1, 4 ];

     suborder_w_d = 20;

  elseif ( rule == 4 )

    suborder_xyz_n(1:4,1:suborder_num) = [ ...
      0, 0, 0, 3; ...
      0, 0, 1, 2; ...
      1, 1, 1, 0 ]';

    suborder_xyz_d = 3;

    suborder_w_n(1:suborder_num) = [ 1, 0, 9 ];

     suborder_w_d = 40;

  elseif ( rule == 5 )

    suborder_xyz_n(1:4,1:suborder_num) = [ ...
      0, 0, 0, 4; ...
      0, 0, 3, 1; ...
      2, 2, 0, 0; ...
      1, 1, 0, 2; ...
      1, 1, 1, 1 ]';

    suborder_xyz_d = 4;

    suborder_w_n(1:suborder_num) = [ -5, 16, -12, 16, 128 ];

     suborder_w_d = 420;

  elseif ( rule == 6 )

    suborder_xyz_n(1:4,1:suborder_num) = [ ...
      0, 0, 0, 5; ...
      0, 0, 4, 1; ...
      0, 0, 3, 2; ...
      1, 1, 0, 3; ...
      2, 2, 1, 0; ...
      1, 1, 1, 2  ]';

    suborder_xyz_d = 5;

    suborder_w_n(1:suborder_num) = [ 33, -35, 35, 275, -75, 375 ];

    suborder_w_d = 4032;

  elseif ( rule == 7 )

    suborder_xyz_n(1:4,1:suborder_num) = [ ...
      0, 0, 0, 6; ...
      0, 0, 5, 1; ...
      0, 0, 4, 2; ...
      1, 1, 0, 4; ...
      3, 3, 0, 0; ...
      3, 2, 1, 0; ...
      1, 1, 1, 3; ...
      2, 2, 2, 0; ...
      2, 2, 1, 1 ]';

    suborder_xyz_d = 6;

    suborder_w_n(1:suborder_num) = [ ...
      -7, 24, -30, 0, 40, 30, 180, -45, 0 ];

    suborder_w_d = 1400;

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'TETRAHEDRON_NCC_SUBRULE - Fatal error!\n' );
    fprintf ( 1, '  Illegal RULE = %d\n', rule );
    error ( 'TETRAHEDRON_NCC_SUBRULE - Fatal error!' )

  end

  suborder_xyz(1:4,1:suborder_num) = ...
    suborder_xyz_n(1:4,1:suborder_num) / suborder_xyz_d;

  suborder_w(1:suborder_num) = ...
    suborder_w_n(1:suborder_num) / suborder_w_d;

  return
end


text:
function varargout = GUI_2D_prestuptepla(varargin)

% Last Modified by GUIDE v2.5 06-Mar-2011 12:28:11

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @GUI_2D_prestuptepla_OpeningFcn, ...
                   'gui_OutputFcn',  @GUI_2D_prestuptepla_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before GUI_2D_prestuptepla is made visible.
function GUI_2D_prestuptepla_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to GUI_2D_prestuptepla (see VARARGIN)

% Choose default command line output for GUI_2D_prestuptepla
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes GUI_2D_prestuptepla wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = GUI_2D_prestuptepla_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in Run.
function Run_Callback(hObject, eventdata, handles)
clear global
clc

global tkon t

% inputs
ro=str2double(get(handles.hustota,'String'));
vod=str2double(get(handles.vodivost,'String'));
Cp=str2double(get(handles.kapacita,'String'));
T0=str2double(get(handles.T0,'String'));
TH=str2double(get(handles.TH,'String'));
TD=str2double(get(handles.TD,'String'));
TP=str2double(get(handles.TP,'String'));
TL=str2double(get(handles.TL,'String'));
L=str2double(get(handles.L,'String'));
M=str2double(get(handles.M,'String'));
N=str2double(get(handles.n,'String'));
tkon=str2double(get(handles.tkon,'String'));

% calculation ===================================================
a=vod/ro/Cp;
% length step
dx=L/(N-1);
% time step
dt=((dx)^2)/M/a;
t=dt;

% =======================================================
% inicialy temperatures
Tpoc=zeros(N,N);
for i=1:1:N
    for j=1:1:N
        Tpoc(i,j)=T0;
    end
end

while t<tkon

% ============================================================
j=1;
i=1;
Tpoc(i,j)=(Tpoc(i+1,j)+TL+TD+Tpoc(i,j+1)+(M-4)*Tpoc(i,j))/M;

j=N;
i=1;
Tpoc(i,j)=(Tpoc(i+1,j)+TD+Tpoc(i,j-1)+TP+(M-4)*Tpoc(i,j))/M;

j=1;
i=N;
Tpoc(i,j)=(TH+Tpoc(i-1,j)+TL+Tpoc(i,j+1)+(M-4)*Tpoc(i,j))/M;

j=N;
i=N;
Tpoc(i,j)=(TP+Tpoc(i-1,j)+Tpoc(i,j-1)+TP+(M-4)*Tpoc(i,j))/M;

% ==========================================================
i=1;
for j=2:1:N-1
Tpoc(i,j)=(Tpoc(i+1,j)+TD+Tpoc(i,j-1)+Tpoc(i,j+1)+(M-4)*Tpoc(i,j))/M;
end

i=N;
for j=2:1:N-1
    Tpoc(i,j)=(TH+Tpoc(i-1,j)+Tpoc(i,j-1)+Tpoc(i,j+1)+(M-4)*Tpoc(i,j))/M;
end
j=1;
for i=2:1:N-1
    Tpoc(i,j)=(Tpoc(i+1,j)+Tpoc(i-1,j)+TL+Tpoc(i,j+1)+(M-4)*Tpoc(i,j))/M;
end

j=N;
for i=2:1:N-1
    Tpoc(i,j)=(Tpoc(i+1,j)+Tpoc(i-1,j)+Tpoc(i,j-1)+TP+(M-4)*Tpoc(i,j))/M;
end

% ===========================================================
for i=2:1:N-1
    for j=2:1:N-1
        Tpoc(i,j)=(Tpoc(i+1,j)+Tpoc(i-1,j)+Tpoc(i,j-1)+Tpoc(i,j+1)+(M-4)*Tpoc(i,j))/M;
    end
end

% ===========================================================
% graph
pause(0.02)
%axes(handles.graf);
pcolor(Tpoc)
retazec=sprintf('Time=%g s',t);
title(retazec)
colorbar
shading interp

% --------
t=t+dt;
end

function hustota_Callback(hObject, eventdata, handles)
% hObject    handle to hustota (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of hustota as text
%        str2double(get(hObject,'String')) returns contents of hustota as a double

% --- Executes during object creation, after setting all properties.
function hustota_CreateFcn(hObject, eventdata, handles)
% hObject    handle to hustota (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function kapacita_Callback(hObject, eventdata, handles)
% hObject    handle to kapacita (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of kapacita as text
%        str2double(get(hObject,'String')) returns contents of kapacita as a double

% --- Executes during object creation, after setting all properties.
function kapacita_CreateFcn(hObject, eventdata, handles)
% hObject    handle to kapacita (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function vodivost_Callback(hObject, eventdata, handles)
% hObject    handle to vodivost (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of vodivost as text
%        str2double(get(hObject,'String')) returns contents of vodivost as a double

% --- Executes during object creation, after setting all properties.
function vodivost_CreateFcn(hObject, eventdata, handles)
% hObject    handle to vodivost (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function T0_Callback(hObject, eventdata, handles)
% hObject    handle to T0 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of T0 as text
%        str2double(get(hObject,'String')) returns contents of T0 as a double

% --- Executes during object creation, after setting all properties.
function T0_CreateFcn(hObject, eventdata, handles)
% hObject    handle to T0 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function TD_Callback(hObject, eventdata, handles)
% hObject    handle to TD (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of TD as text
%        str2double(get(hObject,'String')) returns contents of TD as a double

% --- Executes during object creation, after setting all properties.
function TD_CreateFcn(hObject, eventdata, handles)
% hObject    handle to TD (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function edit6_Callback(hObject, eventdata, handles)
% hObject    handle to edit6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit6 as text
%        str2double(get(hObject,'String')) returns contents of edit6 as a double

% --- Executes during object creation, after setting all properties.
function edit6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function TP_Callback(hObject, eventdata, handles)
% hObject    handle to TP (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of TP as text
%        str2double(get(hObject,'String')) returns contents of TP as a double

% --- Executes during object creation, after setting all properties.
function TP_CreateFcn(hObject, eventdata, handles)
% hObject    handle to TP (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function TL_Callback(hObject, eventdata, handles)
% hObject    handle to TL (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of TL as text
%        str2double(get(hObject,'String')) returns contents of TL as a double

% --- Executes during object creation, after setting all properties.
function TL_CreateFcn(hObject, eventdata, handles)
% hObject    handle to TL (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function TH_Callback(hObject, eventdata, handles)
% hObject    handle to TH (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of TH as text
%        str2double(get(hObject,'String')) returns contents of TH as a double

% --- Executes during object creation, after setting all properties.
function TH_CreateFcn(hObject, eventdata, handles)
% hObject    handle to TH (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function M_Callback(hObject, eventdata, handles)
% hObject    handle to M (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of M as text
%        str2double(get(hObject,'String')) returns contents of M as a double

% --- Executes during object creation, after setting all properties.
function M_CreateFcn(hObject, eventdata, handles)
% hObject    handle to M (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function n_Callback(hObject, eventdata, handles)
% hObject    handle to n (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of n as text
%        str2double(get(hObject,'String')) returns contents of n as a double

% --- Executes during object creation, after setting all properties.
function n_CreateFcn(hObject, eventdata, handles)
% hObject    handle to n (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function L_Callback(hObject, eventdata, handles)
% hObject    handle to L (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of L as text
%        str2double(get(hObject,'String')) returns contents of L as a double

% --- Executes during object creation, after setting all properties.
function L_CreateFcn(hObject, eventdata, handles)
% hObject    handle to L (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function tkon_Callback(hObject, eventdata, handles)
% hObject    handle to tkon (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of tkon as text
%        str2double(get(hObject,'String')) returns contents of tkon as a double

% --- Executes during object creation, after setting all properties.
function tkon_CreateFcn(hObject, eventdata, handles)
% hObject    handle to tkon (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global t tkon
t=tkon;
pause(0.02)
clc


text:
filename='Cantilever_quad_fine';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance';'perimeter'};
weights = [1, 0.1];
constraint = {'volumeConstraint'};
optimizer = 'MMA';
incrementFactor = 1;
designVariable = 'Density';
filterType = 'P1';

nsteps = 5;
Vfrac_final = 0.4;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

Vfrac_initial = 1;
optimality_initial = 1e-2;
constr_initial = 1e-3;
TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function [xi,w]=firstOrder3DCubPoints()
%%FIRSTORDER3DCUBPOINTS Generate first-order cubature points
%               for integration over a 3-dimensional cube with vertices of
%               (1,-1,-1), (-1,-1,-1), (-1,1,-1), (1,1,-1), (1,-1,1),
%               (-1,-1,1), (-1,1,1), and (1,1,1).
%
%INPUTS: None
%
%OUTPUTS: xi This is a 3XnumCubPoints set of points for the standard
%            cube.
%          w A 1XnumCubPoints set of cubature weights. This sums to the
%            volume of the standard cube (8).
%
%This function implements the points given in [1] (1 point). This point is
%just the origin with a weight of 8.
%
%REFERENCES:
%[1] F. D. Witherden and P. E. Vincent, "On the identification of symmetric
%    quadrature rules for finite element methods," Computer and Mathematics
%    with Applications, vol. 69, no. 10, pp. 1232-1241, May 2015.
%
%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

w=8;
xi=[0;0;0];

end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
function chebyshev1_compute_test ( )

%*****************************************************************************80
%
%% CHEBYSHEV1_COMPUTE_TEST tests CHEBYSHEV1_COMPUTE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 April 2015
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CHEBYSHEV1_COMPUTE_TEST\n' );
  fprintf ( 1, '  CHEBYSHEV1_COMPUTE computes\n' );
  fprintf ( 1, '  a Chebyshev Type 1 quadrature rule over [-1,1]\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Index       X             W\n' );
  fprintf ( 1, '\n' );

  for n = 1 : 10

    [ x, w ] = chebyshev1_compute ( n );

    fprintf ( 1, '\n' );

    for i = 1 : n
      fprintf ( 1, '  %2d  %12g  %12g\n', i, x(i), w(i) );
    end

  end

  return
end

author: johannesgerer


text:
function vis_multicut2(det,pidxs,parts)

colors = {'r','g','b','c','m','y'};
markers = {'+','o','s'}; %,'x','.','-','s','d'

for j = 1:length(det)
    labels = cell(0);
    n = 0;
    points = zeros(1,2);
    for i = 1:length(pidxs)
        pidx = pidxs(i);
        jidx = parts(pidx+1).pos(1);
        pp = det{jidx+1};
        if (~isempty(pp))
            n = n  + 1;
            labels{n} = num2str(i);
            %                     labels{n} = sprintf('%1.2f',pp(3));
            points(n,:) = pp(1:2);
        end
    end
    lp = 1;
    if (lp <= 5)
        m = markers{1};
    elseif (lp > 5 && lp <= 11)
        m = markers{2};
    else
        m = markers{3};
    end
    plot(points(:,1),points(:,2),[colors{mod(lp,6)+1} m],'MarkerSize',5);
    text(points(:,1)+10,points(:,2),labels,'FontSize',6,'BackgroundColor','w');
    axis off;
end

end

author: eldar

repo: deepcut

save_path: github-repos/MATLAB/eldar-deepcut


text:
function m=min2(u)

if ndims(u) > 2
   error('Input image must be grayscale.')
   return
end
if strcmp(class(u),'double')
   y = u;
else
   y = double(u);
end

m=min(min(u));


text:
% Chapter 5: Duality
%
%  qcqp.m            - Section 5.2.4: Solves a simple QCQP
%  matrix_games.m    - Section 5.2.5: Mixed strategies for matrix games
%  matrix_games_LP.m - Section 5.2.5: Mixed strategies for matrix games (LP formulation)
%  norm_approx.m     - Examples 5.6,5.8: An l_p norm approximation problem
%  ex_5_19.m         - Exercise 5.19c: Markovitz portfolio optimization w/ diversification constraint
%  ex_5_1.m          - Exercise 5.1d: Sensitivity analysis for a simple QCQP
%  ex_5_33.m         - Exercise 5.33: Parametrized l1-norm approximation
%  ex_5_39.m         - Exercise 5.39: SDP relaxations of the two-way partitioning problem
help Contents

author: cvxr

repo: CVX

save_path: github-repos/MATLAB/cvxr-CVX