text:
function vol = hist_vol(ticker, N)
% HIST_VOL          Calculate historical volatility
%   vol = hist_vol(ticker, N) is used to calculate the historical
%   volatility for the underlying asset specified in TICKER over N trading
%   days.  If N is not specified, a default of 20 trading days will be
%   used.
%
%   INPUTS
%       ticker --> A string or cell array of strings specifying the ticker
%                  symbols for the underlying assets to use.
%
%       N --> An integer specifying the number of days to use in the
%             volatility calculationg
%
%   OUTPUT
%       The function will return the historical volatility for each of the
%       tickers passed to the function
%
%   NOTES
%       This program uses the function 'hist_stock_data.m', which downloads
%       historical stock data to use for the volatility calculations.
%       Therefore, you must also download this function from my File
%       Exchange and place it in the same directory as this function.
%
%       The historical volatility is calculated by using the closing prices
%       of each trading day.  Additionally, one year of historical stock
%       data will be downloaded, limiting N to a maximum of roughly 252 (as
%       there are about 252 trading days in a year).  If the user wishes to
%       allow larger N, changes must be made to the code when creating the
%       variable 'start_date'.

% Created by Josiah Renfree
% July 20, 2009

% Error checking
if nargin == 0          % If no inputs provided
    error('Please provide at least one ticker symbol')
elseif nargin > 2       % If too many inputs provided
    error('Function accepts no more than 2 inputs')
elseif ~ischar(ticker) && ~iscell(ticker)   % If ticker input is wrong type
    error('Ticker input must be either a string or cell array of strings')
elseif nargin == 1      % If N not supplied, use default
    N = 20;
elseif ~isnumeric(N) || length(N) > 1  % If N is supplied, but is wrong type
    error('N must be a single integer value')
end

% If only one ticker given, convert to cell array
if ~iscell(ticker)
    ticker = {ticker};
end

% Cycle through each ticker and calculate historical volatility
vol = zeros(length(ticker), 1);
for i = 1:length(ticker)
    % Clear for loop variables for next iteration
    clear curr_date start_date data closing log_change stdev

    % Create date strings to pass to hist_stock_data function
    curr_date = datestr(now, 'ddmmyyyy');       % get current date string
    start_date = datestr(now-365, 'ddmmyyyy');  % go back 1 year

    % First step is to download historical stock data for the ticker
    data = hist_stock_data(start_date, curr_date, ticker{i});
    closing = data.Close;   % Use only closing data

    % Calculate the percentage change over the past N trading days
    log_change = log(closing(2:N+1)./closing(1:N));

    % Get standard deviation of that change
    stdev = std(log_change);

    % Now normalize to annual volatility
    vol(i) = stdev*sqrt(252);
end


text:
function P = P_given_TVN(x)
% Downloaded from the personal page of Professor Sigurd Skogestad
% http://www.nt.ntnu.no/users/skoge/diplom/prosjekt03/wold/MatLab/
A = co2_sw(x);
P = -A.g(2);

author: simulkade

repo: FVTool

save_path: github-repos/MATLAB/simulkade-FVTool


text:
%==========================================================================
% This is the testing code of a special case of SRMD (scale factor = 1) for real image <denoising & deblurring>.
% There are two models, "SRMDx1_gray.mat" for grayscale image, "SRMDx1_color.mat"
% for color image. The models can do:
%   1. Deblurring. (The kernel is assumed to be Gaussian-like!!! For other kernels, you should re-train the model!)
%      there are two types of kernels,
%      including isotropic Gaussian (width range: [0.1, 3]),
%      anisotropic Gaussian ([0.5, 8]).
%   2. Denoising. the noise level range is [0, 75].
%      For denoising only, set "kerneltype = 1; kernelwidth = 0.1." (i.e., delta kernel)
%
%==========================================================================
% The basic idea of SRMD is to learn a CNN to infer the MAP of general SISR (with special case of sf=1), i.e.,
% solve x^ = arg min_x 1/(2 sigma^2) ||kx - y||^2 + lamda \Phi(x)
% via x^ = CNN(y,k,sigma;\Theta) or x^ = CNN(y,kernel,noiselevel;\Theta).
%
% There involves two important factors, i.e., blur kernel (k; kernel) and noise
% level (sigma; nlevel).
%
% For more information, please refer to the following paper.
%    @article{zhang2017learningsrmd,
%    title={Learning a Single Convolutional Super-Resolution Network for Multiple Degradations},
%    author={Kai, Zhang and Wangmeng, Zuo and Lei, Zhang},
%    year={2017},
%    }
%
% If you have any question, please feel free to contact with <Kai Zhang (cskaizhang@gmail.com)>.
%
% This code is for research purpose only.
%
% by Kai Zhang (Nov, 2017)
%==========================================================================

% clear; clc;
format compact;

addpath('utilities');
imageSets    = {'hanzi','starsL','Audrey_Hepburn','flowersL','frog','Nami','Set5','Set14'}; % testing dataset

%%======= ======= ======= degradation parameter settings ======= ======= =======
% For real image 'starsL', some examples of degradation setting are given as follows.
% sf = 1; nlevel = 20; kerneltype = 1; kernelwidth =   0.1;  % denoising

% For real image 'Audrey_Hepburn', some examples of degradation setting are given as follows.
% sf = 1; nlevel = 10; kerneltype = 1; kernelwidth =   0.1;  % denoising

% For real image 'flowersL', some examples of degradation setting are given as follows.
% sf = 1; nlevel = 65; kerneltype = 1; kernelwidth =   0.1;  % denoising

% For real image 'frog', some examples of degradation setting are given as follows.
% sf = 1; nlevel = 15; kerneltype = 1; kernelwidth =   0.1;  % denoising

% For real image 'Nami', some examples of degradation setting are given as follows.
% sf = 1; nlevel = 10; kerneltype = 1; kernelwidth =   1;   % denoising and deblurring

%%=======  ======= ======= ======= ======= ======= ======= ======= ======= =======

%% select testing dataset, use GPU or not, ...
setTest      = imageSets([5]); %
showResult   = 1; % 1; show results; 2; save restored images
pauseTime    = 1;
useGPU       = 1; % 1 or 0, true or false
method       = 'SRMD';
folderTest   = 'testsets';
folderResult = 'results';
if ~exist(folderResult,'file')
    mkdir(folderResult);
end

%% scale factor (it is fixed to 1)

sf          = 1; %{1}

%% load model with scale factor sf
folderModel = 'models';
load(fullfile(folderModel,['SRMDx',int2str(sf),'_color.mat']));
%net.layers = net.layers(1:end-1);
net = vl_simplenn_tidy(net);
if useGPU
    net = vl_simplenn_move(net, 'gpu') ;
end

%% degradation parameter (noise level and kernel) setting
%############################# noise level ################################
% noise level, from a range of [0, 75]

nlevel     = 15;  % [0, 75]

kerneltype = 1;  % {1, 2}

%############################### kernel ###################################
% there are tree types of kernels, including isotropic Gaussian,
% anisotropic Gaussian, and estimated kernel k_b for isotropic Gaussian k_d
% under direct downsampler (x2 and x3 only).

if kerneltype == 1
    % type 1, isotropic Gaussian---although it is a special case of anisotropic Gaussian.
    kernelwidth = 0.1; % from a range of [0.1, 3]. set kernelwidth from (0.001, 0.2) to generate delta kernel (no blur)
    kernel = fspecial('gaussian',15, kernelwidth); % Note: the kernel size is fixed to 15X15.
    tag    = ['_',method,'_x',num2str(sf),'_itrG_',int2str(kernelwidth*10),'_nlevel_',int2str(nlevel)];

elseif kerneltype == 2
    % type 2, anisotropic Gaussian
    nk     = randi(size(net.meta.AtrpGaussianKernel,4)); % randomly select one
    kernel = net.meta.AtrpGaussianKernel(:,:,:,nk);
    tag    = ['_',method,'_x',num2str(sf),'_atrG_',int2str(nk),'_nlevel_',int2str(nlevel)];

end

%##########################################################################

surf(kernel) % show kernel
view(45,55);
title('Assumed kernel');
xlim([1 15]);
ylim([1 15]);
pause(2)
close;

%% for degradation maps
global degpar;
degpar = single([net.meta.P*kernel(:); nlevel(:)/255]);

for n_set = 1 : numel(setTest)

    %% search images
    setTestCur = cell2mat(setTest(n_set));
    disp('--------------------------------------------');
    disp(['    ----',setTestCur,'-----Super-Resolution-----']);
    disp('--------------------------------------------');
    folderTestCur = fullfile(folderTest,setTestCur);
    ext                 =  {'*.jpg','*.png','*.bmp'};
    filepaths           =  [];
    for i = 1 : length(ext)
        filepaths = cat(1,filepaths,dir(fullfile(folderTestCur, ext{i})));
    end

    %% prepare results
    folderResultCur = fullfile(folderResult, [setTestCur,tag]);
    if ~exist(folderResultCur,'file')
        mkdir(folderResultCur);
    end

    %% perform denoising or/and deblurring (only support Gaussian-like kernel)
    for i = 1 : length(filepaths)

        label  = imread(fullfile(folderTestCur,filepaths(i).name));
        %label  = modcrop(label, 2);
        [h,w,C]   = size(label);
        if C == 1
            label = cat(3,label,label,label);
        end

        input = label;
        [~,imageName,ext] = fileparts(filepaths(i).name);

        input = im_pad(input);
        %tic
        if useGPU
            input = gpuArray(im2single(input));
        end
        res = vl_srmd(net, input,[],[],'conserveMemory',true,'mode','test','cudnn',true);
        %res = vl_srmd_concise(net, input); % a concise version of "vl_srmd".
        %res = vl_srmd_matlab(net, input); % When use this, you should also set "useGPU = 0;" and comment "net = vl_simplenn_tidy(net);"

        output = im2uint8(gather(res(end).x));

        output = im_crop(output,h,w);
        input  = im_crop(input,h,w);
        %toc;
        %         a = 0.1;%0.15-nlevel/700;
        %         output2 = (1-a)*output + a*label; % add noise and structure back to make the output more visually plausible. or GAN?
        disp([setTestCur,'    ',int2str(i),'    ',filepaths(i).name]);

        if showResult
            imshow(cat(2,label,output));
            drawnow;
            title(['Denoising and Gaussian deblurring   ',filepaths(i).name],'FontSize',12)
            pause(pauseTime)
            imwrite(output,fullfile(folderResultCur,[imageName,'_x',int2str(sf),'.png']));% save results

        end

    end

end

author: cszn

repo: SRMD

save_path: github-repos/MATLAB/cszn-SRMD


text:
function [I_patch,I]=getI(obj,theConf,tarSize,IsFlip)
filename=[theConf.data.imgdir,obj.folder,obj.filename];
try
    I=imread(filename);
catch
    disp(filename);
    error('cannot read the above image.');
end
[h,w,d]=size(I);
if(d==1)
    I=repmat(reshape(I,[h,w,1]),[1,1,3]);
end
xmin=max(str2double(obj.bndbox.xmin),1);
xmax=min(str2double(obj.bndbox.xmax),w);
ymin=max(str2double(obj.bndbox.ymin),1);
ymax=min(str2double(obj.bndbox.ymax),h);
I_patch=I(ymin:ymax,xmin:xmax,:);
I_patch=single(I_patch); % note: 0-255 range
I_patch=imresize(I_patch,tarSize,'bilinear');
if(IsFlip)
    I_patch=I_patch(:,end:-1:1,:);
    I=I(:,end:-1:1,:);
