text:
function [studylist, dosetype]=dicomrt_DICOMdirscan(path2scan)
% dicomrt_DICOMdirscan(path2scan)
%
% Scan a directory for DICOM studies.
%
% path2scan is the directory path that will be scanned. Scan is not recursive.
%
% Returns a cell array "studylist" containing a list of the studies found in directory "path2scan".
%
% This is the structure of studylist
%
%    Patients         RTPLAN             RTDOSE            CT               RTSTRUCTURE      MR
%      Name           series             series            series           series           studies
%  ----------------------------------------------------------------------------------------------------------|
%  | [Name 1] |[L 1] [D 1] [Flist 1] | [D 1] [Flist 1] | [D 1] [Flist 1] | [D 1] [Flist 1] | [D 1] [Flist 1] |
%  |          |                      |                 |                 |                 |                 |
%  |          |[L j] [D j] [Flist j] | [D k] [Flist k] | [D l] [Flist l] | [D m] [Flist m] | [D n] [Flist n] |
%  |          |                      |                 |                 |                 |                 |
%  ----------------------------------------------------------------------------------------------------------|
%  |               ...                                    ...                                                |
%  ----------------------------------------------------------------------------------------------------------|
%  | [Name p] |[L 1] [D 1] [Flist 1] | [D 1] [Flist 1] | [D 1] [Flist 1] | [D 1] [Flist 1] | [D 1] [Flist 1] |
%  |          |                      |                 |                 |                 |                 |
%  |          |[L q] [D q] [Flist q] | [D r] [Flist r] | [D s] [Flist s] | [D t] [Flist t] | [D v] [Flist v] |
%  |          |                      |                 |                 |                 |                 |
%  ----------------------------------------------------------------------------------------------------------|
%
% where L=Label, D=Date, Flist=Filename list, j-v are indices
%
% See also: dicomrt_DICOMscan, dicomrt_DICOMimport
%
%
% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org)
% LM DK 11/16/2005 if the files do not have extension it checks if the
% files are philips DICOM files if the answer is true it renames them with
% DICOM extension .dcm
%
% LM  DK changed the data structure of studylist to incorporate multiple
% rtdose and rtplan file import.
global dosetype

if nargin == 0
    [path2scan] = uigetdir('*.*','Select the directory that you want to scan');
elseif ischar(path2scan)~=1
    error('dicomrt_DICOMdirscan: The input path is not a character string. Exit now!');
end

% Allowed extensions
oklist=strvcat('dcm','DCM','ct','CT','rtp','RTP','rtstruct','RTSTRUCT','ima','IMA');

% List directory contents
list=dir(path2scan);

%
PatientName=[];        % initialize character array with patients name
studyUID=[];            % initialize character array with study UID
studylist=cell(1,6);    % initialize character array with study UID
nrtplans=0;             % initialize number of different RTPLANS
nrtdoses=0;             % initialize number of different RTDOSES series
nrtcts=0;               % initialize number of different CT series
nrtstructs=0;           % initialize number of different RTSTRUCTURES
nrtmrs=0;               % initialize number of different MR series
nrtpts = 0;             % initialize number of different PET series
nseries=0;              % initialize number of series whitin current study

% Set progress bar
list=dir(path2scan);
h = waitbar(0,'Scanning progress');
set(h,'Name',['dicomrt_DICOMimport: ',path2scan]);

