text:
function lebesgue_test02 ( )

%*****************************************************************************80
%
%% LEBESGUE_TEST02 looks at Chebyshev2 points.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 January 2015
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LEBESGUE_TEST02:\n' );
  fprintf ( 1, '  Analyze Chebyshev2 points.\n' );

  n_max = 11;
  l = zeros ( n_max, 1 );
  xfun = linspace ( -1.0, +1.0, 501 );
  xfun = xfun';

  for n = 1 : n_max
    x = chebyshev2 ( n );
    l(n) = lebesgue_constant ( n, x, xfun );
  end

  r8vec_print ( n_max, l, '  Chebyshev2 Lebesgue constants for N = 1 to 11:' )
%
%  Examine one case more closely.
%
  n = 11;
  x = chebyshev2 ( n );
  r8vec_print ( n, x, '  Chebyshev2 points for N = 11' );

  label = 'Chebyshev2 points for N = 11';
  filename = 'chebyshev2.png';
  lebesgue_plot ( n, x, xfun, label, filename );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Plot file saved as "%s"\n', filename );

  return
end


text:
function RGB = ImageToRGB(im,cmap,minlim,maxlim)
L = size(cmap,1);
ix = round(interp1(linspace(minlim,maxlim,L),1:L,im,'linear','extrap'));
RGB = reshape(cmap(ix,:),[size(ix) 3]); % Make RGB image from scaled.
end

author: xiuyechen

repo: FishExplorer


text:
function outMesh = state2mesh(state)
% Use original triangulation and smooth to construct mesh from deformed point cloud
    S = state.S;
    verts = state.transform3d(S);
    newVerts =  smoothMesh(state.tri,verts,2);
    newVerts(:,3) = newVerts(:,3) - mean(newVerts(:,3));
    outMesh.vertices = newVerts;
    outMesh.faces = state.tri;
end

repo: CategoryShapes


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

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

% Last Modified by GUIDE v2.5 09-Jul-2012 15:10:21

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

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = infogram_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 during object creation, after setting all properties.
function axes1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to axes1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: place code in OpeningFcn to populate axes1
axes (hObject);
imshow('infogram.jpg');

author: Sable

repo: mcbench-benchmarks


text:
function [data, stamps, f] = fmf_read( filename, f_start, nframes, incr, show_progress )
% [data, stamps, f] = fmf_read( filename, f_start, nframes, incr, show_progress )
%
% reads FlyMovieFormat data from FILENAME
%
% starts with frame F_START (1-based) [defaults to 1], reads NFRAMES [defaults to inf]
%
% DATA is HxWxNFRAMES where H and W are the height and width of a
% frame STAMPS are the timestamps for each frame, double format F is
% the number of frames actually read
%
% JAB 6/30/04

CHUNKSIZE = 200;

if nargin < 5, show_progress = 0; end
if nargin < 4, incr = 1; end;
if nargin < 3, nframes = inf; end
if nargin < 2, f_start = 1; end

[header_size, version, h, w, bytes_per_chunk, max_n_frames, data_format] = ...
    fmf_read_header( filename );
if( nframes ~= inf && (nframes-1)*incr + f_start > max_n_frames ),
  nframes = floor( (max_n_frames - f_start)/incr + 1);
  warning( sprintf( 'not enough frames in file -- returning %d frames', nframes ) );
elseif nframes == inf,
  nframes = max_n_frames - f_start + 1;
end

datatype = fmf_get_datatype(data_format);
if isinf(nframes),
  % allocate one chunk at a time
  data = zeros( h, w, CHUNKSIZE, datatype );
  stamps = zeros(1,CHUNKSIZE);
else,
  data = zeros( h, w, nframes, datatype );
  stamps = zeros( 1, nframes );
end;
% read frames
fp = fopen( filename, 'r' );
fseek( fp, header_size, 'bof' );
% skip the first f_start - 1 frames
fseek( fp, bytes_per_chunk*(f_start-1), 'cof' );
% add wait bar
if show_progress
 bar_handle = waitbar(0,'Please wait...');
