text:
%% PTspecUIcontrol - ui controls for spectral analyses plots

% ----------------------------------------------------------------------------------
% "THE BEER-WARE LICENSE" (Revision 42):
% <brian.white@queensu.ca> wrote this file. As long as you retain this notice you
% can do whatever you want with this stuff. If we meet some day, and you think
% this stuff is worth it, you can buy me a beer in return. -Brian White
% ----------------------------------------------------------------------------------

if ~isempty(fnameMaster)

%%% tooltips
TooltipString_specRun=['Run current spectral configuration',...
    newline, 'Warning: Set subsampling dropdown @ or < medium for faster processing.'];
TooltipString_presets=['Choose from a selection of PRESET configurations'];
TooltipString_cmap=['Choose from a selection of colormaps'];
TooltipString_smooth=['Choose amount of smoothing'];
TooltipString_2d=['Show 2 dimensional plots'];
TooltipString_user=['Choose the variable you wish to plot (consider PRESETs dropdown menu above for quick configurations)'];
TooltipString_sub100=['Zoom data to show sub 100Hz details',...
    newline, 'Typically used to see propwash or mid-throttle vibration in e.g. Gyro/Pterm/PIDerror'];
TooltipString_phase=['Estimated phase delay based on cross-correlation technique.',...
    newline, 'Note: estimate is most reliable with sufficient stick input so as to modulate the gyro and dterm.',...
    newline, 'Also requires that betaflight debug_mode is set to ''GYRO_SCALED'' '];
TooltipString_scale=['Colormap scaling. Note, the default is set such that an optimally filtered gyro ',...
    newline, 'should show little to no activity with the exception of a sub 100Hz band across throttle.',...
    newline, 'Dterm and motor outputs will typically be noisier, so sometimes scale adjustments ',...
    newline, 'are useful to see details. Otherwise, scaling should be the same when making comparisons'];
TooltipString_controlFreqCutoff=['Hz = Freq cutoff bounds for sub100Hz mean/peak analysis window.',...
    newline  'Changing this will move the yellow dashed lines representing this range (only in sub100Hz view).'];

%%%

% define
smat=[];%string
ampmat=[];%spec matrix
amp2d=[];%spec 2d
freq=[];% freq

% only need to call once to compute extra colormaps
PTcolormap;
SpecLineCols=[];
SpecLineCols(:,:,1) = [colorA; colorA; colorA; colorA];
SpecLineCols(:,:,2) = [colorA; colorA; colorB; colorB];
SpecLineCols(:,:,3) = [colorA; colorB; colorC; colorD];

clear posInfo.SpecPos
cols=[0.04 0.261 0.482 0.703];
rows=[0.64 0.35 0.06];
k=0;
for c=1:4
    for r=1:3
        k=k+1;
        posInfo.SpecPos(k,:)=[cols(c) rows(r) 0.18 0.24];
    end
end

posInfo.computeSpec=            [.896 .87 .0455 .026];
posInfo.resetSpec=              [.942 .87 .0455 .026];
posInfo.saveFig1=               [.8965 .845 .0455 .026];
posInfo.saveSettings1=          [.942 .845 .0455 .026];

posInfo.specPresets=            [.8945 .802 .096 .04];
posInfo.ColormapSelect=         [.8945 .778 .096 .04];
posInfo.smooth_select =         [.8945 .754 .096 .04];
posInfo.controlFreq1Cutoff =    [.91 .715 .023 .025];
posInfo.controlFreq2Cutoff =    [.945 .715 .023 .025];
posInfo.controlFreqCutoff_text =[.9 .74 .07 .025];
posInfo.checkbox2d=             [.91 .685 .04 .02];
posInfo.checkboxPSD=            [.94 .685 .04 .02];

posInfo.AphasedelayText1=[.06 .984 .14 .02];
posInfo.AphasedelayText2=[.282 .984 .14 .02];
posInfo.AphasedelayText3=[.504 .984 .14 .02];
posInfo.AphasedelayText4=[.726 .984 .14 .02];

posInfo.hCbar1pos=[0.04 0.89 0.18  0.02];
posInfo.hCbar2pos=[0.262 0.89 0.18  0.02];
posInfo.hCbar3pos=[0.484 0.89 0.18  0.02];
posInfo.hCbar4pos=[0.706 0.89 0.18  0.02];

posInfo.hDropdn1pos=[0.08 0.97 0.095   0.01];
posInfo.hDropdn2pos=[0.302 0.97 0.095   0.01];
posInfo.hDropdn3pos=[0.524 0.97 0.095   0.01];
posInfo.hDropdn4pos=[0.746 0.97 0.095   0.01];

posInfo.fDropdn1pos=[0.08 0.946 0.095  0.01];
posInfo.fDropdn2pos=[0.302 0.946 0.095  0.01];
posInfo.fDropdn3pos=[0.524 0.946 0.095  0.01];
posInfo.fDropdn4pos=[0.746 0.946 0.095  0.01];

posInfo.Sub100HzCheck1=[0.175 0.945 .06 .025];
posInfo.Sub100HzCheck2=[.4 .945 .06 .025];
posInfo.Sub100HzCheck3=[0.62 0.945 .06 .025];
posInfo.Sub100HzCheck4=[.84 .945 .06 .025];

posInfo.climMax_text = [.01 .913 .025 .024];
posInfo.climMax_input = [.01 .888 .025 .024];
posInfo.climMax_text2 = [.232 .913 .025 .024];
posInfo.climMax_input2 = [.232 .888 .025 .024];
posInfo.climMax_text3 = [.455 .913 .025 .024];
posInfo.climMax_input3 = [.455 .888 .025 .024];
posInfo.climMax_text4 = [.677 .913 .025 .024];
posInfo.climMax_input4 = [.677 .888 .025 .024];
climScale=[0.5 0.5 0.5 0.5; 10 10 10 10];
Flim1=20; % 3.3333Hz steps
Flim2=60;

PTspecfig=figure(2);
set(PTspecfig, 'units','normalized','outerposition',[.1 .1 .75 .8])
PTspecfig.NumberTitle='off';
PTspecfig.Name= ['PIDtoolbox (' PtbVersion ') - Frequency x Throttle Spectrogram'];
PTspecfig.InvertHardcopy='off';
set(PTspecfig,'color',bgcolor);

dcm_obj2 = datacursormode(PTspecfig);
set(dcm_obj2,'UpdateFcn',@PTdatatip);

specCrtlpanel = uipanel('Title','Params','FontSize',fontsz,...
              'BackgroundColor',[.95 .95 .95],...
              'Position',[.89 .68 .105 .24]);

%%% PRESET CONFIGURATIONS

% guiHandles.FileNum = uicontrol(PTspecfig,'Style','popupmenu','string',[fnameMaster],'TooltipString', [TooltipString_FileNum],...
%     'fontsize',fontsz, 'units','normalized','outerposition', [posInfo.fnameASpec],'callback','PTplotSpec;');

guiHandlesSpec.specPresets = uicontrol(PTspecfig,'Style','popupmenu','string',{'Presets:'; '1. Gyro prefilt | Gyro | Dterm prefilt | Dterm' ;  '2. Gyro prefilt | Gyro | Pterm | Dterm' ; '3. Gyro | Dterm | Set point | PID error' ; '4. A|A|B|B Gyro prefilt | Gyro' ; '5. A|A|B|B Dterm prefilt | Dterm' ; '6. A|B|C|D Gyro prefilt ' ;'7. A|B|C|D Gyro '; '8. A|B|C|D Dterm '; '9. A|B|C|D PID error'},...
    'fontsize',fontsz,'TooltipString', [TooltipString_presets], 'units','normalized','outerposition', [posInfo.specPresets],'callback',...
    ['if guiHandlesSpec.specPresets.Value == 1, guiHandlesSpec.SpecSelect{1}.Value=1; guiHandlesSpec.SpecSelect{2}.Value=1; guiHandlesSpec.SpecSelect{3}.Value=1; guiHandlesSpec.SpecSelect{4}.Value=1; guiHandlesSpec.Sub100HzCheck{1}.Value=0; guiHandlesSpec.Sub100HzCheck{2}.Value=0; guiHandlesSpec.Sub100HzCheck{3}.Value=0; guiHandlesSpec.Sub100HzCheck{4}.Value=0; end;',...
     'if guiHandlesSpec.specPresets.Value == 2, guiHandlesSpec.SpecSelect{1}.Value=3; guiHandlesSpec.SpecSelect{2}.Value=2; guiHandlesSpec.SpecSelect{3}.Value=8; guiHandlesSpec.SpecSelect{4}.Value=7; guiHandlesSpec.Sub100HzCheck{1}.Value=0; guiHandlesSpec.Sub100HzCheck{2}.Value=0; guiHandlesSpec.Sub100HzCheck{3}.Value=0; guiHandlesSpec.Sub100HzCheck{4}.Value=0; end;',...
     'if guiHandlesSpec.specPresets.Value == 3, guiHandlesSpec.SpecSelect{1}.Value=3; guiHandlesSpec.SpecSelect{2}.Value=2; guiHandlesSpec.SpecSelect{3}.Value=6; guiHandlesSpec.SpecSelect{4}.Value=7; guiHandlesSpec.Sub100HzCheck{1}.Value=0; guiHandlesSpec.Sub100HzCheck{2}.Value=0; guiHandlesSpec.Sub100HzCheck{3}.Value=0; guiHandlesSpec.Sub100HzCheck{4}.Value=0; end;',...
     'if guiHandlesSpec.specPresets.Value == 4, guiHandlesSpec.SpecSelect{1}.Value=2; guiHandlesSpec.SpecSelect{2}.Value=7; guiHandlesSpec.SpecSelect{3}.Value=5; guiHandlesSpec.SpecSelect{4}.Value=4; guiHandlesSpec.Sub100HzCheck{1}.Value=0; guiHandlesSpec.Sub100HzCheck{2}.Value=0; guiHandlesSpec.Sub100HzCheck{3}.Value=1; guiHandlesSpec.Sub100HzCheck{4}.Value=1; end;',...
     'if guiHandlesSpec.specPresets.Value == 5, guiHandlesSpec.SpecSelect{1}.Value=3; guiHandlesSpec.SpecSelect{2}.Value=2; guiHandlesSpec.SpecSelect{3}.Value=3; guiHandlesSpec.SpecSelect{4}.Value=2; guiHandlesSpec.Sub100HzCheck{1}.Value=0; guiHandlesSpec.Sub100HzCheck{2}.Value=0; guiHandlesSpec.Sub100HzCheck{3}.Value=0; guiHandlesSpec.Sub100HzCheck{4}.Value=0; end;',...
     'if guiHandlesSpec.specPresets.Value == 6, guiHandlesSpec.SpecSelect{1}.Value=8; guiHandlesSpec.SpecSelect{2}.Value=7; guiHandlesSpec.SpecSelect{3}.Value=8; guiHandlesSpec.SpecSelect{4}.Value=7; guiHandlesSpec.Sub100HzCheck{1}.Value=0; guiHandlesSpec.Sub100HzCheck{2}.Value=0; guiHandlesSpec.Sub100HzCheck{3}.Value=0; guiHandlesSpec.Sub100HzCheck{4}.Value=0; end;',...
     'if guiHandlesSpec.specPresets.Value == 7, guiHandlesSpec.SpecSelect{1}.Value=3; guiHandlesSpec.SpecSelect{2}.Value=3; guiHandlesSpec.SpecSelect{3}.Value=3; guiHandlesSpec.SpecSelect{4}.Value=3; guiHandlesSpec.Sub100HzCheck{1}.Value=0; guiHandlesSpec.Sub100HzCheck{2}.Value=0; guiHandlesSpec.Sub100HzCheck{3}.Value=0; guiHandlesSpec.Sub100HzCheck{4}.Value=0; end;',...
     'if guiHandlesSpec.specPresets.Value == 8, guiHandlesSpec.SpecSelect{1}.Value=2; guiHandlesSpec.SpecSelect{2}.Value=2; guiHandlesSpec.SpecSelect{3}.Value=2; guiHandlesSpec.SpecSelect{4}.Value=2; guiHandlesSpec.Sub100HzCheck{1}.Value=0; guiHandlesSpec.Sub100HzCheck{2}.Value=0; guiHandlesSpec.Sub100HzCheck{3}.Value=0; guiHandlesSpec.Sub100HzCheck{4}.Value=0; end;',...
     'if guiHandlesSpec.specPresets.Value == 9, guiHandlesSpec.SpecSelect{1}.Value=7; guiHandlesSpec.SpecSelect{2}.Value=7; guiHandlesSpec.SpecSelect{3}.Value=7; guiHandlesSpec.SpecSelect{4}.Value=7; guiHandlesSpec.Sub100HzCheck{1}.Value=0; guiHandlesSpec.Sub100HzCheck{2}.Value=0; guiHandlesSpec.Sub100HzCheck{3}.Value=0; guiHandlesSpec.Sub100HzCheck{4}.Value=0; end;',...
     'if guiHandlesSpec.specPresets.Value == 10, guiHandlesSpec.SpecSelect{1}.Value=4; guiHandlesSpec.SpecSelect{2}.Value=4; guiHandlesSpec.SpecSelect{3}.Value=4; guiHandlesSpec.SpecSelect{4}.Value=4; guiHandlesSpec.Sub100HzCheck{1}.Value=0; guiHandlesSpec.Sub100HzCheck{2}.Value=0; guiHandlesSpec.Sub100HzCheck{3}.Value=0; guiHandlesSpec.Sub100HzCheck{4}.Value=0; end;']);