for k=1:size(list,1)
    if list(k).isdir==0
        try
            dictFlg = checkDictUse;
            if dictFlg
                if isdeployed
                    temp = dicominfo(fullfile(path2scan,list(k).name), 'dictionary',...
                        fullfile(getCERRPath,'bin','ES - IPT4.1CompatibleDictionary.mat'));
                else
                    temp = dicominfo(fullfile(path2scan,list(k).name), 'dictionary',...
                        'ES - IPT4.1CompatibleDictionary.mat');
                end
            else
                temp=dicominfo(fullfile(path2scan,list(k).name));
            end
        catch
            warning(['file ' list(k).name ' not DICOM']);
            continue;
        end
        if strcmpi(temp.Format,'DICOM')

            % check if the loaded DICOM file is valid (based on Modality field)
            if ~isfield(temp,'Modality')
                try
                    temp=dicominfo(fullfile(path2scan,list(k).name));
                    if ~isfield(temp,'Modality')
                        warning(['file ' list(k).name ' is not a valid DICOM. ignoring...']);
                    end
                end
                continue;
            end

            % check if a patient name has been already loaded
            if isempty(PatientName)==0
                % yes, a patient name has been already loaded
                % check if this patient's name has been already loaded
                matchname=strcmpi(temp.PatientName.FamilyName,PatientName);
                if matchname
                    % no, add this the name to the list
                    PatientName=strvcat(PatientName,temp.PatientName.FamilyName);
                    % add this patient to the studylist
                    matchname=size(studylist,1)+1;
                    studylist{matchname,1}=temp.PatientName.FamilyName;
                    % flag this is a new patient
                    newpatient=1;
                else
                    % nothing to be done for now
                    % flag this is not a new patient
                    newpatient=0;
                end
            else
                % no, add this name as first name in the list
                PatientName=strvcat(PatientName,temp.PatientName.FamilyName);
                % add this patient to the studylist
                studylist{1,1}=temp.PatientName.FamilyName;
                % flag this is a new patient
                newpatient=1;
                % set accordingly matchname
                matchname=1;
            end
            if newpatient==0
                % we are not dealing with a new patient
                % check if a study has been already loaded for this patient
                if isempty(studyUID)==0
                    % yes, a study has been already loaded
                    % check if this study has been already loaded
                    matchstudy = strcmpi(temp.StudyInstanceUID,studyUID);
                    if matchstudy
                        % no, add this study to the list
                        studyUID=strvcat(studyUID,temp.StudyInstanceUID);
                        % add this study to the studylist
                        matchstudy=size(studylist{matchname,2},1)+1;
                        if strcmpi(temp.Modality,'RTPLAN')==1
                            % update nrtplans
                            nrtplans=nrtplans+1;
                            studylist{matchname,2}{nrtplans,1}=temp.RTPlanLabel;
                            studylist{matchname,2}{nrtplans,2}=temp.StudyDate;
                            if size(studylist{matchname,2},2)==2
                                studylist{matchname,2}{nrtplans,3}=temp.Filename;
                            else
                                studylist{matchname,2}{nrtplans,3}=strvcat(studylist{matchname,2}{nrtplans,3},temp.Filename);
                            end
                        elseif strcmpi(temp.Modality,'rtdose')==1
                            % update nrtdoses
                            nrtdoses=nrtdoses+1;
                            dosetype = temp.DoseSummationType;
                            studylist{matchname,3}{nrtdoses,1}=temp.StudyDate;
                            if size(studylist{matchname,3},2)==1
                                studylist{matchname,3}{nrtdoses,2}=temp.Filename;
                            else
                                studylist{matchname,3}{nrtdoses,2}=strvcat(studylist{matchname,3}{nrtdoses,2},temp.Filename);
                            end
                        elseif strcmpi(temp.Modality,'CT')==1
                            % update nrtcts
                            nrtcts=nrtcts+1;
                            studylist{matchname,4}{nrtcts,1}=temp.StudyDate;
                            if size(studylist{matchname,4},2)==1
                                studylist{matchname,4}{nrtcts,2}=temp.Filename;
                            else
                                studylist{matchname,4}{nrtcts,2}=strvcat(studylist{matchname,4}{nrtcts,2},temp.Filename);
                            end
                        elseif strcmpi(temp.Modality,'RTSTRUCT')==1
                            % update nrtstructs
                            nrtstructs=nrtstructs+1;
                            studylist{matchname,5}{nrtstructs,1}=temp.StudyDate;
                            if size(studylist{matchname,5},2)==1
                                studylist{matchname,5}{nrtstructs,2}=temp.Filename;
                            else
                                studylist{matchname,5}{nrtstructs,2}=strvcat(studylist{matchname,5}{nrtstructs,2},temp.Filename);
                            end
                        elseif strcmpi(temp.Modality,'MR')==1
                            % update nrtmrs
                            nrtmrs=nrtmrs+1;
                            studylist{matchname,6}{nrtmrs,1}=temp.StudyDate;
                            if size(studylist{matchname,6},2)==1
                                studylist{matchname,6}{nrtmrs,2}=temp.Filename;
                            else
                                studylist{matchname,6}{nrtmrs,2}=strvcat(studylist{matchname,6}{nrtmrs,2},temp.Filename);
                            end
                        elseif strcmpi(temp.Modality,'PET')==1 | strcmpi(temp.Modality,'PT')==1
                            % update nrtmrs
                            nrtpts=nrtpts+1;
                            studylist{matchname,7}{nrtpts,1}=temp.StudyDate;
                            if size(studylist{matchname,7},2)==1
                                studylist{matchname,7}{nrtpts,2}=temp.Filename;
                            else
                                studylist{matchname,7}{nrtpts,2}=strvcat(studylist{matchname,7}{nrtpts,2},temp.Filename);
                            end

                        % Scan for SPECT images
                        elseif strcmpi(temp.Modality,'NM')
                            nrtpts = nrtpts+1;
                            if nrtpts == 1
                                studylist{matchname,8}{nrtpts,1}= temp.StudyDate;
                                if size(studylist{matchname,8},2)==1
                                    studylist{matchname,8}{nrtpts,2}= temp.Filename;
                                else % add to new scan as SPECT are multiframe studies
                                    warning('Multiple SPECT study import work in progress');
                                end
                            else
                                warning('Multiple SPECT study import work in progress');
                            end
                        end
                        % flag this is a new study
                        newstudy=1;
                    else
                        % this study has been already loaded
                        if strcmpi(temp.Modality,'RTPLAN')==1
                            nrtplans=nrtplans+1;
                            try
                                studylist{matchname,2}{nrtplans,1}=temp.RTPlanLabel;
                            catch
                                studylist{matchname,2}{nrtplans,1}='Unknown';
                            end
                            studylist{matchname,2}{nrtplans,2}=temp.StudyDate;
                            if size(studylist{matchname,2},2)==2
                                studylist{matchname,2}{nrtplans,3}=temp.Filename;
                            else
                                studylist{matchname,2}{nrtplans,3}=strvcat(studylist{matchname,2}{nrtplans,3},temp.Filename);
                            end
                        elseif strcmpi(temp.Modality,'rtdose')==1
                            % DK
                            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                            if nrtdoses==0
                                nrtdoses=1;
                            elseif strcmpi(temp.DoseSummationType,'FRACTION')
                                nrtdoses = nrtdoses+1;
                            end
                            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                            studylist{matchname,3}{nrtdoses,1}=temp.StudyDate;
                            if size(studylist{matchname,3},2)==1
                                studylist{matchname,3}{nrtdoses,2}=temp.Filename;
                            else
                                studylist{matchname,3}{nrtdoses,2}=strvcat(studylist{matchname,3}{nrtdoses,2},temp.Filename);
                            end
                        elseif strcmpi(temp.Modality,'CT')==1
                            if nrtcts==0
                                nrtcts=1;
                            end
                            studylist{matchname,4}{nrtcts,1}=temp.StudyDate;
                            if size(studylist{matchname,4},2)==1
                                studylist{matchname,4}{nrtcts,2}=temp.Filename;
                            else
                                studylist{matchname,4}{nrtcts,2}=strvcat(studylist{matchname,4}{nrtcts,2},temp.Filename);
                            end
                        elseif strcmpi(temp.Modality,'RTSTRUCT')==1
                            nrtstructs=nrtstructs+1;
                            studylist{matchname,5}{nrtstructs,1}=temp.StudyDate;
                            if size(studylist{matchname,5},2)==1
                                studylist{matchname,5}{nrtstructs,2}=temp.Filename;
                            else
                                studylist{matchname,5}{nrtstructs,2}=strvcat(studylist{matchname,5}{nrtstructs,2},temp.Filename);
                            end
                        elseif strcmpi(temp.Modality,'MR')==1
                            studylist{matchname,6}{nrtmrs,1}=temp.StudyDate;
                            if size(studylist{matchname,6},2)==1
                                studylist{matchname,6}{nrtmrs,2}=temp.Filename;
                            else
                                studylist{matchname,6}{nrtmrs,2}=strvcat(studylist{matchname,6}{nrtmrs,2},temp.Filename);
                            end
                        elseif strcmpi(temp.Modality,'PET')==1 | strcmpi(temp.Modality,'PT')==1
                            % update nrtmrs
                            nrtpts=nrtpts+1;
                            studylist{matchname,7}{nrtpts,1}=temp.StudyDate;
                            if size(studylist{matchname,7},2)==1
                                studylist{matchname,7}{nrtpts,2}=temp.Filename;
                            else
                                studylist{matchname,7}{nrtpts,2}=strvcat(studylist{matchname,7}{nrtpts,2},temp.Filename);
                            end

                        elseif strcmpi(temp.Modality,'NM')
                            nrtpts = nrtpts+1;
                            if nrtpts == 1
                                studylist{matchname,8}{nrtpts,1}= temp.StudyDate;
                                if size(studylist{matchname,8},2)==1
                                    studylist{matchname,8}{nrtpts,2}= temp.Filename;
                                else % add to new scan as SPECT are multiframe studies
                                    warning('Multiple SPECT study import work in progress');
                                end
                            else
                                warning('Multiple SPECT study import work in progress');
                            end
                        end
                        % flag this is a new study
                        newstudy=0;
                    end
                else
                    error('dicomrt_DICOMdirscan: there is a problem: old patient and no study already in ?');
                end
            elseif newpatient==1
                % we are dealing with a new patient
                % add this study to the list
                studyUID=strvcat(studyUID,temp.StudyInstanceUID);
                % add this study to the studylist
                if strcmpi(temp.Modality,'RTPLAN')==1
                    % update nrtplans
                    nrtplans=1;
                    studylist{matchname,2}{nrtplans,1}=temp.RTPlanLabel;
                    studylist{matchname,2}{nrtplans,2}=temp.StudyDate;
                    if size(studylist{matchname,2},2)==2
                        studylist{matchname,2}{nrtplans,3}=temp.Filename;
                    else
                        studylist{matchname,2}{nrtplans,3}=strvcat(studylist{matchname,2}{nrtplans,3},temp.Filename);
                    end
                elseif strcmpi(temp.Modality,'rtdose')==1
                    % update nrtdoses
                    if strcmpi(temp.DoseSummationType,'FRACTION')
                        nrtdoses = nrtdoses +1;
                    else
                        nrtdoses=1;
                    end
                    studylist{matchname,3}{nrtdoses,1}=temp.StudyDate;
                    if size(studylist{matchname,3},2)==1
                        studylist{matchname,3}{nrtdoses,2}=temp.Filename;
                    else
                        studylist{matchname,3}{nrtdoses,2}=strvcat(studylist{matchname,3}{nrtdoses,2},temp.Filename);
                    end
                elseif strcmpi(temp.Modality,'CT')==1
                    % update nrtcts
                    nrtcts=1;
                    studylist{matchname,4}{nrtcts,1}=temp.StudyDate;
                    if size(studylist{matchname,4},2)==1
                        studylist{matchname,4}{nrtcts,2}=temp.Filename;
                    else
                        studylist{matchname,4}{nrtcts,2}=strvcat(studylist{matchname,4}{nrtcts,2},temp.Filename);
                    end
                elseif strcmpi(temp.Modality,'RTSTRUCT')==1
                    % update ntrstructs
                    ntrstructs=1;
                    studylist{matchname,5}{ntrstructs,1}=temp.StudyDate;
                    if size(studylist{matchname,5},2)==1
                        studylist{matchname,5}{ntrstructs,2}=temp.Filename;
                    else
                        studylist{matchname,5}{ntrstructs,2}=strvcat(studylist{matchname,5}{ntrstructs,2},temp.Filename);
                    end
                elseif strcmpi(temp.Modality,'MR')==1
                    % update ntrstructs
                    nrtmrs=1;
                    studylist{matchname,6}{nrtmrs,1}=temp.StudyDate;
                    if size(studylist{matchname,6},2)==1
                        studylist{matchname,6}{nrtmrs,2}=temp.Filename;
                    else
                        studylist{matchname,6}{nrtmrs,2}=strvcat(studylist{matchname,6}{nrtmrs,2},temp.Filename);
                    end
                elseif strcmpi(temp.Modality,'PET')==1 | strcmpi(temp.Modality,'PT')==1
                    % update nrtmrs
                    nrtpts=1;
                    studylist{matchname,7}{nrtpts,1}=temp.StudyDate;
                    if size(studylist{matchname,7},2)==1
                        studylist{matchname,7}{nrtpts,2}=temp.Filename;
                    else
                        studylist{matchname,7}{nrtpts,2}=strvcat(studylist{matchname,7}{nrtpts,2},temp.Filename);
                    end

                elseif strcmpi(temp.Modality,'NM')
                    nrtpts = nrtpts+1;
                    if nrtpts == 1
                        studylist{matchname,8}{nrtpts,1}= temp.StudyDate;
                        if size(studylist{matchname,8},2)==1
                            studylist{matchname,8}{nrtpts,2}= temp.Filename;
                        else % add to new scan as SPECT are multiframe studies
                            warning('Multiple SPECT study import work in progress');
                        end
                    else
                        warning('Multiple SPECT study import work in progress');
                    end

                end
            end
            % flag this is a new study
            newstudy=1;
        end
    end
    waitbar(k/size(list,1),h);