end
seekfailed = 0;
for f=1:nframes,
  if show_progress & ~isinf(nframes),
    waitbar(f/nframes, bar_handle)
  end
  % do we need to allocate more memory?
  if f > size(data,3),
    data = cat(3,data,zeros(h,w,CHUNKSIZE,datatype));
    stamps = cat(2,stamps,zeros(1,CHUNKSIZE));
  end;

  [data(:,:,f), stamps(f)] = fmf_read_frame( fp, h, w, ...
					     bytes_per_chunk, data_format );
  % were we unable to read frame f?
  if stamps(f) == 9e9,
    warning( sprintf( 'not enough frames in file -- returning %d frames', f-1 ) );
    % return data we've read up until now
    data = data(:,:,1:f-1);
    stamps = stamps(1:f-1);
    break;
  end;

  % skip incr-1 frames
  if f < nframes,
    seekfailed = fseek(fp,(incr-1)*bytes_per_chunk,'cof');
    % stop seeking when we can't seek anymore
    if seekfailed ~= 0,
      break;
    end;
  end;
  % if we've reached the end of the file, return the data we've
  % read up until now.
  if seekfailed~=0,
    data = data(:,:,1:f);
    stamps = stamps(1:f);
    break;
  end;
end
fclose( fp );

if show_progress & ~isinf(nframes),
  close(bar_handle)
end

author: kristinbranson

repo: JAABA


text:
function H = mldivide(C, F)
%\   SPHEREFUNV left divide.
%   C\F Divides each component of the SPHEREFUNV F by the DOUBLE C.
%
%   Only allowed to divide a SPHEREFUNV by a DOUBLE.
%
% See also SPHEREFUNV/MRDIVIDE.

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

if ( isempty(C) || isempty(F) )
    H = spherefunv;
    return
end

if ( ~isa(C, 'double') )
    error('SPHEREFUN:SPHEREFUNV:mldivide:nonScalar', ...
        'Division must be by a scalar.');
end

% Left divide.
H = F;
for j = 1 : 3
    H.components{j} = mldivide(C, F.components{j});
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function r = introw(n, dom)
%INTROW     One row of spectral integration matrix.
%   INTROW(N) returns the last row of INTMAT(N), i.e.,
%         a row vector of N Clenshaw-Curtis quadrature coefficients.
%   INTROW(N, DOM) returns the last row of INTMAT(N, DOM), i.e.,
%         Clenshaw-Curtis coefficients scaled to the interval DOM.
%
% More general functionality, such as higher-order integrals
% or trigonometric quadrature, has not yet been implemented.
%
% See also DIFFMAT, DIFFROW, INTMAT.

% This code has been written for Aurentz and Trefethen,
% "Block operators and spectral discretizations", and is not
% yet fully compliant with standard Chebfun coding practices.

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

if ( nargin == 1 )
    dom = [-1 1];
end

[~,r] = chebpts(n,dom);

end


text:
function [ x, seed ] = fisk_sample ( a, b, c, seed )

%*****************************************************************************80
%
%% FISK_SAMPLE samples the Fisk PDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 October 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real A, B, C, the parameters of the PDF.
%    0.0 < B,
%    0.0 < C.
%
%    Input, integer SEED, a seed for the random number generator.
%
%    Output, real X, a sample of the PDF.
%
%    Output, integer SEED, an updated seed for the random number generator.
%
  [ cdf, seed ] = r8_uniform_01 ( seed );

  x = fisk_cdf_inv ( cdf, a, b, c );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
%if exist('images_read');
%   active_images = active_images & images_read;
%end;

var2fix = 'dX_default';

fixvariable;

var2fix = 'dY_default';

fixvariable;

var2fix = 'map';

fixvariable;

if ~exist('n_ima'),
    data_calib_no_read;
end;

check_active_images;

%if ~exist(['I_' num2str(ind_active(1))]),
%    ima_read_calib;
%    if isempty(ind_read),
%        disp('Cannot extract corners without images');
%        return;
%    end;
%end;

%% Step used to clean the memory if a previous atttempt has been made to read the entire set of images into memory:
for kk = 1:n_ima,
    if (exist(['I_' num2str(kk)])==1),
        clear(['I_' num2str(kk)]);
    end;
end;

fprintf(1,'\nExtraction of the grid corners on the images\n');

if (exist('map')~=1), map = gray(256); end;

%disp('WARNING!!! Do not forget to change dX_default and dY_default in click_calib.m!!!')

if exist('dX'),
    dX_default = dX;
end;

if exist('dY'),
    dY_default = dY;
end;

if exist('n_sq_x'),
    n_sq_x_default = n_sq_x;
end;

if exist('n_sq_y'),
    n_sq_y_default = n_sq_y;
end;

if ~exist('dX_default')|~exist('dY_default');

    % Setup of JY - 3D calibration rig at Intel (new at Intel) - use units in mm to match Zhang
    dX_default = 30;
    dY_default = 30;

end;

if ~exist('n_sq_x_default')|~exist('n_sq_y_default'),
    n_sq_x_default = 10;
    n_sq_y_default = 10;
end;

