text:
function f = conj(f)
%CONJ   Complex conjugate of a SEPARABLEAPPROX.
%   CONJ(F) returns the complex conjugate of F.  For a complex F, CONJ(F) =
%   REAL(F) - i*IMAG(F).
%
% See also REAL, IMAG.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Check for empty SEPARABLEAPPROX.
if ( isempty( f ) )
   return
end

% TODO: Write down the formulas for conj, instead of calling the
% constructor.

f = compose( f, @conj );

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
%{
    Copyright (C) Cambridge Electronic Design Limited 2014
    Author: James Thompson
    Web: www.ced.co.uk email: james@ced.co.uk, softhelp@ced.co.uk

    This file is part of CEDS64ML, a MATLAB interface to the SON64 library.

    CEDS64ML 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.

    CEDS64ML 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 CEDS64ML.  If not, see <http://www.gnu.org/licenses/>.
%}

function [ iOk, sCommentOut ] = CEDS64ChanComment( fhand, iChan, sCommentIn )
%CEDS64CHANCOMMENT Gets and sets the comment for a channel
%   [ iOk, sCommentOut ] = CEDS64ChanComment( fhand, iChan {, sCommentIn} )
%   fhand - An integer handle to an open file
%   iChan - A channel number
%   sCommentIn - (Optional) A string containing the new comment
%   Output
%   iOk - 0 if the comment was set correctly otherwise a negative error code
%   sCommentOut - A string containing the old comment

if (nargin == 2 || nargin == 3) % always get the comment
    %step 1 find out how big the comment is
    dummystring = blanks(1);
    [iSize] = calllib('ceds64int', 'S64GetChanComment', fhand, iChan, dummystring, -1);
    %step 2 create a string buffer of the correct size
    stringptr = blanks(iSize+1);
    [iOk, sCommentOut] = calllib('ceds64int', 'S64GetChanComment', fhand, iChan, stringptr, 0);
else
    iOk = -22;
end

% has there been an error?
if iOk < 0
    return;
end

% if not set the comment if we're given one
if (nargin == 3)
    iOk = calllib('ceds64int', 'S64SetChanComment', fhand, iChan, sCommentIn);
end
end

author: brainstorm-tools


text:
function [label] = atlas_lookup(atlas, pos, varargin)

% ATLAS_LOOKUP determines the anatomical label of a location in the given atlas.
%
% Use as
%   label = atlas_lookup(atlas, pos, ...);
%
% Optinal input arguments should come in key-value pairs and can include
%   'method'       = 'sphere' (default) searches surrounding voxels in a sphere
%                    'cube' searches surrounding voxels in a cube
%   'queryrange'   = number, should be 1, 3, 5, 7, 9 or 11 (default = 3)
%   'coordsys'     = 'mni' or 'tal' (default = [])
%
% Dependent on the coordinates if the input points and the coordinates of the atlas,
% the input positions are transformed betweem MNI and Talairach-Tournoux coordinates.
% See http://www.mrc-cbu.cam.ac.uk/Imaging/Common/mnispace.shtml for more details.

% Copyright (C) 2005-2020, Robert Oostenveld
%
% 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$

% get the optional input arguments
method      = ft_getopt(varargin, 'method', 'sphere');
queryrange  = ft_getopt(varargin, 'queryrange', 3);
coordsys    = ft_getopt(varargin, 'coordsys');

if isempty(coordsys)
  ft_error('you must specify coordsys');
end

if isempty(intersect(queryrange, 1:2:queryrange))
  ft_error('incorrect query range, should be an odd number');
end

if size(pos,1)==3 && size(pos,2)~=3
  % transpose the input positions to get Nx3
  pos = pos';
end

% determine which field(s) to use to look up the labels,
% and whether these are boolean or indexed
fn = fieldnames(atlas);
isboolean = false(numel(fn),1);
isindexed = false(numel(fn),1);
for i=1:length(fn)
  if islogical(atlas.(fn{i})) && isequal(size(atlas.(fn{i})), atlas.dim)
    isboolean(i) = true;
  elseif isnumeric(atlas.(fn{i})) && isequal(size(atlas.(fn{i})), atlas.dim)
    isindexed(i) = true;
  end
end
if any(isindexed)
  % let the indexed prevail
  fn = fn(isindexed);
  isindexed = 1;
elseif any(isboolean)
  % use the boolean
  fn = fn(isboolean);
  isindexed = 0;
end

