text:
function test_bug168

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_realtime_topography

[ftver, ftpath] = ft_version;
cd(ftpath);

% ensure that these compat folders are presaent on the path
% although they should not be used
ft_hastoolbox('COMPAT', 2);
ft_hastoolbox('UTILITIES/COMPAT', 2);
ft_hastoolbox('FILEIO/COMPAT', 2);
ft_hastoolbox('PREPROC/COMPAT', 2);
ft_hastoolbox('FORWARD/COMPAT', 2);
ft_hastoolbox('PLOTTING/COMPAT', 2);

% this list was compiled on 1 May 2012 from the fieldtrip/realtime directory
% functions that will be added future don't have to be tested persee
inlist = {
  'acquisition/matlab/ft_realtime_asaproxy.m'
  'acquisition/matlab/ft_realtime_brainampproxy.m'
  'acquisition/matlab/ft_realtime_ctfproxy.m'
  'acquisition/matlab/ft_realtime_dicomproxy.m'
  'acquisition/matlab/ft_realtime_fileproxy.m'
  'acquisition/matlab/ft_realtime_fmriproxy.m'
  'acquisition/matlab/ft_realtime_neuralynxproxy.m'
  'acquisition/matlab/ft_realtime_pooraudioproxy.m'
  'acquisition/matlab/ft_realtime_signalproxy.m'
  'acquisition/matlab/private/encode_nifti1.m'
  'acquisition/matlab/private/tcpread.m'
  'acquisition/siemens/compile.m'
  'acquisition/siemens/matlab/replay_dicoms.m'
  'buffer/matlab/buffer.m'
  'buffer/matlab/compile.m'
  'example/ft_realtime_average.m'
  'example/ft_realtime_benchmark.m'
  'example/ft_realtime_classification.m'
  'example/ft_realtime_downsample.m'
  'example/ft_realtime_fmriviewer.m'
  'example/ft_realtime_heartratemonitor.m'
  'example/ft_realtime_packettimer.m'
  'example/ft_realtime_powerestimate.m'
  'example/ft_realtime_selectiveaverage.m'
  'example/ft_realtime_signalviewer.m'
  'example/ft_realtime_topography.m'
  'online_eeg/ft_realtime_oddball.m'
  'online_eeg/ft_realtime_ouunpod.m'
  'online_eeg/private/compile_midiOut.m'
  'online_eeg/private/controlfunction.m'
  'online_eeg/private/midiOut.m'
  'online_meg/ft_realtime_coillocalizer.m'
  'online_meg/ft_realtime_headlocalizer.m'
  'online_mri/ft_omri_align_init.m'
  'online_mri/ft_omri_align_scan.m'
  'online_mri/ft_omri_info_from_header.m'
  'online_mri/ft_omri_pipeline.m'
  'online_mri/ft_omri_pipeline_nuisance.m'
  'online_mri/ft_omri_quality.m'
  'online_mri/ft_omri_quality_plot.m'
  'online_mri/ft_omri_slice_time_apply.m'
  'online_mri/ft_omri_slice_time_init.m'
  'online_mri/ft_omri_smoothing_kernel.m'
  'online_mri/ft_omri_volume_to_mosaic.m'
  'online_mri/private/coords.m'
  'online_mri/private/encode_nifti1.m'
  'online_mri/private/hom2six.m'
  'online_mri/private/kspace3d.m'
  'online_mri/private/make_A.m'
  'online_mri/private/reslice_vol.m'
  'online_mri/private/rls_init.m'
  'online_mri/private/rls_predict.m'
  'online_mri/private/rls_update.m'
  'online_mri/private/shear_decomp.m'
  'online_mri/private/smooth_vol.m'
  'tutorial/bcifun_latidx.m'
  'tutorial/ft_realtime_asynchronous.m'
  'tutorial/ft_realtime_synchronous.m'
  };

[outlist, depmat] = mydepfun(inlist);

problem = ~cellfun(@isempty, regexp(outlist, 'compat/obsolete'));
problem = outlist(problem)  % display the output;

if ~isempty(problem)
  error('there are some files that depend on the compat functions');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this was the version of the test script prior to 1 May 2012
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% if isempty(which('ft_realtime_topography'))
%   addpath(fullfile(fileparts(which('ft_defaults')), 'realtime/example'));
% end
%
% cfg = [];
% cfg.dataset = dccnpath('/home/common/matlab/fieldtrip/data/ftp/test/ctf/Subject01.ds');
% cfg.bufferdata = 'first';
% cfg.layout = 'CTF151.lay';
%
% ft_realtime_topography(cfg);


text:
function [xo,yo,ind] = polybool(x1,y1,x2,y2,flag,flag2)
% POLYBOOL Boolean operations on polygons.
%	[XO,YO] = POLYBOOL(X1,Y1,X2,Y2,FLAG)
%	calulates results of Boolean operations on
%	a pair of polygons.
%	FLAG Specifies the type of the operation:
%	1 - Intersection (P1 & P2)
%	2 - Union (P1 | P2)
%	3 - Difference (P1 & ~P2)

%  Copyright (c) 1995 by Kirill K. Pankratov,
%       kirill@plume.mit.edu.
%       06/25/95, 09/07/95

%	This program calls the following functions:
%	AREA, ISINTPL, ISCROSS, INTSECL.

% Algorithm:
%  1. Check boundary contour directions (area).
%     For intersection and union make all
%     counter-clockwise. For difference make the second
%    contour clock-wise.
%  2. Calculate matrix of intersections (function ISINTPL).
%     Quick exit if no intersections.
%  3. For intersecting segments calculate intersection
%     coordinates (function INTSECL).
%  4. Sort intersections along both contours.
%  5. Calculate sign of cross-product between intersectiong
%     segments. This will give which contour goes "in" and
%     "out" at intersections.
%
%  6. Start with first intersection:
%     Determine direction to go ("in" for intersection,
%     "out" for union).
%     Move until next intersection, switch polygons at each
%     intersection until coming to the initial point.
%     If not all intersections are encountered, the
%     resulting polygon is disjoint. Separate output
%     coordinates by NaN and repeat procedure until all
%     intersections are counted.
xo=[];yo=[];ind=[];
% Default for flag
flag_dflt = 1; % 1- intersec., 2-union, 3 - diff.
if ~exist('flag2','var')
flag2=1;
end
% Handle input
if nargin==0, help polybool, return, end
if nargin < 4
    error(' Not enough input arguments')
end
if nargin<5, flag = flag_dflt; end

x1 = x1(:); y1 = y1(:);
x2 = x2(:); y2 = y2(:);
l1 = length(x1);
l2 = length(x2);

%  % Check areas and reverse if negative
% nn1 = area(x1,y1);
% if nn1<0, x1 = flipud(x1); y1 = flipud(y1); end
% nn2 = area(x2,y2);
% if (nn2<0 & flag<3) | (nn2>0 & flag==3)
%   x2 = flipud(x2); y2 = flipud(y2);
% end

% Check areas and reverse if negative
x_temp = [x1;x1(1)]; y_temp = [y1;y1(1)];
nn1 = (sum(x_temp(1:end-1).*y_temp(2:end))...
    -sum(x_temp(2:end).*y_temp(1:end-1)))/2;
if nn1<0, x1 = flipud(x1); y1 = flipud(y1); end
x_temp = [x2;x2(1)]; y_temp = [y2;y2(1)];
nn2 = (sum(x_temp(1:end-1).*y_temp(2:end))...
    -sum(x_temp(2:end).*y_temp(1:end-1)))/2;
if (nn2<0 && flag<3) | (nn2>0 && flag==3)
    x2 = flipud(x2); y2 = flipud(y2);
end

% If both polygons are identical ........
if l1==l2
    if all(x1==x2) && all(y1==y2)
        if flag<3, xo = x1; yo = y1; ind = 1:l1;
        else, xo = []; yo = []; ind = []; end
        return
    end
end

% Calculate matrix of intersections .....
[is,C] = isintpl(x1,y1,x2,y2);
is = any(any(C));

% Quick exit if no intersections ........
if ~is
    if flag==1       % Intersection
        xo=[]; yo = [];
    elseif flag==2   % Union
        xo = [x1; nan; x2];
        yo = [y1; nan; y2];
    elseif flag==3   % Difference
        xo = x1; yo = y1;
    end
    return
end

% Mark intersections with unique numbers
i1 = find(C);
ni = length(i1);
C(i1) = 1:ni;

% Close polygon contours
x1 = [x1; x1(1)]; y1 = [y1; y1(1)];
x2 = [x2; x2(1)]; y2 = [y2; y2(1)];
l1 = length(x1);  l2 = length(x2);

% Calculate intersections themselves
[i1,i2,id] = find(C);
xs1 = [x1(i1) x1(i1+1)]'; ys1 = [y1(i1) y1(i1+1)]';
xs2 = [x2(i2) x2(i2+1)]'; ys2 = [y2(i2) y2(i2+1)]';

% Call INTSECL ............................
[xint,yint] = intsecl(xs1,ys1,xs2,ys2);

% For sements belonging to the same line
% find interval of intersection ...........
ii = find(xint==inf);
if length(ii)~=0
    [is,inx] = interval(xs1(:,ii),xs2(:,ii));
    [is,iny] = interval(ys1(:,ii),ys2(:,ii));
    xint(ii) = mean(inx);
    yint(ii) = mean(iny);
end

% Coordinate differences of intersecting segments
xs1 = diff(xs1); ys1 = diff(ys1);
xs2 = diff(xs2); ys2 = diff(ys2);

% Calculate cross-products
cp = xs1.*ys2-xs2.*ys1;
cp = cp>0;
if flag==2, cp=~cp; end % Reverse if union
cp(ii) = 2*ones(size(ii));

% Sort intersections along the contours
ind = (xint-x1(i1)').^2+(yint-y1(i1)').^2;
ind = ind./(xs1.^2+ys1.^2);
cnd = min(ind(ind>0));
ind = ind+i1'+i2'/(ni+1)*cnd*0;
[xo,ii] = sort(ind);
xs1 = id(ii);
[xo,ind] = sort(xs1);
ind = rem(ind,ni)+1;
xs1 = xs1(ind);

ind = (xint-x2(i2)').^2+(yint-y2(i2)').^2;
ind = ind./(xs2.^2+ys2.^2);
cnd = min(ind(ind>0));
[xo,ii] = sort(i2'+ind+i1'/(ni+1)*cnd*0);
xs2 = id(ii);
[xo,ind] = sort(xs2);
ind = rem(ind,ni)+1;
xs2 = xs2(ind);

% Combine coordinates in one vector
x1 = [x1; x2]; y1 = [y1; y2];