if ~exist('wintx_default')|~exist('winty_default'),
    if ~exist('nx'),
        wintx_default = 5;
        winty_default = wintx_default;
        clear wintx winty
    else
        wintx_default = max(round(nx/128),round(ny/96));
        winty_default = wintx_default;
        clear wintx winty
    end;
end;

if ~exist('wintx') | ~exist('winty'),
    clear_windows; % Clear all the window sizes (to re-initiate)
end;

if ~exist('dont_ask'),
    dont_ask = 0;
end;

if ~dont_ask,
    ima_numbers = input('Number(s) of image(s) to process ([] = all images) = ');
else
    ima_numbers = [];
end;

if isempty(ima_numbers),
    ima_proc = 1:n_ima;
else
    ima_proc = ima_numbers;
end;

% Useful option to add images:
kk_first = ima_proc(1); %input('Start image number ([]=1=first): ');

%if isempty(kk_first), kk_first = 1; end;

if exist(['wintx_' num2str(kk_first)]),

    eval(['wintxkk = wintx_' num2str(kk_first) ';']);

    if isempty(wintxkk) | isnan(wintxkk),

        disp('Window size for corner finder (wintx and winty):');
        wintx = input(['wintx ([] = ' num2str(wintx_default) ') = ']);
        if isempty(wintx), wintx = wintx_default; end;
        wintx = round(wintx);
        winty = input(['winty ([] = ' num2str(winty_default) ') = ']);
        if isempty(winty), winty = winty_default; end;
        winty = round(winty);

        fprintf(1,'Window size = %dx%d\n',2*wintx+1,2*winty+1);

    end;

else

    disp('Window size for corner finder (wintx and winty):');
    wintx = input(['wintx ([] = ' num2str(wintx_default) ') = ']);
    if isempty(wintx), wintx = wintx_default; end;
    wintx = round(wintx);
    winty = input(['winty ([] = ' num2str(winty_default) ') = ']);
    if isempty(winty), winty = winty_default; end;
    winty = round(winty);

    fprintf(1,'Window size = %dx%d\n',2*wintx+1,2*winty+1);

end;

if ~dont_ask,
    fprintf(1,'Do you want to use the automatic square counting mechanism (0=[]=default)\n');
    manual_squares = input('  or do you always want to enter the number of squares manually (1,other)? ');
    if isempty(manual_squares),
        manual_squares = 0;
    else
        manual_squares = ~~manual_squares;
    end;
else
    manual_squares = 0;
end;

for kk = ima_proc,

    if ~type_numbering,
        number_ext =  num2str(image_numbers(kk));
    else
        number_ext = sprintf(['%.' num2str(N_slots) 'd'],image_numbers(kk));
    end;

    ima_name = [calib_name  number_ext '.' format_image];

    if exist(ima_name),

        fprintf(1,'\nProcessing image %d...\n',kk);

        fprintf(1,'Loading image %s...\n',ima_name);

        if format_image(1) == 'p',
            if format_image(2) == 'p',
                I = double(loadppm(ima_name));
            else
                I = double(loadpgm(ima_name));
            end;
        else
            if format_image(1) == 'r',
                I = readras(ima_name);
            else
                I = double(imread(ima_name));
            end;
        end;

        if size(I,3)>1,
            I = 0.299 * I(:,:,1) + 0.5870 * I(:,:,2) + 0.114 * I(:,:,3);
        end;

        [ny,nx,junk] = size(I);
        Wcal = nx; % to avoid errors later
        Hcal = ny; % to avoid errors later

        click_ima_calib_no_read;

        active_images(kk) = 1;

    else
        eval(['dX_' num2str(kk) ' = NaN;']);
        eval(['dY_' num2str(kk) ' = NaN;']);

        eval(['wintx_' num2str(kk) ' = NaN;']);
        eval(['winty_' num2str(kk) ' = NaN;']);

        eval(['x_' num2str(kk) ' = NaN*ones(2,1);']);
        eval(['X_' num2str(kk) ' = NaN*ones(3,1);']);

        eval(['n_sq_x_' num2str(kk) ' = NaN;']);
        eval(['n_sq_y_' num2str(kk) ' = NaN;']);
    end;
end;

check_active_images;

% Fix potential non-existing variables:

