text:
function filt = filter_with_correction(B,A,dat,dir,usefftfilt)

% FILTER_WITH_CORRECTION applies the filter to the data and corrects
% edge-artifacts for one-pass filtering.
%
% Use as
%   [filt] = filter_with_correction(B,A,dat,dir);
% where
%   B,A        filter coefficients
%   dat        data matrix (Nchans X Ntime)
%   dir        optional filter direction, can be
%                'onepass'                   forward filter only
%                'onepass-reverse'           reverse filter only, i.e. backward in time
%                'twopass'                   zero-phase forward and reverse filter (default)
%                'twopass-reverse'           zero-phase reverse and forward filter
%                'twopass-average'           average of the twopass and the twopass-reverse
%                'onepass-zerophase'         zero-phase forward filter with delay compensation (default for firws, linear-phase symmetric FIR only)
%                'onepass-reverse-zerophase' zero-phase reverse filter with delay compensation
%                'onepass-minphase'          minimum-phase converted forward filter (non-linear!, firws only)
%
% Note that a one- or two-pass filter has consequences for the
% strength of the filter, i.e. a two-pass filter with the same filter
% order will attenuate the signal twice as strong.

% Copyright (c) 2010, Stefan Klanke
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% convert the data to double precision
% see  http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2653
inputclass = class(dat);
B = double(B);
A = double(A);
dat = double(dat);

poles = roots(A);
if any(abs(poles) >= 1)
  ft_error('Calculated filter coefficients have poles on or outside the unit circle and will not be stable. Try a higher cutoff frequency or a different type/order of filter.');
end

dcGain = sum(B)/sum(A);

[nchan,nsample] = size(dat);