guiHandlesSpec.computeSpec = uicontrol(PTspecfig,'string','Run','fontsize',fontsz,'TooltipString', [TooltipString_specRun],'units','normalized','outerposition',[posInfo.computeSpec],...
    'callback','PTplotSpec;');
guiHandlesSpec.computeSpec.ForegroundColor=[colRun];

guiHandlesSpec.resetSpec = uicontrol(PTspecfig,'string','Reset','fontsize',fontsz,'TooltipString', ['Reset Spectral Tool'],'units','normalized','outerposition',[posInfo.resetSpec],...
    'callback',' for k = 1 :12, delete(subplot(''position'',posInfo.SpecPos(k,:))), end; guiHandlesSpec.specPresets.Value = 1; PTspecUIcontrol; set(PTspecfig, ''pointer'', ''arrow'');');
guiHandlesSpec.resetSpec.ForegroundColor=[cautionCol];

guiHandlesSpec.checkbox2d =uicontrol(PTspecfig,'Style','checkbox','String','2D','fontsize',fontsz,'TooltipString', [TooltipString_2d],...
    'units','normalized','BackgroundColor',bgcolor,'outerposition',[posInfo.checkbox2d],'callback','if ~isempty(fnameMaster), end;updateSpec=1;PTplotSpec;');

guiHandlesSpec.checkboxPSD =uicontrol(PTspecfig,'Style','checkbox','String','PSD','fontsize',fontsz,'TooltipString', ['Power Spectral Density'],...
    'units','normalized','BackgroundColor',bgcolor,'outerposition',[posInfo.checkboxPSD],'callback', 'PTplotSpec;');
guiHandlesSpec.checkboxPSD.Value = 0;

guiHandlesSpec.controlFreqCutoff_text = uicontrol(PTspecfig,'style','text','string','freq lims Hz','fontsize',fontsz,'TooltipString',[TooltipString_controlFreqCutoff],'units','normalized','BackgroundColor',bgcolor,'outerposition',[posInfo.controlFreqCutoff_text]);
guiHandlesSpec.controlFreq1Cutoff = uicontrol(PTspecfig,'style','edit','string',[num2str(round(Flim1))],'fontsize',fontsz,'TooltipString',[TooltipString_controlFreqCutoff],'units','normalized','outerposition',[posInfo.controlFreq1Cutoff],...
     'callback','@textinput_call2; Flim1=round(str2num(guiHandlesSpec.controlFreq1Cutoff.String));updateSpec=1;PTplotSpec;');
guiHandlesSpec.controlFreq2Cutoff = uicontrol(PTspecfig,'style','edit','string',[num2str(round(Flim2))],'fontsize',fontsz,'TooltipString',[TooltipString_controlFreqCutoff],'units','normalized','outerposition',[posInfo.controlFreq2Cutoff],...
     'callback','@textinput_call2; Flim2=round(str2num(guiHandlesSpec.controlFreq2Cutoff.String));updateSpec=1;PTplotSpec;');

guiHandlesSpec.saveFig1 = uicontrol(PTspecfig,'string','Save Fig','fontsize',fontsz,'TooltipString',[TooltipString_saveFig],'units','normalized','ForegroundColor',[saveCol],'outerposition',[posInfo.saveFig1],...
    'callback','guiHandlesSpec.saveFig1.FontWeight=''bold'';PTsaveFig;guiHandlesSpec.saveFig1.FontWeight=''normal'';');

guiHandlesSpec.saveSettings1 = uicontrol(PTspecfig,'string','Save Settings','fontsize',fontsz, 'TooltipString',['Save current settings to PTB defaults' ], 'units','normalized','outerposition',[posInfo.saveSettings1],...
    'callback','guiHandlesSpec.saveSettings1.FontWeight=''bold'';PTsaveSettings; guiHandlesSpec.saveSettings1.FontWeight=''normal'';');
guiHandlesSpec.saveSettings1.ForegroundColor=[saveCol];

guiHandlesSpec.Sub100HzCheck{1} =uicontrol(PTspecfig,'Style','checkbox','String','<100Hz','fontsize',fontsz,'TooltipString', [TooltipString_sub100], 'units','normalized','BackgroundColor',bgcolor,'outerposition',[posInfo.Sub100HzCheck1],'callback','if ~isempty(fnameMaster), end;updateSpec=1;PTplotSpec;');
guiHandlesSpec.Sub100HzCheck{2} =uicontrol(PTspecfig,'Style','checkbox','String','<100Hz','fontsize',fontsz,'TooltipString', [TooltipString_sub100], 'units','normalized','BackgroundColor',bgcolor,'outerposition',[posInfo.Sub100HzCheck2],'callback','if ~isempty(fnameMaster), end;updateSpec=1;PTplotSpec;');
guiHandlesSpec.Sub100HzCheck{3} =uicontrol(PTspecfig,'Style','checkbox','String','<100Hz','fontsize',fontsz,'TooltipString', [TooltipString_sub100], 'units','normalized','BackgroundColor',bgcolor,'outerposition',[posInfo.Sub100HzCheck3],'callback','if ~isempty(fnameMaster), end;updateSpec=1;PTplotSpec;');
guiHandlesSpec.Sub100HzCheck{4} =uicontrol(PTspecfig,'Style','checkbox','String','<100Hz','fontsize',fontsz,'TooltipString', [TooltipString_sub100], 'units','normalized','BackgroundColor',bgcolor,'outerposition',[posInfo.Sub100HzCheck4],'callback','if ~isempty(fnameMaster), end;updateSpec=1;PTplotSpec;');

% create string list for SpecSelect
sA={'NONE','Gyro','Gyro prefilt','PID error','Set point','Pterm','Dterm','Dterm prefilt','PIDsum'};

guiHandlesSpec.SpecSelect{1} = uicontrol(PTspecfig,'Style','popupmenu','string',sA, 'fontsize',fontsz,'TooltipString',[TooltipString_user],'units','normalized','outerposition', [posInfo.hDropdn1pos]);
guiHandlesSpec.SpecSelect{2} = uicontrol(PTspecfig,'Style','popupmenu','string',sA, 'fontsize',fontsz,'TooltipString',[TooltipString_user],'units','normalized','outerposition', [posInfo.hDropdn2pos]);
guiHandlesSpec.SpecSelect{3} = uicontrol(PTspecfig,'Style','popupmenu','string',sA,  'fontsize',fontsz,'TooltipString',[TooltipString_user],'units','normalized','outerposition', [posInfo.hDropdn3pos]);
guiHandlesSpec.SpecSelect{4} = uicontrol(PTspecfig,'Style','popupmenu','string',sA, 'fontsize',fontsz,'TooltipString',[TooltipString_user],'units','normalized','outerposition', [posInfo.hDropdn4pos]);

guiHandlesSpec.FileSelect{1} = uicontrol(PTspecfig,'Style','popupmenu','string',[fnameMaster], 'fontsize',fontsz,'TooltipString',[TooltipString_user],'units','normalized','outerposition', [posInfo.fDropdn1pos]);
guiHandlesSpec.FileSelect{2} = uicontrol(PTspecfig,'Style','popupmenu','string',[fnameMaster], 'fontsize',fontsz,'TooltipString',[TooltipString_user],'units','normalized','outerposition', [posInfo.fDropdn2pos]);
guiHandlesSpec.FileSelect{3} = uicontrol(PTspecfig,'Style','popupmenu','string',[fnameMaster], 'fontsize',fontsz,'TooltipString',[TooltipString_user],'units','normalized','outerposition', [posInfo.fDropdn3pos]);
guiHandlesSpec.FileSelect{4} = uicontrol(PTspecfig,'Style','popupmenu','string',[fnameMaster], 'fontsize',fontsz,'TooltipString',[TooltipString_user],'units','normalized','outerposition', [posInfo.fDropdn4pos]);

guiHandlesSpec.smoothFactor_select = uicontrol(PTspecfig,'style','popupmenu','string',{'smoothing low' 'smoothing low-med' 'smoothing medium' 'smoothing med-high' 'smoothing high'},'fontsize',fontsz,'TooltipString', [TooltipString_smooth], 'units','normalized','outerposition',[posInfo.smooth_select],...
     'callback','@selection2;updateSpec=1;PTplotSpec;');

guiHandlesSpec.climMax_text = uicontrol(PTspecfig,'style','text','string','scale','fontsize',fontsz,'TooltipString',[TooltipString_scale],'units','normalized','BackgroundColor',bgcolor,'outerposition',[posInfo.climMax_text]);
guiHandlesSpec.climMax_input = uicontrol(PTspecfig,'style','edit','string',[num2str(climScale(guiHandlesSpec.checkboxPSD.Value+1, 1))],'fontsize',fontsz,'TooltipString',[TooltipString_scale],'units','normalized','outerposition',[posInfo.climMax_input],...
     'callback','@textinput_call2; climScale(guiHandlesSpec.checkboxPSD.Value+1, 1)=str2num(guiHandlesSpec.climMax_input.String);updateSpec=1;PTplotSpec;');

 guiHandlesSpec.climMax_text2 = uicontrol(PTspecfig,'style','text','string','scale','fontsize',fontsz,'TooltipString',[TooltipString_scale],'units','normalized','BackgroundColor',bgcolor,'outerposition',[posInfo.climMax_text2]);
guiHandlesSpec.climMax_input2 = uicontrol(PTspecfig,'style','edit','string',[num2str(climScale(guiHandlesSpec.checkboxPSD.Value+1, 2))],'fontsize',fontsz,'TooltipString',[TooltipString_scale],'units','normalized','outerposition',[posInfo.climMax_input2],...
     'callback','@textinput_call2; climScale(guiHandlesSpec.checkboxPSD.Value+1, 2)=str2num(guiHandlesSpec.climMax_input2.String);updateSpec=1;PTplotSpec;');

 guiHandlesSpec.climMax_text3 = uicontrol(PTspecfig,'style','text','string','scale','fontsize',fontsz,'TooltipString',[TooltipString_scale],'units','normalized','BackgroundColor',bgcolor,'outerposition',[posInfo.climMax_text3]);
guiHandlesSpec.climMax_input3 = uicontrol(PTspecfig,'style','edit','string',[num2str(climScale(guiHandlesSpec.checkboxPSD.Value+1, 3))],'fontsize',fontsz,'TooltipString',[TooltipString_scale],'units','normalized','outerposition',[posInfo.climMax_input3],...
     'callback','@textinput_call2; climScale(guiHandlesSpec.checkboxPSD.Value+1, 3)=str2num(guiHandlesSpec.climMax_input3.String);updateSpec=1;PTplotSpec;');

 guiHandlesSpec.climMax_text4 = uicontrol(PTspecfig,'style','text','string','scale','fontsize',fontsz,'TooltipString',[TooltipString_scale],'units','normalized','BackgroundColor',bgcolor,'outerposition',[posInfo.climMax_text4]);
