text:
%
%   run an example of ordfilt3 on a noisy sphere.
%
%   for uint8, a 100x100x100 sphere dataset takes 2.75s on a P4 2.4GHz
clear
randn('seed',0)

[x,y,z] = meshgrid(1:100,1:100,1:100);
sphere = 20 + 200*( ( sqrt((x-50).^2+(y-50).^2+(z-50).^2) ) < 40 );
clear x y z
sphere = uint8(1*sphere + 50*randn(size(sphere)));

% -- median filter
tic
[Vr] = ordfilt3D(sphere,14);
toc
clf
% -- compare to box filter
subplot(221)
p1 = patch(isosurface(sphere,100), ...
   'FaceColor','blue','EdgeColor','none');
p2 = patch(isocaps(sphere,100), ...
    'FaceColor','interp','EdgeColor','none');
isonormals(sphere,p1)
view(3); axis vis3d square
camlight; lighting phong

subplot(222)
p1 = patch(isosurface(Vr,100), ...
   'FaceColor','blue','EdgeColor','none');
p2 = patch(isocaps(Vr,100), ...
    'FaceColor','interp','EdgeColor','none');
isonormals(Vr,p1)
view(3); axis vis3d square
camlight; lighting phong

%%
% show some slice
for k=1:20,
    subplot(223)
    imagesc( sphere(:,:,k) ,[0 255]),axis image
    title('original')

    subplot(224)
    imagesc( Vr(:,:,k) ,[0 255]),axis image
    title('Filtered with a 3D median filter')

    drawnow
end

author: Sable

repo: mcbench-benchmarks


text:
function varargout = dsxy2figxy(varargin)
if length(varargin{1}) == 1 && ishandle(varargin{1}) ...
                            && strcmp(get(varargin{1},'type'),'axes')
    hAx = varargin{1};
    varargin = varargin(2:end);
else
    hAx = gca;
end;
if length(varargin) == 1
    pos = varargin{1};
else
    [x,y] = deal(varargin{:});
end
axun = get(hAx,'Units');
set(hAx,'Units','normalized');
axpos = get(hAx,'Position');
axlim = axis(hAx);
axwidth = diff(axlim(1:2));
axheight = diff(axlim(3:4));
if exist('x','var')
    varargout{1} = (x - axlim(1)) * axpos(3) / axwidth + axpos(1);
    varargout{2} = (y - axlim(3)) * axpos(4) / axheight + axpos(2);
else
    pos(1) = (pos(1) - axlim(1)) / axwidth * axpos(3) + axpos(1);
    pos(2) = (pos(2) - axlim(3)) / axheight * axpos(4) + axpos(2);
    pos(3) = pos(3) * axpos(3) / axwidth;
    pos(4) = pos(4) * axpos(4 )/ axheight;
    varargout{1} = pos;
end
set(hAx,'Units',axun)

author: HuangCongQing


function [ bs ] = LandmarkDetector( im )
%LANDMARKDETECTOR Summary of this function goes here
%   Detailed explanation goes here
load('ZhuRamananModel.mat');
%posemap = 90:-15:-90;
%clf; imagesc(im); axis image; axis off; drawnow;
    bs = detect(im, model, model.thresh);
    bs = clipboxes(im, bs);
    bs = nms_face(bs,0.3);