end

% Close progress bar
close(h);
clear temp

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function determ = leslie_determinant ( b, di, da )

%*****************************************************************************80
%
%% LESLIE_DETERMINANT returns the determinant of the LESLIE matrix.
%
%  Discussion:
%
%    DETERM = a(4,4) * (
%        a(1,1) * a(2,2) * a(3,3)
%      + a(1,3) * a(2,1) * a(3,2) )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real B, DI, DA, the birth rate, infant mortality rate,
%    and aged mortality rate.  These should be positive values.
%    The mortality rates must be between 0.0 and 1.0.  Reasonable
%    values might be B = 0.025, DI = 0.010, and DA = 0.100
%
%    Output, real DETERM, the determinant.
%
  determ = 9.0 * ( 1.0 - da ) / 10.0 * ...
  ( ...
      5.0 * ( 1.0 - di ) / 6.0 ...
    * 13.0 / 14.0 ...
    * 39.0 / 40.0 ...
  +   b ...
    * ( 1.0 - di ) / 6.0 ...
    * 1.0 / 14.0 ...
   );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% [INPUT]
% chi = A float n-by-n-by-t matrix [0,1] representing the time-varying Chi coefficients.
%
% [OUTPUT]
% achi = A row vector of floats [0,1] of length t representing the Average Chi.
% adr = A row vector of floats [0,1] of length t representing the Asymptotic Dependence Rate.

function [achi,adr] = chi_metrics(varargin)

    persistent ip;

    if (isempty(ip))
        ip = inputParser();
        ip.addRequired('chi',@(x)validateattributes(x,{'double'},{'real' '3d' 'nonempty'}));
    end

    ip.parse(varargin{:});

    ipr = ip.Results;
    chi = validate_input(ipr.chi);

    nargoutchk(2,2);

    [achi,adr] = chi_metrics_internal(chi);

end

function [achi,adr] = chi_metrics_internal(chi)

    up = isempty(getCurrentTask());

    [n1,n2,t] = size(chi);
    n = min(n1,n2);

    achi = zeros(t,1);
    adr = zeros(t,1);

    if (up)
        parfor k = 1:t
            chi_k = chi(:,:,k);

            adr_num = 0;
            chi_sum = 0;
            den = 0;

            for i = 1:n
                for j = 1:n
                    if (i == j)
                        continue;
                    end

                    chi_kij = chi_k(i,j);

                    if (isnan(chi_kij))
                        continue;
                    end

                    if (chi_kij > 0)
                        adr_num = adr_num + 1;
                    end

                    chi_sum = chi_sum + chi_kij;
                    den = den + 1;
                end
            end

            achi(k) = chi_sum / den;
            adr(k) = adr_num / den;
        end
    else
        for k = 1:t
            chi_k = chi(:,:,k);

            adr_num = 0;
            chi_sum = 0;
            den = 0;

            for i = 1:n
                for j = 1:n
                    if (i == j)
                        continue;
                    end

                    chi_kij = chi_k(i,j);

                    if (isnan(chi_kij))
                        continue;
                    end

                    if (chi_kij > 0)
                        adr_num = adr_num + 1;
                    end

                    chi_sum = chi_sum + chi_kij;
                    den = den + 1;
                end
            end

            achi(k) = chi_sum / den;
            adr(k) = adr_num / den;
        end
    end

end

function chi = validate_input(chi)

    [n1,n2,t] = size(chi);

    if ((n1 ~= n2) || (min(n1,n2) < 2))
        error('The value of ''chi'' is invalid. Expected input to be a square 3d matrix with a minimum size of 2x2xt.');
    end

    if (t < 5)
        error('The value of ''chi'' is invalid. Expected input to be a square 3d matrix with at least elements on the third dimension.');
    end

    chiv = chi(:);
    chiv(isnan(chiv)) = [];

    if (any((chiv < 0) | (chiv > 1)))
        error('The value of ''chi'' is invalid. Expected input to contain non-NaN values greater than or equal to 0 and less than or equal to 1.');
    end