guiHandlesSpec.climMax_input4 = uicontrol(PTspecfig,'style','edit','string',[num2str(climScale(guiHandlesSpec.checkboxPSD.Value+1, 4))],'fontsize',fontsz,'TooltipString',[TooltipString_scale],'units','normalized','outerposition',[posInfo.climMax_input4],...
     'callback','@textinput_call2; climScale(guiHandlesSpec.checkboxPSD.Value+1, 4)=str2num(guiHandlesSpec.climMax_input4.String);updateSpec=1;PTplotSpec;');

 guiHandlesSpec.ColormapSelect = uicontrol(PTspecfig,'Style','popupmenu','string',{'parula','jet','hot','cool','gray','bone','copper','viridis','linear-RED','linear-GREY'},...
    'fontsize',fontsz,'TooltipString', [TooltipString_cmap], 'units','normalized','outerposition',[posInfo.ColormapSelect],'callback','@selection2;updateSpec=1; PTplotSpec;');
guiHandlesSpec.ColormapSelect.Value=3;% jet 2 hot 3 viridis 8

try guiHandlesSpec.SpecSelect{1}.Value = defaults.Values(find(strcmp(defaults.Parameters, 'FreqXthr-Column1'))), catch, guiHandlesSpec.SpecSelect{1}.Value=3; end
try guiHandlesSpec.SpecSelect{2}.Value = defaults.Values(find(strcmp(defaults.Parameters, 'FreqXthr-Column2'))), catch, guiHandlesSpec.SpecSelect{2}.Value=2; end
try guiHandlesSpec.SpecSelect{3}.Value = defaults.Values(find(strcmp(defaults.Parameters, 'FreqXthr-Column3'))), catch, guiHandlesSpec.SpecSelect{3}.Value=8; end
try guiHandlesSpec.SpecSelect{4}.Value = defaults.Values(find(strcmp(defaults.Parameters, 'FreqXthr-Column4'))), catch, guiHandlesSpec.SpecSelect{4}.Value=7; end
try guiHandlesSpec.specPresets.Value = defaults.Values(find(strcmp(defaults.Parameters, 'FreqXthr-Preset'))), catch, guiHandlesSpec.specPresets.Value = 1; end
try guiHandlesSpec.ColormapSelect.Value = defaults.Values(find(strcmp(defaults.Parameters, 'FreqXthr-Colormap'))), catch, guiHandlesSpec.ColormapSelect.Value = 3; end
try guiHandlesSpec.smoothFactor_select.Value = defaults.Values(find(strcmp(defaults.Parameters, 'FreqXthr-Smoothing'))), catch, guiHandlesSpec.smoothFactor_select.Value = 3; end

else
     warndlg('Please select file(s)');
end

% functions
function selection2(src,event)
    val = c.Value;
    str = c.String;
    str{val};
end

function getList2(hObj,event)
v=get(hObj,'value')
end

function textinput_call2(src,eventdata)
str=get(src,'String');
    if isempty(str2num(str))
        set(src,'string','0');
        warndlg('Input must be numerical');
    end
end

repo: PIDtoolbox


text:
function [result, M] = warp_pnt(input, target, method);

% WARP_PNT determine intermediate positions using warping (deformation)
% the input cloud of points is warped to match the target.
% The strategy is to start with simpelest linear warp, followed by a more
% elaborate linear warp, which then is followed by the nonlinear warps up
% to the desired order.
%
% [result, M] = warp_pnt(input, target, method)
%     input          contains the Nx3 measured 3D positions
%     target         contains the Nx3 template 3D positions
%     method         should be empty or any of 'nonlin1', 'nonlin2' ... 'nonlin5'
%
% The default is a traditional linear warp with rescaling in each
% dimension. Optionally you can select a nonlinear warp of the 1st (affine)
% up to the 5th order.
%
% This function depends on the OPTIM and WARPING toolboxes.

% Copyright (C) 2000-2005, Robert Oostenveld
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% $Log: warp_optim.m,v $
% Revision 1.1  2009/01/30 04:02:13  arno
% *** empty log message ***
%
% Revision 1.7  2006/11/23 11:34:51  roboos
% use optimization toolbox if possible, othewise use the standard fminsearch function
%
% Revision 1.6  2006/09/13 09:55:58  roboos
% fixed bug (typo) in rigidbody
%
% Revision 1.5  2006/04/13 12:55:45  roboos
% added a str2func to solve a problem with feval and private
%
% Revision 1.4  2006/04/13 10:50:34  roboos
% renamed calls to warp3d into warp_apply
%
% Revision 1.3  2006/04/13 10:47:39  roboos
% renamed all calls to warpfun into warp_error
%
% Revision 1.2  2006/04/13 10:38:24  roboos
% fixed a problem due to find/strmatch
%
% Revision 1.1  2005/08/15 08:12:40  roboos
% Renamed warp_pnt into warp_optim for consistency with other functions.
% Also changed the code, the subsequent ordering of the simple to
% more complex warps is handled more clean.
%
% Revision 1.4  2005/03/21 15:43:42  roboos
% fixed bug in output for nonlinear warping
% added support for rigidbody or globalrescale warp
%
% Revision 1.3  2004/05/19 09:57:08  roberto
% added GPL copyright statement, added CVS log item
%

global fb;

if nargin<3
  method='traditional';
end

pos1 = input;
pos2 = target;

% The warp_error function might be located in the private subdirectory fo
% fieldtrip, i.e. only available to functions in the fieldtrip toolbox.
% The following line ensures that the function can also be found by the
% feval that is executed by the optimalization toolbox.
warp_error = str2func('warp_error');

% set the options for the minimalisation routine
if exist('fminunc')
  % use the optimization toolbox
  optimfun = @fminunc;
  options  = optimset('fminunc');
  options  = optimset(options, 'Display', 'off');
  options  = optimset(options, 'MaxIter', 1500);
  % options  = optimset(options, 'MaxFunEvals', '1000*numberOfVariables');
  options  = optimset(options, 'TolFun', 1e-4);
  options  = optimset(options, 'LargeScale', 'off');
else
  % use a standard matlab function, this function converges slower
  optimfun = @fminsearch;
  options  = optimset('fminsearch');
  options  = optimset(options, 'Display', 'off');
  options  = optimset(options, 'MaxIter', 4500);
end

if fb; fprintf('distance = %f\n', warp_error([0 0 0 0 0 0], pos1, pos2, 'rigidbody')); end

% the warp is done in steps, starting simple and progressively getting more complex
level = find(strcmp(method, {
  'rigidbody'          % 1
  'globalrescale'     % 2
  'traditional'       % 3
  'nonlin1'           % 4
  'nonlin2'           % 5
  'nonlin3'           % 6
  'nonlin4'           % 7
  'nonlin5'           % 8
  }));

if isempty(method)
  error('incorrect warping method specified');
end

if level>=1
  % do a rigid-body transformation (6 parameters)
  if fb; disp('rigidbody...'); end
  ri = [0 0 0 0 0 0];
  rf = optimfun(warp_error, ri, options, pos1, pos2, 'rigidbody');
  if fb; fprintf('distance = %f\n', warp_error(rf, pos1, pos2, 'rigidbody')); end
end

if level>=2
  % do a rigid-body + global rescaling transformation (7 parameters)
  if fb; disp('rigidbody + global rescaling...'); end
  gi = [rf 1];
  gf = optimfun(warp_error, gi, options, pos1, pos2, 'globalrescale');
  if fb; fprintf('distance = %f\n', warp_error(gf, pos1, pos2, 'globalrescale')); end
end

if level>=3
  % do a rigid-body + individual rescaling transformation (9 parameters)
  if fb; disp('rigidbody + individual rescaling...'); end
  ti = [gf gf(7) gf(7)];
  tf = optimfun(warp_error, ti, options, pos1, pos2, 'traditional');
  if fb; fprintf('distance = %f\n', warp_error(tf, pos1, pos2, 'traditional')); end
end

if level>=4
  % do a first order nonlinear transformation,
  if fb; disp('1st order nonlinear...'); end
  e1i = traditional(tf);
  e1i = [e1i(1:3,4) e1i(1:3,1:3)];	% reshuffle from homogenous into nonlinear
  e1f = optimfun(warp_error, e1i, options, pos1, pos2);
  if fb; fprintf('distance = %f\n', warp_error(e1f, pos1, pos2, 'nonlinear')); end
end

if level>=5
  % do a second order nonlinear transformation,
  if fb; disp('2nd order nonlinear...'); end
  e2i = [e1f zeros(3,6)];
  e2f = optimfun(warp_error, e2i, options, pos1, pos2);
  if fb; fprintf('distance = %f\n', warp_error(e2f, pos1, pos2, 'nonlinear')); end
end

if level>=6
  % do a third order nonlinear transformation,
  if fb; disp('3rd order nonlinear...'); end
  e3i = [e2f zeros(3,10)];
  e3f = optimfun(warp_error, e3i, options, pos1, pos2);
  if fb; fprintf('distance = %f\n', warp_error(e3f, pos1, pos2, 'nonlinear')); end
end

if level>=7
  % do a fourth order nonlinear transformation,
  if fb; disp('4th order nonlinear...'); end
  e4i = [e3f zeros(3,10)];
  e4f = optimfun(warp_error, e4i, options, pos1, pos2);
  if fb; fprintf('distance = %f\n', warp_error(e4f, pos1, pos2, 'nonlinear')); end
end

if level>=8
  % do a fifth order nonlinear transformation,
  if fb; disp('5th order nonlinear...'); end
  e5i = [e4f zeros(3,10)];
  e5f = optimfun(warp_error, e5i, options, pos1, pos2);
  if fb; fprintf('distance = %f\n', warp_error(e5f, pos1, pos2, 'nonlinear')); end
end

% return the estimated parameters of the highest level warp
% and compute the warped points
switch level
  case 1
    M = rf;
  case 2
    M = gf;
  case 3
    M = tf;
  case 4
    M = e1f;
  case 5
    M = e2f;
  case 6
    M = e3f;
  case 7
    M = e4f;
  case 8
    M = e5f;
end
result = warp_apply(M, input, method);

author: PatternRecognition

repo: OpenBMI


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 	WRITE A FUNCTION THAT COMPUTES THE JACOBIAN OF A ROBOT
%
%   Jn = compute_jacobian(robot, q)
%
%   The method exposed here as a solution is translated from the method in:
%
%   "Robot Modeling and Control". Mark W. Spong, Seth Hutchinson, M. Vidyasagar
%   Ed. Wiley
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (C) 2016, by Arturo Gil Aparicio
%
% This file is part of ARTE (A Robotics Toolbox for Education).
%
% ARTE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% ARTE is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with ARTE.  If not, see <http://www.gnu.org/licenses/>.
function Jn = compute_jacobian(robot, q)
Jn = []; %Initialize J
for i=1:robot.DOF,
   Ji = jacobian_submatrix(robot, q, i);
   Jn = [Jn Ji]; % Add submatrix to J
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   Computes the value of the submatrix Ji which accounts for the
%   contribution of joint i (either rotational or prismatic) in the
%   rotational and translational speed of the end effector.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Ji = jacobian_submatrix(robot, q, i)
%CAution, the following functions are evaluated according to the values of q
%compute direct kinematics for serial robotics
theta = eval(robot.DH.theta);
d = eval(robot.DH.d);
a = eval(robot.DH.a);
alfa = eval(robot.DH.alpha);

%load the position/orientation of the robot's base
T = robot.T0;
%Compute Matrix until joint i-1 (note that no computation is performed for i=1)
for j=1:i-1,
    T=T*dh(theta(j), d(j), a(j), alfa(j));
end

% obtain z_{i-1}
zim = T(1:3,3);
% obtain o_{i-1}
oim = T(1:3,4);
%a zero vector
zero = zeros(3,1);

%Compute the end effector's position
T = directkinematic(robot, q);
on = T(1:3,4);

%rotational joint
if robot.kind(i) == 'R'
    Ji = [cross(zim,(on-oim)); zim];
else %prismatic joint
    Ji = [zim; zero];
end

repo: ARTE


text:
function describe(threecomp)