% convert between MNI head coordinates and TAL head coordinates
% coordinates should be expressed compatible with the atlas
if     strcmp(coordsys, 'mni') && strcmp(atlas.coordsys, 'tal')
  pos = mni2tal(pos')'; % this function likes 3xN
elseif strcmp(coordsys, 'mni') && strcmp(atlas.coordsys, 'mni')
  % nothing to do
elseif strcmp(coordsys, 'tal') && strcmp(atlas.coordsys, 'tal')
  % nothing to do
elseif strcmp(coordsys, 'tal') && strcmp(atlas.coordsys, 'mni')
  pos = tal2mni(pos')'; % this function likes 3xN
elseif ~strcmp(coordsys, atlas.coordsys)
  ft_error('the mismatch between the coordinate system in the atlas and the coordinate system in the data cannot be resolved');
end

num = size(pos,1);
sel = cell(1,numel(fn));
label = {};

% convert the atlas head coordinates into voxel coordinates
vox  = ft_warp_apply(inv(atlas.transform), pos);

for i=1:num

  % this is the center voxel
  ijk_center = vox(i,:);

  if isindexed
    if strcmp(method, 'sphere')
      % search in a sphere around the center voxel

      % first, identify the voxels (x,y,z) in a sphere around the center voxel
      [x, y, z] = sphere(1000);
      ori = [0 0 0];
      ptswithinq = [];
      for r = 0:(queryrange/2 - 0.5)
        xs = round(r*x(:));
        ys = round(r*y(:));
        zs = round(r*z(:));
        pts = unique([xs ys zs], 'rows');

        spherepts = [];
        for a = 1:size(pts,1)
          d2ori = sqrt(sum((pts(a, :)-ori).^2));
          if d2ori <= r
            spherepts = [spherepts; pts(a, :)];
          end
        end

        ptswithinr = []; % voxels located at a radius of r voxels from the center voxel
        for n = 1:size(spherepts,1)
          ptswithinr = [ptswithinr; spherepts(n, 1)+ijk_center(1), spherepts(n, 2)+ijk_center(2), spherepts(n,3)+ijk_center(3)];
        end

        ptswithinq = [ptswithinq; ptswithinr]; % voxels within a radius of queryrange from the center voxel
      end
      ptswithinq = unique(round(ptswithinq), 'rows');

      for n = 1:size(ptswithinq,1)
        ijk = ptswithinq(n, :);
        if ijk(1)>=1 && ijk(1)<=atlas.dim(1) && ...
            ijk(2)>=1 && ijk(2)<=atlas.dim(2) && ...
            ijk(3)>=1 && ijk(3)<=atlas.dim(3)
          for k=1:numel(fn)
            sel{k} = [sel{k}; atlas.(fn{k})(ijk(1), ijk(2), ijk(3))];
          end
        else
          ft_warning('location is outside atlas volume');
        end
      end

    elseif strcmp(method, 'cube')
      % search in a cube around the center voxel
      for di=(-(queryrange-1)/2):1:((queryrange-1)/2)
        for dj=(-(queryrange-1)/2):1:((queryrange-1)/2)
          for dk=(-(queryrange-1)/2):1:((queryrange-1)/2)

            % search in a cube around the center voxel
            ijk = round(ijk_center + [di dj dk]);

            if ijk(1)>=1 && ijk(1)<=atlas.dim(1) && ...
                ijk(2)>=1 && ijk(2)<=atlas.dim(2) && ...
                ijk(3)>=1 && ijk(3)<=atlas.dim(3)
              for k=1:numel(fn)
                sel{k} = [sel{k}; atlas.(fn{k})(ijk(1), ijk(2), ijk(3))];
              end
              %brick0_val = atlas.brick0(ijk(1), ijk(2), ijk(3));
              %brick1_val = atlas.brick1(ijk(1), ijk(2), ijk(3));
              %sel = [sel; find(atlas.descr.brick==0 & atlas.descr.value==brick0_val)];
              %sel = [sel; find(atlas.descr.brick==1 & atlas.descr.value==brick1_val)];
            else
              ft_warning('location is outside atlas volume');
            end % k
            %FIXME the three loops can probably be easily vectorized
          end % dk
        end % dj
      end % di
    end

    for k = 1:numel(fn)
      if ~isempty(sel{k})
        % Get rid of zeros in sel{k}
        for t = numel(sel{k}):-1:1
          if sel{k}(t) == 0
            sel{k}(t) = [];
          end
        end
        label = [label; atlas.([fn{k} 'label'])(sel{k})]; % by using setdiff and/or unique, the count for each label is lost, and ft_volumelookup cannot provide an accurate number for labels.count
      end
    end
  else
    ft_error('support for atlases that have a probabilistic segmentationstyle is not supported yet');
  end
end

%label = unique(atlas.descr.name(sel));

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
%{
 * Copyright (C) 2020-2030, The Regents of The University of Michigan.
 * All rights reserved.
 * This software was developed in the Biped Lab (https://www.biped.solutions/)
 * under the direction of Jessy Grizzle, grizzle@umich.edu. This software may
 * be available under alternative licensing terms; contact the address above.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. 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.
 * 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.
 * The views and conclusions contained in the software and documentation are those
 * of the authors and should not be interpreted as representing official policies,
 * either expressed or implied, of the Regents of The University of Michigan.
 *
 * AUTHOR: Bruce JK Huang (bjhuang[at]umich.edu)
 * WEBSITE: https://www.brucerobot.com/
%}

function line = point3DToLineForDrawing(points)
    line = [points(1,1), points(2,1), points(3,1);
        points(1,2), points(2,2), points(3,2);
        points(1,2), points(2,2), points(3,2)
        points(1,4), points(2,4), points(3,4);
        points(1,4), points(2,4), points(3,4);
        points(1,3), points(2,3), points(3,3);
        points(1,1), points(2,1), points(3,1)]';
end

author: UMich-BipedLab


text:
% Li, Hui and Wu, Xiao-Jun and Durrani, Tariq S. Infrared and Visible Image Fusion with ResNet and zero-phase component analysis
% Infrared Physics & Technology, v102, 2019.
% ResNet50 + ZCA & norm(l1, l2, nuclear)

clear all
clc

addpath(genpath('D:\develop\matconvnet\matlab\')); % matconvnet path
% load the pre-trained model - ResNet-50
model_path = './models/';
% http://www.vlfeat.org/matconvnet/pretrained/
net_ = load([model_path, 'imagenet-resnet-50-dag.mat']);
net = dagnn.DagNN.loadobj(net_);
net.mode = 'test';
%% remove layers - ResNet50
% Conv5 - res5cx
for i = 173:175
    net.removeLayer(net.layers(173).name);
end
net_res5cx = net;
% Conv4 - res4fx
net = dagnn.DagNN.loadobj(net_);
net.mode = 'test';
for i = 141:175
    net.removeLayer(net.layers(141).name);
end
net_res4fx = net;

%% Start
n = 20; % number of sourc image
time = zeros(n,1);

% testing dataset
test_path_ir = './IV_images/IR/';
fileFolder_ir=fullfile(test_path_ir);
dirOutput_ir =dir(fullfile(fileFolder_ir,'*'));
num_ir = length(dirOutput_ir);

test_path_vis = replace(test_path_ir, '/IR/', '/VIS/');
fileFolder_vis=fullfile(test_path_vis);
dirOutput_vis =dir(fullfile(fileFolder_vis,'*'));

for i=3:num_ir
    index = i;
    disp(num2str(index));

    % infrared and visible images
    path1 = [test_path_ir,dirOutput_ir(i).name]; % IR image
    path2 = [test_path_vis,dirOutput_vis(i).name]; % VIS image

    % block - 5*5
    % l1 norm
    fuse_path5 = ['./fused_iv/fused_resnet_zca_',dirOutput_ir(i).name];

    image1 = imread(path1);
    image2 = imread(path2);
    image1 = im2double(image1);
    image2 = im2double(image2);

    tic;
    %% Extract features, run the net - ResNet50
    disp('ResNet');
    if size(image1, 3)<3
        I1 = make_3c(image1);
    end
    if size(image2, 3)<3
        I2 = make_3c(image2);
    end
    I1 = single(I1) ; % note: 255 range
    I2 = single(I2) ; % note: 255 range

    % I1
    disp('run the ResNet - I1');
    net_res4fx.eval({'data', I1}) ;
    output4_1 = net_res4fx.vars(net_res4fx.getVarIndex('res4fx')).value ;
    net_res5cx.eval({'data', I1}) ;
    output5_1 = net_res5cx.vars(net_res5cx.getVarIndex('res5cx')).value ;
    % I2
    disp('run the ResNet - I2');
    net_res4fx.eval({'data', I2}) ;
    output4_2 = net_res4fx.vars(net_res4fx.getVarIndex('res4fx')).value ;
    net_res5cx.eval({'data', I2}) ;
    output5_2 = net_res5cx.vars(net_res5cx.getVarIndex('res5cx')).value ;

    %% extract features - ZCA & l1-norm operation
    disp('extract features(whitening operation) - I1');
    feature4_1 = whitening_norm(output4_1);
    feature5_1 = whitening_norm(output5_1);
    disp('extract features(whitening operation) - I2');
    feature4_2 = whitening_norm(output4_2);
    feature5_2 = whitening_norm(output5_2);

    %% fusion strategy - resize to original size and soft-max
    disp('fusion strategy(weighting)');
    % output4 - 1024
    [F_relu4, weight4_a, weight4_b] = fusion_strategy(feature4_1, feature4_2, image1, image2);
    % output5 - 2048
    [F_relu5, weight5_a, weight5_b] = fusion_strategy(feature5_1, feature5_2, image1, image2);
    time(i) = toc;

%     imwrite(F_relu4,fuse_path4,'png');
    imwrite(F_relu5,fuse_path5,'png');
end

author: thfylsty


text:
function dtiRawEddyCorrect(dwRaw, mnB0, outEddyCorrectXform)
%
% dtiRawEddyCorrect([dwRaw=uigetfile], [mnB0=uigetfile], [outEddyCorrectXform])
%
% Aligns each raw DW image in dwRaw (NIFTI format) to the mean
% b=0 image, saving all the resulting xforms in outEddyCorrectXform.
%
% HISTORY:
% 2007.04.23 RFD: wrote it.

% Initialize SPM default params
spm_defaults; global defaults;
estParams = defaults.coreg.estimate;

%% Load the raw DW data (in NIFTI format)
if(~exist('dwRaw','var')|isempty(dwRaw))
    [f,p] = uigetfile({'*.nii.gz;*.nii';'*.*'}, 'Select the raw DW NIFTI dataset...');
    if(isnumeric(f)) error('User cancelled.'); end
    dwRaw = fullfile(p,f);
end
if(ischar(dwRaw))
    % dwRaw can be a path to the file or the file itself
    [dataDir,inBaseName] = fileparts(dwRaw);
else
    [dataDir,inBaseName] = fileparts(dwRaw.fname);
end
[junk,inBaseName,junk] = fileparts(inBaseName);
if(isempty(dataDir)) dataDir = pwd; end

% Load the b0 data (in NIFTI format)
if(~exist('mnB0','var')|isempty(mnB0))
   mnB0 = fullfile(dataDir, [inBaseName '_b0.nii.gz']);
   [f,p] = uigetfile({'*.nii.gz;*.nii';'*.*'}, 'Select the mean b0 NIFTI dataset...',mnB0);
   if(isnumeric(f)) error('User cancelled.'); end
   mnB0 = fullfile(p,f);
end
if(ischar(mnB0))
    disp(['Loading b0 data ' mnB0 '...']);
    mnB0 = niftiRead(mnB0);
end

if(~exist('outEddyCorrectXform','var')|isempty(outEddyCorrectXform))
    outEddyCorrectXform = fullfile(dataDir,[inBaseName 'EcXform']);
end

if(ischar(dwRaw))
    disp(['Loading raw data ' dwRaw '...']);
    dwRaw = niftiRead(dwRaw);
end

nvols = size(dwRaw.data,4);
dtMm = dwRaw.pixdim(1:3);

%% Eddy correction (will also correct for motion)
% Compute an affine xform to align each DW image to the mean B0
% image.
% Affine (12-params)
estParams.params = [0 0 0 0 0 0 1 1 1 0 0 0];
estParams.sep = [2];
target.uint8 = uint8(round(mrAnatHistogramClip(double(mnB0.data),0.4,0.99)*255));
target.mat = [diag(dtMm), [-[size(target.uint8)/2].*dtMm]'; 0 0 0 1];
source.mat = target.mat;
for(ii=1:nvols)
    fprintf('Aligning vol %d of %d to mean b=0 image', ii, nvols);
    if(ii>2)
        % Skip the first since it's usually the reference.
        estRemain = mean(et(2:end))*(nvols-ii+1)./60;
        if(estRemain>90) estRemain = estRemain./60; estUnits = 'hours';
        else estUnits = 'minutes'; end
        fprintf(' (previous iteration took %0.1f secs; %0.1f %s remaining)...\n',et(ii-1),estRemain,estUnits);
    else
        fprintf('\n');
    end
    tic;
    im = double(dwRaw.data(:,:,:,ii));
    source.uint8 = uint8(round(mrAnatHistogramClip(im,0.4,0.99)*255));
    msg = evalc('xformParams = spm_coreg(source,target,estParams);');
    xform{ii} = inv(target.mat)*spm_matrix(xformParams)*source.mat;
    et(ii) = toc;
end
disp(['Saving eddy/motion correction transforms to ' outEddyCorrectXform '...']);
disp('These transforms map voxels in each of the volumes to the reference image (usually the mean b=0).');
save(outEddyCorrectXform, 'xform');
fn = [outEddyCorrectXform '.txt'];
dlmwrite(fn,xform{1},'delimiter',' ','precision',6);
for(ii=2:length(xform))
    dlmwrite(fn,xform{ii},'delimiter',' ','roffset',1,'-append','precision',6);
end

return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function varargout = choose_method(varargin)
% CHOOSE_METHOD M-file for choose_method.fig
%      CHOOSE_METHOD, by itself, creates a new CHOOSE_METHOD or raises the existing
%      singleton*.
%
%      H = CHOOSE_METHOD returns the handle to a new CHOOSE_METHOD or the handle to
%      the existing singleton*.
%
%      CHOOSE_METHOD('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in CHOOSE_METHOD.M with the given input arguments.
%
%      CHOOSE_METHOD('Property','Value',...) creates a new CHOOSE_METHOD or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before choose_method_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to choose_method_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

% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology

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

% Last Modified by GUIDE v2.5 25-Jul-2008 10:40:42

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

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

% --- Executes just before choose_method is made visible.
function choose_method_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 choose_method (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

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

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

% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
vl=get(hObject,'Value');
switch vl
    case 1
        str='CorrDim';
    case 2
        str='NearNbDim';
    case 3
        str='GMST';
    case 4
        str='PackingNumbers';
    case 5
        str='EigValue';
    case 6
        str='MLE';
end
set(handles.str,'string',str);
drawnow;

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

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

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

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

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

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

% --- Executes on button press in ok.
function ok_Callback(hObject, eventdata, handles)
uiresume(handles.figure1);

repo: cluster


text:
classdef Filter_LevelSet < Filter

    properties (Access = protected)

    end

    methods (Access = public)

    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function lib( libInfo )
% Engine Cooling Components library

% Copyright 2012 The MathWorks, Inc.

    libInfo.Annotation = sprintf('Custom thermal fluid library used by the example model ssc_engine_cooling_system');
end

author: Sable

repo: mcbench-benchmarks


text:
function D = deleteObjectsOutsideFrame(D, HOMEIMAGES)
%
% mark as deleted objects with a center of mass outside the image
%

for j = 1:length(D)
    %info = imfinfo(strrep(strrep(fullfile(HOMEIMAGES, D(j).annotation.folder, D(j).annotation.filename), '\', '/'), ' ', '%20'));
    info = imfinfo(strrep(fullfile(HOMEIMAGES, D(j).annotation.folder, D(j).annotation.filename), '\', '/'));
    nrows = info.Height;
    ncols = info.Width;

    % Change the size of the polygon coordinates
    if isfield(D(j).annotation, 'object')
        Nobjects = length(D(j).annotation.object);
        for i = 1:Nobjects
            [x,y] = getLMpolygon(D(j).annotation.object(i).polygon);

            xm = mean(x);
            ym = mean(y);

            if xm<1 || ym<1 || xm>ncols || ym>nrows
                D(j).annotation.object(i).deleted = '1';
            end
        end
    end
end

author: CSAILVision

repo: LabelMeToolbox


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
%==============================================================================
%
% KERNEL/DATA
%
% This folder provides the basis data (examples) that come with the toolbox
% and some convenient tools for handling the data;
% see also references at the end of the mfiles
%
% To get the data "X" (e.g. 2DHandData), conveniently run setup"X";
% e.g. setup2DHandData.
% For faster access, the generated data is saved in an automatically
% generated file in the temp folder and later simply re-used.
%
%------------------------------------------------------------------------------
%
% The following examples are available:
%
% 2D data:
%   2Dhands     -  hand xrays,                  see ref. [1] and setup2DHandData
%   2DHNSP      -  brain serial sectioning,     see ref. [2] and setup2DHNSPData
%   2DMRIs      -  MR slices from human brain,  see ref. [3] and setup2DMRIData
%   2DPETCT     -  PET-CT study,                see ref. [4] and setup2DPETCTdata
%   2DUS        -  US image of Vibe Heldmann,
%                  courtesy by Dr. Stefan Heldmnn, Fraunhofer MEVIS, Lübeck
%   2Ddisc2C    -  binary images of a disc and a C a la Gary Christensen,
%                  test case for large deformations, academic testcase
%   2DGaussian  -  Gaussian blobs, test-case for mass-preserving schemes,
%                  academic testcase
%
% 3D data:
%   3Dbrains    -  MRI data of a human brain,
%                  data courtesy Ron Kikinis, Brigham & Women's Hospital, Boston, USA
%   3Dknees     -  MRI data from a human knee,
%                  data courtesy Thomas Netsch, Philips Medical Solutions, Hamburg
%   3Dmice      -  PET data of a mouse heart,
%                  data courtesy European Institute for Molecular Imaging (EIMI),
%                  University of Muenster, Germany
%   3Dboxes     -  academical example with deformed binary boxes
%
% Tools (M-files)
%
%   setup2DhandData     - requires hands-T.jpg,     hands-R.jpg
%   setup2DHNSPData     - requires HNSP-T.jpg,      HNSP-R.jpg
%   setup2DMRIData      - requires MRIhead-T.jpg,   MRIhead-R.jpg
%   setup2DPETCTData    - requires PET-CT-CT.jpg,   PET-CT-PET.jpg
%   setup2DUSData       - requires US.jpg
%   setup2Ddisc2CData   - requires disc.jpg and c.jpg
%   setup2DGaussianData - requires Gauss-T.jpg, Gauss-r.jpg
%   setup3DbrainData    - requires brain3D.mat
%   setup3DkneeData     - requires createPhilipsKnees.mat
%   setup3DmouseData    - requires mice3D.mat
%   setup3DboxData      - academic, a box
%
%------------------------------------------------------------------------------
% More tools:
%   contents            -  this file
%   checkDataFile       -  in the first run, the data is saved and later simply
%                          loaded for faster access,
%                          this file handles the administration
%   jpgs2data           -  convenient tool to convert two jpgs files into the
%                          FAIR data structure
%   testData            -  tests this part of the toolbox
%
%------------------------------------------------------------------------------
% JPG files:
%   Gauss-R.jpg,           Gauss-T.jpg
%   HNSP-R.jpg             HNSP-T.jpg
%   MRIhead-R.jpg          MRIhead-T.jpg
%   PET-CT-CT.jpg          PET-CT-PET.jpg
%   c.jpg                  disc.jpg
%   hands-R.jpg            hands-T.jpg
%   US.jpg
%   EPIslice-R.jpg         EPIslice-T.jpg [5]
%
% MAT files:
%   brain3D.mat
%   knees3D.mat
%   mice3D.mat
%
%
% [5] 2D slices of MR images, Institute of Clinical Radiology, Univesity
%     Hospital Muenster, Germany.
%   phantom3D.mat
%     MR data of a hardware phantom,
% Institute for Clinical Radiology, University Hospital Muenster, Germany
% for data sources see the corresponding setup file
%
%==============================================================================

function debit = contents
if nargout == 0,
  help(mfilename);
  return;
end;

debit = {
  'contents.m'
  'checkDataFile.m'
  'jpgs2data.m'

  'setup2DGaussianData.m'
  'setup2DHNSPData.m'
  'setup2DMRIData.m'
  'setup2DPETCTData.m'
  'setup2DUSData.m'
  'setup2Ddisc2CData.m'
  'setup2DhandData.m'
  'setup3DboxData.m'
  'setup3DbrainData.m'
  'setup3DkneeData.m'
  'setup3DmouseData.m'

  'testData.m'

  'Gauss-R.jpg'
  'Gauss-T.jpg'
  'HNSP-R.jpg'
  'HNSP-T.jpg'
  'MRIhead-R.jpg'
  'MRIhead-T.jpg'
  'PET-CT-CT.jpg'
  'PET-CT-PET.jpg'
  'US.jpg'
  'c.jpg'
  'disc.jpg'
  'hands-R.jpg'
  'hands-T.jpg'
  'brain3D.mat'
  'EPIslice-R.jpg'
  'EPIslice-T.jpg'
  'knee3D.mat'
  'mice3D.mat'
  'phantom3D.mat'
  };
%==============================================================================


text:
% TESTFITLINE - demonstrates RANSAC line fitting
%
% Usage: testfitline(outliers, sigma, t, feedback)
%
% Arguments:
%               outliers - Fraction specifying how many points are to be
%                          outliers.
%               sigma    - Standard deviation of inlying points from the
%                          true line.
%               t        - Distance threshold to be used by the RANSAC
%                          algorithm for deciding whether a point is an
%                          inlier.
%               feedback - Optional flag 0 or 1 to turn on RANSAC feedback
%                          information.
%
%  Try using:  testfit3Dline(0.3, 0.05, 0.05)
%
% See also: RANSACFITPLANE, FITPLANE

% Copyright (c) 2003-2006 Peter Kovesi and Felix Duvallet (CMU)
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.

% August 2006  testfitline created from testfitplane
%              author: Felix Duvallet

function testfit3Dline(outliers, sigma, t, feedback)

    close all;

    if nargin == 3
        feedback = 0;
    end

    % Hard wire some constants - vary these as you wish

    npts = 100;  % Number of 3D data points

    % Define a line:
    %    Y = m*X
    %    Z = n*X + Y + b
    % This definition needs fixing, but it works for now

    m = 6;
    n = -3;
    b = -4;

    outsigma = 30*sigma;  % outlying points have a distribution that is
                          % 30 times as spread as the inlying points

    vpts = round((1-outliers)*npts);  % No of valid points
    opts = npts - vpts;               % No of outlying points

    % Generate npts points in the line
    X = rand(1,npts);

    Y = m*X;
    Z = n*X + Y + b;
    Z = zeros(size(Y));

    XYZ =  [X
    	    Y
    	    Z];

    % Add uniform noise of +/-sigma
    XYZ = XYZ + (2*rand(size(XYZ))-1)*sigma;

    % Generate opts random outliers

    n = length(XYZ);
    ind = randperm(n);  % get a random set of point indices
    ind = ind(1:opts);  % ... of length opts

    % Add uniform noise of outsigma to the points chosen to be outliers.
    XYZ(:,ind) = XYZ(:,ind)  +   sign(rand(3,opts)-.5).*(rand(3,opts)+1)*outsigma;

    % Perform RANSAC fitting of the line
    [V, P, inliers] = ransacfit3Dline(XYZ, t, feedback);

    if(feedback)
        disp(['Number of Inliers: ' num2str(length(inliers)) ]);
    end

    % We want to plot the inlier points blue, with the outlier points in
    % red.  In order to do that, we must find the outliers.
    % Use setxor on all the points, and the inliers to find outliers
    %  (plotting all the points in red and then plotting over them in blue
    %  does not work well)
    oulier_points = setxor(transpose(XYZ), transpose(XYZ(:, inliers)), 'rows');
    oulier_points = oulier_points';

    % Display the cloud of outlier points
    figure(1); clf
    hold on;
    plot3(oulier_points(1,:),oulier_points(2,:),oulier_points(3,:), 'r*');

    % Plot the inliers as blue points
    plot3(XYZ(1,inliers), XYZ(2, inliers), XYZ(3, inliers), 'b*');

    % Display the line formed by the 2 points that gave the
    % line of maximum consensus as a green line
    line(P(1,:), P(2,:), P(3,:), 'Color', 'green', 'LineWidth', 4);

    %Display the line formed by the covariance fitting in magenta
    line(V(1,:), V(2, :), V(3,:), 'Color', 'magenta', 'LineWidth', 5);

    box('on'), grid('on'), rotate3d('on')

author: DrGabor

repo: LiDAR

save_path: github-repos/MATLAB/DrGabor-LiDAR


text:
function [imgOut, FC_MAX_L] = FalseColor(img, FC_compress, FC_Vis, FC_LMax, FC_figure, FC_title, FC_lin, FC_title_color_map)
%
%
%       [imgOut, FC_MAX_L] = FalseColor(img, compress, FC_Vis, LMax)
%
%       This function creates a false color image for re-mapping luminance
%       into an LDR RGB image.
%
%       Input:
%           -img: the input img
%           -FC_compress: compression option for HDR images:
%               -'lin': no compression to the dynamic range (it typically creates
%               good results for LDR images only!)
%               -'log': the HDR domain is compressed using natural
%               logarithm (default parameter)
%               -'log2': the HDR domain is compressed using base 2
%               logarithm
%               -'log10': the HDR domain is compressed using base 10
%               logarithm
%               -'sigmoid': the HDR domain is compressed using a basic
%               sigmoid curve
%           -FC_Vis: a boolean parameter. If it is set to 1, it will show.
%           Default values is 1, so the image will visualized
%           the image as a complete figure including the visualization bar
%           -FC_LMax: the maximum luminance for the color re-mapping functions.
%               This needs to be used when creating false color images with the same scale.
%           -FC_figure: index for the figure
%           -FC_title: title for the false color window
%           -FC_lin: linear scale or exponential one.
%           -FC_title_color_map: color map unit
%
%       Output:
%           -imgOut: the false color LDR and RGB image (no gamma is
%           required for visualization purposes)
%           -FC_MAX_L: the maxium luminance value in the selected
%           FC_compress domain
%
%     Copyright (C) 2011-17 Francesco Banterle
%
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.
%

L = lum(img);

if(~exist('FC_Vis', 'var'))
    FC_Vis = 1;
end

if(~exist('FC_compress', 'var'))
    FC_compress = 'log';
end

if(~exist('FC_figure', 'var'))
    FC_figure = 1;
end

if(~exist('FC_title', 'var'))
    FC_title = 'False color visualization';
end

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

if(~exist('FC_title_color_map', 'var'))
    FC_title_color_map = 'Lux';
end

%minimum luminance
LMin = min(L(:));

%maximum luminance
if(~exist('FC_LMax', 'var'))
    LMax = max(L(:));
else
    if(FC_LMax < 0)
        LMax = max(L(:));
    else
        tLMax = max(L(:));
        if(FC_LMax < tLMax)
            LMax = tLMax;
        else
            LMax = FC_LMax - LMin;
        end
    end
end

FC_MAX_L = LMax;

%luminance compression
epsilon = 1e-6; %for avoiding singularities
switch FC_compress
    case 'log2'
        L = log2(L + epsilon);
        LMax = log2(LMax + epsilon);
        LMin = log2(LMin + epsilon);

    case 'log'
        L = log(L + epsilon);
        LMax = log(LMax + epsilon);
        LMin = log(LMin + epsilon);

    case 'log10'
        L = log10(L + epsilon);
        LMax = log10(LMax + epsilon);
        LMin = log10(LMin + epsilon);

    case 'sigmoid'
        L = (L ./ (L + 1.0)).^(1.0 / 2.2);
        LMax = (LMax ./ (LMax + 1.0)).^(1.0 / 2.2);
        LMin = (LMin ./ (LMax + 1.0)).^(1.0 / 2.2);

    otherwise
end

%creating ticks for the visualization
if(FC_Vis)
    delta = LMax - LMin;
    yticks = LMin:(delta / 4):LMax;

    switch FC_compress
        case 'log2'
            yticks = 2.^yticks - epsilon;
        case 'log'
            yticks = exp(yticks) - epsilon;
        case 'log10'
            yticks = 10.^yticks - epsilon;
        case 'sigmoid'
            yticks = yticks.^2.2;
            yticks = yticks ./ (1.0 - yticks);
        otherwise
    end
end

L = L - LMin;
LMax = LMax - LMin;
L = L / LMax;

contrast = 1.0;
L = L.^(1.0 / contrast);

%Create a color map
n_bit = 8;
res = 2^n_bit;
color_map = colormap(jet(res));
%color_map = ldrimread('fc_colormap.png');

%Coloring using the colormap
L = ClampImg(round(L * res), 1, res);
imgOut = ind2rgb(L, color_map);

if(FC_Vis)%Visualization
    close(FC_figure);
    h = figure(FC_figure);
    axes1 = axes('Parent', h);
    axis off
    hold(axes1,'on');

    set(h, 'Name', FC_title);

    image(imgOut, 'Parent', axes1);%'InitialMagnification', 'fit');
    colormap(color_map);

    box(axes1,'on');
    axis(axes1,'ij');
    set(axes1,'DataAspectRatio',[1 1 1],'Layer','top','TickDir','out');

    if(FC_lin)
        str = {sprintf('%2.1f', yticks(1)), sprintf('%2.1f', yticks(2)), sprintf('%2.1f', yticks(3)), sprintf('%2.1f', yticks(4)), sprintf('%2.1f', yticks(5))};
    else
        str = {sprintf('%2.1e', yticks(1)), sprintf('%2.1e', yticks(2)), sprintf('%2.1e', yticks(3)), sprintf('%2.1e', yticks(4)), sprintf('%2.1e', yticks(5))};
    end

    hcb = colorbar('peer',axes1, 'Position',...
    [0.743515850144089 0.299424184261036 0.0374639769452479 0.566218809980805],...
    'Ticks',[0 0.25 0.5 0.75 1],...
    'Ticks', 0:(1/4):1 ,'YtickLabel', str);%, 'Position',...
%    [0.329470198675497 0.345738295318127 0.302152317880795 0.0261944917126994]);

    set(hcb, 'FontSize', 24);
    set(hcb, 'FontName', 'Times New Roman');

    pos = hcb.Position;
    set(get(hcb, 'XLabel'), 'Rotation', 0, 'String', FC_title_color_map, 'FontSize', 24, 'FontName', 'Times New Roman', 'Position', [pos(1), 0.0 , 0.0]);
    hold(axes1,'off');

end

end

author: banterle


text:
% mff_importevents - import information from MFF 'eventsxxxxx.xml'
%                    files. If several files are detected, information
%                    from all files is imported.
%
% Usage:
%   [events, timezone] = mff_importevents(mffFile);
%
% Inputs:
%  mffFile - filename/foldername for the MFF file
%
% Output:
%  events   - EEGLAB event structure
%  timezone - time zone

% This file is part of mffmatlabio.
%
% mffmatlabio 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.
%
% mffmatlabio 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 mffmatlabio.  If not, see <https://www.gnu.org/licenses/>.

function [events, timeZone] = mff_importevents(mffFile, begTime, srate)

events = [];
timeZone = [];
p = fileparts(which('mff_importsignal.m'));
warning('off', 'MATLAB:Java:DuplicateClass');
javaaddpath(fullfile(p, 'MFF-1.2.2-jar-with-dependencies.jar'));
warning('on', 'MATLAB:Java:DuplicateClass');

% create a factory
mfffactorydelegate = javaObject('com.egi.services.mff.api.LocalMFFFactoryDelegate');
mfffactory = javaObject('com.egi.services.mff.api.MFFFactory', mfffactorydelegate);

% Create Signal object and read in event track file.
% Note that 3 is the value associated with the event track resource type.
eventFile = dir( fullfile(mffFile, 'Events_*.xml'));
if isempty(eventFile), return; end
timeZone = [];
eventCount = 1;
showWarning = true;

% use vararg2str to save events so they may be exported
eeglabExport = true;
if ~exist('vararg2str', 'file')
    eeglabExport = false;
end

for iEvent = 1:length(eventFile)
    eventtrackfilename = fullfile(mffFile, eventFile(iEvent).name);
    eventtracktype = javaObject('com.egi.services.mff.api.MFFResourceType', javaMethod('valueOf', 'com.egi.services.mff.api.MFFResourceType$MFFResourceTypes', 'kMFF_RT_EventTrack'));
    eventtrackObj = mfffactory.openResourceAtURI(eventtrackfilename, eventtracktype);

    if eventtrackObj.loadResource()

        name      = eventtrackObj.getName();
        trackType = eventtrackObj.getTrackType();
        eventlist = eventtrackObj.getEvents();
        nevents = eventlist.size();
        fprintf('Importing %d events from file %s...\n', nevents, eventFile(iEvent).name);

        % Read through each event track and inspect count of events
        % and beginTime for last event in each.
        if nevents>0

            multiplier = 24*60*60*srate;
            events(nevents).description = ''; % create last event

            for eventnum = 1:nevents

                eventObj = eventlist.get(eventnum-1);

                % Get keys for event and display key codes
                events(eventCount).begintime    = char(eventObj.getBeginTime());
                if events(eventCount).begintime(end-1) == '-'
                    events(eventCount).begintime = [ events(eventCount).begintime(1:end-1) '0' events(eventCount).begintime(end) ':00' ];
                elseif events(eventCount).begintime(end-2) == '-'
                    events(eventCount).begintime = [ events(eventCount).begintime(1:end-2) events(eventCount).begintime(end) ':00' ];
                end
                events(eventCount).classid      = char(eventObj.getClassID());
                events(eventCount).code         = char(eventObj.getCode());
                events(eventCount).description  = char(eventObj.getDescription());
                events(eventCount).duration     = eventObj.getDuration();
                events(eventCount).label        = char(eventObj.getLabel());
                events(eventCount).relativebegintime = eventObj.getRelativeBeginTime();
                events(eventCount).sourcedevice = char(eventObj.getSourceDevice());
                events(eventCount).name         = char(name);
                events(eventCount).tracktype    = char(trackType);

                % compute latency in days with ms -> convert to samples
                % eventCount = 1;
                events(eventCount).latency = (mff_decodetime(events(eventCount).begintime)-begTime)*multiplier;

                % dual time recoding
%                 tmp = mff_encodetime(events(eventCount).latency/multiplier+begTime, '08:00')
%                 fprintf('%s\n%s\n', events(eventCount).begintime, tmp);

                events(eventCount).type    = events(eventCount).code;

                % import keys
                keylist = eventObj.getKeys();
                events = mff_importkeys(events, eventCount, keylist, eeglabExport);

                eventCount = eventCount+1;

            end
        end
    else
        fprintf('Could not load event file %s\n', eventtrackfilename);
    end
end
if ~isempty(events)
    % get the time zone (duplicate code in mff_importevents and mff_importinfo)
    minusSign = find(events(end).begintime == '+');
    if isempty(minusSign)
        minusSign = find(events(end).begintime == '-');
        minusSign = minusSign(end);
    end
    timeZone = events(end).begintime(minusSign(end):end);
    if length(timeZone) > 6
        timeZone =  [];
        disp('Issue with decoding the time zone');
    end
end

% % same as above but 10% faster. Was not retained because the increased
% % complexitity. Does not support importing keys
%
% begintime         = cell(1,eventcount);
% classid           = cell(1,eventcount);
% code              = cell(1,eventcount);
% description       = cell(1,eventcount);
% duration          = cell(1,eventcount);
% label             = cell(1,eventcount);
% relativebegintime = cell(1,eventcount);
% sourcedevice      = cell(1,eventcount);
% eventkeys         = cell(1,eventcount);
% for eventnum = 1:eventcount
%
%     eventObj = eventlist.get(eventnum-1);
%
%     % Get keys for event and display key codes
%     begintime{eventnum}    = eventObj.getBeginTime();
%     classid{eventnum}      = eventObj.getClassID();
%     code{eventnum}         = eventObj.getCode();
%     description{eventnum}  = eventObj.getDescription();
%     duration{eventnum}     = eventObj.getDuration();
%     label{eventnum}        = eventObj.getLabel();
%     relativebegintime{eventnum} = eventObj.getRelativeBeginTime();
%     sourcedevice{eventnum} = eventObj.getSourceDevice();
%     eventkeys{eventnum}    = eventObj.getKeys();
%
% end
%
% disp('Converting events to Matlab format...')
% begintime    = cellfun(@(x)char(x), begintime, 'uniformoutput', false);
% begintime2   = cellfun(@(x)mff_decodetime(x), begintime, 'uniformoutput', false);
% classid      = cellfun(@(x)char(x), classid, 'uniformoutput', false);
% code         = cellfun(@(x)char(x), code, 'uniformoutput', false);
% description  = cellfun(@(x)char(x), description, 'uniformoutput', false);
% label        = cellfun(@(x)char(x), label, 'uniformoutput', false);
% relativebegintime = cellfun(@(x)char(x), relativebegintime, 'uniformoutput', false);
% sourcedevice = cellfun(@(x)char(x), sourcedevice, 'uniformoutput', false);
% eventkeys    = cellfun(@(x)char(x), eventkeys, 'uniformoutput', false);
%
% events = struct('begintime', begintime, 'latency', begintime2, 'classid', classid, 'code', code, 'description', description, ...
%                 'label', label, 'relativebegintime', relativebegintime, 'sourcedevice', sourcedevice, 'eventkeys', eventkeys);

% Save as above but not faster
% eventlist = eventlist.toArray;
% eventlist = cell(eventlist);
%
% begintime    = cellfun(@(x)char(x.getBeginTime()), eventlist, 'uniformoutput', false);
% begintime2   = cellfun(@(x)mff_decodetime(x), begintime, 'uniformoutput', false);
% classid      = cellfun(@(x)char(x.getClassID()), eventlist, 'uniformoutput', false);
% code         = cellfun(@(x)char(x.getCode()), eventlist, 'uniformoutput', false);
% description  = cellfun(@(x)char(x.getDescription()), eventlist, 'uniformoutput', false);
% label        = cellfun(@(x)char(x.getLabel()), eventlist, 'uniformoutput', false);
% sourcedevice = cellfun(@(x)char(x.getSourceDevice()), eventlist, 'uniformoutput', false);
% eventkeys    = cellfun(@(x)char(x.getKeys()), eventlist, 'uniformoutput', false);
%
% relativebegintime = cellfun(@(x)x.getRelativeBeginTime(), eventlist, 'uniformoutput', false);
% duration          = cellfun(@(x)x.getDuration(), eventlist, 'uniformoutput', false);
%
% events = struct('begintime', begintime, 'latency', begintime2, 'classid', classid, 'code', code, 'type', code, 'description', description, ...
%                 'label', label, 'duration', duration, 'relativebegintime', relativebegintime, 'sourcedevice', sourcedevice, 'eventkeys', eventkeys);


text:
function wts = cliqfs ( nt, t, kind, alpha, beta, lo )

%*****************************************************************************80
%
%% CLIQFS computes the weights of a quadrature formula in the default interval.
%
%  Discussion:
%
%    This routine computes the weights of an interpolatory quadrature formula
%    with a classical weight function, in the default interval A, B,
%    using only simple knots.
%
%    It can optionally print knots and weights and a check of the moments.
%
%    To evaluate a quadrature computed by CLIQFS, call EIQFS.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    05 January 2010
%
%  Author:
%
%    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Sylvan Elhay, Jaroslav Kautsky,
%    Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of
%    Interpolatory Quadrature,
%    ACM Transactions on Mathematical Software,
%    Volume 13, Number 4, December 1987, pages 399-415.
%
%  Parameters:
%
%    Input, integer NT, the number of knots.
%
%    Input, real T(NT), the knots.
%
%    Input, integer KIND, the rule.
%    1, Legendre,             (a,b)       1.0
%    2, Chebyshev Type 1,     (a,b)       ((b-x)*(x-a))^(-0.5)
%    3, Gegenbauer,           (a,b)       ((b-x)*(x-a))^alpha
%    4, Jacobi,               (a,b)       (b-x)^alpha*(x-a)^beta
%    5, Generalized Laguerre, (a,+oo)     (x-a)^alpha*exp(-b*(x-a))
%    6, Generalized Hermite,  (-oo,+oo)   |x-a|^alpha*exp(-b*(x-a)^2)
%    7, Exponential,          (a,b)       |x-(a+b)/2.0|^alpha
%    8, Rational,             (a,+oo)     (x-a)^alpha*(x+b)^beta
%    9, Chebyshev Type 2,     (a,b)       ((b-x)*(x-a))^(+0.5)
%
%    Input, real ALPHA, the value of Alpha, if needed.
%
%    Input, real BETA, the value of Beta, if needed.
%
%    Input, integer LO, chooses the printing option.
%     > 0, compute weights, print them, print the moment check results.
%     0, compute weights.
%     < 0, compute weights and print them.
%
%    Output, real WTS(NT), the weights.
%
  key = 1;

  mlt = zeros(nt,1);
  mlt(1:nt) = 1;

  ndx = zeros(nt,1);

  wts = ciqfs ( nt, t, mlt, nt, ndx, key, kind, alpha, beta, lo );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function cuts = knapsack_add_cover_cut(p,x,alg,upper)

if ~isinf(upper) && p.LinearBinaryPositiveCost
    % We can add a global knapsack from c'*x <= upper
    relevant_to_use = find(p.c & p.c <= upper);
    p.knapsack.a{end+1} = p.c(relevant_to_use);
    p.knapsack.b{end+1} = upper;
    p.knapsack.variables{end+1} = relevant_to_use;
    p.knapsack.type(end+1) = 0;
end

cuts = [];
for i = find(p.knapsack.type == 0)
    a = p.knapsack.a{i};
    b = p.knapsack.b{i};
    v = p.knapsack.variables{i};
    x_ = x(v);

    cut_ = knapsack_create_cover_cut(a,b,x_,alg,p.gubs);
    if ~isempty(cut_)
        cut = spalloc(1,length(p.c)+1,0);
        cut(1) = cut_(1);
        cut(1 + v) = cut_(2:end);
        cuts = [cuts;cut];
    end
end

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
function value = r8_si ( x )

%*****************************************************************************80
%
%% R8_SI evaluates the sine integral Si of an R8 argument.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 September 2011
%
%  Author:
%
%    Original FORTRAN77 version by Wayne Fullerton.
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Wayne Fullerton,
%    Portable Special Function Routines,
%    in Portability of Numerical Software,
%    edited by Wayne Cowell,
%    Lecture Notes in Computer Science, Volume 57,
%    Springer 1977,
%    ISBN: 978-3-540-08446-4,
%    LC: QA297.W65.
%
%  Parameters:
%
%    Input, real X, the argument.
%
%    Output, real VALUE, the sine integral Si evaluated at X.
%
  persistent nsi
  persistent sics
  persistent xsml

  if ( isempty ( nsi ) )

    sics = [ ...
      -0.1315646598184841928904275173000457, ...
      -0.2776578526973601892048287660157299, ...
       0.0354414054866659179749135464710086, ...
      -0.0025631631447933977658752788361530, ...
       0.0001162365390497009281264921482985, ...
      -0.0000035904327241606042670004347148, ...
       0.0000000802342123705710162308652976, ...
      -0.0000000013562997692540250649931846, ...
       0.0000000000179440721599736775567759, ...
      -0.0000000000001908387343087145490737, ...
       0.0000000000000016669989586824330853, ...
      -0.0000000000000000121730988368503042, ...
       0.0000000000000000000754181866993865, ...
      -0.0000000000000000000004014178842446, ...
       0.0000000000000000000000018553690716, ...
      -0.0000000000000000000000000075166966, ...
       0.0000000000000000000000000000269113, ...
      -0.0000000000000000000000000000000858 ]';

    nsi = r8_inits ( sics, 18, 0.1 * r8_mach ( 3 ) );
    xsml = sqrt ( r8_mach ( 3 ) );

  end

  absx = abs ( x );

  if ( absx < xsml )
    value = x;
  elseif ( absx <= 4.0 )
    value = x * ( 0.75 + r8_csevl ( ( x * x - 8.0 ) * 0.125, sics, nsi ) );
  else
    [ f, g ] = r8_sifg ( absx );
    cosx = cos ( absx );
    value = 0.5 * pi - f * cosx - g * sin ( x );
    if ( x < 0.0 )
      value = - value;
    end
  end

  return
end


text:
function [ x, seed ] = log_series_sample ( a, seed )

%*****************************************************************************80
%
%% LOG_SERIES_SAMPLE samples the Logarithmic Series PDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 March 1999
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Luc Devroye,
%    Non-Uniform Random Variate Generation,
%    Springer-Verlag, New York, 1986, page 547.
%
%  Parameters:
%
%    Input, real A, the parameter of the PDF.
%    0.0 < A < 1.0.
%
%    Input, integer SEED, a seed for the random number generator.
%
%    Output, integer X, a sample of the PDF.
%
%    Output, integer SEED, an updated seed for the random number generator.
%
  [ u, seed ] = r8_uniform_01 ( seed );
  [ v, seed ] = r8_uniform_01 ( seed );

  x = floor ( 1.0 + log ( v ) / ( log ( 1.0 - ( 1.0 - a )^u ) ) );

  return
end


text:
function map2ecefTrafo(obj, mstruct, varargin)
% MAP2ECEFTRAFO Coordinate transformation from ecef to map coordinates.
%
% Example: definition of mstruct for UTM33N
% mstruct       = defaultm('utm');
% mstruct.zone  = '33n';
% mstruct.geoid = referenceEllipsoid('GRS 80');
% mstruct       = defaultm(mstruct);

% Input parsing ----------------------------------------------------------------

p = inputParser;
p.addRequired( 'mstruct');
p.parse(mstruct, varargin{:});
p = p.Results;
% Clear required inputs to avoid confusion
clear mstruct

% Start ------------------------------------------------------------------------

procHierarchy = {'POINTCLOUD' 'MAP2ECEFTRAFO'};
msg('S', procHierarchy);
msg('I', procHierarchy, sprintf('Point cloud label = ''%s''', obj.label));

% Conversion to ecef coordinates -----------------------------------------------

[lat, lon, hEll] = minvtran(p.mstruct, obj.X(:,1), obj.X(:,2), obj.X(:,3)); % lat, lon in degrees!

[xEcef, yEcef, zEcef] = geodetic2ecef(lat*pi/180, lon*pi/180, hEll, p.mstruct.geoid); % lat, lon in radian!

% Update coordinates -----------------------------------------------------------

obj.X = [xEcef yEcef zEcef];
obj.info;

% End --------------------------------------------------------------------------

msg('E', procHierarchy);

end

author: pglira


text:
% KDTREE_LOAD loads a kd-tree from a binary file
%
% Added by Pablo Sala, November 25, 2008
%
% SYNTAX
% kdtree_load(filename)
%
% INPUT PARAMETERS
%   filename: name of file previously generated by a call to KDTREE_SAVE
%
% DESCRIPTION
% Loads a kd-tree from a file that was previously generated by a call to
% KDTREE_SAVE.
%
% See also:
% KDTREE_SAVE

% Copyright (c) 2008 Andrea Tagliasacchi
% All Rights Reserved
% email: ata2@cs.sfu.ca
% $Revision: 1.0$  Created on: 2008/09/15

author: intellhave

repo: SDRSAC

save_path: github-repos/MATLAB/intellhave-SDRSAC


text:
function [c, ceq] = flybyDVNonlconFunc(x, departBodyInfo, flybyBodyInfo, arrivalBodyInfo, gmuXfr, disableRpConst)
%flybyDVNonlconFunc Summary of this function goes here
%   Detailed explanation goes here

[~, ~, Rp, xferOrbitIn, xferOrbitOut] = flybyDVObjFunc(x, departBodyInfo, flybyBodyInfo, arrivalBodyInfo, gmuXfr);

c = [];
if(disableRpConst==0)
    c(end+1) = (flybyBodyInfo.radius+flybyBodyInfo.atmohgt+0.1) - Rp;
    c(end+1) = Rp - 0.9*flybyBodyInfo.sma*(flybyBodyInfo.gm/gmuXfr)^(2/5);
end
c(end+1) = xferOrbitIn(3) - pi/2;
c(end+1) = xferOrbitOut(3) - pi/2;

ceq = [];
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


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

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @deftypemethod  @@sym {@var{d} =} size (@var{x})
%% @deftypemethodx @@sym {[@var{n}, @var{m}] =} size (@var{x})
%% @deftypemethodx @@sym {@var{d} =} size (@var{x}, @var{dim})
%% Return the size of a symbolic array.
%%
%% Examples:
%% @example
%% @group
%% syms x
%% A = [1 2 x; x 3 4];
%% [n, m] = size(A)
%%   @result{} n = 2
%%   @result{} m = 3
%% @end group
%%
%% @group
%% A = sym('a', [3 4]);
%% [n, m] = size(A)
%%   @result{} n = 3
%%   @result{} m = 4
%% size(A, 1)
%%   @result{} 3
%% size(A, 2)
%%   @result{} 4
%% @end group
%% @end example
%%
%% Symbolic-sized matrices currently return @code{1 × 1} but we might
%% prefer @code{NaN × NaN}:
%% @example
%% @group
%% syms n m integer
%% A = sym('a', [n m])
%%   @result{} A = (sym) a  (n×m matrix expression)
%%
%% size(A)          % doctest: +XFAIL
%%   @result{} NaN   NaN
%% @end group
%% @end example
%%
%% @seealso{@@sym/length, @@sym/numel}
%% @end deftypemethod

function [n, m] = size(x, dim)

  % Note: symbolic sized matrices should return double, not sym/string.

  n = x.size;

  % FIXME: for now, we artificially force symbolic sized objects
  % (where one or more dimension is recorded as NaN) to be 1x1.
  % This effects MatrixSymbol and MatrixExpr.  See Issue #159.
  if (any(isnan(n)))
    n = [1 1];
  end
  % Alternatively:
  %n(isnan(n)) = 1;

  if (nargin == 2) && (nargout == 2)
    print_usage ();
  elseif (nargout == 2)
    m = n(2);
    n = n(1);
  elseif (nargin == 2)
    n = n(dim);
  end

end

%!test
%! a = sym([1 2 3]);
%! [n,m] = size(a);
%! assert (n == 1 && m == 3)

%!test
%! a = sym([1 2 3]);
%! n = size(a);
%! assert (isequal (n, [1 3]))

%!test
%! %% size, numel, length
%! a = sym([1 2 3; 4 5 6]);
%! assert (isa (size(a), 'double'))
%! assert (isa (numel(a), 'double'))
%! assert (isa (length(a), 'double'))
%! assert (isequal (size(a), [2 3]))
%! assert (length(a) == 3)
%! assert (numel(a) == 6)
%! a = sym([1; 2; 3]);
%! assert (isequal (size(a), [3 1]))
%! assert (length(a) == 3)
%! assert (numel(a) == 3)

%!test
%! %% size by dim
%! a = sym([1 2 3; 4 5 6]);
%! n = size(a, 1);
%! assert (n == 2)
%! m = size(a, 2);
%! assert (m == 3)
%! a = sym([1 2 3]');
%! n = size(a, 1);
%! assert (n == 3)
%! m = size(a, 2);
%! assert (m == 1)

%!xtest
%! % symbolic-size matrices
%! syms n m integer
%! A = sym('A', [n m]);
%! d = size(A);
%! assert (~isa(d, 'sym'))
%! assert (isnumeric(d))
%! assert (isequaln (d, [NaN NaN]))

%!xtest
%! % half-symbolic-size matrices
%! % FIXME: will fail until size stop lying by saying 1x1
%! syms n integer
%! A = sym('A', [n 3]);
%! assert (isequaln (size(A), [NaN 3]))
%! A = sym('A', [4 n]);
%! assert (isequaln (size(A), [4 NaN]))

%!xtest
%! % half-symbolic-size empty matrices
%! % FIXME: will fail until size stop lying by saying 1x1
%! syms n integer
%! A = sym('A', [n 0]);
%! assert (isequaln (size(A), [NaN 0]))

repo: octsympy


text:
function [randomizedCatalog, okPressed] = syn_invoke_random_dialog(catalog)
    % permutes/generates a catalog based on interactive choices
    %
    %  [randCatalog, ok] = SYN_INVOKE_RANDOM_DIALOG(catalog) allows permutation of longitude,
    %  latitude, depth, dates, and magnitudes.  randCatalog contains the permutated catalog
    %
    %  if user cancels, then ok is false and no catalog is returend.

    randomizedCatalog=[];
    % Open figure

    zdlg = ZmapDialog();
    zdlg.AddHeader('Spatio-temporal permutations');
    zdlg.AddCheckbox('bTimes', 'Permute Times', false, [], 'tooltip');
    zdlg.AddCheckbox('bLon', 'Permute Longitudes', false, [], 'tooltip');
    zdlg.AddCheckbox('bLat', 'Permute Latitudes', false, [], 'tooltip');
    zdlg.AddCheckbox('bDepth', 'Permute Depths', false, [], 'tooltip');
    zdlg.AddHeader('Magnitude Options')
    zdlg.AddCheckbox('bMags', 'Permute Magnitudes', false, [], 'has no effect if new magnitudes are created');
    zdlg.AddCheckbox('createMags', 'Create New magnitudes', false, {'fBValue', 'fMc', 'fInc'}, 'tooltip');
    zdlg.AddEdit('fBValue', 'b-value', 1, 'tooltip');
    zdlg.AddEdit('fMc', 'Magnitude of completeness', 1, 'tooltip');
    zdlg.AddEdit('fInc', 'Bin spacing', 0.1, 'bins into which magnitudes will fall');

    passes = false;
    while ~passes
        [res, okPressed] = zdlg.Create('Name', 'Synthetic Catalog Choices');
        if ~okPressed
            return
        end
        passes = validate_choices(res);
    end

    if res.createMags
        randomizedCatalog = syn_randomize_catalog(catalog, res.bLon, res.bLat,...
            res.bDepth, res.bTimes, 'create', res.fBValue, res.fMc, res.fInc);
    else
        randomizedCatalog = syn_randomize_catalog(catalog, res.bLon, res.bLat,...
            res.bDepth, res.bTimes, 'perturb');
    end
    msg.infodisp(randomizedCatalog, 'permutated catalog')
end

function ok = validate_choices(res)
    ttl = 'permuted catalog';
    ok = true;
    wasChanged = res.bLon || res.bMags || res.bLat || res.bTimes || res.bDepth || res.createMags;
    if ~wasChanged
        msgtxt = 'No changes were specified';
        ok = false;
    elseif res.createMags
        if res.fInc <= 0.1
            msgtxt = 'bin spacing must be greater than 0';
            ok = false;
        end

        if res.fInc <= 0
            msgtxt = 'b-value must be positive';
            ok = false;
        end
    end
    if ~ok
        msg.errordisp(msgtxt, ttl);
        mdlg = errordlg(msgtxt, ttl);
        waitfor(mdlg);
    end
end

author: CelsoReyes


text:
function gX = biasKernDiagGradX(kern, X)

% BIASKERNDIAGGRADX Gradient of BIAS kernel's diagonal with respect to X.
% FORMAT
% DESC computes the gradient of the diagonal of the bias kernel matrix with
% respect to the elements of the design matrix given in X.
% ARG kern : the kernel structure for which gradients are being computed.
% ARG X : the input data in the form of a design matrix.
% RETURN gX : the gradients of the diagonal with respect to each element
% of X. The returned matrix has the same dimensions as X.
%
% SEEALSO : biasKernParamInit, kernDiagGradX, biaskernGradX
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006

% KERN

gX = zeros(size(X));

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function [ readerobj ] = open_palsar2_reader( filename )
%OPEN_PALSAR2_READER Intiates a reader object for ALOS PALSAR 2 dataset
%
% Handles ALOS PALSAR 2 level 1.1 (SLC) data
%
% Written by: Wade Schwartzkopf, NGA/R
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

%% Setup reader
filenames = palsar2_files(filename);
if any(strcmp(filename, filenames.IMG))
    % If a single polarization is passed, only open that polarization.  If
    % a VOL/LED/TRL file is passed, open all polarizations.
    filenames.IMG = {filename};
end
meta_base = struct();
if isfield(filenames,'VOL')
    meta_base.native.vol = read_ceos_vol_meta(filenames.VOL);
    meta_base = setstructfields(meta_base, meta2sicd_palsar2vol(meta_base.native.vol));
end
if isfield(filenames,'LED')
    meta_base.native.led = read_ceos_led_meta(filenames.LED);
    meta_base = setstructfields(meta_base, meta2sicd_palsar2led(meta_base.native.led));
end
% Not really anything useful for us in the TRL file, so we skip that one
for i = 1:numel(filenames.IMG)
    img_meta = read_ceos_img_meta(filenames.IMG{i});
    datasize{i}=[img_meta.num_pixels img_meta.num_lines];
    data_offset{i}=[img_meta.rec_length + img_meta.prefix_bytes... % Byte offset to first data sample
                 img_meta.suffix_bytes + img_meta.prefix_bytes]; % Byte spacing between rows
    meta{i} = setstructfields(meta_base, meta2sicd_palsar2img(img_meta));
    % Much of the useful metadata requires both he LED and IMG files to compute.
    if isfield(filenames,'LED')
        meta{i} = setstructfields(meta{i}, ...
            meta2sicd_palsar2ledimg(meta_base.native.led, img_meta));
        % Now that sensor model fields have been populated, we can populate
        % GeoData.SCP more precisely.
        ecf = point_image_to_ground([meta{i}.ImageData.SCPPixel.Row;meta{i}.ImageData.SCPPixel.Col],meta{i});
        meta{i}.GeoData.SCP.ECF.X=ecf(1);
        meta{i}.GeoData.SCP.ECF.Y=ecf(2);
        meta{i}.GeoData.SCP.ECF.Z=ecf(3);
        llh=ecf_to_geodetic([meta{i}.GeoData.SCP.ECF.X meta{i}.GeoData.SCP.ECF.Y meta{i}.GeoData.SCP.ECF.Z]);
        meta{i}.GeoData.SCP.LLH.Lat=llh(1);
        meta{i}.GeoData.SCP.LLH.Lon=llh(2);
        meta{i}.GeoData.SCP.LLH.HAE=llh(3);
    end
    meta{i} = derived_sicd_fields(meta{i});
    meta{i}.native.img = img_meta;
end
% Consolidate polarizations across images
pols = cellfun(@(x) x.ImageFormation.TxRcvPolarizationProc, meta, 'UniformOutput', false);
tpols = unique(cellfun(@(x) x(1), pols));
for i = 1:numel(filenames.IMG)
    meta{i}.ImageFormation.RcvChanProc.ChanIndex = i;
    if isscalar(tpols)
        meta{i}.RadarCollection.TxPolarization = tpols;
    else
        meta{i}.RadarCollection.TxPolarization = 'SEQUENCE';
        for j = 1:numel(tpols)
            meta{i}.RadarCollection.TxSequence.TxStep(j).TxPolarization = tpols(j);
        end
    end
    for j = 1:numel(pols)
        meta{i}.RadarCollection.RcvChannels(j).ChanParameters.TxRcvPolarization = pols{j};
    end
end
if isfield(meta{1}, 'SCPCOA') && isfield(meta{1}.SCPCOA, 'SideOfTrack') && ...
        upper(meta{1}.SCPCOA.SideOfTrack(1))=='L'
    symmetry=[0 1 1]; % PALSAR written in range lines
else
    symmetry=[0 0 1]; % PALSAR written in range lines
end
if strncmp(img_meta.sar_datatype_code, 'C*8', 3) % Assumes all IMG files are of same type
    datatype='float32';
    complextype=true;
else
    datatype='uint16';
    complextype=false;
end
endian='b';
bands=1;

%% Open reader
for i = 1:numel(filenames.IMG)
    readerobj{i}=open_generic_reader(filenames.IMG{i}, datasize{i},...
        datatype, complextype, data_offset{i}, endian, symmetry, bands);
    readerobj{i}.get_meta=@() meta{i};
end

end

% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

author: ngageoint


text:
function root_num = p13_root_num ( )

%*****************************************************************************80
%
%% P13_ROOT_NUM returns the number of known roots for problem 13.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 May 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer ROOT_NUM, the number of known roots.
%
  root_num = 1;

  return
end


text:
function [flowftrs,hogftrs,info] = genFeatures(varargin)

%%

wsize = 5;
psize = 40;
nbins = 8;
halfpsize = round(psize*10/2);
hsz = round( (wsize - 1)/2);
debug = false;

% * Video: either readframeFcns or vidfile should be specified.
% * Interest pts: If interest points are desired, specify either ips or
% trxfile. If interest points are not desired (side only), leave both ips
% and trxfile empty.
[ts,readframeFcns,vidfile,trxfile,ips,face,framechunksize,frontside,...
  dopatchprint] = myparse(varargin,...
  'ts',[],...
  'readframeFcns',[],...
  'vidfile','',...
  'trxfile','',...
  'ips',[],...
  'face','',...
  'framechunksize',[],...
  'frontside',false,...
  'dopatchprint',true);

if isempty(framechunksize),

  framechunksize = 100;

end

if isempty(face)
  error('Face direction of the mice is not specified');
end

if strcmpi(face,'left')
  do_fliplr = true;
else
  do_fliplr = false;
end

if isempty(readframeFcns) && isempty(vidfile)
  error('Both arguments are empty');
end

tfvidfile = false;
if isempty(readframeFcns)
  if frontside
    assert(isstruct(vidfile) && all(isfield(vidfile,{'front' 'side'})),...
      'vidfile must be a struct with fields .front, .side.');
    [readFrameFcns.front.readframe,readFrameFcns.front.nframes,readFrameFcns.front.fid,readFrameFcns.front.headerinfo] = get_readframe_fcn(vidfile.front);
    [readFrameFcns.side.readframe,readFrameFcns.side.nframes,readFrameFcns.side.fid,readFrameFcns.side.headerinfo] = get_readframe_fcn(vidfile.side);
  else
    [readFrameFcns.side.readframe,readFrameFcns.side.nframes,readFrameFcns.side.fid,readFrameFcns.side.headerinfo] = get_readframe_fcn(vidfile);
  end
  tfvidfile = true;
else
  if ~frontside
    readFrameFcns.side = readframeFcns;
  end
end

% offside = 0;
% offfront = 0;
if frontside
  if readFrameFcns.front.nframes~=readFrameFcns.side.nframes
    warning('genFeatures:nframe',...
      'Number of frames in front video (%d) and side video (%d) do not match. Using minimum.',...
      readFrameFcns.front.nframes,readFrameFcns.side.nframes);
  end
  nframes = min(readFrameFcns.front.nframes,readFrameFcns.side.nframes);
  % turns out we should cut from the end
  %offfront = readFrameFcns.front.nframes-nframes;
  %offside = readFrameFcns.side.nframes-nframes;
else
  nframes = readFrameFcns.side.nframes;
end

if isempty(ts)
  ts = 1:nframes;
  if any(diff(ts)~=1),
    error('ts must be starframe:endframe');
  end
end

if ~isempty(ips) && ~isempty(trxfile)
  error('Both ips and trxfile specified.');
elseif ~isempty(ips) && isempty(trxfile)
  if frontside
    assert(all(isfield(ips,{'front' 'side'})),'Expected fields missing from ips.');
  elseif ~isstruct(ips)
    ips = struct('side',ips);
  end
elseif isempty(ips) && ~isempty(trxfile)
  T = load(trxfile);
  ips.side(1,:) = T.trx(1).arena.food;
  ips.side(2,:) = T.trx(1).arena.mouth;
  ips.side(3,:) = T.trx(1).arena.perch;
  ips.side = round(ips.side);
  if frontside
    ips.front(1,:) = T.trx(1).arena.foodfront;
    ips.front(2,:) = T.trx(1).arena.mouthfront;
    ips.front = round(ips.front);
  end
  assert(strcmp(face,T.trx(1).arena.face),'Specified ''face'' does not match ''face'' in specified trxfile');
else
  % isempty(ips) && isempty(trxfile)
  % no-op; handled below
end

if do_fliplr
  imw = readframeFcns.side.headerinfo.Width;
  ips.side(:,1) = imw - ips.side(:,1);
  if frontside
    imw = readframeFcns.front.headerinfo.Width;
    ips.front(:,1) = imw - ips.front(:,1);
  end
end

if isempty(ips),
  assert(~frontside,'Frontside currently requires interest point specification');
  patchsz = [headerinfo.Height,headerinfo.Width];
else
  Npatch = size(ips.side,1);
  if frontside
    Npatch = Npatch + size(ips.front,1);
  end
  patchsz1 = halfpsize*2+1;
  patchsz = [patchsz1,patchsz1*Npatch];
end

% initialize
flowftrs = [];
hogftrs = [];

% buffer of the past wsize frames
Fall = {};
Hall = {};
buffert0 = -1;
buffert1 = -2;
first = true;
% Fallslow = {};
% Hallslow = {};

% previous and current patch
patchPrev = zeros(patchsz,'single');
patchCurr = zeros(patchsz,'single');

% which frames to read
ts2readstart = max(ts(1)-hsz,1);
ts2readend = min(ts(end)+hsz,nframes);

s = warning('error','MATLAB:audiovideo:VideoReader:incompleteRead');

% initialize buffer

if dopatchprint && tfvidfile && ~isdeployed && numel(ts) >= 2+hsz,
  randomframe = randsample(ts(2+hsz:end),1);
else
  randomframe = nan;
end

tic;
for ndx = 1:numel(ts),

  t = ts(ndx);

  % window considered during this frame
  wstart = max(1,t-hsz);
  wend = min(nframes,t+hsz);
  curn = wend - wstart +1;

  % reuse the previously computed features.
  if numel(Hall)>=curn,
    Fall(1:end-1) = Fall(2:end);
    Hall(1:end-1) = Hall(2:end);
    buffert0 = buffert0+1;
  end

  % initialize HOG, HOF buffer
  if first,

    for wndx = 1:curn,

      patchPrev = patchCurr;
      patchCurr = lclGrabPatch(readFrameFcns,wstart+wndx-1,do_fliplr,tfvidfile,frontside,ips,halfpsize,patchCurr);

      % HOG
      % step size is two for gradient computation
      % approx equiv Matlab code, ignoring borders
      % gx = patchCurr(2:end-1,3:end)-patchCurr(2:end-1,1:end-2);
      % gy = patchCurr(3:end,2:end-1)-patchCurr(1:end-2,2:end-1);
      % M = sqrt(gx.^2+gy.^2)/2;
      % O = modrange(atan2(gy,gx),0,pi);
      % will match M(2:end-1,2:end-1) and O(2:end-1,2:end-1)
      [M,O] = gradientMag(patchCurr/255);
      H=gradientHist(M,O,psize,nbins,1);
      Hall{wndx} = H;

      if wndx > 1,

        % HOF
        [Vx,Vy,~] = optFlowLk(patchPrev,patchCurr,[],3);
        M = sqrt(Vx.^2 + Vy.^2);
        O = mod(atan2(Vy,Vx)/2,pi);
        O = min(O,pi-1e-6);
        H = gradientHist(single(M),single(O),psize,nbins,1);
        Fall{wndx-1} = H;

      end

    end
    buffert0 = wstart;
    buffert1 = wend;

  else

    % add to the buffer
    if buffert1 < wend,

      patchPrev = patchCurr;
      patchCurr = lclGrabPatch(readFrameFcns,wend,do_fliplr,tfvidfile,frontside,ips,halfpsize,patchCurr);

      % HOG feature for frame wend
      [M,O] = gradientMag(patchCurr/255);
      H=gradientHist(M,O,psize,nbins,1);
      Hall{curn} = H; %#ok<AGROW>

      [Vx,Vy,~] = optFlowLk(patchPrev,patchCurr,[],3);
      % Gradient hist requires orientation to be between 0 and pi. Makes sense for
      % image gradients. But for flow pi/2 is different than -pi/2. So adjust for
      % that.

      M = sqrt(Vx.^2 + Vy.^2);
      O = mod(atan2(Vy,Vx)/2,pi);
      O = min(O,pi-1e-6);
      H = gradientHist(single(M),single(O),psize,nbins,1);
      Fall{curn-1} = H; %#ok<AGROW>
      buffert1 = buffert1 + 1;
    end

  end

  curFall = Fall{1};
  curHall = Hall{1};
  for ii = 2:curn-1
    curFall = curFall + Fall{ii};
    curHall = curHall + Hall{ii};
  end
  curHall = curHall + Hall{curn};

  curFall = curFall/(curn-1);
  curHall = curHall/curn;

  if first,
    flowftrs = zeros([size(curFall),numel(ts)],'single');
    hogftrs = zeros([size(curFall),numel(ts)],'single');
  end

  flowftrs(:,:,:,ndx) = curFall;
  hogftrs(:,:,:,ndx) = curHall;

  if mod(ndx,10)==0,
    fprintf('Processed frame %d / %d\n',ndx,numel(ts));
  end
  first = false;

  if buffert1 == randomframe,
    hFig = figure;
    imshow(patchCurr,[0 256]);
    fname = sprintf('patch_%d.jpg',randomframe);
    if ischar(vidfile)
      pth = fileparts(vidfile);
    else
      pth = fileparts(vidfile.side);
    end
    fname = fullfile(pth,fname);
    print(hFig,'-djpeg',fname);
    delete(hFig);
  end

end
warning(s);

fprintf('\n');
fprintf('Generating features for %d frames took %f seconds.\n',numel(ts),toc);

info = struct();
info.nframes = nframes;

function imMat = lclReadFrame(rff,i0,i1,do_fliplr,tfvidfile)
try
  tt = rff.readframe([i0 i1]);
catch ME,
  if strcmp(ME.identifier,'MATLAB:audiovideo:VideoReader:incompleteRead')
    fprintf('Reading Frames individually\n');
    tt = [];
    for ndx = i0:i1
      tt(:,:,:,end+1) = rff.readframe(ndx); %#ok<AGROW>
    end
  else
    rethrow(ME);
  end
end

iscolor = size(tt,3) > 1;

nfrm = i1-i0+1;
imMat = zeros(rff.headerinfo.Height,rff.headerinfo.Width,nfrm,'single');

for ndx = 1:nfrm,
  if iscolor,
    ttgraycurr = rgb2gray(tt(:,:,:,ndx));
  else
    ttgraycurr = tt(:,:,:,ndx);
  end
  if do_fliplr,
    qq = fliplr(ttgraycurr);
  else
    qq = ttgraycurr;
  end
  imMat(:,:,ndx) = single(qq);
end

if tfvidfile && rff.fid>0
  fclose(rff.fid);
end

function patchMat = lclGrabPatch(readFrameFcns,f,do_fliplr,tfvidfile,frontside,ips,halfpsize,patchMat)

imMat.side = lclReadFrame(readFrameFcns.side,f,f,do_fliplr,tfvidfile);
if frontside
  imMat.front = lclReadFrame(readFrameFcns.front,f,f,do_fliplr,tfvidfile);
end

patchsz1 = size(patchMat,1);
if ~isempty(ips)
  Nipsside = size(ips.side,1);
  for pndx = 1:Nipsside
    pp = padgrab(imMat.side,0,...
      ips.side(pndx,2)-halfpsize,ips.side(pndx,2)+halfpsize,...
      ips.side(pndx,1)-halfpsize,ips.side(pndx,1)+halfpsize,...
      1,size(imMat.side,3));
    patchMat(:,(pndx-1)*patchsz1+1:pndx*patchsz1) = pp;
  end
  if frontside
    for pndx = 1:size(ips.front,1)
      pp = padgrab(imMat.front,0,...
        ips.front(pndx,2)-halfpsize,ips.front(pndx,2)+halfpsize,...
        ips.front(pndx,1)-halfpsize,ips.front(pndx,1)+halfpsize,...
        1,size(imMat.front,3));
      patchMat(:,(pndx-1+Nipsside)*patchsz1+1:(pndx+Nipsside)*patchsz1) = pp;
    end
  end
else
  assert(~frontside);
  patchMat = imMat.side;
end

author: kristinbranson

repo: JAABA


text:
function f12=f12(x)
Bound=[-50 50];

if nargin==0
    f12 = Bound;
else
    y=1+(x+1)./4;
    a=x>10;
    b=x<-10;
    [row col]=size(x);

    y1=y(1:row-1,:);
    y2=y(2:row,:);

    usum=sum(a*.100.*((x-10)).^4)+sum(b*.100.*(x+10).^4);
    f12=(10*sin(pi*y(1,:)).^2+sum((y1-1).^2.*(1+10*sin(pi.*y2).^2))+(y(row,:)-1).^2)*(pi/30)+usum;
end

author: sfvsfv

repo: Mathematical-modeling


text:
function [hmm,Gamma,fehist] = hmmmar_init(data,T,options)
%
% Initialise the hidden Markov chain using HMM-MAR
%
% INPUT
% data      observations, a struct with X (time series) and C (classes, optional)
% T         length of observation sequence
% options,  structure with the training options
% Sind
%
% OUTPUT
% Gamma     p(state given X)
%
% Author: Diego Vidaurre, University of Oxford
% Author: Romesh Abeysuriya, University of Oxford

if ~isfield(options,'maxorder')
    [~,order] = formorders(options.order,options.orderoffset,options.timelag,options.exptimelag);
    options.maxorder = order;
end

% Run two initializations for each K less than requested K, plus options.initrep K
if options.initTestSmallerK
    init_k = [repmat(1:(options.K-1),1,2) options.K*ones(1,options.initrep)];
    init_k = init_k(end:-1:1);
else % Standard behaviour, test specified K options.initrep times
    init_k = options.K*ones(1,options.initrep);
end

felast = zeros(length(init_k),1);
maxfo = zeros(length(init_k),1);
fehist = cell(length(init_k),1);
Gamma = cell(length(init_k),1);
hmm = cell(length(init_k),1);

if options.useParallel && length(init_k) > 1 % not very elegant
    parfor it = 1:length(init_k)
        [hmm{it},Gamma{it},fehist{it}] = run_initialization(data,T,options,init_k(it));
        felast(it) = fehist{it}(end);
        maxfo(it) = mean(getMaxFractionalOccupancy(Gamma{it},T,options));
        if options.verbose
            if options.episodic
                fprintf('Init run %2d, Free Energy = %f \n',it,felast(it));
            else
                fprintf('Init run %2d, %2d->%2d states, Free Energy = %f \n',...
                    it,init_k(it),size(Gamma{it},2),felast(it));
            end
        end
    end
else
    for it = 1:length(init_k)
        [hmm{it},Gamma{it},fehist{it}] = run_initialization(data,T,options,init_k(it));
        felast(it) = fehist{it}(end);
        maxfo(it) = mean(getMaxFractionalOccupancy(Gamma{it},T,options));
        if options.verbose
            if options.episodic
                fprintf('Init run %2d, Free Energy = %f \n',it,felast(it));
            else
                fprintf('Init run %2d, %2d->%2d states, Free Energy = %f \n',...
                    it,init_k(it),size(Gamma{it},2),felast(it));
            end
        end
    end
end

if isfield(options,'initcriterion') && strcmpi(options.initcriterion,'FreeEnergy')
    [fe,s] = min(felast);
    if options.verbose
        fprintf('%i-th was the best iteration with FE=%f \n',s,fe)
    end
else
    [fo,s] = min(maxfo);
    if options.verbose
        fprintf('%i-th was the best iteration with mean maxFO=%f \n',s,fo)
    end
end

Gamma = Gamma{s};
hmm = hmm{s};
fehist = fehist{s};

end

function [hmm,Gamma,fehist] = run_initialization(data,T,options,init_k)
% INPUTS
% - data,T,options,Sind <same as hmmmar_init>
% - init_k is the number of states to use for this initialization

% Need to adjust the worker dirichletdiags if testing smaller K values
%if ~options.episodic && init_k < options.K
Sind = options.Sind;

if init_k < options.K
    for j = 1:length(options.DirichletDiag)
        p = options.DirichletDiag(j)/(options.DirichletDiag(j) + options.K - 1); % Probability of remaining in same state
        f_prob = dirichletdiags.mean_lifetime(); % Function that returns the lifetime in steps given the probability
        expected_lifetime =  f_prob(p)/options.Fs; % Expected number of steps given the probability
        options.K = init_k;
        adjusted_DirichletDiag = dirichletdiags.get(expected_lifetime,options.Fs,options.K);
        if isfinite(adjusted_DirichletDiag) % It is NaN if there was a numerical issue
            options.DirichletDiag(j) = adjusted_DirichletDiag;
        end
    end
end

data.C = data.C(:,1:options.K);
if ~isfield(options,'ehmm_priorOFFvsON'), ehmm_priorOFFvsON = [];
else, ehmm_priorOFFvsON = options.ehmm_priorOFFvsON;
end
% Note - initGamma_random uses DD=1 so that there are lots of transition times, which
% helps the inference not get stuck in a local minimum. options.DirichletDiag is
% then used inside hmmtrain when computing the free energy
keep_trying = true; notries = 0;
while keep_trying
    Gamma = initGamma_random(T-options.maxorder,options.K,...
        min(median(double(T))/10,500),...
        options.Pstructure,options.Pistructure,...
        options.episodic,ehmm_priorOFFvsON);
    hmm = struct('train',struct());
    hmm.K = options.K;
    hmm.train = options;
    hmm.train.Sind = Sind;
    hmm.train.cyc = max(hmm.train.initcyc,2);
    hmm.train.verbose = 0;
    hmm.train.plotGamma = 0;
    hmm = hmmhsinit(hmm);
    if isfield(hmm.train,'Gamma'), hmm.train = rmfield(hmm.train,'Gamma'); end
    [hmm,residuals] = obsinit(data,T,hmm,Gamma);
    try
        [hmm,Gamma,~,fehist] = hmmtrain(data,T,hmm,Gamma,residuals);
        fehist(end) = [];
        keep_trying = false;
    catch exception
        notries = notries + 1;
        if notries > 10
            disp('Initialisation went wrong');
            throw(exception)
        end
        disp('Something strange happened in the initialisation - repeating')
    end
    hmm.train.verbose = options.verbose;
    hmm.train.cyc = options.cyc;
    hmm.train.plotGamma = options.plotGamma;
end
%fe = fehist(end);
end

author: OHBA-analysis

repo: HMM-MAR


text:
function sliceBrowser(slice_figure, processed_images_folder, f, reference_size)
% -----------------------------------------------------------------
% browser to go through histology along with the reference browser
%-----------------------------------------------------------------

% initialize user data variables held by the figure
processed_images = dir([processed_images_folder filesep '*.tif']);
ud_slice.processed_image_names = natsortfiles({processed_images.name});
total_num_files = size(processed_images,1); disp(['found ' num2str(total_num_files) ' processed slice images']);
ud_slice.total_num_files = total_num_files;
ud_slice.break = 0;
ud_slice.slice_num = 1;
ud_slice.key = 1;
ud_slice.pointList = [];
ud_slice.pointHands = [];
ud_slice.getPoint = 0;
ud_slice.ref_size = reference_size(2:3);

ud_slice.processed_images = processed_images;
ud_slice.processed_images_folder = processed_images_folder;
ud_slice.sliceAx = axes('Position', [0.05 0.05 0.9 0.9]);
hold(ud_slice.sliceAx, 'on');
set(ud_slice.sliceAx, 'HitTest', 'off');
ud_slice.im = plotTVslice(zeros(ud_slice.ref_size, 'uint8'));

% create functions needed to interact with the figure
set(ud_slice.im, 'ButtonDownFcn', @(slice_figure,k)sliceClickCallback(slice_figure, k));
set(slice_figure, 'KeyPressFcn', @(slice_figure, keydata)SliceAtlasHotkeyFcn(slice_figure, keydata, f));
set(slice_figure, 'UserData', ud_slice)

% adjust figure to user's screen size
try; screen_size = get(0,'ScreenSize'); screen_size = [max(screen_size(3:4)) min(screen_size(3:4))]./[2560 1440];
catch; screen_size = [1900 1080]./[2560 1440];
end
set(slice_figure,'Position', [150*screen_size(1) 660*screen_size(2) 880*screen_size(1) 650*screen_size(2)])
movegui(slice_figure,'onscreen')

% set up first slice image
ud_slice = updateSliceImage(ud_slice);

% ------------------------------------------------
% Clicking function to register transform points
% ------------------------------------------------
function sliceClickCallback(im, keydata)
f = get(get(im, 'Parent'), 'Parent');
ud = get(f, 'UserData');

if ud.getPoint
    clickX = round(keydata.IntersectionPoint(1));
    clickY = round(keydata.IntersectionPoint(2));

    ud.pointList(end+1, :) = [clickX, ud.ref_size(1) - clickY];
    ud.pointHands(end+1) = plot(ud.sliceAx, clickX, clickY, 'ro', 'color', [0 .5 0],'linewidth',2,'markers',4);

     if clickX < 100 && (ud.ref_size(1) - clickY) < 100 % if click in corner, break
        ud.pointList = [];
        set(ud.pointHands(:), 'Visible', 'off');
     end

end
set(f, 'UserData', ud);

% ------------------------
% react to keyboard press
% ------------------------
function SliceAtlasHotkeyFcn(fig, keydata, f)

ud = get(fig, 'UserData');

% left arrow -- go to previous slice
if strcmp(keydata.Key,'leftarrow')
    if ud.slice_num > 1
        ud.slice_num = ud.slice_num - 1;
        ud = updateSliceImage(ud);
    end

% right arrow -- go to next slice
elseif strcmp(keydata.Key,'rightarrow')
    if ud.slice_num < ud.total_num_files
        ud.slice_num = ud.slice_num + 1;
        ud = updateSliceImage(ud);
    end
% d -- delete current transform points
elseif strcmp(keydata.Key,'d')
%     disp('current transform points deleted')
%     set(ud.pointHands(:), 'Visible', 'off');
%     ud.pointList = [];

    % Try to delete only most recent point
    set(ud.pointHands(end), 'Visible', 'off');
    ud.pointHands = ud.pointHands(1:end-1);
    ud.pointList = ud.pointList(1:end-1,:);
    disp('transform point deleted')
% t -- transform point mode
elseif strcmp(keydata.Key,'t')
    ud.getPoint = ~ud.getPoint;
        if ud.getPoint; disp('transform point mode!'); end
else
% otherwise -- call function to atlas browser
    figure(f);
    fcn = get(f, 'KeyPressFcn');
    fcn(f, keydata);
end

set(fig, 'UserData', ud);

function ud = updateSliceImage(ud)

    title_ending = '';

    processed_image_name = ud.processed_image_names{ud.slice_num};
    current_slice_image = flip(imread(fullfile(ud.processed_images_folder, processed_image_name)),1);
    % reduce to 3 channels at most
    color_channels = min( 3, size(current_slice_image,3));
    current_slice_image = current_slice_image(:,:,1:color_channels);
    % reduce to reference atlas size
    if size(current_slice_image,1) > ud.ref_size(1)+2 || size(current_slice_image,2) > ud.ref_size(2)+2
        disp(['shrinking image to reference size ' num2str(ud.ref_size(1)) ' x ' num2str(ud.ref_size(2)) ' pxl'])
        current_slice_image = imresize(current_slice_image, ud.ref_size);
    end
    set(ud.im, 'CData', current_slice_image);

    file_transformations = fullfile(ud.processed_images_folder, 'transformations\\' ,...
                            [processed_image_name(1:end-4) '_transform_data.mat']);

    set(ud.pointHands(:), 'Visible', 'off');
    ud.pointList = [];

    if exist(file_transformations,'file')
        % load transform data
        transform_data = load(file_transformations);
        transform_data = transform_data.save_transform;
        if ~isempty(transform_data.transform_points{2})
            ud.pointList = transform_data.transform_points{2};
            title_ending = ' (transform points loaded)';
        end
    end
    title(['Slice Viewer -- Slice ' num2str(ud.slice_num) '/' num2str(ud.total_num_files) title_ending])

author: cortex-lab

repo: allenCCF

save_path: github-repos/MATLAB/cortex-lab-allenCCF


text:
function [theta, phi, r] = besa_transformCartesian2Spherical(X, Y, Z)
% BESA_TRANSFORMCARTESIAN2SPHERICAL takes the cartesian coordinates X, Y
% and Z of a 3D point and transforms them to the spherical coordinates
% theta, phi and r.
%
% Parameters:
%     [X]
%         The X-coordinate of the current 3D point. It should point to the
%         right.
%
%     [Y]
%         The Y-coordinate of the current 3D point. It should point
%         foreward.
%
%     [Z]
%         The Z-coordinate of the current 3D point. It should point up.
%
%
% Return:
%     [theta]
%         The azimuth angle with the vertical z-axis (0 degree) in the
%         x-z-plane, +90 degree lie in the positive x-axis.
%
%     [phi]
%         The latitude angle in the horizontal x-y-plane
%         (counter-clockwise).
%
%     [r]
%         The radius.

% Copyright (C) 2015, BESA GmbH
%
% File name: besa_transformCartesian2Spherical.m
%
% Author: Todor Jordanov
% Created: 2015-07-29

SquareOfRadiusXY = X*X + Y*Y;
RadiusXY = sqrt(SquareOfRadiusXY);

if(RadiusXY == 0.0 && Z == 0.0)

    theta = 0.0;

else

    theta = atan2d(RadiusXY, Z);

end

if(X==0.0 && Y==0.0)

    phi = 0.0;

else

    phi = atan2d(Y, X);

end

% square of total radius
SquareOfRadiusXY = SquareOfRadiusXY + Z*Z;

r = sqrt(SquareOfRadiusXY);

% set phi & theta to BESA ranges
if(phi > 90.)

    phi = phi - 180.0;
    theta = -theta;

elseif(phi < -90.)

    phi = phi+180.0;
    theta = -theta;

end

author: fieldtrip

repo: fieldtrip


text:
function autoChoiceBestModels_VASARI_LGG(pathExperiments,fSetNames,nameOutcomes,metric,maxOrder,pathFig)
% -------------------------------------------------------------------------
% function autoChoiceBestModels_VASARI_LGG(pathExperiments,fSetNames,nameOutcomes,metric,maxOrder,pathFig)
% -------------------------------------------------------------------------
% DESCRIPTION:
% This function automatically chooses (hard-coded in the function) the set
% types and models orders providing the best parsimonious models for all
% outcoms analyzed in the LGG study.
% -------------------------------------------------------------------------
% INPUTS:
% 1. pathExperiments: Full path to the directory containing all experiments.
%                     --> Ex: '/myProject/WORKSPACE/VASARI'
% 2. fSetNames: Cell of strings specifying the name of the type of feature
%               set analyzed.
%               --> Ex: {'VASARI'}
% 3. nameOutcomes: Cell of strings specifying the outcome names to analyze.
%                  --> Ex: {'nonIDH1','IDHcodel','progression','lowGrade'}
% 4. metric: String specifying the metric to display.
%            --> 'AUC632'
% 5. maxOrder: Integer specifying the maximal multivariable model order.
%              --> Ex: 10
% 6. pathFig: (optional).  Full path to where figure is saved without
%             displaying it. Put '' for displaying the figure and not
%             saving it to 'pathFig' (default).
%             --> Ex: ''
% -------------------------------------------------------------------------
% OUTPUTS: Final prediction models saved in a folder named
%          '/myProject/WORKSPACE/VASARI/FINAL_MODELS/nameOutcome/fSetName'
% -------------------------------------------------------------------------
% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>
% -------------------------------------------------------------------------
% HISTORY:
% - Creation: January 2017
%--------------------------------------------------------------------------
% STATEMENT:
% This file is part of <https://github.com/mvallieres/radiomics/>,
% a package providing MATLAB programming tools for radiomics analysis.
% --> Copyright (C) 2015-2017  Martin Vallieres
%
%    This package is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    This package 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 package.  If not, see <http://www.gnu.org/licenses/>.
% -------------------------------------------------------------------------

startpath = pwd;
cd(pathExperiments)
nOutcomes = length(nameOutcomes);
nType = length(fSetNames);

n = 0;
order = [2,4,5,3]; % For 'nonIDH1', IDHcodel, 'progression', 'lowGrade'

cd(pathExperiments), pathExperimentBinary = pathExperiments;
cd(pathExperimentBinary), mkdir('FINAL_MODELS'), cd('FINAL_MODELS'), pathFinalModelsBinary = pwd;
for o = 1:nOutcomes
    cd(pathFinalModelsBinary), mkdir(nameOutcomes{o}), cd(fullfile(pathFinalModelsBinary,nameOutcomes{o})), pathOutcomeBinary = pwd;
    plotPredictionResults_VASARI(fullfile(pathExperimentBinary,'RESULTS'),nameOutcomes{o},fSetNames,metric,maxOrder,pathFig)
    for f = 1:nType
        n = n + 1;
        cd(pathOutcomeBinary), mkdir(fSetNames{f}), cd(fullfile(pathOutcomeBinary,fSetNames{f})), pathFinalBinary = pwd;
        cd(fullfile(pathExperimentBinary,'RESULTS'))
        results = load(['RESULTS_',fSetNames{f},'_',nameOutcomes{o}]); results = struct2cell(results); results = results{1};
        finalModel = results.(['Order',num2str(order(n))]);
        finalModel.Order = order(n);
        finalModel.outcome = nameOutcomes{o};
        cd(pathFinalBinary), save('finalModel','finalModel')
    end
end

cd(startpath)
end

author: mvallieres

repo: radiomics


text:
classdef SuperEllipseExponentTxiRhoPlotter < handle

    properties (Access = public)

    end

    properties (Access = private)

    end

    properties (Access = private)
        fileName
        title
        rhoV
        xiV
        value
    end

    methods (Access = public)

        function obj = SuperEllipseExponentTxiRhoPlotter(cParams)
            obj.init(cParams);
        end

        function plot(obj)
            obj.plotContour();
            obj.plotTriSurf();
        end

    end

    methods (Access = private)

        function init(obj,cParams)
            obj.fileName = [cParams.fileName,'XiRho'];
            obj.title = cParams.title;
            obj.rhoV = cParams.rhoV;
            obj.xiV  = cParams.xiV;
            obj.value = cParams.value;
        end

        function plotTriSurf(obj)
            s.fileName = obj.fileName;
            s.title = obj.title;
            s.axisAdder = XiRhoAxisAdder();
            s.view = [-223 67];
            p =  SuperEllipseExponentTriSurfPlotter(s);
            x = obj.xiV;
            y = obj.rhoV;
            z = obj.value;
            p.plot(x,y,z);
        end

        function plotContour(obj)
            s.fileName = obj.fileName;
            s.title = obj.title;
            s.axisAdder = XiRhoAxisAdder();
            p =  SuperEllipseExponentContourPlotter(s);
            x = obj.xiV;
            y = obj.rhoV;
            z = obj.value;
            p.plot(x,y,z);
        end

        function addAxis(obj)
            zlabel('q');
        end

    end

end

author: SwanLab


text:
filename='ImprovedBridge_hexahedra';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance','perimeter'};
weights = [1 0.1];
constraint = {'volume'};
optimizer = 'MMA'; incrementFactor = 1;
filterType = 'P1';
constraint_case = 'INEQUALITY';
line_search_initiator = 'STANDARD';
showBC = true;

nsteps = 10;
Vfrac_final = 0.1;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

Vfrac_initial = 1;
optimality_initial = 1e-3;
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;


text:
%% <../index.html MATLAB xUnit Test Framework>: How to Write Tests That Share Common Set-Up Code
% Sometimes you want to write a set of test cases in which the same
% set of initialization steps is performed before each test case, or
% in which the same set of cleanup steps is performed after each
% test case.  This set of common _setup_ and _teardown_ code is
% called a _test fixture_.
%
% In subfunction-based test files, you can add subfunctions whose
% names begin with "setup" and "teardown".  These functions will be
% called before and after every test-case subfunction is called.  If
% the setup function returns an output argument, that value is saved
% and passed to every test-case subfunction and also to the teardown
% function.
%
% This example shows a setup function that creates a figure and
% returns its handle.  The figure handle is passed to each test-case
% subfunction.  The figure handle is also passed to the teardown
% function, which cleans up after each test case by deleting the
% figure.

cd examples_general
type testSetupExample

%%
% Run the tests using |runtests|.

runtests testSetupExample

%%
% You might also want to see the
% <./exTestCase.html example on writing test cases by
% subclassing TestCase>.

%%
% <../index.html Back to MATLAB xUnit Test Framework>

%%
% Copyright 2008-2010 The MathWorks, Inc.

author: ricedsp