text:
% add the path of RBM code
addpath('..');

% load MNIST
load 'mnist_14x14.mat';

% shuffle the training data
perm_idx = randperm (size(X,1));
X = X(perm_idx, :);
X_labels = X_labels(perm_idx);

layers = [size(X, 2) 500 500 1000];
n_layers = length(layers);

Rs = cell(n_layers, 1);

% construct RBM and use default configurations
H = X;

for l=1:n_layers-1
    R = default_rbm (size(H, 2), layers(l+1));

    R.data.binary = 1;

    mH = mean(H, 1)';
    R.vbias = min(max(log(mH./(1 - mH)), -4), 4);
    %R.hbias = -4 * ones(size(R.hbias));

    R.learning.lrate = 1e-3;

    R.learning.persistent_cd = 0;
    R.parallel_tempering.use = 0;
    R.adaptive_lrate.use = 1;
    R.adaptive_lrate.lrate_ub = R.learning.lrate;
    R.enhanced_grad.use = 1;
    R.learning.minibatch_sz = 256;

    % max. 100 epochs
    R.iteration.n_epochs = 200;

    % set the stopping criterion
    R.stop.criterion = 0;
    R.stop.recon_error.tolerate_count = 1000;

    % save the intermediate data after every epoch
    R.hook.per_epoch = {@save_intermediate, {sprintf('rbm_%d.mat', l)}};
    R.hook.per_update = {};

    % print learining process
    R.verbose = 0;
    R.debug.do_display = 0;
    R.debug.display_interval = 10;
    R.debug.display_fid = 1;
    R.debug.display_function = @visualize_rbm;

    % train RBM
    fprintf(1, 'Training RBM\n');
    tic;
    R = train_rbm (R, H);
    fprintf(1, 'Training is done after %f seconds\n', toc);

    Rs{l} = R;

    H = rbm_get_hidden(H, R);
end

D = default_dbn (layers);

D.hook.per_epoch = {@save_intermediate, {'dbn_mnist.mat'}};

D.learning.lrate = 1e-3;
D.learning.lrate0 = 5000;
D.learning.momentum = 0;
D.learning.weight_decay = 0.0001;
D.learning.minibatch_sz = 256;

D.learning.contrastive_step = 10;
D.learning.persistent_cd = 0;
D.learning.ffactored = 1;

D.iteration.n_epochs = 200;

for l = 1:n_layers-2
    if l > 1
        D.gen.biases{l} = (D.gen.biases{l} + Rs{l}.vbias)/2;
    else
        D.gen.biases{l} = Rs{l}.vbias;
    end
    D.gen.biases{l+1} = Rs{l}.hbias;
    D.gen.W{l} = Rs{l}.W;

    if l > 1
        D.rec.biases{l} = (D.rec.biases{l} + Rs{l}.vbias)/2;
    else
        D.rec.biases{l} = Rs{l}.vbias;
    end
    D.rec.biases{l+1} = Rs{l}.hbias;
    D.rec.W{l} = Rs{l}.W;
end

D.top.W = Rs{n_layers-1}.W;
D.top.vbias = Rs{n_layers-1}.vbias;
D.top.hbias = Rs{n_layers-1}.hbias;

fprintf(1, 'Training DBN\n');
tic;
D = dbn (D, X);
fprintf(1, 'Training is done after %f seconds\n', toc);

n_chains = 20;
n_samples = 11;
rndidx = randperm(size(X, 1));
Sall = zeros(n_samples * n_chains, size(X, 2));
for ci = 1:n_chains
    %S = dbn_sample(rand(1, size(X, 2)), D, n_samples, 1);
    S = dbn_sample(X(rndidx(ci),:), D, n_samples-1, 1);
    Sall(((ci-1) * n_samples + 1), :) = X(rndidx(ci),:);
    Sall(((ci-1) * n_samples + 2):(ci * n_samples), :) = S;
end
save 'dbn_samples.mat' Sall;

author: kyunghyuncho

repo: deepmat


text:
function [lyrics info] = get_lyrics_as_bytes(file_name)
% Returns the lyrics in midi file
%
%   [lyrics info] = get_lyrics(file_name)
%
% INPUTS:
%   file_name - the name of the midi file
%
% OUPUTS:
%   lyrics - an Nx1 cell array where each cell contains the ascii
%     bytes from a particular lyric command.  Some of these may be
%     unprintable characters such as carriage return (0xd).
%   info - an Nx3 matrix.  Each row of the matrix contains additional
%     information about each cell element of lyrics.  The columns are:
%       1 - time in beats of the command
%       2 - time in seconds of the command
%       3 - track number of the command
%
% 2010-05-03 Christine Smit csmit@ee.columbia.edu

import edu.columbia.ee.csmit.MidiKaraoke.read.*;
import java.io.File;
import javax.sound.midi.*;

midiFile = File(file_name);
seq = MidiSystem.getSequence(midiFile);

% first parse the file
lyricsInMidi = LyricsViewParser.parse(seq);
% now get out the individual lyrics
lyricInTrack = lyricsInMidi.getLyrics();
N = length(lyricInTrack);
lyrics = cell(1,N);
info = zeros(N,3);

% and compile the information
for i=1:N
    lyrics{i} = lyricInTrack(i).getTextBytes();
    info(i,1) = lyricInTrack(i).getTicks();
    info(i,2) = lyricInTrack(i).getSeconds();
    info(i,3) = lyricInTrack(i).getTrackNumber();
end

% get the number of ticks/quarter note, which I assume is the
% 'beat' in the nm
ticksPerQuarterNote = seq.getResolution();

% convert the first column on info from ticks to beats
info(:,1) = info(:,1)./ticksPerQuarterNote;

% add 1 to the track numbers
info(:,3) = info(:,3) +1;

end

author: Sable

repo: mcbench-benchmarks


text:
function dif = angleAbsDiff(angle1, angle2)
%ANGLEABSDIFF Absolute difference between two angles.
%
%   AD = angleAbsDiff(ANGLE1, ANGLE2)
%   Computes the absolute angular difference between two angles in radians.
%   The result is comprised between 0 and PI.
%
%   Example
%     A = angleAbsDiff(pi/2, pi/3)
%     A =
%         0.5236   % equal to pi/6
%
%   See also
%   angles2d, angleDiff

% ------
% Author: David Legland
% E-mail: david.legland@grignon.inra.fr
% Created: 2011-07-27, using Matlab 7.9.0.529 (R2009b)
% Copyright 2011-2022 INRA - Cepia Software Platform

% first, normalization
angle1 = normalizeAngle(angle1);
angle2 = normalizeAngle(angle2);

% compute difference and normalize
dif = normalizeAngle(angle1 - angle2);
dif = min(dif, 2*pi - dif);

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function varargout = ApertureTool(varargin)
%ApertureTool Interactive Image Aperture Viewer
%
% Interactive aperture tool.  Allows user to interactivly select the
% portion of the aperture that contributes to the image.
%
% INPUTS:
%   filename   - optional : complex image filename
%   aoi        - optional : image AOI (filename must be specified)
%   segment    - optional : image number of multi-image file (filename must be specified)
%
% OUTPUTS:
%   GUI display, Movie and images as specified
%
% VERSION:
%   1.0
%     - Tim Cox 20100324
%     - Based on previous ApertureTool written by Tim Cox.
%       Initial concept based on tool written by Matt Banta, code lost to
%       antiquity
%   1.1
%     - Tim Cox 20110401
%     - Redesigned GUI.  Added resolution mode tab and functionaity.
%   1.2
%     - Wade Schwartzkopf 20121116
%     - Metadata-driven data normalization and general code cleanup
%   1.3
%     - Pat Cutler 20140124
%     - Added compatibility with polarized data
%     - Added image representation dropdown
%     - Added PHD axes labels
%   2.0
%     - Tim Cox 20200909
%     - Got rid of old TabControl, uses new tab trick
%     - Redesigned tabs to move more common controls to first tab and
%       consolidated.  Moved some controls to menu items.
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

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

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

% Update handles structure
guidata(hObject, handles);

handles.MaxLoadSize = 3000;

% Setup image and PHD axes
remap_list = getremaplist();
default_remap = find(strcmpi(remap_list,'densityremap'),1,'first');
set(handles.RemapCombo,'String',remap_list);
set(handles.RemapCombo,'Value',default_remap);
set(handles.ImageContrast,'Visible','off');
image_rep_list = {'amplitude' 'Pauli' 'AlphaEntropy' 'Stokes'};
set(handles.image_rep_combo,'String',image_rep_list);
set(handles.image_rep_combo,'Value',1);
set(handles.image_rep_combo,'Visible','off');
old_img_position = getpixelposition(handles.image);
handles.imghandle = imshow(0, 'Parent', handles.image);
handles.hSP1 = imscrollpanel(handles.figure1,handles.imghandle);
setpixelposition(handles.hSP1,old_img_position);
handles.apiSP1 = iptgetapi(handles.hSP1);
set(handles.phd,'Visible','off');
set(handles.PHDPolCombo,'Visible','off');

%metaicon
set(handles.metaicon,'XTick',[]);
set(handles.metaicon,'YTick',[]);
set(handles.metaicon,'Box','on');

%animation tab
set(handles.Slow,'Value',1);
set(handles.NumFrames,'String',7);
set(handles.ApFraction,'String',0.25);
set(handles.FrameRate,'String',5);
set(handles.CycleCheck,'Value',1);
set([handles.First,handles.Prev,...
    handles.Play,handles.Pause,...
    handles.Next,handles.Last],'enable','off');

%processing tab
set(handles.nx,'Enable','off');
set(handles.ny,'Enable','off');
set(handles.AlwaysApply,'Value',1);
set(handles.AlwaysApply,'Visible','off');

%set image/movie controls
set(handles.MovieFrameRate,'String',5);
set(handles.AnnotationCheck,'Value',1);
set(handles.StopRecording,'Enable','off');
set(handles.Recording,'Enable','off');
set(handles.SaveImage,'Enable','off');
set(handles.CurRecFrame,'Enable','off');
set(handles.TotRecFrame,'Enable','off');
set(handles.MovieFrameRate,'String',5);