%Detailed description of threecomp properties
% DESCRIBE(THREECOMP) provides detailed descriptions of threecomp object
% properties and how they are related.
%
%
% ------------------- COORDINATE SYSTEM -------------------------
% The threecomp object is designed to use a familiar spherical polar
% coordinate system in which horizontal direction on Earth is given in
% clockwise degrees from north: north is 0; east is 90; south is 180; and
% west is 270 degrees. Vertical directions are given with respect to
% vertical up. up is 0 degrees; horizontal is 90 degrees; and 180 is down.
%
%
% ------------------ TRACE NAME CONVENTIONS -----------------------
% Trace names follow the convention of network-station-channel-location.
% (Internally, this is enforced via the scnlobject and waveform objects.)
% Station and channel codes have particular importance in threecomp
% objects. A simple check is performed upon initiation to ensure that all
% three traces in each object come from the same seismic station. In other
% words, all three traces must have the same station code. The channel
% codes have specific meaning and users are encouraged to make sure that
% channel names are correct before converting to a threecomp object. The
% threecomp channel code convention adheres to the SEED standard of a
% minimum three character name where the third character represents the
% component orientation. Threecomp requires that the third channel
% characters be: Z-N-E, Z-R-T, or Z-2-1. Modest deviations from these
% channel names are accomodated by the horizontal and vertical orientation
% properties (see below). However, the actual channel names must contain
% one of these character sets.
%
%
% ------------------ COMPONENT ORIENTATIONS ----------------------
% The orientation of each component of trace data is essential to
% performing any type of three component analysis. The safest way to ensure
% that component orientations are correct is to provide them explicitly.
% The THREECOMP function allows users to provide the horizontal and
% vertical orientation of all three channels of data. It is also possible
% to read these parameters automatically from the original waveforms if they
% have been set as properties there. If no orientation information is
% given, THREECOMP will assign default values where possible.
%
% DEFAULT VALUES
% If the component (third character of the channel name) is Z, N, E and no
% explicit orientation is given, then the orientations are assumed to be
%       Z: [0 0]    N:[0 90]    E: [90 90]
% This is equivalent to calling the THREECOMP function with an orientation
% matrix [0 0 0 90 90 90 ; ... ; ... ]. If the components are Z, R, T, and
% a backazimuth is given, then the horizontal components will be aligned
% accordingly. Components of Z, 2, 1 do not have any default orientations.
% Orientations provided as arguments to function THREECOMP, and
% orientations described in the input waveform properties, will override
% default values. For details see horizontal and vertical orientation
% descriptions below.
%
% HORIZONTAL ORIENTATION
% This attribute specifies the orientation of the component in the
% horizontal plane, measured clockwise from North.  For a North-South
% orientation, positive toward the north, the horizontal orientation is 0.
% For East-West orientation with positive to the east, the horizontal
% orientation is 90. Allowable range is 0 to 360.
%
% VERTICAL ORIENTATION
% This attribute measures the angle between the sensitive axis of a
% seismometer and the outward-pointing vertical direction.  For a
% vertically-oriented seismometer, the vertical orientation is 0, or 180
% (to reverse the sense of the instrument). For a horizontally oriented
% component, the vertical orientation is 90. Allowable range is 0 - 180.
%
% RADIAL TRANSVERSE COORDINATE SYSTEM
% Threecomp objects recognize the familiar coordinate system of vertical,
% radial, and transverse (ZRT). In this system the positive radial
% direction (R+) is 180 degrees opposite the backazimuth. The relative
% component orientations in a ZRT coordinate system are the same as in ZNE
% coordinates. That is, the positive transverse direction points 90 degrees
% clockwise from the positive radial direction. For example, for a wave
% arriving from due south on Z-N-E components, there is no rotation and N
% becomes R, while E becomes T.
%
%
% ------------------ PARTICLE MOTION ----------------------
% Particle motions are calculated in a sliding time window. In each window
% the covariance matrix of the three waveform vectors in computed. The
% eigenvectors of the covariance matrix define the dominant orientations of
% the data, while the eigenvalues express the relative amplitudes in each
% of these directions. Conceptually, rectilinearity expresseses the
% relative dominance of the largest eigenvalue (range is 0 to 1). Planarity
% is the degree to which the largest two eigenvalues dominate (range is 0
% to 1). Azimuth and inclination give the spherical polar orientation of
% the largest eigenvector. It is important to note that azimuth and
% inclination only have meaning if the waveforms show a high degree of
% rectilinearity or in some orientations, planarity. It makes sense - think
% about it!
%
% Energy is computed from the trace of the eigenvalue matrix. The
% calculation is performed independent of the data type. The term "energy"
% should be treated carefully however. This term is essentially just the
% square of the total particle velocity. The "energy" units are the square
% of whatever units the input waveforms had. IF the input traces are in
% velocity, then the energy term is the seismic kenetic energy density,
% (smoothed over size of the sliding time window). If the input traces are
% not velocity, then the output cannot be used as a proxy for physical
% energy.

% As defined here, the azimuth range is 0 to 360 degrees measured from
% north. Inclination ranges from 0 (up) to 90 (horizontal). This reference
% frame differs from some in the literature, but is used here because it is
% intuitive; it is consistent through the threecomp toolbox; and, most
% importantly, to match the reference frame used for component
% orientations. See horizontal and vertical orientation, above. For
% mathematical descriptions of the particle motion coefficients, users are
% encouraged to consult the PARTICLEMOTION.M code. It is reasonably short
% and well commented. Note that rectilinearity and planarity have somewhat
% variable definitions in the literature. For the discerning user, parallel
% definitions are included in the PARTICLEMOTION code, but are commented
% out.

help describe

author: geoscience-community-codes

repo: GISMO


text:
function [y,deriv] = brier_obj(w,T,weights,logit_prior)
% This is an MV2DF. See MV2DF_API_DEFINITION.readme.
%
% Weighted binary classifier cross-entropy objective, based on 'Brier'
% quadratic proper scoring rule. This rule places less emphasis on extreme scores,
% than the logariothmic scoring rule.
%
%  Differentiable inputs:
%   w: is vector of N detection scores (in log-likelihood-ratio format)
%
%  Fixed parameters:
%   T: is vector of N labels: 1 for target and -1 for non-target.
%   weights: is N-vector of objective function weights, one per trial.
%   logit_prior: is logit(prior), this controls the region of interest

if nargin==0
    test_this();
    return;
end

if isempty(w)
    y = @(w)brier_obj(w,T,weights,logit_prior);
    return;
end

if isa(w,'function_handle')
    outer = brier_obj([],T,weights,logit_prior);
    y = compose_mv(outer,w,[]);
    return;
end

w = w(:);
scores = w.';

arg = bsxfun(@plus,scores,logit_prior).*T;
logp2 = -neglogsigmoid(-arg);
wobj = 0.5*exp(2*logp2).*weights; % 1*N
y = sum(wobj);

if nargout>1
    logp1 = -neglogsigmoid(arg);
    deriv = @(dy) deriv_this(dy,weights(:),T(:),logp1(:),logp2(:));
end

function [g,hess,linear] = deriv_this(dy,weights,T,logp1,logp2)
g0 = -exp(logp1+2*logp2).*weights.*T;
g = dy*g0;
linear = false;
hess = @(d) hessianprod(d,dy,g0,weights,logp1,logp2);

function [h,Jv] = hessianprod(d,dy,g0,weights,logp1,logp2)

ddx = -exp(logp1+2*logp2);
h = dy*(ddx.*(1-3*exp(logp1))).*weights.*d(:);

if nargout>1
    Jv = d.'*g0;
end

function test_this()
N = 30;
T = [ones(1,N/3),-ones(1,N/3),zeros(1,N/3)];
scores = randn(1,N);
weights = [rand(1,2*N/3),zeros(1,N/3)];
f = @(w) brier_obj(w,T,weights,-2.23);
test_MV2DF(f,scores(:));

author: nesl


text:
function r = sqrt(a)
%SQRT         Taylor square root sqrt(a)
%

% written  05/21/09     S.M. Rump
% modified 08/26/12     S.M. Rump  global variables removed
%

  e = 1e-30;
  if 1+e==1-e                           % fast check for rounding to nearest
    rndold = 0;
  else
    rndold = getround;
    setround(0)
  end

  K1 = getappdata(0,'INTLAB_TAYLOR_ORDER') + 1;

  r = a;
  r.t(1,:) = sqrt(a.t(1,:));
  rt2 = 2*r.t(1,:);                     % almost 10 % faster
  for j=2:K1
    r.t(j,:) = ( a.t(j,:) - sum(r.t(2:j-1,:).*r.t(j-1:-1:2,:),1) ) ./ (rt2);
  end
% straight version is faster
%   for j=2:K1
%     if even(j)
%       r.t(j,:) = ( a.t(j,:)/2 - sum(r.t(2:(j/2),:).*r.t(j-1:-1:(j/2)+1,:),1) ) ./ r.t(1,:);
%     else
%       r.t(j,:) = ( a.t(j,:)/2 - sum(r.t(2:((j-1)/2),:).*r.t(j-1:-1:(j+3)/2,:),1) - ...
%                               (r.t((j+1)/2,:).^2)/2 ) ./ r.t(1,:);
%     end
%   end

  if rndold
    setround(rndold)
  end

repo: OpenMAS


text:
function distmap = test_breadth_first_search(A,u)

distmap = ipdouble(zeros(size(A,1),1));
distmap(u) = 0;

    function on_tree_edge(ei,u,v)
        distmap(v) = distmap(u)+1;
    end

breadth_first_search(A,u,struct('tree_edge',@on_tree_edge));

distmap = double(distmap);
end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
classdef SettingsLevelSetSmoothSquareInclusion < SettingsLevelSetCreator

    properties (Access = public)
        widthSquare
        pnorm
    end

    methods (Access = public)

        function obj = SettingsLevelSetSmoothSquareInclusion(varargin)
            obj.loadParams('paramsLevelSetCreator_SmoothSquare.json')
            if nargin == 1
                obj.loadParams(varargin{1})
            end
        end

    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function radiomicsParamS = getRadiomicsParamTemplate(paramFilename,dictS)
% radiomicsParamS = getRadiomicsParamTemplate(paramFilename);
%
% Template parameters for radiomics feature extraction
%
% --------------------------------------------------------------------------------------
% INPUT:
% paramFileName : Path to JSON file for radiomics feature extraction.
%                 Sample JSON file: CERR_core/PlanMetrics/heterogenity_metrics/sample_radiomics_extraction_settings.json
% -------- Optional --------
% dictS       : Alternatively, pass dictionary userInS
% --------------------------------------------------------------------------------------
%
% APA, 2/27/2019
% AI, 3/22/19     Modified for compatibility with JSON input

feature accel off

%% Read JSON file
if ~isempty(paramFilename)
    userInS = jsondecode(fileread(paramFilename));
else
    userInS = dictS;
end

%% Get image type
filterTypeC = fieldnames(userInS.imageType);
radiomicsParamS.imageType = struct();
for m = 1:length(filterTypeC)
    %paramListC = fieldnames(userInS.imageType.(filterTypeC{m}));
    radiomicsParamS.imageType.(filterTypeC{m}) = struct();
    for iFilt = 1:length(userInS.imageType.(filterTypeC{m}))
        if ~(isstruct(userInS.imageType.(filterTypeC{m})) && ...
                isempty(fieldnames(userInS.imageType.(filterTypeC{m}))))
            if isstruct(userInS.imageType.(filterTypeC{m}))
                paramListC = fieldnames(userInS.imageType.(filterTypeC{m}));
            else
                paramListC = fieldnames(userInS.imageType.(filterTypeC{m}){iFilt});
            end
            for n = 1:length(paramListC)
                if isstruct(userInS.imageType.(filterTypeC{m}))
                    radiomicsParamS.imageType.(filterTypeC{m})(iFilt).(paramListC{n}).val = ...
                        userInS.imageType.(filterTypeC{m})(iFilt).(paramListC{n});
                else
                    radiomicsParamS.imageType.(filterTypeC{m})(iFilt).(paramListC{n}).val = ...
                        userInS.imageType.(filterTypeC{m}){iFilt}.(paramListC{n});
                end
            end
        end
    end
end

%% Calculation Parameters
whichFeatS = struct('resample',struct('flag',0), 'padding',struct('flag',0),...
        'perturbation',struct('flag',0),'firstOrder',struct('flag',0),...
        'shape',struct('flag',0),'texture',struct('flag',0),...
        'peakValley',struct('flag',0),'ivh',struct('flag',0),'glcm',struct('flag',0),...
        'glrlm',struct('flag',0),'gtdm',struct('flag',0),'gldm',struct('flag',0),...
        'glszm',struct('flag',0));