for kk = 1:n_ima,
    if ~exist(['x_' num2str(kk)]),
        eval(['dX_' num2str(kk) ' = NaN;']);
        eval(['dY_' num2str(kk) ' = NaN;']);

        eval(['x_' num2str(kk) ' = NaN*ones(2,1);']);
        eval(['X_' num2str(kk) ' = NaN*ones(3,1);']);

        eval(['n_sq_x_' num2str(kk) ' = NaN;']);
        eval(['n_sq_y_' num2str(kk) ' = NaN;']);
    end;

    if ~exist(['wintx_' num2str(kk)]) | ~exist(['winty_' num2str(kk)]),

        eval(['wintx_' num2str(kk) ' = NaN;']);
        eval(['winty_' num2str(kk) ' = NaN;']);

    end;
end;

string_save = 'save calib_data active_images ind_active wintx winty n_ima type_numbering N_slots first_num image_numbers format_image calib_name Hcal Wcal nx ny map dX_default dY_default dX dY';

for kk = 1:n_ima,
    string_save = [string_save ' X_' num2str(kk) ' x_' num2str(kk) ' n_sq_x_' num2str(kk) ' n_sq_y_' num2str(kk) ' wintx_' num2str(kk) ' winty_' num2str(kk) ' dX_' num2str(kk) ' dY_' num2str(kk)];
end;

eval(string_save);

disp('done');

repo: ekfmonoslam


