text:
%kextractor 'Interactive image Region of Interest (ROI) extraction'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros extractor.pane file
%
% Parameters:
% InputFile: i 'Input File', required: 'File containing image from which to extract ROI'
% OutputFile: o 'Output ROI ', optional: 'Output image in which to save ROI'
% MultiChoice: shape 'ROI Shape:', default: 1: 'Desired shape for ROI'
%    Choices are:
%   1: 'Rectangle'
%   2: 'Polyline'
%   3: 'Circle'
%   4: 'Ellipse'
%   5: 'Line'
%   6: 'Freehand'
% Integer: x 'X Placement', default: -1: 'X location for GUI autoplacement'
% Integer: y 'Y Placement', default: -1: 'Y location for GUI autoplacement'
% Double: update 'Update time', default: 1: 'How often to check input file for modification'
%
% Example: o = kextractor(i, {'i','';'o','';'shape',1;'x',-1;'y',-1;'update',1})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% extractor - Interactive image Region of Interest (ROI) extraction
%
%  DESCRIPTION
%
% The extractor program allows you to display an image, and interactively
% extract regions of interest (ROI's) from it.  The region of interest shapes
% supported include rectangle, line, polyline, signal, circle, curve, ellipse,
% and freehand.  The region of interest extracted may be defined by the region
% inside the shape, by the region outside the shape, or by the outline of the
% shape.  When a region of interest is extracted, it may be written to an output
% file, displayed in a separate window, or both.
%
% When running extractor, you must provide an input image.  If desired, you may
% specify the shape to be used in ROI extraction using the [-shape] argument.
% The [-disp] argument may be used to specify whether the extracted ROI is
% automatically displayed in a separate window.  The [-o] argument may be used
% to specify an output file.  Note that the extracted ROI may be displayed in
% a separate window, written to an output file, or both.  The ROI Extraction
% Policy dictates whether the region of interest is to be specified by the
% area inside the shape, by the area outside the shape, or by the outline of the
% shape; this can be specified using the [-policy] argument.
%
% For all ROI extraction, you will first indicate the desired region of interest
% by drawing the desired shape in the input image.  For all ROI shapes except
% signal (for which it does not apply) a mask is employed to obscure the pixels
% which are not inside the region of interest before the ROI is written to disk
% or displayed.  How the mask is applied depends on the ROI Extraction Policy.  ROI's may be
% defined by the area inside the shape drawn, the area outside the shape drawn,
% or by the outline of the shape drawn.
%
% Once the input image is displayed, the desired ROI shape is specified, the
% desired ROI Extraction Policy is given, and an optional output filename is
% entered (all of which can be done using the arguments to extractor) you
% may immediately begin the ROI extraction process. The procedure used to
% specify the region of interest in the input image will differ depending on
% the ROI shape being used. The following is a summary of the available ROI
% shapes and the procedure used for the extraction of each.
%
%
%  "Rectangle"
% The region of interest will be defined by a simple rectangle. For an
% ROI Extraction policy of "Inside Shape", the subimage defined by the rectangle
% is extracted.  For an ROI Extraction policy of "Shape Outline", the bounding
% box of the rectangle is calculated, and all pixel values inside the bounding
% box but not on the outline of the rectangle are masked out.  For an ROI
% Extraction policy of "Outside Shape", the pixel values within the rectangle
% are masked out, while the remainder of the image is preserved.
%
%
% To extract a rectangular region of interest, rubberband the rectangle
% surrounding the region of interest in the input image.  To rubberband the
% rectangle, click the mouse button on a corner of the desired region of interest.
% Holding the mouse button down, move the mouse to the opposite corner of the
% desired rectangle.  The rectangle will refreshed as the mouse moves, or
% "rubberbanded" after the mouse.
%
%
%  "Line"
% The region of interest will be defined by a line.  For ROI Extraction Policies
% of "Inside Shape" and "Shape Outline", the bounding box is calculated from the
% endpoints of the line and all pixel values within the bounding box but not on
% the line are masked out.  For an ROI Extraction Policy of "Outside Shape",
% all pixels on the line itself are masked out, while the rest of the image is
% preserved.
%
%
% To extract a line region of interest, rubberband the line defining
% the region of interest in the input image.  To rubberband the line, click the
% mouse button on one endpoint of the desired region of interest.  Holding the
% mouse button down, move the mouse to the other endpoint of the line.
%
%
%  "Signal"
% The region of interest will be defined by a line; however, rather than
% computing the bounding box of the line and masking out all unwanted pixels,
% the pixel values on the line are written out "alone" to the output image.
% Thus, the extraction of signal ROI's is a useful way of creating VIFF images
% containing single lines of image data that can be used in a 2D plot.  The
% ROI Extraction Policy does not apply to the signal ROI.
%
%
% Extraction of a signal is identical to extraction of a line (see above).
%
%
%  "Polyline"
% The region of interest will be defined by a polyline. For ROI Extraction
% Policy of "Inside Shape", the bounding box is calculated from the vertices
% of the polyline and all pixel values within the bounding box but not inside
% the polygon are masked out. For an ROI Extraction policy of "Shape Outline",
% the bounding box is calculated from the vertices of the polyline and all pixel
% values not on the polyline itself are masked out.  For ROI Extraction policy of
% "Outside Shape", all pixels within the polyline are masked out, while the
% rest of the image is preserved.
%
%
% To extract a polyline region of interest, begin by clicking the mouse on
% one vertex of the desired polyline. As you move the mouse, a line will be
% rubberbanded after it.  Continue to button click on each successive vertex,
% until the polyline appears as desired; double click to end the polyline.
% The first and last vertices of the polyline will be joined in order to define
% a closed region of interest.
%
%
%  "Circle"
% The region of interest will be defined by a circle. For ROI Extraction
% Policy of "Inside Shape", the bounding box is calculated from the dimensions
% of the circle and all pixel values within the bounding box but not inside
% the circle are masked out. For an ROI Extraction policy of "Shape Outline",
% the bounding box is calculated from the vertices of the polyline and all pixel
% values not on the circle itself are masked out.  For ROI Extraction policy of
% "Outside Shape", all pixels within the circle are masked out, while the
% rest of the image is preserved.
%
%
% To extract a circular region of interest, rubberband the circle defining
% the region of interest in the input image.  To rubberband the circle, click
% the mouse button on the center of the desired region of interest.  Holding
% the mouse button down, move the mouse until the circle has the desired radius.
%
%
%  "Ellipse"
% The ellipse region of interest works similarly to that of a circle (see above).
% To extract an ellipsoid region of interest, rubberband the ellipse defining
% the region of interest in the input image.  Rubberbanding an ellipse is similar
% to rubberbanding a circle, except that the width and height of the ellipse will
% be changed with horizontal and vertical mouse movement.
%
%
%
%
%
%  EXAMPLES
% % extractor -i image:mandril
%
%  "SEE ALSO"
% editimage(1)
%
%  RESTRICTIONS
%
%  REFERENCES
% The extractor program is covered in detail in Chapter 5 of the Envision Manual.
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kextractor(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kextractor(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'o', '__output';'shape', 1;'x', -1;'y', -1;'update', 1};
maxval={0,1,0,1000,1000,1};
minval={0,1,0,-1,-1,1};
istoggle=[0,1,0,1,1,1];
was_set=istoggle * 0;
paramtype={'InputFile','OutputFile','MultiChoice','Integer','Integer','Double'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=0; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'extractor"  '],Inputs,narglist);

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
%% KalmanFilterX Demo
% ----------------------
% * This script demonstrates the process of configuring an running a
%   KalmanFilterX object to perform single-target state estimation.
%
% * A toy single-target scenario is considered, for a target that generates
%   regular reports of it's position in the absence of clutter and/or
%   missed detection.
%
%% Extract the GroundTruth data from the example workspace
load('single-target-tracking.mat');
NumIter = size(TrueTrack.Trajectory,2);

%% Models
% Instantiate a Transitionamic model
transition_model = ConstantVelocityX('NumDims',2,'VelocityErrVariance',0.0001);

% Instantiate an Observation model
measurement_model = LinearGaussianX('NumMeasDims',2,'NumStateDims',4,'MeasurementErrVariance',0.02,'Mapping',[1 3]);
%measurement_model = RangeBearing2CartesianX('NumStateDims',4,'MeasurementErrVariance',[0.001,0.02],'Mapping',[1 3]);

% Compile the State-Space model
model = StateSpaceModelX(transition_model,measurement_model);

%% Simulation
% Data Simulator
dataSim = SingleTargetMeasurementSimulatorX(model);

% Simulate some measurements from ground-truth data
MeasurementScans = dataSim.simulate(TrueTrack);
measurements = [MeasurementScans.Vectors];

%% Initiation
% Use the first measurement scan to perform single-point initiation
measurement = MeasurementScans(1).Measurements;
timestamp = measurement.Timestamp;

% Setup prior
xPrior = measurement.Model.Measurement.finv(measurement.Vector);
PPrior = 10*transition_model.covar();
dist = GaussianDistributionX(xPrior,PPrior);
StatePrior = GaussianStateX(dist,timestamp);

% Initiate a track using the generated prior
track = TrackX(StatePrior, TagX(1));

%% Estimation
% Instantiate a filter objects
filter = KalmanFilterX('Model',model);
figure;
for t = 2:NumIter

    % Provide filter with the new measurement
    MeasurementList = MeasurementScans(t);

    % Perform filtering
    prior = track.State;
    prediction = filter.predict(prior, MeasurementList.Timestamp);
    posterior = filter.update(prediction, MeasurementList);

    % Log the data
    track.Trajectory(end+1) = posterior;

    clf;
    hold on;
    meas = measurement_model.finv(measurements(:,1:t));
    true_means = [TrueTrack.Trajectory(1:t).Vector];
    track_means = [track.Trajectory(1:t).Mean];
    plot(true_means(1,1:t), true_means(3,1:t),'.-k', track_means(1,1:t), track_means(3,1:t), 'b-', meas(1,:), meas(3,:), 'rx');
    plotgaussellipse(track.Trajectory(t).Mean([1,3],1),...
                     track.Trajectory(t).Covar([1,3],[1,3]));
    legend('GroundTrouth','Estimated Mean','Measurements', 'Estimated Covariance');
    xlabel("x coordinate (m)");
    ylabel("y coordinate (m)");
    axis([2 9 1 9]);
    drawnow();
end

author: sglvladi

repo: TrackingX

save_path: github-repos/MATLAB/sglvladi-TrackingX


text:
function [saliencyFeatures,saliencyMask,saliencyMap] = PQFT_2(img,img_3,varargin)
%%PQFT is written to demonstrate the ability of generating PQFT saliency
%%map
% Article: A Novel Multiresoulution Spatiotemporal Saliency Detection Model
% and Its Applications in Image and Video Compression
% input:
% img: current image
% img_3: frame at t = -3
% Copyright LE NGO ANH CAT, The University of Nottingham, Malaysia Campus 2012

%% Read info of img

% Tune the application for lane mark detection.
% Default value is 'general'
% Lanemark application has 'lanemark' tag
tmp_img = img;
inImg = im2double(img);
img_3 = im2double(img_3);
[row col] = size(rgb2gray(img));
visualScale = varargin{2};
inImg = imresize(inImg, [visualScale, visualScale], 'bilinear');
img_3 = imresize(img_3, [visualScale, visualScale], 'bilinear');
%% Create a quaternion image

r = inImg(:,:,1);
g = inImg(:,:,2);
b = inImg(:,:,3);

R = r - (b + g) /2;
G = g - (r + b) /2;
B = b - (r + g) /2;
Y = (r + g)/2 - abs(r - g)/2 - b;

% 2 Color channels
RG = R - G;
BY = B - Y;

% 1 Intensity channel
I = ( r + g + b ) / 3;
I_3 = sum(img_3,3) / 3;

% 1 Motion channel
M = abs(I - I_3);

% tst = zeros(varargin{2},varargin{2});
% q = quaternion(M,tst,tst,tst);
% q = quaternion(tst,RG,tst,tst);
% q = quaternion(tst,tst,BY,tst);
% q = quaternion(tst,tst,tst,I);
q = quaternion(M,RG,BY,I);

%% Test for edge features
% gray_img = rgb2gray(inImg);
% HE = double(edge(gray_img,'sobel','horizontal'));
% VE = double(edge(gray_img,'sobel','vertical'));
% q = quaternion(M,HE,VE,I);

%% Create Spatio-temporal Saliency Map by using QFT (Quaternion Fourier
%% Transform

myFFT = fft2(q);
a = ones(visualScale,visualScale)*q1 + ones(visualScale,visualScale)*q2 + ones(visualScale,visualScale)*q3;
myPhase = angle(myFFT,unit(a));

%% Display the spectrum of images with Gaussian Smoother
% tmp_myPhase = reshape(myPhase,[1 4096]);
% [n,xout] = hist(tmp_myPhase,100);
% figure;
% plot(xout,n);
% % % Gaussian Filter begin
% % gf=gausswin(8,3);
% % gf=gf/sum(gf);
% % n_smoothed=conv(gf,n);
% % figure;
% % plot(n_smoothed);
% ylabel('No of pixels');
% xlabel('Phase');
% % % Datacursors format
% % alldatacursors = findall(gcf,'type','hggroup');
% % set(alldatacursors,'FontSize',12);
saliencyMap = abs(ifft2(exp(1i*myPhase))).^2;
saliencyMap(1,1) = (saliencyMap(1,2) + saliencyMap(2,2) + saliencyMap(2,1))/3;
%% After Effect
if (isequal(varargin{1},'disk'))
    saliencyMap = imfilter(saliencyMap, fspecial('disk', 3));
elseif (isequal(varargin{1},'gaussian'))
    saliencyMap = imfilter(saliencyMap, fspecial('gaussian', 8, 3));
end
saliencyMap = mat2gray(saliencyMap);
% imshow(saliencyMap);
saliencyMask = im2bw(saliencyMap,graythresh(saliencyMap));

saliencyMap = imresize(saliencyMap, [row,col], 'bilinear');
saliencyMask = imresize(saliencyMask, [row,col], 'bilinear');

% %% LME as post-processing step
% if isequal(varargin{3},'lanemark_pospro')
%     img = LME(img);
%     saliencyMask = saliencyMask | (rgb2gray(img) > 0);
% end
%
% %% Result Presentation
% img = tmp_img;
% grayImg = double(rgb2gray(img));
%
% % % The below code line is for drawing around the lanemark
% % saliencyMask = 1 - edge(double(saliencyMask),'canny');
% saliencyFeatures = grayImg .* saliencyMask;

%% Filter the unnecessary road parts
tmp(:,:,1) = tmp_img(:,:,1) .* uint8(saliencyMask);
tmp(:,:,2) = tmp_img(:,:,2) .* uint8(saliencyMask);
tmp(:,:,3) = tmp_img(:,:,3) .* uint8(saliencyMask);
tmp = []; % Delete temporary variable

%% Result Presentation in Grayscale or Color
img = tmp_img;

if (nargin - 2 < 3) || isequal(varargin{3},'grayscale')
    grayImg = double(rgb2gray(img));
    % saliencyMask = 1 - edge(double(saliencyMask),'canny');
    saliencyFeatures = grayImg .* saliencyMask;
elseif isequal(varargin{3},'color')
    saliencyFeatures(:,:,1) = img(:,:,1) .* uint8(saliencyMask);
    saliencyFeatures(:,:,2) = img(:,:,2) .* uint8(saliencyMask);
    saliencyFeatures(:,:,3) = img(:,:,3) .* uint8(saliencyMask);
end
end

author: Sable

repo: mcbench-benchmarks


text:
function value = circle_annulus_area_2d ( radius1, radius2 )

%*****************************************************************************80
%
%% CIRCLE_ANNULUS_AREA_2D returns the area of a circular annulus in 2D.
%
%  Integration region:
%
%    Points (X,Y) such that
%
%      RADIUS1**2 <= ( X - XC )**2 + ( Y - YC )**2 <= RADIUS2**2
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 May 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real RADIUS1, RADIUS2, the radii of the circles.
%
%    Output, real CIRCLE_ANNULUS_AREA_2D, the area of the annulus.
%
  value = pi * ( radius1 + radius2 ) * ( radius2 - radius1 );

  return
end

author: johannesgerer

repo: jburkardt-m


text: %SETTYPE Set TYPE datafile field

author: marianux

repo: ecg-kit

save_path: github-repos/MATLAB/marianux-ecg-kit


text:
function varargout=plotmodt(t,tper,y,fitflag,MarkerSize)

% plotmodt(t,tper,y)
% plotmodt(t,tper,y,fitflag)
% plotmodt(t,tper,y,fitflag,MarkerSize)
% [tt,yy]=plotmodt(t,tper,y)
% [tt,yy,yyres]=plotmodt(t,tper,y,1)
%
% The Modulo Time Plot is useful for quick visual inspection
% of system performance including dynamic range, distortion and
% error plots, the detection of random bit errors, and timing errors
% between the test signal and the sample clock. [1]
%
% The method also works well on plotting eye diagrams.
%
% INPUTS        t: time vector, required as t is not always linearly spaced
%               tper: the trace period
%               y: input signal
%               fitflag: if 1, perform fit to find the residual
%                        works well for distorted 1-tones, see also (*)
%               MarkeSize: To adjust the resolution of the plot default:4
%                         (if y is large, MarkerSize should be small)
% OUPUTS        tt & yy: inputs t and y rearranged into a trace period
%               yyres: residual of y (if fit is done) also rearranged
%
% type plotmodt to launch two examples
%
% Author: Marko Neitola, University of Oulu, Finland
%
%[1] F. H. Irons andD. M. Hummels,
%"The Modulo Time Plot - a Useful Data Acquisition Diagnostic Tool"
%IEEE Tr. on Instrumentation and Measurement, Vol.45, NO. 3, June 1996
%(*) the order of fit is fixed to 17, unless you download
%    the "polydeg" function (optimal polyn. degree) by Damien Garcia:
%    http://www.biomecardio.com/matlab/polydeg.html

if nargin ==0
    % Example 1 grabbed from for EYEMAP File ID: #15900
    n_simb = 1024; %Number of symbols
    ak=round(rand(1,n_simb)); %create random binary sequence
    n_pt=128; %Number of samples per symbol
    signal=zeros(1,length(ak)*n_pt); %initialize signal variable
    for k=1:length(ak) %Generate polar signal from digital sequence
        signal((k-1)*n_pt+1:k*n_pt) = 2*(ak(k)-0.5);
    end;
    %Filter signal using a gaussian filter
    signal=real(ifft(fft(signal).*exp(-(1:length(signal)).^2/n_simb^2)));
    %Generate random gaussian noise
    noise=randn(size(signal))*0.1;
    %Visualize eye diagram of signal and noise
    figure
    plotmodt(0:131071,n_pt*4,signal+noise,0,4)
    %eyemap(signal+noise,n_pt*2)  % you can compare this to File ID: #15900

    %example 2: distorted sinusoid
    N=pow2(11);          	%vector length
    fs = pi*1e3;            %sampling freq
    ts = 1/fs;              %sampling interval
    freq = (N/128-1)*fs/N;  %freq (Hz)
    phase = -pi/8;          %phase (rad)
    offset = pi*4;          %offset (i.e mean)
    amplitude = pi/3;       %amplitude
    t = (0:(N-1))*ts;       %time vector
    std_jitter = 1e-2;  %standard deviation of jitter noise
    std_addnoi = 1e-1;  %standard deviation of  noise added to signal
    std_phase  = 0.2;   %standard deviation of phase noise
    noise = randn(1,N);
    std1_noise = noise/std(noise);  % random vector with stdev = 1
    jit_noise = std_jitter*std1_noise;
    phase_noise = std_phase*std1_noise;
    add_noise = std_addnoi*std1_noise;
    w=2*pi*freq;
    t = t + ts*jit_noise;                          % add clock jitter
    A2 = 0.1;     % 2. harmonic ampl
    A3 = 0.5;     % 3. harmonic ampl
    yin = cos(w*t+phase+phase_noise);  % sinusoid with phase noise
    yin = offset+amplitude*yin+A2*yin.*yin+A3*yin.*yin.*yin+add_noise; %add offset, noise & harmonics
    figure
    plotmodt(t,1/freq,yin,1,4)
    return
end

ts = norm(diff(t))/sqrt(length(t)-1);
lstyle = 'k.';

%The main idea is in these 3 lines:
tt=mod(t,tper);
[tt,index]=sort(tt);
yy=y(index);

if nargin == 3
    fitflag=0;
end
if nargin < 5
    MarkerSize = 4;
end

if fitflag == 1
    if exist('polydeg','file')==2
        n_poly = polydeg(tt,yy);
    else
        n_poly=17;
    end
    warning off %#ok<WNOFF>
    p=polyfit(tt,yy,n_poly);
    warning on %#ok<WNON>
    yest=polyval(p,tt);
    legendtext = ['polyfit (o:',int2str(n_poly),')'];

    yyresi = yy-yest;
    subplot(211)

    plot(tt,yy,lstyle,tt,yest,'-r','MarkerSize',MarkerSize)
    title(['trace period plot, period is ', num2str(tper,2),'s. t_s = ', num2str(ts,2),'s'])
    axis tight,legend('data',legendtext,1),xlabel('time, 1 period')

    subplot(212)
    plot(tt,yyresi,lstyle,'MarkerSize',MarkerSize)
    title('trace period plot, residual'), axis tight,xlabel('time, 1 period')

else
    subplot(111)
    plot(tt,yy,lstyle,'MarkerSize',MarkerSize)
    title(['trace period plot, period is ', num2str(tper,2),'s. t_s = ', num2str(ts,2),'s'])
    axis tight,xlabel('time, 1 period')
end

if nargout>0
    varargout{1}=tt;
    varargout{2}=yy;
    if nargout == 3
        varargout{3}=yyresi;
    end
end


text:
function out=prox_l1_squared(x,alpha)
%PROX_L1_SQUARED computes the proximal operator of the function alpha*(norm(x(:),1)^2)
%
%  Usage:
%  out = PROX_L1_SQUARED(x,alpha)
%  ===========================================
%  INPUT:
%  x - point to be projected (vector/matrix)
%  alpha - positive scalar
%  ===========================================
%  Output:
%  out - proximal operator at x

% This file is part of the FOM package - a collection of first order methods for solving convex optimization problems
% Copyright (C) 2017 Amir and Nili Beck
%
% 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 3 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, see <http://www.gnu.org/licenses/>.

if (nargin < 2)
    error ('usage: prox_l1_squared(x,alpha)') ;
end

if (alpha < 0)
    error('usage: prox_l1_squared(x,alpha) - alpha should be positive')
end

%setting eps to defalut value : 1e-10
eps = 1e-10 ;

if (norm(x) < eps)
    out = x;
    return ;
end

%defining f on mu - to be used by the bisetion
f=@(mu)   sum(sum( max(sqrt(alpha) *abs(x)/sqrt(mu) - 2*alpha,0))) - 1 ;

mu_min = 0 ;
mu_max = 1 ;
while(f(mu_max)> 0)
    mu_max = mu_max * 2 ;
end

final_mu = bisection(f,mu_min,mu_max,eps) ;
lam = max(sqrt(alpha) * abs(x)/sqrt(final_mu) - 2 *alpha,0) ;

out = (lam .* x) ./ (lam + 2 * alpha) ;

end

author: hiroyuki-kasai

repo: SGDLibrary


text:
function [] = generate_undistort_map_radtan(cinfo, sequence_name, batch_size)
%GENERATE_UNDISTORT_MAP_RADTAN generates a mapping from distorted to
%undistorted pixels in a given image with radtan camera distortion, given
%the camera intrinsics.
%
% Syntax: GENERATE_UNDISTORT_MAP_RADTAN(cinfo, sequence_name, batch_size)
%
% Inputs:
%    cinfo         - camera info struct, generated by extract_ros_data.
%    sequence_name - string to be concatenated to the output name.
%    batch_size    - OPTIONAL number of points to undistort at once.
%                    Unclear if increasing this will speed up the program.
%
% See also EXTRACT_ROS_DATA
%
% Author: Alex Zihao Zhu, University of Pennsylvania
% Email: alexzhu(at)seas.upenn.edu
% Copyright 2018 University of Pennsylvania
% Alex Zihao Zhu, Nikolay Atanasov, Kostas Daniilidis
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS, CONTRIBUTORS, AND THE
% TRUSTEES OF THE UNIVERSITY OF PENNSYLVANIA "AS IS" AND ANY EXPRESS OR
% IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
% OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
% IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE TRUSTEES OF
% THE UNIVERSITY OF PENNSYLVANIA BE LIABLE FOR ANY DIRECT, INDIRECT,
% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
% NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
% THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
% THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

output_name = ['undistort_map_', sequence_name];
fprintf('Generating undistort maps and saving in %s. This may take some time.\n', ...
    output_name)

if nargin < 3
    batch_size = 1;
end

K = reshape(cinfo.K, 3, 3);
D = cinfo.D;
rows = cinfo.height;
cols = cinfo.width;
cameraParams = cameraParameters(...
    'IntrinsicMatrix', K, ...
    'RadialDistortion', D(1:2), ...
    'TangentialDistortion', D(3:4));

undistort_map_x = zeros(rows, cols);
undistort_map_y = zeros(rows, cols);

[X, Y] = meshgrid(0:cols-1, 0:rows-1);
X = X(:);
Y = Y(:);

n_pts = length(X);
undistorted_points = zeros(n_pts, 2);

last_iter = 1;
fprintf('Processing %d points\n', n_pts);
for i=1:batch_size:n_pts
    end_val = min(n_pts, i+batch_size-1);
    undistorted_points(i:end_val, :) = undistortPoints([X(i:end_val) Y(i:end_val)], cameraParams);
    if i - last_iter >= 1000
        fprintf('Processed %d points\n', i);
        last_iter = i;
    end
end

% undistortedPoints = undistortPoints([X Y], cameraParams);
addpath('../EventFeatureTracking/Tracker/')
inds = sub2indc(X+1, Y+1, [rows, cols]);
undistort_map_x(inds) = undistorted_points(:, 1);
undistort_map_y(inds) = undistorted_points(:, 2);

save(output_name, 'undistort_map_x', 'undistort_map_y', '-v7.3');
end

author: daniilidis-group


text:
function [tg] = tgso2(tmap,ntex,radius,theta,varargin)
% function [tg] = tgso2(tmap,ntex,radius,theta,...)
%
% Compute the texture gradient at a single orientation and scale.
%
% INPUT
%	tmap		Texton map, values in [1,ntex].
%	ntex		Number of textons.
%	radius		Radius of disc for tg.
%	theta		Orientation orthogonal to tg.
%	'smooth'	Smoothing method, one of
%			{'gaussian','savgol','none'}, default 'none'.
%	'sigma'		Sigma for smoothing, default to radius.
%	'tsim'		Texton similarity matrix.  If not
%			provided, then use chi-squared.
%
% OUTPUT
%	tg		The tg image.
%
% David R. Martin <dmartin@eecs.berkeley.edu>
% March 2003

% process options
smooth = 'none';
sigma = radius;
usechi2 = true;
for i = 1:2:numel(varargin),
  opt = varargin{i};
  if ~ischar(opt), error('option names not a string'); end
  if i==numel(varargin), error(sprintf('option ''%s'' has no value',opt)); end
  val = varargin{i+1};
  switch opt,
   case 'smooth',
    switch val,
     case {'none','gaussian','savgol'}, smooth=val;
     otherwise, error(sprintf('invalid option smooth=''%s''',val));
    end
   case 'sigma', sigma=val;
   case 'tsim', tsim=val; usechi2=false;
   otherwise, error(sprintf('invalid option ''%s''',opt));
  end
end

radius = max(1,radius);
theta = mod(theta,pi);

% check texton labels
if any(tmap~=round(tmap)),
  error('texton labels not integral');
end
if min(tmap(:)) < 1 | max(tmap(:))>ntex,
  error(sprintf('texton labels out of range [1,%d]',ntex));
end

% radius of discrete disc
wr = floor(radius);

% count number of pixels in a disc
[u,v] = meshgrid(-wr:wr,-wr:wr);
gamma = atan2(v,u);
mask = (u.^2 + v.^2 <= radius^2);
mask(wr+1,wr+1) = 0; % mask out center pixel to remove bias
count = sum(mask(:));

% determine which half of the disc pixels fall in
% (0=masked 1=left 2=right)
side = 1 + (mod(gamma-theta,2*pi) < pi);
side = side .* mask;
if sum(sum(side==1)) ~= sum(sum(side==2)), error('bug:inbalance'); end

[h,w] = size(tmap);
tg = zeros(h,w);
fwrite(2,'[');
for x = 1:w,
  fwrite(2,'.');
  for y = 1:h,
    hist = zeros(ntex,2);
    for u = -wr:wr,
      xi = x + u;
      if xi<1 | xi>w, continue; end
      for v = -wr:wr,
        yi = y + v;
        if yi<1 | yi>h, continue; end
        s = side(v+wr+1,u+wr+1);
        if s==0, continue; end % masked out
        t = tmap(yi,xi);
        hist(t,s) = hist(t,s) + 1;
      end
    end
    hist = hist .* (2/count); % normalize
    if usechi2,
      chi = (hist(:,1)-hist(:,2)).^2 ./ (hist(:,1)+hist(:,2)+eps);
      tg(y,x) = 0.5*sum(chi);
    else
      lrdiff = abs(hist(:,1)-hist(:,2));
      tg(y,x) = lrdiff' * tsim * lrdiff;
    end
  end
end
fprintf(2,']\n');

switch smooth,
 case 'gaussian',
  f = oeFilter([sigma .5],3,theta+pi/2);
  tg = applyFilter(f,tg);
 case 'savgol',
  a = fitparab(tg,sigma,sigma/4,theta);
  tg = max(0,a);
end

author: Cloud-CV

repo: object-proposals


text:
function analyticalSolution = analyticalSolutionQP(HessianMatrixQP,gradientQP)

    % ANALYTICALSOLUTIONQP provides the unconstrained solution of a QP
    %                      problem. To be used as possible alternative when
    %                      the WBToolbox "QP block" fails to find a solution.
    %
    % FORMAT: analyticalSolution = analyticalSolutionQP(HessianMatrixQP,gradientQP)
    %
    % INPUT:   - HessianMatrixQP = hessian matrix of the QP problem;
    %          - gradientQP      = gradient of the QP problem.
    %
    % OUTPUT:  - analyticalSolution = the analytical solution of the QP problem.
    %
    % Authors: Daniele Pucci, Marie Charbonneau, Gabriele Nava
    %
    %          all authors are with the Italian Istitute of Technology (IIT)
    %          email: name.surname@iit.it
    %
    % Genoa, Dec 2017
    %

    %% --- Initialization ---

    analyticalSolution = -inv(HessianMatrixQP)*gradientQP;
end

author: robotology

repo: whole-body-controllers


text:
function [] = fcnninfo()
%FCNNINFO Parameters and notation of fully-connected neural net.
%   Background for the terminology and parameters used in all fcnn
%   related functions can be found in Section 14.5 of DIPUM3E. In
%   paticular, see Fig. 14.15.
%
%   This function is used to reduce duplication in the documentation of
%   the various functions used to implement a fully-connected neural net.
%   In those functions, the user is asked to type
%
%    >> help fcnninfo
%
%   at the prompt for a list of parameters and a detailed explanation of
%   the role they play in each function and in the network.
%
% PARAMETERS FOR SPECIFYING THE ARCHITECTURE OF AN FCNN.
%
%  The fully-connected neural net requires only three (TWO!!!) parameters
%  specified by a user: (1) The number of nodes per layer. (2) The
%  activation function used in each layer. (3) The learning rate
%  constant. These are specified as a structure, fcnnparam, with the
%  following fields.
%
% fcnnparam.NumNodes
%  A vector containing the number of nodes per layer. The number of
%  nodes in the first layer is equal to the dimensionality of the input
%  vectors. The number of nodes in the output layer is equal to the
%  number of pattern classes. The number of hidden layers, and the
%  number of nodes in each is arbitrary. If no hidden layers are
%  specifived, the neural net will act as a linear classifier. Example:
%  fcnnparam.NumNodes = [6 3 2] is an fcnn whose input vectors are
%  6-dimensional, it has one hidden layer with three nodes, and the
%  number of pattern classes it can recognize is two. The number of
%  layers, L, is computed as L = numel([fcnnparam.NumNodes]).
%
% fcnnparam.ActivationFunction
%  A cell array of size L - 1, the kth element of which is a character
%  string giving the activation function to be used in layer k for 2 <=
%  k <= L. Valid activation functions are: 'sigmoid', 'tanh', and
%  'ReLU'. If only one activation function is specified, that activation
%  function is used in all layers. The default when no activation is
%  specified is {'sigmoid'}.
%
% fcnnparam.Alpha
%  The learning rate constant. It defaults to 1.0.
%
% FCNN PARAMETERS COMPUTED BY VARIOUS FUNCTIONS IN THE FCNN TOOLKIT.
% THESE ARE THE VALUES THAT ARE PASSED BACK-AND-FORTH BETWEEN
% FEEDFORWARD, BACKPROPAGATION, AND WHEN THE FCNN IS ULTIMATELY USED FOR
% CLASSIFICATION.
%
%  A fully-connected neural network is defined by a structure named
%  fcnn, whose fields are as follows:
%
%  L denotes the number of layers in the fcnn. k = 1 is the input layer,
%  and k = L is the output layer. Layers 1 < k < L are hidden layers.
%
% fcnn(k).NumNodes           (formatted in func fcnninit from fcnnparam)
%  A 1-by-L vector containing the number of nodes per layer in the fcnn.
%  The number of nodes in the 1st layer, fcnn(1).NumNodes, is equal to
%  the dimension of the input pattern vectors. The number of nodes in
%  the last layer, fcnn(L).NumNodes is equal to the number of pattern
%  classes. The number L of layers is computed as L =
%  numel([fcnn.NumNodes]).
%
% fcnn(k).ActivationFunction (formatted in func fcnninit from fcnnparam)
%  The kth element of a 2-by-Lc cell array giving the type of activation
%  function used in layer k, for 2 <= k <= L. Valid activation functions
%  are: 'sigmoid', 'tanh', and 'ReLU'. If only one activation function
%  is specified in fcnnparam.ActivationFunction, that activation
%  function is used in all layers. The default when no activation is
%  specified is fcnn(k).ActivationFunction = {'sigmoid'} for k =
%  2,...,L.
%
% fcnn(k).Alpha              (formatted in func fcnninit from fcnnparam)
%  The learning rate constant. This is a scalar specified in
%  fcnnparam.Alpha, but for consistency in structure notation, it is
%  converted two a vector, all elements of which are the same:
%  fcnn(k).Alpha = fcnnparam.Alpha for for k = 1,2,...,L.
%
% fcnn(k).Weights   (computed initially in function fcnninit and updated
%                    in function fcnnbp during training)
%  For each layer k, 2 <= k <= L, fcnn(k).Weights is a matrix of size
%  fcnn(k - 1).NumNodes-by-fcnn(k).NumNodes, containing the weights
%  associated with the nodes in layer k.
%
% fcnn(k).Biases    (computed initially in function fcnninit and updated
%                     in function fcnnbp during training)
%  For each layer k, 2 < k <= L, this is a fcnn(k).NumNodes-by-1 vector
%  containing the biases associated with the nodes in layer k.
%
%  fcnn(k).HprimeZ                         (computed in function fcnnff)
%  The output of layer k before activation, 2 <= k <= L. This is a
%  matrix of size fcnn(k).NumNodes-by-NP, where NP is the number of
%  pattern vectors input into the fcnn simultaneously.
%
% fcnn(k).A                                (computed in function fcnnff)
%  The output (activation) values of layer k, 1 <= k <= L. This is a
%  matrix of size fcnn(k).NumNodes-by-NP, where NP is the number of
%  pattern vectors input into the fcnn simultaneously. fcnn(1).A is
%  equal to the input pattern matrix, and fcnn(L).A is the matrix of
%  output values. Each colum of A are all the output activation values
%  corresponding to one input pattern vector.
%
% fcnn(k).D                                (computed in function fcnnbp)
%  This is the error matrix of layer k, 2 <= k <= L. It is computed
%  during backpropagation and its dimensions are the same as the
%  dimensions of fcnn(k).A. The error matrix and fcnn.HprimeZ are used
%  to update the weights (and biases) for the fcnn. An extra backprop
%  step is taken to generate fcnn(1).D. The extra backprop step brings
%  the backprop output (going in the reverse direction) to the same
%  location as the feedforward output of the cnn after vectorization. No
%  fcnn(1).HprimeZ is computed because this quantity is related only to
%  the fully connected net.The extra step does not affect any other fcnn
%  functions.
%
% APPLICATION-SPECIFIC INPUTS.
%
% fcnndatain.X                                        (provided by user)
%  The input training patterns. This is a matrix of size dim-by-NP where
%  dim = the dimensionality of the patterns and NP = number of pattern
%  vectors. That is, fcnndatain.X(:,k) is the kth input pattern vector.
%
% fcnndatain.R                                        (provided by user)
%  The class membership matrix. This is a matrix of size NC-by-NP, where
%  NC is the number of pattern classes. As explained in Section 14.SS,
%  column fcnndatain.R(:,k) has a 1 in the jth position if the kth
%  pattern vector belongs to class j.
%
% fcnndatain.Epochs                                   (provided by user)
%  The number of training epochs.
%
% fcnndatain.MiniBatchSize                            (provided by user)
%  The minibatch size used during training. The ratio of the number of
%  training patterns to the minibatch size must be an integer (whole
%  number).
%
% USING THE FCNN AS A CLASSIFIER
%
%  In DIPUM3E, the objective of training a fully-connected net is to use
%  it as a pattern classifier. This task is performed by function
%  fcnnclassifier, which is called as follows:
%
%           classifieroutput = fcnnclassifier(classifierinput)
%
%  where classifierinput and classfieroutput are structures whose fields
%  are explained below.
%
% classifierinput.fcnn                                (provided by user)
%  The fully connected neural net to be used as the classfier.
%  Typically, classifierinput.fcnn = fcnn, the neural net obtained from
%  training.
%
% classifierinput.X                                   (provided by user)
%  Pattern matrix, each column of which is a pattern vector.
%
% classifierinput.R                                   (provided by user)
%  Class membership matrix for the input pattern vectors. This is an
%  optional input that, if provided, will be used to compute the correct
%  classification rate.
%
% OUTPUTS FROM THE VARIOUS FUNCTIONS IN THE fcnn TOOLBOX
%
% fcnndataout.MSE                       (computed in function fcnntrain)
%  The mean-squared error during training, computed as the sum of the output errors squared, divided by 2. This a a vector with (NumInput
%  Patterns)/(MinibactSize)*fcnndatain.Epochs elements.
%
% fcnndataout.SmoothMSE                 (computed in function fcnntrain)
%  Smoothed version of fcnndataout.MSE.
%
% classifieroutput.Class           (computed in function fcnnclassifier)
%  A vector whose nunber of elements is equal to the number of input
%  patterns. The kth element of this vector gives the class to which the
%  kth vector was assigned (i.e., classified).
%
% classifieroutput.ClassificationRate (computed in function fcnnclassifier)
%  A scalar that gives the percent of patterns classified correctly,
%  assuming that classifierinput.R was provided. If this is not the case
%  then classifieroutput.ClassificationRate = [].
%
%   Copyright 2002-2020 Gatesmark
%
%   This function, and other functions in the DIPUM Toolbox, are based
%   on the theoretical and practical foundations established in the
%   book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark
%   Press, 2020.
%
%   Book website: http://www.imageprocessingplace.com
%   License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt

doc fcnninfo

author: dipum

repo: dipum-toolbox

save_path: github-repos/MATLAB/dipum-dipum-toolbox


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

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

% Last Modified by GUIDE v2.5 25-Jan-2019 14:31:50

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @lvd_EditActionSetThirdBodyGravitySourcesGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @lvd_EditActionSetThirdBodyGravitySourcesGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before lvd_EditActionSetThirdBodyGravitySourcesGUI is made visible.
function lvd_EditActionSetThirdBodyGravitySourcesGUI_OpeningFcn(hObject, eventdata, handles, varargin)
    % This function has no output args, see OutputFcn.
    % hObject    handle to figure
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    % varargin   command line arguments to lvd_EditActionSetThirdBodyGravitySourcesGUI (see VARARGIN)

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

    centerUIFigure(hObject);

    action = varargin{1};
    setappdata(hObject,'action',action);

    lv = varargin{2};
    setappdata(hObject,'lv',lv);

    populateGUI(handles, action, lv);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, action, lv)
    lvdData = lv.lvdData;
    celBodyData = lvdData.celBodyData;

    [bodiesStr, sortedBodyInfo] = ma_getSortedBodyNames(celBodyData);
    handles.bodiesListBox.String = bodiesStr;

    sortedBodyInfoArr = KSPTOT_BodyInfo.empty(1,0);
    for(i=1:length(sortedBodyInfo))
        sortedBodyInfoArr(end+1) = sortedBodyInfo{i}; %#ok<AGROW>
    end

    curSelBodies = action.bodiesToSet;
    [~,inds,~] = intersect(sortedBodyInfoArr,curSelBodies);

    set(handles.bodiesListBox,'Value',inds);

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

% Get default command line output from handles structure
    if(isempty(handles))
        varargout{1} = false;
    else
        action = getappdata(hObject,'action');
        lv = getappdata(hObject,'lv');
        lvdData = lv.lvdData;
        celBodyData = lvdData.celBodyData;

        [~, sortedBodyInfo] = ma_getSortedBodyNames(celBodyData);
        inds = handles.bodiesListBox.Value;
        if(not(isempty(inds)))
            action.bodiesToSet = [sortedBodyInfo{inds}];
        else
            action.bodiesToSet = KSPTOT_BodyInfo.empty(1,0);
        end

        varargout{1} = true;
        close(handles.lvd_EditActionSetThirdBodyGravitySourcesGUI);
    end

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

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

% --- Executes on key press with focus on lvd_EditActionSetThirdBodyGravitySourcesGUI or any of its controls.
function lvd_EditActionSetThirdBodyGravitySourcesGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditActionSetThirdBodyGravitySourcesGUI (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'return'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'enter'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'escape'
            close(handles.lvd_EditActionSetThirdBodyGravitySourcesGUI);
    end

% --- Executes on selection change in bodiesListBox.
function bodiesListBox_Callback(hObject, eventdata, handles)
% hObject    handle to bodiesListBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns bodiesListBox contents as cell array
%        contents{get(hObject,'Value')} returns selected item from bodiesListBox

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

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function n = kpu_order ( l )

%*****************************************************************************80
%
%% KPU_ORDER computes the order of a KPU rule from the level.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 May 2012
%
%  Author:
%
%    John Burkardt.
%
%  Parameters:
%
%    Input, integer L, the level of the rule.
%    1 <= L <= 25
%
%    Output, integer N, the order of the rule.
%
  if ( l < 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'KPU_ORDER - Fatal error!\n' );
    fprintf ( 1, '  1 <= L <= 25 required.\n' );
    fprintf ( 1, '  Input L = %d\n', l );
    error ( 'KPU_ORDER - Fatal error!' );
  elseif ( l == 1 )
    n = 1;
  elseif ( l <= 3 )
    n = 3;
  elseif ( l <= 6 )
    n = 7;
  elseif ( l <= 12 )
    n = 15;
  elseif ( l <= 24 )
    n = 31;
  elseif ( l <= 25 )
    n = 63;
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'KPU_ORDER - Fatal error!\n' );
    fprintf ( 1, '  1 <= L <= 25 required.\n' );
    fprintf ( 1, '  Input L = %d\n', l );
    error ( 'KPU_ORDER - Fatal error!' );
  end

  return
end


text:
function pass = test_dot( )
% Test dot product

tol = 10*chebfunpref().cheb2Prefs.chebfun2eps;

% Test dot product of empty diskfunv.
f = diskfunv;
g = diskfunv;
h = dot(f,g);
pass(1) = isempty(h);

% Check definition:
F = chebfun2v(@(x,y) cos(x), @(x,y) sin(y));
G = chebfun2v(@(x,y) x, @(x,y) y);
dotF1 = dot(F, G);
dotF2 = F' * G;
pass(2) = ( norm(dotF1 - dotF2) < tol );

% Test with diskfun
u1 = diskfun(@(x,y) x.*cos(2*y));
u2 = diskfun(@(x,y) y.*sin(2*x));
u = diskfunv(u1,u2);
v1 = diskfun(@(x,y) x.*y);
v2 = diskfun(@(x,y) y.^2);
v = diskfunv(v1,v2);
f = dot(u,v);
% Same as the dot product
g = u1.*v1 + u2.*v2;
pass(3) = norm(g-f) < tol;

% Same as dot product
g = u'*v;
pass(4) = norm(g-f) < tol;

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function Y = nnsoft(X, T)
%% Soft threshold function
%% Copyright (c) 2017 Yan Yang
%% All rights reserved.
TH = abs(T);
 B = X >= TH;
 S = X <= -TH;
 Y = (X - TH) .* B + (X + TH) .* S;
end

repo: Deep-ADMM-Net


text:
function bubblesort_complexity ( )

%*****************************************************************************80
%
%% BUBBLESORT_COMPLEXITY measures the complexity of the bubblesort algorithm.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 December 2012
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BUBBLESORT_COMPLEXITY\n' );
  fprintf ( 1, '  How does the time requirement increase with vector length\n' );
  fprintf ( 1, '  for the bubblesort algorithm?\n' );
%
%  Get some data for N = 1 : 200.
%  Do the loop twice to avoid startup anomalies.
%
  for i = 1 : 2

    data_size = zeros ( 200, 1 );
    data_time = zeros ( 200, 1 );

    for n = 1 : 200
      a = rand ( n, 1 );
      tic;
      a_heap = r8vec_sort_bubble_a ( n, a );
      data_size(n) = n;
      data_time(n) = toc;
    end

  end

  figure ( 1 )
  plot ( data_size, data_time, 'r-' )
  grid on
  xlabel ( 'Vector length N' );
  ylabel ( 'Elapsed time T' );
  title ( 'T(N), time to heap sort a vector of length N' );

  filename = 'bubblesort_1to200.png';
  print ( '-dpng', filename );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Plot saved as "%s".\n', filename );
%
%  Get some data for N = 1, 2, 4, ..., 2^12.
%  Do the loop twice to avoid startup anomalies.
%
  for i = 1 : 2

    data_size = zeros ( 13, 1 );
    data_time = zeros ( 13, 1 );

    n = 1;

    for nlog = 0 : 12
      a = rand ( n, 1 );
      tic;
      a_heap = r8vec_sort_bubble_a ( n, a );
      data_size(nlog+1) = n;
      data_time(nlog+1) = toc;
      n = n * 2;
    end

  end

  figure ( 2 )
  loglog ( data_size, data_time, 'r-o' )
  grid on
  xlabel ( 'Vector length N' );
  ylabel ( 'Elapsed time T' );
  title ( 'T(N), time to heap sort a vector of length N' );

  filename = 'bubblesort_powersoftwo.png';
  print ( '-dpng', filename );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Plot saved as "%s".\n', filename );
!
!  Terminate.
!
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BUBBLESORT_COMPLEXITY\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

  return
end
function a = r8vec_sort_bubble_a ( n, a )

%*****************************************************************************80
%
%% R8VEC_SORT_BUBBLE_A ascending sorts an R8VEC using bubble sort.
%
%  Discussion:
%
%    Bubble sort is simple to program, but inefficient.  It should not
%    be used for large arrays.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 February 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of entries in the array.
%
%    Input, real A(N), an unsorted array.
%
%    Output, real A(N), the array has been sorted.
%
  for i = 1 : n-1
    for j = i + 1 : n
      if ( a(j) < a(i) )
        t    = a(i);
        a(i) = a(j);
        a(j) = t;
      end
    end
  end

  return
end


text:
function [amu] = mg2amu(mg)
% Convert mass from milligrams to atomic mass units.
% Chad Greene 2012
amu = mg*602213665167500000000;


text:
function ProcDir(RawDir,FinDir,varargin)

%% This script processes stxm data found in "RawDir" and places it in P1Dir

datafolder=RawDir;
cd(datafolder) %% move to raw data folder
foldstruct=dir;

if ~isempty(varargin)
    badE=varargin{1};
else
    badE=[];
end

cnt=1;
numobj=length(dir);
for i = 3:numobj %% loops through stack folders in raw data folder
    try cd(fullfile(datafolder,foldstruct(i).name)); %% move to data folder
            S=LoadStackRaw(pwd); %% load stack data
            S.particle=sprintf('%s',foldstruct(i).name); %% print particle name
            S=DeglitchStack(S,badE);
            %             filename=sprintf('%s%s%s',P1Dir,'\S',foldstruct(i).name); %% define directory to save file in
            %             cd(P1Dir)
            %             save(sprintf('%s%s','S',foldstruct(i).name)) %% save stack data in .mat file
            figure,plot(S.eVenergy,squeeze(mean(mean(S.spectr))))
            S=AlignStack(S);
            if length(S.eVenergy)==1
                Snew=OdStack(S,'O');
            else
                Snew=OdStack(S,'O');
            end
            cd(FinDir)
            save(sprintf('%s%s','F',foldstruct(i).name))
            cd(FinDir);
    catch
        %         cd(fullfile(datafolder,foldstruct(i).name)); %% move back to raw data folder
        cd(datafolder); %% move back to raw data folder
        %         cd ..

        cnt=cnt+1;
    end
end


text:
function fcnCallback_cmd_ClearCommandLine()
%% About:
% This function is used to clear the command line interface

% Copyright: Mohammad SAFEEA, 20th-July-2018

% show confirmation dialog box
quest='Are you sure you want to clear the command line, this will delete all entered instructions!!!';
title='Confirmation request!!!';
btn1='Apply';
btn2='Cancel';
defbtn=btn2;
answer = questdlg(quest,title,btn1,btn2,defbtn);

switch answer
    case btn1
        % clar interface
        h=findobj(0,'tag','txt_CommandLine');
        st=[];
        set(h,'String',st);
    case btn2
        % nothing
end

end

repo: KST-Kuka-Sunrise-Toolbox