if isfield(userInS,'settings')
    settingsC = fieldnames(userInS.settings);
    firstOrderParamS = struct;
    textureParamS = struct;
    shapeParamS = struct;
    peakValleyParamS = struct;
    ivhParamS = struct;

    % Structure names
    if isfield(userInS,'structures')
        radiomicsParamS.structuresC = userInS.structures;
    end
    %Otherwise, use entire scan

    % ---1. First-order features ---
    idx = strcmpi(settingsC,'firstOrder');
    if any(idx)
        paramC = fieldnames(userInS.settings.(settingsC{idx}));
        for k = 1: length(paramC)
            firstOrderParamS.(paramC{k}) = userInS.settings.(settingsC{idx}).(paramC{k});
        end
        radiomicsParamS.firstOrderParamS = firstOrderParamS;
    end

    %---2. Shape features ----
    idx = strcmpi(settingsC,'shape');
    if any(idx)
        paramC = fieldnames(userInS.settings.(settingsC{idx}));
        for k = 1: length(paramC)
            shapeParamS.(paramC{k}) = userInS.settings.(settingsC{idx}).(paramC{k});
        end
        radiomicsParamS.shapeParamS = shapeParamS;
    end

    %---3. Higher-order (texture) features ----
    idx = strcmpi(settingsC,'texture');
    if any(idx)
        paramC = fieldnames(userInS.settings.(settingsC{idx}));
        for k = 1: length(paramC)
            textureParamS.(paramC{k}) = userInS.settings.(settingsC{idx}).(paramC{k});
        end
        radiomicsParamS.textureParamS = textureParamS;
    end

    %---4. Peak-valley features ----
    idx = strcmpi(settingsC,'peakvalley');
    if any(idx)
        paramC = fieldnames(userInS.settings.(settingsC{idx}));
        for k = 1: length(paramC)
            peakValleyParamS.(paramC{k}) = userInS.settings.(settingsC{idx}).(paramC{k});
        end
        radiomicsParamS.peakValleyParamS = peakValleyParamS;
    end

    %---5. IVH features ----
    idx = strcmpi(settingsC,'ivh');
    if any(idx)
        paramC = fieldnames(userInS.settings.(settingsC{idx}));
        for k = 1: length(paramC)
            ivhParamS.(paramC{k}) = userInS.settings.(settingsC{idx}).(paramC{k});
        end
        radiomicsParamS.ivhParamS = ivhParamS;
    end

    %% Set flags for sub-classes of features to be extracted
    for k = 1:length(settingsC)
        fieldNamC = fieldnames(userInS.settings.(settingsC{k}));
        if ~isempty(fieldNamC)
            whichFeatS.(settingsC{k}).flag = 1;
            for iField = 1:length(fieldNamC)
                whichFeatS.(settingsC{k}).(fieldNamC{iField}) = userInS.settings...
                    .(settingsC{k}).(fieldNamC{iField});
            end
        end
    end
end

if isfield(userInS,'featureClass')
    inputClassesC = fieldnames(userInS.featureClass);
    for k =1:length(inputClassesC)
        whichFeatS.(inputClassesC{k}).flag = 1;
        if isfield(userInS.featureClass.(inputClassesC{k}),'featureList')
            whichFeatS.(inputClassesC{k}).featureList = ...
                userInS.featureClass.(inputClassesC{k}).featureList;
        else
            whichFeatS.(inputClassesC{k}).featureList = {'all'};
        end
    end
    radiomicsParamS.whichFeatS = whichFeatS;

    if isfield(userInS,'toQuantizeFlag')
        %% Flag to quantize input data
        radiomicsParamS.toQuantizeFlag = userInS.toQuantizeFlag;
    else
        radiomicsParamS.toQuantizeFlag = 1;
    end
else
    radiomicsParamS.whichFeatS = whichFeatS;
end

feature accel on

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function mv = mv_assignColors(mv);
% mv = mv_assignColors(mv);
%
% Assign a color order to an time course UI,
% saving the results to the event-related parameters.
%
% 09/05 ras.
if ieNotDefined('trials')
   mv = get(gcf,'UserData');
end

mv.trials = er_assignColors(mv.trials);

% update and save the colors in the event-related parameters
mv.params.condColors = mv.trials.condColors;
hI = initHiddenInplane;
params = er_getParams(hI,mv.params.scans(1),mv.params.dataType);
params.condColors = mv.params.condColors;
er_setParams(hI,params,mv.params.scans,mv.params.dataType);

set(mv.ui.fig,'UserData',mv);
MultiVoxelUI;

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function tests = test_ft_specest_mtmfft

% MEM 1gb
% WALLTIME 00:10:00
% DEPENDENCY ft_specest_mtmfft

if nargout
  % assume that this is called by RUNTESTS
  tests = functiontests(localfunctions);
else
  % assume that this is called from the command line
  fn = localfunctions;
  for i=1:numel(fn)
    feval(fn{i});
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function testOptions(testCase)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fsample = 1000;
nchan   = 8;
nsample = 1000;

dat     = randn(nchan, nsample) + 1 + linspace(0,1,nsample);
time    = (0:(nsample-1))/fsample;
freqoi  = 1:500;
verbose = false;

result = {};
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'bartlett'      , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'barthannwin'   , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'blackman'      , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'blackmanharris', 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'bohmanwin'     , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'chebwin'       , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'flattopwin'    , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'gausswin'      , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'hann'          , 'verbose', verbose); % hann and hanning are nearly the same in the MATLAB implementation, and exactly the same in external/signal
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'kaiser'        , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'nuttallwin'    , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'parzenwin'     , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'rectwin'       , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'taylorwin'     , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'tukeywin'      , 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'triang'        , 'verbose', verbose);

result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', 11:20, 'taper', 'hanning', 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', 21:30, 'taper', 'hanning', 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', 31:40, 'taper', 'hanning', 'verbose', verbose);

result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'tapsmofrq', 1, 'taper', 'dpss', 'verbose', verbose); % Warning: using only one taper for specified smoothing
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'tapsmofrq', 3, 'taper', 'dpss', 'verbose', verbose);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'tapsmofrq', 5, 'taper', 'dpss', 'verbose', verbose);

result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'hanning', 'verbose', verbose, 'pad', 1.1, 'padtype', 'zero');
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'hanning', 'verbose', verbose, 'pad', 1.2, 'padtype', 'zero');
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'hanning', 'verbose', verbose, 'pad', 1.3, 'padtype', 'zero');

% try out the various padding types, don't remove the polynomial fit
% this will result in warning: output frequencies are different from input frequencies
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'hanning', 'verbose', verbose, 'polyorder', -1, 'pad', 1/0.9, 'padtype', 'zero');
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'hanning', 'verbose', verbose, 'polyorder', -1, 'pad', 1/0.9, 'padtype', 'mean');
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'hanning', 'verbose', verbose, 'polyorder', -1, 'pad', 1/0.9, 'padtype', 'localmean');
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'hanning', 'verbose', verbose, 'polyorder', -1, 'pad', 1/0.9, 'padtype', 'edge');
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', freqoi, 'taper', 'hanning', 'verbose', verbose, 'polyorder', -1, 'pad', 1/0.9, 'padtype', 'mirror');

% the default polyorder 0 was already computed above, so use different frequencies
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', 2:2:100, 'taper', 'hanning', 'verbose', verbose, 'polyorder', 0);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', 2:2:100, 'taper', 'hanning', 'verbose', verbose, 'polyorder', 1);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', 2:2:100, 'taper', 'hanning', 'verbose', verbose, 'polyorder', 2);
result{end+1} = ft_specest_mtmfft(dat, time, 'freqoi', 2:2:100, 'taper', 'hanning', 'verbose', verbose, 'polyorder', 3);

% all iterations were done with (slightly) different options, hence the results should not be equal
for i=1:numel(result)
  for j=(i+1):numel(result)
    assert(~isequaln(result{i}, result{j}), 'the results %d and %d should not be equal', i, j);
  end
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function ldl_install
%LDL_INSTALL compile and install the LDL package for use in MATLAB.
% Your current working directory must be LDL for this function to work.
%
% Example:
%   ldl_install
%
% See also ldlsparse, ldlsymbol

% Copyright 2006-2007 by Timothy A. Davis, Univ. of Florida

ldl_make
addpath (pwd) ;
fprintf ('LDL has been compiled and installed.  The path:\n') ;
disp (pwd) ;
fprintf ('has been added to your path.  Use pathtool to add it permanently.\n');
ldldemo


text:
% im2imstat    computes image statistics from several images
%              and finds the projections of laser points
%
% The computation core is taken from  im2points.m
% computes average image and image of standard deviations
% requires configdata.m
% The name of the experiment has to be specified
% it determines the location of files etc ...
%
% the scripts serves as a template for a multiprocessing
% it assumes a vector of camera IDs CamIds to be known
% indexes in the CamIds are supposed to be correct
%
% It is used by im2pmultiproc.pl

% $Author: svoboda $
% $Revision: 2.0 $
% $Id: im2imstat.m,v 2.0 2003/06/19 12:06:51 svoboda Exp $
% $State: Exp $

% Read configuration from whatever is specified on command-line (via --config=FILENAME)
config = read_configuration();

STEP4STAT = 5; % step for computing average and std images, if 1 then all images taken

im.dir = config.paths.img;
im.ext = config.files.imgext;

% NoCams = size(config.files.idxcams,2);	% number of cameras
% Use concrete CameraIds instead of all cameras
NoCams = size(CamsIds,2);
CamsIds

% load image names
for i=1:NoCams,
  seq(i).camId = CamsIds(i);
  if seq(i).camId > -1
	seq(i).data = dir([sprintf(im.dir,seq(i).camId),sprintf(config.files.imnames,seq(i).camId),im.ext]);
	[sprintf(im.dir,seq(i).camId),sprintf(config.files.imnames,seq(i).camId),im.ext]
  else
	seq(i).data = dir([im.dir,sprintf(config.files.imnames),im.ext]);
  end
  seq(i).size = size(seq(i).data,1);
  if seq(i).size<4
	error('Not enough images found. Wrong image path or name pattern?');
  end
end

% Expected number of 3D points is equal to the number of frames.
% In fact, some frames might be without any calibration point

% Because of non-consistent stopping of capturing, the sequences might
% have different number of images, select the minimal value as the right one
NoPoints = min([seq.size]);

% compute the average images that will be used for finding LEDs
% if not already computed

pointsIdx = [1:STEP4STAT:NoPoints];

t = cputime;
for i=1:NoCams,
  if ~exist(sprintf(config.files.avIM,seq(i).camId)),
	disp(sprintf('The average image of the camera %d is being computed',seq(i).camId));
	avIM = zeros(size(imread([sprintf(im.dir,seq(i).camId),seq(i).data(1).name])));
	for j=pointsIdx,
	  IM = imread([sprintf(im.dir,seq(i).camId),seq(i).data(j).name]);
	  avIM = avIM + double(IM);
	end
	avIM = uint8(round(avIM./size(pointsIdx,2)));
	imwrite(avIM,sprintf(config.files.avIM,seq(i).camId));
  else	disp('Average files already exist');
  end
end
disp(sprintf('Elapsed time for average images: %d [sec]',cputime-t))
% compute the standard deviations images that will be used for finding LEDs
% if not already computed
t = cputime;
for i=1:NoCams,
  if ~exist(sprintf(config.files.stdIM,seq(i).camId)),
	avIM = double(imread(sprintf(config.files.avIM,seq(i).camId)));
	disp(sprintf('The image of standard deviations of the camera %d is being computed',seq(i).camId));
	stdIM = zeros(size(imread([sprintf(im.dir,seq(i).camId),seq(i).data(1).name])));
	for j=pointsIdx,
	  IM = imread([sprintf(im.dir,seq(i).camId),seq(i).data(j).name]);
	  stdIM = stdIM + (double(IM)-avIM).^2;
	end
	stdIM = uint8(round(sqrt(stdIM./(size(pointsIdx,2)-1))));
	imwrite(stdIM,sprintf(config.files.stdIM,seq(i).camId));
  else
	disp('Image of standard deviations already exist')
  end
end
disp(sprintf('Elapsed time for computation of images [sec]: %d',cputime-t))

% find points in the images
Ws    = [];
IdWs  = [];
Res	  = [];

IdMat = ones(NoCams,NoPoints);
% IdMat is very important for Martinec&Pajdla filling [ECCV2002]
% it is a NoCams x NoPoints matrix,
% IdMat(i,j) = 0 -> no j-th point in i-th
% IdMat(i,j) = 1 -> point successfully detected

