text:
function [decodedMsgs,epochTimes]=decodeAISPosReports2Mat(NMEAStrings,convert2Metric)
%%DECODEAISPOSREPORTS2MAT Given a matrix of Automatic Identification
%                 System (AIS) messages (or a cell array of AIS messages)
%                 given as National Marine Electronics Association (NMEA)
%                 formatted ASCII text messages, extract position reports
%                 of message types 1, 2, 3, 18, 19, and 27, storing the
%                 information related to ship location, identity, course,
%                 and time in different rows of a matrix, where each
%                 column corresponds to a different report. If a cell
%                 array is passed, then the matrices for decoding each
%                 cell array are placed into corresponding cells on
%                 return. It is also possible to decode timestamps (or
%                 another integer number) appended as a final field on the
%                  messages. The manipulation of matrices rather than
%                 structures is significantly faster in Matlab, which is
%                 why one might prefer this function to decodeAISString
%                 when only simple position reports are needed.
%
%INPUTS: NMEAStrings A character string containing one or more Automatic
%                 Identification System (AIS) messages given as National
%                 Marine Electronics Association (NMEA) formatted ASCII
%                 text. Each message is on its own line. Invalid messages
%                 and messages that are not of types 1, 2, 3, 18, 19, and
%                 27 are skipped.
% convert2Metric  If true, all distance units in the result are converted
%                 to meters, all speed units are converted to meters per
%                 second, and all angles are converted to radians North of
%                 East (the mathematical definition) and angular rates are
%                 converted to radians per second North of East, all
%                 rather than using typical nautical units. The default if
%                 omitted is true.
%
%decodedMsgs A 14XN matrix of the N successfully decoded position reports.
%            The 14 fields that are decoded are stored in the matrix as:
%                     1) The maritime mobile service identity (MMSI)
%                        number of the transmitter that can be used to
%                        identify targets (A 30-bit integer value).
%                     2) Navigation status. An integer indicating what the
%                        ship is doing/ whether it is moving. Possible
%                        valid values are:
%                       *0 = under way using engine
%                       *1 = at anchor
%                       *2 = not under command,
%                       *3 = restricted maneuverability
%                       *4 = constrained by her draught
%                       *5 = moored
%                       *6 = aground
%                       *7 = engaged in fishing
%                       *8 = under way sailing
%                       *9 = reserved for future amendment of
%                          navigational status for ships carrying DG, HS,
%                          or MP, or IMO hazard or pollutant category C,
%                          high speed craft (HSC).
%                       *10 = reserved for future amendment of
%                          navigational status for ships carrying
%                          dangerous goods (DG), harmful substances (HS)
%                          or marine pollutants (MP), or IMO hazard or
%                          pollutant category A, wing in ground (WIG).
%                       *11 = power- driven vessel towing astern
%                              (regional use)
%                       *12 = power-driven vessel pushing ahead or towing
%                              alongside (regional use)
%                       *13 = reserved for future use,
%                       *14 = AIS-SART (active), MOB-AIS, EPIRB-AIS
%                     3) Turn rate. This is limited to +/- 708 degrees per
%                        minute (about +/- .2059 radians per second when
%                        using metric units).
%                     4) Speed over ground in knots up to 102.2 knots, or
%                        52.6 meters per second when using metric units.
%                     5) Position accuracy flag. Possible values are:
%                        1=high (accuracy beter than 10m)
%                        0=low (accuracy worse than 10 meters)
%                     6) Latitude (WGS-84) in degrees North or radians
%                        North when using the metric units option.
%                     7) Longitude (WGS 84) in degrees East or radians
%                        East when using the metric units option.
%                     8) Course over ground (heading) in degrees East of
%                        North or radians North of East when using the
%                        metric units option.
%                     9) True heading in degrees East of North or radians
%                        North of East when using the metric units option.
%                    10) The second number within the universal
%                        coordinated time (UTC) minute when the ship's
%                        transmitter sent the position report. NOTE that
%                        if this is 61 or greater, than this means that the
%                        the positioning system is broken or in dead
%                        reckoning mode, so the return is likely to be
%                        inaccurate. Also, the standard does not properly
%                        account for 61 second minutes when a leapsecond
%                        is added, so it is not clear what will happen
%                        with leapseconds. This field is not used by
%                        message 27. Rather, there is no timestamp and a
%                        position latency indicator is used to indicate
%                        the extend of the delay of the true time of the
%                        position from the broadcast time.
%                    11) Special manoeuvre indicator. This can be
%                        1 = not engaged in special manoeuvre
%                        2 = engaged in special manoeuvre
%                    12) The ID of the message that provided the above
%                        information. This can be
%                        1  Class A position report, scheduled.
%                        2  Class A position report, assigned.
%                        3  Class A position report, when interrogated.
%                        18 Standard class B equipment position report.
%                        19 Extended class B equipment position report.
%                        27 Long-range automatic identification system
%                           broadcast message.
%                    13) A number indicating how many times the message
%                        has been repeated. This ranged from 0 to 3. 3
%                        also indicates that the message should not be
%                        repeated anymore.
%                    14) Position latency. This is only used with message
%                        27. This is 0 or 1. 0 means the position latency
%                        is less than five seconds, one means it is more.
%          epochTimes If this parameter is requested, then the final
%                     numbers after the checklsum (separated by a comma)
%                     are assumed to either be an integer epoch time, or
%                     anything with a comma separating an integer epoch
%                     time at the end. Thus, this tries to decode the
%                     epoch time associated with the message. Note that in
%                     multi-part messages (message 19 can have multiple
%                     parts), the epoch time used is that of the LAST
%                     received part in the sequence. If no time can be
%                     decoded, then
%
%This function relies on libais from
%https://github.com/schwehr/libais
%The library probably does not work on big-endian processors (Intel
%processors are little-endian).
%
%The algorithm can be compiled for use in Matlab using the
%CompileCLibraries function.
%
%The algorithm is run in Matlab using the command format
%decodedMsgs=decodeAISPosReports2Mat(NMEAStrings,convert2Metric);
%or
%[decodedMsgs,epochTimes]=decodeAISPosReports2Mat(NMEAStrings,convert2Metric);
%if timestamps are available
%
%The algorithm is run in Matlab using the command format
%decodedMsgs=decodeAISPosReports2Mat(NMEAStrings,convert2Metric);
%or
%[decodedMsgs,epochTimes]=decodeAISPosReports2Mat(NMEAStrings,convert2Metric);
%if timestamps are available
%
%Example 1:, Decoding a single valid ID=1 string.
% NMEAStrings='!AIVDM,1,1,,A,13HOI:0P0000VOHLCnHQKwvL05Ip,0*23';
% decodedMsgs=decodeAISPosReports2Mat(NMEAStrings,false)
%The decoded message should be:
% decodedMsgs=[227006760;%MMSI
%                      0;%Navigation status (underway)
%                    NaN;%Not used
%                      0;%Turn rate
%                      0;%Speed over ground
%     49.475578308105469;%North latitude
%      0.131380006670952;%East longitude
%     36.700000762939453;%Heading East of North
%                    NaN;%Not used
%                     14;%Seconds within minute when message sent.
%                    NaN;%Not used.
%                      1;%Class A position report, scheduled.
%                      0;%has not ben rebroadcast.
%                    NaN];%Not used.
%
%Example 2: Decoding multiple messages, one valid string of each type of
%message. It is most likely that this would arise from reading the
%messages in from a file, because adding newline characters to strings has
%to be done using the \n newline character to separate the string in
%sprintf rather than just typing them. The AIS19 string consists of two
%parts that are joined.
% NMEAStrings=sprintf('!AIVDM,1,1,,A,13HOI:0P0000VOHLCnHQKwvL05Ip,0*23\n!AIVDM,1,1,,B,284;UGTdP4301>3L;B@Wk3TnU@A1,0*7C\n!AIVDM,1,1,,B,34hoV<5000Jw95`GWokbFTuf0000,0*6C\n!SAVDM,1,1,4,B,B5NU=J000=l0BD6l590EkwuUoP06,0*61\n!AIVDM,2,1,7,B,C5NMbDQl0NNJC7VNuC<v`7NF4T28V@2g0J6F::00000,0*59\n!AIVDM,2,2,7,B,0J70<RRS0,0*30\n!AIVDM,1,1,,B,K815>P8=5EikdUet,0*6B');
% decodedMsgs=decodeAISPosReports2Mat(NMEAStrings,false)
%One will observe that 6 messages are correctly decoded, of types 1, 2, 3,
%18, 19, and 27.
%
%Example 3: Decoding multiple messages, some of them of the wrong type.
%When messages of the wrong type are used, then they are askipped. Here,
%two correct messages are read in as well as one incorrect message in
%between them. The "incorrect" message is of type 26 (not a position report) and is thus ignored.
%Below are four strings, but only two of them contain AIS position reports
% NMEAStrings=sprintf('!AIVDM,1,1,,A,13HOI:0P0000VOHLCnHQKwvL05Ip,0*23\n!AIVDM,1,1,,A,H44cj<0DdvlHhuB222222222220,2*46\n!AIVDM,1,1,,B,284;UGTdP4301>3L;B@Wk3TnU@A1,0*7C');
% decodedMsgs=decodeAISPosReports2Mat(NMEAStrings)
%The results are in metric units.
%
%Example 4: Consider the case where the messages contain some numbers
%after the checksum, which make up the timestamps of the messages.
%This is the same as the previous example, but with fake timestamps
%appended.
% NMEAStrings=sprintf('!AIVDM,1,1,,A,13HOI:0P0000VOHLCnHQKwvL05Ip,0*23,1241827197\n!AIVDM,1,1,,A,H44cj<0DdvlHhuB222222222220,2*46,1241827198\n!AIVDM,1,1,,B,284;UGTdP4301>3L;B@Wk3TnU@A1,0*7C,1241827199');
% [decodedMsgs,epochTimes]=decodeAISPosReports2Mat(NMEAStrings)
%The results are in metric units.
%
%Example 5: Some receivers will append aditional information before the
%timestamp. As long as the timestamp is the last thing in the message,
%then we can still recover it.
% NMEAStrings='!AIVDM,1,1,,A,100WhdhP0nJRdiFFHFvm??v00L12,0*13,raishub,1342569600';
% [decodedMsgs,epochTimes]=decodeAISPosReports2Mat(NMEAStrings)
%The results are in metric units.
%
%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

error('This function is only implemented as a mexed C or C++ function. Please run CompileCLibraries.m to compile the function for use.')