end

author: TommasoBelluzzo

repo: SystemicRisk


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

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

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

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function [V,F,VC,FC] = image_mesh(filename,m)
  % IMAGE_MESH Given a path to .png file, create a mesh within the α>½ region of
  % the image with triangles placed economically so that per-vertex colors will
  % look reasonable.
  %
  % Input:
  %   filename  path to .png file
  %   m  number of output triangles
  % Outputs:
  %   V  #V by 2 list of 2D vertex positions
  %   F  #F by 3 list of triangle indices into V
  %   VC  #V by 3 list of vertex colors
  %   FC  #F by 3 list of face colors
  %
  % See also: bwmesh
  %

  [im,M,A] = imread(filename);
  if ~isempty(M)
      im = ind2rgb(im,M);
  end
  if isempty(A)
    A = ones(size(im,1),size(im,2));
  end
  [V,F] = bwmesh(A,'SmoothingIters',2,'Tol',0.2);
  %[V,F] = bwmesh(A);
  [X,Y] = meshgrid((1:size(im,2))-0.5,(size(im,1):-1:1)-0.5);

  for c = 1:3
    V(:,2+c) = interp2(X,Y,im2double(im(:,:,c)),V(:,1),V(:,2));
  end

  % weird trick to get better quality elements. Based on Delaunay lifting idea.
  %V(:,end+1) = (V(:,1).^2+V(:,2).^2)*0.001;

  [V,F] = decimate_libigl(V,F,m,'Method','qslim');

  VC = V(:,3:5);
  V = V(:,1:2);

  if nargout>3
    BC = barycenter(V,F);
    FC = zeros(size(F,1),3);
    for c = 1:3
      FC(:,c) = interp2(X,Y,im2double(im(:,:,c)),BC(:,1),BC(:,2));
    end
  end
end

author: alecjacobson

repo: gptoolbox


text:
%SerialLink.IKUNC Inverse manipulator by optimization without joint limits
%
% Q = R.ikunc(T, OPTIONS) are the joint coordinates (1xN) corresponding to
% the robot end-effector pose T which is an SE3 object or homogenenous
% transform matrix (4x4), and N is the number of robot joints. OPTIONS is
% an optional list of name/value pairs than can be passed to fminunc.
%
% Q = robot.ikunc(T, Q0, OPTIONS) as above but specify the
% initial joint coordinates Q0 used for the minimisation.
%
% [Q,ERR] = robot.ikunc(T,...) as above but also returns ERR which is the
% scalar final value of the objective function.
%
% [Q,ERR,EXITFLAG] = robot.ikunc(T,...) as above but also returns the
% status EXITFLAG from fminunc.
%
% [Q,ERR,EXITFLAG,OUTPUT] = robot.ikunc(T,...) as above but also returns the
% structure OUTPUT from fminunc which contains details about the optimization.
%
% Trajectory operation::
%
% In all cases if T is a vector of SE3 objects (1xM) or a homogeneous transform
% sequence (4x4xM) then returns the joint coordinates corresponding to
% each of the transforms in the sequence.  Q is MxN where N is the number
% of robot joints. The initial estimate of Q for each time step is taken as
% the solution from the previous time step.
%
% ERR and EXITFLAG are also Mx1 and indicate the results of optimisation
% for the corresponding trajectory step.
%
% Notes::
% - Requires fminunc from the MATLAB Optimization Toolbox.
% - Joint limits are not considered in this solution.
% - Can be used for robots with arbitrary degrees of freedom.
% - In the case of multiple feasible solutions, the solution returned
%   depends on the initial choice of Q0
% - Works by minimizing the error between the forward kinematics of the
%   joint angle solution and the end-effector frame as an optimisation.
%   The objective function (error) is described as:
%           sumsqr( (inv(T)*robot.fkine(q) - eye(4)) * omega )
%   Where omega is some gain matrix, currently not modifiable.
%
% Author::
% Bryan Moutrie
%
% See also SerialLink.ikcon, fmincon, SerialLink.ikine, SerialLink.fkine.

% Copyright (C) Bryan Moutrie, 2013-2015
% Licensed under the GNU Lesser General Public License
% see full file for full statement
%
% LICENSE STATEMENT:
%
% This file is part of pHRIWARE.
%
% pHRIWARE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation, either version 3 of
% the License, or (at your option) any later version.
%
% pHRIWARE 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 Lesser General Public
% License along with pHRIWARE.  If not, see <http://www.gnu.org/licenses/>.

function [qstar, error, exitflag, output] = ikunc(robot, T, varargin)

    % check if Optimization Toolbox exists, we need it
    assert( exist('fminunc', 'file')>0, 'rtb:ikunc:nosupport', 'Optimization Toolbox required');

    if isa(T, 'SE3')
        T = T.T;
    end

    % create output variables
    T_sz = size(T,3);
    qstar = zeros(T_sz,robot.n);
    error = zeros(T_sz,1);
    exitflag = zeros(T_sz,1);

    problem.solver = 'fminunc';
    problem.x0 = zeros(1, robot.n);
    problem.options = optimoptions('fminunc', ...
        'Algorithm', 'quasi-newton', ...
        'Display', 'off'); % default options for ikunc

    if nargin > 2
        % check if there is a q0 passed
        if isnumeric(varargin{1}) && length(varargin{1}) == robot.n
            problem.x0 = varargin{1};
            varargin = varargin(2:end);
        end
    end
    if ~isempty(varargin)
        % if given, add optional argument to the list of optimiser options
        problem.options = optimoptions(problem.options, varargin{:});
    end

    reach = sum(abs([robot.a, robot.d]));
    omega = diag([1 1 1 3/reach]);

    for t = 1:T_sz
        problem.objective = ...
            @(x) sumsqr(((T(:,:,t) \ robot.fkine(x).T) - eye(4)) * omega);

        [q_t, err_t, ef_t, out_t] = fminunc(problem);

        if ef_t ~= 1
            if T_sz > 1
                warning('step %d: errflag = %d, err = %f\n', t, ef_t, err_t);
            else
                warning('errflag = %d, err = %f\n', ef_t, err_t);
                out_t
            end
        end
        qstar(t,:) = q_t;
        error(t) = err_t;
        exitflag(t) = ef_t;
        output(t) = out_t;

        problem.x0 = q_t;
    end

end

function s = sumsqr(A)
    s = sum(A(:).^2);
end

author: petercorke

repo: robotics-toolbox-matlab


text:
function [B, elapse] = DSH_compress(A, model)
%   This is a wrapper function of Density Sensitive Hashing testing.
%
%     [B, elapse] = DSH_compress(A, model)
%
%	      A: Rows of vectors of data points. Each row is sample point
%     model: The model generated by DSH_learn.
%
%	      B: The binary code of the input data A. Each row is sample point
%    elapse: The coding time (testing time).
%
%
%
%   Reference:
%
%   Zhongming Jin, Cheng Li, Yue Lin, Deng Cai: Density Sensitive Hashing.
%   IEEE Trans. Cybernetics 44(8): 1362-1371 (2014)
%
%
%
%   version 2.0 --Nov/2016
%   version 1.0 -- Feb/2012
%
%      Written by Yue Lin (linyue29@gmail.com)
%                 Deng Cai (dengcai AT gmail DOT com)