end

repo: interpretableCNN


text:
% computes cell and neuropil fluorescence for surround model of neuropil
function [ops, stat, Fcell, FcellNeu] = extractSignalsSurroundNeuropil2(ops, stat)

Nk       = numel(stat); % all ROIs

Ny = numel(ops.yrange);
Nx = numel(ops.xrange);

stat = getNonOverlapROIs(stat, Ny, Nx);

[Ly, Lx] = size(ops.mimg);

% create cell masks and cell exclusion areas
[stat, cellPix, cellMasks] = createCellMasks(stat, Ny, Nx);

% create surround neuropil masks
[ops, neuropMasks] = createNeuropilMasks(ops, stat, cellPix);

% add surround neuropil masks to stat
for k = 1:Nk
    stat(k).ipix_neuropil = find(squeeze(neuropMasks(k,:,:))>0);
end

%%
radius0 = 2; % cells you choose
[stat, centerMasks, surroundMasks] = ...
    createCenterSurroundMasks2(ops, stat, Ny, Nx, 1, radius0);

ivcell = [stat.radius]>=radius0;
Nkv = sum(ivcell);
centerMasks = centerMasks(ivcell, :);
surroundMasks = surroundMasks(ivcell, :);
%%
% convert masks to sparse matrices for fast multiplication
neuropMasks = sparse(double(neuropMasks(:,:)));
cellMasks   = sparse(double(cellMasks(:,:)));
centerMasks = sparse(double(centerMasks(:,:)));
surroundMasks   = sparse(double(surroundMasks(:,:)));

%% get fluorescence and surround neuropil
nimgbatch = 2000;
ix = 0;
fclose all;
fid = fopen(ops.RegFile, 'r');

tic
F = NaN(Nk, sum(ops.Nframes), 'single');
Fneu = NaN(Nk, sum(ops.Nframes), 'single');
cF = NaN(Nkv, sum(ops.Nframes), 'single');
sF = NaN(Nkv, sum(ops.Nframes), 'single');

while 1
    data = fread(fid,  Ly*Lx*nimgbatch, '*int16');
    if isempty(data)
        break;
    end

    data = reshape(data, Ly, Lx, []);
    data = data(ops.yrange, ops.xrange, :);
    NT   = size(data,3);
    data = reshape(data, [], NT);
    data = double(data);

    % process the data
    %data = my_conv2(data, ops.sig, [1 2]);

    % compute cell fluorescence
    % each mask is weighted by lam (SUM TO 1)
    F(:,ix + (1:NT)) = cellMasks * data;

    % compute neuropil fluorescence
    Fneu(:,ix + (1:NT)) = neuropMasks * data;

    % compute neuropil fluorescence
    cF(:,ix + (1:NT)) = centerMasks * data;
    sF(:,ix + (1:NT)) = surroundMasks * data;

    ix = ix + NT;
    if rem(ix, 3*NT)==0
        fprintf('Frame %d done in time %2.2f \n', ix, toc)
    end
end
fclose(fid);

%% get z drift
if getOr(ops, 'getZdrift', 0)
    cFt = my_conv2(cF,.5, 2);
    sFt = my_conv2(sF,.5, 2);

    cFt = ordfilt2(cFt,1, true(1,100),[], 'symmetric');
    sFt = ordfilt2(sFt,1, true(1,100),[], 'symmetric');

    ratCS = log(max(1e-4,cFt )) - log(max(1e-4,sFt));
    ratCS = zscore(ratCS, 1, 2);

    [u, s, v] = svdecon(ratCS);

    ops.zdrift = v(:,1);

    figure(10)
    plot(v(:,1))
    hold all
end
%%
% keyboard;

% get activity stats
[stat, F, Fneu] = getActivityStats(ops, stat, F, Fneu);

%
csumNframes = [0 cumsum(ops.Nframes)];
Fcell       = cell(1, length(ops.Nframes));
FcellNeu    = cell(1, length(ops.Nframes));
for i = 1:length(ops.Nframes)
    Fcell{i}     = F(:, csumNframes(i) + (1:ops.Nframes(i)));
    FcellNeu{i}  = Fneu(:, csumNframes(i) + (1:ops.Nframes(i)));
end

author: cortex-lab


text:
function [omckk,Tckk,Rckk] = compute_extrinsic_init_fisheye(x_kk,X_kk,fc,cc,kc,alpha_c)

%compute_extrinsic
%
%[omckk,Tckk,Rckk] = compute_extrinsic_init_fisheye(x_kk,X_kk,fc,cc,kc,alpha_c)
%
%Computes the extrinsic parameters attached to a 3D structure X_kk given its projection
%on the image plane x_kk and the intrinsic camera parameters fc, cc and kc.
%Works with planar and non-planar structures.
%
%INPUT: x_kk: Feature locations on the images
%       X_kk: Corresponding grid coordinates
%       fc: Camera focal length
%       cc: Principal point coordinates
%       kc: Distortion coefficients
%       alpha_c: Skew coefficient
%
%OUTPUT: omckk: 3D rotation vector attached to the grid positions in space
%        Tckk: 3D translation vector attached to the grid positions in space
%        Rckk: 3D rotation matrices corresponding to the omc vectors
%
%Method: Computes the normalized point coordinates, then computes the 3D pose
%
%Important functions called within that program:
%
%normalize_pixel: Computes the normalize image point coordinates.
%
%pose3D: Computes the 3D pose of the structure given the normalized image projection.
%
%project_points.m: Computes the 2D image projections of a set of 3D points

if nargin < 6,
   alpha_c = 0;
	if nargin < 5,
   	kc = zeros(5,1);
   	if nargin < 4,
      	cc = zeros(2,1);
      	if nargin < 3,
         	fc = ones(2,1);
         	if nargin < 2,
            	error('Need 2D projections and 3D points (in compute_extrinsic.m)');
            	return;
         	end;
      	end;
   	end;
	end;
end;

%keyboard;

% Compute the normalized coordinates:

xn = normalize_pixel_fisheye(x_kk,fc,cc,kc,alpha_c);

Np = size(xn,2);

%% Check for planarity of the structure:
%keyboard;