end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
classdef LossSmoothL1 < dagnn.Loss
%LossSmoothL1  Smooth L1 loss
%  `LossSmoothL1.forward({x, x0, w})` computes the smooth L1 distance
%  between `x` and `x0`, weighting the elements by `w`.
%
%  Here the smooth L1 loss between two vectors is defined as:
%
%     Loss = sum_i f(x_i - x0_i) w_i.
%
%  where f is the function (following the Faster R-CNN definition):
%
%              { 0.5 * sigma^2 * delta^2,         if |delta| < 1 / sigma^2,
%   f(delta) = {
%              { |delta| - 0.5 / sigma^2,         otherwise.
%
%  In practice, `x` and `x0` can pack multiple instances as 1 x 1 x C
%  x N arrays (or simply C x N arrays).

  properties
    sigma = 1.
  end

  methods
    function outputs = forward(obj, inputs, params)
      sigma2 = obj.sigma^2 ;
      delta = inputs{1} - inputs{2} ;
      absDelta = abs(delta) ;

      linearRegion = (absDelta > 1. / sigma2) ;
      absDelta(linearRegion) = absDelta(linearRegion) - 0.5/sigma2 ;
      absDelta(~linearRegion) = 0.5 * sigma2 * absDelta(~linearRegion).^2 ;

      % Mutliply by instance weights and sum.
      outputs{1} = inputs{3}(:)' * absDelta(:) ;

      % Accumulate loss statistics.
      n = obj.numAveraged ;
      m = n + gather(sum(inputs{3}(:))) + 1e-9 ;
      obj.average = (n * obj.average + gather(outputs{1})) / m ;
      obj.numAveraged = m ;
    end

    function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)
    % Function derivative:
    %
    %          { sigma^2 * x,             if |x| < 1 / sigma^2,
    %  f'(x) = {
    %          { sign(x),                 otherwise.

      sigma2 = obj.sigma^2 ;
      delta = inputs{1} - inputs{2} ;
      absDelta = abs(delta) ;

      linearRegion = (absDelta > 1. / sigma2) ;
      delta(linearRegion) = sign(delta(linearRegion));
      delta(~linearRegion) = sigma2 * delta(~linearRegion) ;

      derInputs = {inputs{3} .* delta .* derOutputs{1}, [], []} ;
      derParams = {} ;
    end

    function obj = LossSmoothL1(varargin)
      obj.load(varargin) ;
      obj.loss = 'smoothl1';
    end
  end
end

author: guosheng

repo: refinenet

save_path: github-repos/MATLAB/guosheng-refinenet


text:
clear

load('./results/results_clnf_wild.mat');

[clnf_error, ~,~,frontal_ids] = compute_error( experiment.labels,  experiment.shapes-1.0);
clnf_error_frontal = clnf_error(frontal_ids);
clnf_error_profile = clnf_error(~frontal_ids);

load('./results/results_ceclm_general.mat');

[ceclm_error,~,~,frontal_ids] = compute_error( experiment.labels,  experiment.shapes-1.0);
ceclm_error_frontal = ceclm_error(frontal_ids);
ceclm_error_profile = ceclm_error(~frontal_ids);

load('results/CFAN_JANUS.mat');

[cfan_error,~,~,frontal_ids] = compute_error( labels_all,  shapes_all-1.0);
cfan_error_frontal = cfan_error(frontal_ids);
cfan_error_profile = cfan_error(~frontal_ids);

load('results/JANUS_3DDFA.mat');

[error_3ddfa,~,~,frontal_ids] = compute_error( labels_all,  shapes-1.0);
error_3ddfa_frontal = error_3ddfa(frontal_ids);
error_3ddfa_profile = error_3ddfa(~frontal_ids);

load('results/JANUS-CFSS.mat');
shapes = zeros(68,2, size(estimatedPose,1));

for i = 1:size(shapes, 3)
    shapes(:,1,i) = estimatedPose(i,1:68);
    shapes(:,2,i) = estimatedPose(i,69:end);
end

[cfss_error,~,~,frontal_ids] = compute_error( experiment.labels, shapes-1.0);
cfss_error_frontal = cfss_error(frontal_ids);
cfss_error_profile = cfss_error(~frontal_ids);

%
load('results/tcdcn_JANUS.mat');
shapes_c = shapes;
shapes = zeros(68,2, numel(shapes_c));

for i = 1:size(shapes, 3)
    shapes(:,1,i) = shapes_c{i}(:,1);
    shapes(:,2,i) = shapes_c{i}(:,2);
end

[tcdcn_error,~,~,frontal_ids] = compute_error( experiment.labels, shapes-1);
tcdcn_error_frontal = tcdcn_error(frontal_ids);
tcdcn_error_profile = tcdcn_error(~frontal_ids);

author: TadasBaltrusaitis

repo: OpenFace


text:
function sPsi = packBPHMMState( Psi );

sPsi.F = Psi.F;
sPsi.gamma = Psi.bpM.gamma;
sPsi.c     = Psi.bpM.c;
sPsi.Eta    = Psi.TransM.seq;
sPsi.alpha  = Psi.TransM.prior.alpha;
sPsi.kappa  = Psi.TransM.prior.kappa;
sPsi.theta  = Psi.ThetaM.theta;
sPsi.stateSeq = Psi.stateSeq;

end

author: michaelchughes

repo: NPBayesHMM


text:
function [numOfEx,vecDim,outDim,numOfCls] = get_dim(dat)

%   [numEx,vDim,oDim,numCls] = get_dim(data)
%
%   Returns (ind given order) the number of examples, the vectors
%   dimension, the number of output dimensions and the number
%   of classes.
%
%   Note:
%   Sometimes the number of classes differs from the output dimension
%   (e.g. in binary pattern recognition often oDim equals 1 and numCls
%   equals 2).

  global X;
  global Y;

  numOfEx=length(dat.index);
  vecDim=length(dat.findex);
  if isempty(dat.myY)
    outp=Y(dat.index,:);
    outDim=size(outp,2);
    numOfCls=outDim;
    if numOfCls==1
        fin1=find(outp==1);
        fin2=find(outp==-1);
    end;
  else
    outp=dat.myY;
    outDim=size(outp,2);
    numOfCls=outDim;
    if numOfCls==1
        fin1=find(outp==1);
        fin2=find(outp==-1);
    end;
  end

  if numOfCls==1
    if length(fin1)>0 & length(fin2)>0 & (length(fin1)+length(fin2))==numOfEx
      numOfCls=2;  %% -1s and +1s => classes
    end
  end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
% readneurone()  -  Read data from a Mega NeurOne device and arrange it
%                   into a struct.
%
% Usage:    >> NEURONE = readneurone(dataPath, sessionPhaseNumber, chans)
%
% =======================================================================
% Inputs:
%   dataPath              - Path to directory containing NeurOne data
%                           from a single measurement.
%
% Optional input arguments:
%   sessionPhaseNumber    - Defines which session phase will be read.
%                           Default value for sessionPhaseNumber is 1.
%   chans                 - Defines which channels will be read. The
%                           channel numbers have to be strings containing
%                           numeric values between 1 and the total number
%                           of channels. In addition, they are arranged in
%                           vector form without brackets. For example,
%                           if the total number of channels is 64, the
%                           'chans' input argument can be '1,6,3,7' or
%                           '1:12'. The default value for chans is an empty
%                           string which indicates that all channels will
%                           be read. The channel numbers can be arranged
%                           in a completely random order.
%
% =======================================================================
% Outputs:
%       NEURONE is a struct with the same fields as a standard EEG
%       structure under EEGLAB (see eeg_checkset.m).
%
% Used fields are:
%   NEURONE.filename
%   NEURONE.setname
%   NEURONE.srate
%   NEURONE.pnts
%   NEURONE.xmin
%   NEURONE.xmax
%   NEURONE.filepath
%   NEURONE.trials
%   NEURONE.nbchan
%   NEURONE.data
%   NEURONE.ref
%   NEURONE.times
%   NEURONE.comments
%   NEURONE.etc
%   NEURONE.subject
%   NEURONE.event (a struct containing all event data)
%   NEURONE.eventdescription
%   NEURONE.chanlocs (will be defined by EEGLAB if channel locations exist
%                for used channel names)
%   NEURONE.chaninfo
%
% The following fields were added as empty to ensure proper working:
%   NEURONE.icawinv
%   NEURONE.icaweights
%   NEURONE.icasphere
%   NEURONE.icaact
%
%
% ========================================================================
% NOTE:
% This file is part of the NeurOne data import plugin for EEGLAB.
% ========================================================================
%
% Current version: 1.0.3.4 (2016-06-17)
% Author: Mega Electronics

function NEURONE = readneurone(dataPath, varargin)
%% Parse input arguments

p = inputParser;
p.addRequired('dataPath', @ischar);
p.addOptional('sessionPhaseNumber', 1 ,@isnumeric);
p.addOptional('chans','', @isstr);

p.parse(dataPath, varargin{:});
arglist = p.Results;

%%  Empty recording structure for output

NEURONE = {};

%% Read Session and Protocol xml-files

session = module_read_neurone_xml([dataPath 'Session.xml']);
protocol = module_read_neurone_xml([dataPath 'Protocol.xml']);

%% Obtain information from session and protocol

% Obtain sampling frequency (it is same for all channels)
srate = str2num(protocol.TableProtocol.SamplingFrequency);

% Get the total number of channels
nChannels = numel(protocol.TableInput);

NEURONE.comments = ['Protocol: ' session.TableSession.ProtocolName];
NEURONE.etc = strvcat( ['NeurOne Version: ' protocol.TableInfo.NeurOneVersion], ...
    ['Protocol File Revision: ' protocol.TableInfo.Revision], ...
    ['Session File Revision: ' session.TableInfo.Revision]);

NEURONE.subject = session.TablePerson.PersonID;

NEURONE.setname = session.TableSession.ProtocolName;

%% Check the session phase number

% Total number of sessions in recording
nSessionPhases = numel(session.TableSessionPhase);
disp(['Number of session phases: ' num2str(nSessionPhases)])
disp(['Current session phase number: ' num2str(arglist.sessionPhaseNumber)]);

% Check the validity of the sessionPhaseNumber taken from GUI
if arglist.sessionPhaseNumber>nSessionPhases
    disp('Current session phase number exceeds the total number of session phases.')
    disp('Defaulting to 1.')
    sessionPhaseNumber = 1;
elseif arglist.sessionPhaseNumber<=0
    disp('Invalid session phase number.')
    disp('Defaulting to 1.')
    sessionPhaseNumber = 1;
else
    sessionPhaseNumber = arglist.sessionPhaseNumber;
end

%% Get correct channel names and locations

% Set the channels for data acquisition
if isempty(arglist.chans)
    chans = 1:nChannels;
else
    chans = [str2num(arglist.chans)];
    chans = sort(chans); % ensure that the channels are in ascending order
end

% Check that no channel number exceeds the total number of channels
if any(chans>nChannels)
    error('One or more of the given channel numbers exceeds the total number of channels. See pop_readneurone help.')
elseif any(chans<1)
    error('One or more of the given channel numbers are invalid (zero or negative). See pop_readneurone help.')
end

% Get all channel names and corresponding input numbers
inputNumbersAll = zeros(1,nChannels);
inputNumbersAll(1) = str2num(protocol.TableInput(1).InputNumber);
channelnames = protocol.TableInput(1).Name;

for n = 2:nChannels
    inputNumbersAll(n) = str2num(protocol.TableInput(n).InputNumber);
    channelnames = char(channelnames,protocol.TableInput(n).Name);
end

channelnames = cellstr(channelnames);

% The value of the highest input number
maxInput = max(inputNumbersAll);

channelnames = channelnames';

% Sort channel names in ascending order based on their input number
for k = 1:nChannels
    ii = 1;
    while ~(any(inputNumbersAll(k)==ii)) && ii<=max(inputNumbersAll)
          ii = ii+1;
    end
    sortIndex(ii) = ii; % Store the indices for future data arrangements
    channelNames(ii) = channelnames(k);
end

inputNumbersTrue = 1:maxInput;
inputNumbersTrue = inputNumbersTrue(find(sortIndex));

% Remove empty channel names:
% Find empty cells...
emptyCells = cellfun(@isempty,channelNames);
% ...and remove them.
channelNames(emptyCells) = [];

% Take only the names of the selected channels
channelNames = channelNames(chans);

fprintf('Looking up channel locations...\n')
chanlocs=struct('labels', channelNames');
% NEURONE.chanlocs = pop_chanedit(chanlocs);
NEURONE.chanlocs = chanlocs;

%% Obtain additional information about the dataset

measurementMode = protocol.TableInput(1).AlternatingCurrent;
deviceFilter = protocol.TableInput(1).Filter;
for n = 2:nChannels
    measurementMode = char(measurementMode,protocol.TableInput(n).AlternatingCurrent);
    deviceFilter = char(deviceFilter,protocol.TableInput(n).Filter);
end

measurementMode = cellstr(measurementMode);
deviceFilter = cellstr(deviceFilter);

for k = 1:nChannels
    if strcmp(measurementMode(k),'true')
        measurementMode(k) = {'AC'};
    else
        measurementMode(k) = {'DC'};
    end
end

% Arrange measurementModes according to the input number
ii = 1;
for k = inputNumbersAll
    measurementMode(k) = measurementMode(ii);
    deviceFilter(k) = deviceFilter(ii);
    ii = ii+1;
end

measurementMode = measurementMode(inputNumbersTrue);
measurementMode = measurementMode(chans);
deviceFilter = deviceFilter(inputNumbersTrue);
deviceFilter = deviceFilter(chans);

measurementModeField = [char(channelNames(1)) ': ' char(measurementMode(1))];
deviceFilterField = [char(channelNames(1)) ': ' char(deviceFilter(1))];

for k = 2:length(chans)
    measurementModeField = strvcat(measurementModeField,[char(channelNames(k)) ': ' char(measurementMode(k))]);
    deviceFilterField = strvcat(deviceFilterField,[char(channelNames(k)) ': ' char(deviceFilter(k))]);
end

NEURONE.chaninfo.measurementMode = measurementModeField;
NEURONE.chaninfo.deviceFilter = deviceFilterField;

%% Preparing to read binary data
% If the size of the measurement in each session phase has exceeded the
% file size, the data may have been split into several files named as
% 1.bin, 2.bin etc. Usually there exists only one file: 1.bin. However, all
% this data needs to be read.

dataFiles = {}; % empty structure for data files

% Get all .bin files related to the chosen sessionPhaseNumber
sessionData = dir([dataPath num2str(sessionPhaseNumber) filesep '*.bin']);

ii = 1;
for k = 1:numel(sessionData); % total number of .bin files in current session phase data folder
    [path,filename,ext] = fileparts(sessionData(k).name);
    if ~isempty(regexpi(filename,'[123456789]'))
        dataFiles{ii,1} = [dataPath num2str(sessionPhaseNumber) filesep sessionData(k).name];
        ii = ii+1;
    end
end

%% Read NeurOne binary data and calibrate it

% Read data. The data of a specific channel is arranged in a row based on its input
% number.

data = readneuronedata(dataFiles, nChannels, chans);

% Preallocate memory to read maximum and minimum values for calibration
rawMinimum = zeros(1,maxInput);
rawMaximum = zeros(1,maxInput);
calibratedMinimum = zeros(1,maxInput);
calibratedMaximum = zeros(1,maxInput);

% Get all minimum and maximum values
for n = 1:nChannels
    rawMinimum(n) = str2num(protocol.TableInput(1,n).RangeMinimum);
    rawMaximum(n) = str2num(protocol.TableInput(1,n).RangeMaximum);
    calibratedMinimum(n) = str2num(protocol.TableInput(1,n).RangeAsCalibratedMinimum);
    calibratedMaximum(n) = str2num(protocol.TableInput(1,n).RangeAsCalibratedMaximum);
end

% Arrange them in the correct according to the input number
 ii = 1;
for k = inputNumbersAll
    rawMinimum(inputNumbersAll) = rawMinimum(ii);
    rawMaximum(inputNumbersAll) = rawMaximum(ii);
    calibratedMinimum(inputNumbersAll) = calibratedMinimum(ii);
    calibratedMaximum(inputNumbersAll) = calibratedMaximum(ii);
    ii = ii+1;
end

% Remove unused input numbers
rawMinimum = rawMinimum(inputNumbersTrue);
rawMaximum = rawMaximum(inputNumbersTrue);
calibratedMinimum = calibratedMinimum(inputNumbersTrue);
calibratedMaximum = calibratedMaximum(inputNumbersTrue);

% Calibrate channels
for n = 1:numel(chans)
    data(n,:) = calibratedMinimum(n) + ...
        (data(n,:)-rawMinimum(n)) / (rawMaximum(n)-rawMinimum(n)) * (calibratedMaximum(n)-calibratedMinimum(n));
end

%% Read events

fprintf('Loading events...\n');
event = readneuroneevents([dataPath num2str(sessionPhaseNumber) filesep]);
NEURONE.event = event;

% Writing event description
latency = strvcat('Latency:','The index number indicating the point in the data when the particular event has occurred');
type = strvcat('Type:','A descriptive name for the event. Will be generated depending on the type of the event as follows:',' ', ...
    'Event type', ...
    '----------', ...
    '1) Unknown', ...
    '2) Stimulation', ...
    '3) Video trigger', ...
    '4) Mute trigger', ...
    '5) 8-bit trigger', ...
    '6) Comment', ' ', ...
    'Corresponding value of the type field', ...
    '-----------------------', ...
    '1) (Source port name) - Unknown', ...
    '2) (Source port name) - Stimulation', ...
    '3) (Source port name) - Video', ...
    '4) (Source port name) - Mute', ...
    '5) (8-bit trigger code, a value between 1-255)',...
    '6) (any user-entered comment related to the event)');

NEURONE.eventdescription = {latency type};

%% Store rest of the data
fprintf('Preparing output...\n');

% Basic dataset information:
NEURONE.srate = srate;
NEURONE.pnts = numel(data)/numel(chans);
NEURONE.xmin = 0;
NEURONE.xmax =(NEURONE.pnts-1)/srate;
NEURONE.trials = 1;
NEURONE.nbchan = length(chans);
NEURONE.data = data;
NEURONE.ref = 'common';
NEURONE.filepath = ''; % Will be generated by EEGLAB when saved
NEURONE.filename = ''; % Will be generated by EEGLAB when saved

% Additional dataset information:
NEURONE.icawinv = [];
NEURONE.icaweights = [];
NEURONE.icasphere = [];
NEURONE.icaact = [];

end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
%% nonlinspace
% Below is a demonstration of the features of the |nonlinspace| function

%%
clear; close all; clc;

%% Syntax
% |y=nonlinspace(range_in,range_out,fform,n);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% 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/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function [min_width, min_angle] = minimumCaliperDiameter(points)
%MINIMUMCALIPERDIAMETER Minimum caliper diameter of a set of points.
%
%   WIDTH = minimumCaliperDiameter(POINTS)
%   Computes the minimum width of a set of points. As polygons and
%   polylines are represented as point lists, this function works also for
%   polygons and polylines.
%
%   [WIDTH THETA] = minimumCaliperDiameter(POINTS)
%   Also returns the direction of minimum width. The direction corresponds
%   to the horizontal angle of the edge that minimizes the width. THETA is
%   given in radians, between 0 and PI.
%
%
%   Example
%   % Compute minimal caliper diameter, and check coords of rotated points
%   % have expected extent
%     points = randn(30, 2);
%     [width theta] = minimumCaliperDiameter(points);
%     points2 = transformPoint(points, createRotation(-theta));
%     diff = max(points2) - min(points2);
%     abs(width - diff(2)) < 1e-10
%     ans =
%         1
%
%   References
%   Algorithms use rotating caliper. Implementation was based on that of
%   Wikipedia:
%   http://en.wikipedia.org/wiki/Rotating_calipers
%
%   See also
%   polygons2d, convexHull, orientedBox
%

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

% first, compute convex hull of the polygon
inds = convhull(points(:,1), points(:,2));
hull = points(inds, :);

% if first and last points are the same, remove the last one
if inds(1) == inds(end)
    hull = hull(1:end-1, :);
end

% number of hull vertices
nV = size(hull, 1);

% default values
rotated_angle = 0;
min_width = inf;
min_angle = 0;

% avoid degenerated cases
if nV < 3
    return;
end

[tmp, p_a] = min(hull(:, 2)); %#ok<ASGLU>
[tmp, p_b] = max(hull(:, 2)); %#ok<ASGLU>

caliper_a = [ 1 0];    % Caliper A points along the positive x-axis
caliper_b = [-1 0];    % Caliper B points along the negative x-axis

while rotated_angle < pi
    % compute the direction vectors corresponding to each edge
    ind_a2 = mod(p_a, nV) + 1;
    vector_a = hull(ind_a2, :) - hull(p_a, :);

    ind_b2 = mod(p_b, nV) + 1;
    vector_b = hull(ind_b2, :) - hull(p_b, :);

    % Determine the angle between each caliper and the next adjacent edge
    % in the polygon
    angle_a = vectorAngle(caliper_a, vector_a);
    angle_b = vectorAngle(caliper_b, vector_b);

    % Determine the smallest of these angles
    minAngle = min(angle_a, angle_b);

    % Rotate the calipers by the smallest angle
    caliper_a = rotateVector(caliper_a, minAngle);
    caliper_b = rotateVector(caliper_b, minAngle);

    rotated_angle = rotated_angle + minAngle;

    % compute current width, and update opposite vertex
    if angle_a < angle_b
        line = createLine(hull(p_a, :), hull(ind_a2, :));
        width = distancePointLine(hull(p_b, :), line);
        p_a = mod(p_a, nV) + 1;

    else
        line = createLine(hull(p_b, :), hull(ind_b2, :));
        width = distancePointLine(hull(p_a, :), line);
        p_b = mod(p_b, nV) + 1;

    end

    % update minimum width and corresponding angle if needed
    if width < min_width
        min_width = width;
        min_angle = rotated_angle;
    end

end

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
%Function that creates different kernels

function func=kernelCreator()
	%Xtrain is the training set
	%Xtest is the test set

	func.SE=@SE;
	func.powExp=@powExp;

end

function [yhat,conf95,K,dd]=SE(Xtrain,ytrain,Xtest,l,A,nugget)
	%Squared Exponential kernel:
	%K(x,x')=exp(-0.5*||x-x'||^2/l^2)
	%l is the length parameter

	%yhat gives the mean of the prediction
	%conf95 is a matrix with two columns with the
	%lower 95 and upper 95 confidence interval

	dd=distance(Xtrain,Xtrain);
	k=dd;
	ks=distance(Xtrain,Xtest);
	kss=distance(Xtest,Xtest);
	%Creating the covariance matrices
	scl=2*l^2;
	K=A*exp(-k/scl)+nugget*eye(size(dd));
	Ks=A*exp(-ks/scl);
	Kss=A*exp(-kss/scl);
	U=chol(K);
	aux=U'\ytrain;
	v=U\aux;

	yhat=Ks'*v;
	yhat;
	%Calculating the confidence intervales
	covariance=Kss-Ks'*inv(K)*Ks;
	diag(covariance);
	temp=sqrt(diag(covariance));
	temp;
	%pause()
	conf95(:,1)=yhat-temp; %lower 95
	conf95(:,2)=yhat+temp;

end

function yhat=powExp(Xtrain,ytrain,Xtest,l,p,nugget)
	%PowerExponentialKernel: exp(-\|x-x'\|^{p}/l^{2})
	%K(x,x')=min(x,x');

	dd=distance(Xtrain,Xtrain);
	k=dd;
	ks=distance(Xtrain,Xtest);
	kss=distance(Xtest,Xtest);
	%Creating the covariance matrices
	scl=l^2;
	K=exp(-(k).^(p/2)/scl)+nugget*eye(size(dd));
	Ks=exp(-(ks).^(p/2)/scl);
	Kss=exp(-(kss).^(p/2)/scl);
	U=chol(K);
	aux=U'\ytrain;
	v=U\aux;

	yhat=Ks'*v;
end

function D=distance(Xtrain,Xtest)
	%Xtrain, Xtest
	%D(i,j) is the euclidean distance between training point i
	%and test point j

	[n,d]=size(Xtrain);
	[t,d]=size(Xtest);

	D=Xtrain.^2*ones(d,t)+ones(n,d)*(Xtest').^2-2*Xtrain*Xtest';
end

author: gudbrandtandberg


text:
function e_global = error_cam_proj(param);

global n_ima x_1 X_1 xproj_1 x_proj_1 x_2 X_2 xproj_2 x_proj_2 x_3 X_3 xproj_3 x_proj_3 x_4 X_4 xproj_4 x_proj_4 x_5 X_5 xproj_5 x_proj_5 x_6 X_6 xproj_6 x_proj_6 x_7 X_7 xproj_7 x_proj_7 x_8 X_8 xproj_8 x_proj_8 x_9 X_9 xproj_9 x_proj_9 x_10 X_10 xproj_10 x_proj_10 x_11 X_11 xproj_11 x_proj_11 x_12 X_12 xproj_12 x_proj_12 x_13 X_13 xproj_13 x_proj_13 x_14 X_14 xproj_14 x_proj_14 x_15 X_15 xproj_15 x_proj_15 x_16 X_16 xproj_16 x_proj_16  x_17 X_17 xproj_17 x_proj_17 x_18 X_18 xproj_18 x_proj_18 x_19 X_19 xproj_19 x_proj_19 x_20 X_20 xproj_20 x_proj_20 x_21 X_21 xproj_21 x_proj_21 x_22 X_22 xproj_22 x_proj_22 x_23 X_23 xproj_23 x_proj_23 x_24 X_24 xproj_24 x_proj_24 x_25 X_25 xproj_25 x_proj_25 x_26 X_26 xproj_26 x_proj_26  x_27 X_27 xproj_27 x_proj_27 x_28 X_28 xproj_28 x_proj_28 x_29 X_29 xproj_29 x_proj_29 x_30 X_30 xproj_30 x_proj_30

% This is the same model, but with a simpler distortion model (no 6th order)

% Computation of the errors:

fc = param(1:2);
cc = param(3:4);
alpha_c = param(5);
kc = [param(6:9);0];

e_cam = [];

for kk = 1:n_ima,
   omckk = param(11+(kk-1)*6-1:11+(kk-1)*6+2-1);
   Tckk = param(11+(kk-1)*6+3-1:11+(kk-1)*6+3+2-1);

   eval(['Xkk = X_' num2str(kk) ';']);
   eval(['xkk = x_' num2str(kk) ';']);

   ekk = xkk - project_points2(Xkk,omckk,Tckk,fc,cc,kc,alpha_c);

   Rckk = rodrigues(omckk);
   eval(['omc_' num2str(kk) '= omckk;']);
   eval(['Tc_' num2str(kk) '= Tckk;']);
   eval(['Rc_' num2str(kk) '= Rckk;']);

   e_cam = [e_cam ekk];

end;

X_proj = [];
x_proj = [];

for kk = 1:n_ima,
   eval(['xproj = xproj_' num2str(kk) ';']);
   xprojn = normalize_pixel(xproj,fc,cc,kc,alpha_c);
   eval(['Rc = Rc_' num2str(kk) ';']);
   eval(['Tc = Tc_' num2str(kk) ';']);
   Np_proj = size(xproj,2);
	Zc = ((Rc(:,3)'*Tc) * (1./(Rc(:,3)' * [xprojn; ones(1,Np_proj)])));
	Xcp = (ones(3,1)*Zc) .* [xprojn; ones(1,Np_proj)]; % % in the camera frame
   eval(['X_proj_' num2str(kk) ' = Xcp;']); % coordinates of the points in the
   eval(['X_proj = [X_proj X_proj_' num2str(kk) '];']);
   eval(['x_proj = [x_proj x_proj_' num2str(kk) '];']);
end;

fp = param((1:2)+n_ima * 6 + 10-1);
cp = param((3:4)+n_ima * 6 + 10-1);
alpha_p = param((5)+n_ima * 6 + 10-1);
kp = [param((6-1:10-2)+n_ima * 6 + 10);0];

om = param(10+n_ima*6+10+1-2:10+n_ima*6+10+1+2-2);
T = param(10+n_ima*6+10+1+2+1-2:10+n_ima*6+10+1+2+1+2-2);

e_proj = x_proj - project_points2(X_proj,om,T,fp,cp,kp,alpha_p);

e_global = [e_cam e_proj];

repo: ekfmonoslam


text:
function opt_checkExclusiveProps(opt, proppair, isdefault)

if ischar(opt),
  tag= ['in STRUCT ''' opt ''' '];
  opt= evalin('caller', opt);
else
  tag= '';
end

if nargin<3,
  for p= 1:size(proppair,1),
    for k= 1:length(opt),
      if ~isempty(opt(k).(proppair{p,1})) && ~isempty(opt(k).(proppair{p,2})),
        error('%sonly one of properties ''%s'' and ''%s'' can be nonempty.', ...
              tag, proppair{p,1}, proppair{p,2});
      end
    end
  end
else
  for p= 1:size(proppair,1),
    if ~isdefault.(proppair{p,1}) && ~isdefault.(proppair{p,2}),
      error('%sonly one of properties ''%s'' and ''%s'' can be set.', ...
            tag, proppair{p,1}, proppair{p,2});
    end
  end
end

author: bbci


text:
function varargout= procutil_catFilters(varargin)
% PROCUTIL_CATFILTERS - Concatenate several filters into one
%
%Synopsis:
% [B, A]= procutil_catFilters(FILT1, <FILT2>, ...)
% HD= procutil_catFilters(FILT1, <FILT2>, ...)
%
%Arguments:
% FILTx - Filter specified as struct with fields b and a
%
%Output:
% B, A - filter coefficients
% HD   - filter specified as discrete-time filter object

sos= zeros(0, 6);
g= [];

for ii= 1:length(varargin),
  [sos0, g0]= tf2sos(varargin{ii}.b, varargin{ii}.a);
  sos= cat(1, sos, sos0);
  g= cat(1, g, g0);
end

if nargout==2,
  [b, a]= sos2tf(sos, g);
  varargout= {b, a};
elseif nargout==1,
  Hd= dfilt.df2sos(sos, g);
  varargout= {Hd};
end


text:
% -------------------------------------------------------------------------------------------------------------------------
classdef XCorr < dagnn.Layer
%XCORR
%   Crosscorrelates two activations of different size exploiting  the API of vl_nnconv
%
%   Luca Bertinetto, Jack Valmadre, Joao F. Henriques, 2016
% -------------------------------------------------------------------------------------------------------------------------
    properties
        opts = {'cuDNN'}
    end

    methods
        function outputs = forward(obj, inputs, params)
            assert(numel(inputs) == 2, 'two inputs are needed');

            z = inputs{1}; % exemplar
            x = inputs{2}; % instance (search region)

%             assert(ndims(z) == ndims(x), 'z and x have different number of dimensions');
%             assert(size(z,1) <= size(x,1), 'exemplar z has to be smaller than instance x');
%
%             [wx,hx,cx,bx] = size(x);
%             x = reshape(x, [wx,hx,cx*bx,1]);
%             o = vl_nnconv(x, z, []);
%             [wo,ho,co,bo] = size(o);
%             assert(co==bx);
%             outputs{1} = reshape(o, [wo,ho,bo,co]);
%             [w,h,c] = size(x);
%             x = reshape(x,[w,h,c,1]);
            outputs{1} = vl_nnconv(x, z, []);
        end

        function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)
            assert(numel(inputs) == 2, 'two inputs are needed');
            assert(numel(derOutputs) == 1, 'only one gradient should be flowing in this layer (dldy)');
            z = inputs{1}; % exemplar
            x = inputs{2}; % instance
            assert(size(z,1) < size(x,1), 'exemplar z has to be smaller than instance x');
            [wx,hx,cx,bx] = size(x);
            x = reshape(x, [wx,hx,cx*bx,1]);
            dldy = derOutputs{1};
            [wdl,hdl,cdl,bdl] = size(dldy);
            assert(cdl==1);
            dldy = reshape(dldy, [wdl,hdl,cdl*bdl,1]);
            [dldx, dldz, ~] = vl_nnconv(x, z, [], dldy);
            [mx,nx,cb,one] = size(dldx);
            assert(mx == size(x, 1));
            assert(nx == size(x, 2));
            assert(cb == cx * bx);
            assert(one == 1);
            derInputs{1} = dldz;
            derInputs{2} = reshape(dldx, [mx,nx,cx,bx]);
            derParams = {};
        end

        function outputSizes = getOutputSizes(obj, inputSizes)
            z_sz = inputSizes{1};
            x_sz = inputSizes{2};
            y_sz = [x_sz(1:2) - z_sz(1:2) + 1, 1, z_sz(4)];
            outputSizes = {y_sz};
        end

        function rfs = getReceptiveFields(obj)
            rfs(1,1).size = [inf inf]; % could be anything
            rfs(1,1).stride = [1 1];
            rfs(1,1).offset = 1;
            rfs(2,1).size = [inf inf];
            rfs(2,1).stride = [1 1];
            rfs(2,1).offset = 1;
        end

        function obj = XCorr(varargin)
            obj.load(varargin);
        end

    end

end

author: XinLi-zn

repo: TADT

save_path: github-repos/MATLAB/XinLi-zn-TADT


text:
function varargout = lvd_editEvtTermCond(varargin)
% LVD_EDITEVTTERMCOND MATLAB code for lvd_editEvtTermCond.fig
%      LVD_EDITEVTTERMCOND, by itself, creates a new LVD_EDITEVTTERMCOND or raises the existing
%      singleton*.
%
%      H = LVD_EDITEVTTERMCOND returns the handle to a new LVD_EDITEVTTERMCOND or the handle to
%      the existing singleton*.
%
%      LVD_EDITEVTTERMCOND('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in LVD_EDITEVTTERMCOND.M with the given input arguments.
%
%      LVD_EDITEVTTERMCOND('Property','Value',...) creates a new LVD_EDITEVTTERMCOND or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before lvd_editEvtTermCond_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to lvd_editEvtTermCond_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_editEvtTermCond

% Last Modified by GUIDE v2.5 11-May-2021 14:34:10

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

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

    event = varargin{1};
    setappdata(hObject,'event',event);
    setappdata(hObject,'lvdData',event.script.lvdData);

    populateGUI(handles, event);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, event)
    termCondStrs = TerminationConditionEnum.getTermCondTypeNameStrs();
    set(handles.termCondTypeCombo,'String',termCondStrs);

    termCond = event.termCond;
    ind = TerminationConditionEnum.getIndOfListboxStrsForTermCond(termCond);
    set(handles.termCondTypeCombo,'Value',ind);

    params = termCond.getTermCondUiStruct();

    value = params.value;
    if(isempty(value))
        value = 0.0;
    end

    set(handles.numParamText,'String',fullAccNum2Str(value));

    lv = event.script.lvdData.launchVehicle;

    stagesListStr = lv.getStagesListBoxStr();
    set(handles.refStageCombo,'String',stagesListStr);

    tanksListStr = lv.getTanksListBoxStr();
    set(handles.refTankCombo,'String',tanksListStr);

    enginesListStr = lv.getEnginesListBoxStr();
    set(handles.refEngineCombo,'String',enginesListStr);

    swListStr = lv.getStopwatchesListBoxStr();
    set(handles.refStopwatchCombo,'String',swListStr);
    if(isempty(swListStr))
        set(handles.refStopwatchCombo,'String','<No Stopwatch Yet Created>');
        set(handles.refStopwatchCombo,'Value',1);
    end

    set(handles.numParamLabel,'String',params.paramName);
    set(handles.numParamUnitLabel,'String',params.paramUnit);

    set(handles.numParamText,'Enable',params.useParam);
    set(handles.optParamCheckbox,'Enable',params.useParam);
    set(handles.paramLbText,'Enable',params.useParam);
    set(handles.paramUbText,'Enable',params.useParam);

    set(handles.refStageCombo,'Enable',params.useStages);
    set(handles.refTankCombo,'Enable',params.useTanks);
    set(handles.refEngineCombo,'Enable',params.useEngines);
    set(handles.refStopwatchCombo,'Enable',params.useStopwatches);

    if(not(isempty(params.refStage)))
        set(handles.refStageCombo,'Value',lv.getListBoxIndForStage(params.refStage));
    end

    if(not(isempty(params.refTank)))
        set(handles.refTankCombo,'Value',lv.getListBoxIndForTank(params.refTank));
    end

    if(not(isempty(params.refEngine)))
        set(handles.refEngineCombo,'Value',lv.getListBoxIndForEngine(params.refEngine));
    end

    if(not(isempty(params.refStopwatch)))
        set(handles.refStopwatchCombo,'Value',lv.getListBoxIndForStopwatch(params.refStopwatch));
    end

    optVar = termCond.getExistingOptVar();
    if(isempty(optVar))
        useTf = false([1,1]);
        lb = zeros(size(useTf));
        ub = zeros(size(useTf));
    else
        useTf = optVar.getUseTfForVariable();
        optVar.setUseTfForVariable(true(size(useTf)));
        [lb, ub] = optVar.getBndsForVariable();
        optVar.setUseTfForVariable(useTf);
    end

    if(strcmpi(params.paramUnit,'deg'))
        lb = rad2deg(lb);
        ub = rad2deg(ub);
    elseif(strcmpi(params.paramUnit,'%'))
        lb = lb*100;
        ub = ub*100;
    end

    lbStr = fullAccNum2Str(lb);
    ubStr = fullAccNum2Str(ub);

    set(handles.optParamCheckbox,'Value',useTf);
    set(handles.paramLbText,'String',lbStr);
    set(handles.paramUbText,'String',ubStr);

    optParamCheckbox_Callback(handles.optParamCheckbox,[],handles);

    frame = termCond.frame;
    if(isempty(frame))
        frame = LvdData.getDefaultInitialBodyInfo(event.script.lvdData.celBodyData).getBodyCenteredInertialFrame();
        termCond.frame = frame;
    end
    setappdata(handles.lvd_editEvtTermCond,'frame',frame);

    handles.refFrameTypeCombo.String = ReferenceFrameEnum.getListBoxStr();
    [ind, ~] = ReferenceFrameEnum.getIndForName(frame.typeEnum.name);
    handles.refFrameTypeCombo.Value = ind;
    handles.setFrameOptionsButton.TooltipString = sprintf('Current Frame: %s', frame.getNameStr());
    handles.refFrameNameLabel.String = sprintf('%s', frame.getNameStr());
    handles.refFrameNameLabel.TooltipString = sprintf('%s', frame.getNameStr());

% --- Outputs from this function are returned to the command line.
function varargout = lvd_editEvtTermCond_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} = [];
    else
        event = getappdata(hObject,'event');
        lv = event.script.lvdData.launchVehicle;

        paramValue = str2double(get(handles.numParamText,'String'));

        termCond = event.termCond;
        params = getParamsForSelectedTermCondType(handles);

        optVar = termCond.getExistingOptVar();
        if(not(isempty(optVar)))
            lv.lvdData.optimizer.vars.removeVariable(optVar);%need to remove existing var if it exists
        end

        if(strcmpi(params.paramUnit,'deg'))
            paramValue = deg2rad(paramValue);
        elseif(strcmpi(params.paramUnit,'%'))
            paramValue = paramValue/100;
        end

        [~,stages] = lv.getStagesListBoxStr();
        [~,tanks] = lv.getTanksListBoxStr();
        [~,engines] = lv.getEnginesListBoxStr();
        [~,stopwatches] = lv.getStopwatchesListBoxStr();

        if(not(isempty(stages)))
            stage = stages(get(handles.refStageCombo,'Value'));
        else
            stage = stages;
        end

        if(not(isempty(tanks)))
            tank = tanks(get(handles.refTankCombo,'Value'));
        else
            tank = tanks;
        end

        if(not(isempty(engines)))
            engine = engines(get(handles.refEngineCombo,'Value'));
        else
            engine = engines;
        end

        if(not(isempty(stopwatches)))
            stopwatch = stopwatches(get(handles.refStopwatchCombo,'Value'));
        else
            stopwatch = stopwatches;
        end

        [m,~] = enumeration('TerminationConditionEnum');
        contents = cellstr(get(handles.termCondTypeCombo,'String'));
        termCondType = contents{get(handles.termCondTypeCombo,'Value')};
        ind = strcmpi({m.nameStr},termCondType);
        termCond = feval(sprintf('%s.getTermCondForParams',m(ind).classNameStr), paramValue, stage, tank, engine, stopwatch);

        lb = str2double(get(handles.paramLbText,'String'));
        ub = str2double(get(handles.paramUbText,'String'));

        if(strcmpi(params.paramUnit,'deg'))
            lb = deg2rad(lb);
            ub = deg2rad(ub);
        elseif(strcmpi(params.paramUnit,'%'))
            lb = lb/100;
            ub = ub/100;
        end

        optVar = termCond.getNewOptVar();

        if(not(isempty(optVar)))
            optVar.setUseTfForVariable(true);
            optVar.setBndsForVariable(lb, ub);

            useTf = logical(get(handles.optParamCheckbox,'Value'));
            optVar.setUseTfForVariable(useTf);

            termCond.optVar = optVar;
            optVar.varObj = termCond;

            lv.lvdData.optimizer.vars.addVariable(optVar);
        end

        frame = getappdata(hObject,'frame');
        termCond.frame = frame;

        event.termCond = termCond;

        close(handles.lvd_editEvtTermCond);
    end

function errMsg = validateInputs(handles)
    errMsg = {};

    value = str2double(get(handles.numParamText,'String'));
    enteredStr = get(handles.numParamText,'String');
    numberName = get(handles.numParamLabel,'String');
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    lwrBndValue = str2double(get(handles.paramLbText,'String'));
    enteredStr = get(handles.paramLbText,'String');
    numberName = [get(handles.numParamLabel,'String'), ' Lower Bound'];
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(lwrBndValue, numberName, lb, ub, isInt, errMsg, enteredStr);

    uprBndValue = str2double(get(handles.paramUbText,'String'));
    enteredStr = get(handles.paramUbText,'String');
    numberName = [get(handles.numParamLabel,'String'), ' Upper Bound'];
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(uprBndValue, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        uprBndValue = str2double(get(handles.paramUbText,'String'));
        enteredStr = get(handles.paramUbText,'String');
        numberName = [get(handles.numParamLabel,'String'), ' Upper Bound'];
        lb = lwrBndValue;
        ub = Inf;
        isInt = false;
        errMsg = validateNumber(uprBndValue, numberName, lb, ub, isInt, errMsg, enteredStr);
    end

% --- Executes on selection change in termCondTypeCombo.
function termCondTypeCombo_Callback(hObject, eventdata, handles)
% hObject    handle to termCondTypeCombo (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 termCondTypeCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from termCondTypeCombo
    params = getParamsForSelectedTermCondType(handles);

    set(handles.numParamLabel,'String',params.paramName);
    set(handles.numParamUnitLabel,'String',params.paramUnit);

    set(handles.numParamText,'Enable',params.useParam);
    set(handles.optParamCheckbox,'Enable',params.useParam);
    set(handles.paramLbText,'Enable',params.useParam);
    set(handles.paramUbText,'Enable',params.useParam);

    if(params.useParam == false)
        set(handles.optParamCheckbox,'Value',0);
    end

    set(handles.refStageCombo,'Enable',params.useStages);
    set(handles.refTankCombo,'Enable',params.useTanks);
    set(handles.refEngineCombo,'Enable',params.useEngines);
    set(handles.refStopwatchCombo,'Enable',params.useStopwatches);

function params = getParamsForSelectedTermCondType(handles)
	event = getappdata(handles.lvd_editEvtTermCond,'event');
    lv = event.script.lvdData.launchVehicle;

    [~,stages] = lv.getStagesListBoxStr();
    [~,tanks] = lv.getTanksListBoxStr();
    [~,engines] = lv.getEnginesListBoxStr();
    [~, stopwatches] = lv.getStopwatchesListBoxStr();

    stage = stages(1);
    tank = tanks(1);
    engine = engines(1);

    if(not(isempty(stopwatches)))
        stopwatch = stopwatches(1);
    else
        stopwatch = LaunchVehicleStopwatch.empty(1,0);
    end

    [m,~] = enumeration('TerminationConditionEnum');
    contents = cellstr(get(handles.termCondTypeCombo,'String'));
    termCondType = contents{get(handles.termCondTypeCombo,'Value')};
    ind = strcmpi({m.nameStr},termCondType);
    termCond = feval(sprintf('%s.getTermCondForParams',m(ind).classNameStr), 0, stage, tank, engine, stopwatch);

    params = termCond.getTermCondUiStruct();

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

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

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

% Hints: get(hObject,'String') returns contents of numParamText as text
%        str2double(get(hObject,'String')) returns contents of numParamText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

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

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

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

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

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

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

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

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

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

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

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

% --- Executes on button press in 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)
    errMsg = validateInputs(handles);

    if(isempty(errMsg))
       uiresume(handles.lvd_editEvtTermCond);
    else
        msgbox(errMsg,'Errors were found while editing the termination conditions.','error');
    end

% --- 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_editEvtTermCond);

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

% Hint: get(hObject,'Value') returns toggle state of optParamCheckbox
    if(get(hObject,'Value') == 1)
        set(handles.paramLbText,'Enable','on');
        set(handles.paramUbText,'Enable','on');
    else
        set(handles.paramLbText,'Enable','off');
        set(handles.paramUbText,'Enable','off');
    end

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

% Hints: get(hObject,'String') returns contents of paramLbText as text
%        str2double(get(hObject,'String')) returns contents of paramLbText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

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

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

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

% Hints: get(hObject,'String') returns contents of paramUbText as text
%        str2double(get(hObject,'String')) returns contents of paramUbText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

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

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

% --- Executes on key release with focus on lvd_editEvtTermCond or any of its controls.
function lvd_editEvtTermCond_WindowKeyReleaseFcn(hObject, eventdata, handles)
% hObject    handle to lvd_editEvtTermCond (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was released, in lower case
%	Character: character interpretation of the key(s) that was released
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) released
% 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_editEvtTermCond);
    end

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

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

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

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

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

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

% --- Executes on button press in setFrameOptionsButton.
function setFrameOptionsButton_Callback(hObject, eventdata, handles)
% hObject    handle to setFrameOptionsButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    curFrame = getappdata(handles.lvd_editEvtTermCond,'frame');
    curFrame = curFrame.editFrameDialogUI(EditReferenceFrameContextEnum.ForState);

    setappdata(handles.lvd_editEvtTermCond,'frame',curFrame);

    handles.setFrameOptionsButton.Tooltip = sprintf('Current Frame: %s', curFrame.getNameStr());
    handles.refFrameNameLabel.String = sprintf('%s', curFrame.getNameStr());
    handles.refFrameNameLabel.TooltipString = sprintf('%s', curFrame.getNameStr());

function updateFrameChange(handles)
    lvdData = getappdata(handles.lvd_editEvtTermCond,'lvdData');
    celBodyData = lvdData.celBodyData;

    refEnumListBoxStr = ReferenceFrameEnum.getListBoxStr();
    selFrameTypeInd = handles.refFrameTypeCombo.Value;
    refFrameEnum = ReferenceFrameEnum.getEnumForListboxStr(refEnumListBoxStr{selFrameTypeInd});

%             if(not(isempty(newFrame)) && newFrame.typeEnum ~= refFrameEnum)
%                 refFrameEnum = newFrame.typeEnum;
%                 app.refFrameTypeCombo.Value = ReferenceFrameEnum.getIndForName(refFrameEnum.name);
%             end

    switch refFrameEnum
        case ReferenceFrameEnum.BodyCenteredInertial
            bodyInfo = getSelectedBodyInfo(handles);

            newFrame = bodyInfo.getBodyCenteredInertialFrame();

        case ReferenceFrameEnum.BodyFixedRotating
            bodyInfo = getSelectedBodyInfo(handles);

            newFrame = bodyInfo.getBodyFixedFrame();

        case ReferenceFrameEnum.TwoBodyRotating
            bodyInfo = getSelectedBodyInfo(handles);
            if(not(isempty(bodyInfo.childrenBodyInfo)))
                primaryBody = bodyInfo;
                secondaryBody = bodyInfo.childrenBodyInfo(1);
            else
                primaryBody = bodyInfo.getParBodyInfo();
                secondaryBody = bodyInfo;
            end

            originPt = TwoBodyRotatingFrameOriginEnum.Primary;

            newFrame = TwoBodyRotatingFrame(primaryBody, secondaryBody, originPt, celBodyData);

        case ReferenceFrameEnum.UserDefined
            numFrames = lvdData.geometry.refFrames.getNumRefFrames();
            if(numFrames >= 1)
                geometricFrame = AbstractGeometricRefFrame.empty(1,0);
                for(i=1:numFrames)
                    frame = lvdData.geometry.refFrames.getRefFrameAtInd(i);
                    if(frame.isVehDependent() == false)
                        geometricFrame = frame;
                        break;
                    end
                end

                if(not(isempty(geometricFrame)))
                    newFrame = UserDefinedGeometricFrame(geometricFrame, lvdData);
                else
                    bodyInfo = getSelectedBodyInfo(handles);
                    newFrame = bodyInfo.getBodyCenteredInertialFrame();

                    warndlg('There are no geometric frames available which are not dependent on vehicle properties.  A body-centered inertial frame will be selected instead.');
                end
            else
                bodyInfo = getSelectedBodyInfo(handles);
                newFrame = bodyInfo.getBodyCenteredInertialFrame();

                warndlg('There are no geometric frames available which are not dependent on vehicle properties.  A body-centered inertial frame will be selected instead.');
            end

        otherwise
            error('Unknown reference frame type: %s', string(refFrameEnum));
    end

    if(not(isempty(newFrame)) && newFrame.typeEnum ~= refFrameEnum)
        refFrameEnum = newFrame.typeEnum;
        handles.refFrameTypeCombo.Value = ReferenceFrameEnum.getIndForName(refFrameEnum.name);
    end

    setappdata(handles.lvd_editEvtTermCond,'frame', newFrame);
    handles.setFrameOptionsButton.TooltipString = sprintf('Current Frame: %s', newFrame.getNameStr());
    handles.refFrameNameLabel.String = sprintf('%s', newFrame.getNameStr());
    handles.refFrameNameLabel.TooltipString = sprintf('%s', newFrame.getNameStr());

function bodyInfo = getSelectedBodyInfo(handles)
    curFrame = getappdata(handles.lvd_editEvtTermCond,'frame');
    bodyInfo = curFrame.getOriginBody();

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function [pmiss,pfa] = rocch(tar_scores,nontar_scores)
% ROCCH: ROC Convex Hull.
% Usage: [pmiss,pfa] = rocch(tar_scores,nontar_scores)
% (This function has the same interface as compute_roc.)
%
% Note: pmiss and pfa contain the coordinates of the vertices of the
%       ROC Convex Hull.
%
% For a demonstration that plots ROCCH against ROC for a few cases, just
% type 'rocch' at the MATLAB command line.
%
% Inputs:
%   tar_scores: scores for target trials
%   nontar_scores: scores for non-target trials

if nargin==0
    test_this();
    return
end

assert(nargin==2)
assert(isvector(tar_scores))
assert(isvector(nontar_scores))

Nt = length(tar_scores);
Nn = length(nontar_scores);
N = Nt+Nn;
scores = [tar_scores(:)',nontar_scores(:)'];
Pideal = [ones(1,Nt),zeros(1,Nn)];  %ideal, but non-monotonic posterior

%It is important here that scores that are the same (i.e. already in order) should NOT be swapped.
%MATLAB's sort algorithm has this property.
[scores,perturb] = sort(scores);

Pideal = Pideal(perturb);
[Popt,width] = pavx(Pideal);

nbins = length(width);
pmiss = zeros(1,nbins+1);
pfa = zeros(1,nbins+1);

%threshold leftmost: accept eveything, miss nothing
left = 0; %0 scores to left of threshold
fa = Nn;
miss = 0;

for i=1:nbins
    pmiss(i) = miss/Nt;
    pfa(i) = fa/Nn;
    left = left + width(i);
    miss = sum(Pideal(1:left));
    fa = N - left - sum(Pideal(left+1:end));
end
pmiss(nbins+1) = miss/Nt;
pfa(nbins+1) = fa/Nn;

end

function test_this()

figure();

subplot(2,3,1);
tar = [1]; non = [0];
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g--v');
axis('square');grid;legend('ROCCH','ROC');
title('2 scores: non < tar');

subplot(2,3,2);
tar = [0]; non = [1];
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g-v');
axis('square');grid;
title('2 scores: tar < non');

subplot(2,3,3);
tar = [0]; non = [-1,1];
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g--v');
axis('square');grid;
title('3 scores: non < tar < non');

subplot(2,3,4);
tar = [-1,1]; non = [0];
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g--v');
axis('square');grid;
title('3 scores: tar < non < tar');
xlabel('P_{fa}');
ylabel('P_{miss}');

subplot(2,3,5);
tar = randn(1,100)+1; non = randn(1,100);
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g');
axis('square');grid;
title('45^{\circ} DET');

subplot(2,3,6);
tar = randn(1,100)*2+1; non = randn(1,100);
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g');
axis('square');grid;
title('flatter DET');

end

author: nesl


text:
function [f,df] = knitro_callback_f(x,model)

global latest_x_f
global latest_df
global latest_f

x = x(:);
if isequal(x,latest_x_f)
    df = latest_df;
    f = latest_f;
else
    [f,df] = fmincon_fun_liftlayer(x,model);
    latest_x_f = x;
    latest_f = f;
    latest_df = df;
end

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
function this = smooth(this)
% Smoothes all images in the time series
%
%   MrSeries = smooth(MrSeries)
%
% This is a method of class MrSeries.
%
% IN
%   parameters.smooth.fwhmMillimeter
%
% OUT
%
% EXAMPLE
%   smooth
%
%   See also MrSeries

% Author:   Saskia Klein & Lars Kasper
% Created:  2014-07-02
% Copyright (C) 2014 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public Licence (GPL), version 3.
% You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version).
% For further details, see the file COPYING or
%  <http://www.gnu.org/licenses/>.

fwhm = this.parameters.smooth.fwhmMillimeters;

this.init_processing_step('smooth');
this.data = this.data.smooth('fwhm', fwhm);
this.finish_processing_step('smooth', this.data);

author: translationalneuromodeling

repo: tapas


text:
%%COMPARE2DASSIGN Compile the C and C++ implementations of the assignment
%                 algorithms and run the various 2D assignment algorithms
%                 on random cost  matrices of differing sizes to compare
%                 the execution times. This function demonstrates how fast
%                 2D assignment can be, but also how the speed is
%                 influenced by some programmatic options such as whether
%                 one uses a direct Matlab implementation or a compiled C
%                 or C++ implementation. Additionally, whether one scans
%                 by row or by column makes a difference, because Matlab
%                 stores data by column, so scanning across columns
%                 increases the likelihood of a cache miss, slowing things
%                 down.
%
%This function requires that the CompileCLibraries function has been run so
%that the necessary functions have been compiled. This function comes with
%the additional supporting files
%assign2DAlt.cpp
%assign2DByCol.c
%assign2DByCol.m
%which all mirror the functionality of assign2D.m/assign2D.c, but which
%differ in how they are implemented so as to demonstrate the effects on
%speed of the differences. The type of comparison done is here essentially
%that done in [1] and the second half of [2].
%
%When recording execution times, the functions tic and toc are used.
%However, to speed up the Monte Carlo runs, if installed, the parallel
%processing toolbox will be used (by using parfor instead of for) so that
%the Monte Carlo runs can occur in parallel across processors/ cores. This
%means that the loop has to keep a local variable, named ticLoc here, so
%that the timer across processors can properly match starting times to
%stopping times.
%
%REFERENCES:
%[1] D. F. Crouse, "On implementing 2D rectangular assignment algorithms,"
%    IEEE Transactions on Aerospace and Electronic Systems, accepted 2016.
%[2] D. F. Crouse, "Advances in displaying uncertain estimates of multiple
%    targets," in Proceedings of SPIE: Signal Processing, Sensor Fusion,
%    and Target Recognition XXII, Baltimore, MD, Apr. 2013.
%
%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

%Change this value to 1000 to redo the simulations used in the paper.
numRuns=2;
fprintf('%i Monte Carlo runs shall be used used\n',numRuns)

%The search path and current working directories will be modified. Thus,
%save the old search path and working directory so that they can be
%restored when the script exits.
oldPath=path();
curDir=pwd;
ScriptPath=mfilename('fullpath');
ScriptFolder=fileparts(ScriptPath);
%Set the current working directory to the folder in which this script is
%located.
cd(ScriptFolder)

%%Test the Matlab implementations of the 2D assignment code
%Remove the compiled code directory from the search path, so that the
%Matlab implementations are used and the C and C++ implementationa are
%ignored.
compiledCodeFolder=[fileparts(fileparts(ScriptFolder)),'/0_Compiled_Code'];
rmpath(compiledCodeFolder)

disp('Running the Monte Carlo runs for the 2D assignment code in Matlab')
MatlabByRow100=zeros(numRuns,1);
MatlabByRow200=zeros(numRuns,1);
MatlabByRow500=zeros(numRuns,1);
MatlabByRow500b1000=zeros(numRuns,1);
MatlabByRow3000=zeros(numRuns,1);

MatlabByCol100=zeros(numRuns,1);
MatlabByCol200=zeros(numRuns,1);
MatlabByCol500=zeros(numRuns,1);
MatlabByCol500b1000=zeros(numRuns,1);
MatlabByCol3000=zeros(numRuns,1);
for curRun=1:numRuns
    curRun
    %100X100 Matrix
    C=rand(100,100);
    %Matlab Implementation, where the inner loop scans by row.
    ticLoc=tic;
    [col4row,row4col,gain]=assign2D(C,false);
    MatlabByRow100(curRun)=toc(ticLoc);
    %Matlab implementation where the inner loop scans by column.
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DByCol(C,false);
    MatlabByCol100(curRun)=toc(ticLoc);

    %200X200 matrix
    C=rand(200,200);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2D(C,false);
    MatlabByRow200(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DByCol(C,false);
    MatlabByCol200(curRun)=toc(ticLoc);

    %500X500 Matrix
    C=rand(500,500);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2D(C,false);
    MatlabByRow500(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DByCol(C,false);
    MatlabByCol500(curRun)=toc(ticLoc);

    %500X1000 Matrix
    C=rand(500,1000);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2D(C,false);
    MatlabByRow500b1000(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DByCol(C,false);
    MatlabByCol500b1000(curRun)=toc(ticLoc);

    %3000X3000 Matrix
    C=rand(3000,3000);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2D(C,false);
    MatlabByRow3000(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DByCol(C,false);
    MatlabByCol3000(curRun)=toc(ticLoc);
end

%%Test the Matlab implementation of the k-best 2D assignment code
disp('Running the Monte Carlo runs for the k-best 2D assignment code in Matlab')
MatlabkB10b20h2=zeros(numRuns,1);
MatlabkB10b20h25=zeros(numRuns,1);
MatlabkB10b20h50=zeros(numRuns,1);

MatlabkB50b100h2=zeros(numRuns,1);
MatlabkB50b100h25=zeros(numRuns,1);
MatlabkB50b100h50=zeros(numRuns,1);

MatlabkB100b100h2=zeros(numRuns,1);
MatlabkB100b100h25=zeros(numRuns,1);
MatlabkB100b100h50=zeros(numRuns,1);
for curRun=1:numRuns
    %10X20 Matrix
    C=rand(10,20);
    k=2;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    MatlabkB10b20h2(curRun)=toc(ticLoc);
    k=25;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    MatlabkB10b20h25(curRun)=toc(ticLoc);
    k=50;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    MatlabkB10b20h50(curRun)=toc(ticLoc);

    %50X100 Matrix
    C=rand(50,100);
    k=2;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    MatlabkB50b100h2(curRun)=toc(ticLoc);
    k=25;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    MatlabkB50b100h25(curRun)=toc(ticLoc);
    k=50;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    MatlabkB50b100h50(curRun)=toc(ticLoc);

    %100X100 Matrix
    C=rand(100,100);
    k=2;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    MatlabkB100b100h2(curRun)=toc(ticLoc);
    k=25;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    MatlabkB100b100h25(curRun)=toc(ticLoc);
    k=50;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    MatlabkB100b100h50(curRun)=toc(ticLoc);
end

%%Test the C and C++ implementations of the 2D assignment code

%Add the compiled code directory to the search path so that the Matlab
%versions of the algorithms will no longer be used
addpath(compiledCodeFolder)

disp('Running the Monte Carlo runs for the 2D assignment code in C and C++')
CPPByRow100=zeros(numRuns,1);
CPPByRow200=zeros(numRuns,1);
CPPByRow500=zeros(numRuns,1);
CPPByRow500b1000=zeros(numRuns,1);
CPPByRow3000=zeros(numRuns,1);

CByRow100=zeros(numRuns,1);
CByRow200=zeros(numRuns,1);
CByRow500=zeros(numRuns,1);
CByRow500b1000=zeros(numRuns,1);
CByRow3000=zeros(numRuns,1);

CByCol100=zeros(numRuns,1);
CByCol200=zeros(numRuns,1);
CByCol500=zeros(numRuns,1);
CByCol500b1000=zeros(numRuns,1);
CByCol3000=zeros(numRuns,1);

for curRun=1:numRuns
    %100X100 Matrix
    C=rand(100,100);
    %C++ Implementation, where the inner loop scans by row.
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DAlt(C,false);
    CPPByRow100(curRun)=toc(ticLoc);
    %C implementation, where the inner loop scans by row.
    ticLoc=tic;
    [col4row,row4col,gain]=assign2D(C,false);
    CByRow100(curRun)=toc(ticLoc);
    %C implementation where the inner loop scans by column.
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DByCol(C,false);
    CByCol100(curRun)=toc(ticLoc);

    %200X200 Matrix
    C=rand(200,200);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DAlt(C,false);
    CPPByRow200(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2D(C,false);
    CByRow200(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DByCol(C,false);
    CByCol200(curRun)=toc(ticLoc);

    %500X500 Matrix
    C=rand(500,500);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DAlt(C,false);
    CPPByRow500(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2D(C,false);
    CByRow500(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DByCol(C,false);
    CByCol500(curRun)=toc(ticLoc);

    %500X1000 Matrix
    C=rand(500,1000);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DAlt(C,false);
    CPPByRow500b1000(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2D(C,false);
    CByRow500b1000(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DByCol(C,false);
    CByCol500b1000(curRun)=toc(ticLoc);

    %3000X3000 Matrix
    C=rand(3000,3000);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DAlt(C,false);
    CPPByRow3000(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2D(C,false);
    CByRow3000(curRun)=toc(ticLoc);
    ticLoc=tic;
    [col4row,row4col,gain]=assign2DByCol(C,false);
    CByCol3000(curRun)=toc(ticLoc);
end

%%Test the C++ implementation of the k-best 2D assignment code
disp('Running the Monte Carlo runs for the k-best 2D assignment code in C++')
CPPkB10b20h2=zeros(numRuns,1);
CPPkB10b20h25=zeros(numRuns,1);
CPPkB10b20h50=zeros(numRuns,1);

CPPkB50b100h2=zeros(numRuns,1);
CPPkB50b100h25=zeros(numRuns,1);
CPPkB50b100h50=zeros(numRuns,1);

CPPkB100b100h2=zeros(numRuns,1);
CPPkB100b100h25=zeros(numRuns,1);
CPPkB100b100h50=zeros(numRuns,1);
for curRun=1:numRuns
    curRun
    %10X20 Matrix
    C=rand(10,20);
    k=2;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    CPPkB10b20h2(curRun)=toc(ticLoc);
    k=25;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    CPPkB10b20h25(curRun)=toc(ticLoc);
    k=50;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    CPPkB10b20h50(curRun)=toc(ticLoc);

    %50X100 Matrix
    C=rand(50,100);
    k=2;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    CPPkB50b100h2(curRun)=toc(ticLoc);
    k=25;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    CPPkB50b100h25(curRun)=toc(ticLoc);
    k=50;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    CPPkB50b100h50(curRun)=toc(ticLoc);

    %100X100 Matrix
    C=rand(100,100);
    k=2;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    CPPkB100b100h2(curRun)=toc(ticLoc);
    k=25;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    CPPkB100b100h25(curRun)=toc(ticLoc);
    k=50;
    ticLoc=tic;
    [col4row,row4col,gain]=kBest2DAssign(C,k,false);
    CPPkB100b100h50(curRun)=toc(ticLoc);
end

%Now, compute and display the median and maximum run times.
disp('2D Assignment')
disp('Problem Size, Matlab by Row Median/Worst Case, Matlab by Column Median/Worst Case')
fprintf('100 X 100   %f/%f %f/%f\n', median(MatlabByRow100),      max(MatlabByRow100),      median(MatlabByCol100),      max(MatlabByCol100))
fprintf('200 X 200   %f/%f %f/%f\n', median(MatlabByRow200),      max(MatlabByRow200),      median(MatlabByCol200),      max(MatlabByCol200))
fprintf('500 X 500   %f/%f %f/%f\n', median(MatlabByRow500),      max(MatlabByRow500),      median(MatlabByCol500),      max(MatlabByCol500))
fprintf('500 X 1000  %f/%f %f/%f\n', median(MatlabByRow500b1000), max(MatlabByRow500b1000), median(MatlabByCol500b1000), max(MatlabByCol500b1000))
fprintf('3000 X 3000 %f/%f %f/%f\n', median(MatlabByRow3000),     max(MatlabByRow3000),     median(MatlabByCol3000),     max(MatlabByCol3000))

disp('2D Assignment')
disp('Problem Size, C++ by Row Median/Worst Case, C by Row Median/Worst Case, C By Column Median/Worst Case')
fprintf('100 X 100   %f/%f %f/%f %f/%f\n', median(CPPByRow100),      max(CPPByRow100),      median(CByRow100),      max(CByRow100),      median(CByCol100),      max(CByCol100))
fprintf('200 X 200   %f/%f %f/%f %f/%f\n', median(CPPByRow200),      max(CPPByRow200),      median(CByRow200),      max(CByRow200),      median(CByCol200),      max(CByCol200))
fprintf('500 X 500   %f/%f %f/%f %f/%f\n', median(CPPByRow500),      max(CPPByRow500),      median(CByRow500),      max(CByRow500),      median(CByCol500),      max(CByCol500))
fprintf('500 X 1000  %f/%f %f/%f %f/%f\n', median(CPPByRow500b1000), max(CPPByRow500b1000), median(CByRow500b1000), max(CByRow500b1000), median(CByCol500b1000), max(CByCol500b1000))
fprintf('3000 X 3000 %f/%f %f/%f %f/%f\n', median(CPPByRow3000),     max(CPPByRow3000),     median(CByRow3000),     max(CByRow3000),     median(CByCol3000),     max(CByCol3000))

disp('k-Best 2D Assignment')
disp('Problem Size, Matlab Median/Worst Case, C++ Median/Worst Case')
fprintf('10 X 20,   2  Hyp %f/%f %f/%f\n', median(MatlabkB10b20h2),    max(MatlabkB10b20h2),    median(CPPkB10b20h2),    max(CPPkB10b20h2))
fprintf('10 X 20,   25 Hyp %f/%f %f/%f\n', median(MatlabkB10b20h25),   max(MatlabkB10b20h25),   median(CPPkB10b20h25),   max(CPPkB10b20h25))
fprintf('10 X 20,   50 Hyp %f/%f %f/%f\n', median(MatlabkB10b20h50),   max(MatlabkB10b20h50),   median(CPPkB10b20h50),   max(CPPkB10b20h50))
fprintf('50 X 100,  2  Hyp %f/%f %f/%f\n', median(MatlabkB50b100h2),   max(MatlabkB50b100h2),   median(CPPkB50b100h2),   max(CPPkB50b100h2))
fprintf('50 X 100,  25 Hyp %f/%f %f/%f\n', median(MatlabkB50b100h25),  max(MatlabkB50b100h25),  median(CPPkB50b100h25),  max(CPPkB50b100h25))
fprintf('50 X 100,  50 Hyp %f/%f %f/%f\n', median(MatlabkB50b100h50),  max(MatlabkB50b100h50),  median(CPPkB50b100h50),  max(CPPkB50b100h50))
fprintf('100 X 100, 2  Hyp %f/%f %f/%f\n', median(MatlabkB100b100h2),  max(MatlabkB100b100h2),  median(CPPkB100b100h2),  max(CPPkB100b100h2))
fprintf('100 X 100, 25 Hyp %f/%f %f/%f\n', median(MatlabkB100b100h25), max(MatlabkB100b100h25), median(CPPkB100b100h25), max(CPPkB100b100h25))
fprintf('100 X 100, 50 Hyp %f/%f %f/%f\n', median(MatlabkB100b100h50), max(MatlabkB100b100h50), median(CPPkB100b100h50), max(CPPkB100b100h50))

%Restore the old working directory.
cd(curDir);
%Restore the old path
path(oldPath);

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


text:
%% PYTHONPLOT
function pythonplot(obj)
    obj.plot('metric', {'counts';'cum_mag'});
end

author: geoscience-community-codes

repo: GISMO


text:
        % Rezolvarea unei ecuatii cu derivate partiale
        % direct din programul MAPLE
Sol=maple('pdesolve( diff(f(x,y),x,x)+5*diff(f(x,y),x,y)=3, f(x,y) )')

author: Sable

repo: mcbench-benchmarks


text:
function [W,imageEdges] = ICgraph(I,dataW,dataEdgemap);
% [W,imageEdges] = ICgraph(I,dataW,dataEdgemap);
% Input:
% I = gray-level image
% optional parameters:
% dataW.sampleRadius=10;
% dataW.sample_rate=0.3;
% dataW.edgeVariance = 0.1;
%
% dataEdgemap.parametres=[4,3, 21,3];%[number of filter orientations, number of scales, filter size, elongation]
% dataEdgemap.threshold=0.02;
%
% Output:
% W: npixels x npixels similarity matrix based on Intervening Contours
% imageEdges: image showing edges extracted in the image
%
% Timothee Cour, Stella Yu, Jianbo Shi, 2004.

[p,q] = size(I);

if (nargin< 2) | isempty(dataW),
    dataW.sampleRadius=10;
    dataW.sample_rate=0.3;
    dataW.edgeVariance = 0.1;
end

if (nargin<3) | isempty(dataEdgemap),
    dataEdgemap.parametres=[4,3, 21,3];%[number of filter orientations, number of scales, filter size, elongation]
    dataEdgemap.threshold=0.02;
end

edgemap = computeEdges(I,dataEdgemap.parametres,dataEdgemap.threshold);
imageEdges = edgemap.imageEdges;
W = computeW(I,dataW,edgemap.emag,edgemap.ephase);

author: jwyang


text:
%% MD_FAST_RUN is a script to run MD_FAST with prescribed input.
%
  filename = 'md_fast_output.txt';

  delete ( filename );

  diary ( filename );

  nd = 3;
  np = 500;
  step_num = 500;

  md_fast ( nd, np, step_num );

  diary ( 'off' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Output written to "%s"\n', filename );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

author: johannesgerer

repo: jburkardt-m


text:
function recall = boxesEval( varargin )
% Perform object proposal bounding box evaluation and plot results.
%
% boxesEval evaluates a set bounding box object proposals on the dataset
% specified by the 'data' parameter (which is generated by boxesData.m).
% The methods are specified by the vector 'names'. For each method the
% boxes must be stored in the file [resDir '/' name '-' data.split]. Each
% file should contain a single cell array 'bbs' of length n, with one set
% of bbs per image, where each matrix row has the format [x y w h score].
% Here score is the confidence of detection but if the boxes are sorted the
% score may be the same for every box. edgeBoxes.m stores results in this
% format by default, other methods can easily be converted to this format.
%
% For every method, evaluation is performed at every threshold in 'thrs'
% and every proposal count in 'cnts'. Two plots may be generated. If
% |cnts|>1 creates a plot with count on x-axis (and plots a separate set of
% curves for each threshold if necessary). If |thrs|>1 creates a plot with
% thresholds on x-axis (and plots a separate set of curves for each count).
%
% USAGE
%  recall = boxesEval( opts )
%
% INPUTS
%  opts       - parameters (struct or name/value pairs)
%   .data       - ['REQ'] data on which to evaluate (see boxesData.m)
%   .names      - ['REQ'] string cell array of object proposal methods
%   .resDir     - ['boxes/'] location for results and evaluation
%   .thrs       - [.7] IoU threshold(s) to use for evaluation
%   .cnts       - [...] propsal count(s) to use for evaluation
%   .maxn       - [inf] maximum number of images to use for evaluation
%   .show       - [1] figure for plotting results
%   .fName      - [''] optional filename for saving plots/recall to disk
%   .col        - [...] color(s) for plotting each method's results
%
% OUTPUTS
%  recall     - [MxTxK] recall for each count/threshold/method
%
% EXAMPLE
%
% See also edgeBoxesDemo, edgeBoxes, boxesData, bbGt
%
% Structured Edge Detection Toolbox      Version 3.01
% Code written by Piotr Dollar and Larry Zitnick, 2014.
% Licensed under the MSR-LA Full Rights License [see license.txt]

cnts=[1 2 5 10 20 50 100 200 500 1000 2000 5000]; col=cell(100,1);
for i=1:100, col{i}=max(.3,mod([.3 .47 .16]*(i+1),1)); end
dfs={ 'data','REQ', 'names','REQ', 'resDir','boxes/', 'thrs',.7, ...
  'cnts',cnts, 'maxn',inf, 'show',1, 'fName','', 'col',col };
o=getPrmDflt(varargin,dfs,1); if(~iscell(o.names)), o.names={o.names}; end
recall=boxesEvalAll(o); if(o.show), plotResult(recall,o); end

end

function recall = boxesEvalAll( o )
% compute and gather all results (caches individual results to disk)
M=length(o.cnts); T=length(o.thrs); K=length(o.names);
gt=o.data.gt; n=min(o.maxn,o.data.n); gt=gt(1:n);
recall=zeros(M,T,K); [ms,ts,ks]=ndgrid(1:M,1:T,1:K);
parfor i=1:M*T*K, m=ms(i); t=ts(i); k=ks(i);
  % if evaluation result exists simply load it
  rdir=[o.resDir '/eval/' o.names{k} '/' o.data.split '/'];
  rnm=[rdir 'N' int2str2(n,5) '-W' int2str2(o.cnts(m),5) ...
    '-T' int2str2(round(o.thrs(t)*100),2) '.txt']; %#ok<*PFBNS>
  if(exist(rnm,'file')), recall(i)=load(rnm,'-ascii'); continue; end
  % perform evaluation if result does not exist
  bbs=load([o.resDir '/' o.names{k} '-' o.data.split]); bbs=bbs.bbs;
  bbs1=bbs(1:n); for j=1:n, bbs1{j}=bbs1{j}(1:min(end,o.cnts(m)),:); end
  [gt1,bbs1]=bbGt('evalRes',gt,bbs1,o.thrs(t));
  [~,r]=bbGt('compRoc',gt1,bbs1,1); r=max(r); recall(i)=r;
  if(~exist(rdir,'dir')), mkdir(rdir); end; dlmwrite(rnm,r);
end
% display summary statistics
[ts,ks]=ndgrid(1:T,1:K); ms=log(o.cnts); rt=.75;
for i=1:T*K, t=ts(i); k=ks(i); r=recall(:,t,k)'; if(M==1), continue; end
  a=find(rt<=r); if(isempty(a)), m=inf; else a=a(1); b=a-1;
    m=round(exp((rt-r(b))/(r(a)-r(b))*(ms(a)-ms(b))+ms(b))); end
  auc=sum(diff(ms/ms(end)).*(r(1:end-1)+r(2:end))/2);
  fprintf('%15s  T=%.2f  A=%.2f  M=%4i  R=%.2f\n',...
    o.names{k},o.thrs(t),auc,m,max(r));
end
% optionally save results to text file
if(isempty(o.fName)), return; end
d=[o.resDir '/plots/']; if(~exist(d,'dir')), mkdir(d); end
dlmwrite([d o.fName '-' o.data.split '.txt'],squeeze(recall));
end

function plotResult( recall, o )
% plot results
[M,T,K]=size(recall); fSiz={'FontSize',12}; f=o.show;
for type=1:2
  if(type==1), xs=o.cnts; else xs=o.thrs; end;
  if(length(xs)==1), continue; end; s=[T,M]; M=s(type);
  R=recall; if(type==2), R=permute(R,[2 1 3]); end
  figure(f); f=f+1; clf; hold on; hs=zeros(M,K);
  for i=1:M, for k=1:K, hs(i,k)=plot(xs,R(:,i,k),...
        'Color',o.col{k},'LineWidth',3); end; end
  s={'# of proposals','IoU'}; xlabel(s{type},fSiz{:});
  s={'log','linear'}; set(gca,'XScale',s{type});
  ylabel('Detection Rate',fSiz{:}); set(gca,'YTick',0:.2:1);
  hold off; axis([min(xs) max(xs) 0 1]); grid on; set(gca,fSiz{:});
  set(gca,'XMinorGrid','off','XMinorTic','off');
  set(gca,'YMinorGrid','off','YMinorTic','off');
  s={'nw','ne'}; legend(hs(1,:),o.names,'Location',s{type});
  if(isempty(o.fName)), continue; end; s={'Cnt','IoU'};
  savefig([o.resDir '/plots/' s{type} '-' o.data.split '-' o.fName],'png');
end
end

author: pdollar

repo: edges

save_path: github-repos/MATLAB/pdollar-edges