%set up tab control
%handles.tgroup = uitabgroup('Parent', handles.figure1,'Position', [.023 .025 .497 .271]);
handles.tgroup = uitabgroup('Parent', handles.figure1,'Position', [.023 .01 .51 .32]);
handles.tab1 = uitab('Parent', handles.tgroup, 'Title', 'Animation');
handles.tab2 = uitab('Parent', handles.tgroup, 'Title', 'Processing');
handles.tab3 = uitab('Parent', handles.tgroup, 'Title', 'Save Image/Movie');
%handles.tab4 = uitab('Parent', handles.tgroup, 'Title', 'Resolution Mode');

%Place panels into each tab
set(handles.P1,'Parent',handles.tab1)
set(handles.P2,'Parent',handles.tab2)
%set(handles.P3,'Parent',handles.tab4)
set(handles.P4,'Parent',handles.tab3)

%Reposition each panel to same location as panel 1
set(handles.P2,'position',get(handles.P1,'position'));
%set(handles.P3,'position',get(handles.P1,'position'));
set(handles.P4,'position',get(handles.P1,'position'));

%add radio-button callbacks
set(handles.FilterPanel,'SelectionChangeFcn',@FilterChange);

%set status flags
handles.ResMode = 0;
handles.Record = 0;

% Update handles structure
guidata(hObject, handles);

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

%determine if Image name was passed as calling argument
if ~isempty(p.Results.filename)
    if ischar(p.Results.aoi) % Allows this to work deployed
        AOI = str2num(p.Results.aoi); % STR2NUM required since this will be a vector (must be passed in quotes for a deployed application)
    else
        AOI = p.Results.aoi;
    end
    if ischar(p.Results.segment)
        segment = str2double(p.Results.segment);
    else
        segment = p.Results.segment;
    end
    ApToolLoadImage(p.Results.filename,hObject,handles,AOI,segment);
end

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

function FilterChange(hObject, eventdata)

handles = guidata(gcf);
ApToolnewpos(getPosition(handles.H), hObject);

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

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

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

imcontrast(handles.phd);