% figure,showboxes(im, bs(1),posemap),title('Highest scoring detection');
% text((bs.xy(:,1)+bs.xy(:,3))/2,(bs.xy(:,2)+bs.xy(:,4))/2,cellstr(num2str([1:68]')))

end


text:
% Description:
%
%     Estimate the dimensionality of Y using the Bayesian information criterion
%     (BIC) and perform an economy SVD of Y such that Y = U * S * V'.
%
% Syntax:
%
%     [ BIC, U, S, V, stats ] = mSVD(Y)
%
% Inputs:
%
%     Y       - [ N x M ] (double)
%     options - [ 1 x P ] (cell)
%
% Outputs:
%
%     BIC - [ 1 x B ] (double)
%     U   - [ N x N ] (double)
%     S   - [ N x N ] (double)
%     V   - [ M x N ] (double)
%
% Details:
%
% Examples:
%
% Notes:
%
% Author(s):
%
%     William Gruner (williamgruner@gmail.com)
%
% References:
%
% Acknowledgements:
%
%     Many thanks to Dr. Erik Erhardt and Dr. Elena Allen of the Mind Research
%     Network (www.mrn.org) for their continued collaboration.
%
% Version:
%
%     $Author: williamgruner $
%     $Date: 2010-04-01 12:52:08 -0600 (Thu, 01 Apr 2010) $
%     $Revision: 483 $

function [ BIC, U, S, V ] = mSVD(Y, options)

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

    if ~isempty(strmatch('verbose', options, 'exact'))
        fprintf('\n')
        fprintf('Using an economy SVD to reduce the dimensionality of Y ...\n\n')
    end

    [ U, S, V ] = svd(Y, 'econ');

    b = [];
    n = size(U, 2);
    r = Inf;

    for i = 1 : n

        e = Y - U(:, 1 : i) * S(1 : i, 1 : i) * V(:, 1 : i)';

        b(i) = log(std(e(:)).^2) + (i / n) * log(n);

        if ~isempty(strmatch('verbose', options))
            fprintf('\tBIC(%d) = %g\n', i, b(i))
        end

        if i > 1 && b(i) > b(i - 1) && r == Inf
            r = i - 1;
        end

        if i > 2 * r
            break
        end

    end

    if ~isempty(strmatch('verbose', options))
        fprintf('\n... to the Bayesian information criterion estimate of %d.\n', r)
    end

    BIC = b;


text:
function st = addfix( st, x, fx )
% x2 = addfix( st, x, fx )
    st(~fx) = x;
end

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab


text:
function [x,e,obj,err,iter] = tracelassoR(A,b,lambda,opts)

% Solve the trace Lasso regularized minimization problem by M-ADMM
%
% min_{x,e} loss(e)+lambda*||A*Diag(x)||_*, s.t. Ax+e=b
% loss(e) = ||e||_1 or 0.5*||e||_2^2
% ---------------------------------------------
% Input:
%       A       -    d*n matrix
%       b       -    d*1 vector
%       opts    -    Structure value in Matlab. The fields are
%           opts.loss       -   'l1' (default): loss(e) = ||e||_1
%                               'l2': loss(e) = 0.5*||e||_2^2
%           opts.tol        -   termination tolerance
%           opts.max_iter   -   maximum number of iterations
%           opts.mu         -   stepsize for dual variable updating in ADMM
%           opts.max_mu     -   maximum stepsize
%           opts.rho        -   rho>=1, ratio used to increase mu
%           opts.DEBUG      -   0 or 1
%
% Output:
%       x       -    n*1 vector
%       e       -    d*1 vector
%       obj     -    objective function value
%       err     -    residual
%       iter    -    number of iterations
%
% version 1.0 - 18/06/2016
%
% Written by Canyi Lu (canyilu@gmail.com)
%

tol = 1e-8;
max_iter = 500;
rho = 1.1;
mu = 1e-4;
max_mu = 1e10;
DEBUG = 0;
loss = 'l1';

if ~exist('opts', 'var')
    opts = [];
end
if isfield(opts, 'loss');        loss = opts.loss;            end
if isfield(opts, 'tol');         tol = opts.tol;              end
if isfield(opts, 'max_iter');    max_iter = opts.max_iter;    end
if isfield(opts, 'rho');         rho = opts.rho;              end
if isfield(opts, 'mu');          mu = opts.mu;                end
if isfield(opts, 'max_mu');      max_mu = opts.max_mu;        end
if isfield(opts, 'DEBUG');       DEBUG = opts.DEBUG;          end

[d,n] = size(A);
x = zeros(n,1);
Z = zeros(d,n);
e = zeros(d,1);
Y1 = e;
Y2 = Z;

Atb = A'*b;
AtA = A'*A;
invAtA = (AtA+diag(diag(AtA)))\eye(n);

iter = 0;
for iter = 1 : max_iter
    xk = x;
    ek = e;
    Zk = Z;
    % first super block {Z,e}
    [Z,nuclearnorm] = prox_nuclear(A*diag(x)-Y2/mu,lambda/mu);
    if strcmp(loss,'l1')
        e = prox_l1(b-A*x-Y1/mu,1/mu);
    elseif strcmp(loss,'l2')
        e = mu*(b-A*x-Y1/mu)/(1+mu);
    else
        error('not supported loss function');
    end
    % second super block {x}
    x = invAtA*(-A'*(Y1/mu+e)+Atb+diagAtB(A,Y2/mu+Z));
    dY1 = A*x+e-b;
    dY2 = Z-A*diag(x);
    chgx = max(abs(xk-x));
    chge = max(abs(ek-e));
    chgZ = max(max(abs(Zk-Z)));
    chg = max([chgx chge chgZ max(abs(dY1(:))) max(abs(dY2(:)))]);
    if DEBUG
        if iter == 1 || mod(iter, 10) == 0
            obj = comp_loss(e,loss)+lambda*nuclearnorm;
            err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2);
            disp(['iter ' num2str(iter) ', mu=' num2str(mu) ...
                    ', obj=' num2str(obj) ', err=' num2str(err)]);
        end
    end

    if chg < tol
        break;
    end
    Y1 = Y1 + mu*dY1;
    Y2 = Y2 + mu*dY2;
    mu = min(rho*mu,max_mu);
end
obj = comp_loss(e,loss)+lambda*nuclearnorm;
err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2);

function v = diagAtB(A,B)
% A, B - d*n matrices
% v = diag(A'*B), n*1 vector

n = size(A,2);
v = zeros(n,1);
for i = 1 : n
   v(i) = A(:,i)'*B(:,i);
end

author: canyilu

repo: LibADMM-toolbox


text:
function stat=valsol(time,v,P,vsat,azel,opt)

global glc
%chi-sqr(n) (alpha=0.001)
chisqr=[
    10.8,13.8,16.3,18.5,18.5,22.5,24.3,26.1,27.9,29.6,...
    31.3,32.9,34.5,36.1,37.7,39.3,40.8,42.3,43.8,45.3,...
    46.8,48.3,49.7,51.2,52.6,54.1,55.5,56.9,58.3,59.7,...
    61.1,62.5,63.9,65.2,66.6,68.0,69.3,70.7,72.1,73.4,...
    74.7,76.0,77.3,78.6,80.0,81.3,82.6,84.0,85.4,86.7,...
    88.0,89.3,90.6,91.9,93.3,94.7,96.0,97.4,98.7,100 ,...
    101 ,102 ,103 ,104 ,105 ,107 ,108 ,109 ,110 ,112 ,...
    113 ,114 ,115 ,116 ,118 ,119 ,120 ,122 ,123 ,125 ,...
    126 ,127 ,128 ,129 ,131 ,132 ,133 ,134 ,135 ,137 ,...
    138 ,139 ,140 ,142 ,143 ,144 ,145 ,147 ,148 ,149 ];
stat=1; nx=3+glc.NSYS;

%chi-square test for residuals
nv=size(v,1); var=P^-1;
for i=1:nv
    v(i)=v(i)/sqrt(var(i,i));
end
if nv>nx && dot(v,v)>chisqr(nv-nx)
    [wn,sow]=time2gpst(time);
    fprintf('Warning:GPS week = %d sow = %.3f,chi-square test error! v=%.3f \n',wn,sow,dot(v,v));
    stat=0;
    return;
end

%validate GDOP
ns=0; n=size(vsat,1); azels=zeros(n,2);
for i=1:n
    if vsat(i)==0,continue;end
    azels(ns+1,:)=azel(i,:);
    ns=ns+1;
end
if ns<n
    azels(ns+1:end,:)=[];
end

dop = dops(azels);
if dop(1)<0 || dop(1)>opt.maxgdop
    [wn,sow]=time2gpst(time);
    fprintf('Warning:GPS week = %d sow = %.3f,GDOP test error! GDOP=%.3f \n',wn,sow,dop(1));
    stat=0;
    return;
end

return

repo: GINav


text:
function H = sphankel(r)
%SPHANKEL   Sparse Hankel operator.
%   SPHANKEL(R) this forms a sparse Hankel matrix by forming it as an upside-
%   down Toeplitz matrix. This is required by the ultraspherical multiplication
%   operator.

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

% Hankel is an upside-down Toeplitz matrix.
r = flipud(r(:)); % Ensure column vector.
H = fliplr(triu(ultraS.sptoeplitz(r, r)));

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


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

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

% Last Modified by GUIDE v2.5 22-Jul-2014 15:37:16

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Image2KMLGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @Image2KMLGUI_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 Image2KMLGUI is made visible.
function Image2KMLGUI_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 Image2KMLGUI (see VARARGIN)

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

set(handles.metaicon,'XTick',[]);
set(handles.metaicon,'YTick',[]);
set(handles.metaicon,'Box','on');
set(handles.metaicon,'Color',[51/255 102/255 153/255]);

set(handles.GroundOverlayCheck,'Value',1);
handles.DecType = 'none';
handles.DecSize = 3000;

set(handles.PlotSRP,'Value',1);
set(handles.PlotPath,'Value',1);
set(handles.PlotGroundTrack,'Value',1);
set(handles.PlotCollectionWedge,'Value',1);
set(handles.PlotCenterApVector,'Value',1);
set(handles.PlotPRFLines,'Value',1);

% Update handles structure
guidata(hObject, handles);

p = inputParser; % Extract parameter-value pairs
p.KeepUnmatched=true;
p.addParamValue('filename','');
p.parse(varargin{:});

if ~isempty(p.Results.filename)
    handles = LoadImage(p.Results.filename,handles);
end

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

function filename_Callback(hObject, eventdata, handles)
% hObject    handle to filename (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 filename as text
%        str2double(get(hObject,'String')) returns contents of filename as a double

% --- Executes during object creation, after setting all properties.
function filename_CreateFcn(hObject, eventdata, handles)
% hObject    handle to filename (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 BrowseFile.
function BrowseFile_Callback(hObject, eventdata, handles)
% hObject    handle to BrowseFile (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%load last path
if ispref('matlab_sar_toolbox','last_used_directory')
    pathstr = getpref('matlab_sar_toolbox','last_used_directory');
    if ~ischar(pathstr)||~exist(pathstr,'dir')
        pathstr = pwd;
    end
else
    pathstr = pwd;
end

%get iq filename
[fname, path] = uigetfile(sar_file_extensions({'complex','phd'}),'Open SAR Data File',pathstr);
if isnumeric(fname)
    return;
end

setpref('matlab_sar_toolbox','last_used_directory',path); %store path

filename = strcat(path,fname);
handles = LoadImage(filename,handles);

% Update handles structure
guidata(hObject, handles);

function handles = LoadImage(filename,handles)

set(handles.filename,'String',filename);

% determine if input file is complex image or phase history data
if ~isempty(guess_ph_format(filename))
    MetaIcon_PHD(filename,'handle',handles.metaicon);
    % Should disable all of the image controls here (overlay, boundary, and fill)
else
    MetaIcon_Complex(filename,'handle',handles.metaicon);
end

% --- Executes on button press in WriteKML.
function WriteKML_Callback(hObject, eventdata, handles)
% hObject    handle to WriteKML (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%get kml name from user
%load last path
if ispref('matlab_sar_toolbox','last_used_directory')
    pathstr = getpref('matlab_sar_toolbox','last_used_directory');
    if ~ischar(pathstr)||~exist(pathstr,'dir')
        pathstr = pwd;
    end
else
    pathstr = pwd;
end

%open input file
filename = get(handles.filename,'String');
if ~exist(filename,'file')
    return;
end
is_phase_history = ~isempty(guess_ph_format(filename));
if is_phase_history
    reader_obj = open_ph_reader(filename);
else
    reader_obj = open_reader(filename);
end
if ~iscell(reader_obj) % Assure cell array format
    reader_obj = {reader_obj};
end
meta = reader_obj{1}.get_meta();
[path_ignore, fnameNoExt] = fileparts(filename);
% Open output file
if get(handles.GroundOverlayCheck,'Value')
    [fname, path] = uiputfile( {'*.kmz','KMZ Files (*.kmz)'},'Save KMZ File',[pathstr fnameNoExt]);
else
    [fname, path] = uiputfile( {'*.kml','KML Files (*.kml)'},'Save KML File',[pathstr fnameNoExt]);
end
if ~fname, return; end; % Cancel was pressed
k = kml(meta.CollectionInfo.CoreName); %create an kmltoolbox object
k.filename = fullfile(path, fname);
k.zip = get(handles.GroundOverlayCheck,'Value'); % Only zip if we have overlay images

%set border values
if get(handles.PlotImageBorder,'Value')
    BorderColor = 'Red';
    FillColor = 'Red';
else
    BorderColor = [];
    FillColor = [];
end

%loop through segments
NumSegments = length(reader_obj);
if NumSegments>1
    wb = waitbar(0);
end
for i=1:NumSegments
    if NumSegments>1
        waitbar(i/NumSegments,wb,sprintf('Processing segment %d of %d',i,NumSegments));
    end

    if get(handles.GroundOverlayCheck,'Value')
        %image filename is state with path relative to KML
        ImName = sprintf('Overlay_%d.png',i); % Will be put in same directory where KML is
    else
        ImName = '';
    end
    add_sar_2kml(k,reader_obj{i},...
        'srp',get(handles.PlotSRP,'Value'),...
        'border_color',BorderColor,...
        'border_thickness',1,...
        'fill_color',FillColor,...
        'transparency',0.25,...
        'overlay_max_size',handles.DecSize,...
        'overlay_decimate',handles.DecType,...
        'overlay_filename',ImName,...
        'sensor_path',get(handles.PlotPath,'Value'),...
        'sensor_ground_track',get(handles.PlotGroundTrack,'Value'),...
        'collection_wedge',get(handles.PlotCollectionWedge,'Value'),...
        'center_aperture_vector',get(handles.PlotCenterApVector,'Value'),...
        'ambiguity_bounds',get(handles.PlotPRFLines,'Value'),...
        'description_function',@(x) default_SICD_description(x,get(handles.English,'Value')));
end

k.save();
if ~isempty(k.includeFiles)
    delete(k.includeFiles{:});
end
reader_obj{1}.close; % Multiple segments, but only a single file to close
if NumSegments>1
    close(wb); % Waitbar
end

msgbox('Done creating shapefile');

% --- Executes on button press in GroundOverlayCheck.
function GroundOverlayCheck_Callback(hObject, eventdata, handles)
% hObject    handle to GroundOverlayCheck (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of GroundOverlayCheck

if get(handles.GroundOverlayCheck,'Value')
    %set size of output overlay image based on Quality specified
    switch get(handles.OverlayQualityCombo,'Value');
        case 1
            handles.DecSize = 5000;
        case 2
            handles.DecSize = 3000;
        otherwise
            handles.DecSize = 1000;
    end

    %remap, max decimated typically looks better with "brighter" remap
    if get(handles.MaxDecimateCheck,'Value')
        handles.DecType = 'max';
    else
        handles.DecType = 'none';
    end
else
    handles.DecSize = 0;
    handles.DecType = '';
end
guidata(hObject, handles);

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

% Hint: popupmenu 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 PlotSRP.
function PlotSRP_Callback(hObject, eventdata, handles)
% hObject    handle to PlotSRP (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of PlotSRP

% --- Executes on button press in PlotPath.
function PlotPath_Callback(hObject, eventdata, handles)
% hObject    handle to PlotPath (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of PlotPath

% --- Executes on button press in PlotGroundTrack.
function PlotGroundTrack_Callback(hObject, eventdata, handles)
% hObject    handle to PlotGroundTrack (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of PlotGroundTrack

% --- Executes on button press in PlotCollectionWedge.
function PlotCollectionWedge_Callback(hObject, eventdata, handles)
% hObject    handle to PlotCollectionWedge (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of PlotCollectionWedge

% --- Executes on button press in PlotCenterApVector.
function PlotCenterApVector_Callback(hObject, eventdata, handles)
% hObject    handle to PlotCenterApVector (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of PlotCenterApVector

% --- Executes on button press in PlotPRFLines.
function PlotPRFLines_Callback(hObject, eventdata, handles)
% hObject    handle to PlotPRFLines (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of PlotPRFLines

% --- Executes on button press in Batch.
function Batch_Callback(hObject, eventdata, handles)
% hObject    handle to Batch (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%load last path
if ispref('matlab_sar_toolbox','last_used_directory')
    pathstr = getpref('matlab_sar_toolbox','last_used_directory');
    if ~ischar(pathstr)||~exist(pathstr,'dir')
        pathstr = pwd;
    end
else
    pathstr = pwd;
end

data_dir = uigetdir(pathstr, 'Select directory of SAR data');
if ~data_dir, return; end; % Cancel
setpref('matlab_sar_toolbox','last_used_directory',data_dir); %store path

if get(handles.GroundOverlayCheck,'Value')
    [fname, path] = uiputfile( {'*.kmz','KMZ Files (*.kmz)'},'Save KMZ File',pathstr);
else
    [fname, path] = uiputfile( {'*.kml','KML Files (*.kml)'},'Save KML File',pathstr);
end
if ~fname, return; end; % Cancel was pressed
[path_ignore, fname_no_extension] = fileparts(fname);

%set border values
if get(handles.PlotImageBorder,'Value')
    BorderColor = 'Red';
    FillColor = 'Red';
else
    BorderColor = [];
    FillColor = [];
end

image2kmlbatch(data_dir, strcat(path,fname), ...
    'name',fname_no_extension,...
    'srp',get(handles.PlotSRP,'Value'),...
    'border_color',BorderColor,...
    'border_thickness',1,...
    'fill_color',FillColor,...
    'transparency',0.25,...
    'overlay_max_size',handles.DecSize,...
    'overlay_decimate',handles.DecType,...
    'sensor_path',get(handles.PlotPath,'Value'),...
    'sensor_ground_track',get(handles.PlotGroundTrack,'Value'),...
    'collection_wedge',get(handles.PlotCollectionWedge,'Value'),...
    'center_aperture_vector',get(handles.PlotCenterApVector,'Value'),...
    'ambiguity_bounds',get(handles.PlotPRFLines,'Value'),...
    'description_function',@(x) default_SICD_description(x,get(handles.English,'Value')));
msgbox('Done creating shapefile');

% --- Executes on selection change in OverlayQualityCombo.
function OverlayQualityCombo_Callback(hObject, eventdata, handles)
% hObject    handle to OverlayQualityCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns OverlayQualityCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from OverlayQualityCombo

% --- Executes on button press in PlotImageBorder.
function PlotImageBorder_Callback(hObject, eventdata, handles)
% hObject    handle to PlotImageBorder (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of PlotImageBorder

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

author: ngageoint


text:
function ll = dnetLogLikelihood(model)

% DNETLOGLIKELIHOOD Density network log likelihood.
% FORMAT
% DESC computes the log likelihood of a density network
% model.
% ARG model : the model structure for computing the log likelihood.
% RETURN ll : the model log likelihood.
%
% SEEALSO : modelLogLikeihood
%
% COPYRIGHT : Neil D. Lawrence, 2008

% MLTOOLS

ll = 0.5*model.d*model.N*log(model.beta/(2*pi)) ...
     - model.N*log(model.M);

ll = ll - 0.5*model.alpha*sum(sum(model.A.*model.A)) ...
     - 0.5*model.alpha*sum(model.b.*model.b);

llPointComp = zeros(model.N, model.M);
% Get projections of latent samples.
Ypred = dnetOut(model);

if model.N > model.M
  for i = 1:model.M
    diffY = model.y - repmat(Ypred(i, :), model.N, 1);
    diffY = diffY.*diffY;
    llPointComp(:, i) = - 0.5*model.beta*sum(diffY, 2);
  end
else
  for i = 1:model.N
    diffY = repmat(model.y(i, :), model.M, 1) - Ypred;
    diffY = diffY.*diffY;
    llPointComp(i, :) = - 0.5*model.beta*sum(diffY, 2)';
  end
end

maxllPointComp = max(llPointComp, [], 2);
llPointComp = exp(llPointComp - repmat(maxllPointComp, 1, model.M));
ll = ll + sum(log(sum(llPointComp, 2)) + maxllPointComp);

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


function [ graphGroup ] = GraphCutting( graphGroup, minNum )
%GRAPHCUTTING Summary of this function goes here
%   Detailed explanation goes here

    % looping

end


text:
function smallpot = marginalize_pot(bigpot, keep, maximize, useC)
% MARGINALIZE_POT Marginalize a cgpot onto a smaller domain.
% smallpot = marginalize_pot(bigpot, keep, maximize, useC)
%
% If maximize = 1, we raise an error.
% useC is ignored.

if nargin < 3, maximize = 0; end
assert(~maximize);

sumover = mysetdiff(bigpot.domain, keep);
csumover = myintersect(sumover, bigpot.cdom);
dsumover = myintersect(sumover, bigpot.ddom);
dkeep = myintersect(keep, bigpot.ddom);
ckeep = myintersect(keep, bigpot.cdom);
%ns = sparse(1, max(bigpot.domain)); % must be full, so I is an integer
ns = zeros(1, max(bigpot.domain));
ns(bigpot.ddom) = bigpot.dsizes;
ns(bigpot.cdom) = bigpot.csizes;

% sum(ns(csumover))==0 is like isempty(csumover) but handles observed nodes.
% Similarly, prod(ns(dsumover))==1 is like isempty(dsumover)

% Marginalize the cts parts.
% If we are in canonical form, we stay that way, since moment form might not exist.
% Besides, we would like to minimize the number of conversions.
if sum(ns(csumover)) > 0
  if bigpot.subtype == 'm'
    for i=1:bigpot.dsize
      bigpot.mom{i} = marginalize_pot(bigpot.mom{i}, ckeep);
    end
  else
    for i=1:bigpot.dsize
      bigpot.can{i} = marginalize_pot(bigpot.can{i}, ckeep);
    end
  end
end

% If we are not marginalizing over any discrete nodes, we are done.
if prod(ns(dsumover))==1
  smallpot = cgpot(dkeep, ckeep, ns, bigpot.can, bigpot.mom, bigpot.subtype);
  return;
end

% To marginalize the discrete parts, we partition the cts parts into those that depend
% on dkeep (i) and those that depend on on dsumover (j).

I = prod(ns(dkeep));
J = prod(ns(dsumover));
C = sum(ns(ckeep));
sum_map = find_equiv_posns(dsumover, bigpot.ddom);
keep_map = find_equiv_posns(dkeep, bigpot.ddom);
iv = zeros(1, length(bigpot.ddom)); % index vector

% If in canonical form, marginalize if possible, else convert to moment form.
if 0 & bigpot.subtype == 'c'
  p1 = zeros(I,J);
  h1 = zeros(C,J,I);
  K1 = zeros(C,C,J,I);
  for i=1:I
    keep_iv = ind2subv(ns(dkeep), i);
    iv(keep_map) = keep_iv;
    for j=1:J
      sum_iv = ind2subv(ns(dsumover), j);
      iv(sum_map) = sum_iv;
      k = subv2ind(ns(bigpot.ddom), iv);
      can = struct(bigpot.can{k}); % violate object privacy
      p1(i,j) = exp(can.g);
      if C > 0 % so mu1 and Sigma1 are non-empty
	h1(:,j,i) = can.h;
	K1(:,:,j,i) = can.K;
      end
    end
  end

  % If the cts parts do not depend on j, we can just marginalize the weighting coefficient g.
  jdepends = 0;
  for i=1:I
    for j=2:J
      if ~approxeq(h1(:,j,i), h1(:,1,i)) | ~approxeq(K1(:,:,j,i), K1(:,:,1,i))
	jdepends = 1;
	break
      end
    end
  end

  if ~jdepends
    %g2 = log(sum(p1, 2));
    g2 = zeros(I,1);
    for i=1:I
      s = sum(p1(i,:));
      if s > 0
	g2(i) = log(s);
      end
    end
    h2 = h1;
    K2 = K1;
    can = cell(1,I);
    j = 1; % arbitrary
    for i=1:I
      can{i} = cpot(ckeep, ns(ckeep), g2(i), h2(:,j,i), K2(:,:,j,i));
    end
    smallpot = cgpot(dkeep, ckeep, ns, can, [], 'c');
    return;
  else
    % Since the cts parts depend on j, we must convert to moment form
    bigpot = cg_can_to_mom(bigpot);
  end
end

% Marginalize in moment form
bigpot = cg_can_to_mom(bigpot);

% Now partition the moment components.
T1 = zeros(I,J);
mu1 = zeros(C,J,I);
Sigma1 = zeros(C,C,J,I);
for i=1:I
  keep_iv = ind2subv(ns(dkeep), i);
  iv(keep_map) = keep_iv;
  for j=1:J
    sum_iv = ind2subv(ns(dsumover), j);
    iv(sum_map) = sum_iv;
    k = subv2ind(ns(bigpot.ddom), iv);
    mom = struct(bigpot.mom{k}); % violate object privacy
    T1(i,j) = exp(mom.logp);
    if C > 0 % so mu1 and Sigma1 are non-empty
      mu1(:,j,i) = mom.mu;
      Sigma1(:,:,j,i) = mom.Sigma;
    end
  end
end

% Collapse the mixture of Gaussians
coef = mk_stochastic(T1); % coef must be convex combination
T2 = sum(T1,2);
T2 = T2 + (T2==0)*eps;
%if C > 0, disp('collapsing onto '); disp(leep); end
mu = [];
Sigma = [];
mom = cell(1,I);
for i=1:I
  if C > 0
    [mu, Sigma] = collapse_mog(mu1(:,:,i), Sigma1(:,:,:,i), coef(i,:));
  end
  logp = log(T2(i));
  mom{i} = mpot(ckeep, ns(ckeep), logp, mu, Sigma);
end

smallpot = cgpot(dkeep, ckeep, ns, [], mom, 'm');

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


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

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

% Last Modified by GUIDE v2.5 30-Nov-2022 05:02:39

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @APTProject_OpeningFcn, ...
                   'gui_OutputFcn',  @APTProject_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 APTProject is made visible.
function APTProject_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 APTProject (see VARARGIN)

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

[lbl_file,aptStruct] = myparse(varargin,'lbl_file','','aptStruct',struct());

aptStruct.lbl_file = lbl_file;
if ~isfield(aptStruct,'featureLexicon')
  aptStruct.featureLexicon = [];
  aptStruct.featureLexiconName = '';
end

if ~isfield(aptStruct,'origFeatureLexiconName')
  aptStruct.origFeatureLexiconName = '';
end
if isfield(aptStruct,'animalType'),
else
  aptStruct.animalType = '';
end
if isfield(aptStruct,'n_pts'),
else
  aptStruct.n_pts = 0;
end
if isfield(aptStruct,'n_view'),
else
  aptStruct.n_view = 0;
end
if isfield(aptStruct,'projname'),
else
  aptStruct.projname = '';
end
if isfield(aptStruct,'trkfilename'),
else
  aptStruct.trkfilename = '';
end

handles.aptStruct = aptStruct;
% Update handles structure
guidata(hObject, handles);

% Checks
if isempty(lbl_file)
  % close the gui if there is no label file.
  % the gui is closed in outputfcn.
  return
end

h = waitbar(0,'Loading label file');
handles.waitbar = h;
guidata(hObject,handles);
try
  apt = loadLbl(lbl_file);
catch ME
  errmsg = sprintf('Could not load label file %s',ME.message);
  uiwait(errordlg(errmsg, 'Unable to load label file'));
  handles.aptStruct.lbl_file = '';
  guidata(hObject,handles);
  return;
end

if isempty(apt.movieFilesAll)
  uiwait(errordlg('APT Label file should have at least one movie','Empty APT project'));
  return;
end

%
handles.apt = apt;
handles.has_trx = apt.projectHasTrx;
if isfield(apt,'maIsMA')
  handles.is_ma = apt.maIsMA;
else
  handles.is_ma = false;
end
handles.has_crops = ~isempty(apt.movieFilesAllCropInfo{1});
aptStruct.n_pts = apt.cfg.NumLabelPoints;
aptStruct.skeletonEdges = apt.skeletonEdges;
if handles.is_ma
  if ~isempty(apt.skelHead)
    handles.head_tail = [apt.skelHead apt.skelTail];
    handles.use_theta = true;
  else
    handles.head_tail = [];
    handles.use_theta = false;
  end
  sz = apt.trackParams.ROOT.MultiAnimal.TargetCrop.ManualRadius;
  handles.sz = [sz,sz];
%  assert 'APT multi-animal projects not yet implemented';
elseif handles.has_trx
  if isfield(apt.trackParams.ROOT.ImageProcessing.MultiTarget,'TargetCrop')
    handles.use_theta = apt.trackParams.ROOT.ImageProcessing.MultiTarget.TargetCrop.AlignUsingTrxTheta;
    sz = apt.trackParams.ROOT.ImageProcessing.MultiTarget.TargetCrop.Radius;
  else
    handle.use_theta = apt.trackParams.ROOT.MultiAnimal.TargetCrop.AlignUsingTrxTheta;
    sz = apt.trackParams.ROOT.MultiAnimal.TargetCrop.ManualRadius;
  end
  handles.sz = [sz,sz];
  handles.head_tail = [apt.skelHead apt.skelTail];
elseif handles.has_crops
  % dont use theta if there is no trx file.
  % might need updating later.
  handles.use_theta = true;
  ff = apt.movieFilesAllCropInfo{1}(1).roi;
  ht = ff(4)-ff(3)+1; wd = ff(2)-ff(1)+1;
  handles.sz = [ht,wd];
else
  handles.use_theta = true;
  ht = apt.movieInfoAll{1}.info.nr;
  wd = apt.movieInfoAll{1}.info.nc;
  handles.sz = [ht,wd];
end

[featureList,xmlList] = getFeatureLexiconListsFromXML();
stFeatures = cellfun(@xmlParamsIsST,xmlList);
featureList = featureList(~stFeatures);
xmlList = xmlList(~stFeatures);
handles.trxList = {featureList, xmlList};

% handles.global_ftrs = {'velmag'};
% handles.body_ftrs = {'velmag',...
%           'distcenter', 'ddistcenter'};
% handles.theta_ftrs = {'x','y','dx','dy',...
%           'dtheta', 'sin', 'cos'};
handles.common_ftrs = {'global_velmag','body_velmag',...
          'body_distcenter', 'body_ddistcenter',...
          'body_x','body_y','body_dx','body_dy',...
          'body_dtheta', 'body_sin', 'body_cos'};
handles.pair_ftrs = {'velmag',...
          'ddist','dist', ... % These are same body_ftrs
          'x','y','dx','dy',...
          'dtheta','cos','sin',... % these are same theta_ftrs
          'areaswept'};
handles.triad_ftrs = {'cos','sin','dangle',...
          'area','darea','dlen'};

waitbar(.5,handles.waitbar,'Reading example frame from movie file');
handles.aptStruct = aptStruct;
handles = initialize(handles);
delete(handles.waitbar);
guidata(hObject,handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = APTProject_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
if ~isempty(handles.aptStruct.lbl_file)
  uiwait(handles.figure1);
end
if ~isgraphics(hObject)
  aptStruct = struct();
  aptStruct.featureLexicon = [];
  varargout{1} = aptStruct;
  return;
end
handles = guidata(hObject);
varargout{1} = handles.aptStruct;
if isgraphics(handles.waitbar)
  delete(handles.waitbar);
end
figure1_CloseRequestFcn(hObject,eventdata,handles);

function handles = initialize(handles)
is_multi = handles.has_trx|handles.is_ma;
handles.is_multi = is_multi;
set(handles.trx_pop,'Enable',onoffif(is_multi));
set(handles.trx_pop,'Visible',onoffif(is_multi));
set(handles.trx_checkbox,'Visible',onoffif(is_multi));
set(handles.trx_checkbox,'Value',is_multi);
set(handles.group_notrx,'Visible',onoffif(~is_multi));
set(handles.rb_centroid,'Visible',onoffif(~is_multi));
set(handles.rb_frame,'Visible',onoffif(~is_multi));
set(handles.rb_crop,'Visible',onoffif(~is_multi));
set(handles.rb_custom,'Visible',onoffif(~is_multi));
set(handles.text_centroid,'Visible',onoffif(~is_multi));

if is_multi
  set(handles.trx_pop,'String',handles.trxList{1})
  trx_type_ndx = find(strcmp(handles.aptStruct.origFeatureLexiconName,handles.trxList{1}),1);
  if ~isempty(trx_type_ndx),
    set(handles.trx_pop,'Value',trx_type_ndx);
  else
    set(handles.trx_pop,'Value',1);
  end
  set(handles.trx_checkbox,'Value',true);
  set(handles.edit_social,'Enable','on')
else
  set(handles.trx_pop,'String',{''})
  set(handles.trx_pop,'Value',0)
  set(handles.trx_checkbox,'Value',true);
  if handles.has_crops
    set(handles.rb_crop,'Value',true);
    set(handles.rb_frame,'Value',false);
    set(handles.rb_crop,'Enable','on');
  else
    set(handles.rb_crop,'Value',false);
    set(handles.rb_crop,'Enable','off');
    set(handles.rb_frame,'Value',true);
  end
  set(handles.rb_centroid,'Value',false);
  set(handles.edit_social,'Enable','off')
end

% load a reference image and point locations.
apt = handles.apt;
has_ref_img = false;
has_mov = true;
for ndx = 1:size(apt.movieFilesAll,1)
  has_label = false;
  tndx_to_use = 1;
  locs = [];
  if isfield(apt,'labeledpos')
    s = apt.labeledpos{ndx};
    cur_pts = nan(s.size);
    cur_pts(s.idx) = s.val; % scalar expansion for 'log'
    for tndx = 1:size(cur_pts,4)
      frm = find(~isnan(cur_pts(1,1,:,tndx)),1);
      if isempty(frm)
        continue;
      else
        has_label = true;
        tndx_to_use = tndx;
        locs = cur_pts(:,:,frm,tndx);
        break;
      end
    end
  else
    s = apt.labels{ndx};
    assert(isstruct(s));
    cur_pts = s.p;
    if numel(s.frm)>0
      has_label = true;
      frm = s.frm(1);
      tndx_to_use = s.tgt(1);
      locs = reshape(s.p(:,1),[s.npts,2]);
    else
      has_label = false;
    end
  end

  if ~has_label
    continue;
  end

  mov_files = {};
  trx_files = {};
  for m_ndx = 1:size(apt.movieFilesAll,2)
    mov_file = unMacroise(apt.movieFilesAll{ndx,m_ndx},apt);
    if ~exist(mov_file,'file')
      [bdir,mname,mext] =fileparts(mov_file);
      qstr = sprintf('JAABA needs movie file %s%s to show a reference labeled example, but it does not exist at location %s. Browse to movie? If you select no, no reference image will be shown.',mname,mext,bdir);
      res = questdlg(qstr,'Missing movie file...','Yes','No','Cancel','Yes');
      if strcmp(res,'Yes')
        [fname,fpath] = uigetfile('',['Missing ' mov_file]);
        if ~isequal(fname,0)
          mov_files{end+1} = fullfile(fpath,fname);
          if handles.has_trx
            trx_file = getTrxFile(apt.trxFilesAll{ndx},mov_file);
            [fname,fpath] = uigetfile('',['Missing ' trx_file]);
            trx_files{end+1} = fullfile(fpath,fname);
          end
        else
          has_mov = false;
          break;
        end
      else
        has_mov = false;
        break;
      end
    else
      mov_files{end+1} = mov_file;
      tt = unMacroise(apt.trxFilesAll{ndx,m_ndx},apt);
      aa = fileparts(mov_files{end});
      tt = strrep(tt,'$movdir',aa);
      trx_files{end+1} = tt;
    end
  end

  if ~has_mov
    break;
  end

  has_ref_img = true;
  img = []; all_locs = []; prev_width = 0;
  for m_ndx = 1:size(apt.movieFilesAll,2)
    mov_file = mov_files{m_ndx};
    if has_mov
      rfn = get_readframe_fcn(mov_file);
      cur_img = rfn(frm);
    else
      nr = apt.movieInfoAll{ndx,m_ndx}.info.nr;
      nc = apt.movieInfoAll{ndx,m_ndx}.info.nc;
      cur_img = zeros(nr,nc);
    end
    if handles.has_trx
      trx = load(trx_files{m_ndx},'-mat');
      trx = trx.trx(tndx_to_use);
      off = trx.off;
      x = trx.x(frm+off);
      y = trx.y(frm+off);
      theta = trx(tndx_to_use).theta(frm+off);
      [cur_img, aff_mat] = CropImAroundTrx(cur_img,x,y,theta,handles.sz(2),handles.sz(1));
      ll = locs*aff_mat(1:2,1:2);
      ll(:,2) = ll(:,2)+aff_mat(3,2) + handles.sz(1) + 0.5;
      ll(:,1) = ll(:,1)+aff_mat(3,1) + handles.sz(2) + 0.5;
      ll(:,1) = ll(:,1) + prev_width;
    elseif handles.is_ma
      if ~isempty(handles.head_tail)
        h_pt = locs(handles.head_tail(1),:);
        t_pt = locs(handles.head_tail(2),:);
        x = (h_pt(1)+t_pt(1))/2;
        y = (h_pt(2)+t_pt(2))/2;
        dy = (h_pt(2)-t_pt(2));
        dx = (h_pt(1)-t_pt(1));
        theta = atan2( dy,dx );
      else
        x = mean(locs(:,1));
        y = mean(locs(:,2));
        theta = 0;
      end
      [cur_img, aff_mat] = CropImAroundTrx(cur_img,x,y,theta,handles.sz(2),handles.sz(1));
      ll = locs*aff_mat(1:2,1:2);
      ll(:,2) = ll(:,2)+aff_mat(3,2) + handles.sz(1) + 0.5;
      ll(:,1) = ll(:,1)+aff_mat(3,1) + handles.sz(2) + 0.5;
      ll(:,1) = ll(:,1) + prev_width;
    else
      n_pts = handles.aptStruct.n_pts;
      st = (m_ndx-1)*n_pts + 1; en = m_ndx*n_pts;
      ll = locs(st:en,:);
      ll(:,1) = ll(:,1) + prev_width;
    end
    img = cat(2,img,cur_img);
    prev_width = size(img,2);
    all_locs = cat(1,all_locs,ll);
  end
  if is_multi
    img = cat(1,img,img);
  end

  break
end

if has_ref_img
  handles.im = img;
  handles.locs = all_locs;
else
  handles.im = [];
  handles.locs = [];
end

set(handles.text_centroid,'String','');

npts = apt.cfg.NumLabelPoints;
if isfield(handles.aptStruct,'pairs') && ~isempty(handles.aptStruct.pairs),
  isvalid = all(cellfun(@(x) all(x==round(x)) && numel(x) == 2 && x(1) ~= x(2) && ...
    all(x>=1) && all(x<=npts),handles.aptStruct.pairs));
  if isvalid,
    pairstr = sprintf('%d %d, ',handles.aptStruct.pairs{:});
    pairstr = pairstr(1:end-2);
    set(handles.edit_pair,'String',pairstr);
  end
end

if isfield(handles.aptStruct,'triads') && ~isempty(handles.aptStruct.triads),
  isvalid = all(cellfun(@(x) all(x==round(x)) && numel(x) == 3 && numel(unique(x))==3 && ...
    all(x>=1) && all(x<=npts),handles.aptStruct.triads));
  if isvalid,
    str = sprintf('%d %d %d, ',handles.aptStruct.triads{:});
    str = str(1:end-2);
    set(handles.edit_triad,'String',str);
  end
end

if isfield(handles.aptStruct,'custom_list') && ~isempty(handles.aptStruct.custom_list),
  str = sprintf('%s, ',handles.aptStruct.custom_list{:});
  str = str(1:end-2);
  set(handles.edit_custom,'String',str);
end

isvalid = ~isempty(handles.aptStruct.trkfilename) && ...
  isvalid_default_trkfilename(handles,handles.aptStruct.trkfilename);
if isvalid,
  str = sprintf('%s, ',handles.aptStruct.trkfilename{:});
  str = str(1:end-2);
  set(handles.edit_trk,'String',str);
else
  trkfilename = reset_trk_edit(handles);
  handles.aptStruct.trkfilename = trkfilename;
end

handles.aptStruct.n_pts = apt.cfg.NumLabelPoints;
handles.aptStruct.n_view = apt.cfg.NumViews;
handles.aptStruct.projname = apt.projname;
handles.aptStruct.head_tail = handles.head_tail;
% handles.aptStruct.featureLexicon = [];
% handles.aptStruct.featureLexiconName = '';
% handles.aptStruct.animalType = '';
handles.aptStruct.view = 1;
handles.aptStruct.is_ma = handles.is_ma;

handles = UpdateHandles(handles);
%UpdatePlots(handles)

function handles = UpdateHandles(handles)
handles.use_trx = get(handles.trx_checkbox,'Value');
if handles.has_trx || handles.is_ma
  trx_type_ndx = get(handles.trx_pop,'Value');
  featureLexiconName = handles.trxList{1}{trx_type_ndx};
  [featureLexicon,animalType]=featureLexiconFromFeatureLexiconName(featureLexiconName);
else
  featureLexiconName = 'apt';
  animalType = 'apt';
end
handles.aptStruct.origFeatureLexiconName = featureLexiconName;
if handles.has_trx || handles.is_ma
  handles.aptStruct.featureLexiconName = [featureLexiconName '_' handles.aptStruct.projname];
else
  handles.aptStruct.featureLexiconName = featureLexiconName;
end

handles.aptStruct.animalType = animalType;
% pairs
str = get(handles.edit_pair,'String');
pairs = parse_pairs(str,handles,true);
handles.pairs = pairs;

% triads
str = get(handles.edit_triad,'String');
pair_str = strsplit(str,',');
triads = {};
if ~isempty(pair_str{1}),
  for ndx = 1:numel(pair_str)
    cur_str = strtrim(pair_str{ndx});
    cur_pair = strsplit(cur_str);
    if numel(cur_pair)~=3
      uiwait(errordlg('Incorrect format for specifying triads.'));
      triads = {}; break;
      return;
    end
    pts = [];
    is_error = false;
    for pndx = 1:numel(cur_pair)
      cur_p = str2double(cur_pair{pndx});
      if round(cur_p) ~= cur_p || isnan(cur_p)
        uiwait(errordlg('Please specify points as integer'));
        triads = {}; is_error = true; break;
      end
      if cur_p > handles.aptStruct.n_pts
        uiwait(errordlg(sprintf('Points should be between 1 and %d',handles.aptStruct.n_pts)));
        triads = {};  is_error = true;break;
      end
      pts(end+1) = cur_p;
    end
    if is_error, triads = {}; break; end
    if numel(unique(pts))~=3
      uiwait(errordlg('Cannot use same points twice in the triads'));
      triads = {}; break;
    end
    triads{end+1} = pts;
  end
end
handles.triads = triads;

if handles.is_multi
  str = get(handles.edit_social,'String');
  social_pairs = parse_pairs(str,handles,false);
  handles.social_pairs = social_pairs;

end

% custom
str = get(handles.edit_custom,'String');
pair_str = strsplit(str,',');
custom_list = {};
if ~isempty(pair_str{1}),
  for ndx = 1:numel(pair_str)
    custom_list{ndx} = strtrim(pair_str{ndx});
  end
end
handles.custom_list = custom_list;
trk_file_str = strtrim(get(handles.edit_trk,'String'));
trkfiles = strsplit(trk_file_str,',');
handles.aptStruct.trkfilename = trkfiles;
UpdatePlots(handles);

function pairs = parse_pairs(str,handles,check_match)
pair_str = strsplit(str,',');
pairs = {};
if ~isempty(pair_str{1}),
  for ndx = 1:numel(pair_str)
    cur_str = strtrim(pair_str{ndx});
    cur_pair = strsplit(cur_str);
    if numel(cur_pair)~=2
      uiwait(errordlg('Incorrect format for specifying pairs.'));
      pairs = {}; break;
    end
    pts = [];
    is_error = false;
    for pndx = 1:numel(cur_pair)
      cur_p = str2double(cur_pair{pndx});
      if round(cur_p) ~= cur_p || isnan(cur_p)
        uiwait(errordlg('Please specify points as integer'));
        pairs = {}; is_error = true; break;
      end
      if cur_p > handles.aptStruct.n_pts
        uiwait(errordlg(sprintf('Points should be between 1 and %d',handles.n_pts)));
        pairs = {};  is_error = true;break;
      end
      pts(end+1) = cur_p;
    end
    if is_error
      pairs = {}; break;
    end
    if (pts(1) == pts(2))&&check_match
      uiwait(errordlg('Cannot use same point in pairs'));
      pairs = {}; break;
    end
    pairs{end+1} = pts;
  end
end

function filename = unMacroise(filename,apt)
macros = fieldnames(apt.projMacros);
for fndx = 1:numel(macros)
  f = macros{fndx};
  filename = strrep(filename,sprintf('$%s',f),apt.projMacros.(f));
end

function trxfile = getTrxFile(trxfile,movfile)
movdir = fileparts(movfile);
trxfile = strrep(trxfile,'$movdir',movdir);

function UpdatePlots(handles)
if isempty(handles.im)
  axis(handles.axes1,'off');
  return
end
is_multi = handles.has_trx|handles.is_ma;

axes(handles.axes1);
img = handles.im;
ll = double(handles.locs);
hsz = size(img,1)/2;

imh = imshow(img);
if is_multi
  if ndims(img)>2
    alpha = img(:,:,1);
  else
    alpha = img;
  end
  alpha = double(alpha);
  alpha(hsz+1:end,:) = 0.2;
  alpha(1:hsz,:) = 1.;
  imh.AlphaData = alpha;
  text(12,12,'Current Animal');
  text(12,hsz+12,'Other Animal');
end
hold on;
scatter(ll(:,1),ll(:,2),'.');
for ndx = 1:size(ll,1)
  cur_n = modrange(ndx,1,handles.aptStruct.n_pts+1);
  text(ll(ndx,1)+1,ll(ndx,2)+1,num2str(cur_n),'Color',[1 0 0]);
end
if is_multi
  scatter(ll(:,1),ll(:,2)+hsz,'.')
  for ndx = 1:size(ll,1)
    cur_n = modrange(ndx,1,handles.aptStruct.n_pts+1);
    text(ll(ndx,1)+1,ll(ndx,2)+1+hsz,num2str(cur_n),'Color',[0 1 0]);
  end
end
for pndx = 1:numel(handles.pairs)
  for view = 1:handles.aptStruct.n_view
    n_pts = handles.aptStruct.n_pts;
    p = ll(handles.pairs{pndx}+(view-1)*n_pts,:);
    plot(p(:,1),p(:,2));
  end
end
if handles.is_multi
  spair = handles.social_pairs;
  for pndx = 1:numel(spair)
    for view = 1:handles.aptStruct.n_view
      p1 = ll(spair{pndx}(1),:);
      p2 = ll(spair{pndx}(2),:);
      p2(2) = p2(2) + hsz;
      plot([p1(1) p2(1)],[p1(2) p2(2)],'Color',[0 0 1],'LineStyle',':');
    end
  end

end
hold off;
handles.im = img;
handles.locs = ll;
axis(handles.axes1,'off');

function all_trkfilenames = reset_trk_edit(handles)
apt = handles.apt;
trk_file_str = '';
all_trkfilenames = cell(1,size(apt.movieFilesAll,2));
for ndx = 1:size(apt.movieFilesAll,2)
  %mov_file = apt.movieFilesAll{1,ndx};
  [~,movfilename,~] = fileparts(apt.movieFilesAll{1,ndx});
  [~,projfile,~] = fileparts(handles.aptStruct.lbl_file);
  trkfilename = [movfilename '_' projfile '.trk'];
  if isempty(trk_file_str)
    trk_file_str = trkfilename;
  else
    trk_file_str = sprintf('%s,%s',trk_file_str,trkfilename);
  end
  all_trkfilenames{ndx} = trkfilename;
end
set(handles.edit_trk,'String',trk_file_str)

function isvalid = isvalid_default_trkfilename(handles,trkfilename)
apt = handles.apt;
isvalid = false;
% check number of views
if numel(trkfilename) ~= size(apt.movieFilesAll,2),
  return;
end

[~,projfile,~] = fileparts(handles.aptStruct.lbl_file);
for ndx = 1:size(apt.movieFilesAll,2),
  [~,movfilename,~] = fileparts(apt.movieFilesAll{1,ndx});
  basename = [movfilename '_' projfile];
  if ~startsWith(trkfilename{ndx},basename) || ~endsWith(trkfilename{ndx},'.trk'),
    return;
  end

end
isvalid = true;

function onoff = onoffif(in)
if in
  onoff = 'on';
else
  onoff = 'off';
end

% --- Executes on button press in trx_checkbox.
function trx_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to trx_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of trx_checkbox

% --- Executes on button press in body_checkbox.
function body_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to body_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of body_checkbox

% --- Executes on button press in checkbox3.
function checkbox3_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox3

% --- Executes on button press in checkbox4.
function checkbox4_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox4

% --- Executes on button press in checkbox5.
function checkbox5_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox5

function edit_pair_Callback(hObject, eventdata, handles)
% hObject    handle to edit_pair (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 edit_pair as text
%        str2double(get(hObject,'String')) returns contents of edit_pair as a double
handles = UpdateHandles(handles);
guidata(hObject,handles)

% --- Executes during object creation, after setting all properties.
function edit_pair_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_pair (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

function edit_triad_Callback(hObject, eventdata, handles)
% hObject    handle to edit_triad (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 edit_triad as text
%        str2double(get(hObject,'String')) returns contents of edit_triad as a double
handles = UpdateHandles(handles);
guidata(hObject,handles)

% --- Executes during object creation, after setting all properties.
function edit_triad_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_triad (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

function edit_custom_Callback(hObject, eventdata, handles)
% hObject    handle to edit_custom (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 edit_custom as text
%        str2double(get(hObject,'String')) returns contents of edit_custom as a double
handles = UpdateHandles(handles);
guidata(hObject,handles)

% --- Executes during object creation, after setting all properties.
function edit_custom_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_custom (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 selection change in trx_pop.
function trx_pop_Callback(hObject, eventdata, handles)
% hObject    handle to trx_pop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns trx_pop contents as cell array
%        contents{get(hObject,'Value')} returns selected item from trx_pop
handles = UpdateHandles(handles);
guidata(hObject,handles)

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

% Hint: popupmenu 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 global_checkbox.
function global_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to global_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of global_checkbox
handles = UpdateHandles(handles);
guidata(hObject,handles)

% --- Executes on button press in theta_checkbox.
function theta_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to theta_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of theta_checkbox
handles = UpdateHandles(handles);
guidata(hObject,handles)

% --- Executes on button press in done_pb.
function done_pb_Callback(hObject, eventdata, handles)
% hObject    handle to done_pb (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles = UpdateHandles(handles);
handles.perframe = struct;
if handles.has_trx || handles.is_ma
  featureLexiconName = handles.aptStruct.origFeatureLexiconName;
  [featureLexicon,animalType]=featureLexiconFromFeatureLexiconName(featureLexiconName);
  if ~handles.use_trx
    f = fieldnames(featureLexicon.perframe);
    for fndx = 1:numel(f)
      featureLexicon.perframe = rmfield(featureLexicon.perframe,f{fndx});
    end
  end
else
  featureLexiconName = 'apt';
  animalType = 'apt';
  [featureLexicon,~]=featureLexiconFromFeatureLexiconName('flies');
  f = fieldnames(featureLexicon.perframe);
  for fndx = 1:numel(f)
    featureLexicon.perframe = rmfield(featureLexicon.perframe,f{fndx});
  end
end

handles.aptStruct.animalType = animalType;
trans_type = {'none' 'relative'};
common_struct = struct();
common_struct.trans_types=trans_type;
common_struct.type='apt_locomotion';
dphi_struct = common_struct;
dphi_struct.trans_types = {'none' 'abs'};
dtheta_struct = common_struct;
dtheta_struct.trans_types = {'none'};

n_pts = handles.aptStruct.n_pts;
n_view = handles.aptStruct.n_view;
cur_set = handles.common_ftrs;
for fndx = 1:numel(cur_set)
  for ndx = 1:n_pts
    for view = 1:n_view
      cur_ftr = sprintf('apt_view%d_%s_%d',view,cur_set{fndx},ndx);
      if contains(cur_ftr,'dphi')
        featureLexicon.perframe.(cur_ftr) = dphi_struct;
      elseif contains(cur_ftr,'dtheta')
        featureLexicon.perframe.(cur_ftr) = dtheta_struct;
      else
        featureLexicon.perframe.(cur_ftr) = common_struct;
      end
    end
  end
end

% if handles.use_global
%   if handles.has_trx
%     cur_set = handles.global_ftrs;
%   else
%     cur_set = cat(2,handles.global_ftrs,handles.theta_ftrs);
%   end
%   for fndx = 1:numel(cur_set)
%     for ndx = 1:n_pts
%       cur_ftr = sprintf('apt_global_%s_%d',cur_set{fndx},ndx);
%       if contains(cur_ftr,'dphi')
%         featureLexicon.perframe.(cur_ftr) = dphi_struct;
%       elseif contains(cur_ftr,'dtheta')
%         featureLexicon.perframe.(cur_ftr) = dtheta_struct;
%       else
%         featureLexicon.perframe.(cur_ftr) = common_struct;
%       end
%     end
%   end
% end
% if handles.use_body
%   cur_set = handles.body_ftrs;
%   for fndx = 1:numel(cur_set)
%     for ndx = 1:n_pts
%       cur_ftr = sprintf('apt_body_%s_%d',cur_set{fndx},ndx);
%       if contains(cur_ftr,'dphi')
%         featureLexicon.perframe.(cur_ftr) = dphi_struct;
%       elseif contains(cur_ftr,'dtheta')
%         featureLexicon.perframe.(cur_ftr) = dtheta_struct;
%       else
%         featureLexicon.perframe.(cur_ftr) = common_struct;
%       end
%     end
%   end
% end
% if handles.use_theta
%   cur_set = handles.theta_ftrs;
%   for fndx = 1:numel(cur_set)
%     for ndx = 1:n_pts
%       cur_ftr = sprintf('apt_body_%s_%d',cur_set{fndx},ndx);
%       if contains(cur_ftr,'dphi')
%         featureLexicon.perframe.(cur_ftr) = dphi_struct;
%       elseif contains(cur_ftr,'dtheta')
%         featureLexicon.perframe.(cur_ftr) = dtheta_struct;
%       else
%         featureLexicon.perframe.(cur_ftr) = common_struct;
%       end
%     end
%   end
% end

% pair features
for pndx = 1:numel(handles.pairs)
  cur_set = handles.pair_ftrs;
  cur_p = handles.pairs{pndx};
  for fndx = 1:numel(cur_set)
    for view = 1:n_view

      cur_ftr = sprintf('apt_view%d_pair_%s_%d_%d',view,cur_set{fndx},cur_p(1),cur_p(2));
      if contains(cur_ftr,'dphi')
        featureLexicon.perframe.(cur_ftr) = dphi_struct;
      elseif contains(cur_ftr,'dtheta')
        featureLexicon.perframe.(cur_ftr) = dtheta_struct;
      else
        featureLexicon.perframe.(cur_ftr) = common_struct;
      end
    end
  end
end
% triad features
for pndx = 1:numel(handles.triads)
  cur_set = handles.triad_ftrs;
  cur_p = handles.triads{pndx};
  for fndx = 1:numel(cur_set)
    for view = 1:n_view
      cur_ftr = sprintf('apt_view%d_triad_%s_%d_%d_%d',view,cur_set{fndx},cur_p(1),cur_p(2),cur_p(3));
      if contains(cur_ftr,'dphi')
        featureLexicon.perframe.(cur_ftr) = dphi_struct;
      elseif contains(cur_ftr,'dtheta')
        featureLexicon.perframe.(cur_ftr) = dtheta_struct;
      else
        featureLexicon.perframe.(cur_ftr) = common_struct;
      end
    end
  end
end

if handles.is_multi
  social_struct = struct();
  social_struct.trans_types=trans_type;
  social_struct.type='apt_social';

  for ndx = 1:n_pts
    for view = 1:n_view
      cur_ftr = sprintf('apt_view%d_social_dist_%d',view,ndx);
      featureLexicon.perframe.(cur_ftr) = social_struct;
      cur_ftr = sprintf('apt_view%d_social_ddist_%d',view,ndx);
      featureLexicon.perframe.(cur_ftr) = social_struct;
      cur_ftr = sprintf('apt_view%d_social_sin_%d',view,ndx);
      featureLexicon.perframe.(cur_ftr) = social_struct;
      cur_ftr = sprintf('apt_view%d_social_cos_%d',view,ndx);
      featureLexicon.perframe.(cur_ftr) = social_struct;
    end
  end

  % social pair features
  for pndx = 1:numel(handles.social_pairs)
    cur_p = handles.social_pairs{pndx};
    for view = 1:n_view
      cur_ftr = sprintf('apt_view%d_socialpair_dist_%d_%d',view,cur_p(1),cur_p(2));
      featureLexicon.perframe.(cur_ftr) = social_struct;
      cur_ftr = sprintf('apt_view%d_socialpair_ddist_%d_%d',view,cur_p(1),cur_p(2));
      featureLexicon.perframe.(cur_ftr) = social_struct;
      cur_ftr = sprintf('apt_view%d_socialpair_sin_%d_%d',view,cur_p(1),cur_p(2));
      featureLexicon.perframe.(cur_ftr) = social_struct;
      cur_ftr = sprintf('apt_view%d_socialpair_cos_%d_%d',view,cur_p(1),cur_p(2));
      featureLexicon.perframe.(cur_ftr) = social_struct;
    end
  end
end

for pndx = 1:numel(handles.custom_list)
  trans_type = {'none' 'relative'};
  cur_ftr = handles.custom_list{pndx};
  featureLexicon.perframe.(cur_ftr) = common_struct;
end
handles.aptStruct.featureLexicon = featureLexicon;
handles.aptStruct.has_trx = handles.has_trx;
handles.aptStruct.has_crops = handles.has_crops;
handles.aptStruct.pairs = handles.pairs;
handles.aptStruct.triads = handles.triads;
handles.aptStruct.custom_list = handles.custom_list;

if handles.has_trx
  handles.aptStruct.apt_trx_type = '';
elseif handles.is_ma
  handles.aptStruct.apt_trx_type = 'ma';
  handles.aptStruct.ma_head_tail = handles.head_tail;
  handles.aptStruct.ma_use_theta = handles.use_theta;
else
  if get(handles.rb_frame,'Value')
    handles.aptStruct.apt_trx_type = 'frame';
  elseif  get(handles.rb_crop,'Value')
    handles.aptStruct.apt_trx_type = 'crop';
  elseif  get(handles.rb_custom,'Value')
    handles.aptStruct.apt_trx_type = 'custom';
  else
    handles.aptStruct.apt_trx_type = 'trk';
    handles.aptStruct.apt_trx_centers = handles.apt_trx_centers;
    handles.aptStruct.apt_trx_orient = handles.apt_trx_orient;
  end
end
guidata(hObject,handles);
uiresume(handles.figure1);

% --- Executes on button press in cancel_pb.
function cancel_pb_Callback(hObject, eventdata, handles)
% hObject    handle to cancel_pb (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.aptStruct.featureLexicon = [];
handles.aptStruct.featureLexiconName = '';
handles.aptStruct.animalType = '';
guidata(hObject,handles);
uiresume(handles.figure1);

% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

% Hint: delete(hObject) closes the figure
delete(hObject);

function edit_trk_Callback(hObject, eventdata, handles)
% hObject    handle to edit_trk (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 edit_trk as text
%        str2double(get(hObject,'String')) returns contents of edit_trk as a double
trk_file_str = strtrim(get(hObject,'String'));
trkfiles = strsplit(trk_file_str,',');
if numel(trkfiles)~=handles.aptStruct.n_view
  uiwait(errormsg('Number of trk files should be same as number of views'));
  handles.aptStruct.trkfilename = reset_trk_edit(handles);
  guidata(hObject,handels);
  return;
end
handles.aptStruct.trkfilename = trkfiles;
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function edit_trk_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_trk (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 rb_crop.
function rb_crop_Callback(hObject, eventdata, handles)
% hObject    handle to rb_crop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of rb_crop

% --- Executes on button press in rb_frame.
function rb_frame_Callback(hObject, eventdata, handles)
% hObject    handle to rb_frame (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of rb_frame

% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over rb_centroid.
function rb_centroid_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to rb_centroid (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in rb_centroid.
function rb_centroid_Callback(hObject, eventdata, handles)
% hObject    handle to rb_centroid (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of rb_centroid
in_str = {'Centroid of landmarks to be used as center for JAABA Trx. Eg ''1 2 3''',...
  'Use direction from centroid to this landmark as orientation. Eg ''3''. For no orientation leave it emtpy'};
gg = inputdlg(in_str,'Select landmarks for JAABA Trx');

handles = guidata(hObject);
if isempty(gg)
  reset_rb(handles);
  % reset to default if user cancels.
  return;
end

bb = strsplit(strtrim(gg{1}));
centers = [];
n_pts = handles.aptStruct.n_pts;
for ndx = 1:numel(bb)
  curo = str2double(bb{ndx});
  if isnan(curo) || round(curo) - curo ~= 0 || curo < 1 || curo > n_pts
    uiwait(errordlg(sprintf('Please input only integers or integers less than %d',n_pts)));
    reset_rb(handles)
    return;
  end
  centers(end+1) = curo;
end

if isempty(strtrim(gg{2})),
  orient = 0;
else
  bb = strsplit(strtrim(gg{2}));
  if numel(bb)>1
    uiwait(errordlg('Please input only 1 integer for orientation'));
    reset_rb(handles)
    return;
  end

  curo = str2double(bb{1});
  if isnan(curo) || round(curo) - curo ~= 0 || curo < 1 || curo > handles.aptStruct.n_pts
    uiwait(errordlg(sprintf('Please input only integers for orientation or integers less than %d',n_pts)));
    reset_rb(handles)
    return;
  end
  orient = curo;
end

handles.apt_trx_centers = centers;
handles.apt_trx_orient = orient;
handles.apt_trx_type = 'trk';
tt = sprintf('%d ', centers);
cstr = sprintf('Centroid: %s',tt);
tstr = sprintf('Orientation: %d',orient);
set(handles.text_centroid,'String',{cstr,tstr});
guidata(hObject,handles);

function reset_rb(handles)
  if handles.has_crops
    set(handles.rb_crop,'Value',true);
    set(handles.rb_frame,'Value',false);
  else
    set(handles.rb_crop,'Value',false);
    set(handles.rb_frame,'Value',true);
  end
  set(handles.rb_custom,'Value',false);
  set(handles.rb_centroid,'Value',false);
  set(handles.text_centroid,'String','');

% --- Executes on button press in rb_custom.
function rb_custom_Callback(hObject, eventdata, handles)
% hObject    handle to rb_custom (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of rb_custom

% --- Executes on button press in pushbutton_help.
function pushbutton_help_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_help (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
web('https://github.com/kristinbranson/APT/wiki/Using-APT-tracking-data-in-JAABA','-browser');

function edit_social_Callback(hObject, eventdata, handles)
% hObject    handle to edit_social (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 edit_social as text
%        str2double(get(hObject,'String')) returns contents of edit_social as a double
handles = UpdateHandles(handles);
guidata(hObject,handles)

% --- Executes during object creation, after setting all properties.
function edit_social_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_social (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

author: kristinbranson

repo: JAABA


text:
function camPDSanityCheck(pds_filename,fa_filename,model_type)

if notDefined('model_type')
    model_type = 'dteig';
end

cmd = ['pdview -inputmodel ' model_type ' `analyzeheader -printprogargs ' fa_filename ' pdview` -scalarfile ' fa_filename ' < ' pds_filename];
display(cmd);
system(cmd,'-echo');

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function T2 = sltensor_multiply(T, varargin)
%SLTENSOR_MULTIPLY Multiplies a tensor and a matrix
%
% $ Syntax $
%   - T2 = sltensor_multiply(T, M, k)
%   - T2 = sltensor_multiply(T, Ms)
%   - T2 = sltensor_multiply(T, Ms, ks)
%   - T2 = sltensor_multiply(T, M1, k1, M2, k2, ...)
%
% $ Description $
%   - T2 = sltensor_multiply(T, M, k) Computes the tensor multiplication between
%   a tensor and a 2D matrix along the k-th mode.
%
%   - T2 = sltensor_multiply(T, Ms) Sequentially multiplies the tensor with
%   the elements in Ms, which is a cell array from the mode 1 to n. n is
%   the number of matrices in Ms. It should be that n == ndims(T).
%
%   - T2 = sltensor_multiply(T, Ms, ks) Sequentially multiplies the tensor
%   with the matrices in the cell array Ms along the modes specified in
%   corresponding element in ks. ks should be an array with the same size
%   as Ms.
%
%   - T2 = sltensor_multiply(T, M1, k1, M2, k2, ...) Sequentially multiplies
%   the tensor with the matrices M1, M2, ... along the modes k1, k2, ...
%
% $ History $
%   - Created by Dahua Lin on Dec 17th, 2005
%

%% parse and verify input arguments
if nargin < 2
    raise_lackinput('sltensot_multiply', 2);
end
n0 = ndims(T);
if iscell(varargin{1});
    Ms = varargin{1};
    if nargin == 2
        n = numel(Ms);
        if n ~= n0
            error('sltoolbox:invalidarg', ...
                'For the case no specifying mode indices, it should be n == ndims(T)');
        end
        ks = 1:n;
    elseif nargin == 3
        ks = varargin{2};
        if ~isequal(size(Ms), size(k))
            error('sltoolbox:argmismatch', ...
                'The size of ks does not match that of Ms');
        end
    else
        error('sltoolbox:invalidarg', ...
            'Invalid input arguments');
    end
else
    if mod(length(varargin), 2) ~= 0
        error('sltoolbox:invalidarg', ...
            'Invalid input arguments');
    end
    Ms = varargin(1:2:end);
    ks = [varargin{2:2:end}];
    if numel(Ms) ~= numel(ks)
        error('sltoolbox:invalidarg', ...
            'Invalid input arguments');
    end
end
if any(ks(:) < 1)
    error('sltoolbox:invalidarg', ...
        'mode indices should all be positive integers');
end
maxk = max(ks(:));
dims = size(T);
if maxk > n0
    dims = [dims, ones(1, maxk-n0)];
end
nmat = numel(ks);

%% compute
if nmat == 1
    T2 = multiply_tensor_matrix(T, Ms{1}, ks, dims);
else
    T2 = T;
    for i = 1 : nmat
        T2 = multiply_tensor_matrix(T2, Ms{i}, ks(i), dims);
    end
end

%% compute (by converting to matrix product)

function T2 = multiply_tensor_matrix(T, M, k, dims)

Tk = sltensor_unfold(T, k);
T2 = M * Tk;
clear Tk;
dims(k) = size(M, 1);
T2 = sltensor_fold(T2, dims, k);

author: lmthang


text:
function ok=validatenodes(t,j)
%VALIDATENODES Validate array of node numbers
%   OK=VALIDATENODES(T,J) returns true if J is a valid array of node
%   numbers or logical array for indexing into an object having a leading
%   dimension with one element per node in the array T.

%   Copyright 2006-2007 The MathWorks, Inc.
%   $Revision: 1.1.6.2 $  $Date: 2007/02/15 21:48:15 $

numnodes = numel(t.node);
if islogical(j)
    ok = (numel(j) <= numnodes);
else
    ok = ismember(j,1:numnodes);
    ok = all(ok(:));
end

author: Cloud-CV

repo: object-proposals


text:
function jst=jacprojS(j, i, rt, xyz, r0, a)
% symbolic projection function Jacobian
% code automatically generated with maple

  qr0=r0(j*4+1:(j+1)*4);

  t1 = (rt(1) ^ 2);
  t2 = (rt(2) ^ 2);
  t3 = (rt(3) ^ 2);
  t5 = sqrt((1 - t1 - t2 - t3));
  t10 = -t5 * qr0(2) - qr0(1) * rt(1) - rt(2) * qr0(4) + rt(3) * qr0(3);
  t11 = t10 ^ 2;
  t16 = t5 * qr0(1) - rt(1) * qr0(2) - rt(2) * qr0(3) - rt(3) * qr0(4);
  t17 = t16 ^ 2;
  t22 = t5 * qr0(4) + qr0(1) * rt(3) + rt(1) * qr0(3) - rt(2) * qr0(2);
  t28 = -t5 * qr0(3) - qr0(1) * rt(2) - rt(3) * qr0(2) + rt(1) * qr0(4);
  t29 = t28 ^ 2;
  t32 = t10 * t28;
  t35 = -t16 * t22;
  t36 = 0.2e1 * t32 + t16 * t22 - t35;
  t38 = -t10 * t22;
  t39 = t16 * t28;
  t42 = t38 + 0.2e1 * t39 - t10 * t22;
  t48 = t10 * xyz(1) + t28 * xyz(2) - t22 * xyz(3);
  t53 = t16 * xyz(3) - t10 * xyz(2) + t28 * xyz(1);
  t58 = t16 * xyz(1) - t28 * xyz(3) - t22 * xyz(2);
  t63 = t16 * xyz(2) + t22 * xyz(1) + t10 * xyz(3);
  t65 = -t48 * t22 + t16 * t53 + t58 * t28 - t63 * t10 + rt(6);
  t66 = 0.1e1 / t65;
  t78 = t48 * t28 + t16 * t63 + t53 * t10 + t58 * t22 + rt(5);
  t82 = t65 ^ 2;
  t83 = 0.1e1 / t82;
  t84 = (a(1) * (t48 * t10 + t16 * t58 - t63 * t22 - t53 * t28 + rt(4)) + a(2) * t78 + a(3) * t65) * t83;
  t92 = t22 ^ 2;
  t93 = t29 + t17 - t10 ^ 2 - t92;
  t95 = -t28 * t22;
  t98 = t16 * t10;
  t99 = 0.2e1 * t95 - t16 * t10 - t98;
  t111 = t95 + 0.2e1 * t98 - t28 * t22;
  t114 = t92 + t17 - t28 ^ 2 - t11;
  t127 = (a(4) * t78 + a(5) * t65) * t83;
  jst(1) = (a(1) * (t11 + t17 - t22 ^ 2 - t29) + a(2) * t36 + a(3) * t42) * t66 - t84 * t42;
  jst(2) = (a(1) * (t32 + 0.2e1 * t35 + t10 * t28) + a(2) * t93 + a(3) * t99) * t66 - t84 * t99;
  jst(3) = (a(1) * (0.2e1 * t38 - t16 * t28 - t39) + a(2) * t111 + a(3) * t114) * t66 - t84 * t114;
  jst(4) = (a(4) * t36 + a(5) * t42) * t66 - t127 * t42;
  jst(5) = (a(4) * t93 + a(5) * t99) * t66 - t127 * t99;
  jst(6) = (a(4) * t111 + a(5) * t114) * t66 - t127 * t114;

author: vrabaud


text:
function x_new = r83_jac_sl ( n, a, b, x, it_max, job )

%*****************************************************************************80
%
%% R83_JAC_SL solves a R83 system using Jacobi iteration.
%
%  Discussion:
%
%    The R83 storage format is used for a tridiagonal matrix.
%    The superdiagonal is stored in entries (1,2:N), the diagonal in
%    entries (2,1:N), and the subdiagonal in (3,1:N-1).  Thus, the
%    original matrix is "collapsed" vertically into the array.
%
%    This routine simply applies a given number of steps of the
%    iteration to an input approximate solution.  On first call, you can
%    simply pass in the zero vector as an approximate solution.  If
%    the returned value is not acceptable, you may call again, using
%    it as the starting point for additional iterations.
%
%  Example:
%
%    Here is how a R83 matrix of order 5 would be stored:
%
%       *  A12 A23 A34 A45
%      A11 A22 A33 A44 A55
%      A21 A32 A43 A54  *
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 February 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%    N must be at least 2.
%
%    Input, real A(3,N), the R83 matrix.
%
%    Input, real B(N), the right hand side of the linear system.
%
%    Input, real X(N), an approximate solution to the system.
%
%    Input, integer IT_MAX, the maximum number of iterations.
%
%    Input, integer JOB, specifies the system to solve.
%    0, solve A * x = b.
%    nonzero, solve A' * x = b.
%
%    Output, real X_NEW(N), an updated approximate solution to the system.
%

%
%  No diagonal matrix entry can be zero.
%
  for i = 1 : n
    if ( a(2,i) == 0.0E+00 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'R83_JAC_SL - Fatal error!\n' );
      fprintf ( 1, '  Zero diagonal entry, index = %d\n', i );
      return;
    end
  end

  if ( job == 0 )

    for it_num = 1 : it_max

      x_new(1) = b(1) - a(3,1) * x(2);
      for i = 2 : n - 1
        x_new(i) = b(i) - a(1,i) * x(i-1) - a(3,i) * x(i+1);
      end
      x_new(n) = b(n) - a(1,n) * x(n-1);

      x_new(1:n) = x_new(1:n) ./ a(2,1:n);

      x(1:n) = x_new(1:n);

    end

  else

    for it_num = 1 : it_max

      x_new(1) = b(1) - a(1,2) * x(2);
      for i = 2 : n - 1
        x_new(i) = b(i) - a(3,i-1) * x(i-1) - a(1,i+1) * x(i+1);
      end
      x_new(n) = b(n) - a(3,n-1) * x(n-1);

      x_new(1:n) = x_new(1:n) ./ a(2,1:n);

      x(1:n) = x_new(1:n);

    end

  end

  x_new(1:n) = x(1:n);

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [out] = baseflow_3(S,Smax)
%baseflow_3

% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter
% This file is part of the Modular Assessment of Rainfall-Runoff Models
% Toolbox (MARRMoT).
% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY
% WARRANTY. See <https://www.gnu.org/licenses/> for details.

% Flux function
% ------------------
% Description:  Empirical non-linear outflow from a reservoir
% Constraints:  None specified
% @(Inputs):    S    - current storage [mm]
%               Smax - maximum contributing storage [mm]

out = Smax^(-4)/(4)*(S^5);

end

author: wknoben

repo: MARRMoT

save_path: github-repos/MATLAB/wknoben-MARRMoT


text:
function Q = cost(V,t,tc,Run)
%
% Least-squares cost function for the IL model
%
% INPUT:
% Run = stick function
% tc = time course
% t = vector of time points
% V = parameters
%
% OUTPUT:
% Q = cost
%
% By Martin Lindquist and Tor Wager
% Edited 12/12/06
%

len = length(Run);

h1 = Get_Logit(V(1:7),t);           % Get IL model corresponding to parameters V
yhat = conv(Run, h1);               % Convolve IL model with stick function
yhat = yhat(1:len);

Q = sum((yhat-tc).^2);              % Calculate cost function

return

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
classdef MimOutputInfo
    % MimOutputInfo. A structure for holding information related to output files
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        Filenames
        Description
        DateCreated
        PluginName
    end

    methods
        function obj = MimOutputInfo(plugin_name, description, filenames, date)
            if nargin > 0
                obj.Filenames = filenames;
                obj.Description = description;
                obj.DateCreated = date;
                obj.PluginName = plugin_name;
            end
        end
    end
end

author: tomdoel

repo: pulmonarytoolkit


text:
function ADMINcopyfolderstructure(ORIGINALFOLDER, MIRRORFOLDER)
%
% ADMINcopyfolderstructure(ORIGINALFOLDER, MIRRORFOLDER)
%
% ORIGINALFOLDER
% MIRRORFOLDER  -> here goes the new folders

% create list of folders
folders = genpath(ORIGINALFOLDER);
h = [findstr(folders,  pathsep)];
h = [0 h];
Nfolders = length(h)-1
for i = 1:Nfolders
    tmp = folders(h(i)+1:h(i+1)-1);
    tmp = strrep(tmp, ORIGINALFOLDER, ''); tmp = tmp(2:end);
    Folder{i} = tmp;
end

% make new folders
for f = 1:Nfolders
    folder = fullfile(MIRRORFOLDER, Folder{f});

    if ~exist(folder, 'dir')
        mkdir(folder);
    else
        disp('folders already exist in target folder')
    end
end

author: CSAILVision

repo: LabelMeToolbox


text:
function ar=v_lpcls2ar(ls)
%V_LPCLS2AR convert line spectrum pair frequencies to ar polynomial AR=(LS)
% input vector elements should be in the range 0 to 0.5

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

[nf,p]=size(ls);
p1=p+1;
p2 = p1*2;
ar=zeros(nf,p1);
for k=1:nf
  le=exp(ls(k,:)*pi*2i);
  lf=[1 le -1 conj(fliplr(le))];
  y=real(poly(lf(1:2:p2)));
  x=real(poly(lf(2:2:p2)));
  ar(k,:)=(x(1:p1)+y(1:p1))/2;
end

author: ImperialCollegeLondon

repo: sap-voicebox


text:
% Peak of polynomial Wigner-Ville frequency estimation
%
% Estimates the instantaneous frequency of the input signal by
% extracting the peaks of the sixth order kernel polynomial
% Wigner-Ville distribution.
%
%
% Usage:
%
%     ife = pwvpe( signal, lag_window_length, time_res, interpol [, fft_length] ))
%
%
% Parameters:
%
%    signal
%
%         Input one dimensional signal to be analysed. An analytic signal
%	  is required for this function, howver, if signal is real, a
%	  default analytic transformer routine will be called from this
%	  function before computing tfd.
%
%    lag_window_length
%
%	  The size of the kernel used for analysis. window_length must be
%	  odd. The kernel used will be defined from -(lag_window_length+1)/2 to
%	  +(lag_window_length+1)/2 in both time and lag dimensions.
%
%    time_res
%
%	  The number of time samples to skip between successive slices of
%	  the analysis.
%
%    interpol
%
%	  The number of interpolating the input signal in time domain to get
%	  the proper time fractional time lags required to compute the sixth
%         order kernel.
%
%    fft_length
%
%         Zero-padding at the fft stage of the analysis may be specified by
%         giving an fft_length larger than normal. If fft_length is not
%         specified, or is smaller than the lag_window_length, then the
%         next highest power of two above lag_window_length is used. If
%         fft_length is not a power of two, the next highest power of two is
%	  used.
%
%
%
%  See Also: pwvd4, pwvd6
%
% TFSAP 7.0
% Copyright Prof. B. Boashash
% Qatar University, Doha
% email: tfsap.research@gmail.com

author: HeLiangHIT


text:
function rs = predict2(s, dim, delay, len, nnr, mode, metric_lambda)

%tstoolbox/@signal/predict2
%   Syntax:
%     * rs = predict2(s, len, nnr, step, mode)
%
%   Input arguments:
%     * len - length of prediction (number of output values)
%     * nnr - number of nearest neighbors to use (default is one)
%     * step - stepsize (in samples) (default is one)
%     * mode:
%          + 0 = Output vectors are the mean of the images of the nearest
%            neighbors
%          + 1 = Output vectors are the distance weighted mean of the
%            images of the nearest neighbors
%          + 2 = Output vectors are calculated based on the local flow
%            using the mean of the images of the neighbors
%          + 3 = Output vectors are calculated based on the local flow
%            using the weighted mean of the images of the neighbors
%
%   Local constant iterative prediction for phase space data (e.g. data
%   stemming from a time delay reconstruction of a scalar time series),
%   using fast nearest neighbor search. Four methods of computing the
%   prediction output are possible.
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt

narginchk(4,6);

if nargin < 5, nnr = 1; end
if nargin < 6, mode = 0; end
if nargin < 7, metric_lambda = 1; end

c = predict2(data(s), dim, delay, len, nnr, mode, metric_lambda); 	% do the prediction in phase space

c = c(:,1);

rs = signal(core(c), s);
a = getaxis(rs, 1);
rs = setaxis(rs, 1, a);
rs = cut(rs, 1, dlens(s,1)+1, dlens(rs, 1));
rs = addhistory(rs,  'Local constant prediction for scalar time series');
rs = addcommandlines(rs, 's = predict2(s', dim, delay, len, nnr, mode);

author: benfulcher

repo: hctsa

save_path: github-repos/MATLAB/benfulcher-hctsa


text:
function rgb = rgb_salt_and_pepper ( rgb, level )

%*****************************************************************************80
%
%% RGB_SALT_AND_PEPPER adds salt-and-pepper noise to an RGB image.
%
%  Discussion:
%
%    This function creates noise in the R, G and B channels independently.
%
%    An alternative procedure would only set all or none of the R, G and
%    B values to extremes at any pixel, resulting in black or white
%    noise pixels.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 February 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, uint8 RGB(:,:,3), the image.
%
%    Input, real LEVEL, the level of noise to add, between 0.0 (none)
%    and 1.0 (all).
%
%    Output, uint8 RGB(:,:,3), the image with added noise.  A fraction of
%    about LEVEL of the values in the RGB array have been reset to 0 or 255.
%
  [ m, n, k ] = size ( rgb );

  r = rand ( m, n, k );

  i0 = find ( r <= level / 2 );
  rgb ( i0 ) = 0;

  i255 = find ( 1 - level / 2 <= r );
  rgb ( i255 ) = 255;

  return
end


text:
function [ nfactor, factor, exponent, nleft ] = i4_factor ( n )

%*****************************************************************************80
%
%% I4_FACTOR factors an integer into prime factors.
%
%  Formula:
%
%    N = NLEFT * Product ( 1 <= I <= NFACTOR ) FACTOR(I)**EXPONENT(I).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 July 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the integer to be factored.  N may be positive,
%    negative, or 0.
%
%    Output, integer NFACTOR, the number of prime factors of N discovered
%    by the routine.
%
%    Output, integer FACTOR(NFACTOR), the prime factors of N.
%
%    Output, integer EXPONENT(NFACTOR).  EXPONENT(I) is the power of
%    the FACTOR(I) in the representation of N.
%
%    Output, integer NLEFT, the factor of N that the routine could not
%    divide out.  If NLEFT is 1, then N has been completely factored.
%    Otherwise, NLEFT represents factors of N involving large primes.
%
  nfactor = 0;

  factor = [];
  exponent = [];

  nleft = n;

  if ( n == 0 )
    return
  end

  if ( abs ( n ) == 1 )
    nfactor = 1;
    factor(1) = 1;
    exponent(1) = 1;
    return;
  end
%
%  Find out how many primes we stored.
%
  maxprime = prime ( -1 );
%
%  Try dividing the remainder by each prime.
%
  for i = 1 : maxprime

    p = prime ( i );

    if ( mod ( abs ( nleft ), p ) == 0 )

      nfactor = nfactor + 1;
      factor(nfactor) = p;
      exponent(nfactor) = 0;

      while ( 1 )

        exponent(nfactor) = exponent(nfactor) + 1;
        nleft = floor ( nleft / p );

        if ( mod ( abs ( nleft ), p ) ~= 0 )
          break;
        end

      end

      if ( abs ( nleft ) == 1 )
        break;
      end

    end

  end

  return
end


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

nsteps = 1;
Vfrac_final = 0.5;
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;

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED "AS IS."  THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.
%
% file: get_rate_diff_ci3.m
% computes confidence interval
%  - assumes x's are the number of successes in n Bernoulli trials
%  - finds confidence interval around the estimate for r1-r2
%  - with confidence level 1 - alpha
%  - finds a symmetrical two-sided interval, unless one side
%    would cross zero or one, in which case the interval is
%    offset.

% 030113 tdr created

function ci = get_rate_diff_ci3(x1,A1,x2,A2,alpha,method,verbose)
% balanced width

r1_hat = x1/A1; r2_hat = x2/A2; delta_r_hat = r1_hat - r2_hat;

tolerance = 1e-6;
max_count = 50;
count = 0;

%set limits on search for width
width_too_small = 0; width_too_big = 1e12;

%check that width_too_big is indeed too big
a = delta_r_hat - width_too_big; b = delta_r_hat + width_too_big;
lower_tail_contribution = 1- rate_diff(x1,A1,x2,A2,a);  upper_tail_contribution = rate_diff(x1,A1,x2,A2,b);
alpha_width_too_big = lower_tail_contribution + upper_tail_contribution;
if alpha_width_too_big > alpha, error('Failure to set upper bound on CI width'); end;

% set initial guess and corresponding alpha
width_guess = (width_too_big + width_too_small)/2;
a = delta_r_hat - width_guess; b = delta_r_hat + width_guess;
lower_tail_contribution = 1- rate_diff(x1,A1,x2,A2,a);  upper_tail_contribution = rate_diff(x1,A1,x2,A2,b);
alpha_guess = lower_tail_contribution + upper_tail_contribution;

% binary search
while (abs(alpha_guess - alpha) > tolerance & (count < max_count))
    if (alpha_guess < alpha)
        width_too_big = width_guess;
        width_guess = (width_too_small + width_guess)/2;
    else
        width_too_small = width_guess;
        width_guess = (width_too_big + width_guess)/2;
    end;
    count = count+1;
    a = delta_r_hat - width_guess;     b = delta_r_hat + width_guess;
    lower_tail_contribution = 1- rate_diff(x1,A1,x2,A2,a);  upper_tail_contribution = rate_diff(x1,A1,x2,A2,b);
    alpha_guess = lower_tail_contribution + upper_tail_contribution;
end;

ci = [delta_r_hat a b];

author: Sable

repo: mcbench-benchmarks


text:
function obj = SSP_OMP_method(obj)

t1 = clock;
[F_RF,F_BB] = OMP_Precoding();
[W_RF,W_BB] = OMP_Combining(F_RF,F_BB);
F = F_RF * F_BB;
W = W_RF * W_BB;

t2 = clock;
runtime = etime(t2,t1);
obj.runtime = obj.runtime + runtime;
obj.V_B = F_BB;
obj.W_B = W_BB;
obj.V_RF = F_RF;
obj.W_RF = W_RF;
obj = get_metric(obj);

author: Zzhaoxingyu

repo: hybrid-beamforming-for-three-scenes