for i=1:NoCams,
  Points = [];
  avIM  = imread(sprintf(config.files.avIM,seq(i).camId));
  stdIM	= imread(sprintf(config.files.stdIM,seq(i).camId));
  for j=1:NoPoints,
	[pos,err] = getpoint([sprintf(im.dir,seq(i).camId),seq(i).data(j).name], 0, config.imgs, avIM, stdIM);
	if err
	  IdMat(i,j) = 0;
	  Points = [Points, [NaN; NaN; NaN]];
	else
	  Points = [Points, [pos; 1]];
	end
  end
  Ws = [Ws; Points];
  Res= [Res; size(avIM,2), size(avIM,1)];
end

idx = '.';
for i=CamsIds,
  idx = sprintf('%s%02d',idx,i);
end

save([config.files.points,idx], 'Ws','-ASCII')
% save(config.files.IdPoints,'IdWs','-ASCII')
save([config.files.Res,idx], 'Res', '-ASCII')
save([config.files.IdMat,idx], 'IdMat', '-ASCII')

% write auxiliary file that is done
done=1;
save(donefile,'done','-ascii');

% exit the Matlab
% this script is to be used in the batch mode
% hence exit at the end is necessary
exit;

author: strawlab

repo: MultiCamSelfCal


text:
function [fSignificanceLevel] = pf_OverallSignificance(nNumberNodesTotal, nNumberNodesHit, fHitProbability)

fIncSumProb = [];
fSumProb = 0;
for nCnt_= 0:nNumberNodesTotal
  nNumberCombinations = nchoosek(nNumberNodesTotal, nCnt_);
  fProbCombination = ((1 - fHitProbability)^(nNumberNodesTotal - nCnt_) * fHitProbability^nCnt_) * nNumberCombinations;
  fSumProb = fSumProb + fProbCombination;
  fIncSumProb = [fIncSumProb; fSumProb];
end
fSignificanceLevel = 1 - (fIncSumProb(nNumberNodesHit + 1));

author: CelsoReyes


text:
function [gr, diams, vols] = imGranulo(img, granuloType, strelShape, strelSizes, varargin)
% Compute granulometry curve of a given image.
%
%   GR = imGranulo(IMG, GRTYPE, STRELSHAPE, SIZES)
%   Computes the granulometry curve for the input image IMG, using the
%   operation GRTYPE, the shape of structuring element given by STRELSHAPE,
%   and the list of structuring element sizes given by SIZES.
%   IMG should be a 2D image (binary or grayscale)
%   GRTYPE can be one of {'opening', 'closing', 'erosion', 'dilation'}.
%   STRELSHAPE can be one of {'square', 'octagon', 'diamond', 'disk',
%     'lineh', 'linev'}.
%   SIZES are given as radius. Diameters of strels are obtained as 2*R+1.
%   The result GR is a 1-by-N array with as many columns as the number of
%     elements provided in SIZES array.
%
%   [GR, DIAMS] = imGranulo(...)
%   Also returns the diameters of the structuring elements for each step of
%   the analysis. DIAMS is 1-by-N array with the same number of columns as
%   the GR array.
%
%   [GR, DIAMS, VOLS] = imGranulo(...)
%   Also returns the array of volume curves, corresponding to the sum of
%   gray levels at each step of the granulometry.
%
%   ... = imGranulo(..., 'verbose', TF)
%   If TF is true, displays the iteration steps on the command window.
%
%
%   Example
%     % Compute granulometric curve by opening on coins image (with two
%     % distinct sizes), using disk structuring element
%     img = imread('coins.png');
%     Rmax = 50;
%     gr = imGranulo(img, 'opening', 'disk', 1:Rmax);
%     % display as a function of strel diameter
%     figure; plot(2*(1:Rmax)+1, gr); xlim([0 2*Rmax]);
%     xlabel('Strel diameter (pixel)'); ylabel('Percentage of Variations');
%     title('Granulometry on "coins" image');
%
%   See also
%     imGranulometry, granuloMeanSize, imGranuloByRegion
%

% ------
% Author: David Legland
% e-mail: david.legland@inrae.fr
% Created: 2014-05-05,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2014 INRAE - Cepia Software Platform.

%% Parse input arguments

% check ROI
roi = true(size(img));
if ~isempty(varargin)
    var1 = varargin{1};
    if islogical(var1) && all(size(var1) == size(img))
        roi = var1;
        varargin(1) = [];
    end
end

% check additional input arguments
verbose = false;
while length(varargin) > 1
    switch lower(varargin{1})
        case 'verbose', verbose = varargin{2};
        otherwise
            error(['Can not understand option: ' varargin{1}]);
    end
    varargin(1:2) = [];
end

% create structuring element factory, as a function handle that returns a
% strel object (or an array) from the radius of the strel.
if isa(strelShape, 'functionHandle')
    strelMaker = strelShape;
else
    % create factory from strel name
    switch lower(strelShape)
        case 'square'
            strelMaker = @(r) strel('square', r);
        case {'octagon', 'diamond'}
            strelMaker = @(r) strel(lower(strelShape), r);
        case 'disk'
            % do not use simplification, as it is not suitable for
            % granulometries
            strelMaker = @(r) strel('disk', r, 0);
        case 'lineh'
            strelMaker = @(r) ones(1, 2*r+1);
        case 'linev'
            strelMaker = @(r) ones(2*r+1, 1);
        otherwise
            error(['matImage:' mfilename], ...
                ['Could not process strel type: ' strelShape]);
    end
end

% create funtion handle for morphological operation
if isa(granuloType, 'functionHandle')
    morphoOp = granuloType;
else
    switch lower(granuloType)
        case 'opening'
            morphoOp = @imopen;
        case 'closing'
            morphoOp = @imclose;
        case 'dilation'
            morphoOp = @imdilate;
        case 'erosion'
            morphoOp = @imerode;

        otherwise
            error(['matImage:' mfilename], ...
                ['Could not process granulometry type: ' granuloType]);
    end
end

%% Initialize

% number of structuring element sizes
nSizes = length(strelSizes);

% compute the associated diameter list (for output)
diams = 2 * strelSizes + 1;

% allocate memory for volume curves (sum of gray levels)
vols = zeros(1, nSizes + 1);

% initialize reference volume
vol0 = sum(img(roi));
vols(1) = vol0;

%% Iteration over structuring element sizes

% iterate
for i = 1:nSizes
    % size of strel for current iteration
    radius = strelSizes(i);

    if verbose
        fprintf('iter %2d/%d, radius = %f\n', i, nSizes, radius);
    end

    % create current strel
    se = strelMaker(radius);

    % compute morphological operation
    img2 = morphoOp(img, se);

    % sum of gray levels within each region
    vols(i+1) = sum(img2(roi));
end

% compute granulometry curve
vols2 = (vols - vol0) / (vols(end) - vol0);
gr = 100 * diff(vols2);

author: mattools

repo: matImage

save_path: github-repos/MATLAB/mattools-matImage


text:
classdef FileReader < handle

    properties (Access = protected)
        filePath
        fid
    end

    methods (Access = protected)

        function openFile(obj)
            obj.fid = fopen(obj.filePath);
        end

        function closeFile(obj)
            fclose(obj.fid);
        end

    end

    methods (Abstract, Access = public)
        read(obj)
        getDataBase(obj)
    end

end