% --- Executes on selection change in PHDZoomCombo.
function PHDZoomCombo_Callback(hObject, eventdata, handles)
% hObject    handle to PHDZoomCombo (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 PHDZoomCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from PHDZoomCombo
val = get(hObject,'Value');
% apiSP2 = iptgetapi(handles.hSP2);

%update image zoom
if (val == 1)
    set(handles.phd,'xlim',[1 handles.phdmagSize(2)],'ylim',[1 handles.phdmagSize(1)])
    %     set(handles.phdhandle,'cdata',handles.phdmag)
    %     mag = apiSP2.findFitMag();
    %     mag = mag-mag*0.2; %adjust for axes labels
    %     apiSP2.setMagnification(mag);
elseif (val == 2)
    xLims = handles.ZpLimsRn(1)+[0 handles.ZpWidthRn] ...
    +[-1 1]*handles.ZpWidthRn*.05; %add buffer
    xLims = [max(1,floor(xLims(1))) ...
        min(handles.phdmagSize(1),ceil(xLims(2)))]; %check image size
    yLims = handles.ZpLimsAz(1)+[0 handles.ZpWidthAz] ...
    +[-1 1]*handles.ZpWidthAz*.05; %add buffer
    yLims = [max(1,floor(yLims(1))) ...
        min(handles.phdmagSize(2),ceil(yLims(2)))]; %check image size
    set(handles.phd,'xlim',yLims,'ylim',xLims)
end
ApToolupdatePHD_axesLabels(handles)

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

strings = get(handles.RemapCombo,'String');
val = get(handles.RemapCombo,'Value');

%make contrast button visible if remap is linearremap
if strcmpi(strings{val},'linearremap')
    set(handles.ImageContrast,'Visible','on');
else
    set(handles.ImageContrast,'Visible','off');
end

ApToolnewpos(getPosition(handles.H),hObject);

% --- Executes during object creation, after setting all properties.
function RemapCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to RemapCombo (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 selection change in ImageZoomCombo.
function ImageZoomCombo_Callback(hObject, eventdata, handles)
% hObject    handle to ImageZoomCombo (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 ImageZoomCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from ImageZoomCombo
val = get(hObject,'Value');
apiSP1 = iptgetapi(handles.hSP1);

%update image zoom
if (val == 1)
    apiSP1.setMagnification(apiSP1.findFitMag());
else
    contents = cellstr(get(hObject,'String'));
    magPercent =  str2double(contents{val}(1:(end-1))); % 'end-1' removes percentage sign
    apiSP1.setMagnification(magPercent/100);
end

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

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

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

if ispref('matlab_sar_toolbox','last_used_directory')
    pathname = getpref('matlab_sar_toolbox','last_used_directory');
    if ~ischar(pathname)||~exist(pathname,'dir')
        pathname = pwd;
    end
else
    pathname = pwd;
end
[filenames,pathname]=uigetfile(sar_file_extensions('amplitude'),...
    'Open SAR Data File',pathname,'MultiSelect','on');

if ~isempty(pathname)
    setpref('matlab_sar_toolbox','last_used_directory',pathname); %store path
end

if(iscell(filenames)) % Multiple files requested
    for j=1:length(filenames)
        fullfilename{j}=[pathname filenames{j}];
    end
elseif(filenames)
    fullfilename{1}=[pathname filenames];
end

ApToolLoadImage(fullfilename,hObject,handles,[],1);

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

if strcmp(get(hObject,'String'),'Measure')
    handles.MeasureLine = imline(handles.image);
    setColor(handles.MeasureLine,'Cyan');
    kids = get(handles.MeasureLine,'Children');
    set(kids,'LineWidth',3);
    set(kids,'MarkerSize',1);
    api_handle = iptgetapi(handles.MeasureLine);
    api_handle.addApToolnewpositionCallback(@newlinepos);
    set(handles.Measure,'String','Remove');
    %compute line distance and heading in the ground plane
    pos = getPosition(handles.MeasureLine);
    StartPos = pos(1,:);
    StopPos = pos(2,:);
    StartPos(1) = StartPos(1)+handles.aoi(1);
    StartPos(2) = StartPos(2)+handles.aoi(2);
    StopPos(1) = StopPos(1)+handles.aoi(1);
    StopPos(2) = StopPos(2)+handles.aoi(2);
    lla1 = point_slant_to_ground(fliplr(StartPos)',handles.meta);
    lla2 = point_slant_to_ground(fliplr(StopPos)',handles.meta);
    d1km=lldistkm(lla1(1:2),lla2(1:2));
    Distance = d1km*1000; %meters
    %get units (meters for metric and feet for English
    if get(handles.MetricCheck,'Value')
        set(handles.MeasureDist,'String',sprintf('%.1f',Distance));
        set(handles.MeasureUnits,'String','meters');
    else
        set(handles.MeasureDist,'String',sprintf('%.1f',Distance/0.3048));
        set(handles.MeasureUnits,'String','feet');
    end
    set(handles.MeasureUnits,'Visible','on');
else
    delete(handles.MeasureLine);
    handles.MeasureLine = [];
    set(handles.Measure,'String','Measure');
    set(handles.MeasureDist,'String','');
    set(handles.MeasureUnits,'Visible','on');
end

guidata(hObject, handles);

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

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

pos = [handles.ZpLimsAz(1), handles.ZpLimsRn(1),...
    handles.ZpWidthAz handles.ZpWidthRn];
setPosition(handles.H,pos);
ApToolnewpos(pos, hObject);

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

% --- Executes during object creation, after setting all properties.
function AzRes_CreateFcn(hObject, eventdata, handles)
% hObject    handle to AzRes (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 RgRes_Callback(hObject, eventdata, handles)
% hObject    handle to RgRes (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 RgRes as text
%        str2double(get(hObject,'String')) returns contents of RgRes as a double

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

ApToolnewpos(getPosition(handles.H),hObject);

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

% --- Executes during object creation, after setting all properties.
function CurFrame_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CurFrame (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 TotFrames_Callback(hObject, eventdata, handles)
% hObject    handle to TotFrames (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 TotFrames as text
%        str2double(get(hObject,'String')) returns contents of TotFrames as a double

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

set([handles.Next handles.Last],'enable','on');
set([handles.First handles.Prev],'enable','off');
UpdateAnimationFrame(1, handles);

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

%previous Frame
CurFrame = str2double(get(handles.CurFrame,'String')) - 1;

set([handles.Next handles.Last],'enable','on');

if (CurFrame == 1)
    set([handles.First handles.Prev],'enable','off');
else
    set([handles.First handles.Prev],'enable','on');
end

UpdateAnimationFrame(CurFrame, handles);

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

%get settings
NumFrames = str2double(get(handles.NumFrames,'String'));
FrameRate = str2double(get(handles.MovieFrameRate,'String'));
CycleCheck = get(handles.CycleCheck,'Value'); % Cycling continuously?

%disable all controls except pause
set(handles.First,'enable','off');
set(handles.Prev,'enable','off');
set(handles.Play,'enable','off');
set(handles.Pause,'enable','on');
set(handles.Next,'enable','off');
set(handles.Last,'enable','off');

% Set flag we will use for recording
handles.InLoop = 1;
guidata(hObject, handles);

set(handles.TotFrames,'String',NumFrames);
CurFrame = 1;

while (handles.InLoop)

    %see if pause was pressed
    if (strcmp(get(handles.Play,'Enable'),'on'))
        handles.InLoop = 0;
        break;
    end

    tic;
    UpdateAnimationFrame(CurFrame, handles);
    %wait until time for next frame
    elapsedtime = toc;
    pausetime = 1/FrameRate - elapsedtime;
    if (pausetime > 0)
        pause(pausetime);
    else
        pause(.05); %pause a little so the animation can be stopped
    end

    if (CurFrame == NumFrames)
        if (CycleCheck)
            CurFrame = 1;
        else
            %stop movie
            set(handles.Play,'enable','on');
            set(handles.Pause,'enable','off');
            break;
        end
    else
        CurFrame = CurFrame + 1;
    end
end

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

set(handles.Play,'Enable','on');
set(handles.NumFrames,'Enable','on');
set(handles.ApFraction,'Enable','on');
set(handles.MovieFrameRate,'Enable','on');

CurFrame = str2double(get(handles.CurFrame,'String'));
TotFrames = str2double(get(handles.TotFrames,'String'));

if (CurFrame > 1)
    set([handles.Prev handles.First],'Enable','on');
end

if (CurFrame < TotFrames)
    set([handles.Next handles.Last],'Enable','on');
end

set(handles.Pause,'Enable','off');

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

%advance Frame
CurFrame = str2double(get(handles.CurFrame,'String')) + 1;
TotFrames = str2double(get(handles.NumFrames,'String'));

if (CurFrame > 1)
    set([handles.First handles.Prev],'enable','on');
else
    set([handles.First handles.Prev],'enable','off');
end

if (CurFrame == TotFrames)
    set([handles.Next handles.Last],'enable','off');
else
    set([handles.Next handles.Last],'enable','on');
end

UpdateAnimationFrame(CurFrame, handles);

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

%advance Frame
set([handles.First handles.Prev],'enable','on');
set([handles.Next handles.Last],'enable','off');

CurFrame = str2double(get(handles.NumFrames,'String'));
UpdateAnimationFrame(CurFrame, handles);

function UpdateAnimationFrame(CurFrame, handles)

if isnan(CurFrame)
    CurFrame = 1;
end
set(handles.CurFrame,'String',CurFrame);

NumFrames = str2double(get(handles.NumFrames,'String'));
ApertureFraction = str2double(get(handles.ApFraction,'String'));
if (get(handles.Slow,'Value'))
    ApWidth = round(handles.ZpWidthAz*ApertureFraction);
    StartPos = max(1,handles.ZpLimsAz(1) + ...
        round((CurFrame-1)*(handles.ZpWidthAz-ApWidth)/(NumFrames-1)));

    %update imrect (this will update image)
    setPosition(handles.H,[StartPos handles.ZpLimsRn(1) ApWidth handles.ZpWidthRn]);
else
    ApWidth = round(handles.ZpWidthRn*ApertureFraction);
    StartPos = max(1,handles.ZpLimsRn(1) + ...
        round((CurFrame-1)*(handles.ZpWidthRn-ApWidth)/(NumFrames-1)));
    [ny, nx] = size(handles.phasehistory);
    StopPos = min(ny,StartPos + ApWidth);
    StartPos = ny - StopPos + 1; % Flip due to imshow convention

    %update imrect
    setPosition(handles.H,[handles.ZpLimsAz(1) StartPos handles.ZpWidthAz ApWidth]);
end

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

% --- Executes during object creation, after setting all properties.
function ApTime_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ApTime (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 ApBandwidth_Callback(hObject, eventdata, handles)
% hObject    handle to ApBandwidth (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 ApBandwidth as text
%        str2double(get(hObject,'String')) returns contents of ApBandwidth as a double

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

if get(hObject,'Value') % In general, we can't deskew in range and cross-range simultaneously
    if ~isscalar(handles.meta.Grid.Col.DeltaKCOAPoly) || ...
            ~isscalar(handles.meta.Grid.Row.DeltaKCOAPoly)
        set(handles.DeskewFast,'Value',false);
    end
    handles.manual_offset = [0 0];
elseif all(handles.meta.Grid.Row.DeltaKCOAPoly(:)==0)&&handles.isvalid_row_deltakcoapoly
    set(handles.DeskewFast,'Value',true);
end
ApToolprocess_phd(hObject,handles);

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

if get(hObject,'Value') % In general, we can't deskew in range and cross-range simultaneously
    if ~isscalar(handles.meta.Grid.Col.DeltaKCOAPoly) || ...
            ~isscalar(handles.meta.Grid.Row.DeltaKCOAPoly)
        set(handles.DeskewSlow,'Value',false);
    end
    handles.manual_offset = [0 0];
elseif all(handles.meta.Grid.Col.DeltaKCOAPoly(:)==0) && handles.isvalid_col_deltakcoapoly
    set(handles.DeskewSlow,'Value',true);
end
ApToolprocess_phd(hObject,handles);

% --- Executes on button press in UniformWeighting.
function UniformWeighting_Callback(hObject, eventdata, handles)
% hObject    handle to UniformWeighting (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 UniformWeighting
ApToolprocess_phd(hObject,handles);

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

fhand = figure('Name','Select Nonzeropad Area','Colormap',gray,...
    'MenuBar','none','Toolbar','none','NumberTitle','off');
ahand = axes('Parent',fhand,'Units','normalized','Position',[0 .2 1 .8]);
uicontrol('Style','pushbutton','String','Recenter','FontWeight','bold',...
    'Units','normalized','Position',[.2 .05 .2 .1],'parent',fhand,...
    'Callback',@manual_recenter);
uicontrol('Style','pushbutton','String','OK','FontWeight','bold',...
    'Units','normalized','Position',[.6 .05 .2 .1],'parent',fhand,...
    'Callback',@manual_ok);
if isfield(handles,'polar_PHD_idx')
    local.phasehistory = abs(fftshift(handles.fft_sp(handles.complex_data(:,:,handles.polar_PHD_idx).')));
else
    local.phasehistory = abs(fftshift(handles.fft_sp(handles.complex_data.')));
end
% PHD display is flipped so that time increase to the right
if isfield(handles.meta,'SCPCOA') && isfield(handles.meta.SCPCOA,'SideOfTrack') && ...
        strcmp(handles.meta.SCPCOA.SideOfTrack,'L')
    local.phasehistory = fliplr(local.phasehistory);
end

% We could guess frequency support center/zeropad from data here to
% intialize imrect position.
phdmean = mean(local.phasehistory(:));
phdstd = std(local.phasehistory(:));
local.ihand = image(local.phasehistory,'Parent',ahand,'CDataMapping','scaled');
set(ahand,'DataAspectRatio',[1 1 1],'CLim',[0 phdmean+3*phdstd],...
    'XTick',[],'YTick',[]);
local.manual_imrect = imrect(ahand, [handles.ZpLimsAz(1), handles.ZpLimsRn(1),...
    handles.ZpWidthAz handles.ZpWidthRn]);
local.manual_offset = [0 0]; % Remember how offcenter we are
local.parent = hObject;
guidata(fhand, local);

% Recenter image of PHD to imrect
function manual_recenter(hObject, eventdata)
handles = guidata(hObject);
[ny, nx] = size(handles.phasehistory);
center = round([nx,ny]/2);
pos = getPosition(handles.manual_imrect);
if all(pos([1 2])<=1) && all((pos([1 2])+pos([3 4]))>[nx ny])
    pos = [1 1 nx ny];
end
handles.manual_offset = mod(center - round(pos([1 2])+(pos([3 4])/2)) + ...
    + handles.manual_offset,[nx ny]);
guidata(hObject, handles); % Update handles.manual_offset
set(handles.ihand,'CData',circshift(handles.phasehistory,handles.manual_offset([2 1])));
pos([1 2]) = center - round(pos([3 4])/2);
setPosition(handles.manual_imrect,pos);

function manual_ok(hObject, eventdata)
manual_recenter(hObject, eventdata);
handles = guidata(hObject);
parent = guidata(handles.parent);
[ny, nx] = size(handles.phasehistory);
pos = getPosition(handles.manual_imrect);
parent.AzPad = max(1,nx/pos(3));
parent.RnPad = max(1,ny/pos(4));
parent.ZpLimsAz = max(1,pos(1));
parent.ZpLimsAz(2) = min(nx,pos(1)+pos(3)-1);
parent.ZpWidthAz = diff(parent.ZpLimsAz)+1;
parent.ZpLimsRn = max(1,pos(2));
parent.ZpLimsRn(2) = min(ny,pos(2)+pos(4)-1);
parent.ZpWidthRn = diff(parent.ZpLimsRn)+1;

if verLessThan('matlab', '7.6')
    disp('Warning. Matlab version does not support imrect constraint function');
else
    setPositionConstraintFcn(parent.H,...
        makeConstrainToRectFcn('imrect',parent.ZpLimsAz,parent.ZpLimsRn));
end

parent.manual_offset = handles.manual_offset;
% PHD display is flipped so that time increase to the right, but offset is
% applied before flipping.
if isfield(parent.meta,'SCPCOA') && isfield(parent.meta.SCPCOA,'SideOfTrack') && ...
        strcmp(parent.meta.SCPCOA.SideOfTrack,'L')
    parent.manual_offset(1) = -parent.manual_offset(1);
end

% Recompute weighting here.  If frequency support/zeropad factor were wrong
% (which they must have been, if the data has to be manually adjusted), and
% the weighting was estimated from the pixel data (as opposed to the
% metadata), the weighting function was almost certainly computed
% incorrectly.
if parent.weighting_computed_from_data
    phasehistory = parent.fft_sp(conj(parent.complex_data));
    phasehistory = circshift(phasehistory,handles.manual_offset);
    data = parent.fft_im(phasehistory);
    parent.weight_fun_az = estimate_weighting_mem(data, 1, parent.AzPad);
    parent.weight_fun_rng = estimate_weighting_mem(data, 2, parent.RnPad);
end

set(parent.DeskewSlow,'Value',false);
set(parent.DeskewFast,'Value',false);
ApToolprocess_phd(handles.parent,parent);
close(get(hObject,'Parent'));

% --- Executes on button press in CycleCheck.
function CycleCheck_Callback(hObject, eventdata, handles)
% hObject    handle to CycleCheck (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 CycleCheck

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

% --- Executes during object creation, after setting all properties.
function NumFrames_CreateFcn(hObject, eventdata, handles)
% hObject    handle to NumFrames (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 ApFraction_Callback(hObject, eventdata, handles)
% hObject    handle to ApFraction (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 ApFraction as text
%        str2double(get(hObject,'String')) returns contents of ApFraction as a double

% --- Executes during object creation, after setting all properties.
function ApFraction_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ApFraction (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 MovieFrameRate_Callback(hObject, eventdata, handles)
% hObject    handle to MovieFrameRate (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 MovieFrameRate as text
%        str2double(get(hObject,'String')) returns contents of MovieFrameRate as a double

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

imcontrast(handles.image);

% --- Executes on selection change in image_rep_combo.
function image_rep_combo_Callback(hObject, eventdata, handles)
% hObject    handle to image_rep_combo (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 image_rep_combo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from image_rep_combo
ApToolnewpos(getPosition(handles.H),hObject);

% --- Executes during object creation, after setting all properties.
function image_rep_combo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to image_rep_combo (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 selection change in PHDPolCombo.
function PHDPolCombo_Callback(hObject, eventdata, handles)
% hObject    handle to PHDPolCombo (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 PHDPolCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from PHDPolCombo

handles.polar_PHD_idx = get(handles.PHDPolCombo,'Value');
ApToolprocess_phd(hObject,handles); % Apply PHD options

% --- Executes during object creation, after setting all properties.
function PHDPolCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to PHDPolCombo (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 InverseSelection.
function InverseSelection_Callback(hObject, eventdata, handles)
% hObject    handle to InverseSelection (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 InverseSelection
if get(hObject,'Value')
    setColor(handles.H,'red');
else
    setColor(handles.H,'blue');
end
ApToolnewpos(getPosition(handles.H),hObject);

% --- Executes on button press in InversePolar.
function InversePolar_Callback(hObject, eventdata, handles)
% hObject    handle to InversePolar (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 InversePolar
ApToolprocess_phd(hObject,handles); % Apply PHD options
ApToolnewpos(getPosition(handles.H),hObject);

% --- Executes on button press in AlwaysApply.
function AlwaysApply_Callback(hObject, eventdata, handles)
% hObject    handle to AlwaysApply (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 AlwaysApply
ApToolnewpos(getPosition(handles.H),hObject);

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

% --- Executes during object creation, after setting all properties.
function nx_CreateFcn(hObject, eventdata, handles)
% hObject    handle to nx (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 ny_Callback(hObject, eventdata, handles)
% hObject    handle to ny (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 ny as text
%        str2double(get(hObject,'String')) returns contents of ny as a double

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

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

% --- Executes during object creation, after setting all properties.
function CurRecFrame_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CurRecFrame (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 TotRecFrame_Callback(hObject, eventdata, handles)
% hObject    handle to TotRecFrame (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 TotRecFrame as text
%        str2double(get(hObject,'String')) returns contents of TotRecFrame as a double

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

handles.Record = 1;
set(handles.Recording,'enable','off');
set(handles.StopRecording,'enable','on');
handles.recordparams = [];

%turn of cycle continuously check as this is not desired for a movie (the
%GIF will cycle on its' own)
set(handles.CycleCheck,'Value',0);

% Update handles structure
guidata(hObject, handles);

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

%get selection and launch appropriate file dialog
%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

filterspec={'*.gif','Animated GIF (*.gif)'};
[fname, path] = uiputfile( filterspec,'Save Movie File',pathstr);
if isequal(fname,0) % Cancel was pressed
    return;
end

filename = strcat(path,fname);
[pathstr, name, ext] = fileparts(filename);

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

set(handles.Recording,'Enable','off');
set(handles.StopRecording,'Enable','off');

numframes = length(handles.recordparams);
set(handles.TotRecFrame,'String',numframes);

%get settings
FullRes = get(handles.FullRes,'Value');
Annotate = get(handles.AnnotationCheck,'Value');
framerate = str2double(get(handles.MovieFrameRate,'String'));

if FullRes
    [chip, handles] = getFullResImage(handles);
    [ny,nx,~] = size(chip);

    %if chip is small then we will make bigger if annotation is selected,
    %otherwise it will not be legible
    MinSize = 1000;
    if Annotate
        if nx<MinSize && ny<MinSize
            if ny < nx
                new_ny = MinSize;
                new_nx = round((new_ny/ny)*nx);
            else
                new_nx = MinSize;
                new_ny = round((new_nx/nx)*ny);
            end
            chip = imresize(chip,[new_ny new_nx]);
        end
    end
else % Screen resolution doesn't do annotation
    F = getframe( handles.image );
    chip = F.cdata(:,:,:);
end

val = get(handles.image_rep_combo,'Value');
strings = get(handles.image_rep_combo,'String');
polstring = strings{val};
animated(:,:,:,numframes) = chip;

TextCount = 0;

for i=1:numframes
    if FullRes
        %Full Resolution, get full chip for
        setPosition(handles.H,handles.recordparams(i).Pos);
        chip = abs(getFullResImage(handles));

        if Annotate
            %Compute Height of Text based on ny, we'll use 1/8th
            %Mode
            %Frame n of n
            %AzRes: # units, RgRes: # units
            BlockHeight = round(size(chip,1)/8);
            FontSize = round(BlockHeight/3);
            ModeString = ['Mode: ' handles.recordparams(i).Mode];
            ModeStringIm = RasterizeText(ModeString,'Times New Roman',FontSize);
            FrameString = ['Frame ' num2str(i) ' of ' num2str(numframes)];
            FrameStringIm = RasterizeText(FrameString,'Times New Roman',FontSize);
            ResString = sprintf('AzRes: %3.1f %s, RgRes: %3.1f %s', handles.recordparams(i).AzRes, ...
                        handles.recordparams(i).AzResUnits, handles.recordparams(i).RangeRes, ...
                        handles.recordparams(i).RangeResUnits);
            ResStringIm = RasterizeText(ResString,'Times New Roman',FontSize);
            ny = size(ModeStringIm,1)+size(FrameStringIm,1)+size(ResStringIm,1);
            nx = max([size(ModeStringIm,2) size(FrameStringIm,2) size(ResStringIm,2)]);
            TextIm = zeros(ny,nx);
            TextIm(1:size(ModeStringIm,1),1:size(ModeStringIm,2)) = ModeStringIm;
            StartRow = size(ModeStringIm,1)+1;
            StopRow = StartRow + size(FrameStringIm,1)-1;
            TextIm(StartRow:StopRow,1:size(FrameStringIm,2)) = FrameStringIm;
            StartRow = StopRow+1;
            StopRow = StartRow + size(ResStringIm,1)-1;
            TextIm(StartRow:StopRow,1:size(ResStringIm,2)) = ResStringIm;
            TextIm(TextIm>0)=255;
            %Add annotation to lower left
            StartRow = size(chip,1)-ny+1;
            if size(chip,3) == 1
                chip(StartRow:end,1:nx) = TextIm;
            else
                chip(StartRow:end,1:nx,1) = TextIm;
                chip(StartRow:end,1:nx,2) = TextIm;
                chip(StartRow:end,1:nx,3) = TextIm;
            end
        end
    else
        %Screen Resolution, just update imrect pos and let callback update
        setPosition(handles.H,handles.recordparams(i).Pos);
        %set CLim
        set(handles.image,'CLim',handles.recordparams(i).CLim);
        %set scroll panel to selected view
        handles.apiSP1.setMagnificationAndCenter(handles.recordparams(i).Mag,...
        handles.recordparams(i).Center(1),handles.recordparams(i).Center(2));
        axes(handles.image);
        F = getframe( handles.image );
        chip = F.cdata(:,:,:);

        if Annotate
            %Compute Height of Text based on ny, we'll use 1/8th
            %Mode
            %Frame n of n
            %AzRes: # units, RgRes: # units
            BlockHeight = round(size(chip,1)/8);
            FontSize = round(BlockHeight/3);
            ModeString = ['Mode: ' handles.recordparams(i).Mode];
            ModeStringIm = RasterizeText(ModeString,'Times New Roman',FontSize);
            FrameString = ['Frame ' num2str(i) ' of ' num2str(numframes)];
            FrameStringIm = RasterizeText(FrameString,'Times New Roman',FontSize);
            ResString = sprintf('AzRes: %3.1f %s, RgRes: %3.1f %s', handles.recordparams(i).AzRes, ...
                        handles.recordparams(i).AzResUnits, handles.recordparams(i).RangeRes, ...
                        handles.recordparams(i).RangeResUnits);
            ResStringIm = RasterizeText(ResString,'Times New Roman',FontSize);
            ny = size(ModeStringIm,1)+size(FrameStringIm,1)+size(ResStringIm,1);
            nx = max([size(ModeStringIm,2) size(FrameStringIm,2) size(ResStringIm,2)]);
            TextIm = zeros(ny,nx);
            TextIm(1:size(ModeStringIm,1),1:size(ModeStringIm,2)) = ModeStringIm;
            StartRow = size(ModeStringIm,1)+1;
            StopRow = StartRow + size(FrameStringIm,1)-1;
            TextIm(StartRow:StopRow,1:size(FrameStringIm,2)) = FrameStringIm;
            StartRow = StopRow+1;
            StopRow = StartRow + size(ResStringIm,1)-1;
            TextIm(StartRow:StopRow,1:size(ResStringIm,2)) = ResStringIm;
            TextIm(TextIm>0)=255;
            %Add annotation to lower left
            StartRow = size(chip,1)-ny+1;
            chip(StartRow:end,1:nx,1) = TextIm;
            chip(StartRow:end,1:nx,2) = TextIm;
            chip(StartRow:end,1:nx,3) = TextIm;
        end
    end

    if ~strcmpi(polstring,'amplitude')
        %convert to indexed image
        if i == 1
            [animated,cmap] = rgb2ind(chip,256,'nodither');
        else
            animated(:,:,1,i) = rgb2ind(chip,cmap,'nodither');
        end
    else
        if i == 1
            animated(:,:,:,i) = double(chip);
        else
            animated(:,:,:,i) = double(chip);
        end
    end

    %update status
    set(handles.CurRecFrame,'String',i);
end

DelayTime = 1/framerate;
if strcmpi(polstring,'amplitude')
    imwrite(animated, filename, 'DelayTime', DelayTime, 'LoopCount', inf);
else
    imwrite(animated, cmap, filename, 'DelayTime', DelayTime, 'LoopCount', inf);
end

set(handles.TotRecFrame,'String','');
set(handles.CurRecFrame,'String','');

set(handles.Recording,'Enable','on');
set(handles.StopRecording,'Enable','off');

handles.Record = 0;

% Update handles structure
guidata(hObject, handles);

% --- Executes on button press in SaveImage.
function SaveImage_Callback(hObject, eventdata, handles)
% hObject    handle to SaveImage (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

if get(handles.JPG,'Value')
    [fname, path] = uiputfile( {'*.jpg','jpg Files (*.jpg)'},'Save JPG File',pathstr);
    filename = strcat(path,fname);
    if get(handles.FullRes,'Value')
        %full res image of chip
        chip = abs(getFullResImage(handles));
        imwrite(chip,filename,'jpg');
    else
        %just write what is on the screen
        frame = getframe(handles.image);
        imwrite(frame.cdata,filename,'jpg');
    end
else
    [fname, path] = uiputfile( {'*.ntf','SICD Files (*.ntf)'},'Save SICD File',pathstr);
    filename = strcat(path,fname);

    %get complex image chip
    chip = getFullResImage(handles,'complex');
    chip = handles.fft_sp(fftshift(handles.fft_im((chip))));
    meta = handles.meta;
    meta.ImageFormation.Processing.Type = 'Subaperture';

    %update res, frequency support etc.
    %this should work for spotlight collects

    %get new BW and center position
    pos = getPosition(handles.H);
    SlowPercent = pos(3)/handles.ZpWidthAz;
    SlowCenter = (pos(1)+pos(3)/2)/size(chip,2);
    FastPercent = pos(4)/handles.ZpWidthRn;
    FastCenter = (pos(2)+pos(4)/2)/size(chip,1);

    %update SICD fields
    meta.Grid.Col.ImpRespBW = meta.Grid.Col.ImpRespBW*SlowPercent;
    meta.Grid.Col.DeltaKCOAPoly = double(meta.Grid.Col.Sgn)*(SlowCenter-.5)/meta.Grid.Col.SS;
    meta.Grid.Row.ImpRespBW = meta.Grid.Row.ImpRespBW*FastPercent;
    meta.Grid.Row.DeltaKCOAPoly = double(meta.Grid.Row.Sgn)*(FastCenter-.5)/meta.Grid.Row.SS;
    %set remaining fields to zero and re-derive
    meta.Grid.Row = rmfield(meta.Grid.Row,'ImpRespWid');
    meta.Grid.Row = rmfield(meta.Grid.Row,'DeltaK1');
    meta.Grid.Row = rmfield(meta.Grid.Row,'DeltaK2');
    meta.Grid.Col = rmfield(meta.Grid.Col,'ImpRespWid');
    meta.Grid.Col = rmfield(meta.Grid.Col,'DeltaK1');
    meta.Grid.Col = rmfield(meta.Grid.Col,'DeltaK2');
    meta = derived_sicd_fields(meta);

    %if weighting was applied, then set the field...TODO: add sampled
    %weighting function so it can be undone
    %we will assume any weighting from the input image has been removed
    if get(handles.Gaussian,'Value')
        WgtType = 'GAUSSIAN';
    elseif get(handles.x4,'Value')
        WgtType = '1/X4';
    elseif get(handles.Hamming,'Value')
        WgtType = 'HAMMING';
    elseif get(handles.CosOnPed,'Value')
        WgtType = 'COSINEONPED';
    else
        WgtType = 'UNIFORM';
    end
    meta.Grid.Col.WgtType = WgtType;
    meta.Grid.Row.WgtType = WgtType;

    meta.ImageData.NumRows = size(chip,1);
    meta.ImageData.NumCols = size(chip,2);
    meta = add_sicd_corners(meta);

    writer = SICDWriter(filename,meta);
    writer.write_chip(chip.',[1 1]);
    delete(writer);
end

function [chip,handles] = getFullResImage(handles,format)

if ~exist('format','var'); format = 'detected'; end

%return full res complex image chip for current position
pos = getPosition(handles.H);
xmin = max(handles.ZpLimsAz(1),floor(pos(1)));
xmax = min(handles.ZpLimsAz(2),floor(pos(1)+pos(3)-1));
ymin = max(handles.ZpLimsRn(1),floor(pos(2)));
ymax = min(handles.ZpLimsRn(2),floor(pos(2)+pos(4)-1));

%need to modify xposition if flight is left
[ny,nx,~] = size(handles.phasehistory);
if isfield(handles.meta,'SCPCOA') && isfield(handles.meta.SCPCOA,'SideOfTrack') && ...
   strcmp(handles.meta.SCPCOA.SideOfTrack,'L')
    xminold = xmin;
    xmin = round(nx-xmax);
    if (xmin<1);xmin=1;end
    xmax = round(nx-xminold);
end

%get filter type
if get(handles.None,'Value')
    WindowFilter = 0;
elseif get(handles.Gaussian,'Value')
    WindowFilter = 1;
elseif get(handles.x4,'Value')
    WindowFilter = 2;
elseif get(handles.Hamming,'Value')
    WindowFilter = 3;
else
    WindowFilter = 4;
end

AlwaysApply = get(handles.AlwaysApply,'Value');
phdchip = handles.phasehistory(ymin:ymax,xmin:xmax,:);

if (ymax-ymin) < handles.ZpWidthRn - 2
    FilterRange = 1;
else
    FilterRange = 0;
end
if (xmax-xmin) < handles.ZpWidthAz - 2
    FilterAz = 1;
else
    FilterAz = 0;
end

if AlwaysApply
    FilterRange = 1;
    FilterAz = 1;
end

%now reform image with selected aperture
if get(handles.InverseSelection,'Value')
    Ap = single(handles.phasehistory);
    Ap(ymin:ymax,xmin:xmax) = 0;
else
    Ap = zeros(ny,nx,'single');
    phdchip = ApToolFilterPHDChip(phdchip,WindowFilter,FilterRange,FilterAz);
    Ap(ymin:ymax,xmin:xmax,1:size(phdchip,3)) = phdchip;
end

if ~strcmpi(format,'complex')
    [chip,handles] = ApToolmakeDisplayable(handles,Ap);
else
    chip = handles.fft_im(Ap);
end

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

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


text:
function obj=geom_count(obj,varargin)
%geom_count Display data as points which size vary with with
%count
%
% Parameters:
% 'scale': set the scaling factor between count and area
% 'point_color': set how the points are colored 'edge', 'face',
% 'all'

p=inputParser;
my_addParameter(p,'scale',20);
my_addParameter(p,'point_color','all'); %edge,face,all
parse(p,varargin{:});
obj.geom=vertcat(obj.geom,{@(dobj,dd)my_count(dobj,dd,p.Results)});
obj.results.geom_count_handle={};
end

function hndl=my_count(obj,draw_data,params)

if obj.continuous_color
    disp('geom_count() unsupported with continuous color')
    hndl=[];
else
    [x,y]=to_polar(obj,comb(draw_data.x),comb(draw_data.y));

    [C,ia,ic]=unique([shiftdim(x) shiftdim(y)],'rows');
    counts=accumarray(ic,1);

    switch params.point_color
        case 'face'
            edge='k';
            face=draw_data.color;
        case 'edge'
            edge=draw_data.color;
            face='none';
        otherwise
            edge='none';
            face=draw_data.color;
    end

    hndl=scatter(C(:,1),C(:,2),counts*params.scale,draw_data.marker,'MarkerEdgeColor',edge,'MarkerFaceColor',face);

    %hndl=my_point(obj,draw_data);
end

obj.results.geom_count_handle{obj.result_ind,1}=hndl;
end

author: piermorel

repo: gramm

save_path: github-repos/MATLAB/piermorel-gramm


text:
function tagS = RT_dose_module_tags
%"RT_dose_module_tags"
%   Return the tags used to represent a RT dose as specified by C.8.8.3 in
%   PS3.3 of 2006 DICOM specification.
%
%   Tags are returned in a struct array with 3 fields:
%
%   Tag: String containing hex DICOM tag of a field.
%  Type: String describing type of field, with 5 options:
%         '1' Field must exist, data must exist and be valid.
%         '2' Field must exist, data can exist and be valid, or be NULL.
%         '3' Field is optional, if the field exists data can exist and be
%             valid or be NULL.
%         '1C' Field must exist under certain conditions and contain valid
%             data.
%         '2C' Field must exist under certain conditions and can contain
%             valid data or be NULL.
%Children: For sequences, a tagS with the same format as this struct array.
%
%JRA 07/10/06
%
%Usage:
%   tagS = RT_dose_module_tags
%
% 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/>.

%Initialize the tagS structure.
tagS = struct('tag', {}, 'tagdec', {}, 'type', {}, 'children', {});

%Create an empty tagS template for sequence creation.
template = tagS;

%Add tags based on PS3.3 attribute lists.

%Samples per Pixel
tagS(end+1) = struct('tag', '00280002', 'tagdec', 2621442, 'type', '1C', 'children', []);

%Photometric Interpretation
tagS(end+1) = struct('tag', '00280004', 'tagdec', 2621444, 'type', '1C', 'children', []);

%Bits Allocated
tagS(end+1) = struct('tag', '00280100', 'tagdec', 2621696, 'type', '1C', 'children', []);

%Bits Stored
tagS(end+1) = struct('tag', '00280101', 'tagdec', 2621697, 'type', '1C', 'children', []);

%High Bit
tagS(end+1) = struct('tag', '00280102', 'tagdec', 2621698, 'type', '1C', 'children', []);

%Pixel Representation
tagS(end+1) = struct('tag', '00280103', 'tagdec', 2621699, 'type', '1C', 'children', []);

%Dose Units
tagS(end+1) = struct('tag', '30040002', 'tagdec', 805568514, 'type', '1', 'children', []);

%Dose Type
tagS(end+1) = struct('tag', '30040004', 'tagdec', 805568516, 'type', '1', 'children', []);

%Instance Number
tagS(end+1) = struct('tag', '00200013', 'tagdec', 2097171, 'type', '3', 'children', []);

%Dose Comment
tagS(end+1) = struct('tag', '30040006', 'tagdec', 805568518, 'type', '3', 'children', []);

%Normalization Point
tagS(end+1) = struct('tag', '30040008', 'tagdec', 805568520, 'type', '3', 'children', []);

%Dose Summation Type
tagS(end+1) = struct('tag', '3004000A', 'tagdec', 805568522, 'type', '1', 'children', []);

%Referenced RT Plan Sequence
tagS(end+1) = struct('tag', '300C0002', 'tagdec', 806092802, 'type', '1C', 'children', []);
child_1 = template;

    %Referenced SOP Class UID
    child_1(end+1) = struct('tag', '00081150', 'tagdec', 528720, 'type', '1C', 'children', []);

    %Referenced SOP Instance UID
    child_1(end+1) = struct('tag', '00081155', 'tagdec', 528725, 'type', '1C', 'children', []);

    %Referenced Fraction Group Sequence
    child_1(end+1) = struct('tag', '300C0020', 'tagdec', 806092832, 'type', '1C', 'children', []);
    child_2 = template;

        %Referenced Fraction Group Number
        child_2(end+1) = struct('tag', '300C0022', 'tagdec', 806092834, 'type', '1C', 'children', []);

        %Referenced Beam Sequence
        child_2(end+1) = struct('tag', '300C0004', 'tagdec', 806092804, 'type', '1C', 'children', []);
        child_3 = template;

            %Referenced Beam Number
            child_3(end+1) = struct('tag', '300C0006', 'tagdec', 806092806, 'type', '1C', 'children', []);

            %Referenced Control Point Sequence
            child_3(end+1) = struct('tag', '300C00F2', 'tagdec', 806093042, 'type', '1C', 'children', []);
            child_4 = template;

                %Referenced Start Control Point Index
                child_4(end+1) = struct('tag', '300C00F4', 'tagdec', 806093044, 'type', '1', 'children', []);

                %Referenced Stop Control Point Index
                child_4(end+1) = struct('tag', '300C00F6', 'tagdec', 806093046, 'type', '1', 'children', []);

                child_3(end).children = child_4;

            child_2(end).children = child_3;

        %Referenced Brachy Application Setup Sequence
        child_2(end+1) = struct('tag', '300C000A', 'tagdec', 806092810, 'type', '1C', 'children', []);
        child_3 = template;

            %Referenced Brachy Application Setup Number
            child_3(end+1) = struct('tag', '300C000C', 'tagdec', 806092812, 'type', '1C', 'children', []);

            child_2(end).children = child_3;

        child_1(end).children = child_2;

    tagS(end).children = child_1;

%Grid Frame Offset Vector
tagS(end+1) = struct('tag', '3004000C', 'tagdec', 805568524, 'type', '1C', 'children', []);

%Dose Grid Scaling
tagS(end+1) = struct('tag', '3004000E', 'tagdec', 805568526, 'type', '1C', 'children', []);

%Tissue Heterogeneity Correction
tagS(end+1) = struct('tag', '30040014', 'tagdec', 805568532, 'type', '3', 'children', []);

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function [nm] = yd2nm(yd)
% Convert length from yards to nanometers.
% Chad Greene 2012
nm = yd*914400000;


text:
function [x,y]=sample2dsubpix(image, n)
% [x,y]=sample2dsubpix(image, n)
% samples from the distribution provided as a 2d pixelised intensity image
% image - pixelised intensity image
% n - number of samples
if ~exist('n', 'var')
    n=1;
end
[xpix,ypix]=sample2d(image,n);
x=xpix-1 + rand;
y=ypix-1 + rand;

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function info = getinfo(vw)
%INFO=GETINFO(VW)
%  Returns a structure whose fields contain information about the opened
%  video object.  This structure may be flattened to a cell array and used
%  with the videoWriter constructor to recreate the current video file.
%
%SEE ALSO
%  videoWriter
%
%Copyright (c) 2006 Gerald Dalley
%See "MIT.txt" in the installation directory for licensing details (especially
%when using this library on GNU/Linux).

[names, vals] = feval(vw.plugin, 'getinfo', vw.handle);
info = cell2struct({vals{:}}, {names{:}}, 2);

% be nice and convert anything that looks like a number into one.
for i=1:length(names)
  name = names{i};
  if (length(info.(name)) < 64)
    num  = str2num(info.(name));
    if numel(num) > 0
      info.(name) = num;
    end
  end
end

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
function [Ytest d C] = clustercov(Ctest,Ctrain,Nclass,varargin)

    if isempty(varargin)
        method_mean = 'riemann';
        method_dist = 'riemann';
        method_clust = 'complete';
    else
        method_mean = varargin{1};
        method_dist = varargin{2};
        if length(varargin)<=2
            method_clust = 'complete';
        else
            method_clust = varargin{3};
        end
    end

    % initialisation
    Ntrial = size(Ctrain,3);

    d = zeros(Ntrial);
    for i=1:Ntrial
        for j=i+1:Ntrial
            d(i,j) = distance(Ctrain(:,:,i),Ctrain(:,:,j),method_dist);
        end
    end
    Y = squareform(d','tovector');
    Z = linkage(Y,method_clust);
    Ytrain = cluster(Z,'maxclust',Nclass);

    [Ytest d C] = mdm(Ctest,Ctrain,Ytrain,method_mean,method_dist);

author: alexandrebarachant

repo: covariancetoolbox


text:
function groups = find_blocks(in,th_max)
if nargin<2
   th_max = 0.6;
end

groups = [];
[xl yl] = size(in);
% maxth = 0.05;
% minth = 0.3;
maxi = max(max(in));
% if maxi<0.8
%     return
% end
maxth = maxi*th_max
if (max(max(in)) / (sum(sum(in))/(xl*xl-xl))) < 3
    fprintf('Clustering using MI may not be accurate since MI matrix has low variance')
    fprintf('\n')
end
i = 1;
found = 1;
while found
    maxconf = 0;
    for m_size = xl:-1:2

        found = 0;
        for tempi = 1:xl-m_size+1
            temp_matrix = in(tempi:tempi+m_size-1,tempi:tempi+m_size-1);
            [dependent conf] = check_dependency(temp_matrix,maxth);

            if dependent
                if conf>maxconf
                    maxconf = conf;
                    res = [tempi m_size];
                end
                found = 1;
            end
        end

    end
    if found
        groups = [groups res maxconf];
        in(res(1),:) = 0;
        in(:,res(1)) = 0;
        in(:,res(1)+res(2)-1)=0;
        in(res(1)+res(2)-1,:)=0;
        in(res(1):res(1)+res(2)-1,res(1):res(1)+res(2)-1) = 0;
    end
end

author: PatternRecognition

repo: OpenBMI


text:
function [] = cmbfast_clean(param)

% =========================================================================
% cmbfast_clean.m - A helper routine to erase output files from CMBFAST
% Last modified: January 25, 2006
% Judd D. Bowman
%
% This function deletes the output files generated by CMBFAST.  Pass to it
% the 'param' structure from cmbfast.m to delete the files associated with
% a particular run of CMBFAST.
%
% INPUT
% =====
% param = the output structure from cmbfast(...) that contains the file names
% and parameters for a specific run of CMBFAST.
%
% OUTPUT
% ======
% None
%
% =========================================================================

if (iscell(param.ftf))
	for n = 1:length(param.ftf)
        if (exist(param.ftf{n}) > 0)
            delete(param.ftf{n});
        end
	end
elseif (exist(param.ftf) > 0)
    delete(param.ftf);
end

if (exist(param.fcl) > 0)
    delete(param.fcl);
end

if (exist(param.fgl) > 0)
    delete(param.fgl);
end

if (exist(param.tcl) > 0)
    delete(param.tcl);
end

if (exist(param.fts) > 0)
    delete(param.fts);
end

if (exist(param.fpa) > 0)
    delete(param.fpa);
end


text:
% Move the roots of a polynom inside the unit circle
%
% Description
%  Stabilize a polynom.
%  Compared to polystab, polystab2 adds 2 elements
%   * Use the LEJA's order to recover the stable polynom from its roots in order
%     to minimize the numerical errors
%   * Even though the result should be stable in a single iteration, numerical
%     errors can still prevent the stability. Therefore, the stabilization step
%     is runned until the final result is finally stable.
%
% Inputs
%  a        : The AR coefficients to stabilize
%  [modmax] : Maximum modulus of the roots.
%             Any root with a bigger modulus than this value will be moved
%             towards the origin.
%             (def. 1)
%
% Outputs
%
% Copyright (c) 2011 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>
%

function b = polystab2(a, modmax)

    if nargin<2; modmax=1; end

    b = a;

    v = roots(a);

    idx = find(abs(v)>modmax);
    while ~isempty(idx)

        v(idx) = modmax*exp(1j*angle(v(idx)));

        ind = find(a~=0);
        b = a(ind(1))*poly(leja(v)); % Use LEJA's order to minimize num errors

        % Return only real coefficients if input was real:
        if ~any(imag(a))
            b = real(b);
        end

        a = b;
        v = roots(a);

        idx = find(abs(v)>modmax);
    end

    b = b(:);
return

author: covarep

repo: covarep

save_path: github-repos/MATLAB/covarep-covarep


text:
function ndx = read_txt(infilename)
% Creates an Ndx object from information stored in a text file.
% Inputs:
%   infilename: The name of the text file to read.
% Outputs:
%   ndx: An object of type Ndx constructed from the information in
%     the file.

assert(nargin==1)
assert(isa(infilename,'char'))

fid = fopen(infilename);
lines = textscan(fid,'%s%s');
fclose(fid);

models = lines{1};
testsegs = lines{2};
modelset = {};
segset = {};
modelset = union(modelset,models);
segset = union(segset,testsegs);

trialmask = false(length(modelset),length(segset));
[dummy,ii] = ismember(models,modelset);
[dummy,jj] = ismember(testsegs,segset);
trialmask(sub2ind(size(trialmask),ii,jj)) = true;

ndx = Ndx();
ndx.modelset = modelset;
ndx.segset = segset;
ndx.trialmask = trialmask;
assert(ndx.validate())

end

author: nesl


text:
function [F] = spm_vb_regionF (Y,xY,SPM)
% Get log model evidence over a region of data for a GLM
% FORMAT [F] = spm_vb_regionF (Y,xY,SPM)
%
% Y     Matrix of fMRI data (eg. from spm_summarise.m)
% xY    Coordinates etc from region (eg. from spm_voi.m)
% SPM   SPM data structure (this must be loaded in from an
%       SPM.mat file). If this field is not specified this function
%       will prompt you for the name of an SPM.mat file
%
% F     Log model evidence (single number for whole region)
%
% Importantly, the design matrix is normalised so that when you compare
% models their regressors will be identically scaled.
%
% Valid model comparisons also require that the DCT basis set used in high
% pass filtering, as specified in SPM.xX.K.X0, is the same for all models
% that are to be compared.
%
% W. Penny, G. Flandin, and N. Trujillo-Barreto. (2007). Bayesian Model
% Comparison of Spatially Regularised General Linear Models. Human
% Brain Mapping, 28(4):275-293.
%__________________________________________________________________________
% Copyright (C) 2005-2014 Wellcome Trust Centre for Neuroimaging

% Will Penny
% $Id: spm_vb_regionF.m 6079 2014-06-30 18:25:37Z spm $

try
    SPM;
catch
    [Pf, sts] = spm_select(1,'^SPM\.mat$','Select SPM.mat');
    if ~sts, return; end
    swd = spm_file(Pf,'fpath');
    load(fullfile(swd,'SPM.mat'))
end

s=length(SPM.Sess);
if s>1
    disp('spm_vb_regionF: only works for single session data');
    return
end

% Normalise design matrices to have columns of unit
% variance - except for last
X=SPM.xX.X;
X=norm_design(X);

% Make residual forming matrix (to later remove drifts)
X0=SPM.xX.K.X0;
N=size(X0,1);
iX0=pinv(X0);
R=eye(N)-X0*iX0;

% Remove drifts
Y=R*Y;

% Normalise Y to unit dev
sigma=std(Y);
N=size(Y,1);
Y=Y./(ones(N,1)*sigma);

xyz  = xY.XYZmm;
N    = size(xyz,2);
xyz  = SPM.xVol.M\[xyz;ones(1,size(xyz,2))];
xyz  = xyz(1:3,:);
vxyz = spm_vb_neighbors(xyz',1);

priors.W='Voxel - Shrinkage';
priors.A='Voxel - Shrinkage';

block=spm_vb_init_volume(X,1);
block=spm_vb_set_priors(block,priors,vxyz);
block.maxits = 64;
block.update_alpha  = 1;
block.update_w      = 1;
block.update_lambda = 1;
block.update_F      = 1;
block=spm_vb_glmar(Y,block);

F=block.F;

function [Xout] = norm_design (Xin)
% Normalise design matrix to have unit variance columns
% FORMAT [Xout] = norm_design (Xin)

X=Xin(:,1:end-1);
s=std(X,[],1);
iS=diag(1./s);
Xout=[X*iS,Xin(:,end)];

author: spm


text:
function [Q] = CouetteIC2D(x, y, time)

% function [Q] = CouetteIC2D(x, y, time)
% Purpose: evaluat solution for Couette flow

gamma = 1.4;

rad = sqrt(x.^2 + y.^2); theta = atan2(y, x);

Q = zeros(size(x,1), size(x,2), 4);

utheta = (-rad + 16./rad)/75;
p = 1 + (1./(75^2))*( (rad.^2)/2 - 32*log(rad) - 128./rad.^2 );

Q(:,:,1) = 1;
Q(:,:,2) = -sin(theta).*utheta;
Q(:,:,3) =  cos(theta).*utheta;
Q(:,:,4) = p/(gamma-1) + 0.5*(Q(:,:,2).^2 + Q(:,:,3).^2)./Q(:,:,1);
return

repo: Aero-matlab


text:
initialize;
configjson.imageLocation = fullfile(pwd, 'demo_img');
if(~exist(fullfile(pwd, 'demo_result')))
    mkdir(fullfile(pwd, 'demo_result'));
end
configjson.outputLocation = fullfile(pwd, 'demo_result');

imageFile='demo_img/2007_009084.jpg';
objectProposal='randomPrim';

%%% Proposals for all images in imageLocation

runObjectProposals(objectProposal);

% Proposals for one image
% 1)

proposals=runObjectProposals(objectProposal,imageFile);

% 2)

im=imread(imageFile);
proposals=runObjectProposals(objectProposal,im);

%%% Certain number of proposals

proposals=runObjectProposals(objectProposal,im,100);

author: Cloud-CV

repo: object-proposals


text:
function [Ei,Angle] = Associate(PopObj,W)
% Associate each solution with a reference direction

%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    Angle      = acos(1-pdist2(PopObj,W,'cosine'));
    [Angle,Ei] = min(Angle',[],1);
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function varargout = out_figure_image( hFig, imgFile, imgLegend)
% OUT_FIGURE_IMAGE: Save window contents as a bitmap image.
%
% USAGE: img = out_figure_image(hFig)           : Extract figure image and return it
%              out_figure_image(hFig, imgFile)  : Extract figure image and save it to imgFile
%              out_figure_image(hFig, 'Viewer') : Extract figure image and open it with the image viewer
%              out_figure_image(hFig, figFile)  : Save figure as a Matlab .fig file after removing some callbacks
%              out_figure_image(hFig, 'Figure') : Copy figure and removes callbacks
%              out_figure_image(hFig)           : Extract figure image and save it to a user selected file
%              out_figure_image(hFig, ..., imgLegend)
%              out_figure_image(hFig, ..., 'time')

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

global GlobalData;
drawnow;

% No legend: plot the time
if (nargin < 3)
    imgLegend = 'time';
elseif isempty(imgLegend)
    imgLegend = '';
end

%% ===== GET FILENAME =====
% If image filename is not specified
if (nargin <= 1) && (nargout == 0)
    % === Build a default filename ===
    % Get default directories and format
    LastUsedDirs = bst_get('LastUsedDirs');
    DefaultFormats = bst_get('DefaultFormats');
    if isempty(DefaultFormats.ImageOut)
        DefaultFormats.ImageOut = 'tif';
    end
    % Get the default filename (from the window title)
    wndTitle = get(hFig, 'Name');
    if isempty(wndTitle)
        imgDefautFile = 'img_default';
    else
        imgDefautFile = file_standardize(wndTitle, 0, '_', 1);
        imgDefautFile = strrep(imgDefautFile, '__', '_');
    end
    % Add extension
    imgDefautFile = [imgDefautFile, '.', lower(DefaultFormats.ImageOut)];
    imgDefautFile = strrep(imgDefautFile, '_.', '.');

    % === Ask user filename ===
    % Ask confirmation for the figure filename
    imgDefaultFile = bst_fullfile(LastUsedDirs.ExportImage, imgDefautFile);
    [imgFile, FileFormat] = java_getfile('save', 'Save figure as...', imgDefaultFile, 'single', 'files', ...
        {{'.tif'}, 'TIFF image, compressed (*.tif)',      'TIF'; ...
         {'.jpg'}, 'JPEG image (*.jpg)',                  'JPG'; ...
         {'.bmp'}, 'Bitmap file (*.bmp)',                 'BMP'; ...
         {'.fig'}, 'Matlab figure (*.fig)',               'FIG'; ...
         {'.png'}, 'Portable Network Graphics (*.png)',   'PNG'; ...
         {'.hdf'}, 'Hierarchical Data Format (*.hdf)',    'HDF'; ...
         {'.pbm'}, 'Portable bitmap (*.pbm)',             'PBM'; ...
         {'.pgm'}, 'Portable Graymap (*.pgm)',            'PGM'; ...
         {'.ppm'}, 'Portable Pixmap (*.ppm)',             'PPM';}, DefaultFormats.ImageOut);
    if isempty(imgFile)
        return
    end
    % Save new default export path
    LastUsedDirs.ExportImage = bst_fileparts(imgFile);
    bst_set('LastUsedDirs', LastUsedDirs);
    % Save default export format
    DefaultFormats.ImageOut = FileFormat;
    bst_set('DefaultFormats',  DefaultFormats);
elseif (nargout == 0)
    [fPath,fBase,fExt] = bst_fileparts(imgFile);
    if ~isempty(fExt)
        FileFormat = upper(fExt(2:end));
    else
        FileFormat = '';
    end
else
    FileFormat = 'ARRAY';
    imgFile = '';
end

%% ===== PREPARE FIGURE =====
% Get figure Type
[tmp,iFig,iDS] = bst_figures('GetFigure', hFig);
if ~isempty(iDS)
    FigureId = GlobalData.DataSet(iDS).Figure(iFig).Id;
else
    FigureId = [];
end
% If figure is a registered data figure
if ~isempty(iDS) && ~isempty(imgLegend)
    % If 3DAxes => Add a time legend
    if strcmpi(imgLegend, 'time')
        isAddTime = ~isempty(FigureId) && (strcmpi(FigureId.Type, '3DViz') || strcmpi(FigureId.Type, 'Topography'));
        if isAddTime && ~isempty(GlobalData.UserTimeWindow.CurrentTime)
            if (GlobalData.UserTimeWindow.CurrentTime > 2)
                imgLegend = sprintf('%4.3fs ', GlobalData.UserTimeWindow.CurrentTime);
            else
                imgLegend = sprintf('%dms ', round(GlobalData.UserTimeWindow.CurrentTime * 1000));
            end
        else
            imgLegend = '';
        end
    end
    % Create legend
    if ~isempty(imgLegend)
        % Get figure color
        figColor = get(hFig, 'Color');
        figPos   = get(hFig, 'Position');
        % Find opposite colors
        if (sum(figColor .^ 2) > 0.8)
            textColor = [0 0 0];
        else
            textColor = [.3 1 .3];
        end
        % Create axes
        hAxesLabel = axes(...
            'Parent',        hFig, ...
            'Tag',           'AxesTimestamp', ...
            'Units',         'Pixels', ...
            'Position',      [0, 0, figPos(3), 30], ...
            'Color',         'none', ...
            'XColor',        figColor, ...
            'YColor',        figColor, ...
            'XLim',          [0,1], ...
            'YLim',          [0,1], ...
            'YGrid',         'off', ...
            'XGrid',         'off', ...
            'XMinorGrid',    'off', ...
            'XTick',         [], ...
            'YTick',         [], ...
            'TickLength',    [0,0], ...
            'XTickLabel',    [], ...
            'Box',           'off', ...
            'Interruptible', 'off', ...
            'BusyAction',    'queue');
        % Create label
        hLabel = text(...
            10 / figPos(3), .5, imgLegend, ...
            'FontUnits',   'points', ...
            'FontWeight',  'bold', ...
            'FontSize',    15, ...
            'Color',       textColor, ...
            'Interpreter', 'none', ...
            'Tag',         'LabelTimestamp', ...
            'Parent',      hAxesLabel);
    end
else
    imgLegend = '';
end
% For time series figures: hide buttons
if ~isempty(FigureId) && ismember(FigureId.Type, {'DataTimeSeries', 'ResultsTimeSeries', 'Spectrum'})
    % Find existing buttons
    if bst_get('isJavacomponent')
        hButtons = findobj(hFig, 'Type', 'hgjavacomponent');
    else
        hButtons = findobj(hFig, 'Type', 'uicontrol');
        if (length(hButtons) > 1)
            hButtons(cellfun(@(c)isempty(strfind(c, 'Button')), get(hButtons, 'Tag'))) = [];
        elseif (length(hButtons) == 1) && isempty(strfind(get(hButtons, 'Tag'), 'Button'))
            hButtons = [];
        end
    end
    isVisible = get(hButtons, 'Visible');
    % Hide them
    set(hButtons, 'Visible', 'off');
else
    hButtons = [];
end
% Focus on figure (captures the contents the topmost figure)
pause(.01);
drawnow;
figure(hFig);
drawnow;

%% ===== SAVE FIGURE =====
if (~isempty(FileFormat) && strcmpi(FileFormat, 'FIG')) || strcmpi(imgFile, 'Figure')
    % === PREPARE FIGURE ===
    % Check figure type
    if ~isempty(FigureId) && ((strcmpi(FigureId.Type, 'Topography') && strcmpi(FigureId.SubType, '2DLayout')) || strcmpi(FigureId.Type, 'Connect') || strcmpi(FigureId.Type, 'MriViewer'))
        bst_error('This figure cannot be exported as a Matlab .fig file.', 'Save figure', 0);
        return;
    end
    % Ask use to remove callbacks or not
    if strcmpi(imgFile, 'Figure')
        isRemoveCallbacks = 0;
    else
        isRemoveCallbacks = java_dialog('confirm', ...
            ['If you save the figure with all the callback functions, you will' 10 ...
             'keep the interactivity of the figure but you will need to have ' 10 ...
             'the same version of Brainstorm running to open it again.' 10 10 ...
             'Remove callbacks from the figure?' 10], 'Save figure');
    end

    % Save existing callbacks
    CloseRequestFcn_bak       = get(hFig, 'CloseRequestFcn');
    KeyPressFcn_bak           = get(hFig, 'KeyPressFcn');
    WindowButtonDownFcn_bak   = get(hFig, 'WindowButtonDownFcn');
    WindowButtonMotionFcn_bak = get(hFig, 'WindowButtonMotionFcn');
    WindowButtonUpFcn_bak     = get(hFig, 'WindowButtonUpFcn');
    ResizeFcn_bak             = get(hFig, 'ResizeFcn');
    if isprop(hFig, 'KeyReleaseFcn')
        KeyReleaseFcn_bak = get(hFig, 'KeyReleaseFcn');
    end
    if isprop(hFig, 'WindowScrollWheelFcn')
        WindowScrollWheelFcn_bak = get(hFig, 'WindowScrollWheelFcn');
    end

    % Remove callbacks that crash without Brainstorm
    set(hFig, 'CloseRequestFcn', 'closereq');
    set(hFig, 'KeyPressFcn', []);
    if isprop(hFig, 'KeyReleaseFcn')
        set(hFig, 'KeyReleaseFcn', []);
    end
    % Remove other callbacks
    if isRemoveCallbacks
        set(hFig, 'WindowButtonDownFcn', []);
        set(hFig, 'WindowButtonMotionFcn', []);
        set(hFig, 'WindowButtonUpFcn', []);
        set(hFig, 'ResizeFcn', []);
        if isprop(hFig, 'WindowScrollWheelFcn')
            set(hFig, 'WindowScrollWheelFcn', []);
        end
    end
    % Find colorbar
    hColorbar = findobj(hFig, '-depth', 1, 'Tag', 'Colorbar');
    if ~isempty(hColorbar)
        ColorbarButton_bak = get(hColorbar, 'ButtonDownFcn');
        set(hColorbar, 'ButtonDownFcn', []);
    end
    % Display figure toolbar
    set(hFig, 'MenuBar', 'figure', 'ToolBar', 'auto');

    % Copy figure
    if strcmpi(imgFile, 'Figure')
        % Copy graphic objects
        hNewFig = copyobj(hFig, 0);
        % Copy callbacks
        set(hNewFig, 'CloseRequestFcn',       'closereq');
        set(hNewFig, 'KeyPressFcn',           []);
        set(hNewFig, 'WindowButtonDownFcn',   WindowButtonDownFcn_bak);
        set(hNewFig, 'WindowButtonMotionFcn', WindowButtonMotionFcn_bak);
        set(hNewFig, 'WindowButtonUpFcn',     WindowButtonUpFcn_bak);
        set(hNewFig, 'ResizeFcn',             ResizeFcn_bak);
        if isprop(hNewFig, 'KeyReleaseFcn')
            set(hNewFig, 'KeyReleaseFcn', []);
        end
        if isprop(hNewFig, 'WindowScrollWheelFcn')
            set(hNewFig, 'WindowScrollWheelFcn', WindowScrollWheelFcn_bak);
        end
        % Copy appdata
        AppData = getappdata(hFig);
        fields = fieldnames(AppData);
        for i = 1:length(fields)
            setappdata(hNewFig, fields{i}, AppData.(fields{i}));
        end
        % Reposition figure
        set(hNewFig, 'Position', get(hNewFig, 'Position') - [0, 70, 0, 0]);
    % Save figure
    else
        saveas(hFig, imgFile, 'fig');
    end

    % === RESTORE FIGURE ===
    % Restore common callbacks
    set(hFig, 'CloseRequestFcn', CloseRequestFcn_bak);
    set(hFig, 'KeyPressFcn',     KeyPressFcn_bak);
    if isprop(hFig, 'KeyReleaseFcn')
        set(hFig, 'KeyReleaseFcn', KeyReleaseFcn_bak);
    end
    % Restore colobar
    if ~isempty(hColorbar)
        set(hColorbar, 'ButtonDownFcn', ColorbarButton_bak);
    end
    % Restore optional callbaks
    if isRemoveCallbacks
        set(hFig, 'WindowButtonDownFcn',   WindowButtonDownFcn_bak);
        set(hFig, 'WindowButtonMotionFcn', WindowButtonMotionFcn_bak);
        set(hFig, 'WindowButtonUpFcn',     WindowButtonUpFcn_bak);
        set(hFig, 'ResizeFcn',             ResizeFcn_bak);
        if isprop(hFig, 'WindowScrollWheelFcn')
            set(hFig, 'WindowScrollWheelFcn',  WindowScrollWheelFcn_bak);
        end
    end
    % Remove figure toolbar
    set(hFig, 'MenuBar', 'none', 'ToolBar', 'none');

% ===== SAVE IMAGE =====
else
    % If figure contains a video in an ActiveX control: must be extracted with screencapture()
    isForceScreencapture = ~isempty(FigureId) && strcmpi(FigureId.Type, 'Video') && ~isempty(iDS) && ismember(GlobalData.DataSet(iDS).Figure(iFig).Handles.PlayerType, {'VLC', 'WMPlayer'});
    % Headless display: we must print the figure
    if (GlobalData.Program.GuiLevel == -1)
        frameGfx.cdata = print(hFig, '-noui', '-r0', '-RGBImage');
    % Get figure bitmap
    elseif (bst_get('MatlabVersion') >= 804) && ~isForceScreencapture
        % Matlab function getframe() was finally fixed in R2014b
        frameGfx = getframe(hFig);
        % MRI Viewer: We need to update the figure to redraw all the java objects
        if ~isempty(FigureId) && strcmpi(FigureId.Type, 'MriViewer')
            figure_mri('ResizeCallback', hFig);
        end
    else
        % frameGfx = getscreen(hFig);
        figPos = get(hFig, 'Position');
        decoSize = bst_get('DecorationSize');
        % Get the screen definition
        ScreenDef = bst_get('ScreenDef');
        % Single screen (TODO: Handle the cases where the two screens are organized in different ways)
        if (length(ScreenDef) == 1)
            ZoomFactor = ScreenDef(1).zoomFactor;
        elseif (figPos(1) < ScreenDef(1).matlabPos(1) + ScreenDef(1).matlabPos(3))
            ZoomFactor = ScreenDef(1).zoomFactor;
        else
            ZoomFactor = ScreenDef(2).zoomFactor;
        end
        % Altman's screencapture doesn't work with ZoomFactor higher than 1
        if (ZoomFactor > 1.01)
            figFix   = round(figPos .* ZoomFactor);
            decoSize = round(decoSize .* ZoomFactor);
            capturePos = [figFix(1) - figPos(1) + decoSize(1), ...
                          -figFix(4) + figPos(4) + decoSize(4), ...
                          figFix(3) - decoSize(3) + 1, ...
                          figFix(4) - decoSize(4)];
        else
            capturePos = [decoSize(1), ...
                          decoSize(4), ...
                          figPos(3), ...
                          figPos(4)];
        end
        % Capture figure
        frameGfx.cdata = screencapture(hFig, capturePos);
    end
    % Save image file or return it in argument
    if (nargout == 0) && ~isempty(imgFile)
        if strcmpi(imgFile, 'Viewer')
            view_image(frameGfx.cdata);
        else
            out_image(imgFile, frameGfx.cdata);
        end
    else
        varargout{1} = frameGfx.cdata;
    end
end

%% ===== RESTORE IMAGE ======
% Delete created label
if ~isempty(imgLegend)
    delete(hAxesLabel);
end
% Show the buttons again
if ~isempty(hButtons)
    for i = 1:length(hButtons)
        set(hButtons(i), 'Visible', isVisible{i});
    end
end

author: brainstorm-tools