switch dir
  case 'onepass'
    offset = dat(:,1);
    dat = dat - repmat(offset,1,nsample);
    filt = filter(B, A, dat')' + repmat(dcGain*offset, 1, nsample);
  case 'onepass-reverse'
    offset = dat(:,end);
    dat  = fliplr(dat) - repmat(offset,1,nsample);
    filt = filter(B, A, dat')';
    filt = fliplr(filt) + repmat(dcGain*offset, 1, nsample);
  case 'twopass'
    % filtfilt does the correction for us
    filt = filtfilt(B, A, dat')';
  case 'twopass-reverse'
    % filtfilt does the correction for us
    filt = fliplr(filtfilt(B, A, fliplr(dat)')');
  case 'twopass-average'
    % take the average from the twopass and the twopass-reverse
    filt1 = filtfilt(B, A, dat')';
    filt2 = fliplr(filtfilt(B, A, fliplr(dat)')');
    filt  = (filt1 + filt2)/2;
  case 'onepass-zerophase'
    filt = fir_filterdcpadded(B, A, dat', 0, usefftfilt)';
  case 'onepass-reverse-zerophase'
    filt = fliplr(fir_filterdcpadded(B, A, fliplr(dat)', 0, usefftfilt)');
  case 'onepass-minphase'
    filt = fir_filterdcpadded(B, A, dat', 1, usefftfilt)';
  otherwise
    ft_error('unsupported filter direction "%s"', dir);
end

% cast it back into the type of the input data, which can e.g. be single or int32
filt = cast(filt, inputclass);


text:
% MRC_scheme.m
% Receiver diversity - MRC
clear, clf
L_frame=130;
N_packet=4000;
b=2;                % Set to 1/2/3/4 for BPSK/QPSK/16QAM/64QAM
SNRdBs=[0:2:20];
sq2=sqrt(2);
%SNRdBs=[0:10:20]; sq2=sqrt(2);
for iter=1:3
   if iter==1
       NT=1;
       NR=1;
       gs='-kx'; % SISO
    elseif iter==2
        NT=1;
        NR=2;
        gs='-^';
   else
       NT=1;
       NR=4;
       gs='-ro';
   end
   sq_NT=sqrt(NT);
   for i_SNR=1:length(SNRdBs)
      SNRdB=SNRdBs(i_SNR);
      sigma=sqrt(0.5/(10^(SNRdB/10)));
      for i_packet=1:N_packet
         symbol_data=randi([0,1],L_frame*b,NT);
         [temp,sym_tab,P]=modulator(symbol_data.',b);
         X=temp.';
         Hr = (randn(L_frame,NR)+j*randn(L_frame,NR))/sq2;
         H = reshape(Hr,L_frame,NR);
         Habs = sum(abs(H).^2,2);
         Z=0;
         for i=1:NR
            R(:,i) = sum(H(:,i).*X,2)/sq_NT + sigma*(randn(L_frame,1)+j*randn(L_frame,1));
            Z = Z + R(:,i).*conj(H(:,i));
         end
         for m=1:P
            d1(:,m)=abs(sum(Z,2)-sym_tab(m)).^2+(-1+sum(Habs,2))*abs(sym_tab(m))^2;
         end
         [y1,i1] = min(d1,[],2);
         Xd=sym_tab(i1).';
         temp1 = X>0;
         temp2 = Xd>0;
         noeb_p(i_packet)=sum(sum(temp1~=temp2));
      end
      BER(iter,i_SNR) = sum(noeb_p)/(N_packet*L_frame*b);
   end
   semilogy(SNRdBs,BER(iter,:),gs);
   hold on;
   axis([SNRdBs([1 end]) 1e-6 1e0])
end
title('BER perfoemancde of MRC Scheme');
xlabel('SNR[dB]');
ylabel('BER')
grid on;
set(gca,'fontsize',9)
legend('SISO','MRC (Tx:1,Rx:2)','MRC (Tx:1,Rx:4)')

author: LyricYang


% Given time domain samples, extracts out each of the OFDM symbols minus their cyclic prefixes for both time and
% frequency domains.  First sample must be the exact start of the burst!
%
% @param samples Time domain samples as a row/column vector
function [time_domain, freq_domain] = extract_ofdm_symbol_samples(samples, sample_rate)
    assert(isrow(samples) || iscolumn(samples), "Samples must be a row or column vector");

    fft_size = get_fft_size(sample_rate);
    [long_cp_len, short_cp_len] = get_cyclic_prefix_lengths(sample_rate);

    % List of cyclic prefix lengths for each OFDM symbol
    cp_lengths = [
        long_cp_len,...
        short_cp_len,...
        short_cp_len,...
        short_cp_len,...
        short_cp_len,...
        short_cp_len,...
        short_cp_len,...
        short_cp_len,...
        long_cp_len...
    ];

    freq_domain = zeros(length(cp_lengths), fft_size);
    time_domain = zeros(length(cp_lengths), fft_size);

    sample_offset = 1;
    for idx=1:length(cp_lengths)
        % Skip the cyclic prefix
        symbol = samples(sample_offset:sample_offset + fft_size + cp_lengths(idx) - 1);
        symbol = symbol(cp_lengths(idx) + 1:end);

        % Extract the time domain samples for this OFDM symbol
        time_domain(idx,:) = symbol;

        % Convert the time domain samples into frequency domain
        freq_domain(idx,:) = fftshift(fft(time_domain(idx,:)));

        sample_offset = sample_offset + fft_size + cp_lengths(idx);
    end
end


text:
% gener_mcardat

%%Jouet 1
N=5;
dag=zeros(N);
dag(1,2)=1;
dag(2,[3 4])=1;
dag(4,5)=1;
node_sizes= [2 3 4 5 2]; ns = node_sizes;
bnet = mk_bnet(dag, node_sizes);
bnet.CPD{1} = tabular_CPD(bnet, 1, [0.2 0.8]);
bnet.CPD{2} = tabular_CPD(bnet, 2, [0.1 0.6 0.3 0.9 0.4 0.7]);
bnet.CPD{3} = tabular_CPD(bnet, 3, [0.3 0.5 0.7 0.2   0.2 0.1 0.05 0.5   0.5 0.4 0.25 0.3]);
bnet.CPD{4} = tabular_CPD(bnet, 4, [0.35 0.05 0.65 0.15 0.25  0.15 0.15 0.10 0.25 0.45  0.5 0.8 0.25 0.6 0.3]);
bnet.CPD{5} = tabular_CPD(bnet, 5, [0.25 0.15  0.15 0.25  0.10 0.15  0.2 0.05  0.3 0.4]);
bnet_orig=bnet

base_proba=0.2;

%%%%%%%% MCAR

bnet_miss = gener_MCAR_net(bnet_orig, base_proba);

carre=zeros(1,3*N);
names={'X1','X2','X3','X4','X5','R1','R2','R3','R4','R5','M1','M2','M3','M4','M5'};
xx=[.1,.3,.5,.7,.9,.05,.25,.45,.65,.85,.15,.35,.55,.75,.95];
yy=[.85,.70,.90,.75,.80,.65,.40,.60,.45,.50,.2,.2,.2,.2,.2];
figure;draw_graph(bnet_miss.dag,names,carre,xx,yy)

[data, comp_data, bnet_miss, taux, bnet_orig, notok] = gener_data_from_bnet_miss(bnet_miss, 500, base_proba ,0,0);

OK = ~notok

%%%%%%%% MAR

bnet_miss = gener_MAR_net(bnet_orig, base_proba);

carre=zeros(1,3*N);
names={'X1','X2','X3','X4','X5','R1','R2','R3','R4','R5','M1','M2','M3','M4','M5'};
xx=[.1,.3,.5,.7,.9,.05,.25,.45,.65,.85,.15,.35,.55,.75,.95];
yy=[.85,.70,.90,.75,.80,.65,.40,.60,.45,.50,.2,.2,.2,.2,.2];
figure;draw_graph(bnet_miss.dag,names,carre,xx,yy)

[data, comp_data, bnet_miss, taux, bnet_orig, notok] = gener_data_from_bnet_miss(bnet_miss, 500, base_proba ,0,0);

OK = ~notok

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function value = i4_log_2 ( i )

%*****************************************************************************80
%
%% I4_LOG_2 returns the integer part of the logarithm base 2 of |I|.
%
%  Discussion:
%
%    For positive I4_LOG_2(I), it should be true that
%      2**I4_LOG_2(X) <= |I| < 2**(I4_LOG_2(I)+1).
%    The special case of I4_LOG_2(0) returns -HUGE().
%
%  Example:
%
%     I  Value
%
%     0  -1
%     1,  0
%     2,  1
%     3,  1
%     4,  2
%     5,  2
%     6,  2
%     7,  2
%     8,  3
%     9,  3
%    10,  3
%   127,  6
%   128,  7
%   129,  7
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 April 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer I, the number whose logarithm base 2 is desired.
%
%    Output, integer VALUE, the integer part of the logarithm base 2 of
%    the absolute value of I.
%
  i = floor ( i );

  if ( i == 0 )

    value = -inf;

  else

    value = 0;

    i = abs ( i );

    while ( 2 <= i )
      i = i / 2;
      value = value + 1;
    end

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [ s, r, l ] = r8_mant ( x )

%*****************************************************************************80
%
%% R8_MANT computes the "mantissa" or "fraction part" of X.
%
%  Formula:
%
%    X = S * R * 2^L
%
%    S is +1 or -1,
%    R is a real value between 1.0 and 2.0,
%    L is an integer.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 April 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the number to be decomposed.
%
%    Output, integer S, the "sign" of the number.
%    S will be -1 if X is less than 0, and +1 if X is greater
%    than or equal to zero.
%
%    Output, real R, the mantissa of X.  R will be greater
%    than or equal to 1, and strictly less than 2.  The one
%    exception occurs if X is zero, in which case R will also
%    be zero.
%
%    Output, integer L, the integer part of the logarithm (base 2) of X.
%

%
%  Determine the sign.
%
  if ( x < 0.0 )
    s = -1;
  else
    s = 1;
  end
%
%  Set R to the absolute value of X, and L to zero.
%  Then force R to lie between 1 and 2.
%
  if ( x < 0.0 )
    r = -x;
  else
    r = x;
  end

  l = 0;
%
%  Time to bail out if X is zero.
%
  if ( x == 0.0 )
    return
  end

  while ( 2.0 <= r )
    r = r / 2.0;
    l = l + 1;
  end

  while ( r < 1.0 )
    r = r * 2.0;
    l = l - 1;
  end

  return
end


text:
function data_list = read_off_list(data_path, classes, train_or_test, debug)
% read raw off filenames

% data_path: off data folder
% classes: a cell array of class names
% train_or_test: select training data or testing data('train', 'test')
% debug: true for debug.

if nargin < 4 ; debug = 0; end

if debug
    maxNum = 20;
else
    maxNum = 10000;
end

num_classes = length(classes);
data_list = cell(num_classes,1);
for c = 1 : num_classes
    fprintf('reading the %s category\n', classes{c});
    category_path = [data_path '/' classes{c}  '/off/' train_or_test];
    files = dir(category_path);

    cat_ind = 0;
    data_list{c} = [];
    for i = 1 : min(length(files), maxNum)
        if strcmp(files(i).name, '.') || strcmp(files(i).name, '..') || files(i).isdir == 1 || ~strcmp(files(i).name(end-2:end), 'off')
            continue;
        end
        filename = [category_path '/' files(i).name];

        cat_ind = cat_ind + 1;
        data_list{c}(cat_ind,1).filename = filename;
        data_list{c}(cat_ind,1).label = c;

        if cat_ind == maxNum; break; end
    end
end

author: zhirongw


text:
function gf=gradmaxdiagnoExp(x,varargin)
% Maximizaton of the diagonality of hte matrix.
covmat = varargin{1};   % #pix X #pix X #taus
% sizevec = varargin{2};
sizevec = [size(covmat,1), length(x)/size(covmat,1)];
W = pinv(exp(reshape(x, sizevec(1), sizevec(2))))';
ntau = size(covmat,3); % #taus (different time delays)
gftmp = zeros(ntau,prod(sizevec));
for tau=1:ntau
    C = covmat(:,:,tau);
    P = W'*C*W;
    Q = diag(1./diag(P));
    R = inv(P);
%     gfr = (Q'*W' - (W*R)')*0.5*(C+C');
    gfr = Q'*W'*0.5*(C+C') - 0.5*((C*W*R)'+R*W'*C);
    gftmp(tau,:) = reshape(gfr',1,prod(sizevec));
end

% gf1 = sum(gftmp,1).*exp(x);
gf1 = sum(gftmp,1);
gf1r = reshape(gf1,sizevec(1), sizevec(2));

% gf2 = -gf1r.*(pinv(W)*exp(reshape(x, sizevec(1)*sizevec(2), sizevec(3)))*pinv(W))';
% gf2 = -(W'*pinv(gf1r)*W');
% gf2 = -(W*pinv(gf1r)*W);
% gf2 = -gf1r.*W;
% S pinv(W) to nejak nefunguje...
gf2 = -gf1r.*W;

gf=reshape(gf2,1,prod(sizevec));

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
%kgbindtexture 'Assign a Texture to a Geometry Object'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros gbindtexture.pane file
%
% Parameters:
% InputFile: i 'Input Geometry Object ', required: 'input geometry object'
% InputFile: i2 'Input Texture Object ', required: 'texture object to be bound'
% OutputFile: o 'Output Geometry Object', required: 'output geometry object with bound texture'
%
% Example: o = kgbindtexture({i, i2}, {'i','';'i2','';'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% gbindtexture - Assign a Texture to a Geometry Object
%
%  DESCRIPTION
% .I gbindtexture
% This module "binds" a texture to an object.  The rendered object
% will then be rendered such as to have the texture "draped" over it's
% surface, in the case of 2d textures.  Texture binding is necessary
% before the renderer will do the texture mapping.  A single texture
% may be bound to multiple objects, but a given object may have only
% one texture bound to it.
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
% gcreate2dtex
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1996,1997 , The Regents of the University of California.  All rights reserved.
%

function varargout = kgbindtexture(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kgbindtexture(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'i2', '__input';'o', '__output'};
maxval={0,0,0};
minval={0,0,0};
istoggle=[0,0,0];
was_set=istoggle * 0;
paramtype={'InputFile','InputFile','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'gbindtexture"  '],Inputs,narglist);


text:
%this class retrieves a preprocessing algorithm from the UI
classdef PreprocessingConfigurator < handle

    properties (Access = private)
        %data
        signalNames;

        %algorithms
        algorithms;
        currentAlgorithms;
        algorithmStrings;

        %ui
        signalsList;
        algorithmsList;
        algorithmVariablesTable;

        %state
        currentAlgorithmVariables;

        %observer
        delegate;
    end

    methods (Access = public)
        function obj = PreprocessingConfigurator(signalNames,algorithms, signalsList,...
                algorithmsList,algorithmVariablesTable,delegate)

            obj.signalNames = signalNames;
            obj.algorithms = algorithms;
            obj.signalsList = signalsList;
            obj.algorithmsList = algorithmsList;
            obj.algorithmVariablesTable = algorithmVariablesTable;
            obj.signalsList.ValueChangedFcn = @obj.handleSelectedSignalChanged;
            obj.algorithmsList.ValueChangedFcn = @obj.handleSelectedAlgorithmChanged;

            if nargin > 5
                obj.delegate = delegate;
            end

            if ~isempty(obj.algorithmsList)
                obj.updateSignalsList();
                obj.updateAlgorithmsList();
                obj.selectFirstAlgorithm();

                obj.updateSelectedAlgorithm();
                obj.updateAlgorithmVariablesTable();
            end
        end

        function setSignals(obj,signals)
            obj.signalNames = signals;
            obj.updateSignalsList();
        end

        function algorithm = getCurrentAlgorithm(obj)
            idxStr = obj.algorithmsList.Value;
            [~,idx] = ismember(idxStr,obj.algorithmsList.Items);
            if isempty(idx)
                algorithm = [];
            else
                algorithm = obj.currentAlgorithms{idx};
            end
        end

        function signalIdxs = getSelectedSignalIdxs(obj)
            idxStr = obj.signalsList.Value;
            [~,signalIdxs] = ismember(idxStr,obj.signalsList.Items);
        end

        function algorithm = createPreprocessingAlgorithmWithUIParameters(obj)
            axisSelector = obj.createAxisSelectorWithUIParameters();
            if isempty(axisSelector)
                algorithm = [];
            else
                algorithm = obj.createAlgorithmWithUIParameters();
                if isempty(algorithm)
                    algorithm = [];
                else
                    axisSelector.addNextAlgorithm(algorithm);
                    algorithm = CompositeAlgorithm(axisSelector,{algorithm});
                end
            end
        end

        function axisSelector = createAxisSelectorWithUIParameters(obj)
            selectedSignalIndices = obj.getSelectedSignalIdxs();
            if isempty(selectedSignalIndices)
                axisSelector = [];
            else
                axisSelector = AxisSelector();
                axisSelector.axes = selectedSignalIndices;
            end
        end

        function algorithm = createAlgorithmWithUIParameters(obj)
            algorithm = obj.getCurrentAlgorithm();
            if isa(algorithm,'NoOp')
                algorithm = [];
            elseif ~isempty(algorithm)
                algorithm = algorithm.copy();
                data = obj.algorithmVariablesTable.Data;
                for i = 1 : size(data,1)
                    variableName = data{i,1};
                    variableValue = data{i,2};
                    property = Property(variableName,variableValue);
                    algorithm.setProperty(property);
                end
            end
        end

    end

    methods (Access = private)

        %ui
        function updateSignalsList(obj)
            obj.signalsList.Items = obj.signalNames;
        end

        function signals = getSelectedSignals(obj)
            %returns signals in order
            [~, signalIndices] = ismember(obj.signalsList.Value,obj.signalsList.Items);
            signalIndices = sort(signalIndices);
            signals = obj.signalsList.Items(signalIndices);
        end

        function selectFirstAlgorithm(obj)
            if ~isempty(obj.algorithmsList.Items)
                obj.algorithmsList.Value = obj.algorithmsList.Items{1};
            end
        end

        function selectFirstSignal(obj)
            obj.signalsList.Value = obj.signalsList.Items{1};
        end

        function updateAlgorithmVariablesTable(obj)
            obj.algorithmVariablesTable.Data = Helper.PropertyArrayToCellArray(obj.currentAlgorithmVariables);
        end

        function updateSelectedAlgorithm(obj)
            algorithm = obj.getCurrentAlgorithm();
            if isempty(algorithm)
                obj.currentAlgorithmVariables = [];
            else
                obj.currentAlgorithmVariables = algorithm.getEditableProperties();
            end
        end

        %methods
        function updateAlgorithmsList(obj)
            nSelectedSignals = length(obj.signalsList.Value);
            switch nSelectedSignals
                case 1
                    obj.currentAlgorithms = Palette.FilterAlgorithmsToInputType(obj.algorithms, DataType.kSignal);
                case 2
                    obj.currentAlgorithms = Palette.FilterAlgorithmsToInputType(obj.algorithms, DataType.kSignal2);
                case 3
                    obj.currentAlgorithms = Palette.FilterAlgorithmsToInputType(obj.algorithms, DataType.kSignal3);
                otherwise
                    obj.currentAlgorithms = Palette.FilterAlgorithmsToInputType(obj.algorithms, DataType.kSignalN);
            end

            obj.algorithmsList.Items = Helper.GenerateAlgorithmNamesArray(obj.currentAlgorithms);
        end

        %% handles
        function handleSelectedSignalChanged(obj,~,~)
            obj.updateAlgorithmsList();
        end

        function handleSelectedAlgorithmChanged(obj,~,~)
            obj.updateSelectedAlgorithm();
            obj.updateAlgorithmVariablesTable();

            selectedAlgorithm = obj.getCurrentAlgorithm();
            if ~isempty(obj.delegate)
                obj.delegate.handlePreprocessingAlgorithmChanged(selectedAlgorithm,obj);
            end
        end
    end
end

author: avenix

repo: WDK

save_path: github-repos/MATLAB/avenix-WDK


text:
function coords = indices2Coords(indices,dims)
%
% coords = indices2Coords(indices,dims)
%
% AUTHOR:  Boynton
% PURPOSE: (Author: Wandell)
%   Well, the comments are pretty hard to figure out and the code ain't
% that easy either.  But I think that this routine suppose that there is
% an array, say X, with dims = size(X).
% Then, if we address the array via X(indices), this routine
% tells us which of the array coordinates, in the form (x1, x2 ... xNdims),
% where Ndims = length(dims), correspond to the list of values in indices.
% This is quite what it says below (the original comments).  But I think
% it does this.
%
% indices: 1xN vector that can be used to pick off the indexed
%   values of an array with dimensions dims.
%
% dims: size of each dimension.  E.g., dims=[100,200,8] means
%   that the 1st row of the returned values, coords,
%   takes on values between 1:100,
%   2nd row between 1:200, 3rd row between 1:8.
%
% coords: MxN array of coordinates, M is the dimensionality. (I think this
%   means that M is length(dims)).
%   e.g., coords might be 3x100 with y,x,z values in each
%   column.
%   And he doesn't say, but I think that N is the number of indices.
%
% gmb, 1/23/98

% Why is this a find?  Does he mean to check whether indices is empty?
if find(indices)

   % Force indices to be a row vector
   indices = indices(:)';

   % Allocates an array to store the coords that will be returned
   coords = zeros([length(dims),length(indices)]);

   % Create the array coords using a Boyntonesque formula
   for d = length(dims):-1:1
      coords(d,:) = floor((indices-1) / prod(dims(1:d-1))) + 1;
      indices = indices - (coords(d,:)-1)*prod(dims(1:d-1));
   end

else
   coords = [];
end

return;

%%% Debug

dims=[10];
coords = [1:10];
indices=coords2Indices(coords,dims)
coords=indices2Coords(indices,dims)

dims=[3 3];
coords = [1 2 3;
          1 2 3];
indices=coords2Indices(coords,dims)
coords=indices2Coords(indices,dims)

dims=[3 3 3];
coords = [1 2 3 1 2 3;
          1 2 3 1 2 3;
	  1 1 1 3 3 3];
indices=coords2Indices(coords,dims)
coords=indices2Coords(indices,dims)

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
classdef PatternSearchOptimizer < AbstractOptimizer
    %PatternSearchOptimizer Summary of this class goes here
    %   Detailed explanation goes here

    properties
        options(1,1) PatternSearchOptions = PatternSearchOptions();
    end

    methods
        function obj = PatternSearchOptimizer()
            obj.options = PatternSearchOptions();
        end

        function [exitflag, message] = optimize(obj, lvdOpt, writeOutput, callOutputFcn, hLvdMainGUI)
            [x0All, actVars, varNameStrs] = lvdOpt.vars.getTotalScaledXVector();
            [lbAll, ubAll, lbUsAll, ubUsAll] = lvdOpt.vars.getTotalScaledBndsVector();
%             typicalX = lvdOpt.vars.getTypicalScaledXVector();

            if(isempty(x0All) && isempty(actVars))
                exitflag = 0;
                message = 'No variables enabled on script.  Aborting optimization.';

                return;
            end

            evtNumToStartScriptExecAt = obj.getEvtNumToStartScriptExecAt(lvdOpt, actVars);
            evtToStartScriptExecAt = lvdOpt.lvdData.script.getEventForInd(evtNumToStartScriptExecAt);

            objFuncWrapper = @(x) lvdOpt.objFcn.evalObjFcn(x, evtToStartScriptExecAt);
            nonlcon = @(x) lvdOpt.constraints.evalConstraints(x, true, evtToStartScriptExecAt, true, []);

%             initMeshSize = norm(typicalX)/(10*length(typicalX));
            opts = obj.options.getOptionsForOptimizer(x0All);
%             opts = optimoptions(opts, 'ScaleMesh',scaleMesh, 'UseParallel',usePara, 'InitialMeshSize',initMeshSize);

            problem.objective = objFuncWrapper;
            problem.x0 = x0All;
            problem.Aineq = [];
            problem.bineq = [];
            problem.Aeq = [];
            problem.beq = [];
            problem.lb = lbAll;
            problem.ub = ubAll;
            problem.nonlcon = nonlcon;
            problem.options = opts;
            problem.solver = 'patternsearch';

            problem.lvdData = lvdOpt.lvdData; %need to get lvdData in somehow

            %%% Run optimizer
            celBodyData = lvdOpt.lvdData.celBodyData;
            recorder = ma_OptimRecorder();

            if(callOutputFcn)
                propNames = lvdOpt.lvdData.launchVehicle.tankTypes.getFirstThreeTypesCellArr();
%                 handlesObsOptimGui = ma_ObserveOptimGUI(celBodyData, problem, true, writeOutput, [], varNameStrs, lbUsAll, ubUsAll);

                out = AppDesignerGUIOutput();
                ma_ObserveOptimGUI_App(out);
                handlesObsOptimGui = out.output{1};

                hOptimStatusLabel = handlesObsOptimGui.optimStatusLabel;
                hFinalStateOptimLabel = handlesObsOptimGui.finalStateOptimLabel;
                hDispAxes = handlesObsOptimGui.dispAxesPanel;
                hCancelButton = handlesObsOptimGui.cancelButton;
                optimStartTic = tic();

                outputFnc = @(optimvalues,options,flag) PatternSearchOptimizer.getOutputFunction(optimvalues,options,flag, hOptimStatusLabel, hFinalStateOptimLabel, hDispAxes, hCancelButton, ...
                                                                                problem.objective, problem.lb, problem.ub, celBodyData, recorder, propNames, writeOutput, varNameStrs, lbUsAll, ubUsAll, optimStartTic);
                problem.options.OutputFcn = outputFnc;
            end

            [exitflag, message] = lvd_executeOptimProblem(celBodyData, writeOutput, problem, recorder, callOutputFcn);

            if(callOutputFcn)
                close(handlesObsOptimGui.ma_ObserveOptimGUI);
            end
        end

        function options = getOptions(obj)
            options = obj.options;
        end

        function tf = usesParallel(obj)
            tf = obj.options.useParallel.optionVal;
        end

        function numWorkers = getNumParaWorkers(obj)
            numWorkers = obj.options.getNumParaWorkers();
        end

        function openOptionsDialog(obj)
%             lvd_editPatternSearchOptionsGUI(obj);

            output = AppDesignerGUIOutput({false});
            lvd_editPatternSearchOptionsGUI_App(obj, output);
        end
    end

    methods(Static, Access=private)
        function [stop,options,optchanged] = getOutputFunction(optimValues,options,flag, hOptimStatusLabel, hFinalStateOptimLabel, hDispAxes, hCancelButton, ...
                                                               objFcn, lb, ub, celBodyData, recorder, propNames, writeOutput, varLabels, lbUsAll, ubUsAll, optimStartTic)

            optchanged = false;
            x = optimValues.x;
            maxConstr = PatternSearchOptimizer.getConstrViolation(optimValues);

            switch flag
                case 'iter'
                    stop = get(hCancelButton,'Value');

                    recorder.iterNums(end+1) = optimValues.iteration;
                    recorder.xVals(end+1) = {x};
                    recorder.fVals(end+1) = optimValues.fval;
                    recorder.maxCVal(end+1) = maxConstr;
                case {'init','interrupt','done'}
                    stop = get(hCancelButton,'Value');
            end

            if(stop == true)
                return;
            end

            [~, stateLog] = objFcn(x);

%             finalStateLogEntry = stateLog.getFinalStateLogEntry();
%             finalStateLogEntryMA = finalStateLogEntry.getMAFormattedStateLogMatrix(true);

            stateLogMA = stateLog.getMAFormattedStateLogMatrix(true);

            if(strcmpi(flag,'init') || strcmpi(flag,'iter'))
                PatternSearchOptimizer.writeOptimStatus(hOptimStatusLabel, optimValues, flag, writeOutput, optimStartTic);
                ma_UpdateStateReadout(hFinalStateOptimLabel, 'final', propNames, stateLogMA, celBodyData);
                PatternSearchOptimizer.generatePlots(x, optimValues, flag, hDispAxes, lb, ub, varLabels, lbUsAll, ubUsAll);
                drawnow;
            end
        end

        function writeOptimStatus(hOptimStatusLabel, optimValues, flag, writeOutput, timer)
            elapTime = toc(timer);

            maxConstr = PatternSearchOptimizer.getConstrViolation(optimValues);

            if(length(optimValues.method) > 13)
                method = optimValues.method(1:13);
            else
                method = optimValues.method;
            end

            outStr = {};
            outStr{end+1} = ['State                = ', flag];
            outStr{end+1} = '                        ';
            outStr{end+1} = ['Iterations           = ', num2str(optimValues.iteration)];
            outStr{end+1} = ['Function Evals       = ', num2str(optimValues.funccount)];
            outStr{end+1} = ['Objective Value      = ', num2str(optimValues.fval)];
            outStr{end+1} = ['Constraint Violation = ', num2str(maxConstr)];
            outStr{end+1} = ['Method               = ', method];
            outStr{end+1} = ['Mesh Size            = ', num2str(optimValues.meshsize)];
            outStr{end+1} = '                       ';
            outStr{end+1} = ['Elapsed Time         = ', num2str(elapTime), ' sec'];

            set(hOptimStatusLabel, 'String', outStr);

            switch flag
                case 'iter'
                    formatstr = ' %- 12.1i %- 12.0i %- 12.6g %- 12.3g %- 13s %- 12.3g';

                    iter = optimValues.iteration;
                    fcnt = optimValues.funccount;
                    val  = optimValues.fval;
                    feas = maxConstr;
                    mesh = optimValues.meshsize;

                    hRow = sprintf(formatstr,iter,fcnt,val,feas,method,mesh);
                    writeOutput(hRow,'append');
                case 'init'
                    hdrStr = sprintf('%- 13s%- 13s%- 13s%- 13s%- 13s%- 13s', 'Iteration','Fcn-Count','f(x)-Value', 'Feasibility', 'Method', 'Mesh Size');
                    writeOutput(hdrStr,'append');
            end
        end

        function generatePlots(x, optimValues, flag, hDispAxes, lb, ub, varLabels, lbUsAll, ubUsAll)
            persistent fValPlotIsLog tLayout hPlot1 hPlot2 hPlot3

            if(isempty(fValPlotIsLog))
                fValPlotIsLog = true;
            end

            switch flag
                case 'init'
                    if(isvalid(hDispAxes))
%                         set(hDispAxes,'Visible','on');
%                         subplot(hDispAxes);
%                         axes(hDispAxes);
                        tLayout = tiledlayout(hDispAxes, 3,1);
                    end
                    fValPlotIsLog = true;
            end

            hPlot1 = nexttile(tLayout, 1);
            if(strcmpi(flag,'init'))

                hPlot1.XTickLabel= [];
                hPlot1.YTickLabel= [];
                hPlot1.ZTickLabel= [];
%                 axes(hPlot1);
            else
%                 axes(hPlot1);
            end
            optimplotxKsptot(x, optimValues, flag, lb, ub, varLabels, lbUsAll, ubUsAll);

            hPlot2 = nexttile(tLayout, 2);
            if(strcmpi(flag,'init'))
                hPlot2.XTickLabel= [];
                hPlot2.YTickLabel= [];
                hPlot2.ZTickLabel= [];
                h = hPlot2;
            else
                h = hPlot2;
%                 axes(hPlot2);
            end
            if(optimValues.fval<=0)
                fValPlotIsLog = false;
                set(h,'yscale','linear');
            end
            psplotbestf(optimValues, flag);
            if(fValPlotIsLog)
                set(h,'yscale','log');
            else
                set(h,'yscale','linear');
            end
            grid on;
            grid minor;

            hPlot3 = nexttile(tLayout, 3);
            if(strcmpi(flag,'init'))
                hPlot3.XTickLabel= [];
                hPlot3.YTickLabel= [];
                hPlot3.ZTickLabel= [];
                h = hPlot3;
            else
                h = hPlot3;
%                 axes(hPlot3);
            end
            psplotmaxconstr(optimValues, flag);

            if(not(isempty(h.Children)))
                hLine = h.Children(1);
                if(isa(hLine,'matlab.graphics.chart.primitive.Line'))
                    yDataLine = hLine.YData;
                    if(abs(max(yDataLine) / min(yDataLine)) >= 10 && all(yDataLine > 0))
                        set(h,'yscale','log');
                    else
                        set(h,'yscale','linear');
                    end
                else
                    set(h,'yscale','linear');
                end
            end

            grid on;
            grid minor;
        end

        function maxConstr = getConstrViolation(optimValues)
            if(not(isfield(optimValues,'nonlinineq')))
                optimValues.nonlinineq = [];
            end

            if(not(isfield(optimValues,'nonlineq')))
                optimValues.nonlineq = [];
            end

            maxConstr = max([max(abs(optimValues.nonlinineq)), max(abs(optimValues.nonlineq))]);

            if(isempty(maxConstr))
                maxConstr = 0;
            end
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function [ qa, qb, ival ] = box_segment_clip_2d ( p1, p2, pa, pb )

%*****************************************************************************80
%
%% BOX_SEGMENT_CLIP_2D uses a box to clip a line segment in 2D.
%
%  Discussion:
%
%    A box is assumed to be a rectangle with sides aligned on coordinate
%    axes.  It can be described by its low and high corner, P1 and P2:
%
%      points P so that P1(1:DIM_NUM) <= P(1:DIM_NUM) <= P2(1:DIM_NUM).
%
%    Thanks to Dennis Strelow for pointing out a typographical error,
%    13 July 2005.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 July 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real P1(2), P2(2), the low and high corners of the box.
%
%    Input, real PA(2), PB(2), the endpoints of the line segment.
%
%    Output, real QA(2), QB(2), the clipped coordinates.
%
%    Output, integer IVAL:
%    -1, no part of the line segment is within the box.
%     0, no clipping was necessary.  The line segment is entirely within
%     the box.
%     1, PA was clipped.
%     2, PB was clipped.
%     3, PA and PB were clipped.
%
  dim_num = 2;

  l1 = 0;
  l2 = 0;

  qa(1:dim_num) = pa(1:dim_num);
  qb(1:dim_num) = pb(1:dim_num);
%
%  Require that XMIN <= X.
%
  if ( qa(1) < p1(1) & qb(1) < p1(1) )
    ival = -1;
    return
  end

  if ( qa(1) < p1(1) & p1(1) <= qb(1) )
    q(1) = p1(1);
    q(2) = qa(2) + ( qb(2) - qa(2) ) * ( q(1) - qa(1) ) / ( qb(1) - qa(1) );
    qa(1:2) = q(1:2);
    l1 = 1;
  elseif ( p1(1) <= qa(1) & qb(1) < p1(1) )
    q(1) = p1(1);
    q(2) = qa(2) + ( qb(2) - qa(2) ) * ( q(1) - qa(1) ) / ( qb(1) - qa(1) );
    qb(1:2) = q(1:2);
    l2 = 1;
  end
%
%  Require that X <= XMAX.
%
  if ( p2(1) < qa(1) & p2(1) < qb(1) )
    ival = -1;
    return
  end

  if ( p2(1) < qa(1) & qb(1) <= p2(1) )
    q(1) = p2(1);
    q(2) = qa(2) + ( qb(2) - qa(2) ) * ( q(1) - qa(1) ) / ( qb(1) - qa(1) );
    qa(1:2) = q(1:2);
    l1 = 1;
  elseif ( qa(1) <= p2(1) & p2(1) < qb(1) )
    q(1) = p2(1);
    q(2) = qa(2) + ( qb(2) - qa(2) ) * ( q(1) - qa(1) ) / ( qb(1) - qa(1) );
    qb(1:2) = q(1:2);
    l2 = 1;
  end
%
%  Require that YMIN <= Y.
%
  if ( qa(2) < p1(2) & qb(2) < p1(2) )
    ival = -1;
    return
  end

  if ( qa(2) < p1(2) & p1(2) <= qb(2) )
    q(2) = p1(2);
    q(1) = qa(1) + ( qb(1) - qa(1) ) * ( q(2) - qa(2) ) / ( qb(2) - qa(2) );
    qa(1:2) = q(1:2);
    l1 = 1;
  elseif ( p1(2) <= qa(2) & qb(2) < p1(2) )
    q(2) = p1(2);
    q(1) = qa(1) + ( qb(1) - qa(1) ) * ( q(2) - qa(2) ) / ( qb(2) - qa(2) );
    qb(1:2) = q(1:2);
    l2 = 1;
  end
%
%  Require that Y <= YMAX.
%
  if ( p2(2) < qa(2) & p2(2) < qb(2) )
    ival = -1;
    return
  end

  if ( p2(2) < qa(2) & qb(2) <= p2(2) )
    q(2) = p2(2);
    q(1) = qa(1) + ( qb(1) - qa(1) ) * ( q(2) - qa(2) ) / ( qb(2) - qa(2) );
    qa(1:2) = q(1:2);
    l1 = 1;
  elseif ( qa(2) <= p2(2) & p2(2) < qb(2) )
    q(2) = p2(2);
    q(1) = qa(1) + ( qb(1) - qa(1) ) * ( q(2) - qa(2) ) / ( qb(2) - qa(2) );
    qb(1:2) = q(1:2);
    l2 = 1;
  end

  ival = 0;

  if ( l1 )
    ival = ival + 1;
  end

  if ( l2 )
    ival = ival + 2;
  end

  return
end


text:
function [suggestedParts, param] = suggestParts(D, objectname, param)

if nargin == 3
    Ppart = param.Ppart;
    objectClasses = param.objectClasses;
else
    [Ppart, objectClasses] = partsGraph(D);
    param.Ppart = Ppart;
    param.objectClasses = objectClasses;
end

j = strmatch(objectname, objectClasses, 'exact');

P = Ppart(j, :);
[p, jp] = sort(P, 'descend');

n = find(p>.2);
for i = 1:length(n)
    fprintf ('%s, ', objectClasses{jp(i)})
end

suggestedParts = objectClasses(n);

author: CSAILVision

repo: LabelMeToolbox


text:
% make results movies
function MakeCtraxResultsMovieWrapper(moviefile,trxfile,xvidfile,movietitle,ctraxresultsmovie_params)

%% ctrax movie parameters
defaulttempdatadir = '/groups/branson/bransonlab/projects/olympiad/TempData_FlyBowlMakeCtraxResultsMovie';
if ~isfield(ctraxresultsmovie_params,'tempdatadir'),
  ctraxresultsmovie_params.tempdatadir = defaulttempdatadir;
elseif isunix
  [status1,res] = unix(sprintf('echo %s',ctraxresultsmovie_params.tempdatadir));
  if status1 == 0,
    ctraxresultsmovie_params.tempdatadir = strtrim(res);
  end
end

if ~exist(ctraxresultsmovie_params.tempdatadir,'dir'),
  [success1,msg1] = mkdir(ctraxresultsmovie_params.tempdatadir);
  if ~success1,
    error('Error making directory %s: %s',ctraxresultsmovie_params.tempdatadir,msg1);
  end
end

%% location of data

[~,avifilestr,ext] = fileparts(xvidfile);
avifile = fullfile(ctraxresultsmovie_params.tempdatadir,[avifilestr,'_temp',ext]);

%% which frames

trx = load_tracks(trxfile);
start_frame = min([trx.firstframe]);
end_frame = max([trx.endframe]);
nframes = end_frame-start_frame + 1;
firstframes_off = min(max(0,round(ctraxresultsmovie_params.firstframes*nframes)),nframes-1);
firstframes_off(ctraxresultsmovie_params.firstframes < 0) = nan;
middleframes_off = round(ctraxresultsmovie_params.middleframes*nframes);
middleframes_off(ctraxresultsmovie_params.middleframes < 0) = nan;
endframes_off = round(ctraxresultsmovie_params.endframes*nframes);
endframes_off(ctraxresultsmovie_params.endframes < 0) = nan;
idx = ~isnan(middleframes_off);
firstframes_off(idx) = ...
  min(nframes-1,max(0,middleframes_off(idx) - ceil(ctraxresultsmovie_params.nframes(idx)/2)));
idx = ~isnan(endframes_off);
firstframes_off(idx) = ...
  min(nframes-1,max(0,endframes_off(idx) - ctraxresultsmovie_params.nframes(idx)));
endframes_off = firstframes_off + ctraxresultsmovie_params.nframes - 1;

firstframes = start_frame + firstframes_off;

%% option to not specify nzoomr, nzoomc

if ischar(ctraxresultsmovie_params.nzoomr) || ischar(ctraxresultsmovie_params.nzoomc),

  nflies = zeros(1,nframes);
  for i = 1:numel(trx),
    j0 = trx(i).firstframe-start_frame+1;
    j1 = trx(i).endframe-start_frame+1;
    nflies(j0:j1) = nflies(j0:j1)+1;
  end
  mediannflies = median(nflies);

  if isnumeric(ctraxresultsmovie_params.nzoomr),
    nzoomr = ctraxresultsmovie_params.nzoomr;
    nzoomc = round(mediannflies/nzoomr);
  elseif isnumeric(ctraxresultsmovie_params.nzoomc),
    nzoomc = ctraxresultsmovie_params.nzoomc;
    nzoomr = round(mediannflies/nzoomc);
  else
    nzoomr = ceil(sqrt(mediannflies));
    nzoomc = round(mediannflies/nzoomr);
  end
  ctraxresultsmovie_params.nzoomr = nzoomr;
  ctraxresultsmovie_params.nzoomc = nzoomc;

  if iscell(ctraxresultsmovie_params.figpos),
    [readframe,~,fid] = get_readframe_fcn(moviefile);
    im = readframe(1);
    [nr,nc,~] = size(im);

    rowszoom = floor(nr/nzoomr);
    imsize = [nr,nc+rowszoom*nzoomc];
    figpos = str2double(ctraxresultsmovie_params.figpos);
    if isnan(figpos(3)),
      figpos(3) = figpos(4)*imsize(2)/imsize(1);
    elseif isnan(figpos(4)),
      figpos(4) = figpos(3)*imsize(1)/imsize(2);
    end
    ctraxresultsmovie_params.figpos = figpos;

    if fid > 1,
      fclose(fid);
    end
  end

end

%% create movie

[succeeded,~,~,height,width]= ...
  make_ctrax_result_movie('moviename',moviefile,'trxname',trxfile,'aviname',avifile,...
  'nzoomr',ctraxresultsmovie_params.nzoomr,'nzoomc',ctraxresultsmovie_params.nzoomc,...
  'boxradius',ctraxresultsmovie_params.boxradius,'taillength',ctraxresultsmovie_params.taillength,...
  'fps',ctraxresultsmovie_params.fps,...
  'maxnframes',ctraxresultsmovie_params.nframes,...
  'firstframes',firstframes,...
  'figpos',ctraxresultsmovie_params.figpos,...
  'movietitle',movietitle,...
  'compression','none',...
  'useVideoWriter',false,...
  'titletext',false,...
  'avifileTempDataFile',[avifile,'-temp'],...
  'dynamicflyselection',true,...
  'doshowsex',true);

if ishandle(1),
  close(1);
end

if ~succeeded,
  error('Failed to create raw avi %s',avifile);
end

%% create subtitle file

subtitlefile = [tempname(ctraxresultsmovie_params.tempdatadir),'.srt'];
fid = fopen(subtitlefile,'w');
dt = [0,ctraxresultsmovie_params.nframes];
ts = cumsum(dt);
for i = 1:numel(dt)-1,
  fprintf(fid,'%d\n',i);
  fprintf(fid,'%s --> %s\n',...
    datestr(ts(i)/ctraxresultsmovie_params.fps/(3600*24),'HH:MM:SS,FFF'),...
    datestr((ts(i+1)-1)/ctraxresultsmovie_params.fps/(3600*24),'HH:MM:SS,FFF'));
  fprintf(fid,'%s, fr %d-%d\n\n',movietitle,...
    firstframes_off(i)+1,...
    endframes_off(i)+1);
end
fclose(fid);

%% compress

tmpfile = [xvidfile,'.tmp'];
newheight = 4*ceil(height/4);
newwidth = 4*ceil(width/4);
% subtitles are upside down, so encode with subtitles and flip, then flip
% again
cmd = sprintf('mencoder %s -o %s -ovc xvid -xvidencopts fixed_quant=4 -vf scale=%d:%d,flip -sub %s -subfont-text-scale 2 -msglevel all=2',...
  avifile,tmpfile,newwidth,newheight,subtitlefile);
status = system(cmd);
if status ~= 0,
  fprintf('*****\n');
  warning('Failed to compress avi to %s',xvidfile);
  fprintf('Need to run:\n');
  fprintf('%s\n',cmd);
  cmd2 = sprintf('mencoder %s -o %s -ovc xvid -xvidencopts fixed_quant=4 -vf flip -msglevel all=2',...
    tmpfile,xvidfile);
  fprintf('then\n');
  fprintf('%s\n',cmd2);
  fprintf('then delete %s %s %s\n',tmpfile,avifile,subtitlefile);
  fprintf('*****\n');
else
  cmd = sprintf('mencoder %s -o %s -ovc xvid -xvidencopts fixed_quant=4 -vf flip -msglevel all=2',...
    tmpfile,xvidfile);
  status = system(cmd);
  if status ~= 0,
    fprintf('*****\n');
    warning('Failed to add subtitles to %s',xvidfile);
    fprintf('Need to run:\n');
    fprintf('%s\n',cmd);
    fprintf('then delete %s %s %s\n',tmpfile,avifile,subtitlefile);
    fprintf('*****\n');
  else
    delete(tmpfile);
    delete(avifile);
    delete(subtitlefile);
  end
end

author: kristinbranson

repo: JAABA


text:
%$Release 4.0
% Copyright (c) Copyright 2004 - 2006 - The General Hospital Corporation and
% President and Fellows of Harvard University.
%
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% *       Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% *       Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
% *       Neither the name of The General Hospital Corporation and Harvard
% University nor the names of its contributors may be used to endorse or
% promote products derived from this software without specific prior written
% permission.
%
% The Software has been designed for research purposes only and has not been
% reviewed or approved by the Food and Drug Administration or by any other
% agency.  YOU ACKNOWLEDGE AND AGREE THAT CLINICAL APPLICATIONS ARE NEITHER
% RECOMMENDED NOR ADVISED.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.

% --------------------------------------------------------------------
function DisplayAxesSDG(handles)
global maingui
global UNIT_TEST

tic;

if ~exist('handles','var')
    handles = [];
end

% This function plots the probe geometry
% Command line call:
% plotAxes_SDG(guidata(gcbo),bool);
%
if isempty(handles)
    maingui.axesSDG = InitAxesSDG(handles);
end
hAxes        = maingui.axesSDG.handles.axes;
iCh          = maingui.axesSDG.iCh;
iSrcDet      = maingui.axesSDG.iSrcDet;
SDPairColors = maingui.axesSDG.SDPairColors;
iWl_gui      = GetWl(handles);

SD          = maingui.dataTree.currElem.GetSDG('2D');

if isfield(maingui.axesSDG, 'xlim')
    xbox        = maingui.axesSDG.xlim;
    ybox        = maingui.axesSDG.ylim;
    bbox        = [xbox(1), xbox(2), ybox(1), ybox(2)];
else
    bbox        = maingui.dataTree.currElem.GetSdgBbox();
end

% Set axes handle properties and parameters
if ~ishandles(hAxes)
    return;
end
if length(bbox)<4
    return;
end

% Set gca to be SDG axes
axes(hAxes);

% Delete all channel lines drawn
if ishandles(maingui.axesSDG.handles.ch) && (maingui.axesSDG.handles.axes == hAxes)
    delete(maingui.axesSDG.handles.ch)
    delete(findobj(hAxes, 'Type', 'line'))  % Prevents previously drawn lines from piling up
end
axis(hAxes, [bbox(1), bbox(2), bbox(3), bbox(4)]);

%set(hAxes, 'xticklabel','', 'yticklabel','', 'xgrid','off, ygrid','off')
set(hAxes, 'xticklabel','')
bttndownfcn = get(hAxes,'ButtonDownFcn');
gridsize = get(hAxes, {'xlim', 'ylim', 'zlim'});
edgecol = 'none';
if ismac() || islinux()
	fs = 18;
else
	fs = 11;
end

% Go through all the data blocks and plot the channels in each block
nSrcs       = size(SD.SrcPos,1);
nDets       = size(SD.DetPos,1);

% get mlActAuto from procResult if it exists and replace ch.MeasListActMan
nDataBlks = maingui.dataTree.currElem.GetDataBlocksNum();
MeasList = [];
MeasListActMan = [];
MeasListActAuto = [];
MeasListVis = [];
for iBlk = 1:nDataBlks
    ch              = maingui.dataTree.currElem.GetMeasList(iBlk);
    chVis           = maingui.dataTree.currElem.GetMeasListVis(iBlk);
    MeasList        = [MeasList; ch.MeasList];
    MeasListActMan  = [MeasListActMan; ch.MeasListActMan];
    MeasListActAuto = [MeasListActAuto; ch.MeasListActAuto];
    MeasListVis     = [MeasListVis; chVis];
end
ml    = MeasList(MeasList(:,1)>0,:);
lstSDPairs = find(ml(:,4)==iWl_gui); %cw6info.displayLambda);
lstInvisible = find(MeasListVis(:,3)==0);
hCh = zeros(length(lstSDPairs),1);

LINESTYLE_MAN_EXCL = ':';
LINESTYLE_AUTO_EXCL = '--';
LINESTYLE_MAN_AND_AUTO_EXCL = '-.';

% Draw all channels
for ii = 1:length(lstSDPairs)
    hCh(ii) = line2(SD.SrcPos(ml(lstSDPairs(ii),1),:), SD.DetPos(ml(lstSDPairs(ii),2),:), [], gridsize, hAxes);

    col = [1.00 1.00 1.00] * 0.85;
    linestyle = '-';
    linewidth = 3;

    % Draw auto-excluded channel
    k1 = find( (MeasListActMan(:,1) == ml(lstSDPairs(ii),1))  &  (MeasListActMan(:,2) == ml(lstSDPairs(ii),2))  &  (MeasListActMan(:,4) == ml(lstSDPairs(ii),4)) );
    k2 = find( (MeasListActAuto(:,1) == ml(lstSDPairs(ii),1))  &  (MeasListActAuto(:,2) == ml(lstSDPairs(ii),2))  &  (MeasListActAuto(:,4) == ml(lstSDPairs(ii),4)) );

    if (~isempty(k1) && MeasListActMan(k1,3) == 0) && (~isempty(k2) && MeasListActAuto(k2,3) == 0)
        col = [1.00 0.6 0.6];
        linestyle = LINESTYLE_MAN_AND_AUTO_EXCL;
    elseif ~isempty(k1) &&  MeasListActMan(k1,3) == 0
        col = [1.00 1.00 1.00] * 0.85;
        linestyle = LINESTYLE_MAN_EXCL;
    elseif ~isempty(k2) && MeasListActAuto(k2,3) == 0
        col = [1.00 0.6 0.6];
        linestyle = LINESTYLE_AUTO_EXCL;
    end

    if ismember(ii, lstInvisible)
        linewidth = 1;
    end

    set(hCh(ii), 'color',col, 'linewidth',linewidth, 'ButtonDownFcn',bttndownfcn, 'linestyle',linestyle);
end

% Draw the user-selected channels
for idx = 1:size(iSrcDet,1)
    hCh(idx+ii) = line2(SD.SrcPos(iSrcDet(idx,1),:), SD.DetPos(iSrcDet(idx,2),:), [], gridsize, hAxes);

    % Attach toggle callback to the selected channels for function on
    % second click
    iSD = GetSelectedSDPairIndex( iSrcDet(idx,1), iSrcDet(idx,2) );
    set(hCh(idx+ii), 'color',SDPairColors(iSD,:), 'ButtonDownFcn',sprintf('toggleLinesAxesSDG_ButtonDownFcn(gcbo,[%d],guidata(gcbo))',idx), 'linewidth',2);

    linestyle = '-';
    linewidth = 3;
    if ~isempty(iCh)
        k1 = find( (MeasListActMan(:,1)==iSrcDet(idx,1))  &  (MeasListActMan(:,2)==iSrcDet(idx,2))  &  (MeasListActMan(:,4)==iWl_gui) );
        k2 = find( (MeasListActAuto(:,1)==iSrcDet(idx,1))  &  (MeasListActAuto(:,2)==iSrcDet(idx,2)) &  (MeasListActMan(:,4)==iWl_gui) );
        k3 = find( (MeasListVis(:,1) == iSrcDet(idx,1))  &  (MeasListVis(:,2) == iSrcDet(idx,2)));

        if (~isempty(k1) && MeasListActMan(k1,3) == 0) && (~isempty(k2) && MeasListActAuto(k2,3) == 0)
            linestyle = LINESTYLE_MAN_AND_AUTO_EXCL;
        elseif ~isempty(k1) &&  MeasListActMan(k1,3) == 0
            linestyle = LINESTYLE_MAN_EXCL;
        elseif ~isempty(k2) && MeasListActAuto(k2,3) == 0
            linestyle = LINESTYLE_AUTO_EXCL;
        end

        if ~isempty(k3) && MeasListVis(k3,3) == 0
            linewidth = 1;
        end
    end
    set(hCh(idx+ii),'linewidth', linewidth, 'linestyle',linestyle);
end

if (maingui.axesSDG.handles.axes == hAxes)
    maingui.axesSDG.handles.ch = hCh;
end

% ADD SOURCE AND DETECTOR LABELS
hSD = zeros(nSrcs+nDets,1);
if isempty(maingui.axesSDG.handles.SD) || (maingui.axesSDG.handles.axes ~= hAxes)
    for idx1 = 1:nSrcs
        if ~isempty(find(MeasList(:,1)==idx1)) %#ok<*EFIND>
            hSD(idx1) = text( SD.SrcPos(idx1,1), SD.SrcPos(idx1,2), sprintf('%d', idx1), 'fontsize',fs, 'fontweight','bold', 'color','r' );
            set(hSD(idx1), 'ButtonDownFcn',get(hAxes,'ButtonDownFcn'), 'horizontalalignment','center', 'edgecolor',edgecol, 'Clipping', 'on');
        end
    end
    for idx2 = 1:nDets
        if ~isempty(find(MeasList(:,2)==idx2))
            hSD(idx2+idx1) = text( SD.DetPos(idx2,1), SD.DetPos(idx2,2), sprintf('%d', idx2), 'fontsize',fs, 'fontweight','bold', 'color','b' );
            set(hSD(idx2+idx1), 'ButtonDownFcn',get(hAxes,'ButtonDownFcn'), 'horizontalalignment','center', 'edgecolor',edgecol, 'Clipping', 'on');
        end
    end
    if (maingui.axesSDG.handles.axes == hAxes)
        maingui.axesSDG.handles.SD = hSD;
    end
else
    uistack(nonzeros(maingui.axesSDG.handles.SD),'top')
end

% Turn off zoom but only for SDG axes
h = zoom(hAxes);
if isempty(UNIT_TEST) || ~UNIT_TEST
    setAllowAxesZoom(h, hAxes, 0);
end

% fprintf('DisplayAxesSDG: Elapsed Time - %0.3f\n', toc);

author: BUNPC


text:
function SUNinstall(destImages, destAnnotations, folder)
%
% SUNinstall(destImages, destAnnotations)
%
% To download a single folder add a third argument:
% SUNinstall(destImages, destAnnotations, folder)

HOMEANNOTATIONS = 'http://labelme.csail.mit.edu/Annotations/users/antonio/static_sun_database';
HOMEIMAGES = 'http://labelme.csail.mit.edu/Images/users/antonio/static_sun_database';

% Build SUN index
disp('Reading folder list')
if nargin == 3
    folder = folderlist(HOMEANNOTATIONS, folder);
else
    folder = folderlist(HOMEANNOTATIONS);
end

% create list of folders to copy, copy and rename folders in XML:
LMinstall(folder, destImages, destAnnotations, HOMEIMAGES, HOMEANNOTATIONS)

% make sure folder names are coherent
ADMINrenamefolder(destAnnotations);


text:
classdef CutMeshProvisionalLine < CutMesh

    properties (Access = private)
        connec
        coord
        cutEdgesComputer
        cutCoordComputer
    end

    properties (Access = private)
        isoCoord
    end

    methods (Access = public)

        function obj = CutMeshProvisionalLine(cParams)
            obj.init(cParams)
            obj.isoCoord = [-1 1];
        end

        function compute(obj)
            obj.computeCutCoordinate();
            obj.coord = obj.cutCoordComputer.coord;
            obj.computeConnec();
            obj.computeXcoordIso();
            obj.cellContainingSubcell = obj.cutCells;
            obj.computeMesh();
            obj.computeInnerCutMesh();
        end

    end

    methods (Access = private)

        function computeCutCoordinate(obj)
            s.levelSet      = obj.levelSet;
            s.nodesInEdges  = obj.backgroundMesh.connec;
            obj.cutEdgesComputer = CutEdgesComputer(s);
            obj.cutEdgesComputer.compute();

            s.coord            = obj.backgroundMesh.coord;
            s.nodesInEdges     = obj.backgroundMesh.connec;
            s.xCutEdgePoint    = obj.cutEdgesComputer.xCutEdgePoint;
            s.isEdgeCut        = obj.cutEdgesComputer.isEdgeCut;
            cComputer = CutCoordinatesComputer(s);
            cComputer.compute();
            obj.cutCoordComputer = cComputer;
        end

        function computeConnec(obj)
            nodeA = obj.backgroundMesh.connec(:,1);
            nodeB = obj.backgroundMesh.connec(:,2);
            lsA = obj.levelSet(nodeA);
            isNodeAinterior = lsA < 0;
            isNodeBinterior = ~isNodeAinterior;
            interiorNode(isNodeAinterior,1) = nodeA(isNodeAinterior);
            interiorNode(isNodeBinterior,1) = nodeB(isNodeBinterior);
            lastNode = size(obj.backgroundMesh.coord,1);
            nElem    = obj.backgroundMesh.nelem;
            boundaryNode(:,1) = lastNode + (1:nElem);
            obj.connec = [interiorNode boundaryNode];
        end

        function computeXcoordIso(obj)
            nodeA = obj.backgroundMesh.connec(:,1);
            lsA = obj.levelSet(nodeA);
            isNodeAinterior = lsA < 0;
            isNodeBinterior = ~isNodeAinterior;
            nDim = 1;
            nnode = 2;
            nelem = length(obj.cutCells);
            xIso = zeros(nDim,nnode,nelem);
            xIso(1,1,:) = obj.cutEdgesComputer.xCutEdgePoint;
            xIso(1,2,isNodeAinterior) = obj.isoCoord(1);
            xIso(1,2,isNodeBinterior) = obj.isoCoord(2);
            obj.xCoordsIso = xIso;
        end

        function computeMesh(obj)
            s.connec = obj.connec;
            s.coord  = obj.coord;
            s.kFace  = obj.backgroundMesh.kFace;
            obj.mesh = Mesh(s);
        end

    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function R = rotx(alpha)

    % ROTX computes a rotation along the x axis (rotation matrix).
    %
    % FORMAT: R = rotx(alpha)
    %
    % INPUT:  - alpha = angle in radians
    %
    % OUTPUT: - R = [3 * 3] rotation matrix along x axis
    %
    % Authors: Daniele Pucci, Marie Charbonneau, Gabriele Nava
    %
    %          all authors are with the Italian Istitute of Technology (IIT)
    %          email: name.surname@iit.it
    %
    % Genoa, Dec 2017
    %

    %% --- Initialization ---

   R =  [1, 0, 0;
         0, cos(alpha), -sin(alpha);
         0, sin(alpha), cos(alpha)];

end

author: robotology

repo: whole-body-controllers


text:
function roi = roiCreate(reference,coords,varargin)
% Create an ROI for an MR object. [May want to add distinct
% function for creating mesh ROIs, though it seems they may
% rather be Xformed from mrMesh...?]
%
%  roi = roiCreate(reference,coords,'Property',[value],...)
%
% Inputs:
% reference: can be either a string specifying a space type
%   (see mrFormatDescription for some possible spaces) or an
%   mr object.
%
%   If it is a string, the ROI can only be processed
%   by mr objects which have that space defined in their spaces
%   fields, and the coordinates will be transformed into the
%   data space of each MR object as needed.
%
%   If it is an mr object,
%   the coords will be considered to refer to rows, columns, and
%   slices in the mr.data field, and can be xformed to other mr objects
%   which share a common space definition with the reference MR object.
%
% coords: 3xN array (integer or double) in which different columns
%   represent different coordinates/voxels in the reference space.
%   The rows describe [Y X Z] in that space: that is the first row of
%   coords describes the rows in each space, the second row describes
%   columns, and the third describes slices. If omitted, coords are
%   left empty.
%
% Properties are:
%   'name',[string]: specify a name for the ROI.
%   'color',[char or [R G B]]: specify a color [default 'b', blue]
%   'referenceMR',[mr]:  mr object on which the ROI has been defined (for when
%       defining with reference to an xformed space -- e.g, if defined
%       on a talairached volume anatomy)
%    'type':  ROI types include:
%               'volume': volume of interest, usually defined on an MR object
%               'patch': 2D patch, usually defined on a surface mesh
%               'line': 1D line, e.g. AC/PC line, or isoeccentricity line
%               'point': single 0D point, e.g. AC or PC, center of a volume ROI
% Wandell and ras, 2005
% ras, 2006: removed requirement for a reference space. Can just return an
% empty ROI.

if notDefined('reference'), reference = 'Raw Data in Pixels'; end
if notDefined('coords'), coords = []; end

%%%%%create a blank ROI
roi.name = 'New ROI';
roi.type = 'volume';
roi.reference = ''; % coordinate space on which ROI is defined
roi.coords = coords;
roi.space = '';
roi.referenceMR =[]; % MR object on which ROI is defined
roi.definedCoords = coords; % coords on which ROI was initially defined
roi.voxelSize = [];  % size of voxels for coords
roi.dimUnits = {'mm' 'mm' 'mm'};
roi.color = 'b';     % can be [R G B] or 'c' -- here 'b'=blue
roi.fillMode = 'perimeter'; % 'perimeter', 'filled', 'patches'
roi.viewType = 'Inplane'; % default: should be over-ridden later
roi.created = datestr(clock);  % permanent stamp on when ROI is created
roi.modified = datestr(clock); % stamp on date of last ROI modification
roi.comments = '';
roi.local = 'local'; % save in local or shared directory

%%%%%parse reference space
if ischar(reference)
    roi.reference = reference;

elseif isstruct(reference)
    roi.reference = 'Pixel Space';
    roi.referenceMR.name = reference.name;
    roi.referenceMR.path = reference.path;
    roi.referenceMR.voxelSize = reference.voxelSize;
    roi.referenceMR.dims = reference.dims;
    roi.referenceMR.extent = reference.extent;
    roi.referenceMR.spaces = reference.spaces;

end

%%%%%parse properties
for i = 1:2:length(varargin)
    switch lower(varargin{i})
        case 'name', roi.name = varargin{i+1};
        case 'color', roi.color = varargin{i+1};
        case 'referencemr', roi.referenceMR = varargin{i+1};
        case 'type', roi.type = varargin{i+1};
		case 'voxelsize', roi.voxelSize = varargin{i+1};
        otherwise, % quietly ignore
    end
end

%%%%%if an mr struct is provided, get the voxel size from it
if ~isempty(roi.referenceMR)
	if ischar(roi.referenceMR), hdr = mrLoadHeader(roi.referenceMR);
	else,						hdr = roi.referenceMR;
	end
	roi.voxelSize = hdr.voxelSize;
end

return;


text:
function test_suite = test_createRotationVector3d
%TEST_CREATEROTATIONVECTOR3D  Test case for the file createRotationVector3d
%
%   Test case for the file createRotationVector3d
%
%   Example
%     runtests('test_createRotationVector3d.m')
%
%   See also
%
% ------
% Author: oqilipo
% Created: 2017-08-08, using Matlab R2016b
% Copyright 2017

test_suite = functiontests(localfunctions);

function test_random(testCase)
A=-1+2.*rand(1,3);
B=-2+4.*rand(1,3);
ROT = createRotationVector3d(A,B);
C = transformVector3d(A,ROT);
testCase.assertEqual(normalizeVector3d(B),normalizeVector3d(C), 'AbsTol', 1e-14);
testCase.assertEqual(vectorNorm3d(A),vectorNorm3d(C), 'AbsTol', 1e-14)

function test_parallel(testCase)
A=-1+2.*rand(1,3);
B=A*2;
ROT = createRotationVector3d(A,B);
C = transformVector3d(A,ROT);
testCase.assertEqual(normalizeVector3d(B),normalizeVector3d(C), 'AbsTol', 1e-14);
testCase.assertEqual(vectorNorm3d(A),vectorNorm3d(C), 'AbsTol', 1e-14)

function test_antiparallel(testCase)
A=-1+2.*rand(1,3);
B=A*-3;
ROT = createRotationVector3d(A,B);
C = transformVector3d(A,ROT);
testCase.assertEqual(normalizeVector3d(B),normalizeVector3d(C), 'AbsTol', 1e-14);
testCase.assertEqual(vectorNorm3d(A),vectorNorm3d(C), 'AbsTol', 1e-14)

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function y=bitsprec(x,n,mode)
%BITSPREC round values to a specified fixed or floating precision (X,N,MODE)
%
% mode is of the form 'uvw' where:
%     u: s - n significant bits (default)
%        f - fixed point: n bits after binary point
%     v: n - round to nearest (default)
%        p - round towards +infinity
%        m - round towards -infinity
%        z - round towards zero
% w is only needed if v=n in which case it dictates what to
%        do if x is min-way between two rounded values:
%     w: p,m - as above
%        e - round to nearest even number (default)
%        o - round to nearest odd number
%        a - round away from zero
% mode='*ne' and '*no' are convergent rounding and introduce
% no DC offset into the result so long as even and odd integer parts are
% equally common.
%
% Examples of y=bitsprec(x,0,'***'):
%
%      x    fp-  fm-  fz-  fne  fno  fnp  fnm  fna
%
%     2.5    3    2    2    2    3    3    2    3
%     1.5    2    1    1    2    1    2    1    2
%     1.1    2    1    1    1    1    1    1    1
%     1.0    1    1    1    1    1    1    1    1
%     0.9    1    0    0    1    1    1    1    1
%     0.5    1    0    0    0    1    1    0    1
%     0.1    1    0    0    0    0    0    0    0
%    -0.1    0   -1    0    0    0    0    0    0
%    -0.5    0   -1    0    0   -1    0   -1   -1
%    -0.9    0   -1    0   -1   -1   -1   -1   -1
%    -1.5   -1   -2   -1   -2   -1   -1   -2   -2

%      Copyright (C) Mike Brookes 1997
%      Version: $Id: bitsprec.m 713 2011-10-16 14:45:43Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin<3
   mode='sne';
end
if mode(1)=='f'
   e=0;
else
   [x,e]=log2(x);
end
switch mode(2)
case 'p'
   y=pow2(ceil(pow2(x,n)),e-n);
case 'm'
   y=pow2(floor(pow2(x,n)),e-n);
case 'z'
   y=pow2(fix(pow2(x,n)),e-n);
otherwise
   switch mode(3)
   case 'a'
      y=pow2(round(pow2(x,n)),e-n);
   case 'p'
      y=pow2(floor(pow2(x,n)+0.5),e-n);
   case 'm'
      y=pow2(ceil(pow2(x,n)-0.5),e-n);
   otherwise
      z=pow2(x,n-1);
      switch mode(3)
      case 'e'
         y=pow2(floor(pow2(x,n)+0.5)-floor(z+0.75)+ceil(z-0.25),e-n);
      case 'o'
         y=pow2(ceil(pow2(x,n)-0.5)+floor(z+0.75)-ceil(z-0.25),e-n);
      end
   end
end

author: jtkim-kaist

repo: VAD

save_path: github-repos/MATLAB/jtkim-kaist-VAD


text:
function [ft2] = mi22ft2(mi2)
% Convert area from square miles to square feet.
% Chad A. Greene 2012
ft2 = mi2*27878400;

author: Sable

repo: mcbench-benchmarks


text:
function [ point_num, edge_num, face_num, face_order_max ] = ...
  truncated_octahedron_size_3d ( )

%*****************************************************************************80
%
%% TRUNCATED_OCTAHEDRON_SIZE_3D gives "sizes" for a truncated octahedron in 3D.
%
%  Discussion:
%
%    The truncated octahedron is "space-filling".
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 July 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer POINT_NUM, the number of points.
%
%    Output, integer EDGE_NUM, the number of edges.
%
%    Output, integer FACE_NUM, the number of faces.
%
%    Output, integer FACE_ORDER_MAX, the maximum order of any face.
%
  point_num = 24;
  edge_num = 36;
  face_num = 14;
  face_order_max = 6;

  return
end


text:
%                                                  y = invcholfac(u,K, perm)
% INVCHOLFAC  Computes y(perm,perm) = u' * u, with u upper triangular.
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also sedumi, getada3

function y = invcholfac(u,K, perm) %#ok
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA

disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ')

repo: REST


text:
function value = a_to_i4 ( ch )

%*****************************************************************************80
%
%% A_TO_I4 returns the index of an alphabetic character.
%
%  Example:
%
%    CH  A_TO_I4
%
%    'A'   1
%    'B'   2
%    ...
%    'Z'  26
%    'a'  27
%    'b'  28
%    ...
%    'z'  52
%    '$'   0
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, character CH, a character.
%
%    Output, integer VALUE, is the alphabetic index of the character,
%    between 1 and 26 if the character is a capital letter,
%    between 27 and 52 if it is lower case, and 0 otherwise.
%
  if ( 'A' <= ch && ch <= 'Z' )
    value = ch - 'A' + 1;
  elseif ( 'a' <= ch && ch <= 'z' )
    value = ch  - 'a' + 27;
  else
    value = 0;
  end

  return
end


text:
function PlotAnnotations(GT_IMG,ALG_IMG,FileName)
nRows=size(GT_IMG,1);
nCols=size(GT_IMG,2);
O=zeros(nRows,nCols,3);
for n=1:nRows
    for k=1:nCols
        if(GT_IMG(n,k)~=0&&ALG_IMG(n,k)~=0)
            O(n,k,:)=[255 255 255];
        elseif(GT_IMG(n,k)==0&&ALG_IMG(n,k)==0)
            O(n,k,:)=[0 0 0];
        elseif(GT_IMG(n,k)~=0&&ALG_IMG(n,k)==0)
            O(n,k,:)=[255 0 0];
        else
            O(n,k,:)=[0 255 0];
        end
    end
end
[~,name,~] = fileparts(FileName);
imwrite(O,['./Results/OutAnnotation/' name '_Diff.jpg'],'jpg');

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
function AxB = Cross(A,B)
%This is a custom implementation of the Cross product operator;
%A and B must be (2x1) symbolic matricies, and AxB is a symbolic variable.
%It assumes that A and B are planar (with components i and j) and that AxB
%is the value of the number out of plane (in the k direction)

AxB = A(1)*B(2) - A(2)*B(1);

end

author: MatthewPeterKelly

repo: dscTutorials


text:
function [ store, abort ] = checkEscape(store)
%CHECKESCAPE checks if the escape key was pressed and abirts the game in
%that case
%
% Outputs:
%   store: main datafile
%   abort: 1 if escape was pressed
%
% About:
%   Coded by F.Petzschner 19. April 2017
%	Last change: F.Petzschner 19. April 2017

keyCode = detectkey(store);

if any(keyCode==store.keys.escape)
        DrawFormattedText(store.screen.window, store.text.abortText, 'center', 'center', store.screen.black);
        Screen('Flip', store.screen.window);

        abort = 1;
        store = logEvent('abort',store);
        save(store.safename, 'store');
        PsychPortAudio('Stop', store.tone.pahandle);
        % Close the audio device
        PsychPortAudio('Close', store.tone.pahandle);
        sca
        return;
else
    abort = 0;
end

end

author: translationalneuromodeling

repo: tapas


text:
% jMap:  Mapping scattered data using local polynomial fitting
%
%   polysmooth - Smoothing scattered 2D data with local polynomial fitting.
%   spheresort - Sorted great circle distances to nearby points on the earth.
%   twodsort   - Distances from data points to nearby grid points.
%
%   Low level functions
%   matinv     - Fast inversion of arrays of small matrices.

help jMap

author: jonathanlilly

repo: jLab

save_path: github-repos/MATLAB/jonathanlilly-jLab


text:
%% OPTI Toolbox Basic Functionality Demo
%
% This file illustrates the basic functionality of the OPTI Toolbox and
% provides a collection of simple examples to get new users familiar with
% the OPTI methods.
%
% Topics covered include:
%
%   - Checking available solvers
%   - Finding a solver for a particular problem type
%   - Building an optiprob problem structure
%   - Building an optiset options structure
%   - Using the opti constructor
%   - Solving an opti object
%   - Validating the solution
%   - Plotting the solution
%
%   Copyright (C) 2011 Jonathan Currie (I2C2)

%% Checking solvers available with your OPTI distribution
% Not all solvers are supplied with the OPTI Toolbox, so to check which are
% available you can use the following function:

checkSolver

%% Matching solvers with a problem type
% Use the 'matrix' argument to print a grid of solver vs problem solved:

checkSolver('matrix')

%% Finding all solvers for a given problem type
% Specify the problem type in order to print a list of all solvers setup to
% solve that problem type. The solver at the top of the list is the default
% solver for that type. The following line prints all solvers which are
% setup to solve a Linear Program (LP) together with constraint and
% sparsity settings (see help checkSolver):

checkSolver('LP')

%% Creating an Optimization Problem
% To create an optimization problem using OPTI there are two methods
% available:
%
%   1) Pass the problem parameters directly to the opti constructor.
%
%   2) Pass the problem parameters to optiprob to generate a problem
%   structure, then pass the structure to the opti constructor.
%
%   Typically we will use (1), however (2) is provided for backwards
%   compatibility, as well as to break up larger problem descriptions.

%% Problem Fields
% Type opti or optiprob with no input arguments to view all available fields
% and groupings. Check the help documentation to see alternative naming and
% grouping strategies.

opti;

%% Options Fields
% Type optiset with no input arguments to view all available fields. Check
% the help documentation for more information.

optiset

%% Problem 1
% This is a simple two decision variable Linear Program (LP) which we will
% use for the next couple of examples.

%Problem
f = -[6 5]';                %Objective Function (min f'x)
A = [1,4; 6,4; 2, -5];      %Linear Inequality Constraints (Ax <= b)
b = [16;28;6];
lb = [0;0];                 %Bounds on x (lb <= x <= ub)
ub = [10;10];

%% Example 1 - Basic Setup
% Problems can be built using the opti constructor. Options from optiset are
% always optional. If the user does not provide any options, OPTI will
% choose default ones for the problem being solved.

Opt = opti('f',f,'ineq',A,b,'bounds',lb,ub)

%% Example 1 - Solving the Problem
% Call solve to solve the problem

[x,fval,exitflag,info] = solve(Opt)

%% Example 2 - Alternative Setup Strategies
% Naming of arguments, as well as pairing is flexible when using optiprob

Opt = opti('c',f,'ineq',A,b,'bounds',lb,ub);    %c = f

% OR
Opt = opti('grad',f,'ineq',A,b,'bounds',lb,ub); %grad = f

% OR
Opt = opti('f',f,'A',A,'b',b,'bounds',lb,ub);   %individual A,b

% OR
Opt = opti('f',f,'ineq',A,b,'lb',lb,'ub',ub);   %individual lb,ub

%% Example 3 - Choosing the Solver
% You can use optiset to select a solver for your problem. This is supplied
% to the opti constructor using optiset, together with the existing
% problem description.

opts = optiset('solver','clp');
Opt = opti(Opt,opts)
x = solve(Opt)

%% Example 3b - Choosing the Solver via 'options'
% You can also specify options when creating the initial OPTI object:

opts = optiset('solver','ooqp');
Opt = opti('f',f,'ineq',A,b,'bounds',lb,ub,'options',opts)
x = solve(Opt)

%% Example 4 - Validating the Solution
% The solution is stored inside the OPTI object, so you can validate it
% against the constraints.

[ok,msg] = checkSol(Opt)

%% Example 5 - Plotting the Solution
% Several problem types have a default plot command available IF the
% problem contains two variables.

plot(Opt)

%% Example 6 - Calling a Solver Directly
% Most OPTI solvers use standard MATLAB function prototypes (such as
% linprog or quadprog), so you can skip using the OPTI class all together:

rl = -Inf(size(b)); %note row format for solver CLP
ru = b;

[x,fval,exitflag,info] = opti_clp([],f,A,rl,ru,lb,ub)

%% Example 7 - MATLAB Optimization Toolbox Overloads
% As described in Overload_demo.m, most Optimization Toolbox functions are
% overloaded ('opti_' is placed in front) for new users.

[x,fval,exitflag,info] = opti_linprog(f,A,b,[],[],lb,ub)

author: vigente

repo: gerardus

save_path: github-repos/MATLAB/vigente-gerardus


text:
function [outdata] = rev_spatial_parse(indata)
% rev_spatial_parse  User-defined function for reverse spatial parsing.
% Input: 'inbits'
%    - input bits for spatial parsing.
% Output: 'outbits'
%    - spatial parsing output bits.

% Get spatial parsing info.
rate   = indata(1);
Nss    = indata(2);
ssize  = indata(3);
remdat = indata(4:end);
inbits = remdat(1:(end/2));
inbits = inbits(1:Nss*ssize);
mscale = remdat((1+end/2):end);
mscale = mscale(1:Nss*ssize);

% Init. rev. spatial parsing
switch rate
    case {1}
        nbits1 = 1;
    case {2,3}
        nbits1 = 2;
    case {4,5}
        nbits1 = 4;
    case {6,7,8}
        nbits1 = 6;
    otherwise
        nbits1 = 1;
end
nbits2 = nbits1;  nbits3 = nbits1;  nbits4 = nbits1;

switch Nss
    case 1
        totbits = nbits1;
    case 2
        totbits = nbits1 + nbits2;
    case 3
        totbits = nbits1 + nbits2 + nbits3;
    case 4
        totbits = nbits1 + nbits2 + nbits3 + nbits4;
end

% Bits: input/output streams...
ssbits1 = zeros(ssize, 1);
ssbits2 = zeros(ssize, 1);
ssbits3 = zeros(ssize, 1);
ssbits4 = zeros(ssize, 1);
outbits = zeros(4*ssize, 1);

% Metric scaling: input/output streams...
ssmscl1 = zeros(ssize, 1);
ssmscl2 = zeros(ssize, 1);
ssmscl3 = zeros(ssize, 1);
ssmscl4 = zeros(ssize, 1);
outmscl = zeros(4*ssize, 1);

% Do rev. spatial parsing...
s1 = 0;
s2 = nbits1;
s3 = nbits1+nbits2;
s4 = nbits1+nbits2+nbits3;
cnt = length(inbits)/totbits - 1;
if (Nss>=1)
    ssbits1 = inbits(1+end*0/Nss : end*1/Nss);
    ssmscl1 = mscale(1+end*0/Nss : end*1/Nss);
    for i=1:nbits1 % stream #1
        outbits(i+s1:totbits:i+s1+totbits*cnt) = ssbits1(i:nbits1:i+nbits1*cnt);
        outmscl(i+s1:totbits:i+s1+totbits*cnt) = ssmscl1(i:nbits1:i+nbits1*cnt);
    end
end
if (Nss>=2)
    ssbits2 = inbits(1+end*1/Nss : end*2/Nss);
    ssmscl2 = mscale(1+end*1/Nss : end*2/Nss);
    for i=1:nbits2 % stream #2
        outbits(i+s2:totbits:i+s2+totbits*cnt) = ssbits2(i:nbits2:i+nbits2*cnt);
        outmscl(i+s2:totbits:i+s2+totbits*cnt) = ssmscl2(i:nbits2:i+nbits2*cnt);
    end
end
if (Nss>=3)
    ssbits3 = inbits(1+end*2/Nss : end*3/Nss);
    ssmscl3 = mscale(1+end*2/Nss : end*3/Nss);
    for i=1:nbits3 % stream #3
        outbits(i+s3:totbits:i+s3+totbits*cnt) = ssbits3(i:nbits3:i+nbits3*cnt);
        outmscl(i+s3:totbits:i+s3+totbits*cnt) = ssmscl3(i:nbits3:i+nbits3*cnt);
    end
end
if (Nss>=4)
    ssbits4 = inbits(1+end*3/Nss : end*4/Nss);
    ssmscl4 = mscale(1+end*3/Nss : end*4/Nss);
    for i=1:nbits4 % stream #4
        outbits(i+s4:totbits:i+s4+totbits*cnt) = ssbits4(i:nbits4:i+nbits4*cnt);
        outmscl(i+s4:totbits:i+s4+totbits*cnt) = ssmscl4(i:nbits4:i+nbits4*cnt);
    end
end

% Reverse spatial parsing output
outdata = [outbits; outmscl];


text:
function H = landmark2hash(L,S)
% H = landmark2hash(L,S)
%  Convert a set of 4-entry landmarks <t1 f1 f2 dt>
%  into a set of <songid time hash> triples ready to store.
%  S is a scalar songid, or one per landmark (defaults to 0)
% 2008-12-29 Dan Ellis dpwe@ee.columbia.edu

% Hash value is 20 bits: 8 bits of F1, 6 bits of delta-F, 6 bits of delta-T

if nargin < 2
  S = 0;
end
if length(S) == 1
  S = repmat(S, size(L,1), 1);
end

H = uint32(L(:,1));
% Make sure F1 is 0..255, not 1..256
F1 = rem(round(L(:,2)-1),2^8);
DF = round(L(:,3)-L(:,2));
if DF < 0
  DF = DF + 2^8;
end
DF = rem(DF,2^6);
DT = rem(abs(round(L(:,4))), 2^6);
H = [S,H,uint32(F1*(2^12)+DF*(2^6)+DT)];


text:
function varargout = process_aec2( varargin )
% PROCESS_AEC2: Compute amplitude envelope correlation between one signal in one file, and all the signals in another file.

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2012-2014
%          Peter Donhauser, 2017

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'Amplitude Envelope Correlation AxB';
    sProcess.Category    = 'Custom';
    sProcess.SubGroup    = 'Connectivity';
    sProcess.Index       = 657;
    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Connectivity';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'data', 'results', 'matrix'};
    sProcess.OutputTypes = {'timefreq', 'timefreq', 'timefreq'};
    sProcess.nInputs     = 2;
    sProcess.nMinFiles   = 1;
    sProcess.isPaired    = 1;

    % === CONNECT INPUT
    sProcess = process_corr2('DefineConnectOptions', sProcess);
    % === FREQ BANDS
    sProcess.options.freqbands.Comment = 'Frequency bands for the Hilbert transform:';
    sProcess.options.freqbands.Type    = 'groupbands';
    sProcess.options.freqbands.Value   = bst_get('DefaultFreqBands');
    % === Orthogonalize pairs of signals
    sProcess.options.isorth.Comment = 'Orthogonalize signal pairs before envelope computation';
    sProcess.options.isorth.Type    = 'checkbox';
    sProcess.options.isorth.Value   = 0;
    % === OUTPUT MODE
    sProcess.options.outputmode.Comment = {'Save individual results (one file per input file)', 'Concatenate input files before processing (one file)', 'Save average connectivity matrix (one file)'};
    sProcess.options.outputmode.Type    = 'radio';
    sProcess.options.outputmode.Value   = 1;
    sProcess.options.outputmode.Group   = 'output';
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
    Comment = sProcess.Comment;
end

%% ===== RUN =====
function OutputFiles = Run(sProcess, sInputA, sInputB) %#ok<DEFNU>
    % Input options
    OPTIONS = process_corr2('GetConnectOptions', sProcess, sInputA, sInputB);
    if isempty(OPTIONS)
        OutputFiles = {};
        return
    end

    OPTIONS.Method = 'aec';
    % Hilbert and frequency bands options
    OPTIONS.Freqs = sProcess.options.freqbands.Value;
    OPTIONS.isOrth = sProcess.options.isorth.Value;

    % Compute metric
    OutputFiles = bst_connectivity({sInputA.FileName}, {sInputB.FileName}, OPTIONS);
end

author: brainstorm-tools


text:
% Version 1.000
%
% Code provided by Ruslan Salakhutdinov and Geoff Hinton
%
% Permission is granted for anyone to copy, use, modify, or distribute this
% program and accompanying programs and documents for any purpose, provided
% this copyright notice is retained and prominently displayed, along with
% a note saying that the original programs are available from our
% web page.
% The programs and documents are distributed without any warranty, express or
% implied.  As the programs were written for research purposes only, they have
% not been tested to the degree that would be advisable in any important
% application.  All use of these programs is entirely at the user's own risk.

% This program fine-tunes an autoencoder with backpropagation.
% Weights of the autoencoder are going to be saved in mnist_weights.mat
% and trainig and test reconstruction errors in mnist_error.mat
% You can also set maxepoch, default value is 200 as in our paper.

maxepoch=50;
fprintf(1,'\nFine-tuning deep autoencoder by minimizing cross entropy error. \n');
% fprintf(1,'60 batches of 1000 cases each. \n');

load mnistvh
load mnisthp
load mnisthp2
load mnistpo

% makebatches;
[numcases numdims numbatches]=size(batchdata);
N=numcases;

%%%% PREINITIALIZE WEIGHTS OF THE AUTOENCODER %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
w1=[vishid; hidrecbiases];
w2=[hidpen; penrecbiases];
% w3=[hidpen2; penrecbiases2];
w4=[hidtop; toprecbiases];
w5=[hidtop'; topgenbiases];
% w6=[hidpen2'; hidgenbiases2];
w7=[hidpen'; hidgenbiases];
w8=[vishid'; visbiases];

%%%%%%%%%% END OF PREINITIALIZATIO OF WEIGHTS  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

l1=size(w1,1)-1;
l2=size(w2,1)-1;
% l3=size(w3,1)-1;
l4=size(w4,1)-1;
l5=size(w5,1)-1;
% l6=size(w6,1)-1;
l7=size(w7,1)-1;
l8=size(w8,1)-1;
l9=l1;
test_err=[];
train_err=[];

for epoch = 1:maxepoch

%%%%%%%%%%%%%%%%%%%% COMPUTE TRAINING RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
err=0;
[numcases numdims numbatches]=size(batchdata);
N=numcases;
 for batch = 1:numbatches
  data = [batchdata(:,:,batch)];
  data = [data ones(N,1)];
  w1probs = 1./(1 + exp(-data*w1)); w1probs = [w1probs  ones(N,1)];
  w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)];
%   w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs  ones(N,1)];
  w4probs = w2probs*w4; w4probs = [w4probs  ones(N,1)];
  w5probs = 1./(1 + exp(-w4probs*w5)); w5probs = [w5probs  ones(N,1)];
%   w6probs = 1./(1 + exp(-w5probs*w6)); w6probs = [w6probs  ones(N,1)];
  w7probs = 1./(1 + exp(-w5probs*w7)); w7probs = [w7probs  ones(N,1)];
  dataout = 1./(1 + exp(-w7probs*w8));
  err= err +  1/N*sum(sum( (data(:,1:end-1)-dataout).^2 ));
  end
 train_err(epoch)=err/numbatches;

%%%%%%%%%%%%%% END OF COMPUTING TRAINING RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%% DISPLAY FIGURE TOP ROW REAL DATA BOTTOM ROW RECONSTRUCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%
% fprintf(1,'Displaying in figure 1: Top row - real data, Bottom row -- reconstructions \n');
% output=[];
%  for ii=1:15
%   output = [output data(ii,1:end-1)' dataout(ii,:)'];
%  end
%    if epoch==1
%    close all
%    figure('Position',[100,600,1000,200]);
%    else
%    figure(1)
%    end
%    mnistdisp(output);
%    drawnow;

%%%%%%%%%%%%%%%%%%%% COMPUTE TEST RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[testnumcases testnumdims testnumbatches]=size(testbatchdata);
N=testnumcases;
err=0;
for batch = 1:testnumbatches
  data = [testbatchdata(:,:,batch)];
  data = [data ones(N,1)];
  w1probs = 1./(1 + exp(-data*w1)); w1probs = [w1probs  ones(N,1)];
  w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)];
%   w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs  ones(N,1)];
  w4probs = w2probs*w4; w4probs = [w4probs  ones(N,1)];
  w5probs = 1./(1 + exp(-w4probs*w5)); w5probs = [w5probs  ones(N,1)];
%   w6probs = 1./(1 + exp(-w5probs*w6)); w6probs = [w6probs  ones(N,1)];
  w7probs = 1./(1 + exp(-w5probs*w7)); w7probs = [w7probs  ones(N,1)];
  dataout = 1./(1 + exp(-w7probs*w8));
  err = err +  1/N*sum(sum( (data(:,1:end-1)-dataout).^2 ));
  end
 test_err(epoch)=err/testnumbatches;
 fprintf(1,'Before epoch %d Train squared error: %6.3f Test squared error: %6.3f \t \t \n',epoch,train_err(epoch),test_err(epoch));

%%%%%%%%%%%%%% END OF COMPUTING TEST RECONSTRUCTION ERROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 tt=0;
 for batch = 1:numbatches/10
 fprintf(1,'epoch %d batch %d\r',epoch,batch);

%%%%%%%%%%% COMBINE 10 MINIBATCHES INTO 1 LARGER MINIBATCH %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 tt=tt+1;
 data=[];
 for kk=1:10
  data=[data
        batchdata(:,:,(tt-1)*10+kk)];
 end

%%%%%%%%%%%%%%% PERFORM CONJUGATE GRADIENT WITH 3 LINESEARCHES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  max_iter=3;
%   VV = [w1(:)' w2(:)' w3(:)' w4(:)' w5(:)' w6(:)' w7(:)' w8(:)']';
  VV = [w1(:)' w2(:)' w4(:)' w5(:)' w7(:)' w8(:)']';
  Dim = [l1; l2; l4; l5; l7; l8; l9];

  [X, fX] = minimize(VV,'CG_MNIST',max_iter,Dim,data);

  w1 = reshape(X(1:(l1+1)*l2),l1+1,l2);
  xxx = (l1+1)*l2;
  w2 = reshape(X(xxx+1:xxx+(l2+1)*l3),l2+1,l3);
  xxx = xxx+(l2+1)*l3;
%   w3 = reshape(X(xxx+1:xxx+(l3+1)*l4),l3+1,l4);
%   xxx = xxx+(l3+1)*l4;
  w4 = reshape(X(xxx+1:xxx+(l4+1)*l5),l4+1,l5);
  xxx = xxx+(l4+1)*l5;
  w5 = reshape(X(xxx+1:xxx+(l5+1)*l6),l5+1,l6);
  xxx = xxx+(l5+1)*l6;
%   w6 = reshape(X(xxx+1:xxx+(l6+1)*l7),l6+1,l7);
%   xxx = xxx+(l6+1)*l7;
  w7 = reshape(X(xxx+1:xxx+(l7+1)*l8),l7+1,l8);
  xxx = xxx+(l7+1)*l8;
  w8 = reshape(X(xxx+1:xxx+(l8+1)*l9),l8+1,l9);

%%%%%%%%%%%%%%% END OF CONJUGATE GRADIENT WITH 3 LINESEARCHES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 end

 save mnist_weights w1 w2  w4 w5  w7 w8
 save mnist_error test_err train_err;

end

repo: DeepFi


text:
function result = postfix(str)
    if isempty(str)
        result = '';
    else
        result = sprintf('_%s', str);
    end
end

author: layumi

repo: Image-Text-Embedding


text:
function obj2 = fft( obj1, varargin )

obj2 = unitaryopp(@fft, obj1, varargin{:});

author: sccn

repo: eeglab

save_path: github-repos/MATLAB/sccn-eeglab


text:
function varargout = rts_OrbOpsConsole(varargin)
% RTS_ORBOPSCONSOLE MATLAB code for rts_OrbOpsConsole.fig
%      RTS_ORBOPSCONSOLE, by itself, creates a new RTS_ORBOPSCONSOLE or raises the existing
%      singleton*.
%
%      H = RTS_ORBOPSCONSOLE returns the handle to a new RTS_ORBOPSCONSOLE or the handle to
%      the existing singleton*.
%
%      RTS_ORBOPSCONSOLE('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in RTS_ORBOPSCONSOLE.M with the given input arguments.
%
%      RTS_ORBOPSCONSOLE('Property','Value',...) creates a new RTS_ORBOPSCONSOLE or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before rts_OrbOpsConsole_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to rts_OrbOpsConsole_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help rts_OrbOpsConsole

% Last Modified by GUIDE v2.5 08-Dec-2013 14:01:25

% Begin initialization code - DO NOT EDIT
    gui_Singleton = 1;
    gui_State = struct('gui_Name',       mfilename, ...
                       'gui_Singleton',  gui_Singleton, ...
                       'gui_OpeningFcn', @rts_OrbOpsConsole_OpeningFcn, ...
                       'gui_OutputFcn',  @rts_OrbOpsConsole_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
end

% --- Executes just before rts_OrbOpsConsole is made visible.
function rts_OrbOpsConsole_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 rts_OrbOpsConsole (see VARARGIN)
    % Choose default command line output for rts_OrbOpsConsole
    handles.output = hObject;

    hRtsMainGUI = varargin{1};
    vesselGUID = varargin{2};
    handles.mainGUI = hRtsMainGUI;
    handles.vesselGUID = vesselGUID;

    %Initialize OrbOps panel
    rts_initRTSOrbOpsPanel(hRtsMainGUI, handles.rts_OrbOpsConsole, handles.clockLabel, handles.connStatusLabel, vesselGUID, handles.orbitTextDispLabel, ...
                            handles.orbitDispAxes, handles.targetOrbitTextDispLabel, handles.maneuversTextDispLabel, handles.rendInfoTextDispLabel);

    % Update handles structure
    guidata(hObject, handles);

    % UIWAIT makes rts_OrbOpsConsole wait for user response (see UIRESUME)
    % uiwait(handles.rts_OrbOpsConsole);
end

% --- Outputs from this function are returned to the command line.
function varargout = rts_OrbOpsConsole_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;
end

% --- Executes when user attempts to close rts_OrbOpsConsole.
function rts_OrbOpsConsole_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to rts_OrbOpsConsole (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure

    rts_pageCloseStopTimers(hObject);
    delete(hObject);
end

% --- Executes on button press in prevManButton.
function prevManButton_Callback(hObject, eventdata, handles)
% hObject    handle to prevManButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    set(handles.maneuversTextDispLabel, 'UserData', max(get(handles.maneuversTextDispLabel,'UserData')-1,0));
end

% --- Executes on button press in nextManButton.
function nextManButton_Callback(hObject, eventdata, handles)
% hObject    handle to nextManButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    set(handles.maneuversTextDispLabel, 'UserData', max(get(handles.maneuversTextDispLabel,'UserData')+1,0));
end

author: Arrowstar

repo: ksptot


text:
function [mach] = mph2mach(mph)
% Convert speed from miles per hour to mach number (at STP!)
% Chad A. Greene 2012
mach = mph*0.00130332361516;