res = repmat(model.intercept', size(A,1), 1);

tmp_T = tic;
Ym = A * model.U';
B = (Ym > res);
elapse = toc(tmp_T);

end

author: ZJULearning

repo: MatlabFunc


text:
%	nufft1_time.m
%	examine time spent in nufft1 sub-routines

if 1
	N1 = 1024 * 128;
	J1 = 6;

	n_shift = 0;
	Nlist = 2 .^ [8];
	Jlist = [8];

	[NN,JJ] = ndgrid(Nlist, Jlist);

	for ii=1:length(NN(:))
		N1 = NN(ii);
		J1 = JJ(ii);
		K1 = 2*N1;

		x = [1:N1]';	% test signal
		x = x(:,ones(1,1000));

		gam = 2*pi/K1;
		o1 = linspace(0,gam,N1)';

%profile clear
%profile on -detail operator
%profile on -detail builtin
		tic
		sb = nufft1_init(o1, N1, J1, K1, n_shift, 'best');
		printf('init time = %g', toc)
%profile on -detail builtin
		[Xn, times] = nufft1(x, sb);
%profile report
%profile off

		printf('time fft=%g other=%g overhead=%g', ...
			times(1), times(2), times(2)/times(1)*100)
	end
return
end

author: thomaskuestner


text:
function dataset = ilsvrc15(dataset, usage, use_flip, root_path)

if  exist([root_path '/' usage '.mat'])
  tic; load([root_path '/' usage '.mat']); toc; return;
end

switch usage
    case {'val15'}
        dataset.imdb_test     = imdb_from_ilsvrc15(root_path, 'val', false);
        dataset.roidb_test    = dataset.imdb_test.roidb_func(dataset.imdb_test, ...
            'roidb_name_suffix', roidb_name_suffix, 'rootDir', root_path);
          % clear images without any object
          valid = ~cellfun(@isempty, {dataset.roidb_test.rois.gt});
            dataset.roidb_test.rois = dataset.roidb_test.rois(valid);
            dataset.imdb_test.is_blacklisted = dataset.imdb_test.is_blacklisted(valid);
            dataset.imdb_test.sizes = dataset.imdb_test.sizes(valid,:);
            dataset.imdb_test.image_ids = dataset.imdb_test.image_ids(valid);
            dataset.imdb_test.image_at = @(i) ...
            fullfile(dataset.imdb_test.image_dir, [dataset.imdb_test.image_ids{i} '.' dataset.imdb_test.extension]);

    case {'train15'}
        dataset.imdb_train     = {imdb_from_ilsvrc15(root_path, 'train', use_flip)};
        dataset.roidb_train = cellfun(@(x) x.roidb_func(x, 'rootDir', root_path), ...
            dataset.imdb_train, 'UniformOutput', false);

          % clear images without any object
        valid = ~cellfun(@isempty, {dataset.roidb_train{1, 1}.rois.gt});
          dataset.roidb_train{1, 1}.rois = dataset.roidb_train{1, 1}.rois(valid);
          dataset.imdb_train{1, 1}.is_blacklisted = dataset.imdb_train{1, 1}.is_blacklisted(valid);
          dataset.imdb_train{1, 1}.sizes = dataset.imdb_train{1, 1}.sizes(valid,:);
          if use_flip, dataset.imdb_train{1, 1}.flip_from = dataset.imdb_train{1, 1}.flip_from(valid); end
          dataset.imdb_train{1, 1}.image_ids = dataset.imdb_train{1, 1}.image_ids(valid);
            dataset.imdb_train{1, 1}.image_at = @(i) ...
            fullfile(dataset.imdb_train{1, 1}.image_dir, [dataset.imdb_train{1, 1}.image_ids{i} '.' dataset.imdb_train{1, 1}.extension]);
    case {'VIDval16'}
        dataset.imdb_test     = imdb_from_ilsvrc15vid(root_path, 'vid_val', false);
        dataset.roidb_test    = dataset.imdb_test.roidb_func(dataset.imdb_test, ...
            'roidb_name_suffix', '', 'rootDir', root_path);
    case {'VIDtrain16'}
        dataset.imdb_train     = {imdb_from_ilsvrc15vid(root_path, 'vid_train', use_flip)};
        dataset.roidb_train = cellfun(@(x) x.roidb_func(x, 'roidb_name_suffix', '', 'rootDir', root_path), ...
            dataset.imdb_train, 'UniformOutput', false);
    case {'VID+DETtrain16'}
        dataset.imdb_train     = {imdb_from_ilsvrc15vid(root_path, 'vid_train', use_flip) } ;
       dataset.imdb_train{2} =   imdb_from_ilsvrc15(root_path, 'train', use_flip );
        dataset.roidb_train = cellfun(@(x) x.roidb_func(x, 'roidb_name_suffix', '', 'rootDir', root_path), ...
            dataset.imdb_train, 'UniformOutput', false);
       % remove classes in DET that do not match vid
       [dataset.imdb_train{2},dataset.roidb_train{2}] = ...
         imdb_remove_cls(dataset.imdb_train{2},dataset.roidb_train{2}, dataset.imdb_train{1}) ;
    case {'VID+DETtrain16sample'}

       dataset.imdb_train     = {imdb_from_ilsvrc15vid(root_path, 'vid_train', use_flip) } ;
       dataset.imdb_train{2} =   imdb_from_ilsvrc15(root_path, 'train', use_flip );
       dataset.roidb_train = cellfun(@(x) x.roidb_func(x, 'roidb_name_suffix', '', 'rootDir', root_path), ...
       dataset.imdb_train, 'UniformOutput', false);

       % remove classes in DET that do not match vid
       [dataset.imdb_train{2},dataset.roidb_train{2}] = ...
         imdb_remove_cls(dataset.imdb_train{2},dataset.roidb_train{2}, dataset.imdb_train{1}) ;

       % sample 2k classes
       [dataset.imdb_train{2},dataset.roidb_train{2}] = ...
         imdb_sample_cls(dataset.imdb_train{2},dataset.roidb_train{2}, 2000) ;

       [dataset.imdb_train{1},dataset.roidb_train{1}] = ...
         imdb_sample_frames(dataset.imdb_train{1},dataset.roidb_train{1}, 30) ;

    case {'DETtrain16sample5k'}
        dataset.imdb_train{2} =   imdb_from_ilsvrc15(root_path, 'train', use_flip );
        dataset.roidb_train(2) = cellfun(@(x) x.roidb_func(x, 'roidb_name_suffix', '', 'rootDir', root_path), ...
            dataset.imdb_train(2), 'UniformOutput', false);

       % remove classes in DET that do not match vid
       [dataset.imdb_train{2},dataset.roidb_train{2}] = ...
         imdb_remove_cls(dataset.imdb_train{2},dataset.roidb_train{2}, dataset.imdb_train{1}) ;

       % sample 5k classes with replacement
       [dataset.imdb_train{2},dataset.roidb_train{2}] = ...
         imdb_sample_cls(dataset.imdb_train{2},dataset.roidb_train{2}, 5000, true) ;

    case {'VIDval16lite'}
        dataset.imdb_test     = imdb_from_ilsvrc15vid(root_path, 'vid_val', false, 5e4 );
        dataset.roidb_test    = dataset.imdb_test.roidb_func(dataset.imdb_test, ...
            'roidb_name_suffix', 'lite50k', 'rootDir', root_path);
    case {'VIDval16lite5k'}
        dataset.imdb_test     = imdb_from_ilsvrc15vid(root_path, 'vid_val', false, 5e3 );
        dataset.roidb_test    = dataset.imdb_test.roidb_func(dataset.imdb_test, ...
            'roidb_name_suffix', 'lite5k', 'rootDir', root_path);
    case {'VIDval16lite30frames'}
        dataset.imdb_test     = imdb_from_ilsvrc15vid(root_path, 'vid_val', false, 30 );
        dataset.roidb_test    = dataset.imdb_test.roidb_func(dataset.imdb_test, ...
            'roidb_name_suffix', 'lite30frames', 'rootDir', root_path);
  case {'VIDval16lite3frames'}
        dataset.imdb_test     = imdb_from_ilsvrc15vid(root_path, 'vid_val', false, 3 );
        dataset.roidb_test    = dataset.imdb_test.roidb_func(dataset.imdb_test, ...
            'roidb_name_suffix', 'lite3frames', 'rootDir', root_path);
  case {'VIDval16liteStride10'}
        dataset.imdb_test     = imdb_from_ilsvrc15vid(root_path, 'vid_val', false, 10, 'uniform');
        dataset.roidb_test    = dataset.imdb_test.roidb_func(dataset.imdb_test, ...
            'roidb_name_suffix', 'liteStride10', 'rootDir', root_path);
  case {'VIDval16liteStride5'}
        dataset.imdb_test     = imdb_from_ilsvrc15vid(root_path, 'vid_val', false, 5, 'uniform');
        dataset.roidb_test    = dataset.imdb_test.roidb_func(dataset.imdb_test, ...
            'roidb_name_suffix', 'liteStride5', 'rootDir', root_path);
    case {'VIDtrain16lite3frames'}
        dataset.imdb_train     = {imdb_from_ilsvrc15vid(root_path, 'vid_train', use_flip, 3)};
        dataset.roidb_train = cellfun(@(x) x.roidb_func(x, 'roidb_name_suffix', 'lite3frames', 'rootDir', root_path), ...
            dataset.imdb_train, 'UniformOutput', false);
    case {'VIDtrain16sample'}
        dataset.imdb_train     = {imdb_from_ilsvrc15vid(root_path, 'vid_train', use_flip) } ;
        dataset.roidb_train = cellfun(@(x) x.roidb_func(x, 'roidb_name_suffix', '', 'rootDir', root_path), ...
            dataset.imdb_train, 'UniformOutput', false);
          frame_offset = 3;
       [dataset.imdb_train{1},dataset.roidb_train{1}] = ...
         imdb_sample_frames(dataset.imdb_train{1},dataset.roidb_train{1}, 30, frame_offset) ;
    case {'VIDtrain16sample5frames'}
        dataset.imdb_train     = {imdb_from_ilsvrc15vid(root_path, 'vid_train', use_flip) } ;
        dataset.roidb_train = cellfun(@(x) x.roidb_func(x, 'roidb_name_suffix', '', 'rootDir', root_path), ...
            dataset.imdb_train, 'UniformOutput', false);
          frame_offset = 3;
       [dataset.imdb_train{1},dataset.roidb_train{1}] = ...
         imdb_sample_frames(dataset.imdb_train{1},dataset.roidb_train{1}, 5, frame_offset) ;

  otherwise
        error('usage = ''train14'' or ''test''');
end

if  0 %strfind(usage, 'VID') &&  strfind(usage, 'train')
  if isfield(dataset, 'imdb_train')
    f='_train';
    imdb = dataset.(['imdb' f]){1};
    roidb = dataset.(['roidb' f]){1};
  else f='_test';
    imdb = dataset.(['imdb' f]);
    roidb = dataset.(['roidb' f]);
  end
  video_label_freq = zeros(numel(imdb.video_ids),imdb.num_classes);
  labelCount = zeros(numel(imdb.video_ids),1);
  for i = 1:numel(imdb.image_ids)
    labels = (unique(roidb.rois(i).overlap==1,'rows'));
    [r, c] = find(labels) ;

%     fprintf('%s-', imdb.classes{c});
    if isfield(imdb,'image_id_sel')
      vid_idx = imdb.vid_id(imdb.image_id_sel(i));
    else
      vid_idx = imdb.vid_id(i);
    end
    video_label_freq(vid_idx,c) = video_label_freq(vid_idx,c) + 1;
    labelCount(vid_idx) = labelCount(vid_idx) + ~isempty(labels);
  end

  video_label_freq(labelCount~=0,:) = bsxfun(@rdivide, video_label_freq(labelCount~=0,:), labelCount(labelCount~=0));

  if isfield(dataset, 'imdb_train')
    dataset.imdb_train{1}.video_label_freq = video_label_freq;
  else
   dataset.imdb_test.video_label_freq = video_label_freq;
  end
end
if  ~isempty(strfind(usage, 'train')) && ~isempty(strfind(usage, 'sample'))
  save([root_path '/' usage], 'dataset', '-v7.3');
end

author: feichtenhofer

repo: Detect-Track


text:
function [bFun, b0Fun, derFun] = conAffPoint2PlaneSimpleOLS(prm, cst, obs)

% ------------------------------------------------------------------------------

bFun = @(obs) bFunNested(obs);

    function bBlock = bFunNested(obs)

        bBlock = obs.dp;

    end

% ------------------------------------------------------------------------------

b0Fun = @(prm, cst) b0FunNested(prm, cst);

    function b0Block = b0FunNested(prm, cst)

        % Affine matrices
        A1 = [prm.a111 prm.a121 prm.a131
              prm.a211 prm.a221 prm.a231
              prm.a311 prm.a321 prm.a331];

        A2 = [prm.a112 prm.a122 prm.a132
              prm.a212 prm.a222 prm.a232
              prm.a312 prm.a322 prm.a332];

        % Homogeneous transformation matrix
        H1 = homotrafo(1, A1, [prm.tx1 prm.ty1 prm.tz1]);
        H2 = homotrafo(1, A2, [prm.tx2 prm.ty2 prm.tz2]);

        % Coordinates
        X1 = [cst.x1 cst.y1 cst.z1];
        X2 = [cst.x2 cst.y2 cst.z2];

        % Normal vector
        n1 = [cst.nx1 cst.ny1 cst.nz1];

        % Transformation from cartesian coord. to homogeneous coord.
        X1_h = homocoord(X1);
        X2_h = homocoord(X2);

        b0Block = dot((homocoord((H1 * X1_h')') - homocoord((H2 * X2_h')'))', n1')';

    end

% Derivatives ------------------------------------------------------------------

derFun.prm.a111 = @(prm, cst) derFunNested(prm, cst, 'prm_a111');
derFun.prm.a121 = @(prm, cst) derFunNested(prm, cst, 'prm_a121');
derFun.prm.a131 = @(prm, cst) derFunNested(prm, cst, 'prm_a131');
derFun.prm.a211 = @(prm, cst) derFunNested(prm, cst, 'prm_a211');
derFun.prm.a221 = @(prm, cst) derFunNested(prm, cst, 'prm_a221');
derFun.prm.a231 = @(prm, cst) derFunNested(prm, cst, 'prm_a231');
derFun.prm.a311 = @(prm, cst) derFunNested(prm, cst, 'prm_a311');
derFun.prm.a321 = @(prm, cst) derFunNested(prm, cst, 'prm_a321');
derFun.prm.a331 = @(prm, cst) derFunNested(prm, cst, 'prm_a331');
derFun.prm.tx1  = @(prm, cst) derFunNested(prm, cst, 'prm_tx1');
derFun.prm.ty1  = @(prm, cst) derFunNested(prm, cst, 'prm_ty1');
derFun.prm.tz1  = @(prm, cst) derFunNested(prm, cst, 'prm_tz1');

derFun.prm.a112 = @(prm, cst) derFunNested(prm, cst, 'prm_a112');
derFun.prm.a122 = @(prm, cst) derFunNested(prm, cst, 'prm_a122');
derFun.prm.a132 = @(prm, cst) derFunNested(prm, cst, 'prm_a132');
derFun.prm.a212 = @(prm, cst) derFunNested(prm, cst, 'prm_a212');
derFun.prm.a222 = @(prm, cst) derFunNested(prm, cst, 'prm_a222');
derFun.prm.a232 = @(prm, cst) derFunNested(prm, cst, 'prm_a232');
derFun.prm.a312 = @(prm, cst) derFunNested(prm, cst, 'prm_a312');
derFun.prm.a322 = @(prm, cst) derFunNested(prm, cst, 'prm_a322');
derFun.prm.a332 = @(prm, cst) derFunNested(prm, cst, 'prm_a332');
derFun.prm.tx2  = @(prm, cst) derFunNested(prm, cst, 'prm_tx2');
derFun.prm.ty2  = @(prm, cst) derFunNested(prm, cst, 'prm_ty2');
derFun.prm.tz2  = @(prm, cst) derFunNested(prm, cst, 'prm_tz2');

    function derFunBlock = derFunNested(prm, cst, var)

        switch var

            % ------------------------------------------------------------------

            case 'prm_a111'

                derFunBlock =   cst.x1 .* cst.nx1;

            % ------------------------------------------------------------------

            case 'prm_a121'

                derFunBlock =   cst.y1 .* cst.nx1;

            % ------------------------------------------------------------------

            case 'prm_a131'

                derFunBlock =   cst.z1 .* cst.nx1;

            % ------------------------------------------------------------------

            case 'prm_a211'

                derFunBlock =   cst.x1 .* cst.ny1;

            % ------------------------------------------------------------------

            case 'prm_a221'

                derFunBlock =   cst.y1 .* cst.ny1;

            % ------------------------------------------------------------------

            case 'prm_a231'

                derFunBlock =   cst.z1 .* cst.ny1;

            % ------------------------------------------------------------------

            case 'prm_a311'

                derFunBlock =   cst.x1 .* cst.nz1;

            % ------------------------------------------------------------------

            case 'prm_a321'

                derFunBlock =   cst.y1 .* cst.nz1;

            % ------------------------------------------------------------------

            case 'prm_a331'

                derFunBlock =   cst.z1.* cst.nz1;

            % ------------------------------------------------------------------

            case 'prm_a112'

                derFunBlock = - cst.x2 .* cst.nx1;

            % ------------------------------------------------------------------

            case 'prm_a122'

                derFunBlock = - cst.y2 .* cst.nx1;

            % ------------------------------------------------------------------

            case 'prm_a132'

                derFunBlock = - cst.z2 .* cst.nx1;

            % ------------------------------------------------------------------

            case 'prm_a212'

                derFunBlock = - cst.x2 .* cst.ny1;

            % ------------------------------------------------------------------

            case 'prm_a222'

                derFunBlock = - cst.y2 .* cst.ny1;

            % ------------------------------------------------------------------

            case 'prm_a232'

                derFunBlock = - cst.z2 .* cst.ny1;

            % ------------------------------------------------------------------

            case 'prm_a312'

                derFunBlock = - cst.x2 .* cst.nz1;

            % ------------------------------------------------------------------

            case 'prm_a322'

                derFunBlock = - cst.y2 .* cst.nz1;

            % ------------------------------------------------------------------

            case 'prm_a332'

                derFunBlock = - cst.z2.* cst.nz1;

            % ------------------------------------------------------------------

            case 'prm_tx1'

                derFunBlock =   cst.nx1;

            % ------------------------------------------------------------------

            case 'prm_tx2'

                derFunBlock = - cst.nx1;

            % ------------------------------------------------------------------

            case 'prm_ty1'

                derFunBlock =   cst.ny1;

            % ------------------------------------------------------------------

            case 'prm_ty2'

                derFunBlock = - cst.ny1;

            % ------------------------------------------------------------------

            case 'prm_tz1'

                derFunBlock =   cst.nz1;

            % ------------------------------------------------------------------

            case 'prm_tz2'

                derFunBlock = - cst.nz1;

        end

    end

end

author: pglira


text:
function [S, mu, sigma2] = standardize(M, mu, sigma2)
% function S = standardize(M, mu, sigma2)
% Make each column of M be zero mean, std 1.
% Thus each row is scaled separately.
%
% If mu, sigma2 are omitted, they are computed from M

if nargin < 2
  mu = mean(M,2);
  sigma2 = std(M,0,2);
  sigma2 = sigma2 + eps*(sigma2==0);
end

[nrows ncols] = size(M);
S = M - repmat(mu(:), [1 ncols]);
S = S ./ repmat(sigma2, [1 ncols]);

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function new_par = update_parameters(new_par, par, type,NaN_fill)
% This function overwrite or create fields from par in new_par. The fields
%   used will be only the ones with type 'type' present in 'par'.
% new_par a struct() could be empty.
% par a struct() with parameters.
% type a string: 'detect' for parameters used in detection an alignment of
%   spikes. 'clus' for parameters used in detection or clustering. 'relevant' for both.

if ~exist('NaN_fill','var')
    NaN_fill = false;
end
detection_params = {'channels','segments_length', 'sr','tmax','tmin','w_pre', ...
    'w_post','alignment_window', 'stdmin','stdmax', 'detect_fmin', ...
    'detect_fmax','sort_fmin','sort_fmax', 'ref_ms', 'detection', ...
    'int_factor','interpolation','alignment_window','sort_order','detect_order','detection_date'};

clus_params = {'min_inputs','max_inputs','scales','features','template_sdnum', 'template_k', ...
    'template_k_min','template_type','force_feature','match', ...
    'max_spk','permut','mintemp', 'maxtemp', 'tempstep','SWCycles',...
    'KNearNeighb', 'min_clus','randomseed','force_auto','sorting_date','elbow_min','c_ov'};

batch_ploting_params = {'temp_plot','max_spikes_plot','print2file','plot_feature_stats'};

new_par_names = fieldnames(new_par);
load_par_names = fieldnames(par);
if strcmp(type,'detect') || strcmp(type,'relevant')
    for i= 1:length(detection_params)
        if ismember(detection_params(i),load_par_names)
            field = char(detection_params(i));
            new_par.(field ) = par.(field );
         elseif NaN_fill
            field = char(detection_params(i));
            new_par.(field) = NaN;
        end
    end
end

if strcmp(type,'batch_plot')
    for i= 1:length(batch_ploting_params)
        if ismember(batch_ploting_params(i),load_par_names)
            field = char(batch_ploting_params(i));
            new_par.(field ) = par.(field );
        end
    end
end

if strcmp(type,'clus') || strcmp(type,'relevant')
    for i= 1:length(clus_params)
        if ismember(clus_params(i),load_par_names)
            field = char(clus_params(i));
            new_par.(field ) = par.(field );
        end
    end
end

if strcmp(type,'none')
    for i= 1:length(new_par_names)
        if ~ (any((ismember(new_par_names(i),clus_params)) || any(ismember(new_par_names(i),detection_params))))
            field = char(new_par_names(i));
            if ismember(new_par_names(i),load_par_names)
                new_par.(field) = par.(field );
            else
                new_par.(field) = [];
            end
        end
    end

end

if isfield(par,'ref')
    new_par.ref_ms = double(par.ref) /par.sr *1000;
end

end

author: csn-le


text:
function add_io(hRD,type)

% add AXI4 and AXI4-Lite slave interfaces
hRD.addAXI4SlaveInterface( ...
    'InterfaceConnection', 'axi_cpu_interconnect/M09_AXI', ...
    'BaseAddress',         '0x43C00000', ...
    'MasterAddressSpace',  'sys_ps7/Data');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Rx Reference design interfaces
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if contains(lower(type),'rx')
    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data Valid OUT', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'dut_data_valid', ...
        'PortWidth',      1, ...
        'InterfaceConnection', 'util_ad9361_adc_pack/adc_valid_0', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 0 OUT', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'dut_data_0', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_0', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 1 OUT', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'dut_data_1', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_1', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 2 OUT', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'dut_data_2', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_2', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 3 OUT', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'dut_data_3', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_3', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 4 OUT', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'dut_data_4', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_4', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 5 OUT', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'dut_data_5', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_5', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 6 OUT', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'dut_data_6', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_6', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 7 OUT', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'dut_data_7', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_7', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 ADC Data I0', ...
        'InterfaceType',  'IN', ...
        'PortName',       'sys_wfifo_0_dma_wdata', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_0', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 ADC Data Q0', ...
        'InterfaceType',  'IN', ...
        'PortName',       'sys_wfifo_1_dma_wdata', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_1', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 ADC Data I1', ...
        'InterfaceType',  'IN', ...
        'PortName',       'sys_wfifo_2_dma_wdata', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_2', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 ADC Data Q1', ...
        'InterfaceType',  'IN', ...
        'PortName',       'sys_wfifo_3_dma_wdata', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_3', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 ADC Data I2', ...
        'InterfaceType',  'IN', ...
        'PortName',       'sys_wfifo_4_dma_wdata', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_4', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 ADC Data Q2', ...
        'InterfaceType',  'IN', ...
        'PortName',       'sys_wfifo_5_dma_wdata', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_5', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 ADC Data I3', ...
        'InterfaceType',  'IN', ...
        'PortName',       'sys_wfifo_6_dma_wdata', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_6', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 ADC Data Q3', ...
        'InterfaceType',  'IN', ...
        'PortName',       'sys_wfifo_7_dma_wdata', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_7', ...
        'IsRequired',     false);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Tx Reference design interfaces
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if contains(lower(type),'tx')
    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 DAC Data I0', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'axi_ad9361_0_dac_data_i0', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'axi_ad9361_dac_fifo/din_data_0', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 DAC Data Q0', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'axi_ad9361_0_dac_data_q0', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'axi_ad9361_dac_fifo/din_data_1', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 DAC Data I1', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'axi_ad9361_0_dac_data_i1', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'axi_ad9361_dac_fifo/din_data_2', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 DAC Data Q1', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'axi_ad9361_0_dac_data_q1', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'axi_ad9361_dac_fifo/din_data_3', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 DAC Data I2', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'axi_ad9361_1_dac_data_i0', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'axi_ad9361_dac_fifo/din_data_4', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 DAC Data Q2', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'axi_ad9361_1_dac_data_q0', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'axi_ad9361_dac_fifo/din_data_5', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 DAC Data I3', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'axi_ad9361_1_dac_data_i1', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'axi_ad9361_axi_ad9361_dac_fifo/din_data_6', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'AD9361 DAC Data Q3', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'axi_ad9361_1_dac_data_q1', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'axi_ad9361_axi_ad9361_dac_fifo/din_data_7', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Load Tx Data OUT', ...
        'InterfaceType',  'OUT', ...
        'PortName',       'util_ad9361_dac_upack_dac_valid_00', ...
        'PortWidth',      1, ...
        'InterfaceConnection', 'axi_ad9361_dac_fifo/din_valid_in_0', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 0 IN', ...
        'InterfaceType',  'IN', ...
        'PortName',       'util_ad9361_dac_upack_dac_data_00', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_0', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 1 IN', ...
        'InterfaceType',  'IN', ...
        'PortName',       'util_ad9361_dac_upack_dac_data_01', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_1', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 2 IN', ...
        'InterfaceType',  'IN', ...
        'PortName',       'util_ad9361_dac_upack_dac_data_02', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_2', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 3 IN', ...
        'InterfaceType',  'IN', ...
        'PortName',       'util_ad9361_dac_upack_dac_data_03', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_3', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 4 IN', ...
        'InterfaceType',  'IN', ...
        'PortName',       'util_ad9361_dac_upack_dac_data_04', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_4', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 5 IN', ...
        'InterfaceType',  'IN', ...
        'PortName',       'util_ad9361_dac_upack_dac_data_05', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_5', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 6 IN', ...
        'InterfaceType',  'IN', ...
        'PortName',       'util_ad9361_dac_upack_dac_data_06', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_6', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Data 7 IN', ...
        'InterfaceType',  'IN', ...
        'PortName',       'util_ad9361_dac_upack_dac_data_07', ...
        'PortWidth',      16, ...
        'InterfaceConnection', 'util_ad9361_dac_upack/dac_data_7', ...
        'IsRequired',     false);

    hRD.addInternalIOInterface( ...
        'InterfaceID',    'IP Valid Tx Data IN', ...
        'InterfaceType',  'IN', ...
        'PortName',       'util_dac_unpack_upack_valid_00', ...
        'PortWidth',      1, ...
        'InterfaceConnection', 'util_ad9361_dac_upack/dac_valid_out_0', ...
        'IsRequired',     false);
end

author: analogdevicesinc