text:
function SimResults = Ch4Ex4_main()
%% Global Adaptive Dynamic Programming for an inverted pendulum
%
% System requirements:
%
% - MATLAB (Manually Tested in MATLAB R2014b)
%
% - MATLAB Symbolic Toolbox
%
% - CVX (free to download at http://cvxr.com/cvx/)
%
%    You can download CVX along with the examples, unzip tools.zip to
%    the root level folder of the examples. Then, run the following
%
%     >> run('.\tools\cvx-w64\cvx\cvx_setup.m')
%
%     >> run('.\tools\cvx-w64\cvx\cvx_startup.m')
%
%
% Copyright 2015 Yu Jiang
%
% Contact: yu.jiang@nyu.edu (Yu Jiang)

SimResults = [];
k = 1;
m = 1;   % Mass of the pendulum
l = 1;   % Length of the pendulum
g = 9.8; % Gravity accelaration rate
Params.F = [0    1     0  ;   0   -k*l/m g ];
Params.G = [0; 1/m];
Params.Q = diag([10 10 0]);   % Weighting matrix
Params.R = 1;                 % Weighting matrix
Params.Noise = 1;
x = [-1.5 1];       % Initial Contidition;
Params.x0 = x;

K = [-10 -1 -15];   % Initial Feedback gains
Psave = [];
Ksave = K;
xsave = [];
tsave = [];

T = 0.01;            % Length of time interval for data collection
P_old = 1000*eye(2); % Initializing the previous Value function
P = 0.9*P_old;       % Initialize the current Value function
c = [1 0 1];         % Coefficient for SOS policy iteration

NumDataIntv  = 50;
Iter = 0;
Tol = 0.1;
while norm(P_old - P)> Tol
    P_old = P;
    % Online Simulation for Data collection
    Theta = []; Xi = []; Phi = [];  % Data matrices
    for IterIntv = 0:NumDataIntv - 1
        [t,x] = ode45(@(t,x) LocalInvertedPendulumSysWrapper(t,x,K,Params), ...
            ([IterIntv, IterIntv + 1] + NumDataIntv * Iter) * T,...
            [x(end,1:2) zeros(1,10)]);
        Theta = [Theta; x(end,1)^2-x(1,1)^2 x(end,1)*x(end,2)-x(1,1)*x(1,2) x(end,2)^2-x(1,2)^2];
        Phi = [Phi; x(end,3:8) -2*x(end,9:11)];
        Xi = [Xi; x(end,12)];
        xsave = [xsave; x(:,1:2)];
        tsave = [tsave;t];
    end

    % Online SOSp based policy iteration
    [P,K] = LocalOnlinePolicyIteration(Theta,Xi,Phi,P_old,c);

    % Save results
    Psave = [Psave; P(:)'];
    Ksave = [Ksave; K(:)'];
    Iter = Iter + 1;
end
Params.Noise = 0;

% Post learning simulation
[t,x] = ode45(@(t,x) LocalInvertedPendulumSysWrapper(t,x,K,Params), ...
    [tsave(end) 5],[x(end,1:2) zeros(1,10)]');
xsave = [xsave; x(:,1:2)];
tsave = [tsave;t];

% Create Simulation output data
SimResults.xsave = xsave;
SimResults.tsave = tsave;
SimResults.Psave = Psave;
SimResults.Ksave = Ksave;
SimResults.P = P;
SimResults.Iter = Iter;

% Plot results
LocalPostProcessData(Params,SimResults);
end

%% LocalOnlinePolicyIteration: Implement online SOS policy iteration
function [P,K] = LocalOnlinePolicyIteration(Theta,Xi,Phi,P_old,c)
cvx_begin sdp
variables p(3,1)
variables bt r1 r2  r3 r4  r5 r6
% Objective of the SDP
minimize(c*p)

% 1) Equality constraint to calculate L and K
LandK = pinv(Phi)*(Xi + Theta*p);

% 2) Inequality constraint
L = LandK(1:6);
dFGQR = [L(1)   L(2)/2 L(4)/2;
    L(2)/2 L(3)   L(5)/2;
    L(4)/2 L(5)/2 L(6)];
O = [0 0 bt;
    0 0 0;
    bt 0 0];
bt>=0;
gamma1 = [r1 0 r2/2; 0  0  0; r2/2 0 0];
gamma2 = [r3 0 0; 0  0  0; 0 0 r4];
gamma3 = [0 0 r5/2; 0  0  0; r5/2 0 r6];
r1 >= 0;
r3 >= 0;
r5 >= 0;
r1+r2 >= 0;
r3+r4 >= 0;
r5+r6 >= 0;
dFGQR + O + gamma1 + gamma2 + gamma3 <= 0;

% 3) Inequality constraint
P = [p(1) p(2)/2;
    p(2)/2 p(3)];
P_old - P >= 0;
cvx_end;

K = LandK(7:9)';
end

%% invertedPendulumSys: Inverted Pendulum System Dynamics
function dx = LocalInvertedPendulumSys(x,K,Params)
u = K * LocalSigma(x);
dx = Params.F * LocalSigma(x) + Params.G * u;
end

%% LocalInvertedPendulumSysWrapper:
% Inverted Pendulum System Dynamics with external states for learning purpose
function dx = LocalInvertedPendulumSysWrapper(t,x,K,Params)
 x1 = x(1);
 x2 = x(2);
 sgm  =  [x1;x2;sin(x1)];

 e  = LocalExplNoise(t) * Params.Noise;
 u  = K * sgm+e;
 dx = Params.F * sgm + Params.G * u;

 dZ  =  [x1*x1 x2*x1 x2*x2 x1*sin(x1) x2*sin(x1) sin(x1)^2]';
 deZ = sgm*e;

 Qk  = Params.Q + K'*Params.R*K;
 dQ  = sgm' * Qk * sgm;
 dx  = [dx;  %2
        dZ;  %6
        deZ; %3
        dQ;  %1
        ]; %12
end

%% LocalSigma: Basic function for the plant
function y = LocalSigma(x)
 y = [x(1) x(2) sin(x(1))]';
end

%% LocalExplNoise: Generate exploration noise
function e = LocalExplNoise(t)
e = sin(10*t) + sin(3*t) + sin(50*t) - sin(10*t) + sin(0.7*t) - sin(100*t);
end

%% LocalPostProcessData - Plot results after all simulation is finished
function LocalPostProcessData(Params,SimResults)
tsave = SimResults.tsave;
xsave = SimResults.xsave;
Ksave = SimResults.Ksave;
Psave = SimResults.Psave;
P = SimResults.P;
x1 = -2:0.2:2;
x2 = -5:0.5:5;
vn = zeros(length(x1),length(x2));
v1 = zeros(length(x1),length(x2));
P1 = [Psave(1,1) Psave(1,2);Psave(1,3) Psave(1,4)] ;
for i=1:length(x1)
    for j=1:length(x2)
        vn(i,j)=[x1(i) x2(j)]*P*[x1(i) x2(j)]';
        v1(i,j)=[x1(i) x2(j)]*P1*[x1(i) x2(j)]';
    end
end
figure(1)
surf(x1,x2,vn')
hold on
surf(x1,x2,v1')
hold off
xlabel('x_1')
ylabel('x_2')

K = Ksave(1,:);[t1,y1]=ode45(@(t,x) LocalInvertedPendulumSys(x,K,Params), ...
    [0 5],Params.x0);
%%
figure(2)
subplot(211)
plot(tsave,xsave(:,1),'b-',t1,y1(:,1),'r-.','Linewidth',2)
axis([0 5 -2 2])
ylabel('x_1')
xlabel('time (sec)')
legend('With GADP-based controller','With initial controller')
subplot(212)
plot(tsave,xsave(:,2),'b-',t1,y1(:,2),'r-.','Linewidth',2)
axis([0 5 -4 6])
legend('With GADP-based controller','With initial controller')
ylabel('x_2')
xlabel('time (sec)')
end

author: yu-jiang

repo: radpbook

save_path: github-repos/MATLAB/yu-jiang-radpbook


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


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