text:
function savexml(filename, varargin)
%SAVEXML Save workspace variables to disk in XML.
%  SAVEXML FILENAME saves all workspace variables to the XML-file
%  named FILENAME.xml. The data may be retrieved with LOADXML. if
%  FILENAME has no extension, .xml is assumed.
%
%  SAVE, by itself, creates the XML-file named 'matlab.xml'. It is
%  an error if 'matlab.xml' is not writable.
%
%  SAVE FILENAME X saves only X.
%  SAVE FILENAME X Y Z saves X, Y, and Z. The wildcard '*' can be
%  used to save only those variables that match a pattern.
%
%  SAVE ... -APPEND adds the variables to an existing file.
%
%  Use the functional form of SAVE, such as SAVE(filename','var1','var2'),
%  when the filename or variable names are stored in strings.
%
%  See also SAVE, MAT2XML, XMLTREE.

%  Copyright 2003 Guillaume Flandin.
%  $Revision: 6530 $  $Date: 2003/07/10 13:50 $

%  $Id: savexml.m 6530 2015-08-21 14:43:52Z guillaume $

if nargin == 0
    filename = 'matlab.xml';
    fprintf('\nSaving to: %s\n\n',filename);
else
    if ~ischar(filename)
        error('[SAVEXML] Argument must contain a string.');
    end
    [pathstr,name,ext] = fileparts(filename);
    if isempty(ext)
        filename = [filename '.xml'];
    end
end
if nargin <= 1, varargin = {'*'}; end

if nargout > 0
    error('[SAVEXML] Too many output arguments.');
end

if strcmpi(varargin{end},'-append')
    if length(varargin) > 1
        varargin = varargin(1:end-1);
    else
        varargin = {'*'};
    end
    if exist(filename,'file')
        % TODO % No need to parse the whole tree ? detect duplicate variables ?
        t = xmltree(filename);
    else
        error(sprintf(...
        '[SAVEXML] Unable to write file %s: file does not exist.',filename));
    end
else
    t = xmltree('<matfile/>');
end

for i=1:length(varargin)
    v = evalin('caller',['whos(''' varargin{i} ''')']);
    if isempty(v)
        error(['[SAVEXML] Variable ''' varargin{i} ''' not found.']);
    end
    for j=1:length(v)
        [t, uid] = add(t,root(t),'element',v(j).name);
        t = attributes(t,'add',uid,'type',v(j).class);
        t = attributes(t,'add',uid,'size',xml_num2str(v(j).size));
        t = xml_var2xml(t,evalin('caller',v(j).name),uid);
    end
end

save(t,filename);

%=======================================================================
function t = xml_var2xml(t,v,uid)

    switch class(v)
        case {'double','single','logical'}
            if ~issparse(v)
                t = add(t,uid,'chardata',xml_num2str(v));
            else % logical
                [i,j,s] = find(v);
                [t, uid2] = add(t,uid,'element','row');
                t = attributes(t,'add',uid2,'size',xml_num2str(size(i)));
                t = add(t,uid2,'chardata',xml_num2str(i));
                [t, uid2] = add(t,uid,'element','col');
                t = attributes(t,'add',uid2,'size',xml_num2str(size(j)));
                t = add(t,uid2,'chardata',xml_num2str(j));
                [t, uid2] = add(t,uid,'element','val');
                t = attributes(t,'add',uid2,'size',xml_num2str(size(s)));
                t = add(t,uid2,'chardata',xml_num2str(s));
            end
        case 'struct'
            names = fieldnames(v);
            for j=1:prod(size(v))
                for i=1:length(names)
                    [t, uid2] = add(t,uid,'element',names{i});
                    t = attributes(t,'add',uid2,'index',num2str(j));
                    t = attributes(t,'add',uid2,'type',...
                        class(getfield(v(j),names{i})));
                    t = attributes(t,'add',uid2,'size', ...
                        xml_num2str(size(getfield(v(j),names{i}))));
                    t = xml_var2xml(t,getfield(v(j),names{i}),uid2);
                end
            end
        case 'cell'
            for i=1:prod(size(v))
                [t, uid2] = add(t,uid,'element','cell');
                % TODO % special handling of cellstr ?
                t = attributes(t,'add',uid2,'index',num2str(i));
                t = attributes(t,'add',uid2,'type',class(v{i}));
                t = attributes(t,'add',uid2,'size',xml_num2str(size(v{i})));
                t = xml_var2xml(t,v{i},uid2);
            end
        case 'char'
            % TODO % char values should be in CData
            if size(v,1) > 1
                t = add(t,uid,'chardata',v'); % row-wise order
            else
                t = add(t,uid,'chardata',v);
            end
        case {'int8','uint8','int16','uint16','int32','uint32'}
            [t, uid] = add(t,uid,'element',class(v));
            % TODO % Handle integer formats (cannot use sprintf or num2str)
        otherwise
            if ismember('serialize',methods(class(v)))
                % TODO % is CData necessary for class output ?
                t = add(t,uid,'cdata',serialize(v));
            else
                warning(sprintf(...
                '[SAVEXML] Cannot convert from %s to XML.',class(v)));
            end
    end

%=======================================================================
function s = xml_num2str(n)
    % TODO % use format ?
    if isempty(n)
        s = '[]';
    else
        s = ['[' sprintf('%g ',n(1:end-1))];
        s = [s num2str(n(end)) ']'];
    end

author: spm


text:
function [ posiout ] = labposition( posiin )
posiout(1)=236+158*posiin(2);
posiout(2)=5444-158*posiin(1);

end

repo: DeepFi


text:
function f = f_function ( x )

%*****************************************************************************80
%
%% F_FUNCTION evaluates the right hand side of the finite element system.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 March 2011
%
%  Author:
%
%    Jeff Borggaard, John Burkardt, Catalin Trenchea, Clayton Webster
%
%  Parameters:
%
%    Input, real X(*), the evaluation points.
%
%    Output, real F(*), the function values.
%
  f = - 15*x.^4 + 3*x.^2 - 6*x;

  return
end

author: johannesgerer

repo: jburkardt-m


text:
%
% lellipe(phi, k, errtol)
%
% Inputs:
%
%   phi     Input angle vector size 1xN.
%   k       Input parameter vector size 1 or 1xN.
%   errtol  Error tolerance for Carlson's algorithms.
%
% Matlab function to compute Legendre's (incomplete) elliptic integral
% E(phi, k).  Uses a vectorized implementation of Carlson's Duplication Algorithms
% for symmetric elliptic integrals as found in "Computing Elliptic
% Integrals by Duplication," by B. C. Carlson, Numer. Math. 33, 1-16 (1979)
% and also found in ACM TOMS Algorithm 577.  Section 4 in the paper cited
% here describes how to convert between the symmetric elliptic integrals
% and Legendre's elliptic integrals.
%
% Returns NaN's for any argument values outside input range.
%

function f = lellipe(phi, k, errtol)

% Argument checking for vectorization:
lphi = length(phi);
lk = length(k);
errflag = logical(0);
if (lphi ~= lk)
    if (lphi==1)
        phivec = phi * ones(1,lk);
        kvec = k;
    elseif (lk==1)
        kvec = k * ones(1,lphi);
        phivec = phi;
    else
        disp('Incompatible input vector dimensions in lellipf!');
        errflag = logical(1);
    end
else
    phivec = phi;
    kvec = k;
end

if (~errflag)
    snphi = sin(phivec);
    csphi = cos(phivec);
    snphi2 = snphi.^2;
    csphi2 = csphi.^2;
    k2 = kvec.^2;
    y = 1.0 - k2.*snphi2;
    onesvec = ones(1,length(phivec));
    f = snphi .* rf(csphi2,  y, onesvec, errtol) - ...
        k2 .* snphi .* snphi2 .* rd(csphi2, y, onesvec, errtol)/3.0;
else
    f = NaN;
end

author: Sable

repo: mcbench-benchmarks


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

%* indicates variables that can be set via the GUI.

VMCOpt.startScoring.startInGeometry                    =  'phantom';

VMCOpt.startScoring.description                        =  'CERR Test';

VMCOpt.startScoring.startDoseOptions.scoreInGeometries =  'phantom';

VMCOpt.startScoring.startDoseOptions.scoreDoseToWater  =  'yes'; %*

VMCOpt.startScoring.startOutputOptions.name            =  'phantom';

VMCOpt.startScoring.startOutputOptions.dumpDose        =  2; %* Keep track of disk space usage... 1 is 4x bigger than 2.

VMCOpt.startGeometry.startXYZGeometry.myName           =  'phantom';

VMCOpt.startGeometry.startXYZGeometry.methodOfInput    =  'CT-PHANTOM';

VMCOpt.startGeometry.startXYZGeometry.phantomFile      =  '';

VMCOpt.startBeamletSource.myName                       =  'source 1';

VMCOpt.startBeamletSource.monitorUnitsSource          =  1;

VMCOpt.startBeamletSource.monoEnergy                  =  []; %*

VMCOpt.startBeamletSource.charge                      =  0; %*photons=0 electrons = -1

VMCOpt.startBeamletSource.beamletEdges                =  [];

VMCOpt.startBeamletSource.virtualPointSourcePosition  =  [];

VMCOpt.startBeamletSource.spectrum                    = ''; %* 6 18 file mono

VMCOpt.startMCParameter.automaticParameter            =  'yes';

VMCOpt.startMCControl.NCase                           =   100000;       %*

VMCOpt.startMCControl.NBatch                          =   10;           %*

VMCOpt.startMCControl.RNGSeeds                        =   [1 1];

VMCOpt.startVarianceReduction.repeatHistory           =   0.251; %*

VMCOpt.startVarianceReduction.splitPhotons            =   1; %*

VMCOpt.startVarianceReduction.photonSplitFactor       =   -40; %*

VMCOpt.startQuasi.base                                =   2; %*

VMCOpt.startQuasi.dimension                           =   60; %*

VMCOpt.startQuasi.skip                                =   1; %*


text:
function tSeries = rmBlurGrayTSeries(view,tSeries,iterlambda)
% rmBlurGrayTSeries - smooth raw time series across cortical surface
%
% tSeries = rmBlurGrayTSeries(view,tSeries,iterlambda);
%
% result^{i+1}[x] = c2[x] s^i[x]               data missing
% 		  = c1[x] (input[x] + lambda s^i[x])     otherwise
%
% c_1[x] = 1/(1 + numNeighbors)
% c_2[x] = 1/numNeighbors
% s[x] = sumNeighbors

% 2007/02 SOD: adapted from regularizeGray.

if ~exist('view','var') || isempty(view),
    error('Need view struct.');
else
    if ~strcmpi(view.viewType,'gray'),
        error('Need gray viewType.');
    end;
end;
if ~exist('tSeries','var') || isempty(tSeries),
    error('Need tSeries');
end;

% these defaults approximate a FWHM of 5mm at 1mm3 resolution
if ~exist('iterlambda','var') || isempty(iterlambda),
    iter = 5;
    lambda = 1;
else
  iter = iterlambda(1);
  lambda = iterlambda(2);
end;

% sanity check
if iter==0 || lambda==0,
    return;
end;

% works only on double format (for now):
tSeries = double(tSeries);

warning('off','MATLAB:divideByZero');

% Get numNeighbors and compute c1 and c2
edges        = double(view.edges);
numNeighbors = double(view.nodes(4,:));
edgeOffsets  = double(view.nodes(5,:));

% Initialize iterations
fprintf(1,'[%s]:Smoothing data:',mfilename);drawnow;tic;
for ii = 1:iter,
    % Get indices for missing data, we assume that data is missing for
    % entire time for a particular location.
    nanSummary = sum(tSeries,1);
    NaNs       = isnan(nanSummary);
    notNaNs    = ~isnan(nanSummary);
    withData   = double(notNaNs);

    % compute weights
    denom = sumOfNeighbors(withData,edges,edgeOffsets,numNeighbors)';

    % compute data that can be estimated (more than one valid data point
    % in the neighborhood)
    estdata = denom>0.5;

    % now restrict NaNs and notNaNs to estdata
    NaNs    = NaNs(:)    & estdata(:);
    notNaNs = notNaNs(:) & estdata(:);

    % new data
    newt    = NaN(1,size(tSeries,2));
    for n=1:size(tSeries,1)
        % input fill nans with zeros
        tmp = tSeries(n,:);
        tmp(NaNs) = 0;

        % Compute sumNeighbors
        sumNeighbors = sumOfNeighbors(tmp,edges,edgeOffsets,numNeighbors)';

        % Compute new values
        newt(NaNs)    = sumNeighbors(NaNs) ./ denom(NaNs);
        newt(notNaNs) = (tmp(notNaNs) + lambda.*sumNeighbors(notNaNs))./...
                        (denom(notNaNs)+1);

        % store
        tSeries(n,:)=newt;
    end;
    fprintf(1,'.');drawnow;
end;
fprintf(1,'Done[%.1fmin].\n',toc./60);drawnow;

return;


text:
%% s_qaOddEvenAnatomical
%
% For anatomical testing, we look at the odd and even planes in various
% directions, find the points above a threshold level for the brain mask,
% and compute the slice-to-slice correlation.  When the level is low, we
% worry.
%
% For diffusion, we should use mean diffusivity as a first test
%
% We compute the mean diffusivity of the diffusion data set
% We compare the MD between odd and even slices.
% We write out the correlation between the mean(MD(:,even)) mean(MD(:,odd)
%
% Try it for a few cases and see how it runs.
%
% Try it for some cases that that we know to be problematic
%
% Try it for different slice orientations (axial, sagittal and coronal)
%
% LM/BW Vistasoft Team, 2015

%%
chdir('~/Desktop')
[plinkList,delimiter] = importdata('memprage_nifti_files.txt');

%%  This is the value we use to decide whether we are in the brain

% By setting this level, we don't use the background as part of the
% correlation calculation
maskLevel = 120;

%% Download a file from LMP's nift file list using sdmGet

nFiles = length(plinkList);
minList = zeros(1,nFiles);
fullList = cell(1,nFiles);

figure;
for nn=1:nFiles
    tic

    pLink = plinkList{nn};
    sdmFile = sdmGet(pLink,'wandell@stanford.edu');

    %% Even and Odd

    % For each different dimension try this.
    %
    % The multi-echo has 4 dimensions.  We need to trap that case.
    % Similarly, we need to deal with the diffusion gradients and maybe
    % multiple b-values in the future.
    %
    % I guess we should always assume that the first 3 dimensions are the
    % volume and the side conditions are the other dimensions, such as time.
    anat1 = niftiRead(sdmFile);
    sz = anat1.dim;
    thisList = zeros(3,sz(4));
    % showMontage(anat1.data);

    %% Loop on each direction and each flip angle
    if length(sz) > 3
        for ii=1:sz(4)
            for dim = 1:3
                if dim == 3
                    odd = anat1.data(:,:,1:2:sz(3),ii);
                    even = anat1.data(:,:,2:2:sz(3),ii);
                elseif dim == 2
                    odd = anat1.data(:,1:2:sz(3),:,ii);
                    even = anat1.data(:,2:2:sz(3),:,ii);
                elseif dim ==1
                    % Is this Axial?  Or What?
                    odd = anat1.data(1:2:sz(3),:,:,ii);
                    even = anat1.data(2:2:sz(3),:,:,ii);
                end
                odd = odd(:); even = even(:);
                keep = (odd > maskLevel); odd = odd(keep); even = even(keep);
                R = corrcoef(single(odd(:)),single(even(:)));
                thisList(dim,ii)  = R(2,1);
            end
        end
    end
    toc

    %% Maybe force display by a flag

    % Store for future returns
    fullList{nn} = thisList;
    minList(nn) = min(thisList(:));

    % Running plot for user
    plot(minList,'-o'); set(gca,'ylim',[0.7 1]);
    xlabel('File number');
    ylabel('Min r across conditions')
    % line([1 nFiles],[T T],'color','r'); grid on; drawnow

    % Get rid of downloaded file
    delete(sdmFile);
end

save memprage fullList minList

%% Have a look at the worst one

% nn = 153;   % Worst one
% nn = 58, 121 are both pretty low
% 74 is really bad arcs.  See what looks odd about this

nn = 64;   % Best one
pLink = plinkList{nn};
fullList{nn}
sdmFile = sdmGet(pLink,'wandell@stanford.edu','tmp.nii.gz');
anat1 = niftiRead(sdmFile);
showMontage(anat1.data(:,:,:,1));

% Just called tmp.nii.gz
% delete(sdmFile);

mrvNewGraphWin;
plot(minList,'-o');

%
bad = 'https://sni-sdm.stanford.edu/api/acquisitions/55b705089173fc362ab00639/file/9999.109235058875865466036129522252016025427_nifti.nii.gz'
for ii=1:length(plinkList)
    if isequal(bad,plinkList{ii})
        disp(ii)
    end
end

%%


text:
function [fobj, fresidue, fsparsity, fregs] = getObjective_RegSc(X, B, S, Sigma, beta, gamma)

Err = X - B*S;

fresidue = 0.5*sum(sum(Err.^2));

fsparsity = gamma*sum(sum(abs(S)));

fregs = 0;
for ii = size(S, 1),
    fregs = fregs + beta*S(:, ii)'*Sigma*S(:, ii);
end

fobj = fresidue + fsparsity + fregs;

author: thomas-koehler

repo: SupER


text:
function [selection,value] = listdlgARH(varargin)
%LISTDLG  List selection dialog box.
%   [SELECTION,OK] = LISTDLG('ListString',S) creates a modal dialog box
%   which allows you to select a string or multiple strings from a list.
%   SELECTION is a vector of indices of the selected strings (length 1 in
%   the single selection mode).  This will be [] when OK is 0.  OK is 1 if
%   you push the OK button, or 0 if you push the Cancel button or close the
%   figure.
%
%   Double-clicking on an item or pressing <CR> when multiple items are
%   selected has the same effect as clicking the OK button.  Pressing <CR>
%   is the same as clicking the OK button. Pressing <ESC> is the same as
%   clicking the Cancel button.
%
%   Inputs are in parameter,value pairs:
%
%   Parameter       Description
%   'ListString'    cell array of strings for the list box.
%   'SelectionMode' string; can be 'single' or 'multiple'; defaults to
%                   'multiple'.
%   'ListSize'      [width height] of listbox in pixels; defaults
%                   to [160 300].
%   'InitialValue'  vector of indices of which items of the list box
%                   are initially selected; defaults to the first item.
%   'Name'          String for the figure's title; defaults to ''.
%   'PromptString'  string matrix or cell array of strings which appears
%                   as text above the list box; defaults to {}.
%   'OKString'      string for the OK button; defaults to 'OK'.
%   'CancelString'  string for the Cancel button; defaults to 'Cancel'.
%
%   A 'Select all' button is provided in the multiple selection case.
%
%   Example:
%     d = dir;
%     str = {d.name};
%     [s,v] = listdlg('PromptString','Select a file:',...
%                     'SelectionMode','single',...
%                     'ListString',str)
 %
%  See also DIALOG, ERRORDLG, HELPDLG, INPUTDLG,
%    MSGBOX, QUESTDLG, WARNDLG.

%   Copyright 1984-2014 The MathWorks, Inc.

%   'uh'            uicontrol button height, in pixels; default = 22.
%   'fus'           frame/uicontrol spacing, in pixels; default = 8.
%   'ffs'           frame/figure spacing, in pixels; default = 8.

% simple test:
%
% d = dir; [s,v] = listdlg('PromptString','Select a file:','ListString',{d.name});
%

% Generate a warning in -nodisplay and -noFigureWindows mode.
% warnfiguredialog('listdlgARH');

narginchk(1,inf)

figname = '';
smode = 2;   % (multiple)
promptstring = {};
liststring = [];
listsize = [160 300];
initialvalue = [];
okstring = getString(message('MATLAB:uistring:popupdialogs:OK'));
cancelstring = getString(message('MATLAB:uistring:popupdialogs:Cancel'));
fus = 8;
ffs = 8;
uh = 22;

if mod(length(varargin),2) ~= 0
    % input args have not com in pairs, woe is me
    error(message('MATLAB:listdlg:InvalidArgument'))
end
for i=1:2:length(varargin)
    switch lower(varargin{i})
     case 'name'
      figname = varargin{i+1};
     case 'promptstring'
      promptstring = varargin{i+1};
     case 'selectionmode'
      switch lower(varargin{i+1})
       case 'single'
        smode = 1;
       case 'multiple'
        smode = 2;
      end
     case 'listsize'
      listsize = varargin{i+1};
     case 'liststring'
      liststring = varargin{i+1};
     case 'initialvalue'
      initialvalue = varargin{i+1};
     case 'uh'
      uh = varargin{i+1};
     case 'fus'
      fus = varargin{i+1};
     case 'ffs'
      ffs = varargin{i+1};
     case 'okstring'
      okstring = varargin{i+1};
     case 'cancelstring'
      cancelstring = varargin{i+1};
     otherwise
      error(message('MATLAB:listdlg:UnknownParameter', varargin{ i }))
    end
end

if ischar(promptstring)
    promptstring = cellstr(promptstring);
end

if isempty(initialvalue) && smode==1
    initialvalue = 1;
end

if isempty(liststring)
    error(message('MATLAB:listdlg:NeedParameter'))
end

ex = get(0,'DefaultUicontrolFontSize')*1.7;  % height extent per line of uicontrol text (approx)

fp = get(0,'DefaultFigurePosition');
w = 2*(fus+ffs)+listsize(1);
h = 2*ffs+6*fus+ex*length(promptstring)+listsize(2)+uh+(smode==2)*(fus+uh);
fp = [fp(1) fp(2)+fp(4)-h w h];  % keep upper left corner fixed

fig_props = { ...
    'windowstyle'            'modal' ...
    'name'                   figname ...
    'color'                  get(0,'DefaultUicontrolBackgroundColor') ...
    'resize'                 'off' ...
    'numbertitle'            'off' ...
    'menubar'                'none' ...
    'visible'                'off' ...
    'createfcn'              ''    ...
    'position'               fp   ...
    'closerequestfcn'        'delete(gcbf)' ...
            };

liststring=cellstr(liststring);

fig = figure(fig_props{:});

if ~isempty(promptstring)
    prompt_text = uicontrol('Style','text','String',promptstring,...
        'HorizontalAlignment','left',...
        'Position',[ffs+fus fp(4)-(ffs+fus+ex*length(promptstring)) ...
        listsize(1) ex*length(promptstring)]); %#ok
end

btn_wid = (fp(3)-2*(ffs+fus)-fus)/2;

listbox = uicontrol('Style','listbox',...
                    'Position',[ffs+fus ffs+uh+4*fus+(smode==2)*(fus+uh) listsize],...
                    'String',liststring,...
                    'BackgroundColor','w',...
                    'Max',smode,...
                    'Tag','listbox',...
                    'Value',initialvalue, ...
                    'Callback', {@doListboxClick});

ok_btn = uicontrol('Style','pushbutton',...
                   'String',okstring,...
                   'Position',[ffs+fus ffs+fus btn_wid uh],...
                   'Tag','ok_btn',...
                   'Callback',{@doOK,listbox});

cancel_btn = uicontrol('Style','pushbutton',...
                       'String',cancelstring,...
                       'Position',[ffs+2*fus+btn_wid ffs+fus btn_wid uh],...
                       'Tag','cancel_btn',...
                       'Callback',{@doCancel,listbox});

if smode == 2
    selectall_btn = uicontrol('Style','pushbutton',...
                              'String',getString(message('MATLAB:uistring:popupdialogs:SelectAll')),...
                              'Position',[ffs+fus 4*fus+ffs+uh listsize(1) uh],...
                              'Tag','selectall_btn',...
                              'Callback',{@doSelectAll, listbox});

    if length(initialvalue) == length(liststring)
        set(selectall_btn,'Enable','off')
    end
    set(listbox,'Callback',{@doListboxClick, selectall_btn})
end

set([fig, ok_btn, cancel_btn, listbox], 'KeyPressFcn', {@doKeypress, listbox});

set(fig,'Position',getnicedialoglocationARH(fp, get(fig,'Units')));
% Make ok_btn the default button.
setdefaultbuttonARH(fig, ok_btn);

% make sure we are on screen
movegui(fig)
set(fig, 'Visible','on'); drawnow;

try
    % Give default focus to the listbox *after* the figure is made visible
    uicontrol(listbox);
    c = matlab.ui.internal.dialog.DialogUtils.disableAllWindowsSafely(true);
    uiwait(fig);
    delete(c);
catch
    if ishghandle(fig)
        delete(fig)
    end
end

if isappdata(0,'ListDialogAppData__')
    ad = getappdata(0,'ListDialogAppData__');
    selection = ad.selection;
    value = ad.value;
    rmappdata(0,'ListDialogAppData__')
else
    % figure was deleted
    selection = [];
    value = 0;
end
drawnow; % Update the view to remove the closed figure (g1031998)

%% figure, OK and Cancel KeyPressFcn
function doKeypress(src, evd, listbox) %#ok
switch evd.Key
 case 'escape'
  doCancel([],[],listbox);
end

%% OK callback
function doOK(ok_btn, evd, listbox) %#ok
if (~isappdata(0, 'ListDialogAppData__'))
    ad.value = 1;
    ad.selection = get(listbox,'Value');
    setappdata(0,'ListDialogAppData__',ad);
    delete(gcbf);
end

%% Cancel callback
function doCancel(cancel_btn, evd, listbox) %#ok
ad.value = 0;
ad.selection = [];
setappdata(0,'ListDialogAppData__',ad)
delete(gcbf);

%% SelectAll callback
function doSelectAll(selectall_btn, evd, listbox) %#ok
set(selectall_btn,'Enable','off')
set(listbox,'Value',1:length(get(listbox,'String')));

%% Listbox callback
function doListboxClick(listbox, evd, selectall_btn) %#ok
% if this is a doubleclick, doOK
if strcmp(get(gcbf,'SelectionType'),'open')
    doOK([],[],listbox);
elseif nargin == 3
    if length(get(listbox,'String'))==length(get(listbox,'Value'))
        set(selectall_btn,'Enable','off')
    else
        set(selectall_btn,'Enable','on')
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED "AS IS."  THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.
%
% file: interval_est_r.m
% computes confidence interval estimates for rates.
%
% 022400 tdr created
% 031600 tdr created rate version from interval_est_p.m
% 032200 tdr added cs1, cs2, and tl methods.
% 012601 tdr added input checking.
% 012901 tdr added 1-sided CIs for CS1 method
% 031501 tdr added minimum length method
%

function ci = interval_est_r(x,A,alpha,method)

% ------------------------------------------------------------
% start checking inputs

if nargin ~= 4,
    error('Requires four input arguments (x,A,alpha,method)');
end

% inputs must all be scalars
if (max(max([size(x); size(A); size(alpha)])) ~= 1)
    error('Non-scalar input');
end;

% x must be integer
if (round(x) ~= x)
    x = round(x);
    warning('Non-integer input x');
end;

% A must be > 0
if (A <= 0),
   ci = [ NaN NaN NaN];
   warning('A <= 0');
   return;
end;

% x must be >= 0
if ( x < 0),
   ci = [ NaN NaN NaN];
   warning('x < 0');
   return;
end;

% alpha must be > 0.0 and < 1.0
if ( alpha < 0 | alpha > 1),
   ci = [ NaN NaN NaN];
   warning('alpha < 0 or alpha > 1');
   return;
end;

% normalize case
if strcmpi(method,'cs1'), method = 'cs1'; end;
if strcmpi(method,'cs1_1s'), method = 'cs1_1s'; end;
if strcmpi(method,'cs2'), method = 'cs2'; end;
if strcmpi(method,'ibp'), method = 'ibp'; end;
%if strcmpi(method,'ibp_1s'), method = 'ibp_1s'; end;
if strcmpi(method,'ml'), method = 'ml'; end;
if strcmpi(method,'nibp'), method = 'nibp'; end;
%if strcmpi(method,'nibp_1s'), method = 'nibp_1s'; end;
if strcmpi(method,'na'), method = 'na'; end;
if strcmpi(method,'tl'), method = 'tl'; end;

% end checking inputs
% ------------------------------------------------------------

switch method
case 'cs1',
   ci = get_r_ci_cs1(x,A,alpha);
case 'cs1_1s',
   ci = get_r_ci_cs1_1s(x,A,alpha);
case 'cs2',
   ci = get_r_ci_cs2(x,A,alpha);
case 'ibp',
   ci = get_r_ci_ibp(x,A,alpha);
case 'ml',
   ci = get_r_ci_ml(x,A,alpha);
case 'na',
   ci = get_r_ci_na(x,A,alpha);
case 'tl',
   ci = get_r_ci_tl(x,A,alpha);
otherwise
   error('Method not recognized. Methods Available: cs1/cs2 - COMPASE Standards, ibp - Integration of Bayes Posterior; ml - minimum length; na - Normal Approximation; tl - Table Lookup');
end;


text:
filename='Gripping_quad_coarse';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'nonadjoint_compliance'};
weights = [1, 0.1];
constraint = {'volumeConstraint'};
constraint_case = 'INEQUALITY';
optimizer = 'IPOPT'; incrementFactor = 1;
filterType = 'P1';

nsteps = 1;
Vfrac_final = 0.75;
optimality_final = 1e-3;
constr_final =1e-3;

Vfrac_initial = 1;
optimality_initial = 1e-3;
constr_initial = 1e-3;
TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;