% Find max. possible length of a chain
xo = find(any(C'));
xo = diff([xo xo(1)+l1]);
mlen(1) = max(xo);
xo = find(any(C));
xo = diff([xo xo(1)+l2]);
mlen(2) = max(xo);

% Check if multiple intersections in one segment
xo = diff([i1 i2]);
is_1 = ~all(all(xo));

% Begin counting intersections *********************

% Initialization ..................
int = zeros(size(xint));
nn = 1;   % First intersection
nn1 = i1(nn); nn2 = i2(nn);
b = cp(nn);
is2 = b==2;
xo = []; yo = []; ind = [];
closed = 0;

% Proceed until all intersections are counted
while ~closed  % begin counting `````````````````````0

    % If contour closes, find new starting point
    if int(nn) & ~all(int)
        ii = find(int);
        C(id(ii)) = zeros(size(ii));
        nn = min(find(~int));  % Next intersection
        nn1 = i1(nn);
        nn2 = i2(nn);
        xo = [xo; nan];        % Separate by NaN
        yo = [yo; nan];
        ind = [ind; nan];
        % Choose direction ......
        b = cp(nn);
    end

    % Add current intersection ......
    xo = [xo; xint(nn)];
    yo = [yo; yint(nn)];
    ind = [ind; 0];
    int(nn) = 1;
    closed = all(int);

    % Find next segment
    % Indices for next intersection
    if ~b, if numel(xs1)>0 nn = xs1(nn); end          %%%%%%%changed here varsha
    else,  nn = xs2(nn);
    end
    if ~b, pt0 = nn1; else,  pt0 = nn2; end

    nn1 = i1(nn);
    nn2 = i2(nn);

    if b, pt = nn2; else, pt = nn1; end

    if b, pt0 = pt0+l1; pt = pt+l1; end
    ii = (pt0+1:pt);

    % Go through the beginning ..............
    cnd = pt<pt0 | (pt==pt0 & is_1 & flag>1);
    if cnd
        if ~b,  ii = [pt0+1:l1 1:pt];
        else,   ii = [pt0+1:l1+l2 l1+1:pt];
        end
    end
    len = length(ii);
    cnd = b & len>mlen(2);
    cnd = cnd | (~b & len>mlen(1));
    if is2 | cnd, ii=[]; end

    % Add new segment
    xo = [xo; x1(ii)];
    yo = [yo; y1(ii)];
    ind = [ind; ii'];

    % Switch direction
    if cp(nn)==2, b = ~b; is2 = 1;
    else, b = cp(nn); is2 = 0;
    end

end    % End while (all intersections) '''''''''''''''0

% %if you are running intersection of image with field polygons uncomment
% %this and comment below
% % Remove coincident successive points
if flag2

if sum(isnan(xo))>0 | sum(isnan(yo))>0
     xo=[];yo=[];ind=[];
     return;
 end
ii = find(~diff(xo) & ~diff(yo));
xo(ii) = []; yo(ii) = []; ind(ii) = [];

 % Remove points which are
ii = find(isnan(xo));
if length(ii)~=0
  i2 = ones(size(xo));
  ii = [ii; length(xo)+1];

  i1 = find(diff(ii)==3);
  i1 = ii(i1);
  i1 = [i1; i1+1; i1+2];
  i2(i1) = zeros(size(i1));

  i1 = find(diff(ii)==2);
  i1 = ii(i1);
  i1 = [i1; i1+1];
  i2(i1) = zeros(size(i1));

  xo = xo(i2); yo = yo(i2); ind = ind(i2);
else
%if you are running intersection with superpixels uncomment this and
%comment above
out_xo=[]; out_yo=[]; out_ind=[];
if sum(isnan(xo))>0 | sum(isnan(yo))>0

    ii=find(isnan(xo));
    ii=[0;ii;length(xo)+1];
    for i=1:numel(ii)-1
        seg_xo=xo(ii(i)+1:ii(i+1)-1);
        seg_yo=yo(ii(i)+1:ii(i+1)-1);
        seg_ind=ind(ii(i)+1:ii(i+1)-1);
        iii = find(~diff(seg_xo) & ~diff(seg_yo));
        seg_xo(iii) = []; seg_yo(iii) = []; seg_ind(iii) = [];
        if numel(seg_xo)> 2
        out_xo=[out_xo;NaN ;seg_xo];
        out_yo=[out_yo;NaN; seg_yo];
        out_ind=[out_ind;NaN ;seg_ind];
        end

    end

    xo=out_xo;
    yo=out_yo;
    ind=out_ind;
else

    ii = find(~diff(xo) & ~diff(yo));
    xo(ii) = []; yo(ii) = []; ind(ii) = []; %both polygons are convex

end
end

end

author: zouchuhang

repo: LayoutNet


text:
function [P,units] = StructDlg(struct_def,title,dflt,fig_pos,visible,present_val)
% StructDlg - A structure based definition of an input GUI. Allows for a quick and
%             convenient text based definition of a GUI
%
%   StructDlg(struct_def, title, default_values, position)
%
% StructDlg creates a modal dialog box that contains a user interface (UI) control
% for each of the struct_def fields.
% In its simple form, StructDlg serves as a structure-based alternative to INPUTDLG
% and it is a convenient method for browsing and changing structure values
% (e.g. when the structure contains parameters).
% In its advanced form, StructDlg allows for a quick and convenient text based definition
% of a GUI that may contain many styles of UI controls such as edit, popup menus,
% radio buttons, toggles and more.
%
% When StructDlg is called the GUI is created and the user can set the
% values of the different UI controls (such as edit controls, radio
% buttons, popup menus, etc.)
% When the user is satisfied with his selections, he presses an OK button which closes the GUI.
% structdlg then returns a structure with the same field names as struct_def. The value of each
% field in the returned structure contains the value of the UI control of the same name.
% The title of the dialog box may be specified by adding a second string argument.
% The dflt_P argument is a structure that contains default values for the fields' values.
% These values will override  the default values specified in struct_def.
% Note that the dflt_P argument should contain the default values ONLY, not the entire
% definition as specified in struct_def. This is useful for allowing user-specific defaults that override the
% 'factory defaults'. A 4-element position vector can be specified by
% the forth argument. Position units are given in characters.
%
% The name of each field of struct_def is the default label of the corresponding input field
% (underscores are presented as spaces). In their simple form, struct_def fields may contain numeric values
% (limited to 2D matrixes) or single line strings.
%
% S.Duration      = 10;
% S.Time_Out      = 20;
% S.Weight_Matrix = [0.3 0.4; 3.4 9.1; 10 0.4];
% S.Comment       = 'No comment';
%
% For allowing more UI control styles and options the value of each struct_def field can be set to
% a cell array of up to four elements:
%     { value/definition   labels  limits  protected_flag }
% The first element determines the type (edit, radio button, pop-up menu and more) of the control and
% its default value.
% The second element allows to override the default label (the field name). Any occurrence of an asterisk
% ('*') in the label is replaced with the field name . This is useful when you want to add a text to the
% default label. For example, '* (kHz)' will add the unit KHz to the field name.
% This field is optional and merely changes the label of the UI control.
% The empty string can be used to indicate that the default label should be used.
% The third element can be used to specify limits to legal values that can be entered by the user.
% This is useful for numerical edit fields (see below.)
% The forth element is a logical element (0/1). Setting this element to 1 causes the UI control to be
% protected (disabled). The user can right-click on that control to unprotect (enable) it.
% This is useful when you want to indicate that the user should think before changing the current
% value of the control.
% Below are detailed examples of how to create all the styles and types of controls that structdlg supports.
%
% See also .\ref\StructDlg.html for more details
%
%     Numeric values: Limited to 2D matrixes of any size (including the empty matrix).
%                     The default value can be a numeric vector, or a string that is a valid Matlab
%                     expression, which its evaluation result is a numeric 2D matrix.
%                     In the later case, you must specify the limits ([] is equivalent to [-Inf Inf]),
%                     so 'StructDlg' will interpret the field as a numeric field.
%           Examples: S.center_frequency = { 2000 '* (Hz)' [30 50000] }; -> default of 2000, allowed range:[30 50000].
%                     S.my_parameter     = { [43 3 ; 56 12] } -> 2x2 matrix, no limits.
%                     S.size_of_matrix   = { [4 12] '' [1 Inf] }; -> default of [4 12], allowed range:[1 Inf].
%               Note: The values the user enters to the dialog box for numeric fields are being 'eval'-uated,
%                     so inputs such as (sin(0.34)+2)^my_func(34.2) or zeros(3,3) are possible.
%                     The field's numeric limits can be displayed by placing the mouse over the field.
%                     Numeric values may be also defined using the short notation:
%                     S.my_parameter     = 5;     default of 5, no limits.
%
%       Free Strings: Limited to one line string (no string arrays). If no default is required, use the
%                     empty string (''), otherwise the field will be treated as numeric.
%                     Strings can be also defined using the short notation:
%                     S.name             = '';
%
% List of Strings(1): One string that contain all the options, separated by '|'. The options will be
%                     presented as a radio buttons. The string that the user chooses will become the value
%                     of that field in P. A Default option can be specified by enclosing it with curly brackets.
%                     The chosen string is converted to numeric values if possible.
%            Example: S.colormap = {'hsv|{gray}|hot|bone|pink'};
%                   : S.Sampling_rate = {'11500|22000|{44000}' '* (Hz)'};
%
% List of Strings(2): One Cell-array of single strings. The options will be presented in a pop-up menu.
%                     The chosen option will be the value of that field in P. A default option can be
%                     specified by enclosing it with curly brackets. The chosen string is converted
%                     to numeric values if possible.
%           Examples: S.Sampling_frequency = { {'12207' '24414' '48828' '{97656}'} , '* (Hz)'};
%                     S.Filter_type = { {'bartlett' 'blackman' '{chebwin}' 'hamming'} };
%
%      Boolean (0/1): The value of the S field must be in the form: {'0' '1'}. A default value may be
%                     specified by the curly brackets.
%            Example: S.use_filter = { {'0','{1}'} };
%
%  File Name Dialogs: The value of the S field is a cell of one string that
%                     must start with 'uigetfile', 'uiputfile' or 'uigetdir'.
%                     The getfile/dir commands may be followed the arguments
%                     allowed by the Matlab command (see help UIGETFILE,
%                     UIPUTFILE and UIGETDIR for more details).
%                     a search filter enclosed by brackets. The user will be able to specify the file
%                     name directly by typing it,or to push a small pushbutton that will pop-up
%                     Matlab's uigetfile, uipufile or uigetdir.
%            Example: S.parameters_file = { {'uigetfile(''d:\my_dir\*.m'')'} };
%                     S.parameters_file = { ...
%                     {'uigetfile({''*.m'';''*.mat'';''*.*''},''File Selector'',''MultiSelect'', ''on'')'}};
%
%      Sub-Structure: S may contain substructures of the same format. The user will be able to push a
%                     push-button that will call 'StructDlg' recursively for the sub-structure.
%                     The current values of the sub-structure can be viewed by placing the mouse over
%                     the push-button.
%
%   Dependent Fields: (For numeric fields only) A numeric field may include a reference to the value of
%                     another numeric fields. This is done using a reserved word 'this' to refer to the
%                     structure.
%            Example: S.Window_size       = { 512 '' [10 1000] };
%                     S.Overlap           = {'this.Window_size / 2' '' [0 Inf]}; -> Note that
%                     a non-empty limits indicator is needed in order to indicate that this is a numeric field.
%
%              Notes: The value of the dependent field will be automatically updated when the values
%                     of the referenced fields changes. The automatically changed value will blink twice
%                     to alert the user. The user is then able to undo the automatic change using the
%                     mouse's right-click.
%                     It is not possible for a sub-structure field to reference fields in other sub-structures,
%                     or in other structure levels. It is possible for a field to reference fields in
%                     sub-structures of lower levels; however, this is highly not recommended.
%
%
%     'title' is the title of the dialog-box.'dflt' is a structure which contain default values for P.
%     These values will override  the default values specified in
%     struct_def.
%     Note that the dflt should contain the default values only, not the entire
%     definition as specified in S. This is useful for enabling user-specific defaults that override the
%     'factory defaults'.
%
%    See also: Struct2str, Browse_Struct
%
% Alon Fishbach, fishbach@northwestern.edu 12/15/04
%
% This code is provided "as is". Enjoy and feel free to modify it.
% Needless to say, the correctness of the code is not guarantied.

% AF 1/10/2005: Fixed a bug that crashed StructDlg when substructure were used.
% AF 1/10/2005: Allow for auto-updates even when the referenced field is not an edit UI

global rec_level

if ((isempty(rec_level)) | (rec_level <0))
   rec_level = 0;
end

if (exist('struct_def','var') ~= 1)
   rec_level = rec_level-1; % For delete function.
   return
end
if ((exist('title','var') ~= 1) | isempty(title))
   title = 'Input Form';
end
if (exist('dflt','var') ~= 1)
   dflt = struct([]);
end
if ((exist('visible','var') ~= 1) | isempty(visible))
   % 'Visible' is used mainly in recursive calls for the construction of a temporary hidden form for substructures.
   visible = 'on';
end
if (exist('present_val','var') ~= 1)
   present_val = []; % 'present_val' is used to pass the last value of sub-structure fields.
end

vert_spacing = 1;
font_size    = 11;
col          = 'k';
screen_size  = get_screen_size('char');
aspec_ratio  = screen_size(3)/screen_size(4);

if (isstruct(struct_def)) % Init
   rec_level = rec_level+1;
   if (isequal(visible,'on'))
      dflt = rm_ignore_dflt(dflt,struct_def);
      present_val = rm_ignore_dflt(present_val,struct_def);
   else
      dflt = rm_ignore_dflt(dflt,struct_def); % AF 6/20/02: Comment this line out if cuases problems.
      present_val = rm_ignore_dflt(present_val,struct_def);
   end
   [struct_def units limits protected] = split_def(struct_def);
   fnames = fieldnames(struct_def);
   fnames_lbl = build_labels(fieldnames(struct_def),units);
   max_width = (size(char(fnames_lbl),2) + 4) * font_size/7;
   tot_height = max(5,length(fnames_lbl)* (1+vert_spacing) + vert_spacing+2.5);
   recurssion_offset = 7*(rec_level-1);
   if ((exist('fig_pos','var') ~= 1) | isempty(fig_pos))
      fig_pos = [screen_size(3)/5+recurssion_offset  screen_size(4)-tot_height-4-recurssion_offset/aspec_ratio ...
         screen_size(3)*3/5  tot_height+2];
      specified_pos = 0;
   else
      if (tot_height+2 > fig_pos(4))
         height_addition = min(fig_pos(2)-0.5,(tot_height+2 -fig_pos(4)));
         fig_pos(2) = fig_pos(2) - height_addition;
         fig_pos(4) = fig_pos(4) + height_addition;
      end
      specified_pos = 1;
   end
   h_fig = figure( ...
      'NumberTitle',         'off',...
      'Name',                title, ...
      'Units',               'char', ...
      'position',            fig_pos, ...
      'keypress',            'StructDlg(get(gcbf,''CurrentCharacter''));', ...
      'color',               get(0,'DefaultuicontrolBackgroundColor'),...
      'Visible',             visible,...
      'DeleteFcn',           'StructDlg;', ...
      'CloseRequestFcn',     'StructDlg(''cancel'');',...
      'WindowStyle',         'modal'); % Change to noraml when debugging

   lbl = zeros(1,length(fnames_lbl));
   for i = 1:length(fnames_lbl)
      vert_pos = fig_pos(4)-i*(1+vert_spacing)-0.5;
      lbl(i)  = uicontrol(h_fig, ...
         'style',            'text', ...
         'units',            'char', ...
         'position',         [2.0 vert_pos max_width 1.5],...
         'String',           [fnames_lbl{i} ':'], ...
         'fontsize',         font_size, ...
         'Tag',              ['LBL_' fnames{i}], ...
         'ForegroundColor',  col, ...
         'horizon',          'right');
   end
   ud.error = [];
   ud.specified_pos = specified_pos;
   ud.col   = col;
   ud.width = 20;
   ud.units     = units;
   ud.dflt      = dflt;
   ud.limits    = limits;
   ud.protected = protected;
   ud = set_fields_ui(struct_def,h_fig,ud,[]);
   if (~isempty(present_val))
      ud.present_val = present_val;
      ud = set_fields_ui(struct_def,h_fig,ud,[]);
      ud = rmfield(ud,'present_val');
      set(h_fig,'UserData',ud);
   end

   OK_vert_pos = min(0.5,fig_pos(4)-tot_height);
   % OK_vert_pos = fig_pos(4)-tot_height;
   if (OK_vert_pos < 0)
      slider_step = fig_pos(4) / (abs(OK_vert_pos)+fig_pos(4));
      h_slider = uicontrol(h_fig, ...
         'style',         'slider', ...
         'callback',      'StructDlg(''slider_change'');', ...
         'Units',         'char', ...
         'position',      [0  0  3  fig_pos(4)/2], ...
         'SliderStep',    [slider_step/5 slider_step], ...
         'Max',           abs(OK_vert_pos), ...
         'value',         abs(OK_vert_pos), ...
         'Userdata',      abs(OK_vert_pos));
   end
   h_OK = uicontrol(h_fig, ...
      'style',         'pushbutton', ...
      'callback',      'StructDlg(''ok'');', ...
      'Units',         'char', ...
      'position',      [fig_pos(3)-40  OK_vert_pos  12  1.75], ...
      'String',        'ok', ...
      'FontName',      'Helvetica', ...
      'FontSize',      11, ...
      'FontWeight',    'normal');

   h_reset = uicontrol(h_fig, ...
      'style',         'pushbutton', ...
      'callback',      'StructDlg(''reset'');', ...
      'Units',         'char', ...
      'position',      [fig_pos(3)-27  OK_vert_pos  12  1.75], ...
      'String',        'reset', ...
      'FontName',      'Helvetica', ...
      'FontSize',      11, ...
      'FontWeight',    'normal');

   h_cancel = uicontrol(h_fig, ...
      'style',         'pushbutton', ...
      'callback',      'StructDlg(''cancel'');', ...
      'Units',         'char', ...
      'position',      [fig_pos(3)-14  OK_vert_pos  12  1.75], ...
      'String',        'cancel', ...
      'FontName',      'Helvetica', ...
      'FontSize',      11, ...
      'FontWeight',    'normal');

   if (rec_level >1) % For sub-forms (created with sub-structures) the cancel is disabled
      set(h_cancel,'Enable','off')
   end
   if (strcmp(visible,'on'))
      reorder_childs(h_fig)
      uiwait(h_fig);
   end
   ud    = get(h_fig,'UserData');
   P     = ud.vals;
   units = ud.units;
   delete(h_fig);

   % Following are callbacks from the form
elseif (iscell(struct_def) & ~isempty(struct_def))
   StructDlgCB(struct_def{1}); % Callback from one of the regular input fields. Processed in 'StructDlgCB'.

elseif (isstr(struct_def))
   % Other push buttons or context-menus in the form.
   [cmd args] = strtok(struct_def,'(');
   if (~isempty(args))
      args = {args(2:end-1)};
   end
   if (~isempty(cmd))
      switch (cmd)
         case 'unlock'
            unlockCB(args{1},gcbf);

         case 'undo'
            undoCB(args{1},gcbf);
            StructDlg(args);

         case {'reset', char(18)}
            ud    = get(gcbf,'UserData');
            set_fields_ui(ud.orig_def,gcbf,ud,[],args,1);

         case {'ok', char(15), char(10), char(13)}
            ud    = get(gcbf,'UserData');
            if (isempty(ud.error))
               uiresume(gcbf);
            else
               beep;
            end

         case {'cancel',char(27)}
            ud    = get(gcbf,'UserData');
            ud.vals = [];
            set(gcbf,'UserData',ud);
            uiresume(gcbf);

         case {'slider_change'}
            hgcbo = gcbo;
            val = get(hgcbo,'Userdata') - get(hgcbo,'Value');
            set(hgcbo,'UserData', get(hgcbo,'Value'));
            chld = get(gcbf,'Children');
            for i = 1:length(chld)
               if (chld(i) ~= hgcbo)
                  cur_pos = get(chld(i),'Position');
                  if (length(cur_pos) == 4) % i.e. not a uicontextmenu
                     set(chld(i),'Pos',cur_pos + [0 val 0 0]);
                     drawnow;
                  end
               end
            end

      end

   end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                        SUB FUNCTIONS                        %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Short Utility functions first:
%%
%%%%%%%%%%%%%
function [struct_def,units,limits,protected] = split_def(struct_def)
units     = struct([]);
limits    = struct([]);
protected = struct([]);
fnames = fieldnames(struct_def);
fvals  = struct2cell(struct_def);
for i = 1:length(fnames)
   switch (class(fvals{i}))
      case 'cell'
         if (length(fvals{i}) >=1)
            struct_def = setfield(struct_def,fnames{i}, fvals{i}{1});
         else
            struct_def = setfield(struct_def,fnames{i}, '');
         end
         if (length(fvals{i}) >=2)
            units = setfield(units,{1},fnames{i}, fvals{i}{2});
         end
         if (length(fvals{i}) >=3)
            if (~isempty(fvals{i}{3}))
               limits = setfield(limits,{1},fnames{i}, fvals{i}{3});
            end
         end
         %          if (length(fvals{i}) >=4)
         %             if (~isempty(fvals{i}{4}))
         %                labels = setfield(labels,{1},fnames{i}, fvals{i}{4});
         %             end
         %          end
         if (length(fvals{i}) >=4)
            if (~isempty(fvals{i}{4}) & fvals{i}{4} == 1)
               protected = setfield(protected,{1},fnames{i},1);
            end
         end

      case 'struct'

      otherwise
   end
end

%----------------------------------------------
function dflt = rm_ignore_dflt(dflt,struct_def)
fnames = fieldnames(struct_def);
fvals  = struct2cell(struct_def);
for i = 1:length(fnames)
   switch (class(fvals{i}))
      case 'cell'
         if (length(fvals{i}) >=5)
            if (~isempty(fvals{i}{5}) & fvals{i}{5} == 1 & isfield(dflt,fnames{i}))
               dflt = rmfield(dflt,fnames{i});
            end
         end

      case 'struct'
         % tmp = rm_ignore_dflt(getfield(dflt,fnames{i}),getfield(struct_def,fnames{i}));
         % dflt = setfield(dflt,fnames{i},tmp);

      otherwise
   end
end

%%%%%%%%%%%%%
function fnames_lbl = build_labels(fnames,units);
%
fnames_lbl = strrep(fnames,'_',' ');
f_units = fieldnames(units);
v_units = struct2cell(units);
for i = 1:length(f_units)
   if (ischar(v_units{i}) & ~isempty(v_units{i}))
      index = strmatch(f_units{i},fnames,'exact');
      if (~isempty(index))
         fnames_lbl{index} = strrep(v_units{i},'*',fnames_lbl{index});
         % fnames_lbl{index} = [fnames_lbl{index} ' (' v_units{i} ')'];
      end
   end
end
return;

%%%%%%%
% So the tab will always bring you to the first editable field (a bug-fix for Matlab Ver 6.1)
function reorder_childs(h_fig)
chld = get(h_fig,'Children');
if (length(chld) ==1)
   return;
end
for i = length(chld):-1:1
   if (strcmp(get(chld(i),'Type'),'uicontrol') & ~strcmp(get(chld(i),'Style'),'text') & ...
         strcmp(get(chld(i),'Enable'),'on'))
      ind = i;
      break;
   end
end
chld = [chld([1:ind-1 ind+1:end]) ; chld(ind)];
set(h_fig,'Children',chld);
return

%%%%%%%%
function tooltipstr = struct_tooltip(S,units)
try
   tooltipstr = char(struct2str(S,units,70));
catch
   tooltipstr = ['sub-structure info can not be displayed. ' lasterr];
end
tooltipstr = sprintf('%s', [tooltipstr repmat(char(10),size(tooltipstr,1),1)]');
return;

%%%%%%%%
function timer(t)
tic;
while(toc < t)
end
return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%  CREATION AND RESET OF UI's  %%%%%%%%%%%%%%%%%%%%%%
function ud = set_fields_ui(def,h_fig,ud,present_val,fnames,ignore_defaults)
%
% vals = def;
if ((exist('fnames','var') ~= 1) | isempty(fnames))
   fnames = fieldnames(def);
end
if (exist('ignore_defaults') ~= 1)
   ignore_defaults = 0;
end
if (~isfield(ud,'vals'))
   ud.vals = [];
end
orig_def = def;
if (isfield(ud,'present_val'))
   dflt = ud.present_val;
else
   dflt = ud.dflt;
end
ud.orig_def = orig_def;
ud.def = def;
if (~isfield(ud,'auto_update')) % needed for self-reference fields
   ud.auto_update = cell2struct(cell(size(fieldnames(def))),fieldnames(def));
end
if (~isfield(ud,'undo_vals'))
   ud.undo_vals = cell2struct(cell(size(fieldnames(def))),fieldnames(def));
end
set(h_fig,'UserData',ud);

fig_pos = get(h_fig, 'Position');
fig_width = fig_pos(3);
for i = 1:length(fnames)
   h_lbl = findobj(h_fig,'Tag',['LBL_' fnames{i}]);
   lbl_pos = get(h_lbl,'Position');
   h = findobj(h_fig,'Tag',fnames{i});
   val = getfield(def,fnames{i});
   if (iscell(val) & isempty(val))
      val = '';
   end
   if (isfield(ud.limits,fnames{i}))
      limits = getfield(ud.limits,fnames{i});
      if (isempty(limits))
         limits = [-Inf Inf];
         ud.limits = setfield(ud.limits,{1},fnames{i},limits);
      end
   elseif (isnumeric(val))
      limits = [-Inf Inf];
      ud.limits = setfield(ud.limits,{1},fnames{i},limits);
   else
      limits = [];
   end
   if (isfield(dflt,fnames{i}) & ~ignore_defaults)
      dflt_val = getfield(dflt,fnames{i});
   else
      dflt_val = [];
   end

   % val is a numeric or should be evaluated to a numeric value
   if (~isempty(limits) & ~isstruct(limits))
      ud = reset_numeric_field(h_fig,h,fnames{i},val,lbl_pos,limits,ud,dflt_val,ignore_defaults);

   elseif (ischar(val))
      sep = findstr(val,'|');
      if (isempty(sep))
         if (~isempty(dflt_val))
            val = dflt_val;
         end
         ud = reset_char_field(h_fig,h,fnames{i},val,lbl_pos,ud);

      else
         ud = reset_radio_field(h_fig,h,fnames{i},val,lbl_pos,ud,sep,dflt_val);
      end

   elseif (iscell(val))
      % Special requests
      if ((length(val) == 1) & ischar(val{1}))
         if (~isempty(strmatch('uigetfile',val{1})) | ...
               ~isempty(strmatch('uiputfile',val{1})) | ...
               ~isempty(strmatch('uigetdir',val{1})) )
            ud = reset_getfile_field(h_fig,h,fnames{i},val,lbl_pos,ud,dflt_val);
         end
      elseif ((length(val) == 2) & strmatch(val{1},{'0','{0}'},'exact') & strmatch(val{2},{'1','{1}'},'exact'))
         ud = reset_checkbox_field(h_fig,h,fnames{i},val,h_lbl,lbl_pos,ud,dflt_val);
      else
         ud = reset_popupmenu_field(h_fig,h,fnames{i},val,lbl_pos,ud,dflt_val);
      end

   elseif (isstruct(val))
      if (isfield(ud.units,fnames{i}))
         sub_units = getfield(ud.units,fnames{i});
      else
         if (isfield(ud.orig_def,fnames{i}))
            [dummy sub_units] = split_def(getfield(ud.orig_def,fnames{i}));
         else
            sub_units = struct([]);
         end
      end
      ud = reset_sub_struct_field(h_fig,h,fnames{i},val,lbl_pos,ud,dflt_val,sub_units);
   end
   if (isempty(h) | ~ishandle(h))  % h did not exist before. Now it is!
      % AF 12/14/2004 don't disable pushbuttons (for uigetfile).
      % h = findobj(h_fig,'Tag',fnames{i});
      h = findobj(h_fig,'Tag',fnames{i},'-not','Style','pushbutton');
      if (isfield(ud.protected,fnames{i}))
         set(h,'Enable',    'off');
         cmenu = get(h,'UIContextMenu');
         if (iscell(cmenu))
            cmenu = unique([cmenu{:}]);
         end
         for hi = 1:length(cmenu)
            item = uimenu(cmenu(hi), ...
               'Label',         'Unlock', ...
               'Separator',     'on', ...
               'Tag',           [fnames{i} '_UnLock'], ...
               'Callback',      ['StructDlg(''unlock(' fnames{i} ')'')'] );
         end
      end
   end
end
set(h_fig,'UserData',ud);
return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ud = auto_update(fnames,ud,hfig,ignore_defaults)
for i = 1:length(fnames)
   AU = getfield(ud.auto_update,fnames{i});
   if (~isempty(AU))
      old_vals = ud.vals;
      for i = 1:length(AU)
         ud = set_fields_ui(ud.orig_def,hfig,ud,[],AU(i),ignore_defaults);
      end
      blink_auto_changes(AU, old_vals, ud.vals, hfig)
   end
end
return;

%%%%%%%%%%%%%%%%%
function blink_auto_changes(AU_fnames, old_vals, new_vals, hfig)
blink_period = 0.2;
h = NaN*zeros(1,length(AU_fnames));
col = cell(1,length(AU_fnames));
enbl = cell(1,length(AU_fnames));
for i = 1:length(AU_fnames)
   oldval = getfield(old_vals,AU_fnames{i});
   val    = getfield(new_vals,AU_fnames{i});
   if (~all(isnan(oldval)) & ((xor(isempty(oldval),isempty(val)) | any(size(oldval)~= size(val)) | oldval ~= val)))
      h(i) = findobj(hfig,'Tag',AU_fnames{i});
      col{i} = get(h(i),'ForegroundColor');
      enbl{i} = get(h(i),'Enable');
   end
end
reps = 2;
do_wait = 0;
for j = 1:reps
   for i = 1:length(AU_fnames)
      if (ishandle(h(i)))
         set(h(i),'enable','on');
         set(h(i),'ForegroundColor',[0 0.8 .4]);
         do_wait = 1;
      end
   end
   if (do_wait)
      drawnow;
      timer(blink_period);
   end
   for i = 1:length(AU_fnames)
      if (ishandle(h(i)))
         set(h(i),'Enable',enbl{i});
         set(h(i),'ForegroundColor',col{i});
      end
   end
   if (do_wait & j < reps)
      drawnow;
      timer(blink_period);
   end
end
drawnow;
return;

%%%%%%%%%%%%%%%%%
function ud = register_undo_info(fnames,vals,ud,h_fig)
for i = 1:length(fnames)
   prev_undo = getfield(ud.undo_vals,fnames{i});
   if (~strcmp(vals{i},'NaN') & ((xor(isempty(prev_undo),isempty(vals{i})) | strcmp(prev_undo,vals{i})==0)))
      ud.undo_vals = setfield(ud.undo_vals,fnames{i},vals{i});
      h_undo = findobj(h_fig,'Tag',[fnames{i} '_UNDO']);
      if (isempty(vals{i}))
         set(h_undo,'Enable','off');
      else
         set(h_undo,'Enable','on');
      end
   end
end
return

%%%%%%%%%%%%%%%%%
function undoCB(f,h_fig)
ud = get(h_fig,'Userdata');
undo_val = getfield(ud.undo_vals,f);
if (~isempty(undo_val))
   if (~ischar(undo_val))
      undo_val = mat2str(undo_val);
   end
   h = findobj(h_fig,'Tag',f);
   set(h,'String',undo_val);
   h_undo = findobj(h_fig,'Tag',[f '_UNDO']);
   set(h_undo,'Enable','off');
end
return

%%%%%%%%%%%%%%%%%
function unlockCB(f,h_fig)
h = findobj(h_fig,'Tag',f);
for i = 1:length(h)
   set(h,'Enable','on');
end
set (gcbo,'Enable','off');
return;

%%%%%%%%%%%%%%%%%
function ud = prepare2evaluate(str,f,h,ud)
self_ref = struct_mfile_reference('','this',{str});
if (isempty(self_ref))
   return;
end
self_fields = fieldnames(self_ref);
if (~isempty(self_fields))
   h_fig = get(h,'Parent');
   ud.vals = setfield(ud.vals,f,NaN);
   set(h_fig,'Userdata',ud); % Prevent recursive loops when the user does stupid things.
   for i = 1:length(self_fields)
      if (isfield(ud.def,self_fields{i}) & ~isfield(ud.vals,self_fields{i}))
         % If the refered field was not set yet, NaN it. it will be evaluated later.
         ud.vals = setfield(ud.vals,self_fields{i},NaN);
      end
      cur_AU = getfield(ud.auto_update,self_fields{i});
      if (isempty(cur_AU)) %% AF 11/22/04 R14
         cur_AU = {};
      end
      if (isempty(strmatch(f,cur_AU,'exact')) & ~strcmp(self_fields{i},f))
         ud.auto_update = setfield(ud.auto_update,self_fields{i},cat(1,cur_AU,{f}));
      end
   end
end
return

%%%%%%%%%%%%%
% Protect other variables from the evaluation results, and passing 'this' as a parameter
function retval = secure_eval(this,str)
retval = eval(['[' str ']']);
return

%%%%%%%%%%%%%
function [ud,str] = checkNset_numeric_field(h,f,limits,ud,undo_val,dflt_val,ignore_defaults)
col   = ud.col;
str = get(h,'String');
h_fig = get(h,'Parent');
try
   iserror = 0;
   ud = prepare2evaluate(str,f,h,ud);
   if (isempty(dflt_val))
      retval = secure_eval(ud.vals,str);
   else
      retval = dflt_val;
   end
   if (~isnumeric(retval))
      str = 'Numbers only!';
      iserror = 1;
   elseif (any(retval(:) < limits(1) | retval(:) > limits(2)))
      str = ['Allowed range: [' num2str(limits) ']'];
      iserror = 1;
   else
      str    = mat2str(retval);
   end
catch
   iserror = 1;
   str     = strrep(lasterr,char(10),': ');
end
if (iserror)
   ud.error = setfield(ud.error,f,1);
   retval = [];
   col = 'r';
elseif (isfield(ud.error,f))
   ud.error = rmfield(ud.error,f);
   if (isempty(fields(ud.error)))
      ud.error = [];
   end
end
set(h,'String',str);
set(h,'ForegroundColor',col);
ud = register_undo_info({f},{undo_val},ud,h_fig);
ud.vals = setfield(ud.vals,f,retval);
if (~iserror)
   ud = auto_update({f},ud,h_fig,ignore_defaults);
end
return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function update_uicontrol_width(h,width)
hud = get(h,'UserData');
if ((isfield(hud,'related_h')) & (ishandle(hud.related_h)))
   related_h = hud.related_h;
   related_pos = get(related_h,'Position');
   related_width = related_pos(3);
else
   related_h = [];
   related_width = 0;
end
fig_pos = get(get(h,'Parent'),'Position');
pos = get(h,'Position');
fig_width = fig_pos(3);
width = min(width, fig_width-related_width-pos(1)-1);
width_change = width - pos(3);
pos(3) = width;
set(h,'Position',pos);
if (~isempty(related_h))
   related_pos(1) = related_pos(1) + width_change;
   set(related_h,'Position',related_pos);
end
return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Implemetation of Numeric field (including function evaluation)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ud = reset_numeric_field(h_fig,h,f,val,lbl_pos,limits,ud,dflt_val, ignore_defaults)
strval = val;
if (~ischar(strval))
   strval = mat2str(strval);
end
if (isempty(h))
   prev_str = '';
   if (length(strval) > 60)
      item_label = ['Reset (to: ''' strval(1:60) '...'')'];
   else
      item_label = ['Reset (to: ''' strval ''')'];
   end
   cmenu = uicontextmenu;
   item1 = uimenu(cmenu, ...
      'Label',     item_label, ...
      'Callback',  ['StructDlg(''reset(' f ')'')'] );
   item2 = uimenu(cmenu, ...
      'Label',     'Undo', ...
      'Enable',    'off', ...
      'Separator', 'off', ...
      'Tag',       [f '_UNDO'], ...
      'Callback',  ['StructDlg(''undo(' f ')'')'] );

   h = uicontrol(h_fig, ...
      'style',      'edit', ...
      'Units',      'char', ...
      'position',   [lbl_pos(3)+lbl_pos(1)+0.5 lbl_pos(2) 20 1.5],...
      'string',     [], ...
      'FontName',   'Helvetica', ...
      'FontSize',   9, ...
      'BackgroundColor', [1 1 1], ...
      'TooltipString', ['Allowed range: [' num2str(limits) ']'], ...
      'horizon',    'left', ...
      'Tag',        f, ...
      'UIContextMenu', cmenu, ...
      'Callback',   ['StructDlg({''' f '''});']);
   set(item2,'Userdata',struct('uicontrol',h));
   if (ischar(val))
      h1 = uicontrol(h_fig, ...
         'style',            'text', ...
         'units',            'char', ...
         'position',         [lbl_pos(3)+lbl_pos(1)+0.5+21.5 lbl_pos(2) length(val)+10 1.5],...
         'String',           ['=(''' val ''')'], ...
         'FontName',         'Helvetica', ...
         'fontsize',         9, ...
         'ForegroundColor',  [0.15 0.15 0.15], ...
         'FontWeight',       'light', ...
         'FontAngle',        'normal', ...
         'Tag',              '', ...
         'horizon',          'left');
      set(h,'UserData', struct('related_h',h1));
   end
end
prev_str = get(h,'String');
set(h,'String',strval);
[ud,str] = checkNset_numeric_field(h,f,limits,ud,prev_str,dflt_val,ignore_defaults);
% fprintf('reset_numeric_field: ''%s'': %s -> %s\n', f, strval, str);
update_uicontrol_width(h,length(str)+10);
return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Implementation of Open String field
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ud = reset_char_field(h_fig,h,f,val,lbl_pos,ud);
ud.vals = setfield(ud.vals,f,val);
if (isempty(h))
   cmenu = uicontextmenu;
   item1 = uimenu(cmenu, ...
      'Label',     ['Reset (to: ''' val ''')'], ...
      'Callback',  ['StructDlg(''reset(' f ')'')'] );

   h = uicontrol(h_fig, ...
      'style',      'edit', ...
      'Units',      'char', ...
      'position',   [lbl_pos(3)+lbl_pos(1)+0.5 lbl_pos(2) 20 1.5],...
      'string',     [], ...
      'FontName',   'Helvetica', ...
      'FontSize',   9, ...
      'horizon',    'left', ...
      'BackgroundColor', [1 1 1], ...
      'Tag',        f, ...
      'UIContextMenu', cmenu, ...
      'Callback',   ['StructDlg({''' f '''});']);
end
set(h,'String',val);
pos = get(h,'Position');
pos(3) = max(20,length(val)+10);
set(h,'Position',pos);
set(h,'ForegroundColor',ud.col);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Implemenation of Radio Buttons
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ud = reset_radio_field(h_fig,h,f,val,lbl_pos,ud,sep,dflt_val)
selected = 1;
sep = [0 sep length(val)+1];
options = cell(1,length(sep)-1);
if (isempty(h))
   h = NaN*zeros(1,length(options));
end
selected = zeros(1,length(options));
selected_str = '';
setval = '';
for sep_i = 1:length(sep)-1
   options{sep_i} = val(sep(sep_i)+1:sep(sep_i+1)-1);
   if ((~isempty(options{sep_i})) & (options{sep_i}(1) == '{' & options{sep_i}(end) == '}'))
      options{sep_i} = options{sep_i}(2:end-1);
      selected(sep_i) = 1;
      selected_str = options{sep_i};
      setval = str2double(options{sep_i});
      if (isnan(setval))
         setval = options{sep_i};
      end
   end
end
ud.vals = setfield(ud.vals,f,setval);
if (~isempty(dflt_val))
   if (isnumeric(dflt_val))
      dflt_val = num2str(dflt_val);
   end
   dflt_selected = strmatch(dflt_val,options,'exact');
   if (~isempty(dflt_selected))
      ud.vals = setfield(ud.vals,f,dflt_val);
      selected = zeros(1,length(options));
      selected(dflt_selected) = 1;
      selected_str = options{dflt_selected};
   end
end
sum_width = 0;
for val_i = 1:length(options)
   cmenu = uicontextmenu;
   item1 = uimenu(cmenu, ...
      'Label',     ['Reset (to: ''' selected_str ''')'], ...
      'Callback',  ['StructDlg(''reset(' f ')'')'] );

   if (~ishandle(h(val_i)))
      width = min(35, 10+length(options{val_i}));
      h(val_i) = uicontrol(h_fig, ...
         'style',          'radio', ...
         'Units',          'char', ...
         'position',       [lbl_pos(3)+lbl_pos(1)+0.5+sum_width lbl_pos(2) width 1.5],...
         'string',         options{val_i}, ...
         'FontName',       'Helvetica', ...
         'FontSize',       9, ...
         'horizon',        'left', ...
         'Value',          selected(val_i), ...
         'Tag',            f, ...
         'UIContextMenu',  cmenu, ...
         'Callback',       ['StructDlg({''' f '''});']);
      sum_width = sum_width + width;
   else
      if (strcmp(get(h(val_i),'String'), selected_str))
         set(h(val_i),'Value',     1);
      else
         set(h(val_i),'Value',     0);
      end
   end
end
return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Implementation of Getfile, Putfile and Getdir
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ud = reset_getfile_field(h_fig,h,f,val,lbl_pos,ud,dflt_val)
lpar = min(findstr(val{1}, '('));
first_comma = min(findstr(val{1}, ','));
rpar = max(findstr(val{1}, ''')'));
end_filter_spec = min([first_comma rpar+1]);
l_curl = min(findstr(val{1}, '{'));
r_curl = min(findstr(val{1}, '}'));
extra_args = '';
filter_spec = '';
if (~isempty(dflt_val))
   filter_spec = dflt_val;
elseif (~isempty(lpar))
   if (~isempty(end_filter_spec))
      if (~isempty(l_curl) & ~isempty(r_curl)) % Note, there is no check that the curls are smaller than end_filter_spec
         filter_spec = val{1}(l_curl:r_curl); % Must contain the curly brackets.
      else
         filter_spec = val{1}(lpar+2:end_filter_spec-2);
      end
      if (~isempty(first_comma))
         extra_args = val{1}(first_comma+1:rpar);
      end
   end
else
   lpar = length(val{1});
end
if (filter_spec(1) == '{') % if the filter is a complex set of filters then don't present it.
   filter_label = ['Files of types: ' filter_spec];
else
   filter_label = filter_spec;
   filter_spec = '';
end
cmd = deblank(val{1}(1:lpar-1));
width = max(20,length(filter_label)+10);
if (isempty(h))
   cmenu = uicontextmenu;
   item1 = uimenu(cmenu, ...
      'Label',         ['Reset (to: ''' filter_label ''')'], ...
      'Callback',      ['StructDlg(''reset(' f ')'')'] );

   h = [0 0];
   h(2) = uicontrol(h_fig, ...
      'style',          'edit', ...
      'Units',          'char', ...
      'position',       [lbl_pos(3)+lbl_pos(1)+0.5 lbl_pos(2) width 1.5],...
      'string',         filter_label, ...
      'FontName',       'Helvetica', ...
      'FontSize',       9, ...
      'horizon',        'left', ...
      'BackgroundColor', [1 1 1], ...
      'Tag',            f, ...
      'UIContextMenu',  cmenu, ...
      'Callback',       ['StructDlg({''' f '''});']);
   h(1) = uicontrol(h_fig, ...
      'style',          'pushbutton', ...
      'Units',          'char', ...
      'position',       [lbl_pos(3)+lbl_pos(1)+0.5+width+0.5 lbl_pos(2)  3  1.5], ...
      'string',         char(133), ...
      'FontName',       'Helvetica', ...
      'FontSize',       9, ...
      'Tag',            f, ...
      'UIContextMenu',  cmenu, ...
      'callback',       ['StructDlg({''' f '''});']);

   push_ud.cmd    = cmd;
   push_ud.params = h(2);
   push_ud.filter_spec = filter_spec;
   push_ud.varargin = extra_args;
   set(h(1),'Userdata',push_ud);
   set(h(2),'Userdata', struct('related_h', h(1)));
end
str_h = findobj(h, 'style', 'edit');
set(str_h,'string',filter_label);
update_uicontrol_width(str_h,width);
ud.vals = setfield(ud.vals,f,filter_label);
% ud.def = setfield(ud.def,f,filter_spec);
return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Implemenation of Binary Check Box
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ud = reset_checkbox_field(h_fig,h,f,val,h_lbl,lbl_pos,ud,dflt_val)
if ((~isempty(dflt_val)) & (dflt_val == 0 | dflt_val == 1))
   selected = dflt_val;
else
   selected = min(strmatch('{',val)) - 1;
   if (isempty(selected))
      selected = 0;
   end
end
if (isempty(h))
   if (selected)
      opt_label = 'Checked';
   else
      opt_label = 'UnChecked';
   end
   cmenu = uicontextmenu;
   item1 = uimenu(cmenu, ...
      'Label',         ['Reset (to: ''' opt_label ''')'], ...
      'Callback',      ['StructDlg(''reset(' f ')'')'] );

   h = uicontrol(h_fig, ...
      'style',          'checkbox', ...
      'Units',          'char', ...
      'position',       [lbl_pos(3)+lbl_pos(1)+0.5 lbl_pos(2) 2 1.5],...
      'string',         'test', ...
      'horizon',        'left', ...
      'value',          selected, ...
      'Tag',            f, ...
      'UIContextMenu',  cmenu, ...
      'Callback',       ['StructDlg({''' f '''});']);
end
set(h, 'value',      selected);
lbl_str = get(h_lbl,'String');
lbl_str(end) = '?';
set(h_lbl,'String',lbl_str);
ud.vals = setfield(ud.vals,f,selected);
return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Implemenation of popupmenu
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ud = reset_popupmenu_field(h_fig,h,f,val,lbl_pos,ud,dflt_val)
selected = 1;
for val_i = 1:length(val)
   if (val{val_i}(1) == '{' & val{val_i}(end) == '}')
      val{val_i} = val{val_i}(2:end-1);
      selected = val_i;
   end
end
setval = str2double(val{selected});
if (isnan(setval))
   setval = val{selected};
end
ud.vals = setfield(ud.vals,f,setval);
if (~isempty(dflt_val))
   if (isnumeric(dflt_val))
      dflt_val = num2str(dflt_val);
   end
   dflt_selected = strmatch(dflt_val,val,'exact');
   if (~isempty(dflt_selected))
      ud.vals = setfield(ud.vals,f,dflt_val);
      selected = dflt_selected;
   end
end
if (isempty(h))
   opt_label = getfield(ud.vals,f);
   if (isnumeric(opt_label))
      opt_label = num2str(opt_label);
   end
   cmenu = uicontextmenu;
   item1 = uimenu(cmenu, ...
      'Label',         ['Reset (to: ''' opt_label ''')'], ...
      'Callback',      ['StructDlg(''reset(' f ')'')'] );

   width = size(char(val),2) + 10;
   h = uicontrol(h_fig, ...
      'style',      'popupmenu', ...
      'Units',      'char', ...
      'position',   [lbl_pos(3)+lbl_pos(1)+0.5 lbl_pos(2) width 1.5],...
      'string',     val, ...
      'FontName',   'Helvetica', ...
      'FontSize',   9, ...
      'horizon',    'left', ...
      'BackgroundColor', [1 1 1], ...
      'Value',      selected, ...
      'Tag',        f, ...
      'UIContextMenu',  cmenu, ...
      'Callback',   ['StructDlg({''' f '''});']);
else
   set(h,'Value',  selected);
end
return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%s
%% Implemenation of recursive call (for sub-structures)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ud = reset_sub_struct_field(h_fig,h,f,val,lbl_pos,ud,dflt_val,units);
if (isfield(ud.vals,f));
   [sub_vals,sub_units] = StructDlg(val,'',getfield(ud.vals,f),[],'off');
else
   [sub_vals,sub_units] = StructDlg(val,'',dflt_val,[],'off');
end
ud.vals  = setfield(ud.vals,f,sub_vals);
ud.units = setfield(ud.units,{1},f,sub_units);
tooltipstr = struct_tooltip(sub_vals,units);
if (isempty(h))
   h = uicontrol(h_fig, ...
      'style',          'pushbutton', ...
      'Units',          'char', ...
      'position',       [lbl_pos(3)+lbl_pos(1)+0.5 lbl_pos(2)  3  1.5], ...
      'string',         char(187), ...
      'FontName',       'Helvetica', ...
      'FontSize',       9, ...
      'Tag',            f, ...
      'TooltipString',  tooltipstr, ...
      'callback',       ['StructDlg({''' f '''});']);

   push_ud.cmd    = 'StructDlg';
   push_ud.params = units; % units are specified here for the tooltip string only
   set(h,'Userdata',push_ud);
end
return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  MAIN CALL_BACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%
function StructDlgCB(f)
%
hgcbf = gcbf;
ud    = get(hgcbf,'UserData');
width = ud.width;
def   = getfield(ud.def,f);
v     = getfield(ud.vals,f);
hgcbo = gcbo;
if (isfield(ud.limits,f))
   limits = getfield(ud.limits,f);
else
   limits = [];
end
undo_flag = 0;
if (strcmp(get(hgcbo,'Type'), 'uimenu'))
   hgcbo = getfield(get(hgcbo,'Userdata'),'uicontrol');
   prev_val = '';
else
   prev_val = v;
end
switch (get(hgcbo,'Style'))
   case 'edit'
      if (~isempty(limits) & isnumeric(limits))
         [ud,str] = checkNset_numeric_field(hgcbo,f,limits,ud,prev_val,[],1);
      elseif (ischar(def))
         str = get(hgcbo,'String');
         width = length(str)+10;
         ud.vals = setfield(ud.vals,f,str);
      elseif (iscell(def)) %% special commands' edit window
         str = get(hgcbo,'String');
         retval = str2num(str);
         if (isempty(retval))
            retval = str;
         end
         ud.vals = setfield(ud.vals,f,retval);
      end
      update_uicontrol_width(hgcbo,length(str)+10)

   case 'popupmenu'
      val = get(hgcbo,'Value');
      str = def{val};
      if (str(1) == '{')
         str = str(2:end-1);
      end
      setval = str2double(str);
      if (isnan(setval))
         setval = str;
      end
      ud.vals = setfield(ud.vals,f,setval);

   case 'radiobutton'
      str = get(hgcbo,'String');
      h = findobj(hgcbf,'Tag',get(hgcbo,'Tag'));
      for h_i = 1:length(h)
         if (~strcmp(str,get(h(h_i),'String')))
            set(h(h_i),'Value',0);
         end
      end
      setval = str2double(str);
      if (isnan(setval))
         setval = str;
      end
      ud.vals = setfield(ud.vals,f,setval);

   case 'checkbox'
      val = get(hgcbo,'Value');
      ud.vals = setfield(ud.vals,f,val);

   case 'pushbutton'
      push_ud = get(hgcbo,'Userdata');
      switch (push_ud.cmd)
         case {'uigetfile','uiputfile','uigetdir'}
            if (~isempty(push_ud.filter_spec))
               filter_spec = push_ud.filter_spec;
            else
               filter_spec = get(push_ud.params,'String');
            end
            extra_args = push_ud.varargin;
            if (isempty(filter_spec))
               filter_spec = '*.*';
            end
            if (filter_spec(1) ~= '{' & filter_spec(1) ~= '''')
               filter_spec = ['''' filter_spec ''''];
            end
            if (~isempty(extra_args))
               extra_args = [',' extra_args];
            end
            if (strcmp(push_ud.cmd,'uigetdir'))
               eval(['fname = ' push_ud.cmd '(' filter_spec  extra_args ');'])
               pname = '';
            else
               eval(['[fname, pname] = ' push_ud.cmd '(' filter_spec  extra_args ');'])
            end
            return_val = '';
            str = '';
            if (~isempty(fname) & (iscell(fname) | fname ~= 0))
               if (isstr(fname))
                  str = [pname fname];
                  return_val = str;
               elseif (iscell(fname))
                  return_val = cell(1,length(fname));
                  return_val{1} = [pname fname{1}];
                  str = [pname '{' fname{1}];
                  for fname_i = 2:length(fname)
                     str = [str ', ' fname{fname_i}];
                     return_val{fname_i} = [pname fname{fname_i}];
                  end
                  str = [str '}'];
               end
               % In case multi-files were chosen, save the current filter spec.
               if (isempty(push_ud.filter_spec) & iscell(fname))
                  push_ud.filter_spec = filter_spec;
                  set(hgcbo,'Userdata',push_ud);
               end
               ud.vals = setfield(ud.vals,f,return_val);
               set(push_ud.params,'String',str);
               width = length(str)+14;
               update_uicontrol_width(push_ud.params, width)
            end

         case 'StructDlg'
            if (isempty(ud.error))
               title = [get(hgcbf,'Name') '->' f];
               if (isfield(ud.dflt,f))
                  dflt_val = getfield(ud.dflt,f);
               else
                  dflt_val = [];
               end
               if (isfield(ud.limits,f))
                  limits = getfield(ud.limits,f);
               else
                  limits = [];
               end
               if (ud.specified_pos)
                  fig_pos = get(hgcbf,'Position');
                  screen_size  = get_screen_size('char');
                  aspec_ratio  = screen_size(3)/screen_size(4);
                  recurssion_offset = 5;
                  rec_pos = [fig_pos(1)+recurssion_offset  fig_pos(2)-recurssion_offset/aspec_ratio fig_pos(3:4)];
               else
                  rec_pos = [];
               end
               ret_struct = StructDlg(getfield(ud.orig_def,f),title,dflt_val,rec_pos,'on',v);
               tooltipstr = struct_tooltip(ret_struct,push_ud.params);
               set(hgcbo,'TooltipString', tooltipstr);
               ud.vals = setfield(ud.vals,f,ret_struct);
            else
               beep;
            end
      end
end
ud = auto_update({f},ud,hgcbf,1);% AF 1/10/2005: Update fields that reference f
set(hgcbf,'UserData',ud);
return;

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
%% This file will symbolic solve for the ODE of the Single Pendulum on a Cart system.
% Coded By: K
% Data: 2019/04/27
%%
clc;clear;close all
% Define the symbolic symbols you need
syms x0(t) dx0(t) ddx0 theta(t) dtheta(t) ddtheta M m L F k0 k1 g I1 dum
% Set some variables to zero to simplify the model
I1=0; k0=0; k1=0;
% First define the position of the pendulum mass center
x1=x0+L*sin(theta)
y1=L*cos(theta)

% Now define the velocity of the cart and moving mass
v0=diff(x0,t)
v1x=diff(x1,t)
v1y=diff(y1,t)

% Substitute the variables
v0=subs(v0,diff(x0,t),dx0);
v1x=subs(v1x,diff(x0,t),dx0);
v1x=subs(v1x,diff(theta,t),dtheta);
v1y=subs(v1y,diff(x0,t),dx0);
v1y=subs(v1y,diff(theta,t),dtheta);

simplify(v1x^2+v1y^2)
simplify(v1x)
simplify(v1y)

% Now define the kinetic energy of the system
EngK=simplify(0.5*M*v0^2+0.5*m*simplify(v1x^2+v1y^2)+0.5*I1*diff(theta,t)^2)
EngP=m*g*(cos(theta))*L

% Define the Rayley disspation function
Damp=0.5*k0*v0^2+0.5*k1*dtheta^2;

% Now define the Lagrangian
Lag=simplify(EngK-EngP)

%% Now get the second order ODE
the1Part1=diff(subs(Lag,dtheta,dum),dum);
the1Part1=subs(the1Part1,dum,dtheta);
the1Part1=diff(the1Part1,t);
%
the1Part2=diff(subs(Lag,theta,dum),dum);
the1Part2=subs(the1Part2,dum,theta);
%
the1Part3=diff(subs(Damp,dtheta,dum),dum);
the1Part3=subs(the1Part3,dum,dtheta);
eqn1=the1Part1-the1Part2+the1Part3
%
eqn1=subs(eqn1,diff(dx0(t), t),ddx0);
eqn1=subs(eqn1,diff(x0(t), t, t),ddx0);
eqn1=subs(eqn1,diff(theta(t), t),dtheta);
eqn1=subs(eqn1,diff(dtheta(t), t),ddtheta);

% Second equation
the2Part1=diff(subs(Lag,dx0,dum),dum);
the2Part1=subs(the2Part1,dum,dx0);
the2Part1=diff(the2Part1,t);
%
the2Part2=diff(subs(Lag,x0,dum),dum);
the2Part2=subs(the2Part2,dum,x0);
%
the2Part3=diff(subs(Damp,dx0,dum),dum);
the2Part3=subs(the2Part3,dum,dx0);
eqn2=the2Part1-the2Part2+the2Part3-F
%
eqn2=subs(eqn2,diff(dx0(t), t),ddx0);
eqn2=subs(eqn2,diff(x0(t), t, t),ddx0);
eqn2=subs(eqn2,diff(theta(t), t),dtheta);
eqn2=subs(eqn2,diff(dtheta(t), t),ddtheta);

% Final eqn1 and eqn2
Eqn1=simplify(eqn1)==0
Eqn2=simplify(eqn2)==0

%% Solve for ddtheta and ddx0
eqns=[Eqn1 Eqn2];
vars=[ddtheta ddx0];
[Ans1 Ans2]=solve(eqns,vars);

Ans1=simplify(Ans1)
Ans2=simplify(Ans2)

%% Now rewrite the second order system into first order system
syms z1 z2 z3 z4
thisisddtheta1=simplify(subs(Ans1,[theta(t) x0(t) dtheta(t) dx0(t)],[z1 z2 z3 z4]))
thisisddtheta2=simplify(subs(Ans2,[theta(t) x0(t) dtheta(t) dx0(t)],[z1 z2 z3 z4]))

%% Save this file into Matlab Function
% dtheta=z3, dx=z4, ddtheta=thisistheta1, ddx=thisistheta2
Eqns=[z3;z4;thisisddtheta1;thisisddtheta2]

matlabFunction(Eqns,'File','SinglePendulum_ODE','Vars',{t,[z1 z2 z3 z4],F,M,m,L,g},'Optimize',true)

author: dynamicslab

repo: SINDy-PI


text:
function [mi, loc] = kminima(a, k, d)
% KMINIMA specified number of minima
%     For vectors, KMINIMA(X,K) is the vector of K smallest elements in X.
%     For matrices, Y = KMINIMA(X,K) is a matrix with K rows; Y(i,:)
%     contains the i-th minimum element from each column. For N-D arrays,
%     KMINIMA(X,K) operates along the first non-singleton dimension.
%
%     [Y,I] = KMINIMA(X,K) returns the indices of the minima in vector I.
%
%     [Y,I] = KMAXIMA(X,K,DIM) operates along the dimension DIM.
%
%     When complex, the magnitude ABS(X) is considered when computing the
%     minima, and the angle ANGLE(X) is ignored.  NaN's are also ignored .

% Mukhtar Ullah
% mukhtar.ullah@informatik.uni-rostock.de
% November 17, 2004

a(isnan(a)) = inf;
if isvector(a) && nargin < 3
    [b,ix] = sort(a);
    mi = b(1:k);
    loc = ix(1:k);
else
    if nargin < 3, d = 1; end
    [b,ix] = sort(a, d);
    n = ndims(a);
    if n < 3
        if d < 2
            mi = b(1:k, :);
            loc = ix(1:k, :);
        else
            mi = b(:, 1:k);
            loc = ix(:, 1:k);
        end
    else
        C = cell(1, n);
        if d > 1, C(1:d-1) = {':,'}; end
        if d < n, C(d+1:n) = {',:'}; end
        C(d) = {'1:k'};
        S = ['(' [C{:}] ')'];
        mi = eval(['b' S]);
        if nargout > 1, loc = eval(['ix' S]); end
    end
end

author: Sable

repo: mcbench-benchmarks


text:
% from DNG to sRGB
filename = fullfile('data', '0001_DSC_9315.DNG');
[im_raw, metadata] = Load_Data_and_Metadata_from_DNG(filename);
im_srgb = run_pipeline(im_raw, metadata, 'raw', 'srgb');
imwrite(im_srgb, fullfile('data', 'im_srgb_1.png'));

% from normalized RAW to sRGB
im_norm = load(fullfile('data', '0001_NOISY_RAW_001.MAT'));
im_norm = im_norm.x;
metadata = load(fullfile('data', '0001_METADATA_RAW_001.MAT'));
metadata = metadata.metadata;
im_srgb = run_pipeline(im_norm, metadata, 'normal', 'srgb');
imwrite(im_srgb, fullfile('data', 'im_srgb_2.png'));

author: AbdoKamel

repo: sidd-ground-truth-image-estimation


text:
function [ readerobj ] = open_mbw_reader(filename)
%OPEN_MBW_READER Intiates a reader object for a multi-band wrapper file
%
% An intermediate format just for handling data that is contained in
% multiple files (color, polarimetric, etc.)
%
% Written by: Wade Schwartzkopf, NGA/IDT
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

%% Read mbw fields
fid=fopen(filename,'r');
while ~feof(fid)
    [fieldname,value]=strtok(fgetl(fid),'=');
    if ~isempty(value)
        mbw.(fieldname)=value(2:end);
        doubval=str2double(mbw.(fieldname));
        if(~isnan(doubval)) % If value is numeric, store as such
            mbw.(fieldname)=doubval;
        end
    end
end
fclose(fid);
if(strcmp(mbw.TYPE,'RGB'))
    for i=1:3, filenamelist{i}=mbw.(mbw.TYPE(i)); end
    readerobj=open_stacked_set(filenamelist{:});
end

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

author: ngageoint


text:
function connection = skelConnectionMatrix(skel);

% SKELCONNECTIONMATRIX Compute the connection matrix for the structure.
% FORMAT
% DESC computes the connection matrix for the structure. Returns a matrix
% which has zeros at all entries except those that are connected in the
% skeleton.
% ARG skel : the skeleton for which the connectivity is required.
% RETURN connection : connectivity matrix.
%
% COPYRIGHT : Neil D. Lawrence, 2006
%
% SEEALSO : skelVisualise, skelModify

% MOCAP

connection = zeros(length(skel.tree));
for i = 1:length(skel.tree);
  for j = 1:length(skel.tree(i).children)
    connection(i, skel.tree(i).children(j)) = 1;
  end
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
classdef MOMFEAII < ALGORITHM
% <multi> <real/integer/label/binary/permutation> <constrained/none> <multitask>
% Multi-objective multifactorial evolutionary algorithm II

%------------------------------- Reference --------------------------------
% K. K. Bali, A. Gupta, Y. Ong, and P. S. Tan, Cognizant multitasking in
% multiobjective multifactorial evolution: MO-MFEA-II, IEEE Transactions on
% Cybernetics, 2021, 51(4): 1784-1796.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Initialize population
            Population    = Problem.Initialization();
            SubPopulation = Divide(Population,length(Problem.SubD));

            %% Optimization
            while Algorithm.NotTerminated([SubPopulation{:}])
                RMP                  = learnRMP(Problem,SubPopulation);
                [SubPopulation,Rank] = Sort(Problem,SubPopulation);
                Population           = [SubPopulation{:}];
                ParentPool           = Population(TournamentSelection(2,length(Population),[Rank{:}]));
                SubOffspring         = CreateOff(Problem,ParentPool,SubPopulation,RMP);
                for i = 1 : length(Problem.SubD)
                    SubPopulation{i} = EnviSelect([SubPopulation{i},SubOffspring{i}],length(SubPopulation{i}));
                end
            end
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function [logp, yhat, res] = tapas_logrt_linear_binary(r, infStates, ptrans)
% Calculates the log-probability of log-reaction times y (in units of log-ms) according to the
% linear log-RT model developed with Louise Marshall and Sven Bestmann
%
% --------------------------------------------------------------------------------------------------
% Copyright (C) 2014-2016 Christoph Mathys, UZH & ETHZ
%
% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

% Transform parameters to their native space
be0  = ptrans(1);
be1  = ptrans(2);
be2  = ptrans(3);
be3  = ptrans(4);
be4  = ptrans(5);
ze   = exp(ptrans(6));

% Initialize returned log-probabilities, predictions,
% and residuals as NaNs so that NaN is returned for all
% irregualar trials
n = size(infStates,1);
logp = NaN(n,1);
yhat = NaN(n,1);
res  = NaN(n,1);

% Weed irregular trials out from responses and inputs
y = r.y(:,1);
y(r.irr) = [];

u = r.u(:,1);
u(r.irr) = [];

% Extract trajectories of interest from infStates
mu1hat = infStates(:,1,1);
sa1hat = infStates(:,1,2);
mu2    = infStates(:,2,3);
sa2    = infStates(:,2,4);
mu3    = infStates(:,3,3);

% Surprise
% ~~~~~~~~
m1hreg = mu1hat;
m1hreg(r.irr) = [];
poo = m1hreg.^u.*(1-m1hreg).^(1-u); % probability of observed outcome
surp = -log2(poo);

% Bernoulli variance (aka irreducible uncertainty, risk)
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bernv = sa1hat;
bernv(r.irr) = [];

% Inferential variance (aka informational or estimation uncertainty, ambiguity)
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
inferv = tapas_sgm(mu2, 1).*(1 -tapas_sgm(mu2, 1)).*sa2; % transform down to 1st level
inferv(r.irr) = [];

% Phasic volatility (aka environmental or unexpected uncertainty)
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pv = tapas_sgm(mu2, 1).*(1-tapas_sgm(mu2, 1)).*exp(mu3); % transform down to 1st level
pv(r.irr) = [];

% Calculate predicted log-reaction time
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
logrt = be0 +be1.*surp +be2.*bernv +be3.*inferv +be4.*pv;

% Calculate log-probabilities for non-irregular trials
% Note: 8*atan(1) == 2*pi (this is used to guard against
% errors resulting from having used pi as a variable).
reg = ~ismember(1:n,r.irr);
logp(reg) = -1/2.*log(8*atan(1).*ze) -(y-logrt).^2./(2.*ze);
yhat(reg) = logrt;
res(reg) = y-logrt;

return;

author: translationalneuromodeling

repo: tapas


text:
function vw = setMapWindow(vw, mapWindow)
%
% setMapWindow(vw,mapWindow)
%
% Sets mapWindow slider values
% ras, 01/07 -- deals w/ hidden views
% ras, 07/09 -- forces slider range to conform to the new window.
% Previously this required you to run UpdateMapWindow. This logic is not
% flexible enough for many analyses.
% jw: 08/2011 -- keep mapWinMin and mapWinMax ranges the same. if we extend
%                   one, then we extend the other.

if ~exist('vw', 'var') || isempty(vw),  vw = getCurView;  end

if checkfields(vw, 'ui', 'mapWinMin', 'sliderHandle')
	% ensure that the slider ranges allow for this map window
	sliderMin = get(vw.ui.mapWinMin.sliderHandle, 'Value');
	if sliderMin > min(mapWindow)
		set(vw.ui.mapWinMin.sliderHandle, 'Min', min(mapWindow));
        set(vw.ui.mapWinMax.sliderHandle, 'Min', min(mapWindow));
	end

	sliderMax = get(vw.ui.mapWinMax.sliderHandle, 'Value');
	if sliderMax < max(mapWindow)
		set(vw.ui.mapWinMax.sliderHandle, 'Max', max(mapWindow));
		set(vw.ui.mapWinMin.sliderHandle, 'Max', max(mapWindow));
	end

	% now set the slider values.
    setSlider(vw, vw.ui.mapWinMin, mapWindow(1));
    setSlider(vw, vw.ui.mapWinMax, mapWindow(2));

else    % hidden view
    vw.settings.mapWin = mapWindow;

end

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
%--- help for generic/simulate ---
%
%  simulate - simulates a RISE model
%
%  ::
%
%
%    [db,states,retcode] = simulate(obj,varargin)
%
%  Args:
%
%     - **obj** [rfvar|dsge|rise|svar]: model object
%
%     - **varargin** : additional arguments including but not restricted to
%
%       - **simul_periods** [integer|{100}]: number of simulation periods
%
%       - **simul_burn** [integer|{100}]: number of burn-in periods. This
%       should not be confused with forecast_conditional_sampling_burnin, which
%       is used in the sampling from the truncated multivariate normal
%       distribution.
%
%       - **simul_historical_data** [ts|struct|{''}]: historical data from
%           which the simulations are based. If empty, the simulations start at
%           the steady state.
%
%       - **simul_history_end_date** [char|integer|serial date]: last date of
%           history
%
%       - **simul_regime** [integer|vector|function handle|{[]}]: regimes for
%           which the model is simulated. When it is a function handle, then it
%           should accept as inputs y (array over all regimes),
%           regimes_1_t_1(regimes from 1 to t-1), sims_1_t_1(the simulated
%           series up to t-1),varargin (possibly further arguments to the
%           function handle). The output is a logical vector that is true for
%           the columns that are acceptable/feasible and false otherwise.
%
%       - **simul_to_time_series** [{true}|false]: if true, the output is a
%           time series, else a cell array with a matrix and information on
%           elements that help reconstruct the time series.
%
%       - **simul_honor_constraints** [true|{false}]: honor restrictions during
%           simulations. If true, agents have to be able anticipate the future.
%
%       - **simul_frwrd_back_shoot** [true|{false}]: uses an algorithm that
%       checks the constraints are satisfied at all horizons instead of just
%       one at a time.
%
%       - **simul_shock_uncertainty** [{true}|false]: draw shocks over the
%       simulation horizon.
%
%       - **simul_honor_constraints_through_switch** [true|{false}]: if true,
%       constraints are honored through the switching mechanism. In that case
%       the number of regimes should be greater than 1. If false, constraints
%       are honored through an anticipatory behavior. In this case, there
%       should be shocks that are foreseen.
%
%       - **simul_anticipate_zero** [true|{false}]: When shocks are drawn, this
%       option allows to impose that agents continue to see only the
%       contemporaneous shocks.
%
%       - **simul_bgp_deviation** [true|{false}]: When the model is
%       nonstationary, a growth component appears in the solution. This option
%       enables or disables that component.
%
%  Returns:
%     :
%
%     - **db** [struct|cell array]: if **simul_to_time_series** is true, the
%       output is a time series, else a cell array with a matrix and
%       information on elements that help reconstruct the time series.
%
%     - **states** [vector]: history of the regimes over the forecast horizon
%
%     - **retcode** [integer]: if 0, the simulation went fine. Else something
%       got wrong. In that case one can understand the problem by running
%       decipher(retcode)
%
%  Note:
%
%     - **simul_historical_data** contains the historical data as well as
%       conditional information over the forecast horizon. It may also include
%       as an alternative to **simul_regime**, a time series with name
%       **regime**, which indicates the regimes over the forecast horizon.
%
%  Example:
%
%     See also:
%
%    Other functions named simulate
%
%       arima/simulate           garch/simulate
%       conjugateblm/simulate    gjr/simulate
%       customblm/simulate       regARIMA/simulate
%       diffuseblm/simulate      sde/simulate
%       dsge/simulate            semiconjugateblm/simulate
%       dtmc/simulate            ssm/simulate
%       egarch/simulate          varm/simulate
%       empiricalblm/simulate    vecm/simulate
%

author: jmaih


text:
function [layout]=getLayouts(vp,h,w,nsamp)
% Get candidate box layout. Samples mulitple rays from each vanishing point
%layout is given by corners of the walls.

imcor=[0 h+1;0 0;w+1 0;w+1 h+1];

[vp nothing]=ordervp(vp,h,w);
%inf conditions
infcond = vp(:,1)>50*w | vp(:,2)>50*h;

%inside image conds

inim = vp(:,1)>=1 & vp(:,1)<=w & vp(:,2)>=1 & vp(:,2)<=h;
rays=cell(1,3);

for vno=1:2
    rays{vno}=[];

    %general
    if ~inim(vno)
        ll1=[vp(vno,1) imcor(1,1) vp(vno,2) imcor(1,2)];
        ll2=[vp(vno,1) imcor(2,1) vp(vno,2) imcor(2,2)];
        ll3=[vp(vno,1) imcor(3,1) vp(vno,2) imcor(3,2)];
        ll4=[vp(vno,1) imcor(4,1) vp(vno,2) imcor(4,2)];
        lla=[ll1;ll1;ll1;ll2;ll2;ll3];
        llb=[ll2;ll3;ll4;ll3;ll4;ll4];

        veca = lla(:,[2,4])-lla(:,[1,3]);
        vecb = llb(:,[2,4])-llb(:,[1,3]);
        norma=(sum(veca.*veca,2)).^.5;
        normb=(sum(vecb.*vecb,2)).^.5;
        theta = acosd(dot(veca,vecb,2)./norma./normb);
        [vv ii]=max(theta);

        dtheta=theta(ii)/nsamp;
        rays{vno}(1,:)=lla(ii,:);% two extra rays passing outside the image
        rays{vno}(2,:)=llb(ii,:);

        veca=lla(ii,[2,4])-lla(ii,[1,3]);
        vecb=[w 0];
        norma=(sum(veca.*veca,2)).^.5;
        normb=(sum(vecb.*vecb,2)).^.5;
        ang = acosd(dot(veca,vecb,2)./norma./normb);

        veca=llb(ii,[2,4])-llb(ii,[1,3]);
        vecb=[w 0];
        norma=(sum(veca.*veca,2)).^.5;
        normb=(sum(vecb.*vecb,2)).^.5;
        ang = acosd(dot(veca,vecb,2)./norma./normb);

    else
        dtheta=180/nsamp;
    end

    for ang=dtheta:dtheta:180

        pa=[];
        pb=[];
        m=tand(ang);

        if isnan(m)
            pa=[vp(vno,1) h];
            pb=[vp(vno,1) 1];
        elseif m==0
            pa=[1 vp(vno,2)];
            pb=[w vp(vno,2)];
        else
            c=vp(vno,2)-m*vp(vno,1);
            x=(h-c)/m;
            p(1,:)=[x h];%intersection with last row of image
            x=(1-c)/m;
            p(2,:)=[x 1];%intersection with 1st row of image
            y=m*w+c;
            p(3,:)=[w y];
            y=m+c;
            p(4,:)=[1 y];

            ind=find(p(:,1) <= w & p(:,1)>=1 & p(:,2)<=h & p(:,2)>=1);
            if numel(ind)==2
                pa=p(ind(1),:);
                pb=p(ind(2),:);
            end
        end

        if numel(pa) ==2 &numel(pb)==2
            rays{vno}=[rays{vno};pa(1) pb(1) pa(2) pb(2)]; %lines=[x1 x2 y1 y2];

        end
    end
end

p1 = [rays{1}(:, [1 3]) ones(size(rays{1}, 1), 1)];
p2 = [rays{1}(:, [2 4]) ones(size(rays{1}, 1), 1)];

ll1 = cross(p1, p2);
ll1 = ll1 ./ repmat(sqrt(sum(ll1.^2,2)), 1, 3);
% ll=cross([vp(2,:) 1],[vp(3,:) 1]);
ll=cross([vp(2,:) 1],[vp(3,:) 1]);
ll = ll ./ repmat(sqrt(sum(ll.^2,2)), 1, 3);
aa = cross(ll1,repmat(ll,[size(ll1,1),1]));
aa=[aa(:,1)./aa(:,3) aa(:,2)./aa(:,3)];
inds = find(aa(:,1)<vp(3,1));
if numel(inds)>0
    rays_left = rays{1}(inds,:);
else
    rays_left = [vp(1,1) vp(3,1)-10 vp(1,2) vp(3,2)];
end
inds = find(aa(:,1)>=vp(3,1));
if numel(inds)>0
    rays_right = rays{1}(inds,:);
else
    rays_right = [vp(1,1) vp(3,1)+10 vp(1,2) vp(3,2)];
end

p1 = [rays{2}(:, [1 3]) ones(size(rays{2}, 1), 1)];
p2 = [rays{2}(:, [2 4]) ones(size(rays{2}, 1), 1)];

ll1 = cross(p1, p2);
ll1 = ll1 ./ repmat(sqrt(sum(ll1.^2,2)), 1, 3);
ll=cross([vp(1,:) 1],[vp(3,:) 1]);
ll = ll ./ repmat(sqrt(sum(ll.^2,2)), 1, 3);
aa = cross(ll1,repmat(ll,[size(ll1,1),1]));
aa=[aa(:,1)./aa(:,3) aa(:,2)./aa(:,3)];
inds = find(aa(:,2)<vp(3,2));
if numel(inds)>0
    rays_top = rays{2}(inds,:);
else
    rays_top = [vp(2,1) vp(3,1) vp(2,2) vp(3,2)-10];
end
inds = find(aa(:,2)>=vp(3,2));
if numel(inds)>0
    rays_bottom = rays{2}(inds,:);
else
    rays_bottom = [vp(2,1) vp(3,1) vp(2,2) vp(3,2)+10];
end

clear rays

[uu vv ww xx]=ndgrid(1:size(rays_left,1),...
    1:size(rays_right,1),...
    1:size(rays_bottom,1),...
    1:size(rays_top,1));
uu=uu(:);
vv=vv(:);
ww=ww(:);
xx=xx(:);

[xs,ys] = IntersectLines(rays_left(uu(:),:),rays_bottom(ww(:),:));
corners_x(:,1) = xs;
corners_y(:,1) = ys;

[xs,ys] = IntersectLines(rays_left(uu(:),:),rays_top(xx(:),:));
corners_x(:,2) = xs;
corners_y(:,2) = ys;

[xs,ys] = IntersectLines(rays_right(vv(:),:),rays_top(xx(:),:));
corners_x(:,3) = xs;
corners_y(:,3) = ys;
[xs,ys] = IntersectLines(rays_right(vv(:),:),rays_bottom(ww(:),:));
corners_x(:,4) = xs;
corners_y(:,4) = ys;

corners_x = round(corners_x);
corners_y = round(corners_y);

ind=find(corners_x >=1 & corners_x <=w & corners_y >=1 & corners_y <=h );
in_img=zeros(size(corners_x));
in_img(ind)=1;

corners_x_temp = corners_x.*in_img;
corners_y_temp = corners_y.*in_img;

[unq,I,J] = unique([corners_x_temp corners_y_temp],'rows');

corners_x = corners_x(I,:);
corners_y = corners_y(I,:);

layout = [];
for i=1:4
    layout = [layout corners_x(:,i) corners_y(:,i)];
end

return;


text:
function [fv, memo]= xvalutil_proc(fv, proc, memo)
% XVALUTIL_PROC - Function used in crossvalidation

% 2014-02 Benjamin Blankertz

if nargin<3,
  memo= cell(2, 0);
end

for k= 1:length(proc),
  procline= proc{k};
  isvar= cellfun(@ischar, procline);
  nVars= min(find(~isvar))-1;
  vars= procline(1:nVars);
  vals= cell(1, nVars);
  cmd= replace_vars(procline(nVars+1:end), memo);
  [fv, vals{:}]= cmd{1}(fv, cmd{2:end});
  memo= cat(2, memo, cat(1, vars, vals));
end

function cmd= replace_vars(cmd, memo)

for n= 1:length(cmd),
  if ischar(cmd{n}) && cmd{n}(1)=='$',
    varname= cmd{n}(2:end);
    idx= strmatch(varname, memo(1,:), 'exact');
    if isempty(idx),
      error('variable %s not defined in opt.Proc', varname);
    end
    cmd{n}= memo{2,idx};
  end
end

author: bbci


text:
function [distance] = d_gaussian_wasserstein( ellipse1, ellipse2)
% D_GAUSSIAN_WASSERSTEIN gives the wasserstein distance between two ellipse
% which are interpreted as Gaussians
%
% Input:
%        ellipse1, 1x5, parameterization of one ellispe [m1 m2 alpha l1 l2]
%        ellipse2, 1x5, parameterization of the other ellispe [m1 m2 alpha l1 l2]
%
% Output:
%       distance, scalar, gaussian wasserstein distance
%
% Written by Shishan Yang

m1 = ellipse1(1:2);
alpha1 = ellipse1(3);
eigen_val1 = [ellipse1(4), ellipse1(5)];
eigen_vec1 = [cos(alpha1), -sin(alpha1); sin(alpha1), cos(alpha1)];
sigma1 = eigen_vec1*diag(eigen_val1.^2)*eigen_vec1';
sigma1 = (sigma1+sigma1')/2; % make covariance symmetric

m2 = ellipse2(1:2);
alpha2 = ellipse2(3);
eigen_val2 = [ellipse2(4),ellipse2(5)];
eigen_vec2 = [cos(alpha2), -sin(alpha2); sin(alpha2), cos(alpha2)];
sigma2 = eigen_vec2*diag(eigen_val2.^2)*eigen_vec2';
sigma2 = (sigma2+sigma2')/2; % make covariance symmetric

error_sq = norm(m1-m2)^2 + trace(sigma1 + sigma2 -2*sqrtm((sqrtm(sigma1)*sigma2*sqrtm(sigma1))));
distance = sqrt(error_sq);

end

author: Fusion-Goettingen

repo: ExtendedObjectTracking


text:
function legendAxis = findLegendAxis(obj,legendHandle)
  if verLessThan('matlab','9.0.0')
    legendAxisIndex = find(arrayfun(@(x)(isequal(handle(getappdata(x.Handle,'LegendPeerHandle')),legendHandle)),obj.State.Axis), 1);
  else
    legendAxisIndex = find(arrayfun(@(x)(isequal(handle(get(x.Handle,'Legend')),legendHandle)),obj.State.Axis), 1);
  end

  legendAxis = obj.State.Axis(legendAxisIndex).Handle;
end

author: plotly


text:
% LFCalInit - initialize calibration estimate, called by LFUtilCalLensletCam
%
% Usage:
%     CalOptions = LFCalInit( InputPath, CalOptions )
%     CalOptions = LFCalInit( InputPath )
%
% This function is called by LFUtilCalLensletCam to initialize a pose and camera model estimate
% given a set of extracted checkerboard corners.
%
% Inputs:
%
%     InputPath : Path to folder containing processed checkerboard images. Checkerboard corners must
%                 be identified prior to calling this function, by running LFCalFindCheckerCorners
%                 for example. This is demonstrated by LFUtilCalLensletCam.
%
%     [optional] CalOptions : struct controlling calibration parameters, all fields are optional
%                   .SaveResult : Set to false to perform a "dry run"
%   .CheckerCornersFnamePattern : Pattern for finding checkerboard corner files, as generated by
%                                 LFCalFindCheckerCorners; %s is a placeholder for the base filename
%             .CheckerInfoFname : Name of the output file containing the summarized checkerboard
%                                 information
%                 .CalInfoFname : Name of the file containing an initial estimate, to be refined.
%                                 Note that this parameter is automatically set in the CalOptions
%                                 struct returned by LFCalInit
%                .ForceRedoInit : Forces the function to overwrite existing results
%
% Outputs :
%
%     CalOptions struct as applied, including any default values as set up by the function.
%
%     The checkerboard info file and calibration info file are the key outputs of this function.
%
% User guide: LFToolbox.pdf
% See also:  LFUtilCalLensletCam, LFCalFindCheckerCorners, LFCalRefine

% Copyright (c) 2013-2020 Donald G. Dansereau

function CalOptions = LFCalInit( InputPath, CalOptions )

%---Defaults---
CalOptions = LFDefaultField( 'CalOptions', 'SaveResult', true );
CalOptions = LFDefaultField( 'CalOptions', 'CheckerCornersFnamePattern', '%s__CheckerCorners.mat' );
CalOptions = LFDefaultField( 'CalOptions', 'CheckerInfoFname', 'CheckerboardCorners.mat' );
CalOptions = LFDefaultField( 'CalOptions', 'CalInfoFname', 'CalInfo.json' );
CalOptions = LFDefaultField( 'CalOptions', 'ForceRedoInit', false );

%---Start by checking if this step has already been completed---
fprintf('\n===Initializing calibration process===\n');
CalInfoSaveFname = fullfile(InputPath, CalOptions.CalInfoFname);
if( ~CalOptions.ForceRedoInit && exist(CalInfoSaveFname, 'file') )
    fprintf(' ---File %s already exists, skipping---\n', CalInfoSaveFname);
    return;
end

%---Compute ideal checkerboard geometry - order matters---
IdealCheckerX = CalOptions.ExpectedCheckerSpacing_m(1) .* (0:CalOptions.ExpectedCheckerSize(1)-1);
IdealCheckerY = CalOptions.ExpectedCheckerSpacing_m(2) .* (0:CalOptions.ExpectedCheckerSize(2)-1);
[IdealCheckerY, IdealCheckerX] = ndgrid(IdealCheckerY, IdealCheckerX);
IdealChecker = cat(3,IdealCheckerX, IdealCheckerY, zeros(size(IdealCheckerX)));
IdealChecker = reshape(IdealChecker, [], 3)';

%---Crawl folder structure locating corner info files---
fprintf('\n===Locating checkerboard corner files in %s===\n', InputPath);
[CalOptions.FileList, BasePath] = LFFindFilesRecursive( InputPath, sprintf(CalOptions.CheckerCornersFnamePattern, '*') );
fprintf('Found :\n');
disp(CalOptions.FileList)

%---Initial estimate of focal length---
SkippedFileCount = 0;
ValidSuperPoseCount = 0;
ValidCheckerCount = 0;
%---Load each checkerboard corner file---
fprintf('Loading corner observations...\n');
for( iFile = 1:length(CalOptions.FileList) )
    ValidSuperPoseCount = ValidSuperPoseCount + 1;
    CurFname = CalOptions.FileList{iFile};
    [~,ShortFname] = fileparts(CurFname);
    fprintf('---%s [%3d / %3d]...', ShortFname, ValidSuperPoseCount+SkippedFileCount, length(CalOptions.FileList));

    load(fullfile(BasePath, CurFname), 'CheckerCorners', 'LFSize', 'CamInfo', 'LensletGridModel', 'DecodeOptions');
    PerImageValidCount = 0;
    for( TIdx = 1:size(CheckerCorners,1) )
        for( SIdx = 1:size(CheckerCorners,2) )
            CurChecker = CheckerCorners{TIdx, SIdx}';
            CurSize = size(CurChecker);
            CurValid = (CurSize(2) == prod(CalOptions.ExpectedCheckerSize));
            CheckerValid(ValidSuperPoseCount, TIdx, SIdx) = CurValid;

            %---For valid poses (having expected corner count), compute a homography---
            if( CurValid )
                ValidCheckerCount = ValidCheckerCount + 1;
                PerImageValidCount = PerImageValidCount + 1;

                %--- reorient to expected ---
                Centroid = mean( CurChecker,2 );
                IsTopLeft = all(CurChecker(:,1) < Centroid);
                IsTopRight = (CurChecker(1,1) > Centroid(1) && CurChecker(2,1) < Centroid(2));
				IsBotLeft = (CurChecker(1,1) < Centroid(1) && CurChecker(2,1) > Centroid(2));
				IsBotRight = all(CurChecker(:,1) > Centroid);
                if( IsTopRight )
                    CurChecker = reshape(CurChecker, [2, CalOptions.ExpectedCheckerSize]);
                    CurChecker = CurChecker(:, end:-1:1, :);
                    CurChecker = permute(CurChecker, [1,3,2]);
                    CurChecker = reshape(CurChecker, 2, []);
				elseif( IsBotLeft )
                    CurChecker = reshape(CurChecker, [2, CalOptions.ExpectedCheckerSize]);
                    CurChecker = CurChecker(:, :, end:-1:1);
                    CurChecker = permute(CurChecker, [1,3,2]);
                    CurChecker = reshape(CurChecker, 2, []);
				elseif( IsBotRight )
                    CurChecker = reshape(CurChecker, [2, CalOptions.ExpectedCheckerSize]);
                    CurChecker = CurChecker(:, end:-1:1, end:-1:1);
                    CurChecker = reshape(CurChecker, 2, []);
				end
                IsTopLeft = all(CurChecker(:,1) < Centroid);
                assert( IsTopLeft, 'Error: unexpected point order from detectCheckerboardPoints' );

                CheckerObs{ValidSuperPoseCount, TIdx, SIdx} = CurChecker;
            end
        end
    end
    CalOptions.ValidSubimageCount(iFile) = PerImageValidCount;
    fprintf(' %d / %d valid.\n', PerImageValidCount, prod(LFSize(1:2)));
end

%---Compute homography for each subcam pose---
fprintf('Initial estimate of focal length...\n');
ValidCheckerCount = 0;
for( iFile = 1:length(CalOptions.FileList) )
    for( TIdx = 1:size(CheckerObs,3) )
        for( SIdx = 1:size(CheckerObs,2) )
			CurChecker = CheckerObs{iFile, TIdx, SIdx};
			if( ~isempty(CurChecker) )
				ValidCheckerCount = ValidCheckerCount + 1;
				%---Compute homography for each subcam pose---
				CurH = compute_homography( CurChecker, IdealChecker(1:2,:) );
				H(ValidCheckerCount, :,:) = CurH;
			end
        end
    end
    fprintf('.');
end
fprintf('\n');

A = [];
b = [];

%---Initialize principal point at the center of the image---
% This section of code is based heavily on code from the Camera Calibration Toolbox for Matlab by
% Jean-Yves Bouguet
CInit = LFSize([4,3])'/2 - 0.5;
RecenterH = [1, 0, -CInit(1); 0, 1, -CInit(2); 0, 0, 1];

for iHomography = 1:size(H,1)
    CurH = squeeze(H(iHomography,:,:));
    CurH = RecenterH * CurH;

    %---Extract vanishing points (direct and diagonal)---
    V_hori_pix = CurH(:,1);
    V_vert_pix = CurH(:,2);
    V_diag1_pix = (CurH(:,1)+CurH(:,2))/2;
    V_diag2_pix = (CurH(:,1)-CurH(:,2))/2;

    V_hori_pix = V_hori_pix/norm(V_hori_pix);
    V_vert_pix = V_vert_pix/norm(V_vert_pix);
    V_diag1_pix = V_diag1_pix/norm(V_diag1_pix);
    V_diag2_pix = V_diag2_pix/norm(V_diag2_pix);

    a1 = V_hori_pix(1);
    b1 = V_hori_pix(2);
    c1 = V_hori_pix(3);

    a2 = V_vert_pix(1);
    b2 = V_vert_pix(2);
    c2 = V_vert_pix(3);

    a3 = V_diag1_pix(1);
    b3 = V_diag1_pix(2);
    c3 = V_diag1_pix(3);

    a4 = V_diag2_pix(1);
    b4 = V_diag2_pix(2);
    c4 = V_diag2_pix(3);

    CurA = [a1*a2, b1*b2; a3*a4, b3*b4];
    CurB = -[c1*c2; c3*c4];

    if( isempty(find(isnan(CurA), 1)) && isempty(find(isnan(CurB), 1)) )
        A = [A; CurA];
        b = [b; CurB];
    end
end

FocInit = sqrt(b'*(sum(A')') / (b'*b)) * ones(2,1);
fprintf('Init focal length est: %.2f, %.2f\n', FocInit);

%---Initial estimate of extrinsics---
fprintf('\nInitial estimate of extrinsics...\n');

for( iSuperPoseIdx = 1:ValidSuperPoseCount )
    fprintf('---[%d / %d]', iSuperPoseIdx, ValidSuperPoseCount);
    for( TIdx = 1:size(CheckerCorners,1) )
        fprintf('.');
        for( SIdx = 1:size(CheckerCorners,2) )
            if( ~CheckerValid(iSuperPoseIdx, TIdx, SIdx) )
                continue;
            end
            CurChecker = CheckerObs{iSuperPoseIdx, TIdx, SIdx};

            [CurRot, CurTrans] = compute_extrinsic_init(CurChecker, IdealChecker, FocInit, CInit, zeros(1,5), 0);
            [CurRot, CurTrans] = compute_extrinsic_refine(CurRot, CurTrans, CurChecker, IdealChecker, FocInit, CInit, zeros(1,5), 0,20,1000000);

            RotVals{iSuperPoseIdx, TIdx, SIdx} = CurRot;
            TransVals{iSuperPoseIdx, TIdx, SIdx} = CurTrans;
        end
    end

    %---Approximate each superpose as the median of its sub-poses---
    % note the approximation in finding the mean orientation: mean of rodrigues... works because all
    % sub-orientations within a superpose are nearly identical.
    MeanRotVals(iSuperPoseIdx,:) = median([RotVals{iSuperPoseIdx, :, :}], 2);
    MeanTransVals(iSuperPoseIdx,:) = median([TransVals{iSuperPoseIdx, :, :}], 2);
    fprintf('\n');

    %---Track the apparent "baseline" of the camera at each pose---
    CurDist = bsxfun(@minus, [TransVals{iSuperPoseIdx, :, :}], MeanTransVals(iSuperPoseIdx,:)');
    CurAbsDist = sqrt(sum(CurDist.^2));
    % store as estimated diameter; the 3/2 comes from the mean radius of points on a disk (2R/3)
    BaselineApprox(iSuperPoseIdx) = 2 * 3/2 * mean(CurAbsDist);
end

%---Initialize the superpose estimates---
EstCamPosesV = [MeanTransVals, MeanRotVals];

%---Estimate full intrinsic matrix---
ST_IJ_SlopeApprox = mean(BaselineApprox) ./ (LFSize(2:-1:1)-1);
UV_KL_SlopeApprox = 1./FocInit';

EstCamIntrinsicsH = eye(5);
EstCamIntrinsicsH(1,1) = ST_IJ_SlopeApprox(1);
EstCamIntrinsicsH(2,2) = ST_IJ_SlopeApprox(2);
EstCamIntrinsicsH(3,3) = UV_KL_SlopeApprox(1);
EstCamIntrinsicsH(4,4) = UV_KL_SlopeApprox(2);

% Force central ray as s,t,u,v = 0, note all indices start at 1, not 0
EstCamIntrinsicsH = LFRecenterIntrinsics( EstCamIntrinsicsH, LFSize );

fprintf('\nInitializing estimate of camera intrinsics to: \n');
disp(EstCamIntrinsicsH);

%---Start with no distortion estimate---
EstCamDistortionV = [];

%---Optionally save the results---
if( CalOptions.SaveResult )
    TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
    GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);

    CheckerSaveFname = fullfile(BasePath, CalOptions.CheckerInfoFname);
    fprintf('\nSaving to %s...\n', CheckerSaveFname);
    save(CheckerSaveFname, 'GeneratedByInfo', 'CalOptions', 'CheckerObs', 'IdealChecker', 'LFSize', 'CamInfo', 'LensletGridModel', 'DecodeOptions');

    fprintf('Saving to %s...\n', CalInfoSaveFname);
    LFWriteMetadata(CalInfoSaveFname, LFVar2Struct(GeneratedByInfo, LensletGridModel, EstCamIntrinsicsH, EstCamDistortionV, EstCamPosesV, CamInfo, CalOptions, DecodeOptions));
end

fprintf(' ---Calibration initialization done---\n');

repo: LFToolbox


text:
RGB = imread('saturn.png');
I = rgb2gray(RGB);
I2G = imnoise(I,'gaussian', 0.02);
I2 = imnoise(I,'salt & pepper', 0.02);
I20 = imnoise(I,'salt & pepper', 0.2);
figure, imshow(RGB);
figure, imshow(I);
figure, imshow(I2G);
figure, imshow(I2);
figure, imshow(I20);

author: UtkarshPathrabe