X_mean = mean(X_kk')';

Y = X_kk - (X_mean*ones(1,Np));

YY = Y*Y';

[U,S,V] = svd(YY);

r = S(3,3)/S(2,2);

%keyboard;

if (r < 1e-3)|(Np < 5), %1e-3, %1e-4, %norm(X_kk(3,:)) < eps, % Test of planarity

   %fprintf(1,'Planar structure detected: r=%f\n',r);

   % Transform the plane to bring it in the Z=0 plane:

   R_transform = V';

   %norm(R_transform(1:2,3))

   if norm(R_transform(1:2,3)) < 1e-6,
      R_transform = eye(3);
   end;

   if det(R_transform) < 0, R_transform = -R_transform; end;

	T_transform = -(R_transform)*X_mean;

	X_new = R_transform*X_kk + T_transform*ones(1,Np);

   % Compute the planar homography:

   H = compute_homography(xn,X_new(1:2,:));

   % De-embed the motion parameters from the homography:

   sc = mean([norm(H(:,1));norm(H(:,2))]);

   H = H/sc;

   % Extra normalization for some reasons...
   %H(:,1) = H(:,1)/norm(H(:,1));
   %H(:,2) = H(:,2)/norm(H(:,2));

   if 0, %%% Some tests for myself... the opposite sign solution leads to negative depth!!!

       % Case#1: no opposite sign:

       omckk1 = rodrigues([H(:,1:2) cross(H(:,1),H(:,2))]);
       Rckk1 = rodrigues(omckk1);
       Tckk1 = H(:,3);

       Hs1 = [Rckk1(:,1:2) Tckk1];
       xn1 = Hs1*[X_new(1:2,:);ones(1,Np)];
       xn1 = [xn1(1,:)./xn1(3,:) ; xn1(2,:)./xn1(3,:)];
       e1 = xn1 - xn;

       % Case#2: opposite sign:

       omckk2 = rodrigues([-H(:,1:2) cross(H(:,1),H(:,2))]);
       Rckk2 = rodrigues(omckk2);
       Tckk2 = -H(:,3);

       Hs2 = [Rckk2(:,1:2) Tckk2];
       xn2 = Hs2*[X_new(1:2,:);ones(1,Np)];
       xn2 = [xn2(1,:)./xn2(3,:) ; xn2(2,:)./xn2(3,:)];
       e2 = xn2 - xn;

       if 1, %norm(e1) < norm(e2),
           omckk = omckk1;
           Tckk = Tckk1;
           Rckk = Rckk1;
       else
           omckk = omckk2;
           Tckk = Tckk2;
           Rckk = Rckk2;
       end;

   else

       u1 = H(:,1);
       u1 = u1 / norm(u1);
       u2 = H(:,2) - dot(u1,H(:,2)) * u1;
       u2 = u2 / norm(u2);
       u3 = cross(u1,u2);
       RRR = [u1 u2 u3];
       omckk = rodrigues(RRR);

       %omckk = rodrigues([H(:,1:2) cross(H(:,1),H(:,2))]);
       Rckk = rodrigues(omckk);
       Tckk = H(:,3);

   end;

   %If Xc = Rckk * X_new + Tckk, then Xc = Rckk * R_transform * X_kk + Tckk + T_transform

   Tckk = Tckk + Rckk* T_transform;
   Rckk = Rckk * R_transform;

   omckk = rodrigues(Rckk);
   Rckk = rodrigues(omckk);

else

   %fprintf(1,'Non planar structure detected: r=%f\n',r);

   % Computes an initial guess for extrinsic parameters (works for general 3d structure, not planar!!!):
   % The DLT method is applied here!!

   J = zeros(2*Np,12);

	xX = (ones(3,1)*xn(1,:)).*X_kk;
	yX = (ones(3,1)*xn(2,:)).*X_kk;

	J(1:2:end,[1 4 7]) = -X_kk';
	J(2:2:end,[2 5 8]) = X_kk';
	J(1:2:end,[3 6 9]) = xX';
	J(2:2:end,[3 6 9]) = -yX';
	J(1:2:end,12) = xn(1,:)';
	J(2:2:end,12) = -xn(2,:)';
	J(1:2:end,10) = -ones(Np,1);
	J(2:2:end,11) = ones(Np,1);

	JJ = J'*J;
	[U,S,V] = svd(JJ);

   RR = reshape(V(1:9,12),3,3);

   if det(RR) < 0,
      V(:,12) = -V(:,12);
      RR = -RR;
   end;

   [Ur,Sr,Vr] = svd(RR);

   Rckk = Ur*Vr';

   sc = norm(V(1:9,12)) / norm(Rckk(:));
   Tckk = V(10:12,12)/sc;

	omckk = rodrigues(Rckk);
   Rckk = rodrigues(omckk);

end;

repo: ekfmonoslam


text:
classdef EventAnnotation < handle
    properties
        sample;
        label;
    end

    methods
        function obj = EventAnnotation(sample,label)
            if nargin>1
                obj.sample = sample;
                obj.label = label;
            end
        end
    end
end

author: avenix

repo: WDK

save_path: github-repos/MATLAB/avenix-WDK


text:
function fsLabelName = fs_getROILabelNameFromLUT(labelIndex)
%Initialize a new vista function
%
%  fName(arguments)
%
%
% INPUTS
%        index for an ROI returned by the freesurfer LUT
%        e.g., left calcarine is 1021
%
% RETURNS
%        the name of the freesurfer roi
%        'ctx-lh-pericalcarine'
%
% Web Resources
%     mrvBrowseSVN('fs_getROILabelNameFromLUT')
%
% Example:
%   calcarineROIname = fs_getROILabelNameFromLUT(1021);
%
% Copyright Stanford team, mrVista, 2011
%
% MP, FP 2011.08.20

load fslabel.mat; % load the freesurfer lut

index = find(ismember(fslabel.num, num2str(labelIndex))==1);
if isempty(index)
    fsLabelName = '';
    warning('This index does not exit in the fslabel LUT');
else
    fsLabelName = (fslabel.name{index});
end

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function res = io_load(varargin)
% Like MATLAB's builtin load(), except that the filename may be platform-independent.
% Contents = io_load(Filename,Arguments...)
%
% In:
%   Filename    :   Platform-independent file name.
%
%   Arguments...:   optional arguments to load, e.g. the list of variables, or load options
%
% Out:
%   Contents    :   structure of contents of the file, if desired (if not specified,
%                   variables are loaded into the workspace)
%
% Example:
%   % load a file
%   io_load('data:/myfile.mat');
%
%   % load only variable 'lastmodel' from the given file
%   io_load('bcilab:/resources/workspaces/myworkspace.mat', 'lastmodel')
%
% See also:
%   load, io_save, env_translatepath
%
%                               Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                               2010-06-21

fname = varargin{1};
if length(fname)>4 && strcmpi(fname(end-3:end),'.sto')
    % load from .sto file
    if strncmp(fname,'cluster:',8)
        % load over the network
        bytes = par_fileclient(env_translatepath(fname(9:end)),'Verbosity',2);
    else
        % load from disk
        f = fopen(env_translatepath(fname),'r');
        try
            bytes = fread(f,inf,'*uint8');
            fclose(f);
        catch e
            if ~exist(fname,'file')
                error('The file named "%s" does not exist.',fname);
            else
                rethrow(e);
            end
        end
    end
    contents = hlp_deserialize(bytes);
else
    if ~isempty(varargin{1}) && varargin{1}(1) == '-' && ~any(varargin{1}=='.')
        contents = load(varargin{1},env_translatepath(varargin{2}),varargin{3:end});
    else
        contents = load(env_translatepath(varargin{1}),varargin{2:end});
    end
end

if isfield(contents,'is_serialized__')
    contents = rmfield(contents,'is_serialized__');
    for fn = fieldnames(contents)'
        contents.(fn{1}) = hlp_deserialize(contents.(fn{1})); end
end

if nargout > 0
    res = contents;
else
    for fn = fieldnames(contents)'
        assignin('caller',fn{1},contents.(fn{1})); end
end

repo: REST


text:
function region = p05_region ( )

%*****************************************************************************80
%
%% P05_REGION returns the name of the integration region for problem 05.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string REGION, the name of the integration region.
%
  region = 'box';

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [A,ua] = polyintersect(X1,Y1,X2,Y2)
% Compute area of intersection:
%
% [areaintersection, areaunion] = int_area(X1,Y1,X2,Y2)

max_res = 100;

min_x = min([X1(:); X2(:)]);
max_x = max([X1(:); X2(:)]);
min_y = min([Y1(:); Y2(:)]);
max_y = max([Y1(:); Y2(:)]);

X1 = X1-min_x;
X2 = X2-min_x;
Y1 = Y1-min_y;
Y2 = Y2-min_y;
max_x = max_x - min_x;
max_y = max_y - min_y;

max_dim = max(max_x,max_y);

X1 = X1*max_res/max_dim+1;
X2 = X2*max_res/max_dim+1;
Y1 = Y1*max_res/max_dim+1;
Y2 = Y2*max_res/max_dim+1;

max_x = ceil(max_x+1);
max_y = ceil(max_y+1);

M1 = poly2mask(X1,Y1,max_res,max_res);
M2 = poly2mask(X2,Y2,max_res,max_res);

A = sum(sum(double(M1&M2)));
ua = sum(sum(double((M1+M2)>0)));

author: CSAILVision

repo: LabelMeToolbox


text:
function varargout = CreateGPR(varargin)
% m-file for CreateGPR.fig
% CreateGPR, by itself, creates a new object or raises the existing
% singleton*.
%
% USAGE:
%
%    varargout = addmetabolites(varargin)
%
% INPUTS:
%    varargin:    various input arguments
%
% OUTPUTS:
%    varargout:   various output arguments
%
% EXAMPLE:
%
%    H = CreateGPR() %returns the handle to a new CreateGPR or the handle to the existing singleton*.
%
%    CreateGPR('CALLBACK',hObject,eventData,handles,...) %calls the local
%    %function named `CALLBACK` in CreateGPR.M with the given input arguments.
%
%    CreateGPR('Property','Value',...) %creates a new CreateGPR or raises the
%    %existing singleton*.  Starting from the left, property value pairs are
%    %applied to the GUI before `CreateGPR_OpeningFcn` gets called. An
%    %unrecognized property name or invalid value makes property application
%    %stop. All inputs are passed to `CreateGPR_OpeningFcn` via `varargin`.
%
% .. Author: - Stefan G. Thorleifsson 2011
%
% NOTE:
%    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 CreateGPR
% .. Last Modified by GUIDE v2.5 18-Aug-2010 13:19:08
%
% .. rBioNet is published under GNU GENERAL PUBLIC LICENSE 3.0+
% .. Thorleifsson, S. G., Thiele, I., rBioNet: A COBRA toolbox extension for
% .. reconstructing high-quality biochemical networks, Bioinformatics, Accepted.
% .. rbionet@systemsbiology.is

gui_Singleton = 1; % Begin initialization code - DO NOT EDIT
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @CreateGPR_OpeningFcn, ...
                   'gui_OutputFcn',  @CreateGPR_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 CreateGPR is made visible.
function CreateGPR_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 CreateGPR (see VARARGIN)
handles.data = varargin{1};
set(handles.uitable1,'data',handles.data)
if ~isempty(varargin{2}) % Previous gpr set in table2
    handles.data2 = {varargin{2}};
else
   handles.data2 = {};
end

set(handles.uitable2,'data',handles.data2);
% Choose default command line output for CreateGPR
handles.output = [];
handles.selection1 = [];
handles.selection2 = [];
% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = CreateGPR_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;
delete(gcf)

% --- Executes on button press in group_and.
function group_and_Callback(hObject, eventdata, handles)
% hObject    handle to group_and (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
line = handles.selection2;
data2 = handles.data2;

S = size(line);

genes = {};
GPR = [];
if S(1) <= 1
    msgbox('To group genes, multiple genes must be selected.',...
        'Select genes.','help')
    return
else
    lines = line(:,1);
    genes = data2(lines,1);

    for i = 1:S(1)-1
        GPR = [ GPR genes{i} ' and '];
    end
    GPR = ['(' GPR genes{end} ')'];

    cnt = 0;
    for k = 1:S(1)

        data2(lines(k)-cnt,:) = '';
        cnt = cnt + 1;

    end
    if isempty(data2)
        data2 = {GPR};
    else

        data2(end+1,:) = {GPR};
    end
end

handles.data2 = data2;

set(handles.uitable2,'data',handles.data2);

guidata(hObject,handles)

% --- Executes on button press in group_or.
function group_or_Callback(hObject, eventdata, handles)
% hObject    handle to group_or (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
line = handles.selection2;
data2 = handles.data2;

S = size(line);

genes = {};
GPR = [];
if S(1) <= 1
    msgbox('To group genes, multiple genes must be selected.',...
        'Select genes.','help')
    return
else
    lines = line(:,1);
    genes = data2(lines,1);

    for i = 1:S(1)-1
        GPR = [ GPR genes{i} ' or '];
    end
    GPR = ['(' GPR genes{end} ')'];

    cnt = 0;
    for k = 1:S(1)

        data2(lines(k)-cnt,:) = '';
        cnt = cnt + 1;

    end
    if isempty(data2)
        data2 = {GPR};
    else

        data2(end+1,:) = {GPR};
    end
end

handles.data2 = data2;

set(handles.uitable2,'data',handles.data2);

guidata(hObject,handles)

% --- Executes on button press in group_scatter.
function group_scatter_Callback(hObject, eventdata, handles)
% hObject    handle to group_scatter (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data2 = handles.data2;
line = handles.selection2;
S = size(line);
if ~(S(1) == 1) || S(1) == 0
    return
else
    GPR = data2(line(1),1);
    genes = GPR2Genes(GPR);
    data2(line(1),:) = '';
    data2 = [data2; genes'];
    handles.data2 = data2;
    set(handles.uitable2,'data',handles.data2);
end

guidata(hObject,handles)

% --- Executes on button press in group_finished.
function group_finished_Callback(hObject, eventdata, handles)
% hObject    handle to group_finished (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data2 = handles.data2;
S = size(data2);
if ~(S(1) == 1)
    msgbox('When finished only one line can remain in the Genes and GPR table'...
        ,'To many lines in table.','help');
    return
else
    handles.output = data2{1,1};
end
guidata(hObject,handles)

uiresume

% --- Executes on button press in group_addgene.
function group_addgene_Callback(hObject, eventdata, handles)
% hObject    handle to group_addgene (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
line = unique(handles.selection1(:,1));
S = size(line);

genes = handles.data(line(:,1),1);

data2 = handles.data2;
if isempty(data2)
    handles.data2 = genes;
    set(handles.uitable2,'data',handles.data2);
else
    handles.data2 = [data2; genes];
    set(handles.uitable2,'data',handles.data2);
end

guidata(hObject,handles)

% --- 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
uiresume

% --- Executes when selected cell(s) is changed in uitable1.
function uitable1_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to uitable1 (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) currently selecteds
% handles    structure with handles and user data (see GUIDATA)
handles.selection1 = eventdata.Indices;
guidata(hObject,handles)

% --- Executes when selected cell(s) is changed in uitable2.
function uitable2_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to uitable2 (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) currently selecteds
% handles    structure with handles and user data (see GUIDATA)
handles.selection2 = eventdata.Indices;
guidata(hObject,handles)

% --- Executes on button press in group_removegene.
function group_removegene_Callback(hObject, eventdata, handles)
% hObject    handle to group_removegene (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
line = handles.selection2;
if size(line) == [0,0]
    return
end
line = unique(line(:,1));
data2 = handles.data2;
S = size(line);
cnt = 0;
for i = 1:S(1)
    data2(line(i)-cnt,:) = '';
    cnt = cnt + 1;
end
handles.data2 = data2;
set(handles.uitable2,'data',handles.data2);
guidata(hObject,handles)

author: opencobra

repo: cobratoolbox


text:
function [obj, x_eig, c_eig] = rotate_to_pca(obj)
% Rotate design matrix columns within all conditions to principal component projection.

eigval_cutoff = .1; % 100*eps;  % or 1

meth = 'nuis only';

switch meth
    case 'all'

        c = obj.xX.cond_assignments;

        % add column for all nuisance covs
        c(:, end + 1) = (~any(c'))';

        % here, if startval = size(c, 2), then
        % it will do only nuisance covariates.  This is the default behavior.
        % if startval were 1, it would do ALL conditions.
        startval = 1;

    case 'nuis only'

        % this for nuisance only instead
        c = false(size(obj.xX.X, 1), 1);
        c(obj.xX.iC) = true;

        startval = size(c, 2);

end

[c_eig, x_eig] = deal(cell(1, size(c, 2)));

for j = startval:size(c, 2)
    % for each condition

    % columns for condition j
    x = obj.xX.X(:, c(:, j));

    % for determining which to save and which are empty
    x2 = scale(x);

    [v, sc, lam] = princomp(x2, 'econ');
    wh_empty = lam < eigval_cutoff;

    v = princomp(x, 'econ');

    % eliminate empty columns
    v(:, wh_empty) = [];
    x = x * v;

    % re-build c matrix
    c_eig{j} = ones(size(x, 2), 1);

    x_eig{j} = x;

end

x_eig = cat(2, x_eig{:});
c_eig = blkdiag(c_eig{:});

switch meth
    case 'all'

    case 'nuis only'
        wh_to_replace = obj.xX.iC(1:size(x_eig, 2));
        wh_to_delete = obj.xX.iC(size(x_eig, 2)+1:end);
        num_to_delete = length(wh_to_delete);

        obj.xX.X(:, wh_to_replace) = x_eig;
        obj.xX.X(:, wh_to_delete) = [];
        obj.xX.cond_assignments(wh_to_delete, :) = [];

        obj.xX.iB = obj.xX.iB - num_to_delete;
        obj.xX.iC = wh_to_replace;

end

end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function DLHGui(command,varargin)
%function DLHGui(command,varargin)
%GUI for Dose Location Histogram (DLH)
%
%APA, 7/6/09
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

global planC stateS
indexS = planC{end};

if nargin==0
    command = 'INIT';
end

switch upper(command)

    case 'INIT'

        % define margin constraints
        leftMarginWidth = 300;
        topMarginHeight = 50;
        stateS.leftMarginWidth = leftMarginWidth;
        stateS.topMarginHeight = topMarginHeight;

        str1 = ['Dose Location Histogram'];
        position = [5 40 800 600];

        defaultColor = [0.8 0.9 0.9];

        if isempty(findobj('tag','DLHFig'))
            % initialize main GUI figure
            hFig = figure('tag','DLHFig','name',str1,'numbertitle','off','position',position,...
                'CloseRequestFcn', 'DLHGui(''closeRequest'')','menubar','none','resize','off','color',defaultColor);
        else
            figure(findobj('tag','DLHFig'))
            return
        end
        %stateS.hFig = hFig;

        figureWidth = position(3); figureHeight = position(4);
        posTop = figureHeight-topMarginHeight;

        % create title handles
        handle(1) = uicontrol(hFig,'tag','titleFrame','units','pixels','Position',[150 figureHeight-topMarginHeight+5 500 40 ],'Style','frame','backgroundColor',defaultColor);
        handle(2) = uicontrol(hFig,'tag','title','units','pixels','Position',[151 figureHeight-topMarginHeight+10 498 30 ], 'String','Dose Location Histogram','Style','text', 'fontSize',10,'FontWeight','Bold','HorizontalAlignment','center','backgroundColor',defaultColor);
        handle(3) = uicontrol(hFig,'tag','titleFrame','units','pixels','Position',[leftMarginWidth-20 250 1 figureHeight-topMarginHeight-260 ],'Style','frame','backgroundColor',defaultColor);

        % create Dose and structure handles
        inputH(1) = uicontrol(hFig,'tag','doseStructTitle','units','pixels','Position',[20 posTop-40 150 20], 'String','DOSE & STRUCTURE','Style','text', 'fontSize',9.5,'FontWeight','Bold','BackgroundColor',defaultColor,'HorizontalAlignment','left');
        prefix = 'Select a dose.';
        doseList = {prefix, planC{indexS.dose}.fractionGroupID};
        prefix = 'Select a structure.';
        structList = {prefix, planC{indexS.structures}.structureName};
        inputH(2) = uicontrol(hFig,'tag','doseStatic','units','pixels','Position',[20 posTop-70 120 20], 'String','Select Dose','Style','text', 'fontSize',8,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment','right');
        inputH(3) = uicontrol(hFig,'tag','doseSelect','units','pixels','Position',[150 posTop-70 120 20], 'String',doseList,'Style','popup', 'fontSize',9,'FontWeight','normal','BackgroundColor',[1 1 1],'HorizontalAlignment','left');
        inputH(4) = uicontrol(hFig,'tag','structStatic','units','pixels','Position',[20 posTop-100 120 20], 'String','Select Structure','Style','text', 'fontSize',8,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment','right');
        inputH(5) = uicontrol(hFig,'tag','structSelect','units','pixels','Position',[150 posTop-100 120 20], 'String',structList,'Style','popup', 'fontSize',9,'FontWeight','normal','BackgroundColor',[1 1 1],'HorizontalAlignment','left');

        inputH(6) = uicontrol(hFig,'tag','criteriaTitle','units','pixels','Position',[20 posTop-140 180 20], 'String','CRITERIA','Style','text', 'fontSize',9.5,'FontWeight','Bold','BackgroundColor',defaultColor,'HorizontalAlignment','left');
        inputH(7) = uicontrol(hFig,'tag','doseStatic','units','pixels','Position',[20 posTop-170 40 20], 'String','Dose','Style','text', 'fontSize',8,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment','center');
        inputH(8) = uicontrol(hFig,'tag','doseOperator','units','pixels','Position',[70 posTop-170 40 20], 'String',{'<=','>='},'Style','popup', 'fontSize',8,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment','center');
        inputH(9) = uicontrol(hFig,'tag','doseEdit','units','pixels','Position',[120 posTop-170 40 20], 'String','','Style','edit', 'fontSize',8,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment','center');
        inputH(10) = uicontrol(hFig,'tag','doseUnitsStatic','units','pixels','Position',[160 posTop-170 80 20], 'String','Gy or cGy','Style','text', 'fontSize',8,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment','center');

        %Create Dose-Stats handles
        uicontrol(hFig,'tag','titleFrame','units','pixels','Position',[20 figureHeight-topMarginHeight-525 760 200 ],'Style','frame','backgroundColor',defaultColor);

        %Define DLH-plot fraction Axis
        plotH(1) = axes('parent',hFig,'tag','dvhAxisFract','tickdir', 'out','nextplot', 'add','units','pixels','Position',[leftMarginWidth+40 posTop*2/4-00 figureWidth-leftMarginWidth-100 posTop*0.9/2], 'color',[1 1 1],'YAxisLocation','right','fontSize',8,'visible','off');

        %Define DLH-plot Axis
        plotH(2) = axes('parent',hFig,'tag','dvhAxis','tickdir', 'out','nextplot', 'add','units','pixels','Position',[leftMarginWidth+40 posTop*2/4-00 figureWidth-leftMarginWidth-100 posTop*0.9/2], 'color',[1 1 1],'YAxisLocation','left','fontSize',8,'visible','off');

        yLim = get(plotH(1), 'yLim');
        %dvhStatH(end+1) = line([0 0], [yLim(1) yLim(2)], 'tag','motionLine','color', 'blue', 'parent', plotH(1), 'hittest', 'off','visible','off');

        submitH(1) = uicontrol(hFig,'tag','SubmitPush','units','pixels','Position',[20 posTop-225 160 25], 'String','Compute DLH','Style','push', 'fontSize',9,'FontWeight','normal','BackgroundColor',[1 1 1],'HorizontalAlignment','center','callback','DLHGui(''COMPUTE_DVH'')');
        submitH(2) = uicontrol(hFig,'tag','ClearPush','units','pixels','Position',[20 posTop-275 160 25], 'String','Clear all DLHs','Style','push', 'fontSize',9,'FontWeight','normal','BackgroundColor',[1 1 1],'HorizontalAlignment','center','callback','DLHGui(''CLEAR_ALL_DLHS'')');

        %Create handles for computed DLH

        %control to display legend in new figure
        dvhStatH(1) = uicontrol(hFig, 'tag','showLegend', 'style', 'checkbox', 'position', [700 posTop-20 100 20], 'string', 'Legend', 'horizontalAlignment', 'center','BackgroundColor',defaultColor, 'callback', 'DLHGui(''LEGENDCALL'')','visible','off');

        %Column headings
        dvhStatH(end+1) = uicontrol(hFig,'tag','sNo','units','pixels','Position',[100 posTop-350 35 20], 'String','DLH #','Style','text', 'fontSize',9,'FontWeight','bold','BackgroundColor',defaultColor,'HorizontalAlignment','center');
        dvhStatH(end+1) = uicontrol(hFig,'tag','doseSelected','units','pixels','Position',[135 posTop-350 120 20], 'String','Dose','Style','text', 'fontSize',9,'FontWeight','bold','BackgroundColor',defaultColor,'HorizontalAlignment','center');
        dvhStatH(end+1) = uicontrol(hFig,'tag','structSelected','units','pixels','Position',[270 posTop-350 120 20], 'String','Structure','Style','text', 'fontSize',9,'FontWeight','bold','BackgroundColor',defaultColor,'HorizontalAlignment','center');
        dvhStatH(end+1) = uicontrol(hFig,'tag','criteriaSelected','units','pixels','Position',[400 posTop-350 150 20], 'String','Criteria','Style','text', 'fontSize',9,'FontWeight','bold','BackgroundColor',defaultColor,'HorizontalAlignment','center');
        dvhStatH(end+1) = uicontrol(hFig,'tag','volumeSelected','units','pixels','Position',[560 posTop-350 100 20], 'String','Vol (cc)','Style','text', 'fontSize',9,'FontWeight','bold','BackgroundColor',defaultColor,'HorizontalAlignment','center');

        numDLH = 5;
        for i=1:numDLH
            rowIndex = rem(i,5);
            if rowIndex == 0
                rowIndex = 5;
            end
            dvhStatH(end+1) = uicontrol(hFig,'tag',['DeleteDLH',num2str(i)],'units','pixels','Position',[45 posTop-350-30*rowIndex 25 20], 'String','--','Style','push', 'fontSize',9,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment', 'center', 'TooltipString','Delete this DLH', 'callBack',['DLHGui(''DELETE_DVH'',',num2str(i),')']);
            dvhStatH(end+1) = uicontrol(hFig,'tag',['sNo',num2str(i)],'units','pixels','Position',[100 posTop-350-30*rowIndex 30 20], 'String',num2str(i),'Style','text', 'fontSize',9,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment','center');
            dvhStatH(end+1) = uicontrol(hFig,'tag',['doseSelected',num2str(i)],'units','pixels','Position',[135 posTop-350-30*rowIndex 120 20], 'String','Dose','Style','text', 'fontSize',9,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment','center');
            dvhStatH(end+1) = uicontrol(hFig,'tag',['structSelected',num2str(i)],'units','pixels','Position',[270 posTop-350-30*rowIndex 120 20], 'String','Structure','Style','text', 'fontSize',9,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment','center');
            dvhStatH(end+1) = uicontrol(hFig,'tag',['criteriaSelected',num2str(i)],'units','pixels','Position',[400 posTop-350-30*rowIndex 150 20], 'String','Criteria','Style','text', 'fontSize',9,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment','center');
            dvhStatH(end+1) = uicontrol(hFig,'tag',['volumeSelected',num2str(i)],'units','pixels','Position',[560 posTop-350-30*rowIndex 100 20], 'String','% Total Vol','Style','text', 'fontSize',9,'FontWeight','normal','BackgroundColor',defaultColor,'HorizontalAlignment','center');
        end

        dvhStatH(end+1) = uicontrol(hFig,'tag','DLHslider','units','pixels','Position',[760 figureHeight-topMarginHeight-525 20 200], 'Style','slider', 'BackgroundColor',defaultColor,'HorizontalAlignment','center', 'max', 5, 'min', 1, 'value', 1, 'sliderStep',[1 1], 'callback','DLHGui(''SLIDER_CLICKED'')');

        DVHInitS = struct('distV','',...
            'volsV','',...
            'binWidth','',...
            'doseNum','',...
            'structNum','',...
            'doseCutoff','',...
            'doseOperatorVal','',...
            'lineStyle','',...
            'hPlot','');

        DVHInitS(1) = [];

        ud.DVH = DVHInitS;
        ud.handle.inputH = inputH;
        ud.handle.DVHStatH = dvhStatH;
        set(ud.handle.DVHStatH,'visible','off')

        ud.currentDVHS.hLB = [];
        ud.currentDVHS.hUB = [];
        ud.currentDVHS.hObserved = [];
        ud.currentDVHS.hPatch = [];

        set(hFig,'userdata',ud);

    case 'COMPUTE_DVH'

        hFig = findobj('tag','DLHFig');
        ud = get(hFig,'userdata');

        doseNum         = get(findobj(ud.handle.inputH,'tag','doseSelect'),'value')-1;
        structNum       = get(findobj(ud.handle.inputH,'tag','structSelect'),'value')-1;
        doseCutoff      = str2num(get(findobj(ud.handle.inputH,'tag','doseEdit'),'string'));
        doseOperatorVal = get(findobj(ud.handle.inputH,'tag','doseOperator'),'value');

        if doseNum == 0
            warndlg('Please select dose.','Invalid dose','modal')
            return;
        end

        if structNum == 0
            warndlg('Please select structure.','Invalid structure','modal')
            return;
        end

        if isempty(doseCutoff)
            warndlg('Incorrect Dose cutoff. Please specify a valid number.','Invalid dose cutoff','modal')
            return;
        end

        [distV, volsV] = getDLH(doseNum, structNum, doseCutoff, doseOperatorVal, planC);

        %Compute total volume of the structure
        totalVol = sum(volsV);

        hFig = findobj('tag','DLHFig');
        ud = get(hFig,'userdata');

        numDVH = length(ud.DVH);
        ud.DVH(numDVH+1).doseNum         = doseNum;
        ud.DVH(numDVH+1).structNum       = structNum;
        ud.DVH(numDVH+1).doseCutoff      = doseCutoff;
        ud.DVH(numDVH+1).doseOperatorVal = doseOperatorVal;
        ud.DVH(numDVH+1).totalVolume     = totalVol;
        ud.DVH(numDVH+1).lineStyle       = '';
        ud.DVH(numDVH+1).hPlot           = [];
        ud.DVH(numDVH+1).distV           = distV;
        ud.DVH(numDVH+1).volsV           = volsV;

        set(hFig,'userdata',ud)

        DLHGui('PLOT_DVH',numDVH+1)

        DLHGui('REFRESH')

    case 'PLOT_DVH'

        hFig = findobj('tag','DLHFig');

        %Get Robust DVH structure to plot
        ud = get(hFig,'userdata');
        hAxis = findobj('tag','dvhAxis');
        hAxisFract = findobj('tag','dvhAxisFract');

        DVHnum = varargin{1};
        hLegend = findobj(ud.handle.DVHStatH,'tag','showLegend');
        if DVHnum == 0
            try
                delete(ud.currentDVHS.hHighlight)
                set(ud.handle.DVHStatH(3:end),'visible','off')
            end
            ud.currentDVHS.hLB = [];
            ud.currentDVHS.hUB = [];
            ud.currentDVHS.hObserved = [];
            ud.currentDVHS.hPatch = [];
            ud.currentDVHS.hMean = [];
            ud.currentDVHS.hHighlight = [];
            for i=1:length(ud.DVH)
                set(ud.DVH(i).handles,'visible','off')
            end
            set(hAxis,'visible','off')
            set(hAxisFract,'visible','off')
            set(hAxis, 'buttonDownFcn', '');
            set(hLegend,'visible','off')
            set(hFig,'userdata',ud);
            return;
        end
        set(hLegend,'visible','on')

        DVHs = ud.DVH(DVHnum);

        hSlider = findobj(ud.handle.DVHStatH,'tag','DLHslider');

        set(hSlider,'value',ceil(length(ud.DVH)/5)-ceil(DVHnum/5)+1,'min',1,'max',ceil(length(ud.DVH)/5),'sliderStep',[1/max(1,(ceil(length(ud.DVH)/5)-1)) 1/max(1,(ceil(length(ud.DVH)/5)-1))])

        %Structure color
        colorV = planC{indexS.structures}(DVHs.structNum).structureColor;

        %Delete old handles
        try, delete(DVHs.handles), end
        DVHs.handles = [];

        distV = DVHs.distV;
        volsV = DVHs.volsV;
        binWidth = 0.05; %DVHs.binWidth;

        %Plot Current DVH
        [distBinsV, volsHistV] = doseHist(distV, volsV, binWidth);
        cumVolsV  = cumsum(volsHistV);
        cumVols2V = cumVolsV(end) - cumVolsV;  %cumVolsV is the cumulative volume of the corresponding dose
        %Get lineStyle
        lineStyleC = repmat({'-','--','-.',':'},1,100);
        indPrevious = find(([ud.DVH.doseNum] == ud.DVH(DVHnum).doseNum) | ([ud.DVH.structNum] == ud.DVH(DVHnum).structNum));
        lineStyle = lineStyleC{length(indPrevious)};
        ud.DVH(DVHnum).lineStyle = lineStyle;
        %Cumulative
        %hDLH     = plot(hAxis,distBinsV, cumVols2V,'LineWidth',2,'color',colorV,'parent',hAxis,'lineStyle',lineStyle);
        %Cumulative
        hDLH     = plot(hAxis,distBinsV, cumVolsV,'LineWidth',2,'color',colorV,'parent',hAxis,'lineStyle',lineStyle);
        %Differential
        %hDLH     = plot(hAxis,distBinsV, volsHistV,'LineWidth',2,'color',colorV,'parent',hAxis,'lineStyle',lineStyle);
        ud.DVH(DVHnum).hPlot = hDLH;

        totalVol = ud.DVH(DVHnum).totalVolume;
        xDLHVals = [distBinsV];
        yDLHVals = [cumVolsV];
        [xDLHVals, aInd] = unique(xDLHVals);
        yDLHVals = yDLHVals(aInd);
        ud.currentDVHS.xDLHVals = xDLHVals;
        ud.currentDVHS.yDLHVals = yDLHVals;
        ud.currentDVHS.hDLH = hDLH;
        DVHs.handles = [DVHs.handles hDLH];

        xlabel(hAxis,'Distance from Surface (cm)')
        ylabel(hAxis,'volume (cc)')
        set(hAxis,'visible','on')
        grid(hAxis,'on')
        axis(hAxis,'tight')

        %Compute Fractions of total volume
        set(hAxisFract,'visible','on')
        yLabelsV = get(hAxis,'yTick');
        fractVolsV = linspace(min(cumVolsV(1),yLabelsV(1)),max(cumVolsV(end),yLabelsV(end)),10);
        fractVolsV = fractVolsV/totalVol*100;
        set(hAxisFract,'yLim',[fractVolsV(1) fractVolsV(end)])
        set(hAxisFract,'xTick',[]);
        ylabel(hAxisFract,'fraction of total volume')

        set(hFig,'userdata',ud)

    case 'REFRESH'

        hFig = findobj('tag','DLHFig');

        %Get Robust DVH structure to plot
        ud = get(hFig,'userdata');

        numDVH = length(ud.DVH);

        %Turn Off all DVH stats
        set(ud.handle.DVHStatH,'visible','off')

        if numDVH > 0
            hSno = findobj(ud.handle.DVHStatH,'tag','sNo');
            hDose = findobj(ud.handle.DVHStatH,'tag','doseSelected');
            hStruct = findobj(ud.handle.DVHStatH,'tag','structSelected');
            hCriteria = findobj(ud.handle.DVHStatH,'tag','criteriaSelected');
            hVolume = findobj(ud.handle.DVHStatH,'tag','volumeSelected');
            set([hSno hDose hStruct hCriteria hVolume], 'visible','on')
            hLegend = findobj(ud.handle.DVHStatH,'tag','showLegend');
            set(hLegend,'visible','on')
        end

        hSlider = findobj(ud.handle.DVHStatH,'tag','DLHslider');
        if numDVH > 5
            set(hSlider,'visible','on')
        else
            set(hSlider,'visible','off')
        end

        sliderVal = get(hSlider,'value');
        sliderMax = get(hSlider,'max');
        sliderVal = sliderMax - sliderVal + 1;
        count = 1;
        for i=(sliderVal-1)*5+1:min(sliderVal*5,numDVH)
            hDelete = findobj(ud.handle.DVHStatH,'tag',['DeleteDLH',num2str(count)]);
            hSno = findobj(ud.handle.DVHStatH,'tag',['sNo',num2str(count)]);
            hDose = findobj(ud.handle.DVHStatH,'tag',['doseSelected',num2str(count)]);
            hStruct = findobj(ud.handle.DVHStatH,'tag',['structSelected',num2str(count)]);
            hCriteria = findobj(ud.handle.DVHStatH,'tag',['criteriaSelected',num2str(count)]);
            hVolume = findobj(ud.handle.DVHStatH,'tag',['volumeSelected',num2str(count)]);
            set([hDelete hSno hDose hStruct hCriteria hVolume], 'visible','on')
            set(hDelete, 'callback', ['DLHGui(''CLEAR_DLH'',',num2str(i),')'])
            set(hSno,'string',num2str(i))
            set(hDose,'string',planC{indexS.dose}(ud.DVH(i).doseNum).fractionGroupID)
            set(hStruct,'string',planC{indexS.structures}(ud.DVH(i).structNum).structureName)
            set(hVolume,'string',num2str(ud.DVH(i).totalVolume))
            criteriaStr = 'Dose ';
            if ud.DVH(i).doseOperatorVal == 1
                criteriaStr = [criteriaStr, '<=', num2str(ud.DVH(i).doseCutoff)];
            else
                criteriaStr = [criteriaStr, '>=', num2str(ud.DVH(i).doseCutoff)];
            end
            set(hCriteria,'string',criteriaStr)
            count = count + 1;
        end

    case 'SLIDER_CLICKED'

        sliderVal = get(gcbo,'value');

        sliderVal = round(sliderVal);

        set(gcbo,'value',sliderVal)

        DLHGui('REFRESH')

    case 'CLEAR_DLH'

        dlhNum = varargin{1};

        hFig = findobj('tag','DLHFig');

        %Get Robust DVH structure to plot
        ud = get(hFig,'userdata');

        delete(ud.DVH(dlhNum).hPlot)

        ud.DVH(dlhNum) = [];

        DVHnum = min(length(ud.DVH), dlhNum);

        hSlider = findobj(ud.handle.DVHStatH,'tag','DLHslider');

        set(hSlider,'value',min(ceil(length(ud.DVH)/5),ceil(length(ud.DVH)/5)-ceil(DVHnum/5)+1),'min',min(1,ceil(length(ud.DVH)/5)),'max',ceil(length(ud.DVH)/5),'sliderStep',[1/max(1,(ceil(length(ud.DVH)/5)-1)) 1/max(1,(ceil(length(ud.DVH)/5)-1))])

        set(hFig,'userdata', ud)

        if length(ud.DVH) == 0
           DLHGui('CLEAR_ALL_DLHS')
        else
            DLHGui('REFRESH')
        end

    case 'CLEAR_ALL_DLHS'

        ButtonName = questdlg('This will delete all DLHs. Do you wish to continue?', 'Delete all DLHs?', 'Yes','No','Yes');

        if strcmpi(ButtonName,'no')
            return
        end

        hFig = findobj('tag','DLHFig');

        %Get Robust DVH structure to plot
        ud = get(hFig,'userdata');

        ud.DVH(:) = [];

        hAxis = findobj('tag','dvhAxis');
        hAxisFract = findobj('tag','dvhAxisFract');
        set(hAxis,'nextPlot','add')
        set(hAxisFract,'nextPlot','add')
        %delete([ud.DVH.handles])
        cla(hAxis)
        set(hAxis,'visible','off')
        set(hAxisFract,'visible','off')
        %DVHs.handles = [];

        set(hFig,'userdata', ud)

        DLHGui('REFRESH')

    case 'TOGGLE_VISIBILITY'
        hFig = findobj('tag','DLHFig');

        %Get Robust DVH structure to plot
        ud = get(hFig,'userdata');

        hDVH_num = findobj(ud.handle.DVHStatH,'tag','dvhSelect');
        DVHnum = get(hDVH_num,'value') - 1;

        value = get(gcbo,'value');
        DVHs = ud.DVH(DVHnum);
        if value
            set(DVHs.handles,'visible','on')
        else
            set(DVHs.handles,'visible','off')
            set(ud.currentDVHS.hHighlight,'visible','off')
        end

    case 'PLOTMOTION'
    %A DVH is selected, the plot has been clicked and motion is occuring. Update guide line/fields.
        hFig = findobj('tag','DLHFig');
        hAxis = findobj('tag','dvhAxis');
        ud = get(hFig, 'userdata');
        cP = get(hAxis, 'currentpoint');
        dose = cP(1,1);
        xLim = get(hAxis, 'xLim');
        if dose < xLim(1)
            dose = xLim(1);
        elseif dose > xLim(2)
            dose = xLim(2);
        end
        observVol = interp1(ud.currentDVHS.xObsVals, ud.currentDVHS.yObsVals, dose);
        if isnan(observVol)
            observVol = 0;
        end
        meanVol = interp1(ud.currentDVHS.xMeanVals, ud.currentDVHS.yMeanVals, dose);
        if isnan(meanVol)
            meanVol = 0;
        end
        lbVol = interp1(ud.currentDVHS.xLBVals, ud.currentDVHS.yLBVals, dose);
        if isnan(lbVol)
            lbVol = 0;
        end
        ubVol = interp1(ud.currentDVHS.xUBVals, ud.currentDVHS.yUBVals, dose);
        if isnan(ubVol)
            ubVol = 0;
        end

        hvolObser = findobj(ud.handle.DVHStatH,'tag','volAbovDoseObserTxt');
        set(hvolObser,'string',num2str(observVol))
        hvolLBD  = findobj(ud.handle.DVHStatH,'tag','volAbovDoseLBTxt');
        set(hvolLBD,'string',num2str(lbVol))
        hvolUBD  = findobj(ud.handle.DVHStatH,'tag','volAbovDoseUBTxt');
        set(hvolUBD,'string',num2str(ubVol))
        hDose = findobj(ud.handle.DVHStatH,'tag','volAbovDoseEdit');
        set(hDose,'string',num2str(dose))
        hvolMeanD  = findobj(ud.handle.DVHStatH,'tag','volAbovDoseMeanTxt');
        set(hvolMeanD,'string',num2str(meanVol))
        hMotionLine = findobj(ud.handle.DVHStatH,'tag','motionLine');
        set(hMotionLine, 'xdata', [dose dose], 'visible', 'on');

    case 'CLICKINPLOT'
    %A DVH is selected and the plot has been clicked, update guide line/fields.
        hFig = findobj('tag','DLHFig');
        hAxis = findobj('tag','dvhAxis');
        ud = get(hFig, 'userdata');
        set(hFig, 'WindowButtonUpFcn', 'DLHGui(''UNCLICKINPLOT'')');
        set(hFig, 'WindowButtonMotionFcn', 'DLHGui(''PLOTMOTION'')');
        cP = get(hAxis, 'currentpoint');
        %Interpolate Vol, display.
        dose = cP(1,1);
        xLim = get(hAxis, 'xLim');
        if dose < xLim(1)
            dose = xLim(1);
        elseif dose > xLim(2)
            dose = xLim(2);
        end
        observVol = interp1(ud.currentDVHS.xObsVals, ud.currentDVHS.yObsVals, dose);
        if isnan(observVol)
            observVol = 0;
        end
        meanVol = interp1(ud.currentDVHS.xMeanVals, ud.currentDVHS.yMeanVals, dose);
        if isnan(meanVol)
            meanVol = 0;
        end
        lbVol = interp1(ud.currentDVHS.xLBVals, ud.currentDVHS.yLBVals, dose);
        if isnan(lbVol)
            lbVol = 0;
        end
        ubVol = interp1(ud.currentDVHS.xUBVals, ud.currentDVHS.yUBVals, dose);
        if isnan(ubVol)
            ubVol = 0;
        end

        hvolObser = findobj(ud.handle.DVHStatH,'tag','volAbovDoseObserTxt');
        set(hvolObser,'string',num2str(observVol))
        hvolLBD  = findobj(ud.handle.DVHStatH,'tag','volAbovDoseLBTxt');
        set(hvolLBD,'string',num2str(lbVol))
        hvolUBD  = findobj(ud.handle.DVHStatH,'tag','volAbovDoseUBTxt');
        set(hvolUBD,'string',num2str(ubVol))
        hDose = findobj(ud.handle.DVHStatH,'tag','volAbovDoseEdit');
        set(hDose,'string',num2str(dose))
        hvolMeanD  = findobj(ud.handle.DVHStatH,'tag','volAbovDoseMeanTxt');
        set(hvolMeanD,'string',num2str(meanVol))
        hMotionLine = findobj(ud.handle.DVHStatH,'tag','motionLine');
        set(hMotionLine, 'xdata', [dose dose], 'visible', 'on');

    case 'UNCLICKINPLOT'
        hFig = findobj('tag','DLHFig');
        ud = get(hFig, 'userdata');
        set(hFig, 'WindowButtonMotionFcn', '');
        set(hFig, 'WindowButtonUpFcn', '');
        set(hFig, 'userdata', ud);

    case 'DOSEVAL'
    %A value has been entered into the doseVal field.
        hFig = get(gcbo, 'parent');
        dose = str2double(get(gcbo, 'string'));
        ud = get(hFig, 'userdata');
        hAxis = findobj('tag','dvhAxis');
        xLim = get(hAxis, 'xLim');
        if dose < xLim(1)
            dose = xLim(1);
        elseif dose > xLim(2)
            dose = xLim(2);
        end

        obserVol = interp1(ud.currentDVHS.xObsVals, ud.currentDVHS.yObsVals, dose);
        if isnan(obserVol)
            obserVol = 0;
        end
        LBVol = interp1(ud.currentDVHS.xLBVals, ud.currentDVHS.yLBVals, dose);
        if isnan(LBVol)
            LBVol = 0;
        end
        UBVol = interp1(ud.currentDVHS.xUBVals, ud.currentDVHS.yUBVals, dose);
        if isnan(UBVol)
            UBVol = 0;
        end

        hvolObser = findobj(ud.handle.DVHStatH,'tag','volAbovDoseObserTxt');
        set(hvolObser,'string',num2str(obserVol))
        hvolLBD  = findobj(ud.handle.DVHStatH,'tag','volAbovDoseLBTxt');
        set(hvolLBD,'string',num2str(LBVol))
        hvolUBD  = findobj(ud.handle.DVHStatH,'tag','volAbovDoseUBTxt');
        set(hvolUBD,'string',num2str(UBVol))
        hMotionLine = findobj(ud.handle.DVHStatH,'tag','motionLine');
        set(hMotionLine, 'xdata', [dose dose], 'visible', 'on');

    case 'LEGENDCALL'

        %executes when "Show Legend" is toggled on or off
        value = get(gcbo,'value');
        hLegend = findobj('tag','DVH_Legend');
        close(hLegend)
        if value == 0
            return;
        end
        hFig = get(gcbo, 'parent');
        ud = get(hFig, 'userdata');
        hLegend = figure('tag','DVH_Legend','name','DVH Legend','numberTitle','off','menubar','none','color','w');
        position = get(hLegend,'position');
        figColor = get(hLegend,'color');
        axisLegend = axes('units', 'normalized', 'Position', [0 0 1 1], 'color', figColor, 'ytick',[],'xtick',[], 'box', 'off', 'parent', hLegend,'nextPlot','add','units','normalized','visible','off');
        numLines = length(ud.DVH);
        dy = 0.8/numLines;
        position(3) = 400;
        position(4) = (numLines+1)*30;
        set(hLegend,'position',position)

        for i = 1:numLines
            Color = planC{indexS.structures}(ud.DVH(i).structNum).structureColor;
            line([0.05 0.15],[0.8-(i-1)*dy 0.8-(i-1)*dy],'LineStyle',ud.DVH(i).lineStyle,'LineWidth',2,'Color',Color,'parent',axisLegend)
            if ud.DVH(i).doseOperatorVal == 1
                criteriaStr = ['dose ', '<= ', num2str(ud.DVH(i).doseCutoff)];
            else
                criteriaStr = ['dose ', '>= ', num2str(ud.DVH(i).doseCutoff)];
            end
            txt = [planC{indexS.structures}(ud.DVH(i).structNum).structureName,'(',planC{indexS.dose}(ud.DVH(i).doseNum).fractionGroupID,'), ',criteriaStr];
            text(0.18,0.8-(i-1)*dy,txt)
        end
        axis(axisLegend,[0 1 0 1])

    case 'CLOSEREQUEST'

        closereq

end

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


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

% Last Modified by GUIDE v2.5 25-Aug-2010 14:04:20

% Begin initialization code - DO NOT EDIT
gui_Singleton = 0;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @playfmf_OpeningFcn, ...
                   'gui_OutputFcn',  @playfmf_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1}) && exist(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 playfmf is made visible.
function playfmf_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 playfmf (see VARARGIN)

handles.MAXSLIDERRES = 10^6;

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

handles.figpos = get(handles.figure1,'Position');

% set up path
if isempty(which('myparse')),
  if exist('../misc','file'),
    addpath('../misc');
  end
  while isempty(which('myparse')),
    miscdir = uigetdir('.','Choose "misc" folder to add to path');
    try
      addpath(miscdir);
    catch %#ok<CTCH>
    end
  end
end

% load previous values
handles.rcfilename = '.playfmfrc.mat';
handles.previous_values = struct;
if exist(handles.rcfilename,'file')
  handles.previous_values = load(handles.rcfilename);
end

if isfield(handles.previous_values,'filename'),
  handles.filename = handles.previous_values.filename;
  [handles.filedir,handles.filenamebase,handles.fileext] = ...
    fileparts(handles.previous_values.filename);
  if ~exist(handles.filename,'file'),
    handles.filename = '';
  end
else
  handles.filename = '';
end

if isfield(handles.previous_values,'CompressionSettings'),
  handles.CompressionSettings = handles.previous_values.CompressionSettings;
else
  handles.CompressionSettings = struct;
end
if ~isfield(handles.CompressionSettings,'OutputFPS'),
  handles.CompressionSettings.OutputFPS = 30;
end
if ~isfield(handles.CompressionSettings,'Compression'),
  handles.CompressionSettings.Compression = 'None';
end
if ~isfield(handles.CompressionSettings,'Quality'),
  handles.CompressionSettings.Quality = 100;
end
handles.CompressionSettings.StartFrame = 1;
handles.CompressionSettings.EndFrame = inf;

if isfield(handles.previous_values,'MaxFPS'),
  handles.MaxFPS = handles.previous_values.MaxFPS;
else
  handles.MaxFPS = 0;
  handles.MinSPF = 0;
end

% set callback for slider motion
fcn = get(handles.slider_Frame,'Callback');

if verLessThan('matlab','8.4.0')
  handles.hslider_listener = handle.listener(handles.slider_Frame,...
    'ActionEvent',fcn);
  set(handles.slider_Frame,'Callback','');
else
  handles.hslider_listener = addlistener(handles.slider_Frame,...
    'ContinuousValueChange',fcn);
  set(handles.slider_Frame,'Callback','');
end

% open video
if numel(varargin) >= 2 && exist(varargin{2},'file'),
  filename = varargin{2};
  try
    handles = open_fmf(handles,filename,varargin{3:end});
  catch
    handles = open_fmf(handles);
  end
else
  handles = open_fmf(handles);
end

% Update handles structure
guidata(hObject, handles);

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

function play(hObject)

global ISPLAYING;

handles = guidata(hObject);
set(hObject,'String','Stop','BackgroundColor',[.5,0,0]);
ISPLAYING = true;

fnext = handles.f;
while true,
  tic;
  handles = guidata(hObject);
  if ~ISPLAYING || fnext > handles.nframes,
    break;
  end
  f = fnext;
  handles.f = f;
  handles = update_frame(handles,hObject);
  drawnow;
  guidata(hObject,handles);
  if handles.MaxFPS > 0,
    elapsedtime = toc;
    if elapsedtime < handles.MinSPF,
      dt = handles.MinSPF-elapsedtime;
      pause(dt);
      fnext = f + 1;
    else,
      df = round(elapsedtime*handles.MaxFPS);
      fnext = f + df;
      if fnext > handles.nframes,
        break;
      end
    end
  else
    fnext = f+1;
    drawnow;
  end
end

stop(hObject);

function stop(hObject)

global ISPLAYING;

handles = guidata(hObject);
ISPLAYING = false;
guidata(hObject,handles);
set(hObject,'String','Play','BackgroundColor',[0,.5,0]);

% --- Outputs from this function are returned to the command line.
function varargout = playfmf_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 handles = update_frame(handles,hObject)

if nargin == 1,
  hObject = nan;
end
persistent update_frame_f;

if ~isempty(update_frame_f) && update_frame_f == handles.f,
  return;
end
update_frame_f = handles.f;
if handles.f ~= handles.lastfread,
  try
    [handles.im,handles.timestamp] = handles.readframe(handles.f);
    handles.lastfread = handles.f;
    guidata(handles.figure1,handles);
  catch ME
    warning('Failed to read frame %d: %s',handles.f,getReport(ME));
  end
%   if isa(handles.im,'uint16'),
%     handles.im = im2uint8(handles.im);
%   end
  set(handles.himage,'CData',handles.im);
end
if hObject ~= handles.edit_Frame,
  set(handles.edit_Frame,'String',num2str(handles.f));
end
if hObject ~= handles.slider_Frame,
  %set(handles.slider_Frame,'Value',(handles.f-1)/(handles.nframes-1));
  set(handles.slider_Frame,'Value',handles.f);
end
update_frame_f = [];

% --- Executes on slider movement.
function slider_Frame_Callback(hObject, eventdata, handles)
% hObject    handle to slider_Frame (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

v = get(hObject,'Value');
roundv = round(v);
if roundv == handles.f,
  if v > handles.f,
    handles.f = min(handles.nframes,handles.f+1);
  elseif v < handles.f,
    handles.f = max(1,handles.f-1);
  end
else
  handles.f = roundv;
end

handles = update_frame(handles);
guidata(hObject,handles);

% v = get(hObject,'Value');
% handles.f = round(1 + v * (handles.nframes - 1));
% handles = update_frame(handles,hObject);
% guidata(hObject,handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

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

global ISPLAYING;

if ~ISPLAYING,
  play(hObject);
else
  stop(hObject);
end

function edit_Frame_Callback(hObject, eventdata, handles)
% hObject    handle to edit_Frame (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_Frame as text
%        str2double(get(hObject,'String')) returns contents of edit_Frame as a double
f = str2double(get(hObject,'String'));
if isnan(f),
  set(hObject,'String',num2str(handles.f));
  return;
end
handles.f = max(1,min(f,handles.nframes));
handles = update_frame(handles,hObject);
guidata(hObject,handles);

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

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

handles = open_fmf(handles);
guidata(hObject,handles);

function handles = open_fmf(handles,filename,varargin)

global ISPLAYING;

if ~isempty(ISPLAYING) && ISPLAYING,
  stop(handles.figure1);
  handles = guidata(handles.figure1);
end

handles.filterspec = {  '*.ufmf','MicroFlyMovieFormat (*.ufmf)'; ...
  '*.fmf','FlyMovieFormat (*.fmf)'; ...
  '*.sbfmf','StaticBackgroundFMF (*.sbfmf)'; ...
  '*.avi','AVI (*.avi)'
  '*.mp4','MP4 (*.mp4)'
  '*.mov','MOV (*.mov)'
  '*.mmf','MMF (*.mmf)'
  '*.mjpg','MJPG (*.mjpg)'
  '*.*','*.*'};

if isfield(handles,'fileext'),
  % default ext is last chosen
  i = find(strcmpi(['*',handles.fileext],handles.filterspec(:,1)),1);
  n = size(handles.filterspec,1);
  if ~isempty(i),
    handles.filterspec = handles.filterspec([i,1:i-1,i+1:n],:);
  end
end

if nargin < 2,
[filename, pathname] = uigetfile(handles.filterspec, 'Choose FMF video to play',handles.filename);
if ~ischar(filename),
  return;
end
else
  pathname = '';
end
handles.filename = fullfile(pathname,filename);
[handles.filedir,handles.filenamebase,handles.fileext] = fileparts(handles.filename);
if strcmp(handles.fileext,'.mjpg'),

  res = questdlg('Is this an indexed MJPG file? If so, you will be prompted to select the corresponding index file location.');
  if strcmpi(res,'Yes'),

    defaultindexfile = fullfile(handles.filedir,'index.txt');
    if ~exist(defaultindexfile,'file'),
      defaultindexfile = handles.filedir;
    end
    [indexfilename,indexpath] = uigetfile('*.txt','Choose MJPG index file',defaultindexfile);
    if ~ischar(indexfilename),
      return;
    end
    handles.indexfilename = fullfile(indexpath,indexfilename);
    varargin = [varargin,{'indexfilename',handles.indexfilename}];
  end

end

if isfield(handles,'fid') && ~isempty(fopen(handles.fid)) && handles.fid > 1,
  fclose(handles.fid);
end
if isfield(handles,'himage') && ishandle(handles.himage),
  delete(handles.himage);
end

try
  [handles.readframe,handles.nframes,handles.fid,handles.headerinfo] = ...
    get_readframe_fcn(handles.filename,varargin{:});
catch ME
  s = sprintf('Could not read video %s.',filename);
  uiwait(errordlg(s,'Error opening video'));
  rethrow(ME);
end

% set slider steps
% this seems to be the limit to slider step resolution
handles.stepsize = ceil(handles.nframes/handles.MAXSLIDERRES);
step1 = handles.stepsize/(handles.nframes-1);
sliderstep = [step1,min(1,100*step1)];
set(handles.slider_Frame,'Value',0,'SliderStep',sliderstep,'Min',1,'Max',handles.nframes);

% % set slider steps
% sliderstep = [1/(handles.nframes-1),min(1,100/(handles.nframes-1))];
% set(handles.slider_Frame,'Value',0,'SliderStep',sliderstep);

% show first image
handles.f = 1;
[handles.im,handles.timestamp] = handles.readframe(handles.f);
handles.minv = 0;
if isa(handles.im,'uint8'),
  handles.maxv = 255;
elseif isa(handles.im,'uint16'),
  handles.maxv = 2^16-1;
elseif isa(handles.im,'double'),
  if max(handles.im(:)) > 1,
    handles.maxv = 255;
  else
    handles.maxv = 1;
  end
end

handles.lastfread = handles.f;
if size(handles.im,3) == 1,
  handles.himage = imagesc(handles.im,'Parent',handles.axes_Video,[handles.minv,handles.maxv]);
else
  handles.himage = image(im2uint8(handles.im),'Parent',handles.axes_Video);
end
colormap(handles.axes_Video,'gray');
axis(handles.axes_Video,'image','off');
handles = update_frame(handles);

ISPLAYING = false;

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

% --- 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

if isfield(handles,'fid') && ~isempty(fopen(handles.fid)) && handles.fid > 1,
  fclose(handles.fid);
end

savefns = {'filename','CompressionSettings'};
save(handles.rcfilename,'-struct','handles',savefns{:});
delete(hObject);

% --- Executes when figure1 is resized.
function figure1_ResizeFcn(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)

if ~isfield(handles,'figpos'),
  return;
end

sliderpos = get(handles.slider_Frame,'Position');
editpos = get(handles.edit_Frame,'Position');
pushbuttonpos = get(handles.pushbutton_PlayStop,'Position');
axespos = get(handles.axes_Video,'Position');
newfigpos = get(handles.figure1,'Position');

woff = newfigpos(3) - handles.figpos(3);
hoff = newfigpos(4) - handles.figpos(4);

sliderpos(3) = sliderpos(3) + woff;
editpos(1) = editpos(1) + woff;
pushbuttonpos(1) = pushbuttonpos(1) + woff;

axespos(3) = axespos(3) + woff;
axespos(4) = axespos(4) + hoff;

set(handles.slider_Frame,'Position',sliderpos);
set(handles.edit_Frame,'Position',editpos);
set(handles.pushbutton_PlayStop,'Position',pushbuttonpos);
set(handles.axes_Video,'Position',axespos);

handles.figpos = newfigpos;
guidata(hObject,handles);

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

prompts = {};
defAns = {};
prompts{end+1} = 'Max FPS: ';
defAns{end+1} = num2str(handles.MaxFPS);
prompts{end+1} = 'Min intensity: ';
defAns{end+1} = num2str(handles.minv);
prompts{end+1} = 'Max intensity: ';
defAns{end+1} = num2str(handles.maxv);
while true,
  answer = inputdlg(prompts,'playfmf Preferences',1,defAns,'on');
  msgs = {};
  if isempty(answer),
    return;
  end
  v = str2double(answer{1});
  iserror = false;
  if isnan(v),
    iserror = true;
    msgs{end+1} = 'Max FPS must be a number';
  elseif v < 0,
    iserror = true;
    msgs{end+1} = 'Max FPS must be >= 0';
  else
    defAns{1} = num2str(v);
    handles.MaxFPS = v;
    handles.MinSPF = 1 / handles.MaxFPS;
  end

  minv = str2double(answer{2});
  if isnan(minv),
    iserror = true;
    msgs{end+1} = 'Min intensity must be a number';
  elseif v < 0,
    iserror = true;
    msgs{end+1} = 'Min intensity must be >= 0';
  end

  maxv = str2double(answer{3});
  if isnan(maxv),
    iserror = true;
    msgs{end+1} = 'Max intensity must be a number';
  elseif maxv < 0,
    iserror = true;
    msgs{end+1} = 'Max intensity must be >= 0';
  end

  if ~iserror,
    if minv > maxv,
      iserror = true;
      msgs{end+1} = 'Max intensity must be > min intensity';
    else
      defAns{2} = num2str(minv);
      defAns{3} = num2str(maxv);
      handles.minv = minv;
      handles.maxv = maxv;
    end
  end

  if iserror,
    uiwait(warndlg('Illegal values entered. Max FPS, min and max intensity must be numbers','Bad Preferences'));
  else
    break;
  end
end

set(handles.axes_Video,'CLim',[handles.minv,handles.maxv]);

guidata(hObject,handles);

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

s = {};
s{end+1} = 'PlayFMF';
s{end+1} = '';
s{end+1} = 'Kristin Branson';
s{end+1} = 'bransonk@janelia.hhmi.org';
s{end+1} = '';
s{end+1} = 'This is a GUI for playing FMF, SBFMF, UFMF, and AVI videos. The maximum frame rate can be set through the "Preferences..." menu. Set to <= 0 for no maximum frame rate. Control the frame shown with the slider or editable text box. The Play/Stop button does what you think it does.';
msgbox(s,'About PlayFMF','help','Replace');

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

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

CompressionSettings = SaveFMFSettings(handles.CompressionSettings);
fns = fieldnames(CompressionSettings);
for i = 1:length(fns),
  fn = fns{i};
  handles.CompressionSettings.(fn) = CompressionSettings.(fn);
end
guidata(hObject,handles);

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

if handles.CompressionSettings.StartFrame > handles.nframes,
  uiwait(errordlg(sprintf('StartFrame set to %d > NFrames = %d. Please fix Compression Settings',...
    handles.CompressionSettings.StartFrame,handles.nframes)));
  return;
end

[pathstr,filestr,ext] = fileparts(handles.filename);
handles.aviname = fullfile(pathstr,[filestr,'.avi']);

[filename,pathname] = uiputfile('*.avi','Save to AVI file',handles.aviname);
if ~ischar(filename),
  return;
end
handles.aviname = fullfile(pathname,filename);

ncolors = size(handles.im,3);
isindexed = ismember(handles.CompressionSettings.Compression,{'MSVC','RLE'}) || ...
  (strcmp(handles.CompressionSettings.Compression,'None') && ...
  ncolors == 1);
if isindexed,
  if ncolors == 1,
    cmap = repmat(linspace(0,1,256)',[1,3]);
  else
    [tmp,cmap] = rgb2ind(handles.im,256,'nodither');
  end
end

params = {'compression',handles.CompressionSettings.Compression,...
  'fps',handles.CompressionSettings.OutputFPS};

if isindexed,
  params(end+1:end+2) = {'colormap',cmap};
end
if ~strcmp(handles.CompressionSettings.Compression,'None'),
  params(end+1:end+2) = {'quality',handles.CompressionSettings.Quality};
end
handles.aviobj = avifile(handles.aviname,params{:});

endframe = min(handles.nframes,handles.CompressionSettings.EndFrame);
nframescompress = endframe - handles.CompressionSettings.StartFrame + 1;

i = 0;
s = sprintf('Compressing frame %d / %d',i,nframescompress);
hwaitbar = waitbar(0,s,'CreateCancelBtn',...
  'setappdata(gcbf,''canceling'',1)');
setappdata(hwaitbar,'canceling',0);
for t = handles.CompressionSettings.StartFrame:endframe,
  if getappdata(hwaitbar,'canceling')
    break
  end
  im = uint8(handles.readframe(t));
  if isindexed,
    if ncolors == 1,
      handles.aviobj = addframe(handles.aviobj,im);
    else
      handles.aviobj = addframe(handles.aviobj,rgb2ind(im,cmap,'nodither'));
    end
  else
    if ncolors == 1,
      handles.aviobj = addframe(handles.aviobj,repmat(im,[1,1,3]));
    else
      handles.aviobj = addframe(handles.aviobj,im);
    end
  end
  i = i + 1;
  if mod(i,50) == 0,
    s = sprintf('Compressing frame %d / %d',i,nframescompress);
    waitbar(i/nframescompress,hwaitbar,s);
  end
end
handles.aviobj = close(handles.aviobj);
if ishandle(hwaitbar),
  delete(hwaitbar);
end
msgbox(sprintf('Successfully compressed %d / %d of frames in the interval [%d,%d].',i,nframescompress,handles.CompressionSettings.StartFrame,endframe),'Compression Complete','modal');

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

author: kristinbranson

repo: JAABA


text:
% Some example for running the sinusoidal and harmonic estimators
%
% Please find the path management in the startup.m script in the root directory
% of this repository. Note that by starting matlab in the root directory, this
% script should automatically run. If it is not the case, you can also move to the
% root directory and run this script manually.
%
% Copyright (c) 2012 University of Crete - Computer Science Department
%
% License
%  This file is under the LGPL license,  you can
%  redistribute it and/or modify it under the terms of the GNU Lesser General
%  Public License as published by the Free Software Foundation, either version 3
%  of the License, or (at your option) any later version. This file 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 Lesser General Public License for more
%  details.
%
% This function is part of the Covarep project: http://covarep.github.io/covarep
%
% Author
%  Gilles Degottex <degottex@csd.uoc.gr>
%

clear all;

% Load the waveform
fname = '0011.arctic_bdl1';
[wav, fs] = audioread([fname '.wav']);
times = (0:length(wav)-1)'/fs;

% Load a rough f0 curve
% Can be replaced by any f0 estimate which is robust to octave jumps
f0s = load([fname '.f0.txt']);

disp(['Compute: Sinusoidal Model (SM) using Peak Picking']);
opt = sin_analysis();
opt.fharmonic  = false;
opt.use_ls     = false;
opt.resyn      = true; % Use the internal OLA method for the resynthesis
[frames syn_sm] = sin_analysis(wav, fs, f0s, opt);
audiowrite([fname '.sm.wav'], syn_sm, fs);

disp(['Compute: Harmonic Model (HM)']);
opt = sin_analysis();
opt.fharmonic  = true;
opt.fadapted   = false;
opt.use_ls     = true;
frames = sin_analysis(wav, fs, f0s, opt);
syn_hm = hm_synthesis4(frames, length(wav), fs); % Use the harmonic resynthesis
audiowrite([fname '.hm.wav'], syn_hm, fs);

disp(['Compute: Adaptive Harmonic Model (aHM) using the Adaptive Iterative Refinment (AIR)']);
optair = ahm_air_analysis2();
optair.do_final_ahm_step = false;
[f0sair, frames] = ahm_air_analysis2(wav, fs, f0s, optair);

disp('Compute the last step with uniform analysis instants');
f0sair = interp1td(f0sair, f0s(:,1));
opt = sin_analysis();
opt.fharmonic  = true;
opt.fadapted   = true;
opt.use_ls     = true;
frames = sin_analysis(wav, fs, f0sair, opt);
syn_ahm = hm_synthesis4(frames, length(wav), fs); % Use the harmonic resynthesis
audiowrite([fname '.ahm-air.wav'], syn_ahm, fs);
%  save([fname '.ahm_frames.mat'], 'frames');

figure
fig(1) = subplot(211);
    plot(times, wav, 'k');
    hold on;
    plot(times, syn_sm, 'g');
    plot(times, syn_hm, 'b');
    plot(times, syn_ahm, 'r');
    xlabel('Time [s]');
    legend({'Waveform', 'Sinusoidal Model (SM)', 'Harmonic Model (HM)', 'Adaptive Harmonic Model (aHM)'});
fig(2) = subplot(212);
    plot(f0s(:,1), log2(f0s(:,2)), '--k');
    hold on;
    plot(f0sair(:,1), log2 (f0sair(:,2)), 'r');
    xlabel('Time [s]');
    legend({'Input f_0 [log_2 Hz]', 'AIR refined f_0 [log_2 Hz]'});
linkaxes(fig, 'x');

author: covarep

repo: covarep

save_path: github-repos/MATLAB/covarep-covarep


text:
% Author:
% - Mehrtash Harandi (mehrtash.harandi at gmail dot com)
%
% This file is provided without any warranty of
% fitness for any purpose. You can redistribute
% this file and/or modify it under the terms of
% the GNU General Public License (GPL) as published
% by the Free Software Foundation, either version 3
% of the License or (at your option) any later version.

function outStein = Compute_Stein_Metric(Set1,Set2)

simFlag = false;
if (nargin < 2)
    Set2 = Set1;
    simFlag = true;
end

l1 = size(Set1,3);
l2 = size(Set2,3);
outStein = zeros(l2,l1);

if (simFlag)
    for tmpC1 = 1:l1
        X = Set1(:,:,tmpC1);
        for tmpC2 = tmpC1+1:l2
            Y = Set2(:,:,tmpC2);
            outStein(tmpC2,tmpC1) = log(det(0.5*(X+Y))) -  0.5*(log(det(X*Y)));
            if  (outStein(tmpC2,tmpC1) < 1e-10)
                outStein(tmpC2,tmpC1) = 0.0;
            end
            outStein(tmpC1,tmpC2) = outStein(tmpC2,tmpC1);
        end
    end

else
    for tmpC1 = 1:l1
        X = Set1(:,:,tmpC1);
        for tmpC2 = 1:l2
            Y = Set2(:,:,tmpC2);
            outStein(tmpC2,tmpC1) = log(det(0.5*(X+Y))) -  0.5*(log(det(X*Y)));
            if  (outStein(tmpC2,tmpC1) < 1e-10)
                outStein(tmpC2,tmpC1) = 0.0;
            end
        end
    end
end

end

author: hiroyuki-kasai

repo: ClassifierToolbox


text:
function Y = sin(X)
    % Symbolic sine function.

    % Convert inputs to SymExpression
    % X = SymExpression(X);

    % construct the operation string
    sstr = ['Sin[' X.s ']'];

    % create a new object with the evaluated string
    Y = SymExpression(sstr);
end

author: ayonga

repo: frost-dev

save_path: github-repos/MATLAB/ayonga-frost-dev